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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PrimeDecomp/prime | 3,219 | include/MetroidPrime/Enemies/CNewIntroBoss.hpp | #ifndef _CNEWINTROBOSS
#define _CNEWINTROBOSS
#include "MetroidPrime/Enemies/CPatterned.hpp"
#include "Kyoto/Animation/CharacterCommon.hpp"
#include "MetroidPrime/CBoneTracking.hpp"
#include "MetroidPrime/Weapons/CProjectileInfo.hpp"
class CCollisionActorManager;
class CPatternedInfo;
class CNewIntroBoss : public CPatterned {
public:
CNewIntroBoss(TUniqueId, const rstl::string&, const CEntityInfo& info, const CTransform4f& xf,
const CModelData& mData, const CPatternedInfo& pInfo,
const CActorParameters& actParms, float minTurnAngle, CAssetId projectile,
const CDamageInfo& dInfo, CAssetId beamContactFxId, CAssetId beamPulseFxId,
CAssetId beamTextureId, CAssetId beamGlowTextureId);
// CEntity
void Accept(IVisitor& visitor) override;
void Think(float dt, CStateManager& mgr) override;
void AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) override;
// CActor
void AddToRenderer(const CFrustumPlanes&, const CStateManager&) const override;
rstl::optional_object< CAABox > GetTouchBounds() const override;
void OnScanStateChange(EScanState, CStateManager&) override;
CAABox GetSortingBounds(const CStateManager&) const override;
void DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUserEventType type,
float dt) override;
// CAi
void Patrol(CStateManager&, EStateMsg, float) override;
void Generate(CStateManager& mgr, EStateMsg msg, float arg) override;
void Attack(CStateManager&, EStateMsg, float) override;
bool InAttackPosition(CStateManager&, float) override;
bool AnimOver(CStateManager&, float) override;
bool ShouldAttack(CStateManager&, float) override;
bool ShouldTurn(CStateManager&, float) override;
bool AIStage(CStateManager&, float) override;
// CPatterned
CProjectileInfo* ProjectileInfo() override;
pas::ELocomotionType GetLocoForHealth(const CStateManager& mgr) const;
pas::EGenerateType GetGenerateForHealth(const CStateManager& mgr) const;
float GetNextAttackTime(CStateManager& mgr) const;
CVector3f PlayerPos(const CStateManager& mgr) const;
void DeleteBeam(CStateManager& mgr);
void StopRumble(CStateManager& mgr);
float GetInitialHP() const { return x640_initialHp; }
private:
pas::ELocomotionType x568_locomotion;
uint x56c_stateProg;
float x570_minTurnAngle;
CBoneTracking x574_boneTracking;
CProjectileInfo x5ac_projectileInfo;
TUniqueId x5d4_stage1Projectile;
TUniqueId x5d6_stage2Projectile;
TUniqueId x5d8_stage3Projectile;
rstl::string x5dc_damageLocator; // ???
rstl::single_ptr< CCollisionActorManager > x5ec_collisionManager;
CAssetId x5f0_beamContactFxId;
CAssetId x5f4_beamPulseFxId;
CAssetId x5f8_beamTextureId;
CAssetId x5fc_beamGlowTextureId;
TUniqueId x600_headActor;
TUniqueId x602_pelvisActor;
CVector3f x604_predictedPlayerPos;
CVector3f x610_lookPos;
CVector3f x61c_startPlayerPos;
float x628_firingTime;
CVector3f x62c_targetPos;
float x638_;
float x63c_attackTime;
float x640_initialHp;
CTransform4f x644_initialXf;
short x674_rumbleVoice;
TUniqueId x676_curProjectile;
bool x678_;
};
#endif // _CNEWINTROBOSS
| 411 | 0.685041 | 1 | 0.685041 | game-dev | MEDIA | 0.854223 | game-dev | 0.629643 | 1 | 0.629643 |
PizzaLovers007/AdofaiTweaks | 1,382 | AdofaiTweaks/Tweaks/JudgmentVisuals/JudgmentVisualsSettings.cs | using AdofaiTweaks.Core;
namespace AdofaiTweaks.Tweaks.JudgmentVisuals;
/// <summary>
/// Settings for the Judgment Visuals tweak.
/// </summary>
public class JudgmentVisualsSettings : TweakSettings
{
/// <summary>
/// Shows the hit error meter.
/// </summary>
public bool ShowHitErrorMeter { get; set; }
/// <summary>
/// The scale multiplier for the hit error meter.
/// </summary>
public float ErrorMeterScale { get; set; } = 1f;
/// <summary>
/// The horizontal position of the hit error meter. Should be bound to
/// the range <c>[0, 1]</c>.
/// </summary>
public float ErrorMeterXPos { get; set; } = 0.5f;
/// <summary>
/// The vertical position of the hit error meter. Should be bound to the
/// range <c>[0, 1]</c>.
/// </summary>
public float ErrorMeterYPos { get; set; } = 0.03f;
/// <summary>
/// The length of time in seconds that a tick is visible on screen.
/// </summary>
public float ErrorMeterTickLife { get; set; } = 4f;
/// <summary>
/// How much the bottom arrow moves towards new hits. This is the alpha
/// value for the Exponential Moving Average formula.
/// </summary>
public float ErrorMeterSensitivity { get; set; } = 0.2f;
/// <summary>
/// Hides Perfect judgments.
/// </summary>
public bool HidePerfects { get; set; }
} | 411 | 0.548852 | 1 | 0.548852 | game-dev | MEDIA | 0.198366 | game-dev | 0.71018 | 1 | 0.71018 |
paulevsGitch/BetterNether | 8,723 | src/main/java/paulevs/betternether/world/structures/plants/StructureAnchorTreeRoot.java | package paulevs.betternether.world.structures.plants;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.util.Mth;
import net.minecraft.world.level.ServerLevelAccessor;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import paulevs.betternether.BlocksHelper;
import paulevs.betternether.MHelper;
import paulevs.betternether.blocks.BlockAnchorTreeVine;
import paulevs.betternether.blocks.BlockPlantWall;
import paulevs.betternether.blocks.BlockProperties.TripleShape;
import paulevs.betternether.registry.NetherBlocks;
import paulevs.betternether.world.structures.IStructure;
import paulevs.betternether.world.structures.StructureGeneratorThreadContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class StructureAnchorTreeRoot implements IStructure {
private static final StructureLucis LUCIS = new StructureLucis();
@Override
public void generate(ServerLevelAccessor world, BlockPos pos, Random random, final int MAX_HEIGHT, StructureGeneratorThreadContext context) {
if (pos.getY() < MAX_HEIGHT*0.75) return;
double angle = random.nextDouble() * Math.PI * 2;
double dx = Math.sin(angle);
double dz = Math.cos(angle);
double size = MHelper.randRange(10, 25, random) * 0.5;
int count = MHelper.floor(size * 2);
if (count < 3) count = 3;
if ((count & 1) == 0) count++;
context.POS.set(pos.getX() - dx * size, pos.getY() + 10, pos.getZ() - dz * size);
BlockPos start = context.POS.above(BlocksHelper.upRay(world, context.POS, (int)(MAX_HEIGHT*0.75)));
if (start.getY() < pos.getY()) start = context.POS.set(start).offset(0, 10, 0).immutable();
context.POS.set(pos.getX() + dx * size, pos.getY() + 10, pos.getZ() + dz * size);
BlockPos end = context.POS.above(BlocksHelper.upRay(world, context.POS, (int)(MAX_HEIGHT*0.75)));
if (end.getY() < pos.getY()) end = context.POS.set(end).offset(0, 10, 0).immutable();
List<BlockPos> blocks = lineParable(start, end, count, random, 0.2);
context.BLOCKS.clear();
buildLine(blocks, 1.3 + random.nextDouble(), context);
BlockState state;
BlockState vine = NetherBlocks.ANCHOR_TREE_VINE.defaultBlockState();
final int minBuildHeight = world.getMinBuildHeight()+1;
final BoundingBox blockBox = BlocksHelper.decorationBounds(world, pos, minBuildHeight, MAX_HEIGHT-2);
for (BlockPos bpos : context.BLOCKS) {
//if (!blockBox.contains(bpos)) continue;
if (bpos.getY() < minBuildHeight || bpos.getY() > MAX_HEIGHT-2) continue;
if (!BlocksHelper.isNetherGround(state = world.getBlockState(bpos)) && !canReplace(state)) continue;
boolean blockUp;
boolean blockDown = true;
if ((blockUp = context.BLOCKS.contains(bpos.above())) && (blockDown = context.BLOCKS.contains(bpos.below())))
BlocksHelper.setWithoutUpdate(world, bpos, NetherBlocks.MAT_ANCHOR_TREE.getLog().defaultBlockState());
else
BlocksHelper.setWithoutUpdate(world, bpos, NetherBlocks.MAT_ANCHOR_TREE.getBark().defaultBlockState());
if (!blockUp && world.getBlockState(bpos.above()).getMaterial().isReplaceable()) {
BlocksHelper.setWithoutUpdate(world, bpos.above(), NetherBlocks.MOSS_COVER.defaultBlockState());
}
if ((bpos.getY() & 3) == 0 && StructureAnchorTree.NOISE.eval(bpos.getX() * 0.1, bpos.getY() * 0.1, bpos.getZ() * 0.1) > 0) {
if (random.nextInt(32) == 0 && !context.BLOCKS.contains(bpos.north()))
if (random.nextBoolean())
StructureAnchorTree.makeMushroom(world, bpos.north(), random.nextDouble() + 1.5, blockBox);
else
LUCIS.generate(world, bpos, random, MAX_HEIGHT, context);
if (random.nextInt(32) == 0 && !context.BLOCKS.contains(bpos.south()))
if (random.nextBoolean())
StructureAnchorTree.makeMushroom(world, bpos.south(), random.nextDouble() + 1.5, blockBox);
else
LUCIS.generate(world, bpos, random, MAX_HEIGHT, context);
if (random.nextInt(32) == 0 && !context.BLOCKS.contains(bpos.east()))
if (random.nextBoolean())
StructureAnchorTree.makeMushroom(world, bpos.east(), random.nextDouble() + 1.5, blockBox);
else
LUCIS.generate(world, bpos, random, MAX_HEIGHT, context);
if (random.nextInt(32) == 0 && !context.BLOCKS.contains(bpos.west()))
if (random.nextBoolean())
StructureAnchorTree.makeMushroom(world, bpos.west(), random.nextDouble() + 1.5, blockBox);
else
LUCIS.generate(world, bpos, random, MAX_HEIGHT, context);
}
state = StructureAnchorTree.wallPlants[random.nextInt(StructureAnchorTree.wallPlants.length)].defaultBlockState();
BlockPos _pos = bpos.north();
if (random.nextInt(8) == 0 && !context.BLOCKS.contains(_pos) && world.isEmptyBlock(_pos))
BlocksHelper.setWithUpdate(world, _pos, state.setValue(BlockPlantWall.FACING, Direction.NORTH));
_pos = bpos.south();
if (random.nextInt(8) == 0 && !context.BLOCKS.contains(_pos) && world.isEmptyBlock(_pos))
BlocksHelper.setWithUpdate(world, _pos, state.setValue(BlockPlantWall.FACING, Direction.SOUTH));
_pos = bpos.east();
if (random.nextInt(8) == 0 && !context.BLOCKS.contains(_pos) && world.isEmptyBlock(_pos))
BlocksHelper.setWithUpdate(world, _pos, state.setValue(BlockPlantWall.FACING, Direction.EAST));
_pos = bpos.west();
if (random.nextInt(8) == 0 && !context.BLOCKS.contains(_pos) && world.isEmptyBlock(_pos))
BlocksHelper.setWithUpdate(world, _pos, state.setValue(BlockPlantWall.FACING, Direction.WEST));
if (blockUp && !blockDown && random.nextInt(16) == 0) {
bpos = bpos.below();
int length = BlocksHelper.downRay(world, bpos, 17);
if (length > 4) {
length = MHelper.randRange(3, length, random);
for (int i = 0; i < length - 2; i++) {
BlocksHelper.setWithoutUpdate(world, bpos.below(i), vine);
}
BlocksHelper.setWithoutUpdate(world, bpos.below(length - 2), vine.setValue(BlockAnchorTreeVine.SHAPE, TripleShape.MIDDLE));
BlocksHelper.setWithoutUpdate(world, bpos.below(length - 1), vine.setValue(BlockAnchorTreeVine.SHAPE, TripleShape.BOTTOM));
}
}
}
}
private boolean canReplace(BlockState state) {
return state.getMaterial().isReplaceable()
|| state.getBlock() == NetherBlocks.GIANT_LUCIS
|| state.getBlock() == NetherBlocks.LUCIS_MUSHROOM
|| state.getBlock() instanceof BlockPlantWall;
}
private void buildLine(List<BlockPos> blocks, double radius, StructureGeneratorThreadContext context) {
for (int i = 0; i < blocks.size() - 1; i++) {
BlockPos a = blocks.get(i);
BlockPos b = blocks.get(i + 1);
if (b.getY() < a.getY()) {
BlockPos c = b;
b = a;
a = c;
}
int count = (int) Math.ceil(Math.sqrt(b.distSqr(a)));
for (int j = 0; j < count; j++)
sphere(lerpCos(a, b, (double) j / count), radius, context);
}
}
private BlockPos lerpCos(BlockPos start, BlockPos end, double mix) {
double v = lcos(mix);
double x = Mth.lerp(v, start.getX(), end.getX());
double y = Mth.lerp(v, start.getY(), end.getY());
double z = Mth.lerp(v, start.getZ(), end.getZ());
return new BlockPos(x, y, z);
}
private double lcos(double mix) {
return Mth.clamp(0.5 - Math.cos(mix * Math.PI) * 0.5, 0, 1);
}
private List<BlockPos> lineParable(BlockPos start, BlockPos end, int count, Random random, double range) {
List<BlockPos> result = new ArrayList<>(count);
int max = count - 1;
int middle = count / 2;
result.add(start);
double size = Math.sqrt(start.distSqr(end)) * 0.8;
for (int i = 1; i < max; i++) {
double offset = (double) (i - middle) / middle;
offset = 1 - offset * offset;
double delta = (double) i / max;
double x = Mth.lerp(delta, start.getX(), end.getX()) + random.nextGaussian() * range;
double y = Mth.lerp(delta, start.getY(), end.getY()) - offset * size;
double z = Mth.lerp(delta, start.getZ(), end.getZ()) + random.nextGaussian() * range;
result.add(new BlockPos(x, y, z));
}
result.add(end);
return result;
}
private void sphere(BlockPos pos, double radius, StructureGeneratorThreadContext context) {
int x1 = MHelper.floor(pos.getX() - radius);
int y1 = MHelper.floor(pos.getY() - radius);
int z1 = MHelper.floor(pos.getZ() - radius);
int x2 = MHelper.floor(pos.getX() + radius + 1);
int y2 = MHelper.floor(pos.getY() + radius + 1);
int z2 = MHelper.floor(pos.getZ() + radius + 1);
radius *= radius;
for (int x = x1; x <= x2; x++) {
int px2 = x - pos.getX();
px2 *= px2;
for (int z = z1; z <= z2; z++) {
int pz2 = z - pos.getZ();
pz2 *= pz2;
for (int y = y1; y <= y2; y++) {
int py2 = y - pos.getY();
py2 *= py2;
if (px2 + pz2 + py2 <= radius) context.BLOCKS.add(new BlockPos(x, y, z));
}
}
}
}
}
| 411 | 0.897359 | 1 | 0.897359 | game-dev | MEDIA | 0.959405 | game-dev | 0.975819 | 1 | 0.975819 |
Sink18/ur5-gazebo-grasping-master | 6,869 | src/ur5-gazebo-grasping/gazebo_grasp_plugin/src/GazeboGraspGripper.cpp | #include <boost/bind.hpp>
#include <gazebo/gazebo.hh>
#include <gazebo/physics/physics.hh>
#include <gazebo/physics/ContactManager.hh>
#include <gazebo/physics/Contact.hh>
#include <gazebo/common/common.hh>
#include <stdio.h>
#include <gazebo_grasp_plugin/GazeboGraspGripper.h>
using gazebo::GazeboGraspGripper;
#define DEFAULT_FORCES_ANGLE_TOLERANCE 120
#define DEFAULT_UPDATE_RATE 5
#define DEFAULT_MAX_GRIP_COUNT 10
#define DEFAULT_RELEASE_TOLERANCE 0.005
#define DEFAULT_DISABLE_COLLISIONS_ON_ATTACH false
GazeboGraspGripper::GazeboGraspGripper():
attached(false)
{
}
GazeboGraspGripper::GazeboGraspGripper(const GazeboGraspGripper& o):
model(o.model),
gripperName(o.gripperName),
linkNames(o.linkNames),
collisionElems(o.collisionElems),
fixedJoint(o.fixedJoint),
palmLink(o.palmLink),
disableCollisionsOnAttach(o.disableCollisionsOnAttach),
attached(o.attached),
attachedObjName(o.attachedObjName)
{}
GazeboGraspGripper::~GazeboGraspGripper() {
this->model.reset();
}
bool GazeboGraspGripper::Init(physics::ModelPtr& _model,
const std::string& _gripperName,
const std::string& palmLinkName,
const std::vector<std::string>& fingerLinkNames,
bool _disableCollisionsOnAttach,
std::map<std::string, physics::CollisionPtr>& _collisionElems)
{
this->gripperName=_gripperName;
this->attached = false;
this->disableCollisionsOnAttach = _disableCollisionsOnAttach;
this->model = _model;
physics::PhysicsEnginePtr physics = this->model->GetWorld()->GetPhysicsEngine();
this->fixedJoint = physics->CreateJoint("revolute");
this->palmLink = this->model->GetLink(palmLinkName);
if (!this->palmLink)
{
gzerr << "GazeboGraspGripper: Palm link "<<palmLinkName<<" not found. The gazebo grasp plugin will not work."<<std::endl;
return false;
}
for (std::vector<std::string>::const_iterator fingerIt=fingerLinkNames.begin();
fingerIt!=fingerLinkNames.end(); ++fingerIt)
{
physics::LinkPtr link = this->model->GetLink(*fingerIt);
//std::cout<<"Got link "<<fingerLinkElem->Get<std::string>()<<std::endl;
if (!link.get()){
gzerr << "GazeboGraspGripper ERROR: Link "<<*fingerIt<<" can't be found in gazebo for GazeboGraspGripper model plugin. Skipping."<<std::endl;
continue;
}
for (unsigned int j = 0; j < link->GetChildCount(); ++j)
{
physics::CollisionPtr collision = link->GetCollision(j);
std::string collName = collision->GetScopedName();
//collision->SetContactsEnabled(true);
std::map<std::string, physics::CollisionPtr>::iterator collIter = collisionElems.find(collName);
if (collIter != this->collisionElems.end()) { //this collision was already added before
gzwarn <<"GazeboGraspGripper: Adding Gazebo collision link element "<<collName<<" multiple times, the gazebo grasp handler may not work properly"<<std::endl;
continue;
}
this->collisionElems[collName] = collision;
_collisionElems[collName] = collision;
}
}
return !this->collisionElems.empty();
}
const std::string& GazeboGraspGripper::getGripperName() const
{
return gripperName;
}
bool GazeboGraspGripper::hasLink(const std::string& linkName) const
{
for (std::vector<std::string>::const_iterator it=linkNames.begin(); it!=linkNames.end(); ++it)
{
if (*it==linkName) return true;
}
return false;
}
bool GazeboGraspGripper::hasCollisionLink(const std::string& linkName) const
{
return collisionElems.find(linkName) != collisionElems.end();
}
bool GazeboGraspGripper::isObjectAttached() const
{
return attached;
}
const std::string& GazeboGraspGripper::attachedObject() const
{
return attachedObjName;
}
// #define USE_MODEL_ATTACH // this only works if the object is a model in itself, which is usually not
// the case. Leaving this in here anyway for documentation of what has been
// tried, and for and later re-evaluation.
bool GazeboGraspGripper::HandleAttach(const std::string& objName)
{
if (!this->palmLink) {
gzwarn << "GazeboGraspGripper: palm link not found, not enforcing grasp hack!\n"<<std::endl;
return false;
}
physics::WorldPtr world = this->model->GetWorld();
if (!world.get())
{
gzerr << "GazeboGraspGripper: world is NULL"<<std::endl;
return false;
}
#ifdef USE_MODEL_ATTACH
physics::ModelPtr obj = world->GetModel(objName);
if (!obj.get()){
std::cerr<<"ERROR: Object ModelPtr "<<objName<<" not found in world, can't attach it"<<std::endl;
return false;
}
gazebo::math::Pose diff = obj->GetLink()->GetWorldPose() - this->palmLink->GetWorldPose();
this->palmLink->AttachStaticModel(obj,diff);
#else
physics::CollisionPtr obj = boost::dynamic_pointer_cast<physics::Collision>(world->GetEntity(objName));
if (!obj.get()){
std::cerr<<"ERROR: Object "<<objName<<" not found in world, can't attach it"<<std::endl;
return false;
}
gazebo::math::Pose diff = obj->GetLink()->GetWorldPose() - this->palmLink->GetWorldPose();
this->fixedJoint->Load(this->palmLink,obj->GetLink(), diff);
this->fixedJoint->Init();
this->fixedJoint->SetHighStop(0, 0);
this->fixedJoint->SetLowStop(0, 0);
if (this->disableCollisionsOnAttach) {
// we can disable collisions of the grasped object, because when the fingers keep colliding with
// it, the fingers keep wobbling, which can create difficulties when moving the arm.
obj->GetLink()->SetCollideMode("none");
}
#endif // USE_MODEL_ATTACH
this->attached=true;
this->attachedObjName=objName;
return true;
}
void GazeboGraspGripper::HandleDetach(const std::string& objName)
{
physics::WorldPtr world = this->model->GetWorld();
if (!world.get())
{
gzerr << "GazeboGraspGripper: world is NULL"<<std::endl<<std::endl;
return;
}
#ifdef USE_MODEL_ATTACH
physics::ModelPtr obj = world->GetModel(objName);
if (!obj.get()){
std::cerr<<"ERROR: Object ModelPtr "<<objName<<" not found in world, can't detach it"<<std::endl;
return;
}
this->palmLink->DetachStaticModel(objName);
#else
physics::CollisionPtr obj = boost::dynamic_pointer_cast<physics::Collision>(world->GetEntity(objName));
if (!obj.get()){
std::cerr<<"ERROR: Object "<<objName<<" not found in world, can't attach it"<<std::endl;
return;
}
else if (this->disableCollisionsOnAttach)
{
obj->GetLink()->SetCollideMode("all");
}
this->fixedJoint->Detach();
#endif // USE_MODEL_ATTACH
this->attached=false;
this->attachedObjName="";
}
| 411 | 0.891009 | 1 | 0.891009 | game-dev | MEDIA | 0.65905 | game-dev | 0.713935 | 1 | 0.713935 |
ohos-decompiler/abc-decompiler | 1,126 | jadx-core/src/main/java/jadx/core/deobf/conditions/DeobfLengthCondition.java | package jadx.core.deobf.conditions;
import jadx.api.JadxArgs;
import jadx.api.deobf.IDeobfCondition;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.PackageNode;
import jadx.core.dex.nodes.RootNode;
public class DeobfLengthCondition implements IDeobfCondition {
private int minLength;
private int maxLength;
@Override
public void init(RootNode root) {
JadxArgs args = root.getArgs();
this.minLength = args.getDeobfuscationMinLength();
this.maxLength = args.getDeobfuscationMaxLength();
}
private Action checkName(String s) {
int len = s.length();
if (len < minLength || len > maxLength) {
return Action.FORCE_RENAME;
}
return Action.NO_ACTION;
}
@Override
public Action check(PackageNode pkg) {
return checkName(pkg.getName());
}
@Override
public Action check(ClassNode cls) {
return checkName(cls.getName());
}
@Override
public Action check(FieldNode fld) {
return checkName(fld.getName());
}
@Override
public Action check(MethodNode mth) {
return checkName(mth.getName());
}
}
| 411 | 0.789851 | 1 | 0.789851 | game-dev | MEDIA | 0.37249 | game-dev | 0.84337 | 1 | 0.84337 |
dust-engine/dust | 5,225 | crates/vdb/src/pool.rs | use std::{alloc::Layout, marker::PhantomData, mem::MaybeUninit};
pub struct Pool {
/// Size of one individual allocation
layout: Layout,
/// Head of freelist
head: u32,
/// Top of free items.
top: u32,
/// Number of items to request when we run out of space.
/// When running out of space, request (1 << chunk_size_log2) * size bytes.
chunk_size_log2: usize,
chunks: Vec<*mut u8>,
count: u32,
}
unsafe impl Send for Pool {}
unsafe impl Sync for Pool {}
/// A memory pool for objects of the same layout.
/// ```
/// use std::alloc::Layout;
/// use dust_vdb::Pool;
/// let item: u64 = 0;
/// // Create a pool of u64s with 2 items in each block.
/// unsafe {
/// let mut pool = Pool::new(Layout::for_value(&item), 1);
/// assert_eq!(pool.alloc::<u64>(), 0);
/// assert_eq!(pool.alloc::<u64>(), 1);
/// assert_eq!(pool.alloc::<u64>(), 2);
/// assert_eq!(pool.alloc::<u64>(), 3);
/// assert_eq!(pool.num_chunks(), 2);
///
/// pool.free(1);
/// pool.free(2);
/// assert_eq!(pool.alloc::<u64>(), 2);
/// assert_eq!(pool.alloc::<u64>(), 1);
/// assert_eq!(pool.alloc::<u64>(), 4);
/// }
/// ```
impl Pool {
pub fn new(layout: Layout, chunk_size_log2: usize) -> Self {
Self {
layout: layout.pad_to_align(),
head: u32::MAX,
top: 0,
chunk_size_log2,
chunks: Vec::new(),
count: 0,
}
}
pub fn count(&self) -> u32 {
self.count
}
pub unsafe fn alloc<T: Default>(&mut self) -> u32 {
debug_assert_eq!(Layout::new::<T>(), self.layout);
let ptr = self.alloc_uninitialized();
let item = self.get_item_mut::<T>(ptr);
*item = T::default();
ptr
}
pub unsafe fn alloc_uninitialized(&mut self) -> u32 {
self.count += 1;
if self.head == u32::MAX {
// allocate new
let top = self.top;
let chunk_index = top as usize >> self.chunk_size_log2;
if chunk_index >= self.chunks.len() {
// allocate new block
let (layout, _) = self.layout.repeat(1 << self.chunk_size_log2).unwrap();
let block = std::alloc::alloc_zeroed(layout);
self.chunks.push(block);
}
self.top += 1;
top
} else {
// take from freelist
let item_location = self.get_mut(self.head);
let next_available_location = *(item_location as *const u32);
let head = self.head;
self.head = next_available_location;
return head;
}
}
pub fn free(&mut self, index: u32) {
self.count -= 1;
unsafe {
let current_free_location = self.get_mut(index);
// The first 4 bytes of the entry is populated with self.head
*(current_free_location as *mut u32) = self.head;
// All other bytes are zeroed
let slice = std::slice::from_raw_parts_mut(current_free_location, self.layout.size());
slice[std::mem::size_of::<u32>()..].fill(0);
// push to freelist
self.head = index;
}
}
pub fn num_chunks(&self) -> usize {
self.chunks.len()
}
#[inline]
pub unsafe fn get(&self, ptr: u32) -> *const u8 {
let chunk_index = (ptr as usize) >> self.chunk_size_log2;
let item_index = (ptr as usize) & ((1 << self.chunk_size_log2) - 1);
return self
.chunks
.get_unchecked(chunk_index)
.add(item_index * self.layout.size());
}
#[inline]
pub unsafe fn get_mut(&mut self, ptr: u32) -> *mut u8 {
let ptr = self.get(ptr);
ptr as *mut u8
}
#[inline]
pub unsafe fn get_item<T>(&self, ptr: u32) -> &T {
debug_assert_eq!(Layout::new::<T>().pad_to_align(), self.layout);
&*(self.get(ptr) as *const T)
}
#[inline]
pub unsafe fn get_item_mut<T>(&mut self, ptr: u32) -> &mut T {
debug_assert_eq!(Layout::new::<T>().pad_to_align(), self.layout);
&mut *(self.get_mut(ptr) as *mut T)
}
pub fn iter_entries<T>(&self) -> PoolIterator<T> {
debug_assert_eq!(Layout::new::<T>().pad_to_align(), self.layout);
PoolIterator {
pool: self,
cur: 0,
_marker: PhantomData,
}
}
}
pub struct PoolIterator<'a, T> {
pool: &'a Pool,
cur: u32,
_marker: PhantomData<T>,
}
impl<'a, T: 'a> Iterator for PoolIterator<'a, T> {
type Item = &'a MaybeUninit<T>;
fn next(&mut self) -> Option<Self::Item> {
if self.cur >= self.pool.top {
return None;
}
let item: &'a MaybeUninit<T> = unsafe {
let item = self.pool.get(self.cur);
std::mem::transmute(item)
};
self.cur += 1;
Some(item)
}
}
impl Drop for Pool {
fn drop(&mut self) {
unsafe {
let (layout, _) = self.layout.repeat(1 << self.chunk_size_log2).unwrap();
for chunk in self.chunks.iter() {
let chunk = *chunk;
std::alloc::dealloc(chunk, layout);
}
}
}
}
| 411 | 0.972883 | 1 | 0.972883 | game-dev | MEDIA | 0.181198 | game-dev | 0.961838 | 1 | 0.961838 |
LiteLDev/LeviLamina | 1,865 | src-server/mc/server/commands/DeferredCommand.h | #pragma once
#include "mc/_HeaderOutputPredefine.h"
// auto generated inclusion list
#include "mc/server/commands/DeferredCommandBase.h"
// auto generated forward declare list
// clang-format off
class CommandContext;
class MinecraftCommands;
struct MCRESULT;
// clang-format on
class DeferredCommand : public ::DeferredCommandBase {
public:
// member variables
// NOLINTBEGIN
::ll::UntypedStorage<8, 8> mUnke036cf;
::ll::UntypedStorage<1, 1> mUnkfecf3f;
::ll::UntypedStorage<1, 1> mUnk15a3f4;
::ll::UntypedStorage<8, 64> mUnked4707;
// NOLINTEND
public:
// prevent constructor by default
DeferredCommand& operator=(DeferredCommand const&);
DeferredCommand(DeferredCommand const&);
DeferredCommand();
public:
// virtual functions
// NOLINTBEGIN
// vIndex: 0
virtual ~DeferredCommand() /*override*/ = default;
// vIndex: 1
virtual void execute(::MinecraftCommands& commands) /*override*/;
// NOLINTEND
public:
// member functions
// NOLINTBEGIN
MCNAPI DeferredCommand(
::std::unique_ptr<::CommandContext> context,
bool suppressOutput,
bool isRequest,
::std::function<void(::MCRESULT)> callback
);
// NOLINTEND
public:
// constructor thunks
// NOLINTBEGIN
MCNAPI void* $ctor(
::std::unique_ptr<::CommandContext> context,
bool suppressOutput,
bool isRequest,
::std::function<void(::MCRESULT)> callback
);
// NOLINTEND
public:
// virtual function thunks
// NOLINTBEGIN
MCNAPI void $execute(::MinecraftCommands& commands);
// NOLINTEND
public:
// vftables
// NOLINTBEGIN
MCNAPI static void** $vftable();
// NOLINTEND
};
| 411 | 0.816375 | 1 | 0.816375 | game-dev | MEDIA | 0.441025 | game-dev | 0.510555 | 1 | 0.510555 |
FreeFalcon/freefalcon-central | 1,201 | src/sim/include/cplift.h | #ifndef _CPLIFT_H
#define _CPLIFT_H
#ifndef _WINDOWS_
#include <windows.h>
#endif
#include "stdhdr.h"
#include "cpobject.h"
#ifdef USE_SH_POOLS
extern MEM_POOL gCockMemPool;
#endif
typedef struct
{
float pan;
float tilt;
int panLabel;
int tiltLabel;
BOOL doLabel;
} LiftInitStr;
//====================================================//
// Structures used for Initialization
//====================================================//
class CPLiftLine : public CPObject
{
#ifdef USE_SH_POOLS
public:
// Overload new/delete to use a SmartHeap pool
void *operator new(size_t size)
{
return MemAllocPtr(gCockMemPool, size, FALSE);
};
void operator delete(void *mem)
{
if (mem) MemFreePtr(mem);
};
#endif
float pan, tilt;
BOOL mDoLabel;
float mCheveron[12][2];
float mLineSegment[6][2];
int mLineSegments;
int mCheverons;
#define CPLIFT_USE_STRING 1
#if CPLIFT_USE_STRING
std::string mString1;
std::string mString2;
#else
char mString1[20];
char mString2[20];
#endif
public:
CPLiftLine(ObjectInitStr*, LiftInitStr*);
virtual ~CPLiftLine();
virtual void DisplayDraw(void);
};
#endif
| 411 | 0.889665 | 1 | 0.889665 | game-dev | MEDIA | 0.38348 | game-dev | 0.615337 | 1 | 0.615337 |
bozimmerman/CoffeeMud | 4,612 | com/planet_ink/coffee_mud/Races/Cobra.java | package com.planet_ink.coffee_mud.Races;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.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.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.List;
import java.util.Vector;
/*
Copyright 2002-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 Cobra extends Snake
{
@Override
public String ID()
{
return "Cobra";
}
private final static String localizedStaticName = CMLib.lang().L("Cobra");
@Override
public String name()
{
return localizedStaticName;
}
@Override
public int shortestMale()
{
return 6;
}
@Override
public int shortestFemale()
{
return 6;
}
@Override
public int heightVariance()
{
return 3;
}
@Override
public int lightestWeight()
{
return 15;
}
@Override
public int weightVariance()
{
return 20;
}
private final static String localizedStaticRacialCat = CMLib.lang().L("Ophidian");
@Override
public String racialCategory()
{
return localizedStaticRacialCat;
}
private final String[] racialAbilityNames = { "SnakeSpeak", "Stigma", "Skill_AutoCrawl", "PoisonousBite" };
private final int[] racialAbilityLevels = { 1, 1, 1, 21 };
private final int[] racialAbilityProficiencies = { 100, 100, 100, 100 };
private final boolean[] racialAbilityQuals = { false, false, false, false };
private final String[] racialAbilityParms = { "", "", "", "Poison_Heartstopper" };
@Override
protected String[] racialAbilityNames()
{
return racialAbilityNames;
}
@Override
protected int[] racialAbilityLevels()
{
return racialAbilityLevels;
}
@Override
protected int[] racialAbilityProficiencies()
{
return racialAbilityProficiencies;
}
@Override
protected boolean[] racialAbilityQuals()
{
return racialAbilityQuals;
}
@Override
public String[] racialAbilityParms()
{
return racialAbilityParms;
}
// an ey ea he ne ar ha to le fo no gi mo wa ta wi
private static final int[] parts={0 ,2 ,2 ,1 ,0 ,0 ,0 ,1 ,0 ,0 ,0 ,0 ,1 ,0 ,1 ,0 };
@Override
public int[] bodyMask()
{
return parts;
}
private static Vector<RawMaterial> resources = new Vector<RawMaterial>();
@Override
public void affectCharStats(final MOB affectedMOB, final CharStats affectableStats)
{
super.affectCharStats(affectedMOB, affectableStats);
affectableStats.setRacialStat(CharStats.STAT_DEXTERITY,18);
}
@Override
public void unaffectCharStats(final MOB affectedMOB, final CharStats affectableStats)
{
super.unaffectCharStats(affectedMOB, affectableStats);
affectableStats.setStat(CharStats.STAT_DEXTERITY,affectedMOB.baseCharStats().getStat(CharStats.STAT_DEXTERITY));
affectableStats.setStat(CharStats.STAT_MAX_DEXTERITY_ADJ,affectedMOB.baseCharStats().getStat(CharStats.STAT_MAX_DEXTERITY_ADJ));
}
@Override
public List<RawMaterial> myResources()
{
synchronized(resources)
{
if(resources.size()==0)
{
resources.addElement(makeResource
(L("a pair of @x1 fangs",name().toLowerCase()),RawMaterial.RESOURCE_BONE));
resources.addElement(makeResource
(L("some @x1 scales",name().toLowerCase()),RawMaterial.RESOURCE_SCALES,L("@x1 scale",name().toLowerCase())));
resources.addElement(makeResource
(L("some @x1 meat",name().toLowerCase()),RawMaterial.RESOURCE_MEAT));
resources.addElement(makeResource
(L("some @x1 blood",name().toLowerCase()),RawMaterial.RESOURCE_BLOOD));
}
}
return resources;
}
}
| 411 | 0.836204 | 1 | 0.836204 | game-dev | MEDIA | 0.895304 | game-dev | 0.745538 | 1 | 0.745538 |
wopss/RED4ext.SDK | 1,139 | include/RED4ext/Scripting/Natives/Generated/game/SmartObjectResource.hpp | #pragma once
// clang-format off
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/DynArray.hpp>
#include <RED4ext/Scripting/Natives/Generated/CResource.hpp>
#include <RED4ext/Scripting/Natives/Generated/game/BodyTypeAnimationDefinition.hpp>
#include <RED4ext/Scripting/Natives/Generated/game/SmartObjectGate.hpp>
#include <RED4ext/Scripting/Natives/Generated/game/SmartObjectType.hpp>
namespace RED4ext
{
namespace game
{
struct SmartObjectResource : CResource
{
static constexpr const char* NAME = "gameSmartObjectResource";
static constexpr const char* ALIAS = NAME;
DynArray<game::SmartObjectGate> entryPoints; // 40
DynArray<game::SmartObjectGate> exitPoints; // 50
DynArray<game::BodyTypeAnimationDefinition> bodyTypes; // 60
DynArray<game::SmartObjectGate> loopAnimations; // 70
game::SmartObjectType type; // 80
uint8_t unk84[0x88 - 0x84]; // 84
};
RED4EXT_ASSERT_SIZE(SmartObjectResource, 0x88);
} // namespace game
using gameSmartObjectResource = game::SmartObjectResource;
} // namespace RED4ext
// clang-format on
| 411 | 0.679789 | 1 | 0.679789 | game-dev | MEDIA | 0.963219 | game-dev | 0.677256 | 1 | 0.677256 |
unity-atoms/fiber | 1,527 | Assets/Fiber/Packages/FiberUtils/Runtime/Pooling/BaseObjectPool.cs | using System;
using System.Collections.Generic;
using UnityEngine;
namespace FiberUtils
{
public abstract class BaseObjectPool<T>
{
protected Queue<T> _currentPool;
protected HashSet<T> _allObjectsCreated;
private readonly Action<T> _onRelease;
public BaseObjectPool(int initialCapacity = 10, Action<T> onRelease = null)
{
_currentPool = new Queue<T>(initialCapacity);
_allObjectsCreated = new HashSet<T>(initialCapacity);
_onRelease = onRelease;
}
public virtual void TryRelease(T pooledObject)
{
if (pooledObject == null)
{
Debug.LogWarning("Tried to release an object that was null.");
return;
}
if (_currentPool.Contains(pooledObject))
{
Debug.LogWarning("Tried to release an object that already was pooled.");
return;
}
if (!_allObjectsCreated.Contains(pooledObject))
{
// Tried to release an object that was never owned by the pool.
// Not logging a warning here because this is a valid use case.
return;
}
_onRelease?.Invoke(pooledObject);
_currentPool.Enqueue(pooledObject);
}
public void Clear()
{
_currentPool.Clear();
_allObjectsCreated.Clear();
}
public int Count => _currentPool.Count;
}
} | 411 | 0.787162 | 1 | 0.787162 | game-dev | MEDIA | 0.589662 | game-dev | 0.744755 | 1 | 0.744755 |
boardgameio/boardgame.io | 27,557 | src/core/reducer.test.ts | /*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
import { INVALID_MOVE } from './constants';
import { applyMiddleware, createStore } from 'redux';
import { CreateGameReducer, TransientHandlingMiddleware } from './reducer';
import { InitializeGame } from './initialize';
import {
makeMove,
gameEvent,
sync,
update,
reset,
undo,
redo,
patch,
} from './action-creators';
import { error } from '../core/logger';
import type { Game, State, SyncInfo } from '../types';
jest.mock('../core/logger', () => ({
info: jest.fn(),
error: jest.fn(),
}));
const game: Game = {
moves: {
A: ({ G }) => G,
B: () => ({ moved: true }),
C: () => ({ victory: true }),
Invalid: () => INVALID_MOVE,
},
endIf: ({ G, ctx }) => (G.victory ? ctx.currentPlayer : undefined),
};
const reducer = CreateGameReducer({ game });
const initialState = InitializeGame({ game });
test('_stateID is incremented', () => {
let state = initialState;
state = reducer(state, makeMove('A'));
expect(state._stateID).toBe(1);
state = reducer(state, gameEvent('endTurn'));
expect(state._stateID).toBe(2);
});
test('move returns INVALID_MOVE', () => {
const game: Game = {
moves: {
A: () => INVALID_MOVE,
},
};
const reducer = CreateGameReducer({ game });
const state = reducer(initialState, makeMove('A'));
expect(error).toBeCalledWith('invalid move: A args: undefined');
expect(state._stateID).toBe(0);
});
test('makeMove', () => {
let state = initialState;
expect(state._stateID).toBe(0);
state = reducer(state, makeMove('unknown'));
expect(state._stateID).toBe(0);
expect(state.G).not.toMatchObject({ moved: true });
expect(error).toBeCalledWith('disallowed move: unknown');
state = reducer(state, makeMove('A'));
expect(state._stateID).toBe(1);
expect(state.G).not.toMatchObject({ moved: true });
state = reducer(state, makeMove('B'));
expect(state._stateID).toBe(2);
expect(state.G).toMatchObject({ moved: true });
state.ctx.gameover = true;
state = reducer(state, makeMove('B'));
expect(state._stateID).toBe(2);
expect(error).toBeCalledWith('cannot make move after game end');
state = reducer(state, gameEvent('endTurn'));
expect(state._stateID).toBe(2);
expect(error).toBeCalledWith('cannot call event after game end');
});
test('disable move by invalid playerIDs', () => {
let state = initialState;
expect(state._stateID).toBe(0);
// playerID="1" cannot move right now.
state = reducer(state, makeMove('A', null, '1'));
expect(state._stateID).toBe(0);
// playerID="1" cannot call events right now.
state = reducer(state, gameEvent('endTurn', null, '1'));
expect(state._stateID).toBe(0);
// playerID="0" can move.
state = reducer(state, makeMove('A', null, '0'));
expect(state._stateID).toBe(1);
// playerID=undefined can always move.
state = reducer(state, makeMove('A'));
expect(state._stateID).toBe(2);
});
test('sync', () => {
const state = reducer(
undefined,
sync({ state: { G: 'restored' } } as SyncInfo)
);
expect(state).toEqual({ G: 'restored' });
});
test('update', () => {
const state = reducer(undefined, update({ G: 'restored' } as State, []));
expect(state).toEqual({ G: 'restored' });
});
test('valid patch', () => {
const originalState = { _stateID: 0, G: 'patch' } as State;
const state = reducer(
originalState,
patch(0, 1, [{ op: 'replace', path: '/_stateID', value: 1 }], [])
);
expect(state).toEqual({ _stateID: 1, G: 'patch' });
});
test('invalid patch', () => {
const originalState = { _stateID: 0, G: 'patch' } as State;
const { transients, ...state } = reducer(
originalState,
patch(0, 1, [{ op: 'replace', path: '/_stateIDD', value: 1 }], [])
);
expect(state).toEqual(originalState);
expect(transients.error.type).toEqual('update/patch_failed');
// It's an array.
expect(transients.error.payload.length).toEqual(1);
// It looks like the standard rfc6902 error language.
expect(transients.error.payload[0].toString()).toContain('/_stateIDD');
});
test('reset', () => {
let state = reducer(initialState, makeMove('A'));
expect(state).not.toEqual(initialState);
state = reducer(state, reset(initialState));
expect(state).toEqual(initialState);
});
test('victory', () => {
let state = reducer(initialState, makeMove('A'));
state = reducer(state, gameEvent('endTurn'));
expect(state.ctx.gameover).toEqual(undefined);
state = reducer(state, makeMove('B'));
state = reducer(state, gameEvent('endTurn'));
expect(state.ctx.gameover).toEqual(undefined);
state = reducer(state, makeMove('C'));
expect(state.ctx.gameover).toEqual('0');
});
test('endTurn', () => {
{
const state = reducer(initialState, gameEvent('endTurn'));
expect(state.ctx.turn).toBe(2);
}
{
const reducer = CreateGameReducer({ game, isClient: true });
const state = reducer(initialState, gameEvent('endTurn'));
expect(state.ctx.turn).toBe(1);
}
});
test('light client when multiplayer=true', () => {
const game: Game = {
moves: { A: () => ({ win: true }) },
endIf: ({ G }) => G.win,
};
{
const reducer = CreateGameReducer({ game });
let state = InitializeGame({ game });
expect(state.ctx.gameover).toBe(undefined);
state = reducer(state, makeMove('A'));
expect(state.ctx.gameover).toBe(true);
}
{
const reducer = CreateGameReducer({ game, isClient: true });
let state = InitializeGame({ game });
expect(state.ctx.gameover).toBe(undefined);
state = reducer(state, makeMove('A'));
expect(state.ctx.gameover).toBe(undefined);
}
});
test('disable optimistic updates', () => {
const game: Game = {
moves: {
A: {
move: () => ({ A: true }),
client: false,
},
},
};
{
const reducer = CreateGameReducer({ game });
let state = InitializeGame({ game });
expect(state.G).not.toMatchObject({ A: true });
state = reducer(state, makeMove('A'));
expect(state.G).toMatchObject({ A: true });
}
{
const reducer = CreateGameReducer({ game, isClient: true });
let state = InitializeGame({ game });
expect(state.G).not.toMatchObject({ A: true });
state = reducer(state, makeMove('A'));
expect(state.G).not.toMatchObject({ A: true });
}
});
test('numPlayers', () => {
const numPlayers = 4;
const state = InitializeGame({ game, numPlayers });
expect(state.ctx.numPlayers).toBe(4);
});
test('deltalog', () => {
let state = initialState;
const actionA = makeMove('A');
const actionB = makeMove('B');
const actionC = gameEvent('endTurn');
state = reducer(state, actionA);
expect(state.deltalog).toEqual([
{
action: actionA,
_stateID: 0,
phase: null,
turn: 1,
},
]);
state = reducer(state, actionB);
expect(state.deltalog).toEqual([
{
action: actionB,
_stateID: 1,
phase: null,
turn: 1,
},
]);
state = reducer(state, actionC);
expect(state.deltalog).toEqual([
{
action: actionC,
_stateID: 2,
phase: null,
turn: 1,
},
]);
});
describe('Events API', () => {
const fn = ({ events }) => (events ? {} : { error: true });
const game: Game = {
setup: () => ({}),
phases: { A: {} },
turn: {
onBegin: fn,
onEnd: fn,
onMove: fn,
},
};
const reducer = CreateGameReducer({ game });
let state = InitializeGame({ game });
test('is attached at the beginning', () => {
expect(state.G).not.toEqual({ error: true });
});
test('is attached at the end of turns', () => {
state = reducer(state, gameEvent('endTurn'));
expect(state.G).not.toEqual({ error: true });
});
test('is attached at the end of phases', () => {
state = reducer(state, gameEvent('endPhase'));
expect(state.G).not.toEqual({ error: true });
});
});
describe('Plugin Invalid Action API', () => {
const pluginName = 'validator';
const message = 'G.value must divide by 5';
const game: Game<{ value: number }> = {
setup: () => ({ value: 5 }),
plugins: [
{
name: pluginName,
isInvalid: ({ G }) => {
if (G.value % 5 !== 0) return message;
return false;
},
},
],
moves: {
setValue: ({ G }, arg: number) => {
G.value = arg;
},
},
phases: {
unenterable: {
onBegin: () => ({ value: 13 }),
},
enterable: {
onBegin: () => ({ value: 25 }),
},
},
};
let state: State;
beforeEach(() => {
state = InitializeGame({ game });
});
describe('multiplayer client', () => {
const reducer = CreateGameReducer({ game });
test('move is cancelled if plugin declares it invalid', () => {
state = reducer(state, makeMove('setValue', [6], '0'));
expect(state.G).toMatchObject({ value: 5 });
expect(state['transients'].error).toEqual({
type: 'action/plugin_invalid',
payload: { plugin: pluginName, message },
});
});
test('move is processed if no plugin declares it invalid', () => {
state = reducer(state, makeMove('setValue', [15], '0'));
expect(state.G).toMatchObject({ value: 15 });
expect(state['transients']).toBeUndefined();
});
test('event is cancelled if plugin declares it invalid', () => {
state = reducer(state, gameEvent('setPhase', 'unenterable', '0'));
expect(state.G).toMatchObject({ value: 5 });
expect(state.ctx.phase).toBe(null);
expect(state['transients'].error).toEqual({
type: 'action/plugin_invalid',
payload: { plugin: pluginName, message },
});
});
test('event is processed if no plugin declares it invalid', () => {
state = reducer(state, gameEvent('setPhase', 'enterable', '0'));
expect(state.G).toMatchObject({ value: 25 });
expect(state.ctx.phase).toBe('enterable');
expect(state['transients']).toBeUndefined();
});
});
describe('local client', () => {
const reducer = CreateGameReducer({ game, isClient: true });
test('move is cancelled if plugin declares it invalid', () => {
state = reducer(state, makeMove('setValue', [6], '0'));
expect(state.G).toMatchObject({ value: 5 });
expect(state['transients'].error).toEqual({
type: 'action/plugin_invalid',
payload: { plugin: pluginName, message },
});
});
test('move is processed if no plugin declares it invalid', () => {
state = reducer(state, makeMove('setValue', [15], '0'));
expect(state.G).toMatchObject({ value: 15 });
expect(state['transients']).toBeUndefined();
});
});
});
describe('Random inside setup()', () => {
const game1: Game = {
seed: 'seed1',
setup: (ctx) => ({ n: ctx.random.D6() }),
};
const game2: Game = {
seed: 'seed2',
setup: (ctx) => ({ n: ctx.random.D6() }),
};
const game3: Game = {
seed: 'seed2',
setup: (ctx) => ({ n: ctx.random.D6() }),
};
test('setting seed', () => {
const state1 = InitializeGame({ game: game1 });
const state2 = InitializeGame({ game: game2 });
const state3 = InitializeGame({ game: game3 });
expect(state1.G.n).not.toBe(state2.G.n);
expect(state2.G.n).toBe(state3.G.n);
});
});
describe('redact', () => {
const game: Game = {
setup: () => ({
isASecret: false,
}),
moves: {
A: {
move: ({ G }) => G,
redact: ({ G }) => G.isASecret,
},
B: ({ G }) => {
return { ...G, isASecret: true };
},
},
};
const reducer = CreateGameReducer({ game });
let state = InitializeGame({ game });
test('move A is not secret and is not redact', () => {
state = reducer(state, makeMove('A', ['not redact'], '0'));
expect(state.G).toMatchObject({
isASecret: false,
});
const [lastLogEntry] = state.deltalog.slice(-1);
expect(lastLogEntry).toMatchObject({
action: {
payload: {
type: 'A',
args: ['not redact'],
},
},
redact: false,
});
});
test('move A is secret and is redact', () => {
state = reducer(state, makeMove('B', ['not redact'], '0'));
state = reducer(state, makeMove('A', ['redact'], '0'));
expect(state.G).toMatchObject({
isASecret: true,
});
const [lastLogEntry] = state.deltalog.slice(-1);
expect(lastLogEntry).toMatchObject({
action: {
payload: {
type: 'A',
args: ['redact'],
},
},
redact: true,
});
});
});
describe('undo / redo', () => {
const game: Game = {
seed: 0,
moves: {
move: ({ G }, arg: string) => ({ ...G, [arg]: true }),
roll: ({ G, random }) => {
G.roll = random.D6();
},
},
turn: {
stages: {
special: {},
},
},
};
beforeEach(() => {
jest.clearAllMocks();
});
const reducer = CreateGameReducer({ game });
const initialState = InitializeGame({ game });
// TODO: Check if this test is still actually required after removal of APIs from ctx
test('plugin APIs are not included in undo state', () => {
let state = reducer(initialState, makeMove('move', 'A', '0'));
state = reducer(state, makeMove('move', 'B', '0'));
expect(state.G).toMatchObject({ A: true, B: true });
expect(state._undo[1].ctx).not.toHaveProperty('events');
expect(state._undo[1].ctx).not.toHaveProperty('random');
});
test('undo restores previous state after move', () => {
const initial = reducer(initialState, makeMove('move', 'A', '0'));
let newState = reducer(initial, makeMove('roll', null, '0'));
newState = reducer(newState, undo());
expect(newState.G).toEqual(initial.G);
expect(newState.ctx).toEqual(initial.ctx);
expect(newState.plugins).toEqual(initial.plugins);
});
test('undo restores previous state after event', () => {
const initial = reducer(
initialState,
gameEvent('setStage', 'special', '0')
);
let newState = reducer(initial, gameEvent('endStage', undefined, '0'));
expect(error).not.toBeCalled();
// Make sure we actually modified the stage.
expect(newState.ctx.activePlayers).not.toEqual(initial.ctx.activePlayers);
newState = reducer(newState, undo());
expect(error).not.toBeCalled();
expect(newState.G).toEqual(initial.G);
expect(newState.ctx).toEqual(initial.ctx);
expect(newState.plugins).toEqual(initial.plugins);
});
test('redo restores undone state', () => {
let state = initialState;
// Make two moves.
const state1 = (state = reducer(state, makeMove('move', 'A', '0')));
const state2 = (state = reducer(state, makeMove('roll', null, '0')));
// Undo both of them.
state = reducer(state, undo());
state = reducer(state, undo());
// Redo one of them.
state = reducer(state, redo());
expect(state.G).toEqual(state1.G);
expect(state.ctx).toEqual(state1.ctx);
expect(state.plugins).toEqual(state1.plugins);
// Redo a second time.
state = reducer(state, redo());
expect(state.G).toEqual(state2.G);
expect(state.ctx).toEqual(state2.ctx);
expect(state.plugins).toEqual(state2.plugins);
});
test('can undo redone state', () => {
let state = reducer(initialState, makeMove('move', 'A', '0'));
state = reducer(state, undo());
state = reducer(state, redo());
state = reducer(state, undo());
expect(state.G).toMatchObject(initialState.G);
expect(state.ctx).toMatchObject(initialState.ctx);
expect(state.plugins).toMatchObject(initialState.plugins);
});
test('undo has no effect if nothing to undo', () => {
let state = reducer(initialState, undo());
state = reducer(state, undo());
state = reducer(state, undo());
expect(state.G).toMatchObject(initialState.G);
expect(state.ctx).toMatchObject(initialState.ctx);
expect(state.plugins).toMatchObject(initialState.plugins);
});
test('redo works after multiple undos', () => {
let state = reducer(initialState, makeMove('move', 'A', '0'));
state = reducer(state, undo());
state = reducer(state, undo());
state = reducer(state, undo());
state = reducer(state, redo());
state = reducer(state, makeMove('move', 'C', '0'));
expect(state.G).toMatchObject({ A: true, C: true });
state = reducer(state, undo());
expect(state.G).toMatchObject({ A: true });
state = reducer(state, redo());
expect(state.G).toMatchObject({ A: true, C: true });
});
test('redo only resets deltalog if nothing to redo', () => {
const state = reducer(initialState, makeMove('move', 'A', '0'));
expect(reducer(state, redo())).toMatchObject({
...state,
deltalog: [],
transients: {
error: {
type: 'action/action_invalid',
},
},
});
});
});
test('disable undo / redo', () => {
const game: Game = {
seed: 0,
disableUndo: true,
moves: {
move: ({ G }, arg: string) => ({ ...G, [arg]: true }),
},
};
const reducer = CreateGameReducer({ game });
let state = InitializeGame({ game });
state = reducer(state, makeMove('move', 'A', '0'));
expect(state.G).toMatchObject({ A: true });
expect(state._undo).toEqual([]);
expect(state._redo).toEqual([]);
state = reducer(state, makeMove('move', 'B', '0'));
expect(state.G).toMatchObject({ A: true, B: true });
expect(state._undo).toEqual([]);
expect(state._redo).toEqual([]);
state = reducer(state, undo());
expect(state.G).toMatchObject({ A: true, B: true });
expect(state._undo).toEqual([]);
expect(state._redo).toEqual([]);
state = reducer(state, undo());
expect(state.G).toMatchObject({ A: true, B: true });
expect(state._undo).toEqual([]);
expect(state._redo).toEqual([]);
state = reducer(state, redo());
expect(state.G).toMatchObject({ A: true, B: true });
expect(state._undo).toEqual([]);
expect(state._redo).toEqual([]);
});
describe('undo stack', () => {
const game: Game = {
moves: {
basic: () => {},
endTurn: ({ events }) => {
events.endTurn();
},
},
};
const reducer = CreateGameReducer({ game });
let state = InitializeGame({ game });
test('contains initial state at start of game', () => {
expect(state._undo).toHaveLength(1);
expect(state._undo[0].ctx).toEqual(state.ctx);
expect(state._undo[0].plugins).toEqual(state.plugins);
});
test('grows when a move is made', () => {
state = reducer(state, makeMove('basic', null, '0'));
expect(state._undo).toHaveLength(2);
expect(state._undo[1].moveType).toBe('basic');
expect(state._undo[1].ctx).toEqual(state.ctx);
expect(state._undo[1].plugins).toEqual(state.plugins);
});
test('shrinks when a move is undone', () => {
state = reducer(state, undo());
expect(state._undo).toHaveLength(1);
expect(state._undo[0].ctx).toEqual(state.ctx);
expect(state._undo[0].plugins).toEqual(state.plugins);
});
test('grows when a move is redone', () => {
state = reducer(state, redo());
expect(state._undo).toHaveLength(2);
expect(state._undo[1].moveType).toBe('basic');
expect(state._undo[1].ctx).toEqual(state.ctx);
expect(state._undo[1].plugins).toEqual(state.plugins);
});
test('is reset when a turn ends', () => {
state = reducer(state, makeMove('endTurn'));
expect(state._undo).toHaveLength(1);
expect(state._undo[0].ctx).toEqual(state.ctx);
expect(state._undo[0].plugins).toEqual(state.plugins);
expect(state._undo[0].moveType).toBe('endTurn');
});
test('can’t undo at the start of a turn', () => {
const newState = reducer(state, undo());
expect(newState).toMatchObject({
...state,
deltalog: [],
transients: {
error: {
type: 'action/action_invalid',
},
},
});
});
test('can’t undo another player’s move', () => {
state = reducer(state, makeMove('basic', null, '1'));
const newState = reducer(state, undo('0'));
expect(newState).toMatchObject({
...state,
deltalog: [],
transients: {
error: {
type: 'action/action_invalid',
},
},
});
});
});
describe('redo stack', () => {
const game: Game = {
moves: {
basic: () => {},
endTurn: ({ events }) => {
events.endTurn();
},
},
};
const reducer = CreateGameReducer({ game });
let state = InitializeGame({ game });
test('is empty at start of game', () => {
expect(state._redo).toHaveLength(0);
});
test('grows when a move is undone', () => {
state = reducer(state, makeMove('basic', null, '0'));
state = reducer(state, undo());
expect(state._redo).toHaveLength(1);
expect(state._redo[0].moveType).toBe('basic');
});
test('shrinks when a move is redone', () => {
state = reducer(state, redo());
expect(state._redo).toHaveLength(0);
});
test('is reset when a move is made', () => {
state = reducer(state, makeMove('basic', null, '0'));
state = reducer(state, undo());
state = reducer(state, undo());
expect(state._redo).toHaveLength(2);
state = reducer(state, makeMove('basic', null, '0'));
expect(state._redo).toHaveLength(0);
});
test('is reset when a turn ends', () => {
state = reducer(state, makeMove('basic', null, '0'));
state = reducer(state, undo());
expect(state._redo).toHaveLength(1);
state = reducer(state, makeMove('endTurn'));
expect(state._redo).toHaveLength(0);
});
test('can’t redo another player’s undo', () => {
state = reducer(state, makeMove('basic', null, '1'));
state = reducer(state, undo('1'));
expect(state._redo).toHaveLength(1);
const newState = reducer(state, redo('0'));
expect(state._redo).toHaveLength(1);
expect(newState).toMatchObject({
...state,
deltalog: [],
transients: {
error: {
type: 'action/action_invalid',
},
},
});
});
});
describe('undo / redo with stages', () => {
const game: Game = {
setup: () => ({ A: false, B: false, C: false }),
turn: {
activePlayers: { currentPlayer: 'start' },
stages: {
start: {
moves: {
moveA: {
move: ({ G, events }, moveAisReversible) => {
events.setStage('A');
return { ...G, moveAisReversible, A: true };
},
undoable: ({ G }) => G.moveAisReversible > 0,
},
},
},
A: {
moves: {
moveB: {
move: ({ G, events }) => {
events.setStage('B');
return { ...G, B: true };
},
undoable: false,
},
},
},
B: {
moves: {
moveC: {
move: ({ G, events }) => {
events.setStage('C');
return { ...G, C: true };
},
undoable: true,
},
},
},
C: {
moves: {},
},
},
},
};
const reducer = CreateGameReducer({ game });
let state = InitializeGame({ game });
test('moveA sets state & moves player to stage A (undoable)', () => {
state = reducer(state, makeMove('moveA', true, '0'));
expect(state.G).toMatchObject({
moveAisReversible: true,
A: true,
B: false,
C: false,
});
expect(state.ctx.activePlayers['0']).toBe('A');
});
test('undo undoes last move (moveA)', () => {
state = reducer(state, undo('0'));
expect(state.G).toMatchObject({
A: false,
B: false,
C: false,
});
expect(state.ctx.activePlayers['0']).toBe('start');
});
test('redo redoes moveA', () => {
state = reducer(state, redo('0'));
expect(state.G).toMatchObject({
moveAisReversible: true,
A: true,
B: false,
C: false,
});
expect(state.ctx.activePlayers['0']).toBe('A');
});
test('undo undoes last move after redo (moveA)', () => {
state = reducer(state, undo('0'));
expect(state.G).toMatchObject({
A: false,
B: false,
C: false,
});
expect(state.ctx.activePlayers['0']).toBe('start');
});
test('moveA sets state & moves player to stage A (not undoable)', () => {
state = reducer(state, makeMove('moveA', false, '0'));
expect(state.G).toMatchObject({
moveAisReversible: false,
A: true,
B: false,
C: false,
});
expect(state.ctx.activePlayers['0']).toBe('A');
});
test('moveB sets state & moves player to stage B', () => {
state = reducer(state, makeMove('moveB', [], '0'));
expect(state.G).toMatchObject({
moveAisReversible: false,
A: true,
B: true,
C: false,
});
expect(state.ctx.activePlayers['0']).toBe('B');
});
test('undo doesn’t undo last move if not undoable (moveB)', () => {
state = reducer(state, undo('0'));
expect(state.G).toMatchObject({
moveAisReversible: false,
A: true,
B: true,
C: false,
});
expect(state.ctx.activePlayers['0']).toBe('B');
});
test('moveC sets state & moves player to stage C', () => {
state = reducer(state, makeMove('moveC', [], '0'));
expect(state.G).toMatchObject({
moveAisReversible: false,
A: true,
B: true,
C: true,
});
expect(state.ctx.activePlayers['0']).toBe('C');
});
test('undo undoes last move (moveC)', () => {
state = reducer(state, undo('0'));
expect(state.G).toMatchObject({
moveAisReversible: false,
A: true,
B: true,
C: false,
});
expect(state.ctx.activePlayers['0']).toBe('B');
});
test('redo redoes moveC', () => {
state = reducer(state, redo('0'));
expect(state.G).toMatchObject({
moveAisReversible: false,
A: true,
B: true,
C: true,
});
expect(state.ctx.activePlayers['0']).toBe('C');
});
test('undo undoes last move after redo (moveC)', () => {
state = reducer(state, undo('0'));
expect(state.G).toMatchObject({
moveAisReversible: false,
A: true,
B: true,
C: false,
});
expect(state.ctx.activePlayers['0']).toBe('B');
});
test('undo doesn’t undo last move if not undoable after undo/redo', () => {
state = reducer(state, undo('0'));
expect(state.G).toMatchObject({
moveAisReversible: false,
A: true,
B: true,
C: false,
});
expect(state.ctx.activePlayers['0']).toBe('B');
});
});
describe('TransientHandlingMiddleware', () => {
const middleware = applyMiddleware(TransientHandlingMiddleware);
let store = null;
beforeEach(() => {
store = createStore(reducer, initialState, middleware);
});
test('regular dispatch result has no transients', () => {
const result = store.dispatch(makeMove('A'));
expect(result).toEqual(
expect.not.objectContaining({ transients: expect.anything() })
);
expect(result).toEqual(
expect.not.objectContaining({ stripTransientsResult: expect.anything() })
);
});
test('failing dispatch result contains transients', () => {
const result = store.dispatch(makeMove('Invalid'));
expect(result).toMatchObject({
transients: {
error: {
type: 'action/invalid_move',
},
},
});
});
});
| 411 | 0.771452 | 1 | 0.771452 | game-dev | MEDIA | 0.576147 | game-dev,testing-qa | 0.657317 | 1 | 0.657317 |
m5stack/StackFlow | 6,037 | projects/llm_framework/include/sherpa/sherpa-ncnn/layer/mips/padding_pack4.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void padding_constant_pack4_msa(const Mat& src, Mat& dst, int top, int bottom, int left, int right, v4f32 v)
{
const float* ptr = src;
float* outptr = dst;
int top_size = top * dst.w;
int bottom_size = bottom * dst.w;
// fill top
for (int y = 0; y < top_size; y++)
{
__msa_st_w((v4i32)v, outptr, 0);
outptr += 4;
}
// fill center
for (int y = 0; y < src.h; y++)
{
for (int x = 0; x < left; x++)
{
__msa_st_w((v4i32)v, outptr, 0);
outptr += 4;
}
for (int x = 0; x < src.w; x++)
{
__builtin_prefetch(ptr + 32);
__msa_st_w(__msa_ld_w(ptr, 0), outptr, 0);
ptr += 4;
outptr += 4;
}
for (int x = 0; x < right; x++)
{
__msa_st_w((v4i32)v, outptr, 0);
outptr += 4;
}
}
// fill top
for (int y = 0; y < bottom_size; y++)
{
__msa_st_w((v4i32)v, outptr, 0);
outptr += 4;
}
}
static void padding_replicate_pack4_msa(const Mat& src, Mat& dst, int top, int bottom, int left, int right)
{
const float* ptr = src;
float* outptr = dst;
// fill top
for (int y = 0; y < top; y++)
{
const float* ptr0 = ptr;
v4f32 _p = (v4f32)__msa_ld_w(ptr0, 0);
for (int x = 0; x < left; x++)
{
__msa_st_w((v4i32)_p, outptr, 0);
outptr += 4;
}
for (int x = 0; x < src.w; x++)
{
_p = (v4f32)__msa_ld_w(ptr0, 0);
__msa_st_w((v4i32)_p, outptr, 0);
ptr0 += 4;
outptr += 4;
}
for (int x = 0; x < right; x++)
{
__msa_st_w((v4i32)_p, outptr, 0);
outptr += 4;
}
}
// fill center
for (int y = 0; y < src.h; y++)
{
v4f32 _p = (v4f32)__msa_ld_w(ptr, 0);
for (int x = 0; x < left; x++)
{
__msa_st_w((v4i32)_p, outptr, 0);
outptr += 4;
}
for (int x = 0; x < src.w; x++)
{
_p = (v4f32)__msa_ld_w(ptr, 0);
__msa_st_w((v4i32)_p, outptr, 0);
ptr += 4;
outptr += 4;
}
for (int x = 0; x < right; x++)
{
__msa_st_w((v4i32)_p, outptr, 0);
outptr += 4;
}
}
// fill bottom
ptr -= src.w * 4;
for (int y = 0; y < bottom; y++)
{
const float* ptr0 = ptr;
v4f32 _p = (v4f32)__msa_ld_w(ptr0, 0);
for (int x = 0; x < left; x++)
{
__msa_st_w((v4i32)_p, outptr, 0);
outptr += 4;
}
for (int x = 0; x < src.w; x++)
{
_p = (v4f32)__msa_ld_w(ptr0, 0);
__msa_st_w((v4i32)_p, outptr, 0);
ptr0 += 4;
outptr += 4;
}
for (int x = 0; x < right; x++)
{
__msa_st_w((v4i32)_p, outptr, 0);
outptr += 4;
}
}
}
static void padding_reflect_pack4_msa(const Mat& src, Mat& dst, int top, int bottom, int left, int right)
{
const float* ptr = src;
float* outptr = dst;
// fill top
ptr += top * src.w * 4;
for (int y = 0; y < top; y++)
{
const float* ptr0 = ptr;
for (int x = 0; x < left; x++)
{
v4f32 _p = (v4f32)__msa_ld_w(ptr0 + (left - x) * 4, 0);
__msa_st_w((v4i32)_p, outptr, 0);
outptr += 4;
}
for (int x = 0; x < src.w; x++)
{
v4f32 _p = (v4f32)__msa_ld_w(ptr0, 0);
__msa_st_w((v4i32)_p, outptr, 0);
ptr0 += 4;
outptr += 4;
}
for (int x = 0; x < right; x++)
{
v4f32 _p = (v4f32)__msa_ld_w(ptr0 - 8 - x * 4, 0);
__msa_st_w((v4i32)_p, outptr, 0);
outptr += 4;
}
ptr -= src.w * 4;
}
// fill center
for (int y = 0; y < src.h; y++)
{
for (int x = 0; x < left; x++)
{
v4f32 _p = (v4f32)__msa_ld_w(ptr + (left - x) * 4, 0);
__msa_st_w((v4i32)_p, outptr, 0);
outptr += 4;
}
for (int x = 0; x < src.w; x++)
{
v4f32 _p = (v4f32)__msa_ld_w(ptr, 0);
__msa_st_w((v4i32)_p, outptr, 0);
ptr += 4;
outptr += 4;
}
for (int x = 0; x < right; x++)
{
v4f32 _p = (v4f32)__msa_ld_w(ptr - 8 - x * 4, 0);
__msa_st_w((v4i32)_p, outptr, 0);
outptr += 4;
}
}
// fill bottom
ptr -= 2 * src.w * 4;
for (int y = 0; y < bottom; y++)
{
const float* ptr0 = ptr;
for (int x = 0; x < left; x++)
{
v4f32 _p = (v4f32)__msa_ld_w(ptr0 + (left - x) * 4, 0);
__msa_st_w((v4i32)_p, outptr, 0);
outptr += 4;
}
for (int x = 0; x < src.w; x++)
{
v4f32 _p = (v4f32)__msa_ld_w(ptr0, 0);
__msa_st_w((v4i32)_p, outptr, 0);
ptr0 += 4;
outptr += 4;
}
for (int x = 0; x < right; x++)
{
v4f32 _p = (v4f32)__msa_ld_w(ptr0 - 8 - x * 4, 0);
__msa_st_w((v4i32)_p, outptr, 0);
outptr += 4;
}
ptr -= src.w * 4;
}
}
| 411 | 0.75907 | 1 | 0.75907 | game-dev | MEDIA | 0.199263 | game-dev | 0.716426 | 1 | 0.716426 |
cmangos/mangos-cata | 17,490 | src/game/AI/ScriptDevAI/scripts/outland/tempest_keep/arcatraz/instance_arcatraz.cpp | /* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information
* 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
*/
/* ScriptData
SDName: Instance_Arcatraz
SD%Complete: 80
SDComment: Mainly Harbringer Skyriss event
SDCategory: Tempest Keep, The Arcatraz
EndScriptData */
#include "AI/ScriptDevAI/include/precompiled.h"
#include "arcatraz.h"
/* Arcatraz encounters:
1 - Zereketh the Unbound event
2 - Dalliah the Doomsayer event
3 - Wrath-Scryer Soccothrates event
4 - Harbinger Skyriss event, 5 sub-events
*/
enum
{
SAY_SOCCOTHRATES_AGGRO = -1552039,
SAY_SOCCOTHRATES_DEATH = -1552043,
YELL_MELLICHAR_INTRO1 = -1552023,
YELL_MELLICHAR_INTRO2 = -1552024,
YELL_MELLICHAR_RELEASE1 = -1552025,
YELL_MELLICHAR_RELEASE2 = -1552026,
YELL_MELLICHAR_RELEASE3 = -1552027,
YELL_MELLICHAR_RELEASE4 = -1552028,
YELL_MELLICHAR_RELEASE5 = -1552029,
YELL_MELLICAR_WELCOME = -1552030,
SAY_SKYRISS_INTRO = -1552000,
SAY_SKYRISS_AGGRO = -1552001,
SAY_MILLHOUSE_COMPLETE = -1552022,
// Spells used by Mellichar during the dialogue
SPELL_TARGET_BETA = 36854,
SPELL_TARGET_ALPHA = 36856,
SPELL_TARGET_DELTA = 36857,
SPELL_TARGET_GAMMA = 36858,
SPELL_SIMPLE_TELEPORT = 12980,
SPELL_MIND_REND = 36859,
};
static const DialogueEntry aArcatrazDialogue[] =
{
// Soccothares taunts
{TYPE_DALLIAH, 0, 5000},
{SAY_SOCCOTHRATES_AGGRO, NPC_SOCCOTHRATES, 0},
{TYPE_SOCCOTHRATES, 0, 5000},
{SAY_SOCCOTHRATES_DEATH, NPC_SOCCOTHRATES, 0},
// Skyriss event
{YELL_MELLICHAR_INTRO1, NPC_MELLICHAR, 22000},
{YELL_MELLICHAR_INTRO2, NPC_MELLICHAR, 7000},
{SPELL_TARGET_ALPHA, 0, 7000},
{YELL_MELLICHAR_RELEASE1, NPC_MELLICHAR, 0},
{YELL_MELLICHAR_RELEASE2, NPC_MELLICHAR, 7000},
{SPELL_TARGET_BETA, 0, 7000},
{TYPE_WARDEN_2, 0, 0},
{YELL_MELLICHAR_RELEASE3, NPC_MELLICHAR, 7000},
{SPELL_TARGET_DELTA, 0, 7000},
{TYPE_WARDEN_3, 0, 0},
{YELL_MELLICHAR_RELEASE4, NPC_MELLICHAR, 7000},
{SPELL_TARGET_GAMMA, 0, 7000},
{TYPE_WARDEN_4, 0, 0},
{YELL_MELLICHAR_RELEASE5, NPC_MELLICHAR, 8000},
{TYPE_WARDEN_5, 0, 5000},
{SAY_SKYRISS_INTRO, NPC_SKYRISS, 25000},
{YELL_MELLICAR_WELCOME, NPC_MELLICHAR, 3000},
{SAY_SKYRISS_AGGRO, NPC_SKYRISS, 0},
{0, 0, 0},
};
instance_arcatraz::instance_arcatraz(Map* pMap) : ScriptedInstance(pMap), DialogueHelper(aArcatrazDialogue),
m_uiResetDelayTimer(0),
m_uiEntranceEventTimer(0),
m_uiKilledWardens(0)
{
Initialize();
}
void instance_arcatraz::Initialize()
{
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
InitializeDialogueHelper(this);
}
void instance_arcatraz::OnPlayerEnter(Player* /*pPlayer*/)
{
// Check encounter states
if (GetData(TYPE_ENTRANCE) == DONE || GetData(TYPE_ENTRANCE) == IN_PROGRESS)
return;
SetData(TYPE_ENTRANCE, IN_PROGRESS);
m_uiEntranceEventTimer = 1000;
}
void instance_arcatraz::OnObjectCreate(GameObject* pGo)
{
switch (pGo->GetEntry())
{
case GO_CORE_SECURITY_FIELD_ALPHA:
if (m_auiEncounter[2] == DONE)
pGo->SetGoState(GO_STATE_ACTIVE);
break;
case GO_CORE_SECURITY_FIELD_BETA:
if (m_auiEncounter[1] == DONE)
pGo->SetGoState(GO_STATE_ACTIVE);
break;
case GO_SEAL_SPHERE:
case GO_POD_ALPHA:
case GO_POD_BETA:
case GO_POD_DELTA:
case GO_POD_GAMMA:
case GO_POD_OMEGA:
break;
default:
return;
}
m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid();
}
void instance_arcatraz::OnCreatureCreate(Creature* pCreature)
{
switch (pCreature->GetEntry())
{
case NPC_SKYRISS:
case NPC_MILLHOUSE:
m_lSkyrissEventMobsGuidList.push_back(pCreature->GetObjectGuid());
// no break here because we want them in both lists
case NPC_PRISON_APHPA_POD:
case NPC_PRISON_BETA_POD:
case NPC_PRISON_DELTA_POD:
case NPC_PRISON_GAMMA_POD:
case NPC_PRISON_BOSS_POD:
case NPC_MELLICHAR:
case NPC_DALLIAH:
case NPC_SOCCOTHRATES:
m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid();
break;
case NPC_BLAZING_TRICKSTER:
case NPC_PHASE_HUNTER:
case NPC_AKKIRIS:
case NPC_SULFURON:
case NPC_TW_DRAKONAAR:
case NPC_BL_DRAKONAAR:
m_lSkyrissEventMobsGuidList.push_back(pCreature->GetObjectGuid());
break;
}
}
void instance_arcatraz::SetData(uint32 uiType, uint32 uiData)
{
switch (uiType)
{
case TYPE_ENTRANCE:
case TYPE_ZEREKETH:
m_auiEncounter[uiType] = uiData;
break;
case TYPE_DALLIAH:
if (uiData == IN_PROGRESS)
{
// Soccothares taunts after Dalliah gets aggro
if (GetData(TYPE_SOCCOTHRATES) != DONE)
StartNextDialogueText(TYPE_DALLIAH);
}
if (uiData == DONE)
{
DoUseDoorOrButton(GO_CORE_SECURITY_FIELD_BETA);
// Soccothares taunts after Dalliah dies
if (GetData(TYPE_SOCCOTHRATES) != DONE)
StartNextDialogueText(TYPE_SOCCOTHRATES);
}
m_auiEncounter[uiType] = uiData;
break;
case TYPE_SOCCOTHRATES:
if (uiData == DONE)
DoUseDoorOrButton(GO_CORE_SECURITY_FIELD_ALPHA);
m_auiEncounter[uiType] = uiData;
break;
case TYPE_HARBINGERSKYRISS:
if (uiData == FAIL)
{
SetData(TYPE_WARDEN_1, NOT_STARTED);
SetData(TYPE_WARDEN_2, NOT_STARTED);
SetData(TYPE_WARDEN_3, NOT_STARTED);
SetData(TYPE_WARDEN_4, NOT_STARTED);
SetData(TYPE_WARDEN_5, NOT_STARTED);
// Reset event in 1 min
if (Creature* pMellichar = GetSingleCreatureFromStorage(NPC_MELLICHAR))
pMellichar->ForcedDespawn();
m_uiResetDelayTimer = 60000;
// Despawn all the summons manually
for (GuidList::const_iterator itr = m_lSkyrissEventMobsGuidList.begin(); itr != m_lSkyrissEventMobsGuidList.end(); ++itr)
{
if (Creature* pTemp = instance->GetCreature(*itr))
pTemp->ForcedDespawn();
}
// Reset these objects, because they doesn't reset automatically
if (GameObject* pGo = GetSingleGameObjectFromStorage(GO_POD_BETA))
pGo->ResetDoorOrButton();
if (GameObject* pGo = GetSingleGameObjectFromStorage(GO_POD_OMEGA))
pGo->ResetDoorOrButton();
if (GameObject* pGo = GetSingleGameObjectFromStorage(GO_SEAL_SPHERE))
pGo->ResetDoorOrButton();
}
if (uiData == IN_PROGRESS)
{
StartNextDialogueText(YELL_MELLICHAR_INTRO1);
DoUseDoorOrButton(GO_SEAL_SPHERE);
}
if (uiData == DONE)
{
if (Creature* pMillhouse = GetSingleCreatureFromStorage(NPC_MILLHOUSE))
DoScriptText(SAY_MILLHOUSE_COMPLETE, pMillhouse);
}
m_auiEncounter[3] = uiData;
break;
case TYPE_WARDEN_1:
if (uiData == IN_PROGRESS)
DoUseDoorOrButton(GO_POD_ALPHA);
if (uiData == DONE)
StartNextDialogueText(YELL_MELLICHAR_RELEASE2);
m_auiEncounter[uiType] = uiData;
break;
case TYPE_WARDEN_2:
if (uiData == IN_PROGRESS)
DoUseDoorOrButton(GO_POD_BETA);
if (uiData == DONE)
StartNextDialogueText(YELL_MELLICHAR_RELEASE3);
m_auiEncounter[uiType] = uiData;
break;
case TYPE_WARDEN_3:
if (uiData == IN_PROGRESS)
DoUseDoorOrButton(GO_POD_DELTA);
if (uiData == DONE)
StartNextDialogueText(YELL_MELLICHAR_RELEASE4);
m_auiEncounter[uiType] = uiData;
break;
case TYPE_WARDEN_4:
if (uiData == IN_PROGRESS)
DoUseDoorOrButton(GO_POD_GAMMA);
if (uiData == DONE)
StartNextDialogueText(YELL_MELLICHAR_RELEASE5);
m_auiEncounter[uiType] = uiData;
break;
case TYPE_WARDEN_5:
if (uiData == IN_PROGRESS)
DoUseDoorOrButton(GO_POD_OMEGA);
m_auiEncounter[uiType] = uiData;
break;
}
if (uiData == DONE)
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1] << " " << m_auiEncounter[2] << " "
<< m_auiEncounter[3] << " " << m_auiEncounter[4];
m_strInstData = saveStream.str();
SaveToDB();
OUT_SAVE_INST_DATA_COMPLETE;
}
}
uint32 instance_arcatraz::GetData(uint32 uiType) const
{
if (uiType < MAX_ENCOUNTER)
return m_auiEncounter[uiType];
return 0;
}
void instance_arcatraz::Load(const char* chrIn)
{
if (!chrIn)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(chrIn);
std::istringstream loadStream(chrIn);
loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3]
>> m_auiEncounter[4];
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
{
if (m_auiEncounter[i] == IN_PROGRESS)
m_auiEncounter[i] = NOT_STARTED;
}
OUT_LOAD_INST_DATA_COMPLETE;
}
void instance_arcatraz::JustDidDialogueStep(int32 iEntry)
{
Creature* pMellichar = GetSingleCreatureFromStorage(NPC_MELLICHAR);
if (!pMellichar)
return;
switch (iEntry)
{
case SPELL_TARGET_ALPHA:
pMellichar->CastSpell(pMellichar, SPELL_TARGET_ALPHA, TRIGGERED_NONE);
if (Creature* pTarget = GetSingleCreatureFromStorage(NPC_PRISON_APHPA_POD))
pMellichar->SetFacingToObject(pTarget);
SetData(TYPE_WARDEN_1, IN_PROGRESS);
break;
case YELL_MELLICHAR_RELEASE1:
pMellichar->SummonCreature(urand(0, 1) ? NPC_BLAZING_TRICKSTER : NPC_PHASE_HUNTER, aSummonPosition[0].m_fX, aSummonPosition[0].m_fY, aSummonPosition[0].m_fZ, aSummonPosition[0].m_fO, TEMPSPAWN_DEAD_DESPAWN, 0);
break;
case YELL_MELLICHAR_RELEASE2:
if (Creature* pTarget = GetSingleCreatureFromStorage(NPC_PRISON_BETA_POD))
pMellichar->SetFacingToObject(pTarget);
break;
case SPELL_TARGET_BETA:
pMellichar->CastSpell(pMellichar, SPELL_TARGET_BETA, TRIGGERED_NONE);
SetData(TYPE_WARDEN_2, IN_PROGRESS);
break;
case TYPE_WARDEN_2:
pMellichar->SummonCreature(NPC_MILLHOUSE, aSummonPosition[1].m_fX, aSummonPosition[1].m_fY, aSummonPosition[1].m_fZ, aSummonPosition[1].m_fO, TEMPSPAWN_DEAD_DESPAWN, 0);
break;
case SPELL_TARGET_DELTA:
pMellichar->CastSpell(pMellichar, SPELL_TARGET_DELTA, TRIGGERED_NONE);
if (Creature* pTarget = GetSingleCreatureFromStorage(NPC_PRISON_DELTA_POD))
pMellichar->SetFacingToObject(pTarget);
SetData(TYPE_WARDEN_3, IN_PROGRESS);
break;
case TYPE_WARDEN_3:
pMellichar->SummonCreature(urand(0, 1) ? NPC_AKKIRIS : NPC_SULFURON, aSummonPosition[2].m_fX, aSummonPosition[2].m_fY, aSummonPosition[2].m_fZ, aSummonPosition[2].m_fO, TEMPSPAWN_DEAD_DESPAWN, 0);
pMellichar->CastSpell(pMellichar, SPELL_TARGET_OMEGA, TRIGGERED_NONE);
if (Creature* pTarget = GetSingleCreatureFromStorage(NPC_PRISON_BOSS_POD))
pMellichar->SetFacingToObject(pTarget);
break;
case YELL_MELLICHAR_RELEASE4:
pMellichar->InterruptNonMeleeSpells(false);
if (Creature* pTarget = GetSingleCreatureFromStorage(NPC_PRISON_GAMMA_POD))
pMellichar->SetFacingToObject(pTarget);
break;
case SPELL_TARGET_GAMMA:
pMellichar->CastSpell(pMellichar, SPELL_TARGET_GAMMA, TRIGGERED_NONE);
if (Creature* pTarget = GetSingleCreatureFromStorage(NPC_PRISON_GAMMA_POD))
pMellichar->SetFacingToObject(pTarget);
SetData(TYPE_WARDEN_4, IN_PROGRESS);
break;
case TYPE_WARDEN_4:
pMellichar->SummonCreature(urand(0, 1) ? NPC_TW_DRAKONAAR : NPC_BL_DRAKONAAR, aSummonPosition[3].m_fX, aSummonPosition[3].m_fY, aSummonPosition[3].m_fZ, aSummonPosition[3].m_fO, TEMPSPAWN_DEAD_DESPAWN, 0);
pMellichar->CastSpell(pMellichar, SPELL_TARGET_OMEGA, TRIGGERED_NONE);
if (Creature* pTarget = GetSingleCreatureFromStorage(NPC_PRISON_BOSS_POD))
pMellichar->SetFacingToObject(pTarget);
break;
case YELL_MELLICHAR_RELEASE5:
pMellichar->InterruptNonMeleeSpells(false);
SetData(TYPE_WARDEN_5, IN_PROGRESS);
break;
case TYPE_WARDEN_5:
if (Creature* pSkyriss = pMellichar->SummonCreature(NPC_SKYRISS, aSummonPosition[4].m_fX, aSummonPosition[4].m_fY, aSummonPosition[4].m_fZ, aSummonPosition[4].m_fO, TEMPSPAWN_DEAD_DESPAWN, 0))
pSkyriss->CastSpell(pSkyriss, SPELL_SIMPLE_TELEPORT, TRIGGERED_NONE);
break;
case YELL_MELLICAR_WELCOME:
if (Creature* pSkyriss = GetSingleCreatureFromStorage(NPC_SKYRISS))
pSkyriss->CastSpell(pSkyriss, SPELL_MIND_REND, TRIGGERED_NONE);
break;
case SAY_SKYRISS_AGGRO:
// Kill Mellichar and start combat
if (Creature* pSkyriss = GetSingleCreatureFromStorage(NPC_SKYRISS))
{
pSkyriss->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_NPC);
pMellichar->DealDamage(pMellichar, pMellichar->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
}
DoUseDoorOrButton(GO_SEAL_SPHERE);
break;
}
}
void instance_arcatraz::OnCreatureDeath(Creature* pCreature)
{
if (pCreature->GetEntry() == NPC_ARCATRAZ_WARDEN || pCreature->GetEntry() == NPC_ARCATRAZ_DEFENDER)
{
++m_uiKilledWardens;
// Stop the intro spawns when the wardens are killed
if (m_uiKilledWardens == MAX_WARDENS)
{
SetData(TYPE_ENTRANCE, DONE);
m_uiEntranceEventTimer = 0;
}
}
}
void instance_arcatraz::Update(uint32 uiDiff)
{
DialogueUpdate(uiDiff);
if (m_uiResetDelayTimer)
{
if (m_uiResetDelayTimer <= uiDiff)
{
if (Creature* pMellichar = GetSingleCreatureFromStorage(NPC_MELLICHAR))
pMellichar->Respawn();
m_uiResetDelayTimer = 0;
}
else
m_uiResetDelayTimer -= uiDiff;
}
if (m_uiEntranceEventTimer)
{
if (m_uiEntranceEventTimer <= uiDiff)
{
Player* pPlayer = GetPlayerInMap();
if (!pPlayer)
return;
uint32 uiEntry = urand(0, 10) ? NPC_PROTEAN_HORROR : NPC_PROTEAN_NIGHTMARE;
// Summon and move the intro creatures into combat positions
if (Creature* pTemp = pPlayer->SummonCreature(uiEntry, aEntranceSpawnLoc[0], aEntranceSpawnLoc[1], aEntranceSpawnLoc[2], aEntranceSpawnLoc[3], TEMPSPAWN_TIMED_OOC_OR_DEAD_DESPAWN, 30000))
{
pTemp->SetWalk(false);
pTemp->GetMotionMaster()->MovePoint(0, aEntranceMoveLoc[0], aEntranceMoveLoc[1], aEntranceMoveLoc[2]);
}
m_uiEntranceEventTimer = urand(0, 10) ? urand(2000, 3500) : urand(5000, 7000);
}
else
m_uiEntranceEventTimer -= uiDiff;
}
}
InstanceData* GetInstanceData_instance_arcatraz(Map* pMap)
{
return new instance_arcatraz(pMap);
}
void AddSC_instance_arcatraz()
{
Script* pNewScript;
pNewScript = new Script;
pNewScript->Name = "instance_arcatraz";
pNewScript->GetInstanceData = &GetInstanceData_instance_arcatraz;
pNewScript->RegisterSelf();
}
| 411 | 0.980422 | 1 | 0.980422 | game-dev | MEDIA | 0.981754 | game-dev | 0.993465 | 1 | 0.993465 |
magefree/mage | 1,720 | Mage.Sets/src/mage/cards/s/SenselessRage.java |
package mage.cards.s;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.AttachEffect;
import mage.abilities.effects.common.continuous.BoostEnchantedEffect;
import mage.abilities.keyword.EnchantAbility;
import mage.abilities.keyword.MadnessAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Duration;
import mage.constants.Outcome;
import mage.constants.Zone;
import mage.target.TargetPermanent;
import mage.target.common.TargetCreaturePermanent;
/**
*
* @author LevelX2
*/
public final class SenselessRage extends CardImpl {
public SenselessRage(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{1}{R}");
this.subtype.add(SubType.AURA);
// Enchant creature
TargetPermanent auraTarget = new TargetCreaturePermanent();
this.getSpellAbility().addTarget(auraTarget);
this.getSpellAbility().addEffect(new AttachEffect(Outcome.BoostCreature));
Ability ability = new EnchantAbility(auraTarget);
this.addAbility(ability);
// Enchanted creature gets +2/+2.
this.addAbility(new SimpleStaticAbility(new BoostEnchantedEffect(2, 2, Duration.WhileOnBattlefield)));
// Madness {1}{R}
this.addAbility(new MadnessAbility(new ManaCostsImpl<>("{1}{R}")));
}
private SenselessRage(final SenselessRage card) {
super(card);
}
@Override
public SenselessRage copy() {
return new SenselessRage(this);
}
}
| 411 | 0.942697 | 1 | 0.942697 | game-dev | MEDIA | 0.979934 | game-dev | 0.955233 | 1 | 0.955233 |
mattgodbolt/xania | 3,663 | src/test/CommandSetTest.cpp | #include "CommandSet.hpp"
#include <catch2/catch_test_macros.hpp>
#include <sstream>
#include <string_view>
namespace {
template <typename T>
std::string enumerate_str(const CommandSet<T> &cs, int min_level, int max_level) {
std::ostringstream result;
cs.enumerate(cs.level_restrict(min_level, max_level, [&result](const std::string &name, const T value, int level) {
result << name << "=" << value << "@" << level << " ";
}));
return result.str();
}
} // namespace
TEST_CASE("CommandSet tests") {
SECTION("empty") {
CommandSet<int> cs;
CHECK(!cs.get("nothing", 1).has_value());
CHECK(enumerate_str(cs, 0, 100).empty());
}
SECTION("level limits") {
CommandSet<std::string> cs;
cs.add("kick", "foot", 0);
cs.add("punch", "fist", 5);
cs.add("disembowel", "spade", 4);
cs.add("smit", "spell it out", 92);
cs.add("smite", "godlike power", 92);
cs.add("smitten", "*blush*", 1);
SECTION("low level enumerate") {
CHECK(enumerate_str(cs, 0, 5) == "disembowel=spade@4 kick=foot@0 punch=fist@5 smitten=*blush*@1 ");
}
SECTION("mid level enumerate") { CHECK(enumerate_str(cs, 3, 5) == "disembowel=spade@4 punch=fist@5 "); }
SECTION("high level enumerate") {
CHECK(enumerate_str(cs, 5, 100) == "punch=fist@5 smit=spell it out@92 smite=godlike power@92 ");
}
SECTION("all level enumerate") {
CHECK(enumerate_str(cs, 0, 100)
== "disembowel=spade@4 kick=foot@0 punch=fist@5 smit=spell it out@92 smite=godlike power@92 "
"smitten=*blush*@1 ");
}
CHECK(cs.get("kick", 0).value() == "foot");
CHECK(!cs.get("punch", 4).has_value());
CHECK(cs.get("punch", 5).value() == "fist");
CHECK(cs.get("smit", 80).value() == "*blush*");
CHECK(cs.get("smit", 92).value() == "spell it out");
CHECK(cs.get("smite", 92).value() == "godlike power");
CHECK(!cs.get("smite", 91).has_value());
}
SECTION("case insensitive") {
CommandSet<std::string> cs;
cs.add("SHOUT", "RARARAAAA", 0);
cs.add("whisper", "pssst", 0);
cs.add("Talk", "Blah blah.", 0);
CHECK(cs.get("SHOUT", 0) == "RARARAAAA");
CHECK(cs.get("shout", 0) == "RARARAAAA");
CHECK(cs.get("sHoUT", 0) == "RARARAAAA");
CHECK(cs.get("whisper", 0) == "pssst");
CHECK(cs.get("WHISPER", 0) == "pssst");
CHECK(cs.get("talk", 0) == "Blah blah.");
CHECK(cs.get("tALK", 0) == "Blah blah.");
CHECK(cs.get("TA", 0) == "Blah blah.");
SECTION("insensitive enum") {
CHECK(enumerate_str(cs, 0, 100) == "shout=RARARAAAA@0 talk=Blah blah.@0 whisper=pssst@0 ");
}
}
SECTION("notes") {
CommandSet<std::string> cs;
cs.add("send", "post", 0);
cs.add("show", "demonstrate", 0);
cs.add("subject", "citizen", 0);
CHECK(cs.get("se", 0) == "post");
CHECK(cs.get("sh", 0) == "demonstrate");
CHECK(cs.get("su", 0) == "citizen");
CHECK(cs.get("s", 0) == "post");
}
// If several commands match the requested prefix, it's vital that the first one added
// is the one we pick. If we just pick the first alphabetically, we end up with weird
// annoying bugs, like "l" matching first "list", whereas everyone expects "look".
SECTION("look first") {
CommandSet<std::string> cs;
cs.add("look", "with your eyes", 0);
cs.add("list", "with a notepad", 0);
CHECK(cs.get("l", 0) == "with your eyes");
}
}
| 411 | 0.85499 | 1 | 0.85499 | game-dev | MEDIA | 0.553669 | game-dev | 0.798194 | 1 | 0.798194 |
martinakaduc/MM241-Assignment | 3,765 | student_submissions/s2311015_2311464_2311616_2112278_2313327/src/genetic.py | # GeneticPolicy implementation
import random
import numpy as np
from policy import Policy
class GeneticPolicy(Policy):
def __init__(self, population_size=100, generations=8, mutation_rate=0.01):
self.population_size = population_size
self.generations = generations
self.mutation_rate = mutation_rate
def get_action(self, observation, info):
population = [self.random_action(observation) for _ in range(self.population_size)]
for _ in range(self.generations):
fitness_scores = [self.evaluate_fitness(action, observation, info) for action in population]
selected = self.select_population(population, fitness_scores)
offspring = self.crossover(selected)
population = self.mutate(offspring)
best_action = population[np.argmax(fitness_scores)]
return best_action
def random_action(self, observation):
available_products = [product for product in observation['products'] if product['quantity'] > 0]
selected_product = random.choice(available_products)
size = selected_product['size']
pos_x, pos_y = None, None
while True:
stock_idx = random.randint(0, len(observation['stocks']) - 1)
stock = observation['stocks'][stock_idx]
stock_w, stock_h = self._get_stock_size_(stock)
if (stock_w < size[0]) or (stock_h < size[1]):
continue
for i in range(stock_w - size[0] + 1):
for j in range(stock_h - size[1] + 1):
if self._can_place_(stock, (i, j), size):
pos_x, pos_y = i, j
break
if pos_x is not None and pos_y is not None:
break
if pos_x is not None and pos_y is not None:
break
return {'stock_idx': stock_idx, 'size': size, 'position': (pos_x, pos_y)}
def evaluate_fitness(self, action, observation, info):
stock = observation["stocks"][action["stock_idx"]]
prod_size = action["size"]
pos_x, pos_y = action["position"]
stock_w, stock_h = self._get_stock_size_(stock)
target_x, target_y = stock_w // 2, stock_h // 2
distance_to_target = ((pos_x - target_x) ** 2 + (pos_y - target_y) ** 2) ** 0.5
space_utilization = (prod_size[0] * prod_size[1]) / (stock_w * stock_h)
used_area = np.sum(stock >= 0)
prod_area = prod_size[0] * prod_size[1]
fitness_score = space_utilization * 100 + distance_to_target + used_area ** 1.5 + prod_area ** 2
if not self._can_place_(stock, (pos_x, pos_y), prod_size):
fitness_score -= 1000
return fitness_score
def select_population(self, population, fitness_scores):
sorted_population = [action for _, action in sorted(zip(fitness_scores, population), key=lambda x: x[0], reverse=True)]
return sorted_population[:len(sorted_population)//2]
def crossover(self, selected):
offspring = []
while len(offspring) < self.population_size:
parent1, parent2 = random.sample(selected, 2)
child = {
'stock_idx': parent1['stock_idx'],
'size': parent2['size'],
'position': parent1['position']
}
offspring.append(child)
return offspring
def mutate(self, offspring):
for action in offspring:
if random.random() < self.mutation_rate:
size = list(action['size'])
size[0] += random.randint(-1, 1)
size[1] += random.randint(-1, 1)
action['size'] = tuple(size[::-1])
return offspring | 411 | 0.827613 | 1 | 0.827613 | game-dev | MEDIA | 0.681696 | game-dev,ml-ai | 0.782155 | 1 | 0.782155 |
mattgodbolt/xania | 1,561 | src/BodySize.cpp | /*************************************************************************/
/* Xania (M)ulti(U)ser(D)ungeon server source code */
/* (C) 2021 Xania Development Team */
/* See merc.h and README for original copyrights */
/*************************************************************************/
#include "BodySize.hpp"
#include "string_utils.hpp"
#include <magic_enum/magic_enum.hpp>
namespace BodySizes {
std::optional<BodySize> try_lookup(std::string_view name) {
for (const auto &enum_name : magic_enum::enum_names<BodySize>()) {
// This doesn't use enum_cast() here as we want a case insensitive prefix match.
if (matches_start(name, enum_name)) {
if (const auto val = magic_enum::enum_cast<BodySize>(enum_name)) {
return val;
}
}
}
// Unlike enums such as ObjectType, BodySize lookups never needed to support
// number->size so it gives up here.
return std::nullopt;
}
sh_int size_diff(const BodySize size_a, const BodySize size_b) {
return magic_enum::enum_integer<BodySize>(size_a) - magic_enum::enum_integer<BodySize>(size_b);
}
sh_int get_mob_str_bonus(const BodySize body_size) {
return magic_enum::enum_integer<BodySize>(body_size) - magic_enum::enum_integer<BodySize>(BodySize::Medium);
}
sh_int get_mob_con_bonus(const BodySize body_size) {
return (magic_enum::enum_integer<BodySize>(body_size) - magic_enum::enum_integer<BodySize>(BodySize::Medium)) / 2;
}
}
| 411 | 0.87893 | 1 | 0.87893 | game-dev | MEDIA | 0.229101 | game-dev | 0.813624 | 1 | 0.813624 |
JiepengTan/LockstepEngine_ARPGDemo | 4,121 | Unity/Assets/Scripts/Util/Event/EventHelper.cs | #define DEBUG_EVENT_TRIGGER
#if UNITY_EDITOR || DEBUG_EVENT_TRIGGER
#define _DEBUG_EVENT_TRIGGER
#endif
using System.Collections.Generic;
namespace Lockstep {
public delegate void GlobalEventHandler(object param);
public delegate void NetMsgHandler(object param);
public partial class EventHelper {
private static Dictionary<int, List<GlobalEventHandler>> allListeners =
new Dictionary<int, List<GlobalEventHandler>>();
private static Queue<MsgInfo> allPendingMsgs = new Queue<MsgInfo>();
private static Queue<ListenerInfo> allPendingListeners = new Queue<ListenerInfo>();
private static Queue<EEvent> allNeedRemoveTypes = new Queue<EEvent>();
private static bool IsTriggingEvent;
public static void RemoveAllListener(EEvent type){
if (IsTriggingEvent) {
allNeedRemoveTypes.Enqueue(type);
return;
}
allListeners.Remove((int) type);
}
public static void AddListener(EEvent type, GlobalEventHandler listener){
if (IsTriggingEvent) {
allPendingListeners.Enqueue(new ListenerInfo(true, type, listener));
return;
}
var itype = (int) type;
if (allListeners.TryGetValue(itype, out var tmplst)) {
tmplst.Add(listener);
}
else {
var lst = new List<GlobalEventHandler>();
lst.Add(listener);
allListeners.Add(itype, lst);
}
}
public static void RemoveListener(EEvent type, GlobalEventHandler listener){
if (IsTriggingEvent) {
allPendingListeners.Enqueue(new ListenerInfo(false, type, listener));
return;
}
var itype = (int) type;
if (allListeners.TryGetValue(itype, out var tmplst)) {
if (tmplst.Remove(listener)) {
if (tmplst.Count == 0) {
allListeners.Remove(itype);
}
return;
}
}
//Debug.LogError("Try remove a not exist listner " + type);
}
public static void Trigger(EEvent type, object param = null){
if (IsTriggingEvent) {
allPendingMsgs.Enqueue(new MsgInfo(type, param));
return;
}
var itype = (int) type;
if (allListeners.TryGetValue(itype, out var tmplst)) {
IsTriggingEvent = true;
foreach (var listener in tmplst.ToArray()) { //TODO 替换成其他更好的方式 避免gc
listener?.Invoke(param);
}
}
IsTriggingEvent = false;
while (allPendingListeners.Count > 0) {
var msgInfo = allPendingListeners.Dequeue();
if (msgInfo.isRegister) {
AddListener(msgInfo.type, msgInfo.param);
}
else {
RemoveListener(msgInfo.type, msgInfo.param);
}
}
while (allNeedRemoveTypes.Count > 0) {
var rmType = allNeedRemoveTypes.Dequeue();
RemoveAllListener(rmType);
}
while (allPendingMsgs.Count > 0) {
var msgInfo = allPendingMsgs.Dequeue();
Trigger(msgInfo.type, msgInfo.param);
}
}
public struct MsgInfo {
public EEvent type;
public object param;
public MsgInfo(EEvent type, object param){
this.type = type;
this.param = param;
}
}
public struct ListenerInfo {
public bool isRegister;
public EEvent type;
public GlobalEventHandler param;
public ListenerInfo(bool isRegister, EEvent type, GlobalEventHandler param){
this.isRegister = isRegister;
this.type = type;
this.param = param;
}
}
}
} | 411 | 0.918424 | 1 | 0.918424 | game-dev | MEDIA | 0.274854 | game-dev | 0.966754 | 1 | 0.966754 |
shawwn/noh | 5,380 | src/sav_shared/i_buildingmine.cpp | // (C)2007 S2 Games
// i_buildingmine.cpp
//
//=============================================================================
//=============================================================================
// Headers
//=============================================================================
#include "game_shared_common.h"
#include "i_buildingmine.h"
#include "c_teaminfo.h"
#include "c_entityclientinfo.h"
#include "../k2/c_sceneentity.h"
#include "../k2/c_scenemanager.h"
//=============================================================================
/*====================
IBuildingMine::HarvestGold
====================*/
uint IBuildingMine::HarvestGold()
{
IPropEntity *pProp(Game.GetPropEntity(m_uiFoundation));
if (pProp == NULL)
return 0;
IPropFoundation *pMine(pProp->GetAsFoundation());
if (pMine == NULL)
return 0;
float fInitialGoldPercent(pMine->GetRemainingGoldPercent());
uint uiGoldHarvested(pMine->HarvestGold());
if (fInitialGoldPercent >= 0.15f && pMine->GetRemainingGoldPercent() < 0.15f)
{
ivector vClients(Game.GetTeam(GetTeam())->GetClientList());
CBufferFixed<6> buffer;
buffer << GAME_CMD_GOLD_MINE_LOW << GetIndex();
for (ivector_cit it(vClients.begin()); it != vClients.end(); ++it)
Game.SendGameData(*it, buffer, true);
}
if (fInitialGoldPercent > 0.0f && pMine->GetRemainingGoldPercent() <= 0.0f)
{
ivector vClients(Game.GetTeam(GetTeam())->GetClientList());
CBufferFixed<6> buffer;
buffer << GAME_CMD_GOLD_MINE_DEPLETED << GetIndex();
StartAnimation(_T("idle_empty"), 0);
for (ivector_cit it(vClients.begin()); it != vClients.end(); ++it)
Game.SendGameData(*it, buffer, true);
}
return uiGoldHarvested;
}
/*====================
IBuildingMine::GetIncomeAmount
====================*/
uint IBuildingMine::GetIncomeAmount() const
{
IPropEntity *pProp(Game.GetPropEntity(m_uiFoundation));
if (pProp == NULL)
return 0;
IPropFoundation *pMine(pProp->GetAsFoundation());
if (pMine == NULL)
return 0;
return MIN(pMine->GetRemainingGold(), pMine->GetHarvestRate());
}
/*====================
IBuildingMine::GetIncomeAmount
====================*/
void IBuildingMine::Kill(IVisualEntity *pAttacker, ushort unKillingObjectID)
{
CEntityTeamInfo *pTeam(Game.GetTeam(GetTeam()));
if (pTeam != NULL)
{
IPropEntity *pProp(Game.GetPropEntity(m_uiFoundation));
if (pProp != NULL)
{
IPropFoundation *pMine(pProp->GetAsFoundation());
if (pMine != NULL)
pTeam->GiveGold(pMine->RaidGold());
}
}
IBuildingEntity::Kill(pAttacker, unKillingObjectID);
}
/*====================
IBuildingMine::AddToScene
====================*/
bool IBuildingMine::AddToScene(const CVec4f &v4Color, int iFlags)
{
if (m_hModel == INVALID_INDEX)
return false;
CEntityClientInfo *pLocalClient(Game.GetClientInfo(Game.GetLocalClientNum()));
if (GetStatus() == ENTITY_STATUS_PREVIEW &&
pLocalClient != NULL &&
pLocalClient->GetTeam() != GetTeam())
return false;
CVec4f v4TintedColor(v4Color);
if (Game.IsCommander() && GetStatus() != ENTITY_STATUS_PREVIEW)
{
if (!(m_bSighted || m_bPrevSighted))
return false;
if (!m_bSighted)
{
//v4TintedColor[R] *= 0.333f;
//v4TintedColor[G] *= 0.333f;
//v4TintedColor[B] *= 0.333f;
}
}
if (m_v3AxisAngles != m_v3Angles)
{
m_aAxis.Set(m_v3Angles);
m_v3AxisAngles = m_v3Angles;
}
static CSceneEntity sceneEntity;
sceneEntity.Clear();
sceneEntity.scale = GetScale() * GetScale2();
sceneEntity.SetPosition(m_v3Position);
sceneEntity.axis = m_aAxis;
sceneEntity.objtype = OBJTYPE_MODEL;
sceneEntity.hModel = m_hModel;
sceneEntity.skeleton = m_pSkeleton;
sceneEntity.color = v4TintedColor;
sceneEntity.flags = iFlags | SCENEOBJ_SOLID_COLOR | SCENEOBJ_USE_AXIS;
bool bEmpty(false);
IPropEntity *pProp(Game.GetPropEntity(m_uiFoundation));
if (pProp != NULL)
{
IPropFoundation *pMine(pProp->GetAsFoundation());
if (pMine != NULL)
{
if (pMine->GetRemainingGold() == 0)
bEmpty = true;
}
}
if (bEmpty)
{
if (Game.LooksLikeEnemy(m_uiIndex))
sceneEntity.hSkin = g_ResourceManager.GetSkin(GetModelHandle(), _T("red_empty"));
else
sceneEntity.hSkin = g_ResourceManager.GetSkin(GetModelHandle(), _T("empty"));
}
else
{
if (Game.LooksLikeEnemy(m_uiIndex))
sceneEntity.hSkin = g_ResourceManager.GetSkin(GetModelHandle(), _T("red"));
}
if (m_uiClientRenderFlags & ECRF_SNAPSELECTED)
sceneEntity.color *= m_v4SelectColor;
if (m_uiClientRenderFlags & ECRF_HALFTRANSPARENT)
sceneEntity.color[A] *= 0.5f;
SSceneEntityEntry &cEntry(SceneManager.AddEntity(sceneEntity));
if (!cEntry.bCull || !cEntry.bCullShadow)
{
if (GetStatus() != ENTITY_STATUS_PREVIEW)
AddSelectionRingToScene();
UpdateSkeleton(true);
}
else
{
UpdateSkeleton(false);
}
return true;
}
| 411 | 0.956094 | 1 | 0.956094 | game-dev | MEDIA | 0.880536 | game-dev | 0.994341 | 1 | 0.994341 |
magefree/mage | 2,032 | Mage.Sets/src/mage/cards/n/NathOfTheGiltLeaf.java | package mage.cards.n;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.triggers.BeginningOfUpkeepTriggeredAbility;
import mage.abilities.common.DiscardsACardOpponentTriggeredAbility;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.effects.common.discard.DiscardTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.SuperType;
import mage.game.permanent.token.ElfWarriorToken;
import mage.target.common.TargetOpponent;
import java.util.UUID;
/**
* @author jeffwadsworth
*/
public final class NathOfTheGiltLeaf extends CardImpl {
public NathOfTheGiltLeaf(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{B}{G}");
this.supertype.add(SuperType.LEGENDARY);
this.subtype.add(SubType.ELF);
this.subtype.add(SubType.WARRIOR);
this.power = new MageInt(4);
this.toughness = new MageInt(4);
// At the beginning of your upkeep, you may have target opponent discard a card at random.
Effect effect = new DiscardTargetEffect(1, true);
effect.setText("you may have target opponent discard a card at random");
Ability ability = new BeginningOfUpkeepTriggeredAbility(effect, true);
ability.addTarget(new TargetOpponent());
this.addAbility(ability);
// Whenever an opponent discards a card, you may create a 1/1 green Elf Warrior creature token.
Effect effect2 = new CreateTokenEffect(new ElfWarriorToken());
effect2.setText("you may create a 1/1 green Elf Warrior creature token");
this.addAbility(new DiscardsACardOpponentTriggeredAbility(effect2, true));
}
private NathOfTheGiltLeaf(final NathOfTheGiltLeaf card) {
super(card);
}
@Override
public NathOfTheGiltLeaf copy() {
return new NathOfTheGiltLeaf(this);
}
}
| 411 | 0.890065 | 1 | 0.890065 | game-dev | MEDIA | 0.957028 | game-dev | 0.996413 | 1 | 0.996413 |
danielah05/UndertaleDecomp | 1,646 | objects/obj_pofftrigger/Step_0.gml | if (t == 2)
{
obj_dogpoff.image_speed = 0.25
t = 3
}
if (t == 6)
{
global.battlegroup = BattleGroup.GreaterDog
FL_AreaKillsPointer = KillsPointer_Invalid
global.mercy = 1
instance_create(0, 0, obj_battler)
t = 10
}
if (global.plot == 60 && t == 10)
{
obj_mainchara.y = 140
global.interact = 1
global.plot = 61
if (FL_GreaterDogStatus == DogStatus.Killed)
{
global.mercy = 0
global.interact = 0
global.plot = 65
global.currentsong = caster_load("music/snowy.ogg")
caster_loop(global.currentsong, 1, 0.95)
// Daniela: fix music not being pitched down in Genocide
if (!global.decomp_vars.VanillaMode && murder == 1)
caster_set_pitch(global.currentsong, 0.4);
t = 9999
with (obj_dogpoff)
instance_destroy()
instance_destroy()
return;
}
alarm[4] = 30
if (FL_GreaterDogStatus == DogStatus.Spared || FL_GreaterDogStatus == DogStatus.SparedWithStick)
t = 20
if (FL_GreaterDogStatus == DogStatus.Ignored)
t = 26
}
if (t == 20 || t == 26)
global.interact = 1
if (t == 21)
{
obj_dogpoff.image_index = 0
obj_dogpoff.sprite_index = spr_doglick
obj_dogpoff.image_speed = 0.25
t = 22
}
if (t == 23 && obj_dogpoff.sprite_index == spr_dogbuttwalk)
{
obj_dogpoff.hspeed = 2
obj_dogpoff.image_speed = 0.25
alarm[4] = 50
t = 24
}
if (t == 25)
{
global.mercy = 0
global.currentsong = caster_load("music/snowy.ogg")
caster_loop(global.currentsong, 1, 0.95)
global.interact = 0
global.plot = 65
instance_destroy()
}
if (t == 27)
{
obj_dogpoff.image_index = 0
obj_dogpoff.sprite_index = spr_dogboredwalk
obj_dogpoff.hspeed = 2
obj_dogpoff.image_speed = 0.5
alarm[4] = 50
t = 28
}
if (t == 29)
t = 25
| 411 | 0.841381 | 1 | 0.841381 | game-dev | MEDIA | 0.268363 | game-dev | 0.691577 | 1 | 0.691577 |
SteamRE/Steam4NET | 1,644 | Steam4NET/Autogen/ISteamRemoteStorage003.cs | // This file is automatically generated.
using System;
using System.Text;
using System.Runtime.InteropServices;
using Steam4NET.Attributes;
namespace Steam4NET
{
[InterfaceVersion("STEAMREMOTESTORAGE_INTERFACE_VERSION003")]
public interface ISteamRemoteStorage003
{
[VTableSlot(0)]
bool FileWrite(string pchFile, Byte[] pvData, Int32 cubData);
[VTableSlot(1)]
Int32 FileRead(string pchFile, Byte[] pvData, Int32 cubDataToRead);
[VTableSlot(2)]
bool FileForget(string pchFile);
[VTableSlot(3)]
bool FileDelete(string pchFile);
[VTableSlot(4)]
UInt64 FileShare(string pchFile);
[VTableSlot(5)]
bool FileExists(string pchFile);
[VTableSlot(6)]
bool FilePersisted(string pchFile);
[VTableSlot(7)]
Int32 GetFileSize(string pchFile);
[VTableSlot(8)]
Int64 GetFileTimestamp(string pchFile);
[VTableSlot(9)]
Int32 GetFileCount();
[VTableSlot(10)]
string GetFileNameAndSize(Int32 iFile, ref Int32 pnFileSizeInBytes);
[VTableSlot(11)]
bool GetQuota(ref Int32 pnTotalBytes, ref Int32 puAvailableBytes);
[VTableSlot(12)]
bool IsCloudEnabledForAccount();
[VTableSlot(13)]
bool IsCloudEnabledThisApp();
[VTableSlot(14)]
bool SetCloudEnabledThisApp(bool bEnable);
[VTableSlot(15)]
UInt64 UGCDownload(UInt64 hContent);
[VTableSlot(16)]
bool GetUGCDetails(UInt64 hContent, ref UInt32 pnAppID, StringBuilder ppchName, ref Int32 pnFileSizeInBytes, ref CSteamID pSteamIDOwner);
[VTableSlot(17)]
Int32 UGCRead(UInt64 hContent, Byte[] pvData, Int32 cubDataToRead);
[VTableSlot(18)]
Int32 GetCachedUGCCount();
[VTableSlot(19)]
UInt64 GetCachedUGCHandle(Int32 iCachedContent);
};
}
| 411 | 0.935828 | 1 | 0.935828 | game-dev | MEDIA | 0.313041 | game-dev | 0.693866 | 1 | 0.693866 |
TASEmulators/BizHawk | 1,214 | src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper164.cs | using BizHawk.Common;
namespace BizHawk.Emulation.Cores.Nintendo.NES
{
internal sealed class Mapper164 : NesBoardBase
{
// http://wiki.nesdev.com/w/index.php/INES_Mapper_164
private int _prgHigh;
private int _prgLow;
private int prg_bank_mask_32k;
public override bool Configure(EDetectionOrigin origin)
{
switch (Cart.BoardType)
{
case "MAPPER164":
break;
default:
return false;
}
_prgLow = 0xFF;
prg_bank_mask_32k = Cart.PrgSize / 32 - 1;
SetMirrorType(Cart.PadH, Cart.PadV);
return true;
}
public override void WriteExp(int addr, byte value)
{
addr = (addr + 0x4000) & 0x7300;
switch (addr)
{
case 0x5000:
_prgLow = value;
break;
case 0x5100:
_prgHigh = value;
break;
}
}
public override byte ReadPrg(int addr)
{
int bank = (_prgHigh << 4) | (_prgLow & 0xF);
bank &= prg_bank_mask_32k;
return Rom[(bank * 0x8000) + (addr & 0x7FFF)];
}
public override void SyncState(Serializer ser)
{
base.SyncState(ser);
ser.Sync("prgHigh", ref _prgHigh);
ser.Sync("prgLow", ref _prgLow);
}
public override void NesSoftReset()
{
_prgHigh = 0xFF;
base.NesSoftReset();
}
}
}
| 411 | 0.885519 | 1 | 0.885519 | game-dev | MEDIA | 0.309001 | game-dev | 0.798416 | 1 | 0.798416 |
LeoMinecraftModding/eternal-starlight | 1,788 | common/src/main/java/cn/leolezury/eternalstarlight/common/util/ESBlockUtil.java | package cn.leolezury.eternalstarlight.common.util;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.AABB;
import java.util.ArrayList;
import java.util.List;
public class ESBlockUtil {
public static boolean isEntityInBlock(Entity entity, Block block) {
AABB box = entity.getBoundingBox();
BlockPos fromPos = BlockPos.containing(box.minX + 1.0E-7, box.minY + 1.0E-7, box.minZ + 1.0E-7);
BlockPos toPos = BlockPos.containing(box.maxX - 1.0E-7, box.maxY - 1.0E-7, box.maxZ - 1.0E-7);
BlockPos.MutableBlockPos mutableBlockPos = new BlockPos.MutableBlockPos();
for (int i = fromPos.getX(); i <= toPos.getX(); ++i) {
for (int j = fromPos.getY(); j <= toPos.getY(); ++j) {
for (int k = fromPos.getZ(); k <= toPos.getZ(); ++k) {
mutableBlockPos.set(i, j, k);
BlockState blockState = entity.level().getBlockState(mutableBlockPos);
if (blockState.is(block)) {
return true;
}
}
}
}
return false;
}
public static List<BlockPos> getBlocksInBoundingBox(AABB box) {
List<BlockPos> posList = new ArrayList<>();
BlockPos fromPos = BlockPos.containing(box.minX + 1.0E-7, box.minY + 1.0E-7, box.minZ + 1.0E-7);
BlockPos toPos = BlockPos.containing(box.maxX - 1.0E-7, box.maxY - 1.0E-7, box.maxZ - 1.0E-7);
BlockPos.MutableBlockPos mutableBlockPos = new BlockPos.MutableBlockPos();
for (int i = fromPos.getX(); i <= toPos.getX(); ++i) {
for (int j = fromPos.getY(); j <= toPos.getY(); ++j) {
for (int k = fromPos.getZ(); k <= toPos.getZ(); ++k) {
mutableBlockPos.set(i, j, k);
posList.add(mutableBlockPos.immutable());
}
}
}
return posList;
}
}
| 411 | 0.857662 | 1 | 0.857662 | game-dev | MEDIA | 0.951701 | game-dev | 0.912007 | 1 | 0.912007 |
Tuinity/Moonrise | 1,866 | src/main/java/ca/spottedleaf/moonrise/mixin/blockstate_propertyaccess/PropertyMixin.java | package ca.spottedleaf.moonrise.mixin.blockstate_propertyaccess;
import ca.spottedleaf.moonrise.patches.blockstate_propertyaccess.PropertyAccess;
import net.minecraft.world.level.block.state.properties.Property;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.concurrent.atomic.AtomicInteger;
@Mixin(Property.class)
abstract class PropertyMixin<T extends Comparable<T>> implements PropertyAccess<T> {
@Unique
private static final AtomicInteger ID_GENERATOR = new AtomicInteger();
@Unique
private int id;
@Unique
private T[] byId;
@Override
public final int moonrise$getId() {
return this.id;
}
@Override
public final T moonrise$getById(final int id) {
final T[] byId = this.byId;
return id < 0 || id >= byId.length ? null : this.byId[id];
}
@Override
public final void moonrise$setById(final T[] byId) {
if (this.byId != null) {
throw new IllegalStateException();
}
this.byId = byId;
}
@Override
public abstract int moonrise$getIdFor(final T value);
/**
* @reason Hook into constructor to init fields
* @author Spottedleaf
*/
@Inject(
method = "<init>",
at = @At(
value = "RETURN"
)
)
private void initId(final CallbackInfo ci) {
this.id = ID_GENERATOR.getAndIncrement();
}
/**
* @reason Properties are identity comparable
* @author Spottedleaf
*/
@Overwrite
@Override
public boolean equals(final Object obj) {
return this == obj;
}
}
| 411 | 0.883808 | 1 | 0.883808 | game-dev | MEDIA | 0.831879 | game-dev | 0.917569 | 1 | 0.917569 |
ProjectIgnis/CardScripts | 1,491 | official/c41230939.lua | --サイバー・ダーク・ホーン
--Cyberdark Horn
local s,id=GetID()
function s.initial_effect(c)
--equip
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(Cyberdark.EquipTarget(s.eqfilter,true,true))
e1:SetOperation(Cyberdark.EquipOperation(s.eqfilter,s.equipop,true))
c:RegisterEffect(e1)
aux.AddEREquipLimit(c,nil,s.eqval,s.equipop,e1)
--pierce
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_PIERCE)
c:RegisterEffect(e2)
end
function s.eqfilter(c)
return c:IsLevelBelow(3) and c:IsRace(RACE_DRAGON)
end
function s.eqval(ec,c,tp)
return ec:IsControler(tp) and ec:IsLevelBelow(3) and ec:IsRace(RACE_DRAGON)
end
function s.equipop(c,e,tp,tc)
local atk=tc:GetTextAttack()
if atk<0 then atk=0 end
if not c:EquipByEffectAndLimitRegister(e,tp,tc) then return end
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetProperty(EFFECT_FLAG_OWNER_RELATE+EFFECT_FLAG_IGNORE_IMMUNE)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetReset(RESET_EVENT|RESETS_STANDARD)
e2:SetValue(atk)
tc:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_EQUIP)
e3:SetCode(EFFECT_DESTROY_SUBSTITUTE)
e3:SetReset(RESET_EVENT|RESETS_STANDARD)
e3:SetValue(s.repval)
tc:RegisterEffect(e3)
end
function s.repval(e,re,r,rp)
return (r&REASON_BATTLE)~=0
end | 411 | 0.923417 | 1 | 0.923417 | game-dev | MEDIA | 0.987996 | game-dev | 0.875712 | 1 | 0.875712 |
openc2e/openc2e | 38,094 | externals/imgui/backends/imgui_impl_sdl3.cpp | // dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*)
// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
// (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**)
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// [X] Platform: IME support.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2024-10-24: Emscripten: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f on Emscripten.
// 2024-09-03: Update for SDL3 api changes: SDL_GetGamepads() memory ownership revert. (#7918, #7898, #7807)
// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
// - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
// - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
// 2024-08-19: Storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*.
// 2024-08-19: ImGui_ImplSDL3_ProcessEvent() now ignores events intended for other SDL windows. (#7853)
// 2024-07-22: Update for SDL3 api changes: SDL_GetGamepads() memory ownership change. (#7807)
// 2024-07-18: Update for SDL3 api changes: SDL_GetClipboardText() memory ownership change. (#7801)
// 2024-07-15: Update for SDL3 api changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794)
// 2024-07-02: Update for SDL3 api changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762).
// 2024-07-01: Update for SDL3 api changes: SDL_SetTextInputRect() changed to SDL_SetTextInputArea().
// 2024-06-26: Update for SDL3 api changes: SDL_StartTextInput()/SDL_StopTextInput()/SDL_SetTextInputRect() functions signatures.
// 2024-06-24: Update for SDL3 api changes: SDL_EVENT_KEY_DOWN/SDL_EVENT_KEY_UP contents.
// 2024-06-03; Update for SDL3 api changes: SDL_SYSTEM_CURSOR_ renames.
// 2024-05-15: Update for SDL3 api changes: SDLK_ renames.
// 2024-04-15: Inputs: Re-enable calling SDL_StartTextInput()/SDL_StopTextInput() as SDL3 no longer enables it by default and should play nicer with IME.
// 2024-02-13: Inputs: Fixed gamepad support. Handle gamepad disconnection. Added ImGui_ImplSDL3_SetGamepadMode().
// 2023-11-13: Updated for recent SDL3 API changes.
// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys.
// 2023-05-04: Fixed build on Emscripten/iOS/Android. (#6391)
// 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306)
// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702)
// 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644)
// 2023-02-07: Forked "imgui_impl_sdl2" into "imgui_impl_sdl3". Removed version checks for old feature. Refer to imgui_impl_sdl2.cpp for older changelog.
#include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_sdl3.h"
// Clang warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#endif
// SDL
#include <SDL3/SDL.h>
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#endif
#if !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__)
#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1
#else
#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0
#endif
// FIXME-LEGACY: remove when SDL 3.1.3 preview is released.
#ifndef SDLK_APOSTROPHE
#define SDLK_APOSTROPHE SDLK_QUOTE
#endif
#ifndef SDLK_GRAVE
#define SDLK_GRAVE SDLK_BACKQUOTE
#endif
// SDL Data
struct ImGui_ImplSDL3_Data
{
SDL_Window* Window;
SDL_WindowID WindowID;
SDL_Renderer* Renderer;
Uint64 Time;
char* ClipboardTextData;
// IME handling
SDL_Window* ImeWindow;
// Mouse handling
Uint32 MouseWindowID;
int MouseButtonsDown;
SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT];
SDL_Cursor* MouseLastCursor;
int MousePendingLeaveFrame;
bool MouseCanUseGlobalState;
// Gamepad handling
ImVector<SDL_Gamepad*> Gamepads;
ImGui_ImplSDL3_GamepadMode GamepadMode;
bool WantUpdateGamepadsList;
ImGui_ImplSDL3_Data() { memset((void*)this, 0, sizeof(*this)); }
};
// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
// FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
static ImGui_ImplSDL3_Data* ImGui_ImplSDL3_GetBackendData()
{
return ImGui::GetCurrentContext() ? (ImGui_ImplSDL3_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
}
// Functions
static const char* ImGui_ImplSDL3_GetClipboardText(ImGuiContext*)
{
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
if (bd->ClipboardTextData)
SDL_free(bd->ClipboardTextData);
const char* sdl_clipboard_text = SDL_GetClipboardText();
bd->ClipboardTextData = sdl_clipboard_text ? SDL_strdup(sdl_clipboard_text) : nullptr;
return bd->ClipboardTextData;
}
static void ImGui_ImplSDL3_SetClipboardText(ImGuiContext*, const char* text)
{
SDL_SetClipboardText(text);
}
static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
{
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
SDL_WindowID window_id = (SDL_WindowID)(intptr_t)viewport->PlatformHandle;
SDL_Window* window = SDL_GetWindowFromID(window_id);
if ((data->WantVisible == false || bd->ImeWindow != window) && bd->ImeWindow != nullptr)
{
SDL_StopTextInput(bd->ImeWindow);
bd->ImeWindow = nullptr;
}
if (data->WantVisible)
{
SDL_Rect r;
r.x = (int)data->InputPos.x;
r.y = (int)data->InputPos.y;
r.w = 1;
r.h = (int)data->InputLineHeight;
SDL_SetTextInputArea(window, &r, 0);
SDL_StartTextInput(window);
bd->ImeWindow = window;
}
}
// Not static to allow third-party code to use that if they want to (but undocumented)
ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode);
ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode)
{
// Keypad doesn't have individual key values in SDL3
switch (scancode)
{
case SDL_SCANCODE_KP_0: return ImGuiKey_Keypad0;
case SDL_SCANCODE_KP_1: return ImGuiKey_Keypad1;
case SDL_SCANCODE_KP_2: return ImGuiKey_Keypad2;
case SDL_SCANCODE_KP_3: return ImGuiKey_Keypad3;
case SDL_SCANCODE_KP_4: return ImGuiKey_Keypad4;
case SDL_SCANCODE_KP_5: return ImGuiKey_Keypad5;
case SDL_SCANCODE_KP_6: return ImGuiKey_Keypad6;
case SDL_SCANCODE_KP_7: return ImGuiKey_Keypad7;
case SDL_SCANCODE_KP_8: return ImGuiKey_Keypad8;
case SDL_SCANCODE_KP_9: return ImGuiKey_Keypad9;
case SDL_SCANCODE_KP_PERIOD: return ImGuiKey_KeypadDecimal;
case SDL_SCANCODE_KP_DIVIDE: return ImGuiKey_KeypadDivide;
case SDL_SCANCODE_KP_MULTIPLY: return ImGuiKey_KeypadMultiply;
case SDL_SCANCODE_KP_MINUS: return ImGuiKey_KeypadSubtract;
case SDL_SCANCODE_KP_PLUS: return ImGuiKey_KeypadAdd;
case SDL_SCANCODE_KP_ENTER: return ImGuiKey_KeypadEnter;
case SDL_SCANCODE_KP_EQUALS: return ImGuiKey_KeypadEqual;
default: break;
}
switch (keycode)
{
case SDLK_TAB: return ImGuiKey_Tab;
case SDLK_LEFT: return ImGuiKey_LeftArrow;
case SDLK_RIGHT: return ImGuiKey_RightArrow;
case SDLK_UP: return ImGuiKey_UpArrow;
case SDLK_DOWN: return ImGuiKey_DownArrow;
case SDLK_PAGEUP: return ImGuiKey_PageUp;
case SDLK_PAGEDOWN: return ImGuiKey_PageDown;
case SDLK_HOME: return ImGuiKey_Home;
case SDLK_END: return ImGuiKey_End;
case SDLK_INSERT: return ImGuiKey_Insert;
case SDLK_DELETE: return ImGuiKey_Delete;
case SDLK_BACKSPACE: return ImGuiKey_Backspace;
case SDLK_SPACE: return ImGuiKey_Space;
case SDLK_RETURN: return ImGuiKey_Enter;
case SDLK_ESCAPE: return ImGuiKey_Escape;
case SDLK_APOSTROPHE: return ImGuiKey_Apostrophe;
case SDLK_COMMA: return ImGuiKey_Comma;
case SDLK_MINUS: return ImGuiKey_Minus;
case SDLK_PERIOD: return ImGuiKey_Period;
case SDLK_SLASH: return ImGuiKey_Slash;
case SDLK_SEMICOLON: return ImGuiKey_Semicolon;
case SDLK_EQUALS: return ImGuiKey_Equal;
case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket;
case SDLK_BACKSLASH: return ImGuiKey_Backslash;
case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket;
case SDLK_GRAVE: return ImGuiKey_GraveAccent;
case SDLK_CAPSLOCK: return ImGuiKey_CapsLock;
case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock;
case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock;
case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen;
case SDLK_PAUSE: return ImGuiKey_Pause;
case SDLK_LCTRL: return ImGuiKey_LeftCtrl;
case SDLK_LSHIFT: return ImGuiKey_LeftShift;
case SDLK_LALT: return ImGuiKey_LeftAlt;
case SDLK_LGUI: return ImGuiKey_LeftSuper;
case SDLK_RCTRL: return ImGuiKey_RightCtrl;
case SDLK_RSHIFT: return ImGuiKey_RightShift;
case SDLK_RALT: return ImGuiKey_RightAlt;
case SDLK_RGUI: return ImGuiKey_RightSuper;
case SDLK_APPLICATION: return ImGuiKey_Menu;
case SDLK_0: return ImGuiKey_0;
case SDLK_1: return ImGuiKey_1;
case SDLK_2: return ImGuiKey_2;
case SDLK_3: return ImGuiKey_3;
case SDLK_4: return ImGuiKey_4;
case SDLK_5: return ImGuiKey_5;
case SDLK_6: return ImGuiKey_6;
case SDLK_7: return ImGuiKey_7;
case SDLK_8: return ImGuiKey_8;
case SDLK_9: return ImGuiKey_9;
case SDLK_A: return ImGuiKey_A;
case SDLK_B: return ImGuiKey_B;
case SDLK_C: return ImGuiKey_C;
case SDLK_D: return ImGuiKey_D;
case SDLK_E: return ImGuiKey_E;
case SDLK_F: return ImGuiKey_F;
case SDLK_G: return ImGuiKey_G;
case SDLK_H: return ImGuiKey_H;
case SDLK_I: return ImGuiKey_I;
case SDLK_J: return ImGuiKey_J;
case SDLK_K: return ImGuiKey_K;
case SDLK_L: return ImGuiKey_L;
case SDLK_M: return ImGuiKey_M;
case SDLK_N: return ImGuiKey_N;
case SDLK_O: return ImGuiKey_O;
case SDLK_P: return ImGuiKey_P;
case SDLK_Q: return ImGuiKey_Q;
case SDLK_R: return ImGuiKey_R;
case SDLK_S: return ImGuiKey_S;
case SDLK_T: return ImGuiKey_T;
case SDLK_U: return ImGuiKey_U;
case SDLK_V: return ImGuiKey_V;
case SDLK_W: return ImGuiKey_W;
case SDLK_X: return ImGuiKey_X;
case SDLK_Y: return ImGuiKey_Y;
case SDLK_Z: return ImGuiKey_Z;
case SDLK_F1: return ImGuiKey_F1;
case SDLK_F2: return ImGuiKey_F2;
case SDLK_F3: return ImGuiKey_F3;
case SDLK_F4: return ImGuiKey_F4;
case SDLK_F5: return ImGuiKey_F5;
case SDLK_F6: return ImGuiKey_F6;
case SDLK_F7: return ImGuiKey_F7;
case SDLK_F8: return ImGuiKey_F8;
case SDLK_F9: return ImGuiKey_F9;
case SDLK_F10: return ImGuiKey_F10;
case SDLK_F11: return ImGuiKey_F11;
case SDLK_F12: return ImGuiKey_F12;
case SDLK_F13: return ImGuiKey_F13;
case SDLK_F14: return ImGuiKey_F14;
case SDLK_F15: return ImGuiKey_F15;
case SDLK_F16: return ImGuiKey_F16;
case SDLK_F17: return ImGuiKey_F17;
case SDLK_F18: return ImGuiKey_F18;
case SDLK_F19: return ImGuiKey_F19;
case SDLK_F20: return ImGuiKey_F20;
case SDLK_F21: return ImGuiKey_F21;
case SDLK_F22: return ImGuiKey_F22;
case SDLK_F23: return ImGuiKey_F23;
case SDLK_F24: return ImGuiKey_F24;
case SDLK_AC_BACK: return ImGuiKey_AppBack;
case SDLK_AC_FORWARD: return ImGuiKey_AppForward;
default: break;
}
return ImGuiKey_None;
}
static void ImGui_ImplSDL3_UpdateKeyModifiers(SDL_Keymod sdl_key_mods)
{
ImGuiIO& io = ImGui::GetIO();
io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & SDL_KMOD_CTRL) != 0);
io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & SDL_KMOD_SHIFT) != 0);
io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & SDL_KMOD_ALT) != 0);
io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & SDL_KMOD_GUI) != 0);
}
static ImGuiViewport* ImGui_ImplSDL3_GetViewportForWindowID(SDL_WindowID window_id)
{
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : nullptr;
}
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.
bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
{
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?");
ImGuiIO& io = ImGui::GetIO();
switch (event->type)
{
case SDL_EVENT_MOUSE_MOTION:
{
if (ImGui_ImplSDL3_GetViewportForWindowID(event->motion.windowID) == nullptr)
return false;
ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);
io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);
return true;
}
case SDL_EVENT_MOUSE_WHEEL:
{
if (ImGui_ImplSDL3_GetViewportForWindowID(event->wheel.windowID) == nullptr)
return false;
//IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);
float wheel_x = -event->wheel.x;
float wheel_y = event->wheel.y;
io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
io.AddMouseWheelEvent(wheel_x, wheel_y);
return true;
}
case SDL_EVENT_MOUSE_BUTTON_DOWN:
case SDL_EVENT_MOUSE_BUTTON_UP:
{
if (ImGui_ImplSDL3_GetViewportForWindowID(event->button.windowID) == nullptr)
return false;
int mouse_button = -1;
if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }
if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }
if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; }
if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; }
if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; }
if (mouse_button == -1)
break;
io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
io.AddMouseButtonEvent(mouse_button, (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN));
bd->MouseButtonsDown = (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button));
return true;
}
case SDL_EVENT_TEXT_INPUT:
{
if (ImGui_ImplSDL3_GetViewportForWindowID(event->text.windowID) == nullptr)
return false;
io.AddInputCharactersUTF8(event->text.text);
return true;
}
case SDL_EVENT_KEY_DOWN:
case SDL_EVENT_KEY_UP:
{
if (ImGui_ImplSDL3_GetViewportForWindowID(event->key.windowID) == nullptr)
return false;
ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.mod);
//IMGUI_DEBUG_LOG("SDL_EVENT_KEY_%s : key=%d ('%s'), scancode=%d ('%s'), mod=%X\n",
// (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP ", event->key.key, SDL_GetKeyName(event->key.key), event->key.scancode, SDL_GetScancodeName(event->key.scancode), event->key.mod);
ImGuiKey key = ImGui_ImplSDL3_KeyEventToImGuiKey(event->key.key, event->key.scancode);
io.AddKeyEvent(key, (event->type == SDL_EVENT_KEY_DOWN));
io.SetKeyEventNativeData(key, event->key.key, event->key.scancode, event->key.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.
return true;
}
case SDL_EVENT_WINDOW_MOUSE_ENTER:
{
if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr)
return false;
bd->MouseWindowID = event->window.windowID;
bd->MousePendingLeaveFrame = 0;
return true;
}
// - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,
// causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why
// we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details.
// FIXME: Unconfirmed whether this is still needed with SDL3.
case SDL_EVENT_WINDOW_MOUSE_LEAVE:
{
if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr)
return false;
bd->MousePendingLeaveFrame = ImGui::GetFrameCount() + 1;
return true;
}
case SDL_EVENT_WINDOW_FOCUS_GAINED:
case SDL_EVENT_WINDOW_FOCUS_LOST:
{
if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr)
return false;
io.AddFocusEvent(event->type == SDL_EVENT_WINDOW_FOCUS_GAINED);
return true;
}
case SDL_EVENT_GAMEPAD_ADDED:
case SDL_EVENT_GAMEPAD_REMOVED:
{
bd->WantUpdateGamepadsList = true;
return true;
}
}
return false;
}
static void ImGui_ImplSDL3_SetupPlatformHandles(ImGuiViewport* viewport, SDL_Window* window)
{
viewport->PlatformHandle = (void*)(intptr_t)SDL_GetWindowID(window);
viewport->PlatformHandleRaw = nullptr;
#if defined(_WIN32) && !defined(__WINRT__)
viewport->PlatformHandleRaw = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr);
#elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA)
viewport->PlatformHandleRaw = SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, nullptr);
#endif
}
static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context)
{
ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
IM_UNUSED(sdl_gl_context); // Unused in this branch
// Check and store if we are on a SDL backend that supports global mouse position
// ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list)
bool mouse_can_use_global_state = false;
#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
const char* sdl_backend = SDL_GetCurrentVideoDriver();
const char* global_mouse_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" };
for (int n = 0; n < IM_ARRAYSIZE(global_mouse_whitelist); n++)
if (strncmp(sdl_backend, global_mouse_whitelist[n], strlen(global_mouse_whitelist[n])) == 0)
mouse_can_use_global_state = true;
#endif
// Setup backend capabilities flags
ImGui_ImplSDL3_Data* bd = IM_NEW(ImGui_ImplSDL3_Data)();
io.BackendPlatformUserData = (void*)bd;
io.BackendPlatformName = "imgui_impl_sdl3";
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
bd->Window = window;
bd->WindowID = SDL_GetWindowID(window);
bd->Renderer = renderer;
bd->MouseCanUseGlobalState = mouse_can_use_global_state;
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText;
platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL3_GetClipboardText;
platform_io.Platform_SetImeDataFn = ImGui_ImplSDL3_PlatformSetImeData;
// Gamepad handling
bd->GamepadMode = ImGui_ImplSDL3_GamepadMode_AutoFirst;
bd->WantUpdateGamepadsList = true;
// Load mouse cursors
bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT);
bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_TEXT);
bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_MOVE);
bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NS_RESIZE);
bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_EW_RESIZE);
bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NESW_RESIZE);
bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NWSE_RESIZE);
bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_POINTER);
bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NOT_ALLOWED);
// Set platform dependent data in viewport
// Our mouse update function expect PlatformHandle to be filled for the main viewport
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
ImGui_ImplSDL3_SetupPlatformHandles(main_viewport, window);
// From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event.
// Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered.
// (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application.
// It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click:
// you can ignore SDL_EVENT_MOUSE_BUTTON_DOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED)
#ifdef SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
#endif
// From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710)
#ifdef SDL_HINT_MOUSE_AUTO_CAPTURE
SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0");
#endif
return true;
}
bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context)
{
IM_UNUSED(sdl_gl_context); // Viewport branch will need this.
return ImGui_ImplSDL3_Init(window, nullptr, sdl_gl_context);
}
bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window)
{
return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
}
bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window)
{
#if !defined(_WIN32)
IM_ASSERT(0 && "Unsupported");
#endif
return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
}
bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window)
{
return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
}
bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer)
{
return ImGui_ImplSDL3_Init(window, renderer, nullptr);
}
bool ImGui_ImplSDL3_InitForSDLGPU(SDL_Window* window)
{
return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
}
bool ImGui_ImplSDL3_InitForOther(SDL_Window* window)
{
return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
}
static void ImGui_ImplSDL3_CloseGamepads();
void ImGui_ImplSDL3_Shutdown()
{
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
ImGuiIO& io = ImGui::GetIO();
if (bd->ClipboardTextData)
SDL_free(bd->ClipboardTextData);
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
SDL_DestroyCursor(bd->MouseCursors[cursor_n]);
ImGui_ImplSDL3_CloseGamepads();
io.BackendPlatformName = nullptr;
io.BackendPlatformUserData = nullptr;
io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad);
IM_DELETE(bd);
}
static void ImGui_ImplSDL3_UpdateMouseData()
{
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
ImGuiIO& io = ImGui::GetIO();
// We forward mouse input when hovered or captured (via SDL_EVENT_MOUSE_MOTION) or when focused (below)
#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
// SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside
SDL_CaptureMouse(bd->MouseButtonsDown != 0);
SDL_Window* focused_window = SDL_GetKeyboardFocus();
const bool is_app_focused = (bd->Window == focused_window);
#else
SDL_Window* focused_window = bd->Window;
const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only
#endif
if (is_app_focused)
{
// (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user)
if (io.WantSetMousePos)
SDL_WarpMouseInWindow(bd->Window, io.MousePos.x, io.MousePos.y);
// (Optional) Fallback to provide mouse position when focused (SDL_EVENT_MOUSE_MOTION already provides this when hovered or captured)
if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0)
{
// Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
float mouse_x_global, mouse_y_global;
int window_x, window_y;
SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global);
SDL_GetWindowPosition(focused_window, &window_x, &window_y);
io.AddMousePosEvent(mouse_x_global - window_x, mouse_y_global - window_y);
}
}
}
static void ImGui_ImplSDL3_UpdateMouseCursor()
{
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
return;
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
{
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
SDL_HideCursor();
}
else
{
// Show OS mouse cursor
SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow];
if (bd->MouseLastCursor != expected_cursor)
{
SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113)
bd->MouseLastCursor = expected_cursor;
}
SDL_ShowCursor();
}
}
static void ImGui_ImplSDL3_CloseGamepads()
{
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
if (bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual)
for (SDL_Gamepad* gamepad : bd->Gamepads)
SDL_CloseGamepad(gamepad);
bd->Gamepads.resize(0);
}
void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array, int manual_gamepads_count)
{
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
ImGui_ImplSDL3_CloseGamepads();
if (mode == ImGui_ImplSDL3_GamepadMode_Manual)
{
IM_ASSERT(manual_gamepads_array != nullptr && manual_gamepads_count > 0);
for (int n = 0; n < manual_gamepads_count; n++)
bd->Gamepads.push_back(manual_gamepads_array[n]);
}
else
{
IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0);
bd->WantUpdateGamepadsList = true;
}
bd->GamepadMode = mode;
}
static void ImGui_ImplSDL3_UpdateGamepadButton(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadButton button_no)
{
bool merged_value = false;
for (SDL_Gamepad* gamepad : bd->Gamepads)
merged_value |= SDL_GetGamepadButton(gamepad, button_no) != 0;
io.AddKeyEvent(key, merged_value);
}
static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
static void ImGui_ImplSDL3_UpdateGamepadAnalog(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadAxis axis_no, float v0, float v1)
{
float merged_value = 0.0f;
for (SDL_Gamepad* gamepad : bd->Gamepads)
{
float vn = Saturate((float)(SDL_GetGamepadAxis(gamepad, axis_no) - v0) / (float)(v1 - v0));
if (merged_value < vn)
merged_value = vn;
}
io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value);
}
static void ImGui_ImplSDL3_UpdateGamepads()
{
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
// Update list of gamepads to use
if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual)
{
ImGui_ImplSDL3_CloseGamepads();
int sdl_gamepads_count = 0;
SDL_JoystickID* sdl_gamepads = SDL_GetGamepads(&sdl_gamepads_count);
for (int n = 0; n < sdl_gamepads_count; n++)
if (SDL_Gamepad* gamepad = SDL_OpenGamepad(sdl_gamepads[n]))
{
bd->Gamepads.push_back(gamepad);
if (bd->GamepadMode == ImGui_ImplSDL3_GamepadMode_AutoFirst)
break;
}
bd->WantUpdateGamepadsList = false;
SDL_free(sdl_gamepads);
}
// FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
return;
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
if (bd->Gamepads.Size == 0)
return;
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
// Update gamepad inputs
const int thumb_dead_zone = 8000; // SDL_gamepad.h suggests using this value.
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_GAMEPAD_BUTTON_START);
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_GAMEPAD_BUTTON_BACK);
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_GAMEPAD_BUTTON_WEST); // Xbox X, PS Square
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_GAMEPAD_BUTTON_EAST); // Xbox B, PS Circle
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_GAMEPAD_BUTTON_NORTH); // Xbox Y, PS Triangle
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_GAMEPAD_BUTTON_SOUTH); // Xbox A, PS Cross
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_GAMEPAD_BUTTON_DPAD_LEFT);
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_GAMEPAD_BUTTON_DPAD_RIGHT);
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_GAMEPAD_BUTTON_DPAD_UP);
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_GAMEPAD_BUTTON_DPAD_DOWN);
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER);
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER);
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, 0.0f, 32767);
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, 0.0f, 32767);
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_GAMEPAD_BUTTON_LEFT_STICK);
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_GAMEPAD_BUTTON_RIGHT_STICK);
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_GAMEPAD_AXIS_LEFTX, -thumb_dead_zone, -32768);
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_GAMEPAD_AXIS_LEFTX, +thumb_dead_zone, +32767);
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_GAMEPAD_AXIS_LEFTY, -thumb_dead_zone, -32768);
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_GAMEPAD_AXIS_LEFTY, +thumb_dead_zone, +32767);
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_GAMEPAD_AXIS_RIGHTX, -thumb_dead_zone, -32768);
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_GAMEPAD_AXIS_RIGHTX, +thumb_dead_zone, +32767);
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_GAMEPAD_AXIS_RIGHTY, -thumb_dead_zone, -32768);
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_GAMEPAD_AXIS_RIGHTY, +thumb_dead_zone, +32767);
}
void ImGui_ImplSDL3_NewFrame()
{
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?");
ImGuiIO& io = ImGui::GetIO();
// Setup display size (every frame to accommodate for window resizing)
int w, h;
int display_w, display_h;
SDL_GetWindowSize(bd->Window, &w, &h);
if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_MINIMIZED)
w = h = 0;
SDL_GetWindowSizeInPixels(bd->Window, &display_w, &display_h);
io.DisplaySize = ImVec2((float)w, (float)h);
if (w > 0 && h > 0)
io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h);
// Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution)
// (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644)
static Uint64 frequency = SDL_GetPerformanceFrequency();
Uint64 current_time = SDL_GetPerformanceCounter();
if (current_time <= bd->Time)
current_time = bd->Time + 1;
io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f);
bd->Time = current_time;
if (bd->MousePendingLeaveFrame && bd->MousePendingLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0)
{
bd->MouseWindowID = 0;
bd->MousePendingLeaveFrame = 0;
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
}
ImGui_ImplSDL3_UpdateMouseData();
ImGui_ImplSDL3_UpdateMouseCursor();
// Update game controllers (if enabled and available)
ImGui_ImplSDL3_UpdateGamepads();
}
//-----------------------------------------------------------------------------
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#endif // #ifndef IMGUI_DISABLE
| 411 | 0.935737 | 1 | 0.935737 | game-dev | MEDIA | 0.742916 | game-dev | 0.873389 | 1 | 0.873389 |
ResoniteModdingGroup/MonkeyLoader.GamePacks.Resonite | 4,463 | MonkeyLoader.Resonite.Unity/UnityLoadProgressIndicator.cs | using HarmonyLib;
using MonkeyLoader.Unity;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UnityEngine.SceneManagement;
namespace MonkeyLoader.Resonite
{
/// <summary>
/// Contains methods to update Resonite's Unity loading progress indicator with custom phases.
/// </summary>
[HarmonyPatch(typeof(EngineLoadProgress))]
[HarmonyPatchCategory(nameof(UnityLoadProgressIndicator))]
internal sealed class UnityLoadProgressIndicator : UnityMonkey<UnityLoadProgressIndicator>, ILoadProgressIndicator
{
private static EngineLoadProgress? _loadProgress;
private static string? _phase;
/// <inheritdoc/>
[MemberNotNullWhen(true, nameof(_loadProgress),
nameof(FixedPhaseIndex), nameof(TotalFixedPhaseCount))]
public bool Available
{
get
{
if (_loadProgress == null)
{
// Clear reference to UnityObject when it compares as null
_loadProgress = null;
return false;
}
#pragma warning disable CS8775 // Member must have a non-null value when exiting in some condition.
return true;
#pragma warning restore CS8775 // Member must have a non-null value when exiting in some condition.
}
}
/// <inheritdoc/>
public int? FixedPhaseIndex => _loadProgress?.FixedPhaseIndex;
/// <inheritdoc/>
public int? TotalFixedPhaseCount => _loadProgress?.TotalFixedPhaseCount;
/// <summary>
/// Increments the <see cref="EngineLoadProgress.TotalFixedPhaseCount"/> by <paramref name="count"/> to make space for additional phases,
/// if the progress indicator is <see cref="Available">available</see>.
/// </summary>
/// <remarks>
/// Should be used as early as possible, to make sure the progress bar doesn't go backwards.
/// </remarks>
/// <returns><c>true</c> if the count was incremented successfully, otherwise <c>false</c>.</returns>
public bool AddFixedPhases(int count)
{
if (!Available)
return false;
_loadProgress.TotalFixedPhaseCount += count;
Logger.Trace(() => $"Incremented EngineLoadProgress.TotalFixedPhaseCount by {count}.");
return true;
}
/// <summary>
/// Sets the subphase, if the progress indicator is <see cref="Available">available</see>.
/// </summary>
/// <param name="subphase">The name of the subphase.</param>
/// <returns><c>true</c> if the subphase was changed successfully, otherwise <c>false</c>.</returns>
public bool SetSubphase(string? subphase)
{
if (!Available)
return false;
_loadProgress.SetSubphase(subphase);
return true;
}
/// <inheritdoc/>
protected override bool OnFirstSceneReady(Scene scene)
{
if (!LoadingConfig.Instance.HijackLoadProgressIndicator)
return true;
_loadProgress = scene.GetRootGameObjects()
.Select(g => g.GetComponentInChildren<EngineLoadProgress>())
.FirstOrDefault(elp => elp != null);
Logger.Info(() => $"Hooked EngineLoadProgress indicator: {Available}");
if (Available)
LoadProgressReporter.LoadProgressIndicator = this;
return base.OnFirstSceneReady(scene);
}
/// <inheritdoc/>
public bool SetFixedPhase(string? phase)
{
if (!Available)
return false;
_loadProgress.SetFixedPhase(phase);
return true;
}
[HarmonyPostfix]
[HarmonyPatch(nameof(EngineLoadProgress.SetFixedPhase))]
private static void SetFixedPhasedPostfix(EngineLoadProgress __instance, string phase)
{
_phase = phase;
__instance._showSubphase = phase;
}
[HarmonyPostfix]
[HarmonyPatch(nameof(EngineLoadProgress.SetSubphase))]
private static void SetSubphasePostfix(EngineLoadProgress __instance, string subphase)
=> __instance._showSubphase = subphase is null ? _phase : $"{_phase} {subphase}";
}
} | 411 | 0.74599 | 1 | 0.74599 | game-dev | MEDIA | 0.260952 | game-dev | 0.765659 | 1 | 0.765659 |
EasyRPG/Player | 1,756 | src/screen.cpp | /*
* This file is part of EasyRPG Player.
*
* EasyRPG Player 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.
*
* EasyRPG Player 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
*/
// Headers
#include <string>
#include "bitmap.h"
#include "color.h"
#include "game_screen.h"
#include "main_data.h"
#include "screen.h"
#include "drawable_mgr.h"
Screen::Screen() : Drawable(Priority_Screen)
{
DrawableMgr::Register(this);
}
void Screen::Draw(Bitmap& dst) {
auto flash_color = Main_Data::game_screen->GetFlashColor();
if (flash_color.alpha > 0) {
if (!flash) {
flash = Bitmap::Create(dst.GetWidth(), dst.GetHeight(), flash_color);
} else {
flash->Fill(flash_color);
}
dst.Blit(0, 0, *flash, flash->GetRect(), 255);
}
if (viewport != Rect()) {
// Clear all parts of the screen that are out-of-bounds
Rect dst_rect = dst.GetRect();
int dx = viewport.x - dst_rect.x;
int dy = viewport.y - dst_rect.y;
if (dx > 0) {
// Left and Right
dst.ClearRect({0, 0, dx, dst.GetHeight()});
dst.ClearRect({dst.GetWidth() - dx, 0, dx, dst.GetHeight()});
}
if (dy > 0) {
// Top and Bottom
dst.ClearRect({0, 0, dst.GetWidth(), dy});
dst.ClearRect({0, dst.GetHeight() - dy, dst.GetWidth(), dy});
}
}
}
| 411 | 0.607896 | 1 | 0.607896 | game-dev | MEDIA | 0.548626 | game-dev,graphics-rendering | 0.863297 | 1 | 0.863297 |
ProjectIgnis/CardScripts | 1,845 | rush/c160019058.lua | --時の機械-タイム・マシーン
--Time Machine (Rush)
--Scripted by YoshiDuels
local s,id=GetID()
function s.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
local tc=eg:GetFirst()
if chk==0 then return Duel.GetLocationCount(tc:GetPreviousControler(),LOCATION_MZONE)>0 and #eg==1
and tc:IsLocation(LOCATION_GRAVE) and tc:IsReason(REASON_BATTLE)
and tc:IsCanBeSpecialSummoned(e,0,tp,false,false,tc:GetPreviousPosition(),tc:GetPreviousControler()) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,eg,1,0,0)
end
function s.maxfilter(c,tc)
return c:WasMaximumModeSide() and c:HasFlagEffect(FLAG_MAXIMUM_SIDE_RELATION+tc:GetCardID())
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
--0x2: second main monster zone/left main monster zone in Rush
--0x4: middle main monster zone
--0x8: fourth main monster zone/right main monster zone in Rush
local tc=eg:GetFirst()
if tc:WasMaximumMode() then
Duel.SpecialSummon(tc,0,tp,tc:GetPreviousControler(),false,false,tc:GetPreviousPosition(),0x4)
tc:RegisterFlagEffect(FLAG_MAXIMUM_CENTER,RESET_EVENT|RESETS_STANDARD&~RESET_TOFIELD,0,1)
local maxg=Duel.GetMatchingGroup(s.maxfilter,tc:GetPreviousControler(),LOCATION_GRAVE,0,nil,tc)
for maxc in maxg:Iter() do
local zone=0x8
if maxc.MaximumSide=="Left" then zone=0x2 end
maxc:RegisterFlagEffect(FLAG_MAXIMUM_SIDE,RESET_EVENT|RESETS_STANDARD&~RESET_TOFIELD,0,1)
Duel.MoveToField(maxc,tc:GetPreviousControler(),tc:GetPreviousControler(),LOCATION_MZONE,POS_FACEUP_ATTACK,true,zone)
end
else
Duel.SpecialSummon(tc,0,tp,tc:GetPreviousControler(),false,false,tc:GetPreviousPosition())
end
end | 411 | 0.984776 | 1 | 0.984776 | game-dev | MEDIA | 0.99413 | game-dev | 0.937058 | 1 | 0.937058 |
SlimeKnights/TinkersConstruct | 5,662 | src/main/java/slimeknights/tconstruct/tools/modifiers/traits/harvest/MomentumModifier.java | package slimeknights.tconstruct.tools.modifiers.traits.harvest;
import net.minecraft.core.Direction;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.AbstractArrow;
import net.minecraft.world.entity.projectile.Projectile;
import net.minecraft.world.item.TooltipFlag;
import net.minecraftforge.event.entity.player.PlayerEvent.BreakSpeed;
import slimeknights.mantle.client.TooltipKey;
import slimeknights.tconstruct.TConstruct;
import slimeknights.tconstruct.common.TinkerEffect;
import slimeknights.tconstruct.library.modifiers.Modifier;
import slimeknights.tconstruct.library.modifiers.ModifierEntry;
import slimeknights.tconstruct.library.modifiers.ModifierHooks;
import slimeknights.tconstruct.library.modifiers.hook.build.ConditionalStatModifierHook;
import slimeknights.tconstruct.library.modifiers.hook.display.TooltipModifierHook;
import slimeknights.tconstruct.library.modifiers.hook.mining.BlockBreakModifierHook;
import slimeknights.tconstruct.library.modifiers.hook.mining.BreakSpeedContext;
import slimeknights.tconstruct.library.modifiers.hook.mining.BreakSpeedModifierHook;
import slimeknights.tconstruct.library.modifiers.hook.ranged.ProjectileLaunchModifierHook;
import slimeknights.tconstruct.library.module.ModuleHookMap.Builder;
import slimeknights.tconstruct.library.tools.context.ToolHarvestContext;
import slimeknights.tconstruct.library.tools.nbt.IToolStackView;
import slimeknights.tconstruct.library.tools.nbt.ModDataNBT;
import slimeknights.tconstruct.library.tools.stat.FloatToolStat;
import slimeknights.tconstruct.library.tools.stat.ToolStats;
import slimeknights.tconstruct.tools.TinkerModifiers;
import slimeknights.tconstruct.tools.stats.ToolType;
import javax.annotation.Nullable;
import java.util.List;
public class MomentumModifier extends Modifier implements ProjectileLaunchModifierHook, ConditionalStatModifierHook, BlockBreakModifierHook, BreakSpeedModifierHook, TooltipModifierHook {
private static final Component SPEED = TConstruct.makeTranslation("modifier", "momentum.speed");
@Override
protected void registerHooks(Builder hookBuilder) {
hookBuilder.addHook(this, ModifierHooks.CONDITIONAL_STAT, ModifierHooks.PROJECTILE_LAUNCH, ModifierHooks.BLOCK_BREAK, ModifierHooks.BREAK_SPEED, ModifierHooks.TOOLTIP);
}
@Override
public int getPriority() {
// run this last as we boost original speed, adds to existing boosts
return 75;
}
/** Gets the bonus for the modifier */
private static float getBonus(LivingEntity living, ToolType type, ModifierEntry modifier) {
return modifier.getEffectiveLevel() * (TinkerEffect.getLevel(living, TinkerModifiers.momentumEffect.get(type)));
}
/** Applies the effect to the target */
private static void applyEffect(LivingEntity living, ToolType type, int duration, int maxLevel) {
TinkerEffect effect = TinkerModifiers.momentumEffect.get(type);
effect.apply(living, duration, Math.min(maxLevel, TinkerEffect.getAmplifier(living, effect) + 1), true);
}
@Override
public void onBreakSpeed(IToolStackView tool, ModifierEntry modifier, BreakSpeed event, Direction sideHit, boolean isEffective, float miningSpeedModifier) {
if (isEffective) {
// 25% boost per level at max
event.setNewSpeed(event.getNewSpeed() * (1 + getBonus(event.getEntity(), ToolType.HARVEST, modifier) / 128f));
}
}
@Override
public float modifyBreakSpeed(IToolStackView tool, ModifierEntry modifier, BreakSpeedContext context, float speed) {
if (context.isEffective()) {
// 25% boost per level at max
speed *= 1 + getBonus(context.player(), ToolType.HARVEST, modifier) / 128f;
}
return speed;
}
@Override
public void afterBlockBreak(IToolStackView tool, ModifierEntry modifier, ToolHarvestContext context) {
if (context.canHarvest() && context.isEffective() && !context.isAOE()) {
// funny duration formula from 1.12, guess it makes faster tools have a slightly shorter effect
int duration = (int) ((10f / tool.getStats().get(ToolStats.MINING_SPEED)) * 1.5f * 20f);
// 32 blocks gets you to max, effect is stronger at higher levels
applyEffect(context.getLiving(), ToolType.HARVEST, duration, 31);
}
}
@Override
public void onProjectileLaunch(IToolStackView tool, ModifierEntry modifier, LivingEntity shooter, Projectile projectile, @Nullable AbstractArrow arrow, ModDataNBT persistentData, boolean primary) {
if (primary && (arrow == null || arrow.isCritArrow())) {
// 16 arrows gets you to max
applyEffect(shooter, ToolType.RANGED, 5*20, 15);
}
}
@Override
public float modifyStat(IToolStackView tool, ModifierEntry modifier, LivingEntity living, FloatToolStat stat, float baseValue, float multiplier) {
if (stat == ToolStats.DRAW_SPEED) {
return baseValue * (1 + getBonus(living, ToolType.RANGED, modifier) / 64f);
}
return baseValue;
}
@Override
public void addTooltip(IToolStackView tool, ModifierEntry modifier, @Nullable Player player, List<Component> tooltip, TooltipKey key, TooltipFlag tooltipFlag) {
ToolType type = ToolType.from(tool.getItem(), ToolType.HARVEST, ToolType.RANGED);
if (type != null) {
float bonus;
if (player != null && key == TooltipKey.SHIFT) {
bonus = getBonus(player, type, modifier) / (type == ToolType.RANGED ? 64 : 128);
} else {
bonus = modifier.getEffectiveLevel();
}
if (bonus > 0) {
TooltipModifierHook.addPercentBoost(this, SPEED, bonus, tooltip);
}
}
}
}
| 411 | 0.917188 | 1 | 0.917188 | game-dev | MEDIA | 0.845944 | game-dev | 0.964134 | 1 | 0.964134 |
StranikS-Scan/WorldOfTanks-Decompiled | 1,597 | source/res/scripts/client/gui/impl/gen/view_models/views/lobby/post_progression/single_step_model.py | # Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/gui/impl/gen/view_models/views/lobby/post_progression/single_step_model.py
from frameworks.wulf import Array
from gui.impl.gen.view_models.views.lobby.post_progression.modification_model import ModificationModel
from gui.impl.gen.view_models.views.lobby.post_progression.step_model import StepModel
class SingleStepModel(StepModel):
__slots__ = ()
def __init__(self, properties=10, commands=0):
super(SingleStepModel, self).__init__(properties=properties, commands=commands)
@property
def modification(self):
return self._getViewModel(6)
@staticmethod
def getModificationType():
return ModificationModel
def getChildrenIds(self):
return self._getArray(7)
def setChildrenIds(self, value):
self._setArray(7, value)
@staticmethod
def getChildrenIdsType():
return int
def getIsPrebattleSwitchEnabled(self):
return self._getBool(8)
def setIsPrebattleSwitchEnabled(self, value):
self._setBool(8, value)
def getIsPrebattleSwitchLocked(self):
return self._getBool(9)
def setIsPrebattleSwitchLocked(self, value):
self._setBool(9, value)
def _initialize(self):
super(SingleStepModel, self)._initialize()
self._addViewModelProperty('modification', ModificationModel())
self._addArrayProperty('childrenIds', Array())
self._addBoolProperty('isPrebattleSwitchEnabled', True)
self._addBoolProperty('isPrebattleSwitchLocked', False)
| 411 | 0.746659 | 1 | 0.746659 | game-dev | MEDIA | 0.723963 | game-dev | 0.939976 | 1 | 0.939976 |
gem5/gem5-resources | 7,463 | src/deprecated/parsec/disk-image/parsec/parsec-benchmark/pkgs/apps/facesim/src/Public_Library/Collisions_And_Interactions/COLLISION_PENALTY_FORCES.h | //#####################################################################
// Copyright 2004-2005, Ron Fedkiw, Joseph Teran, Eftychios Sifakis.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
// Class COLLISION_PENALTY_FORCES
//#####################################################################
#ifndef __COLLISION_PENALTY_FORCES__
#define __COLLISION_PENALTY_FORCES__
#include "../Forces_And_Torques/SOLIDS_FORCES.h"
#include "../Grids/TETRAHEDRON_MESH.h"
#include "TETRAHEDRON_COLLISION_BODY.h"
#include "COLLISION_BODY_LIST_3D.h"
#include "../Utilities/LOG.h"
namespace PhysBAM
{
template<class T>
class COLLISION_PENALTY_FORCES: public SOLIDS_FORCES<T, VECTOR_3D<T> >
{
public:
using SOLIDS_FORCES<T, VECTOR_3D<T> >::particles;
COLLISION_BODY_LIST_3D<T>* collision_body_list;
ARRAY<bool> skip_collision_body;
ARRAY<int> check_collision;
ARRAY<VECTOR_3D<T> > collision_force;
ARRAY<SYMMETRIC_MATRIX_3X3<T> > collision_force_derivative;
T stiffness;
T separation_parameter;
T self_collision_reciprocity_factor;
int collision_body_list_id;
LIST_ARRAY<LIST_ARRAY<int> > partition_check_collision;
LIST_ARRAY<int> particle_to_check_collision_index;
COLLISION_PENALTY_FORCES (SOLIDS_PARTICLE<T, VECTOR_3D<T> >& particles_input)
: SOLIDS_FORCES<T, VECTOR_3D<T> > (particles_input), collision_body_list_id (0)
{
Set_Stiffness();
Set_Separation_Parameter();
Set_Self_Collision_Reciprocity_Factor();
}
~COLLISION_PENALTY_FORCES()
{}
void Set_Stiffness (const T stiffness_input = (T) 1e4)
{
stiffness = stiffness_input;
}
void Set_Separation_Parameter (const T separation_parameter_input = (T) 1e-4)
{
separation_parameter = separation_parameter_input;
}
void Set_Collision_Body_List (COLLISION_BODY_LIST_3D<T>& collision_body_list_input)
{
collision_body_list = &collision_body_list_input;
skip_collision_body.Resize_Array (collision_body_list->collision_bodies.m);
ARRAY<bool>::copy (false, skip_collision_body);
}
void Set_Boundary_Only_Collisions (TETRAHEDRON_MESH& tetrahedron_mesh)
{
LIST_ARRAY<bool>* old_node_on_boundary = tetrahedron_mesh.node_on_boundary;
tetrahedron_mesh.node_on_boundary = 0;
tetrahedron_mesh.Initialize_Node_On_Boundary();
for (int p = 1; p <= particles.array_size; p++) if ( (*tetrahedron_mesh.node_on_boundary) (p)) check_collision.Append_Element (p);
collision_force.Resize_Array (check_collision.m);
collision_force_derivative.Resize_Array (check_collision.m);
delete tetrahedron_mesh.node_on_boundary;
tetrahedron_mesh.node_on_boundary = old_node_on_boundary;
ARRAY<bool> particle_checked (particles.number);
particle_to_check_collision_index.Resize_Array (particles.number);
for (int p = 1; p <= check_collision.m; p++)
{
particle_checked (check_collision (p)) = true;
particle_to_check_collision_index (check_collision (p)) = p;
}
if (particles.particle_ranges)
{
partition_check_collision.Resize_Array (particles.particle_ranges->m);
for (int r = 1; r <= particles.particle_ranges->m; r++)
{
VECTOR_2D<int>& range = (*particles.particle_ranges) (r);
for (int p = range.x; p <= range.y; p++)
{
if (particle_checked (p)) partition_check_collision (r).Append_Element (p);
}
}
}
}
void Set_Collision_Body_List_ID (const int id)
{
collision_body_list_id = id;
}
void Set_Self_Collision_Reciprocity_Factor (const T self_collision_reciprocity_factor_input = (T) 2)
{
self_collision_reciprocity_factor = self_collision_reciprocity_factor_input;
}
void Check_Collision (const int particle)
{
check_collision.Append_Unique_Element (particle);
}
void Omit_Collision (const int particle)
{
int index;
if (check_collision.Find (particle, index)) check_collision.Remove_Index (index);
}
void Resize_Collision_Arrays_From_Check_Collision()
{
collision_force.Resize_Array (check_collision.m);
collision_force_derivative.Resize_Array (check_collision.m);
}
void Enforce_Definiteness (const bool enforce_definiteness_input)
{}
void Update_Position_Based_State()
{
LOG::Time ("UPBS (CPF)");
if (collision_body_list_id && collision_body_list->collision_bodies (collision_body_list_id)->body_type == COLLISION_BODY_3D<T>::TETRAHEDRON_TYPE)
{
TETRAHEDRON_COLLISION_BODY<T>* collision_body = (TETRAHEDRON_COLLISION_BODY<T>*) collision_body_list->collision_bodies (collision_body_list_id);
collision_body->tetrahedralized_volume.tetrahedron_hierarchy->Update_Boxes (collision_body->collision_thickness);
collision_body->tetrahedralized_volume.triangulated_surface->Update_Vertex_Normals();
}
LOG::Stop_Time();
}
void Update_Forces_And_Derivatives()
{
for (int p = 1; p <= check_collision.m; p++)
{
int index = check_collision (p);
collision_force (p) = VECTOR_3D<T>();
collision_force_derivative (p) = SYMMETRIC_MATRIX_3X3<T>();
for (int r = 1; r <= collision_body_list->collision_bodies.m; r++) if (!skip_collision_body (r))
{
int collision_body_particle_index = 0;
if (collision_body_list_id == r) collision_body_particle_index = index;
T phi_value;
int aggregate = -1;
VECTOR_3D<T> normal = collision_body_list->collision_bodies (r)->Implicit_Surface_Extended_Normal (particles.X (index), phi_value, aggregate, collision_body_particle_index);
if (phi_value <= 0)
{
collision_force (p) += stiffness * (-phi_value + separation_parameter) * normal;
if (collision_body_list_id == r) collision_force_derivative (p) -= self_collision_reciprocity_factor * stiffness * SYMMETRIC_MATRIX_3X3<T>::Outer_Product (normal);
else collision_force_derivative (p) -= stiffness * SYMMETRIC_MATRIX_3X3<T>::Outer_Product (normal);
}
else if (phi_value < collision_body_list->collision_bodies (r)->collision_thickness)
{
collision_force (p) += stiffness * separation_parameter * (T) exp (-phi_value / separation_parameter) * normal;
if (collision_body_list_id == r)
collision_force_derivative (p) -= self_collision_reciprocity_factor * stiffness * (T) exp (-phi_value / separation_parameter) * SYMMETRIC_MATRIX_3X3<T>::Outer_Product (normal);
else collision_force_derivative (p) -= stiffness * (T) exp (-phi_value / separation_parameter) * SYMMETRIC_MATRIX_3X3<T>::Outer_Product (normal);
}
}
}
}
void Add_Velocity_Independent_Forces (ARRAY<VECTOR_3D<T> >& F) const
{
LOG::Time ("AVIF (CPF)");
for (int p = 1; p <= check_collision.m; p++) F (check_collision (p)) += collision_force (p);
LOG::Stop_Time();
}
void Add_Force_Differential (const ARRAY<VECTOR_3D<T> >& dX, ARRAY<VECTOR_3D<T> >& dF) const
{
//LOG::Time("AFD (CPF)");
for (int p = 1; p <= check_collision.m; p++) dF (check_collision (p)) += collision_force_derivative (p) * dX (check_collision (p));
//LOG::Stop_Time();
}
void Add_Force_Differential (const ARRAY<VECTOR_3D<T> >& dX, ARRAY<VECTOR_3D<T> >& dF, const int partition_id) const
{
for (int i = 1; i <= partition_check_collision (partition_id).m; i++)
{
int particle = partition_check_collision (partition_id) (i), index = particle_to_check_collision_index (particle);
dF (particle) += collision_force_derivative (index) * dX (particle);
}
}
//#####################################################################
};
}
#endif
| 411 | 0.690864 | 1 | 0.690864 | game-dev | MEDIA | 0.966194 | game-dev | 0.586569 | 1 | 0.586569 |
ServUO/ServUO | 1,229 | Scripts/Items/Artifacts/Equipment/Jewelry/PetrifiedMatriarchsTongue.cs | using System;
using Server;
namespace Server.Items
{
public class PetrifiedMatriarchsTongue : GoldRing
{
public override bool IsArtifact { get { return true; } }
public override int LabelNumber { get { return 1115776; } } // Petrified Matriarch's Tongue
public override int InitMinHits { get { return 255; } }
public override int InitMaxHits { get { return 255; } }
[Constructable]
public PetrifiedMatriarchsTongue()
{
Hue = 2006; //TODO: get proper hue, this is a guess
Attributes.RegenMana = 2;
Attributes.AttackChance = 10;
Attributes.CastSpeed = 1;
Attributes.CastRecovery = 2;
Attributes.LowerManaCost = 4;
Resistances.Poison = 5;
}
public PetrifiedMatriarchsTongue(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | 411 | 0.78304 | 1 | 0.78304 | game-dev | MEDIA | 0.627904 | game-dev | 0.683968 | 1 | 0.683968 |
pokeclicker/pokeclicker | 1,654 | src/scripts/quests/questTypes/UsePokeballQuest.ts | /// <reference path="../Quest.ts" />
class UsePokeballQuest extends Quest implements QuestInterface {
private pokeball: GameConstants.Pokeball;
constructor(amount: number, reward: number, pokeball: GameConstants.Pokeball) {
super(amount, reward);
this.pokeball = pokeball;
this.focus = App.game.statistics.pokeballsUsed[this.pokeball];
}
public static generateData(): any[] {
const possiblePokeballs = [GameConstants.Pokeball.Pokeball];
if (TownList['Lavender Town'].isUnlocked()) {
possiblePokeballs.push(GameConstants.Pokeball.Greatball);
}
if (TownList['Fuchsia City'].isUnlocked()) {
possiblePokeballs.push(GameConstants.Pokeball.Ultraball);
}
const pokeball = SeededRand.fromArray(possiblePokeballs);
const amount = SeededRand.intBetween(100, 500);
const reward = this.calcReward(amount, pokeball);
return [amount, reward, pokeball];
}
private static calcReward(amount: number, pokeball: GameConstants.Pokeball) {
// Reward for Greatballs is 4x Pokeballs, Ultraballs are 9x Pokeballs
const reward = Math.ceil(amount * (pokeball + 1) * (pokeball + 1) * GameConstants.DEFEAT_POKEMONS_BASE_REWARD);
return super.randomizeReward(reward);
}
get defaultDescription(): string {
return `Use ${this.amount.toLocaleString('en-US')} ${ItemList[GameConstants.Pokeball[this.pokeball]].displayName}s.`;
}
toJSON() {
const json = super.toJSON();
json.name = this.constructor.name;
json.data.push(this.pokeball);
return json;
}
}
| 411 | 0.706821 | 1 | 0.706821 | game-dev | MEDIA | 0.657958 | game-dev,web-frontend | 0.694075 | 1 | 0.694075 |
VeloraDEX/paraswap-dex-lib | 9,338 | src/dex/uniswap-v4/uniswap-v4-pool.ts | import {
InitializeStateOptions,
StatefulEventSubscriber,
} from '../../stateful-event-subscriber';
import { DexParams, PoolPairsInfo, PoolState, TickInfo } from './types';
import { IDexHelper } from '../../dex-helper';
import { Log, Logger } from '../../types';
import { BytesLike, Interface } from 'ethers/lib/utils';
import UniswapV4StateViewABI from '../../abi/uniswap-v4/state-view.abi.json';
import UniswapV4PoolManagerABI from '../../abi/uniswap-v4/pool-manager.abi.json';
import UniswapV4StateMulticallABI from '../../abi/uniswap-v4/state-multicall.abi.json';
import { BlockHeader } from 'web3-eth';
import { DeepReadonly } from 'ts-essentials';
import _ from 'lodash';
import { catchParseLogError } from '../../utils';
import { uniswapV4PoolMath } from './contract-math/uniswap-v4-pool-math';
import {
TICK_BITMAP_BUFFER,
TICK_BITMAP_BUFFER_BY_CHAIN,
TICK_BITMAP_TO_USE,
TICK_BITMAP_TO_USE_BY_CHAIN,
} from './constants';
import { MultiResult } from '../../lib/multi-wrapper';
import { NumberAsString } from '@paraswap/core';
import { extractSuccessAndValue } from '../../lib/decoders';
export class UniswapV4Pool extends StatefulEventSubscriber<PoolState> {
handlers: {
[event: string]: (
event: any,
pool: PoolState,
log: Log,
blockHeader: Readonly<BlockHeader>,
) => PoolState;
} = {};
logDecoder: (log: Log) => any;
stateViewIface: Interface;
poolManagerIface: Interface;
stateMulticallIface: Interface;
constructor(
readonly dexHelper: IDexHelper,
parentName: string,
private readonly network: number,
private readonly config: DexParams,
protected logger: Logger,
mapKey: string = '',
public readonly poolId: string,
public readonly token0: string,
public readonly token1: string,
public readonly fee: string,
public readonly hooks: string,
public tickSpacing: string,
) {
super(parentName, poolId, dexHelper, logger, true, mapKey);
this.stateViewIface = new Interface(UniswapV4StateViewABI);
this.poolManagerIface = new Interface(UniswapV4PoolManagerABI);
this.stateMulticallIface = new Interface(UniswapV4StateMulticallABI);
this.addressesSubscribed = [this.config.poolManager];
this.logDecoder = (log: Log) => this.poolManagerIface.parseLog(log);
// Add handlers
this.handlers['Swap'] = this.handleSwapEvent.bind(this);
this.handlers['Donate'] = this.handleDonateEvent.bind(this);
this.handlers['ProtocolFeeUpdated'] =
this.handleProtocolFeeUpdatedEvent.bind(this);
this.handlers['ModifyLiquidity'] =
this.handleModifyLiquidityEvent.bind(this);
}
async initialize(
blockNumber: number,
options?: InitializeStateOptions<PoolState>,
) {
await super.initialize(blockNumber, options);
}
getPoolIdentifierData(): PoolPairsInfo {
return {
poolId: this.poolId,
};
}
async getOrGenerateState(blockNumber: number): Promise<PoolState> {
let state = this.getState(blockNumber);
this.logger.warn(
`${this.parentName}: No state found on block ${blockNumber} for pool ${this.poolId}, generating new one`,
);
if (!state) {
state = await this.generateState(blockNumber);
this.setState(state, blockNumber);
}
return state;
}
async generateState(blockNumber: number): Promise<PoolState> {
const poolKey = {
currency0: this.token0,
currency1: this.token1,
fee: this.fee,
tickSpacing: parseInt(this.tickSpacing),
hooks: this.hooks,
};
const callData = this.stateMulticallIface.encodeFunctionData(
'getFullStateWithRelativeBitmaps',
[
this.config.poolManager,
poolKey,
this.getBitmapRange(),
this.getBitmapRange(),
],
);
const result = await this.dexHelper.multiWrapper.tryAggregate<any>(
false,
[
{
target: this.config.stateMulticall,
callData,
decodeFunction: (result: MultiResult<BytesLike> | BytesLike) => {
const [, toDecode] = extractSuccessAndValue(result);
return this.stateMulticallIface.decodeFunctionResult(
'getFullStateWithRelativeBitmaps',
toDecode,
);
},
},
],
blockNumber,
this.dexHelper.multiWrapper.defaultBatchSize,
false,
);
const stateResult = result[0].returnData[0];
const ticksResults: Record<NumberAsString, TickInfo> = {};
stateResult.ticks.forEach((tick: any) => {
if (tick.value.liquidityGross > 0n) {
ticksResults[tick.index.toString()] = {
liquidityGross: BigInt(tick.value.liquidityGross),
liquidityNet: BigInt(tick.value.liquidityNet),
};
}
});
const tickBitMapResults: Record<NumberAsString, bigint> = {};
stateResult.tickBitmap.forEach((bitmap: any) => {
tickBitMapResults[bitmap.index.toString()] = BigInt(bitmap.value);
});
return {
id: this.poolId,
token0: this.token0.toLowerCase(),
token1: this.token1.toLowerCase(),
fee: this.fee,
hooks: this.hooks,
feeGrowthGlobal0X128: BigInt(stateResult.feeGrowthGlobal0X128),
feeGrowthGlobal1X128: BigInt(stateResult.feeGrowthGlobal1X128),
liquidity: BigInt(stateResult.liquidity),
slot0: {
sqrtPriceX96: BigInt(stateResult.slot0.sqrtPriceX96),
tick: BigInt(stateResult.slot0.tick),
protocolFee: BigInt(stateResult.slot0.protocolFee),
lpFee: BigInt(stateResult.slot0.lpFee),
},
tickSpacing: parseInt(this.tickSpacing),
ticks: ticksResults,
tickBitmap: tickBitMapResults,
isValid: true,
};
}
getBitmapRange() {
const networkId = this.dexHelper.config.data.network;
const tickBitMapToUse =
TICK_BITMAP_TO_USE_BY_CHAIN[networkId] ?? TICK_BITMAP_TO_USE;
const tickBitMapBuffer =
TICK_BITMAP_BUFFER_BY_CHAIN[networkId] ?? TICK_BITMAP_BUFFER;
return tickBitMapToUse + tickBitMapBuffer;
}
protected async processBlockLogs(
state: DeepReadonly<PoolState>,
logs: Readonly<Log>[],
blockHeader: Readonly<BlockHeader>,
): Promise<DeepReadonly<PoolState> | null> {
const newState = await super.processBlockLogs(state, logs, blockHeader);
if (newState && !newState.isValid) {
return await this.generateState(blockHeader.number);
}
return newState;
}
protected async processLog(
state: PoolState,
log: Readonly<Log>,
blockHeader: Readonly<BlockHeader>,
): Promise<DeepReadonly<PoolState | null>> {
try {
const event = this.logDecoder(log);
if (event.name in this.handlers) {
const id = event.args.id.toLowerCase();
if (id && id !== this.poolId.toLowerCase()) return null; // skip not relevant events
const _state = _.cloneDeep(state) as PoolState;
try {
return this.handlers[event.name](event, _state, log, blockHeader);
} catch (e) {
this.logger.error(
`${this.parentName}: PoolManager ${this.config.poolManager} (pool id ${this.poolId}), ` +
`network=${this.dexHelper.config.data.network}: Unexpected ` +
`error while handling event on blockNumber=${blockHeader.number} for ${this.parentName}, txHash=${log.transactionHash}, logIndex=${log.logIndex}, event=${event?.name}`,
e,
);
_state.isValid = false;
return _state;
}
}
} catch (e) {
catchParseLogError(e, this.logger);
}
return null;
}
handleProtocolFeeUpdatedEvent(event: any, poolState: PoolState) {
const protocolFee = event.args.protocolFee;
uniswapV4PoolMath.checkPoolInitialized(poolState);
uniswapV4PoolMath.setProtocolFee(poolState, protocolFee);
return poolState;
}
handleDonateEvent(event: any, poolState: PoolState) {
const amount0 = BigInt(event.args.amount0);
const amount1 = BigInt(event.args.amount1);
uniswapV4PoolMath.checkPoolInitialized(poolState);
uniswapV4PoolMath.donate(poolState, amount0, amount1);
return poolState;
}
handleSwapEvent(event: any, poolState: PoolState) {
const amount0 = BigInt(event.args.amount0);
const amount1 = BigInt(event.args.amount1);
const resultSqrtPriceX96 = BigInt(event.args.sqrtPriceX96);
const resultLiquidity = BigInt(event.args.liquidity);
const resultTick = BigInt(event.args.tick);
const resultSwapFee = BigInt(event.args.fee);
const zeroForOne = amount0 < 0n;
uniswapV4PoolMath.checkPoolInitialized(poolState);
uniswapV4PoolMath.swapFromEvent(
poolState,
zeroForOne,
resultSqrtPriceX96,
resultTick,
resultLiquidity,
resultSwapFee,
amount0,
amount1,
this.logger,
);
return poolState;
}
handleModifyLiquidityEvent(event: any, poolState: PoolState, _: Log) {
uniswapV4PoolMath.checkPoolInitialized(poolState);
const tickLower = BigInt(event.args.tickLower);
const tickUpper = BigInt(event.args.tickUpper);
const liquidityDelta = BigInt(event.args.liquidityDelta);
uniswapV4PoolMath.modifyLiquidity(poolState, {
liquidityDelta,
tickUpper,
tickLower,
tickSpacing: BigInt(poolState.tickSpacing),
});
return poolState;
}
}
| 411 | 0.913659 | 1 | 0.913659 | game-dev | MEDIA | 0.450812 | game-dev | 0.964675 | 1 | 0.964675 |
shit-ware/IW4 | 16,595 | maps/so_rooftop_contingency_code.gsc | #include maps\_utility;
#include common_scripts\utility;
#include maps\_anim;
#include maps\_specialops;
#include maps\_hud_util;
#include maps\_vehicle;
get_wave_count()
{
return level.wave_spawn_structs.size;
}
get_wave_ai_count( wave_num )
{
return level.wave_spawn_structs[ wave_num ].hostile_count;
}
get_wave_vehicles( wave_num )
{
return level.wave_spawn_structs[ wave_num ].vehicles;
}
get_vehicle_type_count( wave_num, type )
{
count = 0;
vehicles = get_wave_vehicles( wave_num );
foreach ( vehicle in vehicles )
{
if ( vehicle.type == type )
{
count++;
}
}
return count;
}
// UAV Section ---------------------------------------------- //
uav_pickup_setup()
{
uav_pickup = GetEnt( "uav_controller", "targetname" );
AssertEx( IsDefined( uav_pickup ), "Missing UAV controller pickup objective model in level." );
uav_pickup Hide();
wait_to_pickup_uav();
thread pickup_uav_reminder();
wait( 1 );
while ( 1 )
{
//level waittill( "new_wave_started" );
wait( 2 );
uav_pickup Show();
uav_pickup MakeUsable();
uav_pickup SetCursorHint( "HINT_NOICON" );
// Hold &&1 to pick up
uav_pickup SetHintString( &"SO_ROOFTOP_CONTINGENCY_DRONE_PICKUP" );
uav_pickup waittill( "trigger", player );
uav_pickup PlaySound( "detpack_pickup" );
level.so_uav_picked_up = true;
level.so_uav_player = player;
flag_set( "uav_in_use" );
player maps\_remotemissile::give_remotemissile_weapon( level.remote_detonator_weapon );
// If wave 2 has not started yet, disable the uav.
if ( level.gameskill > 1 && !flag( "wave_2_started" ) || !flag( "wave_1_started" ) )
{
level.so_uav_player maps\_remotemissile::disable_uav( false, true );
}
uav_pickup MakeUnusable();
uav_pickup Hide();
if ( !isdefined( player.already_displayed_hint ) )
{
// If the wave 2 hasn't already started, then hold on displaying hint until it actually does.
if ( level.gameskill > 1 && !flag( "wave_2_started" ) )
{
flag_wait( "wave_2_started" );
}
else if ( !flag( "wave_1_started" ) )
{
flag_wait( "wave_1_started" );
}
player.already_displayed_hint = 1;
if ( IsDefined( player.remotemissile_actionslot ) )
{
player display_hint( "use_uav_" + player.remotemissile_actionslot );
}
else
{
player display_hint( "use_uav_4" );
}
}
if ( !level.UAV_pickup_respawn )
{
return;
}
flag_waitopen( "uav_in_use" );
wait level.uav_spawn_delay;// delay between uav spawns
}
}
pickup_uav_reminder()
{
level endon( "uav_in_use" );
while ( 1 )
{
wait( RandomFloatRange( 15, 20 ) );
if ( flag( "special_op_terminated" ) )
{
return;
}
radio_dialogue( "so_pickup_uav_reminder" );
}
}
wait_to_pickup_uav()
{
wait_to_pickup = true;
/#
if ( GetDvarInt( "uav_now" ) > 0 )
{
wait_to_pickup = false;
}
#/
if ( level.gameSkill < 2 )
{
wait_to_pickup = false;
}
if ( wait_to_pickup )
{
// Just wait for the first wave to be wiped out
flag_wait( "wave_wiped_out" );
}
else
{
// Wait for the first round to start
flag_wait( "start_countdown" );
}
}
uav()
{
wait_to_pickup_uav();
thread dialog_uav();
level.uav = spawn_vehicle_from_targetname_and_drive( "second_uav" );
level.uav PlayLoopSound( "uav_engine_loop" );
level.uavRig = Spawn( "script_model", level.uav.origin );
level.uavRig SetModel( "tag_origin" );
thread uav_rig_aiming();
}
dialog_uav()
{
//The UAV is almost in position.
radio_dialogue( "cont_cmt_almostinpos" );
}
uav_rig_aiming()
{
if ( !isalive( level.uav ) )
{
return;
}
if ( IsDefined( level.uav_is_destroyed ) )
{
return;
}
focus_points = GetEntArray( "uav_focus_point", "targetname" );
level endon( "uav_destroyed" );
level.uav endon( "death" );
for ( ;; )
{
closest_focus = getClosest( level.player.origin, focus_points );
targetPos = closest_focus.origin;
angles = VectorToAngles( targetPos - level.uav.origin );
level.uavRig MoveTo( level.uav.origin, 0.10, 0, 0 );
level.uavRig RotateTo( ANGLES, 0.10, 0, 0 );
wait( 0.05 );
}
}
// Vehicles -----------------------------------------------
setup_base_vehicles()
{
self endon( "death" );
self thread maps\_remotemissile::setup_remote_missile_target();
// self thread update_badplace();
self thread unload_when_stuck();
// self thread custom_connectpaths_ondeath();
self thread vehicle_death_paths();
self waittill( "unloaded" );
if ( IsDefined( self.has_target_shader ) )
{
self.has_target_shader = undefined;
Target_Remove( self );
}
level.remote_missile_targets = array_remove( level.remote_missile_targets, self );
}
vehicle_death_paths()
{
self endon( "delete" );
// Notify from _vehicle::vehicle_kill, after the phys vehicle is blown up and disconnectpaths
self waittill( "kill_badplace_forever" );
min_dist = 50 * 50;
death_origin = self.origin;
while ( IsDefined( self ) )
{
if ( DistanceSquared( self.origin, death_origin ) > min_dist )
{
death_origin = self.origin;
// Connect the paths before we get to far away from the death_origin
self ConnectPaths();
// Don't disconnectpaths until we're done moving.
while ( 1 )
{
wait( 0.05 );
if ( !IsDefined( self ) )
{
return;
}
if ( DistanceSquared( self.origin, death_origin ) < 1 )
{
break;
}
death_origin = self.origin;
}
// Now disconnectpaths after we have settled
self DisconnectPaths();
}
wait( 0.05 );
}
}
// We need this to reconnect the paths after _vehicle::vehicle_kill disconnects them.
//custom_connectpaths_ondeath()
//{
// self waittill( "kill_badplace_forever" );
//
// wait( 0.1 );
// self ConnectPaths();
//}
//
//update_badplace()
//{
// self endon( "delete" );
//
// duration = 0.5;
//
// radius = 100;
// if ( self.vehicletype == "bm21_troops" )
// {
// radius = 176;
// }
// else if( self.vehicletype == "uaz_physics" )
// {
// radius = 90;
// }
//
// height = 300;
//
// while ( 1 )
// {
// speed = self Vehicle_GetSpeed();
// if ( !IsAlive( self ) || speed < 0.2 )
// {
// BadPlace_Cylinder( self.unique_id + "cyl_bp", duration, self.origin, radius, height, "axis", "team3", "allies" );
// }
//
// wait( duration + 0.05 );
// }
//}
unload_when_stuck()
{
self endon( "unloaded" );
self endon( "unloading" );
self endon( "death" );
while ( 1 )
{
wait( 2 );
if ( self Vehicle_GetSpeed() < 2 )
{
self Vehicle_SetSpeed( 0, 15 );
self thread maps\_vehicle::vehicle_unload();
self notify( "kill_badplace_forever" );
return;
}
}
}
spawn_vehicle_and_go( struct )
{
spawner = struct.ent;
if ( IsDefined( struct.delay ) )
{
wait( struct.delay );
}
if ( IsDefined( struct.alt_node ) )
{
targetname = struct.alt_node.targetname;
spawner.target = targetname;
}
vehicle = spawner spawn_vehicle();
// So the corpse of the vehicle cannot be moved
// vehicle.free_on_death = true;
// vehicle thread vehicle_becomes_crashable();
// vehicle.dontDisconnectPaths = true;
vehicle StartPath();
// vehicle thread force_unload( spawner.target + "_end" );
/#
so_debug_print( "vehicle[" + spawner.targetname + "] spawned" );
vehicle waittill( "unloading" );
so_debug_print( "vehicle[" + spawner.targetname + "] unloading guys" );
vehicle waittill( "unloaded" );
so_debug_print( "vehicle[" + spawner.targetname + "] unloading complete" );
#/
}
//force_unload( end_name )
//{
//// end_node = get_last_ent_in_chain( sEntityType );
//
// end_node = GetVehicleNode( end_name, "targetname" );
// end_node waittill( "trigger" );
//
// self Vehicle_SetSpeed( 0, 15 );
// wait 1;
// self maps\_vehicle::vehicle_unload();
//}
// HUD ----------------------------------------------------
hud_wave_num()
{
while ( 1 )
{
level waittill( "new_wave_started" );
// Little delay so the "Wave Starting in..." can be removed
wait( 1 );
hud_count = undefined;
if ( level.current_wave < get_wave_count() )
{
hud = so_create_hud_item( 0, so_hud_ypos(), &"SPECIAL_OPS_WAVENUM", self );
hud_count = so_create_hud_item( 0, so_hud_ypos(), undefined, self );
hud_count.alignx = "left";
hud_count SetValue( level.current_wave );
}
else
{
hud = so_create_hud_item( 0, so_hud_ypos(), &"SPECIAL_OPS_WAVEFINAL", self );
hud.alignx = "center";
}
music_loop( "so_rooftop_contingency_music", 291 );
flag_wait( "wave_wiped_out" );
music_stop( 1 );
hud thread so_remove_hud_item( true );
if ( IsDefined( hud_count ) )
{
hud_count thread so_remove_hud_item( true );
}
}
}
hud_hostile_count()
{
// Hostiles:
hudelem_title = so_create_hud_item( 2, so_hud_ypos(), &"SO_ROOFTOP_CONTINGENCY_HOSTILES", self );
hudelem_count = so_create_hud_item( 2, so_hud_ypos(), &"SPECIAL_OPS_DASHDASH", self );
hudelem_count.alignx = "left";
flag_wait( "waves_start" );
/* thread info_hud_handle_fade( hudelem_title, "stop_fading_count" );
thread info_hud_handle_fade( hudelem_count, "stop_fading_count" );*/
max_count = level.hostile_count;
while ( !flag( "challenge_success" ) || !flag( "special_op_terminated" ) )
{
// Be sure to only play the dialog once.
if ( self == level.player )
{
thread so_dialog_counter_update( level.hostile_count, max_count );
}
curr_count = level.hostile_count;
hudelem_count.label = "";
hudelem_count Setvalue( level.hostile_count );
if ( curr_count <= 0 )
{
hudelem_count so_remove_hud_item( true );
hudelem_count = so_create_hud_item( 2, so_hud_ypos(), &"SPECIAL_OPS_DASHDASH", self );
hudelem_count.alignx = "left";
hudelem_title thread so_hud_pulse_success();
hudelem_count thread so_hud_pulse_success();
}
else if ( curr_count <= 5 )
{
hudelem_title thread so_hud_pulse_close();
hudelem_count thread so_hud_pulse_close();
}
while ( !flag( "challenge_success" ) && ( curr_count == level.hostile_count ) )
{
wait( 0.05 );
// This indicates a new wave has started...
if ( level.hostile_count > curr_count )
{
max_count = level.hostile_count;
level.so_progress_goal_status = "none";
hudelem_title thread so_hud_pulse_default();
hudelem_count thread so_hud_pulse_default();
}
}
}
hudelem_count so_remove_hud_item( true );
hudelem_count = so_create_hud_item( 2, so_hud_ypos(), &"SPECIAL_OPS_DASHDASH", self );
hudelem_count.alignx = "left";
hudelem_title thread so_remove_hud_item();
hudelem_count thread so_remove_hud_item();
level notify( "stop_fading_count" );
}
hud_new_wave()
{
current_wave = level.current_wave + 1;
if ( current_wave > get_wave_count() )
{
return;
}
// Next Wave in:
wave_msg = &"SO_ROOFTOP_CONTINGENCY_WAVE_STARTS";
wave_delay = 0.75;
if ( current_wave == get_wave_count() )
{
// Final Wave in:
wave_msg = &"SO_ROOFTOP_CONTINGENCY_WAVE_FINAL_STARTS";
}
else
{
if ( current_wave == 2 )
{
// Second Wave in:
wave_msg = &"SO_ROOFTOP_CONTINGENCY_WAVE_SECOND_STARTS";
}
if ( current_wave == 3 )
{
// Third Wave in:
wave_msg = &"SO_ROOFTOP_CONTINGENCY_WAVE_THIRD_STARTS";
}
if ( current_wave == 4 )
{
// Fourth Wave in:
wave_msg = &"SO_ROOFTOP_CONTINGENCY_WAVE_FOURTH_STARTS";
}
}
thread enable_countdown_timer( level.wave_delay, false, wave_msg, wave_delay );
wait 2;
hud_wave_splash( current_wave, level.wave_delay - 2 );
/*
hudelem = so_create_hud_item( 0, so_hud_ypos(), wave_msg );
hudelem SetPulseFX( 50, level.wave_delay * 1000, 500 );
hudelem_time = so_create_hud_item( 0, so_hud_ypos(), "" );
hudelem_time.alignX = "left";
hudelem_time SetTenthsTimer( level.wave_delay );
hudelem_time SetPulseFX( 50, level.wave_delay * 1000, 500 );
wait( level.wave_delay );*/
}
// Returns structs...
hud_get_wave_list( wave_num )
{
list = [];
list[ 0 ] = SpawnStruct();
if ( wave_num < get_wave_count() )
{
list[ 0 ].text = &"SPECIAL_OPS_INTERMISSION_WAVENUM";
list[ 0 ].count = wave_num;
}
else
{
list[ 0 ].text = &"SPECIAL_OPS_INTERMISSION_WAVEFINAL";
}
// switch( wave_num )
// {
// case 1:
// // - Wave 1 -
// list[ 0 ].text = &"SO_ROOFTOP_CONTINGENCY_WAVE1";
// break;
//
// case 2:
// // - Wave 2 -
// list[ 0 ].text = &"SO_ROOFTOP_CONTINGENCY_WAVE2";
// break;
//
// case 3:
// // - Wave 3 -
// list[ 0 ].text = &"SO_ROOFTOP_CONTINGENCY_WAVE3";
// break;
//
// case 4:
// // - Wave 4 -
// list[ 0 ].text = &"SO_ROOFTOP_CONTINGENCY_WAVE4";
// break;
//
// case 5:
// // - Wave 5 -
// list[ 0 ].text = &"SO_ROOFTOP_CONTINGENCY_WAVE5";
// break;
//
// default:
// AssertMsg( "Wrong wave_num passed in" );
// break;
// }
list[ 1 ] = SpawnStruct();
// &&1 Hostiles
list[ 1 ].text = &"SO_ROOFTOP_CONTINGENCY_HOSTILES_COUNT";
list[ 1 ].count = get_wave_ai_count( wave_num );
index = 2;
// Figure out vehicles
uaz_count = get_vehicle_type_count( wave_num, "uaz" );
// Add each UAZ to the total hostiles
list[ 1 ].count += ( uaz_count * 4 );
if ( uaz_count > 0 )
{
if ( uaz_count == 1 )
{
// &&1 UAZ Vehicle
str = &"SO_ROOFTOP_CONTINGENCY_UAZ_COUNT_SINGLE";
}
else
{
// &&1 UAZ Vehicles
str = &"SO_ROOFTOP_CONTINGENCY_UAZ_COUNT";
}
list[ index ] = SpawnStruct();
list[ index ].text = str;
list[ index ].count = uaz_count;
index++;
}
bm21_count = get_vehicle_type_count( wave_num, "bm21" );
// Add each BM21 to the total hostiles
list[ 1 ].count += ( bm21_count * 6 );
if ( bm21_count > 0 )
{
if ( bm21_count == 1 )
{
// &&1 BM21 Troop Carrier
str = &"SO_ROOFTOP_CONTINGENCY_BM21_COUNT_SINGLE";
}
else
{
// &&1 BM21 Troop Carriers
str = &"SO_ROOFTOP_CONTINGENCY_BM21_COUNT";
}
list[ index ] = SpawnStruct();
list[ index ].text = str;
list[ index ].count = bm21_count;
}
return list;
}
hud_create_wave_splash( yLine, message )
{
hudelem = so_create_hud_item( yLine, 0, message );
hudelem.alignX = "center";
hudelem.horzAlign = "center";
return hudelem;
}
hud_wave_splash( wave_num, timer )
{
hudelems = [];
list = hud_get_wave_list( wave_num );
for ( i = 0; i < list.size; i++ )
{
hudelems[ i ] = hud_create_wave_splash( i, list[ i ].text );
if ( IsDefined( list[ i ].count ) )
{
hudelems[ i ] SetValue( list[ i ].count );
}
hudelems[ i ] SetPulseFX( 60, ( ( timer - 1 ) * 1000 ) - ( i * 1000 ), 1000 );
wait( 1 );
}
wait( timer - ( list.size * 1 ) );
foreach ( hudelem in hudelems )
{
hudelem Destroy();
}
}
// DEBUG ---------------------------------------------------
so_debug_print( msg, delay )
{
message = "> " + msg;
if ( IsDefined( delay ) )
{
wait delay;
message = "+>" + message;
}
else
{
message = ">>" + message;
}
if ( GetDvar( "specialops_debug" ) == "1" )
IPrintLn( message );
}
distance2d_squared( pos1, pos2 )
{
pos1 = ( pos1[ 0 ], pos1[ 1 ], 0 );
pos2 = ( pos2[ 0 ], pos2[ 1 ], 0 );
return DistanceSquared( pos1, pos2 );
}
//player_input()
//{
// while( 1 )
// {
// eye_pos = level.player GetEye();
// forward = AnglesToForward( level.player GetPlayerAngles() );
// forward_pos = eye_pos + vector_multiply( forward, 2000 );
// trace = BulletTrace( eye_pos, forward_pos, false, undefined );
// pos = trace[ "position" ];
// draw_circle( pos, 32 );
//
// if ( level.player UseButtonPressed() )
// {
// missile = MagicBullet( "remote_missile_snow", pos + ( 0, 0, 200 ), pos, level.player );
// thread do_physics_impact_on_explosion( level.player );
// wait( 0.5 );
// }
//
// wait( 0.05 );
// }
//}
//
//do_physics_impact_on_explosion( player )
//{
// player waittill( "projectile_impact", weaponName, position, radius );
//
// level.uavTargetPos = position;
//
// physicsSphereRadius = 1000;
// physicsSphereForce = 6.0;
//// Earthquake( .3, 1.4, position, 8000 );
//
// wait 0.1;
// PhysicsExplosionSphere( position, physicsSphereRadius, physicsSphereRadius / 2, physicsSphereForce );
//}
//
//
//draw_circle( center, radius )
//{
// circle_sides = 16;
//
// angleFrac = 360 / circle_sides;
//
// // Z circle
// circlepoints = [];
// for ( i = 0; i < circle_sides; i++ )
// {
// angle = ( angleFrac * i );
// xAdd = Cos( angle ) * radius;
// yAdd = Sin( angle ) * radius;
// x = center[ 0 ] + xAdd;
// y = center[ 1 ] + yAdd;
// z = center[ 2 ];
// circlepoints[ circlepoints.size ] = ( x, y, z );
// }
//
// thread draw_circlepoints( circlepoints );
//}
//
//draw_circlepoints( circlepoints )
//{
// color = ( 0.8, 0, 0 );
//
// for ( i = 0; i < circlepoints.size; i++ )
// {
// start = circlepoints[ i ];
// if ( i + 1 >= circlepoints.size )
// {
// end = circlepoints[ 0 ];
// }
// else
// {
// end = circlepoints[ i + 1 ];
// }
//
// line( start, end, color );
// }
//} | 411 | 0.94515 | 1 | 0.94515 | game-dev | MEDIA | 0.95209 | game-dev | 0.972813 | 1 | 0.972813 |
ComputationalBiomechanicsLab/opensim-creator | 3,945 | libopensimcreator/UI/Simulation/ISimulatorUIAPI.h | #pragma once
#include <libopensimcreator/Documents/OutputExtractors/OutputExtractor.h>
#include <libopensimcreator/Documents/Simulation/SimulationClock.h>
#include <libopensimcreator/Documents/Simulation/SimulationReport.h>
#include <libopensimcreator/UI/Simulation/SimulationUILoopingState.h>
#include <libopensimcreator/UI/Simulation/SimulationUIPlaybackState.h>
#include <initializer_list>
#include <optional>
#include <span>
namespace osc { class OutputExtractor; }
namespace osc { class SimulationModelStatePair; }
namespace osc { class ISimulation; }
namespace osc
{
// virtual API for the simulator UI (e.g. the simulator tab)
//
// this is how individual widgets within a simulator UI communicate with the simulator UI
class ISimulatorUIAPI {
protected:
ISimulatorUIAPI() = default;
ISimulatorUIAPI(const ISimulatorUIAPI&) = default;
ISimulatorUIAPI(ISimulatorUIAPI&&) noexcept = default;
ISimulatorUIAPI& operator=(const ISimulatorUIAPI&) = default;
ISimulatorUIAPI& operator=(ISimulatorUIAPI&&) noexcept = default;
public:
virtual ~ISimulatorUIAPI() noexcept = default;
const ISimulation& getSimulation() const { return implGetSimulation(); }
ISimulation& updSimulation() { return implUpdSimulation(); }
SimulationUIPlaybackState getSimulationPlaybackState() { return implGetSimulationPlaybackState(); }
void setSimulationPlaybackState(SimulationUIPlaybackState s) { implSetSimulationPlaybackState(s); }
virtual SimulationUILoopingState getSimulationLoopingState() const { return implGetSimulationLoopingState(); }
virtual void setSimulationLoopingState(SimulationUILoopingState s) { implSetSimulationLoopingState(s); }
float getSimulationPlaybackSpeed() { return implGetSimulationPlaybackSpeed(); }
void setSimulationPlaybackSpeed(float v) { implSetSimulationPlaybackSpeed(v); }
SimulationClock::time_point getSimulationScrubTime() { return implGetSimulationScrubTime(); }
void stepBack() { implStepBack(); }
void stepForward() { implStepForward(); }
void setSimulationScrubTime(SimulationClock::time_point t) { implSetSimulationScrubTime(t); }
std::optional<SimulationReport> trySelectReportBasedOnScrubbing() { return implTrySelectReportBasedOnScrubbing(); }
void tryPromptToSaveOutputsAsCSV(std::span<const OutputExtractor>, bool openInDefaultApp) const;
void tryPromptToSaveOutputsAsCSV(std::initializer_list<OutputExtractor> il, bool openInDefaultApp) const
{
tryPromptToSaveOutputsAsCSV(std::span<const OutputExtractor>{il}, openInDefaultApp);
}
void tryPromptToSaveAllOutputsAsCSV(std::span<const OutputExtractor>, bool andOpenInDefaultApp = false) const;
SimulationModelStatePair* tryGetCurrentSimulationState() { return implTryGetCurrentSimulationState(); }
private:
virtual const ISimulation& implGetSimulation() const = 0;
virtual ISimulation& implUpdSimulation() = 0;
virtual SimulationUIPlaybackState implGetSimulationPlaybackState() = 0;
virtual void implSetSimulationPlaybackState(SimulationUIPlaybackState) = 0;
virtual SimulationUILoopingState implGetSimulationLoopingState() const = 0;
virtual void implSetSimulationLoopingState(SimulationUILoopingState) = 0;
virtual float implGetSimulationPlaybackSpeed() = 0;
virtual void implSetSimulationPlaybackSpeed(float) = 0;
virtual SimulationClock::time_point implGetSimulationScrubTime() = 0;
virtual void implSetSimulationScrubTime(SimulationClock::time_point) = 0;
virtual void implStepBack() = 0;
virtual void implStepForward() = 0;
virtual std::optional<SimulationReport> implTrySelectReportBasedOnScrubbing() = 0;
virtual SimulationModelStatePair* implTryGetCurrentSimulationState() = 0;
};
}
| 411 | 0.786486 | 1 | 0.786486 | game-dev | MEDIA | 0.715902 | game-dev | 0.757282 | 1 | 0.757282 |
hannibal002/SkyHanni | 5,621 | src/main/java/at/hannibal2/skyhanni/features/misc/pathfind/NavigationHelper.kt | package at.hannibal2.skyhanni.features.misc.pathfind
import at.hannibal2.skyhanni.SkyHanniMod
import at.hannibal2.skyhanni.api.event.HandleEvent
import at.hannibal2.skyhanni.config.commands.CommandRegistrationEvent
import at.hannibal2.skyhanni.data.IslandGraphs
import at.hannibal2.skyhanni.data.IslandGraphs.pathFind
import at.hannibal2.skyhanni.data.model.GraphNode
import at.hannibal2.skyhanni.data.model.GraphNodeTag
import at.hannibal2.skyhanni.skyhannimodule.SkyHanniModule
import at.hannibal2.skyhanni.utils.ChatUtils
import at.hannibal2.skyhanni.utils.GraphUtils
import at.hannibal2.skyhanni.utils.LorenzVec.Companion.toLorenzVec
import at.hannibal2.skyhanni.utils.NumberUtil.roundTo
import at.hannibal2.skyhanni.utils.SkyBlockUtils
import at.hannibal2.skyhanni.utils.chat.TextHelper
import at.hannibal2.skyhanni.utils.chat.TextHelper.asComponent
import at.hannibal2.skyhanni.utils.chat.TextHelper.onClick
import at.hannibal2.skyhanni.utils.chat.TextHelper.send
import at.hannibal2.skyhanni.utils.collection.CollectionUtils.sorted
import at.hannibal2.skyhanni.utils.collection.CollectionUtils.takeIfAllNotNull
import at.hannibal2.skyhanni.utils.compat.hover
@SkyHanniModule
object NavigationHelper {
private val messageId = ChatUtils.getUniqueMessageId()
val allowedTags = listOf(
GraphNodeTag.NPC,
GraphNodeTag.AREA,
GraphNodeTag.SMALL_AREA,
GraphNodeTag.POI,
GraphNodeTag.SLAYER,
GraphNodeTag.GRIND_MOBS,
GraphNodeTag.GRIND_ORES,
GraphNodeTag.GRIND_CROPS,
GraphNodeTag.MINES_EMISSARY,
GraphNodeTag.CRIMSON_MINIBOSS,
)
private fun onCommand(args: Array<String>) {
if (args.size == 3) {
args.map { it.toDoubleOrNull() }.takeIfAllNotNull()?.let {
val location = it.toLorenzVec()
pathFind(location.add(-1, -1, -1), "Custom Goal", condition = { true })
with(location) {
ChatUtils.chat("Started Navigating to custom goal at §f$x $y $z", messageId = messageId)
}
return
}
}
SkyHanniMod.launchCoroutine("shnavigate command") {
doCommandAsync(args)
}
}
private fun doCommandAsync(args: Array<String>) {
val searchTerm = args.joinToString(" ").lowercase()
val distances = calculateDistances(searchTerm)
val locations = calculateNames(distances)
val goBack = {
onCommand(searchTerm.split(" ").toTypedArray())
IslandGraphs.stop()
}
val title = if (searchTerm.isBlank()) "SkyHanni Navigation Locations" else "SkyHanni Navigation Locations Matching: \"$searchTerm\""
TextHelper.displayPaginatedList(
title,
locations,
chatLineId = messageId,
emptyMessage = "No locations found.",
) { (name, node) ->
val distance = distances[node]!!.roundTo(1)
val component = "$name §e$distance".asComponent()
component.onClick {
node.pathFind(label = name, allowRerouting = true, condition = { true })
sendNavigateMessage(name, goBack)
}
val tag = node.tags.first { it in allowedTags }
val hoverText = "Name: $name\n§7Type: §r${tag.displayName}\n§7Distance: §e$distance blocks\n§eClick to start navigating!"
component.hover = hoverText.asComponent()
component
}
}
private fun sendNavigateMessage(name: String, goBack: () -> Unit) {
val componentText = "§7Navigating to §r$name".asComponent()
componentText.onClick(onClick = goBack)
componentText.hover = "§eClick to stop navigating and return to previous search".asComponent()
componentText.send(messageId)
}
private fun calculateNames(distances: Map<GraphNode, Double>): List<Pair<String, GraphNode>> {
val names = mutableMapOf<String, GraphNode>()
for (node in distances.sorted().keys) {
// hiding areas that are none
if (node.name == "no_area") continue
// no need to navigate to the current area
if (node.name == SkyBlockUtils.graphArea) continue
val tag = node.tags.first { it in allowedTags }
val name = "${node.name} §7(${tag.displayName}§7)"
if (name in names) continue
names[name] = node
}
return names.toList()
}
private fun calculateDistances(
searchTerm: String,
): Map<GraphNode, Double> {
val graph = IslandGraphs.currentIslandGraph ?: return emptyMap()
val closestNode = IslandGraphs.closestNode ?: return emptyMap()
val distances = mutableMapOf<GraphNode, Double>()
for (node in graph) {
val name = node.name ?: continue
val remainingTags = node.tags.filter { it in allowedTags }
if (remainingTags.isEmpty()) continue
if (name.lowercase().contains(searchTerm)) {
distances[node] = GraphUtils.findShortestDistance(closestNode, node)
}
if (remainingTags.size != 1) {
println("found node with invalid amount of tags: ${node.name} (${remainingTags.map { it.cleanName }}")
}
}
return distances
}
@HandleEvent
fun onCommandRegistration(event: CommandRegistrationEvent) {
event.registerBrigadier("shnavigate") {
description = "Using path finder to go to locations"
legacyCallbackArgs { onCommand(it) }
}
}
}
| 411 | 0.793413 | 1 | 0.793413 | game-dev | MEDIA | 0.311747 | game-dev | 0.922502 | 1 | 0.922502 |
snozbot/fungus | 2,281 | Assets/Fungus/Scripts/Commands/ShakeRotation.cs | // This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using UnityEngine.Serialization;
using System.Collections;
namespace Fungus
{
/// <summary>
/// Randomly shakes a GameObject's rotation by a diminishing amount over time.
/// </summary>
[CommandInfo("iTween",
"Shake Rotation",
"Randomly shakes a GameObject's rotation by a diminishing amount over time.")]
[AddComponentMenu("")]
[ExecuteInEditMode]
public class ShakeRotation : iTweenCommand
{
[Tooltip("A rotation offset in space the GameObject will animate to")]
[SerializeField] protected Vector3Data _amount;
[Tooltip("Apply the transformation in either the world coordinate or local cordinate system")]
[SerializeField] protected Space space = Space.Self;
#region Public members
public override void DoTween()
{
Hashtable tweenParams = new Hashtable();
tweenParams.Add("name", _tweenName.Value);
tweenParams.Add("amount", _amount.Value);
tweenParams.Add("space", space);
tweenParams.Add("time", _duration.Value);
tweenParams.Add("easetype", easeType);
tweenParams.Add("looptype", loopType);
tweenParams.Add("oncomplete", "OniTweenComplete");
tweenParams.Add("oncompletetarget", gameObject);
tweenParams.Add("oncompleteparams", this);
iTween.ShakeRotation(_targetObject.Value, tweenParams);
}
public override bool HasReference(Variable variable)
{
return _amount.vector3Ref == variable || base.HasReference(variable);
}
#endregion
#region Backwards compatibility
[HideInInspector] [FormerlySerializedAs("amount")] public Vector3 amountOLD;
protected override void OnEnable()
{
base.OnEnable();
if (amountOLD != default(Vector3))
{
_amount.Value = amountOLD;
amountOLD = default(Vector3);
}
}
#endregion
}
} | 411 | 0.83496 | 1 | 0.83496 | game-dev | MEDIA | 0.887506 | game-dev | 0.846606 | 1 | 0.846606 |
gilbutITbook/006772 | 6,022 | Unity 5.1/09/dokidoki_ganmodoki/Assets/Script/Level/NormalLevelSequence.cs | using UnityEngine;
using System.Collections;
public class NormalLevelSequence : SequenceBase {
public enum STEP {
NONE = -1,
IDLE = 0,
IN_ACTION,
TRANSPORT, // 방 이동 이벤트 중.
READY, // "レディ!" 표시
RESTART, // 쓰러진 후 재시작.
WAIT_FINISH,
FINISH,
NUM,
};
public Step<STEP> step = new Step<STEP>(STEP.NONE);
//===================================================================
// 디버그 창 생성 시에 호출.
public override void createDebugWindow(dbwin.Window window)
{
window.createButton("다음 플로어로")
.setOnPress(() =>
{
switch(this.step.get_current()) {
case STEP.IN_ACTION:
{
this.step.set_next(STEP.FINISH);
}
break;
}
});
}
protected bool is_floor_door_event = false; // 룸 이동 이벤트의 도어가 플로어 이동 도어인가?.
protected bool is_first_ready = true; // 레벨을 시작하고 최초의 STEP.READY
// 쓰러진 후 재시작 위치.
protected class RestartPoint {
public Vector3 position = Vector3.zero;
public float direction = 0.0f;
public DoorControl door = null;
}
protected RestartPoint restart_point = new RestartPoint();
protected float wait_counter = 0.0f;
//===================================================================
// 리벨 시작 시에 호출.
public override void start()
{
this.step.set_next(STEP.READY);
}
// 매 프레임 호출.
public override void execute()
{
// ---------------------------------------------------------------- //
// 다음 상태로 전환할지 체크.
switch(this.step.do_transition()) {
case STEP.IN_ACTION:
{
var player = PartyControl.get().getLocalPlayer();
if(player.step.get_current() == chrBehaviorLocal.STEP.WAIT_RESTART) {
// 체력이 0이 되면 재시작.
player.start();
player.control.cmdSetPositionAnon(this.restart_point.position);
player.control.cmdSetDirectionAnon(this.restart_point.direction);
if(this.restart_point.door != null) {
this.restart_point.door.beginWaitLeave();
}
this.step.set_next(STEP.RESTART);
} else {
// 방 이동 이벤트 시작?.
var ev = EventRoot.get().getCurrentEvent<TransportEvent>();
if(ev != null) {
DoorControl door = ev.getDoor();
if(door.type == DoorControl.TYPE.FLOOR) {
// 플로어 이동 도어일 때 .
this.is_floor_door_event = true;
ev.setEndAtHoleIn(true);
} else {
// 방 이동 도어일 때.
this.restart_point.door = door.connect_to;
this.is_floor_door_event = false;
}
this.step.set_next(STEP.TRANSPORT);
}
}
}
break;
// 방 이동 이벤트 중.
case STEP.TRANSPORT:
{
// 방 이동 이벤트가 끝나면 일반 모드로.
var ev = EventRoot.get().getCurrentEvent<TransportEvent>();
wait_counter += Time.deltaTime;
if(ev == null) {
if(this.is_floor_door_event) {
this.step.set_next(STEP.WAIT_FINISH);
} else {
this.step.set_next(STEP.READY);
wait_counter = 0.0f;
}
} else {
if(ev.step.get_current() == TransportEvent.STEP.READY) {
this.step.set_next(STEP.READY);
wait_counter = 0.0f;
}
}
}
break;
// 'レディ!' 표시.
// 쓰러졌을 때 재시작.
case STEP.READY:
case STEP.RESTART:
{
if(this.is_first_ready) {
if(this.step.get_time() > 1.0f) {
this.step.set_next(STEP.IN_ACTION);
this.is_first_ready = false;
}
} else {
var ev = EventRoot.get().getCurrentEvent<TransportEvent>();
if(ev == null) {
this.step.set_next(STEP.IN_ACTION);
}
}
}
break;
case STEP.WAIT_FINISH:
{
// 약긴 대기.
wait_counter += Time.deltaTime;
if (wait_counter > 3.0f) {
this.step.set_next(STEP.FINISH);
}
}
break;
}
// ---------------------------------------------------------------- //
// 상태 전환 시 초기화.
while(this.step.get_next() != STEP.NONE) {
switch(this.step.do_initialize()) {
case STEP.IN_ACTION:
{
Navi.get().dispatchPlayerMarker();
LevelControl.get().endStillEnemies(null, 0.0f);
}
break;
// 방 이동 이벤트 중.
case STEP.TRANSPORT:
{
var current_room = PartyControl.get().getCurrentRoom();
var next_room = PartyControl.get().getNextRoom();
// 다음 방에 적을 만든다.
// 방 이동 이벤트 조료 시에 갑자기 적이 나타나지 않게.
// 일짜김치 만들어 둔다.
LevelControl.get().createRoomEnemies(next_room);
LevelControl.get().beginStillEnemies(next_room);
LevelControl.get().beginStillEnemies(current_room);
}
break;
// 'レディ!표시.
case STEP.READY:
{
var current_room = PartyControl.get().getCurrentRoom();
var next_room = PartyControl.get().getNextRoom();
if(this.is_first_ready) {
LevelControl.get().createRoomEnemies(current_room);
LevelControl.get().beginStillEnemies(current_room);
LevelControl.get().onEnterRoom(current_room);
} else {
LevelControl.get().onLeaveRoom(current_room);
LevelControl.get().onEnterRoom(next_room);
}
// 'レディ!' 표시
Navi.get().dispatchYell(YELL_WORD.READY);
// 전에 있던 방의 적을 삭제..
if(next_room != current_room) {
LevelControl.get().deleteRoomEnemies(current_room);
}
ItemWindow.get().onRoomChanged(next_room);
this.restart_point.position = PartyControl.get().getLocalPlayer().control.getPosition();
this.restart_point.direction = PartyControl.get().getLocalPlayer().control.getDirection();
}
break;
// 쓰러진 후 재시작.
case STEP.RESTART:
{
// 'レディ!' 표시.
Navi.get().dispatchYell(YELL_WORD.READY);
this.restart_point.position = PartyControl.get().getLocalPlayer().control.getPosition();
this.restart_point.direction = PartyControl.get().getLocalPlayer().control.getDirection();
}
break;
case STEP.FINISH:
{
GameRoot.get().setNextScene("BossScene");
}
break;
}
}
// ---------------------------------------------------------------- //
// 각 상태에서의 실행 처리.
switch(this.step.do_execution(Time.deltaTime)) {
case STEP.IN_ACTION:
{
}
break;
}
// ---------------------------------------------------------------- //
}
}
| 411 | 0.855956 | 1 | 0.855956 | game-dev | MEDIA | 0.7264 | game-dev | 0.972209 | 1 | 0.972209 |
lzk228/space-axolotl-14 | 2,603 | Content.Shared/Placeable/ItemPlacerSystem.cs | using Content.Shared.Whitelist;
using Robust.Shared.Physics.Events;
using Robust.Shared.Physics.Systems;
namespace Content.Shared.Placeable;
/// <summary>
/// Tracks placed entities
/// Subscribe to <see cref="ItemPlacedEvent"/> or <see cref="ItemRemovedEvent"/> to do things when items or placed or removed.
/// </summary>
public sealed class ItemPlacerSystem : EntitySystem
{
[Dependency] private readonly CollisionWakeSystem _wake = default!;
[Dependency] private readonly PlaceableSurfaceSystem _placeableSurface = default!;
[Dependency] private readonly EntityWhitelistSystem _whitelistSystem = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<ItemPlacerComponent, StartCollideEvent>(OnStartCollide);
SubscribeLocalEvent<ItemPlacerComponent, EndCollideEvent>(OnEndCollide);
}
private void OnStartCollide(EntityUid uid, ItemPlacerComponent comp, ref StartCollideEvent args)
{
if (_whitelistSystem.IsWhitelistFail(comp.Whitelist, args.OtherEntity))
return;
if (TryComp<CollisionWakeComponent>(args.OtherEntity, out var wakeComp))
_wake.SetEnabled(args.OtherEntity, false, wakeComp);
var count = comp.PlacedEntities.Count;
if (comp.MaxEntities == 0 || count < comp.MaxEntities)
{
comp.PlacedEntities.Add(args.OtherEntity);
var ev = new ItemPlacedEvent(args.OtherEntity);
RaiseLocalEvent(uid, ref ev);
}
if (comp.MaxEntities > 0 && count >= (comp.MaxEntities - 1))
{
// Don't let any more items be placed if it's reached its limit.
_placeableSurface.SetPlaceable(uid, false);
}
}
private void OnEndCollide(EntityUid uid, ItemPlacerComponent comp, ref EndCollideEvent args)
{
if (TryComp<CollisionWakeComponent>(args.OtherEntity, out var wakeComp))
_wake.SetEnabled(args.OtherEntity, true, wakeComp);
comp.PlacedEntities.Remove(args.OtherEntity);
var ev = new ItemRemovedEvent(args.OtherEntity);
RaiseLocalEvent(uid, ref ev);
_placeableSurface.SetPlaceable(uid, true);
}
}
/// <summary>
/// Raised on the <see cref="ItemPlacer"/> when an item is placed and it is under the item limit.
/// </summary>
[ByRefEvent]
public readonly record struct ItemPlacedEvent(EntityUid OtherEntity);
/// <summary>
/// Raised on the <see cref="ItemPlacer"/> when an item is removed from it.
/// </summary>
[ByRefEvent]
public readonly record struct ItemRemovedEvent(EntityUid OtherEntity);
| 411 | 0.85948 | 1 | 0.85948 | game-dev | MEDIA | 0.635126 | game-dev | 0.866443 | 1 | 0.866443 |
AndriySvyryd/UnicornHack | 19,314 | src/UnicornHack.Web/Hubs/GameHub.cs | using System.Collections;
using System.Security.Cryptography;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.Extensions.Caching.Memory;
using UnicornHack.Data;
using UnicornHack.Data.Items;
using UnicornHack.Services;
using UnicornHack.Systems.Abilities;
using UnicornHack.Systems.Actors;
using UnicornHack.Utils;
using UnicornHack.Utils.MessagingECS;
namespace UnicornHack.Hubs;
public class GameHub : Hub
{
private readonly GameDbContext _dbContext;
private readonly GameServices _gameServices;
private readonly GameTransmissionProtocol _protocol;
public GameHub(GameDbContext dbContext, GameServices gameServices, GameTransmissionProtocol protocol)
{
_dbContext = dbContext;
_gameServices = gameServices;
_protocol = protocol;
}
public Task SendMessage(string message)
{
// TODO: Sanitize tags
return Clients.All.SendAsync("ReceiveMessage", Context.User!.Identity!.Name, message);
}
public List<object?> GetState(string playerName)
{
// TODO: Avoid using a DbContext
var player = FindPlayer(playerName) ?? CreatePlayer(playerName);
// TODO: Get a read lock or make serialization thread-safe
var gameState = _protocol.Serialize(player.Entity, EntityState.Added, null,
new SerializationContext(_dbContext, player.Entity, _gameServices));
Debug.Assert(_dbContext.ChangeTracker.Entries().All(e => e.State == EntityState.Unchanged));
return gameState;
}
public Task ShowDialog(string playerName, int intQueryType, int[] arguments)
{
var results = (GameQueryType)intQueryType == GameQueryType.Clear
? SerializationContext.DeletedBitArray
: QueryGame(playerName, intQueryType, arguments);
// TODO: only send to clients watching this player
return Clients.All.SendAsync("ReceiveUIRequest", results);
}
public List<object?> QueryGame(string playerName, int intQueryType, int[] arguments)
{
var queryType = (GameQueryType)intQueryType;
var player = FindPlayer(playerName);
if (player?.Entity.Being!.IsAlive != true)
{
return SerializationContext.DeletedBitArray;
}
var result = new List<object?> { null };
var setValues = new bool[12];
setValues[intQueryType + 1] = true;
result[0] = new BitArray(setValues);
var manager = player.Entity.Manager;
var context = new SerializationContext(_dbContext, player.Entity, _gameServices);
switch (queryType)
{
case GameQueryType.SlottableAbilities:
var slot = arguments[0];
setValues[intQueryType] = true;
result.Add(slot);
var abilities = new Dictionary<int, List<object?>>();
result.Add(abilities);
foreach (var slottableAbilityEntity in manager.AbilitiesToAffectableRelationship.GetDependents(
player.Entity))
{
var ability = slottableAbilityEntity.Ability!;
if (!ability.IsUsable)
{
continue;
}
if (slot == AbilitySlottingSystem.DefaultMeleeAttackSlot)
{
if (ability.Type == AbilityType.DefaultAttack
&& ((WieldingAbility)ability.Template!).ItemType == ItemType.WeaponMelee)
{
abilities.Add(ability.EntityId, AbilitySnapshot.Serialize(slottableAbilityEntity, null, context)!);
}
}
else if (slot == AbilitySlottingSystem.DefaultRangedAttackSlot)
{
if (ability.Type == AbilityType.DefaultAttack
&& ((WieldingAbility)ability.Template!).ItemType == ItemType.WeaponRanged)
{
abilities.Add(ability.EntityId, AbilitySnapshot.Serialize(slottableAbilityEntity, null, context)!);
}
}
else if ((ability.Activation & ActivationType.Slottable) != 0
&& ability.Type != AbilityType.DefaultAttack)
{
abilities.Add(ability.EntityId, AbilitySnapshot.Serialize(slottableAbilityEntity, null, context)!);
}
}
break;
case GameQueryType.PlayerAttributes:
result.Add(LevelActorSnapshot.SerializeAttributes(player.Entity, SenseType.Sight, context));
break;
case GameQueryType.PlayerInventory:
result.Add(PlayerSnapshot.SerializeItems(player.Entity, context));
break;
case GameQueryType.PlayerAdaptations:
result.Add(PlayerSnapshot.SerializeAdaptations(player.Entity, context));
break;
case GameQueryType.PlayerSkills:
result.Add(PlayerSnapshot.SerializeSkills(player.Entity, context));
break;
case GameQueryType.AbilityAttributes:
var abilityEntity = manager.FindEntity(arguments[0])!;
var ownerEntity = abilityEntity.Ability!.OwnerEntity!;
var activatorEntity = abilityEntity.Ability!.OwnerEntity!.HasComponent(EntityComponent.Item)
? player.Entity!
: ownerEntity;
result.Add(AbilitySnapshot.SerializeAttributes(abilityEntity, activatorEntity, context));
break;
case GameQueryType.ActorAttributes:
{
var actorKnowledge = manager.FindEntity(arguments[0])?.Knowledge;
result.Add(LevelActorSnapshot.SerializeAttributes(
actorKnowledge?.KnownEntity, actorKnowledge?.SensedType ?? SenseType.None, context));
break;
}
case GameQueryType.ItemAttributes:
var itemEntity = manager.FindEntity(arguments[0]);
var item = itemEntity?.Item;
var itemKnowledge = itemEntity?.Knowledge;
if (item != null)
{
result.Add(InventoryItemSnapshot.SerializeAttributes(itemEntity, SenseType.Sight, context));
}
else
{
result.Add(InventoryItemSnapshot.SerializeAttributes(
itemKnowledge?.KnownEntity, itemKnowledge?.SensedType ?? SenseType.None, context));
}
break;
// TODO: Handle PostGameStatistics
default:
throw new InvalidOperationException($"Query type {intQueryType} not supported");
}
return result;
}
public string QueryStaticDescription(string topicId, int category)
=> _gameServices.Language.GetDescription(topicId, (DescriptionCategory)category);
public async Task PerformAction(string playerName, int intAction, int? target, int? target2)
{
var action = (ActorAction?)intAction;
var currentPlayer = FindPlayer(playerName);
if (currentPlayer == null)
{
currentPlayer = CreatePlayer(playerName);
action = null;
target = null;
target2 = null;
}
else
{
if (currentPlayer.Game.CurrentTick != currentPlayer.NextActionTick)
{
Debug.Assert(false, "Action sent out of turn");
// TODO: Log action sent out of turn
return;
}
if (_dbContext.Snapshot == null)
{
_dbContext.Snapshot = new GameSnapshot();
}
_dbContext.Snapshot.CaptureState(_dbContext, _gameServices);
}
// TODO: Get a lock
currentPlayer.NextAction = action;
currentPlayer.NextActionTarget = target;
currentPlayer.NextActionTarget2 = target2;
Turn(currentPlayer);
// TODO: Log turn ended prematurely
Debug.Assert(currentPlayer.Game.CurrentTick == currentPlayer.NextActionTick, "Turn ended prematurely");
_dbContext.ChangeTracker.AutoDetectChangesEnabled = false;
foreach (var playerEntity in currentPlayer.Game.Manager.Players)
{
var newPlayer = action == null;
var serializedPlayer = _protocol.Serialize(
playerEntity, newPlayer ? EntityState.Added : EntityState.Modified, _dbContext.Snapshot,
new SerializationContext(_dbContext, playerEntity, _gameServices));
// TODO: only send to clients watching this player
await Clients.All.SendAsync("ReceiveState", serializedPlayer).ConfigureAwait(false);
if (!playerEntity.Being!.IsAlive)
{
var results = new List<object> { GameQueryType.PostGameStatistics, new List<object>() };
// TODO: only send to clients watching this player
await Clients.All.SendAsync("ReceiveUIRequest", results).ConfigureAwait(false);
}
}
_dbContext.ChangeTracker.AutoDetectChangesEnabled = true;
_dbContext.ChangeTracker.AcceptAllChanges();
}
private void Turn(PlayerComponent currentPlayer)
{
var manager = currentPlayer.Game.Manager;
foreach (var levelEntity in manager.Levels)
{
var level = levelEntity.Level!;
if (level.TerrainChanges != null)
{
level.TerrainChanges.Clear();
}
else
{
level.TerrainChanges = new Dictionary<short, byte>();
}
if (level.KnownTerrainChanges != null)
{
level.KnownTerrainChanges.Clear();
}
else
{
level.KnownTerrainChanges = new Dictionary<short, byte>();
}
if (level.WallNeighborsChanges != null)
{
level.WallNeighborsChanges.Clear();
}
else
{
level.WallNeighborsChanges = new Dictionary<short, byte>();
}
if (_dbContext.Snapshot?.LevelSnapshots.ContainsKey(levelEntity.Id) != true)
{
level.VisibleTerrainSnapshot = null;
}
level.VisibleNeighborsChanged = false;
}
currentPlayer.Game.ActingPlayer = null;
manager.TimeSystem.AdvanceToNextPlayerTurn(manager);
//TODO: If all players are dead end the game
_dbContext.ChangeTracker.AutoDetectChangesEnabled = false;
foreach (var levelEntity in manager.Levels)
{
var level = levelEntity.Level!;
var levelEntry = _dbContext.Entry(level);
if (levelEntry.State == EntityState.Added
|| level.Width == 0)
{
continue;
}
if (level.TerrainChanges == null
|| level.TerrainChanges.Count > 0)
{
levelEntry.Property(l => l.Terrain).IsModified = true;
}
if (level.KnownTerrainChanges == null
|| level.KnownTerrainChanges.Count > 0)
{
levelEntry.Property(l => l.KnownTerrain).IsModified = true;
}
if (level.WallNeighborsChanges == null
|| level.WallNeighborsChanges.Count > 0)
{
levelEntry.Property(l => l.WallNeighbors).IsModified = true;
}
// TODO: Move VisibleTerrainSnapshot and VisibleTerrainChanges to the snapshot
if (level.VisibleTerrainChanges == null)
{
level.VisibleTerrainChanges = new Dictionary<short, byte>();
}
else
{
level.VisibleTerrainChanges.Clear();
}
if (level.VisibleTerrainSnapshot != null)
{
var tileCount = level.TileCount;
for (short i = 0; i < tileCount; i++)
{
var newValue = level.VisibleTerrain[i];
if (newValue != level.VisibleTerrainSnapshot[i])
{
level.VisibleTerrainChanges.Add(i, newValue);
}
}
}
if (level.VisibleTerrainSnapshot == null
|| level.VisibleTerrainChanges.Count > 0)
{
levelEntry.Property(l => l.VisibleTerrain).IsModified = true;
}
if (level.VisibleNeighborsChanged)
{
levelEntry.Property(l => l.VisibleNeighbors).IsModified = true;
}
}
_dbContext.ChangeTracker.AutoDetectChangesEnabled = true;
// AcceptChanges is delayed to allow using this state in serialization
_dbContext.SaveChanges(acceptAllChangesOnSuccess: false);
}
private PlayerComponent CreatePlayer(string name)
{
uint seed;
using (var rng = RandomNumberGenerator.Create())
{
var rngData = new byte[4];
rng.GetBytes(rngData);
seed = (uint)(rngData[0] | rngData[1] << 8 | rngData[2] << 16 | rngData[3] << 24);
}
var game = new Game { InitialSeed = seed, Random = new SimpleRandom { Seed = seed } };
Initialize(game);
_dbContext.Games.Add(game);
_dbContext.SaveChanges();
var manager = game.Manager;
var surfaceBranch = Branch.Loader.Find("surface")!.Instantiate(game);
var surfaceLevel = LevelGenerator.CreateEmpty(surfaceBranch, depth: 1, seed, manager);
LevelGenerator.EnsureGenerated(surfaceLevel);
var initialLevelConnection = surfaceLevel.Connections.Single().Value.Connection!;
var initialLevelEntity = initialLevelConnection.TargetLevelEntity;
LevelGenerator.EnsureGenerated(initialLevelEntity.Level!);
// TODO: Set correct sex
var playerEntity = PlayerRace.InstantiatePlayer(
name, Sex.Male, initialLevelEntity.Level!, initialLevelConnection.TargetLevelCell!.Value);
manager.Queue.ProcessQueue(manager);
ItemData.FlaskOfHealing.Instantiate(playerEntity);
ItemData.MailArmor.Instantiate(playerEntity);
ItemData.LongSword.Instantiate(playerEntity);
ItemData.Dagger.Instantiate(playerEntity);
ItemData.Shortbow.Instantiate(playerEntity);
ItemData.ThrowingKnives.Instantiate(playerEntity);
ItemData.FireStaff.Instantiate(playerEntity);
ItemData.FreezingFocus.Instantiate(playerEntity);
ItemData.FieryAegis.Instantiate(playerEntity);
ItemData.PotionOfOgreness.Instantiate(playerEntity);
ItemData.PotionOfElfness.Instantiate(playerEntity);
ItemData.PotionOfDwarfness.Instantiate(playerEntity);
ItemData.SkillbookOfConjuration.Instantiate(playerEntity);
manager.Queue.ProcessQueue(manager);
manager.LoggingSystem.WriteLog(game.Services.Language.Welcome(playerEntity), playerEntity, manager);
Turn(playerEntity.Player!);
_dbContext.ChangeTracker.AcceptAllChanges();
_gameServices.SharedCache.Set(game, game,
new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromHours(1)));
return playerEntity.Player!;
}
private PlayerComponent? FindPlayer(string name)
{
var loadedGame = _dbContext.PlayerComponents.Where(playerComponent => playerComponent.ProperName == name)
.Join(_dbContext.Games,
playerComponent => playerComponent.GameId, game => game.Id,
(_, game) => game)
.AsNoTracking()
.FirstOrDefault();
if (loadedGame == null)
{
return null;
}
// TODO: Perf: Cache the DbContext as well to avoid reattaching
if (_gameServices.SharedCache.TryGetValue(loadedGame, out var cachedGameObject)
&& cachedGameObject is Game cachedGame
&& cachedGame.CurrentTick == loadedGame.CurrentTick)
{
// TODO: Unload old levels
loadedGame = cachedGame;
InitializeContext(loadedGame);
_dbContext.ChangeTracker.AutoDetectChangesEnabled = false;
EntityAttacher.Attach(loadedGame, _dbContext);
_dbContext.ChangeTracker.AutoDetectChangesEnabled = true;
}
else
{
Initialize(loadedGame);
EntityAttacher.Attach(loadedGame, _dbContext);
loadedGame = _dbContext.LoadGame(loadedGame.Id);
_gameServices.SharedCache.Set(loadedGame, loadedGame,
new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromHours(1)));
}
// TODO: Preserve replays
if (!_dbContext.PlayerComponents.Local.Any(pc => pc.Entity.Being!.IsAlive))
{
_dbContext.Clean(loadedGame);
_dbContext.ChangeTracker.Tracked -= OnTracked;
_dbContext.ChangeTracker.StateChanged -= OnStateChanged;
_gameServices.SharedCache.Remove(loadedGame);
return null;
}
return _dbContext.PlayerComponents.Local.First(p
=> p.ProperName.Equals(name, StringComparison.OrdinalIgnoreCase));
}
private void Initialize(Game game)
{
game.Services = _gameServices;
if (game.Manager == null!)
{
var queue = new SequentialMessageQueue<GameManager>();
var gameManager = new GameManager { Game = game };
gameManager.Initialize(queue);
game.Manager = gameManager;
}
InitializeContext(game);
_dbContext.Snapshot = null;
}
private void InitializeContext(Game game)
{
if (game.Repository != null
&& game.Repository is DbContext oldContext)
{
oldContext.ChangeTracker.Tracked -= OnTracked;
oldContext.ChangeTracker.StateChanged -= OnStateChanged;
}
game.Repository = _dbContext;
_dbContext.Manager = game.Manager;
_dbContext.ChangeTracker.Tracked += OnTracked;
_dbContext.ChangeTracker.StateChanged += OnStateChanged;
}
private void OnTracked(object? sender, EntityTrackedEventArgs args)
{
var entry = args.Entry;
if (entry.State == EntityState.Added
&& entry.Entity is ITrackable trackable)
{
trackable.StartTracking(sender!);
}
if (args.FromQuery
&& entry.Entity is GameEntity entity)
{
((GameDbContext)entry.Context).Manager.AddEntity(entity);
}
}
private void OnStateChanged(object? sender, EntityStateChangedEventArgs args)
{
if (args.NewState == EntityState.Detached && args.Entry.Entity is ITrackable trackable)
{
trackable.StopTracking(sender!);
}
}
}
| 411 | 0.933756 | 1 | 0.933756 | game-dev | MEDIA | 0.6342 | game-dev | 0.904385 | 1 | 0.904385 |
sinkillerj/ProjectE | 3,855 | src/api/java/moze_intel/projecte/api/data/WorldTransmutationProvider.java | package moze_intel.projecte.api.data;
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import javax.annotation.ParametersAreNonnullByDefault;
import moze_intel.projecte.api.world_transmutation.WorldTransmutationFile;
import net.minecraft.MethodsReturnNonnullByDefault;
import net.minecraft.core.HolderLookup;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataProvider;
import net.minecraft.data.PackOutput;
import net.minecraft.data.PackOutput.PathProvider;
import net.minecraft.data.PackOutput.Target;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.neoforged.neoforge.common.conditions.ICondition;
import net.neoforged.neoforge.common.conditions.WithConditions;
/**
* Base Data Generator Provider class for use in creating world transmutations json data files that ProjectE will read from the data pack.
*/
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public abstract class WorldTransmutationProvider implements DataProvider {
private final Map<ResourceLocation, ConditionalBuilder> worldTransmutations = new LinkedHashMap<>();
private final CompletableFuture<HolderLookup.Provider> lookupProvider;
private final PathProvider outputProvider;
private final String modid;
private final Set<BlockState> seenBlockStates = new ReferenceOpenHashSet<>();
private final Set<Block> seenBlocks = new ReferenceOpenHashSet<>();
protected WorldTransmutationProvider(PackOutput output, CompletableFuture<HolderLookup.Provider> lookupProvider, String modid) {
this.outputProvider = output.createPathProvider(Target.DATA_PACK, "pe_world_transmutations");
this.lookupProvider = lookupProvider;
this.modid = modid;
}
@Override
public final String getName() {
return "World Transmutations: " + modid;
}
@Override
public CompletableFuture<?> run(CachedOutput output) {
return this.lookupProvider.thenApply(registries -> {
worldTransmutations.clear();
addWorldTransmutations(registries);
return registries;
}).thenCompose(registries -> CompletableFuture.allOf(worldTransmutations.entrySet().stream()
.map(entry -> DataProvider.saveStable(output, registries, WorldTransmutationFile.CONDITIONAL_CODEC,
entry.getValue().build(), outputProvider.json(entry.getKey())))
.toArray(CompletableFuture[]::new)
));
}
/**
* Implement this method to add any world transmutation files.
*
* @param registries Access to holder lookups.
*/
protected abstract void addWorldTransmutations(HolderLookup.Provider registries);
/**
* Creates and adds a world transmutation builder with the file located by data/modid/pe_world_transmutations/namespace.json
*
* @param id modid:namespace
* @param conditions Any conditions necessary to have the file load.
*
* @return Builder
*/
protected WorldTransmutationBuilder createTransmutationBuilder(ResourceLocation id, ICondition... conditions) {
Objects.requireNonNull(id, "World Transmutation Builder ID cannot be null.");
if (worldTransmutations.containsKey(id)) {
throw new RuntimeException("World transmutation file '" + id + "' has already been registered.");
}
WorldTransmutationBuilder builder = new WorldTransmutationBuilder(seenBlocks, seenBlockStates);
worldTransmutations.put(id, new ConditionalBuilder(builder, conditions));
return builder;
}
private record ConditionalBuilder(WorldTransmutationBuilder builder, ICondition... conditions) {
public Optional<WithConditions<WorldTransmutationFile>> build() {
return Optional.of(new WithConditions<>(builder.build(), conditions));
}
}
} | 411 | 0.828485 | 1 | 0.828485 | game-dev | MEDIA | 0.902665 | game-dev | 0.876775 | 1 | 0.876775 |
Suprcode/Crystal | 19,713 | Server/MirObjects/Monsters/HornedCommander.cs | using System.Drawing;
using Server.MirDatabase;
using Server.MirEnvir;
using S = ServerPackets;
namespace Server.MirObjects.Monsters
{
/// <summary>
/// Attack1 - Basic melee attack
/// Attack2 - Basic melee attack alt
/// Attack3 - Charge up then Spin attack (between 5 and 10 damage multiplier) twice
/// Attack4 - Charge up then AOE rock fall (between 5 and 10 damage multiplier)
/// Attack5 - Immunity shield, Summons slave (Under 10% HP)
/// AttackRange1 - Teleport
/// AttackRange2 - Hammer smash AOE in front
/// AttackRange3 - Summon rock spikes (Between 10% - 30% HP)
/// Summons Rock Slaves
/// </summary>
public class HornedCommander : MonsterObject
{
private bool _StartAdvanced;
private bool _Immune;
private Point _MapCentre
{
get
{
if (CurrentMap == null) return Point.Empty;
//Should be spawned on "HY01_morae_chon". Change me to correct centre if its spawned on another map.
return new Point(26, 32);
}
}
//Phase 0
private readonly byte _BoulderHealthPercent = 80;
private bool _CalledBoulders, _StartedBoulderWalk;
//Phase 1
private readonly byte _RockHealthPercent = 50;
private bool _CalledRockSpikes;
private long _RockSpikeTime;
private readonly Point[,] _RockSpikeArea = new Point[7, 7];
private readonly List<SpellObject> _RockSpikeEffects = new List<SpellObject>();
//Phase 2
private readonly byte _ShieldHealthPercent = 10;
private bool _CalledShield;
private readonly byte _ShieldSeconds = 20;
protected internal HornedCommander(MonsterInfo info)
: base(info)
{
}
public override bool IsAttackTarget(MonsterObject attacker)
{
return !_Immune && base.IsAttackTarget(attacker);
}
public override bool IsAttackTarget(HumanObject attacker)
{
return !_Immune && base.IsAttackTarget(attacker);
}
protected override void ProcessAI()
{
if ((HealthPercent < _BoulderHealthPercent || _StartedBoulderWalk) && !_CalledBoulders)
{
_StartedBoulderWalk = true;
SpawnBoulder();
}
if (_Immune) return;
if (HealthPercent < _ShieldHealthPercent && !_CalledShield)
{
KillRockSpikes();
_CalledShield = true;
_Immune = true;
Broadcast(new S.ObjectAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, Type = 4, Level = _ShieldSeconds });
AddBuff(BuffType.HornedCommanderShield, this, Settings.Second * _ShieldSeconds, new Stats());
SpawnSlave();
return;
}
if (HealthPercent < _RockHealthPercent && HealthPercent >= _ShieldHealthPercent)
{
if (!_CalledRockSpikes)
{
SetupRockSpike();
_CalledRockSpikes = true;
Broadcast(new S.ObjectRangeAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, Type = 2 });
}
}
if (_CalledRockSpikes && Envir.Time > _RockSpikeTime)
{
var spawned = SpawnRockSpikes();
_RockSpikeTime = Envir.Time + 5000;
if (!spawned)
{
_RockSpikeTime = long.MaxValue;
}
}
if (HealthPercent < 100 && !_StartAdvanced)
{
_StartAdvanced = true;
}
else if (HealthPercent == 100 && _StartAdvanced)
{
Reset();
}
base.ProcessAI();
}
private void Reset()
{
_StartAdvanced = false;
_StartedBoulderWalk = false;
_CalledBoulders = false;
_CalledRockSpikes = false;
_CalledShield = false;
_RockSpikeTime = 0;
KillRockSpikes();
KillSlaves();
}
protected override void ProcessBuffEnd(Buff buff)
{
if (buff.Type == BuffType.HornedCommanderShield)
{
_Immune = false;
AttackTime = Envir.Time + AttackSpeed;
ActionTime = Envir.Time + 300;
}
}
protected override void ProcessTarget()
{
if (Target == null || !CanAttack) return;
if (InAttackRange())
{
Attack();
if (Target != null && Target.Dead)
{
FindTarget();
}
return;
}
if (Envir.Time < ShockTime)
{
Target = null;
return;
}
MoveTo(Target.CurrentLocation);
}
protected override void Attack()
{
if (!Target.IsAttackTarget(this))
{
Target = null;
return;
}
AttackTime = Envir.Time + AttackSpeed;
ShockTime = 0;
Direction = Functions.DirectionFromPoint(CurrentLocation, Target.CurrentLocation);
//Charge-Up AOE Rock Fall
if (_StartAdvanced && Envir.Random.Next(20) == 0)
{
byte rockFallLoops = (byte)Envir.Random.Next(5, 10);
int rockFallDuration = rockFallLoops * 500;
_Immune = true;
ActionTime = Envir.Time + (rockFallDuration) + 500;
AttackTime = Envir.Time + (rockFallDuration) + 500 + AttackSpeed;
Broadcast(new S.ObjectAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, Type = 3, Level = rockFallLoops });
var front = Functions.PointMove(CurrentLocation, Direction, 2);
MassSpawnRockFall(front, rockFallDuration);
int damage = GetAttackPower(Stats[Stat.MinDC], Stats[Stat.MaxDC]) * rockFallLoops;
DelayedAction action = new DelayedAction(DelayedType.RangeDamage, Envir.Time + (rockFallDuration) + 500, Target, damage, DefenceType.AC, 5);
ActionList.Add(action);
return;
}
//Charge-Up Spin Hit
if (_StartAdvanced && Envir.Random.Next(15) == 0)
{
byte spinLoops = (byte)Envir.Random.Next(5, 10);
int spinDuration = spinLoops * 700;
_Immune = true;
ActionTime = Envir.Time + spinDuration + 1500;
AttackTime = Envir.Time + spinDuration + 1500 + AttackSpeed;
Broadcast(new S.ObjectAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, Type = 2, Level = spinLoops });
int damage = GetAttackPower(Stats[Stat.MinDC], Stats[Stat.MaxDC]) * spinLoops;
DelayedAction action = new DelayedAction(DelayedType.Damage, Envir.Time + spinDuration + 500, Target, damage, DefenceType.AC, true);
ActionList.Add(action);
action = new DelayedAction(DelayedType.Damage, Envir.Time + spinDuration + 1000, Target, damage, DefenceType.AC, true);
ActionList.Add(action);
return;
}
//Hammer Smash
if (_StartAdvanced && Envir.Random.Next(10) == 0)
{
Broadcast(new S.ObjectRangeAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, Type = 1 });
int damage = GetAttackPower(Stats[Stat.MinDC], Stats[Stat.MaxDC]);
if (damage == 0) return;
DelayedAction action = new DelayedAction(DelayedType.RangeDamage, Envir.Time + 300, Target, damage, DefenceType.AC, 3);
ActionList.Add(action);
return;
}
//Teleport
if (_StartAdvanced && Envir.Random.Next(10) == 0)
{
Broadcast(new S.ObjectRangeAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, Type = 0 });
DelayedAction action = new DelayedAction(DelayedType.RangeDamage, Envir.Time + 300);
ActionList.Add(action);
return;
}
//Normal Attacks
if (Envir.Random.Next(2) == 0)
{
Broadcast(new S.ObjectAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, Type = 0 });
int damage = GetAttackPower(Stats[Stat.MinDC], Stats[Stat.MaxDC]);
if (damage == 0) return;
DelayedAction action = new DelayedAction(DelayedType.Damage, Envir.Time + 500, Target, damage, DefenceType.ACAgility, false);
ActionList.Add(action);
}
else
{
Broadcast(new S.ObjectAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, Type = 1 });
int damage = GetAttackPower(Stats[Stat.MinDC], Stats[Stat.MaxDC]);
if (damage == 0) return;
DelayedAction action = new DelayedAction(DelayedType.Damage, Envir.Time + 500, Target, damage, DefenceType.ACAgility, false);
ActionList.Add(action);
}
}
protected override void CompleteAttack(IList<object> data)
{
_Immune = false;
if (data.Count > 0)
{
MapObject target = (MapObject)data[0];
int damage = (int)data[1];
DefenceType defence = (DefenceType)data[2];
bool aoe = (bool)data[3];
if (target == null || !target.IsAttackTarget(this) || target.CurrentMap != CurrentMap || target.Node == null) return;
if (aoe)
{
var targets = FindAllTargets(3, CurrentLocation, false);
for (int i = 0; i < targets.Count; i++)
{
targets[i].Attacked(this, damage, defence);
}
}
else
{
target.Attacked(this, damage, defence);
}
}
}
protected override void CompleteRangeAttack(IList<object> data)
{
_Immune = false;
if (data.Count > 0)
{
MapObject target = (MapObject)data[0];
int damage = (int)data[1];
DefenceType defence = (DefenceType)data[2];
int aoeSize = (int)data[3];
if (target == null || !target.IsAttackTarget(this) || target.CurrentMap != CurrentMap || target.Node == null) return;
var front = Functions.PointMove(CurrentLocation, Direction, 2);
var targets = FindAllTargets(aoeSize, front, false);
for (int i = 0; i < targets.Count; i++)
{
targets[i].Attacked(this, damage, defence);
}
}
else
{
TeleportRandom(10, 10);
Target = null;
}
}
public override bool TeleportRandom(int attempts, int distance, Map temp = null)
{
for (int i = 0; i < attempts; i++)
{
Point location;
if (distance <= 0)
location = new Point(Envir.Random.Next(CurrentMap.Width), Envir.Random.Next(CurrentMap.Height));
else
location = new Point(CurrentLocation.X + Envir.Random.Next(-distance, distance + 1),
CurrentLocation.Y + Envir.Random.Next(-distance, distance + 1));
if (Teleport(CurrentMap, location, true, 10)) return true;
}
return false;
}
private void MassSpawnRockFall(Point centerPoint, int duration)
{
int range = 15;
for (int x = -range; x < range; x+=10)
{
for (int y = -range; y < range; y += 10)
{
var location = new Point(centerPoint.X + x, centerPoint.Y + y);
SpawnRockFall(location, Envir.Random.Next(0, 200), duration);
}
}
}
private void SpawnRockFall(Point location, int offset, int duration)
{
if (Dead) return;
for (int y = location.Y - 10; y <= location.Y + 10; y++)
{
if (y < 0) continue;
if (y >= CurrentMap.Height) break;
for (int x = location.X - 10; x <= location.X + 10; x++)
{
if (x < 0) continue;
if (x >= CurrentMap.Width) break;
if (x == CurrentLocation.X && y == CurrentLocation.Y) continue;
var cell = CurrentMap.GetCell(x, y);
if (!cell.Valid) continue;
int damage = GetAttackPower(Stats[Stat.MinMC], Stats[Stat.MinMC]);
var start = 500 + offset;
SpellObject ob = new SpellObject
{
Spell = Spell.HornedCommanderRockFall,
Value = damage,
ExpireTime = Envir.Time + duration + start,
TickSpeed = 2000,
CurrentLocation = new Point(x, y),
CastLocation = location,
Show = location.X == x && location.Y == y,
CurrentMap = CurrentMap,
Caster = this
};
DelayedAction action = new DelayedAction(DelayedType.Spawn, Envir.Time + start, ob);
CurrentMap.ActionList.Add(action);
}
}
}
private void SetupRockSpike()
{
var xLength = _RockSpikeArea.GetLength(0);
var yLength = _RockSpikeArea.GetLength(1);
var midX = ((int)Math.Ceiling((decimal)xLength / 2) - 1) * -1;
var midY = ((int)Math.Ceiling((decimal)yLength / 2) - 1) * -1;
var actualX = midX;
var actualY = midY;
for (int x = 0; x < xLength; x++)
{
for (int y = 0; y < yLength; y++)
{
var point = new Point(_MapCentre.X + (actualX * 5), _MapCentre.Y + (actualY * 5));
_RockSpikeArea[x, y] = point;
actualY++;
}
actualY = midY;
actualX++;
}
}
private bool SpawnRockSpikes()
{
var spawned = false;
var xLength = _RockSpikeArea.GetLength(0);
var yLength = _RockSpikeArea.GetLength(1);
for (int x = 0; x < xLength; x++)
{
for (int y = 0; y < yLength; y++)
{
var point = _RockSpikeArea[x, y];
var existing = _RockSpikeEffects.Any(x => x.CastLocation == point);
if (existing) continue;
spawned = SpawnRockSpike(point);
if (spawned)
{
return true;
}
}
if (spawned)
{
return true;
}
}
return false;
}
private bool SpawnRockSpike(Point location)
{
var spawned = false;
for (int y = location.Y - 2; y <= location.Y + 2; y++)
{
if (y < 0) continue;
if (y >= CurrentMap.Height) break;
for (int x = location.X - 2; x <= location.X + 2; x++)
{
if (x < 0) continue;
if (x >= CurrentMap.Width) break;
var cell = CurrentMap.GetCell(x, y);
if (!cell.Valid) continue;
if (location.X == x && location.Y == y)
{
spawned = true;
}
int damage = GetAttackPower(Stats[Stat.MinMC], Stats[Stat.MinMC]);
var start = 500;
SpellObject ob = new SpellObject
{
Spell = Spell.HornedCommanderRockSpike,
Value = damage,
ExpireTime = Envir.Time + start + (Settings.Minute * 10),
TickSpeed = 1000,
CurrentLocation = new Point(x, y),
CastLocation = location,
Show = location.X == x && location.Y == y,
CurrentMap = CurrentMap,
Caster = this
};
DelayedAction action = new DelayedAction(DelayedType.Spawn, Envir.Time + start, ob);
CurrentMap.ActionList.Add(action);
_RockSpikeEffects.Add(ob);
}
}
return spawned;
}
private void SpawnBoulder()
{
if (Functions.InRange(CurrentLocation, _MapCentre, 20))
{
Teleport(CurrentMap, _MapCentre, true, 10);
}
_CalledBoulders = true;
for (int i = 0; i < 8; i++)
{
var mob = GetMonster(Envir.GetMonsterInfo(Settings.HornedCommanderBombMob));
var odd = i % 2 != 0;
var point = Functions.PointMove(CurrentLocation, (MirDirection)i, odd ? 7 : 9);
if (mob == null) continue;
mob.Direction = Functions.DirectionFromPoint(point, CurrentLocation);
if (mob.Spawn(CurrentMap, point))
{
mob.Target = Target;
mob.ActionTime = Envir.Time;
SlaveList.Add(mob);
}
}
}
private void SpawnSlave()
{
ActionTime = Envir.Time + 300;
AttackTime = Envir.Time + AttackSpeed;
var mob = GetMonster(Envir.GetMonsterInfo(Settings.HornedCommanderMob));
if (mob == null) return;
if (!mob.Spawn(CurrentMap, Front))
mob.Spawn(CurrentMap, CurrentLocation);
mob.Target = Target;
mob.ActionTime = Envir.Time;
SlaveList.Add(mob);
}
private void KillRockSpikes()
{
_RockSpikeTime = long.MaxValue;
foreach (var effect in _RockSpikeEffects)
{
effect.ExpireTime = Envir.Time;
}
_RockSpikeEffects.Clear();
}
private void KillSlaves()
{
//Kill Minions
for (int i = SlaveList.Count - 1; i >= 0; i--)
{
if (!SlaveList[i].Dead && SlaveList[i].Node != null)
{
SlaveList[i].Die();
}
}
}
public override void Die()
{
base.Die();
KillRockSpikes();
KillSlaves();
}
}
}
| 411 | 0.986056 | 1 | 0.986056 | game-dev | MEDIA | 0.973719 | game-dev | 0.989093 | 1 | 0.989093 |
NH07HACKS/farlight84-cheat- | 1,631 | ImGui DirectX 11 Kiero Hook/CppSDK/SDK/UI_HUD_Notice_CountDown_functions.cpp | #pragma once
/*
* SDK generated by Dumper-7
*
* https://github.com/Encryqed/Dumper-7
*/
// Package: UI_HUD_Notice_CountDown
#include "Basic.hpp"
#include "UI_HUD_Notice_CountDown_classes.hpp"
#include "UI_HUD_Notice_CountDown_parameters.hpp"
namespace SDK
{
// Function UI_HUD_Notice_CountDown.UI_HUD_Notice_CountDown_C.EnableBattleController
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// bool Show (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void UUI_HUD_Notice_CountDown_C::EnableBattleController(bool Show)
{
static class UFunction* Func = nullptr;
if (Func == nullptr)
Func = Class->GetFunction("UI_HUD_Notice_CountDown_C", "EnableBattleController");
Params::UI_HUD_Notice_CountDown_C_EnableBattleController Parms{};
Parms.Show = Show;
UObject::ProcessEvent(Func, &Parms);
}
// Function UI_HUD_Notice_CountDown.UI_HUD_Notice_CountDown_C.GetCDAnim
// (Event, Public, HasOutParams, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UWidgetAnimation* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UWidgetAnimation* UUI_HUD_Notice_CountDown_C::GetCDAnim()
{
static class UFunction* Func = nullptr;
if (Func == nullptr)
Func = Class->GetFunction("UI_HUD_Notice_CountDown_C", "GetCDAnim");
Params::UI_HUD_Notice_CountDown_C_GetCDAnim Parms{};
UObject::ProcessEvent(Func, &Parms);
return Parms.ReturnValue;
}
}
| 411 | 0.729396 | 1 | 0.729396 | game-dev | MEDIA | 0.917531 | game-dev | 0.603892 | 1 | 0.603892 |
ForestryMC/ForestryMC | 2,711 | src/main/java/forestry/plugins/CompatPlugin.java | package forestry.plugins;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import forestry.api.storage.BackpackManager;
import forestry.core.utils.Log;
import forestry.core.utils.ModUtil;
import forestry.modules.BlankForestryModule;
public abstract class CompatPlugin extends BlankForestryModule {
protected final String modName;
protected final String modID;
public CompatPlugin(String modName, String modID) {
this.modName = modName;
this.modID = modID;
}
@Override
public final boolean isAvailable() {
return ModUtil.isModLoaded(modID);
}
@Override
public final String getFailMessage() {
return modName + " not found";
}
@Nullable
protected ItemStack getItemStack(@Nonnull String itemName) {
return getItemStack(itemName, 0);
}
@Nullable
protected ItemStack getItemStack(@Nonnull String itemName, int meta) {
Item item = getItem(itemName);
if (item == null) {
return null;
}
return new ItemStack(item, 1, meta);
}
@Nullable
protected Block getBlock(@Nonnull String blockName) {
ResourceLocation key = new ResourceLocation(modID, blockName);
if (ForgeRegistries.BLOCKS.containsKey(key)) {
return ForgeRegistries.BLOCKS.getValue(key);
}
Log.debug("Could not find block {}", key);
return null;
}
@Nullable
protected Item getItem(String itemName) {
ResourceLocation key = new ResourceLocation(modID, itemName);
if (ForgeRegistries.ITEMS.containsKey(key)) {
return ForgeRegistries.ITEMS.getValue(key);
}
Log.debug("Could not find item {}", key);
return null;
}
@Nullable
protected Fluid getFluid(String fluidName) {
Fluid fluid = FluidRegistry.getFluid(fluidName);
if (fluid == null) {
Log.debug("Could not find fluid {}", fluidName);
}
return fluid;
}
protected void addBlocksToBackpack(String backpackUid, String... blockNames) {
for (String blockName : blockNames) {
Block block = getBlock(blockName);
if (block != null) {
Item item = Item.getItemFromBlock(block);
ItemStack blockStack = new ItemStack(item, 1, OreDictionary.WILDCARD_VALUE);
if (!blockStack.isEmpty()) {
BackpackManager.backpackInterface.addItemToForestryBackpack(backpackUid, blockStack);
} else {
Log.warning("Could not find an item for block: {}", blockName);
}
} else {
Log.warning("Missing block: {}", blockName);
}
}
}
}
| 411 | 0.875825 | 1 | 0.875825 | game-dev | MEDIA | 0.995445 | game-dev | 0.777588 | 1 | 0.777588 |
Limitex/mono-ui | 15,315 | Runtime/Scripts/Tooling/Data/ColorPresetAsset.cs | #if UNITY_EDITOR
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using UnityEditor;
using UnityEngine;
namespace Limitex.MonoUI.Editor.Data
{
#region Type Definitions
[Serializable]
public struct TransitionColor
{
public Color Normal;
public Color Highlighted;
public Color Pressed;
public Color Selected;
public Color Disabled;
public TransitionColor(Color normal, Color highlighted, Color pressed, Color selected, Color disabled)
{
Normal = normal;
Highlighted = highlighted;
Pressed = pressed;
Selected = selected;
Disabled = disabled;
}
}
// Random IDs are assigned to ensure stability against reordering and for serialization.
public enum ColorType
{
None = 412340151,
Background = 121473958,
Foreground = 790920719,
Primary = 598842521,
PrimaryForeground = 711723875,
Secondary = 471083450,
SecondaryForeground = 533222481,
Accent = 342849487,
AccentForeground = 364665978,
Muted = 432419634,
MutedForeground = 952807518,
Destructive = 578251783,
DestructiveForeground = 173638956,
Chart1 = 406805723,
Chart2 = 464079137,
Chart3 = 534066984,
Chart4 = 288490277,
Chart5 = 876561572,
Border = 694730041,
Ring = 179126290,
MutedHoverBackground = 974697568,
}
// Random IDs are assigned to ensure stability against reordering and for serialization.
public enum TransitionColorType
{
None = 897758581,
Primary = 607538827,
Ghost = 194200482,
Transparent = 353005088,
}
#endregion
[CreateAssetMenu(fileName = "NewColorPreset", menuName = "Mono UI/Color Preset/New Color Preset")]
public class ColorPresetAsset : ScriptableObject
{
[Header("Base Colors")]
public Color Background = new Color(0.03137254901960784f, 0.03137254901960784f, 0.0392156862745098f);
public Color Foreground = new Color(0.9764705882352941f, 0.9764705882352941f, 0.9764705882352941f);
[Header("Primary")]
public Color Primary = new Color(0.9764705882352941f, 0.9764705882352941f, 0.9764705882352941f);
public Color PrimaryForeground = new Color(0.09019607843137255f, 0.09019607843137255f, 0.10588235294117647f);
[Header("Secondary")]
public Color Secondary = new Color(0.15294117647058825f, 0.15294117647058825f, 0.16470588235294117f);
public Color SecondaryForeground = new Color(0.9764705882352941f, 0.9764705882352941f, 0.9764705882352941f);
[Header("Accent")]
public Color Accent = new Color(0.15294117647058825f, 0.15294117647058825f, 0.16470588235294117f);
public Color AccentForeground = new Color(0.9764705882352941f, 0.9764705882352941f, 0.9764705882352941f);
[Header("Muted")]
public Color Muted = new Color(0.15294117647058825f, 0.15294117647058825f, 0.16470588235294117f);
public Color MutedForeground = new Color(0.6313725490196078f, 0.6313725490196078f, 0.6627450980392157f);
[Header("Destructive")]
public Color Destructive = new Color(0.4980392156862745f, 0.11372549019607843f, 0.11372549019607843f);
public Color DestructiveForeground = new Color(0.9764705882352941f, 0.9764705882352941f, 0.9764705882352941f);
[Header("Chart")]
public Color Chart1 = new Color(0.14901960784313725f, 0.3803921568627451f, 0.8470588235294118f);
public Color Chart2 = new Color(0.17647058823529413f, 0.7176470588235294f, 0.5372549019607843f);
public Color Chart3 = new Color(0.9098039215686274f, 0.5490196078431373f, 0.18823529411764706f);
public Color Chart4 = new Color(0.6862745098039216f, 0.33725490196078434f, 0.8588235294117647f);
public Color Chart5 = new Color(0.8862745098039215f, 0.21176470588235294f, 0.43529411764705883f);
[Header("Others")]
public Color Border = new Color(0.15294117647058825f, 0.15294117647058825f, 0.16470588235294117f);
public Color Ring = new Color(0.8274509803921568f, 0.8274509803921568f, 0.8431372549019608f);
public Color MutedHoverBackground = new Color(0.03137254901960784f, 0.03137254901960784f, 0.0392156862745098f, 0.99f);
[Header("Transitions")]
public TransitionColor PrimaryTransition = new TransitionColor(
new Color(1.0f, 1.0f, 1.0f),
new Color(0.8f, 0.8f, 0.8f),
new Color(0.7f, 0.7f, 0.7f),
new Color(1.0f, 1.0f, 1.0f),
new Color(0.6313725490196078f, 0.6313725490196078f, 0.6627450980392157f));
public TransitionColor GhostTransition = new TransitionColor(
new Color(1.0f, 1.0f, 1.0f, 0.0f),
new Color(1.0f, 1.0f, 1.0f, 0.8f),
new Color(1.0f, 1.0f, 1.0f, 0.7f),
new Color(1.0f, 1.0f, 1.0f, 0.0f),
new Color(0.6313725490196078f, 0.6313725490196078f, 0.6627450980392157f));
public TransitionColor TranspanentTransition = new TransitionColor(
new Color(1.0f, 1.0f, 1.0f, 0.0f),
new Color(1.0f, 1.0f, 1.0f, 0.8f),
new Color(1.0f, 1.0f, 1.0f, 0.7f),
new Color(1.0f, 1.0f, 1.0f, 0.8f),
new Color(0.6313725490196078f, 0.6313725490196078f, 0.6627450980392157f));
#region Purse Methods
public Color? GetColorByType(ColorType colorType)
{
return colorType switch
{
ColorType.Background => Background,
ColorType.Foreground => Foreground,
ColorType.Primary => Primary,
ColorType.PrimaryForeground => PrimaryForeground,
ColorType.Secondary => Secondary,
ColorType.SecondaryForeground => SecondaryForeground,
ColorType.Accent => Accent,
ColorType.AccentForeground => AccentForeground,
ColorType.Muted => Muted,
ColorType.MutedForeground => MutedForeground,
ColorType.Destructive => Destructive,
ColorType.DestructiveForeground => DestructiveForeground,
ColorType.Chart1 => Chart1,
ColorType.Chart2 => Chart2,
ColorType.Chart3 => Chart3,
ColorType.Chart4 => Chart4,
ColorType.Chart5 => Chart5,
ColorType.Border => Border,
ColorType.Ring => Ring,
ColorType.MutedHoverBackground => MutedHoverBackground,
_ => null
};
}
public TransitionColor? GetTransitionColorByType(TransitionColorType transitionColorType)
{
return transitionColorType switch
{
TransitionColorType.Primary => PrimaryTransition,
TransitionColorType.Ghost => GhostTransition,
TransitionColorType.Transparent => TranspanentTransition,
_ => null
};
}
#endregion
#region Json Serialization
public static string ConvertToJson(ColorPresetAsset target, Formatting formatting)
{
var preset = new
{
baseColors = new
{
background = ColorToHex(target.Background),
foreground = ColorToHex(target.Foreground)
},
primary = new
{
@base = ColorToHex(target.Primary),
foreground = ColorToHex(target.PrimaryForeground)
},
secondary = new
{
@base = ColorToHex(target.Secondary),
foreground = ColorToHex(target.SecondaryForeground)
},
accent = new
{
@base = ColorToHex(target.Accent),
foreground = ColorToHex(target.AccentForeground)
},
muted = new
{
@base = ColorToHex(target.Muted),
foreground = ColorToHex(target.MutedForeground)
},
destructive = new
{
@base = ColorToHex(target.Destructive),
foreground = ColorToHex(target.DestructiveForeground)
},
chart = new
{
color1 = ColorToHex(target.Chart1),
color2 = ColorToHex(target.Chart2),
color3 = ColorToHex(target.Chart3),
color4 = ColorToHex(target.Chart4),
color5 = ColorToHex(target.Chart5)
},
others = new
{
border = ColorToHex(target.Border),
ring = ColorToHex(target.Ring),
mutedHoverBackground = ColorToHexWithAlpha(target.MutedHoverBackground)
},
transitions = new
{
primary = new
{
normal = ColorToHex(target.PrimaryTransition.Normal),
highlighted = ColorToHex(target.PrimaryTransition.Highlighted),
pressed = ColorToHex(target.PrimaryTransition.Pressed),
selected = ColorToHex(target.PrimaryTransition.Selected),
disabled = ColorToHex(target.PrimaryTransition.Disabled)
},
ghost = new
{
normal = ColorToHexWithAlpha(target.GhostTransition.Normal),
highlighted = ColorToHexWithAlpha(target.GhostTransition.Highlighted),
pressed = ColorToHexWithAlpha(target.GhostTransition.Pressed),
selected = ColorToHexWithAlpha(target.GhostTransition.Selected),
disabled = ColorToHex(target.GhostTransition.Disabled)
},
transparent = new
{
normal = ColorToHexWithAlpha(target.TranspanentTransition.Normal),
highlighted = ColorToHexWithAlpha(target.TranspanentTransition.Highlighted),
pressed = ColorToHexWithAlpha(target.TranspanentTransition.Pressed),
selected = ColorToHexWithAlpha(target.TranspanentTransition.Selected),
disabled = ColorToHex(target.TranspanentTransition.Disabled)
}
}
};
return JsonConvert.SerializeObject(preset, formatting);
}
public static void ParseJson(ref ColorPresetAsset target, string json)
{
try
{
JObject preset = JsonConvert.DeserializeObject<JObject>(json);
target.Background = ParseHexColor(preset["baseColors"]["background"].ToString());
target.Foreground = ParseHexColor(preset["baseColors"]["foreground"].ToString());
target.Primary = ParseHexColor(preset["primary"]["base"].ToString());
target.PrimaryForeground = ParseHexColor(preset["primary"]["foreground"].ToString());
target.Secondary = ParseHexColor(preset["secondary"]["base"].ToString());
target.SecondaryForeground = ParseHexColor(preset["secondary"]["foreground"].ToString());
target.Accent = ParseHexColor(preset["accent"]["base"].ToString());
target.AccentForeground = ParseHexColor(preset["accent"]["foreground"].ToString());
target.Muted = ParseHexColor(preset["muted"]["base"].ToString());
target.MutedForeground = ParseHexColor(preset["muted"]["foreground"].ToString());
target.Destructive = ParseHexColor(preset["destructive"]["base"].ToString());
target.DestructiveForeground = ParseHexColor(preset["destructive"]["foreground"].ToString());
target.Chart1 = ParseHexColor(preset["chart"]["color1"].ToString());
target.Chart2 = ParseHexColor(preset["chart"]["color2"].ToString());
target.Chart3 = ParseHexColor(preset["chart"]["color3"].ToString());
target.Chart4 = ParseHexColor(preset["chart"]["color4"].ToString());
target.Chart5 = ParseHexColor(preset["chart"]["color5"].ToString());
target.Border = ParseHexColor(preset["others"]["border"].ToString());
target.Ring = ParseHexColor(preset["others"]["ring"].ToString());
target.MutedHoverBackground = ParseHexColor(preset["others"]["mutedHoverBackground"].ToString());
target.PrimaryTransition = new TransitionColor(
ParseHexColor(preset["transitions"]["primary"]["normal"].ToString()),
ParseHexColor(preset["transitions"]["primary"]["highlighted"].ToString()),
ParseHexColor(preset["transitions"]["primary"]["pressed"].ToString()),
ParseHexColor(preset["transitions"]["primary"]["selected"].ToString()),
ParseHexColor(preset["transitions"]["primary"]["disabled"].ToString())
);
target.GhostTransition = new TransitionColor(
ParseHexColor(preset["transitions"]["ghost"]["normal"].ToString()),
ParseHexColor(preset["transitions"]["ghost"]["highlighted"].ToString()),
ParseHexColor(preset["transitions"]["ghost"]["pressed"].ToString()),
ParseHexColor(preset["transitions"]["ghost"]["selected"].ToString()),
ParseHexColor(preset["transitions"]["ghost"]["disabled"].ToString())
);
target.TranspanentTransition = new TransitionColor(
ParseHexColor(preset["transitions"]["transparent"]["normal"].ToString()),
ParseHexColor(preset["transitions"]["transparent"]["highlighted"].ToString()),
ParseHexColor(preset["transitions"]["transparent"]["pressed"].ToString()),
ParseHexColor(preset["transitions"]["transparent"]["selected"].ToString()),
ParseHexColor(preset["transitions"]["transparent"]["disabled"].ToString())
);
}
catch (Exception ex)
{
Debug.LogError($"Failed to parse JSON: {ex.Message}");
}
}
#region Helper Methods
private static string ColorToHex(Color color) => $"#{ColorUtility.ToHtmlStringRGB(color)}";
private static string ColorToHexWithAlpha(Color color) => $"#{ColorUtility.ToHtmlStringRGBA(color)}";
private static Color ParseHexColor(string hexColor)
{
if (hexColor.StartsWith("#")) hexColor = hexColor.Substring(1);
if (ColorUtility.TryParseHtmlString("#" + hexColor, out Color color)) return color;
Debug.LogWarning($"Failed to parse color: {hexColor}");
return Color.white;
}
#endregion
#endregion
}
}
#endif
| 411 | 0.68838 | 1 | 0.68838 | game-dev | MEDIA | 0.454794 | game-dev | 0.555359 | 1 | 0.555359 |
eead-csic-compbio/get_homologues | 1,644 | lib/bioperl-1.5.2_102/Bio/Graphics/Glyph/minmax.pm | package Bio::Graphics::Glyph::minmax;
# $Id: minmax.pm,v 1.2.6.1 2006/10/02 23:10:20 sendu Exp $
use strict;
use base qw(Bio::Graphics::Glyph::segments);
sub minmax {
my $self = shift;
my $parts = shift;
# figure out the colors
my $max_score = $self->option('max_score');
my $min_score = $self->option('min_score');
my $do_min = !defined $min_score;
my $do_max = !defined $max_score;
if ($do_min or $do_max) {
my $first = $parts->[0];
for my $part (@$parts) {
my $s = eval { $part->feature->score };
next unless defined $s;
$max_score = $s if $do_max && (!defined $max_score or $s > $max_score);
$min_score = $s if $do_min && (!defined $min_score or $s < $min_score);
}
}
($min_score,$max_score);
}
1;
__END__
=head1 NAME
Bio::Graphics::Glyph::minmax - The minmax glyph
=head1 SYNOPSIS
See L<Bio::Graphics::Panel> and L<Bio::Graphics::Glyph>.
=head1 DESCRIPTION
This glyph is a common base class for
L<Bio::Graphics::Glyph::graded_segments> and
L<Bio::Graphics::Glyph::xyplot>. It adds an internal method named
minmax() for calculating the upper and lower boundaries of scored
features, and is not intended for end users.
=head1 BUGS
Please report them.
=head1 SEE ALSO
L<Bio::Graphics::Panel>,
L<Bio::Graphics::Track>,
L<Bio::Graphics::Glyph::graded_segments>,
L<Bio::Graphics::Glyph::xyplot>,
=head1 AUTHOR
Lincoln Stein E<lt>lstein@cshl.orgE<gt>
Copyright (c) 2003 Cold Spring Harbor Laboratory
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself. See DISCLAIMER.txt for
disclaimers of warranty.
=cut
| 411 | 0.549582 | 1 | 0.549582 | game-dev | MEDIA | 0.375883 | game-dev,testing-qa | 0.545856 | 1 | 0.545856 |
amethyst/rustrogueliketutorial | 3,648 | chapter-30-dla/src/map_builders/common.rs | use super::{Map, Rect, TileType};
use std::cmp::{max, min};
use std::collections::HashMap;
pub fn apply_room_to_map(map : &mut Map, room : &Rect) {
for y in room.y1 +1 ..= room.y2 {
for x in room.x1 + 1 ..= room.x2 {
let idx = map.xy_idx(x, y);
if idx > 0 && idx < ((map.width * map.height)-1) as usize {
map.tiles[idx] = TileType::Floor;
}
}
}
}
pub fn apply_horizontal_tunnel(map : &mut Map, x1:i32, x2:i32, y:i32) {
for x in min(x1,x2) ..= max(x1,x2) {
let idx = map.xy_idx(x, y);
if idx > 0 && idx < map.width as usize * map.height as usize {
map.tiles[idx as usize] = TileType::Floor;
}
}
}
pub fn apply_vertical_tunnel(map : &mut Map, y1:i32, y2:i32, x:i32) {
for y in min(y1,y2) ..= max(y1,y2) {
let idx = map.xy_idx(x, y);
if idx > 0 && idx < map.width as usize * map.height as usize {
map.tiles[idx as usize] = TileType::Floor;
}
}
}
/// Searches a map, removes unreachable areas and returns the most distant tile.
pub fn remove_unreachable_areas_returning_most_distant(map : &mut Map, start_idx : usize) -> usize {
let map_starts : Vec<usize> = vec![start_idx];
let dijkstra_map = rltk::DijkstraMap::new(map.width as usize, map.height as usize, &map_starts , map, 300.0);
let mut exit_tile = (0, 0.0f32);
for (i, tile) in map.tiles.iter_mut().enumerate() {
if *tile == TileType::Floor {
let distance_to_start = dijkstra_map.map[i];
// We can't get to this tile - so we'll make it a wall
if distance_to_start == std::f32::MAX {
*tile = TileType::Wall;
} else {
// If it is further away than our current exit candidate, move the exit
if distance_to_start > exit_tile.1 {
exit_tile.0 = i;
exit_tile.1 = distance_to_start;
}
}
}
}
exit_tile.0
}
/// Generates a Voronoi/cellular noise map of a region, and divides it into spawn regions.
#[allow(clippy::map_entry)]
pub fn generate_voronoi_spawn_regions(map: &Map, rng : &mut rltk::RandomNumberGenerator) -> HashMap<i32, Vec<usize>> {
let mut noise_areas : HashMap<i32, Vec<usize>> = HashMap::new();
let mut noise = rltk::FastNoise::seeded(rng.roll_dice(1, 65536) as u64);
noise.set_noise_type(rltk::NoiseType::Cellular);
noise.set_frequency(0.08);
noise.set_cellular_distance_function(rltk::CellularDistanceFunction::Manhattan);
for y in 1 .. map.height-1 {
for x in 1 .. map.width-1 {
let idx = map.xy_idx(x, y);
if map.tiles[idx] == TileType::Floor {
let cell_value_f = noise.get_noise(x as f32, y as f32) * 10240.0;
let cell_value = cell_value_f as i32;
if noise_areas.contains_key(&cell_value) {
noise_areas.get_mut(&cell_value).unwrap().push(idx);
} else {
noise_areas.insert(cell_value, vec![idx]);
}
}
}
}
noise_areas
}
pub fn draw_corridor(map: &mut Map, x1:i32, y1:i32, x2:i32, y2:i32) {
let mut x = x1;
let mut y = y1;
while x != x2 || y != y2 {
if x < x2 {
x += 1;
} else if x > x2 {
x -= 1;
} else if y < y2 {
y += 1;
} else if y > y2 {
y -= 1;
}
let idx = map.xy_idx(x, y);
map.tiles[idx] = TileType::Floor;
}
}
| 411 | 0.877265 | 1 | 0.877265 | game-dev | MEDIA | 0.87071 | game-dev | 0.98424 | 1 | 0.98424 |
dufernst/LegionCore-7.3.5 | 2,326 | src/server/scripts/EasternKingdoms/MoltenCore/boss_coren_direbrew.cpp | /*
* Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* 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/>.
*/
#include "LFGMgr.h"
#include "Group.h"
/*
UPDATE `creature_template` SET `faction` = '14', `ScriptName` = 'boss_coren_direbrew' WHERE `entry` =23872 LIMIT 1 ;
UPDATE creature SET `spawntimesecs` = 604800 WHERE `id` =23872;
UPDATE `quest_template` SET `SpecialFlags` = '9' WHERE `entry` =25483 LIMIT 1 ;
*/
class boss_coren_direbrew : public CreatureScript
{
public:
boss_coren_direbrew() : CreatureScript("boss_coren_direbrew") { }
struct boss_coren_direbrewAI : public BossAI
{
boss_coren_direbrewAI(Creature* creature) : BossAI(creature, 10) {}
void Reset()
{
}
void JustDied(Unit* /*victim*/)
{
if (instance)
{
// LFG reward
Map::PlayerList const& players = instance->instance->GetPlayers();
LFGDungeonsEntry const* dungeon = sLfgDungeonsStore.LookupEntry(287); //lfg id
if (!players.isEmpty())
{
if (Group* group = players.begin()->getSource()->GetGroup())
if (group->isLFGGroup())
sLFGMgr->FinishDungeon(group->GetGUID(), dungeon->ID);
}
}
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_coren_direbrewAI(creature);
}
};
void AddSC_coren_direbrew()
{
new boss_coren_direbrew();
}
| 411 | 0.806737 | 1 | 0.806737 | game-dev | MEDIA | 0.738364 | game-dev | 0.810455 | 1 | 0.810455 |
MrMC/mrmc | 4,078 | xbmc/input/touch/ITouchInputHandling.cpp | /*
* Copyright (C) 2012-2013 Team XBMC
* http://xbmc.org
*
* 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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "ITouchInputHandling.h"
void ITouchInputHandling::RegisterHandler(ITouchActionHandler *touchHandler)
{
m_handler = touchHandler;
}
void ITouchInputHandling::UnregisterHandler()
{
m_handler = NULL;
}
void ITouchInputHandling::OnTouchAbort()
{
if (m_handler)
m_handler->OnTouchAbort();
}
bool ITouchInputHandling::OnSingleTouchStart(float x, float y)
{
if (m_handler)
return m_handler->OnSingleTouchStart(x, y);
return true;
}
bool ITouchInputHandling::OnSingleTouchHold(float x, float y)
{
if (m_handler)
return m_handler->OnSingleTouchHold(x, y);
return true;
}
bool ITouchInputHandling::OnSingleTouchMove(float x, float y, float offsetX, float offsetY, float velocityX, float velocityY)
{
if (m_handler)
return m_handler->OnSingleTouchMove(x, y, offsetX, offsetY, velocityX, velocityY);
return true;
}
bool ITouchInputHandling::OnSingleTouchEnd(float x, float y)
{
if (m_handler)
return m_handler->OnSingleTouchEnd(x, y);
return true;
}
bool ITouchInputHandling::OnMultiTouchDown(float x, float y, int32_t pointer)
{
if (m_handler)
return m_handler->OnMultiTouchDown(x, y, pointer);
return true;
}
bool ITouchInputHandling::OnMultiTouchHold(float x, float y, int32_t pointers /* = 2 */)
{
if (m_handler)
return m_handler->OnMultiTouchHold(x, y, pointers);
return true;
}
bool ITouchInputHandling::OnMultiTouchMove(float x, float y, float offsetX, float offsetY, float velocityX, float velocityY, int32_t pointer)
{
if (m_handler)
return m_handler->OnMultiTouchMove(x, y, offsetX, offsetY, velocityX, velocityY, pointer);
return true;
}
bool ITouchInputHandling::OnMultiTouchUp(float x, float y, int32_t pointer)
{
if (m_handler)
return m_handler->OnMultiTouchUp(x, y, pointer);
return true;
}
bool ITouchInputHandling::OnTouchGestureStart(float x, float y)
{
if (m_handler)
return m_handler->OnTouchGestureStart(x, y);
return true;
}
bool ITouchInputHandling::OnTouchGesturePan(float x, float y, float offsetX, float offsetY, float velocityX, float velocityY)
{
if (m_handler)
return m_handler->OnTouchGesturePan(x, y, offsetX, offsetY, velocityX, velocityY);
return true;
}
bool ITouchInputHandling::OnTouchGestureEnd(float x, float y, float offsetX, float offsetY, float velocityX, float velocityY)
{
if (m_handler)
return m_handler->OnTouchGestureEnd(x, y, offsetX, offsetY, velocityX, velocityY);
return true;
}
void ITouchInputHandling::OnTap(float x, float y, int32_t pointers /* = 1 */)
{
if (m_handler)
m_handler->OnTap(x, y, pointers);
}
void ITouchInputHandling::OnLongPress(float x, float y, int32_t pointers /* = 1 */)
{
if (m_handler)
m_handler->OnLongPress(x, y, pointers);
}
void ITouchInputHandling::OnSwipe(TouchMoveDirection direction, float xDown, float yDown, float xUp, float yUp, float velocityX, float velocityY, int32_t pointers /* = 1 */)
{
if (m_handler)
m_handler->OnSwipe(direction, xDown, yDown, xUp, yUp, velocityX, velocityY, pointers);
}
void ITouchInputHandling::OnZoomPinch(float centerX, float centerY, float zoomFactor)
{
if (m_handler)
m_handler->OnZoomPinch(centerX, centerY, zoomFactor);
}
void ITouchInputHandling::OnRotate(float centerX, float centerY, float angle)
{
if (m_handler)
m_handler->OnRotate(centerX, centerY, angle);
}
| 411 | 0.797385 | 1 | 0.797385 | game-dev | MEDIA | 0.806777 | game-dev | 0.814495 | 1 | 0.814495 |
VincentFoulon80/console_engine | 8,834 | examples/snake.rs | use console_engine::pixel;
use console_engine::Color;
use console_engine::ConsoleEngine;
use console_engine::KeyCode;
/// custom function for generating a random u32 bound into [0;max[
fn random(max: u32) -> u32 {
rand::random::<u32>() % max
}
/// Direction the snake can face
enum Direction {
North,
East,
South,
West,
}
/// Snake structure :
/// The game logic fits in it
struct Snake {
playing: bool,
bound_w: u32,
bound_h: u32,
direction: Direction,
old_dx: i8,
old_dy: i8,
pos_x: u32,
pos_y: u32,
apple_x: u32,
apple_y: u32,
body: Vec<(u32, u32)>,
}
impl Snake {
/// Game initialization
pub fn init(game_width: u32, game_height: u32) -> Snake {
Snake {
playing: false,
bound_w: game_width,
bound_h: game_height,
direction: Direction::East,
old_dx: 1, // start condition should be 1 due to starting direction being East
old_dy: 0,
pos_x: 4,
pos_y: 4,
apple_x: 0,
apple_y: 0,
body: vec![(3, 4), (2, 4)],
}
}
/// Generates an apple in the board
fn gen_apple(&mut self) {
let mut count_fallback = 0;
loop {
// randomly get coordinates
let x = random(self.bound_w);
let y = random(self.bound_h);
// check if the coordinates aren't colliding with the snake's body
// sets the position if no collision
if !self.body.contains(&(x, y)) {
self.apple_x = x;
self.apple_y = y;
return;
}
count_fallback += 1;
// if 50 tries did not succeed
if count_fallback > 50 {
// bruteforce the first available position
for y in 0..self.bound_h {
for x in 0..self.bound_w {
if !self.body.contains(&(x, y)) {
self.apple_x = x;
self.apple_y = y;
return;
}
}
}
// if bruteforce failed, game has been won
self.playing = false;
return;
}
}
}
pub fn input(&mut self, engine: &ConsoleEngine) {
if self.playing {
// Change snake's direction based on a keypad layout
if engine.is_key_pressed(KeyCode::Char('8')) || engine.is_key_pressed(KeyCode::Up) {
self.direction = Direction::North;
}
if engine.is_key_pressed(KeyCode::Char('6')) || engine.is_key_pressed(KeyCode::Right) {
self.direction = Direction::East;
}
if engine.is_key_pressed(KeyCode::Char('2')) || engine.is_key_pressed(KeyCode::Down) {
self.direction = Direction::South;
}
if engine.is_key_pressed(KeyCode::Char('4')) || engine.is_key_pressed(KeyCode::Left) {
self.direction = Direction::West;
}
} else {
// check when the player starts the game with space
if engine.is_key_pressed(KeyCode::Char(' ')) {
// Initialize game values to a starting state
self.playing = true;
self.direction = Direction::East;
self.old_dx = 1;
self.old_dy = 0;
self.pos_x = 4;
self.pos_y = 4;
self.body = vec![(3, 4), (2, 4)];
self.gen_apple();
}
}
}
pub fn update_position(&mut self) {
if self.playing {
// calculates the delta_x and delta_y
// based on facing direction
let mut dx = 0;
let mut dy = 0;
match self.direction {
Direction::North => dy = -1,
Direction::East => dx = 1,
Direction::South => dy = 1,
Direction::West => dx = -1,
}
// checks to see if old inputed direction overlaps with actual inputed direction
// such as East then West.. This would cause the game to think that the snake collided
// with itself causing a gameover >>
// if dx's or dy's are opposites then continue moving in old direction
if self.old_dx + dx == 0 || self.old_dy + dy == 0 {
dx = self.old_dx;
dy = self.old_dy;
} else {
self.old_dx = dx;
self.old_dy = dy;
}
// if the snake collides with top and left boundaries, game over
// this check need to be made first to bypass an underflowing
if self.pos_x == 0 && dx == -1 || self.pos_y == 0 && dy == -1 {
self.playing = false;
return;
}
// calculate new position, can't underflow because of the check above
let new_pos = (
(self.pos_x as i32 + dx as i32) as u32,
(self.pos_y as i32 + dy as i32) as u32,
);
// if collide with bottom and right boundaries, game over
if new_pos.0 >= self.bound_w || new_pos.1 >= self.bound_h {
self.playing = false;
return;
}
// if collide with own tail, game over
if self.body.contains(&new_pos) {
self.playing = false;
return;
}
// if collide with apple, add a new segment in snake's body
// and generate a new apple
if new_pos == (self.apple_x, self.apple_y) {
self.body.insert(0, (self.pos_x, self.pos_y));
self.gen_apple();
}
// if still alive, move the body
if self.playing {
self.body.insert(0, (self.pos_x, self.pos_y));
self.pos_x = new_pos.0;
self.pos_y = new_pos.1;
self.body.pop();
}
}
}
pub fn draw(&self, engine: &mut ConsoleEngine) {
if self.playing {
// draw apple
engine.set_pxl(
self.apple_x as i32,
self.apple_y as i32,
pixel::pxl_fg('O', Color::Red),
);
// draw snake's body
for segment in self.body.iter() {
engine.set_pxl(
segment.0 as i32,
segment.1 as i32,
pixel::pxl_fg('█', Color::Green),
);
}
// don't forget snake's head !
engine.set_pxl(
self.pos_x as i32,
self.pos_y as i32,
pixel::pxl_fg('█', Color::DarkGreen),
)
} else {
// blink a message, inviting the player to press space
// and display controls on the other side
if engine.frame_count % 8 >= 4 {
engine.print_fbg(2, 1, "Press", Color::Yellow, Color::Black);
engine.print_fbg(2, 2, "Space", Color::Yellow, Color::Black);
engine.print_fbg(3, 3, "To", Color::Yellow, Color::Black);
engine.print_fbg(2, 4, "Play", Color::Yellow, Color::Black);
} else {
engine.print(4, 1, "8");
engine.print(4, 2, "^");
engine.print(1, 3, "4 < > 6");
engine.print(4, 4, "v");
engine.print(4, 5, "2");
}
// score is always displayed
engine.print(1, 8, format!("Score:{}", self.body.len() - 2).as_str());
}
}
}
fn main() {
// initializes a screen filling the terminal of at least 10x10 of size with a target of 4 frame per second
let mut engine = console_engine::ConsoleEngine::init_fill_require(10, 10, 4).unwrap();
// initialize game here, providing term size as boundaries
let mut snake = Snake::init(engine.get_width(), engine.get_height());
// main loop, be aware that you'll have to break it because ctrl+C is captured
loop {
engine.wait_frame(); // wait for next frame + capture inputs
// engine.check_resize(); here we do not want to resize the terminal because it could break the boundaries of the game
// exit check
if engine.is_key_pressed(KeyCode::Char('q')) {
break;
}
engine.clear_screen(); // reset the screen
// run the game
snake.input(&engine);
snake.update_position();
// draw the game in engine's screen
snake.draw(&mut engine);
engine.draw(); // draw the screen
}
}
| 411 | 0.714973 | 1 | 0.714973 | game-dev | MEDIA | 0.760478 | game-dev | 0.907672 | 1 | 0.907672 |
FarGroup/FarManager | 189,102 | plugins/luamacro/luafar/lf_service.c | //---------------------------------------------------------------------------
#include <windows.h>
#include <rpc.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include "lf_version.h"
#include "lf_luafar.h"
#include "lf_util.h"
#include "lf_string.h"
#include "lf_bit64.h"
#include "lf_service.h"
#ifndef LUADLL
# if LUA_VERSION_NUM == 501
# define LUADLL "lua51.dll"
# elif LUA_VERSION_NUM == 502
# define LUADLL "lua52.dll"
# endif
#endif
typedef struct PluginStartupInfo PSInfo;
extern int luaopen_far_host(lua_State *L);
extern int luaopen_regex(lua_State*);
extern int luaopen_usercontrol(lua_State*);
extern int luaopen_uio(lua_State *L);
extern int luaopen_unicode(lua_State *L);
extern int luaopen_utf8(lua_State *L);
extern int luaopen_upackage(lua_State *L);
extern int luaopen_win(lua_State *L);
extern int luaopen_lpeg(lua_State *L);
extern int luaB_dofileW(lua_State *L);
extern int luaB_loadfileW(lua_State *L);
extern int pcall_msg(lua_State* L, int narg, int nret);
extern void push_flags_table(lua_State *L);
extern void SetFarColors(lua_State *L);
extern void WINAPI FarPanelItemFreeCallback(void* UserData, const struct FarPanelItemFreeInfo* Info);
extern int far_MacroCallFar(lua_State *L);
extern int far_MacroCallToLua(lua_State *L);
extern void PackMacroValues(lua_State* L, size_t Count, const struct FarMacroValue* Values);
extern void PushFarMacroValue(lua_State* L, const struct FarMacroValue* val);
extern int GetExportFunction(lua_State* L, const char* FuncName);
extern BOOL RunDefaultScript(lua_State* L, int ForFirstTime);
extern void PushPluginObject(lua_State* L, HANDLE hPlugin);
const char FarFileFilterType[] = "FarFileFilter";
const char FarTimerType[] = "FarTimer";
const char FarTimerQueueKey[] = "FarTimerQueue";
const char FarDialogType[] = "FarDialog";
const char SettingsType[] = "FarSettings";
const char SettingsHandles[] = "FarSettingsHandles";
const char PluginHandleType[] = "FarPluginHandle";
const char AddMacroDataType[] = "FarAddMacroData";
const char SavedScreenType[] = "FarSavedScreen";
const char FAR_VIRTUALKEYS[] = "far.virtualkeys";
const char FAR_FLAGSTABLE[] = "far.Flags";
const char FAR_DN_STORAGE[] = "FAR_DN_STORAGE";
static int InsideFarManager = 1;
const char* VirtualKeyStrings[256] =
{
// 0x00
NULL, "LBUTTON", "RBUTTON", "CANCEL",
"MBUTTON", "XBUTTON1", "XBUTTON2", NULL,
"BACK", "TAB", NULL, NULL,
"CLEAR", "RETURN", NULL, NULL,
// 0x10
"SHIFT", "CONTROL", "MENU", "PAUSE",
"CAPITAL", "KANA", NULL, "JUNJA",
"FINAL", "HANJA", NULL, "ESCAPE",
NULL, "NONCONVERT", "ACCEPT", "MODECHANGE",
// 0x20
"SPACE", "PRIOR", "NEXT", "END",
"HOME", "LEFT", "UP", "RIGHT",
"DOWN", "SELECT", "PRINT", "EXECUTE",
"SNAPSHOT", "INSERT", "DELETE", "HELP",
// 0x30
"0", "1", "2", "3",
"4", "5", "6", "7",
"8", "9", NULL, NULL,
NULL, NULL, NULL, NULL,
// 0x40
NULL, "A", "B", "C",
"D", "E", "F", "G",
"H", "I", "J", "K",
"L", "M", "N", "O",
// 0x50
"P", "Q", "R", "S",
"T", "U", "V", "W",
"X", "Y", "Z", "LWIN",
"RWIN", "APPS", NULL, "SLEEP",
// 0x60
"NUMPAD0", "NUMPAD1", "NUMPAD2", "NUMPAD3",
"NUMPAD4", "NUMPAD5", "NUMPAD6", "NUMPAD7",
"NUMPAD8", "NUMPAD9", "MULTIPLY", "ADD",
"SEPARATOR", "SUBTRACT", "DECIMAL", "DIVIDE",
// 0x70
"F1", "F2", "F3", "F4",
"F5", "F6", "F7", "F8",
"F9", "F10", "F11", "F12",
"F13", "F14", "F15", "F16",
// 0x80
"F17", "F18", "F19", "F20",
"F21", "F22", "F23", "F24",
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
// 0x90
"NUMLOCK", "SCROLL", "OEM_NEC_EQUAL", "OEM_FJ_MASSHOU",
"OEM_FJ_TOUROKU", "OEM_FJ_LOYA", "OEM_FJ_ROYA", NULL,
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
// 0xA0
"LSHIFT", "RSHIFT", "LCONTROL", "RCONTROL",
"LMENU", "RMENU", "BROWSER_BACK", "BROWSER_FORWARD",
"BROWSER_REFRESH", "BROWSER_STOP", "BROWSER_SEARCH", "BROWSER_FAVORITES",
"BROWSER_HOME", "VOLUME_MUTE", "VOLUME_DOWN", "VOLUME_UP",
// 0xB0
"MEDIA_NEXT_TRACK", "MEDIA_PREV_TRACK", "MEDIA_STOP", "MEDIA_PLAY_PAUSE",
"LAUNCH_MAIL", "LAUNCH_MEDIA_SELECT", "LAUNCH_APP1", "LAUNCH_APP2",
NULL, NULL, "OEM_1", "OEM_PLUS",
"OEM_COMMA", "OEM_MINUS", "OEM_PERIOD", "OEM_2",
// 0xC0
"OEM_3", NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
// 0xD0
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, "OEM_4",
"OEM_5", "OEM_6", "OEM_7", "OEM_8",
// 0xE0
NULL, NULL, "OEM_102", NULL,
NULL, "PROCESSKEY", NULL, "PACKET",
NULL, "OEM_RESET", "OEM_JUMP", "OEM_PA1",
"OEM_PA2", "OEM_PA3", "OEM_WSCTRL", NULL,
// 0xF0
NULL, NULL, NULL, NULL,
NULL, NULL, "ATTN", "CRSEL",
"EXSEL", "EREOF", "PLAY", "ZOOM",
"NONAME", "PA1", "OEM_CLEAR", NULL,
};
static lua_CFunction luaopen_bit = NULL;
static lua_CFunction luaopen_ffi = NULL;
static lua_CFunction luaopen_jit = NULL;
int IsLuaJIT(void) { return luaopen_jit != NULL; }
BOOL WINAPI DllMain(HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
{
(void) lpReserved;
if (DLL_PROCESS_ATTACH == dwReason && hDll)
{
// Try to load LuaJIT 2.0 libraries. This is done dynamically to ensure that
// LuaFAR works with either Lua 5.1 or LuaJIT 2.0
HMODULE hLib = GetModuleHandleA(LUADLL);
if (hLib)
{
luaopen_bit = (lua_CFunction)(intptr_t)GetProcAddress(hLib, "luaopen_bit");
luaopen_ffi = (lua_CFunction)(intptr_t)GetProcAddress(hLib, "luaopen_ffi");
luaopen_jit = (lua_CFunction)(intptr_t)GetProcAddress(hLib, "luaopen_jit");
}
}
return TRUE;
}
HANDLE GetLuaStateTimerQueue(lua_State *L)
{
HANDLE hQueue;
lua_getfield(L, LUA_REGISTRYINDEX, FarTimerQueueKey);
hQueue = lua_touserdata(L, -1);
lua_pop(L, 1);
return hQueue;
}
void DeleteLuaStateTimerQueue(lua_State *L)
{
lua_pushnil(L);
lua_setfield(L, LUA_REGISTRYINDEX, FarTimerQueueKey);
}
static TSynchroData* CreateSynchroData(int type, int data, TTimerData *td)
{
TSynchroData* SD = (TSynchroData*) malloc(sizeof(TSynchroData));
SD->type = type;
SD->data = data;
SD->ref = LUA_REFNIL;
SD->timerData = td;
return SD;
}
HANDLE OptHandle(lua_State *L)
{
switch(lua_type(L,1))
{
case LUA_TNONE:
case LUA_TNIL:
break;
case LUA_TNUMBER:
{
lua_Integer whatPanel = lua_tointeger(L,1);
HANDLE hh = (HANDLE)whatPanel;
return (hh==PANEL_PASSIVE || hh==PANEL_ACTIVE) ? hh : whatPanel%2 ? PANEL_ACTIVE:PANEL_PASSIVE;
}
case LUA_TLIGHTUSERDATA:
return lua_touserdata(L,1);
default:
luaL_typerror(L, 1, "integer or light userdata");
}
return NULL;
}
static HANDLE OptHandle2(lua_State *L)
{
return lua_isnoneornil(L,1) ? (luaL_checkinteger(L,2) % 2 ? PANEL_ACTIVE:PANEL_PASSIVE) : OptHandle(L);
}
static UINT64 get_env_flag(lua_State *L, int pos, int *success)
{
int dummy;
const char *str;
INT64 ret = 0;
if (success)
*success = TRUE;
else
success = &dummy;
switch(lua_type(L, pos))
{
case LUA_TNONE:
case LUA_TNIL:
break;
case LUA_TNUMBER:
ret = (__int64)lua_tonumber(L, pos); // IMPORTANT: cast to signed integer.
break;
case LUA_TSTRING:
str = lua_tostring(L, pos);
lua_getfield(L, LUA_REGISTRYINDEX, FAR_FLAGSTABLE);
lua_getfield(L, -1, str);
if (lua_type(L, -1) == LUA_TNUMBER)
ret = (__int64)lua_tonumber(L, -1); // IMPORTANT: cast to signed integer.
else if (!bit64_getvalue(L, -1, &ret))
*success = FALSE;
lua_pop(L, 2);
break;
default:
if (!bit64_getvalue(L, pos, &ret))
*success = FALSE;
break;
}
return ret;
}
static UINT64 check_env_flag(lua_State *L, int pos)
{
int success = FALSE;
UINT64 ret = lua_isnoneornil(L, pos) ? 0 : get_env_flag(L, pos, &success);
if (!success)
{
if (lua_isstring(L, pos))
{
lua_pushfstring(L, "invalid flag: \"%s\"", lua_tostring(L, pos));
luaL_argerror(L, pos, lua_tostring(L, -1));
}
else
luaL_argerror(L, pos, "invalid flag");
}
return ret;
}
UINT64 GetFlagCombination(lua_State *L, int pos, int *success)
{
UINT64 ret = 0;
UINT64 flag;
pos = abs_index(L, pos);
if (success)
*success = TRUE;
if (lua_type(L, pos) == LUA_TTABLE)
{
lua_pushnil(L);
while(lua_next(L, pos))
{
if (lua_type(L,-2)==LUA_TSTRING && lua_toboolean(L,-1))
{
flag = get_env_flag(L, -2, success);
if (success == NULL || *success)
ret |= flag;
else
{ lua_pop(L,2); return ret; }
}
lua_pop(L, 1);
}
}
else if (lua_type(L, pos) == LUA_TSTRING)
{
const char *p = lua_tostring(L, pos), *q;
for (; *p; p=q)
{
int ok;
while (isspace(*p)) p++;
if (*p == 0) break;
for (q=p+1; *q && !isspace(*q); ) q++;
lua_pushlstring(L, p, q-p);
flag = get_env_flag(L, -1, &ok);
lua_pop(L, 1);
if (ok)
ret |= flag;
else if (success)
*success = FALSE;
}
}
else
ret = get_env_flag(L, pos, success);
return ret;
}
static UINT64 CheckFlags(lua_State* L, int pos)
{
int success = FALSE;
UINT64 Flags = lua_isnoneornil(L, pos) ? 0 : GetFlagCombination(L, pos, &success);
if (!success)
luaL_error(L, "invalid flag combination");
return Flags;
}
UINT64 OptFlags(lua_State* L, int pos, UINT64 dflt)
{
return lua_isnoneornil(L, pos) ? dflt : CheckFlags(L, pos);
}
static UINT64 CheckFlagsFromTable(lua_State *L, int pos, const char* key)
{
UINT64 f = 0;
lua_getfield(L, pos, key);
if (!lua_isnil(L, -1))
f = CheckFlags(L, -1);
lua_pop(L, 1);
return f;
}
UINT64 GetFlagsFromTable(lua_State *L, int pos, const char* key)
{
UINT64 f;
lua_getfield(L, pos, key);
f = GetFlagCombination(L, -1, NULL);
lua_pop(L, 1);
return f;
}
void PutFlagsToTable(lua_State *L, const char* key, UINT64 flags)
{
bit64_push(L, flags);
lua_setfield(L, -2, key);
}
void PutFlagsToArray(lua_State *L, int index, UINT64 flags)
{
bit64_push(L, flags);
lua_rawseti(L, -2, index);
}
TPluginData* GetPluginData(lua_State* L)
{
static TPluginData FakePluginData;
TPluginData *pd;
if (InsideFarManager)
(void) lua_getallocf(L, (void**)&pd);
else
{
// There is no Far Manager here and no plugin data but some functions
// need TPluginData::Flags to handle file time resolution.
pd = &FakePluginData;
}
return pd;
}
static void PushPluginHandle(lua_State *L, HANDLE Handle)
{
if (Handle)
{
HANDLE *p = (HANDLE*)lua_newuserdata(L, sizeof(HANDLE));
*p = Handle;
luaL_getmetatable(L, PluginHandleType);
lua_setmetatable(L, -2);
}
else
lua_pushnil(L);
}
static int PluginHandle_rawhandle(lua_State *L)
{
void* Handle = *(void**)luaL_checkudata(L, 1, PluginHandleType);
lua_pushlightuserdata(L, Handle);
return 1;
}
static int Dialog_getvalue(lua_State *L, int pos, HANDLE *target)
{
if (lua_type(L, pos) == LUA_TUSERDATA)
{
int equal;
lua_getmetatable(L, pos);
luaL_getmetatable(L, FarDialogType);
equal = lua_rawequal(L, -1, -2);
lua_pop(L, 2);
if (equal && target)
{
*target = ((TDialogData*)lua_touserdata(L, pos))->hDlg;
equal = *target != INVALID_HANDLE_VALUE;
}
return equal;
}
return 0;
}
void ConvertLuaValue (lua_State *L, int pos, struct FarMacroValue *target)
{
INT64 val64;
HANDLE val_handle;
int type = lua_type(L, pos);
pos = abs_index(L, pos);
target->Type = FMVT_UNKNOWN;
if (type == LUA_TNUMBER)
{
target->Type = FMVT_DOUBLE;
target->Value.Double = lua_tonumber(L, pos);
}
else if (type == LUA_TSTRING)
{
target->Type = FMVT_STRING;
target->Value.String = check_utf8_string(L, pos, NULL);
}
else if (type == LUA_TTABLE)
{
lua_rawgeti(L,pos,1);
if (lua_type(L,-1) == LUA_TSTRING)
{
target->Type = FMVT_BINARY;
target->Value.Binary.Data = (void*)lua_tolstring(L, -1, &target->Value.Binary.Size);
}
lua_pop(L,1);
}
else if (type == LUA_TBOOLEAN)
{
target->Type = FMVT_BOOLEAN;
target->Value.Boolean = lua_toboolean(L, pos);
}
else if (type == LUA_TNIL)
{
target->Type = FMVT_NIL;
}
else if (type == LUA_TLIGHTUSERDATA)
{
target->Type = FMVT_POINTER;
target->Value.Pointer = lua_touserdata(L, pos);
}
else if (bit64_getvalue(L, pos, &val64))
{
target->Type = FMVT_INTEGER;
target->Value.Integer = val64;
}
else if (Dialog_getvalue(L, pos, &val_handle))
{
target->Type = FMVT_DIALOG;
target->Value.Pointer = val_handle;
}
}
static int far_GetFileOwner(lua_State *L)
{
wchar_t Owner[512];
const wchar_t *Computer = opt_utf8_string(L, 1, NULL);
const wchar_t *Name = check_utf8_string(L, 2, NULL);
if (GetPluginData(L)->FSF->GetFileOwner(Computer, Name, Owner, ARRSIZE(Owner)))
push_utf8_string(L, Owner, -1);
else
lua_pushnil(L);
return 1;
}
static int far_GetNumberOfLinks(lua_State *L)
{
const wchar_t *Name = check_utf8_string(L, 1, NULL);
int num = (int)GetPluginData(L)->FSF->GetNumberOfLinks(Name);
return lua_pushinteger(L, num), 1;
}
static int far_GetLuafarVersion(lua_State *L)
{
if (lua_toboolean(L, 1))
{
lua_pushinteger(L, 3);
lua_pushinteger(L, 0);
lua_pushinteger(L, 0);
lua_pushinteger(L, PLUGIN_BUILD);
return 4;
}
lua_pushfstring(L, "3.0.0.%d", (int)PLUGIN_BUILD);
return 1;
}
static void GetMouseEvent(lua_State *L, MOUSE_EVENT_RECORD* rec)
{
rec->dwMousePosition.X = GetOptIntFromTable(L, "MousePositionX", 0);
rec->dwMousePosition.Y = GetOptIntFromTable(L, "MousePositionY", 0);
rec->dwButtonState = GetOptIntFromTable(L, "ButtonState", 0);
rec->dwControlKeyState = GetOptIntFromTable(L, "ControlKeyState", 0);
rec->dwEventFlags = GetOptIntFromTable(L, "EventFlags", 0);
}
void PutMouseEvent(lua_State *L, const MOUSE_EVENT_RECORD* rec, BOOL table_exist)
{
if (!table_exist)
lua_createtable(L, 0, 5);
PutNumToTable(L, "MousePositionX", rec->dwMousePosition.X);
PutNumToTable(L, "MousePositionY", rec->dwMousePosition.Y);
PutNumToTable(L, "ButtonState", rec->dwButtonState);
PutNumToTable(L, "ControlKeyState", rec->dwControlKeyState);
PutNumToTable(L, "EventFlags", rec->dwEventFlags);
}
// convert a string from utf-8 to wide char and put it into a table,
// to prevent stack overflow and garbage collection
static const wchar_t* StoreTempString(lua_State *L, int store_stack_pos)
{
const wchar_t *s = check_utf8_string(L,-1,NULL);
luaL_ref(L, store_stack_pos);
return s;
}
static void PushEditorSetPosition(lua_State *L, const struct EditorSetPosition *esp)
{
lua_createtable(L, 0, 6);
PutIntToTable(L, "CurLine", esp->CurLine + 1);
PutIntToTable(L, "CurPos", esp->CurPos + 1);
PutIntToTable(L, "CurTabPos", esp->CurTabPos + 1);
PutIntToTable(L, "TopScreenLine", esp->TopScreenLine + 1);
PutIntToTable(L, "LeftPos", esp->LeftPos + 1);
PutIntToTable(L, "Overtype", esp->Overtype);
}
static void FillEditorSetPosition(lua_State *L, struct EditorSetPosition *esp)
{
esp->CurLine = GetOptIntFromTable(L, "CurLine", 0) - 1;
esp->CurPos = GetOptIntFromTable(L, "CurPos", 0) - 1;
esp->CurTabPos = GetOptIntFromTable(L, "CurTabPos", 0) - 1;
esp->TopScreenLine = GetOptIntFromTable(L, "TopScreenLine", 0) - 1;
esp->LeftPos = GetOptIntFromTable(L, "LeftPos", 0) - 1;
esp->Overtype = GetOptIntFromTable(L, "Overtype", -1);
}
void PushPanelItem(lua_State *L, const struct PluginPanelItem *PanelItem, int NoUserData)
{
lua_createtable(L, 0, 16); // "PanelItem"
//-----------------------------------------------------------------------
PutFileTimeToTable (L, "CreationTime", PanelItem->CreationTime);
PutFileTimeToTable (L, "LastAccessTime", PanelItem->LastAccessTime);
PutFileTimeToTable (L, "LastWriteTime", PanelItem->LastWriteTime);
PutFileTimeToTable (L, "ChangeTime", PanelItem->ChangeTime);
PutNumToTable (L, "FileSize", (double)PanelItem->FileSize);
PutNumToTable (L, "AllocationSize", (double)PanelItem->AllocationSize);
PutWStrToTable (L, "FileName", PanelItem->FileName, -1);
PutWStrToTable (L, "AlternateFileName", PanelItem->AlternateFileName, -1);
PutFlagsToTable (L, "Flags", PanelItem->Flags);
PutNumToTable (L, "NumberOfLinks", (double)PanelItem->NumberOfLinks);
PutNumToTable (L, "CRC32", (double)PanelItem->CRC32);
PutAttrToTable(L, (int)PanelItem->FileAttributes);
if (PanelItem->Description)
PutWStrToTable(L, "Description", PanelItem->Description, -1);
if (PanelItem->Owner)
PutWStrToTable(L, "Owner", PanelItem->Owner, -1);
/* not clear why custom columns are defined on per-file basis */
if (PanelItem->CustomColumnNumber > 0)
{
int j;
lua_createtable(L, (int)PanelItem->CustomColumnNumber, 0);
for(j=0; j < (int)PanelItem->CustomColumnNumber; j++)
PutWStrToArray(L, j+1, PanelItem->CustomColumnData[j], -1);
lua_setfield(L, -2, "CustomColumnData");
}
if (PanelItem->UserData.Data)
{
if (!NoUserData)
{
if (PanelItem->UserData.FreeData==FarPanelItemFreeCallback)
{
// This is a panel of a LuaFAR plugin
FarPanelItemUserData* ud = (FarPanelItemUserData*)PanelItem->UserData.Data;
// Compare registries rather than Lua states to allow for different coroutines of the same state
if (lua_topointer(ud->L, LUA_REGISTRYINDEX) == lua_topointer(L, LUA_REGISTRYINDEX))
{
lua_rawgeti(L, LUA_REGISTRYINDEX, ud->ref);
lua_setfield(L, -2, "UserData");
}
}
}
else
{
lua_pushlightuserdata(L, PanelItem->UserData.Data);
lua_setfield(L, -2, "ExtUserData"); //use field name different from "UserData" to distinguish later
lua_pushlightuserdata(L, (void*)(intptr_t)PanelItem->UserData.FreeData);
lua_setfield(L, -2, "FreeUserData");
}
}
}
//---------------------------------------------------------------------------
void PushPanelItems(lua_State *L, const struct PluginPanelItem *PanelItems, size_t ItemsNumber, int NoUserData)
{
int i;
lua_createtable(L, (int)ItemsNumber, 0); // "PanelItems"
for(i=0; i < (int)ItemsNumber; i++)
{
PushPanelItem(L, PanelItems + i, NoUserData);
lua_rawseti(L, -2, i+1);
}
}
//---------------------------------------------------------------------------
static int far_PluginStartupInfo(lua_State *L)
{
const wchar_t *p;
intptr_t len=0;
TPluginData *pd = GetPluginData(L);
lua_createtable(L, 0, 4);
PutWStrToTable(L, "ModuleName", pd->Info->ModuleName, -1);
for(p=pd->Info->ModuleName; *p; p++)
{
if (*p==L'\\') len = p - pd->Info->ModuleName;
}
PutWStrToTable(L, "ModuleDir", pd->Info->ModuleName, len+1);
PutLStrToTable(L, "PluginGuid", pd->PluginId, sizeof(GUID));
return 1;
}
static int far_GetCurrentDirectory(lua_State *L)
{
struct FarStandardFunctions *FSF = GetPluginData(L)->FSF;
size_t size = FSF->GetCurrentDirectory(0, NULL);
wchar_t* buf = (wchar_t*)lua_newuserdata(L, size * sizeof(wchar_t));
FSF->GetCurrentDirectory(size, buf);
push_utf8_string(L, buf, -1);
return 1;
}
static int push_ev_filename(lua_State *L, int isEditor, intptr_t Id)
{
wchar_t* fname;
size_t size;
PSInfo *Info = GetPluginData(L)->Info;
size = isEditor ?
Info->EditorControl(Id, ECTL_GETFILENAME, 0, 0) :
Info->ViewerControl(Id, VCTL_GETFILENAME, 0, 0);
if (!size) return 0;
fname = (wchar_t*)lua_newuserdata(L, size * sizeof(wchar_t));
size = isEditor ?
Info->EditorControl(Id, ECTL_GETFILENAME, size, fname) :
Info->ViewerControl(Id, VCTL_GETFILENAME, size, fname);
if (size)
{
push_utf8_string(L, fname, -1);
lua_remove(L, -2);
return 1;
}
lua_pop(L,1);
return 0;
}
static int editor_GetFileName(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
if (!push_ev_filename(L, 1, EditorId)) lua_pushnil(L);
return 1;
}
static int editor_GetInfo(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
struct EditorInfo ei;
ei.StructSize = sizeof(ei);
if (!Info->EditorControl(EditorId, ECTL_GETINFO, 0, &ei))
return lua_pushnil(L), 1;
lua_createtable(L, 0, 18);
PutNumToTable(L, "EditorID", (double)ei.EditorID);
if (push_ev_filename(L, 1, EditorId))
lua_setfield(L, -2, "FileName");
PutNumToTable(L, "WindowSizeX", (double) ei.WindowSizeX);
PutNumToTable(L, "WindowSizeY", (double) ei.WindowSizeY);
PutNumToTable(L, "TotalLines", (double) ei.TotalLines);
PutNumToTable(L, "CurLine", (double) ei.CurLine + 1);
PutNumToTable(L, "CurPos", (double) ei.CurPos + 1);
PutNumToTable(L, "CurTabPos", (double) ei.CurTabPos + 1);
PutNumToTable(L, "TopScreenLine", (double) ei.TopScreenLine + 1);
PutNumToTable(L, "LeftPos", (double) ei.LeftPos + 1);
PutNumToTable(L, "Overtype", (double) ei.Overtype);
PutNumToTable(L, "BlockType", (double) ei.BlockType);
PutNumToTable(L, "BlockStartLine", (double) ei.BlockStartLine + 1);
PutNumToTable(L, "Options", (double) ei.Options);
PutNumToTable(L, "TabSize", (double) ei.TabSize);
PutNumToTable(L, "BookmarkCount", (double) ei.BookmarkCount);
PutNumToTable(L, "SessionBookmarkCount", (double) ei.SessionBookmarkCount);
PutNumToTable(L, "CurState", (double) ei.CurState);
PutNumToTable(L, "CodePage", (double) ei.CodePage);
return 1;
}
/* t-rex:
* Для тех кому плохо доходит описываю:
* Редактор в фаре это двух связный список, указатель на текущюю строку
* изменяется только при ECTL_SETPOSITION, при использовании любой другой
* ECTL_* для которой нужно задавать номер строки если этот номер не -1
* (т.е. текущаая строка) то фар должен найти эту строку в списке (а это
* занимает дофига времени), поэтому если надо делать несколько ECTL_*
* (тем более когда они делаются на последовательность строк
* i,i+1,i+2,...) то перед каждым ECTL_* надо делать ECTL_SETPOSITION а
* сами ECTL_* вызывать с -1.
*/
static BOOL FastGetString(intptr_t EditorId, intptr_t string_num,
struct EditorGetString *egs, PSInfo *Info)
{
struct EditorSetPosition esp;
esp.StructSize = sizeof(esp);
esp.CurLine = string_num;
esp.CurPos = -1;
esp.CurTabPos = -1;
esp.TopScreenLine = -1;
esp.LeftPos = -1;
esp.Overtype = -1;
if (!Info->EditorControl(EditorId, ECTL_SETPOSITION, 0, &esp))
return FALSE;
egs->StringNumber = string_num;
return Info->EditorControl(EditorId, ECTL_GETSTRING, 0, egs) != 0;
}
// EditorGetString (EditorId, line_num, [mode])
//
// line_num: number of line in the Editor, a 1-based integer.
//
// mode: 0 = returns: table LineInfo; changes current position: no
// 1 = returns: table LineInfo; changes current position: yes
// 2 = returns: StringText,StringEOL; changes current position: yes
// 3 = returns: StringText,StringEOL; changes current position: no
//
// return: either table LineInfo or StringText,StringEOL - depending on `mode` argument.
//
static int _EditorGetString(lua_State *L, int is_wide)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
intptr_t line_num = luaL_optinteger(L, 2, 0) - 1;
intptr_t mode = luaL_optinteger(L, 3, 0);
BOOL res = 0;
struct EditorGetString egs = {0,0,0,NULL,NULL,0,0};
egs.StructSize = sizeof(egs);
if (mode == 0 || mode == 3 || mode == 4)
{
egs.StringNumber = line_num;
res = Info->EditorControl(EditorId, ECTL_GETSTRING, 0, &egs) != 0;
}
else if (mode == 1 || mode == 2)
res = FastGetString(EditorId, line_num, &egs, Info);
if (res)
{
if (mode == 2 || mode == 3)
{
if (is_wide)
{
push_utf16_string(L, egs.StringText, egs.StringLength);
push_utf16_string(L, egs.StringEOL, -1);
}
else
{
push_utf8_string(L, egs.StringText, egs.StringLength);
push_utf8_string(L, egs.StringEOL, -1);
}
return 2;
}
else if (mode == 4)
{
lua_pushinteger(L, egs.SelStart+1);
lua_pushinteger(L, egs.SelEnd);
lua_pushinteger(L, egs.StringLength);
return 3;
}
else
{
lua_createtable(L, 0, 6);
PutNumToTable(L, "StringNumber", (double)egs.StringNumber+1);
PutNumToTable(L, "StringLength", (double)egs.StringLength);
PutNumToTable(L, "SelStart", (double)egs.SelStart+1);
PutNumToTable(L, "SelEnd", (double)egs.SelEnd);
if (is_wide)
{
push_utf16_string(L, egs.StringText, egs.StringLength);
lua_setfield(L, -2, "StringText");
push_utf16_string(L, egs.StringEOL, -1);
lua_setfield(L, -2, "StringEOL");
}
else
{
PutWStrToTable(L, "StringText", egs.StringText, egs.StringLength);
PutWStrToTable(L, "StringEOL", egs.StringEOL, -1);
}
}
return 1;
}
return lua_pushnil(L), 1;
}
static int editor_GetString(lua_State *L) { return _EditorGetString(L, 0); }
static int editor_GetStringW(lua_State *L) { return _EditorGetString(L, 1); }
static int _EditorSetString(lua_State *L, int is_wide)
{
PSInfo *Info = GetPluginData(L)->Info;
struct EditorSetString ess;
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
size_t len;
ess.StructSize = sizeof(ess);
ess.StringNumber = luaL_optinteger(L, 2, 0) - 1;
if (is_wide)
{
ess.StringText = check_utf16_string(L, 3, &len);
ess.StringEOL = opt_utf16_string(L, 4, NULL);
if (ess.StringEOL)
{
lua_pushvalue(L, 4);
lua_pushliteral(L, "\0\0");
lua_concat(L, 2);
ess.StringEOL = (wchar_t*) lua_tostring(L, -1);
}
}
else
{
ess.StringText = check_utf8_string(L, 3, &len);
ess.StringEOL = opt_utf8_string(L, 4, NULL);
}
ess.StringLength = len;
lua_pushboolean(L, Info->EditorControl(EditorId, ECTL_SETSTRING, 0, &ess) != 0);
return 1;
}
static int editor_SetString(lua_State *L) { return _EditorSetString(L, 0); }
static int editor_SetStringW(lua_State *L) { return _EditorSetString(L, 1); }
static int editor_InsertString(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
int indent = lua_toboolean(L, 2);
lua_pushboolean(L, Info->EditorControl(EditorId, ECTL_INSERTSTRING, 0, &indent) != 0);
return 1;
}
static int editor_DeleteString(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
lua_pushboolean(L, Info->EditorControl(EditorId, ECTL_DELETESTRING, 0, 0) != 0);
return 1;
}
static int _EditorInsertText(lua_State *L, int is_wide)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
const wchar_t* text;
if (is_wide)
{
size_t len;
const char *s = luaL_checklstring(L,2,&len);
int needZero = 0;
if (len % sizeof(wchar_t))
{
if (s[len-1] && --len)
needZero = 1;
}
else
needZero = len && (s[len-2] || s[len-1]);
if (needZero)
{
lua_pushlstring(L, s, len);
lua_pushlstring(L, "\0", 1);
lua_concat(L, 2);
text = (const wchar_t*)lua_tostring(L, -1);
}
else
text = len ? (const wchar_t*)s : L"";
}
else
{
text = check_utf8_string(L,2,NULL);
}
lua_pushboolean(L, Info->EditorControl(EditorId, ECTL_INSERTTEXT, 0, (void*)text) != 0);
return 1;
}
static int editor_InsertText(lua_State *L) { return _EditorInsertText(L, 0); }
static int editor_InsertTextW(lua_State *L) { return _EditorInsertText(L, 1); }
static int editor_DeleteChar(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
lua_pushboolean(L, Info->EditorControl(EditorId, ECTL_DELETECHAR, 0, 0) != 0);
return 1;
}
static int editor_DeleteBlock(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
lua_pushboolean(L, Info->EditorControl(EditorId, ECTL_DELETEBLOCK, 0, 0) != 0);
return 1;
}
static int editor_UndoRedo(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
struct EditorUndoRedo eur;
memset(&eur, 0, sizeof(eur));
eur.StructSize = sizeof(eur);
eur.Command = check_env_flag(L, 2);
lua_pushboolean(L, GetPluginData(L)->Info->EditorControl(EditorId, ECTL_UNDOREDO, 0, &eur) != 0);
return 1;
}
static void FillKeyBarTitles(lua_State *L, int src_pos, struct KeyBarTitles *kbt)
{
int store_pos, i;
size_t size;
lua_newtable(L);
store_pos = lua_gettop(L);
//-------------------------------------------------------------------------
memset(kbt, 0, sizeof(*kbt));
kbt->CountLabels = lua_objlen(L, src_pos);
size = kbt->CountLabels * sizeof(struct KeyBarLabel);
kbt->Labels = (struct KeyBarLabel*)lua_newuserdata(L, size);
memset(kbt->Labels, 0, size);
for(i=0; i < (int)kbt->CountLabels; i++)
{
lua_rawgeti(L, src_pos, i+1);
if (!lua_istable(L, -1))
{
kbt->CountLabels = i;
lua_pop(L, 1);
break;
}
kbt->Labels[i].Key.VirtualKeyCode = GetOptIntFromTable(L, "VirtualKeyCode", 0);
kbt->Labels[i].Key.ControlKeyState = CAST(DWORD,CheckFlagsFromTable(L, -1, "ControlKeyState"));
//-----------------------------------------------------------------------
lua_getfield(L, -1, "Text");
kbt->Labels[i].Text = StoreTempString(L, store_pos);
//-----------------------------------------------------------------------
lua_getfield(L, -1, "LongText");
kbt->Labels[i].LongText = StoreTempString(L, store_pos);
//-----------------------------------------------------------------------
lua_pop(L, 1);
}
}
static int SetKeyBar(lua_State *L, BOOL editor)
{
intptr_t result;
void* param = NULL;
struct KeyBarTitles kbt;
struct FarSetKeyBarTitles skbt;
intptr_t Id = luaL_optinteger(L, 1, -1);
PSInfo *Info = GetPluginData(L)->Info;
enum { REDRAW=-1, RESTORE=0 }; // corresponds to FAR API
BOOL argfail = FALSE;
if (lua_isstring(L,2))
{
const char* p = lua_tostring(L,2);
if (0 == strcmp("redraw", p)) param = (void*)REDRAW;
else if (0 == strcmp("restore", p)) param = (void*)RESTORE;
else argfail = TRUE;
}
else if (lua_istable(L,2))
{
param = &skbt;
FillKeyBarTitles(L, 2, &kbt);
skbt.StructSize = sizeof(skbt);
skbt.Titles = &kbt;
}
else
argfail = TRUE;
if (argfail)
return luaL_argerror(L, 2, "must be 'redraw', 'restore', or table");
result = editor ? Info->EditorControl(Id, ECTL_SETKEYBAR, 0, param) :
Info->ViewerControl(Id, VCTL_SETKEYBAR, 0, param);
lua_pushboolean(L, result != 0);
return 1;
}
static int editor_SetKeyBar(lua_State *L)
{
return SetKeyBar(L, TRUE);
}
static int viewer_SetKeyBar(lua_State *L)
{
return SetKeyBar(L, FALSE);
}
static int editor_SetParam(lua_State *L)
{
wchar_t buf[256];
int tp;
intptr_t result;
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
struct EditorSetParameter esp;
memset(&esp, 0, sizeof(esp));
esp.StructSize = sizeof(esp);
esp.Type = check_env_flag(L,2);
//-----------------------------------------------------
tp = lua_type(L,3);
if (tp == LUA_TNUMBER)
esp.Param.iParam = lua_tointeger(L,3);
else if (tp == LUA_TBOOLEAN)
esp.Param.iParam = lua_toboolean(L,3);
else if (tp == LUA_TSTRING)
esp.Param.wszParam = (wchar_t*)check_utf8_string(L,3,NULL);
//-----------------------------------------------------
if (esp.Type == ESPT_GETWORDDIV)
{
esp.Param.wszParam = buf;
esp.Size = ARRSIZE(buf);
}
//-----------------------------------------------------
esp.Flags = GetFlagCombination(L, 4, NULL);
//-----------------------------------------------------
result = Info->EditorControl(EditorId, ECTL_SETPARAM, 0, &esp);
lua_pushboolean(L, result != 0);
if (result && esp.Type == ESPT_GETWORDDIV)
{
push_utf8_string(L,buf,-1); return 2;
}
return 1;
}
static int editor_SetPosition(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
struct EditorSetPosition esp;
esp.StructSize = sizeof(esp);
if (lua_istable(L, 2))
{
lua_settop(L, 2);
FillEditorSetPosition(L, &esp);
}
else
{
esp.CurLine = luaL_optinteger(L,2,0) - 1;
esp.CurPos = luaL_optinteger(L,3,0) - 1;
esp.CurTabPos = luaL_optinteger(L,4,0) - 1;
esp.TopScreenLine = luaL_optinteger(L,5,0) - 1;
esp.LeftPos = luaL_optinteger(L,6,0) - 1;
esp.Overtype = luaL_optinteger(L,7,-1);
}
lua_pushboolean(L, (int)Info->EditorControl(EditorId, ECTL_SETPOSITION, 0, &esp));
return 1;
}
static int editor_Redraw(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
lua_pushboolean(L, (int)Info->EditorControl(EditorId, ECTL_REDRAW, 0, 0));
return 1;
}
static int editor_ExpandTabs(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
intptr_t line_num = luaL_optinteger(L, 2, 0) - 1;
lua_pushboolean(L, (int)Info->EditorControl(EditorId, ECTL_EXPANDTABS, 0, &line_num));
return 1;
}
static int PushBookmarks(lua_State *L, int command)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
size_t size = GetPluginData(L)->Info->EditorControl(EditorId, command, 0, NULL);
if (size)
{
struct EditorBookmarks *ebm = (struct EditorBookmarks*)lua_newuserdata(L, size);
ebm->StructSize = sizeof(*ebm);
ebm->Size = size;
if (GetPluginData(L)->Info->EditorControl(EditorId, command, 0, ebm))
{
int i;
lua_createtable(L, (int)ebm->Count, 0);
for(i=0; i < (int)ebm->Count; i++)
{
lua_pushinteger(L, i+1);
lua_createtable(L, 0, 4);
PutNumToTable(L, "Line", (double) ebm->Line[i] + 1);
PutNumToTable(L, "Cursor", (double) ebm->Cursor[i] + 1);
PutNumToTable(L, "ScreenLine", (double) ebm->ScreenLine[i] + 1);
PutNumToTable(L, "LeftPos", (double) ebm->LeftPos[i] + 1);
lua_rawset(L, -3);
}
return 1;
}
}
return lua_pushnil(L), 1;
}
static int editor_GetBookmarks(lua_State *L)
{
return PushBookmarks(L, ECTL_GETBOOKMARKS);
}
static int editor_GetSessionBookmarks(lua_State *L)
{
return PushBookmarks(L, ECTL_GETSESSIONBOOKMARKS);
}
static int editor_AddSessionBookmark(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
lua_pushboolean(L, Info->EditorControl(EditorId, ECTL_ADDSESSIONBOOKMARK, 0, 0) != 0);
return 1;
}
static int editor_ClearSessionBookmarks(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
lua_pushboolean(L, Info->EditorControl(EditorId, ECTL_CLEARSESSIONBOOKMARKS, 0, 0) != 0);
return 1;
}
static int editor_DeleteSessionBookmark(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
intptr_t num = luaL_optinteger(L, 2, 0) - 1;
PSInfo *Info = GetPluginData(L)->Info;
lua_pushboolean(L, Info->EditorControl(EditorId, ECTL_DELETESESSIONBOOKMARK, 0, (void*)num) != 0);
return 1;
}
static int editor_NextSessionBookmark(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
lua_pushboolean(L, Info->EditorControl(EditorId, ECTL_NEXTSESSIONBOOKMARK, 0, 0) != 0);
return 1;
}
static int editor_PrevSessionBookmark(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
lua_pushboolean(L, Info->EditorControl(EditorId, ECTL_PREVSESSIONBOOKMARK, 0, 0) != 0);
return 1;
}
static int editor_SetTitle(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
const wchar_t* text = opt_utf8_string(L, 2, NULL);
lua_pushboolean(L, (int)Info->EditorControl(EditorId, ECTL_SETTITLE, 0, (void*)text));
return 1;
}
static int editor_GetTitle(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
intptr_t size = Info->EditorControl(EditorId, ECTL_GETTITLE, 0, NULL);
if (size)
{
wchar_t* buf = (wchar_t*)lua_newuserdata(L, size*sizeof(wchar_t));
if (size == Info->EditorControl(EditorId, ECTL_GETTITLE, size, buf))
{
push_utf8_string(L, buf, -1);
return 1;
}
}
lua_pushnil(L);
return 1;
}
static int editor_Quit(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
lua_pushboolean(L, (int)Info->EditorControl(EditorId, ECTL_QUIT, 0, 0));
return 1;
}
static int FillEditorSelect(lua_State *L, int pos_table, struct EditorSelect *es)
{
int success;
lua_getfield(L, pos_table, "BlockType");
es->BlockType = CAST(int, get_env_flag(L, -1, &success));
if (!success)
{
lua_pop(L,1);
return 0;
}
lua_pushvalue(L, pos_table);
es->BlockStartLine = GetOptIntFromTable(L, "BlockStartLine", 0) - 1;
es->BlockStartPos = GetOptIntFromTable(L, "BlockStartPos", 0) - 1;
es->BlockWidth = GetOptIntFromTable(L, "BlockWidth", -1);
es->BlockHeight = GetOptIntFromTable(L, "BlockHeight", -1);
lua_pop(L,2);
return 1;
}
static int editor_Select(lua_State *L)
{
int success = TRUE;
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
struct EditorSelect es;
es.StructSize = sizeof(es);
if (lua_istable(L, 2))
success = FillEditorSelect(L, 2, &es);
else
{
es.BlockType = CAST(int, check_env_flag(L, 2));
es.BlockStartLine = luaL_optinteger(L, 3, 0) - 1;
es.BlockStartPos = luaL_optinteger(L, 4, 0) - 1;
es.BlockWidth = luaL_optinteger(L, 5, -1);
es.BlockHeight = luaL_optinteger(L, 6, -1);
}
lua_pushboolean(L, success && Info->EditorControl(EditorId, ECTL_SELECT, 0, &es));
return 1;
}
// This function is that long because FAR API does not supply needed
// information directly.
static int editor_GetSelection(lua_State *L)
{
intptr_t BlockStartPos, h, from, to;
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
struct EditorInfo EI;
struct EditorGetString egs;
struct EditorSetPosition esp;
EI.StructSize = sizeof(EI);
egs.StructSize = sizeof(egs);
esp.StructSize = sizeof(esp);
Info->EditorControl(EditorId, ECTL_GETINFO, 0, &EI);
if (EI.BlockType == BTYPE_NONE || !FastGetString(EditorId, EI.BlockStartLine, &egs, Info))
return lua_pushnil(L), 1;
lua_createtable(L, 0, 5);
PutIntToTable(L, "BlockType", EI.BlockType);
PutIntToTable(L, "StartLine", EI.BlockStartLine+1);
BlockStartPos = egs.SelStart;
PutIntToTable(L, "StartPos", BlockStartPos+1);
// binary search for a non-block line
h = 100; // arbitrary small number
from = EI.BlockStartLine;
for(to = from+h; to < EI.TotalLines; to = from + (h*=2))
{
if (!FastGetString(EditorId, to, &egs, Info))
return lua_pushnil(L), 1;
if (egs.SelStart < 0)
break;
}
if (to >= EI.TotalLines)
to = EI.TotalLines - 1;
// binary search for the last block line
while(from != to)
{
intptr_t curr = (from + to + 1) / 2;
if (!FastGetString(EditorId, curr, &egs, Info))
return lua_pushnil(L), 1;
if (egs.SelStart < 0)
{
if (curr == to)
break;
to = curr; // curr was not selected
}
else
{
from = curr; // curr was selected
}
}
if (!FastGetString(EditorId, from, &egs, Info))
return lua_pushnil(L), 1;
PutIntToTable(L, "EndLine", from+1);
PutIntToTable(L, "EndPos", egs.SelEnd);
// restore current position, since FastGetString() changed it
esp.CurLine = EI.CurLine;
esp.CurPos = EI.CurPos;
esp.CurTabPos = EI.CurTabPos;
esp.TopScreenLine = EI.TopScreenLine;
esp.LeftPos = EI.LeftPos;
esp.Overtype = EI.Overtype;
Info->EditorControl(EditorId, ECTL_SETPOSITION, 0, &esp);
return 1;
}
static int _EditorTabConvert(lua_State *L, int Operation)
{
intptr_t EditorId = luaL_optinteger(L,1,CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
struct EditorConvertPos ecp;
ecp.StructSize = sizeof(ecp);
ecp.StringNumber = luaL_optinteger(L,2,0) - 1;
ecp.SrcPos = luaL_checkinteger(L,3) - 1;
if (Info->EditorControl(EditorId, Operation, 0, &ecp))
lua_pushinteger(L, ecp.DestPos+1);
else
lua_pushnil(L);
return 1;
}
static int editor_TabToReal(lua_State *L)
{
return _EditorTabConvert(L, ECTL_TABTOREAL);
}
static int editor_RealToTab(lua_State *L)
{
return _EditorTabConvert(L, ECTL_REALTOTAB);
}
int GetFarColor(lua_State *L, int pos, struct FarColor* Color)
{
if (lua_istable(L, pos))
{
lua_pushvalue(L, pos);
Color->Flags = CheckFlagsFromTable(L, -1, "Flags");
Color->Foreground.ForegroundColor = CAST(COLORREF, GetOptNumFromTable(L, "ForegroundColor", 0));
Color->Background.BackgroundColor = CAST(COLORREF, GetOptNumFromTable(L, "BackgroundColor", 0));
Color->Underline.UnderlineColor = CAST(COLORREF, GetOptNumFromTable(L, "UnderlineColor", 0));
Color->Reserved = 0;
lua_pop(L, 1);
return 1;
}
else if (lua_isnumber(L, pos))
{
DWORD num = (DWORD)lua_tonumber(L, pos);
Color->Flags = FCF_INDEXMASK;
Color->Foreground.ForegroundColor = (num & 0x0F) | ALPHAMASK;
Color->Background.BackgroundColor = ((num>>4) & 0x0F) | ALPHAMASK;
Color->Underline.UnderlineColor = 0;
Color->Reserved = 0;
return 1;
}
return 0;
}
void PushFarColor(lua_State *L, const struct FarColor* Color)
{
lua_createtable(L, 0, 3);
PutFlagsToTable(L, "Flags", Color->Flags);
PutNumToTable(L, "ForegroundColor", Color->Foreground.ForegroundColor);
PutNumToTable(L, "BackgroundColor", Color->Background.BackgroundColor);
PutNumToTable(L, "UnderlineColor", Color->Underline.UnderlineColor);
}
static void GetOptGuid(lua_State *L, int pos, GUID* target, const GUID* source)
{
if (lua_type(L, pos) == LUA_TSTRING && lua_objlen(L, pos) >= sizeof(GUID))
*target = *CAST(const GUID*, lua_tostring(L, pos));
else if (lua_isnoneornil(L, pos))
*target = *source;
else
luaL_argerror(L, pos, "GUID required");
}
static int editor_AddColor(lua_State *L)
{
TPluginData *pd = GetPluginData(L);
intptr_t EditorId;
struct EditorColor ec;
memset(&ec, 0, sizeof(ec));
ec.StructSize = sizeof(ec);
ec.ColorItem = 0;
EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
ec.StringNumber = luaL_optinteger(L, 2, 0) - 1;
ec.StartPos = luaL_checkinteger(L, 3) - 1;
ec.EndPos = luaL_checkinteger(L, 4) - 1;
ec.Flags = OptFlags(L, 5, 0);
luaL_argcheck(L, GetFarColor(L, 6, &ec.Color), 6, "table or number expected");
ec.Priority = CAST(unsigned, luaL_optnumber(L, 7, EDITOR_COLOR_NORMAL_PRIORITY));
GetOptGuid(L, 8, &ec.Owner, pd->PluginId);
lua_pushboolean(L, pd->Info->EditorControl(EditorId, ECTL_ADDCOLOR, 0, &ec) != 0);
return 1;
}
static int editor_DelColor(lua_State *L)
{
TPluginData *pd = GetPluginData(L);
intptr_t EditorId;
struct EditorDeleteColor edc;
edc.StructSize = sizeof(edc);
EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
edc.StringNumber = luaL_optinteger(L, 2, 0) - 1;
edc.StartPos = luaL_optinteger(L, 3, 0) - 1;
GetOptGuid(L, 4, &edc.Owner, pd->PluginId);
lua_pushboolean(L, pd->Info->EditorControl(EditorId, ECTL_DELCOLOR, 0, &edc) != 0);
return 1;
}
static int editor_GetColor(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
intptr_t EditorId;
struct EditorColor ec;
memset(&ec, 0, sizeof(ec));
ec.StructSize = sizeof(ec);
EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
ec.StringNumber = luaL_optinteger(L, 2, 0) - 1;
ec.ColorItem = luaL_checkinteger(L, 3);
if (Info->EditorControl(EditorId, ECTL_GETCOLOR, 0, &ec))
{
lua_createtable(L, 0, 6);
PutNumToTable(L, "StartPos", (double)ec.StartPos+1);
PutNumToTable(L, "EndPos", (double)ec.EndPos+1);
PutNumToTable(L, "Priority", (double)ec.Priority);
PutFlagsToTable(L, "Flags", ec.Flags);
PushFarColor(L, &ec.Color);
lua_setfield(L, -2, "Color");
PutLStrToTable(L, "Owner", (const void*)&ec.Owner, sizeof(ec.Owner));
}
else
lua_pushnil(L);
return 1;
}
static int editor_SaveFile(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
struct EditorSaveFile esf;
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
esf.StructSize = sizeof(esf);
esf.FileName = opt_utf8_string(L, 2, NULL);
esf.FileEOL = opt_utf8_string(L, 3, NULL);
esf.CodePage = luaL_optinteger(L, 4, CP_DEFAULT);
lua_pushboolean(L, (int)Info->EditorControl(EditorId, ECTL_SAVEFILE, 0, &esf));
return 1;
}
void PushInputRecord(lua_State *L, const INPUT_RECORD* ir)
{
lua_newtable(L);
PutIntToTable(L, "EventType", ir->EventType);
switch(ir->EventType)
{
case KEY_EVENT:
PutBoolToTable(L,"KeyDown", ir->Event.KeyEvent.bKeyDown);
PutNumToTable(L, "RepeatCount", ir->Event.KeyEvent.wRepeatCount);
PutNumToTable(L, "VirtualKeyCode", ir->Event.KeyEvent.wVirtualKeyCode);
PutNumToTable(L, "VirtualScanCode", ir->Event.KeyEvent.wVirtualScanCode);
PutWStrToTable(L, "UnicodeChar", &ir->Event.KeyEvent.uChar.UnicodeChar, 1);
PutNumToTable(L, "ControlKeyState", ir->Event.KeyEvent.dwControlKeyState);
break;
case MOUSE_EVENT:
PutMouseEvent(L, &ir->Event.MouseEvent, TRUE);
break;
case WINDOW_BUFFER_SIZE_EVENT:
PutNumToTable(L, "SizeX", ir->Event.WindowBufferSizeEvent.dwSize.X);
PutNumToTable(L, "SizeY", ir->Event.WindowBufferSizeEvent.dwSize.Y);
break;
case MENU_EVENT:
PutNumToTable(L, "CommandId", ir->Event.MenuEvent.dwCommandId);
break;
case FOCUS_EVENT:
PutBoolToTable(L,"SetFocus", ir->Event.FocusEvent.bSetFocus);
break;
default:
break;
}
}
static int editor_ReadInput(lua_State *L)
{
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
PSInfo *Info = GetPluginData(L)->Info;
INPUT_RECORD ir;
if (Info->EditorControl(EditorId, ECTL_READINPUT, 0, &ir))
PushInputRecord(L, &ir);
else
lua_pushnil(L);
return 1;
}
void FillInputRecord(lua_State *L, int pos, INPUT_RECORD *ir)
{
int success = 0;
pos = abs_index(L, pos);
luaL_checktype(L, pos, LUA_TTABLE);
memset(ir, 0, sizeof(INPUT_RECORD));
// determine event type
lua_getfield(L, pos, "EventType");
ir->EventType = CAST(WORD, get_env_flag(L, -1, &success));
if (success)
{
if (ir->EventType == 0)
{
ir->EventType = KEY_EVENT;
}
success = ir->EventType == KEY_EVENT
|| ir->EventType == MOUSE_EVENT
|| ir->EventType == WINDOW_BUFFER_SIZE_EVENT
|| ir->EventType == MENU_EVENT
|| ir->EventType == FOCUS_EVENT;
}
if (!success)
luaL_error(L, "invalid 'EventType' specified");
lua_pop(L, 1);
lua_pushvalue(L, pos);
switch(ir->EventType)
{
case KEY_EVENT:
ir->Event.KeyEvent.bKeyDown = GetOptBoolFromTable(L, "KeyDown", TRUE);
ir->Event.KeyEvent.wRepeatCount = GetOptIntFromTable(L, "RepeatCount", 1);
ir->Event.KeyEvent.wVirtualKeyCode = GetOptIntFromTable(L, "VirtualKeyCode", 0);
ir->Event.KeyEvent.wVirtualScanCode = GetOptIntFromTable(L, "VirtualScanCode", 0);
lua_getfield(L, -1, "UnicodeChar");
ir->Event.KeyEvent.uChar.UnicodeChar = *opt_utf8_string(L, -1, L"");
lua_pop(L, 1);
ir->Event.KeyEvent.dwControlKeyState = GetOptIntFromTable(L, "ControlKeyState", 0);
break;
case MOUSE_EVENT:
GetMouseEvent(L, &ir->Event.MouseEvent);
break;
case WINDOW_BUFFER_SIZE_EVENT:
ir->Event.WindowBufferSizeEvent.dwSize.X = GetOptIntFromTable(L, "SizeX", 0);
ir->Event.WindowBufferSizeEvent.dwSize.Y = GetOptIntFromTable(L, "SizeY", 0);
break;
case MENU_EVENT:
ir->Event.MenuEvent.dwCommandId = GetOptIntFromTable(L, "CommandId", 0);
break;
case FOCUS_EVENT:
ir->Event.FocusEvent.bSetFocus = GetOptBoolFromTable(L, "SetFocus", FALSE);
break;
}
lua_pop(L, 1);
}
static void OptInputRecord(lua_State* L, TPluginData *pd, int pos, INPUT_RECORD* ir)
{
if (lua_istable(L, pos))
FillInputRecord(L, pos, ir);
else if (lua_type(L, pos) == LUA_TSTRING)
{
wchar_t* name = check_utf8_string(L, pos, NULL);
if (!pd->FSF->FarNameToInputRecord(name, ir))
luaL_argerror(L, pos, "invalid key");
}
else
{
memset(ir, 0, sizeof(INPUT_RECORD));
ir->EventType = KEY_EVENT;
}
}
static int editor_ProcessInput(lua_State *L)
{
INPUT_RECORD ir;
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
luaL_checktype(L, 2, LUA_TTABLE);
FillInputRecord(L, 2, &ir);
lua_pushboolean(L, GetPluginData(L)->Info->EditorControl(EditorId, ECTL_PROCESSINPUT, 0, &ir) != 0);
return 1;
}
static int editor_SubscribeChangeEvent(lua_State *L)
{
TPluginData *pd = GetPluginData(L);
struct EditorSubscribeChangeEvent data;
intptr_t EditorId = luaL_optinteger(L, 1, CURRENT_EDITOR);
int command = lua_toboolean(L, 2) ? ECTL_SUBSCRIBECHANGEEVENT : ECTL_UNSUBSCRIBECHANGEEVENT;
data.StructSize = sizeof(data);
data.PluginId = *pd->PluginId;
lua_pushboolean(L, pd->Info->EditorControl(EditorId, command, 0, &data) != 0);
return 1;
}
// Item, Position = Menu (Properties, Items [, Breakkeys])
// Parameters:
// Properties -- a table
// Items -- an array of tables
// BreakKeys -- an array of strings with special syntax
// Return value:
// Item:
// a table -- the table of selected item (or of breakkey) is returned
// a nil -- menu canceled by the user
// Position:
// a number -- position of selected menu item
// a nil -- menu canceled by the user
static int far_Menu(lua_State *L)
{
enum {
POS_PROPS = 1, // properties
POS_ITEMS = 2, // items
POS_BKEYS = 3, // break keys
POS_STORE = 4, // temporary storage
};
TPluginData *pd = GetPluginData(L);
luaL_checktype(L, POS_PROPS, LUA_TTABLE);
luaL_checktype(L, POS_ITEMS, LUA_TTABLE);
intptr_t ItemsNumber = lua_objlen(L, POS_ITEMS);
lua_settop(L, POS_BKEYS); // cut unneeded parameters; make stack predictable
lua_newtable(L); // temporary store; at stack position 4
if (!lua_isnil(L,POS_BKEYS) && !lua_istable(L,POS_BKEYS) && lua_type(L,POS_BKEYS)!=LUA_TSTRING)
return luaL_argerror(L, POS_BKEYS, "must be table, string or nil");
// Properties
lua_pushvalue(L, POS_PROPS);
int X = GetOptIntFromTable(L, "X", -1);
int Y = GetOptIntFromTable(L, "Y", -1);
int MaxHeight = GetOptIntFromTable(L, "MaxHeight", 0);
UINT64 Flags = FMENU_WRAPMODE;
lua_getfield(L, POS_PROPS, "Flags");
if (!lua_isnil(L, -1)) Flags = CheckFlags(L, -1);
const wchar_t *Title = L"Menu";
lua_getfield(L, POS_PROPS, "Title");
if (lua_isstring(L,-1)) Title = StoreTempString(L, POS_STORE);
const wchar_t *Bottom = NULL;
lua_getfield(L, POS_PROPS, "Bottom");
if (lua_isstring(L,-1)) Bottom = StoreTempString(L, POS_STORE);
const wchar_t *HelpTopic = NULL;
lua_getfield(L, POS_PROPS, "HelpTopic");
if (lua_isstring(L,-1)) HelpTopic = StoreTempString(L, POS_STORE);
intptr_t SelectIndex = 0;
lua_getfield(L, POS_PROPS, "SelectIndex");
if ((SelectIndex = lua_tointeger(L,-1)) > ItemsNumber)
SelectIndex = 0;
const GUID* MenuGuid = NULL;
lua_getfield(L, POS_PROPS, "Id");
if (lua_type(L,-1)==LUA_TSTRING && lua_objlen(L,-1)==sizeof(GUID))
MenuGuid = (const GUID*)lua_tostring(L, -1);
lua_settop (L, POS_STORE);
// Items
struct FarMenuItem *Items =
(struct FarMenuItem*)lua_newuserdata(L, ItemsNumber*sizeof(struct FarMenuItem));
memset(Items, 0, ItemsNumber*sizeof(struct FarMenuItem));
struct FarMenuItem *pItem = Items;
for(int i=0; i < ItemsNumber; i++,pItem++,lua_pop(L,1))
{
static const char key[] = "text";
lua_pushinteger(L, i+1);
lua_gettable(L, POS_ITEMS);
if (lua_isstring(L, -1)) { // convert a string to a table element
lua_createtable(L, 0, 1);
lua_insert(L, -2);
lua_setfield(L, -2, key);
}
else if (!lua_istable(L, -1))
return luaLF_SlotError(L, i+1, "string or table");
//-------------------------------------------------------------------------
lua_getfield(L, -1, key);
if (lua_isstring(L,-1)) pItem->Text = StoreTempString(L, POS_STORE);
else if (!lua_isnil(L,-1)) return luaLF_FieldError(L, key, "string");
if (!pItem->Text)
lua_pop(L, 1);
//-------------------------------------------------------------------------
lua_getfield(L,-1,"checked");
if (lua_type(L,-1) == LUA_TSTRING)
{
const wchar_t* s = utf8_to_utf16(L,-1,NULL);
if (s) pItem->Flags |= s[0];
}
else if (lua_toboolean(L,-1)) pItem->Flags |= MIF_CHECKED;
lua_pop(L,1);
//-------------------------------------------------------------------------
if (GetBoolFromTable(L, "separator")) pItem->Flags |= MIF_SEPARATOR;
if (GetBoolFromTable(L, "disable")) pItem->Flags |= MIF_DISABLE;
if (GetBoolFromTable(L, "grayed")) pItem->Flags |= MIF_GRAYED;
if (GetBoolFromTable(L, "hidden")) pItem->Flags |= MIF_HIDDEN;
if (SelectIndex==0 && GetBoolFromTable(L, "selected")) pItem->Flags |= MIF_SELECTED;
//-------------------------------------------------------------------------
lua_getfield(L, -1, "AccelKey");
if (lua_istable(L, -1))
{
pItem->AccelKey.VirtualKeyCode = GetOptIntFromTable(L, "VirtualKeyCode", 0);
pItem->AccelKey.ControlKeyState = GetOptIntFromTable(L, "ControlKeyState", 0);
}
else if (lua_tostring(L, -1) && utf8_to_utf16(L, -1, NULL)) // lua_tostring is used on purpose
{
INPUT_RECORD Rec;
if (pd->FSF->FarNameToInputRecord((const wchar_t*)lua_touserdata(L,-1), &Rec)
&& Rec.EventType == KEY_EVENT)
{
pItem->AccelKey.VirtualKeyCode = Rec.Event.KeyEvent.wVirtualKeyCode;
pItem->AccelKey.ControlKeyState = Rec.Event.KeyEvent.dwControlKeyState;
}
}
lua_pop(L, 1);
}
if (SelectIndex > 0)
Items[SelectIndex-1].Flags |= MIF_SELECTED;
// Break Keys
intptr_t BreakCode = 0;
int NumBreakCodes = 0;
struct FarKey *pBreakKeys = NULL;
intptr_t *pBreakCode = NULL;
if (lua_type(L, POS_BKEYS) == LUA_TSTRING)
{
const char *q, *ptr = lua_tostring(L, POS_BKEYS);
lua_newtable(L);
while (*ptr)
{
while (isspace(*ptr)) ptr++;
if (*ptr == 0) break;
q = ptr++;
while(*ptr && !isspace(*ptr)) ptr++;
lua_createtable(L,0,1);
lua_pushlstring(L,q,ptr-q);
lua_setfield(L,-2,"BreakKey");
lua_rawseti(L,-2,++NumBreakCodes);
}
lua_replace(L, POS_BKEYS);
}
else
NumBreakCodes = lua_istable(L,POS_BKEYS) ? (int)lua_objlen(L,POS_BKEYS) : 0;
if (NumBreakCodes)
{
char buf[32];
int ind;
struct FarKey* BreakKeys = (struct FarKey*)lua_newuserdata(L, (1+NumBreakCodes)*sizeof(struct FarKey));
// get virtualkeys table from the registry; push it on top
lua_pushstring(L, FAR_VIRTUALKEYS);
lua_rawget(L, LUA_REGISTRYINDEX);
// push breakkeys table on top
lua_pushvalue(L, POS_BKEYS); // vk=-2; bk=-1;
for(ind=0; ind < NumBreakCodes; ind++)
{
DWORD mod = 0;
const char* s;
char* vk; // virtual key
WORD VirtualKeyCode;
BreakKeys[ind].VirtualKeyCode = 0xFF; // preset to invalid value !=0, since 0 marks end-of-array for Far.
BreakKeys[ind].ControlKeyState = LEFT_CTRL_PRESSED|LEFT_ALT_PRESSED|SHIFT_PRESSED;
// get next break key (optional modifier plus virtual key)
lua_pushinteger(L,ind+1); // vk=-3; bk=-2;
lua_gettable(L,-2); // vk=-3; bk=-2; bki=-1;
if (!lua_istable(L,-1)) { lua_pop(L,1); continue; }
lua_getfield(L, -1, "BreakKey");// vk=-4; bk=-3;bki=-2;bknm=-1;
if (!lua_isstring(L,-1)) { lua_pop(L,2); continue; }
// first try to use "Far key names" instead of "virtual key names"
if (utf8_to_utf16(L, -1, NULL))
{
INPUT_RECORD Rec;
if (pd->FSF->FarNameToInputRecord((const wchar_t*)lua_touserdata(L,-1), &Rec)
&& Rec.EventType == KEY_EVENT)
{
BreakKeys[ind].VirtualKeyCode = Rec.Event.KeyEvent.wVirtualKeyCode;
BreakKeys[ind].ControlKeyState = Rec.Event.KeyEvent.dwControlKeyState;
lua_pop(L, 2);
continue; // success
}
// restore the original string
lua_pop(L, 1);
lua_getfield(L, -1, "BreakKey");// vk=-4; bk=-3;bki=-2;bknm=-1;
}
// separate modifier and virtual key strings
s = lua_tostring(L,-1);
if (strlen(s) >= sizeof(buf)) { lua_pop(L,2); continue; }
strcpy(buf, s);
_strupr(buf);
vk = strchr(buf, '+'); // virtual key
if (vk)
{
*vk++ = '\0';
if (strchr(buf,'C')) mod |= LEFT_CTRL_PRESSED;
if (strchr(buf,'A')) mod |= LEFT_ALT_PRESSED;
if (strchr(buf,'S')) mod |= SHIFT_PRESSED;
}
else
vk = buf;
// replace on stack: break key name with virtual key name
lua_pop(L, 1);
lua_pushstring(L, vk); // vk=-4; bk=-3;bki=-2;vknm=-1;
// get virtual key and break key values
lua_rawget(L,-4); // vk=-4; bk=-3;
VirtualKeyCode = (WORD)lua_tointeger(L,-1);
if (VirtualKeyCode)
{
BreakKeys[ind].VirtualKeyCode = VirtualKeyCode;
BreakKeys[ind].ControlKeyState = mod;
}
lua_pop(L,2); // vk=-2; bk=-1;
}
BreakKeys[ind].VirtualKeyCode = 0; // required by FAR API
pBreakKeys = BreakKeys;
pBreakCode = &BreakCode;
}
intptr_t ret = pd->Info->Menu(pd->PluginId, MenuGuid, X, Y, MaxHeight, Flags, Title,
Bottom, HelpTopic, pBreakKeys, pBreakCode, Items, ItemsNumber);
if (NumBreakCodes && (BreakCode != -1))
{
lua_pushinteger(L, BreakCode+1);
lua_gettable(L, POS_BKEYS);
}
else if (ret == -1)
return lua_pushnil(L), 1;
else
{
lua_pushinteger(L, ret+1);
lua_gettable(L, POS_ITEMS);
}
lua_pushinteger(L, ret+1);
return 2;
}
// Return: -1 if escape pressed, else - button number chosen (0 based).
int LF_Message(lua_State *L,
const wchar_t* aMsg, // if multiline, then lines must be separated by '\n'
const wchar_t* aTitle,
const wchar_t* aButtons, // if multiple, then captions must be separated by ';'
const char* aFlags,
const wchar_t* aHelpTopic,
const GUID* aMessageGuid)
{
const wchar_t **items, **pItems;
wchar_t** allocLines;
int nAlloc;
wchar_t *lastDelim, *MsgCopy, *start, *pos;
TPluginData *pd = GetPluginData(L);
CONSOLE_SCREEN_BUFFER_INFO csbi;
HANDLE hnd = GetStdHandle(STD_OUTPUT_HANDLE);
int ret = GetConsoleScreenBufferInfo(hnd, &csbi);
const int max_len = ret ? csbi.srWindow.Right - csbi.srWindow.Left+1-14 : 66;
const int max_lines = ret ? csbi.srWindow.Bottom - csbi.srWindow.Top+1-5 : 20;
int num_lines = 0, num_buttons = 0;
UINT64 Flags = 0;
// Buttons
wchar_t *BtnCopy = NULL, *ptr = NULL;
int wrap = !(aFlags && strchr(aFlags, 'n'));
if (*aButtons == L';')
{
const wchar_t* p = aButtons + 1;
if (!_wcsicmp(p, L"Ok")) Flags = FMSG_MB_OK;
else if (!_wcsicmp(p, L"OkCancel")) Flags = FMSG_MB_OKCANCEL;
else if (!_wcsicmp(p, L"AbortRetryIgnore")) Flags = FMSG_MB_ABORTRETRYIGNORE;
else if (!_wcsicmp(p, L"YesNo")) Flags = FMSG_MB_YESNO;
else if (!_wcsicmp(p, L"YesNoCancel")) Flags = FMSG_MB_YESNOCANCEL;
else if (!_wcsicmp(p, L"RetryCancel")) Flags = FMSG_MB_RETRYCANCEL;
else
while(*aButtons == L';') aButtons++;
}
if (Flags == 0)
{
// Buttons: 1-st pass, determining number of buttons
BtnCopy = _wcsdup(aButtons);
ptr = BtnCopy;
while(*ptr && (num_buttons < 64))
{
while(*ptr == L';')
ptr++; // skip semicolons
if (*ptr)
{
++num_buttons;
ptr = wcschr(ptr, L';');
if (!ptr) break;
}
}
}
items = (const wchar_t**) malloc((1+max_lines+num_buttons) * sizeof(wchar_t*));
allocLines = (wchar_t**) malloc(max_lines * sizeof(wchar_t*)); // array of pointers to allocated lines
nAlloc = 0; // number of allocated lines
pItems = items;
// Title
*pItems++ = aTitle;
// Message lines
lastDelim = NULL;
MsgCopy = _wcsdup(aMsg);
start = pos = MsgCopy;
while(num_lines < max_lines)
{
if (*pos == 0) // end of the entire message
{
*pItems++ = start;
++num_lines;
break;
}
else if (*pos == L'\n') // end of a message line
{
*pItems++ = start;
*pos = L'\0';
++num_lines;
start = ++pos;
lastDelim = NULL;
}
else if (pos-start < max_len) // characters inside the line
{
if (wrap && !iswalnum(*pos) && *pos != L'_' && *pos != L'\'' && *pos != L'\"')
lastDelim = pos;
pos++;
}
else if (wrap) // the 1-st character beyond the line
{
size_t len;
wchar_t **q;
pos = lastDelim ? lastDelim+1 : pos;
len = pos - start;
q = &allocLines[nAlloc++]; // line allocation is needed
*pItems++ = *q = (wchar_t*) malloc((len+1)*sizeof(wchar_t));
wcsncpy(*q, start, len);
(*q)[len] = L'\0';
++num_lines;
start = pos;
lastDelim = NULL;
}
else
pos++;
}
if (*aButtons != L';')
{
// Buttons: 2-nd pass.
int i;
ptr = BtnCopy;
for(i=0; i < num_buttons; i++)
{
while(*ptr == L';')
++ptr;
if (*ptr)
{
*pItems++ = ptr;
ptr = wcschr(ptr, L';');
if (ptr)
*ptr++ = 0;
else
break;
}
else break;
}
}
// Flags
if (aFlags)
{
if (strchr(aFlags, 'w')) Flags |= FMSG_WARNING;
if (strchr(aFlags, 'e')) Flags |= FMSG_ERRORTYPE;
if (strchr(aFlags, 'k')) Flags |= FMSG_KEEPBACKGROUND;
if (strchr(aFlags, 'l')) Flags |= FMSG_LEFTALIGN;
}
// Id
if (aMessageGuid == NULL) aMessageGuid = pd->PluginId;
ret = (int)pd->Info->Message(pd->PluginId, aMessageGuid, Flags, aHelpTopic,
items, 1+num_lines+num_buttons, num_buttons);
free(BtnCopy);
while(nAlloc) free(allocLines[--nAlloc]);
free(allocLines);
free(MsgCopy);
free(CAST(void*, items));
return ret;
}
void LF_Error(lua_State *L, const wchar_t* aMsg)
{
PSInfo *Info = GetPluginData(L)->Info;
if (Info == NULL)
return;
if (!aMsg) aMsg = L"<non-string error message>";
lua_pushlstring(L, (const char*)Info->ModuleName, wcslen(Info->ModuleName)*sizeof(wchar_t));
lua_pushlstring(L, (const char*)L":\n", 4);
LF_Gsub(L, aMsg, L"\n\t", L"\n ");
lua_concat(L, 3);
LF_Message(L, (const wchar_t*)lua_tostring(L,-1), L"Error", L"OK", "wl", NULL, NULL);
lua_pop(L, 1);
}
// 1-st param: message text (if multiline, then lines must be separated by '\n')
// 2-nd param: message title (if absent or nil, then "Message" is used)
// 3-rd param: buttons (if multiple, then captions must be separated by ';';
// if absent or nil, then one button "OK" is used).
// 4-th param: flags
// 5-th param: help topic
// 6-th param: Id
// Return: -1 if escape pressed, else - button number chosen (1 based).
static int far_Message(lua_State *L)
{
int ret;
const wchar_t *Msg, *Title, *Buttons, *HelpTopic;
const char *Flags;
const GUID *Id;
luaL_checkany(L,1);
lua_settop(L,6);
Msg = NULL;
luaL_tolstring(L, 1, NULL);
Msg = check_utf8_string(L, -1, NULL);
lua_replace(L,1);
Title = opt_utf8_string(L, 2, L"Message");
Buttons = opt_utf8_string(L, 3, L";OK");
Flags = luaL_optstring(L, 4, "");
HelpTopic = opt_utf8_string(L, 5, NULL);
Id = (lua_type(L,6)==LUA_TSTRING && lua_objlen(L,6)==sizeof(GUID)) ?
(const GUID*)lua_tostring(L,6) : NULL;
ret = LF_Message(L, Msg, Title, Buttons, Flags, HelpTopic, Id);
lua_pushinteger(L, ret<0 ? ret : ret+1);
return 1;
}
static int panel_CheckPanelsExist(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle(L);
lua_pushboolean(L, (int)Info->PanelControl(handle, FCTL_CHECKPANELSEXIST, 0, 0));
return 1;
}
static int panel_ClosePanel(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle(L);
const wchar_t *dir = opt_utf8_string(L, 2, NULL);
lua_pushboolean(L, (int)Info->PanelControl(handle, FCTL_CLOSEPANEL, 0, (void*)dir));
return 1;
}
static int panel_GetPanelInfo(lua_State *L)
{
TPluginData *pd = GetPluginData(L);
HANDLE handle = OptHandle2(L);
struct PanelInfo pi;
pi.StructSize = sizeof(pi);
if (!pd->Info->PanelControl(handle, FCTL_GETPANELINFO, 0, &pi))
return lua_pushnil(L), 1;
lua_createtable(L, 0, 13);
//-------------------------------------------------------------------------
PutLStrToTable(L, "OwnerGuid", &pi.OwnerGuid, sizeof(GUID));
pi.PluginHandle ? lua_pushlightuserdata(L, pi.PluginHandle) : lua_pushnil(L);
lua_setfield(L, -2, "PluginHandle");
//-------------------------------------------------------------------------
if (0 == memcmp(&pi.OwnerGuid, pd->PluginId, sizeof(GUID)))
{
PushPluginObject(L, pi.PluginHandle);
lua_setfield(L, -2, "PluginObject");
}
//-------------------------------------------------------------------------
PutIntToTable(L, "PanelType", pi.PanelType);
//-------------------------------------------------------------------------
lua_createtable(L, 0, 4); // "PanelRect"
PutIntToTable(L, "left", pi.PanelRect.left);
PutIntToTable(L, "top", pi.PanelRect.top);
PutIntToTable(L, "right", pi.PanelRect.right);
PutIntToTable(L, "bottom", pi.PanelRect.bottom);
lua_setfield(L, -2, "PanelRect");
//-------------------------------------------------------------------------
PutIntToTable(L, "ItemsNumber", pi.ItemsNumber);
PutIntToTable(L, "SelectedItemsNumber", pi.SelectedItemsNumber);
//-------------------------------------------------------------------------
PutIntToTable(L, "CurrentItem", pi.CurrentItem + 1);
PutIntToTable(L, "TopPanelItem", pi.TopPanelItem + 1);
PutIntToTable(L, "ViewMode", pi.ViewMode);
PutIntToTable(L, "SortMode", pi.SortMode);
PutFlagsToTable(L, "Flags", pi.Flags);
//-------------------------------------------------------------------------
return 1;
}
static int get_panel_item(lua_State *L, int command)
{
struct FarGetPluginPanelItem fgppi = { sizeof(struct FarGetPluginPanelItem),0,0 };
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle2(L);
intptr_t index = luaL_optinteger(L,3,1) - 1;
if (index >= 0 || command == FCTL_GETCURRENTPANELITEM)
{
fgppi.Size = Info->PanelControl(handle, command, index, &fgppi);
if (fgppi.Size)
{
fgppi.Item = (struct PluginPanelItem*)lua_newuserdata(L, fgppi.Size);
if (Info->PanelControl(handle, command, index, &fgppi))
{
PushPanelItem(L, fgppi.Item, 0);
return 1;
}
}
}
return lua_pushnil(L), 1;
}
static int panel_GetPanelItem(lua_State *L)
{
return get_panel_item(L, FCTL_GETPANELITEM);
}
static int panel_GetSelectedPanelItem(lua_State *L)
{
return get_panel_item(L, FCTL_GETSELECTEDPANELITEM);
}
static int panel_GetCurrentPanelItem(lua_State *L)
{
return get_panel_item(L, FCTL_GETCURRENTPANELITEM);
}
static int get_string_info(lua_State *L, int command)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle2(L);
intptr_t size = Info->PanelControl(handle, command, 0, 0);
if (size)
{
wchar_t *buf = (wchar_t*)lua_newuserdata(L, size * sizeof(wchar_t));
if (Info->PanelControl(handle, command, size, buf))
{
push_utf8_string(L, buf, -1);
return 1;
}
}
return lua_pushnil(L), 1;
}
static int panel_GetPanelFormat(lua_State *L)
{
return get_string_info(L, FCTL_GETPANELFORMAT);
}
static int panel_GetPanelHostFile(lua_State *L)
{
return get_string_info(L, FCTL_GETPANELHOSTFILE);
}
static int panel_GetColumnTypes(lua_State *L)
{
return get_string_info(L, FCTL_GETCOLUMNTYPES);
}
static int panel_GetColumnWidths(lua_State *L)
{
return get_string_info(L, FCTL_GETCOLUMNWIDTHS);
}
static int panel_GetPanelPrefix(lua_State *L)
{
return get_string_info(L, FCTL_GETPANELPREFIX);
}
static int panel_RedrawPanel(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
void *param2 = NULL;
HANDLE handle = OptHandle2(L);
struct PanelRedrawInfo pri;
pri.StructSize = sizeof(pri);
if (lua_istable(L, 3))
{
param2 = &pri;
lua_getfield(L, 3, "CurrentItem");
pri.CurrentItem = lua_tointeger(L, -1) - 1;
lua_getfield(L, 3, "TopPanelItem");
pri.TopPanelItem = lua_tointeger(L, -1) - 1;
}
lua_pushboolean(L, Info->PanelControl(handle, FCTL_REDRAWPANEL, 0, param2) != 0);
return 1;
}
static int SetPanelBooleanProperty(lua_State *L, int command)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle2(L);
int param1 = lua_toboolean(L,3);
lua_pushboolean(L, Info->PanelControl(handle, command, param1, 0) != 0);
return 1;
}
static int SetPanelIntegerProperty(lua_State *L, int command)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle2(L);
int param1 = CAST(int, check_env_flag(L,3));
lua_pushboolean(L, Info->PanelControl(handle, command, param1, 0) != 0);
return 1;
}
static int panel_SetSortOrder(lua_State *L)
{
return SetPanelBooleanProperty(L, FCTL_SETSORTORDER);
}
static int panel_SetDirectoriesFirst(lua_State *L)
{
return SetPanelBooleanProperty(L, FCTL_SETDIRECTORIESFIRST);
}
static int panel_UpdatePanel(lua_State *L)
{
return SetPanelBooleanProperty(L, FCTL_UPDATEPANEL);
}
static int panel_SetSortMode(lua_State *L)
{
return SetPanelIntegerProperty(L, FCTL_SETSORTMODE);
}
static int panel_SetViewMode(lua_State *L)
{
return SetPanelIntegerProperty(L, FCTL_SETVIEWMODE);
}
static int panel_GetPanelDirectory(lua_State *L)
{
TPluginData *pd = GetPluginData(L);
HANDLE handle = OptHandle2(L);
intptr_t size = pd->Info->PanelControl(handle, FCTL_GETPANELDIRECTORY, 0, NULL);
if (size)
{
struct FarPanelDirectory *fpd = (struct FarPanelDirectory*)lua_newuserdata(L, size);
memset(fpd, 0, size);
fpd->StructSize = sizeof(*fpd);
if (pd->Info->PanelControl(handle, FCTL_GETPANELDIRECTORY, size, fpd))
{
lua_createtable(L, 0, 4);
PutWStrToTable(L, "Name", fpd->Name, -1);
PutWStrToTable(L, "Param", fpd->Param, -1);
PutWStrToTable(L, "File", fpd->File, -1);
PutLStrToTable(L, "PluginId", &fpd->PluginId, sizeof(fpd->PluginId));
return 1;
}
}
return lua_pushnil(L), 1;
}
static int panel_SetPanelDirectory(lua_State *L)
{
TPluginData *pd = GetPluginData(L);
struct FarPanelDirectory fpd;
HANDLE handle = OptHandle2(L);
memset(&fpd, 0, sizeof(fpd)); // also sets fpd.PluginId = FarId
fpd.StructSize = sizeof(fpd);
if (lua_istable(L, 3))
{
size_t len;
const GUID* id;
lua_getfield(L, 3, "PluginId");
id = (const GUID*)lua_tolstring(L, -1, &len);
if (id && len == sizeof(GUID)) fpd.PluginId = *id;
lua_getfield(L, 3, "Name");
if (lua_isstring(L, -1)) fpd.Name = check_utf8_string(L, -1, NULL);
lua_getfield(L, 3, "Param");
if (lua_isstring(L, -1)) fpd.Param = check_utf8_string(L, -1, NULL);
lua_getfield(L, 3, "File");
if (lua_isstring(L, -1)) fpd.File = check_utf8_string(L, -1, NULL);
}
else if (lua_isstring(L, 3))
fpd.Name = check_utf8_string(L, 3, NULL);
else
luaL_argerror(L, 3, "table or string");
lua_pushboolean(L, pd->Info->PanelControl(handle, FCTL_SETPANELDIRECTORY, 0, &fpd) != 0);
return 1;
}
static int panel_GetCmdLine(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle(L);
intptr_t size = Info->PanelControl(handle, FCTL_GETCMDLINE, 0, 0);
wchar_t *buf = (wchar_t*) malloc(size*sizeof(wchar_t));
Info->PanelControl(handle, FCTL_GETCMDLINE, size, buf);
push_utf8_string(L, buf, -1);
free(buf);
return 1;
}
static int panel_SetCmdLine(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle(L);
wchar_t* str = check_utf8_string(L, 2, NULL);
lua_pushboolean(L, Info->PanelControl(handle, FCTL_SETCMDLINE, 0, str) != 0);
return 1;
}
static int panel_GetCmdLinePos(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle(L);
int pos;
Info->PanelControl(handle, FCTL_GETCMDLINEPOS, 0, &pos) ?
lua_pushinteger(L, pos+1) : lua_pushnil(L);
return 1;
}
static int panel_SetCmdLinePos(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle(L);
intptr_t pos = luaL_checkinteger(L, 2) - 1;
intptr_t ret = Info->PanelControl(handle, FCTL_SETCMDLINEPOS, pos, 0);
return lua_pushboolean(L, ret != 0), 1;
}
static int panel_InsertCmdLine(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle(L);
wchar_t* str = check_utf8_string(L, 2, NULL);
lua_pushboolean(L, Info->PanelControl(handle, FCTL_INSERTCMDLINE, 0, str) != 0);
return 1;
}
static int panel_GetCmdLineSelection(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle(L);
struct CmdLineSelect cms;
cms.StructSize = sizeof(cms);
if (Info->PanelControl(handle, FCTL_GETCMDLINESELECTION, 0, &cms))
{
if (cms.SelStart < 0) cms.SelStart = 0;
if (cms.SelEnd < 0) cms.SelEnd = 0;
lua_pushinteger(L, cms.SelStart + 1);
lua_pushinteger(L, cms.SelEnd);
return 2;
}
return lua_pushnil(L), 1;
}
static int panel_SetCmdLineSelection(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle(L);
struct CmdLineSelect cms;
cms.StructSize = sizeof(cms);
cms.SelStart = luaL_checkinteger(L, 2) - 1;
cms.SelEnd = luaL_checkinteger(L, 3);
if (cms.SelStart < -1) cms.SelStart = -1;
if (cms.SelEnd < -1) cms.SelEnd = -1;
lua_pushboolean(L, Info->PanelControl(handle, FCTL_SETCMDLINESELECTION, 0, &cms) != 0);
return 1;
}
// CtrlSetSelection (handle, whatpanel, items, selection)
// CtrlClearSelection (handle, whatpanel, items)
// handle: handle
// whatpanel: 1=active_panel, 0=inactive_panel
// items: either number of an item, or a list of item numbers
// selection: boolean
static int ChangePanelSelection(lua_State *L, BOOL op_set)
{
PSInfo *Info = GetPluginData(L)->Info;
intptr_t itemindex = -1, numItems, command;
intptr_t state;
struct PanelInfo pi;
HANDLE handle = OptHandle2(L);
if (lua_isnumber(L,3))
{
itemindex = lua_tointeger(L,3) - 1;
if (itemindex < 0) return luaL_argerror(L, 3, "non-positive index");
}
else if (!lua_istable(L,3))
return luaL_typerror(L, 3, "number or table");
state = op_set ? lua_toboolean(L,4) : 0;
// get panel info
pi.StructSize = sizeof(pi);
if (!Info->PanelControl(handle, FCTL_GETPANELINFO, 0, &pi) ||
(pi.PanelType != PTYPE_FILEPANEL))
return lua_pushboolean(L,0), 1;
numItems = op_set ? pi.ItemsNumber : pi.SelectedItemsNumber;
command = op_set ? FCTL_SETSELECTION : FCTL_CLEARSELECTION;
if (itemindex >= 0 && itemindex < numItems)
Info->PanelControl(handle, command, itemindex, (void*)state);
else
{
intptr_t i, len = lua_objlen(L,3);
for(i=1; i<=len; i++)
{
lua_pushinteger(L, i);
lua_gettable(L,3);
if (lua_isnumber(L,-1))
{
itemindex = lua_tointeger(L,-1) - 1;
if (itemindex >= 0 && itemindex < numItems)
Info->PanelControl(handle, command, itemindex, (void*)state);
}
lua_pop(L,1);
}
}
return lua_pushboolean(L,1), 1;
}
static int panel_SetSelection(lua_State *L)
{
return ChangePanelSelection(L, TRUE);
}
static int panel_ClearSelection(lua_State *L)
{
return ChangePanelSelection(L, FALSE);
}
static int panel_BeginSelection(lua_State *L)
{
intptr_t res = GetPluginData(L)->Info->PanelControl(OptHandle2(L), FCTL_BEGINSELECTION, 0, 0);
return lua_pushboolean(L, (int)res), 1;
}
static int panel_EndSelection(lua_State *L)
{
intptr_t res = GetPluginData(L)->Info->PanelControl(OptHandle2(L), FCTL_ENDSELECTION, 0, 0);
return lua_pushboolean(L, (int)res), 1;
}
// CtrlSetUserScreen (handle, scrolltype)
// handle: FALSE=INVALID_HANDLE_VALUE, TRUE=lua_State*
static int panel_SetUserScreen(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle(L);
intptr_t scrolltype = luaL_optinteger(L,2,0);
int ret = Info->PanelControl(handle, FCTL_SETUSERSCREEN, scrolltype, 0) != 0;
lua_pushboolean(L, ret);
return 1;
}
// CtrlGetUserScreen (handle, scrolltype)
// handle: FALSE=INVALID_HANDLE_VALUE, TRUE=lua_State*
static int panel_GetUserScreen(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle(L);
intptr_t scrolltype = luaL_optinteger(L,2,0);
int ret = Info->PanelControl(handle, FCTL_GETUSERSCREEN, scrolltype, 0) != 0;
lua_pushboolean(L, ret);
return 1;
}
static int panel_IsActivePanel(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle(L);
lua_pushboolean(L, Info->PanelControl(handle, FCTL_ISACTIVEPANEL, 0, 0) != 0);
return 1;
}
static int panel_SetActivePanel(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE handle = OptHandle2(L);
lua_pushboolean(L, Info->PanelControl(handle, FCTL_SETACTIVEPANEL, 0, 0) != 0);
return 1;
}
// GetDirList (Dir)
// Dir: Name of the directory to scan (full pathname).
static int far_GetDirList(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
const wchar_t *Dir = check_utf8_string(L, 1, NULL);
struct PluginPanelItem *PanelItems;
size_t ItemsNumber;
if (Info->GetDirList(Dir, &PanelItems, &ItemsNumber))
{
int i;
lua_createtable(L, (int)ItemsNumber, 0); // "PanelItems"
for(i=0; i < (int)ItemsNumber; i++)
{
PushPanelItem(L, PanelItems + i, 0);
lua_rawseti(L, -2, i+1);
}
Info->FreeDirList(PanelItems, ItemsNumber);
}
else
lua_pushnil(L);
return 1;
}
// GetPluginDirList (hPanel, Dir)
// hPanel: Panel handle.
// Dir: Name of the directory to scan (full pathname).
static int far_GetPluginDirList(lua_State *L)
{
TPluginData *pd = GetPluginData(L);
HANDLE handle = OptHandle(L);
const wchar_t *Dir = check_utf8_string(L, 2, NULL);
struct PanelInfo pi;
pi.StructSize = sizeof(pi);
if (handle && pd->Info->PanelControl(handle, FCTL_GETPANELINFO, 0, &pi) && (pi.Flags & PFLAGS_PLUGIN))
{
struct PluginPanelItem *PanelItems;
size_t ItemsNumber;
if (pd->Info->GetPluginDirList(&pi.OwnerGuid, handle, Dir, &PanelItems, &ItemsNumber))
{
PushPanelItems(L, PanelItems, ItemsNumber, 0);
pd->Info->FreePluginDirList(handle, PanelItems, ItemsNumber);
return 1;
}
}
lua_pushnil(L);
return 1;
}
static int SavedScreen_tostring (lua_State *L)
{
void **pp = (void**)luaL_checkudata(L, 1, SavedScreenType);
if (*pp)
lua_pushfstring(L, "%s (%p)", SavedScreenType, *pp);
else
lua_pushfstring(L, "%s (freed)", SavedScreenType);
return 1;
}
// RestoreScreen (handle)
// handle: handle of saved screen.
static int far_RestoreScreen(lua_State *L)
{
if (lua_isnoneornil(L, 1))
GetPluginData(L)->Info->RestoreScreen(NULL);
else
{
void **pp = (void**)luaL_checkudata(L, 1, SavedScreenType);
if (*pp)
{
GetPluginData(L)->Info->RestoreScreen(*pp);
*pp = NULL;
}
}
return 0;
}
// FreeScreen (handle)
// handle: handle of saved screen.
static int far_FreeScreen(lua_State *L)
{
void **pp = (void**)luaL_checkudata(L, 1, SavedScreenType);
if (*pp)
{
GetPluginData(L)->Info->FreeScreen(*pp);
*pp = NULL;
}
return 0;
}
// handle = SaveScreen (X1,Y1,X2,Y2)
// handle: handle of saved screen, [lightuserdata]
static int far_SaveScreen(lua_State *L)
{
intptr_t X1 = luaL_optinteger(L,1,0);
intptr_t Y1 = luaL_optinteger(L,2,0);
intptr_t X2 = luaL_optinteger(L,3,-1);
intptr_t Y2 = luaL_optinteger(L,4,-1);
*(void**)lua_newuserdata(L, sizeof(void*)) = GetPluginData(L)->Info->SaveScreen(X1,Y1,X2,Y2);
luaL_getmetatable(L, SavedScreenType);
lua_setmetatable(L, -2);
return 1;
}
static UINT64 GetDialogItemType(lua_State* L, int key, int item)
{
int success;
UINT64 iType;
lua_pushinteger(L, key);
lua_gettable(L, -2);
iType = get_env_flag(L, -1, &success);
if (!success)
{
const char* sType = lua_tostring(L, -1);
return luaL_error(L, "%s - unsupported type in dialog item %d", sType, item);
}
lua_pop(L, 1);
return iType;
}
// the table is on lua stack top
static UINT64 GetItemFlags(lua_State* L, int flag_index, int item_index)
{
UINT64 flags;
int success;
lua_pushinteger(L, flag_index);
lua_gettable(L, -2);
flags = GetFlagCombination(L, -1, &success);
if (!success)
return luaL_error(L, "unsupported flag in dialog item %d", item_index);
lua_pop(L, 1);
return flags;
}
// list table is on Lua stack top
struct FarList* CreateList(lua_State *L, int historyindex)
{
int i, n = (int)lua_objlen(L,-1);
struct FarList* list = (struct FarList*)lua_newuserdata(L,
sizeof(struct FarList) + n*sizeof(struct FarListItem)); // +2
int len = (int)lua_objlen(L, historyindex);
lua_rawseti(L, historyindex, ++len); // +1; put into "histories" table to avoid being gc'ed
list->StructSize = sizeof(struct FarList);
list->ItemsNumber = n;
list->Items = (struct FarListItem*)(list+1);
for(i=0; i<n; i++)
{
struct FarListItem *p = list->Items + i;
lua_pushinteger(L, i+1); // +2
lua_gettable(L,-2); // +2
if (lua_type(L,-1) != LUA_TTABLE)
luaL_error(L, "value at index %d is not a table", i+1);
p->Text = NULL;
lua_getfield(L, -1, "Text"); // +3
if (lua_isstring(L,-1))
{
lua_pushvalue(L,-1); // +4
p->Text = check_utf8_string(L,-1,NULL); // +4
lua_rawseti(L, historyindex, ++len); // +3
}
lua_pop(L, 1); // +2
p->Flags = CheckFlagsFromTable(L, -1, "Flags");
lua_pop(L, 1); // +1
}
return list;
}
static void PushList (lua_State *L, const struct FarList *list)
{
int i;
lua_createtable(L, (int)list->ItemsNumber, 0);
for (i=0; i<(int)list->ItemsNumber; i++)
{
lua_createtable(L,0,2);
PutFlagsToTable(L, "Flags", list->Items[i].Flags);
PutWStrToTable(L, "Text", list->Items[i].Text, -1);
lua_rawseti(L,-2,i+1);
if (list->Items[i].Flags & LIF_SELECTED)
PutIntToTable(L, "SelectIndex", i+1);
}
}
// enum FARDIALOGITEMTYPES Type; 1
// intptr_t X1,Y1,X2,Y2; 2,3,4,5
// union
// {
// intptr_t Selected; 6
// struct FarList *ListItems; 6
// struct FAR_CHAR_INFO *VBuf; 6
// intptr_t Reserved0; 6
// }
//#ifndef __cplusplus
// Param
//#endif
// ;
// const wchar_t *History; 7
// const wchar_t *Mask; 8
// FARDIALOGITEMFLAGS Flags; 9
// const wchar_t *Data; 10
// size_t MaxLength; 11 // terminate 0 not included (if == 0 string size is unlimited)
// intptr_t UserData; 12
// intptr_t Reserved[2];
// item table is on Lua stack top
static void SetFarDialogItem(lua_State *L, struct FarDialogItem* Item, int itemindex,
int historyindex)
{
int len;
memset(Item, 0, sizeof(struct FarDialogItem));
Item->Type = GetDialogItemType(L, 1, itemindex+1);
Item->X1 = GetIntFromArray(L, 2);
Item->Y1 = GetIntFromArray(L, 3);
Item->X2 = GetIntFromArray(L, 4);
Item->Y2 = GetIntFromArray(L, 5);
Item->Flags = GetItemFlags(L, 9, itemindex+1);
if (Item->Type==DI_LISTBOX || Item->Type==DI_COMBOBOX)
{
int SelectIndex;
lua_rawgeti(L, -1, 6); // +1
if (lua_type(L,-1) != LUA_TTABLE)
luaLF_SlotError(L, 6, "table");
Item->Param.ListItems = CreateList(L, historyindex);
SelectIndex = GetOptIntFromTable(L, "SelectIndex", -1);
if (SelectIndex > 0 && SelectIndex <= (int)lua_objlen(L,-1))
Item->Param.ListItems->Items[SelectIndex-1].Flags |= LIF_SELECTED;
lua_pop(L,1); // 0
}
else if (Item->Type == DI_USERCONTROL)
{
lua_rawgeti(L, -1, 6);
if (lua_type(L,-1) == LUA_TUSERDATA)
{
TFarUserControl* fuc = CheckFarUserControl(L, -1);
Item->Param.VBuf = fuc->VBuf;
}
lua_pop(L,1);
}
else
Item->Param.Selected = GetIntFromArray(L, 6);
//---------------------------------------------------------------------------
if (Item->Flags & DIF_HISTORY)
{
lua_rawgeti(L, -1, 7); // +1
Item->History = opt_utf8_string(L, -1, NULL); // +1
len = (int)lua_objlen(L, historyindex);
lua_rawseti(L, historyindex, len+1); // +0; put into "histories" table to avoid being gc'ed
}
//---------------------------------------------------------------------------
lua_rawgeti(L, -1, 8); // +1
Item->Mask = opt_utf8_string(L, -1, NULL); // +1
len = (int)lua_objlen(L, historyindex);
lua_rawseti(L, historyindex, len+1); // +0; put into "histories" table to avoid being gc'ed
//---------------------------------------------------------------------------
Item->MaxLength = GetOptIntFromArray(L, 11, 0);
lua_pushinteger(L, 10); // +1
lua_gettable(L, -2); // +1
if (lua_isstring(L, -1))
{
Item->Data = check_utf8_string(L, -1, NULL); // +1
len = (int)lua_objlen(L, historyindex);
lua_rawseti(L, historyindex, len+1); // +0; put into "histories" table to avoid being gc'ed
}
else
lua_pop(L, 1);
//---------------------------------------------------------------------------
lua_rawgeti(L, -1, 12);
Item->UserData = lua_tointeger(L, -1);
lua_pop(L, 1);
}
static void PushDlgItem(lua_State *L, const struct FarDialogItem* pItem, BOOL table_exist)
{
if (! table_exist)
lua_createtable(L, 12, 0);
PutIntToArray(L, 1, pItem->Type);
PutIntToArray(L, 2, pItem->X1);
PutIntToArray(L, 3, pItem->Y1);
PutIntToArray(L, 4, pItem->X2);
PutIntToArray(L, 5, pItem->Y2);
if ((pItem->Type == DI_LISTBOX || pItem->Type == DI_COMBOBOX) && pItem->Param.ListItems)
{
PushList(L, pItem->Param.ListItems);
lua_rawseti(L, -2, 6);
}
else if (pItem->Type == DI_USERCONTROL)
{
lua_pushinteger(L, 6);
lua_pushlightuserdata(L, pItem->Param.VBuf);
lua_settable(L, -3);
}
else
PutIntToArray(L, 6, pItem->Param.Selected);
PutWStrToArray(L, 7, pItem->History, -1);
PutWStrToArray(L, 8, pItem->Mask, -1);
PutFlagsToArray(L, 9, pItem->Flags);
lua_pushinteger(L, 10);
push_utf8_string(L, pItem->Data, -1);
lua_settable(L, -3);
PutIntToArray(L, 11, pItem->MaxLength);
lua_pushinteger(L, 12);
lua_pushinteger(L, pItem->UserData);
lua_rawset(L, -3);
}
static void PushDlgItemNum(lua_State *L, HANDLE hDlg, int numitem, int pos_table,
PSInfo *Info)
{
struct FarGetDialogItem fgdi = { sizeof(struct FarGetDialogItem), 0, 0 };
fgdi.Size = Info->SendDlgMessage(hDlg, DM_GETDLGITEM, numitem, &fgdi);
if (fgdi.Size > 0)
{
BOOL table_exist;
fgdi.Item = (struct FarDialogItem*) lua_newuserdata(L, fgdi.Size);
Info->SendDlgMessage(hDlg, DM_GETDLGITEM, numitem, &fgdi);
table_exist = lua_istable(L, pos_table);
if (table_exist)
lua_pushvalue(L, pos_table);
PushDlgItem(L, fgdi.Item, table_exist);
lua_remove(L, -2);
}
else
lua_pushnil(L);
}
static int SetDlgItem(lua_State *L, HANDLE hDlg, int numitem, int pos_table,
PSInfo *Info)
{
struct FarDialogItem DialogItem;
lua_newtable(L);
lua_replace(L,1);
luaL_checktype(L, pos_table, LUA_TTABLE);
lua_pushvalue(L, pos_table);
SetFarDialogItem(L, &DialogItem, numitem, 1);
lua_pushboolean(L, (int)Info->SendDlgMessage(hDlg, DM_SETDLGITEM, numitem, &DialogItem));
return 1;
}
TDialogData* NewDialogData(lua_State* L, PSInfo *Info, HANDLE hDlg, BOOL isOwned)
{
TDialogData *dd = (TDialogData*) lua_newuserdata(L, sizeof(TDialogData));
dd->L = GetPluginData(L)->MainLuaState;
dd->Info = Info;
dd->hDlg = hDlg;
dd->isOwned = isOwned;
dd->wasError = FALSE;
dd->isModal = TRUE;
dd->dataRef = LUA_REFNIL;
luaL_getmetatable(L, FarDialogType);
lua_setmetatable(L, -2);
if (isOwned)
{
lua_newtable(L);
lua_setfenv(L, -2);
}
return dd;
}
TDialogData* CheckDialog(lua_State* L, int pos)
{
return (TDialogData*)luaL_checkudata(L, pos, FarDialogType);
}
TDialogData* CheckValidDialog(lua_State* L, int pos)
{
TDialogData* dd = CheckDialog(L, pos);
luaL_argcheck(L, dd->hDlg != INVALID_HANDLE_VALUE, pos, "closed dialog");
return dd;
}
HANDLE CheckDialogHandle(lua_State* L, int pos)
{
return CheckValidDialog(L, pos)->hDlg;
}
int DialogHandleEqual(lua_State* L)
{
TDialogData* dd1 = CheckDialog(L, 1);
TDialogData* dd2 = CheckDialog(L, 2);
lua_pushboolean(L, dd1->hDlg == dd2->hDlg);
return 1;
}
int PushDMParams (lua_State *L, intptr_t Msg, intptr_t Param1)
{
if (! ((Msg>DM_FIRST && Msg<=DM_GETDIALOGTITLE) || Msg==DM_USER))
return 0;
lua_pushinteger(L, Msg); //+1
// Param1
switch(Msg)
{
case DM_CLOSE:
lua_pushinteger(L, Param1<=0 ? Param1 : Param1+1);
break;
case DM_ENABLEREDRAW:
case DM_GETDIALOGINFO:
case DM_GETDIALOGTITLE:
case DM_GETDLGDATA:
case DM_GETDLGRECT:
case DM_GETDROPDOWNOPENED:
case DM_GETFOCUS:
case DM_KEY:
case DM_MOVEDIALOG:
case DM_REDRAW:
case DM_RESIZEDIALOG:
case DM_SETDLGDATA:
case DM_SETINPUTNOTIFY:
case DM_SHOWDIALOG:
case DM_USER:
lua_pushinteger(L, Param1);
break;
default: // dialog element position
lua_pushinteger(L, Param1+1);
break;
}
return 1;
}
static int DoSendDlgMessage (lua_State *L, intptr_t Msg, int delta)
{
typedef struct { void *Id; int Ref; } listdata_t;
TPluginData *pluginData = GetPluginData(L);
PSInfo *Info = pluginData->Info;
intptr_t Param1=0, res=0, res_incr=0;
void* Param2 = NULL;
wchar_t buf[512];
int pos2 = 2-delta, pos3 = 3-delta, pos4 = 4-delta;
//---------------------------------------------------------------------------
COORD coord;
SMALL_RECT small_rect;
//---------------------------------------------------------------------------
lua_settop(L, pos4); //many cases below rely on top==pos4
HANDLE hDlg = CheckDialogHandle(L, 1);
if (delta == 0)
Msg = CAST(int, check_env_flag(L, 2));
// Param1
switch(Msg)
{
case DM_CLOSE:
Param1 = luaL_optinteger(L,pos3,-1);
if (Param1>0) --Param1;
break;
case DM_GETDLGDATA:
case DM_SETDLGDATA:
break;
case DM_ENABLEREDRAW:
case DM_GETDIALOGINFO:
case DM_GETDIALOGTITLE:
case DM_GETDLGRECT:
case DM_GETDROPDOWNOPENED:
case DM_GETFOCUS:
case DM_KEY:
case DM_MOVEDIALOG:
case DM_REDRAW:
case DM_RESIZEDIALOG:
case DM_SETINPUTNOTIFY:
case DM_SHOWDIALOG:
case DM_USER:
// DN_*
case DN_DRAGGED:
case DN_DRAWDIALOG:
case DN_DRAWDIALOGDONE:
Param1 = luaL_optinteger(L,pos3,0);
break;
default: // dialog element position
Param1 = luaL_optinteger(L,pos3,1) - 1;
break;
}
// res_incr
switch(Msg)
{
case DM_GETFOCUS:
case DM_LISTADDSTR:
res_incr=1;
break;
default:
res_incr=0;
break;
}
switch(Msg)
{
default:
luaL_argerror(L, pos2, "operation not implemented");
break;
case DM_CLOSE:
case DM_EDITUNCHANGEDFLAG:
case DM_ENABLE:
case DM_ENABLEREDRAW:
case DM_GETCHECK:
case DM_GETCOMBOBOXEVENT:
case DM_GETCURSORSIZE:
case DM_GETDROPDOWNOPENED:
case DM_GETFOCUS:
case DM_GETITEMDATA:
case DM_LISTSORT:
case DM_REDRAW: // alias: DM_SETREDRAW
case DM_SET3STATE:
case DM_SETCURSORSIZE:
case DM_SETDROPDOWNOPENED:
case DM_SETFOCUS:
case DM_SETITEMDATA:
case DM_SETMAXTEXTLENGTH: // alias: DM_SETTEXTLENGTH
case DM_SETINPUTNOTIFY:
case DM_SHOWDIALOG:
case DM_SHOWITEM:
case DM_USER:
// DN_*
case DN_BTNCLICK:
case DN_DRAGGED:
case DN_DRAWDIALOG:
case DN_DRAWDIALOGDONE:
case DN_DROPDOWNOPENED:
Param2 = (void*)(intptr_t)luaL_optint(L,pos4,0);
break;
case DM_LISTGETDATASIZE:
Param2 = (void*)(intptr_t)(luaL_optint(L,pos4,1) - 1);
break;
case DM_LISTADDSTR:
case DM_ADDHISTORY:
case DM_SETHISTORY:
case DM_SETTEXTPTR:
Param2 = (void*)opt_utf8_string(L, pos4, NULL);
break;
case DM_SETCHECK:
res = lua_isboolean(L,pos4) ? (lua_toboolean(L,pos4) ? BSTATE_CHECKED : BSTATE_UNCHECKED)
: check_env_flag(L, pos4);
Param2 = (void*) res;
break;
case DM_GETCURSORPOS:
if (Info->SendDlgMessage(hDlg, Msg, Param1, &coord))
{
lua_createtable(L,0,2);
PutNumToTable(L, "X", coord.X);
PutNumToTable(L, "Y", coord.Y);
return 1;
}
return lua_pushnil(L), 1;
case DM_GETDIALOGINFO:
{
struct DialogInfo dlg_info;
dlg_info.StructSize = sizeof(dlg_info);
if (Info->SendDlgMessage(hDlg, Msg, Param1, &dlg_info))
{
lua_createtable(L,0,2);
PutLStrToTable(L, "Id", (const char*)&dlg_info.Id, sizeof(dlg_info.Id));
PutLStrToTable(L, "Owner", (const char*)&dlg_info.Owner, sizeof(dlg_info.Owner));
return 1;
}
return lua_pushnil(L), 1;
}
case DM_GETDLGDATA: {
TDialogData *dd = (TDialogData*) Info->SendDlgMessage(hDlg,Msg,0,0);
lua_rawgeti(L, LUA_REGISTRYINDEX, dd->dataRef);
return 1;
}
case DM_SETDLGDATA: {
TDialogData *dd = (TDialogData*) Info->SendDlgMessage(hDlg,DM_GETDLGDATA,0,0);
lua_rawgeti(L, LUA_REGISTRYINDEX, dd->dataRef);
luaL_unref(L, LUA_REGISTRYINDEX, dd->dataRef);
lua_pushvalue(L, pos3);
dd->dataRef = luaL_ref(L, LUA_REGISTRYINDEX);
return 1;
}
case DM_GETDLGRECT:
case DM_GETITEMPOSITION:
if (Info->SendDlgMessage(hDlg, Msg, Param1, &small_rect))
{
lua_createtable(L,0,4);
PutNumToTable(L, "Left", small_rect.Left);
PutNumToTable(L, "Top", small_rect.Top);
PutNumToTable(L, "Right", small_rect.Right);
PutNumToTable(L, "Bottom", small_rect.Bottom);
return 1;
}
return lua_pushnil(L), 1;
case DM_GETEDITPOSITION:
{
struct EditorSetPosition esp;
esp.StructSize = sizeof(esp);
if (Info->SendDlgMessage(hDlg, Msg, Param1, &esp))
return PushEditorSetPosition(L, &esp), 1;
return lua_pushnil(L), 1;
}
case DM_GETSELECTION:
{
struct EditorSelect es;
es.StructSize = sizeof(es);
if (Info->SendDlgMessage(hDlg, Msg, Param1, &es))
{
lua_createtable(L,0,5);
PutNumToTable(L, "BlockType", (double) es.BlockType);
PutNumToTable(L, "BlockStartLine", (double) es.BlockStartLine+1);
PutNumToTable(L, "BlockStartPos", (double) es.BlockStartPos+1);
PutNumToTable(L, "BlockWidth", (double) es.BlockWidth);
PutNumToTable(L, "BlockHeight", (double) es.BlockHeight);
return 1;
}
return lua_pushnil(L), 1;
}
case DM_SETSELECTION:
{
struct EditorSelect es;
es.StructSize = sizeof(es);
luaL_checktype(L, pos4, LUA_TTABLE);
if (FillEditorSelect(L, pos4, &es))
lua_pushinteger(L, Info->SendDlgMessage(hDlg, Msg, Param1, &es));
else
lua_pushinteger(L,0);
return 1;
}
case DM_GETTEXT:
case DM_GETDIALOGTITLE:
{
struct FarDialogItemData fdid;
size_t size;
fdid.StructSize = sizeof(fdid);
fdid.PtrLength = (size_t) Info->SendDlgMessage(hDlg, Msg, Param1, NULL);
fdid.PtrData = (wchar_t*) malloc((fdid.PtrLength+1) * sizeof(wchar_t));
size = Info->SendDlgMessage(hDlg, Msg, Param1, &fdid);
push_utf8_string(L, size?fdid.PtrData:L"", size);
free(fdid.PtrData);
return 1;
}
case DM_GETCONSTTEXTPTR:
{
wchar_t *ptr = (wchar_t*)Info->SendDlgMessage(hDlg, Msg, Param1, 0);
push_utf8_string(L, ptr ? ptr:L"", -1);
return 1;
}
case DM_SETTEXT:
{
struct FarDialogItemData fdid;
fdid.StructSize = sizeof(fdid);
fdid.PtrLength = 0;
fdid.PtrData = (wchar_t*)check_utf8_string(L, pos4, &fdid.PtrLength);
lua_pushinteger(L, Info->SendDlgMessage(hDlg, Msg, Param1, &fdid));
return 1;
}
case DM_KEY:
{
size_t i, count;
INPUT_RECORD *arr;
if (lua_istable(L,pos4))
{
count = lua_objlen(L, pos4);
arr = (INPUT_RECORD*)lua_newuserdata(L, count * sizeof(INPUT_RECORD));
for(i=0; i<count; i++)
{
lua_pushinteger(L,i+1);
lua_gettable(L,pos4);
if (!lua_istable(L,-1))
{
luaL_error(L, "element #%d in argument #%d is not a table", i+1, pos4);
}
FillInputRecord(L, -1, arr+i);
lua_pop(L,1);
}
lua_pushinteger(L, Info->SendDlgMessage(hDlg, Msg, count, arr));
}
else if (lua_isstring(L,pos4))
{
wchar_t *str = check_utf8_string(L,pos4,NULL);
wchar_t *p, *q;
for (p=str,count=0; *p; count++)
{
while(iswspace(*p)) p++;
if (*p == 0) break;
while(*p && !iswspace(*p)) p++;
}
arr = (INPUT_RECORD*)lua_newuserdata(L, count * sizeof(INPUT_RECORD));
for(i=0,p=str; i<count; i++)
{
while(iswspace(*p)) p++;
q = p;
while(*p && !iswspace(*p)) p++;
*p++ = 0;
if (!pluginData->FSF->FarNameToInputRecord(q, arr+i))
luaL_argerror(L, pos4, "invalid key");
}
lua_pushinteger(L, Info->SendDlgMessage(hDlg, Msg, count, arr));
}
else
luaL_typerror(L, pos4, "table or string");
return 1;
}
case DM_LISTADD:
case DM_LISTSET:
{
luaL_checktype(L, pos4, LUA_TTABLE);
lua_createtable(L,1,0); // "history table"
lua_replace(L,1);
lua_settop(L,pos4);
Param2 = CreateList(L, 1);
break;
}
case DM_LISTDELETE:
{
struct FarListDelete fld;
fld.StructSize = sizeof(fld);
if (lua_isnoneornil(L, pos4))
lua_pushinteger(L, Info->SendDlgMessage(hDlg, Msg, Param1, NULL));
else
{
luaL_checktype(L, pos4, LUA_TTABLE);
fld.StartIndex = GetOptIntFromTable(L, "StartIndex", 1) - 1;
fld.Count = GetOptIntFromTable(L, "Count", 1);
lua_pushinteger(L, Info->SendDlgMessage(hDlg, Msg, Param1, &fld));
}
return 1;
}
case DM_LISTFINDSTRING:
{
struct FarListFind flf;
flf.StructSize = sizeof(flf);
luaL_checktype(L, pos4, LUA_TTABLE);
flf.StartIndex = GetOptIntFromTable(L, "StartIndex", 1) - 1;
lua_getfield(L, pos4, "Pattern");
flf.Pattern = check_utf8_string(L, -1, NULL);
lua_getfield(L, pos4, "Flags");
flf.Flags = get_env_flag(L, -1, NULL);
res = Info->SendDlgMessage(hDlg, Msg, Param1, &flf);
res < 0 ? lua_pushnil(L) : lua_pushinteger(L, res+1);
return 1;
}
case DM_LISTGETCURPOS:
{
struct FarListPos flp;
flp.StructSize = sizeof(flp);
Info->SendDlgMessage(hDlg, Msg, Param1, &flp);
lua_createtable(L,0,2);
PutIntToTable(L, "SelectPos", flp.SelectPos+1);
PutIntToTable(L, "TopPos", flp.TopPos+1);
return 1;
}
case DM_LISTGETITEM:
{
struct FarListGetItem flgi;
flgi.StructSize = sizeof(flgi);
flgi.ItemIndex = luaL_checkinteger(L, pos4) - 1;
if (Info->SendDlgMessage(hDlg, Msg, Param1, &flgi))
{
lua_createtable(L,0,2);
PutFlagsToTable(L, "Flags", flgi.Item.Flags);
PutWStrToTable(L, "Text", flgi.Item.Text, -1);
return 1;
}
return lua_pushnil(L), 1;
}
case DM_LISTGETTITLES:
{
struct FarListTitles flt;
flt.StructSize = sizeof(flt);
flt.Title = buf;
flt.Bottom = buf + ARRSIZE(buf)/2;
flt.TitleSize = ARRSIZE(buf)/2;
flt.BottomSize = ARRSIZE(buf)/2;
if (Info->SendDlgMessage(hDlg, Msg, Param1, &flt))
{
lua_createtable(L,0,2);
PutWStrToTable(L, "Title", flt.Title, -1);
PutWStrToTable(L, "Bottom", flt.Bottom, -1);
return 1;
}
return lua_pushnil(L), 1;
}
case DM_LISTSETTITLES:
{
struct FarListTitles flt;
flt.StructSize = sizeof(flt);
luaL_checktype(L, pos4, LUA_TTABLE);
lua_getfield(L, pos4, "Title");
flt.Title = lua_isstring(L,-1) ? check_utf8_string(L,-1,NULL) : NULL;
lua_getfield(L, pos4, "Bottom");
flt.Bottom = lua_isstring(L,-1) ? check_utf8_string(L,-1,NULL) : NULL;
lua_pushinteger(L, Info->SendDlgMessage(hDlg, Msg, Param1, &flt));
return 1;
}
case DM_LISTINFO:
{
struct FarListInfo fli;
fli.StructSize = sizeof(fli);
if (Info->SendDlgMessage(hDlg, Msg, Param1, &fli))
{
lua_createtable(L,0,6);
PutFlagsToTable(L, "Flags", fli.Flags);
PutIntToTable(L, "ItemsNumber", fli.ItemsNumber);
PutIntToTable(L, "SelectPos", fli.SelectPos+1);
PutIntToTable(L, "TopPos", fli.TopPos+1);
PutIntToTable(L, "MaxHeight", fli.MaxHeight);
PutIntToTable(L, "MaxLength", fli.MaxLength);
return 1;
}
return lua_pushnil(L), 1;
}
case DM_LISTINSERT:
{
struct FarListInsert flins;
flins.StructSize = sizeof(flins);
luaL_checktype(L, pos4, LUA_TTABLE);
flins.Index = GetOptIntFromTable(L, "Index", 1) - 1;
lua_getfield(L, pos4, "Text");
flins.Item.Text = lua_isstring(L,-1) ? check_utf8_string(L,-1,NULL) : NULL;
flins.Item.Flags = CheckFlagsFromTable(L, pos4, "Flags");
res = Info->SendDlgMessage(hDlg, Msg, Param1, &flins);
res < 0 ? lua_pushnil(L) : lua_pushinteger(L, res);
return 1;
}
case DM_LISTUPDATE:
{
struct FarListUpdate flu;
flu.StructSize = sizeof(flu);
luaL_checktype(L, pos4, LUA_TTABLE);
flu.Index = GetOptIntFromTable(L, "Index", 1) - 1;
lua_getfield(L, pos4, "Text");
flu.Item.Text = lua_isstring(L,-1) ? check_utf8_string(L,-1,NULL) : NULL;
flu.Item.Flags = CheckFlagsFromTable(L, pos4, "Flags");
lua_pushboolean(L, Info->SendDlgMessage(hDlg, Msg, Param1, &flu) != 0);
return 1;
}
case DM_LISTSETCURPOS:
{
struct FarListPos flp;
flp.StructSize = sizeof(flp);
luaL_checktype(L, pos4, LUA_TTABLE);
flp.SelectPos = GetOptIntFromTable(L, "SelectPos", 1) - 1;
flp.TopPos = GetOptIntFromTable(L, "TopPos", 1) - 1;
lua_pushinteger(L, 1 + Info->SendDlgMessage(hDlg, Msg, Param1, &flp));
return 1;
}
case DM_LISTSETDATA:
{
listdata_t Data, *oldData;
intptr_t Index;
struct FarListItemData flid;
luaL_checktype(L, pos4, LUA_TTABLE);
Index = GetOptIntFromTable(L, "Index", 1) - 1;
lua_getfenv(L, 1);
lua_getfield(L, pos4, "Data");
if (lua_isnil(L,-1)) // nil is not allowed
{
lua_pushinteger(L,0);
return 1;
}
oldData = (listdata_t*)Info->SendDlgMessage(hDlg, DM_LISTGETDATA, Param1, (void*)Index);
if (oldData &&
sizeof(listdata_t) == Info->SendDlgMessage(hDlg, DM_LISTGETDATASIZE, Param1, (void*)Index) &&
oldData->Id == pluginData)
{
luaL_unref(L, -2, oldData->Ref);
}
Data.Id = pluginData;
Data.Ref = luaL_ref(L, -2);
flid.StructSize = sizeof(flid);
flid.Index = Index;
flid.Data = &Data;
flid.DataSize = sizeof(Data);
lua_pushinteger(L, Info->SendDlgMessage(hDlg, Msg, Param1, &flid));
return 1;
}
case DM_LISTGETDATA:
{
intptr_t Index = luaL_checkinteger(L, pos4) - 1;
listdata_t *Data = (listdata_t*)Info->SendDlgMessage(hDlg, Msg, Param1, (void*)Index);
if (Data)
{
if (sizeof(listdata_t) == Info->SendDlgMessage(hDlg, DM_LISTGETDATASIZE, Param1, (void*)Index) &&
Data->Id == pluginData)
{
lua_getfenv(L, 1);
lua_rawgeti(L, -1, Data->Ref);
}
else
lua_pushlightuserdata(L, Data);
}
else
lua_pushnil(L);
return 1;
}
case DM_GETDLGITEM:
return PushDlgItemNum(L, hDlg, (int)Param1, pos4, Info), 1;
case DM_SETDLGITEM:
return SetDlgItem(L, hDlg, (int)Param1, pos4, Info);
case DM_MOVEDIALOG:
case DM_RESIZEDIALOG:
case DM_SETCURSORPOS:
{
COORD *c;
luaL_checktype(L, pos4, LUA_TTABLE);
coord.X = GetOptIntFromTable(L, "X", 0);
coord.Y = GetOptIntFromTable(L, "Y", 0);
if (Msg == DM_SETCURSORPOS)
{
lua_pushinteger(L, Info->SendDlgMessage(hDlg, Msg, Param1, &coord));
return 1;
}
c = (COORD*) Info->SendDlgMessage(hDlg, Msg, Param1, &coord);
lua_createtable(L, 0, 2);
PutIntToTable(L, "X", c->X);
PutIntToTable(L, "Y", c->Y);
return 1;
}
case DM_SETITEMPOSITION:
luaL_checktype(L, pos4, LUA_TTABLE);
small_rect.Left = GetOptIntFromTable(L, "Left", 0);
small_rect.Top = GetOptIntFromTable(L, "Top", 0);
small_rect.Right = GetOptIntFromTable(L, "Right", 0);
small_rect.Bottom = GetOptIntFromTable(L, "Bottom", 0);
Param2 = &small_rect;
break;
case DM_SETCOMBOBOXEVENT:
Param2 = (void*)(intptr_t)OptFlags(L, pos4, 0);
break;
case DM_SETEDITPOSITION:
{
struct EditorSetPosition esp;
esp.StructSize = sizeof(esp);
luaL_checktype(L, pos4, LUA_TTABLE);
lua_settop(L, pos4);
FillEditorSetPosition(L, &esp);
lua_pushinteger(L, Info->SendDlgMessage(hDlg, Msg, Param1, &esp));
return 1;
}
case DN_CONTROLINPUT:
{
INPUT_RECORD rec;
OptInputRecord(L, pluginData, pos4, &rec);
lua_pushinteger(L, Info->SendDlgMessage(hDlg, Msg, Param1, &rec));
return 1;
}
}
res = Info->SendDlgMessage(hDlg, Msg, Param1, Param2);
lua_pushinteger(L, res + res_incr);
return 1;
}
#define DlgMethod(name,msg) \
static int dlg_##name(lua_State *L) { return DoSendDlgMessage(L,msg,1); }
static int far_SendDlgMessage(lua_State *L) { return DoSendDlgMessage(L,0,0); }
DlgMethod( AddHistory, DM_ADDHISTORY)
DlgMethod( Close, DM_CLOSE)
DlgMethod( EditUnchangedFlag, DM_EDITUNCHANGEDFLAG)
DlgMethod( Enable, DM_ENABLE)
DlgMethod( EnableRedraw, DM_ENABLEREDRAW)
DlgMethod( GetCheck, DM_GETCHECK)
DlgMethod( GetComboboxEvent, DM_GETCOMBOBOXEVENT)
DlgMethod( GetConstTextPtr, DM_GETCONSTTEXTPTR)
DlgMethod( GetCursorPos, DM_GETCURSORPOS)
DlgMethod( GetCursorSize, DM_GETCURSORSIZE)
DlgMethod( GetDialogInfo, DM_GETDIALOGINFO)
DlgMethod( GetDialogTitle, DM_GETDIALOGTITLE)
DlgMethod( GetDlgData, DM_GETDLGDATA)
DlgMethod( GetDlgItem, DM_GETDLGITEM)
DlgMethod( GetDlgRect, DM_GETDLGRECT)
DlgMethod( GetDropdownOpened, DM_GETDROPDOWNOPENED)
DlgMethod( GetEditPosition, DM_GETEDITPOSITION)
DlgMethod( GetFocus, DM_GETFOCUS)
DlgMethod( GetItemData, DM_GETITEMDATA)
DlgMethod( GetItemPosition, DM_GETITEMPOSITION)
DlgMethod( GetSelection, DM_GETSELECTION)
DlgMethod( GetText, DM_GETTEXT)
DlgMethod( Key, DM_KEY)
DlgMethod( ListAdd, DM_LISTADD)
DlgMethod( ListAddStr, DM_LISTADDSTR)
DlgMethod( ListDelete, DM_LISTDELETE)
DlgMethod( ListFindString, DM_LISTFINDSTRING)
DlgMethod( ListGetCurPos, DM_LISTGETCURPOS)
DlgMethod( ListGetData, DM_LISTGETDATA)
DlgMethod( ListGetDataSize, DM_LISTGETDATASIZE)
DlgMethod( ListGetItem, DM_LISTGETITEM)
DlgMethod( ListGetTitles, DM_LISTGETTITLES)
DlgMethod( ListInfo, DM_LISTINFO)
DlgMethod( ListInsert, DM_LISTINSERT)
DlgMethod( ListSet, DM_LISTSET)
DlgMethod( ListSetCurPos, DM_LISTSETCURPOS)
DlgMethod( ListSetData, DM_LISTSETDATA)
DlgMethod( ListSetTitles, DM_LISTSETTITLES)
DlgMethod( ListSort, DM_LISTSORT)
DlgMethod( ListUpdate, DM_LISTUPDATE)
DlgMethod( MoveDialog, DM_MOVEDIALOG)
DlgMethod( Redraw, DM_REDRAW)
DlgMethod( ResizeDialog, DM_RESIZEDIALOG)
DlgMethod( Set3State, DM_SET3STATE)
DlgMethod( SetCheck, DM_SETCHECK)
DlgMethod( SetComboboxEvent, DM_SETCOMBOBOXEVENT)
DlgMethod( SetCursorPos, DM_SETCURSORPOS)
DlgMethod( SetCursorSize, DM_SETCURSORSIZE)
DlgMethod( SetDlgData, DM_SETDLGDATA)
DlgMethod( SetDlgItem, DM_SETDLGITEM)
DlgMethod( SetDropdownOpened, DM_SETDROPDOWNOPENED)
DlgMethod( SetEditPosition, DM_SETEDITPOSITION)
DlgMethod( SetFocus, DM_SETFOCUS)
DlgMethod( SetHistory, DM_SETHISTORY)
DlgMethod( SetInputNotify, DM_SETINPUTNOTIFY)
DlgMethod( SetItemData, DM_SETITEMDATA)
DlgMethod( SetItemPosition, DM_SETITEMPOSITION)
DlgMethod( SetMaxTextLength, DM_SETMAXTEXTLENGTH)
DlgMethod( SetSelection, DM_SETSELECTION)
DlgMethod( SetText, DM_SETTEXT)
DlgMethod( SetTextPtr, DM_SETTEXTPTR)
DlgMethod( ShowDialog, DM_SHOWDIALOG)
DlgMethod( ShowItem, DM_SHOWITEM)
DlgMethod( User, DM_USER)
int PushDNParams (lua_State *L, intptr_t Msg, intptr_t Param1, void *Param2)
{
// Param1
switch(Msg)
{
case DN_CTLCOLORDIALOG:
case DN_DRAGGED:
case DN_DRAWDIALOG:
case DN_DRAWDIALOGDONE:
case DN_INPUT:
case DN_RESIZECONSOLE:
break;
case DN_CLOSE:
case DN_CONTROLINPUT:
case DN_GOTFOCUS:
case DN_KILLFOCUS:
if (Param1 >= 0)
++Param1;
break;
case DN_BTNCLICK:
case DN_CTLCOLORDLGITEM:
case DN_CTLCOLORDLGLIST:
case DN_DRAWDLGITEM:
case DN_DRAWDLGITEMDONE:
case DN_DROPDOWNOPENED:
case DN_EDITCHANGE:
case DN_GETVALUE:
case DN_HELP:
case DN_HOTKEY:
case DN_INITDIALOG:
case DN_LISTCHANGE:
case DN_LISTHOTKEY:
++Param1; // dialog element position
break;
default:
return FALSE;
}
lua_pushinteger(L, Msg); //+1
lua_pushinteger(L, Param1); //+2
// Param2
switch(Msg)
{
case DN_CONTROLINPUT: // TODO
case DN_INPUT: // TODO was: (Msg == DN_MOUSEEVENT)
case DN_HOTKEY:
PushInputRecord(L, (const INPUT_RECORD*)Param2);
break;
case DN_CTLCOLORDIALOG:
PushFarColor(L, (struct FarColor*) Param2);
break;
case DN_CTLCOLORDLGITEM:
case DN_CTLCOLORDLGLIST:
{
int i;
struct FarDialogItemColors* fdic = (struct FarDialogItemColors*) Param2;
lua_createtable(L, (int)fdic->ColorsCount, 1);
PutFlagsToTable(L, "Flags", fdic->Flags);
for(i=0; i < (int)fdic->ColorsCount; i++)
{
PushFarColor(L, &fdic->Colors[i]);
lua_rawseti(L, -2, i+1);
}
break;
}
case DN_DRAWDLGITEM:
case DN_EDITCHANGE:
PushDlgItem(L, (struct FarDialogItem*)Param2, FALSE);
break;
case DN_GETVALUE:
{
struct FarGetValue *fgv = (struct FarGetValue*) Param2;
lua_newtable(L);
PutIntToTable(L, "GetType", fgv->Type);
PutIntToTable(L, "ValType", fgv->Value.Type);
PushFarMacroValue(L, &fgv->Value);
lua_setfield(L, -2, "Value");
break;
}
case DN_HELP:
push_utf8_string(L, Param2 ? (wchar_t*)Param2 : L"", -1);
break;
case DN_LISTCHANGE:
case DN_LISTHOTKEY:
lua_pushinteger(L, (intptr_t)Param2+1); // make list positions 1-based
break;
case DN_RESIZECONSOLE:
{
COORD* coord = (COORD*)Param2;
lua_createtable(L, 0, 2);
PutIntToTable(L, "X", coord->X);
PutIntToTable(L, "Y", coord->Y);
break;
}
default:
lua_pushinteger(L, (intptr_t)Param2); //+3
break;
}
return TRUE;
}
intptr_t ProcessDNResult(lua_State *L, intptr_t Msg, void *Param2)
{
intptr_t ret = 0;
switch(Msg)
{
case DN_CTLCOLORDLGLIST:
case DN_CTLCOLORDLGITEM:
if ((ret = lua_istable(L,-1)) != 0)
{
struct FarDialogItemColors* fdic = (struct FarDialogItemColors*) Param2;
int i;
size_t len = lua_objlen(L, -1);
if (len > fdic->ColorsCount) len = fdic->ColorsCount;
for(i = 0; i < (int)len; i++)
{
lua_rawgeti(L, -1, i+1);
GetFarColor(L, -1, &fdic->Colors[i]);
lua_pop(L, 1);
}
}
break;
case DN_CTLCOLORDIALOG:
ret = GetFarColor(L, -1, (struct FarColor*)Param2);
break;
case DN_HELP:
if ((ret = (intptr_t)utf8_to_utf16(L, -1, NULL)) != 0)
{
lua_getfield(L, LUA_REGISTRYINDEX, FAR_DN_STORAGE);
lua_pushvalue(L, -2); // keep stack balanced
lua_setfield(L, -2, "helpstring"); // protect from garbage collector
lua_pop(L, 1);
}
break;
case DN_GETVALUE:
if ((ret = lua_istable(L,-1)) != 0)
{
struct FarMacroValue tempValue;
struct FarGetValue *fgv = (struct FarGetValue*) Param2;
lua_getfield(L, -1, "Value");
ConvertLuaValue(L, -1, &tempValue);
if (tempValue.Type == fgv->Value.Type)
{
fgv->Value = tempValue;
if (fgv->Value.Type == FMVT_STRING)
{
lua_getfield(L, LUA_REGISTRYINDEX, FAR_DN_STORAGE);
lua_pushvalue(L, -2); // keep stack balanced
lua_setfield(L, -2, "getvaluestring"); // protect from garbage collector
lua_pop(L, 1);
}
}
else if (tempValue.Type==FMVT_DOUBLE && fgv->Value.Type==FMVT_INTEGER)
fgv->Value.Value.Integer = (__int64)tempValue.Value.Double;
else
ret = 0;
lua_pop(L, 1);
}
break;
case DN_KILLFOCUS:
ret = lua_tointeger(L, -1) - 1;
break;
default:
ret = lua_isnumber(L, -1) ? lua_tointeger(L, -1) : (lua_Integer)lua_toboolean(L, -1);
break;
}
return ret;
}
static intptr_t DoDlgProc(lua_State *L, PSInfo *Info, TDialogData *dd, HANDLE hDlg, intptr_t Msg, intptr_t Param1, void *Param2)
{
intptr_t ret;
if (!dd || dd->wasError)
return Info->DefDlgProc(hDlg, Msg, Param1, Param2);
lua_pushlightuserdata(L, dd); //+1 retrieve the table
lua_rawget(L, LUA_REGISTRYINDEX); //+1
lua_rawgeti(L, -1, 2); //+2 retrieve the procedure
lua_rawgeti(L, -2, 3); //+3 retrieve the handle
lua_remove(L, -3); //+2
if (Msg == DN_INITDIALOG) {
lua_pushinteger(L, Msg); //+3
lua_pushinteger(L, Param1 + 1); //+4
lua_rawgeti(L, LUA_REGISTRYINDEX, dd->dataRef); //+5
}
else {
if (!PushDNParams(L, Msg, Param1, Param2)) { //+5
lua_pop(L, 2);
return Info->DefDlgProc(hDlg, Msg, Param1, Param2);
}
}
if (pcall_msg(L, 4, 1)) //+2
{
dd->wasError = TRUE;
Info->SendDlgMessage(hDlg, DM_CLOSE, -1, 0);
return Info->DefDlgProc(hDlg, Msg, Param1, Param2);
}
ret = lua_isnil(L, -1) ?
Info->DefDlgProc(hDlg, Msg, Param1, Param2) :
ProcessDNResult(L, Msg, Param2);
lua_pop(L, 1);
return ret;
}
static void RemoveDialogFromRegistry(lua_State *L, TDialogData *dd)
{
luaL_unref(dd->L, LUA_REGISTRYINDEX, dd->dataRef);
dd->hDlg = INVALID_HANDLE_VALUE;
lua_pushlightuserdata(L, dd);
lua_pushnil(L);
lua_rawset(L, LUA_REGISTRYINDEX);
}
static __inline BOOL NonModal(TDialogData *dd)
{
return dd && !dd->isModal;
}
intptr_t LF_DlgProc(lua_State *L, HANDLE hDlg, intptr_t Msg, intptr_t Param1, void *Param2)
{
intptr_t ret;
PSInfo *Info = GetPluginData(L)->Info;
TDialogData *dd = (TDialogData*) Info->SendDlgMessage(hDlg,DM_GETDLGDATA,0,0);
if (Msg == DN_INITDIALOG && dd->hDlg == INVALID_HANDLE_VALUE)
{
dd->hDlg = hDlg;
}
if (dd)
{
L = dd->L; // the dialog may be called from a lua_State other than the main one
}
ret = DoDlgProc(L, Info, dd, hDlg, Msg, Param1, Param2);
if (Msg == DN_CLOSE && ret && NonModal(dd))
{
Info->SendDlgMessage(hDlg, DM_SETDLGDATA, 0, 0);
RemoveDialogFromRegistry(L, dd);
}
return ret;
}
static int far_DialogInit(lua_State *L)
{
enum { POS_HISTORIES=1, POS_ITEMS=2 };
intptr_t ItemsNumber, i;
struct FarDialogItem *Items;
UINT64 Flags;
TDialogData *dd;
FARAPIDEFDLGPROC Proc;
void *Param;
TPluginData *pd = GetPluginData(L);
GUID Id;
intptr_t X1, Y1, X2, Y2;
const wchar_t *HelpTopic;
memset(&Id, 0, sizeof(Id));
if (lua_type(L,1) == LUA_TSTRING) {
if (lua_objlen(L,1) >= sizeof(GUID))
Id = *(const GUID*)lua_tostring(L, 1);
}
else if (!lua_isnoneornil(L,1))
return luaL_typerror(L, 1, "optional string");
X1 = luaL_checkinteger(L, 2);
Y1 = luaL_checkinteger(L, 3);
X2 = luaL_checkinteger(L, 4);
Y2 = luaL_checkinteger(L, 5);
HelpTopic = opt_utf8_string(L, 6, NULL);
luaL_checktype(L, 7, LUA_TTABLE);
lua_newtable(L); // create a "histories" table, to prevent history strings
// from being garbage collected too early
lua_replace(L, POS_HISTORIES);
ItemsNumber = lua_objlen(L, 7);
Items = (struct FarDialogItem*)lua_newuserdata(L, ItemsNumber * sizeof(struct FarDialogItem));
lua_replace(L, POS_ITEMS);
for(i=0; i < ItemsNumber; i++) {
lua_pushinteger(L, i+1);
lua_gettable(L, 7);
if (lua_type(L, -1) == LUA_TTABLE) {
SetFarDialogItem(L, Items+i, (int)i, POS_HISTORIES);
lua_pop(L, 1);
}
else
return luaL_error(L, "Items[%d] is not a table", (int)i+1);
}
// 8-th parameter (flags)
Flags = OptFlags(L, 8, 0);
dd = NewDialogData(L, pd->Info, INVALID_HANDLE_VALUE, TRUE);
// 9-th parameter (DlgProc function)
Proc = NULL;
Param = NULL;
if (lua_isfunction(L, 9))
{
Proc = pd->DlgProc;
Param = dd;
if (lua_gettop(L) >= 10) {
lua_pushvalue(L,10);
dd->dataRef = luaL_ref(L, LUA_REGISTRYINDEX);
}
}
// Put some values into the registry
lua_pushlightuserdata(L, dd); // important: index it with dd
lua_createtable(L, 3, 0);
lua_pushvalue(L, POS_HISTORIES); // store the "histories" table
lua_rawseti(L, -2, 1);
if (lua_isfunction(L, 9))
{
lua_pushvalue(L, 9); // store the procedure
lua_rawseti(L, -2, 2);
lua_pushvalue(L, -3); // store the handle
lua_rawseti(L, -2, 3);
}
lua_rawset(L, LUA_REGISTRYINDEX);
dd->hDlg = pd->Info->DialogInit(pd->PluginId, &Id, X1, Y1, X2, Y2, HelpTopic,
Items, ItemsNumber, 0, Flags, Proc, Param);
if (dd->hDlg == INVALID_HANDLE_VALUE)
{
RemoveDialogFromRegistry(L, dd);
lua_pushnil(L);
}
else
{
dd->isModal = (Flags&FDLG_NONMODAL) == 0;
}
return 1;
}
static void free_dialog(TDialogData* dd)
{
lua_State* L = dd->L;
if (dd->isOwned && dd->isModal && dd->hDlg != INVALID_HANDLE_VALUE)
{
dd->Info->DialogFree(dd->hDlg);
RemoveDialogFromRegistry(L, dd);
}
}
static int far_DialogRun(lua_State *L)
{
TDialogData* dd = CheckValidDialog(L, 1);
intptr_t result = dd->Info->DialogRun(dd->hDlg);
if (result >= 0) ++result;
if (dd->wasError)
{
free_dialog(dd);
luaL_error(L, "error occured in dialog procedure");
}
lua_pushinteger(L, (int)result);
return 1;
}
static int far_DialogFree(lua_State *L)
{
free_dialog(CheckDialog(L, 1));
return 0;
}
static int dialog_tostring(lua_State *L)
{
TDialogData* dd = CheckDialog(L, 1);
if (dd->hDlg != INVALID_HANDLE_VALUE)
lua_pushfstring(L, "%s (%p)", FarDialogType, dd->hDlg);
else
lua_pushfstring(L, "%s (closed)", FarDialogType);
return 1;
}
static int dialog_rawhandle(lua_State *L)
{
TDialogData* dd = CheckDialog(L, 1);
if (dd->hDlg != INVALID_HANDLE_VALUE)
lua_pushlightuserdata(L, dd->hDlg);
else
lua_pushnil(L);
return 1;
}
static int far_GetDlgItem(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE hDlg = CheckDialogHandle(L,1);
int numitem = (int)luaL_checkinteger(L,2) - 1;
PushDlgItemNum(L, hDlg, numitem, 3, Info);
return 1;
}
static int far_SetDlgItem(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE hDlg = CheckDialogHandle(L,1);
int numitem = (int)luaL_checkinteger(L,2) - 1;
return SetDlgItem(L, hDlg, numitem, 3, Info);
}
static int far_SubscribeDialogDrawEvents(lua_State *L)
{
GetPluginData(L)->Flags |= PDF_DIALOGEVENTDRAWENABLE;
return 0;
}
static int editor_Editor(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
const wchar_t* FileName = check_utf8_string(L, 1, NULL);
const wchar_t* Title = opt_utf8_string(L, 2, NULL);
intptr_t X1 = luaL_optinteger(L, 3, 0);
intptr_t Y1 = luaL_optinteger(L, 4, 0);
intptr_t X2 = luaL_optinteger(L, 5, -1);
intptr_t Y2 = luaL_optinteger(L, 6, -1);
UINT64 Flags = OptFlags(L,7,0);
intptr_t StartLine = luaL_optinteger(L, 8, -1);
intptr_t StartChar = luaL_optinteger(L, 9, -1);
intptr_t CodePage = luaL_optinteger(L, 10, CP_DEFAULT);
intptr_t ret = Info->Editor(FileName, Title, X1, Y1, X2, Y2, Flags,
StartLine, StartChar, CodePage);
lua_pushinteger(L, (int)ret);
return 1;
}
static int viewer_Viewer(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
const wchar_t* FileName = check_utf8_string(L, 1, NULL);
const wchar_t* Title = opt_utf8_string(L, 2, NULL);
intptr_t X1 = luaL_optinteger(L, 3, 0);
intptr_t Y1 = luaL_optinteger(L, 4, 0);
intptr_t X2 = luaL_optinteger(L, 5, -1);
intptr_t Y2 = luaL_optinteger(L, 6, -1);
UINT64 Flags = OptFlags(L, 7, 0);
intptr_t CodePage = luaL_optinteger(L, 8, CP_DEFAULT);
intptr_t ret = Info->Viewer(FileName, Title, X1, Y1, X2, Y2, Flags, CodePage);
lua_pushboolean(L, ret != 0);
return 1;
}
static int viewer_GetFileName(lua_State *L)
{
intptr_t ViewerId = luaL_optinteger(L, 1, -1);
if (!push_ev_filename(L, 0, ViewerId)) lua_pushnil(L);
return 1;
}
static int viewer_GetInfo(lua_State *L)
{
intptr_t ViewerId = luaL_optinteger(L, 1, -1);
PSInfo *Info = GetPluginData(L)->Info;
struct ViewerInfo vi;
vi.StructSize = sizeof(vi);
if (Info->ViewerControl(ViewerId, VCTL_GETINFO, 0, &vi))
{
lua_createtable(L, 0, 10);
PutNumToTable(L, "ViewerID", (double) vi.ViewerID);
if (push_ev_filename(L, 0, ViewerId))
lua_setfield(L, -2, "FileName");
PutNumToTable(L, "FileSize", (double) vi.FileSize);
PutNumToTable(L, "FilePos", (double) vi.FilePos);
PutNumToTable(L, "WindowSizeX", (double) vi.WindowSizeX);
PutNumToTable(L, "WindowSizeY", (double) vi.WindowSizeY);
PutNumToTable(L, "Options", (double) vi.Options);
PutNumToTable(L, "TabSize", (double) vi.TabSize);
PutNumToTable(L, "LeftPos", (double) vi.LeftPos + 1);
lua_createtable(L, 0, 3);
PutNumToTable(L, "CodePage", (double) vi.CurMode.CodePage);
PutFlagsToTable(L, "Flags", vi.CurMode.Flags);
PutNumToTable(L, "ViewMode", (double) vi.CurMode.ViewMode);
lua_setfield(L, -2, "CurMode");
}
else
lua_pushnil(L);
return 1;
}
static int viewer_Quit(lua_State *L)
{
intptr_t ViewerId = luaL_optinteger(L, 1, -1);
PSInfo *Info = GetPluginData(L)->Info;
lua_pushboolean(L, Info->ViewerControl(ViewerId, VCTL_QUIT, 0, 0));
return 1;
}
static int viewer_Redraw(lua_State *L)
{
intptr_t ViewerId = luaL_optinteger(L, 1, -1);
PSInfo *Info = GetPluginData(L)->Info;
Info->ViewerControl(ViewerId, VCTL_REDRAW, 0, 0);
return 0;
}
static int viewer_Select(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
intptr_t ViewerId = luaL_optinteger(L, 1, -1);
struct ViewerSelect vs;
vs.StructSize = sizeof(vs);
vs.BlockStartPos = (INT64)luaL_checknumber(L,2);
vs.BlockLen = (INT64)luaL_checknumber(L,3);
lua_pushboolean(L, Info->ViewerControl(ViewerId, VCTL_SELECT, 0, &vs) != 0);
return 1;
}
static int viewer_SetPosition(lua_State *L)
{
intptr_t ViewerId = luaL_optinteger(L, 1, -1);
PSInfo *Info = GetPluginData(L)->Info;
struct ViewerSetPosition vsp;
vsp.StructSize = sizeof(vsp);
if (lua_istable(L, 2))
{
lua_settop(L, 2);
vsp.StartPos = (__int64)GetOptNumFromTable(L, "StartPos", 0);
vsp.LeftPos = (__int64)GetOptNumFromTable(L, "LeftPos", 1) - 1;
vsp.Flags = CheckFlagsFromTable(L, -1, "Flags");
}
else
{
vsp.StartPos = (__int64)luaL_optnumber(L,2,0);
vsp.LeftPos = (__int64)luaL_optnumber(L,3,1) - 1;
vsp.Flags = OptFlags(L,4,0);
}
if (Info->ViewerControl(ViewerId, VCTL_SETPOSITION, 0, &vsp))
lua_pushnumber(L, (double)vsp.StartPos);
else
lua_pushnil(L);
return 1;
}
static int viewer_SetMode(lua_State *L)
{
int success;
intptr_t ViewerId;
struct ViewerSetMode vsm;
memset(&vsm, 0, sizeof(vsm));
vsm.StructSize = sizeof(vsm);
ViewerId = luaL_optinteger(L, 1, -1);
luaL_checktype(L, 2, LUA_TTABLE);
lua_getfield(L, 2, "Type");
vsm.Type = get_env_flag(L, -1, &success);
if (!success)
return lua_pushboolean(L,0), 1;
lua_getfield(L, 2, "iParam");
if (lua_isnumber(L, -1))
vsm.Param.iParam = lua_tointeger(L, -1);
else
return lua_pushboolean(L,0), 1;
lua_getfield(L, 2, "Flags");
vsm.Flags = get_env_flag(L, -1, &success);
if (!success)
return lua_pushboolean(L,0), 1;
lua_pushboolean(L, GetPluginData(L)->Info->ViewerControl(ViewerId, VCTL_SETMODE, 0, &vsm) != 0);
return 1;
}
static int far_ShowHelp(lua_State *L)
{
const wchar_t *ModuleName = (const wchar_t*)luaL_checkstring(L, 1);
const wchar_t *HelpTopic = opt_utf8_string(L,2,NULL);
UINT64 Flags = OptFlags(L,3,0);
PSInfo *Info = GetPluginData(L)->Info;
if ((Flags & FHELP_GUID) == 0)
ModuleName = check_utf8_string(L,1,NULL);
lua_pushboolean(L, Info->ShowHelp(ModuleName, HelpTopic, Flags));
return 1;
}
// DestText = far.InputBox(Title,Prompt,HistoryName,SrcText,DestLength,HelpTopic,Flags)
// all arguments are optional
static int far_InputBox(lua_State *L)
{
TPluginData *pd = GetPluginData(L);
const GUID *Id = (lua_type(L,1)==LUA_TSTRING && lua_objlen(L,1)==sizeof(GUID)) ?
(const GUID*)lua_tostring(L, 1) : pd->PluginId;
const wchar_t *Title = opt_utf8_string(L, 2, L"Input Box");
const wchar_t *Prompt = opt_utf8_string(L, 3, L"Enter the text:");
const wchar_t *HistoryName = opt_utf8_string(L, 4, NULL);
const wchar_t *SrcText = opt_utf8_string(L, 5, L"");
intptr_t DestLength = luaL_optinteger(L, 6, 1024);
const wchar_t *HelpTopic = opt_utf8_string(L, 7, NULL);
UINT64 Flags = OptFlags(L, 8, FIB_ENABLEEMPTY|FIB_BUTTONS|FIB_NOAMPERSAND);
wchar_t *DestText;
intptr_t res;
if (DestLength < 0) DestLength = 0;
DestText = (wchar_t*) malloc(sizeof(wchar_t)*(DestLength+1));
res = pd->Info->InputBox(pd->PluginId, Id, Title, Prompt, HistoryName, SrcText,
DestText, DestLength+1, HelpTopic, Flags);
if (res) push_utf8_string(L, DestText, -1);
else lua_pushnil(L);
free(DestText);
return 1;
}
static int far_GetMsg(lua_State *L)
{
intptr_t MsgId = luaL_checkinteger(L, 1);
if (MsgId >= 0)
{
GUID guid;
TPluginData *pd = GetPluginData(L);
const wchar_t* str;
GetOptGuid(L, 2, &guid, pd->PluginId);
str = pd->Info->GetMsg(&guid, MsgId);
if (str)
push_utf8_string(L, str, -1);
else
lua_pushnil(L);
}
else
lua_pushnil(L); // (MsgId < 0) crashes FAR
return 1;
}
static int far_Text(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
const wchar_t *Str;
struct FarColor fc = { FCF_4BITMASK, {0x0F}, {0x00} };
intptr_t X = luaL_optinteger(L, 1, 0);
intptr_t Y = luaL_optinteger(L, 2, 0);
GetFarColor(L, 3, &fc);
Str = opt_utf8_string(L, 4, NULL);
Info->Text(X, Y, &fc, Str);
return 0;
}
static int far_CopyToClipboard(lua_State *L)
{
int ret;
if (lua_isnoneornil(L,1))
ret = GetPluginData(L)->FSF->CopyToClipboard(FCT_STREAM,NULL);
else
{
const wchar_t *str = check_utf8_string(L,1,NULL);
enum FARCLIPBOARD_TYPE type = (enum FARCLIPBOARD_TYPE) OptFlags(L,2,FCT_STREAM);
ret = GetPluginData(L)->FSF->CopyToClipboard(type,str);
}
return lua_pushboolean(L, ret), 1;
}
static int far_PasteFromClipboard(lua_State *L)
{
struct FarStandardFunctions *FSF = GetPluginData(L)->FSF;
enum FARCLIPBOARD_TYPE type = (enum FARCLIPBOARD_TYPE) OptFlags(L,1,FCT_ANY);
size_t len = FSF->PasteFromClipboard(type,NULL,0);
if (len)
{
wchar_t *buf = (wchar_t*) malloc(len * sizeof(wchar_t));
if (buf)
{
FSF->PasteFromClipboard(type,buf,len);
push_utf8_string(L,buf,len-1);
free(buf);
return 1;
}
}
lua_pushnil(L);
return 1;
}
static int far_InputRecordToName(lua_State *L)
{
wchar_t buf[256];
INPUT_RECORD ir;
size_t result;
FillInputRecord(L, 1, &ir);
result = GetPluginData(L)->FSF->FarInputRecordToName(&ir, buf, ARRSIZE(buf)-1);
if (result > 0)
{
if (lua_toboolean(L, 2))
{
static const char C[]="RCtrl", A[]="RAlt", S[]="Shift";
const char *p;
push_utf8_string(L, buf, -1);
p = lua_tostring(L, -1);
if (!strncmp(p, C+1, 4)) { lua_pushstring(L, C+1); p += 4; }
else if (!strncmp(p, C, 5)) { lua_pushstring(L, C); p += 5; }
else lua_pushboolean(L, 0);
if (!strncmp(p, A+1, 3)) { lua_pushstring(L, A+1); p += 3; }
else if (!strncmp(p, A, 4)) { lua_pushstring(L, A); p += 4; }
else lua_pushboolean(L, 0);
if (!strncmp(p, S, 5)) { lua_pushstring(L, S); p += 5; }
else lua_pushboolean(L, 0);
*p ? lua_pushstring(L, p) : lua_pushboolean(L, 0);
return 4;
}
else
push_utf8_string(L, buf, -1);
}
else
lua_pushnil(L);
return 1;
}
static int far_NameToInputRecord(lua_State *L)
{
INPUT_RECORD ir;
const wchar_t* str = check_utf8_string(L, 1, NULL);
if (GetPluginData(L)->FSF->FarNameToInputRecord(str, &ir))
PushInputRecord(L, &ir);
else
lua_pushnil(L);
return 1;
}
static int far_LStricmp(lua_State *L)
{
const wchar_t* s1 = check_utf8_string(L, 1, NULL);
const wchar_t* s2 = check_utf8_string(L, 2, NULL);
lua_pushinteger(L, GetPluginData(L)->FSF->LStricmp(s1, s2));
return 1;
}
static int far_LStrnicmp(lua_State *L)
{
const wchar_t* s1 = check_utf8_string(L, 1, NULL);
const wchar_t* s2 = check_utf8_string(L, 2, NULL);
intptr_t num = luaL_checkinteger(L, 3);
if (num < 0) num = 0;
lua_pushinteger(L, GetPluginData(L)->FSF->LStrnicmp(s1, s2, num));
return 1;
}
// Result = far.ProcessName (Op, Mask, Name, Flags, Size)
// @Op: PN_CMPNAME, PN_CMPNAMELIST, PN_GENERATENAME, PN_CHECKMASK
// @Mask: string
// @Name: string
// @Flags: PN_SKIPPATH, PN_SHOWERRORMESSAGE
// @Size: integer 0...0xFFFF
// @Result: boolean
static int _ProcessName (lua_State *L, UINT64 Op)
{
struct FarStandardFunctions *FSF = GetPluginData(L)->FSF;
int pos2=2, pos3=3, pos4=4;
if (Op == 0xFFFFFFFF)
Op = CheckFlags(L, 1);
else {
--pos2, --pos3, --pos4;
if (Op == PN_CHECKMASK)
--pos4;
}
const wchar_t* Mask = check_utf8_string(L, pos2, NULL);
const wchar_t* Name = (Op == PN_CHECKMASK) ? L"" : check_utf8_string(L, pos3, NULL);
int Flags = Op | OptFlags(L, pos4, 0);
if (Op == PN_CMPNAME || Op == PN_CMPNAMELIST || Op == PN_CHECKMASK) {
size_t result = FSF->ProcessName(Mask, (wchar_t*)Name, 0, Flags);
lua_pushboolean(L, (int)result);
}
else if (Op == PN_GENERATENAME) {
UINT64 Size = luaL_optinteger(L, pos4+1, 0) & 0xFFFF;
const int BUFSIZE = 1024;
wchar_t* buf = (wchar_t*)lua_newuserdata(L, BUFSIZE * sizeof(wchar_t));
wcsncpy(buf, Mask, BUFSIZE-1);
buf[BUFSIZE-1] = 0;
size_t result = FSF->ProcessName(Name, buf, BUFSIZE, Flags|Size);
if (result)
push_utf8_string(L, buf, -1);
else
lua_pushboolean(L, (int)result);
}
else
luaL_argerror(L, 1, "command not supported");
return 1;
}
static int far_ProcessName (lua_State *L) { return _ProcessName(L, 0xFFFFFFFF); }
static int far_CmpName (lua_State *L) { return _ProcessName(L, PN_CMPNAME); }
static int far_CmpNameList (lua_State *L) { return _ProcessName(L, PN_CMPNAMELIST); }
static int far_CheckMask (lua_State *L) { return _ProcessName(L, PN_CHECKMASK); }
static int far_GenerateName (lua_State *L) { return _ProcessName(L, PN_GENERATENAME); }
static int far_GetReparsePointInfo(lua_State *L)
{
wchar_t* Dest;
struct FarStandardFunctions *FSF = GetPluginData(L)->FSF;
const wchar_t* Src = check_utf8_string(L, 1, NULL);
size_t size = FSF->GetReparsePointInfo(Src, NULL, 0);
if (size == 0)
return lua_pushnil(L), 1;
Dest = (wchar_t*)lua_newuserdata(L, size * sizeof(wchar_t));
FSF->GetReparsePointInfo(Src, Dest, size);
return push_utf8_string(L, Dest, -1), 1;
}
static int far_LIsAlpha(lua_State *L)
{
const wchar_t* str = check_utf8_string(L, 1, NULL);
lua_pushboolean(L, GetPluginData(L)->FSF->LIsAlpha(*str) != 0);
return 1;
}
static int far_LIsAlphanum(lua_State *L)
{
const wchar_t* str = check_utf8_string(L, 1, NULL);
lua_pushboolean(L, GetPluginData(L)->FSF->LIsAlphanum(*str) != 0);
return 1;
}
static int far_LIsLower(lua_State *L)
{
const wchar_t* str = check_utf8_string(L, 1, NULL);
lua_pushboolean(L, GetPluginData(L)->FSF->LIsLower(*str) != 0);
return 1;
}
static int far_LIsUpper(lua_State *L)
{
const wchar_t* str = check_utf8_string(L, 1, NULL);
lua_pushboolean(L, GetPluginData(L)->FSF->LIsUpper(*str) != 0);
return 1;
}
static int convert_buf(lua_State *L, int command)
{
struct FarStandardFunctions *FSF = GetPluginData(L)->FSF;
size_t len;
wchar_t* dest = check_utf8_string(L, 1, &len);
if (command=='l')
FSF->LLowerBuf(dest,len);
else
FSF->LUpperBuf(dest,len);
push_utf8_string(L, dest, len);
return 1;
}
static int far_LLowerBuf(lua_State *L)
{
return convert_buf(L, 'l');
}
static int far_LUpperBuf(lua_State *L)
{
return convert_buf(L, 'u');
}
static int far_MkTemp(lua_State *L)
{
const wchar_t* prefix = opt_utf8_string(L, 1, NULL);
const int dim = 4096;
wchar_t* dest = (wchar_t*)lua_newuserdata(L, dim * sizeof(wchar_t));
if (GetPluginData(L)->FSF->MkTemp(dest, dim, prefix))
push_utf8_string(L, dest, -1);
else
lua_pushnil(L);
return 1;
}
static int far_MkLink(lua_State *L)
{
const wchar_t* src = check_utf8_string(L, 1, NULL);
const wchar_t* dst = check_utf8_string(L, 2, NULL);
UINT64 type = CheckFlags(L, 3);
UINT64 flags = OptFlags(L, 4, 0);
lua_pushboolean(L, GetPluginData(L)->FSF->MkLink(src, dst, type, flags));
return 1;
}
static int far_GetPathRoot(lua_State *L)
{
const wchar_t* Path = check_utf8_string(L, 1, NULL);
struct FarStandardFunctions *FSF = GetPluginData(L)->FSF;
size_t size = FSF->GetPathRoot(Path, NULL, 0);
wchar_t* Root = (wchar_t*)lua_newuserdata(L, (size+1) * sizeof(wchar_t));
*Root = L'\0';
FSF->GetPathRoot(Path, Root, size);
push_utf8_string(L, Root, -1);
return 1;
}
static int truncstring(lua_State *L, int op)
{
struct FarStandardFunctions *FSF = GetPluginData(L)->FSF;
const wchar_t *Src = check_utf8_string(L, 1, NULL), *ptr;
wchar_t *Trg;
intptr_t MaxLen = luaL_checkinteger(L, 2);
intptr_t SrcLen = wcslen(Src);
if (MaxLen < 0) MaxLen = 0;
else if (MaxLen > SrcLen) MaxLen = SrcLen;
Trg = (wchar_t*)lua_newuserdata(L, (1 + SrcLen) * sizeof(wchar_t));
wcscpy(Trg, Src);
ptr = (op == 'p') ? FSF->TruncPathStr(Trg, MaxLen) : FSF->TruncStr(Trg, MaxLen);
return push_utf8_string(L, ptr, -1), 1;
}
static int far_TruncPathStr(lua_State *L)
{
return truncstring(L, 'p');
}
static int far_TruncStr(lua_State *L)
{
return truncstring(L, 's');
}
typedef struct
{
lua_State *L;
int nparams;
int err;
DWORD attr_incl;
DWORD attr_excl;
} FrsData;
static int WINAPI FrsUserFunc(const struct PluginPanelItem *FData, const wchar_t *FullName,
void *Param)
{
FrsData *Data = (FrsData*)Param;
lua_State *L = Data->L;
int i, nret = lua_gettop(L);
if ((FData->FileAttributes & Data->attr_excl) != 0 || (FData->FileAttributes & Data->attr_incl) != Data->attr_incl)
return TRUE; // attributes mismatch
lua_pushvalue(L, 3); // push the Lua function
PushPanelItem(L, FData, 0);
push_utf8_string(L, FullName, -1);
for (i=1; i<=Data->nparams; i++)
lua_pushvalue(L, 4+i);
Data->err = lua_pcall(L, 2+Data->nparams, LUA_MULTRET, 0);
nret = lua_gettop(L) - nret;
if (!Data->err && (nret==0 || lua_toboolean(L,-nret)==0))
{
lua_pop(L, nret);
return TRUE;
}
return FALSE;
}
static int far_RecursiveSearch(lua_State *L)
{
UINT64 Flags;
FrsData Data = { L,0,0,0,0 };
const wchar_t *InitDir = check_utf8_string(L, 1, NULL);
wchar_t *Mask = check_utf8_string(L, 2, NULL);
wchar_t *MaskEnd;
luaL_checktype(L, 3, LUA_TFUNCTION);
if ((MaskEnd=wcsstr(Mask, L">>")) != NULL)
{
*MaskEnd = 0;
SetAttrWords(MaskEnd+2, &Data.attr_incl, &Data.attr_excl);
}
Flags = OptFlags(L, 4, 0);
if (lua_gettop(L) == 3)
lua_pushnil(L);
Data.nparams = lua_gettop(L) - 4;
lua_checkstack(L, 256);
GetPluginData(L)->FSF->FarRecursiveSearch(InitDir, Mask, FrsUserFunc, Flags, &Data);
if (Data.err)
LF_Error(L, check_utf8_string(L, -1, NULL));
return Data.err ? 0 : lua_gettop(L) - Data.nparams - 4;
}
static int far_ConvertPath(lua_State *L)
{
struct FarStandardFunctions *FSF = GetPluginData(L)->FSF;
const wchar_t *Src = check_utf8_string(L, 1, NULL);
enum CONVERTPATHMODES Mode = lua_isnoneornil(L,2) ?
CPM_FULL : (enum CONVERTPATHMODES)check_env_flag(L,2);
size_t Size = FSF->ConvertPath(Mode, Src, NULL, 0);
wchar_t* Target = (wchar_t*)lua_newuserdata(L, Size*sizeof(wchar_t));
FSF->ConvertPath(Mode, Src, Target, Size);
push_utf8_string(L, Target, -1);
return 1;
}
static int DoAdvControl (lua_State *L, int Command, int Delta)
{
int pos2 = 2-Delta, pos3 = 3-Delta;
TPluginData *pd = GetPluginData(L);
GUID* PluginId = pd->PluginId;
PSInfo *Info = pd->Info;
intptr_t Param1 = 0;
void *Param2 = NULL;
if (Command != ACTL_SYNCHRO)
lua_settop(L,pos3); /* for proper calling GetOptIntFromTable and the like */
if (Delta == 0)
Command = CAST(int, check_env_flag(L, 1));
switch(Command)
{
default:
return luaL_argerror(L, 1, "command not supported");
case ACTL_COMMIT:
case ACTL_GETWINDOWCOUNT:
case ACTL_PROGRESSNOTIFY:
case ACTL_REDRAWALL:
break;
case ACTL_QUIT:
Param1 = luaL_optinteger(L, pos2, EXIT_SUCCESS);
break;
case ACTL_GETFARHWND:
lua_pushlightuserdata(L, CAST(void*, Info->AdvControl(PluginId, Command, 0, NULL)));
return 1;
case ACTL_SETCURRENTWINDOW:
Param1 = luaL_checkinteger(L, pos2) - 1;
break;
case ACTL_WAITKEY:
{
INPUT_RECORD ir;
if (!lua_isnoneornil(L, pos3))
{
OptInputRecord(L, pd, pos3, &ir);
Param2 = &ir;
}
lua_pushinteger(L, Info->AdvControl(PluginId, Command, Param1, Param2));
return 1;
}
case ACTL_GETCOLOR:
{
struct FarColor fc;
Param1 = luaL_checkinteger(L, pos2);
if (Info->AdvControl(PluginId, Command, Param1, &fc))
PushFarColor(L, &fc);
else
lua_pushnil(L);
return 1;
}
case ACTL_SYNCHRO:
if (lua_isfunction(L, pos2)) {
TSynchroData *sd = CreateSynchroData(SYNCHRO_FUNCTION, 0, NULL);
int top = lua_gettop(L);
sd->narg = top - pos2 + 1;
lua_newtable(L);
for (int i=pos2,j=1; i <= top; ) {
lua_pushvalue(L, i++);
lua_rawseti(L, -2, j++);
}
sd->ref = luaL_ref(L, LUA_REGISTRYINDEX);
lua_pushinteger(L, Info->AdvControl(PluginId, Command, 0, sd));
return 1;
}
else {
luaL_argcheck(L, lua_isnumber(L,pos2), pos2, "integer or function expected");
TSynchroData *sd = CreateSynchroData(SYNCHRO_COMMON, lua_tointeger(L,pos2), NULL);
lua_pushinteger(L, Info->AdvControl(PluginId, Command, 0, sd));
return 1;
}
case ACTL_SETPROGRESSSTATE:
Param1 = (intptr_t) check_env_flag(L, pos2);
break;
case ACTL_SETPROGRESSVALUE:
{
struct ProgressValue pv;
luaL_checktype(L, pos3, LUA_TTABLE);
pv.StructSize = sizeof(pv);
pv.Completed = (UINT64)GetOptNumFromTable(L, "Completed", 0.0);
pv.Total = (UINT64)GetOptNumFromTable(L, "Total", 100.0);
lua_pushinteger(L, Info->AdvControl(PluginId, Command, Param1, &pv));
return 1;
}
case ACTL_GETARRAYCOLOR:
{
intptr_t len = Info->AdvControl(PluginId, Command, 0, NULL), i;
struct FarColor *arr = (struct FarColor*) lua_newuserdata(L, len*sizeof(struct FarColor));
Info->AdvControl(PluginId, Command, len, arr);
lua_createtable(L, (int)len, 0);
for(i=0; i < len; i++)
{
PushFarColor(L, &arr[i]);
lua_rawseti(L, -2, (int)i+1);
}
return 1;
}
case ACTL_GETFARMANAGERVERSION:
{
struct VersionInfo vi;
Info->AdvControl(PluginId, Command, 0, &vi);
if (lua_toboolean(L, pos2))
{
lua_pushinteger(L, vi.Major);
lua_pushinteger(L, vi.Minor);
lua_pushinteger(L, vi.Revision);
lua_pushinteger(L, vi.Build);
lua_pushinteger(L, vi.Stage);
return 5;
}
lua_pushfstring(L, "%d.%d.%d.%d.%d", vi.Major, vi.Minor, vi.Revision, vi.Build, vi.Stage);
return 1;
}
case ACTL_GETWINDOWINFO:
{
intptr_t r;
struct WindowInfo wi;
memset(&wi, 0, sizeof(wi));
wi.StructSize = sizeof(wi);
wi.Pos = luaL_optinteger(L, pos2, 0) - 1;
r = Info->AdvControl(PluginId, Command, 0, &wi);
if (!r)
return lua_pushnil(L), 1;
wi.TypeName = (wchar_t*)
lua_newuserdata(L, (wi.TypeNameSize + wi.NameSize) * sizeof(wchar_t));
wi.Name = wi.TypeName + wi.TypeNameSize;
r = Info->AdvControl(PluginId, Command, 0, &wi);
if (!r)
return lua_pushnil(L), 1;
lua_createtable(L,0,6);
switch(wi.Type)
{
case WTYPE_DIALOG:
case WTYPE_VMENU:
case WTYPE_COMBOBOX:
NewDialogData(L, Info, CAST(HANDLE, wi.Id), FALSE);
lua_setfield(L, -2, "Id");
break;
default:
PutIntToTable(L, "Id", CAST(int, wi.Id));
break;
}
PutIntToTable(L, "Pos", wi.Pos + 1);
PutIntToTable(L, "Type", wi.Type);
PutFlagsToTable(L, "Flags", wi.Flags);
PutWStrToTable(L, "TypeName", wi.TypeName, -1);
PutWStrToTable(L, "Name", wi.Name, -1);
return 1;
}
case ACTL_SETARRAYCOLOR:
{
struct FarSetColors fsc;
size_t size;
int i;
luaL_checktype(L, pos3, LUA_TTABLE);
fsc.StructSize = sizeof(fsc);
fsc.StartIndex = GetOptIntFromTable(L, "StartIndex", 0);
lua_getfield(L, pos3, "Flags");
fsc.Flags = GetFlagCombination(L, -1, NULL);
fsc.ColorsCount = lua_objlen(L, pos3);
size = fsc.ColorsCount * sizeof(struct FarColor);
fsc.Colors = (struct FarColor*) lua_newuserdata(L, size);
memset(fsc.Colors, 0, size);
for(i=0; i < (int)fsc.ColorsCount; i++)
{
lua_rawgeti(L, pos3, i+1);
GetFarColor(L, -1, &fsc.Colors[i]);
lua_pop(L,1);
}
lua_pushinteger(L, Info->AdvControl(PluginId, Command, Param1, &fsc));
return 1;
}
case ACTL_GETFARRECT:
{
SMALL_RECT sr;
if (Info->AdvControl(PluginId, Command, 0, &sr))
{
lua_createtable(L, 0, 4);
PutIntToTable(L, "Left", sr.Left);
PutIntToTable(L, "Top", sr.Top);
PutIntToTable(L, "Right", sr.Right);
PutIntToTable(L, "Bottom", sr.Bottom);
}
else
lua_pushnil(L);
return 1;
}
case ACTL_GETCURSORPOS:
{
COORD coord;
if (Info->AdvControl(PluginId, Command, 0, &coord))
{
lua_createtable(L, 0, 2);
PutIntToTable(L, "X", coord.X);
PutIntToTable(L, "Y", coord.Y);
}
else
lua_pushnil(L);
return 1;
}
case ACTL_SETCURSORPOS:
{
COORD coord;
luaL_checktype(L, pos3, LUA_TTABLE);
lua_getfield(L, pos3, "X");
coord.X = (SHORT) lua_tointeger(L, -1);
lua_getfield(L, pos3, "Y");
coord.Y = (SHORT) lua_tointeger(L, -1);
lua_pushinteger(L, Info->AdvControl(PluginId, Command, Param1, &coord));
return 1;
}
case ACTL_GETWINDOWTYPE:
{
struct WindowType wt;
wt.StructSize = sizeof(wt);
if (Info->AdvControl(PluginId, Command, 0, &wt))
{
lua_createtable(L, 0, 1);
lua_pushinteger(L, wt.Type);
lua_setfield(L, -2, "Type");
}
else lua_pushnil(L);
return 1;
}
}
lua_pushinteger(L, Info->AdvControl(PluginId, Command, Param1, Param2));
return 1;
}
#define AdvCommand(name,command) \
static int adv_##name(lua_State *L) { return DoAdvControl(L,command,1); }
static int far_AdvControl(lua_State *L) { return DoAdvControl(L,0,0); }
AdvCommand( Commit, ACTL_COMMIT)
AdvCommand( GetArrayColor, ACTL_GETARRAYCOLOR)
AdvCommand( GetColor, ACTL_GETCOLOR)
AdvCommand( GetCursorPos, ACTL_GETCURSORPOS)
AdvCommand( GetFarHwnd, ACTL_GETFARHWND)
AdvCommand( GetFarManagerVersion, ACTL_GETFARMANAGERVERSION)
AdvCommand( GetFarRect, ACTL_GETFARRECT)
AdvCommand( GetWindowCount, ACTL_GETWINDOWCOUNT)
AdvCommand( GetWindowInfo, ACTL_GETWINDOWINFO)
AdvCommand( GetWindowType, ACTL_GETWINDOWTYPE)
AdvCommand( ProgressNotify, ACTL_PROGRESSNOTIFY)
AdvCommand( Quit, ACTL_QUIT)
AdvCommand( RedrawAll, ACTL_REDRAWALL)
AdvCommand( SetArrayColor, ACTL_SETARRAYCOLOR)
AdvCommand( SetCurrentWindow, ACTL_SETCURRENTWINDOW)
AdvCommand( SetCursorPos, ACTL_SETCURSORPOS)
AdvCommand( SetProgressState, ACTL_SETPROGRESSSTATE)
AdvCommand( SetProgressValue, ACTL_SETPROGRESSVALUE)
AdvCommand( Synchro, ACTL_SYNCHRO)
AdvCommand( WaitKey, ACTL_WAITKEY)
static int far_MacroLoadAll(lua_State* L)
{
TPluginData *pd = GetPluginData(L);
struct FarMacroLoad Data;
Data.StructSize = sizeof(Data);
Data.Path = opt_utf8_string(L, 1, NULL);
Data.Flags = OptFlags(L, 2, 0);
lua_pushboolean(L, pd->Info->MacroControl(pd->PluginId, MCTL_LOADALL, 0, (void*)&Data) != 0);
return 1;
}
static int far_MacroSaveAll(lua_State* L)
{
TPluginData *pd = GetPluginData(L);
lua_pushboolean(L, pd->Info->MacroControl(pd->PluginId, MCTL_SAVEALL, 0, 0) != 0);
return 1;
}
static int far_MacroGetState(lua_State* L)
{
TPluginData *pd = GetPluginData(L);
lua_pushinteger(L, pd->Info->MacroControl(pd->PluginId, MCTL_GETSTATE, 0, 0));
return 1;
}
static int far_MacroGetArea(lua_State* L)
{
TPluginData *pd = GetPluginData(L);
lua_pushinteger(L, pd->Info->MacroControl(pd->PluginId, MCTL_GETAREA, 0, 0));
return 1;
}
static int MacroSendString(lua_State* L, int Param1)
{
TPluginData *pd = GetPluginData(L);
struct MacroSendMacroText smt;
memset(&smt, 0, sizeof(smt));
smt.StructSize = sizeof(smt);
smt.SequenceText = check_utf8_string(L, 1, NULL);
smt.Flags = OptFlags(L, 2, 0);
if (Param1 == MSSC_POST)
OptInputRecord(L, pd, 3, &smt.AKey);
lua_pushboolean(L, pd->Info->MacroControl(pd->PluginId, MCTL_SENDSTRING, Param1, &smt) != 0);
return 1;
}
static int far_MacroPost(lua_State* L)
{
return MacroSendString(L, MSSC_POST);
}
static int far_MacroCheck(lua_State* L)
{
return MacroSendString(L, MSSC_CHECK);
}
static int far_MacroGetLastError(lua_State* L)
{
TPluginData *pd = GetPluginData(L);
intptr_t size = pd->Info->MacroControl(pd->PluginId, MCTL_GETLASTERROR, 0, NULL);
if (size)
{
struct MacroParseResult *mpr = (struct MacroParseResult*)lua_newuserdata(L, size);
mpr->StructSize = sizeof(*mpr);
pd->Info->MacroControl(pd->PluginId, MCTL_GETLASTERROR, size, mpr);
lua_createtable(L, 0, 4);
PutIntToTable(L, "ErrCode", mpr->ErrCode);
PutIntToTable(L, "ErrPosX", mpr->ErrPos.X);
PutIntToTable(L, "ErrPosY", mpr->ErrPos.Y);
PutWStrToTable(L, "ErrSrc", mpr->ErrSrc, -1);
}
else
lua_pushboolean(L, 0);
return 1;
}
typedef struct
{
lua_State *L;
int funcref;
} MacroAddData;
intptr_t WINAPI MacroAddCallback (void* Id, FARADDKEYMACROFLAGS Flags)
{
lua_State *L;
int result = TRUE;
MacroAddData *data = (MacroAddData*)Id;
if ((L = data->L) == NULL)
return FALSE;
lua_rawgeti(L, LUA_REGISTRYINDEX, data->funcref);
if (lua_type(L,-1) == LUA_TFUNCTION)
{
lua_pushlightuserdata(L, Id);
lua_rawget(L, LUA_REGISTRYINDEX);
bit64_push(L, Flags);
result = !lua_pcall(L, 2, 1, 0) && lua_toboolean(L, -1);
}
lua_pop(L, 1);
return result;
}
static int far_MacroAdd(lua_State* L)
{
TPluginData *pd = GetPluginData(L);
struct MacroAddMacro data;
memset(&data, 0, sizeof(data));
data.StructSize = sizeof(data);
data.Area = OptFlags(L, 1, MACROAREA_COMMON);
data.Flags = OptFlags(L, 2, 0);
OptInputRecord(L, pd, 3, &data.AKey);
data.SequenceText = check_utf8_string(L, 4, NULL);
data.Description = opt_utf8_string(L, 5, L"");
lua_settop(L, 7);
if (lua_toboolean(L, 6))
{
luaL_checktype(L, 6, LUA_TFUNCTION);
data.Callback = MacroAddCallback;
}
data.Id = lua_newuserdata(L, sizeof(MacroAddData));
data.Priority = luaL_optinteger(L, 7, 50);
if (pd->Info->MacroControl(pd->PluginId, MCTL_ADDMACRO, 0, &data))
{
MacroAddData* Id = (MacroAddData*)data.Id;
lua_isfunction(L, 6) ? lua_pushvalue(L, 6) : lua_pushboolean(L, 1);
Id->funcref = luaL_ref(L, LUA_REGISTRYINDEX);
Id->L = pd->MainLuaState;
luaL_getmetatable(L, AddMacroDataType);
lua_setmetatable(L, -2);
lua_pushlightuserdata(L, Id); // Place it in the registry to protect from gc. It should be collected only at lua_close().
lua_pushvalue(L, -2);
lua_rawset(L, LUA_REGISTRYINDEX);
}
else
lua_pushnil(L);
return 1;
}
static int far_MacroDelete(lua_State* L)
{
TPluginData *pd = GetPluginData(L);
MacroAddData *Id;
int result = FALSE;
Id = (MacroAddData*)luaL_checkudata(L, 1, AddMacroDataType);
if (Id->L)
{
result = (int)pd->Info->MacroControl(pd->PluginId, MCTL_DELMACRO, 0, Id);
if (result)
{
luaL_unref(L, LUA_REGISTRYINDEX, Id->funcref);
Id->L = NULL;
lua_pushlightuserdata(L, Id);
lua_pushnil(L);
lua_rawset(L, LUA_REGISTRYINDEX);
}
}
lua_pushboolean(L, result);
return 1;
}
static int AddMacroData_gc(lua_State* L)
{
far_MacroDelete(L);
return 0;
}
static int far_MacroExecute(lua_State* L)
{
TPluginData *pd = GetPluginData(L);
int top = lua_gettop(L);
struct MacroExecuteString Data;
Data.StructSize = sizeof(Data);
Data.SequenceText = check_utf8_string(L, 1, NULL);
Data.Flags = OptFlags(L,2,0);
Data.InCount = 0;
if (top > 2)
{
size_t i;
Data.InCount = top-2;
Data.InValues = (struct FarMacroValue*)lua_newuserdata(L, Data.InCount*sizeof(struct FarMacroValue));
memset(Data.InValues, 0, Data.InCount*sizeof(struct FarMacroValue));
for (i=0; i<Data.InCount; i++)
ConvertLuaValue(L, (int)i+3, Data.InValues+i);
}
if (pd->Info->MacroControl(pd->PluginId, MCTL_EXECSTRING, 0, &Data))
PackMacroValues(L, Data.OutCount, Data.OutValues);
else
lua_pushnil(L);
return 1;
}
static int far_CPluginStartupInfo(lua_State *L)
{
return lua_pushlightuserdata(L, (void*)GetPluginData(L)->Info), 1;
}
void pushFileTime(lua_State *L, const FILETIME *ft)
{
long long llFileTime = ft->dwLowDateTime + 0x100000000LL * ft->dwHighDateTime;
if (! (GetPluginData(L)->Flags & PDF_FULL_TIME_RESOLUTION))
lua_pushnumber(L, (double)(llFileTime / 10000));
else
bit64_pushuserdata(L, llFileTime);
}
static int far_MakeMenuItems(lua_State *L)
{
int argn = lua_gettop(L);
lua_createtable(L, argn, 0); //+1 (items)
if (argn > 0)
{
int item = 1, i;
char delim[] = { 226,148,130,0 }; // Unicode char 9474 in UTF-8
char buf_prefix[64], buf_space[64];
int maxno = 0;
size_t len_prefix;
for (i=argn; i; maxno++,i/=10) {}
len_prefix = sprintf(buf_space, "%*s%s ", maxno, "", delim);
for(i=1; i<=argn; i++)
{
size_t j, len_arg;
const char *start;
char* str;
start = luaL_tolstring(L, i, &len_arg); //+2
sprintf(buf_prefix, "%*d%s ", maxno, i, delim);
str = (char*) malloc(len_arg + 1);
memcpy(str, start, len_arg + 1);
lua_pop(L, 1); //+1 (items)
for (j=0; j<len_arg; j++)
if (str[j] == '\0') str[j] = ' ';
for (start=str; start; )
{
size_t len_text;
char *line;
const char* nl = strchr(start, '\n');
lua_newtable(L); //+2 (items,curr_item)
len_text = nl ? (nl++) - start : (str+len_arg) - start;
line = (char*) malloc(len_prefix + len_text);
memcpy(line, buf_prefix, len_prefix);
memcpy(line + len_prefix, start, len_text);
lua_pushlstring(L, line, len_prefix + len_text);
free(line);
lua_setfield(L, -2, "text"); //+2
lua_pushvalue(L, i);
lua_setfield(L, -2, "arg"); //+2
lua_rawseti(L, -2, item++); //+1 (items)
strcpy(buf_prefix, buf_space);
start = nl;
}
free(str);
}
}
return 1;
}
static int far_Show(lua_State *L)
{
const char* f =
"local items,n=...\n"
"local bottom=n==0 and 'No arguments' or n==1 and '1 argument' or n..' arguments'\n"
"return far.Menu({Title='',Bottom=bottom,Flags='FMENU_SHOWAMPERSAND FMENU_WRAPMODE'},items,"
"{{BreakKey='SPACE'}})";
int argn = lua_gettop(L);
far_MakeMenuItems(L);
if (luaL_loadstring(L, f) != 0)
luaL_error(L, lua_tostring(L, -1));
lua_pushvalue(L, -2);
lua_pushinteger(L, argn);
if (lua_pcall(L, 2, LUA_MULTRET, 0) != 0)
luaL_error(L, lua_tostring(L, -1));
return lua_gettop(L) - argn - 1;
}
void NewVirtualKeyTable(lua_State* L, BOOL twoways)
{
int i;
lua_createtable(L, twoways ? 256:0, 200);
for(i=0; i<256; i++)
{
const char* str = VirtualKeyStrings[i];
if (str)
{
lua_pushinteger(L, i);
lua_setfield(L, -2, str);
}
if (twoways)
{
lua_pushstring(L, str ? str : "");
lua_rawseti(L, -2, i);
}
}
}
HANDLE* CheckFileFilter(lua_State* L, int pos)
{
return (HANDLE*)luaL_checkudata(L, pos, FarFileFilterType);
}
HANDLE CheckValidFileFilter(lua_State* L, int pos)
{
HANDLE h = *CheckFileFilter(L, pos);
luaL_argcheck(L,h != INVALID_HANDLE_VALUE,pos,"attempt to access invalid file filter");
return h;
}
static int far_CreateFileFilter(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
HANDLE hHandle = (luaL_checkinteger(L,1) % 2) ? PANEL_ACTIVE:PANEL_PASSIVE;
int filterType = CAST(int, check_env_flag(L,2));
HANDLE* pOutHandle = (HANDLE*)lua_newuserdata(L, sizeof(HANDLE));
if (Info->FileFilterControl(hHandle, FFCTL_CREATEFILEFILTER, filterType, pOutHandle))
{
luaL_getmetatable(L, FarFileFilterType);
lua_setmetatable(L, -2);
}
else
lua_pushnil(L);
return 1;
}
static int filefilter_Free(lua_State *L)
{
HANDLE *h = CheckFileFilter(L, 1);
if (*h != INVALID_HANDLE_VALUE)
{
PSInfo *Info = GetPluginData(L)->Info;
lua_pushboolean(L, Info->FileFilterControl(*h, FFCTL_FREEFILEFILTER, 0, 0) != 0);
*h = INVALID_HANDLE_VALUE;
}
else
lua_pushboolean(L,0);
return 1;
}
static int filefilter_gc(lua_State *L)
{
filefilter_Free(L);
return 0;
}
static int filefilter_tostring(lua_State *L)
{
HANDLE *h = CheckFileFilter(L, 1);
if (*h != INVALID_HANDLE_VALUE)
lua_pushfstring(L, "%s (%p)", FarFileFilterType, h);
else
lua_pushfstring(L, "%s (closed)", FarFileFilterType);
return 1;
}
static int filefilter_OpenMenu(lua_State *L)
{
HANDLE h = CheckValidFileFilter(L, 1);
PSInfo *Info = GetPluginData(L)->Info;
lua_pushboolean(L, Info->FileFilterControl(h, FFCTL_OPENFILTERSMENU, 0, 0) != 0);
return 1;
}
static int filefilter_Starting(lua_State *L)
{
HANDLE h = CheckValidFileFilter(L, 1);
PSInfo *Info = GetPluginData(L)->Info;
lua_pushboolean(L, Info->FileFilterControl(h, FFCTL_STARTINGTOFILTER, 0, 0) != 0);
return 1;
}
static int filefilter_IsFileInFilter(lua_State *L)
{
struct PluginPanelItem ppi;
PSInfo *Info = GetPluginData(L)->Info;
HANDLE h = CheckValidFileFilter(L, 1);
luaL_checktype(L, 2, LUA_TTABLE);
lua_settop(L, 2); // +2
FillPluginPanelItem(L, &ppi, 0); // +6
lua_pushboolean(L, Info->FileFilterControl(h, FFCTL_ISFILEINFILTER, 0, &ppi) != 0);
return 1;
}
static int plugin_load(lua_State *L, enum FAR_PLUGINS_CONTROL_COMMANDS command)
{
PSInfo *Info = GetPluginData(L)->Info;
int param1 = CAST(int, check_env_flag(L, 1));
void *param2 = check_utf8_string(L, 2, NULL);
intptr_t result = Info->PluginsControl(INVALID_HANDLE_VALUE, command, param1, param2);
if (result) PushPluginHandle(L, CAST(HANDLE, result));
else lua_pushnil(L);
return 1;
}
static int far_LoadPlugin(lua_State *L) { return plugin_load(L, PCTL_LOADPLUGIN); }
static int far_ForcedLoadPlugin(lua_State *L) { return plugin_load(L, PCTL_FORCEDLOADPLUGIN); }
static int far_UnloadPlugin(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
void* Handle = *(void**)luaL_checkudata(L, 1, PluginHandleType);
lua_pushboolean(L, Info->PluginsControl(Handle, PCTL_UNLOADPLUGIN, 0, 0) != 0);
return 1;
}
static int far_FindPlugin(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
int param1 = CAST(int, check_env_flag(L, 1));
void *param2 = NULL;
if (param1 == PFM_MODULENAME)
param2 = check_utf8_string(L, 2, NULL);
else if (param1 == PFM_GUID)
{
size_t len;
param2 = CAST(void*, luaL_checklstring(L, 2, &len));
if (len < sizeof(GUID)) param2 = NULL;
}
if (param2)
{
intptr_t handle = Info->PluginsControl(NULL, PCTL_FINDPLUGIN, param1, param2);
if (handle)
{
PushPluginHandle(L, CAST(HANDLE, handle));
return 1;
}
}
lua_pushnil(L);
return 1;
}
static void PutPluginMenuItemToTable(lua_State *L, const char* field, const struct PluginMenuItem *mi)
{
lua_createtable(L, 0, 3);
{
int i;
PutIntToTable(L, "Count", mi->Count);
lua_createtable(L, (int) mi->Count, 0); // Guids
lua_createtable(L, (int) mi->Count, 0); // Strings
for(i=0; i < (int) mi->Count; i++)
{
lua_pushlstring(L, CAST(const char*, mi->Guids + i), sizeof(GUID));
lua_rawseti(L, -3, i+1);
push_utf8_string(L, mi->Strings[i], -1);
lua_rawseti(L, -2, i+1);
}
lua_setfield(L, -3, "Strings");
lua_setfield(L, -2, "Guids");
}
lua_setfield(L, -2, field);
}
static void PutVersionInfoToTable(lua_State *L, const char* field, const struct VersionInfo *vi)
{
lua_createtable(L, 5, 0);
PutIntToArray(L, 1, vi->Major);
PutIntToArray(L, 2, vi->Minor);
PutIntToArray(L, 3, vi->Revision);
PutIntToArray(L, 4, vi->Build);
PutIntToArray(L, 5, vi->Stage);
lua_setfield(L, -2, field);
}
static int far_GetPluginInformation(lua_State *L)
{
struct FarGetPluginInformation *pi;
PSInfo *Info = GetPluginData(L)->Info;
HANDLE Handle = *(HANDLE*)luaL_checkudata(L, 1, PluginHandleType);
size_t size = Info->PluginsControl(Handle, PCTL_GETPLUGININFORMATION, 0, 0);
if (size == 0) return lua_pushnil(L), 1;
pi = (struct FarGetPluginInformation *)lua_newuserdata(L, size);
pi->StructSize = sizeof(*pi);
if (!Info->PluginsControl(Handle, PCTL_GETPLUGININFORMATION, size, pi))
return lua_pushnil(L), 1;
lua_createtable(L, 0, 4);
{
PutWStrToTable(L, "ModuleName", pi->ModuleName, -1);
PutFlagsToTable(L, "Flags", pi->Flags);
lua_createtable(L, 0, 6); // PInfo
{
PutIntToTable(L, "StructSize", pi->PInfo->StructSize);
PutFlagsToTable(L, "Flags", pi->PInfo->Flags);
PutPluginMenuItemToTable(L, "DiskMenu", &pi->PInfo->DiskMenu);
PutPluginMenuItemToTable(L, "PluginMenu", &pi->PInfo->PluginMenu);
PutPluginMenuItemToTable(L, "PluginConfig", &pi->PInfo->PluginConfig);
if (pi->PInfo->CommandPrefix)
PutWStrToTable(L, "CommandPrefix", pi->PInfo->CommandPrefix, -1);
lua_setfield(L, -2, "PInfo");
}
lua_createtable(L, 0, 7); // GInfo
{
PutIntToTable(L, "StructSize", pi->GInfo->StructSize);
PutVersionInfoToTable(L, "MinFarVersion", &pi->GInfo->MinFarVersion);
PutVersionInfoToTable(L, "Version", &pi->GInfo->Version);
PutLStrToTable(L, "Guid", (const char*)&pi->GInfo->Guid, sizeof(GUID));
PutWStrToTable(L, "Title", pi->GInfo->Title, -1);
PutWStrToTable(L, "Description", pi->GInfo->Description, -1);
PutWStrToTable(L, "Author", pi->GInfo->Author, -1);
lua_setfield(L, -2, "GInfo");
}
}
return 1;
}
static int far_GetPlugins(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
int count = (int)Info->PluginsControl(INVALID_HANDLE_VALUE, PCTL_GETPLUGINS, 0, 0);
lua_createtable(L, count, 0);
if (count > 0)
{
int i;
HANDLE *handles = lua_newuserdata(L, count*sizeof(HANDLE));
count = (int)Info->PluginsControl(INVALID_HANDLE_VALUE, PCTL_GETPLUGINS, count, handles);
for(i=0; i<count; i++)
{
PushPluginHandle(L, handles[i]);
lua_rawseti(L, -3, i+1);
}
lua_pop(L, 1);
}
return 1;
}
static int far_IsPluginLoaded(lua_State *L)
{
UUID uuid;
size_t len;
intptr_t handle;
int result = 0;
const char *guid = luaL_checklstring(L, 1, &len);
PSInfo *Info = GetPluginData(L)->Info;
if (len == 16)
uuid = *(UUID*)guid;
else
luaL_argcheck(L, UuidFromStringA((unsigned char*)guid, &uuid) == RPC_S_OK, 1, "invalid GUID");
handle = Info->PluginsControl(NULL, PCTL_FINDPLUGIN, PFM_GUID, &uuid);
if (handle)
{
size_t size = Info->PluginsControl((HANDLE)handle, PCTL_GETPLUGININFORMATION, 0, 0);
if (size)
{
struct FarGetPluginInformation *pi = (struct FarGetPluginInformation *)malloc(size);
pi->StructSize = sizeof(*pi);
if (Info->PluginsControl((HANDLE)handle, PCTL_GETPLUGININFORMATION, size, pi))
result = (pi->Flags & FPF_LOADED) ? 1:0;
free(pi);
}
}
lua_pushboolean(L, result);
return 1;
}
static int far_XLat(lua_State *L)
{
size_t size;
wchar_t *Line = check_utf8_string(L, 1, &size), *str;
intptr_t StartPos = luaL_optinteger(L, 2, 1) - 1;
intptr_t EndPos = luaL_optinteger(L, 3, size);
UINT64 Flags = OptFlags(L, 4, 0);
StartPos < 0 ? StartPos = 0 : StartPos > (intptr_t)size ? StartPos = size : 0;
EndPos < StartPos ? EndPos = StartPos : EndPos > (intptr_t)size ? EndPos = size : 0;
str = GetPluginData(L)->FSF->XLat(Line, StartPos, EndPos, Flags);
str ? (void)push_utf8_string(L, str, -1) : lua_pushnil(L);
return 1;
}
static int far_FormatFileSize(lua_State *L)
{
uint64_t Size = (uint64_t) luaL_checknumber(L, 1);
int Width = (int)luaL_checkinteger(L, 2);
if (abs(Width) > 10000)
return luaL_error(L, "the 'Width' argument exceeds 10000");
UINT64 Flags = OptFlags(L, 3, 0) & ~FFFS_MINSIZEINDEX_MASK;
Flags |= luaL_optinteger(L, 4, 0) & FFFS_MINSIZEINDEX_MASK;
TPluginData *pd = GetPluginData(L);
size_t bufsize = pd->FSF->FormatFileSize(Size, Width, Flags, NULL, 0);
wchar_t *buf = (wchar_t*) lua_newuserdata(L, bufsize*sizeof(wchar_t));
pd->FSF->FormatFileSize(Size, Width, Flags, buf, bufsize);
push_utf8_string(L, buf, -1);
return 1;
}
static int far_FarClock(lua_State *L)
{
UINT64 c = GetPluginData(L)->FSF->FarClock();
lua_pushnumber(L, (double)c);
return 1;
}
void CALLBACK TimerCallback(void *lpParameter, BOOLEAN TimerOrWaitFired)
{
TTimerData *td = (TTimerData*)lpParameter;
TSynchroData *sd;
(void)TimerOrWaitFired;
if (!td->needClose && td->enabled)
{
sd = CreateSynchroData(SYNCHRO_TIMER_CALL, 0, td);
td->Info->AdvControl(td->PluginGuid, ACTL_SYNCHRO, 0, sd);
}
}
static int far_Timer(lua_State *L)
{
TPluginData *pd;
TTimerData *td;
HANDLE hQueue;
int interval, index, tabSize;
interval = (int)luaL_checkinteger(L, 1);
luaL_checktype(L, 2, LUA_TFUNCTION);
tabSize = lua_gettop(L);
lua_createtable(L, tabSize, 1); // place the function at [1]
lua_pushinteger(L, tabSize);
lua_setfield(L, -2, "n");
lua_pushvalue(L, 2);
lua_rawseti(L, -2, 1);
td = (TTimerData*)lua_newuserdata(L, sizeof(TTimerData));
luaL_getmetatable(L, FarTimerType);
lua_setmetatable(L, -2);
lua_pushvalue(L, -1);
lua_rawseti(L, -3, 2); // place the userdata at [2]
for (index=3; index<=tabSize; index++) // place the arguments, if any
{
lua_pushvalue(L, index);
lua_rawseti(L, -3, index);
}
pd = GetPluginData(L);
td->Info = pd->Info;
td->PluginGuid = pd->PluginId;
td->interval = interval < 1 ? 1 : interval;
lua_pushvalue(L, -2);
td->tabRef = luaL_ref(L, LUA_REGISTRYINDEX);
td->needClose = FALSE;
td->enabled = 1;
hQueue = GetLuaStateTimerQueue(L);
if (hQueue && CreateTimerQueueTimer(&td->hTimer,hQueue,TimerCallback,td,td->interval,td->interval,WT_EXECUTEDEFAULT))
return 1;
luaL_unref(L, LUA_REGISTRYINDEX, td->tabRef);
return lua_pushnil(L), 1;
}
TTimerData* CheckTimer(lua_State* L, int pos)
{
return (TTimerData*)luaL_checkudata(L, pos, FarTimerType);
}
TTimerData* CheckValidTimer(lua_State* L, int pos)
{
TTimerData* td = CheckTimer(L, pos);
luaL_argcheck(L, !td->needClose, pos, "attempt to access closed timer");
return td;
}
static int timer_Close(lua_State *L)
{
HANDLE hQueue;
TSynchroData* sd;
TTimerData* td = CheckTimer(L, 1);
if (!td->needClose)
{
td->needClose = TRUE;
hQueue = GetLuaStateTimerQueue(L);
if (hQueue)
DeleteTimerQueueTimer(hQueue, td->hTimer, NULL);
sd = CreateSynchroData(SYNCHRO_TIMER_UNREF, 0, td);
td->Info->AdvControl(td->PluginGuid, ACTL_SYNCHRO, 0, sd);
}
return 0;
}
static int timer_gc(lua_State *L)
{
HANDLE hQueue;
TTimerData* td = CheckTimer(L, 1);
if (!td->needClose)
{
td->needClose = TRUE;
hQueue = GetLuaStateTimerQueue(L);
if (hQueue)
DeleteTimerQueueTimer(hQueue, td->hTimer, NULL);
}
return 0;
}
static int timer_tostring(lua_State *L)
{
TTimerData* td = CheckTimer(L, 1);
if (!td->needClose)
lua_pushfstring(L, "%s (%p)", FarTimerType, td);
else
lua_pushfstring(L, "%s (closed)", FarTimerType);
return 1;
}
static int timer_index(lua_State *L)
{
TTimerData* td = CheckTimer(L, 1);
const char* method = luaL_checkstring(L, 2);
if (!strcmp(method, "Close"))
lua_pushcfunction(L, timer_Close);
else if (!strcmp(method, "Enabled"))
lua_pushboolean(L, td->enabled);
else if (!strcmp(method, "Interval"))
lua_pushinteger(L, td->interval);
else if (!strcmp(method, "OnTimer"))
{
lua_rawgeti(L, LUA_REGISTRYINDEX, td->tabRef);
lua_rawgeti(L, -1, 1);
}
else if (!strcmp(method, "Closed"))
lua_pushboolean(L, td->needClose);
else
luaL_error(L, "attempt to call non-existent method");
return 1;
}
static int timer_newindex(lua_State *L)
{
TTimerData* td = CheckValidTimer(L, 1);
const char* method = luaL_checkstring(L, 2);
if (!strcmp(method, "Enabled"))
{
luaL_checkany(L, 3);
td->enabled = lua_toboolean(L, 3);
}
else if (!strcmp(method, "Interval"))
{
int interval = (int)luaL_checkinteger(L, 3);
HANDLE hQueue = GetLuaStateTimerQueue(L);
if (hQueue)
{
td->interval = interval < 1 ? 1 : interval;
ChangeTimerQueueTimer(hQueue, td->hTimer, td->interval, td->interval);
}
}
else if (!strcmp(method, "OnTimer"))
{
luaL_checktype(L, 3, LUA_TFUNCTION);
lua_rawgeti(L, LUA_REGISTRYINDEX, td->tabRef);
lua_pushvalue(L, 3);
lua_rawseti(L, -2, 1);
}
else luaL_error(L, "attempt to call non-existent method");
return 0;
}
typedef struct
{
HANDLE Handle;
BOOL IsFarSettings;
} FarSettingsUdata;
static int far_CreateSettings(lua_State *L)
{
size_t len = 0;
const char* strId;
const GUID* ParamId;
FarSettingsUdata *udata;
struct FarSettingsCreate fsc;
BOOL IsFarSettings = 0;
TPluginData *pd = GetPluginData(L);
int location;
strId = luaL_optlstring(L, 1, NULL, &len);
if (strId == NULL)
ParamId = pd->PluginId;
else
{
if (len == 3 && strcmp(strId, "far") == 0)
IsFarSettings = 1;
else if (len == sizeof(GUID))
IsFarSettings = !memcmp(strId, &FarGuid, len);
else
{
lua_pushnil(L);
return 1;
}
ParamId = IsFarSettings? &FarGuid : CAST(const GUID*, strId);
}
location = CAST(int, OptFlags(L, 2, PSL_ROAMING));
fsc.StructSize = sizeof(fsc);
fsc.Guid = *ParamId;
if (!pd->Info->SettingsControl(INVALID_HANDLE_VALUE, SCTL_CREATE, location, &fsc))
{
lua_pushnil(L);
return 1;
}
lua_getfield(L, LUA_REGISTRYINDEX, SettingsHandles);
udata = (FarSettingsUdata*)lua_newuserdata(L, sizeof(FarSettingsUdata));
udata->Handle = fsc.Handle;
udata->IsFarSettings = IsFarSettings;
luaL_getmetatable(L, SettingsType);
lua_setmetatable(L, -2);
lua_pushvalue(L, -1);
lua_pushinteger(L, 1);
lua_rawset(L, -4);
return 1;
}
static FarSettingsUdata* GetSettingsUdata(lua_State *L, int pos)
{
return luaL_checkudata(L, pos, SettingsType);
}
static FarSettingsUdata* CheckSettings(lua_State *L, int pos)
{
FarSettingsUdata* udata = GetSettingsUdata(L, pos);
if (udata->Handle == INVALID_HANDLE_VALUE)
{
const char* s = lua_pushfstring(L, "attempt to access a closed %s", SettingsType);
luaL_argerror(L, pos, s);
}
return udata;
}
static int Settings_set(lua_State *L)
{
struct FarSettingsItem fsi;
FarSettingsUdata* udata = CheckSettings(L, 1);
fsi.StructSize = sizeof(fsi);
fsi.Root = (size_t)check_env_flag(L, 2);
fsi.Name = opt_utf8_string(L, 3, NULL);
fsi.Type = (enum FARSETTINGSTYPES) check_env_flag(L, 4);
if (fsi.Type == FST_QWORD)
fsi.Value.Number = GetFlagCombination(L, 5, NULL);
else if (fsi.Type == FST_STRING)
fsi.Value.String = check_utf8_string(L, 5, NULL);
else if (fsi.Type == FST_DATA)
fsi.Value.Data.Data = luaL_checklstring(L, 5, &fsi.Value.Data.Size);
else
return lua_pushboolean(L,0), 1;
lua_pushboolean(L, GetPluginData(L)->Info->SettingsControl(udata->Handle, SCTL_SET, 0, &fsi) != 0);
return 1;
}
static int Settings_get(lua_State *L)
{
struct FarSettingsItem fsi;
FarSettingsUdata* udata = CheckSettings(L, 1);
fsi.StructSize = sizeof(fsi);
fsi.Root = (size_t)check_env_flag(L, 2);
fsi.Name = check_utf8_string(L, 3, NULL);
fsi.Type = (enum FARSETTINGSTYPES) check_env_flag(L, 4);
if (GetPluginData(L)->Info->SettingsControl(udata->Handle, SCTL_GET, 0, &fsi))
{
if (fsi.Type == FST_QWORD)
bit64_push(L, fsi.Value.Number);
else if (fsi.Type == FST_STRING)
push_utf8_string(L, fsi.Value.String, -1);
else if (fsi.Type == FST_DATA)
lua_pushlstring(L, fsi.Value.Data.Data, fsi.Value.Data.Size);
else
lua_pushnil(L);
}
else
lua_pushnil(L);
return 1;
}
static int Settings_delete(lua_State *L)
{
struct FarSettingsValue fsv;
FarSettingsUdata* udata = CheckSettings(L, 1);
fsv.StructSize = sizeof(fsv);
fsv.Root = (size_t)check_env_flag(L, 2);
fsv.Value = opt_utf8_string(L, 3, NULL);
lua_pushboolean(L, GetPluginData(L)->Info->SettingsControl(udata->Handle, SCTL_DELETE, 0, &fsv) != 0);
return 1;
}
static int Settings_createsubkey(lua_State *L)
{
PSInfo *Info = GetPluginData(L)->Info;
const wchar_t *description;
struct FarSettingsValue fsv;
intptr_t subkey;
FarSettingsUdata* udata = CheckSettings(L, 1);
fsv.StructSize = sizeof(fsv);
fsv.Root = (size_t)check_env_flag(L, 2);
fsv.Value = check_utf8_string(L, 3, NULL);
description = opt_utf8_string(L, 4, NULL);
subkey = Info->SettingsControl(udata->Handle, SCTL_CREATESUBKEY, 0, &fsv);
if (subkey != 0)
{
if (description != NULL)
{
struct FarSettingsItem fsi;
fsi.StructSize = sizeof(fsi);
fsi.Root = subkey;
fsi.Name = NULL;
fsi.Type = FST_STRING;
fsi.Value.String = description;
Info->SettingsControl(udata->Handle, SCTL_SET, 0, &fsi);
}
lua_pushinteger(L, subkey);
}
else
lua_pushnil(L);
return 1;
}
static int Settings_opensubkey(lua_State *L)
{
intptr_t subkey;
struct FarSettingsValue fsv;
FarSettingsUdata* udata = CheckSettings(L, 1);
fsv.StructSize = sizeof(fsv);
fsv.Root = (size_t)check_env_flag(L, 2);
fsv.Value = check_utf8_string(L, 3, NULL);
subkey = GetPluginData(L)->Info->SettingsControl(udata->Handle, SCTL_OPENSUBKEY, 0, &fsv);
if (subkey != 0)
lua_pushinteger(L, subkey);
else
lua_pushnil(L);
return 1;
}
static int Settings_enum(lua_State *L)
{
struct FarSettingsEnum fse;
intptr_t i, from = 1, to = -1;
FarSettingsUdata* udata = CheckSettings(L, 1);
fse.StructSize = sizeof(fse);
fse.Root = (size_t)check_env_flag(L, 2);
if (!lua_isnoneornil(L, 3)) from = luaL_checkinteger(L, 3);
if (!lua_isnoneornil(L, 4)) to = luaL_checkinteger(L, 4);
if (GetPluginData(L)->Info->SettingsControl(udata->Handle, SCTL_ENUM, 0, &fse))
{
if (from < 1 && (from += fse.Count + 1) < 1) from = 1;
--from;
if (to < 0 && (to += fse.Count + 1) < 0) to = 0;
if (to > (int)fse.Count) to = fse.Count;
lua_createtable(L, (int)fse.Count, 1);
PutIntToTable(L, "Count", (int)fse.Count);
for(i = from; i < to; i++)
{
if (udata->IsFarSettings)
{
const struct FarSettingsHistory *fsh = fse.Value.Histories + i;
lua_createtable(L, 0, 6);
if (fsh->Name) PutWStrToTable(L, "Name", fsh->Name, -1);
if (fsh->Param) PutWStrToTable(L, "Param", fsh->Param, -1);
PutLStrToTable(L, "PluginId", &fsh->PluginId, sizeof(GUID));
if (fsh->File) PutWStrToTable(L, "File", fsh->File, -1);
pushFileTime(L, &fsh->Time);
lua_setfield(L, -2, "Time");
PutBoolToTable(L, "Lock", fsh->Lock);
}
else
{
lua_createtable(L, 0, 2);
PutWStrToTable(L, "Name", fse.Value.Items[i].Name, -1);
PutIntToTable(L, "Type", fse.Value.Items[i].Type);
}
lua_rawseti(L, -2, (int)(i-from+1));
}
}
else
lua_pushnil(L);
return 1;
}
static int Settings_free(lua_State *L)
{
FarSettingsUdata* udata = GetSettingsUdata(L, 1);
if (udata->Handle != INVALID_HANDLE_VALUE)
{
PSInfo *Info = GetPluginData(L)->Info;
Info->SettingsControl(udata->Handle, SCTL_FREE, 0, 0);
udata->Handle = INVALID_HANDLE_VALUE;
lua_getfield(L, LUA_REGISTRYINDEX, SettingsHandles);
lua_pushvalue(L, 1);
lua_pushnil(L);
lua_rawset(L, -3);
}
return 0;
}
static int far_FreeSettings(lua_State *L)
{
lua_getfield(L, LUA_REGISTRYINDEX, SettingsHandles);
lua_pushnil(L);
while(lua_next(L, -2))
{
lua_pushcfunction(L, Settings_free);
lua_pushvalue(L, -3);
lua_call(L, 1, 0);
lua_pop(L, 1);
}
lua_pop(L, 1); // mandatory, since this function is called directly from pcall_msg
return 0;
}
static int Settings_tostring(lua_State *L)
{
FarSettingsUdata* udata = GetSettingsUdata(L, 1);
if (udata->Handle != INVALID_HANDLE_VALUE)
lua_pushfstring(L, "%s (%p)", SettingsType, udata->Handle);
else
lua_pushfstring(L, "%s (closed)", SettingsType);
return 1;
}
static int far_ColorDialog(lua_State *L)
{
UINT64 Flags;
struct FarColor Color;
TPluginData *pd = GetPluginData(L);
if (!GetFarColor(L, 1, &Color))
{
Color.Foreground.ForegroundColor = 0x0F | ALPHAMASK;
Color.Background.BackgroundColor = 0x00 | ALPHAMASK;
Color.Flags = FCF_4BITMASK;
}
Flags = OptFlags(L, 2, 0);
if (pd->Info->ColorDialog(pd->PluginId, Flags, &Color))
PushFarColor(L, &Color);
else
lua_pushnil(L);
return 1;
}
static int far_RunDefaultScript(lua_State *L)
{
lua_pushboolean(L, RunDefaultScript(L, 0));
return 1;
}
static int far_FileTimeResolution(lua_State *L)
{
lua_Integer op = luaL_optinteger(L, 1, 0);
TPluginData *pd = GetPluginData(L);
int ret = (pd->Flags & PDF_FULL_TIME_RESOLUTION) ? 2:1;
if (op == 1)
pd->Flags &= ~PDF_FULL_TIME_RESOLUTION;
else if (op == 2)
pd->Flags |= PDF_FULL_TIME_RESOLUTION;
lua_pushinteger(L, ret);
return 1;
}
static int far_DetectCodePage(lua_State *L)
{
int codepage;
struct DetectCodePageInfo Info;
Info.StructSize = sizeof(Info);
Info.FileName = check_utf8_string(L, 1, NULL);
codepage = GetPluginData(L)->FSF->DetectCodePage(&Info);
if (codepage)
lua_pushinteger(L, codepage);
else
lua_pushnil(L);
return 1;
}
static int far_GetPluginId(lua_State *L)
{
lua_pushlstring(L, (char*)GetPluginData(L)->PluginId, sizeof(UUID));
return 1;
}
#define PAIR(prefix,txt) {#txt, prefix ## _ ## txt}
const luaL_Reg timer_methods[] =
{
{"__gc", timer_gc},
{"__tostring", timer_tostring},
{"__index", timer_index},
{"__newindex", timer_newindex},
{NULL, NULL},
};
const luaL_Reg filefilter_methods[] =
{
{"__gc", filefilter_gc},
{"__tostring", filefilter_tostring},
{"FreeFileFilter", filefilter_Free},
{"OpenFiltersMenu", filefilter_OpenMenu},
{"StartingToFilter", filefilter_Starting},
{"IsFileInFilter", filefilter_IsFileInFilter},
{NULL, NULL},
};
const luaL_Reg dialog_methods[] =
{
{"__gc", far_DialogFree},
{"__tostring", dialog_tostring},
{"rawhandle", dialog_rawhandle},
{"send", far_SendDlgMessage},
PAIR( dlg, AddHistory),
PAIR( dlg, Close),
PAIR( dlg, EditUnchangedFlag),
PAIR( dlg, Enable),
PAIR( dlg, EnableRedraw),
PAIR( dlg, GetCheck),
PAIR( dlg, GetComboboxEvent),
PAIR( dlg, GetConstTextPtr),
PAIR( dlg, GetCursorPos),
PAIR( dlg, GetCursorSize),
PAIR( dlg, GetDialogInfo),
PAIR( dlg, GetDialogTitle),
PAIR( dlg, GetDlgData),
PAIR( dlg, GetDlgItem),
PAIR( dlg, GetDlgRect),
PAIR( dlg, GetDropdownOpened),
PAIR( dlg, GetEditPosition),
PAIR( dlg, GetFocus),
PAIR( dlg, GetItemData),
PAIR( dlg, GetItemPosition),
PAIR( dlg, GetSelection),
PAIR( dlg, GetText),
PAIR( dlg, Key),
PAIR( dlg, ListAdd),
PAIR( dlg, ListAddStr),
PAIR( dlg, ListDelete),
PAIR( dlg, ListFindString),
PAIR( dlg, ListGetCurPos),
PAIR( dlg, ListGetData),
PAIR( dlg, ListGetDataSize),
PAIR( dlg, ListGetItem),
PAIR( dlg, ListGetTitles),
PAIR( dlg, ListInfo),
PAIR( dlg, ListInsert),
PAIR( dlg, ListSet),
PAIR( dlg, ListSetCurPos),
PAIR( dlg, ListSetData),
PAIR( dlg, ListSetTitles),
PAIR( dlg, ListSort),
PAIR( dlg, ListUpdate),
PAIR( dlg, MoveDialog),
PAIR( dlg, Redraw),
PAIR( dlg, ResizeDialog),
PAIR( dlg, Set3State),
PAIR( dlg, SetCheck),
PAIR( dlg, SetComboboxEvent),
PAIR( dlg, SetCursorPos),
PAIR( dlg, SetCursorSize),
PAIR( dlg, SetDlgData),
PAIR( dlg, SetDlgItem),
PAIR( dlg, SetDropdownOpened),
PAIR( dlg, SetEditPosition),
PAIR( dlg, SetFocus),
PAIR( dlg, SetHistory),
PAIR( dlg, SetInputNotify),
PAIR( dlg, SetItemData),
PAIR( dlg, SetItemPosition),
PAIR( dlg, SetMaxTextLength),
PAIR( dlg, SetSelection),
PAIR( dlg, SetText),
PAIR( dlg, SetTextPtr),
PAIR( dlg, ShowDialog),
PAIR( dlg, ShowItem),
PAIR( dlg, User),
{NULL, NULL},
};
static const luaL_Reg actl_funcs[] =
{
PAIR( adv, Commit),
PAIR( adv, GetArrayColor),
PAIR( adv, GetColor),
PAIR( adv, GetCursorPos),
PAIR( adv, GetFarHwnd),
PAIR( adv, GetFarManagerVersion),
PAIR( adv, GetFarRect),
PAIR( adv, GetWindowCount),
PAIR( adv, GetWindowInfo),
PAIR( adv, GetWindowType),
PAIR( adv, ProgressNotify),
PAIR( adv, Quit),
PAIR( adv, RedrawAll),
PAIR( adv, SetArrayColor),
PAIR( adv, SetCurrentWindow),
PAIR( adv, SetCursorPos),
PAIR( adv, SetProgressState),
PAIR( adv, SetProgressValue),
PAIR( adv, Synchro),
PAIR( adv, WaitKey),
{NULL, NULL},
};
const luaL_Reg Settings_methods[] =
{
{"__gc", Settings_free},
{"__tostring", Settings_tostring},
{"Delete", Settings_delete},
{"Enum", Settings_enum},
{"Free", Settings_free},
{"Get", Settings_get},
{"Set", Settings_set},
{"CreateSubkey", Settings_createsubkey},
{"OpenSubkey", Settings_opensubkey},
{NULL, NULL},
};
const luaL_Reg editor_funcs[] =
{
PAIR( editor, AddColor),
PAIR( editor, AddSessionBookmark),
PAIR( editor, ClearSessionBookmarks),
PAIR( editor, DelColor),
PAIR( editor, DeleteBlock),
PAIR( editor, DeleteChar),
PAIR( editor, DeleteSessionBookmark),
PAIR( editor, DeleteString),
PAIR( editor, Editor),
PAIR( editor, ExpandTabs),
PAIR( editor, GetBookmarks),
PAIR( editor, GetColor),
PAIR( editor, GetFileName),
PAIR( editor, GetInfo),
PAIR( editor, GetSelection),
PAIR( editor, GetSessionBookmarks),
PAIR( editor, GetString),
PAIR( editor, GetStringW),
PAIR( editor, GetTitle),
PAIR( editor, InsertString),
PAIR( editor, InsertText),
PAIR( editor, InsertTextW),
PAIR( editor, NextSessionBookmark),
PAIR( editor, PrevSessionBookmark),
PAIR( editor, ProcessInput),
PAIR( editor, Quit),
PAIR( editor, ReadInput),
PAIR( editor, RealToTab),
PAIR( editor, Redraw),
PAIR( editor, SaveFile),
PAIR( editor, Select),
PAIR( editor, SetKeyBar),
PAIR( editor, SetParam),
PAIR( editor, SetPosition),
PAIR( editor, SetString),
PAIR( editor, SetStringW),
PAIR( editor, SetTitle),
PAIR( editor, SubscribeChangeEvent),
PAIR( editor, TabToReal),
PAIR( editor, UndoRedo),
{NULL, NULL},
};
const luaL_Reg viewer_funcs[] =
{
PAIR( viewer, GetFileName),
PAIR( viewer, GetInfo),
PAIR( viewer, Quit),
PAIR( viewer, Redraw),
PAIR( viewer, Select),
PAIR( viewer, SetKeyBar),
PAIR( viewer, SetMode),
PAIR( viewer, SetPosition),
PAIR( viewer, Viewer),
{NULL, NULL},
};
const luaL_Reg panel_funcs[] =
{
PAIR( panel, BeginSelection),
PAIR( panel, CheckPanelsExist),
PAIR( panel, ClearSelection),
PAIR( panel, ClosePanel),
PAIR( panel, EndSelection),
PAIR( panel, GetCmdLine),
PAIR( panel, GetCmdLinePos),
PAIR( panel, GetCmdLineSelection),
PAIR( panel, GetColumnTypes),
PAIR( panel, GetColumnWidths),
PAIR( panel, GetCurrentPanelItem),
PAIR( panel, GetPanelDirectory),
PAIR( panel, GetPanelFormat),
PAIR( panel, GetPanelHostFile),
PAIR( panel, GetPanelInfo),
PAIR( panel, GetPanelItem),
PAIR( panel, GetPanelPrefix),
PAIR( panel, GetSelectedPanelItem),
PAIR( panel, GetUserScreen),
PAIR( panel, InsertCmdLine),
PAIR( panel, IsActivePanel),
PAIR( panel, RedrawPanel),
PAIR( panel, SetActivePanel),
PAIR( panel, SetCmdLine),
PAIR( panel, SetCmdLinePos),
PAIR( panel, SetCmdLineSelection),
PAIR( panel, SetDirectoriesFirst),
PAIR( panel, SetPanelDirectory),
PAIR( panel, SetSelection),
PAIR( panel, SetSortMode),
PAIR( panel, SetSortOrder),
PAIR( panel, SetUserScreen),
PAIR( panel, SetViewMode),
PAIR( panel, UpdatePanel),
{NULL, NULL},
};
const luaL_Reg far_funcs[] =
{
PAIR( far, AdvControl),
PAIR( far, CPluginStartupInfo),
PAIR( far, CheckMask),
PAIR( far, CmpName),
PAIR( far, CmpNameList),
PAIR( far, ColorDialog),
PAIR( far, ConvertPath),
PAIR( far, CopyToClipboard),
PAIR( far, CreateFileFilter),
PAIR( far, CreateSettings),
PAIR( far, DetectCodePage),
PAIR( far, DialogFree),
PAIR( far, DialogInit),
PAIR( far, DialogRun),
PAIR( far, FarClock),
PAIR( far, FileTimeResolution),
PAIR( far, FindPlugin),
PAIR( far, ForcedLoadPlugin),
PAIR( far, FormatFileSize),
PAIR( far, FreeScreen),
PAIR( far, FreeSettings),
PAIR( far, GenerateName),
PAIR( far, GetCurrentDirectory),
PAIR( far, GetDirList),
PAIR( far, GetDlgItem),
PAIR( far, GetFileOwner),
PAIR( far, GetLuafarVersion),
PAIR( far, GetMsg),
PAIR( far, GetNumberOfLinks),
PAIR( far, GetPathRoot),
PAIR( far, GetPluginDirList),
PAIR( far, GetPluginId),
PAIR( far, GetPluginInformation),
PAIR( far, GetPlugins),
PAIR( far, GetReparsePointInfo),
PAIR( far, InputBox),
PAIR( far, InputRecordToName),
PAIR( far, IsPluginLoaded),
PAIR( far, LIsAlpha),
PAIR( far, LIsAlphanum),
PAIR( far, LIsLower),
PAIR( far, LIsUpper),
PAIR( far, LLowerBuf),
PAIR( far, LStricmp),
PAIR( far, LStrnicmp),
PAIR( far, LUpperBuf),
PAIR( far, LoadPlugin),
PAIR( far, MacroAdd),
PAIR( far, MacroCheck),
PAIR( far, MacroDelete),
PAIR( far, MacroExecute),
PAIR( far, MacroGetArea),
PAIR( far, MacroGetLastError),
PAIR( far, MacroGetState),
PAIR( far, MacroLoadAll),
PAIR( far, MacroPost),
PAIR( far, MacroSaveAll),
PAIR( far, MakeMenuItems),
PAIR( far, Menu),
PAIR( far, Message),
PAIR( far, MkLink),
PAIR( far, MkTemp),
PAIR( far, NameToInputRecord),
PAIR( far, PasteFromClipboard),
PAIR( far, PluginStartupInfo),
PAIR( far, ProcessName),
PAIR( far, RecursiveSearch),
PAIR( far, RestoreScreen),
PAIR( far, RunDefaultScript),
PAIR( far, SaveScreen),
PAIR( far, SendDlgMessage),
PAIR( far, SetDlgItem),
PAIR( far, Show),
PAIR( far, ShowHelp),
PAIR( far, SubscribeDialogDrawEvents),
PAIR( far, Text),
PAIR( far, Timer),
PAIR( far, TruncPathStr),
PAIR( far, TruncStr),
PAIR( far, UnloadPlugin),
PAIR( far, XLat),
{NULL, NULL}
};
static const char far_Dialog[] =
"function far.Dialog (Id,X1,Y1,X2,Y2,HelpTopic,Items,Flags,DlgProc,Param)\n"
"local hDlg = far.DialogInit(Id,X1,Y1,X2,Y2,HelpTopic,Items,Flags,DlgProc,Param)\n"
"if hDlg == nil then return nil end\n"
"local ret = far.DialogRun(hDlg)\n"
"for i, item in ipairs(Items) do\n"
"local newitem = far.GetDlgItem(hDlg, i)\n"
"if type(item[6]) == 'table' then\n"
"local pos = far.SendDlgMessage(hDlg, 'DM_LISTGETCURPOS', i, 0)\n"
"item[6].SelectIndex = pos.SelectPos\n"
"else\n"
"item[6] = newitem[6]\n"
"end\n"
"item[10] = newitem[10]\n"
"end\n"
"far.DialogFree(hDlg)\n"
"return ret\n"
"end";
static const char utf8_reformat[] =
"function utf8.reformat (patt, ...)\n"
"local args = { ... }\n"
"local function Subst (i, m, f)\n"
"i = tonumber(i)\n"
"f = f:match('[^s]')\n"
"return args[i] and ('%' .. m .. (f or 's')):format(f and args[i] or tostring(args[i])) or ''\n"
"end\n"
"patt = patt:gsub('%f[%%{]{(%d+):?(%-?%d*%.?%d*)([A-Za-z]?)}', Subst):gsub('%%{', '{')\n"
"return patt:format(...)\n"
"end";
static int luaopen_far(lua_State *L)
{
HANDLE TimerQueue = CreateTimerQueue();
if (TimerQueue)
{
lua_pushlightuserdata(L, TimerQueue);
lua_setfield(L, LUA_REGISTRYINDEX, FarTimerQueueKey);
}
lua_newtable(L);
lua_setfield(L, LUA_REGISTRYINDEX, FAR_DN_STORAGE);
NewVirtualKeyTable(L, FALSE);
lua_setfield(L, LUA_REGISTRYINDEX, FAR_VIRTUALKEYS);
luaL_register(L, "far", far_funcs);
luaopen_far_host(L);
lua_setfield(L, -2, "Host");
if (GetPluginData(L)->Info->Private)
{
lua_pushcfunction(L, far_MacroCallFar);
lua_setfield(L, -2, "MacroCallFar");
lua_pushcfunction(L, far_MacroCallToLua);
lua_setfield(L, -2, "MacroCallToLua");
}
push_flags_table(L);
lua_pushvalue(L, -1);
lua_setfield(L, -3, "Flags");
lua_setfield(L, LUA_REGISTRYINDEX, FAR_FLAGSTABLE);
SetFarColors(L);
luaL_register(L, "editor", editor_funcs);
luaL_register(L, "viewer", viewer_funcs);
luaL_register(L, "panel", panel_funcs);
luaL_register(L, "actl", actl_funcs);
luaL_newmetatable(L, FarFileFilterType);
lua_pushvalue(L,-1);
lua_setfield(L, -2, "__index");
luaL_register(L, NULL, filefilter_methods);
luaL_newmetatable(L, FarTimerType);
luaL_register(L, NULL, timer_methods);
luaL_newmetatable(L, FarDialogType);
lua_pushvalue(L,-1);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, DialogHandleEqual);
lua_setfield(L, -2, "__eq");
luaL_register(L, NULL, dialog_methods);
luaL_newmetatable(L, SettingsType);
lua_pushvalue(L,-1);
lua_setfield(L, -2, "__index");
luaL_register(L, NULL, Settings_methods);
lua_newtable(L);
lua_newtable(L);
lua_pushliteral(L, "k");
lua_setfield(L, -2, "__mode");
lua_setmetatable(L, -2);
lua_setfield(L, LUA_REGISTRYINDEX, SettingsHandles);
(void) luaL_dostring(L, far_Dialog);
luaL_newmetatable(L, PluginHandleType);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, PluginHandle_rawhandle);
lua_setfield(L, -2, "rawhandle");
luaL_newmetatable(L, AddMacroDataType);
lua_pushcfunction(L, AddMacroData_gc);
lua_setfield(L, -2, "__gc");
luaL_newmetatable(L, SavedScreenType);
lua_pushcfunction(L, far_FreeScreen);
lua_setfield(L, -2, "__gc");
lua_pushcfunction(L, SavedScreen_tostring);
lua_setfield(L, -2, "__tostring");
return 0;
}
void LF_RunLuafarInit(lua_State* L)
{
const wchar_t *filename = L"\\luafar_init.lua";
wchar_t buf[2048];
int size;
size = GetEnvironmentVariableW(L"FARPROFILE", buf, ARRSIZE(buf));
if (size && (size + wcslen(filename) < ARRSIZE(buf)))
{
DWORD attr = GetFileAttributesW(wcscat(buf, filename));
if (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
{
int status = LF_LoadFile(L, buf) || lua_pcall(L,0,0,0);
if (status)
{
LF_Error(L, check_utf8_string(L, -1, NULL));
lua_pop(L, 1);
}
}
}
}
static const luaL_Reg lualibs[] =
{
#if LUA_VERSION_NUM == 501
{"", luaopen_base},
{LUA_LOADLIBNAME, luaopen_upackage}, // changed
#else
{"_G", luaopen_base},
{LUA_LOADLIBNAME, luaopen_upackage}, // changed
{LUA_BITLIBNAME, luaopen_bit32},
{LUA_COLIBNAME, luaopen_coroutine},
#endif
{LUA_TABLIBNAME, luaopen_table},
{LUA_IOLIBNAME, luaopen_uio}, // changed
{LUA_OSLIBNAME, luaopen_os},
{LUA_STRLIBNAME, luaopen_string},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_DBLIBNAME, luaopen_debug},
//-------------------------------------------------
{"bit64", luaopen_bit64},
{"unicode", luaopen_unicode},
{"utf8", luaopen_utf8},
{"win", luaopen_win},
{"lpeg", luaopen_lpeg},
{NULL, NULL}
};
void LF_InitLuaState1(lua_State *L, lua_CFunction aOpenLibs)
{
const luaL_Reg *lib;
FP_PROTECT();
// open Lua libraries
for(lib=lualibs; lib->func; lib++)
{
#if LUA_VERSION_NUM == 501
lua_pushcfunction(L, lib->func);
lua_pushstring(L, lib->name);
lua_call(L, 1, 0);
#elif LUA_VERSION_NUM == 502
luaL_requiref(L, lib->name, lib->func, 1);
lua_pop(L, 1); /* remove lib */
#endif
}
lua_getglobal(L, "utf8"); //+1
lua_getglobal(L, "string"); //+2
// utf8.dump = string.dump
lua_getfield(L, -1, "dump"); //+3
lua_setfield(L, -3, "dump"); //+2
// utf8.rep = string.rep
lua_getfield(L, -1, "rep"); //+3
lua_setfield(L, -3, "rep"); //+2
// getmetatable("").__index = utf8
lua_pushliteral(L, ""); //+3
lua_getmetatable(L, -1); //+4
lua_pushvalue(L, -4); //+5
lua_setfield(L, -2, "__index"); //+4
lua_pop(L, 4); //+0
// add utf8.reformat
(void) luaL_dostring(L, utf8_reformat);
// unicode.utf8 = utf8 (for backward compatibility;)
lua_newtable(L);
lua_getglobal(L, "utf8");
lua_setfield(L, -2, "utf8");
lua_setglobal(L, "unicode");
// utf8.cfind = utf8.find (for backward compatibility;)
lua_getglobal(L, "utf8");
lua_getfield(L, -1, "find");
lua_setfield(L, -2, "cfind");
lua_pop(L, 1);
#if LUA_VERSION_NUM == 501
if (IsLuaJIT())
{
if (luaopen_bit)
{
lua_pushcfunction(L, luaopen_bit);
lua_pushstring(L, "bit");
lua_call(L, 1, 0);
}
if (luaopen_jit)
{
lua_pushcfunction(L, luaopen_jit);
lua_pushstring(L, "jit");
lua_call(L, 1, 0);
}
if (luaopen_ffi)
{
luaL_findtable(L, LUA_REGISTRYINDEX, "_PRELOAD", 1);
lua_pushcfunction(L, luaopen_ffi);
lua_setfield(L, -2, "ffi");
lua_pop(L, 1);
}
}
#endif
if (aOpenLibs) {
lua_pushcfunction(L, aOpenLibs);
lua_call(L, 0, 0);
}
lua_pushcfunction(L, luaB_dofileW);
lua_setglobal(L, "dofile");
lua_pushcfunction(L, luaB_loadfileW);
lua_setglobal(L, "loadfile");
}
static const luaL_Reg lualibs_extra[] =
{
{"bit64", luaopen_bit64},
{"unicode", luaopen_unicode},
{"utf8", luaopen_utf8},
{"win", luaopen_win},
{"lpeg", luaopen_lpeg},
{NULL, NULL}
};
static void LoadExtraLibraries(lua_State *L)
{
const luaL_Reg *lib;
FP_PROTECT();
// open Lua libraries
for(lib=lualibs_extra; lib->func; lib++)
{
lua_pushcfunction(L, lib->func);
lua_pushstring(L, lib->name);
lua_call(L, 1, 0);
}
// add "luafar" namespace with a few functions
lua_newtable(L);
lua_pushcfunction(L, far_GetLuafarVersion);
lua_setfield(L, -2, "GetLuafarVersion");
lua_pushcfunction(L, far_FileTimeResolution);
lua_setfield(L, -2, "FileTimeResolution");
lua_setglobal(L, "luafar");
// add utf8.reformat
(void) luaL_dostring(L, utf8_reformat);
// getmetatable("").__index = utf8
lua_pushliteral(L, "");
lua_getmetatable(L, -1);
lua_getglobal(L, "utf8");
lua_setfield(L, -2, "__index");
lua_pop(L, 2);
}
static void* CustomAllocator(void *ud, void *ptr, size_t osize, size_t nsize)
{
return ((TPluginData*)ud)->origAlloc(((TPluginData*)ud)->origUserdata, ptr, osize, nsize);
}
void LF_InitLuaState2(lua_State *L, TPluginData *aInfo)
{
FP_PROTECT();
aInfo->MainLuaState = L;
aInfo->Flags = 0;
aInfo->origAlloc = lua_getallocf(L, &aInfo->origUserdata);
lua_setallocf(L, CustomAllocator, aInfo);
// open "far" library
lua_pushcfunction(L, luaopen_far);
lua_call(L, 0, 0);
// open "regex" library
lua_pushcfunction(L, luaopen_regex);
lua_pushliteral(L, "regex");
lua_call(L, 1, 0);
// open "usercontrol" library
lua_pushcfunction(L, luaopen_usercontrol);
lua_call(L, 0, 0);
}
// This exported function is needed for old builds of the plugins.
intptr_t LF_MacroCallback(lua_State* L, void* Id, FARADDKEYMACROFLAGS Flags) { return 0; }
int LF_DoFile(lua_State *L, const wchar_t *fname, int argc, wchar_t* argv[])
{
int status;
if ((status = LF_LoadFile(L, fname)) == 0)
{
int i;
for(i=0; i < argc; i++)
push_utf8_string(L, argv[i], -1);
status = lua_pcall(L, argc, 0, 0);
}
if (status)
{
fprintf(stderr, "%s\n", lua_tostring(L, -1));
lua_pop(L, 1);
}
return status;
}
const LuafarAPI api_functions = {
0,
check_utf8_string,
opt_utf8_string,
push_utf8_string,
check_utf16_string,
opt_utf16_string,
push_utf16_string,
utf8_to_utf16,
GetBoolFromTable,
GetOptBoolFromTable,
GetOptIntFromArray,
GetOptIntFromTable,
GetOptNumFromTable,
PutBoolToTable,
PutIntToArray,
PutIntToTable,
PutLStrToTable,
PutNumToTable,
PutStrToArray,
PutStrToTable,
PutWStrToArray,
PutWStrToTable,
GetExportFunction,
pcall_msg,
bit64_pushuserdata,
bit64_push,
bit64_getvalue,
};
void LF_GetLuafarAPI (LuafarAPI* target)
{
size_t size = target->StructSize;
memset(target, 0, size); // fill target with nulls (it helps to detect missing functions)
if (size > sizeof(LuafarAPI))
size = sizeof(LuafarAPI);
memcpy(target, &api_functions, size);
target->StructSize = size;
}
// This function makes possible use of luafar3.dll as a library without Far Manager.
// It is called by means of: require("luafar3")
__declspec(dllexport) int luaopen_luafar3 (lua_State *L)
{
InsideFarManager = 0;
lua_getglobal(L, "far");
if (lua_istable(L, -1))
{
lua_getfield(L, -1, "ConvertPath");
InsideFarManager = lua_isfunction(L, -1);
lua_pop(L, 1);
}
lua_pop(L, 1);
if (! InsideFarManager)
LoadExtraLibraries(L);
return 0;
}
| 411 | 0.942566 | 1 | 0.942566 | game-dev | MEDIA | 0.549523 | game-dev | 0.819415 | 1 | 0.819415 |
Ivorforce/RecurrentComplex | 1,270 | src/main/java/ivorius/reccomplex/commands/preview/CommandConfirm.java | /*
* Copyright (c) 2014, Lukas Tenbrink.
* * http://ivorius.net
*/
package ivorius.reccomplex.commands.preview;
import ivorius.reccomplex.RCConfig;
import ivorius.reccomplex.RecurrentComplex;
import ivorius.reccomplex.capability.RCEntityInfo;
import ivorius.reccomplex.commands.RCCommands;
import ivorius.mcopts.commands.SimpleCommand;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer;
/**
* Created by lukas on 03.08.14.
*/
public class CommandConfirm extends SimpleCommand
{
public CommandConfirm()
{
super(RCConfig.commandPrefix + "confirm");
permitFor(2);
}
@Override
public void execute(MinecraftServer server, ICommandSender commandSender, String[] args) throws CommandException
{
EntityPlayer player = getCommandSenderAsPlayer(commandSender);
RCEntityInfo RCEntityInfo = RCCommands.getStructureEntityInfo(player, null);
if (!RCEntityInfo.performOperation((WorldServer) commandSender.getEntityWorld(), player))
throw RecurrentComplex.translations.commandException("commands.rc.noOperation");
}
}
| 411 | 0.741884 | 1 | 0.741884 | game-dev | MEDIA | 0.727838 | game-dev | 0.645407 | 1 | 0.645407 |
defold/defold | 32,356 | external/bullet3d/package/bullet-2.77/src/BulletCollision/BroadphaseCollision/btAxisSweep3.h | //Bullet Continuous Collision Detection and Physics Library
//Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
//
// btAxisSweep3.h
//
// Copyright (c) 2006 Simon Hobbs
//
// This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
#ifndef AXIS_SWEEP_3_H
#define AXIS_SWEEP_3_H
#include "LinearMath/btVector3.h"
#include "btOverlappingPairCache.h"
#include "btBroadphaseInterface.h"
#include "btBroadphaseProxy.h"
#include "btOverlappingPairCallback.h"
#include "btDbvtBroadphase.h"
//#define DEBUG_BROADPHASE 1
#define USE_OVERLAP_TEST_ON_REMOVES 1
/// The internal templace class btAxisSweep3Internal implements the sweep and prune broadphase.
/// It uses quantized integers to represent the begin and end points for each of the 3 axis.
/// Dont use this class directly, use btAxisSweep3 or bt32BitAxisSweep3 instead.
template <typename BP_FP_INT_TYPE>
class btAxisSweep3Internal : public btBroadphaseInterface
{
protected:
BP_FP_INT_TYPE m_bpHandleMask;
BP_FP_INT_TYPE m_handleSentinel;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
class Edge
{
public:
BP_FP_INT_TYPE m_pos; // low bit is min/max
BP_FP_INT_TYPE m_handle;
BP_FP_INT_TYPE IsMax() const {return static_cast<BP_FP_INT_TYPE>(m_pos & 1);}
};
public:
class Handle : public btBroadphaseProxy
{
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
// indexes into the edge arrays
BP_FP_INT_TYPE m_minEdges[3], m_maxEdges[3]; // 6 * 2 = 12
// BP_FP_INT_TYPE m_uniqueId;
btBroadphaseProxy* m_dbvtProxy;//for faster raycast
//void* m_pOwner; this is now in btBroadphaseProxy.m_clientObject
SIMD_FORCE_INLINE void SetNextFree(BP_FP_INT_TYPE next) {m_minEdges[0] = next;}
SIMD_FORCE_INLINE BP_FP_INT_TYPE GetNextFree() const {return m_minEdges[0];}
}; // 24 bytes + 24 for Edge structures = 44 bytes total per entry
protected:
btVector3 m_worldAabbMin; // overall system bounds
btVector3 m_worldAabbMax; // overall system bounds
btVector3 m_quantize; // scaling factor for quantization
BP_FP_INT_TYPE m_numHandles; // number of active handles
BP_FP_INT_TYPE m_maxHandles; // max number of handles
Handle* m_pHandles; // handles pool
BP_FP_INT_TYPE m_firstFreeHandle; // free handles list
Edge* m_pEdges[3]; // edge arrays for the 3 axes (each array has m_maxHandles * 2 + 2 sentinel entries)
void* m_pEdgesRawPtr[3];
btOverlappingPairCache* m_pairCache;
///btOverlappingPairCallback is an additional optional user callback for adding/removing overlapping pairs, similar interface to btOverlappingPairCache.
btOverlappingPairCallback* m_userPairCallback;
bool m_ownsPairCache;
int m_invalidPair;
///additional dynamic aabb structure, used to accelerate ray cast queries.
///can be disabled using a optional argument in the constructor
btDbvtBroadphase* m_raycastAccelerator;
btOverlappingPairCache* m_nullPairCache;
// allocation/deallocation
BP_FP_INT_TYPE allocHandle();
void freeHandle(BP_FP_INT_TYPE handle);
bool testOverlap2D(const Handle* pHandleA, const Handle* pHandleB,int axis0,int axis1);
#ifdef DEBUG_BROADPHASE
void debugPrintAxis(int axis,bool checkCardinality=true);
#endif //DEBUG_BROADPHASE
//Overlap* AddOverlap(BP_FP_INT_TYPE handleA, BP_FP_INT_TYPE handleB);
//void RemoveOverlap(BP_FP_INT_TYPE handleA, BP_FP_INT_TYPE handleB);
void sortMinDown(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps );
void sortMinUp(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps );
void sortMaxDown(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps );
void sortMaxUp(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps );
public:
btAxisSweep3Internal(const btVector3& worldAabbMin,const btVector3& worldAabbMax, BP_FP_INT_TYPE handleMask, BP_FP_INT_TYPE handleSentinel, BP_FP_INT_TYPE maxHandles = 16384, btOverlappingPairCache* pairCache=0,bool disableRaycastAccelerator = false);
virtual ~btAxisSweep3Internal();
BP_FP_INT_TYPE getNumHandles() const
{
return m_numHandles;
}
virtual void calculateOverlappingPairs(btDispatcher* dispatcher);
BP_FP_INT_TYPE addHandle(const btVector3& aabbMin,const btVector3& aabbMax, void* pOwner,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy);
void removeHandle(BP_FP_INT_TYPE handle,btDispatcher* dispatcher);
void updateHandle(BP_FP_INT_TYPE handle, const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher);
SIMD_FORCE_INLINE Handle* getHandle(BP_FP_INT_TYPE index) const {return m_pHandles + index;}
virtual void resetPool(btDispatcher* dispatcher);
void processAllOverlappingPairs(btOverlapCallback* callback);
//Broadphase Interface
virtual btBroadphaseProxy* createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr ,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy);
virtual void destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher);
virtual void getAabb(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const;
virtual void rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin=btVector3(0,0,0), const btVector3& aabbMax = btVector3(0,0,0));
virtual void aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback);
void quantize(BP_FP_INT_TYPE* out, const btVector3& point, int isMax) const;
///unQuantize should be conservative: aabbMin/aabbMax should be larger then 'getAabb' result
void unQuantize(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const;
bool testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1);
btOverlappingPairCache* getOverlappingPairCache()
{
return m_pairCache;
}
const btOverlappingPairCache* getOverlappingPairCache() const
{
return m_pairCache;
}
void setOverlappingPairUserCallback(btOverlappingPairCallback* pairCallback)
{
m_userPairCallback = pairCallback;
}
const btOverlappingPairCallback* getOverlappingPairUserCallback() const
{
return m_userPairCallback;
}
///getAabb returns the axis aligned bounding box in the 'global' coordinate frame
///will add some transform later
virtual void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const
{
aabbMin = m_worldAabbMin;
aabbMax = m_worldAabbMax;
}
virtual void printStats()
{
/* printf("btAxisSweep3.h\n");
printf("numHandles = %d, maxHandles = %d\n",m_numHandles,m_maxHandles);
printf("aabbMin=%f,%f,%f,aabbMax=%f,%f,%f\n",m_worldAabbMin.getX(),m_worldAabbMin.getY(),m_worldAabbMin.getZ(),
m_worldAabbMax.getX(),m_worldAabbMax.getY(),m_worldAabbMax.getZ());
*/
}
};
////////////////////////////////////////////////////////////////////
#ifdef DEBUG_BROADPHASE
#include <stdio.h>
template <typename BP_FP_INT_TYPE>
void btAxisSweep3<BP_FP_INT_TYPE>::debugPrintAxis(int axis, bool checkCardinality)
{
int numEdges = m_pHandles[0].m_maxEdges[axis];
printf("SAP Axis %d, numEdges=%d\n",axis,numEdges);
int i;
for (i=0;i<numEdges+1;i++)
{
Edge* pEdge = m_pEdges[axis] + i;
Handle* pHandlePrev = getHandle(pEdge->m_handle);
int handleIndex = pEdge->IsMax()? pHandlePrev->m_maxEdges[axis] : pHandlePrev->m_minEdges[axis];
char beginOrEnd;
beginOrEnd=pEdge->IsMax()?'E':'B';
printf(" [%c,h=%d,p=%x,i=%d]\n",beginOrEnd,pEdge->m_handle,pEdge->m_pos,handleIndex);
}
if (checkCardinality)
btAssert(numEdges == m_numHandles*2+1);
}
#endif //DEBUG_BROADPHASE
template <typename BP_FP_INT_TYPE>
btBroadphaseProxy* btAxisSweep3Internal<BP_FP_INT_TYPE>::createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy)
{
(void)shapeType;
BP_FP_INT_TYPE handleId = addHandle(aabbMin,aabbMax, userPtr,collisionFilterGroup,collisionFilterMask,dispatcher,multiSapProxy);
Handle* handle = getHandle(handleId);
if (m_raycastAccelerator)
{
btBroadphaseProxy* rayProxy = m_raycastAccelerator->createProxy(aabbMin,aabbMax,shapeType,userPtr,collisionFilterGroup,collisionFilterMask,dispatcher,0);
handle->m_dbvtProxy = rayProxy;
}
return handle;
}
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher)
{
Handle* handle = static_cast<Handle*>(proxy);
if (m_raycastAccelerator)
m_raycastAccelerator->destroyProxy(handle->m_dbvtProxy,dispatcher);
removeHandle(static_cast<BP_FP_INT_TYPE>(handle->m_uniqueId), dispatcher);
}
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher)
{
Handle* handle = static_cast<Handle*>(proxy);
handle->m_aabbMin = aabbMin;
handle->m_aabbMax = aabbMax;
updateHandle(static_cast<BP_FP_INT_TYPE>(handle->m_uniqueId), aabbMin, aabbMax,dispatcher);
if (m_raycastAccelerator)
m_raycastAccelerator->setAabb(handle->m_dbvtProxy,aabbMin,aabbMax,dispatcher);
}
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback,const btVector3& aabbMin,const btVector3& aabbMax)
{
if (m_raycastAccelerator)
{
m_raycastAccelerator->rayTest(rayFrom,rayTo,rayCallback,aabbMin,aabbMax);
} else
{
//choose axis?
BP_FP_INT_TYPE axis = 0;
//for each proxy
for (BP_FP_INT_TYPE i=1;i<m_numHandles*2+1;i++)
{
if (m_pEdges[axis][i].IsMax())
{
rayCallback.process(getHandle(m_pEdges[axis][i].m_handle));
}
}
}
}
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback)
{
if (m_raycastAccelerator)
{
m_raycastAccelerator->aabbTest(aabbMin,aabbMax,callback);
} else
{
//choose axis?
BP_FP_INT_TYPE axis = 0;
//for each proxy
for (BP_FP_INT_TYPE i=1;i<m_numHandles*2+1;i++)
{
if (m_pEdges[axis][i].IsMax())
{
Handle* handle = getHandle(m_pEdges[axis][i].m_handle);
if (TestAabbAgainstAabb2(aabbMin,aabbMax,handle->m_aabbMin,handle->m_aabbMax))
{
callback.process(handle);
}
}
}
}
}
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::getAabb(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const
{
Handle* pHandle = static_cast<Handle*>(proxy);
aabbMin = pHandle->m_aabbMin;
aabbMax = pHandle->m_aabbMax;
}
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::unQuantize(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const
{
Handle* pHandle = static_cast<Handle*>(proxy);
unsigned short vecInMin[3];
unsigned short vecInMax[3];
vecInMin[0] = m_pEdges[0][pHandle->m_minEdges[0]].m_pos ;
vecInMax[0] = m_pEdges[0][pHandle->m_maxEdges[0]].m_pos +1 ;
vecInMin[1] = m_pEdges[1][pHandle->m_minEdges[1]].m_pos ;
vecInMax[1] = m_pEdges[1][pHandle->m_maxEdges[1]].m_pos +1 ;
vecInMin[2] = m_pEdges[2][pHandle->m_minEdges[2]].m_pos ;
vecInMax[2] = m_pEdges[2][pHandle->m_maxEdges[2]].m_pos +1 ;
aabbMin.setValue((btScalar)(vecInMin[0]) / (m_quantize.getX()),(btScalar)(vecInMin[1]) / (m_quantize.getY()),(btScalar)(vecInMin[2]) / (m_quantize.getZ()));
aabbMin += m_worldAabbMin;
aabbMax.setValue((btScalar)(vecInMax[0]) / (m_quantize.getX()),(btScalar)(vecInMax[1]) / (m_quantize.getY()),(btScalar)(vecInMax[2]) / (m_quantize.getZ()));
aabbMax += m_worldAabbMin;
}
template <typename BP_FP_INT_TYPE>
btAxisSweep3Internal<BP_FP_INT_TYPE>::btAxisSweep3Internal(const btVector3& worldAabbMin,const btVector3& worldAabbMax, BP_FP_INT_TYPE handleMask, BP_FP_INT_TYPE handleSentinel,BP_FP_INT_TYPE userMaxHandles, btOverlappingPairCache* pairCache , bool disableRaycastAccelerator)
:m_bpHandleMask(handleMask),
m_handleSentinel(handleSentinel),
m_pairCache(pairCache),
m_userPairCallback(0),
m_ownsPairCache(false),
m_invalidPair(0),
m_raycastAccelerator(0)
{
BP_FP_INT_TYPE maxHandles = static_cast<BP_FP_INT_TYPE>(userMaxHandles+1);//need to add one sentinel handle
if (!m_pairCache)
{
void* ptr = btAlignedAlloc(sizeof(btHashedOverlappingPairCache),16);
m_pairCache = new(ptr) btHashedOverlappingPairCache();
m_ownsPairCache = true;
}
if (!disableRaycastAccelerator)
{
m_nullPairCache = new (btAlignedAlloc(sizeof(btNullPairCache),16)) btNullPairCache();
m_raycastAccelerator = new (btAlignedAlloc(sizeof(btDbvtBroadphase),16)) btDbvtBroadphase(m_nullPairCache);//m_pairCache);
m_raycastAccelerator->m_deferedcollide = true;//don't add/remove pairs
}
//btAssert(bounds.HasVolume());
// init bounds
m_worldAabbMin = worldAabbMin;
m_worldAabbMax = worldAabbMax;
btVector3 aabbSize = m_worldAabbMax - m_worldAabbMin;
BP_FP_INT_TYPE maxInt = m_handleSentinel;
m_quantize = btVector3(btScalar(maxInt),btScalar(maxInt),btScalar(maxInt)) / aabbSize;
// allocate handles buffer, using btAlignedAlloc, and put all handles on free list
m_pHandles = new Handle[maxHandles];
m_maxHandles = maxHandles;
m_numHandles = 0;
// handle 0 is reserved as the null index, and is also used as the sentinel
m_firstFreeHandle = 1;
{
for (BP_FP_INT_TYPE i = m_firstFreeHandle; i < maxHandles; i++)
m_pHandles[i].SetNextFree(static_cast<BP_FP_INT_TYPE>(i + 1));
m_pHandles[maxHandles - 1].SetNextFree(0);
}
{
// allocate edge buffers
for (int i = 0; i < 3; i++)
{
m_pEdgesRawPtr[i] = btAlignedAlloc(sizeof(Edge)*maxHandles*2,16);
m_pEdges[i] = new(m_pEdgesRawPtr[i]) Edge[maxHandles * 2];
}
}
//removed overlap management
// make boundary sentinels
m_pHandles[0].m_clientObject = 0;
for (int axis = 0; axis < 3; axis++)
{
m_pHandles[0].m_minEdges[axis] = 0;
m_pHandles[0].m_maxEdges[axis] = 1;
m_pEdges[axis][0].m_pos = 0;
m_pEdges[axis][0].m_handle = 0;
m_pEdges[axis][1].m_pos = m_handleSentinel;
m_pEdges[axis][1].m_handle = 0;
#ifdef DEBUG_BROADPHASE
debugPrintAxis(axis);
#endif //DEBUG_BROADPHASE
}
}
template <typename BP_FP_INT_TYPE>
btAxisSweep3Internal<BP_FP_INT_TYPE>::~btAxisSweep3Internal()
{
if (m_raycastAccelerator)
{
m_nullPairCache->~btOverlappingPairCache();
btAlignedFree(m_nullPairCache);
m_raycastAccelerator->~btDbvtBroadphase();
btAlignedFree (m_raycastAccelerator);
}
for (int i = 2; i >= 0; i--)
{
btAlignedFree(m_pEdgesRawPtr[i]);
}
delete [] m_pHandles;
if (m_ownsPairCache)
{
m_pairCache->~btOverlappingPairCache();
btAlignedFree(m_pairCache);
}
}
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::quantize(BP_FP_INT_TYPE* out, const btVector3& point, int isMax) const
{
#ifdef OLD_CLAMPING_METHOD
///problem with this clamping method is that the floating point during quantization might still go outside the range [(0|isMax) .. (m_handleSentinel&m_bpHandleMask]|isMax]
///see http://code.google.com/p/bullet/issues/detail?id=87
btVector3 clampedPoint(point);
clampedPoint.setMax(m_worldAabbMin);
clampedPoint.setMin(m_worldAabbMax);
btVector3 v = (clampedPoint - m_worldAabbMin) * m_quantize;
out[0] = (BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v.getX() & m_bpHandleMask) | isMax);
out[1] = (BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v.getY() & m_bpHandleMask) | isMax);
out[2] = (BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v.getZ() & m_bpHandleMask) | isMax);
#else
btVector3 v = (point - m_worldAabbMin) * m_quantize;
out[0]=(v[0]<=0)?(BP_FP_INT_TYPE)isMax:(v[0]>=m_handleSentinel)?(BP_FP_INT_TYPE)((m_handleSentinel&m_bpHandleMask)|isMax):(BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v[0]&m_bpHandleMask)|isMax);
out[1]=(v[1]<=0)?(BP_FP_INT_TYPE)isMax:(v[1]>=m_handleSentinel)?(BP_FP_INT_TYPE)((m_handleSentinel&m_bpHandleMask)|isMax):(BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v[1]&m_bpHandleMask)|isMax);
out[2]=(v[2]<=0)?(BP_FP_INT_TYPE)isMax:(v[2]>=m_handleSentinel)?(BP_FP_INT_TYPE)((m_handleSentinel&m_bpHandleMask)|isMax):(BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v[2]&m_bpHandleMask)|isMax);
#endif //OLD_CLAMPING_METHOD
}
template <typename BP_FP_INT_TYPE>
BP_FP_INT_TYPE btAxisSweep3Internal<BP_FP_INT_TYPE>::allocHandle()
{
btAssert(m_firstFreeHandle);
BP_FP_INT_TYPE handle = m_firstFreeHandle;
m_firstFreeHandle = getHandle(handle)->GetNextFree();
m_numHandles++;
return handle;
}
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::freeHandle(BP_FP_INT_TYPE handle)
{
btAssert(handle > 0 && handle < m_maxHandles);
getHandle(handle)->SetNextFree(m_firstFreeHandle);
m_firstFreeHandle = handle;
m_numHandles--;
}
template <typename BP_FP_INT_TYPE>
BP_FP_INT_TYPE btAxisSweep3Internal<BP_FP_INT_TYPE>::addHandle(const btVector3& aabbMin,const btVector3& aabbMax, void* pOwner,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy)
{
// quantize the bounds
BP_FP_INT_TYPE min[3], max[3];
quantize(min, aabbMin, 0);
quantize(max, aabbMax, 1);
// allocate a handle
BP_FP_INT_TYPE handle = allocHandle();
Handle* pHandle = getHandle(handle);
pHandle->m_uniqueId = static_cast<int>(handle);
//pHandle->m_pOverlaps = 0;
pHandle->m_clientObject = pOwner;
pHandle->m_collisionFilterGroup = collisionFilterGroup;
pHandle->m_collisionFilterMask = collisionFilterMask;
pHandle->m_multiSapParentProxy = multiSapProxy;
// compute current limit of edge arrays
BP_FP_INT_TYPE limit = static_cast<BP_FP_INT_TYPE>(m_numHandles * 2);
// insert new edges just inside the max boundary edge
for (BP_FP_INT_TYPE axis = 0; axis < 3; axis++)
{
m_pHandles[0].m_maxEdges[axis] += 2;
m_pEdges[axis][limit + 1] = m_pEdges[axis][limit - 1];
m_pEdges[axis][limit - 1].m_pos = min[axis];
m_pEdges[axis][limit - 1].m_handle = handle;
m_pEdges[axis][limit].m_pos = max[axis];
m_pEdges[axis][limit].m_handle = handle;
pHandle->m_minEdges[axis] = static_cast<BP_FP_INT_TYPE>(limit - 1);
pHandle->m_maxEdges[axis] = limit;
}
// now sort the new edges to their correct position
sortMinDown(0, pHandle->m_minEdges[0], dispatcher,false);
sortMaxDown(0, pHandle->m_maxEdges[0], dispatcher,false);
sortMinDown(1, pHandle->m_minEdges[1], dispatcher,false);
sortMaxDown(1, pHandle->m_maxEdges[1], dispatcher,false);
sortMinDown(2, pHandle->m_minEdges[2], dispatcher,true);
sortMaxDown(2, pHandle->m_maxEdges[2], dispatcher,true);
return handle;
}
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::removeHandle(BP_FP_INT_TYPE handle,btDispatcher* dispatcher)
{
Handle* pHandle = getHandle(handle);
//explicitly remove the pairs containing the proxy
//we could do it also in the sortMinUp (passing true)
///@todo: compare performance
if (!m_pairCache->hasDeferredRemoval())
{
m_pairCache->removeOverlappingPairsContainingProxy(pHandle,dispatcher);
}
// compute current limit of edge arrays
int limit = static_cast<int>(m_numHandles * 2);
int axis;
for (axis = 0;axis<3;axis++)
{
m_pHandles[0].m_maxEdges[axis] -= 2;
}
// remove the edges by sorting them up to the end of the list
for ( axis = 0; axis < 3; axis++)
{
Edge* pEdges = m_pEdges[axis];
BP_FP_INT_TYPE max = pHandle->m_maxEdges[axis];
pEdges[max].m_pos = m_handleSentinel;
sortMaxUp(axis,max,dispatcher,false);
BP_FP_INT_TYPE i = pHandle->m_minEdges[axis];
pEdges[i].m_pos = m_handleSentinel;
sortMinUp(axis,i,dispatcher,false);
pEdges[limit-1].m_handle = 0;
pEdges[limit-1].m_pos = m_handleSentinel;
#ifdef DEBUG_BROADPHASE
debugPrintAxis(axis,false);
#endif //DEBUG_BROADPHASE
}
// free the handle
freeHandle(handle);
}
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::resetPool(btDispatcher* dispatcher)
{
if (m_numHandles == 0)
{
m_firstFreeHandle = 1;
{
for (BP_FP_INT_TYPE i = m_firstFreeHandle; i < m_maxHandles; i++)
m_pHandles[i].SetNextFree(static_cast<BP_FP_INT_TYPE>(i + 1));
m_pHandles[m_maxHandles - 1].SetNextFree(0);
}
}
}
extern int gOverlappingPairs;
//#include <stdio.h>
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::calculateOverlappingPairs(btDispatcher* dispatcher)
{
if (m_pairCache->hasDeferredRemoval())
{
btBroadphasePairArray& overlappingPairArray = m_pairCache->getOverlappingPairArray();
//perform a sort, to find duplicates and to sort 'invalid' pairs to the end
overlappingPairArray.quickSort(btBroadphasePairSortPredicate());
overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair);
m_invalidPair = 0;
int i;
btBroadphasePair previousPair;
previousPair.m_pProxy0 = 0;
previousPair.m_pProxy1 = 0;
previousPair.m_algorithm = 0;
for (i=0;i<overlappingPairArray.size();i++)
{
btBroadphasePair& pair = overlappingPairArray[i];
bool isDuplicate = (pair == previousPair);
previousPair = pair;
bool needsRemoval = false;
if (!isDuplicate)
{
///important to use an AABB test that is consistent with the broadphase
bool hasOverlap = testAabbOverlap(pair.m_pProxy0,pair.m_pProxy1);
if (hasOverlap)
{
needsRemoval = false;//callback->processOverlap(pair);
} else
{
needsRemoval = true;
}
} else
{
//remove duplicate
needsRemoval = true;
//should have no algorithm
btAssert(!pair.m_algorithm);
}
if (needsRemoval)
{
m_pairCache->cleanOverlappingPair(pair,dispatcher);
// m_overlappingPairArray.swap(i,m_overlappingPairArray.size()-1);
// m_overlappingPairArray.pop_back();
pair.m_pProxy0 = 0;
pair.m_pProxy1 = 0;
m_invalidPair++;
gOverlappingPairs--;
}
}
///if you don't like to skip the invalid pairs in the array, execute following code:
#define CLEAN_INVALID_PAIRS 1
#ifdef CLEAN_INVALID_PAIRS
//perform a sort, to sort 'invalid' pairs to the end
overlappingPairArray.quickSort(btBroadphasePairSortPredicate());
overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair);
m_invalidPair = 0;
#endif//CLEAN_INVALID_PAIRS
//printf("overlappingPairArray.size()=%d\n",overlappingPairArray.size());
}
}
template <typename BP_FP_INT_TYPE>
bool btAxisSweep3Internal<BP_FP_INT_TYPE>::testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1)
{
const Handle* pHandleA = static_cast<Handle*>(proxy0);
const Handle* pHandleB = static_cast<Handle*>(proxy1);
//optimization 1: check the array index (memory address), instead of the m_pos
for (int axis = 0; axis < 3; axis++)
{
if (pHandleA->m_maxEdges[axis] < pHandleB->m_minEdges[axis] ||
pHandleB->m_maxEdges[axis] < pHandleA->m_minEdges[axis])
{
return false;
}
}
return true;
}
template <typename BP_FP_INT_TYPE>
bool btAxisSweep3Internal<BP_FP_INT_TYPE>::testOverlap2D(const Handle* pHandleA, const Handle* pHandleB,int axis0,int axis1)
{
//optimization 1: check the array index (memory address), instead of the m_pos
if (pHandleA->m_maxEdges[axis0] < pHandleB->m_minEdges[axis0] ||
pHandleB->m_maxEdges[axis0] < pHandleA->m_minEdges[axis0] ||
pHandleA->m_maxEdges[axis1] < pHandleB->m_minEdges[axis1] ||
pHandleB->m_maxEdges[axis1] < pHandleA->m_minEdges[axis1])
{
return false;
}
return true;
}
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::updateHandle(BP_FP_INT_TYPE handle, const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher)
{
// btAssert(bounds.IsFinite());
//btAssert(bounds.HasVolume());
Handle* pHandle = getHandle(handle);
// quantize the new bounds
BP_FP_INT_TYPE min[3], max[3];
quantize(min, aabbMin, 0);
quantize(max, aabbMax, 1);
// update changed edges
for (int axis = 0; axis < 3; axis++)
{
BP_FP_INT_TYPE emin = pHandle->m_minEdges[axis];
BP_FP_INT_TYPE emax = pHandle->m_maxEdges[axis];
int dmin = (int)min[axis] - (int)m_pEdges[axis][emin].m_pos;
int dmax = (int)max[axis] - (int)m_pEdges[axis][emax].m_pos;
m_pEdges[axis][emin].m_pos = min[axis];
m_pEdges[axis][emax].m_pos = max[axis];
// expand (only adds overlaps)
if (dmin < 0)
sortMinDown(axis, emin,dispatcher,true);
if (dmax > 0)
sortMaxUp(axis, emax,dispatcher,true);
// shrink (only removes overlaps)
if (dmin > 0)
sortMinUp(axis, emin,dispatcher,true);
if (dmax < 0)
sortMaxDown(axis, emax,dispatcher,true);
#ifdef DEBUG_BROADPHASE
debugPrintAxis(axis);
#endif //DEBUG_BROADPHASE
}
}
// sorting a min edge downwards can only ever *add* overlaps
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::sortMinDown(int axis, BP_FP_INT_TYPE edge, btDispatcher* /* dispatcher */, bool updateOverlaps)
{
Edge* pEdge = m_pEdges[axis] + edge;
Edge* pPrev = pEdge - 1;
Handle* pHandleEdge = getHandle(pEdge->m_handle);
while (pEdge->m_pos < pPrev->m_pos)
{
Handle* pHandlePrev = getHandle(pPrev->m_handle);
if (pPrev->IsMax())
{
// if previous edge is a maximum check the bounds and add an overlap if necessary
const int axis1 = (1 << axis) & 3;
const int axis2 = (1 << axis1) & 3;
if (updateOverlaps && testOverlap2D(pHandleEdge, pHandlePrev,axis1,axis2))
{
m_pairCache->addOverlappingPair(pHandleEdge,pHandlePrev);
if (m_userPairCallback)
m_userPairCallback->addOverlappingPair(pHandleEdge,pHandlePrev);
//AddOverlap(pEdge->m_handle, pPrev->m_handle);
}
// update edge reference in other handle
pHandlePrev->m_maxEdges[axis]++;
}
else
pHandlePrev->m_minEdges[axis]++;
pHandleEdge->m_minEdges[axis]--;
// swap the edges
Edge swap = *pEdge;
*pEdge = *pPrev;
*pPrev = swap;
// decrement
pEdge--;
pPrev--;
}
#ifdef DEBUG_BROADPHASE
debugPrintAxis(axis);
#endif //DEBUG_BROADPHASE
}
// sorting a min edge upwards can only ever *remove* overlaps
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::sortMinUp(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps)
{
Edge* pEdge = m_pEdges[axis] + edge;
Edge* pNext = pEdge + 1;
Handle* pHandleEdge = getHandle(pEdge->m_handle);
while (pNext->m_handle && (pEdge->m_pos >= pNext->m_pos))
{
Handle* pHandleNext = getHandle(pNext->m_handle);
if (pNext->IsMax())
{
Handle* handle0 = getHandle(pEdge->m_handle);
Handle* handle1 = getHandle(pNext->m_handle);
const int axis1 = (1 << axis) & 3;
const int axis2 = (1 << axis1) & 3;
// if next edge is maximum remove any overlap between the two handles
if (updateOverlaps
#ifdef USE_OVERLAP_TEST_ON_REMOVES
&& testOverlap2D(handle0,handle1,axis1,axis2)
#endif //USE_OVERLAP_TEST_ON_REMOVES
)
{
m_pairCache->removeOverlappingPair(handle0,handle1,dispatcher);
if (m_userPairCallback)
m_userPairCallback->removeOverlappingPair(handle0,handle1,dispatcher);
}
// update edge reference in other handle
pHandleNext->m_maxEdges[axis]--;
}
else
pHandleNext->m_minEdges[axis]--;
pHandleEdge->m_minEdges[axis]++;
// swap the edges
Edge swap = *pEdge;
*pEdge = *pNext;
*pNext = swap;
// increment
pEdge++;
pNext++;
}
}
// sorting a max edge downwards can only ever *remove* overlaps
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::sortMaxDown(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps)
{
Edge* pEdge = m_pEdges[axis] + edge;
Edge* pPrev = pEdge - 1;
Handle* pHandleEdge = getHandle(pEdge->m_handle);
while (pEdge->m_pos < pPrev->m_pos)
{
Handle* pHandlePrev = getHandle(pPrev->m_handle);
if (!pPrev->IsMax())
{
// if previous edge was a minimum remove any overlap between the two handles
Handle* handle0 = getHandle(pEdge->m_handle);
Handle* handle1 = getHandle(pPrev->m_handle);
const int axis1 = (1 << axis) & 3;
const int axis2 = (1 << axis1) & 3;
if (updateOverlaps
#ifdef USE_OVERLAP_TEST_ON_REMOVES
&& testOverlap2D(handle0,handle1,axis1,axis2)
#endif //USE_OVERLAP_TEST_ON_REMOVES
)
{
//this is done during the overlappingpairarray iteration/narrowphase collision
m_pairCache->removeOverlappingPair(handle0,handle1,dispatcher);
if (m_userPairCallback)
m_userPairCallback->removeOverlappingPair(handle0,handle1,dispatcher);
}
// update edge reference in other handle
pHandlePrev->m_minEdges[axis]++;;
}
else
pHandlePrev->m_maxEdges[axis]++;
pHandleEdge->m_maxEdges[axis]--;
// swap the edges
Edge swap = *pEdge;
*pEdge = *pPrev;
*pPrev = swap;
// decrement
pEdge--;
pPrev--;
}
#ifdef DEBUG_BROADPHASE
debugPrintAxis(axis);
#endif //DEBUG_BROADPHASE
}
// sorting a max edge upwards can only ever *add* overlaps
template <typename BP_FP_INT_TYPE>
void btAxisSweep3Internal<BP_FP_INT_TYPE>::sortMaxUp(int axis, BP_FP_INT_TYPE edge, btDispatcher* /* dispatcher */, bool updateOverlaps)
{
Edge* pEdge = m_pEdges[axis] + edge;
Edge* pNext = pEdge + 1;
Handle* pHandleEdge = getHandle(pEdge->m_handle);
while (pNext->m_handle && (pEdge->m_pos >= pNext->m_pos))
{
Handle* pHandleNext = getHandle(pNext->m_handle);
const int axis1 = (1 << axis) & 3;
const int axis2 = (1 << axis1) & 3;
if (!pNext->IsMax())
{
// if next edge is a minimum check the bounds and add an overlap if necessary
if (updateOverlaps && testOverlap2D(pHandleEdge, pHandleNext,axis1,axis2))
{
Handle* handle0 = getHandle(pEdge->m_handle);
Handle* handle1 = getHandle(pNext->m_handle);
m_pairCache->addOverlappingPair(handle0,handle1);
if (m_userPairCallback)
m_userPairCallback->addOverlappingPair(handle0,handle1);
}
// update edge reference in other handle
pHandleNext->m_minEdges[axis]--;
}
else
pHandleNext->m_maxEdges[axis]--;
pHandleEdge->m_maxEdges[axis]++;
// swap the edges
Edge swap = *pEdge;
*pEdge = *pNext;
*pNext = swap;
// increment
pEdge++;
pNext++;
}
}
////////////////////////////////////////////////////////////////////
/// The btAxisSweep3 is an efficient implementation of the 3d axis sweep and prune broadphase.
/// It uses arrays rather then lists for storage of the 3 axis. Also it operates using 16 bit integer coordinates instead of floats.
/// For large worlds and many objects, use bt32BitAxisSweep3 or btDbvtBroadphase instead. bt32BitAxisSweep3 has higher precision and allows more then 16384 objects at the cost of more memory and bit of performance.
class btAxisSweep3 : public btAxisSweep3Internal<unsigned short int>
{
public:
btAxisSweep3(const btVector3& worldAabbMin,const btVector3& worldAabbMax, unsigned short int maxHandles = 16384, btOverlappingPairCache* pairCache = 0, bool disableRaycastAccelerator = false);
};
/// The bt32BitAxisSweep3 allows higher precision quantization and more objects compared to the btAxisSweep3 sweep and prune.
/// This comes at the cost of more memory per handle, and a bit slower performance.
/// It uses arrays rather then lists for storage of the 3 axis.
class bt32BitAxisSweep3 : public btAxisSweep3Internal<unsigned int>
{
public:
bt32BitAxisSweep3(const btVector3& worldAabbMin,const btVector3& worldAabbMax, unsigned int maxHandles = 1500000, btOverlappingPairCache* pairCache = 0, bool disableRaycastAccelerator = false);
};
#endif
| 411 | 0.958201 | 1 | 0.958201 | game-dev | MEDIA | 0.941943 | game-dev | 0.966488 | 1 | 0.966488 |
jval1972/DelphiDoom | 5,753 | Doom/d_items.pas | //------------------------------------------------------------------------------
//
// DelphiDoom is a source port of the game Doom and it is
// based on original Linux Doom as published by "id Software"
// Copyright (C) 1993-1996 by id Software, Inc.
// Copyright (C) 2004-2022 by Jim Valavanis
//
// 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.
//
// DESCRIPTION:
// Items: key cards, artifacts, weapon, ammunition.
//
//------------------------------------------------------------------------------
// Site : https://sourceforge.net/projects/delphidoom/
//------------------------------------------------------------------------------
{$I Doom32.inc}
unit d_items;
interface
uses
doomdef,
info_h;
//
// mbf21: Internal weapon flags
//
const
WIF_ENABLEAPS = 1; // [XA] enable "ammo per shot" field for native Doom weapon codepointers
const
// no flag
WPF_NOFLAG = 0;
// doesn't thrust Mobj's
WPF_NOTHRUST = 1;
// weapon is silent
WPF_SILENT = 2;
// weapon won't autofire in A_WeaponReady
WPF_NOAUTOFIRE = 4;
// monsters consider it a melee weapon
WPF_FLEEMELEE = 8;
// can be switched away from when ammo is picked up
WPF_AUTOSWITCHFROM = $10;
// cannot be switched to when ammo is picked up
WPF_NOAUTOSWITCHTO = $20;
type
{ Weapon info: sprite frames, ammunition use. }
weaponinfo_t = record
ammo: ammotype_t;
upstate: integer;
downstate: integer;
readystate: integer;
atkstate: integer;
holdatkstate: integer;
flashstate: integer;
ammopershot: integer; // MBF21
intflags: integer; // MBF21
mbf21bits: integer; // MBF21
end;
Pweaponinfo_t = ^weaponinfo_t;
//
// PSPRITE ACTIONS for weapons.
// This struct controls the weapon animations.
//
// Each entry is:
// ammo/amunition type
// upstate
// downstate
// readystate
// atkstate, i.e. attack/fire/hit frame
// flashstate, muzzle flash
//
var
weaponinfo: array[0..Ord(NUMWEAPONS) - 1] of weaponinfo_t = (
// fist
(ammo: am_noammo; upstate: Ord(S_PUNCHUP); downstate: Ord(S_PUNCHDOWN);
readystate: Ord(S_PUNCH); atkstate: Ord(S_PUNCH1); holdatkstate: Ord(S_NULL);
flashstate: Ord(S_NULL);
ammopershot: 1; // MBF21
intflags: 0; // MBF21
mbf21bits: WPF_FLEEMELEE or WPF_AUTOSWITCHFROM or WPF_NOAUTOSWITCHTO; // MBF21
),
// pistol
(ammo: am_clip; upstate: Ord(S_PISTOLUP); downstate: Ord(S_PISTOLDOWN);
readystate: Ord(S_PISTOL); atkstate: Ord(S_PISTOL1); holdatkstate: Ord(S_NULL);
flashstate: Ord(S_PISTOLFLASH);
ammopershot: 1; // MBF21
intflags: 0; // MBF21
mbf21bits: WPF_AUTOSWITCHFROM; // MBF21
),
// shotgun
(ammo: am_shell; upstate: Ord(S_SGUNUP); downstate: Ord(S_SGUNDOWN);
readystate: Ord(S_SGUN); atkstate: Ord(S_SGUN1); holdatkstate: Ord(S_NULL);
flashstate: Ord(S_SGUNFLASH1);
ammopershot: 1; // MBF21
intflags: 0; // MBF21
mbf21bits: WPF_NOFLAG; // MBF21
),
// chaingun
(ammo: am_clip; upstate: Ord(S_CHAINUP); downstate: Ord(S_CHAINDOWN);
readystate: Ord(S_CHAIN); atkstate: Ord(S_CHAIN1); holdatkstate: Ord(S_NULL);
flashstate: Ord(S_CHAINFLASH1);
ammopershot: 1; // MBF21
intflags: 0; // MBF21
mbf21bits: WPF_NOFLAG; // MBF21
),
// missile launcher
(ammo: am_misl; upstate: Ord(S_MISSILEUP); downstate: Ord(S_MISSILEDOWN);
readystate: Ord(S_MISSILE); atkstate: Ord(S_MISSILE1); holdatkstate: Ord(S_NULL);
flashstate: Ord(S_MISSILEFLASH1);
ammopershot: 1; // MBF21
intflags: 0; // MBF21
mbf21bits: WPF_NOAUTOFIRE; // MBF21
),
// plasma rifle
(ammo: am_cell; upstate: Ord(S_PLASMAUP); downstate: Ord(S_PLASMADOWN);
readystate: Ord(S_PLASMA); atkstate: Ord(S_PLASMA1); holdatkstate: Ord(S_NULL);
flashstate: Ord(S_PLASMAFLASH1);
ammopershot: 1; // MBF21
intflags: 0; // MBF21
mbf21bits: WPF_NOFLAG; // MBF21
),
// bfg 9000
(ammo: am_cell; upstate: Ord(S_BFGUP); downstate: Ord(S_BFGDOWN);
readystate: Ord(S_BFG); atkstate: Ord(S_BFG1); holdatkstate: Ord(S_NULL);
flashstate: Ord(S_BFGFLASH1);
ammopershot: 40; // MBF21
intflags: 0; // MBF21
mbf21bits: WPF_NOAUTOFIRE; // MBF21
),
// chainsaw
(ammo: am_noammo; upstate: Ord(S_SAWUP); downstate: Ord(S_SAWDOWN);
readystate: Ord(S_SAW); atkstate: Ord(S_SAW1); holdatkstate: Ord(S_NULL);
flashstate: Ord(S_NULL);
ammopershot: 1; // MBF21
intflags: 0; // MBF21
mbf21bits: WPF_NOTHRUST or WPF_FLEEMELEE or WPF_NOAUTOSWITCHTO; // MBF21
),
// super shotgun
(ammo: am_shell; upstate: Ord(S_DSGUNUP); downstate: Ord(S_DSGUNDOWN);
readystate: Ord(S_DSGUN); atkstate: Ord(S_DSGUN1); holdatkstate: Ord(S_NULL);
flashstate: Ord(S_DSGUNFLASH1);
ammopershot: 2; // MBF21
intflags: 0; // MBF21
mbf21bits: WPF_NOFLAG; // MBF21
)
);
implementation
end.
| 411 | 0.831936 | 1 | 0.831936 | game-dev | MEDIA | 0.96862 | game-dev | 0.705134 | 1 | 0.705134 |
Electroblob77/Wizardry | 6,408 | src/main/java/electroblob/wizardry/entity/construct/EntityMagicConstruct.java | package electroblob.wizardry.entity.construct;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.item.ISpellCastingItem;
import electroblob.wizardry.registry.WizardrySounds;
import electroblob.wizardry.util.AllyDesignationSystem;
import electroblob.wizardry.util.EntityUtils;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.IEntityOwnable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nullable;
import java.util.UUID;
/**
* This class is for all inanimate magical constructs which are not projectiles. Generally speaking, subclasses of this
* class are areas of effect which deal damage or apply effects over time, including black hole, blizzard, tornado and
* a few others. The caster UUID, lifetime and damage multiplier are stored here, and lifetime is also synced here.
*
* @since Wizardry 1.0
*/
public abstract class EntityMagicConstruct extends Entity implements IEntityOwnable, IEntityAdditionalSpawnData {
/** The UUID of the caster. As of Wizardry 4.3, this <b>is</b> synced, and rather than storing the caster
* instance via a weak reference, it is fetched from the UUID each time it is needed in
* {@link EntityMagicConstruct#getCaster()}. */
private UUID casterUUID;
/** The time in ticks this magical construct lasts for; defaults to 600 (30 seconds). If this is -1 the construct
* doesn't despawn. */
public int lifetime = 600;
/** The damage multiplier for this construct, determined by the wand with which it was cast. */
public float damageMultiplier = 1.0f;
public EntityMagicConstruct(World world){
super(world);
this.height = 1.0f;
this.width = 1.0f;
this.noClip = true;
}
// Overrides the original to stop the entity moving when it intersects stuff. The default arrow does this to allow
// it to stick in blocks.
@Override
@SideOnly(Side.CLIENT)
public void setPositionAndRotationDirect(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean teleport){
this.setPosition(x, y, z);
this.setRotation(yaw, pitch);
}
public void onUpdate(){
if(this.ticksExisted > lifetime && lifetime != -1){
this.despawn();
}
super.onUpdate();
}
@Override
public EnumActionResult applyPlayerInteraction(EntityPlayer player, Vec3d vec, EnumHand hand){
// Permanent constructs can now be dispelled by sneak-right-clicking
if(lifetime == -1 && getCaster() == player && player.isSneaking() && player.getHeldItem(hand).getItem() instanceof ISpellCastingItem){
this.despawn();
return EnumActionResult.SUCCESS;
}
return super.applyPlayerInteraction(player, vec, hand);
}
/**
* Defaults to just setDead() in EntityMagicConstruct, but is provided to allow subclasses to override this e.g.
* bubble uses it to dismount the entity inside it and play the 'pop' sound before calling super(). You should
* always call super() when overriding this method, in case it changes. There is no need, therefore, to call
* setDead() when overriding.
*/
public void despawn(){
this.setDead();
}
@Override
protected void entityInit(){
// We could leave this unimplemented, but since the majority of subclasses don't use it, let's make it optional
}
@Override
protected void readEntityFromNBT(NBTTagCompound nbttagcompound){
if(nbttagcompound.hasUniqueId("casterUUID")) casterUUID = nbttagcompound.getUniqueId("casterUUID");
lifetime = nbttagcompound.getInteger("lifetime");
damageMultiplier = nbttagcompound.getFloat("damageMultiplier");
}
@Override
protected void writeEntityToNBT(NBTTagCompound nbttagcompound){
if(casterUUID != null){
nbttagcompound.setUniqueId("casterUUID", casterUUID);
}
nbttagcompound.setInteger("lifetime", lifetime);
nbttagcompound.setFloat("damageMultiplier", damageMultiplier);
}
@Override
public void writeSpawnData(ByteBuf data){
data.writeInt(lifetime);
data.writeInt(getCaster() == null ? -1 : getCaster().getEntityId());
}
@Override
public void readSpawnData(ByteBuf data){
lifetime = data.readInt();
int id = data.readInt();
if(id == -1){
setCaster(null);
}else{
Entity entity = world.getEntityByID(id);
if(entity instanceof EntityLivingBase){
setCaster((EntityLivingBase)entity);
}else{
Wizardry.logger.warn("Construct caster with ID in spawn data not found");
}
}
}
@Nullable
@Override
public UUID getOwnerId(){
return casterUUID;
}
@Nullable
@Override
public Entity getOwner(){
return getCaster(); // Delegate to getCaster
}
/**
* Returns the EntityLivingBase that created this construct, or null if it no longer exists. Cases where the entity
* may no longer exist are: entity died or was deleted, mob despawned, player logged out, entity teleported to
* another dimension, or this construct simply had no caster in the first place.
*/
@Nullable
public EntityLivingBase getCaster(){ // Kept despite the above method because it returns an EntityLivingBase
Entity entity = EntityUtils.getEntityByUUID(world, getOwnerId());
if(entity != null && !(entity instanceof EntityLivingBase)){ // Should never happen
Wizardry.logger.warn("{} has a non-living owner!", this);
entity = null;
}
return (EntityLivingBase)entity;
}
public void setCaster(@Nullable EntityLivingBase caster){
this.casterUUID = caster == null ? null : caster.getUniqueID();
}
/**
* Shorthand for {@link AllyDesignationSystem#isValidTarget(Entity, Entity)}, with the owner of this construct as the
* attacker. Also allows subclasses to override it if they wish to do so.
*/
public boolean isValidTarget(Entity target){
return AllyDesignationSystem.isValidTarget(this.getCaster(), target);
}
@Override
public SoundCategory getSoundCategory(){
return WizardrySounds.SPELLS;
}
@Override
public boolean canRenderOnFire(){
return false;
}
@Override
public boolean isPushedByWater(){
return false;
}
}
| 411 | 0.835225 | 1 | 0.835225 | game-dev | MEDIA | 0.97985 | game-dev | 0.93985 | 1 | 0.93985 |
LiXizhi/NPLRuntime | 3,497 | Client/trunk/externals/bullet-2.75/src/BulletCollision/CollisionShapes/btConvexPointCloudShape.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_CONVEX_POINT_CLOUD_SHAPE_H
#define BT_CONVEX_POINT_CLOUD_SHAPE_H
#include "btPolyhedralConvexShape.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types
#include "LinearMath/btAlignedObjectArray.h"
///The btConvexPointCloudShape implements an implicit convex hull of an array of vertices.
ATTRIBUTE_ALIGNED16(class) btConvexPointCloudShape : public btPolyhedralConvexAabbCachingShape
{
btVector3* m_unscaledPoints;
int m_numPoints;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btConvexPointCloudShape()
{
m_localScaling.setValue(1.f,1.f,1.f);
m_shapeType = CONVEX_POINT_CLOUD_SHAPE_PROXYTYPE;
m_unscaledPoints = 0;
m_numPoints = 0;
}
btConvexPointCloudShape(btVector3* points,int numPoints, const btVector3& localScaling,bool computeAabb = true)
{
m_localScaling = localScaling;
m_shapeType = CONVEX_POINT_CLOUD_SHAPE_PROXYTYPE;
m_unscaledPoints = points;
m_numPoints = numPoints;
if (computeAabb)
recalcLocalAabb();
}
void setPoints (btVector3* points, int numPoints, bool computeAabb = true,const btVector3& localScaling=btVector3(1.f,1.f,1.f))
{
m_unscaledPoints = points;
m_numPoints = numPoints;
m_localScaling = localScaling;
if (computeAabb)
recalcLocalAabb();
}
SIMD_FORCE_INLINE btVector3* getUnscaledPoints()
{
return m_unscaledPoints;
}
SIMD_FORCE_INLINE const btVector3* getUnscaledPoints() const
{
return m_unscaledPoints;
}
SIMD_FORCE_INLINE int getNumPoints() const
{
return m_numPoints;
}
SIMD_FORCE_INLINE btVector3 getScaledPoint( int index) const
{
return m_unscaledPoints[index] * m_localScaling;
}
#ifndef __SPU__
virtual btVector3 localGetSupportingVertex(const btVector3& vec)const;
virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const;
virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const;
#endif
//debugging
virtual const char* getName()const {return "ConvexPointCloud";}
virtual int getNumVertices() const;
virtual int getNumEdges() const;
virtual void getEdge(int i,btVector3& pa,btVector3& pb) const;
virtual void getVertex(int i,btVector3& vtx) const;
virtual int getNumPlanes() const;
virtual void getPlane(btVector3& planeNormal,btVector3& planeSupport,int i ) const;
virtual bool isInside(const btVector3& pt,btScalar tolerance) const;
///in case we receive negative scaling
virtual void setLocalScaling(const btVector3& scaling);
};
#endif //BT_CONVEX_POINT_CLOUD_SHAPE_H
| 411 | 0.890865 | 1 | 0.890865 | game-dev | MEDIA | 0.973259 | game-dev | 0.855468 | 1 | 0.855468 |
TheDuckCow/godot-road-generator | 4,249 | demo/procedural_generator/road_actor.gd | extends Node3D
enum DriveState {
PARK,
AUTO,
PLAYER
}
@export var drive_state: DriveState = DriveState.AUTO
# Target speed in meters per second
@export var acceleration := 1 # in meters per sec squared
@export var target_speed := 30 # in meters per sec
@export var visualize_lane := false
@export var seek_ahead := 5.0 # How many meters in front of agent to seek position
@export var auto_register: bool = true
@onready var agent:RoadLaneAgent = get_node("%road_lane_agent")
# how big car difference triggers lane change
var lane_change_tolerance = 3
var velocity := Vector3.ZERO
const transition_time_close := 0.05 # how close to end of a transition lane actor has to switch lane
const DEBUG_OUT: bool = false
func _ready() -> void:
agent.visualize_lane = visualize_lane
agent.auto_register = auto_register
if DEBUG_OUT:
print("Agent state: %s par, %s lane, %s manager" % [
agent.actor, agent.current_lane, agent.road_manager
])
if not visible:
set_process(false)
set_physics_process(false)
## Generic function to calc speed
func get_signed_speed() -> float:
return -velocity.z
func get_input() -> Vector3:
match drive_state:
DriveState.AUTO:
return _get_auto_input()
DriveState.PLAYER:
return _get_player_input()
_:
return Vector3.ZERO
func _get_auto_input() -> Vector3:
if ! is_instance_valid(agent.current_lane):
return Vector3.ZERO
var lane_move:int = 0
var speed = get_signed_speed()
if agent.current_lane.transition && agent.close_to_lane_end(abs(speed * transition_time_close), sign(speed)):
# transition line ended, try to automatically switch to the lane that has lane ahead linked
lane_move = agent.find_continued_lane(agent.LaneChangeDir.LEFT, sign(speed))
else:
var cur_cars:int = agent.cars_in_lane(RoadLaneAgent.LaneChangeDir.CURRENT)
if (cur_cars > 1):
var cur_cars_l:int = agent.cars_in_lane(agent.LaneChangeDir.LEFT)
var cur_cars_r:int = agent.cars_in_lane(agent.LaneChangeDir.RIGHT)
if (cur_cars_l >= 0) && (cur_cars - cur_cars_l > lane_change_tolerance):
lane_move -= 1
elif (cur_cars_r >= 0) && (cur_cars - cur_cars_r > lane_change_tolerance):
lane_move += 1
return Vector3(lane_move, 0, -1) # neg z is "forward"
func _get_player_input() -> Vector3:
if ! is_instance_valid(agent.current_lane):
return Vector3.ZERO
var dir:float = 0
var lane_move:int = 0
if Input.is_action_pressed("ui_up"):
dir += 1
if Input.is_action_pressed("ui_down"):
dir -= 1
var speed = get_signed_speed()
if agent.current_lane.transition && agent.close_to_lane_end(abs(speed* transition_time_close), sign(speed)):
# transition line ends soon, try to automatically switch to the lane that has lane ahead linked
lane_move = agent.find_continued_lane(agent.LaneChangeDir.LEFT, sign(speed))
else:
if Input.is_action_just_pressed("ui_left"):
lane_move -= 1
if Input.is_action_just_pressed("ui_right"):
lane_move += 1
return Vector3(lane_move, 0, -dir) # neg z is "forward"
func _physics_process(delta: float) -> void:
velocity.y = 0
var target_dir:Vector3 = get_input()
var target_velz = lerp(velocity.z, target_dir.z * target_speed, delta * acceleration)
velocity.z = target_velz
agent.change_lane(int(target_dir.x))
if not is_instance_valid(agent.current_lane):
var res = agent.assign_nearest_lane()
if not res == OK:
print("Failed to find new lane")
queue_free()
return
# Find the next position to jump to; note that the car's forward is the
# negative Z direction (conventional with Vector3.FORWARD), and thus
# we flip the direction along the Z axis so that positive move direction
# matches a positive move_along_lane call, while negative would be
# going in reverse in the lane's intended direction.
var move_dist:float = get_signed_speed() * delta
var next_pos: Vector3 = agent.move_along_lane(move_dist)
global_transform.origin = next_pos
# Get another point a little further in front for orientation seeking,
# without actually moving the vehicle (ie don't update the assign lane
# if this margin puts us into the next lane in front)
var orientation:Vector3 = agent.test_move_along_lane(0.05)
if ! global_transform.origin.is_equal_approx(orientation):
look_at(orientation, Vector3.UP)
| 411 | 0.851355 | 1 | 0.851355 | game-dev | MEDIA | 0.64526 | game-dev | 0.925072 | 1 | 0.925072 |
ipc-sim/ipc-toolkit | 4,545 | python/src/potentials/potential.hpp | #include <common.hpp>
#include <ipc/potentials/potential.hpp>
using namespace ipc;
/// @brief Define the methods of the templated generic Potential class.
/// @tparam TCollisions Type of the collisions.
/// @tparam PyClass The pybind11 class to define the methods on.
/// @param potential The pybind11 class to define the methods on.
template <typename TCollisions, typename PyClass>
void define_potential_methods(PyClass& potential)
{
using TCollision = typename TCollisions::value_type;
potential
.def(
"__call__",
py::overload_cast<
const TCollisions&, const CollisionMesh&,
Eigen::ConstRef<Eigen::MatrixXd>>(
&Potential<TCollisions>::operator(), py::const_),
R"ipc_Qu8mg5v7(
Compute the potential for a set of collisions.
Parameters:
collisions: The set of collisions.
mesh: The collision mesh.
X: Degrees of freedom of the collision mesh (e.g., vertices or velocities).
Returns:
The potential for a set of collisions.
)ipc_Qu8mg5v7",
"collisions"_a, "mesh"_a, "X"_a)
.def(
"gradient",
py::overload_cast<
const TCollisions&, const CollisionMesh&,
Eigen::ConstRef<Eigen::MatrixXd>>(
&Potential<TCollisions>::gradient, py::const_),
R"ipc_Qu8mg5v7(
Compute the gradient of the potential.
Parameters:
collisions: The set of collisions.
mesh: The collision mesh.
X: Degrees of freedom of the collision mesh (e.g., vertices or velocities).
Returns:
The gradient of the potential w.r.t. X. This will have a size of |X|.
)ipc_Qu8mg5v7",
"collisions"_a, "mesh"_a, "X"_a)
.def(
"hessian",
py::overload_cast<
const TCollisions&, const CollisionMesh&,
Eigen::ConstRef<Eigen::MatrixXd>, const PSDProjectionMethod>(
&Potential<TCollisions>::hessian, py::const_),
R"ipc_Qu8mg5v7(
Compute the hessian of the potential.
Parameters:
collisions: The set of collisions.
mesh: The collision mesh.
X: Degrees of freedom of the collision mesh (e.g., vertices or velocities).
project_hessian_to_psd: Make sure the hessian is positive semi-definite.
Returns:
The Hessian of the potential w.r.t. X. This will have a size of |X|×|X|.
)ipc_Qu8mg5v7",
"collisions"_a, "mesh"_a, "X"_a,
"project_hessian_to_psd"_a = PSDProjectionMethod::NONE)
.def(
"__call__",
py::overload_cast<const TCollision&, Eigen::ConstRef<VectorMax12d>>(
&Potential<TCollisions>::operator(), py::const_),
R"ipc_Qu8mg5v7(
Compute the potential for a single collision.
Parameters:
collision: The collision.
x: The collision stencil's degrees of freedom.
Returns:
The potential.
)ipc_Qu8mg5v7",
"collision"_a, "x"_a)
.def(
"gradient",
py::overload_cast<const TCollision&, Eigen::ConstRef<VectorMax12d>>(
&Potential<TCollisions>::gradient, py::const_),
R"ipc_Qu8mg5v7(
Compute the gradient of the potential for a single collision.
Parameters:
collision: The collision.
x: The collision stencil's degrees of freedom.
Returns:
The gradient of the potential.
)ipc_Qu8mg5v7",
"collision"_a, "x"_a)
.def(
"hessian",
py::overload_cast<
const TCollision&, Eigen::ConstRef<VectorMax12d>,
const PSDProjectionMethod>(
&Potential<TCollisions>::hessian, py::const_),
R"ipc_Qu8mg5v7(
Compute the hessian of the potential for a single collision.
Parameters:
collision: The collision.
x: The collision stencil's degrees of freedom.
Returns:
The hessian of the potential.
)ipc_Qu8mg5v7",
"collision"_a, "x"_a,
"project_hessian_to_psd"_a = PSDProjectionMethod::NONE);
}
| 411 | 0.868428 | 1 | 0.868428 | game-dev | MEDIA | 0.643682 | game-dev | 0.824003 | 1 | 0.824003 |
pablushaa/AllahClientRecode | 3,024 | net/minecraft/entity/boss/dragon/phase/PhaseTakeoff.java | package net.minecraft.entity.boss.dragon.phase;
import javax.annotation.Nullable;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.pathfinding.Path;
import net.minecraft.pathfinding.PathPoint;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.gen.feature.WorldGenEndPodium;
public class PhaseTakeoff extends PhaseBase
{
private boolean firstTick;
private Path currentPath;
private Vec3d targetLocation;
public PhaseTakeoff(EntityDragon dragonIn)
{
super(dragonIn);
}
/**
* Gives the phase a chance to update its status.
* Called by dragon's onLivingUpdate. Only used when !worldObj.isRemote.
*/
public void doLocalUpdate()
{
if (!this.firstTick && this.currentPath != null)
{
BlockPos blockpos = this.dragon.world.getTopSolidOrLiquidBlock(WorldGenEndPodium.END_PODIUM_LOCATION);
double d0 = this.dragon.getDistanceSqToCenter(blockpos);
if (d0 > 100.0D)
{
this.dragon.getPhaseManager().setPhase(PhaseList.HOLDING_PATTERN);
}
}
else
{
this.firstTick = false;
this.findNewTarget();
}
}
/**
* Called when this phase is set to active
*/
public void initPhase()
{
this.firstTick = true;
this.currentPath = null;
this.targetLocation = null;
}
private void findNewTarget()
{
int i = this.dragon.initPathPoints();
Vec3d vec3d = this.dragon.getHeadLookVec(1.0F);
int j = this.dragon.getNearestPpIdx(-vec3d.xCoord * 40.0D, 105.0D, -vec3d.zCoord * 40.0D);
if (this.dragon.getFightManager() != null && this.dragon.getFightManager().getNumAliveCrystals() > 0)
{
j = j % 12;
if (j < 0)
{
j += 12;
}
}
else
{
j = j - 12;
j = j & 7;
j = j + 12;
}
this.currentPath = this.dragon.findPath(i, j, (PathPoint)null);
if (this.currentPath != null)
{
this.currentPath.incrementPathIndex();
this.navigateToNextPathNode();
}
}
private void navigateToNextPathNode()
{
Vec3d vec3d = this.currentPath.getCurrentPos();
this.currentPath.incrementPathIndex();
double d0;
while (true)
{
d0 = vec3d.yCoord + (double)(this.dragon.getRNG().nextFloat() * 20.0F);
if (d0 >= vec3d.yCoord)
{
break;
}
}
this.targetLocation = new Vec3d(vec3d.xCoord, d0, vec3d.zCoord);
}
@Nullable
/**
* Returns the location the dragon is flying toward
*/
public Vec3d getTargetLocation()
{
return this.targetLocation;
}
public PhaseList<PhaseTakeoff> getPhaseList()
{
return PhaseList.TAKEOFF;
}
}
| 411 | 0.80437 | 1 | 0.80437 | game-dev | MEDIA | 0.977476 | game-dev | 0.963138 | 1 | 0.963138 |
tukui-org/ElvUI | 1,531 | ElvUI/Mainline/Modules/Skins/GMChat.lua | local E, L, V, P, G = unpack(ElvUI)
local S = E:GetModule('Skins')
local _G = _G
function S:Blizzard_GMChatUI()
if not (E.private.skins.blizzard.enable and E.private.skins.blizzard.gmChat) then return end
local frame = _G.GMChatFrame
frame:SetClampRectInsets(0, 0, 0, 0)
frame:StripTextures()
frame:SetTemplate('Transparent')
frame.buttonFrame:Hide()
local editbox = frame.editBox
editbox:SetAltArrowKeyMode(false)
editbox:SetTemplate()
editbox:ClearAllPoints()
editbox:Point('TOPLEFT', frame, 'BOTTOMLEFT', 0, -5)
editbox:Point('BOTTOMRIGHT', frame, 'BOTTOMRIGHT', 0, -32)
_G.GMChatFrameEditBoxRight:SetAlpha(0)
_G.GMChatFrameEditBoxLeft:SetAlpha(0)
_G.GMChatFrameEditBoxMid:SetAlpha(0)
_G.GMChatFrameEditBoxFocusRight:SetAlpha(0)
_G.GMChatFrameEditBoxFocusLeft:SetAlpha(0)
_G.GMChatFrameEditBoxFocusMid:SetAlpha(0)
local lang = _G.GMChatFrameEditBoxLanguage
lang:GetRegions():SetAlpha(0)
lang:ClearAllPoints()
lang:Point('TOPLEFT', editbox, 'TOPRIGHT', 3, 0)
lang:Point('BOTTOMRIGHT', editbox, 'BOTTOMRIGHT', 28, 0)
local tab = _G.GMChatTab
tab:StripTextures()
tab:SetTemplate('Transparent')
tab:SetBackdropColor(0, .6, 1, .3)
tab:ClearAllPoints()
tab:Point('BOTTOMLEFT', frame, 'TOPLEFT', 0, 2)
tab:Point('TOPRIGHT', frame, 'TOPRIGHT', 0, 28)
_G.GMChatTabIcon:SetTexture([[Interface\ChatFrame\UI-ChatIcon-Blizz]])
local close = _G.GMChatFrameCloseButton
close:ClearAllPoints()
close:Point('RIGHT', tab, -5, 0)
S:HandleCloseButton(close)
end
S:AddCallbackForAddon('Blizzard_GMChatUI')
| 411 | 0.877879 | 1 | 0.877879 | game-dev | MEDIA | 0.495241 | game-dev,desktop-app | 0.890387 | 1 | 0.890387 |
ezEngine/ezEngine | 1,625 | Data/UnitTests/GameEngineTest/AngelScript/Tests/PhysicsTest.as | #include "TestFramework.as"
enum Phase
{
Raycast,
Spatial,
Done
}
class ScriptObject : ezAngelScriptTestClass
{
private Phase m_Phase = Phase::Raycast;
private int m_iFoundInside = 0;
private int m_iFoundOther = 0;
private array<ezGameObjectHandle> m_Found;
ScriptObject()
{
super("PhysicsTest");
}
bool FoundObject(ezGameObject@ obj)
{
if (obj.HasName("Inside"))
++m_iFoundInside;
else
++m_iFoundOther;
m_Found.PushBack(obj.GetHandle());
return true;
}
bool ExecuteTests()
{
if (m_Phase == Phase::Raycast)
{
ezVec3 vHitPosition, vHitNormal;
ezGameObjectHandle hHitObject;
EZ_TEST_BOOL(!ezPhysics::Raycast(vHitPosition, vHitNormal, hHitObject, ezVec3(1, 2, 3), ezVec3(0, 0, -1) * 10.0f, 0, ezPhysicsShapeType::Dynamic));
EZ_TEST_BOOL(ezPhysics::Raycast(vHitPosition, vHitNormal, hHitObject, ezVec3(1, 2, 3), ezVec3(0, 0, -1) * 10.0f, 0, ezPhysicsShapeType::Static));
EZ_TEST_VEC3(vHitPosition, ezVec3(1, 2, 0));
EZ_TEST_VEC3(vHitNormal, ezVec3(0, 0, 1));
m_Phase = Phase::Spatial;
}
else if (m_Phase == Phase::Spatial)
{
ezSpatial::FindObjectsInSphere("Marker", ezVec3(5.5f, 5.5f, 5.0f), 1.0f, ReportObjectCB(FoundObject));
EZ_TEST_INT(m_iFoundInside, 4);
EZ_TEST_INT(m_iFoundOther, 0);
EZ_TEST_INT(m_Found.GetCount(), 4);
m_Phase = Phase::Done;
}
return m_Phase != Phase::Done;
}
}
| 411 | 0.703867 | 1 | 0.703867 | game-dev | MEDIA | 0.422958 | game-dev | 0.748011 | 1 | 0.748011 |
openjdk/jdk8 | 11,069 | hotspot/src/share/vm/classfile/classLoaderData.hpp | /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_CLASSFILE_CLASSLOADERDATA_HPP
#define SHARE_VM_CLASSFILE_CLASSLOADERDATA_HPP
#include "memory/allocation.hpp"
#include "memory/memRegion.hpp"
#include "memory/metaspace.hpp"
#include "memory/metaspaceCounters.hpp"
#include "runtime/mutex.hpp"
#include "utilities/growableArray.hpp"
#if INCLUDE_TRACE
# include "utilities/ticks.hpp"
#endif
//
// A class loader represents a linkset. Conceptually, a linkset identifies
// the complete transitive closure of resolved links that a dynamic linker can
// produce.
//
// A ClassLoaderData also encapsulates the allocation space, called a metaspace,
// used by the dynamic linker to allocate the runtime representation of all
// the types it defines.
//
// ClassLoaderData are stored in the runtime representation of classes and the
// system dictionary, are roots of garbage collection, and provides iterators
// for root tracing and other GC operations.
class ClassLoaderData;
class JNIMethodBlock;
class JNIHandleBlock;
class Metadebug;
// GC root for walking class loader data created
class ClassLoaderDataGraph : public AllStatic {
friend class ClassLoaderData;
friend class ClassLoaderDataGraphMetaspaceIterator;
friend class VMStructs;
private:
// All CLDs (except the null CLD) can be reached by walking _head->_next->...
static ClassLoaderData* _head;
static ClassLoaderData* _unloading;
// CMS support.
static ClassLoaderData* _saved_head;
static ClassLoaderData* add(Handle class_loader, bool anonymous, TRAPS);
static void post_class_unload_events(void);
public:
static ClassLoaderData* find_or_create(Handle class_loader, TRAPS);
static void purge();
static void clear_claimed_marks();
static void oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim);
static void always_strong_oops_do(OopClosure* blk, KlassClosure* klass_closure, bool must_claim);
static void keep_alive_oops_do(OopClosure* blk, KlassClosure* klass_closure, bool must_claim);
static void classes_do(KlassClosure* klass_closure);
static void classes_do(void f(Klass* const));
static void loaded_classes_do(KlassClosure* klass_closure);
static void classes_unloading_do(void f(Klass* const));
static bool do_unloading(BoolObjectClosure* is_alive);
// CMS support.
static void remember_new_clds(bool remember) { _saved_head = (remember ? _head : NULL); }
static GrowableArray<ClassLoaderData*>* new_clds();
static void dump_on(outputStream * const out) PRODUCT_RETURN;
static void dump() { dump_on(tty); }
static void verify();
#ifndef PRODUCT
// expensive test for pointer in metaspace for debugging
static bool contains(address x);
static bool contains_loader_data(ClassLoaderData* loader_data);
#endif
#if INCLUDE_TRACE
private:
static Ticks _class_unload_time;
static void class_unload_event(Klass* const k);
#endif
};
// ClassLoaderData class
class ClassLoaderData : public CHeapObj<mtClass> {
friend class VMStructs;
private:
class Dependencies VALUE_OBJ_CLASS_SPEC {
objArrayOop _list_head;
void locked_add(objArrayHandle last,
objArrayHandle new_dependency,
Thread* THREAD);
public:
Dependencies() : _list_head(NULL) {}
Dependencies(TRAPS) : _list_head(NULL) {
init(CHECK);
}
void add(Handle dependency, TRAPS);
void init(TRAPS);
void oops_do(OopClosure* f);
};
friend class ClassLoaderDataGraph;
friend class ClassLoaderDataGraphMetaspaceIterator;
friend class MetaDataFactory;
friend class Method;
static ClassLoaderData * _the_null_class_loader_data;
oop _class_loader; // oop used to uniquely identify a class loader
// class loader or a canonical class path
Dependencies _dependencies; // holds dependencies from this class loader
// data to others.
Metaspace * _metaspace; // Meta-space where meta-data defined by the
// classes in the class loader are allocated.
Mutex* _metaspace_lock; // Locks the metaspace for allocations and setup.
bool _unloading; // true if this class loader goes away
bool _keep_alive; // if this CLD can be unloaded for anonymous loaders
bool _is_anonymous; // if this CLD is for an anonymous class
volatile int _claimed; // true if claimed, for example during GC traces.
// To avoid applying oop closure more than once.
// Has to be an int because we cas it.
Klass* _klasses; // The classes defined by the class loader.
JNIHandleBlock* _handles; // Handles to constant pool arrays
// These method IDs are created for the class loader and set to NULL when the
// class loader is unloaded. They are rarely freed, only for redefine classes
// and if they lose a data race in InstanceKlass.
JNIMethodBlock* _jmethod_ids;
// Metadata to be deallocated when it's safe at class unloading, when
// this class loader isn't unloaded itself.
GrowableArray<Metadata*>* _deallocate_list;
// Support for walking class loader data objects
ClassLoaderData* _next; /// Next loader_datas created
// ReadOnly and ReadWrite metaspaces (static because only on the null
// class loader for now).
static Metaspace* _ro_metaspace;
static Metaspace* _rw_metaspace;
void set_next(ClassLoaderData* next) { _next = next; }
ClassLoaderData* next() const { return _next; }
ClassLoaderData(Handle h_class_loader, bool is_anonymous, Dependencies dependencies);
~ClassLoaderData();
void set_metaspace(Metaspace* m) { _metaspace = m; }
JNIHandleBlock* handles() const;
void set_handles(JNIHandleBlock* handles);
Mutex* metaspace_lock() const { return _metaspace_lock; }
// GC interface.
void clear_claimed() { _claimed = 0; }
bool claimed() const { return _claimed == 1; }
bool claim();
void unload();
bool keep_alive() const { return _keep_alive; }
bool is_alive(BoolObjectClosure* is_alive_closure) const;
void classes_do(void f(Klass*));
void loaded_classes_do(KlassClosure* klass_closure);
void classes_do(void f(InstanceKlass*));
// Deallocate free list during class unloading.
void free_deallocate_list();
// Allocate out of this class loader data
MetaWord* allocate(size_t size);
public:
// Accessors
Metaspace* metaspace_or_null() const { return _metaspace; }
static ClassLoaderData* the_null_class_loader_data() {
return _the_null_class_loader_data;
}
bool is_anonymous() const { return _is_anonymous; }
static void init_null_class_loader_data() {
assert(_the_null_class_loader_data == NULL, "cannot initialize twice");
assert(ClassLoaderDataGraph::_head == NULL, "cannot initialize twice");
// We explicitly initialize the Dependencies object at a later phase in the initialization
_the_null_class_loader_data = new ClassLoaderData((oop)NULL, false, Dependencies());
ClassLoaderDataGraph::_head = _the_null_class_loader_data;
assert(_the_null_class_loader_data->is_the_null_class_loader_data(), "Must be");
if (DumpSharedSpaces) {
_the_null_class_loader_data->initialize_shared_metaspaces();
}
}
bool is_the_null_class_loader_data() const {
return this == _the_null_class_loader_data;
}
bool is_ext_class_loader_data() const;
// The Metaspace is created lazily so may be NULL. This
// method will allocate a Metaspace if needed.
Metaspace* metaspace_non_null();
oop class_loader() const { return _class_loader; }
// Returns true if this class loader data is for a loader going away.
bool is_unloading() const {
assert(!(is_the_null_class_loader_data() && _unloading), "The null class loader can never be unloaded");
return _unloading;
}
// Anonymous class loader data doesn't have anything to keep them from
// being unloaded during parsing the anonymous class.
void set_keep_alive(bool value) { _keep_alive = value; }
unsigned int identity_hash() {
return _class_loader == NULL ? 0 : _class_loader->identity_hash();
}
// Used when tracing from klasses.
void oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim);
void classes_do(KlassClosure* klass_closure);
JNIMethodBlock* jmethod_ids() const { return _jmethod_ids; }
void set_jmethod_ids(JNIMethodBlock* new_block) { _jmethod_ids = new_block; }
void print_value() { print_value_on(tty); }
void print_value_on(outputStream* out) const;
void dump(outputStream * const out) PRODUCT_RETURN;
void verify();
const char* loader_name();
jobject add_handle(Handle h);
void add_class(Klass* k);
void remove_class(Klass* k);
void record_dependency(Klass* to, TRAPS);
void init_dependencies(TRAPS);
void add_to_deallocate_list(Metadata* m);
static ClassLoaderData* class_loader_data(oop loader);
static ClassLoaderData* class_loader_data_or_null(oop loader);
static ClassLoaderData* anonymous_class_loader_data(oop loader, TRAPS);
static void print_loader(ClassLoaderData *loader_data, outputStream *out);
// CDS support
Metaspace* ro_metaspace();
Metaspace* rw_metaspace();
void initialize_shared_metaspaces();
};
class ClassLoaderDataGraphMetaspaceIterator : public StackObj {
ClassLoaderData* _data;
public:
ClassLoaderDataGraphMetaspaceIterator();
~ClassLoaderDataGraphMetaspaceIterator();
bool repeat() { return _data != NULL; }
Metaspace* get_next() {
assert(_data != NULL, "Should not be NULL in call to the iterator");
Metaspace* result = _data->metaspace_or_null();
_data = _data->next();
// This result might be NULL for class loaders without metaspace
// yet. It would be nice to return only non-null results but
// there is no guarantee that there will be a non-null result
// down the list so the caller is going to have to check.
return result;
}
};
#endif // SHARE_VM_CLASSFILE_CLASSLOADERDATA_HPP
| 411 | 0.923888 | 1 | 0.923888 | game-dev | MEDIA | 0.364008 | game-dev | 0.731319 | 1 | 0.731319 |
microsoft/Mesh-processing-library | 1,239 | libHh/BoundingSphere.h | // -*- C++ -*- Copyright (c) Microsoft Corporation; see license.txt
#pragma once
#include "Geometry.h"
namespace hh {
struct BoundingSphere {
Point point;
float radius;
friend std::ostream& operator<<(std::ostream& os, const BoundingSphere& bsphere) {
return os << "BoundingSphere(point=" << bsphere.point << ", radius=" << bsphere.radius << ")";
}
};
inline BoundingSphere bsphere_union(const BoundingSphere& bsphere1, const BoundingSphere& bsphere2) {
float d = dist(bsphere1.point, bsphere2.point);
if (bsphere1.radius>=d+bsphere2.radius) {
return bsphere1;
} else if (bsphere2.radius>=d+bsphere1.radius) {
return bsphere2;
} else {
// (from above, d obviously cannot be zero)
float newradius = (bsphere1.radius+bsphere2.radius+d)*0.5f;
// point==interp(bsphere1.point, bsphere2.point, b1) where r1+(1-b1)*d==r2+(b1)*d
// therefore b1 = ((r1-r2)/d+1)/2
float b1 = ((bsphere1.radius-bsphere2.radius)/d+1.f)*0.5f;
ASSERTX(b1>=0.f && b1<=1.f);
BoundingSphere bsphere;
bsphere.point = interp(bsphere1.point, bsphere2.point, b1);
bsphere.radius = newradius;
return bsphere;
}
}
} // namespace hh
| 411 | 0.569674 | 1 | 0.569674 | game-dev | MEDIA | 0.131662 | game-dev | 0.84542 | 1 | 0.84542 |
SHNecro/ShanghaiJAR | 4,820 | ShanghaiEXE/Chip/DarkReygun.cs | using NSAttack;
using NSBattle;
using NSBattle.Character;
using NSShanghaiEXE.InputOutput.Audio;
using NSShanghaiEXE.InputOutput.Rendering;
using NSEffect;
using Common.Vectors;
using System.Drawing;
namespace NSChip
{
internal class DarkReygun : ChipBase
{
private const int shotend = 28;
public DarkReygun(IAudioEngine s)
: base(s)
{
this.rockOnPoint = new Point(-3, 0);
this.number = 255;
this.name = NSGame.ShanghaiEXE.Translate("Chip.DarkReygunName");
this.element = ChipBase.ELEMENT.normal;
this.power = 250;
this.subpower = 0;
this.regsize = 99;
this.reality = 5;
this.dark = true;
this._break = false;
this.powerprint = true;
this.code[0] = ChipFolder.CODE.C;
this.code[1] = ChipFolder.CODE.C;
this.code[2] = ChipFolder.CODE.C;
this.code[3] = ChipFolder.CODE.C;
var information = NSGame.ShanghaiEXE.Translate("Chip.DarkReygunDesc");
this.information[0] = information[0];
this.information[1] = information[1];
this.information[2] = information[2];
this.Init();
}
public override void HaveUpdate(CharacterBase character)
{
this.power = 250 + (character.HpMax - character.Hp);
if (this.power > 500)
this.power = 500;
base.HaveUpdate(character);
}
public override void Action(CharacterBase character, SceneBattle battle)
{
if (character.waittime < 5)
character.animationpoint = new Point(4, 0);
else if (character.waittime < 15)
character.animationpoint = new Point(5, 0);
else if (character.waittime < 28)
{
character.animationpoint = new Point(6, 0);
if (character.waittime < 17)
character.positionDirect.X -= (character.waittime - 15) * this.UnionRebirth(character.union);
}
else if (character.waittime < 33)
{
character.animationpoint = new Point(5, 0);
character.PositionDirectSet();
}
else if (character.waittime == 33)
base.Action(character, battle);
if (character.waittime == 18)
{
this.ShakeStart(5, 5);
this.sound.PlaySE(SoundEffect.bombmiddle);
battle.effects.Add(new BulletBigShells(this.sound, battle, character.position, character.positionDirect.X + 4 * character.UnionRebirth, character.positionDirect.Y, 26, character.union, 20 + this.Random.Next(20), 2, 0));
}
if (character.waittime != 20)
return;
this.HaveUpdate(character);
character.parent.attacks.Add(this.Paralyze(new BustorShot(this.sound, character.parent, character.position.X, character.position.Y, character.union, this.Power(character), BustorShot.SHOT.canon, this.element, false, 0)));
}
public override void GraphicsRender(
IRenderer dg,
Vector2 p,
int c,
bool printgraphics,
bool printstatus)
{
if (printgraphics)
{
this._rect = new Rectangle(0, 0, 56, 48);
dg.DrawImage(dg, "chipgraphic13", this._rect, true, p, Color.White);
}
base.GraphicsRender(dg, p, c, printgraphics, printstatus);
}
public override void IconRender(
IRenderer dg,
Vector2 p,
bool select,
bool custom,
int c,
bool noicon)
{
if (!noicon)
{
int x = 496;
int num1 = 64;
int num2 = this.number - 1;
int num3 = num2 % 40;
int num4 = num2 / 40;
int num5 = 0;
if (select)
num5 = 1;
this._rect = new Rectangle(x, num1 + num5 * 96, 16, 16);
dg.DrawImage(dg, "chipicon", this._rect, true, p, Color.White);
}
base.IconRender(dg, p, select, custom, c, noicon);
}
public override void Render(IRenderer dg, CharacterBase character)
{
if (character.waittime < 5)
return;
this._rect = new Rectangle(1080, 0, character.Wide, character.Height);
this._position = new Vector2(character.positionDirect.X + Shake.X, character.positionDirect.Y + Shake.Y);
if (character.waittime < 10)
this._rect.X = 0;
else if (character.waittime >= 15 && character.waittime < 28)
this._position.X -= 2 * this.UnionRebirth(character.union);
dg.DrawImage(dg, "weapons", this._rect, false, this._position, character.union == Panel.COLOR.blue, Color.White);
if (character.waittime >= 10 && character.waittime < 28)
{
this._position = character.positionDirect;
this._position.X += 24 * this.UnionRebirth(character.union);
this._position.Y += 14f;
this._rect = new Rectangle((character.waittime - 10) / 3 * 64, 32, 64, 64);
dg.DrawImage(dg, "shot", this._rect, false, this._position, character.union == Panel.COLOR.blue, Color.White);
}
}
}
}
| 411 | 0.906799 | 1 | 0.906799 | game-dev | MEDIA | 0.966754 | game-dev | 0.959321 | 1 | 0.959321 |
MobileUO/MobileUO | 7,587 | Assets/Scripts/ClassicUO/src/Game/UI/Controls/ItemGump.cs | #region license
// Copyright (C) 2020 ClassicUO Development Community on Github
//
// This project is an alternative client for the game Ultima Online.
// The goal of this is to develop a lightweight client considering
// new technologies.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#endregion
using System;
using ClassicUO.Configuration;
using ClassicUO.Game.GameObjects;
using ClassicUO.Game.Managers;
using ClassicUO.Game.Scenes;
using ClassicUO.Game.UI.Gumps;
using ClassicUO.Input;
using ClassicUO.Renderer;
using ClassicUO.Game.Data;
using Microsoft.Xna.Framework;
using ClassicUO.IO.Resources;
namespace ClassicUO.Game.UI.Controls
{
internal class ItemGump : StaticPic
{
public ItemGump(uint serial, ushort graphic, ushort hue, int x, int y) : base(graphic, hue)
{
AcceptMouseInput = true;
X = (short) x;
Y = (short) y;
HighlightOnMouseOver = true;
CanPickUp = true;
LocalSerial = serial;
WantUpdateSize = false;
CanMove = false;
SetTooltip(serial);
}
public bool HighlightOnMouseOver { get; set; }
public bool CanPickUp { get; set; }
public static bool PixelCheck = false;
public override void Update(double totalMS, double frameMS)
{
if (IsDisposed)
return;
base.Update(totalMS, frameMS);
if (World.InGame)
{
if (CanPickUp && !ItemHold.Enabled && Mouse.LButtonPressed &&
UIManager.LastControlMouseDown(MouseButtonType.Left) == this &&
((Mouse.LastLeftButtonClickTime != 0xFFFF_FFFF && Mouse.LastLeftButtonClickTime != 0 && Mouse.LastLeftButtonClickTime + Mouse.MOUSE_DELAY_DOUBLE_CLICK < Time.Ticks) ||
CanPickup()))
{
AttempPickUp();
}
else if (MouseIsOver)
{
SelectedObject.Object = World.Get(LocalSerial);
}
}
}
public override bool Draw(UltimaBatcher2D batcher, int x, int y)
{
if (IsDisposed)
return false;
base.Draw(batcher, x, y);
ResetHueVector();
ShaderHuesTraslator.GetHueVector(ref _hueVector, HighlightOnMouseOver && MouseIsOver ? 0x0035 : Hue, IsPartialHue, 0, false);
var texture = ArtLoader.Instance.GetTexture(Graphic);
if (texture != null)
{
batcher.Draw2D(texture, x, y, Width, Height, ref _hueVector);
Item item = World.Items.Get(LocalSerial);
if (item != null && !item.IsMulti && !item.IsCoin && item.Amount > 1 && item.ItemData.IsStackable)
{
batcher.Draw2D(texture, x + 5, y + 5, Width, Height, ref _hueVector);
}
}
return true;
}
public override bool Contains(int x, int y)
{
var texture = ArtLoader.Instance.GetTexture(Graphic);
if (texture == null)
{
return false;
}
if (ProfileManager.Current != null && ProfileManager.Current.ScaleItemsInsideContainers)
{
float scale = UIManager.ContainerScale;
x = (int)(x / scale);
y = (int)(y / scale);
}
if (texture.Contains(x, y, PixelCheck))
{
return true;
}
Item item = World.Items.Get(LocalSerial);
if (item != null && !item.IsCoin && item.Amount > 1 && item.ItemData.IsStackable)
{
if (texture.Contains(x - 5, y - 5, PixelCheck))
{
return true;
}
}
return false;
}
protected override void OnMouseUp(int x, int y, MouseButtonType button)
{
SelectedObject.Object = World.Get(LocalSerial);
base.OnMouseUp(x, y, button);
}
protected override void OnMouseOver(int x, int y)
{
SelectedObject.Object = World.Get(LocalSerial);
}
private bool CanPickup()
{
Point offset = Mouse.LDroppedOffset;
if (Math.Abs(offset.X) < Constants.MIN_PICKUP_DRAG_DISTANCE_PIXELS &&
Math.Abs(offset.Y) < Constants.MIN_PICKUP_DRAG_DISTANCE_PIXELS)
return false;
var split = UIManager.GetGump<SplitMenuGump>(LocalSerial);
if (split == null)
return true;
split.X = Mouse.Position.X - 80;
split.Y = Mouse.Position.Y - 40;
UIManager.AttemptDragControl(split, Mouse.Position, true);
split.BringOnTop();
return false;
}
protected override bool OnMouseDoubleClick(int x, int y, MouseButtonType button)
{
if (button != MouseButtonType.Left || TargetManager.IsTargeting)
return false;
Item item = World.Items.Get(LocalSerial);
Item container;
if ( !Input.Keyboard.Ctrl &&
ProfileManager.Current.DoubleClickToLootInsideContainers &&
item != null && !item.IsDestroyed &&
!item.ItemData.IsContainer && item.IsEmpty &&
(container = World.Items.Get(item.RootContainer)) != null &&
container != World.Player.FindItemByLayer(Layer.Backpack)
)
{
GameActions.GrabItem(LocalSerial, item.Amount);
}
else
{
GameActions.DoubleClick(LocalSerial);
}
return true;
}
private void AttempPickUp()
{
if (CanPickUp)
{
Rectangle bounds = ArtLoader.Instance.GetTexture(Graphic).Bounds;
int centerX = bounds.Width >> 1;
int centerY = bounds.Height >> 1;
if (ProfileManager.Current != null && ProfileManager.Current.ScaleItemsInsideContainers)
{
float scale = UIManager.ContainerScale;
centerX = (int) (centerX * scale);
centerY = (int) (centerY * scale);
}
if (ProfileManager.Current != null && ProfileManager.Current.RelativeDragAndDropItems)
{
Point p = new Point(centerX - (Mouse.Position.X - ScreenCoordinateX), centerY - (Mouse.Position.Y - ScreenCoordinateY));
GameActions.PickUp(LocalSerial, centerX, centerY, offset: p);
}
else
{
GameActions.PickUp(LocalSerial, centerX, centerY);
}
}
}
}
}
| 411 | 0.954893 | 1 | 0.954893 | game-dev | MEDIA | 0.787673 | game-dev,desktop-app | 0.964101 | 1 | 0.964101 |
Moulberry/Lattice | 1,298 | src/common/main/java/com/moulberry/lattice/Lattice.java | package com.moulberry.lattice;
import com.moulberry.lattice.element.LatticeElement;
import com.moulberry.lattice.element.LatticeElements;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
public class Lattice {
public static Screen createConfigScreen(LatticeElements elements, @Nullable Runnable onClosed, @Nullable Screen closeTo) {
return new LatticeConfigScreen(elements, onClosed, closeTo);
}
public static void performTest(LatticeElements elements) {
performWidgetTest(elements);
Screen screen = createConfigScreen(elements, null, null);
screen.init(Minecraft.getInstance(), 480, 270);
}
private static void performWidgetTest(LatticeElements elements) {
Font font = Minecraft.getInstance().font;
for (LatticeElement option : elements.options) {
option.createInnerWidget(font, Component.literal("Title"), null, 100);
}
for (LatticeElements subcategory : elements.subcategories) {
performWidgetTest(subcategory);
}
}
}
| 411 | 0.605811 | 1 | 0.605811 | game-dev | MEDIA | 0.981002 | game-dev | 0.683519 | 1 | 0.683519 |
CalamityTeam/CalamityModPublic | 1,210 | Items/Armor/GemTech/GemTechSchynbaulds.cs | using System.Collections.Generic;
using CalamityMod.Items.Materials;
using CalamityMod.Rarities;
using CalamityMod.Tiles.Furniture.CraftingStations;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Items.Armor.GemTech
{
[AutoloadEquip(EquipType.Legs)]
public class GemTechSchynbaulds : ModItem, ILocalizedModType
{
public new string LocalizationCategory => "Items.Armor.PostMoonLord";
public override void SetDefaults()
{
Item.width = 28;
Item.height = 26;
Item.defense = 24;
Item.value = CalamityGlobalItem.RarityVioletBuyPrice;
Item.rare = ModContent.RarityType<Violet>();
Item.Calamity().donorItem = true;
}
public override void ModifyTooltips(List<TooltipLine> tooltips) => GemTechHeadgear.ModifySetTooltips(this, tooltips);
public override void AddRecipes()
{
CreateRecipe().
AddIngredient<ExoPrism>(12).
AddIngredient<GalacticaSingularity>(4).
AddIngredient<CoreofCalamity>(2).
AddTile<DraedonsForge>().
Register();
}
}
}
| 411 | 0.594642 | 1 | 0.594642 | game-dev | MEDIA | 0.992059 | game-dev | 0.687108 | 1 | 0.687108 |
WCell/WCell | 6,104 | Services/WCell.RealmServer/RacesClasses/ArchetypeMgr.cs | using System;
using System.Collections.Generic;
using WCell.Constants;
using WCell.Core;
using WCell.Core.DBC;
using WCell.Core.Initialization;
using WCell.RealmServer.Content;
using WCell.RealmServer.Items;
using WCell.RealmServer.Spells;
namespace WCell.RealmServer.RacesClasses
{
public static class ArchetypeMgr
{
#region Fields
static readonly Func<BaseClass>[] ClassCreators = new Func<BaseClass>[WCellConstants.ClassTypeLength];
internal static BaseClass CreateClass(ClassId id)
{
return ClassCreators[(int)id]();
}
/// <summary>
/// Use Archetypes for any customizations.
/// </summary>
internal static readonly BaseClass[] BaseClasses = new BaseClass[WCellConstants.ClassTypeLength + 20];
/// <summary>
/// Use Archetypes for any customizations.
/// </summary>
internal static readonly BaseRace[] BaseRaces = new BaseRace[WCellConstants.RaceTypeLength + 20];
/// <summary>
/// Use Archetype objects to customize basic settings.
/// Index: [class][race]
/// </summary>
public static readonly Archetype[][] Archetypes = new Archetype[WCellConstants.ClassTypeLength][];
#endregion
#region Getters
/// <summary>
/// Returns the Class with the given type
/// </summary>
public static BaseClass GetClass(ClassId id)
{
return (uint)id >= BaseClasses.Length ? null : BaseClasses[(uint)id];
}
/// <summary>
/// Returns the Race with the given type
/// </summary>
public static BaseRace GetRace(RaceId id)
{
return (uint)id >= BaseRaces.Length ? null : BaseRaces[(uint)id];
}
/// <summary>
/// Returns the corresponding <see cref="Archetype"/>.
/// </summary>
/// <exception cref="NullReferenceException">If Archetype does not exist</exception>
public static Archetype GetArchetypeNotNull(RaceId race, ClassId clss)
{
Archetype type;
if ((uint)clss >= WCellConstants.ClassTypeLength || (uint)race >= WCellConstants.RaceTypeLength ||
((type = Archetypes[(uint)clss][(uint)race]) == null))
{
throw new ArgumentException(string.Format("Archetype \"{0} {1}\" does not exist.", race, clss));
}
return type;
}
public static Archetype GetArchetype(RaceId race, ClassId clssId)
{
if ((uint)clssId >= WCellConstants.ClassTypeLength || (uint)race >= WCellConstants.RaceTypeLength)
{
return null;
}
var clss = Archetypes[(uint)clssId];
return clss != null ? clss[(uint)race] : null;
}
/// <summary>
/// Returns all archetypes with the given race/class combination.
/// 0 for race or class means all.
/// </summary>
/// <returns></returns>
public static List<Archetype> GetArchetypes(RaceId race, ClassId clss)
{
if ((uint)clss >= WCellConstants.ClassTypeLength || (uint)race >= WCellConstants.RaceTypeLength)
{
return null;
}
var list = new List<Archetype>();
if (clss == 0)
{
// applies to all classes
foreach (var raceArchetypes in Archetypes)
{
if (raceArchetypes != null)
{
if (race == 0)
{
// applies to all classes and races
foreach (var archetype in raceArchetypes)
{
if (archetype != null)
{
list.Add(archetype);
}
}
}
else
{
if (raceArchetypes[(uint)race] != null)
{
list.Add(raceArchetypes[(uint)race]);
}
}
}
}
}
else
{
if (race == 0)
{
// applies to all races
foreach (var archetype in Archetypes[(uint)clss])
{
if (archetype != null)
{
list.Add(archetype);
}
}
}
else
{
// just one
if (Archetypes[(uint)clss][(uint)race] != null)
{
list.Add(Archetypes[(uint)clss][(uint)race]);
}
}
}
if (list.Count == 0)
{
return null;
}
return list;
}
#endregion
#region Init
static ArchetypeMgr()
{
for (var c = 0; c < Archetypes.Length; c++)
{
Archetypes[c] = new Archetype[WCellConstants.RaceTypeLength];
}
}
public static void EnsureInitialize()
{
if (ClassCreators[(int)ClassId.Warrior] == null)
{
Initialize();
}
}
/// <summary>
/// Note: This step is depending on Skills, Spells and WorldMgr
/// </summary>
[Initialization(InitializationPass.Seventh, "Initializing Races and Classes")]
public static void Initialize()
{
if (!loaded)
{
InitClasses();
InitRaces();
ContentMgr.Load<ClassLevelSetting>();
ContentMgr.Load<Archetype>();
ContentMgr.Load<PlayerSpellEntry>();
//ContentHandler.Load<PlayerSkillEntry>();
ContentMgr.Load<PlayerActionButtonEntry>();
ContentMgr.Load<LevelStatInfo>();
if (ItemMgr.Loaded)
{
LoadItems();
}
for (var i = 0; i < SpellLines.SpellLinesByClass.Length; i++)
{
var lines = SpellLines.SpellLinesByClass[i];
if (lines == null) continue;
var clss = GetClass((ClassId)i);
if (clss != null)
{
clss.SpellLines = lines;
}
}
loaded = true;
}
}
private static void InitClasses()
{
AddClass(new WarriorClass());
AddClass(new PaladinClass());
AddClass(new HunterClass());
AddClass(new RogueClass());
AddClass(new PriestClass());
AddClass(new DeathKnightClass());
AddClass(new ShamanClass());
AddClass(new MageClass());
AddClass(new WarlockClass());
AddClass(new DruidClass());
}
private static void AddClass(BaseClass clss)
{
BaseClasses[(int)clss.Id] = clss;
}
private static void InitRaces()
{
//ContentHandler.Load<BaseRace>();
var reader = new ListDBCReader<BaseRace, DBCRaceConverter>(RealmServerConfiguration.GetDBCFile(WCellConstants.DBC_CHRRACES));
foreach (var race in reader.EntryList)
{
race.FinalizeAfterLoad();
}
}
private static bool loaded;
public static bool Loaded
{
get { return loaded; }
}
public static void LoadItems()
{
// ContentHandler.Load<PlayerItemEntry>();
//var reader =
new DBCReader<DBCStartOutfitConverter>(
RealmServerConfiguration.GetDBCFile(WCellConstants.DBC_CHARSTARTOUTFIT));
}
#endregion
}
} | 411 | 0.885913 | 1 | 0.885913 | game-dev | MEDIA | 0.580251 | game-dev | 0.906767 | 1 | 0.906767 |
fortressforever/fortressforever | 4,720 | cl_dll/ff/ff_hud_location.cpp | // =============== Fortress Forever ==============
// ======== A modification for Half-Life 2 =======
//
// @file ff_hud_location.cpp
// @author Patrick O'Leary (Mulchman)
// @date 02/20/2006
// @brief client side Hud Location Info
//
// REVISIONS
// ---------
// 02/20/2006, Mulchman:
// First created
#include "cbase.h"
#include "hudelement.h"
#include "hud_macros.h"
#include "iclientmode.h"
#include "view.h"
using namespace vgui;
#include <vgui_controls/Panel.h>
#include <vgui_controls/Frame.h>
#include <vgui/IScheme.h>
#include <vgui/ISurface.h>
#include <vgui/ILocalize.h>
#include <vgui/IVGui.h>
#include "c_ff_player.h"
#include "ff_utils.h"
#include "ff_panel.h"
int g_iHudLocation2Pos = 0;
//=============================================================================
//
// class CHudLocation
//
//=============================================================================
class CHudLocation : public CHudElement, public vgui::FFPanel
{
private:
DECLARE_CLASS_SIMPLE( CHudLocation, vgui::FFPanel );
public:
CHudLocation( const char *pElementName ) : vgui::FFPanel( NULL, "HudLocation" ), CHudElement( pElementName )
{
SetParent(g_pClientMode->GetViewport());
SetHiddenBits(HIDEHUD_PLAYERDEAD | HIDEHUD_SPECTATING | HIDEHUD_UNASSIGNED);
}
~CHudLocation( void ) {}
void Init( void );
void VidInit( void );
void Paint( void );
void MsgFunc_SetPlayerLocation( bf_read &msg );
protected:
wchar_t m_pText[ 1024 ]; // Unicode text buffer
int m_iTeam;
private:
// Stuff we need to know
CPanelAnimationVar( vgui::HFont, m_hTextFont, "TextFont", "Default" );
CPanelAnimationVarAliasType( float, text1_xpos, "text1_xpos", "8", "proportional_float" );
CPanelAnimationVarAliasType( float, text1_ypos, "text1_ypos", "20", "proportional_float" );
};
DECLARE_HUDELEMENT( CHudLocation );
DECLARE_HUD_MESSAGE( CHudLocation, SetPlayerLocation );
void CHudLocation::Init( void )
{
HOOK_HUD_MESSAGE( CHudLocation, SetPlayerLocation );
m_pText[ 0 ] = '\0';
}
void CHudLocation::VidInit( void )
{
SetPaintBackgroundEnabled( true );
m_pText[ 0 ] = '\0'; // Bug 0000293: clear location text buffer on map change
g_iHudLocation2Pos = 0;
}
void CHudLocation::MsgFunc_SetPlayerLocation( bf_read &msg )
{
char szString[ 1024 ];
msg.ReadString( szString, sizeof( szString ) );
m_iTeam = msg.ReadShort();
wchar_t *pszTemp = vgui::localize()->Find( szString );
if( pszTemp )
wcscpy( m_pText, pszTemp );
else
vgui::localize()->ConvertANSIToUnicode( szString, m_pText, sizeof( m_pText ) );
//DevMsg( "[Location] Team: %i, String: %s\n", iTeam, szString );
}
void CHudLocation::Paint( void )
{
if( g_iHudLocation2Pos == 0 )
{
// We do a bit of hackery here... location block takes a total
// of 4 glyphs spanning 2 different c++ classes. So, we offset
// the 2nd location class from the first location's class
// position so they can be RIGHT next to each other.
if( m_pHudForeground )
{
int x, y;
GetPos( x, y );
vgui::Panel *pParent = g_pClientMode->GetViewport();
int newX = 1.3f * ((float)pParent->GetTall() / (float)480);
//g_iHudLocation2Pos = x + m_pHudForeground->Width() - scheme()->GetProportionalScaledValue( 1 );
g_iHudLocation2Pos = x + m_pHudForeground->Width() - 2 + newX ;
}
}
if( m_pText )
{
surface()->DrawSetTextFont( m_hTextFont );
Color cColor;
SetColorByTeam( m_iTeam, cColor );
surface()->DrawSetTextColor( cColor.r(), cColor.g(), cColor.b(), 255 );
surface()->DrawSetTextPos( text1_xpos, text1_ypos );
for( wchar_t *wch = m_pText; *wch != 0; wch++ )
surface()->DrawUnicodeChar( *wch );
}
BaseClass::Paint();
}
//=============================================================================
//
// class CHudLocation2
//
//=============================================================================
class CHudLocation2 : public CHudElement, public vgui::FFPanel
{
private:
DECLARE_CLASS_SIMPLE( CHudLocation2, vgui::FFPanel );
public:
CHudLocation2( const char *pElementName ) : vgui::FFPanel( NULL, "HudLocation2" ), CHudElement( pElementName )
{
SetParent(g_pClientMode->GetViewport());
SetHiddenBits(HIDEHUD_PLAYERDEAD | HIDEHUD_SPECTATING | HIDEHUD_UNASSIGNED);
}
~CHudLocation2( void ) {}
void Init( void );
void VidInit( void );
void Paint( void );
private:
bool m_bSetup;
};
DECLARE_HUDELEMENT( CHudLocation2 );
void CHudLocation2::Init( void )
{
}
void CHudLocation2::VidInit( void )
{
SetPaintBackgroundEnabled( true );
m_bSetup = false;
}
void CHudLocation2::Paint( void )
{
if( g_iHudLocation2Pos == 0 )
return;
if( !m_bSetup )
{
int x, y;
GetPos( x, y );
SetPos( g_iHudLocation2Pos, y );
m_bSetup = true;
}
BaseClass::Paint();
}
| 411 | 0.913208 | 1 | 0.913208 | game-dev | MEDIA | 0.705858 | game-dev | 0.714112 | 1 | 0.714112 |
Dimbreath/AzurLaneData | 2,333 | en-US/model/vo/chaptercell.lua | slot0 = class("ChapterCell")
function slot0.Ctor(slot0, slot1)
slot0.walkable = true
slot0.forbiddenDirections = ChapterConst.ForbiddenNone
slot0.row = slot1.pos.row
slot0.column = slot1.pos.column
slot0.attachment = slot1.item_type
slot0.attachmentId = slot1.item_id
slot0.flag = slot1.item_flag
slot0.data = slot1.item_data
slot0.trait = ChapterConst.TraitNone
slot0.item = nil
slot0.itemOffset = nil
slot0.flagList = {}
for slot5, slot6 in ipairs(slot1.flag_list or {}) do
table.insert(slot0.flagList, slot6)
end
end
function slot0.updateFlagList(slot0, slot1)
slot0.flagList = slot0.flagList or {}
table.clear(slot0.flagList)
for slot5, slot6 in ipairs(slot1.flag_list) do
table.insert(slot0.flagList, slot6)
end
end
function slot0.GetFlagList(slot0)
return slot0.flagList
end
function slot0.GetWeatherFlagList(slot0)
return _.filter(slot0:GetFlagList(), function (slot0)
return tobool(pg.weather_data_template[slot0])
end)
end
function slot0.checkHadFlag(slot0, slot1)
return table.contains(slot0.flagList, slot1)
end
function slot0.Line2Name(slot0, slot1)
return "chapter_cell_" .. slot0 .. "_" .. slot1
end
function slot0.Line2QuadName(slot0, slot1)
return "chapter_cell_quad_" .. slot0 .. "_" .. slot1
end
function slot0.Line2MarkName(slot0, slot1, slot2)
return "chapter_cell_mark_" .. slot0 .. "_" .. slot1 .. "#" .. slot2
end
function slot0.MinMaxLine2QuadName(slot0, slot1, slot2, slot3)
return "chapter_cell_quad_" .. slot0 .. "_" .. slot1 .. "_" .. slot2 .. "_" .. slot3
end
function slot0.Line2RivalName(slot0, slot1, slot2)
return "rival_" .. slot1 .. "_" .. slot2
end
function slot0.LineAround(slot0, slot1, slot2)
slot3 = {}
for slot7 = -slot2, slot2 do
for slot11 = -slot2, slot2 do
if slot2 >= math.abs(slot7) + math.abs(slot11) then
table.insert(slot3, {
row = slot0 + slot7,
column = slot1 + slot11
})
end
end
end
return slot3
end
function slot0.SetWalkable(slot0, slot1)
slot0.walkable = tobool(slot1)
if type(slot1) == "boolean" then
slot0.forbiddenDirections = slot1 and ChapterConst.ForbiddenNone or ChapterConst.ForbiddenAll
elseif type(slot1) == "number" then
slot0.forbiddenDirections = bit.band(slot1, ChapterConst.ForbiddenAll)
end
end
function slot0.IsWalkable(slot0)
return slot0.walkable
end
return slot0
| 411 | 0.529325 | 1 | 0.529325 | game-dev | MEDIA | 0.906065 | game-dev | 0.805534 | 1 | 0.805534 |
Naton1/osrs-pvp-reinforcement-learning | 2,905 | simulation-rsps/ElvargServer/src/main/java/com/elvarg/net/packet/impl/FollowPlayerPacketListener.java | package com.elvarg.net.packet.impl;
import com.elvarg.game.World;
import com.elvarg.game.entity.impl.player.Player;
import com.elvarg.game.model.Location;
import com.elvarg.game.model.movement.MovementQueue.Mobility;
import com.elvarg.game.model.movement.path.PathFinder;
import com.elvarg.game.task.Task;
import com.elvarg.game.task.TaskManager;
import com.elvarg.game.task.TaskType;
import com.elvarg.net.packet.Packet;
import com.elvarg.net.packet.PacketExecutor;
import com.elvarg.util.TileUtils;
import java.util.Objects;
/**
* Handles the follow player packet listener Sets the player to follow when the
* packet is executed
*
* @author Gabriel Hannason
*/
public class FollowPlayerPacketListener implements PacketExecutor {
@Override
public void execute(Player player, Packet packet) {
if (player.busy()) {
return;
}
/** Required to cancel the follow task **/
TaskManager.cancelTasks(player.getIndex());
int otherPlayersIndex = packet.readLEShort();
if (otherPlayersIndex < 0 || otherPlayersIndex > World.getPlayers().capacity())
return;
Player leader = World.getPlayers().get(otherPlayersIndex);
if (leader == null) {
return;
}
FollowPlayerPacketListener.follow(player, leader);
}
public static void follow(Player player, Player leader) {
Mobility mobility = player.getMovementQueue().getMobility();
if (!mobility.canMove()) {
mobility.sendMessage(player);
player.getMovementQueue().reset();
return;
}
player.getMovementQueue().reset();
player.getMovementQueue().walkToReset();
player.setFollowing(leader);
player.setMobileInteraction(leader);
TaskManager.submit(new Task(1, player.getIndex(), true) {
@Override
protected void execute() {
if (player.getFollowing() == null) {
player.setPositionToFace(null);
stop();
return;
}
if (leader.isTeleporting() || !leader.getLocation().isWithinDistance(player.getLocation(), 15)) {
player.setPositionToFace(null);
stop();
return;
}
int destX = leader.getMovementQueue().followX;
int destY = leader.getMovementQueue().followY;
if (Objects.equals(new Location(destX, destY), player.getLocation()) || destX == -1 && destY == -1) {
return;
}
player.getMovementQueue().reset();
player.setPositionToFace(leader.getLocation());
player.setMobileInteraction(leader);
PathFinder.calculateWalkRoute(player, destX, destY);
}
});
}
}
| 411 | 0.82236 | 1 | 0.82236 | game-dev | MEDIA | 0.877659 | game-dev | 0.914365 | 1 | 0.914365 |
DarkstarProject/darkstar | 1,569 | scripts/globals/mobskills/fulmination.lua | ---------------------------------------------
-- Fulmination
--
-- Description: Deals heavy magical damage in an area of effect. Additional effect: Paralysis + Stun
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes Shadows
-- Range: 30 yalms
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:getFamily() == 316) then
local mobSkin = mob:getModelId()
if (mobSkin == 1805) then
return 0
else
return 1
end
end
local family = mob:getFamily()
local mobhp = mob:getHPP()
local result = 1
if (family == 168 and mobhp <= 35) then -- Khimaira < 35%
result = 0
elseif (family == 315 and mobhp <= 50) then -- Tyger < 50%
result = 0
end
return result
end
function onMobWeaponSkill(target, mob, skill)
-- TODO: Hits all players near Khimaira, not just alliance.
local dmgmod = 3
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg() * 4,dsp.magic.ele.THUNDER,dmgmod,TP_MAB_BONUS,1)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.LIGHTNING,MOBPARAM_WIPE_SHADOWS)
MobStatusEffectMove(mob,target,dsp.effect.PARALYSIS, 40, 0, 60)
MobStatusEffectMove(mob,target,dsp.effect.STUN, 1, 0, 4)
target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.LIGHTNING)
return dmg
end
| 411 | 0.924992 | 1 | 0.924992 | game-dev | MEDIA | 0.968139 | game-dev | 0.982948 | 1 | 0.982948 |
gameflorist/dunedynasty | 1,067 | src/config.h | /** @file src/config.h Configuration and options load and save definitions. */
#ifndef CONFIG_H
#define CONFIG_H
#include "enum_language.h"
#include "video/video_a5.h"
enum WindowMode {
WM_WINDOWED,
WM_FULLSCREEN,
WM_FULLSCREEN_WINDOW
};
typedef struct GameCfg {
enum WindowMode windowMode;
enum Language language;
int gameSpeed;
bool hints;
bool autoScroll;
bool scrollAlongScreenEdge;
int scrollSpeed;
/* "Right-click orders" control scheme:
* Left -> select, selection box.
* Right -> order, pan.
*
* "Left-click orders" (Dune 2000) control scheme:
* Left -> select/order, selection box.
* Right -> deselect, pan.
*/
bool leftClickOrders;
bool holdControlToZoom;
float panSensitivity;
bool hardwareCursor;
struct DisplayMode displayMode;
} GameCfg;
extern GameCfg g_gameConfig;
extern void Config_GetCampaign(void);
extern void Config_SaveCampaignCompletion(void);
extern void ConfigA5_InitDataDirectoriesAndLoadConfigFile(void);
extern void GameOptions_Load(void);
extern void GameOptions_Save(void);
#endif /* CONFIG_H */
| 411 | 0.789449 | 1 | 0.789449 | game-dev | MEDIA | 0.668007 | game-dev | 0.630268 | 1 | 0.630268 |
leecjson/CocosNet | 3,198 | Cpp/Classes/HelloWorldScene.cpp | #include "HelloWorldScene.h"
GameNetDelegate::GameNetDelegate()
{
}
GameNetDelegate::~GameNetDelegate()
{
}
void GameNetDelegate::onMessageReceived(CCBuffer& oBuffer)
{
CCLOG("onMessageReceived");
switch( oBuffer.readInt() )
{
case 10:
{
CCLOG("%d", oBuffer.readInt());
CCLOG("%d", oBuffer.readShort());
CCLOG("%lld", oBuffer.readLongLong());
CCLOG("%c", oBuffer.readChar());
CCLOG("%f", oBuffer.readFloat());
CCLOG("%lf", oBuffer.readDouble());
CCLOG("%s", oBuffer.readLengthAndString().c_str());
}
break;
case 5:
{
// large data
CCLOG("large data length = %d", oBuffer.length());
}
break;
}
}
void GameNetDelegate::onConnected()
{
CCLOG("onConnected");
}
void GameNetDelegate::onConnectTimeout()
{
CCLOG("onConnectTimeout");
}
void GameNetDelegate::onDisconnected()
{
CCLOG("onDisconnected");
}
void GameNetDelegate::onExceptionCaught(CCSocketStatus eStatus)
{
CCLOG("onExceptionCaught %d", (int)eStatus);
}
void GameNetDelegate::CS_Test()
{
CCBuffer buffer;
buffer.writeInt(10);
buffer.writeLongLong(999999999L);
buffer.writeFloat(77.7f);
buffer.writeDouble(99.9);
buffer.writeChar('h');
buffer.writeLengthAndString("hahahahaha");
this->send(&buffer);
}
void GameNetDelegate::CS_LargePackage()
{
CCBuffer buffer;
buffer.writeInt(5);
this->send(&buffer);
}
bool AlphaScene::init()
{
CCScene::init();
CCMenuItemFont* pConnect = CCMenuItemFont::create("Connect", this, menu_selector(AlphaScene::onConnectClick));
pConnect->setFontSize(30);
pConnect->setPosition(ccp(200, 200));
CCMenuItemFont* pDisconnect = CCMenuItemFont::create("Disconnect", this, menu_selector(AlphaScene::onDisconnectClick));
pDisconnect->setFontSize(30);
pDisconnect->setPosition(ccp(350, 200));
CCMenuItemFont* pLargeData = CCMenuItemFont::create("LargeDataTest", this, menu_selector(AlphaScene::onLargeDataClick));
pLargeData->setFontSize(30);
pLargeData->setPosition(ccp(500, 300));
CCMenuItemFont* pTest = CCMenuItemFont::create("Test", this, menu_selector(AlphaScene::onTestClick));
pTest->setFontSize(30);
pTest->setPosition(ccp(500, 200));
CCMenu* pMenu = CCMenu::create(pConnect, pDisconnect, pTest, pLargeData, NULL);
pMenu->setPosition(CCPointZero);
addChild(pMenu);
//test frame
CCSprite* picon = CCSprite::create("Icon.png");
picon->setPosition(ccp(150, 400));
CCMoveBy* pMoveRight = CCMoveBy::create(0.5f, ccp(500, 0));
CCMoveBy* pMoveLeft = CCMoveBy::create(0.5f, ccp(-500, 0));
CCSequence* pSeq = CCSequence::create(pMoveRight, pMoveLeft, NULL);
picon->runAction(CCRepeatForever::create(pSeq));
addChild(picon);
return true;
}
void AlphaScene::onConnectClick(CCObject* pSender)
{
CCInetAddress oAddres;
oAddres.setIp("192.168.0.100");
oAddres.setPort(7789);
GameNetDelegate::sharedDelegate()->setInetAddress(oAddres);
GameNetDelegate::sharedDelegate()->connect();
}
void AlphaScene::onDisconnectClick(CCObject* pSender)
{
GameNetDelegate::sharedDelegate()->disconnect();
}
void AlphaScene::onTestClick(CCObject* pSender)
{
GameNetDelegate::sharedDelegate()->CS_Test();
}
void AlphaScene::onLargeDataClick(CCObject* pSender)
{
GameNetDelegate::sharedDelegate()->CS_LargePackage();
} | 411 | 0.874532 | 1 | 0.874532 | game-dev | MEDIA | 0.664744 | game-dev,networking | 0.920957 | 1 | 0.920957 |
Aussiemon/Darktide-Source-Code | 5,210 | scripts/extension_systems/behavior/nodes/actions/bt_change_target_action.lua | -- chunkname: @scripts/extension_systems/behavior/nodes/actions/bt_change_target_action.lua
require("scripts/extension_systems/behavior/nodes/bt_node")
local Animation = require("scripts/utilities/animation")
local Blackboard = require("scripts/extension_systems/blackboard/utilities/blackboard")
local MinionMovement = require("scripts/utilities/minion_movement")
local BtChangeTargetAction = class("BtChangeTargetAction", "BtNode")
BtChangeTargetAction.enter = function (self, unit, breed, blackboard, scratchpad, action_data, t)
local locomotion_extension = ScriptUnit.extension(unit, "locomotion_system")
local navigation_extension = ScriptUnit.extension(unit, "navigation_system")
navigation_extension:set_enabled(true, action_data.move_speed or breed.run_speed)
scratchpad.animation_extension = ScriptUnit.extension(unit, "animation_system")
scratchpad.locomotion_extension = locomotion_extension
scratchpad.navigation_extension = navigation_extension
scratchpad.behavior_component = Blackboard.write_component(blackboard, "behavior")
local perception_component = blackboard.perception
scratchpad.target_unit = perception_component.target_unit
local rotation_speed = action_data.rotation_speed
if rotation_speed then
scratchpad.original_rotation_speed = locomotion_extension:rotation_speed()
locomotion_extension:set_rotation_speed(rotation_speed)
end
self:_start_change_target_anim(unit, breed, t, scratchpad, action_data)
end
BtChangeTargetAction.leave = function (self, unit, breed, blackboard, scratchpad, action_data, t, reason, destroy)
if scratchpad.is_anim_driven then
MinionMovement.set_anim_driven(scratchpad, false)
end
local original_rotation_speed = scratchpad.original_rotation_speed
if original_rotation_speed then
scratchpad.locomotion_extension:set_rotation_speed(original_rotation_speed)
end
scratchpad.navigation_extension:set_enabled(false)
end
BtChangeTargetAction.run = function (self, unit, breed, blackboard, scratchpad, action_data, dt, t)
local target_unit = scratchpad.target_unit
if not ALIVE[target_unit] then
return "done"
end
local is_anim_driven = scratchpad.is_anim_driven
if is_anim_driven and scratchpad.change_target_start_rotation_timing and t >= scratchpad.change_target_start_rotation_timing then
local target_position = POSITION_LOOKUP[target_unit]
MinionMovement.update_anim_driven_change_target_rotation(unit, scratchpad, action_data, t, target_position)
end
if scratchpad.change_target_event_anim_speed_duration and t < scratchpad.change_target_event_anim_speed_duration then
local navigation_extension = scratchpad.navigation_extension
MinionMovement.apply_animation_wanted_movement_speed(unit, navigation_extension, dt)
end
local fwd_exit_t = scratchpad.fwd_exit_t
if fwd_exit_t then
local rotate_towards_target_on_fwd = action_data.rotate_towards_target_on_fwd
if rotate_towards_target_on_fwd then
local flat_rotation = MinionMovement.rotation_towards_unit_flat(unit, target_unit)
scratchpad.locomotion_extension:set_wanted_rotation(flat_rotation)
end
if fwd_exit_t < t then
scratchpad.fwd_exit_t = nil
end
end
local is_changing_target = is_anim_driven or scratchpad.fwd_exit_t
if not is_changing_target then
return "done"
end
return "running"
end
BtChangeTargetAction._start_change_target_anim = function (self, unit, breed, t, scratchpad, action_data)
local target_unit = scratchpad.target_unit
local target_position = POSITION_LOOKUP[target_unit]
local moving_direction_name = MinionMovement.get_change_target_direction(unit, target_position)
scratchpad.moving_direction_name = moving_direction_name
local change_target_anim_events = action_data.change_target_anim_events[moving_direction_name]
local change_target_anim_event = Animation.random_event(change_target_anim_events)
local animation_extension = scratchpad.animation_extension
animation_extension:anim_event(change_target_anim_event)
if moving_direction_name ~= "fwd" then
MinionMovement.set_anim_driven(scratchpad, true)
local change_target_rotation_timings = action_data.change_target_rotation_timings
local change_target_start_rotation_timing = change_target_rotation_timings[change_target_anim_event]
scratchpad.change_target_start_rotation_timing = t + change_target_start_rotation_timing
scratchpad.change_target_anim_event_name = change_target_anim_event
else
scratchpad.change_target_start_rotation_timing = nil
scratchpad.change_target_anim_event_name = nil
scratchpad.fwd_exit_t = t + (action_data.change_target_rotation_durations[change_target_anim_event] or 0)
end
local change_target_event_anim_speed_duration = action_data.change_target_event_anim_speed_durations and action_data.change_target_event_anim_speed_durations[change_target_anim_event]
if change_target_event_anim_speed_duration then
scratchpad.change_target_event_anim_speed_duration = t + change_target_event_anim_speed_duration
end
local behavior_component = scratchpad.behavior_component
if not action_data.dont_set_moving_move_state then
behavior_component.move_state = "moving"
else
behavior_component.move_state = "idle"
end
end
return BtChangeTargetAction
| 411 | 0.915054 | 1 | 0.915054 | game-dev | MEDIA | 0.857419 | game-dev | 0.965449 | 1 | 0.965449 |
stride3d/stride | 1,060 | samples/Graphics/SpriteStudioDemo/SpriteStudioDemo.Game/BeamScript.cs | // Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System.Threading.Tasks;
using Stride.Engine;
using Stride.Physics;
namespace SpriteStudioDemo
{
public class BeamScript : AsyncScript
{
private const float maxWidthX = 8f + 2f;
private const float minWidthX = -8f - 2f;
private bool dead;
public void Die()
{
dead = true;
}
public override async Task Execute()
{
while(Game.IsRunning)
{
await Script.NextFrame();
if ((Entity.Transform.Position.X <= minWidthX) || (Entity.Transform.Position.X >= maxWidthX) || dead)
{
SceneSystem.SceneInstance.RootScene.Entities.Remove(Entity);
return;
}
}
}
}
}
| 411 | 0.626539 | 1 | 0.626539 | game-dev | MEDIA | 0.892891 | game-dev | 0.821072 | 1 | 0.821072 |
Jannyboy11/InvSee-plus-plus | 5,452 | InvSee++_Platforms/Impl_1_12_2_R1/src/main/java/com/janboerman/invsee/spigot/impl_1_12_R1/KnownPlayersProvider.java | package com.janboerman.invsee.spigot.impl_1_12_R1;
import com.janboerman.invsee.spigot.api.OfflinePlayerProvider;
import static com.janboerman.invsee.spigot.impl_1_12_R1.HybridServerSupport.getPlayerDir;
import com.janboerman.invsee.spigot.api.Scheduler;
import com.janboerman.invsee.spigot.internal.PlayerFileHelper;
import com.janboerman.invsee.utils.StringHelper;
import static com.janboerman.invsee.spigot.internal.NBTConstants.*;
import net.minecraft.server.v1_12_R1.NBTCompressedStreamTools;
import net.minecraft.server.v1_12_R1.NBTTagCompound;
import net.minecraft.server.v1_12_R1.ReportedException;
import net.minecraft.server.v1_12_R1.WorldNBTStorage;
import org.bukkit.craftbukkit.v1_12_R1.CraftServer;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.logging.Level;
public class KnownPlayersProvider implements OfflinePlayerProvider {
private final Plugin plugin;
private final Scheduler scheduler;
public KnownPlayersProvider(Plugin plugin, Scheduler scheduler) {
this.plugin = plugin;
this.scheduler = scheduler;
}
@Override
public void getAll(final Consumer<String> result) {
CraftServer craftServer = (CraftServer) plugin.getServer();
WorldNBTStorage worldNBTStorage = (WorldNBTStorage) craftServer.getHandle().playerFileData;
File playerDirectory = getPlayerDir(worldNBTStorage);
if (!playerDirectory.exists() || !playerDirectory.isDirectory())
return;
File[] playerFiles = playerDirectory.listFiles((directory, fileName) -> PlayerFileHelper.isPlayerSaveFile(fileName));
for (File playerFile : playerFiles) {
try {
readName(result, playerFile);
} catch (IOException | ReportedException e1) {
//did not work, try again on main thread:
UUID playerId = uuidFromFileName(playerFile.getName());
Executor executor = playerId == null ? scheduler::executeSyncGlobal : runnable -> scheduler.executeSyncPlayer(playerId, runnable, null);
executor.execute(() -> {
try {
readName(result, playerFile);
} catch (IOException | ReportedException e2) {
e2.addSuppressed(e1);
plugin.getLogger().log(Level.WARNING, "Error reading player's save file " + playerFile.getAbsolutePath(), e2);
}
});
}
}
}
@Override
public void getWithPrefix(final String prefix, final Consumer<String> result) {
CraftServer craftServer = (CraftServer) plugin.getServer();
WorldNBTStorage worldNBTStorage = (WorldNBTStorage) craftServer.getHandle().playerFileData;
File playerDirectory = worldNBTStorage.getPlayerDir();
if (!playerDirectory.exists() || !playerDirectory.isDirectory())
return;
File[] playerFiles = playerDirectory.listFiles((directory, fileName) -> PlayerFileHelper.isPlayerSaveFile(fileName));
for (File playerFile : playerFiles) {
try {
readName(prefix, result, playerFile);
} catch (IOException | ReportedException e1) {
//did not work, try again on main thread:
UUID playerId = uuidFromFileName(playerFile.getName());
Executor executor = playerId == null ? scheduler::executeSyncGlobal : runnable -> scheduler.executeSyncPlayer(playerId, runnable, null);
executor.execute(() -> {
try {
readName(prefix, result, playerFile);
} catch (IOException | ReportedException e2) {
e2.addSuppressed(e1);
plugin.getLogger().log(Level.WARNING, "Error reading player's save file " + playerFile.getAbsolutePath(), e2);
}
});
}
}
}
private static UUID uuidFromFileName(String fileName) {
if (fileName == null | fileName.length() < 36) return null;
try {
return UUID.fromString(fileName.substring(0, 36));
} catch (IllegalArgumentException e) {
return null;
}
}
private static void readName(Consumer<String> reader, File playerFile) throws IOException, ReportedException {
String name = readName(playerFile);
if (name != null) {
reader.accept(name);
}
}
private static void readName(String prefix, Consumer<String> reader, File playerFile) throws IOException, ReportedException {
String name = readName(playerFile);
if (name != null && StringHelper.startsWithIgnoreCase(name, prefix)) {
reader.accept(name);
}
}
private static String readName(File playerFile) throws IOException, ReportedException {
NBTTagCompound compound = NBTCompressedStreamTools.a(new FileInputStream(playerFile));
if (compound.hasKeyOfType("bukkit", TAG_COMPOUND)) {
NBTTagCompound bukkit = compound.getCompound("bukkit");
if (bukkit.hasKeyOfType("lastKnownName", TAG_STRING)) {
return bukkit.getString("lastKnownName");
}
}
return null;
}
}
| 411 | 0.974389 | 1 | 0.974389 | game-dev | MEDIA | 0.464242 | game-dev | 0.992819 | 1 | 0.992819 |
AtomicGameEngine/AtomicGameEngine | 3,777 | Source/ThirdParty/Box2D/Box2D/Collision/b2Distance.h |
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_DISTANCE_H
#define B2_DISTANCE_H
#include "Box2D/Common/b2Math.h"
class b2Shape;
/// A distance proxy is used by the GJK algorithm.
/// It encapsulates any shape.
struct b2DistanceProxy
{
b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {}
/// Initialize the proxy using the given shape. The shape
/// must remain in scope while the proxy is in use.
void Set(const b2Shape* shape, int32 index);
/// Get the supporting vertex index in the given direction.
int32 GetSupport(const b2Vec2& d) const;
/// Get the supporting vertex in the given direction.
const b2Vec2& GetSupportVertex(const b2Vec2& d) const;
/// Get the vertex count.
int32 GetVertexCount() const;
/// Get a vertex by index. Used by b2Distance.
const b2Vec2& GetVertex(int32 index) const;
b2Vec2 m_buffer[2];
const b2Vec2* m_vertices;
int32 m_count;
float32 m_radius;
};
/// Used to warm start b2Distance.
/// Set count to zero on first call.
struct b2SimplexCache
{
float32 metric; ///< length or area
uint16 count;
uint8 indexA[3]; ///< vertices on shape A
uint8 indexB[3]; ///< vertices on shape B
};
/// Input for b2Distance.
/// You have to option to use the shape radii
/// in the computation. Even
struct b2DistanceInput
{
b2DistanceProxy proxyA;
b2DistanceProxy proxyB;
b2Transform transformA;
b2Transform transformB;
bool useRadii;
};
/// Output for b2Distance.
struct b2DistanceOutput
{
b2Vec2 pointA; ///< closest point on shapeA
b2Vec2 pointB; ///< closest point on shapeB
float32 distance;
int32 iterations; ///< number of GJK iterations used
};
/// Compute the closest points between two shapes. Supports any combination of:
/// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output.
/// On the first call set b2SimplexCache.count to zero.
void b2Distance(b2DistanceOutput* output,
b2SimplexCache* cache,
const b2DistanceInput* input);
//////////////////////////////////////////////////////////////////////////
inline int32 b2DistanceProxy::GetVertexCount() const
{
return m_count;
}
inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const
{
b2Assert(0 <= index && index < m_count);
return m_vertices[index];
}
inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const
{
int32 bestIndex = 0;
float32 bestValue = b2Dot(m_vertices[0], d);
for (int32 i = 1; i < m_count; ++i)
{
float32 value = b2Dot(m_vertices[i], d);
if (value > bestValue)
{
bestIndex = i;
bestValue = value;
}
}
return bestIndex;
}
inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const
{
int32 bestIndex = 0;
float32 bestValue = b2Dot(m_vertices[0], d);
for (int32 i = 1; i < m_count; ++i)
{
float32 value = b2Dot(m_vertices[i], d);
if (value > bestValue)
{
bestIndex = i;
bestValue = value;
}
}
return m_vertices[bestIndex];
}
#endif
| 411 | 0.82559 | 1 | 0.82559 | game-dev | MEDIA | 0.510223 | game-dev | 0.931997 | 1 | 0.931997 |
riksweeney/edgar | 3,386 | src/item/attractor.c | /*
Copyright (C) 2009-2024 Parallel Realities
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, 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
*/
#include "../headers.h"
#include "../audio/audio.h"
#include "../collisions.h"
#include "../custom_actions.h"
#include "../entity.h"
#include "../geometry.h"
#include "../graphics/animation.h"
#include "../graphics/decoration.h"
#include "../system/error.h"
#include "../system/properties.h"
#include "../system/random.h"
extern Entity *self, player;
static void entityWait(void);
static void addRiftEnergy(int, int);
static void energyMoveToRift(void);
Entity *addAttractor(int x, int y, char *name)
{
Entity *e = getFreeEntity();
if (e == NULL)
{
showErrorAndExit("No free slots to add an Attractor");
}
loadProperties(name, e);
e->x = x;
e->y = y;
e->type = KEY_ITEM;
e->action = &entityWait;
e->touch = &entityTouch;
e->takeDamage = &entityTakeDamageNoFlinch;
e->draw = &drawLoopingAnimationToMap;
setEntityAnimation(e, "STAND");
return e;
}
static void entityWait()
{
EntityList *el, *entities;
entities = getEntities();
setEntityAnimation(self, self->active == FALSE ? "STAND" : "WALK");
if (self->active == TRUE)
{
if (self->health == -1)
{
self->health = playSoundToMap("sound/item/rift", -1, self->x, self->y, -1);
}
self->thinkTime--;
if (self->thinkTime <= 0)
{
for (el=entities->next;el!=NULL;el=el->next)
{
if (el->entity->inUse == TRUE && el->entity->type == ENEMY &&
collision(self->x - self->mental, self->y, self->mental * 2, self->mental * 2, el->entity->x, el->entity->y, el->entity->w, el->entity->h) == 1)
{
setCustomAction(el->entity, &attract, self->maxThinkTime, 0, (el->entity->x < (self->x + self->w / 2) ? self->speed : -self->speed));
}
}
self->thinkTime = self->maxThinkTime;
if (collision(self->x - self->mental, self->y, self->mental * 2, self->mental * 2, player.x, player.y, player.w, player.h) == 1)
{
setCustomAction(&player, &attract, self->maxThinkTime, 0, (player.x < (self->x + self->w / 2) ? self->speed : -self->speed));
}
stopSound(self->health);
}
if (prand() % 3 == 0)
{
addRiftEnergy(self->x + self->w / 2, self->y + self->h / 2);
}
}
}
static void addRiftEnergy(int x, int y)
{
Entity *e;
e = addBasicDecoration(x, y, "decoration/rift_energy");
e->x += prand() % 128 * (prand() % 2 == 0 ? -1 : 1);
e->y += prand() % 128 * (prand() % 2 == 0 ? -1 : 1);
x -= e->w / 2;
y -= e->h / 2;
e->targetX = x;
e->targetY = y;
calculatePath(e->x, e->y, e->targetX, e->targetY, &e->dirX, &e->dirY);
e->dirX *= 8;
e->dirY *= 8;
e->action = &energyMoveToRift;
}
static void energyMoveToRift()
{
self->x += self->dirX;
self->y += self->dirY;
if (atTarget())
{
self->inUse = FALSE;
}
}
| 411 | 0.781206 | 1 | 0.781206 | game-dev | MEDIA | 0.826997 | game-dev | 0.955335 | 1 | 0.955335 |
maraakate/q2dos | 20,223 | action/acesrc/acebot_ai.c | ///////////////////////////////////////////////////////////////////////
//
// ACE - Quake II Bot Base Code
//
// Version 1.0
//
// Original file is Copyright(c), Steve Yeager 1998, All Rights Reserved
//
//
// All other files are Copyright(c) Id Software, Inc.
////////////////////////////////////////////////////////////////////////
/*
* $Header: /LicenseToKill/src/acesrc/acebot_ai.c 25 2/11/99 17:02 Riever $
*
* $Log: /LicenseToKill/src/acesrc/acebot_ai.c $
*
* 25 2/11/99 17:02 Riever
* Fog support added for bot vision and target selection.
*
* 24 27/10/99 18:49 Riever
* Added lightlevel check for enemy selection
*
* 23 22/10/99 7:36 Riever
* Commented checkshot for future development.
*
* 22 22/10/99 7:08 Riever
* Removed distance from weightings.
*
* 21 22/10/99 6:22 Riever
* Modified LR goal item selection weightings.
*
* 20 16/10/99 12:06 Riever
* Changed checkshot code to use a single pixel beam for now.
*
* 19 11/10/99 7:47 Riever
* Fixed SP respawn bug (There was no respawn!)
*
* 18 6/10/99 20:28 Riever
* Stopped targetting spectators for long range goals.
*
* 17 6/10/99 18:15 Riever
* ACEAI_Cmd_Choose() for Teamplay equipment.
*
* 16 6/10/99 17:51 Riever
* Teamplay: Bot spectators don't think.
*
* 15 6/10/99 17:40 Riever
* Added TeamPlay state STATE_POSITION to enable bots to seperate and
* avoid centipede formations.
*
* 14 27/09/99 20:47 Riever
* Removed "current enemy" check
* Added line of sight check for "hurt by enemy"
*
* 13 27/09/99 14:27 Riever
* Removed cost weighting from item selection on long range goals
*
* 12 27/09/99 7:05 Riever
* Added more weapon selection groups based on range
*
* 11 26/09/99 15:34 Riever
* Look for nearby enemies even behind us
*
* 10 26/09/99 7:34 Riever
* Bot vision restricted to FOV
* Enemey selection now chooses closest target
*
* 9 21/09/99 20:20 Riever
* Take teamPauseTime into account when choosing long range goals.
*
* 8 21/09/99 17:22 Riever
* Put a timer in to stop the bots going centipede style in
* TeamPlay.(teamPauseTime)
*
* 7 21/09/99 12:20 Riever
*
* 6 18/09/99 19:47 Riever
* If range is over 300, HC and Knife will not be chosen
*
* 5 18/09/99 19:23 Riever
* Increased random door opening time to 5 seconds
*
* 4 18/09/99 10:16 Riever
* changed door opening attempt time to be 3 + random
*
* 3 18/09/99 9:49 Riever
* Stopped the centipede effect in teamplay
*
* 2 13/09/99 19:52 Riever
* Added headers
*
*/
///////////////////////////////////////////////////////////////////////
//
// acebot_ai.c - This file contains all of the
// AI routines for the ACE II bot.
//
//
// NOTE: I went back and pulled out most of the brains from
// a number of these functions. They can be expanded on
// to provide a "higher" level of AI.
////////////////////////////////////////////////////////////////////////
#include "../g_local.h"
#include "../m_player.h"
#include "acebot.h"
// CGF_FOG ADD
#include "cgf_sfx_fog.h"
// CGF_FOG END
void ACEAI_Cmd_Choose( edict_t *ent, char *s);
///////////////////////////////////////////////////////////////////////
// Main Think function for bot
///////////////////////////////////////////////////////////////////////
void ACEAI_Think (edict_t *self)
{
usercmd_t ucmd;
// Set up client movement
VectorCopy(self->client->ps.viewangles,self->s.angles);
VectorSet (self->client->ps.pmove.delta_angles, 0, 0, 0);
memset (&ucmd, 0, sizeof (ucmd));
self->enemy = NULL;
self->movetarget = NULL;
// Force respawn
if (self->deadflag)
{
self->client->buttons = 0;
ucmd.buttons = BUTTON_ATTACK;
}
// Teamplay spectator?
// if( self->solid == SOLID_NOT)
// return;
if(self->state == STATE_WANDER &&
(self->wander_timeout < level.time)
)
ACEAI_PickLongRangeGoal(self); // pick a new long range goal
// In teamplay pick a random node
if( self->state == STATE_POSITION )
{
if( level.time >= self->teamPauseTime)
{
// We've waited long enough - let's go kick some ass!
self->state = STATE_WANDER;
}
// Don't go here too often
if( self->goal_node == INVALID || self->wander_timeout < level.time )
ACEAI_PickLongRangeGoal(self);
}
// Kill the bot if completely stuck somewhere
if(VectorLength(self->velocity) > 37) //
self->suicide_timeout = level.time + 10.0;
if(self->suicide_timeout < level.time && !teamplay->value)
{
self->health = 0;
player_die (self, self, self, 100000, vec3_origin);
}
// Find any short range goal
ACEAI_PickShortRangeGoal(self);
// Look for enemies
if(ACEAI_FindEnemy(self))
{
ACEAI_ChooseWeapon(self);
ACEMV_Attack (self, &ucmd);
}
else
{
// Are we hurt?
if( self->health < 100)
{
Cmd_Bandage_f ( self );
}
// Execute the move, or wander
if(self->state == STATE_WANDER)
ACEMV_Wander(self,&ucmd);
else if( (self->state == STATE_MOVE) || (self->state == STATE_POSITION) )
ACEMV_Move(self,&ucmd);
}
//AQ2 ADD
if(self->last_door_time < (level.time - 5.0 - random()) )
{
// Toggle any door that may be nearby
//@@ Temporary until I get better code in! Needs to trace for the door
Cmd_OpenDoor_f ( self );
self->last_door_time = level.time;
}
//AQ2 END
//debug_printf("State: %d\n",self->state);
// set approximate ping
ucmd.msec = 75 + floor (random () * 25) + 1;
// show random ping values in scoreboard
self->client->ping = ucmd.msec;
// set bot's view angle
ucmd.angles[PITCH] = ANGLE2SHORT(self->s.angles[PITCH]);
ucmd.angles[YAW] = ANGLE2SHORT(self->s.angles[YAW]);
ucmd.angles[ROLL] = ANGLE2SHORT(self->s.angles[ROLL]);
// send command through id's code
ClientThink (self, &ucmd);
self->nextthink = level.time + FRAMETIME;
}
///////////////////////////////////////////////////////////////////////
// Evaluate the best long range goal and send the bot on
// its way. This is a good time waster, so use it sparingly.
// Do not call it for every think cycle.
///////////////////////////////////////////////////////////////////////
void ACEAI_PickLongRangeGoal(edict_t *self)
{
int i;
int node;
float weight,best_weight=0.0;
int current_node,goal_node = INVALID;
edict_t *goal_ent = NULL;
float cost;
// look for a target
current_node = ACEND_FindClosestReachableNode(self,NODE_DENSITY,NODE_ALL);
self->current_node = current_node;
// Even in teamplay, we wander if no valid node
if(current_node == -1)
{
self->state = STATE_WANDER;
self->wander_timeout = level.time + 1.0;
self->goal_node = -1;
return;
}
//======================
// Teamplay POSITION state
//======================
if( self->state == STATE_POSITION )
{
int counter = 0;
cost = INVALID;
self->goal_node = INVALID;
// Pick a random node to go to
while( cost == INVALID && counter < 10) // Don't look for too many
{
counter++;
i = (int)(random() * numnodes -1); // Any of the current nodes will do
cost = ACEND_FindCost(current_node, i);
if(cost == INVALID || cost < 2) // ignore invalid and very short hops
{
cost = INVALID;
i = INVALID;
continue;
}
}
// We have a target node - just go there!
if( i != INVALID )
{
self->state = STATE_MOVE;
self->tries = 0; // Reset the count of how many times we tried this goal
ACEND_SetGoal(self,i);
self->wander_timeout = level.time + 1.0;
return;
}
}
///////////////////////////////////////////////////////
// Items
///////////////////////////////////////////////////////
for(i=0;i<num_items;i++)
{
if(item_table[i].ent == NULL || item_table[i].ent->solid == SOLID_NOT) // ignore items that are not there.
continue;
cost = ACEND_FindCost(current_node,item_table[i].node);
if(cost == INVALID || cost < 2) // ignore invalid and very short hops
continue;
weight = ACEIT_ItemNeed(self, item_table[i].item);
/* // If I am on team one and I have the flag for the other team....return it
if(ctf->value && (item_table[i].item == ITEMLIST_FLAG2 || item_table[i].item == ITEMLIST_FLAG1) &&
(self->client->resp.ctf_team == CTF_TEAM1 && self->client->pers.inventory[ITEMLIST_FLAG2] ||
self->client->resp.ctf_team == CTF_TEAM2 && self->client->pers.inventory[ITEMLIST_FLAG1]))
weight = 10.0;*/
weight *= ( (rand()%5) +1 ); // Allow random variations
// weight /= cost; // Check against cost of getting there
if(weight > best_weight && item_table[i].node != INVALID)
{
best_weight = weight;
goal_node = item_table[i].node;
goal_ent = item_table[i].ent;
}
}
///////////////////////////////////////////////////////
// Players
///////////////////////////////////////////////////////
// This should be its own function and is for now just
// finds a player to set as the goal.
for(i=0;i<num_players;i++)
{
if( (players[i] == self) || (players[i]->solid == SOLID_NOT) )
continue;
// If it's dark and he's not already our enemy, ignore him
if( self->enemy && players[i] != self->enemy)
{
if( players[i]->light_level < 30)
continue;
// CGF_FOG ADD
// Check for FOG!
if( CGF_SFX_IsFogEnabled() )
{
vec3_t v;
float range;
// Get distance to enemy
VectorSubtract (self->s.origin, players[i]->s.origin, v);
range = VectorLength(v);
// If fog index is < 0.1 we can't see him
if( CGF_SFX_GetFogForDistance(range) < 0.1)
continue;
}
// CGF_FOG END
}
node = ACEND_FindClosestReachableNode(players[i],NODE_DENSITY,NODE_ALL);
// RiEvEr - bug fixing
if( node == INVALID)
cost = INVALID;
else
cost = ACEND_FindCost(current_node, node);
if(cost == INVALID || cost < 3) // ignore invalid and very short hops
continue;
/* // Player carrying the flag?
if(ctf->value && (players[i]->client->pers.inventory[ITEMLIST_FLAG2] || players[i]->client->pers.inventory[ITEMLIST_FLAG1]))
weight = 2.0;
else*/
// Stop the centipede effect in teamplay
if( teamplay->value )
{
// Check it's an enemy
// If not an enemy, don't follow him
if( OnSameTeam( self, players[i]))
weight = 0.0;
else
weight = 0.3;
}
else
weight = 0.3;
weight *= ( (rand()%5) +1 ); // Allow random variations
// weight /= cost; // Check against cost of getting there
if(weight > best_weight && node != INVALID)
{
best_weight = weight;
goal_node = node;
goal_ent = players[i];
}
}
// If do not find a goal, go wandering....
if(best_weight == 0.0 || goal_node == INVALID )
{
self->goal_node = INVALID;
self->state = STATE_WANDER;
self->wander_timeout = level.time + 1.0;
if(debug_mode)
debug_printf("%s did not find a LR goal, wandering.\n",self->client->pers.netname);
return; // no path?
}
// OK, everything valid, let's start moving to our goal.
self->state = STATE_MOVE;
self->tries = 0; // Reset the count of how many times we tried this goal
if(goal_ent != NULL && debug_mode)
debug_printf("%s selected a %s at node %d for LR goal.\n",self->client->pers.netname, goal_ent->classname, goal_node);
ACEND_SetGoal(self,goal_node);
}
///////////////////////////////////////////////////////////////////////
// Pick best goal based on importance and range. This function
// overrides the long range goal selection for items that
// are very close to the bot and are reachable.
///////////////////////////////////////////////////////////////////////
void ACEAI_PickShortRangeGoal(edict_t *self)
{
edict_t *target;
float weight,best_weight=0.0;
edict_t *best = NULL;
int index;
// look for a target (should make more efficient later)
target = findradius(NULL, self->s.origin, 200);
while(target)
{
if(target->classname == NULL)
return;
// Missle avoidance code
// Set our movetarget to be the rocket or grenade fired at us.
if(strcmp(target->classname,"rocket")==0 || strcmp(target->classname,"grenade")==0)
{
if(debug_mode)
debug_printf("ROCKET ALERT!\n");
self->movetarget = target;
return;
}
if (ACEIT_IsReachable(self,target->s.origin))
{
if (infront(self, target))
{
index = ACEIT_ClassnameToIndex(target->classname);
weight = ACEIT_ItemNeed(self, index);
if(weight > best_weight)
{
best_weight = weight;
best = target;
}
}
}
// next target
target = findradius(target, self->s.origin, 200);
}
if(best_weight)
{
self->movetarget = best;
if(debug_mode && self->goalentity != self->movetarget)
debug_printf("%s selected a %s for SR goal.\n",self->client->pers.netname, self->movetarget->classname);
self->goalentity = best;
}
}
///////////////////////////////////////////////////////////////////////
// Scan for enemy (simplifed for now to just pick any visible enemy)
///////////////////////////////////////////////////////////////////////
// Modified by RiEvEr
// Chooses nearest enemy or last person to shoot us
//
qboolean ACEAI_FindEnemy(edict_t *self)
{
int i;
edict_t *bestenemy = NULL;
float bestweight = 99999;
float weight;
vec3_t dist;
/* // If we already have an enemy and it is the last enemy to hurt us
if (self->enemy &&
(self->enemy == self->client->attacker) &&
(!self->enemy->deadflag) &&
(self->enemy->solid != SOLID_NOT)
)
{
return true;
}
*/
for(i=0;i<=num_players;i++)
{
if(players[i] == NULL || players[i] == self ||
players[i]->solid == SOLID_NOT)
continue;
// If it's dark and he's not already our enemy, ignore him
if( self->enemy && players[i] != self->enemy)
{
if( players[i]->light_level < 30)
continue;
// CGF_FOG ADD
// Check for FOG!
if( CGF_SFX_IsFogEnabled() )
{
vec3_t v;
float range;
// Get distance to enemy
VectorSubtract (self->s.origin, players[i]->s.origin, v);
range = VectorLength(v);
// If fog index is < 0.1 we can't see him
if( CGF_SFX_GetFogForDistance(range) < 0.1)
continue;
}
// CGF_FOG END
}
/* if(ctf->value &&
self->client->resp.ctf_team == players[i]->client->resp.ctf_team)
continue;*/
// AQ2 ADD
if(teamplay->value && OnSameTeam( self, players[i]) )
continue;
// AQ2 END
if(!players[i]->deadflag && visible(self, players[i]) &&
gi.inPVS(self->s.origin, players[i]->s.origin) )
{
// RiEvEr
// Now we assess this enemy
VectorSubtract(self->s.origin, players[i]->s.origin, dist);
weight = VectorLength( dist );
// Can we see this enemy, or is it so close that we should not ignore it!
if( infront( self, players[i] ) ||
(weight < 300 ) )
{
// See if it's better than what we have already
if (weight < bestweight)
{
bestweight = weight;
bestenemy = players[i];
}
}
}
}
// If we found a good enemy set it up
if( bestenemy)
{
self->enemy = bestenemy;
return true;
}
// Check if we've been shot from behind or out of view
if( self->client->attacker )
{
// Check if it was recent
if( self->client->push_timeout > 0)
{
if(!self->client->attacker->deadflag && visible(self, self->client->attacker) &&
gi.inPVS(self->s.origin, self->client->attacker->s.origin) )
{
self->enemy = self->client->attacker;
return true;
}
}
}
//R
// Otherwise signal "no enemy available"
return false;
}
///////////////////////////////////////////////////////////////////////
// Hold fire with RL/BFG?
///////////////////////////////////////////////////////////////////////
//@@ Modify this to check for hitting teammates in teamplay games.
qboolean ACEAI_CheckShot(edict_t *self)
{
trace_t tr;
//AQ2 tr = gi.trace (self->s.origin, tv(-8,-8,-8), tv(8,8,8), self->enemy->s.origin, self, MASK_OPAQUE);
// tr = gi.trace (self->s.origin, tv(-8,-8,-8), tv(8,8,8), self->enemy->s.origin, self, MASK_SOLID|MASK_OPAQUE);
tr = gi.trace (self->s.origin, vec3_origin, vec3_origin, self->enemy->s.origin, self, MASK_SOLID|MASK_OPAQUE);
// Blocked, do not shoot
if (tr.fraction < 0.9)
return false;
return true;
}
///////////////////////////////////////////////////////////////////////
// Choose the best weapon for bot (simplified)
///////////////////////////////////////////////////////////////////////
void ACEAI_ChooseWeapon(edict_t *self)
{
float range;
vec3_t v;
// if no enemy, then what are we doing here?
if(!self->enemy)
return;
//AQ2 CHANGE
// Currently always favor the dual pistols!
//@@ This will become the "bot choice" weapon
// if(ACEIT_ChangeDualSpecialWeapon(self,FindItem(DUAL_NAME)))
// return;
//AQ2 END
// Base selection on distance.
VectorSubtract (self->s.origin, self->enemy->s.origin, v);
range = VectorLength(v);
// Longer range
if(range > 1000)
{
if(ACEIT_ChangeSniperSpecialWeapon(self,FindItem(SNIPER_NAME)))
return;
if(ACEIT_ChangeM3SpecialWeapon(self,FindItem(M3_NAME)))
return;
if(ACEIT_ChangeM4SpecialWeapon(self,FindItem(M4_NAME)))
return;
if(ACEIT_ChangeMP5SpecialWeapon(self,FindItem(MP5_NAME)))
return;
if(ACEIT_ChangeMK23SpecialWeapon(self,FindItem(MK23_NAME)))
return;
}
// Longer range
if(range > 700)
{
if(ACEIT_ChangeM3SpecialWeapon(self,FindItem(M3_NAME)))
return;
if(ACEIT_ChangeM4SpecialWeapon(self,FindItem(M4_NAME)))
return;
if(ACEIT_ChangeMP5SpecialWeapon(self,FindItem(MP5_NAME)))
return;
if(ACEIT_ChangeSniperSpecialWeapon(self,FindItem(SNIPER_NAME)))
return;
if(ACEIT_ChangeMK23SpecialWeapon(self,FindItem(MK23_NAME)))
return;
}
// Longer range
if(range > 500)
{
if(ACEIT_ChangeMP5SpecialWeapon(self,FindItem(MP5_NAME)))
return;
if(ACEIT_ChangeM3SpecialWeapon(self,FindItem(M3_NAME)))
return;
if(ACEIT_ChangeM4SpecialWeapon(self,FindItem(M4_NAME)))
return;
if(ACEIT_ChangeSniperSpecialWeapon(self,FindItem(SNIPER_NAME)))
return;
if(ACEIT_ChangeMK23SpecialWeapon(self,FindItem(MK23_NAME)))
return;
}
// Longer range
if(range > 300)
{
if(ACEIT_ChangeM4SpecialWeapon(self,FindItem(M4_NAME)))
return;
if(ACEIT_ChangeMP5SpecialWeapon(self,FindItem(MP5_NAME)))
return;
if(ACEIT_ChangeM3SpecialWeapon(self,FindItem(M3_NAME)))
return;
if(ACEIT_ChangeSniperSpecialWeapon(self,FindItem(SNIPER_NAME)))
return;
if(ACEIT_ChangeMK23SpecialWeapon(self,FindItem(MK23_NAME)))
return;
}
// Short range
if(ACEIT_ChangeHCSpecialWeapon(self,FindItem(HC_NAME)))
return;
if(ACEIT_ChangeSniperSpecialWeapon(self,FindItem(SNIPER_NAME)))
return;
if(ACEIT_ChangeM3SpecialWeapon(self,FindItem(M3_NAME)))
return;
if(ACEIT_ChangeM4SpecialWeapon(self,FindItem(M4_NAME)))
return;
if(ACEIT_ChangeMP5SpecialWeapon(self,FindItem(MP5_NAME)))
return;
if(ACEIT_ChangeDualSpecialWeapon(self,FindItem(DUAL_NAME)))
return;
if(ACEIT_ChangeMK23SpecialWeapon(self,FindItem(MK23_NAME)))
return;
if(ACEIT_ChangeWeapon(self,FindItem(KNIFE_NAME)))
return;
}
void ACEAI_Cmd_Choose (edict_t *ent, char *s)
{
// only works in teamplay
if (!teamplay->value)
return;
if ( Q_stricmp(s, MP5_NAME) == 0 )
ent->client->resp.weapon = FindItem(MP5_NAME);
else if ( Q_stricmp(s, M3_NAME) == 0 )
ent->client->resp.weapon = FindItem(M3_NAME);
else if ( Q_stricmp(s, M4_NAME) == 0 )
ent->client->resp.weapon = FindItem(M4_NAME);
else if ( Q_stricmp(s, HC_NAME) == 0 )
ent->client->resp.weapon = FindItem(HC_NAME);
else if ( Q_stricmp(s, SNIPER_NAME) == 0 )
ent->client->resp.weapon = FindItem(SNIPER_NAME);
else if ( Q_stricmp(s, KNIFE_NAME) == 0 )
ent->client->resp.weapon = FindItem(KNIFE_NAME);
else if ( Q_stricmp(s, DUAL_NAME) == 0 )
ent->client->resp.weapon = FindItem(DUAL_NAME);
else if ( Q_stricmp(s, KEV_NAME) == 0 )
ent->client->resp.item = FindItem(KEV_NAME);
else if ( Q_stricmp(s, LASER_NAME) == 0 )
ent->client->resp.item = FindItem(LASER_NAME);
else if ( Q_stricmp(s, SLIP_NAME) == 0 )
ent->client->resp.item = FindItem(SLIP_NAME);
else if ( Q_stricmp(s, SIL_NAME) == 0 )
ent->client->resp.item = FindItem(SIL_NAME);
else if ( Q_stricmp(s, BAND_NAME) == 0 )
ent->client->resp.item = FindItem(BAND_NAME);
}
| 411 | 0.921933 | 1 | 0.921933 | game-dev | MEDIA | 0.96852 | game-dev | 0.961944 | 1 | 0.961944 |
FNF-Porter/Porter.py | 5,709 | psychtobase/src/FileContents.py | CHANGE_CHARACTER_EVENT_HXC_NAME = 'ChangeCharacterEvent.hxc'
CHANGE_CHARACTER_EVENT_HXC_CONTENTS = """import funkin.play.character.CharacterType;
import funkin.modding.module.ModuleHandler;
import funkin.modding.module.Module;
import funkin.play.character.BaseCharacter;
import funkin.play.character.CharacterDataParser;
import funkin.play.event.ScriptedSongEvent;
import funkin.play.PlayState;
import openfl.utils.Assets;
//import Reflect;
/**
* @author MayoOddToSee
*/
class ChangeCharacterEvent extends ScriptedSongEvent {
static var BF = 'bf'; //does static even do or mean anything lol
static var DAD = 'dad';
static var GF = 'gf';
var dataValue:Dynamic;
public function new() {
super('Change Character');
}
override function getEventSchema() {
var map = ["Boyfriend" => BF, "Dad" => DAD, "Girlfriend" => GF,];
var charMap = ["Boyfriend" => "bf"];
for (char in CharacterDataParser.listCharacterIds()) {
charMap.set(CharacterDataParser.fetchCharacterData(char).name, char);
}
return [
{
name: "target",
title: "Target",
type: "enum",
defaultValue: BF,
keys: map,
},
{
name: "char",
title: "Character",
type: "enum",
defaultValue: "bf",
keys: charMap,
}
];
}
override function handleEvent(data) {
if (data.value != null) {
dataValue = data.value;
var target = getValue('target', BF);
ModuleHandler.getModule('change-character-handler').scriptCall('changeCharacter', [
getValue('char', 'bf'),
switch target {
case BF:
CharacterType.BF;
case DAD:
CharacterType.DAD;
case GF:
CharacterType.GF;
},
target
]);
}
}
//helper function
function getValue(field:String, def:Dynamic) {
var value = Assets.resolveClass("Reflect").field(dataValue, field);
if (value == null)
return def;
else
return value;
}
}
//this class actually changes the characters and stuff
class ChangeCharacterHandler extends Module {
var debug = false;
var switchedChars = false;
var chars:Array<Map<String, BaseCharacter>> = [
["" => null],
["" => null],
["" => null],
];
var latest:Array<BaseCharacter> = [];
var charsFetched:Array<String> = [];
var strid:Array<String> = ['bf', 'dad', 'gf'];
var tid:Array<CharacterType> = [CharacterType.BF, CharacterType.DAD, CharacterType.GF];
public function new() {
super('change-character-handler');
}
override function onCreate(e) {
trace('whaaat are you working now bitch');
}
override function onSongRetry() {
super.onSongRetry();
if(!PlayState.instance.isMinimalMode) {
for(i in 0...3) {
replaceChar(tid[i], strid[i], defaults[i]);
}
}
}
override function onStateChangeEnd(event){
super.onStateChangeEnd(event);
ok = false;
for(map in chars) {
for(char in map) {
if(char != null) {
if(debug) trace('IM KILLING YOU', char.characterName);
char.destroy();
}
}
map.clear();
}
}
function changeCharacter(character:String, characterType:CharacterType, characterTypeString:String) {
var id = tid.indexOf(characterType);
var char = chars[id].get(character);
if(char == null) {
trace('couldnt find the preloaded :(', character, characterTypeString);
char = CharacterDataParser.fetchCharacter(char);
chars[id].set(character, char);
if(char == null) {
if(debug) trace('it was STILL null', character, characterTypeString);
return;
}
}else{
if(debug) trace('found preloaded char', character, characterTypeString);
}
replaceChar(characterType, characterTypeString, char);
}
function replaceChar(characterType:CharacterType, characterTypeString:String, char:BaseCharacter) {
var old = PlayState.instance.currentStage.getCharacter(characterTypeString);
if(old == char) return;
var index = PlayState.instance.currentStage.members.indexOf(old);
PlayState.instance.remove(char);
PlayState.instance.currentStage.remove(old);
hideChar(old);
char.scrollFactor.set(1, 1);
char.alpha = 1;
PlayState.instance.currentStage.addCharacter(char, characterType);
PlayState.instance.currentStage.remove(char);
PlayState.instance.currentStage.insert(index, char);
}
function hideChar(char:BaseCharacter) {
char.alpha = .00001;
char.scrollFactor.set();
char.screenCenter();
PlayState.instance.add(char);
}
var ok = false;
var defaults:Array<BaseCharacter> = [];
override function onUpdate(e) {
super.onUpdate(e);
if(PlayState.instance != null && !PlayState.instance.isMinimalMode && PlayState.instance.currentStage != null && !ok) {
ok = true;
var i = 0;
for(char in [PlayState.instance.currentStage.getBoyfriend(), PlayState.instance.currentStage.getDad(), PlayState.instance.currentStage.getGirlfriend()]) {
if (char == null) continue;
chars[i].set(char.characterId, char);
defaults[i] = char;
i++;
}
for(event in PlayState.instance.songEvents) {
if(event.value != null) {
//??????????????????
var char = Assets.resolveClass("Reflect").field(event.value, 'char');
var target = Assets.resolveClass("Reflect").field(event.value, 'target');
if(char != null && target != null && !chars[target].exists(char)) {
var hi = CharacterDataParser.fetchCharacter(char);
chars[strid.indexOf(target)].set(char, hi);
hi.characterType = tid[strid.indexOf(target)];
hideChar(hi);
}
}
}
}
}
}"""
# https://youtu.be/eB6txyhHFG4
# VocalFan, you are officially removed from the dev team! I hate this song. 😡
# https://youtu.be/22tVWwmTie8?si=2TNmHTDoT7UgQvZ-
# Calm down, dude! This song is better!
# https://youtu.be/VMp55KH_3wo
# Shoutout to simpleflips
# https://www.youtube.com/watch?v=JmK98ehX6rc | 411 | 0.865418 | 1 | 0.865418 | game-dev | MEDIA | 0.935374 | game-dev | 0.93287 | 1 | 0.93287 |
revilowaldow/5etools-mirror-2.github.io | 10,302 | js/bestiary/bestiary-encounterbuilder-sublistplugin.js | import {EncounterBuilderHelpers} from "../utils-list-bestiary.js";
import {EncounterBuilderCreatureMeta} from "../encounterbuilder/encounterbuilder-models.js";
import {EncounterBuilderComponentBestiary} from "./bestiary-encounterbuilder-component.js";
/**
* Serialize/deserialize state from the encounter builder.
*/
export class EncounterBuilderSublistPlugin extends SublistPlugin {
constructor ({sublistManager, encounterBuilder, encounterBuilderComp}) {
super();
this._sublistManager = sublistManager;
this._encounterBuilder = encounterBuilder;
this._encounterBuilderComp = encounterBuilderComp;
}
/* -------------------------------------------- */
async pLoadData ({exportedSublist, isMemoryOnly}) {
const nxt = {};
// Allow URLified versions of keys
const keyLookup = this._encounterBuilderComp.getDefaultStateKeys()
.mergeMap(k => ({[k]: k, [k.toUrlified()]: k}));
if (exportedSublist) {
Object.entries(exportedSublist)
.filter(([, v]) => v != null)
.map(([k, v]) => {
// Only add specific keys, as we do not want to track e.g. sublist state
k = keyLookup[k];
if (!k) return null;
return [k, v];
})
.filter(Boolean)
// Always process `colsExtraAdvanced` first (if available), as used in `playersAdvanced`
.sort(([kA], [kB]) => kA === "colsExtraAdvanced" ? -1 : kB === "colsExtraAdvanced" ? 1 : 0)
.forEach(([k, v]) => {
if (isMemoryOnly) return nxt[k] = MiscUtil.copyFast(v);
// When loading from non-memory sources, expand the data
switch (k) {
case "playersSimple": return nxt[k] = v.map(it => EncounterBuilderComponentBestiary.getDefaultPlayerRow_simple(it));
case "colsExtraAdvanced": return nxt[k] = v.map(it => EncounterBuilderComponentBestiary.getDefaultColExtraAdvanced(it));
case "playersAdvanced": return nxt[k] = v.map(it => EncounterBuilderComponentBestiary.getDefaultPlayerRow_advanced({
...it,
extras: it.extras.map(x => EncounterBuilderComponentBestiary.getDefaultPlayerAdvancedExtra(x)),
colsExtraAdvanced: nxt.colsExtraAdvanced || this._encounterBuilderComp.colsExtraAdvanced,
}));
default: return nxt[k] = v;
}
});
if (nxt.playersSimple) {
nxt.playersSimple
.forEach(wrapped => {
wrapped.entity.count = wrapped.entity.count || 1;
wrapped.entity.level = wrapped.entity.level || 1;
});
}
if (nxt.playersAdvanced) {
nxt.playersAdvanced
.forEach(wrapped => {
wrapped.entity.name = wrapped.entity.name || "";
wrapped.entity.level = wrapped.entity.level || 1;
wrapped.entity.extraCols = wrapped.entity.extraCols
|| (nxt.colsExtraAdvanced || this._encounterBuilderComp.colsExtraAdvanced.map(() => ""));
});
}
}
// Note that we do not set `creatureMetas` here, as `onSublistUpdate` handles this
this._encounterBuilderComp.setStateFromLoaded(nxt);
}
async _pLoadData_getCreatureMetas ({exportedSublist}) {
if (!exportedSublist.items?.length) return [];
return exportedSublist.items
.pSerialAwaitMap(async serialItem => {
const {
entity,
entityBase,
count,
isLocked,
customHashId,
} = await SublistManager.pDeserializeExportedSublistItem(serialItem);
return new EncounterBuilderCreatureMeta({
creature: entity,
count,
isLocked,
customHashId: customHashId,
baseCreature: entityBase,
});
});
}
static async pMutLegacyData ({exportedSublist, isMemoryOnly}) {
if (!exportedSublist) return;
// region Legacy Bestiary Encounter Builder format
if (exportedSublist.p) {
exportedSublist.playersSimple = exportedSublist.p.map(it => EncounterBuilderComponentBestiary.getDefaultPlayerRow_simple(it));
if (!isMemoryOnly) this._mutExternalize({obj: exportedSublist, k: "playersSimple"});
delete exportedSublist.p;
}
if (exportedSublist.l) {
Object.assign(exportedSublist, exportedSublist.l);
delete exportedSublist.l;
}
if (exportedSublist.a != null) {
exportedSublist.isAdvanced = !!exportedSublist.a;
delete exportedSublist.a;
}
if (exportedSublist.c) {
exportedSublist.colsExtraAdvanced = exportedSublist.c.map(name => EncounterBuilderComponentBestiary.getDefaultColExtraAdvanced({name}));
if (!isMemoryOnly) this._mutExternalize({obj: exportedSublist, k: "colsExtraAdvanced"});
delete exportedSublist.c;
}
if (exportedSublist.d) {
exportedSublist.playersAdvanced = exportedSublist.d.map(({n, l, x}) => EncounterBuilderComponentBestiary.getDefaultPlayerRow_advanced({
name: n,
level: l,
extras: x.map(value => EncounterBuilderComponentBestiary.getDefaultPlayerAdvancedExtra({value})),
colsExtraAdvanced: exportedSublist.colsExtraAdvanced,
}));
if (!isMemoryOnly) this._mutExternalize({obj: exportedSublist, k: "playersAdvanced"});
delete exportedSublist.d;
}
// endregion
// region Legacy "reference" format
// These are general save manager properties, but we set them here, as encounter data was the only thing to make
// use of this system.
if (exportedSublist.bestiaryId) {
exportedSublist.saveId = exportedSublist.bestiaryId;
delete exportedSublist.bestiaryId;
}
if (exportedSublist.isRef) {
exportedSublist.managerClient_isReferencable = true;
exportedSublist.managerClient_isLoadAsCopy = false;
}
delete exportedSublist.isRef;
// endregion
}
async pMutLegacyData ({exportedSublist, isMemoryOnly}) {
await this.constructor.pMutLegacyData({exportedSublist, isMemoryOnly});
}
/* -------------------------------------------- */
async pMutSaveableData ({exportedSublist, isForce = false, isMemoryOnly = false}) {
if (!isForce && !this._encounterBuilder.isActive()) return;
[
"playersSimple",
"isAdvanced",
"colsExtraAdvanced",
"playersAdvanced",
].forEach(k => {
exportedSublist[k] = MiscUtil.copyFast(this._encounterBuilderComp[k]);
if (isMemoryOnly) return;
this.constructor._mutExternalize({obj: exportedSublist, k});
});
}
static _WALKER_EXTERNALIZE = null;
static _HANDLERS_EXTERNALIZE = {
array: (arr) => {
if (arr.some(it => !it.id || !it.entity)) return arr;
return arr.map(({entity}) => entity);
},
};
static _mutExternalize ({obj, k}) {
this._WALKER_EXTERNALIZE = this._WALKER_EXTERNALIZE || MiscUtil.getWalker();
obj[k] = this._WALKER_EXTERNALIZE.walk(
obj[k],
this._HANDLERS_EXTERNALIZE,
);
}
/* -------------------------------------------- */
async pDoInitNewState ({prevExportableSublist, evt}) {
// If SHIFT pressed, reset players
const nxt = {
playersSimple: evt.shiftKey ? [] : MiscUtil.copyFast(prevExportableSublist.playersSimple),
playersAdvanced: evt.shiftKey ? [] : MiscUtil.copyFast(prevExportableSublist.playersAdvanced),
};
this._encounterBuilderComp.setPartialStateFromLoaded(nxt);
}
/* -------------------------------------------- */
getDownloadName () {
if (!this._encounterBuilder.isActive()) return null;
return "encounter";
}
getDownloadFileType () {
if (!this._encounterBuilder.isActive()) return null;
return "encounter";
}
getUploadFileTypes ({downloadFileTypeBase}) {
if (!this._encounterBuilder.isActive()) return null;
return [this.getDownloadFileType(), downloadFileTypeBase];
}
/* -------------------------------------------- */
onSublistUpdate () {
this._encounterBuilder.withSublistSyncSuppressed(() => {
// Note that we only update `creatureMetas` here, as this only triggers on direct updates to the underlying sublist.
// For everything else, the `pLoadData` path is used.
this._encounterBuilderComp.creatureMetas = this._sublistManager.sublistItems
.map(sublistItem => EncounterBuilderHelpers.getSublistedCreatureMeta({sublistItem}));
});
}
}
class EncounterBuilderLegacyStorageMigration {
static _VERSION = 2;
static _STORAGE_KEY_LEGACY_SAVED_ENCOUNTERS = "ENCOUNTER_SAVED_STORAGE";
static _STORAGE_KEY_LEGACY_ENCOUNTER = "ENCOUNTER_STORAGE";
static _STORAGE_KEY_LEGACY_ENCOUNTER_MIGRATION_VERSION = "ENCOUNTER_STORAGE_MIGRATION_VERSION";
static _STORAGE_KEY_LEGACY_SAVED_ENCOUNTER_MIGRATION_VERSION = "ENCOUNTER_SAVED_STORAGE_MIGRATION_VERSION";
static register () {
SublistPersistor._LEGACY_MIGRATOR.registerLegacyMigration(this._pMigrateSublist.bind(this));
SaveManager._LEGACY_MIGRATOR.registerLegacyMigration(this._pMigrateSaves.bind(this));
}
static async _pMigrateSublist (stored) {
let version = await StorageUtil.pGet(this._STORAGE_KEY_LEGACY_ENCOUNTER_MIGRATION_VERSION);
if (version && version >= 2) return false;
if (!version) version = 1;
const encounter = await StorageUtil.pGet(this._STORAGE_KEY_LEGACY_ENCOUNTER);
if (!encounter) return false;
Object.entries(encounter)
.forEach(([k, v]) => {
if (stored[k] != null) return;
stored[k] = v;
});
await EncounterBuilderSublistPlugin.pMutLegacyData({exportedSublist: stored});
await StorageUtil.pSet(this._STORAGE_KEY_LEGACY_ENCOUNTER_MIGRATION_VERSION, this._VERSION);
JqueryUtil.doToast(`Migrated active Bestiary encounter from version ${version} to version ${this._VERSION}!`);
return true;
}
static async _pMigrateSaves (stored) {
let version = await StorageUtil.pGet(this._STORAGE_KEY_LEGACY_SAVED_ENCOUNTER_MIGRATION_VERSION);
if (version && version >= 2) return false;
if (!version) version = 1;
const encounters = await StorageUtil.pGet(this._STORAGE_KEY_LEGACY_SAVED_ENCOUNTERS);
if (!encounters) return false;
await Object.entries(encounters.savedEncounters || {})
.pSerialAwaitMap(async ([id, enc]) => {
const legacyData = MiscUtil.copyFast(enc.data || {});
legacyData.name = enc.name || "(Unnamed encounter)";
legacyData.saveId = id;
legacyData.manager_isSaved = true;
await EncounterBuilderSublistPlugin.pMutLegacyData({exportedSublist: legacyData});
const tgt = MiscUtil.getOrSet(stored, "state", "saves", []);
tgt.push({
id: CryptUtil.uid(),
entity: legacyData,
});
});
await StorageUtil.pSet(this._STORAGE_KEY_LEGACY_SAVED_ENCOUNTER_MIGRATION_VERSION, this._VERSION);
JqueryUtil.doToast(`Migrated saved Bestiary encounters from version ${version} to version ${this._VERSION}!`);
return true;
}
}
EncounterBuilderLegacyStorageMigration.register();
| 411 | 0.945963 | 1 | 0.945963 | game-dev | MEDIA | 0.47973 | game-dev | 0.975173 | 1 | 0.975173 |
kessiler/muOnline-season6 | 6,758 | gameServer/gameServer/TMonsterAIUnit.cpp | // TMonsterAIUnit.cpp: implementation of the TMonsterAIUnit class.
// GS-N 1.00.77 JPN - Completed
// GS-CS 1.00.90 JPN - Completed
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "TMonsterAIUnit.h"
#include "..\include\ReadScript.h"
#include "LogProc.h"
BOOL TMonsterAIUnit::s_bDataLoad = FALSE;
TMonsterAIUnit TMonsterAIUnit::s_MonsterAIUnitArray[MAX_MONSTER_AI_UNIT];
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
TMonsterAIUnit::TMonsterAIUnit()
{
this->Reset();
}
TMonsterAIUnit::~TMonsterAIUnit()
{
return;
}
void TMonsterAIUnit::Reset()
{
this->m_iUnitNumber = -1;
this->m_iDelayTime = NULL;
this->m_lpAutomata = NULL;
this->m_lpAIClassNormal = NULL;
this->m_lpAIClassMove = NULL;
this->m_lpAIClassAttack = NULL;
this->m_lpAIClassHeal = NULL;
this->m_lpAIClassAvoid = NULL;
this->m_lpAIClassHelp = NULL;
this->m_lpAIClassSpecial = NULL;
this->m_lpAIClassEvent = NULL;
memset(this->m_szUnitName, 0, sizeof(this->m_szUnitName));
this->m_lppAIClassMap[0] = &this->m_lpAIClassNormal;
this->m_lppAIClassMap[1] = &this->m_lpAIClassMove;
this->m_lppAIClassMap[2] = &this->m_lpAIClassAttack;
this->m_lppAIClassMap[3] = &this->m_lpAIClassHeal;
this->m_lppAIClassMap[4] = &this->m_lpAIClassAvoid;
this->m_lppAIClassMap[5] = &this->m_lpAIClassHelp;
this->m_lppAIClassMap[6] = &this->m_lpAIClassSpecial;
this->m_lppAIClassMap[7] = &this->m_lpAIClassEvent;
}
BOOL TMonsterAIUnit::LoadData(LPSTR lpszFileName)
{
TMonsterAIUnit::s_bDataLoad = FALSE;
if ( !lpszFileName || !strcmp(lpszFileName, ""))
{
MsgBox("[Monster AI Unit] - File load error : File Name Error");
return FALSE;
}
try
{
SMDToken Token;
SMDFile = fopen(lpszFileName, "r"); //ok
if ( SMDFile == NULL )
{
MsgBox("[Monster AI Unit] - Can't Open %s ", lpszFileName);
return FALSE;
}
TMonsterAIUnit::DelAllAIUnit();
int iType = -1;
while ( true )
{
Token = GetToken();
if ( Token == END )
break;
iType = TokenNumber;
while ( true )
{
if ( iType == 0 )
{
char szUnitName[50]={0};
int iUnitNumber = -1;
int iDelayTime = 0;
int iAutomata = -1;
int iAIClassNormal = -1;
int iAIClassMove = -1;
int iAIClassAttack = -1;
int iAIClassHeal = -1;
int iAIClassAvoid = -1;
int iAIClassHelp = -1;
int iAIClassSpecial = -1;
int iAIClassEvent = -1;
Token = GetToken();
if ( !strcmp("end", TokenString))
break;
iUnitNumber = TokenNumber;
Token = GetToken();
memcpy(szUnitName, TokenString, 20);
Token = GetToken();
iDelayTime = TokenNumber;
Token = GetToken();
iAutomata = TokenNumber;
Token = GetToken();
iAIClassNormal = TokenNumber;
Token = GetToken();
iAIClassMove = TokenNumber;
Token = GetToken();
iAIClassAttack = TokenNumber;
Token = GetToken();
iAIClassHeal = TokenNumber;
Token = GetToken();
iAIClassAvoid = TokenNumber;
Token = GetToken();
iAIClassHelp = TokenNumber;
Token = GetToken();
iAIClassSpecial = TokenNumber;
Token = GetToken();
iAIClassEvent = TokenNumber;
if ( iUnitNumber < 0 || iUnitNumber >= MAX_MONSTER_AI_UNIT )
{
MsgBox("[Monster AI Unit] - UnitNumber(%d) Error (%s) File. ",
iUnitNumber, lpszFileName);
continue;
}
if ( iAutomata < 0 || iAutomata >= MAX_MONSTER_AI_AUTOMATA )
{
MsgBox("[Monster AI Unit] - AutomatNumber(%d) Error (%s) File. ",
iAutomata, lpszFileName);
continue;
}
TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_iUnitNumber = iUnitNumber;
TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_iDelayTime = iDelayTime;
TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_lpAutomata = TMonsterAIAutomata::FindAutomata(iAutomata);
TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_lpAIClassNormal = TMonsterAIElement::FindAIElement(iAIClassNormal);
TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_lpAIClassMove = TMonsterAIElement::FindAIElement(iAIClassMove);
TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_lpAIClassAttack = TMonsterAIElement::FindAIElement(iAIClassAttack);
TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_lpAIClassHeal = TMonsterAIElement::FindAIElement(iAIClassHeal);
TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_lpAIClassAvoid = TMonsterAIElement::FindAIElement(iAIClassAvoid);
TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_lpAIClassHelp = TMonsterAIElement::FindAIElement(iAIClassHelp);
TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_lpAIClassSpecial = TMonsterAIElement::FindAIElement(iAIClassSpecial);
TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_lpAIClassEvent = TMonsterAIElement::FindAIElement(iAIClassEvent);
memcpy(TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_szUnitName,
szUnitName, sizeof(TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_szUnitName));
}
}
}
fclose(SMDFile);
LogAddC(2, "[Monster AI Unit] - %s file is Loaded", lpszFileName);
TMonsterAIUnit::s_bDataLoad = TRUE;
}
catch(DWORD)
{
MsgBox("[Monster AI Unit] - Loading Exception Error (%s) File. ", lpszFileName);
}
return FALSE;
}
BOOL TMonsterAIUnit::DelAllAIUnit()
{
for (int i=0;i<MAX_MONSTER_AI_UNIT;i++)
{
TMonsterAIUnit::s_MonsterAIUnitArray[i].Reset();
}
return FALSE;
}
TMonsterAIUnit * TMonsterAIUnit::FindAIUnit(int iUnitNumber)
{
if ( iUnitNumber < 0 || iUnitNumber >= MAX_MONSTER_AI_UNIT )
{
LogAddTD("[Monster AI Unit] FindAIUnit() Error - (UnitNumber=%d) ",
iUnitNumber);
return NULL;
}
if ( TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber].m_iUnitNumber == iUnitNumber )
{
return &TMonsterAIUnit::s_MonsterAIUnitArray[iUnitNumber];
}
LogAddTD("[Monster AI Unit] FindAIUnit() Error - (UnitNumber=%d) ",
iUnitNumber);
return NULL;
}
BOOL TMonsterAIUnit::RunAIUnit(int iIndex)
{
LPOBJ lpObj = &gObj[iIndex];
if ( this->m_lpAutomata == NULL )
return FALSE;
if ( (GetTickCount() - lpObj->m_iLastAutomataRuntime) < lpObj->m_iLastAutomataDelay )
return FALSE;
TMonsterAIState * pAIState = this->m_lpAutomata->RunAutomata(iIndex);
if ( pAIState == NULL )
return FALSE;
lpObj->m_iLastAutomataRuntime = GetTickCount();
TMonsterAIElement * pAIElement = *this->m_lppAIClassMap[pAIState->m_iNextState];
if ( pAIElement == NULL )
return FALSE;
int iRetExec = pAIElement->ForceAIElement(iIndex, 0, pAIState);
if ( iRetExec == 0 )
return FALSE;
lpObj->m_iCurrentAIState = pAIState->m_iNextState;
return TRUE;
}
| 411 | 0.706188 | 1 | 0.706188 | game-dev | MEDIA | 0.909703 | game-dev | 0.987295 | 1 | 0.987295 |
latte-soft/builtinplugins | 2,721 | src/BuiltInPlugins/AvatarCompatibilityPreviewer/Src/Components/Screens/SelectScreen/AvatarCell.luau | local l_script_FirstAncestor_0 = script:FindFirstAncestor("AvatarCompatibilityPreviewer");
local v1 = require(l_script_FirstAncestor_0.Packages.Framework);
local v2 = require(l_script_FirstAncestor_0.Packages.React);
local v3 = require(l_script_FirstAncestor_0.Src.Util.SelectionWrapper);
local _ = require(l_script_FirstAncestor_0.Src.Resources.Theme);
local l_UI_0 = v1.UI;
local l_AssetRenderModel_0 = l_UI_0.AssetRenderModel;
local l_Button_0 = l_UI_0.Button;
local l_Pane_0 = l_UI_0.Pane;
local l_TextLabel_0 = l_UI_0.TextLabel;
local l_Stylizer_0 = v1.ContextServices.Stylizer;
local l_LayoutOrderIterator_0 = v1.Util.LayoutOrderIterator;
return function(v12)
local v13 = v3:use():get();
local l_Avatar_0 = l_Stylizer_0:use("ImportPage").Avatar;
local v15 = l_LayoutOrderIterator_0.new();
local v19 = v2.useMemo(function()
local v16 = v12.Cell.Avatar:Clone();
for _, v18 in v16:GetDescendants() do
if not (not v18:IsA("LuaSourceContainer") and not v18:IsA("Sound")) then
v18:Destroy();
end;
end;
return v16;
end, {
v12.Cell.Avatar
});
return v2.createElement(l_Button_0, {
AutomaticSize = Enum.AutomaticSize.XY,
Position = v12.Position,
OnClick = function()
v13:Set({
v12.Cell.Avatar
});
end,
Size = v12.Size
}, {
v2.createElement(l_Pane_0, {
Layout = Enum.FillDirection.Vertical,
Padding = l_Avatar_0.InnerPadding,
Spacing = l_Avatar_0.Padding
}, {
Preview = v2.createElement(l_AssetRenderModel_0, {
FocusDirection = v19.PrimaryPart.CFrame.LookVector,
Model = v19,
Static = true,
Ambient = l_Avatar_0.PreviewAmbient,
LayoutOrder = v15:getNextOrder(),
LightColor = Color3.new(1, 1, 1),
LightDirection = -v19.PrimaryPart.CFrame.LookVector,
Size = UDim2.fromOffset(l_Avatar_0.IconSize, l_Avatar_0.IconSize)
}),
Name = v2.createElement(l_TextLabel_0, {
LayoutOrder = v15:getNextOrder(),
Size = UDim2.new(1, 0, 0, l_Avatar_0.NameFontSize * l_Avatar_0.NameLines),
Text = v12.Cell.Avatar.Name,
TextColor = l_Avatar_0.TitleColor,
TextSize = l_Avatar_0.NameFontSize,
TextTruncate = Enum.TextTruncate.AtEnd,
TextXAlignment = Enum.TextXAlignment.Left,
TextYAlignment = Enum.TextYAlignment.Top,
TextWrapped = true
})
})
});
end;
| 411 | 0.841848 | 1 | 0.841848 | game-dev | MEDIA | 0.85694 | game-dev | 0.976985 | 1 | 0.976985 |
chenmingbiao/stone-age | 11,096 | gmsv/npc/npc_janken.c | #include "version.h"
#include <string.h>
#include "common.h"
#include "char_base.h"
#include "npc_janken.h"
#include "npcutil.h"
#include "char.h"
#include "lssproto_serv.h"
#include "buf.h"
#include "function.h"
#include "readmap.h"
#include "object.h"
#include "log.h"
/*
*Ԫ
*/
static void NPC_Janken_selectWindow( int meindex, int talker, int num);
void NPC_JnakenJudge(int meindex,int talker,int sel);
BOOL NPC_JankenEntryItemCheck(int talker,char *buf);
BOOL NPC_JankenEntryItemDel(int talker,char *buf);
void NPC_WarpPointGet(int meindex,int talker,int *fl,int *x,int *y,int judge);
/*********************************
*
*********************************/
BOOL NPC_JankenInit( int meindex )
{
//ë
CHAR_setInt( meindex , CHAR_WHICHTYPE , CHAR_TYPEJANKEN );
return TRUE;
}
/*********************************
* ƾľݼ
*********************************/
void NPC_JankenTalked( int meindex , int talkerindex , char *szMes ,
int color )
{
/* 帲ƻ ɱ */
if( CHAR_getInt( talkerindex , CHAR_WHICHTYPE ) != CHAR_TYPEPLAYER ) {
return;
}
/* */
if( NPC_Util_CharDistance( talkerindex, meindex ) > 1) return;
NPC_Janken_selectWindow(meindex, talkerindex, 0);
}
/******************************
* ľľ
******************************/
static void NPC_Janken_selectWindow( int meindex, int talker, int num)
{
char token[1024];
char buf[32];
int fd = getfdFromCharaIndex( talker);
int buttontype=0;
int windowtype=0;
int windowno=0;
char argstr[NPC_UTIL_GETARGSTR_BUFSIZE];
/*--̼⻥мƥƱɬ--*/
windowtype=WINDOW_MESSAGETYPE_MESSAGE;
/*--ɬð̻ë --*/
if(NPC_Util_GetArgStr( meindex, argstr, sizeof(argstr))==NULL){
print("NPC_janken Init: GetArgStrErr");
return ;
}
switch( num)
{
case 0:
/*-- ⻥ ľɾ¡ --*/
if(NPC_Util_GetStrFromStrWithDelim( argstr, "MainMsg", token, sizeof( token)) == NULL)
{
print("Janken:MainMsg:%s", CHAR_getChar( meindex, CHAR_NAME));
return ;
}
/*-- --*/
buttontype = WINDOW_BUTTONTYPE_YESNO;
windowtype = WINDOW_MESSAGETYPE_MESSAGE;
windowno = CHAR_WINDOWTYPE_JANKEN_START;
break;
case 1:
//ʧ ة
if(NPC_Util_GetStrFromStrWithDelim( argstr, "EntryItem", buf, sizeof( buf))!= NULL) {
if(NPC_JankenEntryItemCheck(talker,buf) == FALSE)
{
NPC_Janken_selectWindow(meindex, talker, 3);
}
//üʧ ةë
if(NPC_JankenEntryItemDel(talker,buf) == FALSE){
print("ԪERR:ʧ ةƱ");
}
}
/*-- --*/
sprintf(token," ʯͷ\n"
"\n\n ʯͷ "
"\n\n "
"\n\n "
);
buttontype=WINDOW_BUTTONTYPE_NONE;
windowtype=WINDOW_MESSAGETYPE_SELECT;
windowno=CHAR_WINDOWTYPE_JANKEN_MAIN;
break;
case 2:
/*--ؤг --*/
//sprintf(token," ؤгƥ\n"
sprintf(token," ƽ\n"
"\n\n ʯͷ "
"\n\n "
"\n\n "
);
buttontype=WINDOW_BUTTONTYPE_NONE;
windowtype=WINDOW_MESSAGETYPE_SELECT;
windowno=CHAR_WINDOWTYPE_JANKEN_MAIN;
break;
case 3:
/*-- ⻥ ľɾ¡ --*/
NPC_Util_GetStrFromStrWithDelim( argstr, "NoItem", token, sizeof( token));
buttontype=WINDOW_BUTTONTYPE_OK;
windowtype=WINDOW_MESSAGETYPE_MESSAGE;
windowno=CHAR_WINDOWTYPE_JANKEN_END;
break;
}
// makeEscapeString( token, escapedname, sizeof(escapedname));
/*-ƥ˪--*/
lssproto_WN_send( fd, windowtype,
buttontype,
windowno,
CHAR_getWorkInt( meindex, CHAR_WORKOBJINDEX),
token);
}
/*********************************
* ū帲
*********************************/
void NPC_JankenWindowTalked( int meindex, int talkerindex,
int seqno, int select, char *data)
{
/* */
if( NPC_Util_CharDistance( talkerindex, meindex ) > 1) return;
switch( seqno){
case CHAR_WINDOWTYPE_JANKEN_START:
if(select==WINDOW_BUTTONTYPE_YES){
NPC_Janken_selectWindow(meindex, talkerindex, 1);
}
break;
case CHAR_WINDOWTYPE_JANKEN_MAIN:
if (atoi(data) >= 3){
NPC_JnakenJudge(meindex,talkerindex,atoi(data) );
}
break;
}
}
/*
*Ҽ
*/
void NPC_JnakenJudge(int meindex,int talker,int sel)
{
int player=-1;
int jankenman;
char j_char[3][8]={" ʯͷ "," "," "};
char token[1024];
int shouhai = 0;
int fd = getfdFromCharaIndex( talker);
int fl=0,x=0,y=0;
if(sel == 3) player = 0; //
if(sel == 5) player = 1; //ƽ
if(sel == 7) player = 2; //ɡ
jankenman = rand()%3;
switch(jankenman){
case 0:
if(player == 2){
shouhai = 1;
}else if(player == 1){
shouhai = 2;
}
break;
case 1:
if(player == 0){
shouhai = 1;
}else if(player == 2){
shouhai = 2;
}
break;
case 2:
if(player == 1){
shouhai = 1;
}else if(player == 0){
shouhai = 2;
}
break;
}
if(shouhai == 1){
//Change add Ҳʤ˸ĵ
NPC_JankenItemGet( meindex, talker, "WinItem" );
NPC_WarpPointGet(meindex, talker, &fl, &x, &y, 0);
snprintf( token, sizeof( token ) ,
" \n\n"
" %16s %-16s\n"
" [%s] VS [%s]\n\n\n"
" %-16s ʤ",
CHAR_getChar(meindex,CHAR_NAME),CHAR_getChar(talker,CHAR_NAME),
j_char[jankenman],j_char[player],
CHAR_getChar(talker,CHAR_NAME)
);
// CHAR_talkToCli( talker , -1 ,token , CHAR_COLORCYAN );
//
CHAR_warpToSpecificPoint(talker, fl, x, y);
// 巴٣ʧë£
CHAR_sendWatchEvent( CHAR_getWorkInt( talker, CHAR_WORKOBJINDEX), CHAR_ACTPLEASURE,NULL,0,TRUE);
CHAR_setWorkInt( talker, CHAR_WORKACTION, CHAR_ACTPLEASURE);
}else if(shouhai == 2){
//Change add Ҳ˸ĵ
NPC_JankenItemGet( meindex, talker, "LoseItem" );
NPC_WarpPointGet(meindex, talker, &fl, &x, &y, 1);
snprintf( token, sizeof( token ) ,
" \n\n"
" %16s %-16s\n"
" [%s] VS [%s]\n\n\n"
" %-16s ",
CHAR_getChar(meindex,CHAR_NAME),CHAR_getChar(talker,CHAR_NAME),
j_char[jankenman],j_char[player],
CHAR_getChar(talker,CHAR_NAME)
);
// CHAR_talkToCli( talker , -1 ,token , CHAR_COLORCYAN );
//
CHAR_warpToSpecificPoint(talker, fl, x, y);
// 巴 Уʧë
CHAR_sendWatchEvent( CHAR_getWorkInt( talker, CHAR_WORKOBJINDEX), CHAR_ACTSAD,NULL,0,TRUE);
CHAR_setWorkInt( talker, CHAR_WORKACTION, CHAR_ACTSAD);
}else{
//ؤг
NPC_Janken_selectWindow( meindex, talker, 2);
return;
}
//˪
lssproto_WN_send( fd, WINDOW_MESSAGETYPE_MESSAGE,
WINDOW_BUTTONTYPE_OK,
CHAR_WINDOWTYPE_JANKEN_END,
CHAR_getWorkInt( meindex, CHAR_WORKOBJINDEX),
token);
}
/*
*ëGET£
*/
void NPC_WarpPointGet(int meindex,int talker,int *fl,int *x,int *y,int judge)
{
char argstr[NPC_UTIL_GETARGSTR_BUFSIZE];
char *strbuf[2] = {"WinWarp","LoseWarp"};
char buf[64];
char buf2[32];
/*--ɬð̻ë --*/
if(NPC_Util_GetArgStr( meindex, argstr, sizeof(argstr))==NULL){
print("NPC_janken Init: GetArgStrErr");
return ;
}
/*--ë --*/
NPC_Util_GetStrFromStrWithDelim( argstr, strbuf[judge], buf, sizeof( buf));
getStringFromIndexWithDelim(buf,",",1,buf2,sizeof(buf2));
*fl=atoi(buf2);
getStringFromIndexWithDelim(buf,",",2,buf2,sizeof(buf2));
*x=atoi(buf2);
getStringFromIndexWithDelim(buf,",",3,buf2,sizeof(buf2));
*y=atoi(buf2);
}
/*
*--ʧ ةͷë浤
*/
BOOL NPC_JankenEntryItemCheck(int talker,char *buf)
{
char buf2[512];
char buf3[256];
int id=0;
BOOL flg = FALSE;
int i;
int itemindex;
int itemno;
int kosuu;
int cnt=0;
int k=1;
while(getStringFromIndexWithDelim(buf , "," , k, buf2, sizeof(buf2))
!=FALSE )
{
flg = FALSE;
k++;
if(strstr(buf2,"*") != NULL){
cnt = 0;
getStringFromIndexWithDelim(buf2,"*",1,buf3,sizeof(buf3));
itemno = atoi(buf3);
getStringFromIndexWithDelim(buf2,"*",2,buf3,sizeof(buf3));
kosuu = atoi(buf3);
for( i=0 ; i < CHAR_MAXITEMHAVE;i++ ){
itemindex = CHAR_getItemIndex( talker , i );
if( ITEM_CHECKINDEX(itemindex) ){
id = ITEM_getInt(itemindex ,ITEM_ID );
if(itemno == id){
cnt++;
if(cnt == kosuu){
flg = TRUE;
break;
}
}
}
}
if(flg == FALSE)
{
return FALSE;
}
}else{
itemno = atoi(buf2);
for( i=0 ; i < CHAR_MAXITEMHAVE;i++ ){
itemindex = CHAR_getItemIndex( talker , i );
if( ITEM_CHECKINDEX(itemindex) ){
id = ITEM_getInt(itemindex ,ITEM_ID );
if(itemno == id){
flg = TRUE;
break;
}
}
}
if(flg == FALSE)
{
return FALSE;
}
}
}
return TRUE;
}
BOOL NPC_JankenEntryItemDel(int talker,char *buf)
{
int i = 1, j = 1,k = 1;
char buff3[128];
char buf2[32];
int itemindex;
while(getStringFromIndexWithDelim(buf , "," , k, buff3, sizeof(buff3)) !=FALSE ){
k++;
if(strstr(buff3, "*") !=NULL){
int itemno;
int kosuu;
int id;
int cnt=0;
getStringFromIndexWithDelim(buff3,"*",1,buf2,sizeof(buf2));
itemno = atoi(buf2);
getStringFromIndexWithDelim(buff3,"*",2,buf2,sizeof(buf2));
kosuu = atoi(buf2);
for( i =0 ; i < CHAR_MAXITEMHAVE ; i++ ){
itemindex = CHAR_getItemIndex( talker , i );
if( ITEM_CHECKINDEX(itemindex) ){
id=ITEM_getInt(itemindex ,ITEM_ID );
if(itemno==id){
cnt++;
LogItem(
CHAR_getChar( talker, CHAR_NAME ), /* ƽҷ */
CHAR_getChar( talker, CHAR_CDKEY ),
#ifdef _add_item_log_name // WON ADD itemlogitem
itemindex,
#else
ITEM_getInt( itemindex, ITEM_ID), /* ʧ ة į */
#endif
"QuizDelItem(->)",
CHAR_getInt( talker, CHAR_FLOOR),
CHAR_getInt( talker, CHAR_X ),
CHAR_getInt( talker, CHAR_Y ),
ITEM_getChar( itemindex, ITEM_UNIQUECODE),
ITEM_getChar( itemindex, ITEM_NAME),
ITEM_getInt( itemindex, ITEM_ID)
);
CHAR_DelItem( talker, i);
if(cnt == kosuu){
break;
}
}
}
}
}else{
/*--Ϸ įʧ ةë---*/
for( j = 0 ; j < CHAR_MAXITEMHAVE ; j++){
itemindex = CHAR_getItemIndex( talker ,j);
if( ITEM_CHECKINDEX(itemindex) ){
if( atoi( buff3) == ITEM_getInt(itemindex,ITEM_ID)){
LogItem(
CHAR_getChar( talker, CHAR_NAME ), /* ƽҷ */
CHAR_getChar( talker, CHAR_CDKEY ),
#ifdef _add_item_log_name // WON ADD itemlogitem
itemindex,
#else
ITEM_getInt( itemindex, ITEM_ID), /* ʧ ة į */
#endif
"QuizDelItem(->)",
CHAR_getInt( talker,CHAR_FLOOR),
CHAR_getInt( talker,CHAR_X ),
CHAR_getInt( talker,CHAR_Y ),
ITEM_getChar( itemindex, ITEM_UNIQUECODE),
ITEM_getChar( itemindex, ITEM_NAME),
ITEM_getInt( itemindex, ITEM_ID)
);
CHAR_DelItem( talker, j);
}
}
}
}
}
return TRUE;
}
BOOL NPC_JankenItemGet(int meindex,int talker, char *wl)
{
char argstr[NPC_UTIL_GETARGSTR_BUFSIZE];
char buf[64];
/*--ɬð̻ë --*/
if(NPC_Util_GetArgStr( meindex, argstr, sizeof(argstr))==NULL){
print("NPC_janken ItemGet: GetArgStrErr");
return FALSE;
}
if(NPC_Util_GetStrFromStrWithDelim( argstr, wl, buf, sizeof( buf) ) !=NULL){
NPC_EventAddItem( meindex, talker, buf);
}
}
| 411 | 0.714252 | 1 | 0.714252 | game-dev | MEDIA | 0.628416 | game-dev | 0.827731 | 1 | 0.827731 |
shubin/q3c | 8,736 | engine/win32/win_files.cpp | #include "../client/client.h"
#include "../qcommon/qcommon.h"
#include "win_local.h"
#include <Windows.h>
#include <ShlObj.h>
#define PRODUCT_NAME "Quake III Champions"
#define STEAMPATH_NAME "Quake 3 Arena"
#define STEAMPATH_APPID "2200"
#define GOGPATH_ID "1441704920"
#define MSSTORE_PATH "Quake 3"
// Used to store the Steam Quake 3 installation path
static char steamPath[ MAX_OSPATH ] = { 0 };
// Used to store the GOG Quake 3 installation path
static char gogPath[ MAX_OSPATH ] = { 0 };
// Used to store the Microsoft Store Quake 3 installation path
static char microsoftStorePath[MAX_OSPATH] = { 0 };
/*
================
Sys_SteamPath
================
*/
char *Sys_SteamPath( void )
{
#if defined(STEAMPATH_NAME) || defined(STEAMPATH_APPID)
HKEY steamRegKey;
DWORD pathLen = MAX_OSPATH;
qboolean finishPath = qfalse;
#ifdef STEAMPATH_APPID
// Assuming Steam is a 32-bit app
if (!steamPath[0] && !RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Steam App " STEAMPATH_APPID, 0, KEY_QUERY_VALUE | KEY_WOW64_32KEY, &steamRegKey))
{
pathLen = MAX_OSPATH;
if (RegQueryValueEx(steamRegKey, "InstallLocation", NULL, NULL, (LPBYTE)steamPath, &pathLen))
steamPath[0] = '\0';
RegCloseKey(steamRegKey);
}
#endif
#ifdef STEAMPATH_NAME
if (!steamPath[0] && !RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Valve\\Steam", 0, KEY_QUERY_VALUE, &steamRegKey))
{
pathLen = MAX_OSPATH;
if (RegQueryValueEx(steamRegKey, "SteamPath", NULL, NULL, (LPBYTE)steamPath, &pathLen))
if (RegQueryValueEx(steamRegKey, "InstallPath", NULL, NULL, (LPBYTE)steamPath, &pathLen))
steamPath[0] = '\0';
if (steamPath[0])
finishPath = qtrue;
RegCloseKey(steamRegKey);
}
#endif
if (steamPath[0])
{
if (pathLen == MAX_OSPATH)
pathLen--;
steamPath[pathLen] = '\0';
if (finishPath)
Q_strcat(steamPath, MAX_OSPATH, "\\SteamApps\\common\\" STEAMPATH_NAME );
}
#endif
return steamPath;
}
/*
================
Sys_GogPath
================
*/
char *Sys_GogPath( void )
{
#ifdef GOGPATH_ID
HKEY gogRegKey;
DWORD pathLen = MAX_OSPATH;
if (!gogPath[0] && !RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\GOG.com\\Games\\" GOGPATH_ID, 0, KEY_QUERY_VALUE | KEY_WOW64_32KEY, &gogRegKey))
{
pathLen = MAX_OSPATH;
if (RegQueryValueEx(gogRegKey, "PATH", NULL, NULL, (LPBYTE)gogPath, &pathLen))
gogPath[0] = '\0';
RegCloseKey(gogRegKey);
}
if (gogPath[0])
{
if (pathLen == MAX_OSPATH)
pathLen--;
gogPath[pathLen] = '\0';
}
#endif
return gogPath;
}
/*
================
Sys_MicrosoftStorePath
================
*/
char* Sys_MicrosoftStorePath(void)
{
#ifdef MSSTORE_PATH
typedef int ( __stdcall *SHGetFolderPath_f )( HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPSTR pszPath );
if (!microsoftStorePath[0])
{
TCHAR szPath[MAX_PATH];
SHGetFolderPath_f qSHGetFolderPath;
HMODULE shfolder = LoadLibrary("shfolder.dll");
if(shfolder == NULL)
{
Com_Printf("Unable to load SHFolder.dll\n");
return microsoftStorePath;
}
qSHGetFolderPath = (SHGetFolderPath_f)GetProcAddress(shfolder, "SHGetFolderPathA");
if ( qSHGetFolderPath == NULL )
{
Com_Printf("Unable to find SHGetFolderPath in SHFolder.dll\n");
FreeLibrary(shfolder);
return microsoftStorePath;
}
if( !SUCCEEDED( qSHGetFolderPath( NULL, CSIDL_PROGRAM_FILES,
NULL, 0, szPath ) ) )
{
Com_Printf("Unable to detect CSIDL_PROGRAM_FILES\n");
FreeLibrary(shfolder);
return microsoftStorePath;
}
FreeLibrary(shfolder);
// default: C:\Program Files\ModifiableWindowsApps\Quake 3\EN
Com_sprintf(microsoftStorePath, sizeof(microsoftStorePath), "%s%cModifiableWindowsApps%c%s%cEN", szPath, PATH_SEP, PATH_SEP, MSSTORE_PATH, PATH_SEP);
}
#endif
return microsoftStorePath;
}
static const char *Sys_GetConfigurationValue( const char *key, const char *defaultValue ) {
HKEY hKey;
DWORD pathLen = MAX_OSPATH;
static char buffer[MAX_OSPATH];
static char *result = buffer;
if ( !RegOpenKeyEx( HKEY_CURRENT_USER, "SOFTWARE\\" PRODUCT_NAME, 0, KEY_QUERY_VALUE, &hKey ) ) {
pathLen = MAX_OSPATH;
if ( RegQueryValueEx( hKey, key, NULL, NULL, ( LPBYTE )buffer, &pathLen ) ) {
result = NULL;
}
RegCloseKey( hKey );
}
return result ? result : defaultValue;
}
static qboolean Sys_SetConfigurationValue( const char *key, const char *value ) {
HKEY hKey;
DWORD count = MAX_OSPATH, dontCare;
static char buffer[MAX_OSPATH];
qboolean result = qtrue;
if ( RegOpenKeyEx( HKEY_CURRENT_USER, "SOFTWARE\\" PRODUCT_NAME, 0, KEY_SET_VALUE, &hKey ) != ERROR_SUCCESS ) {
if ( RegCreateKeyEx( HKEY_CURRENT_USER, "SOFTWARE\\" PRODUCT_NAME, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, &dontCare ) != ERROR_SUCCESS ) {
return qfalse;
}
}
count = value ? strlen( value ) : 0;
if ( RegSetValueExA( hKey, key, 0, REG_SZ, ( const BYTE * )value, count ) != ERROR_SUCCESS ) {
result = qfalse;
}
RegCloseKey( hKey );
return result;
}
static const char *s_locateDirInitialFolder = NULL;
static int CALLBACK BrowseNotify(HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpData)
{
if ( uMsg == BFFM_INITIALIZED ) {
if ( s_locateDirInitialFolder != NULL ) {
SendMessage( hWnd, BFFM_SETSELECTION, 1, ( LPARAM )s_locateDirInitialFolder );
}
return 1;
}
return 0;
}
const char *Sys_LocateDir( const char *title, const char *initialDir ) {
static char buffer[ MAX_PATH ] = { 0 };
const char *result = NULL;
LPITEMIDLIST pIDL;
BROWSEINFO bi;
if ( OleInitialize( NULL ) != S_OK ) {
return NULL;
}
s_locateDirInitialFolder = initialDir;
memset( &bi, 0, sizeof( bi ) );
bi.ulFlags = BIF_USENEWUI;
bi.lpszTitle = title;
bi.lpfn = BrowseNotify;
pIDL = SHBrowseForFolder( &bi );
if ( pIDL != NULL ) {
if ( SHGetPathFromIDList( pIDL, buffer ) != 0 ) {
result = buffer;
}
CoTaskMemFree( pIDL );
}
OleUninitialize();
return result;
}
struct FileChecksum {
const char* filename;
unsigned int checksum;
};
static FileChecksum s_pakChecksum[] = {
"pak0.pk3", 0xc6554342,
"pak1.pk3", 0x6181a134,
"pak2.pk3", 0x7fad00a1,
"pak3.pk3", 0x28ab3fc4,
"pak4.pk3", 0xf5327c65,
"pak5.pk3", 0x2331ccda,
"pak6.pk3", 0x0dce205d,
"pak7.pk3", 0xda616bca,
"pak8.pk3", 0x08215426,
};
unsigned int CRC32_HashFile(const char* filePath);
qboolean Sys_VerifyChecksums( const char *quake3path ) {
char buf[MAX_PATH];
for ( int i = 0; i < ARRAY_LEN( s_pakChecksum ); i++ ) {
sprintf( buf, "%s/baseq3/%s", quake3path, s_pakChecksum[i].filename );
if ( CRC32_HashFile(buf) != s_pakChecksum[i].checksum ) {
return qfalse;
}
}
return qtrue;
}
qboolean Sys_LocateQ3APath( void ) {
int result;
result = MessageBoxA( g_wv.hWnd,
"Quake III Arena installation path is not found.\n"
"You must have Quake III Arena installed to play Blood Run.\n"
"Please install Quake III Arena from Steam, GOG or Microsoft Store.\n"
"Alternatively, you can provide Quake III Arena installation directory.\n"
"Would you like to choose Quake III Arena installation directory?",
"Information", MB_YESNO | MB_ICONEXCLAMATION );
if ( result == IDYES ) {
choosedir:
const char *quake3path = Sys_GetConfigurationValue( "QuakeIIIArenaPath", NULL );
const char *selectedPath = Sys_LocateDir( "Please choose your Quake III Arena installation path", quake3path );
Sys_SetConfigurationValue( "QuakeIIIArenaPath", selectedPath );
if ( !Sys_VerifyChecksums( selectedPath ) ) {
result = MessageBoxA( g_wv.hWnd,
"The path specified is not a correct Quake III Arena installation path.\n"
"Please check that pak0-8.pk3 files are presented and not corrupted.\n"
"Would you like to choose another directory?",
"Information", MB_YESNO | MB_ICONEXCLAMATION );
if ( result == IDYES ) {
goto choosedir;
}
}
MessageBoxA( g_wv.hWnd, "Please restart the game", PRODUCT_NAME, MB_ICONINFORMATION | MB_OK );
return qtrue;
}
return qfalse;
}
void Sys_FindQ3APath( void ) {
const char* quake3path;
quake3path = Sys_GetConfigurationValue( "QuakeIIIArenaPath", "" );
if ( quake3path[0] ) {
Cvar_Set( "fs_q3apath", quake3path );
Com_Printf( "Quake III Arena is found at %s\n", quake3path );
return;
}
quake3path = Sys_SteamPath();
if ( quake3path[0] ) {
Cvar_Set( "fs_q3apath", quake3path );
Com_Printf( "Steam version of Quake III Arena is found at %s\n", quake3path );
return;
}
quake3path = Sys_GogPath();
if ( quake3path[0] ) {
Cvar_Set( "fs_q3apath", quake3path );
Com_Printf( "GOG version of Quake III Arena is found at %s\n", quake3path );
return;
}
quake3path = Sys_MicrosoftStorePath();
if ( quake3path[0] ) {
Cvar_Set( "fs_q3apath", quake3path );
Com_Printf( "Microsoft Store version of Quake III Arena is found at %s\n", quake3path );
return;
}
}
| 411 | 0.921941 | 1 | 0.921941 | game-dev | MEDIA | 0.747774 | game-dev | 0.544585 | 1 | 0.544585 |
acmeism/RosettaCodeData | 4,495 | Task/Pig-the-dice-game-Player/Java/pig-the-dice-game-player-1.java | import java.util.Scanner;
public class Pigdice {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int players = 0;
//Validate the input
while(true) {
//Get the number of players
System.out.println("Hello, welcome to Pig Dice the game! How many players? ");
if(scan.hasNextInt()) {
//Gotta be more than 0
int nextInt = scan.nextInt();
if(nextInt > 0) {
players = nextInt;
break;
}
}
else {
System.out.println("That wasn't an integer. Try again. \n");
scan.next();
}
}
System.out.println("Alright, starting with " + players + " players. \n");
//Start the game
play(players, scan);
scan.close();
}
public static void play(int group, Scanner scan) {
//Set the number of strategies available.
final int STRATEGIES = 5;
//Construct the dice- accepts an int as an arg for number of sides, but defaults to 6.
Dice dice = new Dice();
//Create an array of players and initialize them to defaults.
Player[] players = new Player[group];
for(int count = 0; count < group; count++) {
players[count] = new Player(count);
System.out.println("Player " + players[count].getNumber() + " is alive! ");
}
/*****Print strategy options here. Modify Player.java to add strategies. *****/
System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: ");
System.out.println(">> Enter '0' for a human player. ");
System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.");
System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. ");
System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. ");
System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. ");
//Get the strategy for each player
for(Player player : players) {
System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? ");
//Validate the strategy is a real strategy.
while(true) {
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if (nextInt < Strategy.STRATEGIES.length) {
player.setStrategy(Strategy.STRATEGIES[nextInt]);
break;
}
}
else {
System.out.println("That wasn't an option. Try again. ");
scan.next();
}
}
}
//Here is where the rules for the game are programmatically defined.
int max = 0;
while(max < 100) {
//Begin the round
for(Player player : players) {
System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. ");
//Set the points for the turn to 0
player.setTurnPoints(0);
//Determine whether the player chooses to roll or hold.
player.setMax(max);
while(true) {
Move choice = player.choose();
if(choice == Move.ROLL) {
int roll = dice.roll();
System.out.println(" A " + roll + " was rolled. ");
player.setTurnPoints(player.getTurnPoints() + roll);
//Increment the player's built in iterator.
player.incIter();
//If the player rolls a 1, their turn is over and they gain 0 points this round.
if(roll == 1) {
player.setTurnPoints(0);
break;
}
}
//Check if the player held or not.
else {
System.out.println(" The player has held. ");
break;
}
}
//End the turn and add any accumulated points to the player's pool.
player.addPoints(player.getTurnPoints());
System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n");
//Reset the player's built in iterator.
player.resetIter();
//Update the max score if necessary.
if(max < player.getPoints()) {
max = player.getPoints();
}
//If someone won, stop the game and announce the winner.
if(max >= 100) {
System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: ");
//Announce the final scores.
for(Player p : players) {
System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. ");
}
break;
}
}
}
}
}
| 411 | 0.723094 | 1 | 0.723094 | game-dev | MEDIA | 0.864467 | game-dev | 0.698216 | 1 | 0.698216 |
mpc-msri/EzPC | 6,450 | GPU-MPC/ext/sytorch/examples/vgg16.cpp | // Authors: Kanav Gupta, Neha Jawalkar
// Copyright:
//
// Copyright (c) 2024 Microsoft Research
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <sytorch/layers/layers.h>
#include <sytorch/module.h>
#include <sytorch/utils.h>
template <typename T>
class VGG16 : public SytorchModule<T>
{
using SytorchModule<T>::add;
public:
Conv2D<T> *conv0;
ReLU<T> *relu1;
Conv2D<T> *conv2;
MaxPool2D<T> *maxpool3;
ReLU<T> *relu4;
Conv2D<T> *conv5;
ReLU<T> *relu6;
Conv2D<T> *conv7;
MaxPool2D<T> *maxpool8;
ReLU<T> *relu9;
Conv2D<T> *conv10;
ReLU<T> *relu11;
Conv2D<T> *conv12;
ReLU<T> *relu13;
Conv2D<T> *conv14;
MaxPool2D<T> *maxpool15;
ReLU<T> *relu16;
Conv2D<T> *conv17;
ReLU<T> *relu18;
Conv2D<T> *conv19;
ReLU<T> *relu20;
Conv2D<T> *conv21;
MaxPool2D<T> *maxpool22;
ReLU<T> *relu23;
Conv2D<T> *conv24;
ReLU<T> *relu25;
Conv2D<T> *conv26;
ReLU<T> *relu27;
Conv2D<T> *conv28;
MaxPool2D<T> *maxpool29;
ReLU<T> *relu30;
Flatten<T> *reshape31;
FC<T> *gemm32;
ReLU<T> *relu33;
FC<T> *gemm34;
ReLU<T> *relu35;
FC<T> *gemm36;
public:
VGG16()
{
conv0 = new Conv2D<T>(3, 64, 3, 1, 1, true);
relu1 = new ReLU<T>();
conv2 = new Conv2D<T>(64, 64, 3, 1, 1, true);
maxpool3 = new MaxPool2D<T>(2, 0, 2);
relu4 = new ReLU<T>();
conv5 = new Conv2D<T>(64, 128, 3, 1, 1, true);
relu6 = new ReLU<T>();
conv7 = new Conv2D<T>(128, 128, 3, 1, 1, true);
maxpool8 = new MaxPool2D<T>(2, 0, 2);
relu9 = new ReLU<T>();
conv10 = new Conv2D<T>(128, 256, 3, 1, 1, true);
relu11 = new ReLU<T>();
conv12 = new Conv2D<T>(256, 256, 3, 1, 1, true);
relu13 = new ReLU<T>();
conv14 = new Conv2D<T>(256, 256, 3, 1, 1, true);
maxpool15 = new MaxPool2D<T>(2, 0, 2);
relu16 = new ReLU<T>();
conv17 = new Conv2D<T>(256, 512, 3, 1, 1, true);
relu18 = new ReLU<T>();
conv19 = new Conv2D<T>(512, 512, 3, 1, 1, true);
relu20 = new ReLU<T>();
conv21 = new Conv2D<T>(512, 512, 3, 1, 1, true);
maxpool22 = new MaxPool2D<T>(2, 0, 2);
relu23 = new ReLU<T>();
conv24 = new Conv2D<T>(512, 512, 3, 1, 1, true);
relu25 = new ReLU<T>();
conv26 = new Conv2D<T>(512, 512, 3, 1, 1, true);
relu27 = new ReLU<T>();
conv28 = new Conv2D<T>(512, 512, 3, 1, 1, true);
maxpool29 = new MaxPool2D<T>(2, 0, 2);
relu30 = new ReLU<T>();
reshape31 = new Flatten<T>();
gemm32 = new FC<T>(25088, 4096, true);
relu33 = new ReLU<T>();
gemm34 = new FC<T>(4096, 4096, true);
relu35 = new ReLU<T>();
gemm36 = new FC<T>(4096, 1000, true);
}
Tensor<T> &_forward(Tensor<T> &input)
{
auto &var35 = conv0->forward(input);
auto &var36 = relu1->forward(var35);
auto &var37 = conv2->forward(var36);
auto &var38 = maxpool3->forward(var37);
auto &var39 = relu4->forward(var38);
auto &var40 = conv5->forward(var39);
auto &var41 = relu6->forward(var40);
auto &var42 = conv7->forward(var41);
auto &var43 = maxpool8->forward(var42);
auto &var44 = relu9->forward(var43);
auto &var45 = conv10->forward(var44);
auto &var46 = relu11->forward(var45);
auto &var47 = conv12->forward(var46);
auto &var48 = relu13->forward(var47);
auto &var49 = conv14->forward(var48);
auto &var50 = maxpool15->forward(var49);
auto &var51 = relu16->forward(var50);
auto &var52 = conv17->forward(var51);
auto &var53 = relu18->forward(var52);
auto &var54 = conv19->forward(var53);
auto &var55 = relu20->forward(var54);
auto &var56 = conv21->forward(var55);
auto &var57 = maxpool22->forward(var56);
auto &var58 = relu23->forward(var57);
auto &var59 = conv24->forward(var58);
auto &var60 = relu25->forward(var59);
auto &var61 = conv26->forward(var60);
auto &var62 = relu27->forward(var61);
auto &var63 = conv28->forward(var62);
auto &var64 = maxpool29->forward(var63);
auto &var65 = relu30->forward(var64);
auto &var66 = reshape31->forward(var65);
auto &var67 = gemm32->forward(var66);
auto &var68 = relu33->forward(var67);
auto &var69 = gemm34->forward(var68);
auto &var70 = relu35->forward(var69);
auto &var71 = gemm36->forward(var70);
return var71;
}
};
int main(int argc, char**__argv){
prngWeights.SetSeed(osuCrypto::toBlock(0, 0));
prngStr.SetSeed(osuCrypto::toBlock(time(NULL)));
srand(time(NULL));
// ClearText<i64>::bw = 64;
const u64 scale = 24;
VGG16<i64> net;
net.init(scale);
net.load("P-VGG16-imgnet-float.dat");
Tensor<i64> input({1, 224, 224, 3});
input.load("2.dat", scale);
net.forward(input);
auto act_2d = net.activation.as_2d();
printf("%d\n", act_2d.data[0]);
// print(net.conv0->activation, scale, 64);
// printf("\n");
// auto w = net.gemm48->weight.as_nd();
// printf("%ld, %ld, %ld\n", w.data[0], w.data[1], w.data[w.size() - 1]);
std::cout << act_2d.argmax(0) + 1 << std::endl;
// printf("%ld\n", net.conv0->activation.data[0]);
return 0;
}
| 411 | 0.609123 | 1 | 0.609123 | game-dev | MEDIA | 0.554656 | game-dev | 0.946057 | 1 | 0.946057 |
magefree/mage | 1,414 | Mage.Sets/src/mage/cards/p/PloKoon.java |
package mage.cards.p;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.continuous.ActivateAbilitiesAnyTimeYouCouldCastInstantEffect;
import mage.abilities.keyword.MeditateAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.SuperType;
import mage.constants.Zone;
/**
*
* @author Styxo
*/
public final class PloKoon extends CardImpl {
public PloKoon(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{3}{W}{W}");
this.supertype.add(SuperType.LEGENDARY);
this.subtype.add(SubType.KELDOR);
this.subtype.add(SubType.JEDI);
this.power = new MageInt(4);
this.toughness = new MageInt(4);
// You may activate meditate abilities any time you could cast an instant.
this.addAbility(new SimpleStaticAbility(new ActivateAbilitiesAnyTimeYouCouldCastInstantEffect(MeditateAbility.class, "meditate abilities")));
// Meditate {1}{W}
this.addAbility(new MeditateAbility(new ManaCostsImpl<>("{1}{W}")));
}
private PloKoon(final PloKoon card) {
super(card);
}
@Override
public PloKoon copy() {
return new PloKoon(this);
}
}
| 411 | 0.898597 | 1 | 0.898597 | game-dev | MEDIA | 0.966762 | game-dev | 0.988715 | 1 | 0.988715 |
ghaffarian/progex | 1,852 | src/main/java/ghaffarian/progex/graphs/pdg/PDNode.java | /*** In The Name of Allah ***/
package ghaffarian.progex.graphs.pdg;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Class type of PDG nodes.
*
* @author Seyed Mohammad Ghaffarian
*/
public class PDNode {
private Map<String, Object> properties;
private Set<String> DEFs, USEs, selfFlows;
public PDNode() {
DEFs = new HashSet<>();
USEs = new HashSet<>();
selfFlows = new HashSet<>();
properties = new HashMap<>();
}
public void setLineOfCode(int line) {
properties.put("line", line);
}
public int getLineOfCode() {
return (Integer) properties.get("line");
}
public void setCode(String code) {
properties.put("code", code);
}
public String getCode() {
return (String) properties.get("code");
}
public boolean addDEF(String var) {
return DEFs.add(var);
}
public boolean hasDEF(String var) {
return DEFs.contains(var);
}
public String[] getAllDEFs() {
return DEFs.toArray(new String[DEFs.size()]);
}
public boolean addUSE(String var) {
return USEs.add(var);
}
public boolean hasUSE(String var) {
return USEs.contains(var);
}
public String[] getAllUSEs() {
return USEs.toArray(new String[USEs.size()]);
}
public boolean addSelfFlow(String var) {
return selfFlows.add(var);
}
public String[] getAllSelfFlows() {
return selfFlows.toArray(new String[selfFlows.size()]);
}
public void setProperty(String key, Object value) {
properties.put(key.toLowerCase(), value);
}
public Object getProperty(String key) {
return properties.get(key.toLowerCase());
}
public Set<String> getAllProperties() {
return properties.keySet();
}
@Override
public String toString() {
int line = (Integer) properties.get("line");
String code = (String) properties.get("code");
return (line + ": " + code);
}
}
| 411 | 0.560917 | 1 | 0.560917 | game-dev | MEDIA | 0.22311 | game-dev | 0.678745 | 1 | 0.678745 |
masumi-network/sokosumi | 1,363 | web-app/src/app/(app)/mcp/components/mcp-page-content.tsx | "use client";
import { useMcpApiKey } from "@/app/components/MCP/use-mcp-api-key";
import { McpActiveKeyView } from "./mcp-active-key-view";
import { McpDisabledKeyState } from "./mcp-disabled-key-state";
import { McpEmptyState } from "./mcp-empty-state";
import { McpErrorState } from "./mcp-error-state";
import { McpLoadingState } from "./mcp-loading-state";
export function McpPageContent({
activeOrganizationId,
}: {
activeOrganizationId: string | null;
}) {
const {
mcpUrl,
isLoading,
error,
generateMcpUrl,
retryLoad,
enableKey,
isKeyExisting,
isKeyDisabled,
} = useMcpApiKey(true, activeOrganizationId);
return (
<div className="space-y-6">
{isLoading && <McpLoadingState />}
{error && <McpErrorState error={error} onRetry={retryLoad} />}
{isKeyDisabled && (
<McpDisabledKeyState
onEnableKey={enableKey}
onGenerateNew={generateMcpUrl}
isLoading={isLoading}
/>
)}
{mcpUrl && (
<McpActiveKeyView
mcpUrl={mcpUrl}
isKeyExisting={isKeyExisting}
onRegenerate={generateMcpUrl}
isLoading={isLoading}
/>
)}
{!isLoading && !error && !isKeyDisabled && !mcpUrl && (
<McpEmptyState onGenerate={generateMcpUrl} isLoading={isLoading} />
)}
</div>
);
}
| 411 | 0.811258 | 1 | 0.811258 | game-dev | MEDIA | 0.150102 | game-dev | 0.868491 | 1 | 0.868491 |
mono/CocosSharp | 32,499 | tests/tests/classes/tests/Box2DTestBet/Farseer Physics Engine 3.3 XNA/Common/Decomposition/SeidelDecomposer.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Common.Decomposition
{
//From the Poly2Tri project by Mason Green: http://code.google.com/p/poly2tri/source/browse?repo=archive#hg/scala/src/org/poly2tri/seidel
/// <summary>
/// Convex decomposition algorithm based on Raimund Seidel's paper "A simple and fast incremental randomized
/// algorithm for computing trapezoidal decompositions and for triangulating polygons"
/// See also: "Computational Geometry", 3rd edition, by Mark de Berg et al, Chapter 6.2
/// "Computational Geometry in C", 2nd edition, by Joseph O'Rourke
/// </summary>
public static class SeidelDecomposer
{
/// <summary>
/// Decompose the polygon into several smaller non-concave polygon.
/// </summary>
/// <param name="vertices">The polygon to decompose.</param>
/// <param name="sheer">The sheer to use. If you get bad results, try using a higher value. The default value is 0.001</param>
/// <returns>A list of triangles</returns>
public static List<Vertices> ConvexPartition(Vertices vertices, float sheer)
{
List<Point> compatList = new List<Point>(vertices.Count);
foreach (Vector2 vertex in vertices)
{
compatList.Add(new Point(vertex.X, vertex.Y));
}
Triangulator t = new Triangulator(compatList, sheer);
List<Vertices> list = new List<Vertices>();
foreach (List<Point> triangle in t.Triangles)
{
Vertices verts = new Vertices(triangle.Count);
foreach (Point point in triangle)
{
verts.Add(new Vector2(point.X, point.Y));
}
list.Add(verts);
}
return list;
}
/// <summary>
/// Decompose the polygon into several smaller non-concave polygon.
/// </summary>
/// <param name="vertices">The polygon to decompose.</param>
/// <param name="sheer">The sheer to use. If you get bad results, try using a higher value. The default value is 0.001</param>
/// <returns>A list of trapezoids</returns>
public static List<Vertices> ConvexPartitionTrapezoid(Vertices vertices, float sheer)
{
List<Point> compatList = new List<Point>(vertices.Count);
foreach (Vector2 vertex in vertices)
{
compatList.Add(new Point(vertex.X, vertex.Y));
}
Triangulator t = new Triangulator(compatList, sheer);
List<Vertices> list = new List<Vertices>();
foreach (Trapezoid trapezoid in t.Trapezoids)
{
Vertices verts = new Vertices();
List<Point> points = trapezoid.Vertices();
foreach (Point point in points)
{
verts.Add(new Vector2(point.X, point.Y));
}
list.Add(verts);
}
return list;
}
}
internal class MonotoneMountain
{
private const float PiSlop = 3.1f;
public List<List<Point>> Triangles;
private HashSet<Point> _convexPoints;
private Point _head;
// Monotone mountain points
private List<Point> _monoPoly;
// Triangles that constitute the mountain
// Used to track which side of the line we are on
private bool _positive;
private int _size;
private Point _tail;
// Almost Pi!
public MonotoneMountain()
{
_size = 0;
_tail = null;
_head = null;
_positive = false;
_convexPoints = new HashSet<Point>();
_monoPoly = new List<Point>();
Triangles = new List<List<Point>>();
}
// Append a point to the list
public void Add(Point point)
{
if (_size == 0)
{
_head = point;
_size = 1;
}
else if (_size == 1)
{
// Keep repeat points out of the list
_tail = point;
_tail.Prev = _head;
_head.Next = _tail;
_size = 2;
}
else
{
// Keep repeat points out of the list
_tail.Next = point;
point.Prev = _tail;
_tail = point;
_size += 1;
}
}
// Remove a point from the list
public void Remove(Point point)
{
Point next = point.Next;
Point prev = point.Prev;
point.Prev.Next = next;
point.Next.Prev = prev;
_size -= 1;
}
// Partition a x-monotone mountain into triangles O(n)
// See "Computational Geometry in C", 2nd edition, by Joseph O'Rourke, page 52
public void Process()
{
// Establish the proper sign
_positive = AngleSign();
// create monotone polygon - for dubug purposes
GenMonoPoly();
// Initialize internal angles at each nonbase vertex
// Link strictly convex vertices into a list, ignore reflex vertices
Point p = _head.Next;
while (p.Neq(_tail))
{
float a = Angle(p);
// If the point is almost colinear with it's neighbor, remove it!
if (a >= PiSlop || a <= -PiSlop || a == 0.0)
Remove(p);
else if (IsConvex(p))
_convexPoints.Add(p);
p = p.Next;
}
Triangulate();
}
private void Triangulate()
{
while (_convexPoints.Count != 0)
{
IEnumerator<Point> e = _convexPoints.GetEnumerator();
e.MoveNext();
Point ear = e.Current;
_convexPoints.Remove(ear);
Point a = ear.Prev;
Point b = ear;
Point c = ear.Next;
List<Point> triangle = new List<Point>(3);
triangle.Add(a);
triangle.Add(b);
triangle.Add(c);
Triangles.Add(triangle);
// Remove ear, update angles and convex list
Remove(ear);
if (Valid(a))
_convexPoints.Add(a);
if (Valid(c))
_convexPoints.Add(c);
}
Debug.Assert(_size <= 3, "Triangulation bug, please report");
}
private bool Valid(Point p)
{
return p.Neq(_head) && p.Neq(_tail) && IsConvex(p);
}
// Create the monotone polygon
private void GenMonoPoly()
{
Point p = _head;
while (p != null)
{
_monoPoly.Add(p);
p = p.Next;
}
}
private float Angle(Point p)
{
Point a = (p.Next - p);
Point b = (p.Prev - p);
return (float)Math.Atan2(a.Cross(b), a.Dot(b));
}
private bool AngleSign()
{
Point a = (_head.Next - _head);
Point b = (_tail - _head);
return Math.Atan2(a.Cross(b), a.Dot(b)) >= 0;
}
// Determines if the inslide angle is convex or reflex
private bool IsConvex(Point p)
{
if (_positive != (Angle(p) >= 0))
return false;
return true;
}
}
// Node for a Directed Acyclic graph (DAG)
internal abstract class Node
{
protected Node LeftChild;
public List<Node> ParentList;
protected Node RightChild;
protected Node(Node left, Node right)
{
ParentList = new List<Node>();
LeftChild = left;
RightChild = right;
if (left != null)
left.ParentList.Add(this);
if (right != null)
right.ParentList.Add(this);
}
public abstract Sink Locate(Edge s);
// Replace a node in the graph with this node
// Make sure parent pointers are updated
public void Replace(Node node)
{
foreach (Node parent in node.ParentList)
{
// Select the correct node to replace (left or right child)
if (parent.LeftChild == node)
parent.LeftChild = this;
else
parent.RightChild = this;
}
ParentList.AddRange(node.ParentList);
}
}
// Directed Acyclic graph (DAG)
// See "Computational Geometry", 3rd edition, by Mark de Berg et al, Chapter 6.2
internal class QueryGraph
{
private Node _head;
public QueryGraph(Node head)
{
_head = head;
}
private Trapezoid Locate(Edge edge)
{
return _head.Locate(edge).Trapezoid;
}
public List<Trapezoid> FollowEdge(Edge edge)
{
List<Trapezoid> trapezoids = new List<Trapezoid>();
trapezoids.Add(Locate(edge));
int j = 0;
while (edge.Q.X > trapezoids[j].RightPoint.X)
{
if (edge.IsAbove(trapezoids[j].RightPoint))
{
trapezoids.Add(trapezoids[j].UpperRight);
}
else
{
trapezoids.Add(trapezoids[j].LowerRight);
}
j += 1;
}
return trapezoids;
}
private void Replace(Sink sink, Node node)
{
if (sink.ParentList.Count == 0)
_head = node;
else
node.Replace(sink);
}
public void Case1(Sink sink, Edge edge, Trapezoid[] tList)
{
YNode yNode = new YNode(edge, Sink.Isink(tList[1]), Sink.Isink(tList[2]));
XNode qNode = new XNode(edge.Q, yNode, Sink.Isink(tList[3]));
XNode node = new XNode(edge.P, Sink.Isink(tList[0]), qNode);
Replace(sink, node);
}
public void Case2(Sink sink, Edge edge, Trapezoid[] tList)
{
YNode yNode = new YNode(edge, Sink.Isink(tList[1]), Sink.Isink(tList[2]));
XNode node = new XNode(edge.P, Sink.Isink(tList[0]), yNode);
Replace(sink, node);
}
public void Case3(Sink sink, Edge edge, Trapezoid[] tList)
{
YNode yNode = new YNode(edge, Sink.Isink(tList[0]), Sink.Isink(tList[1]));
Replace(sink, yNode);
}
public void Case4(Sink sink, Edge edge, Trapezoid[] tList)
{
YNode yNode = new YNode(edge, Sink.Isink(tList[0]), Sink.Isink(tList[1]));
XNode qNode = new XNode(edge.Q, yNode, Sink.Isink(tList[2]));
Replace(sink, qNode);
}
}
internal class Sink : Node
{
public Trapezoid Trapezoid;
private Sink(Trapezoid trapezoid)
: base(null, null)
{
Trapezoid = trapezoid;
trapezoid.Sink = this;
}
public static Sink Isink(Trapezoid trapezoid)
{
if (trapezoid.Sink == null)
return new Sink(trapezoid);
return trapezoid.Sink;
}
public override Sink Locate(Edge edge)
{
return this;
}
}
// See "Computational Geometry", 3rd edition, by Mark de Berg et al, Chapter 6.2
internal class TrapezoidalMap
{
// Trapezoid container
public HashSet<Trapezoid> Map;
// AABB margin
// Bottom segment that spans multiple trapezoids
private Edge _bCross;
// Top segment that spans multiple trapezoids
private Edge _cross;
private float _margin;
public TrapezoidalMap()
{
Map = new HashSet<Trapezoid>();
_margin = 50.0f;
_bCross = null;
_cross = null;
}
public void Clear()
{
_bCross = null;
_cross = null;
}
// Case 1: segment completely enclosed by trapezoid
// break trapezoid into 4 smaller trapezoids
public Trapezoid[] Case1(Trapezoid t, Edge e)
{
Trapezoid[] trapezoids = new Trapezoid[4];
trapezoids[0] = new Trapezoid(t.LeftPoint, e.P, t.Top, t.Bottom);
trapezoids[1] = new Trapezoid(e.P, e.Q, t.Top, e);
trapezoids[2] = new Trapezoid(e.P, e.Q, e, t.Bottom);
trapezoids[3] = new Trapezoid(e.Q, t.RightPoint, t.Top, t.Bottom);
trapezoids[0].UpdateLeft(t.UpperLeft, t.LowerLeft);
trapezoids[1].UpdateLeftRight(trapezoids[0], null, trapezoids[3], null);
trapezoids[2].UpdateLeftRight(null, trapezoids[0], null, trapezoids[3]);
trapezoids[3].UpdateRight(t.UpperRight, t.LowerRight);
return trapezoids;
}
// Case 2: Trapezoid contains point p, q lies outside
// break trapezoid into 3 smaller trapezoids
public Trapezoid[] Case2(Trapezoid t, Edge e)
{
Point rp;
if (e.Q.X == t.RightPoint.X)
rp = e.Q;
else
rp = t.RightPoint;
Trapezoid[] trapezoids = new Trapezoid[3];
trapezoids[0] = new Trapezoid(t.LeftPoint, e.P, t.Top, t.Bottom);
trapezoids[1] = new Trapezoid(e.P, rp, t.Top, e);
trapezoids[2] = new Trapezoid(e.P, rp, e, t.Bottom);
trapezoids[0].UpdateLeft(t.UpperLeft, t.LowerLeft);
trapezoids[1].UpdateLeftRight(trapezoids[0], null, t.UpperRight, null);
trapezoids[2].UpdateLeftRight(null, trapezoids[0], null, t.LowerRight);
_bCross = t.Bottom;
_cross = t.Top;
e.Above = trapezoids[1];
e.Below = trapezoids[2];
return trapezoids;
}
// Case 3: Trapezoid is bisected
public Trapezoid[] Case3(Trapezoid t, Edge e)
{
Point lp;
if (e.P.X == t.LeftPoint.X)
lp = e.P;
else
lp = t.LeftPoint;
Point rp;
if (e.Q.X == t.RightPoint.X)
rp = e.Q;
else
rp = t.RightPoint;
Trapezoid[] trapezoids = new Trapezoid[2];
if (_cross == t.Top)
{
trapezoids[0] = t.UpperLeft;
trapezoids[0].UpdateRight(t.UpperRight, null);
trapezoids[0].RightPoint = rp;
}
else
{
trapezoids[0] = new Trapezoid(lp, rp, t.Top, e);
trapezoids[0].UpdateLeftRight(t.UpperLeft, e.Above, t.UpperRight, null);
}
if (_bCross == t.Bottom)
{
trapezoids[1] = t.LowerLeft;
trapezoids[1].UpdateRight(null, t.LowerRight);
trapezoids[1].RightPoint = rp;
}
else
{
trapezoids[1] = new Trapezoid(lp, rp, e, t.Bottom);
trapezoids[1].UpdateLeftRight(e.Below, t.LowerLeft, null, t.LowerRight);
}
_bCross = t.Bottom;
_cross = t.Top;
e.Above = trapezoids[0];
e.Below = trapezoids[1];
return trapezoids;
}
// Case 4: Trapezoid contains point q, p lies outside
// break trapezoid into 3 smaller trapezoids
public Trapezoid[] Case4(Trapezoid t, Edge e)
{
Point lp;
if (e.P.X == t.LeftPoint.X)
lp = e.P;
else
lp = t.LeftPoint;
Trapezoid[] trapezoids = new Trapezoid[3];
if (_cross == t.Top)
{
trapezoids[0] = t.UpperLeft;
trapezoids[0].RightPoint = e.Q;
}
else
{
trapezoids[0] = new Trapezoid(lp, e.Q, t.Top, e);
trapezoids[0].UpdateLeft(t.UpperLeft, e.Above);
}
if (_bCross == t.Bottom)
{
trapezoids[1] = t.LowerLeft;
trapezoids[1].RightPoint = e.Q;
}
else
{
trapezoids[1] = new Trapezoid(lp, e.Q, e, t.Bottom);
trapezoids[1].UpdateLeft(e.Below, t.LowerLeft);
}
trapezoids[2] = new Trapezoid(e.Q, t.RightPoint, t.Top, t.Bottom);
trapezoids[2].UpdateLeftRight(trapezoids[0], trapezoids[1], t.UpperRight, t.LowerRight);
return trapezoids;
}
// Create an AABB around segments
public Trapezoid BoundingBox(List<Edge> edges)
{
Point max = edges[0].P + _margin;
Point min = edges[0].Q - _margin;
foreach (Edge e in edges)
{
if (e.P.X > max.X) max = new Point(e.P.X + _margin, max.Y);
if (e.P.Y > max.Y) max = new Point(max.X, e.P.Y + _margin);
if (e.Q.X > max.X) max = new Point(e.Q.X + _margin, max.Y);
if (e.Q.Y > max.Y) max = new Point(max.X, e.Q.Y + _margin);
if (e.P.X < min.X) min = new Point(e.P.X - _margin, min.Y);
if (e.P.Y < min.Y) min = new Point(min.X, e.P.Y - _margin);
if (e.Q.X < min.X) min = new Point(e.Q.X - _margin, min.Y);
if (e.Q.Y < min.Y) min = new Point(min.X, e.Q.Y - _margin);
}
Edge top = new Edge(new Point(min.X, max.Y), new Point(max.X, max.Y));
Edge bottom = new Edge(new Point(min.X, min.Y), new Point(max.X, min.Y));
Point left = bottom.P;
Point right = top.Q;
return new Trapezoid(left, right, top, bottom);
}
}
internal class Point
{
// Pointers to next and previous points in Monontone Mountain
public Point Next, Prev;
public float X, Y;
public Point(float x, float y)
{
X = x;
Y = y;
Next = null;
Prev = null;
}
public static Point operator -(Point p1, Point p2)
{
return new Point(p1.X - p2.X, p1.Y - p2.Y);
}
public static Point operator +(Point p1, Point p2)
{
return new Point(p1.X + p2.X, p1.Y + p2.Y);
}
public static Point operator -(Point p1, float f)
{
return new Point(p1.X - f, p1.Y - f);
}
public static Point operator +(Point p1, float f)
{
return new Point(p1.X + f, p1.Y + f);
}
public float Cross(Point p)
{
return X * p.Y - Y * p.X;
}
public float Dot(Point p)
{
return X * p.X + Y * p.Y;
}
public bool Neq(Point p)
{
return p.X != X || p.Y != Y;
}
public float Orient2D(Point pb, Point pc)
{
float acx = X - pc.X;
float bcx = pb.X - pc.X;
float acy = Y - pc.Y;
float bcy = pb.Y - pc.Y;
return acx * bcy - acy * bcx;
}
}
internal class Edge
{
// Pointers used for building trapezoidal map
public Trapezoid Above;
public float B;
public Trapezoid Below;
// Equation of a line: y = m*x + b
// Slope of the line (m)
// Montone mountain points
public HashSet<Point> MPoints;
public Point P;
public Point Q;
public float Slope;
// Y intercept
public Edge(Point p, Point q)
{
P = p;
Q = q;
if (q.X - p.X != 0)
Slope = (q.Y - p.Y) / (q.X - p.X);
else
Slope = 0;
B = p.Y - (p.X * Slope);
Above = null;
Below = null;
MPoints = new HashSet<Point>();
MPoints.Add(p);
MPoints.Add(q);
}
public bool IsAbove(Point point)
{
return P.Orient2D(Q, point) < 0;
}
public bool IsBelow(Point point)
{
return P.Orient2D(Q, point) > 0;
}
public void AddMpoint(Point point)
{
foreach (Point mp in MPoints)
if (!mp.Neq(point))
return;
MPoints.Add(point);
}
}
internal class Trapezoid
{
public Edge Bottom;
public bool Inside;
public Point LeftPoint;
// Neighbor pointers
public Trapezoid LowerLeft;
public Trapezoid LowerRight;
public Point RightPoint;
public Sink Sink;
public Edge Top;
public Trapezoid UpperLeft;
public Trapezoid UpperRight;
public Trapezoid(Point leftPoint, Point rightPoint, Edge top, Edge bottom)
{
LeftPoint = leftPoint;
RightPoint = rightPoint;
Top = top;
Bottom = bottom;
UpperLeft = null;
UpperRight = null;
LowerLeft = null;
LowerRight = null;
Inside = true;
Sink = null;
}
// Update neighbors to the left
public void UpdateLeft(Trapezoid ul, Trapezoid ll)
{
UpperLeft = ul;
if (ul != null) ul.UpperRight = this;
LowerLeft = ll;
if (ll != null) ll.LowerRight = this;
}
// Update neighbors to the right
public void UpdateRight(Trapezoid ur, Trapezoid lr)
{
UpperRight = ur;
if (ur != null) ur.UpperLeft = this;
LowerRight = lr;
if (lr != null) lr.LowerLeft = this;
}
// Update neighbors on both sides
public void UpdateLeftRight(Trapezoid ul, Trapezoid ll, Trapezoid ur, Trapezoid lr)
{
UpperLeft = ul;
if (ul != null) ul.UpperRight = this;
LowerLeft = ll;
if (ll != null) ll.LowerRight = this;
UpperRight = ur;
if (ur != null) ur.UpperLeft = this;
LowerRight = lr;
if (lr != null) lr.LowerLeft = this;
}
// Recursively trim outside neighbors
public void TrimNeighbors()
{
if (Inside)
{
Inside = false;
if (UpperLeft != null) UpperLeft.TrimNeighbors();
if (LowerLeft != null) LowerLeft.TrimNeighbors();
if (UpperRight != null) UpperRight.TrimNeighbors();
if (LowerRight != null) LowerRight.TrimNeighbors();
}
}
// Determines if this point lies inside the trapezoid
public bool Contains(Point point)
{
return (point.X > LeftPoint.X && point.X < RightPoint.X && Top.IsAbove(point) && Bottom.IsBelow(point));
}
public List<Point> Vertices()
{
List<Point> verts = new List<Point>(4);
verts.Add(LineIntersect(Top, LeftPoint.X));
verts.Add(LineIntersect(Bottom, LeftPoint.X));
verts.Add(LineIntersect(Bottom, RightPoint.X));
verts.Add(LineIntersect(Top, RightPoint.X));
return verts;
}
private Point LineIntersect(Edge edge, float x)
{
float y = edge.Slope * x + edge.B;
return new Point(x, y);
}
// Add points to monotone mountain
public void AddPoints()
{
if (LeftPoint != Bottom.P)
{
Bottom.AddMpoint(LeftPoint);
}
if (RightPoint != Bottom.Q)
{
Bottom.AddMpoint(RightPoint);
}
if (LeftPoint != Top.P)
{
Top.AddMpoint(LeftPoint);
}
if (RightPoint != Top.Q)
{
Top.AddMpoint(RightPoint);
}
}
}
internal class XNode : Node
{
private Point _point;
public XNode(Point point, Node lChild, Node rChild)
: base(lChild, rChild)
{
_point = point;
}
public override Sink Locate(Edge edge)
{
if (edge.P.X >= _point.X)
// Move to the right in the graph
return RightChild.Locate(edge);
// Move to the left in the graph
return LeftChild.Locate(edge);
}
}
internal class YNode : Node
{
private Edge _edge;
public YNode(Edge edge, Node lChild, Node rChild)
: base(lChild, rChild)
{
_edge = edge;
}
public override Sink Locate(Edge edge)
{
if (_edge.IsAbove(edge.P))
// Move down the graph
return RightChild.Locate(edge);
if (_edge.IsBelow(edge.P))
// Move up the graph
return LeftChild.Locate(edge);
// s and segment share the same endpoint, p
if (edge.Slope < _edge.Slope)
// Move down the graph
return RightChild.Locate(edge);
// Move up the graph
return LeftChild.Locate(edge);
}
}
internal class Triangulator
{
// Trapezoid decomposition list
public List<Trapezoid> Trapezoids;
public List<List<Point>> Triangles;
// Initialize trapezoidal map and query structure
private Trapezoid _boundingBox;
private List<Edge> _edgeList;
private QueryGraph _queryGraph;
private float _sheer = 0.001f;
private TrapezoidalMap _trapezoidalMap;
private List<MonotoneMountain> _xMonoPoly;
public Triangulator(List<Point> polyLine, float sheer)
{
_sheer = sheer;
Triangles = new List<List<Point>>();
Trapezoids = new List<Trapezoid>();
_xMonoPoly = new List<MonotoneMountain>();
_edgeList = InitEdges(polyLine);
_trapezoidalMap = new TrapezoidalMap();
_boundingBox = _trapezoidalMap.BoundingBox(_edgeList);
_queryGraph = new QueryGraph(Sink.Isink(_boundingBox));
Process();
}
// Build the trapezoidal map and query graph
private void Process()
{
foreach (Edge edge in _edgeList)
{
List<Trapezoid> traps = _queryGraph.FollowEdge(edge);
// Remove trapezoids from trapezoidal Map
foreach (Trapezoid t in traps)
{
_trapezoidalMap.Map.Remove(t);
bool cp = t.Contains(edge.P);
bool cq = t.Contains(edge.Q);
Trapezoid[] tList;
if (cp && cq)
{
tList = _trapezoidalMap.Case1(t, edge);
_queryGraph.Case1(t.Sink, edge, tList);
}
else if (cp && !cq)
{
tList = _trapezoidalMap.Case2(t, edge);
_queryGraph.Case2(t.Sink, edge, tList);
}
else if (!cp && !cq)
{
tList = _trapezoidalMap.Case3(t, edge);
_queryGraph.Case3(t.Sink, edge, tList);
}
else
{
tList = _trapezoidalMap.Case4(t, edge);
_queryGraph.Case4(t.Sink, edge, tList);
}
// Add new trapezoids to map
foreach (Trapezoid y in tList)
{
_trapezoidalMap.Map.Add(y);
}
}
_trapezoidalMap.Clear();
}
// Mark outside trapezoids
foreach (Trapezoid t in _trapezoidalMap.Map)
{
MarkOutside(t);
}
// Collect interior trapezoids
foreach (Trapezoid t in _trapezoidalMap.Map)
{
if (t.Inside)
{
Trapezoids.Add(t);
t.AddPoints();
}
}
// Generate the triangles
CreateMountains();
}
// Build a list of x-monotone mountains
private void CreateMountains()
{
foreach (Edge edge in _edgeList)
{
if (edge.MPoints.Count > 2)
{
MonotoneMountain mountain = new MonotoneMountain();
// Sorting is a perfromance hit. Literature says this can be accomplised in
// linear time, although I don't see a way around using traditional methods
// when using a randomized incremental algorithm
// Insertion sort is one of the fastest algorithms for sorting arrays containing
// fewer than ten elements, or for lists that are already mostly sorted.
List<Point> points = new List<Point>(edge.MPoints);
points.Sort((p1, p2) => p1.X.CompareTo(p2.X));
foreach (Point p in points)
mountain.Add(p);
// Triangulate monotone mountain
mountain.Process();
// Extract the triangles into a single list
foreach (List<Point> t in mountain.Triangles)
{
Triangles.Add(t);
}
_xMonoPoly.Add(mountain);
}
}
}
// Mark the outside trapezoids surrounding the polygon
private void MarkOutside(Trapezoid t)
{
if (t.Top == _boundingBox.Top || t.Bottom == _boundingBox.Bottom)
t.TrimNeighbors();
}
// Create segments and connect end points; update edge event pointer
private List<Edge> InitEdges(List<Point> points)
{
List<Edge> edges = new List<Edge>();
for (int i = 0; i < points.Count - 1; i++)
{
edges.Add(new Edge(points[i], points[i + 1]));
}
edges.Add(new Edge(points[0], points[points.Count - 1]));
return OrderSegments(edges);
}
private List<Edge> OrderSegments(List<Edge> edgeInput)
{
// Ignore vertical segments!
List<Edge> edges = new List<Edge>();
foreach (Edge e in edgeInput)
{
Point p = ShearTransform(e.P);
Point q = ShearTransform(e.Q);
// Point p must be to the left of point q
if (p.X > q.X)
{
edges.Add(new Edge(q, p));
}
else if (p.X < q.X)
{
edges.Add(new Edge(p, q));
}
}
// Randomized triangulation improves performance
// See Seidel's paper, or O'Rourke's book, p. 57
Shuffle(edges);
return edges;
}
private static void Shuffle<T>(IList<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
// Prevents any two distinct endpoints from lying on a common vertical line, and avoiding
// the degenerate case. See Mark de Berg et al, Chapter 6.3
private Point ShearTransform(Point point)
{
return new Point(point.X + _sheer * point.Y, point.Y);
}
}
} | 411 | 0.94352 | 1 | 0.94352 | game-dev | MEDIA | 0.52063 | game-dev | 0.993186 | 1 | 0.993186 |
OpenEndedGroup/Field2 | 1,342 | src/main/java/field/graphics/Guard.java | package field.graphics;
import fieldbox.execution.InverseDebugMapping;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Interpose this class between a Scene.Perform and it's Scene to only execute a Scene.Perform is a Function is true. Use this, for example, to
* implement View Frustum Culling or to skip the drawing of a Mesh that has no vertices (which is, in general, not a safe thing to do, because while a
* mesh might have no vertices, it might have some children which have other side-effects)
*/
public class Guard implements Scene.Perform {
private final Supplier<Scene.Perform> p;
private final Function<Integer, Boolean> guard;
public Guard(Scene.Perform p, Function<Integer, Boolean> guard) {
this.p = () -> p;
this.guard = guard;
}
public Guard(Supplier<Scene.Perform> p, Function<Integer, Boolean> guard) {
this.p = p;
this.guard = guard;
}
Scene.Perform last;
@Override
public boolean perform(int pass) {
if (guard.apply(pass)) return (last=p.get()).perform(pass);
else return true;
}
@Override
public int[] getPasses() {
return p.get().getPasses();
}
@Override
public String toString() {
return "Guard("+InverseDebugMapping.describeWithToString(last)+" | "+ InverseDebugMapping.describeWithToString(guard)+")="+InverseDebugMapping.describe(this);
}
}
| 411 | 0.600473 | 1 | 0.600473 | game-dev | MEDIA | 0.352976 | game-dev | 0.790701 | 1 | 0.790701 |
Fewnity/Xenity-Engine | 6,824 | Xenity_Engine/include/bullet/BulletCollision/CollisionDispatch/btCollisionWorldImporter.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2014 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_COLLISION_WORLD_IMPORTER_H
#define BT_COLLISION_WORLD_IMPORTER_H
#include "LinearMath/btTransform.h"
#include "LinearMath/btVector3.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "LinearMath/btHashMap.h"
class btCollisionShape;
class btCollisionObject;
struct btBulletSerializedArrays;
struct ConstraintInput;
class btCollisionWorld;
struct btCollisionShapeData;
class btTriangleIndexVertexArray;
class btStridingMeshInterface;
struct btStridingMeshInterfaceData;
class btGImpactMeshShape;
class btOptimizedBvh;
struct btTriangleInfoMap;
class btBvhTriangleMeshShape;
class btPoint2PointConstraint;
class btHingeConstraint;
class btConeTwistConstraint;
class btGeneric6DofConstraint;
class btGeneric6DofSpringConstraint;
class btSliderConstraint;
class btGearConstraint;
struct btContactSolverInfo;
class btCollisionWorldImporter
{
protected:
btCollisionWorld* m_collisionWorld;
int m_verboseMode;
btAlignedObjectArray<btCollisionShape*> m_allocatedCollisionShapes;
btAlignedObjectArray<btCollisionObject*> m_allocatedRigidBodies;
btAlignedObjectArray<btOptimizedBvh*> m_allocatedBvhs;
btAlignedObjectArray<btTriangleInfoMap*> m_allocatedTriangleInfoMaps;
btAlignedObjectArray<btTriangleIndexVertexArray*> m_allocatedTriangleIndexArrays;
btAlignedObjectArray<btStridingMeshInterfaceData*> m_allocatedbtStridingMeshInterfaceDatas;
btAlignedObjectArray<btCollisionObject*> m_allocatedCollisionObjects;
btAlignedObjectArray<char*> m_allocatedNames;
btAlignedObjectArray<int*> m_indexArrays;
btAlignedObjectArray<short int*> m_shortIndexArrays;
btAlignedObjectArray<unsigned char*> m_charIndexArrays;
btAlignedObjectArray<btVector3FloatData*> m_floatVertexArrays;
btAlignedObjectArray<btVector3DoubleData*> m_doubleVertexArrays;
btHashMap<btHashPtr,btOptimizedBvh*> m_bvhMap;
btHashMap<btHashPtr,btTriangleInfoMap*> m_timMap;
btHashMap<btHashString,btCollisionShape*> m_nameShapeMap;
btHashMap<btHashString,btCollisionObject*> m_nameColObjMap;
btHashMap<btHashPtr,const char*> m_objectNameMap;
btHashMap<btHashPtr,btCollisionShape*> m_shapeMap;
btHashMap<btHashPtr,btCollisionObject*> m_bodyMap;
//methods
char* duplicateName(const char* name);
btCollisionShape* convertCollisionShape( btCollisionShapeData* shapeData );
public:
btCollisionWorldImporter(btCollisionWorld* world);
virtual ~btCollisionWorldImporter();
bool convertAllObjects( btBulletSerializedArrays* arrays);
///delete all memory collision shapes, rigid bodies, constraints etc. allocated during the load.
///make sure you don't use the dynamics world containing objects after you call this method
virtual void deleteAllData();
void setVerboseMode(int verboseMode)
{
m_verboseMode = verboseMode;
}
int getVerboseMode() const
{
return m_verboseMode;
}
// query for data
int getNumCollisionShapes() const;
btCollisionShape* getCollisionShapeByIndex(int index);
int getNumRigidBodies() const;
btCollisionObject* getRigidBodyByIndex(int index) const;
int getNumConstraints() const;
int getNumBvhs() const;
btOptimizedBvh* getBvhByIndex(int index) const;
int getNumTriangleInfoMaps() const;
btTriangleInfoMap* getTriangleInfoMapByIndex(int index) const;
// queris involving named objects
btCollisionShape* getCollisionShapeByName(const char* name);
btCollisionObject* getCollisionObjectByName(const char* name);
const char* getNameForPointer(const void* ptr) const;
///those virtuals are called by load and can be overridden by the user
//bodies
virtual btCollisionObject* createCollisionObject( const btTransform& startTransform, btCollisionShape* shape,const char* bodyName);
///shapes
virtual btCollisionShape* createPlaneShape(const btVector3& planeNormal,btScalar planeConstant);
virtual btCollisionShape* createBoxShape(const btVector3& halfExtents);
virtual btCollisionShape* createSphereShape(btScalar radius);
virtual btCollisionShape* createCapsuleShapeX(btScalar radius, btScalar height);
virtual btCollisionShape* createCapsuleShapeY(btScalar radius, btScalar height);
virtual btCollisionShape* createCapsuleShapeZ(btScalar radius, btScalar height);
virtual btCollisionShape* createCylinderShapeX(btScalar radius,btScalar height);
virtual btCollisionShape* createCylinderShapeY(btScalar radius,btScalar height);
virtual btCollisionShape* createCylinderShapeZ(btScalar radius,btScalar height);
virtual btCollisionShape* createConeShapeX(btScalar radius,btScalar height);
virtual btCollisionShape* createConeShapeY(btScalar radius,btScalar height);
virtual btCollisionShape* createConeShapeZ(btScalar radius,btScalar height);
virtual class btTriangleIndexVertexArray* createTriangleMeshContainer();
virtual btBvhTriangleMeshShape* createBvhTriangleMeshShape(btStridingMeshInterface* trimesh, btOptimizedBvh* bvh);
virtual btCollisionShape* createConvexTriangleMeshShape(btStridingMeshInterface* trimesh);
#ifdef SUPPORT_GIMPACT_SHAPE_IMPORT
virtual btGImpactMeshShape* createGimpactShape(btStridingMeshInterface* trimesh);
#endif //SUPPORT_GIMPACT_SHAPE_IMPORT
virtual btStridingMeshInterfaceData* createStridingMeshInterfaceData(btStridingMeshInterfaceData* interfaceData);
virtual class btConvexHullShape* createConvexHullShape();
virtual class btCompoundShape* createCompoundShape();
virtual class btScaledBvhTriangleMeshShape* createScaledTrangleMeshShape(btBvhTriangleMeshShape* meshShape,const btVector3& localScalingbtBvhTriangleMeshShape);
virtual class btMultiSphereShape* createMultiSphereShape(const btVector3* positions,const btScalar* radi,int numSpheres);
virtual btTriangleIndexVertexArray* createMeshInterface(btStridingMeshInterfaceData& meshData);
///acceleration and connectivity structures
virtual btOptimizedBvh* createOptimizedBvh();
virtual btTriangleInfoMap* createTriangleInfoMap();
};
#endif //BT_WORLD_IMPORTER_H
| 411 | 0.790243 | 1 | 0.790243 | game-dev | MEDIA | 0.945259 | game-dev | 0.77583 | 1 | 0.77583 |
jzyong/GameAI4j | 6,486 | src/main/java/com/jzy/ai/steer/behaviors/CollisionAvoidance.java | /*******************************************************************************
* Copyright 2014 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jzy.ai.steer.behaviors;
import com.jzy.ai.steer.*;
import com.jzy.javalib.math.geometry.Vector;
/** {@code CollisionAvoidance} behavior steers the owner to avoid obstacles lying in its path. An obstacle is any object that can be
* approximated by a circle (or sphere, if you are working in 3D).
* <p>
* This implementation uses collision prediction working out the closest approach of two agents and determining if their distance
* at this point is less than the sum of their bounding radius. For avoiding groups of characters, averaging positions and
* velocities do not work well with this approach. Instead, the algorithm needs to search for the character whose closest approach
* will occur first and to react to this character only. Once this imminent collision is avoided, the steering behavior can then
* react to more distant characters.
* <p>
* This algorithm works well with small and/or moving obstacles whose shape can be approximately represented by a center and a
* radius.
*
* @param <T> Type of vector, either 2D or 3D, implementing the {@link Vector} interface
*
* @author davebaol */
public class CollisionAvoidance<T extends Vector<T>> extends GroupBehavior<T> implements Proximity.ProximityCallback<T> {
private float shortestTime;
private Steerable<T> firstNeighbor;
private float firstMinSeparation;
private float firstDistance;
private T firstRelativePosition;
private T firstRelativeVelocity;
private T relativePosition;
private T relativeVelocity;
/** Creates a {@code CollisionAvoidance} behavior for the specified owner and proximity.
* @param owner the owner of this behavior
* @param proximity the proximity of this behavior. */
public CollisionAvoidance(Steerable<T> owner, Proximity<T> proximity) {
super(owner, proximity);
this.firstRelativePosition = newVector(owner);
this.firstRelativeVelocity = newVector(owner);
this.relativeVelocity = newVector(owner);
}
@Override
protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) {
shortestTime = Float.POSITIVE_INFINITY;
firstNeighbor = null;
firstMinSeparation = 0;
firstDistance = 0;
relativePosition = steering.linear;
// Take into consideration each neighbor to find the most imminent collision.
int neighborCount = proximity.findNeighbors(this);
// If we have no target, then return no steering acceleration
//
// NOTE: You might think that the condition below always evaluates to true since
// firstNeighbor has been set to null when entering this method. In fact, we have just
// executed findNeighbors(this) that has possibly set firstNeighbor to a non null value
// through the method reportNeighbor defined below.
if (neighborCount == 0 || firstNeighbor == null) return steering.setZero();
// If we're going to hit exactly, or if we're already
// colliding, then do the steering based on current position.
if (firstMinSeparation <= 0 || firstDistance < owner.getBoundingRadius() + firstNeighbor.getBoundingRadius()) {
relativePosition.set(firstNeighbor.getPosition()).sub(owner.getPosition());
} else {
// Otherwise calculate the future relative position
relativePosition.set(firstRelativePosition).mulAdd(firstRelativeVelocity, shortestTime);
}
// Avoid the target
// Notice that steerling.linear and relativePosition are the same vector
relativePosition.nor().scl(-getActualLimiter().getMaxLinearAcceleration());
// No angular acceleration
steering.angular = 0f;
// Output the steering
return steering;
}
@Override
public boolean reportNeighbor (Steerable<T> neighbor) {
// Calculate the time to collision
relativePosition.set(neighbor.getPosition()).sub(owner.getPosition());
relativeVelocity.set(neighbor.getLinearVelocity()).sub(owner.getLinearVelocity());
float relativeSpeed2 = relativeVelocity.len2();
// Collision can't happen when the agents have the same linear velocity.
// Also, note that timeToCollision would be NaN due to the indeterminate form 0/0 and,
// since any comparison involving NaN returns false, it would become the shortestTime,
// so defeating the algorithm.
if (relativeSpeed2 == 0) return false;
float timeToCollision = -relativePosition.dot(relativeVelocity) / relativeSpeed2;
// If timeToCollision is negative, i.e. the owner is already moving away from the the neighbor,
// or it's not the most imminent collision then no action needs to be taken.
if (timeToCollision <= 0 || timeToCollision >= shortestTime) return false;
// Check if it is going to be a collision at all
float distance = relativePosition.len();
float minSeparation = distance - (float)Math.sqrt(relativeSpeed2) * timeToCollision /* shortestTime */;
if (minSeparation > owner.getBoundingRadius() + neighbor.getBoundingRadius()) return false;
// Store most imminent collision data
shortestTime = timeToCollision;
firstNeighbor = neighbor;
firstMinSeparation = minSeparation;
firstDistance = distance;
firstRelativePosition.set(relativePosition);
firstRelativeVelocity.set(relativeVelocity);
return true;
}
//
// Setters overridden in order to fix the correct return type for chaining
//
@Override
public CollisionAvoidance<T> setOwner (Steerable<T> owner) {
this.owner = owner;
return this;
}
@Override
public CollisionAvoidance<T> setEnabled (boolean enabled) {
this.enabled = enabled;
return this;
}
/** Sets the limiter of this steering behavior. The given limiter must at least take care of the maximum linear acceleration.
* @return this behavior for chaining. */
@Override
public CollisionAvoidance<T> setLimiter (Limiter limiter) {
this.limiter = limiter;
return this;
}
}
| 411 | 0.969123 | 1 | 0.969123 | game-dev | MEDIA | 0.782263 | game-dev | 0.978887 | 1 | 0.978887 |
ericraio/vanilla-wow-addons | 4,202 | b/BigWigs/ZG/Marli.lua | ------------------------------
-- Are you local? --
------------------------------
local boss = AceLibrary("Babble-Boss-2.2")["High Priestess Mar'li"]
local L = AceLibrary("AceLocale-2.2"):new("BigWigs"..boss)
local lastdrain = 0
----------------------------
-- Localization --
----------------------------
L:RegisterTranslations("enUS", function() return {
cmd = "Marli",
spider_cmd = "spider",
spider_name = "Spider Alert",
spider_desc = "Warn when spiders spawn",
drain_cmd = "drain",
drain_name = "Drain Alert",
drain_desc = "Warn for life drain",
spiders_trigger = "Aid me my brood!$",
drainlife_trigger = "^High Priestess Mar'li's Drain Life heals High Priestess Mar'li for (.+).",
spiders_message = "Spiders spawned!",
drainlife_message = "High Priestess Mar'li is draining life!",
} end )
L:RegisterTranslations("deDE", function() return {
spider_name = "Spinnen",
spider_desc = "Warnung, wenn Hohepriesterin Mar'li Spinnen beschw\195\182rt.",
drain_name = "Blutsauger",
drain_desc = "Warnung, wenn Hohepriesterin Mar'li sich heilt.",
spiders_trigger = "Helft mir, meine Brut!$",
drainlife_trigger = "^High Priestess Mar'li's Drain Life heals High Priestess Mar'li for (.+).", -- ?
spiders_message = "Spinnen beschworen!",
drainlife_message = "Mar'li heilt sich!",
} end )
L:RegisterTranslations("frFR", function() return {
spider_name = "Alerte Araign\195\169e",
spider_desc = "Pr\195\169viens du pop d'araign\195\169e.",
drain_name = "Alerte Drain",
drain_desc = "Pr\195\169viens d'un drain en cours.",
spiders_trigger = "., mes enfants !$",
drainlife_trigger = "^Drain de vie DE Grande pr\195\170tresse Mar'li gu\195\169rit Grande pr\195\170tresse Mar'li de (.+)%.$",
spiders_message = "Araign\195\169e en approche !",
drainlife_message = "Mar'li fait un drain de vie !",
} end )
L:RegisterTranslations("zhCN", function() return {
spider_name = "蜘蛛警报",
spider_desc = "小蜘蛛出现时发出警报",
drain_name = "吸取警报",
drain_desc = "高阶祭司玛尔里使用生命吸取时发出警报",
spiders_trigger = "来为我作战吧,我的孩子们!$",
drainlife_trigger = "^高阶祭司玛尔里的生命吸取治疗了高阶祭司玛尔里(.+)。",
spiders_message = "蜘蛛出现!",
drainlife_message = "高阶祭司玛尔里正在施放生命吸取,赶快打断她!",
} end )
L:RegisterTranslations("zhTW", function() return {
-- Mar'li 高階祭司瑪爾里(哈卡萊安魂者)
spider_name = "蜘蛛警報",
spider_desc = "當高階祭司瑪爾里召喚蜘蛛時發出警報。",
drain_name = "生命吸取警報",
drain_desc = "高階祭司瑪爾里使用生命吸取時發出警報",
spiders_trigger = "來幫助我吧,我的孩子們!$",
drainlife_trigger = "^高階祭司瑪爾里的生命吸取治療了高階祭司瑪爾里(.+)。",
spiders_message = "小蜘蛛出現!",
drainlife_message = "生命吸取!趕快打斷!",
} end )
L:RegisterTranslations("koKR", function() return {
spider_name = "거미 경고",
spider_desc = "거미 소환 시 경고",
drain_name = "흡수 경고",
drain_desc = "생명령 흡수에 대한 경고",
spiders_trigger = "어미를 도와라!$",
drainlife_trigger = "대여사제 말리의 생명력 흡수|1으로;로; 대여사제 말리의 생명력이 (.+)만큼 회복되었습니다.",
spiders_message = "거미 소환!",
drainlife_message = "말리가 생명력을 흡수합니다. 차단해 주세요!",
} end )
----------------------------------
-- Module Declaration --
----------------------------------
BigWigsMarli = BigWigs:NewModule(boss)
BigWigsMarli.zonename = AceLibrary("Babble-Zone-2.2")["Zul'Gurub"]
BigWigsMarli.enabletrigger = boss
BigWigsMarli.toggleoptions = {"spider", "drain", "bosskill"}
BigWigsMarli.revision = tonumber(string.sub("$Revision: 16639 $", 12, -3))
------------------------------
-- Initialization --
------------------------------
function BigWigsMarli:OnEnable()
self:RegisterEvent("CHAT_MSG_MONSTER_YELL")
self:RegisterEvent("CHAT_MSG_COMBAT_HOSTILE_DEATH", "GenericBossDeath")
self:RegisterEvent("CHAT_MSG_SPELL_CREATURE_VS_CREATURE_BUFF")
end
------------------------------
-- Events --
------------------------------
function BigWigsMarli:CHAT_MSG_MONSTER_YELL( msg )
if self.db.profile.spider and string.find(msg, L["spiders_trigger"]) then
self:TriggerEvent("BigWigs_Message", L["spiders_message"], "Attention")
end
end
function BigWigsMarli:CHAT_MSG_SPELL_CREATURE_VS_CREATURE_BUFF( msg )
if self.db.profile.drain and string.find(msg, L["drainlife_trigger"]) and lastdrain < (GetTime()-3) then
lastdrain = GetTime()
self:TriggerEvent("BigWigs_Message", L["drainlife_message"], "Urgent")
end
end
| 411 | 0.545473 | 1 | 0.545473 | game-dev | MEDIA | 0.780127 | game-dev | 0.913037 | 1 | 0.913037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.