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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Mono-94/mVehicle | 2,257 | resources/vehicleSteal/client.lua | local animDictLockPick = "anim@amb@clubhouse@tutorial@bkr_tut_ig3@"
local animLockPick = "machinic_loop_mechandplayer"
lib.callback.register('mVehicle:PlayerItems', function(action, entity)
local ped = cache.ped
if action == 'changeplate' then
if lib.progressBar({
duration = Config.FakePlateItem.ChangePlateTime,
label = locale('fakeplate4'),
useWhileDead = false,
canCancel = true,
disable = {
car = true,
move = true,
},
anim = {
dict = animDictLockPick,
clip = animLockPick,
flag = 1,
},
prop = {
model = 'p_num_plate_01',
pos = vec3(0.0, 0.2, 0.1),
rot = vec3(100, 100.0, 0.0)
},
}) then
return true
else
return false
end
elseif action == 'lockpick' then
if not NetworkDoesNetworkIdExist(entity) then return false end
local vehicle = NetToVeh(entity)
local pedInVehicle = IsPedInVehicle(ped, vehicle)
if pedInVehicle then return end
local coords = GetEntityCoords(vehicle)
local class = GetVehicleClass(vehicle)
local skillCheck = Config.LockPickItem.skillCheck(vehicle, class)
if skillCheck then
Config.LockPickItem.dispatch(cache.serverId, vehicle, coords)
end
SetVehicleNeedsToBeHotwired(vehicle, false)
return skillCheck
elseif action == 'hotwire' then
local vehicle = GetVehiclePedIsIn(ped, false)
if not vehicle then return false end
local pedInVehicle = IsPedInVehicle(ped, vehicle, -1)
if not pedInVehicle then return false end
local class = GetVehicleClass(vehicle)
local coords = GetEntityCoords(vehicle)
local skillCheck = Config.HotWireItem.skillCheck(vehicle, class)
if skillCheck then
Config.HotWireItem.dispatch(cache.serverId, vehicle, coords)
SetVehicleEngineOn(vehicle, true, true, true)
end
return skillCheck
end
end)
| 0 | 0.876337 | 1 | 0.876337 | game-dev | MEDIA | 0.955742 | game-dev | 0.919659 | 1 | 0.919659 |
RafaelDeJongh/cap | 11,174 | lua/weapons/weapon_hand_device.lua | /*
Hand Device for GarrysMod10
Copyright (C) 2007
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (StarGate==nil or StarGate.CheckModule==nil or not StarGate.CheckModule("weapon")) then return end
if (SGLanguage!=nil and SGLanguage.GetMessage!=nil) then
SWEP.Category = SGLanguage.GetMessage("weapon_cat");
SWEP.PrintName = SGLanguage.GetMessage("weapon_hand_device");
end
SWEP.Author = "JDM12989 & aVoN";
SWEP.Contact = "";
SWEP.Purpose = "";
SWEP.Instructions = "Left Click = Push/Kill/Rings\nRight Click = Change Mode";
SWEP.Base = "weapon_base";
SWEP.Slot = 3;
SWEP.SlotPos = 3;
SWEP.DrawAmmo = true;
SWEP.DrawCrosshair = true;
SWEP.ViewModel = "models/weapons/v_models/v_hdevice.mdl";
SWEP.WorldModel = "models/w_hdevice.mdl";
SWEP.HoldType = "slam"
-- primary.
SWEP.Primary.ClipSize = -1;
SWEP.Primary.DefaultClip = 100;
SWEP.Primary.Automatic = true;
SWEP.Primary.Ammo = "Battery";
-- secondary
SWEP.Secondary.ClipSize = -1;
SWEP.Secondary.DefaultClip = -1;
SWEP.Secondary.Automatic = false;
SWEP.Secondary.Ammo = "none";
-- spawnables.
list.Set("CAP.Weapon", SWEP.PrintName or "", SWEP);
--################### Dummys for the client @ aVoN
function SWEP:PrimaryAttack() return false end;
function SWEP:SecondaryAttack() return false end;
-- to cancel out default reload function
function SWEP:Reload() return end;
function SWEP:Initialize()
self:SetWeaponHoldType(self.HoldType)
end
if SERVER then
if (StarGate==nil or StarGate.CheckModule==nil or not StarGate.CheckModule("weapon")) then return end
AddCSLuaFile();
SWEP.Sounds = {
Shot={Sound("weapons/hd_shot1.mp3"),Sound("weapons/hd_shot2.mp3")},
SwitchMode=Sound("buttons/button5.wav"),
};
SWEP.AttackMode = 1;
SWEP.MaxAmmo = 100;
SWEP.Delay = 5;
SWEP.TimeOut = 0.25; -- Time in seconds, a target will be tracked when hit with the beam
--################### Deploay the SWEP @ Gmod4phun
function SWEP:Deploy()
self.Weapon:SendWeaponAnim(ACT_VM_DRAW);
return true
end
--################### Init the SWEP @ jdm12989
function SWEP:Initialize()
self:SetWeaponHoldType("melee");
end
--################### Initialize the shot @ jdm12989
function SWEP:PrimaryAttack(fast)
local ammo = self.Weapon:Clip1();
local delay = 0;
if(self.AttackMode == 1 and ammo >= 20 and not fast) then
self.Weapon:SendWeaponAnim(ACT_VM_PRIMARYATTACK)
timer.Simple( 0.25, function() if (IsValid(self)) then self.Weapon:SendWeaponAnim( ACT_VM_IDLE ) end end)
self.Owner:EmitSound(self.Sounds.Shot[1],90,math.random(96,102));
self:PushEffect();
delay = 0.3;
self.Weapon:SetNextPrimaryFire(CurTime()+0.8);
elseif(self.AttackMode == 2 and ammo >= 3) then
self.Weapon:SendWeaponAnim(ACT_VM_RECOIL1)
timer.Simple( 0.5, function() if (IsValid(self)) then self.Weapon:SendWeaponAnim( ACT_VM_IDLE ) end end)
self.Owner:SetNetworkedBool("shooting_hand",true);
local time = CurTime();
if((self.LastSound or 0)+0.9 < time) then
self.LastSound = time;
self.Owner:EmitSound(self.Sounds.Shot[2],90,math.random(96,102));
end
self.Weapon:SetNextPrimaryFire(CurTime()+0.1);
else
self.Weapon:SetNextPrimaryFire(CurTime()+0.5);
end
local e = self.Weapon;
timer.Simple(delay,
function()
if(IsValid(e) and IsValid(e.Owner)) then
e:DoShoot();
end
end
);
return true;
end
--################### Secondary Attack @ aVoN
function SWEP:SecondaryAttack()
--Change our Mode
local modes = 4; -- When you want to add more modes, jdm...
self.AttackMode = math.Clamp((self.AttackMode+1) % (modes + 1),1,modes);
self:EmitSound(self.Sounds.SwitchMode); -- Make some mode-change sounds
--self.Owner:SetAmmo(self.Secondary.Ammo,self.AttackMode);
self.Weapon:SetNWBool("Mode",self.AttackMode); -- Tell client, what mode we are in
self.Owner.__HandDeviceMode = self.AttackMode; -- So modes are saved accross "session" (if he died it's the last mode he used it before)
end
--################### Reset Mode @ aVoN
function SWEP:OwnerChanged()
self.AttackMode = self.Owner.__HandDeviceMode or 1;
self.Weapon:SetNWBool("Mode",self.AttackMode);
end
--################### Do the shot @ jdm12989
function SWEP:DoShoot()
local p = self.Owner;
if(not IsValid(p)) then return end;
local pos = p:GetShootPos();
local normal = p:GetAimVector();
local ammo = self.Weapon:Clip1();
-- push attack
if(self.AttackMode == 1) then
if(ammo >= 20) then
self:TakePrimaryAmmo(20);
local direction = p:GetForward()*10000;
for _,v in pairs(ents.FindInSphere(pos + (100*normal),75)) do
if(v ~= self.Owner) then
local phys = v:GetPhysicsObject();
if(phys:IsValid()) then
local allow = hook.Call("StarGate.HandDevice.Push",nil,v,p);
if (allow==nil or allow) then
if(v:IsNPC() or v:IsPlayer() and not v:HasGodMode()) then
if(v:IsPlayer()) then
v:SetMoveType(MOVETYPE_WALK);
end
v:SetVelocity(direction);
end
if(v.TakeDamage) then
v:TakeDamage(70,p);
end
phys:ApplyForceOffset(direction,pos);
end
end
end
end
end
elseif(self.AttackMode == 2) then -- Kill-Beam
if(ammo >= 3) then
if(p:GetNetworkedBool("handdevice_depleted",false)) then
p:SetNWBool("handdevice_depleted",false);
end
self:TakePrimaryAmmo(1);
self:KillEffect();
local time = CurTime();
if(not self.Target or (self.LastHit or 0)+self.TimeOut < time) then
self.LastHit = time;
local trace = util.QuickTrace(pos,normal*200,p); -- Limit this to 200 units
if(trace.Hit) then -- We hit someone or something
if(trace.Entity and trace.Entity:IsValid()) then
if(trace.Entity:IsPlayer() or trace.Entity:IsNPC()) then
self.Target = trace.Entity;
end
end
else
self.Target = nil;
end
end
if(IsValid(self.Target)) then
self:TakePrimaryAmmo(2); -- When we hit someone, take 2 additional ammo!
self.Target:TakeDamage(8,p);
if(self.Target:IsPlayer() and not self.Target:HasGodMode()) then
--################### Slowdown
-- Garry fucked up SprintDisable/Enable with the latest updates
--self.Target:SprintDisable();
--timer.Create("StarGate.UnParalyze",4,1,self.Target.SprintEnable,self.Target);
-- I hope this is not interfearing with any gamemodes... Blame garry if the handdevices makes you slow down permanently then!
GAMEMODE:SetPlayerSpeed(self.Target,80,80);
timer.Destroy("StarGate.UnParalyze"); -- Always start a fresh timer!
timer.Create("StarGate.UnParalyze",4,1,function() if IsValid(self.Entity) and IsValid(self.Target) then GAMEMODE:SetPlayerSpeed(self.Target,250,500) end end);
end
else
self.Target = nil;
end
else
p:SetNWBool("handdevice_depleted",true);
end
elseif(self.AttackMode == 3) then -- Call nearest rings
local ring = self:FindClosestRings();
if(IsValid(ring) and not ring.Busy) then
ring.SetRange=0;
ring:Dial("");
self.Weapon:SetNextPrimaryFire(CurTime()+3);
end
elseif(self.AttackMode == 4) then
local ring = self:FindClosestRings();
if(IsValid(ring) and not ring.Busy) then
self.Owner.RingDialEnt = ring;
umsg.Start("RingTransporterShowWindowCap",self.Owner);
umsg.End();
end
end
end
--################### Think @ jdm12989
function SWEP:Think()
if(self.AttackMode == 2 and self.Owner:GetNWBool("shooting_hand",false) and not self.Owner:KeyDown(IN_ATTACK)) then
self.Owner:SetNWBool("shooting_hand",false);
end
local time = CurTime();
if((self.LastThink or 0) + 0.1 < time) then
self.LastThink = time;
--primary reserve
local ammo = self.Owner:GetAmmoCount(self.Primary.Ammo);
if(ammo > self.Delay) then
self.Owner:RemoveAmmo(ammo-self.Delay,self.Primary.Ammo);
end
--primary ammo
local ammo = self.Weapon:Clip1();
local set = math.Clamp(ammo+1,0,self.MaxAmmo);
self.Weapon:SetClip1(set);
end
end
--################### Do a push @ jdm12989
function SWEP:PushEffect()
local e = self.Owner;
-- Timer fixes bug, where you cant see your own effect
timer.Simple(0.1,
function()
if(e and e:IsValid()) then
local fx = EffectData();
fx:SetEntity(e);
fx:SetOrigin(e:GetPos());
util.Effect("hd_push",fx,true,true);
end
end
);
end
-- FIXME: SERIOUSLY, this needs to put into clientside!!!!!
--################### Do the beam effect@aVoN
function SWEP:KillEffect()
local spectating = 1;
if(self.Owner:IsPlayer() and self.Owner:GetViewEntity() == self.Owner) then spectating = 0 end;
local fx = EffectData();
fx:SetScale(spectating);
fx:SetEntity(self.Owner);
fx:SetOrigin(self.Owner:GetShootPos());
util.Effect("hd_kill",fx,true,true);
end
--################### Find Closest Rings @aVoN
function SWEP:FindClosestRings()
local ring;
local pos = self.Owner:GetPos();
local trace = util.TraceLine(util.GetPlayerTrace(self.Owner));
local dist = 100;
-- First check if we are aiming at a ring to call
for _,v in pairs(ents.FindInSphere(trace.HitPos,100)) do
if(v:GetClass():find("ring_base_*") and not v.Busy) then
local len = (trace.HitPos-v:GetPos()):Length();
if(len < dist) then
dist = len;
ring = v;
end
end
end
-- Not found a ring? Well, call closest
if(not ring) then
local dist = 500;
for _,v in pairs(ents.FindByClass("ring_base_*")) do
local len = (pos-v:GetPos()):Length();
if(len < dist) then
dist = len;
ring = v;
end
end
end
return ring;
end
end
if CLIENT then
-- Inventory Icon
if(file.Exists("materials/VGUI/weapons/hand_inventory.vmt","GAME")) then
SWEP.WepSelectIcon = surface.GetTextureID("VGUI/weapons/hand_inventory");
end
-- Kill Icon
if(file.Exists("materials/VGUI/weapons/hand_killicon.vmt","GAME")) then
killicon.Add("weapon_hand_device","VGUI/weapons/hand_killicon",Color(255,255,255));
end
if (SGLanguage!=nil and SGLanguage.GetMessage!=nil) then
language.Add("Battery_ammo",SGLanguage.GetMessage("naquadah"));
language.Add("weapon_hand_device",SGLanguage.GetMessage("weapon_hand_device"));
end
--################### Positions the viewmodel correctly @aVoN
function SWEP:GetViewModelPosition(p,a)
p = p - 7*a:Up() - 6*a:Forward() + 1*a:Right();
a:RotateAroundAxis(a:Right(),20);
a:RotateAroundAxis(a:Up(),5);
return p,a;
end
--################### Tell a player how to use this @aVoN
function SWEP:DrawHUD()
local mode = "Push";
local int = self.Weapon:GetNetworkedInt("Mode",1);
if(int == 1) then
mode = "Push";
elseif(int == 2) then
mode = "Cook Brain";
elseif(int == 3) then
mode = "Call Nearest Rings";
elseif(int == 4) then
mode = "Open Ring Dial Menu";
end
draw.WordBox(8,ScrW()-188,ScrH()-120,"Primary: "..mode,"Default",Color(0,0,0,80),Color(255,220,0,220));
end
end | 0 | 0.983167 | 1 | 0.983167 | game-dev | MEDIA | 0.975489 | game-dev | 0.994245 | 1 | 0.994245 |
spartanoah/acrimony-client | 1,412 | net/minecraft/world/gen/feature/WorldGenReed.java | /*
* Decompiled with CFR 0.153-SNAPSHOT (d6f6758-dirty).
*/
package net.minecraft.world.gen.feature;
import java.util.Random;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenerator;
public class WorldGenReed
extends WorldGenerator {
@Override
public boolean generate(World worldIn, Random rand, BlockPos position) {
for (int i = 0; i < 20; ++i) {
BlockPos blockpos1;
BlockPos blockpos = position.add(rand.nextInt(4) - rand.nextInt(4), 0, rand.nextInt(4) - rand.nextInt(4));
if (!worldIn.isAirBlock(blockpos) || worldIn.getBlockState((blockpos1 = blockpos.down()).west()).getBlock().getMaterial() != Material.water && worldIn.getBlockState(blockpos1.east()).getBlock().getMaterial() != Material.water && worldIn.getBlockState(blockpos1.north()).getBlock().getMaterial() != Material.water && worldIn.getBlockState(blockpos1.south()).getBlock().getMaterial() != Material.water) continue;
int j = 2 + rand.nextInt(rand.nextInt(3) + 1);
for (int k = 0; k < j; ++k) {
if (!Blocks.reeds.canBlockStay(worldIn, blockpos)) continue;
worldIn.setBlockState(blockpos.up(k), Blocks.reeds.getDefaultState(), 2);
}
}
return true;
}
}
| 0 | 0.622654 | 1 | 0.622654 | game-dev | MEDIA | 0.997487 | game-dev | 0.852577 | 1 | 0.852577 |
CalamityTeam/CalamityModPublic | 12,578 | Projectiles/Summon/MiniGuardianDefense.cs | using System;
using System.IO;
using CalamityMod.NPCs.Providence;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Projectiles.Summon
{
public class MiniGuardianDefense : ModProjectile, ILocalizedModType
{
public enum MiniDefenderAIState
{
ShieldActive,
ShieldInactive,
Vanity
}
public new string LocalizationCategory => "Projectiles.Summon";
public Player Owner => Main.player[Projectile.owner];
public bool SpawnedFromPSC => Projectile.ai[0] == 1f;
public bool ForcedVanity => SpawnedFromPSC && !Owner.Calamity().profanedCrystalBuffs;
public bool shieldActive => !ForcedVanity && Owner.Calamity().pSoulShieldDurability > 0;
public bool shieldActiveBefore = false;
public MiniDefenderAIState AIState => ForcedVanity ? MiniDefenderAIState.Vanity : (shieldActive ? MiniDefenderAIState.ShieldActive : MiniDefenderAIState.ShieldInactive);
public override void SetStaticDefaults()
{
Main.projFrames[Projectile.type] = 4;
ProjectileID.Sets.TrailCacheLength[Projectile.type] = 4;
ProjectileID.Sets.TrailingMode[Projectile.type] = 0;
ProjectileID.Sets.MinionSacrificable[Projectile.type] = true;
ProjectileID.Sets.MinionTargettingFeature[Projectile.type] = true;
}
public override void SetDefaults()
{
Projectile.netImportant = true;
Projectile.tileCollide = false;
Projectile.width = 62;
Projectile.height = 80;
Projectile.minion = true;
Projectile.friendly = true;
Projectile.penetrate = -1;
}
private void HandleRocks(bool spawnRocks = false, bool yeetRocks = false)
{
if (spawnRocks)
{
//spawn rocks
bool psc = Owner.Calamity().profanedCrystalBuffs;
int rockCount = psc ? 10 : 5;
int[] validRockTypes = psc ? new int[] { 1, 3, 4, 5, 6 } : new int[] { 3, 5, 6 }; //1 and 4 are chonkier and psc pushes shield so it looks less weirdge
float angleVariance = MathHelper.TwoPi / rockCount;
float angle = 0f;
for (int i = 0; i < rockCount; i++)
{
int rockType = validRockTypes[Main.rand.Next(0, validRockTypes.Length)];
var rockyRoad = Projectile.NewProjectileDirect(Projectile.GetSource_FromThis(), Owner.position,
angle.ToRotationVector2() * 8f, ModContent.ProjectileType<MiniGuardianRock>(), 1, 2f, Owner.whoAmI, 0f, angle, rockType);
rockyRoad.originalDamage = Projectile.originalDamage;
angle += angleVariance;
}
}
else if (yeetRocks)
{
//flag the rocks for yeetage
int rock = ModContent.ProjectileType<MiniGuardianRock>();
foreach (var proj in Main.projectile)
{
if (proj.active && proj.owner == Owner.whoAmI && proj.type == rock)
{
proj.ai[0] = 1f;
}
}
}
}
public override void AI()
{
// Despawn properly
if (Owner.Calamity().pSoulGuardians)
Projectile.timeLeft = 2;
if (!Owner.Calamity().pSoulArtifact || Owner.dead || !Owner.active)
{
Owner.Calamity().pSoulGuardians = false;
Projectile.active = false;
return;
}
//dust and framing
Projectile.frameCounter++;
Projectile.frame = Projectile.frameCounter / 6 % Main.projFrames[Projectile.type];
var psc = Owner.Calamity().profanedCrystal;
if (psc && !SpawnedFromPSC || !psc && SpawnedFromPSC)
{
int rock = ModContent.ProjectileType<MiniGuardianRock>();
foreach (var proj in Main.projectile)
{
if (proj.active && proj.owner == Owner.whoAmI && proj.type == rock)
{
proj.active = false;
}
}
Projectile.active = false;
}
var shieldIsActive = shieldActive; //avoid checkiing cooldowns multiple times per frame
bool shouldSpawnRocks = !shieldActiveBefore && shieldIsActive;
bool shouldYeetRocks = shieldActiveBefore && !shieldIsActive;
HandleRocks(shouldSpawnRocks, shouldYeetRocks);
bool shouldDust = shouldSpawnRocks || shouldYeetRocks;
if (shouldDust)
{
for (int i = 0; i < 20; i++)
{
Vector2 dustPos = new Vector2(Owner.Center.X + Main.rand.NextFloat(-10, 10), Owner.Center.Y + Main.rand.NextFloat(-10, 10));
Vector2 velocity = (Owner.Center - dustPos).SafeNormalize(Vector2.Zero);
velocity *= (Main.dayTime || !SpawnedFromPSC) ? 3f : 6.9f;
var dust = Dust.NewDustPerfect(Owner.Center, ProvUtils.GetDustID((float)((Main.dayTime || !SpawnedFromPSC) ? Providence.BossMode.Day : Providence.BossMode.Night)), velocity, 0, default(Color), 2f);
if (!Main.dayTime && SpawnedFromPSC)
dust.noGravity = true;
}
}
// Doesn't deal damage directly, damage used for rocks
NPC potentialTarget = Projectile.Center.MinionHoming(1500f, Owner);
Vector2 playerDestination = Owner.Center - Projectile.Center;
switch (AIState)
{
case MiniDefenderAIState.ShieldActive:
case MiniDefenderAIState.ShieldInactive:
if (AIState == MiniDefenderAIState.ShieldInactive) //dust only while inactive
{
for (int i = 0; i < 2; i++)
{
if (!Main.rand.NextBool(3))
continue;
Dust dust = Dust.NewDustDirect(Owner.position, Owner.width, Owner.height, ProvUtils.GetDustID((float)((Main.dayTime || !SpawnedFromPSC) ? Providence.BossMode.Day : Providence.BossMode.Night)));
dust.velocity = Main.rand.NextVector2Circular(3.5f, 3.5f);
dust.velocity.Y -= Main.rand.NextFloat(1f, 3f);
dust.scale = Main.rand.NextFloat(1.15f, 1.45f);
dust.noGravity = true;
}
}
if (potentialTarget != null)
{
Vector2 angle = Owner.Center + Owner.SafeDirectionTo(potentialTarget.Center) * (shieldIsActive ? (Owner.Calamity().profanedCrystalBuffs ? 125f : 75f) : -50f);
playerDestination = angle;
playerDestination.X += Main.rand.NextFloat(-5f, 5f);
playerDestination.Y += Main.rand.NextFloat(-5f, 5f);
}
else
{
playerDestination.X += Main.rand.NextFloat(-10f, 10f) + (75f * (shieldIsActive ? Owner.direction : -Owner.direction));
playerDestination.Y += Main.rand.NextFloat(-10f, 10f);
}
break;
case MiniDefenderAIState.Vanity:
playerDestination.X += Main.rand.NextFloat(-10f, 20f) - (60f * Owner.direction);
playerDestination.Y += Main.rand.NextFloat(-10f, 20f) - 60f;
break;
}
if (potentialTarget != null && AIState != MiniDefenderAIState.Vanity)
{
float dist = Projectile.Center.Distance(playerDestination);
float num543 = playerDestination.X;
float num544 = playerDestination.Y;
float num550 = 40f;
Vector2 vector43 = Projectile.Center;
float num551 = num543 - vector43.X;
float num552 = num544 - vector43.Y;
float num553 = (float)Math.Sqrt((double)(num551 * num551 + num552 * num552));
if (num553 < 100f)
{
num550 = 28f; //14
}
num553 = num550 / num553;
num551 *= num553;
num552 *= num553;
Projectile.velocity.X = (Projectile.velocity.X * 14f + num551) / 13.5f;
Projectile.velocity.Y = (Projectile.velocity.Y * 14f + num552) / 13.5f;
Projectile.velocity *= dist > 10 ? 0.9f : 0.3f;
Projectile.spriteDirection = Projectile.DirectionTo(potentialTarget.Center).X > 0 ? 1 : -1;
}
else
{
float playerDist = playerDestination.Length();
float acceleration = 0.5f;
float returnSpeed = 28f;
// Teleport if too far
if (playerDist > 2000f)
{
Projectile.position = Owner.position;
Projectile.netUpdate = true;
}
// Slow down a lot when close
else if (playerDist < 50f)
{
acceleration = 0.01f;
if (Math.Abs(Projectile.velocity.X) > 2f || Math.Abs(Projectile.velocity.Y) > 2f)
Projectile.velocity *= 0.9f;
}
else
{
if (playerDist < 100f)
acceleration = 0.1f;
if (playerDist > 300f)
acceleration = 1f;
playerDist = returnSpeed / playerDist;
playerDestination *= playerDist;
// Turning (wtf is this)
if (Projectile.velocity.X < playerDestination.X)
{
Projectile.velocity.X += acceleration;
if (acceleration > 0.05f && Projectile.velocity.X < 0f)
Projectile.velocity.X += acceleration;
}
if (Projectile.velocity.X > playerDestination.X)
{
Projectile.velocity.X -= acceleration;
if (acceleration > 0.05f && Projectile.velocity.X > 0f)
Projectile.velocity.X -= acceleration;
}
if (Projectile.velocity.Y < playerDestination.Y)
{
Projectile.velocity.Y += acceleration;
if (acceleration > 0.05f && Projectile.velocity.Y < 0f)
Projectile.velocity.Y += acceleration * 2f;
}
if (Projectile.velocity.Y > playerDestination.Y)
{
Projectile.velocity.Y -= acceleration;
if (acceleration > 0.05f && Projectile.velocity.Y > 0f)
Projectile.velocity.Y -= acceleration * 2f;
}
}
// Direction
if (Math.Abs(Projectile.velocity.X) > 0.2f)
Projectile.direction = Projectile.spriteDirection = Math.Sign(Projectile.velocity.X);
}
Projectile.netUpdate = Projectile.netUpdate || (shieldIsActive != shieldActiveBefore);
shieldActiveBefore = shieldIsActive;
}
public override bool? CanDamage() => false;
public override void SendExtraAI(BinaryWriter writer)
{
writer.Write(shieldActiveBefore);
}
public override void ReceiveExtraAI(BinaryReader reader)
{
shieldActiveBefore = reader.ReadBoolean();
}
public override bool PreDraw(ref Color lightColor)
{
// Has afterimages if maximum empowerment
if (SpawnedFromPSC && !ForcedVanity)
{
CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1);
return false;
}
return true;
}
}
}
| 0 | 0.955146 | 1 | 0.955146 | game-dev | MEDIA | 0.996045 | game-dev | 0.996029 | 1 | 0.996029 |
lukasmonk/lucaschess | 1,154 | Engines/Windows/greko/12/src/moves.h | // GREKO Chess Engine
// (c) 2002-2015 Vladimir Medvedev <vrm@bk.ru>
// http://greko.su
// moves.h: bitboard moves generator
// modified: 21-Apr-2015
#ifndef MOVES_H
#define MOVES_H
#include "position.h"
struct MoveEntry
{
MoveEntry() {}
MoveEntry(Move mv) : m_mv(mv) {}
Move m_mv;
int m_value;
};
class MoveList
{
public:
MoveList() : m_size(0) {}
MoveEntry& operator[] (size_t n) { return m_data[n]; }
const MoveEntry& operator[] (size_t n) const { return m_data[n]; }
void Clear() { m_size = 0; }
void GenAllMoves(const Position& pos);
void GenCaptures(const Position& pos, bool genChecks);
void GenCheckEvasions(const Position& pos);
Move GetNthBest(int n, Move hashMove = 0);
int Size() const { return m_size; }
private:
void Add(FLD from, FLD to, PIECE piece) { m_data[m_size++].m_mv = Move(from, to, piece); }
void Add(FLD from, FLD to, PIECE piece, PIECE captured) { m_data[m_size++].m_mv = Move(from, to, piece, captured); }
void Add(FLD from, FLD to, PIECE piece, PIECE captured, PIECE promotion) { m_data[m_size++].m_mv = Move(from, to, piece, captured, promotion); }
MoveEntry m_data[256];
int m_size;
};
#endif
| 0 | 0.765948 | 1 | 0.765948 | game-dev | MEDIA | 0.578799 | game-dev | 0.891205 | 1 | 0.891205 |
jaredly/terraform | 2,432 | kiss3d-master/src/resource/planar_material_manager.rs | //! A resource manager to load materials.
use builtin::PlanarObjectMaterial;
use resource::PlanarMaterial;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
thread_local!(static KEY_MATERIAL_MANAGER: RefCell<PlanarMaterialManager> = RefCell::new(PlanarMaterialManager::new()));
/// The material manager.
///
/// Upon construction, it contains:
/// * the `object` material, used as the default to render objects.
/// * the `normals` material, used do display an object normals.
///
/// It keeps a cache of already-loaded materials. Note that this is only a cache, nothing more.
/// Thus, its usage is not required to load materials.
pub struct PlanarMaterialManager {
default_material: Rc<RefCell<Box<PlanarMaterial + 'static>>>,
materials: HashMap<String, Rc<RefCell<Box<PlanarMaterial + 'static>>>>,
}
impl PlanarMaterialManager {
/// Creates a new material manager.
pub fn new() -> PlanarMaterialManager {
// load the default ObjectMaterial and the LineMaterial
let mut materials = HashMap::new();
let om = Rc::new(RefCell::new(
Box::new(PlanarObjectMaterial::new()) as Box<PlanarMaterial + 'static>
));
let _ = materials.insert("object".to_string(), om.clone());
PlanarMaterialManager {
default_material: om,
materials: materials,
}
}
/// Mutably applies a function to the material manager.
pub fn get_global_manager<T, F: FnMut(&mut PlanarMaterialManager) -> T>(mut f: F) -> T {
KEY_MATERIAL_MANAGER.with(|manager| f(&mut *manager.borrow_mut()))
}
/// Gets the default material to draw objects.
pub fn get_default(&self) -> Rc<RefCell<Box<PlanarMaterial + 'static>>> {
self.default_material.clone()
}
/// Get a material with the specified name. Returns `None` if the material is not registered.
pub fn get(&mut self, name: &str) -> Option<Rc<RefCell<Box<PlanarMaterial + 'static>>>> {
self.materials.get(&name.to_string()).map(|t| t.clone())
}
/// Adds a material with the specified name to this cache.
pub fn add(&mut self, material: Rc<RefCell<Box<PlanarMaterial + 'static>>>, name: &str) {
let _ = self.materials.insert(name.to_string(), material);
}
/// Removes a mesh from this cache.
pub fn remove(&mut self, name: &str) {
let _ = self.materials.remove(&name.to_string());
}
}
| 0 | 0.927168 | 1 | 0.927168 | game-dev | MEDIA | 0.569182 | game-dev | 0.888683 | 1 | 0.888683 |
captainys/YSFLIGHT | 19,178 | src/dynamics/fsrealprop.cpp | // cl propsim.cpp ..\..\src\fssimplewindow\src\windows\fswin32wrapper.cpp ..\..\src\fssimplewindow\src\windows\fswin32keymap.cpp ..\..\src\ysbitmapfont\src\ysglfontdata.c ..\..\src\ysbitmapfont\src\ysglfontbitmaputil.c ..\..\src\ysbitmapfont\src\ysglusefontbitmap.c -I ..\..\src\fssimplewindow\src ysclass.lib -I ..\..\src\ysbitmapfont\src
#include <stdio.h>
#include <ysclass.h>
#include <fsdef.h>
#include "fsrealprop.h"
#include "fsairproperty.h"
#include "fsutil.h"
FsPropellerEngine::Blade::Blade()
{
Initialize();
}
void FsPropellerEngine::Blade::Initialize(void)
{
area=0.0;
kCl=0.0;
ClZero=0.0;
kCd=0.0;
CdMin=0.0;
minCdAOA=0.0;
pitchChangeSpeed=0.0;
minPitch=0.0;
maxPitch=0.0;
kGoverner=0.0;
gravityCenter=0.0;
liftCenter=0.0;
weight=0.0;
clockwise=YSTRUE; // Direction of rotation must be the property of the blade. Imagine co-axial counter-rotating props.
state.angle=0.0;
state.pitch=0.0;
torque=0.0;
aoa=0.0;
}
YsVec3 FsPropellerEngine::Blade::CalculateForce(const double omega,const double rho,const YsVec3 &relVelInPropCoord)
{
YsVec3 propVel;
const double propSpeed=liftCenter*omega;
const double directionOfRotation=(YSTRUE==clockwise ? -1.0 : 1.0);
propVel.Set(0.0,propSpeed*directionOfRotation,0.0);
propVel.RotateXY(state.angle);
propVel+=relVelInPropCoord;
YsVec3 relVelBlade;
relVelBlade=propVel;
relVelBlade.RotateXY(-state.angle);
aoa=state.pitch-atan2(relVelBlade.z(),-relVelBlade.y());
const double Cl=kCl*aoa+ClZero;
const double Cd=kCd*YsSqr(aoa-minCdAOA)+CdMin;
const double vv=relVelBlade.GetSquareLength();
const double L=0.5*Cl*rho*vv*area;
const double D=0.5*Cd*rho*vv*area;
// printf("%lf %lf\n",L,D);
drag=-D*YsUnitVector(propVel);
lift=YsUnitVector(relVelBlade);
lift.RotateZY(YsPi/2.0);
lift.RotateXY(state.angle);
lift*=L;
// printf("Prop Position=%6.2lfdeg AOA=%6.2lf %s\n",YsRadToDeg(state.angle),YsRadToDeg(aoa),lift.Txt());
return lift+drag;
}
YsVec3 FsPropellerEngine::Blade::GetForceCenterInPropCoord(void) const
{
YsVec3 cen(liftCenter,0.0,0.0);
cen.RotateXY(state.angle);
return cen;
}
const double FsPropellerEngine::Blade::GetMomentOfInertia(void) const
{
return weight*gravityCenter*gravityCenter;
}
////////////////////////////////////////////////////////////
FsPropellerEngine::FsPropellerEngine()
{
Initialize();
}
void FsPropellerEngine::Initialize(void)
{
bladeArray.CleanUp();
engineBrakeTorquePerRpm=0.0;
engineBrakeZeroThrottleRpm=700.0;
engineBrakeMaxThrottleRpm=3000.0;
maxJoulePerSec=0.0;
idleJoulePerSec=0.0;
radianPerSec=0.0;
ctlRadianPerSecMin=YsPi*2.0*500.0/60.0; // 500RPM
ctlRadianPerSecMax=YsPi*2.0*3000.0/60.0; // 3000RPM
sndRPMMin=0.0;
sndRPMMax=0.0;
rho=1.25; // Standard air at mean sea level.
}
void FsPropellerEngine::Move(const YsVec3 &relVelAirframe,const double throttle,const double dt,YSBOOL engineOut)
{
const double airDensityBias=rho/FsGetZeroAirDensity();
const double joulePerSec=(YSTRUE==engineOut ? 0.0 : this->idleJoulePerSec*(1.0-throttle)+this->maxJoulePerSec*throttle)*airDensityBias;
YsVec3 relVelInPropCoord;
relAtt.MulInverse(relVelInPropCoord,relVelAirframe);
double Tsum=0.0;
double Isum=0.0;
for(int bladeIdx=0; bladeIdx<bladeArray.GetN(); ++bladeIdx)
{
YsVec3 f=bladeArray[bladeIdx].CalculateForce(radianPerSec,rho,relVelInPropCoord);
if(YsPi*2.0<bladeArray[bladeIdx].state.angle)
{
bladeArray[bladeIdx].state.angle-=YsPi*2.0;
}
else if(0.0>bladeArray[bladeIdx].state.angle)
{
bladeArray[bladeIdx].state.angle+=YsPi*2.0;
}
const YsVec3 Fxy(f.x(),f.y(),0.0);
const YsVec3 Fcen=bladeArray[bladeIdx].GetForceCenterInPropCoord();
const YsVec3 torqueVec=Fcen^Fxy;
const double torquePerBlade=(YSTRUE==bladeArray[bladeIdx].clockwise ? -torqueVec.z() : torqueVec.z());
Tsum+=torquePerBlade;
Isum+=bladeArray[bladeIdx].GetMomentOfInertia();
bladeArray[bladeIdx].torque=torquePerBlade;
}
if(YsTolerance>Isum) // 2015/04/25 Prevent infinity.
{
Tsum=0.0;
Isum=1.0;
}
if(YsTolerance<engineBrakeTorquePerRpm)
{
const double rpm=fabs(radianPerSec*30.0/YsPi);
const double engineBrakeRpm0=engineBrakeZeroThrottleRpm+(engineBrakeMaxThrottleRpm-engineBrakeZeroThrottleRpm)*throttle;
if(engineBrakeRpm0<rpm)
{
const double excessRpm=rpm-engineBrakeRpm0;
const double engineBrakeTorque=engineBrakeTorquePerRpm*excessRpm;
if(0.0<radianPerSec)
{
Tsum-=engineBrakeTorque;
}
else
{
Tsum+=engineBrakeTorque;
}
}
}
double a=Tsum/Isum;
radianPerSec+=a*dt;
// If the blade happens to be rotating reverse, the engine should descelerate the rotation.
const double E0=0.5*Isum*radianPerSec*radianPerSec;
const double sign=(0.0<radianPerSec ? 1.0 : -1.0);
const double E1=E0+sign*joulePerSec*dt;
const double radianPerSec2=sqrt(fabs(E1)/(0.5*Isum));
if(0.0<radianPerSec*E1) // If E1 sign inverts, it means the direction of rotation changed from negative to positive.
{
radianPerSec=radianPerSec2;
}
else
{
radianPerSec=-radianPerSec2;
}
// 2013/10/15
// Make sure the propeller rotates after torque is calculated.
// Torque must be based on the force and the blade angle at the time when force is calculated.
for(int bladeIdx=0; bladeIdx<bladeArray.GetN(); ++bladeIdx)
{
bladeArray[bladeIdx].state.angle+=radianPerSec*dt;
}
}
void FsPropellerEngine::ControlPitch(double propLeverPosition,double dt)
{
const double desiredRadianPerSec=ctlRadianPerSecMin*(1.0-propLeverPosition)+ctlRadianPerSecMax*propLeverPosition;
const double speedDiff=radianPerSec-desiredRadianPerSec;
for(int idx=0; idx<bladeArray.GetN(); ++idx)
{
const double pitchChange=bladeArray[idx].kGoverner*speedDiff*dt;
bladeArray[idx].state.pitch+=pitchChange;
if(bladeArray[idx].state.pitch<bladeArray[idx].minPitch)
{
bladeArray[idx].state.pitch=bladeArray[idx].minPitch;
}
else if(bladeArray[idx].state.pitch>bladeArray[idx].maxPitch)
{
bladeArray[idx].state.pitch=bladeArray[idx].maxPitch;
}
}
}
void FsPropellerEngine::SetRho(const double rho)
{
this->rho=rho;
}
double FsPropellerEngine::GetConvergentThrust(double &radianPerSecOut,const double throttle,const double rho,const YsVec3 &relVelAirframe,int maxIter,const double dt)
{
State stateSave;
SaveState(stateSave);
SetRho(rho);
// Let's start from 1500RPM=1500*YsPi*2.0 radian per min=1500*YsPi*2.0/60.0 radian per sec
radianPerSec=1500.0*YsPi*2.0/60.0;
double thrust=0.0,prevThrust=0.0;
for(int iter=0; iter<maxIter; ++iter)
{
Move(relVelAirframe,throttle,dt,YSFALSE);
thrust=0.0;
for(auto &blade : bladeArray)
{
thrust+=blade.lift.z()+blade.drag.z();
}
const double diff=fabs(thrust-prevThrust)/YsGreater(fabs(thrust),fabs(prevThrust));
if(0.01>diff)
{
// printf("Converged at %d iterations.\n",iter);
break;
}
prevThrust=thrust;
}
radianPerSecOut=radianPerSec;
// printf("%d rpm\n",(int)(radianPerSec*60.0/(YsPi*2.0)));
RestoreState(stateSave);
return thrust;
}
const YsVec3 FsPropellerEngine::GetForce(void) const
{
YsVec3 force=YsOrigin();
for(auto &blade : bladeArray)
{
force+=blade.lift+blade.drag;
}
relAtt.Mul(force,force);
return force;
}
void FsPropellerEngine::GetRPMRangeForSoundEffect(double &min,double &max) const
{
min=sndRPMMin;
max=sndRPMMax;
}
const char * const FsPropellerEngine::keyWordSource[]=
{
"NBLADE", // 0 1 argument. Number of blades.
"AREAPERBLADE", // 1 1 argument. Blade area.
"CL", // 2 4 argument. aoa Cl1 aoa2 Cl2
"CD", // 3 4 argument. aoaMinCd minCd aoa2 Cd2
"PITCHCHGRATE", // 4 1 argument. Maximum angular velocity that the blade can change pitch. (per sec)
"MINPITCH", // 5 1 argument. Minimum propeller pitch.
"MAXPITCH", // 6 1 argument. Maximum propeller pitch.
"KGOVERNER", // 7 1 argument. Governer const. Defines the reaction speed of the propeller governer.
"GRAVITYCENTER", // 8 1 argument. Distance from the rotation axis
"LIFTCENTER", // 9 1 argument. Distance from the rotation axis
"WEIGHTPERBLADE", // 10 1 argument. The weight of one blade.
"CLOCKWISE", // 11 1 argument. This engine rotates clockwise. Argument is the zero-based blade index.
"COUNTERCLOCKWISE",// 12 1 argument. This engine rotates counter-clockwise. Argument is the zero-based blade index.
"MAXPOWER", // 13 1 argument. Maximum Power Output.
"IDLEPOWER", // 14 1 argument. Idle Power Output.
"RPMCTLRANGE", // 15 2 arguments. RPM minimum and maximum for propeller control.
"SNDRPMRANGE", // 16 2 arguments. RPM minimum and maximum for propeller sound effect.
"ENGBRKTRQRPM", // 17 1 argment. Torque (Nm) from engine brake per excess RPM.
"ENGBRK0THRRPM", // 18 1 argument. RPM at which the engine wants to spin at zero throttle.
"ENGBRKMAXTHRRPM", // 19 1 argument. RPM at which the engine wants to spin at max throttle.
NULL
};
YsKeyWordList FsPropellerEngine::keyWordList;
YsString FsPropellerEngine::MakeShortFormat(const YsString &str)
{
if(keyWordList.GetN()==0)
{
keyWordList.MakeList(keyWordSource);
}
YsString shortFormat;
for(YSSIZE_T ptr=0; ptr<str.Strlen(); ++ptr)
{
if('A'<=str[ptr] && str[ptr]<='Z')
{
YsString nextWord;
YSSIZE_T wordLen=0;
while(wordLen+ptr<str.Strlen() && str[ptr+wordLen]!=' ' && str[ptr+wordLen]!='\t')
{
nextWord.Append(str[ptr+wordLen]);
++wordLen;
}
ptr=ptr+wordLen-1;
auto cmdIdx=keyWordList.GetId(nextWord);
if(0<=cmdIdx)
{
nextWord.Printf("*%d",(int)cmdIdx);
}
shortFormat.Append(nextWord);
}
else
{
shortFormat.Append(str[ptr]);
}
}
return shortFormat;
}
YSRESULT FsPropellerEngine::SendCommand(YSSIZE_T ac,const YsString av[])
{
YsArray <const char *> argv(ac,NULL);
for(YSSIZE_T idx=0; idx<ac; ++idx)
{
argv[idx]=av[idx];
}
return SendCommand(ac,argv);
}
YSRESULT FsPropellerEngine::SendCommand(YSSIZE_T ac,const char *const av[])
{
if(0>=ac)
{
return YSOK;
}
if(keyWordList.GetN()==0)
{
keyWordList.MakeList(keyWordSource);
}
int cmd=-1;
if('*'==av[0][0])
{
cmd=atoi(av[0]+1);
}
else
{
cmd=keyWordList.GetId(av[0]);
}
if(0>cmd)
{
return YSERR;
}
switch(cmd)
{
case 0: // "NBLADE",
if(2<=ac)
{
const int nBlade=atoi(av[1]);
bladeArray.Set(nBlade,NULL);
int n=0;
for(auto &blade : bladeArray)
{
blade.Initialize();
blade.state.angle=YsPi*2.0*(double)n/(double)nBlade;
++n;
}
}
else
{
YsPrintf("Too few arguments for %s\n",(const char *)av[0]);
return YSERR;
}
break;
case 1: // "AREAPERBLADE",
if(2<=ac)
{
double bladeArea;
if(YSOK==FsGetArea(bladeArea,av[1]))
{
for(auto &blade : bladeArray)
{
blade.area=bladeArea;
}
}
else
{
return YSERR;
}
}
else
{
return YSERR;
}
break;
case 2: // "CL",
if(5<=ac)
{
double aoa0;
double aoa1;
if(YSOK==FsGetAngle(aoa0,av[1]) && YSOK==FsGetAngle(aoa1,av[3]))
{
const double cl0=atof(av[2]);
const double cl1=atof(av[4]);
const double kCl=(cl1-cl0)/(aoa1-aoa0);
const double ClZero=cl0-kCl*aoa0;
for(auto &blade : bladeArray)
{
blade.kCl=kCl;
blade.ClZero=ClZero;
}
}
else
{
return YSERR;
}
}
else
{
return YSERR;
}
break;
case 3: // "CD",
if(5<=ac)
{
double minCdAOA;
double aoa1;
if(YSOK==FsGetAngle(minCdAOA,av[1]) && YSOK==FsGetAngle(aoa1,av[3]))
{
const double CdMin=atof(av[2]);
const double cd1=atof(av[4]);
// cd=CdMin+kCd*(aoa-minCdAOA)^2
const double dAOA=aoa1-minCdAOA;
const double kCd=(cd1-CdMin)/(dAOA*dAOA);
for(auto &blade : bladeArray)
{
blade.kCd=kCd;
blade.CdMin=CdMin;
blade.minCdAOA=minCdAOA;
}
}
else
{
return YSERR;
}
}
else
{
return YSERR;
}
break;
case 4: // "PITCHCHGRATE",
if(2<=ac)
{
double pitchChangeSpeed;
if(YSOK==FsGetAngle(pitchChangeSpeed,av[1]))
{
for(auto &blade : bladeArray)
{
blade.pitchChangeSpeed=pitchChangeSpeed;
}
}
else
{
return YSERR;
}
}
else
{
return YSERR;
}
break;
case 5: // "MINPITCH",
if(2<=ac)
{
double minPitch;
if(YSOK==FsGetAngle(minPitch,av[1]))
{
for(auto &blade : bladeArray)
{
blade.minPitch=minPitch;
blade.state.pitch=(blade.minPitch+blade.maxPitch)/2.0;
}
}
else
{
return YSERR;
}
}
else
{
return YSERR;
}
break;
case 6: // "MAXPITCH",
if(2<=ac)
{
double maxPitch;
if(YSOK==FsGetAngle(maxPitch,av[1]))
{
for(auto &blade : bladeArray)
{
blade.maxPitch=maxPitch;
blade.state.pitch=(blade.minPitch+blade.maxPitch)/2.0;
}
}
else
{
return YSERR;
}
}
else
{
return YSERR;
}
break;
case 7: // "KGOVERNER",
if(2<=ac)
{
double kGoverner=atof(av[1]);
for(auto &blade : bladeArray)
{
blade.kGoverner=kGoverner;
}
}
break;
case 8: // "GRAVITYCENTER", // Distance from the rotation axis
if(2<=ac)
{
double gravityCenter;
if(YSOK==FsGetLength(gravityCenter,av[1]))
{
for(auto &blade : bladeArray)
{
blade.gravityCenter=gravityCenter;
}
}
else
{
return YSERR;
}
}
else
{
return YSERR;
}
break;
case 9: // "LIFTCENTER", // Distance from the rotation axis
if(2<=ac)
{
double liftCenter;
if(YSOK==FsGetLength(liftCenter,av[1]))
{
for(auto &blade : bladeArray)
{
blade.liftCenter=liftCenter;
}
}
else
{
return YSERR;
}
}
else
{
return YSERR;
}
break;
case 10: // "WEIGHTPERBLADE",
if(2<=ac)
{
double weight;
if(YSOK==FsGetWeight(weight,av[1]))
{
for(auto &blade : bladeArray)
{
blade.weight=weight;
}
}
else
{
return YSERR;
}
}
else
{
return YSERR;
}
break;
case 11: // "CLOCKWISE",
if(2<=ac)
{
const int bladeIndex=atoi(av[1]);
if(YSTRUE==bladeArray.IsInRange(bladeIndex))
{
bladeArray[bladeIndex].clockwise=YSTRUE;
}
}
break;
case 12: // "COUNTERCLOCKWISE",
if(2<=ac)
{
const int bladeIndex=atoi(av[1]);
if(YSTRUE==bladeArray.IsInRange(bladeIndex))
{
bladeArray[bladeIndex].clockwise=YSFALSE;
}
}
break;
case 13: // "MAXPOWER"
if(2<=ac)
{
double power;
if(YSOK==FsGetJoulePerSecond(power,av[1]))
{
maxJoulePerSec=power;
}
else
{
return YSERR;
}
}
break;
case 14: // "IDLEPOWER"
if(2<=ac)
{
double power;
if(YSOK==FsGetJoulePerSecond(power,av[1]))
{
idleJoulePerSec=power;
}
else
{
return YSERR;
}
}
break;
case 15: // "RPMCTLRANGE", // 2 arguments. RPM minimum and maximum for propeller control.
if(3<=ac)
{
ctlRadianPerSecMin=atof(av[1])*YsPi*2.0/60.0;
ctlRadianPerSecMax=atof(av[2])*YsPi*2.0/60.0;
}
break;
case 16: // "SNDRPMRANGE", // 2 arguments. RPM minimum and maximum for propeller sound effect.
if(3<=ac)
{
sndRPMMin=atof(av[1]);
sndRPMMax=atof(av[2]);
}
break;
case 17: // "ENGBRKTRQRPM", // 17 1 argment. Torque from engine brake per excess RPM.
if(2<=ac)
{
engineBrakeTorquePerRpm=atof(av[1]);
}
break;
case 18: // "ENGBRK0THRRPM", // 18 1 argument. RPM at which the engine wants to spin at zero throttle.
if(2<=ac)
{
engineBrakeZeroThrottleRpm=atof(av[1]);
}
break;
case 19: // "ENGBRKMAXTHRRPM", // 19 1 argument. RPM at which the engine wants to spin at max throttle.
if(2<=ac)
{
engineBrakeMaxThrottleRpm=atof(av[1]);
}
break;
default:
YsPrintf("Unrecognized command sent to FsPropellerEngine.\n");
return YSERR;
}
return YSOK;
}
void FsPropellerEngine::SaveState(State &state) const
{
state.rho=rho;
state.radianPerSec=radianPerSec;
state.bladeStateArray.Set(bladeArray.GetN(),NULL);
for(YSSIZE_T bladeIdx=0; bladeIdx<bladeArray.GetN(); ++bladeIdx)
{
state.bladeStateArray[bladeIdx]=bladeArray[bladeIdx].state;
}
}
void FsPropellerEngine::RestoreState(const State &state)
{
rho=state.rho;
radianPerSec=state.radianPerSec;
for(YSSIZE_T bladeIdx=0; bladeIdx<bladeArray.GetN(); ++bladeIdx)
{
bladeArray[bladeIdx].state=state.bladeStateArray[bladeIdx];
}
}
/* int main(void)
{
FsPropellerEngine prop;
prop.relAtt=YsZeroAtt();
for(int i=0; i<2; ++i)
{
prop.bladeArray.Increment();
prop.bladeArray.GetEnd().clockwise=YSTRUE;
prop.bladeArray.GetEnd().kCl=1.4/YsDegToRad(20.0); // Slope Cl 1.4 per 20 deg, Clark-Y
prop.bladeArray.GetEnd().ClZero=0.35;
prop.bladeArray.GetEnd().minCdAOA=YsDegToRad(-5.0);
prop.bladeArray.GetEnd().CdMin=0.012;
prop.bladeArray.GetEnd().kCd=0.213/(YsSqr(YsDegToRad(25.0)));
prop.bladeArray.GetEnd().pitchChangeSpeed=YsPi; // 180 degree per sec. It moves pretty quickly.
prop.bladeArray.GetEnd().minPitch=YsPi/36.0;
prop.bladeArray.GetEnd().maxPitch=YsPi/4.0;
prop.bladeArray.GetEnd().kGoverner=0.05;
prop.bladeArray.GetEnd().area=0.25; // Something like 0.25m wide 1.0m long
prop.bladeArray.GetEnd().gravityCenter=0.6; // 1m length, probably 60cm off.
prop.bladeArray.GetEnd().liftCenter=0.6; // 1m length, probably 60cm off.
prop.bladeArray.GetEnd().weight=10.0; // Let's say 10kg
prop.bladeArray.GetEnd().state.angle=YsPi*(double)i;
prop.bladeArray.GetEnd().state.pitch=YsDegToRad(18.0);
}
prop.joulePerSec=
double rpm=1000.0;
prop.radianPerSec=(rpm/60.0)*YsPi*2.0;
double desiredRadianPerSec=(1500.0/60.0)*YsPi*2.0;
const double horsePower=160.0;
FsOpenWindow(256,16,800,600,1);
double thr=0.1; // 1.0;
double vel=0.0; // 55.0; // roughly 106kt
for(;;)
{
int key=FsInkey();
if(FSKEY_ESC==key)
{
break;
}
else if(FSKEY_Q==key)
{
thr+=0.05;
}
else if(FSKEY_A==key)
{
thr-=0.05;
}
else if(FSKEY_W==key)
{
vel+=5.0;
}
else if(FSKEY_S==key)
{
vel-=5.0;
}
else if(FSKEY_E==key)
{
desiredRadianPerSec+=(100/60.0)*YsPi*2.0;
}
else if(FSKEY_D==key)
{
desiredRadianPerSec-=(100/60.0)*YsPi*2.0;
}
FsPollDevice();
double dt=1.0/60.0;
const double JperS=horsePower*745.7;
prop.Move(YsVec3(0.0,0.0,vel),thr*JperS,dt);
prop.ControlPitch(desiredRadianPerSec,dt);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
int y=32;
YsString str;
str.Printf("%6.2lf deg/sec %8.2lf RPM",YsRadToDeg(prop.radianPerSec),fabs(prop.radianPerSec*60.0/(YsPi*2.0)));
glRasterPos2d(32,y);
YsGlDrawFontBitmap16x24(str);
y+=24;
str.Printf("Desired %6.2lf RPM",desiredRadianPerSec*60.0/(YsPi*2.0));
glRasterPos2d(32,y);
YsGlDrawFontBitmap16x24(str);
y+=24;
for(int i=0; i<prop.bladeArray.GetN(); ++i)
{
str.Printf("Prop %d Torque %lf Pitch %6.2lf deg\n",i,prop.bladeArray[i].torque,YsRadToDeg(prop.bladeArray[i].state.pitch));
glRasterPos2d(32,y);
YsGlDrawFontBitmap16x24(str);
y+=24;
}
str.Printf("Power %6.2lf\n",thr);
glRasterPos2d(32,y);
YsGlDrawFontBitmap16x24(str);
y+=24;
str.Printf("%6.2lf kt\n",vel*3600/1800);
glRasterPos2d(32,y);
YsGlDrawFontBitmap16x24(str);
y+=24;
FsSwapBuffers();
FsSleep(10);
}
return 0;
} */
| 0 | 0.916635 | 1 | 0.916635 | game-dev | MEDIA | 0.864326 | game-dev | 0.989415 | 1 | 0.989415 |
AK-Saigyouji/Procedural-Cave-Generator | 3,361 | Project/Scripts/Modules - MapGeneration/Editor/Map Gen Window/Global/NodeEditorSettings.cs | using UnityEngine;
using UnityEditor;
using AKSaigyouji.EditorScripting;
namespace AKSaigyouji.Modules.MapGeneration
{
public static class NodeEditorSettings
{
public const int MAJOR_GRID_SPACING = GRID_UNITS_TO_WORLD_UNITS * 50;
public const int MINOR_GRID_SPACING = GRID_UNITS_TO_WORLD_UNITS * 10;
/// <summary>
/// How much space on the UI should represent one unit in the game world.
/// </summary>
public const int GRID_UNITS_TO_WORLD_UNITS = 3;
public const int DEFAULT_NODE_SIZE = 40;
public const int RESIZE_HANDLE_SIZE = 25;
public static GUIStyle SelectedNodeStyle { get { return selectedNodeStyle; } }
public static GUIStyle DefaultNodeStyle { get { return defaultNodeStyle; } }
static readonly GUIStyle selectedNodeStyle;
static readonly GUIStyle defaultNodeStyle;
static readonly RectOffset STYLE_BORDER = new RectOffset(BORDER_SIZE, BORDER_SIZE, BORDER_SIZE, BORDER_SIZE);
const int BORDER_SIZE = 12;
const string DEFAULT_BACKGROUND_PATH = "builtin skins/darkskin/images/node1.png";
const string SELECTED_BACKGROUND_PATH = "builtin skins/darkskin/images/node1 on.png";
const string ROOT_FOLDER = "AKSaigyouji";
const string MODULE_FOLDER = "Compound Modules";
const string MAP_FOLDER = "Maps";
const string CHART_FOLDER = "Charts";
/// <summary>
/// The path to the folder where all assets generated by this project are stored.
/// </summary>
public static string PathToRootFolder
{
get
{
const string parentFolder = "Assets";
string folderName = ROOT_FOLDER;
IOHelpers.RequireFolder(parentFolder, folderName);
return IOHelpers.CombinePath(parentFolder, folderName);
}
}
/// <summary>
/// Folder containing modules produced by the map editor window. Subfolder of the root folder.
/// </summary>
public static string PathToModuleFolder { get { return RequireSubfolder(MODULE_FOLDER); } }
/// <summary>
/// Folder containing maps produced by the map editor window. Subfolder of the root folder.
/// </summary>
public static string PathToMapFolder { get { return RequireSubfolder(MAP_FOLDER); } }
/// <summary>
/// Folder containing charts produced by the ChartBuilder window. Subfolder of the root folder.
/// </summary>
public static string PathToChartFolder { get { return RequireSubfolder(CHART_FOLDER); } }
static NodeEditorSettings()
{
defaultNodeStyle = new GUIStyle();
defaultNodeStyle.normal.background = EditorGUIUtility.Load(DEFAULT_BACKGROUND_PATH) as Texture2D;
defaultNodeStyle.border = STYLE_BORDER;
selectedNodeStyle = new GUIStyle();
selectedNodeStyle.normal.background = EditorGUIUtility.Load(SELECTED_BACKGROUND_PATH) as Texture2D;
selectedNodeStyle.border = STYLE_BORDER;
}
static string RequireSubfolder(string name)
{
string rootPath = PathToRootFolder;
string folderPath = IOHelpers.RequireFolder(rootPath, name);
return folderPath;
}
}
} | 0 | 0.816656 | 1 | 0.816656 | game-dev | MEDIA | 0.621656 | game-dev,desktop-app | 0.915428 | 1 | 0.915428 |
RetroBSD/retrobsd | 3,272 | src/games/sail/pl_6.c | /*
* Copyright (c) 1983 Regents of the University of California.
* All rights reserved. The Berkeley software License Agreement
* specifies the terms and conditions for redistribution.
*/
#include "player.h"
static int
turned()
{
register char *p;
for (p = movebuf; *p; p++)
if (*p == 'r' || *p == 'l')
return 1;
return 0;
}
void
repair()
{
char c;
register char *repairs;
register struct shipspecs *ptr = mc;
register int count;
#define FIX(x, m) (m - ptr->x > count \
? (ptr->x += count, count = 0) : (count -= m - ptr->x, ptr->x = m))
if (repaired || loaded || fired || changed || turned()) {
Signal("No hands free to repair", (struct ship *)0, 0, 0, 0, 0);
return;
}
c = sgetch("Repair (hull, guns, rigging)? ", (struct ship *)0, 1);
switch (c) {
case 'h':
repairs = &mf->RH;
break;
case 'g':
repairs = &mf->RG;
break;
case 'r':
repairs = &mf->RR;
break;
default:
Signal("Avast heaving!", (struct ship *)0, 0, 0, 0, 0);
return;
}
if (++*repairs >= 3) {
count = 2;
switch (c) {
case 'h': {
int max = ptr->guns/4;
if (ptr->hull < max) {
FIX(hull, max);
Write(W_HULL, ms, 0, ptr->hull, 0, 0, 0);
}
break;
}
case 'g':
if (ptr->gunL < ptr->gunR) {
int max = ptr->guns/5 - ptr->carL;
if (ptr->gunL < max) {
FIX(gunL, max);
Write(W_GUNL, ms, 0, ptr->gunL,
ptr->carL, 0, 0);
}
} else {
int max = ptr->guns/5 - ptr->carR;
if (ptr->gunR < max) {
FIX(gunR, max);
Write(W_GUNR, ms, 0, ptr->gunR,
ptr->carR, 0, 0);
}
}
break;
case 'r':
#define X 2
if (ptr->rig4 >= 0 && ptr->rig4 < X) {
FIX(rig4, X);
Write(W_RIG4, ms, 0, ptr->rig4, 0, 0, 0);
}
if (count && ptr->rig3 < X) {
FIX(rig3, X);
Write(W_RIG3, ms, 0, ptr->rig3, 0, 0, 0);
}
if (count && ptr->rig2 < X) {
FIX(rig2, X);
Write(W_RIG2, ms, 0, ptr->rig2, 0, 0, 0);
}
if (count && ptr->rig1 < X) {
FIX(rig1, X);
Write(W_RIG1, ms, 0, ptr->rig1, 0, 0, 0);
}
break;
}
if (count == 2) {
Signal("Repairs completed.", (struct ship *)0, 0, 0, 0, 0);
*repairs = 2;
} else {
*repairs = 0;
blockalarm();
draw_stat();
unblockalarm();
}
}
blockalarm();
draw_slot();
unblockalarm();
repaired = 1;
}
void
loadplayer()
{
int c;
register int loadL, loadR, ready, load;
if (!mc->crew3) {
Signal("Out of crew", (struct ship *)0, 0, 0, 0, 0);
return;
}
loadL = mf->loadL;
loadR = mf->loadR;
if (!loadL && !loadR) {
c = sgetch("Load which broadside (left or right)? ",
(struct ship *)0, 1);
if (c == 'r')
loadL = 1;
else
loadR = 1;
}
if ((!loadL && loadR) || (loadL && !loadR)) {
c = sgetch("Reload with (round, double, chain, grape)? ",
(struct ship *)0, 1);
switch (c) {
case 'r':
load = L_ROUND;
ready = 0;
break;
case 'd':
load = L_DOUBLE;
ready = R_DOUBLE;
break;
case 'c':
load = L_CHAIN;
ready = 0;
break;
case 'g':
load = L_GRAPE;
ready = 0;
break;
default:
Signal("Broadside not loaded.",
(struct ship *)0, 0, 0, 0, 0);
return;
}
if (!loadR) {
mf->loadR = load;
mf->readyR = ready|R_LOADING;
} else {
mf->loadL = load;
mf->readyL = ready|R_LOADING;
}
loaded = 1;
}
}
| 0 | 0.83613 | 1 | 0.83613 | game-dev | MEDIA | 0.740513 | game-dev | 0.907288 | 1 | 0.907288 |
rexrainbow/phaser3-rex-notes | 1,283 | plugins/board/monopoly/Monopoly.d.ts | import ComponentBase from '../../utils/componentbase/ComponentBase';
import { TileXYType } from '../types/Position';
import Board from '../board/Board';
export default Monopoly;
declare namespace Monopoly {
type STOP = -1;
type BLOCKER = null;
type NodeType = {
x: number, y: number,
direction: number
}
type CostCallbackType = (
curTile: NodeType | null, preTile: NodeType | null,
pathFinder: Monopoly
)
=> number | STOP | BLOCKER;
interface IConfig {
face?: number,
pathTileZ?: number,
cost?: number,
costCallback?: CostCallbackType,
costCallbackScope?: object,
}
}
declare class Monopoly<ChessType = Phaser.GameObjects.GameObject> extends ComponentBase {
constructor(
gameObject: ChessType,
config?: Monopoly.IConfig
);
readonly gameObject: ChessType;
readonly board: Board;
setCostFunction(cost: number): this;
setCostFunction(
callback: Monopoly.CostCallbackType,
scope?: object
): this;
setFace(direction: number): this;
getPath(
movingPoints: number,
out?: TileXYType[]
): TileXYType[];
readonly STOP: Monopoly.STOP;
readonly BLOCKER: Monopoly.BLOCKER;
} | 0 | 0.767579 | 1 | 0.767579 | game-dev | MEDIA | 0.752963 | game-dev | 0.826507 | 1 | 0.826507 |
CardboardPowered/cardboard | 10,721 | src/main/java/org/bukkit/craftbukkit/legacy/enums/EnumEvil.java | package org.bukkit.craftbukkit.legacy.enums;
import com.google.common.base.Converter;
import com.google.common.base.Enums;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import org.bukkit.Art;
import org.bukkit.Fluid;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.bukkit.Sound;
import org.bukkit.attribute.Attribute;
import org.bukkit.block.Biome;
import org.bukkit.block.banner.PatternType;
import org.bukkit.craftbukkit.legacy.FieldRename;
import org.bukkit.craftbukkit.legacy.reroute.DoNotReroute;
import org.bukkit.craftbukkit.legacy.reroute.InjectPluginVersion;
import org.bukkit.craftbukkit.legacy.reroute.NotInBukkit;
import org.bukkit.craftbukkit.legacy.reroute.RequireCompatibility;
import org.bukkit.craftbukkit.legacy.reroute.RequirePluginVersion;
import org.bukkit.craftbukkit.legacy.reroute.RerouteArgumentType;
import org.bukkit.craftbukkit.legacy.reroute.RerouteReturnType;
import org.bukkit.craftbukkit.legacy.reroute.RerouteStatic;
import org.bukkit.craftbukkit.util.ApiVersion;
import org.bukkit.craftbukkit.util.ClassTraverser;
import org.bukkit.entity.Cat;
import org.bukkit.entity.Frog;
import org.bukkit.entity.Villager;
import org.bukkit.map.MapCursor;
import org.bukkit.util.OldEnum;
@Deprecated
@NotInBukkit
@RequireCompatibility("enum-compatibility-mode")
@RequirePluginVersion(maxInclusive = "1.20.6")
public class EnumEvil {
private static final Map<Class<?>, LegacyRegistryData> REGISTRIES = new HashMap<>();
static {
// Add Classes which got changed here
REGISTRIES.put(Art.class, new LegacyRegistryData(Registry.ART, Art::valueOf));
REGISTRIES.put(Attribute.class, new LegacyRegistryData(Registry.ATTRIBUTE, Attribute::valueOf));
REGISTRIES.put(Biome.class, new LegacyRegistryData(Registry.BIOME, Biome::valueOf));
REGISTRIES.put(Fluid.class, new LegacyRegistryData(Registry.FLUID, Fluid::valueOf));
REGISTRIES.put(Villager.Type.class, new LegacyRegistryData(Registry.VILLAGER_TYPE, Villager.Type::valueOf));
REGISTRIES.put(Villager.Profession.class, new LegacyRegistryData(Registry.VILLAGER_PROFESSION, Villager.Profession::valueOf));
REGISTRIES.put(Sound.class, new LegacyRegistryData(Registry.SOUNDS, Sound::valueOf));
REGISTRIES.put(Frog.Variant.class, new LegacyRegistryData(Registry.FROG_VARIANT, Frog.Variant::valueOf));
REGISTRIES.put(Cat.Type.class, new LegacyRegistryData(Registry.CAT_VARIANT, Cat.Type::valueOf));
REGISTRIES.put(MapCursor.Type.class, new LegacyRegistryData(Registry.MAP_DECORATION_TYPE, MapCursor.Type::valueOf));
REGISTRIES.put(PatternType.class, new LegacyRegistryData(Registry.BANNER_PATTERN, PatternType::valueOf));
}
public static LegacyRegistryData getRegistryData(Class<?> clazz) {
ClassTraverser it = new ClassTraverser(clazz);
LegacyRegistryData registryData;
while (it.hasNext()) {
registryData = EnumEvil.REGISTRIES.get(it.next());
if (registryData != null) {
return registryData;
}
}
return null;
}
@DoNotReroute
public static Registry<?> getRegistry(Class<?> clazz) {
LegacyRegistryData registryData = EnumEvil.getRegistryData(clazz);
if (registryData != null) {
return registryData.registry();
}
return null;
}
@RerouteStatic("com/google/common/collect/Maps")
@RerouteReturnType("java/util/EnumSet")
public static ImposterEnumMap newEnumMap(Class<?> objectClass) {
return new ImposterEnumMap(objectClass);
}
@RerouteStatic("com/google/common/collect/Maps")
@RerouteReturnType("java/util/EnumSet")
public static ImposterEnumMap newEnumMap(Map map) {
return new ImposterEnumMap(map);
}
@RerouteStatic("com/google/common/collect/Sets")
public static Collector<?, ?, ?> toImmutableEnumSet() {
return Collectors.toUnmodifiableSet();
}
@RerouteStatic("com/google/common/collect/Sets")
@RerouteReturnType("java/util/EnumSet")
public static ImposterEnumSet newEnumSet(Iterable<?> iterable, Class<?> clazz) {
ImposterEnumSet set = ImposterEnumSet.noneOf(clazz);
for (Object some : iterable) {
set.add(some);
}
return set;
}
@RerouteStatic("com/google/common/collect/Sets")
public static ImmutableSet<?> immutableEnumSet(Iterable<?> iterable) {
return ImmutableSet.of(iterable);
}
@RerouteStatic("com/google/common/collect/Sets")
public static ImmutableSet<?> immutableEnumSet(@RerouteArgumentType("java/lang/Enum") Object first, @RerouteArgumentType("[java/lang/Enum") Object... rest) {
return ImmutableSet.of(first, rest);
}
@RerouteStatic("com/google/common/base/Enums")
public static Field getField(@RerouteArgumentType("java/lang/Enum") Object value) {
if (value instanceof Enum eValue) {
return Enums.getField(eValue);
}
try {
return value.getClass().getField(((OldEnum) value).name());
} catch (NoSuchFieldException impossible) {
throw new AssertionError(impossible);
}
}
@RerouteStatic("com/google/common/base/Enums")
public static com.google.common.base.Optional getIfPresent(Class clazz, String name, @InjectPluginVersion ApiVersion apiVersion) {
if (clazz.isEnum()) {
return Enums.getIfPresent(clazz, name);
}
Registry registry = EnumEvil.getRegistry(clazz);
if (registry == null) {
return com.google.common.base.Optional.absent();
}
name = FieldRename.rename(apiVersion, clazz.getName().replace('.', '/'), name);
return com.google.common.base.Optional.fromNullable(registry.get(NamespacedKey.fromString(name.toLowerCase(Locale.ROOT))));
}
@RerouteStatic("com/google/common/base/Enums")
public static Converter stringConverter(Class clazz, @InjectPluginVersion ApiVersion apiVersion) {
if (clazz.isEnum()) {
return Enums.stringConverter(clazz);
}
return new StringConverter(apiVersion, clazz);
}
public static Object[] getEnumConstants(Class<?> clazz) {
if (clazz.isEnum()) {
return clazz.getEnumConstants();
}
Registry<?> registry = EnumEvil.getRegistry(clazz);
if (registry == null) {
return clazz.getEnumConstants();
}
// Need to do this in such away to avoid ClassCastException
List<?> values = Lists.newArrayList(registry);
Object array = Array.newInstance(clazz, values.size());
for (int i = 0; i < values.size(); i++) {
Array.set(array, i, values.get(i));
}
return (Object[]) array;
}
public static String name(@RerouteArgumentType("java/lang/Enum") Object object) {
if (object instanceof OldEnum<?>) {
return ((OldEnum<?>) object).name();
}
return ((Enum<?>) object).name();
}
public static int compareTo(@RerouteArgumentType("java/lang/Enum") Object object, @RerouteArgumentType("java/lang/Enum") Object other) {
if (object instanceof OldEnum<?>) {
return ((OldEnum) object).compareTo((OldEnum) other);
}
return ((Enum) object).compareTo((Enum) other);
}
public static Class<?> getDeclaringClass(@RerouteArgumentType("java/lang/Enum") Object object) {
Class<?> clazz = object.getClass();
Class<?> zuper = clazz.getSuperclass();
return (zuper == Enum.class) ? clazz : zuper;
}
public static Optional<Enum.EnumDesc> describeConstable(@RerouteArgumentType("java/lang/Enum") Object object) {
return EnumEvil.getDeclaringClass(object)
.describeConstable()
.map(c -> Enum.EnumDesc.of(c, EnumEvil.name(object)));
}
@RerouteStatic("java/lang/Enum")
@RerouteReturnType("java/lang/Enum")
public static Object valueOf(Class enumClass, String name, @InjectPluginVersion ApiVersion apiVersion) {
name = FieldRename.rename(apiVersion, enumClass.getName().replace('.', '/'), name);
LegacyRegistryData registryData = EnumEvil.getRegistryData(enumClass);
if (registryData != null) {
return registryData.function().apply(name);
}
return Enum.valueOf(enumClass, name);
}
public static String toString(@RerouteArgumentType("java/lang/Enum") Object object) {
return object.toString();
}
public static int ordinal(@RerouteArgumentType("java/lang/Enum") Object object) {
if (object instanceof OldEnum<?>) {
return ((OldEnum<?>) object).ordinal();
}
return ((Enum<?>) object).ordinal();
}
public record LegacyRegistryData(Registry<?> registry, Function<String, ?> function) {
}
private static final class StringConverter<T extends OldEnum<T>> extends Converter<String, T> implements Serializable {
private final ApiVersion apiVersion;
private final Class<T> clazz;
private transient LegacyRegistryData registryData;
StringConverter(ApiVersion apiVersion, Class<T> clazz) {
this.apiVersion = apiVersion;
this.clazz = clazz;
}
@Override
protected T doForward(String value) {
if (this.registryData == null) {
this.registryData = EnumEvil.getRegistryData(this.clazz);
}
value = FieldRename.rename(this.apiVersion, this.clazz.getName().replace('.', '/'), value);
return (T) this.registryData.function().apply(value);
}
@Override
protected String doBackward(T enumValue) {
return enumValue.name();
}
@Override
public boolean equals(Object object) {
if (object instanceof StringConverter<?> that) {
return this.clazz.equals(that.clazz);
}
return false;
}
@Override
public int hashCode() {
return this.clazz.hashCode();
}
@Override
public String toString() {
return "Enums.stringConverter(" + this.clazz.getName() + ".class)";
}
private static final long serialVersionUID = 0L;
}
}
| 0 | 0.77135 | 1 | 0.77135 | game-dev | MEDIA | 0.671893 | game-dev | 0.766012 | 1 | 0.766012 |
ogclub02/OGCLUB-LEAKS | 90,950 | Gamesense/Lua/volta.lua | LUA_BUILD = "Nightly"
LUA_TYPE = "Semi"
local bit = require "bit"
local ffi = require "ffi"
Discord = require("gamesense/discord_webhooks") or error("Missing discord_webhooks library")
clipboard = require('gamesense/clipboard') or error("Missing clipboard library")
base64 = require("gamesense/base64") or error("Missing base64 library")
AntiAimFunctionsLib = require("gamesense/antiaim_funcs") or error("Missing antiaim_funcs library")
easing = require("gamesense/easing") or error("Missing easing library")
EntityLib = require("gamesense/entity") or error("Missing entity library")
vector = require('vector') or error("Missing vector library")
http = require("gamesense/http") or error("Missing http library")
images = require ("gamesense/images") or error("Missing images library")
color = require("gamesense/color")
---override menu
override_system = {}
ui_ = {}
override_system.thread = 'main'
override_system.history = {}
override_system.get = function(key, result_only)
local this = override_system.history[key]
if not this then
return
end
if result_only then
return unpack(this.m_result)
end
return this
end
override_system.new = function(key, event_name, func)
local this = {}
this.m_key = key
this.m_event_name = event_name
this.m_func = func
this.m_result = {}
local handler = function(ST)
override_system.thread = event_name
this.m_result = { func(ST) }
end
local protect = function(ST)
local success, result = pcall(handler, ST)
if success then
return
end
if isDebug then
result = f('%s, debug info: key = %s, event_name = %s', result, key, event_name)
end
end
client.set_event_callback(event_name, protect)
this.m_protect = protect
override_system.history[key] = this
return this
end
override_system.thread = 'main'
override_system.history = {}
ui_.history = {}
ui_.override = function(id, ST)
if ui_.history[override_system.thread] == nil then
ui_.history[override_system.thread] = {}
local handler = function()
local dir = ui_.history[override_system.thread]
for k, v in pairs(dir) do
if v.active then
v.active = false;
goto skip;
end
ui.set(k, unpack(v.value));
dir[k] = nil;
::skip::
end
end
override_system.new('menu::override::' .. override_system.thread, override_system.thread, handler)
end
local args = { ST }
if #args == 0 then
return
end
if ui_.history[override_system.thread][id] == nil then
local item = { };
local value = { ui.get(id) };
if ui.type(id) == "hotkey" then
value = {enum.ui.hotkey_states[value[2]]};
end
item.value = value;
ui_.history[override_system.thread][id] = item;
end
ui_.history[override_system.thread][id].active = true;
ui.set(id, ST);
end
ui_.shutdown = function()
for k, v in pairs(ui_.history) do
for x, y in pairs(v) do
if y.backup == nil then
goto skip
end
ui.set(x, unpack(y.backup))
y.backup = nil
::skip::
end
end
end
override_system.new('menu::restore', 'pre_config_save', ui_.shutdown)
override_system.new('menu::shutdown_vis', 'shutdown', ui_.visibility_shutdown)
override_system.new('menu::color_label', 'paint_ui', ui_.handle_colorushka)
--entitys
entitys = {
velocity = function(e)
velocity = math.sqrt(math.pow(entity.get_prop(e, "m_vecVelocity[0]"), 2) + math.pow(entity.get_prop(e, "m_vecVelocity[1]"), 2))
return velocity
end,
vector = function(angle_x, angle_y)
local sy = math.sin(math.rad(angle_y))
local cy = math.cos(math.rad(angle_y))
local sp = math.sin(math.rad(angle_x))
local cp = math.cos(math.rad(angle_x))
return cp * cy, cp * sy, -sp
end,
Contains = function(table, value)
for _, v in ipairs(table) do
if v == value then
return true
end
end
return false
end,
RGBtoHEX = function(redArg, greenArg, blueArg)
return string.format("%.2x%.2x%.2xFF", redArg, greenArg, blueArg)
end,
RGBtoDecimal = function(red_arg, green_arg, blue_arg)
return red_arg * 65536 + green_arg * 256 + blue_arg
end,
DistanceCal = function(x1, y1, z1, x2, y2, z2)
return math.sqrt((x2 - x1) ^ 2 + (y2 - y1) ^ 2 + (z2 - z1) ^ 2)
end,
rectangle_outline = function(x, y, w, h, r, g, b, a, s)
s = s or 1
renderer.rectangle(x, y, w, s, r, g, b, a) -- top
renderer.rectangle(x, y+h-s, w, s, r, g, b, a) -- bottom
renderer.rectangle(x, y+s, s, h-s*2, r, g, b, a) -- left
renderer.rectangle(x+w-s, y+s, s, h-s*2, r, g, b, a) -- right
end,
Clamp = function(KB_B,c,d)
return math.min(d,math.max(c,KB_B))
end,
get_hotkey_index = function(refs)
local to_return = {true, -1}
for i = 1, #refs do
if i == 1 and #refs > 1 then
if not ui.get(refs[i]) then
to_return[1] = false
end
end
if #{ui.get(refs[i])} > to_return[2] then
to_return[2] = i
end
end
return to_return
end,
VF_Box = function(box_x, box_y, box_width, box_height, r, g, b, a, text_size_1, Disable_Anim)
if Disable_Anim then
renderer.blur(box_x, box_y, box_width, box_height)
else
renderer.rectangle(box_x, box_y, box_width, box_height, 0, 0, 0, 255)
end
VF_Box_Height = 3
VF_Box_Weight = 3
renderer.rectangle(box_x+1, box_y, box_width/2, VF_Box_Height, 50, 50, 50, 255)
renderer.rectangle(box_x+box_width/2, box_y, box_width/2, VF_Box_Height, 50, 50, 50, 255)
renderer.rectangle(box_x+1, box_y+box_height, box_width/2, VF_Box_Height, 50, 50, 50, 255)
renderer.rectangle(box_x+box_width/2, box_y+box_height, box_width/2, VF_Box_Height, 50, 50, 50, 255)
renderer.rectangle(box_x, box_y, VF_Box_Weight, box_height, 50, 50, 50, 255)
renderer.rectangle(box_x + box_width - VF_Box_Weight, box_y, VF_Box_Weight, box_height, 50, 50, 50, 255)
renderer.rectangle(box_x-1, box_y+6, VF_Box_Weight, box_height/2, r, g, b, a)
renderer.rectangle(box_x+2 + box_width - VF_Box_Weight, box_y+6, VF_Box_Weight, box_height/2, r, g, b, a)
end,
VF_Box_outline = function(box_x, box_y, box_width, box_height, r, g, b, a, Disable_Anim)
if Disable_Anim then
renderer.blur(box_x, box_y, box_width, box_height)
else
renderer.rectangle(box_x, box_y, box_width, box_height, 0, 0, 0, 255)
end
VF_Box_outline_Height = 3
VF_Box_outline_Weight = 3
renderer.gradient(box_x+1, box_y, box_width/2, VF_Box_outline_Height, r, g, b, a, 0, 0, 0, 255, true)
renderer.gradient(box_x+box_width/2, box_y, box_width/2, VF_Box_outline_Height, 0, 0, 0, 255, r, g, b, a, true)
renderer.gradient(box_x+1, box_y+box_height, box_width/2, VF_Box_outline_Height, r, g, b, a, 0, 0, 0, 255, true)
renderer.gradient(box_x+box_width/2, box_y+box_height, box_width/2, VF_Box_outline_Height, 0, 0, 0, 255, r, g, b, a, true)
renderer.rectangle(box_x, box_y, VF_Box_outline_Weight, box_height+VF_Box_outline_Weight, r, g, b, a)
renderer.rectangle(box_x + box_width - VF_Box_outline_Weight, box_y, VF_Box_outline_Weight, box_height, r, g, b, a)
end,
LerpColor = function(color1, color2, ColorTime)
local result = {}
for i = 1, 4 do
result[i] = math.floor(color1[i] * (1 - ColorTime) + color2[i] * ColorTime)
end
return result
end,
}
Custom_error = function(r, g, b, ST)
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, 'Voltaflame\0')
client.color_log(r, g, b, string.format(ST))
end
Custom_Error_U = function(ST)
Custom_error(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, ST)
error()
end
local Create_Drag = (function()
local a = {}
local b, c, d, e, f, g, h, i, j, k, l, m, n, o, w, v
local p = {
__index = {
drag = function(self, ...)
local q, r = self:get()
local s, t = a.drag(q, r, ...)
if q ~= s or r ~= t then
self:set(s, t)
end
return s, t
end,
set = function(self, q, r)
local j, k = client.screen_size()
ui.set(self.x_reference, q / j * self.res)
ui.set(self.y_reference, r / k * self.res)
end,
get = function(self)
local j, k = client.screen_size()
return ui.get(self.x_reference) / self.res * j, ui.get(self.y_reference) / self.res * k
end
}
}
function a.new(u, v, w, x)
x = x or 10000
local j, k = client.screen_size()
local y = ui.new_slider('LUA', 'A', u .. ' window position', 0, x, v / j * x)
local z = ui.new_slider('LUA', 'A', u .. ' window position y', 0, x, w / k * x)
ui.set_visible(y, false)
ui.set_visible(z, false)
return setmetatable({ name = u, x_reference = y, y_reference = z, res = x }, p)
end
function a.new2(u, v, w, x)
x = x or 10000
local j, k = client.screen_size()
local y = ui.new_slider('LUA', 'A', u .. ' window position 2', 0, x, v / j * x)
local z = ui.new_slider('LUA', 'A', u .. ' window position 2 y', 0, x, w / k * x)
ui.set_visible(y, false)
ui.set_visible(z, false)
return setmetatable({ name = u, x_reference = y, y_reference = z, res = x }, p)
end
function a.drag(q, r, A, B, C, D, E)
if globals.framecount() ~= b then
c = ui.is_menu_open()
f, g = d, e
d, e = ui.mouse_position()
i = h
h = client.key_state(0x01) == true
m = l
l = {}
o = n
n = false
j, k = client.screen_size()
end
if c and i ~= nil then
if (not i or o) and h and f > q and g > r and f < q + A and g < r + B then
n = true
q, r = q + d - f, r + e - g
if not D then
q = math.max(0, math.min(j - A, q))
r = math.max(0, math.min(k - B, r))
end
end
end
table.insert(l, { q, r, A, B })
return q, r, A, B
end
return a
end)()
--refs
FAKEDUCK = ui.reference("RAGE", "Other", "Duck peek assist")
MINHTC = ui.reference("RAGE", "Aimbot", "Minimum hit chance")
MINDMG = ui.reference("RAGE","Aimbot","Minimum damage")
MINDMGOVR = {ui.reference("RAGE","Aimbot","Minimum damage override")}
FORCESAFE = ui.reference("RAGE", "Aimbot", "Force safe point")
FORCEBODY = ui.reference("RAGE", "Aimbot", "Force body aim")
DOUBLETAPFAKELAGLIMIT = ui.reference("RAGE", "Aimbot", "Double tap fake lag limit")
AUTOPEEK = {ui.reference("RAGE", "Other", "Quick peek assist")}
DOUBLETAP = {ui.reference("RAGE", "Aimbot", "Double tap")}
SLOWMOTION = {ui.reference("AA", "Other", "Slow motion")}
LEGMOVEMENT = ui.reference("AA", "Other", "Leg movement")
HIDESHOT = {ui.reference("AA", "Other", "On shot anti-aim")}
FAKEPEEK = ui.reference("AA", "Other", "Fake peek")
FAKELAGENABLE = ui.reference("AA", "Fake lag", "Enabled")
FAKELAGAMOUNT = ui.reference("AA", "Fake lag", "Amount")
FAKELAGVARIANCE = ui.reference("AA", "Fake lag", "Variance")
FAKELAGLIMIT = ui.reference("AA", "Fake lag", "Limit")
ENABLE = ui.reference("AA", "Anti-aimbot angles", "Enabled")
PITCH = {ui.reference("AA", "Anti-aimbot angles", "pitch")}
YAWBASE = ui.reference("AA", "Anti-aimbot angles", "Yaw base")
YAW = {ui.reference("AA", "Anti-aimbot angles", "Yaw")}
YAWJITTER = {ui.reference("AA", "Anti-aimbot angles", "Yaw jitter")}
BODYYAW = {ui.reference("AA", "Anti-aimbot angles", "Body yaw")}
BODYYAWFREESTAND = ui.reference("AA", "Anti-aimbot angles", "Freestanding body yaw")
FREESTANDING = ui.reference("AA", "Anti-aimbot angles", "Freestanding")
EDGEYAW = ui.reference("AA", "Anti-aimbot angles", "Edge yaw")
EXTENDEDROLL = ui.reference("AA", "Anti-aimbot angles", "roll")
AMMO = ui.reference("VISUALS","Player ESP","Ammo")
WEAPONTEXT = ui.reference("VISUALS","Player ESP","Weapon text")
WEAPONICON = ui.reference("VISUALS","Player ESP","Weapon icon")
PINGSPIKE = {ui.reference("MISC","Miscellaneous","Ping spike")}
CLANTAGSPAMMER = ui.reference("MISC","Miscellaneous","Clan tag spammer")
NAMESTEAL = ui.reference("Misc", "Miscellaneous", "Steal player name")
PROCESSTICK = ui.reference("MISC", "Settings", "sv_maxusrcmdprocessticks2")
MAXUNLAG = ui.reference("MISC", "Settings", "sv_maxunlag2")
MENUCOLOR = {ui.reference("MISC", "Settings", "Menu color")}
MENUKEY = ui.reference("MISC","Settings","Menu key")
DPISCALE = ui.reference("MISC","Settings","DPI scale")
MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B = ui.get(MENUCOLOR[1])
Hex_MENUCOLOR = entitys.RGBtoHEX(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B)
--intro
ui.new_label("AA", "Anti-aimbot angles", " ")
WelcomeToVoltalfame_Text = "Welcome To Voltaflame!"
Gradient_Start_Color_Volta = color.hex("0000FFFF")
Gradient_End_Color = color.hex("FF0000FF")
Main_Menu_Volta = ui.new_label("AA", "Anti-aimbot angles", WelcomeToVoltalfame_Text)
Start_Time_Volta = globals.curtime()
MainLabel = function()
Current_Time_Volta = globals.curtime() - Start_Time_Volta
Gradient_Ratio_Volta = (math.sin(Current_Time_Volta) + 1) / 2 -- Value between 0 and 1
r = Gradient_Start_Color_Volta.r + (Gradient_End_Color.r - Gradient_Start_Color_Volta.r) * Gradient_Ratio_Volta
g = Gradient_Start_Color_Volta.g + (Gradient_End_Color.g - Gradient_Start_Color_Volta.g) * Gradient_Ratio_Volta
b = Gradient_Start_Color_Volta.b + (Gradient_End_Color.b - Gradient_Start_Color_Volta.b) * Gradient_Ratio_Volta
a = Gradient_Start_Color_Volta.a + (Gradient_End_Color.a - Gradient_Start_Color_Volta.a) * Gradient_Ratio_Volta
Current_Color_Volta = color(r, g, b, a)
Gradient_Volta = ""
labelLength = #WelcomeToVoltalfame_Text
for i = 1, labelLength do
Gradient_Volta = Gradient_Volta .. "\a" .. Current_Color_Volta:to_hex() .. WelcomeToVoltalfame_Text:sub(i, i)
end
Gradient_Volta = Gradient_Volta .. "\a" .. Current_Color_Volta:to_hex() .. " " -- Add an extra space to create a horizontal effect
ui.set(Main_Menu_Volta, Gradient_Volta)
end
ui.new_label("AA", "Anti-aimbot angles", " ")
CFGContainerName = ui.new_label("AA", "Anti-aimbot angles", " Info/CFG")
RageContainerName = ui.new_label("AA", "Anti-aimbot angles", " Ragebot")
AntiAimContainerName = ui.new_label("AA", "Anti-aimbot angles", " Anti-Aim")
VisualContainerName = ui.new_label("AA", "Anti-aimbot angles", " Visuals")
MiscContainerName = ui.new_label("AA", "Anti-aimbot angles", " Miscellaneous")
MenucontainerName = ui.new_label("AA", "Anti-aimbot angles", " Main Menu")
client.exec("clear")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255,"Loading The Script...")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255,"Loading The Script..")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255,"Loading The Script.")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255,"The Script Has Been loaded!")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255,"Hope You Will Enjoy Using Our Product!")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255,"Contact Us On Discord If You Are Having Any Issues!")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255," ")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255," ")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255,"discord.gg/voltaflame")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255," ")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255," ")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255,"Peace!")
--tabs/container
container = "empty"
CFGContainer = ui.new_button("AA", "Anti-aimbot angles", "Info/CFG",function()
container = "CFGContainer"
end)
RageContainer = ui.new_button("AA", "Anti-aimbot angles", "Ragebot",function()
container = "RageContainer"
end)
AntiAimContainer = ui.new_button("AA", "Anti-aimbot angles", "Anti-Aim",function()
container = "AntiAimContainer"
end)
VisualContainer = ui.new_button("AA", "Anti-aimbot angles", "Visuals",function()
container = "VisualContainer"
end)
MiscContainer = ui.new_button("AA", "Anti-aimbot angles", "Miscellaneous",function()
container = "MiscContainer"
end)
BackContainer = ui.new_button("AA", "Anti-aimbot angles", "Back",function()
container = "empty"
end)
client.set_event_callback("paint_ui", function()
ui.set_visible(CFGContainer, container == "empty")
ui.set_visible(CFGContainerName, container == "CFGContainer")
ui.set_visible(RageContainer, container == "empty")
ui.set_visible(RageContainerName, container == "RageContainer")
ui.set_visible(AntiAimContainer, container == "empty")
ui.set_visible(AntiAimContainerName, container == "AntiAimContainer")
ui.set_visible(VisualContainer, container == "empty")
ui.set_visible(VisualContainerName, container == "VisualContainer")
ui.set_visible(MiscContainer, container == "empty")
ui.set_visible(MiscContainerName, container == "MiscContainer")
ui.set_visible(MenucontainerName, container == "empty")
ui.set_visible(BackContainer, container == "CFGContainer" or container == "RageContainer" or container == "AntiAimContainer" or container == "VisualContainer" or container == "MiscContainer")
end)
--animation
Animation_Rainbow = ui.new_checkbox("AA", "Anti-aimbot angles", "Rainbow Colors")
Rainbow_Color_Selection = ui.new_multiselect("AA", "Anti-aimbot angles", "Rainbow Colors", {"Indicators", "Watermark", "Keybinds", "Hitlogs"})
Animation_Speed_Rainbow = ui.new_slider("AA", "Anti-aimbot angles", "Rainbow Speed", 0, 10, 1)
Animation_Speed_1 = ui.new_slider("AA", "Anti-aimbot angles", "[1] Animation Speed", 0, 10, 1)
Animation_Speed_2 = ui.new_slider("AA", "Anti-aimbot angles", "[2] Animation Speed", 0, 10, 1)
DragSelection = ui.new_combobox("AA", "Anti-aimbot angles", "Drag Selection", {"Keybinds", "MinDMG"})
emtpylabel = ui.new_label("AA", "Anti-aimbot angles", " ")
Animation_System_Renderer = function()
ui.set_visible(Animation_Rainbow, container == "VisualContainer")
ui.set_visible(Animation_Speed_Rainbow, container == "VisualContainer" and ui.get(Animation_Rainbow))
ui.set_visible(Rainbow_Color_Selection, container == "VisualContainer" and ui.get(Animation_Rainbow))
ui.set_visible(Animation_Speed_1, container == "VisualContainer")
ui.set_visible(Animation_Speed_2, container == "VisualContainer")
ui.set_visible(emtpylabel, container == "VisualContainer")
ui.set_visible(DragSelection, container == "VisualContainer" and (ui.get(Keybinds_VF) or ui.get(MinDmg_indicator)))
end
Start_Time = globals.curtime()
Animation_System = function()
if ui.get(Animation_Rainbow) then
local Rainbow_Curtime = globals.curtime() - Start_Time
local rainbowSpeed = ui.get(Animation_Speed_Rainbow) * 0.1
RcolorR = math.floor((math.sin(Rainbow_Curtime * rainbowSpeed) + 1) * 127.5)
RcolorG = math.floor((math.sin(Rainbow_Curtime * rainbowSpeed + (2 * math.pi / 3)) + 1) * 127.5)
RcolorB = math.floor((math.sin(Rainbow_Curtime * rainbowSpeed + (4 * math.pi / 3)) + 1) * 127.5)
if entitys.Contains(ui.get(Rainbow_Color_Selection), "Indicators") then
ui.set(Indic_Color1, RcolorR, RcolorG, RcolorB, 255)
ui.set(Indic_Color2, RcolorR, RcolorG, RcolorB, 255)
end
if entitys.Contains(ui.get(Rainbow_Color_Selection), "Watermark") then
ui.set(Water_Mark_VF_Color, RcolorR, RcolorG, RcolorB, 255)
end
if entitys.Contains(ui.get(Rainbow_Color_Selection), "Keybinds") then
ui.set(Keybinds_VF_Color, RcolorR, RcolorG, RcolorB, 255)
end
if entitys.Contains(ui.get(Rainbow_Color_Selection), "Hitlogs") then
ui.set(Log_Color_Box, RcolorR, RcolorG, RcolorB, 255)
end
end
local currentTime = globals.curtime()
local speedMalpha_Duration = ui.get(Animation_Speed_1) + 1.0
local speedMalpha2_Duration = ui.get(Animation_Speed_2) + 0.5
local progressMalpha = (currentTime * speedMalpha_Duration / 2) % 1
local progressMalpha2 = (currentTime * speedMalpha2_Duration / 2) % 1
Malpha = math.abs((progressMalpha * 2) % 2 - 1)
alpha = 255 * Malpha
Malpha2 = math.abs((progressMalpha2 * 2) % 2 - 1)
alpha2 = 255 * Malpha2
end
--tickcontrol
CustomTickControl = ui.new_checkbox("AA", "Anti-aimbot angles", "Custom Tick Control [Risky]")
CustomTickControl_Value = ui.new_slider("AA", "Anti-aimbot angles", "Tick Value", 1, 30, 16)
--Resolver
VFR_Resolver_B = ui.new_checkbox("AA", "Anti-aimbot angles", "\a"..Hex_MENUCOLOR.."VoltaFlame Resolver [Safe]")
RS_logs = ui.new_checkbox("AA", "Anti-aimbot angles", "Resolver Logs. (In Screen Hitlogs)")
Force_BY_Resolver = ui.new_checkbox("AA", "Anti-aimbot angles", "Force Resolve Body Yaw")
CorrectionActive_Resolver = ui.new_checkbox("AA", "Anti-aimbot angles", "Enable Correction Active")
--extended backtrack
Extendedbacktrack = ui.new_checkbox("AA", "Anti-aimbot angles", "Extended Backtrack [Safe]")
Lua_Freestand = ui.new_hotkey("AA", "Anti-aimbot angles", "FreeStand [Risky]")
CustomSlowWalk = ui.new_checkbox("AA", "Anti-aimbot angles","Custom Slow-Walk Speed")
CustomSlowWalk_Delay = ui.new_slider("AA", "Anti-aimbot angles"," Delay:", 1, 10, 0, 1)
CustomSlowWalk_Value_1 = ui.new_slider("AA", "Anti-aimbot angles","[1] Speed:", 1, 100, 0, 1)
CustomSlowWalk_Value_2 = ui.new_slider("AA", "Anti-aimbot angles","[2] Speed:", 1, 100, 0, 1)
CustomSlowWalk_Value_Real = ui.new_slider("AA", "Anti-aimbot angles","Speed:", 1, 100, 0, 1)
DisableOnWarmup = ui.new_checkbox("AA", "Other", "Disable AA on Warmup [Safe]")
FAKELAGENABLE_Label = ui.new_label("AA", "Fake lag", "Using Fakelag Might Be Risky!!")
ManualYaw = ui.new_checkbox("AA", "Anti-aimbot angles","Manual Yaw")
ManualYawLeft = ui.new_hotkey("AA", "Anti-aimbot angles", "Manual Yaw [Left]")
ManualYawRight = ui.new_hotkey("AA", "Anti-aimbot angles", "Manual Yaw [Right]")
RageSystemRenderer = function()
ui.set_visible(VFR_Resolver_B, container == "RageContainer")
ui.set_visible(RS_logs, container == "RageContainer" and ui.get(VFR_Resolver_B))
ui.set_visible(Force_BY_Resolver, container == "RageContainer" and ui.get(VFR_Resolver_B))
ui.set_visible(CorrectionActive_Resolver, container == "RageContainer" and ui.get(VFR_Resolver_B))
ui.set_visible(CustomTickControl, container == "RageContainer")
ui.set_visible(CustomTickControl_Value, container == "RageContainer" and ui.get(CustomTickControl))
ui.set_visible(Extendedbacktrack, container == "RageContainer")
end
OtherAASystemRenderer = function()
ui.set_visible(Lua_Freestand, container == "AntiAimContainer")
ui.set_visible(SLOWMOTION[1], container == "AntiAimContainer")
ui.set_visible(SLOWMOTION[2], container == "AntiAimContainer")
ui.set_visible(HIDESHOT[1], container == "AntiAimContainer")
ui.set_visible(HIDESHOT[2], container == "AntiAimContainer")
ui.set_visible(FAKEPEEK, container == "AntiAimContainer")
ui.set_visible(FAKELAGENABLE, container == "AntiAimContainer")
ui.set_visible(FAKELAGENABLE_Label, container == "AntiAimContainer" and ui.get(FAKELAGENABLE))
ui.set_visible(FAKELAGAMOUNT, container == "AntiAimContainer" and ui.get(FAKELAGENABLE))
ui.set_visible(FAKELAGVARIANCE, container == "AntiAimContainer" and ui.get(FAKELAGENABLE))
ui.set_visible(FAKELAGLIMIT, container == "AntiAimContainer" and (ui.get(FAKELAGENABLE)))
ui.set_visible(CustomSlowWalk, container == "AntiAimContainer")
ui.set_visible(CustomSlowWalk_Delay, container == "AntiAimContainer" and ui.get(CustomSlowWalk))
ui.set_visible(CustomSlowWalk_Value_1, container == "AntiAimContainer" and ui.get(CustomSlowWalk))
ui.set_visible(CustomSlowWalk_Value_2, container == "AntiAimContainer" and ui.get(CustomSlowWalk))
ui.set_visible(CustomSlowWalk_Value_Real, false)
ui.set_visible(DisableOnWarmup, container == "AntiAimContainer")
ui.set_visible(ManualYaw, container == "AntiAimContainer")
ui.set_visible(ManualYawLeft, container == "AntiAimContainer" and ui.get(ManualYaw))
ui.set_visible(ManualYawRight, container == "AntiAimContainer" and ui.get(ManualYaw))
end
ResolvedRP = function(player)
if ui.get(VFR_Resolver_B) and not ui.get(FORCEBODY) then
if entity.is_dormant(player) or entity.get_prop(player, "m_bDormant") then
return
end
RP_Angle = math.deg(math.atan2(entity.get_prop(player, "m_angEyeAngles[1]") - entity.get_prop(player, "m_flLowerBodyYawTarget"), entity.get_prop(player, "m_angEyeAngles[0]")))
RP_YAW = math.min(60, math.max(-60, (RP_Angle * 10000)))
plist.set(player, "Force body yaw value", RP_YAW)
if ui.get(Force_BY_Resolver) then
plist.set(player, "Force body yaw", true)
else
plist.set(player, "Force body yaw", false)
end
if ui.get(CorrectionActive_Resolver) then
plist.set(player, "Correction Active", true)
else
plist.set(player, "Correction Active", false)
end
else
plist.set(player, "Force body yaw", false)
plist.set(player, "Correction Active", true)
end
end
NV_Resolver = function()
enemies = entity.get_players(true)
for i, enemy_ent in ipairs(enemies) do
if enemy_ent and entity.is_alive(enemy_ent) then
ResolvedRP(enemy_ent)
end
end
end
OtherAASystem = function()
KnifeClass = weaponclass == "CKnife"
TaserClass = weaponclass == "CWeaponTaser"
if ui.get(CustomTickControl) then
ui.set(PROCESSTICK, ui.get(CustomTickControl_Value))
else
ui.set(PROCESSTICK, 16)
end
ui.set(EDGEYAW, false)
if ui.get(Lua_Freestand) then
ui.set(FREESTANDING, true)
else
ui.set(FREESTANDING, false)
end
if ui.get(Extendedbacktrack) then
ui.set(MAXUNLAG, 400)
else
ui.set(MAXUNLAG, 200)
end
end
warmup = nil
onWarmupStart = function()
warmup = true
end
onWarmupEnd = function()
warmup = false
end
client.set_event_callback("round_start", function(e)
if e.round_phase == 1 then
onWarmupStart()
elseif e.round_phase == 2 then
onWarmupEnd()
end
end)
local SlowWalk_loop = 1
client.set_event_callback("setup_command", function(e)
CustomSlowWalk_Values = {ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_2), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1), ui.get(CustomSlowWalk_Value_1)}
ui.set(CustomSlowWalk_Value_Real, CustomSlowWalk_Values[SlowWalk_loop])
SlowWalk_loop = SlowWalk_loop + 1
if SlowWalk_loop > ui.get(CustomSlowWalk_Delay)*10 then
SlowWalk_loop = 1
end
if CustomSlowWalk and ui.get(SLOWMOTION[2]) then
if e.forwardmove >= ui.get(CustomSlowWalk_Value_Real) then
e.forwardmove = ui.get(CustomSlowWalk_Value_Real)
end
if e.sidemove >= ui.get(CustomSlowWalk_Value_Real) then
e.sidemove = ui.get(CustomSlowWalk_Value_Real)
end
if e.forwardmove < 0 and -e.forwardmove >= ui.get(CustomSlowWalk_Value_Real) then
e.forwardmove = -ui.get(CustomSlowWalk_Value_Real)
end
if e.sidemove < 0 and -e.sidemove >= ui.get(CustomSlowWalk_Value_Real) then
e.sidemove = -ui.get(CustomSlowWalk_Value_Real)
end
end
end)
--antiaim
AAmode = ui.new_combobox("AA", "Anti-aimbot angles", "\a"..Hex_MENUCOLOR.."Anti-Aim Modes:", {"None", "Safe", "Tryhard", "Risky", "Custom"})
--Custom AA
SelectionTabForCustom = ui.new_combobox("AA", "Anti-aimbot angles", "Condition Tab:", {"Stand", "Move", "Jump", "Crouch", "Crouch+Air", "Slow Walk"})
Lua_Inverter = ui.new_hotkey("AA", "Anti-aimbot angles", "Inverter")
Condition_Tabs_Create = function(State)
StateSynce = {}
StateSynce.Override = ui.new_checkbox("AA", "Anti-aimbot angles", "Override These Settings:")
StateSynce.BodyYaw = ui.new_checkbox("AA", "Anti-aimbot angles", "Body Yaw")
StateSynce.BodyYawSlider_L = ui.new_slider("AA", "Anti-aimbot angles", "[L] Body Yaw Value:", 0, 60, 0)
StateSynce.BodyYawSlider_R = ui.new_slider("AA", "Anti-aimbot angles", "[R] Body Yaw Value:", 0, 60, 0)
StateSynce.Roll = ui.new_checkbox("AA", "Anti-aimbot angles", "Roll")
StateSynce.RollSlider_L = ui.new_slider("AA", "Anti-aimbot angles", "[L] Roll Value:", 0, 60, 0)
StateSynce.RollSlider_R = ui.new_slider("AA", "Anti-aimbot angles", "[R] Roll Value:", 0, 60, 0)
return StateSynce
end
Condition_Tabs_Renderer = function(StateItem, State)
if ui.is_menu_open() then
ui.set_visible(StateItem.Override, container == "AntiAimContainer" and ui.get(AAmode) == "Custom" and ui.get(SelectionTabForCustom) == State)
ui.set_visible(StateItem.BodyYaw, container == "AntiAimContainer" and ui.get(AAmode) == "Custom" and ui.get(SelectionTabForCustom) == State and ui.get(StateItem.Override))
ui.set_visible(StateItem.BodyYawSlider_L, container == "AntiAimContainer" and ui.get(AAmode) == "Custom" and ui.get(SelectionTabForCustom) == State and ui.get(StateItem.Override) and ui.get(StateItem.BodyYaw))
ui.set_visible(StateItem.BodyYawSlider_R, container == "AntiAimContainer" and ui.get(AAmode) == "Custom" and ui.get(SelectionTabForCustom) == State and ui.get(StateItem.Override) and ui.get(StateItem.BodyYaw))
ui.set_visible(StateItem.Roll, container == "AntiAimContainer" and ui.get(AAmode) == "Custom" and ui.get(SelectionTabForCustom) == State and ui.get(StateItem.Override))
ui.set_visible(StateItem.RollSlider_R, container == "AntiAimContainer" and ui.get(AAmode) == "Custom" and ui.get(SelectionTabForCustom) == State and ui.get(StateItem.Override) and ui.get(StateItem.Roll))
ui.set_visible(StateItem.RollSlider_L, container == "AntiAimContainer" and ui.get(AAmode) == "Custom" and ui.get(SelectionTabForCustom) == State and ui.get(StateItem.Override) and ui.get(StateItem.Roll))
end
end
S = Condition_Tabs_Create("Stand")
M = Condition_Tabs_Create("Move")
J = Condition_Tabs_Create("Jump")
C = Condition_Tabs_Create("Crouch")
CA = Condition_Tabs_Create("Crouch+Air")
SW = Condition_Tabs_Create("Slow Walk")
AATabsRenderer = function()
ui.set_visible(AAmode, container == "AntiAimContainer")
ui.set_visible(SelectionTabForCustom, container == "AntiAimContainer" and ui.get(AAmode) == "Custom")
ui.set_visible(Lua_Inverter, container == "AntiAimContainer")
Condition_Tabs_Renderer(S, "Stand")
Condition_Tabs_Renderer(M, "Move")
Condition_Tabs_Renderer(J, "Jump")
Condition_Tabs_Renderer(C, "Crouch")
Condition_Tabs_Renderer(CA, "Crouch+Air")
Condition_Tabs_Renderer(SW, "Slow Walk")
end
RV = 1
RV2 = 1
RV3 = 1
RV4 = 1
RV5 = 1
RV6 = 1
PRV = 1
PRV2 = 1
PRV3 = 1
PRV4 = 1
PRV5 = 1
PRV6 = 1
PRV7 = 1
PRV8 = 1
PRV9 = 1
PRV10 = 1
client.set_event_callback("setup_command", function(e)
lp = entity.get_local_player()
if not entity.is_alive(lp) then
return
end
if warmup and ui.get(DisableOnWarmup) then
ui.set(ENABLE, false)
else
ui.set(ENABLE, true)
end
vx, vy, vz = entity.get_prop(lp, 'm_vecVelocity')
State_Moving = (math.sqrt(vx * vx + vy * vy + vz * vz) >= 2 and bit.band(entity.get_prop(lp, 'm_fFlags'), 1) == 1)
State_Jumping = (entity.get_prop(lp, "m_flDuckAmount") < 1 and bit.band(entity.get_prop(lp, 'm_fFlags'), 1) == 0)
State_SlowWalk = ui.get(SLOWMOTION[2])
State_FakeDuck = ui.get(FAKEDUCK)
State_Crouch = (entity.get_prop(lp, "m_flDuckAmount") > 0 and bit.band(entity.get_prop(lp, 'm_fFlags'), 1) == 1)
State_CrouchAir = (entity.get_prop(lp, "m_flDuckAmount") > 0 and bit.band(entity.get_prop(lp, 'm_fFlags'), 1) == 0)
State_Standing = not State_SlowWalk and not State_Crouch and not State_CrouchAir and not State_FakeDuck and not State_Jumping and not State_Moving
C_Pitch, C_Yaw = client.camera_angles()
if ui.get(ManualYawLeft) and ui.get(ManualYaw) then
ui.set(PITCH[1], "Off")
ui.set(PITCH[2], 0)
ui.set(YAWBASE, "Local View")
ui.set(YAW[1], "180")
ui.set(YAW[2], "-90")
ui.set(YAWJITTER[1], "Off")
ui.set(YAWJITTER[2], 0)
ui.set(EXTENDEDROLL, 0)
elseif ui.get(ManualYawRight) and ui.get(ManualYaw) then
ui.set(PITCH[1], "Off")
ui.set(PITCH[2], 0)
ui.set(YAWBASE, "Local View")
ui.set(YAW[1], "180")
ui.set(YAW[2], "90")
ui.set(YAWJITTER[1], "Off")
ui.set(YAWJITTER[2], 0)
ui.set(EXTENDEDROLL, 0)
else
ui.set(PITCH[1], "Off")
ui.set(PITCH[2], 0)
ui.set(YAWBASE, "Local View")
ui.set(YAW[1], "Off")
ui.set(YAW[2], 0)
ui.set(YAWJITTER[1], "Off")
ui.set(YAWJITTER[2], 0)
end
if ui.get(AAmode) == "Safe" then
ui.set(BODYYAW[1], "static")
ui.set(BODYYAW[2], ui.get(Lua_Inverter) and -60 or 60)
if globals.chokedcommands() == 0 and e.in_attack ~= 1 then
C_Yaw = C_Yaw - (ui.get(Lua_Inverter) and 60 or -60)
e.allow_send_packet = false
else
C_Yaw = C_Yaw
end
ui.set(EXTENDEDROLL, 0)
e.roll = ui.get(Lua_Inverter) and 0 or 0
e.yaw = C_Yaw
elseif ui.get(AAmode) == "Tryhard" then
ui.set(BODYYAW[1], "static")
ui.set(BODYYAW[2], ui.get(Lua_Inverter) and -60 or 60)
if globals.chokedcommands() == 0 and e.in_attack ~= 1 then
C_Yaw = C_Yaw - (ui.get(Lua_Inverter) and 60 or -60)
e.allow_send_packet = false
else
C_Yaw = C_Yaw
end
ui.set(EXTENDEDROLL, 0)
e.roll = ui.get(Lua_Inverter) and 25 or -25
e.yaw = C_Yaw
elseif ui.get(AAmode) == "Risky" then
ui.set(BODYYAW[1], "static")
ui.set(BODYYAW[2], ui.get(Lua_Inverter) and -65 or 65)
if globals.chokedcommands() == 0 and e.in_attack ~= 1 then
C_Yaw = C_Yaw - (ui.get(Lua_Inverter) and 65 or -65)
e.allow_send_packet = false
else
C_Yaw = C_Yaw
end
ui.set(EXTENDEDROLL, 0)
e.roll = ui.get(Lua_Inverter) and 60 or -60
e.yaw = C_Yaw
elseif ui.get(AAmode) == "Custom" then
if State_Standing then
--print("Stand")
if ui.get(S.Override) then
ui.set(BODYYAW[1], "static")
ui.set(BODYYAW[2], (ui.get(Lua_Inverter) and -ui.get(S.BodyYawSlider_L) or ui.get(S.BodyYawSlider_R)))
if globals.chokedcommands() == 0 and e.in_attack ~= 1 then
C_Yaw = C_Yaw - (ui.get(Lua_Inverter) and ui.get(S.BodyYawSlider_L) or -ui.get(S.BodyYawSlider_R))
e.allow_send_packet = false
else
C_Yaw = C_Yaw
end
if ui.get(S.Roll) then
ui.set(EXTENDEDROLL, 0)
e.roll = ui.get(Lua_Inverter) and ui.get(S.RollSlider_L) or -ui.get(S.RollSlider_R)
else
e.roll = 0
end
e.yaw = C_Yaw
end
elseif State_Jumping then
--print("Jump")
if ui.get(J.Override) then
ui.set(BODYYAW[1], "static")
ui.set(BODYYAW[2], (ui.get(Lua_Inverter) and -ui.get(J.BodyYawSlider_L) or ui.get(J.BodyYawSlider_R)))
if globals.chokedcommands() == 0 and e.in_attack ~= 1 then
C_Yaw = C_Yaw - (ui.get(Lua_Inverter) and ui.get(J.BodyYawSlider_L) or -ui.get(J.BodyYawSlider_R))
e.allow_send_packet = false
else
C_Yaw = C_Yaw
end
if ui.get(J.Roll) then
ui.set(EXTENDEDROLL, 0)
e.roll = ui.get(Lua_Inverter) and ui.get(J.RollSlider_L) or -ui.get(J.RollSlider_R)
else
e.roll = 0
end
e.yaw = C_Yaw
end
elseif State_FakeDuck then
--print("FD")
if ui.get(C.Override) then
ui.set(BODYYAW[1], "static")
ui.set(BODYYAW[2], (ui.get(Lua_Inverter) and -ui.get(C.BodyYawSlider_L) or ui.get(C.BodyYawSlider_R)))
if globals.chokedcommands() == 0 and e.in_attack ~= 1 then
C_Yaw = C_Yaw - (ui.get(Lua_Inverter) and ui.get(C.BodyYawSlider_L) or -ui.get(C.BodyYawSlider_R))
e.allow_send_packet = false
else
C_Yaw = C_Yaw
end
if ui.get(C.Roll) then
ui.set(EXTENDEDROLL, 0)
e.roll = ui.get(Lua_Inverter) and ui.get(C.RollSlider_L) or -ui.get(C.RollSlider_R)
else
e.roll = 0
end
e.yaw = C_Yaw
end
elseif State_Crouch then
--print("crouch")
if ui.get(C.Override) then
ui.set(BODYYAW[1], "static")
ui.set(BODYYAW[2], (ui.get(Lua_Inverter) and -ui.get(C.BodyYawSlider_L) or ui.get(C.BodyYawSlider_R)))
if globals.chokedcommands() == 0 and e.in_attack ~= 1 then
C_Yaw = C_Yaw - (ui.get(Lua_Inverter) and ui.get(C.BodyYawSlider_L) or -ui.get(C.BodyYawSlider_R))
e.allow_send_packet = false
else
C_Yaw = C_Yaw
end
if ui.get(C.Roll) then
ui.set(EXTENDEDROLL, 0)
e.roll = ui.get(Lua_Inverter) and ui.get(C.RollSlider_L) or -ui.get(C.RollSlider_R)
else
e.roll = 0
end
e.yaw = C_Yaw
end
elseif State_CrouchAir then
--print("crouchinair")
if ui.get(CA.Override) then
ui.set(BODYYAW[1], "static")
ui.set(BODYYAW[2], (ui.get(Lua_Inverter) and -ui.get(CA.BodyYawSlider_L) or ui.get(CA.BodyYawSlider_R)))
if globals.chokedcommands() == 0 and e.in_attack ~= 1 then
C_Yaw = C_Yaw - (ui.get(Lua_Inverter) and ui.get(CA.BodyYawSlider_L) or -ui.get(CA.BodyYawSlider_R))
e.allow_send_packet = false
else
C_Yaw = C_Yaw
end
if ui.get(CA.Roll) then
ui.set(EXTENDEDROLL, 0)
e.roll = ui.get(Lua_Inverter) and ui.get(CA.RollSlider_L) or -ui.get(CA.RollSlider_R)
else
e.roll = 0
end
e.yaw = C_Yaw
end
elseif State_Moving then
--print("moving")
if ui.get(M.Override) then
ui.set(BODYYAW[1], "static")
ui.set(BODYYAW[2], (ui.get(Lua_Inverter) and -ui.get(M.BodyYawSlider_L) or ui.get(M.BodyYawSlider_R)))
if globals.chokedcommands() == 0 and e.in_attack ~= 1 then
C_Yaw = C_Yaw - (ui.get(Lua_Inverter) and ui.get(M.BodyYawSlider_L) or -ui.get(M.BodyYawSlider_R))
e.allow_send_packet = false
else
C_Yaw = C_Yaw
end
if ui.get(M.Roll) then
ui.set(EXTENDEDROLL, 0)
e.roll = ui.get(Lua_Inverter) and ui.get(M.RollSlider_L) or -ui.get(M.RollSlider_R)
else
e.roll = 0
end
e.yaw = C_Yaw
end
end
end
if globals.chokedcommands() == 0 or entitys.velocity(lp) > 2 then return end
e.forwardmove = 0.1
e.in_forward = 1
end)
--visuals
CSSX, CSSY = client.screen_size()
IndicX = CSSX / 2
IndicY = CSSY / 2
lerp = function(a, b, percentage)
return math.floor(a + (b - a) * percentage)
end
anim = {0, 0, 0, 0, 0, 0}
--indicators
indic_switch = ui.new_checkbox("AA", "Anti-aimbot angles", "\a"..Hex_MENUCOLOR.."Indicators")
Indicators_Selection = ui.new_multiselect("AA", "Anti-aimbot angles", "[I] Options", {"DMG", "HC"})
Indic_Color1L = ui.new_label("AA", "Anti-aimbot angles", "[1] Colour")
Indic_Color1 = ui.new_color_picker("AA", "Anti-aimbot angles", "[1] Colour")
Indic_Color2L = ui.new_label("AA", "Anti-aimbot angles", "[2] Colour")
Indic_Color2 = ui.new_color_picker("AA", "Anti-aimbot angles", "[2] Colour")
IND_DMG_ColorL = ui.new_label("AA", "Anti-aimbot angles", "[DMG] Colour")
IND_DMG_Color = ui.new_color_picker("AA", "Anti-aimbot angles", "[DMG] Colour")
IND_HC_ColorL = ui.new_label("AA", "Anti-aimbot angles", "[HC] Colour")
IND_HC_Color = ui.new_color_picker("AA", "Anti-aimbot angles", "[HC] Colour")
--MinDmg_indicator
MinDmg_indicator = ui.new_checkbox("AA", "Anti-aimbot angles", "Mindmg Indicator")
--Viewmodel
ViewmodelChanger = ui.new_checkbox("AA", "Anti-aimbot angles", "Viewmodel")
Viewmodel_fov = ui.new_slider("AA", "Anti-aimbot angles", "[FOV] Value", 0, 100, 68)
Viewmodel_x = ui.new_slider("AA", "Anti-aimbot angles", "[X] Value", -10, 10, 2)
Viewmodel_y = ui.new_slider("AA", "Anti-aimbot angles", "[Y] Value", -10, 10, 0)
Viewmodel_z = ui.new_slider("AA", "Anti-aimbot angles", "[Z] Value", -10, 10, -2)
--rainbow hud
RainbowHud = ui.new_checkbox("AA", "Anti-aimbot angles", "Rainbow Hud")
rb = 1
hudcolors = {1,1,1,1,1,1, 2,2,2,2,2,2, 3,3,3,3,3,3, 4,4,4,4,4,4, 5,5,5,5,5,5, 6,6,6,6,6,6, 7,7,7,7,7,7, 8,8,8,8,8,8, 9,9,9,9,9,9, 10,10,10,10,10,10}
--watermark
Water_Mark_VF = ui.new_checkbox("AA", "Anti-aimbot angles", "WaterMark")
Water_Mark_VF_Color = ui.new_color_picker("AA", "Anti-aimbot angles", "WaterMark Colour")
Water_Mark_VF_Disable_Anim = ui.new_checkbox("AA", "Anti-aimbot angles", "[W] Light Theme")
Water_Mark_VF_Trans = ui.new_checkbox("AA", "Anti-aimbot angles", "[W] Transparent Background")
Water_Mark_VF_Corner = ui.new_checkbox("AA", "Anti-aimbot angles", "[W] Rounded Corners")
Water_Mark_VF_Corner_Slider = ui.new_slider("AA", "Anti-aimbot angles", "[W] Corners", 0, 10)
--keybinds
Keybinds_VF = ui.new_checkbox("AA", "Anti-aimbot angles", "Keybinds")
Keybinds_VF_Color = ui.new_color_picker("AA", "Anti-aimbot angles", "[K] Keybinds Colour")
Keybinds_VF_Disable_Anim = ui.new_checkbox("AA", "Anti-aimbot angles", "[K] Light Theme")
Keybinds_VF_Trans = ui.new_checkbox("AA", "Anti-aimbot angles", "[K] Transparent Background")
Keybinds_VF_Corner = ui.new_checkbox("AA", "Anti-aimbot angles", "[K] Rounded Corners")
Keybinds_VF_Corner_Slider = ui.new_slider("AA", "Anti-aimbot angles", "[W] Corners", 0, 10)
--hitlogs
Hitlog = ui.new_checkbox("AA", "Anti-aimbot angles", "HitLogs")
HitLogs = ui.new_multiselect("AA", "Anti-aimbot angles", "[HL]", {"Under Crosshair", "Console"})
Log_Color = ui.new_color_picker("AA", "Anti-aimbot angles", "Log Colour")
Log_Color_Box = ui.new_color_picker("AA", "Anti-aimbot angles", "Box Colour")
Hitlog_Gaps = ui.new_slider("AA", "Anti-aimbot angles", " [HL] Gap Value", 0, 10, 6)
Hitlog_Disable_Anim = ui.new_checkbox("AA", "Anti-aimbot angles", "[HL] Light Theme")
Hitlog_Trans = ui.new_checkbox("AA", "Anti-aimbot angles", "[HL] Transparent Background")
Hitlog_Corner = ui.new_checkbox("AA", "Anti-aimbot angles", "[HL] Rounded Corners")
Hitlog_Corner_Slider = ui.new_slider("AA", "Anti-aimbot angles", "[W] Corners", 0, 10)
VisualsSystemRenderer = function()
ui.set_visible(indic_switch, container == "VisualContainer")
ui.set_visible(Indicators_Selection, container == "VisualContainer" and ui.get(indic_switch))
ui.set_visible(Indic_Color1L, container == "VisualContainer" and ui.get(indic_switch))
ui.set_visible(Indic_Color1, container == "VisualContainer" and ui.get(indic_switch))
ui.set_visible(Indic_Color2L, container == "VisualContainer" and ui.get(indic_switch))
ui.set_visible(Indic_Color2, container == "VisualContainer" and ui.get(indic_switch))
ui.set_visible(IND_DMG_ColorL, container == "VisualContainer" and ui.get(indic_switch))
ui.set_visible(IND_DMG_Color, container == "VisualContainer" and ui.get(indic_switch))
ui.set_visible(IND_HC_ColorL, container == "VisualContainer" and ui.get(indic_switch))
ui.set_visible(IND_HC_Color, container == "VisualContainer" and ui.get(indic_switch))
ui.set_visible(ViewmodelChanger, container == "VisualContainer")
ui.set_visible(Viewmodel_fov, container == "VisualContainer" and ui.get(ViewmodelChanger))
ui.set_visible(Viewmodel_x, container == "VisualContainer" and ui.get(ViewmodelChanger))
ui.set_visible(Viewmodel_y, container == "VisualContainer" and ui.get(ViewmodelChanger))
ui.set_visible(Viewmodel_z, container == "VisualContainer" and ui.get(ViewmodelChanger))
ui.set_visible(RainbowHud, container == "VisualContainer")
ui.set_visible(MinDmg_indicator, container == "VisualContainer")
ui.set_visible(Water_Mark_VF, container == "VisualContainer")
ui.set_visible(Water_Mark_VF_Color, container == "VisualContainer" and ui.get(Water_Mark_VF))
ui.set_visible(Water_Mark_VF_Disable_Anim, container == "VisualContainer" and ui.get(Water_Mark_VF) and not ui.get(Water_Mark_VF_Corner))
ui.set_visible(Water_Mark_VF_Trans, container == "VisualContainer" and ui.get(Water_Mark_VF))
ui.set_visible(Keybinds_VF, container == "VisualContainer")
ui.set_visible(Keybinds_VF_Color, container == "VisualContainer" and ui.get(Keybinds_VF))
ui.set_visible(Keybinds_VF_Disable_Anim, container == "VisualContainer" and ui.get(Keybinds_VF) and not ui.get(Keybinds_VF_Corner))
ui.set_visible(Keybinds_VF_Trans, container == "VisualContainer" and ui.get(Keybinds_VF))
ui.set_visible(Hitlog, container == "VisualContainer")
ui.set_visible(HitLogs, container == "VisualContainer" and ui.get(Hitlog))
ui.set_visible(Hitlog_Disable_Anim, container == "VisualContainer" and ui.get(Hitlog) and entitys.Contains(ui.get(HitLogs), "Under Crosshair") and not ui.get(Hitlog_Corner))
ui.set_visible(Hitlog_Trans, container == "VisualContainer" and ui.get(Hitlog) and entitys.Contains(ui.get(HitLogs), "Under Crosshair"))
ui.set_visible(Log_Color, container == "VisualContainer" and ui.get(Hitlog) and entitys.Contains(ui.get(HitLogs), "Under Crosshair"))
ui.set_visible(Log_Color_Box, container == "VisualContainer" and ui.get(Hitlog) and entitys.Contains(ui.get(HitLogs), "Under Crosshair"))
ui.set_visible(Hitlog_Gaps, container == "VisualContainer" and ui.get(Hitlog) and entitys.Contains(ui.get(HitLogs), "Under Crosshair"))
ui.set_visible(bind_multi, false)
ui.set_visible(Water_Mark_VF_Corner, false)
ui.set_visible(Keybinds_VF_Corner, false)
ui.set_visible(Hitlog_Corner, false)
ui.set_visible(Hitlog_Corner_Slider, false)
ui.set_visible(Water_Mark_VF_Corner_Slider, false)
ui.set_visible(Keybinds_VF_Corner_Slider, false)
end
keybind_options = {
'Double tap', 'On shot anti-aim', 'Safe point', 'Force body aim', 'Quick peek assist', 'Duck peek assist', 'Slow motion', 'Freestanding', 'Ping spike', 'Fake peek', 'Blockbot', 'Last second defuse', 'Min Damage override'
}
bind_multi = ui.new_multiselect("AA", "Anti-aimbot angles", "Keybind options", keybind_options)
KB_Bind_State = {'Always', 'Hold', 'Toggled', 'Off-Hold'}
KB_Bind_Easing = {}
active_binds = {}
Kebind_Data = database.read('KeyBinds') or {
x = CSSX * 0.01,
y = CSSY / 2,
alpha = ui.get(Keybinds_VF) and 255 or 0,
}
MinDMG_Data = database.read('MinDMG') or {
x = CSSX * 0.01,
y = CSSY / 2,
alpha = ui.get(MinDmg_indicator) and 255 or 0,
}
KB_Binds = Create_Drag.new('KeyBinds', Kebind_Data.x, Kebind_Data.y)
MinDmg_indicator_drag = Create_Drag.new("MinDmg_indicator", MinDMG_Data.x, MinDMG_Data.y)
KB_Ease_Length = 0.125
KB_Current_Width = 15
Ref_KB = nil
HotkeyLists = {
{Ref_KB = {ui.reference('rage','aimbot','Double tap')}, use_name = 'Double tap'},
{Ref_KB = {ui.reference('aa','other','On shot anti-aim')}, use_name = 'On shot anti-aim'},
{Ref_KB = {ui.reference('rage','aimbot','Force safe point')}, use_name = 'Safe point'},
{Ref_KB = {ui.reference('rage','aimbot','Force body aim')}, use_name = 'Force body aim'},
{Ref_KB = {ui.reference('rage','other','Quick peek assist')}, use_name = 'Quick peek assist'},
{Ref_KB = {ui.reference('rage','other','Duck peek assist')}, use_name = 'Duck peek assist'},
{Ref_KB = {ui.reference('aa','other','Slow motion')}, use_name = 'Slow motion'},
{Ref_KB = {ui.reference('aa', 'Anti-aimbot angles', 'Freestanding')}, use_name = 'Freestanding'},
{Ref_KB = {ui.reference('misc','miscellaneous','Ping spike')}, use_name = 'Ping spike'},
{Ref_KB = {ui.reference('aa','other','Fake peek')}, use_name = 'Fake peek'},
{Ref_KB = {ui.reference('misc','movement','Blockbot')}, use_name = 'Blockbot'},
{Ref_KB = {ui.reference('misc','miscellaneous','Last second defuse')}, use_name = 'Last second defuse'},
{Ref_KB = {ui.reference('rage', 'aimbot', 'Minimum damage override') }, use_name = 'Min Damage override'},
}
local Indicators_AnimationSpeed = 0.01
local currentTime = 0
local VF_TEXT = "Voltaflame"
VisualsSystem = function()
add_y = 25
lp = entity.get_local_player()
scoped = entity.get_prop(lp, "m_bIsScoped") == 1 and true or false
if scoped then
anim[4] = lerp(anim[4], -50, globals.frametime() * 50)
else
anim[4] = lerp(anim[4], 0, globals.frametime() * 50)
end
Desync_Value = AntiAimFunctionsLib:get_desync(2)
if Desync_Value < 0 then
Invert_State = true
else
Invert_State = false
end
CP1R, CP1G, CP1B, CP1A = ui.get(Indic_Color1)
CP2R, CP2G, CP2B, CP2A = ui.get(Indic_Color2)
if ui.get(indic_switch) and entity.is_alive(lp) then
currentTime = currentTime + Indicators_AnimationSpeed
if currentTime >= 1.0 then
currentTime = 0
end
local ColorTime = currentTime * 2
local startColor, endColor
if ColorTime < 1 then
startColor = {CP1R, CP1G, CP1B, CP1A}
endColor = {CP2R, CP2G, CP2B, CP2A}
else
startColor = {CP2R, CP2G, CP2B, CP2A}
endColor = {CP1R, CP1G, CP1B, CP1A}
end
local currentColor = entitys.LerpColor(startColor, endColor, ColorTime % 1)
renderer.text(IndicX - anim[4], IndicY + add_y, currentColor[1], currentColor[2], currentColor[3], currentColor[4], 'cb', 0, VF_TEXT)
add_y = add_y + 7
renderer.rectangle(IndicX - anim[4] - 30, IndicY + add_y, 60, 2, currentColor[1], currentColor[2], currentColor[3], currentColor[4], 20)
DMG_Color_r, DMG_Color_g, DMG_Color_b ,DMG_Color_a = ui.get(IND_DMG_Color)
HC_Color_r, HC_Color_g, HC_Color_b, HC_Color_a = ui.get(IND_HC_Color)
if entitys.Contains(ui.get(Indicators_Selection), "DMG") then
add_y = add_y + 12
if ui.get(MINDMGOVR[2]) then
if ui.get(MINDMGOVR[3]) == 0 then
renderer.text(IndicX - anim[4], IndicY + add_y, DMG_Color_r, DMG_Color_g, DMG_Color_b ,DMG_Color_a , '-c', 0, "AUTO")
else
renderer.text(IndicX - anim[4], IndicY + add_y, DMG_Color_r, DMG_Color_g, DMG_Color_b ,DMG_Color_a , '-c', 0, string.format("DMG:%s", ui.get(MINDMGOVR[3])))
end
else
if ui.get(MINDMG) == 0 then
renderer.text(IndicX - anim[4], IndicY + add_y, DMG_Color_r, DMG_Color_g, DMG_Color_b ,DMG_Color_a , '-c', 0, "AUTO")
else
renderer.text(IndicX - anim[4], IndicY + add_y, DMG_Color_r, DMG_Color_g, DMG_Color_b ,DMG_Color_a , '-c', 0, string.format("DMG:%s", ui.get(MINDMG)))
end
end
end
if entitys.Contains(ui.get(Indicators_Selection), "HC") then
add_y = add_y + 12
renderer.text(IndicX - anim[4], IndicY + add_y, HC_Color_r, HC_Color_g, HC_Color_b, HC_Color_a, '-c', 0, string.format("HC:%s", ui.get(MINHTC)))
end
end
if ui.get(ViewmodelChanger) then
client.set_cvar("viewmodel_fov", ui.get(Viewmodel_fov))
client.set_cvar("viewmodel_offset_x", ui.get(Viewmodel_x))
client.set_cvar("viewmodel_offset_y", ui.get(Viewmodel_y))
client.set_cvar("viewmodel_offset_z", ui.get(Viewmodel_z))
end
if ui.get(RainbowHud) then
cvar.cl_hud_color:set_int(hudcolors[rb])
rb = rb + 1
if rb > 60 then
rb = 1
end
end
fading = KB_Ease_Length * 255 * 50 * globals.absoluteframetime()
MinDmgalpha = entitys.Clamp((ui.is_menu_open() and fading or -fading), 0, 255)
if ui.get(MinDmg_indicator) then
local pos2 = {MinDmg_indicator_drag:get()}
local MINDRAG_X, MINDRAG_Y = pos2[1], pos2[2]
database.write('MinDMG', {
x = pos2[1],
y = pos2[2],
alpha = MinDMG_Data.alpha,
})
if ui.get(MINDMGOVR[2]) then
if ui.get(MINDMGOVR[3]) == 0 then
renderer.text(MINDRAG_X, MINDRAG_Y, 255, 255, 255, 255, "", 0, "AUTO")
else
renderer.text(MINDRAG_X, MINDRAG_Y, 255, 255, 255, 255, "", 0, string.format("%.0f", ui.get(MINDMGOVR[3])))
end
else
if ui.get(MINDMG) == 0 then
renderer.text(MINDRAG_X, MINDRAG_Y, 255, 255, 255, 255, "", 0, "AUTO")
else
renderer.text(MINDRAG_X, MINDRAG_Y, 255, 255, 255, 255, "", 0, string.format("%.0f", ui.get(MINDMG)))
end
end
entitys.rectangle_outline(MINDRAG_X, MINDRAG_Y, 25, 25, 255, 255, 255, MinDMG_Data.alpha, 1)
end
if ui.get(Hitlog) then
if entitys.Contains(ui.get(HitLogs), "Under Crosshair") then
if #hitlog > 0 then
if globals.tickcount() >= hitlog[1][2] then
if hitlog[1][3] > 0 then
hitlog[1][3] = hitlog[1][3] - 20
elseif hitlog[1][3] <= 0 then
table.remove(hitlog, 1)
end
end
if #hitlog > 6 then
table.remove(hitlog, 1)
end
Log_Color_Box_R, Log_Color_Box_G, Log_Color_Box_B, Log_Color_Box_A = ui.get(Log_Color_Box)
local HITLOG_GAB = ui.get(Hitlog_Gaps) -- Adjust the HITLOG_GAB between boxes
for i = 1, #hitlog do
text_size_1_x, text_size_1_y = renderer.measure_text(nil, hitlog[i][1])
if hitlog[i][3] < 255 then
hitlog[i][3] = hitlog[i][3] + 10
end
box_width = text_size_1_x + 20
box_height = text_size_1_y + 10
box_x = CSSX / 2 - box_width / 2
box_y = CSSY / 1.5 + (box_height + HITLOG_GAB) * (i - 1) - box_height / 2
if ui.get(Hitlog_Disable_Anim) then
entitys.VF_Box_outline(box_x, box_y, box_width, box_height, Log_Color_Box_R, Log_Color_Box_G, Log_Color_Box_B, 255, ui.get(Hitlog_Trans))
else
entitys.VF_Box(box_x, box_y, box_width, box_height, Log_Color_Box_R, Log_Color_Box_G, Log_Color_Box_B, 255, text_size_1, ui.get(Hitlog_Trans))
end
local text_x = box_x + box_width / 2
local text_y = box_y + box_height / 2
renderer.text(text_x, text_y, 255, 255, 255, hitlog[i][3], "c", 0, hitlog[i][1])
end
end
end
end
WM_R, WM_G, WM_B, WM_A = ui.get(Water_Mark_VF_Color)
if ui.get(Water_Mark_VF) then
local latency = math.floor(client.latency()*1000+0.5)
local tickrate = 1/globals.tickinterval()
local hours, minutes, seconds = client.system_time()
local text = "VoltaFlame".." | ".. LUA_TYPE .. " | " ..LUA_BUILD.. " | " .. string.format("%sms", latency) .. " | " .. string.format("%02s:%02s", hours, minutes)
local margin, padding, flags = 18, 4, "b"
local text_width, text_height = renderer.measure_text(flags, text)
local container_x = CSSX - text_width - margin - padding
local container_y = margin - padding
local container_width = text_width + padding * 2
local container_height = text_height + padding * 2
if ui.get(Water_Mark_VF_Corner) then
ui.set(Water_Mark_VF_Corner_Slider, 10)
else
ui.set(Water_Mark_VF_Corner_Slider, 0)
end
if ui.get(Water_Mark_VF_Disable_Anim) then
entitys.VF_Box_outline(container_x, container_y, container_width, container_height, WM_R, WM_G, WM_B, WM_A, ui.get(Water_Mark_VF_Trans))
else
entitys.VF_Box(container_x, container_y, container_width, container_height, text_height, WM_R, WM_G, WM_B, WM_A, ui.get(Water_Mark_VF_Trans))
end
renderer.text(CSSX-text_width-margin, margin, 255, 255, 255, 255, flags, 0, text)
end
--keybinds
ui.set(bind_multi, keybind_options)
local pos = {KB_Binds:get()}
local bx, by = pos[1], pos[2]
local bw, bh = 210, 25
local pad = 5
database.write('KeyBinds', {
x = pos[1],
y = pos[2],
alpha = Kebind_Data.alpha,
})
for i, bind in ipairs(HotkeyLists) do
local hotkey_ind = entitys.get_hotkey_index(bind.Ref_KB)
local bind_hk = {ui.get(bind.Ref_KB[hotkey_ind[2]])}
active_binds[bind.use_name] = {bind.use_name, KB_Bind_State[bind_hk[2] + 1], bind_hk[1] and hotkey_ind[1], -1}
if (bind_hk[1] and hotkey_ind[1]) and not KB_Bind_Easing[bind.use_name] then
KB_Bind_Easing[bind.use_name] = {0, 0}
end
end
local total_active = 0
for j = 1, #keybind_options do
local bind = active_binds[keybind_options[j]]
local bind_name = bind[1]
if entitys.Contains(ui.get(bind_multi), bind_name) and (bind[3] or (KB_Bind_Easing[bind_name] and KB_Bind_Easing[bind_name][1] > 0)) then
total_active = total_active + 1
end
end
if ui.get(Keybinds_VF) then
Kebind_Data.alpha = entitys.Clamp(Kebind_Data.alpha + ((ui.is_menu_open() or (entity.is_alive(entity.get_local_player()) and total_active > 0)) and fading or -fading), 0, 255)
local base_sizex, base_sizey = renderer.measure_text(nil, "Keybinds")
if Kebind_Data.alpha > 1 then
local KB_R, KB_G, KB_B = ui.get(Keybinds_VF_Color)
local i, y_offset, desire_w = 1, 0, base_sizex * 1.5
for j = 1, #keybind_options do
local bind = active_binds[keybind_options[j]]
local bind_name = bind[1]
if entitys.Contains(ui.get(bind_multi), bind_name) and (bind[3] or (KB_Bind_Easing[bind_name] and KB_Bind_Easing[bind_name][1] > 0)) then
local line_y = by + bh + y_offset
local base_x = bx
local b_alpha = KB_Bind_Easing[bind_name][1] * 255
local partial = ("\a%02x%02x%02x%02x"):format(KB_R, KB_G, KB_B, b_alpha)
renderer.text(base_x + (KB_Current_Width * 0.5), line_y, 215, 215, 215, b_alpha, "c", 0, bind_name .. " - ".. partial .. bind[2])
local m_w, m_h = renderer.measure_text(nil, bind_name .. " - " .. bind[2])
y_offset = y_offset + m_h
desire_w = math.max(desire_w, m_w)
KB_Bind_Easing[bind_name][1] = bind[3] and easing.quad_out(KB_Bind_Easing[bind_name][2], 0, 1, KB_Ease_Length) or easing.quad_out(KB_Ease_Length - KB_Bind_Easing[bind_name][2], 1, -1, KB_Ease_Length)
KB_Bind_Easing[bind_name][1] = entitys.Clamp(KB_Bind_Easing[bind_name][1], 0, 1)
KB_Bind_Easing[bind_name][2] = bind[3] and KB_Bind_Easing[bind_name][2] + globals.absoluteframetime() or KB_Bind_Easing[bind_name][2] - globals.absoluteframetime()
KB_Bind_Easing[bind_name][2] = entitys.Clamp(KB_Bind_Easing[bind_name][2], 0, KB_Ease_Length)
i = i + 1
end
end
if desire_w - KB_Current_Width > 0 then
KB_Current_Width = entitys.Clamp(KB_Current_Width + (globals.absoluteframetime() * 200), base_sizex * 1.5, desire_w)
else
KB_Current_Width = entitys.Clamp(KB_Current_Width - (globals.absoluteframetime() * 200), desire_w, math.huge)
end
if ui.get(Keybinds_VF_Disable_Anim) then
entitys.VF_Box_outline(bx, by, math.floor(KB_Current_Width), base_sizey * 1.5, KB_R, KB_G, KB_B, 255, ui.get(Keybinds_VF_Trans))
else
entitys.VF_Box(bx, by, math.floor(KB_Current_Width), base_sizey * 1.5, KB_R, KB_G, KB_B, 255, base_sizey, ui.get(Keybinds_VF_Trans))
end
renderer.text(bx + (KB_Current_Width * 0.5), by + (base_sizey * 0.68), 255, 255, 255, Kebind_Data.alpha, "c", 0, "Keybinds")
end
if ui.get(DragSelection) == "Keybinds" then
KB_Binds:drag(KB_Current_Width * 1.5, base_sizey * 2)
elseif ui.get(DragSelection) == "MinDMG" then
MinDmg_indicator_drag:drag(25 , 25)
end
end
end
hitlog = {}
id = 1
hitgroup_names = {'Generic', 'Head', 'Chest', 'Stomach', 'Left arm', 'Right arm', 'Left leg', 'Right leg', 'Neck', '?', 'Gear'}
client.set_event_callback("aim_hit", function(e)
Log_Color_R, Log_Color_G, Log_Color_B = ui.get(Log_Color)
Hex_Log_Color = entitys.RGBtoHEX(Log_Color_R, Log_Color_G, Log_Color_B)
Hl_HitGroup = hitgroup_names[e.hitgroup + 1] or "?"
Hl_Name = string.lower(entity.get_player_name(e.target))
Hl_Target = e.target
HI_DMG = e.damage
Hl_Reason = e.reason
if ui.get(Hitlog) then
if entitys.Contains(ui.get(HitLogs), "Under Crosshair") then
if ui.get(RS_logs) then
hitlog[#hitlog+1] = {("\aFFFFFFFFShot At ".."\a"..Hex_Log_Color.."%s \aFFFFFFFFOn His ".."\a"..Hex_Log_Color.."%s \aFFFFFFFFfor ".."\a"..Hex_Log_Color.."%s \aFFFFFFFFHP! (Resolved Angle: ".."\a"..Hex_Log_Color.."%s \aFFFFFFFF)"):format(Hl_Name, Hl_HitGroup, HI_DMG, string.format("%.2f", RP_YAW)), globals.tickcount() + 250, 0}
else
hitlog[#hitlog+1] = {("\aFFFFFFFFShot At ".."\a"..Hex_Log_Color.."%s \aFFFFFFFFOn His ".."\a"..Hex_Log_Color.."%s \aFFFFFFFFfor ".."\a"..Hex_Log_Color.."%s \aFFFFFFFFHP!"):format(Hl_Name, Hl_HitGroup, HI_DMG), globals.tickcount() + 250, 0}
end
id = id == 999 and 1 or id + 1
end
if entitys.Contains(ui.get(HitLogs), "Console") then
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
if ui.get(RS_logs) then
client.color_log(255, 255, 255, "Shot At "..string.lower(entity.get_player_name(e.target)).." On His "..hitgroup_names[e.hitgroup + 1] .." For "..e.damage.." HP! (Resolved Angle: "..string.format("%.2f", RP_YAW)..")")
else
client.color_log(255, 255, 255, "Shot At "..string.lower(entity.get_player_name(e.target)).." On His "..hitgroup_names[e.hitgroup + 1] .." For "..e.damage.." HP!")
end
end
end
end)
client.set_event_callback("aim_miss", function(e)
Log_Color_R, Log_Color_G, Log_Color_B = ui.get(Log_Color)
Hex_Log_Color = entitys.RGBtoHEX(Log_Color_R, Log_Color_G, Log_Color_B)
Hl_HitGroup = hitgroup_names[e.hitgroup + 1] or "?"
Hl_Name = string.lower(entity.get_player_name(e.target))
Hl_Target = e.target
HI_DMG = e.damage
Hl_Reason = e.reason == "?" and "correction" or e.reason
e.reason = e.reason == "?" and "correction" or e.reason
if ui.get(Hitlog) then
if entitys.Contains(ui.get(HitLogs), "Under Crosshair") then
if ui.get(RS_logs) then
hitlog[#hitlog+1] = {("\aFFFFFFFFMiss Shot At ".."\a"..Hex_Log_Color.."%s \aFFFFFFFFOn His ".."\a"..Hex_Log_Color.."%s \aFFFFFFFFFor ".."\a"..Hex_Log_Color.."%s \aFFFFFFFFHP Due To ".."\a"..Hex_Log_Color.."%s \aFFFFFFFF! (Resolved Angle: ".."\a"..Hex_Log_Color.."%s \aFFFFFFFF)"):format(Hl_Name, Hl_HitGroup, HI_DMG, Hl_Reason, string.format("%.2f", RP_YAW)), globals.tickcount() + 250, 0}
else
hitlog[#hitlog+1] = {("\aFFFFFFFFMiss Shot At ".."\a"..Hex_Log_Color.."%s \aFFFFFFFFOn His ".."\a"..Hex_Log_Color.."%s \aFFFFFFFFFor ".."\a"..Hex_Log_Color.."%s \aFFFFFFFFHP Due To ".."\a"..Hex_Log_Color.."%s \aFFFFFFFF!"):format(Hl_Name, Hl_HitGroup, HI_DMG, Hl_Reason), globals.tickcount() + 250, 0}
end
id = id == 999 and 1 or id + 1
end
if entitys.Contains(ui.get(HitLogs), "Console") then
if ui.get(RS_logs) then
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, "Miss Shot At "..string.lower(entity.get_player_name(e.target)).." On His "..hitgroup_names[e.hitgroup + 1].." HP Due To "..e.reason.." ! (Resolved Angle: "..RP_YAW..")")
else
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, "Miss Shot At "..string.lower(entity.get_player_name(e.target)).." On His "..hitgroup_names[e.hitgroup + 1].." HP Due To "..e.reason.." !")
end
end
end
end)
--misc
--fps booster
FpsBoost = ui.new_checkbox("AA", "Anti-aimbot angles", "FPS Boost (Disabling It Will Requires Restart)")
--buybot
Buybot = ui.new_checkbox("AA", "Anti-aimbot angles", "Buybot")
PrimaryWeapon = ui.new_combobox("AA", "Anti-aimbot angles", "Primary Weapon",{"-", "AWP", "SCAR20/G3SG1", "SSG-08"})
SecondaryWeapon = ui.new_combobox("AA", "Anti-aimbot angles", "Secondary Weapon",{"-", "CZ75/Tec9/FiveSeven", "P250", "Deagle/Revolver", "Dualies"})
Grenades = ui.new_multiselect("AA", "Anti-aimbot angles", "Grenades",{"HE Grenade", "Molotov", "Smoke", "Flash", "Decoy"})
Utilities = ui.new_multiselect("AA", "Anti-aimbot angles", "Utilities",{"Armor", "Helmet", "Zeus", "Defuser"})
MiscSystemRenderer = function()
ui.set_visible(FpsBoost, container == "MiscContainer")
ui.set_visible(Buybot, container == "MiscContainer")
ui.set_visible(PrimaryWeapon, container == "MiscContainer" and ui.get(Buybot))
ui.set_visible(SecondaryWeapon, container == "MiscContainer" and ui.get(Buybot))
ui.set_visible(Grenades, container == "MiscContainer" and ui.get(Buybot))
ui.set_visible(Utilities, container == "MiscContainer" and ui.get(Buybot))
menu_ui()
ui.set_visible(NameSpammer, container == "MiscContainer")
ui.set_visible(NameSpammer_InputText, container == "MiscContainer" and ui.get(NameSpammer))
ui.set_visible(NameSpammer_Input, container == "MiscContainer" and ui.get(NameSpammer))
ui.set_visible(NameSpammer_Button, container == "MiscContainer" and ui.get(NameSpammer))
end
FpsBoostSystem = function()
if ui.get(FpsBoost) then
cvar.cl_disablefreezecam:set_float(1)
cvar.cl_disablehtmlmotd:set_float(1)
cvar.r_dynamic:set_float(0)
cvar.r_3dsky:set_float(0)
cvar.r_shadows:set_float(0)
cvar.cl_csm_static_prop_shadows:set_float(0)
cvar.cl_csm_world_shadows:set_float(0)
cvar.cl_foot_contact_shadows:set_float(0)
cvar.cl_csm_viewmodel_shadows:set_float(0)
cvar.cl_csm_rope_shadows:set_float(0)
cvar.cl_csm_sprite_shadows:set_float(0)
cvar.cl_freezecampanel_position_dynamic:set_float(0)
cvar.cl_freezecameffects_showholiday:set_float(0)
cvar.cl_showhelp:set_float(0)
cvar.cl_autohelp:set_float(0)
cvar.mat_postprocess_enable:set_float(0)
cvar.fog_enable_water_fog:set_float(0)
cvar.gameinstructor_enable:set_float(0)
cvar.cl_csm_world_shadows_in_viewmodelcascade:set_float(0)
cvar.cl_disable_ragdolls:set_float(0)
end
end
MiscSystem = function()
FpsBoostSystem()
end
-- Clantag Changer
local CT_Tag = {}
local function DoAnimation(CT_Tag, CT_Animation)
local CT_Old = nil
local CT_Anim = {}
if CT_Animation == 2 then
return {CT_Tag}
elseif CT_Animation == 1 then
for i in CT_Tag:gmatch(".") do
if CT_Old == nil then
table.insert(CT_Anim, i)
CT_Old = i
else
table.insert(CT_Anim, CT_Old .. i)
CT_Old = CT_Old .. i
end
end
for i in CT_Tag:gmatch(".") do
table.insert(CT_Anim, CT_Old)
CT_Old = string.gsub(CT_Old, i, "", 1)
end
table.insert(CT_Anim, "")
return CT_Anim
elseif CT_Animation == 4 then
if CT_Old == nil then
table.insert(CT_Anim, CT_Tag)
CT_Old = CT_Tag .. " "
end
for i in CT_Tag:gmatch(".") do
table.insert(CT_Anim, CT_Old:gsub(i, "", 1) .. i)
CT_Old = CT_Old:gsub(i, "", 1) .. i
end
return CT_Anim
else
local TG = CT_Tag:reverse()
for i in TG:gmatch(".") do
if CT_Old == nil then
table.insert(CT_Anim, i)
CT_Old = i
else
table.insert(CT_Anim, i .. CT_Old)
CT_Old = i .. CT_Old
end
end
for i in CT_Tag:gmatch(".") do
table.insert(CT_Anim, CT_Old)
CT_Old = string.gsub(CT_Old, i, "", 1)
end
table.insert(CT_Anim, "")
return CT_Anim
end
end
--clantag
CustomClantag = ui.new_checkbox("AA", "Anti-aimbot angles","Custom Clantag")
Clantag_Type = ui.new_combobox("AA", "Anti-aimbot angles", "Clantag Type", {"Voltaflame", "Custom"})
Clantag_InputText = ui.new_label("AA", "Anti-aimbot angles", "Clantag Input: ")
Clantag_input = ui.new_textbox("AA", "Anti-aimbot angles", "Clantag Input")
Clantag_AnimationType_Combo = ui.new_combobox("AA", "Anti-aimbot angles", "Clantag Type", {"Normal", "Static", "Roll", "Reverse"})
Clantag_AnimationType = ui.new_slider("AA", "Anti-aimbot angles", "ClanTag Modes", 1, 4, 1)
Clantag_AnimationSpeed = ui.new_slider("AA", "Anti-aimbot angles", "ClanTag Speed", 1, 100, 50)
Clantag_Options = ui.new_multiselect("AA", "Anti-aimbot angles", "Other Clantag_Options", {"Invisible Name", "Prefix", "Suffix"})
Clantag_PrefixText = ui.new_label("AA", "Anti-aimbot angles", "Clantag Prefix: ")
Clantag_PrefixInput = ui.new_textbox("AA", "Anti-aimbot angles", "Prefix")
Clantag_SuffixText = ui.new_label("AA", "Anti-aimbot angles", "Clantag Suffix: ")
Clantag_SuffixInput = ui.new_textbox("AA", "Anti-aimbot angles", "Suffix")
Clantag_AnimationConsole = ui.new_button("AA", "Anti-aimbot angles", "View ClanTag Animation In Console", function()
if ui.get(Clantag_Type) == "Custom" then
CreatedAnimation = DoAnimation(ui.get(Clantag_input), ui.get(Clantag_AnimationType))
else
CreatedAnimation = DoAnimation("VoltaFlame", ui.get(Clantag_AnimationType))
end
client.log("\aEKD1FF[VoltaFlame]", "ClanTag ANIMATION:")
for k, v in ipairs(CreatedAnimation) do
client.log("[" .. k .. "] " .. v)
end
end)
function menu_ui()
ui.set_visible(CustomClantag, container == "MiscContainer")
ui.set_visible(Clantag_Type, container == "MiscContainer" and ui.get(CustomClantag))
ui.set_visible(Clantag_InputText, container == "MiscContainer" and ui.get(CustomClantag) and ui.get(Clantag_Type) == "Custom")
ui.set_visible(Clantag_AnimationType, false)
ui.set_visible(Clantag_AnimationType_Combo, container == "MiscContainer" and ui.get(CustomClantag))
ui.set_visible(Clantag_input, container == "MiscContainer" and ui.get(CustomClantag) and ui.get(Clantag_Type) == "Custom")
ui.set_visible(Clantag_AnimationSpeed, container == "MiscContainer" and ui.get(CustomClantag) and ui.get(Clantag_AnimationType) ~= 2)
ui.set_visible(Clantag_AnimationConsole, container == "MiscContainer" and ui.get(CustomClantag) and ui.get(Clantag_AnimationType) ~= 2 and ui.get(Clantag_Type) == "Custom")
ui.set_visible(Clantag_Options, container == "MiscContainer" and ui.get(CustomClantag) and ui.get(Clantag_Type) == "Custom")
ui.set_visible(Clantag_SuffixText, container == "MiscContainer" and ui.get(CustomClantag) and entitys.Contains(ui.get(Clantag_Options), "Suffix") and ui.get(Clantag_Type) == "Custom")
ui.set_visible(Clantag_SuffixInput, container == "MiscContainer" and ui.get(CustomClantag) and entitys.Contains(ui.get(Clantag_Options), "Suffix") and ui.get(Clantag_Type) == "Custom")
ui.set_visible(Clantag_PrefixText, container == "MiscContainer" and ui.get(CustomClantag) and entitys.Contains(ui.get(Clantag_Options), "Prefix") and ui.get(Clantag_Type) == "Custom")
ui.set_visible(Clantag_PrefixInput, container == "MiscContainer" and ui.get(CustomClantag) and entitys.Contains(ui.get(Clantag_Options), "Prefix") and ui.get(Clantag_Type) == "Custom")
if ui.get(Clantag_AnimationType_Combo) == "Normal" then
ui.set(Clantag_AnimationType, 1)
elseif ui.get(Clantag_AnimationType_Combo) == "Static" then
ui.set(Clantag_AnimationType, 2)
elseif ui.get(Clantag_AnimationType_Combo) == "Roll" then
ui.set(Clantag_AnimationType, 3)
elseif ui.get(Clantag_AnimationType_Combo) == "Reverse" then
ui.set(Clantag_AnimationType, 4)
end
end
CT_OldTime = nil
client.set_event_callback("paint", function()
if ui.get(CustomClantag) then
if ui.get(Clantag_AnimationType) == 2 then
local Clantag_HideName = ""
local Clantag_Suffix = ""
local Clantag_Prefix = ""
if entitys.Contains(ui.get(Clantag_Options), "Invisible Name") then
Clantag_HideName = "\n"
end
if entitys.Contains(ui.get(Clantag_Options), "Suffix") then
Clantag_Suffix = ui.get(Clantag_SuffixInput)
end
if entitys.Contains(ui.get(Clantag_Options), "Prefix") then
Clantag_Prefix = ui.get(Clantag_PrefixInput)
end
if ui.get(Clantag_Type) == "Custom" then
client.set_clan_tag(Clantag_Prefix .. "VoltaFlame" .. Clantag_Suffix .. Clantag_HideName)
else
client.set_clan_tag(Clantag_Prefix .. "VoltaFlame" .. Clantag_Suffix .. Clantag_HideName)
end
return
end
if ui.get(Clantag_Type) == "Custom" then
CT_Tag = DoAnimation(ui.get(Clantag_input), ui.get(Clantag_AnimationType))
else
CT_Tag = DoAnimation("VoltaFlame", ui.get(Clantag_AnimationType))
end
if ui.get(Clantag_AnimationType) == 2 then
return
end
local curtime = math.floor(globals.curtime())
local speed = ui.get(Clantag_AnimationSpeed)
local latency = client.latency() / globals.tickinterval()
local tickcount_ = globals.tickcount() + latency
local Clantag_HideName = ""
local Clantag_Suffix = ""
local Clantag_Prefix = ""
if entitys.Contains(ui.get(Clantag_Options), "Invisible Name") then
Clantag_HideName = "\n"
end
if entitys.Contains(ui.get(Clantag_Options), "Suffix") then
Clantag_Suffix = ui.get(Clantag_SuffixInput)
end
if entitys.Contains(ui.get(Clantag_Options), "Prefix") then
Clantag_Prefix = ui.get(Clantag_PrefixInput)
end
CT_iter = #CT_Tag > 1 and math.floor(math.fmod(tickcount_ / speed, #CT_Tag)) + 1 or #CT_Tag
if CT_OldTime ~= curtime then
client.set_clan_tag(Clantag_Prefix .. CT_Tag[CT_iter] .. Clantag_Suffix .. Clantag_HideName)
end
CT_OldTime = curtime
end
end)
if not ui.get(CustomClantag) then
client.set_clan_tag("")
end
--name spammer
function DoNameSpam(N_Delay, N_Name)
client.delay_call(N_Delay, function()
client.set_cvar("name", N_Name)
end)
end
NameSpammer = ui.new_checkbox("AA", "Anti-aimbot angles", "Name Spammer")
NameSpammer_InputText = ui.new_label("AA", "Anti-aimbot angles", "Name:")
NameSpammer_Input = ui.new_textbox("AA", "Anti-aimbot angles", "Name")
NameSpammer_Button = ui.new_button("AA", "Anti-aimbot angles", "Name Spam!", function()
if ui.get(NameSpammer) then
NameSpammer_Input_1 = nil
NameSpammer_Input_2 = nil
ui.set(NAMESTEAL, true)
NameSpammer_Input_1 = ui.get(NameSpammer_Input)
NameSpammer_Input_2 = NameSpammer_Input_1..""
client.set_cvar("name", NameSpammer_Input_1)
DoNameSpam(0.1, NameSpammer_Input_2)
DoNameSpam(0.2, NameSpammer_Input_1)
DoNameSpam(0.3, NameSpammer_Input_2)
DoNameSpam(0.4, NameSpammer_Input_1)
end
end)
BuyBotSystem = function(e)
--Primary
if ui.get(Buybot) then
if ui.get(PrimaryWeapon) == "AWP" then
client.exec("buy awp;")
end
if ui.get(PrimaryWeapon) == "SCAR20/G3SG1" then
client.exec("buy scar20;")
end
if ui.get(PrimaryWeapon) == "SSG-08" then
client.exec("buy ssg08;")
end
--Secondary
if ui.get(SecondaryWeapon) == "CZ75/Tec9/FiveSeven" then
client.exec("buy tec9;")
end
if ui.get(SecondaryWeapon) == "P250" then
client.exec("buy p250;")
end
if ui.get(SecondaryWeapon) == "Deagle/Revolver" then
client.exec("buy deagle;")
end
if ui.get(SecondaryWeapon) == "Dualies" then
client.exec("buy elite;")
end
--Grenades
if entitys.Contains(ui.get(Grenades), "HE Grenade") then
client.exec("buy hegrenade;")
end
if entitys.Contains(ui.get(Grenades), "Molotov") then
client.exec("buy molotov;")
end
if entitys.Contains(ui.get(Grenades), "Smoke") then
client.exec("buy smokegrenade;")
end
if entitys.Contains(ui.get(Grenades), "Flash") then
client.exec("buy flashbang;")
end
if entitys.Contains(ui.get(Grenades), "Decoy") then
client.exec("buy decoy;")
end
--Utilities
if entitys.Contains(ui.get(Utilities), "Armor") then
client.exec("buy vest;")
end
if entitys.Contains(ui.get(Utilities), "Helmet") then
client.exec("buy vesthelm;")
end
if entitys.Contains(ui.get(Utilities), "Zeus") then
client.exec("buy taser 34;")
end
if entitys.Contains(ui.get(Utilities), "Defuser") then
client.exec("buy defuser;")
end
end
end
config_data = {
booleans = {
},
colorscodes = {
Indic_Color1,
Indic_Color2,
Log_Color,
Log_Color_Box,
Water_Mark_VF_Color,
Keybinds_VF_Color,
}
}
function import(cfg)
status, config = pcall(function() return json.parse(base64.decode(cfg)) end)
if not status or status == nil then
client.color_log(255, 0, 0, "[Voltaflame] \0")
client.color_log(255, 255, 255,"The Code Is Invalid Or Outdated!")
return end
for k, v in pairs(config) do
k = ({[1] = "booleans", [2] = "colorscodes"})[k]
for k2, v2 in pairs(v) do
if (k == "booleans") then
ui.set(config_data[k][k2], (v2))
end
if (k == "colorscodes") then
col_r, col_g, col_b, col_a = tonumber('0x'..v2:sub(1,2)), tonumber('0x'..v2:sub(3,4)), tonumber('0x'..v2:sub(5, 6)), tonumber('0x'..v2:sub(7,8))
ui.set(config_data[k][k2], col_r, col_g, col_b, col_a)
end
end
end
client.color_log(0, 255, 0, "[Voltaflame] \0")
client.color_log(255, 255, 255,"Config Imported!")
end
Default_CFG = ui.new_button("AA", "Anti-aimbot angles", "Load Default Preset", function()
import("W1t0cnVlLCJEb3duIiwwLDAsIkF0IFRhcmdldHMiLCJEZWZlbnNpdmUiLC0yMSwxOSwiU2tpdHRlciIsNSw3LC0xMiwiQW50aS1CcnV0ZWZvcmNlIiwyOCwtMjQsdHJ1ZSx0cnVlLCJEb3duIiwwLDAsIkF0IFRhcmdldHMiLCIxODAgWiIsLTcsNywiU2tpdHRlciIsMiwxNiwtMTQsIkppdHRlciIsMywtNSx0cnVlLHRydWUsIkRlZmVuc2l2ZSIsODksLTg5LCJBdCBUYXJnZXRzIiwiRGVmZW5zaXZlIiw0MCwtMzUsIlJhbmRvbSIsMiwtMTQsMTQsIkppdHRlciIsMzAsLTE5LHRydWUsdHJ1ZSwiTWluaW1hbCIsMCwwLCJBdCBUYXJnZXRzIiwiRGVmZW5zaXZlIiw3LC03LCJPZmZzZXQiLDIsNywtMywiQW50aS1CcnV0ZWZvcmNlIiwtOCw3LHRydWUsdHJ1ZSwiRG93biIsMCwwLCJBdCBUYXJnZXRzIiwiU3BpbiIsMjEsLTM1LCJSYW5kb20iLDMsLTIyLDI0LCJPcHBvc2l0ZSIsMCwwLGZhbHNlLHRydWUsIkRvd24iLDAsMCwiQXQgVGFyZ2V0cyIsIkRlZmVuc2l2ZSIsLTE2LDIzLCJDZW50ZXIiLDMsMTAsLTEwLCJKaXR0ZXIiLDI0LC0yOCx0cnVlLDUsMCwwLDAsMCwwLC0xLC0yLDAsMCwwLDUsNSwyLDUsNSwyLDUsZmFsc2Use30se30sNTAsNTAsNTAsNTAsNTAsNTAsNTAsZmFsc2UsNSxmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSx7fSxmYWxzZSwxLGZhbHNlLHt9LGZhbHNlLDEsMSwxLDEsZmFsc2UsZmFsc2UsZmFsc2UsZmFsc2UsZmFsc2UsIkN1c3RvbSIsIltTV10gU2xvdyBXYWxrIixmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSxmYWxzZSw2OCwyLDAsLTIsZmFsc2UsZmFsc2UsZmFsc2Use30sNixmYWxzZSxmYWxzZSxmYWxzZSwiLSIsIi0iLHt9LHt9LGZhbHNlLCJWb2x0YWZsYW1lIiwiIiwiTm9ybWFsIiw1MCx7fSxmYWxzZSx7fSwxLDEsMV0sWyJGRjAwMDBGRiIsIkZGMDAwMEZGIiwiRkYwMDAwRkYiLCJGRjAwMDBGRiIsIkZGMDAwMEZGIiwiRkYwMDAwRkYiXV0=")
end)
Import_CFG = ui.new_button("AA", "Anti-aimbot angles", "Import", function()
import(clipboard.get())
end)
Export_CFG = ui.new_button("AA", "Anti-aimbot angles", "Export", function()
config_code = {{}, {}}
for _, booleans in pairs(config_data.booleans) do
table.insert(config_code[1], ui.get(booleans))
end
for _, colorscodes in pairs(config_data.colorscodes) do
col_r, col_g, col_b, col_a = ui.get(colorscodes)
table.insert(config_code[2], string.format('%02X%02X%02X%02X', math.floor(col_r), math.floor(col_g), math.floor(col_b), math.floor(col_a)))
end
clipboard.set(base64.encode(json.stringify(config_code)))
client.color_log(0, 255, 0, "[Voltaflame] \0")
client.color_log(255, 255, 255,"Config Exported To Clipboard!")
end)
Already_Shared = false
LastSharedCFG = 0
DelayForCFGSHARE = 60 -- 5 minutes in seconds
Discord_CFGShare = ui.new_button("AA", "Anti-aimbot angles", "Share CFG On Discord", function()
Current_Time_For_CFG = globals.realtime()
if Already_Shared then
local elapsedTime = Current_Time_For_CFG - LastSharedCFG
if elapsedTime < DelayForCFGSHARE then
local remainingTime = DelayForCFGSHARE - elapsedTime
client.color_log(255, 0, 0, "[Voltaflame] \0")
client.color_log(255, 255, 255, "Config Has Already Been Clicked. Please wait " .. string.format("%.2f", remainingTime).. " Seconds.")
return
end
end
Already_Shared = true
LastSharedCFG = Current_Time_For_CFG
config_code = {{}, {}}
for _, booleans in pairs(config_data.booleans) do
table.insert(config_code[1], ui.get(booleans))
end
for _, colorscodes in pairs(config_data.colorscodes) do
col_r, col_g, col_b, col_a = ui.get(colorscodes)
table.insert(config_code[2], string.format('%02X%02X%02X%02X', math.floor(col_r), math.floor(col_g), math.floor(col_b), math.floor(col_a)))
end
data = Discord.new("")
embeds = Discord.newEmbed()
MenuColorDecimal = entitys.RGBtoDecimal(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B)
embeds:setColor(MenuColorDecimal)
embeds:setTitle("Config For ["..LUA_BUILD.."]")
embeds:setDescription(base64.encode(json.stringify(config_code)))
embeds:setThumbnail("https://cdn.discordapp.com/attachments/1130578613410996396/1145491087541162154/VF_Logo_GS.png")
embeds:setImage("https://cdn.discordapp.com/attachments/1130578613410996396/1145491085502730270/Full_Logo_GS.png")
embeds:setFooter("ꜰᴜʟʟ ꜱʏꜱᴛᴇᴍ ᴄᴏɴꜰɪɢ ꜰᴏʀ ʀᴀɢᴇ ʟᴜᴀ")
data:send(embeds)
client.color_log(0, 255, 0, "[Voltaflame] \0")
client.color_log(255, 255, 255,"Successfully Shared To Discord!")
-- Reset the button after the delay
client.delay_call(DelayForCFGSHARE, function()
Already_Shared = false
end)
end)
client.set_event_callback("paint_ui", function()
ui.set_visible(Default_CFG, container == "CFGContainer")
ui.set_visible(Import_CFG, container == "CFGContainer")
ui.set_visible(Export_CFG, container == "CFGContainer")
ui.set_visible(Discord_CFGShare, container == "CFGContainer")
end)
--callbacks
client.set_event_callback("round_prestart", function()
BuyBotSystem()
end)
client.set_event_callback("setup_command", function()
OtherAASystem()
MiscSystem()
end)
client.set_event_callback("paint", function()
Animation_System()
VisualsSystem()
end)
client.set_event_callback("net_update_start", function()
NV_Resolver()
end)
client.set_event_callback("paint_ui", function()
if ui.is_menu_open() then
MainLabel()
Animation_System_Renderer()
AATabsRenderer()
OtherAASystemRenderer()
RageSystemRenderer()
VisualsSystemRenderer()
MiscSystemRenderer()
end
ui.set_visible(ENABLE, false)
ui.set_visible(PITCH[1], false)
ui.set_visible(PITCH[2], false)
ui.set_visible(YAWBASE, false)
ui.set_visible(YAW[1], false)
ui.set_visible(YAW[2], false)
ui.set_visible(YAWJITTER[1], false)
ui.set_visible(YAWJITTER[2], false)
ui.set_visible(BODYYAW[1], false)
ui.set_visible(BODYYAW[2], false)
ui.set_visible(BODYYAWFREESTAND, false)
ui.set_visible(FREESTANDING, false)
ui.set_visible(EDGEYAW, false)
ui.set_visible(EXTENDEDROLL, false)
ui.set_visible(LEGMOVEMENT, false)
end)
client.set_event_callback("shutdown", function()
e.roll = 0
C_Yaw = C_Yaw
client.set_cvar("viewmodel_fov", 68)
client.set_cvar("viewmodel_offset_x", 2.5)
client.set_cvar("viewmodel_offset_y", 0)
client.set_cvar("viewmodel_offset_z", -1.5)
ui.set(PROCESSTICK, 16)
ui.set(MAXUNLAG, 200)
client.set_clan_tag("")
client.exec("clear")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, "Unloading The Script...")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, "Unloading The Script..")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, "Unloading The Script.")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, "The Script Has Been Unloaded!")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, "Hope You Enjoyed Using Our Product!")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, "Contact Us On Discord If You Are Having Any Issues!")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, " ")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, " ")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, "discord.gg/voltaflame")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, " ")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, " ")
client.color_log(MENUCOLOR_R, MENUCOLOR_G, MENUCOLOR_B, "[Voltaflame] \0")
client.color_log(255, 255, 255, "Peace!")
ui.set_visible(ENABLE, true)
ui.set_visible(PITCH[1], true)
ui.set_visible(PITCH[2], true)
ui.set_visible(YAWBASE, true)
ui.set_visible(YAW[1], true)
ui.set_visible(YAW[2], true)
ui.set_visible(YAWJITTER[1], true)
ui.set_visible(YAWJITTER[2], true)
ui.set_visible(BODYYAW[1], true)
ui.set_visible(BODYYAW[2], true)
ui.set_visible(BODYYAWFREESTAND, true)
ui.set_visible(FREESTANDING, true)
ui.set_visible(EDGEYAW, true)
ui.set_visible(EXTENDEDROLL, true)
ui.set_visible(SLOWMOTION[1], true)
ui.set_visible(SLOWMOTION[2], true)
ui.set_visible(LEGMOVEMENT, true)
ui.set_visible(HIDESHOT[1], true)
ui.set_visible(HIDESHOT[2], true)
ui.set_visible(FAKEPEEK, true)
ui.set_visible(FAKELAGENABLE, true)
ui.set_visible(FAKELAGAMOUNT, true)
ui.set_visible(FAKELAGVARIANCE, true)
ui.set_visible(FAKELAGLIMIT, true)
end)
| 0 | 0.953717 | 1 | 0.953717 | game-dev | MEDIA | 0.545018 | game-dev,desktop-app | 0.980478 | 1 | 0.980478 |
LordOfDragons/dragengine | 3,034 | src/dragengine/src/resources/collider/deColliderReference.cpp | /*
* MIT License
*
* Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch)
*
* 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 "deCollider.h"
#include "deColliderReference.h"
// Class deColliderReference
//////////////////////////////
// Constructor, destructor
////////////////////////////
deColliderReference::deColliderReference(){
}
deColliderReference::deColliderReference( deCollider *object ) :
deObjectReference( object ){
}
deColliderReference::deColliderReference( const deColliderReference &reference ) :
deObjectReference( reference ){
}
// Management
///////////////
void deColliderReference::TakeOver( deCollider *object ){
deObjectReference::TakeOver( object );
}
bool deColliderReference::operator!() const{
return deObjectReference::operator!();
}
deColliderReference::operator bool() const{
return deObjectReference::operator bool();
}
deColliderReference::operator deCollider *() const{
return ( deCollider* )operator deObject *();
}
deColliderReference::operator deCollider &() const{
return ( deCollider& )operator deObject &();
}
deCollider *deColliderReference::operator->() const{
return ( deCollider* )deObjectReference::operator->();
}
deColliderReference &deColliderReference::operator=( deCollider *object ){
deObjectReference::operator=( object );
return *this;
}
deColliderReference &deColliderReference::operator=( const deColliderReference &reference ){
deObjectReference::operator=( reference );
return *this;
}
bool deColliderReference::operator==( deCollider *object ) const{
return deObjectReference::operator==( object );
}
bool deColliderReference::operator!=( deCollider *object ) const{
return deObjectReference::operator!=( object );
}
bool deColliderReference::operator==( const deColliderReference &reference ) const{
return deObjectReference::operator==( reference );
}
bool deColliderReference::operator!=( const deColliderReference &reference ) const{
return deObjectReference::operator!=( reference );
}
| 0 | 0.689325 | 1 | 0.689325 | game-dev | MEDIA | 0.343196 | game-dev | 0.662258 | 1 | 0.662258 |
FMXExpress/Firemonkey | 3,688 | Embarcadero/Rio/CPP/TestBed/Tests/BodyTypes.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 BODY_TYPES_H
#define BODY_TYPES_H
class BodyTypes : public Test
{
public:
BodyTypes()
{
b2Body* ground = NULL;
{
b2BodyDef bd;
ground = m_world->CreateBody(&bd);
b2EdgeShape shape;
shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f));
b2FixtureDef fd;
fd.shape = &shape;
ground->CreateFixture(&fd);
}
// Define attachment
{
b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.position.Set(0.0f, 3.0f);
m_attachment = m_world->CreateBody(&bd);
b2PolygonShape shape;
shape.SetAsBox(0.5f, 2.0f);
m_attachment->CreateFixture(&shape, 2.0f);
}
// Define platform
{
b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.position.Set(-4.0f, 5.0f);
m_platform = m_world->CreateBody(&bd);
b2PolygonShape shape;
shape.SetAsBox(0.5f, 4.0f, b2Vec2(4.0f, 0.0f), 0.5f * b2_pi);
b2FixtureDef fd;
fd.shape = &shape;
fd.friction = 0.6f;
fd.density = 2.0f;
m_platform->CreateFixture(&fd);
b2RevoluteJointDef rjd;
rjd.Initialize(m_attachment, m_platform, b2Vec2(0.0f, 5.0f));
rjd.maxMotorTorque = 50.0f;
rjd.enableMotor = true;
m_world->CreateJoint(&rjd);
b2PrismaticJointDef pjd;
pjd.Initialize(ground, m_platform, b2Vec2(0.0f, 5.0f), b2Vec2(1.0f, 0.0f));
pjd.maxMotorForce = 1000.0f;
pjd.enableMotor = true;
pjd.lowerTranslation = -10.0f;
pjd.upperTranslation = 10.0f;
pjd.enableLimit = true;
m_world->CreateJoint(&pjd);
m_speed = 3.0f;
}
// Create a payload
{
b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.position.Set(0.0f, 8.0f);
b2Body* body = m_world->CreateBody(&bd);
b2PolygonShape shape;
shape.SetAsBox(0.75f, 0.75f);
b2FixtureDef fd;
fd.shape = &shape;
fd.friction = 0.6f;
fd.density = 2.0f;
body->CreateFixture(&fd);
}
}
void Keyboard(int key)
{
switch (key)
{
case GLFW_KEY_D:
m_platform->SetType(b2_dynamicBody);
break;
case GLFW_KEY_S:
m_platform->SetType(b2_staticBody);
break;
case GLFW_KEY_K:
m_platform->SetType(b2_kinematicBody);
m_platform->SetLinearVelocity(b2Vec2(-m_speed, 0.0f));
m_platform->SetAngularVelocity(0.0f);
break;
}
}
void Step(Settings* settings)
{
// Drive the kinematic body.
if (m_platform->GetType() == b2_kinematicBody)
{
b2Vec2 p = m_platform->GetTransform().p;
b2Vec2 v = m_platform->GetLinearVelocity();
if ((p.x < -10.0f && v.x < 0.0f) ||
(p.x > 10.0f && v.x > 0.0f))
{
v.x = -v.x;
m_platform->SetLinearVelocity(v);
}
}
Test::Step(settings);
g_debugDraw.DrawString(5, m_textLine, "Keys: (d) dynamic, (s) static, (k) kinematic");
m_textLine += DRAW_STRING_NEW_LINE;
}
static Test* Create()
{
return new BodyTypes;
}
b2Body* m_attachment;
b2Body* m_platform;
float32 m_speed;
};
#endif
| 0 | 0.859373 | 1 | 0.859373 | game-dev | MEDIA | 0.858411 | game-dev,testing-qa | 0.837947 | 1 | 0.837947 |
fortressforever/fortressforever | 4,179 | game_shared/saverestore_utlmap.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef SAVERESTORE_UTLMAP_H
#define SAVERESTORE_UTLMAP_H
#include "utlmap.h"
#include "saverestore_utlrbtree.h"
#if defined( _WIN32 )
#pragma once
#endif
template <class UTLMAP, int KEY_TYPE, int FIELD_TYPE>
class CUtlMapDataOps : public CDefSaveRestoreOps
{
public:
CUtlMapDataOps()
{
UTLCLASS_SAVERESTORE_VALIDATE_TYPE( KEY_TYPE );
UTLCLASS_SAVERESTORE_VALIDATE_TYPE( FIELD_TYPE );
}
virtual void Save( const SaveRestoreFieldInfo_t &fieldInfo, ISave *pSave )
{
datamap_t *pKeyDatamap = CTypedescDeducer<KEY_TYPE>::Deduce( (UTLMAP *)NULL );
datamap_t *pFieldDatamap = CTypedescDeducer<FIELD_TYPE>::Deduce( (UTLMAP *)NULL );
typedescription_t dataDesc[] =
{
{
(fieldtype_t)KEY_TYPE,
"K",
{ 0, 0 },
1,
FTYPEDESC_SAVE,
NULL,
NULL,
NULL,
pKeyDatamap,
sizeof(KEY_TYPE),
},
{
(fieldtype_t)FIELD_TYPE,
"T",
{ offsetof(typename UTLMAP::Node_t, elem), 0 },
1,
FTYPEDESC_SAVE,
NULL,
NULL,
NULL,
pFieldDatamap,
sizeof(FIELD_TYPE),
}
};
datamap_t dataMap =
{
dataDesc,
2,
"um",
NULL,
false,
false,
0,
#ifdef DEBUG
true
#endif
};
typename UTLMAP::CTree *pUtlRBTree = ((UTLMAP *)fieldInfo.pField)->AccessTree();
pSave->StartBlock();
int nElems = pUtlRBTree->Count();
pSave->WriteInt( &nElems, 1 );
typename UTLMAP::CTree::IndexType_t i = pUtlRBTree->FirstInorder();
while ( i != pUtlRBTree->InvalidIndex() )
{
typename UTLMAP::CTree::ElemType_t &elem = pUtlRBTree->Element( i );
pSave->WriteAll( &elem, &dataMap );
i = pUtlRBTree->NextInorder( i );
}
pSave->EndBlock();
}
virtual void Restore( const SaveRestoreFieldInfo_t &fieldInfo, IRestore *pRestore )
{
datamap_t *pKeyDatamap = CTypedescDeducer<KEY_TYPE>::Deduce( (UTLMAP *)NULL );
datamap_t *pFieldDatamap = CTypedescDeducer<FIELD_TYPE>::Deduce( (UTLMAP *)NULL );
typedescription_t dataDesc[] =
{
{
(fieldtype_t)KEY_TYPE,
"K",
{ 0, 0 },
1,
FTYPEDESC_SAVE,
NULL,
NULL,
NULL,
pKeyDatamap,
sizeof(KEY_TYPE),
},
{
(fieldtype_t)FIELD_TYPE,
"T",
{ offsetof(typename UTLMAP::Node_t, elem), 0 },
1,
FTYPEDESC_SAVE,
NULL,
NULL,
NULL,
pFieldDatamap,
sizeof(FIELD_TYPE),
}
};
datamap_t dataMap =
{
dataDesc,
2,
"um",
NULL,
false,
false,
0,
#ifdef DEBUG
true
#endif
};
UTLMAP *pUtlMap = ((UTLMAP *)fieldInfo.pField);
pRestore->StartBlock();
int nElems = pRestore->ReadInt();
typename UTLMAP::CTree::ElemType_t temp;
while ( nElems-- )
{
pRestore->ReadAll( &temp, &dataMap );
pUtlMap->Insert( temp.key, temp.elem );
}
pRestore->EndBlock();
}
virtual void MakeEmpty( const SaveRestoreFieldInfo_t &fieldInfo )
{
UTLMAP *pUtlMap = (UTLMAP *)fieldInfo.pField;
pUtlMap->RemoveAll();
}
virtual bool IsEmpty( const SaveRestoreFieldInfo_t &fieldInfo )
{
UTLMAP *pUtlMap = (UTLMAP *)fieldInfo.pField;
return ( pUtlMap->Count() == 0 );
}
};
//-------------------------------------
template <int KEYTYPE, int FIELD_TYPE>
class CUtlMapDataopsInstantiator
{
public:
template <class UTLMAP>
static ISaveRestoreOps *GetDataOps(UTLMAP *)
{
static CUtlMapDataOps<UTLMAP, KEYTYPE, FIELD_TYPE> ops;
return &ops;
}
};
//-------------------------------------
#define SaveUtlMap( pSave, pUtlMap, fieldtype) \
CUtlMapDataopsInstantiator<fieldtype>::GetDataOps( pUtlMap )->Save( pUtlMap, pSave );
#define RestoreUtlMap( pRestore, pUtlMap, fieldtype) \
CUtlMapDataopsInstantiator<fieldtype>::GetDataOps( pUtlMap )->Restore( pUtlMap, pRestore );
//-------------------------------------
#define DEFINE_UTLMAP(name,keyType,fieldtype) \
{ FIELD_CUSTOM, #name, { offsetof(classNameTypedef,name), 0 }, 1, FTYPEDESC_SAVE, NULL, CUtlMapDataopsInstantiator<keyType, fieldtype>::GetDataOps(&(((classNameTypedef *)0)->name)), NULL }
#endif // SAVERESTORE_UTLMAP_H
| 0 | 0.944162 | 1 | 0.944162 | game-dev | MEDIA | 0.346807 | game-dev | 0.968978 | 1 | 0.968978 |
brainsynder-Dev/SimplePets | 2,397 | nms/version-1.19/src/simplepets/brainsynder/nms/entity/SeatEntity.java | package simplepets.brainsynder.nms.entity;
import net.minecraft.tags.TagKey;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.decoration.ArmorStand;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.material.Fluid;
import org.bukkit.event.entity.CreatureSpawnEvent;
import simplepets.brainsynder.nms.VersionTranslator;
public class SeatEntity extends ArmorStand {
public SeatEntity(Level level, double x, double y, double z) {
super(level, x, y, z);
setSilent(true);
setNoGravity(true);
setSmall(true);
// Marker armour stands have a size 0 hitbox, which means the rider
// isn't raised while mounted
setMarker(true);
setInvisible(true);
setInvulnerable(true);
// don't save to disk
persist = false;
}
public static boolean attach(Entity rider, Entity entity) {
var seat = new SeatEntity(entity.level, entity.getX(), entity.getY(), entity.getZ());
if (VersionTranslator.addEntity(entity.level, seat, CreatureSpawnEvent.SpawnReason.CUSTOM)) {
if (seat.startRiding(entity)) {
if (rider.startRiding(seat)) {
return true;
}
seat.stopRiding();
}
seat.discard();
}
return false;
}
@Override
public void tick() {
super.tick();
if (getPassengers().isEmpty()) {
// Trash this entity when player stopped riding
stopRiding();
discard();
} else if (getVehicle() == null) {
// We got dismounted somehow
ejectPassengers();
discard();
}
}
@Override
public void setRot(float f, float f1) {
super.setRot(f, f1);
}
// If a passenger has their eyes in water and this returns false, the
// passenger ejects themselves from the vehicle.
@Override
public boolean rideableUnderWater() {
if (getVehicle() != null) {
// let vehicle decide what should happen
return getVehicle().rideableUnderWater();
}
return false;
}
// Never let seats eject themselves if they are in water, the passenger has
// to decide that.
@Override
public boolean isEyeInFluid(TagKey<Fluid> tagkey) {
return false;
}
}
| 0 | 0.927292 | 1 | 0.927292 | game-dev | MEDIA | 0.996597 | game-dev | 0.973776 | 1 | 0.973776 |
Faboslav/friends-and-foes | 1,248 | fabric/src/main/java/com/faboslav/friendsandfoes/fabric/events/FabricReloadListener.java | package com.faboslav.friendsandfoes.fabric.events;
import net.fabricmc.fabric.api.resource.IdentifiableResourceReloadListener;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.PreparableReloadListener;
import net.minecraft.server.packs.resources.ResourceManager;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
//? <1.21.3 {
/*import net.minecraft.util.profiling.ProfilerFiller;
*///?}
public class FabricReloadListener implements IdentifiableResourceReloadListener
{
private final ResourceLocation id;
private final PreparableReloadListener listener;
public FabricReloadListener(ResourceLocation id, PreparableReloadListener listener) {
this.id = id;
this.listener = listener;
}
@Override
public ResourceLocation getFabricId() {
return id;
}
@Override
public CompletableFuture<Void> reload(
PreparationBarrier barrier,
ResourceManager manager,
//? <1.21.3 {
/*ProfilerFiller prepareProfiler,
ProfilerFiller applyProfiler,
*///?}
Executor backgroundExecutor,
Executor gameExecutor
) {
return listener.reload(barrier, manager, /*? <1.21.3 {*//*prepareProfiler, applyProfiler, *//*?}*/ backgroundExecutor, gameExecutor);
}
} | 0 | 0.807712 | 1 | 0.807712 | game-dev | MEDIA | 0.553712 | game-dev,distributed-systems | 0.956682 | 1 | 0.956682 |
HANON-games/Shiden | 2,285 | Source/ShidenCore/Public/Sample/ShidenSaveSlotInterface.h | // Copyright (c) 2025 HANON. All Rights Reserved.
#pragma once
#include "UObject/Interface.h"
#include "ShidenSaveSlotInterface.generated.h"
/*
* This is an interface used in the sample implementation.
* It is not referenced from the core implementation of Shiden, so it is not necessarily required to use it.
*/
UINTERFACE(MinimalAPI, Blueprintable)
class UShidenSaveSlotInterface : public UInterface
{
GENERATED_BODY()
};
class SHIDENCORE_API IShidenSaveSlotInterface
{
GENERATED_BODY()
public:
/**
* Initializes a save slot widget with save game data and preview information.
* @param SlotName The internal name identifier for this save slot
* @param DisplayName The user-friendly display name for this save slot
* @param SaveMenuWidget The parent save menu widget that contains this slot
* @param bIsSaveMode True if this is a save operation, false if it's a load operation
* @param Thumbnail The screenshot thumbnail image for this save
* @param UpdatedAtText The formatted timestamp when this save was last updated
* @param NameText The character name text at the time of save
* @param TalkText The dialogue text preview at the time of save
*/
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Shiden Visual Novel|Widget",
meta = (AutoCreateRefTerm = "DisplayName,UpdatedAtText,NameText,TalkText"))
void InitSaveSlot(const FString& SlotName, const FText& DisplayName, const UUserWidget* SaveMenuWidget,
const bool bIsSaveMode, const UTexture2D* Thumbnail, const FText& UpdatedAtText,
const FText& NameText, const FText& TalkText);
/**
* Initializes an empty save slot widget when no save data exists.
* @param SlotName The internal name identifier for this save slot
* @param DisplayName The user-friendly display name for this save slot
* @param SaveMenuWidget The parent save menu widget that contains this slot
* @param bIsSaveMode True if this is a save operation, false if it's a load operation
*/
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Shiden Visual Novel|Widget", meta = (AutoCreateRefTerm = "DisplayName"))
void InitNoDataSaveSlot(const FString& SlotName, const FText& DisplayName, const UUserWidget* SaveMenuWidget, const bool bIsSaveMode);
};
| 0 | 0.936066 | 1 | 0.936066 | game-dev | MEDIA | 0.514824 | game-dev | 0.926005 | 1 | 0.926005 |
oculus-samples/Unity-MoveFast | 3,785 | Assets/MoveFast/Runtime/Physics/TriggerZone.cs | // Copyright (c) Meta Platforms, Inc. and affiliates.
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Oculus.Interaction.MoveFast
{
/// <summary>
/// Tracks colliders that enter and exit this trigger zone
/// </summary>
public class TriggerZone : MonoBehaviour
{
private HashSet<Collider> _current = new HashSet<Collider>();
private List<Collider> _previous = new List<Collider>();
public event Action<Collider> WhenAdded;
public event Action<Collider> WhenRemoved;
private void OnTriggerEnter(Collider other) => Add(other);
private void OnTriggerStay(Collider other) => Add(other);
private void FixedUpdate() => Flush();
private void Add(Collider other) => _current.Add(other);
private void Flush()
{
RemoveCollidersThatExited();
AddCollidersThatEntered();
}
private void RemoveCollidersThatExited()
{
for (int i = _previous.Count - 1; i >= 0; i--)
{
var collider = _previous[i];
if (!_current.Contains(collider))
{
_previous.RemoveAt(i);
WhenRemoved?.Invoke(collider);
}
}
}
private void AddCollidersThatEntered()
{
_previous.ForEach(x => _current.Remove(x));
if (_current.Count == 0) return;
foreach (var collider in _current)
{
if (collider == null) continue;
_previous.Add(collider);
WhenAdded?.Invoke(collider);
}
_current.Clear();
}
}
public class TriggerZoneList<T> : IDisposable
{
private readonly TriggerZone _zone;
private readonly Dictionary<T, int> _inZone = new Dictionary<T, int>();
public int Count => _inZone.Count;
public event Action WhenChanged;
public event Action<T> WhenAdded;
public event Action<T> WhenRemoved;
public TriggerZoneList(TriggerZone zone)
{
_zone = zone;
_zone.WhenAdded += Add;
_zone.WhenRemoved += Remove;
}
public void Dispose()
{
_zone.WhenAdded -= Add;
_zone.WhenRemoved -= Remove;
}
protected void Add(Collider body)
{
var comp = body.GetComponentInParent<T>();
if (comp == null) return;
_inZone.TryGetValue(comp, out int v);
_inZone[comp] = v + 1;
if (v == 0)
{
WhenAdded?.Invoke(comp);
}
WhenChanged?.Invoke();
}
protected void Remove(Collider body)
{
if (HandleDestroyed(body))
{
WhenChanged?.Invoke();
return;
}
var comp = body.GetComponentInParent<T>();
if (comp == null) return;
if (!_inZone.TryGetValue(comp, out int v)) return;
_inZone[comp] = v - 1;
if (v == 1)
{
_inZone.Remove(comp);
WhenRemoved?.Invoke(comp);
WhenChanged?.Invoke();
}
}
private bool HandleDestroyed(Collider body)
{
if (body == null)
{
var keys = new List<T>(_inZone.Keys);
for (int i = 0; i < keys.Count; i++)
{
if (keys[i] == null)
{
_inZone.Remove(keys[i]);
}
}
return true;
}
return false;
}
}
}
| 0 | 0.789373 | 1 | 0.789373 | game-dev | MEDIA | 0.65949 | game-dev,testing-qa | 0.906139 | 1 | 0.906139 |
ProjectIgnis/CardScripts | 1,189 | official/c3149764.lua | --ツタン仮面
--Tutan Mask
local s,id=GetID()
function s.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_CHAINING)
e1:SetCondition(s.condition)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
end
function s.cfilter(c)
return c:IsLocation(LOCATION_MZONE) and c:IsFaceup() and c:IsRace(RACE_ZOMBIE)
end
function s.condition(e,tp,eg,ep,ev,re,r,rp)
if not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return end
if not re:IsHasType(EFFECT_TYPE_ACTIVATE) then return false end
local tg=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
return tg and #tg==1 and s.cfilter(tg:GetFirst()) and Duel.IsChainNegatable(ev)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0)
if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.NegateActivation(ev) and re:GetHandler():IsRelateToEffect(re) then
Duel.Destroy(eg,REASON_EFFECT)
end
end | 0 | 0.894721 | 1 | 0.894721 | game-dev | MEDIA | 0.960821 | game-dev | 0.922949 | 1 | 0.922949 |
11011010/BFA-Frankenstein-Core | 3,694 | src/server/scripts/EasternKingdoms/Karazhan/karazhan.h | /*
* Copyright (C) 2020 BfaCore
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DEF_KARAZHAN_H
#define DEF_KARAZHAN_H
#include "CreatureAIImpl.h"
#define KZScriptName "instance_karazhan"
#define DataHeader "KZ"
uint32 const EncounterCount = 12;
enum KZDataTypes
{
DATA_ATTUMEN = 0,
DATA_MOROES = 1,
DATA_MAIDEN_OF_VIRTUE = 2,
DATA_OPTIONAL_BOSS = 3,
DATA_OPERA_PERFORMANCE = 4,
DATA_CURATOR = 5,
DATA_ARAN = 6,
DATA_TERESTIAN = 7,
DATA_NETHERSPITE = 8,
DATA_CHESS = 9,
DATA_MALCHEZZAR = 10,
DATA_NIGHTBANE = 11,
DATA_OPERA_OZ_DEATHCOUNT = 14,
DATA_KILREK = 15,
DATA_GO_CURTAINS = 18,
DATA_GO_STAGEDOORLEFT = 19,
DATA_GO_STAGEDOORRIGHT = 20,
DATA_GO_LIBRARY_DOOR = 21,
DATA_GO_MASSIVE_DOOR = 22,
DATA_GO_NETHER_DOOR = 23,
DATA_GO_GAME_DOOR = 24,
DATA_GO_GAME_EXIT_DOOR = 25,
DATA_IMAGE_OF_MEDIVH = 26,
DATA_MASTERS_TERRACE_DOOR_1 = 27,
DATA_MASTERS_TERRACE_DOOR_2 = 28,
DATA_GO_SIDE_ENTRANCE_DOOR = 29
};
enum KZOperaEvents
{
EVENT_OZ = 1,
EVENT_HOOD = 2,
EVENT_RAJ = 3
};
enum KZMiscCreatures
{
NPC_HYAKISS_THE_LURKER = 16179,
NPC_ROKAD_THE_RAVAGER = 16181,
NPC_SHADIKITH_THE_GLIDER = 16180,
NPC_TERESTIAN_ILLHOOF = 15688,
NPC_MOROES = 15687,
NPC_ATTUMEN_UNMOUNTED = 15550,
NPC_ATTUMEN_MOUNTED = 16152,
NPC_MIDNIGHT = 16151,
// Trash
NPC_COLDMIST_WIDOW = 16171,
NPC_COLDMIST_STALKER = 16170,
NPC_SHADOWBAT = 16173,
NPC_VAMPIRIC_SHADOWBAT = 16175,
NPC_GREATER_SHADOWBAT = 16174,
NPC_PHASE_HOUND = 16178,
NPC_DREADBEAST = 16177,
NPC_SHADOWBEAST = 16176,
NPC_KILREK = 17229
};
enum KZGameObjectIds
{
GO_STAGE_CURTAIN = 183932,
GO_STAGE_DOOR_LEFT = 184278,
GO_STAGE_DOOR_RIGHT = 184279,
GO_PRIVATE_LIBRARY_DOOR = 184517,
GO_MASSIVE_DOOR = 185521,
GO_GAMESMAN_HALL_DOOR = 184276,
GO_GAMESMAN_HALL_EXIT_DOOR = 184277,
GO_NETHERSPACE_DOOR = 185134,
GO_MASTERS_TERRACE_DOOR = 184274,
GO_MASTERS_TERRACE_DOOR2 = 184280,
GO_SIDE_ENTRANCE_DOOR = 184275,
GO_DUST_COVERED_CHEST = 185119
};
enum KZMisc
{
OPTIONAL_BOSS_REQUIRED_DEATH_COUNT = 50
};
template<typename AI>
inline AI* GetKarazhanAI(Creature* creature)
{
return GetInstanceAI<AI>(creature, KZScriptName);
}
#endif
| 0 | 0.787507 | 1 | 0.787507 | game-dev | MEDIA | 0.965813 | game-dev | 0.883193 | 1 | 0.883193 |
Dawn-of-Light/DOLSharp | 1,286 | GameServer/keeps/Gameobjects/Guards/Stealther.cs | using DOL.GS.ServerProperties;
using DOL.Language;
namespace DOL.GS.Keeps
{
public class GuardStealther : GameKeepGuard
{
public GuardStealther() : base()
{
Flags = eFlags.STEALTH;
}
protected override CharacterClass GetClass()
{
if (ModelRealm == eRealm.Albion) return CharacterClass.Infiltrator;
else if (ModelRealm == eRealm.Midgard) return CharacterClass.Shadowblade;
else if (ModelRealm == eRealm.Hibernia) return CharacterClass.Nightshade;
return CharacterClass.None;
}
protected override void SetBlockEvadeParryChance()
{
base.SetBlockEvadeParryChance();
EvadeChance = 30;
}
protected override void SetName()
{
switch (ModelRealm)
{
case eRealm.None:
case eRealm.Albion:
Name = LanguageMgr.GetTranslation(Properties.SERV_LANGUAGE, "SetGuardName.Infiltrator");
break;
case eRealm.Midgard:
Name = LanguageMgr.GetTranslation(Properties.SERV_LANGUAGE, "SetGuardName.Shadowblade");
break;
case eRealm.Hibernia:
Name = LanguageMgr.GetTranslation(Properties.SERV_LANGUAGE, "SetGuardName.Nightshade");
break;
}
if (Realm == eRealm.None)
{
Name = LanguageMgr.GetTranslation(Properties.SERV_LANGUAGE, "SetGuardName.Renegade", Name);
}
}
}
}
| 0 | 0.768107 | 1 | 0.768107 | game-dev | MEDIA | 0.558987 | game-dev | 0.961579 | 1 | 0.961579 |
blurite/rsprot | 5,910 | protocol/osrs-228/osrs-228-model/src/main/kotlin/net/rsprot/protocol/game/outgoing/misc/client/HintArrow.kt | package net.rsprot.protocol.game.outgoing.misc.client
import net.rsprot.protocol.ServerProtCategory
import net.rsprot.protocol.game.outgoing.GameServerProtCategory
import net.rsprot.protocol.message.OutgoingGameMessage
/**
* Hint arrow packets are used to render a hint arrow
* at a specific player, NPC or a tile.
* Only a single hint arrow can exist at a time in OldSchool.
* @property type the hint arrow type to render.
*/
public class HintArrow(
public val type: HintArrowType,
) : OutgoingGameMessage {
override val category: ServerProtCategory
get() = GameServerProtCategory.LOW_PRIORITY_PROT
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as HintArrow
return type == other.type
}
override fun hashCode(): Int = type.hashCode()
override fun toString(): String = "HintArrow(type=$type)"
public sealed interface HintArrowType
/**
* Reset hint arrow message is used to clear out any
* existing hint arrows.
*/
public data object ResetHintArrow : HintArrowType
/**
* NPC hint arrows are used to render a hint arrow
* on-top of a specific NPC.
* @property index the index of the NPC who is receiving
* the hint arrow. Note that this is the real index without
* any offsets or additions.
*/
public class NpcHintArrow(
public val index: Int,
) : HintArrowType {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as NpcHintArrow
return index == other.index
}
override fun hashCode(): Int = index
override fun toString(): String = "NpcHintArrow(index=$index)"
}
/**
* Player hint arrows are used to render a hint arrow
* on-top of a specific player.
* @property index the index of the player who is receiving
* the hint arrow. Note that this is the real index without
* any offsets or additions.
*/
public class PlayerHintArrow(
public val index: Int,
) : HintArrowType {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as PlayerHintArrow
return index == other.index
}
override fun hashCode(): Int = index
override fun toString(): String = "PlayerHintArrow(index=$index)"
}
/**
* Tile hint arrows are used to render a hint arrow at
* a specific coordinate.
* @property x the absolute x coordinate of the hint arrow.
* @property z the absolute z coordinate of the hint arrow.
* @property height the height of the hint arrow,
* with the expected range being 0 to 255 (inclusive).
* @property position the position of the hint arrow within
* the target tile.
*/
public class TileHintArrow private constructor(
private val _x: UShort,
private val _z: UShort,
private val _height: UByte,
private val _position: UByte,
) : HintArrowType {
public constructor(
x: Int,
z: Int,
height: Int,
tilePosition: HintArrowTilePosition,
) : this(
x.toUShort(),
z.toUShort(),
height.toUByte(),
tilePosition.id.toUByte(),
)
public constructor(
x: Int,
z: Int,
height: Int,
tilePosition: Int,
) : this(
x.toUShort(),
z.toUShort(),
height.toUByte(),
tilePosition.toUByte(),
)
public val x: Int
get() = _x.toInt()
public val z: Int
get() = _z.toInt()
public val height: Int
get() = _height.toInt()
public val position: HintArrowTilePosition
get() = HintArrowTilePosition[_position.toInt()]
public val positionId: Int
get() = _position.toInt()
/**
* Hint arrow tile positions define where within a tile
* the given hint arrow will render. All the options here
* are centered on the tile, e.g. [WEST] will be at the
* western section of the tile, whilst being centered
* on the z-axis.
*
* @property id the id of the hint arrow position,
* as expected by the client.
*/
public enum class HintArrowTilePosition(
public val id: Int,
) {
CENTER(2),
WEST(3),
EAST(4),
SOUTH(5),
NORTH(6),
;
internal companion object {
operator fun get(id: Int): HintArrowTilePosition = entries.first { it.id == id }
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as TileHintArrow
if (_x != other._x) return false
if (_z != other._z) return false
if (_height != other._height) return false
if (_position != other._position) return false
return true
}
override fun hashCode(): Int {
var result = _x.hashCode()
result = 31 * result + _z.hashCode()
result = 31 * result + _height.hashCode()
result = 31 * result + _position.hashCode()
return result
}
override fun toString(): String =
"TileHintArrow(" +
"x=$x, " +
"z=$z, " +
"height=$height, " +
"position=$position" +
")"
}
}
| 0 | 0.832758 | 1 | 0.832758 | game-dev | MEDIA | 0.626507 | game-dev | 0.906755 | 1 | 0.906755 |
andywiecko/BurstCollections | 18,939 | Runtime/NativeBoundingVolumeTree/NativeBoundingVolumeTree.cs | using System;
using System.Diagnostics;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
namespace andywiecko.BurstCollections
{
[Obsolete("Use " + nameof(NativeBoundingVolumeTree<AABB>) + " instead!")]
public struct BoundingVolumeTree<T> : INativeDisposable where T : unmanaged, IBoundingVolume<T>
{
private const int None = -1;
#region BFS
public struct BFSEnumerator
{
private NativeBoundingVolumeTree<T> owner;
public (int, T) Current { get; private set; }
public BFSEnumerator(NativeBoundingVolumeTree<T> owner)
{
this.owner = owner;
NativeBoundingVolumeTree<T>.CheckIfTreeIsConstructed(owner.RootId.Value);
var root = owner.RootId.Value;
Current = (root, owner.Volumes[root]);
owner.tmpNodesQueue.Clear();
owner.tmpNodesQueue.Enqueue(root);
}
public bool IsLeaf(int id) => owner.Nodes[id].IsLeaf;
public void Traverse(int id)
{
var n = owner.Nodes[id];
if (!n.IsLeaf)
{
owner.tmpNodesQueue.Enqueue(n.LeftChildId);
owner.tmpNodesQueue.Enqueue(n.RightChildId);
}
}
public bool MoveNext()
{
var isEmpty = owner.tmpNodesQueue.IsEmpty();
if (isEmpty)
{
return false;
}
else
{
var id = owner.tmpNodesQueue.Dequeue();
Current = (id, owner.Volumes[id]);
return true;
}
}
public BFSEnumerator GetEnumerator() => this;
}
#endregion
#region Node
public readonly struct Node
{
public bool IsRoot => ParentId == None;
public bool IsLeaf => !LeftChildIsValid && !RightChildIsValid;
public bool ParentIsValid => ParentId != None;
public bool LeftChildIsValid => LeftChildId != None;
public bool RightChildIsValid => RightChildId != None;
public readonly int ParentId;
public readonly int LeftChildId;
public readonly int RightChildId;
public Node(int parentId, int leftChild, int rightChild)
{
ParentId = parentId;
LeftChildId = leftChild;
RightChildId = rightChild;
}
public static implicit operator Node((int parent, int left, int right) n) => new Node(n.parent, n.left, n.right);
public Node WithParent(int parentId) => new Node(parentId, LeftChildId, RightChildId);
public Node WithLeftChild(int childId) => new Node(ParentId, childId, RightChildId);
public Node WithRightChild(int childId) => new Node(ParentId, LeftChildId, childId);
public void Deconstruct(out int parentId, out int leftChildId, out int rightChildId) => _ =
(parentId = ParentId, leftChildId = LeftChildId, rightChildId = RightChildId);
}
#endregion
public BFSEnumerator BreadthFirstSearch => new BFSEnumerator(tree);
public bool IsCreated => tree.IsCreated;
public bool IsEmpty => tree.IsEmpty;
public int LeavesCount => tree.LeavesCount;
public NativeArray<Node> Nodes => tree.Nodes.Reinterpret<Node>();
public NativeArray<T> Volumes => tree.Volumes;
public NativeReference<int> RootId => tree.RootId;
internal NativeBoundingVolumeTree<T> tree;
public BoundingVolumeTree(int leavesCount, Allocator allocator) => tree = new NativeBoundingVolumeTree<T>(leavesCount, allocator);
public JobHandle Dispose(JobHandle dependencies) => tree.Dispose(dependencies);
public void Dispose() => tree.Dispose();
public void Clear() => tree.Clear();
public void Construct(NativeArray<T>.ReadOnly volumes) => tree.Construct(volumes);
public JobHandle Construct(NativeArray<T>.ReadOnly volumes, JobHandle dependencies) => tree.Construct(volumes, dependencies);
public void UpdateLeavesVolumes(NativeArray<T>.ReadOnly volumes) => tree.UpdateLeavesVolumes(volumes);
public JobHandle UpdateLeafesVolumes(NativeArray<T>.ReadOnly volumes, JobHandle dependencies) => tree.UpdateLeavesVolumes(volumes, dependencies);
}
/// <summary>
/// Burst friendly implementation of the native bounding volume tree.
/// </summary>
public struct NativeBoundingVolumeTree<T> : INativeDisposable where T : unmanaged, IBoundingVolume<T>
{
private const int None = -1;
public bool IsCreated => Nodes.IsCreated;
public bool IsEmpty => RootId.Value == None;
public int LeavesCount { get; }
#region BFS
/// <summary>
/// See wikipage about <see href="https://en.wikipedia.org/wiki/Breadth-first_search">Breadth-first search (BFS)</see>.
/// </summary>
public struct BFSEnumerator
{
public (int, T) Current { get; private set; }
private NativeArray<Node>.ReadOnly nodes;
private NativeArray<T>.ReadOnly volumes;
private NativeReference<int>.ReadOnly rootId;
private NativeQueue<int> queue;
public BFSEnumerator(ReadOnly owner, NativeQueue<int> queue)
{
this.nodes = owner.Nodes;
this.volumes = owner.Volumes;
this.rootId = owner.RootId;
this.queue = queue;
CheckIfTreeIsConstructed(rootId.Value);
var root = rootId.Value;
Current = (root, volumes[root]);
queue.Clear();
queue.Enqueue(root);
}
public bool IsLeaf(int id) => nodes[id].IsLeaf;
public void Traverse(int id)
{
var n = nodes[id];
if (!n.IsLeaf)
{
queue.Enqueue(n.LeftChildId);
queue.Enqueue(n.RightChildId);
}
}
public bool MoveNext()
{
var isEmpty = queue.IsEmpty();
if (isEmpty)
{
return false;
}
else
{
var id = queue.Dequeue();
Current = (id, volumes[id]);
return true;
}
}
public BFSEnumerator GetEnumerator() => this;
}
#endregion
#region Node
public readonly struct Node
{
public bool IsRoot => ParentId == None;
public bool IsLeaf => !LeftChildIsValid && !RightChildIsValid;
public bool ParentIsValid => ParentId != None;
public bool LeftChildIsValid => LeftChildId != None;
public bool RightChildIsValid => RightChildId != None;
public readonly int ParentId;
public readonly int LeftChildId;
public readonly int RightChildId;
public Node(int parentId, int leftChild, int rightChild)
{
ParentId = parentId;
LeftChildId = leftChild;
RightChildId = rightChild;
}
public static implicit operator Node((int parent, int left, int right) n) => new Node(n.parent, n.left, n.right);
public Node WithParent(int parentId) => new Node(parentId, LeftChildId, RightChildId);
public Node WithLeftChild(int childId) => new Node(ParentId, childId, RightChildId);
public Node WithRightChild(int childId) => new Node(ParentId, LeftChildId, childId);
public void Deconstruct(out int parentId, out int leftChildId, out int rightChildId) => _ =
(parentId = ParentId, leftChildId = LeftChildId, rightChildId = RightChildId);
}
#endregion
#region Jobs
[BurstCompile]
private struct ConstructJob : IJob
{
private NativeBoundingVolumeTree<T> tree;
private NativeArray<T>.ReadOnly volumes;
public ConstructJob(NativeBoundingVolumeTree<T> tree, NativeArray<T>.ReadOnly volumes)
{
this.tree = tree;
this.volumes = volumes;
}
public void Execute() => tree.Construct(volumes);
}
[BurstCompile]
private struct UpdateLeafesVolumesJob : IJob
{
private NativeBoundingVolumeTree<T> tree;
private NativeArray<T>.ReadOnly volumes;
public UpdateLeafesVolumesJob(NativeBoundingVolumeTree<T> tree, NativeArray<T>.ReadOnly volumes)
{
this.tree = tree;
this.volumes = volumes;
}
public void Execute() => tree.UpdateLeavesVolumes(volumes);
}
#endregion
#region ReadOnly
public struct ReadOnly
{
public bool IsEmpty => RootId.Value == None;
public int LeavesCount { get; }
public NativeArray<Node>.ReadOnly Nodes;
public NativeArray<T>.ReadOnly Volumes;
public NativeReference<int>.ReadOnly RootId;
internal ReadOnly(NativeBoundingVolumeTree<T> owner)
{
Nodes = owner.Nodes.AsReadOnly();
Volumes = owner.Volumes.AsReadOnly();
RootId = owner.RootId.AsReadOnly();
LeavesCount = owner.LeavesCount;
}
public BFSEnumerator BreadthFirstSearch(NativeQueue<int> queue) => new BFSEnumerator(this, queue);
}
#endregion
public NativeArray<Node> Nodes;
public NativeArray<T> Volumes;
public NativeReference<int> RootId;
internal NativeReference<int> currentInternalCount;
internal NativeQueue<int> tmpNodesQueue;
internal NativeStack<int> tmpNodesStack;
public NativeBoundingVolumeTree(int leavesCount, Allocator allocator)
{
LeavesCount = leavesCount;
var length = 2 * leavesCount - 1;
Nodes = new NativeArray<Node>(length, allocator);
Volumes = new NativeArray<T>(length, allocator);
RootId = new NativeReference<int>(-1, allocator);
currentInternalCount = new NativeReference<int>(0, allocator);
tmpNodesQueue = new NativeQueue<int>(allocator);
tmpNodesStack = new NativeStack<int>(leavesCount - 1, allocator);
}
public JobHandle Dispose(JobHandle dependencies)
{
dependencies = Nodes.Dispose(dependencies);
dependencies = Volumes.Dispose(dependencies);
dependencies = RootId.Dispose(dependencies);
dependencies = currentInternalCount.Dispose(dependencies);
dependencies = tmpNodesQueue.Dispose(dependencies);
dependencies = tmpNodesStack.Dispose(dependencies);
return dependencies;
}
public void Dispose()
{
Nodes.Dispose();
Volumes.Dispose();
RootId.Dispose();
currentInternalCount.Dispose();
tmpNodesQueue.Dispose();
tmpNodesStack.Dispose();
}
public BFSEnumerator BreadthFirstSearch() => new BFSEnumerator(AsReadOnly(), tmpNodesQueue);
public ReadOnly AsReadOnly() => new ReadOnly(this);
public void Clear() => RootId.Value = None;
/// <summary>
/// Incremental construction of the tree with the given <paramref name="volumes"/>.
/// </summary>
public void Construct(NativeArray<T>.ReadOnly volumes)
{
CheckLengths(volumes, LeavesCount);
Clear();
if (volumes.Length == 0)
{
return;
}
Nodes[0] = (parent: None, left: None, right: None);
RootId.Value = 0;
Volumes[0] = volumes[0];
for (int objectId = 1; objectId < volumes.Length; objectId++)
{
var volume = volumes[objectId];
var bestNodeId = FindBestNode(volume);
InsertNode(objectId, volume, bestNodeId);
}
}
/// <summary>
/// Incremental (jobified) construction of the tree with the given <paramref name="volumes"/>.
/// </summary>
public JobHandle Construct(NativeArray<T>.ReadOnly volumes, JobHandle dependencies) =>
new ConstructJob(this, volumes).Schedule(dependencies);
/// <summary>
/// Update leaves <paramref name="volumes"/> and all internal tree nodes.
/// </summary>
public void UpdateLeavesVolumes(NativeArray<T>.ReadOnly volumes)
{
CheckIfTreeIsConstructed(RootId.Value);
CheckLengths(volumes, LeavesCount);
for (int i = 0; i < volumes.Length; i++)
{
Volumes[i] = volumes[i];
}
RecalculateVolumes();
}
/// <summary>
/// Update leaves <paramref name="volumes"/> and all internal tree nodes (jobified).
/// </summary>
public JobHandle UpdateLeavesVolumes(NativeArray<T>.ReadOnly volumes, JobHandle dependencies) =>
new UpdateLeafesVolumesJob(this, volumes).Schedule(dependencies);
private void RecalculateVolumes()
{
var bfs = BreadthFirstSearch();
foreach (var (id, _) in bfs)
{
if (!bfs.IsLeaf(id))
{
tmpNodesStack.Push(id);
}
bfs.Traverse(id);
}
while (tmpNodesStack.TryPop(out var id))
{
var (_, leftChild, rightChild) = Nodes[id];
Volumes[id] = Volumes[leftChild].Union(Volumes[rightChild]);
}
}
private void InsertNode(int objectId, T volume, int targetId)
{
var target = Nodes[targetId];
var targetParentId = target.ParentId;
var targetVolume = Volumes[targetId];
// Add internal node
var tmpId = LeavesCount + currentInternalCount.Value;
var tmp = new Node(parentId: targetParentId, leftChild: targetId, rightChild: objectId);
Nodes[tmpId] = tmp;
Volumes[tmpId] = volume.Union(targetVolume);
currentInternalCount.Value++;
// Update target
Nodes[targetId] = target.WithParent(tmpId);
// Change root if necessary
if (targetParentId == None)
{
RootId.Value = tmpId;
}
else
{
var parent = Nodes[targetParentId];
parent = parent.LeftChildId == targetId ? parent.WithLeftChild(tmpId) : parent.WithRightChild(tmpId);
Nodes[targetParentId] = parent;
var left = parent.LeftChildId;
var right = parent.RightChildId;
Volumes[targetParentId] = Volumes[left].Union(Volumes[right]);
while (parent.ParentIsValid)
{
var parentId = parent.ParentId;
parent = Nodes[parentId];
Volumes[parentId] = Volumes[parent.LeftChildId].Union(Volumes[parent.RightChildId]);
}
}
// Add leaf
Nodes[objectId] = new Node(parentId: tmpId, None, None);
Volumes[objectId] = volume;
}
private int FindBestNode(T volume)
{
var bestSibling = None;
var bestCost = float.MaxValue;
tmpNodesQueue.Enqueue(RootId.Value);
while (tmpNodesQueue.TryDequeue(out var otherId))
{
var directCost = GetDirectCost(volume, otherId);
if (directCost >= bestCost)
{
continue;
}
var inheritedCost = GetInheritedCost(volume, otherId);
var cost = directCost + inheritedCost;
if (cost < bestCost)
{
bestCost = cost;
bestSibling = otherId;
var lowerBoundCost = GetLowerBoundCost(volume, otherId);
if (lowerBoundCost < bestCost)
{
EnqueueChildren(otherId);
}
}
}
return bestSibling;
}
private void EnqueueChildren(int nodeId)
{
var node = Nodes[nodeId];
if (!node.IsLeaf)
{
tmpNodesQueue.Enqueue(node.LeftChildId);
tmpNodesQueue.Enqueue(node.RightChildId);
}
}
private float GetDirectCost(T volume, int otherId)
{
var otherVolume = Volumes[otherId];
return volume.Union(otherVolume).Volume;
}
private float GetLowerBoundCost(T volume, int otherId)
{
var otherVolume = Volumes[otherId];
return volume.Volume + volume.Union(otherVolume).Volume - otherVolume.Volume + GetInheritedCost(volume, otherId);
}
private float GetInheritedCost(T volume, int otherId)
{
var cost = 0f;
var other = Nodes[otherId];
while (!other.IsRoot)
{
var parentId = other.ParentId;
var parent = Nodes[parentId];
var parentVolume = Volumes[parentId];
cost += parentVolume.Union(volume).Volume - parentVolume.Volume;
other = parent;
}
return cost;
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
private static void CheckLengths(NativeArray<T>.ReadOnly volumes, int leavesCount)
{
if (volumes.Length != leavesCount)
{
throw new InvalidOperationException
(
$"Tree leaves count ({leavesCount}) does not match " +
$"the provided volumes list length ({volumes.Length})"
);
}
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
internal static void CheckIfTreeIsConstructed(int rootId)
{
if (rootId == None)
{
throw new Exception
(
$"{nameof(NativeBoundingVolumeTree<T>)} has not been constructed! " +
$"One should construct tree before using it."
);
}
}
}
} | 0 | 0.971556 | 1 | 0.971556 | game-dev | MEDIA | 0.588309 | game-dev | 0.986642 | 1 | 0.986642 |
flyyufelix/donkey_rl | 8,549 | donkey_rl/sdsim/Assets/Scripts/Localizer.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class Measurement
{
public int id;
public int offsetX;
public int offsetZ;
public Measurement(int _id, int offX, int offZ)
{
id = _id;
offsetX = offX;
offsetZ = offZ;
}
}
[System.Serializable]
public class Measurements
{
public List<Measurement> m;
public void Init(int count)
{
m = new List<Measurement>(count);
}
}
[System.Serializable]
public class ProbMap
{
public float[,] cells;
public int numX;
public int numZ;
public void Init(int numXCells, int numZCells)
{
numX = numXCells;
numZ = numZCells;
cells = new float[numXCells, numZCells];
}
public void AllEqualProb()
{
int totalCells = numX * numZ;
//At first we are equally likely to be in any cell.
//And since we like the probability to add to 1, we
///divide by total cells.
float iniProb = 1.0f / totalCells;
for(int iX = 0; iX < numX; iX++)
{
for(int iZ = 0; iZ < numZ; iZ++)
{
cells[iX, iZ] = iniProb;
}
}
}
public void Zero()
{
for(int iX = 0; iX < numX; iX++)
{
for(int iZ = 0; iZ < numZ; iZ++)
{
cells[iX, iZ] = 0.0f;
}
}
}
}
public class ProbMapVisualizer
{
public List<GameObject> cellMarkers;
public List<Vector2> topCells;
public void Init(int numToVisualize, GameObject prefab)
{
cellMarkers = new List<GameObject>(numToVisualize);
topCells = new List<Vector2>(numToVisualize);
for(int i = 0; i < numToVisualize; i++)
{
GameObject go = GameObject.Instantiate(prefab) as GameObject;
cellMarkers.Add(go);
}
}
public void Visualize(ProbMap pm, Map world)
{
topCells.Clear();
int numX = pm.numX;
int numZ = pm.numZ;
float thresh = 0.05f;
int iCM = 0;
for(int iX = 0; iX < numX; iX++)
{
for(int iZ = 0; iZ < numZ; iZ++)
{
float p = pm.cells[iX, iZ];
if(p > thresh)
{
Vector3 pos = Vector3.zero;
pos = world.startPos;
pos.x += world.dX * iX;
pos.z += world.dZ * iZ;
cellMarkers[iCM].transform.position = pos;
Vector3 s = Vector3.one;
s.y = p * 100f;
s.x = world.dX;
s.z = world.dZ;
cellMarkers[iCM].transform.localScale = s;
iCM++;
if(iCM == cellMarkers.Count)
break;
}
}
}
for(int iM = iCM; iM < cellMarkers.Count; iM++)
{
cellMarkers[iM].transform.position = Vector3.zero;
cellMarkers[iM].transform.localScale = Vector3.zero;
}
}
}
public class MonteCarloLocalizer
{
public Map world;
public ProbMap probMap;
//for memory efficiency, we will allocate
//two maps and swap between them.
bool useMapA;
ProbMap mapA;
ProbMap mapB;
public void Init(Map worldMap)
{
world = worldMap;
mapA = new ProbMap();
mapA.Init(world.numX, world.numZ);
mapA.AllEqualProb();
useMapA = true;
probMap = mapA;
mapB = new ProbMap();
mapB.Init(world.numX, world.numZ);
}
public void Move(int iMoveX, int iMoveZ, float probExact)
{
if(iMoveX == 0 && iMoveZ == 0)
return;
ProbMap newMap = useMapA ? mapB : mapA;
newMap.Zero();
int numX = probMap.numX;
int numZ = probMap.numZ;
for(int iX = 0; iX < numX; iX++)
{
for(int iZ = 0; iZ < numZ; iZ++)
{
int iTargetX = iX + iMoveX;
int iTargetZ = iZ + iMoveZ;
if(iTargetX < 0 || iTargetX >= numX)
continue;
if(iTargetZ < 0 || iTargetZ >= numZ)
continue;
//int trailX = iMoveX > 0 ? - 1 : (iMoveX == 0 ? 0 : 1);
//int trailZ = iMoveZ > 0 ? - 1 : (iMoveZ == 0 ? 0 : 1);
//most of old value moves to new
float probTarget = probMap.cells[iX, iZ] * probExact;
//some probablity that we are still in old cell.
//float probTrail = probMap.cells[iX, iZ] * (1.0f - probExact);
newMap.cells[iTargetX, iTargetZ] += probTarget;
//newMap.cells[iTargetX + trailX, iTargetZ + trailZ] += probTrail;
}
}
probMap = newMap;
useMapA = !useMapA;
}
public void Sense(Measurements m, float probExact)
{
for(int iM = 0; iM < m.m.Count; iM++)
{
Measurement _m = m.m[iM];
Sense(_m, probExact);
}
}
public void Sense(Measurement m, float probHit)
{
int numX = probMap.numX;
int numZ = probMap.numZ;
float probMiss = 1.0f - probHit;
float t = 0f;
for(int iX = 0; iX < numX; iX++)
{
for(int iZ = 0; iZ < numZ; iZ++)
{
float hit = 0f;
int iSenseX = iX + m.offsetX;
int iSenseZ = iZ + m.offsetZ;
if(iSenseZ >= 0 && iSenseZ < numZ &&
iSenseX >= 0 && iSenseX < numX)
{
hit = (m.id == world.cells[iSenseX, iSenseZ]) ? 1.0f : 0.0f;
}
float p = probMap.cells[iX, iZ];
float np = p * (hit * probHit + (1.0f - hit) * probMiss);
probMap.cells[iX, iZ] = np;
t += np;
}
}
//Normalize.
for(int iX = 0; iX < numX; iX++)
{
for(int iZ = 0; iZ < numZ; iZ++)
{
probMap.cells[iX, iZ] = probMap.cells[iX, iZ] / t;
}
}
}
public void MostLikelyCell(out int cellX, out int cellZ)
{
float p = 0f;
int numX = probMap.numX;
int numZ = probMap.numZ;
cellX = 0;
cellZ = 0;
for(int iX = 0; iX < numX; iX++)
{
for(int iZ = 0; iZ < numZ; iZ++)
{
float pc = probMap.cells[iX, iZ];
if(pc > p)
{
p = pc;
cellX = iX;
cellZ = iZ;
}
}
}
}
public void MostLikelyPos(out Vector3 pos)
{
int iX = 0;
int iZ = 0;
MostLikelyCell(out iX, out iZ);
pos = world.startPos;
pos.x += world.dX * iX;
pos.z += world.dZ * iZ;
}
}
public class LocUnitTester
{
public void Test(Map map, Measurements measurements, List<Vector2> moves,
int iExpectedX, int iExpectedZ)
{
MonteCarloLocalizer loc = new MonteCarloLocalizer();
loc.Init(map);
int iX = (int)moves[0].x;
int iY = (int)moves[0].y;
loc.Move(iX, iY, 1f);
loc.Sense(measurements, 1f);
int mlX, mlZ;
loc.MostLikelyCell(out mlX, out mlZ);
if(iExpectedX == mlX && iExpectedZ == mlZ)
{
Debug.Log("Correct!");
}
else
{
Debug.LogError("Oops");
}
}
public void TestA()
{
Map map = new Map();
map.Init(3, 3);
map.cells [1,1] = 1; //all the rest are zero.
Measurement m = new Measurement(1, 0, 0);
Measurements ma = new Measurements();
ma.Init(1);
ma.m.Add(m);
List<Vector2> moves = new List<Vector2>();
moves.Add(Vector2.zero);
Test (map, ma, moves, 1, 1);
}
public void TestB()
{
Map map = new Map();
map.Init(3, 3);
map.cells [1,1] = 1; //all the rest are zero.
Measurement m = new Measurement(1, 0, -1);
Measurements ma = new Measurements();
ma.Init(1);
ma.m.Add(m);
List<Vector2> moves = new List<Vector2>();
moves.Add(Vector2.zero);
Test (map, ma, moves, 1, 2);
}
}
public class Localizer : MonoBehaviour
{
MonteCarloLocalizer loc;
ProbMapVisualizer vis;
public MapManager mm;
int iPrevX = 0;
int iPrevZ = 0;
Vector3 prevPos;
public float radiusSense = 100f;
public float threshMove = 0.1f;
public float probMoveExact = 0.8f;
public float probSenseExact = 0.8f;
public Transform likelyTM;
// Use this for initialization
void Start ()
{
LocUnitTester tester = new LocUnitTester();
tester.TestB();
loc = new MonteCarloLocalizer();
loc.Init(mm.map);
vis = new ProbMapVisualizer();
vis.Init(25, likelyTM.gameObject );
//when we move at least full a cell dist, then sense again.
threshMove = mm.map.dX;
prevPos = Vector3.zero;
}
// Update is called once per frame
void Update ()
{
Vector3 newPos = transform.position;
int inewX = Mathf.RoundToInt(newPos.x / mm.map.dX);
int inewZ = Mathf.RoundToInt(newPos.z / mm.map.dZ);
if(inewX != iPrevX || inewZ != iPrevZ)
{
int iMoveX = inewX - iPrevX;
int iMoveZ = inewZ - iPrevZ;
SenseEnv(iMoveX, iMoveZ);
iPrevX = inewX;
iPrevZ = inewZ;
prevPos = newPos;
}
vis.Visualize(loc.probMap, loc.world);
}
void SenseEnv(int iMoveX, int iMoveZ)
{
Marker[] allMarkers = GameObject.FindObjectsOfType<Marker>();
Vector3 pos = transform.position;
Measurements ma = new Measurements();
ma.Init(100);
foreach(Marker marker in allMarkers)
{
Vector3 delta = (marker.transform.position - pos);
if(delta.magnitude < radiusSense)
{
int offX = Mathf.RoundToInt(delta.x / mm.map.dX);
int offZ = Mathf.RoundToInt(delta.z / mm.map.dZ);
Measurement m = new Measurement(marker.id, offX, offZ);
ma.m.Add(m);
}
}
//first move is huge and not needed.
if(prevPos != Vector3.zero)
loc.Move(iMoveX, iMoveZ, probMoveExact);
loc.Sense(ma, probSenseExact);
Vector3 likelyPos = Vector3.zero;
likelyTM.position = likelyPos;
}
}
| 0 | 0.828226 | 1 | 0.828226 | game-dev | MEDIA | 0.600479 | game-dev | 0.783595 | 1 | 0.783595 |
pret/pokeplatinum | 15,054 | res/field/scripts/scripts_union_room.s | #include "macros/scrcmd.inc"
#include "res/text/bank/union_room.h"
ScriptEntry _0022
ScriptEntry _0024
ScriptEntry _0026
ScriptEntry _002A
ScriptEntry _07BA
ScriptEntry _0BC0
ScriptEntry _0BD3
ScriptEntry _0BE3
ScriptEntryEnd
_0022:
End
_0024:
End
_0026:
ScrCmd_142
End
_002A:
PlayFanfare SEQ_SE_CONFIRM
LockAll
FacePlayer
ScrCmd_140 VAR_RESULT
SetVar VAR_0x8004, VAR_RESULT
GoToIfEq VAR_RESULT, 5, _0497
ScrCmd_13C 0
GoToIfEq VAR_RESULT, 2, _04AD
GoToIfEq VAR_RESULT, 3, _053A
GoToIfEq VAR_RESULT, 4, _05AF
ScrCmd_146 VAR_0x8004, VAR_RESULT
ScrCmd_140 VAR_RESULT
GoToIfEq VAR_RESULT, 5, _0497
Message 199
ScrCmd_141 VAR_RESULT
SetVar VAR_0x8008, VAR_RESULT
GoToIfEq VAR_0x8008, 3, _07BA
GoToIfEq VAR_0x8008, 2, _0486
GoTo _00BA
End
_00BA:
ScrCmd_135 100
ScrCmd_13F 2, VAR_RESULT
ScrCmd_2C0 VAR_RESULT
GoTo _00EA
End
_00D0:
ScrCmd_135 100
ScrCmd_139 11
ScrCmd_13F 22, VAR_RESULT
MessageVar VAR_RESULT
GoTo _00EA
End
_00EA:
InitGlobalTextMenu 31, 3, 0, VAR_RESULT
SetMenuXOriginToRight
AddMenuEntryImm 165, 0
AddMenuEntryImm 56, 1
AddMenuEntryImm 49, 2
AddMenuEntryImm 22, 3
AddMenuEntryImm 140, 4
AddMenuEntryImm 139, 5
AddMenuEntryImm 23, 99
ShowUnionRoomMenu
SetVar VAR_0x8008, VAR_RESULT
GoToIfEq VAR_0x8008, 0, _0182
GoToIfEq VAR_0x8008, 1, _0334
GoToIfEq VAR_0x8008, 2, _0274
GoToIfEq VAR_0x8008, 3, _01EB
GoToIfEq VAR_0x8008, 4, _0394
GoToIfEq VAR_0x8008, 5, _03F4
GoToIfEq VAR_0x8008, 7, _0792
ScrCmd_143 0, 7
GoTo _0776
End
_0182:
ScrCmd_143 0, 1
ScrCmd_13F 9, VAR_RESULT
GoToIfEq VAR_RESULT, 0, _019F
MessageVar VAR_RESULT
_019F:
ScrCmd_144 VAR_RESULT
GoToIfEq VAR_RESULT, 7, _06A0
ScrCmd_139 5
ScrCmd_13F 1, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
ScrCmd_135 1
CloseMessage
FadeScreenOut
WaitFadeScreen
ScrCmd_0AD
ReturnToField
Call _0BB2
MessageInstant 16
GoTo _00D0
End
_01EB:
CountPartyNonEggs VAR_RESULT
GoToIfLt VAR_RESULT, 2, _0262
ScrCmd_143 0, 3
ScrCmd_13F 9, VAR_RESULT
GoToIfEq VAR_RESULT, 0, _0219
MessageVar VAR_RESULT
_0219:
ScrCmd_144 VAR_RESULT
GoToIfEq VAR_RESULT, 7, _06E8
ScrCmd_139 7
ScrCmd_13F 1, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
ScrCmd_135 3
CloseMessage
FadeScreenOut
WaitFadeScreen
ScrCmd_0AE
ReturnToField
Call _0BB2
GoTo _00D0
End
_0262:
ScrCmd_13F 20, VAR_RESULT
MessageVar VAR_RESULT
GoTo _00D0
End
_0274:
CountPartyMonsBelowLevelThreshold VAR_RESULT, 30
GoToIfLt VAR_RESULT, 2, _0322
ScrCmd_143 0, 2
ScrCmd_13F 9, VAR_RESULT
GoToIfEq VAR_RESULT, 0, _02A4
MessageVar VAR_RESULT
_02A4:
ScrCmd_144 VAR_RESULT
GoToIfEq VAR_RESULT, 7, _06D0
ScrCmd_139 6
ScrCmd_13F 1, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
ScrCmd_135 2
CloseMessage
FadeScreenOut
WaitFadeScreen
SelectPokemonForUnionRoomBattle
FadeScreenIn
WaitFadeScreen
Message 202
ScrCmd_135 102
CloseMessage
ScrCmd_2BA VAR_RESULT
GoToIfEq VAR_RESULT, 1, _0B63
GoToIfEq VAR_RESULT, 2, _0B63
StartLinkBattle
Call _0BB2
GoTo _00D0
End
_0322:
ScrCmd_13F 19, VAR_RESULT
MessageVar VAR_RESULT
GoTo _00D0
End
_0334:
ScrCmd_143 0, 4
ScrCmd_13F 9, VAR_RESULT
GoToIfEq VAR_RESULT, 0, _0351
MessageVar VAR_RESULT
_0351:
ScrCmd_144 VAR_RESULT
GoToIfEq VAR_RESULT, 7, _06B8
ScrCmd_13F 1, VAR_RESULT
MessageVar VAR_RESULT
WaitABPressTime 30
ScrCmd_135 4
CloseMessage
FadeScreenOut
WaitFadeScreen
ScrCmd_0AC
ReturnToField
Call _0BB2
GoTo _0476
End
_0394:
ScrCmd_143 0, 5
ScrCmd_13F 9, VAR_RESULT
GoToIfEq VAR_RESULT, 0, _03B1
MessageVar VAR_RESULT
_03B1:
ScrCmd_144 VAR_RESULT
GoToIfEq VAR_RESULT, 7, _0718
ScrCmd_13F 1, VAR_RESULT
MessageVar VAR_RESULT
WaitABPressTime 30
ScrCmd_135 5
CloseMessage
FadeScreenOut
WaitFadeScreen
ScrCmd_0AF
ReturnToField
Call _0BB2
GoTo _0476
End
_03F4:
CountPartyEggs VAR_RESULT
GoToIfEq VAR_RESULT, 0, _0741
ScrCmd_2C7 VAR_RESULT
GoToIfEq VAR_RESULT, 0, _0753
ScrCmd_143 0, 6
ScrCmd_13F 9, VAR_RESULT
GoToIfEq VAR_RESULT, 0, _0433
MessageVar VAR_RESULT
_0433:
ScrCmd_144 VAR_RESULT
GoToIfEq VAR_RESULT, 7, _075E
ScrCmd_13F 1, VAR_RESULT
MessageVar VAR_RESULT
WaitABPressTime 30
ScrCmd_135 6
CloseMessage
FadeScreenOut
WaitFadeScreen
ScrCmd_2C6
ReturnToField
Call _0BB2
GoTo _0476
End
_0476:
ReleaseAll
End
UnionRoom_Unused:
ScrCmd_143 0, 1
CloseMessage
ReleaseAll
End
_0486:
Message 38
WaitTime 30, VAR_RESULT
CloseMessage
ScrCmd_13B
ReleaseAll
End
_0497:
ScrCmd_13A
ScrCmd_13F 0, VAR_RESULT
MessageVar VAR_RESULT
WaitABPress
CloseMessage
ScrCmd_13B
ReleaseAll
End
_04AD:
ScrCmd_13A
ScrCmd_13F 10, VAR_RESULT
MessageVar VAR_RESULT
ShowYesNoMenu VAR_RESULT
GoToIfEq VAR_RESULT, MENU_NO, _0522
ScrCmd_146 VAR_0x8004, VAR_RESULT
GoToIfEq VAR_RESULT, 5, _0486
ScrCmd_141 VAR_RESULT
GoToIfEq VAR_RESULT, 2, _0486
ScrCmd_13F 13, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
CloseMessage
FadeScreenOut
WaitFadeScreen
ScrCmd_0AC
ReturnToField
FadeScreenIn
GoTo _0476
End
_0522:
ScrCmd_13F 16, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
ScrCmd_13B
CloseMessage
ReleaseAll
End
_053A:
ScrCmd_13A
ScrCmd_13F 11, VAR_RESULT
MessageVar VAR_RESULT
ShowYesNoMenu VAR_RESULT
GoToIfEq VAR_RESULT, MENU_NO, _0646
ScrCmd_146 VAR_0x8004, VAR_RESULT
GoToIfEq VAR_RESULT, 5, _0486
ScrCmd_141 VAR_RESULT
GoToIfEq VAR_RESULT, 2, _0486
ScrCmd_13F 14, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
CloseMessage
FadeScreenOut
WaitFadeScreen
ScrCmd_0AF
ReturnToField
FadeScreenIn
GoTo _0476
End
_05AF:
ScrCmd_13A
ScrCmd_13F 12, VAR_RESULT
MessageVar VAR_RESULT
ShowYesNoMenu VAR_RESULT
GoToIfEq VAR_RESULT, MENU_NO, _065E
CountPartyEggs VAR_RESULT
GoToIfEq VAR_RESULT, 0, _068A
CheckPartyHasBadEgg VAR_RESULT
GoToIfEq VAR_RESULT, 1, _0674
ScrCmd_146 VAR_0x8004, VAR_RESULT
GoToIfEq VAR_RESULT, 5, _0486
ScrCmd_141 VAR_RESULT
GoToIfEq VAR_RESULT, 2, _0486
ScrCmd_13F 15, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
CloseMessage
FadeScreenOut
WaitFadeScreen
ScrCmd_2C6
ReturnToField
FadeScreenIn
GoTo _0476
End
_0646:
ScrCmd_13F 17, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
CloseMessage
ScrCmd_13B
ReleaseAll
End
_065E:
ScrCmd_13F 18, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
CloseMessage
ReleaseAll
End
_0674:
ScrCmd_13F 26, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
CloseMessage
ReleaseAll
End
_068A:
ScrCmd_13F 21, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
CloseMessage
ReleaseAll
End
_06A0:
ScrCmd_13F 3, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
GoTo _07AE
End
_06B8:
ScrCmd_13F 4, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
GoTo _07AE
End
_06D0:
ScrCmd_13F 5, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
GoTo _07AE
End
_06E8:
ScrCmd_13F 6, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
GoTo _07AE
End
UnionRoom_Unused2:
ScrCmd_13F 7, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
GoTo _07AE
End
_0718:
ScrCmd_13F 8, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
GoTo _07AE
End
_0730:
ScrCmd_143 1, 1
Message 36
GoTo _0B9A
End
_0741:
ScrCmd_13F 21, VAR_RESULT
MessageVar VAR_RESULT
GoTo _00D0
End
_0753:
Message 218
GoTo _00D0
End
_075E:
ScrCmd_13F 8, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
GoTo _07AE
End
_0776:
ScrCmd_13F 23, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
ScrCmd_135 101
CloseMessage
ScrCmd_13E
ReleaseAll
End
_0792:
ScrCmd_13F 24, VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
ScrCmd_135 101
CloseMessage
ScrCmd_13E
ReleaseAll
End
_07AE:
ScrCmd_135 101
CloseMessage
ScrCmd_13E
ReleaseAll
End
_07BA:
LockAll
PlayFanfare SEQ_SE_DP_BUTTON9
ScrCmd_13C 1
ScrCmd_2C0 7
WaitABPressTime 30
GoTo _07D4
End
_07D4:
Message 9
ScrCmd_135 100
ScrCmd_139 11
ScrCmd_145 VAR_RESULT
SetVar VAR_0x8008, VAR_RESULT
GoToIfEq VAR_0x8008, 1, _0853
GoToIfEq VAR_0x8008, 4, _0AED
GoToIfEq VAR_0x8008, 2, _095C
GoToIfEq VAR_0x8008, 3, _08C7
GoToIfEq VAR_0x8008, 5, _0A28
GoToIfEq VAR_0x8008, 6, _0A82
GoToIfEq VAR_0x8008, 7, _0B78
GoToIfEq VAR_0x8008, 8, _0B89
End
_0853:
Message 11
ShowYesNoMenu VAR_RESULT
GoToIfEq VAR_RESULT, MENU_NO, _08B6
ScrCmd_143 1, 0
CloseMessage
ScrCmd_144 VAR_RESULT
GoToIfEq VAR_RESULT, 7, _0B58
ScrCmd_2AF VAR_RESULT
MessageVar VAR_RESULT
WaitTime 30, VAR_RESULT
ScrCmd_135 1
CloseMessage
ScrCmd_139 5
FadeScreenOut
WaitFadeScreen
ScrCmd_0AD
ReturnToField
Call _0BB2
GoTo _07D4
End
_08B6:
ScrCmd_143 1, 1
Message 17
GoTo _0B9A
End
_08C7:
Message 26
ShowYesNoMenu VAR_RESULT
GoToIfEq VAR_RESULT, MENU_NO, _093A
CountPartyNonEggs VAR_RESULT
GoToIfLt VAR_RESULT, 2, _094B
ScrCmd_143 1, 0
CloseMessage
ScrCmd_144 VAR_RESULT
GoToIfEq VAR_RESULT, 7, _0B78
Message 27
WaitTime 30, VAR_RESULT
ScrCmd_135 3
CloseMessage
ScrCmd_139 7
FadeScreenOut
WaitFadeScreen
ScrCmd_0AE
ReturnToField
ScrCmd_139 11
Call _0BB2
GoTo _07D4
End
_093A:
ScrCmd_143 1, 1
Message 20
GoTo _0B9A
End
_094B:
ScrCmd_143 1, 1
Message 29
GoTo _0B9A
End
_095C:
Message 21
ShowYesNoMenu VAR_RESULT
GoToIfEq VAR_RESULT, MENU_NO, _0A06
CountPartyMonsBelowLevelThreshold VAR_RESULT, 30
GoToIfLt VAR_RESULT, 2, _0A17
ScrCmd_143 1, 0
CloseMessage
ScrCmd_144 VAR_RESULT
GoToIfEq VAR_RESULT, 7, _0B78
Message 22
WaitTime 30, VAR_RESULT
ScrCmd_135 2
CloseMessage
ScrCmd_139 6
FadeScreenOut
WaitFadeScreen
SelectPokemonForUnionRoomBattle
FadeScreenIn
WaitFadeScreen
Message 202
ScrCmd_135 102
CloseMessage
ScrCmd_2BA VAR_RESULT
GoToIfEq VAR_RESULT, 1, _0B63
GoToIfEq VAR_RESULT, 2, _0B63
StartLinkBattle
ScrCmd_139 11
Call _0BB2
GoTo _07D4
End
_0A06:
ScrCmd_143 1, 1
Message 23
GoTo _0B9A
End
_0A17:
ScrCmd_143 1, 1
Message 24
GoTo _0B9A
End
_0A28:
Message 30
ShowYesNoMenu VAR_RESULT
GoToIfEq VAR_RESULT, MENU_NO, _0A06
ScrCmd_143 1, 0
CloseMessage
ScrCmd_144 VAR_RESULT
GoToIfEq VAR_RESULT, 7, _0B78
Message 31
WaitTime 30, VAR_RESULT
ScrCmd_135 5
CloseMessage
ScrCmd_139 2
FadeScreenOut
WaitFadeScreen
ScrCmd_0AF
ReturnToField
Call _0BB2
ReleaseAll
End
_0A82:
Message 33
ShowYesNoMenu VAR_RESULT
GoToIfEq VAR_RESULT, MENU_NO, _0A06
ScrCmd_143 1, 0
CloseMessage
CountPartyEggs VAR_RESULT
GoToIfEq VAR_RESULT, 0, _0730
ScrCmd_144 VAR_RESULT
GoToIfEq VAR_RESULT, 7, _0B78
Message 34
WaitTime 30, VAR_RESULT
ScrCmd_135 6
CloseMessage
ScrCmd_139 13
FadeScreenOut
WaitFadeScreen
ScrCmd_2C6
ReturnToField
Call _0BB2
ReleaseAll
End
_0AED:
Message 18
ShowYesNoMenu VAR_RESULT
GoToIfEq VAR_RESULT, MENU_NO, _0B47
ScrCmd_143 1, 0
CloseMessage
ScrCmd_144 VAR_RESULT
GoToIfEq VAR_RESULT, 7, _0B78
Message 19
WaitTime 30, VAR_RESULT
ScrCmd_135 4
CloseMessage
ScrCmd_139 1
FadeScreenOut
WaitFadeScreen
ScrCmd_0AC
ReturnToField
Call _0BB2
ReleaseAll
End
_0B47:
ScrCmd_143 1, 1
Message 28
GoTo _0B9A
End
_0B58:
Message 35
GoTo _0B9A
End
_0B63:
ScrCmd_139 11
Message 25
WaitTime 30, VAR_RESULT
GoTo _0B9A
End
_0B78:
Message 8
WaitTime 30, VAR_RESULT
GoTo _0B9A
End
_0B89:
Message 10
WaitTime 30, VAR_RESULT
GoTo _0B9A
End
_0B9A:
ScrCmd_135 101
CloseMessage
ScrCmd_13E
ReleaseAll
End
UnionRoom_Unused3:
ScrCmd_143 1, 1
CloseMessage
ReleaseAll
End
_0BB2:
ScrCmd_13D
FadeScreenIn
Return
_0BC0:
PlayFanfare SEQ_SE_CONFIRM
LockAll
FacePlayer
Message 207
WaitABXPadPress
CloseMessage
ReleaseAll
End
_0BD3:
PlayFanfare SEQ_SE_CONFIRM
LockAll
FacePlayer
GoTo _0497
End
_0BE3:
PlayFanfare SEQ_SE_CONFIRM
LockAll
FacePlayer
GoTo _0BF3
End
_0BF3:
ScrCmd_13A
CallIfSet FLAG_UNK_0x00BB, _0C50
CallIfUnset FLAG_UNK_0x00BB, _0C55
SetFlag FLAG_UNK_0x00BB
InitGlobalTextMenu 31, 11, 0, VAR_RESULT
SetMenuXOriginToRight
AddMenuEntryImm 10, 0
AddMenuEntryImm 166, 1
AddMenuEntryImm 23, 2
ShowMenu
SetVar VAR_0x8008, VAR_RESULT
GoToIfEq VAR_0x8008, 0, _0C72
GoToIfEq VAR_0x8008, 1, _0C5A
GoTo _0C6A
End
_0C50:
Message 158
Return
_0C55:
Message 157
Return
_0C5A:
ScrCmd_138 VAR_RESULT
MessageVar VAR_RESULT
GoTo _0BF3
End
_0C6A:
ScrCmd_13B
CloseMessage
ReleaseAll
End
_0C72:
Message 159
InitGlobalTextMenu 31, 3, 0, VAR_RESULT
SetMenuXOriginToRight
AddMenuEntryImm 49, 0
AddMenuEntryImm 22, 1
AddMenuEntryImm 140, 2
AddMenuEntryImm 56, 3
AddMenuEntryImm 167, 4
AddMenuEntryImm 139, 5
AddMenuEntryImm 12, 6
ShowMenu
SetVar VAR_0x8008, VAR_RESULT
GoToIfEq VAR_0x8008, 0, _0CFA
GoToIfEq VAR_0x8008, 1, _0D05
GoToIfEq VAR_0x8008, 2, _0D10
GoToIfEq VAR_0x8008, 3, _0D1B
GoToIfEq VAR_0x8008, 4, _0D26
GoToIfEq VAR_0x8008, 5, _0D31
GoTo _0BF3
End
_0CFA:
Message 160
GoTo _0C72
End
_0D05:
Message 161
GoTo _0C72
End
_0D10:
Message 162
GoTo _0C72
End
_0D1B:
Message 164
GoTo _0C72
End
_0D26:
Message 165
GoTo _0C72
End
_0D31:
Message 163
GoTo _0C72
End
UnionRoom_Unused4:
GoTo _0BF3
End
| 0 | 0.519034 | 1 | 0.519034 | game-dev | MEDIA | 0.454229 | game-dev | 0.652434 | 1 | 0.652434 |
magefree/mage | 3,138 | Mage.Tests/src/test/java/org/mage/test/cards/single/ori/JaceVrynsProdigyTest.java | package org.mage.test.cards.single.ori;
import mage.constants.PhaseStep;
import mage.constants.Zone;
import org.junit.Test;
import org.mage.test.serverside.base.CardTestPlayerBase;
/**
* @author Susucr
*/
public class JaceVrynsProdigyTest extends CardTestPlayerBase {
/**
* {@link mage.cards.j.JaceVrynsProdigy Jace, Vryn's Prodigy} {1}{U}
* Legendary Creature — Human Wizard
* {T}: Draw a card, then discard a card. If there are five or more cards in your graveyard, exile Jace, Vryn’s Prodigy, then return him to the battlefield transformed under his owner’s control.
* 0/2
* //
* Jace, Telepath Unbound
* Legendary Planeswalker — Jace
* +1: Up to one target creature gets -2/-0 until your next turn.
* −3: You may cast target instant or sorcery card from your graveyard this turn. If that spell would be put into your graveyard, exile it instead.
* −9: You get an emblem with “Whenever you cast a spell, target opponent mills five cards.”
* Loyalty: 5
*/
private static final String jace = "Jace, Vryn's Prodigy";
@Test
public void test_Minus3_Split() {
setStrictChooseMode(true);
skipInitShuffling();
addCard(Zone.BATTLEFIELD, playerA, jace);
addCard(Zone.BATTLEFIELD, playerB, "Memnite");
addCard(Zone.BATTLEFIELD, playerA, "Island", 2);
addCard(Zone.LIBRARY, playerA, "Fire // Ice");
addCard(Zone.GRAVEYARD, playerA, "Taiga", 4);
activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{T}: Draw a card, then discard a card.");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "-3", "Fire // Ice");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Ice", "Memnite");
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertExileCount(playerA, "Fire // Ice", 1);
assertHandCount(playerA, 1);
assertTappedCount("Memnite", true, 1);
assertTappedCount("Island", true, 2); // cost mana to cast
}
@Test
public void test_Minus3_MDFC() {
setStrictChooseMode(true);
skipInitShuffling();
addCard(Zone.BATTLEFIELD, playerA, jace);
addCard(Zone.BATTLEFIELD, playerA, "Swamp", 6);
addCard(Zone.LIBRARY, playerA, "Zof Consumption"); // Each opponent loses 4 life and you gain 4 life.
addCard(Zone.GRAVEYARD, playerA, "Taiga", 4);
activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{T}: Draw a card, then discard a card.");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "-3", "Zof Consumption");
castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, "Zof Consumption");
setStopAt(1, PhaseStep.END_TURN);
execute();
assertExileCount(playerA, "Zof Consumption", 1);
assertLife(playerA, 20 + 4);
assertLife(playerB, 20 - 4);
assertTappedCount("Swamp", true, 6); // cost mana to cast
}
}
| 0 | 0.956989 | 1 | 0.956989 | game-dev | MEDIA | 0.849765 | game-dev,testing-qa | 0.990136 | 1 | 0.990136 |
PolarisSS13/Polaris | 3,535 | code/modules/overmap/ships/computers/computer_shims.dm | /*
**
** HELLO! DON'T COPY THINGS FROM HERE - READ THIS!
**
** The ship machines/computers ported from baystation expect certain procs and infrastruture that we don't have.
** I /could/ just port those computers to our code, but I actually *like* that infrastructure. But I
** don't have time (yet) to implement it fully in our codebase, so I'm shimming it here experimentally as a test
** bed for later implementing it on /obj/machinery and /obj/machinery/computer for everything. ~Leshana (March 2020)
*/
//
// Power
//
// Change one of the power consumption vars
/obj/machinery/proc/change_power_consumption(new_power_consumption, use_power_mode = USE_POWER_IDLE)
switch(use_power_mode)
if(USE_POWER_IDLE)
update_idle_power_usage(new_power_consumption)
if(USE_POWER_ACTIVE)
update_active_power_usage(new_power_consumption)
// No need to do anything else in our power scheme.
// Defining directly here to avoid conflicts with existing set_broken procs in our codebase that behave differently.
/obj/machinery/atmospherics/unary/engine/proc/set_broken(var/new_state, var/cause)
if(!(stat & BROKEN) == !new_state)
return // Nothing changed
stat ^= BROKEN
update_icon()
//
// Compoenents
//
/obj/machinery/proc/total_component_rating_of_type(var/part_type)
. = 0
for(var/thing in component_parts)
if(istype(thing, part_type))
var/obj/item/stock_parts/part = thing
. += part.rating
// Now isn't THIS a cool idea?
// for(var/path in uncreated_component_parts)
// if(ispath(path, part_type))
// var/obj/item/stock_parts/comp = path
// . += initial(comp.rating) * uncreated_component_parts[path]
//
// Skills
//
/obj/machinery/computer/ship
var/core_skill = /datum/skill/devices //The skill used for skill checks for this machine (mostly so subtypes can use different skills).
//
// Topic
//
/obj/machinery/computer/ship/proc/DefaultTopicState()
return global.default_state
/obj/machinery/computer/ship/Topic(var/href, var/href_list = list(), var/datum/topic_state/state)
if((. = ..()))
return
state = state || DefaultTopicState() || global.default_state
if(CanUseTopic(usr, state, href_list) == STATUS_INTERACTIVE)
CouldUseTopic(usr)
return OnTopic(usr, href_list, state)
CouldNotUseTopic(usr)
return TRUE
/obj/machinery/computer/ship/proc/OnTopic(var/mob/user, var/href_list, var/datum/topic_state/state)
return TOPIC_NOACTION
//
// Interaction
//
// If you want to have interface interactions handled for you conveniently, use this.
// Return TRUE for handled.
// If you perform direct interactions in here, you are responsible for ensuring that full interactivity checks have been made (i.e CanInteract).
// The checks leading in to here only guarantee that the user should be able to view a UI.
/obj/machinery/computer/ship/proc/interface_interact(var/mob/user)
ui_interact(user)
return TRUE
/obj/machinery/computer/ship/attack_ai(mob/user)
if(CanUseTopic(user, DefaultTopicState()) > STATUS_CLOSE)
return interface_interact(user)
// After a recent rework this should mostly be safe.
/obj/machinery/computer/ship/attack_ghost(mob/user)
interface_interact(user)
// If you don't call parent in this proc, you must make all appropriate checks yourself.
// If you do, you must respect the return value.
/obj/machinery/computer/ship/attack_hand(mob/user)
if((. = ..()))
return
if(!allowed(user))
to_chat(user, "<span class='warning'>Access Denied.</span>")
return 1
if(CanUseTopic(user, DefaultTopicState()) > STATUS_CLOSE)
return interface_interact(user)
| 0 | 0.937785 | 1 | 0.937785 | game-dev | MEDIA | 0.478325 | game-dev | 0.851246 | 1 | 0.851246 |
agraef/purr-data | 1,680 | externals/sigpack/split~.c | /* sIgpAck
* for
* pure-data
* www.weiss-archiv.de */
#include "m_pd.h"
#ifdef _MSC_VER
#pragma warning( disable : 4244 )
#pragma warning( disable : 4305 )
#endif
/* ------------------------ split~ ----------------------------- */
/* signal splitter */
static t_class *split_tilde_class;
typedef struct _split_tilde
{
t_object x_obj;
float x_f;
t_sample x_thres;
} t_split_tilde;
static void *split_tilde_new(t_floatarg thres)
{
t_split_tilde *x = (t_split_tilde *)pd_new(split_tilde_class);
x->x_thres = thres;
outlet_new(&x->x_obj, gensym("signal"));
outlet_new(&x->x_obj, gensym("signal"));
floatinlet_new(&x->x_obj, &x->x_thres);
x->x_f = 0;
if(thres) x->x_thres = thres;
else x->x_thres = 0;
return (x);
}
static t_int *split_tilde_perform(t_int *w)
{
t_split_tilde *x = (t_split_tilde *)(w[1]);
t_float *in = (t_float *)(w[2]);
t_float *out1 = (t_float *)(w[3]);
t_float *out2 = (t_float *)(w[4]);
int n = (int)(w[5]);
while (n--)
{
float f = *in++;
if(f < x->x_thres)
{
*out1++ = f;
*out2++ = 0;
}
else if(f >= x->x_thres)
{
*out1++ = 0;
*out2++ = f;
}
}
return (w+6);
}
static void split_tilde_dsp(t_split_tilde *x, t_signal **sp)
{
dsp_add(split_tilde_perform, 5, x, sp[0]->s_vec, sp[1]->s_vec, sp[2]->s_vec, (t_int)sp[0]->s_n);
}
void split_tilde_setup(void)
{
split_tilde_class = class_new(gensym("split~"), (t_newmethod)split_tilde_new, 0,
sizeof(t_split_tilde), 0, A_DEFFLOAT, 0);
CLASS_MAINSIGNALIN(split_tilde_class, t_split_tilde, x_f);
class_addmethod(split_tilde_class, (t_method)split_tilde_dsp, gensym("dsp"), A_CANT, 0);
}
| 0 | 0.720976 | 1 | 0.720976 | game-dev | MEDIA | 0.281185 | game-dev | 0.910969 | 1 | 0.910969 |
codetaylor/pyrotech-1.12 | 1,379 | src/main/java/com/codetaylor/mc/pyrotech/library/spi/plugin/waila/BodyProviderAdapter.java | package com.codetaylor.mc.pyrotech.library.spi.plugin.waila;
import mcp.mobius.waila.api.IWailaConfigHandler;
import mcp.mobius.waila.api.IWailaDataAccessor;
import mcp.mobius.waila.api.IWailaDataProvider;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.util.List;
public abstract class BodyProviderAdapter
implements IWailaDataProvider {
@Nonnull
@Override
public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler config) {
return ItemStack.EMPTY;
}
@Nonnull
@Override
public List<String> getWailaHead(
ItemStack itemStack,
List<String> tooltip,
IWailaDataAccessor accessor,
IWailaConfigHandler config
) {
return tooltip;
}
@Nonnull
@Override
public List<String> getWailaTail(
ItemStack itemStack,
List<String> tooltip,
IWailaDataAccessor accessor,
IWailaConfigHandler config
) {
return tooltip;
}
@Nonnull
@Override
public NBTTagCompound getNBTData(
EntityPlayerMP player,
TileEntity tileEntity,
NBTTagCompound tag,
World world,
BlockPos pos
) {
return tag;
}
}
| 0 | 0.542944 | 1 | 0.542944 | game-dev | MEDIA | 0.98567 | game-dev | 0.521423 | 1 | 0.521423 |
PaperMC/Paper-archive | 2,351 | patches/server/1008-Always-send-Banner-patterns-to-the-client.patch | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Shane Freeder <theboyetronic@gmail.com>
Date: Sun, 20 Oct 2024 18:23:59 +0100
Subject: [PATCH] Always send Banner patterns to the client
The mojang client will not remove patterns from a Banner when none
are sent inside of an update packet, given that this is not an expected
flow for them, this is not all too surprising. So, we shall resort to always
sending the patterns over the network for update packets.
diff --git a/src/main/java/net/minecraft/world/level/block/entity/BannerBlockEntity.java b/src/main/java/net/minecraft/world/level/block/entity/BannerBlockEntity.java
index 27fd8b88dc1433c1df1e09604a3cc546bfa0d2b9..1f3e1c7128b9a0f27f2df39a8970050c5313d7a3 100644
--- a/src/main/java/net/minecraft/world/level/block/entity/BannerBlockEntity.java
+++ b/src/main/java/net/minecraft/world/level/block/entity/BannerBlockEntity.java
@@ -57,7 +57,7 @@ public class BannerBlockEntity extends BlockEntity implements Nameable {
@Override
protected void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) {
super.saveAdditional(nbt, registries);
- if (!this.patterns.equals(BannerPatternLayers.EMPTY)) {
+ if (!this.patterns.equals(BannerPatternLayers.EMPTY) || serialisingForNetwork.get()) { // Paper - always send patterns to client
nbt.put("patterns", (Tag) BannerPatternLayers.CODEC.encodeStart(registries.createSerializationContext(NbtOps.INSTANCE), this.patterns).getOrThrow());
}
@@ -89,9 +89,18 @@ public class BannerBlockEntity extends BlockEntity implements Nameable {
return ClientboundBlockEntityDataPacket.create(this);
}
+ // Paper start - always send patterns to client
+ ThreadLocal<Boolean> serialisingForNetwork = ThreadLocal.withInitial(() -> Boolean.FALSE);
@Override
public CompoundTag getUpdateTag(HolderLookup.Provider registries) {
+ final Boolean wasSerialisingForNetwork = serialisingForNetwork.get();
+ try {
+ serialisingForNetwork.set(Boolean.TRUE);
return this.saveWithoutMetadata(registries);
+ } finally {
+ serialisingForNetwork.set(wasSerialisingForNetwork);
+ }
+ // Paper end - always send patterns to client
}
public BannerPatternLayers getPatterns() {
| 0 | 0.758244 | 1 | 0.758244 | game-dev | MEDIA | 0.8605 | game-dev,networking | 0.844138 | 1 | 0.844138 |
mtsamis/box2d-optimized | 7,197 | src/dynamics/b2_friction_joint.cpp | // MIT License
// Copyright (c) 2019 Erin Catto
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "box2d/b2_friction_joint.h"
#include "box2d/b2_body.h"
#include "box2d/b2_time_step.h"
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor)
{
bodyA = bA;
bodyB = bB;
localAnchorA = bodyA->GetLocalPoint(anchor);
localAnchorB = bodyB->GetLocalPoint(anchor);
}
b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def)
: b2Joint(def)
{
m_localAnchorA = def->localAnchorA;
m_localAnchorB = def->localAnchorB;
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
m_maxForce = def->maxForce;
m_maxTorque = def->maxTorque;
}
void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_localCenterA = m_bodyA->m_sweep.localCenter;
m_localCenterB = m_bodyB->m_sweep.localCenter;
m_invMassA = m_bodyA->m_invMass;
m_invMassB = m_bodyB->m_invMass;
m_invIA = m_bodyA->m_invI;
m_invIB = m_bodyB->m_invI;
float aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
float aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
b2Rot qA(aA), qB(aB);
// Compute the effective mass matrix.
m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float mA = m_invMassA, mB = m_invMassB;
float iA = m_invIA, iB = m_invIB;
b2Mat22 K;
K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y;
K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x;
m_linearMass = K.GetInverse();
m_angularMass = iA + iB;
if (m_angularMass > 0.0f)
{
m_angularMass = 1.0f / m_angularMass;
}
if (data.step.warmStarting)
{
// Scale impulses to support a variable time step.
m_linearImpulse *= data.step.dtRatio;
m_angularImpulse *= data.step.dtRatio;
b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y);
vA -= mA * P;
wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse);
vB += mB * P;
wB += iB * (b2Cross(m_rB, P) + m_angularImpulse);
}
else
{
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
float mA = m_invMassA, mB = m_invMassB;
float iA = m_invIA, iB = m_invIB;
float h = data.step.dt;
// Solve angular friction
{
float Cdot = wB - wA;
float impulse = -m_angularMass * Cdot;
float oldImpulse = m_angularImpulse;
float maxImpulse = h * m_maxTorque;
m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve linear friction
{
b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
b2Vec2 impulse = -b2Mul(m_linearMass, Cdot);
b2Vec2 oldImpulse = m_linearImpulse;
m_linearImpulse += impulse;
float maxImpulse = h * m_maxForce;
if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse)
{
m_linearImpulse.Normalize();
m_linearImpulse *= maxImpulse;
}
impulse = m_linearImpulse - oldImpulse;
vA -= mA * impulse;
wA -= iA * b2Cross(m_rA, impulse);
vB += mB * impulse;
wB += iB * b2Cross(m_rB, impulse);
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data)
{
B2_NOT_USED(data);
return true;
}
b2Vec2 b2FrictionJoint::GetAnchorA() const
{
return m_bodyA->GetWorldPoint(m_localAnchorA);
}
b2Vec2 b2FrictionJoint::GetAnchorB() const
{
return m_bodyB->GetWorldPoint(m_localAnchorB);
}
b2Vec2 b2FrictionJoint::GetReactionForce(float inv_dt) const
{
return inv_dt * m_linearImpulse;
}
float b2FrictionJoint::GetReactionTorque(float inv_dt) const
{
return inv_dt * m_angularImpulse;
}
void b2FrictionJoint::SetMaxForce(float force)
{
b2Assert(b2IsValid(force) && force >= 0.0f);
m_maxForce = force;
}
float b2FrictionJoint::GetMaxForce() const
{
return m_maxForce;
}
void b2FrictionJoint::SetMaxTorque(float torque)
{
b2Assert(b2IsValid(torque) && torque >= 0.0f);
m_maxTorque = torque;
}
float b2FrictionJoint::GetMaxTorque() const
{
return m_maxTorque;
}
void b2FrictionJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b2Dump(" b2FrictionJointDef jd;\n");
b2Dump(" jd.bodyA = bodies[%d];\n", indexA);
b2Dump(" jd.bodyB = bodies[%d];\n", indexB);
b2Dump(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b2Dump(" jd.localAnchorA.Set(%.9g, %.9g);\n", m_localAnchorA.x, m_localAnchorA.y);
b2Dump(" jd.localAnchorB.Set(%.9g, %.9g);\n", m_localAnchorB.x, m_localAnchorB.y);
b2Dump(" jd.maxForce = %.9g;\n", m_maxForce);
b2Dump(" jd.maxTorque = %.9g;\n", m_maxTorque);
b2Dump(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
| 0 | 0.92462 | 1 | 0.92462 | game-dev | MEDIA | 0.982472 | game-dev | 0.984376 | 1 | 0.984376 |
EarthSalamander42/dota_imba | 27,320 | game/scripts/vscripts/components/abilities/heroes/hero_outworld_devourer.lua | -- Creator:
-- AltiV, Decemeber 28th, 2019
LinkLuaModifier("modifier_generic_orb_effect_lua", "components/modifiers/generic/modifier_generic_orb_effect_lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_generic_charges", "components/modifiers/generic/modifier_generic_charges", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_outworld_devourer_astral_imprisonment_prison", "components/abilities/heroes/hero_outworld_devourer", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_outworld_devourer_essence_flux", "components/abilities/heroes/hero_outworld_devourer", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_outworld_devourer_essence_flux_active", "components/abilities/heroes/hero_outworld_devourer", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_outworld_devourer_essence_flux_debuff", "components/abilities/heroes/hero_outworld_devourer", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_outworld_devourer_astral_imprisonment_movement", "components/abilities/heroes/hero_outworld_devourer", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_outworld_devourer_sanity_eclipse_charge", "components/abilities/heroes/hero_outworld_devourer", LUA_MODIFIER_MOTION_NONE)
imba_outworld_devourer_arcane_orb = imba_outworld_devourer_arcane_orb or class({})
imba_outworld_devourer_astral_imprisonment = imba_outworld_devourer_astral_imprisonment or class({})
modifier_imba_outworld_devourer_astral_imprisonment_prison = modifier_imba_outworld_devourer_astral_imprisonment_prison or class({})
imba_outworld_devourer_essence_flux = imba_outworld_devourer_essence_flux or class({})
modifier_imba_outworld_devourer_essence_flux = modifier_imba_outworld_devourer_essence_flux or class({})
modifier_imba_outworld_devourer_essence_flux_active = modifier_imba_outworld_devourer_essence_flux_active or class({})
modifier_imba_outworld_devourer_essence_flux_debuff = modifier_imba_outworld_devourer_essence_flux_debuff or class({})
imba_outworld_devourer_astral_imprisonment_movement = imba_outworld_devourer_astral_imprisonment_movement or class({})
modifier_imba_outworld_devourer_astral_imprisonment_movement = modifier_imba_outworld_devourer_astral_imprisonment_movement or class({})
imba_outworld_devourer_sanity_eclipse = imba_outworld_devourer_sanity_eclipse or class({})
modifier_imba_outworld_devourer_sanity_eclipse_charge = modifier_imba_outworld_devourer_sanity_eclipse_charge or class({})
---------------------------------------
-- IMBA_OUTWORLD_DEVOURER_ARCANE_ORB --
---------------------------------------
function imba_outworld_devourer_arcane_orb:GetIntrinsicModifierName()
return "modifier_generic_orb_effect_lua"
end
function imba_outworld_devourer_arcane_orb:GetProjectileName()
return "particles/units/heroes/hero_obsidian_destroyer/obsidian_destroyer_arcane_orb.vpcf"
end
function imba_outworld_devourer_arcane_orb:OnOrbFire()
self:GetCaster():EmitSound("Hero_ObsidianDestroyer.ArcaneOrb")
if self:GetCaster():HasModifier("modifier_imba_outworld_devourer_essence_flux") then
self:GetCaster():FindModifierByName("modifier_imba_outworld_devourer_essence_flux"):RollForProc()
end
end
function imba_outworld_devourer_arcane_orb:OnOrbImpact( keys )
if not keys.target:IsMagicImmune() then
local damage = self:GetCaster():GetMana() * self:GetTalentSpecialValueFor("mana_pool_damage_pct") * 0.01
-- IMBAfication: Universe Unleashed
if keys.target:IsIllusion() or keys.target:IsSummoned() then
damage = damage + self:GetSpecialValueFor("universe_bonus_dmg")
end
self.damage_dealt = ApplyDamage({
victim = keys.target,
damage = damage,
damage_type = self:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NONE,
attacker = self:GetCaster(),
ability = self
})
SendOverheadEventMessage(nil, OVERHEAD_ALERT_BONUS_SPELL_DAMAGE, keys.target, damage, nil)
-- IMBAfication: Universe Unleashed
if (keys.target:IsIllusion() or keys.target:IsSummoned()) and self.damage_dealt > 0 and self.damage_dealt >= keys.target:GetHealth() then -- and not keys.target:IsAlive() then
-- Add main particle
self.particle_explosion_fx = ParticleManager:CreateParticle("particles/hero/outworld_devourer/arcane_orb_explosion.vpcf", PATTACH_ABSORIGIN_FOLLOW, keys.target)
ParticleManager:SetParticleControl(self.particle_explosion_fx, 1, keys.target:GetAbsOrigin())
ParticleManager:ReleaseParticleIndex(self.particle_explosion_fx)
-- Add unleashed energy particles
self.particle_explosion_scatter_fx = ParticleManager:CreateParticle("particles/hero/outworld_devourer/arcane_orb_explosion_f.vpcf", PATTACH_ABSORIGIN, self:GetCaster())
ParticleManager:SetParticleControl(self.particle_explosion_scatter_fx, 0, keys.target:GetAbsOrigin())
ParticleManager:SetParticleControl(self.particle_explosion_scatter_fx, 3, Vector(self:GetSpecialValueFor("universe_splash_radius"), 0, 0))
ParticleManager:ReleaseParticleIndex(self.particle_explosion_scatter_fx)
for _, enemy in pairs(FindUnitsInRadius(self:GetCaster():GetTeamNumber(), keys.target:GetAbsOrigin(), nil, self:GetSpecialValueFor("universe_splash_radius"), DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do
ApplyDamage({
victim = enemy,
damage = damage - self:GetSpecialValueFor("universe_bonus_dmg"),
damage_type = self:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NONE,
attacker = self:GetCaster(),
ability = self
})
SendOverheadEventMessage(nil, OVERHEAD_ALERT_BONUS_SPELL_DAMAGE, enemy, damage - self:GetSpecialValueFor("universe_bonus_dmg"), nil)
end
end
if self:GetCaster():HasAbility("imba_outworld_devourer_sanity_eclipse") and self:GetCaster():FindAbilityByName("imba_outworld_devourer_sanity_eclipse"):IsTrained() and (keys.target:IsRealHero() or keys.target:IsIllusion()) and keys.target:GetTeamNumber() ~= self:GetCaster():GetTeamNumber() then
self:GetCaster():AddNewModifier(self:GetCaster(), self:GetCaster():FindAbilityByName("imba_outworld_devourer_sanity_eclipse"), "modifier_imba_outworld_devourer_sanity_eclipse_charge", {duration = self:GetSpecialValueFor("counter_duration"), charges = 1})
end
end
end
------------------------------------------------
-- IMBA_OUTWORLD_DEVOURER_ASTRAL_IMPRISONMENT --
------------------------------------------------
function imba_outworld_devourer_astral_imprisonment:RequiresScepterForCharges() return true end
function imba_outworld_devourer_astral_imprisonment:GetAssociatedSecondaryAbilities()
return "imba_outworld_devourer_astral_imprisonment_movement"
end
function imba_outworld_devourer_astral_imprisonment:GetCastRange(location, target)
if not self:GetCaster():HasScepter() then
return self.BaseClass.GetCastRange(self, location, target)
else
return self.BaseClass.GetCastRange(self, location, target) + self:GetSpecialValueFor("scepter_range_bonus")
end
end
function imba_outworld_devourer_astral_imprisonment:GetCooldown(level)
if not self:GetCaster():HasScepter() then
return self.BaseClass.GetCooldown(self, level)
else
return 0
end
end
function imba_outworld_devourer_astral_imprisonment:OnInventoryContentsChanged()
-- Caster got scepter
if self:GetCaster():HasScepter() and not self:GetCaster():HasModifier("modifier_generic_charges") then
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_generic_charges", {})
end
end
function imba_outworld_devourer_astral_imprisonment:OnHeroCalculateStatBonus()
self:OnInventoryContentsChanged()
end
function imba_outworld_devourer_astral_imprisonment:OnSpellStart()
local target = self:GetCursorTarget()
if not target:TriggerSpellAbsorb(self) then
target:EmitSound("Hero_ObsidianDestroyer.AstralImprisonment")
local prison_modifier = target:AddNewModifier(self:GetCaster(), self, "modifier_imba_outworld_devourer_astral_imprisonment_prison", {duration = self:GetSpecialValueFor("prison_duration")})
if prison_modifier and target:GetTeamNumber() ~= self:GetCaster():GetTeamNumber() then
prison_modifier:SetDuration(self:GetSpecialValueFor("prison_duration") * (1 - target:GetStatusResistance()), true)
self:GetCaster():AddNewModifier(target, self, "modifier_imba_outworld_devourer_astral_imprisonment_movement", {duration = self:GetSpecialValueFor("prison_duration") * (1 - target:GetStatusResistance())})
else
self:GetCaster():AddNewModifier(target, self, "modifier_imba_outworld_devourer_astral_imprisonment_movement", {duration = self:GetSpecialValueFor("prison_duration")})
end
if self:GetCaster():HasAbility("imba_outworld_devourer_sanity_eclipse") and self:GetCaster():FindAbilityByName("imba_outworld_devourer_sanity_eclipse"):IsTrained() and (target:IsRealHero() or target:IsIllusion()) and target:GetTeamNumber() ~= self:GetCaster():GetTeamNumber() then
self:GetCaster():AddNewModifier(self:GetCaster(), self:GetCaster():FindAbilityByName("imba_outworld_devourer_sanity_eclipse"), "modifier_imba_outworld_devourer_sanity_eclipse_charge", {duration = self:GetSpecialValueFor("counter_duration"), charges = 3})
end
end
end
----------------------------------------------------------------
-- MODIFIER_IMBA_OUTWORLD_DEVOURER_ASTRAL_IMPRISONMENT_PRISON --
----------------------------------------------------------------
function modifier_imba_outworld_devourer_astral_imprisonment_prison:IsPurgable() return false end
function modifier_imba_outworld_devourer_astral_imprisonment_prison:GetEffectName()
return "particles/units/heroes/hero_obsidian_destroyer/obsidian_destroyer_prison.vpcf"
end
function modifier_imba_outworld_devourer_astral_imprisonment_prison:OnCreated()
if not IsServer() then return end
self.damage = self:GetAbility():GetTalentSpecialValueFor("damage")
self.radius = self:GetAbility():GetSpecialValueFor("radius")
self.universal_movespeed = self:GetAbility():GetSpecialValueFor("universal_movespeed")
if self:GetParent() ~= self:GetCaster() and self:GetParent():GetTeamNumber() == self:GetCaster():GetTeamNumber() then
self.universal_movespeed = self.universal_movespeed * 2
end
self.damage_type = self:GetAbility():GetAbilityDamageType()
local ring_particle = ParticleManager:CreateParticleForTeam("particles/units/heroes/hero_obsidian_destroyer/obsidian_destroyer_prison_ring.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetParent(), self:GetCaster():GetTeamNumber())
-- ParticleManager:SetParticleControlEnt(ring_particle, 0, self:GetParent(), PATTACH_ABSORIGIN_FOLLOW, "attach_hitloc", self:GetParent():GetAbsOrigin(), true) -- Doesn't seem like this works
self:AddParticle(ring_particle, false, false, -1, false, false)
-- self:GetParent():AddNoDraw()
end
function modifier_imba_outworld_devourer_astral_imprisonment_prison:OnIntervalThink()
if self.movement_position and self:GetAbility() then
if self:GetParent():GetAbsOrigin() ~= self.movement_position then
self:GetParent():SetAbsOrigin(self:GetParent():GetAbsOrigin() + ((self.movement_position - self:GetParent():GetAbsOrigin()):Normalized() * math.min(FrameTime() * self.universal_movespeed, (self.movement_position - self:GetParent():GetAbsOrigin()):Length2D())))
-- self:GetParent():SetAbsOrigin(self:GetParent():GetAbsOrigin() + ((self.movement_position - self:GetParent():GetAbsOrigin()):Normalized()))
else
self.movement_position = nil
self:StartIntervalThink(-1)
end
else
self:StartIntervalThink(-1)
end
end
-- Astral Imprisonment fully disables the target and turns it invulnerable and hidden for its duration.
function modifier_imba_outworld_devourer_astral_imprisonment_prison:CheckState()
if self:GetParent() ~= self:GetCaster() then
return {
[MODIFIER_STATE_STUNNED] = true,
[MODIFIER_STATE_INVULNERABLE] = true,
[MODIFIER_STATE_OUT_OF_GAME] = true,
[MODIFIER_STATE_NO_HEALTH_BAR] = true,
}
else
return {
[MODIFIER_STATE_MUTED] = true,
[MODIFIER_STATE_ROOTED] = true,
[MODIFIER_STATE_DISARMED] = true,
[MODIFIER_STATE_INVULNERABLE] = true,
[MODIFIER_STATE_OUT_OF_GAME] = true,
[MODIFIER_STATE_NO_HEALTH_BAR] = true,
}
end
end
function modifier_imba_outworld_devourer_astral_imprisonment_prison:OnDestroy()
if not IsServer() then return end
-- self:GetParent():RemoveNoDraw()
self:GetParent():StopSound("Hero_ObsidianDestroyer.AstralImprisonment")
self:GetParent():EmitSound("Hero_ObsidianDestroyer.AstralImprisonment.End")
local end_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_obsidian_destroyer/obsidian_destroyer_prison_end_dmg.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetParent())
ParticleManager:SetParticleControl(end_particle, 1, Vector(self.radius, self.radius, self.radius))
ParticleManager:ReleaseParticleIndex(end_particle)
FindClearSpaceForUnit(self:GetParent(), self:GetParent():GetAbsOrigin(), true)
for _, enemy in pairs(FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetParent():GetAbsOrigin(), nil, self.radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do
ApplyDamage({
victim = enemy,
damage = self.damage,
damage_type = self.damage_type,
damage_flags = DOTA_DAMAGE_FLAG_NONE,
attacker = self:GetCaster(),
ability = self:GetAbility()
})
SendOverheadEventMessage(nil, OVERHEAD_ALERT_BONUS_SPELL_DAMAGE, enemy, self.damage, nil)
end
end
-----------------------------------------
-- IMBA_OUTWORLD_DEVOURER_ESSENCE_FLUX --
-----------------------------------------
function imba_outworld_devourer_essence_flux:GetIntrinsicModifierName()
return "modifier_imba_outworld_devourer_essence_flux"
end
function imba_outworld_devourer_essence_flux:OnSpellStart()
self:GetCaster():EmitSound("Hero_ObsidianDestroyer.Equilibrium.Cast")
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_outworld_devourer_essence_flux_active", {duration = self:GetSpecialValueFor("duration")})
end
--------------------------------------------------
-- MODIFIER_IMBA_OUTWORLD_DEVOURER_ESSENCE_FLUX --
--------------------------------------------------
function modifier_imba_outworld_devourer_essence_flux:IsHidden() return true end
function modifier_imba_outworld_devourer_essence_flux:IsPurgable( ) return false end
function modifier_imba_outworld_devourer_essence_flux:RemoveOnDeath() return false end
function modifier_imba_outworld_devourer_essence_flux:DeclareFunctions()
return {MODIFIER_EVENT_ON_ABILITY_FULLY_CAST}
end
function modifier_imba_outworld_devourer_essence_flux:OnAbilityFullyCast(keys)
if keys.unit == self:GetParent() and not keys.ability:IsToggle() and not keys.ability:IsItem() and not keys.ability:GetName() == "imba_outworld_devourer_astral_imprisonment_movement" and self:GetParent().GetMaxMana then
self:RollForProc()
end
end
-- Custom function for the mana gain since Arcane Orb (which is not a traditionally castable ability) can proc this as well
function modifier_imba_outworld_devourer_essence_flux:RollForProc()
if RollPseudoRandom(self:GetAbility():GetSpecialValueFor("proc_chance"), self) then
self.proc_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_obsidian_destroyer/obsidian_destroyer_essence_effect.vpcf", PATTACH_ABSORIGIN, self:GetParent())
ParticleManager:SetParticleControlEnt(self.proc_particle, 0, self:GetParent(), PATTACH_ABSORIGIN_FOLLOW, "attach_hitloc", self:GetParent():GetAbsOrigin(), true)
ParticleManager:ReleaseParticleIndex(self.proc_particle)
self:GetParent():GiveMana(self:GetParent():GetMaxMana() * self:GetAbility():GetSpecialValueFor("mana_restore") * 0.01)
end
end
---------------------------------------------------------
-- MODIFIER_IMBA_OUTWORLD_DEVOURER_ESSENCE_FLUX_ACTIVE --
---------------------------------------------------------
function modifier_imba_outworld_devourer_essence_flux_active:GetEffectName()
return "particles/units/heroes/hero_obsidian_destroyer/obsidian_destroyer_matter_buff.vpcf"
end
function modifier_imba_outworld_devourer_essence_flux_active:GetEffectAttachType()
return PATTACH_OVERHEAD_FOLLOW
end
function modifier_imba_outworld_devourer_essence_flux_active:GetStatusEffectName()
return "particles/status_fx/status_effect_obsidian_matter.vpcf"
end
function modifier_imba_outworld_devourer_essence_flux_active:OnCreated()
-- AbilitySpecials
-- self.mana_steal = self:GetAbility():GetSpecialValueFor("mana_steal")
self.mana_steal_active = self:GetAbility():GetSpecialValueFor("mana_steal_active")
self.movement_slow = self:GetAbility():GetSpecialValueFor("movement_slow")
self.slow_duration = self:GetAbility():GetSpecialValueFor("slow_duration")
self.duration = self:GetAbility():GetSpecialValueFor("duration")
self.equal_atk_speed_diff = self:GetAbility():GetSpecialValueFor("equal_atk_speed_diff")
end
function modifier_imba_outworld_devourer_essence_flux_active:DeclareFunctions()
return {
MODIFIER_EVENT_ON_TAKEDAMAGE,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT
}
end
function modifier_imba_outworld_devourer_essence_flux_active:GetModifierAttackSpeedBonus_Constant()
return self.equal_atk_speed_diff * self:GetStackCount()
end
--- Enum DamageCategory_t
-- DOTA_DAMAGE_CATEGORY_ATTACK = 1
-- DOTA_DAMAGE_CATEGORY_SPELL = 0
function modifier_imba_outworld_devourer_essence_flux_active:OnTakeDamage(keys)
if not IsServer() then return end
if keys.attacker == self:GetCaster() then --and keys.damage_category == 0 then
keys.unit:EmitSound("Hero_ObsidianDestroyer.Equilibrium.Damage")
keys.unit:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_outworld_devourer_essence_flux_debuff", {duration = self.slow_duration * (1 - keys.unit:GetStatusResistance())})
self:IncrementStackCount()
end
end
------------------------------------------------------
-- MODIFIER_IMBA_OUTWORLD_DEVOURER_ESSENCE_FLUX_DEBUFF --
------------------------------------------------------
function modifier_imba_outworld_devourer_essence_flux_debuff:GetStatusEffectName()
return "particles/status_fx/status_effect_obsidian_matter_debuff.vpcf"
end
function modifier_imba_outworld_devourer_essence_flux_debuff:OnCreated()
self.movement_slow = self:GetAbility():GetTalentSpecialValueFor("movement_slow") * (-1)
self.slow_duration = self:GetAbility():GetSpecialValueFor("slow_duration")
self.equal_atk_speed_diff = self:GetAbility():GetSpecialValueFor("equal_atk_speed_diff") * (-1)
if not IsServer() then return end
self.particle = ParticleManager:CreateParticle("particles/units/heroes/hero_obsidian_destroyer/obsidian_destroyer_matter_debuff.vpcf", PATTACH_ABSORIGIN, self:GetCaster())
ParticleManager:SetParticleControl(self.particle, 0, self:GetParent():GetAbsOrigin())
ParticleManager:SetParticleControlEnt(self.particle, 1, self:GetCaster(), PATTACH_ABSORIGIN_FOLLOW, "attach_hitloc", self:GetCaster():GetAbsOrigin(), true)
ParticleManager:SetParticleControl(self.particle, 2, self:GetParent():GetAbsOrigin())
self:AddParticle(self.particle, false, false, -1, false, false)
end
function modifier_imba_outworld_devourer_essence_flux_debuff:OnRefresh()
if not IsServer() then return end
self:SetDuration(self.slow_duration * (1 - self:GetParent():GetStatusResistance()), true)
self:IncrementStackCount()
end
function modifier_imba_outworld_devourer_essence_flux_debuff:DeclareFunctions()
return {
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT
}
end
function modifier_imba_outworld_devourer_essence_flux_debuff:GetModifierMoveSpeedBonus_Percentage()
return self.movement_slow
end
function modifier_imba_outworld_devourer_essence_flux_debuff:GetModifierAttackSpeedBonus_Constant()
return self.equal_atk_speed_diff * self:GetStackCount()
end
---------------------------------------------------------
-- IMBA_OUTWORLD_DEVOURER_ASTRAL_IMPRISONMENT_MOVEMENT --
---------------------------------------------------------
function imba_outworld_devourer_astral_imprisonment_movement:IsInnateAbility() return true end
function imba_outworld_devourer_astral_imprisonment_movement:IsStealable() return false end
function imba_outworld_devourer_astral_imprisonment_movement:CastFilterResultLocation(location)
if self:GetCaster():HasModifier("modifier_imba_outworld_devourer_astral_imprisonment_movement") then
return UF_SUCCESS
else
return UF_FAIL_CUSTOM
end
end
function imba_outworld_devourer_astral_imprisonment_movement:GetCustomCastErrorLocation(location)
if not self:GetCaster():HasModifier("modifier_imba_outworld_devourer_astral_imprisonment_movement") then
return "#dota_hud_error_no_astral_imprisonments_active"
end
end
function imba_outworld_devourer_astral_imprisonment_movement:OnSpellStart()
for _, astral_mod in pairs(self:GetCaster():FindAllModifiersByName("modifier_imba_outworld_devourer_astral_imprisonment_movement")) do
if astral_mod:GetCaster():HasModifier("modifier_imba_outworld_devourer_astral_imprisonment_prison") then
local prison_modifier = astral_mod:GetCaster():FindModifierByName("modifier_imba_outworld_devourer_astral_imprisonment_prison")
prison_modifier.movement_position = self:GetCursorPosition()
prison_modifier:OnIntervalThink()
prison_modifier:StartIntervalThink(FrameTime())
end
end
end
------------------------------------------------------------------
-- MODIFIER_IMBA_OUTWORLD_DEVOURER_ASTRAL_IMPRISONMENT_MOVEMENT --
------------------------------------------------------------------
function modifier_imba_outworld_devourer_astral_imprisonment_movement:IsDebuff() return false end
function modifier_imba_outworld_devourer_astral_imprisonment_movement:IsPurgable() return false end
function modifier_imba_outworld_devourer_astral_imprisonment_movement:IsHidden() return true end
function modifier_imba_outworld_devourer_astral_imprisonment_movement:RemoveOnDeath() return false end
function modifier_imba_outworld_devourer_astral_imprisonment_movement:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
-------------------------------------------
-- IMBA_OUTWORLD_DEVOURER_SANITY_ECLIPSE --
-------------------------------------------
function imba_outworld_devourer_sanity_eclipse:GetAOERadius()
return self:GetSpecialValueFor("radius")
end
function imba_outworld_devourer_sanity_eclipse:OnSpellStart()
self:GetCaster():EmitSound("Hero_ObsidianDestroyer.SanityEclipse.Cast")
EmitSoundOnLocationWithCaster(self:GetCursorPosition(), "Hero_ObsidianDestroyer.SanityEclipse", self:GetCaster())
self.eclipse_cast_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_obsidian_destroyer/obsidian_destroyer_sanity_eclipse_area.vpcf", PATTACH_POINT, self:GetCaster())
ParticleManager:SetParticleControl(self.eclipse_cast_particle, 0, self:GetCursorPosition())
ParticleManager:SetParticleControl(self.eclipse_cast_particle, 1, Vector(self:GetSpecialValueFor("radius"), self:GetSpecialValueFor("radius"), 1))
ParticleManager:SetParticleControl(self.eclipse_cast_particle, 2, Vector(1, 1, self:GetSpecialValueFor("radius")))
ParticleManager:ReleaseParticleIndex(self.eclipse_cast_particle)
for _, enemy in pairs(FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetCursorPosition(), nil, self:GetSpecialValueFor("radius"), DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_INVULNERABLE + DOTA_UNIT_TARGET_FLAG_OUT_OF_WORLD, FIND_ANY_ORDER, false)) do
if ((not enemy:IsInvulnerable() and not enemy:IsOutOfGame()) or enemy:HasModifier("modifier_imba_outworld_devourer_astral_imprisonment_prison")) and enemy.GetMaxMana then
self.eclipse_damage_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_obsidian_destroyer/obsidian_destroyer_sanity_eclipse_damage.vpcf", PATTACH_ABSORIGIN_FOLLOW, enemy)
ParticleManager:ReleaseParticleIndex(self.eclipse_damage_particle)
if enemy:IsIllusion() and not Custom_bIsStrongIllusion(enemy) then
-- IMBAfication: Occam's Bazooka
enemy:Kill(self, self:GetCaster())
else
ApplyDamage({
victim = enemy,
damage = self:GetSpecialValueFor("base_damage") + ((self:GetCaster():GetMaxMana() - enemy:GetMaxMana()) * self:GetTalentSpecialValueFor("damage_multiplier")),
damage_type = self:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_BYPASSES_INVULNERABILITY,
attacker = self:GetCaster(),
ability = self
})
end
-- IMBAfication: Remnants of Sanity's Eclipse
if enemy:IsAlive() and enemy.GetMaxMana then
self.eclipse_mana_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_obsidian_destroyer/obsidian_destroyer_sanity_eclipse_mana_loss.vpcf", PATTACH_ABSORIGIN_FOLLOW, enemy)
ParticleManager:ReleaseParticleIndex(self.eclipse_mana_particle)
enemy:ReduceMana(enemy:GetMaxMana() * self:GetSpecialValueFor("max_mana_burn_pct") * 0.01, self)
end
end
end
end
-----------------------------------------------------------
-- MODIFIER_IMBA_OUTWORLD_DEVOURER_SANITY_ECLIPSE_CHARGE --
-----------------------------------------------------------
function modifier_imba_outworld_devourer_sanity_eclipse_charge:OnCreated(keys)
if keys and keys.charges then
self:SetStackCount(self:GetStackCount() + keys.charges)
end
self.stack_mana = self:GetAbility():GetSpecialValueFor("stack_mana")
if not IsServer() then return end
self:GetParent():CalculateStatBonus(true)
end
function modifier_imba_outworld_devourer_sanity_eclipse_charge:OnRefresh(keys)
self:OnCreated(keys)
end
function modifier_imba_outworld_devourer_sanity_eclipse_charge:DeclareFunctions()
return {MODIFIER_PROPERTY_MANA_BONUS}
end
function modifier_imba_outworld_devourer_sanity_eclipse_charge:GetModifierManaBonus()
return self:GetStackCount() * self.stack_mana
end
---------------------
-- TALENT HANDLERS --
---------------------
LinkLuaModifier("modifier_special_bonus_imba_outworld_devourer_sanity_eclipse_multiplier", "components/abilities/heroes/hero_outworld_devourer", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_special_bonus_imba_outworld_devourer_arcane_orb_damage", "components/abilities/heroes/hero_outworld_devourer", LUA_MODIFIER_MOTION_NONE)
modifier_special_bonus_imba_outworld_devourer_sanity_eclipse_multiplier = modifier_special_bonus_imba_outworld_devourer_sanity_eclipse_multiplier or class({})
modifier_special_bonus_imba_outworld_devourer_arcane_orb_damage = modifier_special_bonus_imba_outworld_devourer_arcane_orb_damage or class({})
function modifier_special_bonus_imba_outworld_devourer_sanity_eclipse_multiplier:IsHidden() return true end
function modifier_special_bonus_imba_outworld_devourer_sanity_eclipse_multiplier:IsPurgable() return false end
function modifier_special_bonus_imba_outworld_devourer_sanity_eclipse_multiplier:RemoveOnDeath() return false end
function modifier_special_bonus_imba_outworld_devourer_arcane_orb_damage:IsHidden() return true end
function modifier_special_bonus_imba_outworld_devourer_arcane_orb_damage:IsPurgable() return false end
function modifier_special_bonus_imba_outworld_devourer_arcane_orb_damage:RemoveOnDeath() return false end
| 0 | 0.977112 | 1 | 0.977112 | game-dev | MEDIA | 0.978899 | game-dev | 0.982982 | 1 | 0.982982 |
moonheart/mementomori-helper | 26,385 | MementoMori.Ortega/Network/MagicOnion/Client/OrtegaMagicOnionClient.cs | using Grpc.Net.Client;
using MementoMori.Ortega.Common.Enums;
using MementoMori.Ortega.Network.MagicOnion.Interface;
using MementoMori.Ortega.Share;
using MementoMori.Ortega.Share.Data.Chat;
using MementoMori.Ortega.Share.Data.LocalRaid;
using MementoMori.Ortega.Share.Enums;
using MementoMori.Ortega.Share.Extensions;
using MementoMori.Ortega.Share.MagicOnionShare.Interfaces.Receiver;
using MementoMori.Ortega.Share.MagicOnionShare.Interfaces.Sender;
using MementoMori.Ortega.Share.MagicOnionShare.Request;
using MementoMori.Ortega.Share.MagicOnionShare.Response;
namespace MementoMori.Ortega.Network.MagicOnion.Client
{
public class OrtegaMagicOnionClient : MagicOnionClient<IOrtegaSender, IOrtegaReceiver>, IOrtegaReceiver, IDisconnectReceiver
{
public ChatInfo GetLatestChatInfo(ChatType chatType)
{
// if (chatType <= ChatType.Guild)
// {
// Dictionary<ChatType, List<ChatInfo>> chatInfoList = this._chatInfoList;
// List<ChatInfo> list;
// List<ChatInfo> removedBlockPlayerChat = ChatUtil.GetRemovedBlockPlayerChat(list);
// if (!removedBlockPlayerChat.IsNullOrEmpty<ChatInfo>())
// {
// int size = removedBlockPlayerChat._size;
// return removedBlockPlayerChat[size];
// }
// }
// throw new NullReferenceException();
throw new NotImplementedException();
}
public List<ChatInfo> GetChatInfos(ChatType chatType)
{
// if (chatType > ChatType.Guild)
// {
// }
// Dictionary<ChatType, List<ChatInfo>> chatInfoList = this._chatInfoList;
// List<ChatInfo> list;
// return ChatUtil.GetRemovedBlockPlayerChat(list);
throw new NotImplementedException();
}
public List<long> GetAllWorldPlayerIds()
{
// List<long> list = new List();
// List<ChatInfo> removedBlockPlayerChat = ChatUtil.GetRemovedBlockPlayerChat(this._chatInfoList[(uint)1]);
// int num = 0;
// if (removedBlockPlayerChat[num].<SystemChatType>k__BackingField == SystemChatType.None)
// {
// long <PlayerId>k__BackingField = removedBlockPlayerChat[num].<PlayerId>k__BackingField;
// if (!list.Contains(<PlayerId>k__BackingField))
// {
// }
// }
// num++;
// return list;
throw new NotImplementedException();
}
public void ClearGuildChat()
{
// throw new AnalysisFailedException("CPP2IL failed to recover any usable IL for this method.");
}
public void ClearSvsChat()
{
// throw new AnalysisFailedException("CPP2IL failed to recover any usable IL for this method.");
}
public void ClearWorldChat()
{
// throw new AnalysisFailedException("CPP2IL failed to recover any usable IL for this method.");
}
public void SendChatMessageAsync(ChatType chatType, string message)
{
// base.TryReconnect();
// int num = 0;
// string text = string.Format("SendChatMessageAsync : {0} : {1}", "SendChatMessageAsync : {0} : {1}", message);
// SendMessageRequest sendMessageRequest = new SendMessageRequest();
// sendMessageRequest.<ChatType>k__BackingField = chatType;
// sendMessageRequest.<Message>k__BackingField = message;
// int num2 = 0;
// if (num2 < num)
// {
// num2 += num2;
// num2++;
// }
}
public void SendChatJoinGuildAsync()
{
// base.TryReconnect();
}
void IOrtegaReceiver.OnNoticePrivateMessage(OnNoticePrivateMessageResponse response)
{
// UserDataManager instance = SingletonMonoBehaviour.Instance;
// long <PlayerId>k__BackingField = response.<PlayerId>k__BackingField;
// bool flag = instance.IsBlockedPlayer(<PlayerId>k__BackingField);
// long <PlayerId>k__BackingField2 = response.<PlayerId>k__BackingField;
// if (!flag)
// {
// string text = string.Format("OnNoticePrivateMessage : PlayerId -> {0}", flag);
// if (this._chatReceiver != 0)
// {
// int num = 0;
// uint num2;
// if (num < (int)num2)
// {
// num += num;
// num++;
// }
// }
// return;
// }
// string text2 = string.Format("OnNoticePrivateMessage Blocked : PlayerId -> {0}", flag);
}
void IOrtegaReceiver.OnRemovedFromGuild()
{
// if (this._chatReceiver != 0)
// {
// }
}
void IOrtegaReceiver.OnReceiveGuildChatLog(OnReceiveGuildChatLogResponse response)
{
// throw new AnalysisFailedException("CPP2IL failed to recover any usable IL for this method.");
}
void IOrtegaReceiver.OnReceiveSvSChatLog(OnReceiveSvSChatLogResponse response)
{
// throw new AnalysisFailedException("CPP2IL failed to recover any usable IL for this method.");
}
void IOrtegaReceiver.OnReceiveWorldChatLog(OnReceiveWorldChatLogResponse response)
{
// throw new AnalysisFailedException("CPP2IL failed to recover any usable IL for this method.");
}
void IOrtegaReceiver.OnReceiveMessage(OnReceiveMessageResponse response)
{
// ChatInfo <ChatInfo>k__BackingField = response.<ChatInfo>k__BackingField;
// ChatType <ChatType>k__BackingField = <ChatInfo>k__BackingField.<ChatType>k__BackingField;
// long <PlayerId>k__BackingField = <ChatInfo>k__BackingField.<PlayerId>k__BackingField;
// string <Message>k__BackingField = <ChatInfo>k__BackingField.<Message>k__BackingField;
// int num = 0;
// string text = string.Format("OnReceiveMessage -> {0} : {1} : {2}", <ChatType>k__BackingField, <ChatType>k__BackingField, <Message>k__BackingField);
// if (<ChatInfo>k__BackingField.<ChatType>k__BackingField <= ChatType.Guild)
// {
// Dictionary<ChatType, List<ChatInfo>> chatInfoList = this._chatInfoList;
// ChatType <ChatType>k__BackingField2 = <ChatInfo>k__BackingField.<ChatType>k__BackingField;
// chatInfoList[<ChatType>k__BackingField2].Add(<ChatInfo>k__BackingField);
// }
// uint num2;
// if (this._chatReceiver != 0 && num < (int)num2)
// {
// num += num;
// num++;
// }
}
public OrtegaMagicOnionClient(GrpcChannel channel, long playerId, string authToken, IMagicOnionLocalRaidNotificaiton localRaidNotificaiton)
: base(channel, playerId, authToken)
{
_localRaidNotificaiton = localRaidNotificaiton;
_currentLocalRaidPartyInfo = new LocalRaidPartyInfo();
_chatInfoList = new Dictionary<ChatType, List<ChatInfo>>()
{
[ChatType.SvS] = new List<ChatInfo>(),
[ChatType.World] = new List<ChatInfo>(),
[ChatType.Guild] = new List<ChatInfo>()
};
AttachInternalReceiver(this, this);
}
public void SetupLocalRaid(IMagicOnionLocalRaidReceiver localRaidReceiver, IMagicOnionErrorReceiver errorReceiver)
{
_localRaidReceiver = localRaidReceiver;
_errorReceiver = errorReceiver;
}
public void SetupChat(IMagicOnionChatReceiver receiver, IMagicOnionAuthenticateReceiver authenticateReceiver, IMagicOnionErrorReceiver errorReceiver)
{
_chatReceiver = receiver;
_authenticateReceiver = authenticateReceiver;
_errorReceiver = errorReceiver;
}
public void SetupGvg(IMagicOnionGvgReceiver receiver, IMagicOnionErrorReceiver errorReceiver, BattleType battleType)
{
if (battleType == BattleType.GuildBattle)
{
_gvgLocalReceiver = receiver;
}
else
{
_gvgGlobalReceiver = receiver;
}
_errorReceiver = errorReceiver;
}
public void ClearGvgReceiver()
{
_gvgLocalReceiver = null;
_gvgGlobalReceiver = null;
}
public void ClearLocalRaidReceiver()
{
_localRaidReceiver = null;
}
public void ClearErrorReceiver()
{
_errorReceiver = null;
}
public void ClearLocalRaidPartyInfo()
{
_currentLocalRaidPartyInfo = null;
}
public long GetPlayerId()
{
return _playerId;
}
public void SendKeepAliveAsync()
{
TryReconnect();
if (_state == HubClientState.Ready)
{
_sender.KeepAliveAsync();
}
}
protected override async Task Authenticate()
{
if (_sender != null)
{
await base.Authenticate();
AuthenticateRequest authenticateRequest = new AuthenticateRequest()
{
PlayerId = _playerId,
AuthToken = _authToken,
DeviceType = DeviceType.Android
};
await _sender.AuthenticateAsync(authenticateRequest);
}
}
void IDisconnectReceiver.OnDisconnect()
{
_currentLocalRaidPartyInfo = null;
}
void IOrtegaReceiver.OnAuthenticateSuccess()
{
SucceededAuthentication();
_authenticateReceiver?.OnAuthenticateSuccess();
_gvgLocalReceiver?.OnAuthenticateSuccess();
_gvgGlobalReceiver?.OnAuthenticateSuccess();
}
void IOrtegaReceiver.OnError(ErrorCode errorCode)
{
if (errorCode > ErrorCode.MagicOnionLocalRaidLeaveRoomNotExistRoom)
{
if (errorCode == ErrorCode.MagicOnionLocalRaidExpiredLocalRaidQuest)
{
_currentLocalRaidPartyInfo = null;
}
}
if (errorCode == ErrorCode.MagicOnionLocalRaidDisbandRoomFailed)
{
_currentLocalRaidPartyInfo = null;
}
_errorReceiver?.OnError(errorCode);
_localRaidNotificaiton?.OnError(errorCode);
}
public void SendGvgAddCastleParty(BattleType battleType, long castleId, List<long> characterIds, int memberCount)
{
TryReconnect();
var addCastlePartyRequest = new AddCastlePartyRequest()
{
CastleId = castleId,
CharacterIds = characterIds,
MemberCount = memberCount
};
if (battleType == BattleType.GuildBattle)
{
_sender.LocalGvgAddCastleParty(addCastlePartyRequest);
}
else
{
_sender.GlobalGvgAddCastleParty(addCastlePartyRequest);
}
}
public void SendGvgOrderCastleParty(BattleType battleType, int index, long firstCharacterId, long ownerPlayerId, bool isUp)
{
TryReconnect();
var orderCastlePartyRequest = new OrderCastlePartyRequest()
{
Index = index,
FirstCharacterId = firstCharacterId,
OwnerPlayerId = ownerPlayerId,
IsUp = isUp
};
if (battleType == BattleType.GuildBattle)
{
_sender.LocalGvgOrderCastleParty(orderCastlePartyRequest);
}
else
{
_sender.GlobalGvgOrderCastleParty(orderCastlePartyRequest);
}
}
public void SendGvgOpenBattleDialog(BattleType battleType, long castleId)
{
TryReconnect();
var openBattleDialogRequest = new OpenBattleDialogRequest() {CastleId = castleId};
if (battleType == BattleType.GuildBattle)
{
_sender.LocalGvgOpenBattleDialog(openBattleDialogRequest);
}
else
{
_sender.GlobalGvgOpenBattleDialog(openBattleDialogRequest);
}
}
public void SendGvgOpenPartyDeployDialog(BattleType battleType, long castleId)
{
TryReconnect();
var openPartyDeployDialogRequest = new OpenPartyDeployDialogRequest() {CastleId = castleId};
if (battleType == BattleType.GuildBattle)
{
_sender.LocalGvgOpenPartyDeployDialog(openPartyDeployDialogRequest);
}
else
{
_sender.GlobalGvgOpenPartyDeployDialog(openPartyDeployDialogRequest);
}
}
public void SendGvgCloseCastleDialog(BattleType battleType, GvgDialogType gvgDialogType)
{
TryReconnect();
var closeDialogRequest = new CloseDialogRequest() {DialogType = gvgDialogType};
if (battleType == BattleType.GuildBattle)
{
_sender.LocalGvgCloseCastleDialog(closeDialogRequest);
}
else
{
_sender.GlobalGvgCloseCastleDialog(closeDialogRequest);
}
}
public void SendGvgCastleDeclaration(BattleType battleType, long castleId)
{
TryReconnect();
var castleDeclarationRequest = new CastleDeclarationRequest() {CastleId = castleId};
if (battleType == BattleType.GuildBattle)
{
_sender.LocalGvgCastleDeclaration(castleDeclarationRequest);
}
else
{
_sender.GlobalGvgCastleDeclaration(castleDeclarationRequest);
}
}
public void SendGvgCastleDeclarationCounter(BattleType battleType, long castleId)
{
TryReconnect();
var castleDeclarationCounterRequest = new CastleDeclarationCounterRequest() {CastleId = castleId};
if (battleType == BattleType.GuildBattle)
{
_sender.LocalGvgCastleDeclarationCounter(castleDeclarationCounterRequest);
}
else
{
_sender.GlobalGvgCastleDeclarationCounter(castleDeclarationCounterRequest);
}
}
public void SendGvgOpenMap(BattleType battleType, int matchingNumber)
{
TryReconnect();
if (battleType == BattleType.GuildBattle)
{
_sender.LocalGvgOpenMap();
}
else
{
_sender.GlobalGvgOpenMap(new OpenMapRequest() {MatchingNumber = matchingNumber});
}
}
public void SendGvgCloseMap(BattleType battleType)
{
TryReconnect();
if (battleType == BattleType.GuildBattle)
{
_sender.LocalGvgCloseMap();
}
else
{
_sender.GlobalGvgCloseMap();
}
}
void IOrtegaReceiver.OnGlobalGvgEndCastleBattle(OnEndCastleBattleResponse response)
{
// if (this._gvgGlobalReceiver != 0)
// {
// }
}
void IOrtegaReceiver.OnGlobalGvgOpenBattleDialog(OnOpenBattleDialogResponse response)
{
// if (this._gvgGlobalReceiver != 0)
// {
// }
}
void IOrtegaReceiver.OnGlobalGvgUpdateCastleParty(OnUpdateCastlePartyResponse response)
{
// if (this._gvgGlobalReceiver != 0)
// {
// }
}
void IOrtegaReceiver.OnGlobalGvgUpdateMap(OnUpdateMapResponse response)
{
// if (this._gvgGlobalReceiver != 0)
// {
// }
}
void IOrtegaReceiver.OnGlobalGvgUpdateDeployCharacter(OnUpdateDeployCharacterResponse response)
{
// if (this._gvgGlobalReceiver != 0)
// {
// }
}
void IOrtegaReceiver.OnGlobalGvgAddOnlyReceiverParty(OnAddOnlyReceiverPartyResponse response)
{
// if (this._gvgGlobalReceiver != 0)
// {
// }
}
void IOrtegaReceiver.OnLocalGvgEndCastleBattle(OnEndCastleBattleResponse response)
{
_gvgLocalReceiver?.OnEndCastleBattle(response);
}
void IOrtegaReceiver.OnLocalGvgOpenBattleDialog(OnOpenBattleDialogResponse response)
{
_gvgLocalReceiver?.OnOpenBattleDialog(response);
}
void IOrtegaReceiver.OnLocalGvgUpdateCastleParty(OnUpdateCastlePartyResponse response)
{
_gvgLocalReceiver?.OnUpdateCastleParty(response);
}
void IOrtegaReceiver.OnLocalGvgUpdateMap(OnUpdateMapResponse response)
{
_gvgLocalReceiver?.OnUpdateMap(response);
}
void IOrtegaReceiver.OnLocalGvgUpdateDeployCharacter(OnUpdateDeployCharacterResponse response)
{
_gvgLocalReceiver?.OnUpdateDeployCharacter(response);
}
void IOrtegaReceiver.OnLocalGvgAddOnlyReceiverParty(OnAddOnlyReceiverPartyResponse response)
{
_gvgLocalReceiver?.OnAddOnlyReceiverParty(response);
}
public LocalRaidPartyInfo GetCurrentLocalRaidPartyInfo()
{
return _currentLocalRaidPartyInfo;
}
public bool IsLocalRaidMasterInRoom()
{
return _currentLocalRaidPartyInfo != null && _currentLocalRaidPartyInfo.LeaderPlayerId == _playerId;
}
public bool IsLocalRaidInRoom()
{
return _currentLocalRaidPartyInfo != null;
}
public bool IsLocalRaidInvitedInRoom()
{
if (_currentLocalRaidPartyInfo == null) return false;
foreach (var info in _currentLocalRaidPartyInfo.LocalRaidBattleLogPlayerInfoList)
{
return info.IsInvite && info.PlayerInfo.PlayerId == _playerId;
}
return false;
}
public bool IsLocalRaidReadyInRoom()
{
if (_currentLocalRaidPartyInfo == null) return false;
if (_currentLocalRaidPartyInfo.LeaderPlayerId == _playerId) return true;
foreach (var info in _currentLocalRaidPartyInfo.LocalRaidBattleLogPlayerInfoList)
{
return info.IsReady && info.PlayerInfo.PlayerId == _playerId;
}
return false;
}
public void SendLocalRaidGetRoomList(long questId)
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.GetRoomListAsync(new GetRoomListRequest()
{
QuestId = questId
});
}
}
public void SendLocalRaidDisbandRoom()
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.DisbandRoomAsync();
}
}
public void SendLocalRaidInvite(long playerId)
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.InviteAsync(new InviteRequest()
{
FriendPlayerId = playerId
});
}
}
public void SendLocalRaidJoinRandomRoom(long questId)
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.JoinRandomRoomAsync(new JoinRandomRoomRequest()
{
QuestId = questId
});
}
}
public void SendLocalRaidJoinRoom(string roomId, int password)
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.JoinRoomAsync(new JoinRoomRequest()
{
RoomId = roomId,
Password = password
});
}
}
public void SendLocalRaidJoinFriendRoom(string roomId)
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.JoinFriendRoomAsync(new JoinFriendRoomRequest()
{
RoomId = roomId
});
}
}
public void SendLocalRaidLeaveRoom()
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.LeaveRoomAsync();
}
}
public void SendLocalRaidOpenRoom(LocalRaidRoomConditionsType conditionType, long questId, long requiredBattlePower, int password)
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.OpenRoomAsync(new OpenRoomRequest()
{
ConditionsType = conditionType,
QuestId = questId,
RequiredBattlePower = requiredBattlePower,
Password = password,
IsAutoStart = true
});
}
}
public void SendLocalRaidStartBattle()
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.StartBattleAsync();
}
}
public void SendLocalRaidUpdatePartyCount()
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.UpdatePartyCountAsync();
}
}
public void SendLocalRaidRefuse(long targetPlayerId)
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.RefuseAsync(new RefuseRequest()
{
TargetPlayerId = targetPlayerId
});
}
}
public void SendLocalRaidReady(bool isReady)
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.ReadyAsync(new ReadyRequest()
{
IsReady = isReady
});
}
}
public void SendLocalRaidUpdateRoomCondition(LocalRaidRoomConditionsType conditionType, long requiredBattlePower, int password)
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.UpdateRoomConditionAsync(new UpdateRoomConditionRequest()
{
ConditionsType = conditionType,
RequiredBattlePower = requiredBattlePower,
Password = password
});
}
}
public void SendLocalRaidUpdateBattlePower()
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.UpdateBattlePowerAsync(new UpdateBattlePowerRequest());
}
}
public void SendRoomClear()
{
TryReconnect();
if (_state == HubClientState.Ready && _sender != null)
{
_sender.RoomClearAsync();
}
}
void IOrtegaReceiver.OnDisbandRoom()
{
_localRaidReceiver?.OnDisbandRoom();
_currentLocalRaidPartyInfo = null;
}
void IOrtegaReceiver.OnGetRoomList(OnGetRoomListResponse response)
{
_localRaidReceiver?.OnGetRoomList(response);
}
void IOrtegaReceiver.OnInvite(OnInviteResponse response)
{
_localRaidReceiver?.OnInvite(response);
}
void IOrtegaReceiver.OnJoinRoom(OnJoinRoomResponse response)
{
_currentLocalRaidPartyInfo = response.LocalRaidPartyInfo;
_localRaidReceiver?.OnJoinRoom(response);
_localRaidNotificaiton?.OnJoinRoom();
}
void IOrtegaReceiver.OnLeaveRoom()
{
_localRaidReceiver?.OnLeaveRoom();
_currentLocalRaidPartyInfo = null;
}
void IOrtegaReceiver.OnLockRoom()
{
_localRaidReceiver?.OnLockRoom();
}
void IOrtegaReceiver.OnRefuse()
{
_localRaidReceiver?.OnRefuse();
_localRaidNotificaiton?.OnRefused();
_currentLocalRaidPartyInfo = null;
}
void IOrtegaReceiver.OnStartBattle()
{
_localRaidReceiver?.OnStartBattle();
_localRaidNotificaiton?.OnStartBattle();
_currentLocalRaidPartyInfo = null;
}
void IOrtegaReceiver.OnUpdatePartyCount(OnUpdatePartyCountResponse response)
{
_localRaidReceiver?.OnUpdatePartyCount(response);
}
void IOrtegaReceiver.OnUpdateRoom(OnUpdateRoomResponse response)
{
_localRaidReceiver?.OnUpdateRoom(response);
}
private IMagicOnionChatReceiver _chatReceiver;
private IMagicOnionGvgReceiver _gvgLocalReceiver;
private IMagicOnionGvgReceiver _gvgGlobalReceiver;
private IMagicOnionAuthenticateReceiver _authenticateReceiver;
private IMagicOnionErrorReceiver _errorReceiver;
private IMagicOnionLocalRaidNotificaiton _localRaidNotificaiton;
private IMagicOnionLocalRaidReceiver _localRaidReceiver;
private Dictionary<ChatType, List<ChatInfo>> _chatInfoList;
private LocalRaidPartyInfo _currentLocalRaidPartyInfo;
}
} | 0 | 0.861266 | 1 | 0.861266 | game-dev | MEDIA | 0.274366 | game-dev | 0.978988 | 1 | 0.978988 |
SirPlease/L4D2-Competitive-Rework | 4,922 | addons/sourcemod/scripting/l4d2_nospitterduringtank.sp | /*
2.0 - Griffin
More or less cribbed tankdamageannounce's tank tracking, which itself is
heavily based off of ZACK/Rotoblin. Credit to Mr Zero.
This is in response to the following L4D Nation thread:
http://www.l4dnation.com/confogl-and-other-configs/low-hanging-fruit/60/
Specifically:
> If the bot tank is kicked via sourcemod, you won't get any more
> spitters for the rest of the map.
- fig newtons
and
> If the survivors wipe and the Tank is still in play of the Infected
> (and controlled by a player) and the Tank player disconnects/types
> quit into console as the game begins to transition to the load screen
> to transition the players to the next map, the no-spitter plugin stays
> loaded in.
- 3yebex
*/
#pragma semicolon 1
#include <sourcemod>
new TEAM_INFECTED = 3;
new g_iZombieClass_Tank = 8;
new g_iSpitterLimit;
new g_iTankClient;
new bool:g_bIsTankInPlay;
new Handle:g_hSpitterLimit;
public Plugin:myinfo =
{
name = "No Spitter During Tank",
author = "Don, epilimic, Griffin",
description = "Prevents the director from giving the infected team a spitter while the tank is alive",
version = "2.0",
url = "https://bitbucket.org/DonSanchez/random-sourcemod-stuff"
};
public APLRes:AskPluginLoad2(Handle:myself, bool:late, String:error[], err_max)
{
decl String:sGame[12];
GetGameFolderName(sGame, sizeof(sGame));
if (StrEqual(sGame, "left4dead2")) // Only load the plugin if the server is running Left 4 Dead 2.
{
return APLRes_Success;
}
else
{
strcopy(error, err_max, "Plugin only supports L4D2");
return APLRes_Failure;
}
}
public OnPluginStart()
{
HookEvent("tank_spawn", Event_TankSpawn);
HookEvent("player_death", Event_PlayerKilled);
HookEvent("round_start", Event_RoundStart);
HookEvent("round_end", Event_RoundEnd);
g_hSpitterLimit = FindConVar("z_versus_spitter_limit");
HookConVarChange(g_hSpitterLimit, Cvar_SpitterLimit);
g_iSpitterLimit = GetConVarInt(g_hSpitterLimit);
}
void Cvar_SpitterLimit(Handle:convar, const String:oldValue[], const String:newValue[])
{
if (g_bIsTankInPlay || StringToInt(oldValue) == 0) return;
g_iSpitterLimit = StringToInt(newValue);
}
public OnMapStart()
{
// In cases where a tank spawns and map is changed manually, bypassing round end
// OR apparently there's a race condition where tank leaves near round_end; this should
// protect from those scenarios.
if (g_iSpitterLimit > 0 && GetConVarInt(g_hSpitterLimit) == 0)
{
SetConVarInt(g_hSpitterLimit, g_iSpitterLimit);
}
}
public OnClientDisconnect_Post(client)
{
if (!g_bIsTankInPlay || client != g_iTankClient) return;
// Use a delayed timer due to bugs where the tank passes to another player
CreateTimer(0.5, Timer_CheckTank, client);
}
void Event_PlayerKilled(Handle:event, const String:name[], bool:dontBroadcast)
{
if (!g_bIsTankInPlay) return;
new victim = GetClientOfUserId(GetEventInt(event, "userid"));
if (victim != g_iTankClient) return;
// Use a delayed timer due to a bug where the tank passes to another player
// (Does this happen in L4D2?)
CreateTimer(0.5, Timer_CheckTank, victim);
}
void Event_TankSpawn(Handle:event, const String:name[], bool:dontBroadcast)
{
new client = GetClientOfUserId(GetEventInt(event, "userid"));
g_iTankClient = client;
if (g_bIsTankInPlay) return; // Tank passed
g_bIsTankInPlay = true;
SetConVarInt(g_hSpitterLimit, 0);
}
void Event_RoundStart(Handle:event, const String:name[], bool:dontBroadcast)
{
g_bIsTankInPlay = false;
g_iTankClient = 0;
if (g_iSpitterLimit > 0 && GetConVarInt(g_hSpitterLimit) == 0)
{
SetConVarInt(g_hSpitterLimit, g_iSpitterLimit);
}
}
void Event_RoundEnd(Handle:event, const String:name[], bool:dontBroadcast)
{
// A bit redundant to do it on both start/end, but there are cases where those events are bypassed
// specifically by admin commands
g_bIsTankInPlay = false;
if (g_iSpitterLimit > 0 && GetConVarInt(g_hSpitterLimit) == 0)
{
SetConVarInt(g_hSpitterLimit, g_iSpitterLimit);
}
}
Action:Timer_CheckTank(Handle:timer, any:oldtankclient)
{
// We already saw tank pass via another event firing
if (g_iTankClient != oldtankclient) return;
// Check ourselves for a tank pass
new tankclient = FindTankClient();
if (tankclient && tankclient != oldtankclient)
{
g_iTankClient = tankclient;
return;
}
// Can't find tank, it's gone
g_bIsTankInPlay = false;
if (g_iSpitterLimit > 0 && GetConVarInt(g_hSpitterLimit) == 0)
{
SetConVarInt(g_hSpitterLimit, g_iSpitterLimit);
}
}
FindTankClient()
{
for (new client = 1; client <= MaxClients; client++)
{
if (!IsClientInGame(client) ||
GetClientTeam(client) != TEAM_INFECTED ||
!IsPlayerAlive(client) ||
GetEntProp(client, Prop_Send, "m_zombieClass") != g_iZombieClass_Tank)
continue;
return client;
}
return 0;
}
public void OnPluginEnd()
{
if (g_iSpitterLimit > 0 && GetConVarInt(g_hSpitterLimit) == 0)
SetConVarInt(g_hSpitterLimit, g_iSpitterLimit);
} | 0 | 0.983369 | 1 | 0.983369 | game-dev | MEDIA | 0.595695 | game-dev,networking | 0.983771 | 1 | 0.983771 |
unmojang/FjordLauncher | 1,873 | launcher/minecraft/MojangDownloadInfo.h | #pragma once
#include <QMap>
#include <QString>
#include <memory>
struct MojangDownloadInfo {
// types
using Ptr = std::shared_ptr<MojangDownloadInfo>;
// data
/// Local filesystem path. WARNING: not used, only here so we can pass through mojang files unmolested!
QString path;
/// absolute URL of this file
QString url;
/// sha-1 checksum of the file
QString sha1;
/// size of the file in bytes
int size;
};
struct MojangLibraryDownloadInfo {
MojangLibraryDownloadInfo(MojangDownloadInfo::Ptr artifact_) : artifact(artifact_) {}
MojangLibraryDownloadInfo() {}
// types
using Ptr = std::shared_ptr<MojangLibraryDownloadInfo>;
// methods
MojangDownloadInfo* getDownloadInfo(QString classifier)
{
if (classifier.isNull()) {
return artifact.get();
}
return classifiers[classifier].get();
}
// data
MojangDownloadInfo::Ptr artifact;
QMap<QString, MojangDownloadInfo::Ptr> classifiers;
};
struct MojangAssetIndexInfo : public MojangDownloadInfo {
// types
using Ptr = std::shared_ptr<MojangAssetIndexInfo>;
// methods
MojangAssetIndexInfo() {}
MojangAssetIndexInfo(QString id_)
{
this->id = id_;
// HACK: ignore assets from other version files than Minecraft
// workaround for stupid assets issue caused by amazon:
// https://www.theregister.co.uk/2017/02/28/aws_is_awol_as_s3_goes_haywire/
if (id_ == "legacy") {
url = "https://piston-meta.mojang.com/mc/assets/legacy/c0fd82e8ce9fbc93119e40d96d5a4e62cfa3f729/legacy.json";
}
// HACK
else {
url = "https://s3.amazonaws.com/Minecraft.Download/indexes/" + id_ + ".json";
}
known = false;
}
// data
int totalSize;
QString id;
bool known = true;
};
| 0 | 0.918583 | 1 | 0.918583 | game-dev | MEDIA | 0.444881 | game-dev | 0.689044 | 1 | 0.689044 |
CleanroomMC/GroovyScript | 1,036 | src/main/java/com/cleanroommc/groovyscript/compat/vanilla/command/infoparser/InfoParserBlockMaterial.java | package com.cleanroommc.groovyscript.compat.vanilla.command.infoparser;
import com.cleanroommc.groovyscript.api.infocommand.InfoParserPackage;
import com.cleanroommc.groovyscript.helper.ingredient.GroovyScriptCodeConverter;
import net.minecraft.block.material.Material;
import org.jetbrains.annotations.NotNull;
public class InfoParserBlockMaterial extends GenericInfoParser<Material> {
public static final InfoParserBlockMaterial instance = new InfoParserBlockMaterial();
@Override
public String id() {
return "blockmaterial";
}
@Override
public String name() {
return "Block Material";
}
@Override
public String text(@NotNull Material entry, boolean colored, boolean prettyNbt) {
return GroovyScriptCodeConverter.asGroovyCode(entry, colored);
}
@Override
public void parse(InfoParserPackage info) {
if (info.getBlockState() == null) return;
instance.add(info.getMessages(), info.getBlockState().getMaterial(), info.isPrettyNbt());
}
}
| 0 | 0.501041 | 1 | 0.501041 | game-dev | MEDIA | 0.711871 | game-dev | 0.635516 | 1 | 0.635516 |
CodingWithLewis/ReceiptPrinterAgent | 3,281 | src/task_card_generator/arcade_client.py | """Arcade API client for automated task generation and printing."""
import os
from dotenv import load_dotenv
from arcadepy import Arcade
from .ai_client import parse_ai_response
# Load environment variables from .env file
load_dotenv()
class ArcadeTaskGenerator:
"""Handles Arcade API integration for task generation."""
def __init__(self, api_key=None, user_id=None):
"""Initialize Arcade client."""
self.api_key = api_key or os.getenv("ARCADE_API_KEY")
self.user_id = user_id or os.getenv("ARCADE_USER_ID", "user@example.com")
self.client = Arcade(api_key=self.api_key) if self.api_key else None
def get_task_from_arcade(self, tool_name, input_data):
"""Get task response from Arcade tool and format for printing."""
if not self.client:
return None, "Error: ARCADE_API_KEY not configured"
try:
# Execute the Arcade tool
response = self.client.tools.execute(
tool_name=tool_name,
input=input_data,
user_id=self.user_id,
)
# Format the response for task card generation
task_data = self._format_arcade_response(response, tool_name)
return task_data, None
except Exception as e:
return None, f"Error executing Arcade tool: {str(e)}"
def authorize_tool(self, tool_name):
"""Authorize a tool that requires authentication."""
if not self.client:
return None, "Error: ARCADE_API_KEY not configured"
try:
auth_response = self.client.tools.authorize(
tool_name=tool_name,
user_id=self.user_id,
)
return auth_response, None
except Exception as e:
return None, f"Error authorizing tool: {str(e)}"
def _format_arcade_response(self, response, tool_name):
"""Format Arcade response into task card data."""
# Extract the actual value from the response
output_value = response.output.value if hasattr(response.output, 'value') else str(response.output)
# Create task data structure
task_data = {
"title": f"{tool_name} Result",
"priority": "MEDIUM",
"content": output_value,
"tool_name": tool_name
}
# Try to determine priority based on tool name or content
if "urgent" in tool_name.lower() or "critical" in tool_name.lower():
task_data["priority"] = "HIGH"
elif "info" in tool_name.lower() or "search" in tool_name.lower():
task_data["priority"] = "LOW"
return task_data
def get_task_from_arcade_tool(tool_name, input_data, api_key=None, user_id=None):
"""Convenience function to get task from Arcade tool."""
generator = ArcadeTaskGenerator(api_key=api_key, user_id=user_id)
return generator.get_task_from_arcade(tool_name, input_data)
def authorize_arcade_tool(tool_name, api_key=None, user_id=None):
"""Convenience function to authorize an Arcade tool."""
generator = ArcadeTaskGenerator(api_key=api_key, user_id=user_id)
return generator.authorize_tool(tool_name) | 0 | 0.853065 | 1 | 0.853065 | game-dev | MEDIA | 0.509652 | game-dev | 0.893515 | 1 | 0.893515 |
Dark-Basic-Software-Limited/GameGuruRepo | 3,086 | GameGuru Core/SDK/BULLET/bullet-2.81-rev2613/src/BulletCollision/CollisionShapes/btTriangleMesh.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_TRIANGLE_MESH_H
#define BT_TRIANGLE_MESH_H
#include "btTriangleIndexVertexArray.h"
#include "LinearMath/btVector3.h"
#include "LinearMath/btAlignedObjectArray.h"
///The btTriangleMesh class is a convenience class derived from btTriangleIndexVertexArray, that provides storage for a concave triangle mesh. It can be used as data for the btBvhTriangleMeshShape.
///It allows either 32bit or 16bit indices, and 4 (x-y-z-w) or 3 (x-y-z) component vertices.
///If you want to share triangle/index data between graphics mesh and collision mesh (btBvhTriangleMeshShape), you can directly use btTriangleIndexVertexArray or derive your own class from btStridingMeshInterface.
///Performance of btTriangleMesh and btTriangleIndexVertexArray used in a btBvhTriangleMeshShape is the same.
class btTriangleMesh : public btTriangleIndexVertexArray
{
btAlignedObjectArray<btVector3> m_4componentVertices;
btAlignedObjectArray<float> m_3componentVertices;
btAlignedObjectArray<unsigned int> m_32bitIndices;
btAlignedObjectArray<unsigned short int> m_16bitIndices;
bool m_use32bitIndices;
bool m_use4componentVertices;
public:
btScalar m_weldingThreshold;
btTriangleMesh (bool use32bitIndices=true,bool use4componentVertices=true);
bool getUse32bitIndices() const
{
return m_use32bitIndices;
}
bool getUse4componentVertices() const
{
return m_use4componentVertices;
}
///By default addTriangle won't search for duplicate vertices, because the search is very slow for large triangle meshes.
///In general it is better to directly use btTriangleIndexVertexArray instead.
void addTriangle(const btVector3& vertex0,const btVector3& vertex1,const btVector3& vertex2, bool removeDuplicateVertices=false);
int getNumTriangles() const;
virtual void preallocateVertices(int numverts);
virtual void preallocateIndices(int numindices);
///findOrAddVertex is an internal method, use addTriangle instead
int findOrAddVertex(const btVector3& vertex, bool removeDuplicateVertices);
///addIndex is an internal method, use addTriangle instead
void addIndex(int index);
};
#endif //BT_TRIANGLE_MESH_H
| 0 | 0.889722 | 1 | 0.889722 | game-dev | MEDIA | 0.971285 | game-dev | 0.511145 | 1 | 0.511145 |
schteppe/cannon.js | 30,790 | src/world/World.js | /* global performance */
module.exports = World;
var Shape = require('../shapes/Shape');
var Vec3 = require('../math/Vec3');
var Quaternion = require('../math/Quaternion');
var GSSolver = require('../solver/GSSolver');
var ContactEquation = require('../equations/ContactEquation');
var FrictionEquation = require('../equations/FrictionEquation');
var Narrowphase = require('./Narrowphase');
var EventTarget = require('../utils/EventTarget');
var ArrayCollisionMatrix = require('../collision/ArrayCollisionMatrix');
var OverlapKeeper = require('../collision/OverlapKeeper');
var Material = require('../material/Material');
var ContactMaterial = require('../material/ContactMaterial');
var Body = require('../objects/Body');
var TupleDictionary = require('../utils/TupleDictionary');
var RaycastResult = require('../collision/RaycastResult');
var AABB = require('../collision/AABB');
var Ray = require('../collision/Ray');
var NaiveBroadphase = require('../collision/NaiveBroadphase');
/**
* The physics world
* @class World
* @constructor
* @extends EventTarget
* @param {object} [options]
* @param {Vec3} [options.gravity]
* @param {boolean} [options.allowSleep]
* @param {Broadphase} [options.broadphase]
* @param {Solver} [options.solver]
* @param {boolean} [options.quatNormalizeFast]
* @param {number} [options.quatNormalizeSkip]
*/
function World(options){
options = options || {};
EventTarget.apply(this);
/**
* Currently / last used timestep. Is set to -1 if not available. This value is updated before each internal step, which means that it is "fresh" inside event callbacks.
* @property {Number} dt
*/
this.dt = -1;
/**
* Makes bodies go to sleep when they've been inactive
* @property allowSleep
* @type {Boolean}
* @default false
*/
this.allowSleep = !!options.allowSleep;
/**
* All the current contacts (instances of ContactEquation) in the world.
* @property contacts
* @type {Array}
*/
this.contacts = [];
this.frictionEquations = [];
/**
* How often to normalize quaternions. Set to 0 for every step, 1 for every second etc.. A larger value increases performance. If bodies tend to explode, set to a smaller value (zero to be sure nothing can go wrong).
* @property quatNormalizeSkip
* @type {Number}
* @default 0
*/
this.quatNormalizeSkip = options.quatNormalizeSkip !== undefined ? options.quatNormalizeSkip : 0;
/**
* Set to true to use fast quaternion normalization. It is often enough accurate to use. If bodies tend to explode, set to false.
* @property quatNormalizeFast
* @type {Boolean}
* @see Quaternion.normalizeFast
* @see Quaternion.normalize
* @default false
*/
this.quatNormalizeFast = options.quatNormalizeFast !== undefined ? options.quatNormalizeFast : false;
/**
* The wall-clock time since simulation start
* @property time
* @type {Number}
*/
this.time = 0.0;
/**
* Number of timesteps taken since start
* @property stepnumber
* @type {Number}
*/
this.stepnumber = 0;
/// Default and last timestep sizes
this.default_dt = 1/60;
this.nextId = 0;
/**
* @property gravity
* @type {Vec3}
*/
this.gravity = new Vec3();
if(options.gravity){
this.gravity.copy(options.gravity);
}
/**
* The broadphase algorithm to use. Default is NaiveBroadphase
* @property broadphase
* @type {Broadphase}
*/
this.broadphase = options.broadphase !== undefined ? options.broadphase : new NaiveBroadphase();
/**
* @property bodies
* @type {Array}
*/
this.bodies = [];
/**
* The solver algorithm to use. Default is GSSolver
* @property solver
* @type {Solver}
*/
this.solver = options.solver !== undefined ? options.solver : new GSSolver();
/**
* @property constraints
* @type {Array}
*/
this.constraints = [];
/**
* @property narrowphase
* @type {Narrowphase}
*/
this.narrowphase = new Narrowphase(this);
/**
* @property {ArrayCollisionMatrix} collisionMatrix
* @type {ArrayCollisionMatrix}
*/
this.collisionMatrix = new ArrayCollisionMatrix();
/**
* CollisionMatrix from the previous step.
* @property {ArrayCollisionMatrix} collisionMatrixPrevious
* @type {ArrayCollisionMatrix}
*/
this.collisionMatrixPrevious = new ArrayCollisionMatrix();
this.bodyOverlapKeeper = new OverlapKeeper();
this.shapeOverlapKeeper = new OverlapKeeper();
/**
* All added materials
* @property materials
* @type {Array}
*/
this.materials = [];
/**
* @property contactmaterials
* @type {Array}
*/
this.contactmaterials = [];
/**
* Used to look up a ContactMaterial given two instances of Material.
* @property {TupleDictionary} contactMaterialTable
*/
this.contactMaterialTable = new TupleDictionary();
this.defaultMaterial = new Material("default");
/**
* This contact material is used if no suitable contactmaterial is found for a contact.
* @property defaultContactMaterial
* @type {ContactMaterial}
*/
this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial, this.defaultMaterial, { friction: 0.3, restitution: 0.0 });
/**
* @property doProfiling
* @type {Boolean}
*/
this.doProfiling = false;
/**
* @property profile
* @type {Object}
*/
this.profile = {
solve:0,
makeContactConstraints:0,
broadphase:0,
integrate:0,
narrowphase:0,
};
/**
* Time accumulator for interpolation. See http://gafferongames.com/game-physics/fix-your-timestep/
* @property {Number} accumulator
*/
this.accumulator = 0;
/**
* @property subsystems
* @type {Array}
*/
this.subsystems = [];
/**
* Dispatched after a body has been added to the world.
* @event addBody
* @param {Body} body The body that has been added to the world.
*/
this.addBodyEvent = {
type:"addBody",
body : null
};
/**
* Dispatched after a body has been removed from the world.
* @event removeBody
* @param {Body} body The body that has been removed from the world.
*/
this.removeBodyEvent = {
type:"removeBody",
body : null
};
this.idToBodyMap = {};
this.broadphase.setWorld(this);
}
World.prototype = new EventTarget();
// Temp stuff
var tmpAABB1 = new AABB();
var tmpArray1 = [];
var tmpRay = new Ray();
/**
* Get the contact material between materials m1 and m2
* @method getContactMaterial
* @param {Material} m1
* @param {Material} m2
* @return {ContactMaterial} The contact material if it was found.
*/
World.prototype.getContactMaterial = function(m1,m2){
return this.contactMaterialTable.get(m1.id,m2.id); //this.contactmaterials[this.mats2cmat[i+j*this.materials.length]];
};
/**
* Get number of objects in the world.
* @method numObjects
* @return {Number}
* @deprecated
*/
World.prototype.numObjects = function(){
return this.bodies.length;
};
/**
* Store old collision state info
* @method collisionMatrixTick
*/
World.prototype.collisionMatrixTick = function(){
var temp = this.collisionMatrixPrevious;
this.collisionMatrixPrevious = this.collisionMatrix;
this.collisionMatrix = temp;
this.collisionMatrix.reset();
this.bodyOverlapKeeper.tick();
this.shapeOverlapKeeper.tick();
};
/**
* Add a rigid body to the simulation.
* @method add
* @param {Body} body
* @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case.
* @todo Adding an array of bodies should be possible. This would save some loops too
* @deprecated Use .addBody instead
*/
World.prototype.add = World.prototype.addBody = function(body){
if(this.bodies.indexOf(body) !== -1){
return;
}
body.index = this.bodies.length;
this.bodies.push(body);
body.world = this;
body.initPosition.copy(body.position);
body.initVelocity.copy(body.velocity);
body.timeLastSleepy = this.time;
if(body instanceof Body){
body.initAngularVelocity.copy(body.angularVelocity);
body.initQuaternion.copy(body.quaternion);
}
this.collisionMatrix.setNumObjects(this.bodies.length);
this.addBodyEvent.body = body;
this.idToBodyMap[body.id] = body;
this.dispatchEvent(this.addBodyEvent);
};
/**
* Add a constraint to the simulation.
* @method addConstraint
* @param {Constraint} c
*/
World.prototype.addConstraint = function(c){
this.constraints.push(c);
};
/**
* Removes a constraint
* @method removeConstraint
* @param {Constraint} c
*/
World.prototype.removeConstraint = function(c){
var idx = this.constraints.indexOf(c);
if(idx!==-1){
this.constraints.splice(idx,1);
}
};
/**
* Raycast test
* @method rayTest
* @param {Vec3} from
* @param {Vec3} to
* @param {RaycastResult} result
* @deprecated Use .raycastAll, .raycastClosest or .raycastAny instead.
*/
World.prototype.rayTest = function(from, to, result){
if(result instanceof RaycastResult){
// Do raycastclosest
this.raycastClosest(from, to, {
skipBackfaces: true
}, result);
} else {
// Do raycastAll
this.raycastAll(from, to, {
skipBackfaces: true
}, result);
}
};
/**
* Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.
* @method raycastAll
* @param {Vec3} from
* @param {Vec3} to
* @param {Object} options
* @param {number} [options.collisionFilterMask=-1]
* @param {number} [options.collisionFilterGroup=-1]
* @param {boolean} [options.skipBackfaces=false]
* @param {boolean} [options.checkCollisionResponse=true]
* @param {Function} callback
* @return {boolean} True if any body was hit.
*/
World.prototype.raycastAll = function(from, to, options, callback){
options.mode = Ray.ALL;
options.from = from;
options.to = to;
options.callback = callback;
return tmpRay.intersectWorld(this, options);
};
/**
* Ray cast, and stop at the first result. Note that the order is random - but the method is fast.
* @method raycastAny
* @param {Vec3} from
* @param {Vec3} to
* @param {Object} options
* @param {number} [options.collisionFilterMask=-1]
* @param {number} [options.collisionFilterGroup=-1]
* @param {boolean} [options.skipBackfaces=false]
* @param {boolean} [options.checkCollisionResponse=true]
* @param {RaycastResult} result
* @return {boolean} True if any body was hit.
*/
World.prototype.raycastAny = function(from, to, options, result){
options.mode = Ray.ANY;
options.from = from;
options.to = to;
options.result = result;
return tmpRay.intersectWorld(this, options);
};
/**
* Ray cast, and return information of the closest hit.
* @method raycastClosest
* @param {Vec3} from
* @param {Vec3} to
* @param {Object} options
* @param {number} [options.collisionFilterMask=-1]
* @param {number} [options.collisionFilterGroup=-1]
* @param {boolean} [options.skipBackfaces=false]
* @param {boolean} [options.checkCollisionResponse=true]
* @param {RaycastResult} result
* @return {boolean} True if any body was hit.
*/
World.prototype.raycastClosest = function(from, to, options, result){
options.mode = Ray.CLOSEST;
options.from = from;
options.to = to;
options.result = result;
return tmpRay.intersectWorld(this, options);
};
/**
* Remove a rigid body from the simulation.
* @method remove
* @param {Body} body
* @deprecated Use .removeBody instead
*/
World.prototype.remove = function(body){
body.world = null;
var n = this.bodies.length - 1,
bodies = this.bodies,
idx = bodies.indexOf(body);
if(idx !== -1){
bodies.splice(idx, 1); // Todo: should use a garbage free method
// Recompute index
for(var i=0; i!==bodies.length; i++){
bodies[i].index = i;
}
this.collisionMatrix.setNumObjects(n);
this.removeBodyEvent.body = body;
delete this.idToBodyMap[body.id];
this.dispatchEvent(this.removeBodyEvent);
}
};
/**
* Remove a rigid body from the simulation.
* @method removeBody
* @param {Body} body
*/
World.prototype.removeBody = World.prototype.remove;
World.prototype.getBodyById = function(id){
return this.idToBodyMap[id];
};
// TODO Make a faster map
World.prototype.getShapeById = function(id){
var bodies = this.bodies;
for(var i=0, bl = bodies.length; i<bl; i++){
var shapes = bodies[i].shapes;
for (var j = 0, sl = shapes.length; j < sl; j++) {
var shape = shapes[j];
if(shape.id === id){
return shape;
}
}
}
};
/**
* Adds a material to the World.
* @method addMaterial
* @param {Material} m
* @todo Necessary?
*/
World.prototype.addMaterial = function(m){
this.materials.push(m);
};
/**
* Adds a contact material to the World
* @method addContactMaterial
* @param {ContactMaterial} cmat
*/
World.prototype.addContactMaterial = function(cmat) {
// Add contact material
this.contactmaterials.push(cmat);
// Add current contact material to the material table
this.contactMaterialTable.set(cmat.materials[0].id,cmat.materials[1].id,cmat);
};
// performance.now()
if(typeof performance === 'undefined'){
performance = {};
}
if(!performance.now){
var nowOffset = Date.now();
if (performance.timing && performance.timing.navigationStart){
nowOffset = performance.timing.navigationStart;
}
performance.now = function(){
return Date.now() - nowOffset;
};
}
var step_tmp1 = new Vec3();
/**
* Step the physics world forward in time.
*
* There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take.
*
* @method step
* @param {Number} dt The fixed time step size to use.
* @param {Number} [timeSinceLastCalled] The time elapsed since the function was last called.
* @param {Number} [maxSubSteps=10] Maximum number of fixed steps to take per function call.
*
* @example
* // fixed timestepping without interpolation
* world.step(1/60);
*
* @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
*/
World.prototype.step = function(dt, timeSinceLastCalled, maxSubSteps){
maxSubSteps = maxSubSteps || 10;
timeSinceLastCalled = timeSinceLastCalled || 0;
if(timeSinceLastCalled === 0){ // Fixed, simple stepping
this.internalStep(dt);
// Increment time
this.time += dt;
} else {
this.accumulator += timeSinceLastCalled;
var substeps = 0;
while (this.accumulator >= dt && substeps < maxSubSteps) {
// Do fixed steps to catch up
this.internalStep(dt);
this.accumulator -= dt;
substeps++;
}
var t = (this.accumulator % dt) / dt;
for(var j=0; j !== this.bodies.length; j++){
var b = this.bodies[j];
b.previousPosition.lerp(b.position, t, b.interpolatedPosition);
b.previousQuaternion.slerp(b.quaternion, t, b.interpolatedQuaternion);
b.previousQuaternion.normalize();
}
this.time += timeSinceLastCalled;
}
};
var
/**
* Dispatched after the world has stepped forward in time.
* @event postStep
*/
World_step_postStepEvent = {type:"postStep"}, // Reusable event objects to save memory
/**
* Dispatched before the world steps forward in time.
* @event preStep
*/
World_step_preStepEvent = {type:"preStep"},
World_step_collideEvent = {type:Body.COLLIDE_EVENT_NAME, body:null, contact:null },
World_step_oldContacts = [], // Pools for unused objects
World_step_frictionEquationPool = [],
World_step_p1 = [], // Reusable arrays for collision pairs
World_step_p2 = [],
World_step_gvec = new Vec3(), // Temporary vectors and quats
World_step_vi = new Vec3(),
World_step_vj = new Vec3(),
World_step_wi = new Vec3(),
World_step_wj = new Vec3(),
World_step_t1 = new Vec3(),
World_step_t2 = new Vec3(),
World_step_rixn = new Vec3(),
World_step_rjxn = new Vec3(),
World_step_step_q = new Quaternion(),
World_step_step_w = new Quaternion(),
World_step_step_wq = new Quaternion(),
invI_tau_dt = new Vec3();
World.prototype.internalStep = function(dt){
this.dt = dt;
var world = this,
that = this,
contacts = this.contacts,
p1 = World_step_p1,
p2 = World_step_p2,
N = this.numObjects(),
bodies = this.bodies,
solver = this.solver,
gravity = this.gravity,
doProfiling = this.doProfiling,
profile = this.profile,
DYNAMIC = Body.DYNAMIC,
profilingStart,
constraints = this.constraints,
frictionEquationPool = World_step_frictionEquationPool,
gnorm = gravity.norm(),
gx = gravity.x,
gy = gravity.y,
gz = gravity.z,
i=0;
if(doProfiling){
profilingStart = performance.now();
}
// Add gravity to all objects
for(i=0; i!==N; i++){
var bi = bodies[i];
if(bi.type === DYNAMIC){ // Only for dynamic bodies
var f = bi.force, m = bi.mass;
f.x += m*gx;
f.y += m*gy;
f.z += m*gz;
}
}
// Update subsystems
for(var i=0, Nsubsystems=this.subsystems.length; i!==Nsubsystems; i++){
this.subsystems[i].update();
}
// Collision detection
if(doProfiling){ profilingStart = performance.now(); }
p1.length = 0; // Clean up pair arrays from last step
p2.length = 0;
this.broadphase.collisionPairs(this,p1,p2);
if(doProfiling){ profile.broadphase = performance.now() - profilingStart; }
// Remove constrained pairs with collideConnected == false
var Nconstraints = constraints.length;
for(i=0; i!==Nconstraints; i++){
var c = constraints[i];
if(!c.collideConnected){
for(var j = p1.length-1; j>=0; j-=1){
if( (c.bodyA === p1[j] && c.bodyB === p2[j]) ||
(c.bodyB === p1[j] && c.bodyA === p2[j])){
p1.splice(j, 1);
p2.splice(j, 1);
}
}
}
}
this.collisionMatrixTick();
// Generate contacts
if(doProfiling){ profilingStart = performance.now(); }
var oldcontacts = World_step_oldContacts;
var NoldContacts = contacts.length;
for(i=0; i!==NoldContacts; i++){
oldcontacts.push(contacts[i]);
}
contacts.length = 0;
// Transfer FrictionEquation from current list to the pool for reuse
var NoldFrictionEquations = this.frictionEquations.length;
for(i=0; i!==NoldFrictionEquations; i++){
frictionEquationPool.push(this.frictionEquations[i]);
}
this.frictionEquations.length = 0;
this.narrowphase.getContacts(
p1,
p2,
this,
contacts,
oldcontacts, // To be reused
this.frictionEquations,
frictionEquationPool
);
if(doProfiling){
profile.narrowphase = performance.now() - profilingStart;
}
// Loop over all collisions
if(doProfiling){
profilingStart = performance.now();
}
// Add all friction eqs
for (var i = 0; i < this.frictionEquations.length; i++) {
solver.addEquation(this.frictionEquations[i]);
}
var ncontacts = contacts.length;
for(var k=0; k!==ncontacts; k++){
// Current contact
var c = contacts[k];
// Get current collision indeces
var bi = c.bi,
bj = c.bj,
si = c.si,
sj = c.sj;
// Get collision properties
var cm;
if(bi.material && bj.material){
cm = this.getContactMaterial(bi.material,bj.material) || this.defaultContactMaterial;
} else {
cm = this.defaultContactMaterial;
}
// c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
var mu = cm.friction;
// c.restitution = cm.restitution;
// If friction or restitution were specified in the material, use them
if(bi.material && bj.material){
if(bi.material.friction >= 0 && bj.material.friction >= 0){
mu = bi.material.friction * bj.material.friction;
}
if(bi.material.restitution >= 0 && bj.material.restitution >= 0){
c.restitution = bi.material.restitution * bj.material.restitution;
}
}
// c.setSpookParams(
// cm.contactEquationStiffness,
// cm.contactEquationRelaxation,
// dt
// );
solver.addEquation(c);
// // Add friction constraint equation
// if(mu > 0){
// // Create 2 tangent equations
// var mug = mu * gnorm;
// var reducedMass = (bi.invMass + bj.invMass);
// if(reducedMass > 0){
// reducedMass = 1/reducedMass;
// }
// var pool = frictionEquationPool;
// var c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
// var c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
// this.frictionEquations.push(c1, c2);
// c1.bi = c2.bi = bi;
// c1.bj = c2.bj = bj;
// c1.minForce = c2.minForce = -mug*reducedMass;
// c1.maxForce = c2.maxForce = mug*reducedMass;
// // Copy over the relative vectors
// c1.ri.copy(c.ri);
// c1.rj.copy(c.rj);
// c2.ri.copy(c.ri);
// c2.rj.copy(c.rj);
// // Construct tangents
// c.ni.tangents(c1.t, c2.t);
// // Set spook params
// c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
// c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
// c1.enabled = c2.enabled = c.enabled;
// // Add equations to solver
// solver.addEquation(c1);
// solver.addEquation(c2);
// }
if( bi.allowSleep &&
bi.type === Body.DYNAMIC &&
bi.sleepState === Body.SLEEPING &&
bj.sleepState === Body.AWAKE &&
bj.type !== Body.STATIC
){
var speedSquaredB = bj.velocity.norm2() + bj.angularVelocity.norm2();
var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2);
if(speedSquaredB >= speedLimitSquaredB*2){
bi._wakeUpAfterNarrowphase = true;
}
}
if( bj.allowSleep &&
bj.type === Body.DYNAMIC &&
bj.sleepState === Body.SLEEPING &&
bi.sleepState === Body.AWAKE &&
bi.type !== Body.STATIC
){
var speedSquaredA = bi.velocity.norm2() + bi.angularVelocity.norm2();
var speedLimitSquaredA = Math.pow(bi.sleepSpeedLimit,2);
if(speedSquaredA >= speedLimitSquaredA*2){
bj._wakeUpAfterNarrowphase = true;
}
}
// Now we know that i and j are in contact. Set collision matrix state
this.collisionMatrix.set(bi, bj, true);
if (!this.collisionMatrixPrevious.get(bi, bj)) {
// First contact!
// We reuse the collideEvent object, otherwise we will end up creating new objects for each new contact, even if there's no event listener attached.
World_step_collideEvent.body = bj;
World_step_collideEvent.contact = c;
bi.dispatchEvent(World_step_collideEvent);
World_step_collideEvent.body = bi;
bj.dispatchEvent(World_step_collideEvent);
}
this.bodyOverlapKeeper.set(bi.id, bj.id);
this.shapeOverlapKeeper.set(si.id, sj.id);
}
this.emitContactEvents();
if(doProfiling){
profile.makeContactConstraints = performance.now() - profilingStart;
profilingStart = performance.now();
}
// Wake up bodies
for(i=0; i!==N; i++){
var bi = bodies[i];
if(bi._wakeUpAfterNarrowphase){
bi.wakeUp();
bi._wakeUpAfterNarrowphase = false;
}
}
// Add user-added constraints
var Nconstraints = constraints.length;
for(i=0; i!==Nconstraints; i++){
var c = constraints[i];
c.update();
for(var j=0, Neq=c.equations.length; j!==Neq; j++){
var eq = c.equations[j];
solver.addEquation(eq);
}
}
// Solve the constrained system
solver.solve(dt,this);
if(doProfiling){
profile.solve = performance.now() - profilingStart;
}
// Remove all contacts from solver
solver.removeAllEquations();
// Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details
var pow = Math.pow;
for(i=0; i!==N; i++){
var bi = bodies[i];
if(bi.type & DYNAMIC){ // Only for dynamic bodies
var ld = pow(1.0 - bi.linearDamping,dt);
var v = bi.velocity;
v.mult(ld,v);
var av = bi.angularVelocity;
if(av){
var ad = pow(1.0 - bi.angularDamping,dt);
av.mult(ad,av);
}
}
}
this.dispatchEvent(World_step_preStepEvent);
// Invoke pre-step callbacks
for(i=0; i!==N; i++){
var bi = bodies[i];
if(bi.preStep){
bi.preStep.call(bi);
}
}
// Leap frog
// vnew = v + h*f/m
// xnew = x + h*vnew
if(doProfiling){
profilingStart = performance.now();
}
var stepnumber = this.stepnumber;
var quatNormalize = stepnumber % (this.quatNormalizeSkip + 1) === 0;
var quatNormalizeFast = this.quatNormalizeFast;
for(i=0; i!==N; i++){
bodies[i].integrate(dt, quatNormalize, quatNormalizeFast);
}
this.clearForces();
this.broadphase.dirty = true;
if(doProfiling){
profile.integrate = performance.now() - profilingStart;
}
// Update world time
this.time += dt;
this.stepnumber += 1;
this.dispatchEvent(World_step_postStepEvent);
// Invoke post-step callbacks
for(i=0; i!==N; i++){
var bi = bodies[i];
var postStep = bi.postStep;
if(postStep){
postStep.call(bi);
}
}
// Sleeping update
if(this.allowSleep){
for(i=0; i!==N; i++){
bodies[i].sleepTick(this.time);
}
}
};
World.prototype.emitContactEvents = (function(){
var additions = [];
var removals = [];
var beginContactEvent = {
type: 'beginContact',
bodyA: null,
bodyB: null
};
var endContactEvent = {
type: 'endContact',
bodyA: null,
bodyB: null
};
var beginShapeContactEvent = {
type: 'beginShapeContact',
bodyA: null,
bodyB: null,
shapeA: null,
shapeB: null
};
var endShapeContactEvent = {
type: 'endShapeContact',
bodyA: null,
bodyB: null,
shapeA: null,
shapeB: null
};
return function(){
var hasBeginContact = this.hasAnyEventListener('beginContact');
var hasEndContact = this.hasAnyEventListener('endContact');
if(hasBeginContact || hasEndContact){
this.bodyOverlapKeeper.getDiff(additions, removals);
}
if(hasBeginContact){
for (var i = 0, l = additions.length; i < l; i += 2) {
beginContactEvent.bodyA = this.getBodyById(additions[i]);
beginContactEvent.bodyB = this.getBodyById(additions[i+1]);
this.dispatchEvent(beginContactEvent);
}
beginContactEvent.bodyA = beginContactEvent.bodyB = null;
}
if(hasEndContact){
for (var i = 0, l = removals.length; i < l; i += 2) {
endContactEvent.bodyA = this.getBodyById(removals[i]);
endContactEvent.bodyB = this.getBodyById(removals[i+1]);
this.dispatchEvent(endContactEvent);
}
endContactEvent.bodyA = endContactEvent.bodyB = null;
}
additions.length = removals.length = 0;
var hasBeginShapeContact = this.hasAnyEventListener('beginShapeContact');
var hasEndShapeContact = this.hasAnyEventListener('endShapeContact');
if(hasBeginShapeContact || hasEndShapeContact){
this.shapeOverlapKeeper.getDiff(additions, removals);
}
if(hasBeginShapeContact){
for (var i = 0, l = additions.length; i < l; i += 2) {
var shapeA = this.getShapeById(additions[i]);
var shapeB = this.getShapeById(additions[i+1]);
beginShapeContactEvent.shapeA = shapeA;
beginShapeContactEvent.shapeB = shapeB;
beginShapeContactEvent.bodyA = shapeA.body;
beginShapeContactEvent.bodyB = shapeB.body;
this.dispatchEvent(beginShapeContactEvent);
}
beginShapeContactEvent.bodyA = beginShapeContactEvent.bodyB = beginShapeContactEvent.shapeA = beginShapeContactEvent.shapeB = null;
}
if(hasEndShapeContact){
for (var i = 0, l = removals.length; i < l; i += 2) {
var shapeA = this.getShapeById(removals[i]);
var shapeB = this.getShapeById(removals[i+1]);
endShapeContactEvent.shapeA = shapeA;
endShapeContactEvent.shapeB = shapeB;
endShapeContactEvent.bodyA = shapeA.body;
endShapeContactEvent.bodyB = shapeB.body;
this.dispatchEvent(endShapeContactEvent);
}
endShapeContactEvent.bodyA = endShapeContactEvent.bodyB = endShapeContactEvent.shapeA = endShapeContactEvent.shapeB = null;
}
};
})();
/**
* Sets all body forces in the world to zero.
* @method clearForces
*/
World.prototype.clearForces = function(){
var bodies = this.bodies;
var N = bodies.length;
for(var i=0; i !== N; i++){
var b = bodies[i],
force = b.force,
tau = b.torque;
b.force.set(0,0,0);
b.torque.set(0,0,0);
}
};
| 0 | 0.865462 | 1 | 0.865462 | game-dev | MEDIA | 0.44431 | game-dev | 0.88232 | 1 | 0.88232 |
Wanderers-Of-The-Rift/wotr-mod | 2,208 | src/main/java/com/wanderersoftherift/wotr/network/rift/S2CLevelListUpdatePacket.java | package com.wanderersoftherift.wotr.network.rift;
import com.wanderersoftherift.wotr.WanderersOfTheRift;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Player;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadHandler;
import org.jetbrains.annotations.NotNull;
public record S2CLevelListUpdatePacket(ResourceLocation resourceLocation, boolean removal)
implements CustomPacketPayload {
public static final CustomPacketPayload.Type<S2CLevelListUpdatePacket> TYPE = new CustomPacketPayload.Type<>(
ResourceLocation.fromNamespaceAndPath(WanderersOfTheRift.MODID, "s2c_dimension_types_update"));
public static final StreamCodec<ByteBuf, S2CLevelListUpdatePacket> STREAM_CODEC = StreamCodec.composite(
ResourceLocation.STREAM_CODEC, S2CLevelListUpdatePacket::resourceLocation, ByteBufCodecs.BOOL,
S2CLevelListUpdatePacket::removal, S2CLevelListUpdatePacket::new);
@Override
public CustomPacketPayload.@NotNull Type<S2CLevelListUpdatePacket> type() {
return TYPE;
}
public static class S2CLevelListUpdatePacketHandler implements IPayloadHandler<S2CLevelListUpdatePacket> {
public void handle(@NotNull S2CLevelListUpdatePacket packet, @NotNull IPayloadContext context) {
Player player = context.player();
if (!(player instanceof LocalPlayer localPlayer)) {
return;
}
if (packet.removal()) {
localPlayer.connection.levels().removeIf(key -> key.location().equals(packet.resourceLocation()));
} else {
localPlayer.connection.levels()
.add(ResourceKey.create(Registries.DIMENSION, packet.resourceLocation()));
}
}
}
}
| 0 | 0.920046 | 1 | 0.920046 | game-dev | MEDIA | 0.950354 | game-dev,networking | 0.73157 | 1 | 0.73157 |
bubble2k16/emus3ds | 2,192 | src/cores/virtuanes/NES/ApuEX/APU_VRC7.cpp | //////////////////////////////////////////////////////////////////////////
// //
// Konami VRC7 //
// Norix //
// written 2001/09/18 //
// last modify ----/--/-- //
//////////////////////////////////////////////////////////////////////////
#include "APU_VRC7.h"
APU_VRC7::APU_VRC7()
{
u8 new3DS = false;
APT_CheckNew3DS(&new3DS);
int sampleRate = 32000;
if (!new3DS)
sampleRate = 20000;
OPLL_init( 3579545, (uint32)sampleRate ); // ���̃T���v�����O���[�g
VRC7_OPLL = OPLL_new();
if( VRC7_OPLL ) {
OPLL_reset( VRC7_OPLL );
OPLL_reset_patch( VRC7_OPLL, OPLL_VRC7_TONE );
VRC7_OPLL->masterVolume = 128;
}
// ���ݒ�
Reset( APU_CLOCK, sampleRate );
}
APU_VRC7::~APU_VRC7()
{
if( VRC7_OPLL ) {
OPLL_delete( VRC7_OPLL );
VRC7_OPLL = NULL;
// OPLL_close(); // �����Ă��ǂ�(���g����)
}
}
void APU_VRC7::Reset( FLOAT fClock, INT nRate )
{
if( VRC7_OPLL ) {
OPLL_reset( VRC7_OPLL );
OPLL_reset_patch( VRC7_OPLL, OPLL_VRC7_TONE );
VRC7_OPLL->masterVolume = 128;
}
address = 0;
Setup( fClock, nRate );
}
void APU_VRC7::Setup( FLOAT fClock, INT nRate )
{
OPLL_setClock( (uint32)(fClock*2.0f), (uint32)nRate );
}
void APU_VRC7::Write( WORD addr, BYTE data )
{
if( VRC7_OPLL ) {
if( addr == 0x9010 ) {
address = data;
} else if( addr == 0x9030 ) {
OPLL_writeReg( VRC7_OPLL, address, data );
}
}
}
INT APU_VRC7::Process( INT channel )
{
if( VRC7_OPLL )
return OPLL_calc( VRC7_OPLL );
return 0;
}
INT APU_VRC7::GetFreq( INT channel )
{
if( VRC7_OPLL && channel < 8 ) {
INT fno = (((INT)VRC7_OPLL->reg[0x20+channel]&0x01)<<8)
+ (INT)VRC7_OPLL->reg[0x10+channel];
INT blk = (VRC7_OPLL->reg[0x20+channel]>>1) & 0x07;
float blkmul[] = { 0.5f, 1.0f, 2.0f, 4.0f, 8.0f, 16.0f, 32.0f, 64.0f };
if( VRC7_OPLL->reg[0x20+channel] & 0x10 ) {
return (INT)((256.0*(double)fno*blkmul[blk]) / ((double)(1<<18)/(3579545.0/72.0)));
}
}
return 0;
}
| 0 | 0.878474 | 1 | 0.878474 | game-dev | MEDIA | 0.366552 | game-dev | 0.971657 | 1 | 0.971657 |
pWn3d1337/Techguns2 | 1,537 | src/main/java/techguns/tileentities/operation/MachineOperationChance.java | package techguns.tileentities.operation;
import java.util.ArrayList;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fluids.FluidStack;
public class MachineOperationChance extends MachineOperation {
protected TileEntity tile;
protected double[] itemChances;
protected ArrayList<ItemStack> rolled_outputs;
public MachineOperationChance(ArrayList<ItemStack> inputs, ArrayList<ItemStack> outputs,
ArrayList<FluidStack> fluid_inputs, ArrayList<FluidStack> fluid_outputs, int stackMultiplier, double[] itemChances) {
super(inputs, outputs, fluid_inputs, fluid_outputs, stackMultiplier);
this.itemChances = itemChances;
rolled_outputs = new ArrayList<>(outputs.size());
outputs.forEach(o -> rolled_outputs.add(o.copy()));
}
public void setTile(TileEntity e) {
this.tile=e;
}
protected void updateChanceRolls() {
for(int i=0; i<itemChances.length; i++) {
double amount = outputs.get(i).getCount()*itemChances[i]*this.stackMultiplier;
int fixed=0;
while(amount>1f) {
amount-=1f;
fixed++;
}
if(tile.getWorld().rand.nextDouble()<=amount) {
fixed++;
}
rolled_outputs.get(i).setCount(fixed);
}
}
@Override
public MachineOperation setStackMultiplier(int mult) {
super.setStackMultiplier(mult);
updateChanceRolls();
return this;
}
@Override
public ArrayList<ItemStack> getOutputs() {
return rolled_outputs;
}
@Override
public ArrayList<ItemStack> getOutputsWithMult() {
return rolled_outputs;
}
}
| 0 | 0.823398 | 1 | 0.823398 | game-dev | MEDIA | 0.979132 | game-dev | 0.934086 | 1 | 0.934086 |
bastianleicht/badlion-src | 8,474 | net/minecraft/block/BlockRailPowered.java | package net.minecraft.block;
import com.google.common.base.Predicate;
import net.minecraft.block.Block;
import net.minecraft.block.BlockRailBase;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
public class BlockRailPowered extends BlockRailBase {
public static final PropertyEnum SHAPE = PropertyEnum.create("shape", BlockRailBase.EnumRailDirection.class, new Predicate() {
public boolean apply(BlockRailBase.EnumRailDirection p_apply_1_) {
return p_apply_1_ != BlockRailBase.EnumRailDirection.NORTH_EAST && p_apply_1_ != BlockRailBase.EnumRailDirection.NORTH_WEST && p_apply_1_ != BlockRailBase.EnumRailDirection.SOUTH_EAST && p_apply_1_ != BlockRailBase.EnumRailDirection.SOUTH_WEST;
}
});
public static final PropertyBool POWERED = PropertyBool.create("powered");
// $FF: synthetic field
private static int[] $SWITCH_TABLE$net$minecraft$block$BlockRailBase$EnumRailDirection;
protected BlockRailPowered() {
super(true);
this.setDefaultState(this.blockState.getBaseState().withProperty(SHAPE, BlockRailBase.EnumRailDirection.NORTH_SOUTH).withProperty(POWERED, Boolean.valueOf(false)));
}
protected boolean func_176566_a(World worldIn, BlockPos pos, IBlockState state, boolean p_176566_4_, int p_176566_5_) {
if(p_176566_5_ >= 8) {
return false;
} else {
int i = pos.getX();
int j = pos.getY();
int k = pos.getZ();
boolean flag = true;
BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = (BlockRailBase.EnumRailDirection)state.getValue(SHAPE);
switch($SWITCH_TABLE$net$minecraft$block$BlockRailBase$EnumRailDirection()[blockrailbase$enumraildirection.ordinal()]) {
case 1:
if(p_176566_4_) {
++k;
} else {
--k;
}
break;
case 2:
if(p_176566_4_) {
--i;
} else {
++i;
}
break;
case 3:
if(p_176566_4_) {
--i;
} else {
++i;
++j;
flag = false;
}
blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.EAST_WEST;
break;
case 4:
if(p_176566_4_) {
--i;
++j;
flag = false;
} else {
++i;
}
blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.EAST_WEST;
break;
case 5:
if(p_176566_4_) {
++k;
} else {
--k;
++j;
flag = false;
}
blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_SOUTH;
break;
case 6:
if(p_176566_4_) {
++k;
++j;
flag = false;
} else {
--k;
}
blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_SOUTH;
}
return this.func_176567_a(worldIn, new BlockPos(i, j, k), p_176566_4_, p_176566_5_, blockrailbase$enumraildirection)?true:flag && this.func_176567_a(worldIn, new BlockPos(i, j - 1, k), p_176566_4_, p_176566_5_, blockrailbase$enumraildirection);
}
}
protected boolean func_176567_a(World worldIn, BlockPos p_176567_2_, boolean p_176567_3_, int distance, BlockRailBase.EnumRailDirection p_176567_5_) {
IBlockState iblockstate = worldIn.getBlockState(p_176567_2_);
if(iblockstate.getBlock() != this) {
return false;
} else {
BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = (BlockRailBase.EnumRailDirection)iblockstate.getValue(SHAPE);
return p_176567_5_ != BlockRailBase.EnumRailDirection.EAST_WEST || blockrailbase$enumraildirection != BlockRailBase.EnumRailDirection.NORTH_SOUTH && blockrailbase$enumraildirection != BlockRailBase.EnumRailDirection.ASCENDING_NORTH && blockrailbase$enumraildirection != BlockRailBase.EnumRailDirection.ASCENDING_SOUTH?(p_176567_5_ != BlockRailBase.EnumRailDirection.NORTH_SOUTH || blockrailbase$enumraildirection != BlockRailBase.EnumRailDirection.EAST_WEST && blockrailbase$enumraildirection != BlockRailBase.EnumRailDirection.ASCENDING_EAST && blockrailbase$enumraildirection != BlockRailBase.EnumRailDirection.ASCENDING_WEST?(((Boolean)iblockstate.getValue(POWERED)).booleanValue()?(worldIn.isBlockPowered(p_176567_2_)?true:this.func_176566_a(worldIn, p_176567_2_, iblockstate, p_176567_3_, distance + 1)):false):false):false;
}
}
protected void onNeighborChangedInternal(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock) {
boolean flag = ((Boolean)state.getValue(POWERED)).booleanValue();
boolean flag1 = worldIn.isBlockPowered(pos) || this.func_176566_a(worldIn, pos, state, true, 0) || this.func_176566_a(worldIn, pos, state, false, 0);
if(flag1 != flag) {
worldIn.setBlockState(pos, state.withProperty(POWERED, Boolean.valueOf(flag1)), 3);
worldIn.notifyNeighborsOfStateChange(pos.down(), this);
if(((BlockRailBase.EnumRailDirection)state.getValue(SHAPE)).isAscending()) {
worldIn.notifyNeighborsOfStateChange(pos.up(), this);
}
}
}
public IProperty getShapeProperty() {
return SHAPE;
}
public IBlockState getStateFromMeta(int meta) {
return this.getDefaultState().withProperty(SHAPE, BlockRailBase.EnumRailDirection.byMetadata(meta & 7)).withProperty(POWERED, Boolean.valueOf((meta & 8) > 0));
}
public int getMetaFromState(IBlockState state) {
int i = 0;
i = i | ((BlockRailBase.EnumRailDirection)state.getValue(SHAPE)).getMetadata();
if(((Boolean)state.getValue(POWERED)).booleanValue()) {
i |= 8;
}
return i;
}
protected BlockState createBlockState() {
return new BlockState(this, new IProperty[]{SHAPE, POWERED});
}
// $FF: synthetic method
static int[] $SWITCH_TABLE$net$minecraft$block$BlockRailBase$EnumRailDirection() {
int[] var10000 = $SWITCH_TABLE$net$minecraft$block$BlockRailBase$EnumRailDirection;
if($SWITCH_TABLE$net$minecraft$block$BlockRailBase$EnumRailDirection != null) {
return var10000;
} else {
int[] var0 = new int[BlockRailBase.EnumRailDirection.values().length];
try {
var0[BlockRailBase.EnumRailDirection.ASCENDING_EAST.ordinal()] = 3;
} catch (NoSuchFieldError var10) {
;
}
try {
var0[BlockRailBase.EnumRailDirection.ASCENDING_NORTH.ordinal()] = 5;
} catch (NoSuchFieldError var9) {
;
}
try {
var0[BlockRailBase.EnumRailDirection.ASCENDING_SOUTH.ordinal()] = 6;
} catch (NoSuchFieldError var8) {
;
}
try {
var0[BlockRailBase.EnumRailDirection.ASCENDING_WEST.ordinal()] = 4;
} catch (NoSuchFieldError var7) {
;
}
try {
var0[BlockRailBase.EnumRailDirection.EAST_WEST.ordinal()] = 2;
} catch (NoSuchFieldError var6) {
;
}
try {
var0[BlockRailBase.EnumRailDirection.NORTH_EAST.ordinal()] = 10;
} catch (NoSuchFieldError var5) {
;
}
try {
var0[BlockRailBase.EnumRailDirection.NORTH_SOUTH.ordinal()] = 1;
} catch (NoSuchFieldError var4) {
;
}
try {
var0[BlockRailBase.EnumRailDirection.NORTH_WEST.ordinal()] = 9;
} catch (NoSuchFieldError var3) {
;
}
try {
var0[BlockRailBase.EnumRailDirection.SOUTH_EAST.ordinal()] = 7;
} catch (NoSuchFieldError var2) {
;
}
try {
var0[BlockRailBase.EnumRailDirection.SOUTH_WEST.ordinal()] = 8;
} catch (NoSuchFieldError var1) {
;
}
$SWITCH_TABLE$net$minecraft$block$BlockRailBase$EnumRailDirection = var0;
return var0;
}
}
}
| 0 | 0.893991 | 1 | 0.893991 | game-dev | MEDIA | 0.971628 | game-dev | 0.968864 | 1 | 0.968864 |
manisha-v/Number-Cruncher | 2,738 | Codes/Minor2d/Library/PackageCache/com.unity.2d.path@2.1.1/Editor/IMGUI/GUIFramework/GenericControl.cs | using System;
using UnityEngine;
namespace UnityEditor.U2D.Path.GUIFramework
{
public class GenericControl : Control
{
public Func<IGUIState, LayoutData> onBeginLayout;
public Action<IGUIState> onEndLayout;
public Action<IGUIState, Control, int> onRepaint;
public Func<int> count;
public Func<int, Vector3> position;
public Func<IGUIState, int, float> distance;
public Func<int, Vector3> forward;
public Func<int, Vector3> up;
public Func<int, Vector3> right;
public Func<int, object> userData;
public GenericControl(string name) : base(name)
{
}
protected override int GetCount()
{
if (count != null)
return count();
return base.GetCount();
}
protected override void OnEndLayout(IGUIState guiState)
{
if (onEndLayout != null)
onEndLayout(guiState);
}
protected override void OnRepaint(IGUIState guiState, int index)
{
if (onRepaint != null)
onRepaint(guiState, this, index);
}
protected override LayoutData OnBeginLayout(LayoutData data, IGUIState guiState)
{
if (onBeginLayout != null)
return onBeginLayout(guiState);
return data;
}
protected override Vector3 GetPosition(IGUIState guiState, int index)
{
if (position != null)
return position(index);
return base.GetPosition(guiState,index);
}
protected override float GetDistance(IGUIState guiState, int index)
{
if (distance != null)
return distance(guiState, index);
return base.GetDistance(guiState, index);
}
protected override Vector3 GetForward(IGUIState guiState, int index)
{
if (forward != null)
return forward(index);
return base.GetForward(guiState,index);
}
protected override Vector3 GetUp(IGUIState guiState, int index)
{
if (up != null)
return up(index);
return base.GetUp(guiState,index);
}
protected override Vector3 GetRight(IGUIState guiState, int index)
{
if (right != null)
return right(index);
return base.GetRight(guiState,index);
}
protected override object GetUserData(IGUIState guiState, int index)
{
if (userData != null)
return userData(index);
return base.GetUserData(guiState,index);
}
}
}
| 0 | 0.801575 | 1 | 0.801575 | game-dev | MEDIA | 0.42843 | game-dev | 0.689768 | 1 | 0.689768 |
SkidderMC/FDPClient | 26,123 | src/main/java/net/ccbluex/liquidbounce/injection/forge/mixins/render/MixinModelPlayerFix.java | /*
* FDPClient Hacked Client
* A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
* https://github.com/SkidderMC/FDPClient/
*/
package net.ccbluex.liquidbounce.injection.forge.mixins.render;
import net.ccbluex.liquidbounce.event.EventManager;
import net.ccbluex.liquidbounce.event.UpdateModelEvent;
import net.ccbluex.liquidbounce.features.module.modules.visual.CustomModel;
import net.ccbluex.liquidbounce.utils.render.RenderUtils;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.model.ModelBox;
import net.minecraft.client.model.ModelPlayer;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.item.ItemArmor;
import net.minecraft.util.ResourceLocation;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Constant;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.awt.Color;
@Mixin(ModelPlayer.class)
public class MixinModelPlayerFix extends ModelBiped {
public ModelRenderer left_leg;
public ModelRenderer right_leg;
public ModelRenderer body;
public ModelRenderer eye;
public ModelRenderer rabbitBone;
public ModelRenderer rabbitRleg;
public ModelRenderer rabbitLarm;
public ModelRenderer rabbitRarm;
public ModelRenderer rabbitLleg;
public ModelRenderer rabbitHead;
public ModelRenderer fredhead;
public ModelRenderer armLeft;
public ModelRenderer legRight;
public ModelRenderer legLeft;
public ModelRenderer armRight;
public ModelRenderer fredbody;
public ModelRenderer armLeftpad2;
public ModelRenderer torso;
public ModelRenderer earRightpad_1;
public ModelRenderer armRightpad2;
public ModelRenderer legLeftpad;
public ModelRenderer hat;
public ModelRenderer legLeftpad2;
public ModelRenderer armRight2;
public ModelRenderer legRight2;
public ModelRenderer earRightpad;
public ModelRenderer armLeft2;
public ModelRenderer frednose;
public ModelRenderer earLeft;
public ModelRenderer footRight;
public ModelRenderer legRightpad2;
public ModelRenderer legRightpad;
public ModelRenderer armLeftpad;
public ModelRenderer legLeft2;
public ModelRenderer footLeft;
public ModelRenderer hat2;
public ModelRenderer armRightpad;
public ModelRenderer earRight;
public ModelRenderer crotch;
public ModelRenderer jaw;
public ModelRenderer handRight;
public ModelRenderer handLeft;
public ModelRenderer bT1;
public ModelRenderer bT2;
public ModelRenderer bF1;
public ModelRenderer bF2;
public ModelRenderer bF3;
public ModelRenderer bF4;
private float breastOffsetT1 = 0.0F;
private float breastOffsetT2 = 0.0F;
private float breastOffsetF1 = 0.0F;
private float breastOffsetF2 = 0.0F;
private float breastOffsetF3 = 0.0F;
private float breastOffsetF4 = 0.0F;
@Shadow
private boolean smallArms;
@ModifyConstant(method = "<init>", constant = @Constant(floatValue = 2.5F))
private float fixAlexArmHeight(final float original) {
return 2F;
}
/**
* @author As_pw
* @reason Post Arm Renderer
*/
@Override
@Overwrite
public void postRenderArm(final float scale) {
if (this.smallArms) {
this.bipedRightArm.rotationPointX += 0.5F;
this.bipedRightArm.postRender(scale);
this.bipedRightArm.rotationPointZ -= 0.5F;
} else {
this.bipedRightArm.postRender(scale);
}
}
@Inject(method = "render", at = @At("HEAD"), cancellable = true)
public void renderHook(final Entity entityIn, final float limbSwing, final float limbSwingAmount,
final float ageInTicks, final float netHeadYaw, final float headPitch,
final float scale, final CallbackInfo ci) {
final CustomModel customModel = CustomModel.INSTANCE;
if (customModel.getState()) {
if (!customModel.getMode().equals("Female")) {
ci.cancel();
renderCustom(entityIn, limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale);
}
}
}
@Inject(method = "render", at = @At("TAIL"))
public void renderFemaleDetails(final Entity entityIn, final float limbSwing, final float limbSwingAmount,
final float ageInTicks, final float netHeadYaw, final float headPitch,
final float scale, final CallbackInfo ci) {
final CustomModel customModel = CustomModel.INSTANCE;
if (customModel.getState() && customModel.getMode().equals("Female") && entityIn instanceof EntityPlayer) {
renderFemale(entityIn, scale);
}
}
public void setRotationAngle(final ModelRenderer modelRenderer, final float x, final float y, final float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
public void generateModel() {
body = new ModelRenderer(this);
body.setRotationPoint(0.0F, 0.0F, 0.0F);
body.setTextureOffset(34, 8).addBox(-4.0F, 6.0F, -3.0F, 8, 12, 6);
body.setTextureOffset(15, 10).addBox(-3.0F, 9.0F, 3.0F, 6, 8, 3);
body.setTextureOffset(26, 0).addBox(-3.0F, 5.0F, -3.0F, 6, 1, 6);
eye = new ModelRenderer(this);
eye.setTextureOffset(0, 10).addBox(-3.0F, 7.0F, -4.0F, 6, 4, 1);
left_leg = new ModelRenderer(this);
left_leg.setRotationPoint(-2.0F, 18.0F, 0.0F);
left_leg.setTextureOffset(0, 0).addBox(2.9F, 0.0F, -1.5F, 3, 6, 3, 0.0F);
right_leg = new ModelRenderer(this);
right_leg.setRotationPoint(2.0F, 18.0F, 0.0F);
right_leg.setTextureOffset(13, 0).addBox(-5.9F, 0.0F, -1.5F, 3, 6, 3);
rabbitBone = new ModelRenderer(this);
rabbitBone.setRotationPoint(0.0F, 24.0F, 0.0F);
rabbitBone.cubeList.add(new ModelBox(rabbitBone, 28, 45, -5.0F, -13.0F, -5.0F, 10, 11, 8, 0.0F, false));
rabbitRleg = new ModelRenderer(this);
rabbitRleg.setRotationPoint(-3.0F, -2.0F, -1.0F);
rabbitBone.addChild(rabbitRleg);
rabbitRleg.cubeList.add(new ModelBox(rabbitRleg, 0, 0, -2.0F, 0.0F, -2.0F, 4, 2, 4, 0.0F, false));
rabbitLarm = new ModelRenderer(this);
rabbitLarm.setRotationPoint(5.0F, -13.0F, -1.0F);
setRotationAngle(rabbitLarm, 0.0F, 0.0F, -0.0873F);
rabbitBone.addChild(rabbitLarm);
rabbitLarm.cubeList.add(new ModelBox(rabbitLarm, 0, 0, 0.0F, 0.0F, -2.0F, 2, 8, 4, 0.0F, false));
rabbitRarm = new ModelRenderer(this);
rabbitRarm.setRotationPoint(-5.0F, -13.0F, -1.0F);
setRotationAngle(rabbitRarm, 0.0F, 0.0F, 0.0873F);
rabbitBone.addChild(rabbitRarm);
rabbitRarm.cubeList.add(new ModelBox(rabbitRarm, 0, 0, -2.0F, 0.0F, -2.0F, 2, 8, 4, 0.0F, false));
rabbitLleg = new ModelRenderer(this);
rabbitLleg.setRotationPoint(3.0F, -2.0F, -1.0F);
rabbitBone.addChild(rabbitLleg);
rabbitLleg.cubeList.add(new ModelBox(rabbitLleg, 0, 0, -2.0F, 0.0F, -2.0F, 4, 2, 4, 0.0F, false));
rabbitHead = new ModelRenderer(this);
rabbitHead.setRotationPoint(0.0F, -14.0F, -1.0F);
rabbitBone.addChild(rabbitHead);
rabbitHead.cubeList.add(new ModelBox(rabbitHead, 0, 0, -3.0F, 0.0F, -4.0F, 6, 1, 6, 0.0F, false));
rabbitHead.cubeList.add(new ModelBox(rabbitHead, 56, 0, -5.0F, -9.0F, -5.0F, 2, 3, 2, 0.0F, false));
rabbitHead.cubeList.add(new ModelBox(rabbitHead, 56, 0, 3.0F, -9.0F, -5.0F, 2, 3, 2, 0.0F, true));
rabbitHead.cubeList.add(new ModelBox(rabbitHead, 0, 45, -4.0F, -11.0F, -4.0F, 8, 11, 8, 0.0F, false));
rabbitHead.cubeList.add(new ModelBox(rabbitHead, 46, 0, 1.0F, -20.0F, 0.0F, 3, 9, 1, 0.0F, false));
rabbitHead.cubeList.add(new ModelBox(rabbitHead, 46, 0, -4.0F, -20.0F, 0.0F, 3, 9, 1, 0.0F, false));
this.textureWidth = 100;
this.textureHeight = 80;
footRight = new ModelRenderer(this, 22, 39);
footRight.setRotationPoint(0.0F, 8.0F, 0.0F);
footRight.addBox(-2.5F, 0.0F, -6.0F, 5, 3, 8, 0.0F);
setRotationAngle(footRight, -0.034906585F, 0.0F, 0.0F);
earRight = new ModelRenderer(this, 8, 0);
earRight.setRotationPoint(-4.5F, -5.5F, 0.0F);
earRight.addBox(-1.0F, -3.0F, -0.5F, 2, 3, 1, 0.0F);
setRotationAngle(earRight, 0.05235988F, 0.0F, -1.0471976F);
legLeftpad = new ModelRenderer(this, 48, 39);
legLeftpad.setRotationPoint(0.0F, 0.5F, 0.0F);
legLeftpad.addBox(-3.0F, 0.0F, -3.0F, 6, 9, 6, 0.0F);
earRightpad_1 = new ModelRenderer(this, 40, 39);
earRightpad_1.setRotationPoint(0.0F, -1.0F, 0.0F);
earRightpad_1.addBox(-2.0F, -5.0F, -1.0F, 4, 4, 2, 0.0F);
legLeft = new ModelRenderer(this, 54, 10);
legLeft.setRotationPoint(3.3F, 12.5F, 0.0F);
legLeft.addBox(-1.0F, 0.0F, -1.0F, 2, 10, 2, 0.0F);
armRightpad2 = new ModelRenderer(this, 0, 26);
armRightpad2.setRotationPoint(0.0F, 0.5F, 0.0F);
armRightpad2.addBox(-2.5F, 0.0F, -2.5F, 5, 7, 5, 0.0F);
handLeft = new ModelRenderer(this, 58, 56);
handLeft.setRotationPoint(0.0F, 8.0F, 0.0F);
handLeft.addBox(-2.0F, 0.0F, -2.5F, 4, 4, 5, 0.0F);
setRotationAngle(handLeft, 0.0F, 0.0F, 0.05235988F);
armLeft = new ModelRenderer(this, 62, 10);
armLeft.setRotationPoint(6.5F, -8.0F, 0.0F);
armLeft.addBox(-1.0F, 0.0F, -1.0F, 2, 10, 2, 0.0F);
setRotationAngle(armLeft, 0.0F, 0.0F, -0.2617994F);
legRight = new ModelRenderer(this, 90, 8);
legRight.setRotationPoint(-3.3F, 12.5F, 0.0F);
legRight.addBox(-1.0F, 0.0F, -1.0F, 2, 10, 2, 0.0F);
armLeft2 = new ModelRenderer(this, 90, 48);
armLeft2.setRotationPoint(0.0F, 9.6F, 0.0F);
armLeft2.addBox(-1.0F, 0.0F, -1.0F, 2, 8, 2, 0.0F);
setRotationAngle(armLeft2, -0.17453292F, 0.0F, 0.0F);
legRight2 = new ModelRenderer(this, 20, 35);
legRight2.setRotationPoint(0.0F, 9.6F, 0.0F);
legRight2.addBox(-1.0F, 0.0F, -1.0F, 2, 8, 2, 0.0F);
setRotationAngle(legRight2, 0.034906585F, 0.0F, 0.0F);
armLeftpad2 = new ModelRenderer(this, 0, 58);
armLeftpad2.setRotationPoint(0.0F, 0.5F, 0.0F);
armLeftpad2.addBox(-2.5F, 0.0F, -2.5F, 5, 7, 5, 0.0F);
legLeft2 = new ModelRenderer(this, 72, 48);
legLeft2.setRotationPoint(0.0F, 9.6F, 0.0F);
legLeft2.addBox(-1.0F, 0.0F, -1.0F, 2, 8, 2, 0.0F);
setRotationAngle(legLeft2, 0.034906585F, 0.0F, 0.0F);
hat = new ModelRenderer(this, 70, 24);
hat.setRotationPoint(0.0F, -8.4F, 0.0F);
hat.addBox(-3.0F, -0.5F, -3.0F, 6, 1, 6, 0.0F);
setRotationAngle(hat, -0.017453292F, 0.0F, 0.0F);
earRightpad = new ModelRenderer(this, 85, 0);
earRightpad.setRotationPoint(0.0F, -1.0F, 0.0F);
earRightpad.addBox(-2.0F, -5.0F, -1.0F, 4, 4, 2, 0.0F);
crotch = new ModelRenderer(this, 56, 0);
crotch.setRotationPoint(0.0F, 9.5F, 0.0F);
crotch.addBox(-5.5F, 0.0F, -3.5F, 11, 3, 7, 0.0F);
torso = new ModelRenderer(this, 8, 0);
torso.setRotationPoint(0.0F, 0.0F, 0.0F);
torso.addBox(-6.0F, -9.0F, -4.0F, 12, 18, 8, 0.0F);
setRotationAngle(torso, 0.017453292F, 0.0F, 0.0F);
armRight2 = new ModelRenderer(this, 90, 20);
armRight2.setRotationPoint(0.0F, 9.6F, 0.0F);
armRight2.addBox(-1.0F, 0.0F, -1.0F, 2, 8, 2, 0.0F);
setRotationAngle(armRight2, -0.17453292F, 0.0F, 0.0F);
handRight = new ModelRenderer(this, 20, 26);
handRight.setRotationPoint(0.0F, 8.0F, 0.0F);
handRight.addBox(-2.0F, 0.0F, -2.5F, 4, 4, 5, 0.0F);
setRotationAngle(handRight, 0.0F, 0.0F, -0.05235988F);
fredbody = new ModelRenderer(this, 0, 0);
fredbody.setRotationPoint(0.0F, -9.0F, 0.0F);
fredbody.addBox(-1.0F, -14.0F, -1.0F, 2, 24, 2, 0.0F);
fredhead = new ModelRenderer(this, 39, 22);
fredhead.setRotationPoint(0.0F, -13.0F, -0.5F);
fredhead.addBox(-5.5F, -8.0F, -4.5F, 11, 8, 9, 0.0F);
legRightpad = new ModelRenderer(this, 73, 33);
legRightpad.setRotationPoint(0.0F, 0.5F, 0.0F);
legRightpad.addBox(-3.0F, 0.0F, -3.0F, 6, 9, 6, 0.0F);
frednose = new ModelRenderer(this, 17, 67);
frednose.setRotationPoint(0.0F, -2.0F, -4.5F);
frednose.addBox(-4.0F, -2.0F, -3.0F, 8, 4, 3, 0.0F);
legLeftpad2 = new ModelRenderer(this, 16, 50);
legLeftpad2.setRotationPoint(0.0F, 0.5F, 0.0F);
legLeftpad2.addBox(-2.5F, 0.0F, -3.0F, 5, 7, 6, 0.0F);
armRightpad = new ModelRenderer(this, 70, 10);
armRightpad.setRotationPoint(0.0F, 0.5F, 0.0F);
armRightpad.addBox(-2.5F, 0.0F, -2.5F, 5, 9, 5, 0.0F);
armLeftpad = new ModelRenderer(this, 38, 54);
armLeftpad.setRotationPoint(0.0F, 0.5F, 0.0F);
armLeftpad.addBox(-2.5F, 0.0F, -2.5F, 5, 9, 5, 0.0F);
hat2 = new ModelRenderer(this, 78, 61);
hat2.setRotationPoint(0.0F, 0.1F, 0.0F);
hat2.addBox(-2.0F, -4.0F, -2.0F, 4, 4, 4, 0.0F);
setRotationAngle(hat2, -0.017453292F, 0.0F, 0.0F);
legRightpad2 = new ModelRenderer(this, 0, 39);
legRightpad2.setRotationPoint(0.0F, 0.5F, 0.0F);
legRightpad2.addBox(-2.5F, 0.0F, -3.0F, 5, 7, 6, 0.0F);
jaw = new ModelRenderer(this, 49, 65);
jaw.setRotationPoint(0.0F, 0.5F, 0.0F);
jaw.addBox(-5.0F, 0.0F, -4.5F, 10, 3, 9, 0.0F);
setRotationAngle(jaw, 0.08726646F, 0.0F, 0.0F);
armRight = new ModelRenderer(this, 48, 0);
armRight.setRotationPoint(-6.5F, -8.0F, 0.0F);
armRight.addBox(-1.0F, 0.0F, -1.0F, 2, 10, 2, 0.0F);
setRotationAngle(armRight, 0.0F, 0.0F, 0.2617994F);
footLeft = new ModelRenderer(this, 72, 50);
footLeft.setRotationPoint(0.0F, 8.0F, 0.0F);
footLeft.addBox(-2.5F, 0.0F, -6.0F, 5, 3, 8, 0.0F);
setRotationAngle(footLeft, -0.034906585F, 0.0F, 0.0F);
earLeft = new ModelRenderer(this, 40, 0);
earLeft.setRotationPoint(4.5F, -5.5F, 0.0F);
earLeft.addBox(-1.0F, -3.0F, -0.5F, 2, 3, 1, 0.0F);
setRotationAngle(earLeft, 0.05235988F, 0.0F, 1.0471976F);
legRight2.addChild(footRight);
fredhead.addChild(earRight);
legLeft.addChild(legLeftpad);
earLeft.addChild(earRightpad_1);
fredbody.addChild(legLeft);
armRight2.addChild(armRightpad2);
armLeft2.addChild(handLeft);
fredbody.addChild(armLeft);
fredbody.addChild(legRight);
armLeft.addChild(armLeft2);
legRight.addChild(legRight2);
armLeft2.addChild(armLeftpad2);
legLeft.addChild(legLeft2);
fredhead.addChild(hat);
earRight.addChild(earRightpad);
fredbody.addChild(crotch);
fredbody.addChild(torso);
armRight.addChild(armRight2);
armRight2.addChild(handRight);
fredbody.addChild(fredhead);
legRight.addChild(legRightpad);
fredhead.addChild(frednose);
legLeft2.addChild(legLeftpad2);
armRight.addChild(armRightpad);
armLeft.addChild(armLeftpad);
hat.addChild(hat2);
legRight2.addChild(legRightpad2);
fredhead.addChild(jaw);
fredbody.addChild(armRight);
legLeft2.addChild(footLeft);
fredhead.addChild(earLeft);
}
public void renderCustom(final Entity entityIn, final float limbSwing, final float limbSwingAmount, final float ageInTicks,
final float netHeadYaw, final float headPitch, final float scale) {
if (left_leg == null) {
generateModel();
}
final CustomModel customModel = CustomModel.INSTANCE;
GlStateManager.pushMatrix();
if (customModel.getState() && customModel.getMode().contains("Rabbit")) {
GlStateManager.pushMatrix();
GlStateManager.scale(1.25D, 1.25D, 1.25D);
GlStateManager.translate(0.0D, -0.3D, 0.0D);
rabbitHead.rotateAngleX = bipedHead.rotateAngleX;
rabbitHead.rotateAngleY = bipedHead.rotateAngleY;
rabbitHead.rotateAngleZ = bipedHead.rotateAngleZ;
rabbitLarm.rotateAngleX = bipedLeftArm.rotateAngleX;
rabbitLarm.rotateAngleY = bipedLeftArm.rotateAngleY;
rabbitLarm.rotateAngleZ = bipedLeftArm.rotateAngleZ;
rabbitRarm.rotateAngleX = bipedRightArm.rotateAngleX;
rabbitRarm.rotateAngleY = bipedRightArm.rotateAngleY;
rabbitRarm.rotateAngleZ = bipedRightArm.rotateAngleZ;
rabbitRleg.rotateAngleX = bipedRightLeg.rotateAngleX;
rabbitRleg.rotateAngleY = bipedRightLeg.rotateAngleY;
rabbitRleg.rotateAngleZ = bipedRightLeg.rotateAngleZ;
rabbitLleg.rotateAngleX = bipedLeftLeg.rotateAngleX;
rabbitLleg.rotateAngleY = bipedLeftLeg.rotateAngleY;
rabbitLleg.rotateAngleZ = bipedLeftLeg.rotateAngleZ;
rabbitBone.render(scale);
GlStateManager.popMatrix();
} else if (customModel.getState() && customModel.getMode().contains("Freddy")) {
fredhead.rotateAngleX = bipedHead.rotateAngleX;
fredhead.rotateAngleY = bipedHead.rotateAngleY;
fredhead.rotateAngleZ = bipedHead.rotateAngleZ;
armLeft.rotateAngleX = bipedLeftArm.rotateAngleX;
armLeft.rotateAngleY = bipedLeftArm.rotateAngleY;
armLeft.rotateAngleZ = bipedLeftArm.rotateAngleZ;
legRight.rotateAngleX = bipedRightLeg.rotateAngleX;
legRight.rotateAngleY = bipedRightLeg.rotateAngleY;
legRight.rotateAngleZ = bipedRightLeg.rotateAngleZ;
legLeft.rotateAngleX = bipedLeftLeg.rotateAngleX;
legLeft.rotateAngleY = bipedLeftLeg.rotateAngleY;
legLeft.rotateAngleZ = bipedLeftLeg.rotateAngleZ;
armRight.rotateAngleX = bipedRightArm.rotateAngleX;
armRight.rotateAngleY = bipedRightArm.rotateAngleY;
armRight.rotateAngleZ = bipedRightArm.rotateAngleZ;
GlStateManager.pushMatrix();
GlStateManager.scale(0.75, 0.65, 0.75);
GlStateManager.translate(0.0, 0.85, 0.0);
fredbody.render(scale);
GlStateManager.popMatrix();
} else if (customModel.getState() && customModel.getMode().contains("Imposter")) {
bipedHead.rotateAngleY = netHeadYaw * 0.017453292F;
bipedHead.rotateAngleX = headPitch * 0.017453292F;
bipedBody.rotateAngleY = 0.0F;
final float f = 1.0F;
right_leg.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount / f;
left_leg.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + 3.1415927F) * 1.4F * limbSwingAmount / f;
right_leg.rotateAngleY = 0.0F;
left_leg.rotateAngleY = 0.0F;
right_leg.rotateAngleZ = 0.0F;
left_leg.rotateAngleZ = 0.0F;
int bodyCustomColor = new Color(197, 16, 17).getRGB();
int eyeCustomColor = new Color(254, 254, 254).getRGB();
int legsCustomColor = new Color(122, 7, 56).getRGB();
if (this.isChild) {
GlStateManager.scale(0.5F, 0.5F, 0.5F);
GlStateManager.translate(0.0F, 24.0F * scale, 0.0F);
body.render(scale);
left_leg.render(scale);
right_leg.render(scale);
} else {
GlStateManager.translate(0.0D, -0.8D, 0.0D);
GlStateManager.scale(1.8D, 1.6D, 1.6D);
RenderUtils.INSTANCE.color(bodyCustomColor);
GlStateManager.translate(0.0D, 0.15D, 0.0D);
body.render(scale);
RenderUtils.INSTANCE.color(eyeCustomColor);
eye.render(scale);
RenderUtils.INSTANCE.color(legsCustomColor);
GlStateManager.translate(0.0D, -0.15D, 0.0D);
left_leg.render(scale);
right_leg.render(scale);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
}
}
if (customModel.getState() && customModel.getMode().contains("Female")) {
renderFemale(entityIn, scale);
}
GlStateManager.popMatrix();
}
private boolean bindChestArmorTexture(EntityPlayer player) {
ItemStack chest = player.inventory.armorInventory[2];
if (chest != null && chest.getItem() instanceof ItemArmor) {
ItemArmor armor = (ItemArmor) chest.getItem();
String mat = armor.getArmorMaterial().getName().toLowerCase();
ResourceLocation tex = new ResourceLocation("textures/models/armor/" + mat + "_layer_1.png");
Minecraft.getMinecraft().getTextureManager().bindTexture(tex);
if (armor.getArmorMaterial() == ItemArmor.ArmorMaterial.LEATHER) {
int c = armor.getColor(chest);
float r = (float)(c >> 16 & 255) / 255.0F;
float g = (float)(c >> 8 & 255) / 255.0F;
float b = (float)(c & 255) / 255.0F;
GlStateManager.color(r, g, b, 1.0F);
} else {
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
}
return true;
}
return false;
}
private void rebindPlayerSkin(AbstractClientPlayer player) {
Minecraft.getMinecraft().getTextureManager().bindTexture(player.getLocationSkin());
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
}
private void renderFemale(final Entity entityIn, final float scale) {
if (!(entityIn instanceof EntityPlayer)) return;
final EntityPlayer player = (EntityPlayer) entityIn;
if (CustomModel.INSTANCE.getBreastNoArmor()) {
for (ItemStack stack : player.inventory.armorInventory) {
if (stack != null) return;
}
}
if (bT1 == null) {
bT1 = new ModelRenderer(this, 20, 20); bT1.addBox(-3.0F, 1.0F, -3.0F, 6, 1, 1, 0.0F);
bT2 = new ModelRenderer(this, 19, 21); bT2.addBox(-4.0F, 2.0F, -3.0F, 8, 3, 1, 0.0F);
bF1 = new ModelRenderer(this, 20, 21); bF1.addBox(-3.0F, 2.0F, -4.0F, 6, 1, 1, 0.0F);
bF2 = new ModelRenderer(this, 19, 22); bF2.addBox(-4.0F, 3.0F, -4.0F, 8, 1, 1, 0.0F);
bF3 = new ModelRenderer(this, 20, 23); bF3.addBox(-3.0F, 4.0F, -4.0F, 2, 1, 1, 0.0F);
bF4 = new ModelRenderer(this, 23, 23); bF4.addBox( 1.0F, 4.0F, -4.0F, 2, 1, 1, 0.0F);
}
final float rotationDegrees = CustomModel.INSTANCE.getBreastRotation();
boolean usingArmorTex = bindChestArmorTexture(player);
GlStateManager.pushMatrix();
GlStateManager.rotate(rotationDegrees, 1.0F, 0.0F, 0.0F);
if (!CustomModel.INSTANCE.getBreastPhysics()) {
bT1.rotationPointY = 0.0F;
bT2.rotationPointY = 0.0F;
bF1.rotationPointY = 0.0F;
bF2.rotationPointY = 0.0F;
bF3.rotationPointY = 0.0F;
bF4.rotationPointY = 0.0F;
bT1.render(scale);
bT2.render(scale);
bF1.render(scale);
bF2.render(scale);
bF3.render(scale);
bF4.render(scale);
} else {
final float gravity = CustomModel.INSTANCE.getBreastGravity();
final float bounce = CustomModel.INSTANCE.getBreastBounce();
breastOffsetT1 += (0 - breastOffsetT1) * gravity;
breastOffsetT2 += (0 - breastOffsetT2) * gravity;
breastOffsetF1 += (0 - breastOffsetF1) * gravity;
breastOffsetF2 += (0 - breastOffsetF2) * gravity;
breastOffsetF3 += (0 - breastOffsetF3) * gravity;
breastOffsetF4 += (0 - breastOffsetF4) * gravity;
if (entityIn.motionY > 0.0D) {
float jumpForce = (float) entityIn.motionY * 0.5F;
breastOffsetT1 -= jumpForce * bounce;
breastOffsetT2 -= jumpForce * bounce;
breastOffsetF1 -= jumpForce * bounce;
breastOffsetF2 -= jumpForce * bounce;
breastOffsetF3 -= jumpForce * bounce;
breastOffsetF4 -= jumpForce * bounce;
}
bT1.rotationPointY = breastOffsetT1; bT1.render(scale);
bT2.rotationPointY = breastOffsetT2; bT2.render(scale);
bF1.rotationPointY = breastOffsetF1; bF1.render(scale);
bF2.rotationPointY = breastOffsetF2; bF2.render(scale);
bF3.rotationPointY = breastOffsetF3; bF3.render(scale);
bF4.rotationPointY = breastOffsetF4; bF4.render(scale);
}
GlStateManager.popMatrix();
if (usingArmorTex && player instanceof AbstractClientPlayer) {
rebindPlayerSkin((AbstractClientPlayer) player);
}
}
@Inject(method = "setRotationAngles", at = @At("RETURN"))
private void revertSwordAnimation(final float p1, final float p2, final float p3, final float p4,
final float p5, final float p6, final Entity entity, final CallbackInfo callbackInfo) {
EventManager.INSTANCE.call(new UpdateModelEvent((EntityPlayer) entity, (ModelPlayer) (Object) this));
}
} | 0 | 0.80015 | 1 | 0.80015 | game-dev | MEDIA | 0.737287 | game-dev,graphics-rendering | 0.947609 | 1 | 0.947609 |
longturn/freeciv21 | 4,853 | common/movement.h | // SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Freeciv21 and Freeciv Contributors
#pragma once
// common
#include "fc_types.h"
#include "map_types.h" // struct civ_map
#include "tile.h" // struct tile
#define SINGLE_MOVE (terrain_control.move_fragments)
#define MOVE_COST_IGTER (terrain_control.igter_cost)
// packets.def MOVEFRAGS
#define MAX_MOVE_FRAGS 65535
struct unit_type;
struct terrain;
enum unit_move_result {
MR_OK,
MR_DEATH,
MR_PAUSE,
MR_NO_WAR, // Can't move here without declaring war.
MR_PEACE, // Can't move here because of a peace treaty.
MR_ZOC,
MR_BAD_ACTIVITY,
MR_BAD_DESTINATION,
MR_BAD_MAP_POSITION,
MR_DESTINATION_OCCUPIED_BY_NON_ALLIED_UNIT,
MR_NO_TRANSPORTER_CAPACITY,
MR_TRIREME,
MR_CANNOT_DISEMBARK,
MR_NON_NATIVE_MOVE, // Usually RMM_RELAXED road diagonally without link
MR_ANIMAL_DISALLOWED,
MR_UNIT_STAY,
MR_NOT_ALLOWED
};
int utype_move_rate(const struct unit_type *utype, const struct tile *ptile,
const struct player *pplayer, int veteran_level,
int hitpoints);
int unit_move_rate(const struct unit *punit);
int utype_unknown_move_cost(const struct unit_type *utype);
bool unit_can_defend_here(const struct civ_map *nmap,
const struct unit *punit);
bool can_attack_non_native(const struct unit_type *utype);
bool can_attack_from_non_native(const struct unit_type *utype);
bool is_city_channel_tile(const struct unit_class *punitclass,
const struct tile *ptile,
const struct tile *pexclude);
bool is_native_tile(const struct unit_type *punittype,
const struct tile *ptile);
bool is_native_to_class(const struct unit_class *punitclass,
const struct terrain *pterrain,
const bv_extras *extras);
/****************************************************************************
Check if this tile is native to given unit class.
See is_native_to_class()
****************************************************************************/
static inline bool
is_native_tile_to_class(const struct unit_class *punitclass,
const struct tile *ptile)
{
return is_native_to_class(punitclass, tile_terrain(ptile),
tile_extras(ptile));
}
bool is_native_move(const struct unit_class *punitclass,
const struct tile *src_tile,
const struct tile *dst_tile);
bool is_native_near_tile(const struct civ_map *nmap,
const struct unit_class *uclass,
const struct tile *ptile);
bool can_exist_at_tile(const struct civ_map *nmap,
const struct unit_type *utype,
const struct tile *ptile);
bool can_unit_exist_at_tile(const struct civ_map *nmap,
const struct unit *punit,
const struct tile *ptile);
bool can_unit_survive_at_tile(const struct civ_map *nmap,
const struct unit *punit,
const struct tile *ptile);
bool can_step_taken_wrt_to_zoc(const struct unit_type *punittype,
const struct player *unit_owner,
const struct tile *src_tile,
const struct tile *dst_tile,
const struct civ_map *zmap);
bool unit_can_move_to_tile(const struct civ_map *nmap,
const struct unit *punit,
const struct tile *ptile, bool igzoc,
bool enter_enemy_city);
enum unit_move_result
unit_move_to_tile_test(const struct civ_map *nmap, const struct unit *punit,
enum unit_activity activity,
const struct tile *src_tile,
const struct tile *dst_tile, bool igzoc,
struct unit *embark_to, bool enter_enemy_city);
bool can_unit_transport(const struct unit *transporter,
const struct unit *transported);
bool can_unit_type_transport(const struct unit_type *transporter,
const struct unit_class *transported);
bool unit_can_load(const struct unit *punit);
bool unit_could_load_at(const struct unit *punit, const struct tile *ptile);
bool is_unit_being_refueled(const struct unit *punit);
bool is_airunit_refuel_point(const struct tile *ptile,
const struct player *pplayer,
const struct unit *punit);
void init_move_fragments();
QString move_points_text_full(int mp, bool reduce, const char *prefix,
const char *none, bool align);
QString move_points_text(int mp, bool reduce);
| 0 | 0.869858 | 1 | 0.869858 | game-dev | MEDIA | 0.469175 | game-dev | 0.706974 | 1 | 0.706974 |
reactiveui/Pharmacist | 8,302 | src/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeParameter.cs | // Copyright (c) 2018 Daniel Grunwald
//
// 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.
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.TypeSystem.Implementation
{
sealed class MetadataTypeParameter : AbstractTypeParameter
{
readonly MetadataModule module;
readonly GenericParameterHandle handle;
readonly GenericParameterAttributes attr;
// lazy-loaded:
IReadOnlyList<TypeConstraint> constraints;
byte unmanagedConstraint = ThreeState.Unknown;
const byte nullabilityNotYetLoaded = 255;
byte nullabilityConstraint = nullabilityNotYetLoaded;
public static ITypeParameter[] Create(MetadataModule module, ITypeDefinition copyFromOuter, IEntity owner, GenericParameterHandleCollection handles)
{
if (handles.Count == 0)
return Empty<ITypeParameter>.Array;
var outerTps = copyFromOuter.TypeParameters;
var tps = new ITypeParameter[handles.Count];
var i = 0;
foreach (var handle in handles)
{
if (i < outerTps.Count)
tps[i] = outerTps[i];
else
tps[i] = Create(module, owner, i, handle);
i++;
}
return tps;
}
public static ITypeParameter[] Create(MetadataModule module, IEntity owner, GenericParameterHandleCollection handles)
{
if (handles.Count == 0)
return Empty<ITypeParameter>.Array;
var tps = new ITypeParameter[handles.Count];
var i = 0;
foreach (var handle in handles)
{
tps[i] = Create(module, owner, i, handle);
i++;
}
return tps;
}
public static MetadataTypeParameter Create(MetadataModule module, IEntity owner, int index, GenericParameterHandle handle)
{
var metadata = module.metadata;
var gp = metadata.GetGenericParameter(handle);
Debug.Assert(gp.Index == index);
return new MetadataTypeParameter(module, owner, index, module.GetString(gp.Name), handle, gp.Attributes);
}
private MetadataTypeParameter(MetadataModule module, IEntity owner, int index, string name,
GenericParameterHandle handle, GenericParameterAttributes attr)
: base(owner, index, name, GetVariance(attr))
{
this.module = module;
this.handle = handle;
this.attr = attr;
}
private static VarianceModifier GetVariance(GenericParameterAttributes attr)
{
switch (attr & GenericParameterAttributes.VarianceMask)
{
case GenericParameterAttributes.Contravariant:
return VarianceModifier.Contravariant;
case GenericParameterAttributes.Covariant:
return VarianceModifier.Covariant;
default:
return VarianceModifier.Invariant;
}
}
public GenericParameterHandle MetadataToken => handle;
public override IEnumerable<IAttribute> GetAttributes()
{
var metadata = module.metadata;
var gp = metadata.GetGenericParameter(handle);
var attributes = gp.GetCustomAttributes();
var b = new AttributeListBuilder(module, attributes.Count);
b.Add(attributes, SymbolKind.TypeParameter);
return b.Build();
}
public override bool HasDefaultConstructorConstraint => (attr & GenericParameterAttributes.DefaultConstructorConstraint) != 0;
public override bool HasReferenceTypeConstraint => (attr & GenericParameterAttributes.ReferenceTypeConstraint) != 0;
public override bool HasValueTypeConstraint => (attr & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0;
public override bool HasUnmanagedConstraint {
get {
if (unmanagedConstraint == ThreeState.Unknown)
{
unmanagedConstraint = ThreeState.From(LoadUnmanagedConstraint());
}
return unmanagedConstraint == ThreeState.True;
}
}
private bool LoadUnmanagedConstraint()
{
var metadata = module.metadata;
var gp = metadata.GetGenericParameter(handle);
return gp.GetCustomAttributes().HasKnownAttribute(metadata, KnownAttribute.IsUnmanaged);
}
public override Nullability NullabilityConstraint {
get {
if (nullabilityConstraint == nullabilityNotYetLoaded)
{
nullabilityConstraint = (byte)LoadNullabilityConstraint();
}
return (Nullability)nullabilityConstraint;
}
}
Nullability LoadNullabilityConstraint()
{
if (!module.ShouldDecodeNullableAttributes(Owner))
return Nullability.Oblivious;
var metadata = module.metadata;
var gp = metadata.GetGenericParameter(handle);
foreach (var handle in gp.GetCustomAttributes())
{
var customAttribute = metadata.GetCustomAttribute(handle);
if (customAttribute.IsKnownAttribute(metadata, KnownAttribute.Nullable))
{
var attrVal = customAttribute.DecodeValue(module.TypeProvider);
if (attrVal.FixedArguments.Length == 1)
{
if (attrVal.FixedArguments[0].Value is byte b && b <= 2)
{
return (Nullability)b;
}
}
}
}
if (Owner is MetadataMethod method)
{
return method.NullableContext;
}
else if (Owner is ITypeDefinition td)
{
return td.NullableContext;
}
else
{
return Nullability.Oblivious;
}
}
public override IReadOnlyList<TypeConstraint> TypeConstraints {
get {
var constraints = LazyInit.VolatileRead(ref this.constraints);
if (constraints == null)
{
constraints = LazyInit.GetOrSet(ref this.constraints, DecodeConstraints());
}
return constraints;
}
}
private IReadOnlyList<TypeConstraint> DecodeConstraints()
{
var metadata = module.metadata;
var gp = metadata.GetGenericParameter(handle);
Nullability nullableContext;
if (Owner is ITypeDefinition typeDef)
{
nullableContext = typeDef.NullableContext;
}
else if (Owner is MetadataMethod method)
{
nullableContext = method.NullableContext;
}
else
{
nullableContext = Nullability.Oblivious;
}
var constraintHandleCollection = gp.GetConstraints();
var result = new List<TypeConstraint>(constraintHandleCollection.Count + 1);
var hasNonInterfaceConstraint = false;
foreach (var constraintHandle in constraintHandleCollection)
{
var constraint = metadata.GetGenericParameterConstraint(constraintHandle);
var attrs = constraint.GetCustomAttributes();
var ty = module.ResolveType(constraint.Type, new GenericContext(Owner), attrs, nullableContext);
if (attrs.Count == 0)
{
result.Add(new TypeConstraint(ty));
}
else
{
var b = new AttributeListBuilder(module);
b.Add(attrs, SymbolKind.Constraint);
result.Add(new TypeConstraint(ty, b.Build()));
}
hasNonInterfaceConstraint |= (ty.Kind != TypeKind.Interface);
}
if (this.HasValueTypeConstraint)
{
result.Add(new TypeConstraint(Compilation.FindType(KnownTypeCode.ValueType)));
}
else if (!hasNonInterfaceConstraint)
{
result.Add(new TypeConstraint(Compilation.FindType(KnownTypeCode.Object)));
}
return result;
}
public override int GetHashCode()
{
return 0x51fc5b83 ^ module.PEFile.GetHashCode() ^ handle.GetHashCode();
}
public override bool Equals(IType other)
{
return other is MetadataTypeParameter tp && handle == tp.handle && module.PEFile == tp.module.PEFile;
}
public override string ToString()
{
return $"{MetadataTokens.GetToken(handle):X8} {ReflectionName}";
}
}
}
| 0 | 0.92558 | 1 | 0.92558 | game-dev | MEDIA | 0.36465 | game-dev | 0.906788 | 1 | 0.906788 |
Ravaelles/Atlantis | 6,676 | jps/main/java/jps/Graph.java | package jps.main.java.jps;
import java.util.*;
import java.util.function.BiFunction;
/**
* @author Kevin
*/
public class Graph<T extends Node> {
public enum Diagonal {
ALWAYS,
NO_OBSTACLES,
ONE_OBSTACLE,
NEVER
}
private List<T> nodes;
private int width;
private BiFunction<Node, Node, Double> distance = euclidean;
private BiFunction<Node, Node, Double> heuristic = euclidean;
public Graph(List<List<T>> map, DistanceAlgo distance, DistanceAlgo heuristic) {
width = map.get(0).size();
nodes = new ArrayList<>(map.size() * map.get(0).size());
map.forEach(nodes::addAll);
this.distance = distance.algo;
this.heuristic = heuristic.algo;
}
public Graph(T[][] map, DistanceAlgo distance, DistanceAlgo heuristic) {
width = map[0].length;
nodes = new ArrayList<>(map.length * map[0].length);
for (T[] row : map) {
Collections.addAll(nodes, row);
}
this.distance = distance.algo;
this.heuristic = heuristic.algo;
}
/**
* By default, will use EUCLIDEAN for distance and heuristic calculations. You can set your own algorithm
* if you would like to change this.
*/
public Graph(List<List<T>> map) {
width = map.get(0).size();
nodes = new ArrayList<>(map.size() * map.get(0).size());
map.forEach(nodes::addAll);
}
/**
* By default, will use EUCLIDEAN for distance and heuristic calculations. You can set your own algorithm
* if you would like to change this.
*/
public Graph(T[][] map) {
width = map[0].length;
nodes = new ArrayList<>(map.length * map[0].length);
for (T[] row : map) {
Collections.addAll(nodes, row);
}
}
/**
* @return List of all nodes in the graph.
*/
public Collection<T> getNodes() { return nodes; }
public T getNode(int x, int y) {
if (x < 0 || x >= width || y < 0 || y >= nodes.size() / width) {
return null;
}
return nodes.get(x + y*width);
}
/**
* Given two adjacent nodes, returns the distance between them.
* @return The distance between the two nodes given.
*/
public double getDistance(Node a, Node b) { return distance.apply(a, b); }
/**
* Given two nodes, returns the estimated distance between them. Optimizing this is the best way to improve
* performance of your search time.
* @return Estimated distance between the two given nodes.
*/
public double getHeuristicDistance(Node a, Node b) { return heuristic.apply(a, b); }
/**
* By default, we return all reachable diagonal neighbors that have no obstacles blocking us.
* i.e.
* O O G
* O C X
* O O O
*
* In this above example, we could not go diagonally from our (C)urrent position to our (G)oal due to the obstacle (X).
*
* Please use {@link #getNeighborsOf(Node, Diagonal)} method if you would like to specify different diagonal functionality.
*
* @return All reachable neighboring nodes of the given node.
*/
public Collection<T> getNeighborsOf(T node) {
return getNeighborsOf(node, Diagonal.NO_OBSTACLES);
}
/**
* @return All reachable neighboring nodes of the given node.
*/
public Set<T> getNeighborsOf(T node, Diagonal diagonal) {
int x = node.x;
int y = node.y;
Set<T> neighbors = new HashSet<>();
boolean n = false, s = false, e = false, w = false, ne = false, nw = false, se = false, sw = false;
// ?
if (isWalkable(x, y - 1)) {
neighbors.add(getNode(x, y - 1));
n = true;
}
// ?
if (isWalkable(x + 1, y)) {
neighbors.add(getNode(x + 1, y));
e = true;
}
// ?
if (isWalkable(x, y + 1)) {
neighbors.add(getNode(x, y+1));
s = true;
}
// ?
if (isWalkable(x - 1, y)) {
neighbors.add(getNode(x-1, y));
w = true;
}
switch (diagonal) {
case NEVER:
return neighbors;
case NO_OBSTACLES:
ne = n && e;
nw = n && w;
se = s && e;
sw = s && w;
break;
case ONE_OBSTACLE:
ne = n || e;
nw = n || w;
se = s || e;
sw = s || w;
break;
case ALWAYS:
ne = nw = se = sw = true;
}
// ?
if (nw && isWalkable(x - 1, y - 1)) {
neighbors.add(getNode(x - 1, y - 1));
}
// ?
if (ne && isWalkable(x + 1, y - 1)) {
neighbors.add(getNode(x + 1, y - 1));
}
// ?
if (se && isWalkable(x + 1, y + 1)) {
neighbors.add(getNode(x + 1, y + 1));
}
// ?
if (sw && isWalkable(x - 1, y + 1)) {
neighbors.add(getNode(x - 1, y + 1));
}
return neighbors;
}
public boolean isWalkable(int x, int y) {
return x >= 0 && x < width && y >= 0 && y < nodes.size() / width && getNode(x, y).walkable;
}
/**
* If you would like to define your own Distance Algorithm not included.
*/
public void setDistanceAlgo(BiFunction<Node, Node, Double> distance) {
this.distance = distance;
}
/**
* If you would like to define your own Heuristic Algorithm not included.
*/
public void setHeuristicAlgo(BiFunction<Node, Node, Double> heuristic) {
this.heuristic = heuristic;
}
public enum DistanceAlgo {
MANHATTAN(manhattan),
EUCLIDEAN(euclidean),
OCTILE(octile),
CHEBYSHEV(chebyshev);
BiFunction<Node, Node, Double> algo;
DistanceAlgo(BiFunction<Node, Node, Double> algo) {
this.algo = algo;
}
}
private static BiFunction<Node, Node, Double> manhattan = (a, b) -> (double) Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
private static BiFunction<Node, Node, Double> euclidean = (a, b) -> Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
private static BiFunction<Node, Node, Double> octile = (a, b) -> {
double F = Math.sqrt(2) - 1;
double dx = Math.abs(a.x - b.x);
double dy = Math.abs(a.y - b.y);
return (dx < dy) ? F * dx + dy : F * dy + dx;
};
private static BiFunction<Node, Node, Double> chebyshev = (a, b) -> (double) Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y));
}
| 0 | 0.928464 | 1 | 0.928464 | game-dev | MEDIA | 0.432008 | game-dev | 0.945133 | 1 | 0.945133 |
microsoft/MRDL_Unity_LunarModule | 6,756 | Assets/MRDesignLab/HUX/Scripts/Input/WorldCursor.cs | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using UnityEngine;
using System.Collections;
using HUX;
using HUX.Interaction;
using HUX.Focus;
/// <summary>
/// <see cref="MonoBehaviour"/>
///
/// </summary>
public class WorldCursor : MonoBehaviour
{
public float SurfaceRayOffset = 0.1f;
public float CursorSize = 0.02f;
public bool Clamp = false;
public float ClampScale = 1.3f;
public float ScreenClampDotThresh = 0.71f;
public Vector2 DistanceClamp = new Vector2(0.1f, 7.5f);
public float DepthOffset = 0;
public bool AccrueInputsForUpdate;
bool cursorActive;
public bool IsActive
{
get
{
return cursorActive;
}
}
Vector2 accruedDelta;
public Vector2 currentScreenPos;
GameObject pointer;
void Start()
{
pointer = transform.GetChild(0).gameObject;
CenterCursor();
UpdateCursorPlacement();
}
public void AddDepthDelta(float delta)
{
DepthOffset += delta;
//transform.position = CastCursor(HUXGazer.Instance.GetRay());
}
public void SnapToGazeDir()
{
CastCursor(FocusManager.Instance.GazeFocuser.FocusRay);
}
public void ApplyMovementDelta(Vector2 mouseDelta, bool forceApply = false)
{
if (mouseDelta != Vector2.zero)
{
// If desired, just add up the delta inputs to apply once in update, in case there are many inputs each frame
if (AccrueInputsForUpdate && !forceApply)
{
accruedDelta += mouseDelta;
return;
}
//FocusManager focus = FocusManager.Instance;
Transform focusTransform = Veil.Instance.HeadTransform;// focus.GazeTransform;
// Get ray to current mouse pos
Ray newRay = new Ray(focusTransform.transform.position, Vector3.forward);//focus.FocusRay;
Vector3 newDirection = transform.position - newRay.origin;
// Move mouse
float vFov = 0.5f * Mathf.Sin(Mathf.Deg2Rad * Veil.Instance.DeviceFOV);
float hFov = 0.5f * Mathf.Sin(Mathf.Deg2Rad * (Veil.Instance.DeviceFOV * Veil.c_horiz_ratio));
float dist = newDirection.magnitude;
newDirection += dist * (focusTransform.up * mouseDelta.y * vFov + focusTransform.right * mouseDelta.x * hFov);
newDirection.Normalize();
// Clamp direction to screen tho
if (Clamp)
{
// Snap mouse to screen if looking far enough away from mouse
float headMouseDot = Vector3.Dot(newDirection, focusTransform.forward);
if (headMouseDot < Mathf.Max(0, ScreenClampDotThresh))
{
newDirection = focusTransform.forward;
}
// Clamp mouse to view bounds (times a scale) so that we can't move the mouse forever away and have to bring it back
float dot = Vector3.Dot(newDirection, focusTransform.up);
float delta = Mathf.Abs(dot) - vFov * ClampScale;
currentScreenPos.y = dot / vFov;
if (delta > 0)
{
newDirection -= Mathf.Sign(dot) * delta * focusTransform.up;
}
dot = Vector3.Dot(newDirection, focusTransform.right);
delta = Mathf.Abs(dot) - hFov * ClampScale;
currentScreenPos.x = dot / hFov;
if (delta > 0)
{
newDirection -= Mathf.Sign(dot) * delta * focusTransform.right;
}
newDirection.Normalize();
}
// Re-cast with new direction
newRay.direction = newDirection;
transform.position = RaycastPosition(newRay);
UpdateCursorPlacement();
}
}
public void CastCursor(Ray ray)
{
transform.position = RaycastPosition(ray);
UpdateCursorPlacement();
}
void Update()
{
if (AccrueInputsForUpdate && accruedDelta != Vector2.zero)
{
ApplyMovementDelta(accruedDelta, true);
accruedDelta = Vector2.zero;
}
}
public void SetCursorActive(bool active)
{
if (active == cursorActive)
{
return;
}
//Debug.Log("SetMouseCursorActive: " + active);
cursorActive = active;
if (active)
{
pointer.SetActive(true);
CenterCursor();
}
else
{
pointer.SetActive(false);
}
}
public void SetCursorPosition(Vector3 worldPos)
{
transform.position = worldPos;
UpdateCursorPlacement();
}
public void CenterCursor()
{
transform.position = FocusManager.Instance.GazeFocuser.TargetOrigin + FocusManager.Instance.GazeFocuser.TargetDirection * 2.5f;
CastCursor(GetRayForScreenPos(Vector2.zero));
}
public Ray GetRayForScreenPos(Vector2 pos)
{
AFocuser focus = FocusManager.Instance.GazeFocuser;
Ray newRay = focus.FocusRay;
float vFov = 0.5f * Mathf.Sin(Mathf.Deg2Rad * Veil.Instance.DeviceFOV);
float hFov = 0.5f * Mathf.Sin(Mathf.Deg2Rad * (Veil.Instance.DeviceFOV * Veil.c_horiz_ratio));
newRay.direction += (focus.TargetOrientation * Vector3.up) * pos.y * vFov + (focus.TargetOrientation * Vector3.right) * pos.x * hFov;
return newRay;
}
public Vector3 RaycastPosition(Ray newRay)
{
AFocuser focus = FocusManager.Instance.GazeFocuser;
Vector3 newPos = Vector3.zero;
RaycastHit newHit;
if (Physics.Raycast(newRay, out newHit))
{
Vector3 backupDir = newHit.point - focus.TargetOrigin;
newPos = newHit.point - backupDir * SurfaceRayOffset;
}
else
{
float currentDepth = Mathf.Clamp((transform.position - focus.TargetOrigin).magnitude, DistanceClamp.x, DistanceClamp.y);
Debug.DrawLine(focus.TargetOrigin, newRay.origin);
newPos = focus.TargetOrigin + newRay.direction * currentDepth;
}
//newPos += newRay.direction * DepthOffset;
return newPos;
}
public void UpdateCursorPlacement()
{
Vector3 vec = transform.position - FocusManager.Instance.GazeFocuser.TargetOrigin;
float dist = vec.magnitude;
transform.localScale = Vector3.one * dist * CursorSize;
if (vec.sqrMagnitude > 0)
{
transform.rotation = Quaternion.LookRotation(vec);
}
}
}
| 0 | 0.939147 | 1 | 0.939147 | game-dev | MEDIA | 0.640738 | game-dev,graphics-rendering | 0.995218 | 1 | 0.995218 |
tgstation/tgstation | 13,326 | code/modules/projectiles/guns/magic/staff.dm | /obj/item/gun/magic/staff
slot_flags = ITEM_SLOT_BACK
ammo_type = /obj/item/ammo_casing/magic/nothing
worn_icon_state = null
icon_state = "staff"
icon_angle = -45
lefthand_file = 'icons/mob/inhands/weapons/staves_lefthand.dmi'
righthand_file = 'icons/mob/inhands/weapons/staves_righthand.dmi'
item_flags = NEEDS_PERMIT | NO_MAT_REDEMPTION
/// Can non-magic folk use our staff?
/// If FALSE, only wizards or survivalists can use the staff to its full potential - If TRUE, anyone can
var/allow_intruder_use = FALSE
/obj/item/gun/magic/staff/proc/is_wizard_or_friend(mob/user)
if(!HAS_MIND_TRAIT(user, TRAIT_MAGICALLY_GIFTED) && !allow_intruder_use)
return FALSE
return TRUE
/obj/item/gun/magic/staff/can_trigger_gun(mob/living/user, akimbo_usage)
if(akimbo_usage && !is_wizard_or_friend(user))
return FALSE
return ..()
/obj/item/gun/magic/staff/check_botched(mob/living/user, atom/target)
if(!is_wizard_or_friend(user))
return !on_intruder_use(user, target)
return ..()
/// Called when someone who isn't a wizard or magician uses this staff.
/// Return TRUE to allow usage.
/obj/item/gun/magic/staff/proc/on_intruder_use(mob/living/user, atom/target)
return TRUE
/obj/item/gun/magic/staff/change
name = "staff of change"
desc = "An artefact that spits bolts of coruscating energy which cause the target's very form to reshape itself."
fire_sound = 'sound/effects/magic/staff_change.ogg'
ammo_type = /obj/item/ammo_casing/magic/change
icon_state = "staffofchange"
inhand_icon_state = "staffofchange"
school = SCHOOL_TRANSMUTATION
/// If set, all wabbajacks this staff produces will be of this type, instead of random
var/preset_wabbajack_type
/// If set, all wabbajacks this staff produces will be of this changeflag, instead of only WABBAJACK
var/preset_wabbajack_changeflag
/obj/item/gun/magic/staff/change/unrestricted
allow_intruder_use = TRUE
/obj/item/gun/magic/staff/change/pickup(mob/user)
. = ..()
if(!is_wizard_or_friend(user))
to_chat(user, span_hypnophrase("<span style='font-size: 24px'>You don't feel strong enough to properly wield this staff!</span>"))
balloon_alert(user, "you feel weak holding this staff")
/obj/item/gun/magic/staff/change/on_intruder_use(mob/living/user, atom/target)
user.dropItemToGround(src, TRUE)
var/wabbajack_into = preset_wabbajack_type || pick(WABBAJACK_MONKEY, WABBAJACK_HUMAN, WABBAJACK_ANIMAL)
var/mob/living/new_body = user.wabbajack(wabbajack_into, preset_wabbajack_changeflag)
if(!new_body)
return
balloon_alert(new_body, "wabbajack, wabbajack!")
/obj/item/gun/magic/staff/animate
name = "staff of animation"
desc = "An artefact that spits bolts of life-force which causes objects which are hit by it to animate and come to life! This magic doesn't affect machines."
fire_sound = 'sound/effects/magic/staff_animation.ogg'
ammo_type = /obj/item/ammo_casing/magic/animate
icon_state = "staffofanimation"
inhand_icon_state = "staffofanimation"
school = SCHOOL_EVOCATION
/obj/item/gun/magic/staff/healing
name = "staff of healing"
desc = "An artefact that spits bolts of restoring magic which can remove ailments of all kinds and even raise the dead."
fire_sound = 'sound/effects/magic/staff_healing.ogg'
ammo_type = /obj/item/ammo_casing/magic/heal
icon_state = "staffofhealing"
inhand_icon_state = "staffofhealing"
school = SCHOOL_RESTORATION
/// Our internal healbeam, used if an intruder (non-magic person) tries to use our staff
var/obj/item/gun/medbeam/healing_beam
/obj/item/gun/magic/staff/healing/pickup(mob/user)
. = ..()
if(!is_wizard_or_friend(user))
to_chat(user, span_hypnophrase("<span style='font-size: 24px'>The staff feels weaker as you touch it</span>"))
user.balloon_alert(user, "the staff feels weaker as you touch it")
/obj/item/gun/magic/staff/healing/examine(mob/user)
. = ..()
if(!is_wizard_or_friend(user))
. += span_notice("On the handle you notice a beautiful engraving in High Spaceman, \"Thou shalt not crosseth thy beams.\"")
/obj/item/gun/magic/staff/healing/Initialize(mapload)
. = ..()
healing_beam = new(src)
healing_beam.mounted = TRUE
/obj/item/gun/magic/staff/healing/Destroy()
QDEL_NULL(healing_beam)
return ..()
/obj/item/gun/magic/staff/healing/unrestricted
allow_intruder_use = TRUE
/obj/item/gun/magic/staff/healing/on_intruder_use(mob/living/user, atom/target)
if(target == user)
return FALSE
healing_beam.process_fire(target, user)
return FALSE
/obj/item/gun/magic/staff/healing/dropped(mob/user)
healing_beam.LoseTarget()
return ..()
/obj/item/gun/magic/staff/healing/handle_suicide() //Stops people trying to commit suicide to heal themselves
return
/obj/item/gun/magic/staff/chaos
name = "staff of chaos"
desc = "An artefact that spits bolts of chaotic magic that can potentially do anything."
fire_sound = 'sound/effects/magic/staff_chaos.ogg'
ammo_type = /obj/item/ammo_casing/magic/chaos
icon_state = "staffofchaos"
inhand_icon_state = "staffofchaos"
max_charges = 10
recharge_rate = 2
no_den_usage = 1
school = SCHOOL_FORBIDDEN //this staff is evil. okay? it just is. look at this projectile type list. this is wrong.
/// List of all projectiles we can fire from our staff.
/// Doesn't contain all subtypes of magic projectiles, unlike what it looks like
var/list/allowed_projectile_types = list(
/obj/projectile/magic/animate,
/obj/projectile/magic/antimagic,
/obj/projectile/magic/arcane_barrage,
/obj/projectile/magic/bounty,
/obj/projectile/magic/change,
/obj/projectile/magic/death,
/obj/projectile/magic/door,
/obj/projectile/magic/fetch,
/obj/projectile/magic/fireball,
/obj/projectile/magic/flying,
/obj/projectile/magic/locker,
/obj/projectile/magic/necropotence,
/obj/projectile/magic/resurrection,
/obj/projectile/magic/babel,
/obj/projectile/magic/spellblade,
/obj/projectile/magic/teleport,
/obj/projectile/magic/wipe,
/obj/projectile/temp/chill,
/obj/projectile/magic/shrink
)
/obj/item/gun/magic/staff/chaos/unrestricted
allow_intruder_use = TRUE
/obj/item/gun/magic/staff/chaos/process_fire(atom/target, mob/living/user, message = TRUE, params = null, zone_override = "", bonus_spread = 0)
chambered.projectile_type = pick(allowed_projectile_types)
return ..()
/obj/item/gun/magic/staff/chaos/on_intruder_use(mob/living/user)
if(!user.can_cast_magic()) // Don't let people with antimagic use the staff of chaos.
balloon_alert(user, "the staff refuses to fire!")
return FALSE
if(prob(95)) // You have a 5% chance of hitting yourself when using the staff of chaos.
return TRUE
balloon_alert(user, "chaos!")
user.dropItemToGround(src, TRUE)
process_fire(user, user, FALSE)
return FALSE
/**
* Staff of chaos given to the wizard upon completing a cheesy grand ritual. Is completely evil and if something
* breaks, it's completely intended. Fuck off.
* Also can be used by everyone, because why not.
*/
/obj/item/gun/magic/staff/chaos/true_wabbajack
name = "\proper Wabbajack"
desc = "If there is some deity out there, they've definitely skipped their psych appointment before creating this."
icon_state = "the_wabbajack"
inhand_icon_state = "the_wabbajack"
resistance_flags = INDESTRUCTIBLE | LAVA_PROOF | FIRE_PROOF | UNACIDABLE | ACID_PROOF //fuck you
max_charges = 999999 //fuck you
recharge_rate = 1
allow_intruder_use = TRUE
/obj/item/gun/magic/staff/chaos/true_wabbajack/Initialize(mapload)
. = ..()
allowed_projectile_types |= subtypesof(/obj/projectile/bullet/cannonball)
allowed_projectile_types |= subtypesof(/obj/projectile/bullet/rocket)
allowed_projectile_types |= subtypesof(/obj/projectile/energy/tesla)
allowed_projectile_types |= subtypesof(/obj/projectile/magic)
allowed_projectile_types |= subtypesof(/obj/projectile/temp)
allowed_projectile_types |= list(
/obj/projectile/beam/mindflayer,
/obj/projectile/bullet/gyro,
/obj/projectile/bullet/honker,
/obj/projectile/bullet/mime,
/obj/projectile/curse_hand,
/obj/projectile/energy/electrode,
/obj/projectile/energy/nuclear_particle,
/obj/projectile/gravityattract,
/obj/projectile/gravitychaos,
/obj/projectile/gravityrepulse,
/obj/projectile/ion,
/obj/projectile/meteor,
/obj/projectile/neurotoxin,
/obj/projectile/plasma,
) //if you ever try to expand this list, avoid adding bullets/energy projectiles, this ain't supposed to be a gun... unless it's funny
/obj/item/gun/magic/staff/door
name = "staff of door creation"
desc = "An artefact that spits bolts of transformative magic that can create doors in walls."
fire_sound = 'sound/effects/magic/staff_door.ogg'
ammo_type = /obj/item/ammo_casing/magic/door
icon_state = "staffofdoor"
inhand_icon_state = "staffofdoor"
max_charges = 10
recharge_rate = 2
no_den_usage = 1
school = SCHOOL_TRANSMUTATION
/obj/item/gun/magic/staff/honk
name = "staff of the honkmother"
desc = "Honk."
fire_sound = 'sound/items/airhorn/airhorn.ogg'
ammo_type = /obj/item/ammo_casing/magic/honk
icon_state = "honker"
inhand_icon_state = "honker"
max_charges = 4
recharge_rate = 8
school = SCHOOL_EVOCATION
/obj/item/gun/magic/staff/spellblade
name = "spellblade"
desc = "A deadly combination of laziness and bloodlust, this blade allows the user to dismember their enemies without all the hard work of actually swinging the sword."
fire_sound = 'sound/effects/magic/fireball.ogg'
ammo_type = /obj/item/ammo_casing/magic/spellblade
icon_state = "spellblade"
inhand_icon_state = "spellblade"
icon_angle = -45
lefthand_file = 'icons/mob/inhands/weapons/swords_lefthand.dmi'
righthand_file = 'icons/mob/inhands/weapons/swords_righthand.dmi'
hitsound = 'sound/items/weapons/rapierhit.ogg'
block_sound = 'sound/items/weapons/parry.ogg'
force = 20
armour_penetration = 75
block_chance = 50
sharpness = SHARP_EDGED
max_charges = 4
school = SCHOOL_EVOCATION
/obj/item/gun/magic/staff/spellblade/Initialize(mapload)
. = ..()
AddComponent(/datum/component/butchering, \
speed = 1.5 SECONDS, \
effectiveness = 125, \
bonus_modifier = 0, \
butcher_sound = hitsound, \
)
/obj/item/gun/magic/staff/spellblade/hit_reaction(mob/living/carbon/human/owner, atom/movable/hitby, attack_text = "the attack", final_block_chance = 0, damage = 0, attack_type = MELEE_ATTACK, damage_type = BRUTE)
if(attack_type == (PROJECTILE_ATTACK || LEAP_ATTACK || OVERWHELMING_ATTACK))
final_block_chance = 0 //Don't bring a sword to a gunfight, and also you aren't going to really block someone full body tackling you with a sword. Or a road roller, if one happened to hit you.
return ..()
/obj/item/gun/magic/staff/locker
name = "staff of the locker"
desc = "An artefact that expels encapsulating bolts, for incapacitating thy enemy."
fire_sound = 'sound/effects/magic/staff_change.ogg'
ammo_type = /obj/item/ammo_casing/magic/locker
icon_state = "locker"
inhand_icon_state = "locker"
worn_icon_state = "lockerstaff"
max_charges = 6
recharge_rate = 4
school = SCHOOL_TRANSMUTATION //in a way
//yes, they don't have sounds. they're admin staves, and their projectiles will play the chaos bolt sound anyway so why bother?
/obj/item/gun/magic/staff/flying
name = "staff of flying"
desc = "An artefact that spits bolts of graceful magic that can make something fly."
fire_sound = 'sound/effects/magic/staff_healing.ogg'
ammo_type = /obj/item/ammo_casing/magic/flying
icon_state = "staffofflight"
inhand_icon_state = "staffofchange"
worn_icon_state = "flightstaff"
school = SCHOOL_EVOCATION
/obj/item/gun/magic/staff/babel
name = "staff of babel"
desc = "An artefact that spits bolts of confusion magic that can make something depressed and incoherent."
fire_sound = 'sound/effects/magic/staff_change.ogg'
ammo_type = /obj/item/ammo_casing/magic/babel
icon_state = "staffofbabel"
inhand_icon_state = "staffofdoor"
worn_icon_state = "babelstaff"
school = SCHOOL_FORBIDDEN //evil
/obj/item/gun/magic/staff/necropotence
name = "staff of necropotence"
desc = "An artefact that spits bolts of death magic that can repurpose the soul."
fire_sound = 'sound/effects/magic/staff_change.ogg'
ammo_type = /obj/item/ammo_casing/magic/necropotence
icon_state = "staffofnecropotence"
inhand_icon_state = "staffofchaos"
worn_icon_state = "necrostaff"
school = SCHOOL_NECROMANCY //REALLY evil
/obj/item/gun/magic/staff/wipe
name = "staff of possession"
desc = "An artefact that spits bolts of mind-unlocking magic that can let ghosts invade the victim's mind."
fire_sound = 'sound/effects/magic/staff_change.ogg'
ammo_type = /obj/item/ammo_casing/magic/wipe
icon_state = "staffofwipe"
inhand_icon_state = "pharoah_sceptre"
worn_icon_state = "wipestaff"
school = SCHOOL_FORBIDDEN //arguably the worst staff in the entire game effect wise
/obj/item/gun/magic/staff/shrink
name = "staff of shrinking"
desc = "An artefact that spits bolts of tiny magic that makes things small. It's easily mistaken for a wand."
fire_sound = 'sound/effects/magic/staff_shrink.ogg'
ammo_type = /obj/item/ammo_casing/magic/shrink
icon_state = "shrinkstaff"
inhand_icon_state = "staff"
max_charges = 10 // slightly more/faster charges since this will be used on walls and such
recharge_rate = 5
no_den_usage = TRUE
school = SCHOOL_TRANSMUTATION
slot_flags = NONE //too small to wear on your back
w_class = WEIGHT_CLASS_NORMAL //but small enough for a bag
| 0 | 0.876192 | 1 | 0.876192 | game-dev | MEDIA | 0.995134 | game-dev | 0.933325 | 1 | 0.933325 |
IndieVisualLab/UnityGraphicsProgramming3 | 1,443 | Assets/Standard Assets/Characters/ThirdPersonCharacter/Scripts/AICharacterControl.cs | using System;
using UnityEngine;
namespace UnityStandardAssets.Characters.ThirdPerson
{
[RequireComponent(typeof (UnityEngine.AI.NavMeshAgent))]
[RequireComponent(typeof (ThirdPersonCharacter))]
public class AICharacterControl : MonoBehaviour
{
public UnityEngine.AI.NavMeshAgent agent { get; private set; } // the navmesh agent required for the path finding
public ThirdPersonCharacter character { get; private set; } // the character we are controlling
public Transform target; // target to aim for
private void Start()
{
// get the components on the object we need ( should not be null due to require component so no need to check )
agent = GetComponentInChildren<UnityEngine.AI.NavMeshAgent>();
character = GetComponent<ThirdPersonCharacter>();
agent.updateRotation = false;
agent.updatePosition = true;
}
private void Update()
{
if (target != null)
agent.SetDestination(target.position);
if (agent.remainingDistance > agent.stoppingDistance)
character.Move(agent.desiredVelocity, false, false);
else
character.Move(Vector3.zero, false, false);
}
public void SetTarget(Transform target)
{
this.target = target;
}
}
}
| 0 | 0.784588 | 1 | 0.784588 | game-dev | MEDIA | 0.978974 | game-dev | 0.896051 | 1 | 0.896051 |
SkelletonX/DDTank4.1 | 1,527 | Source Server/Game.Logic/Game.Logic.PetEffects.Element.Actives/AE1229.cs | using Game.Logic.PetEffects.ContinueElement;
using Game.Logic.Phy.Object;
namespace Game.Logic.PetEffects.Element.Actives
{
public class AE1229 : BasePetEffect
{
private int m_type = 0;
private int m_count = 0;
private int m_probability = 0;
private int m_delay = 0;
private int m_coldDown = 0;
private int m_added = 0;
private int m_currentId;
public AE1229(int count, int probability, int type, int skillId, int delay, string elementID)
: base(ePetEffectType.AE1229, elementID)
{
m_count = count;
m_coldDown = count;
m_probability = ((probability == -1) ? 10000 : probability);
m_type = type;
m_delay = delay;
m_currentId = skillId;
}
public override bool Start(Living living)
{
AE1229 aE = living.PetEffectList.GetOfType(ePetEffectType.AE1229) as AE1229;
if (aE == null)
{
return base.Start(living);
}
aE.m_probability = ((m_probability > aE.m_probability) ? m_probability : aE.m_probability);
return true;
}
protected override void OnAttachedToPlayer(Player player)
{
player.PlayerBuffSkillPet += player_AfterBuffSkillPetByLiving;
}
protected override void OnRemovedFromPlayer(Player player)
{
player.PlayerBuffSkillPet -= player_AfterBuffSkillPetByLiving;
}
private void player_AfterBuffSkillPetByLiving(Player player)
{
if (player.PetEffects.CurrentUseSkill == m_currentId)
{
player.AddPetEffect(new CE1229(2, m_probability, m_type, m_currentId, m_delay, base.ElementInfo.ID.ToString()), 0);
}
}
}
}
| 0 | 0.945038 | 1 | 0.945038 | game-dev | MEDIA | 0.926382 | game-dev | 0.979081 | 1 | 0.979081 |
mirbeta/OpenMir2 | 2,080 | src/Modules/GameCommand/Commands/MapMoveHumanCommand.cs | using SystemModule;
using SystemModule.Actors;
using SystemModule.Enums;
namespace CommandModule.Commands
{
/// <summary>
/// 将指定地图所有玩家随机移动
/// </summary>
[Command("MapMoveHuman", "将指定地图所有玩家随机移动", CommandHelp.GameCommandMapMoveHelpMsg, 10)]
public class MapMoveHumanCommand : GameCommand
{
[ExecuteCommand]
public void Execute(string[] @params, IPlayerActor PlayerActor)
{
if (@params == null)
{
return;
}
string sSrcMap = @params.Length > 0 ? @params[0] : "";
string sDenMap = @params.Length > 1 ? @params[1] : "";
if (string.IsNullOrEmpty(sDenMap) || string.IsNullOrEmpty(sSrcMap) ||
!string.IsNullOrEmpty(sSrcMap) && sSrcMap[0] == '?')
{
PlayerActor.SysMsg(Command.CommandHelp, MsgColor.Red, MsgType.Hint);
return;
}
SystemModule.Maps.IEnvirnoment srcEnvir = SystemShare.MapMgr.FindMap(sSrcMap);
SystemModule.Maps.IEnvirnoment denEnvir = SystemShare.MapMgr.FindMap(sDenMap);
if (srcEnvir == null)
{
PlayerActor.SysMsg(string.Format(CommandHelp.GameCommandMapMoveMapNotFound, sSrcMap), MsgColor.Red,
MsgType.Hint);
return;
}
if (denEnvir == null)
{
PlayerActor.SysMsg(string.Format(CommandHelp.GameCommandMapMoveMapNotFound, sDenMap), MsgColor.Red,
MsgType.Hint);
return;
}
IList<IPlayerActor> humanList = new List<IPlayerActor>();
SystemShare.WorldEngine.GetMapRageHuman(srcEnvir, srcEnvir.Width / 2, srcEnvir.Height / 2, 1000, ref humanList, true);
for (int i = 0; i < humanList.Count; i++)
{
IPlayerActor moveHuman = humanList[i];
if (moveHuman != PlayerActor)
{
moveHuman.MapRandomMove(sDenMap, 0);
}
}
}
}
} | 0 | 0.788619 | 1 | 0.788619 | game-dev | MEDIA | 0.864868 | game-dev | 0.860434 | 1 | 0.860434 |
magefree/mage | 2,687 | Mage.Sets/src/mage/cards/n/NecronMonolith.java | package mage.cards.n;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.AttacksTriggeredAbility;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.keyword.CrewAbility;
import mage.abilities.keyword.FlyingAbility;
import mage.abilities.keyword.IndestructibleAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.SubType;
import mage.filter.StaticFilters;
import mage.game.Game;
import mage.game.permanent.token.NecronWarriorToken;
import mage.players.Player;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class NecronMonolith extends CardImpl {
public NecronMonolith(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{7}");
this.subtype.add(SubType.VEHICLE);
this.power = new MageInt(7);
this.toughness = new MageInt(7);
// Flying
this.addAbility(FlyingAbility.getInstance());
// Indestructible
this.addAbility(IndestructibleAbility.getInstance());
// Eternity Gate -- Whenever Necron Monolith attacks, mill three cards. For each creature card milled this way, create a 2/2 black Necron Warrior artifact creature token.
this.addAbility(new AttacksTriggeredAbility(new NecronMonolithEffect()).withFlavorWord("Eternity Gate"));
// Crew 4
this.addAbility(new CrewAbility(4));
}
private NecronMonolith(final NecronMonolith card) {
super(card);
}
@Override
public NecronMonolith copy() {
return new NecronMonolith(this);
}
}
class NecronMonolithEffect extends OneShotEffect {
NecronMonolithEffect() {
super(Outcome.Benefit);
staticText = "mill three cards. For each creature card milled this way, " +
"create a 2/2 black Necron Warrior artifact creature token";
}
private NecronMonolithEffect(final NecronMonolithEffect effect) {
super(effect);
}
@Override
public NecronMonolithEffect copy() {
return new NecronMonolithEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Player player = game.getPlayer(source.getControllerId());
if (player == null) {
return false;
}
int count = player
.millCards(3, source, game)
.count(StaticFilters.FILTER_CARD_CREATURE, game);
if (count > 0) {
game.processAction();
new NecronWarriorToken().putOntoBattlefield(count, game, source);
}
return true;
}
}
| 0 | 0.977341 | 1 | 0.977341 | game-dev | MEDIA | 0.968743 | game-dev | 0.955576 | 1 | 0.955576 |
FoxMCTeam/TenacityRecode-master | 3,204 | src/java/net/minecraft/block/BlockStainedGlassPane.java | package net.minecraft.block;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraft.world.World;
import java.util.List;
public class BlockStainedGlassPane extends BlockPane
{
public static final PropertyEnum<EnumDyeColor> COLOR = PropertyEnum.<EnumDyeColor>create("color", EnumDyeColor.class);
public BlockStainedGlassPane()
{
super(Material.glass, false);
this.setDefaultState(this.blockState.getBaseState().withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)).withProperty(COLOR, EnumDyeColor.WHITE));
this.setCreativeTab(CreativeTabs.tabDecorations);
}
/**
* Gets the metadata of the item this Block can drop. This method is called when the block gets destroyed. It
* returns the metadata of the dropped item based on the old metadata of the block.
*/
public int damageDropped(IBlockState state)
{
return ((EnumDyeColor)state.getValue(COLOR)).getMetadata();
}
/**
* returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks)
*/
public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list)
{
for (int i = 0; i < EnumDyeColor.values().length; ++i)
{
list.add(new ItemStack(itemIn, 1, i));
}
}
/**
* Get the MapColor for this Block and the given BlockState
*/
public MapColor getMapColor(IBlockState state)
{
return ((EnumDyeColor)state.getValue(COLOR)).getMapColor();
}
public EnumWorldBlockLayer getBlockLayer()
{
return EnumWorldBlockLayer.TRANSLUCENT;
}
/**
* Convert the given metadata into a BlockState for this Block
*/
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(COLOR, EnumDyeColor.byMetadata(meta));
}
/**
* Convert the BlockState into the correct metadata value
*/
public int getMetaFromState(IBlockState state)
{
return ((EnumDyeColor)state.getValue(COLOR)).getMetadata();
}
protected BlockState createBlockState()
{
return new BlockState(this, new IProperty[] {NORTH, EAST, WEST, SOUTH, COLOR});
}
public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state)
{
if (!worldIn.isRemote)
{
BlockBeacon.updateColorAsync(worldIn, pos);
}
}
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
if (!worldIn.isRemote)
{
BlockBeacon.updateColorAsync(worldIn, pos);
}
}
}
| 0 | 0.765058 | 1 | 0.765058 | game-dev | MEDIA | 0.996973 | game-dev | 0.855182 | 1 | 0.855182 |
kode80/PixelRenderUnity3D | 2,188 | Assets/kode80/PixelRender/Examples/Shooter/Scripts/JetController.cs | //***************************************************
//
// Author: Ben Hopkins
// Copyright (C) 2016 kode80 LLC,
// all rights reserved
//
// Free to use for non-commercial purposes,
// see full license in project root:
// PixelRenderNonCommercialLicense.html
//
// Commercial licenses available for purchase from:
// http://kode80.com/
//
//***************************************************
using UnityEngine;
using System.Collections;
namespace kode80.PixelRender.ShooterExample
{
public class JetController : MonoBehaviour
{
public float speed = 30.0f;
public float scrollSpeed = 8.0f;
public GameObject bullet;
public Transform bulletSpawn;
private Vector3 _velocity;
// Use this for initialization
void Start () {
_velocity = Vector3.zero;
}
// Update is called once per frame
void Update ()
{
_velocity.x = Input.GetAxis( "Horizontal") * speed + scrollSpeed;
_velocity.y = Input.GetAxis( "Vertical") * speed;
Vector3 newPosition = transform.position + _velocity * Time.deltaTime;
Vector3 collisionPoint, collisionNormal;
if( CheckLevelCollision( transform.position, newPosition, out collisionPoint, out collisionNormal))
{
newPosition.y = collisionPoint.y + collisionNormal.y * 0.1f;
}
transform.position = newPosition;
if( Input.GetButtonDown( "Fire"))
{
Instantiate( bullet, bulletSpawn.position, Quaternion.identity);
}
}
bool CheckLevelCollision( Vector3 oldPosition, Vector3 newPosition, out Vector3 collisionPoint, out Vector3 collisionNormal)
{
Vector3 direction = newPosition - oldPosition;
Ray ray = new Ray( transform.position, direction.normalized);
RaycastHit hit;
int layer = 1 << LayerMask.NameToLayer( "Level");
if( Physics.Raycast( ray, out hit, direction.magnitude, layer))
{
collisionPoint = ray.origin + direction * hit.distance;
collisionNormal = hit.normal;
return true;
}
collisionPoint = Vector3.zero;
collisionNormal = Vector3.zero;
return false;
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawLine( transform.position, transform.position + _velocity.normalized * 2.0f);
}
}
}
| 0 | 0.920558 | 1 | 0.920558 | game-dev | MEDIA | 0.989079 | game-dev | 0.962354 | 1 | 0.962354 |
needle-tools/custom-timeline-editor | 3,546 | package/Runtime/Utils/TimelineBuffer.cs | #if UNITY_EDITOR
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using UnityEditor;
using UnityEditor.Timeline;
using UnityEngine;
using UnityEngine.Playables;
using Debug = UnityEngine.Debug;
namespace Needle.Timeline
{
// TODO: use particle system naming: re-simulate
internal static class TimelineBuffer
{
public static bool DebugLog;
public static bool Enabled
{
get => CustomTimelineSettings.Instance.AllowBuffering;
set => CustomTimelineSettings.Instance.AllowBuffering = value;
}
[InitializeOnLoadMethod]
private static void Init()
{
TimelineHooks.StateChanged += OnStateChanged;
TimelineHooks.TimeChanged += OnTimeChanged;
}
private static int timeChangedId;
private static async void OnTimeChanged(PlayableDirector dir, double d)
{
if (isBuffering) return;
var evtTime = d;
var id = bufferRequestId;
var timeChangeId = ++timeChangedId;
await Task.Delay(20);
if (isBuffering || id != bufferRequestId || timeChangeId != timeChangedId) return;
if (DebugLog)
Debug.Log("Time changed");
var diff = Mathf.Abs((float)(dir.time - evtTime));
if (diff > .001f)
{
if (dir.state == PlayState.Playing) return;
await RequestBufferCurrentInspectedTimeline();
}
}
private static async void OnStateChanged(PlayableDirector dir, PlayState oldState)
{
if (oldState == PlayState.Paused && dir.state == PlayState.Playing)
{
// await Buffer(dir, 10);
}
}
private static int bufferRequestId;
internal static async Task RequestBufferCurrentInspectedTimeline(float? seconds = null, double? fromTime = null)
{
var id = ++bufferRequestId;
var timeId = timeChangedId;
if (DebugLog)
Debug.Log("Request buffering");
await Task.Delay(100);
if (id != bufferRequestId || timeChangedId != timeId) return;
var dir = TimelineEditor.inspectedDirector;
if (dir != null) // && dir.state != PlayState.Playing)
{
await Buffer(dir, seconds, fromTime);
}
}
private static bool isBuffering = false;
private static Task Buffer(PlayableDirector dir, float? seconds = null, double? fromTime = null)
{
if (!Enabled) return Task.CompletedTask;
if (isBuffering) return Task.CompletedTask;
isBuffering = true;
if (DebugLog)
Debug.Log("BUFFER");
foreach (var clip in ClipInfoViewModel.Instances)
{
if (clip.Script is IAnimatedEvents evt)
{
evt.OnReset();
}
}
var targetTime = fromTime ?? dir.time;
var sec = seconds ?? CustomTimelineSettings.Instance.DefaultBufferLenght;
var startTime = targetTime - sec;
var frames = Mathf.CeilToInt(sec * 120f);
IAnimatedExtensions.deltaTimeOverride = 1 / 120f;
var state = dir.state;
if (state != PlayState.Playing) dir.Play();
var sw = new Stopwatch();
sw.Start();
var abortBuffer = false;
for (var i = 0; i < frames; i++)
{
var time = (double)Mathf.Lerp((float)startTime, (float)targetTime, i / (float)frames);
if (time < 0) continue;
if (i == frames) time = targetTime;
dir.time = time;
dir.Evaluate();
if (sw.ElapsedMilliseconds > 1000)
{
abortBuffer = true;
Debug.LogWarning("Buffering took too long");
break;
}
}
dir.time = targetTime;
if (!abortBuffer)
dir.Evaluate();
IAnimatedExtensions.deltaTimeOverride = null;
switch (state)
{
case PlayState.Paused:
dir.Pause();
break;
}
TimelineEditor.GetWindow().Repaint();
isBuffering = false;
return Task.CompletedTask;
}
}
}
#endif | 0 | 0.817206 | 1 | 0.817206 | game-dev | MEDIA | 0.883368 | game-dev | 0.977877 | 1 | 0.977877 |
MergHQ/CRYENGINE | 4,594 | Code/CryEngine/Cry3DEngine/ParticleSystem/ParticleEffect.cpp | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
// -------------------------------------------------------------------------
// Created: 23/09/2014 by Filipe amim
// Description:
// -------------------------------------------------------------------------
//
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include <CrySerialization/STL.h>
#include <CrySerialization/IArchive.h>
#include <CrySerialization/SmartPtr.h>
#include "ParticleEffect.h"
#include "ParticleEmitter.h"
#include "ParticleFeature.h"
CRY_PFX2_DBG
namespace pfx2
{
//////////////////////////////////////////////////////////////////////////
// CParticleEffect
CParticleEffect::CParticleEffect()
: m_editVersion(0)
, m_dirty(true)
{
}
cstr CParticleEffect::GetName() const
{
return m_name.c_str();
}
void CParticleEffect::Compile()
{
FUNCTION_PROFILER(GetISystem(), PROFILE_PARTICLE);
if (!m_dirty)
return;
m_attributeInstance.Reset(&m_attributes, EAttributeScope::PerEffect);
for (size_t i = 0; i < m_components.size(); ++i)
{
m_components[i]->m_pEffect = this;
m_components[i]->m_componentId = i;
m_components[i]->SetChanged();
m_components[i]->m_componentParams.Reset();
m_components[i]->PreCompile();
}
for (auto& component : m_components)
component->ResolveDependencies();
for (auto& component : m_components)
component->Compile();
for (auto& component : m_components)
component->FinalizeCompile();
m_dirty = false;
}
TComponentId CParticleEffect::FindComponentIdByName(const char* name) const
{
const auto it = std::find_if(m_components.begin(), m_components.end(), [name](TComponentPtr pComponent)
{
return strcmp(pComponent->GetName(), name) == 0;
});
if (it == m_components.end())
return gInvalidId;
return TComponentId(it - m_components.begin());
}
string CParticleEffect::MakeUniqueName(TComponentId forComponentId, const char* name)
{
TComponentId foundId = FindComponentIdByName(name);
if (foundId == forComponentId || foundId == gInvalidId)
return string(name);
CryStackStringT<char, 256> newName(name);
const uint sz = strlen(name);
if (isdigit(name[sz - 2]) && isdigit(name[sz - 1]))
{
const uint newIdent = (name[sz - 2] - '0') * 10 + (name[sz - 1] - '0') + 1;
newName.replace(sz - 2, 1, 1, (newIdent / 10) % 10 + '0');
newName.replace(sz - 1, 1, 1, newIdent % 10 + '0');
}
else
{
newName.append("01");
}
return MakeUniqueName(forComponentId, newName);
}
void CParticleEffect::SetName(cstr name)
{
m_name = name;
}
void CParticleEffect::Serialize(Serialization::IArchive& ar)
{
uint documentVersion = 1;
if (ar.isOutput())
documentVersion = gCurrentVersion;
ar(documentVersion, "Version", "");
SSerializationContext documentContext(documentVersion);
Serialization::SContext context(ar, &documentContext);
ar(m_attributes, "Attributes");
if (ar.isInput() && documentVersion < 3)
{
std::vector<CParticleComponent> oldComponents;
ar(oldComponents, "Components", "+Components");
m_components.reserve(oldComponents.size());
for (auto& oldComponent : oldComponents)
m_components.push_back(new CParticleComponent(oldComponent));
}
else
ar(m_components, "Components", "+Components");
if (ar.isInput())
{
auto it = std::remove_if(m_components.begin(), m_components.end(), [](TComponentPtr ptr){ return !ptr; });
m_components.erase(it, m_components.end());
SetChanged();
for (auto& component : m_components)
component->SetChanged();
Compile();
}
}
IParticleEmitter* CParticleEffect::Spawn(const ParticleLoc& loc, const SpawnParams* pSpawnParams)
{
FUNCTION_PROFILER(GetISystem(), PROFILE_PARTICLE);
PParticleEmitter pEmitter = GetPSystem()->CreateEmitter(this);
CParticleEmitter* pCEmitter = static_cast<CParticleEmitter*>(pEmitter.get());
pCEmitter->SetLocation(loc);
return pEmitter;
}
void CParticleEffect::AddComponent(uint componentIdx)
{
uint idx = m_components.size();
CParticleComponent* pNewComponent = new CParticleComponent();
pNewComponent->m_pEffect = this;
pNewComponent->m_componentId = componentIdx;
pNewComponent->SetName("Component01");
m_components.insert(m_components.begin() + componentIdx, pNewComponent);
SetChanged();
}
void CParticleEffect::RemoveComponent(uint componentIdx)
{
m_components.erase(m_components.begin() + componentIdx);
SetChanged();
}
void CParticleEffect::SetChanged()
{
if (!m_dirty)
++m_editVersion;
m_dirty = true;
}
Serialization::SStruct CParticleEffect::GetEffectOptionsSerializer() const
{
return Serialization::SStruct(m_attributes);
}
}
| 0 | 0.962541 | 1 | 0.962541 | game-dev | MEDIA | 0.436456 | game-dev | 0.937792 | 1 | 0.937792 |
artemisac/artemis-minecraft-anticheat | 1,799 | ac.artemis.engine/engine-v2/src/main/java/ac/artemis/anticheat/engine/v2/block/impl/LegacyBlockCollisionProvider.java | package ac.artemis.anticheat.engine.v2.block.impl;
import ac.artemis.anticheat.engine.v2.block.BlockCollisionProvider;
import ac.artemis.core.v5.emulator.TransitionData;
import ac.artemis.core.v5.emulator.block.Block;
import ac.artemis.core.v5.emulator.block.CollisionBlockState;
import ac.artemis.core.v5.utils.EntityUtil;
import ac.artemis.core.v5.utils.raytrace.NaivePoint;
public class LegacyBlockCollisionProvider implements BlockCollisionProvider {
@Override
public void doBlockCollisions(TransitionData data) {
final NaivePoint startBlockPos = new NaivePoint(
data.getBoundingBox().minX + 0.001D,
data.getBoundingBox().minY + 0.001D,
data.getBoundingBox().minZ + 0.001D
);
final NaivePoint endBlockPost = new NaivePoint(
data.getBoundingBox().maxX - 0.001D,
data.getBoundingBox().maxY - 0.001D,
data.getBoundingBox().maxZ - 0.001D
);
if (!EntityUtil.isAreaLoaded(data.getData().getPlayer().getWorld(), startBlockPos, endBlockPost)) {
return;
}
for (int x = startBlockPos.getX(); x <= endBlockPost.getX(); ++x) {
for (int y = startBlockPos.getY(); y <= endBlockPost.getY(); ++y) {
for (int z = startBlockPos.getZ(); z <= endBlockPost.getZ(); ++z) {
final Block block = data.getData().getEntity().getWorld().getBlockAt(x, y, z);
final boolean isCollideState = block instanceof CollisionBlockState;
if (!isCollideState) continue;
final CollisionBlockState blockState = (CollisionBlockState) block;
blockState.onCollidedBlockState(data);
}
}
}
}
}
| 0 | 0.935482 | 1 | 0.935482 | game-dev | MEDIA | 0.743807 | game-dev | 0.880825 | 1 | 0.880825 |
mostafa-saad/MyCompetitiveProgramming | 3,022 | Olympiad/Baltic/official/boi2018_solutions/code/polygon/wrong_answer/broken_relationships.cpp | #include <iostream>
#include <vector>
#include <map>
using namespace std;
const int MAX_PEOPLE = 100005;
vector<int> lovers [MAX_PEOPLE];
int love_target [MAX_PEOPLE];
int component [MAX_PEOPLE];
void explore (int vertex) {
if (component[vertex] == -1) { /* we detected a cycle */
component[vertex] = vertex;
} else if (component[vertex] == 0) {
component[vertex] = -1;
explore(love_target[vertex]);
component[vertex] = component[love_target[vertex]];
}
}
int mls_exclu [MAX_PEOPLE];
int mls_inclu [MAX_PEOPLE];
void calculate_dp (int vertex, int forbidden) {
for (int child : lovers[vertex]) {
if (child != vertex && child != forbidden) {
calculate_dp(child, forbidden);
}
}
/* calculate the values of the dynamic programming functions */
mls_inclu[vertex] = 1;
for (int child : lovers[vertex]) {
if (child != vertex && child != forbidden) {
mls_inclu[vertex] += mls_exclu[child];
}
}
mls_exclu[vertex] = 0;
for (int child : lovers[vertex]) {
if (child != vertex && child != forbidden) {
mls_exclu[vertex] = max(mls_exclu[vertex], mls_inclu[child] - mls_exclu[child]);
}
}
mls_exclu[vertex] += mls_inclu[vertex] - 1;
}
int process_component (int vertex) {
if (love_target[vertex] == vertex) { /* a tree */
calculate_dp(vertex, -1);
return mls_exclu[vertex];
} else {
/* variant 1: vertex stays with its original target */
int variant_1 = 1;
for (int lover : lovers[vertex]) {
if (lover != love_target[vertex]) {
calculate_dp(lover, love_target[vertex]);
variant_1 += mls_exclu[lover];
}
}
/* variant 2: it doesn't :'( */
calculate_dp(vertex, vertex);
int variant_2 = mls_exclu[vertex];
return max(variant_1, variant_2);
}
}
int main () {
ios::sync_with_stdio(false);
int character_count;
cin >> character_count;
if (character_count % 2 == 1) {
/* N odd; no solution */
cout << -1 << endl;
return 0;
}
map<string, int> character_index;
/* assign an integer to each character */
int cur_index = 1;
for (int i = 1; i <= character_count; i++) {
string lover, lovee;
cin >> lover >> lovee;
/* is this the first time we encounter these people? */
if (character_index.count(lover) == 0) {
character_index[lover] = cur_index;
cur_index++;
}
if (character_index.count(lovee) == 0) {
character_index[lovee] = cur_index;
cur_index++;
}
int lover_idx = character_index[lover];
int lovee_idx = character_index[lovee];
lovers[lovee_idx].push_back(lover_idx);
love_target[lover_idx] = lovee_idx;
}
for (int i = 1; i <= character_count; i++) {
/* assign each character to a connected component */
if (component[i] == 0) {
explore(i);
}
}
int answer = 0;
for (int i = 1; i <= character_count; i++) {
if (component[i] == i) {
answer += process_component(i);
}
}
cout << character_count - answer << endl;
}
| 0 | 0.753004 | 1 | 0.753004 | game-dev | MEDIA | 0.465291 | game-dev | 0.621661 | 1 | 0.621661 |
Lexxie9952/fcw.org-server | 65,606 | freeciv/freeciv/common/player.c | /***********************************************************************
Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold
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.
***********************************************************************/
#ifdef HAVE_CONFIG_H
#include <fc_config.h>
#endif
/* utility */
#include "fcintl.h"
#include "log.h"
#include "mem.h"
#include "shared.h"
#include "support.h"
/* common */
#include "ai.h"
#include "city.h"
#include "fc_interface.h"
#include "featured_text.h"
#include "game.h"
#include "government.h"
#include "idex.h"
#include "improvement.h"
#include "map.h"
#include "research.h"
#include "rgbcolor.h"
#include "tech.h"
#include "unit.h"
#include "unitlist.h"
#include "vision.h"
#include "player.h"
struct player_slot {
struct player *player;
};
static struct {
struct player_slot *slots;
int used_slots; /* number of used/allocated players in the player slots */
} player_slots;
static void player_defaults(struct player *pplayer);
static void player_diplstate_new(const struct player *plr1,
const struct player *plr2);
static void player_diplstate_defaults(const struct player *plr1,
const struct player *plr2);
static void player_diplstate_destroy(const struct player *plr1,
const struct player *plr2);
/*******************************************************************//**
Return the diplomatic state that cancelling a pact will
end up in.
***********************************************************************/
enum diplstate_type cancel_pact_result(enum diplstate_type oldstate)
{
switch (oldstate) {
case DS_NO_CONTACT: /* possible if someone declares war on our ally */
case DS_WAR: /* no change */
case DS_ARMISTICE:
case DS_CEASEFIRE:
case DS_PEACE:
return DS_WAR;
case DS_ALLIANCE:
return DS_ARMISTICE;
case DS_TEAM: /* no change */
return DS_TEAM;
default:
log_error("non-pact diplstate %d in cancel_pact_result", oldstate);
return DS_WAR; /* arbitrary */
}
}
/*******************************************************************//**
The senate may not allow you to break the treaty. In this
case you must first dissolve the senate then you can break
it. This is waived if you have statue of liberty since you
could easily just dissolve and then recreate it.
***********************************************************************/
enum dipl_reason pplayer_can_cancel_treaty(const struct player *p1,
const struct player *p2)
{
enum diplstate_type ds = player_diplstate_get(p1, p2)->type;
if (p1 == p2 || ds == DS_WAR || ds == DS_NO_CONTACT) {
return DIPL_ERROR;
}
if (players_on_same_team(p1, p2)) {
return DIPL_ERROR;
}
if (!p1->is_alive || !p2->is_alive) {
return DIPL_ERROR;
}
if (player_diplstate_get(p1, p2)->has_reason_to_cancel == 0
&& get_player_bonus(p1, EFT_HAS_SENATE) > 0
&& get_player_bonus(p1, EFT_NO_ANARCHY) <= 0) {
return DIPL_SENATE_BLOCKING;
}
return DIPL_OK;
}
/*******************************************************************//**
Returns true iff p1 can be in alliance with p2.
Check that we are not at war with any of p2's allies. Note
that for an alliance to be made, we need to check this both
ways.
The reason for this is to avoid the dread 'love-love-hate'
triad, in which p1 is allied to p2 is allied to p3 is at
war with p1. These lead to strange situations.
***********************************************************************/
static bool is_valid_alliance(const struct player *p1,
const struct player *p2)
{
players_iterate_alive(pplayer) {
enum diplstate_type ds = player_diplstate_get(p1, pplayer)->type;
if (pplayer != p1
&& pplayer != p2
&& ds == DS_WAR /* do not count 'never met' as war here */
&& pplayers_allied(p2, pplayer)) {
return FALSE;
}
} players_iterate_alive_end;
return TRUE;
}
/*******************************************************************//**
Returns true iff p1 can make given treaty with p2.
We cannot regress in a treaty chain. So we cannot suggest
'Peace' if we are in 'Alliance'. Then you have to cancel.
For alliance there is only one condition: We are not at war
with any of p2's allies.
***********************************************************************/
enum dipl_reason pplayer_can_make_treaty(const struct player *p1,
const struct player *p2,
enum diplstate_type treaty)
{
enum diplstate_type existing = player_diplstate_get(p1, p2)->type;
int turns_left = player_diplstate_get(p1, p2)->turns_left;
bool casus_belli =
(player_diplstate_get(p1, p2)->has_reason_to_cancel
|| player_diplstate_get(p2, p1)->has_reason_to_cancel);
if (players_on_same_team(p1, p2)) {
/* This includes the case p1 == p2 */
return DIPL_ERROR;
}
if (get_player_bonus(p1, EFT_NO_DIPLOMACY) > 0
|| get_player_bonus(p2, EFT_NO_DIPLOMACY) > 0) {
return DIPL_ERROR;
}
if (treaty == DS_WAR
|| treaty == DS_NO_CONTACT
|| treaty == DS_ARMISTICE
|| treaty == DS_TEAM
|| treaty == DS_LAST) {
return DIPL_ERROR; /* these are not negotiable treaties */
}
if (treaty == DS_CEASEFIRE && existing != DS_WAR) {
if (existing == DS_CEASEFIRE && (casus_belli
|| (turns_left >= 1 && turns_left <= 3))) {
// if casus belli, can re-affirm treaty as way to erase casus
// belli for old deeds. can renew cease-fire if <=3 turns left
return DIPL_OK;
}
else return DIPL_ERROR; /* only available from war */
}
if (treaty == DS_PEACE
&& (existing != DS_WAR && existing != DS_CEASEFIRE)) {
if ((existing == DS_PEACE || existing == DS_ARMISTICE)
&& (casus_belli || (turns_left >= 1 && turns_left <= 3))) {
// if casus belli, can re-affirm treaty as way to erase casus
// belli for old deeds. can extend armistice if more time needed
// to get units out of territory if <= 3 turns left.
return DIPL_OK;
}
else return DIPL_ERROR;
}
if (treaty == DS_ALLIANCE) {
if (!is_valid_alliance(p1, p2)) {
/* Our war with a third party prevents entry to alliance. */
return DIPL_ALLIANCE_PROBLEM_US;
} else if (!is_valid_alliance(p2, p1)) {
/* Their war with a third party prevents entry to alliance. */
return DIPL_ALLIANCE_PROBLEM_THEM;
}
}
/* this check must be last: */
if (treaty == existing) {
return DIPL_ERROR;
}
return DIPL_OK;
}
/*******************************************************************//**
Check if pplayer has an embassy with pplayer2. We always have
an embassy with ourselves.
***********************************************************************/
bool player_has_embassy(const struct player *pplayer,
const struct player *pplayer2)
{
return (pplayer == pplayer2
|| player_has_real_embassy(pplayer, pplayer2)
|| player_has_embassy_from_effect(pplayer, pplayer2));
}
/*******************************************************************//**
Returns whether pplayer has a real embassy with pplayer2,
established from a diplomat, or through diplomatic meeting.
***********************************************************************/
bool player_has_real_embassy(const struct player *pplayer,
const struct player *pplayer2)
{
return BV_ISSET(pplayer->real_embassy, player_index(pplayer2));
}
/*******************************************************************//**
Returns whether pplayer has got embassy with pplayer2 thanks
to an effect (e.g. Macro Polo Embassy).
***********************************************************************/
bool player_has_embassy_from_effect(const struct player *pplayer,
const struct player *pplayer2)
{
return (get_player_bonus(pplayer, EFT_HAVE_EMBASSIES) > 0
&& player_diplstate_get(pplayer, pplayer2)->type != DS_NO_CONTACT
&& !is_barbarian(pplayer2));
}
/*******************************************************************//**
Return TRUE iff the given player owns the city.
***********************************************************************/
bool player_owns_city(const struct player *pplayer, const struct city *pcity)
{
return (pcity && pplayer && city_owner(pcity) == pplayer);
}
/*******************************************************************//**
Return TRUE iff the player can invade a particular tile (linked with
borders and diplomatic states).
***********************************************************************/
bool player_can_invade_tile(const struct player *pplayer,
const struct tile *ptile)
{
const struct player *ptile_owner = tile_owner(ptile);
return (!ptile_owner
|| ptile_owner == pplayer
|| !players_non_invade(pplayer, ptile_owner));
}
/*******************************************************************//**
Allocate new diplstate structure for tracking state between given two
players.
***********************************************************************/
static void player_diplstate_new(const struct player *plr1,
const struct player *plr2)
{
struct player_diplstate *diplstate;
fc_assert_ret(plr1 != NULL);
fc_assert_ret(plr2 != NULL);
const struct player_diplstate **diplstate_slot
= plr1->diplstates + player_index(plr2);
fc_assert_ret(*diplstate_slot == NULL);
diplstate = fc_calloc(1, sizeof(*diplstate));
*diplstate_slot = diplstate;
}
/*******************************************************************//**
Set diplstate between given two players to default values.
***********************************************************************/
static void player_diplstate_defaults(const struct player *plr1,
const struct player *plr2)
{
struct player_diplstate *diplstate = player_diplstate_get(plr1, plr2);
fc_assert_ret(diplstate != NULL);
diplstate->type = DS_NO_CONTACT;
diplstate->max_state = DS_NO_CONTACT;
diplstate->first_contact_turn = 0;
diplstate->turns_left = 0;
diplstate->has_reason_to_cancel = 0;
diplstate->contact_turns_left = 0;
diplstate->auto_cancel_turn = -1;
}
/*******************************************************************//**
Returns diplomatic state type between two players
***********************************************************************/
struct player_diplstate *player_diplstate_get(const struct player *plr1,
const struct player *plr2)
{
fc_assert_ret_val(plr1 != NULL, NULL);
fc_assert_ret_val(plr2 != NULL, NULL);
const struct player_diplstate **diplstate_slot
= plr1->diplstates + player_index(plr2);
fc_assert_ret_val(*diplstate_slot != NULL, NULL);
return (struct player_diplstate *) *diplstate_slot;
}
/*******************************************************************//**
Free resources used by diplstate between given two players.
***********************************************************************/
static void player_diplstate_destroy(const struct player *plr1,
const struct player *plr2)
{
fc_assert_ret(plr1 != NULL);
fc_assert_ret(plr2 != NULL);
const struct player_diplstate **diplstate_slot
= plr1->diplstates + player_index(plr2);
if (*diplstate_slot != NULL) {
free(player_diplstate_get(plr1, plr2));
}
*diplstate_slot = NULL;
}
/*******************************************************************//**
Initialise all player slots (= pointer to player pointers).
***********************************************************************/
void player_slots_init(void)
{
int i;
/* Init player slots. */
player_slots.slots = fc_calloc(player_slot_count(),
sizeof(*player_slots.slots));
/* Can't use the defined functions as the needed data will be
* defined here. */
for (i = 0; i < player_slot_count(); i++) {
player_slots.slots[i].player = NULL;
}
player_slots.used_slots = 0;
}
/*******************************************************************//**
Return whether player slots are already initialized.
***********************************************************************/
bool player_slots_initialised(void)
{
return (player_slots.slots != NULL);
}
/*******************************************************************//**
Remove all player slots.
***********************************************************************/
void player_slots_free(void)
{
players_iterate(pplayer) {
player_destroy(pplayer);
} players_iterate_end;
free(player_slots.slots);
player_slots.slots = NULL;
player_slots.used_slots = 0;
}
/*******************************************************************//**
Returns the first player slot.
***********************************************************************/
struct player_slot *player_slot_first(void)
{
return player_slots.slots;
}
/*******************************************************************//**
Returns the next slot.
***********************************************************************/
struct player_slot *player_slot_next(struct player_slot *pslot)
{
pslot++;
return (pslot < player_slots.slots + player_slot_count() ? pslot : NULL);
}
/*******************************************************************//**
Returns the total number of player slots, i.e. the maximum
number of players (including barbarians, etc.) that could ever
exist at once.
***********************************************************************/
int player_slot_count(void)
{
return (MAX_NUM_PLAYER_SLOTS);
}
/*******************************************************************//**
Returns the index of the player slot.
***********************************************************************/
int player_slot_index(const struct player_slot *pslot)
{
fc_assert_ret_val(NULL != pslot, -1);
return pslot - player_slots.slots;
}
/*******************************************************************//**
Returns the team corresponding to the slot. If the slot is not used, it
will return NULL. See also player_slot_is_used().
***********************************************************************/
struct player *player_slot_get_player(const struct player_slot *pslot)
{
fc_assert_ret_val(NULL != pslot, NULL);
return pslot->player;
}
/*******************************************************************//**
Returns TRUE is this slot is "used" i.e. corresponds to a valid,
initialized player that exists in the game.
***********************************************************************/
bool player_slot_is_used(const struct player_slot *pslot)
{
fc_assert_ret_val(NULL != pslot, FALSE);
/* No player slot available, if the game is not initialised. */
if (!player_slots_initialised()) {
return FALSE;
}
return NULL != pslot->player;
}
/*******************************************************************//**
Return the possibly unused and uninitialized player slot.
***********************************************************************/
struct player_slot *player_slot_by_number(int player_id)
{
if (!player_slots_initialised()
|| !(0 <= player_id && player_id < player_slot_count())) {
return NULL;
}
return player_slots.slots + player_id;
}
/*******************************************************************//**
Return the highest used player slot index.
***********************************************************************/
int player_slot_max_used_number(void)
{
int max_pslot = 0;
player_slots_iterate(pslot) {
if (player_slot_is_used(pslot)) {
max_pslot = player_slot_index(pslot);
}
} player_slots_iterate_end;
return max_pslot;
}
/*******************************************************************//**
Creates a new player for the slot. If slot is NULL, it will lookup to a
free slot. If the slot already used, then just return the player.
***********************************************************************/
struct player *player_new(struct player_slot *pslot)
{
struct player *pplayer;
fc_assert_ret_val(player_slots_initialised(), NULL);
if (NULL == pslot) {
player_slots_iterate(aslot) {
if (!player_slot_is_used(aslot)) {
pslot = aslot;
break;
}
} player_slots_iterate_end;
fc_assert_ret_val(NULL != pslot, NULL);
} else if (NULL != pslot->player) {
return pslot->player;
}
/* Now create the player. */
log_debug("Create player for slot %d.", player_slot_index(pslot));
pplayer = fc_calloc(1, sizeof(*pplayer));
pplayer->slot = pslot;
pslot->player = pplayer;
pplayer->diplstates = fc_calloc(player_slot_count(),
sizeof(*pplayer->diplstates));
player_slots_iterate(dslot) {
const struct player_diplstate **diplstate_slot
= pplayer->diplstates + player_slot_index(dslot);
*diplstate_slot = NULL;
} player_slots_iterate_end;
players_iterate(aplayer) {
/* Create diplomatic states for all other players. */
player_diplstate_new(pplayer, aplayer);
/* Create diplomatic state of this player. */
if (aplayer != pplayer) {
player_diplstate_new(aplayer, pplayer);
}
} players_iterate_end;
/* Set default values. */
player_defaults(pplayer);
/* Increase number of players. */
player_slots.used_slots++;
return pplayer;
}
/*******************************************************************//**
Set player structure to its default values.
No initialisation to ruleset-dependent values should be done here.
***********************************************************************/
static void player_defaults(struct player *pplayer)
{
int i;
sz_strlcpy(pplayer->name, ANON_PLAYER_NAME);
sz_strlcpy(pplayer->username, _(ANON_USER_NAME));
pplayer->unassigned_user = TRUE;
sz_strlcpy(pplayer->ranked_username, _(ANON_USER_NAME));
pplayer->unassigned_ranked = TRUE;
pplayer->user_turns = 0;
pplayer->is_male = TRUE;
pplayer->government = NULL;
pplayer->target_government = NULL;
pplayer->nation = NO_NATION_SELECTED;
pplayer->team = NULL;
pplayer->is_ready = FALSE;
pplayer->nturns_idle = 0;
pplayer->is_alive = TRUE;
pplayer->turns_alive = 0;
pplayer->is_winner = FALSE;
pplayer->last_war_action = -1;
pplayer->phase_done = FALSE;
pplayer->revolution_finishes = -1;
BV_CLR_ALL(pplayer->real_embassy);
players_iterate(aplayer) {
/* create diplomatic states for all other players */
player_diplstate_defaults(pplayer, aplayer);
/* create diplomatic state of this player */
if (aplayer != pplayer) {
player_diplstate_defaults(aplayer, pplayer);
}
} players_iterate_end;
pplayer->style = 0;
pplayer->music_style = -1; /* even getting value 0 triggers change */
pplayer->cities = city_list_new();
pplayer->units = unit_list_new();
pplayer->economic.gold = 0;
pplayer->economic.tax = PLAYER_DEFAULT_TAX_RATE;
pplayer->economic.science = PLAYER_DEFAULT_SCIENCE_RATE;
pplayer->economic.luxury = PLAYER_DEFAULT_LUXURY_RATE;
pplayer->economic.infra_points = 0;
spaceship_init(&pplayer->spaceship);
BV_CLR_ALL(pplayer->flags);
set_as_human(pplayer);
pplayer->ai_common.skill_level = ai_level_invalid();
pplayer->ai_common.fuzzy = 0;
pplayer->ai_common.expand = 100;
pplayer->ai_common.barbarian_type = NOT_A_BARBARIAN;
player_slots_iterate(pslot) {
pplayer->ai_common.love[player_slot_index(pslot)] = 1;
} player_slots_iterate_end;
pplayer->ai_common.traits = NULL;
pplayer->ai = NULL;
pplayer->was_created = FALSE;
pplayer->savegame_ai_type_name = NULL;
pplayer->random_name = TRUE;
pplayer->is_connected = FALSE;
pplayer->current_conn = NULL;
pplayer->connections = conn_list_new();
BV_CLR_ALL(pplayer->gives_shared_vision);
for (i = 0; i < B_LAST; i++) {
pplayer->wonders[i] = WONDER_NOT_BUILT;
}
pplayer->attribute_block.data = NULL;
pplayer->attribute_block.length = 0;
pplayer->attribute_block_buffer.data = NULL;
pplayer->attribute_block_buffer.length = 0;
pplayer->tile_known.vec = NULL;
pplayer->tile_known.bits = 0;
pplayer->rgb = NULL;
memset(pplayer->multipliers, 0, sizeof(pplayer->multipliers));
memset(pplayer->multipliers_target, 0, sizeof(pplayer->multipliers_target));
/* pplayer->server is initialised in
./server/plrhand.c:server_player_init()
and pplayer->client in
./client/climisc.c:client_player_init() */
}
/*******************************************************************//**
Set the player's color.
May be NULL in pregame.
***********************************************************************/
void player_set_color(struct player *pplayer,
const struct rgbcolor *prgbcolor)
{
if (pplayer->rgb != NULL) {
rgbcolor_destroy(pplayer->rgb);
pplayer->rgb = NULL;
}
if (prgbcolor) {
pplayer->rgb = rgbcolor_copy(prgbcolor);
}
}
/*******************************************************************//**
Clear all player data. If full is set, then the nation and the team will
be cleared too.
***********************************************************************/
void player_clear(struct player *pplayer, bool full)
{
bool client = !is_server();
if (pplayer == NULL) {
return;
}
if (pplayer->savegame_ai_type_name != NULL) {
free(pplayer->savegame_ai_type_name);
pplayer->savegame_ai_type_name = NULL;
}
/* Clears the attribute blocks. */
if (pplayer->attribute_block.data) {
free(pplayer->attribute_block.data);
pplayer->attribute_block.data = NULL;
}
pplayer->attribute_block.length = 0;
if (pplayer->attribute_block_buffer.data) {
free(pplayer->attribute_block_buffer.data);
pplayer->attribute_block_buffer.data = NULL;
}
pplayer->attribute_block_buffer.length = 0;
/* Clears units and cities. */
unit_list_iterate(pplayer->units, punit) {
/* Unload all cargos. */
unit_list_iterate(unit_transport_cargo(punit), pcargo) {
unit_transport_unload(pcargo);
if (client) {
pcargo->client.transported_by = -1;
}
} unit_list_iterate_end;
/* Unload the unit. */
unit_transport_unload(punit);
if (client) {
punit->client.transported_by = -1;
}
game_remove_unit(&wld, punit);
} unit_list_iterate_end;
city_list_iterate(pplayer->cities, pcity) {
game_remove_city(&wld, pcity);
} city_list_iterate_end;
if (full) {
team_remove_player(pplayer);
/* This comes last because log calls in the above functions
* may use it. */
if (pplayer->nation != NULL) {
player_set_nation(pplayer, NULL);
}
}
}
/*******************************************************************//**
Clear the ruleset dependent pointers of the player structure. Called by
game_ruleset_free().
***********************************************************************/
void player_ruleset_close(struct player *pplayer)
{
pplayer->government = NULL;
pplayer->target_government = NULL;
player_set_nation(pplayer, NULL);
pplayer->style = NULL;
}
/*******************************************************************//**
Destroys and remove a player from the game.
***********************************************************************/
void player_destroy(struct player *pplayer)
{
struct player_slot *pslot;
fc_assert_ret(NULL != pplayer);
pslot = pplayer->slot;
fc_assert(pslot->player == pplayer);
/* Remove all that is game-dependent in the player structure. */
player_clear(pplayer, TRUE);
fc_assert(0 == unit_list_size(pplayer->units));
unit_list_destroy(pplayer->units);
fc_assert(0 == city_list_size(pplayer->cities));
city_list_destroy(pplayer->cities);
fc_assert(conn_list_size(pplayer->connections) == 0);
conn_list_destroy(pplayer->connections);
players_iterate(aplayer) {
/* destroy the diplomatics states of this player with others ... */
player_diplstate_destroy(pplayer, aplayer);
/* and of others with this player. */
if (aplayer != pplayer) {
player_diplstate_destroy(aplayer, pplayer);
}
} players_iterate_end;
free(pplayer->diplstates);
/* Clear player color. */
if (pplayer->rgb) {
rgbcolor_destroy(pplayer->rgb);
}
dbv_free(&pplayer->tile_known);
if (!is_server()) {
vision_layer_iterate(v) {
dbv_free(&pplayer->client.tile_vision[v]);
} vision_layer_iterate_end;
}
free(pplayer);
pslot->player = NULL;
player_slots.used_slots--;
}
/*******************************************************************//**
Return the number of players.
***********************************************************************/
int player_count(void)
{
return player_slots.used_slots;
}
/*******************************************************************//**
Return the player index.
Currently same as player_number(), but indicates use as an array index.
The array must be sized by player_slot_count() or MAX_NUM_PLAYER_SLOTS
(player_count() *cannot* be used) and is likely to be sparse.
***********************************************************************/
int player_index(const struct player *pplayer)
{
return player_number(pplayer);
}
/*******************************************************************//**
Return the player index/number/id.
***********************************************************************/
int player_number(const struct player *pplayer)
{
fc_assert_ret_val(NULL != pplayer, -1);
return player_slot_index(pplayer->slot);
}
/*******************************************************************//**
Return struct player pointer for the given player index.
You can retrieve players that are not in the game (with IDs larger than
player_count). An out-of-range player request will return NULL.
***********************************************************************/
struct player *player_by_number(const int player_id)
{
struct player_slot *pslot = player_slot_by_number(player_id);
return (NULL != pslot ? player_slot_get_player(pslot) : NULL);
}
/*******************************************************************//**
Set the player's nation to the given nation (may be NULL). Returns TRUE
iff there was a change.
Doesn't check if the nation is legal wrt nationset.
***********************************************************************/
bool player_set_nation(struct player *pplayer, struct nation_type *pnation)
{
if (pplayer->nation != pnation) {
if (pplayer->nation) {
fc_assert(pplayer->nation->player == pplayer);
pplayer->nation->player = NULL;
}
if (pnation) {
fc_assert(pnation->player == NULL);
pnation->player = pplayer;
}
pplayer->nation = pnation;
return TRUE;
}
return FALSE;
}
/*******************************************************************//**
Find player by given name.
***********************************************************************/
struct player *player_by_name(const char *name)
{
players_iterate(pplayer) {
if (fc_strcasecmp(name, pplayer->name) == 0) {
return pplayer;
}
} players_iterate_end;
return NULL;
}
/*******************************************************************//**
Return the leader name of the player.
***********************************************************************/
const char *player_name(const struct player *pplayer)
{
if (!pplayer) {
return NULL;
}
return pplayer->name;
}
/*******************************************************************//**
Find player by name, allowing unambigous prefix (ie abbreviation).
Returns NULL if could not match, or if ambiguous or other
problem, and fills *result with characterisation of match/non-match
(see shared.[ch])
***********************************************************************/
static const char *player_name_by_number(int i)
{
struct player *pplayer;
pplayer = player_by_number(i);
return player_name(pplayer);
}
/*******************************************************************//**
Find player by its name prefix
***********************************************************************/
struct player *player_by_name_prefix(const char *name,
enum m_pre_result *result)
{
int ind;
*result = match_prefix(player_name_by_number,
player_slot_count(), MAX_LEN_NAME - 1,
fc_strncasequotecmp, effectivestrlenquote,
name, &ind);
if (*result < M_PRE_AMBIGUOUS) {
return player_by_number(ind);
} else {
return NULL;
}
}
/*******************************************************************//**
Find player by its user name (not player/leader name)
***********************************************************************/
struct player *player_by_user(const char *name)
{
players_iterate(pplayer) {
if (fc_strcasecmp(name, pplayer->username) == 0) {
return pplayer;
}
} players_iterate_end;
return NULL;
}
/*******************************************************************//**
"Age" of the player: number of turns spent alive since created.
***********************************************************************/
int player_age(const struct player *pplayer)
{
fc_assert_ret_val(pplayer != NULL, 0);
return pplayer->turns_alive;
}
/*******************************************************************//**
Returns TRUE iff pplayer can trust that ptile really has no units when
it looks empty. A tile looks empty if the player can't see any units on
it and it doesn't contain anything marked as occupied by a unit.
See can_player_see_unit_at() for rules about when an unit is visible.
***********************************************************************/
bool player_can_trust_tile_has_no_units(const struct player *pplayer,
const struct tile *ptile)
{
/* Can't see invisible units. */
if (!fc_funcs->player_tile_vision_get(ptile, pplayer, V_INVIS)
|| !fc_funcs->player_tile_vision_get(ptile, pplayer, V_SUBSURFACE)) {
return FALSE;
}
/* Units within some extras may be hidden. */
if (!pplayers_allied(pplayer, ptile->extras_owner)) {
extra_type_list_iterate(extra_type_list_of_unit_hiders(), pextra) {
if (tile_has_extra(ptile, pextra)) {
return FALSE;
}
} extra_type_list_iterate_end;
}
return TRUE;
}
/*******************************************************************//**
Check if pplayer could see all units on ptile if it had units.
See can_player_see_unit_at() for rules about when an unit is visible.
***********************************************************************/
bool can_player_see_hypotetic_units_at(const struct player *pplayer,
const struct tile *ptile)
{
struct city *pcity;
if (!player_can_trust_tile_has_no_units(pplayer, ptile)) {
/* The existance of any units at all is hidden from the player. */
return FALSE;
}
/* Can't see city units. */
pcity = tile_city(ptile);
if (pcity && !can_player_see_units_in_city(pplayer, pcity)
&& unit_list_size(ptile->units) > 0) {
return FALSE;
}
/* Can't see non allied units in transports. */
unit_list_iterate(ptile->units, punit) {
if (unit_type_get(punit)->transport_capacity > 0
&& unit_owner(punit) != pplayer) {
/* An ally could transport a non ally */
if (unit_list_size(punit->transporting) > 0) {
return FALSE;
}
}
} unit_list_iterate_end;
return TRUE;
}
/*******************************************************************//**
Checks if a unit can be seen by pplayer at (x,y).
A player can see a unit if he:
(a) can see the tile AND
(b) can see the unit at the tile (i.e. unit not invisible at this tile) AND
(c) the unit is outside a city OR in an allied city AND
(d) the unit isn't in a transporter, or we are allied AND
(e) the unit isn't in a transporter, or we can see the transporter
***********************************************************************/
bool can_player_see_unit_at(const struct player *pplayer,
const struct unit *punit,
const struct tile *ptile,
bool is_transported)
{
struct city *pcity;
/* If the player can't even see the tile... */
if (TILE_KNOWN_SEEN != tile_get_known(ptile, pplayer)) {
return FALSE;
}
/* Don't show non-allied units that are in transports. This is logical
* because allied transports can also contain our units. Shared vision
* isn't taken into account. */
if (is_transported && unit_owner(punit) != pplayer
&& !pplayers_allied(pplayer, unit_owner(punit))) {
return FALSE;
}
/* Units in cities may be hidden. */
pcity = tile_city(ptile);
if (pcity && !can_player_see_units_in_city(pplayer, pcity)) {
return FALSE;
}
/* Units within some extras may be hidden. */
if (!pplayers_allied(pplayer, ptile->extras_owner)) {
const struct unit_type *ptype = unit_type_get(punit);
extra_type_list_iterate(extra_type_list_of_unit_hiders(), pextra) {
if (tile_has_extra(ptile, pextra) && is_native_extra_to_utype(pextra, ptype)) {
return FALSE;
}
} extra_type_list_iterate_end;
}
/* Allied or non-hiding units are always seen. */
if (pplayers_allied(unit_owner(punit), pplayer)
|| !is_hiding_unit(punit)) {
return TRUE;
}
/* Hiding units are only seen by the V_INVIS fog layer. */
return fc_funcs->player_tile_vision_get(ptile, pplayer,
unit_type_get(punit)->vlayer);
return FALSE;
}
/*******************************************************************//**
Checks if a unit can be seen by pplayer at its current location.
See can_player_see_unit_at.
***********************************************************************/
bool can_player_see_unit(const struct player *pplayer,
const struct unit *punit)
{
return can_player_see_unit_at(pplayer, punit, unit_tile(punit),
unit_transported(punit));
}
/*******************************************************************//**
Return TRUE iff the player can see units in the city. Either they
can see all units or none.
If the player can see units in the city, then the server sends the
unit info for units in the city to the client. The client uses the
tile's unitlist to determine whether to show the city occupied flag. Of
course the units will be visible to the player as well, if he clicks on
them.
If the player can't see units in the city, then the server doesn't send
the unit info for these units. The client therefore uses the "occupied"
flag sent in the short city packet to determine whether to show the city
occupied flag.
Note that can_player_see_city_internals => can_player_see_units_in_city.
Otherwise the player would not know anything about the city's units at
all, since the full city packet has no "occupied" flag.
Returns TRUE if given a NULL player. This is used by the client when in
observer mode.
***********************************************************************/
bool can_player_see_units_in_city(const struct player *pplayer,
const struct city *pcity)
{
return (!pplayer
|| can_player_see_city_internals(pplayer, pcity)
|| pplayers_allied(pplayer, city_owner(pcity)));
}
/*******************************************************************//**
Return TRUE iff the player can see the city's internals. This means the
full city packet is sent to the client, who should then be able to popup
a dialog for it.
Returns TRUE if given a NULL player. This is used by the client when in
observer mode.
***********************************************************************/
bool can_player_see_city_internals(const struct player *pplayer,
const struct city *pcity)
{
return (!pplayer || pplayer == city_owner(pcity));
}
/*******************************************************************//**
Returns TRUE iff pow_player can see externally visible features of
target_city.
A city's external features are visible to its owner, to players that
currently sees the tile it is located at and to players that has it as
a trade partner.
***********************************************************************/
bool player_can_see_city_externals(const struct player *pow_player,
const struct city *target_city) {
fc_assert_ret_val(target_city, FALSE);
fc_assert_ret_val(pow_player, FALSE);
if (can_player_see_city_internals(pow_player, target_city)) {
/* City internals includes city externals. */
return TRUE;
}
if (tile_is_seen(city_tile(target_city), pow_player)) {
/* The tile is being observed. */
return TRUE;
}
fc_assert_ret_val(target_city->routes, FALSE);
trade_partners_iterate(target_city, trade_city) {
if (city_owner(trade_city) == pow_player) {
/* Revealed because of the trade route. */
return TRUE;
}
} trade_partners_iterate_end;
return FALSE;
}
/*******************************************************************//**
If the specified player owns the city with the specified id,
return pointer to the city struct. Else return NULL.
Now always uses fast idex_lookup_city.
pplayer may be NULL in which case all cities registered to
hash are considered - even those not currently owned by any
player. Callers expect this behavior.
***********************************************************************/
struct city *player_city_by_number(const struct player *pplayer, int city_id)
{
/* We call idex directly. Should use game_city_by_number() instead? */
struct city *pcity = idex_lookup_city(&wld, city_id);
if (!pcity) {
return NULL;
}
if (!pplayer || (city_owner(pcity) == pplayer)) {
/* Correct owner */
return pcity;
}
return NULL;
}
/*******************************************************************//**
If the specified player owns the unit with the specified id,
return pointer to the unit struct. Else return NULL.
Uses fast idex_lookup_city.
pplayer may be NULL in which case all units registered to
hash are considered - even those not currently owned by any
player. Callers expect this behavior.
***********************************************************************/
struct unit *player_unit_by_number(const struct player *pplayer, int unit_id)
{
/* We call idex directly. Should use game_unit_by_number() instead? */
struct unit *punit = idex_lookup_unit(&wld, unit_id);
if (!punit) {
return NULL;
}
if (!pplayer || (unit_owner(punit) == pplayer)) {
/* Correct owner */
return punit;
}
return NULL;
}
/*******************************************************************//**
Return true iff x,y is inside any of the player's city map.
***********************************************************************/
bool player_in_city_map(const struct player *pplayer,
const struct tile *ptile)
{
city_tile_iterate(CITY_MAP_MAX_RADIUS_SQ, ptile, ptile1) {
struct city *pcity = tile_city(ptile1);
if (pcity
&& (pplayer == NULL || city_owner(pcity) == pplayer)
&& city_map_radius_sq_get(pcity) >= sq_map_distance(ptile,
ptile1)) {
return TRUE;
}
} city_tile_iterate_end;
return FALSE;
}
/*******************************************************************//**
Returns the number of techs the player has researched which has this
flag. Needs to be optimized later (e.g. int tech_flags[TF_COUNT] in
struct player)
***********************************************************************/
int num_known_tech_with_flag(const struct player *pplayer,
enum tech_flag_id flag)
{
return research_get(pplayer)->num_known_tech_with_flag[flag];
}
/*******************************************************************//**
Return the expected net income of the player this turn. This includes
tax revenue and upkeep, but not one-time purchases or found gold.
This function depends on pcity->prod[O_GOLD] being set for all cities, so
make sure the player's cities have been refreshed.
***********************************************************************/
int player_get_expected_income(const struct player *pplayer)
{
int income = 0;
/* City income/expenses. */
city_list_iterate(pplayer->cities, pcity) {
/* Gold suplus accounts for imcome plus building and unit upkeep. */
income += pcity->surplus[O_GOLD];
/* Gold upkeep for buildings and units is defined by the setting
* 'game.info.gold_upkeep_style':
* GOLD_UPKEEP_CITY: Cities pay for buildings and units (this is
* included in pcity->surplus[O_GOLD]).
* GOLD_UPKEEP_MIXED: Cities pay only for buildings; the nation pays
* for units.
* GOLD_UPKEEP_NATION: The nation pays for buildings and units. */
switch (game.info.gold_upkeep_style) {
case GOLD_UPKEEP_CITY:
break;
case GOLD_UPKEEP_NATION:
/* Nation pays for buildings (and units). */
income -= city_total_impr_gold_upkeep(pcity);
fc__fallthrough; /* No break. */
case GOLD_UPKEEP_MIXED:
/* Nation pays for units. */
income -= city_total_unit_gold_upkeep(pcity);
break;
}
/* Capitalization income. */
if (city_production_has_flag(pcity, IF_GOLD)) {
income += pcity->shield_stock + pcity->surplus[O_SHIELD];
}
} city_list_iterate_end;
return income;
}
/*******************************************************************//**
Returns TRUE iff the player knows at least one tech which has the
given flag.
***********************************************************************/
bool player_knows_techs_with_flag(const struct player *pplayer,
enum tech_flag_id flag)
{
return num_known_tech_with_flag(pplayer, flag) > 0;
}
/*******************************************************************//**
Locate the player capital city, (NULL Otherwise)
***********************************************************************/
struct city *player_capital(const struct player *pplayer)
{
if (!pplayer) {
/* The client depends on this behavior in some places. */
return NULL;
}
city_list_iterate(pplayer->cities, pcity) {
if (is_capital(pcity)) {
return pcity;
}
} city_list_iterate_end;
return NULL;
}
/*******************************************************************//**
Return a text describing an AI's love for you. (Oooh, kinky!!)
***********************************************************************/
const char *love_text(const int love)
{
if (love <= - MAX_AI_LOVE * 90 / 100) {
/* TRANS: These words should be adjectives which can fit in the sentence
"The x are y towards us"
"The Babylonians are respectful towards us" */
return Q_("?attitude:Genocidal");
} else if (love <= - MAX_AI_LOVE * 70 / 100) {
return Q_("?attitude:Belligerent");
} else if (love <= - MAX_AI_LOVE * 50 / 100) {
return Q_("?attitude:Hostile");
} else if (love <= - MAX_AI_LOVE * 25 / 100) {
return Q_("?attitude:Uncooperative");
} else if (love <= - MAX_AI_LOVE * 10 / 100) {
return Q_("?attitude:Uneasy");
} else if (love <= MAX_AI_LOVE * 10 / 100) {
return Q_("?attitude:Neutral");
} else if (love <= MAX_AI_LOVE * 25 / 100) {
return Q_("?attitude:Respectful");
} else if (love <= MAX_AI_LOVE * 50 / 100) {
return Q_("?attitude:Helpful");
} else if (love <= MAX_AI_LOVE * 70 / 100) {
return Q_("?attitude:Enthusiastic");
} else if (love <= MAX_AI_LOVE * 90 / 100) {
return Q_("?attitude:Admiring");
} else {
fc_assert(love > MAX_AI_LOVE * 90 / 100);
return Q_("?attitude:Worshipful");
}
}
/*******************************************************************//**
Returns true iff players can attack each other.
***********************************************************************/
bool pplayers_at_war(const struct player *pplayer,
const struct player *pplayer2)
{
enum diplstate_type ds;
if (pplayer == pplayer2) {
return FALSE;
}
ds = player_diplstate_get(pplayer, pplayer2)->type;
return ds == DS_WAR || ds == DS_NO_CONTACT;
}
/*******************************************************************//**
Returns true iff players are allied.
***********************************************************************/
bool pplayers_allied(const struct player *pplayer,
const struct player *pplayer2)
{
enum diplstate_type ds;
if (!pplayer || !pplayer2) {
return FALSE;
}
if (pplayer == pplayer2) {
return TRUE;
}
ds = player_diplstate_get(pplayer, pplayer2)->type;
return (ds == DS_ALLIANCE || ds == DS_TEAM);
}
/*******************************************************************//**
Returns true iff players are allied or at peace.
***********************************************************************/
bool pplayers_in_peace(const struct player *pplayer,
const struct player *pplayer2)
{
enum diplstate_type ds = player_diplstate_get(pplayer, pplayer2)->type;
if (pplayer == pplayer2) {
return TRUE;
}
return (ds == DS_PEACE || ds == DS_ALLIANCE
|| ds == DS_ARMISTICE || ds == DS_TEAM);
}
/*******************************************************************//**
Returns TRUE if players can't enter each others' territory.
***********************************************************************/
bool players_non_invade(const struct player *pplayer1,
const struct player *pplayer2)
{
if (pplayer1 == pplayer2 || !pplayer1 || !pplayer2) {
return FALSE;
}
/* Movement during armistice is allowed so that player can withdraw
units deeper inside opponent territory. */
return player_diplstate_get(pplayer1, pplayer2)->type == DS_PEACE;
}
/*******************************************************************//**
Returns true iff players have peace, cease-fire, or
armistice.
***********************************************************************/
bool pplayers_non_attack(const struct player *pplayer,
const struct player *pplayer2)
{
enum diplstate_type ds;
if (pplayer == pplayer2) {
return FALSE;
}
ds = player_diplstate_get(pplayer, pplayer2)->type;
return (ds == DS_PEACE || ds == DS_CEASEFIRE || ds == DS_ARMISTICE);
}
/*******************************************************************//**
Return TRUE if players are in the same team
***********************************************************************/
bool players_on_same_team(const struct player *pplayer1,
const struct player *pplayer2)
{
return pplayer1->team == pplayer2->team;
}
/*******************************************************************//**
Return TRUE iff the player me gives shared vision to player them.
***********************************************************************/
bool gives_shared_vision(const struct player *me, const struct player *them)
{
return BV_ISSET(me->gives_shared_vision, player_index(them));
}
/*******************************************************************//**
Return TRUE iff the two diplstates are equal.
***********************************************************************/
bool are_diplstates_equal(const struct player_diplstate *pds1,
const struct player_diplstate *pds2)
{
return (pds1->type == pds2->type && pds1->turns_left == pds2->turns_left
&& pds1->has_reason_to_cancel == pds2->has_reason_to_cancel
&& pds1->contact_turns_left == pds2->contact_turns_left);
}
/*******************************************************************//**
Return TRUE iff player1 has the diplomatic relation to player2
***********************************************************************/
bool is_diplrel_between(const struct player *player1,
const struct player *player2,
int diplrel)
{
fc_assert(player1 != NULL);
fc_assert(player2 != NULL);
/* No relationship to it self. */
if (player1 == player2 && diplrel != DRO_FOREIGN) {
return FALSE;
}
if (diplrel < DS_LAST) {
return player_diplstate_get(player1, player2)->type == diplrel;
}
switch (diplrel) {
case DRO_GIVES_SHARED_VISION:
return gives_shared_vision(player1, player2);
case DRO_RECEIVES_SHARED_VISION:
return gives_shared_vision(player2, player1);
case DRO_HOSTS_EMBASSY:
return player_has_embassy(player2, player1);
case DRO_HAS_EMBASSY:
return player_has_embassy(player1, player2);
case DRO_HOSTS_REAL_EMBASSY:
return player_has_real_embassy(player2, player1);
case DRO_HAS_REAL_EMBASSY:
return player_has_real_embassy(player1, player2);
case DRO_HAS_CASUS_BELLI:
return 0 < player_diplstate_get(player1, player2)->has_reason_to_cancel;
case DRO_PROVIDED_CASUS_BELLI:
return 0 < player_diplstate_get(player2, player1)->has_reason_to_cancel;
case DRO_FOREIGN:
return player1 != player2;
}
fc_assert_msg(FALSE, "diplrel_between(): invalid diplrel number %d.",
diplrel);
return FALSE;
}
/*******************************************************************//**
Return TRUE iff pplayer has the diplomatic relation to any living player
***********************************************************************/
bool is_diplrel_to_other(const struct player *pplayer, int diplrel)
{
fc_assert(pplayer != NULL);
players_iterate_alive(oplayer) {
if (oplayer == pplayer) {
continue;
}
if (is_diplrel_between(pplayer, oplayer, diplrel)) {
return TRUE;
}
} players_iterate_alive_end;
return FALSE;
}
/*******************************************************************//**
Return the diplomatic relation that has the given (untranslated) rule
name.
***********************************************************************/
int diplrel_by_rule_name(const char *value)
{
/* Look for asymmetric diplomatic relations */
int diplrel = diplrel_other_by_name(value, fc_strcasecmp);
if (diplrel != diplrel_other_invalid()) {
return diplrel;
}
/* Look for symmetric diplomatic relations */
diplrel = diplstate_type_by_name(value, fc_strcasecmp);
/*
* Make sure DS_LAST isn't returned as DS_LAST is the first diplrel_other.
*
* Can't happend now. This is in case that changes in the future. */
fc_assert_ret_val(diplrel != DS_LAST, diplrel_other_invalid());
/*
* Make sure that diplrel_other_invalid() is returned.
*
* Can't happen now. At the moment dpilrel_asym_invalid() is the same as
* diplstate_type_invalid(). This is in case that changes in the future.
*/
if (diplrel != diplstate_type_invalid()) {
return diplrel;
}
return diplrel_other_invalid();
}
/*******************************************************************//**
Return the (untranslated) rule name of the given diplomatic relation.
***********************************************************************/
const char *diplrel_rule_name(int value)
{
if (value < DS_LAST) {
return diplstate_type_name(value);
} else {
return diplrel_other_name(value);
}
}
/*******************************************************************//**
Return the translated name of the given diplomatic relation.
***********************************************************************/
const char *diplrel_name_translation(int value)
{
if (value < DS_LAST) {
return diplstate_type_translated_name(value);
} else {
return _(diplrel_other_name(value));
}
}
/**************************************************************************
Return the Casus Belli range when offender performs paction to tgt_plr
at tgt_tile and the outcome is outcome.
**************************************************************************/
enum casus_belli_range casus_belli_range_for(const struct player *offender,
const struct unit_type *offender_utype,
const struct player *tgt_plr,
const enum effect_type outcome,
const struct action *paction,
const struct tile *tgt_tile)
{
int casus_belli_amount;
/* The victim gets a casus belli if CASUS_BELLI_VICTIM or above. Everyone
* gets a casus belli if CASUS_BELLI_OUTRAGE or above. */
casus_belli_amount =
get_target_bonus_effects(NULL,
offender, tgt_plr,
tile_city(tgt_tile),
NULL,
tgt_tile,
NULL, offender_utype,
NULL, NULL,
paction,
outcome);
if (casus_belli_amount >= CASUS_BELLI_OUTRAGE) {
/* International outrage: This isn't just between the offender and the
* victim. */
return CBR_INTERNATIONAL_OUTRAGE;
}
if (casus_belli_amount >= CASUS_BELLI_VICTIM) {
/* In this situation the specified action provides a casus belli
* against the actor. */
return CBR_VICTIM_ONLY;
}
return CBR_NONE;
}
/* The number of mutually exclusive requirement sets that
* diplrel_mess_gen() creates for the DiplRel requirement type. */
#define DIPLREL_MESS_SIZE (3 + (DRO_LAST * (5 + 4 + 3 + 2 + 1)))
/*******************************************************************//**
Generate and return an array of mutually exclusive requirement sets for
the DiplRel requirement type. The array has DIPLREL_MESS_SIZE sets.
A mutually exclusive set is a set of requirements were the presence of
one requirement proves the absence of every other requirement. In other
words: at most one of the requirements in the set can be present.
***********************************************************************/
static bv_diplrel_all_reqs *diplrel_mess_gen(void)
{
/* The ranges supported by the DiplRel requiremnt type. */
const enum req_range legal_ranges[] = {
REQ_RANGE_LOCAL,
REQ_RANGE_PLAYER,
REQ_RANGE_ALLIANCE,
REQ_RANGE_TEAM,
REQ_RANGE_WORLD
};
/* Iterators. */
int rel;
int i;
int j;
/* Storage for the mutually exclusive requirement sets. */
bv_diplrel_all_reqs *mess = fc_malloc(DIPLREL_MESS_SIZE
* sizeof(bv_diplrel_all_reqs));
/* Position in mess. */
int mess_pos = 0;
/* The first mutually exclusive set is about local diplstate. */
BV_CLR_ALL(mess[mess_pos]);
/* It is not possible to have more than one diplstate to a nation. */
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(DS_ARMISTICE, REQ_RANGE_LOCAL, TRUE));
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(DS_WAR, REQ_RANGE_LOCAL, TRUE));
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(DS_CEASEFIRE, REQ_RANGE_LOCAL, TRUE));
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(DS_PEACE, REQ_RANGE_LOCAL, TRUE));
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(DS_ALLIANCE, REQ_RANGE_LOCAL, TRUE));
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(DS_NO_CONTACT, REQ_RANGE_LOCAL, TRUE));
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(DS_TEAM, REQ_RANGE_LOCAL, TRUE));
/* It is not possible to have a diplstate to your self. */
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(DRO_FOREIGN, REQ_RANGE_LOCAL, FALSE));
mess_pos++;
/* Having a real embassy excludes not having an embassy. */
BV_CLR_ALL(mess[mess_pos]);
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(DRO_HAS_REAL_EMBASSY, REQ_RANGE_LOCAL,
TRUE));
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(DRO_HAS_EMBASSY, REQ_RANGE_LOCAL,
FALSE));
mess_pos++;
/* Hosting a real embassy excludes not hosting an embassy. */
BV_CLR_ALL(mess[mess_pos]);
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(DRO_HOSTS_REAL_EMBASSY, REQ_RANGE_LOCAL,
TRUE));
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(DRO_HOSTS_EMBASSY, REQ_RANGE_LOCAL,
FALSE));
mess_pos++;
/* Loop over diplstate_type and diplrel_other. */
for (rel = 0; rel < DRO_LAST; rel++) {
/* The presence of a DiplRel at a more local range proves that it can't
* be absent in a more global range. (The alliance range includes the
* Team range) */
for (i = 0; i < 5; i++) {
for (j = i; j < 5; j++) {
BV_CLR_ALL(mess[mess_pos]);
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(rel, legal_ranges[i], TRUE));
BV_SET(mess[mess_pos],
requirement_diplrel_ereq(rel, legal_ranges[j], FALSE));
mess_pos++;
}
}
}
/* No uninitialized element exists. */
fc_assert(mess_pos == DIPLREL_MESS_SIZE);
return mess;
}
/* An array of mutually exclusive requirement sets for the DiplRel
* requirement type. Is initialized the first time diplrel_mess_get() is
* called. */
static bv_diplrel_all_reqs *diplrel_mess = NULL;
/*******************************************************************//**
Get the mutually exclusive requirement sets for DiplRel.
***********************************************************************/
static bv_diplrel_all_reqs *diplrel_mess_get(void)
{
if (diplrel_mess == NULL) {
/* This is the first call. Initialize diplrel_mess. */
diplrel_mess = diplrel_mess_gen();
}
return diplrel_mess;
}
/*******************************************************************//**
Free diplrel_mess
***********************************************************************/
void diplrel_mess_close(void)
{
if (diplrel_mess != NULL) {
free(diplrel_mess);
diplrel_mess = NULL;
}
}
/*******************************************************************//**
Get the DiplRel requirements that are known to contradict the specified
DiplRel requirement.
The known contratictions have their position in the enumeration of all
possible DiplRel requirements set in the returned bitvector.
***********************************************************************/
bv_diplrel_all_reqs diplrel_req_contradicts(const struct requirement *req)
{
int diplrel_req_num;
bv_diplrel_all_reqs *mess;
bv_diplrel_all_reqs known;
int set;
/* Nothing is known to contradict the requirement yet. */
BV_CLR_ALL(known);
if (req->source.kind != VUT_DIPLREL) {
/* No known contradiction of a requirement of any other kind. */
fc_assert(req->source.kind == VUT_DIPLREL);
return known;
}
/* Convert the requirement to its position in the enumeration of all
* DiplRel requirements. */
diplrel_req_num = requirement_diplrel_ereq(req->source.value.diplrel,
req->range, req->present);
/* Get the mutually exclusive requirement sets for DiplRel. */
mess = diplrel_mess_get();
/* Add all known contradictions. */
for (set = 0; set < DIPLREL_MESS_SIZE; set++) {
if (BV_ISSET(mess[set], diplrel_req_num)) {
/* The requirement req is mentioned in the set. It is therefore known
* that all other requirements in the set contradicts it. They should
* therefore be added to the known contradictions. */
BV_SET_ALL_FROM(known, mess[set]);
}
}
/* The requirement isn't self contradicting. It was set by the mutually
* exclusive requirement sets that mentioned it. Remove it. */
BV_CLR(known, diplrel_req_num);
return known;
}
/*******************************************************************//**
Return the number of pplayer2's visible units in pplayer's territory,
from the point of view of pplayer. Units that cannot be seen by pplayer
will not be found (this function doesn't cheat).
***********************************************************************/
int player_in_territory(const struct player *pplayer,
const struct player *pplayer2)
{
int in_territory = 0;
/* This algorithm should work at server or client. It only returns the
* number of visible units (a unit can potentially hide inside the
* transport of a different player).
*
* Note this may be quite slow. An even slower alternative is to iterate
* over the entire map, checking all units inside the player's territory
* to see if they're owned by the enemy. */
unit_list_iterate(pplayer2->units, punit) {
/* Get the owner of the tile/territory. */
struct player *owner = tile_owner(unit_tile(punit));
if (owner == pplayer && can_player_see_unit(pplayer, punit)) {
/* Found one! */
in_territory += 1;
}
} unit_list_iterate_end;
return in_territory;
}
/*******************************************************************//**
Returns whether this is a valid username. This is used by the server to
validate usernames and should be used by the client to avoid invalid
ones.
***********************************************************************/
bool is_valid_username(const char *name)
{
return (strlen(name) > 0
&& !fc_isdigit(name[0])
//&& is_ascii_name(name)
&& fc_strcasecmp(name, ANON_USER_NAME) != 0);
}
/*******************************************************************//**
Return is AI can be set to given level
***********************************************************************/
bool is_settable_ai_level(enum ai_level level)
{
if (level == AI_LEVEL_AWAY) {
/* Cannot set away level for AI */
return FALSE;
}
return TRUE;
}
/*******************************************************************//**
Return number of AI levels in game
***********************************************************************/
int number_of_ai_levels(void)
{
return AI_LEVEL_COUNT - 1; /* AI_LEVEL_AWAY is not real AI */
}
/*******************************************************************//**
Return pointer to ai data of given player and ai type.
***********************************************************************/
void *player_ai_data(const struct player *pplayer, const struct ai_type *ai)
{
return pplayer->server.ais[ai_type_number(ai)];
}
/*******************************************************************//**
Attach ai data to player
***********************************************************************/
void player_set_ai_data(struct player *pplayer, const struct ai_type *ai,
void *data)
{
pplayer->server.ais[ai_type_number(ai)] = data;
}
/*******************************************************************//**
Return the multiplier value currently in effect for pplayer (in display
units).
***********************************************************************/
int player_multiplier_value(const struct player *pplayer,
const struct multiplier *pmul)
{
return pplayer->multipliers[multiplier_index(pmul)];
}
/*******************************************************************//**
Return the multiplier value currently in effect for pplayer, scaled
from display units to the units used in the effect system (if different).
Result is multiplied by 100 (caller should divide down).
***********************************************************************/
int player_multiplier_effect_value(const struct player *pplayer,
const struct multiplier *pmul)
{
return (player_multiplier_value(pplayer, pmul) + pmul->offset)
* pmul->factor;
}
/*******************************************************************//**
Return the player's target value for a multiplier (which may be
different from the value currently in force; it will take effect
next turn). Result is in display units.
***********************************************************************/
int player_multiplier_target_value(const struct player *pplayer,
const struct multiplier *pmul)
{
return pplayer->multipliers_target[multiplier_index(pmul)];
}
/*******************************************************************//**
Check if player has given flag
***********************************************************************/
bool player_has_flag(const struct player *pplayer, enum plr_flag_id flag)
{
return BV_ISSET(pplayer->flags, flag);
}
| 0 | 0.975354 | 1 | 0.975354 | game-dev | MEDIA | 0.84224 | game-dev | 0.730071 | 1 | 0.730071 |
TempleRAIL/pedsim_ros_with_gazebo | 7,135 | 3rdparty/libpedsim/src/ped_scene.cpp | //
// pedsim - A microscopic pedestrian simulation system.
// Copyright (c) 2003 - 2012 by Christian Gloor
//
#include "ped_scene.h"
#include "ped_agent.h"
#include "ped_obstacle.h"
#include "ped_tree.h"
#include "ped_waypoint.h"
#include <algorithm>
#include <cstddef>
#include <stack>
using namespace std;
/// Default constructor. If this constructor is used, there will be no quadtree
/// created.
/// This is faster for small scenarios or less than 1000 Tagents.
Ped::Tscene::Tscene() : tree(NULL) {}
/// Constructor used to create a quadtree statial representation of the Tagents.
/// Use this
/// constructor when you have a sparsely populated world with many agents
/// (>1000).
/// The agents must not be outside the boundaries given here. If in doubt, use
/// an initial
//// boundary that is way to big.
/// \todo Get rid of that limitation. A dynamical outer boundary algorithm
/// would be nice.
/// \param left is the left side of the boundary
/// \param top is the upper side of the boundary
/// \param width is the total width of the boundary. Basically from left to
/// right.
/// \param height is the total height of the boundary. Basically from top to
/// down.
Ped::Tscene::Tscene(double left, double top, double width, double height) {
tree = new Ped::Ttree(this, 0, left, top, width, height);
}
/// Destructor
Ped::Tscene::~Tscene() { delete tree; }
void Ped::Tscene::clear() {
// clear tree
treehash.clear();
tree->clear();
// remove all agents
for (Ped::Tagent* currentAgent : agents) delete currentAgent;
agents.clear();
// remove all obstacles
for (Ped::Tobstacle* currentObstacle : obstacles) delete currentObstacle;
obstacles.clear();
// remove all waypoints
for (Ped::Twaypoint* currentWaypoint : waypoints) delete currentWaypoint;
waypoints.clear();
}
/// Used to add a Tagent to the Tscene.
/// \warning addAgent() does call Tagent::assignScene() to assign itself to the
/// agent.
/// \param *a A pointer to the Tagent to add.
void Ped::Tscene::addAgent(Ped::Tagent* a) {
// add agent to scene
// (take responsibility for object deletion)
agents.push_back(a);
a->assignScene(this);
if (tree != NULL) tree->addAgent(a);
}
/// Used to add a Tobstacle to the Tscene.
/// \param *o A pointer to the Tobstacle to add.
/// \note Obstacles added to the Scene are not deleted if the Scene is
/// destroyed. The reason for this is because they could be member of another
/// Scene theoretically.
void Ped::Tscene::addObstacle(Ped::Tobstacle* o) {
// add obstacle to scene
// (take responsibility for object deletion)
obstacles.push_back(o);
}
void Ped::Tscene::addWaypoint(Ped::Twaypoint* w) {
// add waypoint to scene
// (take responsibility for object deletion)
waypoints.push_back(w);
}
bool Ped::Tscene::removeAgent(Ped::Tagent* a) {
// find position of agent in agent vector
vector<Tagent*>::iterator agentIter = find(agents.begin(), agents.end(), a);
// check whether the agent was found
if (agentIter == agents.end()) return false;
// remove agent as potential neighbor
for (Tagent* currentAgent : agents) currentAgent->removeAgentFromNeighbors(a);
// remove agent from the tree
if (tree != NULL) tree->removeAgent(a);
// remove agent from the scene and delete it, report succesful removal
agents.erase(agentIter);
delete a;
return true;
}
bool Ped::Tscene::removeObstacle(Ped::Tobstacle* o) {
// find position of obstacle in obstacle vector
vector<Tobstacle*>::iterator obstacleIter =
find(obstacles.begin(), obstacles.end(), o);
// check whether the obstacle was found
if (obstacleIter == obstacles.end()) return false;
// remove obstacle from the scene and delete it, report succesful removal
obstacles.erase(obstacleIter);
delete o;
return true;
}
bool Ped::Tscene::removeWaypoint(Ped::Twaypoint* w) {
// find position of waypoint in waypoint vector
vector<Twaypoint*>::iterator waypointIter =
find(waypoints.begin(), waypoints.end(), w);
// check whether the waypoint was found
if (waypointIter == waypoints.end()) return false;
// remove waypoint from the scene and delete it, report succesful removal
waypoints.erase(waypointIter);
delete w;
return true;
}
/// This is a convenience method. It calls Ped::Tagent::move(double h) for all
/// agents in the Tscene.
/// \param h This tells the simulation how far the agents should proceed.
/// \see Ped::Tagent::move(double h)
void Ped::Tscene::moveAgents(double h) {
// first update states
for (Tagent* agent : agents) agent->updateState();
// then update forces
for (Tagent* agent : agents) agent->computeForces();
// finally move agents according to their forces
for (Tagent* agent : agents) agent->move(h);
}
/// Internally used to update the quadtree.
void Ped::Tscene::placeAgent(const Ped::Tagent* agentIn) {
if (tree != NULL) tree->addAgent(agentIn);
}
/// Moves a Tagent within the tree structure. The new position is taken from the
/// agent. So it
/// basically updates the tree structure for that given agent.
/// Ped::Tagent::move(double h) calls
/// this method automatically.
/// \param *agentIn the agent to move.
void Ped::Tscene::moveAgent(const Ped::Tagent* agentIn) {
if (tree != NULL) treehash[agentIn]->moveAgent(agentIn);
}
/// This triggers a cleanup of the tree structure. Unused leaf nodes are
/// collected in order to
/// save memory. Ideally cleanup() is called every second, or about every 20
/// timestep.
/// \date 2012-01-28
void Ped::Tscene::cleanup() {
if (tree != NULL) tree->cut();
}
/// Returns the list of neighbors within dist of the point x/y. This
/// can be the position of an agent, but it is not limited to this.
/// \date 2012-01-29
/// \return The list of neighbors
/// \param x the x coordinate
/// \param y the y coordinate
/// \param dist the distance around x/y that will be searched for agents
/// (search field is a square in the current implementation)
set<const Ped::Tagent*> Ped::Tscene::getNeighbors(double x, double y,
double dist) const {
// if there is no tree, return all agents
if (tree == NULL)
return set<const Ped::Tagent*>(agents.begin(), agents.end());
// create the output list
vector<const Ped::Tagent*> neighborList;
getNeighbors(neighborList, x, y, dist);
// copy the neighbors to a set
return set<const Ped::Tagent*>(neighborList.begin(), neighborList.end());
}
void Ped::Tscene::getNeighbors(vector<const Ped::Tagent*>& neighborList,
double x, double y, double dist) const {
stack<Ped::Ttree*> treestack;
treestack.push(tree);
while (!treestack.empty()) {
Ped::Ttree* t = treestack.top();
treestack.pop();
if (t->isleaf) {
t->getAgents(neighborList);
} else {
if (t->tree1->intersects(x, y, dist)) treestack.push(t->tree1);
if (t->tree2->intersects(x, y, dist)) treestack.push(t->tree2);
if (t->tree3->intersects(x, y, dist)) treestack.push(t->tree3);
if (t->tree4->intersects(x, y, dist)) treestack.push(t->tree4);
}
}
}
| 0 | 0.958883 | 1 | 0.958883 | game-dev | MEDIA | 0.683016 | game-dev | 0.969097 | 1 | 0.969097 |
fawkesrobotics/fawkes | 3,542 | src/plugins/attic/katana/controller_openrave.h |
/***************************************************************************
* controller_openrave.h - OpenRAVE Controller class for katana arm
*
* Created: Sat Jan 07 16:10:54 2012
* Copyright 2012-2014 Bahram Maleki-Fard
*
****************************************************************************/
/* 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 Library General Public License for more details.
*
* Read the full text in the LICENSE.GPL file in the doc directory.
*/
#ifndef _PLUGINS_KATANA_CONTROLLER_OPENRAVE_H_
#define _PLUGINS_KATANA_CONTROLLER_OPENRAVE_H_
#include "controller.h"
#include <core/utils/refptr.h>
#ifdef HAVE_OPENRAVE
# include <openrave/openrave.h>
# include <plugins/openrave/types.h>
#endif
#include <memory>
#include <string>
#include <vector>
namespace fawkes {
class OpenRaveConnector;
class KatanaControllerOpenrave : public KatanaController
{
#ifdef HAVE_OPENRAVE
public:
KatanaControllerOpenrave(fawkes::OpenRaveConnector *openrave);
virtual ~KatanaControllerOpenrave();
// setup
virtual void init();
virtual void set_max_velocity(unsigned int vel);
// status checking
virtual bool final();
virtual bool joint_angles();
virtual bool joint_encoders();
// commands
virtual void calibrate();
virtual void stop();
virtual void turn_on();
virtual void turn_off();
virtual void read_coordinates(bool refresh = false);
virtual void read_motor_data();
virtual void read_sensor_data();
virtual void gripper_open(bool blocking = false);
virtual void gripper_close(bool blocking = false);
virtual void
move_to(float x, float y, float z, float phi, float theta, float psi, bool blocking = false);
virtual void move_to(std::vector<int> encoders, bool blocking = false);
virtual void move_to(std::vector<float> angles, bool blocking = false);
virtual void move_motor_to(unsigned short id, int enc, bool blocking = false);
virtual void move_motor_to(unsigned short id, float angle, bool blocking = false);
virtual void move_motor_by(unsigned short id, int enc, bool blocking = false);
virtual void move_motor_by(unsigned short id, float angle, bool blocking = false);
// getters
virtual double x();
virtual double y();
virtual double z();
virtual double phi();
virtual double theta();
virtual double psi();
virtual void get_sensors(std::vector<int> &to, bool refresh = false);
virtual void get_encoders(std::vector<int> &to, bool refresh = false);
virtual void get_angles(std::vector<float> &to, bool refresh = false);
private:
double x_, y_, z_;
double phi_, theta_, psi_;
fawkes::OpenRaveConnector *openrave_;
fawkes::OpenRaveEnvironmentPtr OR_env_;
fawkes::OpenRaveRobotPtr OR_robot_;
fawkes::OpenRaveManipulatorPtr OR_manip_;
OpenRAVE::EnvironmentBasePtr env_;
OpenRAVE::RobotBasePtr robot_;
OpenRAVE::RobotBase::ManipulatorPtr manip_;
bool initialized_;
std::vector<short> active_motors_;
void update_manipulator();
void wait_finished();
void check_init();
bool motor_oor(unsigned short id);
#endif //HAVE_OPENRAVE
};
} // end of namespace fawkes
#endif
| 0 | 0.901007 | 1 | 0.901007 | game-dev | MEDIA | 0.280134 | game-dev | 0.582362 | 1 | 0.582362 |
coryleach/UnityGUI | 1,835 | Runtime/Effects/TypewriterTextTMPro.cs | using System.Collections;
using TMPro;
using UnityEngine;
namespace Gameframe.GUI
{
public class TypewriterTextTMPro : BaseTypewriterText
{
[SerializeField]
private TextMeshProUGUI text;
public override int CharacterPerSecond
{
get => charactersPerSecond;
set
{
charactersPerSecond = value;
waitInterval = new WaitForSeconds(1.0f / charactersPerSecond);
}
}
[ContextMenu("Play")]
public override void Play()
{
Play(text.text);
}
public override void Finish()
{
base.Finish();
text.text = currentMessage;
}
private readonly WaitForEndOfFrame waitEndOfFrame = new WaitForEndOfFrame();
private WaitForSeconds waitInterval;
protected override IEnumerator RunType()
{
if (waitInterval == null)
{
waitInterval = new WaitForSeconds(1.0f / charactersPerSecond);
}
text.text = currentMessage;
text.maxVisibleCharacters = 0;
for (var i = 0; i < currentMessage.Length; i++)
{
text.maxVisibleCharacters = i;
yield return waitInterval;
yield return waitEndOfFrame;
}
text.maxVisibleCharacters = 99999;
typeCoroutine = null;
onComplete.Invoke();
}
protected override void OnValidate()
{
base.OnValidate();
if (text == null)
{
text = GetComponent<TextMeshProUGUI>();
}
waitInterval = new WaitForSeconds(1.0f/charactersPerSecond);
}
}
} | 0 | 0.921967 | 1 | 0.921967 | game-dev | MEDIA | 0.826594 | game-dev | 0.919677 | 1 | 0.919677 |
SpongePowered/Sponge | 5,005 | forge/src/launch/java/org/spongepowered/forge/launch/command/ForgeCommandManager.java | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.forge.launch.command;
import com.google.common.base.Throwables;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.context.CommandContextBuilder;
import com.mojang.brigadier.context.ParsedArgument;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.kyori.adventure.text.Component;
import net.minecraft.commands.CommandSourceStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.CommandEvent;
import org.spongepowered.api.Game;
import org.spongepowered.api.command.CommandCause;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.exception.CommandException;
import org.spongepowered.api.command.manager.CommandMapping;
import org.spongepowered.api.command.registrar.CommandRegistrar;
import org.spongepowered.common.command.brigadier.SpongeStringReader;
import org.spongepowered.common.command.manager.SpongeCommandManager;
import org.spongepowered.common.command.registrar.BrigadierBasedRegistrar;
import org.spongepowered.common.command.sponge.SpongeCommand;
import java.util.Collections;
public final class ForgeCommandManager extends SpongeCommandManager {
@Inject
public ForgeCommandManager(final Game game, final Provider<SpongeCommand> spongeCommand) {
super(game, spongeCommand);
}
@Override
public CommandResult processCommand(final CommandCause cause, final CommandMapping mapping,
final String command, final String args)
throws CommandException {
final String original = args.isEmpty() ? command : (command + " " + args); // TODO SF 1.19.4, should we pass the original string as a param?
final CommandRegistrar<?> registrar = mapping.registrar();
final boolean isBrig = registrar instanceof BrigadierBasedRegistrar;
final ParseResults<CommandSourceStack> parseResults;
if (isBrig) {
parseResults = this.getDispatcher().parse(original, (CommandSourceStack) cause);
} else {
// We have a non Brig registrar, so we just create a dummy result for mods to inspect.
final CommandContextBuilder<CommandSourceStack> contextBuilder = new CommandContextBuilder<>(
this.getDispatcher(),
(CommandSourceStack) cause,
this.getDispatcher().getRoot(),
0);
contextBuilder.withCommand(ctx -> 1);
if (!args.isEmpty()) {
contextBuilder.withArgument("parsed", new ParsedArgument<>(command.length(), original.length(), args));
}
parseResults = new ParseResults<>(contextBuilder, new SpongeStringReader(original), Collections.emptyMap());
}
// Relocated from Commands (injection short circuits it there)
final CommandEvent event = new CommandEvent(parseResults);
if (MinecraftForge.EVENT_BUS.post(event)) {
if (event.getException() != null) {
Throwables.throwIfUnchecked(event.getException());
}
// As per Forge, we just treat it as a zero success, and do nothing with it.
return CommandResult.builder().result(0).build();
}
if (isBrig) {
try {
return CommandResult.builder().result(this.getDispatcher().execute(parseResults)).build();
} catch (CommandSyntaxException e) {
throw new CommandException(Component.empty(), e); // TODO SF 1.19.4, what message should we put there?
}
} else {
return mapping.registrar().process(cause, mapping, command, args);
}
}
}
| 0 | 0.936948 | 1 | 0.936948 | game-dev | MEDIA | 0.959951 | game-dev | 0.963484 | 1 | 0.963484 |
remance/Masendor | 2,255 | engine/unit/pick_animation.py | from random import choice
equip_set = ("Main", "Sub")
def pick_animation(self):
if self.current_action: # pick animation with current action
if "Action " in self.current_action["name"]:
weapon = self.current_action["weapon"]
animation_name = equip_set[weapon] + "_"
if "run" in self.current_action:
animation_name += "Run" + self.action_list[weapon]["Attack Action"]
elif "walk" in self.current_action:
animation_name += "Walk" + self.action_list[weapon]["Attack Action"]
else:
animation_name += self.action_list[weapon]["Attack Action"]
elif "charge" in self.current_action:
weapon = self.current_action["weapon"]
animation_name = equip_set[weapon] + "_Charge"
else:
animation_name = self.current_action["name"]
else: # idle animation
animation_name = "Idle"
self.current_animation = {key: value for key, value in self.animation_pool.items() if animation_name in key}
self.current_animation = {key: value for key, value in self.current_animation.items() if "/" not in key or
str(self.equipped_weapon_str) == key[-1]}
if self.current_animation:
self.current_animation = self.current_animation[choice(tuple(self.current_animation.keys()))]
else: # animation not found, use default
self.current_animation = self.animation_pool["Default"]
# print(self.name, animation_name)
# print(list(self.animation_pool.keys()))
self.current_animation_direction = self.current_animation[self.sprite_direction]
self.max_show_frame = self.current_animation["frame_number"]
current_animation = self.current_animation_direction[self.show_frame]
self.image = current_animation["sprite"]
self.offset_pos = self.pos - current_animation["center_offset"]
self.rect = self.image.get_rect(center=self.offset_pos)
self.animation_play_time = self.default_animation_play_time # get new play speed
if "play_time_mod" in self.current_animation[self.show_frame]["property"]:
self.animation_play_time *= self.current_animation[self.show_frame]["property"]["play_time_mod"]
| 0 | 0.792688 | 1 | 0.792688 | game-dev | MEDIA | 0.977982 | game-dev | 0.965758 | 1 | 0.965758 |
RoseGoldIsntGay/GumTuneClient | 5,444 | src/main/java/rosegold/gumtuneclient/mixin/MixinMinecraft.java | package rosegold.gumtuneclient.mixin;
import net.minecraft.block.BlockCocoa;
import net.minecraft.block.BlockCrops;
import net.minecraft.block.BlockNetherWart;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.io.IOUtils;
import org.lwjgl.opengl.Display;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import rosegold.gumtuneclient.GumTuneClient;
import rosegold.gumtuneclient.config.GumTuneClientConfig;
import rosegold.gumtuneclient.modules.farming.AvoidBreakingCrops;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
@Mixin(Minecraft.class)
public class MixinMinecraft {
@Shadow
private int leftClickCounter;
@Shadow
public MovingObjectPosition objectMouseOver;
@Shadow
public EntityPlayerSP thePlayer;
@Inject(method = "clickMouse", at = @At(value = "HEAD"), cancellable = true)
private void onClickMouse(CallbackInfo ci) {
if (leftClickCounter <= 0 && objectMouseOver != null && objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
if (shouldCancelBreak()) {
if (GumTuneClientConfig.avoidBreakingMode == 1) {
BlockPos blockPos = objectMouseOver.getBlockPos();
AvoidBreakingCrops.addBlock(blockPos, GumTuneClient.mc.theWorld.getBlockState(blockPos));
GumTuneClient.mc.theWorld.setBlockToAir(blockPos);
}
ci.cancel();
}
}
}
@Inject(method = "sendClickBlockToController", at = @At(value = "HEAD"), cancellable = true)
private void onSendClickBlockToController(boolean leftClick, CallbackInfo ci) {
if (leftClickCounter <= 0 && !thePlayer.isUsingItem() && leftClick && objectMouseOver != null && objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
if (shouldCancelBreak()) {
if (GumTuneClientConfig.avoidBreakingMode == 1) {
BlockPos blockPos = objectMouseOver.getBlockPos();
AvoidBreakingCrops.addBlock(blockPos, GumTuneClient.mc.theWorld.getBlockState(blockPos));
GumTuneClient.mc.theWorld.setBlockToAir(blockPos);
}
ci.cancel();
}
}
}
@Inject(method = "setWindowIcon", at = @At("RETURN"))
private void fuckNewIcon(CallbackInfo ci) {
if (!GumTuneClientConfig.oldMinecraftLogo) return;
InputStream inputStream16 = null;
InputStream inputStream32 = null;
try {
inputStream16 = GumTuneClient.mc.mcDefaultResourcePack.getInputStreamAssets(new ResourceLocation("old_icon_16x16.png"));
inputStream32 = GumTuneClient.mc.mcDefaultResourcePack.getInputStreamAssets(new ResourceLocation("old_icon_32x32.png"));
if (inputStream16 == null || inputStream32 == null) return;
System.out.println("Set icon to old one!");
Display.setIcon(new ByteBuffer[]{readImageToBuffer(inputStream16), readImageToBuffer(inputStream32)});
} catch (IOException ioexception) {
IOUtils.closeQuietly(inputStream16);
IOUtils.closeQuietly(inputStream32);
ioexception.printStackTrace();
}
}
private ByteBuffer readImageToBuffer(InputStream imageStream) throws IOException {
BufferedImage bufferedimage = ImageIO.read(imageStream);
int[] aint = bufferedimage.getRGB(0, 0, bufferedimage.getWidth(), bufferedimage.getHeight(), null, 0, bufferedimage.getWidth());
ByteBuffer bytebuffer = ByteBuffer.allocate(4 * aint.length);
for (int i : aint) {
bytebuffer.putInt(i << 8 | i >> 24 & 0xFF);
}
bytebuffer.flip();
return bytebuffer;
}
private boolean shouldCancelBreak() {
BlockPos blockPos = objectMouseOver.getBlockPos();
IBlockState blockState = GumTuneClient.mc.theWorld.getBlockState(blockPos);
if (GumTuneClientConfig.avoidBreakingStems && (blockState.getBlock() == Blocks.melon_stem || blockState.getBlock() == Blocks.pumpkin_stem)) {
return true;
}
if (GumTuneClientConfig.avoidBreakingBottomSugarCane && blockState.getBlock() == Blocks.reeds && GumTuneClient.mc.theWorld.getBlockState(blockPos.add(0, -1, 0)).getBlock() != Blocks.reeds) {
return true;
}
if (GumTuneClientConfig.avoidBreakingChildCrops) {
if (blockState.getBlock() instanceof BlockNetherWart) {
return blockState.getValue(BlockNetherWart.AGE) != 3;
} else if (blockState.getBlock() instanceof BlockCrops) {
return blockState.getValue(BlockCrops.AGE) != 7;
} else if (blockState.getBlock() instanceof BlockCocoa) {
return blockState.getValue(BlockCocoa.AGE) != 2;
}
}
return false;
}
}
| 0 | 0.914917 | 1 | 0.914917 | game-dev | MEDIA | 0.932795 | game-dev | 0.976774 | 1 | 0.976774 |
etlegacy/etlegacy-deprecated | 29,274 | etmain/maps/radar.script | // rain - Tue Sep 23 20:40:37 EDT 2003 - fixed setautospawns
// rain - Mon Feb 9 23:50:28 EST 2004 - made truck non-dynamitable
game_manager
{
spawn
{
// Game rules
wm_axis_respawntime 30
wm_allied_respawntime 20
wm_number_of_objectives 5
wm_set_round_timelimit 20
// Objectives
// 1: Get into radar installation
// 2: Deconstruct radar(s)
// 3: Forward Bunker
// 4: Axis Field Command
// 5: Allies Base of Operations
wm_objective_status 1 1 0
wm_objective_status 1 0 0
wm_objective_status 2 1 0
wm_objective_status 2 0 0
wm_objective_status 3 1 0
wm_objective_status 3 0 0
wm_objective_status 4 1 0
wm_objective_status 4 0 0
wm_objective_status 5 1 0
wm_objective_status 5 0 0
// Stopwatch mode defending team (0=Axis, 1=Allies)
wm_set_defending_team 0
// Winner on expiration of round timer (0=Axis, 1=Allies)
wm_setwinner 0
accum 1 set 0 // Set counter for radar equipment
wait 500
// spawns:
// Abandoned Villa
// Forward Bunker
// Lower Warehouse
// rain - set allied initial autospawn properly
setautospawn "Abandoned Villa" 1
setautospawn "Forward Bunker" 0
disablespeaker allies_compost_sound
disablespeaker axis_compost_sound
// wait for everything to settle
wait 500
// *----------------------------------- vo ------------------------------------------*
wm_addteamvoiceannounce 0 "radar_axis_entrances_defend"
wm_addteamvoiceannounce 0 "radar_axis_bunker_stop"
wm_addteamvoiceannounce 0 "axis_hq_compost_construct"
wm_addteamvoiceannounce 1 "radar_allies_entrances_destroy"
wm_addteamvoiceannounce 1 "radar_allies_bunker_capture"
wm_teamvoiceannounce 0 "radar_axis_entrances_defend"
wm_teamvoiceannounce 0 "radar_axis_bunker_stop"
wm_teamvoiceannounce 0 "axis_hq_compost_construct"
wm_teamvoiceannounce 1 "radar_allies_entrances_destroy"
wm_teamvoiceannounce 1 "radar_allies_bunker_capture"
// *---------------------------------------------------------------------------------*
// don't use wm_set_main_objective
// on radar there are always several main objectives (maindoor-sidedoor, radar1-radar2 ...)
// FIXME: we might add main objective at end when there is only 1 radar left
//wm_set_main_objective 1 0
//wm_set_main_objective 1 1
}
trigger stolen_circuit
{
accum 1 inc 1 // One circuit board home
trigger game_manager checkgame // Check for end of game
}
trigger maindoor1_destroyed
{
wm_objective_status 1 1 1
wm_objective_status 1 0 2
// spawns:
// Abandoned Villa
// Forward Bunker
// Lower Warehouse
setautospawn "Forward Bunker" 1
setautospawn "Lower Warehouse" 0
trigger roadbunker kill // Switch forward spawn to Allied ONLY
wm_announce "Allies have breached the Main Entrance and secured the Forward Bunker!"
wait 1000
// *----------------------------------- vo ------------------------------------------*
wm_addteamvoiceannounce 0 "radar_axis_radars_defend"
wm_addteamvoiceannounce 1 "radar_allies_radars_steal"
wm_teamvoiceannounce 0 "radar_axis_entrance1_destroyed"
wm_teamvoiceannounce 0 "radar_axis_radars_defend"
wm_teamvoiceannounce 1 "radar_allies_entrance1_destroyed"
wm_teamvoiceannounce 1 "radar_allies_radars_steal"
wm_removeteamvoiceannounce 0 "radar_axis_entrances_defend"
wm_removeteamvoiceannounce 0 "radar_axis_entrance1_defend"
wm_removeteamvoiceannounce 0 "radar_axis_bunker_stop"
wm_removeteamvoiceannounce 1 "radar_allies_entrances_destroy"
wm_removeteamvoiceannounce 1 "radar_allies_entrance1_destroy"
wm_removeteamvoiceannounce 1 "radar_allies_bunker_capture"
// *---------------------------------------------------------------------------------*
//wm_set_main_objective 2 0
//wm_set_main_objective 2 1
}
trigger sidedoor1_destroyed
{
wm_objective_status 1 1 1
wm_objective_status 1 0 2
wm_announce "Allies have breached the Side Entrance!"
// *----------------------------------- vo ------------------------------------------*
wm_addteamvoiceannounce 1 "allies_hq_compost_construct"
wm_teamvoiceannounce 0 "radar_axis_entrance2_destroyed"
wm_teamvoiceannounce 1 "radar_allies_entrance2_destroyed"
trigger allied_radio_built_model alliedcompostvo
wm_removeteamvoiceannounce 0 "radar_axis_entrances_defend"
wm_removeteamvoiceannounce 0 "radar_axis_entrance2_defend"
wm_removeteamvoiceannounce 1 "radar_allies_entrances_destroy"
wm_removeteamvoiceannounce 1 "radar_allies_entrance2_destroy"
// *---------------------------------------------------------------------------------*
//wm_set_main_objective 2 0
//wm_set_main_objective 2 1
}
trigger checkgame
{
accum 1 abort_if_not_equal 2
wm_setwinner 1
wait 1500
wm_endround
}
}
truckbox1
{
spawn
{
wait 50
setstate truckbox1 invisible
accum 1 set 0
}
trigger visible
{
setstate truckbox1 default
accum 1 abort_if_not_equal 0
wm_announce "Allies have secured the West Radar Parts!"
// *----------------------------------- vo ------------------------------------------*
wm_teamvoiceannounce 0 "radar_axis_radarw_secured"
wm_teamvoiceannounce 1 "radar_allies_radarw_secured"
wm_removeteamvoiceannounce 0 "radar_axis_radarw_defend"
// *---------------------------------------------------------------------------------*
accum 1 set 1
}
trigger invisible
{
setstate truckbox1 invisible
}
}
truckbox2
{
spawn
{
wait 50
setstate truckbox2 invisible
accum 1 set 0
}
trigger visible
{
setstate truckbox2 default
accum 1 abort_if_not_equal 0
wm_announce "Allies have secured the East Radar Parts!"
// *----------------------------------- vo ------------------------------------------*
wm_teamvoiceannounce 0 "radar_axis_radare_secured"
wm_teamvoiceannounce 1 "radar_allies_radare_secured"
wm_removeteamvoiceannounce 0 "radar_axis_radare_defend"
// *---------------------------------------------------------------------------------*
accum 1 set 1
}
trigger invisible
{
setstate truckbox2 invisible
}
}
truckboxtrans1
{
trigger visible
{
setstate truckboxtrans1 default
}
trigger invisible
{
setstate truckboxtrans1 invisible
}
}
truckboxtrans2
{
trigger visible
{
setstate truckboxtrans2 default
}
trigger invisible
{
setstate truckboxtrans2 invisible
}
}
thunderstuff
{
spawn
{
accum 0 set 0 //randomiser to play different lightnings and thunders
trigger self random
}
trigger random
{
accum 0 random 5
accum 0 trigger_if_equal 0 thunderstuff thunder01
accum 0 trigger_if_equal 1 thunderstuff thunder02
accum 0 trigger_if_equal 2 thunderstuff thunder03
accum 0 trigger_if_equal 3 thunderstuff thunder04
accum 0 trigger_if_equal 4 thunderstuff thunder05
wait 25000
trigger self random
}
trigger thunder01
{
alertentity lightning01
togglespeaker thunderspeaker01
}
trigger thunder02
{
alertentity lightning02
togglespeaker thunderspeaker02
}
trigger thunder03
{
alertentity lightning03
togglespeaker thunderspeaker03
}
trigger thunder04
{
alertentity lightning04
togglespeaker thunderspeaker04
}
trigger thunder05
{
alertentity lightning05
togglespeaker thunderspeaker05
}
}
truck_exitpoint // Exit point of map
{
death
{
trigger game_manager stolen_circuit
}
}
// ================================================
// ============== RADAR DISH MISC =================
// ================================================
radarbox1
{
spawn
{
}
trigger stolen
{
setstate circuit1 invisible
trigger circuit1_radartop down
wait 1000
// *----------------------------------- vo ------------------------------------------*
wm_teamvoiceannounce 0 "radar_axis_radarw_taken"
wm_teamvoiceannounce 1 "radar_allies_radarw_taken"
// *---------------------------------------------------------------------------------*
}
trigger dropped
{
// *----------------------------------- vo ------------------------------------------*
wm_teamvoiceannounce 0 "radar_axis_radarw_lost"
wm_teamvoiceannounce 1 "radar_allies_radarw_lost"
// *---------------------------------------------------------------------------------*
}
trigger returned
{
// *----------------------------------- vo ------------------------------------------*
wm_teamvoiceannounce 0 "radar_axis_radarw_returned"
wm_teamvoiceannounce 1 "radar_allies_radarw_returned"
// *---------------------------------------------------------------------------------*
setstate circuit1 default
trigger circuit1_radartop up
}
trigger captured
{
trigger truckbox1 visible
trigger truckboxtrans1 invisible
}
}
circuit1_radartop
{
spawn
{
accum 1 set 0 // 0:Down 1:Up
accum 2 set 0 // 0:Stationary 1:Moving
accum 3 set 0 // requested direction
wait 50
trigger circuit1_radartop up
}
trigger up
{
accum 3 set 1
accum 1 abort_if_equal 1 // Abort if UP already
accum 2 abort_if_equal 1 // Abort if moving already
stopsound
playsound sound/vehicles/misc/radar_start.wav volume 64 // radar start sound
accum 2 set 1 // Moving, DND
startanimation 0 35 15 nolerp norandom noloop
wait 2500
startanimation 34 1 15 norandom noloop // Client PVS issue
setrotation 0 30 0
accum 2 set 0 // Finished
accum 1 set 1 // Now in UP status
enablespeaker radar1_sound // radar spinning sound
accum 3 abort_if_equal 1
trigger self down
}
trigger down
{
accum 3 set 0
accum 1 abort_if_equal 0 // Abort if DOWN already
accum 2 abort_if_equal 1 // Abort if moving already
disablespeaker radar1_sound // radar spinning sound
playsound sound/vehicles/misc/radar_end.wav volume 64 // radar stop sound
accum 2 set 1 // Moving, DND
stoprotation
startanimation 34 29 15 nolerp norandom noloop
wait 2500
startanimation 0 1 15 norandom noloop // Client PVS issue
accum 2 set 0 // Finished
accum 1 set 0 // Now in DOWN status
accum 3 abort_if_equal 0
trigger self up
}
}
radarbox2
{
spawn
{
}
trigger stolen
{
setstate circuit2 invisible
trigger circuit2_radartop down
wait 1000
// *----------------------------------- vo ------------------------------------------*
wm_teamvoiceannounce 0 "radar_axis_radare_taken"
wm_teamvoiceannounce 1 "radar_allies_radare_taken"
// *---------------------------------------------------------------------------------*
}
trigger dropped
{
// *----------------------------------- vo ------------------------------------------*
wm_teamvoiceannounce 0 "radar_axis_radare_lost"
wm_teamvoiceannounce 1 "radar_allies_radare_lost"
// *---------------------------------------------------------------------------------*
}
trigger returned
{
// *----------------------------------- vo ------------------------------------------*
wm_teamvoiceannounce 0 "radar_axis_radare_returned"
wm_teamvoiceannounce 1 "radar_allies_radare_returned"
// *---------------------------------------------------------------------------------*
setstate circuit2 default
trigger circuit2_radartop up
}
trigger captured
{
trigger truckbox2 visible
trigger truckboxtrans2 invisible
}
}
circuit2_radartop
{
spawn
{
accum 1 set 0 // 0:Down 1:Up
accum 2 set 0 // 0:Stationary 1:Moving
accum 3 set 0 // requested direction
wait 2500 // Offset so both radar's don't start at the same time
trigger circuit2_radartop up
}
trigger up
{
accum 3 set 1
accum 1 abort_if_equal 1 // Abort if UP already
accum 2 abort_if_equal 1 // Abort if moving already
stopsound
playsound sound/vehicles/misc/radar_start.wav volume 64 // radar start sound
accum 2 set 1 // Moving, DND
startanimation 0 35 15 nolerp norandom noloop
wait 2500
startanimation 34 1 15 norandom noloop // Client PVS issue
setrotation 0 30 0
accum 2 set 0 // Finished
accum 1 set 1 // Now in UP status
enablespeaker radar2_sound // radar spinning sound
accum 3 abort_if_equal 1
trigger self down
}
trigger down
{
accum 3 set 0
accum 1 abort_if_equal 0 // Abort if DOWN already
accum 2 abort_if_equal 1 // Abort if moving already
disablespeaker radar2_sound // radar spinning sound
playsound sound/vehicles/misc/radar_end.wav volume 64 // radar stop sound
accum 2 set 1 // Moving, DND
stoprotation
startanimation 34 29 15 nolerp norandom noloop
wait 2500
startanimation 0 1 15 norandom noloop // Client PVS issue
accum 2 set 0 // Finished
accum 1 set 0 // Now in DOWN status
accum 3 abort_if_equal 0
trigger self up
}
}
// ================================================
// =============== BASE ENTRANCES =================
// ================================================
maindoor1 // Front door of complex
{
spawn
{
wait 50
constructible_class 3
}
death
{
trigger game_manager maindoor1_destroyed
}
}
sidedoor1 // Side door of complex
{
spawn
{
wait 50
constructible_class 3
}
death
{
trigger game_manager sidedoor1_destroyed
}
}
// ================================================
// =========== SPAWN POINT CONTROLS ===============
// ================================================
roadbunker
{
spawn
{
accum 0 set 0 // 0-Axis, 1-Allied
}
trigger axis_capture // Flag has been claimed by an axis player
{
accum 0 abort_if_equal 0 // Do Axis already own the flag?
accum 0 set 0 // Axis own the flag
wm_announce "Axis reclaim the Forward Bunker!"
wm_objective_status 3 1 2
wm_objective_status 3 0 1
// spawns:
// Abandoned Villa
// Forward Bunker
// Lower Warehouse
setautospawn "Abandoned Villa" 1
setautospawn "Forward Bunker" 0
alertentity roadbunker_wobj
// *----------------------------------- vo ------------------------------------------*
wm_addteamvoiceannounce 0 "radar_axis_bunker_stop"
wm_addteamvoiceannounce 1 "radar_allies_bunker_capture"
wm_teamvoiceannounce 0 "radar_axis_bunker_reclaimed"
wm_teamvoiceannounce 1 "radar_allies_bunker_reclaimed"
// *---------------------------------------------------------------------------------*
}
trigger allied_capture // Flag has been claimed by an allied player
{
accum 0 abort_if_equal 1 // Do Allies already own flag?
accum 0 set 1 // Allied own the flag
wm_announce "Allies capture the Forward Bunker!"
wm_objective_status 3 1 1
wm_objective_status 3 0 2
// spawns:
// Abandoned Villa
// Forward Bunker
// Lower Warehouse
setautospawn "Forward Bunker" 1
setautospawn "Lower Warehouse" 0
alertentity roadbunker_wobj
// *----------------------------------- vo ------------------------------------------*
wm_teamvoiceannounce 0 "radar_axis_bunker_captured"
wm_teamvoiceannounce 1 "radar_allies_bunker_captured"
wm_removeteamvoiceannounce 0 "radar_axis_bunker_stop"
wm_removeteamvoiceannounce 1 "radar_allies_bunker_capture"
// *---------------------------------------------------------------------------------*
}
trigger kill
{
trigger roadbunker force_allied
remove
}
trigger force_allied
{
accum 0 abort_if_equal 1 // Do Allies already own flag?
wm_objective_status 3 1 1
wm_objective_status 3 0 2
// spawns:
// Abandoned Villa
// Forward Bunker
// Lower Warehouse
setautospawn "Forward Bunker" 1
setautospawn "Lower Warehouse" 0
alertentity roadbunker_wobj
alertentity roadbunkerspawns
}
}
// *********************************************
// ************** COMMAND POST *****************
// *********************************************
axis_radio_destroyed
{
spawn
{
wait 200
accum 0 set 0
setstate axis_radio_destroyed invisible
setstate axis_radio_destroyed_model invisible
}
trigger hide
{
setstate axis_radio_destroyed invisible
setstate axis_radio_destroyed_model invisible
}
trigger show
{
accum 0 abort_if_equal 0
setstate axis_radio_destroyed default
setstate axis_radio_destroyed_model default
}
trigger enable
{
accum 0 set 1
}
trigger disable
{
accum 0 set 0
}
}
allied_radio_destroyed
{
spawn
{
wait 200
accum 0 set 0
setstate allied_radio_destroyed invisible
setstate allied_radio_destroyed_model invisible
}
trigger hide
{
setstate allied_radio_destroyed invisible
setstate allied_radio_destroyed_model invisible
}
trigger show
{
accum 0 abort_if_equal 0
setstate allied_radio_destroyed default
setstate allied_radio_destroyed_model default
}
trigger enable
{
accum 0 set 1
}
trigger disable
{
accum 0 set 0
}
}
neutral_radio_closed
{
spawn
{
accum 0 set 0
}
trigger hide
{
setstate neutral_radio_closed invisible
setstate neutral_radio_closed_model invisible
}
trigger show
{
accum 0 abort_if_equal 1
setstate neutral_radio_closed default
setstate neutral_radio_closed_model default
}
trigger disable
{
accum 0 set 1
}
}
allied_radio_built
{
spawn
{
wait 50
constructible_class 2
trigger allied_radio_built setup
}
trigger setup
{
setchargetimefactor 1 soldier 1
setchargetimefactor 1 lieutenant 1
setchargetimefactor 1 medic 1
setchargetimefactor 1 engineer 1
setchargetimefactor 1 covertops 1
sethqstatus 1 0
}
buildstart final
{
trigger allied_radio_built_model trans
trigger axis_radio_destroyed hide
trigger allied_radio_destroyed hide
trigger neutral_radio_closed hide
}
built final
{
trigger allied_radio_built_model show
trigger allied_radio_destroyed enable
trigger axis_radio_destroyed disable
trigger neutral_radio_closed disable
trigger allied_radio_built_model enable_allied_features
trigger alliedcpspawns_obj on
enablespeaker allies_compost_sound
}
decayed final
{
trigger allied_radio_built_model hide
trigger allied_radio_destroyed show
trigger axis_radio_destroyed show
trigger neutral_radio_closed show
}
death
{
trigger allied_radio_built_model hide
trigger allied_radio_destroyed show
trigger allied_radio_built_model disable_allied_features
trigger alliedcpspawns_obj off
disablespeaker allies_compost_sound
}
}
axis_radio_built
{
spawn
{
wait 50
constructible_class 2
wait 150
trigger axis_radio_built setup
}
trigger setup
{
setchargetimefactor 0 soldier 1
setchargetimefactor 0 lieutenant 1
setchargetimefactor 0 medic 1
setchargetimefactor 0 engineer 1
setchargetimefactor 0 covertops 1
sethqstatus 0 0
}
buildstart final
{
trigger axis_radio_built_model trans
trigger axis_radio_destroyed hide
trigger allied_radio_destroyed hide
trigger neutral_radio_closed hide
}
built final
{
trigger axis_radio_built_model show
trigger axis_radio_destroyed enable
trigger allied_radio_destroyed enable
trigger neutral_radio_closed disable
trigger axis_radio_built_model enable_axis_features
enablespeaker axis_compost_sound
}
decayed final
{
trigger axis_radio_built_model hide
trigger axis_radio_destroyed show
trigger allied_radio_destroyed show
trigger neutral_radio_closed show
}
death
{
trigger axis_radio_built_model hide
trigger axis_radio_destroyed show
trigger axis_radio_built_model disable_axis_features
disablespeaker axis_compost_sound
}
}
axis_radio_built_model
{
spawn
{
accum 1 set 0
wait 200
setstate axis_radio_built_model invisible
}
trigger show
{
setstate axis_radio_built_model default
}
trigger hide
{
setstate axis_radio_built_model invisible
}
trigger trans
{
setstate axis_radio_built_model underconstruction
}
trigger enable_axis_features
{
// axis built it
setchargetimefactor 0 soldier 0.75
setchargetimefactor 0 lieutenant 0.75
setchargetimefactor 0 medic 0.75
setchargetimefactor 0 engineer 0.75
setchargetimefactor 0 covertops 0.75
sethqstatus 0 1
wm_objective_status 4 1 2
wm_objective_status 4 0 1
wm_objective_status 5 1 2
wm_objective_status 5 0 1
wm_announce "Axis Command Post constructed. Charge speed increased!"
// *----------------------------------- vo ------------------------------------------*
wm_teamvoiceannounce 0 "axis_hq_compost_constructed"
wm_teamvoiceannounce 1 "allies_hq_compost_constructed_axis"
wm_removeteamvoiceannounce 0 "axis_hq_compost_construct"
// *---------------------------------------------------------------------------------*
}
trigger disable_axis_features
{
// axis lost it
setchargetimefactor 0 soldier 1
setchargetimefactor 0 lieutenant 1
setchargetimefactor 0 medic 1
setchargetimefactor 0 engineer 1
setchargetimefactor 0 covertops 1
sethqstatus 0 0
wm_objective_status 4 1 0
wm_objective_status 4 0 0
wm_objective_status 5 1 0
wm_objective_status 5 0 0
wm_announce "Allied team has destroyed the Axis Command Post!"
// *----------------------------------- vo ------------------------------------------*
wm_addteamvoiceannounce 0 "axis_hq_compost_construct"
wm_addteamvoiceannounce 1 "allies_hq_compost_construct"
wm_teamvoiceannounce 0 "axis_hq_compost_damaged"
wm_teamvoiceannounce 1 "allies_hq_compost_construct"
// *---------------------------------------------------------------------------------*
}
}
allied_radio_built_model
{
spawn
{
accum 1 set 0
accum 2 set 0 // state of command post as far as the VO is concerned (0=not built, 1=built) - Wils
wait 200
setstate allied_radio_built_model invisible
}
trigger show
{
setstate allied_radio_built_model default
enablespeaker neutral_radio_sound
}
trigger hide
{
setstate allied_radio_built_model invisible
disablespeaker neutral_radio_sound
}
trigger trans
{
setstate allied_radio_built_model underconstruction
}
trigger alliedcompostvo
{
accum 2 abort_if_equal 1
wm_teamvoiceannounce 1 "allies_hq_compost_construct"
}
trigger enable_allied_features
{
// allies built it
accum 1 set 1 // Is this ever used? - Wils
accum 2 set 1 // State of com post as far as VO is concerned (1=built)
setchargetimefactor 1 soldier 0.75
setchargetimefactor 1 lieutenant 0.75
setchargetimefactor 1 medic 0.75
setchargetimefactor 1 engineer 0.75
setchargetimefactor 1 covertops 0.75
sethqstatus 0 1
wm_objective_status 4 1 1
wm_objective_status 4 0 2
wm_objective_status 5 1 1
wm_objective_status 5 0 2
wm_announce "Allied Command Post constructed. Charge speed increased!"
// *----------------------------------- vo ------------------------------------------*
wm_teamvoiceannounce 0 "axis_hq_compost_constructed_allies"
wm_teamvoiceannounce 1 "allies_hq_compost_constructed"
wm_removeteamvoiceannounce 1 "allies_hq_compost_construct"
// *---------------------------------------------------------------------------------*
}
trigger disable_allied_features
{
// allies lost it
accum 2 set 0 // state of com post as far as VO is concerned (0=destroyed)
wm_announce "Axis team has destroyed the Allied Command Post!"
setchargetimefactor 1 soldier 1
setchargetimefactor 1 lieutenant 1
setchargetimefactor 1 medic 1
setchargetimefactor 1 engineer 1
setchargetimefactor 1 covertops 1
sethqstatus 0 0
wm_objective_status 4 1 0
wm_objective_status 4 0 0
wm_objective_status 5 1 0
wm_objective_status 5 0 0
// *----------------------------------- vo ------------------------------------------*
wm_addteamvoiceannounce 0 "axis_hq_compost_construct"
wm_addteamvoiceannounce 1 "allies_hq_compost_construct"
wm_teamvoiceannounce 0 "axis_hq_compost_construct"
wm_teamvoiceannounce 1 "allies_hq_compost_damaged"
// *---------------------------------------------------------------------------------*
}
}
alliedcpspawns_obj
{
spawn
{
wait 50
setstate alliedcpspawns_obj invisible
setstate alliedcpspawns invisible
}
trigger on
{
setstate alliedcpspawns_obj default
setstate alliedcpspawns default
}
trigger off
{
setstate alliedcpspawns_obj invisible
setstate alliedcpspawns invisible
}
}
alliedcpspawns
{
spawn
{
wait 50
setstate alliedcpspawns invisible
}
}
// ================================================
// ========== CONSTRUCTIBLE STUFF =================
// ================================================
// Axis ONLY - old house on main road
mg42_clip_1
{
spawn
{
wait 50
constructible_class 2
trigger mg42_clip_1 setup
}
trigger setup
{
setstate mg42_1 invisible
setstate mg42_materials_1 default
setstate mg42_materials_clip_1 default
setstate mg42_flag_1 default
}
buildstart final
{
setstate mg42_1 underconstruction
setstate mg42_materials_1 default
setstate mg42_materials_clip_1 default
setstate mg42_flag_1 default
}
built final
{
setstate mg42_1 default
setstate mg42_materials_1 invisible
setstate mg42_materials_clip_1 invisible
setstate mg42_flag_1 invisible
wm_announce "The Axis Road MG Nest has been constructed."
}
decayed final
{
setstate mg42_1 invisible
setstate mg42_materials_1 default
setstate mg42_materials_clip_1 default
setstate mg42_flag_1 default
}
death
{
setstate mg42_1 invisible
repairmg42 mg42_1
setstate mg42_materials_1 default
setstate mg42_materials_clip_1 default
setstate mg42_flag_1 default
wm_announce "The Axis Road MG Nest has been destroyed."
}
}
// Axis ONLY
mg42_clip_2
{
spawn
{
wait 50
constructible_class 2
trigger mg42_clip_2 setup
}
trigger setup
{
setstate mg42_2 invisible
setstate mg42_materials_2 default
setstate mg42_materials_clip_2 default
setstate mg42_flag_2 default
}
buildstart final
{
setstate mg42_2 underconstruction
setstate mg42_materials_2 default
setstate mg42_materials_clip_2 default
setstate mg42_flag_2 default
}
built final
{
setstate mg42_2 default
setstate mg42_materials_2 invisible
setstate mg42_materials_clip_2 invisible
setstate mg42_flag_2 invisible
wm_announce "The Axis Watchtower MG Nest has been constructed."
}
decayed final
{
setstate mg42_2 invisible
setstate mg42_materials_2 default
setstate mg42_materials_clip_2 default
setstate mg42_flag_2 default
}
death
{
setstate mg42_2 invisible
repairmg42 mg42_2
setstate mg42_materials_2 default
setstate mg42_materials_clip_2 default
setstate mg42_flag_2 default
wm_announce "The Axis Watchtower MG Nest has been destroyed."
}
}
// Axis ONLY - in forward bunker pointing towards villa
mg42_clip_3
{
spawn
{
wait 50
constructible_class 2
trigger mg42_clip_3 setup
}
trigger setup
{
setstate mg42_3 invisible
setstate mg42_materials_3 default
setstate mg42_materials_clip_3 default
setstate mg42_flag_3 default
setstate mg42_clip_3_pillar invisible
}
buildstart final
{
setstate mg42_3 underconstruction
setstate mg42_materials_3 default
setstate mg42_materials_clip_3 default
setstate mg42_flag_3 default
setstate mg42_clip_3_pillar underconstruction
}
built final
{
setstate mg42_3 default
setstate mg42_materials_3 invisible
setstate mg42_materials_clip_3 invisible
setstate mg42_flag_3 invisible
setstate mg42_clip_3_pillar default
wm_announce "The Bunker MG Nest has been constructed."
}
decayed final
{
setstate mg42_3 invisible
setstate mg42_materials_3 default
setstate mg42_materials_clip_3 default
setstate mg42_flag_3 default
setstate mg42_clip_3_pillar invisible
}
death
{
setstate mg42_3 invisible
repairmg42 mg42_3
setstate mg42_materials_3 default
setstate mg42_materials_clip_3 default
setstate mg42_flag_3 default
setstate mg42_clip_3_pillar invisible
wm_announce "The Bunker MG Nest has been destroyed."
}
}
// Allied version - in forward bunker pointing towards villa
mg42_clip_3_allied
{
spawn
{
wait 50
constructible_class 2
trigger mg42_clip_3_allied setup
}
trigger setup
{
setstate mg42_3 invisible
setstate mg42_materials_3 default
setstate mg42_materials_clip_3 default
setstate mg42_flag_3 default
setstate mg42_clip_3_pillar invisible
}
buildstart final
{
setstate mg42_3 underconstruction
setstate mg42_materials_3 default
setstate mg42_materials_clip_3 default
setstate mg42_flag_3 default
setstate mg42_clip_3_pillar underconstruction
}
built final
{
setstate mg42_3 default
setstate mg42_materials_3 invisible
setstate mg42_materials_clip_3 invisible
setstate mg42_flag_3 invisible
setstate mg42_clip_3_pillar default
wm_announce "The Bunker MG Nest has been constructed."
}
decayed final
{
setstate mg42_3 invisible
setstate mg42_materials_3 default
setstate mg42_materials_clip_3 default
setstate mg42_flag_3 default
setstate mg42_clip_3_pillar invisible
}
death
{
setstate mg42_3 invisible
repairmg42 mg42_3
setstate mg42_materials_3 default
setstate mg42_materials_clip_3 default
setstate mg42_flag_3 default
setstate mg42_clip_3_pillar invisible
wm_announce "The Bunker MG Nest has been destroyed."
}
}
// ================================================
// ======== END CONSTRUCTIBLE STUFF ===============
// ================================================
lmscab_toi
{
spawn
{
wait 50
remove
}
}
axis_hacabinet_lms
{
spawn
{
wait 50
remove
}
}
lmshacab1
{
spawn
{
wait 50
remove
}
}
lmshacab2
{
spawn
{
wait 50
remove
}
}
truck_trig
{
spawn {
set {
// don't allow dynamite at the truck
spawnflags 139 // AXIS/ALLIED_OBJECTIVE | TANK | DISABLED
}
}
}
| 0 | 0.724729 | 1 | 0.724729 | game-dev | MEDIA | 0.940186 | game-dev | 0.881204 | 1 | 0.881204 |
NeoLoader/NeoLoader | 12,666 | crypto++/algparam.h | #ifndef CRYPTOPP_ALGPARAM_H
#define CRYPTOPP_ALGPARAM_H
#include "cryptlib.h"
#include "smartptr.h"
#include "secblock.h"
NAMESPACE_BEGIN(CryptoPP)
//! used to pass byte array input as part of a NameValuePairs object
/*! the deepCopy option is used when the NameValuePairs object can't
keep a copy of the data available */
class ConstByteArrayParameter
{
public:
ConstByteArrayParameter(const char *data = NULL, bool deepCopy = false)
{
Assign((const byte *)data, data ? strlen(data) : 0, deepCopy);
}
ConstByteArrayParameter(const byte *data, size_t size, bool deepCopy = false)
{
Assign(data, size, deepCopy);
}
template <class T> ConstByteArrayParameter(const T &string, bool deepCopy = false)
{
CRYPTOPP_COMPILE_ASSERT(sizeof(CPP_TYPENAME T::value_type) == 1);
Assign((const byte *)string.data(), string.size(), deepCopy);
}
void Assign(const byte *data, size_t size, bool deepCopy)
{
if (deepCopy)
m_block.Assign(data, size);
else
{
m_data = data;
m_size = size;
}
m_deepCopy = deepCopy;
}
const byte *begin() const {return m_deepCopy ? m_block.begin() : m_data;}
const byte *end() const {return m_deepCopy ? m_block.end() : m_data + m_size;}
size_t size() const {return m_deepCopy ? m_block.size() : m_size;}
private:
bool m_deepCopy;
const byte *m_data;
size_t m_size;
SecByteBlock m_block;
};
class ByteArrayParameter
{
public:
ByteArrayParameter(byte *data = NULL, unsigned int size = 0)
: m_data(data), m_size(size) {}
ByteArrayParameter(SecByteBlock &block)
: m_data(block.begin()), m_size(block.size()) {}
byte *begin() const {return m_data;}
byte *end() const {return m_data + m_size;}
size_t size() const {return m_size;}
private:
byte *m_data;
size_t m_size;
};
class CRYPTOPP_DLL CombinedNameValuePairs : public NameValuePairs
{
public:
CombinedNameValuePairs(const NameValuePairs &pairs1, const NameValuePairs &pairs2)
: m_pairs1(pairs1), m_pairs2(pairs2) {}
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const;
private:
const NameValuePairs &m_pairs1, &m_pairs2;
};
template <class T, class BASE>
class GetValueHelperClass
{
public:
GetValueHelperClass(const T *pObject, const char *name, const std::type_info &valueType, void *pValue, const NameValuePairs *searchFirst)
: m_pObject(pObject), m_name(name), m_valueType(&valueType), m_pValue(pValue), m_found(false), m_getValueNames(false)
{
if (strcmp(m_name, "ValueNames") == 0)
{
m_found = m_getValueNames = true;
NameValuePairs::ThrowIfTypeMismatch(m_name, typeid(std::string), *m_valueType);
if (searchFirst)
searchFirst->GetVoidValue(m_name, valueType, pValue);
if (typeid(T) != typeid(BASE))
pObject->BASE::GetVoidValue(m_name, valueType, pValue);
((*reinterpret_cast<std::string *>(m_pValue) += "ThisPointer:") += typeid(T).name()) += ';';
}
if (!m_found && strncmp(m_name, "ThisPointer:", 12) == 0 && strcmp(m_name+12, typeid(T).name()) == 0)
{
NameValuePairs::ThrowIfTypeMismatch(m_name, typeid(T *), *m_valueType);
*reinterpret_cast<const T **>(pValue) = pObject;
m_found = true;
return;
}
if (!m_found && searchFirst)
m_found = searchFirst->GetVoidValue(m_name, valueType, pValue);
if (!m_found && typeid(T) != typeid(BASE))
m_found = pObject->BASE::GetVoidValue(m_name, valueType, pValue);
}
operator bool() const {return m_found;}
template <class R>
GetValueHelperClass<T,BASE> & operator()(const char *name, const R & (T::*pm)() const)
{
if (m_getValueNames)
(*reinterpret_cast<std::string *>(m_pValue) += name) += ";";
if (!m_found && strcmp(name, m_name) == 0)
{
NameValuePairs::ThrowIfTypeMismatch(name, typeid(R), *m_valueType);
*reinterpret_cast<R *>(m_pValue) = (m_pObject->*pm)();
m_found = true;
}
return *this;
}
GetValueHelperClass<T,BASE> &Assignable()
{
#ifndef __INTEL_COMPILER // ICL 9.1 workaround: Intel compiler copies the vTable pointer for some reason
if (m_getValueNames)
((*reinterpret_cast<std::string *>(m_pValue) += "ThisObject:") += typeid(T).name()) += ';';
if (!m_found && strncmp(m_name, "ThisObject:", 11) == 0 && strcmp(m_name+11, typeid(T).name()) == 0)
{
NameValuePairs::ThrowIfTypeMismatch(m_name, typeid(T), *m_valueType);
*reinterpret_cast<T *>(m_pValue) = *m_pObject;
m_found = true;
}
#endif
return *this;
}
private:
const T *m_pObject;
const char *m_name;
const std::type_info *m_valueType;
void *m_pValue;
bool m_found, m_getValueNames;
};
template <class BASE, class T>
GetValueHelperClass<T, BASE> GetValueHelper(const T *pObject, const char *name, const std::type_info &valueType, void *pValue, const NameValuePairs *searchFirst=NULL, BASE *dummy=NULL)
{
return GetValueHelperClass<T, BASE>(pObject, name, valueType, pValue, searchFirst);
}
template <class T>
GetValueHelperClass<T, T> GetValueHelper(const T *pObject, const char *name, const std::type_info &valueType, void *pValue, const NameValuePairs *searchFirst=NULL)
{
return GetValueHelperClass<T, T>(pObject, name, valueType, pValue, searchFirst);
}
// ********************************************************
template <class R>
R Hack_DefaultValueFromConstReferenceType(const R &)
{
return R();
}
template <class R>
bool Hack_GetValueIntoConstReference(const NameValuePairs &source, const char *name, const R &value)
{
return source.GetValue(name, const_cast<R &>(value));
}
template <class T, class BASE>
class AssignFromHelperClass
{
public:
AssignFromHelperClass(T *pObject, const NameValuePairs &source)
: m_pObject(pObject), m_source(source), m_done(false)
{
if (source.GetThisObject(*pObject))
m_done = true;
else if (typeid(BASE) != typeid(T))
pObject->BASE::AssignFrom(source);
}
template <class R>
AssignFromHelperClass & operator()(const char *name, void (T::*pm)(R)) // VC60 workaround: "const R &" here causes compiler error
{
if (!m_done)
{
R value = Hack_DefaultValueFromConstReferenceType(reinterpret_cast<R>(*(int *)NULL));
if (!Hack_GetValueIntoConstReference(m_source, name, value))
throw InvalidArgument(std::string(typeid(T).name()) + ": Missing required parameter '" + name + "'");
(m_pObject->*pm)(value);
}
return *this;
}
template <class R, class S>
AssignFromHelperClass & operator()(const char *name1, const char *name2, void (T::*pm)(R, S)) // VC60 workaround: "const R &" here causes compiler error
{
if (!m_done)
{
R value1 = Hack_DefaultValueFromConstReferenceType(reinterpret_cast<R>(*(int *)NULL));
if (!Hack_GetValueIntoConstReference(m_source, name1, value1))
throw InvalidArgument(std::string(typeid(T).name()) + ": Missing required parameter '" + name1 + "'");
S value2 = Hack_DefaultValueFromConstReferenceType(reinterpret_cast<S>(*(int *)NULL));
if (!Hack_GetValueIntoConstReference(m_source, name2, value2))
throw InvalidArgument(std::string(typeid(T).name()) + ": Missing required parameter '" + name2 + "'");
(m_pObject->*pm)(value1, value2);
}
return *this;
}
private:
T *m_pObject;
const NameValuePairs &m_source;
bool m_done;
};
template <class BASE, class T>
AssignFromHelperClass<T, BASE> AssignFromHelper(T *pObject, const NameValuePairs &source, BASE *dummy=NULL)
{
return AssignFromHelperClass<T, BASE>(pObject, source);
}
template <class T>
AssignFromHelperClass<T, T> AssignFromHelper(T *pObject, const NameValuePairs &source)
{
return AssignFromHelperClass<T, T>(pObject, source);
}
// ********************************************************
// to allow the linker to discard Integer code if not needed.
typedef bool (CRYPTOPP_API * PAssignIntToInteger)(const std::type_info &valueType, void *pInteger, const void *pInt);
CRYPTOPP_DLL extern PAssignIntToInteger g_pAssignIntToInteger;
CRYPTOPP_DLL const std::type_info & CRYPTOPP_API IntegerTypeId();
class CRYPTOPP_DLL AlgorithmParametersBase
{
public:
class ParameterNotUsed : public Exception
{
public:
ParameterNotUsed(const char *name) : Exception(OTHER_ERROR, std::string("AlgorithmParametersBase: parameter \"") + name + "\" not used") {}
};
// this is actually a move, not a copy
AlgorithmParametersBase(const AlgorithmParametersBase &x)
: m_name(x.m_name), m_throwIfNotUsed(x.m_throwIfNotUsed), m_used(x.m_used)
{
m_next.reset(const_cast<AlgorithmParametersBase &>(x).m_next.release());
x.m_used = true;
}
AlgorithmParametersBase(const char *name, bool throwIfNotUsed)
: m_name(name), m_throwIfNotUsed(throwIfNotUsed), m_used(false) {}
virtual ~AlgorithmParametersBase()
{
#ifdef CRYPTOPP_UNCAUGHT_EXCEPTION_AVAILABLE
if (!std::uncaught_exception())
#else
try
#endif
{
if (m_throwIfNotUsed && !m_used)
throw ParameterNotUsed(m_name);
}
#ifndef CRYPTOPP_UNCAUGHT_EXCEPTION_AVAILABLE
catch(...)
{
}
#endif
}
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const;
protected:
friend class AlgorithmParameters;
void operator=(const AlgorithmParametersBase& rhs); // assignment not allowed, declare this for VC60
virtual void AssignValue(const char *name, const std::type_info &valueType, void *pValue) const =0;
virtual void MoveInto(void *p) const =0; // not really const
const char *m_name;
bool m_throwIfNotUsed;
mutable bool m_used;
member_ptr<AlgorithmParametersBase> m_next;
};
template <class T>
class AlgorithmParametersTemplate : public AlgorithmParametersBase
{
public:
AlgorithmParametersTemplate(const char *name, const T &value, bool throwIfNotUsed)
: AlgorithmParametersBase(name, throwIfNotUsed), m_value(value)
{
}
void AssignValue(const char *name, const std::type_info &valueType, void *pValue) const
{
// special case for retrieving an Integer parameter when an int was passed in
if (!(g_pAssignIntToInteger != NULL && typeid(T) == typeid(int) && g_pAssignIntToInteger(valueType, pValue, &m_value)))
{
NameValuePairs::ThrowIfTypeMismatch(name, typeid(T), valueType);
*reinterpret_cast<T *>(pValue) = m_value;
}
}
void MoveInto(void *buffer) const
{
AlgorithmParametersTemplate<T>* p = new(buffer) AlgorithmParametersTemplate<T>(*this);
}
protected:
T m_value;
};
CRYPTOPP_DLL_TEMPLATE_CLASS AlgorithmParametersTemplate<bool>;
CRYPTOPP_DLL_TEMPLATE_CLASS AlgorithmParametersTemplate<int>;
CRYPTOPP_DLL_TEMPLATE_CLASS AlgorithmParametersTemplate<ConstByteArrayParameter>;
class CRYPTOPP_DLL AlgorithmParameters : public NameValuePairs
{
public:
AlgorithmParameters();
#ifdef __BORLANDC__
template <class T>
AlgorithmParameters(const char *name, const T &value, bool throwIfNotUsed=true)
: m_next(new AlgorithmParametersTemplate<T>(name, value, throwIfNotUsed))
, m_defaultThrowIfNotUsed(throwIfNotUsed)
{
}
#endif
AlgorithmParameters(const AlgorithmParameters &x);
AlgorithmParameters & operator=(const AlgorithmParameters &x);
template <class T>
AlgorithmParameters & operator()(const char *name, const T &value, bool throwIfNotUsed)
{
member_ptr<AlgorithmParametersBase> p(new AlgorithmParametersTemplate<T>(name, value, throwIfNotUsed));
p->m_next.reset(m_next.release());
m_next.reset(p.release());
m_defaultThrowIfNotUsed = throwIfNotUsed;
return *this;
}
template <class T>
AlgorithmParameters & operator()(const char *name, const T &value)
{
return operator()(name, value, m_defaultThrowIfNotUsed);
}
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const;
protected:
member_ptr<AlgorithmParametersBase> m_next;
bool m_defaultThrowIfNotUsed;
};
//! Create an object that implements NameValuePairs for passing parameters
/*! \param throwIfNotUsed if true, the object will throw an exception if the value is not accessed
\note throwIfNotUsed is ignored if using a compiler that does not support std::uncaught_exception(),
such as MSVC 7.0 and earlier.
\note A NameValuePairs object containing an arbitrary number of name value pairs may be constructed by
repeatedly using operator() on the object returned by MakeParameters, for example:
AlgorithmParameters parameters = MakeParameters(name1, value1)(name2, value2)(name3, value3);
*/
#ifdef __BORLANDC__
typedef AlgorithmParameters MakeParameters;
#else
template <class T>
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed = true)
{
return AlgorithmParameters()(name, value, throwIfNotUsed);
}
#endif
#define CRYPTOPP_GET_FUNCTION_ENTRY(name) (Name::name(), &ThisClass::Get##name)
#define CRYPTOPP_SET_FUNCTION_ENTRY(name) (Name::name(), &ThisClass::Set##name)
#define CRYPTOPP_SET_FUNCTION_ENTRY2(name1, name2) (Name::name1(), Name::name2(), &ThisClass::Set##name1##And##name2)
NAMESPACE_END
#endif
| 0 | 0.984826 | 1 | 0.984826 | game-dev | MEDIA | 0.250288 | game-dev | 0.981816 | 1 | 0.981816 |
EpicSentry/P2ASW | 8,397 | src/public/sentence.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef SENTENCE_H
#define SENTENCE_H
#ifdef _WIN32
#pragma once
#endif
// X360 optimizes out the extra memory needed by the editors in these types
#ifndef _X360
#define PHONEME_EDITOR 1
#endif
#include "utlvector.h"
class CUtlBuffer;
#define CACHED_SENTENCE_VERSION 1
#define CACHED_SENTENCE_VERSION_ALIGNED 4
#define CACHED_SENTENCE_VERSION_PACKED 5
//-----------------------------------------------------------------------------
// Purpose: A sample point
//-----------------------------------------------------------------------------
// Can't do this due to backward compat issues
//#ifdef _WIN32
//#pragma pack (1)
//#endif
struct CEmphasisSample
{
float time;
float value;
void SetSelected( bool isSelected );
#if PHONEME_EDITOR
// Used by editors only
bool selected;
#endif
};
class CBasePhonemeTag
{
public:
CBasePhonemeTag();
CBasePhonemeTag( const CBasePhonemeTag& from );
CBasePhonemeTag &operator=( const CBasePhonemeTag &from ) { memcpy( this, &from, sizeof(*this) ); return *this; }
float GetStartTime() const { return m_flStartTime; }
void SetStartTime( float startTime ) { m_flStartTime = startTime; }
void AddStartTime( float startTime ) { m_flStartTime += startTime; }
float GetEndTime() const { return m_flEndTime; }
void SetEndTime( float endTime ) { m_flEndTime = endTime; }
void AddEndTime( float startTime ) { m_flEndTime += startTime; }
int GetPhonemeCode() const { return m_nPhonemeCode; }
void SetPhonemeCode( int phonemeCode ) { m_nPhonemeCode = phonemeCode; }
private:
float m_flStartTime;
float m_flEndTime;
unsigned short m_nPhonemeCode;
};
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class CPhonemeTag : public CBasePhonemeTag
{
typedef CBasePhonemeTag BaseClass;
public:
CPhonemeTag( void );
CPhonemeTag( const char *phoneme );
CPhonemeTag( const CPhonemeTag& from );
~CPhonemeTag( void );
void SetTag( const char *phoneme );
char const *GetTag() const;
unsigned int ComputeDataCheckSum();
#if PHONEME_EDITOR
bool m_bSelected;
unsigned int m_uiStartByte;
unsigned int m_uiEndByte;
#endif
void SetSelected( bool isSelected );
bool GetSelected() const;
void SetStartAndEndBytes( unsigned int start, unsigned int end );
unsigned int GetStartByte() const;
unsigned int GetEndByte() const;
private:
char *m_szPhoneme;
};
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class CWordTag
{
public:
CWordTag( void );
CWordTag( const char *word );
CWordTag( const CWordTag& from );
~CWordTag( void );
void SetWord( const char *word );
const char *GetWord() const;
int IndexOfPhoneme( CPhonemeTag *tag );
unsigned int ComputeDataCheckSum();
float m_flStartTime;
float m_flEndTime;
CUtlVector < CPhonemeTag *> m_Phonemes;
#if PHONEME_EDITOR
bool m_bSelected;
unsigned int m_uiStartByte;
unsigned int m_uiEndByte;
#endif
void SetSelected( bool isSelected );
bool GetSelected() const;
void SetStartAndEndBytes( unsigned int start, unsigned int end );
unsigned int GetStartByte() const;
unsigned int GetEndByte() const;
private:
char *m_pszWord;
};
// A sentence can be closed captioned
// The default case is the entire sentence shown at start time
//
// "<persist:2.0><clr:255,0,0,0>The <I>default<I> case"
// "<sameline>is the <U>entire<U> sentence shown at <B>start time<B>"
// Commands that aren't closed at end of phrase are automatically terminated
//
// Commands
// <linger:2.0> The line should persist for 2.0 seconds beyond m_flEndTime
// <sameline> Don't go to new line for next phrase on stack
// <clr:r,g,b,a> Push current color onto stack and start drawing with new
// color until we reach the next <clr> marker or a <clr> with no commands which
// means restore the previous color
// <U> Underline text (start/end)
// <I> Italics text (start/end)
// <B> Bold text (start/end)
// <position:where> Draw caption at special location ??? needed
// <cr> Go to new line
// Close Captioning Support
// The phonemes drive the mouth in english, but the CC text can
// be one of several languages
enum
{
CC_ENGLISH = 0,
CC_FRENCH,
CC_GERMAN,
CC_ITALIAN,
CC_KOREAN,
CC_SCHINESE, // Simplified Chinese
CC_SPANISH,
CC_TCHINESE, // Traditional Chinese
CC_JAPANESE,
CC_RUSSIAN,
CC_THAI,
CC_PORTUGUESE,
// etc etc
CC_NUM_LANGUAGES
};
//-----------------------------------------------------------------------------
// Purpose: A sentence is a box of words, and words contain phonemes
//-----------------------------------------------------------------------------
class CSentence
{
public:
static char const *NameForLanguage( int language );
static int LanguageForName( char const *name );
static void ColorForLanguage( int language, unsigned char& r, unsigned char& g, unsigned char& b );
// Construction
CSentence( void );
~CSentence( void );
// Assignment operator
CSentence& operator =(const CSentence& src );
void Append( float starttime, const CSentence& src );
void SetText( const char *text );
const char *GetText( void ) const;
void InitFromDataChunk( void *data, int size );
void InitFromBuffer( CUtlBuffer& buf );
void SaveToBuffer( CUtlBuffer& buf );
// This strips out all of the stuff used by the editor, leaving just one blank work, no sentence text, and just
// the phonemes without the phoneme text...(same as the cacherestore version below)
void MakeRuntimeOnly();
// This is a compressed save of just the data needed to drive phonemes in the engine (no word / sentence text, etc )
void CacheSaveToBuffer( CUtlBuffer& buf, int version );
void CacheRestoreFromBuffer( CUtlBuffer& buf );
// Add word/phoneme to sentence
void AddPhonemeTag( CWordTag *word, CPhonemeTag *tag );
void AddWordTag( CWordTag *tag );
void Reset( void );
void ResetToBase( void );
void MarkNewPhraseBase( void );
int GetWordBase( void );
int CountPhonemes( void );
// For legacy loading, try to find a word that contains the time
CWordTag *EstimateBestWord( float time );
CWordTag *GetWordForPhoneme( CPhonemeTag *phoneme );
void SetTextFromWords( void );
float GetIntensity( float time, float endtime );
void Resort( void );
CEmphasisSample *GetBoundedSample( int number, float endtime );
int GetNumSamples( void );
CEmphasisSample *GetSample( int index );
// Compute start and endtime based on all words
void GetEstimatedTimes( float& start, float &end );
void SetVoiceDuck( bool shouldDuck ) { m_bShouldVoiceDuck = shouldDuck; }
bool GetVoiceDuck() const { return m_bShouldVoiceDuck; }
unsigned int ComputeDataCheckSum();
void SetDataCheckSum( unsigned int chk );
unsigned int GetDataCheckSum() const;
int GetRuntimePhonemeCount() const;
const CBasePhonemeTag *GetRuntimePhoneme( int i ) const;
void ClearRuntimePhonemes();
void AddRuntimePhoneme( const CPhonemeTag *src );
void CreateEventWordDistribution( char const *pszText, float flSentenceDuration );
static int CountWords( char const *pszText );
static bool ShouldSplitWord( char in );
public:
#if PHONEME_EDITOR
char *m_szText;
CUtlVector< CWordTag * > m_Words;
#endif
CUtlVector < CBasePhonemeTag *> m_RunTimePhonemes;
#if PHONEME_EDITOR
int m_nResetWordBase;
#endif
// Phoneme emphasis data
CUtlVector< CEmphasisSample > m_EmphasisSamples;
#if PHONEME_EDITOR
unsigned int m_uCheckSum;
#endif
bool m_bIsValid : 8;
bool m_bStoreCheckSum : 8;
bool m_bShouldVoiceDuck : 8;
bool m_bIsCached : 8;
private:
void ParseDataVersionOnePointZero( CUtlBuffer& buf );
void ParsePlaintext( CUtlBuffer& buf );
void ParseWords( CUtlBuffer& buf );
void ParseEmphasis( CUtlBuffer& buf );
void ParseOptions( CUtlBuffer& buf );
void ParseCloseCaption( CUtlBuffer& buf );
void ResetCloseCaptionAll( void );
friend class PhonemeEditor;
};
//#ifdef _WIN32
//#pragma pack ()
//#endif
#endif // SENTENCE_H
| 0 | 0.871995 | 1 | 0.871995 | game-dev | MEDIA | 0.483621 | game-dev | 0.698251 | 1 | 0.698251 |
PrismRL/prism | 7,606 | engine/core/query.lua | --- @class IQueryable
--- @field query fun(self, ...:Component): Query
--- Represents a query over actors in an `ActorStorage`, filtering by required components and optionally by position.
--- Supports fluent chaining via `with()` and `at()` methods.
--- Provides `iter()`, `each()`, and `gather()` for iteration and retrieval.
--- @class Query : Object
--- @field private requiredComponents table<Component, boolean> A set of required component types.
--- @field private requiredComponentsList Component[] Ordered list of required component types.
--- @field private requiredComponentsCount integer The number of required component types.
--- @field private requiredPosition Vector2? Optional position filter.
local Query = prism.Object:extend "Query"
--- @param storage ActorStorage The storage system to query from.
--- @param ... Component A variable number of component types to require.
function Query:__new(storage, ...)
self.storage = storage
self.requiredComponents = {}
self.requiredComponentsList = {}
self.requiredComponentsCount = 0
self:with(...)
self.requiredPosition = nil
self.relationshipInfo = {}
end
--- Adds required component types to the query.
--- Can be called multiple times to accumulate components.
--- @param ... Component A variable number of component types.
--- @return Query query Returns self to allow method chaining.
function Query:with(...)
local req = { ... }
for _, component in ipairs(req) do
assert(
not self.requiredComponents[component],
"Multiple component of the same type added to query!"
)
self.requiredComponentsCount = self.requiredComponentsCount + 1
table.insert(self.requiredComponentsList, component)
self.requiredComponents[component] = true
end
return self
end
function Query:relationship(owner, relationshipType)
table.insert(self.relationshipInfo, {
owner = owner,
prototype = relationshipType
})
return self
end
--- Restricts the query to actors at a specific position.
--- @param x integer The x-coordinate.
--- @param y integer The y-coordinate.
--- @return Query query Returns self to allow method chaining.
function Query:at(x, y)
self.requiredPosition = prism.Vector2(x, y)
return self
end
--- Applies a Target filter to this query.
--- Automatically adds required components from the Target.
--- The query will only return actors that validate against this Target.
--- @param target Target
--- @param level Level
--- @param owner Actor
--- @param previousTargets any[]?
--- @return Query
function Query:target(target, level, owner, previousTargets)
-- Merge Target's required components into the query
for componentType in pairs(target.reqcomponents) do
if not self.requiredComponents[componentType] then
self:with(componentType)
end
end
-- Set the validator
self.targetValidator = function(actor)
return target:validate(level, owner, actor, previousTargets)
end
return self
end
local components = {}
-- Helper function to get components for an actor
--- @param actor Actor
--- @param requiredComponentsList Component[]
--- @return ...:Component
local function getComponents(actor, requiredComponentsList)
local n = 0
for _, component in ipairs(requiredComponentsList) do
n = n + 1
components[n] = actor:get(component)
end
return unpack(components, 1, n)
end
local function lazyIntersectSets(sets, counts, requiredComponentsList)
if #sets == 0 then
return function() return nil end
end
-- Find smallest set by counts (counts[i] corresponds to sets[i])
local smallestIndex = 1
local smallestCount = counts[1]
for i = 2, #sets do
if counts[i] < smallestCount then
smallestCount = counts[i]
smallestIndex = i
end
end
local smallestSet = sets[smallestIndex]
local otherSets = {}
for i = 1, #sets do
if i ~= smallestIndex then
table.insert(otherSets, sets[i])
end
end
local actor = nil
return function()
while true do
actor = next(smallestSet, actor)
if not actor then return nil end
local inAll = true
for _, set in ipairs(otherSets) do
if not set[actor] then
inAll = false
break
end
end
if inAll then
return actor
end
end
end
end
--- Returns an iterator function over all matching actors.
--- The iterator yields `(actor, ...components)` for each match.
--- Selection is optimized depending on number of required components and presence of position.
--- @return fun(): Actor?, ...:Component?
function Query:iter()
local storage = self.storage
local requiredComponents = self.requiredComponents
local sets = {}
local counts = {}
-- Position filter — assign count=0 to prioritize as smallest
if self.requiredPosition then
local posSet = storage:getSparseMap():get(self.requiredPosition:decompose())
if not posSet then
return function() return nil end
end
table.insert(sets, posSet)
table.insert(counts, 0)
end
-- Relationships — also count=1 to prioritize
for _, rel in ipairs(self.relationshipInfo) do
local relSet = rel.owner:getRelationships(rel.prototype)
if not relSet then
return function() return nil end
end
table.insert(sets, relSet)
table.insert(counts, 0)
end
-- Component caches — use actual counts from storage
for componentType in pairs(requiredComponents) do
local cache = storage:getComponentCache(componentType)
if not cache then
return function() return nil end
end
table.insert(sets, cache)
table.insert(counts, storage:getComponentCount(componentType))
end
-- Fallback: if no sets, include all actors
if #sets == 0 then
table.insert(sets, storage:getAllActorIDs())
table.insert(counts, #storage:getAllActors()) -- or just use length
end
local intersectionIter = lazyIntersectSets(sets, counts, self.requiredComponentsList)
return function()
while true do
local actor = intersectionIter()
if not actor then return nil end
if not self.targetValidator or self.targetValidator(actor) then
return actor, getComponents(actor, self.requiredComponentsList)
end
end
end
end
--- Gathers all matching results into a list.
--- @param results? Actor[] Optional table to insert results into.
--- @return Actor[] actors The populated list of results.
function Query:gather(results)
local results = results or {}
local iterator = self:iter()
while true do
local result = iterator()
if not result then break end
table.insert(results, result)
end
return results
end
local function eachBody(fn, ...)
local first = ...
if not first then return false end
fn(...)
return true
end
--- Applies a function to each matching actor and its components.
--- @param fn fun(actor: Actor, ...:Component) The function to apply to each result.
function Query:each(fn)
local iter = self:iter()
while eachBody(fn, iter()) do
end
end
--- Returns the first matching actor and its components.
--- @return Actor? actor The first matching actor, or nil if no actor matches.
function Query:first()
local iterator = self:iter()
local actor = iterator() -- Get the first result from the iterator
if actor then return actor end
return nil -- Return nil if no actor was found
end
return Query
| 0 | 0.900003 | 1 | 0.900003 | game-dev | MEDIA | 0.461028 | game-dev | 0.943576 | 1 | 0.943576 |
mekanism/Mekanism | 17,159 | src/main/java/mekanism/common/content/transporter/TransporterStack.java | package mekanism.common.content.transporter;
import io.netty.buffer.ByteBuf;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.longs.LongList;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.IntFunction;
import mekanism.api.SerializationConstants;
import mekanism.api.SerializerHelper;
import mekanism.api.text.EnumColor;
import mekanism.common.content.network.transmitter.LogisticalTransporterBase;
import mekanism.common.content.transporter.TransporterPathfinder.Destination;
import mekanism.common.content.transporter.TransporterPathfinder.IdlePathData;
import mekanism.common.lib.inventory.IAdvancedTransportEjector;
import mekanism.common.lib.inventory.TransitRequest;
import mekanism.common.lib.inventory.TransitRequest.TransitResponse;
import mekanism.common.util.NBTUtils;
import mekanism.common.util.WorldUtils;
import net.minecraft.core.Direction;
import net.minecraft.core.GlobalPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.util.ByIdMap;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.neoforged.neoforge.network.codec.NeoForgeStreamCodecs;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class TransporterStack {
//Make sure to call updateForPos before calling this method
public static StreamCodec<RegistryFriendlyByteBuf, TransporterStack> STREAM_CODEC = NeoForgeStreamCodecs.composite(
EnumColor.OPTIONAL_STREAM_CODEC, stack -> Optional.ofNullable(stack.color),
ByteBufCodecs.VAR_INT, stack -> stack.progress,
ByteBufCodecs.VAR_LONG, stack -> stack.originalLocation,
Path.STREAM_CODEC, TransporterStack::getPathType,
ByteBufCodecs.optional(ByteBufCodecs.VAR_LONG), stack -> stack.clientNext == Long.MAX_VALUE ? Optional.empty() : Optional.of(stack.clientNext),
ByteBufCodecs.optional(ByteBufCodecs.VAR_LONG), stack -> stack.clientPrev == Long.MAX_VALUE ? Optional.empty() : Optional.of(stack.clientPrev),
ItemStack.OPTIONAL_STREAM_CODEC, stack -> stack.itemStack,
(color, progress, originalLocation, pathType, clientNext, clientPrev, itemStack) -> {
TransporterStack stack = new TransporterStack();
stack.color = color.orElse(null);
stack.progress = progress == 0 ? 5 : progress;
stack.originalLocation = originalLocation;
stack.pathType = pathType;
stack.clientNext = clientNext.orElse(Long.MAX_VALUE);
stack.clientPrev = clientPrev.orElse(Long.MAX_VALUE);
stack.itemStack = itemStack;
return stack;
}
);
public ItemStack itemStack = ItemStack.EMPTY;
public int progress;
public EnumColor color = null;
public boolean initiatedPath = false;
public Direction idleDir = null;
//packed BlockPos-es
public long originalLocation = Long.MAX_VALUE;
public long homeLocation = Long.MAX_VALUE;
private long clientNext = Long.MAX_VALUE;
private long clientPrev = Long.MAX_VALUE;
//
@Nullable
private Path pathType;
private LongList pathToTarget = new LongArrayList();
public static TransporterStack readFromNBT(HolderLookup.Provider provider, CompoundTag nbtTags) {
TransporterStack stack = new TransporterStack();
stack.read(provider, nbtTags);
return stack;
}
public static TransporterStack readFromUpdate(HolderLookup.Provider provider, CompoundTag nbtTags) {
TransporterStack stack = new TransporterStack();
stack.readFromUpdateTag(provider, nbtTags);
return stack;
}
public void writeToUpdateTag(HolderLookup.Provider provider, LogisticalTransporterBase transporter, CompoundTag updateTag) {
if (color != null) {
NBTUtils.writeEnum(updateTag, SerializationConstants.COLOR, color);
}
updateTag.putInt(SerializationConstants.PROGRESS, progress);
updateTag.putLong(SerializationConstants.ORIGINAL_LOCATION, originalLocation);
NBTUtils.writeEnum(updateTag, SerializationConstants.PATH_TYPE, getPathType());
long next = getNext(transporter);
if (next != Long.MAX_VALUE) {
updateTag.putLong(SerializationConstants.NEXT, next);
}
long prev = getPrev(transporter);
if (prev != Long.MAX_VALUE) {
updateTag.putLong(SerializationConstants.PREVIOUS, prev);
}
if (!itemStack.isEmpty()) {
updateTag.put(SerializationConstants.ITEM, SerializerHelper.saveOversized(provider, itemStack));
}
}
public void readFromUpdateTag(HolderLookup.Provider provider, CompoundTag updateTag) {
this.color = NBTUtils.getEnum(updateTag, SerializationConstants.COLOR, EnumColor.BY_ID);
progress = updateTag.getInt(SerializationConstants.PROGRESS);
NBTUtils.setLongIfPresent(updateTag, SerializationConstants.ORIGINAL_LOCATION, coord -> originalLocation = coord);
NBTUtils.setEnumIfPresent(updateTag, SerializationConstants.PATH_TYPE, Path.BY_ID, type -> pathType = type);
//todo is backcompat needed?
clientNext = Long.MAX_VALUE;
NBTUtils.setLongIfPresent(updateTag, SerializationConstants.NEXT, coord -> clientNext = coord);
NBTUtils.setBlockPosIfPresent(updateTag, SerializationConstants.NEXT, coord -> clientNext = coord.asLong());
clientPrev = Long.MAX_VALUE;
NBTUtils.setLongIfPresent(updateTag, SerializationConstants.PREVIOUS, coord -> clientPrev = coord);
NBTUtils.setBlockPosIfPresent(updateTag, SerializationConstants.PREVIOUS, coord -> clientPrev = coord.asLong());
Tag itemTag = updateTag.get(SerializationConstants.ITEM);
if (itemTag != null) {
itemStack = SerializerHelper.parseOversized(provider, itemTag).orElse(ItemStack.EMPTY);
}
}
public void write(HolderLookup.Provider provider, CompoundTag nbtTags) {
if (color != null) {
NBTUtils.writeEnum(nbtTags, SerializationConstants.COLOR, color);
}
nbtTags.putInt(SerializationConstants.PROGRESS, progress);
nbtTags.putLong(SerializationConstants.ORIGINAL_LOCATION, originalLocation);
if (idleDir != null) {
NBTUtils.writeEnum(nbtTags, SerializationConstants.IDLE_DIR, idleDir);
}
if (homeLocation != Long.MAX_VALUE) {
nbtTags.putLong(SerializationConstants.HOME_LOCATION, homeLocation);
}
if (pathType != null) {
NBTUtils.writeEnum(nbtTags, SerializationConstants.PATH_TYPE, pathType);
}
if (!itemStack.isEmpty()) {
nbtTags.put(SerializationConstants.ITEM_OVERSIZED, SerializerHelper.saveOversized(provider, itemStack));
}
}
public void read(HolderLookup.Provider provider, CompoundTag nbtTags) {
this.color = NBTUtils.getEnum(nbtTags, SerializationConstants.COLOR, EnumColor.BY_ID);
progress = nbtTags.getInt(SerializationConstants.PROGRESS);
NBTUtils.setBlockPosIfPresent(nbtTags, SerializationConstants.ORIGINAL_LOCATION, coord -> originalLocation = coord.asLong());//TODO - 1.22 remove backcompat
NBTUtils.setLongIfPresent(nbtTags, SerializationConstants.ORIGINAL_LOCATION, coord -> originalLocation = coord);
NBTUtils.setEnumIfPresent(nbtTags, SerializationConstants.IDLE_DIR, Direction::from3DDataValue, dir -> idleDir = dir);
NBTUtils.setBlockPosIfPresent(nbtTags, SerializationConstants.HOME_LOCATION, coord -> homeLocation = coord.asLong());//TODO - 1.22 remove backcompat
NBTUtils.setLongIfPresent(nbtTags, SerializationConstants.HOME_LOCATION, coord -> homeLocation = coord);
NBTUtils.setEnumIfPresent(nbtTags, SerializationConstants.PATH_TYPE, Path.BY_ID, type -> pathType = type);
Tag oversizedTag = nbtTags.get(SerializationConstants.ITEM_OVERSIZED);
if (oversizedTag != null) {
itemStack = SerializerHelper.parseOversized(provider, oversizedTag).orElse(ItemStack.EMPTY);
} else if (nbtTags.contains(SerializationConstants.ITEM, Tag.TAG_COMPOUND)) {//TODO - 1.22: Remove this legacy way of loading data
itemStack = ItemStack.parseOptional(provider, nbtTags.getCompound(SerializationConstants.ITEM));
} else {//TODO - 1.22: Remove this legacy way of loading data
itemStack = ItemStack.parseOptional(provider, nbtTags);
}
}
private void setPath(Level world, @NotNull LongList path, @NotNull Path type, boolean updateFlowing) {
//Make sure old path isn't null
if (updateFlowing && (pathType == null || pathType.hasTarget())) {
//Only update the actual flowing stacks if we want to modify more than our current stack
TransporterManager.remove(world, this);
}
pathToTarget = path;
pathType = type;
if (updateFlowing && pathType.hasTarget()) {
//Only update the actual flowing stacks if we want to modify more than our current stack
TransporterManager.add(world, this);
}
}
public boolean hasPath() {
return pathToTarget.size() >= 2;
}
public LongList getPath() {
return pathToTarget;
}
public Path getPathType() {
return pathType == null ? Path.NONE : pathType;
}
public TransitResponse recalculatePath(TransitRequest request, LogisticalTransporterBase transporter, int min) {
return recalculatePath(request, transporter, min, true);
}
public final TransitResponse recalculatePath(TransitRequest request, BlockEntity ignored, LogisticalTransporterBase transporter, int min, boolean updateFlowing) {
return recalculatePath(request, transporter, min, updateFlowing);
}
public TransitResponse recalculatePath(TransitRequest request, LogisticalTransporterBase transporter, int min, boolean updateFlowing) {
return recalculatePath(request, transporter, min, updateFlowing, Collections.emptyMap());
}
public TransitResponse recalculatePath(TransitRequest request, LogisticalTransporterBase transporter, int min,
Map<GlobalPos, Set<TransporterStack>> additionalFlowingStacks) {
return recalculatePath(request, transporter, min, false, additionalFlowingStacks);
}
private TransitResponse recalculatePath(TransitRequest request, LogisticalTransporterBase transporter, int min, boolean updateFlowing,
Map<GlobalPos, Set<TransporterStack>> additionalFlowingStacks) {
Destination newPath = TransporterPathfinder.getNewBasePath(transporter, this, request, min, additionalFlowingStacks);
if (newPath == null) {
return request.getEmptyResponse();
}
idleDir = null;
setPath(transporter.getLevel(), newPath.getPath(), Path.DEST, updateFlowing);
initiatedPath = true;
return newPath.getResponse();
}
public <BE extends BlockEntity & IAdvancedTransportEjector> TransitResponse recalculateRRPath(TransitRequest request, BE outputter, LogisticalTransporterBase transporter, int min) {
return recalculateRRPath(request, outputter, transporter, min, true);
}
public <BE extends BlockEntity & IAdvancedTransportEjector> TransitResponse recalculateRRPath(TransitRequest request, BE outputter, LogisticalTransporterBase transporter, int min, boolean updateFlowing) {
Destination newPath = TransporterPathfinder.getNewRRPath(transporter, this, request, outputter, min);
if (newPath == null) {
return request.getEmptyResponse();
}
idleDir = null;
setPath(transporter.getLevel(), newPath.getPath(), Path.DEST, updateFlowing);
initiatedPath = true;
return newPath.getResponse();
}
public boolean calculateIdle(LogisticalTransporterBase transporter) {
IdlePathData newPath = TransporterPathfinder.getIdlePath(transporter, this);
if (newPath == null) {
return false;
}
if (newPath.type().isHome()) {
idleDir = null;
}
setPath(transporter.getLevel(), newPath.path(), newPath.type(), true);
originalLocation = transporter.getWorldPositionLong();
initiatedPath = true;
return true;
}
public boolean isFinal(LogisticalTransporterBase transporter) {
return transporter.getWorldPositionLong() == pathToTarget.get(getPathType().hasTarget() ? 1 : 0);
}
//TODO - 1.20.5: Re-evaluate this method
public TransporterStack updateForPos(long pos) {
clientNext = getNext(pos);
clientPrev = getPrev(pos);
return this;
}
public long getNext(LogisticalTransporterBase transporter) {
return transporter.isRemote() ? clientNext : getNext(transporter.getWorldPositionLong());
}
private long getNext(long pos) {
int index = pathToTarget.indexOf(pos) - 1;
if (index < 0) {
return Long.MAX_VALUE;
}
return pathToTarget.getLong(index);
}
public long getPrev(LogisticalTransporterBase transporter) {
return transporter.isRemote() ? clientPrev : getPrev(transporter.getBlockPos().asLong());
}
private long getPrev(long pos) {
int index = pathToTarget.indexOf(pos) + 1;
if (index < pathToTarget.size()) {
return pathToTarget.getLong(index);
}
return originalLocation;
}
public Direction getSide(LogisticalTransporterBase transporter) {
Direction side = null;
if (progress < 50) {
long prev = getPrev(transporter);
if (prev != Long.MAX_VALUE) {
side = WorldUtils.sideDifference(transporter.getBlockPos().asLong(), prev);
}
} else {
long next = getNext(transporter);
if (next != Long.MAX_VALUE) {
side = WorldUtils.sideDifference(next, transporter.getBlockPos().asLong());
}
}
//sideDifference can return null
//TODO: Look into implications further about what side should be returned.
// This is mainly to stop a crash I randomly encountered but was unable to reproduce.
// (I believe the difference returns null when it is the "same" transporter somehow or something)
return side == null ? Direction.DOWN : side;
}
public Direction getSide(long pos, long target) {
Direction side = null;
if (target != Long.MAX_VALUE) {
side = WorldUtils.sideDifference(target, pos);
}
//TODO: See getSide(Transporter) for why we null check and then return down
return side == null ? Direction.DOWN : side;
}
@Contract("null, _, _ -> false")
public boolean canInsertToTransporter(@Nullable LogisticalTransporterBase transmitter, Direction from, @Nullable LogisticalTransporterBase transporterFrom) {
return transmitter != null && canInsertToTransporterNN(transmitter, from, transporterFrom);
}
public boolean canInsertToTransporterNN(@NotNull LogisticalTransporterBase transporter, Direction from, @Nullable BlockEntity tileFrom) {
//If the color is valid, make sure that the connection is valid
EnumColor color = transporter.getColor();
return (color == null || color == this.color) && transporter.canConnectMutual(from.getOpposite(), tileFrom);
}
public boolean canInsertToTransporterNN(@NotNull LogisticalTransporterBase transporter, Direction from, @Nullable LogisticalTransporterBase transporterFrom) {
//If the color is valid, make sure that the connection is valid
EnumColor color = transporter.getColor();
return (color == null || color == this.color) && transporter.canConnectMutual(from.getOpposite(), transporterFrom);
}
public long getDest() {
return pathToTarget.getFirst();
}
@Nullable
public Direction getSideOfDest() {
if (hasPath()) {
long lastTransporter = pathToTarget.getLong(1);
return WorldUtils.sideDifference(lastTransporter, getDest());
}
return null;
}
public enum Path {
DEST,
HOME,
NONE;
public static final IntFunction<Path> BY_ID = ByIdMap.continuous(Path::ordinal, values(), ByIdMap.OutOfBoundsStrategy.WRAP);
public static final StreamCodec<ByteBuf, Path> STREAM_CODEC = ByteBufCodecs.idMapper(BY_ID, Path::ordinal);
public boolean hasTarget() {
return this != NONE;
}
public boolean noTarget() {
return this == NONE;
}
public boolean isHome() {
return this == HOME;
}
}
} | 0 | 0.939088 | 1 | 0.939088 | game-dev | MEDIA | 0.904498 | game-dev | 0.909333 | 1 | 0.909333 |
AnthonyTornetta/Cosmos | 3,565 | cosmos_client/src/ui/hud/error.rs | use bevy::prelude::*;
use cosmos_core::{ecs::NeedsDespawned, state::GameState};
use crate::ui::font::DefaultFont;
#[derive(Event, Debug)]
pub struct ShowInfoPopup {
pub text: String,
pub popup_type: PopupType,
}
#[derive(Debug, Clone, Copy)]
pub enum PopupType {
Success,
Error,
}
impl ShowInfoPopup {
pub fn success(message: impl Into<String>) -> Self {
Self {
text: message.into(),
popup_type: PopupType::Success,
}
}
pub fn error(message: impl Into<String>) -> Self {
Self {
text: message.into(),
popup_type: PopupType::Error,
}
}
}
#[derive(Component, Debug)]
struct PopupsList;
#[derive(Component, Debug)]
struct Popup(f32);
fn init_error_list(mut commands: Commands) {
commands.spawn((
Name::new("Popup List"),
PopupsList,
Node {
top: Val::Px(50.0),
right: Val::Px(0.0),
position_type: PositionType::Absolute,
flex_direction: FlexDirection::Column,
..Default::default()
},
));
}
const WIDTH: f32 = 500.0;
fn show_error(
font: Res<DefaultFont>,
q_errors: Query<Entity, With<PopupsList>>,
mut commands: Commands,
mut evr_error: EventReader<ShowInfoPopup>,
) {
for ev in evr_error.read() {
let Ok(ent) = q_errors.single() else {
return;
};
info!("{ev:?}");
commands.entity(ent).with_children(|p| {
p.spawn((
Popup(0.0),
Node {
width: Val::Px(WIDTH),
height: Val::Px(150.0),
margin: UiRect::all(Val::Px(30.0)),
..Default::default()
},
BackgroundColor(
match ev.popup_type {
PopupType::Error => Srgba {
red: 1.0,
green: 0.3,
blue: 0.3,
alpha: 0.7,
},
PopupType::Success => Srgba {
red: 0.3,
green: 1.0,
blue: 1.0,
alpha: 0.7,
},
}
.into(),
),
))
.with_children(|p| {
p.spawn((
Node {
margin: UiRect::all(Val::Px(30.0)),
..Default::default()
},
Text::new(ev.text.clone()),
TextFont {
font: font.get(),
font_size: 24.0,
..Default::default()
},
));
});
});
}
}
const POPUP_ALIVE_SECS: f32 = 8.0;
fn tick_error(mut commands: Commands, mut q_error: Query<(Entity, &mut Node, &mut Popup)>, time: Res<Time>) {
for (entity, mut node, mut err) in q_error.iter_mut() {
err.0 += time.delta_secs();
let left = (err.0 - POPUP_ALIVE_SECS).max(0.0).powf(4.0);
node.left = Val::Px(left);
if left > 2.0 * WIDTH {
commands.entity(entity).insert(NeedsDespawned);
}
}
}
pub(super) fn register(app: &mut App) {
app.add_event::<ShowInfoPopup>()
.add_systems(Update, (show_error, tick_error).chain())
.add_systems(OnEnter(GameState::Playing), init_error_list);
}
| 0 | 0.907833 | 1 | 0.907833 | game-dev | MEDIA | 0.489727 | game-dev,desktop-app | 0.983964 | 1 | 0.983964 |
tebe6502/Mad-Pascal | 2,110 | samples/c4plus/siege/inc/init.inc | //-----------------------------------------------------------------------------
procedure initPlayfield;
begin
//restore 7 custom char
Poke(CHARSET + $2B3, 16); Poke(CHARSET + $2B7, 1);
BACKGROUND := BACKGROUND_COLOUR; BOREDER := BOREDER_COLOUR;
FillChar(pointer(SCREEN_ADDR), 24 * 40, EMPTY);
FillChar(pointer(ATTRIBUTE_ADDR), 24 * 40, PLAYFIELD_COLOUR);
for t0b := 39 downto 0 do begin
Poke(SCREEN_ADDR + t0b, WALL);
Poke((SCREEN_ADDR + 24 * 40) + t0b, WALL);
Poke(ATTRIBUTE_ADDR + t0b, WALL_COLOUR);
Poke((ATTRIBUTE_ADDR + 24 * 40) + t0b, WALL_COLOUR);
end;
for t0b := 24 downto 1 do begin
DPoke((SCREEN_ADDR - 1) + mul40[t0b], WALL * 256 + WALL);
DPoke((ATTRIBUTE_ADDR - 1) + mul40[t0b], WALL_COLOUR * 256 + WALL_COLOUR);
end;
end;
//-----------------------------------------------------------------------------
procedure initPlayers;
begin
alive := $ff;
player1.isAlive := false; player2.isAlive := false;
player3.isAlive := false; player4.isAlive := false;
end;
//-----------------------------------------------------------------------------
procedure initScore;
begin
player1.score := ZERO; player2.score := ZERO;
player3.score := ZERO; player4.score := ZERO;
end;
//-----------------------------------------------------------------------------
procedure initArena;
begin
initPlayfield; initPlayers;
case level of
1 : setLevel01; // easy
2 : setLevel02; // easy
3 : setLevel03; // easy
4 : setLevel04; // moderate
5 : setLevel05; // moderate
6 : setLevel06; // hard
7 : setLevel07; // very hard
8 : setLevel08; // very hard
end;
animateObstacles; showScore;
end;
//-----------------------------------------------------------------------------
procedure initFonts;
begin
Move(pointer($d000), pointer(CHARSET), $400);
Move(fonts, pointer(CHARSET + (8 * $50)), SizeOf(fonts));
// set bit 2
RAMROMSEL := RAMROMSEL and %11111011;
// 12 = $3000 / $400 on 2-7 bits
CHBAS := (CHBAS and %11) or 12 shl 2;
end;
//-----------------------------------------------------------------------------
| 0 | 0.651563 | 1 | 0.651563 | game-dev | MEDIA | 0.945391 | game-dev | 0.762047 | 1 | 0.762047 |
magefree/mage | 2,742 | Mage.Sets/src/mage/cards/n/NoosegrafMob.java |
package mage.cards.n;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.EntersBattlefieldAbility;
import mage.abilities.common.SpellCastAllTriggeredAbility;
import mage.abilities.effects.Effect;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.effects.common.counter.AddCountersSourceEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.SubType;
import mage.counters.CounterType;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.game.permanent.token.ZombieToken;
import mage.players.Player;
import java.util.UUID;
/**
*
* @author fireshoes
*/
public final class NoosegrafMob extends CardImpl {
public NoosegrafMob(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{4}{B}{B}");
this.subtype.add(SubType.ZOMBIE);
this.power = new MageInt(0);
this.toughness = new MageInt(0);
// Noosegraf Mob enters the battlefield with five +1/+1 counters on it.
this.addAbility(new EntersBattlefieldAbility(new AddCountersSourceEffect(CounterType.P1P1.createInstance(5)), "with five +1/+1 counters on it"));
// Whenever a player casts a spell, remove a +1/+1 counter from Noosegraf Mob. If you do, create a 2/2 black Zombie creature token.
this.addAbility(new SpellCastAllTriggeredAbility(new NoosegrafMobEffect(), false));
}
private NoosegrafMob(final NoosegrafMob card) {
super(card);
}
@Override
public NoosegrafMob copy() {
return new NoosegrafMob(this);
}
}
class NoosegrafMobEffect extends OneShotEffect {
NoosegrafMobEffect() {
super(Outcome.Benefit);
staticText = "remove a +1/+1 counter from {this}. If you do, create a 2/2 black Zombie creature token";
}
private NoosegrafMobEffect(final NoosegrafMobEffect effect) {
super(effect);
}
@Override
public NoosegrafMobEffect copy() {
return new NoosegrafMobEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Permanent permanent = game.getPermanent(source.getSourceId());
Player controller = game.getPlayer(source.getControllerId());
if (controller != null && permanent != null && permanent.getCounters(game).getCount(CounterType.P1P1) > 0) {
permanent.removeCounters(CounterType.P1P1.createInstance(), source, game);
Effect effect = new CreateTokenEffect(new ZombieToken());
return effect.apply(game, source);
}
return false;
}
}
| 0 | 0.969214 | 1 | 0.969214 | game-dev | MEDIA | 0.948568 | game-dev | 0.995075 | 1 | 0.995075 |
MovingBlocks/Terasology | 1,486 | engine/src/main/java/org/terasology/engine/logic/behavior/core/LeafNode.java | // Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.logic.behavior.core;
import org.terasology.nui.properties.PropertyProvider;
/**
* Node without children.
*/
public abstract class LeafNode implements BehaviorNode {
@Override
public PropertyProvider getProperties() {
return null;
}
@Override
public <T> T visit(T item, Visitor<T> visitor) {
return visitor.visit(item, this);
}
@Override
public void insertChild(int index, BehaviorNode child) {
throw new IllegalArgumentException("Leaf nodes does not accept children");
}
@Override
public void replaceChild(int index, BehaviorNode child) {
throw new IllegalArgumentException("Leaf nodes does not accept children");
}
@Override
public BehaviorNode removeChild(int index) {
throw new IllegalArgumentException("Leaf nodes does not accept children");
}
@Override
public BehaviorNode getChild(int index) {
throw new IllegalArgumentException("Leaf nodes does not accept children");
}
@Override
public int getChildrenCount() {
return 0;
}
@Override
public int getMaxChildren() {
return 0;
}
@Override
public void construct(Actor actor) {
}
@Override
public BehaviorState execute(Actor actor) {
return null;
}
@Override
public void destruct(Actor actor) {
}
}
| 0 | 0.647013 | 1 | 0.647013 | game-dev | MEDIA | 0.764715 | game-dev | 0.817202 | 1 | 0.817202 |
LiteLDev/LeviLamina | 2,245 | src-server/mc/world/containers/managers/controllers/SmithingTableContainerManagerController.h | #pragma once
#include "mc/_HeaderOutputPredefine.h"
// auto generated inclusion list
#include "mc/world/containers/SlotData.h"
#include "mc/world/containers/managers/controllers/ContainerManagerController.h"
#include "mc/world/containers/managers/controllers/ItemResultPreview.h"
// auto generated forward declare list
// clang-format off
class ItemInstance;
class ItemStackBase;
class SmithingTableContainerManagerModel;
struct AutoPlaceItem;
struct AutoPlaceResult;
struct CreateContainerItemScope;
struct ItemTransferAmount;
// clang-format on
class SmithingTableContainerManagerController : public ::ContainerManagerController {
public:
// member variables
// NOLINTBEGIN
::ll::TypedStorage<8, 16, ::std::weak_ptr<::SmithingTableContainerManagerModel>>
mSmithingTableContainerManagerModel;
::ll::TypedStorage<8, 40, ::SlotData const> mCreatedItemOutputSlot;
::ll::TypedStorage<8, 136, ::ItemResultPreview> mResultPreview;
// NOLINTEND
public:
// virtual functions
// NOLINTBEGIN
// vIndex: 0
virtual ~SmithingTableContainerManagerController() /*override*/ = default;
// vIndex: 27
virtual bool isOutputSlot(::std::string const&) const /*override*/;
// vIndex: 8
virtual ::ItemStackBase const& getTakeableItemStackBase(::SlotData const&) const /*override*/;
// vIndex: 9
virtual void handleTakeAmount(::SlotData const&, int, ::SlotData const&) /*override*/;
// vIndex: 10
virtual void handleTakeAll(::SlotData const&, ::SlotData const&) /*override*/;
// vIndex: 12
virtual void handleTakeHalf(::SlotData const&, ::SlotData const&) /*override*/;
// vIndex: 15
virtual int handleAutoPlace(
::SlotData const&,
int,
::std::vector<::AutoPlaceItem> const&,
::std::vector<::AutoPlaceResult>&
) /*override*/;
// vIndex: 32
virtual void _onItemAcquired(::ItemInstance const&, ::SlotData const&) /*override*/;
// vIndex: 29
virtual ::CreateContainerItemScope
_makeCreateItemScope(::SlotData const&, ::ItemTransferAmount const&) /*override*/;
// NOLINTEND
public:
// virtual function thunks
// NOLINTBEGIN
// NOLINTEND
};
| 0 | 0.937785 | 1 | 0.937785 | game-dev | MEDIA | 0.532014 | game-dev,graphics-rendering | 0.6255 | 1 | 0.6255 |
TheIndra55/fivem-burglary | 7,063 | burglary/client.lua | onMission = false
blips = {}
peds = {}
pickups = {}
lastDoor = 1
currentVan = nil
shouldDraw = false
inMissionVehicle = false
missionVehicles = {
`boxville`,
`boxville2`,
`boxville3`,
`boxville4`
}
-- slower thread in idle state
CreateThread(function()
while true do
Wait(2000)
local player = PlayerPedId()
if IsPedInAnyVehicle(player) then
local vehicle = GetVehiclePedIsIn(player)
inMissionVehicle = IsMissionVehicle(GetEntityModel(vehicle))
end
end
end)
CreateThread(function()
if not HasStreamedTextureDictLoaded('timerbars') then
RequestStreamedTextureDict('timerbars')
while not HasStreamedTextureDictLoaded('timerbars') do
Wait(0)
end
end
-- load ipls
RequestIpl("hei_hw1_blimp_interior_v_studio_lo_milo_")
RequestIpl("hei_hw1_blimp_interior_v_apart_midspaz_milo_")
while true do
Wait(0)
-- if pressed E in a vehicle and not onMission
if inMissionVehicle and not onMission and IsControlJustPressed(0, 51) then
local veh = GetVehiclePedIsIn(PlayerPedId(), false)
if IsMissionVehicle(GetEntityModel(veh)) then
local time = TimeToSeconds(GetClockTime())
-- check time
if time >= 0 and time <= TimeToSeconds(5, 30, 0) then
onMission = true
-- spawn blips
for _,door in pairs(doors) do
local blip = AddBlipForCoord(door.coords.x, door.coords.y, door.coords.z)
SetBlipSprite(blip, 40)
SetBlipColour(blip, 1)
SetBlipAsShortRange(blip, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("House")
EndTextCommandSetBlipName(blip)
table.insert(blips, blip)
end
currentVan = VehToNet(veh)
SetEntityAsMissionEntity(veh, false, false)
ShowMPMessage("Burglary", "Find a ~r~house ~s~to rob.", 3500)
else
DisplayHelpText("Burglary missions can only be started from 0:00 - 5:30 AM.")
end
end
end
end
end)
CreateThread(function()
while true do
Wait(0)
if onMission then
-- maths to calculate time until daylight
local hours, minutes, seconds = GetClockTime()
local left = TimeToSeconds(5, 30, 0) - TimeToSeconds(hours, minutes, seconds)
local time = SecondsToTime(left)
-- draw info
DrawTimerBar("ITEMS", #stolenItems, 2)
DrawTimerBar("DAYLIGHT", AddLeadingZero(time.hours) .. ":" .. AddLeadingZero(time.minutes), 1)
end
end
end)
CreateThread(function()
while true do
Wait(0)
if onMission then
local coords = GetEntityCoords(PlayerPedId())
for k,door in pairs(doors) do
-- draw marker
if Vdist(coords, door.coords.x, door.coords.y, door.coords.z) < 100 then
DrawMarker(0, door.coords.x, door.coords.y, door.coords.z + 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 204, 255, 0, 50, true, true, 2, nil, nil, false)
end
-- can enter
if Vdist(coords, door.coords.x, door.coords.y, door.coords.z) < 2 then
DisplayHelpText("Press ~INPUT_CONTEXT~ to enter this house.")
if IsControlJustPressed(0, 51) then
local house = houses[door.house]
SetEntityCoords(PlayerPedId(), house.coords.x, house.coords.y, house.coords.z)
SetEntityHeading(PlayerPedId(), house.coords.heading)
lastDoor = k
shouldDraw = true
SpawnResidents(door.house)
SpawnPickups(door.house, k)
ShowSubtitle("You are in the house now, be careful to not make too much noise. (Maybe try sneaking?)")
end
end
end
end
if shouldDraw then
local coords = GetEntityCoords(PlayerPedId())
-- check inside
for _,house in pairs(houses) do
if IsEntityInArea(PlayerPedId(), house.area[1], house.area[2], 0, 0, 0) then
if onMission then
DrawNoiseBar(GetPlayerCurrentStealthNoise(PlayerId()), 3)
end
-- draw exit doors in houses (even if not in mission)
DrawMarker(0, house.door, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 204, 255, 0, 50, true, true, 2, nil, nil, false)
if Vdist(coords, house.door) < 1 then
local door = doors[lastDoor]
SetEntityCoords(PlayerPedId(), door.coords.x, door.coords.y, door.coords.z)
RemoveResidents()
RemovePickups()
shouldDraw = false
-- play holding anim if holding something after teleported outside
if isHolding then
TaskPlayAnim(PlayerPedId(), "anim@heists@box_carry@", "walk", 1.0, 1.0, -1, 1 | 16 | 32, 0.0, 0, 0, 0)
end
end
end
end
end
end
end)
function SpawnPickups(house, door)
for k,pickup in pairs(houses[house].pickups) do
if not IsAlreadyStolen(door, k) then
-- spawn prop
RequestModel(pickup.model)
while not HasModelLoaded(pickup.model) do
Wait(0)
end
local prop = CreateObject(GetHashKey(pickup.model), pickup.coord, false, false, false)
SetEntityHeading(prop, pickup.rotation)
-- create blip
local blip = AddBlipForCoord(pickup.coord)
SetBlipColour(blip, 2)
SetBlipScale(blip, 0.7)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString(pickup.model)
EndTextCommandSetBlipName(blip)
table.insert(pickups, {
blip = blip,
prop = prop,
item = { house = house, id = k, door = door }
})
end
end
end
function RemovePickups()
for k,pickup in pairs(pickups) do
RemoveBlip(pickup.blip)
SetObjectAsNoLongerNeeded(pickup.prop)
DeleteObject(pickup.prop)
end
pickups = {}
end
function SpawnResidents(house)
for _,resident in pairs(residents) do
if resident.house == house then
RequestModel(resident.model)
while not HasModelLoaded(resident.model) do
Wait(0)
end
local ped = CreatePed(4, resident.model, resident.coord, resident.rotation, false, false)
table.insert(peds, ped)
-- animation
RequestAnimDict(resident.animation.dict)
while not HasAnimDictLoaded(resident.animation.dict) do
Wait(0)
end
if resident.aggressive then
GiveWeaponToPed(ped, `WEAPON_PISTOL`, 255, true, false)
end
TaskPlayAnimAdvanced(ped, resident.animation.dict, resident.animation.anim, resident.coord, 0.0, 0.0, resident.rotation, 8.0, 1.0, -1, 1, 1.0, true, true)
SetFacialIdleAnimOverride(ped, "mood_sleeping_1", 0)
SetPedHearingRange(ped, 3.0)
SetPedSeeingRange(ped, 0.0)
SetPedAlertness(ped, 0)
end
end
end
function RemoveResidents()
for k,ped in pairs(peds) do
SetPedAsNoLongerNeeded(ped)
DeletePed(ped)
end
peds = {}
end
function IsAlreadyStolen(door, id)
for _,v in pairs(stolenItems) do
if v.door == door and v.id == id then
return true
end
end
return false
end
function GetCurrentHouse()
for index,house in pairs(houses) do
if IsEntityInArea(PlayerPedId(), house.area[1], house.area[2], 0, 0, 0) then
return true, index
end
end
return false, index
end
function RemoveBlips()
for _,blip in pairs(blips) do
RemoveBlip(blip)
end
blips = {}
end
function IsMissionVehicle(model)
for _,v in pairs(missionVehicles) do
if model == v then
return true
end
end
return false
end
| 0 | 0.968612 | 1 | 0.968612 | game-dev | MEDIA | 0.943127 | game-dev | 0.970433 | 1 | 0.970433 |
Hiro420/CockPY | 6,522 | server_data/lua/scene/3/scene3_group133106253.lua | -- Trigger变量
local defs = {
point_sum = 11,
route_2 = 310600097,
gadget_seelie = 253002
}
-- DEFS_MISCS
defs.final_point = defs.point_sum - 1
-- DEFS_MISCS
--================================================================
--
-- 配置
--
--================================================================
-- 怪物
monsters = {
}
-- NPC
npcs = {
}
-- 装置
gadgets = {
{ config_id = 253001, gadget_id = 70710006, pos = { x = -178.3, y = 158.0, z = 937.7 }, rot = { x = 0.0, y = 38.8, z = 0.0 }, level = 32 },
{ config_id = 253002, gadget_id = 70710010, pos = { x = -168.1, y = 168.1, z = 892.0 }, rot = { x = 0.0, y = 0.0, z = 0.0 }, level = 32, route_id = 310600098 },
{ config_id = 253003, gadget_id = 70710007, pos = { x = -178.0, y = 158.7, z = 936.1 }, rot = { x = 0.0, y = 166.5, z = 0.0 }, level = 32 },
{ config_id = 253004, gadget_id = 70211111, pos = { x = -181.9, y = 158.2, z = 935.3 }, rot = { x = 0.0, y = 0.0, z = 0.0 }, level = 32, drop_tag = "解谜中级璃月", showcutscene = true, isOneoff = true, persistent = true }
}
-- 区域
regions = {
{ config_id = 253007, shape = RegionShape.SPHERE, radius = 3, pos = { x = -167.7, y = 166.6, z = 891.8 } }
}
-- 触发器
triggers = {
{ name = "PLATFORM_REACH_POINT_253005", event = EventType.EVENT_PLATFORM_REACH_POINT, source = "", condition = "condition_EVENT_PLATFORM_REACH_POINT_253005", action = "action_EVENT_PLATFORM_REACH_POINT_253005", trigger_count = 0 },
{ name = "AVATAR_NEAR_PLATFORM_253006", event = EventType.EVENT_AVATAR_NEAR_PLATFORM, source = "", condition = "condition_EVENT_AVATAR_NEAR_PLATFORM_253006", action = "action_EVENT_AVATAR_NEAR_PLATFORM_253006", trigger_count = 0 },
{ name = "ENTER_REGION_253007", event = EventType.EVENT_ENTER_REGION, source = "", condition = "condition_EVENT_ENTER_REGION_253007", action = "action_EVENT_ENTER_REGION_253007", trigger_count = 0 },
{ name = "GADGET_STATE_CHANGE_253008", event = EventType.EVENT_GADGET_STATE_CHANGE, source = "", condition = "condition_EVENT_GADGET_STATE_CHANGE_253008", action = "action_EVENT_GADGET_STATE_CHANGE_253008" },
{ name = "GADGET_CREATE_253009", event = EventType.EVENT_GADGET_CREATE, source = "", condition = "condition_EVENT_GADGET_CREATE_253009", action = "action_EVENT_GADGET_CREATE_253009", trigger_count = 0 }
}
-- 变量
variables = {
}
--================================================================
--
-- 初始化配置
--
--================================================================
-- 初始化时创建
init_config = {
suite = 1,
end_suite = 2,
rand_suite = false
}
--================================================================
--
-- 小组配置
--
--================================================================
suites = {
{
-- suite_id = 1,
-- description = suite_1,
monsters = { },
gadgets = { 253001, 253002, 253003 },
regions = { 253007 },
triggers = { "PLATFORM_REACH_POINT_253005", "AVATAR_NEAR_PLATFORM_253006", "ENTER_REGION_253007", "GADGET_STATE_CHANGE_253008" },
rand_weight = 100
},
{
-- suite_id = 2,
-- description = suite_2,
monsters = { },
gadgets = { 253001 },
regions = { },
triggers = { "GADGET_CREATE_253009" },
rand_weight = 100
}
}
--================================================================
--
-- 触发器
--
--================================================================
-- 触发条件
function condition_EVENT_PLATFORM_REACH_POINT_253005(context, evt)
if defs.gadget_seelie ~= evt.param1 then
return false
end
if defs.route_2 ~= evt.param2 then
return false
end
if defs.final_point ~= evt.param3 then
return false
end
return true
end
-- 触发操作
function action_EVENT_PLATFORM_REACH_POINT_253005(context, evt)
-- 将configid为 253001 的物件更改为状态 GadgetState.GearStart
if 0 ~= ScriptLib.SetGadgetStateByConfigId(context, 253001, GadgetState.GearStart) then
return -1
end
-- 停止移动平台
if 0 ~= ScriptLib.StopPlatform(context, 253002) then
return -1
end
-- 永久关闭CongfigId的Gadget,需要和Groups的RefreshWithBlock标签搭配
if 0 ~= ScriptLib.KillEntityByConfigId(context, { config_id = 253002 }) then
return -1
end
-- 运营数据埋点,匹配LD定义的规则使用
if 0 ~= ScriptLib.MarkPlayerAction(context, 2005, 3, 1) then
return -1
end
return 0
end
-- 触发条件
function condition_EVENT_AVATAR_NEAR_PLATFORM_253006(context, evt)
if defs.gadget_seelie ~= evt.param1 then
return false
end
if defs.route_2 ~= evt.param2 then
return false
end
if defs.final_point == evt.param3 then
return false
end
return true
end
-- 触发操作
function action_EVENT_AVATAR_NEAR_PLATFORM_253006(context, evt)
if 0 ~= ScriptLib.StartPlatform(context, 253002) then
return -1
end
-- 运营数据埋点,匹配LD定义的规则使用
if 0 ~= evt.param3 then
ScriptLib.MarkPlayerAction(context, 2005, 2, evt.param3 + 1)
end
return 0
end
-- 触发条件
function condition_EVENT_ENTER_REGION_253007(context, evt)
if evt.param1 ~= 253007 then return false end
-- 判断角色数量不少于1
if ScriptLib.GetRegionEntityCount(context, { region_eid = evt.source_eid, entity_type = EntityType.AVATAR }) < 1 then
return false
end
return true
end
-- 触发操作
function action_EVENT_ENTER_REGION_253007(context, evt)
-- 设置移动平台路径
if 0 ~= ScriptLib.SetPlatformRouteId(context, 253002, 310600097) then
return -1
end
-- 永久关闭CongfigId的Gadget,需要和Groups的RefreshWithBlock标签搭配
if 0 ~= ScriptLib.KillEntityByConfigId(context, { config_id = 253003 }) then
return -1
end
-- 运营数据埋点,匹配LD定义的规则使用
if 0 ~= ScriptLib.MarkPlayerAction(context, 2005, 1, 1) then
return -1
end
return 0
end
-- 触发条件
function condition_EVENT_GADGET_STATE_CHANGE_253008(context, evt)
if 253001 ~= evt.param2 or GadgetState.GearAction1 ~= evt.param1 then
return false
end
return true
end
-- 触发操作
function action_EVENT_GADGET_STATE_CHANGE_253008(context, evt)
-- group调整group进度,只对非randSuite有效
if 0 ~= ScriptLib.GoToGroupSuite(context, 133106253, 2) then
return -1
end
-- 针对当前group内变量名为 "count" 的变量,进行修改,变化值为 1
if 0 ~= ScriptLib.ChangeGroupVariableValueByGroup(context, "count", 1, 133106246) then
return -1
end
return 0
end
-- 触发条件
function condition_EVENT_GADGET_CREATE_253009(context, evt)
if 253001 ~= evt.param1 or GadgetState.Default ~= ScriptLib.GetGadgetStateByConfigId(context, 0, evt.param1) then
return false
end
return true
end
-- 触发操作
function action_EVENT_GADGET_CREATE_253009(context, evt)
-- 将configid为 253001 的物件更改为状态 GadgetState.GearAction1
if 0 ~= ScriptLib.SetGadgetStateByConfigId(context, 253001, GadgetState.GearAction1) then
return -1
end
return 0
end
| 0 | 0.934926 | 1 | 0.934926 | game-dev | MEDIA | 0.98123 | game-dev | 0.932613 | 1 | 0.932613 |
setuppf/GameBookServer | 1,006 | 12_02_move/src/apps/game/teleport_object.h | #pragma once
#include "libserver/component.h"
#include "libserver/system.h"
// ת
// 1,תҪȴĿͼ
// 2,תҪȴݴʵͼͬ
enum class TeleportFlagType
{
None = 0,
Waiting = 1,
Completed = 2,
};
template<typename T>
struct TeleportFlag
{
public:
friend class TeleportObject;
TeleportFlagType Flag;
void SetValue(T value)
{
this->Value = value;
this->Flag = TeleportFlagType::Completed;
}
T GetValue()
{
return this->Value;
}
bool IsCompleted()
{
return this->Flag == TeleportFlagType::Completed;
}
private:
T Value;
};
class TeleportObject :public Component<TeleportObject>, public IAwakeFromPoolSystem<int, uint64>
{
public:
void Awake(int worldId, uint64 playerSn) override;
void BackToPool() override;
TeleportFlag<uint64> FlagWorld;
TeleportFlag<bool> FlagPlayerSync;
int GetTargetWorldId() const;
uint64 GetPlayerSN() const;
private:
int _targetWorldId{ 0 };
uint64 _playerSn{ 0 };
};
| 0 | 0.780807 | 1 | 0.780807 | game-dev | MEDIA | 0.850451 | game-dev | 0.855568 | 1 | 0.855568 |
fnmwolf/Anaconda | 1,711 | Chowdren/base/include/Box2D/Dynamics/Controllers/b2ConstantForceController.cpp | /*
* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "b2ConstantForceController.h"
b2ConstantForceController::b2ConstantForceController(const b2ConstantForceControllerDef* def) : b2Controller(def)
{
type = e_constantForceController;
F = def->F;
}
void b2ConstantForceController::Step(const b2TimeStep& step)
{
B2_NOT_USED(step);
for(b2ControllerEdge *i=m_bodyList;i;i=i->nextBody){
b2Body* body = i->body;
if(body->IsSleeping())
continue;
body->ApplyForce(F,body->GetWorldCenter());
}
}
void b2ConstantForceController::Destroy(b2BlockAllocator* allocator)
{
allocator->Free(this, sizeof(b2ConstantForceController));
}
b2ConstantForceController* b2ConstantForceControllerDef::Create(b2BlockAllocator* allocator)
{
void* mem = allocator->Allocate(sizeof(b2ConstantForceController));
return new (mem) b2ConstantForceController(this);
} | 0 | 0.624901 | 1 | 0.624901 | game-dev | MEDIA | 0.831681 | game-dev | 0.602242 | 1 | 0.602242 |
MemoriesOfTime/Nukkit-MOT | 5,620 | src/main/java/cn/nukkit/OfflinePlayer.java | package cn.nukkit;
import cn.nukkit.metadata.MetadataValue;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.plugin.Plugin;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
/**
* Describes an offline player
*
* @author MagicDroidX(code) @ Nukkit Project
* @author 粉鞋大妈(javadoc) @ Nukkit Project
* @see cn.nukkit.Player
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public class OfflinePlayer implements IPlayer {
private final Server server;
private final CompoundTag namedTag;
/**
* Initializes the object {@code OfflinePlayer}.
*
* @param server 这个玩家所在服务器的{@code Server}对象。<br>
* The server this player is in, as a {@code Server} object.
* @param uuid 这个玩家的UUID。<br>
* UUID of this player.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public OfflinePlayer(Server server, UUID uuid) {
this(server, uuid, null);
}
public OfflinePlayer(Server server, String name) {
this(server, null, name);
}
public OfflinePlayer(Server server, UUID uuid, String name) {
this.server = server;
CompoundTag nbt;
if (server.savePlayerDataByUuid) {
if (uuid != null) {
nbt = this.server.getOfflinePlayerData(uuid, false);
} else if (name != null) {
nbt = this.server.getOfflinePlayerData(name, false);
} else {
throw new IllegalArgumentException("Name and UUID cannot both be null");
}
} else { // When not using UUIDs check for the data saved by name first
if (name != null) {
nbt = this.server.getOfflinePlayerData(name, false);
} else if (uuid != null) {
nbt = this.server.getOfflinePlayerData(uuid, false);
} else {
throw new IllegalArgumentException("Name and UUID cannot both be null");
}
}
if (nbt == null) {
nbt = new CompoundTag();
}
this.namedTag = nbt;
if (uuid != null) {
this.namedTag.putLong("UUIDMost", uuid.getMostSignificantBits());
this.namedTag.putLong("UUIDLeast", uuid.getLeastSignificantBits());
} else {
this.namedTag.putString("NameTag", name);
}
}
@Override
public boolean isOnline() {
return this.getPlayer() != null;
}
@Override
public String getName() {
if (namedTag != null && namedTag.contains("NameTag")) {
return namedTag.getString("NameTag");
}
return null;
}
@Override
public UUID getUniqueId() {
if (namedTag != null) {
long least = namedTag.getLong("UUIDLeast");
long most = namedTag.getLong("UUIDMost");
if (least != 0 && most != 0) {
return new UUID(most, least);
}
}
return null;
}
@Override
public Server getServer() {
return server;
}
@Override
public boolean isOp() {
return this.server.isOp(this.getName().toLowerCase(Locale.ROOT));
}
@Override
public void setOp(boolean value) {
if (this.getName() == null) {
Server.getInstance().getLogger().warning("Tried to OP invalid OfflinePlayer");
return;
}
if (value == this.isOp()) {
return;
}
if (value) {
this.server.addOp(this.getName().toLowerCase(Locale.ROOT));
} else {
this.server.removeOp(this.getName().toLowerCase(Locale.ROOT));
}
}
@Override
public boolean isBanned() {
return this.server.getNameBans().isBanned(this.getName());
}
@Override
public void setBanned(boolean value) {
if (value) {
this.server.getNameBans().addBan(this.getName(), null, null, null);
} else {
this.server.getNameBans().remove(this.getName());
}
}
@Override
public boolean isWhitelisted() {
return this.server.isWhitelisted(this.getName().toLowerCase(Locale.ROOT));
}
@Override
public void setWhitelisted(boolean value) {
if (value) {
this.server.addWhitelist(this.getName().toLowerCase(Locale.ROOT));
} else {
this.server.removeWhitelist(this.getName().toLowerCase(Locale.ROOT));
}
}
@Override
public Player getPlayer() {
return this.server.getPlayerExact(this.getName());
}
@Override
public Long getFirstPlayed() {
return this.namedTag != null ? this.namedTag.getLong("firstPlayed") : null;
}
@Override
public Long getLastPlayed() {
return this.namedTag != null ? this.namedTag.getLong("lastPlayed") : null;
}
@Override
public boolean hasPlayedBefore() {
return this.namedTag != null;
}
@Override
public void setMetadata(String metadataKey, MetadataValue newMetadataValue) {
this.server.getPlayerMetadata().setMetadata(this, metadataKey, newMetadataValue);
}
@Override
public List<MetadataValue> getMetadata(String metadataKey) {
return this.server.getPlayerMetadata().getMetadata(this, metadataKey);
}
@Override
public boolean hasMetadata(String metadataKey) {
return this.server.getPlayerMetadata().hasMetadata(this, metadataKey);
}
@Override
public void removeMetadata(String metadataKey, Plugin owningPlugin) {
this.server.getPlayerMetadata().removeMetadata(this, metadataKey, owningPlugin);
}
}
| 0 | 0.907529 | 1 | 0.907529 | game-dev | MEDIA | 0.493296 | game-dev | 0.905897 | 1 | 0.905897 |
basho/riak-dotnet-client | 1,732 | src/RiakClient/Commands/TS/TimeseriesCommandBuilder{TBuilder,TCommand,TOptions}.cs | namespace RiakClient.Commands.TS
{
using System;
/// <summary>
/// Base class for all Riak command builders.
/// </summary>
/// <typeparam name="TBuilder">The type of the builder. Allows chaining.</typeparam>
/// <typeparam name="TCommand">The type of the command.</typeparam>
/// <typeparam name="TOptions">The type of the options for this command.</typeparam>
public abstract class TimeseriesCommandBuilder<TBuilder, TCommand, TOptions>
: CommandBuilder<TBuilder, TCommand, TOptions>
where TBuilder : TimeseriesCommandBuilder<TBuilder, TCommand, TOptions>
where TOptions : TimeseriesCommandOptions
{
protected string table;
public TimeseriesCommandBuilder()
{
}
public TimeseriesCommandBuilder(TimeseriesCommandBuilder<TBuilder, TCommand, TOptions> source)
{
this.table = source.table;
this.timeout = source.timeout;
}
public override TCommand Build()
{
Options = BuildOptions();
PopulateOptions(Options);
return (TCommand)Activator.CreateInstance(typeof(TCommand), Options);
}
public TBuilder WithTable(string table)
{
if (string.IsNullOrWhiteSpace(table))
{
throw new ArgumentNullException("table", "table may not be null, empty or whitespace");
}
this.table = table;
return (TBuilder)this;
}
protected override TOptions BuildOptions()
{
return (TOptions)Activator.CreateInstance(typeof(TOptions), table);
}
protected abstract void PopulateOptions(TOptions options);
}
}
| 0 | 0.911866 | 1 | 0.911866 | game-dev | MEDIA | 0.768298 | game-dev | 0.925298 | 1 | 0.925298 |
pure-data/pure-data | 5,725 | doc/2.control.examples/16.more.arrays.pd | #N canvas 158 37 1074 752 12;
#X text 105 13 MORE ON ARRAYS;
#X obj 522 231 tgl 19 0 empty empty empty 17 7 0 10 #dfdfdf #000000 #000000 0 1;
#X msg 522 258 \; array98 vis \$1;
#X msg 548 683 \; array98 style \$1;
#X floatatom 529 460 4 1 10 0 - - - 0;
#X floatatom 741 512 5 0 0 0 - - - 0;
#X msg 741 538 \; array98 color \$1;
#X msg 741 482 9, f 2;
#X msg 770 482 900;
#X text 36 138 set array values from index 0;
#X text 309 129 sets two values from index 3, f 17;
#X text 30 39 Arrays have methods to set their values explicitly. Below you can set their "bounds" rectangles \, rename them (but if you have two with the same name this won't necessarily do what you want) and add markings. To set values by message \, send a list whose first element gives the index to start at. Indices count up from zero., f 66;
#X msg 28 166 \; array98 0 -1 1 -1 1 -1 1 -1;
#X text 786 512 set color;
#X floatatom 548 653 5 0 0 0 - - - 0;
#X msg 302 166 \; array97 3 -0.5 0.5;
#X msg 27 234 \; array97 rename george;
#X msg 231 234 \; george rename array97;
#X msg 28 307 \; array97 bounds 0 2 10 -2;
#X msg 29 416 \; array97 xticks 0 1 1;
#X msg 222 415 \; array97 yticks 0 0.1 5;
#X msg 304 515 \; array97 ylabel -0.1 -1 0 1;
#X msg 523 325 \; array97 vis \$1;
#N canvas 162 212 568 393 locality 0;
#N canvas 0 22 450 278 (subpatch) 0;
#X array \$0-array 10 float 3;
#A 0 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5;
#A color 0;
#A width 2;
#X coords 0 1 10 -1 200 140 1;
#X restore 68 112 graph;
#X obj 401 170 send \$0-array;
#X obj 319 105 bng 19 250 50 0 empty empty empty 17 7 0 10 #dfdfdf #000000 #000000;
#X msg 401 140 const 0.5;
#X msg 319 202 \; \$1-array const -0.5;
#X obj 319 154 float \$0;
#X text 38 292 You can use "\$0" in an array name wherever you want as above. If you need to send a message to the array \, use the [send] object or load the "\$0" in a [float] object and pass it to a message used as a send. This is because "\$0" doesn't get expanded in messages., f 69;
#X text 31 18 '\$0' - the patch ID number used to force locality in Pd - is widely used in send/receive names as well as array names. This is especially useful in abstractions so each copy has local names instead of global., f 70;
#X text 342 105 <-- click;
#X connect 2 0 5 0;
#X connect 3 0 1 0;
#X connect 5 0 4 0;
#X restore 254 692 pd locality;
#X msg 723 639 0;
#X msg 713 602 1;
#X text 746 596 allow editing with mouse, f 13;
#X text 752 632 prevent mouse interaction, f 14;
#X msg 713 669 \; array97 edit \$1 \; array98 edit \$1;
#X text 25 573 You can also change the x and y range and size in the "properties" dialog. Note that information about size and ranges is saved \, but ticks and labels are lost between Pd sessions. The contents of the array may be saved as part of the patch or discarded. This is set in the 'properties" dialog as well., f 62;
#X text 27 212 renaming an array;
#X text 26 285 setting the bounds rectangle;
#X text 103 476 adding labels: give a y value and a bunch of x values or vice versa, f 37;
#X text 25 363 adding x and y labels: give a point to put a tick \, the interval between ticks \, and the number of ticks overall per large tick;
#X obj 523 299 tgl 19 0 empty empty empty 17 7 0 10 #dfdfdf #000000 #000000 0 1;
#X obj 548 587 vradio 19 1 0 3 empty empty empty 0 -10 0 12 #dfdfdf #000000 #000000 0;
#X text 572 587 Point (0);
#X text 572 606 Polygon (1);
#X text 572 626 Bezier (2);
#X text 542 557 set display style:;
#X obj 694 206 cnv 19 298 148 empty empty empty 20 12 0 12 #e0e0e0 #404040 0;
#N canvas 0 50 450 250 (subpatch) 0;
#X array array97 5 float 9;
#A 0 0.486666 0.126666 0.566675 -0.5 0.5;
#A color 0;
#A width 1;
#X array array98 7 float 9;
#A 0 -1 1 -1 1 -1 1 -1;
#A color 900;
#A width 1;
#X coords 0 1 7 -1 300 150 1 0 0;
#X restore 693 205 graph;
#X text 507 130 For last \, there are methods to change the visual appearance of arrays (and you can use a canvas [cnv] to set background color as in this example):, f 67;
#X msg 683 482 444;
#X msg 255 305 \; array97 bounds 0 1 7 -1;
#X msg 715 482 0, f 2;
#X text 562 461 line width;
#X msg 418 683 \; array97 style \$1;
#X msg 529 491 \; array97 width \$1 \; array98 width \$1;
#X text 102 679 open subpatch for local array names -->, f 21;
#X text 507 22 You can put more than one array in a single "graph" (which is Pd's name for the bounding rectangle \, and is a synonym for "canvas".) In this case you need to click on an exact point of one of the arrays to drag and change values. Note that arrays' sizes need not match the bounds of the containing graph. But if you have only one array in a graph and resize it \, the graph is automatically reset to match its bounds., f 67;
#X msg 20 515 \; array97 xlabel -1.075 0 1 2 3 4 5 6 7;
#X obj 672 378 tgl 19 0 empty empty empty 17 7 0 10 #dfdfdf #000000 #000000 0 1;
#X obj 830 378 tgl 19 0 empty empty empty 17 7 0 10 #dfdfdf #000000 #000000 0 1;
#X msg 672 405 \; array98 visname \$1;
#X msg 830 404 \; array97 visname \$1;
#X text 510 198 show/hide arrays:;
#X text 568 395 show/hide array names:, f 12;
#X obj 904 639 tgl 19 0 empty empty empty 0 -10 0 12 #dfdfdf #000000 #000000 0 1;
#X msg 904 669 \; array98 keep \$1;
#X text 906 591 Change "save contents" flag, f 14;
#X text 885 476 Colors are set in the same way as other data structures. The first digit is Red \, the second is Green and the third is Blue., f 22;
#X connect 1 0 2 0;
#X connect 4 0 48 0;
#X connect 5 0 6 0;
#X connect 7 0 5 0;
#X connect 8 0 5 0;
#X connect 14 0 3 0;
#X connect 14 0 47 0;
#X connect 24 0 28 0;
#X connect 25 0 28 0;
#X connect 34 0 22 0;
#X connect 35 0 14 0;
#X connect 43 0 5 0;
#X connect 45 0 5 0;
#X connect 52 0 54 0;
#X connect 53 0 55 0;
#X connect 58 0 59 0;
| 0 | 0.613188 | 1 | 0.613188 | game-dev | MEDIA | 0.353937 | game-dev | 0.711092 | 1 | 0.711092 |
ServUO/ServUO | 9,041 | Scripts/Services/Expansions/High Seas/Items/Fish/Bait.cs | using System;
using Server;
using Server.Targeting;
using Server.Prompts;
namespace Server.Items
{
public class Bait : Item
{
public static readonly bool UsePrompt = true;
private Type m_BaitType;
private object m_Label;
private int m_UsesRemaining;
private int m_Index;
private bool m_Enhanced;
[CommandProperty(AccessLevel.GameMaster)]
public Type BaitType { get { return m_BaitType; } }
[CommandProperty(AccessLevel.GameMaster)]
public int UsesRemaining { get { return m_UsesRemaining; } set { m_UsesRemaining = value; InvalidateProperties(); } }
[CommandProperty(AccessLevel.GameMaster)]
public int Index
{
get { return m_Index; }
set
{
m_Index = value;
if (value < 0)
m_Index = 0;
if (value >= FishInfo.FishInfos.Count)
m_Index = FishInfo.FishInfos.Count - 1;
m_BaitType = FishInfo.GetTypeFromIndex(m_Index);
Hue = FishInfo.GetFishHue(m_Index);
m_Label = FishInfo.GetFishLabel(m_Index);
InvalidateProperties();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public bool Enhanced { get { return m_Enhanced; } set { m_Enhanced = value; InvalidateProperties(); } }
[Constructable]
public Bait(int index) : base(2454)
{
Index = index;
m_UsesRemaining = 1;
}
[Constructable]
public Bait() : base(2454)
{
m_UsesRemaining = 1;
}
public override void OnDoubleClick(Mobile from)
{
if (IsChildOf(from.Backpack))
{
if (UsePrompt && m_UsesRemaining > 1)
{
from.SendMessage("How much bait would you like to use?");
from.Prompt = new InternalPrompt(this);
}
else
{
from.Target = new InternalTarget(this, 1);
from.SendMessage("Target the fishing pole or lobster trap that you would like to apply the bait to.");
}
}
}
public void TryBeginTarget(Mobile from, int amount)
{
if (amount < 0) amount = 1;
if (amount > m_UsesRemaining) amount = m_UsesRemaining;
from.Target = new InternalTarget(this, amount);
from.SendMessage("Target the fishing pole or lobster trap that you would like to apply the bait to.");
}
public override void AddNameProperty(ObjectPropertyList list)
{
object label = FishInfo.GetFishLabel(m_Index);
if (m_Enhanced)
{
//~1_token~ ~2_token~ bait
if (label is int)
list.Add(1116464, "#{0}\t#{1}", 1116470, (int)label);
else if (label is string)
list.Add(1116464, "#{0}\t{1}", 1116470, (string)label);
}
else if (label is int)
list.Add(1116465, String.Format("#{0}", (int)label)); //~1_token~ bait
else if (label is string)
list.Add(1116465, (string)label);
}
public override void GetProperties(ObjectPropertyList list)
{
base.GetProperties(list);
list.Add(1116466, m_UsesRemaining.ToString()); //amount: ~1_val~
}
private class InternalPrompt : Prompt
{
private Bait m_Bait;
public InternalPrompt(Bait bait)
{
m_Bait = bait;
}
public override void OnResponse(Mobile from, string text)
{
int amount = Utility.ToInt32( text );
m_Bait.TryBeginTarget(from, amount);
}
public override void OnCancel(Mobile from)
{
from.SendMessage("Not applying bait...");
}
}
private class InternalTarget : Target
{
private Bait m_Bait;
private int m_Amount;
public InternalTarget(Bait bait, int amount)
: base(0, false, TargetFlags.None)
{
m_Bait = bait;
m_Amount = amount;
}
protected override void OnTarget(Mobile from, object targeted)
{
if (targeted == m_Bait)
return;
if (targeted is FishingPole)
{
if (!m_Bait.IsFishBait())
{
from.SendMessage("Think again before applying lobster or crab bait to a fishing pole!");
return;
}
FishingPole pole = (FishingPole)targeted;
bool hasBait = pole.BaitType != null;
if (hasBait && pole.BaitType != m_Bait.BaitType)
from.SendMessage("You swap out the old bait for new.");
if (pole.BaitType == m_Bait.BaitType)
pole.BaitUses += m_Amount;
else
{
pole.BaitType = m_Bait.BaitType;
pole.BaitUses += m_Amount;
}
if (m_Bait.Enhanced)
pole.EnhancedBait = true;
from.SendLocalizedMessage(1149759); //You bait the hook.
m_Bait.UsesRemaining -= m_Amount;
}
else if (targeted is LobsterTrap)
{
if (m_Bait.IsFishBait())
{
from.SendMessage("Think again before applying fish bait to a lobster trap!");
return;
}
LobsterTrap trap = (LobsterTrap)targeted;
bool hasBait = trap.BaitType != null;
trap.BaitType = m_Bait.BaitType;
//trap.Hue = m_Bait.Hue;
if (hasBait && trap.BaitType != m_Bait.BaitType)
from.SendMessage("You swap out the old bait for new.");
if (trap.BaitType == m_Bait.BaitType)
trap.BaitUses += m_Amount;
else
{
trap.BaitType = m_Bait.BaitType;
trap.BaitUses += m_Amount;
}
if (m_Bait.Enhanced)
trap.EnhancedBait = true;
from.SendLocalizedMessage(1149760); //You bait the trap.
m_Bait.UsesRemaining -= m_Amount;
}
else if (targeted is Bait && ((Bait)targeted).IsChildOf(from.Backpack) && ((Bait)targeted).BaitType == m_Bait.BaitType)
{
Bait bait = (Bait)targeted;
bait.UsesRemaining += m_Amount;
m_Bait.UsesRemaining -= m_Amount;
if (m_Bait.UsesRemaining <= 0)
{
m_Bait.Delete();
from.SendLocalizedMessage(1116469); //You combine these baits into one cup and destroy the other cup.
}
else
from.SendMessage("You combine these baits into one cup.");
return;
}
if (m_Bait.UsesRemaining <= 0)
{
m_Bait.Delete();
from.SendLocalizedMessage(1116467); //Your bait is used up so you destroy the container.
}
}
}
public bool IsFishBait()
{
if (m_BaitType == null)
Index = Utility.RandomMinMax(0, 34);
return !m_BaitType.IsSubclassOf(typeof(BaseCrabAndLobster));
}
public Bait(Serial serial) : base(serial) { }
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
writer.Write(m_UsesRemaining);
writer.Write(m_Index);
writer.Write(m_Enhanced);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
m_UsesRemaining = reader.ReadInt();
m_Index = reader.ReadInt();
m_Enhanced = reader.ReadBool();
if (m_Index < 0)
m_Index = 0;
if (m_Index >= FishInfo.FishInfos.Count)
m_Index = FishInfo.FishInfos.Count - 1;
m_BaitType = FishInfo.FishInfos[m_Index].Type;
//Hue = FishInfo.FishInfos[m_Index].Hue;
m_Label = FishInfo.GetFishLabel(m_Index);
}
}
} | 0 | 0.761576 | 1 | 0.761576 | game-dev | MEDIA | 0.770286 | game-dev | 0.880936 | 1 | 0.880936 |
sigeer/RuaMS | 3,601 | src/Application.Resources/scripts/quest/20313.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Author: ThreeStep
NPC Name: Irena (1101005)
Description: Wind Archer 3rd job advancement
Quest: Shinsoo's Teardrop
*/
/*
Author: Magical-H
Description: 骑士团转职通用脚本
*/
var job = {
1 : "DAWNWARRIOR", // 魂骑士
2 : "BLAZEWIZARD", // 炎术士
3 : "WINDARCHER", // 风灵使者
4 : "NIGHTWALKER", // 夜行者
5 : "THUNDERBREAKER" // 奇袭者
};
var medalid = 1142066; //定义初级勋章,根据转职次数自动发放对应的勋章
var completeQuestID = 29906; //定义初级勋章任务,根据转职次数自动完成对应的勋章任务
var jobId = null;
var jobLevel = null;
var QuestID = null;
var chrLevel = {
1 : 10,
2 : 30,
3 : 70,
4 : 120
}; //定义角色等级限制
var status = -1;
function start(mode, type, selection) {
if(QuestID == null) {
QuestID = qm.getQuest();
jobId = String(QuestID).slice(-1); //通过任务ID获取职业ID
jobLevel = String(QuestID).substring(2, 3); //通过任务ID获取几转
chrLevel = chrLevel[jobLevel]; //通过转职次数绑定等级限制
job = Job[job[jobId] + jobLevel]; //获取转职职业类
medalid += (jobLevel - 1); //绑定对应的转职勋章
completeQuestID += (jobLevel - 1); //绑定完成对应给予转职勋章的任务
}
if (mode == -1) {
qm.dispose();
} else {
if (status == 1 && mode == 0) {
qm.sendNext("我猜你还没准备好.");
qm.dispose();
return;
}
if (mode == 1) {
status++;
} else {
status--;
}
if (status == 0) {
qm.sendNext("你所带回来的宝石是神兽的眼泪,它拥有非常强大的力量。如果被黑磨法师给得手了,那我们全部都可能要倒大楣了...\r\n");
} else if (status == 1) {
qm.sendYesNo("女皇为了报答你的努力,将任命你为皇家骑士团的#b高级骑士 - " + job.getName() + "#k,你准备好了嘛?");
} else if (status == 2) {
nPSP = (qm.getPlayer().getLevel() - chrLevel) * 3;
if (qm.getPlayer().getRemainingSp() > nPSP) {
qm.sendNext("请检查你的技能点数是否已经加完。");
} else {
if (!qm.canHold(medalid)) {
qm.sendOk(`女皇将赋予你#b#v${medalid}##t${medalid}##k,你必须将#b装备栏#k#r空出1个格子#k才可以接受。\r\n\r\n如果你已拥有该勋章,请你将其丢弃。`);
} else {
qm.getPlayer().changeJob(job); //更改职业
qm.completeQuest();
qm.gainItem(medalid, 1); //原始流程是女皇任务给的勋章,需要配合WZ给任务29908加入自动完成任务代码,比较麻烦,在这里给了。
qm.completeQuest(completeQuestID); //直接完成女皇的任务,这样女皇头顶不会一直顶着书本。
qm.sendNext(`从这一刻起,女皇任命你为高级骑士。请继续努力,成为一名享受更艰难的冒险过程的#b高级骑士#k吧!\r\n获得女皇赋予的勋章:\r\n#b#v${medalid}##t${medalid}##k`);
}
}
} else if (status == 3) {
qm.dispose();
}
}
} | 0 | 0.740222 | 1 | 0.740222 | game-dev | MEDIA | 0.855608 | game-dev | 0.739628 | 1 | 0.739628 |
RobertSkalko/Age-of-Exile | 3,917 | src/main/java/com/robertx22/age_of_exile/database/data/stats/datapacks/stats/CoreStat.java | package com.robertx22.age_of_exile.database.data.stats.datapacks.stats;
import com.robertx22.age_of_exile.capability.entity.EntityData;
import com.robertx22.age_of_exile.database.OptScaleExactStat;
import com.robertx22.age_of_exile.database.data.stats.StatScaling;
import com.robertx22.age_of_exile.database.data.stats.datapacks.base.BaseDatapackStat;
import com.robertx22.age_of_exile.database.data.stats.datapacks.base.CoreStatData;
import com.robertx22.age_of_exile.database.data.stats.name_regex.StatNameRegex;
import com.robertx22.age_of_exile.database.data.stats.types.core_stats.base.ICoreStat;
import com.robertx22.age_of_exile.saveclasses.ExactStatData;
import com.robertx22.age_of_exile.saveclasses.gearitem.gear_bases.TooltipInfo;
import com.robertx22.age_of_exile.saveclasses.unit.InCalcStatData;
import com.robertx22.age_of_exile.saveclasses.unit.StatData;
import com.robertx22.age_of_exile.uncommon.wrappers.SText;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class CoreStat extends BaseDatapackStat implements ICoreStat {
public static String SER_ID = "core_stat";
public CoreStatData data = new CoreStatData();
transient String locname;
public CoreStat(String id, String locname, CoreStatData data) {
super(SER_ID);
this.id = id;
this.data = data;
this.is_perc = true;
this.min = 0;
this.group = StatGroup.CORE;
this.scaling = StatScaling.NORMAL;
this.is_long = false;
this.locname = locname;
}
@Override
public final String locDescForLangFile() {
// because i tend to change things and then the damn tooltip becomes outdated.
String str = "Determines your total: ";
for (OptScaleExactStat x : this.statsThatBenefit()) {
str += x.getStat()
.translate() + ", ";
}
str = str.substring(0, str.length() - 2);
return str;
}
public float getValue(StatData data) {
return data.getValue();
}
public List<ITextComponent> getCoreStatTooltip(EntityData unitdata, StatData data) {
TooltipInfo info = new TooltipInfo(unitdata, null);
int val = (int) getValue(data);
List<ITextComponent> list = new ArrayList<>();
list.add(
new StringTextComponent("For each point: ").withStyle(TextFormatting.GREEN));
getMods(1).forEach(x -> list.addAll(x.GetTooltipString(info)));
list.add(new SText(""));
list.add(
new StringTextComponent("Total: ").withStyle(TextFormatting.GREEN));
getMods(val).forEach(x -> list.addAll(x.GetTooltipString(info)));
return list;
}
public List<ExactStatData> getMods(int amount) {
return data.stats.stream()
.map(x -> {
ExactStatData exact = ExactStatData.of(amount * x.v1, x.getStat()
.getStat(), x.getStat()
.getModType(), 1);
return exact;
})
.collect(Collectors.toList());
}
@Override
public final List<OptScaleExactStat> statsThatBenefit() {
return data.stats.stream()
.map(e -> e.getStat())
.collect(Collectors.toList());
}
@Override
public void addToOtherStats(EntityData unitdata, InCalcStatData data) {
for (ExactStatData x : getMods((int) data.getValue())) {
x.applyStats(unitdata);
}
}
@Override
public StatNameRegex getStatNameRegex() {
return StatNameRegex.BASIC;
}
@Override
public boolean IsPercent() {
return false;
}
@Override
public String locNameForLangFile() {
return locname;
}
} | 0 | 0.728586 | 1 | 0.728586 | game-dev | MEDIA | 0.636411 | game-dev | 0.768781 | 1 | 0.768781 |
CharsetMC/Charset | 4,164 | src/main/java/pl/asie/charset/lib/capability/CapabilityCache.java | /*
* Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020 Adrian Siekierka
*
* This file is part of Charset.
*
* Charset is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Charset is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Charset. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.asie.charset.lib.capability;
import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import pl.asie.charset.api.lib.IBlockCapabilityProvider;
import pl.asie.charset.api.lib.ICacheable;
import java.util.List;
public class CapabilityCache extends TileCache {
public static class Single<T> extends CapabilityCache {
private final Capability<T> capability;
private final EnumFacing facing;
private ICacheable object;
public Single(World world, BlockPos pos, boolean blocks, boolean tiles, boolean entities, Capability<T> capability, EnumFacing facing) {
super(world, pos, blocks, tiles, entities);
this.capability = capability;
this.facing = facing;
}
@Override
public void reload() {
super.reload();
hasBlockCaps = CapabilityHelper.blockProviders.contains(state.getBlock(), capability);
}
@SuppressWarnings("unchecked")
public T get() {
if (state == null) {
object = null;
}
if (object != null && object.isCacheValid()) {
return (T) object;
}
T result = get(capability, facing);
if (result instanceof ICacheable) {
object = (ICacheable) result;
} else {
object = null;
}
return result;
}
}
protected final boolean blocks, tiles, entities;
protected boolean hasBlockCaps, hasEntityCaps;
public CapabilityCache(World world, BlockPos pos, boolean blocks, boolean tiles, boolean entities) {
super(world, pos);
this.blocks = blocks;
this.tiles = tiles;
this.entities = entities;
}
@Override
public void reload() {
super.reload();
hasBlockCaps = CapabilityHelper.blockProviders.containsRow(state.getBlock());
hasEntityCaps = state.isFullCube();
}
@SuppressWarnings("unchecked")
public <T> T get(Capability<T> capability, EnumFacing facing) {
getBlock();
if (tiles && hasTile) {
TileEntity tile = getTile();
if (tile != null) {
T result = CapabilityHelper.get(capability, tile, facing);
if (result != null)
return result;
}
}
if (blocks && hasBlockCaps) {
IBlockCapabilityProvider provider = CapabilityHelper.blockProviders.get(state.getBlock(), capability);
if (provider != null) {
T result = (T) provider.create(world, pos, state, facing);
if (result != null) {
return result;
}
}
}
if (entities && hasEntityCaps) {
List<Entity> entityList = world.getEntitiesWithinAABBExcludingEntity(null, new AxisAlignedBB(pos));
for (Entity entity : entityList) {
T result = CapabilityHelper.get(capability, entity, facing);
if (result != null)
return result;
}
}
return null;
}
}
| 0 | 0.815647 | 1 | 0.815647 | game-dev | MEDIA | 0.986799 | game-dev | 0.948406 | 1 | 0.948406 |
prusa3d/PrusaSlicer | 6,408 | src/libslic3r/Semver.hpp | ///|/ Copyright (c) Prusa Research 2018 - 2022 Lukáš Hejl @hejllukas, Vojtěch Bubník @bubnikv, Vojtěch Král @vojtechkral
///|/
///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher
///|/
#ifndef slic3r_Semver_hpp_
#define slic3r_Semver_hpp_
#include <boost/optional.hpp>
#include <boost/format.hpp>
#include <semver.h>
#include <stdlib.h>
#include <boost/none.hpp>
#include <boost/optional/optional.hpp>
#include <string>
#include <cstring>
#include <ostream>
#include <stdexcept>
#include <limits>
#include <cstdlib>
#include "Exception.hpp"
namespace Slic3r {
class Semver
{
public:
struct Major { const int i; Major(int i) : i(i) {} };
struct Minor { const int i; Minor(int i) : i(i) {} };
struct Patch { const int i; Patch(int i) : i(i) {} };
Semver() : ver(semver_zero()) {}
Semver(int major, int minor, int patch,
boost::optional<const std::string&> metadata, boost::optional<const std::string&> prerelease)
: ver(semver_zero())
{
ver.major = major;
ver.minor = minor;
ver.patch = patch;
set_metadata(metadata);
set_prerelease(prerelease);
}
Semver(int major, int minor, int patch, const char *metadata = nullptr, const char *prerelease = nullptr)
: ver(semver_zero())
{
ver.major = major;
ver.minor = minor;
ver.patch = patch;
set_metadata(metadata);
set_prerelease(prerelease);
}
Semver(const std::string &str) : ver(semver_zero())
{
auto parsed = parse(str);
if (! parsed) {
throw Slic3r::RuntimeError(std::string("Could not parse version string: ") + str);
}
ver = parsed->ver;
parsed->ver = semver_zero();
}
static boost::optional<Semver> parse(const std::string &str)
{
semver_t ver = semver_zero();
if (::semver_parse(str.c_str(), &ver) == 0) {
return Semver(ver);
} else {
return boost::none;
}
}
static const Semver zero() { return Semver(semver_zero()); }
static const Semver inf()
{
static semver_t ver = { std::numeric_limits<int>::max(), std::numeric_limits<int>::max(), std::numeric_limits<int>::max(), nullptr, nullptr };
return Semver(ver);
}
static const Semver invalid()
{
static semver_t ver = { -1, 0, 0, nullptr, nullptr };
return Semver(ver);
}
Semver(Semver &&other) : ver(other.ver) { other.ver = semver_zero(); }
Semver(const Semver &other) : ver(::semver_copy(&other.ver)) {}
Semver &operator=(Semver &&other)
{
::semver_free(&ver);
ver = other.ver;
other.ver = semver_zero();
return *this;
}
Semver &operator=(const Semver &other)
{
::semver_free(&ver);
ver = ::semver_copy(&other.ver);
return *this;
}
~Semver() { ::semver_free(&ver); }
// const accessors
int maj() const { return ver.major; }
int min() const { return ver.minor; }
int patch() const { return ver.patch; }
const char* prerelease() const { return ver.prerelease; }
const char* metadata() const { return ver.metadata; }
// Setters
void set_maj(int maj) { ver.major = maj; }
void set_min(int min) { ver.minor = min; }
void set_patch(int patch) { ver.patch = patch; }
void set_metadata(boost::optional<const std::string &> meta)
{
if (ver.metadata)
free(ver.metadata);
ver.metadata = meta ? strdup(*meta) : nullptr;
}
void set_metadata(const char *meta)
{
if (ver.metadata)
free(ver.metadata);
ver.metadata = meta ? strdup(meta) : nullptr;
}
void set_prerelease(boost::optional<const std::string &> pre)
{
if (ver.prerelease)
free(ver.prerelease);
ver.prerelease = pre ? strdup(*pre) : nullptr;
}
void set_prerelease(const char *pre)
{
if (ver.prerelease)
free(ver.prerelease);
ver.prerelease = pre ? strdup(pre) : nullptr;
}
// Comparison
bool operator<(const Semver &b) const { return ::semver_compare(ver, b.ver) == -1; }
bool operator<=(const Semver &b) const { return ::semver_compare(ver, b.ver) <= 0; }
bool operator==(const Semver &b) const { return ::semver_compare(ver, b.ver) == 0; }
bool operator!=(const Semver &b) const { return ::semver_compare(ver, b.ver) != 0; }
bool operator>=(const Semver &b) const { return ::semver_compare(ver, b.ver) >= 0; }
bool operator>(const Semver &b) const { return ::semver_compare(ver, b.ver) == 1; }
// We're using '&' instead of the '~' operator here as '~' is unary-only:
// Satisfies patch if Major and minor are equal.
bool operator&(const Semver &b) const { return ::semver_satisfies_patch(ver, b.ver) != 0; }
bool operator^(const Semver &b) const { return ::semver_satisfies_caret(ver, b.ver) != 0; }
bool in_range(const Semver &low, const Semver &high) const { return low <= *this && *this <= high; }
bool valid() const { return *this != zero() && *this != inf() && *this != invalid(); }
// Conversion
std::string to_string() const {
auto res = (boost::format("%1%.%2%.%3%") % ver.major % ver.minor % ver.patch).str();
if (ver.prerelease != nullptr) { res += '-'; res += ver.prerelease; }
if (ver.metadata != nullptr) { res += '+'; res += ver.metadata; }
return res;
}
// Arithmetics
Semver& operator+=(const Major &b) { ver.major += b.i; return *this; }
Semver& operator+=(const Minor &b) { ver.minor += b.i; return *this; }
Semver& operator+=(const Patch &b) { ver.patch += b.i; return *this; }
Semver& operator-=(const Major &b) { ver.major -= b.i; return *this; }
Semver& operator-=(const Minor &b) { ver.minor -= b.i; return *this; }
Semver& operator-=(const Patch &b) { ver.patch -= b.i; return *this; }
Semver operator+(const Major &b) const { Semver res(*this); return res += b; }
Semver operator+(const Minor &b) const { Semver res(*this); return res += b; }
Semver operator+(const Patch &b) const { Semver res(*this); return res += b; }
Semver operator-(const Major &b) const { Semver res(*this); return res -= b; }
Semver operator-(const Minor &b) const { Semver res(*this); return res -= b; }
Semver operator-(const Patch &b) const { Semver res(*this); return res -= b; }
// Stream output
friend std::ostream& operator<<(std::ostream& os, const Semver &self) {
os << self.to_string();
return os;
}
private:
semver_t ver;
Semver(semver_t ver) : ver(ver) {}
static semver_t semver_zero() { return { 0, 0, 0, nullptr, nullptr }; }
static char * strdup(const std::string &str) { return ::semver_strdup(str.data()); }
};
}
#endif
| 0 | 0.824201 | 1 | 0.824201 | game-dev | MEDIA | 0.249342 | game-dev | 0.940505 | 1 | 0.940505 |
Gaby-Station/Gaby-Station | 2,213 | Content.Server/Atmos/EntitySystems/AutomaticAtmosSystem.cs | // SPDX-FileCopyrightText: 2022 Moony <moonheart08@users.noreply.github.com>
// SPDX-FileCopyrightText: 2022 ScalyChimp <72841710+scaly-chimp@users.noreply.github.com>
// SPDX-FileCopyrightText: 2022 Vera Aguilera Puerto <6766154+Zumorica@users.noreply.github.com>
// SPDX-FileCopyrightText: 2022 Vera Aguilera Puerto <gradientvera@outlook.com>
// SPDX-FileCopyrightText: 2022 metalgearsloth <comedian_vs_clown@hotmail.com>
// SPDX-FileCopyrightText: 2023 metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Leon Friedrich <60421075+ElectroJr@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 LordCarve <27449516+LordCarve@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
//
// SPDX-License-Identifier: MIT
using Content.Server.Atmos.Components;
using Content.Server.Shuttles.Systems;
using Robust.Shared.Map.Components;
using Robust.Shared.Physics.Events;
namespace Content.Server.Atmos.EntitySystems;
/// <summary>
/// Handles automatically adding a grid atmosphere to grids that become large enough, allowing players to build shuttles
/// with a sealed atmosphere from scratch.
/// </summary>
public sealed class AutomaticAtmosSystem : EntitySystem
{
[Dependency] private readonly AtmosphereSystem _atmosphereSystem = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<MapGridComponent, MassDataChangedEvent>(OnMassDataChanged);
}
private void OnMassDataChanged(Entity<MapGridComponent> ent, ref MassDataChangedEvent ev)
{
if (_atmosphereSystem.HasAtmosphere(ent))
return;
// We can't actually count how many tiles there are efficiently, so instead estimate with the mass.
if (ev.NewMass / ShuttleSystem.TileDensityMultiplier >= 7.0f)
{
AddComp<GridAtmosphereComponent>(ent);
Log.Info($"Giving grid {ent} GridAtmosphereComponent.");
}
// It's not super important to remove it should the grid become too small again.
// If explosions ever gain the ability to outright shatter grids, do rethink this.
return;
}
} | 0 | 0.775283 | 1 | 0.775283 | game-dev | MEDIA | 0.920971 | game-dev | 0.882971 | 1 | 0.882971 |
BramStoutProductions/MiEx | 9,012 | src/nl/bramstout/mcworldexporter/world/anvil/chunkreader/ChunkReader_2529_2835.java | /*
* BSD 3-Clause License
*
* Copyright (c) 2024, Bram Stout Productions
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package nl.bramstout.mcworldexporter.world.anvil.chunkreader;
import java.util.Arrays;
import nl.bramstout.mcworldexporter.Reference;
import nl.bramstout.mcworldexporter.nbt.NbtTag;
import nl.bramstout.mcworldexporter.nbt.NbtTagByte;
import nl.bramstout.mcworldexporter.nbt.NbtTagCompound;
import nl.bramstout.mcworldexporter.nbt.NbtTagIntArray;
import nl.bramstout.mcworldexporter.nbt.NbtTagList;
import nl.bramstout.mcworldexporter.nbt.NbtTagLongArray;
import nl.bramstout.mcworldexporter.nbt.NbtTagString;
import nl.bramstout.mcworldexporter.translation.BlockTranslation.BlockTranslatorManager;
import nl.bramstout.mcworldexporter.translation.TranslationRegistry;
import nl.bramstout.mcworldexporter.world.Block;
import nl.bramstout.mcworldexporter.world.BlockRegistry;
import nl.bramstout.mcworldexporter.world.Chunk;
/**
* Chunks from 20w17a (1.16) to 21w39a (1.18)
*/
public class ChunkReader_2529_2835 extends ChunkReader{
@Override
public void readChunk(Chunk chunk, NbtTagCompound rootTag, int dataVersion) {
NbtTagCompound levelTag = (NbtTagCompound) rootTag.get("Level");
String status = "full";
NbtTagString statusTag = (NbtTagString) levelTag.get("Status");
if(statusTag != null)
status = statusTag.getData();
if (!status.contains("full")) {
//chunk._setBlocks(new int[1][]);
//chunk._setBiomes(new int[1][]);
return;
}
Reference<char[]> charBuffer = new Reference<char[]>();
BlockTranslatorManager blockTranslatorManager = TranslationRegistry.BLOCK_JAVA.getTranslator(dataVersion);
NbtTagList sections = (NbtTagList) levelTag.get("Sections");
int minSectionY = Integer.MAX_VALUE;
int maxSectionY = Integer.MIN_VALUE;
NbtTagCompound section = null;
for (NbtTag tag : sections.getData()) {
section = (NbtTagCompound) tag;
minSectionY = Math.min(minSectionY, ((NbtTagByte) section.get("Y")).getData());
maxSectionY = Math.max(maxSectionY, ((NbtTagByte) section.get("Y")).getData());
}
if(minSectionY == Integer.MAX_VALUE || maxSectionY == Integer.MIN_VALUE) {
return;
}
chunk._setChunkSectionOffset(minSectionY);
chunk._setBlocks(new int[maxSectionY - chunk._getChunkSectionOffset() + 1][]);
chunk._setBiomes(new int[maxSectionY - chunk._getChunkSectionOffset() + 1][]);
NbtTagIntArray biomesTag = (NbtTagIntArray) levelTag.get("Biomes");
int sectionY;
NbtTagList palette = null;
int[] paletteMap = null;
String blockName = "";
NbtTagCompound blockProperties = null;
int i = 0;
NbtTagLongArray sectionData;
int[] sectionBlocks = null;
int[] sectionBiomes = null;
int bitsPerId = 0;
int idsPerLong = 0;
int longIndex = 0;
int idIndex = 0;
long paletteIndex = 0;
for (NbtTag tag : sections.getData()) {
section = (NbtTagCompound) tag;
sectionY = ((NbtTagByte) section.get("Y")).getData();
palette = (NbtTagList) section.get("Palette");
if(palette == null)
continue;
if (paletteMap == null || palette.getSize() > paletteMap.length)
paletteMap = new int[palette.getSize()];
i = 0;
for (NbtTag block : palette.getData()) {
blockName = ((NbtTagString) ((NbtTagCompound) block).get("Name")).getData();
if(blockName.equals("cave_air") || blockName.equals("minecraft:cave_air") ||
blockName.equals("void_air") || blockName.equals("minecraft:void_air"))
blockName = "minecraft:air";
blockProperties = (NbtTagCompound) ((NbtTagCompound) block).get("Properties");
boolean freeBlockProperties = false;
if(blockProperties == null) {
blockProperties = NbtTagCompound.newInstance("");
freeBlockProperties = true;
}
blockName = blockTranslatorManager.map(blockName, blockProperties);
paletteMap[i] = BlockRegistry.getIdForName(blockName, blockProperties, dataVersion, charBuffer);
if(freeBlockProperties)
blockProperties.free();
++i;
}
// If this section is entirely air, let's keep the section array still null for efficiency
if(palette.getSize() == 1 && paletteMap[0] == 0)
continue;
sectionData = (NbtTagLongArray) section.get("BlockStates");
sectionBlocks = new int[16*16*16];
chunk._getBlocks()[sectionY - chunk._getChunkSectionOffset()] = sectionBlocks;
if (sectionData == null) {
Arrays.fill(sectionBlocks, paletteMap[0]);
} else {
bitsPerId = Math.max(32 - Integer.numberOfLeadingZeros(palette.getSize() - 1), 4);
idsPerLong = 64 / bitsPerId;
longIndex = 0;
idIndex = 0;
paletteIndex = 0;
for (i = 0; i < 16 * 16 * 16; ++i) {
longIndex = i / idsPerLong;
idIndex = i % idsPerLong;
paletteIndex = (sectionData.getData()[longIndex] >>> (idIndex * bitsPerId)) & (-1l >>> (64 - bitsPerId));
sectionBlocks[i] = paletteMap[(int) paletteIndex];
}
}
if(biomesTag != null){
sectionBiomes = new int[4*4*4];
chunk._getBiomes()[sectionY - chunk._getChunkSectionOffset()] = sectionBiomes;
i = 0;
for(int y = 0; y < 4; ++y) {
for(int z = 0; z < 4; ++z) {
for(int x = 0; x < 4; ++x) {
int index = (sectionY * 4 + y) * 16 + z * 4 + x;
sectionBiomes[i] = BiomeIds.getRuntimeIdForId(biomesTag.getData()[index], dataVersion);
i++;
}
}
}
}
}
NbtTagList blockEntities = (NbtTagList) levelTag.get("TileEntities");
if(blockEntities != null) {
NbtTagCompound blockEntity = null;
String blockEntityName = "";
int blockEntityX = 0;
int blockEntityY = 0;
int blockEntityZ = 0;
int blockId = 0;
int blockEntitySectionY = 0;
int currentBlockId = 0;
Block currentBlock = null;
for(NbtTag tag : blockEntities.getData()) {
blockEntity = (NbtTagCompound) tag;
NbtTagByte keepPackedTag = (NbtTagByte)blockEntity.get("keepPacked");
if(keepPackedTag == null || keepPackedTag.getData() > 0)
continue;
blockEntityName = ((NbtTagString) blockEntity.get("id")).getData();
blockEntityX = blockEntity.get("x").asInt();
blockEntityY = blockEntity.get("y").asInt();
blockEntityZ = blockEntity.get("z").asInt();
blockEntityX -= chunk.getChunkX() * 16;
blockEntityZ -= chunk.getChunkZ() * 16;
// Make sure that the block entity is actually in the chunk.
if(blockEntityX < 0 || blockEntityX > 15 || blockEntityZ < 0 || blockEntityZ > 15)
continue;
currentBlockId = chunk.getBlockIdLocal(blockEntityX, blockEntityY, blockEntityZ);
currentBlock = BlockRegistry.getBlock(currentBlockId);
blockEntity.addAllElements(currentBlock.getProperties());
if(currentBlockId > 0)
blockEntityName = currentBlock.getName();
blockEntityName = blockTranslatorManager.map(blockEntityName, blockEntity);
blockId = BlockRegistry.getIdForName(blockEntityName, blockEntity, dataVersion, charBuffer);
blockEntitySectionY = (blockEntityY < 0 ? (blockEntityY - 15) : blockEntityY) / 16;
blockEntityY -= blockEntitySectionY * 16;
blockEntitySectionY -= chunk._getChunkSectionOffset();
if(blockEntitySectionY >= chunk._getBlocks().length)
continue;
if(chunk._getBlocks()[blockEntitySectionY] == null)
chunk._getBlocks()[blockEntitySectionY] = new int[16*16*16];
chunk._getBlocks()[blockEntitySectionY][blockEntityY * 16 * 16 + blockEntityZ * 16 + blockEntityX] = blockId;
}
}
}
@Override
public boolean supportDataVersion(int dataVersion) {
return dataVersion >= 2529 && dataVersion <= 2835;
}
}
| 0 | 0.952341 | 1 | 0.952341 | game-dev | MEDIA | 0.798615 | game-dev | 0.978778 | 1 | 0.978778 |
BitBuf/nbt | 4,758 | src/test/java/dev/dewy/nbt/test/NbtTest.java | package dev.dewy.nbt.test;
import dev.dewy.nbt.Nbt;
import dev.dewy.nbt.io.CompressionType;
import dev.dewy.nbt.tags.array.ByteArrayTag;
import dev.dewy.nbt.tags.array.IntArrayTag;
import dev.dewy.nbt.tags.array.LongArrayTag;
import dev.dewy.nbt.tags.collection.CompoundTag;
import dev.dewy.nbt.tags.collection.ListTag;
import dev.dewy.nbt.tags.primitive.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* A simple demonstration of how the NBT library may be used.
*
* @author dewy
*/
public class NbtTest {
// paths for the sample files
private static final String SAMPLES_PATH = "samples/";
private static final File STANDARD_SAMPLE = new File(SAMPLES_PATH + "sample.nbt");
private static final File GZIP_SAMPLE = new File(SAMPLES_PATH + "samplegzip.nbt");
private static final File ZLIB_SAMPLE = new File(SAMPLES_PATH + "samplezlib.nbt");
private static final File JSON_SAMPLE = new File(SAMPLES_PATH + "sample.json");
// instance of the Nbt class, globally used. use setTypeRegistry() to use custom-made tag types.
private static final Nbt NBT = new Nbt();
public static void main(String[] args) throws IOException {
// creation of a root compound (think of it like a JSONObject in GSON)
CompoundTag root = new CompoundTag("root");
// primitive NBT tags (tags contained inside compounds MUST have unique names)
root.put(new ByteTag("byte", 45));
root.put(new ShortTag("short", 345));
root.put(new IntTag("int", -981735));
root.put(new LongTag("long", -398423290489L));
// more primitives, using the specialized put methods
root.putFloat("float", 12.5F);
root.putDouble("double", -19040912.1235);
// putting a previously unnamed tag.
root.put("string", new StringTag("https://dewy.dev"));
// array NBT tags
root.put(new ByteArrayTag("bytes", new byte[] {0, -124, 13, -6, Byte.MAX_VALUE}));
root.put(new IntArrayTag("ints", new int[] {0, -1348193, 817519, Integer.MIN_VALUE, 4}));
// constructing array tags with List<> objects
List<Long> longList = new ArrayList<>();
longList.add(12490812L);
longList.add(903814091904L);
longList.add(-3L);
longList.add(Long.MIN_VALUE);
longList.add(Long.MAX_VALUE);
longList.add(0L);
root.put(new LongArrayTag("longs", longList));
// compound and list tags
CompoundTag subCompound = new CompoundTag("sub");
ListTag<CompoundTag> doubles = new ListTag<>("listmoment");
for (int i = 0; i < 1776; i++) {
CompoundTag tmp = new CompoundTag("tmp" + i);
tmp.put(new DoubleTag("i", i));
tmp.put(new DoubleTag("n", i / 1348.1));
doubles.add(tmp);
}
subCompound.put(doubles);
root.put(subCompound);
// compound containing an empty compound
ListTag<CompoundTag> compounds = new ListTag<>("compounds");
compounds.add(new CompoundTag());
root.put(compounds);
// list containing an empty list of ints
ListTag<ListTag<IntTag>> listsOfInts = new ListTag<>("listofints");
listsOfInts.add(new ListTag<>());
root.putList("listofints", listsOfInts.getValue());
// writing to file (no compression type provided for no compression)
NBT.toFile(root, STANDARD_SAMPLE);
NBT.toFile(root, GZIP_SAMPLE, CompressionType.GZIP);
NBT.toFile(root, ZLIB_SAMPLE, CompressionType.ZLIB);
// displaying a Base64 representation
System.out.println(NBT.toBase64(root));
// reading from file
CompoundTag clone = NBT.fromFile(ZLIB_SAMPLE);
System.out.println(clone.equals(root));
// retrieving data from the read compound
System.out.println(clone.getName());
System.out.println("Be sure to visit " + clone.getString("string").getValue() + " c:");
// nbt to json and back: see readme for NBT JSON format documentation
jsonTest();
// displaying as SNBT
System.out.println(root);
}
private static void jsonTest() throws IOException {
CompoundTag root = new CompoundTag("root");
root.putInt("primitive", 3);
root.putIntArray("array", new int[]{0, 1, 2, 3});
List<StringTag> list = new LinkedList<>();
list.add(new StringTag("duck"));
list.add(new StringTag("goose"));
root.putList("list", list);
root.put("compound", new CompoundTag());
NBT.toJson(root, JSON_SAMPLE);
System.out.println(NBT.fromJson(JSON_SAMPLE).equals(root));
}
}
| 0 | 0.740763 | 1 | 0.740763 | game-dev | MEDIA | 0.809605 | game-dev | 0.897524 | 1 | 0.897524 |
RainbowMango/GoComments | 13,248 | go-go1.11/src/runtime/race.go | // Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build race
package runtime
import (
"unsafe"
)
// Public race detection API, present iff build with -race.
func RaceRead(addr unsafe.Pointer)
func RaceWrite(addr unsafe.Pointer)
func RaceReadRange(addr unsafe.Pointer, len int)
func RaceWriteRange(addr unsafe.Pointer, len int)
func RaceErrors() int {
var n uint64
racecall(&__tsan_report_count, uintptr(unsafe.Pointer(&n)), 0, 0, 0)
return int(n)
}
//go:nosplit
// RaceAcquire/RaceRelease/RaceReleaseMerge establish happens-before relations
// between goroutines. These inform the race detector about actual synchronization
// that it can't see for some reason (e.g. synchronization within RaceDisable/RaceEnable
// sections of code).
// RaceAcquire establishes a happens-before relation with the preceding
// RaceReleaseMerge on addr up to and including the last RaceRelease on addr.
// In terms of the C memory model (C11 §5.1.2.4, §7.17.3),
// RaceAcquire is equivalent to atomic_load(memory_order_acquire).
func RaceAcquire(addr unsafe.Pointer) {
raceacquire(addr)
}
//go:nosplit
// RaceRelease performs a release operation on addr that
// can synchronize with a later RaceAcquire on addr.
//
// In terms of the C memory model, RaceRelease is equivalent to
// atomic_store(memory_order_release).
func RaceRelease(addr unsafe.Pointer) {
racerelease(addr)
}
//go:nosplit
// RaceReleaseMerge is like RaceRelease, but also establishes a happens-before
// relation with the preceding RaceRelease or RaceReleaseMerge on addr.
//
// In terms of the C memory model, RaceReleaseMerge is equivalent to
// atomic_exchange(memory_order_release).
func RaceReleaseMerge(addr unsafe.Pointer) {
racereleasemerge(addr)
}
//go:nosplit
// RaceDisable disables handling of race synchronization events in the current goroutine.
// Handling is re-enabled with RaceEnable. RaceDisable/RaceEnable can be nested.
// Non-synchronization events (memory accesses, function entry/exit) still affect
// the race detector.
func RaceDisable() {
_g_ := getg()
if _g_.raceignore == 0 {
racecall(&__tsan_go_ignore_sync_begin, _g_.racectx, 0, 0, 0)
}
_g_.raceignore++
}
//go:nosplit
// RaceEnable re-enables handling of race events in the current goroutine.
func RaceEnable() {
_g_ := getg()
_g_.raceignore--
if _g_.raceignore == 0 {
racecall(&__tsan_go_ignore_sync_end, _g_.racectx, 0, 0, 0)
}
}
// Private interface for the runtime.
const raceenabled = true
// For all functions accepting callerpc and pc,
// callerpc is a return PC of the function that calls this function,
// pc is start PC of the function that calls this function.
func raceReadObjectPC(t *_type, addr unsafe.Pointer, callerpc, pc uintptr) {
kind := t.kind & kindMask
if kind == kindArray || kind == kindStruct {
// for composite objects we have to read every address
// because a write might happen to any subobject.
racereadrangepc(addr, t.size, callerpc, pc)
} else {
// for non-composite objects we can read just the start
// address, as any write must write the first byte.
racereadpc(addr, callerpc, pc)
}
}
func raceWriteObjectPC(t *_type, addr unsafe.Pointer, callerpc, pc uintptr) {
kind := t.kind & kindMask
if kind == kindArray || kind == kindStruct {
// for composite objects we have to write every address
// because a write might happen to any subobject.
racewriterangepc(addr, t.size, callerpc, pc)
} else {
// for non-composite objects we can write just the start
// address, as any write must write the first byte.
racewritepc(addr, callerpc, pc)
}
}
//go:noescape
func racereadpc(addr unsafe.Pointer, callpc, pc uintptr)
//go:noescape
func racewritepc(addr unsafe.Pointer, callpc, pc uintptr)
type symbolizeCodeContext struct {
pc uintptr
fn *byte
file *byte
line uintptr
off uintptr
res uintptr
}
var qq = [...]byte{'?', '?', 0}
var dash = [...]byte{'-', 0}
const (
raceGetProcCmd = iota
raceSymbolizeCodeCmd
raceSymbolizeDataCmd
)
// Callback from C into Go, runs on g0.
func racecallback(cmd uintptr, ctx unsafe.Pointer) {
switch cmd {
case raceGetProcCmd:
throw("should have been handled by racecallbackthunk")
case raceSymbolizeCodeCmd:
raceSymbolizeCode((*symbolizeCodeContext)(ctx))
case raceSymbolizeDataCmd:
raceSymbolizeData((*symbolizeDataContext)(ctx))
default:
throw("unknown command")
}
}
func raceSymbolizeCode(ctx *symbolizeCodeContext) {
f := FuncForPC(ctx.pc)
if f != nil {
file, line := f.FileLine(ctx.pc)
if line != 0 {
ctx.fn = cfuncname(f.funcInfo())
ctx.line = uintptr(line)
ctx.file = &bytes(file)[0] // assume NUL-terminated
ctx.off = ctx.pc - f.Entry()
ctx.res = 1
return
}
}
ctx.fn = &qq[0]
ctx.file = &dash[0]
ctx.line = 0
ctx.off = ctx.pc
ctx.res = 1
}
type symbolizeDataContext struct {
addr uintptr
heap uintptr
start uintptr
size uintptr
name *byte
file *byte
line uintptr
res uintptr
}
func raceSymbolizeData(ctx *symbolizeDataContext) {
if base, span, _ := findObject(ctx.addr, 0, 0); base != 0 {
ctx.heap = 1
ctx.start = base
ctx.size = span.elemsize
ctx.res = 1
}
}
// Race runtime functions called via runtime·racecall.
//go:linkname __tsan_init __tsan_init
var __tsan_init byte
//go:linkname __tsan_fini __tsan_fini
var __tsan_fini byte
//go:linkname __tsan_proc_create __tsan_proc_create
var __tsan_proc_create byte
//go:linkname __tsan_proc_destroy __tsan_proc_destroy
var __tsan_proc_destroy byte
//go:linkname __tsan_map_shadow __tsan_map_shadow
var __tsan_map_shadow byte
//go:linkname __tsan_finalizer_goroutine __tsan_finalizer_goroutine
var __tsan_finalizer_goroutine byte
//go:linkname __tsan_go_start __tsan_go_start
var __tsan_go_start byte
//go:linkname __tsan_go_end __tsan_go_end
var __tsan_go_end byte
//go:linkname __tsan_malloc __tsan_malloc
var __tsan_malloc byte
//go:linkname __tsan_free __tsan_free
var __tsan_free byte
//go:linkname __tsan_acquire __tsan_acquire
var __tsan_acquire byte
//go:linkname __tsan_release __tsan_release
var __tsan_release byte
//go:linkname __tsan_release_merge __tsan_release_merge
var __tsan_release_merge byte
//go:linkname __tsan_go_ignore_sync_begin __tsan_go_ignore_sync_begin
var __tsan_go_ignore_sync_begin byte
//go:linkname __tsan_go_ignore_sync_end __tsan_go_ignore_sync_end
var __tsan_go_ignore_sync_end byte
//go:linkname __tsan_report_count __tsan_report_count
var __tsan_report_count byte
// Mimic what cmd/cgo would do.
//go:cgo_import_static __tsan_init
//go:cgo_import_static __tsan_fini
//go:cgo_import_static __tsan_proc_create
//go:cgo_import_static __tsan_proc_destroy
//go:cgo_import_static __tsan_map_shadow
//go:cgo_import_static __tsan_finalizer_goroutine
//go:cgo_import_static __tsan_go_start
//go:cgo_import_static __tsan_go_end
//go:cgo_import_static __tsan_malloc
//go:cgo_import_static __tsan_free
//go:cgo_import_static __tsan_acquire
//go:cgo_import_static __tsan_release
//go:cgo_import_static __tsan_release_merge
//go:cgo_import_static __tsan_go_ignore_sync_begin
//go:cgo_import_static __tsan_go_ignore_sync_end
//go:cgo_import_static __tsan_report_count
// These are called from race_amd64.s.
//go:cgo_import_static __tsan_read
//go:cgo_import_static __tsan_read_pc
//go:cgo_import_static __tsan_read_range
//go:cgo_import_static __tsan_write
//go:cgo_import_static __tsan_write_pc
//go:cgo_import_static __tsan_write_range
//go:cgo_import_static __tsan_func_enter
//go:cgo_import_static __tsan_func_exit
//go:cgo_import_static __tsan_go_atomic32_load
//go:cgo_import_static __tsan_go_atomic64_load
//go:cgo_import_static __tsan_go_atomic32_store
//go:cgo_import_static __tsan_go_atomic64_store
//go:cgo_import_static __tsan_go_atomic32_exchange
//go:cgo_import_static __tsan_go_atomic64_exchange
//go:cgo_import_static __tsan_go_atomic32_fetch_add
//go:cgo_import_static __tsan_go_atomic64_fetch_add
//go:cgo_import_static __tsan_go_atomic32_compare_exchange
//go:cgo_import_static __tsan_go_atomic64_compare_exchange
// start/end of global data (data+bss).
var racedatastart uintptr
var racedataend uintptr
// start/end of heap for race_amd64.s
var racearenastart uintptr
var racearenaend uintptr
func racefuncenter(uintptr)
func racefuncenterfp()
func racefuncexit()
func racereadrangepc1(uintptr, uintptr, uintptr)
func racewriterangepc1(uintptr, uintptr, uintptr)
func racecallbackthunk(uintptr)
// racecall allows calling an arbitrary function f from C race runtime
// with up to 4 uintptr arguments.
func racecall(*byte, uintptr, uintptr, uintptr, uintptr)
// checks if the address has shadow (i.e. heap or data/bss)
//go:nosplit
func isvalidaddr(addr unsafe.Pointer) bool {
return racearenastart <= uintptr(addr) && uintptr(addr) < racearenaend ||
racedatastart <= uintptr(addr) && uintptr(addr) < racedataend
}
//go:nosplit
func raceinit() (gctx, pctx uintptr) {
// cgo is required to initialize libc, which is used by race runtime
if !iscgo {
throw("raceinit: race build must use cgo")
}
racecall(&__tsan_init, uintptr(unsafe.Pointer(&gctx)), uintptr(unsafe.Pointer(&pctx)), funcPC(racecallbackthunk), 0)
// Round data segment to page boundaries, because it's used in mmap().
start := ^uintptr(0)
end := uintptr(0)
if start > firstmoduledata.noptrdata {
start = firstmoduledata.noptrdata
}
if start > firstmoduledata.data {
start = firstmoduledata.data
}
if start > firstmoduledata.noptrbss {
start = firstmoduledata.noptrbss
}
if start > firstmoduledata.bss {
start = firstmoduledata.bss
}
if end < firstmoduledata.enoptrdata {
end = firstmoduledata.enoptrdata
}
if end < firstmoduledata.edata {
end = firstmoduledata.edata
}
if end < firstmoduledata.enoptrbss {
end = firstmoduledata.enoptrbss
}
if end < firstmoduledata.ebss {
end = firstmoduledata.ebss
}
size := round(end-start, _PageSize)
racecall(&__tsan_map_shadow, start, size, 0, 0)
racedatastart = start
racedataend = start + size
return
}
var raceFiniLock mutex
//go:nosplit
func racefini() {
// racefini() can only be called once to avoid races.
// This eventually (via __tsan_fini) calls C.exit which has
// undefined behavior if called more than once. If the lock is
// already held it's assumed that the first caller exits the program
// so other calls can hang forever without an issue.
lock(&raceFiniLock)
racecall(&__tsan_fini, 0, 0, 0, 0)
}
//go:nosplit
func raceproccreate() uintptr {
var ctx uintptr
racecall(&__tsan_proc_create, uintptr(unsafe.Pointer(&ctx)), 0, 0, 0)
return ctx
}
//go:nosplit
func raceprocdestroy(ctx uintptr) {
racecall(&__tsan_proc_destroy, ctx, 0, 0, 0)
}
//go:nosplit
func racemapshadow(addr unsafe.Pointer, size uintptr) {
if racearenastart == 0 {
racearenastart = uintptr(addr)
}
if racearenaend < uintptr(addr)+size {
racearenaend = uintptr(addr) + size
}
racecall(&__tsan_map_shadow, uintptr(addr), size, 0, 0)
}
//go:nosplit
func racemalloc(p unsafe.Pointer, sz uintptr) {
racecall(&__tsan_malloc, 0, 0, uintptr(p), sz)
}
//go:nosplit
func racefree(p unsafe.Pointer, sz uintptr) {
racecall(&__tsan_free, uintptr(p), sz, 0, 0)
}
//go:nosplit
func racegostart(pc uintptr) uintptr {
_g_ := getg()
var spawng *g
if _g_.m.curg != nil {
spawng = _g_.m.curg
} else {
spawng = _g_
}
var racectx uintptr
racecall(&__tsan_go_start, spawng.racectx, uintptr(unsafe.Pointer(&racectx)), pc, 0)
return racectx
}
//go:nosplit
func racegoend() {
racecall(&__tsan_go_end, getg().racectx, 0, 0, 0)
}
//go:nosplit
func racewriterangepc(addr unsafe.Pointer, sz, callpc, pc uintptr) {
_g_ := getg()
if _g_ != _g_.m.curg {
// The call is coming from manual instrumentation of Go code running on g0/gsignal.
// Not interesting.
return
}
if callpc != 0 {
racefuncenter(callpc)
}
racewriterangepc1(uintptr(addr), sz, pc)
if callpc != 0 {
racefuncexit()
}
}
//go:nosplit
func racereadrangepc(addr unsafe.Pointer, sz, callpc, pc uintptr) {
_g_ := getg()
if _g_ != _g_.m.curg {
// The call is coming from manual instrumentation of Go code running on g0/gsignal.
// Not interesting.
return
}
if callpc != 0 {
racefuncenter(callpc)
}
racereadrangepc1(uintptr(addr), sz, pc)
if callpc != 0 {
racefuncexit()
}
}
//go:nosplit
func raceacquire(addr unsafe.Pointer) {
raceacquireg(getg(), addr)
}
//go:nosplit
func raceacquireg(gp *g, addr unsafe.Pointer) {
if getg().raceignore != 0 || !isvalidaddr(addr) {
return
}
racecall(&__tsan_acquire, gp.racectx, uintptr(addr), 0, 0)
}
//go:nosplit
func racerelease(addr unsafe.Pointer) {
racereleaseg(getg(), addr)
}
//go:nosplit
func racereleaseg(gp *g, addr unsafe.Pointer) {
if getg().raceignore != 0 || !isvalidaddr(addr) {
return
}
racecall(&__tsan_release, gp.racectx, uintptr(addr), 0, 0)
}
//go:nosplit
func racereleasemerge(addr unsafe.Pointer) {
racereleasemergeg(getg(), addr)
}
//go:nosplit
func racereleasemergeg(gp *g, addr unsafe.Pointer) {
if getg().raceignore != 0 || !isvalidaddr(addr) {
return
}
racecall(&__tsan_release_merge, gp.racectx, uintptr(addr), 0, 0)
}
//go:nosplit
func racefingo() {
racecall(&__tsan_finalizer_goroutine, getg().racectx, 0, 0, 0)
}
| 0 | 0.724248 | 1 | 0.724248 | game-dev | MEDIA | 0.105765 | game-dev | 0.774123 | 1 | 0.774123 |
SpartanJ/eepp | 60,049 | src/thirdparty/SDL2/src/dynapi/SDL_dynapi_procs.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/* vi: set ts=4 sw=4 expandtab: */
/*
DO NOT EDIT THIS FILE BY HAND. It is autogenerated by gendynapi.pl.
NEVER REARRANGE THIS FILE, THE ORDER IS ABI LAW.
Changing this file means bumping SDL_DYNAPI_VERSION. You can safely add
new items to the end of the file, though.
Also, this file gets included multiple times, don't add #pragma once, etc.
*/
/* direct jump magic can use these, the rest needs special code. */
#if !SDL_DYNAPI_PROC_NO_VARARGS
SDL_DYNAPI_PROC(int,SDL_SetError,(SDL_PRINTF_FORMAT_STRING const char *a, ...),(a),return)
SDL_DYNAPI_PROC(void,SDL_Log,(SDL_PRINTF_FORMAT_STRING const char *a, ...),(a),)
SDL_DYNAPI_PROC(void,SDL_LogVerbose,(int a, SDL_PRINTF_FORMAT_STRING const char *b, ...),(a,b),)
SDL_DYNAPI_PROC(void,SDL_LogDebug,(int a, SDL_PRINTF_FORMAT_STRING const char *b, ...),(a,b),)
SDL_DYNAPI_PROC(void,SDL_LogInfo,(int a, SDL_PRINTF_FORMAT_STRING const char *b, ...),(a,b),)
SDL_DYNAPI_PROC(void,SDL_LogWarn,(int a, SDL_PRINTF_FORMAT_STRING const char *b, ...),(a,b),)
SDL_DYNAPI_PROC(void,SDL_LogError,(int a, SDL_PRINTF_FORMAT_STRING const char *b, ...),(a,b),)
SDL_DYNAPI_PROC(void,SDL_LogCritical,(int a, SDL_PRINTF_FORMAT_STRING const char *b, ...),(a,b),)
SDL_DYNAPI_PROC(void,SDL_LogMessage,(int a, SDL_LogPriority b, SDL_PRINTF_FORMAT_STRING const char *c, ...),(a,b,c),)
SDL_DYNAPI_PROC(int,SDL_sscanf,(const char *a, SDL_SCANF_FORMAT_STRING const char *b, ...),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_snprintf,(SDL_OUT_Z_CAP(b) char *a, size_t b, SDL_PRINTF_FORMAT_STRING const char *c, ...),(a,b,c),return)
#endif
#ifdef SDL_CreateThread
#undef SDL_CreateThread
#endif
#if defined(__WIN32__)
SDL_DYNAPI_PROC(SDL_Thread*,SDL_CreateThread,(SDL_ThreadFunction a, const char *b, void *c, pfnSDL_CurrentBeginThread d, pfnSDL_CurrentEndThread e),(a,b,c,d,e),return)
#elif defined(__OS2__)
SDL_DYNAPI_PROC(SDL_Thread*,SDL_CreateThread,(SDL_ThreadFunction a, const char *b, void *c, pfnSDL_CurrentBeginThread d, pfnSDL_CurrentEndThread e),(a,b,c,d,e),return)
#else
SDL_DYNAPI_PROC(SDL_Thread*,SDL_CreateThread,(SDL_ThreadFunction a, const char *b, void *c),(a,b,c),return)
#endif
#ifdef HAVE_STDIO_H
SDL_DYNAPI_PROC(SDL_RWops*,SDL_RWFromFP,(FILE *a, SDL_bool b),(a,b),return)
#else
SDL_DYNAPI_PROC(SDL_RWops*,SDL_RWFromFP,(void *a, SDL_bool b),(a,b),return)
#endif
#ifdef __WIN32__
SDL_DYNAPI_PROC(int,SDL_RegisterApp,(char *a, Uint32 b, void *c),(a,b,c),return)
SDL_DYNAPI_PROC(void,SDL_UnregisterApp,(void),(),)
SDL_DYNAPI_PROC(int,SDL_Direct3D9GetAdapterIndex,(int a),(a),return)
SDL_DYNAPI_PROC(IDirect3DDevice9*,SDL_RenderGetD3D9Device,(SDL_Renderer *a),(a),return)
#endif
#ifdef __IPHONEOS__
SDL_DYNAPI_PROC(int,SDL_iPhoneSetAnimationCallback,(SDL_Window *a, int b, void c, void *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(void,SDL_iPhoneSetEventPump,(SDL_bool a),(a),)
#endif
#ifdef __ANDROID__
SDL_DYNAPI_PROC(void*,SDL_AndroidGetJNIEnv,(void),(),return)
SDL_DYNAPI_PROC(void*,SDL_AndroidGetActivity,(void),(),return)
SDL_DYNAPI_PROC(const char*,SDL_AndroidGetInternalStoragePath,(void),(),return)
SDL_DYNAPI_PROC(int,SDL_AndroidGetExternalStorageState,(void),(),return)
SDL_DYNAPI_PROC(const char*,SDL_AndroidGetExternalStoragePath,(void),(),return)
#endif
SDL_DYNAPI_PROC(int,SDL_Init,(Uint32 a),(a),return)
SDL_DYNAPI_PROC(int,SDL_InitSubSystem,(Uint32 a),(a),return)
SDL_DYNAPI_PROC(void,SDL_QuitSubSystem,(Uint32 a),(a),)
SDL_DYNAPI_PROC(Uint32,SDL_WasInit,(Uint32 a),(a),return)
SDL_DYNAPI_PROC(void,SDL_Quit,(void),(),)
SDL_DYNAPI_PROC(SDL_assert_state,SDL_ReportAssertion,(SDL_assert_data *a, const char *b, const char *c, int d),(a,b,c,d),return)
SDL_DYNAPI_PROC(void,SDL_SetAssertionHandler,(SDL_AssertionHandler a, void *b),(a,b),)
SDL_DYNAPI_PROC(const SDL_assert_data*,SDL_GetAssertionReport,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_ResetAssertionReport,(void),(),)
SDL_DYNAPI_PROC(SDL_bool,SDL_AtomicTryLock,(SDL_SpinLock *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_AtomicLock,(SDL_SpinLock *a),(a),)
SDL_DYNAPI_PROC(void,SDL_AtomicUnlock,(SDL_SpinLock *a),(a),)
SDL_DYNAPI_PROC(SDL_bool,SDL_AtomicCAS,(SDL_atomic_t *a, int b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_AtomicSet,(SDL_atomic_t *a, int b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_AtomicGet,(SDL_atomic_t *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_AtomicAdd,(SDL_atomic_t *a, int b),(a,b),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_AtomicCASPtr,(void **a, void *b, void *c),(a,b,c),return)
SDL_DYNAPI_PROC(void*,SDL_AtomicSetPtr,(void **a, void *b),(a,b),return)
SDL_DYNAPI_PROC(void*,SDL_AtomicGetPtr,(void **a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GetNumAudioDrivers,(void),(),return)
SDL_DYNAPI_PROC(const char*,SDL_GetAudioDriver,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_AudioInit,(const char *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_AudioQuit,(void),(),)
SDL_DYNAPI_PROC(const char*,SDL_GetCurrentAudioDriver,(void),(),return)
SDL_DYNAPI_PROC(int,SDL_OpenAudio,(SDL_AudioSpec *a, SDL_AudioSpec *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetNumAudioDevices,(int a),(a),return)
SDL_DYNAPI_PROC(const char*,SDL_GetAudioDeviceName,(int a, int b),(a,b),return)
SDL_DYNAPI_PROC(SDL_AudioDeviceID,SDL_OpenAudioDevice,(const char *a, int b, const SDL_AudioSpec *c, SDL_AudioSpec *d, int e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(SDL_AudioStatus,SDL_GetAudioStatus,(void),(),return)
SDL_DYNAPI_PROC(SDL_AudioStatus,SDL_GetAudioDeviceStatus,(SDL_AudioDeviceID a),(a),return)
SDL_DYNAPI_PROC(void,SDL_PauseAudio,(int a),(a),)
SDL_DYNAPI_PROC(void,SDL_PauseAudioDevice,(SDL_AudioDeviceID a, int b),(a,b),)
SDL_DYNAPI_PROC(SDL_AudioSpec*,SDL_LoadWAV_RW,(SDL_RWops *a, int b, SDL_AudioSpec *c, Uint8 **d, Uint32 *e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(void,SDL_FreeWAV,(Uint8 *a),(a),)
SDL_DYNAPI_PROC(int,SDL_BuildAudioCVT,(SDL_AudioCVT *a, SDL_AudioFormat b, Uint8 c, int d, SDL_AudioFormat e, Uint8 f, int g),(a,b,c,d,e,f,g),return)
SDL_DYNAPI_PROC(int,SDL_ConvertAudio,(SDL_AudioCVT *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_MixAudio,(Uint8 *a, const Uint8 *b, Uint32 c, int d),(a,b,c,d),)
SDL_DYNAPI_PROC(void,SDL_MixAudioFormat,(Uint8 *a, const Uint8 *b, SDL_AudioFormat c, Uint32 d, int e),(a,b,c,d,e),)
SDL_DYNAPI_PROC(void,SDL_LockAudio,(void),(),)
SDL_DYNAPI_PROC(void,SDL_LockAudioDevice,(SDL_AudioDeviceID a),(a),)
SDL_DYNAPI_PROC(void,SDL_UnlockAudio,(void),(),)
SDL_DYNAPI_PROC(void,SDL_UnlockAudioDevice,(SDL_AudioDeviceID a),(a),)
SDL_DYNAPI_PROC(void,SDL_CloseAudio,(void),(),)
SDL_DYNAPI_PROC(void,SDL_CloseAudioDevice,(SDL_AudioDeviceID a),(a),)
SDL_DYNAPI_PROC(int,SDL_SetClipboardText,(const char *a),(a),return)
SDL_DYNAPI_PROC(char*,SDL_GetClipboardText,(void),(),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasClipboardText,(void),(),return)
SDL_DYNAPI_PROC(int,SDL_GetCPUCount,(void),(),return)
SDL_DYNAPI_PROC(int,SDL_GetCPUCacheLineSize,(void),(),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasRDTSC,(void),(),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasAltiVec,(void),(),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasMMX,(void),(),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_Has3DNow,(void),(),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasSSE,(void),(),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasSSE2,(void),(),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasSSE3,(void),(),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasSSE41,(void),(),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasSSE42,(void),(),return)
SDL_DYNAPI_PROC(int,SDL_GetSystemRAM,(void),(),return)
SDL_DYNAPI_PROC(const char*,SDL_GetError,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_ClearError,(void),(),)
SDL_DYNAPI_PROC(int,SDL_Error,(SDL_errorcode a),(a),return)
SDL_DYNAPI_PROC(void,SDL_PumpEvents,(void),(),)
SDL_DYNAPI_PROC(int,SDL_PeepEvents,(SDL_Event *a, int b, SDL_eventaction c, Uint32 d, Uint32 e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasEvent,(Uint32 a),(a),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasEvents,(Uint32 a, Uint32 b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_FlushEvent,(Uint32 a),(a),)
SDL_DYNAPI_PROC(void,SDL_FlushEvents,(Uint32 a, Uint32 b),(a,b),)
SDL_DYNAPI_PROC(int,SDL_PollEvent,(SDL_Event *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_WaitEvent,(SDL_Event *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_WaitEventTimeout,(SDL_Event *a, int b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_PushEvent,(SDL_Event *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_SetEventFilter,(SDL_EventFilter a, void *b),(a,b),)
SDL_DYNAPI_PROC(SDL_bool,SDL_GetEventFilter,(SDL_EventFilter *a, void **b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_AddEventWatch,(SDL_EventFilter a, void *b),(a,b),)
SDL_DYNAPI_PROC(void,SDL_DelEventWatch,(SDL_EventFilter a, void *b),(a,b),)
SDL_DYNAPI_PROC(void,SDL_FilterEvents,(SDL_EventFilter a, void *b),(a,b),)
SDL_DYNAPI_PROC(Uint8,SDL_EventState,(Uint32 a, int b),(a,b),return)
SDL_DYNAPI_PROC(Uint32,SDL_RegisterEvents,(int a),(a),return)
SDL_DYNAPI_PROC(char*,SDL_GetBasePath,(void),(),return)
SDL_DYNAPI_PROC(char*,SDL_GetPrefPath,(const char *a, const char *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GameControllerAddMapping,(const char *a),(a),return)
SDL_DYNAPI_PROC(char*,SDL_GameControllerMappingForGUID,(SDL_JoystickGUID a),(a),return)
SDL_DYNAPI_PROC(char*,SDL_GameControllerMapping,(SDL_GameController *a),(a),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_IsGameController,(int a),(a),return)
SDL_DYNAPI_PROC(const char*,SDL_GameControllerNameForIndex,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_GameController*,SDL_GameControllerOpen,(int a),(a),return)
SDL_DYNAPI_PROC(const char*,SDL_GameControllerName,(SDL_GameController *a),(a),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_GameControllerGetAttached,(SDL_GameController *a),(a),return)
SDL_DYNAPI_PROC(SDL_Joystick*,SDL_GameControllerGetJoystick,(SDL_GameController *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GameControllerEventState,(int a),(a),return)
SDL_DYNAPI_PROC(void,SDL_GameControllerUpdate,(void),(),)
SDL_DYNAPI_PROC(SDL_GameControllerAxis,SDL_GameControllerGetAxisFromString,(const char *a),(a),return)
SDL_DYNAPI_PROC(const char*,SDL_GameControllerGetStringForAxis,(SDL_GameControllerAxis a),(a),return)
SDL_DYNAPI_PROC(SDL_GameControllerButtonBind,SDL_GameControllerGetBindForAxis,(SDL_GameController *a, SDL_GameControllerAxis b),(a,b),return)
SDL_DYNAPI_PROC(Sint16,SDL_GameControllerGetAxis,(SDL_GameController *a, SDL_GameControllerAxis b),(a,b),return)
SDL_DYNAPI_PROC(SDL_GameControllerButton,SDL_GameControllerGetButtonFromString,(const char *a),(a),return)
SDL_DYNAPI_PROC(const char*,SDL_GameControllerGetStringForButton,(SDL_GameControllerButton a),(a),return)
SDL_DYNAPI_PROC(SDL_GameControllerButtonBind,SDL_GameControllerGetBindForButton,(SDL_GameController *a, SDL_GameControllerButton b),(a,b),return)
SDL_DYNAPI_PROC(Uint8,SDL_GameControllerGetButton,(SDL_GameController *a, SDL_GameControllerButton b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_GameControllerClose,(SDL_GameController *a),(a),)
SDL_DYNAPI_PROC(int,SDL_RecordGesture,(SDL_TouchID a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SaveAllDollarTemplates,(SDL_RWops *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SaveDollarTemplate,(SDL_GestureID a, SDL_RWops *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_LoadDollarTemplates,(SDL_TouchID a, SDL_RWops *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_NumHaptics,(void),(),return)
SDL_DYNAPI_PROC(const char*,SDL_HapticName,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_Haptic*,SDL_HapticOpen,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_HapticOpened,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_HapticIndex,(SDL_Haptic *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_MouseIsHaptic,(void),(),return)
SDL_DYNAPI_PROC(SDL_Haptic*,SDL_HapticOpenFromMouse,(void),(),return)
SDL_DYNAPI_PROC(int,SDL_JoystickIsHaptic,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(SDL_Haptic*,SDL_HapticOpenFromJoystick,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_HapticClose,(SDL_Haptic *a),(a),)
SDL_DYNAPI_PROC(int,SDL_HapticNumEffects,(SDL_Haptic *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_HapticNumEffectsPlaying,(SDL_Haptic *a),(a),return)
SDL_DYNAPI_PROC(unsigned int,SDL_HapticQuery,(SDL_Haptic *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_HapticNumAxes,(SDL_Haptic *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_HapticEffectSupported,(SDL_Haptic *a, SDL_HapticEffect *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_HapticNewEffect,(SDL_Haptic *a, SDL_HapticEffect *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_HapticUpdateEffect,(SDL_Haptic *a, int b, SDL_HapticEffect *c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_HapticRunEffect,(SDL_Haptic *a, int b, Uint32 c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_HapticStopEffect,(SDL_Haptic *a, int b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_HapticDestroyEffect,(SDL_Haptic *a, int b),(a,b),)
SDL_DYNAPI_PROC(int,SDL_HapticGetEffectStatus,(SDL_Haptic *a, int b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_HapticSetGain,(SDL_Haptic *a, int b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_HapticSetAutocenter,(SDL_Haptic *a, int b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_HapticPause,(SDL_Haptic *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_HapticUnpause,(SDL_Haptic *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_HapticStopAll,(SDL_Haptic *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_HapticRumbleSupported,(SDL_Haptic *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_HapticRumbleInit,(SDL_Haptic *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_HapticRumblePlay,(SDL_Haptic *a, float b, Uint32 c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_HapticRumbleStop,(SDL_Haptic *a),(a),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_SetHintWithPriority,(const char *a, const char *b, SDL_HintPriority c),(a,b,c),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_SetHint,(const char *a, const char *b),(a,b),return)
SDL_DYNAPI_PROC(const char*,SDL_GetHint,(const char *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_AddHintCallback,(const char *a, SDL_HintCallback b, void *c),(a,b,c),)
SDL_DYNAPI_PROC(void,SDL_DelHintCallback,(const char *a, SDL_HintCallback b, void *c),(a,b,c),)
SDL_DYNAPI_PROC(void,SDL_ClearHints,(void),(),)
SDL_DYNAPI_PROC(int,SDL_NumJoysticks,(void),(),return)
SDL_DYNAPI_PROC(const char*,SDL_JoystickNameForIndex,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_Joystick*,SDL_JoystickOpen,(int a),(a),return)
SDL_DYNAPI_PROC(const char*,SDL_JoystickName,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(SDL_JoystickGUID,SDL_JoystickGetDeviceGUID,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_JoystickGUID,SDL_JoystickGetGUID,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_JoystickGetGUIDString,(SDL_JoystickGUID a, char *b, int c),(a,b,c),)
SDL_DYNAPI_PROC(SDL_JoystickGUID,SDL_JoystickGetGUIDFromString,(const char *a),(a),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_JoystickGetAttached,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(SDL_JoystickID,SDL_JoystickInstanceID,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_JoystickNumAxes,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_JoystickNumBalls,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_JoystickNumHats,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_JoystickNumButtons,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_JoystickUpdate,(void),(),)
SDL_DYNAPI_PROC(int,SDL_JoystickEventState,(int a),(a),return)
SDL_DYNAPI_PROC(Sint16,SDL_JoystickGetAxis,(SDL_Joystick *a, int b),(a,b),return)
SDL_DYNAPI_PROC(Uint8,SDL_JoystickGetHat,(SDL_Joystick *a, int b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_JoystickGetBall,(SDL_Joystick *a, int b, int *c, int *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(Uint8,SDL_JoystickGetButton,(SDL_Joystick *a, int b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_JoystickClose,(SDL_Joystick *a),(a),)
SDL_DYNAPI_PROC(SDL_Window*,SDL_GetKeyboardFocus,(void),(),return)
SDL_DYNAPI_PROC(const Uint8*,SDL_GetKeyboardState,(int *a),(a),return)
SDL_DYNAPI_PROC(SDL_Keymod,SDL_GetModState,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_SetModState,(SDL_Keymod a),(a),)
SDL_DYNAPI_PROC(SDL_Keycode,SDL_GetKeyFromScancode,(SDL_Scancode a),(a),return)
SDL_DYNAPI_PROC(SDL_Scancode,SDL_GetScancodeFromKey,(SDL_Keycode a),(a),return)
SDL_DYNAPI_PROC(const char*,SDL_GetScancodeName,(SDL_Scancode a),(a),return)
SDL_DYNAPI_PROC(SDL_Scancode,SDL_GetScancodeFromName,(const char *a),(a),return)
SDL_DYNAPI_PROC(const char*,SDL_GetKeyName,(SDL_Keycode a),(a),return)
SDL_DYNAPI_PROC(SDL_Keycode,SDL_GetKeyFromName,(const char *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_StartTextInput,(void),(),)
SDL_DYNAPI_PROC(SDL_bool,SDL_IsTextInputActive,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_StopTextInput,(void),(),)
SDL_DYNAPI_PROC(void,SDL_SetTextInputRect,(SDL_Rect *a),(a),)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasScreenKeyboardSupport,(void),(),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_IsScreenKeyboardShown,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(void*,SDL_LoadObject,(const char *a),(a),return)
SDL_DYNAPI_PROC(void*,SDL_LoadFunction,(void *a, const char *b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_UnloadObject,(void *a),(a),)
SDL_DYNAPI_PROC(void,SDL_LogSetAllPriority,(SDL_LogPriority a),(a),)
SDL_DYNAPI_PROC(void,SDL_LogSetPriority,(int a, SDL_LogPriority b),(a,b),)
SDL_DYNAPI_PROC(SDL_LogPriority,SDL_LogGetPriority,(int a),(a),return)
SDL_DYNAPI_PROC(void,SDL_LogResetPriorities,(void),(),)
SDL_DYNAPI_PROC(void,SDL_LogMessageV,(int a, SDL_LogPriority b, const char *c, va_list d),(a,b,c,d),)
SDL_DYNAPI_PROC(void,SDL_LogGetOutputFunction,(SDL_LogOutputFunction *a, void **b),(a,b),)
SDL_DYNAPI_PROC(void,SDL_LogSetOutputFunction,(SDL_LogOutputFunction a, void *b),(a,b),)
SDL_DYNAPI_PROC(void,SDL_SetMainReady,(void),(),)
SDL_DYNAPI_PROC(int,SDL_ShowMessageBox,(const SDL_MessageBoxData *a, int *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_ShowSimpleMessageBox,(Uint32 a, const char *b, const char *c, SDL_Window *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(SDL_Window*,SDL_GetMouseFocus,(void),(),return)
SDL_DYNAPI_PROC(Uint32,SDL_GetMouseState,(int *a, int *b),(a,b),return)
SDL_DYNAPI_PROC(Uint32,SDL_GetRelativeMouseState,(int *a, int *b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_WarpMouseInWindow,(SDL_Window *a, int b, int c),(a,b,c),)
SDL_DYNAPI_PROC(int,SDL_SetRelativeMouseMode,(SDL_bool a),(a),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_GetRelativeMouseMode,(void),(),return)
SDL_DYNAPI_PROC(SDL_Cursor*,SDL_CreateCursor,(const Uint8 *a, const Uint8 *b, int c, int d, int e, int f),(a,b,c,d,e,f),return)
SDL_DYNAPI_PROC(SDL_Cursor*,SDL_CreateColorCursor,(SDL_Surface *a, int b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(SDL_Cursor*,SDL_CreateSystemCursor,(SDL_SystemCursor a),(a),return)
SDL_DYNAPI_PROC(void,SDL_SetCursor,(SDL_Cursor *a),(a),)
SDL_DYNAPI_PROC(SDL_Cursor*,SDL_GetCursor,(void),(),return)
SDL_DYNAPI_PROC(SDL_Cursor*,SDL_GetDefaultCursor,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_FreeCursor,(SDL_Cursor *a),(a),)
SDL_DYNAPI_PROC(int,SDL_ShowCursor,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_mutex*,SDL_CreateMutex,(void),(),return)
SDL_DYNAPI_PROC(int,SDL_LockMutex,(SDL_mutex *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_TryLockMutex,(SDL_mutex *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_UnlockMutex,(SDL_mutex *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_DestroyMutex,(SDL_mutex *a),(a),)
SDL_DYNAPI_PROC(SDL_sem*,SDL_CreateSemaphore,(Uint32 a),(a),return)
SDL_DYNAPI_PROC(void,SDL_DestroySemaphore,(SDL_sem *a),(a),)
SDL_DYNAPI_PROC(int,SDL_SemWait,(SDL_sem *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SemTryWait,(SDL_sem *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SemWaitTimeout,(SDL_sem *a, Uint32 b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_SemPost,(SDL_sem *a),(a),return)
SDL_DYNAPI_PROC(Uint32,SDL_SemValue,(SDL_sem *a),(a),return)
SDL_DYNAPI_PROC(SDL_cond*,SDL_CreateCond,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_DestroyCond,(SDL_cond *a),(a),)
SDL_DYNAPI_PROC(int,SDL_CondSignal,(SDL_cond *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_CondBroadcast,(SDL_cond *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_CondWait,(SDL_cond *a, SDL_mutex *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_CondWaitTimeout,(SDL_cond *a, SDL_mutex *b, Uint32 c),(a,b,c),return)
SDL_DYNAPI_PROC(const char*,SDL_GetPixelFormatName,(Uint32 a),(a),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_PixelFormatEnumToMasks,(Uint32 a, int *b, Uint32 *c, Uint32 *d, Uint32 *e, Uint32 *f),(a,b,c,d,e,f),return)
SDL_DYNAPI_PROC(Uint32,SDL_MasksToPixelFormatEnum,(int a, Uint32 b, Uint32 c, Uint32 d, Uint32 e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(SDL_PixelFormat*,SDL_AllocFormat,(Uint32 a),(a),return)
SDL_DYNAPI_PROC(void,SDL_FreeFormat,(SDL_PixelFormat *a),(a),)
SDL_DYNAPI_PROC(SDL_Palette*,SDL_AllocPalette,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SetPixelFormatPalette,(SDL_PixelFormat *a, SDL_Palette *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_SetPaletteColors,(SDL_Palette *a, const SDL_Color *b, int c, int d),(a,b,c,d),return)
SDL_DYNAPI_PROC(void,SDL_FreePalette,(SDL_Palette *a),(a),)
SDL_DYNAPI_PROC(Uint32,SDL_MapRGB,(const SDL_PixelFormat *a, Uint8 b, Uint8 c, Uint8 d),(a,b,c,d),return)
SDL_DYNAPI_PROC(Uint32,SDL_MapRGBA,(const SDL_PixelFormat *a, Uint8 b, Uint8 c, Uint8 d, Uint8 e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(void,SDL_GetRGB,(Uint32 a, const SDL_PixelFormat *b, Uint8 *c, Uint8 *d, Uint8 *e),(a,b,c,d,e),)
SDL_DYNAPI_PROC(void,SDL_GetRGBA,(Uint32 a, const SDL_PixelFormat *b, Uint8 *c, Uint8 *d, Uint8 *e, Uint8 *f),(a,b,c,d,e,f),)
SDL_DYNAPI_PROC(void,SDL_CalculateGammaRamp,(float a, Uint16 *b),(a,b),)
SDL_DYNAPI_PROC(const char*,SDL_GetPlatform,(void),(),return)
SDL_DYNAPI_PROC(SDL_PowerState,SDL_GetPowerInfo,(int *a, int *b),(a,b),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasIntersection,(const SDL_Rect *a, const SDL_Rect *b),(a,b),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_IntersectRect,(const SDL_Rect *a, const SDL_Rect *b, SDL_Rect *c),(a,b,c),return)
SDL_DYNAPI_PROC(void,SDL_UnionRect,(const SDL_Rect *a, const SDL_Rect *b, SDL_Rect *c),(a,b,c),)
SDL_DYNAPI_PROC(SDL_bool,SDL_EnclosePoints,(const SDL_Point *a, int b, const SDL_Rect *c, SDL_Rect *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_IntersectRectAndLine,(const SDL_Rect *a, int *b, int *c, int *d, int *e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(int,SDL_GetNumRenderDrivers,(void),(),return)
SDL_DYNAPI_PROC(int,SDL_GetRenderDriverInfo,(int a, SDL_RendererInfo *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_CreateWindowAndRenderer,(int a, int b, Uint32 c, SDL_Window **d, SDL_Renderer **e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(SDL_Renderer*,SDL_CreateRenderer,(SDL_Window *a, int b, Uint32 c),(a,b,c),return)
SDL_DYNAPI_PROC(SDL_Renderer*,SDL_CreateSoftwareRenderer,(SDL_Surface *a),(a),return)
SDL_DYNAPI_PROC(SDL_Renderer*,SDL_GetRenderer,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GetRendererInfo,(SDL_Renderer *a, SDL_RendererInfo *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetRendererOutputSize,(SDL_Renderer *a, int *b, int *c),(a,b,c),return)
SDL_DYNAPI_PROC(SDL_Texture*,SDL_CreateTexture,(SDL_Renderer *a, Uint32 b, int c, int d, int e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(SDL_Texture*,SDL_CreateTextureFromSurface,(SDL_Renderer *a, SDL_Surface *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_QueryTexture,(SDL_Texture *a, Uint32 *b, int *c, int *d, int *e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(int,SDL_SetTextureColorMod,(SDL_Texture *a, Uint8 b, Uint8 c, Uint8 d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_GetTextureColorMod,(SDL_Texture *a, Uint8 *b, Uint8 *c, Uint8 *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_SetTextureAlphaMod,(SDL_Texture *a, Uint8 b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetTextureAlphaMod,(SDL_Texture *a, Uint8 *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_SetTextureBlendMode,(SDL_Texture *a, SDL_BlendMode b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetTextureBlendMode,(SDL_Texture *a, SDL_BlendMode *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_UpdateTexture,(SDL_Texture *a, const SDL_Rect *b, const void *c, int d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_UpdateYUVTexture,(SDL_Texture *a, const SDL_Rect *b, const Uint8 *c, int d, const Uint8 *e, int f, const Uint8 *g, int h),(a,b,c,d,e,f,g,h),return)
SDL_DYNAPI_PROC(int,SDL_LockTexture,(SDL_Texture *a, const SDL_Rect *b, void **c, int *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(void,SDL_UnlockTexture,(SDL_Texture *a),(a),)
SDL_DYNAPI_PROC(SDL_bool,SDL_RenderTargetSupported,(SDL_Renderer *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SetRenderTarget,(SDL_Renderer *a, SDL_Texture *b),(a,b),return)
SDL_DYNAPI_PROC(SDL_Texture*,SDL_GetRenderTarget,(SDL_Renderer *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_RenderSetLogicalSize,(SDL_Renderer *a, int b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(void,SDL_RenderGetLogicalSize,(SDL_Renderer *a, int *b, int *c),(a,b,c),)
SDL_DYNAPI_PROC(int,SDL_RenderSetViewport,(SDL_Renderer *a, const SDL_Rect *b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_RenderGetViewport,(SDL_Renderer *a, SDL_Rect *b),(a,b),)
SDL_DYNAPI_PROC(int,SDL_RenderSetClipRect,(SDL_Renderer *a, const SDL_Rect *b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_RenderGetClipRect,(SDL_Renderer *a, SDL_Rect *b),(a,b),)
SDL_DYNAPI_PROC(int,SDL_RenderSetScale,(SDL_Renderer *a, float b, float c),(a,b,c),return)
SDL_DYNAPI_PROC(void,SDL_RenderGetScale,(SDL_Renderer *a, float *b, float *c),(a,b,c),)
SDL_DYNAPI_PROC(int,SDL_SetRenderDrawColor,(SDL_Renderer *a, Uint8 b, Uint8 c, Uint8 d, Uint8 e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(int,SDL_GetRenderDrawColor,(SDL_Renderer *a, Uint8 *b, Uint8 *c, Uint8 *d, Uint8 *e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(int,SDL_SetRenderDrawBlendMode,(SDL_Renderer *a, SDL_BlendMode b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetRenderDrawBlendMode,(SDL_Renderer *a, SDL_BlendMode *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_RenderClear,(SDL_Renderer *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_RenderDrawPoint,(SDL_Renderer *a, int b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_RenderDrawPoints,(SDL_Renderer *a, const SDL_Point *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_RenderDrawLine,(SDL_Renderer *a, int b, int c, int d, int e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(int,SDL_RenderDrawLines,(SDL_Renderer *a, const SDL_Point *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_RenderDrawRect,(SDL_Renderer *a, const SDL_Rect *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_RenderDrawRects,(SDL_Renderer *a, const SDL_Rect *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_RenderFillRect,(SDL_Renderer *a, const SDL_Rect *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_RenderFillRects,(SDL_Renderer *a, const SDL_Rect *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_RenderCopy,(SDL_Renderer *a, SDL_Texture *b, const SDL_Rect *c, const SDL_Rect *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_RenderCopyEx,(SDL_Renderer *a, SDL_Texture *b, const SDL_Rect *c, const SDL_Rect *d, const double e, const SDL_Point *f, const SDL_RendererFlip g),(a,b,c,d,e,f,g),return)
SDL_DYNAPI_PROC(int,SDL_RenderReadPixels,(SDL_Renderer *a, const SDL_Rect *b, Uint32 c, void *d, int e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(void,SDL_RenderPresent,(SDL_Renderer *a),(a),)
SDL_DYNAPI_PROC(void,SDL_DestroyTexture,(SDL_Texture *a),(a),)
SDL_DYNAPI_PROC(void,SDL_DestroyRenderer,(SDL_Renderer *a),(a),)
SDL_DYNAPI_PROC(int,SDL_GL_BindTexture,(SDL_Texture *a, float *b, float *c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_GL_UnbindTexture,(SDL_Texture *a),(a),return)
SDL_DYNAPI_PROC(SDL_RWops*,SDL_RWFromFile,(const char *a, const char *b),(a,b),return)
SDL_DYNAPI_PROC(SDL_RWops*,SDL_RWFromMem,(void *a, int b),(a,b),return)
SDL_DYNAPI_PROC(SDL_RWops*,SDL_RWFromConstMem,(const void *a, int b),(a,b),return)
SDL_DYNAPI_PROC(SDL_RWops*,SDL_AllocRW,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_FreeRW,(SDL_RWops *a),(a),)
SDL_DYNAPI_PROC(Uint8,SDL_ReadU8,(SDL_RWops *a),(a),return)
SDL_DYNAPI_PROC(Uint16,SDL_ReadLE16,(SDL_RWops *a),(a),return)
SDL_DYNAPI_PROC(Uint16,SDL_ReadBE16,(SDL_RWops *a),(a),return)
SDL_DYNAPI_PROC(Uint32,SDL_ReadLE32,(SDL_RWops *a),(a),return)
SDL_DYNAPI_PROC(Uint32,SDL_ReadBE32,(SDL_RWops *a),(a),return)
SDL_DYNAPI_PROC(Uint64,SDL_ReadLE64,(SDL_RWops *a),(a),return)
SDL_DYNAPI_PROC(Uint64,SDL_ReadBE64,(SDL_RWops *a),(a),return)
SDL_DYNAPI_PROC(size_t,SDL_WriteU8,(SDL_RWops *a, Uint8 b),(a,b),return)
SDL_DYNAPI_PROC(size_t,SDL_WriteLE16,(SDL_RWops *a, Uint16 b),(a,b),return)
SDL_DYNAPI_PROC(size_t,SDL_WriteBE16,(SDL_RWops *a, Uint16 b),(a,b),return)
SDL_DYNAPI_PROC(size_t,SDL_WriteLE32,(SDL_RWops *a, Uint32 b),(a,b),return)
SDL_DYNAPI_PROC(size_t,SDL_WriteBE32,(SDL_RWops *a, Uint32 b),(a,b),return)
SDL_DYNAPI_PROC(size_t,SDL_WriteLE64,(SDL_RWops *a, Uint64 b),(a,b),return)
SDL_DYNAPI_PROC(size_t,SDL_WriteBE64,(SDL_RWops *a, Uint64 b),(a,b),return)
SDL_DYNAPI_PROC(SDL_Window*,SDL_CreateShapedWindow,(const char *a, unsigned int b, unsigned int c, unsigned int d, unsigned int e, Uint32 f),(a,b,c,d,e,f),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_IsShapedWindow,(const SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SetWindowShape,(SDL_Window *a, SDL_Surface *b, SDL_WindowShapeMode *c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_GetShapedWindowMode,(SDL_Window *a, SDL_WindowShapeMode *b),(a,b),return)
SDL_DYNAPI_PROC(void*,SDL_malloc,(size_t a),(a),return)
SDL_DYNAPI_PROC(void*,SDL_calloc,(size_t a, size_t b),(a,b),return)
SDL_DYNAPI_PROC(void*,SDL_realloc,(void *a, size_t b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_free,(void *a),(a),)
SDL_DYNAPI_PROC(char*,SDL_getenv,(const char *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_setenv,(const char *a, const char *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(void,SDL_qsort,(void *a, size_t b, size_t c, int (*d)(const void *, const void *)),(a,b,c,d),)
SDL_DYNAPI_PROC(int,SDL_abs,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_isdigit,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_isspace,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_toupper,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_tolower,(int a),(a),return)
SDL_DYNAPI_PROC(void*,SDL_memset,(SDL_OUT_BYTECAP(c) void *a, int b, size_t c),(a,b,c),return)
SDL_DYNAPI_PROC(void*,SDL_memcpy,(SDL_OUT_BYTECAP(c) void *a, SDL_IN_BYTECAP(c) const void *b, size_t c),(a,b,c),return)
SDL_DYNAPI_PROC(void*,SDL_memmove,(SDL_OUT_BYTECAP(c) void *a, SDL_IN_BYTECAP(c) const void *b, size_t c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_memcmp,(const void *a, const void *b, size_t c),(a,b,c),return)
SDL_DYNAPI_PROC(size_t,SDL_wcslen,(const wchar_t *a),(a),return)
SDL_DYNAPI_PROC(size_t,SDL_wcslcpy,(SDL_OUT_Z_CAP(c) wchar_t *a, const wchar_t *b, size_t c),(a,b,c),return)
SDL_DYNAPI_PROC(size_t,SDL_wcslcat,(SDL_INOUT_Z_CAP(c) wchar_t *a, const wchar_t *b, size_t c),(a,b,c),return)
SDL_DYNAPI_PROC(size_t,SDL_strlen,(const char *a),(a),return)
SDL_DYNAPI_PROC(size_t,SDL_strlcpy,(SDL_OUT_Z_CAP(c) char *a, const char *b, size_t c),(a,b,c),return)
SDL_DYNAPI_PROC(size_t,SDL_utf8strlcpy,(SDL_OUT_Z_CAP(c) char *a, const char *b, size_t c),(a,b,c),return)
SDL_DYNAPI_PROC(size_t,SDL_strlcat,(SDL_INOUT_Z_CAP(c) char *a, const char *b, size_t c),(a,b,c),return)
SDL_DYNAPI_PROC(char*,SDL_strdup,(const char *a),(a),return)
SDL_DYNAPI_PROC(char*,SDL_strrev,(char *a),(a),return)
SDL_DYNAPI_PROC(char*,SDL_strupr,(char *a),(a),return)
SDL_DYNAPI_PROC(char*,SDL_strlwr,(char *a),(a),return)
SDL_DYNAPI_PROC(char*,SDL_strchr,(const char *a, int b),(a,b),return)
SDL_DYNAPI_PROC(char*,SDL_strrchr,(const char *a, int b),(a,b),return)
SDL_DYNAPI_PROC(char*,SDL_strstr,(const char *a, const char *b),(a,b),return)
SDL_DYNAPI_PROC(char*,SDL_itoa,(int a, char *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(char*,SDL_uitoa,(unsigned int a, char *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(char*,SDL_ltoa,(long a, char *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(char*,SDL_ultoa,(unsigned long a, char *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(char*,SDL_lltoa,(Sint64 a, char *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(char*,SDL_ulltoa,(Uint64 a, char *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_atoi,(const char *a),(a),return)
SDL_DYNAPI_PROC(double,SDL_atof,(const char *a),(a),return)
SDL_DYNAPI_PROC(long,SDL_strtol,(const char *a, char **b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(unsigned long,SDL_strtoul,(const char *a, char **b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(Sint64,SDL_strtoll,(const char *a, char **b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(Uint64,SDL_strtoull,(const char *a, char **b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(double,SDL_strtod,(const char *a, char **b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_strcmp,(const char *a, const char *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_strncmp,(const char *a, const char *b, size_t c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_strcasecmp,(const char *a, const char *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_strncasecmp,(const char *a, const char *b, size_t c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_vsnprintf,(SDL_OUT_Z_CAP(b) char *a, size_t b, const char *c, va_list d),(a,b,c,d),return)
SDL_DYNAPI_PROC(double,SDL_acos,(double a),(a),return)
SDL_DYNAPI_PROC(double,SDL_asin,(double a),(a),return)
SDL_DYNAPI_PROC(double,SDL_atan,(double a),(a),return)
SDL_DYNAPI_PROC(double,SDL_atan2,(double a, double b),(a,b),return)
SDL_DYNAPI_PROC(double,SDL_ceil,(double a),(a),return)
SDL_DYNAPI_PROC(double,SDL_copysign,(double a, double b),(a,b),return)
SDL_DYNAPI_PROC(double,SDL_cos,(double a),(a),return)
SDL_DYNAPI_PROC(float,SDL_cosf,(float a),(a),return)
SDL_DYNAPI_PROC(double,SDL_fabs,(double a),(a),return)
SDL_DYNAPI_PROC(double,SDL_floor,(double a),(a),return)
SDL_DYNAPI_PROC(double,SDL_log,(double a),(a),return)
SDL_DYNAPI_PROC(double,SDL_pow,(double a, double b),(a,b),return)
SDL_DYNAPI_PROC(double,SDL_scalbn,(double a, int b),(a,b),return)
SDL_DYNAPI_PROC(double,SDL_sin,(double a),(a),return)
SDL_DYNAPI_PROC(float,SDL_sinf,(float a),(a),return)
SDL_DYNAPI_PROC(double,SDL_sqrt,(double a),(a),return)
SDL_DYNAPI_PROC(SDL_iconv_t,SDL_iconv_open,(const char *a, const char *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_iconv_close,(SDL_iconv_t a),(a),return)
SDL_DYNAPI_PROC(size_t,SDL_iconv,(SDL_iconv_t a, const char **b, size_t *c, char **d, size_t *e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(char*,SDL_iconv_string,(const char *a, const char *b, const char *c, size_t d),(a,b,c,d),return)
SDL_DYNAPI_PROC(SDL_Surface*,SDL_CreateRGBSurface,(Uint32 a, int b, int c, int d, Uint32 e, Uint32 f, Uint32 g, Uint32 h),(a,b,c,d,e,f,g,h),return)
SDL_DYNAPI_PROC(SDL_Surface*,SDL_CreateRGBSurfaceFrom,(void *a, int b, int c, int d, int e, Uint32 f, Uint32 g, Uint32 h, Uint32 i),(a,b,c,d,e,f,g,h,i),return)
SDL_DYNAPI_PROC(void,SDL_FreeSurface,(SDL_Surface *a),(a),)
SDL_DYNAPI_PROC(int,SDL_SetSurfacePalette,(SDL_Surface *a, SDL_Palette *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_LockSurface,(SDL_Surface *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_UnlockSurface,(SDL_Surface *a),(a),)
SDL_DYNAPI_PROC(SDL_Surface*,SDL_LoadBMP_RW,(SDL_RWops *a, int b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_SaveBMP_RW,(SDL_Surface *a, SDL_RWops *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_SetSurfaceRLE,(SDL_Surface *a, int b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_SetColorKey,(SDL_Surface *a, int b, Uint32 c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_GetColorKey,(SDL_Surface *a, Uint32 *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_SetSurfaceColorMod,(SDL_Surface *a, Uint8 b, Uint8 c, Uint8 d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_GetSurfaceColorMod,(SDL_Surface *a, Uint8 *b, Uint8 *c, Uint8 *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_SetSurfaceAlphaMod,(SDL_Surface *a, Uint8 b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetSurfaceAlphaMod,(SDL_Surface *a, Uint8 *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_SetSurfaceBlendMode,(SDL_Surface *a, SDL_BlendMode b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetSurfaceBlendMode,(SDL_Surface *a, SDL_BlendMode *b),(a,b),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_SetClipRect,(SDL_Surface *a, const SDL_Rect *b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_GetClipRect,(SDL_Surface *a, SDL_Rect *b),(a,b),)
SDL_DYNAPI_PROC(SDL_Surface*,SDL_ConvertSurface,(SDL_Surface *a, const SDL_PixelFormat *b, Uint32 c),(a,b,c),return)
SDL_DYNAPI_PROC(SDL_Surface*,SDL_ConvertSurfaceFormat,(SDL_Surface *a, Uint32 b, Uint32 c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_ConvertPixels,(int a, int b, Uint32 c, const void *d, int e, Uint32 f, void *g, int h),(a,b,c,d,e,f,g,h),return)
SDL_DYNAPI_PROC(int,SDL_FillRect,(SDL_Surface *a, const SDL_Rect *b, Uint32 c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_FillRects,(SDL_Surface *a, const SDL_Rect *b, int c, Uint32 d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_UpperBlit,(SDL_Surface *a, const SDL_Rect *b, SDL_Surface *c, SDL_Rect *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_LowerBlit,(SDL_Surface *a, SDL_Rect *b, SDL_Surface *c, SDL_Rect *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_SoftStretch,(SDL_Surface *a, const SDL_Rect *b, SDL_Surface *c, const SDL_Rect *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_UpperBlitScaled,(SDL_Surface *a, const SDL_Rect *b, SDL_Surface *c, SDL_Rect *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_LowerBlitScaled,(SDL_Surface *a, SDL_Rect *b, SDL_Surface *c, SDL_Rect *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_GetWindowWMInfo,(SDL_Window *a, SDL_SysWMinfo *b),(a,b),return)
SDL_DYNAPI_PROC(const char*,SDL_GetThreadName,(SDL_Thread *a),(a),return)
SDL_DYNAPI_PROC(SDL_threadID,SDL_ThreadID,(void),(),return)
SDL_DYNAPI_PROC(SDL_threadID,SDL_GetThreadID,(SDL_Thread *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SetThreadPriority,(SDL_ThreadPriority a),(a),return)
SDL_DYNAPI_PROC(void,SDL_WaitThread,(SDL_Thread *a, int *b),(a,b),)
SDL_DYNAPI_PROC(void,SDL_DetachThread,(SDL_Thread *a),(a),)
SDL_DYNAPI_PROC(SDL_TLSID,SDL_TLSCreate,(void),(),return)
SDL_DYNAPI_PROC(void*,SDL_TLSGet,(SDL_TLSID a),(a),return)
SDL_DYNAPI_PROC(int,SDL_TLSSet,(SDL_TLSID a, const void *b, void (*c)(void*)),(a,b,c),return)
SDL_DYNAPI_PROC(Uint32,SDL_GetTicks,(void),(),return)
SDL_DYNAPI_PROC(Uint64,SDL_GetPerformanceCounter,(void),(),return)
SDL_DYNAPI_PROC(Uint64,SDL_GetPerformanceFrequency,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_Delay,(Uint32 a),(a),)
SDL_DYNAPI_PROC(SDL_TimerID,SDL_AddTimer,(Uint32 a, SDL_TimerCallback b, void *c),(a,b,c),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_RemoveTimer,(SDL_TimerID a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GetNumTouchDevices,(void),(),return)
SDL_DYNAPI_PROC(SDL_TouchID,SDL_GetTouchDevice,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GetNumTouchFingers,(SDL_TouchID a),(a),return)
SDL_DYNAPI_PROC(SDL_Finger*,SDL_GetTouchFinger,(SDL_TouchID a, int b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_GetVersion,(SDL_version *a),(a),)
SDL_DYNAPI_PROC(const char*,SDL_GetRevision,(void),(),return)
SDL_DYNAPI_PROC(int,SDL_GetRevisionNumber,(void),(),return)
SDL_DYNAPI_PROC(int,SDL_GetNumVideoDrivers,(void),(),return)
SDL_DYNAPI_PROC(const char*,SDL_GetVideoDriver,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_VideoInit,(const char *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_VideoQuit,(void),(),)
SDL_DYNAPI_PROC(const char*,SDL_GetCurrentVideoDriver,(void),(),return)
SDL_DYNAPI_PROC(int,SDL_GetNumVideoDisplays,(void),(),return)
SDL_DYNAPI_PROC(const char*,SDL_GetDisplayName,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GetDisplayBounds,(int a, SDL_Rect *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetNumDisplayModes,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GetDisplayMode,(int a, int b, SDL_DisplayMode *c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_GetDesktopDisplayMode,(int a, SDL_DisplayMode *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetCurrentDisplayMode,(int a, SDL_DisplayMode *b),(a,b),return)
SDL_DYNAPI_PROC(SDL_DisplayMode*,SDL_GetClosestDisplayMode,(int a, const SDL_DisplayMode *b, SDL_DisplayMode *c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_GetWindowDisplayIndex,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SetWindowDisplayMode,(SDL_Window *a, const SDL_DisplayMode *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetWindowDisplayMode,(SDL_Window *a, SDL_DisplayMode *b),(a,b),return)
SDL_DYNAPI_PROC(Uint32,SDL_GetWindowPixelFormat,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(SDL_Window*,SDL_CreateWindow,(const char *a, int b, int c, int d, int e, Uint32 f),(a,b,c,d,e,f),return)
SDL_DYNAPI_PROC(SDL_Window*,SDL_CreateWindowFrom,(const void *a),(a),return)
SDL_DYNAPI_PROC(Uint32,SDL_GetWindowID,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(SDL_Window*,SDL_GetWindowFromID,(Uint32 a),(a),return)
SDL_DYNAPI_PROC(Uint32,SDL_GetWindowFlags,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_SetWindowTitle,(SDL_Window *a, const char *b),(a,b),)
SDL_DYNAPI_PROC(const char*,SDL_GetWindowTitle,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_SetWindowIcon,(SDL_Window *a, SDL_Surface *b),(a,b),)
SDL_DYNAPI_PROC(void*,SDL_SetWindowData,(SDL_Window *a, const char *b, void *c),(a,b,c),return)
SDL_DYNAPI_PROC(void*,SDL_GetWindowData,(SDL_Window *a, const char *b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_SetWindowPosition,(SDL_Window *a, int b, int c),(a,b,c),)
SDL_DYNAPI_PROC(void,SDL_GetWindowPosition,(SDL_Window *a, int *b, int *c),(a,b,c),)
SDL_DYNAPI_PROC(void,SDL_SetWindowSize,(SDL_Window *a, int b, int c),(a,b,c),)
SDL_DYNAPI_PROC(void,SDL_GetWindowSize,(SDL_Window *a, int *b, int *c),(a,b,c),)
SDL_DYNAPI_PROC(void,SDL_SetWindowMinimumSize,(SDL_Window *a, int b, int c),(a,b,c),)
SDL_DYNAPI_PROC(void,SDL_GetWindowMinimumSize,(SDL_Window *a, int *b, int *c),(a,b,c),)
SDL_DYNAPI_PROC(void,SDL_SetWindowMaximumSize,(SDL_Window *a, int b, int c),(a,b,c),)
SDL_DYNAPI_PROC(void,SDL_GetWindowMaximumSize,(SDL_Window *a, int *b, int *c),(a,b,c),)
SDL_DYNAPI_PROC(void,SDL_SetWindowBordered,(SDL_Window *a, SDL_bool b),(a,b),)
SDL_DYNAPI_PROC(void,SDL_ShowWindow,(SDL_Window *a),(a),)
SDL_DYNAPI_PROC(void,SDL_HideWindow,(SDL_Window *a),(a),)
SDL_DYNAPI_PROC(void,SDL_RaiseWindow,(SDL_Window *a),(a),)
SDL_DYNAPI_PROC(void,SDL_MaximizeWindow,(SDL_Window *a),(a),)
SDL_DYNAPI_PROC(void,SDL_MinimizeWindow,(SDL_Window *a),(a),)
SDL_DYNAPI_PROC(void,SDL_RestoreWindow,(SDL_Window *a),(a),)
SDL_DYNAPI_PROC(int,SDL_SetWindowFullscreen,(SDL_Window *a, Uint32 b),(a,b),return)
SDL_DYNAPI_PROC(SDL_Surface*,SDL_GetWindowSurface,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_UpdateWindowSurface,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_UpdateWindowSurfaceRects,(SDL_Window *a, const SDL_Rect *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(void,SDL_SetWindowGrab,(SDL_Window *a, SDL_bool b),(a,b),)
SDL_DYNAPI_PROC(SDL_bool,SDL_GetWindowGrab,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SetWindowBrightness,(SDL_Window *a, float b),(a,b),return)
SDL_DYNAPI_PROC(float,SDL_GetWindowBrightness,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SetWindowGammaRamp,(SDL_Window *a, const Uint16 *b, const Uint16 *c, const Uint16 *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_GetWindowGammaRamp,(SDL_Window *a, Uint16 *b, Uint16 *c, Uint16 *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(void,SDL_DestroyWindow,(SDL_Window *a),(a),)
SDL_DYNAPI_PROC(SDL_bool,SDL_IsScreenSaverEnabled,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_EnableScreenSaver,(void),(),)
SDL_DYNAPI_PROC(void,SDL_DisableScreenSaver,(void),(),)
SDL_DYNAPI_PROC(int,SDL_GL_LoadLibrary,(const char *a),(a),return)
SDL_DYNAPI_PROC(void*,SDL_GL_GetProcAddress,(const char *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_GL_UnloadLibrary,(void),(),)
SDL_DYNAPI_PROC(SDL_bool,SDL_GL_ExtensionSupported,(const char *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GL_SetAttribute,(SDL_GLattr a, int b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GL_GetAttribute,(SDL_GLattr a, int *b),(a,b),return)
SDL_DYNAPI_PROC(SDL_GLContext,SDL_GL_CreateContext,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GL_MakeCurrent,(SDL_Window *a, SDL_GLContext b),(a,b),return)
SDL_DYNAPI_PROC(SDL_Window*,SDL_GL_GetCurrentWindow,(void),(),return)
SDL_DYNAPI_PROC(SDL_GLContext,SDL_GL_GetCurrentContext,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_GL_GetDrawableSize,(SDL_Window *a, int *b, int *c),(a,b,c),)
SDL_DYNAPI_PROC(int,SDL_GL_SetSwapInterval,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GL_GetSwapInterval,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_GL_SwapWindow,(SDL_Window *a),(a),)
SDL_DYNAPI_PROC(void,SDL_GL_DeleteContext,(SDL_GLContext a),(a),)
SDL_DYNAPI_PROC(int,SDL_vsscanf,(const char *a, const char *b, va_list c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_GameControllerAddMappingsFromRW,(SDL_RWops *a, int b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_GL_ResetAttributes,(void),(),)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasAVX,(void),(),return)
SDL_DYNAPI_PROC(SDL_AssertionHandler,SDL_GetDefaultAssertionHandler,(void),(),return)
SDL_DYNAPI_PROC(SDL_AssertionHandler,SDL_GetAssertionHandler,(void **a),(a),return)
#ifdef __WIN32__
SDL_DYNAPI_PROC(SDL_bool,SDL_DXGIGetOutputInfo,(int a,int *b, int *c),(a,b,c),return)
#endif
SDL_DYNAPI_PROC(SDL_bool,SDL_RenderIsClipEnabled,(SDL_Renderer *a),(a),return)
#ifdef __WINRT__
SDL_DYNAPI_PROC(int,SDL_WinRTRunApp,(int a, char **b, void *c),(a,b,c),return)
SDL_DYNAPI_PROC(const wchar_t*,SDL_WinRTGetFSPathUNICODE,(SDL_WinRT_Path a),(a),return)
SDL_DYNAPI_PROC(const char*,SDL_WinRTGetFSPathUTF8,(SDL_WinRT_Path a),(a),return)
#endif
SDL_DYNAPI_PROC(int,SDL_WarpMouseGlobal,(int a, int b),(a,b),return)
SDL_DYNAPI_PROC(float,SDL_sqrtf,(float a),(a),return)
SDL_DYNAPI_PROC(double,SDL_tan,(double a),(a),return)
SDL_DYNAPI_PROC(float,SDL_tanf,(float a),(a),return)
SDL_DYNAPI_PROC(int,SDL_CaptureMouse,(SDL_bool a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SetWindowHitTest,(SDL_Window *a, SDL_HitTest b, void *c),(a,b,c),return)
SDL_DYNAPI_PROC(Uint32,SDL_GetGlobalMouseState,(int *a, int *b),(a,b),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasAVX2,(void),(),return)
SDL_DYNAPI_PROC(int,SDL_QueueAudio,(SDL_AudioDeviceID a, const void *b, Uint32 c),(a,b,c),return)
SDL_DYNAPI_PROC(Uint32,SDL_GetQueuedAudioSize,(SDL_AudioDeviceID a),(a),return)
SDL_DYNAPI_PROC(void,SDL_ClearQueuedAudio,(SDL_AudioDeviceID a),(a),)
SDL_DYNAPI_PROC(SDL_Window*,SDL_GetGrabbedWindow,(void),(),return)
#ifdef __WIN32__
SDL_DYNAPI_PROC(void,SDL_SetWindowsMessageHook,(SDL_WindowsMessageHook a, void *b),(a,b),)
#endif
SDL_DYNAPI_PROC(int,SDL_GetDisplayDPI,(int a, float *b, float *c, float *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(SDL_JoystickPowerLevel,SDL_JoystickCurrentPowerLevel,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(SDL_GameController*,SDL_GameControllerFromInstanceID,(SDL_JoystickID a),(a),return)
SDL_DYNAPI_PROC(SDL_Joystick*,SDL_JoystickFromInstanceID,(SDL_JoystickID a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GetDisplayUsableBounds,(int a, SDL_Rect *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetWindowBordersSize,(SDL_Window *a, int *b, int *c, int *d, int *e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(int,SDL_SetWindowOpacity,(SDL_Window *a, float b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetWindowOpacity,(SDL_Window *a, float *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_SetWindowInputFocus,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SetWindowModalFor,(SDL_Window *a, SDL_Window *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_RenderSetIntegerScale,(SDL_Renderer *a, SDL_bool b),(a,b),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_RenderGetIntegerScale,(SDL_Renderer *a),(a),return)
SDL_DYNAPI_PROC(Uint32,SDL_DequeueAudio,(SDL_AudioDeviceID a, void *b, Uint32 c),(a,b,c),return)
SDL_DYNAPI_PROC(void,SDL_SetWindowResizable,(SDL_Window *a, SDL_bool b),(a,b),)
SDL_DYNAPI_PROC(SDL_Surface*,SDL_CreateRGBSurfaceWithFormat,(Uint32 a, int b, int c, int d, Uint32 e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(SDL_Surface*,SDL_CreateRGBSurfaceWithFormatFrom,(void *a, int b, int c, int d, int e, Uint32 f),(a,b,c,d,e,f),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_GetHintBoolean,(const char *a, SDL_bool b),(a,b),return)
SDL_DYNAPI_PROC(Uint16,SDL_JoystickGetDeviceVendor,(int a),(a),return)
SDL_DYNAPI_PROC(Uint16,SDL_JoystickGetDeviceProduct,(int a),(a),return)
SDL_DYNAPI_PROC(Uint16,SDL_JoystickGetDeviceProductVersion,(int a),(a),return)
SDL_DYNAPI_PROC(Uint16,SDL_JoystickGetVendor,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(Uint16,SDL_JoystickGetProduct,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(Uint16,SDL_JoystickGetProductVersion,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(Uint16,SDL_GameControllerGetVendor,(SDL_GameController *a),(a),return)
SDL_DYNAPI_PROC(Uint16,SDL_GameControllerGetProduct,(SDL_GameController *a),(a),return)
SDL_DYNAPI_PROC(Uint16,SDL_GameControllerGetProductVersion,(SDL_GameController *a),(a),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasNEON,(void),(),return)
SDL_DYNAPI_PROC(int,SDL_GameControllerNumMappings,(void),(),return)
SDL_DYNAPI_PROC(char*,SDL_GameControllerMappingForIndex,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_JoystickGetAxisInitialState,(SDL_Joystick *a, int b, Sint16 *c),(a,b,c),return)
SDL_DYNAPI_PROC(SDL_JoystickType,SDL_JoystickGetDeviceType,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_JoystickType,SDL_JoystickGetType,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_MemoryBarrierReleaseFunction,(void),(),)
SDL_DYNAPI_PROC(void,SDL_MemoryBarrierAcquireFunction,(void),(),)
SDL_DYNAPI_PROC(SDL_JoystickID,SDL_JoystickGetDeviceInstanceID,(int a),(a),return)
SDL_DYNAPI_PROC(size_t,SDL_utf8strlen,(const char *a),(a),return)
SDL_DYNAPI_PROC(void*,SDL_LoadFile_RW,(SDL_RWops *a, size_t *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_wcscmp,(const wchar_t *a, const wchar_t *b),(a,b),return)
SDL_DYNAPI_PROC(SDL_BlendMode,SDL_ComposeCustomBlendMode,(SDL_BlendFactor a, SDL_BlendFactor b, SDL_BlendOperation c, SDL_BlendFactor d, SDL_BlendFactor e, SDL_BlendOperation f),(a,b,c,d,e,f),return)
SDL_DYNAPI_PROC(SDL_Surface*,SDL_DuplicateSurface,(SDL_Surface *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_Vulkan_LoadLibrary,(const char *a),(a),return)
SDL_DYNAPI_PROC(void*,SDL_Vulkan_GetVkGetInstanceProcAddr,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_Vulkan_UnloadLibrary,(void),(),)
SDL_DYNAPI_PROC(SDL_bool,SDL_Vulkan_GetInstanceExtensions,(SDL_Window *a, unsigned int *b, const char **c),(a,b,c),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_Vulkan_CreateSurface,(SDL_Window *a, VkInstance b, VkSurfaceKHR *c),(a,b,c),return)
SDL_DYNAPI_PROC(void,SDL_Vulkan_GetDrawableSize,(SDL_Window *a, int *b, int *c),(a,b,c),)
SDL_DYNAPI_PROC(void,SDL_LockJoysticks,(void),(),)
SDL_DYNAPI_PROC(void,SDL_UnlockJoysticks,(void),(),)
SDL_DYNAPI_PROC(void,SDL_GetMemoryFunctions,(SDL_malloc_func *a, SDL_calloc_func *b, SDL_realloc_func *c, SDL_free_func *d),(a,b,c,d),)
SDL_DYNAPI_PROC(int,SDL_SetMemoryFunctions,(SDL_malloc_func a, SDL_calloc_func b, SDL_realloc_func c, SDL_free_func d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_GetNumAllocations,(void),(),return)
SDL_DYNAPI_PROC(SDL_AudioStream*,SDL_NewAudioStream,(const SDL_AudioFormat a, const Uint8 b, const int c, const SDL_AudioFormat d, const Uint8 e, const int f),(a,b,c,d,e,f),return)
SDL_DYNAPI_PROC(int,SDL_AudioStreamPut,(SDL_AudioStream *a, const void *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_AudioStreamGet,(SDL_AudioStream *a, void *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(void,SDL_AudioStreamClear,(SDL_AudioStream *a),(a),)
SDL_DYNAPI_PROC(int,SDL_AudioStreamAvailable,(SDL_AudioStream *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_FreeAudioStream,(SDL_AudioStream *a),(a),)
SDL_DYNAPI_PROC(int,SDL_AudioStreamFlush,(SDL_AudioStream *a),(a),return)
SDL_DYNAPI_PROC(float,SDL_acosf,(float a),(a),return)
SDL_DYNAPI_PROC(float,SDL_asinf,(float a),(a),return)
SDL_DYNAPI_PROC(float,SDL_atanf,(float a),(a),return)
SDL_DYNAPI_PROC(float,SDL_atan2f,(float a, float b),(a,b),return)
SDL_DYNAPI_PROC(float,SDL_ceilf,(float a),(a),return)
SDL_DYNAPI_PROC(float,SDL_copysignf,(float a, float b),(a,b),return)
SDL_DYNAPI_PROC(float,SDL_fabsf,(float a),(a),return)
SDL_DYNAPI_PROC(float,SDL_floorf,(float a),(a),return)
SDL_DYNAPI_PROC(float,SDL_logf,(float a),(a),return)
SDL_DYNAPI_PROC(float,SDL_powf,(float a, float b),(a,b),return)
SDL_DYNAPI_PROC(float,SDL_scalbnf,(float a, int b),(a,b),return)
SDL_DYNAPI_PROC(double,SDL_fmod,(double a, double b),(a,b),return)
SDL_DYNAPI_PROC(float,SDL_fmodf,(float a, float b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_SetYUVConversionMode,(SDL_YUV_CONVERSION_MODE a),(a),)
SDL_DYNAPI_PROC(SDL_YUV_CONVERSION_MODE,SDL_GetYUVConversionMode,(void),(),return)
SDL_DYNAPI_PROC(SDL_YUV_CONVERSION_MODE,SDL_GetYUVConversionModeForResolution,(int a, int b),(a,b),return)
SDL_DYNAPI_PROC(void*,SDL_RenderGetMetalLayer,(SDL_Renderer *a),(a),return)
SDL_DYNAPI_PROC(void*,SDL_RenderGetMetalCommandEncoder,(SDL_Renderer *a),(a),return)
#ifdef __WINRT__
SDL_DYNAPI_PROC(SDL_WinRT_DeviceFamily,SDL_WinRTGetDeviceFamily,(void),(),return)
#endif
#ifdef __ANDROID__
SDL_DYNAPI_PROC(SDL_bool,SDL_IsAndroidTV,(void),(),return)
#endif
SDL_DYNAPI_PROC(double,SDL_log10,(double a),(a),return)
SDL_DYNAPI_PROC(float,SDL_log10f,(float a),(a),return)
SDL_DYNAPI_PROC(char*,SDL_GameControllerMappingForDeviceIndex,(int a),(a),return)
#ifdef __LINUX__
SDL_DYNAPI_PROC(int,SDL_LinuxSetThreadPriority,(Sint64 a, int b),(a,b),return)
#endif
SDL_DYNAPI_PROC(SDL_bool,SDL_HasAVX512F,(void),(),return)
#ifdef __ANDROID__
SDL_DYNAPI_PROC(SDL_bool,SDL_IsChromebook,(void),(),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_IsDeXMode,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_AndroidBackButton,(void),(),)
#endif
SDL_DYNAPI_PROC(double,SDL_exp,(double a),(a),return)
SDL_DYNAPI_PROC(float,SDL_expf,(float a),(a),return)
SDL_DYNAPI_PROC(wchar_t*,SDL_wcsdup,(const wchar_t *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GameControllerRumble,(SDL_GameController *a, Uint16 b, Uint16 c, Uint32 d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_JoystickRumble,(SDL_Joystick *a, Uint16 b, Uint16 c, Uint32 d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_NumSensors,(void),(),return)
SDL_DYNAPI_PROC(const char*,SDL_SensorGetDeviceName,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_SensorType,SDL_SensorGetDeviceType,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SensorGetDeviceNonPortableType,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_SensorID,SDL_SensorGetDeviceInstanceID,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_Sensor*,SDL_SensorOpen,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_Sensor*,SDL_SensorFromInstanceID,(SDL_SensorID a),(a),return)
SDL_DYNAPI_PROC(const char*,SDL_SensorGetName,(SDL_Sensor *a),(a),return)
SDL_DYNAPI_PROC(SDL_SensorType,SDL_SensorGetType,(SDL_Sensor *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SensorGetNonPortableType,(SDL_Sensor *a),(a),return)
SDL_DYNAPI_PROC(SDL_SensorID,SDL_SensorGetInstanceID,(SDL_Sensor *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SensorGetData,(SDL_Sensor *a, float *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(void,SDL_SensorClose,(SDL_Sensor *a),(a),)
SDL_DYNAPI_PROC(void,SDL_SensorUpdate,(void),(),)
SDL_DYNAPI_PROC(SDL_bool,SDL_IsTablet,(void),(),return)
SDL_DYNAPI_PROC(SDL_DisplayOrientation,SDL_GetDisplayOrientation,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasColorKey,(SDL_Surface *a),(a),return)
#ifdef SDL_CreateThreadWithStackSize
#undef SDL_CreateThreadWithStackSize
#endif
#if defined(__WIN32__)
SDL_DYNAPI_PROC(SDL_Thread*,SDL_CreateThreadWithStackSize,(SDL_ThreadFunction a, const char *b, const size_t c, void *d, pfnSDL_CurrentBeginThread e, pfnSDL_CurrentEndThread f),(a,b,c,d,e,f),return)
#elif defined(__OS2__)
SDL_DYNAPI_PROC(SDL_Thread*,SDL_CreateThreadWithStackSize,(SDL_ThreadFunction a, const char *b, const size_t c, void *d, pfnSDL_CurrentBeginThread e, pfnSDL_CurrentEndThread f),(a,b,c,d,e,f),return)
#else
SDL_DYNAPI_PROC(SDL_Thread*,SDL_CreateThreadWithStackSize,(SDL_ThreadFunction a, const char *b, const size_t c, void *d),(a,b,c,d),return)
#endif
SDL_DYNAPI_PROC(int,SDL_JoystickGetDevicePlayerIndex,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_JoystickGetPlayerIndex,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GameControllerGetPlayerIndex,(SDL_GameController *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_RenderFlush,(SDL_Renderer *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_RenderDrawPointF,(SDL_Renderer *a, float b, float c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_RenderDrawPointsF,(SDL_Renderer *a, const SDL_FPoint *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_RenderDrawLineF,(SDL_Renderer *a, float b, float c, float d, float e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(int,SDL_RenderDrawLinesF,(SDL_Renderer *a, const SDL_FPoint *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_RenderDrawRectF,(SDL_Renderer *a, const SDL_FRect *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_RenderDrawRectsF,(SDL_Renderer *a, const SDL_FRect *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_RenderFillRectF,(SDL_Renderer *a, const SDL_FRect *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_RenderFillRectsF,(SDL_Renderer *a, const SDL_FRect *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_RenderCopyF,(SDL_Renderer *a, SDL_Texture *b, const SDL_Rect *c, const SDL_FRect *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_RenderCopyExF,(SDL_Renderer *a, SDL_Texture *b, const SDL_Rect *c, const SDL_FRect *d, const double e, const SDL_FPoint *f, const SDL_RendererFlip g),(a,b,c,d,e,f,g),return)
SDL_DYNAPI_PROC(SDL_TouchDeviceType,SDL_GetTouchDeviceType,(SDL_TouchID a),(a),return)
#ifdef __IPHONEOS__
SDL_DYNAPI_PROC(int,SDL_UIKitRunApp,(int a, char *b, SDL_main_func c),(a,b,c),return)
#endif
SDL_DYNAPI_PROC(size_t,SDL_SIMDGetAlignment,(void),(),return)
SDL_DYNAPI_PROC(void*,SDL_SIMDAlloc,(const size_t a),(a),return)
SDL_DYNAPI_PROC(void,SDL_SIMDFree,(void *a),(a),)
SDL_DYNAPI_PROC(Sint64,SDL_RWsize,(SDL_RWops *a),(a),return)
SDL_DYNAPI_PROC(Sint64,SDL_RWseek,(SDL_RWops *a, Sint64 b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(Sint64,SDL_RWtell,(SDL_RWops *a),(a),return)
SDL_DYNAPI_PROC(size_t,SDL_RWread,(SDL_RWops *a, void *b, size_t c, size_t d),(a,b,c,d),return)
SDL_DYNAPI_PROC(size_t,SDL_RWwrite,(SDL_RWops *a, const void *b, size_t c, size_t d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_RWclose,(SDL_RWops *a),(a),return)
SDL_DYNAPI_PROC(void*,SDL_LoadFile,(const char *a, size_t *b),(a,b),return)
SDL_DYNAPI_PROC(SDL_MetalView,SDL_Metal_CreateView,(SDL_Window *a),(a),return)
SDL_DYNAPI_PROC(void,SDL_Metal_DestroyView,(SDL_MetalView a),(a),)
SDL_DYNAPI_PROC(int,SDL_LockTextureToSurface,(SDL_Texture *a, const SDL_Rect *b, SDL_Surface **c),(a,b,c),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasARMSIMD,(void),(),return)
SDL_DYNAPI_PROC(char*,SDL_strtokr,(char *a, const char *b, char **c),(a,b,c),return)
SDL_DYNAPI_PROC(wchar_t*,SDL_wcsstr,(const wchar_t *a, const wchar_t *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_wcsncmp,(const wchar_t *a, const wchar_t *b, size_t c),(a,b,c),return)
SDL_DYNAPI_PROC(SDL_GameControllerType,SDL_GameControllerTypeForIndex,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_GameControllerType,SDL_GameControllerGetType,(SDL_GameController *a),(a),return)
SDL_DYNAPI_PROC(SDL_GameController*,SDL_GameControllerFromPlayerIndex,(int a),(a),return)
SDL_DYNAPI_PROC(void,SDL_GameControllerSetPlayerIndex,(SDL_GameController *a, int b),(a,b),)
SDL_DYNAPI_PROC(SDL_Joystick*,SDL_JoystickFromPlayerIndex,(int a),(a),return)
SDL_DYNAPI_PROC(void,SDL_JoystickSetPlayerIndex,(SDL_Joystick *a, int b),(a,b),)
SDL_DYNAPI_PROC(int,SDL_SetTextureScaleMode,(SDL_Texture *a, SDL_ScaleMode b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetTextureScaleMode,(SDL_Texture *a, SDL_ScaleMode *b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_OnApplicationWillTerminate,(void),(),)
SDL_DYNAPI_PROC(void,SDL_OnApplicationDidReceiveMemoryWarning,(void),(),)
SDL_DYNAPI_PROC(void,SDL_OnApplicationWillResignActive,(void),(),)
SDL_DYNAPI_PROC(void,SDL_OnApplicationDidEnterBackground,(void),(),)
SDL_DYNAPI_PROC(void,SDL_OnApplicationWillEnterForeground,(void),(),)
SDL_DYNAPI_PROC(void,SDL_OnApplicationDidBecomeActive,(void),(),)
#ifdef __IPHONEOS__
SDL_DYNAPI_PROC(void,SDL_OnApplicationDidChangeStatusBarOrientation,(void),(),)
#endif
#ifdef __ANDROID__
SDL_DYNAPI_PROC(int,SDL_GetAndroidSDKVersion,(void),(),return)
#endif
SDL_DYNAPI_PROC(int,SDL_isupper,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_islower,(int a),(a),return)
| 0 | 0.872337 | 1 | 0.872337 | game-dev | MEDIA | 0.456096 | game-dev | 0.593379 | 1 | 0.593379 |
rotators/fo2238 | 18,027 | Server/scripts/replication.fos | //
// FOnline: 2238
// Rotators
//
// replication.fos
//
#include "_macros.fos"
#include "_basetypes.fos"
#include "follower_h.fos"
#include "factions_bases_h.fos"
#include "npc_common_h.fos"
#include "follower_common_h.fos"
#include "world_common_h.fos"
#include "entire.fos"
#include "logging_h.fos"
#include "map_tent_h.fos"
#include "minigames_h.fos"
#include "npc_roles_h.fos"
#include "utils_h.fos"
#include "MsgStr.h"
import void DropDrugEffects(Critter& cr) from "drugs";
import void DropPoison(Critter& cr) from "poison";
// import void DropRadiation(Critter& cr) from "radiation";
import void CapRadiation(Critter& cr) from "radiation";
import Map@ GetRoomPosition(uint PlayerId, uint16& out hx, uint16& out hy) from "rooms";
import bool IsInsideArena(Critter&) from "arena";
import void OnTeleportToLobby(Critter&) from "arena";
import void ClearInfluenceBuffer(Critter& cr) from "town";
// const uint16 HellMapPid=MAP_replication_hell;
const uint16[] Hospitals =
{
LOCATION_Replication1,
LOCATION_Replication2,
LOCATION_Replication3,
LOCATION_Replication4,
LOCATION_Replication5,
LOCATION_Replication6,
LOCATION_Replication7,
LOCATION_Replication8
};
// starting towns
const uint16[] Towns =
{
// LOCATION_Den,
// LOCATION_Klamath,
// LOCATION_Modoc,
// LOCATION_BrokenHills,
// LOCATION_NewReno,
LOCATION_NCR,
// LOCATION_Redding,
LOCATION_SanFrancisco,
LOCATION_Junktown,
LOCATION_Hub,
LOCATION_Boneyard
};
//
// Gets nearest replication map
//
Map@ GetNearestReplicatorMap(Critter& player)
{
Location@ loc;
Location@ nearest;
uint dist = 999999;
uint tmp = 0;
for(uint i = 0, j = Hospitals.length(); i < j; i++)
{
@loc = GetLocationByPid(Hospitals[i], 0);
if(!valid(loc))
{
Log("Invalid hospital location, looking further...");
continue;
}
tmp = DIST(loc.WorldX, loc.WorldY, player.WorldX, player.WorldY);
#ifdef __DEBUG__
player.Say(SAY_NETMSG, "Loc (" + loc.WorldX + ", " + loc.WorldY + "), Me (" + player.WorldX + ", " + player.WorldY + "), dist: " + tmp);
#endif
DLog("" + tmp + " ?< " + dist);
if(tmp < dist)
{
dist = tmp;
@nearest = @loc;
}
}
if(!valid(nearest))
{
Log("Couldn't obtain nearest hospital");
return null;
}
// get first map
return nearest.GetMapByIndex(0);
}
Map@ GetRandomReplicatorMap(Critter& player)
{
return GetLocationByPid(random_from_array(Hospitals), 0).GetMapByIndex(0);
}
//
// Chose one of the towns to start
//
Map@ GetStartingMap(Critter& player)
{
uint idx = Random(0, Towns.length() - 1);
Location@ loc = GetLocation(Towns[idx]);
return loc.GetMapByIndex(0);
}
void SetStartLocation(Critter& cr) // Export
{
/*Map@ map=GetStartingMap(cr);
if(not valid(map))
return;*/
// Spawn player in instanced starter location
uint x, y = 0;
uint startloc = Random(LOCATION_Spawnpoint1, LOCATION_Spawnpoint3);
switch(startloc)
{
case LOCATION_Spawnpoint1:
x = 1522;
y = 2028;
break;
case LOCATION_Spawnpoint2:
x = 1712;
y = 1438;
break;
case LOCATION_Spawnpoint3:
x = 1482;
y = 290;
break;
default:
Log("Wrong location pid!");
break;
}
uint locId = CreateLocation(startloc, x, y, null);
Location@ loc = GetLocation(locId);
Map@ map = loc.GetMapByIndex(0);
if(!valid(map))
return;
// Hidden fog on default player position
uint zoneX = cr.WorldX / __GlobalMapZoneLength;
uint zoneY = cr.WorldY / __GlobalMapZoneLength;
cr.SetFog(zoneX, zoneY, FOG_FULL);
cr.SetFog(zoneX - 1, zoneY - 1, FOG_FULL);
cr.SetFog(zoneX, zoneY - 1, FOG_FULL);
cr.SetFog(zoneX + 1, zoneY - 1, FOG_FULL);
cr.SetFog(zoneX - 1, zoneY, FOG_FULL);
cr.SetFog(zoneX + 1, zoneY, FOG_FULL);
cr.SetFog(zoneX - 1, zoneY + 1, FOG_FULL);
cr.SetFog(zoneX, zoneY + 1, FOG_FULL);
cr.SetFog(zoneX + 1, zoneY + 1, FOG_FULL);
cr.TransitToMap(map.Id, 0);
zoneX = cr.WorldX / __GlobalMapZoneLength;
zoneY = cr.WorldY / __GlobalMapZoneLength;
cr.SetFog(zoneX, zoneY, FOG_NONE);
cr.SetFog(zoneX - 1, zoneY - 1, FOG_HALF);
cr.SetFog(zoneX, zoneY - 1, FOG_HALF);
cr.SetFog(zoneX + 1, zoneY - 1, FOG_HALF);
cr.SetFog(zoneX - 1, zoneY, FOG_HALF);
cr.SetFog(zoneX + 1, zoneY, FOG_HALF);
cr.SetFog(zoneX - 1, zoneY + 1, FOG_HALF);
cr.SetFog(zoneX, zoneY + 1, FOG_HALF);
cr.SetFog(zoneX + 1, zoneY + 1, FOG_HALF);
}
void SetReplicationTime(Critter& cr) // Export
{
Map@ map = cr.GetMap();
// encounter mob corpses not removed
if(_IsTrueNpc(cr) && IsEncounterMap(map) && cr.Param[ST_NPC_ROLE] != ROLE_MOB_WAVE)
cr.StatBase[ST_REPLICATION_TIME] = REPLICATION_NEVER;
// DLog("Setting replication time");
int replTime = cr.Stat[ST_REPLICATION_TIME];
if(replTime == REPLICATION_NEVER)
return;
if(replTime < 0)
{
// No respawn, set corpse removal timeout
// DLog("No respawn, set corpse removal timeout");
if(replTime == REPLICATION_DELETE_FAST)
replTime = 1;
else
replTime = 10;
}
else if(replTime == 0) // Take default values
{
// DLog("Take default values");
if(cr.IsPlayer())
replTime = REAL_SECOND(20);
else
replTime = REAL_MINUTE(10);
}
else
replTime = REAL_SECOND(replTime);
_SetTimeout(cr, TO_REPLICATION, replTime);
}
void DropItems(Critter& cr)
{
Map@ dropMap = cr.GetMap();
array<Item@> items;
// Don't drop trophies
cr.GetItems(SLOT_TROPHY, items);
if(items.length() > 0)
{
DeleteItems(items);
items.resize(0);
}
// Disable drop of hidden items and delete containers
cr.GetItems(-1, items);
for(uint i = 0, j = items.length(); i < j; i++)
{
if(items[i].GetType() == ITEM_TYPE_CONTAINER)
{
DeleteItem(items[i]);
@items[i] = null;
}
else if(FLAG(items[i].Flags, ITEM_HIDDEN))
@items[i] = null;
}
if(valid(dropMap))
MoveItems(items, dropMap, cr.HexX, cr.HexY);
else
DeleteItems(items);
}
Map@ TryFindCompanionRespawn(Critter& cr, uint16& hx, uint16& hy, bool TryAny)
{
Map@ map = null;
if(!valid(map) && (TryAny || (cr.FollowerVar[FV_RESPAWN_PLACE] == FOLLOWER_RESPAWN_TENT)))
{
/*@map=GetTentMap(cr.FollowerVar[FV_MASTER]);
if(!valid(map))
DLog("Companion attempting to respawn in tent, but no tent found.")
else
{
DLog("Companion attempting to respawn in tent, at "+hx+","+hy);
if (GetEntireFreeHex(map,ENTIRE_REPLICATION,hx,hy))
return map;
else
{
FLog(LOG_FOLLOWER, "Companion "+cr.Id+": Found valid tent map for replication on pid " + map.GetProtoId() + " but no free replication entires");
@map=null;
}
}
*/
Location@ loc = GetNearestTentLocation(cr.FollowerVar[FV_MASTER], cr.WorldX, cr.WorldY);
if(valid(loc))
{
array<Map@> maps;
uint count = loc.GetMaps(maps);
for(uint m = 0; m < count; m++)
{
if(GetEntireFreeHex(maps[m], ENTIRE_REPLICATION, hx, hy))
return(maps[m]);
}
FLog(LOG_FOLLOWER, "Companion " + cr.Id + ": Found valid tent location for replication on pid " + loc.GetProtoId() + " but no free replication entires");
}
else
DLog("Companion attempting to respawn in tent, but no tent found.");
}
if(!valid(map) && (TryAny || (cr.FollowerVar[FV_RESPAWN_PLACE] == FOLLOWER_RESPAWN_HOTEL)))
{
@map = GetRoomPosition(cr.FollowerVar[FV_MASTER], hx, hy);
if(!valid(map))
DLog("Companion attempting to respawn in hotel, but room not found.");
// DLog("Companion attempting to respawn in hotel, at "+hx+","+hy);
}
if(!valid(map) && (TryAny || (cr.FollowerVar[FV_RESPAWN_PLACE] == FOLLOWER_RESPAWN_FACTION_BASE)))
{
DLog("Companion attempting to respawn at base.");
uint locId = cr.FollowerVar[FV_RESPAWN_BASE_ID];
Location@ loc;
if(locId != 0)
@loc = GetLocation(locId);
if(!valid(loc))
{
array<IFactionBase@> bases;
if(GetFactionBases(cr.FollowerVar[FV_FACTION], bases) != 0)
{
@loc = GetLocation(bases[0].LocationId); // Try first base if other one is invalid
cr.FollowerVarBase[FV_RESPAWN_BASE_ID] = bases[0].LocationId;
}
}
if(valid(loc))
{
DLog("Loc found: " + locId);
@map = loc.GetMapByIndex(0);
if(map.GetProtoId() == 236 || map.GetProtoId() == 238) // hq_cave1out, hq_vault1out, so need to pick the inner map in location...
@map = loc.GetMapByIndex(1);
if(GetEntireFreeHex(map, ENTIRE_REPLICATION, hx, hy))
return map;
else
{
FLog(LOG_FOLLOWER, "Companion " + cr.Id + ": Found valid base map for replication on pid " + map.GetProtoId() + " but no free replication entires");
@map = null;
}
}
}
if(!valid(map) && !TryAny)
return TryFindCompanionRespawn(cr, hx, hy, true); // Recursion, yay!
if(!valid(map))
FLog(LOG_FOLLOWER, "Companion " + cr.Id + ": Searched trough all options, no valid map found or no free replication entires found on possible maps.");
return map;
}
void ReplicateCritter(Critter& cr) // Export
{
if(cr.IsNpc() && cr.Stat[ST_REPLICATION_TIME] == REPLICATION_NEVER)
return;
// Delete some critters instead
if(cr.IsNpc() &&
(cr.Stat[ST_REPLICATION_TIME] == REPLICATION_DELETE ||
cr.Stat[ST_REPLICATION_TIME] == REPLICATION_DELETE_FAST))
{
// DLog("Removing");
if(_CritCanDropItemsOnDead(cr) && _IsFollower(cr) &&
cr.FollowerVar[FV_TYPE] == FOLLOWER_TYPE_SLAVE ||
cr.FollowerVar[FV_TYPE] == FOLLOWER_TYPE_COMPANION ||
cr.FollowerVar[FV_TYPE] == FOLLOWER_TYPE_BRAHMIN ||
cr.FollowerVar[FV_TYPE] == FOLLOWER_TYPE_DOG)
{
Item@ item = cr.GetItem(0, SLOT_ARMOR);
if(valid(item))
cr.MoveItem(item.Id, item.GetCount(), SLOT_INV);
DropItems(cr);
}
DeleteNpc(cr);
return;
}
/*if (_IsFollower(cr) || cr.CrType == CT_BRAHMIN)
{
DeleteNpc(cr);
return;
}*/
if(_IsRealPlayer(cr) && GetLvar(cr, LVAR_killer_admin) > 0)
{
if(cr.ToLife())
{
cr.StatBase[ST_CURRENT_HP] = GetLvar(cr, LVAR_killer_admin);
SetLvar(cr, LVAR_killer_admin, 0);
_CritUnsetMode(cr, MODE_NO_LOOT);
_CritUnsetMode(cr, MODE_NO_STEAL);
}
else
{
_SetTimeout(cr, TO_REPLICATION, REAL_SECOND(10));
}
return;
}
if(IsFlaggedAsIllegal(cr) && cr.GetMapId() != 0)
UnsetCritterIllegalFlag(cr);
ClearInfluenceBuffer(cr);
GameVar@ casinovar = GetLocalVar(LVAR_newr_incasino, cr.Id); // entered a casino in new reno
if(valid(casinovar))
casinovar = 0;
cr.StatBase[ST_TURN_BASED_AC] = 0;
Map@ map = null;
uint16 hx = 0, hy = 0;
bool room = false;
if(cr.IsPlayer())
{
Map@ deathMap = cr.GetMap();
if(valid(deathMap) && (IsJail(deathMap) || IsWarzone(deathMap)))
{
@map = deathMap;
array<Entire> entires;
ParseEntires(map, entires, 0);
if(entires.length() > 0)
{
int i = Random(0, entires.length() - 1);
hx = entires[i].HexX;
hy = entires[i].HexY;
}
}
else if(valid(deathMap) && deathMap.GetLocation().GetProtoId() == LOCATION_Hinkley && IsInsideArena(cr))
{
@map = deathMap;
array<Entire> entires;
ParseEntires(map, entires, 242);
if(entires.length() > 0)
{
int i = Random(0, entires.length() - 1);
hx = entires[i].HexX;
hy = entires[i].HexY;
}
}
else
{
// Try dynamic respawn points.
if(valid(deathMap))
{
Item@ dynRespawn = GetDSpawn(deathMap, cr.Param[ST_MINIGAME_DATA]);
if(valid(dynRespawn))
{
@map = GetMap(dynRespawn.MapId);
hx = dynRespawn.HexX;
hy = dynRespawn.HexY;
}
}
if(!valid(map))
{
// try hotel
@map = GetRoomPosition(cr.Id, hx, hy);
if(!valid(map))
{
@map = GetNearestReplicatorMap(cr); // GetNearestReplicatorMap(cr);
GetEntireFreeHex(map, ENTIRE_REPLICATION, hx, hy);
}
else
room = true;
}
}
if(!valid(map) || (hx == 0 && hy == 0))
{
// Continue dead
_SetTimeout(cr, TO_REPLICATION, REAL_MINUTE(1));
return;
}
if(_CritCanDropItemsOnDead(cr))
{
if(!(map.GetLocation().GetProtoId() == LOCATION_Hinkley && IsInsideArena(cr)))
DropItems(cr);
}
}
else
{
cr.DropPlanes();
cr.ClearEnemyStackNpc();
bool Tried = false;
if(cr.FollowerVar[FV_TYPE] == FOLLOWER_TYPE_COMPANION)
{
@map = TryFindCompanionRespawn(cr, hx, hy, false);
if(!valid(map))
{
DLog("Didn't find respawn for companion, deleting ");
DeleteNpc(cr);
}
if(valid(cr))
cr.FollowerVarBase[FV_LOYALITY] = CLAMP(cr.FollowerVar[FV_LOYALITY] - FOLLOWER_LOYALITY_DEATH_DROP, 0, 100);
}
else
{
cr.StatBase[ST_LAST_WEAPON_ID] = 0;
@map = cr.GetMap();
if(!valid(map)) // On global, delete
{
DeleteNpc(cr);
return;
}
hx = cr.HexX;
hy = cr.HexY;
if(cr.Stat[ST_DEAD_BLOCKER_ID] != 0)
{
Item@ block = ::GetItem(cr.Stat[ST_DEAD_BLOCKER_ID]);
if(valid(block))
DeleteItem(block);
cr.StatBase[ST_DEAD_BLOCKER_ID] = 0;
}
if(!map.IsHexPassed(hx, hy))
{
bool founded = false;
for(int x = -1; x <= 1; x++)
{
for(int y = -1; y <= 1; y++)
{
if(x == 0 && y == 0)
continue; // Skip direct position
if(__MapHexagonal)
{
if((hx % 2) == 1 && ((x == -1 && y == 1) || (x == 1 && y == 1)))
continue;
if((hx % 2) == 0 && ((x == -1 && y == -1) || (x == 1 && y == -1)))
continue;
}
if(map.IsHexPassed(hx + x, hy + y))
{
hx += x;
hy += y;
founded = true;
break;
}
}
if(founded)
break;
}
if(!founded)
{
// Continue dead
_SetTimeout(cr, TO_REPLICATION, REAL_MINUTE(1));
return;
}
}
}
}
if(!valid(map))
{
Log("Cannot find replication map, critter " + cr.Id);
return;
}
if(map.GetLocation().GetProtoId() == LOCATION_Hinkley && IsInsideArena(cr))
{
cr.TransitToMap(map.Id, hx, hy, Random(0, 5));
OnTeleportToLobby(cr);
}
else
{
cr.TransitToMap(map.Id, hx, hy, Random(0, 5));
cr.DamageBase[DAMAGE_EYE] = 0;
cr.DamageBase[DAMAGE_RIGHT_ARM] = 0;
cr.DamageBase[DAMAGE_LEFT_ARM] = 0;
cr.DamageBase[DAMAGE_RIGHT_LEG] = 0;
cr.DamageBase[DAMAGE_LEFT_LEG] = 0;
cr.StatBase[ST_CURRENT_HP] = 10;
if(cr.IsNpc())
cr.StatBase[ST_CURRENT_HP] = cr.Stat[ST_MAX_LIFE];
if(IsWarzone(map)) // Full life on warzone
cr.StatBase[ST_CURRENT_HP] = cr.Stat[ST_MAX_LIFE];
else
_SetTimeout(cr, TO_WEAKENED, WEAKENED_TIMEOUT(cr));
}
cr.ToLife();
if(room)
cr.SayMsg(SAY_NORM_ON_HEAD, TEXTMSG_TEXT, STR_ROOM_REPLICATION);
SetLvar(cr, LVAR_event_outfitted, 0);
cr.StatBase[ST_CURRENT_AP] = cr.Stat[ST_ACTION_POINTS] * 100;
if(_IsRealPlayer(cr))
_CritUnsetMode(cr, MODE_NO_LOOT);
DropPoison(cr);
CapRadiation(cr);
// DropRadiation(cr);
// DropDrugEffects(cr);
cr.DropTimers();
// ClearIllegalFlags(cr); // Clear illegal flags in all towns
uint toVote = cr.Timeout[TO_KARMA_VOTING];
// cr.DropTimeouts();
_SetTimeout(cr, TO_KARMA_VOTING, toVote);
#ifdef __TEST__
cr.AddItem(PID_RADIO, 1);
#endif
}
| 0 | 0.973606 | 1 | 0.973606 | game-dev | MEDIA | 0.987912 | game-dev | 0.947194 | 1 | 0.947194 |
raven2cz/dotfiles | 4,996 | .config/awesome/lain/util/menu_iterator.lua | --[[
Licensed under GNU General Public License v2
* (c) 2017, Simon Désaulniers <sim.desaulniers@gmail.com>
* (c) 2017, Uli Schlachter
* (c) 2017, Jeferson Siqueira <jefersonlsiq@gmail.com>
--]]
-- Menu iterator with Naughty notifications
-- lain.util.menu_iterator
local naughty = require("naughty")
local helpers = require("lain.helpers")
local atable = require("awful.util").table
local assert = assert
local pairs = pairs
local tconcat = table.concat
local unpack = unpack or table.unpack -- lua 5.1 retro-compatibility
local state = { cid = nil }
local function naughty_destroy_callback(reason)
local closed = naughty.notificationClosedReason
if reason == closed.expired or reason == closed.dismissedByUser then
local actions = state.index and state.menu[state.index - 1][2]
if actions then
for _,action in pairs(actions) do
-- don't try to call nil callbacks
if action then action() end
end
state.index = nil
end
end
end
-- Iterates over a menu.
-- After the timeout, callbacks associated to the last visited choice are
-- executed. Inputs:
-- * menu: a list of {label, {callbacks}} pairs
-- * timeout: time to wait before confirming the menu selection
-- * icon: icon to display in the notification of the chosen label
local function iterate(menu, timeout, icon)
timeout = timeout or 4 -- default timeout for each menu entry
icon = icon or nil -- icon to display on the menu
-- Build the list of choices
if not state.index then
state.menu = menu
state.index = 1
end
-- Select one and display the appropriate notification
local label
local next = state.menu[state.index]
state.index = state.index + 1
if not next then
label = "Cancel"
state.index = nil
else
label, _ = unpack(next)
end
state.cid = naughty.notify({
text = label,
icon = icon,
timeout = timeout,
screen = mouse.screen,
replaces_id = state.cid,
destroy = naughty_destroy_callback
}).id
end
-- Generates a menu compatible with the first argument of `iterate` function and
-- suitable for the following cases:
-- * all possible choices individually (partition of singletons);
-- * all possible subsets of the set of choices (powerset).
--
-- Inputs:
-- * args: an array containing the following members:
-- * choices: Array of choices (string) on which the menu will be
-- generated.
-- * name: Displayed name of the menu (in the form "name: choices").
-- * selected_cb: Callback to execute for each selected choice. Takes
-- the choice as a string argument. Can be `nil` (no action
-- to execute).
-- * rejected_cb: Callback to execute for each rejected choice (possible
-- choices which are not selected). Takes the choice as a
-- string argument. Can be `nil` (no action to execute).
-- * extra_choices: An array of extra { choice_str, callback_fun } pairs to be
-- added to the menu. Each callback_fun can be `nil`.
-- * combination: The combination of choices to generate. Possible values:
-- "powerset" and "single" (default).
-- Output:
-- * m: menu to be iterated over.
local function menu(args)
local choices = assert(args.choices or args[1])
local name = assert(args.name or args[2])
local selected_cb = args.selected_cb
local rejected_cb = args.rejected_cb
local extra_choices = args.extra_choices or {}
local ch_combinations = args.combination == "powerset" and helpers.powerset(choices) or helpers.trivial_partition_set(choices)
for _, c in pairs(extra_choices) do
ch_combinations = atable.join(ch_combinations, {{c[1]}})
end
local m = {} -- the menu
for _,c in pairs(ch_combinations) do
if #c > 0 then
local cbs = {}
-- selected choices
for _,ch in pairs(c) do
if atable.hasitem(choices, ch) then
cbs[#cbs + 1] = selected_cb and function() selected_cb(ch) end or nil
end
end
-- rejected choices
for _,ch in pairs(choices) do
if not atable.hasitem(c, ch) and atable.hasitem(choices, ch) then
cbs[#cbs + 1] = rejected_cb and function() rejected_cb(ch) end or nil
end
end
-- add user extra choices (like the choice "None" for example)
for _,x in pairs(extra_choices) do
if x[1] == c[1] then
cbs[#cbs + 1] = x[2]
end
end
m[#m + 1] = { name .. ": " .. tconcat(c, " + "), cbs }
end
end
return m
end
return { iterate = iterate, menu = menu }
| 0 | 0.966714 | 1 | 0.966714 | game-dev | MEDIA | 0.360211 | game-dev | 0.985298 | 1 | 0.985298 |
bryceredd/CastleHassle | 6,944 | Rev6/Catapult.mm | //
// Tower.m
// Rev3
//
// Created by Bryce Redd on 11/15/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import "Catapult.h"
#import "CatapultBall.h"
#import "Battlefield.h"
#import "PlayerArea.h"
#import "PlayerAreaManager.h"
#import "Settings.h"
#import "AI.h"
@implementation Catapult
-(id) initWithWorld:(b2World*)w coords:(CGPoint)p {
if((self = [super init])) {
// these adjust the offset of the arm to the base of the physical box
offset = 0.0;
currentShotAngle = M_PI_4;
world = w;
maxHp = hp = MAX_CATAPULT_HP;
buyPrice = CATAPULT_BUY_PRICE;
repairPrice = CATAPULT_REPAIR_PRICE;
upgradePrice = CATAPULT_UPGRADE_PRICE;
maxCooldown = CATAPULT_COOLDOWN;
acceptsPlayerColoring = NO;
[self setupSpritesWithRect:CGRectMake(3, 6, 23, 22) image:CATAPULT_IMAGE atPoint:p];
[self setupSwingSpritesWithRect:CGRectMake(0, 0, 35, 5) image:CATAPULT_IMAGE atPoint:p];
// define the base dynamic body
b2BodyDef bodyDef;
bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
bodyDef.userData = self;
body = world->CreateBody(&bodyDef);
//Audio Section
[[SimpleAudioEngine sharedEngine] preloadEffect:@"catapult.caf"];
}
return self;
}
- (void) onTouchMoved:(CGPoint)touch {
[super onTouchMoved:touch];
// configure the direction
self.isFacingLeft = (currentShotAngle < CC_DEGREES_TO_RADIANS(self.currentSprite.rotation + 90.f));
}
-(BOOL) onTouchEndedLocal:(CGPoint)touch {
if(self.shootIndicatorTail) [[Battlefield instance] removeChild:self.shootIndicatorTail cleanup:YES];
if(self.shootIndicatorTop) [[Battlefield instance] removeChild:self.shootIndicatorTop cleanup:YES];
self.shootIndicatorTail = nil;
self.shootIndicatorTop = nil;
if(shotPower < 20) { return NO; }
if(![self isUsable]) { return NO; }
//Audio Section
[[SimpleAudioEngine sharedEngine] playEffect:@"catapult.caf"];
// so we don't spawn the bullet inside the cannon body
float pixelsInFront = 30.0;
CGPoint projectileLoc = CGPointMake((float)self.swingSprite.position.x, (float)self.swingSprite.position.y);
float h = touch.y - initialTouch.y;
float w = touch.x - initialTouch.x;
if(WEAPON_MAX_POWER < fabs(h)+fabs(w)) {
h = WEAPON_MAX_POWER*(h/(fabs(h)+fabs(w)));
w = WEAPON_MAX_POWER*(w/(fabs(h)+fabs(w)));
}
float power = b2Vec2(w,h).Length();
// only shoot up
if(h<0.0)h=0.0;
// this initiates the cannonball just outside the cannon
projectileLoc.x += (w/power)*pixelsInFront;
projectileLoc.y += (h/power)*pixelsInFront;
CatapultBall *ball;
CatapultBall *firstball=nil;
for(int i=0;i<weaponLevel*CATPULT_BALLS_PER_UPGRADE;i++) {
float xRandomness = 1.f;
float yRandomness = 1.f;
if(i > 0) {
xRandomness += (float)(-(CATAPULT_SHOT_RANDOMNESS/2) + (int)(arc4random() % CATAPULT_SHOT_RANDOMNESS)) / 100.f;
yRandomness += (float)(-(CATAPULT_SHOT_RANDOMNESS/2) + (int)(arc4random() % CATAPULT_SHOT_RANDOMNESS)) / 100.f;
}
// this initiates the catapultball just outside the weapon
ball = [[[CatapultBall alloc] initWithWorld:world coords:projectileLoc level:weaponLevel shooter:self.owner] autorelease];
[[Battlefield instance] addProjectileToBin:ball];
ball.body->ApplyLinearImpulse(b2Vec2(w*xRandomness*CATAPULT_DEFAULT_POWER,h*yRandomness*CATAPULT_DEFAULT_POWER),
ball.body->GetPosition());
firstball = firstball == nil ? ball : firstball;
}
[super fired:firstball];
return YES;
}
-(BOOL) shootFromAICatapult:(float)F isLeft:(BOOL)left {
if(![[Battlefield instance] canFire]) { return NO;}
[self setIsFacingLeft:left];
CGPoint swingLoc = ccp((float)self.swingSprite.position.x, (float)self.swingSprite.position.y);
swingLoc.y += 20;
CatapultBall * ball = [[[CatapultBall alloc] initWithWorld:world
coords:swingLoc
level:weaponLevel
shooter:self.owner] autorelease];
[[Battlefield instance] addProjectileToBin:ball];
float forceX = [AI getCatapultForce]*cos(CC_DEGREES_TO_RADIANS(45));
float forceY = [AI getCatapultForce]*sin(CC_DEGREES_TO_RADIANS(45));
ball.body->ApplyLinearImpulse(b2Vec2(forceX*(left?-1:1),forceY),ball.body->GetPosition());
currentShotAngle = M_PI_2+(left?-M_PI_4:M_PI_4);
[super fired:ball];
return YES;
}
-(void) finalizePiece {
// define another box shape for our dynamic body.
b2PolygonShape dynamicBox;
// we need to make this a slightly weighted object as we have an offset
dynamicBox.SetAsBox(23.0/PTM_RATIO*.5, 22.0/PTM_RATIO*.5, b2Vec2(0,offset/(1.5*PTM_RATIO)), 0);
// define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = PIECE_DENSITY;
fixtureDef.friction = 1.0f;
body->CreateFixture(&fixtureDef);
[super finalizePiece];
}
-(void) targetWasHit:(b2Contact*)contact by:(Projectile*)p {
[super targetWasHit:contact by:p];
}
-(void) updateView {
if (hp < (MAX_CATAPULT_HP/2)) {
[self.currentSprite setTextureRect:CGRectMake(3, 36, 23, 22)];
[self.backSprite setTextureRect:CGRectMake(3, 36, 23, 22)];
[self.swingSprite setTextureRect:CGRectMake(0, 30, 35, 5)];
[self.backSwingSprite setTextureRect:CGRectMake(0, 30, 35, 5)];
} else {
[self.currentSprite setTextureRect:CGRectMake(3, 6, 23, 22)];
[self.backSprite setTextureRect:CGRectMake(3, 6, 23, 22)];
[self.swingSprite setTextureRect:CGRectMake(0, 0, 35, 5)];
[self.backSwingSprite setTextureRect:CGRectMake(0, 0, 35, 5)];
}
[super updateView];
}
-(void) moveObject:(CGPoint)touch {
[super moveObject:touch];
}
-(void) updateSpritesAngle:(float)ang position:(b2Vec2)pos time:(float)t {
if(([Battlefield instance].selected != self || ![Battlefield instance]->touchDown)) {
if(shotPower > 30) {
self.shotPower -= 20;
}
}
float percentPower = self.shotPower / WEAPON_MAX_POWER;
[super updateSpritesAngle:ang position:pos time:t];
// swing position is normal, but the rotation adds the current angle
self.swingSprite.position = ccp(pos.x * PTM_RATIO, pos.y * PTM_RATIO);
self.swingSprite.rotation = CC_RADIANS_TO_DEGREES(-(M_PI+M_PI_2) + (self.isFacingLeft? 1 : -1) * percentPower*M_PI_2);
// figure out if the backsprite must be moved
if(self.backSwingSprite) {
float camX,camY,camZ;
[[Battlefield instance].camera centerX:&camX centerY:&camY centerZ:&camZ];
self.backSwingSprite.position = [[Battlefield instance].playerAreaManager getBackImagePosFromObjPos:ccp(pos.x * PTM_RATIO, pos.y * PTM_RATIO) cameraPosition:ccp(camX, camY)];
self.backSwingSprite.position = ccp(self.backSwingSprite.position.x,
self.backSwingSprite.position.y);
self.backSwingSprite.rotation = CC_RADIANS_TO_DEGREES(ang-self.currentShotAngle);
}
}
@end
| 0 | 0.846912 | 1 | 0.846912 | game-dev | MEDIA | 0.988966 | game-dev | 0.977841 | 1 | 0.977841 |
ErichStyger/mcuoneclipse | 12,440 | Examples/KDS/FRDM-K64F120M/FRDM-K64F_Zork/Sources/Zork/dinit.c | /* INIT-- DUNGEON INITIALIZATION SUBROUTINE */
/*COPYRIGHT 1980, INFOCOM COMPUTERS AND COMMUNICATIONS, CAMBRIDGE MA. 02142*/
/* ALL RIGHTS RESERVED, COMMERCIAL USAGE STRICTLY PROHIBITED */
/* WRITTEN BY R. M. SUPNIK */
#include <stdio.h>
#ifdef __AMOS__
#include <amos.h>
#endif
#include "funcs.h"
#include "vars.h"
/* This is here to avoid depending on the existence of <stdlib.h> */
extern void srand P((unsigned int));
FILE *dbfile;
#ifndef TEXTFILE
#ifdef __AMOS__
#define TEXTFILE "lib:dtextc.dat"
#else /* ! __AMOS__ */
#ifdef unix
#define TEXTFILE "/usr/games/lib/dunlib/dtextc.dat"
#else /* ! unix */
#define TEXTFILE "./dtextc.dat"
// I need a definition for TEXTFILE
#endif /* ! unix */
#endif /* ! __AMOS__ */
#endif /* ! TEXTFILE */
#ifndef LOCALTEXTFILE
#define LOCALTEXTFILE "dtextc.dat"
#endif
/* Read a single two byte integer from the index file */
#define rdint(indxfile) \
(ch = getc(indxfile), \
((ch > 127) ? (ch - 256) : (ch)) * 256 + getc(indxfile))
/* Read a number of two byte integers from the index file */
static void rdints(c, pi, indxfile)
integer c;
integer *pi;
FILE *indxfile;
{
integer ch; /* Local variable for rdint */
while (c-- != 0)
*pi++ = rdint(indxfile);
}
/* Read a partial array of integers. These are stored as index,value
* pairs.
*/
static void rdpartialints(c, pi, indxfile)
integer c;
integer *pi;
FILE *indxfile;
{
integer ch; /* Local variable for rdint */
while (1) {
int i;
if (c < 255) {
i = getc(indxfile);
if (i == 255)
return;
}
else {
i = rdint(indxfile);
if (i == -1)
return;
}
pi[i] = rdint(indxfile);
}
}
/* Read a number of one byte flags from the index file */
static void rdflags(c, pf, indxfile)
integer c;
logical *pf;
FILE *indxfile;
{
while (c-- != 0)
*pf++ = getc(indxfile);
}
logical init_()
{
/* System generated locals */
integer i__1;
logical ret_val;
/* Local variables */
integer xmax, r2max, dirmax, recno;
integer i, j, k;
register integer ch;
register FILE *indxfile;
integer mmax, omax, rmax, vmax, amax, cmax, fmax, smax;
more_init();
/* FIRST CHECK FOR PROTECTION VIOLATION */
if (protected()) {
goto L10000;
}
/* !PROTECTION VIOLATION? */
more_output("There appears before you a threatening figure clad all over");
more_output("in heavy black armor. His legs seem like the massive trunk");
more_output("of the oak tree. His broad shoulders and helmeted head loom");
more_output("high over your own puny frame, and you realize that his powerful");
more_output("arms could easily crush the very life from your body. There");
more_output("hangs from his belt a veritable arsenal of deadly weapons:");
more_output("sword, mace, ball and chain, dagger, lance, and trident.");
more_output("He speaks with a commanding voice:");
more_output("");
more_output(" \"You shall not pass.\"");
more_output("");
more_output("As he grabs you by the neck all grows dim about you.");
exit_();
/* NOW START INITIALIZATION PROPER */
L10000:
ret_val = FALSE_;
/* !ASSUME INIT FAILS. */
mmax = 1050;
/* !SET UP ARRAY LIMITS. */
omax = 220;
rmax = 200;
vmax = 4;
amax = 4;
cmax = 25;
fmax = 46;
smax = 22;
xmax = 900;
r2max = 20;
dirmax = 15;
rmsg_1.mlnt = 0;
/* !INIT ARRAY COUNTERS. */
objcts_1.olnt = 0;
rooms_1.rlnt = 0;
vill_1.vlnt = 0;
advs_1.alnt = 0;
cevent_1.clnt = 0;
exits_1.xlnt = 1;
oroom2_1.r2lnt = 0;
state_1.ltshft = 10;
/* !SET UP STATE VARIABLES. */
state_1.mxscor = state_1.ltshft;
state_1.egscor = 0;
state_1.egmxsc = 0;
state_1.mxload = 100;
state_1.rwscor = 0;
state_1.deaths = 0;
state_1.moves = 0;
time_1.pltime = 0;
state_1.mungrm = 0;
state_1.hs = 0;
prsvec_1.prsa = 0;
/* !CLEAR PARSE VECTOR. */
prsvec_1.prsi = 0;
prsvec_1.prso = 0;
prsvec_1.prscon = 1;
orphs_1.oflag = 0;
/* !CLEAR ORPHANS. */
orphs_1.oact = 0;
orphs_1.oslot = 0;
orphs_1.oprep = 0;
orphs_1.oname = 0;
hack_1.thfflg = FALSE_;
/* !THIEF NOT INTRODUCED BUT */
hack_1.thfact = TRUE_;
/* !IS ACTIVE. */
hack_1.swdact = FALSE_;
/* !SWORD IS INACTIVE. */
hack_1.swdsta = 0;
/* !SWORD IS OFF. */
recno = 1;
/* !INIT DB FILE POINTER. */
star_1.mbase = 0;
/* !INIT MELEE BASE. */
/* INIT, PAGE 3 */
/* INIT ALL ARRAYS. */
i__1 = cmax;
for (i = 1; i <= i__1; ++i) {
/* !CLEAR CLOCK EVENTS */
cevent_1.cflag[i - 1] = FALSE_;
cevent_1.ctick[i - 1] = 0;
cevent_1.cactio[i - 1] = 0;
/* L5: */
}
i__1 = fmax;
for (i = 1; i <= i__1; ++i) {
/* !CLEAR FLAGS. */
flags[i - 1] = FALSE_;
/* L10: */
}
findex_1.buoyf = TRUE_;
/* !SOME START AS TRUE. */
findex_1.egyptf = TRUE_;
findex_1.cagetf = TRUE_;
findex_1.mr1f = TRUE_;
findex_1.mr2f = TRUE_;
findex_1.follwf = TRUE_;
i__1 = smax;
for (i = 1; i <= i__1; ++i) {
/* !CLEAR SWITCHES. */
switch_[i - 1] = 0;
/* L12: */
}
findex_1.ormtch = 4;
/* !NUMBER OF MATCHES. */
findex_1.lcell = 1;
findex_1.pnumb = 1;
findex_1.mdir = 270;
findex_1.mloc = rindex_1.mrb;
findex_1.cphere = 10;
i__1 = r2max;
for (i = 1; i <= i__1; ++i) {
/* !CLEAR ROOM 2 ARRAY. */
oroom2_1.rroom2[i - 1] = 0;
oroom2_1.oroom2[i - 1] = 0;
/* L15: */
}
i__1 = xmax;
for (i = 1; i <= i__1; ++i) {
/* !CLEAR TRAVEL ARRAY. */
exits_1.travel[i - 1] = 0;
/* L20: */
}
i__1 = vmax;
for (i = 1; i <= i__1; ++i) {
/* !CLEAR VILLAINS ARRAYS. */
vill_1.vopps[i - 1] = 0;
vill_1.vprob[i - 1] = 0;
vill_1.villns[i - 1] = 0;
vill_1.vbest[i - 1] = 0;
vill_1.vmelee[i - 1] = 0;
/* L30: */
}
i__1 = omax;
for (i = 1; i <= i__1; ++i) {
/* !CLEAR OBJECT ARRAYS. */
objcts_1.odesc1[i - 1] = 0;
objcts_1.odesc2[i - 1] = 0;
objcts_1.odesco[i - 1] = 0;
objcts_1.oread[i - 1] = 0;
objcts_1.oactio[i - 1] = 0;
objcts_1.oflag1[i - 1] = 0;
objcts_1.oflag2[i - 1] = 0;
objcts_1.ofval[i - 1] = 0;
objcts_1.otval[i - 1] = 0;
objcts_1.osize[i - 1] = 0;
objcts_1.ocapac[i - 1] = 0;
objcts_1.ocan[i - 1] = 0;
objcts_1.oadv[i - 1] = 0;
objcts_1.oroom[i - 1] = 0;
/* L40: */
}
i__1 = rmax;
for (i = 1; i <= i__1; ++i) {
/* !CLEAR ROOM ARRAYS. */
rooms_1.rdesc1[i - 1] = 0;
rooms_1.rdesc2[i - 1] = 0;
rooms_1.ractio[i - 1] = 0;
rooms_1.rflag[i - 1] = 0;
rooms_1.rval[i - 1] = 0;
rooms_1.rexit[i - 1] = 0;
/* L50: */
}
i__1 = mmax;
for (i = 1; i <= i__1; ++i) {
/* !CLEAR MESSAGE DIRECTORY. */
rmsg_1.rtext[i - 1] = 0;
/* L60: */
}
i__1 = amax;
for (i = 1; i <= i__1; ++i) {
/* !CLEAR ADVENTURER'S ARRAYS. */
advs_1.aroom[i - 1] = 0;
advs_1.ascore[i - 1] = 0;
advs_1.avehic[i - 1] = 0;
advs_1.aobj[i - 1] = 0;
advs_1.aactio[i - 1] = 0;
advs_1.astren[i - 1] = 0;
advs_1.aflag[i - 1] = 0;
/* L70: */
}
debug_1.dbgflg = 0;
debug_1.prsflg = 0;
debug_1.gdtflg = 0;
#ifdef ALLOW_GDT
/* allow setting gdtflg true if user id matches wizard id */
/* this way, the wizard doesn't have to recompile to use gdt */
if (wizard()) {
debug_1.gdtflg = 1;
}
#endif /* ALLOW_GDT */
screen_1.fromdr = 0;
/* !INIT SCOL GOODIES. */
screen_1.scolrm = 0;
screen_1.scolac = 0;
/* INIT, PAGE 4 */
/* NOW RESTORE FROM EXISTING INDEX FILE. */
#ifdef __AMOS__
if ((dbfile = fdopen(ropen(LOCALTEXTFILE, 0), BINREAD)) == NULL &&
(dbfile = fdopen(ropen(TEXTFILE, 0), BINREAD)) == NULL)
#else
if ((dbfile = fopen(LOCALTEXTFILE, BINREAD)) == NULL &&
(dbfile = fopen(TEXTFILE, BINREAD)) == NULL)
#endif
goto L1950;
indxfile = dbfile;
i = rdint(indxfile);
j = rdint(indxfile);
k = rdint(indxfile);
/* !GET VERSION. */
if (i != vers_1.vmaj || j != vers_1.vmin) {
goto L1925;
}
state_1.mxscor = rdint(indxfile);
star_1.strbit = rdint(indxfile);
state_1.egmxsc = rdint(indxfile);
rooms_1.rlnt = rdint(indxfile);
rdints(rooms_1.rlnt, &rooms_1.rdesc1[0], indxfile);
rdints(rooms_1.rlnt, &rooms_1.rdesc2[0], indxfile);
rdints(rooms_1.rlnt, &rooms_1.rexit[0], indxfile);
rdpartialints(rooms_1.rlnt, &rooms_1.ractio[0], indxfile);
rdpartialints(rooms_1.rlnt, &rooms_1.rval[0], indxfile);
rdints(rooms_1.rlnt, &rooms_1.rflag[0], indxfile);
exits_1.xlnt = rdint(indxfile);
rdints(exits_1.xlnt, &exits_1.travel[0], indxfile);
objcts_1.olnt = rdint(indxfile);
rdints(objcts_1.olnt, &objcts_1.odesc1[0], indxfile);
rdints(objcts_1.olnt, &objcts_1.odesc2[0], indxfile);
rdpartialints(objcts_1.olnt, &objcts_1.odesco[0], indxfile);
rdpartialints(objcts_1.olnt, &objcts_1.oactio[0], indxfile);
rdints(objcts_1.olnt, &objcts_1.oflag1[0], indxfile);
rdpartialints(objcts_1.olnt, &objcts_1.oflag2[0], indxfile);
rdpartialints(objcts_1.olnt, &objcts_1.ofval[0], indxfile);
rdpartialints(objcts_1.olnt, &objcts_1.otval[0], indxfile);
rdints(objcts_1.olnt, &objcts_1.osize[0], indxfile);
rdpartialints(objcts_1.olnt, &objcts_1.ocapac[0], indxfile);
rdints(objcts_1.olnt, &objcts_1.oroom[0], indxfile);
rdpartialints(objcts_1.olnt, &objcts_1.oadv[0], indxfile);
rdpartialints(objcts_1.olnt, &objcts_1.ocan[0], indxfile);
rdpartialints(objcts_1.olnt, &objcts_1.oread[0], indxfile);
oroom2_1.r2lnt = rdint(indxfile);
rdints(oroom2_1.r2lnt, &oroom2_1.oroom2[0], indxfile);
rdints(oroom2_1.r2lnt, &oroom2_1.rroom2[0], indxfile);
cevent_1.clnt = rdint(indxfile);
rdints(cevent_1.clnt, &cevent_1.ctick[0], indxfile);
rdints(cevent_1.clnt, &cevent_1.cactio[0], indxfile);
rdflags(cevent_1.clnt, &cevent_1.cflag[0], indxfile);
vill_1.vlnt = rdint(indxfile);
rdints(vill_1.vlnt, &vill_1.villns[0], indxfile);
rdpartialints(vill_1.vlnt, &vill_1.vprob[0], indxfile);
rdpartialints(vill_1.vlnt, &vill_1.vopps[0], indxfile);
rdints(vill_1.vlnt, &vill_1.vbest[0], indxfile);
rdints(vill_1.vlnt, &vill_1.vmelee[0], indxfile);
advs_1.alnt = rdint(indxfile);
rdints(advs_1.alnt, &advs_1.aroom[0], indxfile);
rdpartialints(advs_1.alnt, &advs_1.ascore[0], indxfile);
rdpartialints(advs_1.alnt, &advs_1.avehic[0], indxfile);
rdints(advs_1.alnt, &advs_1.aobj[0], indxfile);
rdints(advs_1.alnt, &advs_1.aactio[0], indxfile);
rdints(advs_1.alnt, &advs_1.astren[0], indxfile);
rdpartialints(advs_1.alnt, &advs_1.aflag[0], indxfile);
star_1.mbase = rdint(indxfile);
rmsg_1.mlnt = rdint(indxfile);
rdints(rmsg_1.mlnt, &rmsg_1.rtext[0], indxfile);
/* Save location of start of message text */
rmsg_1.mrloc = ftell(indxfile);
/* !INIT DONE. */
/* INIT, PAGE 5 */
/* THE INTERNAL DATA BASE IS NOW ESTABLISHED. */
/* SET UP TO PLAY THE GAME. */
itime_(&time_1.shour, &time_1.smin, &time_1.ssec);
/* srand(time_1.shour ^ (time_1.smin ^ time_1.ssec)); */
play_1.winner = aindex_1.player;
last_1.lastit = advs_1.aobj[aindex_1.player - 1];
play_1.here = advs_1.aroom[play_1.winner - 1];
hack_1.thfpos = objcts_1.oroom[oindex_1.thief - 1];
state_1.bloc = objcts_1.oroom[oindex_1.ballo - 1];
ret_val = TRUE_;
return ret_val;
/* INIT, PAGE 6 */
/* ERRORS-- INIT FAILS. */
L1925:
more_output(NULL);
printf("%s is version %1d.%1d%c.\n", TEXTFILE, i, j, k);
more_output(NULL);
printf("I require version %1d.%1d%c.\n", vers_1.vmaj, vers_1.vmin,
vers_1.vedit);
goto L1975;
L1950:
more_output(NULL);
printf("I can't open %s.\n", TEXTFILE);
L1975:
more_output("Suddenly a sinister, wraithlike figure appears before you,");
more_output("seeming to float in the air. In a low, sorrowful voice he says,");
more_output("\"Alas, the very nature of the world has changed, and the dungeon");
more_output("cannot be found. All must now pass away.\" Raising his oaken staff");
more_output("in farewell, he fades into the spreading darkness. In his place");
more_output("appears a tastefully lettered sign reading:");
more_output("");
more_output(" INITIALIZATION FAILURE");
more_output("");
more_output("The darkness becomes all encompassing, and your vision fails.");
return ret_val;
} /* init_ */
| 0 | 0.870031 | 1 | 0.870031 | game-dev | MEDIA | 0.876164 | game-dev | 0.940513 | 1 | 0.940513 |
Wend4r/mms2-menu_system | 1,867 | src/menu/provider/gamedata/baseplayerpawn.cpp |
/**
* vim: set ts=4 sw=4 tw=99 noet :
* ======================================================
* Metamod:Source Menu System
* Written by Wend4r & komashchenko (Vladimir Ezhikov & Borys Komashchenko).
* ======================================================
* 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/>.
*/
#include <menu/provider.hpp>
#include <dynlibutils/virtual.hpp>
Menu::CProvider::CGameDataStorage::CBasePlayerPawn::CBasePlayerPawn()
: m_nGetEyePositionOffset(-1)
{
{
auto &aCallbacks = m_aOffsetCallbacks;
aCallbacks.Insert(m_aGameConfig.GetSymbol("CBasePlayerPawn::GetEyePosition"), GAMEDATA_OFFSET_SHARED_LAMBDA_CAPTURE(m_nGetEyePositionOffset));
m_aGameConfig.GetOffsets().AddListener(&aCallbacks);
}
}
bool Menu::CProvider::CGameDataStorage::CBasePlayerPawn::Load(IGameData *pRoot, KeyValues3 *pGameConfig, GameData::CStringVector &vecMessages)
{
return m_aGameConfig.Load(pRoot, pGameConfig, vecMessages);
}
void Menu::CProvider::CGameDataStorage::CBasePlayerPawn::Reset()
{
m_nGetEyePositionOffset = -1;
}
Vector Menu::CProvider::CGameDataStorage::CBasePlayerPawn::GetEyePosition(CEntityInstance *pInstance) const
{
return reinterpret_cast<DynLibUtils::VirtualTable *>(pInstance)->CallMethod<Vector>(m_nGetEyePositionOffset);
}
| 0 | 0.87887 | 1 | 0.87887 | game-dev | MEDIA | 0.90034 | game-dev | 0.7578 | 1 | 0.7578 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.