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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
huzhiqian/MVision | 3,748 | 测试版/HalconMVision/Halcon.MVision/HalSyncObject.cs | // Halcon.MVision.Implementation.HalSyncObject
using Halcon.MVision.Implementation;
using System;
using System.Threading;
namespace Halcon.MVision.Implementation
{
/// <summary>
/// 该类用于同步MVision成员访问。多线程程序必须向
/// 任何编辑控件提供该类的实例,应用程序从非GUI线程访问
/// 共享工具,应用程序有责任锁定和解锁
/// </summary>
public class HalSyncObject
{
private int _count;
private readonly object _objectLock = new object();
private int _threadID;
#region 构造函数
public HalSyncObject() { }
#endregion
#region 属性
/// <summary>
/// 获取或设置用户指定的线程ID
/// </summary>
/// <value>
/// 用户指定的线程ID,默认值为0
/// </value>
/// <remake>
/// 该属性存储用户提供的线程ID,方便锁定HalSyncObject
/// 中的线程,该属性时可选的
/// </remake>
public int ThreadID
{
get
{
return this._threadID;
}
set
{
this._threadID = value;
}
}
#endregion
#region 公共方法
public void Lock()
{
Monitor.Enter(this._objectLock);
this._count++;
if (this._count == 1)
{
this.OnLock();
}
}
public bool TryLock()
{
bool flag = Monitor.TryEnter(this._objectLock);
if (flag)
{
this._count++;
if (this._count == 1)
{
this.OnLock();
}
}
return flag;
}
public void Unlock()
{
bool flag = true;
if (this._count > 0)
{
this._count--;
if (this._count == 0)
{
try
{
this.OnLock();
}
finally
{
Monitor.Exit(this._objectLock);
flag = false;
}
}
}
if (flag)
{
Monitor.Exit(_objectLock);
}
}
#endregion
#region 私有方法
/// <summary>
/// 该方法用于将Lock事件通知已注册的对象
/// </summary>
internal void OnLock()
{
HalLockedEventHandler locked = this.Locked;
if (locked != null)
{
locked(this, new EventArgs());
}
}
internal void OnUnlock()
{
HalUnLockEventHandler unlocked = this.Unlocked;
if (unlocked != null)
{
unlocked(this,new EventArgs());
}
}
#endregion
#region 委托
/// <summary>
/// A delegate for the HalVisionToolSyncRoot Lock event.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void HalLockedEventHandler(object sender, EventArgs e);
/// <summary>
/// A delegate for the HalVisionToolSyncRoot Unlock event.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void HalUnLockEventHandler(object sender, EventArgs e);
#endregion
#region 事件
/// <summary>
/// This event is raised when this object is locked
/// </summary>
public event HalLockedEventHandler Locked;
/// <summary>
/// this event is raised when this object is unlocked
/// </summary>
public event HalUnLockEventHandler Unlocked;
#endregion
}
}
| 411 | 0.934929 | 1 | 0.934929 | game-dev | MEDIA | 0.326517 | game-dev | 0.973036 | 1 | 0.973036 |
polyworld/polyworld | 2,389 | src/library/environment/BrickPatch.cc |
// BrickPatch.cp - implementation of brick patches
// Self
#include "BrickPatch.h"
// System
#include <ostream>
// Local
#include "brick.h"
#include "agent/agent.h"
#include "graphics/graphics.h"
#include "sim/globals.h"
#include "sim/Simulation.h"
#include "utils/distributions.h"
using namespace std;
//===========================================================================
// BrickPatch
//===========================================================================
// Default constructor
BrickPatch::BrickPatch(){
}
//-------------------------------------------------------------------------------------------
// BrickPatch::BrickPatch
//-------------------------------------------------------------------------------------------
void BrickPatch::init(Color color, float x, float z, float sx, float sz, int numberBricks, int shape, int distrib, float nhsize, gstage* fs, Domain* dm, int domainNumber, bool on)
{
initBase(x, z, sx, sz, shape, distrib, nhsize, fs, dm, domainNumber);
brickCount = numberBricks;
brickColor = color;
onPrev = false;
this->on = on;
}
//-------------------------------------------------------------------------------------------
// BrickPatch::~BrickPatch
//-------------------------------------------------------------------------------------------
BrickPatch::~BrickPatch()
{
}
void BrickPatch::updateOn()
{
if( on != onPrev )
{
if( on )
addBricks();
else
removeBricks();
onPrev = on;
}
}
void BrickPatch::addBricks()
{
for( int i = 0; i < brickCount; i++ )
{
float x, z;
brick* b = new brick( brickColor );
// set the values of x and y to a legal point in the BrickPatch
setPoint(&x, &z);
b->setx(x);
b->setz(z);
b->setPatch(this);
objectxsortedlist::gXSortedObjects.add(b);
fStage->AddObject(b);
}
}
void BrickPatch::removeBricks()
{
brick *b;
list<brick *> removeList;
// There are patches currently needing removal, so do it
objectxsortedlist::gXSortedObjects.reset();
while( objectxsortedlist::gXSortedObjects.nextObj( BRICKTYPE, (gobject**) &b ) )
{
if( b->myBrickPatch == this )
{
objectxsortedlist::gXSortedObjects.removeCurrentObject(); // get it out of the list
fStage->RemoveObject( b );
if( b->BeingCarried() )
{
// if it's being carried, have to remove it from the carrier
((agent*)(b->CarriedBy()))->DropObject( (gobject*) b );
}
}
}
}
| 411 | 0.964031 | 1 | 0.964031 | game-dev | MEDIA | 0.83798 | game-dev | 0.908083 | 1 | 0.908083 |
robotlegs-sharp/robotlegs-sharp-framework | 4,260 | src/Robotlegs/Bender/Extensions/CommandCenter/Impl/CommandMapper.cs | //------------------------------------------------------------------------------
// Copyright (c) 2014-2016 the original author or authors. All Rights Reserved.
//
// NOTICE: You are permitted to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//------------------------------------------------------------------------------
using System;
using Robotlegs.Bender.Extensions.CommandCenter.API;
using Robotlegs.Bender.Extensions.CommandCenter.DSL;
namespace Robotlegs.Bender.Extensions.CommandCenter.Impl
{
public class CommandMapper : ICommandMapper, ICommandUnmapper, ICommandConfigurator
{
/*============================================================================*/
/* Private Properties */
/*============================================================================*/
private ICommandMappingList _mappings;
private ICommandMapping _mapping;
/*============================================================================*/
/* Constructor */
/*============================================================================*/
/**
* Creates a Command Mapper
* @param mappings The command mapping list to add mappings to
*/
public CommandMapper(ICommandMappingList mappings)
{
_mappings = mappings;
}
/*============================================================================*/
/* Public Functions */
/*============================================================================*/
/**
* @inheritDoc
*/
public ICommandConfigurator ToCommand<T>()
{
return ToCommand (typeof(T));
}
public ICommandConfigurator ToCommand(Type commandClass)
{
_mapping = new CommandMapping(commandClass);
_mappings.AddMapping(_mapping);
return this;
}
/**
* @inheritDoc
*/
public void FromCommand<T>()
{
FromCommand (typeof(T));
}
public void FromCommand(Type commandClass)
{
_mappings.RemoveMappingFor(commandClass);
}
/**
* @inheritDoc
*/
public void FromAll()
{
_mappings.RemoveAllMappings();
}
/**
* @inheritDoc
*/
public ICommandConfigurator Once(bool value = true)
{
_mapping.SetFireOnce(value);
return this;
}
/**
* @inheritDoc
*/
public ICommandConfigurator WithGuards(params object[] guards)
{
_mapping.AddGuards(guards);
return this;
}
public ICommandConfigurator WithGuards<T>()
{
return WithGuards (typeof(T));
}
public ICommandConfigurator WithGuards<T1, T2>()
{
return WithGuards (typeof(T1), typeof(T2));
}
public ICommandConfigurator WithGuards<T1, T2, T3>()
{
return WithGuards (typeof(T1), typeof(T2), typeof(T3));
}
public ICommandConfigurator WithGuards<T1, T2, T3, T4>()
{
return WithGuards (typeof(T1), typeof(T2), typeof(T3), typeof(T4));
}
public ICommandConfigurator WithGuards<T1, T2, T3, T4, T5>()
{
return WithGuards (typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5));
}
/**
* @inheritDoc
*/
public ICommandConfigurator WithHooks(params object[] hooks)
{
_mapping.AddHooks(hooks);
return this;
}
public ICommandConfigurator WithHooks<T>()
{
return WithHooks (typeof(T));
}
public ICommandConfigurator WithHooks<T1, T2>()
{
return WithHooks (typeof(T1), typeof(T2));
}
public ICommandConfigurator WithHooks<T1, T2, T3>()
{
return WithHooks (typeof(T1), typeof(T2), typeof(T3));
}
public ICommandConfigurator WithHooks<T1, T2, T3, T4>()
{
return WithHooks (typeof(T1), typeof(T2), typeof(T3), typeof(T4));
}
public ICommandConfigurator WithHooks<T1, T2, T3, T4, T5>()
{
return WithHooks (typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5));
}
/**
* @inheritDoc
*/
public ICommandConfigurator WithExecuteMethod(string name)
{
_mapping.SetExecuteMethod(name);
return this;
}
/**
* @inheritDoc
*/
public ICommandConfigurator WithPayloadInjection(bool value)
{
_mapping.SetPayloadInjectionEnabled(value);
return this;
}
}
}
| 411 | 0.932097 | 1 | 0.932097 | game-dev | MEDIA | 0.426697 | game-dev | 0.777347 | 1 | 0.777347 |
aniketrajnish/Unity-WebGPU-PBR-Maps-Generator | 3,327 | src/PBR Maps Generator/Assets/TextMesh Pro/Examples & Extras/Scripts/TMPro_InstructionOverlay.cs | using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class TMPro_InstructionOverlay : MonoBehaviour
{
public enum FpsCounterAnchorPositions { TopLeft, BottomLeft, TopRight, BottomRight };
public FpsCounterAnchorPositions AnchorPosition = FpsCounterAnchorPositions.BottomLeft;
private const string instructions = "Camera Control - <#ffff00>Shift + RMB\n</color>Zoom - <#ffff00>Mouse wheel.";
private TextMeshPro m_TextMeshPro;
private TextContainer m_textContainer;
private Transform m_frameCounter_transform;
private Camera m_camera;
//private FpsCounterAnchorPositions last_AnchorPosition;
void Awake()
{
if (!enabled)
return;
m_camera = Camera.main;
GameObject frameCounter = new GameObject("Frame Counter");
m_frameCounter_transform = frameCounter.transform;
m_frameCounter_transform.parent = m_camera.transform;
m_frameCounter_transform.localRotation = Quaternion.identity;
m_TextMeshPro = frameCounter.AddComponent<TextMeshPro>();
m_TextMeshPro.font = Resources.Load<TMP_FontAsset>("Fonts & Materials/LiberationSans SDF");
m_TextMeshPro.fontSharedMaterial = Resources.Load<Material>("Fonts & Materials/LiberationSans SDF - Overlay");
m_TextMeshPro.fontSize = 30;
m_TextMeshPro.isOverlay = true;
m_textContainer = frameCounter.GetComponent<TextContainer>();
Set_FrameCounter_Position(AnchorPosition);
//last_AnchorPosition = AnchorPosition;
m_TextMeshPro.text = instructions;
}
void Set_FrameCounter_Position(FpsCounterAnchorPositions anchor_position)
{
switch (anchor_position)
{
case FpsCounterAnchorPositions.TopLeft:
//m_TextMeshPro.anchor = AnchorPositions.TopLeft;
m_textContainer.anchorPosition = TextContainerAnchors.TopLeft;
m_frameCounter_transform.position = m_camera.ViewportToWorldPoint(new Vector3(0, 1, 100.0f));
break;
case FpsCounterAnchorPositions.BottomLeft:
//m_TextMeshPro.anchor = AnchorPositions.BottomLeft;
m_textContainer.anchorPosition = TextContainerAnchors.BottomLeft;
m_frameCounter_transform.position = m_camera.ViewportToWorldPoint(new Vector3(0, 0, 100.0f));
break;
case FpsCounterAnchorPositions.TopRight:
//m_TextMeshPro.anchor = AnchorPositions.TopRight;
m_textContainer.anchorPosition = TextContainerAnchors.TopRight;
m_frameCounter_transform.position = m_camera.ViewportToWorldPoint(new Vector3(1, 1, 100.0f));
break;
case FpsCounterAnchorPositions.BottomRight:
//m_TextMeshPro.anchor = AnchorPositions.BottomRight;
m_textContainer.anchorPosition = TextContainerAnchors.BottomRight;
m_frameCounter_transform.position = m_camera.ViewportToWorldPoint(new Vector3(1, 0, 100.0f));
break;
}
}
}
}
| 411 | 0.895858 | 1 | 0.895858 | game-dev | MEDIA | 0.448885 | game-dev | 0.961562 | 1 | 0.961562 |
JonnyBro/beatrun | 18,331 | gamemodes/beatrun/gamemode/sh/Climb.lua | local ClimbingTimes = {5, 1.25, 1, 1, nil, 2}
--[[
local CLIMB_HANG = 1
local CLIMB_HEAVEUP = 2
local CLIMB_STRAFELEFT = 3
local CLIMB_STRAFERIGHT = 4
local CLIMB_FOLDEDSTART = 5
local CLIMB_FOLDEDHEAVEUP = 6
local climb1 = {
followplayer = false,
animmodelstring = "new_climbanim",
allowmove = true,
lockang = false,
ignorez = true,
smoothend = true,
AnimString = "climb1"
}
local climbstrings = {"climb1", "climb2"}
]]
if game.SinglePlayer() and SERVER then
util.AddNetworkString("Climb_SPFix")
elseif game.SinglePlayer() and CLIENT then
net.Receive("Climb_SPFix", function()
local lock = net.ReadBool()
local neweyeang = net.ReadBool()
local ang = net.ReadAngle()
local oldlock = net.ReadBool()
lockang = lock
if oldlock ~= nil then
lockang = oldlock
end
if neweyeang then
LocalPlayer().OrigEyeAng = ang
end
end)
end
local function ClimbingEnd(ply, mv, cmd)
mv:SetOrigin(ply:GetClimbingEnd())
ply:SetClimbing(0)
ply:SetMoveType(MOVETYPE_WALK)
local tr = {
filter = ply
}
tr.mins, tr.maxs = ply:GetHull()
tr.start = mv:GetOrigin()
tr.endpos = tr.start
tr.mask = MASK_PLAYERSOLID
tr.collisiongroup = COLLISION_GROUP_PLAYER_MOVEMENT
local trout = util.TraceHull(tr)
if trout.Hit then
local trout = {}
tr.output = trout
local start = tr.start
for _ = 1, 64 do
start.z = start.z + 1
util.TraceHull(tr)
if not trout.Hit then
mv:SetOrigin(start)
break
end
end
end
local activewep = ply:GetActiveWeapon()
if IsValid(activewep) then
activewep:SendWeaponAnim(ACT_VM_DRAW)
end
lockang2 = false
lockang = false
if game.SinglePlayer() then
net.Start("Climb_SPFix")
net.WriteBool(false)
net.WriteBool(false)
net.WriteAngle(angle_zero)
net.WriteBool(false)
net.Send(ply)
end
end
local function ClimbingThink(ply, mv, cmd)
if ply:GetClimbing() == 5 then
if mv:KeyPressed(IN_FORWARD) and ply:GetClimbingDelay() < CurTime() + 0.65 or mv:KeyDown(IN_FORWARD) and ply:GetClimbingDelay() < CurTime() then
ParkourEvent("hangfoldedheaveup", ply)
ply:SetClimbing(6)
ply:SetClimbingTime(0)
elseif ply:GetClimbingDelay() < CurTime() then
ParkourEvent("hangfoldedendhang", ply)
ply:SetClimbing(1)
ply:SetClimbingDelay(CurTime() + 1.35)
end
mv:SetForwardSpeed(0)
mv:SetSideSpeed(0)
mv:SetUpSpeed(0)
mv:SetButtons(bit.band(mv:GetButtons(), bit.bnot(IN_DUCK)))
mv:SetButtons(bit.band(mv:GetButtons(), bit.bnot(IN_JUMP)))
return
end
if (ply:GetClimbing() == 2 or ply:GetClimbing() == 6) and ply:GetClimbingTime() >= 1 then
mv:SetButtons(0)
mv:SetForwardSpeed(0)
mv:SetSideSpeed(0)
mv:SetUpSpeed(0)
ClimbingEnd(ply, mv, cmd)
return
end
mv:SetVelocity(vector_origin)
if ply:GetClimbing() == 1 and ply:GetClimbingDelay() < CurTime() then
if ply.ClimbLockAng < CurTime() then
lockang2 = false
lockang = false
if game.SinglePlayer() then
net.Start("Climb_SPFix")
net.WriteBool(false)
net.WriteBool(false)
net.WriteAngle(angle_zero)
net.WriteBool(false)
net.Send(ply)
end
end
if mv:KeyDown(IN_DUCK) then
mv:SetOrigin(ply:GetClimbingStart() - ply:GetClimbingAngle():Forward() * 5)
ply:SetMoveType(MOVETYPE_WALK)
mv:SetButtons(0)
ply:SetClimbing(0)
ply:SetCrouchJumpBlocked(true)
ParkourEvent("hangend", ply)
if CLIENT and IsFirstTimePredicted() then
lockang2 = false
lockang = false
BodyLimitX = 90
BodyLimitY = 180
elseif game.SinglePlayer() then
ply:SendLua("lockang2=false lockang=false BodyLimitX=90 BodyLimitY=180")
end
return
end
local ang = cmd:GetViewAngles()
ang = math.abs(math.AngleDifference(ang.y, ply.wallang.y))
if mv:KeyDown(IN_JUMP) and ang > 42 then
mv:SetOrigin(ply:GetClimbingStart() - ply:GetClimbingAngle():Forward() * 0.6)
ply:SetMoveType(MOVETYPE_WALK)
mv:SetButtons(0)
ply:SetClimbing(0)
ply:SetSafetyRollKeyTime(CurTime() + 0.1)
ParkourEvent("hangjump", ply)
if CLIENT and IsFirstTimePredicted() then
lockang2 = false
lockang = false
BodyLimitX = 90
BodyLimitY = 180
local ang = ply:EyeAngles()
ang.x = 0
ang.z = 0
BodyAnim:SetAngles(ang)
elseif game.SinglePlayer() then
ply:SendLua("lockang2=false lockang=false BodyLimitX=90 BodyLimitY=180 local ang=LocalPlayer():EyeAngles() ang.x=0 ang.z=0 BodyAnim:SetAngles(ang)")
end
local ang = cmd:GetViewAngles()
ang.x = math.min(ang.x, 0)
ang = ang:Forward()
ang:Mul(350)
ang.z = 250
mv:SetVelocity(ang)
return
end
if (mv:KeyPressed(IN_FORWARD) or mv:KeyPressed(IN_JUMP)) and ang <= 42 then
local tr = ply.ClimbingTraceSafety
local trout = ply.ClimbingTraceSafetyOut
local mins, maxs = ply:GetHull()
mins.z = maxs.z * 0.25
tr.start = ply:GetClimbingEnd()
tr.endpos = tr.start
tr.maxs = maxs
tr.mins = mins
tr.filter = ply
tr.output = trout
util.TraceHull(tr)
--[[ TODO: Make this work
for i = -64, 64, 1 do
tr.endpos = tr.start + ply:GetClimbingAngle():Forward() * i
util.TraceHull(tr)
print(trout.Hit)
print(tr.endpos)
if not trout.Hit then
-- tr.start = tr.endpos
-- tr.endpos = tr.start - ply:GetClimbingAngle():Forward() * i
-- util.TraceHull(tr)
-- if not trout.Hit then
ply:SetClimbingEnd(tr.endpos)
ply:SetClimbing(2)
ParkourEvent("climbheave", ply)
-- end
end
end
--]]
if not trout.Hit then
tr.start = ply:GetClimbingEnd()
tr.endpos = tr.start - ply:GetClimbingAngle():Forward() * 20
util.TraceHull(tr)
if not trout.Hit then
ply:SetClimbing(2)
ParkourEvent("climbheave", ply)
end
end
end
if ply:GetClimbing() == 1 and (mv:KeyDown(IN_MOVELEFT) or mv:KeyDown(IN_MOVERIGHT)) and ply:GetClimbingDelay() < CurTime() then
local wallang = ply:GetClimbingAngle()
local dir = wallang:Right()
local isright = mv:KeyDown(IN_MOVERIGHT)
local mult = isright and 30 or -30
dir:Mul(mult)
local tr = ply.ClimbingTraceEnd
local trout = ply.ClimbingTraceEndOut
-- local oldstart = tr.start
-- local oldend = tr.endpos
local start = mv:GetOrigin() + wallang:Forward() * 20 + Vector(0, 0, 100) + dir
tr.start = start
tr.endpos = start - Vector(0, 0, 80)
util.TraceLine(tr)
if trout.Entity and trout.Entity.IsNPC and (trout.Entity:IsNPC() or trout.Entity:IsPlayer()) then return false end
local fail = trout.Fraction < 0.25 or trout.Fraction > 0.5
if not fail then
local ostart = tr.start
local oendpos = tr.endpos
tr.start = ply:GetClimbingEnd() + dir
tr.endpos = tr.start - Vector(0, 0, 100)
util.TraceLine(tr)
dir.z = trout.HitPos.z - mv:GetOrigin().z - 77
tr.endpos = oendpos
tr.start = ostart
tr = ply.ClimbingTraceSafety
trout = ply.ClimbingTraceSafetyOut
tr.start = mv:GetOrigin() + dir - wallang:Forward() * 0.533
tr.endpos = tr.start
util.TraceHull(tr)
if not trout.Hit then
ply:SetClimbingEndOld(ply:GetClimbingEnd())
ply:SetClimbing(isright and 4 or 3)
ply:SetClimbingStart(mv:GetOrigin())
ply:SetClimbingEnd(mv:GetOrigin() + dir)
ply:SetClimbingTime(0)
tr.start = mv:GetOrigin() + ply:GetClimbingAngle():Forward() * 20 + Vector(0, 0, 100) + dir
tr.endpos = tr.start - Vector(0, 0, 80)
if isright then
ParkourEvent("hangstraferight", ply)
else
ParkourEvent("hangstrafeleft", ply)
end
ply:SetClimbingDelay(CurTime() + 0.9)
end
end
end
end
if ply:GetClimbing() == 3 or ply:GetClimbing() == 4 then
local isright = mv:KeyDown(IN_MOVERIGHT)
local dir = ply:GetClimbingAngle():Right()
local mult = isright and 30 or -30
dir:Mul(mult)
local tr = ply.ClimbingTraceEnd
local trout = ply.ClimbingTraceEndOut
util.TraceLine(tr)
if trout.Entity and trout.Entity.IsNPC and (trout.Entity:IsNPC() or trout.Entity:IsPlayer()) then return false end
local fail = trout.Fraction < 0.25 or trout.Fraction == 1
if not fail then
local lerp = ply:GetClimbingTime()
local lerprate = ClimbingTimes[ply:GetClimbing()]
local poslerp = LerpVector(lerp, ply:GetClimbingStart(), ply:GetClimbingEnd())
ply:SetClimbingEndOld(trout.HitPos)
mv:SetOrigin(poslerp)
ply:SetClimbingTime(ply:GetClimbingTime() + FrameTime() * lerprate)
end
if fail or ply:GetClimbingTime() >= 1 then
ply:SetClimbing(1)
ply:SetClimbingStart(mv:GetOrigin())
ply:SetClimbingEnd(ply:GetClimbingEndOld())
ply:SetClimbingTime(0)
end
end
if ply:GetClimbing() == 2 or ply:GetClimbing() == 6 then
if game.SinglePlayer() then
net.Start("Climb_SPFix")
net.WriteBool(false)
net.WriteBool(false)
net.WriteAngle(angle_zero)
net.WriteBool(false)
net.Send(ply)
end
local lerp = ply:GetClimbingTime()
local lerprate = ClimbingTimes[ply:GetClimbing()]
if lerp > 0.5 then
lerprate = lerprate * 0.75
end
local poslerp = LerpVector(lerp, ply:GetClimbingStart(), ply:GetClimbingEnd())
mv:SetOrigin(poslerp)
ply:SetClimbingTime(lerp + FrameTime() * lerprate)
end
mv:SetForwardSpeed(0)
mv:SetSideSpeed(0)
mv:SetUpSpeed(0)
mv:SetButtons(bit.band(mv:GetButtons(), bit.bnot(IN_DUCK)))
mv:SetButtons(bit.band(mv:GetButtons(), bit.bnot(IN_JUMP)))
end
local function ClimbingRemoveInput(ply, cmd)
end
hook.Add("StartCommand", "ClimbingRemoveInput", ClimbingRemoveInput)
local realistic = CreateConVar("Beatrun_LeRealisticClimbing", "0", FCVAR_ARCHIVE, "Makes you be able to climb and wallrun only if you have runnerhands equipped.")
local function ClimbingCheck(ply, mv, cmd)
if realistic:GetBool() and not ply:UsingRH() then return end
local mins, maxs = ply:GetHull()
if not ply.ClimbingTrace then
ply.ClimbingTrace = {}
ply.ClimbingTraceOut = {}
ply.ClimbingTraceEnd = {}
ply.ClimbingTraceEndOut = {}
ply.ClimbingTraceSafety = {}
ply.ClimbingTraceSafetyOut = {}
ply.ClimbingTraceSafety.output = ply.ClimbingTraceSafetyOut
TraceParkourMask(ply.ClimbingTrace)
TraceParkourMask(ply.ClimbingTraceEnd)
TraceParkourMask(ply.ClimbingTraceSafety)
end
local eyeang = ply:EyeAngles()
local oldpos = mv:GetOrigin()
eyeang.x = 0
local tr = ply.ClimbingTrace
local trout = ply.ClimbingTraceOut
mins.z = 45
tr.start = mv:GetOrigin()
if ply:GetDive() then
tr.start:Sub(Vector(0, 0, 48))
end
tr.endpos = tr.start + eyeang:Forward() * 50
tr.maxs = maxs
tr.mins = mins
tr.filter = ply
tr.output = trout
util.TraceHull(tr)
mins.z = 0
if not trout.Hit then return end
local wallang = trout.HitNormal:Angle()
wallang.y = wallang.y - 180
if wallang.x ~= 0 then return end
if math.abs(math.AngleDifference(wallang.y, eyeang.y)) > 50 then return end
if IsValid(trout.Entity) and trout.Entity.NoClimbing then return end
ply:SetClimbingAngle(wallang)
local tr = ply.ClimbingTraceEnd
local trout = ply.ClimbingTraceEndOut
local upvalue = ply:GetWallrun() == 1 and Vector(0, 0, 90) or Vector(0, 0, 65)
local plymins, plymaxs = ply:GetHull()
tr.start = mv:GetOrigin() + wallang:Forward() * 45 + upvalue
tr.endpos = tr.start - Vector(0, 0, 90)
tr.maxs = plymaxs
tr.mins = plymins
tr.filter = ply
tr.output = trout
util.TraceLine(tr)
if trout.Entity and trout.Entity.IsNPC and (trout.Entity:IsNPC() or trout.Entity:IsPlayer()) then return false end
local detectionlen = 60
if trout.Fraction <= 0 or trout.Fraction >= 0.5 then
tr.start = mv:GetOrigin() + wallang:Forward() * 20 + upvalue
tr.endpos = tr.start - Vector(0, 0, 90)
-- debugoverlay.Line(tr.start, tr.endpos, 5, Color(0, 0, 255), true)
util.TraceLine(tr)
if trout.Fraction <= 0 or trout.Fraction >= 0.5 then return end
detectionlen = 25
end
local endpos = trout.HitPos
-- local height = trout.Fraction
local startpos = ply.ClimbingTraceOut.HitPos
startpos.z = trout.HitPos.z - 77
startpos:Add(wallang:Forward() * 0.533)
if ply:GetDive() then
local origin = mv:GetOrigin()
startpos.z = trout.HitPos.z - 30
mv:SetOrigin(startpos)
if Vault5(ply, mv, eyeang, ply.mantletr, ply.mantlehull) then
if CLIENT then
BodyAnimSetEase(origin)
elseif game.SinglePlayer() then
ply:SetNW2Vector("SPBAEase", origin)
ply:SendLua("BodyAnimSetEase(LocalPlayer():GetNW2Vector('SPBAEase'))")
end
startpos.z = trout.HitPos.z - 60
ply:SetViewOffsetDucked(Vector(0, 0, 64))
ply:SetMantleStartPos(startpos)
return
else
mv:SetOrigin(origin)
end
return
end
local tr = ply.ClimbingTraceSafety
local trout = ply.ClimbingTraceSafetyOut
tr.filter = ply
tr.start = endpos
tr.endpos = tr.start - wallang:Forward() * detectionlen
util.TraceLine(tr)
if trout.Hit then return end
-- local h1 = trout.HitPos
-- local h2 = tr.start - wallang:Forward() - Vector(100, 0, 0)
-- local hit = util.QuickTrace(h1, h2, ply)
-- debugoverlay.Line(h1, h2, 5, Color(255, 200, 100), true)
-- print(hit.Hit)
-- print(hit.HitPos)
-- end
tr.start = startpos + Vector(0, 0, 77)
tr.endpos = tr.start + wallang:Forward() * detectionlen * 0.5
util.TraceLine(tr)
if trout.Hit then return end
-- local steep = trout.HitNormal:Distance(Vector(0, 0, 1)) > 0.01
local tr = ply.ClimbingTraceSafety
local trout = ply.ClimbingTraceSafetyOut
tr.start = mv:GetOrigin()
tr.endpos = tr.start + Vector(0, 0, 75)
util.TraceLine(tr)
if trout.Hit then return end
local origin = mv:GetOrigin()
local tr = ply.ClimbingTraceSafety
local trout = ply.ClimbingTraceSafetyOut
tr.start = startpos
tr.endpos = startpos
util.TraceLine(tr)
if trout.Hit then return end
startpos.z = startpos.z
ply.ClimbingStartPosCache = startpos
ply.ClimbingStartSmooth = origin
mv:SetOrigin(startpos)
local resetstartpos = false
if mv:KeyDown(IN_FORWARD) then
resetstartpos = true
if ply:GetWallrun() ~= 1 then
startpos.z = startpos.z + 17
mv:SetOrigin(startpos)
end
if Vault4(ply, mv, eyeang, ply.mantletr, ply.mantlehull) then
if CLIENT then
BodyAnimSetEase(origin)
elseif game.SinglePlayer() then
ply:SetNW2Vector("SPBAEase", origin)
ply:SendLua("BodyAnimSetEase(LocalPlayer():GetNW2Vector('SPBAEase'))")
end
return
else
if ply:GetWallrun() == 1 then
startpos.z = startpos.z + 17
end
mv:SetOrigin(startpos)
if Vault5(ply, mv, eyeang, ply.mantletr, ply.mantlehull) then
if CLIENT then
BodyAnimSetEase(origin)
elseif game.SinglePlayer() then
ply:SetNW2Vector("SPBAEase", origin)
ply:SendLua("BodyAnimSetEase(LocalPlayer():GetNW2Vector('SPBAEase'))")
end
return
end
end
end
if resetstartpos then
startpos.z = startpos.z - 17
ply.ClimbingStartPosCache = startpos
mv:SetOrigin(startpos)
end
local __mins, __maxs = ply:GetHull()
tr.start = mv:GetOrigin() + wallang:Forward() * 20 + vector_up * __maxs.z + vector_up * 5
tr.endpos = tr.start
util.TraceHull(tr)
if trout.Hit then
mv:SetOrigin(oldpos)
return
end
if CLIENT then
BodyAnimSetEase(origin)
elseif game.SinglePlayer() then
ply:SetNW2Vector("SPBAEase", origin)
ply:SendLua("BodyAnimSetEase(LocalPlayer():GetNW2Vector('SPBAEase'))")
end
local wr = ply:GetWallrun()
-- local wrtime = ply:GetWallrunTime() - CurTime()
-- local vel = mv:GetVelocity()
if wr ~= 0 then
ply:SetWallrun(0)
ply:EmitSound("Wallrun.Concrete")
end
local climbvalue = 1
ply:SetClimbing(climbvalue)
ply:SetClimbingStart(startpos)
ply:SetClimbingEnd(tr.endpos)
ply:SetClimbingTime(0)
ply:SetClimbingDelay(CurTime() + 0.75)
ply.ClimbLockAng = CurTime() + 1.45
ply:SetCrouchJumpBlocked(false)
ply:SetQuickturn(false)
local activewep = ply:GetActiveWeapon()
if ply:UsingRH() and activewep.SendWeaponAnim then
activewep:SendWeaponAnim(ACT_VM_HITCENTER)
activewep:SetBlockAnims(false)
end
local folded = mv:GetVelocity().z < -400
if folded then
local tr = ply.ClimbingTraceSafety
local trout = ply.ClimbingTraceSafetyOut
local mins, maxs = ply:GetCollisionBounds()
mins.z = maxs.z * 0.25
tr.start = ply:GetClimbingEnd()
tr.endpos = tr.start
tr.maxs = maxs
tr.mins = mins
tr.filter = ply
tr.output = trout
util.TraceHull(tr)
folded = not trout.Hit
end
local lastvel = mv:GetVelocity()
mv:SetVelocity(vector_origin)
ply:SetMoveType(MOVETYPE_NOCLIP)
ply:ViewPunch(Angle(5, 0, 0.5))
local wallangc = Angle(wallang)
if folded then
ply:SetClimbing(5)
ply:SetClimbingDelay(CurTime() + 0.8)
ParkourEvent("hangfoldedstart", ply)
else
local event = "climbhard"
if wr == 1 then
event = "climb"
wallangc.x = -30
elseif lastvel.z < -200 then
event = "climbhard2"
end
ParkourEvent(event, ply)
end
ply.wallang = wallang
if IsFirstTimePredicted() then
if CLIENT or game.SinglePlayer() then
timer.Simple(0.05, function()
ply:EmitSound("Bump.Concrete")
end)
end
ply:EmitSound("Handsteps.ConcreteHard")
ply:EmitSound("Cloth.RollLand")
if CLIENT and IsFirstTimePredicted() then
ply.OrigEyeAng = wallang
lockang2 = true
if folded then
DoImpactBlur(8)
lockang2 = false
lockang = true
end
end
if game.SinglePlayer() then
net.Start("Climb_SPFix")
net.WriteBool(false)
net.WriteBool(true)
net.WriteAngle(wallang)
if folded then
ply:SendLua("DoImpactBlur(8)")
net.WriteBool(true)
end
net.Send(ply)
end
end
if CLIENT and IsFirstTimePredicted() then
timer.Simple(0, function()
BodyLimitX = 80
BodyLimitY = 170
end)
elseif game.SinglePlayer() then
timer.Simple(0, function()
ply:SendLua("BodyLimitX=80 BodyLimitY=170")
end)
end
if CLIENT or game.SinglePlayer() then
ply:ConCommand("-jump")
end
mv:SetButtons(0)
mv:SetForwardSpeed(0)
mv:SetSideSpeed(0)
mv:SetUpSpeed(0)
end
hook.Add("SetupMove", "Climbing", function(ply, mv, cmd)
if ply:GetClimbing() == nil or not ply:Alive() then
ply:SetClimbing(0)
end
if IsValid(ply:GetSwingbar()) then return end
if (not ply:GetCrouchJump() or ply:GetDive()) and not ply:GetJumpTurn() and (mv:KeyDown(IN_FORWARD) or mv:GetVelocity().z < -50 or ply:GetWallrun() == 1) and ply:GetClimbing() == 0 and ply:GetWallrun() ~= 4 and not ply:OnGround() and ply:GetMoveType() ~= MOVETYPE_NOCLIP and ply:GetMoveType() ~= MOVETYPE_LADDER then
ClimbingCheck(ply, mv, cmd)
end
if ply:GetClimbing() ~= 0 then
ClimbingThink(ply, mv, cmd)
end
end) | 411 | 0.810503 | 1 | 0.810503 | game-dev | MEDIA | 0.631923 | game-dev,networking | 0.903345 | 1 | 0.903345 |
NG-ZORRO/today-ng-steps | 2,248 | src/app/services/list/list.service.ts | import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { LocalStorageService } from '../local-storage/local-storage.service';
import { List } from '../../../domain/entities';
import { LISTS } from '../local-storage/local-storage.namespace';
type SpecialListUUID = 'today' | 'todo';
@Injectable()
export class ListService {
private current: List;
private lists: List[] = [];
currentUuid: SpecialListUUID | string = 'today';
currentUuid$ = new Subject<string>();
current$ = new Subject<List>();
lists$ = new Subject<List[]>();
constructor(
private store: LocalStorageService
) { }
private broadCast(): void {
this.lists$.next(this.lists);
this.current$.next(this.current);
this.currentUuid$.next(this.currentUuid);
}
private persist(): void {
this.store.set(LISTS, this.lists);
}
private getByUuid(uuid: string): List {
return this.lists.find(l => l._id === uuid);
}
private update(list: List): void {
const index = this.lists.findIndex(l => l._id === list._id);
if (index !== -1) {
this.lists.splice(index, 1, list);
this.persist();
this.broadCast();
}
}
getCurrentListUuid(): SpecialListUUID | string {
return this.currentUuid;
}
getAll(): void {
this.lists = this.store.getList(LISTS);
this.broadCast();
}
setCurrentUuid(uuid: string): void {
this.currentUuid = uuid;
this.current = this.lists.find(l => l._id === uuid);
this.broadCast();
}
add(title: string): void {
const newList = new List(title);
this.lists.push(newList);
this.currentUuid = newList._id;
this.current = newList;
this.broadCast();
this.persist();
}
rename(listUuid: string, title: string) {
const list = this.getByUuid(listUuid);
if (list) {
list.title = title;
this.update(list);
}
}
delete(uuid: string): void {
const i = this.lists.findIndex(l => l._id === uuid);
if (i !== -1) {
this.lists.splice(i, 1);
this.currentUuid = this.lists.length
? this.lists[ this.lists.length - 1 ]._id
: this.currentUuid === 'today'
? 'today'
: 'todo';
this.broadCast();
this.persist();
}
}
}
| 411 | 0.860646 | 1 | 0.860646 | game-dev | MEDIA | 0.58444 | game-dev | 0.836589 | 1 | 0.836589 |
mangosone/server | 10,255 | src/game/OutdoorPvP/OutdoorPvPNA.h | /**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2025 MaNGOS <https://www.getmangos.eu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#ifndef WORLD_PVP_NA
#define WORLD_PVP_NA
#include "Common.h"
#include "OutdoorPvP.h"
#include "Language.h"
enum
{
MAX_NA_GUARDS = 15,
MAX_NA_ROOSTS = 4, // roosts for each type and team
MAX_FIRE_BOMBS = 10,
// spells
SPELL_STRENGTH_HALAANI = 33795,
SPELL_NAGRAND_TOKEN_ALLIANCE = 33005,
SPELL_NAGRAND_TOKEN_HORDE = 33004,
// npcs
// quest credit
NPC_HALAA_COMBATANT = 24867,
GRAVEYARD_ID_HALAA = 993,
GRAVEYARD_ZONE_ID_HALAA = 3518,
ITEM_ID_FIRE_BOMB = 24538,
// gameobjects
GO_HALAA_BANNER = 182210,
// spawned when horde is in control - alliance is attacking
GO_WYVERN_ROOST_ALLIANCE_SOUTH = 182267,
GO_WYVERN_ROOST_ALLIANCE_WEST = 182280,
GO_WYVERN_ROOST_ALLIANCE_NORTH = 182281,
GO_WYVERN_ROOST_ALLIANCE_EAST = 182282,
GO_BOMB_WAGON_HORDE_SOUTH = 182222,
GO_BOMB_WAGON_HORDE_WEST = 182272,
GO_BOMB_WAGON_HORDE_NORTH = 182273,
GO_BOMB_WAGON_HORDE_EAST = 182274,
GO_DESTROYED_ROOST_ALLIANCE_SOUTH = 182266,
GO_DESTROYED_ROOST_ALLIANCE_WEST = 182275,
GO_DESTROYED_ROOST_ALLIANCE_NORTH = 182276,
GO_DESTROYED_ROOST_ALLIANCE_EAST = 182277,
// spawned when alliance is in control - horde is attacking
GO_WYVERN_ROOST_HORDE_SOUTH = 182301,
GO_WYVERN_ROOST_HORDE_WEST = 182302,
GO_WYVERN_ROOST_HORDE_NORTH = 182303,
GO_WYVERN_ROOST_HORDE_EAST = 182304,
GO_BOMB_WAGON_ALLIANCE_SOUTH = 182305,
GO_BOMB_WAGON_ALLIANCE_WEST = 182306,
GO_BOMB_WAGON_ALLIANCE_NORTH = 182307,
GO_BOMB_WAGON_ALLIANCE_EAST = 182308,
GO_DESTROYED_ROOST_HORDE_SOUTH = 182297,
GO_DESTROYED_ROOST_HORDE_WEST = 182298,
GO_DESTROYED_ROOST_HORDE_NORTH = 182299,
GO_DESTROYED_ROOST_HORDE_EAST = 182300,
// npcs
// alliance
NPC_RESEARCHER_KARTOS = 18817,
NPC_QUARTERMASTER_DAVIAN = 18822,
NPC_MERCHANT_ALDRAAN = 21485,
NPC_VENDOR_CENDRII = 21487,
NPC_AMMUNITIONER_BANRO = 21488,
NPC_ALLIANCE_HANAANI_GUARD = 18256,
// horde
NPC_RESEARCHER_AMERELDINE = 18816,
NPC_QUARTERMASTER_NORELIQE = 18821,
NPC_MERCHANT_COREIEL = 21474,
NPC_VENDOR_EMBELAR = 21484,
NPC_AMMUNITIONER_TASALDAN = 21483,
NPC_HORDE_HALAANI_GUARD = 18192,
// events
EVENT_HALAA_BANNER_WIN_ALLIANCE = 11504,
EVENT_HALAA_BANNER_WIN_HORDE = 11503,
EVENT_HALAA_BANNER_CONTEST_ALLIANCE = 11559,
EVENT_HALAA_BANNER_CONTEST_HORDE = 11558,
EVENT_HALAA_BANNER_PROGRESS_ALLIANCE = 11821,
EVENT_HALAA_BANNER_PROGRESS_HORDE = 11822,
// world states
WORLD_STATE_NA_GUARDS_HORDE = 2503,
WORLD_STATE_NA_GUARDS_ALLIANCE = 2502,
WORLD_STATE_NA_GUARDS_MAX = 2493,
WORLD_STATE_NA_GUARDS_LEFT = 2491,
// map states
WORLD_STATE_NA_WYVERN_NORTH_NEUTRAL_H = 2762,
WORLD_STATE_NA_WYVERN_NORTH_NEUTRAL_A = 2662,
WORLD_STATE_NA_WYVERN_NORTH_H = 2663,
WORLD_STATE_NA_WYVERN_NORTH_A = 2664,
WORLD_STATE_NA_WYVERN_SOUTH_NEUTRAL_H = 2760,
WORLD_STATE_NA_WYVERN_SOUTH_NEUTRAL_A = 2670,
WORLD_STATE_NA_WYVERN_SOUTH_H = 2668,
WORLD_STATE_NA_WYVERN_SOUTH_A = 2669,
WORLD_STATE_NA_WYVERN_WEST_NEUTRAL_H = 2761,
WORLD_STATE_NA_WYVERN_WEST_NEUTRAL_A = 2667,
WORLD_STATE_NA_WYVERN_WEST_H = 2665,
WORLD_STATE_NA_WYVERN_WEST_A = 2666,
WORLD_STATE_NA_WYVERN_EAST_NEUTRAL_H = 2763,
WORLD_STATE_NA_WYVERN_EAST_NEUTRAL_A = 2659,
WORLD_STATE_NA_WYVERN_EAST_H = 2660,
WORLD_STATE_NA_WYVERN_EAST_A = 2661,
WORLD_STATE_NA_HALAA_NEUTRAL = 2671,
WORLD_STATE_NA_HALAA_NEUTRAL_A = 2676,
WORLD_STATE_NA_HALAA_NEUTRAL_H = 2677,
WORLD_STATE_NA_HALAA_HORDE = 2672,
WORLD_STATE_NA_HALAA_ALLIANCE = 2673,
};
struct HalaaSoldiersSpawns
{
float x, y, z, o;
};
static const uint32 nagrandRoostsAlliance[MAX_NA_ROOSTS] = {GO_WYVERN_ROOST_ALLIANCE_SOUTH, GO_WYVERN_ROOST_ALLIANCE_NORTH, GO_WYVERN_ROOST_ALLIANCE_EAST, GO_WYVERN_ROOST_ALLIANCE_WEST};
static const uint32 nagrandRoostsHorde[MAX_NA_ROOSTS] = {GO_WYVERN_ROOST_HORDE_SOUTH, GO_WYVERN_ROOST_HORDE_NORTH, GO_WYVERN_ROOST_HORDE_EAST, GO_WYVERN_ROOST_HORDE_WEST};
static const uint32 nagrandRoostsBrokenAlliance[MAX_NA_ROOSTS] = {GO_DESTROYED_ROOST_ALLIANCE_SOUTH, GO_DESTROYED_ROOST_ALLIANCE_NORTH, GO_DESTROYED_ROOST_ALLIANCE_EAST, GO_DESTROYED_ROOST_ALLIANCE_WEST};
static const uint32 nagrandRoostsBrokenHorde[MAX_NA_ROOSTS] = {GO_DESTROYED_ROOST_HORDE_SOUTH, GO_DESTROYED_ROOST_HORDE_NORTH, GO_DESTROYED_ROOST_HORDE_EAST, GO_DESTROYED_ROOST_HORDE_WEST};
static const uint32 nagrandWagonsAlliance[MAX_NA_ROOSTS] = {GO_BOMB_WAGON_ALLIANCE_SOUTH, GO_BOMB_WAGON_ALLIANCE_NORTH, GO_BOMB_WAGON_ALLIANCE_EAST, GO_BOMB_WAGON_ALLIANCE_WEST};
static const uint32 nagrandWagonsHorde[MAX_NA_ROOSTS] = {GO_BOMB_WAGON_HORDE_SOUTH, GO_BOMB_WAGON_HORDE_NORTH, GO_BOMB_WAGON_HORDE_EAST, GO_BOMB_WAGON_HORDE_WEST};
static const uint32 nagrandRoostStatesAlliance[MAX_NA_ROOSTS] = {WORLD_STATE_NA_WYVERN_SOUTH_A, WORLD_STATE_NA_WYVERN_NORTH_A, WORLD_STATE_NA_WYVERN_EAST_A, WORLD_STATE_NA_WYVERN_WEST_A};
static const uint32 nagrandRoostStatesHorde[MAX_NA_ROOSTS] = {WORLD_STATE_NA_WYVERN_SOUTH_H, WORLD_STATE_NA_WYVERN_NORTH_H, WORLD_STATE_NA_WYVERN_EAST_H, WORLD_STATE_NA_WYVERN_WEST_H};
static const uint32 nagrandRoostStatesAllianceNeutral[MAX_NA_ROOSTS] = {WORLD_STATE_NA_WYVERN_SOUTH_NEUTRAL_A, WORLD_STATE_NA_WYVERN_NORTH_NEUTRAL_A, WORLD_STATE_NA_WYVERN_EAST_NEUTRAL_A, WORLD_STATE_NA_WYVERN_WEST_NEUTRAL_A};
static const uint32 nagrandRoostStatesHordeNeutral[MAX_NA_ROOSTS] = {WORLD_STATE_NA_WYVERN_SOUTH_NEUTRAL_H, WORLD_STATE_NA_WYVERN_NORTH_NEUTRAL_H, WORLD_STATE_NA_WYVERN_EAST_NEUTRAL_H, WORLD_STATE_NA_WYVERN_WEST_NEUTRAL_H};
class OutdoorPvPNA : public OutdoorPvP
{
public:
OutdoorPvPNA();
void HandlePlayerEnterZone(Player* player, bool isMainZone) override;
void HandlePlayerLeaveZone(Player* player, bool isMainZone) override;
void FillInitialWorldStates(WorldPacket& data, uint32& count) override;
void SendRemoveWorldStates(Player* player) override;
bool HandleEvent(uint32 eventId, GameObject* go) override;
void HandleObjectiveComplete(uint32 eventId, const std::list<Player*> &players, Team team) override;
void HandleCreatureCreate(Creature* creature) override;
void HandleGameObjectCreate(GameObject* go) override;
void HandleCreatureDeath(Creature* creature) override;
void HandlePlayerKillInsideArea(Player* player) override;
bool HandleGameObjectUse(Player* player, GameObject* go) override;
void Update(uint32 diff) override;
private:
// world states handling
void UpdateWorldState(uint32 value);
void UpdateWyvernsWorldState(uint32 value);
// process capture events
void ProcessCaptureEvent(GameObject* go, Team team);
// set specific team vendors and objects after capture
void DespawnVendors(const WorldObject* objRef);
void HandleFactionObjects(const WorldObject* objRef);
// handle a specific game objects
void LockHalaa(const WorldObject* objRef);
void UnlockHalaa(const WorldObject* objRef);
// handle soldier respawn on timer
void RespawnSoldier();
Team m_zoneOwner;
uint32 m_soldiersRespawnTimer;
uint32 m_zoneWorldState;
uint32 m_zoneMapState;
uint32 m_roostWorldState[MAX_NA_ROOSTS];
uint8 m_guardsLeft;
bool m_isUnderSiege;
ObjectGuid m_capturePoint;
ObjectGuid m_roostsAlliance[MAX_NA_ROOSTS];
ObjectGuid m_roostsHorde[MAX_NA_ROOSTS];
ObjectGuid m_roostsBrokenAlliance[MAX_NA_ROOSTS];
ObjectGuid m_roostsBrokenHorde[MAX_NA_ROOSTS];
ObjectGuid m_wagonsAlliance[MAX_NA_ROOSTS];
ObjectGuid m_wagonsHorde[MAX_NA_ROOSTS];
GuidList m_teamVendors;
std::queue<HalaaSoldiersSpawns> m_deadSoldiers;
};
#endif
| 411 | 0.621957 | 1 | 0.621957 | game-dev | MEDIA | 0.995621 | game-dev | 0.55345 | 1 | 0.55345 |
openairlinetycoon/OpenATDeluxe | 2,125 | src/Scenes/Cafe.cs | using Godot;
using System;
using System.Collections.Generic;
public class Cafe : BaseRoom {
AnimationList rickAnims = new AnimationList();
//SAVED
public static bool hasMetRick = false;
//STILL WIP - will be finished when missions are implemented - rick depends on those!
public override void OnReady() {
Vector2 rickPos = new Vector2(-229, -91);
rickAnims.basePosition = rickPos;
rickAnims.CreateMouseArea(baseNode);
DialogueSystem.AddActor(new Actor("RI",(DialogueWindow)FindNode("RI")));
Dialogue rickDialogue = new Dialogue("Rick","rickDialogue","RI");
{
DialogueNode start = new DialogueNode(1000);
rickDialogue.AddNode(start); //All nodes which can start a dialogue have to be added to the dialogue!
DialogueNode greeting = new DialogueNode(1200);
greeting.AddEvent(()=>hasMetRick=true);
DialogueNode noNews = new DialogueNodeExit(2199);
//if(firstMeet)
start.AddOption(new DialogueOptionConditioned(()=>hasMetRick?2000:1100, ()=>hasMetRick?noNews:greeting));
//else
//start.AddOption(new DialogueOption(2000, randomTip));
DialogueNode firstAdvice1 = new DialogueNode(1400);
DialogueNode firstAdvice2 = new DialogueNodeExit(1401);
firstAdvice1.AddFollowup(firstAdvice2);
greeting.AddOption(new DialogueOption(1300, firstAdvice1));
}
rickAnims.mouseArea.onClick += () => DialogueSystem.StartDialogue(rickDialogue);
//Idle 0:
rickAnims.Add(SmkAnimation.CreateAnimation(baseNode,"Bar_WAIT.smk",
goal:new AnimationGoalIdle("RI",2,1)));
//Idle 1:
rickAnims.Add(SmkAnimation.CreateAnimation(baseNode,"Bar_AUG.smk",
goal:new AnimationGoal(finish:0)));
//Talk 2:
rickAnims.Add(SmkAnimation.CreateAnimation(baseNode,"Bar_rede.smk",
goal:new AnimationGoalTalking(null,"RI",3,0)));
//No Talk 3:
rickAnims.Add(SmkAnimation.CreateAnimation(baseNode,"Bar_WAIT.smk",
goal:new AnimationGoalListening(null,"RI",2,0)));
rickAnims.Play(0);
}
override public void _Process(float delta) {
rickAnims.ProcessTrigger();
}
public override void Cancel() {
throw new NotImplementedException();
}
} | 411 | 0.630333 | 1 | 0.630333 | game-dev | MEDIA | 0.840544 | game-dev | 0.569761 | 1 | 0.569761 |
FirstPersonKSP/AvionicsSystems | 4,223 | GameData/MOARdV/MAS_ASET/Push_Button_Modular/MAS_pb_Eng_2_Fuel_Pump.cfg | PROP
{
name = MAS_pb_Eng_2_Fuel_Pump
// Black full cap
MODEL
{
model = ASET/ASET_Props/Control/Push_Button_Modular/models/pb_Full_Cap
texture = pb_Full_Cap_Black,ASET/ASET_Props/Control/Push_Button_Modular/models/pb_Full_Cap_Black
texture = Switch_TUMBLEDiffuse,ASET/ASET_Props/Control/Switch_Tumble/Switch_TUMBLEDiffuse
}
// Glow Border Type 5 - 3/4 wrap around, text on top
MODEL
{
model = ASET/ASET_Props/Control/Push_Button_Modular/models/pb_Bcklt_5
texture = Switch_TUMBLEDiffuse,ASET/ASET_Props/Control/Switch_Tumble/Switch_TUMBLEDiffuse
}
MODEL
{
model = ASET/ASET_Props/Control/Push_Button_Modular/models/pb_Cover02
texture = pb_Glass_Diffuse,ASET/ASET_Props/Control/Push_Button_Modular/models/pb_Glass_Diffuse
texture = Switch_TUMBLEDiffuse,ASET/ASET_Props/Control/Switch_Tumble/Switch_TUMBLEDiffuse
}
MODEL
{
model = ASET/ASET_Props/Control/Push_Button_Modular/models/pb_Collider
}
MODULE
{
name = MASComponent
ANIMATION
{
name = Cover Animation
animation = pb_Cover_Anim
variable = fc.GetPersistent("Global_Fuel_Cover_2") * (fc.GetPersistentAsNumber("Global_FuelDoor_State") == 0)
speed = 5
}
COLLIDER_EVENT
{
name = Cover Collider
collider = pb_Cover_Collider
onClick = fc.TogglePersistent("Global_Fuel_Cover_2")
sound = ASET/ASET_Props/Sounds/pb_Cover02
volume = 1
}
COLLIDER_EVENT
{
name = Collider
collider = pb_Collider
sound = ASET/ASET_Props/Sounds/pb_Push02
volume = 1
variable = fc.GetPersistentAsNumber("Global_FuelLeverState_Eng_1")
onClick = fc.TogglePersistent("Global_FuelPumpState_Eng_2")
}
ANIMATION_PLAYER
{
name = Button press animation
animation = pb_PushAnim
animationSpeed = 1.0
variable = fc.GetPersistentAsNumber("Global_FuelPumpState_Eng_2")
}
TEXT_LABEL
{
name = Caption
transform = PanelTextTop_cover
fontSize = 5.8
lineSpacing = 0.9
font = Liberation Sans
style = Bold
alignment = Center
anchor = LowerCenter
emissive = active
variable = fc.Conditioned(fc.GetPersistentAsNumber("Backlight"))
blend = true
activeColor = COLOR_ASET_SWITCHER_NAME_POSITIVECOLOR
passiveColor = COLOR_ASET_SWITCHER_NAME_ZEROCOLOR
text = FUEL$$$PUMP#2
}
TEXT_LABEL
{
name = Upper Legend
transform = Legend_Upper
fontSize = 3.9
lineSpacing = 0.9
font = Liberation Sans
style = Bold
alignment = Center
anchor = MiddleCenter
emissive = active
variable = fc.Conditioned(1 - fc.GetPersistentAsNumber("Global_FuelPumpState_Eng_2"))
activeColor = COLOR_MOARdV_IndicatorLampAmber
passiveColor = COLOR_MOARdV_PassiveBacklightText
text = OFF
}
TEXT_LABEL
{
name = Upper Legend Bullets
transform = Legend_Upper
fontSize = 3.9
lineSpacing = 0.9
font = Liberation Sans
style = Bold
alignment = Center
anchor = MiddleCenter
emissive = active
variable = fc.Conditioned(1 - fc.GetPersistentAsNumber("Global_FuelPumpState_Eng_2"))
activeColor = COLOR_MOARdV_IndicatorLampAmber
passiveColor = COLOR_MOARdV_PassiveBacklightText
text = ● ●
}
TEXT_LABEL
{
name = Lower Legend
transform = Legend_Lower
fontSize = 3.9
lineSpacing = 0.9
font = Liberation Sans
style = Bold
alignment = Center
anchor = MiddleCenter
emissive = active
variable = fc.Conditioned(fc.GetPersistentAsNumber("Global_FuelPumpState_Eng_2"))
activeColor = COLOR_MOARdV_IndicatorLampGreen
passiveColor = COLOR_MOARdV_PassiveBacklightText
text = ON
}
TEXT_LABEL
{
name = Lower Legend Bullets
transform = Legend_Lower
fontSize = 3.9
lineSpacing = 0.9
font = Liberation Sans
style = Bold
alignment = Center
anchor = MiddleCenter
emissive = active
variable = fc.Conditioned(fc.GetPersistentAsNumber("Global_FuelPumpState_Eng_2"))
activeColor = COLOR_MOARdV_IndicatorLampGreen
passiveColor = COLOR_MOARdV_PassiveBacklightText
text = ● ●
}
COLOR_SHIFT
{
name = Border
transform = GlowBorder
variable = fc.Conditioned(fc.GetPersistentAsNumber("Backlight"))
passiveColor = 0,0,0,255
activeColor = COLOR_ASET_SWITCHER_BORDER_POSITIVECOLOR
blend = true
}
}
}
| 411 | 0.879759 | 1 | 0.879759 | game-dev | MEDIA | 0.807285 | game-dev | 0.678606 | 1 | 0.678606 |
metadriverse/urban-sim | 1,946 | meta_source/metadrive/metadrive/engine/physics_node.py | """
Physics Node is the subclass of BulletNode (BulletRigidBBodyNode/BulletGhostNode and so on)
Since callback method in BulletPhysicsEngine returns PhysicsNode class and sometimes we need to do some custom
calculation and tell Object about these results, inheriting from these BulletNode class will help communicate between
Physics Callbacks and Object class
"""
from panda3d.bullet import BulletRigidBodyNode, BulletGhostNode
class BaseRigidBodyNode(BulletRigidBodyNode):
def __init__(self, base_object_name, type_name):
self.type_name = type_name
super(BaseRigidBodyNode, self).__init__(type_name)
self.setPythonTag(type_name, self)
self.base_object_name = base_object_name
self._clear_python_tag = False
def rename(self, new_name):
self.base_object_name = new_name
def destroy(self):
# This sentence is extremely important!
self.base_object_name = None
self.clearPythonTag(self.getName())
self._clear_python_tag = True
def __del__(self):
assert self._clear_python_tag, "You should call destroy() of BaseRigidBodyNode!"
class BaseGhostBodyNode(BulletGhostNode):
"""
Ghost node will not collide with any bodies, while contact information can still be accessed
"""
def __init__(self, base_object_name, type_name):
self.type_name = type_name
super(BaseGhostBodyNode, self).__init__(type_name)
self.setPythonTag(type_name, self)
self.base_object_name = base_object_name
self._clear_python_tag = False
def rename(self, new_name):
self.base_object_name = new_name
def destroy(self):
# This sentence is extremely important!
self.base_object_name = None
self.clearPythonTag(self.getName())
self._clear_python_tag = True
def __del__(self):
assert self._clear_python_tag, "You should call destroy() of BaseRigidBodyNode!"
| 411 | 0.80738 | 1 | 0.80738 | game-dev | MEDIA | 0.705121 | game-dev | 0.841101 | 1 | 0.841101 |
SteveDunn/PacManBlazor | 1,898 | src/PacMan.GameComponents/GlobalDotCounter.cs | using PacMan.GameComponents.Ghosts;
namespace PacMan.GameComponents;
public class GlobalDotCounter : DotCounter
{
private bool _finished;
private GhostNickname? _nextOneToForceOut;
private GhostNickname? _lastOneForcedOut;
public GlobalDotCounter(int limit = 0) : base(limit, "GLOBAL")
{
}
public virtual void Reset()
{
_finished = false;
Counter = 0;
}
// the thing that calls this switches dot counters if all the ghosts are out.
// this never finishes if Clyde is out the house when the counter reaches
// 32 - this mimics the bug in the arcade game
public override bool IsFinished => _finished;
public override void SetTimedOut() =>
_nextOneToForceOut = _lastOneForcedOut switch
{
null => GhostNickname.Pinky,
GhostNickname.Clyde => GhostNickname.Pinky,
GhostNickname.Pinky => GhostNickname.Inky,
GhostNickname.Inky => GhostNickname.Clyde,
_ => _nextOneToForceOut
};
public bool CanGhostLeave(GhostNickname nickName)
{
if (_nextOneToForceOut == nickName)
{
_nextOneToForceOut = null;
_lastOneForcedOut = nickName;
return true;
}
bool canLeave = false;
// ReSharper disable once SwitchStatementMissingSomeEnumCasesNoDefault
switch (nickName)
{
case GhostNickname.Pinky when Counter == 7:
canLeave = true;
break;
case GhostNickname.Inky when Counter == 17:
canLeave = true;
break;
case GhostNickname.Clyde when Counter == 32:
canLeave = true;
// debt: SD: confusing!
_finished = Counter == 32;
break;
}
return canLeave;
}
} | 411 | 0.707966 | 1 | 0.707966 | game-dev | MEDIA | 0.944105 | game-dev | 0.830883 | 1 | 0.830883 |
Innoxia/liliths-throne-public | 8,106 | src/com/lilithsthrone/controller/DebugController.java | package com.lilithsthrone.controller;
import org.w3c.dom.events.EventTarget;
import com.lilithsthrone.controller.eventListeners.tooltips.TooltipInformationEventListener;
import com.lilithsthrone.controller.eventListeners.tooltips.TooltipInventoryEventListener;
import com.lilithsthrone.game.character.markings.AbstractTattooType;
import com.lilithsthrone.game.character.markings.TattooType;
import com.lilithsthrone.game.dialogue.responses.Response;
import com.lilithsthrone.game.dialogue.utils.DebugDialogue;
import com.lilithsthrone.game.inventory.AbstractSetBonus;
import com.lilithsthrone.game.inventory.InventorySlot;
import com.lilithsthrone.game.inventory.ItemTag;
import com.lilithsthrone.game.inventory.SetBonus;
import com.lilithsthrone.game.inventory.clothing.AbstractClothingType;
import com.lilithsthrone.game.inventory.clothing.ClothingType;
import com.lilithsthrone.game.inventory.item.AbstractItemType;
import com.lilithsthrone.game.inventory.item.ItemType;
import com.lilithsthrone.game.inventory.outfit.AbstractOutfit;
import com.lilithsthrone.game.inventory.outfit.OutfitType;
import com.lilithsthrone.game.inventory.weapon.AbstractWeaponType;
import com.lilithsthrone.game.inventory.weapon.WeaponType;
import com.lilithsthrone.main.Main;
/**
* @since 0.4.6.4
* @version 0.4.6.4
* @author Maxis010, Innoxia
*/
public class DebugController {
public static void initSpawnItemListeners() {
String id;
for (AbstractClothingType clothingType : ClothingType.getAllClothing()) {
id = clothingType.getId()+"_SPAWN";
if (MainController.document.getElementById(id) != null) {
((EventTarget) MainController.document.getElementById(id)).addEventListener("click", e->{
Main.game.getActiveWorld().getCell(Main.game.getPlayer().getLocation()).getInventory().addClothing(Main.game.getItemGen().generateClothing(clothingType, true));
MainController.updateUIRightPanel();
}, false);
MainController.addTooltipListeners(id, new TooltipInventoryEventListener().setGenericClothing(clothingType, clothingType.getColourReplacement(0).getFirstOfDefaultColours()));
}
}
for (AbstractWeaponType weaponType : WeaponType.getAllWeapons()) {
id = weaponType.getId()+"_SPAWN";
if (MainController.document.getElementById(id) != null) {
((EventTarget) MainController.document.getElementById(id)).addEventListener("click", e->{
Main.game.getActiveWorld().getCell(Main.game.getPlayer().getLocation()).getInventory().addWeapon(Main.game.getItemGen().generateWeapon(weaponType));
MainController.updateUIRightPanel();
}, false);
MainController.addTooltipListeners(id, new TooltipInventoryEventListener().setGenericWeapon(weaponType, weaponType.getAvailableDamageTypes().get(0)));
}
}
for (AbstractItemType itemType : ItemType.getAllItems()) {
id = itemType.getId()+"_SPAWN";
if (MainController.document.getElementById(id) != null) {
((EventTarget) MainController.document.getElementById(id)).addEventListener("click", e->{
Main.game.getActiveWorld().getCell(Main.game.getPlayer().getLocation()).getInventory().addItem(Main.game.getItemGen().generateItem(itemType));
MainController.updateUIRightPanel();
}, false);
MainController.addTooltipListeners(id, new TooltipInventoryEventListener().setGenericItem(itemType));
}
}
for (AbstractTattooType tattooType : TattooType.getAllTattooTypes()) {
id = tattooType.getId()+"_SPAWN";
if (MainController.document.getElementById(id) != null) {
MainController.addTooltipListeners(id, new TooltipInventoryEventListener().setGenericTattoo(tattooType));
}
}
for (InventorySlot slot : InventorySlot.values()) {
id = slot+"_SPAWN_SELECT";
if (MainController.document.getElementById(id) != null) {
((EventTarget) MainController.document.getElementById(id)).addEventListener("click", e->{
DebugDialogue.itemTag = null;
DebugDialogue.activeSlot = slot;
Main.game.setContent(new Response("", "", Main.game.getCurrentDialogueNode()));
}, false);
}
}
id = "ITEM_SPAWN_SELECT";
if (MainController.document.getElementById(id) != null) {
((EventTarget) MainController.document.getElementById(id)).addEventListener("click", e->{
DebugDialogue.activeSlot = null;
DebugDialogue.itemTag = null;
Main.game.setContent(new Response("", "", Main.game.getCurrentDialogueNode()));
}, false);
}
id = "BOOK_SPAWN_SELECT";
if (MainController.document.getElementById(id) != null) {
((EventTarget) MainController.document.getElementById(id)).addEventListener("click", e->{
DebugDialogue.activeSlot = null;
DebugDialogue.itemTag = ItemTag.BOOK;
Main.game.setContent(new Response("", "", Main.game.getCurrentDialogueNode()));
}, false);
}
id = "ESSENCE_SPAWN_SELECT";
if (MainController.document.getElementById(id) != null) {
((EventTarget) MainController.document.getElementById(id)).addEventListener("click", e->{
DebugDialogue.activeSlot = null;
DebugDialogue.itemTag = ItemTag.ESSENCE;
Main.game.setContent(new Response("", "", Main.game.getCurrentDialogueNode()));
}, false);
}
id = "SPELL_SPAWN_SELECT";
if (MainController.document.getElementById(id) != null) {
((EventTarget) MainController.document.getElementById(id)).addEventListener("click", e->{
DebugDialogue.activeSlot = null;
DebugDialogue.itemTag = ItemTag.SPELL_BOOK;
Main.game.setContent(new Response("", "", Main.game.getCurrentDialogueNode()));
}, false);
}
id = "HIDDEN_SPAWN_SELECT";
if (MainController.document.getElementById(id) != null) {
((EventTarget) MainController.document.getElementById(id)).addEventListener("click", e->{
DebugDialogue.activeSlot = null;
DebugDialogue.itemTag = ItemTag.CHEAT_ITEM;
Main.game.setContent(new Response("", "", Main.game.getCurrentDialogueNode()));
}, false);
}
}
public static void initSpawnSetListeners() {
for (AbstractSetBonus sb : SetBonus.allSetBonuses) {
String id = "SET_BONUS_"+SetBonus.getIdFromSetBonus(sb);
if (MainController.document.getElementById(id) != null) {
((EventTarget) MainController.document.getElementById(id)).addEventListener("click", e->{
if(WeaponType.getAllWeaponsInSet(sb)!=null) {
for (AbstractWeaponType wt : WeaponType.getAllWeaponsInSet(sb)) {
Main.game.getActiveWorld().getCell(Main.game.getPlayer().getLocation()).getInventory().addWeapon(Main.game.getItemGen().generateWeapon(wt));
}
}
if(ClothingType.getAllClothingInSet(sb)!=null) {
for (AbstractClothingType ct : ClothingType.getAllClothingInSet(sb)) {
Main.game.getActiveWorld().getCell(Main.game.getPlayer().getLocation()).getInventory().addClothing(Main.game.getItemGen().generateClothing(ct, false));
}
}
Main.game.setContent(new Response("", "", Main.game.getCurrentDialogueNode()));
}, false);
}
}
}
public static void initApplyOutfitListeners() {
for (AbstractOutfit ot : OutfitType.getAllOutfits()) {
String id = "OUTFIT_"+OutfitType.getIdFromOutfitType(ot);
if (MainController.document.getElementById(id) != null) {
((EventTarget) MainController.document.getElementById(id)).addEventListener("click", e->{
DebugDialogue.applyOutfitToDoll(ot);
Main.game.setContent(new Response("", "", Main.game.getCurrentDialogueNode()));
}, false);
MainController.addEventListener(MainController.document, id, "mousemove", MainController.moveTooltipListener, false);
MainController.addEventListener(MainController.document, id, "mouseleave", MainController.hideTooltipListener, false);
TooltipInformationEventListener el = new TooltipInformationEventListener().setInformation("Apply Outfit",
"Click to apply this outfit to the Dress-up doll."
+ " The outfit's femininity, outfit type, and conditional statement are all ignored for this purpose."
+ " The doll's leg configuration will change if needed."
+ " Click this multiple times to see many variations.");
MainController.addEventListener(MainController.document, id, "mouseenter", el, false);
}
}
}
}
| 411 | 0.858336 | 1 | 0.858336 | game-dev | MEDIA | 0.947349 | game-dev | 0.903198 | 1 | 0.903198 |
aappleby/matcheroni | 5,031 | examples/regex/regex_parser.cpp | //------------------------------------------------------------------------------
// This file is a full working example of using Matcheroni to build a parser
// that can parse a subset of regular expressions. Supported operators are
// ^, $, ., *, ?, +, |, (), [], [^], and escaped characters.
// Example usage:
// bin/regex_parser "(^\d+\s+(very)?\s+(good|bad)\s+[a-z]*$)"
// SPDX-FileCopyrightText: 2023 Austin Appleby <aappleby@gmail.com>
// SPDX-License-Identifier: MIT License
#include "matcheroni/Matcheroni.hpp"
#include "matcheroni/Parseroni.hpp"
#include "matcheroni/Utilities.hpp"
using namespace matcheroni;
using namespace parseroni;
template<StringParam match_name, typename pattern, typename node_type>
struct Capture3 {
static TextSpan match(TextParseContext& ctx, TextSpan body) {
return Capture<match_name, pattern, node_type>::match(ctx, body);
}
};
//------------------------------------------------------------------------------
// To match anything at all, we first need to tell Matcheroni how to compare
// one atom of our input sequence against a constant.
static TextSpan match_regex(TextParseContext& ctx, TextSpan body);
// Our 'control' characters consist of all atoms with special regex meanings.
struct cchar {
using pattern = Atoms<'\\', '(', ')', '|', '$', '.', '+', '*', '?', '[', ']', '^'>;
static TextSpan match(TextParseContext& ctx, TextSpan body) { return pattern::match(ctx, body); }
};
// Our 'plain' characters are every character that's not a control character.
struct pchar {
using pattern = Seq<Not<cchar>, AnyAtom>;
static TextSpan match(TextParseContext& ctx, TextSpan body) { return pattern::match(ctx, body); }
};
// Plain text is any span of plain characters not followed by an operator.
struct text {
using pattern = Some<Seq<pchar, Not<Atoms<'*', '+', '?'>>>>;
static TextSpan match(TextParseContext& ctx, TextSpan body) { return pattern::match(ctx, body); }
};
// Our 'meta' characters are anything after a backslash.
struct mchar {
using pattern = Seq<Atom<'\\'>, AnyAtom>;
static TextSpan match(TextParseContext& ctx, TextSpan body) { return pattern::match(ctx, body); }
};
// A character range is a beginning character and an end character separated
// by a hyphen.
struct range {
using pattern = Seq<
Capture3<"begin", pchar, TextParseNode>,
Atom<'-'>,
Capture3<"end", pchar, TextParseNode>
>;
static TextSpan match(TextParseContext& ctx, TextSpan body) { return pattern::match(ctx, body); }
};
// The contents of a matcher set must be ranges or individual characters.
struct set_body {
static TextSpan match(TextParseContext& ctx, TextSpan body) {
return
Some<
Capture3<"range", range, TextParseNode>,
Capture3<"char", pchar, TextParseNode>,
Capture3<"meta", mchar, TextParseNode>
>::match(ctx, body);
}
};
// The regex units that we can apply a */+/? operator to are sets, groups,
// dots, and single characters.
// Note that "group" recurses through RegexParser::match.
struct unit {
using pattern =
Oneof<
Capture3<"neg_set", Seq<Atom<'['>, Atom<'^'>, set_body, Atom<']'>>, TextParseNode>,
Capture3<"pos_set", Seq<Atom<'['>, set_body, Atom<']'>>, TextParseNode>,
Capture3<"group", Seq<Atom<'('>, Ref<match_regex>, Atom<')'>>, TextParseNode>,
Capture3<"dot", Atom<'.'>, TextParseNode>,
Capture3<"char", pchar, TextParseNode>,
Capture3<"meta", mchar, TextParseNode>
>;
static TextSpan match(TextParseContext& ctx, TextSpan body) { return pattern::match(ctx, body); }
};
// A 'simple' regex is text, line end markers, a unit w/ operator, or a bare
// unit.
struct simple {
using pattern = Some<
Capture3<"text", text, TextParseNode>,
Capture3<"BOL", Atom<'^'>, TextParseNode>,
Capture3<"EOL", Atom<'$'>, TextParseNode>,
Capture3<"any", Seq<unit, Atom<'*'>>, TextParseNode>,
Capture3<"some", Seq<unit, Atom<'+'>>, TextParseNode>,
Capture3<"opt", Seq<unit, Atom<'?'>>, TextParseNode>,
unit
>;
static TextSpan match(TextParseContext& ctx, TextSpan body) {
return pattern::match(ctx, body);
}
};
// A 'one-of' regex is a list of simple regexes separated by '|'.
struct oneof {
using pattern =
Seq<
Capture3<"option", simple, TextParseNode>,
Some<Seq<
Atom<'|'>,
Capture3<"option", simple, TextParseNode>
>>
>;
static TextSpan match(TextParseContext& ctx, TextSpan body) {
return pattern::match(ctx, body);
}
};
// This is the top level of our regex parser.
static TextSpan match_regex(TextParseContext& ctx, TextSpan body) {
// A 'top-level' regex is either a simple regex or a one-of regex.
using regex_top =
Oneof<
Capture3<"oneof", oneof, TextParseNode>,
simple
>;
return regex_top::match(ctx, body);
}
TextSpan parse_regex(TextParseContext& ctx, TextSpan body) {
return match_regex(ctx, body);
//return body.fail();
}
//------------------------------------------------------------------------------
| 411 | 0.85674 | 1 | 0.85674 | game-dev | MEDIA | 0.273466 | game-dev | 0.726829 | 1 | 0.726829 |
b-crawl/bcrawl | 2,560 | crawl-ref/source/webserver/game_data/static/view_data.js | define(["jquery", "comm"], function ($, comm) {
"use strict";
var exports = {};
exports.flash = 0;
exports.flash_colour = null;
var flash_changed = false;
function VColour(r, g, b, a)
{
return {r: r, g: g, b: b, a: a};
}
// Compare tilereg-dgn.cc
var flash_colours = [
VColour( 0, 0, 0, 0), // BLACK (transparent)
VColour( 0, 0, 128, 100), // BLUE
VColour( 0, 128, 0, 100), // GREEN
VColour( 0, 128, 128, 100), // CYAN
VColour(128, 0, 0, 100), // RED
VColour(150, 0, 150, 100), // MAGENTA
VColour(165, 91, 0, 100), // BROWN
VColour( 50, 50, 50, 150), // LIGHTGRAY
VColour( 0, 0, 0, 150), // DARKGRAY
VColour( 64, 64, 255, 100), // LIGHTBLUE
VColour( 64, 255, 64, 100), // LIGHTGREEN
VColour( 0, 255, 255, 100), // LIGHTCYAN
VColour(255, 64, 64, 100), // LIGHTRED
VColour(255, 64, 255, 100), // LIGHTMAGENTA
VColour(150, 150, 0, 100), // YELLOW
VColour(255, 255, 255, 100), // WHITE
];
exports.flash_changed = function ()
{
var val = flash_changed;
flash_changed = false;
return val;
}
function handle_flash_message(data)
{
if (exports.flash != data.col)
flash_changed = true;
exports.flash = data.col;
if (data.col)
exports.flash_colour = flash_colours[data.col];
else
exports.flash_colour = null;
}
exports.cursor_locs = [];
function place_cursor(type, loc)
{
var old_loc;
if (exports.cursor_locs[type])
{
old_loc = exports.cursor_locs[type];
}
exports.cursor_locs[type] = loc;
var rerender = [];
if (old_loc)
rerender.push(old_loc);
if (loc)
rerender.push(loc);
$("#dungeon").trigger("update_cells", [rerender]);
}
exports.place_cursor = place_cursor;
exports.remove_cursor = function (type)
{
place_cursor(type, null);
}
function handle_cursor_message(data)
{
place_cursor(data.id, data.loc);
}
function init()
{
exports.flash = 0;
exports.flash_colour = null;
flash_changed = false;
exports.cursor_locs = [];
}
$(document).bind("game_init", init);
comm.register_handlers({
"cursor": handle_cursor_message,
"flash": handle_flash_message,
});
return exports;
});
| 411 | 0.654899 | 1 | 0.654899 | game-dev | MEDIA | 0.690631 | game-dev | 0.947219 | 1 | 0.947219 |
Ragebones/StormCore | 33,457 | src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp | /*
* Copyright (C) 2014-2017 StormCore
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Lady_Vashj
SD%Complete: 99
SDComment: Missing blizzlike Shield Generators coords
SDCategory: Coilfang Resevoir, Serpent Shrine Cavern
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "serpent_shrine.h"
#include "Spell.h"
#include "Player.h"
#include "WorldSession.h"
enum LadyVashj
{
SAY_INTRO = 0,
SAY_AGGRO = 1,
SAY_PHASE1 = 2,
SAY_PHASE2 = 3,
SAY_PHASE3 = 4,
SAY_BOWSHOT = 5,
SAY_SLAY = 6,
SAY_DEATH = 7,
SPELL_SURGE = 38044,
SPELL_MULTI_SHOT = 38310,
SPELL_SHOCK_BLAST = 38509,
SPELL_ENTANGLE = 38316,
SPELL_STATIC_CHARGE_TRIGGER = 38280,
SPELL_FORKED_LIGHTNING = 40088,
SPELL_SHOOT = 40873,
SPELL_POISON_BOLT = 40095,
SPELL_TOXIC_SPORES = 38575,
SPELL_MAGIC_BARRIER = 38112,
SHIED_GENERATOR_CHANNEL = 19870,
ENCHANTED_ELEMENTAL = 21958,
TAINTED_ELEMENTAL = 22009,
COILFANG_STRIDER = 22056,
COILFANG_ELITE = 22055,
TOXIC_SPOREBAT = 22140,
TOXIC_SPORES_TRIGGER = 22207
};
#define MIDDLE_X 30.134f
#define MIDDLE_Y -923.65f
#define MIDDLE_Z 42.9f
#define SPOREBAT_X 30.977156f
#define SPOREBAT_Y -925.297761f
#define SPOREBAT_Z 77.176567f
#define SPOREBAT_O 5.223932f
#define TEXT_NOT_INITIALIZED "Instance script not initialized"
#define TEXT_ALREADY_DEACTIVATED "Already deactivated"
float ElementPos[8][4] =
{
{8.3f, -835.3f, 21.9f, 5.0f},
{53.4f, -835.3f, 21.9f, 4.5f},
{96.0f, -861.9f, 21.8f, 4.0f},
{96.0f, -986.4f, 21.4f, 2.5f},
{54.4f, -1010.6f, 22, 1.8f},
{9.8f, -1012, 21.7f, 1.4f},
{-35.0f, -987.6f, 21.5f, 0.8f},
{-58.9f, -901.6f, 21.5f, 6.0f}
};
float ElementWPPos[8][3] =
{
{71.700752f, -883.905884f, 41.097168f},
{45.039848f, -868.022827f, 41.097015f},
{14.585141f, -867.894470f, 41.097061f},
{-25.415508f, -906.737732f, 41.097061f},
{-11.801594f, -963.405884f, 41.097067f},
{14.556657f, -979.051514f, 41.097137f},
{43.466549f, -979.406677f, 41.097027f},
{69.945908f, -964.663940f, 41.097054f}
};
float SporebatWPPos[8][3] =
{
{31.6f, -896.3f, 59.1f},
{9.1f, -913.9f, 56.0f},
{5.2f, -934.4f, 52.4f},
{20.7f, -946.9f, 49.7f},
{41.0f, -941.9f, 51.0f},
{47.7f, -927.3f, 55.0f},
{42.2f, -912.4f, 51.7f},
{27.0f, -905.9f, 50.0f}
};
float CoilfangElitePos[3][4] =
{
{28.84f, -923.28f, 42.9f, 6.0f},
{31.183281f, -953.502625f, 41.523602f, 1.640957f},
{58.895180f, -923.124268f, 41.545307f, 3.152848f}
};
float CoilfangStriderPos[3][4] =
{
{66.427010f, -948.778503f, 41.262245f, 2.584220f},
{7.513962f, -959.538208f, 41.300422f, 1.034629f},
{-12.843201f, -907.798401f, 41.239620f, 6.087094f}
};
float ShieldGeneratorChannelPos[4][4] =
{
{49.6262f, -902.181f, 43.0975f, 3.95683f},
{10.988f, -901.616f, 42.5371f, 5.4373f},
{10.3859f, -944.036f, 42.5446f, 0.779888f},
{49.3126f, -943.398f, 42.5501f, 2.40174f}
};
class boss_lady_vashj : public CreatureScript
{
public:
boss_lady_vashj() : CreatureScript("boss_lady_vashj") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_lady_vashjAI>(creature);
}
struct boss_lady_vashjAI : public ScriptedAI
{
boss_lady_vashjAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
instance = creature->GetInstanceScript();
Intro = false;
JustCreated = true;
CanAttack = false;
creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); // set it only once on Creature create (no need do intro if wiped)
}
void Initialize()
{
AggroTimer = 19000;
ShockBlastTimer = 1 + rand32() % 60000;
EntangleTimer = 30000;
StaticChargeTimer = 10000 + rand32() % 15000;
ForkedLightningTimer = 2000;
CheckTimer = 15000;
EnchantedElementalTimer = 5000;
TaintedElementalTimer = 50000;
CoilfangEliteTimer = 45000 + rand32() % 5000;
CoilfangStriderTimer = 60000 + rand32() % 10000;
SummonSporebatTimer = 10000;
SummonSporebatStaticTimer = 30000;
EnchantedElementalPos = 0;
Phase = 0;
Entangle = false;
}
InstanceScript* instance;
ObjectGuid ShieldGeneratorChannel[4];
uint32 AggroTimer;
uint32 ShockBlastTimer;
uint32 EntangleTimer;
uint32 StaticChargeTimer;
uint32 ForkedLightningTimer;
uint32 CheckTimer;
uint32 EnchantedElementalTimer;
uint32 TaintedElementalTimer;
uint32 CoilfangEliteTimer;
uint32 CoilfangStriderTimer;
uint32 SummonSporebatTimer;
uint32 SummonSporebatStaticTimer;
uint8 EnchantedElementalPos;
uint8 Phase;
bool Entangle;
bool Intro;
bool CanAttack;
bool JustCreated;
void Reset() override
{
Initialize();
if (JustCreated)
{
CanAttack = false;
JustCreated = false;
} else CanAttack = true;
for (uint8 i = 0; i < 4; ++i)
{
if (!ShieldGeneratorChannel[i].IsEmpty())
{
if (Unit* remo = ObjectAccessor::GetUnit(*me, ShieldGeneratorChannel[i]))
{
remo->setDeathState(JUST_DIED);
ShieldGeneratorChannel[i].Clear();
}
}
}
instance->SetData(DATA_LADYVASHJEVENT, NOT_STARTED);
me->SetCorpseDelay(1000*60*60);
}
// Called when a tainted elemental dies
void EventTaintedElementalDeath()
{
// the next will spawn 50 seconds after the previous one's death
if (TaintedElementalTimer > 50000)
TaintedElementalTimer = 50000;
}
void KilledUnit(Unit* /*victim*/) override
{
Talk(SAY_SLAY);
}
void JustDied(Unit* /*killer*/) override
{
Talk(SAY_DEATH);
instance->SetData(DATA_LADYVASHJEVENT, DONE);
}
void StartEvent()
{
Talk(SAY_AGGRO);
Phase = 1;
instance->SetData(DATA_LADYVASHJEVENT, IN_PROGRESS);
}
void EnterCombat(Unit* who) override
{
// remove old tainted cores to prevent cheating in phase 2
Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers();
for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr)
if (Player* player = itr->GetSource())
player->DestroyItemCount(31088, 1, true);
StartEvent(); // this is EnterCombat(), so were are 100% in combat, start the event
if (Phase != 2)
AttackStart(who);
}
void MoveInLineOfSight(Unit* who) override
{
if (!Intro)
{
Intro = true;
Talk(SAY_INTRO);
}
if (!CanAttack)
return;
if (!who || me->GetVictim())
return;
if (me->CanCreatureAttack(who))
{
float attackRadius = me->GetAttackDistance(who);
if (me->IsWithinDistInMap(who, attackRadius) && me->GetDistanceZ(who) <= CREATURE_Z_ATTACK_RANGE && me->IsWithinLOSInMap(who))
{
if (!me->IsInCombat()) // AttackStart() sets UNIT_FLAG_IN_COMBAT, so this msut be before attacking
StartEvent();
if (Phase != 2)
AttackStart(who);
}
}
}
void CastShootOrMultishot()
{
switch (urand(0, 1))
{
case 0:
// Shoot
// Used in Phases 1 and 3 after Entangle or while having nobody in melee range. A shot that hits her target for 4097-5543 Physical damage.
DoCastVictim(SPELL_SHOOT);
break;
case 1:
// Multishot
// Used in Phases 1 and 3 after Entangle or while having nobody in melee range. A shot that hits 1 person and 4 people around him for 6475-7525 physical damage.
DoCastVictim(SPELL_MULTI_SHOT);
break;
}
if (rand32() % 3)
{
Talk(SAY_BOWSHOT);
}
}
void UpdateAI(uint32 diff) override
{
if (!CanAttack && Intro)
{
if (AggroTimer <= diff)
{
CanAttack = true;
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
AggroTimer=19000;
}
else
{
AggroTimer-=diff;
return;
}
}
// to prevent abuses during phase 2
if (Phase == 2 && !me->GetVictim() && me->IsInCombat())
{
EnterEvadeMode();
return;
}
// Return since we have no target
if (!UpdateVictim())
return;
if (Phase == 1 || Phase == 3)
{
// ShockBlastTimer
if (ShockBlastTimer <= diff)
{
// Shock Burst
// Randomly used in Phases 1 and 3 on Vashj's target, it's a Shock spell doing 8325-9675 nature damage and stunning the target for 5 seconds, during which she will not attack her target but switch to the next person on the aggro list.
DoCastVictim(SPELL_SHOCK_BLAST);
me->TauntApply(me->GetVictim());
ShockBlastTimer = 1000 + rand32() % 14000; // random cooldown
} else ShockBlastTimer -= diff;
// StaticChargeTimer
if (StaticChargeTimer <= diff)
{
// Static Charge
// Used on random people (only 1 person at any given time) in Phases 1 and 3, it's a debuff doing 2775 to 3225 Nature damage to the target and everybody in about 5 yards around it, every 1 seconds for 30 seconds. It can be removed by Cloak of Shadows, Iceblock, Divine Shield, etc, but not by Cleanse or Dispel Magic.
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 200, true);
if (target && !target->HasAura(SPELL_STATIC_CHARGE_TRIGGER))
DoCast(target, SPELL_STATIC_CHARGE_TRIGGER); // cast Static Charge every 2 seconds for 20 seconds
StaticChargeTimer = 10000 + rand32() % 20000;
} else StaticChargeTimer -= diff;
// EntangleTimer
if (EntangleTimer <= diff)
{
if (!Entangle)
{
// Entangle
// Used in Phases 1 and 3, it casts Entangling Roots on everybody in a 15 yard radius of Vashj, immobilzing them for 10 seconds and dealing 500 damage every 2 seconds. It's not a magic effect so it cannot be dispelled, but is removed by various buffs such as Cloak of Shadows or Blessing of Freedom.
DoCastVictim(SPELL_ENTANGLE);
Entangle = true;
EntangleTimer = 10000;
}
else
{
CastShootOrMultishot();
Entangle = false;
EntangleTimer = 20000 + rand32() % 5000;
}
} else EntangleTimer -= diff;
// Phase 1
if (Phase == 1)
{
// Start phase 2
if (HealthBelowPct(70))
{
// Phase 2 begins when Vashj hits 70%. She will run to the middle of her platform and surround herself in a shield making her invulerable.
Phase = 2;
me->GetMotionMaster()->Clear();
DoTeleportTo(MIDDLE_X, MIDDLE_Y, MIDDLE_Z);
for (uint8 i = 0; i < 4; ++i)
if (Creature* creature = me->SummonCreature(SHIED_GENERATOR_CHANNEL, ShieldGeneratorChannelPos[i][0], ShieldGeneratorChannelPos[i][1], ShieldGeneratorChannelPos[i][2], ShieldGeneratorChannelPos[i][3], TEMPSUMMON_CORPSE_DESPAWN, 0))
ShieldGeneratorChannel[i] = creature->GetGUID();
Talk(SAY_PHASE2);
}
}
// Phase 3
else
{
// SummonSporebatTimer
if (SummonSporebatTimer <= diff)
{
if (Creature* sporebat = me->SummonCreature(TOXIC_SPOREBAT, SPOREBAT_X, SPOREBAT_Y, SPOREBAT_Z, SPOREBAT_O, TEMPSUMMON_CORPSE_DESPAWN, 0))
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
sporebat->AI()->AttackStart(target);
// summon sporebats faster and faster
if (SummonSporebatStaticTimer > 1000)
SummonSporebatStaticTimer -= 1000;
SummonSporebatTimer = SummonSporebatStaticTimer;
if (SummonSporebatTimer < 5000)
SummonSporebatTimer = 5000;
} else SummonSporebatTimer -= diff;
}
// Melee attack
DoMeleeAttackIfReady();
// CheckTimer - used to check if somebody is in melee range
if (CheckTimer <= diff)
{
bool inMeleeRange = false;
std::list<HostileReference*> t_list = me->getThreatManager().getThreatList();
for (std::list<HostileReference*>::const_iterator itr = t_list.begin(); itr!= t_list.end(); ++itr)
{
Unit* target = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid());
if (target && target->IsWithinDistInMap(me, 5)) // if in melee range
{
inMeleeRange = true;
break;
}
}
// if nobody is in melee range
if (!inMeleeRange)
CastShootOrMultishot();
CheckTimer = 5000;
} else CheckTimer -= diff;
}
// Phase 2
else
{
// ForkedLightningTimer
if (ForkedLightningTimer <= diff)
{
// Forked Lightning
// Used constantly in Phase 2, it shoots out completely randomly targeted bolts of lightning which hit everybody in a roughtly 60 degree cone in front of Vashj for 2313-2687 nature damage.
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0);
if (!target)
target = me->GetVictim();
DoCast(target, SPELL_FORKED_LIGHTNING);
ForkedLightningTimer = 2000 + rand32() % 6000;
} else ForkedLightningTimer -= diff;
// EnchantedElementalTimer
if (EnchantedElementalTimer <= diff)
{
me->SummonCreature(ENCHANTED_ELEMENTAL, ElementPos[EnchantedElementalPos][0], ElementPos[EnchantedElementalPos][1], ElementPos[EnchantedElementalPos][2], ElementPos[EnchantedElementalPos][3], TEMPSUMMON_CORPSE_DESPAWN, 0);
if (EnchantedElementalPos == 7)
EnchantedElementalPos = 0;
else
++EnchantedElementalPos;
EnchantedElementalTimer = 10000 + rand32() % 5000;
} else EnchantedElementalTimer -= diff;
// TaintedElementalTimer
if (TaintedElementalTimer <= diff)
{
uint32 pos = rand32() % 8;
me->SummonCreature(TAINTED_ELEMENTAL, ElementPos[pos][0], ElementPos[pos][1], ElementPos[pos][2], ElementPos[pos][3], TEMPSUMMON_DEAD_DESPAWN, 0);
TaintedElementalTimer = 120000;
} else TaintedElementalTimer -= diff;
// CoilfangEliteTimer
if (CoilfangEliteTimer <= diff)
{
uint32 pos = rand32() % 3;
Creature* coilfangElite = me->SummonCreature(COILFANG_ELITE, CoilfangElitePos[pos][0], CoilfangElitePos[pos][1], CoilfangElitePos[pos][2], CoilfangElitePos[pos][3], TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000);
if (coilfangElite)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
coilfangElite->AI()->AttackStart(target);
else if (me->GetVictim())
coilfangElite->AI()->AttackStart(me->GetVictim());
}
CoilfangEliteTimer = 45000 + rand32() % 5000;
} else CoilfangEliteTimer -= diff;
// CoilfangStriderTimer
if (CoilfangStriderTimer <= diff)
{
uint32 pos = rand32() % 3;
if (Creature* CoilfangStrider = me->SummonCreature(COILFANG_STRIDER, CoilfangStriderPos[pos][0], CoilfangStriderPos[pos][1], CoilfangStriderPos[pos][2], CoilfangStriderPos[pos][3], TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000))
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
CoilfangStrider->AI()->AttackStart(target);
else if (me->GetVictim())
CoilfangStrider->AI()->AttackStart(me->GetVictim());
}
CoilfangStriderTimer = 60000 + rand32() % 10000;
} else CoilfangStriderTimer -= diff;
// CheckTimer
if (CheckTimer <= diff)
{
// Start Phase 3
if (instance->GetData(DATA_CANSTARTPHASE3))
{
// set life 50%
me->SetHealth(me->CountPctFromMaxHealth(50));
me->RemoveAurasDueToSpell(SPELL_MAGIC_BARRIER);
Talk(SAY_PHASE3);
Phase = 3;
// return to the tank
me->GetMotionMaster()->MoveChase(me->GetVictim());
}
CheckTimer = 1000;
} else CheckTimer -= diff;
}
}
};
};
// Enchanted Elemental
// If one of them reaches Vashj he will increase her damage done by 5%.
class npc_enchanted_elemental : public CreatureScript
{
public:
npc_enchanted_elemental() : CreatureScript("npc_enchanted_elemental") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_enchanted_elementalAI>(creature);
}
struct npc_enchanted_elementalAI : public ScriptedAI
{
npc_enchanted_elementalAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
instance = creature->GetInstanceScript();
}
void Initialize()
{
Move = 0;
Phase = 1;
X = ElementWPPos[0][0];
Y = ElementWPPos[0][1];
Z = ElementWPPos[0][2];
}
InstanceScript* instance;
uint32 Move;
uint32 Phase;
float X, Y, Z;
ObjectGuid VashjGUID;
void Reset() override
{
me->SetSpeedRate(MOVE_WALK, 0.6f); // walk
me->SetSpeedRate(MOVE_RUN, 0.6f); // run
Initialize();
//search for nearest waypoint (up on stairs)
for (uint32 i = 1; i < 8; ++i)
{
if (me->GetDistance(ElementWPPos[i][0], ElementWPPos[i][1], ElementWPPos[i][2]) < me->GetDistance(X, Y, Z))
{
X = ElementWPPos[i][0];
Y = ElementWPPos[i][1];
Z = ElementWPPos[i][2];
}
}
VashjGUID = instance->GetGuidData(DATA_LADYVASHJ);
}
void EnterCombat(Unit* /*who*/) override { }
void MoveInLineOfSight(Unit* /*who*/) override { }
void UpdateAI(uint32 diff) override
{
if (!VashjGUID)
return;
if (Move <= diff)
{
me->SetWalk(true);
if (Phase == 1)
me->GetMotionMaster()->MovePoint(0, X, Y, Z);
if (Phase == 1 && me->IsWithinDist3d(X, Y, Z, 0.1f))
Phase = 2;
if (Phase == 2)
{
me->GetMotionMaster()->MovePoint(0, MIDDLE_X, MIDDLE_Y, MIDDLE_Z);
Phase = 3;
}
if (Phase == 3)
{
me->GetMotionMaster()->MovePoint(0, MIDDLE_X, MIDDLE_Y, MIDDLE_Z);
if (me->IsWithinDist3d(MIDDLE_X, MIDDLE_Y, MIDDLE_Z, 3))
DoCast(me, SPELL_SURGE);
}
if (Creature* vashj = ObjectAccessor::GetCreature(*me, VashjGUID))
if (!vashj->IsInCombat() || ENSURE_AI(boss_lady_vashj::boss_lady_vashjAI, vashj->AI())->Phase != 2 || vashj->isDead())
me->KillSelf();
Move = 1000;
} else Move -= diff;
}
};
};
// Tainted Elemental
// This mob has 7, 900 life, doesn't move, and shoots Poison Bolts at one person anywhere in the area, doing 3, 000 nature damage and placing a posion doing 2, 000 damage every 2 seconds. He will switch targets often, or sometimes just hang on a single player, but there is nothing you can do about it except heal the damage and kill the Tainted Elemental
class npc_tainted_elemental : public CreatureScript
{
public:
npc_tainted_elemental() : CreatureScript("npc_tainted_elemental") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_tainted_elementalAI>(creature);
}
struct npc_tainted_elementalAI : public ScriptedAI
{
npc_tainted_elementalAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
instance = creature->GetInstanceScript();
}
void Initialize()
{
PoisonBoltTimer = 5000 + rand32() % 5000;
DespawnTimer = 30000;
}
InstanceScript* instance;
uint32 PoisonBoltTimer;
uint32 DespawnTimer;
void Reset() override
{
Initialize();
}
void JustDied(Unit* /*killer*/) override
{
if (Creature* vashj = ObjectAccessor::GetCreature((*me), instance->GetGuidData(DATA_LADYVASHJ)))
ENSURE_AI(boss_lady_vashj::boss_lady_vashjAI, vashj->AI())->EventTaintedElementalDeath();
}
void EnterCombat(Unit* who) override
{
me->AddThreat(who, 0.1f);
}
void UpdateAI(uint32 diff) override
{
// PoisonBoltTimer
if (PoisonBoltTimer <= diff)
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0);
if (target && target->IsWithinDistInMap(me, 30))
DoCast(target, SPELL_POISON_BOLT);
PoisonBoltTimer = 5000 + rand32() % 5000;
} else PoisonBoltTimer -= diff;
// DespawnTimer
if (DespawnTimer <= diff)
{
// call Unsummon()
me->setDeathState(DEAD);
// to prevent crashes
DespawnTimer = 1000;
} else DespawnTimer -= diff;
}
};
};
//Toxic Sporebat
//Toxic Spores: Used in Phase 3 by the Spore Bats, it creates a contaminated green patch of ground, dealing about 2775-3225 nature damage every second to anyone who stands in it.
class npc_toxic_sporebat : public CreatureScript
{
public:
npc_toxic_sporebat() : CreatureScript("npc_toxic_sporebat") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_toxic_sporebatAI>(creature);
}
struct npc_toxic_sporebatAI : public ScriptedAI
{
npc_toxic_sporebatAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
instance = creature->GetInstanceScript();
EnterEvadeMode();
}
void Initialize()
{
MovementTimer = 0;
ToxicSporeTimer = 5000;
BoltTimer = 5500;
CheckTimer = 1000;
}
InstanceScript* instance;
uint32 MovementTimer;
uint32 ToxicSporeTimer;
uint32 BoltTimer;
uint32 CheckTimer;
void Reset() override
{
me->SetDisableGravity(true);
me->setFaction(14);
Initialize();
}
void MoveInLineOfSight(Unit* /*who*/) override
{
}
void MovementInform(uint32 type, uint32 id) override
{
if (type != POINT_MOTION_TYPE)
return;
if (id == 1)
MovementTimer = 0;
}
void UpdateAI(uint32 diff) override
{
// Random movement
if (MovementTimer <= diff)
{
uint32 rndpos = rand32() % 8;
me->GetMotionMaster()->MovePoint(1, SporebatWPPos[rndpos][0], SporebatWPPos[rndpos][1], SporebatWPPos[rndpos][2]);
MovementTimer = 6000;
} else MovementTimer -= diff;
// toxic spores
if (BoltTimer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
{
if (Creature* trig = me->SummonCreature(TOXIC_SPORES_TRIGGER, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 30000))
{
trig->setFaction(14);
trig->CastSpell(trig, SPELL_TOXIC_SPORES, true);
}
}
BoltTimer = 10000 + rand32() % 5000;
}
else BoltTimer -= diff;
// CheckTimer
if (CheckTimer <= diff)
{
// check if vashj is death
Unit* Vashj = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_LADYVASHJ));
if (!Vashj || !Vashj->IsAlive() || ENSURE_AI(boss_lady_vashj::boss_lady_vashjAI, Vashj->ToCreature()->AI())->Phase != 3)
{
// remove
me->setDeathState(DEAD);
me->RemoveCorpse();
me->setFaction(35);
}
CheckTimer = 1000;
}
else
CheckTimer -= diff;
}
};
};
class npc_shield_generator_channel : public CreatureScript
{
public:
npc_shield_generator_channel() : CreatureScript("npc_shield_generator_channel") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_shield_generator_channelAI>(creature);
}
struct npc_shield_generator_channelAI : public ScriptedAI
{
npc_shield_generator_channelAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
instance = creature->GetInstanceScript();
}
void Initialize()
{
CheckTimer = 0;
Cast = false;
}
InstanceScript* instance;
uint32 CheckTimer;
bool Cast;
void Reset() override
{
Initialize();
me->SetDisplayId(11686); // invisible
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
void MoveInLineOfSight(Unit* /*who*/) override { }
void UpdateAI(uint32 diff) override
{
if (CheckTimer <= diff)
{
Unit* vashj = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_LADYVASHJ));
if (vashj && vashj->IsAlive())
{
// start visual channel
if (!Cast || !vashj->HasAura(SPELL_MAGIC_BARRIER))
{
DoCast(vashj, SPELL_MAGIC_BARRIER, true);
Cast = true;
}
}
CheckTimer = 1000;
} else CheckTimer -= diff;
}
};
};
class item_tainted_core : public ItemScript
{
public:
item_tainted_core() : ItemScript("item_tainted_core") { }
bool OnUse(Player* player, Item* /*item*/, SpellCastTargets const& targets, ObjectGuid /*castId*/) override
{
InstanceScript* instance = player->GetInstanceScript();
if (!instance)
{
player->GetSession()->SendNotification(TEXT_NOT_INITIALIZED);
return true;
}
Creature* vashj = ObjectAccessor::GetCreature((*player), instance->GetGuidData(DATA_LADYVASHJ));
if (vashj && (ENSURE_AI(boss_lady_vashj::boss_lady_vashjAI, vashj->AI())->Phase == 2))
{
if (GameObject* gObj = targets.GetGOTarget())
{
uint32 identifier;
uint8 channelIdentifier;
switch (gObj->GetEntry())
{
case 185052:
identifier = DATA_SHIELDGENERATOR1;
channelIdentifier = 0;
break;
case 185053:
identifier = DATA_SHIELDGENERATOR2;
channelIdentifier = 1;
break;
case 185051:
identifier = DATA_SHIELDGENERATOR3;
channelIdentifier = 2;
break;
case 185054:
identifier = DATA_SHIELDGENERATOR4;
channelIdentifier = 3;
break;
default:
return true;
}
if (instance->GetData(identifier))
{
player->GetSession()->SendNotification(TEXT_ALREADY_DEACTIVATED);
return true;
}
// get and remove channel
if (Unit* channel = ObjectAccessor::GetCreature(*vashj, ENSURE_AI(boss_lady_vashj::boss_lady_vashjAI, vashj->AI())->ShieldGeneratorChannel[channelIdentifier]))
channel->setDeathState(JUST_DIED); // call Unsummon()
instance->SetData(identifier, 1);
// remove this item
player->DestroyItemCount(31088, 1, true);
return true;
}
else if (targets.GetUnitTarget()->GetTypeId() == TYPEID_UNIT)
return false;
else if (targets.GetUnitTarget()->GetTypeId() == TYPEID_PLAYER)
{
player->DestroyItemCount(31088, 1, true);
player->CastSpell(targets.GetUnitTarget(), 38134, true);
return true;
}
}
return true;
}
};
void AddSC_boss_lady_vashj()
{
new boss_lady_vashj();
new npc_enchanted_elemental();
new npc_tainted_elemental();
new npc_toxic_sporebat();
new npc_shield_generator_channel();
new item_tainted_core();
}
| 411 | 0.979293 | 1 | 0.979293 | game-dev | MEDIA | 0.986473 | game-dev | 0.9004 | 1 | 0.9004 |
Hendrix-Shen/MagicLib | 10,522 | magiclib-wrapper/fabric/build.gradle | import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
plugins {
id("java")
id("maven-publish")
id("signing")
}
allprojects {
apply(plugin: "java")
apply(plugin: "maven-publish")
apply(plugin: "signing")
}
Project coreProject = evaluationDependsOn(":magiclib-core:${project.name}")
jar {
outputs.upToDateWhen { false }
dependsOn(coreProject.tasks.shadowJar)
dependsOn("copyPublishModule")
}
tasks.register("copyPublishModule", Copy.class) { Copy copyTask ->
copyTask.setGroup("${project.property("mod.id")}")
from {
coreProject.tasks.shadowJar.outputs.files
}
into(project.layout.buildDirectory.file("tmp/submods/publish"))
}
tasks.withType(AbstractPublishToMaven).configureEach {
enabled = false
}
tasks.withType(ProcessResources).configureEach {
enabled = false
}
subprojects {
Map<String, Map<String, ?>> settings = rootProject.file("settings.json").withReader {
new JsonSlurper().parse(it) as Map<String, Map<String, ?>>
}
Set<Project> submodules = new HashSet<>()
for (String module_name : settings.get("projects").keySet()) {
Map<String, ?> project_detail = settings.get("projects").get(module_name) as Map<String, ?>
String prefix = project_detail.get("prefix")
List<String> versions = project_detail.get("versions") as List<String>
versions.findAll { it == "${project.name}-${project.parent.name}" }
.collect { project(":${module_name}:${prefix}-${it}") }
.forEach { submodules.add(it) }
}
Set<Project> submodules_publish = submodules.findAll { !it.name.contains("better-dev") }
Set<Project> submodules_unpublish = submodules.findAll { !(it in submodules_publish) }
base {
setArchivesName("${project.parent.property("mod.archives_base_name")}-mc${project.name}-${project.parent.name}")
setGroup("${project.parent.property("mod.maven_group")}")
setVersion(project.getModVersion(rootProject))
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
withSourcesJar()
withJavadocJar()
}
jar {
outputs.upToDateWhen { false }
dependsOn(project.parent.tasks.jar)
dependsOn("copyPublishModule")
dependsOn("copyUnpublishModule")
dependsOn("processMetadata")
from(project.layout.buildDirectory.file("tmp/submods/publish")) {
into("META-INF/jars")
}
from(project.parent.layout.buildDirectory.file("tmp/submods/publish")) {
into("META-INF/jars")
}
}
processResources {
dependsOn(coreProject.tasks.processResources)
outputs.upToDateWhen { false }
inputs.property("mod_description", project.property("mod.description"))
inputs.property("mod_homepage" , project.property("mod.homepage"))
inputs.property("mod_id" , project.property("mod.id"))
inputs.property("mod_license" , project.property("mod.license"))
inputs.property("mod_name" , project.property("mod.name"))
inputs.property("mod_sources" , project.property("mod.sources"))
inputs.property("mod_version" , project.getVersionWithCommitHash(rootProject))
from(project.parent.sourceSets.main.resources.srcDirs) {
include("fabric.mod.json")
expand([
"mod_description": inputs.properties.get("mod_description"),
"mod_homepage" : inputs.properties.get("mod_homepage"),
"mod_id" : inputs.properties.get("mod_id"),
"mod_license" : inputs.properties.get("mod_license"),
"mod_name" : inputs.properties.get("mod_name"),
"mod_sources" : inputs.properties.get("mod_sources"),
"mod_version" : inputs.properties.get("mod_version")
])
}
from("${rootDir}/LICENSE")
from("${rootDir}/icon.png") {
into("assets/${project.property("mod.id")}")
}
}
signing {
String signingKey = project.getOrDefault("secrets.gpg.signingKey", project.getEnv().SIGNING_PGP_KEY)
String signingPassword = project.getOrDefault("secrets.gpg.signingPassword", project.getEnv().SIGNING_PGP_PASSWORD)
required = signingKey
useInMemoryPgpKeys(signingKey, signingPassword ? signingPassword : "")
sign(publishing.publications)
}
publishing {
publications { PublicationContainer publications ->
register("release", MavenPublication) { MavenPublication publication ->
artifactId = "${project.parent.property("mod.artifact_name")}-${project.name}-${project.parent.name}"
artifact(jar)
artifact(javadocJar)
artifact(sourcesJar)
version = "${this.project.getMavenArtifactVersion(rootProject)}"
this.project.addPomMetadataInformation(this.project, publication)
pom.withXml { XmlProvider provider ->
Node dependencies = provider.asNode().appendNode("dependencies")
Node core_dependency = dependencies.appendNode("dependency")
core_dependency.appendNode("groupId", coreProject.group)
core_dependency.appendNode("artifactId", "${coreProject.parent.property("mod.artifact_name")}-${coreProject.name}")
core_dependency.appendNode("version", "${this.project.getMavenArtifactVersion(coreProject.parent)}")
core_dependency.appendNode("scope", "compile")
submodules
.findAll { !it.name.contains("legacy") }
.forEach { Project submodule ->
Node dependency = dependencies.appendNode("dependency")
dependency.appendNode("groupId", submodule.group)
dependency.appendNode("artifactId", "${submodule.parent.property("mod.artifact_name")}-${submodule.name.replace("${(settings.get("projects").get(submodule.parent.name) as Map<String, ?>).get("prefix")}-", "")}")
dependency.appendNode("version", "${this.project.getMavenArtifactVersion(submodule.parent)}")
dependency.appendNode("scope", "compile")
}
}
}
}
repositories { RepositoryHandler repositoryHandler ->
mavenLocal {
name = "mavenLocal"
}
maven {
name = "projectLocalRelease"
url = "${rootDir}/publish/release"
}
maven {
name = "nyanMavenRelease"
url = "https://maven.hendrixshen.top/releases"
project.credentialsNyanMaven(it)
}
}
}
// Solutions from: https://youtrack.jetbrains.com/issue/KT-46466
TaskCollection<Sign> signingTasks = tasks.withType(Sign)
tasks.withType(AbstractPublishToMaven).configureEach {
dependsOn(signingTasks)
}
tasks.withType(PublishToMavenRepository).configureEach {
Provider<Boolean> predicate = provider {
repository == publishing.repositories.mavenLocal ||
(repository == publishing.repositories.projectLocalRelease && publication == publishing.publications.release) ||
(repository == publishing.repositories.nyanMavenRelease && publication == publishing.publications.release && project.isNyanMavenCredentialsExist())
}
onlyIf {
predicate.get()
}
}
tasks.register("copyPublishModule", Copy.class) { Copy copyTask ->
copyTask.dependsOn(submodules.collect { it.tasks.remapJar })
copyTask.setGroup("${project.property("mod.id")}")
from {
submodules_publish.collect {
it.tasks.remapJar.outputs.files
}
}
into(project.layout.buildDirectory.file("tmp/submods/publish"))
}
tasks.register("copyUnpublishModule", Copy.class) { Copy copyTask ->
copyTask.dependsOn(submodules.collect { it.tasks.remapJar })
copyTask.setGroup("${project.property("mod.id")}")
from {
submodules_unpublish.collect {
it.tasks.remapJar.outputs.files
}
}
into(project.layout.buildDirectory.file("tmp/submods/unpublish"))
}
tasks.register("processMetadata", ProcessMetadata.class) { ProcessMetadata processTask ->
processTask.dependsOn(tasks.processResources)
processTask.setGroup("${project.property("mod.id")}")
processTask.fabricMetadataFile.set(file(project.layout.buildDirectory.file("resources/main/fabric.mod.json")))
processTask.coreProject.set(coreProject)
processTask.subProjects.set(submodules_publish)
}
}
abstract class ProcessMetadata extends DefaultTask {
@Input
abstract Property<File> getFabricMetadataFile();
@Input
abstract Property<Project> getCoreProject();
@Input
abstract SetProperty<Project> getSubProjects();
@TaskAction
void runTask() {
try {
this.runTaskImpl();
} catch (Exception e) {
this.getLogger().error("Failed to execute ProcessMetadata task.", e);
throw e;
}
}
private void runTaskImpl() {
Set<String> mc_condition = []
Set<Map<String, String>> jars = [["file": "META-INF/jars/${this.coreProject.get().parent.property("mod.archives_base_name")}-fabric-${this.coreProject.get().version}.jar"]]
this.subProjects.get().forEach {
mc_condition.add("${it.property("dependencies.minecraft_dependency")}")
jars.add(["file": "META-INF/jars/${it.parent.property("mod.archives_base_name")}-mc${it.property("dependencies.minecraft_version")}-${it.loom.platform.get().toString().toLowerCase()}-${it.version}.jar"])
}
File file = this.fabricMetadataFile.get()
JsonSlurper slurper = new JsonSlurper()
JsonBuilder builder = new JsonBuilder(slurper.parse(file))
builder.content.depends.minecraft = mc_condition
builder.content.jars = jars
file.withWriter {
it.append(builder.toPrettyString())
}
}
}
| 411 | 0.929113 | 1 | 0.929113 | game-dev | MEDIA | 0.283917 | game-dev | 0.820128 | 1 | 0.820128 |
followingthefasciaplane/source-engine-diff-check | 5,914 | misc/game/shared/simtimer.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef SIMTIMER_H
#define SIMTIMER_H
#if defined( _WIN32 )
#pragma once
#endif
#define ST_EPS 0.001
#define DEFINE_SIMTIMER( type, name ) DEFINE_EMBEDDED( type, name )
//-----------------------------------------------------------------------------
class CSimpleSimTimer
{
public:
CSimpleSimTimer()
: m_next( -1 )
{
}
void Force()
{
m_next = -1;
}
bool Expired() const
{
return ( gpGlobals->curtime - m_next > -ST_EPS );
}
float Delay( float delayTime )
{
return (m_next += delayTime);
}
float GetNext() const
{
return m_next;
}
void Set( float interval )
{
m_next = gpGlobals->curtime + interval;
}
void Set( float minInterval, float maxInterval )
{
if ( maxInterval > 0.0 )
m_next = gpGlobals->curtime + random->RandomFloat( minInterval, maxInterval );
else
m_next = gpGlobals->curtime + minInterval;
}
float GetRemaining() const
{
float result = m_next - gpGlobals->curtime;
if (result < 0 )
return 0;
return result;
}
DECLARE_SIMPLE_DATADESC();
protected:
float m_next;
};
//-----------------------------------------------------------------------------
class CSimTimer : public CSimpleSimTimer
{
public:
CSimTimer( float interval = 0.0, bool startExpired = true )
{
Set( interval, startExpired );
}
void Set( float interval, bool startExpired = true )
{
m_interval = interval;
m_next = (startExpired) ? -1.0 : gpGlobals->curtime + m_interval;
}
void Reset( float interval = -1.0 )
{
if ( interval == -1.0 )
{
m_next = gpGlobals->curtime + m_interval;
}
else
{
m_next = gpGlobals->curtime + interval;
}
}
float GetInterval() const
{
return m_interval;
}
DECLARE_SIMPLE_DATADESC();
private:
float m_interval;
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
class CRandSimTimer : public CSimpleSimTimer
{
public:
CRandSimTimer( float minInterval = 0.0, float maxInterval = 0.0, bool startExpired = true )
{
Set( minInterval, maxInterval, startExpired );
}
void Set( float minInterval, float maxInterval = 0.0, bool startExpired = true )
{
m_minInterval = minInterval;
m_maxInterval = maxInterval;
if (startExpired)
{
m_next = -1;
}
else
{
if ( m_maxInterval == 0 )
m_next = gpGlobals->curtime + m_minInterval;
else
m_next = gpGlobals->curtime + random->RandomFloat( m_minInterval, m_maxInterval );
}
}
void Reset()
{
if ( m_maxInterval == 0 )
m_next = gpGlobals->curtime + m_minInterval;
else
m_next = gpGlobals->curtime + random->RandomFloat( m_minInterval, m_maxInterval );
}
float GetMinInterval() const
{
return m_minInterval;
}
float GetMaxInterval() const
{
return m_maxInterval;
}
DECLARE_SIMPLE_DATADESC();
private:
float m_minInterval;
float m_maxInterval;
};
//-----------------------------------------------------------------------------
class CStopwatchBase : public CSimpleSimTimer
{
public:
CStopwatchBase()
{
m_fIsRunning = false;
}
bool IsRunning() const
{
return m_fIsRunning;
}
void Stop()
{
m_fIsRunning = false;
}
bool Expired() const
{
return ( m_fIsRunning && CSimpleSimTimer::Expired() );
}
DECLARE_SIMPLE_DATADESC();
protected:
bool m_fIsRunning;
};
//-------------------------------------
class CSimpleStopwatch : public CStopwatchBase
{
public:
void Start( float minCountdown, float maxCountdown = 0.0 )
{
m_fIsRunning = true;
CSimpleSimTimer::Set( minCountdown, maxCountdown );
}
void Stop()
{
m_fIsRunning = false;
}
bool Expired() const
{
return ( m_fIsRunning && CSimpleSimTimer::Expired() );
}
};
//-------------------------------------
class CStopwatch : public CStopwatchBase
{
public:
CStopwatch ( float interval = 0.0 )
{
Set( interval );
}
void Set( float interval )
{
m_interval = interval;
}
void Start( float intervalOverride )
{
m_fIsRunning = true;
m_next = gpGlobals->curtime + intervalOverride;
}
void Start()
{
Start( m_interval );
}
float GetInterval() const
{
return m_interval;
}
DECLARE_SIMPLE_DATADESC();
private:
float m_interval;
};
//-------------------------------------
class CRandStopwatch : public CStopwatchBase
{
public:
CRandStopwatch( float minInterval = 0.0, float maxInterval = 0.0 )
{
Set( minInterval, maxInterval );
}
void Set( float minInterval, float maxInterval = 0.0 )
{
m_minInterval = minInterval;
m_maxInterval = maxInterval;
}
void Start( float minOverride, float maxOverride = 0.0 )
{
m_fIsRunning = true;
if ( maxOverride == 0 )
m_next = gpGlobals->curtime + minOverride;
else
m_next = gpGlobals->curtime + random->RandomFloat( minOverride, maxOverride );
}
void Start()
{
Start( m_minInterval, m_maxInterval );
}
float GetInterval() const
{
return m_minInterval;
}
float GetMinInterval() const
{
return m_minInterval;
}
float GetMaxInterval() const
{
return m_maxInterval;
}
DECLARE_SIMPLE_DATADESC();
private:
float m_minInterval;
float m_maxInterval;
};
//-----------------------------------------------------------------------------
class CThinkOnceSemaphore
{
public:
CThinkOnceSemaphore()
: m_lastTime( -1 )
{
}
bool EnterThink()
{
if ( m_lastTime == gpGlobals->curtime )
return false;
m_lastTime = gpGlobals->curtime;
return true;
}
bool DidThink() const
{
return ( gpGlobals->curtime == m_lastTime );
}
void SetDidThink()
{
m_lastTime = gpGlobals->curtime;
}
private:
float m_lastTime;
};
//-----------------------------------------------------------------------------
#endif // SIMTIMER_H
| 411 | 0.948444 | 1 | 0.948444 | game-dev | MEDIA | 0.829039 | game-dev | 0.972482 | 1 | 0.972482 |
gameplay3d/gameplay | 36,328 | gameplay/src/lua/lua_Terrain.cpp | // Autogenerated by gameplay-luagen
#include "Base.h"
#include "ScriptController.h"
#include "lua_Terrain.h"
#include "Animation.h"
#include "AnimationTarget.h"
#include "Base.h"
#include "Drawable.h"
#include "FileSystem.h"
#include "Game.h"
#include "MaterialParameter.h"
#include "Node.h"
#include "Ref.h"
#include "ScriptController.h"
#include "ScriptTarget.h"
#include "Terrain.h"
#include "TerrainPatch.h"
#include "Transform.h"
#include "Drawable.h"
#include "Ref.h"
#include "Transform.h"
namespace gameplay
{
extern void luaGlobal_Register_Conversion_Function(const char* className, void*(*func)(void*, const char*));
static Terrain* getInstance(lua_State* state)
{
void* userdata = luaL_checkudata(state, 1, "Terrain");
luaL_argcheck(state, userdata != NULL, 1, "'Terrain' expected.");
return (Terrain*)((gameplay::ScriptUtil::LuaObject*)userdata)->instance;
}
static int lua_Terrain__gc(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
void* userdata = luaL_checkudata(state, 1, "Terrain");
luaL_argcheck(state, userdata != NULL, 1, "'Terrain' expected.");
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)userdata;
if (object->owns)
{
Terrain* instance = (Terrain*)object->instance;
SAFE_RELEASE(instance);
}
return 0;
}
lua_pushstring(state, "lua_Terrain__gc - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Terrain_addRef(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
Terrain* instance = getInstance(state);
instance->addRef();
return 0;
}
lua_pushstring(state, "lua_Terrain_addRef - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Terrain_draw(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
Terrain* instance = getInstance(state);
unsigned int result = instance->draw();
// Push the return value onto the stack.
lua_pushunsigned(state, result);
return 1;
}
lua_pushstring(state, "lua_Terrain_draw - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TBOOLEAN)
{
// Get parameter 1 off the stack.
bool param1 = gameplay::ScriptUtil::luaCheckBool(state, 2);
Terrain* instance = getInstance(state);
unsigned int result = instance->draw(param1);
// Push the return value onto the stack.
lua_pushunsigned(state, result);
return 1;
}
lua_pushstring(state, "lua_Terrain_draw - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Terrain_getBoundingBox(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
Terrain* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getBoundingBox());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "BoundingBox");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_Terrain_getBoundingBox - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Terrain_getHeight(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
// Get parameter 2 off the stack.
float param2 = (float)luaL_checknumber(state, 3);
Terrain* instance = getInstance(state);
float result = instance->getHeight(param1, param2);
// Push the return value onto the stack.
lua_pushnumber(state, result);
return 1;
}
lua_pushstring(state, "lua_Terrain_getHeight - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Terrain_getNode(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
Terrain* instance = getInstance(state);
void* returnPtr = ((void*)instance->getNode());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Node");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_Terrain_getNode - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Terrain_getPatch(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
unsigned int param1 = (unsigned int)luaL_checkunsigned(state, 2);
Terrain* instance = getInstance(state);
void* returnPtr = ((void*)instance->getPatch(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "TerrainPatch");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_Terrain_getPatch - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Terrain_getPatchCount(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
Terrain* instance = getInstance(state);
unsigned int result = instance->getPatchCount();
// Push the return value onto the stack.
lua_pushunsigned(state, result);
return 1;
}
lua_pushstring(state, "lua_Terrain_getPatchCount - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Terrain_getRefCount(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
Terrain* instance = getInstance(state);
unsigned int result = instance->getRefCount();
// Push the return value onto the stack.
lua_pushunsigned(state, result);
return 1;
}
lua_pushstring(state, "lua_Terrain_getRefCount - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Terrain_isFlagSet(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Terrain::Flags param1 = (Terrain::Flags)luaL_checkint(state, 2);
Terrain* instance = getInstance(state);
bool result = instance->isFlagSet(param1);
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_Terrain_isFlagSet - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Terrain_release(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
Terrain* instance = getInstance(state);
instance->release();
return 0;
}
lua_pushstring(state, "lua_Terrain_release - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Terrain_setFlag(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TBOOLEAN)
{
// Get parameter 1 off the stack.
Terrain::Flags param1 = (Terrain::Flags)luaL_checkint(state, 2);
// Get parameter 2 off the stack.
bool param2 = gameplay::ScriptUtil::luaCheckBool(state, 3);
Terrain* instance = getInstance(state);
instance->setFlag(param1, param2);
return 0;
}
lua_pushstring(state, "lua_Terrain_setFlag - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Terrain_static_create(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
do
{
if ((lua_type(state, 1) == LUA_TSTRING || lua_type(state, 1) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(1, false);
void* returnPtr = ((void*)Terrain::create(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = true;
luaL_getmetatable(state, "Terrain");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
} while (0);
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TTABLE || lua_type(state, 1) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Properties> param1 = gameplay::ScriptUtil::getObjectPointer<Properties>(1, "Properties", false, ¶m1Valid);
if (!param1Valid)
break;
void* returnPtr = ((void*)Terrain::create(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = true;
luaL_getmetatable(state, "Terrain");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
} while (0);
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TTABLE || lua_type(state, 1) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<HeightField> param1 = gameplay::ScriptUtil::getObjectPointer<HeightField>(1, "HeightField", false, ¶m1Valid);
if (!param1Valid)
break;
void* returnPtr = ((void*)Terrain::create(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = true;
luaL_getmetatable(state, "Terrain");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
} while (0);
lua_pushstring(state, "lua_Terrain_static_create - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TTABLE || lua_type(state, 1) == LUA_TNIL) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<HeightField> param1 = gameplay::ScriptUtil::getObjectPointer<HeightField>(1, "HeightField", false, ¶m1Valid);
if (!param1Valid)
break;
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<Vector3> param2 = gameplay::ScriptUtil::getObjectPointer<Vector3>(2, "Vector3", true, ¶m2Valid);
if (!param2Valid)
break;
void* returnPtr = ((void*)Terrain::create(param1, *param2));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = true;
luaL_getmetatable(state, "Terrain");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
} while (0);
lua_pushstring(state, "lua_Terrain_static_create - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 3:
{
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TTABLE || lua_type(state, 1) == LUA_TNIL) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<HeightField> param1 = gameplay::ScriptUtil::getObjectPointer<HeightField>(1, "HeightField", false, ¶m1Valid);
if (!param1Valid)
break;
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<Vector3> param2 = gameplay::ScriptUtil::getObjectPointer<Vector3>(2, "Vector3", true, ¶m2Valid);
if (!param2Valid)
break;
// Get parameter 3 off the stack.
unsigned int param3 = (unsigned int)luaL_checkunsigned(state, 3);
void* returnPtr = ((void*)Terrain::create(param1, *param2, param3));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = true;
luaL_getmetatable(state, "Terrain");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
} while (0);
lua_pushstring(state, "lua_Terrain_static_create - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 4:
{
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TTABLE || lua_type(state, 1) == LUA_TNIL) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER &&
lua_type(state, 4) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<HeightField> param1 = gameplay::ScriptUtil::getObjectPointer<HeightField>(1, "HeightField", false, ¶m1Valid);
if (!param1Valid)
break;
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<Vector3> param2 = gameplay::ScriptUtil::getObjectPointer<Vector3>(2, "Vector3", true, ¶m2Valid);
if (!param2Valid)
break;
// Get parameter 3 off the stack.
unsigned int param3 = (unsigned int)luaL_checkunsigned(state, 3);
// Get parameter 4 off the stack.
unsigned int param4 = (unsigned int)luaL_checkunsigned(state, 4);
void* returnPtr = ((void*)Terrain::create(param1, *param2, param3, param4));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = true;
luaL_getmetatable(state, "Terrain");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
} while (0);
lua_pushstring(state, "lua_Terrain_static_create - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 5:
{
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TTABLE || lua_type(state, 1) == LUA_TNIL) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER &&
lua_type(state, 4) == LUA_TNUMBER &&
lua_type(state, 5) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<HeightField> param1 = gameplay::ScriptUtil::getObjectPointer<HeightField>(1, "HeightField", false, ¶m1Valid);
if (!param1Valid)
break;
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<Vector3> param2 = gameplay::ScriptUtil::getObjectPointer<Vector3>(2, "Vector3", true, ¶m2Valid);
if (!param2Valid)
break;
// Get parameter 3 off the stack.
unsigned int param3 = (unsigned int)luaL_checkunsigned(state, 3);
// Get parameter 4 off the stack.
unsigned int param4 = (unsigned int)luaL_checkunsigned(state, 4);
// Get parameter 5 off the stack.
float param5 = (float)luaL_checknumber(state, 5);
void* returnPtr = ((void*)Terrain::create(param1, *param2, param3, param4, param5));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = true;
luaL_getmetatable(state, "Terrain");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
} while (0);
lua_pushstring(state, "lua_Terrain_static_create - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 6:
{
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TTABLE || lua_type(state, 1) == LUA_TNIL) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER &&
lua_type(state, 4) == LUA_TNUMBER &&
lua_type(state, 5) == LUA_TNUMBER &&
(lua_type(state, 6) == LUA_TSTRING || lua_type(state, 6) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<HeightField> param1 = gameplay::ScriptUtil::getObjectPointer<HeightField>(1, "HeightField", false, ¶m1Valid);
if (!param1Valid)
break;
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<Vector3> param2 = gameplay::ScriptUtil::getObjectPointer<Vector3>(2, "Vector3", true, ¶m2Valid);
if (!param2Valid)
break;
// Get parameter 3 off the stack.
unsigned int param3 = (unsigned int)luaL_checkunsigned(state, 3);
// Get parameter 4 off the stack.
unsigned int param4 = (unsigned int)luaL_checkunsigned(state, 4);
// Get parameter 5 off the stack.
float param5 = (float)luaL_checknumber(state, 5);
// Get parameter 6 off the stack.
const char* param6 = gameplay::ScriptUtil::getString(6, false);
void* returnPtr = ((void*)Terrain::create(param1, *param2, param3, param4, param5, param6));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = true;
luaL_getmetatable(state, "Terrain");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
} while (0);
lua_pushstring(state, "lua_Terrain_static_create - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 7:
{
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TTABLE || lua_type(state, 1) == LUA_TNIL) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER &&
lua_type(state, 4) == LUA_TNUMBER &&
lua_type(state, 5) == LUA_TNUMBER &&
(lua_type(state, 6) == LUA_TSTRING || lua_type(state, 6) == LUA_TNIL) &&
(lua_type(state, 7) == LUA_TSTRING || lua_type(state, 7) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<HeightField> param1 = gameplay::ScriptUtil::getObjectPointer<HeightField>(1, "HeightField", false, ¶m1Valid);
if (!param1Valid)
break;
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<Vector3> param2 = gameplay::ScriptUtil::getObjectPointer<Vector3>(2, "Vector3", true, ¶m2Valid);
if (!param2Valid)
break;
// Get parameter 3 off the stack.
unsigned int param3 = (unsigned int)luaL_checkunsigned(state, 3);
// Get parameter 4 off the stack.
unsigned int param4 = (unsigned int)luaL_checkunsigned(state, 4);
// Get parameter 5 off the stack.
float param5 = (float)luaL_checknumber(state, 5);
// Get parameter 6 off the stack.
const char* param6 = gameplay::ScriptUtil::getString(6, false);
// Get parameter 7 off the stack.
const char* param7 = gameplay::ScriptUtil::getString(7, false);
void* returnPtr = ((void*)Terrain::create(param1, *param2, param3, param4, param5, param6, param7));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = true;
luaL_getmetatable(state, "Terrain");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
} while (0);
lua_pushstring(state, "lua_Terrain_static_create - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1, 2, 3, 4, 5, 6 or 7).");
lua_error(state);
break;
}
}
return 0;
}
// Provides support for conversion to all known relative types of Terrain
static void* __convertTo(void* ptr, const char* typeName)
{
Terrain* ptrObject = reinterpret_cast<Terrain*>(ptr);
if (strcmp(typeName, "Drawable") == 0)
{
return reinterpret_cast<void*>(static_cast<Drawable*>(ptrObject));
}
else if (strcmp(typeName, "Ref") == 0)
{
return reinterpret_cast<void*>(static_cast<Ref*>(ptrObject));
}
else if (strcmp(typeName, "Transform::Listener") == 0)
{
return reinterpret_cast<void*>(static_cast<Transform::Listener*>(ptrObject));
}
// No conversion available for 'typeName'
return NULL;
}
static int lua_Terrain_to(lua_State* state)
{
// There should be only a single parameter (this instance)
if (lua_gettop(state) != 2 || lua_type(state, 1) != LUA_TUSERDATA || lua_type(state, 2) != LUA_TSTRING)
{
lua_pushstring(state, "lua_Terrain_to - Invalid number of parameters (expected 2).");
lua_error(state);
return 0;
}
Terrain* instance = getInstance(state);
const char* typeName = gameplay::ScriptUtil::getString(2, false);
void* result = __convertTo((void*)instance, typeName);
if (result)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = (void*)result;
object->owns = false;
luaL_getmetatable(state, typeName);
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
void luaRegister_Terrain()
{
const luaL_Reg lua_members[] =
{
{"addRef", lua_Terrain_addRef},
{"draw", lua_Terrain_draw},
{"getBoundingBox", lua_Terrain_getBoundingBox},
{"getHeight", lua_Terrain_getHeight},
{"getNode", lua_Terrain_getNode},
{"getPatch", lua_Terrain_getPatch},
{"getPatchCount", lua_Terrain_getPatchCount},
{"getRefCount", lua_Terrain_getRefCount},
{"isFlagSet", lua_Terrain_isFlagSet},
{"release", lua_Terrain_release},
{"setFlag", lua_Terrain_setFlag},
{"to", lua_Terrain_to},
{NULL, NULL}
};
const luaL_Reg lua_statics[] =
{
{"create", lua_Terrain_static_create},
{NULL, NULL}
};
std::vector<std::string> scopePath;
gameplay::ScriptUtil::registerClass("Terrain", lua_members, NULL, lua_Terrain__gc, lua_statics, scopePath);
luaGlobal_Register_Conversion_Function("Terrain", __convertTo);
}
}
| 412 | 0.832641 | 1 | 0.832641 | game-dev | MEDIA | 0.839063 | game-dev | 0.650093 | 1 | 0.650093 |
Tslat/Advent-Of-Ascension | 22,138 | source/util/InteractionResults.java | package net.tslat.aoa3.util;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.ItemInteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.gameevent.GameEvent;
import net.neoforged.neoforge.event.entity.player.PlayerDestroyItemEvent;
/**
* Over-engineered helper class designed to make concise and correct return calls for the various {@link net.minecraft.world.InteractionResult InteractionResult}
* usages.<br>
* This primarily exists because Mojang made this as confusing as possible.
*/
public final class InteractionResults {
/**
* Specifically for {@link net.minecraft.world.item.Item#use(Level, Player, InteractionHand) Item.use}<br>
* The stack returned here will be the item left in the player's hand after completion.
*/
public static class ItemUse {
/**
* Use if you want to count the call as a success (Your intended functionality occurred successfully),
* and want the player's arm to swing.<br>
* Only use if returning a different value on the opposing logical side to prevent wasteful double-swinging.<br>
* <br>
* <b>Properties</b>:
* <p>
* On server:
* <ul>
* <li>{@link Player#swing(InteractionHand) Swings} the player's arm</li>
* <li>Swaps the player's held {@link ItemStack} out with the returned stack, if different to the original</li>
* </ul>
*
* On client:
* <ul>
* <li>Swings the player's arm</li>
* <li>Prevents the next hand from being checked for action</li>
* </ul>
* </p>
*
*/
public static InteractionResultHolder<ItemStack> succeedAndSwingArmOneSide(ItemStack stack) {
return InteractionResultHolder.success(stack);
}
/**
* Equivalent to {@link ItemUse#succeedAndSwingArmOneSide(ItemStack) ItemUse.succeedAndSwingArmOneSide} in functionality,
* but specifically when using this single return call for both server and client logical sides
*/
public static InteractionResultHolder<ItemStack> succeedAndSwingArmBothSides(ItemStack stack, boolean clientSide) {
return InteractionResultHolder.sidedSuccess(stack, clientSide);
}
/**
* Use if you want to count the call as a success (Your intended functionality occurred successfully),
* but <u>don't</u> want the player's arm to swing.<br>
* <br>
* <b>Properties</b>:
* <p>
* On server:
* <ul>
* <li>Swaps the player's held {@link ItemStack} out with the returned stack, if different to the original</li>
* </ul>
*
* On client:
* <ul>
* <li>Prevents the next hand from being checked for action</li>
* </ul>
* </p>
*
*/
public static InteractionResultHolder<ItemStack> succeedNoArmSwing(ItemStack stack) {
return InteractionResultHolder.consume(stack);
}
/**
* Use if you want to count the call as a miss and that you took no action and don't care about the result of this call<br>
* <br>
* <b>Properties:</b>
* <p>
* On server:
* <ul>
* <li>Swaps the player's held {@link ItemStack} out with the returned stack, if different to the original</li>
* </ul>
*
* On client:
* <ul>
* <li>Lets the client check the next hand for action</li>
* </ul>
* </p>
*/
public static InteractionResultHolder<ItemStack> noActionTaken(ItemStack stack) {
return InteractionResultHolder.pass(stack);
}
/**
* Use if you want to count the call as a failure<br>
* <br>
* <b>Properties:</b>
* <p>
* On server:
* <ul>
* <li>Discards the returned {@link ItemStack} if the item has a {@link net.minecraft.world.item.Item#getUseDuration(ItemStack) held-usage functionality}</li>
* </ul>
*
* On client:
* <ul>
* <li>Lets the client check the next hand for action</li>
* </ul>
* </p>
*/
public static InteractionResultHolder<ItemStack> denyUsage(ItemStack stack) {
return InteractionResultHolder.fail(stack);
}
}
/**
* Specifically for {@link net.minecraftforge.common.extensions.IForgeItem#onItemUseFirst(ItemStack, UseOnContext) IForgeItem.onItemUseFirst}
*/
public static class ItemUseFirst {
/**
* Use this if your item completed some functionality as a result of this call.<br>
* <br>
* <b>Properties:</b>
* <p>
* On server:
* <ul>
* <li>Adds a point to the {@link net.minecraft.stats.Stats#ITEM_USED Stats.ITEM_USED} statistic for this item</li>
* <li>Prevents any further block interaction functionality (such as {@link BlockState#use})</li>
* </ul>
* On client:
* <ul>
* <li>Prevents any further block interaction functionality (such as {@link BlockState#use})</li>
* </ul>
* </p>
*/
public static InteractionResult itemCompletedFunctionality() {
return InteractionResult.SUCCESS;
}
/**
* Use this if you want to prevent the {@link BlockState#use block interaction} from going ahead, but don't want to count it as an item usage for the purpose of {@link net.minecraft.stats.Stats#ITEM_USED statistics}<br>
* <br>
* <b>Properties:</b>
* <p>
* On both client and server:
* <ul>
* <li>Prevents any further block interaction functionality (such as {@link BlockState#use})</li>
* </ul>
* </p>
*/
public static InteractionResult cancelBlockUsage() {
return InteractionResult.FAIL;
}
/**
* Use this if your item didn't get used, and you don't want to prevent any further action from taking place (I.E. pretend your call never happened)<br>
* <br>
* <b>Properties:</b>
* <p>
* On both client and server:
* <ul>
* <li>The game continues on to {@link BlockState#use interact with} the clicked block</li>
* </ul>
* </p>
*/
public static InteractionResult noActionTaken() {
return InteractionResult.PASS;
}
}
/**
* Specifically for {@link net.minecraft.world.item.Item#useOn Item.useOn}
*/
public static class ItemUseOn {
/**
* Use if you want to count the call as a success (Your intended functionality occurred successfully),
* and want the player's arm to swing.<br>
* Only use if returning a different value on the opposing logical side to prevent wasteful double-swinging.<br>
* <br>
* <b>Properties</b>:
* <p>
* On server:
* <ul>
* <li>{@link Player#swing(InteractionHand) Swings} the player's arm</li>
* <li>Triggers {@link net.minecraft.advancements.CriteriaTriggers#ITEM_USED_ON_BLOCK ITEM_USED_ON_BLOCK} advancement trigger</li>
* </ul>
*
* On client:
* <ul>
* <li>Swings the player's arm</li>
* <li>Prevents the next hand from being checked for action</li>
* </ul>
* </p>
*
*/
public static InteractionResult succeedAndSwingArmOneSide() {
return InteractionResult.SUCCESS;
}
/**
* Equivalent to {@link ItemUseOn#succeedAndSwingArmOneSide ItemUseOn.succeedAndSwingArmOneSide} in functionality,
* but specifically when using this single return call for both server and client logical sides
*/
public static InteractionResult succeedAndSwingArmBothSides(boolean clientSide) {
return InteractionResult.sidedSuccess(clientSide);
}
/**
* Use this if you want to count the call as a success (Your intended functionality occured successfully),
* but don't want the player's arm to swing or an {@link net.minecraft.stats.Stats#ITEM_USED ITEM_USED} stat point to be added.<br>
* Normally this is used for items with secondary functions (such as a {@link net.minecraft.world.item.BlockItem BlockItem} that can also be eaten in-hand
*/
public static InteractionResult succeedNoSwingOrStats() {
return InteractionResult.CONSUME_PARTIAL;
}
/**
* Use if you want to count the call as a success (Your intended functionality occurred successfully),
* but <u>don't</u> want the player's arm to swing.<br>
* <br>
* <b>Properties</b>:
* <p>
* On server:
* <ul>
* <li>Triggers {@link net.minecraft.advancements.CriteriaTriggers#ITEM_USED_ON_BLOCK ITEM_USED_ON_BLOCK} advancement trigger</li>
* </ul>
*
* On client:
* <ul>
* <li>Prevents the next hand from being checked for action</li>
* </ul>
* </p>
*
*/
public static InteractionResult succeedNoArmSwing() {
return InteractionResult.CONSUME;
}
/**
* Use if you want to count the call as a miss and that you took no action and don't care about the result of this call<br>
* <br>
* <b>Properties:</b>
* <p>
* On client:
* <ul>
* <li>Lets the client check the next hand for action</li>
* </ul>
* </p>
*/
public static InteractionResult noActionTaken() {
return InteractionResult.PASS;
}
/**
* Use if you want to count the call as a failure (E.G. some conditions weren't met)<br>
* <br>
* <b>Properties:</b>
* <p>
* On client:
* <ul>
* <li>Prevents the next hand from being checked for action</li>
* </ul>
* </p>
*
*/
public static InteractionResult denyUsage() {
return InteractionResult.FAIL;
}
}
/**
* Specifically for {@link net.minecraft.world.level.block.state.BlockBehaviour#useItemOn Block.useItemOn}.<br>
*/
public static class BlockUseItemOn {
public static ItemInteractionResult success() {
return ItemInteractionResult.SUCCESS;
}
public static ItemInteractionResult consume() {
return ItemInteractionResult.CONSUME;
}
public static ItemInteractionResult consumePartial() {
return ItemInteractionResult.CONSUME_PARTIAL;
}
public static ItemInteractionResult noActionTaken() {
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
}
public static ItemInteractionResult skipBlockInteract() {
return ItemInteractionResult.SKIP_DEFAULT_BLOCK_INTERACTION;
}
public static ItemInteractionResult fail() {
return ItemInteractionResult.FAIL;
}
public static ItemInteractionResult succeedAndSwingArmBothSides(boolean clientSide) {
return ItemInteractionResult.sidedSuccess(clientSide);
}
}
/**
* Specifically for {@link net.minecraft.world.level.block.state.BlockBehaviour#useWithoutItem Block.useWithoutItem}.<br>
* Note that there is no way to prevent the second hand from being checked here without returning a successful result
*/
public static class BlockUseWithoutItem {
/**
* Use if you want to count the call as a success (Your intended functionality occurred successfully),
* and want the player's arm to swing.<br>
* Only use if returning a different value on the opposing logical side to prevent wasteful double-swinging.<br>
* <br>
* <b>Properties</b>:
* <p>
* On server:
* <ul>
* <li>{@link Player#swing(InteractionHand) Swings} the player's arm</li>
* <li>Triggers {@link net.minecraft.advancements.CriteriaTriggers#ITEM_USED_ON_BLOCK ITEM_USED_ON_BLOCK} advancement trigger</li>
* <li>Prevents the game from proceeding onto trigger {@link ItemStack#useOn} for the current hand</li>
* </ul>
*
* On client:
* <ul>
* <li>Swings the player's arm</li>
* <li>Prevents the next hand from being checked for action</li>
* <li>Prevents the game from proceeding onto trigger {@link ItemStack#useOn} for the current hand</li>
* </ul>
* </p>
*
*/
public static InteractionResult succeedAndSwingArmOneSide() {
return InteractionResult.SUCCESS;
}
/**
* Equivalent to {@link BlockUseWithoutItem#succeedAndSwingArmOneSide BlockUse.succeedAndSwingArmOneSide} in functionality,
* but specifically when using this single return call for both server and client logical sides
*/
public static InteractionResult succeedAndSwingArmBothSides(boolean clientSide) {
return InteractionResult.sidedSuccess(clientSide);
}
/**
* Use if you want to count the call as a success (Your intended functionality occurred successfully),
* but <u>don't</u> want the player's arm to swing.<br>
* <br>
* <b>Properties</b>:
* <p>
* On server:
* <ul>
* <li>Triggers {@link net.minecraft.advancements.CriteriaTriggers#ITEM_USED_ON_BLOCK ITEM_USED_ON_BLOCK} advancement trigger</li>
* <li>Prevents the game from proceeding onto trigger {@link ItemStack#useOn} for the current hand</li>
* </ul>
*
* On client:
* <ul>
* <li>Prevents the next hand from being checked for action</li>
* <li>Prevents the game from proceeding onto trigger {@link ItemStack#useOn} for the current hand</li>
* </ul>
* </p>
*
*/
public static InteractionResult succeedNoArmSwing() {
return InteractionResult.CONSUME;
}
/**
* Use if you want to count the call as a miss and that you took no action and don't care about the result of this call<br>
* <br>
* <b>Properties:</b>
* <p>
* On client:
* <ul>
* <li>Lets the client check the next hand for action</li>
* </ul>
* </p>
*/
public static InteractionResult noActionTaken() {
return InteractionResult.PASS;
}
}
/**
* Specifically for {@link net.minecraft.world.item.Item#interactLivingEntity Item.interactLivingEntity}
*/
public static class ItemInteractLivingEntity {
/**
* Use if you want to count the call as a success (Your intended functionality occurred successfully),
* and want the player's arm to swing.<br>
* Only use if returning a different value on the opposing logical side to prevent wasteful double-swinging.<br>
* <br>
* <b>Properties</b>:
* <p>
* On server:
* <ul>
* <li>{@link Player#swing(InteractionHand) Swings} the player's arm</li>
* <li>Fires the {@link PlayerDestroyItemEvent} if the held stack is consumed in the call</li>
* <li>Triggers the {@link net.minecraft.advancements.CriteriaTriggers#PLAYER_INTERACTED_WITH_ENTITY CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY} advancement trigger</li>
* <li>Sends the {@link GameEvent#ENTITY_INTERACT} game event</li>
* </ul>
*
* On client:
* <ul>
* <li>Swings the player's arm</li>
* <li>Prevents the next hand from being checked for action</li>
* <li>Prevents {@link Item#use} from being called</li>
* </ul>
* </p>
*
*/
public static InteractionResult succeedAndSwingArmOneSide() {
return InteractionResult.SUCCESS;
}
/**
* Equivalent to {@link ItemInteractLivingEntity#succeedAndSwingArmOneSide} in functionality,
* but specifically when using this single return call for both server and client logical sides
*/
public static InteractionResult succeedAndSwingArmBothSides(boolean clientSide) {
return InteractionResult.sidedSuccess(clientSide);
}
/**
* Equivalent to {@link ItemInteractLivingEntity#succeedAndSwingArmOneSide} except that the player's arm does not swing
*/
public static InteractionResult succeedNoArmSwing() {
return InteractionResult.CONSUME;
}
/**
* Use this if your function didn't take effect (either through not meeting the required conditions, or through failure)
*/
public static InteractionResult noActionTaken() {
return InteractionResult.PASS;
}
}
/**
* Specifically for {@link net.minecraft.world.entity.Entity#interact Entity.interact}
*/
public static class EntityInteract {
/**
* Use if you want to count the call as a success (Your intended functionality occurred successfully),
* and want the player's arm to swing.<br>
* Only use if returning a different value on the opposing logical side to prevent wasteful double-swinging.<br>
* <br>
* <b>Properties</b>:
* <p>
* On server:
* <ul>
* <li>{@link Player#swing(InteractionHand) Swings} the player's arm</li>
* <li>Fires the {@link PlayerDestroyItemEvent} if the held stack is consumed in the call</li>
* <li>Triggers the {@link net.minecraft.advancements.CriteriaTriggers#PLAYER_INTERACTED_WITH_ENTITY CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY} advancement trigger</li>
* </ul>
*
* On client:
* <ul>
* <li>Swings the player's arm</li>
* <li>Prevents the next hand from being checked for action</li>
* <li>Prevents {@link Item#use} from being called</li>
* </ul>
* </p>
*
*/
public static InteractionResult succeedAndSwingArmOneSide() {
return InteractionResult.SUCCESS;
}
/**
* Equivalent to {@link EntityInteract#succeedAndSwingArmOneSide} in functionality,
* but specifically when using this single return call for both server and client logical sides
*/
public static InteractionResult succeedAndSwingArmBothSides(boolean clientSide) {
return InteractionResult.sidedSuccess(clientSide);
}
/**
* Equivalent to {@link EntityInteract#succeedAndSwingArmOneSide} except that the player's arm does not swing
*/
public static InteractionResult succeedNoArmSwing() {
return InteractionResult.CONSUME;
}
/**
* Use this if your function didn't take effect (either through not meeting the required conditions, or through failure).<br>
* <br>
* <b>Properties:</b>
* <ul>
* <li>Proceeds onto {@link Item#interactLivingEntity}</li>
* </ul>
*/
public static InteractionResult noActionTaken() {
return InteractionResult.PASS;
}
}
/**
* Specifically for {@link net.minecraft.world.entity.Entity#interactAt Entity.interactAt}.<br>
* This is almost completely identical to {@link EntityInteract}, with the single difference being that
* an unsuccessful response just forwards the call on to {@link net.minecraft.world.entity.Entity#interact Entity.interact}.<br>
* Refer to {@link EntityInteract} for responses not listed below
*/
public static class EntityInteractAt {
/**
* Use this if you don't have any specific action to take.<br>
* This just pushes the game onto Entity.interact, so any further responses can be referred to from {@link EntityInteract}.<br>
* <br>
* <b>NOTE:</b> This only passes onto Entity.interact if used on the client-side.
* However, you should still return this on the server side for consistency if returning it on the client side
*/
public static InteractionResult noActionTaken() {
return InteractionResult.PASS;
}
}
/**
* Specifically for {@link net.minecraft.world.entity.Mob#mobInteract Mob.mobInteract}.<br>
* This is technically a subsidiary of {@link net.minecraft.world.entity.Entity#interact Entity.interact},
* but contains an additional property if returning a successful response.
*/
public static class MobInteract {
/**
* Use if you want to count the call as a success (Your intended functionality occurred successfully),
* and want the player's arm to swing.<br>
* Only use if returning a different value on the opposing logical side to prevent wasteful double-swinging.<br>
* <br>
* <b>Properties</b>:
* <p>
* On server:
* <ul>
* <li>{@link Player#swing(InteractionHand) Swings} the player's arm</li>
* <li>Fires the {@link PlayerDestroyItemEvent} if the held stack is consumed in the call</li>
* <li>Triggers the {@link net.minecraft.advancements.CriteriaTriggers#PLAYER_INTERACTED_WITH_ENTITY CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY} advancement trigger</li>
* <li>Fires the {@link GameEvent#ENTITY_INTERACT} GameEvent</li>
* </ul>
*
* On client:
* <ul>
* <li>Swings the player's arm</li>
* <li>Prevents the next hand from being checked for action</li>
* <li>Prevents {@link Item#use} from being called</li>
* </ul>
* </p>
*
*/
public static InteractionResult succeedAndSwingArmOneSide() {
return InteractionResult.SUCCESS;
}
/**
* Equivalent to {@link MobInteract#succeedAndSwingArmOneSide} in functionality,
* but specifically when using this single return call for both server and client logical sides
*/
public static InteractionResult succeedAndSwingArmBothSides(boolean clientSide) {
return InteractionResult.sidedSuccess(clientSide);
}
/**
* Equivalent to {@link MobInteract#succeedAndSwingArmOneSide} except that the player's arm does not swing
*/
public static InteractionResult succeedNoArmSwing() {
return InteractionResult.CONSUME;
}
/**
* Use this if your function didn't take effect (either through not meeting the required conditions, or through failure).<br>
* <br>
* <b>Properties:</b>
* <ul>
* <li>Proceeds onto {@link Item#interactLivingEntity}</li>
* </ul>
*/
public static InteractionResult noActionTaken() {
return InteractionResult.PASS;
}
}
/**
* Specifically for {@link net.minecraft.world.item.BlockItem#place BlockItem.place}.<br>
* This is a subsidiary of {@link net.minecraft.world.item.BlockItem#useOn BlockItem.useOn}.<br>
* Refer to {@link ItemUseOn} for responses, with the single exception of {@link BlockItemPlace#failAndCheckFood}
*/
public static class BlockItemPlace extends ItemUseOn {
/**
* Use this if your BlockItem failed to place, but it also has {@link net.minecraft.core.component.DataComponents#FOOD DataComponents.FOOD}.<br>
* The game will then proceed to check for eating actions.<br>
* <br>
* For everything else, use {@link ItemUseOn}'s return options
*/
public static InteractionResult failAndCheckFood() {
return InteractionResult.FAIL;
}
}
}
| 412 | 0.855487 | 1 | 0.855487 | game-dev | MEDIA | 0.937112 | game-dev | 0.506054 | 1 | 0.506054 |
Gaby-Station/Gaby-Station | 1,395 | Content.Shared/_Shitmed/Surgery/Tools/SurgeryToolComponent.cs | // SPDX-FileCopyrightText: 2024 Piras314 <p1r4s@proton.me>
// SPDX-FileCopyrightText: 2024 deltanedas <39013340+deltanedas@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 deltanedas <@deltanedas:kde.org>
// SPDX-FileCopyrightText: 2024 gluesniffler <159397573+gluesniffler@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using Robust.Shared.Audio;
using Robust.Shared.GameStates;
namespace Content.Shared._Shitmed.Medical.Surgery.Tools;
[RegisterComponent, NetworkedComponent, AutoGenerateComponentState]
public sealed partial class SurgeryToolComponent : Component
{
/// <summary>
/// Ignores the ItemToggle activated check when using this item in a surgery.
/// Useful for things like augments whose ItemToggle is unrelated to use in surgery.
/// </summary>
[DataField]
public bool IgnoreToggle;
[DataField, AutoNetworkedField]
public SoundSpecifier? StartSound;
[DataField, AutoNetworkedField]
public SoundSpecifier? EndSound;
}
/// <summary>
/// Raised on a tool to see if it can be used in a surgery step.
/// If this is cancelled the step can't be completed.
/// </summary>
[ByRefEvent]
public record struct SurgeryToolUsedEvent(EntityUid User, EntityUid Target, bool IgnoreToggle = false, bool Cancelled = false);
| 412 | 0.535318 | 1 | 0.535318 | game-dev | MEDIA | 0.728271 | game-dev | 0.721154 | 1 | 0.721154 |
Revolutionary-Games/Thrive | 1,348 | src/thriveopedia/pages/ThriveopediaCurrentWorldPage.cs | using Godot;
/// <summary>
/// Thriveopedia page displaying information about the current game in progress.
/// </summary>
public partial class ThriveopediaCurrentWorldPage : ThriveopediaPage, IThriveopediaPage
{
#pragma warning disable CA2213
[Export]
private RichTextLabel difficultyDetails = null!;
[Export]
private RichTextLabel planetDetails = null!;
[Export]
private RichTextLabel miscDetails = null!;
#pragma warning restore CA2213
public string PageName => "CurrentWorld";
public string TranslatedPageName => Localization.Translate("THRIVEOPEDIA_CURRENT_WORLD_PAGE_TITLE");
public string? ParentPageName => null;
public override void _Ready()
{
base._Ready();
UpdateCurrentWorldDetails();
}
public override void UpdateCurrentWorldDetails()
{
if (CurrentGame == null)
return;
var settings = CurrentGame.GameWorld.WorldSettings;
// For now, just display the world generation settings associated with this game
difficultyDetails.Text = settings.GetTranslatedDifficultyString();
planetDetails.Text = settings.GetTranslatedPlanetString();
miscDetails.Text = settings.GetTranslatedMiscString();
}
public override void OnTranslationsChanged()
{
UpdateCurrentWorldDetails();
}
}
| 412 | 0.912416 | 1 | 0.912416 | game-dev | MEDIA | 0.974205 | game-dev | 0.675828 | 1 | 0.675828 |
11011010/BFA-Frankenstein-Core | 11,908 | src/server/game/AuctionHouseBot/AuctionHouseBot.h | /*
* Copyright (C) 2020 BfaCore
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef AUCTION_HOUSE_BOT_H
#define AUCTION_HOUSE_BOT_H
#include "Define.h"
#include "ObjectGuid.h"
#include "SharedDefines.h"
#include <string>
class AuctionBotSeller;
class AuctionBotBuyer;
// shadow of ItemQualities with skipped ITEM_QUALITY_HEIRLOOM, anything after ITEM_QUALITY_ARTIFACT(6) in fact
enum AuctionQuality
{
AUCTION_QUALITY_GRAY = ITEM_QUALITY_POOR,
AUCTION_QUALITY_WHITE = ITEM_QUALITY_NORMAL,
AUCTION_QUALITY_GREEN = ITEM_QUALITY_UNCOMMON,
AUCTION_QUALITY_BLUE = ITEM_QUALITY_RARE,
AUCTION_QUALITY_PURPLE = ITEM_QUALITY_EPIC,
AUCTION_QUALITY_ORANGE = ITEM_QUALITY_LEGENDARY,
AUCTION_QUALITY_YELLOW = ITEM_QUALITY_ARTIFACT,
};
#define MAX_AUCTION_QUALITY 7
enum AuctionHouseType
{
AUCTION_HOUSE_NEUTRAL = 0,
AUCTION_HOUSE_ALLIANCE = 1,
AUCTION_HOUSE_HORDE = 2
};
#define MAX_AUCTION_HOUSE_TYPE 3
enum AuctionBotConfigUInt32Values
{
CONFIG_AHBOT_MAXTIME,
CONFIG_AHBOT_MINTIME,
CONFIG_AHBOT_ITEMS_PER_CYCLE_BOOST,
CONFIG_AHBOT_ITEMS_PER_CYCLE_NORMAL,
CONFIG_AHBOT_ALLIANCE_ITEM_AMOUNT_RATIO,
CONFIG_AHBOT_HORDE_ITEM_AMOUNT_RATIO,
CONFIG_AHBOT_NEUTRAL_ITEM_AMOUNT_RATIO,
CONFIG_AHBOT_ITEM_MIN_ITEM_LEVEL,
CONFIG_AHBOT_ITEM_MAX_ITEM_LEVEL,
CONFIG_AHBOT_ITEM_MIN_REQ_LEVEL,
CONFIG_AHBOT_ITEM_MAX_REQ_LEVEL,
CONFIG_AHBOT_ITEM_MIN_SKILL_RANK,
CONFIG_AHBOT_ITEM_MAX_SKILL_RANK,
CONFIG_AHBOT_ITEM_GRAY_AMOUNT,
CONFIG_AHBOT_ITEM_WHITE_AMOUNT,
CONFIG_AHBOT_ITEM_GREEN_AMOUNT,
CONFIG_AHBOT_ITEM_BLUE_AMOUNT,
CONFIG_AHBOT_ITEM_PURPLE_AMOUNT,
CONFIG_AHBOT_ITEM_ORANGE_AMOUNT,
CONFIG_AHBOT_ITEM_YELLOW_AMOUNT,
CONFIG_AHBOT_CLASS_CONSUMABLE_AMOUNT,
CONFIG_AHBOT_CLASS_CONTAINER_AMOUNT,
CONFIG_AHBOT_CLASS_WEAPON_AMOUNT,
CONFIG_AHBOT_CLASS_GEM_AMOUNT,
CONFIG_AHBOT_CLASS_ARMOR_AMOUNT,
CONFIG_AHBOT_CLASS_REAGENT_AMOUNT,
CONFIG_AHBOT_CLASS_PROJECTILE_AMOUNT,
CONFIG_AHBOT_CLASS_TRADEGOOD_AMOUNT,
CONFIG_AHBOT_CLASS_GENERIC_AMOUNT,
CONFIG_AHBOT_CLASS_RECIPE_AMOUNT,
CONFIG_AHBOT_CLASS_QUIVER_AMOUNT,
CONFIG_AHBOT_CLASS_QUEST_AMOUNT,
CONFIG_AHBOT_CLASS_KEY_AMOUNT,
CONFIG_AHBOT_CLASS_MISC_AMOUNT,
CONFIG_AHBOT_CLASS_GLYPH_AMOUNT,
CONFIG_AHBOT_ALLIANCE_PRICE_RATIO,
CONFIG_AHBOT_HORDE_PRICE_RATIO,
CONFIG_AHBOT_NEUTRAL_PRICE_RATIO,
CONFIG_AHBOT_ITEM_GRAY_PRICE_RATIO,
CONFIG_AHBOT_ITEM_WHITE_PRICE_RATIO,
CONFIG_AHBOT_ITEM_GREEN_PRICE_RATIO,
CONFIG_AHBOT_ITEM_BLUE_PRICE_RATIO,
CONFIG_AHBOT_ITEM_PURPLE_PRICE_RATIO,
CONFIG_AHBOT_ITEM_ORANGE_PRICE_RATIO,
CONFIG_AHBOT_ITEM_YELLOW_PRICE_RATIO,
CONFIG_AHBOT_CLASS_CONSUMABLE_PRICE_RATIO,
CONFIG_AHBOT_CLASS_CONTAINER_PRICE_RATIO,
CONFIG_AHBOT_CLASS_WEAPON_PRICE_RATIO,
CONFIG_AHBOT_CLASS_GEM_PRICE_RATIO,
CONFIG_AHBOT_CLASS_ARMOR_PRICE_RATIO,
CONFIG_AHBOT_CLASS_REAGENT_PRICE_RATIO,
CONFIG_AHBOT_CLASS_PROJECTILE_PRICE_RATIO,
CONFIG_AHBOT_CLASS_TRADEGOOD_PRICE_RATIO,
CONFIG_AHBOT_CLASS_GENERIC_PRICE_RATIO,
CONFIG_AHBOT_CLASS_RECIPE_PRICE_RATIO,
CONFIG_AHBOT_CLASS_MONEY_PRICE_RATIO,
CONFIG_AHBOT_CLASS_QUIVER_PRICE_RATIO,
CONFIG_AHBOT_CLASS_QUEST_PRICE_RATIO,
CONFIG_AHBOT_CLASS_KEY_PRICE_RATIO,
CONFIG_AHBOT_CLASS_PERMANENT_PRICE_RATIO,
CONFIG_AHBOT_CLASS_MISC_PRICE_RATIO,
CONFIG_AHBOT_CLASS_GLYPH_PRICE_RATIO,
CONFIG_AHBOT_BUYER_RECHECK_INTERVAL,
CONFIG_AHBOT_BUYER_BASEPRICE_GRAY,
CONFIG_AHBOT_BUYER_BASEPRICE_WHITE,
CONFIG_AHBOT_BUYER_BASEPRICE_GREEN,
CONFIG_AHBOT_BUYER_BASEPRICE_BLUE,
CONFIG_AHBOT_BUYER_BASEPRICE_PURPLE,
CONFIG_AHBOT_BUYER_BASEPRICE_ORANGE,
CONFIG_AHBOT_BUYER_BASEPRICE_YELLOW,
CONFIG_AHBOT_BUYER_CHANCEMULTIPLIER_GRAY,
CONFIG_AHBOT_BUYER_CHANCEMULTIPLIER_WHITE,
CONFIG_AHBOT_BUYER_CHANCEMULTIPLIER_GREEN,
CONFIG_AHBOT_BUYER_CHANCEMULTIPLIER_BLUE,
CONFIG_AHBOT_BUYER_CHANCEMULTIPLIER_PURPLE,
CONFIG_AHBOT_BUYER_CHANCEMULTIPLIER_ORANGE,
CONFIG_AHBOT_BUYER_CHANCEMULTIPLIER_YELLOW,
CONFIG_AHBOT_CLASS_MISC_MOUNT_MIN_REQ_LEVEL,
CONFIG_AHBOT_CLASS_MISC_MOUNT_MAX_REQ_LEVEL,
CONFIG_AHBOT_CLASS_MISC_MOUNT_MIN_SKILL_RANK,
CONFIG_AHBOT_CLASS_MISC_MOUNT_MAX_SKILL_RANK,
CONFIG_AHBOT_CLASS_GLYPH_MIN_REQ_LEVEL,
CONFIG_AHBOT_CLASS_GLYPH_MAX_REQ_LEVEL,
CONFIG_AHBOT_CLASS_GLYPH_MIN_ITEM_LEVEL,
CONFIG_AHBOT_CLASS_GLYPH_MAX_ITEM_LEVEL,
CONFIG_AHBOT_CLASS_TRADEGOOD_MIN_ITEM_LEVEL,
CONFIG_AHBOT_CLASS_TRADEGOOD_MAX_ITEM_LEVEL,
CONFIG_AHBOT_CLASS_CONTAINER_MIN_ITEM_LEVEL,
CONFIG_AHBOT_CLASS_CONTAINER_MAX_ITEM_LEVEL,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_CONSUMABLE,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_CONTAINER,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_WEAPON,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_GEM,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_ARMOR,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_REAGENT,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_PROJECTILE,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_TRADEGOOD,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_GENERIC,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_RECIPE,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_QUIVER,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_QUEST,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_KEY,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_MISC,
CONFIG_AHBOT_CLASS_RANDOMSTACKRATIO_GLYPH,
CONFIG_AHBOT_ACCOUNT_ID,
CONFIG_UINT32_AHBOT_UINT32_COUNT
};
enum AuctionBotConfigBoolValues
{
CONFIG_AHBOT_BUYER_ALLIANCE_ENABLED,
CONFIG_AHBOT_BUYER_HORDE_ENABLED,
CONFIG_AHBOT_BUYER_NEUTRAL_ENABLED,
CONFIG_AHBOT_ITEMS_VENDOR,
CONFIG_AHBOT_ITEMS_LOOT,
CONFIG_AHBOT_ITEMS_MISC,
CONFIG_AHBOT_BIND_NO,
CONFIG_AHBOT_BIND_PICKUP,
CONFIG_AHBOT_BIND_EQUIP,
CONFIG_AHBOT_BIND_USE,
CONFIG_AHBOT_BIND_QUEST,
CONFIG_AHBOT_BUYPRICE_SELLER,
CONFIG_AHBOT_SELLER_ENABLED,
CONFIG_AHBOT_BUYER_ENABLED,
CONFIG_AHBOT_LOCKBOX_ENABLED,
CONFIG_AHBOT_CLASS_CONSUMABLE_ALLOW_ZERO,
CONFIG_AHBOT_CLASS_CONTAINER_ALLOW_ZERO,
CONFIG_AHBOT_CLASS_WEAPON_ALLOW_ZERO,
CONFIG_AHBOT_CLASS_GEM_ALLOW_ZERO,
CONFIG_AHBOT_CLASS_ARMOR_ALLOW_ZERO,
CONFIG_AHBOT_CLASS_REAGENT_ALLOW_ZERO,
CONFIG_AHBOT_CLASS_PROJECTILE_ALLOW_ZERO,
CONFIG_AHBOT_CLASS_TRADEGOOD_ALLOW_ZERO,
CONFIG_AHBOT_CLASS_RECIPE_ALLOW_ZERO,
CONFIG_AHBOT_CLASS_QUIVER_ALLOW_ZERO,
CONFIG_AHBOT_CLASS_QUEST_ALLOW_ZERO,
CONFIG_AHBOT_CLASS_KEY_ALLOW_ZERO,
CONFIG_AHBOT_CLASS_MISC_ALLOW_ZERO,
CONFIG_AHBOT_CLASS_GLYPH_ALLOW_ZERO,
CONFIG_UINT32_AHBOT_BOOL_COUNT
};
enum AuctionBotConfigFloatValues
{
CONFIG_AHBOT_BUYER_CHANCE_FACTOR,
CONFIG_AHBOT_BIDPRICE_MIN,
CONFIG_AHBOT_BIDPRICE_MAX,
CONFIG_AHBOT_FLOAT_COUNT
};
// All basic config data used by other AHBot classes for self-configure.
class TC_GAME_API AuctionBotConfig
{
private:
AuctionBotConfig() : _itemsPerCycleBoost(1000), _itemsPerCycleNormal(20) { }
~AuctionBotConfig() { }
AuctionBotConfig(AuctionBotConfig const&) = delete;
AuctionBotConfig& operator=(AuctionBotConfig const&) = delete;
public:
static AuctionBotConfig* instance();
bool Initialize();
const std::string& GetAHBotIncludes() const { return _AHBotIncludes; }
const std::string& GetAHBotExcludes() const { return _AHBotExcludes; }
uint32 GetConfig(AuctionBotConfigUInt32Values index) const { return _configUint32Values[index]; }
bool GetConfig(AuctionBotConfigBoolValues index) const { return _configBoolValues[index]; }
float GetConfig(AuctionBotConfigFloatValues index) const { return _configFloatValues[index]; }
void SetConfig(AuctionBotConfigBoolValues index, bool value) { _configBoolValues[index] = value; }
void SetConfig(AuctionBotConfigUInt32Values index, uint32 value) { _configUint32Values[index] = value; }
void SetConfig(AuctionBotConfigFloatValues index, float value) { _configFloatValues[index] = value; }
uint32 GetConfigItemAmountRatio(AuctionHouseType houseType) const;
bool GetConfigBuyerEnabled(AuctionHouseType houseType) const;
uint32 GetConfigItemQualityAmount(AuctionQuality quality) const;
uint32 GetItemPerCycleBoost() const { return _itemsPerCycleBoost; }
uint32 GetItemPerCycleNormal() const { return _itemsPerCycleNormal; }
ObjectGuid GetRandChar() const;
ObjectGuid GetRandCharExclude(ObjectGuid exclude) const;
bool IsBotChar(ObjectGuid characterID) const;
void Reload() { GetConfigFromFile(); }
uint32 GetAuctionHouseId(AuctionHouseType houseType) const;
static char const* GetHouseTypeName(AuctionHouseType houseType);
private:
std::string _AHBotIncludes;
std::string _AHBotExcludes;
std::vector<ObjectGuid> _AHBotCharacters;
uint32 _itemsPerCycleBoost;
uint32 _itemsPerCycleNormal;
uint32 _configUint32Values[CONFIG_UINT32_AHBOT_UINT32_COUNT];
bool _configBoolValues[CONFIG_UINT32_AHBOT_BOOL_COUNT];
float _configFloatValues[CONFIG_AHBOT_FLOAT_COUNT];
void SetAHBotIncludes(const std::string& AHBotIncludes) { _AHBotIncludes = AHBotIncludes; }
void SetAHBotExcludes(const std::string& AHBotExcludes) { _AHBotExcludes = AHBotExcludes; }
void SetConfig(AuctionBotConfigUInt32Values index, char const* fieldname, uint32 defvalue);
void SetConfigMax(AuctionBotConfigUInt32Values index, char const* fieldname, uint32 defvalue, uint32 maxvalue);
void SetConfigMinMax(AuctionBotConfigUInt32Values index, char const* fieldname, uint32 defvalue, uint32 minvalue, uint32 maxvalue);
void SetConfig(AuctionBotConfigBoolValues index, char const* fieldname, bool defvalue);
void SetConfig(AuctionBotConfigFloatValues index, char const* fieldname, float defvalue);
void GetConfigFromFile();
};
#define sAuctionBotConfig AuctionBotConfig::instance()
class AuctionBotAgent
{
public:
AuctionBotAgent() {}
virtual ~AuctionBotAgent() {}
virtual bool Initialize() = 0;
virtual bool Update(AuctionHouseType houseType) = 0;
};
struct AuctionHouseBotStatusInfoPerType
{
uint32 ItemsCount;
uint32 QualityInfo[MAX_AUCTION_QUALITY];
};
typedef AuctionHouseBotStatusInfoPerType AuctionHouseBotStatusInfo[MAX_AUCTION_HOUSE_TYPE];
// This class handle both Selling and Buying method
// (holder of AuctionBotBuyer and AuctionBotSeller objects)
class TC_GAME_API AuctionHouseBot
{
private:
AuctionHouseBot();
~AuctionHouseBot();
AuctionHouseBot(const AuctionHouseBot&);
AuctionHouseBot& operator=(const AuctionHouseBot&);
public:
static AuctionHouseBot* instance();
void Update();
void Initialize();
// Followed method is mainly used by cs_ahbot.cpp for in-game/console command
void SetItemsRatio(uint32 al, uint32 ho, uint32 ne);
void SetItemsRatioForHouse(AuctionHouseType house, uint32 val);
void SetItemsAmount(uint32(&vals)[MAX_AUCTION_QUALITY]);
void SetItemsAmountForQuality(AuctionQuality quality, uint32 val);
void ReloadAllConfig();
void Rebuild(bool all);
void PrepareStatusInfos(AuctionHouseBotStatusInfo& statusInfo);
private:
void InitializeAgents();
AuctionBotBuyer* _buyer;
AuctionBotSeller* _seller;
uint32 _operationSelector; // 0..2*MAX_AUCTION_HOUSE_TYPE-1
};
#define sAuctionBot AuctionHouseBot::instance()
#endif
| 412 | 0.819732 | 1 | 0.819732 | game-dev | MEDIA | 0.731607 | game-dev | 0.55979 | 1 | 0.55979 |
DruidMech/UE4-CPP-Shooter-Series | 5,549 | Source Code Per Lesson/Section 15 - AI and Behavior Trees/307 Stop Enemy Attack on Death/Weapon.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Weapon.h"
AWeapon::AWeapon() :
ThrowWeaponTime(0.7f),
bFalling(false),
Ammo(30),
MagazineCapacity(30),
WeaponType(EWeaponType::EWT_SubmachineGun),
AmmoType(EAmmoType::EAT_9mm),
ReloadMontageSection(FName(TEXT("Reload SMG"))),
ClipBoneName(TEXT("smg_clip")),
SlideDisplacement(0.f),
SlideDisplacementTime(0.2f),
bMovingSlide(false),
MaxSlideDisplacement(4.f),
MaxRecoilRotation(20.f),
bAutomatic(true)
{
PrimaryActorTick.bCanEverTick = true;
}
void AWeapon::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// Keep the Weapon upright
if (GetItemState() == EItemState::EIS_Falling && bFalling)
{
const FRotator MeshRotation{ 0.f, GetItemMesh()->GetComponentRotation().Yaw, 0.f };
GetItemMesh()->SetWorldRotation(MeshRotation, false, nullptr, ETeleportType::TeleportPhysics);
}
// Update slide on pistol
UpdateSlideDisplacement();
}
void AWeapon::ThrowWeapon()
{
FRotator MeshRotation{ 0.f, GetItemMesh()->GetComponentRotation().Yaw, 0.f };
GetItemMesh()->SetWorldRotation(MeshRotation, false, nullptr, ETeleportType::TeleportPhysics);
const FVector MeshForward{ GetItemMesh()->GetForwardVector() };
const FVector MeshRight{ GetItemMesh()->GetRightVector() };
// Direction in which we throw the Weapon
FVector ImpulseDirection = MeshRight.RotateAngleAxis(-20.f, MeshForward);
float RandomRotation{ 30.f };
ImpulseDirection = ImpulseDirection.RotateAngleAxis(RandomRotation, FVector(0.f, 0.f, 1.f));
ImpulseDirection *= 20'000.f;
GetItemMesh()->AddImpulse(ImpulseDirection);
bFalling = true;
GetWorldTimerManager().SetTimer(
ThrowWeaponTimer,
this,
&AWeapon::StopFalling,
ThrowWeaponTime);
EnableGlowMaterial();
}
void AWeapon::StopFalling()
{
bFalling = false;
SetItemState(EItemState::EIS_Pickup);
StartPulseTimer();
}
void AWeapon::OnConstruction(const FTransform& Transform)
{
Super::OnConstruction(Transform);
const FString WeaponTablePath{ TEXT("DataTable'/Game/_Game/DataTable/WeaponData.WeaponData'") };
UDataTable* WeaponTableObject = Cast<UDataTable>(StaticLoadObject(UDataTable::StaticClass(), nullptr, *WeaponTablePath));
if (WeaponTableObject)
{
FWeaponDataTable* WeaponDataRow = nullptr;
switch (WeaponType)
{
case EWeaponType::EWT_SubmachineGun:
WeaponDataRow = WeaponTableObject->FindRow<FWeaponDataTable>(FName("SubmachineGun"), TEXT(""));
break;
case EWeaponType::EWT_AssaultRifle:
WeaponDataRow = WeaponTableObject->FindRow<FWeaponDataTable>(FName("AssaultRifle"), TEXT(""));
break;
case EWeaponType::EWT_Pistol:
WeaponDataRow = WeaponTableObject->FindRow<FWeaponDataTable>(FName("Pistol"), TEXT(""));
break;
}
if (WeaponDataRow)
{
AmmoType = WeaponDataRow->AmmoType;
Ammo = WeaponDataRow->WeaponAmmo;
MagazineCapacity = WeaponDataRow->MagazingCapacity;
SetPickupSound(WeaponDataRow->PickupSound);
SetEquipSound(WeaponDataRow->EquipSound);
GetItemMesh()->SetSkeletalMesh(WeaponDataRow->ItemMesh);
SetItemName(WeaponDataRow->ItemName);
SetIconItem(WeaponDataRow->InventoryIcon);
SetAmmoIcon(WeaponDataRow->AmmoIcon);
SetMaterialInstance(WeaponDataRow->MaterialInstance);
PreviousMaterialIndex = GetMaterialIndex();
GetItemMesh()->SetMaterial(PreviousMaterialIndex, nullptr);
SetMaterialIndex(WeaponDataRow->MaterialIndex);
SetClipBoneName(WeaponDataRow->ClipBoneName);
SetReloadMontageSection(WeaponDataRow->ReloadMontageSection);
GetItemMesh()->SetAnimInstanceClass(WeaponDataRow->AnimBP);
CrosshairsMiddle = WeaponDataRow->CrosshairsMiddle;
CrosshairsLeft = WeaponDataRow->CrosshairsLeft;
CrosshairsRight = WeaponDataRow->CrosshairsRight;
CrosshairsTop = WeaponDataRow->CrosshairsTop;
CrosshairsBottom = WeaponDataRow->CrosshairsBottom;
AutoFireRate = WeaponDataRow->AutoFireRate;
MuzzleFlash = WeaponDataRow->MuzzleFlash;
FireSound = WeaponDataRow->FireSound;
BoneToHide = WeaponDataRow->BoneToHide;
bAutomatic = WeaponDataRow->bAutomatic;
Damage = WeaponDataRow->Damage;
HeadShotDamage = WeaponDataRow->HeadShotDamage;
}
if (GetMaterialInstance())
{
SetDynamicMaterialInstance(UMaterialInstanceDynamic::Create(GetMaterialInstance(), this));
GetDynamicMaterialInstance()->SetVectorParameterValue(TEXT("FresnelColor"), GetGlowColor());
GetItemMesh()->SetMaterial(GetMaterialIndex(), GetDynamicMaterialInstance());
EnableGlowMaterial();
}
}
}
void AWeapon::BeginPlay()
{
Super::BeginPlay();
if (BoneToHide != FName(""))
{
GetItemMesh()->HideBoneByName(BoneToHide, EPhysBodyOp::PBO_None);
}
}
void AWeapon::FinishMovingSlide()
{
bMovingSlide = false;
}
void AWeapon::UpdateSlideDisplacement()
{
if (SlideDisplacementCurve && bMovingSlide)
{
const float ElapsedTime{ GetWorldTimerManager().GetTimerElapsed(SlideTimer) };
const float CurveValue{ SlideDisplacementCurve->GetFloatValue(ElapsedTime) };
SlideDisplacement = CurveValue * MaxSlideDisplacement;
RecoilRotation = CurveValue * MaxRecoilRotation;
}
}
void AWeapon::DecrementAmmo()
{
if (Ammo - 1 <= 0)
{
Ammo = 0;
}
else
{
--Ammo;
}
}
void AWeapon::StartSlideTimer()
{
bMovingSlide = true;
GetWorldTimerManager().SetTimer(
SlideTimer,
this,
&AWeapon::FinishMovingSlide,
SlideDisplacementTime
);
}
void AWeapon::ReloadAmmo(int32 Amount)
{
checkf(Ammo + Amount <= MagazineCapacity, TEXT("Attempted to reload with more than magazine capacity!"));
Ammo += Amount;
}
bool AWeapon::ClipIsFull()
{
return Ammo >= MagazineCapacity;
}
| 412 | 0.926331 | 1 | 0.926331 | game-dev | MEDIA | 0.992843 | game-dev | 0.720892 | 1 | 0.720892 |
Kolos65/Mockable | 2,279 | Sources/Mockable/Builder/PropertyBuilders/PropertyActionBuilder.swift | //
// PropertyActionBuilder.swift
// Mockable
//
// Created by Kolos Foltanyi on 2023. 11. 22..
//
/// A builder for specifying actions to be performed when mocking the getter and setter of a property.
///
/// This builder is typically used within the context of a higher-level builder (e.g., an `ActionBuilder`)
/// to specify the behavior of the getter and setter of a particular property of a mock.
public struct PropertyActionBuilder<T: MockableService, ParentBuilder: Builder<T>> {
/// Convenient type for the associated service's Member.
public typealias Member = T.Member
/// The member representing the getter of the property.
var getMember: Member
/// The member representing the setter of the property.
var setMember: Member
/// The associated service's mocker.
var mocker: Mocker<T>
/// Initializes a new instance of `PropertyActionBuilder`.
///
/// - Parameters:
/// - mocker: The `Mocker` instance of the associated mock service.
/// - getKind: The member representing the getter of the property.
/// - setKind: The member representing the setter of the property.
public init(_ mocker: Mocker<T>, kind getMember: Member, setKind setMember: Member) {
self.getMember = getMember
self.setMember = setMember
self.mocker = mocker
}
/// Specifies the action to be performed when the getter of the property is called.
///
/// - Parameter action: The closure representing the action to be performed.
/// - Returns: The parent builder, typically used for chaining additional specifications.
@discardableResult
public func performOnGet(_ action: @escaping () -> Void) -> ParentBuilder {
mocker.addAction(action, for: getMember)
return .init(mocker: mocker)
}
/// Specifies the action to be performed when the setter of the property is called.
///
/// - Parameter action: The closure representing the action to be performed.
/// - Returns: The parent builder, typically used for chaining additional specifications.
@discardableResult
public func performOnSet(_ action: @escaping () -> Void) -> ParentBuilder {
mocker.addAction(action, for: setMember)
return .init(mocker: mocker)
}
}
| 412 | 0.790729 | 1 | 0.790729 | game-dev | MEDIA | 0.780176 | game-dev | 0.831523 | 1 | 0.831523 |
Hoto-Mocha/Re-ARranged-Pixel-Dungeon | 2,743 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/sprites/ShamanSprite.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2025 Evan Debenham
*
* 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.sprites;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.Shaman;
import com.shatteredpixel.shatteredpixeldungeon.effects.MagicMissile;
import com.watabou.noosa.TextureFilm;
import com.watabou.noosa.audio.Sample;
import com.watabou.utils.Callback;
public abstract class ShamanSprite extends MobSprite {
protected int boltType;
protected abstract int texOffset();
public ShamanSprite() {
super();
int c = texOffset();
texture( Assets.Sprites.SHAMAN );
TextureFilm frames = new TextureFilm( texture, 12, 15 );
idle = new Animation( 2, true );
idle.frames( frames, c+0, c+0, c+0, c+1, c+0, c+0, c+1, c+1 );
run = new Animation( 12, true );
run.frames( frames, c+4, c+5, c+6, c+7 );
attack = new Animation( 12, false );
attack.frames( frames, c+2, c+3, c+0 );
zap = attack.clone();
die = new Animation( 12, false );
die.frames( frames, c+8, c+9, c+10 );
play( idle );
}
public void zap( int cell ) {
super.zap( cell );
MagicMissile.boltFromChar( parent,
boltType,
this,
cell,
new Callback() {
@Override
public void call() {
((Shaman)ch).onZapComplete();
}
} );
Sample.INSTANCE.play( Assets.Sounds.ZAP );
}
@Override
public void onComplete( Animation anim ) {
if (anim == zap) {
idle();
}
super.onComplete( anim );
}
public static class Red extends ShamanSprite {
{
boltType = MagicMissile.SHAMAN_RED;
}
@Override
protected int texOffset() {
return 0;
}
}
public static class Blue extends ShamanSprite {
{
boltType = MagicMissile.SHAMAN_BLUE;
}
@Override
protected int texOffset() {
return 21;
}
}
public static class Purple extends ShamanSprite {
{
boltType = MagicMissile.SHAMAN_PURPLE;
}
@Override
protected int texOffset() {
return 42;
}
}
}
| 412 | 0.79179 | 1 | 0.79179 | game-dev | MEDIA | 0.988573 | game-dev | 0.690328 | 1 | 0.690328 |
ryzom/ryzomcore | 1,960 | ryzom/tools/leveldesign/georges_convert/type_unit_file_name.cpp | // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// 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, 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 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/>.
#include "stdgeorgesconvert.h"
#include "type_unit_file_name.h"
namespace NLOLDGEORGES
{
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CTypeUnitFileName::CTypeUnitFileName( const CStringEx _sxll, const CStringEx _sxhl, const CStringEx _sxdv, const CStringEx _sxf ) : CTypeUnit( _sxhl, _sxll, _sxdv, _sxf )
{
if( sxformula.empty() )
sxformula = "file name";
}
CTypeUnitFileName::~CTypeUnitFileName()
{
}
CStringEx CTypeUnitFileName::Format( const CStringEx _sxvalue ) const
{
if( _sxvalue.empty() )
return( sxdefaultvalue );
return( _sxvalue );
}
CStringEx CTypeUnitFileName::CalculateResult( const CStringEx _sxbasevalue, const CStringEx _sxvalue ) const
{
if( _sxvalue.empty() )
return( Format( _sxbasevalue ) );
return( Format( _sxvalue ) );
}
void CTypeUnitFileName::SetDefaultValue( const CStringEx _sxdv )
{
sxdefaultvalue = _sxdv;
}
void CTypeUnitFileName::SetLowLimit( const CStringEx _sxll )
{
sxlowlimit = _sxll;
}
void CTypeUnitFileName::SetHighLimit( const CStringEx _sxhl )
{
sxhighlimit = _sxhl;
}
} | 412 | 0.598676 | 1 | 0.598676 | game-dev | MEDIA | 0.397133 | game-dev | 0.648032 | 1 | 0.648032 |
ipc-sim/rigid-ipc | 3,707 | src/ccd/rigid/rigid_trajectory_aabb.cpp | #include "rigid_trajectory_aabb.hpp"
namespace ipc::rigid {
typedef Pose<Interval> PoseI;
VectorMax3I vertex_trajectory_aabb(
const RigidBody& body,
const PoseI& pose_t0, // Pose of body at t=0
const PoseI& pose_t1, // Pose of body at t=1
size_t vertex_id, // In body
const Interval& t)
{
// Compute the pose at time t
PoseI pose = PoseI::interpolate(pose_t0, pose_t1, t);
// Get the world vertex of the edges at time t
return body.world_vertex(pose, vertex_id);
}
VectorMax3I edge_trajectory_aabb(
const RigidBody& body,
const PoseI& pose_t0, // Pose of body at t=0
const PoseI& pose_t1, // Pose of body at t=1
size_t edge_id, // In body
const Interval& t,
const Interval& alpha)
{
// Compute the pose at time t
PoseI pose = PoseI::interpolate(pose_t0, pose_t1, t);
// Get the world vertex of the edges at time t
VectorMax3I e0 = body.world_vertex(pose, body.edges(edge_id, 0));
VectorMax3I e1 = body.world_vertex(pose, body.edges(edge_id, 1));
return (e1 - e0) * alpha + e0;
}
VectorMax3I face_trajectory_aabb(
const RigidBody& body,
const PoseI& pose_t0, // Pose of body at t=0
const PoseI& pose_t1, // Pose of body at t=1
size_t face_id, // In body
const Interval& t,
const Interval& u,
const Interval& v)
{
// Compute the pose at time t
PoseI pose = PoseI::interpolate(pose_t0, pose_t1, t);
// Get the world vertex of the edges at time t
VectorMax3I f0 = body.world_vertex(pose, body.faces(face_id, 0));
VectorMax3I f1 = body.world_vertex(pose, body.faces(face_id, 1));
VectorMax3I f2 = body.world_vertex(pose, body.faces(face_id, 2));
return (f1 - f0) * u + (f2 - f0) * v + f0;
}
VectorMax3I edge_vertex_aabb(
const RigidBody& bodyA, // Body of the vertex
const PoseI& poseA_t0, // Pose of bodyA at t=0
const PoseI& poseA_t1, // Pose of bodyA at t=1
size_t vertex_id, // In bodyA
const RigidBody& bodyB, // Body of the edge
const PoseI& poseB_t0, // Pose of bodyB at t=0
const PoseI& poseB_t1, // Pose of bodyB at t=1
size_t edge_id, // In bodyB
const Interval& t,
const Interval& alpha)
{
return vertex_trajectory_aabb(bodyA, poseA_t0, poseA_t1, vertex_id, t)
- edge_trajectory_aabb(bodyB, poseB_t0, poseB_t1, edge_id, t, alpha);
}
VectorMax3I edge_edge_aabb(
const RigidBody& bodyA, // Body of the first edge
const PoseI& poseA_t0, // Pose of bodyA at t=0
const PoseI& poseA_t1, // Pose of bodyA at t=1
size_t edgeA_id, // In bodyA
const RigidBody& bodyB, // Body of the second edge
const PoseI& poseB_t0, // Pose of bodyB at t=0
const PoseI& poseB_t1, // Pose of bodyB at t=1
size_t edgeB_id, // In bodyB
const Interval& t,
const Interval& alpha,
const Interval& beta)
{
return edge_trajectory_aabb(bodyA, poseA_t0, poseA_t1, edgeA_id, t, alpha)
- edge_trajectory_aabb(bodyB, poseB_t0, poseB_t1, edgeB_id, t, beta);
}
VectorMax3I face_vertex_aabb(
const RigidBody& bodyA, // Body of the vertex
const PoseI& poseA_t0, // Pose of bodyA at t=0
const PoseI& poseA_t1, // Pose of bodyA at t=1
size_t vertex_id, // In bodyA
const RigidBody& bodyB, // Body of the triangle
const PoseI& poseB_t0, // Pose of bodyB at t=0
const PoseI& poseB_t1, // Pose of bodyB at t=1
size_t face_id, // In bodyB
const Interval& t,
const Interval& u,
const Interval& v)
{
return vertex_trajectory_aabb(bodyA, poseA_t0, poseA_t1, vertex_id, t)
- face_trajectory_aabb(bodyB, poseB_t0, poseB_t1, face_id, t, u, v);
}
} // namespace ipc::rigid
| 412 | 0.844291 | 1 | 0.844291 | game-dev | MEDIA | 0.68458 | game-dev | 0.68077 | 1 | 0.68077 |
H4PM/Elywing | 3,316 | src/pocketmine/block/PressurePlate.php | <?php
/*
*
* _____ _____ __ _ _ _____ __ __ _____
* / ___| | ____| | \ | | | | / ___/ \ \ / / / ___/
* | | | |__ | \| | | | | |___ \ \/ / | |___
* | | _ | __| | |\ | | | \___ \ \ / \___ \
* | |_| | | |___ | | \ | | | ___| | / / ___| |
* \_____/ |_____| |_| \_| |_| /_____/ /_/ /_____/
*
* 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.
*
* @author iTX Technologies
* @link https://itxtech.org
*
*/
namespace pocketmine\block;
use pocketmine\entity\Entity;
use pocketmine\item\Item;
use pocketmine\math\Math;
use pocketmine\math\Vector3;
use pocketmine\level\Level;
use pocketmine\level\sound\GenericSound;
use pocketmine\Player;
class PressurePlate extends RedstoneSource{
protected $activateTime = 0;
protected $canActivate = true;
public function __construct($meta = 0){
$this->meta = $meta;
}
public function hasEntityCollision(){
return true;
}
public function onEntityCollide(Entity $entity){
if($this->getLevel()->getServer()->redstoneEnabled and $this->canActivate){
if(!$this->isActivated()){
$this->meta = 1;
$this->getLevel()->setBlock($this, $this, true, false);
$this->getLevel()->addSound(new GenericSound($this, 1000));
}
if(!$this->isActivated() or ($this->isActivated() and ($this->getLevel()->getServer()->getTick() % 30) == 0)){
$this->activate();
}
}
}
public function isActivated(Block $from = null){
return ($this->meta == 0) ? false : true;
}
public function onUpdate($type){
if($type === Level::BLOCK_UPDATE_NORMAL){
$below = $this->getSide(Vector3::SIDE_DOWN);
if($below instanceof Transparent){
$this->getLevel()->useBreakOn($this);
return Level::BLOCK_UPDATE_NORMAL;
}
}
/*if($type == Level::BLOCK_UPDATE_SCHEDULED){
if($this->isActivated()){
if(!$this->isCollided()){
$this->meta = 0;
$this->getLevel()->setBlock($this, $this, true, false);
$this->deactivate();
return Level::BLOCK_UPDATE_SCHEDULED;
}
}
}*/
return true;
}
public function checkActivation(){
if($this->isActivated()){
if((($this->getLevel()->getServer()->getTick() - $this->activateTime)) >= 3){
$this->meta = 0;
$this->getLevel()->setBlock($this, $this, true, false);
$this->deactivate();
}
}
}
/*public function isCollided(){
foreach($this->getLevel()->getEntities() as $p){
$blocks = $p->getBlocksAround();
if(isset($blocks[Level::blockHash($this->x, $this->y, $this->z)])) return true;
}
return false;
}*/
public function place(Item $item, Block $block, Block $target, $face, $fx, $fy, $fz, Player $player = null){
$below = $this->getSide(Vector3::SIDE_DOWN);
if($below instanceof Transparent) return;
else $this->getLevel()->setBlock($block, $this, true, false);
}
public function onBreak(Item $item){
if($this->isActivated()){
$this->meta = 0;
$this->deactivate();
}
$this->canActivate = false;
$this->getLevel()->setBlock($this, new Air(), true);
}
public function getHardness() {
return 0.5;
}
public function getResistance(){
return 2.5;
}
}
| 412 | 0.980606 | 1 | 0.980606 | game-dev | MEDIA | 0.94014 | game-dev | 0.982463 | 1 | 0.982463 |
Suprcode/Zircon | 2,795 | ServerLibrary/Models/Monsters/ArchLichTaedu.cs | using Library;
using Server.Envir;
using System;
using System.Collections.Generic;
using S = Library.Network.ServerPackets;
namespace Server.Models.Monsters
{
public class ArchLichTaedu : MonsterObject
{
public int MaxStage = 7;
public int Stage;
public int MinSpawn = 20;
public int RandomSpawn = 5;
public ArchLichTaedu()
{
AvoidFireWall = false;
MaxMinions = 50;
}
protected override void OnSpawned()
{
base.OnSpawned();
Stage = MaxStage;
}
public override void Process()
{
base.Process();
if (Dead) return;
if (CurrentHP * MaxStage / Stats[Stat.Health] >= Stage || Stage <= 0) return;
Stage--;
ActionTime += TimeSpan.FromSeconds(1);
Broadcast(new S.ObjectShow { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation });
SpawnMinions(MinSpawn, RandomSpawn, Target);
}
public override void ProcessTarget()
{
if (Target == null) return;
if (!InAttackRange())
{
if (CanAttack)
{
if (SEnvir.Random.Next(2) == 0)
RangeAttack();
}
if (CurrentLocation == Target.CurrentLocation)
{
MirDirection direction = (MirDirection)SEnvir.Random.Next(8);
int rotation = SEnvir.Random.Next(2) == 0 ? 1 : -1;
for (int d = 0; d < 8; d++)
{
if (Walk(direction)) break;
direction = Functions.ShiftDirection(direction, rotation);
}
}
else
MoveTo(Target.CurrentLocation);
}
if (!CanAttack) return;
if (SEnvir.Random.Next(5) > 0)
{
if (InAttackRange())
Attack();
}
else RangeAttack();
}
public void RangeAttack()
{
Direction = Functions.DirectionFromPoint(CurrentLocation, Target.CurrentLocation);
UpdateAttackTime();
Broadcast(new S.ObjectRangeAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, Targets = new List<uint> { Target.ObjectID } });
ActionList.Add(new DelayedAction(
SEnvir.Now.AddMilliseconds(400),
ActionType.DelayAttack,
Target,
GetDC(),
AttackElement));
}
}
}
| 412 | 0.969959 | 1 | 0.969959 | game-dev | MEDIA | 0.905636 | game-dev | 0.973521 | 1 | 0.973521 |
ferrocene/criticalup | 1,033 | crates/criticalup-cli/src/cli/subcommand/link/mod.rs | // SPDX-FileCopyrightText: The Ferrocene Developers
// SPDX-License-Identifier: MIT OR Apache-2.0
mod create;
mod remove;
mod show;
use crate::cli::CommandExecute;
use crate::errors::Error;
use crate::Context;
use clap::{Parser, Subcommand};
use create::LinkCreate;
use remove::LinkRemove;
use show::LinkShow;
#[derive(Subcommand, Debug)]
pub(crate) enum LinkSubcommand {
Show(LinkShow),
Create(LinkCreate),
Remove(LinkRemove),
}
/// Manage `rustup` toolchain linking support
#[derive(Debug, Parser)]
pub(crate) struct Link {
#[command(subcommand)]
command: LinkSubcommand,
}
impl CommandExecute for Link {
#[tracing::instrument(level = "debug", skip_all)]
async fn execute(self, ctx: &Context) -> Result<(), Error> {
match self.command {
LinkSubcommand::Show(show) => return show.execute(ctx).await,
LinkSubcommand::Create(create) => return create.execute(ctx).await,
LinkSubcommand::Remove(remove) => return remove.execute(ctx).await,
}
}
}
| 412 | 0.805261 | 1 | 0.805261 | game-dev | MEDIA | 0.304 | game-dev | 0.786358 | 1 | 0.786358 |
ProjectDreamland/area51 | 6,199 | Support/PhysicsMgr/CollisionShape.cpp | //==============================================================================
//
// CollisionShape.cpp
//
//==============================================================================
//==============================================================================
// INCLUDES
//==============================================================================
#include "Entropy.hpp"
#include "CollisionShape.hpp"
#include "PhysicsMgr.hpp"
//==============================================================================
// SPHERE FUNCTIONS
//==============================================================================
#ifdef ENABLE_PHYSICS_DEBUG
collision_shape::sphere::sphere()
{
PHYSICS_DEBUG_DYNAMIC_MEM_ALLOC( sizeof( collision_shape::sphere ) );
}
//==============================================================================
collision_shape::sphere::~sphere()
{
PHYSICS_DEBUG_DYNAMIC_MEM_FREE( sizeof( collision_shape::sphere ) );
}
#endif //#ifdef ENABLE_PHYSICS_DEBUG
//==============================================================================
// SHAPE FUNCTIONS
//==============================================================================
#ifdef ENABLE_PHYSICS_DEBUG
collision_shape::collision_shape() :
m_Type ( collision_shape::TYPE_NULL ),
m_pOwner ( NULL ),
m_Radius ( 0.0f )
{
PHYSICS_DEBUG_DYNAMIC_MEM_ALLOC( sizeof( collision_shape ) );
}
//==============================================================================
collision_shape::~collision_shape()
{
PHYSICS_DEBUG_DYNAMIC_MEM_FREE( sizeof( collision_shape ) );
}
#endif
//==============================================================================
void collision_shape::AddSphere( const vector3& Offset )
{
// Create new sphere
sphere& Sphere = m_Spheres.Append();
// Init sphere
Sphere.m_Offset = Offset;
Sphere.m_CollFreePos.Zero();
Sphere.m_PrevPos.Zero();
Sphere.m_CurrPos.Zero();
#ifdef ENABLE_PHYSICS_DEBUG
Sphere.m_bCollision = FALSE;
#endif
}
//==============================================================================
// BBox functions
//==============================================================================
bbox collision_shape::ComputeLocalBBox( void ) const
{
// Compute local bbox
bbox LocalBBox;
LocalBBox.Clear();
// Add all spheres to bounds
for( s32 i = 0; i < m_Spheres.GetCount(); i++ )
{
// Get sphere
sphere& Sphere = m_Spheres[i];
// Add local sphere center to local bbox
LocalBBox += Sphere.m_Offset;
}
// Take sphere radius and float error into account
f32 Inflate = m_Radius + 1.0f;
LocalBBox.Inflate( Inflate, Inflate, Inflate );
return LocalBBox;
}
//==============================================================================
bbox collision_shape::ComputeWorldBBox( void ) const
{
// Clear world bbox
bbox WorldBBox;
WorldBBox.Clear();
// Add all spheres to bounds
f32 Radius = m_Radius + 1.0f;
for( s32 i = 0; i < m_Spheres.GetCount(); i++ )
{
// Lookup sphere info
sphere& Sphere = m_Spheres[i];
// Compute movement bbox
bbox MoveBBox( Sphere.m_PrevPos, Sphere.m_CurrPos );
MoveBBox.Inflate( Radius, Radius, Radius );
// Compute movement sphere bounds
bbox MoveSphereBBox( MoveBBox.GetCenter(), MoveBBox.GetRadius() );
// Compute collision bbox
bbox CollBBox( Sphere.m_CollFreePos, Radius );
// Update world bounds
WorldBBox += MoveSphereBBox;
WorldBBox += CollBBox;
}
// For float error
WorldBBox.Inflate( 1.0f, 1.0f, 1.0f );
return WorldBBox;
}
//==============================================================================
void collision_shape::SetL2W( const matrix4& L2W )
{
ASSERT( L2W.IsValid() );
// Put spheres and collision pos into world space
for( s32 i = 0; i < m_Spheres.GetCount(); i++ )
{
// Look up sphere
sphere& Sphere = m_Spheres[i];
// Compute world position
vector3 WorldPos = L2W * Sphere.m_Offset;
Sphere.m_CollFreePos = WorldPos;
Sphere.m_PrevPos = WorldPos;
Sphere.m_CurrPos = WorldPos;
}
}
//==============================================================================
void collision_shape::SetL2W( const matrix4& PrevL2W, const matrix4& NextL2W )
{
ASSERT( PrevL2W.IsValid() );
ASSERT( NextL2W.IsValid() );
// Put spheres into world space
for( s32 i = 0; i < m_Spheres.GetCount(); i++ )
{
// Look up sphere
sphere& Sphere = m_Spheres[i];
// Compute world positions
Sphere.m_PrevPos = PrevL2W * Sphere.m_Offset;
Sphere.m_CurrPos = NextL2W * Sphere.m_Offset;
}
}
//==============================================================================
// Render functions
//==============================================================================
#ifdef ENABLE_PHYSICS_DEBUG
void collision_shape::DebugClearCollision( void )
{
// Clear sphere collision rendering
s32 nSpheres = GetNSpheres();
for( s32 i = 0; i < nSpheres; i++ )
{
collision_shape::sphere& Sphere = GetSphere( i );
Sphere.m_bCollision = FALSE;
}
}
//==============================================================================
void collision_shape::DebugRender( const matrix4& L2W, xcolor Color )
{
// Render spheres
draw_ClearL2W();
s32 nSpheres = GetNSpheres();
for( s32 i = 0; i < nSpheres; i++ )
{
collision_shape::sphere& Sphere = GetSphere( i );
if( Sphere.m_bCollision )
draw_Sphere( Sphere.m_CollFreePos, m_Radius, XCOLOR_RED );
else
draw_Sphere( Sphere.m_CollFreePos, m_Radius, XCOLOR_YELLOW );
draw_Sphere( Sphere.m_CurrPos, m_Radius, XCOLOR_GREEN );
}
// Render world bbox
draw_SetL2W( L2W );
draw_BBox( ComputeLocalBBox(), Color );
draw_ClearL2W();
}
#endif //#ifdef ENABLE_PHYSICS_DEBUG
//==============================================================================
| 412 | 0.767186 | 1 | 0.767186 | game-dev | MEDIA | 0.909677 | game-dev | 0.950922 | 1 | 0.950922 |
liuxq/TestGame | 2,588 | Assets/InventoryMaster/Editor/StorageInventoryEditor.cs | using UnityEngine;
using System.Collections;
using UnityEditor;
using UnityEngine.UI;
using UnityEngine.EventSystems;
[CustomEditor(typeof(StorageInventory))]
public class StorageInventoryEditor : Editor
{
StorageInventory inv;
private int itemID;
private int itemValue = 1;
private int imageTypeIndex;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void OnEnable()
{
inv = target as StorageInventory;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
serializedObject.Update();
addItemGUI();
serializedObject.ApplyModifiedProperties();
}
void addItemGUI() //add a item to the inventory through the inspector
{
inv.setImportantVariables();
EditorGUILayout.BeginHorizontal(); //starting horizontal GUI elements
ItemDataBaseList inventoryItemList = (ItemDataBaseList)Resources.Load("ItemDatabase"); //loading the itemdatabase
string[] items = new string[inventoryItemList.itemList.Count]; //create a string array in length of the itemcount
for (int i = 1; i < items.Length; i++) //go through the item array
{
items[i] = inventoryItemList.itemList[i].itemName; //and paste all names into the array
}
itemID = EditorGUILayout.Popup("", itemID, items, EditorStyles.popup); //create a popout with all itemnames in it and save the itemID of it
itemValue = EditorGUILayout.IntField("", itemValue, GUILayout.Width(40));
GUI.color = Color.green; //set the color of all following guielements to green
if (GUILayout.Button("Add Item")) //creating button with name "AddItem"
{
inv.addItemToStorage(itemID, itemValue);
}
EditorGUILayout.EndHorizontal(); //end the horizontal gui layout
}
}
| 412 | 0.637214 | 1 | 0.637214 | game-dev | MEDIA | 0.901279 | game-dev | 0.796561 | 1 | 0.796561 |
Creators-of-Create/Create | 2,381 | src/main/java/com/simibubi/create/content/kinetics/drill/DrillRenderer.java | package com.simibubi.create.content.kinetics.drill;
import com.simibubi.create.AllPartialModels;
import com.simibubi.create.content.contraptions.behaviour.MovementContext;
import com.simibubi.create.content.contraptions.render.ContraptionMatrices;
import com.simibubi.create.content.kinetics.base.KineticBlockEntityRenderer;
import com.simibubi.create.foundation.virtualWorld.VirtualRenderWorld;
import net.createmod.catnip.render.CachedBuffers;
import net.createmod.catnip.render.SuperByteBuffer;
import net.createmod.catnip.animation.AnimationTickHolder;
import net.createmod.catnip.math.VecHelper;
import net.createmod.catnip.math.AngleHelper;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
import net.minecraft.core.Direction;
import net.minecraft.world.level.block.state.BlockState;
public class DrillRenderer extends KineticBlockEntityRenderer<DrillBlockEntity> {
public DrillRenderer(BlockEntityRendererProvider.Context context) {
super(context);
}
@Override
protected SuperByteBuffer getRotatedModel(DrillBlockEntity be, BlockState state) {
return CachedBuffers.partialFacing(AllPartialModels.DRILL_HEAD, state);
}
public static void renderInContraption(MovementContext context, VirtualRenderWorld renderWorld,
ContraptionMatrices matrices, MultiBufferSource buffer) {
BlockState state = context.state;
SuperByteBuffer superBuffer = CachedBuffers.partial(AllPartialModels.DRILL_HEAD, state);
Direction facing = state.getValue(DrillBlock.FACING);
float speed = (float) (context.contraption.stalled
|| !VecHelper.isVecPointingTowards(context.relativeMotion, facing
.getOpposite()) ? context.getAnimationSpeed() : 0);
float time = AnimationTickHolder.getRenderTime() / 20;
float angle = (float) (((time * speed) % 360));
superBuffer
.transform(matrices.getModel())
.center()
.rotateYDegrees(AngleHelper.horizontalAngle(facing))
.rotateXDegrees(AngleHelper.verticalAngle(facing))
.rotateZDegrees(angle)
.uncenter()
.light(LevelRenderer.getLightColor(renderWorld, context.localPos))
.useLevelLight(context.world, matrices.getWorld())
.renderInto(matrices.getViewProjection(), buffer.getBuffer(RenderType.solid()));
}
}
| 412 | 0.871649 | 1 | 0.871649 | game-dev | MEDIA | 0.872729 | game-dev,graphics-rendering | 0.938593 | 1 | 0.938593 |
DanceManiac/Advanced-X-Ray-Public | 9,473 | SourcesAXR/xrGameCS/Entity.cpp | // Entity.cpp: implementation of the CEntity class.
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "hudmanager.h"
#include "Entity.h"
#include "actor.h"
#include "xrserver_objects_alife_monsters.h"
#include "entity.h"
#include "level.h"
#include "seniority_hierarchy_holder.h"
#include "team_hierarchy_holder.h"
#include "squad_hierarchy_holder.h"
#include "group_hierarchy_holder.h"
#include "../Include/xrRender/Kinematics.h"
#include "monster_community.h"
#include "ai_space.h"
#include "alife_simulator.h"
#include "alife_time_manager.h"
#define BODY_REMOVE_TIME 600000
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CEntity::CEntity()
{
m_registered_member = false;
}
CEntity::~CEntity()
{
xr_delete (m_entity_condition);
}
CEntityConditionSimple *CEntity::create_entity_condition(CEntityConditionSimple* ec)
{
if(!ec)
m_entity_condition = xr_new<CEntityConditionSimple>();
else
m_entity_condition = smart_cast<CEntityCondition*>(ec);
return m_entity_condition;
}
void CEntity::OnEvent (NET_Packet& P, u16 type)
{
inherited::OnEvent (P,type);
switch (type)
{
case GE_DIE:
{
u16 id;
u32 cl;
P.r_u16 (id);
P.r_u32 (cl);
CObject *who = Level().Objects.net_Find (id);
if (who && !IsGameTypeSingle())
{
if (this!=who) /*if(bDebug) */ Msg( "%s killed by %s ...", cName().c_str(), who->cName().c_str() );
else /*if(bDebug) */ Msg( "%s dies himself ...", cName().c_str() );
}
Die (who);
}
break;
}
}
void CEntity::Die(CObject* who)
{
if (!AlreadyDie()) set_death_time();
set_ready_to_save ();
SetfHealth (-1.f);
if(IsGameTypeSingle())
{
VERIFY (m_registered_member);
}
m_registered_member = false;
if (IsGameTypeSingle())
Level().seniority_holder().team(g_Team()).squad(g_Squad()).group(g_Group()).unregister_member(this);
}
//
float CEntity::CalcCondition(float hit)
{
// If Local() - perform some logic
if (Local() && g_Alive()) {
SetfHealth (GetfHealth()-hit);
SetfHealth ((GetfHealth()<-1000)?-1000:GetfHealth());
}
return hit;
}
//void CEntity::Hit (float perc, Fvector &dir, CObject* who, s16 element,Fvector position_in_object_space, float impulse, ALife::EHitType hit_type)
void CEntity::Hit (SHit* pHDS)
{
// if (bDebug) Log("Process HIT: ", *cName());
// *** process hit calculations
// Calc impulse
Fvector vLocalDir;
float m = pHDS->dir.magnitude();
VERIFY (m>EPS);
// convert impulse into local coordinate system
Fmatrix mInvXForm;
mInvXForm.invert (XFORM());
mInvXForm.transform_dir (vLocalDir,pHDS->dir);
vLocalDir.invert ();
// hit impulse
if(pHDS->impulse) HitImpulse (pHDS->impulse,pHDS->dir,vLocalDir); // @@@: WT
// Calc amount (correct only on local player)
float lost_health = CalcCondition(pHDS->damage());
// Signal hit
if(BI_NONE!=pHDS->bone()) HitSignal(lost_health,vLocalDir,pHDS->who,pHDS->boneID);
// If Local() - perform some logic
if (Local() && !g_Alive() && !AlreadyDie() && (m_killer_id == ALife::_OBJECT_ID(-1))) {
KillEntity (pHDS->whoID);
}
//must be last!!! @slipch
inherited::Hit(pHDS);
}
void CEntity::Load (LPCSTR section)
{
inherited::Load (section);
setVisible (FALSE);
// Team params
id_Team = READ_IF_EXISTS(pSettings,r_s32,section,"team",-1);
id_Squad = READ_IF_EXISTS(pSettings,r_s32,section,"squad",-1);
id_Group = READ_IF_EXISTS(pSettings,r_s32,section,"group",-1);
#pragma todo("Jim to Dima: no specific figures or comments needed")
m_fMorale = 66.f;
//
m_dwBodyRemoveTime = READ_IF_EXISTS(pSettings,r_u32,section,"body_remove_time",BODY_REMOVE_TIME);
//////////////////////////////////////
}
BOOL CEntity::net_Spawn (CSE_Abstract* DC)
{
m_level_death_time = 0;
m_game_death_time = 0;
m_killer_id = ALife::_OBJECT_ID(-1);
CSE_Abstract *e = (CSE_Abstract*)(DC);
CSE_ALifeCreatureAbstract *E = smart_cast<CSE_ALifeCreatureAbstract*>(e);
// Initialize variables
if (E) {
SetfHealth (E->get_health());
R_ASSERT2(!((E->get_killer_id() != ALife::_OBJECT_ID(-1)) && g_Alive()), make_string("server entity [%s][%d] has an killer [%d] and not dead",
E->name_replace(), E->ID, E->get_killer_id()).c_str());
m_killer_id = E->get_killer_id();
if (m_killer_id == ID())
m_killer_id = ALife::_OBJECT_ID(-1);
}
else
SetfHealth (1.0f);
// load damage params
if (!E) {
// Car or trader only!!!!
CSE_ALifeCar *C = smart_cast<CSE_ALifeCar*>(e);
CSE_ALifeTrader *T = smart_cast<CSE_ALifeTrader*>(e);
CSE_ALifeHelicopter *H = smart_cast<CSE_ALifeHelicopter*>(e);
R_ASSERT2 (C||T||H,"Invalid entity (no inheritance from CSE_CreatureAbstract, CSE_ALifeItemCar and CSE_ALifeTrader and CSE_ALifeHelicopter)!");
id_Team = id_Squad = id_Group = 0;
}
else {
id_Team = E->g_team();
id_Squad = E->g_squad();
id_Group = E->g_group();
CSE_ALifeMonsterBase *monster = smart_cast<CSE_ALifeMonsterBase*>(E);
if (monster) {
MONSTER_COMMUNITY monster_community;
monster_community.set (pSettings->r_string(*cNameSect(), "species"));
if(monster_community.team() != 255)
id_Team = monster_community.team();
}
}
if (g_Alive() && IsGameTypeSingle()) {
m_registered_member = true;
Level().seniority_holder().team(g_Team()).squad(g_Squad()).group(g_Group()).register_member(this);
++Level().seniority_holder().team(g_Team()).squad(g_Squad()).group(g_Group()).m_dwAliveCount;
}
if(!g_Alive())
{
m_level_death_time = Device.dwTimeGlobal;
m_game_death_time = E->m_game_death_time;;
}
if (!inherited::net_Spawn(DC))
return (FALSE);
// SetfHealth (E->fHealth);
IKinematics* pKinematics=smart_cast<IKinematics*>(Visual());
CInifile* ini = NULL;
if(pKinematics) ini = pKinematics->LL_UserData();
if (ini) {
if (ini->section_exist("damage_section") && !use_simplified_visual())
CDamageManager::reload(pSettings->r_string("damage_section","damage"),ini);
CParticlesPlayer::LoadParticles(pKinematics);
}
return TRUE;
}
void CEntity::net_Destroy ()
{
if (m_registered_member) {
m_registered_member = false;
if (IsGameTypeSingle())
Level().seniority_holder().team(g_Team()).squad(g_Squad()).group(g_Group()).unregister_member(this);
}
inherited::net_Destroy ();
set_ready_to_save ();
}
void CEntity::KillEntity(u16 whoID)
{
if (whoID != ID()) {
#ifdef DEBUG
if (m_killer_id != ALife::_OBJECT_ID(-1)) {
Msg ("! Entity [%s][%s] already has killer with id %d, but new killer id arrived - %d",*cNameSect(),*cName(),m_killer_id,whoID);
CObject *old_killer = Level().Objects.net_Find(m_killer_id);
Msg ("! Old killer is %s",old_killer ? *old_killer->cName() : "unknown");
CObject *new_killer = Level().Objects.net_Find(whoID);
Msg ("! New killer is %s",new_killer ? *new_killer->cName() : "unknown");
VERIFY (m_killer_id == ALife::_OBJECT_ID(-1));
}
#endif
}
else {
if (m_killer_id != ALife::_OBJECT_ID(-1))
return;
}
m_killer_id = whoID;
set_death_time ();
if (!getDestroy()){
NET_Packet P;
u_EventGen (P,GE_DIE,ID());
P.w_u16 (u16(whoID));
P.w_u32 (0);
if (OnServer())
u_EventSend (P, net_flags(TRUE, TRUE, FALSE, TRUE));
}
};
//void CEntity::KillEntity(CObject* who)
//{
// VERIFY (who);
// if (who) KillEntity(who->ID());
//}
void CEntity::reinit ()
{
inherited::reinit ();
}
void CEntity::reload (LPCSTR section)
{
inherited::reload (section);
if (!use_simplified_visual())
CDamageManager::reload (section,"damage",pSettings);
}
void CEntity::set_death_time ()
{
m_level_death_time = Device.dwTimeGlobal;
m_game_death_time = ai().get_alife() ? ai().alife().time_manager().game_time() : Level().GetGameTime();
}
bool CEntity::IsFocused ()const { return (smart_cast<const CEntity*>(g_pGameLevel->CurrentEntity())==this); }
bool CEntity::IsMyCamera ()const { return (smart_cast<const CEntity*>(g_pGameLevel->CurrentViewEntity())==this); }
void CEntity::set_ready_to_save ()
{
}
DLL_Pure *CEntity::_construct ()
{
inherited::_construct ();
CDamageManager::_construct ();
m_entity_condition = create_entity_condition(NULL);
return (this);
}
const u32 FORGET_KILLER_TIME = 180000;
void CEntity::shedule_Update (u32 dt)
{
inherited::shedule_Update (dt);
if (!getDestroy() && !g_Alive() && (m_killer_id != u16(-1))) {
if (Device.dwTimeGlobal > m_level_death_time + FORGET_KILLER_TIME) {
m_killer_id = u16(-1);
NET_Packet P;
u_EventGen (P,GE_ASSIGN_KILLER,ID());
P.w_u16 (u16(-1));
if (IsGameTypeSingle()) u_EventSend (P);
}
}
}
void CEntity::on_before_change_team ()
{
}
void CEntity::on_after_change_team ()
{
}
void CEntity::ChangeTeam(int team, int squad, int group)
{
if ((team == g_Team()) && (squad == g_Squad()) && (group == g_Group())) return;
VERIFY2 (g_Alive(), "Try to change team of a dead object");
if(IsGameTypeSingle())
{
VERIFY (m_registered_member);
}
// remove from current team
on_before_change_team ();
Level().seniority_holder().team(g_Team()).squad(g_Squad()).group(g_Group()).unregister_member (this);
id_Team = team;
id_Squad = squad;
id_Group = group;
// add to new team
Level().seniority_holder().team(g_Team()).squad(g_Squad()).group(g_Group()).register_member (this);
on_after_change_team ();
}
| 412 | 0.975936 | 1 | 0.975936 | game-dev | MEDIA | 0.973854 | game-dev | 0.982539 | 1 | 0.982539 |
LunarClient/Apollo | 6,448 | example/bukkit/proto/src/main/java/com/lunarclient/apollo/example/proto/util/ProtobufPacketUtil.java | /*
* This file is part of Apollo, licensed under the MIT License.
*
* Copyright (c) 2023 Moonsworth
*
* 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.lunarclient.apollo.example.proto.util;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.protobuf.Any;
import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.ListValue;
import com.google.protobuf.Value;
import com.lunarclient.apollo.configurable.v1.ConfigurableSettings;
import com.lunarclient.apollo.configurable.v1.OverrideConfigurableSettingsMessage;
import com.lunarclient.apollo.example.ApolloExamplePlugin;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public final class ProtobufPacketUtil {
private static final List<String> APOLLO_MODULES = Arrays.asList("limb", "beam", "border", "chat", "colored_fire", "combat", "cooldown",
"entity", "glow", "hologram", "mod_setting", "nametag", "nick_hider", "notification", "packet_enrichment", "rich_presence",
"server_rule", "staff_mod", "stopwatch", "team", "title", "tnt_countdown", "transfer", "vignette", "waypoint"
);
// Module Id -> Option key -> Value
private static final Table<String, String, Value> CONFIG_MODULE_PROPERTIES = HashBasedTable.create();
static {
// Module Options that the client needs to notified about, these properties are sent with the enable module packet
// While using the Apollo plugin this would be equivalent to modifying the config.yml
CONFIG_MODULE_PROPERTIES.put("combat", "disable-miss-penalty", Value.newBuilder().setBoolValue(false).build());
CONFIG_MODULE_PROPERTIES.put("server_rule", "competitive-game", Value.newBuilder().setBoolValue(false).build());
CONFIG_MODULE_PROPERTIES.put("server_rule", "competitive-commands", Value.newBuilder().setListValue(
ListValue.newBuilder().addAllValues(Arrays.asList(
Value.newBuilder().setStringValue("/server").build(),
Value.newBuilder().setStringValue("/servers").build(),
Value.newBuilder().setStringValue("/hub").build()))
.build()
).build());
CONFIG_MODULE_PROPERTIES.put("server_rule", "disable-shaders", Value.newBuilder().setBoolValue(false).build());
CONFIG_MODULE_PROPERTIES.put("server_rule", "disable-chunk-reloading", Value.newBuilder().setBoolValue(false).build());
CONFIG_MODULE_PROPERTIES.put("server_rule", "disable-broadcasting", Value.newBuilder().setBoolValue(false).build());
CONFIG_MODULE_PROPERTIES.put("server_rule", "anti-portal-traps", Value.newBuilder().setBoolValue(true).build());
CONFIG_MODULE_PROPERTIES.put("server_rule", "override-brightness", Value.newBuilder().setBoolValue(false).build());
CONFIG_MODULE_PROPERTIES.put("server_rule", "brightness", Value.newBuilder().setNumberValue(50).build());
CONFIG_MODULE_PROPERTIES.put("server_rule", "override-nametag-render-distance", Value.newBuilder().setBoolValue(false).build());
CONFIG_MODULE_PROPERTIES.put("server_rule", "nametag-render-distance", Value.newBuilder().setNumberValue(64).build());
CONFIG_MODULE_PROPERTIES.put("server_rule", "override-max-chat-length", Value.newBuilder().setBoolValue(false).build());
CONFIG_MODULE_PROPERTIES.put("server_rule", "max-chat-length", Value.newBuilder().setNumberValue(256).build());
CONFIG_MODULE_PROPERTIES.put("tnt_countdown", "tnt-ticks", Value.newBuilder().setNumberValue(80).build());
CONFIG_MODULE_PROPERTIES.put("title", "clear-title-on-server-switch", Value.newBuilder().setBoolValue(false).build());
CONFIG_MODULE_PROPERTIES.put("waypoint", "server-handles-waypoints", Value.newBuilder().setBoolValue(false).build());
}
public static void enableModules(Player player) {
List<ConfigurableSettings> settings = APOLLO_MODULES.stream()
.map(module -> createModuleMessage(module, CONFIG_MODULE_PROPERTIES.row(module)))
.collect(Collectors.toList());
OverrideConfigurableSettingsMessage message = OverrideConfigurableSettingsMessage
.newBuilder()
.addAllConfigurableSettings(settings)
.build();
ProtobufPacketUtil.sendPacket(player, message);
}
public static ConfigurableSettings createModuleMessage(String module, Map<String, Value> properties) {
ConfigurableSettings.Builder moduleBuilder = ConfigurableSettings.newBuilder()
.setApolloModule(module)
.setEnable(true);
if (properties != null) {
moduleBuilder.putAllProperties(properties);
}
return moduleBuilder.build();
}
public static void sendPacket(Player player, GeneratedMessageV3 message) {
byte[] bytes = Any.pack(message).toByteArray();
player.sendPluginMessage(ApolloExamplePlugin.getInstance(), "lunar:apollo", bytes);
}
public static void broadcastPacket(GeneratedMessageV3 message) {
byte[] bytes = Any.pack(message).toByteArray();
Bukkit.getOnlinePlayers().forEach(player ->
player.sendPluginMessage(ApolloExamplePlugin.getInstance(), "lunar:apollo", bytes));
}
private ProtobufPacketUtil() {
}
}
| 412 | 0.88187 | 1 | 0.88187 | game-dev | MEDIA | 0.906306 | game-dev | 0.709926 | 1 | 0.709926 |
DSpace/dspace-angular | 3,905 | src/app/shared/form/chips/chips.component.ts | import {
CdkDrag,
CdkDragDrop,
CdkDropList,
moveItemInArray,
} from '@angular/cdk/drag-drop';
import {
AsyncPipe,
NgClass,
} from '@angular/common';
import {
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnChanges,
Output,
SimpleChanges,
} from '@angular/core';
import {
NgbTooltip,
NgbTooltipModule,
} from '@ng-bootstrap/ng-bootstrap';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import isObject from 'lodash/isObject';
import { BehaviorSubject } from 'rxjs';
import { AuthorityConfidenceStateDirective } from '../directives/authority-confidence-state.directive';
import { Chips } from './models/chips.model';
import { ChipsItem } from './models/chips-item.model';
@Component({
selector: 'ds-chips',
styleUrls: ['./chips.component.scss'],
templateUrl: './chips.component.html',
imports: [
AsyncPipe,
AuthorityConfidenceStateDirective,
CdkDrag,
CdkDropList,
NgbTooltipModule,
NgClass,
TranslateModule,
],
standalone: true,
})
export class ChipsComponent implements OnChanges {
@Input() chips: Chips;
@Input() wrapperClass: string;
@Input() editable = true;
@Input() showIcons = false;
@Output() selected: EventEmitter<number> = new EventEmitter<number>();
@Output() remove: EventEmitter<number> = new EventEmitter<number>();
@Output() change: EventEmitter<any> = new EventEmitter<any>();
isDragging: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
dragged = -1;
tipText: string[];
constructor(
private cdr: ChangeDetectorRef,
private translate: TranslateService) {
}
ngOnChanges(changes: SimpleChanges) {
if (changes.chips && !changes.chips.isFirstChange()) {
this.chips = changes.chips.currentValue;
}
}
chipsSelected(event: Event, index: number) {
event.preventDefault();
if (this.editable) {
this.chips.getChips().forEach((item: ChipsItem, i: number) => {
if (i === index) {
item.setEditMode();
} else {
item.unsetEditMode();
}
});
this.selected.emit(index);
}
}
removeChips(event: Event, index: number) {
event.preventDefault();
event.stopPropagation();
// Can't remove if this element is in editMode
if (!this.chips.getChipByIndex(index).editMode) {
this.chips.remove(this.chips.getChipByIndex(index));
}
}
onDrag(index) {
this.isDragging.next(true);
this.dragged = index;
}
onDrop(event: CdkDragDrop<ChipsItem[]>) {
moveItemInArray(this.chips.chipsItems.getValue(), event.previousIndex, event.currentIndex);
this.dragged = -1;
this.chips.updateOrder();
this.isDragging.next(false);
}
showTooltip(tooltip: NgbTooltip, index, field?) {
tooltip.close();
if (this.isDragging.value) {
return;
}
const chipsItem = this.chips.getChipByIndex(index);
const textToDisplay: string[] = [];
if (!chipsItem.editMode && this.dragged === -1) {
if (field) {
if (isObject(chipsItem.item[field])) {
textToDisplay.push(chipsItem.item[field].display);
if (chipsItem.item[field].hasOtherInformation()) {
Object.keys(chipsItem.item[field].otherInformation)
.forEach((otherField) => {
this.translate.get('form.other-information.' + otherField)
.subscribe((label) => {
textToDisplay.push(label + ': ' + chipsItem.item[field].otherInformation[otherField]);
});
});
}
} else {
textToDisplay.push(chipsItem.item[field]);
}
} else {
textToDisplay.push(chipsItem.display);
}
this.cdr.detectChanges();
if (!chipsItem.hasIcons() || !chipsItem.hasVisibleIcons() || field) {
this.tipText = textToDisplay;
tooltip.open();
}
}
}
}
| 412 | 0.836217 | 1 | 0.836217 | game-dev | MEDIA | 0.407718 | game-dev | 0.911493 | 1 | 0.911493 |
TheAnswer/Core3 | 2,540 | MMOCoreORB/src/server/zone/objects/tangible/misc/DeadEyePrototypeImplementation.cpp | /*
* DeadEyePrototypeImplementation.cpp
*
* Created on: 6/24/2022
* Author: H
*/
#include "server/zone/objects/tangible/misc/DeadEyePrototype.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/packets/scene/AttributeListMessage.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
void DeadEyePrototypeImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) {
if (player == nullptr)
return;
}
int DeadEyePrototypeImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {
if (player == nullptr)
return 0;
if (!isASubChildOf(player))
return 0;
if (selectedID != 20) {
return 0;
}
if (player->isDead() || player->isIncapacitated())
return 0;
uint32 buffCRC = STRING_HASHCODE("dead_eye");
if (player->hasBuff(buffCRC)) {
player->sendSystemMessage("@combat_effects:dead_eye_already"); //You are already under the effects of Dead Eye.
return 0;
}
if (!player->checkCooldownRecovery("dead_eye")) {
player->sendSystemMessage("@combat_effects:dead_eye_wait"); // You took Dead Eye too recently. An overdose could cause neurological damage.
return 0;
}
Reference<Buff*> buff = new Buff(player, buffCRC, duration, BuffType::SKILL);
Locker locker(buff);
buff->setSkillModifier("dead_eye", effectiveness);
player->addBuff(buff);
// 2 hour cooldown
player->addCooldown("dead_eye", 7200 * 1000);
// Send message to player
player->sendSystemMessage("@combat_effects:dead_eye_active"); // The chemical infusion immediately begins to heighten your awareness, agility, and visual acuity.
//Consume a charge from the item
decreaseUseCount();
return 1;
}
void DeadEyePrototypeImplementation::fillAttributeList(AttributeListMessage* alm, CreatureObject* player) {
if (player == nullptr)
return;
int volume = getContainerVolumeLimit();
alm->insertAttribute("volume", volume);
String crafter = getCraftersName();
alm->insertAttribute("crafter", crafter);
String serial = getSerialNumber();
alm->insertAttribute("serial_number", serial);
// Effectiveness
StringBuffer effectivenessBuffer;
effectivenessBuffer << effectiveness << "%";
alm->insertAttribute("effectiveness", effectivenessBuffer.toString());
// Duration
StringBuffer durationstring;
int minutes = (int) floor(duration / 60.0f);
int seconds = Math::getPrecision(duration % 60, 2);
durationstring << minutes << ":" << seconds;
alm->insertAttribute("duration", durationstring.toString());
}
| 412 | 0.909335 | 1 | 0.909335 | game-dev | MEDIA | 0.953716 | game-dev | 0.949253 | 1 | 0.949253 |
ima-games/ATD | 1,523 | Assets/Plugins/Behavior Designer/Runtime/Tasks/Unity/NavMeshAgent/GetRemainingDistance.cs | using UnityEngine;
using UnityEngine.AI;
namespace BehaviorDesigner.Runtime.Tasks.Unity.UnityNavMeshAgent
{
[TaskCategory("Unity/NavMeshAgent")]
[TaskDescription("Gets the distance between the agent's position and the destination on the current path. Returns Success.")]
public class GetRemainingDistance : Action
{
[Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")]
public SharedGameObject targetGameObject;
[SharedRequired]
[Tooltip("The remaining distance")]
public SharedFloat storeValue;
// cache the navmeshagent component
private NavMeshAgent navMeshAgent;
private GameObject prevGameObject;
public override void OnStart()
{
var currentGameObject = GetDefaultGameObject(targetGameObject.Value);
if (currentGameObject != prevGameObject) {
navMeshAgent = currentGameObject.GetComponent<NavMeshAgent>();
prevGameObject = currentGameObject;
}
}
public override TaskStatus OnUpdate()
{
if (navMeshAgent == null) {
Debug.LogWarning("NavMeshAgent is null");
return TaskStatus.Failure;
}
storeValue.Value = navMeshAgent.remainingDistance;
return TaskStatus.Success;
}
public override void OnReset()
{
targetGameObject = null;
storeValue = 0;
}
}
} | 412 | 0.884087 | 1 | 0.884087 | game-dev | MEDIA | 0.990665 | game-dev | 0.886436 | 1 | 0.886436 |
demoth/jake2 | 37,936 | game/src/main/java/jake2/game/GameSpawn.java | /*
* Copyright (C) 1997-2001 Id Software, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
*
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
// Created on 18.11.2003 by RST.
package jake2.game;
import jake2.game.adapters.EntThinkAdapter;
import jake2.game.character.GameCharacterKt;
import jake2.game.func.*;
import jake2.game.items.GameItem;
import jake2.game.items.GameItems;
import jake2.game.monsters.*;
import jake2.qcommon.Com;
import jake2.qcommon.Defines;
import jake2.qcommon.EntityParserKt;
import jake2.qcommon.ServerEntity;
import jake2.qcommon.util.Lib;
import jake2.qcommon.util.Math3D;
import java.util.*;
import java.util.stream.Collectors;
public class GameSpawn {
private static final String single_statusbar = "yb -24 " // health
+ "xv 0 " + "hnum " + "xv 50 " + "pic 0 " // ammo
+ "if 2 " + " xv 100 " + " anum " + " xv 150 " + " pic 2 "
+ "endif " // armor
+ "if 4 " + " xv 200 " + " rnum " + " xv 250 " + " pic 4 "
+ "endif " // selected item
+ "if 6 " + " xv 296 " + " pic 6 " + "endif " + "yb -50 " // picked
// up
// item
+ "if 7 " + " xv 0 " + " pic 7 " + " xv 26 " + " yb -42 "
+ " stat_string 8 " + " yb -50 " + "endif "
// timer
+ "if 9 " + " xv 262 " + " num 2 10 " + " xv 296 " + " pic 9 "
+ "endif "
// help / weapon icon
+ "if 11 " + " xv 148 " + " pic 11 " + "endif ";
private static final String dm_statusbar = "yb -24 " // health
+ "xv 0 " + "hnum " + "xv 50 " + "pic 0 " // ammo
+ "if 2 " + " xv 100 " + " anum " + " xv 150 " + " pic 2 "
+ "endif " // armor
+ "if 4 " + " xv 200 " + " rnum " + " xv 250 " + " pic 4 "
+ "endif " // selected item
+ "if 6 " + " xv 296 " + " pic 6 " + "endif " + "yb -50 " // picked
// up
// item
+ "if 7 " + " xv 0 " + " pic 7 " + " xv 26 " + " yb -42 "
+ " stat_string 8 " + " yb -50 " + "endif "
// timer
+ "if 9 " + " xv 246 " + " num 2 10 " + " xv 296 " + " pic 9 "
+ "endif "
// help / weapon icon
+ "if 11 " + " xv 148 " + " pic 11 " + "endif " // frags
+ "xr -50 " + "yt 2 " + "num 3 14 " // spectator
+ "if 17 " + "xv 0 " + "yb -58 " + "string2 \"SPECTATOR MODE\" "
+ "endif " // chase camera
+ "if 16 " + "xv 0 " + "yb -68 " + "string \"Chasing\" " + "xv 64 "
+ "stat_string 16 " + "endif ";
/**
* QUAKED worldspawn (0 0 0) ?
* <p>
* Only used for the world. "sky" environment map name "skyaxis" vector axis
* for rotating sky "skyrotate" speed of rotation in degrees/second "sounds"
* music cd track number "gravity" 800 is default gravity "message" text to
* print at user logon
*/
private static EntThinkAdapter SP_worldspawn = new EntThinkAdapter() {
public String getID() {
return "SP_worldspawn";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
ent.movetype = GameDefines.MOVETYPE_PUSH;
ent.solid = Defines.SOLID_BSP;
ent.inuse = true;
// since the world doesn't use G_Spawn()
ent.s.modelindex = 1;
// world model is always index 1
//---------------
// reserve some spots for dead player bodies for coop / deathmatch
PlayerClient.InitBodyQue(gameExports);
// set configstrings for items
GameItems.SetItemNames(gameExports);
if (ent.st.nextmap != null)
gameExports.level.nextmap = ent.st.nextmap;
// make some data visible to the server
if (ent.message != null && ent.message.length() > 0) {
gameExports.gameImports.configstring(Defines.CS_NAME, ent.message);
gameExports.level.level_name = ent.message;
} else
gameExports.level.level_name = gameExports.level.mapname;
if (ent.st.sky != null && ent.st.sky.length() > 0)
gameExports.gameImports.configstring(Defines.CS_SKY, ent.st.sky);
else
gameExports.gameImports.configstring(Defines.CS_SKY, "unit1_");
gameExports.gameImports.configstring(Defines.CS_SKYROTATE, ""
+ ent.st.skyrotate);
gameExports.gameImports.configstring(Defines.CS_SKYAXIS, Lib
.vtos(ent.st.skyaxis));
gameExports.gameImports.configstring(Defines.CS_CDTRACK, "" + ent.sounds);
gameExports.gameImports.configstring(Defines.CS_MAXCLIENTS, ""
+ (int) (gameExports.game.maxclients));
// status bar program
if (gameExports.gameCvars.deathmatch.value != 0)
gameExports.gameImports.configstring(Defines.CS_STATUSBAR, "" + dm_statusbar);
else
gameExports.gameImports.configstring(Defines.CS_STATUSBAR, "" + single_statusbar);
//---------------
// help icon for statusbar
gameExports.gameImports.imageindex("i_help");
gameExports.level.pic_health = gameExports.gameImports.imageindex("i_health");
gameExports.gameImports.imageindex("help");
gameExports.gameImports.imageindex("field_3");
if ("".equals(ent.st.gravity))
gameExports.gameImports.cvar_set("sv_gravity", "800");
else
gameExports.gameImports.cvar_set("sv_gravity", ent.st.gravity);
// standing in lava / slime
gameExports.gameImports.soundindex("player/fry.wav");
// starter weapon
GameItems.PrecacheItem(GameItems.FindItem("Blaster", gameExports), gameExports);
gameExports.gameImports.soundindex("player/lava1.wav");
gameExports.gameImports.soundindex("player/lava2.wav");
gameExports.gameImports.soundindex("misc/pc_up.wav");
gameExports.gameImports.soundindex("misc/talk1.wav");
gameExports.gameImports.soundindex("misc/udeath.wav");
// gibs
gameExports.gameImports.soundindex("items/respawn1.wav");
// sexed sounds
gameExports.gameImports.soundindex("*death1.wav");
gameExports.gameImports.soundindex("*death2.wav");
gameExports.gameImports.soundindex("*death3.wav");
gameExports.gameImports.soundindex("*death4.wav");
gameExports.gameImports.soundindex("*fall1.wav");
gameExports.gameImports.soundindex("*fall2.wav");
gameExports.gameImports.soundindex("*gurp1.wav");
// drowning damage
gameExports.gameImports.soundindex("*gurp2.wav");
gameExports.gameImports.soundindex("*jump1.wav");
// player jump
gameExports.gameImports.soundindex("*pain25_1.wav");
gameExports.gameImports.soundindex("*pain25_2.wav");
gameExports.gameImports.soundindex("*pain50_1.wav");
gameExports.gameImports.soundindex("*pain50_2.wav");
gameExports.gameImports.soundindex("*pain75_1.wav");
gameExports.gameImports.soundindex("*pain75_2.wav");
gameExports.gameImports.soundindex("*pain100_1.wav");
gameExports.gameImports.soundindex("*pain100_2.wav");
// sexed models
// THIS ORDER MUST MATCH THE DEFINES IN g_local.h
// you can add more, max 15
gameExports.gameImports.modelindex("#w_blaster.md2");
gameExports.gameImports.modelindex("#w_shotgun.md2");
gameExports.gameImports.modelindex("#w_sshotgun.md2");
gameExports.gameImports.modelindex("#w_machinegun.md2");
gameExports.gameImports.modelindex("#w_chaingun.md2");
gameExports.gameImports.modelindex("#a_grenades.md2");
gameExports.gameImports.modelindex("#w_glauncher.md2");
gameExports.gameImports.modelindex("#w_rlauncher.md2");
gameExports.gameImports.modelindex("#w_hyperblaster.md2");
gameExports.gameImports.modelindex("#w_railgun.md2");
gameExports.gameImports.modelindex("#w_bfg.md2");
//-------------------
gameExports.gameImports.soundindex("player/gasp1.wav");
// gasping for air
gameExports.gameImports.soundindex("player/gasp2.wav");
// head breaking surface, not gasping
gameExports.gameImports.soundindex("player/watr_in.wav");
// feet hitting water
gameExports.gameImports.soundindex("player/watr_out.wav");
// feet leaving water
gameExports.gameImports.soundindex("player/watr_un.wav");
// head going underwater
gameExports.gameImports.soundindex("player/u_breath1.wav");
gameExports.gameImports.soundindex("player/u_breath2.wav");
gameExports.gameImports.soundindex("items/pkup.wav");
// bonus item pickup
gameExports.gameImports.soundindex("world/land.wav");
// landing thud
gameExports.gameImports.soundindex("misc/h2ohit1.wav");
// landing splash
gameExports.gameImports.soundindex("items/damage.wav");
gameExports.gameImports.soundindex("items/protect.wav");
gameExports.gameImports.soundindex("items/protect4.wav");
gameExports.gameImports.soundindex("weapons/noammo.wav");
gameExports.gameImports.soundindex("infantry/inflies1.wav");
gameExports.gameImports.modelindex("models/objects/gibs/sm_meat/tris.md2");
gameExports.gameImports.modelindex("models/objects/gibs/arm/tris.md2");
gameExports.gameImports.modelindex("models/objects/gibs/bone/tris.md2");
gameExports.gameImports.modelindex("models/objects/gibs/bone2/tris.md2");
gameExports.gameImports.modelindex("models/objects/gibs/chest/tris.md2");
gameExports.gameImports.modelindex("models/objects/gibs/skull/tris.md2");
gameExports.gameImports.modelindex("models/objects/gibs/head2/tris.md2");
defineLightStyles(gameExports);
return true;
}
};
/**
* Setup light animation tables. 'a' is total darkness, 'z' is doublebright.
*/
private static void defineLightStyles(GameExportsImpl game) {
// 0 normal
game.gameImports.configstring(Defines.CS_LIGHTS + 0, "m");
// 1 FLICKER (first variety)
game.gameImports.configstring(Defines.CS_LIGHTS + 1, "mmnmmommommnonmmonqnmmo");
// 2 SLOW STRONG PULSE
game.gameImports.configstring(Defines.CS_LIGHTS + 2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
// 3 CANDLE (first variety)
game.gameImports.configstring(Defines.CS_LIGHTS + 3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
// 4 FAST STROBE
game.gameImports.configstring(Defines.CS_LIGHTS + 4, "mamamamamama");
// 5 GENTLE PULSE 1
game.gameImports.configstring(Defines.CS_LIGHTS + 5, "jklmnopqrstuvwxyzyxwvutsrqponmlkj");
// 6 FLICKER (second variety)
game.gameImports.configstring(Defines.CS_LIGHTS + 6, "nmonqnmomnmomomno");
// 7 CANDLE (second variety)
game.gameImports.configstring(Defines.CS_LIGHTS + 7, "mmmaaaabcdefgmmmmaaaammmaamm");
// 8 CANDLE (third variety)
game.gameImports.configstring(Defines.CS_LIGHTS + 8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
// 9 SLOW STROBE (fourth variety)
game.gameImports.configstring(Defines.CS_LIGHTS + 9, "aaaaaaaazzzzzzzz");
// 10 FLUORESCENT FLICKER
game.gameImports.configstring(Defines.CS_LIGHTS + 10, "mmamammmmammamamaaamammma");
// 11 SLOW PULSE NOT FADE TO BLACK
game.gameImports.configstring(Defines.CS_LIGHTS + 11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
// styles 32-62 are assigned by the light program for switchable lights
// 63 testing
game.gameImports.configstring(Defines.CS_LIGHTS + 63, "a");
}
private static final Map<String, SpawnInterface> spawns;
private static void addSpawnAdapter(String id, EntThinkAdapter adapter) {
spawns.put(id, adapter::think);
}
static {
spawns = new HashMap<>();
spawns.put("new_monster", GameCharacterKt::spawnNewMonster);
spawns.put("item_health", ItemsKt::itemHealthMedium);
spawns.put("item_health_small", ItemsKt::itemHealthSmall);
spawns.put("item_health_large", ItemsKt::itemHealthLarge);
spawns.put("item_health_mega", ItemsKt::itemHealthMega);
spawns.put("info_player_start", InfoEntitiesKt::infoPlayerStart);
spawns.put("info_player_deathmatch", InfoEntitiesKt::infoPlayerDeathmatch);
spawns.put("info_player_coop", InfoEntitiesKt::infoPlayerCoop);
/*
* QUAKED info_player_intermission (1 0 1) (-16 -16 -24) (16 16 32)
* The deathmatch intermission point will be at one of these Use 'angles'
* instead of 'angle', so you can set pitch or roll as well as yaw.
* 'pitch yaw roll'
*
* Does not contain any special code
*/
spawns.put("info_player_intermission", (self, game) -> {});
spawns.put("func_plat", PlatKt::funcPlat);
spawns.put("func_button", ButtonKt::funcButton);
spawns.put("func_door", DoorKt::funcDoor);
spawns.put("func_door_secret", DoorKt::funcDoorSecret);
spawns.put("func_door_rotating", DoorKt::funcDoorRotating);
spawns.put("func_rotating", RotatingKt::funcRotating);
spawns.put("func_train", TrainKt::funcTrain);
spawns.put("func_water", WaterKt::funcWater);
spawns.put("func_conveyor", ConveyorKt::funcConveyor);
spawns.put("func_areaportal", AreaportalKt::funcAreaPortal);
spawns.put("func_clock", ClockKt::funcClock);
spawns.put("func_wall", WallKt::funcWall);
spawns.put("func_object", Func_objectKt::funcObject);
spawns.put("func_timer", TimerKt::funcTimer);
spawns.put("func_explosive", ExplosiveKt::funcExplosive);
spawns.put("func_killbox", KillboxKt::funcKillbox);
spawns.put("trigger_always", TriggersKt::triggerAlways);
spawns.put("trigger_once", TriggersKt::triggerOnce);
spawns.put("trigger_multiple", TriggersKt::triggerMultiple);
spawns.put("trigger_relay", TriggersKt::triggerRelay);
spawns.put("trigger_push", TriggersKt::triggerPush);
spawns.put("trigger_hurt", TriggersKt::triggerHurt);
spawns.put("trigger_key", TriggersKt::triggerKey);
spawns.put("trigger_counter", TriggersKt::triggerCounter);
spawns.put("trigger_elevator", TrainKt::triggerElevator);
spawns.put("trigger_gravity", TriggersKt::triggerGravity);
spawns.put("trigger_monsterjump", TriggersKt::triggerMonsterJump);
spawns.put("target_temp_entity", TargetEntitiesKt::targetTempEntity);
spawns.put("target_speaker", TargetEntitiesKt::targetSpeaker);
spawns.put("target_explosion", TargetEntitiesKt::targetExplosion);
spawns.put("target_changelevel", TargetEntitiesKt::targetChangelevel);
spawns.put("target_secret", TargetEntitiesKt::targetSecret);
spawns.put("target_goal", TargetEntitiesKt::targetGoal);
spawns.put("target_splash", TargetEntitiesKt::targetSplash);
spawns.put("target_spawner", TargetEntitiesKt::targetSpawner);
spawns.put("target_blaster", TargetEntitiesKt::targetBlaster);
spawns.put("target_crosslevel_trigger", TargetEntitiesKt::targetCrosslevelTrigger);
spawns.put("target_crosslevel_target", TargetEntitiesKt::targetCrosslevelTarget);
spawns.put("target_laser", TargetEntitiesKt::targetLaser);
spawns.put("target_help", TargetEntitiesKt::targetHelp);
spawns.put("target_lightramp", TargetEntitiesKt::targetLightramp);
spawns.put("target_earthquake", TargetEntitiesKt::targetEarthquake);
spawns.put("target_character", TargetEntitiesKt::targetCharacter);
spawns.put("target_string", TargetEntitiesKt::targetString);
addSpawnAdapter("worldspawn", SP_worldspawn);
spawns.put("light", LightKt::light);
spawns.put("light_mine1", LightKt::lightMine1);
spawns.put("light_mine2", LightKt::lightMine2);
/*
* QUAKED info_null (0 0.5 0) (-4 -4 -4) (4 4 4)
* Used as a positional target for spotlights, etc.
*/
spawns.put("info_null", (self, game) -> game.freeEntity(self));
/*
* QUAKED func_group (0 0 0) ? Used to group brushes together just for
* editor convenience.
*/
spawns.put("func_group", (self, game) -> game.freeEntity(self));
spawns.put("info_notnull", InfoEntitiesKt::infoNotNull);
spawns.put("path_corner", PathKt::pathCorner);
spawns.put("point_combat", PathKt::pointCombat);
spawns.put("misc_explobox", MiscEntitiesKt::miscExplobox);
spawns.put("misc_banner", MiscEntitiesKt::miscBanner);
spawns.put("misc_satellite_dish", MiscEntitiesKt::miscSatelliteDish);
spawns.put("misc_gib_arm", MiscEntitiesKt::miscGibArm);
spawns.put("misc_gib_leg", MiscEntitiesKt::miscGibLeg);
spawns.put("misc_gib_head", MiscEntitiesKt::miscGibHead);
addSpawnAdapter("misc_insane", new EntThinkAdapter() {
public String getID() {
return "SP_misc_insane";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Insane.SP_misc_insane(ent, gameExports);
return true;
}
});
spawns.put("misc_deadsoldier", MiscEntitiesKt::miscDeadSoldier);
spawns.put("misc_viper", (self, game) -> TrainKt.miscFlyingShip(self, game, "viper"));
spawns.put("misc_strogg_ship", (self, game) -> TrainKt.miscFlyingShip(self, game, "strogg1"));
spawns.put("misc_viper_bomb", MiscEntitiesKt::miscViperBomb);
spawns.put("misc_bigviper", MiscEntitiesKt::miscBigViper);
spawns.put("misc_teleporter", MiscEntitiesKt::miscTeleporter);
spawns.put("misc_teleporter_dest", MiscEntitiesKt::miscTeleporterDest);
spawns.put("misc_blackhole", MiscEntitiesKt::miscBlackhole);
addSpawnAdapter("misc_eastertank", new EntThinkAdapter() {
public String getID() {
return "SP_misc_eastertank";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
GameMisc.SP_misc_eastertank(ent, gameExports);
return true;
}
});
addSpawnAdapter("misc_easterchick", new EntThinkAdapter() {
public String getID() {
return "SP_misc_easterchick";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
GameMisc.SP_misc_easterchick(ent, gameExports);
return true;
}
});
addSpawnAdapter("misc_easterchick2", new EntThinkAdapter() {
public String getID() {
return "SP_misc_easterchick2";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
GameMisc.SP_misc_easterchick2(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_berserk", new EntThinkAdapter() {
public String getID() {
return "SP_monster_berserk";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Berserk.SP_monster_berserk(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_gladiator", new EntThinkAdapter() {
public String getID() {
return "SP_monster_gladiator";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Gladiator.SP_monster_gladiator(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_gunner", new EntThinkAdapter() {
public String getID() {
return "SP_monster_gunner";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Gunner.SP_monster_gunner(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_infantry", new EntThinkAdapter() {
public String getID() {
return "SP_monster_infantry";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Infantry.SP_monster_infantry(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_soldier_light", M_Soldier.SP_monster_soldier_light);
addSpawnAdapter("monster_soldier", M_Soldier.SP_monster_soldier);
addSpawnAdapter("monster_soldier_ss", M_Soldier.SP_monster_soldier_ss);
addSpawnAdapter("monster_tank", M_Tank.SP_monster_tank);
addSpawnAdapter("monster_tank_commander", M_Tank.SP_monster_tank);
addSpawnAdapter("monster_medic", new EntThinkAdapter() {
public String getID() {
return "SP_monster_medic";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Medic.SP_monster_medic(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_flipper", new EntThinkAdapter() {
public String getID() {
return "SP_monster_flipper";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Flipper.SP_monster_flipper(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_chick", new EntThinkAdapter() {
public String getID() {
return "SP_monster_chick";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Chick.SP_monster_chick(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_parasite", M_Parasite.SP_monster_parasite);
addSpawnAdapter("monster_flyer", new EntThinkAdapter() {
public String getID() {
return "SP_monster_flyer";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Flyer.SP_monster_flyer(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_brain", new EntThinkAdapter() {
public String getID() {
return "SP_monster_brain";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Brain.SP_monster_brain(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_floater", new EntThinkAdapter() {
public String getID() {
return "SP_monster_floater";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Float.SP_monster_floater(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_hover", new EntThinkAdapter() {
public String getID() {
return "SP_monster_hover";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Hover.SP_monster_hover(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_mutant", M_Mutant.SP_monster_mutant);
addSpawnAdapter("monster_supertank", M_Supertank.SP_monster_supertank);
addSpawnAdapter("monster_boss2", new EntThinkAdapter() {
public String getID() {
return "SP_monster_boss2";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Hornet.SP_monster_boss2(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_boss3_stand", new EntThinkAdapter() {
public String getID() {
return "SP_monster_boss3_stand";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Makron_Idle.SP_monster_boss3_stand(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_jorg", new EntThinkAdapter() {
public String getID() {
return "SP_monster_jorg";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
M_Makron_Jorg.SP_monster_jorg(ent, gameExports);
return true;
}
});
addSpawnAdapter("monster_commander_body", new EntThinkAdapter() {
public String getID() {
return "SP_monster_commander_body";
}
public boolean think(GameEntity ent, GameExportsImpl gameExports) {
GameMisc.SP_monster_commander_body(ent, gameExports);
return true;
}
});
spawns.put("turret_breach", TurretKt::turretBreach);
spawns.put("turret_base", TurretKt::turretBase);
spawns.put("turret_driver", TurretKt::turretDriver);
}
/**
* ED_ParseField
* <p>
* Takes a key/value pair and sets the binary values in an edict.
*/
private static void ED_ParseField(String key, String value, GameEntity ent, GameExportsImpl gameExports) {
if (!ent.st.set(key, value))
if (!ent.setField(key, value))
gameExports.gameImports.dprintf("??? The key [" + key + "] is not a field\n");
}
/**
* ED_ParseEdict
* <p>
* Parses an edict out of the given string, returning the new position ed
* should be a properly initialized empty edict.
*/
@Deprecated
private static void ED_ParseEdict(Com.ParseHelp ph, GameEntity ent, GameExportsImpl gameExports) {
String keyname;
String com_token;
boolean init = false;
while (true) {
// parse key
com_token = Com.Parse(ph);
if (com_token.equals("}"))
break;
if (ph.isEof())
gameExports.gameImports.error("ED_ParseEntity: EOF without closing brace");
keyname = com_token;
// parse value
com_token = Com.Parse(ph);
if (ph.isEof())
gameExports.gameImports.error("ED_ParseEntity: EOF without closing brace");
if (com_token.equals("}"))
gameExports.gameImports.error("ED_ParseEntity: closing brace without data");
init = true;
// keynames with a leading underscore are used for utility comments,
// and are immediately discarded by quake
if (keyname.charAt(0) == '_')
continue;
ED_ParseField(keyname.toLowerCase(), com_token, ent, gameExports);
}
if (!init) {
G_ClearEdict(ent, gameExports);
}
}
private static void G_ClearEdict(ServerEntity ent, GameExportsImpl gameExports) {
gameExports.g_edicts[ent.index] = new GameEntity(ent.index);
}
/**
* G_FindTeams
* <p>
* Chain together all entities with a matching team field.
* <p>
* All but the first will have the FL_TEAMSLAVE flag set. All but the last
* will have the teamchain field set to the next one.
*
* fixme: n^2 complexity
*/
private static void G_FindTeams(GameExportsImpl game) {
var teams = new HashMap<String, ArrayList<GameEntity>>();
// TODO check that num_edicts is not more than g_edicts.size()
// TODO rename fields: teamchain -> next, teamslave -> teammember, teammaster -> teamlead
for (int i = 1; i < game.num_edicts; i++) {
GameEntity e = game.g_edicts[i];
if (!e.inuse)
continue;
if (e.team == null)
continue;
if ((e.flags & GameDefines.FL_TEAMSLAVE) != 0)
throw new RuntimeException("Some flags are already set. why?");
var team = teams.get(e.team);
if (team == null) {
// teamlead
e.teammaster = e;
team = new ArrayList<>();
team.add(e);
teams.put(e.team, team);
} else if (team.size() == 0) {
throw new RuntimeException("Array exists but empty. why?");
} else {
// member
e.teammaster = team.get(0);
e.flags |= GameDefines.FL_TEAMSLAVE;
team.get(team.size() - 1).teamchain = e;
team.add(e);
}
}
}
static void SpawnEntities(String mapname, String entities, String spawnpoint, GameExportsImpl gameExports) {
// todo: split into different functions
gameExports.level.mapname = mapname;
gameExports.game.spawnpoint = spawnpoint;
final float skill = normalizeSkillCvar(gameExports);
// set client fields on player ents
for (int i = 0; i < gameExports.game.maxclients; i++)
gameExports.g_edicts[i + 1].setClient(gameExports.game.clients[i]);
EntityParserKt.parseEntities(entities).forEach(map -> {
final GameEntity ent;
if ("worldspawn".equals(map.get("classname")))
ent = gameExports.g_edicts[0];
else
ent = gameExports.G_Spawn();
map.forEach((key, value) -> ED_ParseField(key, value, ent, gameExports));
// todo: add description
// yet another map hack
if ("command".equalsIgnoreCase(gameExports.level.mapname)
&& "trigger_once".equalsIgnoreCase(ent.classname)
&& "*27".equalsIgnoreCase(ent.model))
ent.spawnflags &= ~GameDefines.SPAWNFLAG_NOT_HARD;
boolean spawned = true;
if (!ent.classname.equals("worldspawn")) {
if (gameExports.gameCvars.deathmatch.value != 0) {
if ((ent.spawnflags & GameDefines.SPAWNFLAG_NOT_DEATHMATCH) != 0) {
spawned = false;
}
} else {
// fixme: similar check for SPAWNFLAG_NOT_COOP?
if (skill == 0 && (ent.spawnflags & GameDefines.SPAWNFLAG_NOT_EASY) != 0
|| skill == 1 && (ent.spawnflags & GameDefines.SPAWNFLAG_NOT_MEDIUM) != 0
// SPAWNFLAG_NOT_HARD implies not hard+ also
|| (skill == 2 || skill == 3) && (ent.spawnflags & GameDefines.SPAWNFLAG_NOT_HARD) != 0) {
spawned = false;
}
}
// reset difficulty spawnflags
ent.spawnflags &= ~(GameDefines.SPAWNFLAG_NOT_EASY
| GameDefines.SPAWNFLAG_NOT_MEDIUM
| GameDefines.SPAWNFLAG_NOT_HARD
| GameDefines.SPAWNFLAG_NOT_COOP
| GameDefines.SPAWNFLAG_NOT_DEATHMATCH);
}
if (spawned) {
gameExports.gameImports.dprintf("spawning ent[" + ent.index + "], classname=" +
ent.classname + ", flags= " + Integer.toHexString(ent.spawnflags) + "\n");
ED_CallSpawn(ent, gameExports);
} else {
gameExports.freeEntity(ent);
}
});
gameExports.gameImports.dprintf("player skill level:" + skill + "\n");
G_FindTeams(gameExports);
gameExports.playerTrail.Init();
}
private static float normalizeSkillCvar(GameExportsImpl gameExports) {
final float skill = gameExports.gameCvars.skill.value;
float skillNormalized = (float) Math.floor(skill);
if (skillNormalized < 0)
skillNormalized = 0;
if (skillNormalized > 3)
skillNormalized = 3;
if (skill != skillNormalized)
gameExports.gameImports.cvar_forceset("skill", "" + skillNormalized);
return skill;
}
/**
* Finds the spawn function for the entity and calls it.
*/
public static void ED_CallSpawn(GameEntity ent, GameExportsImpl gameExports) {
if (null == ent.classname) {
gameExports.gameImports.dprintf("ED_CallSpawn: null classname\n");
return;
}
// check item spawn functions
var item = gameExports.items.stream()
.filter(it -> ent.classname.equals(it.classname))
.findFirst();
if (item.isPresent()) {
GameItems.SpawnItem(ent, item.get(), gameExports);
return;
}
// check normal spawn functions
var spawn = spawns.get(ent.classname.toLowerCase());
if (spawn != null) {
spawn.spawn(ent, gameExports);
ent.st = null;
} else {
gameExports.gameImports.dprintf(ent.classname + " doesn't have a spawn function\n");
}
}
static String[] mobs = { "monster_berserk", "monster_gladiator", "monster_gunner", "monster_infantry", "monster_soldier_light", "monster_soldier", "monster_soldier_ss", "monster_tank", "monster_tank_commander", "monster_medic", "monster_chick", "monster_parasite", "monster_flyer", "monster_brain", "monster_floater", "monster_mutant"};
// for debugging and testing
static void SpawnRandomMonster(GameEntity ent, GameExportsImpl gameExports){
final int index = Lib.rand() % mobs.length;
SpawnNewEntity(ent, Arrays.asList("spawn", mobs[index]), gameExports);
}
static void SpawnNewEntity(GameEntity creator, List<String> args, GameExportsImpl gameExports) {
String className;
if (args.size() >= 2)
className = args.get(1);
else {
gameExports.gameImports.dprintf("usage: spawn <classname>\n");
return;
}
if (gameExports.gameCvars.deathmatch.value != 0 && gameExports.gameCvars.sv_cheats.value == 0) {
gameExports.gameImports.cprintf(creator, Defines.PRINT_HIGH,
"You must run the server with '+set cheats 1' to enable this command.\n");
return;
}
gameExports.gameImports.dprintf("Spawning " + className + " at " + Lib.vtofs(creator.s.origin) + ", " + Lib.vtofs(creator.s.angles) + "\n");
var spawn = spawns.get(className);
GameItem gitem_t = GameItems.FindItemByClassname(className, gameExports);
if (spawn != null || gitem_t != null) {
GameEntity newThing = gameExports.G_Spawn();
putInFrontOfCreator(creator, newThing);
newThing.classname = className;
gameExports.gameImports.linkentity(newThing);
if (spawn != null)
spawn.spawn(newThing, gameExports);
else
GameItems.SpawnItem(newThing, gitem_t, gameExports);
gameExports.gameImports.dprintf("Spawned!\n");
}
}
private static void putInFrontOfCreator(GameEntity creator, GameEntity newThing) {
float[] location = creator.s.origin;
float[] offset = {0,0,0};
float[] forward = { 0, 0, 0 };
Math3D.AngleVectors(creator.s.angles, forward, null, null);
Math3D.VectorNormalize(forward);
Math3D.VectorScale(forward, 128, offset);
Math3D.VectorAdd(location, offset, offset);
newThing.s.origin = offset;
newThing.s.angles[Defines.YAW] = creator.s.angles[Defines.YAW];
}
/**
* Makes sense only for point entities
*/
public static void createEntity(GameEntity creator, List<String> args, GameExportsImpl gameExports) {
// hack: join back all the arguments, quoting keys and values
// no comments are expected here
String entities = args.stream()
.skip(1)
.filter(s -> !s.equals("}") && !s.equals("{"))
.map(s -> '"' + s + '"')
.collect(Collectors.joining(" ", "{", "}"));
// actually we expect 1 entity
EntityParserKt.parseEntities(entities).forEach(entity -> {
GameEntity newThing = gameExports.G_Spawn();
entity.forEach((key, value) -> ED_ParseField(key, value, newThing, gameExports));
putInFrontOfCreator(creator, newThing);
ED_CallSpawn(newThing, gameExports);
});
}
}
| 412 | 0.874658 | 1 | 0.874658 | game-dev | MEDIA | 0.674191 | game-dev | 0.858919 | 1 | 0.858919 |
Silverlan/pragma | 2,393 | core/client/src/entities/environment/lights/c_env_light_base.cpp | // SPDX-FileCopyrightText: (c) 2021 Silverlan <opensource@pragma-engine.com>
// SPDX-License-Identifier: MIT
#include "stdafx_client.h"
#include "pragma/entities/environment/lights/c_env_light.h"
#include "pragma/entities/c_entityfactories.h"
#include "pragma/entities/baseentity_luaobject.h"
#include <pragma/networking/nwm_util.h>
#include "pragma/entities/components/c_radius_component.hpp"
#include "pragma/entities/components/c_color_component.hpp"
#include <pragma/lua/converters/game_type_converters_t.hpp>
#include <pragma/entities/entity_component_system_t.hpp>
using namespace pragma;
extern DLLCLIENT CGame *c_game;
CBaseLightComponent::CBaseLightComponent(BaseEntity &ent) : BaseEnvLightComponent(ent) {}
CBaseLightComponent::~CBaseLightComponent() {}
void CBaseLightComponent::Initialize() { BaseEnvLightComponent::Initialize(); }
void CBaseLightComponent::OnEntityComponentAdded(BaseEntityComponent &component) { BaseEnvLightComponent::OnEntityComponentAdded(component); }
util::EventReply CBaseLightComponent::HandleEvent(ComponentEventId eventId, ComponentEvent &evData)
{
if(BaseEnvLightComponent::HandleEvent(eventId, evData) == util::EventReply::Handled)
return util::EventReply::Handled;
return util::EventReply::Unhandled;
}
void CBaseLightComponent::ReceiveData(NetPacket &packet)
{
m_shadowType = packet->Read<decltype(m_shadowType)>();
SetFalloffExponent(packet->Read<float>());
m_lightFlags = packet->Read<LightFlags>();
auto lightIntensity = packet->Read<float>();
auto lightIntensityType = packet->Read<LightIntensityType>();
SetLightIntensity(lightIntensity, lightIntensityType);
}
Bool CBaseLightComponent::ReceiveNetEvent(pragma::NetEventId eventId, NetPacket &packet)
{
if(eventId == m_netEvSetShadowType)
SetShadowType(packet->Read<BaseEnvLightComponent::ShadowType>());
else if(eventId == m_netEvSetFalloffExponent)
SetFalloffExponent(packet->Read<float>());
else
return CBaseNetComponent::ReceiveNetEvent(eventId, packet);
return true;
}
void CBaseLightComponent::OnEntitySpawn()
{
BaseEnvLightComponent::OnEntitySpawn();
if(m_hLight.valid())
InitializeLightSource();
}
void CBaseLightComponent::InitializeLightSource()
{
//auto &scene = c_game->GetScene();
//scene->AddLight(m_light.get()); // prosper TODO
}
/////////////
void CEnvLight::Initialize()
{
CBaseEntity::Initialize();
AddComponent<CLightComponent>();
}
| 412 | 0.849654 | 1 | 0.849654 | game-dev | MEDIA | 0.692475 | game-dev | 0.909193 | 1 | 0.909193 |
dingzhen-vape/WurstCN | 16,123 | src/main/java/net/wurstclient/navigator/NavigatorFeatureScreen.java | /*
* Copyright (c) 2014-2024 Wurst-Imperium and contributors.
*
* This source code is subject to the terms of the GNU General Public
* License, version 3. If a copy of the GPL was not distributed with this
* file, You can obtain one at: https://www.gnu.org/licenses/gpl-3.0.txt
*/
package net.wurstclient.navigator;
import java.awt.Color;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeMap;
import org.joml.Matrix4f;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.opengl.GL11;
import com.mojang.blaze3d.systems.RenderSystem;
import net.fabricmc.fabric.api.client.screen.v1.Screens;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.ClickableWidget;
import net.minecraft.client.render.BufferBuilder;
import net.minecraft.client.render.BufferRenderer;
import net.minecraft.client.render.GameRenderer;
import net.minecraft.client.render.Tessellator;
import net.minecraft.client.render.VertexFormat;
import net.minecraft.client.render.VertexFormats;
import net.minecraft.client.sound.PositionedSoundInstance;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.sound.SoundEvents;
import net.minecraft.text.Text;
import net.minecraft.util.math.MathHelper;
import net.wurstclient.Feature;
import net.wurstclient.WurstClient;
import net.wurstclient.clickgui.ClickGui;
import net.wurstclient.clickgui.Component;
import net.wurstclient.clickgui.Window;
import net.wurstclient.command.Command;
import net.wurstclient.hack.Hack;
import net.wurstclient.hacks.TooManyHaxHack;
import net.wurstclient.keybinds.Keybind;
import net.wurstclient.keybinds.PossibleKeybind;
import net.wurstclient.settings.Setting;
import net.wurstclient.util.ChatUtils;
import net.wurstclient.util.RenderUtils;
public final class NavigatorFeatureScreen extends NavigatorScreen
{
private Feature feature;
private NavigatorMainScreen parent;
private ButtonData activeButton;
private ButtonWidget primaryButton;
private String text;
private ArrayList<ButtonData> buttonDatas = new ArrayList<>();
private Window window = new Window("");
private int windowComponentY;
public NavigatorFeatureScreen(Feature feature, NavigatorMainScreen parent)
{
this.feature = feature;
this.parent = parent;
hasBackground = false;
for(Setting setting : feature.getSettings().values())
{
Component c = setting.getComponent();
if(c != null)
window.add(c);
}
window.setWidth(308);
window.setFixedWidth(true);
window.pack();
}
@Override
protected void onResize()
{
buttonDatas.clear();
// primary button
String primaryAction = feature.getPrimaryAction();
boolean hasPrimaryAction = !primaryAction.isEmpty();
boolean hasHelp = false;// !feature.getHelpPage().isEmpty();
if(hasPrimaryAction)
{
primaryButton =
ButtonWidget.builder(Text.literal(primaryAction), b -> {
TooManyHaxHack tooManyHax =
WurstClient.INSTANCE.getHax().tooManyHaxHack;
if(tooManyHax.isEnabled() && tooManyHax.isBlocked(feature))
{
ChatUtils.error(
feature.getName() + " is blocked by TooManyHax.");
return;
}
feature.doPrimaryAction();
primaryButton
.setMessage(Text.literal(feature.getPrimaryAction()));
WurstClient.INSTANCE.getNavigator()
.addPreference(feature.getName());
}).dimensions(width / 2 - 151, height - 65, hasHelp ? 149 : 302,
18).build();
addDrawableChild(primaryButton);
}
// help button
// if(hasHelp)
// method_37063(new ButtonWidget(
// width / 2 + (hasPrimaryAction ? 2 : -151), height - 65,
// hasPrimaryAction ? 149 : 302, 20, "Help", b -> {
// MiscUtils.openLink("https://www.wurstclient.net/wiki/"
// + feature.getHelpPage() + "/");
// wurst.navigator.analytics.trackEvent("help", "open",
// feature.getName());
// wurst.navigator.addPreference(feature.getName());
// ConfigFiles.NAVIGATOR.save();
// }));
// type
text = "Type: ";
if(feature instanceof Hack)
text += "Hack";
else if(feature instanceof Command)
text += "Command";
else
text += "Other Feature";
// category
if(feature.getCategory() != null)
text += ", Category: " + feature.getCategory().getName();
// description
String description = feature.getWrappedDescription(300);
if(!description.isEmpty())
text += "\n\nDescription:\n" + description;
// area
Rectangle area = new Rectangle(middleX - 154, 60, 308, height - 103);
// settings
Collection<Setting> settings = feature.getSettings().values();
if(!settings.isEmpty())
{
text += "\n\nSettings:";
windowComponentY = getStringHeight(text) + 2;
for(int i = 0; i < Math.ceil(window.getInnerHeight() / 9.0); i++)
text += "\n";
}
// keybinds
Set<PossibleKeybind> possibleKeybinds = feature.getPossibleKeybinds();
if(!possibleKeybinds.isEmpty())
{
// heading
text += "\n\nKeybinds:";
// add keybind button
ButtonData addKeybindButton =
new ButtonData(area.x + area.width - 16,
area.y + getStringHeight(text) - 7, 12, 8, "+", 0x00ff00)
{
@Override
public void press()
{
// add keybind
WurstClient.MC.setScreen(new NavigatorNewKeybindScreen(
possibleKeybinds, NavigatorFeatureScreen.this));
}
};
buttonDatas.add(addKeybindButton);
// keybind list
HashMap<String, String> possibleKeybindsMap = new HashMap<>();
for(PossibleKeybind possibleKeybind : possibleKeybinds)
possibleKeybindsMap.put(possibleKeybind.getCommand(),
possibleKeybind.getDescription());
TreeMap<String, PossibleKeybind> existingKeybinds = new TreeMap<>();
boolean noKeybindsSet = true;
for(Keybind keybind : WurstClient.INSTANCE.getKeybinds()
.getAllKeybinds())
{
String commands = keybind.getCommands();
commands = commands.replace(";", "\u00a7")
.replace("\u00a7\u00a7", ";");
for(String command : commands.split("\u00a7"))
{
command = command.trim();
String keybindDescription =
possibleKeybindsMap.get(command);
if(keybindDescription != null)
{
if(noKeybindsSet)
noKeybindsSet = false;
text +=
"\n" + keybind.getKey().replace("key.keyboard.", "")
+ ": " + keybindDescription;
existingKeybinds.put(keybind.getKey(),
new PossibleKeybind(command, keybindDescription));
}else if(feature instanceof Hack
&& command.equalsIgnoreCase(feature.getName()))
{
if(noKeybindsSet)
noKeybindsSet = false;
text +=
"\n" + keybind.getKey().replace("key.keyboard.", "")
+ ": " + "Toggle " + feature.getName();
existingKeybinds.put(keybind.getKey(),
new PossibleKeybind(command,
"Toggle " + feature.getName()));
}
}
}
if(noKeybindsSet)
text += "\nNone";
else
{
// remove keybind button
buttonDatas.add(new ButtonData(addKeybindButton.x,
addKeybindButton.y, addKeybindButton.width,
addKeybindButton.height, "-", 0xff0000)
{
@Override
public void press()
{
// remove keybind
client.setScreen(new NavigatorRemoveKeybindScreen(
existingKeybinds, NavigatorFeatureScreen.this));
}
});
addKeybindButton.x -= 16;
}
}
// text height
setContentHeight(getStringHeight(text));
}
@Override
protected void onKeyPress(int keyCode, int scanCode, int int_3)
{
if(keyCode == GLFW.GLFW_KEY_ESCAPE
|| keyCode == GLFW.GLFW_KEY_BACKSPACE)
goBack();
}
@Override
protected void onMouseClick(double x, double y, int button)
{
// popups
if(WurstClient.INSTANCE.getGui().handleNavigatorPopupClick(x, y,
button))
return;
// back button
if(button == GLFW.GLFW_MOUSE_BUTTON_4)
{
goBack();
return;
}
boolean noButtons = Screens.getButtons(this).isEmpty();
Rectangle area = new Rectangle(width / 2 - 154, 60, 308,
height - 60 - (noButtons ? 43 : 67));
if(!area.contains(x, y))
return;
// buttons
if(activeButton != null)
{
client.getSoundManager().play(
PositionedSoundInstance.master(SoundEvents.UI_BUTTON_CLICK, 1));
activeButton.press();
WurstClient.INSTANCE.getNavigator()
.addPreference(feature.getName());
return;
}
// component settings
WurstClient.INSTANCE.getGui().handleNavigatorMouseClick(
x - middleX + 154, y - 60 - scroll - windowComponentY, button,
window);
}
private void goBack()
{
parent.setExpanding(false);
client.setScreen(parent);
}
@Override
protected void onMouseDrag(double mouseX, double mouseY, int button,
double double_3, double double_4)
{
}
@Override
protected void onMouseRelease(double x, double y, int button)
{
WurstClient.INSTANCE.getGui().handleMouseRelease(x, y, button);
}
@Override
protected void onUpdate()
{
if(primaryButton != null)
primaryButton.setMessage(Text.literal(feature.getPrimaryAction()));
}
@Override
protected void onRender(DrawContext context, int mouseX, int mouseY,
float partialTicks)
{
MatrixStack matrixStack = context.getMatrices();
ClickGui gui = WurstClient.INSTANCE.getGui();
int txtColor = gui.getTxtColor();
// title bar
context.drawCenteredTextWithShadow(client.textRenderer,
feature.getName(), middleX, 32, txtColor);
GL11.glEnable(GL11.GL_BLEND);
// background
int bgx1 = middleX - 154;
window.setX(bgx1);
int bgx2 = middleX + 154;
int bgy1 = 60;
int bgy2 = height - 43;
boolean noButtons = Screens.getButtons(this).isEmpty();
int bgy3 = bgy2 - (noButtons ? 0 : 24);
int windowY1 = bgy1 + scroll + windowComponentY;
int windowY2 = windowY1 + window.getInnerHeight();
setColorToBackground();
drawQuads(matrixStack, bgx1, bgy1, bgx2,
MathHelper.clamp(windowY1, bgy1, bgy3));
drawQuads(matrixStack, bgx1, MathHelper.clamp(windowY2, bgy1, bgy3),
bgx2, bgy2);
drawBoxShadow(matrixStack, bgx1, bgy1, bgx2, bgy2);
// scissor box
RenderUtils.scissorBox(bgx1, bgy1, bgx2, bgy3);
GL11.glEnable(GL11.GL_SCISSOR_TEST);
// settings
gui.setTooltip("");
window.validate();
window.setY(windowY1 - 13);
matrixStack.push();
matrixStack.translate(bgx1, windowY1, 0);
{
int x1 = 0;
int y1 = -13;
int x2 = x1 + window.getWidth();
int y2 = y1 + window.getHeight();
int y3 = y1 + 13;
int x3 = x1 + 2;
int x5 = x2 - 2;
Matrix4f matrix = matrixStack.peek().getPositionMatrix();
Tessellator tessellator = RenderSystem.renderThreadTesselator();
RenderSystem.setShader(GameRenderer::getPositionProgram);
// window background
// left & right
setColorToBackground();
BufferBuilder bufferBuilder = tessellator
.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION);
bufferBuilder.vertex(matrix, x1, y3, 0);
bufferBuilder.vertex(matrix, x1, y2, 0);
bufferBuilder.vertex(matrix, x3, y2, 0);
bufferBuilder.vertex(matrix, x3, y3, 0);
bufferBuilder.vertex(matrix, x5, y3, 0);
bufferBuilder.vertex(matrix, x5, y2, 0);
bufferBuilder.vertex(matrix, x2, y2, 0);
bufferBuilder.vertex(matrix, x2, y3, 0);
BufferRenderer.drawWithGlobalProgram(bufferBuilder.end());
setColorToBackground();
bufferBuilder = tessellator.begin(VertexFormat.DrawMode.QUADS,
VertexFormats.POSITION);
// window background
// between children
int xc1 = 2;
int xc2 = x5 - x1;
for(int i = 0; i < window.countChildren(); i++)
{
int yc1 = window.getChild(i).getY();
int yc2 = yc1 - 2;
if(yc1 < bgy1 - windowY1)
continue;
if(yc2 > bgy3 - windowY1)
break;
bufferBuilder.vertex(matrix, xc1, yc2, 0);
bufferBuilder.vertex(matrix, xc1, yc1, 0);
bufferBuilder.vertex(matrix, xc2, yc1, 0);
bufferBuilder.vertex(matrix, xc2, yc2, 0);
}
// window background
// bottom
int yc1;
if(window.countChildren() == 0)
yc1 = 0;
else
{
Component lastChild =
window.getChild(window.countChildren() - 1);
yc1 = lastChild.getY() + lastChild.getHeight();
}
int yc2 = yc1 + 2;
bufferBuilder.vertex(matrix, xc1, yc2, 0);
bufferBuilder.vertex(matrix, xc1, yc1, 0);
bufferBuilder.vertex(matrix, xc2, yc1, 0);
bufferBuilder.vertex(matrix, xc2, yc2, 0);
BufferRenderer.drawWithGlobalProgram(bufferBuilder.end());
}
for(int i = 0; i < window.countChildren(); i++)
{
Component child = window.getChild(i);
if(child.getY() + child.getHeight() < bgy1 - windowY1)
continue;
if(child.getY() > bgy3 - windowY1)
break;
child.render(context, mouseX - bgx1, mouseY - windowY1,
partialTicks);
}
matrixStack.pop();
// buttons
activeButton = null;
for(ButtonData buttonData : buttonDatas)
{
// positions
int x1 = buttonData.x;
int x2 = x1 + buttonData.width;
int y1 = buttonData.y + scroll;
int y2 = y1 + buttonData.height;
// color
float alpha;
if(buttonData.isLocked())
alpha = 0.25F;
else if(mouseX >= x1 && mouseX <= x2 && mouseY >= y1
&& mouseY <= y2)
{
alpha = 0.75F;
activeButton = buttonData;
}else
alpha = 0.375F;
float[] rgb = buttonData.color.getColorComponents(null);
RenderSystem.setShaderColor(rgb[0], rgb[1], rgb[2], alpha);
// button
drawBox(matrixStack, x1, y1, x2, y2);
// text
context.drawCenteredTextWithShadow(client.textRenderer,
buttonData.buttonText, (x1 + x2) / 2,
y1 + (buttonData.height - 10) / 2 + 1,
buttonData.isLocked() ? 0xaaaaaa : buttonData.textColor);
GL11.glEnable(GL11.GL_BLEND);
}
// text
RenderSystem.setShaderColor(1, 1, 1, 1);
int textY = bgy1 + scroll + 2;
for(String line : text.split("\n"))
{
context.drawText(client.textRenderer, line, bgx1 + 2, textY,
txtColor, false);
textY += client.textRenderer.fontHeight;
}
GL11.glEnable(GL11.GL_BLEND);
// scissor box
GL11.glDisable(GL11.GL_SCISSOR_TEST);
// buttons below scissor box
for(ClickableWidget button : Screens.getButtons(this))
{
// positions
int x1 = button.getX();
int x2 = x1 + button.getWidth();
int y1 = button.getY();
int y2 = y1 + 18;
// color
boolean hovering =
mouseX >= x1 && mouseX <= x2 && mouseY >= y1 && mouseY <= y2;
if(feature.isEnabled() && button == primaryButton)
// if(feature.isBlocked())
// RenderSystem.setShaderColor(hovering ? 1F : 0.875F, 0F, 0F,
// 0.25F);
// else
RenderSystem.setShaderColor(0F, hovering ? 1F : 0.875F, 0F,
0.25F);
else if(hovering)
RenderSystem.setShaderColor(0.375F, 0.375F, 0.375F, 0.25F);
else
RenderSystem.setShaderColor(0.25F, 0.25F, 0.25F, 0.25F);
// button
drawBox(matrixStack, x1, y1, x2, y2);
// text
String buttonText = button.getMessage().getString();
context.drawText(client.textRenderer, buttonText,
(x1 + x2 - client.textRenderer.getWidth(buttonText)) / 2,
y1 + 5, txtColor, false);
GL11.glEnable(GL11.GL_BLEND);
}
// popups & tooltip
gui.renderPopups(context, mouseX, mouseY);
gui.renderTooltip(context, mouseX, mouseY);
// GL resets
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glDisable(GL11.GL_BLEND);
}
@Override
public void close()
{
window.close();
WurstClient.INSTANCE.getGui().handleMouseClick(Integer.MIN_VALUE,
Integer.MIN_VALUE, 0);
}
public Feature getFeature()
{
return feature;
}
public int getMiddleX()
{
return middleX;
}
public void addText(String text)
{
this.text += text;
}
public int getTextHeight()
{
return getStringHeight(text);
}
public abstract static class ButtonData extends Rectangle
{
public String buttonText;
public Color color;
public int textColor = 0xffffff;
public ButtonData(int x, int y, int width, int height,
String buttonText, int color)
{
super(x, y, width, height);
this.buttonText = buttonText;
this.color = new Color(color);
}
public abstract void press();
public boolean isLocked()
{
return false;
}
}
}
| 412 | 0.825504 | 1 | 0.825504 | game-dev | MEDIA | 0.769144 | game-dev,desktop-app | 0.984867 | 1 | 0.984867 |
mehah/otclient | 9,781 | mods/game_bot/default_configs/cavebot_1.3/targetbot/looting.lua | TargetBot.Looting = {}
TargetBot.Looting.list = {} -- list of containers to loot
local ui
local items = {}
local containers = {}
local itemsById = {}
local containersById = {}
local dontSave = false
TargetBot.Looting.setup = function()
ui = UI.createWidget("TargetBotLootingPanel")
UI.Container(TargetBot.Looting.onItemsUpdate, true, nil, ui.items)
UI.Container(TargetBot.Looting.onContainersUpdate, true, nil, ui.containers)
ui.everyItem.onClick = function()
ui.everyItem:setOn(not ui.everyItem:isOn())
TargetBot.save()
end
ui.maxDangerPanel.value.onTextChange = function()
local value = tonumber(ui.maxDangerPanel.value:getText())
if not value then
ui.maxDangerPanel.value:setText(0)
end
if dontSave then return end
TargetBot.save()
end
ui.minCapacityPanel.value.onTextChange = function()
local value = tonumber(ui.minCapacityPanel.value:getText())
if not value then
ui.minCapacityPanel.value:setText(0)
end
if dontSave then return end
TargetBot.save()
end
end
TargetBot.Looting.onItemsUpdate = function()
if dontSave then return end
TargetBot.save()
TargetBot.Looting.updateItemsAndContainers()
end
TargetBot.Looting.onContainersUpdate = function()
if dontSave then return end
TargetBot.save()
TargetBot.Looting.updateItemsAndContainers()
end
TargetBot.Looting.update = function(data)
dontSave = true
TargetBot.Looting.list = {}
ui.items:setItems(data['items'] or {})
ui.containers:setItems(data['containers'] or {})
ui.everyItem:setOn(data['everyItem'])
ui.maxDangerPanel.value:setText(data['maxDanger'] or 10)
ui.minCapacityPanel.value:setText(data['minCapacity'] or 100)
TargetBot.Looting.updateItemsAndContainers()
dontSave = false
end
TargetBot.Looting.save = function(data)
data['items'] = ui.items:getItems()
data['containers'] = ui.containers:getItems()
data['maxDanger'] = tonumber(ui.maxDangerPanel.value:getText())
data['minCapacity'] = tonumber(ui.minCapacityPanel.value:getText())
data['everyItem'] = ui.everyItem:isOn()
end
TargetBot.Looting.updateItemsAndContainers = function()
items = ui.items:getItems()
containers = ui.containers:getItems()
itemsById = {}
containersById = {}
for i, item in ipairs(items) do
itemsById[item.id] = 1
end
for i, container in ipairs(containers) do
containersById[container.id] = 1
end
end
local waitTill = 0
local waitingForContainer = nil
local status = ""
local lastFoodConsumption = 0
TargetBot.Looting.getStatus = function()
return status
end
TargetBot.Looting.process = function(targets, dangerLevel)
if (not items[1] and not ui.everyItem:isOn()) or not containers[1] then
status = ""
return false
end
if dangerLevel > tonumber(ui.maxDangerPanel.value:getText()) then
status = "High danger"
return false
end
if player:getFreeCapacity() < tonumber(ui.minCapacityPanel.value:getText()) then
status = "No cap"
TargetBot.Looting.list = {}
return false
end
local loot = TargetBot.Looting.list[1]
if loot == nil then
status = ""
return false
end
if waitTill > now then
return true
end
local containers = g_game.getContainers()
local lootContainers = TargetBot.Looting.getLootContainers(containers)
-- check if there's container for loot and has empty space for it
if not lootContainers[1] then
-- there's no space, don't loot
status = "No space"
return false
end
status = "Looting"
for index, container in pairs(containers) do
if container.lootContainer then
TargetBot.Looting.lootContainer(lootContainers, container)
return true
end
end
local pos = player:getPosition()
local dist = math.max(math.abs(pos.x-loot.pos.x), math.abs(pos.y-loot.pos.y))
if loot.tries > 30 or loot.pos.z ~= pos.z or dist > 20 then
table.remove(TargetBot.Looting.list, 1)
return true
end
local tile = g_map.getTile(loot.pos)
if dist >= 3 or not tile then
loot.tries = loot.tries + 1
TargetBot.walkTo(loot.pos, 20, { ignoreNonPathable = true, precision = 2 })
return true
end
local container = tile:getTopUseThing()
if not container or not container:isContainer() then
table.remove(TargetBot.Looting.list, 1)
return true
end
g_game.open(container)
waitTill = now + 1000 -- give it 1s to open
waitingForContainer = container:getId()
loot.tries = loot.tries + 10
return true
end
TargetBot.Looting.getLootContainers = function(containers)
local lootContainers = {}
local openedContainersById = {}
local toOpen = nil
for index, container in pairs(containers) do
openedContainersById[container:getContainerItem():getId()] = 1
if containersById[container:getContainerItem():getId()] and not container.lootContainer then
if container:getItemsCount() < container:getCapacity() then
table.insert(lootContainers, container)
else -- it's full, open next container if possible
for slot, item in ipairs(container:getItems()) do
if item:isContainer() and containersById[item:getId()] then
toOpen = {item, container}
break
end
end
end
end
end
if not lootContainers[1] then
if toOpen then
g_game.open(toOpen[1], toOpen[2])
waitTill = now + 500 -- wait 0.5s
return lootContainers
end
-- check containers one more time, maybe there's any loot container
for index, container in pairs(containers) do
if not containersById[container:getContainerItem():getId()] and not container.lootContainer then
for slot, item in ipairs(container:getItems()) do
if item:isContainer() and containersById[item:getId()] then
g_game.open(item)
waitTill = now + 500 -- wait 0.5s
return lootContainers
end
end
end
end
-- can't find any lootContainer, let's check slots, maybe there's one
for slot = InventorySlotFirst, InventorySlotLast do
local item = getInventoryItem(slot)
if item and item:isContainer() and not openedContainersById[item:getId()] then
-- container which is not opened yet, let's open it
g_game.open(item)
waitTill = now + 500 -- wait 0.5s
return lootContainers
end
end
end
return lootContainers
end
TargetBot.Looting.lootContainer = function(lootContainers, container)
-- loot items
local nextContainer = nil
for i, item in ipairs(container:getItems()) do
if item:isContainer() and not itemsById[item:getId()] then
nextContainer = item
elseif itemsById[item:getId()] or (ui.everyItem:isOn() and not item:isContainer()) then
item.lootTries = (item.lootTries or 0) + 1
if item.lootTries < 5 then -- if can't be looted within 0.5s then skip it
return TargetBot.Looting.lootItem(lootContainers, item)
end
elseif storage.foodItems and storage.foodItems[1] and lastFoodConsumption + 5000 < now then
for _, food in ipairs(storage.foodItems) do
if item:getId() == food.id then
g_game.use(item)
lastFoodConsumption = now
return
end
end
end
end
-- no more items to loot, open next container
if nextContainer then
nextContainer.lootTries = (nextContainer.lootTries or 0) + 1
if nextContainer.lootTries < 2 then -- max 0.6s to open it
g_game.open(nextContainer, container)
waitTill = now + 300 -- give it 0.3s to open
waitingForContainer = nextContainer:getId()
return
end
end
-- looting finished, remove container from list
container.lootContainer = false
g_game.close(container)
table.remove(TargetBot.Looting.list, 1)
end
TargetBot.Looting.lootItem = function(lootContainers, item)
if item:isStackable() then
local count = item:getCount()
for _, container in ipairs(lootContainers) do
for slot, citem in ipairs(container:getItems()) do
if item:getId() == citem:getId() and citem:getCount() < 100 then
g_game.move(item, container:getSlotPosition(slot - 1), count)
waitTill = now + 300 -- give it 0.3s to move item
return
end
end
end
end
local container = lootContainers[1]
g_game.move(item, container:getSlotPosition(container:getItemsCount()), 1)
waitTill = now + 300 -- give it 0.3s to move item
end
onContainerOpen(function(container, previousContainer)
if container:getContainerItem():getId() == waitingForContainer then
container.lootContainer = true
waitingForContainer = nil
end
end)
onCreatureDisappear(function(creature)
if not TargetBot.isOn() then return end
if not creature:isMonster() then return end
local config = TargetBot.Creature.calculateParams(creature, {}) -- return {craeture, config, danger, priority}
if not config.config or config.config.dontLoot then
return
end
local pos = player:getPosition()
local mpos = creature:getPosition()
local name = creature:getName()
if pos.z ~= mpos.z or math.max(math.abs(pos.x-mpos.x), math.abs(pos.y-mpos.y)) > 6 then return end
schedule(20, function() -- check in 20ms if there's container (dead body) on that tile
if not containers[1] then return end
if TargetBot.Looting.list[20] then return end -- too many items to loot
local tile = g_map.getTile(mpos)
if not tile then return end
local container = tile:getTopUseThing()
if not container or not container:isContainer() then return end
if not findPath(player:getPosition(), mpos, 6, {ignoreNonPathable=true, ignoreCreatures=true, ignoreCost=true}) then return end
table.insert(TargetBot.Looting.list, {pos=mpos, creature=name, container=container:getId(), added=now, tries=0})
container:setMarked('#000088')
end)
end)
| 412 | 0.866791 | 1 | 0.866791 | game-dev | MEDIA | 0.99186 | game-dev | 0.958715 | 1 | 0.958715 |
00-Evan/shattered-pixel-dungeon | 2,050 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/trinkets/EyeOfNewt.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2025 Evan Debenham
*
* 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.items.trinkets;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
public class EyeOfNewt extends Trinket {
{
image = ItemSpriteSheet.EYE_OF_NEWT;
}
@Override
protected int upgradeEnergyCost() {
//6 -> 8(14) -> 10(24) -> 12(36)
return 6+2*level();
}
@Override
public String statsDesc() {
if (isIdentified()){
return Messages.get(this, "stats_desc",
Messages.decimalFormat("#.##", 100*(1f-visionRangeMultiplier(buffedLvl()))),
mindVisionRange(buffedLvl()));
} else {
return Messages.get(this, "typical_stats_desc",
Messages.decimalFormat("#.##", 100*(1f-visionRangeMultiplier(0))),
mindVisionRange(0));
}
}
public static float visionRangeMultiplier(){
return visionRangeMultiplier(trinketLevel(EyeOfNewt.class));
}
public static float visionRangeMultiplier( int level ){
if (level < 0){
return 1;
} else {
return 0.875f - 0.125f*level;
}
}
public static int mindVisionRange(){
return mindVisionRange(trinketLevel(EyeOfNewt.class));
}
public static int mindVisionRange( int level ){
if (level < 0){
return 0;
} else {
return 2+level;
}
}
}
| 412 | 0.718019 | 1 | 0.718019 | game-dev | MEDIA | 0.850613 | game-dev | 0.863591 | 1 | 0.863591 |
LadybirdBrowser/ladybird | 1,384 | Libraries/LibWeb/UIEvents/TextEvent.cpp | /*
* Copyright (c) 2024, Jamie Mansfield <jmansfield@cadixdev.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/TextEventPrototype.h>
#include <LibWeb/UIEvents/TextEvent.h>
namespace Web::UIEvents {
GC_DEFINE_ALLOCATOR(TextEvent);
GC::Ref<TextEvent> TextEvent::create(JS::Realm& realm, FlyString const& event_name)
{
return realm.create<TextEvent>(realm, event_name);
}
TextEvent::TextEvent(JS::Realm& realm, FlyString const& event_name)
: UIEvent(realm, event_name)
{
}
TextEvent::~TextEvent() = default;
void TextEvent::initialize(JS::Realm& realm)
{
WEB_SET_PROTOTYPE_FOR_INTERFACE(TextEvent);
Base::initialize(realm);
}
// https://w3c.github.io/uievents/#dom-textevent-inittextevent
void TextEvent::init_text_event(String const& type, bool bubbles, bool cancelable, GC::Ptr<HTML::WindowProxy> view, String const& data)
{
// Initializes attributes of a TextEvent object. This method has the same behavior as UIEvent.initUIEvent().
// The value of detail remains undefined.
// 1. If this’s dispatch flag is set, then return.
if (dispatched())
return;
// 2. Initialize this with type, bubbles, and cancelable.
initialize_event(type, bubbles, cancelable);
// Implementation Defined: Initialise other values.
m_view = view;
m_data = data;
}
}
| 412 | 0.823664 | 1 | 0.823664 | game-dev | MEDIA | 0.606877 | game-dev | 0.789165 | 1 | 0.789165 |
thearcticfox25/AdvancedServer | 12,412 | advancedserver/ui/Main.c | #include "Config.h"
#include <string.h>
#include <ui/Main.h>
#include <ui/Components.h>
#include <ui/Presets.h>
#include <io/Threads.h>
#include <SDL.h>
#include <SDL_image.h>
#include <Lib.h>
#include <Maps.h>
#include <Server.h>
#include <States.h>
#include <stdbool.h>
#include <stdio.h>
int lobby = 0;
int text_index = 0;
int text_length = 0;
int g_mouseWheel = 0;
int g_pmouseWheel = 0;
PlayerAction player_action = { PAP_HIDDEN, NULL };
bool main_menu(Component* component);
bool options_menu(Component* component);
bool players_menu(Component* component);
bool info_menu(Component* component);
bool back_to_lobby(Component* component);
bool practice_mode(Component* component);
bool map_list_changed(Component* component);
bool map_list_reset(Component* component);
Component* base_components[] =
{
(Component*)&(ButtonCreate(59, 452, 32, 8, 0, 0, "main", main_menu, 0, 0, 0, 0)),
(Component*)&(ButtonCreate(272, 452, 54, 8, 0, 0, "options", options_menu, 0, 0, 0, 0)),
(Component*)&(ButtonCreate(536, 452, 53, 8, 0, 0, "players", players_menu, 0, 0, 0, 0)),
(Component*)&(LabelCreate(411, 35, "ver "SERVER_VERSION)),
};
Component* main_components[] =
{
(Component*)&(ImageCreate(16, 72, 348, 302, 647, 0, 348, 302)),
(Component*)&(ButtonCreate(420, 354, 128, 20, 16, 6, "back to lobby", back_to_lobby, 647, 342, 128, 20)),
(Component*)&(ButtonCreate(420, 316, 128, 20, 8, 6, "force test mode", practice_mode, 647, 342, 128, 20)),
};
Component* options_components[] =
{
(Component*)&(MapListCreate(0, 60, 420, 354, map_list_changed)),
(Component*)&(ImageCreate(0, 0, 640, 59, 0, 0, 640, 59)),
(Component*)&(ImageCreate(0, 419, 640, 61, 0, 419, 640, 61)),
(Component*)&(ImageCreate(424, 0, 7, 480, 640, 0, 7, 480)),
(Component*)&(MapListPresetCreate(448, 64, 128, 40)),
(Component*)&(ButtonCreate(448, 112, 128, 20, 16, 6, "disable all", map_list_reset, 647, 342, 128, 20)),
(Component*)&(PingLimitCreate(448, 142, 128, 40)),
(Component*)&(TButtonCreate(448, 188, 128, 20, 10, 6, "zone anticheat", (ButtonCallback)config_save, &g_config.states.gameplay.anticheat.zone_anticheat, true, 647, 342, 128, 20)),
(Component*)&(TButtonCreate(448, 216, 128, 20, 0, 6, "camp tease (pride)", (ButtonCallback)config_save, &g_config.states.results_misc.pride, false, 647, 342, 128, 20)),
};
Component* players_components[] =
{
(Component*)&(PlayerListCreate(16, 64)),
(Component*)&(PlayerListConfigCreate(216, 64, playerlist_op_update)),
(Component*)&(PlayerListConfigCreate(416, 64, playerlist_bannedips_update)),
};
Component* player_action_components[] =
{
(Component*)&(LabelCreate(32, 64, player_data)),
(Component*)&(LabelCreate(446, 64, "actions")),
(Component*)&(ButtonCreate(32, 32, 29, 8, 0, 0, "back", ui_button_back, 0, 0, 0, 0)),
(Component*)&(ButtonCreate(426, 84, 29, 8, 0, 0, "kick", ui_button_kick, 0, 0, 0, 0)),
(Component*)&(ButtonCreate(426, 96, 29, 8, 0, 0, "ban", ui_button_ban, 0, 0, 0, 0)),
(Component*)&(ButtonCreate(426, 108, 29, 8, 0, 0, "op", ui_button_op, 0, 0, 0, 0)),
};
void log_msg(const char* type, const char* message)
{
char msg[512];
if (strcmp(type, DEBUG_TYPE) == 0)
snprintf(msg, 512, "|%s~", message);
else if (strcmp(type, WARN_TYPE) == 0)
snprintf(msg, 512, "`%s~", message);
else if (strcmp(type, ERROR_TYPE) == 0)
snprintf(msg, 512, "\\%s~", message);
else
snprintf(msg, 512, "~%s", message);
if (text_length > 31)
{
for (int i = 1; i < 32; i++)
strncpy(text_buffer[i - 1], text_buffer[i], 255);
}
strncpy(text_buffer[text_index], msg, 255);
if (text_index < 31)
text_index++;
if (text_length < 32)
text_length++;
}
int server_loop(void)
{
if (!disaster_init())
return 1;
return disaster_run();
}
int console_loop(void)
{
SDL_Quit();
#ifdef WIN32
AllocConsole();
(void)freopen("CONOUT$", "w", stdout);
#endif
return server_loop();
}
int main(int argc, char** argv)
{
if (argc > 1)
{
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "--nogui") == 0)
return console_loop();
}
}
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
char msg[1024];
snprintf(msg, 1024, "%s\n\nPress OK to fallback to console mode.", SDL_GetError());
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error (Report to dev)", msg, NULL);
return console_loop();
}
if (!config_init()) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error (Report to dev)", "Unable to load config file!", NULL);
}
SDL_Window* window;
SDL_Renderer* renderer;
if (!(window = SDL_CreateWindow("AdvancedSer ver. " SERVER_VERSION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640 * g_config.miscellaneous.gui.interface_scale, 480 * g_config.miscellaneous.gui.interface_scale, SDL_WINDOW_SHOWN)))
{
char msg[1024];
snprintf(msg, 1024, "%s\n\nPress OK to fallback to console mode.", SDL_GetError());
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error (Report to dev)", msg, NULL);
return console_loop();
}
if (!(renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED)))
{
char msg[1024];
snprintf(msg, 1024, "%s\n\nPress OK to fallback to console mode.", SDL_GetError());
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error (Report to dev)", msg, NULL);
return console_loop();
}
if (!resources_load(renderer))
return console_loop();
log_hook(log_msg);
SDL_RenderSetLogicalSize(renderer, 640 * g_config.miscellaneous.gui.interface_scale, 480 * g_config.miscellaneous.gui.interface_scale);
SDL_RenderSetVSync(renderer, true);
Label label;
Thread thr;
ThreadSpawn(thr, server_loop, NULL);
bool running = true;
while (running)
{
SDL_Event ev;
while (SDL_PollEvent(&ev))
{
switch (ev.type)
{
case SDL_QUIT:
running = false;
break;
case SDL_MOUSEWHEEL:
g_mouseWheel = ev.wheel.y;
break;
}
}
SDL_RenderClear(renderer);
{
SDL_Rect src = (SDL_Rect){ 0, 0, 640, 480 };
SDL_Rect dst = (SDL_Rect){ 0, 0, 640 * g_config.miscellaneous.gui.interface_scale, 480 * g_config.miscellaneous.gui.interface_scale };
SDL_RenderCopy(renderer, g_textureSheet, &src, &dst);
switch (state)
{
case UST_MAIN:
{
for (int i = 0; i < sizeof(main_components) / sizeof(Component*); i++)
main_components[i]->update(renderer, main_components[i]);
for (int i = 0; i < text_length; i++)
{
label = LabelCreate(23, 80 + i * 9, text_buffer[i]);
label.update(renderer, (Component*)&label);
}
break;
}
case UST_OPTIONS:
{
for (int i = 0; i < sizeof(options_components) / sizeof(Component*); i++)
options_components[i]->update(renderer, options_components[i]);
break;
}
case UST_PLAYERS:
{
switch (player_action.panel_state)
{
case PAP_HIDDEN:
for (int i = 0; i < sizeof(players_components) / sizeof(Component*); i++)
players_components[i]->update(renderer, players_components[i]);
break;
case PAP_PEER:
refresh_peer_info(player_action.peer);
for (int i = 0; i < sizeof(player_action_components) / sizeof(Component*); i++)
player_action_components[i]->update(renderer, player_action_components[i]);
break;
}
break;
}
}
g_mouseWheel = 0;
if (!player_action.panel_state)
for (int i = 0; i < sizeof(base_components) / sizeof(Component*); i++)
base_components[i]->update(renderer, base_components[i]);
}
SDL_RenderPresent(renderer);
SDL_Delay(32);
}
return 0;
}
bool main_menu(Component* component)
{
state = UST_MAIN;
return true;
}
bool options_menu(Component* component)
{
state = UST_OPTIONS;
return true;
}
bool players_menu(Component* component)
{
state = UST_PLAYERS;
return true;
}
bool back_to_lobby(Component* component)
{
Server* server = disaster_get(lobby);
if(!server)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error (Report to dev)", "Server is not running (Check logs in Info tab)!", NULL);
return false;
}
MutexLock(server->state_lock);
{
if (server->state == ST_GAME && !server->game.end) {
if (!game_end(server, ED_TIMEOVER, false)) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error (Report to dev)", "Failed to return to lobby: game_end() returned FALSE", NULL);
}
} else if(server->state != ST_LOBBY && !lobby_init(server))
if (!lobby_init(server)) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error (Report to dev)", "Failed to return to lobby: lobby_init() returned FALSE", NULL);
}
}
MutexUnlock(server->state_lock);
return true;
}
bool practice_mode(Component* component)
{
Server* server = disaster_get(lobby);
if(!server)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error (Report to dev)", "Server is not running (Check logs in Info tab)!", NULL);
return false;
}
MutexLock(server->state_lock);
{
if(server->state == ST_LOBBY && server_ingame(server) > 1)
{
if(!charselect_init(20, server))
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error (Report to dev)", "Failed to set practice mode: charselect_init() returned FALSE", NULL);
}
}
}
MutexUnlock(server->state_lock);
return true;
}
bool map_list_changed(Component* component)
{
MapListPreset* preset_list = (MapListPreset*)options_components[4]; // Be careful, when you change "options" interface!!!
preset_list->preset = PRESET_CUSTOM;
for (int i = 0; i < PRESET_COUNT; i++)
{
if (memcmp(g_config.states.map_selection.map_list, g_defaultPresets[i].values, sizeof(g_config.states.map_selection.map_list)) == 0)
{
preset_list->preset = i;
break;
}
}
return true;
}
bool map_list_reset(Component* component)
{
MapListPreset* preset_list = (MapListPreset*)options_components[4]; // Be careful, when you change "options" interface!!!
preset_list->preset = PRESET_CUSTOM;
MutexLock(g_config.map_list_lock);
memset(g_config.states.map_selection.map_list, 0, sizeof(g_config.states.map_selection.map_list));
MutexUnlock(g_config.map_list_lock);
return true;
}
bool ui_update_delete(Component* component)
{
DeleteButton* delete = (DeleteButton*)component;
if (cJSON_HasObjectItem(delete->root, delete->key))
{
cJSON_DeleteItemFromObject(delete->root, delete->key);
if (!collection_save(delete->collection, delete->root))
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error (Report to dev)", "Failed to save collection!", NULL);
}
return false;
}
void ui_button_back()
{
player_action.panel_state = PAP_HIDDEN;
player_action.peer = NULL;
return;
}
bool ui_button_op(struct _Component* component)
{
if (!player_action.peer) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Peer is NULL, maybe player has left.", NULL);
ui_button_back();
return true;
}
Button* button = (Button*)component;
Server* server = player_action.peer->server;
bool res = true;
MutexLock(server->state_lock);
{
PeerData* peer = player_action.peer;
server_send_msg(server, peer->peer, CLRCODE_GRN "you're an operator now");
res = op_add(peer->nickname.value, peer->ip.value);
peer->op = g_config.states.lobby_misc.moderation.op_default_level;
}
MutexUnlock(server->state_lock);
RAssert(res);
return false;
}
bool ui_button_kick(struct _Component* component)
{
if (!player_action.peer) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Peer is NULL, maybe player has left.", NULL);
ui_button_back();
return true;
}
Button* button = (Button*)component;
Server* server = player_action.peer->server;
bool res = true;
MutexLock(server->state_lock);
{
PeerData* peer = player_action.peer;
server_disconnect(server, peer->peer, DR_KICKEDBYHOST, NULL);
res = timeout_set(peer->nickname.value, peer->udid.value, peer->ip.value, time(NULL) + 5);
}
MutexUnlock(server->state_lock);
RAssert(res);
ui_button_back();
return false;
}
bool ui_button_ban(struct _Component* component)
{
if (!player_action.peer) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Peer is NULL, maybe player has left.", NULL);
ui_button_back();
}
Button* button = (Button*)component;
Server* server = disaster_get(lobby);
bool res = true;
MutexLock(server->state_lock);
{
PeerData* peer = player_action.peer;
server_disconnect(server, peer->peer, DR_BANNEDBYHOST, NULL);
res = ban_add(peer->nickname.value, peer->udid.value, peer->ip.value);
}
MutexUnlock(server->state_lock);
RAssert(res);
ui_button_back();
return false;
} | 412 | 0.95968 | 1 | 0.95968 | game-dev | MEDIA | 0.394329 | game-dev | 0.888234 | 1 | 0.888234 |
pmndrs/xr | 3,180 | examples/handle/app.tsx | import { RigidBodyType } from '@dimforge/rapier3d-compat'
import { Environment, Gltf, Sky } from '@react-three/drei'
import { Canvas } from '@react-three/fiber'
import { Handle, OrbitHandles } from '@react-three/handle'
import { Physics, RapierRigidBody, RigidBody } from '@react-three/rapier'
import { createXRStore, noEvents, PointerEvents, useXRControllerLocomotion, XR, XROrigin } from '@react-three/xr'
import { ReactNode, RefObject, useMemo, useRef } from 'react'
import { Group, Object3D } from 'three'
const store = createXRStore()
export function App() {
return (
<>
<button onClick={() => store.enterVR()}>Enter VR</button>
<button onClick={() => store.enterAR()}>Enter AR</button>
<Canvas camera={{ position: [1, 1, 1] }} events={noEvents} style={{ width: '100%', flexGrow: 1 }}>
<PointerEvents />
<OrbitHandles />
<Sky />
<XR store={store}>
<Locomotion />
<Environment preset="city" />
<Physics>
<PhysicsHandle>
<Gltf scale={0.2} src="axe.gltf" />
</PhysicsHandle>
<RigidBody includeInvisible colliders="cuboid" type="fixed">
<mesh visible={true} scale={[200, 1, 200]} position={[0, -0.5, 0]}>
<boxGeometry />
</mesh>
</RigidBody>
</Physics>
</XR>
</Canvas>
</>
)
}
function PhysicsHandle({ children }: { children?: ReactNode }) {
const ref = useRef<RapierRigidBody>(null)
const groupRef = useRef<Group>(null)
const targetRef = useMemo(
() => new Proxy<RefObject<Object3D>>({ current: null }, { get: () => groupRef.current?.parent }),
[],
)
return (
<RigidBody ref={ref} colliders="trimesh" type="dynamic" position={[0, 1, 0]}>
<group ref={groupRef}>
<Handle
multitouch={false}
handleRef={groupRef}
scale={false}
targetRef={targetRef}
apply={(state) => {
const rigidBody = ref.current
if (rigidBody == null) {
return
}
if (state.last) {
rigidBody.setBodyType(RigidBodyType.Dynamic, true)
if (state.delta != null) {
const deltaTime = state.delta.time
const deltaPosition = state.delta.position.clone().divideScalar(deltaTime)
rigidBody.setLinvel(deltaPosition, true)
const deltaRotation = state.delta.rotation.clone()
deltaRotation.x /= deltaTime
deltaRotation.y /= deltaTime
deltaRotation.z /= deltaTime
rigidBody.setAngvel(deltaRotation, true)
}
} else {
rigidBody.setBodyType(RigidBodyType.KinematicPositionBased, true)
rigidBody.setRotation(state.current.quaternion, true)
rigidBody.setTranslation(state.current.position, true)
}
}}
>
{children}
</Handle>
</group>
</RigidBody>
)
}
function Locomotion() {
const ref = useRef<Group>(null)
useXRControllerLocomotion(ref)
return <XROrigin ref={ref} />
}
| 412 | 0.869889 | 1 | 0.869889 | game-dev | MEDIA | 0.532568 | game-dev,graphics-rendering,web-frontend | 0.936193 | 1 | 0.936193 |
PunishXIV/Splatoon | 7,824 | Presets/Heavensward/Hunt.md | The Hunt - HW B Ranks
```
~Lv2~{"Name":"B Ranks: Coerthas Western Highlands","Group":"The Hunt - HW B Ranks","ZoneLockH":[397],"ElementsL":[{"Name":"Alteci","type":1,"color":3372196352,"Filled":false,"thicc":3.0,"overlayText":"B Rank","refActorNPCID":4350,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true},{"Name":"Kreutzet","type":1,"color":3372196352,"Filled":false,"thicc":3.0,"overlayText":"B Rank","refActorNPCID":4351,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"B Ranks: The Dravanian Forelands","Group":"The Hunt - HW B Ranks","ZoneLockH":[398],"ElementsL":[{"Name":"Gnath Cometdrone","type":1,"color":3372196352,"Filled":false,"thicc":3.0,"overlayText":"B Rank","refActorNPCID":4352,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true},{"Name":"Thextera","type":1,"color":3372196352,"Filled":false,"thicc":3.0,"overlayText":"B Rank","refActorNPCID":4353,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"B Ranks: The Churning Mists","Group":"The Hunt - HW B Ranks","ZoneLockH":[400],"ElementsL":[{"Name":"Scitalis","type":1,"color":3372196352,"Filled":false,"thicc":3.0,"overlayText":"B Rank","refActorNPCID":4356,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true},{"Name":"The Scarecrow","type":1,"color":3372196352,"Filled":false,"thicc":3.0,"overlayText":"B Rank","refActorNPCID":4357,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"B Ranks: The Sea of Clouds","Group":"The Hunt - HW B Ranks","ZoneLockH":[401],"ElementsL":[{"Name":"Squonk","type":1,"color":3372196352,"Filled":false,"thicc":3.0,"overlayText":"B Rank","refActorNPCID":4358,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true},{"Name":"Sanu Vali of Dancing Wings","type":1,"color":3372196352,"Filled":false,"thicc":3.0,"overlayText":"B Rank","refActorNPCID":4359,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"B Ranks: The Dravanian Hinterlands","Group":"The Hunt - HW B Ranks","ZoneLockH":[399],"ElementsL":[{"Name":"Pterygotus","type":1,"color":3372196352,"Filled":false,"thicc":3.0,"overlayText":"B Rank","refActorNPCID":4354,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true},{"Name":"False Gigantopithecus","type":1,"color":3372196352,"Filled":false,"thicc":3.0,"overlayText":"B Rank","refActorNPCID":4355,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"B Ranks: Azys Lla","Group":"The Hunt - HW B Ranks","ZoneLockH":[402],"ElementsL":[{"Name":"Lycidas","type":1,"color":3372196352,"Filled":false,"thicc":3.0,"overlayText":"B Rank","refActorNPCID":4360,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true},{"Name":"Omni","type":1,"color":3372196352,"Filled":false,"thicc":3.0,"overlayText":"B Rank","refActorNPCID":4361,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
```
The Hunt - HW A Ranks
```
~Lv2~{"Name":"A Ranks: Coerthas Western Highlands","Group":"The Hunt - HW A Ranks","ZoneLockH":[397],"ElementsL":[{"Name":"Mirka","type":1,"thicc":3.0,"overlayText":"A Rank","refActorNPCID":4362,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true},{"Name":"Lyuba","type":1,"thicc":3.0,"overlayText":"A Rank","refActorNPCID":4363,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"A Ranks: The Dravanian Forelands","Group":"The Hunt - HW A Ranks","ZoneLockH":[398],"ElementsL":[{"Name":"Pylraster","type":1,"thicc":3.0,"overlayText":"A Rank","refActorNPCID":4364,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true},{"Name":"Lord of the Wyverns","type":1,"thicc":3.0,"overlayText":"A Rank","refActorNPCID":4365,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"A Ranks: The Churning Mists","Group":"The Hunt - HW A Ranks","ZoneLockH":[400],"ElementsL":[{"Name":"Bune","type":1,"thicc":3.0,"overlayText":"A Rank","refActorNPCID":4368,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true},{"Name":"Agathos","type":1,"thicc":3.0,"overlayText":"A Rank","refActorNPCID":4369,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"A Ranks: The Sea of Clouds","Group":"The Hunt - HW A Ranks","ZoneLockH":[401],"ElementsL":[{"Name":"Enkelados","type":1,"thicc":3.0,"overlayText":"A Rank","refActorNPCID":4370,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true},{"Name":"Sisiutl","type":1,"thicc":3.0,"overlayText":"A Rank","refActorNPCID":4371,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"A Ranks: The Dravanian Hinterlands","Group":"The Hunt - HW A Ranks","ZoneLockH":[399],"ElementsL":[{"Name":"Slipkinx Steeljoints","type":1,"thicc":3.0,"overlayText":"A Rank","refActorNPCID":4366,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true},{"Name":"Stolas","type":1,"thicc":3.0,"overlayText":"A Rank","refActorNPCID":4367,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"A Ranks: Azys Lla","Group":"The Hunt - HW A Ranks","ZoneLockH":[402],"ElementsL":[{"Name":"Campacti","type":1,"thicc":3.0,"overlayText":"A Rank","refActorNPCID":4372,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true},{"Name":"Stench Blossom","type":1,"thicc":3.0,"overlayText":"A Rank","refActorNPCID":4373,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
```
The Hunt - HW S Ranks
```
~Lv2~{"Name":"S Ranks: Coerthas Western Highlands","Group":"The Hunt - HW S Ranks","ZoneLockH":[397],"ElementsL":[{"Name":"Kaiser Behemoth","type":1,"color":3355484415,"Filled":false,"thicc":3.0,"overlayText":"S Rank","refActorNPCID":4374,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"S Ranks: The Dravanian Forelands","Group":"The Hunt - HW S Ranks","ZoneLockH":[398],"ElementsL":[{"Name":"Senmurv","type":1,"color":3355484415,"Filled":false,"thicc":3.0,"overlayText":"S Rank","refActorNPCID":4375,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"S Ranks: The Churning Mists","Group":"The Hunt - HW S Ranks","ZoneLockH":[400],"ElementsL":[{"Name":"Gandarewa","type":1,"color":3355484415,"Filled":false,"thicc":3.0,"overlayText":"S Rank","refActorNPCID":4377,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"S Ranks: The Sea of Clouds","Group":"The Hunt - HW S Ranks","ZoneLockH":[401],"ElementsL":[{"Name":"Bird of Paradise","type":1,"color":3355484415,"Filled":false,"thicc":3.0,"overlayText":"S Rank","refActorNPCID":4378,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"S Ranks: The Dravanian Hinterlands","Group":"The Hunt - HW S Ranks","ZoneLockH":[399],"ElementsL":[{"Name":"The Pale Rider","type":1,"color":3355484415,"Filled":false,"thicc":3.0,"overlayText":"S Rank","refActorNPCID":4376,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
~Lv2~{"Name":"S Ranks: Azys Lla","Group":"The Hunt - HW S Ranks","ZoneLockH":[402],"ElementsL":[{"Name":"Leucrotta","type":1,"color":3355484415,"Filled":false,"thicc":3.0,"overlayText":"S Rank","refActorNPCID":4380,"refActorComparisonType":4,"includeHitbox":true,"onlyTargetable":true,"tether":true}]}
```
| 412 | 0.547438 | 1 | 0.547438 | game-dev | MEDIA | 0.561574 | game-dev | 0.687869 | 1 | 0.687869 |
HurricanGame/Hurrican | 4,835 | Hurrican/src/enemies/Gegner_Auge.cpp | // --------------------------------------------------------------------------------------
// Das Augen Extra
//
// fliegt Sinus förmig durchs Level und hinterlässt nach Zerstörung ein Extra
// welches Extra, das steht in Value1
// --------------------------------------------------------------------------------------
#include "Gegner_Auge.hpp"
#include "stdafx.hpp"
// --------------------------------------------------------------------------------------
// Konstruktor
// --------------------------------------------------------------------------------------
GegnerAuge::GegnerAuge(int Wert1, int Wert2, bool Light) {
// DKS - Moved the Wert1 check check to the top, it was having no effect in its original
// position here:
// I discovered that GegnerExtras were being pushed with Value1 parameters that were
// outside their valid range, causing AnimPhase to be set to 40, when its only has
// 13 animation frames.
// Powerline ist Standard
//
if (Wert1 < 0 || Wert1 > 11)
Wert1 = 7;
Handlung = GEGNER::LAUFEN;
Energy = 1;
Value1 = Wert1;
Value2 = Wert2;
smokedelay = 0.2f;
ChangeLight = Light;
Destroyable = true;
xSpeed = 12.0f;
ySpeed = 0.0f;
yAcc = 4.0f;
AnimSpeed = 0.5f;
}
// --------------------------------------------------------------------------------------
// "Bewegungs KI"
// --------------------------------------------------------------------------------------
void GegnerAuge::DoKI() {
// rauchen lassen
//
smokedelay -= Timer.sync(0.25f);
if (smokedelay < 0.0f) {
smokedelay = 0.1f;
if (BlickRichtung == DirectionEnum::RECHTS)
PartikelSystem.PushPartikel(xPos + 8.0f, yPos + 18.0f, SMOKE2);
else
PartikelSystem.PushPartikel(xPos + 42.0f, yPos + 18.0f, SMOKE2);
}
// Animieren (nur drehen)
//
if (Handlung != GEGNER::STEHEN) {
AnimCount += Timer.getSpeedFactor(); // Animationscounter weiterzählen
if (Handlung == GEGNER::DREHEN) {
if (AnimCount > AnimSpeed) // Grenze überschritten ?
{
AnimCount = 0; // Dann wieder auf Null setzen
AnimPhase++; // Und nächste Animationsphase
if (AnimPhase >= AnimEnde) // Animation von zu Ende ?
{
AnimCount = 0.0f;
Handlung = GEGNER::DREHEN2;
BlickRichtung = Direction::invert(BlickRichtung);
}
}
} else if (Handlung == GEGNER::DREHEN2) {
if (AnimCount > AnimSpeed) // Grenze überschritten ?
{
AnimCount = 0; // Dann wieder auf Null setzen
AnimPhase--; // Und nächste Animationsphase
if (AnimPhase <= 0) // Animation von zu Ende ?
{
AnimPhase = 0; // Dann wieder von vorne beginnen
AnimEnde = 0;
Handlung = GEGNER::LAUFEN;
}
}
}
}
if (ySpeed > 12.0f)
yAcc = -4.0f;
else if (ySpeed < -12.0f)
yAcc = 4.0f;
// An der Decke bzw dem Boden
// abprallen
//
if (blocko & BLOCKWERT_WAND || blocko & BLOCKWERT_GEGNERWAND) {
yAcc = -yAcc;
ySpeed = -ySpeed;
}
if (blocku & BLOCKWERT_WAND || blocku & BLOCKWERT_GEGNERWAND) {
yAcc = -yAcc;
ySpeed = -ySpeed;
}
// Links oder rechts an der Wand abgeprallt ?
//
if ((xSpeed < 0.0f && (blockl & BLOCKWERT_WAND || blockl & BLOCKWERT_GEGNERWAND)) ||
(xSpeed > 0.0f && (blockr & BLOCKWERT_WAND || blockr & BLOCKWERT_GEGNERWAND))) {
Handlung = GEGNER::DREHEN;
AnimPhase = 0;
AnimCount = 0.0f;
AnimEnde = 5;
xSpeed *= -1.0f;
}
// Spieler verletzen ?
//
/*if (SpriteCollision(xPos, yPos, GegnerRect[GegnerArt],
pPlayer->xpos, pPlayer->ypos, pPlayer->CollideRect) == true)
pPlayer->DamagePlayer(Timer.sync(2.0f));*/
}
// --------------------------------------------------------------------------------------
// Auge explodiert
// --------------------------------------------------------------------------------------
void GegnerAuge::GegnerExplode() {
// Explosion
for (int i = 0; i < 5; i++)
PartikelSystem.PushPartikel(xPos - 15.0f + static_cast<float>(GetRandom(20)),
yPos - 15.0f + static_cast<float>(GetRandom(40)), EXPLOSION_MEDIUM2);
SoundManager.PlayWave(100, 128, -GetRandom(2000) + 11025, SOUND::EXPLOSION1); // Sound ausgeben
Player[0].Score += 100;
// Extra spawnen
Gegner.PushGegner(xPos + 12.0f, yPos + 12.0f, EXTRAS, Value1, 0, true);
}
| 412 | 0.815155 | 1 | 0.815155 | game-dev | MEDIA | 0.917294 | game-dev | 0.848196 | 1 | 0.848196 |
BG-Software-LLC/SuperiorSkyblock2 | 3,379 | src/main/java/com/bgsoftware/superiorskyblock/core/menu/button/impl/BankLogsPagedObjectButton.java | package com.bgsoftware.superiorskyblock.core.menu.button.impl;
import com.bgsoftware.superiorskyblock.api.enums.BankAction;
import com.bgsoftware.superiorskyblock.api.island.bank.BankTransaction;
import com.bgsoftware.superiorskyblock.api.menu.button.MenuTemplateButton;
import com.bgsoftware.superiorskyblock.api.menu.button.PagedMenuTemplateButton;
import com.bgsoftware.superiorskyblock.api.wrappers.SuperiorPlayer;
import com.bgsoftware.superiorskyblock.core.formatting.Formatters;
import com.bgsoftware.superiorskyblock.core.itemstack.ItemBuilder;
import com.bgsoftware.superiorskyblock.core.menu.button.AbstractPagedMenuButton;
import com.bgsoftware.superiorskyblock.core.menu.button.PagedMenuTemplateButtonImpl;
import com.bgsoftware.superiorskyblock.core.menu.impl.MenuBankLogs;
import com.bgsoftware.superiorskyblock.core.messages.Message;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import java.util.UUID;
public class BankLogsPagedObjectButton extends AbstractPagedMenuButton<MenuBankLogs.View, BankTransaction> {
private static final UUID CONSOLE_UUID = new UUID(0, 0);
private BankLogsPagedObjectButton(MenuTemplateButton<MenuBankLogs.View> templateButton, MenuBankLogs.View menuView) {
super(templateButton, menuView);
}
@Override
public void onButtonClick(InventoryClickEvent clickEvent) {
menuView.setFilteredPlayer(pagedObject.getPlayer());
menuView.refreshView();
}
@Override
public ItemStack modifyViewItem(ItemStack buttonItem) {
SuperiorPlayer inventoryViewer = menuView.getInventoryViewer();
return new ItemBuilder(buttonItem)
.replaceAll("{0}", pagedObject.getPosition() + "")
.replaceAll("{1}", getFilteredPlayerName(pagedObject.getPlayer() == null ? CONSOLE_UUID : pagedObject.getPlayer()))
.replaceAll("{2}", (pagedObject.getAction() == BankAction.WITHDRAW_COMPLETED ?
Message.BANK_WITHDRAW_COMPLETED : Message.BANK_DEPOSIT_COMPLETED).getMessage(inventoryViewer.getUserLocale()))
.replaceAll("{3}", pagedObject.getDate())
.replaceAll("{4}", pagedObject.getAmount() + "")
.replaceAll("{5}", Formatters.NUMBER_FORMATTER.format(pagedObject.getAmount()))
.replaceAll("{6}", Formatters.FANCY_NUMBER_FORMATTER.format(pagedObject.getAmount(), inventoryViewer.getUserLocale()))
.asSkullOf(inventoryViewer)
.build(inventoryViewer);
}
private static String getFilteredPlayerName(UUID filteredPlayer) {
if (filteredPlayer == null) {
return "";
} else if (filteredPlayer.equals(CONSOLE_UUID)) {
return "Console";
} else {
return plugin.getPlayers().getSuperiorPlayer(filteredPlayer).getName();
}
}
public static class Builder extends PagedMenuTemplateButtonImpl.AbstractBuilder<MenuBankLogs.View, BankTransaction> {
@Override
public PagedMenuTemplateButton<MenuBankLogs.View, BankTransaction> build() {
return new PagedMenuTemplateButtonImpl<>(buttonItem, clickSound, commands, requiredPermission,
lackPermissionSound, nullItem, getButtonIndex(), BankLogsPagedObjectButton.class, BankLogsPagedObjectButton::new);
}
}
}
| 412 | 0.827086 | 1 | 0.827086 | game-dev | MEDIA | 0.563762 | game-dev,desktop-app | 0.94509 | 1 | 0.94509 |
Patcher0/ThePitUltimate | 2,051 | core/src/main/java/net/mizukilab/pit/enchantment/type/rare/SolitudeEnchant.java | package net.mizukilab.pit.enchantment.type.rare;
import com.google.common.util.concurrent.AtomicDouble;
import net.mizukilab.pit.enchantment.AbstractEnchantment;
import net.mizukilab.pit.enchantment.param.event.PlayerOnly;
import net.mizukilab.pit.enchantment.param.item.ArmorOnly;
import net.mizukilab.pit.enchantment.rarity.EnchantmentRarity;
import net.mizukilab.pit.parm.listener.IPlayerDamaged;
import net.mizukilab.pit.util.PlayerUtil;
import net.mizukilab.pit.util.Utils;
import net.mizukilab.pit.util.cooldown.Cooldown;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @Author: Misoryan
* @Created_In: 2021/1/31 18:07
*/
@ArmorOnly
public class SolitudeEnchant extends AbstractEnchantment implements IPlayerDamaged {
@Override
public String getEnchantName() {
return "独处";
}
@Override
public int getMaxEnchantLevel() {
return 3;
}
@Override
public String getNbtName() {
return "solitude_enchant";
}
@Override
public EnchantmentRarity getRarity() {
return EnchantmentRarity.RARE;
}
@Override
public Cooldown getCooldown() {
return null;
}
@Override
public String getUsefulnessLore(int enchantLevel) {
return "&7在你周围7格范围内的玩家数低于或等于" + (enchantLevel >= 2 ? 2 : 1) + "时(不包括你),"
+ "/s&7你受到的玩家伤害 &9-" + (enchantLevel * 10 + 30) + "%";
}
@Override
@PlayerOnly
public void handlePlayerDamaged(int enchantLevel, Player myself, Entity attacker, double damage, AtomicDouble finalDamage, AtomicDouble boostDamage, AtomicBoolean cancel) {
int size = PlayerUtil.getNearbyPlayers(myself.getLocation(), 7).size();
int sybilLevel = Utils.getEnchantLevel(myself.getInventory().getLeggings(), "sybil");
if (sybilLevel > 0) {
size += sybilLevel + 1;
}
if (size <= (enchantLevel >= 2 ? 3 : 2)) {
boostDamage.getAndAdd(-0.1 * enchantLevel - 0.3);
}
}
}
| 412 | 0.856209 | 1 | 0.856209 | game-dev | MEDIA | 0.944622 | game-dev | 0.964555 | 1 | 0.964555 |
gridgain/gridgain | 10,018 | modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesForceRebuild.java | /*
* Copyright 2020 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.commandline.cache;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Logger;
import org.apache.ignite.internal.client.GridClient;
import org.apache.ignite.internal.client.GridClientConfiguration;
import org.apache.ignite.internal.commandline.AbstractCommand;
import org.apache.ignite.internal.commandline.Command;
import org.apache.ignite.internal.commandline.CommandArgIterator;
import org.apache.ignite.internal.commandline.TaskExecutor;
import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
import org.apache.ignite.internal.commandline.cache.argument.IndexForceRebuildCommandArg;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.internal.visor.cache.index.IndexForceRebuildTask;
import org.apache.ignite.internal.visor.cache.index.IndexForceRebuildTaskArg;
import org.apache.ignite.internal.visor.cache.index.IndexForceRebuildTaskRes;
import org.apache.ignite.internal.visor.cache.index.IndexRebuildStatusInfoContainer;
import static org.apache.ignite.internal.IgniteFeatures.INDEXES_MANIPULATIONS_FROM_CONTROL_SCRIPT;
import static org.apache.ignite.internal.client.util.GridClientUtils.nodeSupports;
import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
import static org.apache.ignite.internal.commandline.CommandLogger.or;
import static org.apache.ignite.internal.commandline.cache.CacheCommands.usageCache;
import static org.apache.ignite.internal.commandline.cache.CacheSubcommands.INDEX_FORCE_REBUILD;
import static org.apache.ignite.internal.commandline.cache.argument.IndexForceRebuildCommandArg.CACHE_NAMES;
import static org.apache.ignite.internal.commandline.cache.argument.IndexForceRebuildCommandArg.GROUP_NAMES;
import static org.apache.ignite.internal.commandline.cache.argument.IndexForceRebuildCommandArg.NODE_ID;
/**
* Cache subcommand that triggers indexes force rebuild.
*/
public class CacheIndexesForceRebuild extends AbstractCommand<CacheIndexesForceRebuild.Arguments> {
/** Command parsed arguments. */
private Arguments args;
/** {@inheritDoc} */
@Override public void printUsage(Logger logger) {
String desc = "Triggers rebuild of all indexes for specified caches or cache groups.";
Map<String, String> map = U.newLinkedHashMap(16);
map.put(NODE_ID.argName(), "Specify node for indexes rebuild.");
map.put(CACHE_NAMES.argName(), "Comma-separated list of cache names for which indexes should be rebuilt.");
map.put(GROUP_NAMES.argName(), "Comma-separated list of cache group names for which indexes should be rebuilt.");
usageCache(
logger,
INDEX_FORCE_REBUILD,
desc,
map,
NODE_ID.argName() + " nodeId",
or(CACHE_NAMES + " cacheName1,...cacheNameN", GROUP_NAMES + " groupName1,...groupNameN")
);
}
/** {@inheritDoc} */
@Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
IndexForceRebuildTaskRes taskRes;
IndexForceRebuildTaskArg taskArg = new IndexForceRebuildTaskArg(args.cacheGrps, args.cacheNames);
final UUID nodeId = args.nodeId;
try (GridClient client = Command.startClient(clientCfg)) {
if (nodeSupports(nodeId, client, INDEXES_MANIPULATIONS_FROM_CONTROL_SCRIPT))
taskRes = TaskExecutor.executeTaskByNameOnNode(
client,
IndexForceRebuildTask.class.getName(),
taskArg,
nodeId,
clientCfg
);
else {
logger.info("Indexes force rebuild is not supported by node " + nodeId);
return null;
}
}
printResult(taskRes, logger);
return taskRes;
}
/**
* @param res Rebuild task result.
* @param logger Logger to print to.
*/
private void printResult(IndexForceRebuildTaskRes res, Logger logger) {
if (!F.isEmpty(res.notFoundCacheNames())) {
String warning = args.cacheGrps == null ?
"WARNING: These caches were not found:" : "WARNING: These cache groups were not found:";
logger.info(warning);
res.notFoundCacheNames()
.stream()
.sorted()
.forEach(name -> logger.info(INDENT + name));
logger.info("");
}
if (!F.isEmpty(res.cachesWithRebuildInProgress())) {
logger.info("WARNING: These caches have indexes rebuilding in progress:");
printInfos(res.cachesWithRebuildInProgress(), logger);
logger.info("");
}
if (!F.isEmpty(res.cachesWithStartedRebuild())) {
logger.info("Indexes rebuild was started for these caches:");
printInfos(res.cachesWithStartedRebuild(), logger);
}
else
logger.info("WARNING: Indexes rebuild was not started for any cache. Check command input.");
logger.info("");
}
/** */
private void printInfos(Collection<IndexRebuildStatusInfoContainer> infos, Logger logger) {
infos.stream()
.sorted(IndexRebuildStatusInfoContainer.comparator())
.forEach(rebuildStatusInfo -> logger.info(INDENT + rebuildStatusInfo.toString()));
}
/** {@inheritDoc} */
@Override public Arguments arg() {
return args;
}
/** {@inheritDoc} */
@Override public String name() {
return INDEX_FORCE_REBUILD.text().toUpperCase();
}
/**
* Container for command arguments.
*/
public static class Arguments {
/** Node id. */
private UUID nodeId;
/** Cache group name. */
private Set<String> cacheGrps;
/** Cache name. */
private Set<String> cacheNames;
/** */
public Arguments(UUID nodeId, Set<String> cacheGrps, Set<String> cacheNames) {
this.nodeId = nodeId;
this.cacheGrps = cacheGrps;
this.cacheNames = cacheNames;
}
/**
* @return Node id.
*/
public UUID nodeId() {
return nodeId;
}
/**
* @return Cache group to scan for, null means scanning all groups.
*/
public Set<String> cacheGrps() {
return cacheGrps;
}
/**
* @return List of caches names.
*/
public Set<String> cacheNames() {
return cacheNames;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(Arguments.class, this);
}
}
/** {@inheritDoc} */
@Override public void parseArguments(CommandArgIterator argIterator) {
UUID nodeId = null;
Set<String> cacheGrps = null;
Set<String> cacheNames = null;
while (argIterator.hasNextSubArg()) {
String nextArg = argIterator.nextArg("");
IndexForceRebuildCommandArg arg = CommandArgUtils.of(nextArg, IndexForceRebuildCommandArg.class);
if (arg == null)
throw new IllegalArgumentException("Unknown argument: " + nextArg);
switch (arg) {
case NODE_ID:
if (nodeId != null)
throw new IllegalArgumentException(arg.argName() + " arg specified twice.");
nodeId = UUID.fromString(argIterator.nextArg("Failed to read node id."));
break;
case GROUP_NAMES:
if (cacheGrps != null)
throw new IllegalArgumentException(arg.argName() + " arg specified twice.");
cacheGrps = argIterator.nextStringSet("comma-separated list of cache group names.");
if (cacheGrps.equals(Collections.emptySet()))
throw new IllegalArgumentException(arg.argName() + " not specified.");
break;
case CACHE_NAMES:
if (cacheNames != null)
throw new IllegalArgumentException(arg.argName() + " arg specified twice.");
cacheNames = argIterator.nextStringSet("comma-separated list of cache names.");
if (cacheNames.equals(Collections.emptySet()))
throw new IllegalArgumentException(arg.argName() + " not specified.");
break;
default:
throw new IllegalArgumentException("Unknown argument: " + arg.argName());
}
}
args = new Arguments(nodeId, cacheGrps, cacheNames);
validateArguments();
}
/** */
private void validateArguments() {
if (args.nodeId == null)
throw new IllegalArgumentException(NODE_ID + " must be specified.");
if ((args.cacheGrps == null) == (args.cacheNames() == null))
throw new IllegalArgumentException("Either " + GROUP_NAMES + " or " + CACHE_NAMES + " must be specified.");
}
}
| 412 | 0.969826 | 1 | 0.969826 | game-dev | MEDIA | 0.297978 | game-dev | 0.988401 | 1 | 0.988401 |
transbot/EssentialCSharp | 1,316 | src/Chapter04/Listing04.51.BreakStatement.cs | namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_51;
public class TicTacToe // 声明TicTacToe类
{
public static void Main() // 声明程序的入口点
{
#region INCLUDE
int winner = 0;
// 存储每个玩家的落子位置
int[] playerPositions = { 0, 0 };
// 硬编码的棋盘位置
// X | 2 | O
// ---+---+---
// O | O | 6
// ---+---+---
// X | X | X
playerPositions[0] = 449;
playerPositions[1] = 28;
// 判断是否出现了一个赢家
int[] winningMasks = {
7, 56, 448, 73, 146, 292, 84, 273 };
// 遍历每个致胜掩码(winning mask),
// 判断是否有一位赢家
#region HIGHLIGHT
foreach (int mask in winningMasks)
{
#endregion HIGHLIGHT
if ((mask & playerPositions[0]) == mask)
{
winner = 1;
#region HIGHLIGHT
break;
#endregion HIGHLIGHT
}
else if((mask & playerPositions[1]) == mask)
{
winner = 2;
#region HIGHLIGHT
break;
#endregion HIGHLIGHT
}
#region HIGHLIGHT
}
#endregion HIGHLIGHT
Console.WriteLine($"玩家{ winner }是赢家。");
#endregion INCLUDE
}
}
| 412 | 0.693324 | 1 | 0.693324 | game-dev | MEDIA | 0.856182 | game-dev | 0.798017 | 1 | 0.798017 |
Shinoow/AbyssalCraft | 3,225 | src/main/java/com/shinoow/abyssalcraft/common/structures/overworld/StructureElevatedShrine.java | /*******************************************************************************
* AbyssalCraft
* Copyright (c) 2012 - 2025 Shinoow.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Contributors:
* Shinoow - implementation
******************************************************************************/
package com.shinoow.abyssalcraft.common.structures.overworld;
import java.util.Random;
import com.shinoow.abyssalcraft.api.block.ACBlocks;
import com.shinoow.abyssalcraft.common.blocks.BlockShoggothOoze;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class StructureElevatedShrine extends StructureDarklandsBase {
@Override
@SuppressWarnings("deprecation")
public boolean generate(World worldIn, Random rand, BlockPos pos) {
IBlockState brick_slab = ACBlocks.darkstone_brick_slab.getDefaultState();
IBlockState cobble = ACBlocks.darkstone_cobblestone.getDefaultState();
IBlockState cobble_wall = ACBlocks.darkstone_cobblestone_wall.getDefaultState();
for(int i = -2; i < 3; i++)
for(int j = -4; j < 5; j++){
boolean flag = i > -2 && i < 2;
if(j > -3 && j < 3 && flag)
for(int k = 1; k < 7; k++)
if(k != 2){
worldIn.setBlockToAir(pos.add(i, k, j));
worldIn.setBlockToAir(pos.add(j, k, i));
}
if((j == -4 || j == 4) && flag){
setBlockAndNotifyAdequately(worldIn, pos.add(j, 1, i), ACBlocks.darkstone_cobblestone_stairs.getStateFromMeta(j > 0 ? 1 : 0));
setBlockAndNotifyAdequately(worldIn, pos.add(i, 1, j), ACBlocks.darkstone_cobblestone_stairs.getStateFromMeta(j > 0 ? 3 : 2));
}
if((j == -3 || j == 3) && flag){
setBlockAndNotifyAdequately(worldIn, pos.add(j, 1, i), cobble);
setBlockAndNotifyAdequately(worldIn, pos.add(i, 1, j), cobble);
setBlockAndNotifyAdequately(worldIn, pos.add(j, 2, i), ACBlocks.darkstone_cobblestone_stairs.getStateFromMeta(j > 0 ? 1 : 0));
setBlockAndNotifyAdequately(worldIn, pos.add(i, 2, j), ACBlocks.darkstone_cobblestone_stairs.getStateFromMeta(j > 0 ? 3 : 2));
}
if(j == -2 || j == 2)
for(int k = 1; k < 7; k++){
if(i == -2 || i == 2){
setBlockAndNotifyAdequately(worldIn, pos.add(j, k, i), cobble_wall);
setBlockAndNotifyAdequately(worldIn, pos.add(i, k, j), cobble_wall);
}
if(k == 2 && flag){
setBlockAndNotifyAdequately(worldIn, pos.add(i, k, j), ACBlocks.monolith_stone.getDefaultState());
setBlockAndNotifyAdequately(worldIn, pos.add(j, k, i), ACBlocks.monolith_stone.getDefaultState());
}
if(k == 6){
setBlockAndNotifyAdequately(worldIn, pos.add(i, k, j), brick_slab);
setBlockAndNotifyAdequately(worldIn, pos.add(j, k, i), brick_slab);
}
}
if(j > -2 && j < 2 && flag)
setBlockAndNotifyAdequately(worldIn, pos.add(i, 2, j), ACBlocks.shoggoth_ooze.getDefaultState().withProperty(BlockShoggothOoze.LAYERS, 8));
}
placeStatue(worldIn, rand, pos.up(3));
return true;
}
}
| 412 | 0.902766 | 1 | 0.902766 | game-dev | MEDIA | 0.994405 | game-dev | 0.935624 | 1 | 0.935624 |
focus-creative-games/luban_examples | 1,933 | Projects/CfgValidator/Gen/common/GlobalConfig.cs |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using Luban;
using System.Text.Json;
namespace cfg.common
{
public sealed partial class GlobalConfig : Luban.BeanBase
{
public GlobalConfig(JsonElement _buf)
{
X1 = _buf.GetProperty("x1").GetInt32();
X2 = _buf.GetProperty("x2").GetInt32();
X3 = _buf.GetProperty("x3").GetInt32();
X4 = _buf.GetProperty("x4").GetInt32();
X5 = _buf.GetProperty("x5").GetInt32();
X6 = _buf.GetProperty("x6").GetInt32();
{ var __json0 = _buf.GetProperty("x7"); X7 = new System.Collections.Generic.List<int>(__json0.GetArrayLength()); foreach(JsonElement __e0 in __json0.EnumerateArray()) { int __v0; __v0 = __e0.GetInt32(); X7.Add(__v0); } }
}
public static GlobalConfig DeserializeGlobalConfig(JsonElement _buf)
{
return new common.GlobalConfig(_buf);
}
/// <summary>
/// 背包容量
/// </summary>
public readonly int X1;
public readonly int X2;
public readonly int X3;
public readonly int X4;
public readonly int X5;
public readonly int X6;
public readonly System.Collections.Generic.List<int> X7;
public const int __ID__ = -848234488;
public override int GetTypeId() => __ID__;
public void ResolveRef(Tables tables)
{
}
public override string ToString()
{
return "{ "
+ "x1:" + X1 + ","
+ "x2:" + X2 + ","
+ "x3:" + X3 + ","
+ "x4:" + X4 + ","
+ "x5:" + X5 + ","
+ "x6:" + X6 + ","
+ "x7:" + Luban.StringUtil.CollectionToString(X7) + ","
+ "}";
}
}
}
| 412 | 0.758446 | 1 | 0.758446 | game-dev | MEDIA | 0.313264 | game-dev | 0.671934 | 1 | 0.671934 |
MoonMotionProject/MoonMotion | 1,223 | Assets/Plugins/Moon Motion Toolkit/Build/Powerups/Objects Togglers/PowerupObjectsToggler.cs | using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
// Powerup Objects Toggler
// • adds the following pickup functionality to this powerup:
// · toggles the activity of each of the objects given by the objects to toggle connections, by the toggling setting
// • provides methods to toggle (the connected objects to toggle) on or off explicitly
public class PowerupObjectsToggler : Powerup
{
// variables //
// variables for: toggling objects //
[Header("Toggling Objects")]
[Tooltip("the objects to toggle the activity of")]
public GameObject[] objectsToToggle = New.arrayOf<GameObject>(); // connections - manual: the objects to toggle the active state of
[Tooltip("the toggling by which to toggle the objects")]
public Toggling objectToggling = Toggling.invertToggle; // setting: the toggling by which to toggle the objects
// methods //
// method: cast this powerup //
public override void cast()
=> objectsToToggle.toggleActivityBy(objectToggling);
// method: toggle the objects off //
public void toggleOff()
=> objectsToToggle.deactivate();
// method: toggle the objects on //
public void toggleOn()
=> objectsToToggle.activate();
} | 412 | 0.76554 | 1 | 0.76554 | game-dev | MEDIA | 0.884946 | game-dev | 0.678292 | 1 | 0.678292 |
rweyrauch/PrettyScribe | 8,526 | src/registry40k10th.ts | import {Wh40k} from "./roster40k10th";
import { filterAndOrderStats, formatStat, Entry, Registry } from "./rosterizer";
export function Create40kRosterFromRegistry(registry: Registry) {
return CreateRoster(registry);
}
export function CreateRoster(registry: Registry) {
const roster = new Wh40k.Roster40k();
const force = new Wh40k.Force();
roster._name = registry.name;
force._name = registry.info.name;
ParseDetachment(registry, force);
// Combat patrol puts units in traits instead of included.
for (const unitEntry of [...registry.assets.included, ...registry.assets.traits]) {
if (unitEntry.classIdentity != 'Unit') continue;
const unit = ParseUnit(unitEntry);
force._units.push(unit);
roster._cost.add(unit._cost);
for (const entry of [...unit._rules.entries(), ...unit._weaponRules.entries()]) {
force._rules.set(entry[0], entry[1]);
}
}
force._rules = new Map([...force._rules.entries()].sort()); // Sort rules.
roster._forces.push(force);
return roster;
}
function ParseDetachment(registry: Registry, force: Wh40k.Force) {
const detachment = registry.assets.traits.filter(t => t.classification === 'Detachment')[0];
if (!detachment) return;
force._faction = detachment.designation;
force._rules.set(detachment.designation, detachment.text);
}
function ParseUnit(entry: Entry) {
const unit = new Wh40k.Unit();
unit._name = entry.designation;
ParseUnitCost(entry, unit);
entry.keywords['Faction']?.sort().forEach(f => unit._factions.add(f));
entry.keywords['Keywords']?.sort().forEach(kw => unit._keywords.add(kw));
ParseModels(entry, unit);
ParseUnitProfiles(entry, unit);
unit.normalize();
return unit;
}
function ParseUnitCost(entry: Entry, unit: Wh40k.Unit) {
// Use the newer finalModelTally rule if available, otherwise use best effort
// stats.Models.
const numModels = entry.rules.finalModelTally?.evals[1]?.result.integer ||
entry.stats.Models?.value as number;
if (entry.stats.model3rdTally.value
&& numModels > (entry.stats.model3rdTally.value as number)) {
unit._cost._points = entry.stats.model4thCost.value as number;
} else if (entry.stats.model2ndTally.value
&& numModels > (entry.stats.model2ndTally.value as number)) {
unit._cost._points = entry.stats.model3rdCost.value as number;
} else if (entry.stats.model1stTally.value
&& numModels > (entry.stats.model1stTally.value as number)) {
unit._cost._points = entry.stats.model2ndCost.value as number;
} else if (entry.stats.Points) {
unit._cost._points = entry.stats.Points.value as number;
} else {
// Do nothing. Combat patrols don't include points
}
function countAddonPoints(e: Entry) {
for (const asset of [...e.assets.included, ...e.assets.traits]) {
if (asset.stats.Points?.value) {
unit._cost._points += asset.stats.Points.value as number;
}
countAddonPoints(asset);
}
}
countAddonPoints(entry);
}
function ParseUnitProfiles(entry: Entry, unit: Wh40k.Unit) {
for (const trait of [...entry.assets.traits, ...entry.assets.included]) {
const classification = trait.classification;
if (classification === 'Wargear' || classification === 'Enhancement') {
if (!unit._abilities[classification]) unit._abilities[classification] = new Map();
unit._abilities[classification].set(trait.designation, trait.text);
} else if (classification === 'Ability') {
if (trait.designation === 'Leader') {
// Clean up Leader text, by splitting it up between the core rule and
// the unit-specific rule.
const splitIndex = trait.text.indexOf("This model can be attached");
const coreRule = trait.text.substring(0, splitIndex).trim();
if (coreRule) unit._rules.set(trait.designation, coreRule);
const unitRule = trait.text.substring(splitIndex);
if (!unit._abilities['Abilities']) unit._abilities['Abilities'] = new Map();
unit._abilities['Abilities'].set(trait.designation, unitRule);
} else if ((trait.tally['Core'] || trait.tally['Faction'])
&& !trait.designation.startsWith('Damaged:')) {
// Core abilities don't have text in the unit datasheet, and get
// aggregated under Rules at the bottom of the page.
unit._rules.set(trait.designation, trait.text);
} else {
if (!unit._abilities['Abilities']) unit._abilities['Abilities'] = new Map();
unit._abilities['Abilities'].set(trait.designation, trait.text);
}
} else if (classification === 'Model') {
// Recurse into Model traits for additional profiles like weapons.
ParseUnitProfiles(trait, unit);
} else if (classification === 'Ranged Weapon'
|| classification === 'Melee Weapon'
|| classification === 'Weapon') {
ParseWeaponProfile(trait, unit);
// Check for attack profiles like standard/overcharge.
const subweaponTraits = trait.assets.traits.filter(t => t.classification.endsWith('Weapon'));
for (const subweaponTrait of subweaponTraits) {
ParseWeaponProfile(subweaponTrait, unit, trait.designation);
}
} else {
console.error(`Unexepcted classification '${classification}': ${trait.designation}`)
}
}
}
function ParseWeaponProfile(trait: Entry, unit: Wh40k.Unit, namePrefix?: string) {
const key = `${trait.classification}s`;
const row = converStatsToTabularProfileRow(trait, key, unit);
if (namePrefix) {
row[Object.keys(row)[0]] = `${namePrefix} - ${row[Object.keys(row)[0]]}`;
}
// Weapons with multiple profiles (eg standard/overcharge), don't have stats
// on the top level trait, so ignore them.
if (Object.keys(row).length <= 1) return;
const weaponAbilities = trait.assets.traits.filter(t => t.classification === 'Ability');
if (weaponAbilities.length > 0) {
weaponAbilities.forEach(a => unit._weaponRules.set(a.designation, a.text));
const keywords = weaponAbilities.map(t => t.designation);
Object.assign(row, { Keywords: keywords.join(', ') });
}
if (!unit._profileTables[key]) unit._profileTables[key] = new Wh40k.TabularProfile();
unit._profileTables[key].addRow(row);
}
function converStatsToTabularProfileRow(entry: Entry, name: string, unit?: Wh40k.Unit) {
const relevantStats = filterAndOrderStats(entry.stats);
const row = Object.assign(
{[name]: entry.designation},
Object.fromEntries(relevantStats.map(s => [s[0], formatStat(s[1])])));
return row;
}
function ParseModels(entry: Entry, unit: Wh40k.Unit) {
// Look for models in the unit...
const models = [...entry.assets.traits, ...entry.assets.included]
.filter(t => t.classification === 'Model');
// ... and if there are none, the unit covers the model.
if (models.length === 0) {
models.push(entry);
} else {
// Since there are Models, look for unit-level upgrades.
ParseModel(
{
designation: 'Unit Upgrades',
assets: entry.assets,
quantity: 1
} as Entry, unit,
/* addModelWithoutAddons = */ false);
}
for (const modelEntry of models) {
ParseUnitStatsProfile(modelEntry, unit);
ParseModel(modelEntry, unit);
}
}
function ParseUnitStatsProfile(entry: Entry, unit: Wh40k.Unit) {
const unitStats = converStatsToTabularProfileRow(entry, 'Unit');
if (Object.keys(unitStats).length > 1) {
if (!unit._profileTables['Unit']) unit._profileTables['Unit'] = new Wh40k.TabularProfile();
unit._profileTables['Unit'].addRow(Object.assign({ Unit: entry.designation }, unitStats));
}
}
function ParseModel(entry: Entry, unit: Wh40k.Unit, addModelWithoutAddons = true) {
const model = new Wh40k.Model();
model._name = entry.designation;
model._count = entry.quantity;
const addons = [...entry.assets.traits, ...entry.assets.included]
.filter(t => t.classification === 'Wargear'
|| t.classification === 'Weapon'
|| t.classification === 'Ranged Weapon'
|| t.classification === 'Melee Weapon'
|| t.classification === 'Enhancement');
for (const addon of addons) {
// Use Upgrades for everything, even Weapons, since Upgrades and Weapons
// are merged in the model list.
const upgrade = new Wh40k.Upgrade();
upgrade._name = addon.designation;
const cost = addon.stats.Points?.value;
if (cost) upgrade._cost._points = cost as number;
model._upgrades.push(upgrade);
}
if (addModelWithoutAddons || addons.length > 0) {
unit._models.push(model);
}
}
| 412 | 0.857352 | 1 | 0.857352 | game-dev | MEDIA | 0.623132 | game-dev | 0.961028 | 1 | 0.961028 |
Silverlan/pragma | 9,132 | core/client/src/entities/components/c_debug_component.cpp | // SPDX-FileCopyrightText: (c) 2021 Silverlan <opensource@pragma-engine.com>
// SPDX-License-Identifier: MIT
#include "stdafx_client.h"
#include "pragma/entities/components/c_debug_component.hpp"
#include "pragma/entities/components/c_radius_component.hpp"
#include <pragma/lua/converters/game_type_converters_t.hpp>
#include <pragma/entities/entity_iterator.hpp>
#include <pragma/entities/entity_component_system_t.hpp>
extern DLLCLIENT CEngine *c_engine;
using namespace pragma;
void CDebugTextComponent::ReloadDebugObject(Color color, const Vector3 &pos, DebugRenderInfo renderInfo) { m_debugObject = DebugRenderer::DrawText(renderInfo, m_debugText, m_size); }
void CDebugTextComponent::SetText(const std::string &text)
{
BaseDebugTextComponent::SetText(text);
if(GetEntity().IsSpawned())
ReloadDebugObject();
}
void CDebugTextComponent::SetSize(float size)
{
BaseDebugTextComponent::SetSize(size);
if(GetEntity().IsSpawned())
ReloadDebugObject();
}
Bool CDebugTextComponent::ReceiveNetEvent(pragma::NetEventId eventId, NetPacket &packet)
{
if(eventId == m_netEvSetText)
SetText(packet->ReadString());
else if(eventId == m_netEvSetSize)
SetSize(packet->Read<float>());
else
return CBaseNetComponent::ReceiveNetEvent(eventId, packet);
return true;
}
void CDebugTextComponent::ReceiveData(NetPacket &packet)
{
m_debugText = packet->ReadString();
m_size = packet->Read<float>();
}
void CDebugTextComponent::InitializeLuaObject(lua_State *l) { return TCBaseDebugComponent<BaseDebugTextComponent>::InitializeLuaObject<std::remove_reference_t<decltype(*this)>>(l); }
////////////////
void CBaseDebugOutlineComponent::ReceiveData(NetPacket &packet)
{
auto *pDebugComponent = dynamic_cast<BaseDebugOutlineComponent *>(this);
pDebugComponent->SetOutlineColor(packet->Read<Color>());
}
////////////////
void CDebugPointComponent::ReceiveData(NetPacket &packet) { m_bAxis = packet->Read<bool>(); }
void CDebugPointComponent::InitializeLuaObject(lua_State *l) { return BaseDebugPointComponent::InitializeLuaObject<std::remove_reference_t<decltype(*this)>>(l); }
void CDebugPointComponent::ReloadDebugObject(Color color, const Vector3 &pos, DebugRenderInfo renderInfo) { m_debugObject = DebugRenderer::DrawPoint(renderInfo); }
////////////////
void CDebugLineComponent::ReceiveData(NetPacket &packet)
{
m_targetEntity = packet->ReadString();
m_targetOrigin = packet->Read<Vector3>();
}
void CDebugLineComponent::InitializeLuaObject(lua_State *l) { return BaseDebugLineComponent::InitializeLuaObject<std::remove_reference_t<decltype(*this)>>(l); }
void CDebugLineComponent::ReloadDebugObject(Color color, const Vector3 &pos, DebugRenderInfo renderInfo)
{
auto origin = m_targetOrigin;
if(m_targetEntity.empty() == false) {
EntityIterator entIt {*GetEntity().GetNetworkState()->GetGameState(), EntityIterator::FilterFlags::Default | EntityIterator::FilterFlags::Pending};
entIt.AttachFilter<EntityIteratorFilterName>(m_targetEntity);
auto it = entIt.begin();
if(it == entIt.end())
return;
auto *ent = *it;
auto trComponent = (ent != nullptr) ? ent->GetTransformComponent() : nullptr;
if(!trComponent)
return;
origin = trComponent->GetPosition();
}
renderInfo.SetOrigin({});
m_debugObject = DebugRenderer::DrawLine(pos, origin, renderInfo);
}
////////////////
void CDebugBoxComponent::SetBounds(const Vector3 &min, const Vector3 &max)
{
if(m_bounds.first == min && m_bounds.second == max)
return;
BaseDebugBoxComponent::SetBounds(min, max);
ReloadDebugObject();
}
void CDebugBoxComponent::ReceiveData(NetPacket &packet)
{
CBaseDebugOutlineComponent::ReceiveData(packet);
m_bounds.first = packet->Read<Vector3>();
m_bounds.second = packet->Read<Vector3>();
}
void CDebugBoxComponent::InitializeLuaObject(lua_State *l) { return BaseDebugBoxComponent::InitializeLuaObject<std::remove_reference_t<decltype(*this)>>(l); }
void CDebugBoxComponent::ReloadDebugObject(Color color, const Vector3 &pos, DebugRenderInfo renderInfo)
{
auto pTrComponent = GetEntity().GetTransformComponent();
auto ang = pTrComponent != nullptr ? pTrComponent->GetAngles() : EulerAngles {};
if(m_outlineColor.a > 0)
renderInfo.SetOutlineColor(m_outlineColor);
renderInfo.SetRotation(uquat::create(ang));
m_debugObject = DebugRenderer::DrawBox(m_bounds.first, m_bounds.second, renderInfo);
}
Bool CDebugBoxComponent::ReceiveNetEvent(pragma::NetEventId eventId, NetPacket &packet)
{
if(eventId == m_netEvSetBounds) {
auto min = packet->Read<Vector3>();
auto max = packet->Read<Vector3>();
SetBounds(min, max);
}
else
return CBaseNetComponent::ReceiveNetEvent(eventId, packet);
return true;
}
////////////////
void CDebugSphereComponent::ReceiveData(NetPacket &packet)
{
CBaseDebugOutlineComponent::ReceiveData(packet);
m_recursionLevel = packet->Read<uint32_t>();
}
void CDebugSphereComponent::InitializeLuaObject(lua_State *l) { return BaseDebugSphereComponent::InitializeLuaObject<std::remove_reference_t<decltype(*this)>>(l); }
void CDebugSphereComponent::ReloadDebugObject(Color color, const Vector3 &pos, DebugRenderInfo renderInfo)
{
auto pRadiusComponent = GetEntity().GetComponent<CRadiusComponent>();
if(pRadiusComponent.expired())
return;
if(m_outlineColor.a > 0)
renderInfo.SetOutlineColor(m_outlineColor);
m_debugObject = DebugRenderer::DrawSphere(renderInfo, pRadiusComponent->GetRadius(), m_recursionLevel);
}
////////////////
void CDebugConeComponent::SetConeAngle(float angle)
{
if(angle == m_coneAngle)
return;
BaseDebugConeComponent::SetConeAngle(angle);
ReloadDebugObject();
}
void CDebugConeComponent::SetStartRadius(float radius)
{
if(radius == m_startRadius)
return;
BaseDebugConeComponent::SetStartRadius(radius);
ReloadDebugObject();
}
void CDebugConeComponent::ReceiveData(NetPacket &packet)
{
CBaseDebugOutlineComponent::ReceiveData(packet);
m_coneAngle = packet->Read<float>();
m_startRadius = packet->Read<float>();
m_segmentCount = packet->Read<uint32_t>();
}
void CDebugConeComponent::InitializeLuaObject(lua_State *l) { return BaseDebugConeComponent::InitializeLuaObject<std::remove_reference_t<decltype(*this)>>(l); }
void CDebugConeComponent::ReloadDebugObject(Color color, const Vector3 &pos, DebugRenderInfo renderInfo)
{
auto &ent = GetEntity();
auto pRadiusComponent = ent.GetComponent<CRadiusComponent>();
auto pTrComponent = ent.GetTransformComponent();
if(pRadiusComponent.expired() || pTrComponent == nullptr)
return;
if(m_outlineColor.a > 0)
renderInfo.SetOutlineColor(m_outlineColor);
if(m_startRadius > 0.f) {
// Truncated Cone
m_debugObject = DebugRenderer::DrawTruncatedCone(renderInfo, m_startRadius, pTrComponent->GetForward(), pRadiusComponent->GetRadius(), m_coneAngle, m_segmentCount);
return;
}
m_debugObject = DebugRenderer::DrawCone(renderInfo, pTrComponent->GetForward(), pRadiusComponent->GetRadius(), m_coneAngle, m_segmentCount);
}
Bool CDebugConeComponent::ReceiveNetEvent(pragma::NetEventId eventId, NetPacket &packet)
{
if(eventId == m_netEvSetConeAngle)
SetConeAngle(packet->Read<float>());
else if(eventId == m_netEvSetStartRadius)
SetStartRadius(packet->Read<float>());
else
return CBaseNetComponent::ReceiveNetEvent(eventId, packet);
return true;
}
////////////////
void CDebugCylinderComponent::SetLength(float length)
{
if(length == m_length)
return;
BaseDebugCylinderComponent::SetLength(length);
ReloadDebugObject();
}
void CDebugCylinderComponent::ReceiveData(NetPacket &packet)
{
CBaseDebugOutlineComponent::ReceiveData(packet);
m_length = packet->Read<float>();
m_segmentCount = packet->Read<uint32_t>();
}
void CDebugCylinderComponent::InitializeLuaObject(lua_State *l) { return BaseDebugCylinderComponent::InitializeLuaObject<std::remove_reference_t<decltype(*this)>>(l); }
void CDebugCylinderComponent::ReloadDebugObject(Color color, const Vector3 &pos, DebugRenderInfo renderInfo)
{
auto &ent = GetEntity();
auto pRadiusComponent = ent.GetComponent<CRadiusComponent>();
auto pTrComponent = ent.GetTransformComponent();
if(pRadiusComponent.expired() || pTrComponent == nullptr)
return;
if(m_outlineColor.a > 0)
renderInfo.SetOutlineColor(m_outlineColor);
m_debugObject = DebugRenderer::DrawCylinder(renderInfo, pTrComponent->GetForward(), m_length, pRadiusComponent->GetRadius(), m_segmentCount);
}
Bool CDebugCylinderComponent::ReceiveNetEvent(pragma::NetEventId eventId, NetPacket &packet)
{
if(eventId == m_netEvSetLength)
SetLength(packet->Read<float>());
else
return CBaseNetComponent::ReceiveNetEvent(eventId, packet);
return true;
}
////////////////
void CDebugPlaneComponent::InitializeLuaObject(lua_State *l) { return BaseDebugPlaneComponent::InitializeLuaObject<std::remove_reference_t<decltype(*this)>>(l); }
void CDebugPlaneComponent::ReloadDebugObject(Color color, const Vector3 &pos, DebugRenderInfo renderInfo)
{
auto pTrComponent = GetEntity().GetTransformComponent();
if(pTrComponent == nullptr)
return;
umath::Plane plane {pTrComponent->GetForward(), 0.0};
plane.MoveToPos(pos);
m_debugObject = DebugRenderer::DrawPlane(plane, color);
}
void CDebugPlaneComponent::ReceiveData(NetPacket &packet) {}
| 412 | 0.923958 | 1 | 0.923958 | game-dev | MEDIA | 0.687062 | game-dev,graphics-rendering | 0.96759 | 1 | 0.96759 |
LoliKingdom/LoliASM | 1,981 | src/main/java/zone/rong/loliasm/common/internal/mixins/CapabilityDispatcherMixin.java | package zone.rong.loliasm.common.internal.mixins;
import net.minecraft.nbt.NBTBase;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityDispatcher;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.util.INBTSerializable;
import org.apache.commons.lang3.ArrayUtils;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import zone.rong.loliasm.LoliLogger;
import zone.rong.loliasm.api.ICapabilityDispatcherManipulator;
import javax.annotation.Nullable;
import java.util.Arrays;
@Mixin(value = CapabilityDispatcher.class, remap = false)
public class CapabilityDispatcherMixin implements ICapabilityDispatcherManipulator {
@Shadow private ICapabilityProvider[] caps;
@Shadow private INBTSerializable<NBTBase>[] writers;
@Shadow private String[] names;
@Override
public void injectCapability(String name, ICapabilityProvider provider) {
this.caps = ArrayUtils.add(this.caps, provider);
if (provider instanceof INBTSerializable) {
this.writers = ArrayUtils.add(this.writers, (INBTSerializable<NBTBase>) provider);
this.names = ArrayUtils.add(this.names, name);
}
}
@Override
public <T> void stripCapability(String name, Capability<T> capability, @Nullable EnumFacing facing, T capabilityInstance) {
ICapabilityProvider provider = null;
for (ICapabilityProvider p : this.caps) {
if (p.getCapability(capability, facing) == capabilityInstance) {
provider = p;
}
}
if (provider == null) {
LoliLogger.instance.error("{}@{} does not exist in {}", name, capability.getName(), Arrays.toString(this.caps));
return;
}
this.caps = ArrayUtils.removeElement(this.caps, provider);
if (provider instanceof INBTSerializable) {
this.writers = ArrayUtils.removeElement(this.writers, provider);
this.names = ArrayUtils.removeElement(this.names, name);
}
}
} | 412 | 0.839222 | 1 | 0.839222 | game-dev | MEDIA | 0.942859 | game-dev | 0.843906 | 1 | 0.843906 |
oot-pc-port/oot-pc-port | 2,859 | asm/non_matchings/overlays/actors/ovl_En_Goroiwa/func_80A4C1C4.s | glabel func_80A4C1C4
/* 00524 80A4C1C4 848F001C */ lh $t7, 0x001C($a0) ## 0000001C
/* 00528 80A4C1C8 3C0E0001 */ lui $t6, 0x0001 ## $t6 = 00010000
/* 0052C 80A4C1CC 01C57021 */ addu $t6, $t6, $a1
/* 00530 80A4C1D0 8DCE1E08 */ lw $t6, 0x1E08($t6) ## 00011E08
/* 00534 80A4C1D4 31F800FF */ andi $t8, $t7, 0x00FF ## $t8 = 00000000
/* 00538 80A4C1D8 0018C8C0 */ sll $t9, $t8, 3
/* 0053C 80A4C1DC 01D91021 */ addu $v0, $t6, $t9
/* 00540 80A4C1E0 8C470004 */ lw $a3, 0x0004($v0) ## 00000004
/* 00544 80A4C1E4 3C0B8016 */ lui $t3, 0x8016 ## $t3 = 80160000
/* 00548 80A4C1E8 3C0100FF */ lui $at, 0x00FF ## $at = 00FF0000
/* 0054C 80A4C1EC 00074100 */ sll $t0, $a3, 4
/* 00550 80A4C1F0 00084F02 */ srl $t1, $t0, 28
/* 00554 80A4C1F4 00095080 */ sll $t2, $t1, 2
/* 00558 80A4C1F8 016A5821 */ addu $t3, $t3, $t2
/* 0055C 80A4C1FC 8D6B6FA8 */ lw $t3, 0x6FA8($t3) ## 80166FA8
/* 00560 80A4C200 3421FFFF */ ori $at, $at, 0xFFFF ## $at = 00FFFFFF
/* 00564 80A4C204 00067880 */ sll $t7, $a2, 2
/* 00568 80A4C208 01E67823 */ subu $t7, $t7, $a2
/* 0056C 80A4C20C 00E16024 */ and $t4, $a3, $at
/* 00570 80A4C210 000F7840 */ sll $t7, $t7, 1
/* 00574 80A4C214 016C6821 */ addu $t5, $t3, $t4
/* 00578 80A4C218 01AF1821 */ addu $v1, $t5, $t7
/* 0057C 80A4C21C 3C018000 */ lui $at, 0x8000 ## $at = 80000000
/* 00580 80A4C220 00611821 */ addu $v1, $v1, $at
/* 00584 80A4C224 84780000 */ lh $t8, 0x0000($v1) ## 00000000
/* 00588 80A4C228 44982000 */ mtc1 $t8, $f4 ## $f4 = 0.00
/* 0058C 80A4C22C 00000000 */ nop
/* 00590 80A4C230 468021A0 */ cvt.s.w $f6, $f4
/* 00594 80A4C234 E4860024 */ swc1 $f6, 0x0024($a0) ## 00000024
/* 00598 80A4C238 846E0002 */ lh $t6, 0x0002($v1) ## 00000002
/* 0059C 80A4C23C 448E4000 */ mtc1 $t6, $f8 ## $f8 = 0.00
/* 005A0 80A4C240 00000000 */ nop
/* 005A4 80A4C244 468042A0 */ cvt.s.w $f10, $f8
/* 005A8 80A4C248 E48A0028 */ swc1 $f10, 0x0028($a0) ## 00000028
/* 005AC 80A4C24C 84790004 */ lh $t9, 0x0004($v1) ## 00000004
/* 005B0 80A4C250 44998000 */ mtc1 $t9, $f16 ## $f16 = 0.00
/* 005B4 80A4C254 00000000 */ nop
/* 005B8 80A4C258 468084A0 */ cvt.s.w $f18, $f16
/* 005BC 80A4C25C 03E00008 */ jr $ra
/* 005C0 80A4C260 E492002C */ swc1 $f18, 0x002C($a0) ## 0000002C
| 412 | 0.611311 | 1 | 0.611311 | game-dev | MEDIA | 0.882966 | game-dev | 0.76913 | 1 | 0.76913 |
fulpstation/fulpstation | 1,057 | code/__DEFINES/dcs/signals/signals_material_container.dm | //Material Container Signals
/// Called from datum/component/material_container/proc/can_hold_material() : (mat)
#define COMSIG_MATCONTAINER_MAT_CHECK "matcontainer_mat_check"
#define MATCONTAINER_ALLOW_MAT (1<<0)
/// Called from datum/component/material_container/proc/user_insert() : (target_item, user)
#define COMSIG_MATCONTAINER_PRE_USER_INSERT "matcontainer_pre_user_insert"
#define MATCONTAINER_BLOCK_INSERT (1<<1)
/// Called from datum/component/material_container/proc/insert_item() : (item, primary_mat, mats_consumed, material_amount, context)
#define COMSIG_MATCONTAINER_ITEM_CONSUMED "matcontainer_item_consumed"
/// Called from datum/component/material_container/proc/retrieve_sheets() : (new_sheets, context)
#define COMSIG_MATCONTAINER_SHEETS_RETRIEVED "matcontainer_sheets_retrieved"
//mat container signals but from the ore silo's perspective
/// Called from /obj/machinery/ore_silo/on_item_consumed() : (container, item_inserted, last_inserted_id, mats_consumed, amount_inserted)
#define COMSIG_SILO_ITEM_CONSUMED "silo_item_consumed"
| 412 | 0.817952 | 1 | 0.817952 | game-dev | MEDIA | 0.356453 | game-dev | 0.726398 | 1 | 0.726398 |
rbfx/rbfx | 3,345 | Source/ThirdParty/Bullet/Bullet/BulletCollision/CollisionShapes/btTriangleIndexVertexArray.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btTriangleIndexVertexArray.h"
btTriangleIndexVertexArray::btTriangleIndexVertexArray(int numTriangles, int* triangleIndexBase, int triangleIndexStride, int numVertices, btScalar* vertexBase, int vertexStride)
: m_hasAabb(0)
{
btIndexedMesh mesh;
mesh.m_numTriangles = numTriangles;
mesh.m_triangleIndexBase = (const unsigned char*)triangleIndexBase;
mesh.m_triangleIndexStride = triangleIndexStride;
mesh.m_numVertices = numVertices;
mesh.m_vertexBase = (const unsigned char*)vertexBase;
mesh.m_vertexStride = vertexStride;
addIndexedMesh(mesh);
}
btTriangleIndexVertexArray::~btTriangleIndexVertexArray()
{
}
void btTriangleIndexVertexArray::getLockedVertexIndexBase(unsigned char** vertexbase, int& numverts, PHY_ScalarType& type, int& vertexStride, unsigned char** indexbase, int& indexstride, int& numfaces, PHY_ScalarType& indicestype, int subpart)
{
btAssert(subpart < getNumSubParts());
btIndexedMesh& mesh = m_indexedMeshes[subpart];
numverts = mesh.m_numVertices;
(*vertexbase) = (unsigned char*)mesh.m_vertexBase;
type = mesh.m_vertexType;
vertexStride = mesh.m_vertexStride;
numfaces = mesh.m_numTriangles;
(*indexbase) = (unsigned char*)mesh.m_triangleIndexBase;
indexstride = mesh.m_triangleIndexStride;
indicestype = mesh.m_indexType;
}
void btTriangleIndexVertexArray::getLockedReadOnlyVertexIndexBase(const unsigned char** vertexbase, int& numverts, PHY_ScalarType& type, int& vertexStride, const unsigned char** indexbase, int& indexstride, int& numfaces, PHY_ScalarType& indicestype, int subpart) const
{
const btIndexedMesh& mesh = m_indexedMeshes[subpart];
numverts = mesh.m_numVertices;
(*vertexbase) = (const unsigned char*)mesh.m_vertexBase;
type = mesh.m_vertexType;
vertexStride = mesh.m_vertexStride;
numfaces = mesh.m_numTriangles;
(*indexbase) = (const unsigned char*)mesh.m_triangleIndexBase;
indexstride = mesh.m_triangleIndexStride;
indicestype = mesh.m_indexType;
}
bool btTriangleIndexVertexArray::hasPremadeAabb() const
{
return (m_hasAabb == 1);
}
void btTriangleIndexVertexArray::setPremadeAabb(const btVector3& aabbMin, const btVector3& aabbMax) const
{
m_aabbMin = aabbMin;
m_aabbMax = aabbMax;
m_hasAabb = 1; // this is intentionally an int see notes in header
}
void btTriangleIndexVertexArray::getPremadeAabb(btVector3* aabbMin, btVector3* aabbMax) const
{
*aabbMin = m_aabbMin;
*aabbMax = m_aabbMax;
}
| 412 | 0.881544 | 1 | 0.881544 | game-dev | MEDIA | 0.823056 | game-dev | 0.874387 | 1 | 0.874387 |
Vawlpe/BakuganDotC-decomp | 2,896 | src/TODO/FUN_089e4664@089e4664.c | #include "ULUS10536_MYTHREAD-MAIN.BIN.h"
void FUN_089e4664(int param_1,int param_2,int param_3)
{
int iVar1;
int iVar2;
undefined (*pauVar3) [12];
ushort *puVar4;
uint uVar5;
int iVar6;
float fVar7;
float local_50 [3];
undefined4 *local_44;
undefined (*local_40) [12];
int local_3c;
iVar1 = FUN_089e9858(param_2,param_3);
if (iVar1 != 0) {
local_50[0] = INFINITY;
if (*(int *)(param_2 + 0x20) == 0) {
FUN_089e4664(param_1,*(undefined4 *)(param_2 + 0x28),param_3);
FUN_089e4664(param_1,*(undefined4 *)(param_2 + 0x2c),param_3);
}
else {
iVar1 = 0;
local_40 = (undefined (*) [12])(param_3 + 0x10);
if (0 < *(int *)(param_2 + 0x20)) {
iVar6 = 0;
local_44 = &DAT_08af8390;
local_3c = param_3;
do {
puVar4 = (ushort *)
(*(int *)(param_1 + 0x14) +
(uint)*(ushort *)(*(int *)(param_2 + 0x24) + iVar6) * 10);
uVar5 = (uint)*(char *)(DAT_08af83b0 + ((int)*(char *)(puVar4 + 4) & 0xfU));
if ((uVar5 == 0xffffffff) || ((1 << (uVar5 & 0x1f) & DAT_08af8380) != 0)) {
pauVar3 = (undefined (*) [12])(*(int *)(param_1 + 0xc) + (uint)puVar4[3] * 0x10);
fVar7 = (float)vdot_t(*pauVar3,*local_40);
if (0.0 <= fVar7 - *(float *)pauVar3[1]) {
iVar2 = *(int *)(param_1 + 4);
iVar2 = FUN_089e45d0(iVar2 + (uint)*puVar4 * 0x10,iVar2 + (uint)puVar4[1] * 0x10,
iVar2 + (uint)puVar4[2] * 0x10,local_3c,local_50);
if (iVar2 == 0) {
iVar2 = *(int *)(param_2 + 0x20);
}
else if ((DAT_08ac5ce8 == (code *)0x0) ||
(iVar2 = (*DAT_08ac5ce8)(param_1,puVar4), iVar2 != 0)) {
if (local_50[0] < DAT_08b002a0) {
DAT_08b002a0 = local_50[0];
DAT_08b00280 = *local_44;
DAT_08b00284 = local_44[1];
DAT_08b00288 = local_44[2];
DAT_08b0028c = local_44[3];
DAT_08b002a8 = DAT_08af8384;
DAT_08b002b8 = DAT_08af8388;
DAT_08ac5c98 = 1;
iVar2 = *(int *)(param_2 + 0x20);
DAT_08b002ac = param_1;
DAT_08b002b0 = puVar4;
DAT_08b002b4 = uVar5;
}
else {
iVar2 = *(int *)(param_2 + 0x20);
}
}
else {
iVar2 = *(int *)(param_2 + 0x20);
}
}
else {
iVar2 = *(int *)(param_2 + 0x20);
}
}
else {
iVar2 = *(int *)(param_2 + 0x20);
}
iVar1 = iVar1 + 1;
iVar6 = iVar6 + 2;
} while (iVar1 < iVar2);
}
}
}
return;
}
| 412 | 0.599629 | 1 | 0.599629 | game-dev | MEDIA | 0.624221 | game-dev | 0.855158 | 1 | 0.855158 |
FlashyReese/sodium-extra | 49,726 | common/src/main/java/me/flashyreese/mods/sodiumextra/client/gui/SodiumExtraGameOptionPages.java | package me.flashyreese.mods.sodiumextra.client.gui;
import com.google.common.collect.ImmutableList;
import me.flashyreese.mods.sodiumextra.client.SodiumExtraClientMod;
import me.flashyreese.mods.sodiumextra.client.gui.options.control.DynamicSliderControl;
import me.flashyreese.mods.sodiumextra.client.gui.options.control.SliderControlExtended;
import me.flashyreese.mods.sodiumextra.client.gui.options.storage.SodiumExtraOptionsStorage;
import me.flashyreese.mods.sodiumextra.common.util.ControlValueFormatterExtended;
import net.caffeinemc.mods.sodium.client.gui.options.*;
import net.caffeinemc.mods.sodium.client.gui.options.control.ControlValueFormatter;
import net.caffeinemc.mods.sodium.client.gui.options.control.CyclingControl;
import net.caffeinemc.mods.sodium.client.gui.options.control.SliderControl;
import net.caffeinemc.mods.sodium.client.gui.options.control.TickBoxControl;
import net.caffeinemc.mods.sodium.client.gui.options.storage.MinecraftOptionsStorage;
import net.minecraft.client.Minecraft;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.material.FogType;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
public class SodiumExtraGameOptionPages {
public static final SodiumExtraOptionsStorage sodiumExtraOpts = new SodiumExtraOptionsStorage();
public static final MinecraftOptionsStorage vanillaOpts = new MinecraftOptionsStorage();
private static Component parseVanillaString(String key) {
return Component.literal((Component.translatable(key).getString()).replaceAll("§.", ""));
}
public static OptionPage animation() {
List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.animation").isEnabled())
.setName(parseVanillaString("gui.socialInteractions.tab_all"))
.setTooltip(Component.translatable("sodium-extra.option.animations_all.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.animationSettings.animation = value, opts -> opts.animationSettings.animation)
.setFlags(OptionFlag.REQUIRES_ASSET_RELOAD)
.build()
)
.build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.animation").isEnabled())
.setName(parseVanillaString("block.minecraft.water"))
.setTooltip(Component.translatable("sodium-extra.option.animate_water.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.animationSettings.water = value, opts -> opts.animationSettings.water)
.setFlags(OptionFlag.REQUIRES_ASSET_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.animation").isEnabled())
.setName(parseVanillaString("block.minecraft.lava"))
.setTooltip(Component.translatable("sodium-extra.option.animate_lava.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.animationSettings.lava = value, opts -> opts.animationSettings.lava)
.setFlags(OptionFlag.REQUIRES_ASSET_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.animation").isEnabled())
.setName(parseVanillaString("block.minecraft.fire"))
.setTooltip(Component.translatable("sodium-extra.option.animate_fire.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.animationSettings.fire = value, opts -> opts.animationSettings.fire)
.setFlags(OptionFlag.REQUIRES_ASSET_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.animation").isEnabled())
.setName(parseVanillaString("block.minecraft.nether_portal"))
.setTooltip(Component.translatable("sodium-extra.option.animate_portal.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.animationSettings.portal = value, opts -> opts.animationSettings.portal)
.setFlags(OptionFlag.REQUIRES_ASSET_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.animation").isEnabled())
.setName(Component.translatable("sodium-extra.option.block_animations"))
.setTooltip(Component.translatable("sodium-extra.option.block_animations.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.animationSettings.blockAnimations = value, options -> options.animationSettings.blockAnimations)
.setFlags(OptionFlag.REQUIRES_ASSET_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.animation").isEnabled())
.setName(parseVanillaString("block.minecraft.sculk_sensor"))
.setTooltip(Component.translatable("sodium-extra.option.animate_sculk_sensor.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.animationSettings.sculkSensor = value, options -> options.animationSettings.sculkSensor)
.setFlags(OptionFlag.REQUIRES_ASSET_RELOAD)
.build()
)
.build());
return new OptionPage(Component.translatable("sodium-extra.option.animations"), ImmutableList.copyOf(groups));
}
public static OptionPage particle() {
List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.particle").isEnabled())
.setName(parseVanillaString("gui.socialInteractions.tab_all"))
.setTooltip(Component.translatable("sodium-extra.option.particles_all.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.particleSettings.particles = value, opts -> opts.particleSettings.particles)
.build()
)
.build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.particle").isEnabled())
.setName(parseVanillaString("subtitles.entity.generic.splash"))
.setTooltip(Component.translatable("sodium-extra.option.rain_splash.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.particleSettings.rainSplash = value, opts -> opts.particleSettings.rainSplash)
.build()
)
// todo:
/*.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.particle").isEnabled())
.setName(parseVanillaString("subtitles.block.generic.break"))
.setTooltip(Component.translatable("sodium-extra.option.block_break.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.particleSettings.blockBreak = value, opts -> opts.particleSettings.blockBreak)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.particle").isEnabled())
.setName(parseVanillaString("subtitles.block.generic.hit"))
.setTooltip(Component.translatable("sodium-extra.option.block_breaking.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.particleSettings.blockBreaking = value, opts -> opts.particleSettings.blockBreaking)
.build()
)*/
.build());
Map<String, List<ResourceLocation>> otherParticles = BuiltInRegistries.PARTICLE_TYPE.keySet().stream()
.collect(Collectors.groupingBy(ResourceLocation::getNamespace));
otherParticles.forEach((namespace, identifiers) -> groups.add(identifiers.stream()
.map(identifier -> OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.particle").isEnabled())
.setName(translatableName(identifier, "particles"))
.setTooltip(translatableTooltip(identifier, "particles"))
.setControl(TickBoxControl::new)
.setBinding((opts, val) -> opts.particleSettings.otherMap.put(identifier, val),
opts -> opts.particleSettings.otherMap.computeIfAbsent(identifier, k -> true))
.build())
.sorted(Comparator.comparing(o -> o.getName().getString()))
.collect(
OptionGroup::createBuilder,
OptionGroup.Builder::add,
(b1, b2) -> {
}
).build()
));
return new OptionPage(parseVanillaString("options.particles"), ImmutableList.copyOf(groups));
}
public static OptionPage detail() {
List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.sky").isEnabled())
.setName(Component.translatable("sodium-extra.option.sky"))
.setTooltip(Component.translatable("sodium-extra.option.sky.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.detailSettings.sky = value, opts -> opts.detailSettings.sky)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.stars").isEnabled())
.setName(Component.translatable("sodium-extra.option.stars"))
.setTooltip(Component.translatable("sodium-extra.option.stars.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.detailSettings.stars = value, opts -> opts.detailSettings.stars)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.sun_moon").isEnabled())
.setName(Component.translatable("sodium-extra.option.sun"))
.setTooltip(Component.translatable("sodium-extra.option.sun.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.detailSettings.sun = value, opts -> opts.detailSettings.sun)
.build()
).add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.sun_moon").isEnabled())
.setName(Component.translatable("sodium-extra.option.moon"))
.setTooltip(Component.translatable("sodium-extra.option.moon.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.detailSettings.moon = value, opts -> opts.detailSettings.moon)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.particle").isEnabled())
.setName(parseVanillaString("soundCategory.weather"))
.setTooltip(Component.translatable("sodium-extra.option.rain_snow.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.detailSettings.rainSnow = value, opts -> opts.detailSettings.rainSnow)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.biome_colors").isEnabled())
.setName(Component.translatable("sodium-extra.option.biome_colors"))
.setTooltip(Component.translatable("sodium-extra.option.biome_colors.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.detailSettings.biomeColors = value, options -> options.detailSettings.biomeColors)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.sky_colors").isEnabled())
.setName(Component.translatable("sodium-extra.option.sky_colors"))
.setTooltip(Component.translatable("sodium-extra.option.sky_colors.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.detailSettings.skyColors = value, options -> options.detailSettings.skyColors)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.build());
return new OptionPage(Component.translatable("sodium-extra.option.details"), ImmutableList.copyOf(groups));
}
public static OptionPage render() {
List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.fog").isEnabled())
.setName(Component.translatable("sodium-extra.option.global_fog"))
.setTooltip(Component.translatable("sodium-extra.option.global_fog.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.renderSettings.globalFog = value, options -> options.renderSettings.globalFog)
.build()
)
.build());
Arrays.stream(FogType.values())
.sorted(Comparator.comparing(Enum::name))
.filter(type -> type != FogType.NONE)
.forEach(fogType -> {
// Setup cross-references
AtomicReference<OptionImpl<SodiumExtraGameOptions, Integer>> environmentStartRef = new AtomicReference<>();
AtomicReference<OptionImpl<SodiumExtraGameOptions, Integer>> environmentEndRef = new AtomicReference<>();
AtomicReference<OptionImpl<SodiumExtraGameOptions, Integer>> renderDistanceStartRef = new AtomicReference<>();
AtomicReference<OptionImpl<SodiumExtraGameOptions, Integer>> renderDistanceEndRef = new AtomicReference<>();
// Environment Start
OptionImpl<SodiumExtraGameOptions, Integer> envStart = OptionImpl.createBuilder(int.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.fog").isEnabled())
.setName(Component.translatable("sodium-extra.option.fog_type.environment_start", fogTypeName(fogType)))
.setTooltip(Component.translatable("sodium-extra.option.fog_type.environment_start.tooltip"))
.setControl(option -> new SliderControlExtended(option, 0, 300, 1, ControlValueFormatter.percentage(), false))
.setBinding(
(opts, val) -> {
FogTypeConfig config = opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig());
config.environmentStartMultiplier = val;
// Enforce: end >= start
if (config.environmentEndMultiplier < val) {
config.environmentEndMultiplier = val;
if (environmentEndRef.get() != null) {
environmentEndRef.get().setValue(val);
environmentEndRef.get().applyChanges();
}
}
},
opts -> opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig()).environmentStartMultiplier
)
.build();
environmentStartRef.set(envStart);
// Environment End
OptionImpl<SodiumExtraGameOptions, Integer> envEnd = OptionImpl.createBuilder(int.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.fog").isEnabled())
.setName(Component.translatable("sodium-extra.option.fog_type.environment_end", fogTypeName(fogType)))
.setTooltip(Component.translatable("sodium-extra.option.fog_type.environment_end.tooltip"))
.setControl(option -> new SliderControlExtended(option, 0, 300, 1, ControlValueFormatter.percentage(), false))
.setBinding(
(opts, val) -> {
FogTypeConfig config = opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig());
config.environmentEndMultiplier = val;
if (config.environmentStartMultiplier > val) {
config.environmentStartMultiplier = val;
if (environmentStartRef.get() != null) {
environmentStartRef.get().setValue(val);
environmentStartRef.get().applyChanges();
}
}
},
opts -> opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig()).environmentEndMultiplier
)
.build();
environmentEndRef.set(envEnd);
// Render Start
OptionImpl<SodiumExtraGameOptions, Integer> renderStart = OptionImpl.createBuilder(int.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.fog").isEnabled())
.setName(Component.translatable("sodium-extra.option.fog_type.render_distance_start", fogTypeName(fogType)))
.setTooltip(Component.translatable("sodium-extra.option.fog_type.render_distance_start.tooltip"))
.setControl(option -> new SliderControlExtended(option, 0, 300, 1, ControlValueFormatter.percentage(), false))
.setBinding(
(opts, val) -> {
FogTypeConfig config = opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig());
config.renderDistanceStartMultiplier = val;
// Enforce: end >= start
if (config.renderDistanceEndMultiplier < val) {
config.renderDistanceEndMultiplier = val;
if (renderDistanceEndRef.get() != null) {
renderDistanceEndRef.get().setValue(val);
renderDistanceEndRef.get().applyChanges();
}
}
},
opts -> opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig()).renderDistanceStartMultiplier
)
.build();
renderDistanceStartRef.set(renderStart);
// Render End
OptionImpl<SodiumExtraGameOptions, Integer> renderEnd = OptionImpl.createBuilder(int.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.fog").isEnabled())
.setName(Component.translatable("sodium-extra.option.fog_type.render_distance_end", fogTypeName(fogType)))
.setTooltip(Component.translatable("sodium-extra.option.fog_type.render_distance_end.tooltip"))
.setControl(option -> new SliderControlExtended(option, 0, 300, 1, ControlValueFormatter.percentage(), false))
.setBinding(
(opts, val) -> {
FogTypeConfig config = opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig());
config.renderDistanceEndMultiplier = val;
if (config.renderDistanceStartMultiplier > val) {
config.renderDistanceStartMultiplier = val;
if (renderDistanceStartRef.get() != null) {
renderDistanceStartRef.get().setValue(val);
renderDistanceStartRef.get().applyChanges();
}
}
},
opts -> opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig()).renderDistanceEndMultiplier
)
.build();
renderDistanceEndRef.set(renderEnd);
OptionImpl<SodiumExtraGameOptions, Integer> skyEnd = OptionImpl.createBuilder(int.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.fog").isEnabled())
.setName(Component.translatable("sodium-extra.option.fog_type.sky_end", fogTypeName(fogType)))
.setTooltip(Component.translatable("sodium-extra.option.fog_type.sky_end.tooltip"))
.setControl(option -> new SliderControlExtended(option, 0, 300, 1, ControlValueFormatter.percentage(), false))
.setBinding(
(opts, val) -> opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig()).skyEndMultiplier = val,
opts -> opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig()).skyEndMultiplier
)
.build();
OptionImpl<SodiumExtraGameOptions, Integer> cloudEnd = OptionImpl.createBuilder(int.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.fog").isEnabled())
.setName(Component.translatable("sodium-extra.option.fog_type.cloud_end", fogTypeName(fogType)))
.setTooltip(Component.translatable("sodium-extra.option.fog_type.cloud_end.tooltip"))
.setControl(option -> new SliderControlExtended(option, 0, 300, 1, ControlValueFormatter.percentage(), false))
.setBinding(
(opts, val) -> opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig()).cloudEndMultiplier = val,
opts -> opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig()).cloudEndMultiplier
)
.build();
// Add group
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.fog").isEnabled())
.setName(fogTypeName(fogType))
.setTooltip(fogTypeTooltip(fogType))
.setControl(TickBoxControl::new)
.setBinding(
(opts, val) -> opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig()).enable = val,
opts -> opts.renderSettings.fogTypeConfig.computeIfAbsent(fogType, k -> new FogTypeConfig()).enable
)
.build())
.add(envStart)
.add(envEnd)
.add(renderStart)
.add(renderEnd)
.add(skyEnd)
.add(cloudEnd)
.build());
});
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.light_updates").isEnabled())
.setName(Component.translatable("sodium-extra.option.light_updates"))
.setTooltip(Component.translatable("sodium-extra.option.light_updates.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.renderSettings.lightUpdates = value, options -> options.renderSettings.lightUpdates)
.build()
)
.build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.render.entity").isEnabled())
.setName(parseVanillaString("entity.minecraft.item_frame"))
.setTooltip(Component.translatable("sodium-extra.option.item_frames.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.renderSettings.itemFrame = value, opts -> opts.renderSettings.itemFrame)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.render.entity").isEnabled())
.setName(parseVanillaString("entity.minecraft.armor_stand"))
.setTooltip(Component.translatable("sodium-extra.option.armor_stands.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.renderSettings.armorStand = value, options -> options.renderSettings.armorStand)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.render.entity").isEnabled())
.setName(parseVanillaString("entity.minecraft.painting"))
.setTooltip(Component.translatable("sodium-extra.option.paintings.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.renderSettings.painting = value, options -> options.renderSettings.painting)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.render.block.entity").isEnabled())
.setName(Component.translatable("sodium-extra.option.beacon_beam"))
.setTooltip(Component.translatable("sodium-extra.option.beacon_beam.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.renderSettings.beaconBeam = value, opts -> opts.renderSettings.beaconBeam)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.render.block.entity").isEnabled())
.setName(Component.translatable("sodium-extra.option.limit_beacon_beam_height"))
.setTooltip(Component.translatable("sodium-extra.option.limit_beacon_beam_height.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.renderSettings.limitBeaconBeamHeight = value, opts -> opts.renderSettings.limitBeaconBeamHeight)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.render.block.entity").isEnabled())
.setName(Component.translatable("sodium-extra.option.enchanting_table_book"))
.setTooltip(Component.translatable("sodium-extra.option.enchanting_table_book.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.renderSettings.enchantingTableBook = value, opts -> opts.renderSettings.enchantingTableBook)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.render.block.entity").isEnabled())
.setName(parseVanillaString("block.minecraft.piston"))
.setTooltip(Component.translatable("sodium-extra.option.piston.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.renderSettings.piston = value, options -> options.renderSettings.piston)
.build()
)
.build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.render.entity").isEnabled())
.setName(Component.translatable("sodium-extra.option.item_frame_name_tag"))
.setTooltip(Component.translatable("sodium-extra.option.item_frame_name_tag.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.renderSettings.itemFrameNameTag = value, opts -> opts.renderSettings.itemFrameNameTag)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.render.entity").isEnabled())
.setName(Component.translatable("sodium-extra.option.player_name_tag"))
.setTooltip(Component.translatable("sodium-extra.option.player_name_tag.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.renderSettings.playerNameTag = value, options -> options.renderSettings.playerNameTag)
.build()
)
.build());
return new OptionPage(Component.translatable("sodium-extra.option.render"), ImmutableList.copyOf(groups));
}
public static OptionPage extra() {
List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.reduce_resolution_on_mac").isEnabled() && System.getProperty("os.name").toLowerCase().contains("mac"))
.setName(Component.translatable("sodium-extra.option.reduce_resolution_on_mac"))
.setTooltip(Component.translatable("sodium-extra.option.reduce_resolution_on_mac.tooltip"))
.setEnabled(() -> System.getProperty("os.name").toLowerCase().contains("mac"))
.setImpact(OptionImpact.HIGH)
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.extraSettings.reduceResolutionOnMac = value, opts -> opts.extraSettings.reduceResolutionOnMac)
.build()
).build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(SodiumExtraGameOptions.OverlayCorner.class, sodiumExtraOpts)
.setName(Component.translatable("sodium-extra.option.overlay_corner"))
.setTooltip(Component.translatable("sodium-extra.option.overlay_corner.tooltip"))
.setControl(option -> new CyclingControl<>(option, SodiumExtraGameOptions.OverlayCorner.class))
.setBinding((opts, value) -> opts.extraSettings.overlayCorner = value, opts -> opts.extraSettings.overlayCorner)
.build()
)
.add(OptionImpl.createBuilder(SodiumExtraGameOptions.TextContrast.class, sodiumExtraOpts)
.setName(Component.translatable("sodium-extra.option.text_contrast"))
.setTooltip(Component.translatable("sodium-extra.option.text_contrast.tooltip"))
.setControl(option -> new CyclingControl<>(option, SodiumExtraGameOptions.TextContrast.class))
.setBinding((opts, value) -> opts.extraSettings.textContrast = value, opts -> opts.extraSettings.textContrast)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setName(Component.translatable("sodium-extra.option.show_fps"))
.setTooltip(Component.translatable("sodium-extra.option.show_fps.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.extraSettings.showFps = value, opts -> opts.extraSettings.showFps)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setName(Component.translatable("sodium-extra.option.show_fps_extended"))
.setTooltip(Component.translatable("sodium-extra.option.show_fps_extended.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.extraSettings.showFPSExtended = value, opts -> opts.extraSettings.showFPSExtended)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setName(Component.translatable("sodium-extra.option.show_coordinates"))
.setTooltip(Component.translatable("sodium-extra.option.show_coordinates.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.extraSettings.showCoords = value, opts -> opts.extraSettings.showCoords)
.build()
)
.add(OptionImpl.createBuilder(int.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.cloud").isEnabled())
.setName(Component.translatable("sodium-extra.option.cloud_height"))
.setTooltip(Component.translatable("sodium-extra.option.cloud_height.tooltip"))
.setControl(option -> new SliderControl(option, -64, 319, 1, ControlValueFormatter.number()))
.setBinding((options, value) -> options.extraSettings.cloudHeight = value, options -> options.extraSettings.cloudHeight)
.build()
)
.build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, vanillaOpts)
.setName(Component.translatable("sodium-extra.option.advanced_item_tooltips"))
.setTooltip(Component.translatable("sodium-extra.option.advanced_item_tooltips.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.advancedItemTooltips = value, opts -> opts.advancedItemTooltips)
.build()
)
.build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.toasts").isEnabled())
.setName(Component.translatable("sodium-extra.option.toasts"))
.setTooltip(Component.translatable("sodium-extra.option.toasts.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.extraSettings.toasts = value, options -> options.extraSettings.toasts)
.build())
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.toasts").isEnabled())
.setName(Component.translatable("sodium-extra.option.advancement_toast"))
.setTooltip(Component.translatable("sodium-extra.option.advancement_toast.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.extraSettings.advancementToast = value, options -> options.extraSettings.advancementToast)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.toasts").isEnabled())
.setName(Component.translatable("sodium-extra.option.recipe_toast"))
.setTooltip(Component.translatable("sodium-extra.option.recipe_toast.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.extraSettings.recipeToast = value, options -> options.extraSettings.recipeToast)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.toasts").isEnabled())
.setName(Component.translatable("sodium-extra.option.system_toast"))
.setTooltip(Component.translatable("sodium-extra.option.system_toast.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.extraSettings.systemToast = value, options -> options.extraSettings.systemToast)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.toasts").isEnabled())
.setName(Component.translatable("sodium-extra.option.tutorial_toast"))
.setTooltip(Component.translatable("sodium-extra.option.tutorial_toast.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.extraSettings.tutorialToast = value, options -> options.extraSettings.tutorialToast)
.build()
)
.build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.instant_sneak").isEnabled())
.setName(Component.translatable("sodium-extra.option.instant_sneak"))
.setTooltip(Component.translatable("sodium-extra.option.instant_sneak.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.extraSettings.instantSneak = value, options -> options.extraSettings.instantSneak)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.prevent_shaders").isEnabled())
.setName(Component.translatable("sodium-extra.option.prevent_shaders"))
.setTooltip(Component.translatable("sodium-extra.option.prevent_shaders.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.extraSettings.preventShaders = value, options -> options.extraSettings.preventShaders)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.steady_debug_hud").isEnabled())
.setName(Component.translatable("sodium-extra.option.steady_debug_hud"))
.setTooltip(Component.translatable("sodium-extra.option.steady_debug_hud.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((options, value) -> options.extraSettings.steadyDebugHud = value, options -> options.extraSettings.steadyDebugHud)
.build()
)
.add(OptionImpl.createBuilder(int.class, sodiumExtraOpts)
.setEnabled(() -> SodiumExtraClientMod.mixinConfig().getOptions().get("mixin.steady_debug_hud").isEnabled())
.setName(Component.translatable("sodium-extra.option.steady_debug_hud_refresh_interval"))
.setTooltip(Component.translatable("sodium-extra.option.steady_debug_hud_refresh_interval.tooltip"))
.setControl(option -> new SliderControlExtended(option, 1, 20, 1, ControlValueFormatterExtended.ticks(), false))
.setBinding((options, value) -> options.extraSettings.steadyDebugHudRefreshInterval = value, options -> options.extraSettings.steadyDebugHudRefreshInterval)
.build()
)
.build());
return new OptionPage(Component.translatable("sodium-extra.option.extras"), ImmutableList.copyOf(groups));
}
private static Component fogTypeName(FogType type) {
String key = "sodium-extra.option.fog_type." + type.name().toLowerCase();
Component translated = Component.translatable(key);
// Fallback: pretty print from enum name (e.g., DIMENSION_OR_BOSS → "Dimension Or Boss Fog")
if (!ComponentUtils.isTranslationResolvable(translated)) {
String pretty = Arrays.stream(type.name().split("_"))
.map(s -> s.charAt(0) + s.substring(1).toLowerCase())
.collect(Collectors.joining(" ")) + " Fog";
return Component.literal(pretty);
}
return translated;
}
private static Component fogTypeTooltip(FogType type) {
String key = "sodium-extra.option.fog_type." + type.name().toLowerCase() + ".tooltip";
Component translated = Component.translatable(key);
if (!ComponentUtils.isTranslationResolvable(translated)) {
return Component.translatable("sodium-extra.option.fog_type.default.tooltip", fogTypeName(type));
}
return translated;
}
private static Component translatableName(ResourceLocation identifier, String category) {
String key = identifier.toLanguageKey("options.".concat(category));
Component translatable = Component.translatable(key);
if (!ComponentUtils.isTranslationResolvable(translatable)) {
translatable = Component.literal(
Arrays.stream(key.substring(key.lastIndexOf('.') + 1).split("_"))
.map(s -> s.substring(0, 1).toUpperCase() + s.substring(1))
.collect(Collectors.joining(" "))
);
}
return translatable;
}
private static Component translatableTooltip(ResourceLocation identifier, String category) {
String key = identifier.toLanguageKey("options.".concat(category)).concat(".tooltip");
Component translatable = Component.translatable(key);
if (!ComponentUtils.isTranslationResolvable(translatable)) {
translatable = Component.translatable(
"sodium-extra.option.".concat(category).concat(".tooltips"),
translatableName(identifier, category)
);
}
return translatable;
}
}
| 412 | 0.907446 | 1 | 0.907446 | game-dev | MEDIA | 0.979227 | game-dev | 0.95514 | 1 | 0.95514 |
Fedoraware/Fedoraware | 33,508 | Fedoraware/Fedoraware-TF2/src/SDK/Includes/Const.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#ifndef CONST_H
#define CONST_H
#ifdef _WIN32
#pragma once
#endif
// the command line param that tells the engine to use steam
#define STEAM_PARM "-steam"
// the command line param to tell dedicated server to restart
// if they are out of date
#define AUTO_RESTART "-autoupdate"
// the message a server sends when a clients steam login is expired
#define INVALID_STEAM_TICKET "Invalid STEAM UserID Ticket\n"
#define INVALID_STEAM_LOGON "No Steam logon\n"
#define INVALID_STEAM_VACBANSTATE "VAC banned from secure server\n"
#define INVALID_STEAM_LOGGED_IN_ELSEWHERE "This Steam account is being used in another location\n"
// This is the default, see shareddefs.h for mod-specific value, which can override this
#define DEFAULT_TICK_INTERVAL (0.015) // 15 msec is the default
#define MINIMUM_TICK_INTERVAL (0.001)
#define MAXIMUM_TICK_INTERVAL (0.1)
// This is the max # of players the engine can handle
#define ABSOLUTE_PLAYER_LIMIT 255 // not 256, so we can send the limit as a byte
#define ABSOLUTE_PLAYER_LIMIT_DW ( (ABSOLUTE_PLAYER_LIMIT/32) + 1 )
// a player name may have 31 chars + 0 on the PC.
// the 360 only allows 15 char + 0, but stick with the larger PC size for cross-platform communication
#define MAX_PLAYER_NAME_LENGTH 32
#ifdef _X360
#define MAX_PLAYERS_PER_CLIENT XUSER_MAX_COUNT // Xbox 360 supports 4 players per console
#else
#define MAX_PLAYERS_PER_CLIENT 1 // One player per PC
#endif
#define MAX_MAP_NAME 32
#define MAX_NETWORKID_LENGTH 64 // num chars for a network (i.e steam) ID
// BUGBUG: Reconcile with or derive this from the engine's internal definition!
// FIXME: I added an extra bit because I needed to make it signed
#define SP_MODEL_INDEX_BITS 11
// How many bits to use to encode an edict.
#define MAX_EDICT_BITS 11 // # of bits needed to represent max edicts
// Max # of edicts in a level
#define MAX_EDICTS (1<<MAX_EDICT_BITS)
// How many bits to use to encode an server class index
#define MAX_SERVER_CLASS_BITS 9
// Max # of networkable server classes
#define MAX_SERVER_CLASSES (1<<MAX_SERVER_CLASS_BITS)
#define SIGNED_GUID_LEN 32 // Hashed CD Key (32 hex alphabetic chars + 0 terminator )
// Used for networking ehandles.
#define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
#define NUM_ENT_ENTRIES (1 << NUM_ENT_ENTRY_BITS)
#define ENT_ENTRY_MASK (NUM_ENT_ENTRIES - 1)
#define INVALID_EHANDLE_INDEX 0xFFFFFFFF
#define NUM_SERIAL_NUM_BITS (32 - NUM_ENT_ENTRY_BITS)
// Networked ehandles use less bits to encode the serial number.
#define NUM_NETWORKED_EHANDLE_SERIAL_NUMBER_BITS 10
#define NUM_NETWORKED_EHANDLE_BITS (MAX_EDICT_BITS + NUM_NETWORKED_EHANDLE_SERIAL_NUMBER_BITS)
#define INVALID_NETWORKED_EHANDLE_VALUE ((1 << NUM_NETWORKED_EHANDLE_BITS) - 1)
// This is the maximum amount of data a PackedEntity can have. Having a limit allows us
// to use static arrays sometimes instead of allocating memory all over the place.
#define MAX_PACKEDENTITY_DATA (16384)
// This is the maximum number of properties that can be delta'd. Must be evenly divisible by 8.
#define MAX_PACKEDENTITY_PROPS (4096)
// a client can have up to 4 customization files (logo, sounds, models, txt).
#define MAX_CUSTOM_FILES 4 // max 4 files
#define MAX_CUSTOM_FILE_SIZE 131072
//
// Constants shared by the engine and dlls
// This header file included by engine files and DLL files.
// Most came from server.h
// CBaseEntity::m_fFlags
// PLAYER SPECIFIC FLAGS FIRST BECAUSE WE USE ONLY A FEW BITS OF NETWORK PRECISION
#define FL_ONGROUND (1<<0) // At rest / on the ground
#define FL_DUCKING (1<<1) // Player flag -- Player is fully crouched
#define FL_WATERJUMP (1<<2) // player jumping out of water
#define FL_ONTRAIN (1<<3) // Player is _controlling_ a train, so movement commands should be ignored on client during prediction.
#define FL_INRAIN (1<<4) // Indicates the entity is standing in rain
#define FL_FROZEN (1<<5) // Player is frozen for 3rd person camera
#define FL_ATCONTROLS (1<<6) // Player can't move, but keeps key inputs for controlling another entity
#define FL_CLIENT (1<<7) // Is a player
#define FL_FAKECLIENT (1<<8) // Fake client, simulated server side; don't send network messages to them
// NOTE if you move things up, make sure to change this value
#define PLAYER_FLAG_BITS 9
// NON-PLAYER SPECIFIC (i.e., not used by GameMovement or the client .dll ) -- Can still be applied to players, though
#define FL_INWATER (1<<9) // In water
#define FL_FLY (1<<10) // Changes the SV_Movestep() behavior to not need to be on ground
#define FL_SWIM (1<<11) // Changes the SV_Movestep() behavior to not need to be on ground (but stay in water)
#define FL_CONVEYOR (1<<12)
#define FL_NPC (1<<13)
#define FL_GODMODE (1<<14)
#define FL_NOTARGET (1<<15)
#define FL_AIMTARGET (1<<16) // set if the crosshair needs to aim onto the entity
#define FL_PARTIALGROUND (1<<17) // not all corners are valid
#define FL_STATICPROP (1<<18) // Eetsa static prop!
#define FL_GRAPHED (1<<19) // worldgraph has this ent listed as something that blocks a connection
#define FL_GRENADE (1<<20)
#define FL_STEPMOVEMENT (1<<21) // Changes the SV_Movestep() behavior to not do any processing
#define FL_DONTTOUCH (1<<22) // Doesn't generate touch functions, generates Untouch() for anything it was touching when this flag was set
#define FL_BASEVELOCITY (1<<23) // Base velocity has been applied this frame (used to convert base velocity into momentum)
#define FL_WORLDBRUSH (1<<24) // Not moveable/removeable brush entity (really part of the world, but represented as an entity for transparency or something)
#define FL_OBJECT (1<<25) // Terrible name. This is an object that NPCs should see. Missiles, for example.
#define FL_KILLME (1<<26) // This entity is marked for death -- will be freed by game DLL
#define FL_ONFIRE (1<<27) // You know...
#define FL_DISSOLVING (1<<28) // We're dissolving!
#define FL_TRANSRAGDOLL (1<<29) // In the process of turning into a client side ragdoll.
#define FL_UNBLOCKABLE_BY_PLAYER (1<<30) // pusher that can't be blocked by the player
// edict->movetype values
enum MoveType_t
{
MOVETYPE_NONE = 0, // never moves
MOVETYPE_ISOMETRIC, // For players -- in TF2 commander view, etc.
MOVETYPE_WALK, // Player only - moving on the ground
MOVETYPE_STEP, // gravity, special edge handling -- monsters use this
MOVETYPE_FLY, // No gravity, but still collides with stuff
MOVETYPE_FLYGRAVITY, // flies through the air + is affected by gravity
MOVETYPE_VPHYSICS, // uses VPHYSICS for simulation
MOVETYPE_PUSH, // no clip to world, push and crush
MOVETYPE_NOCLIP, // No gravity, no collisions, still do velocity/avelocity
MOVETYPE_LADDER, // Used by players only when going onto a ladder
MOVETYPE_OBSERVER, // Observer movement, depends on player's observer mode
MOVETYPE_CUSTOM, // Allows the entity to describe its own physics
// should always be defined as the last item in the list
MOVETYPE_LAST = MOVETYPE_CUSTOM,
MOVETYPE_MAX_BITS = 4
};
// edict->movecollide values
enum MoveCollide_t
{
MOVECOLLIDE_DEFAULT = 0,
// These ones only work for MOVETYPE_FLY + MOVETYPE_FLYGRAVITY
MOVECOLLIDE_FLY_BOUNCE, // bounces, reflects, based on elasticity of surface and object - applies friction (adjust velocity)
MOVECOLLIDE_FLY_CUSTOM, // Touch() will modify the velocity however it likes
MOVECOLLIDE_FLY_SLIDE, // slides along surfaces (no bounce) - applies friciton (adjusts velocity)
MOVECOLLIDE_COUNT, // Number of different movecollides
// When adding new movecollide types, make sure this is correct
MOVECOLLIDE_MAX_BITS = 3
};
// edict->solid values
// NOTE: Some movetypes will cause collisions independent of SOLID_NOT/SOLID_TRIGGER when the entity moves
// SOLID only effects OTHER entities colliding with this one when they move - UGH!
// Solid type basically describes how the bounding volume of the object is represented
// NOTE: SOLID_BBOX MUST BE 2, and SOLID_VPHYSICS MUST BE 6
// NOTE: These numerical values are used in the FGD by the prop code (see prop_dynamic)
enum SolidType_t
{
SOLID_NONE = 0, // no solid model
SOLID_BSP = 1, // a BSP tree
SOLID_BBOX = 2, // an AABB
SOLID_OBB = 3, // an OBB (not implemented yet)
SOLID_OBB_YAW = 4, // an OBB, constrained so that it can only yaw
SOLID_CUSTOM = 5, // Always call into the entity for tests
SOLID_VPHYSICS = 6, // solid vphysics object, get vcollide from the model and collide with that
SOLID_LAST,
};
enum SolidFlags_t
{
FSOLID_CUSTOMRAYTEST = 0x0001, // Ignore solid type + always call into the entity for ray tests
FSOLID_CUSTOMBOXTEST = 0x0002, // Ignore solid type + always call into the entity for swept box tests
FSOLID_NOT_SOLID = 0x0004, // Are we currently not solid?
FSOLID_TRIGGER = 0x0008, // This is something may be collideable but fires touch functions
// even when it's not collideable (when the FSOLID_NOT_SOLID flag is set)
FSOLID_NOT_STANDABLE = 0x0010, // You can't stand on this
FSOLID_VOLUME_CONTENTS = 0x0020, // Contains volumetric contents (like water)
FSOLID_FORCE_WORLD_ALIGNED = 0x0040, // Forces the collision rep to be world-aligned even if it's SOLID_BSP or SOLID_VPHYSICS
FSOLID_USE_TRIGGER_BOUNDS = 0x0080, // Uses a special trigger bounds separate from the normal OBB
FSOLID_ROOT_PARENT_ALIGNED = 0x0100, // Collisions are defined in root parent's local coordinate space
FSOLID_TRIGGER_TOUCH_DEBRIS = 0x0200, // This trigger will touch debris objects
FSOLID_MAX_BITS = 10
};
//-----------------------------------------------------------------------------
// A couple of inline helper methods
//-----------------------------------------------------------------------------
#pragma warning (disable : 26812) //unscoped enum
inline bool IsSolid(SolidType_t solidType, int nSolidFlags)
{
return (solidType != SOLID_NONE) && ((nSolidFlags & FSOLID_NOT_SOLID) == 0);
}
// m_lifeState values
#define LIFE_ALIVE 0 // alive
#define LIFE_DYING 1 // playing death animation or still falling off of a ledge waiting to hit ground
#define LIFE_DEAD 2 // dead. lying still.
#define LIFE_RESPAWNABLE 3
#define LIFE_DISCARDBODY 4
// entity effects
enum
{
EF_BONEMERGE = 0x001, // Performs bone merge on client side
EF_BRIGHTLIGHT = 0x002, // DLIGHT centered at entity origin
EF_DIMLIGHT = 0x004, // player flashlight
EF_NOINTERP = 0x008, // don't interpolate the next frame
EF_NOSHADOW = 0x010, // Don't cast no shadow
EF_NODRAW = 0x020, // don't draw entity
EF_NORECEIVESHADOW = 0x040, // Don't receive no shadow
EF_BONEMERGE_FASTCULL = 0x080, // For use with EF_BONEMERGE. If this is set, then it places this ent's origin at its
// parent and uses the parent's bbox + the max extents of the aiment.
// Otherwise, it sets up the parent's bones every frame to figure out where to place
// the aiment, which is inefficient because it'll setup the parent's bones even if
// the parent is not in the PVS.
EF_ITEM_BLINK = 0x100, // blink an item so that the user notices it.
EF_PARENT_ANIMATES = 0x200, // always assume that the parent entity is animating
EF_MAX_BITS = 10
};
#define EF_PARITY_BITS 3
#define EF_PARITY_MASK ((1<<EF_PARITY_BITS)-1)
// How many bits does the muzzle flash parity thing get?
#define EF_MUZZLEFLASH_BITS 2
// plats
#define PLAT_LOW_TRIGGER 1
// Trains
#define SF_TRAIN_WAIT_RETRIGGER 1
#define SF_TRAIN_PASSABLE 8 // Train is not solid -- used to make water trains
// view angle update types for CPlayerState::fixangle
#define FIXANGLE_NONE 0
#define FIXANGLE_ABSOLUTE 1
#define FIXANGLE_RELATIVE 2
// Break Model Defines
#define BREAK_GLASS 0x01
#define BREAK_METAL 0x02
#define BREAK_FLESH 0x04
#define BREAK_WOOD 0x08
#define BREAK_SMOKE 0x10
#define BREAK_TRANS 0x20
#define BREAK_CONCRETE 0x40
// If this is set, then we share a lighting origin with the last non-slave breakable sent down to the client
#define BREAK_SLAVE 0x80
// Colliding temp entity sounds
#define BOUNCE_GLASS BREAK_GLASS
#define BOUNCE_METAL BREAK_METAL
#define BOUNCE_FLESH BREAK_FLESH
#define BOUNCE_WOOD BREAK_WOOD
#define BOUNCE_SHRAP 0x10
#define BOUNCE_SHELL 0x20
#define BOUNCE_CONCRETE BREAK_CONCRETE
#define BOUNCE_SHOTSHELL 0x80
// Temp entity bounce sound types
#define TE_BOUNCE_NULL 0
#define TE_BOUNCE_SHELL 1
#define TE_BOUNCE_SHOTSHELL 2
// Rendering constants
// if this is changed, update common/MaterialSystem/Sprite.cpp
enum RenderMode_t
{
kRenderNormal, // src
kRenderTransColor, // c*a+dest*(1-a)
kRenderTransTexture, // src*a+dest*(1-a)
kRenderGlow, // src*a+dest -- No Z buffer checks -- Fixed size in screen space
kRenderTransAlpha, // src*srca+dest*(1-srca)
kRenderTransAdd, // src*a+dest
kRenderEnvironmental, // not drawn, used for environmental effects
kRenderTransAddFrameBlend, // use a fractional frame value to blend between animation frames
kRenderTransAlphaAdd, // src + dest*(1-a)
kRenderWorldGlow, // Same as kRenderGlow but not fixed size in screen space
kRenderNone, // Don't render.
};
enum RenderFx_t
{
kRenderFxNone = 0,
kRenderFxPulseSlow,
kRenderFxPulseFast,
kRenderFxPulseSlowWide,
kRenderFxPulseFastWide,
kRenderFxFadeSlow,
kRenderFxFadeFast,
kRenderFxSolidSlow,
kRenderFxSolidFast,
kRenderFxStrobeSlow,
kRenderFxStrobeFast,
kRenderFxStrobeFaster,
kRenderFxFlickerSlow,
kRenderFxFlickerFast,
kRenderFxNoDissipation,
kRenderFxDistort, // Distort/scale/translate flicker
kRenderFxHologram, // kRenderFxDistort + distance fade
kRenderFxExplode, // Scale up really big!
kRenderFxGlowShell, // Glowing Shell
kRenderFxClampMinScale, // Keep this sprite from getting very small (SPRITES only!)
kRenderFxEnvRain, // for environmental rendermode, make rain
kRenderFxEnvSnow, // " " " , make snow
kRenderFxSpotlight, // TEST CODE for experimental spotlight
kRenderFxRagdoll, // HACKHACK: TEST CODE for signalling death of a ragdoll character
kRenderFxPulseFastWider,
kRenderFxMax
};
enum Collision_Group_t
{
COLLISION_GROUP_NONE = 0,
COLLISION_GROUP_DEBRIS, // Collides with nothing but world and static stuff
COLLISION_GROUP_DEBRIS_TRIGGER, // Same as debris, but hits triggers
COLLISION_GROUP_INTERACTIVE_DEBRIS, // Collides with everything except other interactive debris or debris
COLLISION_GROUP_INTERACTIVE, // Collides with everything except interactive debris or debris
COLLISION_GROUP_PLAYER,
COLLISION_GROUP_BREAKABLE_GLASS,
COLLISION_GROUP_VEHICLE,
COLLISION_GROUP_PLAYER_MOVEMENT, // For HL2, same as Collision_Group_Player, for
// TF2, this filters out other players and CBaseObjects
COLLISION_GROUP_NPC, // Generic NPC group
COLLISION_GROUP_IN_VEHICLE, // for any entity inside a vehicle
COLLISION_GROUP_WEAPON, // for any weapons that need collision detection
COLLISION_GROUP_VEHICLE_CLIP, // vehicle clip brush to restrict vehicle movement
COLLISION_GROUP_PROJECTILE, // Projectiles!
COLLISION_GROUP_DOOR_BLOCKER, // Blocks entities not permitted to get near moving doors
COLLISION_GROUP_PASSABLE_DOOR, // Doors that the player shouldn't collide with
COLLISION_GROUP_DISSOLVING, // Things that are dissolving are in this group
COLLISION_GROUP_PUSHAWAY, // Nonsolid on client and server, pushaway in player code
COLLISION_GROUP_NPC_ACTOR, // Used so NPCs in scripts ignore the player.
COLLISION_GROUP_NPC_SCRIPTED, // USed for NPCs in scripts that should not collide with each other
LAST_SHARED_COLLISION_GROUP
};
#define SOUND_NORMAL_CLIP_DIST 1000.0f
// How many networked area portals do we allow?
#define MAX_AREA_STATE_BYTES 32
#define MAX_AREA_PORTAL_STATE_BYTES 24
// user message max payload size (note, this value is used by the engine, so MODs cannot change it)
#define MAX_USER_MSG_DATA 255
#define MAX_ENTITY_MSG_DATA 255
#define SOURCE_MT
#ifdef SOURCE_MT
class CThreadMutex;
typedef CThreadMutex CSourceMutex;
#else
class CThreadNullMutex;
typedef CThreadNullMutex CSourceMutex;
#endif
#endif
// lower bits are stronger, and will eat weaker brushes completely
#define CONTENTS_EMPTY 0 // No contents
#define CONTENTS_SOLID 0x1 // an eye is never valid in a solid
#define CONTENTS_WINDOW 0x2 // translucent, but not watery (glass)
#define CONTENTS_AUX 0x4
#define CONTENTS_GRATE 0x8 // alpha-tested "grate" textures. Bullets/sight pass through, but solids don't
#define CONTENTS_SLIME 0x10
#define CONTENTS_WATER 0x20
#define CONTENTS_BLOCKLOS 0x40 // block AI line of sight
#define CONTENTS_OPAQUE 0x80 // things that cannot be seen through (may be non-solid though)
#define LAST_VISIBLE_CONTENTS 0x80
#define ALL_VISIBLE_CONTENTS ( LAST_VISIBLE_CONTENTS | ( LAST_VISIBLE_CONTENTS - 1 ) )
#define CONTENTS_TESTFOGVOLUME 0x100
#define CONTENTS_UNUSED 0x200
// unused
// NOTE: If it's visible, grab from the top + update LAST_VISIBLE_CONTENTS
// if not visible, then grab from the bottom.
#define CONTENTS_UNUSED6 0x400
#define CONTENTS_TEAM1 0x800 // per team contents used to differentiate collisions
#define CONTENTS_TEAM2 0x1000 // between players and objects on different teams
// ignore CONTENTS_OPAQUE on surfaces that have SURF_NODRAW
#define CONTENTS_IGNORE_NODRAW_OPAQUE 0x2000
// hits entities which are MOVETYPE_PUSH (doors, plats, etc.)
#define CONTENTS_MOVEABLE 0x4000
// remaining contents are non-visible, and don't eat brushes
#define CONTENTS_AREAPORTAL 0x8000
#define CONTENTS_PLAYERCLIP 0x10000
#define CONTENTS_MONSTERCLIP 0x20000
// currents can be added to any other contents, and may be mixed
#define CONTENTS_CURRENT_0 0x40000
#define CONTENTS_CURRENT_90 0x80000
#define CONTENTS_CURRENT_180 0x100000
#define CONTENTS_CURRENT_270 0x200000
#define CONTENTS_CURRENT_UP 0x400000
#define CONTENTS_CURRENT_DOWN 0x800000
#define CONTENTS_ORIGIN 0x1000000 // removed before bsping an entity
#define CONTENTS_MONSTER 0x2000000 // should never be on a brush, only in game
#define CONTENTS_DEBRIS 0x4000000
#define CONTENTS_DETAIL 0x8000000 // brushes to be added after vis leafs
#define CONTENTS_TRANSLUCENT 0x10000000 // auto set if any surface has trans
#define CONTENTS_LADDER 0x20000000
#define CONTENTS_HITBOX 0x40000000 // use accurate hitboxes on trace
#define MASK_ALL ( 0xFFFFFFFF )
// everything that is normally solid
#define MASK_SOLID ( CONTENTS_SOLID | CONTENTS_MOVEABLE | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_GRATE )
// everything that blocks player movement
#define MASK_PLAYERSOLID ( CONTENTS_SOLID | CONTENTS_MOVEABLE | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_GRATE )
// blocks npc movement
#define MASK_NPCSOLID ( CONTENTS_SOLID | CONTENTS_MOVEABLE | CONTENTS_MONSTERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_GRATE )
// water physics in these contents
#define MASK_WATER ( CONTENTS_WATER | CONTENTS_MOVEABLE | CONTENTS_SLIME )
// everything that blocks lighting
#define MASK_OPAQUE ( CONTENTS_SOLID | CONTENTS_MOVEABLE | CONTENTS_OPAQUE )
// everything that blocks lighting, but with monsters added.
#define MASK_OPAQUE_AND_NPCS ( MASK_OPAQUE | CONTENTS_MONSTER )
// everything that blocks line of sight for AI
#define MASK_BLOCKLOS ( CONTENTS_SOLID | CONTENTS_MOVEABLE | CONTENTS_BLOCKLOS )
// everything that blocks line of sight for AI plus NPCs
#define MASK_BLOCKLOS_AND_NPCS ( MASK_BLOCKLOS | CONTENTS_MONSTER )
// everything that blocks line of sight for players
#define MASK_VISIBLE ( MASK_OPAQUE | CONTENTS_IGNORE_NODRAW_OPAQUE )
// everything that blocks line of sight for players, but with monsters added.
#define MASK_VISIBLE_AND_NPCS ( MASK_OPAQUE_AND_NPCS | CONTENTS_IGNORE_NODRAW_OPAQUE )
// bullets see these as solid
#define MASK_SHOT ( CONTENTS_SOLID | CONTENTS_MOVEABLE | CONTENTS_MONSTER | CONTENTS_WINDOW | CONTENTS_DEBRIS | CONTENTS_HITBOX )
// non-raycasted weapons see this as solid (includes grates)
#define MASK_SHOT_HULL ( CONTENTS_SOLID | CONTENTS_MOVEABLE | CONTENTS_MONSTER | CONTENTS_WINDOW | CONTENTS_DEBRIS | CONTENTS_GRATE )
// hits solids (not grates) and passes through everything else
#define MASK_SHOT_PORTAL ( CONTENTS_SOLID | CONTENTS_MOVEABLE | CONTENTS_WINDOW | CONTENTS_MONSTER )
// everything normally solid, except monsters (world+brush only)
#define MASK_SOLID_BRUSHONLY ( CONTENTS_SOLID | CONTENTS_MOVEABLE | CONTENTS_WINDOW | CONTENTS_GRATE )
// everything normally solid for player movement, except monsters (world+brush only)
#define MASK_PLAYERSOLID_BRUSHONLY ( CONTENTS_SOLID | CONTENTS_MOVEABLE | CONTENTS_WINDOW | CONTENTS_PLAYERCLIP | CONTENTS_GRATE )
// everything normally solid for npc movement, except monsters (world+brush only)
#define MASK_NPCSOLID_BRUSHONLY ( CONTENTS_SOLID | CONTENTS_MOVEABLE | CONTENTS_WINDOW | CONTENTS_MONSTERCLIP | CONTENTS_GRATE )
// just the world, used for route rebuilding
#define MASK_NPCWORLDSTATIC ( CONTENTS_SOLID | CONTENTS_WINDOW | CONTENTS_MONSTERCLIP | CONTENTS_GRATE )
// These are things that can split areaportals
#define MASK_SPLITAREAPORTAL ( CONTENTS_WATER | CONTENTS_SLIME )
// UNDONE: This is untested, any moving water
#define MASK_CURRENT ( CONTENTS_CURRENT_0 | CONTENTS_CURRENT_90 | CONTENTS_CURRENT_180 | CONTENTS_CURRENT_270 | CONTENTS_CURRENT_UP | CONTENTS_CURRENT_DOWN )
// everything that blocks corpse movement
// UNDONE: Not used yet / may be deleted
#define MASK_DEADSOLID ( CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_GRATE )
#define DMG_GENERIC 0 // generic damage -- do not use if you want players to flinch and bleed!
#define DMG_CRUSH (1 << 0) // crushed by falling or moving object.
// NOTE: It's assumed crush damage is occurring as a result of physics collision, so no extra physics force is generated by crush damage.
// DON'T use DMG_CRUSH when damaging entities unless it's the result of a physics collision. You probably want DMG_CLUB instead.
#define DMG_BULLET (1 << 1) // shot
#define DMG_SLASH (1 << 2) // cut, clawed, stabbed
#define DMG_BURN (1 << 3) // heat burned
#define DMG_VEHICLE (1 << 4) // hit by a vehicle
#define DMG_FALL (1 << 5) // fell too far
#define DMG_BLAST (1 << 6) // explosive blast damage
#define DMG_CLUB (1 << 7) // crowbar, punch, headbutt
#define DMG_SHOCK (1 << 8) // electric shock
#define DMG_SONIC (1 << 9) // sound pulse shockwave
#define DMG_ENERGYBEAM (1 << 10) // laser or other high energy beam
#define DMG_PREVENT_PHYSICS_FORCE (1 << 11) // Prevent a physics force
#define DMG_NEVERGIB (1 << 12) // with this bit OR'd in, no damage type will be able to gib victims upon death
#define DMG_ALWAYSGIB (1 << 13) // with this bit OR'd in, any damage type can be made to gib victims upon death.
#define DMG_DROWN (1 << 14) // Drowning
#define DMG_PARALYZE (1 << 15) // slows affected creature down
#define DMG_NERVEGAS (1 << 16) // nerve toxins, very bad
#define DMG_POISON (1 << 17) // blood poisoning - heals over time like drowning damage
#define DMG_RADIATION (1 << 18) // radiation exposure
#define DMG_DROWNRECOVER (1 << 19) // drowning recovery
#define DMG_ACID (1 << 20) // toxic chemicals or acid burns
#define DMG_SLOWBURN (1 << 21) // in an oven
#define DMG_REMOVENORAGDOLL (1<<22) // with this bit OR'd in, no ragdoll will be created, and the target will be quietly removed.
// use this to kill an entity that you've already got a server-side ragdoll for
#define DMG_PHYSGUN (1<<23) // Hit by manipulator. Usually doesn't do any damage.
#define DMG_PLASMA (1<<24) // Shot by Cremator
#define DMG_AIRBOAT (1<<25) // Hit by the airboat's gun
#define DMG_DISSOLVE (1<<26) // Dissolving!
#define DMG_BLAST_SURFACE (1<<27) // A blast on the surface of water that cannot harm things underwater
#define DMG_DIRECT (1<<28)
#define DMG_BUCKSHOT (1<<29) // not quite a bullet. Little, rounder, different.
// NOTE: DO NOT ADD ANY MORE CUSTOM DMG_ TYPES. MODS USE THE DMG_LASTGENERICFLAG BELOW, AND
// IF YOU ADD NEW DMG_ TYPES, THEIR TYPES WILL BE HOSED. WE NEED A BETTER SOLUTION.
// TODO: keep this up to date so all the mod-specific flags don't overlap anything.
#define DMG_LASTGENERICFLAG DMG_BUCKSHOT
#define DMG_USE_HITLOCATIONS (DMG_AIRBOAT)
#define DMG_HALF_FALLOFF (DMG_RADIATION)
#define DMG_CRITICAL (DMG_ACID)
#define DMG_RADIUS_MAX (DMG_ENERGYBEAM)
#define DMG_IGNITE (DMG_PLASMA)
#define DMG_USEDISTANCEMOD (DMG_SLOWBURN) // NEED TO REMOVE CALTROPS
#define DMG_NOCLOSEDISTANCEMOD (DMG_POISON)
#define DMG_FROM_OTHER_SAPPER (DMG_IGNITE) // USED TO DAMAGE SAPPERS ON MATCHED TELEPORTERS
#define DMG_MELEE (DMG_BLAST_SURFACE)
#define DMG_DONT_COUNT_DAMAGE_TOWARDS_CRIT_RATE (DMG_DISSOLVE) // DON'T USE THIS FOR EXPLOSION DAMAGE YOU WILL MAKE BRANDON SAD AND KYLE SADDER
// This can only ever be used on a TakeHealth call, since it re-uses a dmg flag that means something else
#define DMG_IGNORE_MAXHEALTH (DMG_BULLET)
#define DMG_IGNORE_DEBUFFS (DMG_SLASH)
#define FLOW_OUTGOING 0
#define FLOW_INCOMING 1
#define COORD_INTEGER_BITS 14
#define COORD_FRACTIONAL_BITS 5
#define COORD_DENOMINATOR (1<<(COORD_FRACTIONAL_BITS))
#define COORD_RESOLUTION (1.0/(COORD_DENOMINATOR))
typedef enum
{
EMPTY,
SINGLE,
SINGLE_NPC,
WPN_DOUBLE, // Can't be "DOUBLE" because windows.h uses it.
DOUBLE_NPC,
BURST,
RELOAD,
RELOAD_NPC,
MELEE_MISS,
MELEE_HIT,
MELEE_HIT_WORLD,
SPECIAL1,
SPECIAL2,
SPECIAL3,
TAUNT,
DEPLOY,
// Add new shoot sound types here
NUM_SHOOT_SOUND_TYPES,
} WeaponSound_t;
#define MAX_SHOOT_SOUNDS 16 // Maximum number of shoot sounds per shoot type
#define MAX_WEAPON_STRING 80
#define MAX_WEAPON_PREFIX 16
#define MAX_WEAPON_AMMO_NAME 32
#define WEAPON_PRINTNAME_MISSING "!!! Missing printname on weapon"
#define BONE_CALCULATE_MASK 0x1F
#define BONE_PHYSICALLY_SIMULATED 0x01 // bone is physically simulated when physics are active
#define BONE_PHYSICS_PROCEDURAL 0x02 // procedural when physics is active
#define BONE_ALWAYS_PROCEDURAL 0x04 // bone is always procedurally animated
#define BONE_SCREEN_ALIGN_SPHERE 0x08 // bone aligns to the screen, not constrained in motion.
#define BONE_SCREEN_ALIGN_CYLINDER 0x10 // bone aligns to the screen, constrained by it's own axis.
#define BONE_USED_MASK 0x0007FF00
#define BONE_USED_BY_ANYTHING 0x0007FF00
#define BONE_USED_BY_HITBOX 0x00000100 // bone (or child) is used by a hit box
#define BONE_USED_BY_ATTACHMENT 0x00000200 // bone (or child) is used by an attachment point
#define BONE_USED_BY_VERTEX_MASK 0x0003FC00
#define BONE_USED_BY_VERTEX_LOD0 0x00000400 // bone (or child) is used by the toplevel model via skinned vertex
#define BONE_USED_BY_VERTEX_LOD1 0x00000800
#define BONE_USED_BY_VERTEX_LOD2 0x00001000
#define BONE_USED_BY_VERTEX_LOD3 0x00002000
#define BONE_USED_BY_VERTEX_LOD4 0x00004000
#define BONE_USED_BY_VERTEX_LOD5 0x00008000
#define BONE_USED_BY_VERTEX_LOD6 0x00010000
#define BONE_USED_BY_VERTEX_LOD7 0x00020000
#define BONE_USED_BY_BONE_MERGE 0x00040000 // bone is available for bone merge to occur against it
#define BONE_USED_BY_VERTEX_AT_LOD(lod) ( BONE_USED_BY_VERTEX_LOD0 << (lod) )
#define BONE_USED_BY_ANYTHING_AT_LOD(lod) ( ( BONE_USED_BY_ANYTHING & ~BONE_USED_BY_VERTEX_MASK ) | BONE_USED_BY_VERTEX_AT_LOD(lod) )
#define MAX_NUM_LODS 8
#define BONE_TYPE_MASK 0x00F00000
#define BONE_FIXED_ALIGNMENT 0x00100000 // bone can't spin 360 degrees, all interpolation is normalized around a fixed orientation
#define BONE_HAS_SAVEFRAME_POS 0x00200000 // Vector48
#define BONE_HAS_SAVEFRAME_ROT 0x00400000 // Quaternion64
#define MAXSTUDIOTRIANGLES 65536 // TODO: tune this
#define MAXSTUDIOVERTS 65536 // TODO: tune this
#define MAXSTUDIOFLEXVERTS 10000 // max number of verts that can be flexed per mesh. TODO: tune this
#define MAXSTUDIOSKINS 32 // total textures
#define MAXSTUDIOBONES 128 // total bones actually used
#define MAXSTUDIOFLEXDESC 1024 // maximum number of low level flexes (actual morph targets)
#define MAXSTUDIOFLEXCTRL 96 // maximum number of flexcontrollers (input sliders)
#define MAXSTUDIOPOSEPARAM 24
#define MAXSTUDIOBONECTRLS 4
#define MAXSTUDIOANIMBLOCKS 256
#define MAXSTUDIOBONEBITS 7 // NOTE: MUST MATCH MAXSTUDIOBONES
// NOTE!!! : Changing this number also changes the vtx file format!!!!!
#define MAX_NUM_BONES_PER_VERT 3
#define CREATERENDERTARGETFLAGS_HDR 0x00000001
#define CREATERENDERTARGETFLAGS_AUTOMIPMAP 0x00000002
#define CREATERENDERTARGETFLAGS_UNFILTERABLE_OK 0x00000004
#define TEXTURE_GROUP_LIGHTMAP "Lightmaps"
#define TEXTURE_GROUP_WORLD "World textures"
#define TEXTURE_GROUP_MODEL "Model textures"
#define TEXTURE_GROUP_VGUI "VGUI textures"
#define TEXTURE_GROUP_PARTICLE "Particle textures"
#define TEXTURE_GROUP_DECAL "Decal textures"
#define TEXTURE_GROUP_SKYBOX "SkyBox textures"
#define TEXTURE_GROUP_CLIENT_EFFECTS "ClientEffect textures"
#define TEXTURE_GROUP_OTHER "Other textures"
#define TEXTURE_GROUP_PRECACHED "Precached" // TODO: assign texture groups to the precached materials
#define TEXTURE_GROUP_CUBE_MAP "CubeMap textures"
#define TEXTURE_GROUP_RENDER_TARGET "RenderTargets"
#define TEXTURE_GROUP_RUNTIME_COMPOSITE "Runtime Composite"
#define TEXTURE_GROUP_UNACCOUNTED "Unaccounted textures" // Textures that weren't assigned a texture group.
//#define TEXTURE_GROUP_STATIC_VERTEX_BUFFER "Static Vertex"
#define TEXTURE_GROUP_STATIC_INDEX_BUFFER "Static Indices"
#define TEXTURE_GROUP_STATIC_VERTEX_BUFFER_DISP "Displacement Verts"
#define TEXTURE_GROUP_STATIC_VERTEX_BUFFER_COLOR "Lighting Verts"
#define TEXTURE_GROUP_STATIC_VERTEX_BUFFER_WORLD "World Verts"
#define TEXTURE_GROUP_STATIC_VERTEX_BUFFER_MODELS "Model Verts"
#define TEXTURE_GROUP_STATIC_VERTEX_BUFFER_OTHER "Other Verts"
#define TEXTURE_GROUP_DYNAMIC_INDEX_BUFFER "Dynamic Indices"
#define TEXTURE_GROUP_DYNAMIC_VERTEX_BUFFER "Dynamic Verts"
#define TEXTURE_GROUP_DEPTH_BUFFER "DepthBuffer"
#define TEXTURE_GROUP_VIEW_MODEL "ViewModel"
#define TEXTURE_GROUP_PIXEL_SHADERS "Pixel Shaders"
#define TEXTURE_GROUP_VERTEX_SHADERS "Vertex Shaders"
#define TEXTURE_GROUP_RENDER_TARGET_SURFACE "RenderTarget Surfaces"
#define TEXTURE_GROUP_MORPH_TARGETS "Morph Targets"
#define STUDIO_NONE 0x00000000
#define STUDIO_RENDER 0x00000001
#define STUDIO_VIEWXFORMATTACHMENTS 0x00000002
#define STUDIO_DRAWTRANSLUCENTSUBMODELS 0x00000004
#define STUDIO_TWOPASS 0x00000008
#define STUDIO_STATIC_LIGHTING 0x00000010
#define STUDIO_WIREFRAME 0x00000020
#define STUDIO_ITEM_BLINK 0x00000040
#define STUDIO_NOSHADOWS 0x00000080
#define STUDIO_WIREFRAME_VCOLLIDE 0x00000100
#define STUDIO_NO_OVERRIDE_FOR_ATTACH 0x00000200
// Not a studio flag, but used to flag when we want studio stats
#define STUDIO_GENERATE_STATS 0x01000000
// Not a studio flag, but used to flag model as using shadow depth material override
#define STUDIO_SSAODEPTHTEXTURE 0x08000000
// Not a studio flag, but used to flag model as using shadow depth material override
#define STUDIO_SHADOWDEPTHTEXTURE 0x40000000
// Not a studio flag, but used to flag model as a non-sorting brush model
#define STUDIO_TRANSPARENCY 0x80000000
#define MAX_SPHERE_QUERY 512
enum soundlevel_t
{
SNDLVL_NONE = 0,
SNDLVL_20dB = 20, // rustling leaves
SNDLVL_25dB = 25, // whispering
SNDLVL_30dB = 30, // library
SNDLVL_35dB = 35,
SNDLVL_40dB = 40,
SNDLVL_45dB = 45, // refrigerator
SNDLVL_50dB = 50, // 3.9 // average home
SNDLVL_55dB = 55, // 3.0
SNDLVL_IDLE = 60, // 2.0
SNDLVL_60dB = 60, // 2.0 // normal conversation, clothes dryer
SNDLVL_65dB = 65, // 1.5 // washing machine, dishwasher
SNDLVL_STATIC = 66, // 1.25
SNDLVL_70dB = 70, // 1.0 // car, vacuum cleaner, mixer, electric sewing machine
SNDLVL_NORM = 75,
SNDLVL_75dB = 75, // 0.8 // busy traffic
SNDLVL_80dB = 80, // 0.7 // mini-bike, alarm clock, noisy restaurant, office tabulator, outboard motor, passing snowmobile
SNDLVL_TALKING = 80, // 0.7
SNDLVL_85dB = 85, // 0.6 // average factory, electric shaver
SNDLVL_90dB = 90, // 0.5 // screaming child, passing motorcycle, convertible ride on frw
SNDLVL_95dB = 95,
SNDLVL_100dB = 100, // 0.4 // subway train, diesel truck, woodworking shop, pneumatic drill, boiler shop, jackhammer
SNDLVL_105dB = 105, // helicopter, power mower
SNDLVL_110dB = 110, // snowmobile drvrs seat, inboard motorboat, sandblasting
SNDLVL_120dB = 120, // auto horn, propeller aircraft
SNDLVL_130dB = 130, // air raid siren
SNDLVL_GUNFIRE = 140, // 0.27 // THRESHOLD OF PAIN, gunshot, jet engine
SNDLVL_140dB = 140, // 0.2
SNDLVL_150dB = 150, // 0.2
SNDLVL_180dB = 180, // rocket launching
// NOTE: Valid soundlevel_t values are 0-255.
// 256-511 are reserved for sounds using goldsrc compatibility attenuation.
};
#define PITCH_NORM 100 // non-pitch shifted
#define PITCH_LOW 95 // other values are possible - 0-255, where 255 is very high
#define PITCH_HIGH 120
enum modtype_t
{
mod_bad = 0,
mod_brush,
mod_sprite,
mod_studio
}; | 412 | 0.841496 | 1 | 0.841496 | game-dev | MEDIA | 0.947007 | game-dev | 0.520597 | 1 | 0.520597 |
dotnet/runtime | 87,117 | src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text;
namespace Microsoft.VisualBasic
{
internal sealed partial class VBCodeGenerator : CodeCompiler
{
private static readonly char[] s_periodArray = new char[] { '.' };
private const int MaxLineLength = 80;
private const GeneratorSupport LanguageSupport = GeneratorSupport.EntryPointMethod |
GeneratorSupport.GotoStatements |
GeneratorSupport.ArraysOfArrays |
GeneratorSupport.MultidimensionalArrays |
GeneratorSupport.StaticConstructors |
GeneratorSupport.ReturnTypeAttributes |
GeneratorSupport.AssemblyAttributes |
GeneratorSupport.TryCatchStatements |
GeneratorSupport.DeclareValueTypes |
GeneratorSupport.DeclareEnums |
GeneratorSupport.DeclareEvents |
GeneratorSupport.DeclareDelegates |
GeneratorSupport.DeclareInterfaces |
GeneratorSupport.ParameterAttributes |
GeneratorSupport.ReferenceParameters |
GeneratorSupport.ChainedConstructorArguments |
GeneratorSupport.NestedTypes |
GeneratorSupport.MultipleInterfaceMembers |
GeneratorSupport.PublicStaticMembers |
GeneratorSupport.ComplexExpressions |
GeneratorSupport.Win32Resources |
GeneratorSupport.Resources |
GeneratorSupport.PartialTypes |
GeneratorSupport.GenericTypeReference |
GeneratorSupport.GenericTypeDeclaration |
GeneratorSupport.DeclareIndexerProperties;
private int _statementDepth;
private readonly IDictionary<string, string> _provOptions;
// This is the keyword list. To minimize search time and startup time, this is stored by length
// and then alphabetically for use by FixedStringLookup.Contains.
private static readonly string[][] s_keywords = new string[][] {
null, // 1 character
new string[] { // 2 characters
"as",
"do",
"if",
"in",
"is",
"me",
"of",
"on",
"or",
"to",
},
new string[] { // 3 characters
"and",
"dim",
"end",
"for",
"get",
"let",
"lib",
"mod",
"new",
"not",
"rem",
"set",
"sub",
"try",
"xor",
},
new string[] { // 4 characters
"ansi",
"auto",
"byte",
"call",
"case",
"cdbl",
"cdec",
"char",
"cint",
"clng",
"cobj",
"csng",
"cstr",
"date",
"each",
"else",
"enum",
"exit",
"goto",
"like",
"long",
"loop",
"next",
"step",
"stop",
"then",
"true",
"wend",
"when",
"with",
},
new string[] { // 5 characters
"alias",
"byref",
"byval",
"catch",
"cbool",
"cbyte",
"cchar",
"cdate",
"class",
"const",
"ctype",
"cuint",
"culng",
"endif",
"erase",
"error",
"event",
"false",
"gosub",
"isnot",
"redim",
"sbyte",
"short",
"throw",
"ulong",
"until",
"using",
"while",
},
new string[] { // 6 characters
"csbyte",
"cshort",
"double",
"elseif",
"friend",
"global",
"module",
"mybase",
"object",
"option",
"orelse",
"public",
"resume",
"return",
"select",
"shared",
"single",
"static",
"string",
"typeof",
"ushort",
},
new string[] { // 7 characters
"andalso",
"boolean",
"cushort",
"decimal",
"declare",
"default",
"finally",
"gettype",
"handles",
"imports",
"integer",
"myclass",
"nothing",
"partial",
"private",
"shadows",
"trycast",
"unicode",
"variant",
},
new string[] { // 8 characters
"assembly",
"continue",
"delegate",
"function",
"inherits",
"operator",
"optional",
"preserve",
"property",
"readonly",
"synclock",
"uinteger",
"widening"
},
new string [] { // 9 characters
"addressof",
"interface",
"namespace",
"narrowing",
"overloads",
"overrides",
"protected",
"structure",
"writeonly",
},
new string [] { // 10 characters
"addhandler",
"directcast",
"implements",
"paramarray",
"raiseevent",
"withevents",
},
new string[] { // 11 characters
"mustinherit",
"overridable",
},
new string[] { // 12 characters
"mustoverride",
},
new string [] { // 13 characters
"removehandler",
},
// class_finalize and class_initialize are not keywords anymore,
// but it will be nice to escape them to avoid warning
new string [] { // 14 characters
"class_finalize",
"notinheritable",
"notoverridable",
},
null, // 15 characters
new string [] {
"class_initialize",
}
};
internal VBCodeGenerator() { }
internal VBCodeGenerator(IDictionary<string, string> providerOptions)
{
_provOptions = providerOptions;
}
protected override string FileExtension => ".vb";
protected override string CompilerName => "vbc.exe";
/// <summary>Tells whether or not the current class should be generated as a module</summary>
private bool IsCurrentModule => IsCurrentClass && GetUserData(CurrentClass, "Module", false);
protected override string NullToken => "Nothing";
private static void EnsureInDoubleQuotes(ref bool fInDoubleQuotes, StringBuilder b)
{
if (fInDoubleQuotes)
{
return;
}
b.Append("&\"");
fInDoubleQuotes = true;
}
private static void EnsureNotInDoubleQuotes(ref bool fInDoubleQuotes, StringBuilder b)
{
if (!fInDoubleQuotes)
{
return;
}
b.Append('\"');
fInDoubleQuotes = false;
}
protected override string QuoteSnippetString(string value)
{
StringBuilder b = new StringBuilder(value.Length + 5);
bool fInDoubleQuotes = true;
Indentation indentObj = new Indentation((ExposedTabStringIndentedTextWriter)Output, Indent + 1);
b.Append('\"');
int i = 0;
while (i < value.Length)
{
char ch = value[i];
switch (ch)
{
case '\"':
// These are the inward sloping quotes used by default in some cultures like CHS.
// VBC.EXE does a mapping ANSI that results in it treating these as syntactically equivalent to a
// regular double quote.
case '\u201C':
case '\u201D':
case '\uFF02':
EnsureInDoubleQuotes(ref fInDoubleQuotes, b);
b.Append(ch);
b.Append(ch);
break;
case '\r':
EnsureNotInDoubleQuotes(ref fInDoubleQuotes, b);
if (i < value.Length - 1 && value[i + 1] == '\n')
{
b.Append("&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)");
i++;
}
else
{
b.Append("&Global.Microsoft.VisualBasic.ChrW(13)");
}
break;
case '\t':
EnsureNotInDoubleQuotes(ref fInDoubleQuotes, b);
b.Append("&Global.Microsoft.VisualBasic.ChrW(9)");
break;
case '\0':
EnsureNotInDoubleQuotes(ref fInDoubleQuotes, b);
b.Append("&Global.Microsoft.VisualBasic.ChrW(0)");
break;
case '\n':
EnsureNotInDoubleQuotes(ref fInDoubleQuotes, b);
b.Append("&Global.Microsoft.VisualBasic.ChrW(10)");
break;
case '\u2028':
case '\u2029':
EnsureNotInDoubleQuotes(ref fInDoubleQuotes, b);
AppendEscapedChar(b, ch);
break;
default:
EnsureInDoubleQuotes(ref fInDoubleQuotes, b);
b.Append(value[i]);
break;
}
if (i > 0 && i % MaxLineLength == 0)
{
// If current character is a high surrogate and the following
// character is a low surrogate, don't break them.
// Otherwise when we write the string to a file, we might lose
// the characters.
if (char.IsHighSurrogate(value[i])
&& (i < value.Length - 1)
&& char.IsLowSurrogate(value[i + 1]))
{
b.Append(value[++i]);
}
if (fInDoubleQuotes)
b.Append('\"');
fInDoubleQuotes = true;
b.Append("& _ ");
b.Append(Environment.NewLine);
b.Append(indentObj.IndentationString);
b.Append('\"');
}
++i;
}
if (fInDoubleQuotes)
b.Append('\"');
return b.ToString();
}
private static void AppendEscapedChar(StringBuilder b, char value)
{
b.Append("&Global.Microsoft.VisualBasic.ChrW(");
b.Append(((int)value).ToString(CultureInfo.InvariantCulture));
b.Append(')');
}
protected override void ProcessCompilerOutputLine(CompilerResults results, string line)
{
throw new PlatformNotSupportedException();
}
protected override string CmdArgsFromParameters(CompilerParameters options)
{
throw new PlatformNotSupportedException();
}
protected override void OutputAttributeArgument(CodeAttributeArgument arg)
{
if (!string.IsNullOrEmpty(arg.Name))
{
OutputIdentifier(arg.Name);
Output.Write(":=");
}
((ICodeGenerator)this).GenerateCodeFromExpression(arg.Value, ((ExposedTabStringIndentedTextWriter)Output).InnerWriter, Options);
}
private void OutputAttributes(CodeAttributeDeclarationCollection attributes, bool inLine)
{
OutputAttributes(attributes, inLine, null, false);
}
private void OutputAttributes(CodeAttributeDeclarationCollection attributes, bool inLine, string prefix, bool closingLine)
{
if (attributes.Count == 0) return;
bool firstAttr = true;
GenerateAttributeDeclarationsStart(attributes);
foreach (CodeAttributeDeclaration current in attributes)
{
if (firstAttr)
{
firstAttr = false;
}
else
{
Output.Write(", ");
if (!inLine)
{
ContinueOnNewLine("");
Output.Write(' ');
}
}
if (!string.IsNullOrEmpty(prefix))
{
Output.Write(prefix);
}
if (current.AttributeType != null)
{
Output.Write(GetTypeOutput(current.AttributeType));
}
Output.Write('(');
bool firstArg = true;
foreach (CodeAttributeArgument arg in current.Arguments)
{
if (firstArg)
{
firstArg = false;
}
else
{
Output.Write(", ");
}
OutputAttributeArgument(arg);
}
Output.Write(')');
}
GenerateAttributeDeclarationsEnd(attributes);
Output.Write(' ');
if (!inLine)
{
if (closingLine)
{
Output.WriteLine();
}
else
{
ContinueOnNewLine("");
}
}
}
protected override void OutputDirection(FieldDirection dir)
{
switch (dir)
{
case FieldDirection.In:
Output.Write("ByVal ");
break;
case FieldDirection.Out:
case FieldDirection.Ref:
Output.Write("ByRef ");
break;
}
}
protected override void GenerateDefaultValueExpression(CodeDefaultValueExpression e)
{
Output.Write("CType(Nothing, " + GetTypeOutput(e.Type) + ")");
}
protected override void GenerateDirectionExpression(CodeDirectionExpression e)
{
// Visual Basic does not need to adorn the calling point with a direction, so just output the expression.
GenerateExpression(e.Expression);
}
protected override void OutputFieldScopeModifier(MemberAttributes attributes)
{
switch (attributes & MemberAttributes.ScopeMask)
{
case MemberAttributes.Final:
Output.Write("");
break;
case MemberAttributes.Static:
// ignore Static for fields in a Module since all fields in a module are already
// static and it is a syntax error to explicitly mark them as static
//
if (!IsCurrentModule)
{
Output.Write("Shared ");
}
break;
case MemberAttributes.Const:
Output.Write("Const ");
break;
default:
Output.Write("");
break;
}
}
protected override void OutputMemberAccessModifier(MemberAttributes attributes)
{
switch (attributes & MemberAttributes.AccessMask)
{
case MemberAttributes.Assembly:
Output.Write("Friend ");
break;
case MemberAttributes.FamilyAndAssembly:
Output.Write("Friend ");
break;
case MemberAttributes.Family:
Output.Write("Protected ");
break;
case MemberAttributes.FamilyOrAssembly:
Output.Write("Protected Friend ");
break;
case MemberAttributes.Private:
Output.Write("Private ");
break;
case MemberAttributes.Public:
Output.Write("Public ");
break;
}
}
private void OutputVTableModifier(MemberAttributes attributes)
{
switch (attributes & MemberAttributes.VTableMask)
{
case MemberAttributes.New:
Output.Write("Shadows ");
break;
}
}
protected override void OutputMemberScopeModifier(MemberAttributes attributes)
{
switch (attributes & MemberAttributes.ScopeMask)
{
case MemberAttributes.Abstract:
Output.Write("MustOverride ");
break;
case MemberAttributes.Final:
Output.Write("");
break;
case MemberAttributes.Static:
// ignore Static for members in a Module since all members in a module are already
// static and it is a syntax error to explicitly mark them as static
//
if (!IsCurrentModule)
{
Output.Write("Shared ");
}
break;
case MemberAttributes.Override:
Output.Write("Overrides ");
break;
default:
switch (attributes & MemberAttributes.AccessMask)
{
case MemberAttributes.Family:
case MemberAttributes.Public:
case MemberAttributes.Assembly:
Output.Write("Overridable ");
break;
default:
// nothing;
break;
}
break;
}
}
protected override void OutputOperator(CodeBinaryOperatorType op)
{
switch (op)
{
case CodeBinaryOperatorType.IdentityInequality:
Output.Write("<>");
break;
case CodeBinaryOperatorType.IdentityEquality:
Output.Write("Is");
break;
case CodeBinaryOperatorType.BooleanOr:
Output.Write("OrElse");
break;
case CodeBinaryOperatorType.BooleanAnd:
Output.Write("AndAlso");
break;
case CodeBinaryOperatorType.ValueEquality:
Output.Write('=');
break;
case CodeBinaryOperatorType.Modulus:
Output.Write("Mod");
break;
case CodeBinaryOperatorType.BitwiseOr:
Output.Write("Or");
break;
case CodeBinaryOperatorType.BitwiseAnd:
Output.Write("And");
break;
default:
base.OutputOperator(op);
break;
}
}
private void GenerateNotIsNullExpression(CodeExpression e)
{
Output.Write("(Not (");
GenerateExpression(e);
Output.Write(") Is ");
Output.Write(NullToken);
Output.Write(')');
}
protected override void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpression e)
{
if (e.Operator != CodeBinaryOperatorType.IdentityInequality)
{
base.GenerateBinaryOperatorExpression(e);
return;
}
// "o <> nothing" should be "not o is nothing"
if (e.Right is CodePrimitiveExpression && ((CodePrimitiveExpression)e.Right).Value == null)
{
GenerateNotIsNullExpression(e.Left);
return;
}
if (e.Left is CodePrimitiveExpression && ((CodePrimitiveExpression)e.Left).Value == null)
{
GenerateNotIsNullExpression(e.Right);
return;
}
base.GenerateBinaryOperatorExpression(e);
}
protected override string GetResponseFileCmdArgs(CompilerParameters options, string cmdArgs)
{
// Always specify the /noconfig flag (outside of the response file)
return "/noconfig " + base.GetResponseFileCmdArgs(options, cmdArgs);
}
protected override void OutputIdentifier(string ident)
{
Output.Write(CreateEscapedIdentifier(ident));
}
protected override void OutputType(CodeTypeReference typeRef)
{
Output.Write(GetTypeOutputWithoutArrayPostFix(typeRef));
}
private void OutputTypeAttributes(CodeTypeDeclaration e)
{
if ((e.Attributes & MemberAttributes.New) != 0)
{
Output.Write("Shadows ");
}
TypeAttributes attributes = e.TypeAttributes;
if (e.IsPartial)
{
Output.Write("Partial ");
}
switch (attributes & TypeAttributes.VisibilityMask)
{
case TypeAttributes.Public:
case TypeAttributes.NestedPublic:
Output.Write("Public ");
break;
case TypeAttributes.NestedPrivate:
Output.Write("Private ");
break;
case TypeAttributes.NestedFamily:
Output.Write("Protected ");
break;
case TypeAttributes.NotPublic:
case TypeAttributes.NestedAssembly:
case TypeAttributes.NestedFamANDAssem:
Output.Write("Friend ");
break;
case TypeAttributes.NestedFamORAssem:
Output.Write("Protected Friend ");
break;
}
if (e.IsStruct)
{
Output.Write("Structure ");
}
else if (e.IsEnum)
{
Output.Write("Enum ");
}
else
{
switch (attributes & TypeAttributes.ClassSemanticsMask)
{
case TypeAttributes.Class:
// if this "class" should generate as a module, then don't check
// inheritance flags since modules can't inherit
if (IsCurrentModule)
{
Output.Write("Module ");
}
else
{
if ((attributes & TypeAttributes.Sealed) == TypeAttributes.Sealed)
{
Output.Write("NotInheritable ");
}
if ((attributes & TypeAttributes.Abstract) == TypeAttributes.Abstract)
{
Output.Write("MustInherit ");
}
Output.Write("Class ");
}
break;
case TypeAttributes.Interface:
Output.Write("Interface ");
break;
}
}
}
protected override void OutputTypeNamePair(CodeTypeReference typeRef, string name)
{
if (string.IsNullOrEmpty(name))
name = "__exception";
OutputIdentifier(name);
OutputArrayPostfix(typeRef);
Output.Write(" As ");
OutputType(typeRef);
}
private static string GetArrayPostfix(CodeTypeReference typeRef)
{
string s = "";
if (typeRef.ArrayElementType != null)
{
// Recurse up
s = GetArrayPostfix(typeRef.ArrayElementType);
}
if (typeRef.ArrayRank > 0)
{
char[] results = new char[typeRef.ArrayRank + 1];
results[0] = '(';
results[typeRef.ArrayRank] = ')';
for (int i = 1; i < typeRef.ArrayRank; i++)
{
results[i] = ',';
}
s = new string(results) + s;
}
return s;
}
private void OutputArrayPostfix(CodeTypeReference typeRef)
{
if (typeRef.ArrayRank > 0)
{
Output.Write(GetArrayPostfix(typeRef));
}
}
protected override void GenerateIterationStatement(CodeIterationStatement e)
{
GenerateStatement(e.InitStatement);
Output.Write("Do While ");
GenerateExpression(e.TestExpression);
Output.WriteLine();
Indent++;
GenerateVBStatements(e.Statements);
GenerateStatement(e.IncrementStatement);
Indent--;
Output.WriteLine("Loop");
}
protected override void GeneratePrimitiveExpression(CodePrimitiveExpression e)
{
if (e.Value is char)
{
Output.Write("Global.Microsoft.VisualBasic.ChrW(" + ((IConvertible)e.Value).ToInt32(CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture) + ")");
}
else if (e.Value is sbyte)
{
Output.Write("CSByte(");
Output.Write(((sbyte)e.Value).ToString(CultureInfo.InvariantCulture));
Output.Write(')');
}
else if (e.Value is ushort)
{
Output.Write(((ushort)e.Value).ToString(CultureInfo.InvariantCulture));
Output.Write("US");
}
else if (e.Value is uint)
{
Output.Write(((uint)e.Value).ToString(CultureInfo.InvariantCulture));
Output.Write("UI");
}
else if (e.Value is ulong)
{
Output.Write(((ulong)e.Value).ToString(CultureInfo.InvariantCulture));
Output.Write("UL");
}
else
{
base.GeneratePrimitiveExpression(e);
}
}
protected override void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e)
{
Output.Write("Throw");
if (e.ToThrow != null)
{
Output.Write(' ');
GenerateExpression(e.ToThrow);
}
Output.WriteLine();
}
protected override void GenerateArrayCreateExpression(CodeArrayCreateExpression e)
{
Output.Write("New ");
CodeExpressionCollection init = e.Initializers;
if (init.Count > 0)
{
string typeName = GetTypeOutput(e.CreateType);
Output.Write(typeName);
#if NET
if (!typeName.Contains('('))
#else
if (typeName.IndexOf('(') == -1)
#endif
{
Output.Write("()");
}
Output.Write(" {");
Indent++;
OutputExpressionList(init);
Indent--;
Output.Write('}');
}
else
{
string typeName = GetTypeOutput(e.CreateType);
int index = typeName.IndexOf('(');
if (index == -1)
{
Output.Write(typeName);
Output.Write('(');
}
else
{
#if NET
Output.Write(typeName.AsSpan(0, index + 1));
#else
Output.Write(typeName.Substring(0, index + 1));
#endif
}
// The tricky thing is we need to declare the size - 1
if (e.SizeExpression != null)
{
Output.Write('(');
GenerateExpression(e.SizeExpression);
Output.Write(") - 1");
}
else
{
Output.Write(e.Size - 1);
}
if (index == -1)
{
Output.Write(')');
}
else
{
#if NET
Output.Write(typeName.AsSpan(index + 1));
#else
Output.Write(typeName.Substring(index + 1));
#endif
}
Output.Write(" {}");
}
}
protected override void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e)
{
Output.Write("MyBase");
}
protected override void GenerateCastExpression(CodeCastExpression e)
{
Output.Write("CType(");
GenerateExpression(e.Expression);
Output.Write(',');
OutputType(e.TargetType);
OutputArrayPostfix(e.TargetType);
Output.Write(')');
}
protected override void GenerateDelegateCreateExpression(CodeDelegateCreateExpression e)
{
Output.Write("AddressOf ");
GenerateExpression(e.TargetObject);
Output.Write('.');
OutputIdentifier(e.MethodName);
}
protected override void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e)
{
if (e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write('.');
}
OutputIdentifier(e.FieldName);
}
protected override void GenerateSingleFloatValue(float s)
{
if (float.IsNaN(s))
{
Output.Write("Single.NaN");
}
else if (float.IsNegativeInfinity(s))
{
Output.Write("Single.NegativeInfinity");
}
else if (float.IsPositiveInfinity(s))
{
Output.Write("Single.PositiveInfinity");
}
else
{
Output.Write(s.ToString(CultureInfo.InvariantCulture));
Output.Write('!');
}
}
protected override void GenerateDoubleValue(double d)
{
if (double.IsNaN(d))
{
Output.Write("Double.NaN");
}
else if (double.IsNegativeInfinity(d))
{
Output.Write("Double.NegativeInfinity");
}
else if (double.IsPositiveInfinity(d))
{
Output.Write("Double.PositiveInfinity");
}
else
{
Output.Write(d.ToString("R", CultureInfo.InvariantCulture));
// always mark a double as being a double in case we have no decimal portion (e.g write 1D instead of 1 which is an int)
Output.Write('R');
}
}
protected override void GenerateDecimalValue(decimal d)
{
Output.Write(d.ToString(CultureInfo.InvariantCulture));
Output.Write('D');
}
protected override void GenerateArgumentReferenceExpression(CodeArgumentReferenceExpression e)
{
OutputIdentifier(e.ParameterName);
}
protected override void GenerateVariableReferenceExpression(CodeVariableReferenceExpression e)
{
OutputIdentifier(e.VariableName);
}
protected override void GenerateIndexerExpression(CodeIndexerExpression e)
{
GenerateExpression(e.TargetObject);
// If this IndexerExpression is referencing to base, we need to emit
// .Item after MyBase. Otherwise the code won't compile.
if (e.TargetObject is CodeBaseReferenceExpression)
{
Output.Write(".Item");
}
Output.Write('(');
bool first = true;
foreach (CodeExpression exp in e.Indices)
{
if (first)
{
first = false;
}
else
{
Output.Write(", ");
}
GenerateExpression(exp);
}
Output.Write(')');
}
protected override void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e)
{
GenerateExpression(e.TargetObject);
Output.Write('(');
bool first = true;
foreach (CodeExpression exp in e.Indices)
{
if (first)
{
first = false;
}
else
{
Output.Write(", ");
}
GenerateExpression(exp);
}
Output.Write(')');
}
protected override void GenerateSnippetExpression(CodeSnippetExpression e)
{
Output.Write(e.Value);
}
protected override void GenerateMethodInvokeExpression(CodeMethodInvokeExpression e)
{
GenerateMethodReferenceExpression(e.Method);
CodeExpressionCollection parameters = e.Parameters;
if (parameters.Count > 0)
{
Output.Write('(');
OutputExpressionList(e.Parameters);
Output.Write(')');
}
}
protected override void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e)
{
if (e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write('.');
Output.Write(e.MethodName);
}
else
{
OutputIdentifier(e.MethodName);
}
if (e.TypeArguments.Count > 0)
{
Output.Write(GetTypeArgumentsOutput(e.TypeArguments));
}
}
protected override void GenerateEventReferenceExpression(CodeEventReferenceExpression e)
{
if (e.TargetObject != null)
{
bool localReference = (e.TargetObject is CodeThisReferenceExpression);
GenerateExpression(e.TargetObject);
Output.Write('.');
if (localReference)
{
Output.Write(e.EventName + "Event");
}
else
{
Output.Write(e.EventName);
}
}
else
{
OutputIdentifier(e.EventName + "Event");
}
}
private void GenerateFormalEventReferenceExpression(CodeEventReferenceExpression e)
{
if (e.TargetObject != null)
{
// Visual Basic Compiler does not like the me reference like this.
if (!(e.TargetObject is CodeThisReferenceExpression))
{
GenerateExpression(e.TargetObject);
Output.Write('.');
}
}
OutputIdentifier(e.EventName);
}
protected override void GenerateDelegateInvokeExpression(CodeDelegateInvokeExpression e)
{
if (e.TargetObject != null)
{
if (e.TargetObject is CodeEventReferenceExpression)
{
Output.Write("RaiseEvent ");
GenerateFormalEventReferenceExpression((CodeEventReferenceExpression)e.TargetObject);
}
else
{
GenerateExpression(e.TargetObject);
}
}
CodeExpressionCollection parameters = e.Parameters;
if (parameters.Count > 0)
{
Output.Write('(');
OutputExpressionList(e.Parameters);
Output.Write(')');
}
}
protected override void GenerateObjectCreateExpression(CodeObjectCreateExpression e)
{
Output.Write("New ");
OutputType(e.CreateType);
// always write out the () to disambiguate cases like "New System.Random().Next(x,y)"
Output.Write('(');
OutputExpressionList(e.Parameters);
Output.Write(')');
}
protected override void GenerateParameterDeclarationExpression(CodeParameterDeclarationExpression e)
{
if (e.CustomAttributes.Count > 0)
{
OutputAttributes(e.CustomAttributes, true);
}
OutputDirection(e.Direction);
OutputTypeNamePair(e.Type, e.Name);
}
protected override void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e)
{
Output.Write("value");
}
protected override void GenerateThisReferenceExpression(CodeThisReferenceExpression e)
{
Output.Write("Me");
}
protected override void GenerateExpressionStatement(CodeExpressionStatement e)
{
GenerateExpression(e.Expression);
Output.WriteLine();
}
private static bool IsDocComment(CodeCommentStatement comment)
{
return ((comment != null) && (comment.Comment != null) && comment.Comment.DocComment);
}
protected override void GenerateCommentStatements(CodeCommentStatementCollection e)
{
// since the compiler emits a warning if XML DocComment blocks appear before
// normal comments, we need to output non-DocComments first, followed by
// DocComments.
//
foreach (CodeCommentStatement comment in e)
{
if (!IsDocComment(comment))
{
GenerateCommentStatement(comment);
}
}
foreach (CodeCommentStatement comment in e)
{
if (IsDocComment(comment))
{
GenerateCommentStatement(comment);
}
}
}
protected override void GenerateComment(CodeComment e)
{
string commentLineStart = e.DocComment ? "'''" : "'";
Output.Write(commentLineStart);
bool isAfterCommentLineStart = true;
string value = e.Text;
for (int i = 0; i < value.Length; i++)
{
if (isAfterCommentLineStart)
{
if (value[i] == '\'' && (e.DocComment || (value.HasCharAt(i + 1, '\'') && !value.HasCharAt(i + 2, '\''))))
{
Output.Write(' ');
}
isAfterCommentLineStart = false;
}
Output.Write(value[i]);
if (value[i] == '\r')
{
if (value.HasCharAt(i + 1, '\n'))
{ // if next char is '\n', skip it
Output.Write('\n');
i++;
}
((ExposedTabStringIndentedTextWriter)Output).InternalOutputTabs();
Output.Write(commentLineStart);
isAfterCommentLineStart = true;
}
else if (value[i] == '\n')
{
((ExposedTabStringIndentedTextWriter)Output).InternalOutputTabs();
Output.Write(commentLineStart);
isAfterCommentLineStart = true;
}
else if (value[i] == '\u2028' || value[i] == '\u2029' || value[i] == '\u0085')
{
Output.Write(commentLineStart);
isAfterCommentLineStart = true;
}
}
Output.WriteLine();
}
protected override void GenerateMethodReturnStatement(CodeMethodReturnStatement e)
{
if (e.Expression != null)
{
Output.Write("Return ");
GenerateExpression(e.Expression);
Output.WriteLine();
}
else
{
Output.WriteLine("Return");
}
}
protected override void GenerateConditionStatement(CodeConditionStatement e)
{
Output.Write("If ");
GenerateExpression(e.Condition);
Output.WriteLine(" Then");
Indent++;
GenerateVBStatements(e.TrueStatements);
Indent--;
CodeStatementCollection falseStatements = e.FalseStatements;
if (falseStatements.Count > 0)
{
Output.Write("Else");
Output.WriteLine();
Indent++;
GenerateVBStatements(e.FalseStatements);
Indent--;
}
Output.WriteLine("End If");
}
protected override void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e)
{
Output.WriteLine("Try ");
Indent++;
GenerateVBStatements(e.TryStatements);
Indent--;
CodeCatchClauseCollection catches = e.CatchClauses;
foreach (CodeCatchClause current in catches)
{
Output.Write("Catch ");
OutputTypeNamePair(current.CatchExceptionType, current.LocalName);
Output.WriteLine();
Indent++;
GenerateVBStatements(current.Statements);
Indent--;
}
CodeStatementCollection finallyStatements = e.FinallyStatements;
if (finallyStatements.Count > 0)
{
Output.WriteLine("Finally");
Indent++;
GenerateVBStatements(finallyStatements);
Indent--;
}
Output.WriteLine("End Try");
}
protected override void GenerateAssignStatement(CodeAssignStatement e)
{
GenerateExpression(e.Left);
Output.Write(" = ");
GenerateExpression(e.Right);
Output.WriteLine();
}
protected override void GenerateAttachEventStatement(CodeAttachEventStatement e)
{
Output.Write("AddHandler ");
GenerateFormalEventReferenceExpression(e.Event);
Output.Write(", ");
GenerateExpression(e.Listener);
Output.WriteLine();
}
protected override void GenerateRemoveEventStatement(CodeRemoveEventStatement e)
{
Output.Write("RemoveHandler ");
GenerateFormalEventReferenceExpression(e.Event);
Output.Write(", ");
GenerateExpression(e.Listener);
Output.WriteLine();
}
protected override void GenerateSnippetStatement(CodeSnippetStatement e)
{
Output.WriteLine(e.Value);
}
protected override void GenerateGotoStatement(CodeGotoStatement e)
{
Output.Write("goto ");
Output.WriteLine(e.Label);
}
protected override void GenerateLabeledStatement(CodeLabeledStatement e)
{
Indent--;
Output.Write(e.Label);
Output.WriteLine(':');
Indent++;
if (e.Statement != null)
{
GenerateStatement(e.Statement);
}
}
protected override void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e)
{
bool doInit = true;
Output.Write("Dim ");
CodeTypeReference typeRef = e.Type;
if (typeRef.ArrayRank == 1 && e.InitExpression != null)
{
CodeArrayCreateExpression eAsArrayCreate = e.InitExpression as CodeArrayCreateExpression;
if (eAsArrayCreate != null && eAsArrayCreate.Initializers.Count == 0)
{
doInit = false;
OutputIdentifier(e.Name);
Output.Write('(');
if (eAsArrayCreate.SizeExpression != null)
{
Output.Write('(');
GenerateExpression(eAsArrayCreate.SizeExpression);
Output.Write(") - 1");
}
else
{
Output.Write(eAsArrayCreate.Size - 1);
}
Output.Write(')');
if (typeRef.ArrayElementType != null)
OutputArrayPostfix(typeRef.ArrayElementType);
Output.Write(" As ");
OutputType(typeRef);
}
else
OutputTypeNamePair(e.Type, e.Name);
}
else
OutputTypeNamePair(e.Type, e.Name);
if (doInit && e.InitExpression != null)
{
Output.Write(" = ");
GenerateExpression(e.InitExpression);
}
Output.WriteLine();
}
protected override void GenerateLinePragmaStart(CodeLinePragma e)
{
Output.WriteLine();
Output.Write("#ExternalSource(\"");
Output.Write(e.FileName);
Output.Write("\",");
Output.Write(e.LineNumber);
Output.WriteLine(')');
}
protected override void GenerateLinePragmaEnd(CodeLinePragma e)
{
Output.WriteLine();
Output.WriteLine("#End ExternalSource");
}
protected override void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c)
{
if (IsCurrentDelegate || IsCurrentEnum) return;
if (e.CustomAttributes.Count > 0)
{
OutputAttributes(e.CustomAttributes, false);
}
string eventName = e.Name;
if (e.PrivateImplementationType != null)
{
string impl = GetBaseTypeOutput(e.PrivateImplementationType, preferBuiltInTypes: false);
impl = impl.Replace('.', '_');
e.Name = impl + "_" + e.Name;
}
OutputMemberAccessModifier(e.Attributes);
Output.Write("Event ");
OutputTypeNamePair(e.Type, e.Name);
if (e.ImplementationTypes.Count > 0)
{
Output.Write(" Implements ");
bool first = true;
foreach (CodeTypeReference type in e.ImplementationTypes)
{
if (first)
{
first = false;
}
else
{
Output.Write(" , ");
}
OutputType(type);
Output.Write('.');
OutputIdentifier(eventName);
}
}
else if (e.PrivateImplementationType != null)
{
Output.Write(" Implements ");
OutputType(e.PrivateImplementationType);
Output.Write('.');
OutputIdentifier(eventName);
}
Output.WriteLine();
}
protected override void GenerateField(CodeMemberField e)
{
if (IsCurrentDelegate || IsCurrentInterface) return;
if (IsCurrentEnum)
{
if (e.CustomAttributes.Count > 0)
{
OutputAttributes(e.CustomAttributes, false);
}
OutputIdentifier(e.Name);
if (e.InitExpression != null)
{
Output.Write(" = ");
GenerateExpression(e.InitExpression);
}
Output.WriteLine();
}
else
{
if (e.CustomAttributes.Count > 0)
{
OutputAttributes(e.CustomAttributes, false);
}
OutputMemberAccessModifier(e.Attributes);
OutputVTableModifier(e.Attributes);
OutputFieldScopeModifier(e.Attributes);
if (GetUserData(e, "WithEvents", false))
{
Output.Write("WithEvents ");
}
OutputTypeNamePair(e.Type, e.Name);
if (e.InitExpression != null)
{
Output.Write(" = ");
GenerateExpression(e.InitExpression);
}
Output.WriteLine();
}
}
private static bool MethodIsOverloaded(CodeMemberMethod e, CodeTypeDeclaration c)
{
if ((e.Attributes & MemberAttributes.Overloaded) != 0)
{
return true;
}
foreach (var current in c.Members)
{
if (!(current is CodeMemberMethod))
continue;
CodeMemberMethod meth = (CodeMemberMethod)current;
if (!(current is CodeTypeConstructor) && !(current is CodeConstructor)
&& meth != e
&& meth.Name.Equals(e.Name, StringComparison.OrdinalIgnoreCase)
&& meth.PrivateImplementationType == null)
{
return true;
}
}
return false;
}
protected override void GenerateSnippetMember(CodeSnippetTypeMember e)
{
Output.Write(e.Text);
}
protected override void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c)
{
if (!(IsCurrentClass || IsCurrentStruct || IsCurrentInterface)) return;
if (e.CustomAttributes.Count > 0)
{
OutputAttributes(e.CustomAttributes, false);
}
// need to change the implements name before doing overloads resolution
//
string methodName = e.Name;
if (e.PrivateImplementationType != null)
{
string impl = GetBaseTypeOutput(e.PrivateImplementationType, preferBuiltInTypes: false);
impl = impl.Replace('.', '_');
e.Name = impl + "_" + e.Name;
}
if (!IsCurrentInterface)
{
if (e.PrivateImplementationType == null)
{
OutputMemberAccessModifier(e.Attributes);
if (MethodIsOverloaded(e, c))
Output.Write("Overloads ");
}
OutputVTableModifier(e.Attributes);
OutputMemberScopeModifier(e.Attributes);
}
else
{
// interface may still need "Shadows"
OutputVTableModifier(e.Attributes);
}
bool sub = false;
if (e.ReturnType.BaseType.Length == 0 || string.Equals(e.ReturnType.BaseType, typeof(void).FullName, StringComparison.OrdinalIgnoreCase))
{
sub = true;
}
if (sub)
{
Output.Write("Sub ");
}
else
{
Output.Write("Function ");
}
OutputIdentifier(e.Name);
OutputTypeParameters(e.TypeParameters);
Output.Write('(');
OutputParameters(e.Parameters);
Output.Write(')');
if (!sub)
{
Output.Write(" As ");
if (e.ReturnTypeCustomAttributes.Count > 0)
{
OutputAttributes(e.ReturnTypeCustomAttributes, true);
}
OutputType(e.ReturnType);
OutputArrayPostfix(e.ReturnType);
}
if (e.ImplementationTypes.Count > 0)
{
Output.Write(" Implements ");
bool first = true;
foreach (CodeTypeReference type in e.ImplementationTypes)
{
if (first)
{
first = false;
}
else
{
Output.Write(" , ");
}
OutputType(type);
Output.Write('.');
OutputIdentifier(methodName);
}
}
else if (e.PrivateImplementationType != null)
{
Output.Write(" Implements ");
OutputType(e.PrivateImplementationType);
Output.Write('.');
OutputIdentifier(methodName);
}
Output.WriteLine();
if (!IsCurrentInterface
&& (e.Attributes & MemberAttributes.ScopeMask) != MemberAttributes.Abstract)
{
Indent++;
GenerateVBStatements(e.Statements);
Indent--;
if (sub)
{
Output.WriteLine("End Sub");
}
else
{
Output.WriteLine("End Function");
}
}
// reset the name that possibly got changed with the implements clause
e.Name = methodName;
}
protected override void GenerateEntryPointMethod(CodeEntryPointMethod e, CodeTypeDeclaration c)
{
if (e.CustomAttributes.Count > 0)
{
OutputAttributes(e.CustomAttributes, false);
}
Output.WriteLine("Public Shared Sub Main()");
Indent++;
GenerateVBStatements(e.Statements);
Indent--;
Output.WriteLine("End Sub");
}
private static bool PropertyIsOverloaded(CodeMemberProperty e, CodeTypeDeclaration c)
{
if ((e.Attributes & MemberAttributes.Overloaded) != 0)
{
return true;
}
foreach (var current in c.Members)
{
if (!(current is CodeMemberProperty))
continue;
CodeMemberProperty prop = (CodeMemberProperty)current;
if (prop != e
&& prop.Name.Equals(e.Name, StringComparison.OrdinalIgnoreCase)
&& prop.PrivateImplementationType == null)
{
return true;
}
}
return false;
}
protected override void GenerateProperty(CodeMemberProperty e, CodeTypeDeclaration c)
{
if (!(IsCurrentClass || IsCurrentStruct || IsCurrentInterface)) return;
if (e.CustomAttributes.Count > 0)
{
OutputAttributes(e.CustomAttributes, false);
}
string propName = e.Name;
if (e.PrivateImplementationType != null)
{
string impl = GetBaseTypeOutput(e.PrivateImplementationType, preferBuiltInTypes: false);
impl = impl.Replace('.', '_');
e.Name = impl + "_" + e.Name;
}
if (!IsCurrentInterface)
{
if (e.PrivateImplementationType == null)
{
OutputMemberAccessModifier(e.Attributes);
if (PropertyIsOverloaded(e, c))
{
Output.Write("Overloads ");
}
}
OutputVTableModifier(e.Attributes);
OutputMemberScopeModifier(e.Attributes);
}
else
{
// interface may still need "Shadows"
OutputVTableModifier(e.Attributes);
}
if (e.Parameters.Count > 0 && string.Equals(e.Name, "Item", StringComparison.OrdinalIgnoreCase))
{
Output.Write("Default ");
}
if (e.HasGet)
{
if (!e.HasSet)
{
Output.Write("ReadOnly ");
}
}
else if (e.HasSet)
{
Output.Write("WriteOnly ");
}
Output.Write("Property ");
OutputIdentifier(e.Name);
Output.Write('(');
if (e.Parameters.Count > 0)
{
OutputParameters(e.Parameters);
}
Output.Write(')');
Output.Write(" As ");
OutputType(e.Type);
OutputArrayPostfix(e.Type);
if (e.ImplementationTypes.Count > 0)
{
Output.Write(" Implements ");
bool first = true;
foreach (CodeTypeReference type in e.ImplementationTypes)
{
if (first)
{
first = false;
}
else
{
Output.Write(" , ");
}
OutputType(type);
Output.Write('.');
OutputIdentifier(propName);
}
}
else if (e.PrivateImplementationType != null)
{
Output.Write(" Implements ");
OutputType(e.PrivateImplementationType);
Output.Write('.');
OutputIdentifier(propName);
}
Output.WriteLine();
if (!c.IsInterface && (e.Attributes & MemberAttributes.ScopeMask) != MemberAttributes.Abstract)
{
Indent++;
if (e.HasGet)
{
Output.WriteLine("Get");
if (!IsCurrentInterface)
{
Indent++;
GenerateVBStatements(e.GetStatements);
e.Name = propName;
Indent--;
Output.WriteLine("End Get");
}
}
if (e.HasSet)
{
Output.WriteLine("Set");
if (!IsCurrentInterface)
{
Indent++;
GenerateVBStatements(e.SetStatements);
Indent--;
Output.WriteLine("End Set");
}
}
Indent--;
Output.WriteLine("End Property");
}
e.Name = propName;
}
protected override void GeneratePropertyReferenceExpression(CodePropertyReferenceExpression e)
{
if (e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write('.');
Output.Write(e.PropertyName);
}
else
{
OutputIdentifier(e.PropertyName);
}
}
protected override void GenerateConstructor(CodeConstructor e, CodeTypeDeclaration c)
{
if (!(IsCurrentClass || IsCurrentStruct)) return;
if (e.CustomAttributes.Count > 0)
{
OutputAttributes(e.CustomAttributes, false);
}
OutputMemberAccessModifier(e.Attributes);
Output.Write("Sub New(");
OutputParameters(e.Parameters);
Output.WriteLine(')');
Indent++;
CodeExpressionCollection baseArgs = e.BaseConstructorArgs;
CodeExpressionCollection thisArgs = e.ChainedConstructorArgs;
if (thisArgs.Count > 0)
{
Output.Write("Me.New(");
OutputExpressionList(thisArgs);
Output.Write(')');
Output.WriteLine();
}
else if (baseArgs.Count > 0)
{
Output.Write("MyBase.New(");
OutputExpressionList(baseArgs);
Output.Write(')');
Output.WriteLine();
}
else if (IsCurrentClass)
{
// struct doesn't have MyBase
Output.WriteLine("MyBase.New");
}
GenerateVBStatements(e.Statements);
Indent--;
Output.WriteLine("End Sub");
}
protected override void GenerateTypeConstructor(CodeTypeConstructor e)
{
if (!(IsCurrentClass || IsCurrentStruct)) return;
if (e.CustomAttributes.Count > 0)
{
OutputAttributes(e.CustomAttributes, false);
}
Output.WriteLine("Shared Sub New()");
Indent++;
GenerateVBStatements(e.Statements);
Indent--;
Output.WriteLine("End Sub");
}
protected override void GenerateTypeOfExpression(CodeTypeOfExpression e)
{
Output.Write("GetType(");
Output.Write(GetTypeOutput(e.Type));
Output.Write(')');
}
protected override void GenerateTypeStart(CodeTypeDeclaration e)
{
if (IsCurrentDelegate)
{
if (e.CustomAttributes.Count > 0)
{
OutputAttributes(e.CustomAttributes, false);
}
switch (e.TypeAttributes & TypeAttributes.VisibilityMask)
{
case TypeAttributes.Public:
Output.Write("Public ");
break;
case TypeAttributes.NotPublic:
default:
break;
}
CodeTypeDelegate del = (CodeTypeDelegate)e;
if (del.ReturnType.BaseType.Length > 0 && !string.Equals(del.ReturnType.BaseType, "System.Void", StringComparison.OrdinalIgnoreCase))
Output.Write("Delegate Function ");
else
Output.Write("Delegate Sub ");
OutputIdentifier(e.Name);
Output.Write('(');
OutputParameters(del.Parameters);
Output.Write(')');
if (del.ReturnType.BaseType.Length > 0 && !string.Equals(del.ReturnType.BaseType, "System.Void", StringComparison.OrdinalIgnoreCase))
{
Output.Write(" As ");
OutputType(del.ReturnType);
OutputArrayPostfix(del.ReturnType);
}
Output.WriteLine();
}
else if (e.IsEnum)
{
if (e.CustomAttributes.Count > 0)
{
OutputAttributes(e.CustomAttributes, false);
}
OutputTypeAttributes(e);
OutputIdentifier(e.Name);
if (e.BaseTypes.Count > 0)
{
Output.Write(" As ");
OutputType(e.BaseTypes[0]);
}
Output.WriteLine();
Indent++;
}
else
{
if (e.CustomAttributes.Count > 0)
{
OutputAttributes(e.CustomAttributes, false);
}
OutputTypeAttributes(e);
OutputIdentifier(e.Name);
OutputTypeParameters(e.TypeParameters);
bool writtenInherits = false;
bool writtenImplements = false;
// For a structure we can't have an inherits clause
if (e.IsStruct)
{
writtenInherits = true;
}
// For an interface we can't have an implements clause
if (e.IsInterface)
{
writtenImplements = true;
}
Indent++;
foreach (CodeTypeReference typeRef in e.BaseTypes)
{
// if we're generating an interface, we always want to use Inherits because interfaces can't Implement anything.
if (!writtenInherits && (e.IsInterface || !typeRef.IsInterface))
{
Output.WriteLine();
Output.Write("Inherits ");
writtenInherits = true;
}
else if (!writtenImplements)
{
Output.WriteLine();
Output.Write("Implements ");
writtenImplements = true;
}
else
{
Output.Write(", ");
}
OutputType(typeRef);
}
Output.WriteLine();
}
}
private void OutputTypeParameters(CodeTypeParameterCollection typeParameters)
{
if (typeParameters.Count == 0)
{
return;
}
Output.Write("(Of ");
bool first = true;
for (int i = 0; i < typeParameters.Count; i++)
{
if (first)
{
first = false;
}
else
{
Output.Write(", ");
}
Output.Write(typeParameters[i].Name);
OutputTypeParameterConstraints(typeParameters[i]);
}
Output.Write(')');
}
// In VB, constraints are put right after the type parameter name.
// In C#, there is a separate "where" statement
private void OutputTypeParameterConstraints(CodeTypeParameter typeParameter)
{
CodeTypeReferenceCollection constraints = typeParameter.Constraints;
int constraintCount = constraints.Count;
if (typeParameter.HasConstructorConstraint)
{
constraintCount++;
}
if (constraintCount == 0)
{
return;
}
// generating something like: "ValType As {IComparable, Customer, New}"
Output.Write(" As ");
if (constraintCount > 1)
{
Output.Write(" {");
}
bool first = true;
foreach (CodeTypeReference typeRef in constraints)
{
if (first)
{
first = false;
}
else
{
Output.Write(", ");
}
Output.Write(GetTypeOutput(typeRef));
}
if (typeParameter.HasConstructorConstraint)
{
if (!first)
{
Output.Write(", ");
}
Output.Write("New");
}
if (constraintCount > 1)
{
Output.Write('}');
}
}
protected override void GenerateTypeEnd(CodeTypeDeclaration e)
{
if (!IsCurrentDelegate)
{
Indent--;
string ending;
if (e.IsEnum)
{
ending = "End Enum";
}
else if (e.IsInterface)
{
ending = "End Interface";
}
else if (e.IsStruct)
{
ending = "End Structure";
}
else
{
if (IsCurrentModule)
{
ending = "End Module";
}
else
{
ending = "End Class";
}
}
Output.WriteLine(ending);
}
}
protected override void GenerateNamespace(CodeNamespace e)
{
if (GetUserData(e, "GenerateImports", true))
{
GenerateNamespaceImports(e);
}
Output.WriteLine();
GenerateCommentStatements(e.Comments);
GenerateNamespaceStart(e);
GenerateTypes(e);
GenerateNamespaceEnd(e);
}
private static bool AllowLateBound(CodeCompileUnit e)
{
object o = e.UserData["AllowLateBound"];
if (o != null && o is bool)
{
return (bool)o;
}
// We have Option Strict Off by default because it can fail on simple things like dividing
// two integers.
return true;
}
private static bool RequireVariableDeclaration(CodeCompileUnit e)
{
object o = e.UserData["RequireVariableDeclaration"];
if (o != null && o is bool)
{
return (bool)o;
}
return true;
}
private static bool GetUserData(CodeObject e, string property, bool defaultValue)
{
object o = e.UserData[property];
if (o != null && o is bool)
{
return (bool)o;
}
return defaultValue;
}
protected override void GenerateCompileUnitStart(CodeCompileUnit e)
{
base.GenerateCompileUnitStart(e);
Output.WriteLine("'------------------------------------------------------------------------------");
Output.Write("' <");
Output.WriteLine(SR.AutoGen_Comment_Line1);
Output.Write("' ");
Output.WriteLine(SR.AutoGen_Comment_Line2);
Output.WriteLine("'");
Output.Write("' ");
Output.WriteLine(SR.AutoGen_Comment_Line4);
Output.Write("' ");
Output.WriteLine(SR.AutoGen_Comment_Line5);
Output.Write("' </");
Output.WriteLine(SR.AutoGen_Comment_Line1);
Output.WriteLine("'------------------------------------------------------------------------------");
Output.WriteLine();
if (AllowLateBound(e))
Output.WriteLine("Option Strict Off");
else
Output.WriteLine("Option Strict On");
if (!RequireVariableDeclaration(e))
Output.WriteLine("Option Explicit Off");
else
Output.WriteLine("Option Explicit On");
Output.WriteLine();
}
protected override void GenerateCompileUnit(CodeCompileUnit e)
{
GenerateCompileUnitStart(e);
// Visual Basic needs all the imports together at the top of the compile unit.
// If generating multiple namespaces, gather all the imports together
var importList = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (CodeNamespace nspace in e.Namespaces)
{
// mark the namespace to stop it generating its own import list
nspace.UserData["GenerateImports"] = false;
// Collect the unique list of imports
foreach (CodeNamespaceImport import in nspace.Imports)
{
importList.Add(import.Namespace);
}
}
// now output the imports
foreach (string import in importList)
{
Output.Write("Imports ");
OutputIdentifier(import);
Output.WriteLine();
}
if (e.AssemblyCustomAttributes.Count > 0)
{
OutputAttributes(e.AssemblyCustomAttributes, false, "Assembly: ", true);
}
GenerateNamespaces(e);
GenerateCompileUnitEnd(e);
}
protected override void GenerateDirectives(CodeDirectiveCollection directives)
{
for (int i = 0; i < directives.Count; i++)
{
CodeDirective directive = directives[i];
if (directive is CodeChecksumPragma)
{
GenerateChecksumPragma((CodeChecksumPragma)directive);
}
else if (directive is CodeRegionDirective)
{
GenerateCodeRegionDirective((CodeRegionDirective)directive);
}
}
}
private void GenerateChecksumPragma(CodeChecksumPragma checksumPragma)
{
// the syntax is: #ExternalChecksum("FileName","GuidChecksum","ChecksumValue")
Output.Write("#ExternalChecksum(\"");
Output.Write(checksumPragma.FileName);
Output.Write("\",\"");
Output.Write(checksumPragma.ChecksumAlgorithmId.ToString("B", CultureInfo.InvariantCulture));
Output.Write("\",\"");
if (checksumPragma.ChecksumData != null)
{
foreach (byte b in checksumPragma.ChecksumData)
{
Output.Write(b.ToString("X2"));
}
}
Output.WriteLine("\")");
}
private void GenerateCodeRegionDirective(CodeRegionDirective regionDirective)
{
// VB does not support regions within statement blocks
if (IsGeneratingStatements())
{
return;
}
if (regionDirective.RegionMode == CodeRegionMode.Start)
{
Output.Write("#Region \"");
Output.Write(regionDirective.RegionText);
Output.WriteLine("\"");
}
else if (regionDirective.RegionMode == CodeRegionMode.End)
{
Output.WriteLine("#End Region");
}
}
protected override void GenerateNamespaceStart(CodeNamespace e)
{
if (!string.IsNullOrEmpty(e.Name))
{
Output.Write("Namespace ");
string[] names = e.Name.Split(s_periodArray);
Debug.Assert(names.Length > 0);
OutputIdentifier(names[0]);
for (int i = 1; i < names.Length; i++)
{
Output.Write('.');
OutputIdentifier(names[i]);
}
Output.WriteLine();
Indent++;
}
}
protected override void GenerateNamespaceEnd(CodeNamespace e)
{
if (!string.IsNullOrEmpty(e.Name))
{
Indent--;
Output.WriteLine("End Namespace");
}
}
protected override void GenerateNamespaceImport(CodeNamespaceImport e)
{
Output.Write("Imports ");
OutputIdentifier(e.Namespace);
Output.WriteLine();
}
protected override void GenerateAttributeDeclarationsStart(CodeAttributeDeclarationCollection attributes)
{
Output.Write('<');
}
protected override void GenerateAttributeDeclarationsEnd(CodeAttributeDeclarationCollection attributes)
{
Output.Write('>');
}
public static bool IsKeyword(string value)
{
return FixedStringLookup.Contains(s_keywords, value, true);
}
protected override bool Supports(GeneratorSupport support)
{
return ((support & LanguageSupport) == support);
}
protected override bool IsValidIdentifier(string value)
{
// identifiers must be 1 char or longer
//
if (string.IsNullOrEmpty(value))
{
return false;
}
if (value.Length > 1023)
return false;
// identifiers cannot be a keyword unless surrounded by []'s
//
if (value[0] != '[' || value[value.Length - 1] != ']')
{
if (IsKeyword(value))
{
return false;
}
}
else
{
value = value.Substring(1, value.Length - 2);
}
// just _ as an identifier is not valid.
if (value.Length == 1 && value[0] == '_')
return false;
return CodeGenerator.IsValidLanguageIndependentIdentifier(value);
}
protected override string CreateValidIdentifier(string name)
{
if (IsKeyword(name))
{
return "_" + name;
}
return name;
}
protected override string CreateEscapedIdentifier(string name)
{
if (IsKeyword(name))
{
return "[" + name + "]";
}
return name;
}
private string GetBaseTypeOutput(CodeTypeReference typeRef, bool preferBuiltInTypes = true)
{
string baseType = typeRef.BaseType;
if (preferBuiltInTypes)
{
if (baseType.Length == 0)
{
return "Void";
}
string lowerCaseString = baseType.ToLowerInvariant();
switch (lowerCaseString)
{
case "system.byte":
return "Byte";
case "system.sbyte":
return "SByte";
case "system.int16":
return "Short";
case "system.int32":
return "Integer";
case "system.int64":
return "Long";
case "system.uint16":
return "UShort";
case "system.uint32":
return "UInteger";
case "system.uint64":
return "ULong";
case "system.string":
return "String";
case "system.datetime":
return "Date";
case "system.decimal":
return "Decimal";
case "system.single":
return "Single";
case "system.double":
return "Double";
case "system.boolean":
return "Boolean";
case "system.char":
return "Char";
case "system.object":
return "Object";
}
}
var sb = new StringBuilder(baseType.Length + 10);
if ((typeRef.Options & CodeTypeReferenceOptions.GlobalReference) != 0)
{
sb.Append("Global.");
}
int lastIndex = 0;
int currentTypeArgStart = 0;
for (int i = 0; i < baseType.Length; i++)
{
switch (baseType[i])
{
case '+':
case '.':
sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
sb.Append('.');
i++;
lastIndex = i;
break;
case '`':
sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
i++; // skip the '
int numTypeArgs = 0;
while (i < baseType.Length && baseType[i] >= '0' && baseType[i] <= '9')
{
numTypeArgs = numTypeArgs * 10 + (baseType[i] - '0');
i++;
}
GetTypeArgumentsOutput(typeRef.TypeArguments, currentTypeArgStart, numTypeArgs, sb);
currentTypeArgStart += numTypeArgs;
// Arity can be in the middle of a nested type name, so we might have a . or + after it.
// Skip it if so.
if (i < baseType.Length && (baseType[i] == '+' || baseType[i] == '.'))
{
sb.Append('.');
i++;
}
lastIndex = i;
break;
}
}
if (lastIndex < baseType.Length)
{
sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex)));
}
return sb.ToString();
}
private string GetTypeOutputWithoutArrayPostFix(CodeTypeReference typeRef)
{
while (typeRef.ArrayElementType != null)
{
typeRef = typeRef.ArrayElementType;
}
return GetBaseTypeOutput(typeRef);
}
private string GetTypeArgumentsOutput(CodeTypeReferenceCollection typeArguments)
{
StringBuilder sb = new StringBuilder(128);
GetTypeArgumentsOutput(typeArguments, 0, typeArguments.Count, sb);
return sb.ToString();
}
private void GetTypeArgumentsOutput(CodeTypeReferenceCollection typeArguments, int start, int length, StringBuilder sb)
{
sb.Append("(Of ");
bool first = true;
for (int i = start; i < start + length; i++)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
// it's possible that we call GetTypeArgumentsOutput with an empty typeArguments collection. This is the case
// for open types, so we want to just output the brackets and commas.
if (i < typeArguments.Count)
sb.Append(GetTypeOutput(typeArguments[i]));
}
sb.Append(')');
}
protected override string GetTypeOutput(CodeTypeReference typeRef)
{
string s = string.Empty;
s += GetTypeOutputWithoutArrayPostFix(typeRef);
if (typeRef.ArrayRank > 0)
{
s += GetArrayPostfix(typeRef);
}
return s;
}
protected override void ContinueOnNewLine(string st)
{
Output.Write(st);
Output.WriteLine(" _");
}
private bool IsGeneratingStatements()
{
Debug.Assert(_statementDepth >= 0, "statementDepth >= 0");
return (_statementDepth > 0);
}
private void GenerateVBStatements(CodeStatementCollection stms)
{
_statementDepth++;
try
{
GenerateStatements(stms);
}
finally
{
_statementDepth--;
}
}
}
}
| 412 | 0.929665 | 1 | 0.929665 | game-dev | MEDIA | 0.297184 | game-dev | 0.876474 | 1 | 0.876474 |
ryzom/ryzomcore | 1,528 | nel/tools/3d/plugin_max/nel_patch_paint/paint_tileset.cpp | #include "stdafx.h"
#include "nel_patch_paint.h"
#include "paint_tileset.h"
/*-------------------------------------------------------------------*/
// Set current sub selection of tileSet
void CTileSetSelection::setSelection (int selection, CTileBank& bank)
{
// Reset the array
_TileSetArray.resize (0);
// Get the land selected
CTileLand* pTileLand=NULL;
if ((selection>=0)&&(selection<bank.getLandCount ()))
pTileLand=bank.getLand (selection);
// For each tileSet in the bank
for (int t=0; t<bank.getTileSetCount (); t++)
{
// Get the tile set
CTileSet *pTileSet=bank.getTileSet (t);
nlassert (pTileSet);
// Is this tileSet in the land ?
if (pTileLand)
{
if (pTileLand->isTileSet (pTileSet->getName()))
// Add this tileset
_TileSetArray.push_back (t);
}
else
// By default, insert it
_TileSetArray.push_back (t);
}
}
/*-------------------------------------------------------------------*/
// Get tileSet by id
int CTileSetSelection::getTileSet (int id)
{
// If in the array ?
if ((id>=0)&&(id<(sint)_TileSetArray.size()))
return _TileSetArray[id];
// No, return -1 as not found
else
return -1;
}
/*-------------------------------------------------------------------*/
// Get tileSet by id. Return -1 if the tileset asked for doesn't exist.
bool CTileSetSelection::isInArray (int id)
{
// Number of tileset
uint count=getTileCount ();
// Search this in the array
for (uint t=0; t<count; t++)
{
if (_TileSetArray[t]==id)
return true;
}
return false;
}
| 412 | 0.740853 | 1 | 0.740853 | game-dev | MEDIA | 0.685818 | game-dev | 0.885002 | 1 | 0.885002 |
LiteLDev/LeviLamina | 1,098 | src-server/mc/world/level/levelgen/structure/JunglePyramidPiece.h | #pragma once
#include "mc/_HeaderOutputPredefine.h"
// auto generated inclusion list
#include "mc/world/level/levelgen/structure/ScatteredFeaturePiece.h"
#include "mc/world/level/levelgen/structure/StructurePieceType.h"
// auto generated forward declare list
// clang-format off
class BlockSource;
class BoundingBox;
class Random;
// clang-format on
class JunglePyramidPiece : public ::ScatteredFeaturePiece {
public:
// virtual functions
// NOLINTBEGIN
// vIndex: 4
virtual bool postProcess(::BlockSource& region, ::Random& random, ::BoundingBox const& chunkBB) /*override*/;
// vIndex: 2
virtual ::StructurePieceType getType() const /*override*/;
// vIndex: 0
virtual ~JunglePyramidPiece() /*override*/ = default;
// NOLINTEND
public:
// virtual function thunks
// NOLINTBEGIN
MCAPI bool $postProcess(::BlockSource& region, ::Random& random, ::BoundingBox const& chunkBB);
MCAPI ::StructurePieceType $getType() const;
// NOLINTEND
public:
// vftables
// NOLINTBEGIN
MCNAPI static void** $vftable();
// NOLINTEND
};
| 412 | 0.940026 | 1 | 0.940026 | game-dev | MEDIA | 0.576207 | game-dev | 0.711399 | 1 | 0.711399 |
opensim-org/opensim-core | 20,917 | OpenSim/Simulation/Test/testForceProducer.cpp | /* -------------------------------------------------------------------------- *
* OpenSim: testForceProducer.h *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2024 Stanford University and the Authors *
* Author(s): Adam Kewley *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
#include <OpenSim/Simulation/Model/ForceProducer.h>
#include <catch2/catch_all.hpp>
#include <OpenSim/Simulation/SimbodyEngine/Body.h>
#include <OpenSim/Simulation/SimbodyEngine/Coordinate.h>
#include <OpenSim/Simulation/SimbodyEngine/FreeJoint.h>
#include <OpenSim/Simulation/Model/ForceAdapter.h>
#include <OpenSim/Simulation/Model/ForceConsumer.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/Model/PhysicalFrame.h>
#include <algorithm>
#include <cstddef>
using namespace OpenSim;
namespace
{
// A trivial example of a `ForceProducer` for the purposes of testing.
class ExampleForceProducer final : public ForceProducer {
OpenSim_DECLARE_CONCRETE_OBJECT(ExampleForceProducer, ForceProducer);
public:
ExampleForceProducer() = default;
ExampleForceProducer(
size_t numGeneralizedForcesToProduce,
size_t numBodySpatialVectorsToProduce,
size_t numPointForcesToProduce) :
_numGeneralizedForcesToProduce{numGeneralizedForcesToProduce},
_numBodySpatialVectorsToProduce{numBodySpatialVectorsToProduce},
_numPointForcesToProduce{numPointForcesToProduce}
{}
private:
void implProduceForces(
const SimTK::State& state,
ForceConsumer& consumer) const final
{
for (size_t i = 0; i < _numGeneralizedForcesToProduce; ++i) {
consumer.consumeGeneralizedForce(state, _dummyCoordinate, static_cast<double>(i));
}
for (size_t i = 0; i < _numBodySpatialVectorsToProduce; ++i) {
const SimTK::Vec3 torque{static_cast<double>(i)};
const SimTK::Vec3 force{static_cast<double>(i)};
consumer.consumeBodySpatialVec(state, _dummyBody, SimTK::SpatialVec{torque, force});
}
for (size_t i = 0; i < _numPointForcesToProduce; ++i) {
const SimTK::Vec3 point{static_cast<double>(i)};
const SimTK::Vec3 force{static_cast<double>(i)};
consumer.consumePointForce(state, _dummyBody, point, force);
}
}
OpenSim::Coordinate _dummyCoordinate;
OpenSim::Body _dummyBody;
size_t _numGeneralizedForcesToProduce = 0;
size_t _numBodySpatialVectorsToProduce = 0;
size_t _numPointForcesToProduce = 0;
};
// A trivial example of a `ForceConsumer` for the purposes of testing.
class ExampleForceConsumer final : public ForceConsumer {
public:
size_t getNumGeneralizedForcesConsumed() const { return _numGeneralizedForcesConsumed; }
size_t getNumBodySpatialVectorsConsumed() const { return _numBodySpatialVectorsConsumed; }
size_t getNumPointForcesConsumed() const { return _numPointForcesConsumed; }
private:
void implConsumeGeneralizedForce(const SimTK::State&, const Coordinate&, double) final
{
++_numGeneralizedForcesConsumed;
}
void implConsumeBodySpatialVec(const SimTK::State&, const PhysicalFrame&, const SimTK::SpatialVec&) final
{
++_numBodySpatialVectorsConsumed;
}
void implConsumePointForce(const SimTK::State&, const PhysicalFrame&, const SimTK::Vec3&, const SimTK::Vec3&) final
{
++_numPointForcesConsumed;
}
size_t _numGeneralizedForcesConsumed = 0;
size_t _numBodySpatialVectorsConsumed = 0;
size_t _numPointForcesConsumed = 0;
};
// A trivial implementation of a `ForceProducer` that can be added to a `Model`
// for the purposes of comparing side-effects to the `Force` API (see `MockForce`
// below).
class MockForceProducer final : public ForceProducer {
OpenSim_DECLARE_CONCRETE_OBJECT(MockForceProducer, ForceProducer);
public:
OpenSim_DECLARE_SOCKET(force_target, OpenSim::PhysicalFrame, "the physical frame that forces should be produced for");
OpenSim_DECLARE_SOCKET(generalized_force_target, OpenSim::Coordinate, "the coordinate that generalized forces should be produced for");
explicit MockForceProducer(
const OpenSim::PhysicalFrame& forceTarget,
const OpenSim::Coordinate& generalizedForceTarget)
{
connectSocket_force_target(forceTarget);
connectSocket_generalized_force_target(generalizedForceTarget);
}
private:
void implProduceForces(const SimTK::State& state, ForceConsumer& consumer) const final
{
// Note: this should be logically equivalent to `MockForce::computeForce` (below), so
// that the `ForceProducer`'s default `computeForce` implementations can be compared
// in an end-to-end way.
consumer.consumeBodySpatialVec(
state,
getConnectee<OpenSim::PhysicalFrame>("force_target"),
SimTK::SpatialVec{SimTK::Vec3{1.0}, SimTK::Vec3{2.0}}
);
consumer.consumeBodySpatialVec(
state,
getConnectee<OpenSim::PhysicalFrame>("force_target"),
SimTK::SpatialVec{SimTK::Vec3{-0.5}, SimTK::Vec3{-0.25}}
);
consumer.consumeTorque(
state,
getConnectee<OpenSim::PhysicalFrame>("force_target"),
SimTK::Vec3{0.1, 0.25, 0.5}
);
consumer.consumeGeneralizedForce(
state,
getConnectee<OpenSim::Coordinate>("generalized_force_target"),
2.0
);
consumer.consumePointForce(
state,
getConnectee<OpenSim::PhysicalFrame>("force_target"),
SimTK::Vec3{1.0, 2.0, 3.0},
SimTK::Vec3{-1.0, -3.0, -9.0}
);
}
};
// A trivial implementation of a `Force` that can be added to a `Model`
// for the purposes of comparing side-effects to the `ForceProducer` API
// (see `MockForceProducer` above).
class MockForce final : public Force {
OpenSim_DECLARE_CONCRETE_OBJECT(MockForce, Force);
public:
OpenSim_DECLARE_SOCKET(force_target, OpenSim::PhysicalFrame, "the physical frame that forces should be produced for");
OpenSim_DECLARE_SOCKET(generalized_force_target, OpenSim::Coordinate, "the coordinate that generalized forces should be produced for");
explicit MockForce(
const OpenSim::PhysicalFrame& forceTarget,
const OpenSim::Coordinate& generalizedForceTarget)
{
connectSocket_force_target(forceTarget);
connectSocket_generalized_force_target(generalizedForceTarget);
}
void computeForce(
const SimTK::State& state,
SimTK::Vector_<SimTK::SpatialVec>& bodyForces,
SimTK::Vector& generalizedForces) const override
{
// Note: this should be logically equivalent to `MockForceProducer::implProduceForces`
// (above), so that the `ForceProducer`'s default `computeForce` implementations can
// be compared in an end-to-end way.
// (this is usually how legacy `Force` code adds `SimTK::SpatialVec`s to the body forces)
bodyForces[getConnectee<OpenSim::PhysicalFrame>("force_target").getMobilizedBodyIndex()] +=
SimTK::SpatialVec{SimTK::Vec3{1.0}, SimTK::Vec3{2.0}};
bodyForces[getConnectee<OpenSim::PhysicalFrame>("force_target").getMobilizedBodyIndex()] +=
SimTK::SpatialVec{SimTK::Vec3{-0.5}, SimTK::Vec3{-0.25}};
applyTorque(
state,
getConnectee<OpenSim::PhysicalFrame>("force_target"),
SimTK::Vec3{0.1, 0.25, 0.5},
bodyForces
);
applyGeneralizedForce(
state,
getConnectee<OpenSim::Coordinate>("generalized_force_target"),
2.0,
generalizedForces
);
applyForceToPoint(
state,
getConnectee<OpenSim::PhysicalFrame>("force_target"),
SimTK::Vec3{1.0, 2.0, 3.0},
SimTK::Vec3{-1.0, -3.0, -9.0},
bodyForces
);
}
};
// Returns true if the contents of `a` and `b` are equal, that is, they have the same
// number of elements, and each element in `a` compares equal with the element in `b`
// at the same position.
template<typename T>
bool equals(const SimTK::Vector_<T>& a, const SimTK::Vector_<T>& b)
{
if (a.size() != b.size()) {
return false;
}
for (int i = 0; i < a.size(); ++i) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
// Represents the vectors of forces the simbody physics engine lets downstream
// code (e.g. `OpenSim::Force`s) manipulate
//
// They're bundled together in this struct for ease of use, initialization, and comparison.
struct SimbodyEngineForceVectors {
// Constructs a zero-initialized set of vectors.
explicit SimbodyEngineForceVectors(const SimTK::SimbodyMatterSubsystem& matter) :
bodyForces{matter.getNumBodies(), SimTK::SpatialVec{SimTK::Vec3{0.0}, SimTK::Vec3{0.0}}},
particleForces{matter.getNumParticles(), SimTK::Vec3{0.0}},
mobilityForces{matter.getNumMobilities(), double{}}
{}
friend bool operator==(const SimbodyEngineForceVectors& lhs, const SimbodyEngineForceVectors& rhs)
{
return
equals(lhs.bodyForces, rhs.bodyForces) &&
equals(lhs.particleForces, rhs.particleForces) &&
equals(lhs.mobilityForces, rhs.mobilityForces);
}
friend bool operator!=(const SimbodyEngineForceVectors& lhs, const SimbodyEngineForceVectors& rhs)
{
return !(lhs == rhs);
}
SimTK::Vector_<SimTK::SpatialVec> bodyForces;
SimTK::Vector_<SimTK::Vec3> particleForces; // unused by OpenSim
SimTK::Vector mobilityForces;
};
}
TEST_CASE("ForceProducer (ExampleForceProducer)")
{
SECTION("Can Default Construct `ExampleForceProducer`")
{
// This test is mostly just ensuring that the example components for
// the test suite behave correctly. That is, inheriting from the
// `ForceProducer` API should work in trivial cases
const ExampleForceProducer example;
}
SECTION("Passing `ExampleForceConsumer` to default-constructed `ExampleForceProducer` produces no forces")
{
// This test is checking that the API lets calling code pass an example
// consumer into an example producer. It's ensuring that the concrete
// public API talks to the relevant virtual APIs in this trivial (0-force)
// case.
const ExampleForceProducer producer;
ExampleForceConsumer consumer;
const SimTK::State state; // untouched by example classes
producer.produceForces(state, consumer);
REQUIRE(consumer.getNumGeneralizedForcesConsumed() == 0);
REQUIRE(consumer.getNumBodySpatialVectorsConsumed() == 0);
REQUIRE(consumer.getNumPointForcesConsumed() == 0);
}
SECTION("Passing Non-Zero Number of Generalized Forces to `ExampleForceProducer` makes it produce stubbed generalized forces into the `ExampleForceConsumer`")
{
// This test is checking that a generalized force produced by an (example)
// `ForceProducer` will correctly worm its way into an (example) `ForceConsumer`
const size_t numGeneralizedForcesToProduce = 7;
const ExampleForceProducer producer{numGeneralizedForcesToProduce, 0, 0};
ExampleForceConsumer consumer;
const SimTK::State state; // untouched by example classes
producer.produceForces(state, consumer);
REQUIRE(consumer.getNumGeneralizedForcesConsumed() == numGeneralizedForcesToProduce);
REQUIRE(consumer.getNumBodySpatialVectorsConsumed() == 0);
REQUIRE(consumer.getNumPointForcesConsumed() == 0);
}
SECTION("Passing Non-Zero Number of Body Spatial Vectors to `ExampleForceProducer` makes it produce stubbed spatial vectors into the `ExampleForceConsumer`")
{
// This test is checking that a body spatial vector produced by an (example)
// `ForceProducer` will correctly worm its way into an example `ForceConsumer`
const size_t numBodySpatialVectorsToProduce = 9;
const ExampleForceProducer producer{0, numBodySpatialVectorsToProduce, 0};
ExampleForceConsumer consumer;
const SimTK::State state; // untouched by example classes
producer.produceForces(state, consumer);
REQUIRE(consumer.getNumGeneralizedForcesConsumed() == 0);
REQUIRE(consumer.getNumBodySpatialVectorsConsumed() == numBodySpatialVectorsToProduce);
REQUIRE(consumer.getNumPointForcesConsumed() == 0);
}
SECTION("Passing Non-Zero Number of Point Force Vectors to `ExampleForceProducer` makes it produce stubbed point forces into the `ExampleForceConsumer`")
{
// This test is checking that a body spatial vector produced by an (example)
// `ForceProducer` will correctly worm its way into an example `ForceConsumer`
const size_t numPointForcesToProduce = 11;
const ExampleForceProducer producer{0, 0, numPointForcesToProduce};
ExampleForceConsumer consumer;
const SimTK::State state; // untouched by example classes
producer.produceForces(state, consumer);
REQUIRE(consumer.getNumGeneralizedForcesConsumed() == 0);
REQUIRE(consumer.getNumBodySpatialVectorsConsumed() == 0);
REQUIRE(consumer.getNumPointForcesConsumed() == numPointForcesToProduce);
}
SECTION("Setting `produceForces` to `false` Causes `ExampleForceProducer` to Still Produce Forces")
{
// This test is checking that `appliesForce`, which `ForceProducer` inherits from the
// `Force` base class, is ignored by the `ForceProducer` API. The wording,
// "APPLIES force" implies that the flag should only be checked during force
// application, not production.
ExampleForceProducer producer{1, 2, 3}; // produce nonzero number of forces
producer.set_appliesForce(false); // from `OpenSim::Force`
producer.finalizeFromProperties();
ExampleForceConsumer consumer;
const SimTK::State state; // untouched by example classes
producer.produceForces(state, consumer);
REQUIRE(consumer.getNumGeneralizedForcesConsumed() == 1);
REQUIRE(consumer.getNumBodySpatialVectorsConsumed() == 2);
REQUIRE(consumer.getNumPointForcesConsumed() == 3);
}
SECTION("The `ForceProducer` class's default `computeForce` Implementation Works as Expected")
{
// The `ForceProducer` base class provides a default implementation of `Force::computeForce`,
// which should behave identically to it in the case where the downstream code uses the
// `ForceConsumer` API "identially" (logically speaking) to the `Force` API.
//
// For example, when a concrete implementation calls `ForceConsumer::consumePointForce` in
// its `implProduceForces` implementation during a call to `ForceProducer::computeForce`,
// that should have identical side-effects as when a concrete implementation calls
// `Force::applyForceToPoint` during a call to `Force::computeForce` (assuming the
// same arguments, conditions, etc.).
//
// I.e. "The `ForceProducer::computeForce` API should behave logically identically to the
// `Force::computeForce` API. It's just that the `ForceProducer` API allows for
// switching consumers' behavior.
// step 1) build a model with "equivalent" `ForceProducer` and `Force` implementations
Model model;
auto* body = new Body{"body", 1.0, SimTK::Vec3{0.0}, SimTK::Inertia{1.0}};
auto* joint = new FreeJoint{"joint", model.getGround(), *body};
auto* force = new MockForce{*body, joint->get_coordinates(0)};
auto* forceProducer = new MockForceProducer{*body, joint->get_coordinates(0)};
model.addBody(body);
model.addJoint(joint);
model.addForce(force);
model.addForce(forceProducer);
model.buildSystem();
model.initializeState();
// step 2) create zero-initialized force vectors "as if" pretending to be the physics engine
SimbodyEngineForceVectors blankForceVectors{model.getMatterSubsystem()};
SimbodyEngineForceVectors forceVectors{model.getMatterSubsystem()};
SimbodyEngineForceVectors forceProducerVectors{model.getMatterSubsystem()};
// step 3a) pump one set of the vectors through the `Force` implementation
{
ForceAdapter adapter{*force};
adapter.calcForce(model.getWorkingState(), forceVectors.bodyForces, forceVectors.particleForces, forceVectors.mobilityForces);
}
// step 3b) pump the other set of vectors through the `ForceProducer` implementation
{
ForceAdapter adapter{*forceProducer};
adapter.calcForce(model.getWorkingState(), forceProducerVectors.bodyForces, forceProducerVectors.particleForces, forceProducerVectors.mobilityForces);
}
// step 4) compare the vector sets, which should be equal if `ForceProducer` behaves the same
// as `Force` for typical use-cases
REQUIRE((forceVectors != blankForceVectors && forceVectors == forceProducerVectors));
}
SECTION("Setting `appliesForces` to `false` Causes `ForceProducer::computeForce` to Not Apply Forces")
{
// The base `OpenSim::Force` class has an `appliesForces` flag, which `ForceProducer`
// should check when it wants to APPLY forces to the multibody system (i.e. during
// `ForceProducer::computeForce` override to satisfy the `OpenSim::Force` API)
Model model;
auto* body = new Body{"body", 1.0, SimTK::Vec3{0.0}, SimTK::Inertia{1.0}};
auto* joint = new FreeJoint{"joint", model.getGround(), *body};
auto* forceProducer = new MockForceProducer{*body, joint->get_coordinates(0)};
forceProducer->set_appliesForce(false); // should disable force application
model.addBody(body);
model.addJoint(joint);
model.addForce(forceProducer);
model.buildSystem();
model.initializeState();
SimbodyEngineForceVectors blankForceVectors{model.getMatterSubsystem()};
SimbodyEngineForceVectors forceProducerVectors{model.getMatterSubsystem()};
ForceAdapter adapter{*forceProducer};
adapter.calcForce(model.getWorkingState(), forceProducerVectors.bodyForces, forceProducerVectors.particleForces, forceProducerVectors.mobilityForces);
REQUIRE(forceProducerVectors == blankForceVectors);
}
}
| 412 | 0.69467 | 1 | 0.69467 | game-dev | MEDIA | 0.943726 | game-dev | 0.73958 | 1 | 0.73958 |
goblinhack/zorbash | 1,144 | src/thing_block_of_crystal.cpp | //
// Copyright goblinhack@gmail.com
//
#include "my_array_bounds_check.hpp"
#include "my_game.hpp"
#include "my_thing.hpp"
uint8_t Level::is_block_of_crystal(const point p)
{
TRACE_NO_INDENT();
if (unlikely(is_oob(p.x, p.y))) {
return false;
}
return (get(_is_block_of_crystal, p.x, p.y));
}
uint8_t Level::is_block_of_crystal(const int x, const int y)
{
TRACE_NO_INDENT();
if (unlikely(is_oob(x, y))) {
return false;
}
return (get(_is_block_of_crystal, x, y));
}
void Level::is_block_of_crystal_set(const int x, const int y)
{
TRACE_NO_INDENT();
if (unlikely(is_oob(x, y))) {
return;
}
is_map_changed = true;
incr(_is_block_of_crystal, x, y, (uint8_t) 1);
}
void Level::is_block_of_crystal_unset(const int x, const int y)
{
TRACE_NO_INDENT();
if (unlikely(is_oob(x, y))) {
return;
}
is_map_changed = true;
decr(_is_block_of_crystal, x, y, (uint8_t) 1);
}
int Thing::is_block_of_crystal(void)
{
TRACE_NO_INDENT();
return (tp()->is_block_of_crystal());
}
int Thing::is_able_to_break_out_of_crystal(void)
{
TRACE_NO_INDENT();
return (tp()->is_able_to_break_out_of_crystal());
}
| 412 | 0.915819 | 1 | 0.915819 | game-dev | MEDIA | 0.191259 | game-dev | 0.919018 | 1 | 0.919018 |
MillenniumDB/MillenniumDB | 1,853 | src/query/parser/expr/mql/atom_expr/expr_var_property.h | #pragma once
#include "graph_models/object_id.h"
#include "query/parser/expr/mql/expr.h"
namespace MQL {
class ExprVarProperty : public Expr {
public:
VarId var_without_property; // ?x
ObjectId key;
VarId var_with_property; // ?x.key
ExprVarProperty(VarId var_without_property, ObjectId key, VarId var_with_property) :
var_without_property(var_without_property),
key(key),
var_with_property(var_with_property)
{ }
virtual std::unique_ptr<Expr> clone() const override
{
return std::make_unique<ExprVarProperty>(var_without_property, key, var_with_property);
}
void accept_visitor(ExprVisitor& visitor) override
{
visitor.visit(*this);
}
bool has_aggregation() const override
{
return false;
}
std::set<VarId> get_all_vars() const override
{
return { var_without_property, var_with_property };
}
std::set<VarId> get_input_vars() const override
{
return { var_without_property };
}
bool operator<(const ExprVarProperty& other) const
{
if (var_without_property < other.var_without_property) {
return true;
} else if (other.var_without_property < var_without_property) {
return false;
}
if (key < other.key) {
return true;
} else if (other.key < key) {
return false;
}
if (var_with_property < other.var_with_property) {
return true;
} else if (other.var_with_property < var_with_property) {
return false;
}
return false;
}
std::optional<VarId> get_var() const override
{
return var_with_property;
}
void print(std::ostream& os) const override
{
os << var_with_property;
}
};
} // namespace MQL
| 412 | 0.952986 | 1 | 0.952986 | game-dev | MEDIA | 0.275981 | game-dev | 0.855124 | 1 | 0.855124 |
Pathoschild/StardewMods | 2,767 | CropsAnytimeAnywhere/Framework/TillableRule.cs | using System.Collections.Generic;
using Newtonsoft.Json;
using StardewValley;
namespace Pathoschild.Stardew.CropsAnytimeAnywhere.Framework;
/// <summary>A rule which sets the tiles to force tillable if it matches.</summary>
internal class TillableRule : BaseRule
{
/*********
** Accessors
*********/
/// <summary>Whether to allow tilling dirt tiles not normally allowed by the game.</summary>
public bool Dirt { get; }
/// <summary>Whether to allow tilling grass tiles.</summary>
public bool Grass { get; }
/// <summary>Whether to allow tilling stone tiles.</summary>
public bool Stone { get; }
/// <summary>Whether to allow tilling other tile types (like paths, indoor floors, etc).</summary>
public bool Other { get; }
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="conditions">The rule whose conditions to copy.</param>
/// <param name="dirt"><inheritdoc cref="Dirt" path="/summary"/></param>
/// <param name="grass"><inheritdoc cref="Grass" path="/summary"/></param>
/// <param name="stone"><inheritdoc cref="Stone" path="/summary"/></param>
/// <param name="other"><inheritdoc cref="Other" path="/summary"/></param>
public TillableRule(BaseRule conditions, bool dirt, bool grass, bool stone, bool other)
: this(conditions.ForLocations, conditions.ForLocationContexts, conditions.ForSeasons, dirt, grass, stone, other) { }
/// <summary>Construct an instance.</summary>
/// <param name="forLocations"><inheritdoc cref="BaseRule.ForLocations" path="/summary"/></param>
/// <param name="forLocationContexts"><inheritdoc cref="BaseRule.ForLocationContexts" path="/summary"/></param>
/// <param name="forSeasons"><inheritdoc cref="BaseRule.ForSeasons" path="/summary"/></param>
/// <param name="dirt"><inheritdoc cref="Dirt" path="/summary"/></param>
/// <param name="grass"><inheritdoc cref="Grass" path="/summary"/></param>
/// <param name="stone"><inheritdoc cref="Stone" path="/summary"/></param>
/// <param name="other"><inheritdoc cref="Other" path="/summary"/></param>
[JsonConstructor]
public TillableRule(HashSet<string>? forLocations, HashSet<string>? forLocationContexts, HashSet<Season>? forSeasons, bool dirt, bool grass, bool stone, bool other)
: base(forLocations, forLocationContexts, forSeasons)
{
this.Dirt = dirt;
this.Grass = grass;
this.Stone = stone;
this.Other = other;
}
/// <summary>Whether any of the options are enabled.</summary>
public bool IsAnyEnabled()
{
return
this.Dirt
|| this.Grass
|| this.Stone
|| this.Other;
}
}
| 412 | 0.70126 | 1 | 0.70126 | game-dev | MEDIA | 0.660958 | game-dev,testing-qa | 0.636764 | 1 | 0.636764 |
FalsehoodMC/Fabrication | 1,981 | src/main/java/com/unascribed/fabrication/mixin/f_balance/lava_causes_fall_damage/MixinLivingEntity.java | package com.unascribed.fabrication.mixin.f_balance.lava_causes_fall_damage;
import com.unascribed.fabrication.FabConf;
import com.unascribed.fabrication.support.ConfigPredicates;
import com.unascribed.fabrication.support.EligibleIf;
import com.unascribed.fabrication.support.injection.FabModifyVariable;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.network.packet.s2c.play.EntityVelocityUpdateS2CPacket;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.tag.FluidTags;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import java.util.function.Predicate;
@Mixin(LivingEntity.class)
@EligibleIf(configAvailable="*.lava_causes_fall_damage")
public abstract class MixinLivingEntity extends Entity {
public MixinLivingEntity(EntityType<?> type, World world) {
super(type, world);
}
private static final Predicate<LivingEntity> fabrication$lavaFallDamagePredicate = ConfigPredicates.getFinalPredicate("*.lava_causes_fall_damage");
@FabModifyVariable(method="fall(DZLnet/minecraft/block/BlockState;Lnet/minecraft/util/math/BlockPos;)V", at=@At("HEAD"), argsOnly=true)
public boolean fabrication$treatLavaAsGround(boolean onGround) {
if (!FabConf.isEnabled("*.lava_causes_fall_damage")) return onGround;
if (!this.world.isClient && this.fallDistance > 6F && this.updateMovementInFluid(FluidTags.LAVA, 0.014D)) {
if (fabrication$lavaFallDamagePredicate.test((LivingEntity)(Object) this)) {
this.fallDistance /= 2F;
this.setVelocity(this.getVelocity().multiply(.4));
Object self = this;
if (self instanceof ServerPlayerEntity && ((ServerPlayerEntity) self).networkHandler.getConnection().isOpen()) {
((ServerPlayerEntity) self).networkHandler.sendPacket(new EntityVelocityUpdateS2CPacket(this));
}
return true;
}
}
return onGround;
}
}
| 412 | 0.796591 | 1 | 0.796591 | game-dev | MEDIA | 0.997775 | game-dev | 0.677879 | 1 | 0.677879 |
AzureXuanVerse/GameServer.SCHALE | 6,520 | SCHALE.Common/FlatData/FloaterCommonExcel.cs | // <auto-generated>
// automatically generated by the FlatBuffers compiler, do not modify
// </auto-generated>
namespace SCHALE.Common.FlatData
{
using global::System;
using global::System.Collections.Generic;
using global::SCHALE.Common.Crypto;
using global::Google.FlatBuffers;
public struct FloaterCommonExcel : IFlatbufferObject
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_24_3_25(); }
public static FloaterCommonExcel GetRootAsFloaterCommonExcel(ByteBuffer _bb) { return GetRootAsFloaterCommonExcel(_bb, new FloaterCommonExcel()); }
public static FloaterCommonExcel GetRootAsFloaterCommonExcel(ByteBuffer _bb, FloaterCommonExcel obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
public FloaterCommonExcel __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public long Id { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetLong(o + __p.bb_pos) : (long)0; } }
public SCHALE.Common.FlatData.TacticEntityType TacticEntityType { get { int o = __p.__offset(6); return o != 0 ? (SCHALE.Common.FlatData.TacticEntityType)__p.bb.GetInt(o + __p.bb_pos) : SCHALE.Common.FlatData.TacticEntityType.None; } }
public int FloaterOffsetPosX { get { int o = __p.__offset(8); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } }
public int FloaterOffsetPosY { get { int o = __p.__offset(10); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } }
public int FloaterRandomPosRangeX { get { int o = __p.__offset(12); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } }
public int FloaterRandomPosRangeY { get { int o = __p.__offset(14); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } }
public static Offset<SCHALE.Common.FlatData.FloaterCommonExcel> CreateFloaterCommonExcel(FlatBufferBuilder builder,
long Id = 0,
SCHALE.Common.FlatData.TacticEntityType TacticEntityType = SCHALE.Common.FlatData.TacticEntityType.None,
int FloaterOffsetPosX = 0,
int FloaterOffsetPosY = 0,
int FloaterRandomPosRangeX = 0,
int FloaterRandomPosRangeY = 0) {
builder.StartTable(6);
FloaterCommonExcel.AddId(builder, Id);
FloaterCommonExcel.AddFloaterRandomPosRangeY(builder, FloaterRandomPosRangeY);
FloaterCommonExcel.AddFloaterRandomPosRangeX(builder, FloaterRandomPosRangeX);
FloaterCommonExcel.AddFloaterOffsetPosY(builder, FloaterOffsetPosY);
FloaterCommonExcel.AddFloaterOffsetPosX(builder, FloaterOffsetPosX);
FloaterCommonExcel.AddTacticEntityType(builder, TacticEntityType);
return FloaterCommonExcel.EndFloaterCommonExcel(builder);
}
public static void StartFloaterCommonExcel(FlatBufferBuilder builder) { builder.StartTable(6); }
public static void AddId(FlatBufferBuilder builder, long id) { builder.AddLong(0, id, 0); }
public static void AddTacticEntityType(FlatBufferBuilder builder, SCHALE.Common.FlatData.TacticEntityType tacticEntityType) { builder.AddInt(1, (int)tacticEntityType, 0); }
public static void AddFloaterOffsetPosX(FlatBufferBuilder builder, int floaterOffsetPosX) { builder.AddInt(2, floaterOffsetPosX, 0); }
public static void AddFloaterOffsetPosY(FlatBufferBuilder builder, int floaterOffsetPosY) { builder.AddInt(3, floaterOffsetPosY, 0); }
public static void AddFloaterRandomPosRangeX(FlatBufferBuilder builder, int floaterRandomPosRangeX) { builder.AddInt(4, floaterRandomPosRangeX, 0); }
public static void AddFloaterRandomPosRangeY(FlatBufferBuilder builder, int floaterRandomPosRangeY) { builder.AddInt(5, floaterRandomPosRangeY, 0); }
public static Offset<SCHALE.Common.FlatData.FloaterCommonExcel> EndFloaterCommonExcel(FlatBufferBuilder builder) {
int o = builder.EndTable();
return new Offset<SCHALE.Common.FlatData.FloaterCommonExcel>(o);
}
public FloaterCommonExcelT UnPack() {
var _o = new FloaterCommonExcelT();
this.UnPackTo(_o);
return _o;
}
public void UnPackTo(FloaterCommonExcelT _o) {
byte[] key = TableEncryptionService.CreateKey("FloaterCommon");
_o.Id = TableEncryptionService.Convert(this.Id, key);
_o.TacticEntityType = TableEncryptionService.Convert(this.TacticEntityType, key);
_o.FloaterOffsetPosX = TableEncryptionService.Convert(this.FloaterOffsetPosX, key);
_o.FloaterOffsetPosY = TableEncryptionService.Convert(this.FloaterOffsetPosY, key);
_o.FloaterRandomPosRangeX = TableEncryptionService.Convert(this.FloaterRandomPosRangeX, key);
_o.FloaterRandomPosRangeY = TableEncryptionService.Convert(this.FloaterRandomPosRangeY, key);
}
public static Offset<SCHALE.Common.FlatData.FloaterCommonExcel> Pack(FlatBufferBuilder builder, FloaterCommonExcelT _o) {
if (_o == null) return default(Offset<SCHALE.Common.FlatData.FloaterCommonExcel>);
return CreateFloaterCommonExcel(
builder,
_o.Id,
_o.TacticEntityType,
_o.FloaterOffsetPosX,
_o.FloaterOffsetPosY,
_o.FloaterRandomPosRangeX,
_o.FloaterRandomPosRangeY);
}
}
public class FloaterCommonExcelT
{
public long Id { get; set; }
public SCHALE.Common.FlatData.TacticEntityType TacticEntityType { get; set; }
public int FloaterOffsetPosX { get; set; }
public int FloaterOffsetPosY { get; set; }
public int FloaterRandomPosRangeX { get; set; }
public int FloaterRandomPosRangeY { get; set; }
public FloaterCommonExcelT() {
this.Id = 0;
this.TacticEntityType = SCHALE.Common.FlatData.TacticEntityType.None;
this.FloaterOffsetPosX = 0;
this.FloaterOffsetPosY = 0;
this.FloaterRandomPosRangeX = 0;
this.FloaterRandomPosRangeY = 0;
}
}
static public class FloaterCommonExcelVerify
{
static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos)
{
return verifier.VerifyTableStart(tablePos)
&& verifier.VerifyField(tablePos, 4 /*Id*/, 8 /*long*/, 8, false)
&& verifier.VerifyField(tablePos, 6 /*TacticEntityType*/, 4 /*SCHALE.Common.FlatData.TacticEntityType*/, 4, false)
&& verifier.VerifyField(tablePos, 8 /*FloaterOffsetPosX*/, 4 /*int*/, 4, false)
&& verifier.VerifyField(tablePos, 10 /*FloaterOffsetPosY*/, 4 /*int*/, 4, false)
&& verifier.VerifyField(tablePos, 12 /*FloaterRandomPosRangeX*/, 4 /*int*/, 4, false)
&& verifier.VerifyField(tablePos, 14 /*FloaterRandomPosRangeY*/, 4 /*int*/, 4, false)
&& verifier.VerifyTableEnd(tablePos);
}
}
}
| 412 | 0.745684 | 1 | 0.745684 | game-dev | MEDIA | 0.689992 | game-dev | 0.769648 | 1 | 0.769648 |
bates64/papermario-dx | 7,207 | src/world/area_sam/sam_03/npc1.c | #include "sam_03.h"
#include "world/common/npc/JrTroopa.inc.c"
API_CALLABLE(N(GetAngleToPlayer)) {
Npc* npc = get_npc_unsafe(NPC_JrTroopa);
script->varTable[0] = atan2(npc->pos.x, npc->pos.z, gPlayerStatus.pos.x, gPlayerStatus.pos.z);
return ApiStatus_DONE2;
}
EvtScript N(EVS_NpcIdle_JrTroopa) = {
IfGe(GB_StoryProgress, STORY_CH7_DEFEATED_JR_TROOPA)
Return
EndIf
Label(11)
Call(GetPlayerPos, LVar0, LVar1, LVar2)
Wait(1)
IfLt(LVar0, 400)
Goto(11)
EndIf
Call(InterruptUsePartner)
Call(DisablePlayerInput, TRUE)
Call(SetMusicTrack, 0, SONG_JR_TROOPA_THEME, 0, 8)
Call(SpeakToPlayer, NPC_JrTroopa, ANIM_JrTroopa_Talk, ANIM_JrTroopa_Idle, 0, MSG_CH7_00D8)
Call(SetNpcJumpscale, NPC_JrTroopa, Float(1.0))
Call(NpcJump0, NPC_JrTroopa, 520, 0, -68, 20 * DT)
Call(PlayerFaceNpc, NPC_JrTroopa, FALSE)
Wait(15 * DT)
Call(GetNpcPos, NPC_JrTroopa, LVar0, LVar1, LVar2)
Add(LVar0, -20)
Call(UseSettingsFrom, CAM_DEFAULT, LVar0, LVar1, LVar2)
Call(SetPanTarget, CAM_DEFAULT, LVar0, LVar1, LVar2)
Call(SetCamDistance, CAM_DEFAULT, Float(225.0))
Call(SetCamPitch, CAM_DEFAULT, Float(15.0), Float(-8.0))
Call(SetCamSpeed, CAM_DEFAULT, Float(90.0))
Call(PanToTarget, CAM_DEFAULT, 0, TRUE)
Call(WaitForCam, CAM_DEFAULT, Float(1.0))
Call(SpeakToPlayer, NPC_JrTroopa, ANIM_JrTroopa_PointTalk, ANIM_JrTroopa_Idle, 0, MSG_CH7_00D9)
Call(GetPlayerPos, LVar0, LVar1, LVar2)
Add(LVar0, 30)
Call(UseSettingsFrom, CAM_DEFAULT, LVar0, LVar1, LVar2)
Call(SetPanTarget, CAM_DEFAULT, LVar0, LVar1, LVar2)
Call(SetCamSpeed, CAM_DEFAULT, Float(90.0))
Call(PanToTarget, CAM_DEFAULT, 0, TRUE)
Call(WaitForCam, CAM_DEFAULT, Float(1.0))
Call(SpeakToPlayer, NPC_JrTroopa, ANIM_JrTroopa_Talk, ANIM_JrTroopa_Idle, 0, MSG_CH7_00DA)
Call(GetPlayerPos, LVar0, LVar1, LVar2)
Call(GetNpcPos, NPC_JrTroopa, LVar3, LVar4, LVar5)
Call(GetDist2D, LVar6, LVar0, LVar2, LVar3, LVar5)
MulF(LVar6, Float(0.7))
Call(N(GetAngleToPlayer))
Call(AddVectorPolar, LVar3, LVar5, LVar6, LVar0)
Call(SetNpcSpeed, NPC_JrTroopa, Float(4.0 / DT))
Call(SetNpcAnimation, NPC_JrTroopa, ANIM_JrTroopa_Charge)
Thread
Call(NpcMoveTo, NPC_JrTroopa, LVar3, LVar5, 0)
EndThread
Call(StartBossBattle, SONG_JR_TROOPA_BATTLE)
Call(PanToTarget, CAM_DEFAULT, 0, FALSE)
Return
End
};
EvtScript N(EVS_NpcInteract_JrTroopa) = {
Call(SpeakToPlayer, NPC_SELF, ANIM_JrTroopa_Defeated, ANIM_JrTroopa_Defeated, 5, MSG_CH7_00DF)
Return
End
};
EvtScript N(EVS_NpcHit_JrTroopaHitbox) = {
Call(GetOwnerEncounterTrigger, LVar0)
Switch(LVar0)
CaseOrEq(ENCOUNTER_TRIGGER_JUMP)
CaseOrEq(ENCOUNTER_TRIGGER_HAMMER)
CaseOrEq(ENCOUNTER_TRIGGER_PARTNER)
Call(DisablePlayerInput, TRUE)
Call(SpeakToPlayer, NPC_SELF, ANIM_JrTroopa_Hurt, ANIM_JrTroopa_Collapse, 5, MSG_CH7_00DF)
Call(DisablePlayerInput, FALSE)
EndCaseGroup
EndSwitch
Return
End
};
EvtScript N(EVS_NpcDefeat_JrTroopa) = {
Call(ClearDefeatedEnemies)
Call(GetBattleOutcome, LVar0)
Switch(LVar0)
CaseEq(OUTCOME_PLAYER_WON)
Set(GB_StoryProgress, STORY_CH7_DEFEATED_JR_TROOPA)
Call(SetNpcAnimation, NPC_JrTroopa, ANIM_JrTroopa_Defeated)
Call(SetNpcAnimation, NPC_JrTroopa_Hitbox, ANIM_JrTroopa_Defeated)
Call(GetNpcPos, NPC_JrTroopa, LVar0, LVar1, LVar2)
Call(UseSettingsFrom, CAM_DEFAULT, LVar0, LVar1, LVar2)
Call(SetPanTarget, CAM_DEFAULT, LVar0, LVar1, LVar2)
Call(SetCamDistance, CAM_DEFAULT, Float(200.0))
Call(SetCamSpeed, CAM_DEFAULT, Float(90.0))
Call(PanToTarget, CAM_DEFAULT, 0, TRUE)
Call(WaitForCam, CAM_DEFAULT, Float(1.0))
Thread
Wait(5 * DT)
Call(PanToTarget, CAM_DEFAULT, 0, FALSE)
Call(SetCamSpeed, CAM_DEFAULT, Float(2.0 / DT))
Call(WaitForCam, CAM_DEFAULT, Float(1.0))
Call(SetCamSpeed, CAM_DEFAULT, Float(1.0 / DT))
EndThread
Call(SpeakToPlayer, NPC_JrTroopa, ANIM_JrTroopa_Defeated, ANIM_JrTroopa_Defeated, 5, MSG_CH7_00DF)
Call(GetNpcPos, NPC_JrTroopa, LVar0, LVar1, LVar2)
Call(SetNpcPos, NPC_JrTroopa_Hitbox, LVar0, LVar1, LVar2)
Call(SetNpcCollisionSize, NPC_JrTroopa, 26, 24)
Call(SetNpcCollisionSize, NPC_JrTroopa_Hitbox, 26, 24)
Call(SetNpcFlagBits, NPC_JrTroopa_Hitbox, NPC_FLAG_INVISIBLE, TRUE)
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_JrTroopa)))
Call(BindNpcHit, NPC_JrTroopa_Hitbox, Ref(N(EVS_NpcHit_JrTroopaHitbox)))
Exec(N(EVS_SetupMusic))
Call(DisablePlayerInput, FALSE)
CaseEq(OUTCOME_PLAYER_FLED)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcInit_JrTroopa) = {
Call(BindNpcIdle, NPC_SELF, Ref(N(EVS_NpcIdle_JrTroopa)))
Call(BindNpcDefeat, NPC_SELF, Ref(N(EVS_NpcDefeat_JrTroopa)))
Switch(GB_StoryProgress)
CaseLt(STORY_CH7_DEFEATED_JR_TROOPA)
Call(SetNpcPos, NPC_JrTroopa, 600, 0, -65)
CaseGe(STORY_CH7_DEFEATED_JR_TROOPA)
Call(SetNpcPos, NPC_JrTroopa, 399, 6, -100)
Call(SetNpcAnimation, NPC_JrTroopa, ANIM_JrTroopa_Collapse)
Call(EnableModel, MODEL_o44, TRUE)
Call(ModifyColliderFlags, MODIFY_COLLIDER_FLAGS_CLEAR_BITS, COLLIDER_o44, COLLIDER_FLAGS_UPPER_MASK)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcInit_JrTroopaHitbox) = {
Call(SetNpcPos, NPC_SELF, NPC_DISPOSE_LOCATION)
Return
End
};
// first Jr Troopa is for interacting with player, the second is 'hostile' and can respond to being hit
NpcData N(NpcData_JrTroopa)[] = {
{
.id = NPC_JrTroopa,
.pos = { 261.0f, 0.0f, -76.0f },
.yaw = 270,
.init = &N(EVS_NpcInit_JrTroopa),
.settings = &N(NpcSettings_JrTroopa),
.flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_DO_NOT_KILL | ENEMY_FLAG_ENABLE_HIT_SCRIPT | ENEMY_FLAG_IGNORE_WORLD_COLLISION | ENEMY_FLAG_IGNORE_ENTITY_COLLISION | ENEMY_FLAG_FLYING | ENEMY_FLAG_NO_DELAY_AFTER_FLEE | ENEMY_FLAG_DO_NOT_AUTO_FACE_PLAYER,
.drops = NO_DROPS,
.animations = JR_TROOPA_ANIMS,
.tattle = MSG_NpcTattle_JrTroopa,
},
{
.id = NPC_JrTroopa_Hitbox,
.pos = { 261.0f, 0.0f, -76.0f },
.yaw = 270,
.init = &N(EVS_NpcInit_JrTroopaHitbox),
.settings = &N(NpcSettings_JrTroopa),
.flags = ENEMY_FLAG_DO_NOT_KILL | ENEMY_FLAG_ENABLE_HIT_SCRIPT | ENEMY_FLAG_IGNORE_WORLD_COLLISION | ENEMY_FLAG_IGNORE_PLAYER_COLLISION | ENEMY_FLAG_IGNORE_ENTITY_COLLISION | ENEMY_FLAG_FLYING | ENEMY_FLAG_NO_DELAY_AFTER_FLEE | ENEMY_FLAG_SKIP_BATTLE | ENEMY_FLAG_DO_NOT_AUTO_FACE_PLAYER | ENEMY_FLAG_IGNORE_TOUCH | ENEMY_FLAG_IGNORE_SPIN,
.drops = NO_DROPS,
.animations = JR_TROOPA_ANIMS,
.tattle = MSG_NpcTattle_JrTroopa,
},
};
NpcGroupList N(BeforeNPCs) = {
NPC_GROUP(N(NpcData_JrTroopa), BTL_KMR_3_FORMATION_06),
{}
};
| 412 | 0.953604 | 1 | 0.953604 | game-dev | MEDIA | 0.96993 | game-dev | 0.82374 | 1 | 0.82374 |
itsmeow/betteranimalsplus | 2,499 | common/src/main/java/dev/itsmeow/betteranimalsplus/common/entity/ai/EntityAITemptAnyNav.java | package dev.itsmeow.betteranimalsplus.common.entity.ai;
import com.google.common.collect.Sets;
import net.minecraft.world.entity.PathfinderMob;
import net.minecraft.world.entity.ai.goal.Goal;
import net.minecraft.world.entity.ai.targeting.TargetingConditions;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import java.util.EnumSet;
import java.util.Set;
public class EntityAITemptAnyNav extends Goal {
private static final TargetingConditions selector = TargetingConditions.forNonCombat().range(10.0D).ignoreLineOfSight();
private final PathfinderMob entity;
private final double speed;
private Player tempter;
private int cooldown;
private final Set<Item> temptItems;
public EntityAITemptAnyNav(PathfinderMob creature, double speed, Set<Item> temptItems) {
this.entity = creature;
this.speed = speed;
this.temptItems = temptItems;
this.setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK));
}
public EntityAITemptAnyNav(PathfinderMob creature, double speed, Item... temptItems) {
this(creature, speed, Sets.newHashSet(temptItems));
}
@Override
public boolean canUse() {
if(this.cooldown > 0) {
--this.cooldown;
return false;
} else {
this.tempter = this.entity.level.getNearestPlayer(selector, this.entity);
if(this.tempter == null) {
return false;
} else {
return this.isTemptedBy(this.tempter.getMainHandItem()) || this.isTemptedBy(this.tempter.getOffhandItem());
}
}
}
private boolean isTemptedBy(ItemStack stack) {
return this.temptItems.contains(stack.getItem());
}
@Override
public boolean canContinueToUse() {
return this.canUse();
}
@Override
public void stop() {
this.tempter = null;
this.entity.getNavigation().stop();
this.cooldown = 100;
}
@Override
public void tick() {
if(this.tempter == null) {
return;
}
this.entity.getLookControl().setLookAt(this.tempter, (float) (this.entity.getMaxHeadYRot() + 20), (float) this.entity.getMaxHeadXRot());
if(this.entity.distanceToSqr(this.tempter) < 6.25D) {
this.entity.getNavigation().stop();
} else {
this.entity.getNavigation().moveTo(this.tempter, this.speed);
}
}
}
| 412 | 0.885308 | 1 | 0.885308 | game-dev | MEDIA | 0.991328 | game-dev | 0.952884 | 1 | 0.952884 |
Gaby-Station/Gaby-Station | 1,730 | Content.Server/EntityEffects/Effects/PlantMetabolism/PlantDestroySeeds.cs | // SPDX-FileCopyrightText: 2024 Aidenkrz <aiden@djkraz.com>
// SPDX-FileCopyrightText: 2024 Eris <eris@erisws.com>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using Content.Server.Botany.Components;
using Content.Server.Botany.Systems;
using Content.Shared.EntityEffects;
using Content.Shared.Popups;
using Robust.Shared.Prototypes;
namespace Content.Server.EntityEffects.Effects.PlantMetabolism;
/// <summary>
/// Handles removal of seeds on a plant.
/// </summary>
public sealed partial class PlantDestroySeeds : EntityEffect
{
public override void Effect(EntityEffectBaseArgs args)
{
if (
!args.EntityManager.TryGetComponent(args.TargetEntity, out PlantHolderComponent? plantHolderComp)
|| plantHolderComp.Seed == null
|| plantHolderComp.Dead
|| plantHolderComp.Seed.Immutable
)
return;
var plantHolder = args.EntityManager.System<PlantHolderSystem>();
var popupSystem = args.EntityManager.System<SharedPopupSystem>();
if (plantHolderComp.Seed.Seedless == false)
{
plantHolder.EnsureUniqueSeed(args.TargetEntity, plantHolderComp);
popupSystem.PopupEntity(
Loc.GetString("botany-plant-seedsdestroyed"),
args.TargetEntity,
PopupType.SmallCaution
);
plantHolderComp.Seed.Seedless = true;
}
}
protected override string? ReagentEffectGuidebookText(IPrototypeManager prototype, IEntitySystemManager entSys) =>
Loc.GetString("reagent-effect-guidebook-plant-seeds-remove", ("chance", Probability));
} | 412 | 0.594862 | 1 | 0.594862 | game-dev | MEDIA | 0.867081 | game-dev | 0.736448 | 1 | 0.736448 |
bozimmerman/CoffeeMud | 11,656 | com/planet_ink/coffee_mud/Abilities/Properties/Prop_ItemSlotFiller.java | package com.planet_ink.coffee_mud.Abilities.Properties;
import com.planet_ink.coffee_mud.core.CMClass;
import com.planet_ink.coffee_mud.core.CMLib;
import com.planet_ink.coffee_mud.core.CMParms;
import com.planet_ink.coffee_mud.core.CMStrings;
import com.planet_ink.coffee_mud.core.collections.Converter;
import com.planet_ink.coffee_mud.core.collections.ConvertingEnumeration;
import com.planet_ink.coffee_mud.core.collections.IteratorEnumeration;
import com.planet_ink.coffee_mud.core.collections.Pair;
import com.planet_ink.coffee_mud.core.collections.PairList;
import com.planet_ink.coffee_mud.core.collections.PairVector;
import com.planet_ink.coffee_mud.core.collections.XVector;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.CharClass;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.MOB;
import com.planet_ink.coffee_mud.Races.interfaces.Race;
import java.util.*;
/*
Copyright 2015-2025 Bo Zimmerman
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.
*/
public class Prop_ItemSlotFiller extends Property implements AbilityContainer
{
@Override
public String ID()
{
return "Prop_ItemSlotFiller";
}
@Override
public String name()
{
return "Provides for enhanced item slots.";
}
@Override
protected int canAffectCode()
{
return Ability.CAN_ITEMS;
}
protected int slotCount = 1;
protected String slotType = "";
protected Ability[] affects = new Ability[0];
protected Physical affected2 = null;
protected List<String> skips = new Vector<String>(0);
protected static Item fakeItem = null;
protected PairList<String, String> adds = new PairVector<String, String>(0);
@Override
public CMObject copyOf()
{
final Prop_ItemSlotFiller pA = (Prop_ItemSlotFiller)super.copyOf();
if(skips != null)
pA.skips = new XVector<String>(skips);
if(adds != null)
{
pA.adds = new PairVector<String, String>();
pA.adds.addAll(adds);
}
if(affects != null)
{
pA.affects = new Ability[affects.length];
for(int i=0;i<affects.length;i++)
{
if(affects[i]!=null)
pA.affects[i] = (Ability)affects[i].copyOf();
}
}
return pA;
}
@Override
public String accountForYourself()
{
if(numAbilities()==0)
return "";
final StringBuilder str=new StringBuilder("Adds the following effects: ");
for(final Enumeration<Ability> a=abilities();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if(A!=null)
str.append(A.accountForYourself()+", ");
}
if(str.length()>2)
str.delete(str.length()-2,str.length());
str.append(". ");
return str.toString();
}
@Override
public void setAffectedOne(final Physical P)
{
if((P==this.affected)||(affected==null))
{
super.setAffectedOne(P);
for(final Ability A : getAffects())
{
if((A!=null)&&(!A.ID().startsWith("Prop_ItemSlot")))
{
final Physical oldP=A.affecting();
A.setAffectedOne(null); // helps reset the effect
A.setAffectedOne(oldP);
}
}
}
else
{
affected2 = P;
for(final Ability A : getAffects())
{
if((A!=null)&&(!A.ID().startsWith("Prop_ItemSlot")))
A.setAffectedOne(P);
}
}
}
protected Physical getAffected()
{
if(affected2 instanceof Item)
return affected2;
if(fakeItem == null)
{
fakeItem=CMClass.getBasicItem("StdItem");
}
return fakeItem;
}
protected Ability[] getAffects()
{
if((affects==null)
&&(this.affecting()!=null))
{
final List<Ability> newAffects=new LinkedList<Ability>();
if(affecting().numEffects()>1)
{
for(final Enumeration<Ability> a=affecting().effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=this)
&&(!skips.contains(A.ID().toUpperCase())))
{
A.setAffectedOne(getAffected());
newAffects.add(A); // not the copy!
}
}
}
for(final Enumeration<Ability> a=this.abilities();a.hasMoreElements();)
{
final Ability A=a.nextElement();
A.setAffectedOne(getAffected());
newAffects.add(A); // not the copy!
}
affects=newAffects.toArray(new Ability[0]);
}
return affects;
}
protected String newText()
{
final StringBuilder str = new StringBuilder("");
if(slotCount>1)
str.append("NUM="+slotCount+" ");
if(slotType.length()>0)
str.append("TYPE=\""+slotType+"\" ");
final StringBuilder skips = new StringBuilder("");
for(final String s : this.skips)
skips.append(","+CMStrings.escape(s));
if(skips.toString().trim().length()>0)
str.append("SKIPS=\""+skips.toString().substring(1).trim()+"\" ");
final StringBuilder adds = new StringBuilder("");
for(final Pair<String,String> p : this.adds)
adds.append(",").append(p.first).append("(").append(p.second).append(")");
if(adds.toString().trim().length()>0)
str.append("ADDS=\""+adds.toString().substring(1).trim()+"\" ");
return str.toString().trim();
}
@Override
public void setMiscText(final String text)
{
slotCount = CMParms.getParmInt(text, "NUM", 1);
slotType= CMParms.getParmStr(text, "TYPE", "");
skips.clear();
skips.addAll(CMParms.parseCommas(CMParms.getParmStr(text, "SKIPS", "").toUpperCase(), true));
adds.clear();
int addState=0;
final String addStr=CMParms.getParmStr(text, "ADDS", "");
int lastDex=0;
Pair<String,String> p=new Pair<String,String>("","");
for(int i=0;i<addStr.length();i++)
{
final char c=addStr.charAt(i);
switch(addState)
{
case 0:
if((c=='(')&&(lastDex!=i))
{
p.first=addStr.substring(lastDex,i).trim();
lastDex=i+1;
addState=1;
}
else
if((c==',')&&(lastDex!=i))
{
p.first=addStr.substring(lastDex,i).trim();
lastDex=i+1;
if((p.first.length()>0)&&(CMClass.getAbilityPrototype(p.first)!=null))
{
adds.add(p);
p=new Pair<String,String>("","");
}
}
break;
case 1:
if(c==')')
{
if(lastDex!=i)
p.second=addStr.substring(lastDex,i);
addState=2;
}
break;
case 2:
if(c==',')
{
if((p.first.length()>0)&&(CMClass.getAbilityPrototype(p.first)!=null))
{
adds.add(p);
p=new Pair<String,String>("","");
}
lastDex=i+1;
addState=0;
}
break;
}
}
if((p.first.length()>0)&&(CMClass.getAbilityPrototype(p.first)!=null))
{
adds.add(p);
if(addState == 1)
p.second=addStr.substring(lastDex);
}
affects=null;
super.setMiscText(text);
}
protected boolean isSlotted()
{
final Physical affected=this.affected;
if(affected == null)
return true;
if(!(affected instanceof Item))
return true;
final Item I=(Item)affected;
if(I.owner() == null) // this is the key "tell"
return true;
return false;
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost,msg))
return false;
if(isSlotted()
&&(myHost instanceof Physical))
{
final Physical P=(affected2 != null)?affected2:(Physical)myHost;
for(final Ability A : getAffects())
{
if((A!=null)&&(!A.ID().startsWith("Prop_ItemSlot")))
{
if(!A.okMessage(P, msg))
return false;
}
}
}
return true;
}
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
if(isSlotted()
&&(myHost instanceof Physical))
{
final Physical P=(affected2 != null)?affected2:(Physical)myHost;
for(final Ability A : getAffects())
{
if((A!=null)&&(!A.ID().startsWith("Prop_ItemSlot")))
A.executeMsg(P, msg);
}
}
super.executeMsg(myHost, msg);
}
@Override
public void affectPhyStats(final Physical host, final PhyStats affectableStats)
{
if(isSlotted())
{
if(host instanceof MOB)
{
for(final Ability A : getAffects())
{
if((A!=null)
&&(A.bubbleAffect())
&&(!A.ID().startsWith("Prop_ItemSlot")))
A.affectPhyStats(host, affectableStats);
}
}
else
{
for(final Ability A : getAffects())
{
if((A!=null)
&&(!A.bubbleAffect())
&&(!A.ID().startsWith("Prop_ItemSlot")))
A.affectPhyStats(host, affectableStats);
}
}
}
super.affectPhyStats(host,affectableStats);
}
@Override
public void affectCharStats(final MOB affectedMOB, final CharStats affectedStats)
{
if(isSlotted())
{
for(final Ability A : getAffects())
{
if((A!=null)
&&(A.bubbleAffect())
&&(!A.ID().startsWith("Prop_ItemSlot")))
A.affectCharStats(affectedMOB, affectedStats);
}
}
super.affectCharStats(affectedMOB,affectedStats);
}
@Override
public void affectCharState(final MOB affectedMOB, final CharState affectedState)
{
if(isSlotted())
{
for(final Ability A : getAffects())
{
if((A!=null)
&&(A.bubbleAffect())
&&(!A.ID().startsWith("Prop_ItemSlot")))
A.affectCharState(affectedMOB, affectedState);
}
}
super.affectCharState(affectedMOB,affectedState);
}
@Override
public void addAbility(final Ability to)
{
adds.add(new Pair<String,String>(to.ID(),to.text()));
super.miscText = newText();
this.affects = null;
}
@Override
public void delAbility(final Ability to)
{
for(final Iterator<Pair<String,String>> i=adds.iterator();i.hasNext();)
{
final Pair<String,String> p=i.next();
if(p.first.equalsIgnoreCase(to.ID()) && p.second.equalsIgnoreCase(to.text()))
i.remove();
}
super.miscText = newText();
this.affects = null;
}
@Override
public int numAbilities()
{
return adds.size();
}
@Override
public Ability fetchAbility(final int index)
{
if((index<0)||(index>=adds.size()))
return null;
final Ability A=CMClass.getAbility(adds.getFirst(index));
if(A!=null)
A.setMiscText(adds.getSecond(index));
return A;
}
@Override
public Ability fetchAbility(final String ID)
{
for(int i=0;i<adds.size();i++)
{
if(adds.getFirst(i).equalsIgnoreCase(ID))
{
final Ability A=CMClass.getAbility(adds.getFirst(i));
if(A!=null)
A.setMiscText(adds.getSecond(i));
return A;
}
}
return null;
}
@Override
public Ability fetchRandomAbility()
{
if(adds.size()==0)
return null;
return this.fetchAbility(CMLib.dice().roll(1, adds.size(), -1));
}
@Override
public Enumeration<Ability> abilities()
{
return new ConvertingEnumeration<Pair<String,String>, Ability>(
new IteratorEnumeration<Pair<String,String>>(adds.iterator()),
new Converter<Pair<String,String>, Ability>()
{
@Override
public Ability convert(final Pair<String, String> obj)
{
if(obj==null)
return null;
final Ability A=CMClass.getAbility(obj.first);
if(A!=null)
A.setMiscText(obj.second);
return A;
}
});
}
@Override
public void delAllAbilities()
{
throw new java.lang.UnsupportedOperationException();
}
@Override
public int numAllAbilities()
{
return adds.size();
}
@Override
public Enumeration<Ability> allAbilities()
{
return abilities();
}
}
| 412 | 0.975999 | 1 | 0.975999 | game-dev | MEDIA | 0.514806 | game-dev | 0.919224 | 1 | 0.919224 |
pirhosoft/PiRhoUtilities | 21,959 | Assets/PiRhoUtilities/Editor/Extensions/SerializedPropertyExtensions.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
using Object = UnityEngine.Object;
namespace PiRhoSoft.Utilities.Editor
{
public static class SerializedPropertyExtensions
{
#region Internal Lookups
private const string _changedInternalsError = "(PUPFECI) failed to setup SerializedProperty: Unity internals have changed";
private const string _createFieldFromPropertyName = "CreateFieldFromProperty";
private static MethodInfo _createFieldFromPropertyMethod;
private static object[] _createFieldFromPropertyParameters = new object[1];
private static PropertyField _createFieldFromPropertyInstance;
private const string _gradientValueName = "gradientValue";
private static PropertyInfo _gradientValueProperty;
private const string _hasVisibleChildFieldsName = "HasVisibleChildFields";
private static MethodInfo _hasVisibleChildFieldsMethod;
private static object[] _hasVisibleChildFieldsParameters = new object[1];
static SerializedPropertyExtensions()
{
var createFieldFromPropertyMethod = typeof(PropertyField).GetMethod(_createFieldFromPropertyName, BindingFlags.Instance | BindingFlags.NonPublic);
if (createFieldFromPropertyMethod != null && createFieldFromPropertyMethod.HasSignature(typeof(VisualElement), typeof(SerializedProperty)))
{
_createFieldFromPropertyMethod = createFieldFromPropertyMethod;
_createFieldFromPropertyInstance = new PropertyField();
}
var gradientValueProperty = typeof(SerializedProperty).GetProperty(_gradientValueName, BindingFlags.Instance | BindingFlags.NonPublic);
if (gradientValueProperty != null && gradientValueProperty.PropertyType == typeof(Gradient) && gradientValueProperty.CanRead && gradientValueProperty.CanWrite)
_gradientValueProperty = gradientValueProperty;
var hasVisibleChildFieldsMethod = typeof(EditorGUI).GetMethod(_hasVisibleChildFieldsName, BindingFlags.Static | BindingFlags.NonPublic);
if (hasVisibleChildFieldsMethod != null && hasVisibleChildFieldsMethod.HasSignature(typeof(bool), typeof(SerializedProperty)))
_hasVisibleChildFieldsMethod = hasVisibleChildFieldsMethod;
if (_createFieldFromPropertyMethod == null || _gradientValueProperty == null || _hasVisibleChildFieldsMethod == null)
Debug.LogError(_changedInternalsError);
}
#endregion
#region Extension Methods
public static string GetTooltip(this SerializedProperty property)
{
var obj = property.GetOwner<object>();
var type = obj?.GetType();
var field = type?.GetField(property.name);
return field?.GetTooltip();
}
public static IEnumerable<SerializedProperty> Children(this SerializedProperty property)
{
if (property.isArray)
{
for (int i = 0; i < property.arraySize; i++)
yield return property.GetArrayElementAtIndex(i);
}
else if (string.IsNullOrEmpty(property.propertyPath))
{
var iterator = property.Copy();
var valid = iterator.NextVisible(true);
while (valid)
{
yield return iterator.Copy();
valid = iterator.NextVisible(false);
}
}
else
{
var iterator = property.Copy();
var end = iterator.GetEndProperty();
var valid = iterator.NextVisible(true);
while (valid && !SerializedProperty.EqualContents(iterator, end))
{
yield return iterator.Copy();
valid = iterator.NextVisible(false);
}
}
}
// this property is internal for some reason
public static Gradient GetGradientValue(this SerializedProperty property)
{
return _gradientValueProperty?.GetValue(property) as Gradient;
}
public static void SetGradientValue(this SerializedProperty property, Gradient gradient)
{
_gradientValueProperty?.SetValue(property, gradient);
}
public static Type GetManagedReferenceFieldType(this SerializedProperty property)
{
if (property.propertyType != SerializedPropertyType.ManagedReference)
return null;
return ParseType(property.managedReferenceFieldTypename);
}
public static Type GetManagedReferenceValueType(this SerializedProperty property)
{
if (property.propertyType != SerializedPropertyType.ManagedReference)
return null;
return ParseType(property.managedReferenceFullTypename);
}
public static bool HasManagedReferenceValue(this SerializedProperty property)
{
if (property.propertyType != SerializedPropertyType.ManagedReference)
return false;
return !string.IsNullOrEmpty(property.managedReferenceFullTypename);
}
private static Regex _unityType = new Regex(@"(\S+) ([^/]+)(?:/(.+))?", RegexOptions.Compiled);
private static Dictionary<string, Type> _unityTypeMap = new Dictionary<string, Type>();
private static Type ParseType(string unityName)
{
if (!_unityTypeMap.TryGetValue(unityName, out var type))
{
var match = _unityType.Match(unityName);
if (match.Success)
{
// unity format is "Assembly Type" or "Assembly Parent/Type"
// c# format is "Type, Assembly" or "Parent+Type, Assembly" but Assembly must be fully qualified
var assembly = match.Groups[1].Value;
var name = match.Groups[2].Value;
var nested = match.Groups[3].Value;
var fullName = string.IsNullOrEmpty(nested) ? name : $"{name}+{nested}";
var a = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(am => am.GetName().Name == assembly);
type = a.GetType(fullName);
_unityTypeMap.Add(unityName, type);
}
}
return type;
}
public static object GetManagedReferenceValue(this SerializedProperty property)
{
return property.GetObject<object>(); // PENDING: slow but property.managedReferenceValue is write only
}
public static VisualElement CreateField(this SerializedProperty property)
{
_createFieldFromPropertyParameters[0] = property;
return _createFieldFromPropertyMethod?.Invoke(_createFieldFromPropertyInstance, _createFieldFromPropertyParameters) as VisualElement;
}
public static bool HasVisibleChildFields(this SerializedProperty property)
{
_hasVisibleChildFieldsParameters[0] = property;
return (bool)_hasVisibleChildFieldsMethod?.Invoke(null, _hasVisibleChildFieldsParameters);
}
public static void SetToDefault(this SerializedProperty property)
{
if (property.isArray)
{
property.ClearArray();
}
else if (property.hasChildren && property.propertyType != SerializedPropertyType.ManagedReference)
{
foreach (var child in property.Children())
child.SetToDefault();
}
else
{
switch (property.propertyType)
{
case SerializedPropertyType.Generic: break;
case SerializedPropertyType.Integer: property.intValue = default; break;
case SerializedPropertyType.Boolean: property.boolValue = default; break;
case SerializedPropertyType.Float: property.floatValue = default; break;
case SerializedPropertyType.String: property.stringValue = string.Empty; break;
case SerializedPropertyType.Color: property.colorValue = default; break;
case SerializedPropertyType.ObjectReference: property.objectReferenceValue = default; break;
case SerializedPropertyType.LayerMask: property.intValue = 0; break;
case SerializedPropertyType.Enum: property.enumValueIndex = 0; break;
case SerializedPropertyType.Vector2: property.vector2Value = default; break;
case SerializedPropertyType.Vector3: property.vector3Value = default; break;
case SerializedPropertyType.Vector4: property.vector4Value = default; break;
case SerializedPropertyType.Rect: property.rectValue = default; break;
case SerializedPropertyType.ArraySize: property.intValue = 0; break;
case SerializedPropertyType.Character: property.intValue = default; break;
case SerializedPropertyType.AnimationCurve: property.animationCurveValue = default; break;
case SerializedPropertyType.Bounds: property.boundsValue = default; break;
case SerializedPropertyType.Gradient: property.SetGradientValue(default); break;
case SerializedPropertyType.Quaternion: property.quaternionValue = default; break;
case SerializedPropertyType.ExposedReference: property.exposedReferenceValue = default; break;
case SerializedPropertyType.FixedBufferSize: property.intValue = 0; break;
case SerializedPropertyType.Vector2Int: property.vector2IntValue = default; break;
case SerializedPropertyType.Vector3Int: property.vector3IntValue = default; break;
case SerializedPropertyType.RectInt: property.rectIntValue = default; break;
case SerializedPropertyType.BoundsInt: property.boundsIntValue = default; break;
case SerializedPropertyType.ManagedReference: property.managedReferenceValue = default; break;
}
}
}
public static SerializedPropertyType GetPropertyType<T>()
{
var type = typeof(T);
// SerializedPropertyType.Generic
if (type == typeof(int)) return SerializedPropertyType.Integer;
else if (type == typeof(bool)) return SerializedPropertyType.Boolean;
else if (type == typeof(float)) return SerializedPropertyType.Float;
else if (type == typeof(string)) return SerializedPropertyType.String;
else if (type == typeof(Color)) return SerializedPropertyType.Color;
else if (typeof(Object).IsAssignableFrom(type)) return SerializedPropertyType.ObjectReference;
else if (type == typeof(LayerMask)) return SerializedPropertyType.LayerMask;
else if (type == typeof(Enum) || type.IsEnum) return SerializedPropertyType.Enum;
else if (type == typeof(Vector2)) return SerializedPropertyType.Vector2;
else if (type == typeof(Vector3)) return SerializedPropertyType.Vector3;
else if (type == typeof(Vector4)) return SerializedPropertyType.Vector4;
else if (type == typeof(Rect)) return SerializedPropertyType.Rect;
// SerializedPropertyType.ArraySize - stored as ints
else if (type == typeof(char)) return SerializedPropertyType.Character;
else if (type == typeof(AnimationCurve)) return SerializedPropertyType.AnimationCurve;
else if (type == typeof(Bounds)) return SerializedPropertyType.Bounds;
else if (type == typeof(Gradient)) return SerializedPropertyType.Gradient;
else if (type == typeof(Quaternion)) return SerializedPropertyType.Quaternion;
// SerializedPropertyType.ExposedReference
// SerializedPropertyType.FixedBufferSize
else if (type == typeof(Vector2Int)) return SerializedPropertyType.Vector2Int;
else if (type == typeof(Vector3Int)) return SerializedPropertyType.Vector3Int;
else if (type == typeof(RectInt)) return SerializedPropertyType.RectInt;
else if (type == typeof(BoundsInt)) return SerializedPropertyType.BoundsInt;
// SerializedPropertyType.ManagedReference - no way to know
return SerializedPropertyType.Generic;
}
public static bool TryGetValue<T>(this SerializedProperty property, out T value)
{
// this boxes for value types but I don't think there's a way around that without dynamic code generation
var type = typeof(T);
switch (property.propertyType)
{
case SerializedPropertyType.Generic: break;
case SerializedPropertyType.Integer: if (type == typeof(int)) { value = (T)(object)property.intValue; return true; } break;
case SerializedPropertyType.Boolean: if (type == typeof(bool)) { value = (T)(object)property.boolValue; return true; } break;
case SerializedPropertyType.Float: if (type == typeof(float)) { value = (T)(object)property.floatValue; return true; } break;
case SerializedPropertyType.String: if (type == typeof(string)) { value = (T)(object)property.stringValue; return true; } break;
case SerializedPropertyType.Color: if (type == typeof(Color)) { value = (T)(object)property.colorValue; return true; } break;
case SerializedPropertyType.ObjectReference: if (typeof(Object).IsAssignableFrom(type)) { value = (T)(object)property.objectReferenceValue; return true; } break;
case SerializedPropertyType.LayerMask: if (type == typeof(LayerMask)) { value = (T)(object)(LayerMask)property.intValue; return true; } else if (type == typeof(int)) { value = (T)(object)property.intValue; return true; } break;
case SerializedPropertyType.Enum: if (type == typeof(Enum) || type.IsEnum) { value = (T)(object) property.GetEnumValue(); return true; } break;
case SerializedPropertyType.Vector2: if (type == typeof(Vector2)) { value = (T)(object)property.vector2Value; return true; } break;
case SerializedPropertyType.Vector3: if (type == typeof(Vector3)) { value = (T)(object)property.vector3Value; return true; } break;
case SerializedPropertyType.Vector4: if (type == typeof(Vector4)) { value = (T)(object)property.vector4Value; return true; } break;
case SerializedPropertyType.Rect: if (type == typeof(Rect)) { value = (T)(object)property.rectValue; return true; } break;
case SerializedPropertyType.ArraySize: if (type == typeof(int)) { value = (T)(object)property.intValue; return true; } break;
case SerializedPropertyType.Character: if (type == typeof(char)) { value = (T)(object)(char)property.intValue; return true; } break;
case SerializedPropertyType.AnimationCurve: if (type == typeof(AnimationCurve)) { value = (T)(object)property.animationCurveValue; return true; } break;
case SerializedPropertyType.Bounds: if (type == typeof(Bounds)) { value = (T)(object)property.boundsValue; return true; } break;
case SerializedPropertyType.Gradient: if (type == typeof(Gradient)) { value = (T)(object)property.GetGradientValue(); return true; } break;
case SerializedPropertyType.Quaternion: if (type == typeof(Quaternion)) { value = (T)(object)property.quaternionValue; return true; } break;
case SerializedPropertyType.ExposedReference: break;
case SerializedPropertyType.FixedBufferSize: break;
case SerializedPropertyType.Vector2Int: if (type == typeof(Vector2Int)) { value = (T)(object)property.vector2IntValue; return true; } break;
case SerializedPropertyType.Vector3Int: if (type == typeof(Vector3Int)) { value = (T)(object)property.vector3IntValue; return true; } break;
case SerializedPropertyType.RectInt: if (type == typeof(RectInt)) { value = (T)(object)property.rectIntValue; return true; } break;
case SerializedPropertyType.BoundsInt: if (type == typeof(BoundsInt)) { value = (T)(object)property.boundsIntValue; return true; } break;
case SerializedPropertyType.ManagedReference: var managed = property.GetManagedReferenceValue(); if (managed == null) { value = default; return true; } else if (managed is T t) { value = t; return true; } break;
}
value = default;
return false;
}
public static bool TrySetValue(this SerializedProperty property, object value)
{
switch (property.propertyType)
{
case SerializedPropertyType.Generic: return false;
case SerializedPropertyType.Integer: if (value is int i) { property.intValue = i; return true; } return false;
case SerializedPropertyType.Boolean: if (value is bool b) { property.boolValue = b; return true; } return false;
case SerializedPropertyType.Float: if (value is float f) { property.floatValue = f; return true; } return false;
case SerializedPropertyType.String: if (value is string s) { property.stringValue = s; return true; } return false;
case SerializedPropertyType.Color: if (value is Color color) { property.colorValue = color; return true; } return false;
case SerializedPropertyType.ObjectReference: if (typeof(Object).IsAssignableFrom(value.GetType())) { property.objectReferenceValue = (Object)value; return true; } return false;
case SerializedPropertyType.LayerMask: if (value is LayerMask mask) { property.intValue = mask; return true; } return false;
case SerializedPropertyType.Enum: if (value.GetType().IsEnum || value.GetType() == typeof(Enum)) { return property.SetEnumValue((Enum)value); } return false;
case SerializedPropertyType.Vector2: if (value is Vector2 v2) { property.vector2Value = v2; return true; } return false;
case SerializedPropertyType.Vector3: if (value is Vector3 v3) { property.vector3Value = v3; return true; } return false;
case SerializedPropertyType.Vector4: if (value is Vector4 v4) { property.vector4Value = v4; return true; } return false;
case SerializedPropertyType.Rect: if (value is Rect rect) { property.rectValue = rect; return true; } return false;
case SerializedPropertyType.ArraySize: if (value is int size) { property.intValue = size; return true; } return false;
case SerializedPropertyType.Character: if (value is int character) { property.intValue = character; return true; } return false;
case SerializedPropertyType.AnimationCurve: if (value is AnimationCurve curve) { property.animationCurveValue = curve; return true; } return false;
case SerializedPropertyType.Bounds: if (value is Bounds bounds) { property.boundsValue = bounds; return true; } return false;
case SerializedPropertyType.Gradient: if (value is Gradient gradient) { property.SetGradientValue(gradient); return true; } return false;
case SerializedPropertyType.Quaternion: if (value is Quaternion q) { property.quaternionValue = q; return true; } return false;
case SerializedPropertyType.ExposedReference: return false;
case SerializedPropertyType.FixedBufferSize: return false;
case SerializedPropertyType.Vector2Int: if (value is Vector2Int v2i) { property.vector2IntValue = v2i; return true; } return false;
case SerializedPropertyType.Vector3Int: if (value is Vector3Int v3i) { property.vector3IntValue = v3i; return true; } return false;
case SerializedPropertyType.RectInt: if (value is RectInt recti) { property.rectIntValue = recti; return true; } return false;
case SerializedPropertyType.BoundsInt: if (value is BoundsInt boundsi) { property.boundsIntValue = boundsi; return true; } return false;
case SerializedPropertyType.ManagedReference: if (property.GetManagedReferenceFieldType().IsAssignableFrom(value.GetType())) { property.managedReferenceValue = value; return true; } return false;
}
return false;
}
public static Enum GetEnumValue(this SerializedProperty property)
{
var type = property.GetObject<object>().GetType();
return (Enum)Enum.Parse(type, property.intValue.ToString());
}
public static bool SetEnumValue(this SerializedProperty property, Enum value)
{
var index = Array.IndexOf(property.enumNames, value.ToString());
if (index >= 0)
{
property.enumValueIndex = index;
return true;
}
return false;
}
public static void ResizeArray(this SerializedProperty arrayProperty, int newSize)
{
var size = arrayProperty.arraySize;
arrayProperty.arraySize = newSize;
// new items will be a copy of the previous last item so this resets them to their default value
for (var i = size; i < newSize; i++)
SetToDefault(arrayProperty.GetArrayElementAtIndex(i));
}
public static void RemoveFromArray(this SerializedProperty arrayProperty, int index)
{
// If an object is removed from an array of ObjectReference, DeleteArrayElementAtIndex will set the item
// to null instead of removing it. If the entry is already null it will be removed as expected.
var item = arrayProperty.GetArrayElementAtIndex(index);
// TODO: check how this behaves with managedReferenceValue
if (item.propertyType == SerializedPropertyType.ObjectReference && item.objectReferenceValue != null)
item.objectReferenceValue = null;
arrayProperty.DeleteArrayElementAtIndex(index);
}
public static SerializedProperty GetSibling(this SerializedProperty property, string siblingName)
{
var path = property.propertyPath;
var index = property.propertyPath.LastIndexOf('.');
var siblingPath = index > 0 ? path.Substring(0, index) + "." + siblingName : siblingName;
return property.serializedObject.FindProperty(siblingPath);
}
public static SerializedProperty GetParent(this SerializedProperty property)
{
var path = property.propertyPath;
var index = property.propertyPath.LastIndexOf('.');
if (index < 0)
return property.serializedObject.GetIterator();
var parentPath = path.Substring(0, index);
return property.serializedObject.FindProperty(parentPath);
}
public static T GetOwner<T>(this SerializedProperty property) where T : class
{
var index = 1;
var obj = property.GetAncestorObject<object>(index);
while (obj is IList || obj is IDictionary)
obj = property.GetAncestorObject<object>(++index);
return obj as T;
}
public static T GetObject<T>(this SerializedProperty property) where T : class
{
return property.GetAncestorObject<T>(0);
}
public static T GetParentObject<T>(this SerializedProperty property) where T : class
{
return property.GetAncestorObject<T>(1);
}
public static T GetAncestorObject<T>(this SerializedProperty property, int generations) where T : class
{
var obj = (object)property.serializedObject.targetObject;
var elements = property.propertyPath.Replace("Array.data[", "[").Split('.');
var count = elements.Length - generations;
for (var i = 0; i < count; i++)
{
var element = elements[i];
if (element.StartsWith("["))
{
var indexString = element.Substring(1, element.Length - 2);
var index = Convert.ToInt32(indexString);
obj = GetIndexed(obj, index);
}
else
{
obj = obj.GetType().GetField(element, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetValue(obj);
}
}
return obj as T;
}
public static Type GetType(this SerializedProperty property)
{
return GetObject<object>(property).GetType();
}
private static object GetIndexed(object obj, int index)
{
if (obj is Array array)
return array.GetValue(index);
if (obj is IList list)
return list[index];
return null;
}
#endregion
}
} | 412 | 0.907136 | 1 | 0.907136 | game-dev | MEDIA | 0.825001 | game-dev | 0.98828 | 1 | 0.98828 |
HongZhaoHua/jstarcraft-ai | 1,048 | jstarcraft-ai-math/src/test/java/com/jstarcraft/ai/math/structure/MockMessage.java | package com.jstarcraft.ai.math.structure;
import java.util.concurrent.atomic.AtomicInteger;
import com.jstarcraft.ai.math.structure.message.AccumulationMessage;
public class MockMessage implements AccumulationMessage<Float> {
private AtomicInteger attachTimes = new AtomicInteger();
private AtomicInteger detachTimes = new AtomicInteger();
private float value = 0F;
@Override
public void attach(MathMessage message) {
attachTimes.incrementAndGet();
value += MockMessage.class.cast(message).value;
}
@Override
public MathMessage detach() {
detachTimes.incrementAndGet();
MathMessage message = new MockMessage();
return message;
}
@Override
public synchronized void accumulateValue(float value) {
this.value += value;
}
@Override
public Float getValue() {
return value;
}
public int getAttachTimes() {
return attachTimes.get();
}
public int getDetachTimes() {
return detachTimes.get();
}
} | 412 | 0.614609 | 1 | 0.614609 | game-dev | MEDIA | 0.452981 | game-dev | 0.888286 | 1 | 0.888286 |
raquo/Airstream | 6,325 | src/test/scala/com/raquo/airstream/extensions/EitherObservableSpec.scala | package com.raquo.airstream.extensions
import com.raquo.airstream.UnitSpec
import com.raquo.airstream.eventbus.EventBus
import com.raquo.airstream.fixtures.{Effect, TestableOwner}
import com.raquo.airstream.state.Var
import scala.collection.mutable
class EitherObservableSpec extends UnitSpec {
it("EitherObservable: mapLeft, mapRight, mapEither") {
implicit val owner: TestableOwner = new TestableOwner
val bus = new EventBus[Either[Int, String]]
val effects = mutable.Buffer[Effect[_]]()
bus
.events
.mapLeft(_ * 10)
.mapRight(_ + "x")
.foldEither(
left = _.toString + "-left",
right = _ + "-right"
)
.foreach(v => effects += Effect("obs", v))
effects shouldBe mutable.Buffer()
// --
bus.emit(Left(1))
effects shouldBe mutable.Buffer(
Effect("obs", "10-left")
)
effects.clear()
// --
bus.emit(Right("a"))
effects shouldBe mutable.Buffer(
Effect("obs", "ax-right")
)
effects.clear()
// --
bus.emit(Right("b"))
effects shouldBe mutable.Buffer(
Effect("obs", "bx-right")
)
effects.clear()
}
it("EitherStream: splitEither") {
val owner: TestableOwner = new TestableOwner
val innerOwner: TestableOwner = new TestableOwner
val bus = new EventBus[Either[Int, String]]
val effects = mutable.Buffer[Effect[_]]()
var ix = 0
bus
.events
.splitEither(
left = (_, leftS) => {
ix += 1
leftS.foreach(l => effects += Effect(s"left-${ix}", l))(innerOwner)
ix
},
right = (_, rightS) => {
ix += 1
rightS.foreach(r => effects += Effect(s"right-${ix}", r))(innerOwner)
ix
}
)
.foreach(v => effects += Effect("obs", v))(owner)
effects shouldBe mutable.Buffer()
// --
bus.emit(Left(1))
effects shouldBe mutable.Buffer(
Effect("left-1", 1),
Effect("obs", 1)
)
effects.clear()
// --
bus.emit(Left(2))
effects shouldBe mutable.Buffer(
Effect("obs", 1),
Effect("left-1", 2)
)
effects.clear()
// --
innerOwner.killSubscriptions() // switch to right
bus.emit(Right("a"))
effects shouldBe mutable.Buffer(
Effect("right-2", "a"),
Effect("obs", 2),
)
effects.clear()
// --
bus.emit(Right("b"))
effects shouldBe mutable.Buffer(
Effect("obs", 2),
Effect("right-2", "b")
)
effects.clear()
// --
innerOwner.killSubscriptions() // switch to left
bus.emit(Left(3))
effects shouldBe mutable.Buffer(
Effect("left-3", 3),
Effect("obs", 3),
)
effects.clear()
// --
innerOwner.killSubscriptions() // switch to right
bus.emit(Right("c"))
effects shouldBe mutable.Buffer(
Effect("right-4", "c"),
Effect("obs", 4)
)
effects.clear()
}
it("EitherSignal: splitEither") {
val owner: TestableOwner = new TestableOwner
val innerOwner: TestableOwner = new TestableOwner
val _var = Var[Either[Int, String]](Left(0))
val effects = mutable.Buffer[Effect[_]]()
var ix = 0
_var
.signal
.splitEither(
left = (_, leftS) => {
ix += 1
leftS.foreach(l => effects += Effect(s"left-${ix}", l))(innerOwner)
ix
},
right = (_, rightS) => {
ix += 1
rightS.foreach(r => effects += Effect(s"right-${ix}", r))(innerOwner)
ix
}
)
.foreach(v => effects += Effect("obs", v))(owner)
effects shouldBe mutable.Buffer(
Effect("left-1", 0),
Effect("obs", 1)
)
effects.clear()
// --
_var.set(Left(1))
effects shouldBe mutable.Buffer(
Effect("obs", 1),
Effect("left-1", 1)
)
effects.clear()
// --
_var.set(Left(2))
effects shouldBe mutable.Buffer(
Effect("obs", 1),
Effect("left-1", 2)
)
effects.clear()
// --
innerOwner.killSubscriptions() // switch to right
_var.set(Right("a"))
effects shouldBe mutable.Buffer(
Effect("right-2", "a"),
Effect("obs", 2),
)
effects.clear()
// --
_var.set(Right("b"))
effects shouldBe mutable.Buffer(
Effect("obs", 2),
Effect("right-2", "b")
)
effects.clear()
// --
innerOwner.killSubscriptions() // switch to left
_var.set(Left(3))
effects shouldBe mutable.Buffer(
Effect("left-3", 3),
Effect("obs", 3),
)
effects.clear()
// --
innerOwner.killSubscriptions() // switch to right
_var.set(Right("c"))
effects shouldBe mutable.Buffer(
Effect("right-4", "c"),
Effect("obs", 4)
)
effects.clear()
}
it("EitherStream: collectRight") {
val owner: TestableOwner = new TestableOwner
val bus = new EventBus[Either[Int, String]]
val effects = mutable.Buffer[Effect[_]]()
bus
.events
.collectRight
.foreach(v => effects += Effect("obs", v))(owner)
effects shouldBe mutable.Buffer()
// --
bus.emit(Left(1))
effects.toList shouldBe Nil
// --
bus.emit(Right("a"))
effects.toList shouldBe List(
Effect("obs", "a")
)
effects.clear()
// --
bus.emit(Right("b"))
effects.toList shouldBe List(
Effect("obs", "b")
)
effects.clear()
// --
bus.emit(Left(2))
effects.toList shouldBe Nil
}
it("EitherStream: collectRight()") {
val owner: TestableOwner = new TestableOwner
val bus = new EventBus[Either[Int, String]]
val effects = mutable.Buffer[Effect[_]]()
bus
.events
.collectRight { case "a" => true }
.foreach(v => effects += Effect("obs", v))(owner)
effects shouldBe mutable.Buffer()
// --
bus.emit(Left(1))
effects.toList shouldBe Nil
// --
bus.emit(Right("a"))
effects.toList shouldBe List(
Effect("obs", true)
)
effects.clear()
// --
bus.emit(Right("b"))
effects.toList shouldBe Nil
effects.clear()
// --
bus.emit(Right("a"))
effects.toList shouldBe List(
Effect("obs", true)
)
effects.clear()
// --
bus.emit(Left(2))
effects.toList shouldBe Nil
}
}
| 412 | 0.898541 | 1 | 0.898541 | game-dev | MEDIA | 0.664943 | game-dev | 0.776628 | 1 | 0.776628 |
hlrs-vis/covise | 5,980 | src/OpenCOVER/plugins/visit/StarCD/StarCDPlugin.h | #ifndef _STARCD_PLUGIN_H
#define _STARCD_PLUGIN_H
/****************************************************************************\
** (C)1999 RUS **
** **
** Description: Plugin for StarCD simulation coupled to COVISE **
** **
** **
** Author: D. Rainer **
** **
** History: **
** October-99 **
** **
** **
\****************************************************************************/
#include <list>
#include <osg/MatrixTransform>
#include <cover/coVRPluginSupport.h>
using namespace covise;
using namespace opencover;
using namespace vrui;
#include "StarRegion.h"
// order of function calls is:
// newInteractor for set
// addNode for set
// newInteractor for set element
// addNode for set element
// removeObject for set element
// removeNode for set element
// removeObject for set
// remove node for set
class PluginObject;
class StarCDPlugin : public coVRPlugin
{
private:
coInteractor *currentSetInter; //interactor which comes with the set
// we use this interactor to send parameters back
// the interactors from the set elements are not saved
coInteractor *currentObjInter; // interactor of current set element
int numRegions;
int showInteractors;
int counter; // incremented after a set element is added
int interactionOngoing; // true if dragging an interactor
char **regionNameList;
StarRegion **regionList;
StarRegion *activeRegion;
int activeRegionIndex; // -1=off 0 = "vent1" 1 = "vent2" ...
char *currentSetObjName; // pointer to the current covise set
RenderObject *currentObj; // pointer to the current covise element
osg::ref_ptr<osg::Group> objectsRoot;
// button group id for the radio buttons in the submenu
////int subMenuSwitchGroupId;
// buttons in submenu"simcontrol"
static void regionButtonCallback(void* c, buttonSpecCell* spec);
static void switchButtonCallback(void* c, buttonSpecCell* spec);
static void sliderButtonCallback(void* c, buttonSpecCell* spec);
static void dialButtonCallback(void* c, buttonSpecCell* spec);
int numSimControlParams; // number of sim control params
char **simControlParamNameList; // names of the boolean parameters which appear in the menu
osg::Matrixf currentHandMat, initHandMat;
int debug;
int newConfig; // true if object is from a new configuration (different region geometry)
int removed; // true if removeObhject was a real remove not a replace
// in this case the controlSim menu and the regions were removed
// and have to be created in addFeedback as if configuratons is new
bool firsttime;
void createSimControlMenu(coInteractor *inter);
void deleteSimControlMenu();
void updateSimControlMenu(coInteractor *inter);
char residualLabels[200];
char residualNumbers[200];
public:
typedef std::list<PluginObject*> PluginObjectList;
PluginObjectList pluginObjectList;
StarCDPlugin();
~StarCDPlugin();
bool init();
void newInteractor(RenderObject *, coInteractor *i);
void addObject(const RenderObject *, osg::Group *, const RenderObject *, const RenderObject *, const RenderObject *, const RenderObject *);
void removeObject(const char *objName, bool r);
void addNode(osg::Node * node, const RenderObject * obj);
void removeNode(osg::Node * node, bool isGroup, osg::Node *realNode);
// this will be called in PreFrame
void preFrame();
// this will be called if an object with feedback arrives
// keyword SET:
// replace the old ist of region names with the new names
// if the new names are different replace the submenu
// replace list of StarRegion objects
// replace the StarRegion objects
// keyword REGION: set the parameters (not yet implemented)
void getFeedbackInfo(coInteractor *i);
// this will be called if a COVISE object has to be removed
// if obj is the set:
// if replace:
// test if the names changed
// if namesChanged
// delete regionNameList
// delete the submenu
// else
// set
// delete the list of StarRegion objects
// if obj is a geode: delete the StarRegion objects
void getRemoveObjectInfo(const char *objName, int r);
// called if a node is appended to the COVER scene graph
// if obj is the set: create a list of StarRegionsSensor objects
// if obj is a region geometry: create a StarRegionsSensor object
void getAddNodeInfo(osg::Node *node, RenderObject *obj);
// called if a node is removed from the COVER scene graph
// if obj is the set: delete the list of StarRegionsSensor objects
// if obj is a region geometry: delete the StarRegionsSensor object
void getRemoveNodeInfo(osg::Node *node);
char *residualObjectName;
void addResidualMenu(RenderObject *obj);
void removeResidualMenu();
bool showDials;
};
class PluginObject
{
public:
RenderObject *dobj;
PluginObject(RenderObject *d);
~PluginObject();
osg::ref_ptr<osg::Node> node;
char *objName;
};
#endif
| 412 | 0.838111 | 1 | 0.838111 | game-dev | MEDIA | 0.758226 | game-dev | 0.667415 | 1 | 0.667415 |
manisha-v/MineBlaster | 5,070 | codes/Library/PackageCache/com.unity.2d.animation@3.2.11/Editor/SkinningModule/SpriteBoneInfluence/SpriteBoneInfluenceListWidget.cs | using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditorInternal;
namespace UnityEditor.U2D.Animation
{
internal class SpriteBoneInfluenceListWidget : VisualElement
{
public class CustomUxmlFactory : UxmlFactory<SpriteBoneInfluenceListWidget, CustomUxmlTraits> {}
public class CustomUxmlTraits : UxmlTraits {}
static class Contents
{
public static readonly GUIContent PlusSign = new GUIContent("+");
public static readonly GUIContent MinusSign = new GUIContent("-");
}
const float k_AddRemoveButtonWidth = 30f;
public Action onAddBone = () => {};
public Action onRemoveBone = () => {};
public Action<IEnumerable<BoneCache>> onReordered = _ => {};
public Action<IEnumerable<BoneCache>> onSelectionChanged = (s) => {};
public Func<SpriteBoneInflueceToolController> GetController = () => null;
IMGUIContainer m_IMGUIContainer;
ReorderableList m_ReorderableList;
List<BoneCache> m_BoneInfluences = new List<BoneCache>();
bool m_IgnoreSelectionChange = false;
Vector2 m_ScrollPosition = Vector2.zero;
public SpriteBoneInfluenceListWidget()
{
var visualTree = ResourceLoader.Load<VisualTreeAsset>("SkinningModule/SpriteBoneInfluenceListWidget.uxml");
var ve = visualTree.CloneTree().Q("Container");
ve.styleSheets.Add(ResourceLoader.Load<StyleSheet>("SkinningModule/SpriteBoneInfluenceListWidgetStyle.uss"));
if (EditorGUIUtility.isProSkin)
AddToClassList("Dark");
this.Add(ve);
BindElements();
}
void BindElements()
{
m_ReorderableList = new ReorderableList(m_BoneInfluences, typeof(List<BoneCache>), true, false, false, false);
m_ReorderableList.headerHeight = 0;
m_ReorderableList.footerHeight = 0;
m_ReorderableList.drawElementCallback = OnDrawElement;
m_ReorderableList.onSelectCallback = OnListViewSelectionChanged;
m_ReorderableList.onReorderCallback = _ => { onReordered(m_BoneInfluences); };
m_IMGUIContainer = this.Q<IMGUIContainer>();
m_IMGUIContainer.onGUIHandler = OnDrawGUIContainer;
}
void OnDrawElement(Rect rect, int index, bool isActive, bool isFocused)
{
if (m_BoneInfluences != null && m_BoneInfluences.Count > index)
EditorGUI.LabelField(rect, m_BoneInfluences[index].name);
}
void OnAddCallback()
{
onAddBone();
OnListViewSelectionChanged(m_ReorderableList);
}
void OnRemoveCallback()
{
onRemoveBone();
OnListViewSelectionChanged(m_ReorderableList);
}
void OnListViewSelectionChanged(ReorderableList list)
{
if (m_IgnoreSelectionChange)
return;
var selectedBones = new List<BoneCache>()
{
m_BoneInfluences.Count > 0 ? m_BoneInfluences[list.index] : null
};
onSelectionChanged(selectedBones);
}
void OnDrawGUIContainer()
{
m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition,
false,
false,
GUILayout.Height(GetScrollViewHeight()));
if(m_BoneInfluences != null)
m_ReorderableList.DoLayoutList();
EditorGUILayout.EndScrollView();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.enabled = IsAddButtonEnabled();
if(GUILayout.Button(Contents.PlusSign, GUILayout.Width(k_AddRemoveButtonWidth)))
OnAddCallback();
GUI.enabled = IsRemoveButtonEnabled();
if(GUILayout.Button(Contents.MinusSign, GUILayout.Width(k_AddRemoveButtonWidth)))
OnRemoveCallback();
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
}
bool IsAddButtonEnabled() => GetController().ShouldEnableAddButton(m_BoneInfluences);
bool IsRemoveButtonEnabled() => GetController().InCharacterMode() && m_BoneInfluences.Count > 0 && m_ReorderableList.index >= 0;
float GetScrollViewHeight() => Mathf.Min(m_ReorderableList.GetHeight(), 130f);
public void Update()
{
m_BoneInfluences = GetController().GetSelectedSpriteBoneInfluence().ToList();
m_ReorderableList.list = m_BoneInfluences;
}
internal void OnBoneSelectionChanged()
{
var selectedBones = GetController().GetSelectedBoneForList(m_BoneInfluences);
m_IgnoreSelectionChange = true;
m_ReorderableList.index = selectedBones.Length > 0 ? selectedBones[0] : 0;
m_IgnoreSelectionChange = false;
}
}
}
| 412 | 0.904497 | 1 | 0.904497 | game-dev | MEDIA | 0.750652 | game-dev,desktop-app | 0.960681 | 1 | 0.960681 |
SimonBaars/AdventOfCode-Java | 3,730 | src/main/java/com/sbaars/adventofcode/year23/days/Day22.java | package com.sbaars.adventofcode.year23.days;
import com.sbaars.adventofcode.common.location.Loc3D;
import com.sbaars.adventofcode.year23.Day2023;
import java.util.*;
import static com.sbaars.adventofcode.util.DataMapper.readString;
public class Day22 extends Day2023 {
public Day22() {
super(22);
}
public static void main(String[] args) {
new Day22().printParts();
}
static int idCounter = 0;
public record Brick(int id, List<Loc3D> cubes) {
public Brick(long x1, long y1, long z1, long x2, long y2, long z2) {
this(idCounter++, new Loc3D(x1, y1, z1).lineTo(new Loc3D(x2, y2, z2)));
}
}
@Override
public Object part1() {
return solve(true);
}
@Override
public Object part2() {
return solve(false);
}
private long solve(boolean part1) {
var bricks = dayStream()
.map(s -> readString(s, "%n,%n,%n~%n,%n,%n", Brick.class))
.sorted(Comparator.comparingLong(b -> b.cubes.get(0).z))
.toList();
var settledBricks = dropBricks(bricks);
var supportedBy = new HashMap<Brick, Set<Brick>>();
var supports = new HashMap<Brick, Set<Brick>>();
settledBricks.forEach(b -> {
supportedBy.put(b, new HashSet<>());
supports.put(b, new HashSet<>());
});
settledBricks.forEach(upper ->
settledBricks.stream()
.filter(lower -> !lower.equals(upper) && isSupporting(lower, upper))
.forEach(lower -> {
supportedBy.get(upper).add(lower);
supports.get(lower).add(upper);
}));
if (part1) {
return settledBricks.stream()
.filter(b -> supports.get(b).stream()
.allMatch(supported -> supportedBy.get(supported).size() > 1))
.count();
}
return settledBricks.stream()
.mapToLong(brick -> {
Set<Brick> falling = new HashSet<>();
falling.add(brick);
Queue<Brick> queue = new ArrayDeque<>(supports.get(brick));
while (!queue.isEmpty()) {
Brick current = queue.poll();
if (!falling.contains(current) &&
supportedBy.get(current).stream().allMatch(falling::contains)) {
falling.add(current);
queue.addAll(supports.get(current));
}
}
return falling.size() - 1;
}).sum();
}
private boolean isSupporting(Brick lower, Brick upper) {
return lower.cubes().stream().anyMatch(c ->
upper.cubes.stream().anyMatch(uc ->
uc.x == c.x && uc.y == c.y && uc.z == c.z + 1));
}
private Set<Brick> dropBricks(List<Brick> bricks) {
Set<Brick> result = new HashSet<>();
Map<Loc3D, Brick> occupiedSpaces = new HashMap<>();
for (Brick brick : bricks) {
List<Loc3D> newPos = new ArrayList<>(brick.cubes);
long maxZ = brick.cubes.stream()
.mapToLong(cube -> {
for (long z = cube.z - 1; z >= 1; z--) {
if (occupiedSpaces.containsKey(new Loc3D(cube.x, cube.y, z))) {
return z + 1;
}
}
return 1L;
})
.max()
.orElse(1L);
long drop = brick.cubes.get(0).z - maxZ;
for (int i = 0; i < newPos.size(); i++) {
Loc3D cube = newPos.get(i);
newPos.set(i, new Loc3D(cube.x, cube.y, cube.z - drop));
}
Brick droppedBrick = new Brick(brick.id, newPos);
result.add(droppedBrick);
droppedBrick.cubes.forEach(cube -> occupiedSpaces.put(cube, droppedBrick));
}
return result;
}
}
| 412 | 0.871591 | 1 | 0.871591 | game-dev | MEDIA | 0.499838 | game-dev | 0.911621 | 1 | 0.911621 |
andr3wmac/Torque6 | 4,740 | lib/bullet/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/// This file was created by Alex Silverman
#ifndef BT_BVH_TRIANGLE_MATERIAL_MESH_SHAPE_H
#define BT_BVH_TRIANGLE_MATERIAL_MESH_SHAPE_H
#include "btBvhTriangleMeshShape.h"
#include "btMaterial.h"
///The BvhTriangleMaterialMeshShape extends the btBvhTriangleMeshShape. Its main contribution is the interface into a material array, which allows per-triangle friction and restitution.
ATTRIBUTE_ALIGNED16(class) btMultimaterialTriangleMeshShape : public btBvhTriangleMeshShape
{
btAlignedObjectArray <btMaterial*> m_materialList;
int ** m_triangleMaterials;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btMultimaterialTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression, bool buildBvh = true):
btBvhTriangleMeshShape(meshInterface, useQuantizedAabbCompression, buildBvh)
{
m_shapeType = MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE;
const unsigned char *vertexbase;
int numverts;
PHY_ScalarType type;
int stride;
const unsigned char *indexbase;
int indexstride;
int numfaces;
PHY_ScalarType indicestype;
//m_materialLookup = (int**)(btAlignedAlloc(sizeof(int*) * meshInterface->getNumSubParts(), 16));
for(int i = 0; i < meshInterface->getNumSubParts(); i++)
{
m_meshInterface->getLockedReadOnlyVertexIndexBase(
&vertexbase,
numverts,
type,
stride,
&indexbase,
indexstride,
numfaces,
indicestype,
i);
//m_materialLookup[i] = (int*)(btAlignedAlloc(sizeof(int) * numfaces, 16));
}
}
///optionally pass in a larger bvh aabb, used for quantization. This allows for deformations within this aabb
btMultimaterialTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression,const btVector3& bvhAabbMin,const btVector3& bvhAabbMax, bool buildBvh = true):
btBvhTriangleMeshShape(meshInterface, useQuantizedAabbCompression, bvhAabbMin, bvhAabbMax, buildBvh)
{
m_shapeType = MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE;
const unsigned char *vertexbase;
int numverts;
PHY_ScalarType type;
int stride;
const unsigned char *indexbase;
int indexstride;
int numfaces;
PHY_ScalarType indicestype;
//m_materialLookup = (int**)(btAlignedAlloc(sizeof(int*) * meshInterface->getNumSubParts(), 16));
for(int i = 0; i < meshInterface->getNumSubParts(); i++)
{
m_meshInterface->getLockedReadOnlyVertexIndexBase(
&vertexbase,
numverts,
type,
stride,
&indexbase,
indexstride,
numfaces,
indicestype,
i);
//m_materialLookup[i] = (int*)(btAlignedAlloc(sizeof(int) * numfaces * 2, 16));
}
}
virtual ~btMultimaterialTriangleMeshShape()
{
/*
for(int i = 0; i < m_meshInterface->getNumSubParts(); i++)
{
btAlignedFree(m_materialValues[i]);
m_materialLookup[i] = NULL;
}
btAlignedFree(m_materialValues);
m_materialLookup = NULL;
*/
}
//debugging
virtual const char* getName()const {return "MULTIMATERIALTRIANGLEMESH";}
///Obtains the material for a specific triangle
const btMaterial * getMaterialProperties(int partID, int triIndex);
}
;
#endif //BT_BVH_TRIANGLE_MATERIAL_MESH_SHAPE_H
| 412 | 0.966196 | 1 | 0.966196 | game-dev | MEDIA | 0.90353 | game-dev | 0.976276 | 1 | 0.976276 |
EricDDK/billiards_cocos2d | 7,075 | Billiards/frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/Armature.lua |
--------------------------------
-- @module Armature
-- @extend Node,BlendProtocol
-- @parent_module ccs
--------------------------------
-- Get a bone with the specified name<br>
-- param name The bone's name you want to get
-- @function [parent=#Armature] getBone
-- @param self
-- @param #string name
-- @return Bone#Bone ret (return value: ccs.Bone)
--------------------------------
-- Change a bone's parent with the specified parent name.<br>
-- param bone The bone you want to change parent<br>
-- param parentName The new parent's name.
-- @function [parent=#Armature] changeBoneParent
-- @param self
-- @param #ccs.Bone bone
-- @param #string parentName
-- @return Armature#Armature self (return value: ccs.Armature)
--------------------------------
--
-- @function [parent=#Armature] setAnimation
-- @param self
-- @param #ccs.ArmatureAnimation animation
-- @return Armature#Armature self (return value: ccs.Armature)
--------------------------------
--
-- @function [parent=#Armature] getBoneAtPoint
-- @param self
-- @param #float x
-- @param #float y
-- @return Bone#Bone ret (return value: ccs.Bone)
--------------------------------
--
-- @function [parent=#Armature] getArmatureTransformDirty
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Armature] setVersion
-- @param self
-- @param #float version
-- @return Armature#Armature self (return value: ccs.Armature)
--------------------------------
-- Set contentsize and Calculate anchor point.
-- @function [parent=#Armature] updateOffsetPoint
-- @param self
-- @return Armature#Armature self (return value: ccs.Armature)
--------------------------------
--
-- @function [parent=#Armature] getParentBone
-- @param self
-- @return Bone#Bone ret (return value: ccs.Bone)
--------------------------------
-- Remove a bone with the specified name. If recursion it will also remove child Bone recursionly.<br>
-- param bone The bone you want to remove<br>
-- param recursion Determine whether remove the bone's child recursion.
-- @function [parent=#Armature] removeBone
-- @param self
-- @param #ccs.Bone bone
-- @param #bool recursion
-- @return Armature#Armature self (return value: ccs.Armature)
--------------------------------
--
-- @function [parent=#Armature] getBatchNode
-- @param self
-- @return BatchNode#BatchNode ret (return value: ccs.BatchNode)
--------------------------------
-- @overload self, string, ccs.Bone
-- @overload self, string
-- @function [parent=#Armature] init
-- @param self
-- @param #string name
-- @param #ccs.Bone parentBone
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Armature] setParentBone
-- @param self
-- @param #ccs.Bone parentBone
-- @return Armature#Armature self (return value: ccs.Armature)
--------------------------------
--
-- @function [parent=#Armature] setBatchNode
-- @param self
-- @param #ccs.BatchNode batchNode
-- @return Armature#Armature self (return value: ccs.Armature)
--------------------------------
-- js NA<br>
-- lua NA
-- @function [parent=#Armature] getBlendFunc
-- @param self
-- @return BlendFunc#BlendFunc ret (return value: cc.BlendFunc)
--------------------------------
--
-- @function [parent=#Armature] setArmatureData
-- @param self
-- @param #ccs.ArmatureData armatureData
-- @return Armature#Armature self (return value: ccs.Armature)
--------------------------------
-- Add a Bone to this Armature,<br>
-- param bone The Bone you want to add to Armature<br>
-- param parentName The parent Bone's name you want to add to . If it's nullptr, then set Armature to its parent
-- @function [parent=#Armature] addBone
-- @param self
-- @param #ccs.Bone bone
-- @param #string parentName
-- @return Armature#Armature self (return value: ccs.Armature)
--------------------------------
--
-- @function [parent=#Armature] getArmatureData
-- @param self
-- @return ArmatureData#ArmatureData ret (return value: ccs.ArmatureData)
--------------------------------
--
-- @function [parent=#Armature] getVersion
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#Armature] getAnimation
-- @param self
-- @return ArmatureAnimation#ArmatureAnimation ret (return value: ccs.ArmatureAnimation)
--------------------------------
--
-- @function [parent=#Armature] getOffsetPoints
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
-- js NA<br>
-- lua NA
-- @function [parent=#Armature] setBlendFunc
-- @param self
-- @param #cc.BlendFunc blendFunc
-- @return Armature#Armature self (return value: ccs.Armature)
--------------------------------
-- Get Armature's bone dictionary<br>
-- return Armature's bone dictionary
-- @function [parent=#Armature] getBoneDic
-- @param self
-- @return map_table#map_table ret (return value: map_table)
--------------------------------
-- @overload self, string
-- @overload self
-- @overload self, string, ccs.Bone
-- @function [parent=#Armature] create
-- @param self
-- @param #string name
-- @param #ccs.Bone parentBone
-- @return Armature#Armature ret (return value: ccs.Armature)
--------------------------------
--
-- @function [parent=#Armature] setAnchorPoint
-- @param self
-- @param #vec2_table point
-- @return Armature#Armature self (return value: ccs.Armature)
--------------------------------
--
-- @function [parent=#Armature] draw
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table transform
-- @param #unsigned int flags
-- @return Armature#Armature self (return value: ccs.Armature)
--------------------------------
--
-- @function [parent=#Armature] getAnchorPointInPoints
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
--
-- @function [parent=#Armature] update
-- @param self
-- @param #float dt
-- @return Armature#Armature self (return value: ccs.Armature)
--------------------------------
-- Init the empty armature
-- @function [parent=#Armature] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Armature] getNodeToParentTransform
-- @param self
-- @return mat4_table#mat4_table ret (return value: mat4_table)
--------------------------------
-- This boundingBox will calculate all bones' boundingBox every time
-- @function [parent=#Armature] getBoundingBox
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)
--------------------------------
-- js ctor
-- @function [parent=#Armature] Armature
-- @param self
-- @return Armature#Armature self (return value: ccs.Armature)
return nil
| 412 | 0.847837 | 1 | 0.847837 | game-dev | MEDIA | 0.556826 | game-dev | 0.5469 | 1 | 0.5469 |
acidicoala/SmokeAPI | 24,455 | res/steamworks/145/headers/steam/isteamuserstats.h | //====== Copyright � 1996-2009, Valve Corporation, All rights reserved. =======
//
// Purpose: interface to stats, achievements, and leaderboards
//
//=============================================================================
#ifndef ISTEAMUSERSTATS_H
#define ISTEAMUSERSTATS_H
#ifdef _WIN32
#pragma once
#endif
#include "steam_api_common.h"
#include "isteamremotestorage.h"
// size limit on stat or achievement name (UTF-8 encoded)
enum { k_cchStatNameMax = 128 };
// maximum number of bytes for a leaderboard name (UTF-8 encoded)
enum { k_cchLeaderboardNameMax = 128 };
// maximum number of details int32's storable for a single leaderboard entry
enum { k_cLeaderboardDetailsMax = 64 };
// handle to a single leaderboard
typedef uint64 SteamLeaderboard_t;
// handle to a set of downloaded entries in a leaderboard
typedef uint64 SteamLeaderboardEntries_t;
// type of data request, when downloading leaderboard entries
enum ELeaderboardDataRequest
{
k_ELeaderboardDataRequestGlobal = 0,
k_ELeaderboardDataRequestGlobalAroundUser = 1,
k_ELeaderboardDataRequestFriends = 2,
k_ELeaderboardDataRequestUsers = 3
};
// the sort order of a leaderboard
enum ELeaderboardSortMethod
{
k_ELeaderboardSortMethodNone = 0,
k_ELeaderboardSortMethodAscending = 1, // top-score is lowest number
k_ELeaderboardSortMethodDescending = 2, // top-score is highest number
};
// the display type (used by the Steam Community web site) for a leaderboard
enum ELeaderboardDisplayType
{
k_ELeaderboardDisplayTypeNone = 0,
k_ELeaderboardDisplayTypeNumeric = 1, // simple numerical score
k_ELeaderboardDisplayTypeTimeSeconds = 2, // the score represents a time, in seconds
k_ELeaderboardDisplayTypeTimeMilliSeconds = 3, // the score represents a time, in milliseconds
};
enum ELeaderboardUploadScoreMethod
{
k_ELeaderboardUploadScoreMethodNone = 0,
k_ELeaderboardUploadScoreMethodKeepBest = 1, // Leaderboard will keep user's best score
k_ELeaderboardUploadScoreMethodForceUpdate = 2, // Leaderboard will always replace score with specified
};
// a single entry in a leaderboard, as returned by GetDownloadedLeaderboardEntry()
#if defined( VALVE_CALLBACK_PACK_SMALL )
#pragma pack( push, 4 )
#elif defined( VALVE_CALLBACK_PACK_LARGE )
#pragma pack( push, 8 )
#else
#error steam_api_common.h should define VALVE_CALLBACK_PACK_xxx
#endif
struct LeaderboardEntry_t
{
CSteamID m_steamIDUser; // user with the entry - use SteamFriends()->GetFriendPersonaName() & SteamFriends()->GetFriendAvatar() to get more info
int32 m_nGlobalRank; // [1..N], where N is the number of users with an entry in the leaderboard
int32 m_nScore; // score as set in the leaderboard
int32 m_cDetails; // number of int32 details available for this entry
UGCHandle_t m_hUGC; // handle for UGC attached to the entry
};
#pragma pack( pop )
//-----------------------------------------------------------------------------
// Purpose: Functions for accessing stats, achievements, and leaderboard information
//-----------------------------------------------------------------------------
class ISteamUserStats
{
public:
// Ask the server to send down this user's data and achievements for this game
STEAM_CALL_BACK( UserStatsReceived_t )
virtual bool RequestCurrentStats() = 0;
// Data accessors
virtual bool GetStat( const char *pchName, int32 *pData ) = 0;
virtual bool GetStat( const char *pchName, float *pData ) = 0;
// Set / update data
virtual bool SetStat( const char *pchName, int32 nData ) = 0;
virtual bool SetStat( const char *pchName, float fData ) = 0;
virtual bool UpdateAvgRateStat( const char *pchName, float flCountThisSession, double dSessionLength ) = 0;
// Achievement flag accessors
virtual bool GetAchievement( const char *pchName, bool *pbAchieved ) = 0;
virtual bool SetAchievement( const char *pchName ) = 0;
virtual bool ClearAchievement( const char *pchName ) = 0;
// Get the achievement status, and the time it was unlocked if unlocked.
// If the return value is true, but the unlock time is zero, that means it was unlocked before Steam
// began tracking achievement unlock times (December 2009). Time is seconds since January 1, 1970.
virtual bool GetAchievementAndUnlockTime( const char *pchName, bool *pbAchieved, uint32 *punUnlockTime ) = 0;
// Store the current data on the server, will get a callback when set
// And one callback for every new achievement
//
// If the callback has a result of k_EResultInvalidParam, one or more stats
// uploaded has been rejected, either because they broke constraints
// or were out of date. In this case the server sends back updated values.
// The stats should be re-iterated to keep in sync.
virtual bool StoreStats() = 0;
// Achievement / GroupAchievement metadata
// Gets the icon of the achievement, which is a handle to be used in ISteamUtils::GetImageRGBA(), or 0 if none set.
// A return value of 0 may indicate we are still fetching data, and you can wait for the UserAchievementIconFetched_t callback
// which will notify you when the bits are ready. If the callback still returns zero, then there is no image set for the
// specified achievement.
virtual int GetAchievementIcon( const char *pchName ) = 0;
// Get general attributes for an achievement. Accepts the following keys:
// - "name" and "desc" for retrieving the localized achievement name and description (returned in UTF8)
// - "hidden" for retrieving if an achievement is hidden (returns "0" when not hidden, "1" when hidden)
virtual const char *GetAchievementDisplayAttribute( const char *pchName, const char *pchKey ) = 0;
// Achievement progress - triggers an AchievementProgress callback, that is all.
// Calling this w/ N out of N progress will NOT set the achievement, the game must still do that.
virtual bool IndicateAchievementProgress( const char *pchName, uint32 nCurProgress, uint32 nMaxProgress ) = 0;
// Used for iterating achievements. In general games should not need these functions because they should have a
// list of existing achievements compiled into them
virtual uint32 GetNumAchievements() = 0;
// Get achievement name iAchievement in [0,GetNumAchievements)
virtual const char *GetAchievementName( uint32 iAchievement ) = 0;
// Friends stats & achievements
// downloads stats for the user
// returns a UserStatsReceived_t received when completed
// if the other user has no stats, UserStatsReceived_t.m_eResult will be set to k_EResultFail
// these stats won't be auto-updated; you'll need to call RequestUserStats() again to refresh any data
STEAM_CALL_RESULT( UserStatsReceived_t )
virtual SteamAPICall_t RequestUserStats( CSteamID steamIDUser ) = 0;
// requests stat information for a user, usable after a successful call to RequestUserStats()
virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, int32 *pData ) = 0;
virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, float *pData ) = 0;
virtual bool GetUserAchievement( CSteamID steamIDUser, const char *pchName, bool *pbAchieved ) = 0;
// See notes for GetAchievementAndUnlockTime above
virtual bool GetUserAchievementAndUnlockTime( CSteamID steamIDUser, const char *pchName, bool *pbAchieved, uint32 *punUnlockTime ) = 0;
// Reset stats
virtual bool ResetAllStats( bool bAchievementsToo ) = 0;
// Leaderboard functions
// asks the Steam back-end for a leaderboard by name, and will create it if it's not yet
// This call is asynchronous, with the result returned in LeaderboardFindResult_t
STEAM_CALL_RESULT(LeaderboardFindResult_t)
virtual SteamAPICall_t FindOrCreateLeaderboard( const char *pchLeaderboardName, ELeaderboardSortMethod eLeaderboardSortMethod, ELeaderboardDisplayType eLeaderboardDisplayType ) = 0;
// as above, but won't create the leaderboard if it's not found
// This call is asynchronous, with the result returned in LeaderboardFindResult_t
STEAM_CALL_RESULT( LeaderboardFindResult_t )
virtual SteamAPICall_t FindLeaderboard( const char *pchLeaderboardName ) = 0;
// returns the name of a leaderboard
virtual const char *GetLeaderboardName( SteamLeaderboard_t hSteamLeaderboard ) = 0;
// returns the total number of entries in a leaderboard, as of the last request
virtual int GetLeaderboardEntryCount( SteamLeaderboard_t hSteamLeaderboard ) = 0;
// returns the sort method of the leaderboard
virtual ELeaderboardSortMethod GetLeaderboardSortMethod( SteamLeaderboard_t hSteamLeaderboard ) = 0;
// returns the display type of the leaderboard
virtual ELeaderboardDisplayType GetLeaderboardDisplayType( SteamLeaderboard_t hSteamLeaderboard ) = 0;
// Asks the Steam back-end for a set of rows in the leaderboard.
// This call is asynchronous, with the result returned in LeaderboardScoresDownloaded_t
// LeaderboardScoresDownloaded_t will contain a handle to pull the results from GetDownloadedLeaderboardEntries() (below)
// You can ask for more entries than exist, and it will return as many as do exist.
// k_ELeaderboardDataRequestGlobal requests rows in the leaderboard from the full table, with nRangeStart & nRangeEnd in the range [1, TotalEntries]
// k_ELeaderboardDataRequestGlobalAroundUser requests rows around the current user, nRangeStart being negate
// e.g. DownloadLeaderboardEntries( hLeaderboard, k_ELeaderboardDataRequestGlobalAroundUser, -3, 3 ) will return 7 rows, 3 before the user, 3 after
// k_ELeaderboardDataRequestFriends requests all the rows for friends of the current user
STEAM_CALL_RESULT( LeaderboardScoresDownloaded_t )
virtual SteamAPICall_t DownloadLeaderboardEntries( SteamLeaderboard_t hSteamLeaderboard, ELeaderboardDataRequest eLeaderboardDataRequest, int nRangeStart, int nRangeEnd ) = 0;
// as above, but downloads leaderboard entries for an arbitrary set of users - ELeaderboardDataRequest is k_ELeaderboardDataRequestUsers
// if a user doesn't have a leaderboard entry, they won't be included in the result
// a max of 100 users can be downloaded at a time, with only one outstanding call at a time
STEAM_METHOD_DESC(Downloads leaderboard entries for an arbitrary set of users - ELeaderboardDataRequest is k_ELeaderboardDataRequestUsers)
STEAM_CALL_RESULT( LeaderboardScoresDownloaded_t )
virtual SteamAPICall_t DownloadLeaderboardEntriesForUsers( SteamLeaderboard_t hSteamLeaderboard,
STEAM_ARRAY_COUNT_D(cUsers, Array of users to retrieve) CSteamID *prgUsers, int cUsers ) = 0;
// Returns data about a single leaderboard entry
// use a for loop from 0 to LeaderboardScoresDownloaded_t::m_cEntryCount to get all the downloaded entries
// e.g.
// void OnLeaderboardScoresDownloaded( LeaderboardScoresDownloaded_t *pLeaderboardScoresDownloaded )
// {
// for ( int index = 0; index < pLeaderboardScoresDownloaded->m_cEntryCount; index++ )
// {
// LeaderboardEntry_t leaderboardEntry;
// int32 details[3]; // we know this is how many we've stored previously
// GetDownloadedLeaderboardEntry( pLeaderboardScoresDownloaded->m_hSteamLeaderboardEntries, index, &leaderboardEntry, details, 3 );
// assert( leaderboardEntry.m_cDetails == 3 );
// ...
// }
// once you've accessed all the entries, the data will be free'd, and the SteamLeaderboardEntries_t handle will become invalid
virtual bool GetDownloadedLeaderboardEntry( SteamLeaderboardEntries_t hSteamLeaderboardEntries, int index, LeaderboardEntry_t *pLeaderboardEntry, int32 *pDetails, int cDetailsMax ) = 0;
// Uploads a user score to the Steam back-end.
// This call is asynchronous, with the result returned in LeaderboardScoreUploaded_t
// Details are extra game-defined information regarding how the user got that score
// pScoreDetails points to an array of int32's, cScoreDetailsCount is the number of int32's in the list
STEAM_CALL_RESULT( LeaderboardScoreUploaded_t )
virtual SteamAPICall_t UploadLeaderboardScore( SteamLeaderboard_t hSteamLeaderboard, ELeaderboardUploadScoreMethod eLeaderboardUploadScoreMethod, int32 nScore, const int32 *pScoreDetails, int cScoreDetailsCount ) = 0;
// Attaches a piece of user generated content the user's entry on a leaderboard.
// hContent is a handle to a piece of user generated content that was shared using ISteamUserRemoteStorage::FileShare().
// This call is asynchronous, with the result returned in LeaderboardUGCSet_t.
STEAM_CALL_RESULT( LeaderboardUGCSet_t )
virtual SteamAPICall_t AttachLeaderboardUGC( SteamLeaderboard_t hSteamLeaderboard, UGCHandle_t hUGC ) = 0;
// Retrieves the number of players currently playing your game (online + offline)
// This call is asynchronous, with the result returned in NumberOfCurrentPlayers_t
STEAM_CALL_RESULT( NumberOfCurrentPlayers_t )
virtual SteamAPICall_t GetNumberOfCurrentPlayers() = 0;
// Requests that Steam fetch data on the percentage of players who have received each achievement
// for the game globally.
// This call is asynchronous, with the result returned in GlobalAchievementPercentagesReady_t.
STEAM_CALL_RESULT( GlobalAchievementPercentagesReady_t )
virtual SteamAPICall_t RequestGlobalAchievementPercentages() = 0;
// Get the info on the most achieved achievement for the game, returns an iterator index you can use to fetch
// the next most achieved afterwards. Will return -1 if there is no data on achievement
// percentages (ie, you haven't called RequestGlobalAchievementPercentages and waited on the callback).
virtual int GetMostAchievedAchievementInfo( char *pchName, uint32 unNameBufLen, float *pflPercent, bool *pbAchieved ) = 0;
// Get the info on the next most achieved achievement for the game. Call this after GetMostAchievedAchievementInfo or another
// GetNextMostAchievedAchievementInfo call passing the iterator from the previous call. Returns -1 after the last
// achievement has been iterated.
virtual int GetNextMostAchievedAchievementInfo( int iIteratorPrevious, char *pchName, uint32 unNameBufLen, float *pflPercent, bool *pbAchieved ) = 0;
// Returns the percentage of users who have achieved the specified achievement.
virtual bool GetAchievementAchievedPercent( const char *pchName, float *pflPercent ) = 0;
// Requests global stats data, which is available for stats marked as "aggregated".
// This call is asynchronous, with the results returned in GlobalStatsReceived_t.
// nHistoryDays specifies how many days of day-by-day history to retrieve in addition
// to the overall totals. The limit is 60.
STEAM_CALL_RESULT( GlobalStatsReceived_t )
virtual SteamAPICall_t RequestGlobalStats( int nHistoryDays ) = 0;
// Gets the lifetime totals for an aggregated stat
virtual bool GetGlobalStat( const char *pchStatName, int64 *pData ) = 0;
virtual bool GetGlobalStat( const char *pchStatName, double *pData ) = 0;
// Gets history for an aggregated stat. pData will be filled with daily values, starting with today.
// So when called, pData[0] will be today, pData[1] will be yesterday, and pData[2] will be two days ago,
// etc. cubData is the size in bytes of the pubData buffer. Returns the number of
// elements actually set.
virtual int32 GetGlobalStatHistory( const char *pchStatName, STEAM_ARRAY_COUNT(cubData) int64 *pData, uint32 cubData ) = 0;
virtual int32 GetGlobalStatHistory( const char *pchStatName, STEAM_ARRAY_COUNT(cubData) double *pData, uint32 cubData ) = 0;
#ifdef _PS3
// Call to kick off installation of the PS3 trophies. This call is asynchronous, and the results will be returned in a PS3TrophiesInstalled_t
// callback.
virtual bool InstallPS3Trophies() = 0;
// Returns the amount of space required at boot to install trophies. This value can be used when comparing the amount of space needed
// by the game to the available space value passed to the game at boot. The value is set during InstallPS3Trophies().
virtual uint64 GetTrophySpaceRequiredBeforeInstall() = 0;
// On PS3, user stats & achievement progress through Steam must be stored with the user's saved game data.
// At startup, before calling RequestCurrentStats(), you must pass the user's stats data to Steam via this method.
// If you do not have any user data, call this function with pvData = NULL and cubData = 0
virtual bool SetUserStatsData( const void *pvData, uint32 cubData ) = 0;
// Call to get the user's current stats data. You should retrieve this data after receiving successful UserStatsReceived_t & UserStatsStored_t
// callbacks, and store the data with the user's save game data. You can call this method with pvData = NULL and cubData = 0 to get the required
// buffer size.
virtual bool GetUserStatsData( void *pvData, uint32 cubData, uint32 *pcubWritten ) = 0;
#endif
};
#define STEAMUSERSTATS_INTERFACE_VERSION "STEAMUSERSTATS_INTERFACE_VERSION011"
// Global interface accessor
inline ISteamUserStats *SteamUserStats();
STEAM_DEFINE_USER_INTERFACE_ACCESSOR( ISteamUserStats *, SteamUserStats, STEAMUSERSTATS_INTERFACE_VERSION );
// callbacks
#if defined( VALVE_CALLBACK_PACK_SMALL )
#pragma pack( push, 4 )
#elif defined( VALVE_CALLBACK_PACK_LARGE )
#pragma pack( push, 8 )
#else
#error steam_api_common.h should define VALVE_CALLBACK_PACK_xxx
#endif
//-----------------------------------------------------------------------------
// Purpose: called when the latests stats and achievements have been received
// from the server
//-----------------------------------------------------------------------------
struct UserStatsReceived_t
{
enum { k_iCallback = k_iSteamUserStatsCallbacks + 1 };
uint64 m_nGameID; // Game these stats are for
EResult m_eResult; // Success / error fetching the stats
CSteamID m_steamIDUser; // The user for whom the stats are retrieved for
};
//-----------------------------------------------------------------------------
// Purpose: result of a request to store the user stats for a game
//-----------------------------------------------------------------------------
struct UserStatsStored_t
{
enum { k_iCallback = k_iSteamUserStatsCallbacks + 2 };
uint64 m_nGameID; // Game these stats are for
EResult m_eResult; // success / error
};
//-----------------------------------------------------------------------------
// Purpose: result of a request to store the achievements for a game, or an
// "indicate progress" call. If both m_nCurProgress and m_nMaxProgress
// are zero, that means the achievement has been fully unlocked.
//-----------------------------------------------------------------------------
struct UserAchievementStored_t
{
enum { k_iCallback = k_iSteamUserStatsCallbacks + 3 };
uint64 m_nGameID; // Game this is for
bool m_bGroupAchievement; // if this is a "group" achievement
char m_rgchAchievementName[k_cchStatNameMax]; // name of the achievement
uint32 m_nCurProgress; // current progress towards the achievement
uint32 m_nMaxProgress; // "out of" this many
};
//-----------------------------------------------------------------------------
// Purpose: call result for finding a leaderboard, returned as a result of FindOrCreateLeaderboard() or FindLeaderboard()
// use CCallResult<> to map this async result to a member function
//-----------------------------------------------------------------------------
struct LeaderboardFindResult_t
{
enum { k_iCallback = k_iSteamUserStatsCallbacks + 4 };
SteamLeaderboard_t m_hSteamLeaderboard; // handle to the leaderboard serarched for, 0 if no leaderboard found
uint8 m_bLeaderboardFound; // 0 if no leaderboard found
};
//-----------------------------------------------------------------------------
// Purpose: call result indicating scores for a leaderboard have been downloaded and are ready to be retrieved, returned as a result of DownloadLeaderboardEntries()
// use CCallResult<> to map this async result to a member function
//-----------------------------------------------------------------------------
struct LeaderboardScoresDownloaded_t
{
enum { k_iCallback = k_iSteamUserStatsCallbacks + 5 };
SteamLeaderboard_t m_hSteamLeaderboard;
SteamLeaderboardEntries_t m_hSteamLeaderboardEntries; // the handle to pass into GetDownloadedLeaderboardEntries()
int m_cEntryCount; // the number of entries downloaded
};
//-----------------------------------------------------------------------------
// Purpose: call result indicating scores has been uploaded, returned as a result of UploadLeaderboardScore()
// use CCallResult<> to map this async result to a member function
//-----------------------------------------------------------------------------
struct LeaderboardScoreUploaded_t
{
enum { k_iCallback = k_iSteamUserStatsCallbacks + 6 };
uint8 m_bSuccess; // 1 if the call was successful
SteamLeaderboard_t m_hSteamLeaderboard; // the leaderboard handle that was
int32 m_nScore; // the score that was attempted to set
uint8 m_bScoreChanged; // true if the score in the leaderboard change, false if the existing score was better
int m_nGlobalRankNew; // the new global rank of the user in this leaderboard
int m_nGlobalRankPrevious; // the previous global rank of the user in this leaderboard; 0 if the user had no existing entry in the leaderboard
};
struct NumberOfCurrentPlayers_t
{
enum { k_iCallback = k_iSteamUserStatsCallbacks + 7 };
uint8 m_bSuccess; // 1 if the call was successful
int32 m_cPlayers; // Number of players currently playing
};
//-----------------------------------------------------------------------------
// Purpose: Callback indicating that a user's stats have been unloaded.
// Call RequestUserStats again to access stats for this user
//-----------------------------------------------------------------------------
struct UserStatsUnloaded_t
{
enum { k_iCallback = k_iSteamUserStatsCallbacks + 8 };
CSteamID m_steamIDUser; // User whose stats have been unloaded
};
//-----------------------------------------------------------------------------
// Purpose: Callback indicating that an achievement icon has been fetched
//-----------------------------------------------------------------------------
struct UserAchievementIconFetched_t
{
enum { k_iCallback = k_iSteamUserStatsCallbacks + 9 };
CGameID m_nGameID; // Game this is for
char m_rgchAchievementName[k_cchStatNameMax]; // name of the achievement
bool m_bAchieved; // Is the icon for the achieved or not achieved version?
int m_nIconHandle; // Handle to the image, which can be used in SteamUtils()->GetImageRGBA(), 0 means no image is set for the achievement
};
//-----------------------------------------------------------------------------
// Purpose: Callback indicating that global achievement percentages are fetched
//-----------------------------------------------------------------------------
struct GlobalAchievementPercentagesReady_t
{
enum { k_iCallback = k_iSteamUserStatsCallbacks + 10 };
uint64 m_nGameID; // Game this is for
EResult m_eResult; // Result of the operation
};
//-----------------------------------------------------------------------------
// Purpose: call result indicating UGC has been uploaded, returned as a result of SetLeaderboardUGC()
//-----------------------------------------------------------------------------
struct LeaderboardUGCSet_t
{
enum { k_iCallback = k_iSteamUserStatsCallbacks + 11 };
EResult m_eResult; // The result of the operation
SteamLeaderboard_t m_hSteamLeaderboard; // the leaderboard handle that was
};
//-----------------------------------------------------------------------------
// Purpose: callback indicating that PS3 trophies have been installed
//-----------------------------------------------------------------------------
struct PS3TrophiesInstalled_t
{
enum { k_iCallback = k_iSteamUserStatsCallbacks + 12 };
uint64 m_nGameID; // Game these stats are for
EResult m_eResult; // The result of the operation
uint64 m_ulRequiredDiskSpace; // If m_eResult is k_EResultDiskFull, will contain the amount of space needed to install trophies
};
//-----------------------------------------------------------------------------
// Purpose: callback indicating global stats have been received.
// Returned as a result of RequestGlobalStats()
//-----------------------------------------------------------------------------
struct GlobalStatsReceived_t
{
enum { k_iCallback = k_iSteamUserStatsCallbacks + 12 };
uint64 m_nGameID; // Game global stats were requested for
EResult m_eResult; // The result of the request
};
#pragma pack( pop )
#endif // ISTEAMUSER_H
| 412 | 0.890054 | 1 | 0.890054 | game-dev | MEDIA | 0.358632 | game-dev | 0.83822 | 1 | 0.83822 |
emileb/OpenGames | 3,734 | opengames/src/main/jni/Doom/gzdoom-g1.8.6/src/g_shared/a_fastprojectile.cpp |
#include "a_sharedglobal.h"
#include "p_local.h"
#include "g_level.h"
#include "r_sky.h"
#include "p_lnspec.h"
IMPLEMENT_CLASS(AFastProjectile)
//----------------------------------------------------------------------------
//
// AFastProjectile :: Tick
//
// Thinker for the ultra-fast projectiles used by Heretic and Hexen
//
//----------------------------------------------------------------------------
void AFastProjectile::Tick ()
{
int i;
fixed_t xfrac;
fixed_t yfrac;
fixed_t zfrac;
int changexy;
PrevX = x;
PrevY = y;
PrevZ = z;
fixed_t oldz = z;
PrevAngle = angle;
if (!(flags5 & MF5_NOTIMEFREEZE))
{
//Added by MC: Freeze mode.
if (bglobal.freeze || level.flags2 & LEVEL2_FROZEN)
{
return;
}
}
// [RH] Ripping is a little different than it was in Hexen
FCheckPosition tm(!!(flags2 & MF2_RIP));
int shift = 3;
int count = 8;
if (radius > 0)
{
while ( ((abs(velx) >> shift) > radius) || ((abs(vely) >> shift) > radius))
{
// we need to take smaller steps.
shift++;
count<<=1;
}
}
// Handle movement
if (velx || vely || (z != floorz) || velz)
{
xfrac = velx >> shift;
yfrac = vely >> shift;
zfrac = velz >> shift;
changexy = xfrac || yfrac;
int ripcount = count >> 3;
for (i = 0; i < count; i++)
{
if (changexy)
{
if (--ripcount <= 0)
{
tm.LastRipped = NULL; // [RH] Do rip damage each step, like Hexen
}
if (!P_TryMove (this, x + xfrac,y + yfrac, true, NULL, tm))
{ // Blocked move
if (!(flags3 & MF3_SKYEXPLODE))
{
if (tm.ceilingline &&
tm.ceilingline->backsector &&
tm.ceilingline->backsector->GetTexture(sector_t::ceiling) == skyflatnum &&
z >= tm.ceilingline->backsector->ceilingplane.ZatPoint (x, y))
{
// Hack to prevent missiles exploding against the sky.
// Does not handle sky floors.
Destroy ();
return;
}
// [RH] Don't explode on horizon lines.
if (BlockingLine != NULL && BlockingLine->special == Line_Horizon)
{
Destroy ();
return;
}
}
P_ExplodeMissile (this, BlockingLine, BlockingMobj);
return;
}
}
z += zfrac;
UpdateWaterLevel (oldz);
oldz = z;
if (z <= floorz)
{ // Hit the floor
if (floorpic == skyflatnum && !(flags3 & MF3_SKYEXPLODE))
{
// [RH] Just remove the missile without exploding it
// if this is a sky floor.
Destroy ();
return;
}
z = floorz;
P_HitFloor (this);
P_ExplodeMissile (this, NULL, NULL);
return;
}
if (z + height > ceilingz)
{ // Hit the ceiling
if (ceilingpic == skyflatnum && !(flags3 & MF3_SKYEXPLODE))
{
Destroy ();
return;
}
z = ceilingz - height;
P_ExplodeMissile (this, NULL, NULL);
return;
}
if (changexy && ripcount <= 0)
{
ripcount = count >> 3;
Effect();
}
}
}
// Advance the state
if (tics != -1)
{
if (tics > 0) tics--;
while (!tics)
{
if (!SetState (state->GetNextState ()))
{ // mobj was removed
return;
}
}
}
}
void AFastProjectile::Effect()
{
//if (pr_smoke() < 128) // [RH] I think it looks better if it's consistent
{
FName name = (ENamedName) this->GetClass()->Meta.GetMetaInt (ACMETA_MissileName, NAME_None);
if (name != NAME_None)
{
fixed_t hitz = z-8*FRACUNIT;
if (hitz < floorz)
{
hitz = floorz;
}
// Do not clip this offset to the floor.
hitz += GetClass()->Meta.GetMetaFixed (ACMETA_MissileHeight);
const PClass *trail = PClass::FindClass(name);
if (trail != NULL)
{
AActor *act = Spawn (trail, x, y, hitz, ALLOW_REPLACE);
if (act != NULL)
{
act->angle = this->angle;
}
}
}
}
}
| 412 | 0.925681 | 1 | 0.925681 | game-dev | MEDIA | 0.939822 | game-dev | 0.985409 | 1 | 0.985409 |
WenhaoYu1998/LDP | 20,255 | data_collection/drlnav_env/src/drl_nav/3rdparty/pedsimros/src/ped_agent.cpp | //
// pedsim - A microscopic pedestrian simulation system.
// Copyright (c) by Christian Gloor
//
#include "ped_agent.h"
#include "ped_waypoint.h"
#include "ped_scene.h"
#include "ped_obstacle.h"
#include <cmath>
#include <algorithm>
#include <random>
#include <iostream>
using namespace std;
default_random_engine generator;
/// Default Constructor
/// \date 2003-12-29
Ped::Tagent::Tagent() {
static int staticid = 0;
id = staticid++;
p.x = 0;
p.y = 0;
p.z = 0;
v.x = 0;
v.y = 0;
v.z = 0;
type = 0;
destination = NULL;
lastdestination = NULL;
follow = -1;
mlLookAhead = false;
scene = NULL;
// assign random maximal speed in m/s
// normal distribution (mean 1.2, std 0.2)
normal_distribution<double> distribution(1.2, 0.2);
vmax = distribution(generator);
factorsocialforce = 2.1;
factorobstacleforce = 1.0; // parameter based on plausible pedsim output, not real measurement!
factordesiredforce = 1.0;
factorlookaheadforce = 1.0;
obstacleForceSigma = 0.8;
agentRadius = 0.2;
relaxationTime = 0.5;
waypointbehavior = BEHAVIOR_CIRCULAR;
}
/// Destructor
/// \date 2012-02-04
Ped::Tagent::~Tagent() {
}
/// Assigns a Tscene to the agent. Tagent uses this to iterate over all
/// obstacles and other agents in a scene. The scene will invoke this function
/// when Tscene::addAgent() is called.
/// \date 2012-01-17
/// \warning Bad things will happen if the agent is not assigned to a scene. But usually, Tscene takes care of that.
/// \param *s A valid Tscene initialized earlier.
void Ped::Tagent::setscene(Ped::Tscene *s) {
scene = s;
}
/// Returns the Tscene assigned to the agent.
/// \date 2012-01-17
/// \warning Bad things will happen if the agent is not assigned to a scene. But usually, Tscene takes care of that.
/// \return *s A Tscene initialized earlier, if one is assigned to the agent.
Ped::Tscene* Ped::Tagent::getscene() {
return scene;
};
/// Adds a TWaypoint to an agent's list of waypoints. Twaypoints are stored in a
/// cyclic queue, the one just visited is pushed to the back again. There will be a
/// flag to change this behavior soon.
/// Adding a waypoint will also selecting the first waypoint in the internal list
/// as the active one, i.e. the first waypoint added will be the first point to
/// headt to, no matter what is added later.
/// \author chgloor
/// \date 2012-01-19
void Ped::Tagent::addWaypoint(Twaypoint *wp) {
waypoints.push_back(wp);
destination = waypoints.front();
}
bool Ped::Tagent::removeWaypoint(const Twaypoint *wp) {
// unset references
if (destination == wp)
destination = NULL;
if (lastdestination == wp)
lastdestination = NULL;
// remove waypoint from list of destinations
bool removed = false;
for (int i = waypoints.size(); i > 0; --i) {
Twaypoint* currentWaypoint = waypoints.front();
waypoints.pop_front();
if (currentWaypoint != wp) {
waypoints.push_back(currentWaypoint);
removed = true;
}
}
return removed;
}
void Ped::Tagent::clearWaypoints() {
// unset references
destination = NULL;
lastdestination = NULL;
// remove all references to the waypoints
// note: don't delete waypoints, because the scene is responsible
for (int i = waypoints.size(); i > 0; --i) {
waypoints.pop_front();
}
}
/*
void Ped::Tagent::removeAgentFromNeighbors(const Ped::Tagent* agentIn) {
// search agent in neighbors, and remove him
set<const Ped::Tagent*>::iterator foundNeighbor = neighbors.find(agentIn);
if (foundNeighbor != neighbors.end()) {
neighbors.erase(foundNeighbor);
}
}
*/ // no longer required
/// Sets the agent ID this agent has to follow. If set, the agent will ignore
/// its assigned waypoints and just follow the other agent.
/// \date 2012-01-08
/// \param id is the agent to follow (must exist, obviously)
/// \todo Add a method that takes a Tagent* as argument
void Ped::Tagent::setFollow(int id) {
follow = id;
}
/// Gets the ID of the agent this agent is following.
/// \date 2012-01-18
/// \return int, the agent id of the agent
/// \todo Add a method that returns a Tagent*
int Ped::Tagent::getFollow() const {
return follow;
}
/// Sets the maximum velocity of an agent (vmax). Even if pushed by other
/// agents, it will not move faster than this.
/// \date 2012-01-08
/// \param pvmax The maximum velocity. In scene units per timestep, multiplied by the simulation's precision h.
void Ped::Tagent::setVmax(double pvmax) {
vmax = pvmax;
}
/// Gets the maximum velocity of an agent (vmax). Even if pushed by other
/// agents, it will not move faster than this.
/// \date 2016-08-10
/// \return The maximum velocity. In scene units per timestep, multiplied by the simulation's precision h.
double Ped::Tagent::getVmax() {
return vmax;
}
/// Sets the agent's position. This, and other getters returning coordinates,
/// will eventually changed to returning a Tvector.
/// \date 2004-02-10
/// \param px Position x
/// \param py Position y
/// \param pz Position z
void Ped::Tagent::setPosition(double px, double py, double pz) {
p.x = px;
p.y = py;
p.z = pz;
}
/// Sets the factor by which the social force is multiplied. Values between 0
/// and about 10 do make sense.
/// \date 2012-01-20
/// \param f The factor
void Ped::Tagent::setfactorsocialforce(double f) {
factorsocialforce = f;
}
/// Sets the factor by which the obstacle force is multiplied. Values between 0
/// and about 10 do make sense.
/// \date 2012-01-20
/// \param f The factor
void Ped::Tagent::setfactorobstacleforce(double f) {
factorobstacleforce = f;
}
/// Sets the factor by which the desired force is multiplied. Values between 0
/// and about 10 do make sense.
/// \date 2012-01-20
/// \param f The factor
void Ped::Tagent::setfactordesiredforce(double f) {
factordesiredforce = f;
}
/// Sets the factor by which the look ahead force is multiplied. Values between
/// 0 and about 10 do make sense.
/// \date 2012-01-20
/// \param f The factor
void Ped::Tagent::setfactorlookaheadforce(double f) {
factorlookaheadforce = f;
}
/// Calculates the force between this agent and the next assigned waypoint. If
/// the waypoint has been reached, the next waypoint in the list will be
/// selected. At the moment, a visited waypoint is pushed back to the end of
/// the list, which means that the agents will visit all the waypoints over and
/// over again. This behavior can be controlled by a flag using setWaypointBehavior().
/// \date 2012-01-17
/// \return Tvector: the calculated force
Ped::Tvector Ped::Tagent::desiredForce() {
// following behavior
if (follow >= 0) {
Tagent* followedAgent = scene->agents.at(follow);
Twaypoint newDestination(followedAgent->getPosition().x, followedAgent->getPosition().y, 0);
newDestination.settype(Ped::Twaypoint::TYPE_POINT);
Ped::Tvector ef = newDestination.getForce(p.x, p.y, 0, 0);
desiredDirection = Ped::Tvector(followedAgent->getPosition().x, followedAgent->getPosition().y);
// walk with full speed if nothing else affects me
return vmax * ef;
}
// waypoint management (fetch new destination if available)
if ((destination == NULL) && (!waypoints.empty())) {
destination = waypoints.front();
waypoints.pop_front();
if (waypointbehavior == Ped::Tagent::BEHAVIOR_CIRCULAR) {
waypoints.push_back(destination);
}
}
// Agent has reached last waypoint, or there never was one.
// if ((destination != NULL) && (waypoints.empty())) {
// destination = NULL;
// }
// if there is no destination, don't move
if (destination == NULL) {
// desiredDirection = Ped::Tvector();
// Tvector antiMove = -v / relaxationTime;
// return antiMove;
// not shure about these lines above
desiredDirection = Ped::Tvector(0, 0, 0);
}
bool reached = false;
if (destination != NULL) {
if (lastdestination == NULL) {
// create a temporary destination of type point, since no normal from last dest is available
Twaypoint tempDestination(destination->getx(), destination->gety(), destination->getr());
tempDestination.settype(Ped::Twaypoint::TYPE_POINT);
desiredDirection = tempDestination.getForce(p.x,
p.y,
0,
0,
&reached);
} else {
desiredDirection = destination->getForce(p.x,
p.y,
lastdestination->getx(),
lastdestination->gety(),
&reached);
}
}
// mark destination as reached for next time step
if ((destination != NULL) && (reached == true)) {
lastdestination = destination;
destination = NULL;
}
// Compute force. This translates to "I want to move into that
// direction at the maximum speed"
Tvector force = desiredDirection.normalized() * vmax;
// cout << force.to_string() << endl;
return force;
}
/// Calculates the social force between this agent and all the other agents
/// belonging to the same scene. It iterates over all agents inside the scene,
/// has therefore complexity \f$O(N^2)\f$. A better agent storing structure in
/// Tscene would fix this. But for small (less than 10000 agents) scenarios,
/// this is just fine.
/// \date 2012-01-17
/// \return Tvector: the calculated force
Ped::Tvector Ped::Tagent::socialForce(const set<const Ped::Tagent*> &neighbors) {
// define relative importance of position vs velocity vector
// (set according to Moussaid-Helbing 2009)
const double lambdaImportance = 2.0;
// define speed interaction
// (set according to Moussaid-Helbing 2009)
const double gamma = 0.35;
// define speed interaction
// (set according to Moussaid-Helbing 2009)
const double n = 2;
// define angular interaction
// (set according to Moussaid-Helbing 2009)
const double n_prime = 3;
Tvector force;
for (const Ped::Tagent* other: neighbors) {
// don't compute social force to yourself
if (other->id == id) continue;
// compute difference between both agents' positions
Tvector diff = other->p - p;
// skip futher computation if they are too far away from each
// other. Should speed up things.
if (diff.lengthSquared() > 64.0) continue; // val to high --chgloor 20160630
Tvector diffDirection = diff.normalized();
// compute difference between both agents' velocity vectors
// Note: the agent-other-order changed here
Tvector velDiff = v - other->v;
// compute interaction direction t_ij
Tvector interactionVector = lambdaImportance * velDiff + diffDirection;
double interactionLength = interactionVector.length();
Tvector interactionDirection = interactionVector / interactionLength;
// compute angle theta (between interaction and position difference vector)
double theta = interactionDirection.angleTo(diffDirection);
int thetaSign = (theta == 0) ? (0) : (theta / abs(theta));
// compute model parameter B = gamma * ||D||
double B = gamma * interactionLength;
// According to paper, this should be the sum of the two forces...
// force += -exp(-diff.length()/B)
// * (exp(-pow(n_prime*B*theta,2)) * interactionDirection
// + exp(-pow(n*B*theta,2)) * interactionDirection.leftNormalVector());
double forceVelocityAmount = -exp(-diff.length()/B - (n_prime*B*theta)*(n_prime*B*theta));
double forceAngleAmount = -thetaSign * exp(-diff.length()/B - (n*B*theta)*(n*B*theta));
Tvector forceVelocity = forceVelocityAmount * interactionDirection;
Tvector forceAngle = forceAngleAmount * interactionDirection.leftNormalVector();
force += forceVelocity + forceAngle;
}
// Old code: (didn't follow papers)
// const double maxDistance = 10.0;
// const double maxDistSquared = maxDistance*maxDistance;
//
// Ped::Tvector force;
// for(set<const Ped::Tagent*>::iterator iter = neighbors.begin(); iter!=neighbors.end(); ++iter) {
// const Ped::Tagent* other = *iter;
//
// // don't compute social force to yourself
// if (other->id == id)
// continue;
//
// // quick distance check
// Ped::Tvector diff = other->p - p;
// if ((abs(diff.x) < maxDistance)
// && (abs(diff.y) < maxDistance)) {
// double dist2 = diff.lengthSquared();
//
// // ignore too small forces
// if (dist2 < maxDistSquared) {
// double expdist = exp(-sqrt(dist2)/socialForceSigma);
// force += -expdist * diff;
// }
// }
// }
return force;
}
/// Calculates the force between this agent and the nearest obstacle in this scene.
/// Iterates over all obstacles == O(N).
/// \date 2012-01-17
/// \return Tvector: the calculated force
Ped::Tvector Ped::Tagent::obstacleForce(const set<const Ped::Tagent*> &neighbors) {
// obstacle which is closest only
Ped::Tvector minDiff;
double minDistanceSquared = INFINITY;
for (const Tobstacle* obstacle : scene->obstacles) {
Ped::Tvector closestPoint = obstacle->closestPoint(p);
Ped::Tvector diff = p - closestPoint;
double distanceSquared = diff.lengthSquared(); // use squared distance to avoid computing square root
if (distanceSquared < minDistanceSquared) {
minDistanceSquared = distanceSquared;
minDiff = diff;
}
}
double distance = sqrt(minDistanceSquared) - agentRadius;
double forceAmount = exp(-distance/obstacleForceSigma);
return forceAmount * minDiff.normalized();
}
/// Calculates the mental layer force of the strategy "look ahead". It is
/// implemented here in the physical layer because of performance reasons. It
/// iterates over all Tagents in the Tscene, complexity \f$O(N^2)\f$.
/// \date 2012-01-17
/// \return Tvector: the calculated force
/// \param e is a vector defining the direction in which the agent should look
/// ahead to. Usually, this is the direction he wants to walk to.
Ped::Tvector Ped::Tagent::lookaheadForce(Ped::Tvector e, const set<const Ped::Tagent*> &neighbors) {
const double pi = 3.14159265;
int lookforwardcount = 0;
for (set<const Ped::Tagent*>::iterator iter = neighbors.begin(); iter!=neighbors.end(); ++iter) {
const Ped::Tagent* other = *iter;
// don't compute this force for the agent himself
if (other->id == id) continue;
double distancex = other->p.x - p.x;
double distancey = other->p.y - p.y;
double dist2 = (distancex * distancex + distancey * distancey); // 2D
if (dist2 < 400) { // look ahead feature
double at2v = atan2(-e.x, -e.y); // was vx, vy --chgloor 2012-01-15
double at2d = atan2(-distancex, -distancey);
double at2v2 = atan2(-other->v.x, -other->v.y);
double s = at2d - at2v;
if (s > pi) s -= 2*pi;
if (s < -pi) s += 2*pi;
double vv = at2v - at2v2;
if (vv > pi) vv -= 2*pi;
if (vv < -pi) vv += 2*pi;
if (abs(vv) > 2.5) { // opposite direction
if ((s < 0) && (s > -0.3)) // position vor mir, in meine richtung
lookforwardcount--;
if ((s > 0) && (s < 0.3))
lookforwardcount++;
}
}
}
Ped::Tvector lf;
if (lookforwardcount < 0) {
lf.x = 0.5f * e.y; // was vx, vy --chgloor 2012-01-15
lf.y = 0.5f * -e.x;
}
if (lookforwardcount > 0) {
lf.x = 0.5f * -e.y;
lf.y = 0.5f * e.x;
}
return lf;
}
/// myForce() is a method that returns an "empty" force (all components set to 0).
/// This method can be overridden in order to define own forces.
/// It is called in move() in addition to the other default forces.
/// \date 2012-02-12
/// \return Tvector: the calculated force
/// \param e is a vector defining the direction in which the agent wants to walk to.
Ped::Tvector Ped::Tagent::myForce(Ped::Tvector e, const set<const Ped::Tagent*> &neighbors) {
Ped::Tvector lf;
return lf;
}
/// This is the first step of the 2-step update process used
/// here. First, all forces are computed, using the t-1 agent
/// positions as input. Once the forces are computed, all agent
/// positions for timestep t are updated at the same time.
void Ped::Tagent::computeForces() {
const double neighborhoodRange = 20.0;
auto neighbors = scene->getNeighbors(p.x, p.y, neighborhoodRange);
desiredforce = desiredForce();
if (factorlookaheadforce > 0) lookaheadforce = lookaheadForce(desiredDirection, neighbors);
if (factorsocialforce > 0) socialforce = socialForce(neighbors);
if (factorobstacleforce > 0) obstacleforce = obstacleForce(neighbors);
myforce = myForce(desiredDirection, neighbors);
}
/// Does the agent dynamics stuff. In the current implementation a
/// simple Euler integration is used. As the first step, the new
/// position is calculated using t-1 velocity. Then, the new
/// contributing individual forces are calculated. This will then be
/// added to the existing velocity, which again is used during the
/// next time step. See e.g. https://en.wikipedia.org/wiki/Euler_method
///
/// \date 2003-12-29
/// \param h Integration time step delta t
void Ped::Tagent::move(double h) {
// internal position update = actual move
// p = p + v * h;
Tvector p_desired = p + v * h;
Ped::Tvector intersection;
bool has_intersection = false;
for (auto obstacle : scene->getAllObstacles()) {
Ped::Tvector intersection;
// Ped::Tvector surface = obstacle->getEndPoint() - obstacle->getStartPoint();
// Ped::Tvector vd = surface.leftNormalVector().normalized() * 0.30; // min radius of agent
// // walls left and right
// if (Ped::Tvector::lineIntersection(p, p_desired, obstacle->getStartPoint()-vd, obstacle->getEndPoint()-vd, &intersection) == 1) {
// p_desired = intersection - (v*h).normalized()*0.1;
// }
// if (Ped::Tvector::lineIntersection(p, p_desired, obstacle->getStartPoint()+vd, obstacle->getEndPoint()+vd, &intersection) == 1) {
// p_desired = intersection - (v*h).normalized()*0.1;
// }
// // caps
// if (Ped::Tvector::lineIntersection(p, p_desired, obstacle->getStartPoint()-vd, obstacle->getStartPoint()+vd, &intersection) == 1) {
// p_desired = intersection - (v*h).normalized()*0.1;
// }
// if (Ped::Tvector::lineIntersection(p, p_desired, obstacle->getEndPoint()-vd, obstacle->getEndPoint()+vd, &intersection) == 1) {
// p_desired = intersection - (v*h).normalized()*0.1;
// }
if (Ped::Tvector::lineIntersection(p, p_desired, obstacle->getStartPoint(), obstacle->getEndPoint(), &intersection) == 1) {
p_desired = intersection - (v*h).normalized()*0.1;
}
}
p = p_desired; // update my position
// weighted sum of all forces --> acceleration
a = factordesiredforce * desiredforce
+ factorsocialforce * socialforce
+ factorobstacleforce * obstacleforce
+ factorlookaheadforce * lookaheadforce
+ myforce;
// calculate the new velocity
v = 0.5 * v + a * h; // prob rather (0.5 / h) * v
// don't exceed maximal speed
if (v.length() > vmax) v = v.normalized() * vmax;
// notice scene of movement
scene->moveAgent(this);
}
| 412 | 0.91471 | 1 | 0.91471 | game-dev | MEDIA | 0.926899 | game-dev | 0.987293 | 1 | 0.987293 |
w3champions/flo | 3,123 | crates/controller/src/schema.rs | // @generated automatically by Diesel CLI.
diesel::table! {
api_client (id) {
id -> Int4,
name -> Text,
secret_key -> Text,
created_at -> Timestamptz,
}
}
diesel::table! {
game (id) {
id -> Int4,
name -> Text,
map_name -> Text,
status -> Int4,
node_id -> Nullable<Int4>,
is_private -> Bool,
secret -> Nullable<Int4>,
is_live -> Bool,
max_players -> Int4,
created_by -> Int4,
started_at -> Nullable<Timestamptz>,
ended_at -> Nullable<Timestamptz>,
meta -> Jsonb,
created_at -> Timestamptz,
updated_at -> Timestamptz,
random_seed -> Int4,
locked -> Bool,
mask_player_names -> Bool,
game_version -> Nullable<Text>,
enable_ping_equalizer -> Bool,
flo_tv_delay_override_secs -> Nullable<Int4>,
map_twelve_p -> Bool,
flo_tv_password_sha256 -> Nullable<Text>,
}
}
diesel::table! {
game_used_slot (id) {
id -> Int4,
game_id -> Int4,
player_id -> Nullable<Int4>,
slot_index -> Int4,
team -> Int4,
color -> Int4,
computer -> Int4,
handicap -> Int4,
status -> Int4,
race -> Int4,
client_status -> Int4,
node_token -> Nullable<Bytea>,
created_at -> Timestamptz,
updated_at -> Timestamptz,
client_status_synced_node_conn_id -> Nullable<Int8>,
}
}
diesel::table! {
map_checksum (id) {
id -> Int4,
sha1 -> Text,
checksum -> Bytea,
}
}
diesel::table! {
node (id) {
id -> Int4,
name -> Text,
location -> Text,
secret -> Text,
ip_addr -> Text,
created_at -> Timestamptz,
updated_at -> Timestamptz,
country_id -> Text,
disabled -> Bool,
internal_address -> Nullable<Text>,
}
}
diesel::table! {
player (id) {
id -> Int4,
name -> Text,
source -> Int4,
source_id -> Text,
source_state -> Nullable<Jsonb>,
realm -> Nullable<Text>,
created_at -> Timestamptz,
updated_at -> Timestamptz,
api_client_id -> Int4,
}
}
diesel::table! {
player_ban (id) {
id -> Int4,
player_id -> Int4,
ban_type -> Int4,
ban_expires_at -> Nullable<Timestamptz>,
created_at -> Timestamptz,
author -> Nullable<Text>,
}
}
diesel::table! {
player_mute (id) {
id -> Int4,
player_id -> Int4,
mute_player_id -> Int4,
created_at -> Timestamptz,
}
}
diesel::joinable!(game -> node (node_id));
diesel::joinable!(game -> player (created_by));
diesel::joinable!(game_used_slot -> game (game_id));
diesel::joinable!(game_used_slot -> player (player_id));
diesel::joinable!(player -> api_client (api_client_id));
diesel::joinable!(player_ban -> player (player_id));
diesel::allow_tables_to_appear_in_same_query!(
api_client,
game,
game_used_slot,
map_checksum,
node,
player,
player_ban,
player_mute,
);
| 412 | 0.757778 | 1 | 0.757778 | game-dev | MEDIA | 0.685887 | game-dev | 0.786523 | 1 | 0.786523 |
sunsvip/GF_X | 2,887 | Assets/Plugins/UnityGameFramework/Scripts/Editor/Inspector/LocalizationComponentInspector.cs | //------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------
using UnityEditor;
using UnityGameFramework.Runtime;
namespace UnityGameFramework.Editor
{
[CustomEditor(typeof(LocalizationComponent))]
internal sealed class LocalizationComponentInspector : GameFrameworkInspector
{
private SerializedProperty m_EnableLoadDictionaryUpdateEvent = null;
private SerializedProperty m_EnableLoadDictionaryDependencyAssetEvent = null;
private SerializedProperty m_CachedBytesSize = null;
private HelperInfo<LocalizationHelperBase> m_LocalizationHelperInfo = new HelperInfo<LocalizationHelperBase>("Localization");
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
serializedObject.Update();
LocalizationComponent t = (LocalizationComponent)target;
EditorGUI.BeginDisabledGroup(EditorApplication.isPlayingOrWillChangePlaymode);
{
EditorGUILayout.PropertyField(m_EnableLoadDictionaryUpdateEvent);
EditorGUILayout.PropertyField(m_EnableLoadDictionaryDependencyAssetEvent);
m_LocalizationHelperInfo.Draw();
EditorGUILayout.PropertyField(m_CachedBytesSize);
}
EditorGUI.EndDisabledGroup();
if (EditorApplication.isPlaying && IsPrefabInHierarchy(t.gameObject))
{
EditorGUILayout.LabelField("Language", t.Language.ToString());
EditorGUILayout.LabelField("System Language", t.SystemLanguage.ToString());
EditorGUILayout.LabelField("Dictionary Count", t.DictionaryCount.ToString());
EditorGUILayout.LabelField("Cached Bytes Size", t.CachedBytesSize.ToString());
}
serializedObject.ApplyModifiedProperties();
Repaint();
}
protected override void OnCompileComplete()
{
base.OnCompileComplete();
RefreshTypeNames();
}
private void OnEnable()
{
m_EnableLoadDictionaryUpdateEvent = serializedObject.FindProperty("m_EnableLoadDictionaryUpdateEvent");
m_EnableLoadDictionaryDependencyAssetEvent = serializedObject.FindProperty("m_EnableLoadDictionaryDependencyAssetEvent");
m_CachedBytesSize = serializedObject.FindProperty("m_CachedBytesSize");
m_LocalizationHelperInfo.Init(serializedObject);
RefreshTypeNames();
}
private void RefreshTypeNames()
{
m_LocalizationHelperInfo.Refresh();
serializedObject.ApplyModifiedProperties();
}
}
}
| 412 | 0.871604 | 1 | 0.871604 | game-dev | MEDIA | 0.769705 | game-dev | 0.969963 | 1 | 0.969963 |
mr-kelly/KEngine | 2,562 | KEngine.UnityProject/Assets/KEngine/CoreModules/ResourceModule/KSpriteLoader.cs | #region Copyright (c) 2015 KEngine / Kelly <http://github.com/mr-kelly>, All rights reserved.
// KEngine - Toolset and framework for Unity3D
// ===================================
//
// Filename: SpriteLoader.cs
// Date: 2015/12/03
// Author: Kelly
// Email: 23110388@qq.com
// Github: https://github.com/mr-kelly/KEngine
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library.
#endregion
using UnityEngine;
namespace KEngine
{
public class SpriteLoader : AbstractResourceLoader
{
public Sprite Asset
{
get { return ResultObject as Sprite; }
}
public delegate void CSpriteLoaderDelegate(bool isOk, Sprite tex);
private AssetFileLoader AssetFileBridge;
public override float Progress
{
get { return AssetFileBridge.Progress; }
}
public string Path { get; private set; }
public static SpriteLoader Load(string path, CSpriteLoaderDelegate callback = null)
{
LoaderDelgate newCallback = null;
if (callback != null)
{
newCallback = (isOk, obj) =>
{
var t2d = obj as UnityEngine.Texture2D;
var sp = Sprite.Create(t2d, new Rect(0, 0, t2d.width, t2d.height), new Vector2(0.5f, 0.5f));
callback(isOk, sp as Sprite);
};
}
return AutoNew<SpriteLoader>(path, newCallback);
}
protected override void Init(string url, params object[] args)
{
base.Init(url, args);
Path = url;
AssetFileBridge = AssetFileLoader.Load(Path, OnAssetLoaded);
}
private void OnAssetLoaded(bool isOk, UnityEngine.Object obj)
{
OnFinish(obj);
}
protected override void DoDispose()
{
base.DoDispose();
AssetFileBridge.Release(); // all, Texture is singleton!
}
}
} | 412 | 0.888812 | 1 | 0.888812 | game-dev | MEDIA | 0.88137 | game-dev | 0.739848 | 1 | 0.739848 |
acts-project/acts | 3,558 | Fatras/include/ActsFatras/Kernel/ContinuousProcess.hpp | // This file is part of the ACTS project.
//
// Copyright (C) 2016 CERN for the benefit of the ACTS project
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
#pragma once
#include "Acts/Material/MaterialSlab.hpp"
#include "ActsFatras/EventData/Particle.hpp"
#include "ActsFatras/Kernel/InteractionList.hpp"
namespace ActsFatras {
/// A continuous simulation process based on a physics model plus selectors.
///
/// @tparam physics_t is the physics model type
/// @tparam input_particle_selector_t is the input particle selector
/// @tparam output_particle_selector_t is the output particle selector
/// @tparam child_particle_selector_t is the child particle selector
///
/// The physics model type **must** provide a call operator with the following
/// signature
///
/// <Particle Container>
/// operator()(
/// generator_t& generator,
/// const Acts::MaterialSlab& slab,
/// Particle& particle) const
///
/// The return type can be any `Container` with `Particle` elements.
///
/// The input selector defines whether the process is applied while the
/// output selector defines a break condition, i.e. whether to continue
/// simulating the particle propagation. The child selector is used to
/// filter the generated child particles.
///
/// @note The output and child particle selectors are identical unless the
/// child particle selector is explicitly specified.
template <detail::ContinuousProcessConcept physics_t,
typename input_particle_selector_t,
typename output_particle_selector_t,
typename child_particle_selector_t = output_particle_selector_t>
struct ContinuousProcess {
/// The physics interactions implementation.
physics_t physics;
/// Input selection: if this process applies to this particle.
input_particle_selector_t selectInputParticle;
/// Output selection: if the particle is still valid after the interaction.
output_particle_selector_t selectOutputParticle;
/// Child selection: if a generated child particle should be kept.
child_particle_selector_t selectChildParticle;
/// Execute the physics process considering the configured selectors.
///
/// @param[in] generator is the random number generator
/// @param[in] slab is the passed material
/// @param[in,out] particle is the particle being updated
/// @param[out] generated is the container of generated particles
/// @return Break condition, i.e. whether this process stops the propagation
///
/// @tparam generator_t must be a RandomNumberEngine
template <typename generator_t>
bool operator()(generator_t &generator, const Acts::MaterialSlab &slab,
Particle &particle, std::vector<Particle> &generated) const {
// not selecting this process is not a break condition
if (!selectInputParticle(particle)) {
return false;
}
// modify particle according to the physics process
auto children = physics(generator, slab, particle);
// move selected child particles to the output container
std::copy_if(std::begin(children), std::end(children),
std::back_inserter(generated), selectChildParticle);
// break condition is defined by whether the output particle is still valid
// or not e.g. because it has fallen below a momentum threshold.
return !selectOutputParticle(particle);
}
};
} // namespace ActsFatras
| 412 | 0.838789 | 1 | 0.838789 | game-dev | MEDIA | 0.559223 | game-dev | 0.876516 | 1 | 0.876516 |
megahoneybadger/grafana-ng | 1,465 | src/server/data-sources/redis/driver/conn/commands/RedisHash.cs | using CSRedis.Internal.IO;
using CSRedis.Internal.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
namespace CSRedis.Internal.Commands
{
class RedisHash : RedisCommand<Dictionary<string, string>>
{
public RedisHash(string command, params object[] args)
: base(command, args)
{ }
public override Dictionary<string, string> Parse(RedisReader reader)
{
return ToDict(reader);
}
static Dictionary<string, string> ToDict(RedisReader reader)
{
reader.ExpectType(RedisMessage.MultiBulk);
long count = reader.ReadInt(false);
var dict = new Dictionary<string, string>();
string key = String.Empty;
for (int i = 0; i < count; i++)
{
if (i % 2 == 0)
key = reader.ReadBulkString();
else
dict[key] = reader.ReadBulkString();
}
return dict;
}
public class Generic<T> : RedisCommand<T>
where T : class
{
public Generic(string command, params object[] args)
: base(command, args)
{ }
public override T Parse(RedisReader reader)
{
return Serializer<T>.Deserialize(RedisHash.ToDict(reader));
}
}
}
}
| 412 | 0.678454 | 1 | 0.678454 | game-dev | MEDIA | 0.425039 | game-dev | 0.633694 | 1 | 0.633694 |
saul/demofile-net | 2,193 | src/DemoFile.Test/Integration/Source1GameEventIntegrationTest.cs | using System.Text;
using System.Text.Json;
namespace DemoFile.Test.Integration;
[TestFixtureSource(typeof(GlobalUtil), nameof(ParseModes))]
public class Source1GameEventIntegrationTest
{
private readonly ParseMode _mode;
public Source1GameEventIntegrationTest(ParseMode mode)
{
_mode = mode;
}
[Test]
public async Task GameEvent()
{
// Arrange
DemoSnapshot ParseSection(CsDemoParser demo)
{
var snapshot = new DemoSnapshot();
demo.Source1GameEvents.Source1GameEvent += e =>
{
// Ignore very noisy events
if (e.GameEventName is "player_sound" or "player_footstep")
return;
var sb = new StringBuilder();
sb.AppendLine($"Event {e.GameEventName}@{demo.CurrentGameTick}:");
var eventJson = JsonSerializer.Serialize(e, DemoJson.SerializerOptions)
.ReplaceLineEndings(Environment.NewLine + " ");
sb.AppendLine($" {eventJson}");
snapshot.Add(demo.CurrentDemoTick, sb.ToString());
};
return snapshot;
}
// Act
var snapshot = await Parse(_mode, GotvCompetitiveProtocol13963, ParseSection);
// Assert
Snapshot.Assert(snapshot);
}
[Test]
public async Task PlayerProperties()
{
DemoSnapshot ParseSection(CsDemoParser demo)
{
demo.Source1GameEvents.PlayerHurt += e =>
{
Assert.That(e.Player, Is.Not.Null);
Assert.That(e.PlayerPawn, Is.Not.Null);
};
demo.Source1GameEvents.PlayerDeath += e =>
{
Assert.That(e.Player, Is.Not.Null);
Assert.That(e.PlayerPawn, Is.Not.Null);
};
demo.Source1GameEvents.WeaponFire += e =>
{
Assert.That(e.Player, Is.Not.Null);
Assert.That(e.PlayerPawn, Is.Not.Null);
};
return new DemoSnapshot();
}
// Act
await Parse(_mode, GotvCompetitiveProtocol13963, ParseSection);
}
}
| 412 | 0.836564 | 1 | 0.836564 | game-dev | MEDIA | 0.658461 | game-dev | 0.608729 | 1 | 0.608729 |
ParadiseSS13/Paradise | 2,236 | code/datums/spells/horsemask.dm | /datum/spell/horsemask
name = "Curse of the Horseman"
desc = "This spell triggers a curse on a target, causing them to wield an unremovable horse head mask. They will speak like a horse! Any masks they are wearing will be disintegrated. This spell does not require robes."
base_cooldown = 150
clothes_req = FALSE
invocation = "KN'A FTAGHU, PUCK 'BTHNK!"
invocation_type = "shout"
cooldown_min = 30 //30 deciseconds reduction per rank
selection_activated_message = "<span class='notice'>You start to quietly neigh an incantation. Click on or near a target to cast the spell.</span>"
selection_deactivated_message = "<span class='notice'>You stop neighing to yourself.</span>"
action_icon_state = "barn"
sound = 'sound/magic/HorseHead_curse.ogg'
/datum/spell/horsemask/create_new_targeting()
var/datum/spell_targeting/click/T = new()
T.selection_type = SPELL_SELECTION_RANGE
return T
/datum/spell/horsemask/cast(list/targets, mob/user = usr)
if(!length(targets))
to_chat(user, "<span class='notice'>No target found in range.</span>")
return
var/mob/living/carbon/human/target = targets[1]
if(target.can_block_magic(antimagic_flags))
target.visible_message("<span class='danger'>[target]'s face bursts into flames, which instantly burst outward, leaving [target.p_them()] unharmed!</span>",
"<span class='danger'>Your face starts burning up, but the flames are repulsed by your anti-magic protection!</span>",
)
to_chat(user, "<span class='warning'>The spell had no effect!</span>")
return FALSE
var/obj/item/clothing/mask/horsehead/magichead = new /obj/item/clothing/mask/horsehead
magichead.flags |= DROPDEL //curses!
magichead.set_nodrop(TRUE)
magichead.flags_inv = null //so you can still see their face
magichead.voicechange = TRUE //NEEEEIIGHH
target.visible_message( "<span class='danger'>[target]'s face lights up in fire, and after the event a horse's head takes its place!</span>", \
"<span class='danger'>Your face burns up, and shortly after the fire you realize you have the face of a horse!</span>")
if(!target.drop_item_to_ground(target.wear_mask))
qdel(target.wear_mask)
target.equip_to_slot_if_possible(magichead, ITEM_SLOT_MASK, TRUE, TRUE)
target.flash_eyes()
| 412 | 0.81553 | 1 | 0.81553 | game-dev | MEDIA | 0.998664 | game-dev | 0.83303 | 1 | 0.83303 |
Darkrp-community/OpenKeep | 2,247 | code/modules/buildmode/submodes/area_edit.dm | /datum/buildmode_mode/area_edit
key = "areaedit"
var/area/storedarea
var/image/areaimage
/datum/buildmode_mode/area_edit/New()
areaimage = image('icons/turf/areas.dmi', null, "yellow")
..()
/datum/buildmode_mode/area_edit/enter_mode(datum/buildmode/BM)
BM.holder.images += areaimage
/datum/buildmode_mode/area_edit/exit_mode(datum/buildmode/BM)
areaimage.loc = null // de-color the area
BM.holder.images -= areaimage
return ..()
/datum/buildmode_mode/area_edit/Destroy()
QDEL_NULL(areaimage)
storedarea = null
return ..()
/datum/buildmode_mode/area_edit/show_help(client/c)
to_chat(c, "<span class='notice'>***********************************************************</span>")
to_chat(c, "<span class='notice'>Left Mouse Button on obj/turf/mob = Paint area</span>")
to_chat(c, "<span class='notice'>Right Mouse Button on obj/turf/mob = Select area to paint</span>")
to_chat(c, "<span class='notice'>Right Mouse Button on buildmode button = Create new area</span>")
to_chat(c, "<span class='notice'>***********************************************************</span>")
/datum/buildmode_mode/area_edit/change_settings(client/c)
var/target_path = input(c, "Enter typepath:", "Typepath", "/area")
var/areatype = text2path(target_path)
if(ispath(areatype,/area))
var/areaname = input(c, "Enter area name:", "Area name", "Area")
if(!areaname || !length(areaname))
return
storedarea = new areatype
storedarea.power_equip = 0
storedarea.power_light = 0
storedarea.power_environ = 0
storedarea.always_unpowered = 0
storedarea.name = areaname
areaimage.loc = storedarea // color our area
/datum/buildmode_mode/area_edit/handle_click(client/c, params, object)
var/list/pa = params2list(params)
var/left_click = pa.Find("left")
var/right_click = pa.Find("right")
if(left_click)
if(!storedarea)
to_chat(c, "<span class='warning'>Configure or select the area you want to paint first!</span>")
return
var/turf/T = get_turf(object)
if(get_area(T) != storedarea)
log_admin("Build Mode: [key_name(c)] added [AREACOORD(T)] to [storedarea]")
storedarea.contents.Add(T)
else if(right_click)
var/turf/T = get_turf(object)
storedarea = get_area(T)
areaimage.loc = storedarea // color our area
| 412 | 0.901151 | 1 | 0.901151 | game-dev | MEDIA | 0.771468 | game-dev | 0.907954 | 1 | 0.907954 |
DeltaV-Station/Delta-v | 3,678 | Content.Server/Anomaly/Effects/EntityAnomalySystem.cs | using Content.Shared.Anomaly;
using Content.Shared.Anomaly.Components;
using Content.Shared.Anomaly.Effects;
using Content.Shared.Anomaly.Effects.Components;
using Robust.Shared.Map.Components;
using Robust.Shared.Physics.Components;
using Robust.Shared.Random;
namespace Content.Server.Anomaly.Effects;
public sealed class EntityAnomalySystem : SharedEntityAnomalySystem
{
[Dependency] private readonly SharedAnomalySystem _anomaly = default!;
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly SharedMapSystem _mapSystem = default!;
private EntityQuery<PhysicsComponent> _physicsQuery;
/// <inheritdoc/>
public override void Initialize()
{
_physicsQuery = GetEntityQuery<PhysicsComponent>();
SubscribeLocalEvent<EntitySpawnAnomalyComponent, AnomalyPulseEvent>(OnPulse);
SubscribeLocalEvent<EntitySpawnAnomalyComponent, AnomalySupercriticalEvent>(OnSupercritical);
SubscribeLocalEvent<EntitySpawnAnomalyComponent, AnomalyStabilityChangedEvent>(OnStabilityChanged);
SubscribeLocalEvent<EntitySpawnAnomalyComponent, AnomalySeverityChangedEvent>(OnSeverityChanged);
SubscribeLocalEvent<EntitySpawnAnomalyComponent, AnomalyShutdownEvent>(OnShutdown);
}
private void OnPulse(Entity<EntitySpawnAnomalyComponent> component, ref AnomalyPulseEvent args)
{
foreach (var entry in component.Comp.Entries)
{
if (!entry.Settings.SpawnOnPulse)
continue;
SpawnEntities(component, entry, args.Stability, args.Severity, args.PowerModifier);
}
}
private void OnSupercritical(Entity<EntitySpawnAnomalyComponent> component, ref AnomalySupercriticalEvent args)
{
foreach (var entry in component.Comp.Entries)
{
if (!entry.Settings.SpawnOnSuperCritical)
continue;
SpawnEntities(component, entry, 1, 1, args.PowerModifier);
}
}
private void OnShutdown(Entity<EntitySpawnAnomalyComponent> component, ref AnomalyShutdownEvent args)
{
foreach (var entry in component.Comp.Entries)
{
if (!entry.Settings.SpawnOnShutdown || args.Supercritical)
continue;
SpawnEntities(component, entry, 1, 1, 1);
}
}
private void OnStabilityChanged(Entity<EntitySpawnAnomalyComponent> component, ref AnomalyStabilityChangedEvent args)
{
foreach (var entry in component.Comp.Entries)
{
if (!entry.Settings.SpawnOnStabilityChanged)
continue;
SpawnEntities(component, entry, args.Stability, args.Severity, 1);
}
}
private void OnSeverityChanged(Entity<EntitySpawnAnomalyComponent> component, ref AnomalySeverityChangedEvent args)
{
foreach (var entry in component.Comp.Entries)
{
if (!entry.Settings.SpawnOnSeverityChanged)
continue;
SpawnEntities(component, entry, args.Stability, args.Severity, 1);
}
}
private void SpawnEntities(Entity<EntitySpawnAnomalyComponent> anomaly, EntitySpawnSettingsEntry entry, float stability, float severity, float powerMod)
{
var xform = Transform(anomaly);
if (!TryComp(xform.GridUid, out MapGridComponent? grid))
return;
var tiles = _anomaly.GetSpawningPoints(anomaly, stability, severity, entry.Settings, powerMod);
if (tiles == null)
return;
foreach (var tileref in tiles)
{
Spawn(_random.Pick(entry.Spawns), _mapSystem.ToCenterCoordinates(tileref, grid));
}
}
}
| 412 | 0.72035 | 1 | 0.72035 | game-dev | MEDIA | 0.994673 | game-dev | 0.6561 | 1 | 0.6561 |
tunjid/teammate-android | 2,131 | app/src/main/java/com/mainstreetcode/teammate/model/enums/TournamentStyle.kt | /*
* MIT License
*
* Copyright (c) 2019 Adetunji Dahunsi
*
* 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.mainstreetcode.teammate.model.enums
import android.os.Build
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonObject
import java.util.*
class TournamentStyle internal constructor(code: String, name: String) : MetaData(code, name) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TournamentStyle) return false
val variant = other as TournamentStyle?
return code == variant!!.code && name == variant.name
}
override fun hashCode(): Int = Objects.hash(code, name)
class GsonAdapter : MetaData.GsonAdapter<TournamentStyle>() {
override fun fromJson(code: String, name: String, body: JsonObject, context: JsonDeserializationContext): TournamentStyle =
TournamentStyle(code, name)
}
companion object {
fun empty(): TournamentStyle =
TournamentStyle(Build.VERSION.SDK_INT.toString(), Build.MODEL)
}
}
| 412 | 0.60916 | 1 | 0.60916 | game-dev | MEDIA | 0.548941 | game-dev | 0.843673 | 1 | 0.843673 |
median-dxz/seerh5-assistant | 9,344 | sdk/mods/median/commands.ts | /* eslint-disable */
import { scope } from '@/median/constants.json';
import { GameConfigRegistry, PetElement, SEAEventSource, SEAPetStore, delay, socket, spet } from '@sea/core';
import type { Command, SEAModContext, SEAModExport, SEAModMetadata } from '@sea/mod-type';
const rate = [
[0, 24, 5.8, 1.4, 0.3],
[0, 0, 23, 5.5, 1.3],
[0, 0, 0, 22, 5.3],
[0, 0, 0, 0, 21]
];
function calcProbability(level: number, targetLevel: number) {
return rate[level][targetLevel];
}
declare var pvePetYinzi: any;
export const metadata = {
id: 'CommandPresets',
scope,
version: '1.0.0',
description: '预置命令组'
} satisfies SEAModMetadata;
export default function builtinCommands({ logger }: SEAModContext<typeof metadata>): SEAModExport {
const filterUniversalMarks = (filter: (countermarkInfo: CountermarkInfo) => boolean) =>
CountermarkController.getAllUniversalMark().reduce((pre, v) => {
const name = v.markName;
if (filter(v)) {
if (pre.has(name)) {
pre.get(name)!.push(v);
} else {
pre.set(v.markName, [v]);
}
}
return pre;
}, new Map<string, CountermarkInfo[]>());
const commands: Command[] = [
{
name: 'getCurPanelInfo',
handler() {
logger(pvePetYinzi.DataManager._instance.curYinziData);
}
},
{
name: 'logDataByName',
handler(args) {
const { petName } = args as { petName: string };
const data = config.xml
.getAnyRes('new_super_design')
.Root.Design.find((r: any) => (r.Desc as string).match(petName));
logger(data);
},
parametersDescription: 'petName: 精灵名'
},
{
name: 'calcAllEfficientPet',
async handler(args) {
const { e, radio } = args as { e: number; radio: number };
const [bag1, bag2] = await SEAPetStore.bag.get();
const mini = (await SEAPetStore.miniInfo.get()).values();
const pets = [...bag1, ...bag2, ...mini];
const r = pets.filter((v) => PetElement.formatById(PetXMLInfo.getType(v.id)).calcRatio(e) >= radio);
logger(
r.map((v) => {
const eid = PetXMLInfo.getType(v.id);
return {
name: v.name,
elementId: eid,
element: SkillXMLInfo.typeMap[eid].cn,
id: v.id,
ratio: PetElement.formatById(eid).calcRatio(e)
};
})
);
},
description: '计算可用的高倍克制精灵',
parametersDescription: 'e: 要克制属性id, radio: 最低克制比例'
},
{
name: 'refreshBatteryTime',
handler() {
const leftTime =
MainManager.actorInfo.timeLimit -
(MainManager.actorInfo.timeToday +
Math.floor(Date.now() / 1000 - MainManager.actorInfo.logintimeThisTime));
BatteryController.Instance._leftTime = Math.max(0, leftTime);
}
},
{
name: 'delCounterMark',
async handler(args) {
const { i: preserved } = args as { i: number };
const universalMarks = filterUniversalMarks((v) => v.catchTime === 0 && v.isBindMon === false);
for (const [_, v] of universalMarks) {
if (v.length - preserved <= 0) continue;
logger(`删除多余刻印: ${v[0].markName} *${v.length - preserved}`);
await socket.sendByQueue(
41445,
[v.length - preserved].concat(
v
.toReversed() // 保留较新的刻印
.slice(preserved)
.map((v) => {
CountermarkController.removeFromCache(v);
return v.obtainTime;
})
)
);
}
},
description: '删除多余刻印',
parametersDescription: 'i: 保留的刻印数量'
},
{
name: 'upgradeAllCounterMark',
description: '一键升级所有刻印',
async handler() {
const universalMarks = filterUniversalMarks(
(v) => v.catchTime === 0 && v.isBindMon === false && v.level < 5
);
for (const [_, v] of universalMarks) {
for (let i = 0; i < v.length; i++) {
const mark = v[i];
logger(`升级刻印: ${mark.markName} lv${mark.level}`);
await socket.sendByQueue(41447, [mark.obtainTime]);
await delay(100);
}
}
await CountermarkController.init();
}
},
{
name: 'getClickTarget',
handler() {
LevelManager.stage.once(egret.TouchEvent.TOUCH_BEGIN, (e: egret.TouchEvent) => logger(e.target), null);
}
},
{
name: '关闭主页(挂机模式)',
handler() {
ModuleManager.currModule.hide();
}
},
{
name: '开启主页(恢复)',
handler() {
ModuleManager.currModule.show();
}
},
{
name: '返回主页(关闭所有模块)',
handler() {
ModuleManager.CloseAll();
}
},
{
name: '打开面板',
handler(args) {
const { panel } = args as { panel: string };
void ModuleManager.showModule(panel);
},
parametersDescription: 'panel: 面板名'
}
];
const resetNature: Command = {
name: 'resetNature',
description: '刷性格',
async handler(args) {
const { ct, nature } = args as { ct: number; nature: number };
const query = GameConfigRegistry.getQuery('nature');
for (; ; await delay(200)) {
await spet(ct).useItem(300070).done;
const info = await PetManager.UpdateBagPetInfoAsynce(ct);
logger(`刷性格: 当前性格: ${query.getName(info.nature)}`);
if (info.nature === nature) {
break;
}
await new Promise((resolve) => {
SEAEventSource.socket(CommandID.MULTI_ITEM_LIST, 'receive').once(resolve);
ItemManager.updateItemNum([300070], [true]);
});
await delay(200);
const num = ItemManager.getNumByID(300070);
logger(`刷性格: 剩余胶囊数: ${num}`);
if (num < 20) {
break;
}
}
}
};
const craftOne: Command = {
name: 'craftOne',
async handler() {
let stones: Array<{
name: string;
level: number;
id: number;
num: number;
}> = [];
await new Promise((resolve) => {
SEAEventSource.socket(4475, 'receive').once(resolve);
ItemManager.getSkillStone();
});
const stoneInfos = ItemManager.getSkillStoneInfos();
stones = [];
stoneInfos.forEach((stone) => {
const stoneName = ItemXMLInfo.getName(stone.itemID);
stones.push({
name: stoneName.replace('系技能', ''),
level: ItemXMLInfo.getSkillStoneRank(stone.itemID) - 1,
id: stone.itemID,
num: stone.itemNum
});
});
stones.sort((a, b) => a.level - b.level);
const toCraft: {
name: string;
level: number;
id: number;
}[] = [];
const getRate = () => {
const maxValue = Math.max(...toCraft.map((v) => v.level));
if (maxValue === 4 || !isFinite(maxValue)) return 0;
const baseRate = toCraft.reduce((pre, cur) => pre + calcProbability(cur.level, maxValue + 1), 0);
return Math.min(baseRate + 10, 100);
};
for (let i = 0; i < stones.length && toCraft.length < 4; i++) {
const stone = stones[i];
if (stone.num > 2 || stone.level > 0) {
toCraft.push(stone);
}
}
if (toCraft.length < 4 || getRate() === 0) {
return;
}
console.log(getRate(), toCraft);
await socket.sendByQueue(
CommandID.SKILL_STONE_COMPOSE_ITEM,
toCraft.map((v) => v.id)
);
// await this.init();
}
};
return {
commands: [...commands, resetNature, craftOne]
};
}
| 412 | 0.878217 | 1 | 0.878217 | game-dev | MEDIA | 0.52504 | game-dev,web-backend | 0.944737 | 1 | 0.944737 |
DestroyerDarkNess/Hydra | 1,578 | EXGuard.Runtime/Execution/Internal/ArrayStoreHelpers.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Emit;
namespace EXGuard.Runtime.Execution.Internal {
internal class ArrayStoreHelpers {
static Hashtable storeHelpers = new Hashtable();
delegate void _SetValue(Array array, int index, object value);
public static void SetValue(Array array, int index, object value, Type valueType, Type elemType) {
Debug.Assert(value == null || value.GetType() == valueType);
var key = new KeyValuePair<Type, Type>(valueType, elemType);
var helper = storeHelpers[key];
if (helper == null) {
lock (storeHelpers) {
helper = storeHelpers[key];
if (helper == null) {
helper = BuildStoreHelper(valueType, elemType);
storeHelpers[key] = helper;
}
}
}
((_SetValue)helper)(array, index, value);
}
static _SetValue BuildStoreHelper(Type valueType, Type elemType) {
var paramTypes = new[] { typeof(Array), typeof(int), typeof(object) };
var dm = new DynamicMethod("", typeof(void), paramTypes, typeof(ArrayStoreHelpers).Module, true);
var gen = dm.GetILGenerator();
gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
if (elemType.IsValueType)
gen.Emit(System.Reflection.Emit.OpCodes.Unbox_Any, valueType);
gen.Emit(System.Reflection.Emit.OpCodes.Stelem, elemType);
gen.Emit(System.Reflection.Emit.OpCodes.Ret);
return (_SetValue)dm.CreateDelegate(typeof(_SetValue));
}
}
} | 412 | 0.882586 | 1 | 0.882586 | game-dev | MEDIA | 0.266538 | game-dev | 0.913521 | 1 | 0.913521 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.