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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ProjectIgnis/CardScripts | 3,530 | official/c5253985.lua | --交差する魂
--Soul Crossing
--Scripted by Larry126
local s,id=GetID()
function s.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,id,EFFECT_COUNT_CODE_OATH)
e1:SetCondition(function()return Duel.IsMainPhase() end)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
Duel.AddCustomActivityCounter(id,ACTIVITY_CHAIN,s.chainfilter)
end
function s.chainfilter(re,tp,cid)
if Duel.GetFlagEffect(tp,id)==0 then return true end
return not (re:IsSpellTrapEffect() or not re:GetHandler():IsRace(RACE_DIVINE))
end
function s.filter(c,e,ec)
if not c:IsRace(RACE_DIVINE) then return false end
local e1=Effect.CreateEffect(ec)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_ADD_EXTRA_TRIBUTE)
e1:SetTargetRange(0,LOCATION_MZONE)
e1:SetValue(POS_FACEUP)
e1:SetReset(RESET_CHAIN)
c:RegisterEffect(e1,true)
local res=c:IsSummonable(true,nil,1) or c:IsMSetable(true,nil,1)
e1:Reset()
return res
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.filter,tp,LOCATION_HAND,0,1,nil,e,e:GetHandler()) end
Duel.SetOperationInfo(0,CATEGORY_SUMMON,nil,1,0,0)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SUMMON)
local tc=Duel.SelectMatchingCard(tp,s.filter,tp,LOCATION_HAND,0,1,1,nil,e,c):GetFirst()
if tc then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EFFECT_ADD_EXTRA_TRIBUTE)
e1:SetTargetRange(0,LOCATION_MZONE)
e1:SetValue(POS_FACEUP)
e1:SetReset(RESET_EVENT|RESETS_STANDARD)
tc:RegisterEffect(e1,true)
local s1=tc:IsSummonable(true,nil,1)
local s2=tc:IsMSetable(true,nil,1)
if (s1 and s2 and Duel.SelectPosition(tp,tc,POS_FACEUP_ATTACK+POS_FACEDOWN_DEFENSE)==POS_FACEUP_ATTACK) or not s2 then
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetCode(EVENT_SUMMON_SUCCESS)
e2:SetOperation(s.sumsuc)
e2:SetLabel(tp)
e2:SetReset(RESET_EVENT|(RESETS_STANDARD&~RESET_TOFIELD))
tc:RegisterEffect(e2,true)
Duel.Summon(tp,tc,true,nil,1)
else
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetCode(EVENT_MSET)
e3:SetReset(RESET_EVENT|(RESETS_STANDARD&~RESET_TOFIELD))
e3:SetOperation(s.sumsuc)
e3:SetLabel(tp)
tc:RegisterEffect(e3,true)
Duel.MSet(tp,tc,true,nil,1)
end
end
end
function s.sumsuc(e,tp,eg,ep,ev,re,r,rp)
local player=e:GetLabel()
if e:GetHandler():GetMaterial():IsExists(Card.IsPreviousControler,1,nil,1-player) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetDescription(aux.Stringid(id,0))
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CLIENT_HINT)
e1:SetTargetRange(1,0)
e1:SetCondition(s.accon)
e1:SetValue(s.aclimit)
e1:SetReset(RESET_PHASE|PHASE_END,2)
Duel.RegisterEffect(e1,player)
Duel.RegisterFlagEffect(player,id,RESET_PHASE|PHASE_END,0,2)
end
end
function s.accon(e)
return Duel.GetCustomActivityCount(id,e:GetHandlerPlayer(),ACTIVITY_CHAIN)>0
end
function s.aclimit(e,re,tp)
return re:IsSpellTrapEffect() or not re:GetHandler():IsRace(RACE_DIVINE)
end | 0 | 0.90544 | 1 | 0.90544 | game-dev | MEDIA | 0.991782 | game-dev | 0.924597 | 1 | 0.924597 |
PacktPublishing/Mastering-Cpp-Game-Development | 3,035 | Chapter07/Include/bullet/BulletInverseDynamics/details/MultiBodyTreeInitCache.cpp | #include "MultiBodyTreeInitCache.hpp"
namespace btInverseDynamics {
MultiBodyTree::InitCache::InitCache() {
m_inertias.resize(0);
m_joints.resize(0);
m_num_dofs = 0;
m_root_index=-1;
}
int MultiBodyTree::InitCache::addBody(const int body_index, const int parent_index,
const JointType joint_type,
const vec3& parent_r_parent_body_ref,
const mat33& body_T_parent_ref,
const vec3& body_axis_of_motion, const idScalar mass,
const vec3& body_r_body_com, const mat33& body_I_body,
const int user_int, void* user_ptr) {
switch (joint_type) {
case REVOLUTE:
case PRISMATIC:
m_num_dofs += 1;
break;
case FIXED:
// does not add a degree of freedom
// m_num_dofs+=0;
break;
case FLOATING:
m_num_dofs += 6;
break;
default:
error_message("unknown joint type %d\n", joint_type);
return -1;
}
if(-1 == parent_index) {
if(m_root_index>=0) {
error_message("trying to add body %d as root, but already added %d as root body\n",
body_index, m_root_index);
return -1;
}
m_root_index=body_index;
}
JointData joint;
joint.m_child = body_index;
joint.m_parent = parent_index;
joint.m_type = joint_type;
joint.m_parent_pos_parent_child_ref = parent_r_parent_body_ref;
joint.m_child_T_parent_ref = body_T_parent_ref;
joint.m_child_axis_of_motion = body_axis_of_motion;
InertiaData body;
body.m_mass = mass;
body.m_body_pos_body_com = body_r_body_com;
body.m_body_I_body = body_I_body;
m_inertias.push_back(body);
m_joints.push_back(joint);
m_user_int.push_back(user_int);
m_user_ptr.push_back(user_ptr);
return 0;
}
int MultiBodyTree::InitCache::getInertiaData(const int index, InertiaData* inertia) const {
if (index < 0 || index > static_cast<int>(m_inertias.size())) {
error_message("index out of range\n");
return -1;
}
*inertia = m_inertias[index];
return 0;
}
int MultiBodyTree::InitCache::getUserInt(const int index, int* user_int) const {
if (index < 0 || index > static_cast<int>(m_user_int.size())) {
error_message("index out of range\n");
return -1;
}
*user_int = m_user_int[index];
return 0;
}
int MultiBodyTree::InitCache::getUserPtr(const int index, void** user_ptr) const {
if (index < 0 || index > static_cast<int>(m_user_ptr.size())) {
error_message("index out of range\n");
return -1;
}
*user_ptr = m_user_ptr[index];
return 0;
}
int MultiBodyTree::InitCache::getJointData(const int index, JointData* joint) const {
if (index < 0 || index > static_cast<int>(m_joints.size())) {
error_message("index out of range\n");
return -1;
}
*joint = m_joints[index];
return 0;
}
int MultiBodyTree::InitCache::buildIndexSets() {
// NOTE: This function assumes that proper indices were provided
// User2InternalIndex from utils can be used to facilitate this.
m_parent_index.resize(numBodies());
for (idArrayIdx j = 0; j < m_joints.size(); j++) {
const JointData& joint = m_joints[j];
m_parent_index[joint.m_child] = joint.m_parent;
}
return 0;
}
}
| 0 | 0.937069 | 1 | 0.937069 | game-dev | MEDIA | 0.78735 | game-dev | 0.976782 | 1 | 0.976782 |
526077247/ETPro | 1,631 | Unity/Packages/com.tuyoogame.yooasset/Samples~/UniTask Sample/UniTask/Runtime/Linq/Return.cs | using Cysharp.Threading.Tasks.Internal;
using System.Threading;
namespace Cysharp.Threading.Tasks.Linq
{
public static partial class UniTaskAsyncEnumerable
{
public static IUniTaskAsyncEnumerable<TValue> Return<TValue>(TValue value)
{
return new Return<TValue>(value);
}
}
internal class Return<TValue> : IUniTaskAsyncEnumerable<TValue>
{
readonly TValue value;
public Return(TValue value)
{
this.value = value;
}
public IUniTaskAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return new _Return(value, cancellationToken);
}
class _Return : IUniTaskAsyncEnumerator<TValue>
{
readonly TValue value;
CancellationToken cancellationToken;
bool called;
public _Return(TValue value, CancellationToken cancellationToken)
{
this.value = value;
this.cancellationToken = cancellationToken;
this.called = false;
}
public TValue Current => value;
public UniTask<bool> MoveNextAsync()
{
cancellationToken.ThrowIfCancellationRequested();
if (!called)
{
called = true;
return CompletedTasks.True;
}
return CompletedTasks.False;
}
public UniTask DisposeAsync()
{
return default;
}
}
}
} | 0 | 0.541512 | 1 | 0.541512 | game-dev | MEDIA | 0.629696 | game-dev | 0.52109 | 1 | 0.52109 |
shit-ware/IW4 | 29,718 | maps/dc_whitehouse_code.gsc | #include maps\_utility;
#include common_scripts\utility;
#include maps\_anim;
#include maps\_weather;
//#include maps\dcemp_code;
#using_animtree( "generic_human" );
whitehouse_spotlight_create( str_targetname, health )
{
damage_ent = getent( str_targetname, "targetname" );
damage_ent SetCanDamage( true );
damage_ent.health = health;
spotlight_origin = getstruct( damage_ent.target, "targetname");
spotlight = SpawnTurret( "misc_turret", spotlight_origin.origin, "heli_spotlight" ); // "heli_spotlight"
spotlight.angles = spotlight_origin.angles;
spotlight setmodel( "cod3mg42" );
spotlight SetTurretTeam( "axis" );
spotlight setmode( "manual" );
spotlight SetConvergenceTime( 1, "yaw" );
spotlight SetConvergenceTime( 1, "pitch" );
spotlight.target = spotlight_origin.target;
spotlight.damage_ent = damage_ent;
spotlight thread whitehouse_spotlight();
return spotlight;
}
whitehouse_spotlight()
{
self endon( "death" );
target_struct = getstruct( self.target, "targetname" );
target_struct.ent = spawn( "script_origin", target_struct.origin );
self settargetentity( target_struct.ent );
self waittill( "turret_on_target" );
self thread whitehouse_spotlight_flicker();
self thread whitehouse_spotlight_damage();
self thread whitehouse_spotlight_pathing( target_struct );
// self thread whitehouse_spotlight_targeting();
}
whitehouse_spotlight_pathing( target_struct )
{
self endon( "death" );
target_ent = target_struct.ent;
while( true )
{
if ( isdefined( target_struct.script_speed ) )
{
time = target_struct.script_speed/1000; // hacky use of speed to set the convergence time.
self SetConvergenceTime( time, "yaw" );
self SetConvergenceTime( time, "pitch" );
}
target_ent delete();
target_ent = spawn( "script_origin", target_struct.origin );
self settargetentity( target_ent );
self waittill( "turret_on_target" );
if ( isdefined( target_struct.script_flag_set ) )
flag_set( target_struct.script_flag_set );
target_struct script_delay();
if ( isdefined( target_struct.script_flag_wait ) )
flag_wait( target_struct.script_flag_wait );
if ( !isdefined( target_struct.target ) )
break;
target_struct_array = getstructarray( target_struct.target, "targetname" );
target_struct = random( target_struct_array );
}
}
whitehouse_spotlight_flicker()
{
self endon( "death" );
flickers = randomintrange( 3, 5 );
for ( i=0; i<flickers; i++ )
{
PlayFXOnTag( level._effect[ "_attack_heli_spotlight" ], self, "tag_flash" );
wait randomfloatrange( 0.05, 0.15 );
waittillframeend;
StopFXOnTag( level._effect[ "_attack_heli_spotlight" ], self, "tag_flash" );
wait randomfloatrange( 0.05, 0.15 );
waittillframeend;
}
wait .1;
PlayFXOnTag( level._effect[ "_attack_heli_spotlight" ], self, "tag_flash" );
}
whitehouse_spotlight_damage()
{
self endon( "spotlight_delete" );
health = self.damage_ent.health;
self.damage_ent waittill_friendly_damage( health );
StopFXOnTag( level._effect[ "_attack_heli_spotlight" ], self, "tag_flash" );
self notify( "death" );
fx = getfx( "spotlight_spark" );
fx_origin = self.origin;
PlayFX( fx, fx_origin );
wait 0.3;
PlayFX( fx, fx_origin + ( 0, 8, 8 ) );
wait 0.5;
PlayFX( fx, fx_origin + ( 0, -12, 4 ) );
wait 0.3;
PlayFX( fx, fx_origin + ( 0, 4, -8 ) );
self delete();
}
manual_mg_init( delay )
{
self endon( "death" );
if( isdefined( delay ) )
wait randomint( 3 );
self thread manual_mg_drone();
self setmode( "auto_nonai" ); //"manual", "manual_ai", "auto_nonai", "auto_ai", "sentry"
self setturretteam( "axis" );
self setbottomarc( 35 );
self setleftarc( 90 );
self setrightarc( 90 );
self thread manual_mg_fire();
if ( level.live_mg_count > 0 )
{
if ( isdefined( self.target ) )
self thread manual_mg_path();
}
level.live_mg_count--;
if ( isdefined( self.script_group ) )
{
level waittill( "sandbag_group_" + self.script_group );
self thread manual_mg_stop();
}
}
manual_mg_drone()
{
self endon( "death" );
drone_spawner = self get_linked_ent();
self.drone = drone_spawner spawn_ai( true );
self.drone.health = 250;
self.drone waittill( "death" );
level notify( "sandbag_group_" + self.script_group );
}
manual_mg_fire()
{
self endon( "stop_firing" );
while( true )
{
timer = randomfloatrange( 1, 2.5 ) * 20;
for ( i = 0; i < timer; i++ )
{
self shootturret();
wait( 0.05 );
}
wait randomfloatrange( 1, 3);
}
}
manual_mg_path( start_target, noloop )
{
self endon( "stop_path" );
self SetConvergenceTime( 4, "yaw" );
self SetConvergenceTime( 2, "pitch" );
self SetAISpread( 0.4 );
self SetMode( "manual" );
if ( isdefined( start_target ) )
self.current_target = start_target;
else
self.current_target = getstruct( self.target, "targetname" );
target_ent = spawn( "script_origin", self.current_target.origin );
while( true )
{
if ( isdefined( self.current_target.script_speed ) )
{
time = self.current_target.script_speed/1000; // hacky use of speed to set the convergence time.
self SetConvergenceTime( time, "yaw" );
self SetConvergenceTime( time, "pitch" );
}
target_ent delete();
target_ent = spawn( "script_origin", self.current_target.origin );
self settargetentity( target_ent );
self turret_on_target( self.current_target );
if ( isdefined( self.current_target.target ) )
self.current_target = getstruct( self.current_target.target, "targetname" );
else if ( isdefined( self.target ) )
self.current_target = getstruct( self.target, "targetname" );
else
break;
}
target_ent delete();
}
manual_mg_stop( delay )
{
self endon( "death" );
if ( isdefined( delay ) )
{
delay = delay * 3;
wait randomfloatrange( delay, delay+2 );
}
if ( isdefined( self ) )
{
self notify( "stop_path" );
self notify( "stop_firing" );
}
if ( isalive( self.drone ) )
self.drone kill();
self delete();
}
manual_mg_threat_trigger( turret )
{
level endon( "whitehouse_breached" );
self waittill( "trigger" );
if ( flag( "mg_threat" ) )
return;
turret setmode( "manual" );
turret setturretteam( "axis" );
turret setbottomarc( 45 );
turret SetConvergenceTime( 0.25, "yaw" );
turret SetConvergenceTime( 0.25, "pitch" );
flag_set( "mg_threat" );
start_target = getstruct( self.target, "targetname" );
target_ent = spawn( "script_origin", start_target.origin );
turret settargetentity( target_ent );
turret waittill( "turret_on_target" );
target_ent delete();
turret thread manual_mg_fire();
turret manual_mg_path( start_target );
turret notify( "stop_firing" );
flag_clear( "mg_threat" );
}
magic_rpg_setup()
{
trigger_arr = getentarray( "magic_rpg_trigger", "targetname" );
array_thread( trigger_arr, ::magic_rpg_trigger );
}
magic_rpg_trigger()
{
self waittill( "trigger" );
source_arr = getstructarray( self.target, "targetname" );
foreach( source in source_arr )
{
target_arr = getstructarray( source.target, "targetname" );
array_thread( target_arr, ::magic_rpg, source );
}
}
magic_rpg( source )
{
self script_delay();
rocket = MagicBullet( "rpg_straight", source.origin, self.origin );
}
sandbag_group_setup( str_targetname )
{
sandbag_group_create_models( str_targetname );
sandbag_array = getentarray( str_targetname, "targetname" );
group_array = [];
foreach( sandbag in sandbag_array )
{
group_id = sandbag.script_group;
if ( !isdefined( group_array[ group_id ] ) )
group_array[ group_id ] = [];
index = group_array[ group_id ].size;
group_array[ group_id ][ index ] = sandbag;
}
// used to calculate the vector to throw the bags for these groups.
force_struct = getstruct( str_targetname, "script_noteworthy" );
foreach( group in group_array )
{
level thread sandbag_group( group, force_struct );
}
}
sandbag_group_create_models( str_targetname )
{
struct_arr = getstructarray( str_targetname, "targetname" );
foreach( struct in struct_arr )
{
model = spawn( "script_model", struct.origin );
model.angles = struct.angles;
model setmodel( struct.script_modelname );
model.script_group = struct.script_group;
model.script_index = struct.script_index;
model.script_parameters = struct.script_parameters;
model.targetname = struct.targetname;
struct = undefined;
}
}
sandbag_group( sandbag_array, force_struct )
{
group_struct = SpawnStruct();
group_struct.hit_count = 0;
array_thread( sandbag_array, ::sandbag_damage, group_struct );
// vector hardcoded since that works for me in DCemp.
vector = anglestoforward( force_struct.angles );
// vector = anglestoforward( (345, 180, 0) );
force = vector * 3000;
while( sandbag_array.size )
{
group_struct waittill( "damage", damaged_ent, damage );
// lets all damaged bags report in.
waittillframeend;
if ( damage > 500 )
{
group_struct.hit_count = max( group_struct.hit_count, int( sandbag_array.size * 0.75 ) );
level notify( "sandbag_group_" + damaged_ent.script_group );
}
for ( i = 0; i < group_struct.hit_count; i++ )
{
if ( i==0 )
{
bag = find_lowest_indexed_ent( sandbag_array, damaged_ent );
if ( isdefined( bag.script_parameters ) )
{
group_struct.hit_count = sandbag_array.size;
level notify( "sandbag_group_" + bag.script_group );
}
}
else
bag = find_lowest_indexed_ent( sandbag_array );
bag notify( "thrown" );
sandbag_array = array_remove( sandbag_array, bag );
bag PhysicsLaunchClient( bag.origin, force );
}
group_struct.hit_count = 0;
group_struct notify( "throw_done" );
}
}
find_lowest_indexed_ent( ent_array, damaged_ent )
{
current_index = 1000000;
final_ent = undefined;
foreach( ent in ent_array )
{
if ( ent.script_index > current_index )
continue;
current_index = ent.script_index;
final_ent = ent;
}
if ( isdefined( damaged_ent ) && final_ent.script_index == damaged_ent.script_index )
return damaged_ent;
return final_ent;
}
sandbag_damage( group_struct )
{
self endon( "thrown" );
self.health = 10000;
self SetCanDamage( true );
while( true )
{
damage = self waittill_friendly_damage( 100 );
group_struct.hit_count++;
group_struct notify( "damage", self, damage );
group_struct waittill( "throw_done" );
}
}
whitehouse_cleanup_approach()
{
// kill east side enemies and friendly mg guys
allied_mg = get_ai_group_ai( "allied_mg" );
foreach( ai in allied_mg )
ai kill();
enemies = get_ai_group_ai( "whitehouse_approach_enemies" );
array_thread( enemies, ::random_delayed_kill, 10, 15 );
// make enemies ignore the player.
array_call( enemies, ::setthreatbiasgroup, "ignore_player" );
flag_wait( "whitehouse_entrance_init" );
// stop enemy MGs
mg_array = getentarray( "manual_mg", "script_noteworthy" );
mg_array = array_add( mg_array, getent( "west_side_mg", "script_noteworthy" ) );
for( i=0; i<mg_array.size; i++ )
mg_array[i] thread manual_mg_stop( i+1 );
flag_wait( "whitehouse_entrance_clear" );
enemies = get_ai_group_ai( "westwing_roof_enemies" );
array_thread( enemies, ::random_delayed_kill, 5, 15 );
flag_wait( "whitehouse_breached" );
// kill remaining exterior enemies
axis_arr = getaiarray( "axis" );
array_call( axis_arr, ::kill );
flag_wait( "whitehouse_path_kitchen" );
// delete exterior allies
ai_arr = getaiarray( "allies" );
foreach( ai in ai_arr )
{
if ( ai is_hero() )
continue;
ai random_delayed_kill( 4, 10, true );
}
}
whitehouse_mg_setup()
{
level.live_mg_count = ( level.gameskill - 1 ); // 2 live mg's on Veteran and one on Hardened.
mg_array = getentarray( "manual_mg", "script_noteworthy" );
array_thread( mg_array, ::manual_mg_init, true );
// trigger that activates the turret to fire infront of the player.
turret = getent( "threat_mg", "targetname" );
trigger_array = getentarray( "mg_threat_trigger", "targetname" );
array_thread( trigger_array, ::manual_mg_threat_trigger, turret );
turret thread mg_delete();
}
westwing_mg_setup()
{
ai_spread = 2;
convergance_time = 1.5;
switch( level.gameskill )
{
case 0: // recruit
ai_spread = 5;
convergance_time = 2;
break;
case 1: // regular
ai_spread = 4;
convergance_time = 2;
break;
}
mg_array = getentarray( "westwing_mg", "script_noteworthy" );
foreach( mg in mg_array )
{
mg SetAISpread( ai_spread );
mg setconvergencetime( convergance_time );
}
}
mg_delete()
{
flag_wait( "whitehouse_breached" );
self delete();
}
whitehouse_drone_slaughter()
{
flag_wait( "whitehouse_silhouette_ready");
rocket_source_arr = getentarray( "drone_rocket_source", "targetname" );
drones = array_removeDead( level.whitehouse_drone_array );
index = 0;
while( drones.size )
{
source = rocket_source_arr[ index % rocket_source_arr.size ];
MagicBullet( "rpg_straight", source.origin, random( drones ).origin );
wait randomfloat( 2 );
drones = array_removeDead( level.whitehouse_drone_array );
index++;
}
flag_set( "whitehouse_silhouette_over");
}
whitehouse_rappel_setup()
{
array_spawn_function_noteworthy( "whitehouse_rappel_ai", ::whitehouse_rappel );
}
whitehouse_rappel( data_struct )
{
self endon( "death" );
anim_ent = getent( self.target, "targetname" );
self enable_achievement_harder_they_fall();
rope = spawn_anim_model( "rope", anim_ent.origin );
rope thread whitehouse_rappel_delete_rope();
ents = [];
ents[0] = self;
ents[1] = rope;
index = randomintrange( 1, 3 );
self.animname = "rappel_guy";
self.allowdeath = true;
self.ignoreme = true;
anim_ent thread anim_loop( ents , "rappel_stand_idle_" + index, "stop_loop" );
anim_ent script_delay();
anim_ent anim_stopanimscripted();
anim_ent anim_single( ents , "rappel_drop" , undefined, 4.3 );
self disable_achievement_harder_they_fall();
ent = getent( "rappel_goal", "targetname" );
self setgoalpos( ent.origin );
self.goalradius = 1024;
self.goalheight = 128;
self.ignoreme = false;
}
whitehouse_rappel_delete_rope()
{
self waittill_match_or_timeout( "single anim", "end", 10 );
flag_wait( "whitehouse_rappel_delete_rope" );
self delete();
}
fake_flare( delay, tag, origin_offset, angles_offset )
{
wait delay;
flare = spawn( "script_model", (0,0,0) );
flare setmodel( "mil_emergency_flare" );
flare LinkTo( self, tag, origin_offset, angles_offset );
PlayFXOnTag( level._effect[ "green_flare" ] , flare, "tag_fire_fx" );
wait 12;
StopFXOnTag( level._effect[ "green_flare" ] , flare, "tag_fire_fx" );
wait 0.5;
flare delete();
}
flare_fx_start( guy )
{
guy endon( "death" );
// don't do flares if player is not looking
if ( !flag( "player_looking_at_flareguy" ) )
return false;
// start middle anim when player is looking.
guy PlaySound( "scn_dcwhite_npc_flare_start" );
flare = spawn( "script_model", (0,0,0) );
flare setmodel( "mil_emergency_flare" );
flare LinkTo( guy, "tag_weapon_left", (0,0,0), (0,0,0) );
flare thread play_flare_fx( guy );
guy thread play_flare_fx( guy );
flag_wait( "flare_guy_drop_flares" );
guy notify( "stop_flare_fx" );
flare notify( "stop_flare_fx" );
flare unlink();
flare delete();
guy Detach( "mil_emergency_flare", "tag_inhand" );
}
play_flare_fx( guy )
{
guy endon( "death" );
playfxontag( getfx( "green_flare_ignite" ), self, "tag_fire_fx" );
level endon( "whitehouse_hammerdown" );
self endon( "stop_flare_fx" );
while ( true )
{
wait( .1 );
playfxontag( getfx( "green_flare" ), self, "tag_fire_fx" );
}
}
flare_weapon()
{
self endon( "remove_flare" );
// thread flag_set_delayed( "remove_flare_hint", 3 );
self.old_weapon = self getcurrentprimaryweapon();
level.player AllowFire( false );
level.player GiveWeapon( "flare" );
level.player switchtoweapon( "flare" );
level.player DisableWeaponSwitch();
level.player disableoffhandweapons();
wait 0.5;
display_hint( "how_to_pop_flare" );
level.player AllowFire( true );
// wait 2;
// self ForceViewmodelAnimation( "flare", "fire" );
self waittill( "weapon_fired" );
flag_set( "player_flare_popped" );
self waittill( "end_firing" );
level.player TakeWeapon( "flare" );
level.player EnableWeaponSwitch();
level.player EnableOffhandWeapons();
// switch back to old weapon or the first primary if old weapon is invalid.
self.old_weapon = self can_switch_to_weapon( self.old_weapon );
level.player switchtoweapon( self.old_weapon );
}
stop_flare_hint()
{
return ( flag( "player_flare_popped" ) || flag( "remove_flare_hint" ) );
}
can_switch_to_weapon( weapon )
{
primary = self getweaponslistprimaries()[0];
if ( !isdefined( weapon ) )
return primary;
if ( !self hasweapon( weapon ) )
return primary;
return weapon;
}
door_open_kick()
{
wait( 0.4 );
self PlaySound( "door_wood_double_kick" );
self ConnectPaths();
self RotateTo( self.angles + ( 0, 90, 0 ), .5, .1, 0 );
self waittill( "rotatedone" );
self RotateTo( self.angles + ( 0, -10, 0 ), .3, 0, .3 );
self waittill( "rotatedone" );
self RotateTo( self.angles + ( 0, 5, 0 ), .3, 0.15, 0.15 );
}
waittill_player_damage( damage_limit )
{
if ( !isdefined( damage_limit ) )
damage_limit = 0;
state = false;
total_damage = 0;
while ( !state )
{
self waittill( "damage", damage, attacker );
if ( attacker == level.player )
total_damage += damage;
state = ( total_damage > damage_limit );
}
return total_damage;
}
waittill_friendly_damage( damage_limit )
{
if ( !isdefined( damage_limit ) )
damage_limit = 0;
state = false;
total_damage = 0;
while ( !state )
{
self waittill( "damage", damage, attacker );
assert( isdefined( attacker ) );
if ( isdefined( attacker.team ) && attacker.team == "allies" )
total_damage += damage;
state = ( total_damage > damage_limit );
}
return total_damage;
}
turret_on_target( target_ent )
{
self waittill( "turret_on_target" );
while( true )
{
aim_vector = anglestoforward( self gettagangles( "tag_flash" ) );
target_vector = vectornormalize( target_ent.origin - self.origin );
dot = vectordot( aim_vector, target_vector );
if ( dot > 0.9999 )
return;
wait 0.05;
}
}
random_delayed_kill( min_delay, max_delay, check_sight )
{
enemy_team = [];
enemy_team[ "allies" ] = "axis";
enemy_team[ "axis" ] = "allies";
self endon( "death" );
while( true )
{
wait randomfloatrange( min_delay, max_delay );
// don't kill if guy can see player.
if ( isdefined( check_sight ) && self CanSee( level.player ) )
continue;
enemies = getaiarray( enemy_team[ self.team ] );
enemies = SortByDistance( enemies, self.origin );
guy = enemies[0];
if ( isdefined( guy ) )
self Kill( guy geteye(), guy );
else
self Kill( self geteye() );
}
}
chandelier_setup()
{
chandelier_arr = getentarray( "chandelier", "targetname" );
array_thread( chandelier_arr, ::chandelier );
}
chandelier()
{
// get all parts
parts = getentarray( self.target, "targetname" );
self.wire = parts[0];
self.light = parts[1];
if ( parts[0].classname != "script_model" )
{
self.wire = parts[1];
self.light = parts[0];
}
if ( isdefined( self.wire.target ) )
{
ceiling_struct = getstruct( self.wire.target, "targetname" );
ceiling = ceiling_struct.origin;
}
else
ceiling = PhysicsTrace( self.origin, self.origin + ( 0,0,80 ) );
self.swing_origin = spawn( "script_origin", ceiling );
self.swing = false;
// connect all parts
self linkto( self.swing_origin );
self.wire linkto( self.swing_origin );
self thread chandelier_link_light();
// turn light on
self.light SetLightIntensity( 1.5 );
self thread chandelier_react();
}
chandelier_react()
{
self endon( "chandelier_fall" );
self SetCanDamage( true );
self SetCanRadiusDamage( true );
while( true )
{
self waittill( "damage", damage, attacker, direction_vec, point, type );
if ( common_scripts\_destructible::getDamageType( type ) != "splash" )
continue;
self thread chandelier_swing( damage, direction_vec );
self thread chandelier_flicker();
if ( isdefined( self.script_parameters ) )
self thread chandelier_fall();
}
}
chandelier_swing( damage, direction_vec )
{
self.swing = true;
self notify( "chandelier_swing" );
self endon( "chandelier_swing" );
damage = clamp( damage, 0, 80 );
multiplier = damage / 100;
angle = 75 * multiplier;
swing_speed = 0.4;
weight_vector = vectornormalize( ( direction_vec[0] * -1, direction_vec[1], 0 ) );
rotation = ( angle * weight_vector[0], 0, angle * weight_vector[1]);
// first fast rotation from explosion
self.swing_origin rotateto( rotation, swing_speed, 0, swing_speed );
self.swing_origin waittill( "rotatedone" );
while( abs( angle ) > 2 )
{
angle *= -0.75;
rotation = ( angle*weight_vector[0], 0, angle*weight_vector[1] );
self.swing_origin rotateto( rotation, swing_speed * 2, swing_speed, swing_speed );
self.swing_origin waittill( "rotatedone" );
self notify( "chandelier_turn" );
}
self.swing_origin rotateto( ( 0,0,0 ), swing_speed * 2, swing_speed, swing_speed );
self.swing_origin waittill( "rotatedone" );
self.swing = false;
self notify( "chandelier_turn" );
}
chandelier_flicker()
{
self endon( "chandelier_fall" );
self endon( "chandelier_swing" );
wait .5; // total wait ~5.4 sec.
for( i=0; i<14; i++ )
{
self.light SetLightIntensity( 0 );
self setmodel( "furniture_chandelier1_off" );
wait randomfloatrange( 0.05, 0.2 ); // ~0.125
self.light SetLightIntensity( randomfloatrange( 0.5, 1.5 ) );
self setmodel( "furniture_chandelier1" );
wait randomfloatrange( 0.15, 0.3 ); // ~0.225
}
self.light SetLightIntensity( 1.5 );
}
chandelier_fall()
{
self endon( "chandelier_swing" );
center_origin = self.light_origin.origin;
wait randomfloatrange( 1, 4 );
self notify( "chandelier_fall" );
self.light SetLightIntensity( 4 );
self setmodel( "furniture_chandelier1" );
wait 0.05;
self.light SetLightIntensity( 0 );
self setmodel( "furniture_chandelier1_off" );
PlayFX( level._effect[ "wire_spark" ], self.origin );
if ( self.swing )
self waittill( "chandelier_turn" );
self unlink();
vector = center_origin - self.light_origin.origin;
self physicslaunchclient( self.light_origin.origin, vector * 2);
}
chandelier_link_light()
{
self endon( "chandelier_fall" );
self.light_origin = spawn( "script_origin", self.light.origin );
self.light_origin linkto( self );
while( true )
{
self waittill( "chandelier_swing" );
while( self.swing )
{
self.light.origin = self.light_origin.origin;
wait 0.05;
}
}
}
chandelier_get( noteworthy )
{
ent_arr = getentarray( noteworthy, "script_noteworthy");
chandelier = undefined;
foreach( chandelier in ent_arr )
{
if ( chandelier.targetname == "chandelier" )
break;
}
return chandelier;
}
chandelier_force_swing( damage, direction_vec )
{
if ( !isdefined( direction_vec ) )
direction_vec = (10,10,0);
self notify( "damage", damage, undefined, direction_vec, undefined, "mod_grenade_splash" );
}
player_attached_use( hintstring )
{
ent = Spawn( "script_origin", level.player.origin + (0,0,32) );
ent makeusable();
ent sethintstring( hintstring );
ent linkto( level.player );
level thread set_flag_on_trigger( ent, "remove_use_hint" );
flag_wait( "remove_use_hint" );
ent delete();
}
elapsed_time( start_time )
{
return int( ( gettime() - start_time ) / 1000 );
}
rotate_vector( vector, rotation )
{
right = anglestoright( rotation ) * -1;
forward = anglestoforward( rotation );
up = anglestoup( rotation );
new_vector = forward * vector[ 0 ] + right * vector[ 1 ] + up * vector[ 2 ];
return new_vector;
}
simple_drone_init()
{
self useAnimTree( #animtree );
self setCanDamage( true );
}
/*
tunnels_teleport()
{
trigger = getent( "tunnels_teleport_trigger", "targetname" );
trigger waittill( "trigger" );
flag_set( "tunnels_teleport" );
// fx_rain_pause();
// fx_rain_pause2();
while( !level.player IsOnGround() )
wait 0.05;
flag_set( "end_fx" );
// teleport player
start_ent = getent( trigger.target, "targetname" );
target_ent = getent( start_ent.target, "targetname" );
angles_rotation = target_ent.angles - start_ent.angles;
origin_offset = level.player.origin - start_ent.origin;
origin_offset = rotate_vector( origin_offset, angles_rotation );
player_angles_offset = level.player getplayerangles() - start_ent.angles;
destination_origin = target_ent.origin + origin_offset;
destination_angles = target_ent.angles + player_angles_offset;
level.player SetOrigin( destination_origin );
level.player setplayerangles( destination_angles );
SetNorthYaw( 0.0 );
// teleport ai
volume = getent( "tunnels_teleport_volume", "targetname" );
dest_arr = getstructarray( "tunnels_teleport_struct", "targetname" );
index = 0;
angles_rotation = target_ent.angles - start_ent.angles;
foreach( ai in level.team )
{
origin_offset = ai.origin - start_ent.origin;
origin_offset = rotate_vector( origin_offset, angles_rotation );
ai_angles_offset = ai.angles - start_ent.angles;
destination_origin = target_ent.origin + origin_offset;
destination_angles = target_ent.angles + ai_angles_offset;
// if ( !goal_in_volume( destination_origin, volume ) )
// {
// destination_origin = dest_arr[ index ].origin;
// destination_angles = dest_arr[ index ].angles;
// index++;
// }
ai ForceTeleport( destination_origin, destination_angles );
}
flag_set( "tunnels_teleport_done" );
}
*/
goal_in_volume( origin, volume )
{
ent = spawn( "script_model", origin );
state = ent IsTouching( volume );
ent delete();
return state;
}
remove_drone_weapon()
{
size = self GetAttachSize();
for ( i=0; i<size; i++ )
{
model_name = self GetAttachModelName( i );
tag_name = self GetAttachTagName( i );
if ( IsSubStr( model_name, "weapon" ) )
self detach( model_name, tag_name );
}
}
force_flash_setup()
{
array = getentarray( "force_flash", "targetname" );
array_thread( array, ::force_flash );
}
force_flash()
{
self waittill( "trigger" );
thread maps\_weather::lightningFlash( maps\dc_whitehouse_fx::lightning_normal, maps\dc_whitehouse_fx::lightning_flash );
}
/***************************/
/***** new since split *****/
/***************************/
spawn_team()
{
spawner_arr = getentarray( "team", "targetname" );
array_thread( spawner_arr, ::add_spawn_function, ::team_init, spawner_arr.size );
activate_trigger_with_targetname( "team_trigger" );
flag_wait( "team_initialized" );
}
team_init( team_size )
{
add_team( self );
if( isdefined( self.script_noteworthy ) )
{
if( self.script_noteworthy == "foley" )
{
self thread magic_bullet_shield();
self make_hero();
level.foley = self;
}
if( self.script_noteworthy == "dunn" )
{
self thread magic_bullet_shield();
self make_hero();
level.dunn = self;
}
}
if( level.team.size == team_size )
flag_set( "team_initialized" );
}
add_team( team )
{
array = [];
if( !isarray( team ) )
array[ array.size ] = team;
else
array = team;
array_thread( array, ::remove_team );
foreach( member in array )
{
if( isdefined( member.script_noteworthy ) )
{
member.animname = member.script_noteworthy;
level.team[ member.script_noteworthy ] = member;
}
else
level.team[ level.team.size ] = member;
}
}
remove_team()
{
self notify( "remove_team" );
self endon( "remove_team" );
self waittill( "death" );
level.team = array_removedead_keepkeys( level.team );
}
set_color_goal_func()
{
self.colornode_func = ::colornode_do_stuff_on_goal;
}
colornode_do_stuff_on_goal( node )
{
self endon( "stop_going_to_node" );
self endon( "stop_color_move" );
self endon( "death" );
self waittill( "goal" );
if ( isdefined( node.script_flag_set ) )
flag_set( node.script_flag_set );
node notify( "trigger", self );
}
dcwh_teleport_player( name )
{
if ( !isdefined( name ) )
name = level.start_point;
array = getstructarray( "start_point", "targetname" );
nodes = [];
foreach ( ent in array )
{
if ( ent.script_noteworthy != name )
continue;
nodes[ nodes.size ] = ent;
}
teleport_players( nodes );
}
dcwh_teleport_team( team, nodes )
{
index = 0;
foreach( actor in team )
{
actor thread dcwh_teleport_actor( nodes[ index ] );
//actor thread dcwh_teleport_actor( nodes[ index ] );
index++;
}
}
dcwh_teleport_actor( eNode )
{
AssertEx( IsAI( self ), "Function teleport_ai can only be called on an AI entity" );
AssertEx( IsDefined( eNode ), "Need to pass a node entity to function teleport_ai" );
self ForceTeleport( eNode.origin, eNode.angles );
self SetGoalPos( self.origin );
}
blind_enemies()
{
self endon( "death" );
self.baseAccuracy = 0.1;
self.health = 200;
flag_wait( "whitehouse_path_office" );
self kill( level.player.origin );
}
fade_out_level( fadeOutTime )
{
setSavedDvar( "compass", 0 );
setSavedDvar( "hud_showStance", 0 );
overlay = newHudElem();
overlay.x = 0;
overlay.y = 0;
overlay setshader( "black", 640, 480 );
overlay.alignX = "left";
overlay.alignY = "top";
overlay.horzAlign = "fullscreen";
overlay.vertAlign = "fullscreen";
overlay.alpha = 0;
overlay fadeOverTime( fadeOutTime );
overlay.alpha = 1;
wait fadeOutTime;
level.player freezeControls( true );
enablePlayerWeapons( false );
}
flickerlight_flares()
{
wait randomfloatrange( .05, .5 );
intensity = self getlightintensity();
while( 1 )
{
self setlightintensity( intensity * randomfloatrange( .8, 1.1 ) );
wait .05;
}
}
/*
step_obj( obj_id, ent )
{
level endon( "whitehouse_radio" );
while( isdefined( ent.target ) )
{
trigger = Spawn( "trigger_radius", ent.origin, 0, ent.radius, 72 );
trigger waittill( "trigger" );
trigger delete();
if ( isdefined( self.script_flag_wait ) )
flag_wait( self.script_flag_wait );
ent = getstruct( ent.target, "targetname" );
objective_Position( obj_id, ent.origin );
}
}
*/
| 0 | 0.934094 | 1 | 0.934094 | game-dev | MEDIA | 0.99278 | game-dev | 0.914969 | 1 | 0.914969 |
Potion-Studios/BYG | 4,298 | Common/src/main/java/potionstudios/byg/common/world/feature/gen/nether/sythiantorrids/SythianStalk.java | package potionstudios.byg.common.world.feature.gen.nether.sythiantorrids;
import com.mojang.serialization.Codec;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.BambooStalkBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.BambooLeaves;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.levelgen.feature.Feature;
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
import net.minecraft.world.level.levelgen.feature.configurations.ProbabilityFeatureConfiguration;
import potionstudios.byg.common.block.BYGBlocks;
public class SythianStalk extends Feature<ProbabilityFeatureConfiguration> {
private static final BlockState BAMBOO_BASE;
private static final BlockState BAMBOO_LARGE_LEAVES_GROWN;
private static final BlockState BAMBOO_LARGE_LEAVES;
private static final BlockState BAMBOO_SMALL_LEAVES;
public SythianStalk(Codec<ProbabilityFeatureConfiguration> config) {
super(config);
}
@Override
public boolean place(FeaturePlaceContext<ProbabilityFeatureConfiguration> featurePlaceContext) {
return place(featurePlaceContext.level(), featurePlaceContext.chunkGenerator(), featurePlaceContext.random(), featurePlaceContext.origin(), featurePlaceContext.config());
}
public boolean place(WorldGenLevel world, ChunkGenerator generator, RandomSource rand, BlockPos pos, ProbabilityFeatureConfiguration config) {
int aNumber = 0;
BlockPos.MutableBlockPos mutable = new BlockPos.MutableBlockPos().set(pos);
BlockPos.MutableBlockPos mutable2 = new BlockPos.MutableBlockPos().set(pos);
if (world.isEmptyBlock(mutable)) {
if (BYGBlocks.SYTHIAN_STALK_BLOCK.defaultBlockState().canSurvive(world, mutable)) {
int randSpawnHeight = rand.nextInt(12) + 5;
int randNextInt;
if (rand.nextFloat() < config.probability) {
randNextInt = rand.nextInt(4) + 1;
for (int x = pos.getX() - randNextInt; x <= pos.getX() + randNextInt; ++x) {
for (int z = pos.getZ() - randNextInt; z <= pos.getZ() + randNextInt; ++z) {
int xBuild = x - pos.getX();
int zBuild = z - pos.getZ();
if (xBuild * xBuild + zBuild * zBuild <= randNextInt * randNextInt) {
mutable2.set(x, world.getHeight(Heightmap.Types.WORLD_SURFACE, x, z) - 1, z);
if (isDirt(world.getBlockState(mutable2))) {
world.setBlock(mutable2, BYGBlocks.SYTHIAN_NYLIUM.defaultBlockState(), 2);
}
}
}
}
}
for (randNextInt = 0; randNextInt < randSpawnHeight && world.isEmptyBlock(mutable); ++randNextInt) {
world.setBlock(mutable, BAMBOO_BASE, 2);
mutable.move(Direction.UP, 1);
}
if (mutable.getY() - pos.getY() >= 3) {
world.setBlock(mutable, BAMBOO_LARGE_LEAVES_GROWN, 2);
world.setBlock(mutable.move(Direction.DOWN, 1), BAMBOO_LARGE_LEAVES, 2);
world.setBlock(mutable.move(Direction.DOWN, 1), BAMBOO_SMALL_LEAVES, 2);
}
}
++aNumber;
}
return aNumber > 0;
}
static {
BAMBOO_BASE = BYGBlocks.SYTHIAN_STALK_BLOCK.defaultBlockState().setValue(BambooStalkBlock.AGE, 1).setValue(BambooStalkBlock.LEAVES, BambooLeaves.NONE).setValue(BambooStalkBlock.STAGE, 0);
BAMBOO_LARGE_LEAVES_GROWN = BAMBOO_BASE.setValue(BambooStalkBlock.LEAVES, BambooLeaves.LARGE).setValue(BambooStalkBlock.STAGE, 1);
BAMBOO_LARGE_LEAVES = BAMBOO_BASE.setValue(BambooStalkBlock.LEAVES, BambooLeaves.LARGE);
BAMBOO_SMALL_LEAVES = BAMBOO_BASE.setValue(BambooStalkBlock.LEAVES, BambooLeaves.SMALL);
}
} | 0 | 0.679741 | 1 | 0.679741 | game-dev | MEDIA | 0.990304 | game-dev | 0.947922 | 1 | 0.947922 |
Secrets-of-Sosaria/World | 6,126 | Data/Scripts/Magic/Magery/Spells/Magery 8th/Resurrection.cs | using System;
using Server.Targeting;
using Server.Network;
using Server.Gumps;
using Server.Mobiles;
using Server.Items;
using System.Collections;
using System.Collections.Generic;
namespace Server.Spells.Eighth
{
public class ResurrectionSpell : MagerySpell
{
private static SpellInfo m_Info = new SpellInfo(
"Resurrection", "An Corp",
245,
9062,
Reagent.Bloodmoss,
Reagent.Garlic,
Reagent.Ginseng
);
public override SpellCircle Circle { get { return SpellCircle.Eighth; } }
public ResurrectionSpell( Mobile caster, Item scroll ) : base( caster, scroll, m_Info )
{
}
public override void OnCast()
{
Caster.Target = new InternalTarget( this );
}
public void Target( Mobile m )
{
if ( !Caster.CanSee( m ) )
{
Caster.SendLocalizedMessage( 500237 ); // Target can not be seen.
}
else if ( m == Caster && CheckBSequence( m, true ) )
{
ArrayList targets = new ArrayList();
foreach ( Item item in World.Items.Values )
if ( item is SoulOrb )
{
SoulOrb myOrb = (SoulOrb)item;
if ( myOrb.m_Owner == m )
{
targets.Add( item );
}
}
for ( int i = 0; i < targets.Count; ++i )
{
Item item = ( Item )targets[ i ];
item.Delete();
}
m.PlaySound( 0x214 );
m.FixedEffect( 0x376A, 10, 16, Server.Misc.PlayerSettings.GetMySpellHue( true, Caster, 0 ), 0 );
m.SendMessage( "You summon a magical orb to protect your soul." );
SoulOrb iOrb = new SoulOrb();
iOrb.m_Owner = m;
m.AddToBackpack( iOrb );
Server.Items.SoulOrb.OnSummoned( m, iOrb );
}
else if ( m == Caster )
{
Caster.SendMessage("You failed to summon an orb.");
}
else if ( !Caster.Alive )
{
Caster.SendLocalizedMessage( 501040 ); // The resurrecter must be alive.
}
else if (m.Alive)
{
Caster.SendLocalizedMessage( 501041 ); // Target is not dead.
}
else if ( !Caster.InRange( m, 2 ) )
{
Caster.SendLocalizedMessage( 501042 ); // Target is not close enough.
}
else if ( m.Map == null || !m.Map.CanFit( m.Location, 16, false, false ) )
{
Caster.SendLocalizedMessage( 501042 ); // Target can not be resurrected at that location.
m.SendLocalizedMessage( 502391 ); // Thou can not be resurrected there!
}
else if ( m is PlayerMobile && CheckBSequence( m, true ) )
{
SpellHelper.Turn( Caster, m );
m.PlaySound( 0x214 );
m.FixedEffect( 0x376A, 10, 16, Server.Misc.PlayerSettings.GetMySpellHue( true, Caster, 0 ), 0 );
m.CloseGump( typeof( ResurrectGump ) );
m.SendGump( new ResurrectGump( m, Caster ) );
}
else if (m is BaseCreature && CheckBSequence( m, true ) )
{
BaseCreature pet = (BaseCreature)m;
Mobile master = pet.GetMaster();
SpellHelper.Turn( Caster, m );
m.PlaySound( 0x214 );
m.FixedEffect( 0x376A, 10, 16, Server.Misc.PlayerSettings.GetMySpellHue( true, Caster, 0 ), 0 );
master.CloseGump(typeof(PetResurrectGump));
master.SendGump(new PetResurrectGump(master, pet));
}
FinishSequence();
}
public void ItemTarget( Item hench )
{
if ( hench is HenchmanFighterItem && CheckSequence() )
{
HenchmanFighterItem friend = (HenchmanFighterItem)hench;
if ( friend.HenchDead > 0 )
{
friend.Name = "fighter henchman";
friend.HenchDead = 0;
friend.InvalidateProperties();
Caster.PlaySound( 0x214 );
}
else
{
Caster.SendMessage("They are not dead.");
}
}
else if ( hench is HenchmanWizardItem && CheckSequence() )
{
HenchmanWizardItem friend = (HenchmanWizardItem)hench;
if ( friend.HenchDead > 0 )
{
friend.Name = "wizard henchman";
friend.HenchDead = 0;
friend.InvalidateProperties();
Caster.PlaySound( 0x214 );
}
else
{
Caster.SendMessage("They are not dead.");
}
}
else if ( hench is HenchmanArcherItem && CheckSequence() )
{
HenchmanArcherItem friend = (HenchmanArcherItem)hench;
if ( friend.HenchDead > 0 )
{
friend.Name = "archer henchman";
friend.HenchDead = 0;
friend.InvalidateProperties();
Caster.PlaySound( 0x214 );
}
else
{
Caster.SendMessage("They are not dead.");
}
}
else if (hench is HenchmanMonsterItem && CheckSequence() )
{
HenchmanMonsterItem friend = (HenchmanMonsterItem)hench;
if ( friend.HenchDead > 0 )
{
friend.Name = "creature henchman";
friend.HenchDead = 0;
friend.InvalidateProperties();
Caster.PlaySound( 0x214 );
}
else
{
Caster.SendMessage("They are not dead.");
}
}
else
{
Caster.SendMessage("This spell didn't seem to work.");
}
FinishSequence();
}
private class InternalTarget : Target
{
private ResurrectionSpell m_Owner;
public InternalTarget( ResurrectionSpell owner ) : base( 1, false, TargetFlags.Beneficial )
{
m_Owner = owner;
}
protected override void OnTarget( Mobile from, object o )
{
if ( o is Mobile )
{
m_Owner.Target( (Mobile)o );
}
else if ( o is Item )
{
m_Owner.ItemTarget( (Item)o );
}
}
protected override void OnTargetFinish( Mobile from )
{
m_Owner.FinishSequence();
}
}
}
} | 0 | 0.970669 | 1 | 0.970669 | game-dev | MEDIA | 0.985073 | game-dev | 0.996803 | 1 | 0.996803 |
CBATeam/CBA_A3 | 1,234 | addons/diagnostic/fnc_addUnitTrackProjectiles.sqf | #include "script_component.hpp"
/* ----------------------------------------------------------------------------
Function: CBA_fnc_addUnitTrackProjectiles
Description:
Adds projectile tracking to a given unit or vehicle.
Will show colored lines following a projectile's path.
Parameters:
_unit - the unit or vehicle to track <OBJECT>
Returns:
nil
Examples:
(begin example)
private _eventId = [player] call CBA_fnc_addUnitTrackProjectiles;
(end)
Author:
bux578
---------------------------------------------------------------------------- */
params [["_unit", objNull]];
if (isNull _unit) exitWith {
WARNING_1("Unit %1 is objNull.",_unit);
(-1)
};
private _arrayIndex = GVAR(projectileTrackedUnits) find _unit;
if (_arrayIndex >= 0) exitWith {
WARNING_1("Unit %1 already tracked.",_unit);
(-1)
};
private _eventId = _unit addEventHandler ["Fired", FUNC(projectileTracking_handleFired)];
_unit setVariable ["cba_projectile_firedEhId", _eventId];
GVAR(projectileTrackedUnits) pushBack _unit;
if (GVAR(projectileStartedDrawing) isEqualTo false) then {
GVAR(projectileDrawHandle) = [FUNC(projectileTracking_drawProjectilePaths), 0, []] call CBA_fnc_addPerFrameHandler;
};
| 0 | 0.869031 | 1 | 0.869031 | game-dev | MEDIA | 0.907607 | game-dev | 0.768643 | 1 | 0.768643 |
moongardenmods/allium | 1,439 | bouquet/src/main/java/dev/hugeblank/bouquet/mixin/server/network/ServerPlayerEntityMixin.java | package dev.hugeblank.bouquet.mixin.server.network;
import dev.hugeblank.bouquet.api.event.ServerEvents;
import dev.hugeblank.bouquet.util.EntityDataHolder;
import net.minecraft.block.BlockState;
import net.minecraft.server.network.ServerPlayerEntity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ServerPlayerEntity.class)
public class ServerPlayerEntityMixin{
@Inject(at = @At("HEAD"), method = "onSpawn")
private void onPlayerConnect(CallbackInfo ci) {
ServerEvents.PLAYER_JOIN.invoker().onPlayerJoin((ServerPlayerEntity)(Object) this);
}
@Inject(at = @At("HEAD"), method = "onDisconnect")
private void onDisconnect(CallbackInfo ci) {
ServerEvents.PLAYER_QUIT.invoker().onPlayerQuit((ServerPlayerEntity)(Object) this);
}
@Inject(at = @At("HEAD"), method = "onBlockCollision")
private void onBlockCollision(BlockState state, CallbackInfo ci) {
ServerEvents.PLAYER_BLOCK_COLLISION.invoker().onPlayerBlockCollision((ServerPlayerEntity)(Object) this, state);
}
@Inject(at = @At("RETURN"), method = "copyFrom")
private void allium_private$copyFrom(ServerPlayerEntity oldPlayer, boolean alive, CallbackInfo ci) {
((EntityDataHolder) this).allium_private$copyFromData(oldPlayer);
}
}
| 0 | 0.900824 | 1 | 0.900824 | game-dev | MEDIA | 0.748187 | game-dev | 0.725353 | 1 | 0.725353 |
Mercurows/SuperbWarfare | 4,115 | src/main/java/com/atsuishio/superbwarfare/entity/goal/GunShootGoal.java | package com.atsuishio.superbwarfare.entity.goal;
import com.atsuishio.superbwarfare.data.gun.FireMode;
import com.atsuishio.superbwarfare.data.gun.GunData;
import com.atsuishio.superbwarfare.data.gun.GunProp;
import com.atsuishio.superbwarfare.data.mob_guns.MobGunData;
import com.atsuishio.superbwarfare.item.gun.GunItem;
import com.atsuishio.superbwarfare.tools.MillisTimer;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.ai.goal.Goal;
// TODO 正确处理追踪距离
public class GunShootGoal<T extends Mob> extends Goal {
private final T mob;
private final MobGunData data;
private int aimTime = 0;
private final MillisTimer shootTimer = new MillisTimer();
public GunShootGoal(T mob, MobGunData data) {
this.mob = mob;
this.data = data;
}
public boolean canUse() {
return this.mob.getTarget() != null
&& this.mob.getMainHandItem().getItem() instanceof GunItem
&& this.data.getGunData() != null
&& (this.data.getGunData().countBackupAmmo(mob) > 0 || this.data.getGunData().hasEnoughAmmoToShoot(this.mob));
}
@Override
public boolean canContinueToUse() {
return (this.canUse() || !this.mob.getNavigation().isDone())
&& this.mob.getMainHandItem().getItem() instanceof GunItem
&& this.data.getGunData() != null
&& (this.data.getGunData().countBackupAmmo(mob) > 0 || this.data.getGunData().hasEnoughAmmoToShoot(this.mob));
}
@Override
public void start() {
super.start();
this.mob.setAggressive(true);
}
public void stop() {
super.stop();
this.mob.setAggressive(false);
this.mob.stopUsingItem();
}
public boolean requiresUpdateEveryTick() {
return true;
}
public void tick() {
var target = this.mob.getTarget();
if (target == null) return;
double distance = this.mob.distanceToSqr(target.getX(), target.getY(), target.getZ());
boolean canSeeTarget = this.mob.getSensing().hasLineOfSight(target);
if (canSeeTarget) {
aimTime = Math.min(data.aimTime(), aimTime + 1);
} else {
if (data.clearAimTimeWhenLostSight()) {
aimTime = 0;
} else {
aimTime--;
}
}
this.mob.lookAt(target, 30.0F, 30.0F);
// this.mob.getLookControl().setLookAt(target, 30.0F, 30.0F);
if (distance > data.shootDistance()) {
this.mob.getNavigation().moveTo(target, 1);
} else {
this.mob.getNavigation().stop();
}
var gunData = GunData.from(this.mob.getMainHandItem());
gunData.tick(this.mob, true);
if (gunData.shouldStartReloading(this.mob)) {
gunData.startReload();
}
if (gunData.shouldStartBolt()) {
gunData.startBolt();
}
if (gunData.canShoot(this.mob) && aimTime >= this.data.aimTime()) {
double rps = (double) gunData.get(GunProp.RPM) / 60;
// cooldown in ms
long cooldown = Math.round(1000 / rps);
var fireMode = gunData.selectedFireModeInfo().mode;
// 半自动或连发开火时,添加额外的开火冷却时间
if (fireMode == FireMode.SEMI || fireMode == FireMode.BURST && gunData.burstAmount.get() == 0) {
cooldown += data.semiFireInterval();
}
if (!shootTimer.started()) {
shootTimer.start();
// 首发瞬间发射
shootTimer.setProgress(cooldown + 1);
}
if (shootTimer.getProgress() >= cooldown) {
var newProgress = shootTimer.getProgress();
// 低帧率下的开火次数补偿
do {
gunData.shoot(this.mob, data.spread(), data.zoom(), target.getUUID());
newProgress -= cooldown;
} while (newProgress - cooldown > 0);
shootTimer.setProgress(newProgress);
}
} else {
shootTimer.stop();
}
}
}
| 0 | 0.704542 | 1 | 0.704542 | game-dev | MEDIA | 0.773341 | game-dev | 0.939257 | 1 | 0.939257 |
pkgplus/migateway | 1,447 | motion.go | package migateway
import (
"time"
)
const (
MODEL_MOTION = "motion"
FIELD_NO_MOTION = "no_motion"
)
type Motion struct {
*Device
State MotionState
}
type MotionState struct {
Battery float32
HasMotion bool
LastMotion time.Time
}
type MotionStateChange struct {
ID string
From MotionState
To MotionState
}
func (m MotionStateChange) IsChanged() bool {
return m.From.HasMotion != m.To.HasMotion || m.From.LastMotion != m.To.LastMotion
}
func (m *Motion) GetData() interface{} {
return m.Data
}
func NewMotion(dev *Device) *Motion {
return &Motion{
Device: dev,
State: MotionState{
Battery: dev.GetBatteryLevel(0),
HasMotion: dev.GetDataAsBool(FIELD_STATUS),
},
}
}
func (m *Motion) Set(dev *Device) {
timestamp := time.Now()
change := &MotionStateChange{ID: m.Sid, From: m.State, To: m.State}
if dev.hasField(FIELD_STATUS) {
m.State.HasMotion = dev.GetDataAsBool(FIELD_STATUS)
if m.State.HasMotion {
m.State.LastMotion = timestamp
}
} else if dev.hasField(FIELD_NO_MOTION) {
m.State.HasMotion = false
nomotionInSeconds := int64(dev.GetDataAsInt(FIELD_NO_MOTION)) * -1
timestamp.Add(time.Duration(nomotionInSeconds) * time.Second)
m.State.LastMotion = timestamp
}
m.State.Battery = dev.GetBatteryLevel(m.State.Battery)
change.To = m.State
if change.IsChanged() || m.shouldPushUpdates() {
m.Aqara.StateMessages <- change
}
if dev.Token != "" {
m.Token = dev.Token
}
}
| 0 | 0.661355 | 1 | 0.661355 | game-dev | MEDIA | 0.603046 | game-dev | 0.949316 | 1 | 0.949316 |
KospY/BasSDK | 2,474 | Packages/Tri-Inspector/Editor.Extras/Drawers/SceneDrawer.cs | using TriInspector;
using TriInspector.Drawers;
using UnityEditor;
using UnityEngine;
[assembly: RegisterTriAttributeDrawer(typeof(SceneDrawer), TriDrawerOrder.Decorator, ApplyOnArrayElement = true)]
namespace TriInspector.Drawers
{
public class SceneDrawer : TriAttributeDrawer<SceneAttribute>
{
public override TriExtensionInitializationResult Initialize(TriPropertyDefinition propertyDefinition)
{
var type = propertyDefinition.FieldType;
if (type != typeof(string))
{
return "Scene attribute can only be used on field with string type";
}
return base.Initialize(propertyDefinition);
}
public override TriElement CreateElement(TriProperty property, TriElement next)
{
return new SceneElement(property);
}
private class SceneElement : TriElement
{
private readonly TriProperty _property;
private SceneAsset _sceneAsset;
public SceneElement(TriProperty property)
{
_property = property;
}
protected override void OnAttachToPanel()
{
base.OnAttachToPanel();
_property.ValueChanged += OnValueChanged;
RefreshSceneAsset();
}
protected override void OnDetachFromPanel()
{
_property.ValueChanged -= OnValueChanged;
base.OnDetachFromPanel();
}
public override float GetHeight(float width)
{
return EditorGUIUtility.singleLineHeight;
}
public override void OnGUI(Rect position)
{
EditorGUI.BeginChangeCheck();
var asset = EditorGUI.ObjectField(position, _property.DisplayName, _sceneAsset,
typeof(SceneAsset), false);
if (EditorGUI.EndChangeCheck())
{
var path = AssetDatabase.GetAssetPath(asset);
_property.SetValue(path);
}
}
private void OnValueChanged(TriProperty property)
{
RefreshSceneAsset();
}
private void RefreshSceneAsset()
{
_sceneAsset = AssetDatabase.LoadAssetAtPath<SceneAsset>(_property.Value as string);
}
}
}
} | 0 | 0.945355 | 1 | 0.945355 | game-dev | MEDIA | 0.943353 | game-dev | 0.940005 | 1 | 0.940005 |
ippa/chingu | 24,363 | lib/chingu/game_states/edit.rb | #--
#
# Chingu -- OpenGL accelerated 2D game framework for Ruby
# Copyright (C) 2009 ippa / ippa@rubylicio.us
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#++
module Chingu
module GameStates
#
# Premade game state for chingu - simple level editing.
# Start editing in a gamestate with:
# push_game_state(Chingu::GameStates::Edit)
#
# requires the global $window set to the instance of Gosu::Window (automaticly handled if you use Chingu::Window)
#
# Edit will only edit game objects created with the editor itself or that's been loaded with load_game_objects.
# This makes mixing of loaded game objects and code create game objects possible, in the game, and in the editor.
#
# Various shortcuts are available in the editor
#
# 1-5: create object 1..5 shown in toolbar
# DEL: delete selected objects
# CTRL+A: select all objects (not code-created ones though)
# S: Save
# E: Save and Quit
# Right Mouse Button Click: Copy object that was clicked on for fast duplication
# Arrows: Scroll within a viewport
# Page up/down: Modify the zorder of selected game objects
#
class Edit < Chingu::GameState
attr_accessor :grid, :debug, :file, :hud_color
attr_reader :classes, :exclude
def initialize(options = {})
super
options = {:draw_grid => true, :snap_to_grid => true, :resize_to_grid => true}.merge(options)
@grid = options[:grid] || [8,8]
@grid_color = options[:grid_color] || Gosu::Color.new(0xaa222222)
@draw_grid = options[:draw_grid]
@snap_to_grid = options[:snap_to_grid] # todo
@resize_to_grid = options[:resize_to_grid] # todo
@classes = Array(options[:classes] || game_object_classes)
@except = options[:except] || []
@classes -= Array(@except)
@debug = options[:debug]
@attributes = options[:attributes] || [:x, :y, :angle, :zorder, :factor_x, :factor_y, :alpha]
#
# Turn on cursor + turn it back to its original value in finalize()
#
@original_cursor = $window.cursor
$window.cursor = true
p @classes if @debug
@hud_color = Gosu::Color.new(200,70,70,70)
@selected_game_object = nil
self.input = {
:f1 => :display_help,
:left_mouse_button => :left_mouse_button,
:released_left_mouse_button => :released_left_mouse_button,
:right_mouse_button => :right_mouse_button,
:released_right_mouse_button => :released_right_mouse_button,
:delete => :destroy_selected_game_objects,
:d => :destroy_selected_game_objects,
:backspace => :reset_selected_game_objects,
:holding_numpad_7 => :scale_down,
:holding_numpad_9 => :scale_up,
:holding_numpad_4 => :tilt_left,
:holding_numpad_8 => :tilt_right,
:holding_numpad_1 => :dec_alpha,
:holding_numpad_3 => :inc_alpha,
:r => :scale_up,
:f => :scale_down,
:t => :tilt_left,
:g => :tilt_right,
:y => :inc_zorder,
:h => :dec_zorder,
:u => :inc_alpha,
:j => :dec_alpha,
:page_up => :inc_zorder,
:page_down => :dec_zorder,
:s => :try_save,
:a => :try_select_all,
:e => :save_and_quit,
:esc => :esc,
:q => :quit,
:up_arrow => :move_up,
:down_arrow => :move_down,
:left_arrow => :move_left,
:right_arrow => :move_right,
:holding_up_arrow => :try_scroll_up,
:holding_down_arrow => :try_scroll_down,
:holding_left_arrow => :try_scroll_left,
:holding_right_arrow => :try_scroll_right,
:plus => :scale_up,
:minus => :scale_down,
:mouse_wheel_up => :mouse_wheel_up,
:mouse_wheel_down => :mouse_wheel_down,
:"1" => :create_object_1,
:"2" => :create_object_2,
:"3" => :create_object_3,
:"4" => :create_object_4,
:"5" => :create_object_5,
}
@hud_height = 140
@toolbar_icon_size = [32,32]
draw_toolbar_objects
end
def draw_toolbar_objects
x = 20
y = 60
@classes.each do |klass|
puts "Creating a #{klass}" if @debug
# We initialize x,y,zorder,rotation_center after creation
# so they're not overwritten by the class initialize/setup or simular
begin
game_object = klass.create(:paused => true)
game_object.x = x + 10
game_object.y = y
game_object.options[:toolbar] = true
game_object.rotation_center = :center_center
# Scale down object to fit our toolbar
if game_object.image
Text.create("#{klass.to_s[0..9]}\n#{game_object.width.to_i}x#{game_object.height.to_i}", :size => 12, :x=>x-16, :y=>y+18, :max_width => 55, :rotation_center => :top_left, :align => :center, :factor => 1)
game_object.size = @toolbar_icon_size
x += 50
else
puts "Skipping #{klass} - no image" if @debug
game_object.destroy
end
rescue
puts "Couldn't use #{klass} in editor: #{$!}"
end
end
end
def display_help
text = <<END_OF_STRING
F1: This help screen
ESC: Return to Edit
1-5: create object 1..5 shown in toolbar at mousecursor
CTRL+A: select all objects (not in-code-created ones though)
CTRL+S: Save
E: Save and Quit
Q: Quit (without saving)
ESC: Deselect all objects
Right Mouse Button Click: Copy object bellow cursor for fast duplication
Arrow-keys (with selected objects): Move objects 1 pixel at the time
Arrow-keys (with no selected objects): Scroll within a viewport
Bellow keys operates on all currently selected game objects
-----------------------------------------------------------------------------------
DEL: delete selected objects
BACKSPACE: reset angle and scale to default values
Page Up: Increase zorder
Page Down: Decrease zorder
R: scale up
F: scale down
T: tilt left
G: tilt right
Y: inc zorder
H: dec zorder
U: less transparency
J: more transparencty
Mouse Wheel (with no selected objects): Scroll viewport up/down
Mouse Wheel: Scale up/down
SHIFT + Mouse Wheel: Tilt left/right
CTRL + Mouse Wheel: Zorder up/down
ALT + Mouse Wheel: Transparency less/more
END_OF_STRING
push_game_state( GameStates::Popup.new(:text => text) )
end
def draw_grid
return unless @grid
start_x, start_y = 0,0
if defined?(previous_game_state.viewport)
start_x = -previous_game_state.viewport.x % @grid.first
start_y = -previous_game_state.viewport.y % @grid.last
end
(start_x .. $window.width).step(@grid.first).each do |x|
$window.draw_line(x, 1, @grid_color, x, $window.height, @grid_color, 0, :additive)
end
(start_y .. $window.height).step(@grid.last).each do |y|
$window.draw_line(1, y, @grid_color, $window.width, y, @grid_color, 0, :additive)
end
end
#
# SETUP
#
def setup
@scroll_border_thickness = 30
@file = options[:file] || previous_game_state.filename + ".yml"
@title = Text.create("File: #{@file}", :x => 5, :y => 2, :factor => 1, :size => 16)
@title.text += " - Grid: #{@grid}" if @grid
@text = Text.create("", :x => 300, :y => 20, :factor => 1, :size => 16)
@status_text = Text.create("-", :x => 5, :y => 20, :factor => 1, :size => 16)
if defined?(previous_game_state.viewport)
@game_area_backup = previous_game_state.viewport.game_area.dup
previous_game_state.viewport.game_area.x -= @hud_height
previous_game_state.viewport.game_area.y -= @hud_height
end
end
#
# UPDATE
#
def update
super
@status_text.text = "#{self.mouse_x.to_i} / #{self.mouse_y.to_i}"
@text.text = @selected_game_object.to_s
#
# We got a selected game object and the left mouse button is held down
#
if @left_mouse_button && @selected_game_object
selected_game_objects.each do |selected_game_object|
selected_game_object.x = self.mouse_x + selected_game_object.options[:mouse_x_offset]
selected_game_object.y = self.mouse_y + selected_game_object.options[:mouse_y_offset]
if @snap_to_grid
selected_game_object.x -= selected_game_object.x % @grid[0]
selected_game_object.y -= selected_game_object.y % @grid[1]
end
end
elsif @left_mouse_button
if defined?(self.previous_game_state.viewport)
self.previous_game_state.viewport.x = @left_mouse_click_at[0] - $window.mouse_x
self.previous_game_state.viewport.y = @left_mouse_click_at[1] - $window.mouse_y
end
end
if inside_window?($window.mouse_x, $window.mouse_y)
scroll_right if $window.mouse_x > $window.width - @scroll_border_thickness
scroll_left if $window.mouse_x < @scroll_border_thickness
scroll_up if $window.mouse_y < @scroll_border_thickness
scroll_down if $window.mouse_y > $window.height - @scroll_border_thickness
end
end
#
# DRAW
#
def draw
# Draw prev game state onto screen (the level we're editing)
previous_game_state.draw
# Restart z-ordering, everything after this will be drawn on top
$window.flush
draw_grid if @draw_grid
#
# Draw an edit HUD
#
$window.draw_quad( 0,0,@hud_color, $window.width,0,@hud_color,
$window.width,@hud_height,@hud_color,0,@hud_height,@hud_color)
#
# Draw gameobjects
#
super
#
# Draw red rectangles/circles around all selected game objects
#
if defined?(previous_game_state.viewport)
previous_game_state.viewport.apply { draw_selections }
else
draw_selections
end
@cursor_game_object.draw_at($window.mouse_x, $window.mouse_y) if @cursor_game_object
end
#
# Draw a red rectangle around all selected objects
#
def draw_selections
selected_game_objects.each { |game_object| draw_rect(bounding_box(game_object), Color::RED, 10000) }
end
#
# CLICKED LEFT MOUSE BUTTON
#
def left_mouse_button
@left_mouse_button = true
@selected_game_object = false
if defined?(self.previous_game_state.viewport)
@left_mouse_click_at = [self.previous_game_state.viewport.x + $window.mouse_x, self.previous_game_state.viewport.y + $window.mouse_y]
else
@left_mouse_click_at = [$window.mouse_x, $window.mouse_y]
end
# Put out a new game object in the editor window and select it right away
@selected_game_object = copy_game_object(@cursor_game_object) if @cursor_game_object
# Check if user clicked on anything in the icon-toolbar of available game objects
@cursor_game_object = game_object_icon_at($window.mouse_x, $window.mouse_y)
# Get editable game object that was clicked at (if any)
@selected_game_object ||= game_object_at(self.mouse_x, self.mouse_y)
if @selected_game_object && defined?(self.previous_game_state.viewport)
self.previous_game_state.viewport.center_around(@selected_game_object) if @left_double_click
end
if @selected_game_object
#
# If clicking on a new object that's wasn't previosly selected
# --> deselect all objects unless holding left_ctrl
#
if @selected_game_object.options[:selected] == nil
selected_game_objects.each { |object| object.options[:selected] = nil } unless holding?(:left_ctrl)
end
if holding?(:left_ctrl)
@selected_game_object.options[:selected] = !@selected_game_object.options[:selected]
else
@selected_game_object.options[:selected] = true
end
if holding?(:left_shift)
previous_game_state.game_objects.select { |x| x.class == @selected_game_object.class }.each do |game_object|
game_object.options[:selected] = true
end
end
#
# Re-align all objects x/y offset in relevance to the cursor
#
selected_game_objects.each do |selected_game_object|
selected_game_object.options[:mouse_x_offset] = selected_game_object.x - self.mouse_x
selected_game_object.options[:mouse_y_offset] = selected_game_object.y - self.mouse_y
end
else
deselect_selected_game_objects unless holding?(:left_ctrl)
end
end
def right_mouse_button
@cursor_game_object = @cursor_game_object ? nil : game_object_at(mouse_x, mouse_y)
end
def released_right_mouse_button
end
#
# RELASED LEFT MOUSE BUTTON
#
def released_left_mouse_button
@left_mouse_button = false
end
#
# Returns a list of game objects the editor can create. 2 types of object gets this flag:
# - An object loaded with load_game_objects
# - An object created from within the editor
#
# This helps us mix code-created with editor-created objects inside the editor and not muck around with
# the code-created ones.
#
def editable_game_objects
previous_game_state.game_objects.select { |o| o.options[:created_with_editor] }
end
#
# Returns a list of selected game objects
#
def selected_game_objects
editable_game_objects.select { |o| o.options[:selected] }
end
#
# Call destroy on all selected game objects
#
def destroy_selected_game_objects
selected_game_objects.each { |game_object| game_object.destroy }
end
def deselect_selected_game_objects
selected_game_objects.each { |object| object.options[:selected] = nil }
end
def empty_area_at_cursor
game_object_at(self.mouse_x, self.mouse_y)==nil &&
game_object_icon_at($window.mouse_x, $window.mouse_y) == nil
end
#
# Get all classes based on GameObject except Chingus internal classes.
#
def game_object_classes
ObjectSpace.enum_for(:each_object, class << GameObject; self; end).to_a.select do |game_class|
game_class.instance_methods && !game_class.to_s.include?("Chingu::")
end
end
def create_object_nr(number)
c = @classes[number].create(:x => self.mouse_x, :y => self.mouse_y, :parent => previous_game_state) if @classes[number]
c.options[:created_with_editor] = true
c.update
#@text.text = "Created a #{c.class} @ #{c.x} / #{c.y}"
end
def create_object_1; create_object_nr(0); end
def create_object_2; create_object_nr(1); end
def create_object_3; create_object_nr(2); end
def create_object_4; create_object_nr(3); end
def create_object_5; create_object_nr(4); end
#
# Resets selected game objects defaults, angle=0, scale=1.
#
def reset_selected_game_objects
selected_game_objects.each do |game_object|
game_object.angle = 0
game_object.scale = 1
end
end
def game_object_icon_at(x, y)
game_objects.select do |game_object|
next if game_object.is_a? Text
next unless game_object.image
bounding_box(game_object).collide_point?(x,y)
end.first
end
#
# Get editable object at X/Y .. if there's many objects at the same coordinate..
# .. get the one with highest zorder.
#
def game_object_at(x, y)
editable_game_objects.select do |game_object|
next if game_object.is_a? Text
bounding_box(game_object).collide_point?(x,y)
end.sort {|x,y| y.zorder <=> x.zorder }.first
end
def try_select_all
editable_game_objects.each { |x| x.options[:selected] = true } if holding?(:left_ctrl)
end
def try_save
save if holding?(:left_ctrl)
end
def quit
pop_game_state
end
def save
save_game_objects(:game_objects => editable_game_objects, :file => @file, :classes => @classes, :attributes => @attributes)
end
def save_and_quit
save unless holding?(:left_ctrl)
quit
end
def finalize
if defined?(previous_game_state.viewport)
previous_game_state.viewport.game_area = @game_area_backup
end
$window.cursor = @original_cursor
end
def move_left
scroll_left && return if selected_game_objects.empty?
selected_game_objects.each { |game_object| game_object.x -= 1 }
end
def move_right
scroll_right && return if selected_game_objects.empty?
selected_game_objects.each { |game_object| game_object.x += 1 }
end
def move_up
scroll_up && return if selected_game_objects.empty?
selected_game_objects.each { |game_object| game_object.y -= 1 }
end
def move_down
scroll_down && return if selected_game_objects.empty?
selected_game_objects.each { |game_object| game_object.y += 1 }
end
def try_scroll_left
scroll_left if selected_game_objects.empty?
end
def try_scroll_right
scroll_right if selected_game_objects.empty?
end
def try_scroll_up
scroll_up if selected_game_objects.empty?
end
def try_scroll_down
scroll_down if selected_game_objects.empty?
end
def mouse_wheel_up
if selected_game_objects.empty?
scroll_up(40)
else
tilt_left && return if holding?(:left_shift)
inc_zorder && return if holding?(:left_ctrl)
inc_alpha && return if holding?(:left_alt)
scale_up
end
end
def mouse_wheel_down
if selected_game_objects.empty?
scroll_down(40)
else
tilt_right && return if holding?(:left_shift)
dec_zorder && return if holding?(:left_ctrl)
dec_alpha && return if holding?(:left_alt)
scale_down
end
end
def tilt_left
selected_game_objects.each { |game_object| game_object.angle -= 5 }
end
def tilt_right
selected_game_objects.each { |game_object| game_object.angle += 5 }
end
def scale_up
scale_up_x && scale_up_y
end
def scale_down
scale_down_x && scale_down_y
end
def inc_zorder
selected_game_objects.each { |game_object| game_object.zorder += 1 }
end
def dec_zorder
selected_game_objects.each { |game_object| game_object.zorder -= 1 }
end
def inc_alpha
selected_game_objects.each { |game_object| game_object.alpha += 1 }
end
def dec_alpha
selected_game_objects.each { |game_object| game_object.alpha -= 1 }
end
def scale_up_x
selected_game_objects.each { |game_object| game_object.width += grid[0] }
end
def scale_up_y
selected_game_objects.each { |game_object| game_object.height += grid[1] }
end
def scale_down_x
selected_game_objects.each { |game_object| game_object.width -= grid[0] if game_object.width > grid[0] }
end
def scale_down_y
selected_game_objects.each { |game_object| game_object.height -= grid[1] if game_object.height > grid[1] }
end
def esc
deselect_selected_game_objects
@cursor_game_object = nil
end
def page_up
self.previous_game_state.viewport.y -= $window.height if defined?(self.previous_game_state.viewport)
end
def page_down
self.previous_game_state.viewport.y += $window.height if defined?(self.previous_game_state.viewport)
end
def scroll_up(amount = 10)
self.previous_game_state.viewport.y -= amount if defined?(self.previous_game_state.viewport)
end
def scroll_down(amount = 10)
self.previous_game_state.viewport.y += amount if defined?(self.previous_game_state.viewport)
end
def scroll_left(amount = 10)
self.previous_game_state.viewport.x -= amount if defined?(self.previous_game_state.viewport)
end
def scroll_right(amount = 10)
self.previous_game_state.viewport.x += amount if defined?(self.previous_game_state.viewport)
end
def mouse_x
x = $window.mouse_x
x += self.previous_game_state.viewport.x if defined?(self.previous_game_state.viewport)
return x
end
def mouse_y
y = $window.mouse_y
y += self.previous_game_state.viewport.y if defined?(self.previous_game_state.viewport)
return y
end
def inside_window?(x = $window.mouse_x, y = $window.mouse_y)
x >= 0 && x <= $window.width && y >= 0 && y <= $window.height
end
def copy_game_object(template)
game_object = template.class.create(:parent => previous_game_state)
# If we don't create it from the toolbar, we're cloning another object
# When cloning we wan't the cloned objects attributes
game_object.attributes = template.attributes unless template.options[:toolbar]
game_object.x = self.mouse_x
game_object.y = self.mouse_y
game_object.options[:created_with_editor] = true
game_object.options[:mouse_x_offset] = (game_object.x - self.mouse_x) rescue 0
game_object.options[:mouse_y_offset] = (game_object.y - self.mouse_y) rescue 0
return game_object
end
CENTER_TO_FACTOR = { 0 => -1, 0.5 => 0, 1 => 1 }
#
# Returns a bounding box (Rect-class) for any gameobject
# It will take into considerations rotation_center and scaling
#
def bounding_box(game_object)
width, height = game_object.width, game_object.height
x = game_object.x - width * game_object.center_x
y = game_object.y - height * game_object.center_y
x += width * CENTER_TO_FACTOR[game_object.center_x] if game_object.factor_x < 0
y += height * CENTER_TO_FACTOR[game_object.center_y] if game_object.factor_y < 0
return Rect.new(x, y, width, height)
end
alias :bb :bounding_box
#
# If we're editing a game state with automaticly called special methods,
# the following takes care of those.
#
def method_missing(symbol, *args)
if symbol != :button_down || symbol != :button_up
previous_game_state.__send__(symbol, *args)
end
end
end
end
end
| 0 | 0.845081 | 1 | 0.845081 | game-dev | MEDIA | 0.702711 | game-dev | 0.956915 | 1 | 0.956915 |
Gamemode4Dev/GM4_Datapacks | 1,680 | gm4_metallurgy/data/gm4_metallurgy/function/casting/sustain_mould.mcfunction | # maintains active moulds
# @s = armor_stand moulds
# at @s positioned ~ ~1.23 ~ (at the x-z location of the mould, just above the surface of the sand)
# run from main
# manage heat
scoreboard players remove @s gm4_ml_heat 1
execute if block ~ ~ ~ lava run scoreboard players add @s gm4_ml_heat 3
# kill moulds that left their sand block
execute if score @s gm4_ml_heat matches 1..89 unless block ~ ~-1 ~ #minecraft:sand run function gm4_metallurgy:casting/destroy_mould
execute unless score @s gm4_ml_heat matches 1..89 run function gm4_metallurgy:casting/destroy_mould
# add metals if player desires to do so
execute if score @s gm4_ml_heat matches 50..89 align xyz if entity @e[type=item,predicate=gm4_metallurgy:is_castable,nbt={OnGround:1b},dx=0,dy=0,dz=0] run function gm4_metallurgy:casting/add_metal/initialize
# hot ring without metal
execute if score @s[tag=!gm4_contains_metal] gm4_ml_heat matches 50..51 run item modify entity @s armor.head gm4_metallurgy:mould/hot_empty
# hot ring with metal
execute if score @s[tag=gm4_contains_metal] gm4_ml_heat matches 50..51 run item modify entity @s armor.head gm4_metallurgy:mould/hot_metal
# cool (I'm way too awesome!) ring without metals
execute if score @s[tag=!gm4_contains_metal] gm4_ml_heat matches 48..49 run item modify entity @s armor.head gm4_metallurgy:mould/cool_empty
# cool ring with metal
execute if score @s[tag=gm4_contains_metal] gm4_ml_heat matches 48..49 run item modify entity @s armor.head gm4_metallurgy:mould/cool_metal
execute if score @s gm4_ml_heat matches 56.. run particle lava ~ ~ ~ 0 0 0 0.005 1
execute if score @s gm4_ml_heat matches 80.. run particle large_smoke ~ ~ ~ 0 0 0 0.05 6
| 0 | 0.804803 | 1 | 0.804803 | game-dev | MEDIA | 0.98217 | game-dev | 0.63889 | 1 | 0.63889 |
umuthopeyildirim/DOOM-Mistral | 2,169 | src/vizdoom/src/g_hexen/a_bats.cpp | /*
#include "actor.h"
#include "info.h"
#include "m_random.h"
#include "p_local.h"
#include "s_sound.h"
#include "thingdef/thingdef.h"
*/
static FRandom pr_batspawn ("BatSpawn");
static FRandom pr_batmove ("BatMove");
//===========================================================================
// Bat Spawner Variables
// special1 frequency counter
// special2
// args[0] frequency of spawn (1=fastest, 10=slowest)
// args[1] spread angle (0..255)
// args[2]
// args[3] duration of bats (in octics)
// args[4] turn amount per move (in degrees)
//
// Bat Variables
// special2 lifetime counter
// args[4] turn amount per move (in degrees)
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_BatSpawnInit)
{
self->special1 = 0; // Frequency count
}
DEFINE_ACTION_FUNCTION(AActor, A_BatSpawn)
{
AActor *mo;
int delta;
angle_t angle;
// Countdown until next spawn
if (self->special1-- > 0) return;
self->special1 = self->args[0]; // Reset frequency count
delta = self->args[1];
if (delta==0) delta=1;
angle = self->angle + (((pr_batspawn()%delta)-(delta>>1))<<24);
mo = P_SpawnMissileAngle (self, PClass::FindClass ("Bat"), angle, 0);
if (mo)
{
mo->args[0] = pr_batspawn()&63; // floatbob index
mo->args[4] = self->args[4]; // turn degrees
mo->special2 = self->args[3]<<3; // Set lifetime
mo->target = self;
}
}
DEFINE_ACTION_FUNCTION(AActor, A_BatMove)
{
angle_t newangle;
if (self->special2 < 0)
{
self->SetState (self->FindState(NAME_Death));
}
self->special2 -= 2; // Called every 2 tics
if (pr_batmove()<128)
{
newangle = self->angle + ANGLE_1*self->args[4];
}
else
{
newangle = self->angle - ANGLE_1*self->args[4];
}
// Adjust velocity vector to new direction
newangle >>= ANGLETOFINESHIFT;
self->velx = FixedMul (self->Speed, finecosine[newangle]);
self->vely = FixedMul (self->Speed, finesine[newangle]);
if (pr_batmove()<15)
{
S_Sound (self, CHAN_VOICE, "BatScream", 1, ATTN_IDLE);
}
// Handle Z movement
self->SetZ(self->target->Z() + 16*finesine[self->args[0] << BOBTOFINESHIFT]);
self->args[0] = (self->args[0]+3)&63;
}
| 0 | 0.73066 | 1 | 0.73066 | game-dev | MEDIA | 0.838339 | game-dev | 0.950937 | 1 | 0.950937 |
followingthefasciaplane/source-engine-diff-check | 6,008 | misc/game/shared/tf/passtime_convars.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#define FLAGS_DEFAULT (FCVAR_NOTIFY | FCVAR_REPLICATED)
#define PASSTIME_CONVAR(NAME, STR, DESC) ConVar NAME(#NAME, #STR, FLAGS_DEFAULT, DESC)
PASSTIME_CONVAR( tf_passtime_scores_per_round, 5, "Number of scores it takes to win a round. Similar to tf_flag_caps_per_round." );
PASSTIME_CONVAR( tf_passtime_ball_damping_scale, 0.01f, "" );
PASSTIME_CONVAR( tf_passtime_ball_drag_coefficient, 0.01f, "" );
PASSTIME_CONVAR( tf_passtime_ball_inertia_scale, 1.0f, "" );
PASSTIME_CONVAR( tf_passtime_ball_mass, 1.0f, "" );
PASSTIME_CONVAR( tf_passtime_ball_model, models/passtime/ball/passtime_ball.mdl, "Needs a model with collision info. Map change required." ); // TODO allow override in map
PASSTIME_CONVAR( tf_passtime_ball_sphere_collision, 1, "Boolean value. If nonzero, override mdl collision with a perfect sphere collider." );
PASSTIME_CONVAR( tf_passtime_ball_sphere_radius, 7.2f, "" );
PASSTIME_CONVAR( tf_passtime_ball_reset_time, 15, "How long the ball can be neutral before being automatically reset" );
PASSTIME_CONVAR( tf_passtime_ball_rotdamping_scale, 1.0f, "Higher values will prevent the ball from rolling on the ground." );
PASSTIME_CONVAR( tf_passtime_ball_seek_range, 128, "How close players have to be for the ball to be drawn to them." );
PASSTIME_CONVAR( tf_passtime_ball_seek_speed_factor, 3f, "How fast the ball will move toward nearby players as a ratio of that player's max speed." );
PASSTIME_CONVAR( tf_passtime_ball_takedamage, 1, "Enables shooting the ball" );
PASSTIME_CONVAR( tf_passtime_ball_takedamage_force, 800.0f, "Controls how much the ball responds to being shot" );
PASSTIME_CONVAR( tf_passtime_flinch_boost, 0, "Intensity of flinch on taking damage while carrying the ball. 0 to use TF defaults." );
PASSTIME_CONVAR( tf_passtime_mode_homing_lock_sec, 1.5f, "Number of seconds the ball carrier will stay locked on to a teammate after line of sight is broken." );
PASSTIME_CONVAR( tf_passtime_mode_homing_speed, 1000.0f, "How fast the ball moves during a pass." );
PASSTIME_CONVAR( tf_passtime_overtime_idle_sec, 5, "How many seconds the ball can be idle in overtime before the round ends.");
PASSTIME_CONVAR( tf_passtime_player_reticles_enemies, 1, "Controls HUD reticles for enemies. 0 = never, 1 = when carrying ball, 2 = always." );
PASSTIME_CONVAR( tf_passtime_player_reticles_friends, 2, "Controls HUD reticles for teammates. 0 = never, 1 = when carrying ball, 2 = always." );
PASSTIME_CONVAR( tf_passtime_score_crit_sec, 5.0f, "How long a scoring team's crits last." );
PASSTIME_CONVAR( tf_passtime_speedboost_on_get_ball_time, 2.0f, "How many seconds of speed boost players get when they get the ball." );
PASSTIME_CONVAR( tf_passtime_steal_on_melee, 1, "Enables melee stealing." );
PASSTIME_CONVAR( tf_passtime_teammate_steal_time, 45, "How many seconds a player can hold the ball before teammates can steal it." );
PASSTIME_CONVAR( tf_passtime_throwarc_scout, 0.1f, "" );
PASSTIME_CONVAR( tf_passtime_throwarc_soldier, 0.1f, "" );
PASSTIME_CONVAR( tf_passtime_throwarc_pyro, 0.1f, "" );
PASSTIME_CONVAR( tf_passtime_throwarc_demoman, 0.15f, "" );
PASSTIME_CONVAR( tf_passtime_throwarc_heavy, 0.175f, "" );
PASSTIME_CONVAR( tf_passtime_throwarc_engineer, 0.2f, "" );
PASSTIME_CONVAR( tf_passtime_throwarc_medic, 0.0f, "" );
PASSTIME_CONVAR( tf_passtime_throwarc_sniper, 0.0f, "" );
PASSTIME_CONVAR( tf_passtime_throwarc_spy, 0.0f, "" );
PASSTIME_CONVAR( tf_passtime_throwspeed_scout, 700.0f, "" );
PASSTIME_CONVAR( tf_passtime_throwspeed_soldier, 800.0f, "" );
PASSTIME_CONVAR( tf_passtime_throwspeed_pyro, 750.0f, "" );
PASSTIME_CONVAR( tf_passtime_throwspeed_demoman, 850.0f, "" );
PASSTIME_CONVAR( tf_passtime_throwspeed_heavy, 850.0f, "" );
PASSTIME_CONVAR( tf_passtime_throwspeed_engineer, 850.0f, "" );
PASSTIME_CONVAR( tf_passtime_throwspeed_medic, 900.0f, "" );
PASSTIME_CONVAR( tf_passtime_throwspeed_sniper, 900.0f, "" );
PASSTIME_CONVAR( tf_passtime_throwspeed_spy, 900.0f, "" );
PASSTIME_CONVAR( tf_passtime_throwspeed_velocity_scale, 0.33f, "How much player velocity to add when tossing (0=none 1=100%)" );
PASSTIME_CONVAR( tf_passtime_save_stats, 0, "" );
PASSTIME_CONVAR( tf_passtime_experiment_telepass, 0, "None,\
TeleportToCatcher,\
SwapWithCatcher,\
TeleportToCatcherMaintainPossession,");
PASSTIME_CONVAR( tf_passtime_experiment_instapass_charge, 0, "" );
PASSTIME_CONVAR( tf_passtime_experiment_autopass, 0, "" );
PASSTIME_CONVAR( tf_passtime_experiment_instapass, 0, "" );
PASSTIME_CONVAR( tf_passtime_powerball_decayamount, 1, "How many points are removed are removed per decay. (must be integer)" );
PASSTIME_CONVAR( tf_passtime_powerball_decaysec, 4.5f, "How many seconds per decay when the ball is held." );
PASSTIME_CONVAR( tf_passtime_powerball_decaysec_neutral, 1.5f, "How many seconds per decay when the ball is neutral." );
PASSTIME_CONVAR( tf_passtime_powerball_passpoints, 25, "How many ball meter points are awarded for a complete pass." );
PASSTIME_CONVAR( tf_passtime_powerball_threshold, 80, "How many ball meter points it takes to unlock bonus goals." );
PASSTIME_CONVAR( tf_passtime_powerball_airtimebonus, 40, "Ball meter points added per second of time a pass is in the air." );
PASSTIME_CONVAR( tf_passtime_powerball_maxairtimebonus, 100, "Cap on extra points added by tf_passtime_powerball_airtimebonus." );
PASSTIME_CONVAR( tf_passtime_powerball_decay_delay, 10, "Number of seconds between ball reaching full charge and decay beginning." );
PASSTIME_CONVAR( tf_passtime_pack_range, 512, "How close players must be to the ball carrier to be included in the pack." );
PASSTIME_CONVAR( tf_passtime_pack_speed, 1, "When set to 1, all players near the ball carrier will move the same speed." );
PASSTIME_CONVAR( tf_passtime_pack_hp_per_sec, 2.0f, "How many HP per second pack members are healed." );
| 0 | 0.731645 | 1 | 0.731645 | game-dev | MEDIA | 0.88294 | game-dev | 0.672453 | 1 | 0.672453 |
kierstone/Buff-In-TopDownShooter | 4,408 | Library/PackageCache/com.unity.timeline@1.4.8/Editor/Manipulators/Move/MoveItemModeMix.cs | using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Timeline;
namespace UnityEditor.Timeline
{
class MoveItemModeMix : IMoveItemMode, IMoveItemDrawer
{
public void OnTrackDetach(IEnumerable<ItemsPerTrack> itemsGroups)
{
// Nothing
}
public void HandleTrackSwitch(IEnumerable<ItemsPerTrack> itemsGroups)
{
foreach (var itemsGroup in itemsGroups)
{
var targetTrack = itemsGroup.targetTrack;
if (targetTrack != null && itemsGroup.items.Any())
{
var compatible = itemsGroup.items.First().IsCompatibleWithTrack(targetTrack) &&
!EditModeUtils.IsInfiniteTrack(targetTrack);
var track = compatible ? targetTrack : null;
UndoExtensions.RegisterTrack(track, "Move Items");
EditModeUtils.SetParentTrack(itemsGroup.items, track);
}
else
{
EditModeUtils.SetParentTrack(itemsGroup.items, null);
}
}
}
public bool AllowTrackSwitch()
{
return true;
}
public double AdjustStartTime(WindowState state, ItemsPerTrack itemsGroup, double time)
{
return time;
}
public void OnModeClutchEnter(IEnumerable<ItemsPerTrack> itemsGroups)
{
// Nothing
}
public void OnModeClutchExit(IEnumerable<ItemsPerTrack> itemsGroups)
{
// Nothing
}
public void BeginMove(IEnumerable<ItemsPerTrack> itemsGroups)
{
// Nothing
}
public void UpdateMove(IEnumerable<ItemsPerTrack> itemsGroups)
{
// Nothing
}
public void FinishMove(IEnumerable<ItemsPerTrack> itemsGroups)
{
// Nothing
}
public bool ValidateMove(ItemsPerTrack itemsGroup)
{
var track = itemsGroup.targetTrack;
var items = itemsGroup.items;
if (EditModeUtils.IsInfiniteTrack(track))
{
double startTime;
double stopTime;
EditModeUtils.GetInfiniteClipBoundaries(track, out startTime, out stopTime);
return items.All(item =>
!EditModeUtils.IsItemWithinRange(item, startTime, stopTime) &&
!EditModeUtils.IsRangeWithinItem(startTime, stopTime, item));
}
var siblings = ItemsUtils.GetItemsExcept(itemsGroup.targetTrack, items);
return items.All(item => EditModeMixUtils.GetPlacementValidity(item, siblings) == PlacementValidity.Valid);
}
public void DrawGUI(WindowState state, IEnumerable<MovingItems> movingItems, Color color)
{
var selectionHasAnyBlendIn = false;
var selectionHasAnyBlendOut = false;
foreach (var grabbedItems in movingItems)
{
var bounds = grabbedItems.onTrackItemsBounds;
var counter = 0;
foreach (var item in grabbedItems.items.OfType<IBlendable>())
{
if (item.hasLeftBlend)
{
EditModeGUIUtils.DrawBoundsEdge(bounds[counter], color, TrimEdge.Start);
selectionHasAnyBlendIn = true;
}
if (item.hasRightBlend)
{
EditModeGUIUtils.DrawBoundsEdge(bounds[counter], color, TrimEdge.End);
selectionHasAnyBlendOut = true;
}
counter++;
}
}
if (selectionHasAnyBlendIn && selectionHasAnyBlendOut)
{
TimelineCursors.SetCursor(TimelineCursors.CursorType.MixBoth);
}
else if (selectionHasAnyBlendIn)
{
TimelineCursors.SetCursor(TimelineCursors.CursorType.MixLeft);
}
else if (selectionHasAnyBlendOut)
{
TimelineCursors.SetCursor(TimelineCursors.CursorType.MixRight);
}
else
{
TimelineCursors.ClearCursor();
}
}
}
}
| 0 | 0.857582 | 1 | 0.857582 | game-dev | MEDIA | 0.702484 | game-dev | 0.950219 | 1 | 0.950219 |
MJITG/PyTorch-HITNet-Hierarchical-Iterative-Tile-Refinement-Network-for-Real-time-Stereo-Matching | 7,608 | models/initialization.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .FE import BasicConv2d
import pdb
from .submodules import BuildVolume2d
class INIT(nn.Module):
"""
Tile hypothesis initialization
input: dual feature pyramid
output: initial tile hypothesis pyramid
"""
def __init__(self, args):
super().__init__()
self.maxdisp = args.maxdisp
fea_c1x = args.fea_c[4]
fea_c2x = args.fea_c[3]
fea_c4x = args.fea_c[2]
fea_c8x = args.fea_c[1]
fea_c16x = args.fea_c[0]
self.tile_conv1x = nn.Sequential(
BasicConv2d(fea_c1x, fea_c1x, 4, 4, 0, 1),
nn.Conv2d(fea_c1x, fea_c1x, 1, 1, 0, bias=False)
)
self.tile_conv2x = nn.Sequential(
BasicConv2d(fea_c2x, fea_c2x, 4, 4, 0, 1),
nn.Conv2d(fea_c2x, fea_c2x, 1, 1, 0, bias=False)
)
self.tile_conv4x = nn.Sequential(
BasicConv2d(fea_c4x, fea_c4x, 4, 4, 0, 1),
nn.Conv2d(fea_c4x, fea_c4x, 1, 1, 0, bias=False)
)
self.tile_conv8x = nn.Sequential(
BasicConv2d(fea_c8x, fea_c8x, 4, 4, 0, 1),
nn.Conv2d(fea_c8x, fea_c8x, 1, 1, 0, bias=False)
)
self.tile_conv16x = nn.Sequential(
BasicConv2d(fea_c16x, fea_c16x, 4, 4, 0, 1),
nn.Conv2d(fea_c16x, fea_c16x, 1, 1, 0, bias=False)
)
self.tile_fea_dscrpt16x = BasicConv2d(fea_c16x+1, 13, 1, 1, 0, 1)
self.tile_fea_dscrpt8x = BasicConv2d(fea_c8x+1, 13, 1, 1, 0, 1)
self.tile_fea_dscrpt4x = BasicConv2d(fea_c4x+1, 13, 1, 1, 0, 1)
self.tile_fea_dscrpt2x = BasicConv2d(fea_c2x+1, 13, 1, 1, 0, 1)
self.tile_fea_dscrpt1x = BasicConv2d(fea_c1x+1, 13, 1, 1, 0, 1)
self._build_volume_2d16x = BuildVolume2d(self.maxdisp//16)
self._build_volume_2d8x = BuildVolume2d(self.maxdisp//8)
self._build_volume_2d4x = BuildVolume2d(self.maxdisp//4)
self._build_volume_2d2x = BuildVolume2d(self.maxdisp//2)
self._build_volume_2d1x = BuildVolume2d(self.maxdisp)
def tile_features(self, fea_l, fea_r):
right_fea_pad = [0, 3, 0, 0]
# pdb.set_trace()
tile_fea_l1x = self.tile_conv1x(fea_l[-1])
padded_fea_r1x = F.pad(fea_r[-1], right_fea_pad)
self.tile_conv1x[0][0].stride = (4, 1)
tile_fea_r1x = self.tile_conv1x(padded_fea_r1x)
self.tile_conv1x[0][0].stride = (4, 4)
tile_fea_l2x = self.tile_conv2x(fea_l[-2])
padded_fea_r2x = F.pad(fea_r[-2], right_fea_pad)
self.tile_conv2x[0][0].stride = (4, 1)
tile_fea_r2x = self.tile_conv2x(padded_fea_r2x)
self.tile_conv2x[0][0].stride = (4, 4)
tile_fea_l4x = self.tile_conv4x(fea_l[-3])
padded_fea_r4x = F.pad(fea_r[-3], right_fea_pad)
self.tile_conv4x[0][0].stride = (4, 1)
tile_fea_r4x = self.tile_conv4x(padded_fea_r4x)
self.tile_conv4x[0][0].stride = (4, 4)
tile_fea_l8x = self.tile_conv8x(fea_l[-4])
padded_fea_r8x = F.pad(fea_r[-4], right_fea_pad)
self.tile_conv8x[0][0].stride = (4, 1)
tile_fea_r8x = self.tile_conv8x(padded_fea_r8x)
self.tile_conv8x[0][0].stride = (4, 4)
tile_fea_l16x = self.tile_conv16x(fea_l[-5])
padded_fea_r16x = F.pad(fea_r[-5], right_fea_pad)
self.tile_conv16x[0][0].stride = (4, 1)
tile_fea_r16x = self.tile_conv16x(padded_fea_r16x)
self.tile_conv16x[0][0].stride = (4, 4)
return [
[tile_fea_l16x, tile_fea_r16x],
[tile_fea_l8x, tile_fea_r8x],
[tile_fea_l4x, tile_fea_r4x],
[tile_fea_l2x, tile_fea_r2x],
[tile_fea_l1x, tile_fea_r1x],
]
def tile_hypothesis_pyramid(self, tile_feature_pyramid):
init_tile_cost16x = self._build_volume_2d16x(tile_feature_pyramid[0][0], tile_feature_pyramid[0][1])
init_tile_cost8x = self._build_volume_2d8x(tile_feature_pyramid[1][0], tile_feature_pyramid[1][1])
init_tile_cost4x = self._build_volume_2d4x(tile_feature_pyramid[2][0], tile_feature_pyramid[2][1])
init_tile_cost2x = self._build_volume_2d2x(tile_feature_pyramid[3][0], tile_feature_pyramid[3][1])
init_tile_cost1x = self._build_volume_2d1x(tile_feature_pyramid[4][0], tile_feature_pyramid[4][1])
min_tile_cost16x, min_tile_disp16x = torch.min(init_tile_cost16x, 1)
min_tile_cost8x, min_tile_disp8x = torch.min(init_tile_cost8x, 1)
min_tile_cost4x, min_tile_disp4x = torch.min(init_tile_cost4x, 1)
min_tile_cost2x, min_tile_disp2x = torch.min(init_tile_cost2x, 1)
min_tile_cost1x, min_tile_disp1x = torch.min(init_tile_cost1x, 1)
min_tile_cost16x = torch.unsqueeze(min_tile_cost16x, 1)
min_tile_cost8x = torch.unsqueeze(min_tile_cost8x, 1)
min_tile_cost4x = torch.unsqueeze(min_tile_cost4x, 1)
min_tile_cost2x = torch.unsqueeze(min_tile_cost2x, 1)
min_tile_cost1x = torch.unsqueeze(min_tile_cost1x, 1)
min_tile_disp16x = min_tile_disp16x.float().unsqueeze(1)
min_tile_disp8x = min_tile_disp8x.float().unsqueeze(1)
min_tile_disp4x = min_tile_disp4x.float().unsqueeze(1)
min_tile_disp2x = min_tile_disp2x.float().unsqueeze(1)
min_tile_disp1x = min_tile_disp1x.float().unsqueeze(1)
tile_dscrpt16x = self.tile_fea_dscrpt16x(torch.cat([min_tile_cost16x, tile_feature_pyramid[0][0]], 1))
tile_dscrpt8x = self.tile_fea_dscrpt8x(torch.cat([min_tile_cost8x, tile_feature_pyramid[1][0]], 1))
tile_dscrpt4x = self.tile_fea_dscrpt4x(torch.cat([min_tile_cost4x, tile_feature_pyramid[2][0]], 1))
tile_dscrpt2x = self.tile_fea_dscrpt2x(torch.cat([min_tile_cost2x, tile_feature_pyramid[3][0]], 1))
tile_dscrpt1x = self.tile_fea_dscrpt1x(torch.cat([min_tile_cost1x, tile_feature_pyramid[4][0]], 1))
tile_dx16x = torch.zeros_like(min_tile_disp16x)
tile_dx8x = torch.zeros_like(min_tile_disp8x)
tile_dx4x = torch.zeros_like(min_tile_disp4x)
tile_dx2x = torch.zeros_like(min_tile_disp2x)
tile_dx1x = torch.zeros_like(min_tile_disp1x)
tile_dy16x = torch.zeros_like(min_tile_disp16x)
tile_dy8x = torch.zeros_like(min_tile_disp8x)
tile_dy4x = torch.zeros_like(min_tile_disp4x)
tile_dy2x = torch.zeros_like(min_tile_disp2x)
tile_dy1x = torch.zeros_like(min_tile_disp1x)
# pdb.set_trace()
tile_hyp16x = torch.cat([min_tile_disp16x, tile_dx16x, tile_dy16x, tile_dscrpt16x], 1)
tile_hyp8x = torch.cat([min_tile_disp8x, tile_dx8x, tile_dy8x, tile_dscrpt8x], 1)
tile_hyp4x = torch.cat([min_tile_disp4x, tile_dx4x, tile_dy4x, tile_dscrpt4x], 1)
tile_hyp2x = torch.cat([min_tile_disp2x, tile_dx2x, tile_dy2x, tile_dscrpt2x], 1)
tile_hyp1x = torch.cat([min_tile_disp1x, tile_dx1x, tile_dy1x, tile_dscrpt1x], 1)
return [
[
init_tile_cost16x,
init_tile_cost8x,
init_tile_cost4x,
init_tile_cost2x,
init_tile_cost1x,
],
[
tile_hyp16x,
tile_hyp8x,
tile_hyp4x,
tile_hyp2x,
tile_hyp1x,
]
]
def forward(self, fea_l_pyramid, fea_r_pyramid):
tile_feature_duo_pyramid = self.tile_features(fea_l_pyramid, fea_r_pyramid)
init_cv_pyramid, init_hypo_pyramid = self.tile_hypothesis_pyramid(tile_feature_duo_pyramid)
return [init_cv_pyramid, init_hypo_pyramid]
| 0 | 0.716827 | 1 | 0.716827 | game-dev | MEDIA | 0.226103 | game-dev | 0.85731 | 1 | 0.85731 |
jonathaneeckhout/jdungeon | 6,799 | todo/components/player/charclasscomponent/CharClassSelection.gd | extends Control
class_name CharacterClassSelectionMenu
## Call [method select_target] to start.
@export var class_component: CharacterClassComponent
## These are the classes that will be presented to the player as available. Updated from [method update_allowed_classes]
var allowed_classes: Array[String]
## Used to know when a synch is required on the next timeout.
var sync_required: bool
## Internally used to queue syncs with the server.
var syncTimer := Timer.new()
var charClassRegisteredNameAvailable: Dictionary
var charClassRegisteredNameOwned: Dictionary
@onready var available_list: GridContainer = $AvailableClasses
@onready var owned_list: GridContainer = $OwnedClasses
@onready var statsDisplay: Control = $StatDisplay
@onready var classDesc: RichTextLabel = $ClassDescription
@onready var lockedText: Label = $LockedText
@onready var doneButton: Button = $Done
@onready var change_skill_button: Button = $ChangeSkills
func _ready() -> void:
assert(not G.is_server(), "The server should not be creating UI elements on it's end.")
mouse_entered.connect(_on_mouse_entered)
mouse_exited.connect(_on_mouse_exited)
change_skill_button.pressed.connect(_on_change_skills_pressed)
#Close button
doneButton.pressed.connect(close)
statsDisplay.accept_input = false
#Sync changes to server on a timer
syncTimer.timeout.connect(_on_sync_timer_timeout)
add_child(syncTimer)
syncTimer.start(1)
func select_target(class_comp: CharacterClassComponent):
if not is_node_ready():
await ready
class_component = class_comp
statsDisplay.stats = class_component.stats_component
lockedText.visible = not class_component.is_class_change_allowed()
class_component.class_lock_changed.connect(_on_class_lock_changed)
populate_available_list()
populate_owned_list()
func populate_available_list():
if not class_component:
GodotLogger.warn("No target has been selected. Cannot list available classes.")
return
for child in available_list.get_children():
child.queue_free()
update_allowed_classes()
for charclass in J.charclass_resources:
var characterClass: CharacterClassResource = J.charclass_resources[charclass].duplicate()
var menuElement := CharacterClassMenuElement.new(
characterClass.class_registered,
characterClass.displayed_name,
characterClass.get_icon()
)
available_list.add_child(menuElement)
menuElement.self_hovered.connect(_on_available_selected)
menuElement.self_pressed.connect(_on_available_activated)
update_available_list()
func populate_owned_list():
if not class_component:
GodotLogger.warn("No target has been selected. Cannot list available classes.")
return
for child in owned_list.get_children():
child.queue_free()
for characterClass in class_component.classes:
var menuElement := CharacterClassMenuElement.new(
characterClass.class_registered,
characterClass.displayed_name,
characterClass.get_icon()
)
owned_list.add_child(menuElement)
menuElement.self_hovered.connect(_on_owned_selected)
menuElement.self_pressed.connect(_on_owned_activated)
update_owned_list()
# Update methods are more lightweight than the "populate_" ones and can be used more freely
# Simply cause visual updates
func update_available_list():
#Disable if the player is not allowed to change or add classes
if class_component.is_full() or not class_component.is_class_change_allowed():
for child in available_list.get_children():
if child is Button:
child.disabled = true
#Enable otherwise
else:
for child in available_list.get_children():
if child is Button:
child.disabled = false
func update_owned_list():
owned_list.columns = class_component.max_classes
statsDisplay.renew_values.call_deferred()
func update_lists():
update_available_list()
update_owned_list()
func update_allowed_classes():
allowed_classes.assign(J.charclass_resources.keys().filter(class_component.is_class_allowed))
#Signal targets
func _on_available_activated(element: CharacterClassMenuElement):
if class_component.class_change_locked:
return
var charClass: String = element.char_class
class_component.add_class(charClass)
populate_owned_list()
update_lists()
sync_required = true
func _on_owned_activated(element: CharacterClassMenuElement):
if class_component.class_change_locked:
return
var charClass: String = element.char_class
class_component.remove_class(charClass)
populate_owned_list()
update_lists()
sync_required = true
func _on_owned_selected(element: CharacterClassMenuElement):
var charClassRes: CharacterClassResource = J.charclass_resources[element.char_class].duplicate()
var text: String = "[b]{0}[/b] \n {1}".format(
[charClassRes.displayed_name, charClassRes.description]
)
classDesc.parse_bbcode(text)
func _on_available_selected(element: CharacterClassMenuElement):
var charClassRes: CharacterClassResource = J.charclass_resources[element.char_class].duplicate()
var text: String = "[b]{0}[/b] \n {1}".format(
[charClassRes.displayed_name, charClassRes.description]
)
classDesc.parse_bbcode(text)
func _on_sync_timer_timeout():
if sync_required and class_component:
class_component.client_class_change_attempt()
sync_required = false
func _on_class_lock_changed():
lockedText.visible = not class_component.is_class_change_allowed()
update_lists()
func close():
if is_inside_tree():
get_parent().remove_child(self)
JUI.above_ui = false
func _on_change_skills_pressed():
var skillSelection: SkillSelectionUI = SkillSelectionUI.PACKED_SCENE.instantiate()
skillSelection.select_target(class_component.user)
add_sibling(skillSelection)
skillSelection.populate_ui()
close()
func _on_mouse_entered():
JUI.above_ui = true
func _on_mouse_exited():
JUI.above_ui = false
## Should the UI quit early with a sync queued, the change attempt will be deferred instantly.
func _notification(what: int):
if (
(what == NOTIFICATION_PREDELETE or what == NOTIFICATION_EXIT_TREE)
and sync_required
and class_component
):
class_component.client_class_change_attempt()
class CharacterClassMenuElement:
extends Button
var char_class: String
signal self_pressed(this: CharacterClassMenuElement)
signal self_hovered(this: CharacterClassMenuElement)
func _init(_charClass: String, _classDisplayName: String, _iconTexture: Texture) -> void:
char_class = _charClass
icon = _iconTexture
text = _classDisplayName
mouse_entered.connect(_on_mouse_entered)
func _ready() -> void:
#Do not allow the icon to resize the button
expand_icon = true
#Size control
size_flags_horizontal = Control.SIZE_EXPAND_FILL
offset_bottom = 0
offset_top = 0
offset_left = 0
offset_right = 0
func _pressed() -> void:
self_pressed.emit(self)
func _on_mouse_entered():
self_hovered.emit(self)
| 0 | 0.897873 | 1 | 0.897873 | game-dev | MEDIA | 0.559106 | game-dev,desktop-app | 0.959956 | 1 | 0.959956 |
mastercomfig/tf2-patches-old | 12,692 | src/game/client/tf/vgui/tf_giveawayitempanel.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "vgui/IInput.h"
#include <vgui/IVGui.h>
#include <vgui/IScheme.h>
#include "tf_giveawayitempanel.h"
#include "iclientmode.h"
#include "baseviewport.h"
#include "econ_entity.h"
#include "c_tf_player.h"
#include "gamestringpool.h"
#include "vgui_controls/TextImage.h"
#include "vgui_controls/Label.h"
#include "vgui_controls/Button.h"
#include "econ_item_system.h"
#include "ienginevgui.h"
#include "achievementmgr.h"
#include "fmtstr.h"
#include "c_tf_playerresource.h"
#include "tf_gamerules.h"
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CGiveawayPlayerPanel::CGiveawayPlayerPanel( vgui::Panel *parent, const char *name ) : BaseClass(parent,name)
{
m_pNameLabel = new vgui::Label( this, "name_label", "" );
m_pScoreLabel = new vgui::Label( this, "score_label", "" );
REGISTER_COLOR_AS_OVERRIDABLE( m_PlayerColorLocal, "fgcolor_local" );
REGISTER_COLOR_AS_OVERRIDABLE( m_PlayerColorOther, "fgcolor_other" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGiveawayPlayerPanel::PerformLayout( void )
{
BaseClass::PerformLayout();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGiveawayPlayerPanel::SetPlayer( CTFPlayer *pPlayer )
{
m_iBonus = 0;
if ( pPlayer )
{
SetVisible( true );
if ( g_TF_PR )
{
int playerIndex = pPlayer->entindex();
const char *pszName = g_TF_PR->GetPlayerName( playerIndex );
m_iBonus = pPlayer->m_Shared.GetItemFindBonus();
SetDialogVariable( "playername", pszName );
SetDialogVariable( "playerscore", m_iBonus );
}
m_iPlayerIndex = pPlayer->entindex();
if ( pPlayer->IsLocalPlayer() )
{
m_pNameLabel->SetFgColor( m_PlayerColorLocal );
m_pScoreLabel->SetFgColor( m_PlayerColorLocal );
}
else
{
m_pNameLabel->SetFgColor( m_PlayerColorOther );
m_pScoreLabel->SetFgColor( m_PlayerColorOther );
}
}
else
{
SetVisible( false );
m_iPlayerIndex = 0;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGiveawayPlayerPanel::SpinBonus( void )
{
SetDialogVariable( "playerscore", RandomInt( PLAYER_ROLL_MIN, PLAYER_ROLL_MAX ) );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGiveawayPlayerPanel::LockBonus( int iRoll )
{
m_iRoll = iRoll;
SetDialogVariable( "playerscore", m_iBonus + m_iRoll );
}
//===========================================================================================================================
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTFGiveawayItemPanel::CTFGiveawayItemPanel( IViewPort *pViewPort ) : Frame( NULL, PANEL_GIVEAWAY_ITEM )
{
m_pViewPort = pViewPort;
// load the new scheme early!!
SetScheme( "ClientScheme" );
SetTitleBarVisible( false );
SetMinimizeButtonVisible( false );
SetMaximizeButtonVisible( false );
SetCloseButtonVisible( false );
SetSizeable( false );
SetMoveable( false );
SetProportional( true );
SetVisible( false );
SetKeyBoardInputEnabled( true );
SetMouseInputEnabled( true );
m_pModelPanel = new CItemModelPanel( this, "item_panel" );
m_pPlayerListPanelKVs = NULL;
m_iNumActivePlayers = 0;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTFGiveawayItemPanel::~CTFGiveawayItemPanel( void )
{
if ( m_pPlayerListPanelKVs )
{
m_pPlayerListPanelKVs->deleteThis();
m_pPlayerListPanelKVs = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGiveawayItemPanel::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
LoadControlSettings( "Resource/UI/GiveawayItemPanel.res" );
for ( int i = 0; i < m_aPlayerList.Count(); i++ )
{
m_aPlayerList[i]->ApplySettings( m_pPlayerListPanelKVs );
m_aPlayerList[i]->SetBorder( pScheme->GetBorder("EconItemBorder") );
m_aPlayerList[i]->InvalidateLayout();
}
m_pModelPanel->SetNoItemText( "#Item_Giveaway_NoItem" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGiveawayItemPanel::ApplySettings( KeyValues *inResourceData )
{
BaseClass::ApplySettings( inResourceData );
KeyValues *pItemKV = inResourceData->FindKey( "playerlist_panel_kvs" );
if ( pItemKV )
{
if ( m_pPlayerListPanelKVs )
{
m_pPlayerListPanelKVs->deleteThis();
}
m_pPlayerListPanelKVs = new KeyValues("playerlist_panel_kvs");
pItemKV->CopySubkeys( m_pPlayerListPanelKVs );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGiveawayItemPanel::PerformLayout( void )
{
BaseClass::PerformLayout();
int iPosition = 0;
for ( int i = 0; i < m_aPlayerList.Count(); i++ )
{
if ( !m_aPlayerList[i]->IsVisible() )
continue;
int iCenter = GetWide() * 0.5;
int iXPos = iCenter;
int iYPos = 0;
if ( iPosition < (m_iNumActivePlayers * 0.5) )
{
iXPos -= m_aPlayerList[i]->GetWide() + m_iPlayerXOffset;
iYPos = m_iPlayerYPos + iPosition * m_aPlayerList[i]->GetTall();
}
else
{
iXPos += m_iPlayerXOffset;
iYPos = m_iPlayerYPos + (iPosition - Ceil2Int(m_iNumActivePlayers * 0.5)) * m_aPlayerList[i]->GetTall();
}
m_aPlayerList[i]->SetPos( iXPos, iYPos );
iPosition++;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGiveawayItemPanel::ShowPanel(bool bShow)
{
if ( bShow )
{
SetItem( NULL );
m_bBuiltPlayerList = false;
m_flNextRollStart = 0;
m_iRollingForPlayer = 0;
m_iNumActivePlayers = 0;
}
SetMouseInputEnabled( bShow );
SetVisible( bShow );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGiveawayItemPanel::FireGameEvent( IGameEvent *event )
{
const char * type = event->GetName();
if ( Q_strcmp(type, "gameui_hidden") == 0 )
{
ShowPanel( false );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGiveawayItemPanel::OnCommand( const char *command )
{
if ( !Q_stricmp( command, "vguicancel" ) )
{
ShowPanel( false );
// If we're connected to a game server, we also close the game UI.
if ( engine->IsInGame() )
{
engine->ClientCmd_Unrestricted( "gameui_hide" );
}
}
else
{
engine->ClientCmd( const_cast<char *>( command ) );
}
BaseClass::OnCommand( command );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGiveawayItemPanel::Update( void )
{
// First, wait for the player list to get built
if ( !m_bBuiltPlayerList )
{
BuildPlayerList();
if ( !m_bBuiltPlayerList )
return;
}
// Then wait for the server to send us the item details
if ( !m_pModelPanel->HasItem() )
{
if ( TFGameRules() )
{
CBonusRoundLogic *pLogic = TFGameRules()->GetBonusLogic();
if ( pLogic )
{
m_pModelPanel->SetItem( pLogic->GetBonusItem() );
}
}
if ( !m_pModelPanel->HasItem() )
return;
}
// Then start rolling through the players and locking in their bonuses
if ( m_iRollingForPlayer < m_iNumActivePlayers )
{
// Spin all the numbers & lock them in one by one
for ( int i = 0; i < m_aPlayerList.Count(); i++ )
{
if ( m_iRollingForPlayer < i )
{
// Haven't got to this player yet, so spin their bonus.
m_aPlayerList[i]->SpinBonus();
continue;
}
if ( i == m_iRollingForPlayer )
{
if ( gpGlobals->curtime > m_flNextRollStart )
{
// Lock in this player's bonus and move on to the next one
CBonusRoundLogic *pLogic = TFGameRules()->GetBonusLogic();
if ( pLogic )
{
m_aPlayerList[i]->LockBonus( pLogic->GetPlayerBonusRoll( m_aPlayerList[i]->GetPlayerIndex() ) );
}
m_iRollingForPlayer++;
m_flNextRollStart = gpGlobals->curtime + 0.4;
}
else
{
m_aPlayerList[i]->SpinBonus();
}
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGiveawayItemPanel::BuildPlayerList( void )
{
CBonusRoundLogic *pLogic = TFGameRules()->GetBonusLogic();
if ( !pLogic )
return;
m_bBuiltPlayerList = true;
pLogic->BuildBonusPlayerList();
for ( int i = 0; i < m_aPlayerList.Count(); i++ )
{
m_aPlayerList[i]->SetPlayer(NULL);
}
m_iNumActivePlayers = 0;
for( int playerIndex = 0; playerIndex < pLogic->GetNumBonusPlayers(); playerIndex++ )
{
C_TFPlayer *pPlayer = pLogic->GetBonusPlayer(playerIndex);
if ( !pPlayer )
continue;
CGiveawayPlayerPanel *pPlayerPanel;
if ( m_iNumActivePlayers < m_aPlayerList.Count() )
{
pPlayerPanel = m_aPlayerList[m_iNumActivePlayers];
}
else
{
const char *pszCommand = VarArgs("playerpanel%d",m_iNumActivePlayers);
pPlayerPanel = new CGiveawayPlayerPanel( this, pszCommand );
if ( m_pPlayerListPanelKVs )
{
pPlayerPanel->ApplySettings( m_pPlayerListPanelKVs );
}
pPlayerPanel->MakeReadyForUse();
vgui::IScheme *pScheme = vgui::scheme()->GetIScheme( GetScheme() );
pPlayerPanel->SetBorder( pScheme->GetBorder("EconItemBorder") );
m_aPlayerList.AddToTail( pPlayerPanel );
}
pPlayerPanel->SetPlayer( pPlayer );
m_iNumActivePlayers++;
}
// Start the animation
m_flNextRollStart = gpGlobals->curtime + 1.0;
m_iRollingForPlayer = 0;
InvalidateLayout();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGiveawayItemPanel::SetItem( CEconItemView *pItem )
{
m_pModelPanel->SetItem( pItem );
}
static vgui::DHANDLE<CTFGiveawayItemPanel> g_GiveawayItemPanel;
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTFGiveawayItemPanel *OpenGiveawayItemPanel( CEconItemView *pItem )
{
CTFGiveawayItemPanel *pPanel = (CTFGiveawayItemPanel*)gViewPortInterface->FindPanelByName( PANEL_GIVEAWAY_ITEM );
if ( pPanel )
{
pPanel->InvalidateLayout( false, true );
pPanel->SetItem( pItem );
gViewPortInterface->ShowPanel( pPanel, true );
}
return pPanel;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void Test_GiveawayItemPanel( const CCommand &args )
{
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( !pLocalPlayer )
return;
CEconItemView *pScriptCreatedItem = NULL;
bool bAllItems = (args.ArgC() <= 1);
for ( int i = bAllItems ? 0 : clamp( atoi(args[1]), 0, 2 ); i <= 2; i++ )
{
CEconEntity *pItem = dynamic_cast<CEconEntity *>( pLocalPlayer->Weapon_GetWeaponByType( i ) );
if ( !pItem )
continue;
pScriptCreatedItem = pItem->GetAttributeContainer()->GetItem();
break;
}
if ( pScriptCreatedItem )
{
OpenGiveawayItemPanel( pScriptCreatedItem );
}
}
ConCommand test_giveawayitem( "test_giveawayitem", Test_GiveawayItemPanel, "Debugging tool to test the item giveaway panel. Usage: test_giveawayitem <weapon name>\n <weapon id>: 0 = primary, 1 = secondary, 2 = melee.", FCVAR_CHEAT );
| 0 | 0.940898 | 1 | 0.940898 | game-dev | MEDIA | 0.513278 | game-dev | 0.912356 | 1 | 0.912356 |
Kaixhin/rlenvs | 2,816 | rlenvs/DynaMaze.lua | local classic = require 'classic'
local DynaMaze, super = classic.class('DynaMaze', Env)
-- Constructor
function DynaMaze:_init(opts)
opts = opts or {}
super._init(self, opts)
-- Set change: none|blocking|shortcut
self.change = opts.change or 'none'
-- Create blank grid (y, x)
self.maze = torch.ByteTensor(6, 9):zero()
-- Place blocks
if self.change == 'none' then
self.maze[{{3, 5}, {3}}] = 1
self.maze[{{2}, {6}}] = 1
self.maze[{{4, 6}, {8}}] = 1
elseif self.change == 'blocking' then
self.maze[{{3}, {1, 8}}] = 1
elseif self.change == 'shortcut' then
self.maze[{{3}, {2, 9}}] = 1
end
-- Keep internal step counter
self.counter = 0
end
-- 2 states returned, of type 'int', of dimensionality 1, where x is 1-9 and y is 1-6
function DynaMaze:getStateSpace()
local state = {}
state['name'] = 'Box'
state['shape'] = {2}
state['low'] = {
1, -- x
1 -- y
}
state['high'] = {
9, -- x
6 -- y
}
return state
end
-- 1 action required, of type 'int', of dimensionality 1, between 1 and 4
function DynaMaze:getActionSpace()
local action = {}
action['name'] = 'Discrete'
action['n'] = 4
return action
end
-- Min and max reward
function DynaMaze:getRewardSpace()
return 0, 1
end
-- Reset position
function DynaMaze:_start()
if self.change == 'none' then
self.position = {1, 4}
else
self.position = {4, 1}
end
return self.position
end
-- Move up, right, down or left
function DynaMaze:_step(action)
action = action + 1 -- scale action
local reward = 0
local terminal = false
-- Calculate new position
local newX = self.position[1]
local newY = self.position[2]
if action == 1 then
-- Move up
newY = math.min(newY + 1, 6)
elseif action == 2 then
-- Move right
newX = math.min(newX + 1, 9)
elseif action == 3 then
-- Move down
newY = math.max(newY - 1, 1)
else
-- Move left
newX = math.max(newX - 1, 1)
end
-- Move if not blocked
if self.maze[{{newY}, {newX}}][1][1] == 0 then
self.position[1] = newX
self.position[2] = newY
end
-- Check if reached goal
if newX == 9 and newY == 6 then
reward = 1
terminal = true
end
-- Increment counter
self.counter = self.counter + 1
-- Change environment
if self.counter == 1000 and self.change == 'blocking' then
-- Open up hole in left of wall
self.maze[{{3}, {1}}] = 0
-- Fill up hole on right of wall
self.maze[{{3}, {9}}] = 1
-- Move agent in case it is now on top of wall
if self.position[1] == 9 and self.position[2] == 3 then
self.position[1] = 4
end
elseif self.counter == 3000 and self.change == 'shortcut' then
-- Open up hole in wall
self.maze[{{3}, {9}}] = 0
end
return reward, self.position, terminal
end
return DynaMaze
| 0 | 0.951892 | 1 | 0.951892 | game-dev | MEDIA | 0.749941 | game-dev | 0.99306 | 1 | 0.99306 |
HalfADog/Unity-ARPGGameDemo-TheDawnAbyss | 8,660 | Plugins/UniTask/Runtime/Linq/Single.cs | using Cysharp.Threading.Tasks.Internal;
using System;
using System.Threading;
namespace Cysharp.Threading.Tasks.Linq
{
public static partial class UniTaskAsyncEnumerable
{
public static UniTask<TSource> SingleAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
{
Error.ThrowArgumentNullException(source, nameof(source));
return SingleOperator.SingleAsync(source, cancellationToken, false);
}
public static UniTask<TSource> SingleAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, Func<TSource, Boolean> predicate, CancellationToken cancellationToken = default)
{
Error.ThrowArgumentNullException(source, nameof(source));
Error.ThrowArgumentNullException(predicate, nameof(predicate));
return SingleOperator.SingleAsync(source, predicate, cancellationToken, false);
}
public static UniTask<TSource> SingleAwaitAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, Func<TSource, UniTask<Boolean>> predicate, CancellationToken cancellationToken = default)
{
Error.ThrowArgumentNullException(source, nameof(source));
Error.ThrowArgumentNullException(predicate, nameof(predicate));
return SingleOperator.SingleAwaitAsync(source, predicate, cancellationToken, false);
}
public static UniTask<TSource> SingleAwaitWithCancellationAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, UniTask<Boolean>> predicate, CancellationToken cancellationToken = default)
{
Error.ThrowArgumentNullException(source, nameof(source));
Error.ThrowArgumentNullException(predicate, nameof(predicate));
return SingleOperator.SingleAwaitWithCancellationAsync(source, predicate, cancellationToken, false);
}
public static UniTask<TSource> SingleOrDefaultAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
{
Error.ThrowArgumentNullException(source, nameof(source));
return SingleOperator.SingleAsync(source, cancellationToken, true);
}
public static UniTask<TSource> SingleOrDefaultAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, Func<TSource, Boolean> predicate, CancellationToken cancellationToken = default)
{
Error.ThrowArgumentNullException(source, nameof(source));
Error.ThrowArgumentNullException(predicate, nameof(predicate));
return SingleOperator.SingleAsync(source, predicate, cancellationToken, true);
}
public static UniTask<TSource> SingleOrDefaultAwaitAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, Func<TSource, UniTask<Boolean>> predicate, CancellationToken cancellationToken = default)
{
Error.ThrowArgumentNullException(source, nameof(source));
Error.ThrowArgumentNullException(predicate, nameof(predicate));
return SingleOperator.SingleAwaitAsync(source, predicate, cancellationToken, true);
}
public static UniTask<TSource> SingleOrDefaultAwaitWithCancellationAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, UniTask<Boolean>> predicate, CancellationToken cancellationToken = default)
{
Error.ThrowArgumentNullException(source, nameof(source));
Error.ThrowArgumentNullException(predicate, nameof(predicate));
return SingleOperator.SingleAwaitWithCancellationAsync(source, predicate, cancellationToken, true);
}
}
internal static class SingleOperator
{
public static async UniTask<TSource> SingleAsync<TSource>(IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken, bool defaultIfEmpty)
{
var e = source.GetAsyncEnumerator(cancellationToken);
try
{
if (await e.MoveNextAsync())
{
var v = e.Current;
if (!await e.MoveNextAsync())
{
return v;
}
throw Error.MoreThanOneElement();
}
else
{
if (defaultIfEmpty)
{
return default;
}
else
{
throw Error.NoElements();
}
}
}
finally
{
if (e != null)
{
await e.DisposeAsync();
}
}
}
public static async UniTask<TSource> SingleAsync<TSource>(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, Boolean> predicate, CancellationToken cancellationToken, bool defaultIfEmpty)
{
var e = source.GetAsyncEnumerator(cancellationToken);
try
{
TSource value = default;
bool found = false;
while (await e.MoveNextAsync())
{
var v = e.Current;
if (predicate(v))
{
if (found)
{
throw Error.MoreThanOneElement();
}
else
{
found = true;
value = v;
}
}
}
if (found || defaultIfEmpty)
{
return value;
}
throw Error.NoElements();
}
finally
{
if (e != null)
{
await e.DisposeAsync();
}
}
}
public static async UniTask<TSource> SingleAwaitAsync<TSource>(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, UniTask<Boolean>> predicate, CancellationToken cancellationToken, bool defaultIfEmpty)
{
var e = source.GetAsyncEnumerator(cancellationToken);
try
{
TSource value = default;
bool found = false;
while (await e.MoveNextAsync())
{
var v = e.Current;
if (await predicate(v))
{
if (found)
{
throw Error.MoreThanOneElement();
}
else
{
found = true;
value = v;
}
}
}
if (found || defaultIfEmpty)
{
return value;
}
throw Error.NoElements();
}
finally
{
if (e != null)
{
await e.DisposeAsync();
}
}
}
public static async UniTask<TSource> SingleAwaitWithCancellationAsync<TSource>(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, UniTask<Boolean>> predicate, CancellationToken cancellationToken, bool defaultIfEmpty)
{
var e = source.GetAsyncEnumerator(cancellationToken);
try
{
TSource value = default;
bool found = false;
while (await e.MoveNextAsync())
{
var v = e.Current;
if (await predicate(v, cancellationToken))
{
if (found)
{
throw Error.MoreThanOneElement();
}
else
{
found = true;
value = v;
}
}
}
if (found || defaultIfEmpty)
{
return value;
}
throw Error.NoElements();
}
finally
{
if (e != null)
{
await e.DisposeAsync();
}
}
}
}
} | 0 | 0.833225 | 1 | 0.833225 | game-dev | MEDIA | 0.408105 | game-dev | 0.588089 | 1 | 0.588089 |
apache/beam | 4,469 | sdks/python/apache_beam/runners/portability/fn_api_runner/visualization_tools.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Set of utilities to visualize a pipeline to be executed by FnApiRunner."""
from typing import Set
from typing import Tuple
from apache_beam.runners.portability.fn_api_runner.translations import Stage
from apache_beam.runners.portability.fn_api_runner.watermark_manager import WatermarkManager
from apache_beam.utils import timestamp
def show_stage(stage: Stage):
try:
import graphviz
except ImportError:
import warnings
warnings.warn('Unable to draw pipeline. graphviz library missing.')
return
g = graphviz.Digraph()
seen_pcollections = set()
for t in stage.transforms:
g.node(t.unique_name, shape='box')
for i in t.inputs.values():
assert isinstance(i, str)
if i not in seen_pcollections:
g.node(i)
seen_pcollections.add(i)
g.edge(i, t.unique_name)
for o in t.outputs.values():
assert isinstance(o, str)
if o not in seen_pcollections:
g.node(o)
seen_pcollections.add(o)
g.edge(t.unique_name, o)
g.render('stage_graph', format='png')
def show_watermark_manager(watermark_manager: WatermarkManager, filename=None):
try:
import graphviz
except ImportError:
import warnings
warnings.warn('Unable to draw pipeline. graphviz library missing.')
return
g = graphviz.Digraph()
def pcoll_node_name(pcoll_node: WatermarkManager.PCollectionNode):
if isinstance(pcoll_node.name, tuple):
return 'PCOLL_%s_%s' % pcoll_node.name
else:
return 'PCOLL_%s' % pcoll_node.name
def add_node(name, shape=None, color=None, label=None):
if name not in seen_nodes:
seen_nodes.add(name)
g.node(
name,
shape=shape,
fillcolor=color,
style='filled',
label=name + (label or ''))
def add_links(link_from=None, link_to=None, edge_style="solid"):
if link_from and link_to:
if (link_to, link_from, edge_style) not in seen_links:
g.edge(link_from, link_to, style=edge_style)
seen_links.add((link_to, link_from, edge_style))
seen_nodes: Set[str] = set()
seen_links: Set[Tuple[str, str]] = set()
for node in watermark_manager._stages_by_name.values():
name = 'STAGE_%s...%s' % (node.name[:30], node.name[-30:])
add_node(name, 'box')
for pcnode in watermark_manager._pcollections_by_name.values():
assert isinstance(pcnode, WatermarkManager.PCollectionNode)
name = pcoll_node_name(pcnode)
if pcnode.watermark() == timestamp.MIN_TIMESTAMP:
color = 'aquamarine'
elif pcnode.watermark() == timestamp.MAX_TIMESTAMP:
color = 'aquamarine4'
else:
color = 'aquamarine2'
add_node(
name,
color=color,
label='\n%s\nprod: %s' %
(pcnode.watermark(), pcnode._produced_watermark))
for node in watermark_manager._stages_by_name.values():
stage = 'STAGE_%s...%s' % (node.name[:30], node.name[-30:])
for pcoll in node.inputs:
input_name = pcoll_node_name(pcoll)
# Main inputs have a BOLD edge.
add_links(link_from=input_name, link_to=stage, edge_style="bold")
for pcoll in node.side_inputs:
# Side inputs have a dashed edge.
input_name = pcoll_node_name(pcoll)
add_links(link_from=input_name, link_to=stage, edge_style="dashed")
for pcnode in watermark_manager._pcollections_by_name.values():
assert isinstance(pcnode, WatermarkManager.PCollectionNode)
pcoll_name = pcoll_node_name(pcnode)
for producer in pcnode.producers:
prod_name = 'STAGE_%s...%s' % (producer.name[:30], producer.name[-30:])
add_links(link_from=prod_name, link_to=pcoll_name)
g.render(filename or 'pipeline_graph', format='png')
| 0 | 0.749311 | 1 | 0.749311 | game-dev | MEDIA | 0.298445 | game-dev | 0.901801 | 1 | 0.901801 |
EmptyKeys/UI_Generator | 18,398 | UIGenerator/BindingGenerator.cs | using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using EmptyKeys.UserInterface.Designer;
namespace EmptyKeys.UserInterface.Generator
{
/// <summary>
/// Implements binding generator
/// </summary>
public sealed class BindingGenerator
{
private static readonly char[] partSeparator = new char[] { '.' };
private static readonly char[] indexStartChars = new char[] { '[' };
private static readonly char[] indexEndChars = new char[] { ']' };
private static readonly char[] indexSeparator = new char[] { ',' };
private static readonly char[] paramStartChars = new char[] { '(' };
private static readonly char[] paramEndChars = new char[] { ')' };
private static BindingGenerator singleton = new BindingGenerator();
/// <summary>
/// Gets the instance.
/// </summary>
/// <value>
/// The instance.
/// </value>
public static BindingGenerator Instance
{
get
{
return singleton;
}
}
private readonly string memoryMappedFileName = "GenerationCodeMapppedFile_Bindings";
private readonly long nemoryMappedFileCapacity = 1000000;
private CodeNamespace ns;
private List<Tuple<Type, string, string>> propertyInfos;
private SortedSet<int> generated;
/// <summary>
/// Gets or sets the type of the active data.
/// </summary>
/// <value>
/// The type of the active data.
/// </value>
public Type ActiveDataType { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is enabled.
/// </summary>
/// <value>
/// <c>true</c> if this instance is enabled; otherwise, <c>false</c>.
/// </value>
public bool IsEnabled { get; set; }
/// <summary>
/// Prevents a default instance of the <see cref="BindingGenerator"/> class from being created.
/// </summary>
private BindingGenerator()
{
}
/// <summary>
/// Generates the namespace.
/// </summary>
/// <param name="desiredNamespace">The desired namespace.</param>
public void GenerateNamespace(string desiredNamespace)
{
propertyInfos = new List<Tuple<Type, string, string>>();
generated = new SortedSet<int>();
ns = new CodeNamespace(desiredNamespace);
ns.Imports.Add(new CodeNamespaceImport("System"));
ns.Imports.Add(new CodeNamespaceImport("System.CodeDom.Compiler"));
ns.Imports.Add(new CodeNamespaceImport("System.Collections.ObjectModel"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Charts"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Data"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Controls"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Controls.Primitives"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Input"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Interactions.Core"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Interactivity"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Media"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Media.Animation"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Media.Imaging"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Shapes"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Renderers"));
ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Themes"));
ns.Comments.Add(new CodeCommentStatement("-----------------------------------------------------------", false));
ns.Comments.Add(new CodeCommentStatement(" ", false));
ns.Comments.Add(new CodeCommentStatement(" This file was generated, please do not modify.", false));
ns.Comments.Add(new CodeCommentStatement(" ", false));
ns.Comments.Add(new CodeCommentStatement("-----------------------------------------------------------", false));
}
/// <summary>
/// Generates the registration code.
/// </summary>
/// <param name="method">The method.</param>
public void GenerateRegistrationCode(CodeMemberMethod method)
{
// GeneratedPropertyInfo.RegisterGeneratedProperty(Type dataType, string propertyName, Type propertyInfoType)
// GeneratedPropertyInfo.RegisterGeneratedProperty(typeof(BindPerfData), "ColorA", typeof(BindPerfData_ColorA_Binding));
foreach (var info in propertyInfos)
{
method.Statements.Add(new CodeMethodInvokeExpression(
new CodeTypeReferenceExpression("GeneratedPropertyInfo"), "RegisterGeneratedProperty",
new CodeTypeOfExpression(info.Item1.FullName), new CodePrimitiveExpression(info.Item2), new CodeTypeOfExpression(info.Item3)));
}
propertyInfos.Clear();
}
/// <summary>
/// Generates the binding path.
/// </summary>
/// <param name="propertyPath">The property path.</param>
/// <param name="mode">The mode.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">Namespace is empty.</exception>
public bool GenerateBindingPath(PropertyPath propertyPath, GeneratedBindingsMode mode)
{
if (ActiveDataType == null || !IsEnabled)
{
return false;
}
if (ns == null)
{
throw new ArgumentNullException("Namespace is empty.");
}
Type dataType = ActiveDataType;
if (dataType.IsPrimitive)
{
return false;
}
string path = propertyPath.Path;
string[] pathParts = path.Split(partSeparator, StringSplitOptions.RemoveEmptyEntries);
bool isCollectionProperty = false;
for (int i = 0; i < pathParts.Length; i++)
{
string propertyName = pathParts[i];
int indexStart = propertyName.IndexOfAny(indexStartChars);
if (indexStart != -1)
{
propertyName = propertyName.Substring(0, indexStart);
}
PropertyInfo propertyInfo = dataType.GetRuntimeProperty(propertyName);
int paramStart = propertyName.IndexOfAny(paramStartChars);
if (paramStart != -1)
{
int paramEnd = propertyName.IndexOfAny(paramEndChars);
string paramIndexString = propertyName.Substring(paramStart + 1, paramEnd - paramStart - 1).Trim();
int paramIndex = Convert.ToInt32(paramIndexString);
propertyInfo = propertyPath.PathParameters[paramIndex] as PropertyInfo;
if (propertyInfo != null)
{
propertyName = propertyInfo.Name;
dataType = propertyInfo.ReflectedType;
}
}
string className = string.Format("{0}_{1}_PropertyInfo", dataType.Name, propertyName);
className = Regex.Replace(className, "[`|<|>]", "");
CodeTypeDeclaration classType = CreateClass(className);
if (propertyInfo == null)
{
// if mixed mode return with false (binding was not generated) but don't generate error so reflection can be used
if (mode == GeneratedBindingsMode.Mixed)
{
return false;
}
CodeSnippetTypeMember error = new CodeSnippetTypeMember(string.Format("#error {0} type does not have property {1}", dataType, propertyName));
classType.Members.Add(error);
ns.Types.Add(classType);
return false;
}
isCollectionProperty = propertyInfo.PropertyType.IsArray ||
(typeof(IEnumerable).IsAssignableFrom(propertyInfo.PropertyType) && propertyInfo.PropertyType != typeof(string));
Type elementType = propertyInfo.PropertyType.GetElementType();
if (elementType == null && propertyInfo.PropertyType.IsGenericType)
{
elementType = propertyInfo.PropertyType.GetGenericArguments()[0];
}
int key = propertyName.GetHashCode() ^ dataType.GetHashCode();
if (!generated.Contains(key))
{
generated.Add(key);
ns.Types.Add(classType);
GenerateProperties(classType, propertyInfo);
GenerateMethods(dataType, isCollectionProperty, propertyName, classType, propertyInfo, elementType);
propertyInfos.Add(new Tuple<Type, string, string>(dataType, propertyName, ns.Name + "." + className));
}
if (isCollectionProperty)
{
dataType = elementType;
}
else
{
dataType = propertyInfo.PropertyType;
}
}
return true;
}
private static void GenerateMethods(Type dataType, bool isCollectionProperty, string propertyName, CodeTypeDeclaration classType, PropertyInfo propertyInfo, Type elementType)
{
// public object GetValue(object obj) method
CodeMemberMethod getValue1 = new CodeMemberMethod();
getValue1.Name = "GetValue";
getValue1.ReturnType = new CodeTypeReference(typeof(object));
getValue1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
getValue1.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "obj"));
CodeExpression nonArrayAccessor = null;
nonArrayAccessor = new CodeFieldReferenceExpression(new CodeCastExpression(dataType, new CodeVariableReferenceExpression("obj")), propertyInfo.Name);
getValue1.Statements.Add(new CodeMethodReturnStatement(nonArrayAccessor));
classType.Members.Add(getValue1);
// public object GetValue(object obj, object[] index) method
CodeMemberMethod getValue2 = new CodeMemberMethod();
getValue2.Name = "GetValue";
getValue2.ReturnType = new CodeTypeReference(typeof(object));
getValue2.Attributes = MemberAttributes.Public | MemberAttributes.Final;
getValue2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "obj"));
getValue2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object[]), "index"));
CodeExpression arrayAccessor = null;
if (isCollectionProperty)
{
arrayAccessor = new CodeIndexerExpression(
new CodeFieldReferenceExpression(new CodeCastExpression(dataType, new CodeVariableReferenceExpression("obj")), propertyName),
new CodeCastExpression(typeof(int), new CodeIndexerExpression(new CodeVariableReferenceExpression("index"), new CodePrimitiveExpression(0)))
);
}
else
{
arrayAccessor = new CodePrimitiveExpression(null);
}
getValue2.Statements.Add(new CodeMethodReturnStatement(arrayAccessor));
classType.Members.Add(getValue2);
// public void SetValue(object obj, object value) method
CodeMemberMethod setValue1 = new CodeMemberMethod();
setValue1.Name = "SetValue";
setValue1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
setValue1.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "obj"));
setValue1.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "value"));
if (propertyInfo.CanWrite && propertyInfo.SetMethod.IsPublic)
{
setValue1.Statements.Add(new CodeAssignStatement(nonArrayAccessor, new CodeCastExpression(propertyInfo.PropertyType, new CodeVariableReferenceExpression("value"))));
}
classType.Members.Add(setValue1);
// public void SetValue(object obj, object value, object[] index) method
CodeMemberMethod setValue2 = new CodeMemberMethod();
setValue2.Name = "SetValue";
setValue2.Attributes = MemberAttributes.Public | MemberAttributes.Final;
setValue2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "obj"));
setValue2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "value"));
setValue2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object[]), "index"));
if (isCollectionProperty && propertyInfo.CanWrite && propertyInfo.SetMethod.IsPublic)
{
setValue2.Statements.Add(new CodeAssignStatement(arrayAccessor, new CodeCastExpression(elementType, new CodeVariableReferenceExpression("value"))));
}
classType.Members.Add(setValue2);
}
private static void GenerateProperties(CodeTypeDeclaration classType, PropertyInfo propertyInfo)
{
// PropertyType property
CodeMemberProperty typeProperty = new CodeMemberProperty();
typeProperty.Name = "PropertyType";
typeProperty.Type = new CodeTypeReference(typeof(Type));
typeProperty.HasGet = true;
typeProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
typeProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeOfExpression(propertyInfo.PropertyType)));
classType.Members.Add(typeProperty);
// IsResolved property
CodeMemberProperty isResolvedProperty = new CodeMemberProperty();
isResolvedProperty.Name = "IsResolved";
isResolvedProperty.Type = new CodeTypeReference(typeof(bool));
isResolvedProperty.HasGet = true;
isResolvedProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
isResolvedProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(true)));
classType.Members.Add(isResolvedProperty);
}
private CodeTypeDeclaration CreateClass(string className)
{
CodeTypeDeclaration classType = new CodeTypeDeclaration(className);
GeneratedCodeAttribute generatedCodeAttribute =
new GeneratedCodeAttribute("Empty Keys UI Generator", Assembly.GetExecutingAssembly().GetName().Version.ToString());
CodeAttributeDeclaration codeAttrDecl =
new CodeAttributeDeclaration(generatedCodeAttribute.GetType().Name,
new CodeAttributeArgument(
new CodePrimitiveExpression(generatedCodeAttribute.Tool)),
new CodeAttributeArgument(
new CodePrimitiveExpression(generatedCodeAttribute.Version)));
classType.CustomAttributes.Add(codeAttrDecl);
classType.BaseTypes.Add(new CodeTypeReference("IPropertyInfo"));
return classType;
}
/// <summary>
/// Generates the file.
/// </summary>
/// <param name="outputFile">The output file.</param>
/// <exception cref="System.ArgumentNullException">Code not generated. Namespace is empty.</exception>
public void GenerateFile(string outputFile)
{
if (ns == null)
{
throw new ArgumentNullException("Code not generated. Namespace is empty.");
}
string generatedCode = string.Empty;
try
{
using (CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider())
{
using (MemoryMappedFile mappedFile = MemoryMappedFile.CreateNew(memoryMappedFileName, nemoryMappedFileCapacity))
{
MemoryMappedViewStream stream = mappedFile.CreateViewStream();
using (StreamWriter sw = new StreamWriter(stream))
{
provider.GenerateCodeFromNamespace(ns, sw, new CodeGeneratorOptions());
}
stream = mappedFile.CreateViewStream();
TextReader tr = new StreamReader(stream);
generatedCode = tr.ReadToEnd();
generatedCode = generatedCode.Trim(new char());
tr.Close();
}
}
}
catch (Exception ex)
{
generatedCode = "#error " + ex.Message;
throw;
}
finally
{
string directory = Path.GetDirectoryName(outputFile);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
using (StreamWriter outfile = new StreamWriter(outputFile))
{
outfile.Write(generatedCode);
}
}
}
}
}
| 0 | 0.875929 | 1 | 0.875929 | game-dev | MEDIA | 0.34418 | game-dev | 0.923899 | 1 | 0.923899 |
lordofduct/spacepuppy-unity-framework-4.0 | 2,600 | Framework/com.spacepuppy.radicalcoroutine/Runtime/src/IProgressingYieldInstruction.cs |
using System.Runtime.InteropServices;
namespace com.spacepuppy
{
/// <summary>
/// Implement this if your RadicalYieldInstruction should have a progress property.
/// </summary>
public interface IProgressingYieldInstruction : IRadicalYieldInstruction
{
float Progress { get; }
}
/// <summary>
/// Base abstract class that implements IProgressingYieldInstruction. Inherit from this instead of directly implementing
/// IProgressingYieldInstruction, unless you can't otherwise.
/// </summary>
public class ProgressingYieldInstructionQueue : IProgressingYieldInstruction
{
#region Fields
private IProgressingYieldInstruction[] _operations;
private bool _complete;
#endregion
#region CONSTRUCTOR
public ProgressingYieldInstructionQueue(params IProgressingYieldInstruction[] operations)
{
if (operations == null) throw new System.ArgumentNullException("operations");
_operations = operations;
}
#endregion
#region IProgressingAsyncOperation Interface
public float Progress
{
get
{
if (_operations.Length == 0) return 1f;
else if (_operations.Length == 1) return _operations[0].Progress;
else
{
float p = 0f;
for (int i = 0; i < _operations.Length; i++)
{
p += _operations[i].Progress;
}
return p / _operations.Length;
}
}
}
public bool IsComplete
{
get
{
if (_complete) return true;
else
{
for (int i = 0; i < _operations.Length; i++)
{
if (!_operations[i].IsComplete) return false;
}
_complete = true;
return true;
}
}
}
bool IRadicalYieldInstruction.Tick(out object yieldObject)
{
if (!_complete)
{
for (int i = 0; i < _operations.Length; i++)
{
if (!_operations[i].IsComplete)
{
return _operations[i].Tick(out yieldObject);
}
}
}
yieldObject = null;
return false;
}
#endregion
}
}
| 0 | 0.868634 | 1 | 0.868634 | game-dev | MEDIA | 0.631533 | game-dev | 0.95149 | 1 | 0.95149 |
mitsuhiko/webgl-meincraft | 5,352 | src/worldgen.coffee | NOTHING = 0
FLYING_ROCK = 1
GROUND = 2
class GeneratorState
constructor: (chunkSize) ->
@chunkSize = chunkSize
@cacheSizeX = @chunkSize
@cacheSizeY = @chunkSize + 1
@cacheSizeZ = @chunkSize
@blockSourceCache = new Uint8Array @cacheSizeX * @cacheSizeY * @cacheSizeZ
init: (gen, offX, offY, offZ) ->
{cacheSizeX, cacheSizeY, cacheSizeZ} = this
@offX = offX
@offY = offY
@offZ = offZ
sc = @blockSourceCache
for cz in [0...cacheSizeZ] by 1
for cy in [0...cacheSizeY] by 1
for cx in [0...cacheSizeX] by 1
source = gen.getBlockSource offX + cx, offY + cy, offZ + cz
sc[cx + cy * cacheSizeX + cz * cacheSizeX * cacheSizeY] = source
getBlockSource: (cx, cy, cz) ->
@blockSourceCache[cx + cy * @cacheSizeX + cz * @cacheSizeX * @cacheSizeY]
class WorldGeneratorProcess extends webglmc.Process
constructor: (seed) ->
@perlin = new webglmc.PerlinGenerator seed
@cachedState = null
@cachedChunk = null
@waterLevel = 16
isFlyingRock: (x, y, z) ->
nx = x * 0.01
ny = y * 0.01
nz = z * 0.01
heightOff = @perlin.simpleNoise2D(nx * 3.0, nz * 3.0) * 0.2
mx = (nx % 1.0 + 1.0) % 1.0
my = ((ny + heightOff) % 1.4 + 1.4) % 1.4
mz = (nz % 1.0 + 1.0) % 1.0
# falloff from the top
if my > 0.9
return false
if my > 0.8
plateauFalloff = 1.0 - (my - 0.8) * 10
else
plateauFalloff = 1.0
# falloff from the center
a = (mx - 0.5) * 1.5
b = (my - 1.0) * 0.8
c = (mz - 0.5) * 1.5
centerFalloff = 0.1 / (a * a + b * b + c * c)
noise = @perlin.noise3D nx, ny * 0.5, nz, 4
density = noise * centerFalloff * plateauFalloff
density > 0.1
getGroundHeight: (x, z) ->
nx = x * 0.01
nz = z * 0.01
noise = @perlin.noise2D(nx, nz, 3) * 0.5 + 0.5
noise * 30
getGrassVariation: (x, y, z) ->
nx = x * 1.2
ny = y * 1.4
nz = z * 1.1
noise = @perlin.simpleNoise3D(nx, ny, nz) * 0.5 + 0.5
variation = Math.floor(noise * 4) + 1
webglmc.BLOCK_TYPES["grass0#{variation}"]
getRockVariation: (x, y, z) ->
nx = 0.3 + x * 1.1
ny = 0.4 + y * 1.1
nz = 0.5 + z * 1.05
noise = @perlin.simpleNoise3D(nx, ny, nz) * 0.5 + 0.5
noise = Math.floor(noise * 3)
if noise > 0.4
return webglmc.BLOCK_TYPES.rock01
return webglmc.BLOCK_TYPES.rock02
getBlockSource: (x, y, z) ->
# Ground level blocks
if y < this.getGroundHeight x, z
return GROUND
# Flying rocks
if this.isFlyingRock x, y, z
return FLYING_ROCK
NOTHING
getBlock: (state, cx, cy, cz) ->
x = state.offX + cx
y = state.offY + cy
z = state.offZ + cz
blockSource = state.getBlockSource cx, cy, cz
if !blockSource
if y < @waterLevel
return webglmc.BLOCK_TYPES.water
return webglmc.BLOCK_TYPES.air
if blockSource == FLYING_ROCK
if !state.getBlockSource cx, cy + 1, cz
return this.getGrassVariation x, y, z
return this.getRockVariation x, y, z
if blockSource == GROUND
if y < @waterLevel - 4
return webglmc.BLOCK_TYPES.stone
if @waterLevel - 1 <= y <= @waterLevel + 1
return webglmc.BLOCK_TYPES.sand
return this.getGrassVariation x, y, z
getGeneratorState: (offX, offY, offZ, chunkSize) ->
if !@cachedState || @cachedState.chunkSize != chunkSize
@cachedState = new GeneratorState chunkSize
@cachedState.init this, offX, offY, offZ
@cachedState
getChunkArray: (chunkSize) ->
dim = chunkSize * chunkSize * chunkSize
if !@cachedChunk || @cachedChunk.length != dim
@cachedChunk = new Uint8Array dim
@cachedChunk
generateChunk: (def) ->
{chunkSize, x, y, z} = def
offX = x * chunkSize
offY = y * chunkSize
offZ = z * chunkSize
# Since generateChunk is not reentrant and JavaScript does not
# support multithreading we can savely keep them around. These
# functions will cache them in the background so that we do not
# need any memory allocations during world generation
state = this.getGeneratorState offX, offY, offZ, chunkSize
chunk = this.getChunkArray chunkSize
for cz in [0...chunkSize] by 1
for cy in [0...chunkSize] by 1
for cx in [0...chunkSize] by 1
blockID = this.getBlock state, cx, cy, cz
chunk[cx + cy * chunkSize + cz * chunkSize * chunkSize] = blockID
this.notifyParent x: x, y: y, z: z, chunk: chunk
class WorldGenerator
constructor: (world) ->
@world = world
numberOfWorkers = parseInt webglmc.getRuntimeParameter 'workers', 4
# Spawn a few workers for the actual world generation.
@manager = new webglmc.ProcessManager numberOfWorkers,
process: 'webglmc.WorldGeneratorProcess'
args: [world.seed]
onNotification: (data) =>
this.processGeneratedChunk data.x, data.y, data.z, data.chunk
@manager.addStatusDisplay('Worldgen worker load')
generateChunk: (x, y, z) ->
@manager.getWorker().generateChunk
x: x
y: y
z: z
chunkSize: @world.chunkSize
processGeneratedChunk: (x, y, z, chunk) ->
@world.setRequestedChunk x, y, z, chunk
public = self.webglmc ?= {}
public.WorldGenerator = WorldGenerator
public.WorldGeneratorProcess = WorldGeneratorProcess
| 0 | 0.901985 | 1 | 0.901985 | game-dev | MEDIA | 0.538252 | game-dev,graphics-rendering | 0.855828 | 1 | 0.855828 |
Baystation12/Baystation12 | 3,596 | code/modules/hydroponics/spreading/spreading_response.dm | /obj/vine/HasProximity(atom/movable/AM)
if(!is_mature() || seed.get_trait(TRAIT_SPREAD) != 2)
return
var/mob/living/M = AM
if(!istype(M))
return
if(issmall(M) || prob(round(seed.get_trait(TRAIT_POTENCY)/6)))
//wait a tick for the Entered() proc that called HasProximity() to finish (and thus the moving animation),
//so we don't appear to teleport from two tiles away when moving into a turf adjacent to vines.
spawn(1)
if(prob(seed.get_trait(((TRAIT_POTENCY)/2)*3)))
entangle(M)
/obj/vine/attack_hand(mob/user)
manual_unbuckle(user)
/obj/vine/attack_generic(mob/user)
if (buckled_mob == user)
manual_unbuckle(user)
return
..()
/obj/vine/Crossed(atom/movable/O)
if(isliving(O))
trodden_on(O)
/obj/vine/proc/trodden_on(mob/living/victim)
wake_neighbors()
if(!is_mature())
return
if(prob(seed.get_trait(((TRAIT_POTENCY)/2)*3)))
entangle(victim)
var/mob/living/carbon/human/H = victim
if(istype(H) && H.shoes)
return
seed.do_thorns(victim,src)
seed.do_sting(victim,src,pick(BP_R_FOOT,BP_L_FOOT,BP_R_LEG,BP_L_LEG))
/obj/vine/proc/manual_unbuckle(mob/user)
if (!can_unbuckle(user))
return
if(buckled_mob != user)
to_chat(user, SPAN_NOTICE("You try to free \the [buckled_mob] from \the [src]."))
var/chance = round(100/(20*seed.get_trait(TRAIT_POTENCY)/100))
if(prob(chance))
buckled_mob.visible_message(
"\The [user] frees \the [buckled_mob] from \the [src].",
SPAN_NOTICE("\The [user] frees you from \the [src]."),
SPAN_WARNING("You hear shredding and ripping.")
)
unbuckle_mob()
else
user.setClickCooldown(100)
var/escapetime = rand(600, 1200) //1 to 2 minutes.
user.visible_message(
"\The [user] attempts to get free from [src]!",
SPAN_NOTICE("You attempt to get free from [src].")
)
if (do_after(user, escapetime, src, DO_DEFAULT | DO_USER_UNIQUE_ACT | DO_PUBLIC_PROGRESS, INCAPACITATION_DEFAULT & ~INCAPACITATION_RESTRAINED) && can_unbuckle(user))
if(unbuckle_mob())
user.visible_message(
"\The [user] manages to escape [src]!",
SPAN_NOTICE("You successfully escape [src]!")
)
/obj/vine/proc/entangle(mob/living/victim)
if(buckled_mob)
return
if(victim.anchored)
return
if(!Adjacent(victim))
return
if(victim.is_floating)
victim.visible_message(
SPAN_WARNING("Tendrils lash out towards \the [victim] but \the [src] can't quite reach them as they float above!"),
SPAN_WARNING("Tendrils lash out from \the [src] below but can't quite reach you!")
)
return
if(ishuman(victim))
var/mob/living/carbon/human/H = victim
if(H.species.species_flags & SPECIES_FLAG_NO_TANGLE)
return
if(victim.loc != loc && istype(H.shoes, /obj/item/clothing/shoes/magboots) && (H.shoes.item_flags & ITEM_FLAG_NOSLIP) || H.species.check_no_slip(H))
visible_message(
SPAN_WARNING("Tendrils lash to drag \the [victim] but \the [src] can't pull them across the ground!"),
SPAN_WARNING("Tendrils lash to drag you but \the [src] can't pull you across the ground!")
)
return
victim.visible_message(
SPAN_DANGER("Tendrils lash out from \the [src] and drag \the [victim] in!"),
SPAN_DANGER("Tendrils lash out from \the [src] and drag you in!"))
victim.forceMove(loc)
if (victim.buckled)
victim.buckled.unbuckle_mob()
if (can_buckle(victim) && buckle_mob(victim))
victim.set_dir(pick(GLOB.cardinal))
to_chat(victim, SPAN_DANGER("The tendrils [pick("wind", "tangle", "tighten", "coil", "knot", "snag", "twist", "constrict", "squeeze", "clench", "tense")] around you!"))
/obj/vine/buckle_mob()
. = ..()
if(.) START_PROCESSING(SSvines, src)
| 0 | 0.983477 | 1 | 0.983477 | game-dev | MEDIA | 0.964243 | game-dev | 0.99036 | 1 | 0.99036 |
LandSandBoat/server | 1,407 | scripts/missions/soa/4_1_4_Ministerial_Whispers.lua | -----------------------------------
-- Ministerial Whispers
-- Seekers of Adoulin M4-1-4
-----------------------------------
-- !addmission 12 75
-- Levil : !pos -87.204 3.350 12.655 256
-- Kipligg : !pos -32 0 22 256
-----------------------------------
local mission = Mission:new(xi.mission.log_id.SOA, xi.mission.id.soa.MINISTERIAL_WHISPERS)
mission.reward =
{
bayld = 500,
nextMission = { xi.mission.log_id.SOA, xi.mission.id.soa.A_DAY_IN_THE_LIFE_OF_A_PIONEER },
}
mission.sections =
{
{
check = function(player, currentMission, missionStatus, vars)
return currentMission == mission.missionId
end,
[xi.zone.WESTERN_ADOULIN] =
{
['Kipligg'] = mission:event(163):setPriority(101), -- TODO: This overrides default logic in NPC script
['Levil'] = mission:progressEvent(158),
onEventFinish =
{
[158] = function(player, csid, option, npc)
if mission:complete(player) then
xi.mission.setVar(player, xi.mission.log_id.SOA, xi.mission.id.soa.A_DAY_IN_THE_LIFE_OF_A_PIONEER, 'Timer', VanadielUniqueDay() + 1)
xi.mission.setMustZone(player, xi.mission.log_id.SOA, xi.mission.id.soa.A_DAY_IN_THE_LIFE_OF_A_PIONEER)
end
end,
},
},
},
}
return mission
| 0 | 0.67486 | 1 | 0.67486 | game-dev | MEDIA | 0.555366 | game-dev | 0.661432 | 1 | 0.661432 |
qcdong2016/QCEditor | 32,432 | cocos2d/external/bullet/include/bullet/BulletCollision/BroadphaseCollision/btDbvt.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///btDbvt implementation by Nathanael Presson
#ifndef BT_DYNAMIC_BOUNDING_VOLUME_TREE_H
#define BT_DYNAMIC_BOUNDING_VOLUME_TREE_H
#include "LinearMath/btAlignedObjectArray.h"
#include "LinearMath/btVector3.h"
#include "LinearMath/btTransform.h"
#include "LinearMath/btAabbUtil2.h"
//
// Compile time configuration
//
// Implementation profiles
#define DBVT_IMPL_GENERIC 0 // Generic implementation
#define DBVT_IMPL_SSE 1 // SSE
// Template implementation of ICollide
#ifdef _WIN32
#if (defined (_MSC_VER) && _MSC_VER >= 1400)
#define DBVT_USE_TEMPLATE 1
#else
#define DBVT_USE_TEMPLATE 0
#endif
#else
#define DBVT_USE_TEMPLATE 0
#endif
// Use only intrinsics instead of inline asm
#define DBVT_USE_INTRINSIC_SSE 1
// Using memmov for collideOCL
#define DBVT_USE_MEMMOVE 1
// Enable benchmarking code
#define DBVT_ENABLE_BENCHMARK 0
// Inlining
#define DBVT_INLINE SIMD_FORCE_INLINE
// Specific methods implementation
//SSE gives errors on a MSVC 7.1
#if defined (BT_USE_SSE) //&& defined (_WIN32)
#define DBVT_SELECT_IMPL DBVT_IMPL_SSE
#define DBVT_MERGE_IMPL DBVT_IMPL_SSE
#define DBVT_INT0_IMPL DBVT_IMPL_SSE
#else
#define DBVT_SELECT_IMPL DBVT_IMPL_GENERIC
#define DBVT_MERGE_IMPL DBVT_IMPL_GENERIC
#define DBVT_INT0_IMPL DBVT_IMPL_GENERIC
#endif
#if (DBVT_SELECT_IMPL==DBVT_IMPL_SSE)|| \
(DBVT_MERGE_IMPL==DBVT_IMPL_SSE)|| \
(DBVT_INT0_IMPL==DBVT_IMPL_SSE)
#include <emmintrin.h>
#endif
//
// Auto config and checks
//
#if DBVT_USE_TEMPLATE
#define DBVT_VIRTUAL
#define DBVT_VIRTUAL_DTOR(a)
#define DBVT_PREFIX template <typename T>
#define DBVT_IPOLICY T& policy
#define DBVT_CHECKTYPE static const ICollide& typechecker=*(T*)1;(void)typechecker;
#else
#define DBVT_VIRTUAL_DTOR(a) virtual ~a() {}
#define DBVT_VIRTUAL virtual
#define DBVT_PREFIX
#define DBVT_IPOLICY ICollide& policy
#define DBVT_CHECKTYPE
#endif
#if DBVT_USE_MEMMOVE
#if !defined( __CELLOS_LV2__) && !defined(__MWERKS__)
#include <memory.h>
#endif
#include <string.h>
#endif
#ifndef DBVT_USE_TEMPLATE
#error "DBVT_USE_TEMPLATE undefined"
#endif
#ifndef DBVT_USE_MEMMOVE
#error "DBVT_USE_MEMMOVE undefined"
#endif
#ifndef DBVT_ENABLE_BENCHMARK
#error "DBVT_ENABLE_BENCHMARK undefined"
#endif
#ifndef DBVT_SELECT_IMPL
#error "DBVT_SELECT_IMPL undefined"
#endif
#ifndef DBVT_MERGE_IMPL
#error "DBVT_MERGE_IMPL undefined"
#endif
#ifndef DBVT_INT0_IMPL
#error "DBVT_INT0_IMPL undefined"
#endif
//
// Defaults volumes
//
/* btDbvtAabbMm */
struct btDbvtAabbMm
{
DBVT_INLINE btVector3 Center() const { return((mi+mx)/2); }
DBVT_INLINE btVector3 Lengths() const { return(mx-mi); }
DBVT_INLINE btVector3 Extents() const { return((mx-mi)/2); }
DBVT_INLINE const btVector3& Mins() const { return(mi); }
DBVT_INLINE const btVector3& Maxs() const { return(mx); }
static inline btDbvtAabbMm FromCE(const btVector3& c,const btVector3& e);
static inline btDbvtAabbMm FromCR(const btVector3& c,btScalar r);
static inline btDbvtAabbMm FromMM(const btVector3& mi,const btVector3& mx);
static inline btDbvtAabbMm FromPoints(const btVector3* pts,int n);
static inline btDbvtAabbMm FromPoints(const btVector3** ppts,int n);
DBVT_INLINE void Expand(const btVector3& e);
DBVT_INLINE void SignedExpand(const btVector3& e);
DBVT_INLINE bool Contain(const btDbvtAabbMm& a) const;
DBVT_INLINE int Classify(const btVector3& n,btScalar o,int s) const;
DBVT_INLINE btScalar ProjectMinimum(const btVector3& v,unsigned signs) const;
DBVT_INLINE friend bool Intersect( const btDbvtAabbMm& a,
const btDbvtAabbMm& b);
DBVT_INLINE friend bool Intersect( const btDbvtAabbMm& a,
const btVector3& b);
DBVT_INLINE friend btScalar Proximity( const btDbvtAabbMm& a,
const btDbvtAabbMm& b);
DBVT_INLINE friend int Select( const btDbvtAabbMm& o,
const btDbvtAabbMm& a,
const btDbvtAabbMm& b);
DBVT_INLINE friend void Merge( const btDbvtAabbMm& a,
const btDbvtAabbMm& b,
btDbvtAabbMm& r);
DBVT_INLINE friend bool NotEqual( const btDbvtAabbMm& a,
const btDbvtAabbMm& b);
DBVT_INLINE btVector3& tMins() { return(mi); }
DBVT_INLINE btVector3& tMaxs() { return(mx); }
private:
DBVT_INLINE void AddSpan(const btVector3& d,btScalar& smi,btScalar& smx) const;
private:
btVector3 mi,mx;
};
// Types
typedef btDbvtAabbMm btDbvtVolume;
/* btDbvtNode */
struct btDbvtNode
{
btDbvtVolume volume;
btDbvtNode* parent;
DBVT_INLINE bool isleaf() const { return(childs[1]==0); }
DBVT_INLINE bool isinternal() const { return(!isleaf()); }
union
{
btDbvtNode* childs[2];
void* data;
int dataAsInt;
};
};
///The btDbvt class implements a fast dynamic bounding volume tree based on axis aligned bounding boxes (aabb tree).
///This btDbvt is used for soft body collision detection and for the btDbvtBroadphase. It has a fast insert, remove and update of nodes.
///Unlike the btQuantizedBvh, nodes can be dynamically moved around, which allows for change in topology of the underlying data structure.
struct btDbvt
{
/* Stack element */
struct sStkNN
{
const btDbvtNode* a;
const btDbvtNode* b;
sStkNN() {}
sStkNN(const btDbvtNode* na,const btDbvtNode* nb) : a(na),b(nb) {}
};
struct sStkNP
{
const btDbvtNode* node;
int mask;
sStkNP(const btDbvtNode* n,unsigned m) : node(n),mask(m) {}
};
struct sStkNPS
{
const btDbvtNode* node;
int mask;
btScalar value;
sStkNPS() {}
sStkNPS(const btDbvtNode* n,unsigned m,btScalar v) : node(n),mask(m),value(v) {}
};
struct sStkCLN
{
const btDbvtNode* node;
btDbvtNode* parent;
sStkCLN(const btDbvtNode* n,btDbvtNode* p) : node(n),parent(p) {}
};
// Policies/Interfaces
/* ICollide */
struct ICollide
{
DBVT_VIRTUAL_DTOR(ICollide)
DBVT_VIRTUAL void Process(const btDbvtNode*,const btDbvtNode*) {}
DBVT_VIRTUAL void Process(const btDbvtNode*) {}
DBVT_VIRTUAL void Process(const btDbvtNode* n,btScalar) { Process(n); }
DBVT_VIRTUAL bool Descent(const btDbvtNode*) { return(true); }
DBVT_VIRTUAL bool AllLeaves(const btDbvtNode*) { return(true); }
};
/* IWriter */
struct IWriter
{
virtual ~IWriter() {}
virtual void Prepare(const btDbvtNode* root,int numnodes)=0;
virtual void WriteNode(const btDbvtNode*,int index,int parent,int child0,int child1)=0;
virtual void WriteLeaf(const btDbvtNode*,int index,int parent)=0;
};
/* IClone */
struct IClone
{
virtual ~IClone() {}
virtual void CloneLeaf(btDbvtNode*) {}
};
// Constants
enum {
SIMPLE_STACKSIZE = 64,
DOUBLE_STACKSIZE = SIMPLE_STACKSIZE*2
};
// Fields
btDbvtNode* m_root;
btDbvtNode* m_free;
int m_lkhd;
int m_leaves;
unsigned m_opath;
btAlignedObjectArray<sStkNN> m_stkStack;
mutable btAlignedObjectArray<const btDbvtNode*> m_rayTestStack;
// Methods
btDbvt();
~btDbvt();
void clear();
bool empty() const { return(0==m_root); }
void optimizeBottomUp();
void optimizeTopDown(int bu_treshold=128);
void optimizeIncremental(int passes);
btDbvtNode* insert(const btDbvtVolume& box,void* data);
void update(btDbvtNode* leaf,int lookahead=-1);
void update(btDbvtNode* leaf,btDbvtVolume& volume);
bool update(btDbvtNode* leaf,btDbvtVolume& volume,const btVector3& velocity,btScalar margin);
bool update(btDbvtNode* leaf,btDbvtVolume& volume,const btVector3& velocity);
bool update(btDbvtNode* leaf,btDbvtVolume& volume,btScalar margin);
void remove(btDbvtNode* leaf);
void write(IWriter* iwriter) const;
void clone(btDbvt& dest,IClone* iclone=0) const;
static int maxdepth(const btDbvtNode* node);
static int countLeaves(const btDbvtNode* node);
static void extractLeaves(const btDbvtNode* node,btAlignedObjectArray<const btDbvtNode*>& leaves);
#if DBVT_ENABLE_BENCHMARK
static void benchmark();
#else
static void benchmark(){}
#endif
// DBVT_IPOLICY must support ICollide policy/interface
DBVT_PREFIX
static void enumNodes( const btDbvtNode* root,
DBVT_IPOLICY);
DBVT_PREFIX
static void enumLeaves( const btDbvtNode* root,
DBVT_IPOLICY);
DBVT_PREFIX
void collideTT( const btDbvtNode* root0,
const btDbvtNode* root1,
DBVT_IPOLICY);
DBVT_PREFIX
void collideTTpersistentStack( const btDbvtNode* root0,
const btDbvtNode* root1,
DBVT_IPOLICY);
#if 0
DBVT_PREFIX
void collideTT( const btDbvtNode* root0,
const btDbvtNode* root1,
const btTransform& xform,
DBVT_IPOLICY);
DBVT_PREFIX
void collideTT( const btDbvtNode* root0,
const btTransform& xform0,
const btDbvtNode* root1,
const btTransform& xform1,
DBVT_IPOLICY);
#endif
DBVT_PREFIX
void collideTV( const btDbvtNode* root,
const btDbvtVolume& volume,
DBVT_IPOLICY) const;
///rayTest is a re-entrant ray test, and can be called in parallel as long as the btAlignedAlloc is thread-safe (uses locking etc)
///rayTest is slower than rayTestInternal, because it builds a local stack, using memory allocations, and it recomputes signs/rayDirectionInverses each time
DBVT_PREFIX
static void rayTest( const btDbvtNode* root,
const btVector3& rayFrom,
const btVector3& rayTo,
DBVT_IPOLICY);
///rayTestInternal is faster than rayTest, because it uses a persistent stack (to reduce dynamic memory allocations to a minimum) and it uses precomputed signs/rayInverseDirections
///rayTestInternal is used by btDbvtBroadphase to accelerate world ray casts
DBVT_PREFIX
void rayTestInternal( const btDbvtNode* root,
const btVector3& rayFrom,
const btVector3& rayTo,
const btVector3& rayDirectionInverse,
unsigned int signs[3],
btScalar lambda_max,
const btVector3& aabbMin,
const btVector3& aabbMax,
DBVT_IPOLICY) const;
DBVT_PREFIX
static void collideKDOP(const btDbvtNode* root,
const btVector3* normals,
const btScalar* offsets,
int count,
DBVT_IPOLICY);
DBVT_PREFIX
static void collideOCL( const btDbvtNode* root,
const btVector3* normals,
const btScalar* offsets,
const btVector3& sortaxis,
int count,
DBVT_IPOLICY,
bool fullsort=true);
DBVT_PREFIX
static void collideTU( const btDbvtNode* root,
DBVT_IPOLICY);
// Helpers
static DBVT_INLINE int nearest(const int* i,const btDbvt::sStkNPS* a,btScalar v,int l,int h)
{
int m=0;
while(l<h)
{
m=(l+h)>>1;
if(a[i[m]].value>=v) l=m+1; else h=m;
}
return(h);
}
static DBVT_INLINE int allocate( btAlignedObjectArray<int>& ifree,
btAlignedObjectArray<sStkNPS>& stock,
const sStkNPS& value)
{
int i;
if(ifree.size()>0)
{ i=ifree[ifree.size()-1];ifree.pop_back();stock[i]=value; }
else
{ i=stock.size();stock.push_back(value); }
return(i);
}
//
private:
btDbvt(const btDbvt&) {}
};
//
// Inline's
//
//
inline btDbvtAabbMm btDbvtAabbMm::FromCE(const btVector3& c,const btVector3& e)
{
btDbvtAabbMm box;
box.mi=c-e;box.mx=c+e;
return(box);
}
//
inline btDbvtAabbMm btDbvtAabbMm::FromCR(const btVector3& c,btScalar r)
{
return(FromCE(c,btVector3(r,r,r)));
}
//
inline btDbvtAabbMm btDbvtAabbMm::FromMM(const btVector3& mi,const btVector3& mx)
{
btDbvtAabbMm box;
box.mi=mi;box.mx=mx;
return(box);
}
//
inline btDbvtAabbMm btDbvtAabbMm::FromPoints(const btVector3* pts,int n)
{
btDbvtAabbMm box;
box.mi=box.mx=pts[0];
for(int i=1;i<n;++i)
{
box.mi.setMin(pts[i]);
box.mx.setMax(pts[i]);
}
return(box);
}
//
inline btDbvtAabbMm btDbvtAabbMm::FromPoints(const btVector3** ppts,int n)
{
btDbvtAabbMm box;
box.mi=box.mx=*ppts[0];
for(int i=1;i<n;++i)
{
box.mi.setMin(*ppts[i]);
box.mx.setMax(*ppts[i]);
}
return(box);
}
//
DBVT_INLINE void btDbvtAabbMm::Expand(const btVector3& e)
{
mi-=e;mx+=e;
}
//
DBVT_INLINE void btDbvtAabbMm::SignedExpand(const btVector3& e)
{
if(e.x()>0) mx.setX(mx.x()+e[0]); else mi.setX(mi.x()+e[0]);
if(e.y()>0) mx.setY(mx.y()+e[1]); else mi.setY(mi.y()+e[1]);
if(e.z()>0) mx.setZ(mx.z()+e[2]); else mi.setZ(mi.z()+e[2]);
}
//
DBVT_INLINE bool btDbvtAabbMm::Contain(const btDbvtAabbMm& a) const
{
return( (mi.x()<=a.mi.x())&&
(mi.y()<=a.mi.y())&&
(mi.z()<=a.mi.z())&&
(mx.x()>=a.mx.x())&&
(mx.y()>=a.mx.y())&&
(mx.z()>=a.mx.z()));
}
//
DBVT_INLINE int btDbvtAabbMm::Classify(const btVector3& n,btScalar o,int s) const
{
btVector3 pi,px;
switch(s)
{
case (0+0+0): px=btVector3(mi.x(),mi.y(),mi.z());
pi=btVector3(mx.x(),mx.y(),mx.z());break;
case (1+0+0): px=btVector3(mx.x(),mi.y(),mi.z());
pi=btVector3(mi.x(),mx.y(),mx.z());break;
case (0+2+0): px=btVector3(mi.x(),mx.y(),mi.z());
pi=btVector3(mx.x(),mi.y(),mx.z());break;
case (1+2+0): px=btVector3(mx.x(),mx.y(),mi.z());
pi=btVector3(mi.x(),mi.y(),mx.z());break;
case (0+0+4): px=btVector3(mi.x(),mi.y(),mx.z());
pi=btVector3(mx.x(),mx.y(),mi.z());break;
case (1+0+4): px=btVector3(mx.x(),mi.y(),mx.z());
pi=btVector3(mi.x(),mx.y(),mi.z());break;
case (0+2+4): px=btVector3(mi.x(),mx.y(),mx.z());
pi=btVector3(mx.x(),mi.y(),mi.z());break;
case (1+2+4): px=btVector3(mx.x(),mx.y(),mx.z());
pi=btVector3(mi.x(),mi.y(),mi.z());break;
}
if((btDot(n,px)+o)<0) return(-1);
if((btDot(n,pi)+o)>=0) return(+1);
return(0);
}
//
DBVT_INLINE btScalar btDbvtAabbMm::ProjectMinimum(const btVector3& v,unsigned signs) const
{
const btVector3* b[]={&mx,&mi};
const btVector3 p( b[(signs>>0)&1]->x(),
b[(signs>>1)&1]->y(),
b[(signs>>2)&1]->z());
return(btDot(p,v));
}
//
DBVT_INLINE void btDbvtAabbMm::AddSpan(const btVector3& d,btScalar& smi,btScalar& smx) const
{
for(int i=0;i<3;++i)
{
if(d[i]<0)
{ smi+=mx[i]*d[i];smx+=mi[i]*d[i]; }
else
{ smi+=mi[i]*d[i];smx+=mx[i]*d[i]; }
}
}
//
DBVT_INLINE bool Intersect( const btDbvtAabbMm& a,
const btDbvtAabbMm& b)
{
#if DBVT_INT0_IMPL == DBVT_IMPL_SSE
const __m128 rt(_mm_or_ps( _mm_cmplt_ps(_mm_load_ps(b.mx),_mm_load_ps(a.mi)),
_mm_cmplt_ps(_mm_load_ps(a.mx),_mm_load_ps(b.mi))));
#if defined (_WIN32)
const __int32* pu((const __int32*)&rt);
#else
const int* pu((const int*)&rt);
#endif
return((pu[0]|pu[1]|pu[2])==0);
#else
return( (a.mi.x()<=b.mx.x())&&
(a.mx.x()>=b.mi.x())&&
(a.mi.y()<=b.mx.y())&&
(a.mx.y()>=b.mi.y())&&
(a.mi.z()<=b.mx.z())&&
(a.mx.z()>=b.mi.z()));
#endif
}
//
DBVT_INLINE bool Intersect( const btDbvtAabbMm& a,
const btVector3& b)
{
return( (b.x()>=a.mi.x())&&
(b.y()>=a.mi.y())&&
(b.z()>=a.mi.z())&&
(b.x()<=a.mx.x())&&
(b.y()<=a.mx.y())&&
(b.z()<=a.mx.z()));
}
//////////////////////////////////////
//
DBVT_INLINE btScalar Proximity( const btDbvtAabbMm& a,
const btDbvtAabbMm& b)
{
const btVector3 d=(a.mi+a.mx)-(b.mi+b.mx);
return(btFabs(d.x())+btFabs(d.y())+btFabs(d.z()));
}
//
DBVT_INLINE int Select( const btDbvtAabbMm& o,
const btDbvtAabbMm& a,
const btDbvtAabbMm& b)
{
#if DBVT_SELECT_IMPL == DBVT_IMPL_SSE
#if defined (_WIN32)
static ATTRIBUTE_ALIGNED16(const unsigned __int32) mask[]={0x7fffffff,0x7fffffff,0x7fffffff,0x7fffffff};
#else
static ATTRIBUTE_ALIGNED16(const unsigned int) mask[]={0x7fffffff,0x7fffffff,0x7fffffff,0x00000000 /*0x7fffffff*/};
#endif
///@todo: the intrinsic version is 11% slower
#if DBVT_USE_INTRINSIC_SSE
union btSSEUnion ///NOTE: if we use more intrinsics, move btSSEUnion into the LinearMath directory
{
__m128 ssereg;
float floats[4];
int ints[4];
};
__m128 omi(_mm_load_ps(o.mi));
omi=_mm_add_ps(omi,_mm_load_ps(o.mx));
__m128 ami(_mm_load_ps(a.mi));
ami=_mm_add_ps(ami,_mm_load_ps(a.mx));
ami=_mm_sub_ps(ami,omi);
ami=_mm_and_ps(ami,_mm_load_ps((const float*)mask));
__m128 bmi(_mm_load_ps(b.mi));
bmi=_mm_add_ps(bmi,_mm_load_ps(b.mx));
bmi=_mm_sub_ps(bmi,omi);
bmi=_mm_and_ps(bmi,_mm_load_ps((const float*)mask));
__m128 t0(_mm_movehl_ps(ami,ami));
ami=_mm_add_ps(ami,t0);
ami=_mm_add_ss(ami,_mm_shuffle_ps(ami,ami,1));
__m128 t1(_mm_movehl_ps(bmi,bmi));
bmi=_mm_add_ps(bmi,t1);
bmi=_mm_add_ss(bmi,_mm_shuffle_ps(bmi,bmi,1));
btSSEUnion tmp;
tmp.ssereg = _mm_cmple_ss(bmi,ami);
return tmp.ints[0]&1;
#else
ATTRIBUTE_ALIGNED16(__int32 r[1]);
__asm
{
mov eax,o
mov ecx,a
mov edx,b
movaps xmm0,[eax]
movaps xmm5,mask
addps xmm0,[eax+16]
movaps xmm1,[ecx]
movaps xmm2,[edx]
addps xmm1,[ecx+16]
addps xmm2,[edx+16]
subps xmm1,xmm0
subps xmm2,xmm0
andps xmm1,xmm5
andps xmm2,xmm5
movhlps xmm3,xmm1
movhlps xmm4,xmm2
addps xmm1,xmm3
addps xmm2,xmm4
pshufd xmm3,xmm1,1
pshufd xmm4,xmm2,1
addss xmm1,xmm3
addss xmm2,xmm4
cmpless xmm2,xmm1
movss r,xmm2
}
return(r[0]&1);
#endif
#else
return(Proximity(o,a)<Proximity(o,b)?0:1);
#endif
}
//
DBVT_INLINE void Merge( const btDbvtAabbMm& a,
const btDbvtAabbMm& b,
btDbvtAabbMm& r)
{
#if DBVT_MERGE_IMPL==DBVT_IMPL_SSE
__m128 ami(_mm_load_ps(a.mi));
__m128 amx(_mm_load_ps(a.mx));
__m128 bmi(_mm_load_ps(b.mi));
__m128 bmx(_mm_load_ps(b.mx));
ami=_mm_min_ps(ami,bmi);
amx=_mm_max_ps(amx,bmx);
_mm_store_ps(r.mi,ami);
_mm_store_ps(r.mx,amx);
#else
for(int i=0;i<3;++i)
{
if(a.mi[i]<b.mi[i]) r.mi[i]=a.mi[i]; else r.mi[i]=b.mi[i];
if(a.mx[i]>b.mx[i]) r.mx[i]=a.mx[i]; else r.mx[i]=b.mx[i];
}
#endif
}
//
DBVT_INLINE bool NotEqual( const btDbvtAabbMm& a,
const btDbvtAabbMm& b)
{
return( (a.mi.x()!=b.mi.x())||
(a.mi.y()!=b.mi.y())||
(a.mi.z()!=b.mi.z())||
(a.mx.x()!=b.mx.x())||
(a.mx.y()!=b.mx.y())||
(a.mx.z()!=b.mx.z()));
}
//
// Inline's
//
//
DBVT_PREFIX
inline void btDbvt::enumNodes( const btDbvtNode* root,
DBVT_IPOLICY)
{
DBVT_CHECKTYPE
policy.Process(root);
if(root->isinternal())
{
enumNodes(root->childs[0],policy);
enumNodes(root->childs[1],policy);
}
}
//
DBVT_PREFIX
inline void btDbvt::enumLeaves( const btDbvtNode* root,
DBVT_IPOLICY)
{
DBVT_CHECKTYPE
if(root->isinternal())
{
enumLeaves(root->childs[0],policy);
enumLeaves(root->childs[1],policy);
}
else
{
policy.Process(root);
}
}
//
DBVT_PREFIX
inline void btDbvt::collideTT( const btDbvtNode* root0,
const btDbvtNode* root1,
DBVT_IPOLICY)
{
DBVT_CHECKTYPE
if(root0&&root1)
{
int depth=1;
int treshold=DOUBLE_STACKSIZE-4;
btAlignedObjectArray<sStkNN> stkStack;
stkStack.resize(DOUBLE_STACKSIZE);
stkStack[0]=sStkNN(root0,root1);
do {
sStkNN p=stkStack[--depth];
if(depth>treshold)
{
stkStack.resize(stkStack.size()*2);
treshold=stkStack.size()-4;
}
if(p.a==p.b)
{
if(p.a->isinternal())
{
stkStack[depth++]=sStkNN(p.a->childs[0],p.a->childs[0]);
stkStack[depth++]=sStkNN(p.a->childs[1],p.a->childs[1]);
stkStack[depth++]=sStkNN(p.a->childs[0],p.a->childs[1]);
}
}
else if(Intersect(p.a->volume,p.b->volume))
{
if(p.a->isinternal())
{
if(p.b->isinternal())
{
stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[0]);
stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[0]);
stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[1]);
stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[1]);
}
else
{
stkStack[depth++]=sStkNN(p.a->childs[0],p.b);
stkStack[depth++]=sStkNN(p.a->childs[1],p.b);
}
}
else
{
if(p.b->isinternal())
{
stkStack[depth++]=sStkNN(p.a,p.b->childs[0]);
stkStack[depth++]=sStkNN(p.a,p.b->childs[1]);
}
else
{
policy.Process(p.a,p.b);
}
}
}
} while(depth);
}
}
DBVT_PREFIX
inline void btDbvt::collideTTpersistentStack( const btDbvtNode* root0,
const btDbvtNode* root1,
DBVT_IPOLICY)
{
DBVT_CHECKTYPE
if(root0&&root1)
{
int depth=1;
int treshold=DOUBLE_STACKSIZE-4;
m_stkStack.resize(DOUBLE_STACKSIZE);
m_stkStack[0]=sStkNN(root0,root1);
do {
sStkNN p=m_stkStack[--depth];
if(depth>treshold)
{
m_stkStack.resize(m_stkStack.size()*2);
treshold=m_stkStack.size()-4;
}
if(p.a==p.b)
{
if(p.a->isinternal())
{
m_stkStack[depth++]=sStkNN(p.a->childs[0],p.a->childs[0]);
m_stkStack[depth++]=sStkNN(p.a->childs[1],p.a->childs[1]);
m_stkStack[depth++]=sStkNN(p.a->childs[0],p.a->childs[1]);
}
}
else if(Intersect(p.a->volume,p.b->volume))
{
if(p.a->isinternal())
{
if(p.b->isinternal())
{
m_stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[0]);
m_stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[0]);
m_stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[1]);
m_stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[1]);
}
else
{
m_stkStack[depth++]=sStkNN(p.a->childs[0],p.b);
m_stkStack[depth++]=sStkNN(p.a->childs[1],p.b);
}
}
else
{
if(p.b->isinternal())
{
m_stkStack[depth++]=sStkNN(p.a,p.b->childs[0]);
m_stkStack[depth++]=sStkNN(p.a,p.b->childs[1]);
}
else
{
policy.Process(p.a,p.b);
}
}
}
} while(depth);
}
}
#if 0
//
DBVT_PREFIX
inline void btDbvt::collideTT( const btDbvtNode* root0,
const btDbvtNode* root1,
const btTransform& xform,
DBVT_IPOLICY)
{
DBVT_CHECKTYPE
if(root0&&root1)
{
int depth=1;
int treshold=DOUBLE_STACKSIZE-4;
btAlignedObjectArray<sStkNN> stkStack;
stkStack.resize(DOUBLE_STACKSIZE);
stkStack[0]=sStkNN(root0,root1);
do {
sStkNN p=stkStack[--depth];
if(Intersect(p.a->volume,p.b->volume,xform))
{
if(depth>treshold)
{
stkStack.resize(stkStack.size()*2);
treshold=stkStack.size()-4;
}
if(p.a->isinternal())
{
if(p.b->isinternal())
{
stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[0]);
stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[0]);
stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[1]);
stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[1]);
}
else
{
stkStack[depth++]=sStkNN(p.a->childs[0],p.b);
stkStack[depth++]=sStkNN(p.a->childs[1],p.b);
}
}
else
{
if(p.b->isinternal())
{
stkStack[depth++]=sStkNN(p.a,p.b->childs[0]);
stkStack[depth++]=sStkNN(p.a,p.b->childs[1]);
}
else
{
policy.Process(p.a,p.b);
}
}
}
} while(depth);
}
}
//
DBVT_PREFIX
inline void btDbvt::collideTT( const btDbvtNode* root0,
const btTransform& xform0,
const btDbvtNode* root1,
const btTransform& xform1,
DBVT_IPOLICY)
{
const btTransform xform=xform0.inverse()*xform1;
collideTT(root0,root1,xform,policy);
}
#endif
//
DBVT_PREFIX
inline void btDbvt::collideTV( const btDbvtNode* root,
const btDbvtVolume& vol,
DBVT_IPOLICY) const
{
DBVT_CHECKTYPE
if(root)
{
ATTRIBUTE_ALIGNED16(btDbvtVolume) volume(vol);
btAlignedObjectArray<const btDbvtNode*> stack;
stack.resize(0);
stack.reserve(SIMPLE_STACKSIZE);
stack.push_back(root);
do {
const btDbvtNode* n=stack[stack.size()-1];
stack.pop_back();
if(Intersect(n->volume,volume))
{
if(n->isinternal())
{
stack.push_back(n->childs[0]);
stack.push_back(n->childs[1]);
}
else
{
policy.Process(n);
}
}
} while(stack.size()>0);
}
}
DBVT_PREFIX
inline void btDbvt::rayTestInternal( const btDbvtNode* root,
const btVector3& rayFrom,
const btVector3& rayTo,
const btVector3& rayDirectionInverse,
unsigned int signs[3],
btScalar lambda_max,
const btVector3& aabbMin,
const btVector3& aabbMax,
DBVT_IPOLICY) const
{
(void) rayTo;
DBVT_CHECKTYPE
if(root)
{
btVector3 resultNormal;
int depth=1;
int treshold=DOUBLE_STACKSIZE-2;
btAlignedObjectArray<const btDbvtNode*>& stack = m_rayTestStack;
stack.resize(DOUBLE_STACKSIZE);
stack[0]=root;
btVector3 bounds[2];
do
{
const btDbvtNode* node=stack[--depth];
bounds[0] = node->volume.Mins()-aabbMax;
bounds[1] = node->volume.Maxs()-aabbMin;
btScalar tmin=1.f,lambda_min=0.f;
unsigned int result1=false;
result1 = btRayAabb2(rayFrom,rayDirectionInverse,signs,bounds,tmin,lambda_min,lambda_max);
if(result1)
{
if(node->isinternal())
{
if(depth>treshold)
{
stack.resize(stack.size()*2);
treshold=stack.size()-2;
}
stack[depth++]=node->childs[0];
stack[depth++]=node->childs[1];
}
else
{
policy.Process(node);
}
}
} while(depth);
}
}
//
DBVT_PREFIX
inline void btDbvt::rayTest( const btDbvtNode* root,
const btVector3& rayFrom,
const btVector3& rayTo,
DBVT_IPOLICY)
{
DBVT_CHECKTYPE
if(root)
{
btVector3 rayDir = (rayTo-rayFrom);
rayDir.normalize ();
///what about division by zero? --> just set rayDirection[i] to INF/BT_LARGE_FLOAT
btVector3 rayDirectionInverse;
rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[0];
rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[1];
rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[2];
unsigned int signs[3] = { rayDirectionInverse[0] < 0.0, rayDirectionInverse[1] < 0.0, rayDirectionInverse[2] < 0.0};
btScalar lambda_max = rayDir.dot(rayTo-rayFrom);
btVector3 resultNormal;
btAlignedObjectArray<const btDbvtNode*> stack;
int depth=1;
int treshold=DOUBLE_STACKSIZE-2;
stack.resize(DOUBLE_STACKSIZE);
stack[0]=root;
btVector3 bounds[2];
do {
const btDbvtNode* node=stack[--depth];
bounds[0] = node->volume.Mins();
bounds[1] = node->volume.Maxs();
btScalar tmin=1.f,lambda_min=0.f;
unsigned int result1 = btRayAabb2(rayFrom,rayDirectionInverse,signs,bounds,tmin,lambda_min,lambda_max);
#ifdef COMPARE_BTRAY_AABB2
btScalar param=1.f;
bool result2 = btRayAabb(rayFrom,rayTo,node->volume.Mins(),node->volume.Maxs(),param,resultNormal);
btAssert(result1 == result2);
#endif //TEST_BTRAY_AABB2
if(result1)
{
if(node->isinternal())
{
if(depth>treshold)
{
stack.resize(stack.size()*2);
treshold=stack.size()-2;
}
stack[depth++]=node->childs[0];
stack[depth++]=node->childs[1];
}
else
{
policy.Process(node);
}
}
} while(depth);
}
}
//
DBVT_PREFIX
inline void btDbvt::collideKDOP(const btDbvtNode* root,
const btVector3* normals,
const btScalar* offsets,
int count,
DBVT_IPOLICY)
{
DBVT_CHECKTYPE
if(root)
{
const int inside=(1<<count)-1;
btAlignedObjectArray<sStkNP> stack;
int signs[sizeof(unsigned)*8];
btAssert(count<int (sizeof(signs)/sizeof(signs[0])));
for(int i=0;i<count;++i)
{
signs[i]= ((normals[i].x()>=0)?1:0)+
((normals[i].y()>=0)?2:0)+
((normals[i].z()>=0)?4:0);
}
stack.reserve(SIMPLE_STACKSIZE);
stack.push_back(sStkNP(root,0));
do {
sStkNP se=stack[stack.size()-1];
bool out=false;
stack.pop_back();
for(int i=0,j=1;(!out)&&(i<count);++i,j<<=1)
{
if(0==(se.mask&j))
{
const int side=se.node->volume.Classify(normals[i],offsets[i],signs[i]);
switch(side)
{
case -1: out=true;break;
case +1: se.mask|=j;break;
}
}
}
if(!out)
{
if((se.mask!=inside)&&(se.node->isinternal()))
{
stack.push_back(sStkNP(se.node->childs[0],se.mask));
stack.push_back(sStkNP(se.node->childs[1],se.mask));
}
else
{
if(policy.AllLeaves(se.node)) enumLeaves(se.node,policy);
}
}
} while(stack.size());
}
}
//
DBVT_PREFIX
inline void btDbvt::collideOCL( const btDbvtNode* root,
const btVector3* normals,
const btScalar* offsets,
const btVector3& sortaxis,
int count,
DBVT_IPOLICY,
bool fsort)
{
DBVT_CHECKTYPE
if(root)
{
const unsigned srtsgns=(sortaxis[0]>=0?1:0)+
(sortaxis[1]>=0?2:0)+
(sortaxis[2]>=0?4:0);
const int inside=(1<<count)-1;
btAlignedObjectArray<sStkNPS> stock;
btAlignedObjectArray<int> ifree;
btAlignedObjectArray<int> stack;
int signs[sizeof(unsigned)*8];
btAssert(count<int (sizeof(signs)/sizeof(signs[0])));
for(int i=0;i<count;++i)
{
signs[i]= ((normals[i].x()>=0)?1:0)+
((normals[i].y()>=0)?2:0)+
((normals[i].z()>=0)?4:0);
}
stock.reserve(SIMPLE_STACKSIZE);
stack.reserve(SIMPLE_STACKSIZE);
ifree.reserve(SIMPLE_STACKSIZE);
stack.push_back(allocate(ifree,stock,sStkNPS(root,0,root->volume.ProjectMinimum(sortaxis,srtsgns))));
do {
const int id=stack[stack.size()-1];
sStkNPS se=stock[id];
stack.pop_back();ifree.push_back(id);
if(se.mask!=inside)
{
bool out=false;
for(int i=0,j=1;(!out)&&(i<count);++i,j<<=1)
{
if(0==(se.mask&j))
{
const int side=se.node->volume.Classify(normals[i],offsets[i],signs[i]);
switch(side)
{
case -1: out=true;break;
case +1: se.mask|=j;break;
}
}
}
if(out) continue;
}
if(policy.Descent(se.node))
{
if(se.node->isinternal())
{
const btDbvtNode* pns[]={ se.node->childs[0],se.node->childs[1]};
sStkNPS nes[]={ sStkNPS(pns[0],se.mask,pns[0]->volume.ProjectMinimum(sortaxis,srtsgns)),
sStkNPS(pns[1],se.mask,pns[1]->volume.ProjectMinimum(sortaxis,srtsgns))};
const int q=nes[0].value<nes[1].value?1:0;
int j=stack.size();
if(fsort&&(j>0))
{
/* Insert 0 */
j=nearest(&stack[0],&stock[0],nes[q].value,0,stack.size());
stack.push_back(0);
#if DBVT_USE_MEMMOVE
memmove(&stack[j+1],&stack[j],sizeof(int)*(stack.size()-j-1));
#else
for(int k=stack.size()-1;k>j;--k) stack[k]=stack[k-1];
#endif
stack[j]=allocate(ifree,stock,nes[q]);
/* Insert 1 */
j=nearest(&stack[0],&stock[0],nes[1-q].value,j,stack.size());
stack.push_back(0);
#if DBVT_USE_MEMMOVE
memmove(&stack[j+1],&stack[j],sizeof(int)*(stack.size()-j-1));
#else
for(int k=stack.size()-1;k>j;--k) stack[k]=stack[k-1];
#endif
stack[j]=allocate(ifree,stock,nes[1-q]);
}
else
{
stack.push_back(allocate(ifree,stock,nes[q]));
stack.push_back(allocate(ifree,stock,nes[1-q]));
}
}
else
{
policy.Process(se.node,se.value);
}
}
} while(stack.size());
}
}
//
DBVT_PREFIX
inline void btDbvt::collideTU( const btDbvtNode* root,
DBVT_IPOLICY)
{
DBVT_CHECKTYPE
if(root)
{
btAlignedObjectArray<const btDbvtNode*> stack;
stack.reserve(SIMPLE_STACKSIZE);
stack.push_back(root);
do {
const btDbvtNode* n=stack[stack.size()-1];
stack.pop_back();
if(policy.Descent(n))
{
if(n->isinternal())
{ stack.push_back(n->childs[0]);stack.push_back(n->childs[1]); }
else
{ policy.Process(n); }
}
} while(stack.size()>0);
}
}
//
// PP Cleanup
//
#undef DBVT_USE_MEMMOVE
#undef DBVT_USE_TEMPLATE
#undef DBVT_VIRTUAL_DTOR
#undef DBVT_VIRTUAL
#undef DBVT_PREFIX
#undef DBVT_IPOLICY
#undef DBVT_CHECKTYPE
#undef DBVT_IMPL_GENERIC
#undef DBVT_IMPL_SSE
#undef DBVT_USE_INTRINSIC_SSE
#undef DBVT_SELECT_IMPL
#undef DBVT_MERGE_IMPL
#undef DBVT_INT0_IMPL
#endif
| 0 | 0.985279 | 1 | 0.985279 | game-dev | MEDIA | 0.657592 | game-dev | 0.930515 | 1 | 0.930515 |
liyongliang999/slam_in_autonomous_driving_change | 12,515 | thirdparty/g2o/g2o/examples/tutorial_slam2d/simulator.cpp | // g2o - General Graph Optimization
// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 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.
#include "simulator.h"
#include "rand.h"
#include <map>
#include <iostream>
#include <cmath>
using namespace std;
namespace g2o {
namespace tutorial {
using namespace Eigen;
# ifdef _MSC_VER
inline double round(double number)
{
return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5);
}
# endif
typedef std::map<int, std::map<int, Simulator::LandmarkPtrVector> > LandmarkGrid;
Simulator::Simulator()
{
time_t seed = time(0);
Rand::seed_rand(static_cast<unsigned int>(seed));
}
Simulator::~Simulator()
{
}
void Simulator::simulate(int numNodes, const SE2& sensorOffset)
{
// simulate a robot observing landmarks while travelling on a grid
int steps = 5;
double stepLen = 1.0;
int boundArea = 50;
double maxSensorRangeLandmarks = 2.5 * stepLen;
int landMarksPerSquareMeter = 1;
double observationProb = 0.8;
int landmarksRange=2;
Vector2d transNoise(0.05, 0.01);
double rotNoise = DEG2RAD(2.);
Vector2d landmarkNoise(0.05, 0.05);
Vector2d bound(boundArea, boundArea);
VectorXd probLimits;
probLimits.resize(MO_NUM_ELEMS);
for (int i = 0; i < probLimits.size(); ++i)
probLimits[i] = (i + 1) / (double) MO_NUM_ELEMS;
Matrix3d covariance;
covariance.fill(0.);
covariance(0, 0) = transNoise[0]*transNoise[0];
covariance(1, 1) = transNoise[1]*transNoise[1];
covariance(2, 2) = rotNoise*rotNoise;
Matrix3d information = covariance.inverse();
SE2 maxStepTransf(stepLen * steps, 0, 0);
Simulator::PosesVector& poses = _poses;
poses.clear();
LandmarkVector& landmarks = _landmarks;
landmarks.clear();
Simulator::GridPose firstPose;
firstPose.id = 0;
firstPose.truePose = SE2(0,0,0);
firstPose.simulatorPose = SE2(0,0,0);
poses.push_back(firstPose);
cerr << "Simulator: sampling nodes ...";
while ((int)poses.size() < numNodes) {
// add straight motions
for (int i = 1; i < steps && (int)poses.size() < numNodes; ++i) {
Simulator::GridPose nextGridPose = generateNewPose(poses.back(), SE2(stepLen,0,0), transNoise, rotNoise);
poses.push_back(nextGridPose);
}
if ((int)poses.size() == numNodes)
break;
// sample a new motion direction
double sampleMove = Rand::uniform_rand(0., 1.);
int motionDirection = 0;
while (probLimits[motionDirection] < sampleMove && motionDirection+1 < MO_NUM_ELEMS) {
motionDirection++;
}
SE2 nextMotionStep = getMotion(motionDirection, stepLen);
Simulator::GridPose nextGridPose = generateNewPose(poses.back(), nextMotionStep, transNoise, rotNoise);
// check whether we will walk outside the boundaries in the next iteration
SE2 nextStepFinalPose = nextGridPose.truePose * maxStepTransf;
if (fabs(nextStepFinalPose.translation().x()) >= bound[0] || fabs(nextStepFinalPose.translation().y()) >= bound[1]) {
//cerr << "b";
// will be outside boundaries using this
for (int i = 0; i < MO_NUM_ELEMS; ++i) {
nextMotionStep = getMotion(i, stepLen);
nextGridPose = generateNewPose(poses.back(), nextMotionStep, transNoise, rotNoise);
nextStepFinalPose = nextGridPose.truePose * maxStepTransf;
if (fabs(nextStepFinalPose.translation().x()) < bound[0] && fabs(nextStepFinalPose.translation().y()) < bound[1])
break;
}
}
poses.push_back(nextGridPose);
}
cerr << "done." << endl;
// creating landmarks along the trajectory
cerr << "Simulator: Creating landmarks ... ";
LandmarkGrid grid;
for (PosesVector::const_iterator it = poses.begin(); it != poses.end(); ++it) {
int ccx = (int)round(it->truePose.translation().x());
int ccy = (int)round(it->truePose.translation().y());
for (int a=-landmarksRange; a<=landmarksRange; a++)
for (int b=-landmarksRange; b<=landmarksRange; b++){
int cx=ccx+a;
int cy=ccy+b;
LandmarkPtrVector& landmarksForCell = grid[cx][cy];
if (landmarksForCell.size() == 0) {
for (int i = 0; i < landMarksPerSquareMeter; ++i) {
Landmark* l = new Landmark();
double offx, offy;
do {
offx = Rand::uniform_rand(-0.5*stepLen, 0.5*stepLen);
offy = Rand::uniform_rand(-0.5*stepLen, 0.5*stepLen);
} while (hypot_sqr(offx, offy) < 0.25*0.25);
l->truePose[0] = cx + offx;
l->truePose[1] = cy + offy;
landmarksForCell.push_back(l);
}
}
}
}
cerr << "done." << endl;
cerr << "Simulator: Simulating landmark observations for the poses ... ";
double maxSensorSqr = maxSensorRangeLandmarks * maxSensorRangeLandmarks;
int globalId = 0;
for (PosesVector::iterator it = poses.begin(); it != poses.end(); ++it) {
Simulator::GridPose& pv = *it;
int cx = (int)round(it->truePose.translation().x());
int cy = (int)round(it->truePose.translation().y());
int numGridCells = (int)(maxSensorRangeLandmarks) + 1;
pv.id = globalId++;
SE2 trueInv = pv.truePose.inverse();
for (int xx = cx - numGridCells; xx <= cx + numGridCells; ++xx)
for (int yy = cy - numGridCells; yy <= cy + numGridCells; ++yy) {
LandmarkPtrVector& landmarksForCell = grid[xx][yy];
if (landmarksForCell.size() == 0)
continue;
for (size_t i = 0; i < landmarksForCell.size(); ++i) {
Landmark* l = landmarksForCell[i];
double dSqr = hypot_sqr(pv.truePose.translation().x() - l->truePose.x(), pv.truePose.translation().y() - l->truePose.y());
if (dSqr > maxSensorSqr)
continue;
double obs = Rand::uniform_rand(0.0, 1.0);
if (obs > observationProb) // we do not see this one...
continue;
if (l->id < 0)
l->id = globalId++;
if (l->seenBy.size() == 0) {
Vector2d trueObservation = trueInv * l->truePose;
Vector2d observation = trueObservation;
observation[0] += Rand::gauss_rand(0., landmarkNoise[0]);
observation[1] += Rand::gauss_rand(0., landmarkNoise[1]);
l->simulatedPose = pv.simulatorPose * observation;
}
l->seenBy.push_back(pv.id);
pv.landmarks.push_back(l);
}
}
}
cerr << "done." << endl;
// add the odometry measurements
_odometry.clear();
cerr << "Simulator: Adding odometry measurements ... ";
for (size_t i = 1; i < poses.size(); ++i) {
const GridPose& prev = poses[i-1];
const GridPose& p = poses[i];
_odometry.push_back(GridEdge());
GridEdge& edge = _odometry.back();
edge.from = prev.id;
edge.to = p.id;
edge.trueTransf = prev.truePose.inverse() * p.truePose;
edge.simulatorTransf = prev.simulatorPose.inverse() * p.simulatorPose;
edge.information = information;
}
cerr << "done." << endl;
_landmarks.clear();
_landmarkObservations.clear();
// add the landmark observations
{
cerr << "Simulator: add landmark observations ... ";
Matrix2d covariance; covariance.fill(0.);
covariance(0, 0) = landmarkNoise[0]*landmarkNoise[0];
covariance(1, 1) = landmarkNoise[1]*landmarkNoise[1];
Matrix2d information = covariance.inverse();
for (size_t i = 0; i < poses.size(); ++i) {
const GridPose& p = poses[i];
for (size_t j = 0; j < p.landmarks.size(); ++j) {
Landmark* l = p.landmarks[j];
if (l->seenBy.size() > 0 && l->seenBy[0] == p.id) {
landmarks.push_back(*l);
}
}
}
for (size_t i = 0; i < poses.size(); ++i) {
const GridPose& p = poses[i];
SE2 trueInv = (p.truePose * sensorOffset).inverse();
for (size_t j = 0; j < p.landmarks.size(); ++j) {
Landmark* l = p.landmarks[j];
Vector2d observation;
Vector2d trueObservation = trueInv * l->truePose;
observation = trueObservation;
if (l->seenBy.size() > 0 && l->seenBy[0] == p.id) { // write the initial position of the landmark
observation = (p.simulatorPose * sensorOffset).inverse() * l->simulatedPose;
} else {
// create observation for the LANDMARK using the true positions
observation[0] += Rand::gauss_rand(0., landmarkNoise[0]);
observation[1] += Rand::gauss_rand(0., landmarkNoise[1]);
}
_landmarkObservations.push_back(LandmarkEdge());
LandmarkEdge& le = _landmarkObservations.back();
le.from = p.id;
le.to = l->id;
le.trueMeas = trueObservation;
le.simulatorMeas = observation;
le.information = information;
}
}
cerr << "done." << endl;
}
// cleaning up
for (LandmarkGrid::iterator it = grid.begin(); it != grid.end(); ++it) {
for (std::map<int, Simulator::LandmarkPtrVector>::iterator itt = it->second.begin(); itt != it->second.end(); ++itt) {
Simulator::LandmarkPtrVector& landmarks = itt->second;
for (size_t i = 0; i < landmarks.size(); ++i)
delete landmarks[i];
}
}
}
Simulator::GridPose Simulator::generateNewPose(const Simulator::GridPose& prev, const SE2& trueMotion, const Eigen::Vector2d& transNoise, double rotNoise)
{
Simulator::GridPose nextPose;
nextPose.id = prev.id + 1;
nextPose.truePose = prev.truePose * trueMotion;
SE2 noiseMotion = sampleTransformation(trueMotion, transNoise, rotNoise);
nextPose.simulatorPose = prev.simulatorPose * noiseMotion;
return nextPose;
}
SE2 Simulator::getMotion(int motionDirection, double stepLen)
{
switch (motionDirection) {
case MO_LEFT:
return SE2(stepLen, 0, 0.5*M_PI);
case MO_RIGHT:
return SE2(stepLen, 0, -0.5*M_PI);
default:
cerr << "Unknown motion direction" << endl;
return SE2(stepLen, 0, -0.5*M_PI);
}
}
SE2 Simulator::sampleTransformation(const SE2& trueMotion_, const Eigen::Vector2d& transNoise, double rotNoise)
{
Vector3d trueMotion = trueMotion_.toVector();
SE2 noiseMotion(
trueMotion[0] + Rand::gauss_rand(0.0, transNoise[0]),
trueMotion[1] + Rand::gauss_rand(0.0, transNoise[1]),
trueMotion[2] + Rand::gauss_rand(0.0, rotNoise));
return noiseMotion;
}
} // end namespace
} // end namespace
| 0 | 0.758954 | 1 | 0.758954 | game-dev | MEDIA | 0.612545 | game-dev | 0.967747 | 1 | 0.967747 |
cutechess/cutechess | 2,997 | projects/lib/src/board/pocketknightboard.cpp | /*
This file is part of Cute Chess.
Copyright (C) 2008-2018 Cute Chess authors
Cute Chess 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.
Cute Chess 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 Cute Chess. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pocketknightboard.h"
#include "westernzobrist.h"
namespace Chess {
PocketKnightBoard::PocketKnightBoard()
: WesternBoard(new WesternZobrist())
{
}
Board* PocketKnightBoard::copy() const
{
return new PocketKnightBoard(*this);
}
QList< Piece > PocketKnightBoard::reservePieceTypes() const
{
QList<Piece> list;
list << Piece(Side::White, Knight);
list << Piece(Side::Black, Knight);
return list;
}
QString PocketKnightBoard::variant() const
{
return "pocketknight";
}
/*!
* Most common set-up positions for Pocket Knight Chess:
* Pocket Knight Chess with full standard pieces and extra knight in pocket
* rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR[Nn] w KQkq - 0 1
* Pocket Knight Chess with Queen's Knight in pocket
* r1bqkbnr/pppppppp/8/8/8/8/PPPPPPPP/R1BQKBNR[Nn] w KQkq - 0 1
* Pocket Knight Chess with full standard set and two extra knights in pocket
* rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR[NNnn] w KQkq - 0 1
*/
QString PocketKnightBoard::defaultFenString() const
{
return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR[Nn] w KQkq - 0 1";
}
bool PocketKnightBoard::variantHasDrops() const
{
return true;
}
int PocketKnightBoard::reserveType(int) const
{
return Piece::NoPiece;
}
void PocketKnightBoard::vMakeMove(const Move& move, BoardTransition* transition)
{
int source = move.sourceSquare();
int prom = move.promotion();
int ctype = captureType(move);
if (ctype == Piece::NoPiece
&& source == 0)
removeFromReserve(Piece(sideToMove(), prom));
WesternBoard::vMakeMove(move, transition);
}
void PocketKnightBoard::vUndoMove(const Move& move)
{
int source = move.sourceSquare();
int prom = move.promotion();
WesternBoard::vUndoMove(move);
int ctype = captureType(move);
if (ctype == Piece::NoPiece
&& source == 0)
addToReserve(Piece(sideToMove(), prom));
}
void PocketKnightBoard::generateMovesForPiece(QVarLengthArray< Move >& moves, int pieceType, int square) const
{
// Generate drops
if (square == 0)
{
const int size = arraySize();
for (int i = 0; i < size; i++)
{
Piece tmp = pieceAt(i);
if (!tmp.isEmpty())
continue;
moves.append(Move(0, i, pieceType));
}
}
else
WesternBoard::generateMovesForPiece(moves, pieceType, square);
}
} // namespace Chess
| 0 | 0.768829 | 1 | 0.768829 | game-dev | MEDIA | 0.901915 | game-dev | 0.91314 | 1 | 0.91314 |
amethyst/rustrogueliketutorial | 1,865 | chapter-50-stats/src/map_builders/rooms_corridors_dogleg.rs | use super::{MetaMapBuilder, BuilderMap, Rect, apply_horizontal_tunnel, apply_vertical_tunnel };
use rltk::RandomNumberGenerator;
pub struct DoglegCorridors {}
impl MetaMapBuilder for DoglegCorridors {
#[allow(dead_code)]
fn build_map(&mut self, rng: &mut rltk::RandomNumberGenerator, build_data : &mut BuilderMap) {
self.corridors(rng, build_data);
}
}
impl DoglegCorridors {
#[allow(dead_code)]
pub fn new() -> Box<DoglegCorridors> {
Box::new(DoglegCorridors{})
}
fn corridors(&mut self, rng : &mut RandomNumberGenerator, build_data : &mut BuilderMap) {
let rooms : Vec<Rect>;
if let Some(rooms_builder) = &build_data.rooms {
rooms = rooms_builder.clone();
} else {
panic!("Dogleg Corridors require a builder with room structures");
}
let mut corridors : Vec<Vec<usize>> = Vec::new();
for (i,room) in rooms.iter().enumerate() {
if i > 0 {
let (new_x, new_y) = room.center();
let (prev_x, prev_y) = rooms[i as usize -1].center();
if rng.range(0,2) == 1 {
let mut c1 = apply_horizontal_tunnel(&mut build_data.map, prev_x, new_x, prev_y);
let mut c2 = apply_vertical_tunnel(&mut build_data.map, prev_y, new_y, new_x);
c1.append(&mut c2);
corridors.push(c1);
} else {
let mut c1 = apply_vertical_tunnel(&mut build_data.map, prev_y, new_y, prev_x);
let mut c2 = apply_horizontal_tunnel(&mut build_data.map, prev_x, new_x, new_y);
c1.append(&mut c2);
corridors.push(c1);
}
build_data.take_snapshot();
}
}
build_data.corridors = Some(corridors);
}
}
| 0 | 0.966913 | 1 | 0.966913 | game-dev | MEDIA | 0.610155 | game-dev | 0.902436 | 1 | 0.902436 |
Stewmath/oracles-disasm | 5,100 | object_code/common/interactions/minibossPortal.s | ; ==================================================================================================
; INTERAC_MINIBOSS_PORTAL
; ==================================================================================================
interactionCode7e:
ld e,Interaction.subid
ld a,(de)
rst_jumpTable
.dw @subid00
.dw @subid01
.ifdef ROM_SEASONS
.dw @subid02
.endif
; Subid $00: miniboss portals
@subid00:
ld e,Interaction.state
ld a,(de)
rst_jumpTable
.dw @minibossState0
.dw @state1
.dw @state2
.dw @minibossState3
@minibossState0:
ld a,(wDungeonIndex)
ld hl,@dungeonRoomTable
rst_addDoubleIndex
ld c,(hl)
ld a,(wActiveGroup)
ld hl,flagLocationGroupTable
rst_addAToHl
ld h,(hl)
ld l,c
; hl now points to room flags for the miniboss room
; Delete if miniboss is not dead.
ld a,(hl)
and $80
jp z,interactionDelete
ld c,$57
call objectSetShortPosition
@commonState0:
call interactionInitGraphics
ld a,$03
call objectSetCollideRadius
; Go to state 1 if Link's not touching the portal, state 2 if he is.
call objectCheckCollidedWithLink_notDeadAndNotGrabbing
ld a,$01
jr nc,+
inc a
+
ld e,Interaction.state
ld (de),a
jp objectSetVisible83
; State 1: waiting for Link to touch the portal to initiate the warp.
@state1:
call interactionAnimate
call objectCheckCollidedWithLink_notDeadAndNotGrabbing
ret nc
; Check that [w1Link.id] == SPECIALOBJECT_LINK, check collisions are enabled
ld a,(w1Link.id)
or a
call z,checkLinkCollisionsEnabled
ret nc
call resetLinkInvincibility
ld a,$03
ld e,Interaction.state
ld (de),a
ld (wLinkCanPassNpcs),a
ld a,$30
ld e,Interaction.counter1
ld (de),a
call setLinkForceStateToState08
ld hl,w1Link.visible
ld (hl),$82
call objectCopyPosition ; Link.position = this.position
ld a,$01
ld (wDisabledObjects),a
ld a,SND_TELEPORT
jp playSound
; State 2: wait for Link to get off the portal before detecting collisions
@state2:
call interactionAnimate
call objectCheckCollidedWithLink_notDeadAndNotGrabbing
ret c
ld a,$01
ld e,Interaction.state
ld (de),a
ret
; State 3: Do the warp
@minibossState3:
ld hl,w1Link
call objectCopyPosition
call @spinLink
ret nz
; Get starting room in 'b', miniboss room in 'c'
ld a,(wDungeonIndex)
ld hl,@dungeonRoomTable
rst_addDoubleIndex
ldi a,(hl)
ld c,(hl)
ld b,a
ld hl,wWarpDestGroup
ld a,(wActiveGroup)
or $80
ldi (hl),a
ld a,(wActiveRoom)
cp b
jr nz,+
ld b,c
+
ld a,b
ldi (hl),a ; [wWarpDestRoom] = b
lda TRANSITION_DEST_BASIC
ldi (hl),a ; [wWarpTransition] = TRANSITION_DEST_BASIC
ld (hl),$57 ; [wWarpDestPos] = $57
inc l
ld (hl),$03 ; [wWarpTransition2] = $03 (fadeout)
ret
; Each row corresponds to a dungeon. The first byte is the miniboss room index, the second
; is the dungeon entrance (the two locations of the portal).
; If bit 7 is set in the miniboss room's flags, the portal is enabled.
@dungeonRoomTable:
.ifdef ROM_AGES
.db $01 $04
.db $18 $24
.db $34 $46
.db $4d $66
.db $80 $91
.db $b4 $bb
.db $12 $26
.db $4d $56
.db $82 $aa
.else
.db $01 $01
.db $0b $15
.db $21 $39
.db $48 $4b
.db $6a $81
.db $a2 $a7
.db $c8 $ba
.db $42 $5b
.db $72 $87
.endif
@spinLink:
call resetLinkInvincibility
call interactionAnimate
ld a,(wLinkDeathTrigger)
or a
ret nz
ld a,(wFrameCounter)
and $03
jr nz,++
ld hl,w1Link.direction
ld a,(hl)
inc a
and $03
ld (hl),a
++
jp interactionDecCounter1
; Subid $01: miscellaneous portals used in Hero's Cave
@subid01:
ld e,Interaction.state
ld a,(de)
rst_jumpTable
.dw @herosCaveState0
.dw @state1
.dw @state2
.dw @herosCaveState3
@herosCaveState0:
.ifdef ROM_AGES
call interactionDeleteAndRetIfEnabled02
ld e,Interaction.xh
ld a,(de)
ld e,Interaction.var03
ld (de),a
bit 7,a
jr z,+
call getThisRoomFlags
and ROOMFLAG_ITEM
ret z
+
ld h,d
ld e,Interaction.yh
ld l,e
ld a,(de)
call setShortPosition
.else
ld a,(wc64a)
or a
jp z,interactionDelete
.endif
jp @commonState0
@herosCaveState3:
call @spinLink
ret nz
.ifdef ROM_AGES
; Initiate the warp
ld e,Interaction.var03
ld a,(de)
and $0f
call @initHerosCaveWarp
ld a,$84
ld (wWarpDestGroup),a
ret
.else
ld a,(wc64a)
jr @initHerosCaveWarp
@subid02:
ld e,Interaction.state
ld a,(de)
rst_jumpTable
.dw @herosCave2State0
.dw @state1
.dw @state2
.dw @herosCave2State3
@herosCave2State0:
call getThisRoomFlags
and $20
jp z,interactionDelete
jp @commonState0
@herosCave2State3:
call @spinLink
ret nz
xor a
.endif
@initHerosCaveWarp:
ld hl,@herosCaveWarps
rst_addDoubleIndex
ldi a,(hl)
ld (wWarpDestRoom),a
ldi a,(hl)
ld (wWarpDestPos),a
ld a,$85
ld (wWarpDestGroup),a
lda TRANSITION_DEST_BASIC
ld (wWarpTransition),a
ld a,$03
ld (wWarpTransition2),a ; Fadeout transition
ret
; Each row corresponds to a value for bits 0-3 of "X" (later var03).
; First byte is "wWarpDestRoom" (room index), second is "wWarpDestPos".
@herosCaveWarps:
.ifdef ROM_AGES
.db $c2 $11
.db $c3 $2c
.db $c4 $11
.db $c5 $2c
.db $c6 $7a
.db $c9 $86
.db $ce $57
.db $cf $91
.else
.db $30 $37
.db $31 $9d
.db $2f $95
.db $28 $59
.db $24 $57
.db $34 $17
.endif
| 0 | 0.682036 | 1 | 0.682036 | game-dev | MEDIA | 0.909187 | game-dev | 0.773237 | 1 | 0.773237 |
Sgt-Imalas/Sgt_Imalas-Oni-Mods | 7,117 | RonivansLegacy_ChemicalProcessing/Content/Defs/Buildings/ChemicalProcessing_IO/Chemical_NaphthaReformerConfig.cs | using HarmonyLib;
using KSerialization;
using RonivansLegacy_ChemicalProcessing.Content.Scripts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TUNING;
using UnityEngine;
using UtilLibs;
using UtilLibs.BuildingPortUtils;
namespace Dupes_Industrial_Overhaul.Chemical_Processing.Buildings
{
//==== [ CHEMICAL: NAPHTHA REFORMER CONFIG ] =================================================================
[SerializationConfig(MemberSerialization.OptIn)]
public class Chemical_NaphthaReformerConfig : IBuildingConfig
{
//--[ Base Information ]-----------------------------------------------
public static string ID = "Chemical_NaphthaReformer";
//--[ Identification and DLC stuff ]-----------------------------------
//--[ Special Settings ]-----------------------------------------------
private static readonly PortDisplayInput HydrogenGasInputPort = new PortDisplayInput(ConduitType.Gas, new CellOffset(2, 1), null, new Color32(197, 31, 139, 255));
private static readonly PortDisplayOutput methaneGasOutputPort = new PortDisplayOutput(ConduitType.Gas, new CellOffset(-1, 1), null, new Color32(255, 114, 33, 255));
private static readonly PortDisplayInput naphthaLiquidInputPort = new PortDisplayInput(ConduitType.Liquid, new CellOffset(2, -2), null, new Color32(176, 0, 255, 255));
private static readonly PortDisplayOutput PetroleumLiquidOutputPort = new PortDisplayOutput(ConduitType.Liquid, new CellOffset(-1, -2), null, new Color32(255, 195, 37, 255));
//--[ Building Definitions ]-------------------------------------------
public override BuildingDef CreateBuildingDef()
{
float[] ingredient_mass = [300f, 100f];
string[] ingredient_types = ["RefinedMetal", SimHashes.Steel.ToString()];
EffectorValues tier = NOISE_POLLUTION.NOISY.TIER6;
BuildingDef buildingDef = BuildingTemplates.CreateBuildingDef(ID, 4, 7, "naphtha_reformer_kanim", 100, 30f, ingredient_mass, ingredient_types, 800f, BuildLocationRule.Anywhere, BUILDINGS.DECOR.PENALTY.TIER2, tier);
buildingDef.Overheatable = false;
buildingDef.RequiresPowerInput = true;
buildingDef.EnergyConsumptionWhenActive = 360f;
buildingDef.ExhaustKilowattsWhenActive = 2f;
buildingDef.SelfHeatKilowattsWhenActive = 6f;
buildingDef.PowerInputOffset = new CellOffset(1, 1);
buildingDef.AudioCategory = "Metal";
SoundUtils.CopySoundsToAnim("naphtha_reformer_kanim", "algae_distillery_kanim");
ColliderOffsetHandler.GenerateBuildingDefOffsets(buildingDef, -2, 0);
//for (int i = 0; i < buildingDef.PlacementOffsets.Length; i++)
//{
// buildingDef.PlacementOffsets[i] = new CellOffset(buildingDef.PlacementOffsets[i].x, buildingDef.PlacementOffsets[i].y - 2);
//}
return buildingDef;
}
public override void ConfigureBuildingTemplate(GameObject go, Tag prefab_tag)
{
go.GetComponent<KPrefabID>().AddTag(RoomConstraints.ConstraintTags.IndustrialMachinery);
go.AddOrGet<BuildingComplete>().isManuallyOperated = false;
//-----[ Element Converter Section ]---------------------------------
ElementConverter naphtha_reforming = go.AddComponent<ElementConverter>();
naphtha_reforming.consumedElements = [
new ElementConverter.ConsumedElement(SimHashes.Naphtha.CreateTag(), 2.5f),
new ElementConverter.ConsumedElement(SimHashes.Hydrogen.CreateTag(), 0.210f) ];
naphtha_reforming.outputElements = [
new ElementConverter.OutputElement(1.125f, SimHashes.Petroleum, 371.15f, false, true, 0f, 0.5f, 0.75f, 0xff, 0),
new ElementConverter.OutputElement(0.25f, SimHashes.Methane, 388.15f, false, true, 0f, 0.5f, 0.75f, 0xff, 0),
new ElementConverter.OutputElement(1.125f, SimHashes.Bitumen, 343.15f, true, true, 0f, 0.5f, 0.25f, 0xff, 0)];
//--------------------------------------------------------------------
ElementDropper bitumenDropper = go.AddComponent<ElementDropper>();
bitumenDropper.emitMass = 50f;
bitumenDropper.emitTag = SimHashes.Bitumen.CreateTag();
bitumenDropper.emitOffset = new Vector3(0f, 1f, 0f);
Storage outputStorage = go.AddOrGet<Storage>();
outputStorage.SetDefaultStoredItemModifiers(Storage.StandardInsulatedStorage);
outputStorage.showInUI = true;
PortConduitConsumer crudeOilInput = go.AddOrGet<PortConduitConsumer>();
crudeOilInput.conduitType = ConduitType.Liquid;
crudeOilInput.consumptionRate = 10f;
crudeOilInput.capacityKG = 50f;
crudeOilInput.capacityTag = SimHashes.Naphtha.CreateTag();
crudeOilInput.forceAlwaysSatisfied = true;
crudeOilInput.wrongElementResult = ConduitConsumer.WrongElementResult.Dump;
crudeOilInput.AssignPort(naphthaLiquidInputPort);
PortConduitConsumer HydrogenInput = go.AddComponent<PortConduitConsumer>();
HydrogenInput.conduitType = ConduitType.Gas;
HydrogenInput.consumptionRate = 10f;
HydrogenInput.capacityKG = 50f;
HydrogenInput.capacityTag = SimHashes.Hydrogen.CreateTag();
HydrogenInput.forceAlwaysSatisfied = true;
HydrogenInput.wrongElementResult = ConduitConsumer.WrongElementResult.Dump;
HydrogenInput.AssignPort(HydrogenGasInputPort);
PipedConduitDispenser petrolOutput = go.AddOrGet<PipedConduitDispenser>();
petrolOutput.conduitType = ConduitType.Liquid;
petrolOutput.storage = outputStorage;
petrolOutput.alwaysDispense = true;
petrolOutput.elementFilter = [SimHashes.Petroleum];
petrolOutput.AssignPort(PetroleumLiquidOutputPort);
PipedConduitDispenser methaneOutput = go.AddComponent<PipedConduitDispenser>();
methaneOutput.storage = outputStorage;
methaneOutput.conduitType = ConduitType.Gas;
methaneOutput.alwaysDispense = true;
methaneOutput.elementFilter = [SimHashes.Methane];
methaneOutput.AssignPort(methaneGasOutputPort);
go.AddOrGet<ElementConversionBuilding>(); //Handles element converter
Prioritizable.AddRef(go);
this.AttachPort(go);
}
private void AttachPort(GameObject go)
{
PortDisplayController controller = go.AddComponent<PortDisplayController>();
controller.Init(go);
controller.AssignPort(go, HydrogenGasInputPort);
controller.AssignPort(go, methaneGasOutputPort);
controller.AssignPort(go, PetroleumLiquidOutputPort);
controller.AssignPort(go, naphthaLiquidInputPort);
}
public override void DoPostConfigureComplete(GameObject go)
{
go.AddOrGetDef<PoweredActiveController.Def>().showWorkingStatus = true;
go.AddTag(GameTags.CorrosionProof);
MakeBaseSolid.Def def = go.AddOrGetDef<MakeBaseSolid.Def>();
def.occupyFoundationLayer = false;
def.solidOffsets = new CellOffset[4];
for (int i = 0; i < 4; i++)
{
def.solidOffsets[i] = new CellOffset(i - 1, 0);
}
go.AddOrGet<ColliderOffsetHandler>().ColliderOffsetY = -2;
}
public override void DoPostConfigurePreview(BuildingDef def, GameObject go)
{
base.DoPostConfigurePreview(def, go);
this.AttachPort(go);
}
public override void DoPostConfigureUnderConstruction(GameObject go)
{
go.AddOrGet<ColliderOffsetHandler>().ColliderOffsetY = -2;
base.DoPostConfigureUnderConstruction(go);
this.AttachPort(go);
}
}
}
| 0 | 0.846042 | 1 | 0.846042 | game-dev | MEDIA | 0.977795 | game-dev | 0.842909 | 1 | 0.842909 |
IntellectualSites/fastasyncvoxelsniper | 1,605 | src/main/java/com/thevoxelbox/voxelsniper/performer/type/ink/InkNoPhysicsPerformer.java | package com.thevoxelbox.voxelsniper.performer.type.ink;
import cloud.commandframework.annotations.CommandMethod;
import cloud.commandframework.annotations.CommandPermission;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.world.block.BlockState;
import com.thevoxelbox.voxelsniper.command.argument.annotation.RequireToolkit;
import com.thevoxelbox.voxelsniper.performer.type.AbstractPerformer;
import com.thevoxelbox.voxelsniper.sniper.snipe.performer.PerformerSnipe;
import com.thevoxelbox.voxelsniper.sniper.toolkit.ToolkitProperties;
import org.jetbrains.annotations.NotNull;
@RequireToolkit
@CommandMethod(value = "performer|perf|p ink-nophys|ip")
@CommandPermission("voxelsniper.sniper")
public class InkNoPhysicsPerformer extends AbstractPerformer {
private Pattern pattern;
@CommandMethod("")
public void onPerformer(
final @NotNull PerformerSnipe snipe
) {
super.onPerformerCommand(snipe);
}
@Override
public void initialize(PerformerSnipe snipe) {
ToolkitProperties toolkitProperties = snipe.getToolkitProperties();
this.pattern = toolkitProperties.getPattern().getPattern();
}
@Override
public void perform(EditSession editSession, int x, int y, int z, BlockState block) {
setBlock(editSession, x, y, z, this.pattern);
}
@Override
public void sendInfo(PerformerSnipe snipe) {
snipe.createMessageSender()
.performerNameMessage()
.patternMessage()
.send();
}
}
| 0 | 0.757922 | 1 | 0.757922 | game-dev | MEDIA | 0.431692 | game-dev | 0.553065 | 1 | 0.553065 |
OpenStarbound/OpenStarbound | 1,459 | source/core/StarLuaConverters.cpp | #include "StarLuaConverters.hpp"
#include "StarColor.hpp"
namespace Star {
LuaValue LuaConverter<Color>::from(LuaEngine& engine, Color const& c) {
if (c.alpha() == 255)
return engine.createArrayTable(initializer_list<uint8_t>{c.red(), c.green(), c.blue()});
else
return engine.createArrayTable(initializer_list<uint8_t>{c.red(), c.green(), c.blue(), c.alpha()});
}
Maybe<Color> LuaConverter<Color>::to(LuaEngine& engine, LuaValue const& v) {
if (auto t = v.ptr<LuaTable>()) {
Color c = Color::rgba(0, 0, 0, 255);
Maybe<int> r = engine.luaMaybeTo<int>(t->get(1));
Maybe<int> g = engine.luaMaybeTo<int>(t->get(2));
Maybe<int> b = engine.luaMaybeTo<int>(t->get(3));
if (!r || !g || !b)
return {};
c.setRed(*r);
c.setGreen(*g);
c.setBlue(*b);
if (Maybe<int> a = engine.luaMaybeTo<int>(t->get(4))) {
if (!a)
return {};
c.setAlpha(*a);
}
return c;
} else if (auto s = v.ptr<LuaString>()) {
try {
return Color(s->ptr());
} catch (ColorException const&) {}
}
return {};
}
LuaValue LuaConverter<LuaCallbacks>::from(LuaEngine& engine, LuaCallbacks const& c) {
auto table = engine.createTable(0, c.callbacks().size());
for (auto& callback : c.callbacks())
table.set(callback.first, engine.createWrappedFunction(callback.second));
return table;
}
Maybe<LuaCallbacks> LuaConverter<LuaCallbacks>::to(LuaEngine&, LuaValue const&) {
return {};
}
}
| 0 | 0.896678 | 1 | 0.896678 | game-dev | MEDIA | 0.462911 | game-dev | 0.670539 | 1 | 0.670539 |
AzureeDev/payday-2-luajit | 1,585 | pd2-lua/lib/units/weapons/grenades/smokescreengrenade.lua | SmokeScreenGrenade = SmokeScreenGrenade or class(FragGrenade)
function SmokeScreenGrenade:_setup_server_data(...)
SmokeScreenGrenade.super._setup_server_data(self, ...)
if self._timer then
self._timer = math.max(self._timer, 0.1)
end
end
function SmokeScreenGrenade:set_thrower_unit(unit)
SmokeScreenGrenade.super.set_thrower_unit(self, unit)
self._has_dodge_bonus = self._thrower_unit ~= managers.player:player_unit() and self._thrower_unit:base():upgrade_value("player", "sicario_multiplier")
end
function SmokeScreenGrenade:_detonate(tag, unit, body, other_unit, other_body, position, normal, collision_velocity, velocity, other_velocity, new_velocity, direction, damage, ...)
local pos = self._unit:position()
local normal = math.UP
local range = self._range
if Network:is_server() then
managers.network:session():send_to_peers_synched("sync_unit_event_id_16", self._unit, "base", GrenadeBase.EVENT_IDS.detonate)
end
managers.player:spawn_smoke_screen(pos, normal, self._unit, self._has_dodge_bonus)
managers.groupai:state():propagate_alert({
"explosion",
pos,
range,
managers.groupai:state("civilian_enemies"),
self._unit
})
end
function SmokeScreenGrenade:bullet_hit()
end
function SmokeScreenGrenade:_detonate_on_client()
self:_detonate()
end
function SmokeScreenGrenade:update(unit, t, dt)
if self._timer then
self._timer = self._timer - dt
if self._timer <= 0 and mvector3.length(self._unit:body("static_body"):velocity()) < 1 then
self._timer = nil
self:_detonate()
end
end
ProjectileBase.update(self, unit, t, dt)
end
| 0 | 0.972981 | 1 | 0.972981 | game-dev | MEDIA | 0.929723 | game-dev | 0.914002 | 1 | 0.914002 |
AstralOrdana/Immersive-Weathering | 1,801 | common/src/main/java/com/ordana/immersive_weathering/reg/ModEntities.java | package com.ordana.immersive_weathering.reg;
import com.ordana.immersive_weathering.ImmersiveWeathering;
import com.ordana.immersive_weathering.entities.FallingIcicleEntity;
import com.ordana.immersive_weathering.entities.FallingLayerEntity;
import com.ordana.immersive_weathering.entities.FallingPropaguleEntity;
import com.ordana.immersive_weathering.entities.IcicleBlockEntity;
import net.mehvahdjukaar.moonlight.api.platform.PlatHelper;
import net.mehvahdjukaar.moonlight.api.platform.RegHelper;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.block.entity.BlockEntityType;
import java.util.function.Supplier;
public class ModEntities {
public static void init() {
}
//entities
public static Supplier<EntityType<FallingIcicleEntity>> FALLING_ICICLE = RegHelper.registerEntityType(
ImmersiveWeathering.res("falling_icicle"),
FallingIcicleEntity::new, MobCategory.MISC, 0.98F, 0.98F, 10, 20);
public static Supplier<EntityType<FallingLayerEntity>> FALLING_LAYER = RegHelper.registerEntityType(
ImmersiveWeathering.res("falling_layer"),
FallingLayerEntity::new, MobCategory.MISC, 0.98F, 0.98F, 10, 20);
public static Supplier<EntityType<FallingPropaguleEntity>> FALLING_PROPAGULE = RegHelper.registerEntityType(
ImmersiveWeathering.res("falling_propagule"),
FallingPropaguleEntity::new, MobCategory.MISC, 0.28F, 0.98F, 10, 20);
//block entities
public static final Supplier<BlockEntityType<IcicleBlockEntity>> ICICLE_TILE = RegHelper.registerBlockEntityType(
ImmersiveWeathering.res("icicle"),
() -> PlatHelper.newBlockEntityType(IcicleBlockEntity::new, ModBlocks.ICICLE.get()));
}
| 0 | 0.638673 | 1 | 0.638673 | game-dev | MEDIA | 0.979175 | game-dev | 0.661328 | 1 | 0.661328 |
FederatedAI/eggroll | 4,727 | jvm/cluster_dashboard/src/main/java/org/fedai/eggroll/webapp/dao/NodeResourceDao.java | package org.fedai.eggroll.webapp.dao;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import org.fedai.eggroll.clustermanager.entity.NodeResource;
import org.fedai.eggroll.clustermanager.entity.ServerNode;
import org.fedai.eggroll.webapp.dao.impl.NodeResourceService;
import org.fedai.eggroll.webapp.dao.impl.ServerNodeService;
import org.fedai.eggroll.webapp.queryobject.NodeResourceQO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Singleton
public class NodeResourceDao {
Logger logger = LoggerFactory.getLogger(NodeResourceDao.class);
@Inject
ServerNodeService serverNodeService;
@Inject
NodeResourceService nodeResourceService;
public PageInfo<NodeResource> queryData(NodeResourceQO nodeResourceQO) {
PageHelper.startPage(nodeResourceQO.getPageNum(), nodeResourceQO.getPageSize(), true);
QueryWrapper<NodeResource> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("created_at");
if (StringUtils.isNotBlank(nodeResourceQO.getResourceId())
|| StringUtils.isNotBlank(nodeResourceQO.getServerNodeId())
|| StringUtils.isNotBlank(nodeResourceQO.getStatus())
|| StringUtils.isNotBlank(nodeResourceQO.getResourceType())) {
queryWrapper.lambda()
.like(StringUtils.isNotBlank(nodeResourceQO.getResourceId()), NodeResource::getResourceId, nodeResourceQO.getResourceId())
.and(StringUtils.isNotBlank(nodeResourceQO.getServerNodeId()), i -> i.like(NodeResource::getServerNodeId, nodeResourceQO.getServerNodeId()))
.and(StringUtils.isNotBlank(nodeResourceQO.getStatus()), i -> i.like(NodeResource::getStatus, nodeResourceQO.getStatus()))
.and(StringUtils.isNotBlank(nodeResourceQO.getResourceType()), i -> i.like(NodeResource::getResourceType, nodeResourceQO.getResourceType()));
}
List<NodeResource> list = this.nodeResourceService.list(queryWrapper);
PageInfo<NodeResource> result = new PageInfo<>(list);
return result;
}
// 查询cpu剩余资源数据
public Map<String, Long> queryCpuResources() {
QueryWrapper<NodeResource> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("resource_type", "VCPU_CORE");
List<NodeResource> nodeResourceList = this.nodeResourceService.list(queryWrapper);
List<ServerNode> serverNodeList = this.serverNodeService.list();
if (nodeResourceList == null || nodeResourceList.isEmpty() || serverNodeList == null || serverNodeList.isEmpty()) {
return null;
}
Long cpuResource = 0L;
Map<String, Long> resourcesMap = new HashMap<>();
for (ServerNode serverNode : serverNodeList) {
for (NodeResource nodeResource : nodeResourceList) {
if (serverNode.getServerNodeId().equals(nodeResource.getServerNodeId())) {
String ip = serverNode.getHost();
if (!resourcesMap.containsKey(ip)) {
cpuResource = nodeResource.getTotal() - nodeResource.getUsed();
resourcesMap.put(ip, cpuResource);
}
}
}
}
return resourcesMap;
}
// 查询GPU剩余资源数据
public Map<String, Long> queryGpuResources() {
QueryWrapper<NodeResource> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("resource_type", "VGPU_CORE");
List<NodeResource> nodeResourceList = this.nodeResourceService.list(queryWrapper);
List<ServerNode> serverNodeList = this.serverNodeService.list();
if (nodeResourceList == null || nodeResourceList.isEmpty() || serverNodeList == null || serverNodeList.isEmpty()) {
return null;
}
Long gpuResource = 0L;
Map<String, Long> resourcesMap = new HashMap<>();
for (ServerNode serverNode : serverNodeList) {
for (NodeResource nodeResource : nodeResourceList) {
if (serverNode.getServerNodeId().equals(nodeResource.getServerNodeId())) {
String ip = serverNode.getHost();
if (!resourcesMap.containsKey(ip)) {
gpuResource = nodeResource.getTotal() - nodeResource.getUsed();
resourcesMap.put(ip, gpuResource);
}
}
}
}
return resourcesMap;
}
}
| 0 | 0.786285 | 1 | 0.786285 | game-dev | MEDIA | 0.218457 | game-dev | 0.923128 | 1 | 0.923128 |
Robosturm/Commander_Wars | 2,772 | resources/scripts/terrain/plains.js | var Constructor = function()
{
this.getTerrainGroup = function()
{
return 1;
};
this.getDefaultPalette = function()
{
return "palette_clear";
};
this.init = function (terrain)
{
if (terrain.getPalette() === "")
{
terrain.setPalette(PLAINS.getDefaultPalette());
}
terrain.setTerrainName(PLAINS.getName());
};
this.getName = function()
{
return qsTr("Plains");
};
this.getDefense = function()
{
return 1;
};
this.loadBaseSprite = function(terrain, currentTerrainID, map)
{
var random = globals.randInt(0, 33);
if (random < 12)
{
terrain.loadBaseSprite("plains+" + random.toString());
}
else
{
terrain.loadBaseSprite("plains+" + (random - 12).toString());
}
};
this.loadOverlaySprite = function(terrain, map)
{
var x = terrain.getX();
var y = terrain.getY();
var highTerrain = terrain.getSurroundings(TERRAIN.getHighTerrains(), true, false, GameEnums.Directions_West, false);
if (map.onMap(x - 1, y))
{
var building = map.getTerrain(x - 1, y).getBuilding();
if (building !== null &&
building.getBuildingWidth() === 1 &&
building.getBuildingHeigth() === 1)
{
highTerrain = "+W";
}
}
if (highTerrain !== "")
{
terrain.loadOverlaySprite("shadow_plains", -1, -1, terrain.getNeighbourPalette(GameEnums.Directions_West, ""));
}
};
this.getMiniMapIcon = function()
{
return "minimap_plains";
};
this.getDescription = function()
{
return qsTr("Ground units move easily on this terrain.");
};
this.getTerrainSprites = function()
{
// array of sprites that can be selected as fix sprites for this terrain
return ["plains+0",
"plains+1",
"plains+2",
"plains+3",
"plains+4",
"plains+5",
"plains+6",
"plains+7",
"plains+8",
"plains+9",
"plains+10",
"plains+11",
"plains+12",
"plains+13",
"plains+14",
"plains+15",
"plains+16",
"plains+17",
"plains+18",
"plains+19",
"plains+20",
"plains+21"];
};
this.getOverlayTerrainSprites = function(map)
{
return ["shadow_plains"]
};
};
Constructor.prototype = TERRAIN;
var PLAINS = new Constructor();
| 0 | 0.845466 | 1 | 0.845466 | game-dev | MEDIA | 0.950783 | game-dev | 0.895295 | 1 | 0.895295 |
Craftventure/open-plugin-parts | 24,532 | net/craftventure/core/feature/casino/WheelOfFortune.java | package net.craftventure.core.feature.casino;
import net.craftventure.bukkit.ktx.MaterialConfig;
import net.craftventure.bukkit.ktx.manager.MessageBarManager;
import net.craftventure.bukkit.ktx.util.ChatUtils;
import net.craftventure.bukkit.ktx.util.SoundUtils;
import net.craftventure.bukkit.ktx.util.Translation;
import net.craftventure.core.CraftventureCore;
import net.craftventure.core.async.AsyncTask;
import net.craftventure.core.ktx.util.Logger;
import net.craftventure.core.ktx.util.TimeUtils;
import net.craftventure.core.map.renderer.MapManager;
import net.craftventure.core.npc.NpcEntity;
import net.craftventure.core.npc.tracker.NpcAreaTracker;
import net.craftventure.core.utils.LocationUtil;
import net.craftventure.database.MainRepositoryProvider;
import net.craftventure.database.generated.cvdata.tables.pojos.BankAccount;
import net.craftventure.database.type.BankAccountType;
import net.craftventure.database.type.TransactionType;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Sign;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Directional;
import org.bukkit.block.data.type.Switch;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import penner.easing.Quad;
import javax.annotation.Nullable;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
// TODO: Either unrig this or ban Aron so that it doesnt leak that this machine is 1000% rigged and not just random
public class WheelOfFortune implements Listener {
private static final int MAX_INPUT_AMOUNT = 2;
private final Location centerLocation;
private int bukkitTaskId = -1;
private int countdownTaskId = -1;
private boolean isCountingDown = false;
private boolean isPlaying = false;
private final Wheel wheel;
private final List<InputSign> inputSigns = new ArrayList<>(4 * 3);
private final List<FortunePlayer> fortunePlayers = new ArrayList<>();
public static WheelOfFortune wheelOfFortune;
public WheelOfFortune(NpcAreaTracker areaTracker) {
wheelOfFortune = this;
this.centerLocation = new Location(Bukkit.getWorld("world"), 139.5, 43.5 - 1.45, -807.5, 90, 0);
Bukkit.getServer().getPluginManager().registerEvents(this, CraftventureCore.getInstance());
wheel = new Wheel(centerLocation);
areaTracker.addEntity(wheel.npcEntity);
areaTracker.addEntity(wheel.backside);
onValuesUpdated();
inputSigns.add(new InputSign(new Location(Bukkit.getWorld("world"), 130.0, 40, -806), InputColor.YELLOW, 10));
inputSigns.add(new InputSign(new Location(Bukkit.getWorld("world"), 130.0, 40, -807), InputColor.GREEN, 10));
inputSigns.add(new InputSign(new Location(Bukkit.getWorld("world"), 130.0, 40, -809), InputColor.RED, 10));
inputSigns.add(new InputSign(new Location(Bukkit.getWorld("world"), 130.0, 40, -810), InputColor.PURPLE, 10));
inputSigns.add(new InputSign(new Location(Bukkit.getWorld("world"), 130.0, 41, -806), InputColor.YELLOW, 100));
inputSigns.add(new InputSign(new Location(Bukkit.getWorld("world"), 130.0, 41, -807), InputColor.GREEN, 100));
inputSigns.add(new InputSign(new Location(Bukkit.getWorld("world"), 130.0, 41, -809), InputColor.RED, 100));
inputSigns.add(new InputSign(new Location(Bukkit.getWorld("world"), 130.0, 41, -810), InputColor.PURPLE, 100));
inputSigns.add(new InputSign(new Location(Bukkit.getWorld("world"), 130.0, 42, -806), InputColor.YELLOW, 1000));
inputSigns.add(new InputSign(new Location(Bukkit.getWorld("world"), 130.0, 42, -807), InputColor.GREEN, 1000));
inputSigns.add(new InputSign(new Location(Bukkit.getWorld("world"), 130.0, 42, -809), InputColor.RED, 1000));
inputSigns.add(new InputSign(new Location(Bukkit.getWorld("world"), 130.0, 42, -810), InputColor.PURPLE, 1000));
inputSigns.add(new InputSign(new Location(Bukkit.getWorld("world"), 130.0, 41, -808), null, 0));
for (InputSign inputSign : inputSigns) {
updateSign(inputSign);
}
}
private void updateSign(InputSign inputSign) {
if (inputSign.getLocation().getBlock().getState() instanceof Sign) {
BlockData blockData = Material.SPRUCE_WALL_SIGN.createBlockData();
if (blockData instanceof Directional) {
Directional directional = (Directional) blockData;
directional.setFacing(BlockFace.EAST);
}
inputSign.getLocation().getBlock().setBlockData(blockData);
// inputSign.getLocation().getBlock().setData((byte) 5);
}
if (inputSign.getLocation().getBlock().getState() instanceof Sign) {
Sign sign = (Sign) inputSign.getLocation().getBlock().getState();
sign.line(0, Component.empty());
sign.line(1, inputSign.getColor().displayName());
if (inputSign.getAmount() == 0)
sign.line(2, Component.text("Reset this color", NamedTextColor.DARK_RED));
else
sign.line(2, Component.text(inputSign.getAmount() + "VC", NamedTextColor.DARK_GREEN));
sign.line(3, Component.empty());
// sign.setLine(3, "§4Right click -" + inputSign.getAmount() + "VC");
sign.update(true);
}
}
public void play() {
if (!isPlaying) {
cancelCountdown();
isPlaying = true;
wheel.newRandoms();
bukkitTaskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(CraftventureCore.getInstance(), () -> {
if (!wheel.update()) {
Bukkit.getScheduler().cancelTask(bukkitTaskId);
int space = (int) Math.floor(wheel.targetAngle % 360 / 90d);
// Logger.console("Space " + space);
final List<FortunePlayer> fortunePlayers = new ArrayList<>(WheelOfFortune.this.fortunePlayers);
new AsyncTask() {
final List<Player> players = new ArrayList<>();
@Override
public void doInBackground() {
try {
for (FortunePlayer fortunePlayer : fortunePlayers) {
fortunePlayer.player.sendMessage(Translation.CASINO_WOF_PROCESSED.getTranslation(fortunePlayer.player));
}
for (FortunePlayer fortunePlayer : fortunePlayers) {
fortunePlayer.player.playSound(fortunePlayer.player.getLocation(), SoundUtils.INSTANCE.getMONEY(), 10f, 1f);
int input = -(fortunePlayer.purple + fortunePlayer.yellow + fortunePlayer.red + fortunePlayer.green);
int win = 0;
if (space == 0 && fortunePlayer.purple > 0) {
win += (fortunePlayer.purple * 4);
} else if (space == 1 && fortunePlayer.yellow > 0) {
win += (fortunePlayer.yellow * 4);
} else if (space == 2 && fortunePlayer.green > 0) {
win += (fortunePlayer.green * 4);
} else if (space == 3 && fortunePlayer.red > 0) {
win += (fortunePlayer.red * 4);
}
MainRepositoryProvider.INSTANCE.getCasinoLogRepository().createOrUpdate(fortunePlayer.player.getUniqueId(), "wof", win);
if (win != 0)
fortunePlayer.player.sendMessage(Translation.CASINO_WOF_WON.getTranslation(fortunePlayer.player, win));
else
fortunePlayer.player.sendMessage(Translation.CASINO_WOF_LOST.getTranslation(fortunePlayer.player));
MessageBarManager.remove(fortunePlayer.player, ChatUtils.INSTANCE.getID_CASINO());
MainRepositoryProvider.INSTANCE.getBankAccountRepository().delta(fortunePlayer.player.getUniqueId(), BankAccountType.VC, win, TransactionType.CASINO_WIN);
MainRepositoryProvider.INSTANCE.getBankAccountRepository().delta(fortunePlayer.player.getUniqueId(), BankAccountType.VC, input, TransactionType.CASINO_SPEND);
// Logger.console("%s won %s (spent %s)", fortunePlayer.player.getName(), win, input);
players.add(fortunePlayer.player);
}
for (FortunePlayer fortunePlayer : fortunePlayers) {
if (fortunePlayer.player != null)
MainRepositoryProvider.INSTANCE.getAchievementProgressRepository().reward(fortunePlayer.player.getUniqueId(), "casino_spend");
fortunePlayer.player = null;
}
} catch (Exception e) {
Logger.capture(e);
}
MapManager.getInstance().invalidateForCasinoMachine("wof");
}
}.executeNow();
isPlaying = false;
WheelOfFortune.this.fortunePlayers.clear();
}
}, 1L, 1L);
}
}
private void cancelCountdown() {
if (isCountingDown) {
Bukkit.getScheduler().cancelTask(countdownTaskId);
isCountingDown = false;
}
}
private void triggerCountdown() {
if (!isCountingDown) {
isCountingDown = true;
countdownTaskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(CraftventureCore.getInstance(), new Runnable() {
int secondsLeft = 30;
@Override
public void run() {
if (secondsLeft <= 0) {
play();
return;
}
if (secondsLeft < 5 || secondsLeft % 5 == 0) {
for (FortunePlayer fortunePlayer : fortunePlayers) {
fortunePlayer.player.sendMessage(Translation.CASINO_WOF_SPINNING.getTranslation(fortunePlayer.player, secondsLeft));
}
}
secondsLeft--;
}
}, 0L, 20L);
}
}
@Nullable
public FortunePlayer get(Player player) {
for (FortunePlayer fortunePlayer : fortunePlayers) {
if (fortunePlayer.player == player) {
return fortunePlayer;
}
}
return null;
}
public FortunePlayer getOrCreate(Player player) {
FortunePlayer fortunePlayer = get(player);
if (fortunePlayer == null) {
fortunePlayer = new FortunePlayer(player);
fortunePlayers.add(fortunePlayer);
player.sendMessage(Translation.CASINO_WOF_JOIN.getTranslation(player));
triggerCountdown();
}
return fortunePlayer;
}
public void remove(Player player) {
for (Iterator<FortunePlayer> fortunePlayerIterator = fortunePlayers.iterator(); fortunePlayerIterator.hasNext(); ) {
FortunePlayer fortunePlayer = fortunePlayerIterator.next();
if (fortunePlayer.player == player) {
fortunePlayerIterator.remove();
if (fortunePlayers.size() == 0) {
cancelCountdown();
}
onValuesUpdated();
return;
}
}
}
public void onValuesUpdated() {
// int yellow = 0;
// int green = 0;
// int red = 0;
// int purple = 0;
//
// for (FortunePlayer fortunePlayer : fortunePlayers) {
// yellow += fortunePlayer.yellow;
// green += fortunePlayer.green;
// red += fortunePlayer.red;
// purple += fortunePlayer.purple;
// }
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerInteractEvent(PlayerInteractEvent event) {
Block block = event.getClickedBlock();
if (block != null) {
for (int i = 0; i < inputSigns.size(); i++) {
InputSign inputSign = inputSigns.get(i);
if (LocationUtil.INSTANCE.equals(inputSign.getLocation(), block) ||
LocationUtil.INSTANCE.equals(inputSign.getBlockLocation(), block)) {
event.setCancelled(true);
}
}
}
if (isPlaying) {
return;
}
if (block != null && (block.getState() instanceof Sign || block.getType().data.isAssignableFrom(Switch.class)) && (event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_BLOCK)) {
for (int i = 0; i < inputSigns.size(); i++) {
InputSign inputSign = inputSigns.get(i);
if (LocationUtil.INSTANCE.equals(inputSign.getLocation(), block)) {
boolean isInput = inputSign.getAmount() > 0;
FortunePlayer fortunePlayer = get(event.getPlayer());
if (CraftventureCore.getInstance().isShuttingDown() && fortunePlayer == null) {
event.getPlayer().sendMessage(Translation.SHUTDOWN_PREPARING.getTranslation(event.getPlayer()));
return;
}
if (isInput)
fortunePlayer = getOrCreate(event.getPlayer());
if (fortunePlayer != null) {
if (!fortunePlayer.canIncreaseWith(inputSign.getAmount()) && isInput) {
fortunePlayer.player.sendMessage(Translation.CASINO_WOF_NOT_ENOUGH_VENTURECOINS.getTranslation(fortunePlayer.player,
BankAccountType.VC.getPluralName(),
BankAccountType.VC.getPluralName()));
if (fortunePlayer.total() == 0)
remove(event.getPlayer());
return;
}
}
if (inputSign.getColor() == InputColor.YELLOW) {
if (fortunePlayer != null)
if (fortunePlayer.canSetYellow())
if (isInput) fortunePlayer.yellow += inputSign.getAmount();
else fortunePlayer.yellow = 0;
else
fortunePlayer.player.sendMessage(Translation.CASINO_WOF_MAX_INPUT.getTranslation(fortunePlayer.player, MAX_INPUT_AMOUNT));
} else if (inputSign.getColor() == InputColor.GREEN) {
if (fortunePlayer != null)
if (fortunePlayer.canSetGreen())
if (isInput) fortunePlayer.green += inputSign.getAmount();
else fortunePlayer.green = 0;
else
fortunePlayer.player.sendMessage(Translation.CASINO_WOF_MAX_INPUT.getTranslation(fortunePlayer.player, MAX_INPUT_AMOUNT));
} else if (inputSign.getColor() == InputColor.RED) {
if (fortunePlayer != null)
if (fortunePlayer.canSetRed())
if (isInput) fortunePlayer.red += inputSign.getAmount();
else fortunePlayer.red = 0;
else
fortunePlayer.player.sendMessage(Translation.CASINO_WOF_MAX_INPUT.getTranslation(fortunePlayer.player, MAX_INPUT_AMOUNT));
} else if (inputSign.getColor() == InputColor.PURPLE) {
if (fortunePlayer != null)
if (fortunePlayer.canSetPurple())
if (isInput) fortunePlayer.purple += inputSign.getAmount();
else fortunePlayer.purple = 0;
else
fortunePlayer.player.sendMessage(Translation.CASINO_WOF_MAX_INPUT.getTranslation(fortunePlayer.player, MAX_INPUT_AMOUNT));
} else if (inputSign.color == null) {
if (fortunePlayer != null) {
fortunePlayer.yellow = 0;
fortunePlayer.green = 0;
fortunePlayer.purple = 0;
fortunePlayer.red = 0;
}
}
event.setCancelled(true);
if (fortunePlayer != null)
fortunePlayer.onValuesUpdated();
return;
}
}
}
}
// @EventHandler
// public void onPlayerQuit(PlayerQuitEvent event) {
// remove(event.getPlayer());
// }
private class FortunePlayer {
private Player player;
private int yellow;
private int green;
private int red;
private int purple;
public FortunePlayer(Player player) {
this.player = player;
}
public int total() {
return yellow + green + red + purple;
}
public boolean canSetYellow() {
int colorsSet = 0;
// if (yellow > 0) colorsSet++;
if (green > 0) colorsSet++;
if (red > 0) colorsSet++;
if (purple > 0) colorsSet++;
return colorsSet < MAX_INPUT_AMOUNT;
}
public boolean canSetGreen() {
int colorsSet = 0;
if (yellow > 0) colorsSet++;
// if (green > 0) colorsSet++;
if (red > 0) colorsSet++;
if (purple > 0) colorsSet++;
return colorsSet < MAX_INPUT_AMOUNT;
}
public boolean canSetRed() {
int colorsSet = 0;
if (yellow > 0) colorsSet++;
if (green > 0) colorsSet++;
// if (red > 0) colorsSet++;
if (purple > 0) colorsSet++;
return colorsSet < MAX_INPUT_AMOUNT;
}
public boolean canSetPurple() {
int colorsSet = 0;
if (yellow > 0) colorsSet++;
if (green > 0) colorsSet++;
if (red > 0) colorsSet++;
// if (purple > 0) colorsSet++;
return colorsSet < MAX_INPUT_AMOUNT;
}
public boolean canIncreaseWith(int amount) {
BankAccount bankAccount = MainRepositoryProvider.INSTANCE.getBankAccountRepository().getOrCreate(player.getUniqueId(), BankAccountType.VC);
if (bankAccount != null) {
return bankAccount.getBalance() >= yellow + green + red + purple + amount;
}
return false;
}
public void onValuesUpdated() {
yellow = Math.max(0, yellow);
green = Math.max(0, green);
red = Math.max(0, red);
purple = Math.max(0, purple);
if (yellow == 0 && green == 0 && red == 0 && purple == 0) {
remove(player);
MessageBarManager.remove(player, ChatUtils.INSTANCE.getID_CASINO());
player.sendMessage(Translation.CASINO_WOF_LEAVE.getTranslation(player));
} else {
MessageBarManager.display(player,
Translation.CASINO_WOF_INPUT.getTranslation(player, yellow, green, red, purple),
MessageBarManager.Type.CASINO,
TimeUtils.secondsFromNow(40.0),
ChatUtils.INSTANCE.getID_CASINO()
);
}
player.playSound(player.getLocation(), SoundUtils.INSTANCE.getR3_CLICK1(), 10f, 1f);
WheelOfFortune.this.onValuesUpdated();
}
}
private class Wheel {
private final SecureRandom secureRandom = new SecureRandom();
private double targetAngle;
private int spinDuration;
private final NpcEntity npcEntity;
private final NpcEntity backside;
private double startAngle;
private int currentTick;
private int lastSpot = 0;
public Wheel(Location centerLocation) {
npcEntity = new NpcEntity("wof", EntityType.ARMOR_STAND, centerLocation);
npcEntity.invisible(true);
// npcEntity.marker(true);
npcEntity.helmet(MaterialConfig.INSTANCE.getCASINO_ARROW());
npcEntity.head(0, 0, 0);
for (int i = 0; i < 10; i++)
secureRandom.nextDouble();
backside = new NpcEntity("wof", EntityType.ARMOR_STAND, centerLocation);
backside.invisible(true);
// npcEntity.marker(true);
backside.helmet(MaterialConfig.INSTANCE.getCASINO_WOF());
backside.head(0, 0, 0);
}
void newRandoms() {
targetAngle = 0;
while (targetAngle % 90 < 2 || targetAngle % 90 > 88) {
targetAngle = (secureRandom.nextDouble() * 360) + ((secureRandom.nextInt(2) + 3) * 360);
}
spinDuration = secureRandom.nextInt(20 * 5) + (5 * 20);
currentTick = 0;
startAngle = startAngle % 360;
}
boolean update() {
currentTick++;
double percentage = Quad.easeOut(currentTick, (float) startAngle, (float) targetAngle, spinDuration);
npcEntity.head(0, 0, (float) (percentage));
if (currentTick > spinDuration) {
return false;
}
int newSpot = (int) Math.floor((percentage % 360) / 90.0);
// Logger.info(percentage + " > " + newSpot);
if (newSpot != lastSpot) {
playTickSound();
lastSpot = newSpot;
}
return true;
}
private void playTickSound() {
centerLocation.getWorld().playSound(centerLocation, Sound.BLOCK_DISPENSER_FAIL, 1f, 1f);
}
}
public enum InputColor {
PURPLE(Component.text("Purple", NamedTextColor.BLUE, net.kyori.adventure.text.format.TextDecoration.BOLD)),
YELLOW(Component.text("Yellow", NamedTextColor.GOLD, net.kyori.adventure.text.format.TextDecoration.BOLD)),
GREEN(Component.text("Green", NamedTextColor.GREEN, net.kyori.adventure.text.format.TextDecoration.BOLD)),
RED(Component.text("Red", NamedTextColor.RED, net.kyori.adventure.text.format.TextDecoration.BOLD));
private final Component displayName;
InputColor(Component displayName) {
this.displayName = displayName;
}
public Component displayName() {
return displayName;
}
}
public static class InputSign {
private final Location location;
private final Location blockLocation;
@Nullable
private final InputColor color;
private final int amount;
public InputSign(Location location, @Nullable InputColor color, int amount) {
this.location = location;
this.color = color;
this.amount = amount;
this.blockLocation = this.location.clone().add(-1, 0, 0);
}
public Location getLocation() {
return location;
}
public Location getBlockLocation() {
return blockLocation;
}
public @Nullable InputColor getColor() {
return color;
}
public int getAmount() {
return amount;
}
}
}
| 0 | 0.961033 | 1 | 0.961033 | game-dev | MEDIA | 0.964065 | game-dev | 0.992841 | 1 | 0.992841 |
seanhess/wizardwar | 11,764 | Frameworks/Cocos2d/external/Box2d/Box2D/Dynamics/Joints/b2GearJoint.cpp | /*
* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Joints/b2GearJoint.h>
#include <Box2D/Dynamics/Joints/b2RevoluteJoint.h>
#include <Box2D/Dynamics/Joints/b2PrismaticJoint.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2TimeStep.h>
// Gear Joint:
// C0 = (coordinate1 + ratio * coordinate2)_initial
// C = (coordinate1 + ratio * coordinate2) - C0 = 0
// J = [J1 ratio * J2]
// K = J * invM * JT
// = J1 * invM1 * J1T + ratio * ratio * J2 * invM2 * J2T
//
// Revolute:
// coordinate = rotation
// Cdot = angularVelocity
// J = [0 0 1]
// K = J * invM * JT = invI
//
// Prismatic:
// coordinate = dot(p - pg, ug)
// Cdot = dot(v + cross(w, r), ug)
// J = [ug cross(r, ug)]
// K = J * invM * JT = invMass + invI * cross(r, ug)^2
b2GearJoint::b2GearJoint(const b2GearJointDef* def)
: b2Joint(def)
{
m_joint1 = def->joint1;
m_joint2 = def->joint2;
m_typeA = m_joint1->GetType();
m_typeB = m_joint2->GetType();
b2Assert(m_typeA == e_revoluteJoint || m_typeA == e_prismaticJoint);
b2Assert(m_typeB == e_revoluteJoint || m_typeB == e_prismaticJoint);
float32 coordinateA, coordinateB;
// TODO_ERIN there might be some problem with the joint edges in b2Joint.
m_bodyC = m_joint1->GetBodyA();
m_bodyA = m_joint1->GetBodyB();
// Get geometry of joint1
b2Transform xfA = m_bodyA->m_xf;
float32 aA = m_bodyA->m_sweep.a;
b2Transform xfC = m_bodyC->m_xf;
float32 aC = m_bodyC->m_sweep.a;
if (m_typeA == e_revoluteJoint)
{
b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint1;
m_localAnchorC = revolute->m_localAnchorA;
m_localAnchorA = revolute->m_localAnchorB;
m_referenceAngleA = revolute->m_referenceAngle;
m_localAxisC.SetZero();
coordinateA = aA - aC - m_referenceAngleA;
}
else
{
b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint1;
m_localAnchorC = prismatic->m_localAnchorA;
m_localAnchorA = prismatic->m_localAnchorB;
m_referenceAngleA = prismatic->m_referenceAngle;
m_localAxisC = prismatic->m_localXAxisA;
b2Vec2 pC = m_localAnchorC;
b2Vec2 pA = b2MulT(xfC.q, b2Mul(xfA.q, m_localAnchorA) + (xfA.p - xfC.p));
coordinateA = b2Dot(pA - pC, m_localAxisC);
}
m_bodyD = m_joint2->GetBodyA();
m_bodyB = m_joint2->GetBodyB();
// Get geometry of joint2
b2Transform xfB = m_bodyB->m_xf;
float32 aB = m_bodyB->m_sweep.a;
b2Transform xfD = m_bodyD->m_xf;
float32 aD = m_bodyD->m_sweep.a;
if (m_typeB == e_revoluteJoint)
{
b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint2;
m_localAnchorD = revolute->m_localAnchorA;
m_localAnchorB = revolute->m_localAnchorB;
m_referenceAngleB = revolute->m_referenceAngle;
m_localAxisD.SetZero();
coordinateB = aB - aD - m_referenceAngleB;
}
else
{
b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint2;
m_localAnchorD = prismatic->m_localAnchorA;
m_localAnchorB = prismatic->m_localAnchorB;
m_referenceAngleB = prismatic->m_referenceAngle;
m_localAxisD = prismatic->m_localXAxisA;
b2Vec2 pD = m_localAnchorD;
b2Vec2 pB = b2MulT(xfD.q, b2Mul(xfB.q, m_localAnchorB) + (xfB.p - xfD.p));
coordinateB = b2Dot(pB - pD, m_localAxisD);
}
m_ratio = def->ratio;
m_constant = coordinateA + m_ratio * coordinateB;
m_impulse = 0.0f;
}
void b2GearJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_indexC = m_bodyC->m_islandIndex;
m_indexD = m_bodyD->m_islandIndex;
m_lcA = m_bodyA->m_sweep.localCenter;
m_lcB = m_bodyB->m_sweep.localCenter;
m_lcC = m_bodyC->m_sweep.localCenter;
m_lcD = m_bodyD->m_sweep.localCenter;
m_mA = m_bodyA->m_invMass;
m_mB = m_bodyB->m_invMass;
m_mC = m_bodyC->m_invMass;
m_mD = m_bodyD->m_invMass;
m_iA = m_bodyA->m_invI;
m_iB = m_bodyB->m_invI;
m_iC = m_bodyC->m_invI;
m_iD = m_bodyD->m_invI;
b2Vec2 cA = data.positions[m_indexA].c;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 cB = data.positions[m_indexB].c;
float32 aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Vec2 cC = data.positions[m_indexC].c;
float32 aC = data.positions[m_indexC].a;
b2Vec2 vC = data.velocities[m_indexC].v;
float32 wC = data.velocities[m_indexC].w;
b2Vec2 cD = data.positions[m_indexD].c;
float32 aD = data.positions[m_indexD].a;
b2Vec2 vD = data.velocities[m_indexD].v;
float32 wD = data.velocities[m_indexD].w;
b2Rot qA(aA), qB(aB), qC(aC), qD(aD);
m_mass = 0.0f;
if (m_typeA == e_revoluteJoint)
{
m_JvAC.SetZero();
m_JwA = 1.0f;
m_JwC = 1.0f;
m_mass += m_iA + m_iC;
}
else
{
b2Vec2 u = b2Mul(qC, m_localAxisC);
b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC);
b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA);
m_JvAC = u;
m_JwC = b2Cross(rC, u);
m_JwA = b2Cross(rA, u);
m_mass += m_mC + m_mA + m_iC * m_JwC * m_JwC + m_iA * m_JwA * m_JwA;
}
if (m_typeB == e_revoluteJoint)
{
m_JvBD.SetZero();
m_JwB = m_ratio;
m_JwD = m_ratio;
m_mass += m_ratio * m_ratio * (m_iB + m_iD);
}
else
{
b2Vec2 u = b2Mul(qD, m_localAxisD);
b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD);
b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB);
m_JvBD = m_ratio * u;
m_JwD = m_ratio * b2Cross(rD, u);
m_JwB = m_ratio * b2Cross(rB, u);
m_mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * m_JwD * m_JwD + m_iB * m_JwB * m_JwB;
}
// Compute effective mass.
m_mass = m_mass > 0.0f ? 1.0f / m_mass : 0.0f;
if (data.step.warmStarting)
{
vA += (m_mA * m_impulse) * m_JvAC;
wA += m_iA * m_impulse * m_JwA;
vB += (m_mB * m_impulse) * m_JvBD;
wB += m_iB * m_impulse * m_JwB;
vC -= (m_mC * m_impulse) * m_JvAC;
wC -= m_iC * m_impulse * m_JwC;
vD -= (m_mD * m_impulse) * m_JvBD;
wD -= m_iD * m_impulse * m_JwD;
}
else
{
m_impulse = 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;
data.velocities[m_indexC].v = vC;
data.velocities[m_indexC].w = wC;
data.velocities[m_indexD].v = vD;
data.velocities[m_indexD].w = wD;
}
void b2GearJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Vec2 vC = data.velocities[m_indexC].v;
float32 wC = data.velocities[m_indexC].w;
b2Vec2 vD = data.velocities[m_indexD].v;
float32 wD = data.velocities[m_indexD].w;
float32 Cdot = b2Dot(m_JvAC, vA - vC) + b2Dot(m_JvBD, vB - vD);
Cdot += (m_JwA * wA - m_JwC * wC) + (m_JwB * wB - m_JwD * wD);
float32 impulse = -m_mass * Cdot;
m_impulse += impulse;
vA += (m_mA * impulse) * m_JvAC;
wA += m_iA * impulse * m_JwA;
vB += (m_mB * impulse) * m_JvBD;
wB += m_iB * impulse * m_JwB;
vC -= (m_mC * impulse) * m_JvAC;
wC -= m_iC * impulse * m_JwC;
vD -= (m_mD * impulse) * m_JvBD;
wD -= m_iD * impulse * m_JwD;
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
data.velocities[m_indexC].v = vC;
data.velocities[m_indexC].w = wC;
data.velocities[m_indexD].v = vD;
data.velocities[m_indexD].w = wD;
}
bool b2GearJoint::SolvePositionConstraints(const b2SolverData& data)
{
b2Vec2 cA = data.positions[m_indexA].c;
float32 aA = data.positions[m_indexA].a;
b2Vec2 cB = data.positions[m_indexB].c;
float32 aB = data.positions[m_indexB].a;
b2Vec2 cC = data.positions[m_indexC].c;
float32 aC = data.positions[m_indexC].a;
b2Vec2 cD = data.positions[m_indexD].c;
float32 aD = data.positions[m_indexD].a;
b2Rot qA(aA), qB(aB), qC(aC), qD(aD);
float32 linearError = 0.0f;
float32 coordinateA, coordinateB;
b2Vec2 JvAC, JvBD;
float32 JwA, JwB, JwC, JwD;
float32 mass = 0.0f;
if (m_typeA == e_revoluteJoint)
{
JvAC.SetZero();
JwA = 1.0f;
JwC = 1.0f;
mass += m_iA + m_iC;
coordinateA = aA - aC - m_referenceAngleA;
}
else
{
b2Vec2 u = b2Mul(qC, m_localAxisC);
b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC);
b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA);
JvAC = u;
JwC = b2Cross(rC, u);
JwA = b2Cross(rA, u);
mass += m_mC + m_mA + m_iC * JwC * JwC + m_iA * JwA * JwA;
b2Vec2 pC = m_localAnchorC - m_lcC;
b2Vec2 pA = b2MulT(qC, rA + (cA - cC));
coordinateA = b2Dot(pA - pC, m_localAxisC);
}
if (m_typeB == e_revoluteJoint)
{
JvBD.SetZero();
JwB = m_ratio;
JwD = m_ratio;
mass += m_ratio * m_ratio * (m_iB + m_iD);
coordinateB = aB - aD - m_referenceAngleB;
}
else
{
b2Vec2 u = b2Mul(qD, m_localAxisD);
b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD);
b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB);
JvBD = m_ratio * u;
JwD = m_ratio * b2Cross(rD, u);
JwB = m_ratio * b2Cross(rB, u);
mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * JwD * JwD + m_iB * JwB * JwB;
b2Vec2 pD = m_localAnchorD - m_lcD;
b2Vec2 pB = b2MulT(qD, rB + (cB - cD));
coordinateB = b2Dot(pB - pD, m_localAxisD);
}
float32 C = (coordinateA + m_ratio * coordinateB) - m_constant;
float32 impulse = 0.0f;
if (mass > 0.0f)
{
impulse = -C / mass;
}
cA += m_mA * impulse * JvAC;
aA += m_iA * impulse * JwA;
cB += m_mB * impulse * JvBD;
aB += m_iB * impulse * JwB;
cC -= m_mC * impulse * JvAC;
aC -= m_iC * impulse * JwC;
cD -= m_mD * impulse * JvBD;
aD -= m_iD * impulse * JwD;
data.positions[m_indexA].c = cA;
data.positions[m_indexA].a = aA;
data.positions[m_indexB].c = cB;
data.positions[m_indexB].a = aB;
data.positions[m_indexC].c = cC;
data.positions[m_indexC].a = aC;
data.positions[m_indexD].c = cD;
data.positions[m_indexD].a = aD;
// TODO_ERIN not implemented
return linearError < b2_linearSlop;
}
b2Vec2 b2GearJoint::GetAnchorA() const
{
return m_bodyA->GetWorldPoint(m_localAnchorA);
}
b2Vec2 b2GearJoint::GetAnchorB() const
{
return m_bodyB->GetWorldPoint(m_localAnchorB);
}
b2Vec2 b2GearJoint::GetReactionForce(float32 inv_dt) const
{
b2Vec2 P = m_impulse * m_JvAC;
return inv_dt * P;
}
float32 b2GearJoint::GetReactionTorque(float32 inv_dt) const
{
float32 L = m_impulse * m_JwA;
return inv_dt * L;
}
void b2GearJoint::SetRatio(float32 ratio)
{
b2Assert(b2IsValid(ratio));
m_ratio = ratio;
}
float32 b2GearJoint::GetRatio() const
{
return m_ratio;
}
void b2GearJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
int32 index1 = m_joint1->m_index;
int32 index2 = m_joint2->m_index;
b2Log(" b2GearJointDef jd;\n");
b2Log(" jd.bodyA = bodies[%d];\n", indexA);
b2Log(" jd.bodyB = bodies[%d];\n", indexB);
b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b2Log(" jd.joint1 = joints[%d];\n", index1);
b2Log(" jd.joint2 = joints[%d];\n", index2);
b2Log(" jd.ratio = %.15lef;\n", m_ratio);
b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
| 0 | 0.94421 | 1 | 0.94421 | game-dev | MEDIA | 0.472768 | game-dev | 0.949942 | 1 | 0.949942 |
OpenFOAM/OpenFOAM-dev | 3,056 | src/OSspecific/POSIX/signals/sigQuit.C | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2011-2018 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "sigQuit.H"
#include "error.H"
#include "jobInfo.H"
#include "IOstreams.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
struct sigaction Foam::sigQuit::oldAction_;
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
void Foam::sigQuit::sigHandler(int)
{
// Reset old handling
if (sigaction(SIGQUIT, &oldAction_, nullptr) < 0)
{
FatalErrorInFunction
<< "Cannot reset SIGQUIT trapping"
<< abort(FatalError);
}
// Update jobInfo file
jobInfo_.signalEnd();
error::printStack(Perr);
// Throw signal (to old handler)
raise(SIGQUIT);
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::sigQuit::sigQuit()
{
oldAction_.sa_handler = nullptr;
}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
Foam::sigQuit::~sigQuit()
{
// Reset old handling
if (oldAction_.sa_handler && sigaction(SIGQUIT, &oldAction_, nullptr) < 0)
{
FatalErrorInFunction
<< "Cannot reset SIGQUIT trapping"
<< abort(FatalError);
}
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
void Foam::sigQuit::set(const bool verbose)
{
if (oldAction_.sa_handler)
{
FatalErrorInFunction
<< "Cannot call sigQuit::set() more than once"
<< abort(FatalError);
}
struct sigaction newAction;
newAction.sa_handler = sigHandler;
newAction.sa_flags = SA_NODEFER;
sigemptyset(&newAction.sa_mask);
if (sigaction(SIGQUIT, &newAction, &oldAction_) < 0)
{
FatalErrorInFunction
<< "Cannot set SIGQUIT trapping"
<< abort(FatalError);
}
}
// ************************************************************************* //
| 0 | 0.857551 | 1 | 0.857551 | game-dev | MEDIA | 0.155701 | game-dev | 0.776068 | 1 | 0.776068 |
ChiselsAndBits/Chisels-and-Bits | 2,197 | core/src/main/java/mod/chiselsandbits/modification/operation/MirrorOverAxisModificationOperation.java | package mod.chiselsandbits.modification.operation;
import com.communi.suggestu.scena.core.registries.AbstractCustomRegistryEntry;
import mod.chiselsandbits.api.modification.operation.IModificationOperation;
import mod.chiselsandbits.api.modification.operation.IModificationOperationGroup;
import mod.chiselsandbits.api.multistate.mutator.IGenerallyModifiableAreaMutator;
import mod.chiselsandbits.api.util.LocalStrings;
import mod.chiselsandbits.registrars.ModModificationOperationGroups;
import net.minecraft.core.Direction;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
public class MirrorOverAxisModificationOperation extends AbstractCustomRegistryEntry implements IModificationOperation
{
private final Direction.Axis axis;
private MirrorOverAxisModificationOperation(final Direction.Axis axis) {this.axis = axis;}
@Override
public void apply(final IGenerallyModifiableAreaMutator source)
{
source.mirror(axis);
}
public static final class Builder
{
private Direction.Axis axis;
private Builder() {}
public static Builder create() { return new Builder(); }
public Builder withAxis(Direction.Axis axis)
{
this.axis = axis;
return this;
}
public MirrorOverAxisModificationOperation build() { return new MirrorOverAxisModificationOperation(axis); }
}
@Override
public @NotNull ResourceLocation getIcon()
{
return ModModificationOperationGroups.MIRROR.getIcon();
}
@Override
public @NotNull Optional<IModificationOperationGroup> getGroup()
{
return Optional.of(ModModificationOperationGroups.MIRROR);
}
@Override
public Component getDisplayName()
{
return switch (axis)
{
case X -> LocalStrings.PatternModificationAcrossXAxis.getText();
case Y -> LocalStrings.PatternModificationAcrossYAxis.getText();
case Z -> LocalStrings.PatternModificationAcrossZAxis.getText();
};
}
}
| 0 | 0.660666 | 1 | 0.660666 | game-dev | MEDIA | 0.842275 | game-dev | 0.815555 | 1 | 0.815555 |
Athlaeos/ValhallaMMO | 5,506 | core/src/main/java/me/athlaeos/valhallammo/item/throwable_weapon_animations/ThrownItem.java | package me.athlaeos.valhallammo.item.throwable_weapon_animations;
import me.athlaeos.valhallammo.ValhallaMMO;
import me.athlaeos.valhallammo.item.ItemAttributesRegistry;
import me.athlaeos.valhallammo.item.ItemBuilder;
import me.athlaeos.valhallammo.item.item_attributes.AttributeWrapper;
import me.athlaeos.valhallammo.utility.ItemUtils;
import me.athlaeos.valhallammo.utility.MathUtils;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Player;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import java.util.Collection;
import java.util.HashSet;
import java.util.UUID;
public class ThrownItem {
private static final NamespacedKey THROWN_WEAPON = new NamespacedKey(ValhallaMMO.getInstance(), "thrown_weapon");
public static UUID getThrownBy(ArmorStand a){
String value = a.getPersistentDataContainer().get(THROWN_WEAPON, PersistentDataType.STRING);
if (value == null) return null;
return UUID.fromString(value);
}
private final ArmorStand stand;
private final BukkitRunnable runnable;
private final ItemBuilder item;
private final ThrowableItemStats stats;
private final EquipmentSlot hand;
private final Player thrower;
private Vector direction;
private Vector gravity;
private final Location location;
private int piercingLeft;
private final Collection<UUID> hitEntities = new HashSet<>();
private int tick = 0;
private boolean returning = false;
private final ItemStack rawThrown;
private static final double GRAVITY = 9.81;
public ThrownItem(Player thrower, EquipmentSlot hand, ItemBuilder item, ThrowableWeaponAnimation animation){
this.thrower = thrower;
this.stats = ThrowableWeaponAnimationRegistry.getItemStats(item.getMeta());
this.hand = hand;
this.item = item.amount(1);
rawThrown = item.get();
gravity = new Vector(0, -GRAVITY * stats.getGravityStrength(), 0);
location = thrower.getLocation().add(MathUtils.getHandOffset(thrower, hand == EquipmentSlot.HAND));
location.setPitch(0);
location.setYaw(thrower.getEyeLocation().getYaw() + 90);
direction = thrower.getEyeLocation().getDirection().multiply(stats.getDefaultVelocity()); // TODO thrown weapon speed
AttributeWrapper piercing = ItemAttributesRegistry.getAttribute(item.getMeta(), "ARROW_PIERCING", false);
if (piercing != null) piercingLeft = Math.max(0, ((int) piercing.getValue()));
AttributeWrapper speedWrapper = ItemAttributesRegistry.getAttribute(item.getMeta(), "ARROW_VELOCITY", false);
if (speedWrapper != null) direction = direction.multiply(1 + speedWrapper.getValue());
stand = thrower.getWorld().spawn(location, ArmorStand.class);
if (stand.getEquipment() == null){
stand.remove();
runnable = null;
return;
}
ThrowableWeaponAnimationRegistry.setStats(stand.getPersistentDataContainer(), stats);
stand.getPersistentDataContainer().set(THROWN_WEAPON, PersistentDataType.STRING, thrower.getUniqueId().toString());
stand.setGravity(false);
stand.setInvulnerable(true);
stand.setInvisible(true);
stand.setCollidable(false);
stand.setMarker(false);
stand.setAI(false);
stand.getEquipment().setHelmet(item.get());
for (EquipmentSlot slot : EquipmentSlot.values()) {
stand.addEquipmentLock(slot, ArmorStand.LockType.REMOVING_OR_CHANGING);
stand.addEquipmentLock(slot, ArmorStand.LockType.ADDING);
}
final ThrownItem instance = this;
runnable = new BukkitRunnable(){
@Override
public void run() {
animation.tick(instance);
}
};
runnable.runTaskTimer(ValhallaMMO.getInstance(), 0, 1L);
}
public void incrementTick(){ tick++; }
public int getTick() { return tick; }
public ArmorStand getStand() { return stand; }
public Collection<UUID> getHitEntities() { return hitEntities; }
public EquipmentSlot getHand() { return hand; }
public int getPiercingLeft() { return piercingLeft; }
public ItemBuilder getItem() { return item; }
public ItemStack getRawThrown() { return rawThrown; }
public Location getLocation() { return location; }
public Player getThrower() { return thrower; }
public ThrowableItemStats getStats() { return stats; }
public Vector getDirection() { return direction; }
public Vector getGravity() { return gravity; }
public boolean isReturning() { return returning; }
public void setDirection(Vector direction) { this.direction = direction; }
public void setGravity(Vector gravity) { this.gravity = gravity; }
public void setPiercingLeft(int piercingLeft) { this.piercingLeft = piercingLeft; }
public void setReturning(boolean returning) { this.returning = returning; }
public void stop(){
runnable.cancel();
stand.remove();
}
public void drop(){
if (stand.getEquipment() == null || ItemUtils.isEmpty(stand.getEquipment().getHelmet())) return;
if (!stats.isInfinity()) stand.getWorld().dropItem(stand.getEyeLocation(), stand.getEquipment().getHelmet());
stop();
}
}
| 0 | 0.885295 | 1 | 0.885295 | game-dev | MEDIA | 0.953096 | game-dev | 0.980825 | 1 | 0.980825 |
pmret/papermario | 3,114 | src/world/common/enemy/DryBones.inc.c | #include "DryBones.h"
#include "world/common/enemy/ai/RangedAttackAI.inc.c"
#include "world/common/todo/GetEncounterEnemyIsOwner.inc.c"
EvtScript N(EVS_NpcDefeat_ThrownBone) = {
Call(GetBattleOutcome, LVar0)
Switch(LVar0)
CaseEq(OUTCOME_PLAYER_WON)
Call(SetSelfVar, 0, 5)
Call(RemoveNpc, NPC_SELF)
CaseEq(OUTCOME_PLAYER_FLED)
Call(SetNpcPos, NPC_SELF, NPC_DISPOSE_LOCATION)
Call(OnPlayerFled, 1)
CaseEq(OUTCOME_ENEMY_FLED)
Call(SetEnemyFlagBits, NPC_SELF, ENEMY_FLAG_FLED, true)
Call(RemoveNpc, NPC_SELF)
EndSwitch
Return
End
};
MobileAISettings N(AISettings_DryBones) = {
.moveSpeed = 2.0f,
.moveTime = 20,
.waitTime = 3,
.alertRadius = 120.0f,
.alertOffsetDist = 120.0f,
.playerSearchInterval = 2,
.chaseSpeed = 1.0f,
.chaseRadius = 150.0f,
.chaseOffsetDist = 150.0f,
.unk_AI_2C = 1,
};
EvtScript N(EVS_NpcAI_DryBones) = {
Call(SetSelfVar, 0, 0)
Call(SetSelfVar, 1, 15)
Call(SetSelfVar, 2, 10)
Call(SetSelfVar, 3, 2)
Call(N(RangedAttackAI_Main), Ref(N(AISettings_DryBones)))
Return
End
};
NpcSettings N(NpcSettings_DryBones) = {
.height = 32,
.radius = 24,
.level = ACTOR_LEVEL_DRY_BONES,
.ai = &N(EVS_NpcAI_DryBones),
.onHit = &EnemyNpcHit,
.onDefeat = &EnemyNpcDefeat,
};
MobileAISettings N(AISettings_ThrownBone) = {
.moveSpeed = 7.5f,
.alertRadius = 1.1f,
.alertOffsetDist = 0.18f,
.playerSearchInterval = -1,
};
EvtScript N(EVS_NpcAI_ThrownBone) = {
Call(SetSelfVar, 0, 0)
Call(SetSelfVar, 1, 3)
Call(SetSelfVar, 2, 15)
Call(SetSelfVar, 3, 15)
Call(N(ProjectileAI_Main), Ref(N(AISettings_ThrownBone)))
Return
End
};
EvtScript N(EVS_NoAI_ThrownBone) = {
Return
End
};
EvtScript N(EVS_NpcHit_ThrownBone) = {
Call(N(GetEncounterEnemyIsOwner))
IfEq(LVar0, 0)
Return
EndIf
Call(BindNpcAI, NPC_SELF, Ref(N(EVS_NoAI_ThrownBone)))
Call(GetOwnerEncounterTrigger, LVar0)
Switch(LVar0)
CaseOrEq(ENCOUNTER_TRIGGER_HAMMER)
CaseOrEq(ENCOUNTER_TRIGGER_SPIN)
Call(SetSelfVar, 0, 3)
Call(N(ProjectileAI_Reflect))
IfEq(LVar0, 0)
Return
EndIf
EndCaseGroup
CaseOrEq(ENCOUNTER_TRIGGER_JUMP)
CaseOrEq(ENCOUNTER_TRIGGER_PARTNER)
Call(SetSelfVar, 0, 4)
Call(GetNpcPos, NPC_SELF, LVar0, LVar1, LVar2)
PlayEffect(EFFECT_WALKING_DUST, 2, LVar0, LVar1, LVar2, 0, 0)
Call(SetNpcPos, NPC_SELF, NPC_DISPOSE_LOCATION)
Call(SetSelfVar, 0, 0)
EndCaseGroup
CaseDefault
Call(SetBattleAsScripted)
EndCaseGroup
EndSwitch
Call(BindNpcAI, NPC_SELF, Ref(N(EVS_NpcAI_ThrownBone)))
Return
End
};
NpcSettings N(NpcSettings_ThrownBone) = {
.height = 12,
.radius = 12,
.ai = &N(EVS_NpcAI_ThrownBone),
.onHit = &N(EVS_NpcHit_ThrownBone),
.onDefeat = &N(EVS_NpcDefeat_ThrownBone),
.actionFlags = AI_ACTION_08,
};
| 0 | 0.929004 | 1 | 0.929004 | game-dev | MEDIA | 0.973996 | game-dev | 0.896074 | 1 | 0.896074 |
Robosturm/Commander_Wars | 3,636 | resources/scripts/units/torpedoboat.js | var Constructor = function()
{
this.init = function(unit)
{
unit.setAmmo1(3);
unit.setMaxAmmo1(3);
unit.setWeapon1ID("WEAPON_BOAT_TORPEDO");
unit.setAmmo2(0);
unit.setMaxAmmo2(0);
unit.setWeapon2ID("");
unit.setFuel(100);
unit.setMaxFuel(100);
unit.setBaseMovementPoints(6);
unit.setMinRange(1);
unit.setMaxRange(1);
unit.setVision(2);
};
this.loadSprites = function(unit)
{
unit.loadSpriteV2("torpedoboat+mask", GameEnums.Recoloring_Matrix);
};
this.getMovementType = function()
{
return "MOVE_SMALL_BOAT";
};
this.getBaseCost = function()
{
return 8500;
};
this.getName = function()
{
return qsTr("Torpedo boat");
};
this.startOfTurn = function(unit, map)
{
if (unit.getTerrain() !== null)
{
// pay unit upkeep
var fuelCosts = 1 + unit.getFuelCostModifier(Qt.point(unit.getX(), unit.getY()), 1);
if (fuelCosts < 0)
{
fuelCosts = 0;
}
unit.setFuel(unit.getFuel() - fuelCosts);
}
UNIT.transporterRefilling(unit, map);
};
this.createExplosionAnimation = function(x, y, unit, map)
{
var animation = GameAnimationFactory.createAnimation(map, x, y);
animation.addSprite("explosion+water", -map.getImageSize() / 2, -map.getImageSize(), 0, 2);
animation.setSound("explosion+water.wav");
return animation;
};
this.doWalkingAnimation = function(action, map)
{
var unit = action.getTargetUnit();
var animation = GameAnimationFactory.createWalkingAnimation(map, unit, action);
var unitID = unit.getUnitID().toLowerCase();
animation.loadSpriteV2(unitID + "+walk+mask", GameEnums.Recoloring_Matrix, 1.5);
animation.setSound("moveship.wav", -2);
return animation;
};
this.canMoveAndFire = function()
{
return true;
};
this.getTerrainAnimationBase = function(unit, terrain, defender, map)
{
var terrainId = terrain.getID();
if (terrainId === "RIVER" || terrainId === "DESERT_TRY_RIVER")
{
return Global[terrainId].getTerrainAnimationBase(unit, terrain, defender, map);
}
else
{
var weatherModifier = TERRAIN.getWeatherModifier(map);
return "base_" + weatherModifier + "air";
}
};
this.getTerrainAnimationForeground = function(unit, terrain, defender, map)
{
return "";
};
this.getTerrainAnimationBackground = function(unit, terrain, defender, map)
{
var terrainId = terrain.getID();
if (terrainId === "RIVER" || terrainId === "DESERT_TRY_RIVER")
{
return Global[terrainId].getTerrainAnimationBackground(unit, terrain, defender, map);
}
else
{
var weatherModifier = TERRAIN.getWeatherModifier(map);
return "back_" + weatherModifier +"sea";
}
};
this.getTerrainAnimationMoveSpeed = function()
{
return 1;
};
this.getDescription = function()
{
return qsTr("<r>Short-range Naval Unit intended for harrassing much larger Naval Units. Like all boats, it can also traverse rivers.</r>");
};
this.getUnitType = function()
{
return GameEnums.UnitType_Naval;
};
this.getEditorPlacementSound = function()
{
return "moveship.wav";
};
}
Constructor.prototype = UNIT;
var TORPEDOBOAT = new Constructor();
| 0 | 0.801895 | 1 | 0.801895 | game-dev | MEDIA | 0.990215 | game-dev | 0.919317 | 1 | 0.919317 |
Fundynamic/RealBot | 22,657 | dependencies/hlsdk/dlls/islave.cpp | /***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* This source code contains proprietary and confidential information of
* Valve LLC and its suppliers. Access to this code is restricted to
* persons who have executed a written SDK license with Valve. Any access,
* use or distribution of this code by or to any unlicensed person is illegal.
*
****/
//=========================================================
// Alien slave monster
//=========================================================
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "monsters.h"
#include "squadmonster.h"
#include "schedule.h"
#include "effects.h"
#include "weapons.h"
#include "soundent.h"
extern DLL_GLOBAL int g_iSkillLevel;
//=========================================================
// Monster's Anim Events Go Here
//=========================================================
#define ISLAVE_AE_CLAW ( 1 )
#define ISLAVE_AE_CLAWRAKE ( 2 )
#define ISLAVE_AE_ZAP_POWERUP ( 3 )
#define ISLAVE_AE_ZAP_SHOOT ( 4 )
#define ISLAVE_AE_ZAP_DONE ( 5 )
#define ISLAVE_MAX_BEAMS 8
class CISlave : public CSquadMonster
{
public:
void Spawn( void );
void Precache( void );
void SetYawSpeed( void );
int ISoundMask( void );
int Classify ( void );
int IRelationship( CBaseEntity *pTarget );
void HandleAnimEvent( MonsterEvent_t *pEvent );
BOOL CheckRangeAttack1 ( float flDot, float flDist );
BOOL CheckRangeAttack2 ( float flDot, float flDist );
void CallForHelp( const char *szClassname, float flDist, EHANDLE hEnemy, Vector &vecLocation );
void TraceAttack( entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType);
int TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType);
void DeathSound( void );
void PainSound( void );
void AlertSound( void );
void IdleSound( void );
void Killed( entvars_t *pevAttacker, int iGib );
void StartTask ( Task_t *pTask );
Schedule_t *GetSchedule( void );
Schedule_t *GetScheduleOfType ( int Type );
CUSTOM_SCHEDULES;
int Save( CSave &save );
int Restore( CRestore &restore );
static TYPEDESCRIPTION m_SaveData[];
void ClearBeams( );
void ArmBeam( int side );
void WackBeam( int side, CBaseEntity *pEntity );
void ZapBeam( int side );
void BeamGlow( void );
int m_iBravery;
CBeam *m_pBeam[ISLAVE_MAX_BEAMS];
int m_iBeams;
float m_flNextAttack;
int m_voicePitch;
EHANDLE m_hDead;
static const char *pAttackHitSounds[];
static const char *pAttackMissSounds[];
static const char *pPainSounds[];
static const char *pDeathSounds[];
};
LINK_ENTITY_TO_CLASS( monster_alien_slave, CISlave );
LINK_ENTITY_TO_CLASS( monster_vortigaunt, CISlave );
TYPEDESCRIPTION CISlave::m_SaveData[] =
{
DEFINE_FIELD( CISlave, m_iBravery, FIELD_INTEGER ),
DEFINE_ARRAY( CISlave, m_pBeam, FIELD_CLASSPTR, ISLAVE_MAX_BEAMS ),
DEFINE_FIELD( CISlave, m_iBeams, FIELD_INTEGER ),
DEFINE_FIELD( CISlave, m_flNextAttack, FIELD_TIME ),
DEFINE_FIELD( CISlave, m_voicePitch, FIELD_INTEGER ),
DEFINE_FIELD( CISlave, m_hDead, FIELD_EHANDLE ),
};
IMPLEMENT_SAVERESTORE( CISlave, CSquadMonster );
const char *CISlave::pAttackHitSounds[] =
{
"zombie/claw_strike1.wav",
"zombie/claw_strike2.wav",
"zombie/claw_strike3.wav",
};
const char *CISlave::pAttackMissSounds[] =
{
"zombie/claw_miss1.wav",
"zombie/claw_miss2.wav",
};
const char *CISlave::pPainSounds[] =
{
"aslave/slv_pain1.wav",
"aslave/slv_pain2.wav",
};
const char *CISlave::pDeathSounds[] =
{
"aslave/slv_die1.wav",
"aslave/slv_die2.wav",
};
//=========================================================
// Classify - indicates this monster's place in the
// relationship table.
//=========================================================
int CISlave :: Classify ( void )
{
return CLASS_ALIEN_MILITARY;
}
int CISlave::IRelationship( CBaseEntity *pTarget )
{
if ( (pTarget->IsPlayer()) )
if ( (pev->spawnflags & SF_MONSTER_WAIT_UNTIL_PROVOKED ) && ! (m_afMemory & bits_MEMORY_PROVOKED ))
return R_NO;
return CBaseMonster::IRelationship( pTarget );
}
void CISlave :: CallForHelp( const char *szClassname, float flDist, EHANDLE hEnemy, Vector &vecLocation )
{
// ALERT( at_aiconsole, "help " );
// skip ones not on my netname
if ( FStringNull( pev->netname ))
return;
CBaseEntity *pEntity = NULL;
while ((pEntity = UTIL_FindEntityByString( pEntity, "netname", STRING( pev->netname ))) != NULL)
{
float d = (pev->origin - pEntity->pev->origin).Length();
if (d < flDist)
{
CBaseMonster *pMonster = pEntity->MyMonsterPointer( );
if (pMonster)
{
pMonster->m_afMemory |= bits_MEMORY_PROVOKED;
pMonster->PushEnemy( hEnemy, vecLocation );
}
}
}
}
//=========================================================
// ALertSound - scream
//=========================================================
void CISlave :: AlertSound( void )
{
if ( m_hEnemy != 0 )
{
SENTENCEG_PlayRndSz(ENT(pev), "SLV_ALERT", 0.85, ATTN_NORM, 0, m_voicePitch);
CallForHelp( "monster_alien_slave", 512, m_hEnemy, m_vecEnemyLKP );
}
}
//=========================================================
// IdleSound
//=========================================================
void CISlave :: IdleSound( void )
{
if (RANDOM_LONG( 0, 2 ) == 0)
{
SENTENCEG_PlayRndSz(ENT(pev), "SLV_IDLE", 0.85, ATTN_NORM, 0, m_voicePitch);
}
#if 0
int side = RANDOM_LONG( 0, 1 ) * 2 - 1;
ClearBeams( );
ArmBeam( side );
UTIL_MakeAimVectors( pev->angles );
Vector vecSrc = pev->origin + gpGlobals->v_right * 2 * side;
MESSAGE_BEGIN( MSG_PVS, SVC_TEMPENTITY, vecSrc );
WRITE_BYTE(TE_DLIGHT);
WRITE_COORD(vecSrc.x); // X
WRITE_COORD(vecSrc.y); // Y
WRITE_COORD(vecSrc.z); // Z
WRITE_BYTE( 8 ); // radius * 0.1
WRITE_BYTE( 255 ); // r
WRITE_BYTE( 180 ); // g
WRITE_BYTE( 96 ); // b
WRITE_BYTE( 10 ); // time * 10
WRITE_BYTE( 0 ); // decay * 0.1
MESSAGE_END( );
EMIT_SOUND_DYN( ENT(pev), CHAN_WEAPON, "debris/zap1.wav", 1, ATTN_NORM, 0, 100 );
#endif
}
//=========================================================
// PainSound
//=========================================================
void CISlave :: PainSound( void )
{
if (RANDOM_LONG( 0, 2 ) == 0)
{
EMIT_SOUND_DYN ( ENT(pev), CHAN_WEAPON, pPainSounds[ RANDOM_LONG(0,ARRAYSIZE(pPainSounds)-1) ], 1.0, ATTN_NORM, 0, m_voicePitch );
}
}
//=========================================================
// DieSound
//=========================================================
void CISlave :: DeathSound( void )
{
EMIT_SOUND_DYN ( ENT(pev), CHAN_WEAPON, pDeathSounds[ RANDOM_LONG(0,ARRAYSIZE(pDeathSounds)-1) ], 1.0, ATTN_NORM, 0, m_voicePitch );
}
//=========================================================
// ISoundMask - returns a bit mask indicating which types
// of sounds this monster regards.
//=========================================================
int CISlave :: ISoundMask ( void)
{
return bits_SOUND_WORLD |
bits_SOUND_COMBAT |
bits_SOUND_DANGER |
bits_SOUND_PLAYER;
}
void CISlave::Killed( entvars_t *pevAttacker, int iGib )
{
ClearBeams( );
CSquadMonster::Killed( pevAttacker, iGib );
}
//=========================================================
// SetYawSpeed - allows each sequence to have a different
// turn rate associated with it.
//=========================================================
void CISlave :: SetYawSpeed ( void )
{
int ys;
switch ( m_Activity )
{
case ACT_WALK:
ys = 50;
break;
case ACT_RUN:
ys = 70;
break;
case ACT_IDLE:
ys = 50;
break;
default:
ys = 90;
break;
}
pev->yaw_speed = ys;
}
//=========================================================
// HandleAnimEvent - catches the monster-specific messages
// that occur when tagged animation frames are played.
//
// Returns number of events handled, 0 if none.
//=========================================================
void CISlave :: HandleAnimEvent( MonsterEvent_t *pEvent )
{
// ALERT( at_console, "event %d : %f\n", pEvent->event, pev->frame );
switch( pEvent->event )
{
case ISLAVE_AE_CLAW:
{
// SOUND HERE!
CBaseEntity *pHurt = CheckTraceHullAttack( 70, gSkillData.slaveDmgClaw, DMG_SLASH );
if ( pHurt )
{
if ( pHurt->pev->flags & (FL_MONSTER|FL_CLIENT) )
{
pHurt->pev->punchangle.z = -18;
pHurt->pev->punchangle.x = 5;
}
// Play a random attack hit sound
EMIT_SOUND_DYN ( ENT(pev), CHAN_WEAPON, pAttackHitSounds[ RANDOM_LONG(0,ARRAYSIZE(pAttackHitSounds)-1) ], 1.0, ATTN_NORM, 0, m_voicePitch );
}
else
{
// Play a random attack miss sound
EMIT_SOUND_DYN ( ENT(pev), CHAN_WEAPON, pAttackMissSounds[ RANDOM_LONG(0,ARRAYSIZE(pAttackMissSounds)-1) ], 1.0, ATTN_NORM, 0, m_voicePitch );
}
}
break;
case ISLAVE_AE_CLAWRAKE:
{
CBaseEntity *pHurt = CheckTraceHullAttack( 70, gSkillData.slaveDmgClawrake, DMG_SLASH );
if ( pHurt )
{
if ( pHurt->pev->flags & (FL_MONSTER|FL_CLIENT) )
{
pHurt->pev->punchangle.z = -18;
pHurt->pev->punchangle.x = 5;
}
EMIT_SOUND_DYN ( ENT(pev), CHAN_WEAPON, pAttackHitSounds[ RANDOM_LONG(0,ARRAYSIZE(pAttackHitSounds)-1) ], 1.0, ATTN_NORM, 0, m_voicePitch );
}
else
{
EMIT_SOUND_DYN ( ENT(pev), CHAN_WEAPON, pAttackMissSounds[ RANDOM_LONG(0,ARRAYSIZE(pAttackMissSounds)-1) ], 1.0, ATTN_NORM, 0, m_voicePitch );
}
}
break;
case ISLAVE_AE_ZAP_POWERUP:
{
// speed up attack when on hard
if (g_iSkillLevel == SKILL_HARD)
pev->framerate = 1.5;
UTIL_MakeAimVectors( pev->angles );
if (m_iBeams == 0)
{
Vector vecSrc = pev->origin + gpGlobals->v_forward * 2;
MESSAGE_BEGIN( MSG_PVS, SVC_TEMPENTITY, vecSrc );
WRITE_BYTE(TE_DLIGHT);
WRITE_COORD(vecSrc.x); // X
WRITE_COORD(vecSrc.y); // Y
WRITE_COORD(vecSrc.z); // Z
WRITE_BYTE( 12 ); // radius * 0.1
WRITE_BYTE( 255 ); // r
WRITE_BYTE( 180 ); // g
WRITE_BYTE( 96 ); // b
WRITE_BYTE( 20 / pev->framerate ); // time * 10
WRITE_BYTE( 0 ); // decay * 0.1
MESSAGE_END( );
}
if (m_hDead != 0)
{
WackBeam( -1, m_hDead );
WackBeam( 1, m_hDead );
}
else
{
ArmBeam( -1 );
ArmBeam( 1 );
BeamGlow( );
}
EMIT_SOUND_DYN( ENT(pev), CHAN_WEAPON, "debris/zap4.wav", 1, ATTN_NORM, 0, 100 + m_iBeams * 10 );
pev->skin = m_iBeams / 2;
}
break;
case ISLAVE_AE_ZAP_SHOOT:
{
ClearBeams( );
if (m_hDead != 0)
{
Vector vecDest = m_hDead->pev->origin + Vector( 0, 0, 38 );
TraceResult trace;
UTIL_TraceHull( vecDest, vecDest, dont_ignore_monsters, human_hull, m_hDead->edict(), &trace );
if ( !trace.fStartSolid )
{
CBaseEntity *pNew = Create( "monster_alien_slave", m_hDead->pev->origin, m_hDead->pev->angles );
pNew->pev->spawnflags |= 1;
WackBeam( -1, pNew );
WackBeam( 1, pNew );
UTIL_Remove( m_hDead );
EMIT_SOUND_DYN( ENT(pev), CHAN_WEAPON, "hassault/hw_shoot1.wav", 1, ATTN_NORM, 0, RANDOM_LONG( 130, 160 ) );
/*
CBaseEntity *pEffect = Create( "test_effect", pNew->Center(), pev->angles );
pEffect->Use( this, this, USE_ON, 1 );
*/
break;
}
}
ClearMultiDamage();
UTIL_MakeAimVectors( pev->angles );
ZapBeam( -1 );
ZapBeam( 1 );
EMIT_SOUND_DYN( ENT(pev), CHAN_WEAPON, "hassault/hw_shoot1.wav", 1, ATTN_NORM, 0, RANDOM_LONG( 130, 160 ) );
// STOP_SOUND( ENT(pev), CHAN_WEAPON, "debris/zap4.wav" );
ApplyMultiDamage(pev, pev);
m_flNextAttack = gpGlobals->time + RANDOM_FLOAT( 0.5, 4.0 );
}
break;
case ISLAVE_AE_ZAP_DONE:
{
ClearBeams( );
}
break;
default:
CSquadMonster::HandleAnimEvent( pEvent );
break;
}
}
//=========================================================
// CheckRangeAttack1 - normal beam attack
//=========================================================
BOOL CISlave :: CheckRangeAttack1 ( float flDot, float flDist )
{
if (m_flNextAttack > gpGlobals->time)
{
return FALSE;
}
return CSquadMonster::CheckRangeAttack1( flDot, flDist );
}
//=========================================================
// CheckRangeAttack2 - check bravery and try to resurect dead comrades
//=========================================================
BOOL CISlave :: CheckRangeAttack2 ( float flDot, float flDist )
{
return FALSE;
if (m_flNextAttack > gpGlobals->time)
{
return FALSE;
}
m_hDead = NULL;
m_iBravery = 0;
CBaseEntity *pEntity = NULL;
while ((pEntity = UTIL_FindEntityByClassname( pEntity, "monster_alien_slave" )) != NULL)
{
TraceResult tr;
UTIL_TraceLine( EyePosition( ), pEntity->EyePosition( ), ignore_monsters, ENT(pev), &tr );
if (tr.flFraction == 1.0 || tr.pHit == pEntity->edict())
{
if (pEntity->pev->deadflag == DEAD_DEAD)
{
float d = (pev->origin - pEntity->pev->origin).Length();
if (d < flDist)
{
m_hDead = pEntity;
flDist = d;
}
m_iBravery--;
}
else
{
m_iBravery++;
}
}
}
if (m_hDead != 0)
return TRUE;
else
return FALSE;
}
//=========================================================
// StartTask
//=========================================================
void CISlave :: StartTask ( Task_t *pTask )
{
ClearBeams( );
CSquadMonster :: StartTask ( pTask );
}
//=========================================================
// Spawn
//=========================================================
void CISlave :: Spawn()
{
Precache( );
SET_MODEL(ENT(pev), "models/islave.mdl");
UTIL_SetSize(pev, VEC_HUMAN_HULL_MIN, VEC_HUMAN_HULL_MAX);
pev->solid = SOLID_SLIDEBOX;
pev->movetype = MOVETYPE_STEP;
m_bloodColor = BLOOD_COLOR_GREEN;
pev->effects = 0;
pev->health = gSkillData.slaveHealth;
pev->view_ofs = Vector ( 0, 0, 64 );// position of the eyes relative to monster's origin.
m_flFieldOfView = VIEW_FIELD_WIDE; // NOTE: we need a wide field of view so npc will notice player and say hello
m_MonsterState = MONSTERSTATE_NONE;
m_afCapability = bits_CAP_HEAR | bits_CAP_TURN_HEAD | bits_CAP_RANGE_ATTACK2 | bits_CAP_DOORS_GROUP;
m_voicePitch = RANDOM_LONG( 85, 110 );
MonsterInit();
}
//=========================================================
// Precache - precaches all resources this monster needs
//=========================================================
void CISlave :: Precache()
{
size_t i;
PRECACHE_MODEL("models/islave.mdl");
PRECACHE_MODEL("sprites/lgtning.spr");
PRECACHE_SOUND("debris/zap1.wav");
PRECACHE_SOUND("debris/zap4.wav");
PRECACHE_SOUND("weapons/electro4.wav");
PRECACHE_SOUND("hassault/hw_shoot1.wav");
PRECACHE_SOUND("zombie/zo_pain2.wav");
PRECACHE_SOUND("headcrab/hc_headbite.wav");
PRECACHE_SOUND("weapons/cbar_miss1.wav");
for ( i = 0; i < ARRAYSIZE( pAttackHitSounds ); i++ )
PRECACHE_SOUND((char *)pAttackHitSounds[i]);
for ( i = 0; i < ARRAYSIZE( pAttackMissSounds ); i++ )
PRECACHE_SOUND((char *)pAttackMissSounds[i]);
for ( i = 0; i < ARRAYSIZE( pPainSounds ); i++ )
PRECACHE_SOUND((char *)pPainSounds[i]);
for ( i = 0; i < ARRAYSIZE( pDeathSounds ); i++ )
PRECACHE_SOUND((char *)pDeathSounds[i]);
UTIL_PrecacheOther( "test_effect" );
}
//=========================================================
// TakeDamage - get provoked when injured
//=========================================================
int CISlave :: TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType)
{
// don't slash one of your own
if ((bitsDamageType & DMG_SLASH) && pevAttacker && IRelationship( Instance(pevAttacker) ) < R_DL)
return 0;
m_afMemory |= bits_MEMORY_PROVOKED;
return CSquadMonster::TakeDamage(pevInflictor, pevAttacker, flDamage, bitsDamageType);
}
void CISlave::TraceAttack( entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType)
{
if (bitsDamageType & DMG_SHOCK)
return;
CSquadMonster::TraceAttack( pevAttacker, flDamage, vecDir, ptr, bitsDamageType );
}
//=========================================================
// AI Schedules Specific to this monster
//=========================================================
// primary range attack
Task_t tlSlaveAttack1[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_FACE_IDEAL, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
};
Schedule_t slSlaveAttack1[] =
{
{
tlSlaveAttack1,
ARRAYSIZE ( tlSlaveAttack1 ),
bits_COND_CAN_MELEE_ATTACK1 |
bits_COND_HEAR_SOUND |
bits_COND_HEAVY_DAMAGE,
bits_SOUND_DANGER,
"Slave Range Attack1"
},
};
DEFINE_CUSTOM_SCHEDULES( CISlave )
{
slSlaveAttack1,
};
IMPLEMENT_CUSTOM_SCHEDULES( CISlave, CSquadMonster );
//=========================================================
//=========================================================
Schedule_t *CISlave :: GetSchedule( void )
{
ClearBeams( );
/*
if (pev->spawnflags)
{
pev->spawnflags = 0;
return GetScheduleOfType( SCHED_RELOAD );
}
*/
if ( HasConditions( bits_COND_HEAR_SOUND ) )
{
CSound *pSound;
pSound = PBestSound();
ASSERT( pSound != NULL );
if ( pSound && (pSound->m_iType & bits_SOUND_DANGER) )
return GetScheduleOfType( SCHED_TAKE_COVER_FROM_BEST_SOUND );
if ( pSound->m_iType & bits_SOUND_COMBAT )
m_afMemory |= bits_MEMORY_PROVOKED;
}
switch (m_MonsterState)
{
case MONSTERSTATE_COMBAT:
// dead enemy
if ( HasConditions( bits_COND_ENEMY_DEAD ) )
{
// call base class, all code to handle dead enemies is centralized there.
return CBaseMonster :: GetSchedule();
}
if (pev->health < 20 || m_iBravery < 0)
{
if (!HasConditions( bits_COND_CAN_MELEE_ATTACK1 ))
{
m_failSchedule = SCHED_CHASE_ENEMY;
if (HasConditions( bits_COND_LIGHT_DAMAGE | bits_COND_HEAVY_DAMAGE))
{
return GetScheduleOfType( SCHED_TAKE_COVER_FROM_ENEMY );
}
if ( HasConditions ( bits_COND_SEE_ENEMY ) && HasConditions ( bits_COND_ENEMY_FACING_ME ) )
{
// ALERT( at_console, "exposed\n");
return GetScheduleOfType( SCHED_TAKE_COVER_FROM_ENEMY );
}
}
}
break;
default:
break;
}
return CSquadMonster::GetSchedule( );
}
Schedule_t *CISlave :: GetScheduleOfType ( int Type )
{
switch ( Type )
{
case SCHED_FAIL:
if (HasConditions( bits_COND_CAN_MELEE_ATTACK1 ))
{
return CSquadMonster :: GetScheduleOfType( SCHED_MELEE_ATTACK1 ); ;
}
break;
case SCHED_RANGE_ATTACK1:
return slSlaveAttack1;
case SCHED_RANGE_ATTACK2:
return slSlaveAttack1;
}
return CSquadMonster :: GetScheduleOfType( Type );
}
//=========================================================
// ArmBeam - small beam from arm to nearby geometry
//=========================================================
void CISlave :: ArmBeam( int side )
{
TraceResult tr;
float flDist = 1.0;
if (m_iBeams >= ISLAVE_MAX_BEAMS)
return;
UTIL_MakeAimVectors( pev->angles );
Vector vecSrc = pev->origin + gpGlobals->v_up * 36 + gpGlobals->v_right * side * 16 + gpGlobals->v_forward * 32;
for (int i = 0; i < 3; i++)
{
Vector vecAim = gpGlobals->v_right * side * RANDOM_FLOAT( 0, 1 ) + gpGlobals->v_up * RANDOM_FLOAT( -1, 1 );
TraceResult tr1;
UTIL_TraceLine ( vecSrc, vecSrc + vecAim * 512, dont_ignore_monsters, ENT( pev ), &tr1);
if (flDist > tr1.flFraction)
{
tr = tr1;
flDist = tr.flFraction;
}
}
// Couldn't find anything close enough
if ( flDist == 1.0 )
return;
DecalGunshot( &tr, BULLET_PLAYER_CROWBAR );
m_pBeam[m_iBeams] = CBeam::BeamCreate( "sprites/lgtning.spr", 30 );
if (!m_pBeam[m_iBeams])
return;
m_pBeam[m_iBeams]->PointEntInit( tr.vecEndPos, entindex( ) );
m_pBeam[m_iBeams]->SetEndAttachment( side < 0 ? 2 : 1 );
// m_pBeam[m_iBeams]->SetColor( 180, 255, 96 );
m_pBeam[m_iBeams]->SetColor( 96, 128, 16 );
m_pBeam[m_iBeams]->SetBrightness( 64 );
m_pBeam[m_iBeams]->SetNoise( 80 );
m_iBeams++;
}
//=========================================================
// BeamGlow - brighten all beams
//=========================================================
void CISlave :: BeamGlow( )
{
int b = m_iBeams * 32;
if (b > 255)
b = 255;
for (int i = 0; i < m_iBeams; i++)
{
if (m_pBeam[i]->GetBrightness() != 255)
{
m_pBeam[i]->SetBrightness( b );
}
}
}
//=========================================================
// WackBeam - regenerate dead colleagues
//=========================================================
void CISlave :: WackBeam( int side, CBaseEntity *pEntity )
{
if (m_iBeams >= ISLAVE_MAX_BEAMS)
return;
if (pEntity == NULL)
return;
m_pBeam[m_iBeams] = CBeam::BeamCreate( "sprites/lgtning.spr", 30 );
if (!m_pBeam[m_iBeams])
return;
m_pBeam[m_iBeams]->PointEntInit( pEntity->Center(), entindex( ) );
m_pBeam[m_iBeams]->SetEndAttachment( side < 0 ? 2 : 1 );
m_pBeam[m_iBeams]->SetColor( 180, 255, 96 );
m_pBeam[m_iBeams]->SetBrightness( 255 );
m_pBeam[m_iBeams]->SetNoise( 80 );
m_iBeams++;
}
//=========================================================
// ZapBeam - heavy damage directly forward
//=========================================================
void CISlave :: ZapBeam( int side )
{
Vector vecSrc, vecAim;
TraceResult tr;
CBaseEntity *pEntity;
if (m_iBeams >= ISLAVE_MAX_BEAMS)
return;
vecSrc = pev->origin + gpGlobals->v_up * 36;
vecAim = ShootAtEnemy( vecSrc );
float deflection = 0.01;
vecAim = vecAim + side * gpGlobals->v_right * RANDOM_FLOAT( 0, deflection ) + gpGlobals->v_up * RANDOM_FLOAT( -deflection, deflection );
UTIL_TraceLine ( vecSrc, vecSrc + vecAim * 1024, dont_ignore_monsters, ENT( pev ), &tr);
m_pBeam[m_iBeams] = CBeam::BeamCreate( "sprites/lgtning.spr", 50 );
if (!m_pBeam[m_iBeams])
return;
m_pBeam[m_iBeams]->PointEntInit( tr.vecEndPos, entindex( ) );
m_pBeam[m_iBeams]->SetEndAttachment( side < 0 ? 2 : 1 );
m_pBeam[m_iBeams]->SetColor( 180, 255, 96 );
m_pBeam[m_iBeams]->SetBrightness( 255 );
m_pBeam[m_iBeams]->SetNoise( 20 );
m_iBeams++;
pEntity = CBaseEntity::Instance(tr.pHit);
if (pEntity != NULL && pEntity->pev->takedamage)
{
pEntity->TraceAttack( pev, gSkillData.slaveDmgZap, vecAim, &tr, DMG_SHOCK );
}
UTIL_EmitAmbientSound( ENT(pev), tr.vecEndPos, "weapons/electro4.wav", 0.5, ATTN_NORM, 0, RANDOM_LONG( 140, 160 ) );
}
//=========================================================
// ClearBeams - remove all beams
//=========================================================
void CISlave :: ClearBeams( )
{
for (int i = 0; i < ISLAVE_MAX_BEAMS; i++)
{
if (m_pBeam[i])
{
UTIL_Remove( m_pBeam[i] );
m_pBeam[i] = NULL;
}
}
m_iBeams = 0;
pev->skin = 0;
STOP_SOUND( ENT(pev), CHAN_WEAPON, "debris/zap4.wav" );
}
| 0 | 0.975996 | 1 | 0.975996 | game-dev | MEDIA | 0.990202 | game-dev | 0.97058 | 1 | 0.97058 |
gw2scratch/evtc | 1,149 | EVTCAnalytics/Processing/Encounters/Results/AgentKillingBlowDeterminer.cs | using System.Collections.Generic;
using System.Linq;
using GW2Scratch.EVTCAnalytics.Events;
using GW2Scratch.EVTCAnalytics.Model.Agents;
using System;
namespace GW2Scratch.EVTCAnalytics.Processing.Encounters.Results
{
/// <summary>
/// A result determiner that returns success if there was a killing blow towards an agent
/// </summary>
public class AgentKillingBlowDeterminer : EventFoundResultDeterminer
{
private readonly Agent agent;
public AgentKillingBlowDeterminer(Agent agent)
{
this.agent = agent;
}
public override IReadOnlyList<Type> RequiredEventTypes { get; } = new List<Type> { typeof(PhysicalDamageEvent) };
public override IReadOnlyList<uint> RequiredBuffSkillIds { get; } = new List<uint>();
public override IReadOnlyList<PhysicalDamageEvent.Result> RequiredPhysicalDamageEventResults { get; } =
new List<PhysicalDamageEvent.Result> { PhysicalDamageEvent.Result.KillingBlow };
protected override Event GetEvent(IEnumerable<Event> events)
{
return events.OfType<PhysicalDamageEvent>()
.FirstOrDefault(x => x.Defender == agent && x.HitResult == PhysicalDamageEvent.Result.KillingBlow);
}
}
} | 0 | 0.903851 | 1 | 0.903851 | game-dev | MEDIA | 0.92143 | game-dev | 0.798422 | 1 | 0.798422 |
rossturner/king-under-the-mountain | 3,663 | core/src/main/java/technology/rocketjump/undermount/entities/behaviour/furniture/TransformAfterSetTimeBehaviour.java | package technology.rocketjump.undermount.entities.behaviour.furniture;
import com.alibaba.fastjson.JSONObject;
import com.badlogic.gdx.ai.msg.MessageDispatcher;
import com.google.common.collect.ImmutableMap;
import org.pmw.tinylog.Logger;
import technology.rocketjump.undermount.entities.components.furniture.FurnitureParticleEffectsComponent;
import technology.rocketjump.undermount.entities.model.Entity;
import technology.rocketjump.undermount.gamecontext.GameContext;
import technology.rocketjump.undermount.jobs.model.JobTarget;
import technology.rocketjump.undermount.messaging.MessageType;
import technology.rocketjump.undermount.messaging.types.TransformFurnitureMessage;
import technology.rocketjump.undermount.persistence.SavedGameDependentDictionaries;
import technology.rocketjump.undermount.persistence.model.InvalidSaveException;
import technology.rocketjump.undermount.persistence.model.SavedGameStateHolder;
import technology.rocketjump.undermount.ui.i18n.I18nText;
import technology.rocketjump.undermount.ui.i18n.I18nTranslator;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static technology.rocketjump.undermount.ui.i18n.I18nTranslator.oneDecimalFormat;
public class TransformAfterSetTimeBehaviour extends FurnitureBehaviour implements SelectableDescription {
private static final double TOTAL_TIME = 50.0;
private double timeRemaining = TOTAL_TIME;
private double lastUpdateGameTime = 0;
@Override
public void init(Entity parentEntity, MessageDispatcher messageDispatcher, GameContext gameContext) {
super.init(parentEntity, messageDispatcher, gameContext);
lastUpdateGameTime = gameContext.getGameClock().getCurrentGameTime();
if (relatedFurnitureTypes.size() != 1) {
Logger.error("Expecting 1 related furniture type for " + this.getClass().getSimpleName());
}
}
@Override
public void infrequentUpdate(GameContext gameContext) {
super.infrequentUpdate(gameContext);
double elapsed = gameContext.getGameClock().getCurrentGameTime() - lastUpdateGameTime;
timeRemaining -= elapsed;
lastUpdateGameTime = gameContext.getGameClock().getCurrentGameTime();
FurnitureParticleEffectsComponent particleEffectsComponent = parentEntity.getComponent(FurnitureParticleEffectsComponent.class);
if (particleEffectsComponent != null) {
particleEffectsComponent.triggerProcessingEffects(
Optional.ofNullable(new JobTarget(parentEntity)));
}
if (timeRemaining <= 0) {
if (particleEffectsComponent != null) {
particleEffectsComponent.releaseParticles();
}
messageDispatcher.dispatchMessage(MessageType.TRANSFORM_FURNITURE_TYPE, new TransformFurnitureMessage(parentEntity, relatedFurnitureTypes.get(0)));
}
}
@Override
public void writeTo(JSONObject asJson, SavedGameStateHolder savedGameStateHolder) {
super.writeTo(asJson, savedGameStateHolder);
asJson.put("timeRemaining", timeRemaining);
}
@Override
public void readFrom(JSONObject asJson, SavedGameStateHolder savedGameStateHolder, SavedGameDependentDictionaries relatedStores) throws InvalidSaveException {
super.readFrom(asJson, savedGameStateHolder, relatedStores);
this.timeRemaining = asJson.getDoubleValue("timeRemaining");
}
@Override
public List<I18nText> getDescription(I18nTranslator i18nTranslator, GameContext gameContext) {
List<I18nText> descriptions = new ArrayList<>(1);
double progress = (TOTAL_TIME - timeRemaining) / TOTAL_TIME;
descriptions.add(i18nTranslator.getTranslatedWordWithReplacements("FURNITURE.DESCRIPTION.GENERIC_PROGRESS",
ImmutableMap.of("progress", new I18nText(oneDecimalFormat.format(100f * progress)))));
return descriptions;
}
}
| 0 | 0.72081 | 1 | 0.72081 | game-dev | MEDIA | 0.903481 | game-dev | 0.958231 | 1 | 0.958231 |
Nebukam/PCGExtendedToolkit | 2,569 | Source/PCGExtendedToolkit/Private/Misc/Filters/PCGExPickerFilter.cpp | // Copyright 2025 Timothé Lapetite and contributors
// Released under the MIT license https://opensource.org/license/MIT/
#include "Misc/Filters/PCGExPickerFilter.h"
#include "Data/PCGExData.h"
#include "Data/PCGExPointIO.h"
#include "Misc/Pickers/PCGExPicker.h"
#include "Transform/Tensors/PCGExTensorFactoryProvider.h"
#define LOCTEXT_NAMESPACE "PCGExPickerFilterDefinition"
#define PCGEX_NAMESPACE PCGExPickerFilterDefinition
bool UPCGExPickerFilterFactory::Init(FPCGExContext* InContext)
{
if (!Super::Init(InContext)) { return false; }
if (!PCGExFactories::GetInputFactories(InContext, PCGExPicker::SourcePickersLabel, PickerFactories, {PCGExFactories::EType::IndexPicker}, true)) { return false; }
if (PickerFactories.IsEmpty())
{
if (!bQuietMissingInputError) { PCGE_LOG_C(Error, GraphAndLog, InContext, FTEXT("Missing pickers.")); }
return false;
}
return true;
}
TSharedPtr<PCGExPointFilter::IFilter> UPCGExPickerFilterFactory::CreateFilter() const
{
return MakeShared<PCGExPointFilter::FPickerFilter>(this);
}
bool PCGExPointFilter::FPickerFilter::Init(FPCGExContext* InContext, const TSharedPtr<PCGExData::FFacade>& InPointDataFacade)
{
if (!IFilter::Init(InContext, InPointDataFacade)) { return false; }
for (const TObjectPtr<const UPCGExPickerFactoryData>& FactoryData : TypedFilterFactory->PickerFactories)
{
FactoryData->AddPicks(InPointDataFacade->GetNum(), Picks);
}
return true;
}
bool PCGExPointFilter::FPickerFilter::Test(const int32 PointIndex) const
{
return TypedFilterFactory->Config.bInvert ? !Picks.Contains(PointIndex) : Picks.Contains(PointIndex);
}
bool PCGExPointFilter::FPickerFilter::Test(const TSharedPtr<PCGExData::FPointIO>& IO, const TSharedPtr<PCGExData::FPointIOCollection>& ParentCollection) const
{
if (!ParentCollection) { return false; }
const int32 NumEntries = ParentCollection->Num();
for (const TObjectPtr<const UPCGExPickerFactoryData>& FactoryData : TypedFilterFactory->PickerFactories)
{
TSet<int32> TempPicks;
FactoryData->AddPicks(NumEntries, TempPicks);
if (TempPicks.Contains(IO->IOIndex)) { return !TypedFilterFactory->Config.bInvert; }
}
return TypedFilterFactory->Config.bInvert;
}
TArray<FPCGPinProperties> UPCGExPickerFilterProviderSettings::InputPinProperties() const
{
TArray<FPCGPinProperties> PinProperties = Super::InputPinProperties();
PCGEX_PIN_FACTORIES(PCGExPicker::SourcePickersLabel, "Pickers", Required, FPCGExDataTypeInfoPicker::AsId())
return PinProperties;
}
PCGEX_CREATE_FILTER_FACTORY(Picker)
#undef LOCTEXT_NAMESPACE
#undef PCGEX_NAMESPACE
| 0 | 0.733454 | 1 | 0.733454 | game-dev | MEDIA | 0.681175 | game-dev | 0.766506 | 1 | 0.766506 |
OpenVisualCloud/Immersive-Video-Sample | 5,806 | src/isolib/atoms/SegIndexAtom.cpp | /*
* Copyright (c) 2019, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
//!
//! \file: SegIndexAtom.cpp
//! \brief: SegIndexAtom class implementation
//!
//! Created on October 16, 2019, 13:39 PM
//!
#include "SegIndexAtom.h"
#include <cassert>
#include <iostream>
#include <stdexcept>
VCD_MP4_BEGIN
SegmentIndexAtom::SegmentIndexAtom(uint8_t version)
: FullAtom("sidx", version, 0)
, m_referenceID(0)
, m_timescale(0)
, m_earliestPresentationTime(0)
, m_firstOffset(0)
, m_references()
, m_reserveTotal(0)
{
}
void SegmentIndexAtom::SetSpaceReserve(size_t reserveTotal)
{
m_reserveTotal = reserveTotal;
}
void SegmentIndexAtom::AddReference(const SegmentIndexAtom::Reference& reference)
{
m_references.push_back(reference);
assert(m_reserveTotal == 0 || m_references.size() < m_reserveTotal);
}
std::vector<SegmentIndexAtom::Reference> SegmentIndexAtom::GetReferences() const
{
return m_references;
}
void SegmentIndexAtom::ToStream(Stream& str)
{
const uint32_t referenceSize = 3 * 4;
const uint32_t reserveBytes = static_cast<uint32_t>((m_reserveTotal - m_references.size()) * referenceSize);
WriteFullAtomHeader(str);
str.Write32(m_referenceID);
str.Write32(m_timescale);
if (GetVersion() == 0)
{
str.Write32(static_cast<uint32_t>(m_earliestPresentationTime));
str.Write32(static_cast<uint32_t>(m_firstOffset + reserveBytes));
}
else if (GetVersion() == 1)
{
str.Write64(m_earliestPresentationTime);
str.Write64(m_firstOffset + reserveBytes);
}
else
{
ISO_LOG(LOG_ERROR, "SegmentIndexAtom::ToStream() supports only 'sidx' version 0 or 1\n");
throw Exception();
}
str.Write16(0); // reserved = 0
str.Write16(static_cast<uint16_t>(m_references.size())); // reference_count
for (uint32_t i = 0; i < m_references.size(); i++)
{
str.Write1(m_references.at(i).referenceType ? uint64_t(1) : uint64_t(0), 1); // bit (1) reference_type
str.Write1(uint64_t(0) | m_references.at(i).referencedSize, 31); // unsigned int(31) referenced_size
str.Write32(m_references.at(i).subsegmentDuration); // unsigned int(32) subsegment_duration
str.Write1(m_references.at(i).startsWithSAP ? uint64_t(1) : uint64_t(0), 1); // bit (1) starts_with_SAP
str.Write1(uint64_t(0) | m_references.at(i).sapType, 3); // unsigned int(3) SAP_type
str.Write1(uint64_t(0) | m_references.at(i).sapDeltaTime, 28); // unsigned int(28) SAP_delta_time
}
UpdateSize(str);
if (m_reserveTotal != 0)
{
str.Write32(reserveBytes);
str.Write32(FourCCInt("free").GetUInt32());
str.Write32(0);
for (uint32_t i = 1; i < m_reserveTotal - m_references.size(); i++)
{
str.Write32(0);
str.Write32(0);
str.Write32(0);
}
}
}
void SegmentIndexAtom::FromStream(Stream& str)
{
ParseFullAtomHeader(str);
m_referenceID = str.Read32();
m_timescale = str.Read32();
if (GetVersion() == 0)
{
m_earliestPresentationTime = str.Read32();
m_firstOffset = str.Read32();
}
else if (GetVersion() == 1)
{
m_earliestPresentationTime = str.Read64();
m_firstOffset = str.Read64();
}
else
{
ISO_LOG(LOG_ERROR, "SegmentIndexAtom::FromStream() supports only 'sidx' version 0 or 1\n");
throw Exception();
}
str.Read16(); // reserved = 0
uint16_t referenceCount = str.Read16(); // reference_count
m_references.clear();
m_references.reserve(referenceCount);
for (uint16_t i = 0; i < referenceCount; i++)
{
Reference ref;
ref.referenceType = (str.Read1(1) != 0); // bit (1) reference_type
ref.referencedSize = str.Read1(31); // unsigned int(31) referenced_size
ref.subsegmentDuration = str.Read32(); // unsigned int(32) subsegment_duration
ref.startsWithSAP = (str.Read1(1) != 0); // bit (1) starts_with_SAP
ref.sapType = static_cast<uint8_t>(str.Read1(3)); // unsigned int(3) SAP_type
ref.sapDeltaTime = str.Read1(28); // unsigned int(28) SAP_delta_time
m_references.push_back(ref);
}
}
VCD_MP4_END
| 0 | 0.740155 | 1 | 0.740155 | game-dev | MEDIA | 0.208496 | game-dev | 0.829911 | 1 | 0.829911 |
superman-t/PlaneGame | 1,134 | cocos/scripting/lua-bindings/auto/api/EventListenerAssetsManagerEx.lua |
--------------------------------
-- @module EventListenerAssetsManagerEx
-- @extend EventListenerCustom
-- @parent_module cc
--------------------------------
-- Initializes event with type and callback function
-- @function [parent=#EventListenerAssetsManagerEx] init
-- @param self
-- @param #cc.AssetsManagerEx AssetsManagerEx
-- @param #function callback
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#EventListenerAssetsManagerEx] clone
-- @param self
-- @return EventListenerAssetsManagerEx#EventListenerAssetsManagerEx ret (return value: cc.EventListenerAssetsManagerEx)
--------------------------------
-- / Overrides
-- @function [parent=#EventListenerAssetsManagerEx] checkAvailable
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Constructor
-- @function [parent=#EventListenerAssetsManagerEx] EventListenerAssetsManagerEx
-- @param self
-- @return EventListenerAssetsManagerEx#EventListenerAssetsManagerEx self (return value: cc.EventListenerAssetsManagerEx)
return nil
| 0 | 0.838263 | 1 | 0.838263 | game-dev | MEDIA | 0.727251 | game-dev | 0.823839 | 1 | 0.823839 |
kuri65536/python-for-android | 9,300 | python-modules/twisted/twisted/words/xish/xpath.py | # -*- test-case-name: twisted.words.test.test_xpath -*-
#
# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
XPath query support.
This module provides L{XPathQuery} to match
L{domish.Element<twisted.words.xish.domish.Element>} instances against
XPath-like expressions.
"""
try:
import cStringIO as StringIO
except ImportError:
import StringIO
class LiteralValue(str):
def value(self, elem):
return self
class IndexValue:
def __init__(self, index):
self.index = int(index) - 1
def value(self, elem):
return elem.children[self.index]
class AttribValue:
def __init__(self, attribname):
self.attribname = attribname
if self.attribname == "xmlns":
self.value = self.value_ns
def value_ns(self, elem):
return elem.uri
def value(self, elem):
if self.attribname in elem.attributes:
return elem.attributes[self.attribname]
else:
return None
class CompareValue:
def __init__(self, lhs, op, rhs):
self.lhs = lhs
self.rhs = rhs
if op == "=":
self.value = self._compareEqual
else:
self.value = self._compareNotEqual
def _compareEqual(self, elem):
return self.lhs.value(elem) == self.rhs.value(elem)
def _compareNotEqual(self, elem):
return self.lhs.value(elem) != self.rhs.value(elem)
class BooleanValue:
"""
Provide boolean XPath expression operators.
@ivar lhs: Left hand side expression of the operator.
@ivar op: The operator. One of C{'and'}, C{'or'}.
@ivar rhs: Right hand side expression of the operator.
@ivar value: Reference to the method that will calculate the value of
this expression given an element.
"""
def __init__(self, lhs, op, rhs):
self.lhs = lhs
self.rhs = rhs
if op == "and":
self.value = self._booleanAnd
else:
self.value = self._booleanOr
def _booleanAnd(self, elem):
"""
Calculate boolean and of the given expressions given an element.
@param elem: The element to calculate the value of the expression from.
"""
return self.lhs.value(elem) and self.rhs.value(elem)
def _booleanOr(self, elem):
"""
Calculate boolean or of the given expressions given an element.
@param elem: The element to calculate the value of the expression from.
"""
return self.lhs.value(elem) or self.rhs.value(elem)
def Function(fname):
"""
Internal method which selects the function object
"""
klassname = "_%s_Function" % fname
c = globals()[klassname]()
return c
class _not_Function:
def __init__(self):
self.baseValue = None
def setParams(self, baseValue):
self.baseValue = baseValue
def value(self, elem):
return not self.baseValue.value(elem)
class _text_Function:
def setParams(self):
pass
def value(self, elem):
return str(elem)
class _Location:
def __init__(self):
self.predicates = []
self.elementName = None
self.childLocation = None
def matchesPredicates(self, elem):
if self.elementName != None and self.elementName != elem.name:
return 0
for p in self.predicates:
if not p.value(elem):
return 0
return 1
def matches(self, elem):
if not self.matchesPredicates(elem):
return 0
if self.childLocation != None:
for c in elem.elements():
if self.childLocation.matches(c):
return 1
else:
return 1
return 0
def queryForString(self, elem, resultbuf):
if not self.matchesPredicates(elem):
return
if self.childLocation != None:
for c in elem.elements():
self.childLocation.queryForString(c, resultbuf)
else:
resultbuf.write(str(elem))
def queryForNodes(self, elem, resultlist):
if not self.matchesPredicates(elem):
return
if self.childLocation != None:
for c in elem.elements():
self.childLocation.queryForNodes(c, resultlist)
else:
resultlist.append(elem)
def queryForStringList(self, elem, resultlist):
if not self.matchesPredicates(elem):
return
if self.childLocation != None:
for c in elem.elements():
self.childLocation.queryForStringList(c, resultlist)
else:
for c in elem.children:
if isinstance(c, (str, unicode)):
resultlist.append(c)
class _AnyLocation:
def __init__(self):
self.predicates = []
self.elementName = None
self.childLocation = None
def matchesPredicates(self, elem):
for p in self.predicates:
if not p.value(elem):
return 0
return 1
def listParents(self, elem, parentlist):
if elem.parent != None:
self.listParents(elem.parent, parentlist)
parentlist.append(elem.name)
def isRootMatch(self, elem):
if (self.elementName == None or self.elementName == elem.name) and \
self.matchesPredicates(elem):
if self.childLocation != None:
for c in elem.elements():
if self.childLocation.matches(c):
return True
else:
return True
return False
def findFirstRootMatch(self, elem):
if (self.elementName == None or self.elementName == elem.name) and \
self.matchesPredicates(elem):
# Thus far, the name matches and the predicates match,
# now check into the children and find the first one
# that matches the rest of the structure
# the rest of the structure
if self.childLocation != None:
for c in elem.elements():
if self.childLocation.matches(c):
return c
return None
else:
# No children locations; this is a match!
return elem
else:
# Ok, predicates or name didn't match, so we need to start
# down each child and treat it as the root and try
# again
for c in elem.elements():
if self.matches(c):
return c
# No children matched...
return None
def matches(self, elem):
if self.isRootMatch(elem):
return True
else:
# Ok, initial element isn't an exact match, walk
# down each child and treat it as the root and try
# again
for c in elem.elements():
if self.matches(c):
return True
# No children matched...
return False
def queryForString(self, elem, resultbuf):
raise NotImplementedError(
"queryForString is not implemented for any location")
def queryForNodes(self, elem, resultlist):
# First check to see if _this_ element is a root
if self.isRootMatch(elem):
resultlist.append(elem)
# Now check each child
for c in elem.elements():
self.queryForNodes(c, resultlist)
def queryForStringList(self, elem, resultlist):
if self.isRootMatch(elem):
for c in elem.children:
if isinstance(c, (str, unicode)):
resultlist.append(c)
for c in elem.elements():
self.queryForStringList(c, resultlist)
class XPathQuery:
def __init__(self, queryStr):
self.queryStr = queryStr
from twisted.words.xish.xpathparser import parse
self.baseLocation = parse('XPATH', queryStr)
def __hash__(self):
return self.queryStr.__hash__()
def matches(self, elem):
return self.baseLocation.matches(elem)
def queryForString(self, elem):
result = StringIO.StringIO()
self.baseLocation.queryForString(elem, result)
return result.getvalue()
def queryForNodes(self, elem):
result = []
self.baseLocation.queryForNodes(elem, result)
if len(result) == 0:
return None
else:
return result
def queryForStringList(self, elem):
result = []
self.baseLocation.queryForStringList(elem, result)
if len(result) == 0:
return None
else:
return result
__internedQueries = {}
def internQuery(queryString):
if queryString not in __internedQueries:
__internedQueries[queryString] = XPathQuery(queryString)
return __internedQueries[queryString]
def matches(xpathstr, elem):
return internQuery(xpathstr).matches(elem)
def queryForStringList(xpathstr, elem):
return internQuery(xpathstr).queryForStringList(elem)
def queryForString(xpathstr, elem):
return internQuery(xpathstr).queryForString(elem)
def queryForNodes(xpathstr, elem):
return internQuery(xpathstr).queryForNodes(elem)
| 0 | 0.810374 | 1 | 0.810374 | game-dev | MEDIA | 0.129877 | game-dev | 0.928974 | 1 | 0.928974 |
BobbyAnguelov/Esoterica | 5,752 | Code/Engine/Animation/Graph/Animation_RuntimeGraph_Recording.h | #pragma once
#include "Engine/_Module/API.h"
#include "Animation_RuntimeGraph_Context.h"
#include "Animation_RuntimeGraph_LayerData.h"
#include "Engine/Animation/AnimationTarget.h"
#include "Engine/Animation/AnimationSyncTrack.h"
#include "Base/Time/Time.h"
#include "Base/Serialization/BinarySerialization.h"
#include "Base/Types/Containers_ForwardDecl.h"
#include "Base/Resource/ResourceID.h"
//-------------------------------------------------------------------------
#if EE_DEVELOPMENT_TOOLS
namespace EE::Animation
{
class GraphNode;
//-------------------------------------------------------------------------
// Recorded Full Graph State
//-------------------------------------------------------------------------
// Records the state of a given graph instance
struct EE_ENGINE_API RecordedGraphState
{
struct ReferencedGraphState
{
int16_t m_referencedGraphNodeIdx = InvalidIndex;
RecordedGraphState* m_pRecordedState = nullptr;
};
public:
~RecordedGraphState();
// Clears all recorded data and allows for a new recording to occur
void Reset();
// Prepares recording to be read back
void PrepareForReading();
// Get a unique list of the various graphs recorded
void GetAllRecordedGraphResourceIDs( TVector<ResourceID>& outGraphIDs ) const;
// Referenced graphs
//-------------------------------------------------------------------------
RecordedGraphState* CreateReferencedGraphStateRecording( int16_t referencedGraphNodeIdx );
RecordedGraphState* GetReferencedGraphRecording( int16_t referencedGraphNodeIdx ) const;
// Serialization helpers
//-------------------------------------------------------------------------
template<typename T>
inline void WriteValue( T& value )
{
m_outputArchive << value;
}
template<typename T>
inline void WriteValue( T const& value )
{
m_outputArchive << value;
}
template<typename T>
inline void ReadValue( T& value ) const
{
m_inputArchive << value;
}
// Node accessor
//-------------------------------------------------------------------------
template<typename T>
inline T* GetNode( int16_t nodeIdx ) const
{
EE_ASSERT( nodeIdx >= 0 && nodeIdx < m_pNodes->size() );
return (T*) ( *m_pNodes )[nodeIdx];
}
public:
ResourceID m_graphID;
StringID m_variationID;
uint64_t m_recordedResourceHash;
TVector<int16_t> m_initializedNodeIndices;
TVector<ReferencedGraphState> m_referencedGraphStates;
TVector<GraphNode*>* m_pNodes = nullptr;
private:
Serialization::BinaryOutputArchive m_outputArchive;
mutable Serialization::BinaryInputArchive m_inputArchive;
};
//-------------------------------------------------------------------------
// Recorded Per-Frame Graph Data
//-------------------------------------------------------------------------
// All the data needed to replay a given recorded frame
struct RecordedGraphFrameData
{
union ParameterData
{
ParameterData() {}
bool m_bool;
StringID m_ID;
float m_float;
Float3 m_vector;
Target m_target;
};
public:
Transform m_characterWorldTransform;
SyncTrackTimeRange m_updateRange;
TVector<ParameterData> m_parameterData;
Seconds m_deltaTime;
Blob m_serializedTaskData;
TVector<GraphLayerUpdateState> m_layerUpdateStates;
};
//-------------------------------------------------------------------------
// Graph Recorder
//-------------------------------------------------------------------------
// Records information about each update for the recorded graph instance
struct EE_ENGINE_API GraphRecorder
{
public:
inline bool HasRecordedData() const { return !m_recordedData.empty(); }
bool HasRecordedDataForGraph( ResourceID const& graphResourceID ) const;
inline int32_t GetNumRecordedFrames() const { return int32_t( m_recordedData.size() ); }
inline bool IsValidRecordedFrameIndex( int32_t frameIdx ) const { return frameIdx >= 0 && frameIdx < m_recordedData.size(); }
inline void Reset()
{
m_recordedData.clear();
m_initialState.Reset();
}
public:
ResourceID m_graphID;
StringID m_variationID;
uint64_t m_recordedResourceHash;
RecordedGraphState m_initialState;
TVector<RecordedGraphFrameData> m_recordedData;
};
}
#endif | 0 | 0.984267 | 1 | 0.984267 | game-dev | MEDIA | 0.776207 | game-dev | 0.669665 | 1 | 0.669665 |
BreweryTeam/TheBrewingProject | 2,917 | bukkit/src/main/java/dev/jsinco/brewery/bukkit/integration/item/MmoItemsIntegration.java | package dev.jsinco.brewery.bukkit.integration.item;
import com.google.common.base.Preconditions;
import dev.jsinco.brewery.bukkit.TheBrewingProject;
import dev.jsinco.brewery.bukkit.api.integration.ItemIntegration;
import dev.jsinco.brewery.util.ClassUtil;
import io.lumine.mythic.lib.api.item.NBTItem;
import net.Indyuce.mmoitems.MMOItems;
import net.Indyuce.mmoitems.api.Type;
import net.Indyuce.mmoitems.api.event.MMOItemsReloadEvent;
import net.Indyuce.mmoitems.api.item.build.ItemStackBuilder;
import net.Indyuce.mmoitems.api.item.build.MMOItemBuilder;
import net.Indyuce.mmoitems.api.item.mmoitem.MMOItem;
import net.Indyuce.mmoitems.api.item.template.MMOItemTemplate;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public class MmoItemsIntegration implements ItemIntegration, Listener {
CompletableFuture<Void> initialized = new CompletableFuture<>();
@Override
public Optional<ItemStack> createItem(String id) {
return getMmoItem(id)
.map(MMOItem::newBuilder)
.map(ItemStackBuilder::build);
}
@Override
public boolean isIngredient(String id) {
return getMmoItem(id).isPresent();
}
@Override
public @Nullable Component displayName(String id) {
return createItem(id)
.map(ItemStack::displayName)
.orElse(null);
}
private Optional<MMOItem> getMmoItem(String id) {
String[] split = id.split(":");
Preconditions.checkArgument(split.length == 2, "mmoitems id needs to be in the format <type>:<id>");
return Optional.ofNullable(MMOItems.plugin.getTemplates().getTemplate(Type.get(split[0]), split[1]))
.map(MMOItemTemplate::newBuilder)
.map(MMOItemBuilder::build);
}
@Override
public @Nullable String getItemId(ItemStack itemStack) {
NBTItem nbtItem = NBTItem.get(itemStack);
if (!nbtItem.hasType()) {
return null;
}
return nbtItem.getType() + ":" + nbtItem.get("MMOITEMS_ITEM_ID");
}
@Override
public CompletableFuture<Void> initialized() {
return initialized;
}
@Override
public boolean isEnabled() {
return ClassUtil.exists("net.Indyuce.mmoitems.MMOItems");
}
@Override
public String getId() {
return "mmoitems";
}
@Override
public void onEnable() {
Bukkit.getPluginManager().registerEvents(this, TheBrewingProject.getInstance());
this.initialized = new CompletableFuture<>();
}
@EventHandler
public void onMmoItemsReload(MMOItemsReloadEvent event) {
initialized.completeAsync(() -> null);
}
}
| 0 | 0.876586 | 1 | 0.876586 | game-dev | MEDIA | 0.858578 | game-dev | 0.936658 | 1 | 0.936658 |
Exiled-Team/EXILED | 16,977 | Changelog.md | ## Fixes:
- `[All]` A lot of documentation has been updated.
- `[Exiled.API]` Fixed a bug that would sometimes cause `Room.FlickerableLightController` to be null. [#975]
- `[Exiled.API]` Fixed a bug that would cause the `Room.Doors` property to not always contain all the doors connecting to the room. [#975]
- `[Exiled.API]` The `Player.Hurt` methods will now cause cassie to use the `DamageHandlerBase.CassieDeathAnnouncement` property or the `cassieAnnouncement` argument if the damage will kill a non-SCP player. [#989]
- `[Exiled.API]` The `Player.ArtificialHealth` and `Player.MaxArtificialHealth` properties should now function properly. [#1008]
- `[Exiled.API]` The `Map.Lockers` property should no longer fail to contain all lockers on the map. [#1030]
- `[Exiled.API]` Fixed `Room.TeslaGate` being null in rooms it shouldn't be null in. [#1122]
- `[Exiled.API]` Fixed the `Script` property in SCP-related `Features.Roles` classes sometimes being null. Added the peoperty to SCP classes it was missing from. [#1126]
- `[Exiled.API]` Fixed `API.Features.TeslaGate.Position` always being `Vector3.zero`. [#1128]
- `[Exiled.API]` `Room.Players` should no longer throw a nullref when a player is not in a room. [#1146]
- `[Exiled.API]` `Player.Get(string)` documentation updated to reflect it can accept the `string` version of an `int` to match with player IDs. [#1147]
- `[Exiled.CreditTags]` Changed the default value of the `ignore_dnt_flag` config value to reflect it's documentation. [#1116]
- `[Exiled.CustomRoles]` The `CustomRole.CustomAbilities` property is now checked for null before accessed. [#994]
- `[Exiled.CustomRoles]` The `CustomRole.CustomAbilities` property will now deserialize abilities inheriting the `CustomAbility` class correctly using the default config deserializer. [#1018]
- `[Exiled.CustomRoles]` Fixed the `Player.InfoArea.Role` value not being set back to visible when removing a `CustomRole`. [#1117]
- `[Exiled.CustomItems]` + `[Exiled.CustomRoles]` The `CustomItem`, `CustomRole` and `CustomAbility` types can now be registered from existing objects for the purpose of configs. [#1143]
- `[Exiled.CustomItems]` + `[Exiled.CustomRoles]` The `CustomWeapon`, `CustomGrenade`, `ActiveAbility` and `PassiveAbility` sub-types should now serialize as the correct types. [#1143 & 1142]
- `[Exiled.Example]` Fixed all null reference exceptions caused by the bad usage of ?. operator inside all the events. [#815]
- `[Exiled.Events]` The `Warhead.Starting` event will no longer fire twice when triggered by a player. [#1009]
- `[Exiled.Events]` The `Warhead.Starting` event will now correctly include the player causing it when triggered by a command. [#1009]
- `[Exiled.Events]` The Warhead commands that can start the warhead will now return `Action prevented by a plugin` when the `Warhead.Starting` event is denied via a plugin. [#1009]
- `[Exiled.Events]` The server's max respawn wave settings will now be respected by the `Server.RespawningTeam` event. [#1013]
- `[Exiled.Events]` The `RemovingHandcuffsEventArgs.Player` will now correctly be the player removing the handcuffs. [#1024]
- `[Exiled.Events]` Tesla gates will now exit the Idle animation properly. [#1026]
- `[Exiled.Events]` Pickups should no longer remain locked indefinitely when `PickingUpItemEventArgs.IsAllowed` is set to false. [#1029]
- `[Exiled.Events]` The EXILED Anti-Backdoor feature will no longer print messages about Exiled.Events changing values if those values were not actually changed by a plugin. [#1050]
- `[Exiled.Events]` Added a check to the `PlayerHasHint` patch to prevent unnecessary nullrefs in the console. [#1055]
- `[Exiled.Events]` Fixed the logic check for the `InteractingScp330EventArgs.ShouldSever` property's value. [#1066]
- `[Exiled.Events]` Fixed a player disconnection bug when shooting a Shooting Target in sync mode. [#1077]
- `[Exiled.Events]` Fixed improper documentation on several event methods. [#1118, #1120, #1123]
- `[Exiled.Events]` Fixed an issue with shotguns not firing the `Player.Shot` event. [#1131]
- `[Exiled.Events]` Corrected an issue with RA command logs being spammed when someone has the RA panel open. [#1133]
- `[Exiled.Events]` Fixed an issue that would cause more than the configured max of players to respawn during NTF or CI waves. [#1140]
- `[Exiled.Loader]` Fixed the chance of seeing the 'sexiled' message upon server loading. [#1129]
## Additions:
- `[Exiled.API]` Added the `AttachmentIdentifier` struct to avoid using the `FirearmAttachment` class from the base-game API. [#815]
- `[Exiled.API]` Added the `ItemExtensions::GetAttachments(ItemType, uint)` method. [#815]
- `[Exiled.API]` Added the `ItemExtensions::TryGetAttachments(ItemType, uint, out IEnumerable<AttachmentIdentifier>)` method. [#815]
- `[Exiled.API]` Added the `ItemExtensions::GetAttachmentsCode(IEnumerable<AttachmentIdentifier>)` method. [#815]
- `[Exiled.API]` Added the `ItemExtensions::GetBaseCode(ItemType)` method. [#815]
- `[Exiled.API]` Added the `Firearm::AttachmentIdentifiers` property. [#1025]
- `[Exiled.API]` Added the `Firearm::AddAttachment` method. [#815]
- `[Exiled.API]` Added the `Firearm::RemoveAttachment` method. [#815]
- `[Exiled.API]` Added the `Firearm::ClearAttachments` method. [#815]
- `[Exiled.API]` Added the `Firearm::GetAttachment` method. [#815]
- `[Exiled.API]` Added the `Firearm::TryGetAttachment` method. [#815]
- `[Exiled.API]` Added the `Firearm::AddPreference` method. [#815]
- `[Exiled.API]` Added the `Firearm::RemovePreference` method. [#815]
- `[Exiled.API]` Added the `Firearm::ClearPreferences` method. [#815]
- `[Exiled.API]` Added the `Firearm::AvailableAttachments` static property. [#815]
- `[Exiled.API]` Added the `Firearm::PlayerPreferences` static property. [#815]
- `[Exiled.API]` Added the `Firearm::BaseCode` property. [#815]
- `[Exiled.API]` Added the `Player::Preferences` property. [#815]
- `[Exiled.API]` Added an overload to `Item::Spawn` method. [#815]
- `[Exiled.API]` Added an overload to `Player::AddItem` method. [#815]
- `[Exiled.API]` Added the `Ammo.AmmoLimit` property. [#979]
- `[Exiled.API]` Added the `Item.Category`, `Item.IsAmmo`, `Item.IsArmor`, `Item.IsKeycard`, `Item.IsMedical`, `Item.IsScp`, `Item.IsThrowable`, `Item.IsUtility` and `Item.IsWeapon` properties. [#979]
- `[Exiled.API]` Added the `CameraType.Lcz330Hall`, `CameraType.Lcz330Chamber`, `DoorType.Scp330`, `DoorType.Scp330Chamber` and `RoomType.Lcz330` enum values. [#982]
- `[Exiled.API]` Added the `Player.TryAddCandy(CandyKindID)` method. [#986]
- `[Exiled.API]` Added the `Player.GetCategoryLimit(ItemCategory)` property. [#979]
- `[Exiled.API]` Added the `Map.GetCameraType(string)` method. [#991]
- `[Exiled.API]` Added the `Map.GetCameraByName(string) method. [#991]
- `[Exiled.API]` Added the `Door.Unlock(float, DoorLockType)` method. [#1001]
- `[Exiled.API]` Added the `Door.Lock(float, DoorLockType)` method. [#1001]
- `[Exiled.API]` Added the `Room.RoomIdentifier` property. [#1003]
- `[Exiled.API]` Added the `Room.TeslaGate` property. This can be null. [#1003]
- `[Exiled.API]` Added the `Player.GetModule<T>` method. [#1003]
- `[Exiled.API]` Added the `Log.DebugObject<T>(T, bool)` method. [#1003]
- `[Exiled.API]` Added the `Player.IsInventoryFull` property. [#1004]
- `[Exiled.API]` Added the `Player.AddAhp(float, float, float, float, float, bool)` method. [#1010]
- `[Exiled.API]` Added the `DamageType.IsWeapon(bool)`, `DamageType.IsScp(bool)` and `DamageType.IsStatusEffect` extension methods. [#1011]
- `[Exiled.API]` Added the `Item.Create(ItemType)` method, which always creates and returns the correct subclass type for the given item type. [#1012]
- `[Exiled.API]` Added the `Player.MakeNoise` method. [#1019]
- `[Exiled.API]` Added the `Cassie.VoiceLines` property. [#1020]
- `[Exiled.API]` Added the `Cassie.IsValid(string)` method. [#1020]
- `[Exiled.API]` Added an API class for SCP-244, Lifts, Elevators, Tesla Gates, Cameras and Generators. [#1031 & 1038 & 1042 & 1045]
- `[Exiled.API]` Added the `Player.Reconnect(ushort, float, bool, RoundRestartType)` method. [#1056]
- `[Exiled.API]` Added the `Player.Role` property, which is an object unique to each player representing their class. [#1058]
- `[Exiled.API]` Added various `GameObject` properties to API classes, such as `Door`, `Generator`, `Armor` and more. [#1062]
- `[Exiled.API]` Added overloads to `Log.Info`, `Log.Warn`, `Log.Error` and `Log.Debug` that accept a `string` instead of an `object` for efficiency. [#1070]
- `[Exiled.API]` Added the `Log.Assert(bool, object)` method. This method can be used to assert that a certain condition **MUST** be met, and if it is not, it will print a `Log.Error` message and throw an exception. [#1082]
- `[Exiled.API]` Added the `Player.Teleport(Vector3)`, `Player.Teleport(object)`, `Player.RandomTeleport(IEnumerable<Type>)` and `Player.RandomTeleport(Type)` methods. [#1125] **Read more below**
- `[Exiled.API]` Added the `API.Features.Intercom` class. [#1127]
- `[Exiled.API]` Added the `Server.TPS` property. [#1130]
- `[Exiled.API]` Added the `API.Features.Scp106Container` class. [#1135]
- `[Exiled.API]` Added the `DoorLockType.Lockdown2176` enum, `Ragdoll.CreationTime` property, `Recontainer.BreakGlass()` method, `Room.GameObject` property, `Round.AliveSides` property, `Scp914.GameObject` property, `Server.LaterJoinEnabled`, `Server.LaterJoinTime` and `Server.SpawnProtectTime` properties. [#1141]
- `[Exiled.API]` Added the `Player.Mute`, `Player.IntercomMute`, `Player.Unmute` and `Player.IntercomUnmute` methods. The `Player.Muted` and `Player.Unmuted` properties are no longer persistant through rounds. [#1144]
- `[Exiled.CustomItems]` Added the `CustomItem.OnAcquired(Player)` method, which is called anytime a player gains the item via any means, which is more reliable than just using `CustomItem.OnPickup`. [#988]
- `[Exiled.CustomItems]` Added the `CustomItem.RegisterItems` and `Customitem.UnregisterItems` methods. These will use the new `ExiledSerializableAttribute` to register/unregister all items in the calling plugin automatically. [#998]
- `[Exiled.CustomItems]` Added the `CustomItem.Check(Player)` overload to check the given player's current item.
- `[Exiled.CustomRoles]` Added the `CustomRole.CustomInfo` property which will be used instead of `CustomRole.Name (Custom Role)` in the player's custom info. [#966]
- `[Exiled.CustomRoles]` Added the `CustomRole.RegisterRoles` and `CustomRole.UnregisterRoles` methods. These will use the new `ExiledSerializableAttribute` to register/unregister all roles in the calling plugin automatically. [#998]
- `[Exiled.CustomRoles]` Added the `CustomRole.Scale` property that will be used to automatically change a player's size when they gain the role. [#1005]
- `[Exiled.Events]` Added the `Item.ReceivingPreference` event. [#815]
- `[Exiled.Events]` Added the `TriggeringTeslaEventArgs.Tesla` and `TriggeringTeslaEventArgs.IsInIdleRange` properties. [#973]
- `[Exiled.Events]` Added the `Ragdoll` property to both `Scp049.StartingRecall` and `Scp049.FinishingRecall` events. [#992]
- `[Exiled.Events]` Added the `Player.Landing` event. [#997]
- `[Exiled.Events]` Added the `DiedEventArgs.TargetOldRole` property. [#1039]
- `[Exiled.Events]` Added the `Map.BreakingScp2176` event. [#1051]
- `[Exiled.Events]` Added the `TogglingNoClipEventArgs.IsEnabled` property. [#1054]
- `[Exiled.Events]` Added the `DamagingWindowEventArgs.IsAllowed` property. [#1055]
- `[Exiled.Events]` The `Warhead.ActivatingWarheadPanel` event will now fire regardless of the keycard being held by the player. `IsAllowed` will default to false if they are not using a keycard that can normally activate the panel. [#1115]
- `[Exiled.Example]` Added the `Attachments` property to configs. [#815]
- `[Exiled.Loader]` Added the `AttachmentIdentifiersConverter` class to make the `AttachmentIdentifier` struct serializable. [#815]
## Changes (non-breaking):
- `[Exiled.API]` Increased the efficiency of finding doors, cameras and the light controller of rooms when they are cached. [#975]
- `[Exiled.API]` The `Respawn.NtfTickets` and `Respawn.ChaosTickets` values can now be changed. [#1067]
- `[Exiled.API]` Made several optimizations to the Attachments API to reduce server lag. [#1139]
- `[Exiled.Events]` The `Player.TriggeringTesla` event patch is now a transpiler. [#987]
- `[Exiled.Events]` The `Player.ActivatingWarheadPanel` event will now fire even when the player's current keycard does not have permission to unlock it. In this case, ev.IsAllowed will default to false, but can be changed to true to allow access. [#1115]
- `[Exiled.Events]` Made several improvements to patches that may help reduce server lag. [#1131]
## Changes (breaking):
- `[Exiled.API]` Removed the `Player.ShotHitMarker` method in favor of using `Player.ShotHitMarker(float)`.
- `[Exiled.API]` Removed the `BarrelType` enum. [#815]
- `[Exiled.API]` Removed the `SightType` enum. [#815]
- `[Exiled.API]` Removed the `OtherType` enum. [#815]
- `[Exiled.API]` Removed the `Modifiers` struct. [#815]
- `[Exiled.API]` Removed the `Player.AddItem(List<T>)` method in favor of using `Player.AddItem(IEnumerable<T>)`. [#815]
- `[Exiled.API]` Removed the `Player.ResetInventory(List<T>)` method in favor of using `Player.ResetInventory(IEnumerable<T>)`. [#815]
- `[Exiled.API]` Changed the `Scp330.AddCandy(CandyKindID)` method to `Scp330.AddCandy(CandyKindID, out bool)`. [#979]
- `[Exiled.API]` Changed the `Scp330.RemoveCandy(CandyKindID, bool)` method to `Scp330.RemoveCandy(CandyKindID, out int, bool)` [#979]
- `[Exiled.API]` Changed the order of values and names of many values in `Enums.CameraType` [#991]
- `[Exiled.API]` Removed all `Item` subclass constructors in favor of using the new `Item.Create(ItemType)` method. [#1012]
- `[Exiled.API]` Changed `Cassie.CustomSCPTermination(string, DamageHandlerBase)` to `Cassie.CustomScpTermination(string, DamageHandler)` [#1020]
- `[Exiled.API]` Removed all extension classes related to Lifts, Elevators, Tesla Gates, Cameras and Generators. [#1031 & 1038 & 1042]
- `[Exiled.API]` Changed the return type of `ItemExtensions.GetItemTypes()` from a `List<ItemType>` to `IEnumerable<ItemType>`. [#1062]
- `[Exiled.API]` Changed the `Cassie.Message`, `Cassie.DelayedMessage`, `MirrorExtensions.PlayCassieAnnouncement` methods to include a `isSubtitles` value. [#1063]
- `[Exiled.API]` Changed `Player.GetAmmoLimit(ItemType)` to `Player.GetAmmoLimit(AmmoType)`. [#1059]
- `[Exiled.API]` Many `Player` properties such as `Team`, `RoleType`, `Abilities`, `Speaker`, `SpectatedPlayer` and more have been moved to be contained inside the `Player.Role` object. [#1058]
- `[Exiled.API]` The `Room.LightsOff` property is now `Room.LightsOn` and has a setter. [#1106]
- `[Exiled.API]` The `Player.IsDead` property will no longer return true if their role type is `None` instead of `Spectator`. [#1134]
- `[Exiled.API]` Renamed `Round.ForceEnd()` to `Round.EndRound(bool)` [#1136]
- `[Exiled.API]` Renamed `Round.IsEnding` to `Round.IsEnded`. [#1138]
- `[Exiled.API]` `Player.Rotations` has been removed. The value type of `Player.Rotation` has been changed to `Vector2`. [#1165]
- `[Exiled.API]` All uses of `Scp079Generator` in EXILED has been replaced with `Exiled.API.Features.Generator`.
- `[Exiled.CustomItems]` Removed the `Modifiers` property in favor of using an array of `AttachmentNameTranslation`. [#815]
- `[Exiled.CustomItems]` Removed the `CustomItem.TryRegister` and `CustomItem.TryUnregister` methods. [#998]
- `[Exiled.CustomRole]` The following properties have been made public, instead of protected, so they can be used as config values: [#994]
- CustomRole.Inventory
- CustomRole.SpawnProperties
- CustomRole.KeepInventoryOnSpawn
- CustomRole.RemovalKillsPlayer
- CustomRole.KeepRoleOnDeath
- `[Exiled.CustomRoles]` Removed the `CustomRole.TryRegister` and `CustomRole.TryUnregister methods. [#998]
- `[Exiled.CustomRoles]` Renamed the `CustomRole.UnSubscribeEvents` method to `CustomRole.UnsubscribeEvents`. [#998]
- `[Exiled.Events]` Removed the `HurtingEventArgs.DamageHandler` property.
- `[Exiled.Events]` Removed the `DiedEventArgs.DamageHandler` property.
- `[Exiled.Events]` Removed the `DyingEventArgs.DamageHandler` property.
- `[Exiled.Events]` Removed the `AnnouncingScpTerminationEventArgs.DamageHandler` property.
- `[Exiled.Events]` Removed the `ExplodingGrenadeEventArgs.IsFrag` property.
- `[Exiled.Events]` Removed the `Item.ChangingAttributes` event. [#815]
- `[Exiled.Events]` Re-implemented the `Item.ChangingDurability` event with new parameters. [#815]
- `[Exiled.Events]` Re-implemented the `Item.ChangingAttachments` event with new parameters. [#815]
- `[Exiled.Events]` All events interacting with Lifts, Elevators, Tesla Gates, Cameras and Generators now use the Exiled.API objects in the event, instead of the base-game ones. [#1031 & 1038 & 1042]
- `[Exiled.Events]` Removed the `Player.SyncingData` event. [#1054]
| 0 | 0.790887 | 1 | 0.790887 | game-dev | MEDIA | 0.599539 | game-dev | 0.649317 | 1 | 0.649317 |
splhack/Hello-LWF-Cocos2d-x | 2,981 | lwf/cplusplus/core/lwf_animation.cpp | /*
* Copyright (C) 2013 GREE, Inc.
*
* 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 "lwf_animation.h"
#include "lwf_button.h"
#include "lwf_core.h"
#include "lwf_data.h"
#include "lwf_movie.h"
namespace LWF {
void LWF::PlayAnimation(int animationId, Movie *movie, Button *button)
{
int i = 0;
const vector<int> &animations = data->animations[animationId];
Movie *target = movie;
for (;;) {
switch (animations[i++]) {
case Animation::END:
return;
case Animation::PLAY:
target->Play();
break;
case Animation::STOP:
target->Stop();
break;
case Animation::NEXTFRAME:
target->NextFrame();
break;
case Animation::PREVFRAME:
target->PrevFrame();
break;
case Animation::GOTOFRAME:
target->GotoFrameInternal(animations[i++]);
break;
case Animation::GOTOLABEL:
target->GotoFrame(SearchFrame(target, animations[i++]));
break;
case Animation::SETTARGET:
{
target = movie;
int count = animations[i++];
if (count == 0)
break;
for (int j = 0; j < count; ++j) {
int instId = animations[i++];
switch (instId) {
case Animation::INSTANCE_TARGET_ROOT:
target = rootMovie.get();
break;
case Animation::INSTANCE_TARGET_PARENT:
target = target->parent;
if (!target)
target = rootMovie.get();
break;
default:
{
target = target->SearchMovieInstanceByInstanceId(
instId, false);
if (!target)
target = movie;
break;
}
}
}
}
break;
case Animation::EVENT:
{
int eventId = animations[i++];
#if defined(LWF_USE_LUA)
CallEventFunctionLua(eventId, movie, button);
#endif
EventHandlerList v(m_eventHandlers[eventId]);
EventHandlerList::iterator it(v.begin()), itend(v.end());
for (; it != itend; ++it)
it->second(movie, button);
}
break;
case Animation::CALL:
#if defined(LWF_USE_LUA)
{
int stringId = animations[i++];
if (stringId < 0 || stringId >= data->strings.size())
break;
CallFunctionLua(data->strings[stringId], target);
}
#else
i++;
#endif
break;
}
}
}
} // namespace LWF
| 0 | 0.754709 | 1 | 0.754709 | game-dev | MEDIA | 0.737918 | game-dev | 0.819295 | 1 | 0.819295 |
team-eternity/eternity | 43,809 | source/a_doom.cpp | //
// The Eternity Engine
// Copyright (C) 2025 James Haley et al.
//
// 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/
//
//------------------------------------------------------------------------------
//
// Purpose: DOOM action functions.
// Authors: James Haley, Ioan Chera, Max Waine, Xaser Acheron, Simone Ivanish
//
#include "z_zone.h"
#include "a_args.h"
#include "a_common.h"
#include "d_gi.h"
#include "d_mod.h"
#include "doomstat.h"
#include "e_args.h"
#include "e_mod.h"
#include "e_sound.h"
#include "e_states.h"
#include "e_things.h"
#include "e_ttypes.h"
#include "g_game.h"
#include "m_bbox.h" // ioanch 20160108: portal aware block iterator
#include "p_enemy.h"
#include "p_info.h"
#include "p_inter.h"
#include "p_map.h"
#include "p_maputl.h"
#include "p_mobjcol.h"
#include "p_mobj.h"
#include "p_portalcross.h"
#include "p_pspr.h"
#include "p_setup.h"
#include "p_skin.h"
#include "p_spec.h"
#include "p_tick.h"
#include "r_defs.h"
#include "r_main.h" // ioanch 20160106: portal correct access
#include "r_state.h"
#include "s_sound.h"
#include "sounds.h"
#include "v_misc.h"
//
// A_PosAttack
//
// Zombieman attack.
//
void A_PosAttack(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
int angle, damage, slope;
if(!actor->target)
return;
A_FaceTarget(actionargs);
angle = actor->angle;
slope = P_AimLineAttack(actor, angle, MISSILERANGE, false); // killough 8/2/98
S_StartSound(actor, sfx_pistol);
// haleyjd 08/05/04: use new function
angle += P_SubRandom(pr_posattack) << 20;
damage = (P_Random(pr_posattack) % 5 + 1) * 3;
P_LineAttack(actor, angle, MISSILERANGE, slope, damage);
}
//
// A_SPosAttack
//
// Sergeant attack.
//
void A_SPosAttack(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
int i, bangle, slope;
if(!actor->target)
return;
S_StartSound(actor, sfx_shotgn);
A_FaceTarget(actionargs);
bangle = actor->angle;
slope = P_AimLineAttack(actor, bangle, MISSILERANGE, false); // killough 8/2/98
for(i = 0; i < 3; ++i)
{
// haleyjd 08/05/04: use new function
int angle = bangle + (P_SubRandom(pr_sposattack) << 20);
int damage = ((P_Random(pr_sposattack) % 5) + 1) * 3;
P_LineAttack(actor, angle, MISSILERANGE, slope, damage);
}
}
//=============================================================================
//
// Chaingunner
//
//
// A_CPosAttack
//
// Heavy weapons dude attack.
//
void A_CPosAttack(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
int angle, bangle, damage, slope;
if(!actor->target)
return;
// haleyjd: restored to normal
S_StartSound(actor, sfx_shotgn);
A_FaceTarget(actionargs);
bangle = actor->angle;
slope = P_AimLineAttack(actor, bangle, MISSILERANGE, false); // killough 8/2/98
// haleyjd 08/05/04: use new function
angle = bangle + (P_SubRandom(pr_cposattack) << 20);
damage = ((P_Random(pr_cposattack) % 5) + 1) * 3;
P_LineAttack(actor, angle, MISSILERANGE, slope, damage);
}
//
// A_CPosRefire
//
// Line-of-sight checking for Chaingunner.
//
void A_CPosRefire(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
// keep firing unless target got out of sight
A_FaceTarget(actionargs);
// killough 12/98: Stop firing if a friend has gotten in the way
if(actor->flags & MF_FRIEND && P_HitFriend(actor))
{
P_SetMobjState(actor, actor->info->seestate);
return;
}
// killough 11/98: prevent refiring on friends continuously
if(P_Random(pr_cposrefire) < 40)
{
if(actor->target && (actor->flags & actor->target->flags & MF_FRIEND))
P_SetMobjState(actor, actor->info->seestate);
return;
}
if(!actor->target || actor->target->health <= 0 || !P_CheckSight(actor, actor->target))
{
P_SetMobjState(actor, actor->info->seestate);
}
}
//=============================================================================
//
// Basic Demons
//
//
// A_TroopAttack
//
// Imp attack.
//
void A_TroopAttack(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
if(!actor->target)
return;
A_FaceTarget(actionargs);
if(P_CheckMeleeRange(actor))
{
int damage;
S_StartSound(actor, sfx_claw);
damage = (P_Random(pr_troopattack) % 8 + 1) * 3;
P_DamageMobj(actor->target, actor, actor, damage, MOD_HIT);
}
else
{
// launch a missile
P_SpawnMissile(actor, actor->target, E_SafeThingType(MT_TROOPSHOT), actor->z + actor->info->missileheight);
}
}
//
// A_SargAttack
//
// Demon attack.
//
void A_SargAttack(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
if(!actor->target)
return;
A_FaceTarget(actionargs);
if(P_CheckMeleeRange(actor))
{
int damage = ((P_Random(pr_sargattack) % 10) + 1) * 4;
P_DamageMobj(actor->target, actor, actor, damage, MOD_HIT);
}
}
//
// A_SargAttack12
//
// DOOM 1.2 Demon attack
// haleyjd 07/29/14
//
void A_SargAttack12(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
int damage, mod, mul;
if(!actor->target)
return;
mod = E_ArgAsInt(actionargs->args, 0, 10);
mul = E_ArgAsInt(actionargs->args, 1, 4);
// ioanch: also pufftype
const char *pufftype = E_ArgAsString(actionargs->args, 2, nullptr);
A_FaceTarget(actionargs);
damage = ((P_Random(pr_sargattack) % mod) + 1) * mul;
P_LineAttack(actor, actor->angle, MELEERANGE, 0, damage, pufftype);
}
//
// A_HeadAttack
//
// Cacodemon attack.
//
void A_HeadAttack(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
if(!actor->target)
return;
A_FaceTarget(actionargs);
if(P_CheckMeleeRange(actor))
{
int damage = (P_Random(pr_headattack) % 6 + 1) * 10;
P_DamageMobj(actor->target, actor, actor, damage, MOD_HIT);
}
else
{
// launch a missile
P_SpawnMissile(actor, actor->target, E_SafeThingType(MT_HEADSHOT), actor->z + actor->info->missileheight);
}
}
//
// A_BruisAttack
//
// Baron of Hell attack.
//
void A_BruisAttack(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
if(!actor->target)
return;
if(P_CheckMeleeRange(actor))
{
int damage;
S_StartSound(actor, sfx_claw);
damage = (P_Random(pr_bruisattack) % 8 + 1) * 10;
P_DamageMobj(actor->target, actor, actor, damage, MOD_HIT);
}
else
{
// launch a missile
P_SpawnMissile(actor, actor->target, E_SafeThingType(MT_BRUISERSHOT), actor->z + actor->info->missileheight);
}
}
//=============================================================================
//
// Spider Actions
//
//
// A_SpidRefire
//
// Spider Mastermind line-of-sight checking.
//
void A_SpidRefire(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
// keep firing unless target got out of sight
A_FaceTarget(actionargs);
// killough 12/98: Stop firing if a friend has gotten in the way
if(actor->flags & MF_FRIEND && P_HitFriend(actor))
{
P_SetMobjState(actor, actor->info->seestate);
return;
}
if(P_Random(pr_spidrefire) < 10)
return;
// killough 11/98: prevent refiring on friends continuously
if(!actor->target || actor->target->health <= 0 || //
actor->flags & actor->target->flags & MF_FRIEND || //
!P_CheckSight(actor, actor->target))
{
P_SetMobjState(actor, actor->info->seestate);
}
}
//
// A_BspiAttack
//
// Arachnotron attack.
//
void A_BspiAttack(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
if(!actor->target)
return;
A_FaceTarget(actionargs);
// launch a missile
P_SpawnMissile(actor, actor->target, E_SafeThingType(MT_ARACHPLAZ), actor->z + actor->info->missileheight);
}
//
// A_BabyMetal
//
// Arachnotron chase w/sound.
//
void A_BabyMetal(actionargs_t *actionargs)
{
S_StartSound(actionargs->actor, sfx_bspwlk);
A_Chase(actionargs);
}
//=============================================================================
//
// Cyberdemon
//
//
// A_Hoof
//
// Cyberdemon chase pointer 1 with hoof sound.
//
void A_Hoof(actionargs_t *actionargs)
{
S_StartSound(actionargs->actor, sfx_hoof);
A_Chase(actionargs);
}
//
// A_Metal
//
// Cyberdemon chase pointer 2 with metal sound.
// Also used by Spider Mastermind.
//
void A_Metal(actionargs_t *actionargs)
{
S_StartSound(actionargs->actor, sfx_metal);
A_Chase(actionargs);
}
//
// A_CyberAttack
//
// Cyberdemon rocket attack.
//
void A_CyberAttack(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
if(!actor->target)
return;
A_FaceTarget(actionargs);
P_SpawnMissile(actor, actor->target, E_SafeThingType(MT_ROCKET), actor->z + actor->info->missileheight);
}
//=============================================================================
//
// Revenant
//
//
// A_SkelMissile
//
// Fire seeker missile.
//
void A_SkelMissile(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
Mobj *mo;
if(!actor->target)
return;
A_FaceTarget(actionargs);
actor->z += 16 * FRACUNIT; // so missile spawns higher
mo = P_SpawnMissile(actor, actor->target, E_SafeThingType(MT_TRACER), actor->z + actor->info->missileheight);
actor->z -= 16 * FRACUNIT; // back to normal
mo->x += mo->momx;
mo->y += mo->momy;
mo->backupPosition();
P_SetTarget<Mobj>(&mo->tracer, actor->target); // killough 11/98
}
static constexpr sangle_t TRACEANGLE = 0xc000000; /* killough 9/9/98: change to #define */
//
// A_Tracer
//
// (Accidentally?) randomized homing missile maintenance.
// ioanch 20151230: fixed to be portal-aware
//
void A_Tracer(actionargs_t *actionargs)
{
angle_t exact;
fixed_t dist;
fixed_t slope;
Mobj *actor = actionargs->actor;
Mobj *dest;
Mobj *th;
// killough 1/18/98: this is why some missiles do not have smoke
// and some do. Also, internal demos start at random gametics,
// thus the bug in which revenants cause internal demos to go out
// of sync.
//
// killough 3/6/98: fix revenant internal demo bug by subtracting
// levelstarttic from gametic.
//
// killough 9/29/98: use new "basetic" so that demos stay in sync
// during pauses and menu activations, while retaining old demo
// sync.
//
// leveltime would have been better to use to start with in Doom,
// but since old demos were recorded using gametic, we must stick
// with it, and improvise around it (using leveltime causes desync
// across levels).
if((gametic - basetic) & 3)
return;
// spawn a puff of smoke behind the rocket
P_SpawnPuff(actor->x, actor->y, actor->z, 0, 3, false, actor->target);
th = P_SpawnMobj(actor->x - actor->momx, //
actor->y - actor->momy, //
actor->z, E_SafeThingType(MT_SMOKE));
th->momz = FRACUNIT;
th->tics -= P_Random(pr_tracer) & 3;
if(th->tics < 1)
th->tics = 1;
// adjust direction
dest = actor->tracer;
if(!dest || dest->health <= 0)
return;
fixed_t dx = getThingX(actor, dest);
fixed_t dy = getThingY(actor, dest);
fixed_t dz = getThingZ(actor, dest);
// change angle
exact = P_PointToAngle(actor->x, actor->y, dx, dy);
if(exact != actor->angle)
{
if(exact - actor->angle > 0x80000000)
{
actor->angle -= TRACEANGLE;
if(exact - actor->angle < 0x80000000)
actor->angle = exact;
}
else
{
actor->angle += TRACEANGLE;
if(exact - actor->angle > 0x80000000)
actor->angle = exact;
}
}
exact = actor->angle >> ANGLETOFINESHIFT;
actor->momx = FixedMul(actor->info->speed, finecosine[exact]);
actor->momy = FixedMul(actor->info->speed, finesine[exact]);
// change slope
dist = P_AproxDistance(dx - actor->x, dy - actor->y);
dist = dist / actor->info->speed;
if(dist < 1)
dist = 1;
slope = (dz + 40 * FRACUNIT - actor->z) / dist;
if(slope < actor->momz)
actor->momz -= FRACUNIT / 8;
else
actor->momz += FRACUNIT / 8;
}
//
// A_SkelWhoosh
//
// Fist swing sound for Revenant.
//
void A_SkelWhoosh(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
if(!actor->target)
return;
A_FaceTarget(actionargs);
S_StartSound(actor, sfx_skeswg);
}
//
// A_SkelFist
//
// Revenant punch attack.
//
void A_SkelFist(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
if(!actor->target)
return;
A_FaceTarget(actionargs);
if(P_CheckMeleeRange(actor))
{
int damage = ((P_Random(pr_skelfist) % 10) + 1) * 6;
S_StartSound(actor, sfx_skepch);
P_DamageMobj(actor->target, actor, actor, damage, MOD_HIT);
}
}
//=============================================================================
//
// Arch-Vile
//
static struct vileContext_t
{
Mobj *corpsehit;
Mobj *vileobj;
fixed_t viletryx;
fixed_t viletryy;
int viletryradius;
} vileContext;
//
// Detect a corpse that could be raised.
//
static bool PIT_vileCheck(Mobj *thing, void *context)
{
int maxdist;
// ioanch 20160221: call functions
if(!P_ThingIsCorpse(thing))
return true;
maxdist = thing->info->radius + vileContext.viletryradius;
if(D_abs(getThingX(vileContext.vileobj, thing) - vileContext.viletryx) > maxdist ||
D_abs(getThingY(vileContext.vileobj, thing) - vileContext.viletryy) > maxdist)
return true; // not actually touching
// ioanch 20160108: since now it's portal aware, make sure that corpses
// from different group ids are seen. This restriction doesn't apply for
// single layer areas.
if(vileContext.vileobj->groupid != R_NOGROUP && thing->groupid != R_NOGROUP &&
vileContext.vileobj->groupid != thing->groupid && !P_CheckSight(vileContext.vileobj, thing))
{
return true;
}
// Check to see if the radius and height are zero. If they are // phares
// then this is a crushed monster that has been turned into a // |
// gib. One of the options may be to ignore this guy. // V
// Option 1: the original, buggy method, -> ghost (compatibility)
// Option 2: resurrect the monster, but not as a ghost
// Option 3: ignore the gib
// if (Option3) // ^
// if ((thing->height == 0) && (thing->radius == 0)) // |
// return true; // phares
vileContext.corpsehit = thing;
// Exit (return false) if the function returns true!
return !P_CheckCorpseRaiseSpace(vileContext.corpsehit);
}
struct healContext_t
{
actionargs_t *actionargs;
int healstate;
int healsound;
};
//
// Check for ressurecting a body (split out from A_VileChase)
//
bool P_HealCorpse(actionargs_t *actionargs, const int radius, const int healstate, const int healsound)
{
Mobj *actor = actionargs->actor;
if(actor->movedir != DI_NODIR)
{
healContext_t healContext = {};
// check for corpses to raise
vileContext.viletryx = actor->x + actor->info->speed * xspeed[actor->movedir];
vileContext.viletryy = actor->y + actor->info->speed * yspeed[actor->movedir];
// ioanch 20160108: make resurrection portal aware
fixed_t bbox[4];
bbox[BOXLEFT] = vileContext.viletryx - MAXRADIUS * 2;
bbox[BOXBOTTOM] = vileContext.viletryy - MAXRADIUS * 2;
bbox[BOXRIGHT] = vileContext.viletryx + MAXRADIUS * 2;
bbox[BOXTOP] = vileContext.viletryy + MAXRADIUS * 2;
vileContext.vileobj = actor;
vileContext.viletryradius = radius;
healContext.actionargs = actionargs;
healContext.healstate = healstate;
healContext.healsound = healsound;
auto healVisit = [](int x, int y, int groupid, void *data) -> bool {
// get the variables back
auto healContext = static_cast<healContext_t *>(data);
actionargs_t *actionargs = healContext->actionargs;
int healstate = healContext->healstate;
int healsound = healContext->healsound;
Mobj *actor = actionargs->actor;
if(!P_BlockThingsIterator(x, y, groupid, PIT_vileCheck))
{
// got one!
Mobj *temp = actor->target;
actor->target = vileContext.corpsehit;
A_FaceTarget(actionargs);
actor->target = temp;
P_SetMobjState(actor, healstate);
// ioanch 20160221: call function
P_RaiseCorpse(vileContext.corpsehit, actor, healsound);
return false;
}
return true;
};
// if the block returned false, a thing was successfully raised
return !P_TransPortalBlockWalker(bbox, actor->groupid, true, &healContext, healVisit);
}
return false;
}
//
// Check for ressurecting a body
//
void A_VileChase(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
int vileType = E_SafeThingType(MT_VILE);
int healStateNum;
// ioanch 20160220: allow custom state
const state_t *healState = E_GetStateForMobjInfo(actor->info, METASTATE_HEAL);
if(healState && healState->index != NullStateNum)
healStateNum = healState->index;
else
healStateNum = S_VILE_HEAL1; // Doom behaviour
if(!P_HealCorpse(actionargs, mobjinfo[vileType]->radius, healStateNum, sfx_slop))
A_Chase(actionargs); // Return to normal attack.
}
//
// A_VileStart
//
// Play vilatk sound.
//
void A_VileStart(actionargs_t *actionargs)
{
S_StartSound(actionargs->actor, sfx_vilatk);
}
//
// A_Fire
//
// Keep fire in front of player unless out of sight
//
void A_Fire(actionargs_t *actionargs)
{
angle_t an;
Mobj *actor = actionargs->actor;
Mobj *dest = actor->tracer;
if(!dest)
return;
// don't move it if the vile lost sight
if(!P_CheckSight(actor->target, dest))
return;
an = dest->angle >> ANGLETOFINESHIFT;
P_UnsetThingPosition(actor);
// IOANCH 20160106: correct line portal behaviour
v2fixed_t pos =
P_LinePortalCrossing(*dest, FixedMul(24 * FRACUNIT, finecosine[an]), FixedMul(24 * FRACUNIT, finesine[an]));
actor->x = pos.x;
actor->y = pos.y;
actor->z = dest->z;
actor->backupPosition();
P_SetThingPosition(actor);
}
//
// A_StartFire
//
// Start vile fire effect. This never does anything in vanilla DOOM however,
// because it is only in the fire's spawn state, and the pointer in any
// object's spawnstate is never executed the first time it spawns.
//
void A_StartFire(actionargs_t *actionargs)
{
S_StartSound(actionargs->actor, sfx_flamst);
A_Fire(actionargs);
}
//
// A_FireCrackle
//
// Play fire crackling sound.
//
void A_FireCrackle(actionargs_t *actionargs)
{
S_StartSound(actionargs->actor, sfx_flame);
A_Fire(actionargs);
}
//
// A_VileTarget
//
// Spawn the hellfire
//
// args[0] -- thing to spawn (default: MT_FIRE)
//
void A_VileTarget(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
Mobj *fog;
arglist_t *args = actionargs->args;
int thingnum = E_ArgAsThingNumG0(args, 0);
if(!actor->target)
return;
// validate thingtype
if(thingnum < 0)
thingnum = E_SafeThingType(MT_FIRE);
A_FaceTarget(actionargs);
// killough 12/98: fix Vile fog coordinates
fog = P_SpawnMobj(actor->target->x, demo_version < 203 ? actor->target->x : actor->target->y, actor->target->z,
thingnum);
P_SetTarget<Mobj>(&actor->tracer, fog); // killough 11/98
P_SetTarget<Mobj>(&fog->target, actor);
P_SetTarget<Mobj>(&fog->tracer, actor->target);
actionargs_t fogaction;
fogaction.actiontype = actionargs_t::MOBJFRAME;
fogaction.actor = fog;
fogaction.args = ESAFEARGS(fog);
fogaction.pspr = nullptr;
A_Fire(&fogaction);
}
//
// A_VileAttack
//
// Arch-vile attack.
//
// args[0] -- sound (default: sfx_barexp)
// args[1] -- initial damage (default: 20)
// args[2] -- blast damage (default: 70)
// args[3] -- blast radius (default: 70)
// args[4] -- thrust factor (default: 1.0)
// args[5] -- damage type for initial hit (default: actor->info->mod)
// args[6] -- damage type for blast (default: actor->info->mod)
//
void A_VileAttack(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
Mobj *fire;
arglist_t *args = actionargs->args;
soundparams_t params{};
int an;
int initialdamage;
int blastdamage;
int blastradius;
fixed_t thrustfactor;
int initialdmgtype;
int blastdmgtype;
if(!actor->target)
return;
A_FaceTarget(actionargs);
if(!P_CheckSight(actor, actor->target))
return;
// Get parameters with defaults matching original behavior
params.sfx = E_ArgAsSound(args, 0);
initialdamage = E_ArgAsInt(args, 1, 20);
blastdamage = E_ArgAsInt(args, 2, 70);
blastradius = E_ArgAsInt(args, 3, 70);
thrustfactor = E_ArgAsFixed(args, 4, FRACUNIT);
initialdmgtype = E_ArgAsDamageType(args, 5, actor->info->mod)->num;
blastdmgtype = E_ArgAsDamageType(args, 6, actor->info->mod)->num;
// Play sound - use default if none specified
if(params.sfx)
S_StartSfxInfo(params.setNormalDefaults(actor));
else
S_StartSound(actor, sfx_barexp);
// Deal initial damage and apply thrust
P_DamageMobj(actor->target, actor, actor, initialdamage, initialdmgtype);
actor->target->momz = 1000 * thrustfactor / actor->target->info->mass;
an = actor->angle >> ANGLETOFINESHIFT;
fire = actor->tracer;
if(!fire)
return;
// move the fire between the vile and the player
// ioanch 20160106: correct fire position based on portals
v2fixed_t pos = P_LinePortalCrossing(*actor->target, -FixedMul(24 * FRACUNIT, finecosine[an]),
-FixedMul(24 * FRACUNIT, finesine[an]));
fire->x = pos.x;
fire->y = pos.y;
// ioanch: set the correct group ID now
if(full_demo_version >= make_full_version(340, 48))
fire->groupid = R_PointInSubsector(pos)->sector->groupid;
P_RadiusAttack(fire, actor, blastdamage, blastradius, blastdmgtype, 0);
}
//=============================================================================
//
// Mancubus
//
// Mancubus attack,
// firing three missiles (bruisers)
// in three different directions?
// Doesn't look like it. - haleyjd: weird comment #345932
static constexpr sangle_t FATSPREAD = ANG90 / 8;
//
// A_FatRaise
//
// Prepare to attack.
//
void A_FatRaise(actionargs_t *actionargs)
{
A_FaceTarget(actionargs);
S_StartSound(actionargs->actor, sfx_manatk);
}
//
// A_FatAttack1
//
// Mancubus attack 1.
// * args[0] = type to spawn
//
void A_FatAttack1(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
Mobj *mo;
int an;
fixed_t z = actor->z + actor->info->missileheight;
int thingType = E_ArgAsThingNumG0(actionargs->args, 0);
if(thingType < 0)
thingType = E_SafeThingType(MT_FATSHOT);
// haleyjd: no crashing
if(!actor->target)
return;
A_FaceTarget(actionargs);
// Change direction to ...
actor->angle += FATSPREAD;
P_SpawnMissile(actor, actor->target, thingType, z);
mo = P_SpawnMissile(actor, actor->target, thingType, z);
mo->angle += FATSPREAD;
an = mo->angle >> ANGLETOFINESHIFT;
mo->momx = FixedMul(mo->info->speed, finecosine[an]);
mo->momy = FixedMul(mo->info->speed, finesine[an]);
}
//
// A_FatAttack2
//
// Mancubus attack 2.
// * args[0] = type to spawn
//
void A_FatAttack2(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
Mobj *mo;
int an;
fixed_t z = actor->z + actor->info->missileheight;
int thingType = E_ArgAsThingNumG0(actionargs->args, 0);
if(thingType < 0)
thingType = E_SafeThingType(MT_FATSHOT);
// haleyjd: no crashing
if(!actor->target)
return;
A_FaceTarget(actionargs);
// Now here choose opposite deviation.
actor->angle -= FATSPREAD;
P_SpawnMissile(actor, actor->target, thingType, z);
mo = P_SpawnMissile(actor, actor->target, thingType, z);
mo->angle -= FATSPREAD * 2;
an = mo->angle >> ANGLETOFINESHIFT;
mo->momx = FixedMul(mo->info->speed, finecosine[an]);
mo->momy = FixedMul(mo->info->speed, finesine[an]);
}
//
// A_FatAttack3
//
// Mancubus attack 3.
// * args[0] = type to spawn
//
void A_FatAttack3(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
Mobj *mo;
int an;
fixed_t z = actor->z + actor->info->missileheight;
int thingType = E_ArgAsThingNumG0(actionargs->args, 0);
if(thingType < 0)
thingType = E_SafeThingType(MT_FATSHOT);
// haleyjd: no crashing
if(!actor->target)
return;
A_FaceTarget(actionargs);
mo = P_SpawnMissile(actor, actor->target, thingType, z);
mo->angle -= FATSPREAD / 2;
an = mo->angle >> ANGLETOFINESHIFT;
mo->momx = FixedMul(mo->info->speed, finecosine[an]);
mo->momy = FixedMul(mo->info->speed, finesine[an]);
mo = P_SpawnMissile(actor, actor->target, thingType, z);
mo->angle += FATSPREAD / 2;
an = mo->angle >> ANGLETOFINESHIFT;
mo->momx = FixedMul(mo->info->speed, finecosine[an]);
mo->momy = FixedMul(mo->info->speed, finesine[an]);
}
//=============================================================================
//
// Lost Soul and Pain Elemental
//
constexpr fixed_t SKULLSPEED = 20 * FRACUNIT;
//
// A_SkullAttack
//
// Fly at the player like a missile.
//
void A_SkullAttack(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
if(!actor->target)
return;
S_StartSound(actor, actor->info->attacksound);
// haleyjd 08/07/04: use new P_SkullFly function
P_SkullFly(actor, SKULLSPEED, false);
}
//
// A_BetaSkullAttack()
//
// killough 10/98: this emulates the beta version's lost soul attacks
//
void A_BetaSkullAttack(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
int damage;
// haleyjd: changed to check if objects are the SAME type, not
// for hard-coded lost soul
if(!actor->target || actor->target->type == actor->type)
return;
S_StartSound(actor, actor->info->attacksound);
A_FaceTarget(actionargs);
damage = (P_Random(pr_skullfly) % 8 + 1) * actor->damage;
P_DamageMobj(actor->target, actor, actor, damage, actor->info->mod);
}
//
// A_Stop
//
// Remove all momentum from an object.
// POINTER-TODO: Move to a_common?
//
void A_Stop(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
actor->momx = actor->momy = actor->momz = 0;
}
enum painattackflags_e : unsigned int
{
PAF_NOSKULLATTACK = 0x00000001,
PAF_AIMFACING = 0x00000002,
PAF_NOTARGET = 0x00000004,
};
//
// Spawn a lost soul and launch it at the target
//
static void A_painShootSkull(Mobj *actor, const angle_t angle, int thingType, const unsigned int flags = 0,
int count = -1)
{
fixed_t x, y, z;
Mobj *newmobj;
angle_t an;
int prestep;
// The original code checked for 20 skulls on the level, // phares
// and wouldn't spit another one if there were. If not in // phares
// compatibility mode, we remove the limit. // phares
if((getComp(comp_pain) && count < 0) || count > 0) // killough 10/98: compatibility-optioned
{
// count total number of skulls currently on the level
if(count < 0)
count = 20;
else
count--;
Thinker *th;
for(th = thinkercap.next; th != &thinkercap; th = th->next)
{
Mobj *mo;
if((mo = thinker_cast<Mobj *>(th)) && mo->type == thingType)
{
if(--count < 0) // killough 8/29/98: early exit
return;
}
}
}
// okay, there's room for another one
an = angle >> ANGLETOFINESHIFT;
prestep = 4 * FRACUNIT + 3 * (actor->info->radius + mobjinfo[thingType]->radius) / 2;
// ioanch 20160107: spawn at the correct position if there's a line portal
// between monster and intended position.
// Also keep track of the "relative" position: the one without portal trans-
// lation. Needed for Check_Sides
v2fixed_t relpos = { actor->x + FixedMul(prestep, finecosine[an]), actor->y + FixedMul(prestep, finesine[an]) };
v2fixed_t pos = P_LinePortalCrossing(*actor, relpos - v2fixed_t{ actor->x, actor->y });
x = pos.x;
y = pos.y;
z = actor->z + 8 * FRACUNIT;
if(getComp(comp_skull)) // killough 10/98: compatibility-optioned
newmobj = P_SpawnMobj(x, y, z, thingType); // phares
else // V
{
// Check whether the Lost Soul is being fired through a 1-sided
// wall or an impassible line, or a "monsters can't cross" line.
// If it is, then we don't allow the spawn. This is a bug fix,
// but it should be considered an enhancement, since it may
// disturb existing demos, so don't do it in compatibility mode.
// ioanch 20160107: check sides against the non-translated position. This
// way the two coordinates will be in valid range and it will only check
// sides against the passable portal line
if(Check_Sides(actor, relpos.x, relpos.y, thingType))
return;
newmobj = P_SpawnMobj(x, y, z, thingType);
// Check to see if the new Lost Soul's z value is above the
// ceiling of its new sector, or below the floor. If so, kill it.
// ioanch 20160107: check against the floor or ceiling sector behind any
// portals
if(!P_CheckFloorCeilingForSpawning(*newmobj))
{
// kill it immediately
P_DamageMobj(newmobj, actor, actor, GOD_BREACH_DAMAGE, MOD_UNKNOWN);
return; // ^
} // |
} // phares
// killough 7/20/98: PEs shoot lost souls with the same friendliness
P_transferFriendship(*newmobj, *actor);
// killough 8/29/98: add to appropriate thread
newmobj->updateThinker();
// Check for movements.
// killough 3/15/98: don't jump over dropoffs:
if(!P_TryMove(newmobj, newmobj->x, newmobj->y, false))
{
// kill it immediately
P_DamageMobj(newmobj, actor, actor, GOD_BREACH_DAMAGE, MOD_UNKNOWN);
return;
}
if(!(flags & PAF_NOTARGET))
P_SetTarget<Mobj>(&newmobj->target, actor->target);
if(!(flags & PAF_NOSKULLATTACK))
{
actionargs_t skullaction;
skullaction.actiontype = actionargs_t::MOBJFRAME;
skullaction.actor = newmobj;
skullaction.args = ESAFEARGS(newmobj);
skullaction.pspr = nullptr;
A_SkullAttack(&skullaction);
}
}
static dehflags_t painattack_flaglist[] = {
{ "NOSKULLATTACK", PAF_NOSKULLATTACK },
{ "AIMFACING", PAF_AIMFACING },
{ "NOTARGET", PAF_NOTARGET },
{ nullptr, 0 }
};
static dehflagset_t painattack_flagset = {
painattack_flaglist, // flaglist
0, // mode
};
//
// Spawn a thing and launch it at the target
// * args[0] = type to spawn
// * args[1] = angle to add to spawned thing
// * args[2] = flags
// * args[3] = maximum amount allowed on map (infinite if 0, 21 if negative)
//
void A_PainAttack(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
if(!actor->target)
return;
int thingType = E_ArgAsThingNumG0(actionargs->args, 0);
if(thingType < 0)
thingType = E_SafeThingType(MT_SKULL);
const angle_t angle = FixedToAngle(E_ArgAsFixed(actionargs->args, 1, 0));
const unsigned int flags = E_ArgAsFlags(actionargs->args, 2, &painattack_flagset);
const int count = E_ArgAsInt(actionargs->args, 3, -1);
if(!(flags & PAF_NOTARGET))
A_FaceTarget(actionargs);
A_painShootSkull(actor, actor->angle + angle, thingType, flags, count);
}
//
// Normal fall logic plus 3 things spawn.
// * args[0] = type to spawn
//
void A_PainDie(actionargs_t *actionargs)
{
Mobj *actor = actionargs->actor;
int thingType = E_ArgAsThingNumG0(actionargs->args, 0);
if(thingType < 0)
thingType = E_SafeThingType(MT_SKULL);
A_Fall(actionargs);
A_painShootSkull(actor, actor->angle + ANG90, thingType);
A_painShootSkull(actor, actor->angle + ANG180, thingType);
A_painShootSkull(actor, actor->angle + ANG270, thingType);
}
//=============================================================================
//
// Special Death Effects
//
struct boss_spec_t
{
unsigned int thing_flag;
unsigned int level_flag;
};
static constexpr int NUM_BOSS_SPECS = 7;
static boss_spec_t boss_specs[NUM_BOSS_SPECS] = {
{ MF2_MAP07BOSS1, BSPEC_MAP07_1 },
{ MF2_MAP07BOSS2, BSPEC_MAP07_2 },
{ MF2_E1M8BOSS, BSPEC_E1M8 },
{ MF2_E2M8BOSS, BSPEC_E2M8 },
{ MF2_E3M8BOSS, BSPEC_E3M8 },
{ MF2_E4M6BOSS, BSPEC_E4M6 },
{ MF2_E4M8BOSS, BSPEC_E4M8 },
};
//
// A_BossDeath
//
// Possibly trigger special effects if on boss level
//
// haleyjd: enhanced to allow user specification of the thing types
// allowed to trigger each special effect.
// haleyjd: 03/14/05 -- enhanced to allow actions on any map.
//
void A_BossDeath(actionargs_t *actionargs)
{
Mobj *mo = actionargs->actor;
int i;
player_t *thePlayer = nullptr;
// make sure there is a player alive for victory
for(i = 0; i < MAXPLAYERS; i++)
{
if(playeringame[i] && players[i].health > 0)
{
thePlayer = players + i;
break;
}
}
// no one left alive, so do not end game
if(i == MAXPLAYERS || !thePlayer)
return;
// Now check the UMAPINFO bossactions
P_CheckCustomBossActions(*mo, *thePlayer);
for(boss_spec_t &boss_spec : boss_specs)
{
// to activate a special, the thing must be a boss that triggers
// it, and the map must have the special enabled.
if((mo->flags2 & boss_spec.thing_flag) && (LevelInfo.bossSpecs & boss_spec.level_flag))
{
// scan the remaining thinkers to see if all bosses are dead
for(Thinker *th = thinkercap.next; th != &thinkercap; th = th->next)
{
Mobj *mo2;
if((mo2 = thinker_cast<Mobj *>(th)))
{
if(mo2 != mo && (mo2->flags2 & boss_spec.thing_flag) && mo2->health > 0)
return; // other boss not dead
}
}
// victory!
switch(boss_spec.level_flag)
{
case BSPEC_E1M8:
case BSPEC_E4M8:
case BSPEC_MAP07_1:
// lower floors tagged 666 to lowest neighbor
EV_DoFloor(nullptr, 666, lowerFloorToLowest);
break;
case BSPEC_MAP07_2:
// raise floors tagged 667 by shortest lower texture
EV_DoFloor(nullptr, 667, raiseToTexture);
break;
case BSPEC_E2M8:
case BSPEC_E3M8:
// exit map -- no use processing any further after this
G_ExitLevel();
return;
case BSPEC_E4M6:
// open sectors tagged 666 as blazing doors
EV_DoDoor(666, blazeOpen);
break;
default: //
break;
} // end switch
} // end if
} // end for
}
//
// A_KeenDie
//
// DOOM II special, map 32.
// Uses special tag 666.
//
void A_KeenDie(actionargs_t *actionargs)
{
Mobj *mo = actionargs->actor;
Thinker *th;
A_Fall(actionargs);
// scan the remaining thinkers to see if all Keens are dead
for(th = thinkercap.next; th != &thinkercap; th = th->next)
{
Mobj *mo2;
if((mo2 = thinker_cast<Mobj *>(th)))
{
if(mo2 != mo && mo2->type == mo->type && mo2->health > 0)
return; // other Keen not dead
}
}
EV_DoDoor(666, doorOpen);
}
//=============================================================================
//
// DOOM II Boss Brain
//
// "To win the game, you must kill me, John Romero"
//
// killough 2/7/98: Remove limit on icon landings:
// haleyjd 07/30/04: use new MobjCollection
static MobjCollection braintargets;
struct brain_s brain; // killough 3/26/98: global state of boss brain
// killough 3/26/98: initialize icon landings at level startup,
// rather than at boss wakeup, to prevent savegame-related crashes
void P_SpawnBrainTargets() // killough 3/26/98: renamed old function
{
// find all the target spots
braintargets.mobjType = "BossSpawnSpot";
braintargets.makeEmpty();
brain.easy = 0; // killough 3/26/98: always init easy to 0
braintargets.collectThings();
}
// haleyjd 07/30/04: P_CollectThings moved to p_mobj.c
//
// A_BrainAwake
//
// Awaken the Boss Brain spawn shooter.
//
void A_BrainAwake(actionargs_t *actionargs)
{
S_StartSound(nullptr, sfx_bossit); // killough 3/26/98: only generates sound now
}
//
// A_BrainPain
//
// Called when the Romero head is injured.
//
void A_BrainPain(actionargs_t *actionargs)
{
S_StartSound(nullptr, sfx_bospn);
}
//
// A_BrainScream
//
// Romero head death effects.
//
void A_BrainScream(actionargs_t *actionargs)
{
Mobj *mo = actionargs->actor;
int x;
int rocketType = E_SafeThingType(MT_ROCKET);
for(x = mo->x - 196 * FRACUNIT; x < mo->x + 320 * FRACUNIT; x += FRACUNIT * 8)
{
int y = mo->y - 320 * FRACUNIT;
int z = 128 + P_Random(pr_brainscream) * 2 * FRACUNIT;
Mobj *th = P_SpawnMobj(x, y, z, rocketType);
// haleyjd 02/21/05: disable particle events/effects for this thing
th->intflags |= MIF_NOPTCLEVTS;
th->effects = 0;
th->momz = P_Random(pr_brainscream) * 512;
P_SetMobjState(th, E_SafeState(S_BRAINEXPLODE1));
th->tics -= P_Random(pr_brainscream) & 7;
if(th->tics < 1)
th->tics = 1;
}
S_StartSound(nullptr, sfx_bosdth);
}
//
// A_BrainExplode
//
// More Romero head death effects.
//
void A_BrainExplode(actionargs_t *actionargs)
{
Mobj *mo = actionargs->actor;
// haleyjd 08/05/04: use new function
int x = mo->x + P_SubRandom(pr_brainexp) * 2048;
int y = mo->y;
int z = 128 + P_Random(pr_brainexp) * 2 * FRACUNIT;
Mobj *th = P_SpawnMobj(x, y, z, E_SafeThingType(MT_ROCKET));
th->momz = P_Random(pr_brainexp) * 512;
// haleyjd 02/21/05: disable particle events/effects for this thing
th->intflags |= MIF_NOPTCLEVTS;
th->effects = 0;
P_SetMobjState(th, E_SafeState(S_BRAINEXPLODE1));
th->tics -= P_Random(pr_brainexp) & 7;
if(th->tics < 1)
th->tics = 1;
}
//
// A_BrainDie
//
// Romero head final death pointer.
//
void A_BrainDie(actionargs_t *actionargs)
{
G_ExitLevel();
}
//
// A_BrainSpit
//
// Spawn cube shooter attack.
//
void A_BrainSpit(actionargs_t *actionargs)
{
Mobj *mo = actionargs->actor;
Mobj *targ, *newmobj;
int SpawnShotType = E_SafeThingType(MT_SPAWNSHOT);
// killough 4/1/98: ignore if no targets
if(braintargets.isEmpty())
return;
brain.easy ^= 1; // killough 3/26/98: use brain struct
if(gameskill <= sk_easy && !brain.easy)
return;
// shoot a cube at current target
targ = braintargets.wrapIterator();
// spawn brain missile
newmobj = P_SpawnMissile(mo, targ, SpawnShotType, mo->z + mo->info->missileheight);
P_SetTarget<Mobj>(&newmobj->target, targ);
if(!newmobj->state->tics)
{
newmobj->remove();
doom_printf(FC_ERROR "BrainSpit: invalid 0 tic spawn state");
return;
}
newmobj->reactiontime = (int16_t)(((targ->y - mo->y) / newmobj->momy) / newmobj->state->tics);
// killough 7/18/98: brain friendliness is transferred
P_transferFriendship(*newmobj, *mo);
// killough 8/29/98: add to appropriate thread
newmobj->updateThinker();
S_StartSound(nullptr, sfx_bospit);
}
void A_SpawnFly(actionargs_t *actionargs);
//
// A_SpawnSound
//
// travelling cube sound
//
void A_SpawnSound(actionargs_t *actionargs)
{
S_StartSound(actionargs->actor, sfx_boscub);
A_SpawnFly(actionargs);
}
// haleyjd 07/13/03: editable boss brain spawn types
// schepe: removed 11-type limit
int NumBossTypes;
int *BossSpawnTypes;
int *BossSpawnProbs;
//
// A_SpawnFly
//
// Called by spawn cubes in flight.
//
void A_SpawnFly(actionargs_t *actionargs)
{
int i; // schepe
int r;
mobjtype_t type = 0;
int fireType = E_SafeThingType(MT_SPAWNFIRE);
Mobj *mo = actionargs->actor;
Mobj *fog;
Mobj *targ;
Mobj *newmobj; // killough 8/9/98
// haleyjd 05/31/06: allow 0 boss types
if(NumBossTypes == 0)
return;
if(--mo->reactiontime)
return; // still flying
// haleyjd: do not crash if target is null
if(!(targ = mo->target))
return;
// First spawn teleport fog.
fog = P_SpawnMobj(targ->x, targ->y, targ->z, fireType);
S_StartSound(fog, sfx_telept);
// Randomly select monster to spawn.
r = P_Random(pr_spawnfly);
// Probability distribution (kind of :), decreasing likelihood.
// schepe:
for(i = 0; i < NumBossTypes; ++i)
{
if(r < BossSpawnProbs[i])
{
type = BossSpawnTypes[i];
break;
}
}
newmobj = P_SpawnMobj(targ->x, targ->y, targ->z, type);
// killough 7/18/98: brain friendliness is transferred
P_transferFriendship(*newmobj, *mo);
// killough 8/29/98: add to appropriate thread
newmobj->updateThinker();
if(P_LookForTargets(newmobj, true)) // killough 9/4/98
P_SetMobjState(newmobj, newmobj->info->seestate);
// telefrag anything in this spot
P_TeleportMove(newmobj, newmobj->x, newmobj->y, TELEMOVE_BOSS); // killough 8/9/98
// remove self (i.e., cube).
mo->remove();
}
// EOF
| 0 | 0.846571 | 1 | 0.846571 | game-dev | MEDIA | 0.996862 | game-dev | 0.565864 | 1 | 0.565864 |
markol/machines | 2,382 | include/libdev/machlog/opadsupc.hpp | /*
* O P S U P C O N . H P P
* (c) Charybdis Limited, 1998. All Rights Reserved
*/
/*
MachLogAdminSuperConstructOperation
This class takes an actor, a vector of constructions and one of 4 valid operation types,
and makes that actor perform that operation on each construction in turn, executing
suboperations in sequence.
*/
#ifndef _MACHLOG_OPADSUPC_HPP
#define _MACHLOG_OPADSUPC_HPP
#include "base/base.hpp"
#include "phys/phys.hpp"
#include "ctl/pvector.hpp"
#include "mathex/point3d.hpp"
#include "mathex/point2d.hpp"
#include "machlog/operatio.hpp"
class MachLogAdministrator;
class MachLogConstructor;
class MachLogConstruction;
// orthodox canonical (revoked)
class MachLogAdminSuperConstructOperation
: public MachLogOperation
{
typedef ctl_pvector< MachLogConstruction > Constructions;
typedef ctl_pvector< MachLogConstructor > Constructors;
public:
MachLogAdminSuperConstructOperation( MachLogAdministrator * pActor, const Constructions& constructionArray, MachLogOperation::OperationType opType );
virtual ~MachLogAdminSuperConstructOperation();
virtual bool beNotified( W4dSubject* pSubject,
W4dSubject::NotificationEvent event, int clientData );
PER_MEMBER_PERSISTENT_VIRTUAL( MachLogAdminSuperConstructOperation );
PER_FRIEND_READ_WRITE( MachLogAdminSuperConstructOperation );
protected:
virtual bool doStart();
virtual void doFinish();
virtual bool doIsFinished() const;
virtual void doOutputOperator( ostream& ) const;
virtual PhysRelativeTime doUpdate( );
virtual bool doBeInterrupted();
private:
// Operations deliberately revoked
MachLogAdminSuperConstructOperation( const MachLogAdminSuperConstructOperation& );
MachLogAdminSuperConstructOperation& operator =( const MachLogAdminSuperConstructOperation& );
bool operator ==( const MachLogAdminSuperConstructOperation& );
void addReservationToAllConstructions();
void cancelReservationFromAllConstructions();
int nConstructorsRemaining() const;
MachLogAdministrator * pActor_;
Constructions constructionArray_;
MachLogOperation::OperationType opType_;
MachLogConstruction * pTargetConstruction_;
PhysAbsoluteTime lastUpdateTime_;
};
PER_DECLARE_PERSISTENT( MachLogAdminSuperConstructOperation );
#endif
/* End OPCONSTR.HPP *************************************************/
| 0 | 0.63149 | 1 | 0.63149 | game-dev | MEDIA | 0.644877 | game-dev | 0.558381 | 1 | 0.558381 |
ShadowApex/SpaceBase-DF9 | 34,346 | Data/Scripts/EnvObjects/EnvObjectData.lua | local Character=require('CharacterConstants')
local EnvObjectData = {}
local World=require('WorldConstants')
EnvObjectData.tMenus=
{
ALL={ 'Door','Airlock','HeavyDoor','FirePanel','EmergencyAlarm',},
POWER={ 'Generator', 'GeneratorLevel2', 'GeneratorLevel3', 'GeneratorLevel4' },
LIFESUPPORT={'AirScrubber', 'OxygenRecycler', 'OxygenRecyclerLevel2', 'OxygenRecyclerLevel3', 'OxygenRecyclerLevel4'},
RESIDENCE={},
GARDEN={},
PUB={'Bar','Fridge','FridgeLvl2','Stove','StandingTable','BurgerSign','PizzaSign','FriesSign',},
AIRLOCK={},
REFINERY={},
FITNESS={},
INFIRMARY={},
RESEARCH={},
COMMAND={},
}
EnvObjectData.tObjects=
{
Spawner=
{
width=1,
height=1,
margin=0,
customClass='EnvObjects.Spawner',
customInspector='Spawner',
spriteName='spawner',
showInObjectMenu=false,
noRoom=true,
bCanBuildInSpace=true,
},
SpaceshipEngine=
{
spriteName='ShipEngine',
friendlyNameLinecode='PROPSX094TEXT',
description='PROPSX095TEXT',
bCanBuildInSpace=true,
noRoom=true,
margin=1, -- this margin is a hack: it's to indicate where it will provide power.
width=2,
height=3,
noRoom=true,
bBlocksPathing=true,
clickSound = 'fusionreactor',
showInObjectMenu=false,
matterCost=200,
portrait = 'Env_SeedPod',
nPowerOutput = 250,
nSabotageDuration = 30,
},
DockPoint=
{
width=1,
height=1,
margin=0,
customInspector='Generic',
spriteName='dockpoint',
showInObjectMenu=false,
noRoom=true,
bCanBuildInSpace=true,
},
Door=
{
layer='worldWall',
friendlyNameLinecode='PROPSX019TEXT',
description='PROPSX020TEXT',
door=true,
noRoom=true,
customInspector='Door',
width=1,
height=1,
margin=0,
decayPerSecond=0.01,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
-- spriteName='door_closed',
-- spriteSheetPath='Environments/Tiles/Wall',
customClass='EnvObjects.Door',
commandSpriteName='door_closed',
commandSpriteNameFlipped='door_closed_flip',
commandSpriteSheet='Environments/Tiles/Wall',
clickSound = 'spacedoor',
showInObjectMenu=true,
placeSound = 'placedoor',
portrait = 'Env_Door',
sidebarIcon = 'icon_door',
autoFlip=true,
matterCost=12,
sFlavorText='OBFLAV018TEXT',
},
HeavyDoor=
{
layer='worldWall',
friendlyNameLinecode='PROPSX064TEXT',
description='PROPSX065TEXT',
door=true,
noRoom=true,
customInspector='Door',
width=1,
height=1,
margin=0,
decayPerSecond=0.01,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
-- spriteName='door_closed',
-- spriteSheetPath='Environments/Tiles/Wall',
customClass='EnvObjects.HeavyDoor',
commandSpriteName='door_heavy_closed',
commandSpriteNameFlipped='door_closed_flip',
commandSpriteSheet='Environments/Tiles/Wall',
clickSound = 'spacedoor',
showInObjectMenu=true,
placeSound = 'placedoor',
portrait = 'Env_HeavyDoor',
sidebarIcon = 'icon_heavydoor',
researchPrereq='DoorLevel2',
sFunctionality='Door',
autoFlip=true,
matterCost=20,
sFlavorText = 'OBFLAV025TEXT',
},
Airlock=
{
layer='worldWall',
friendlyNameLinecode='PROPSX021TEXT',
description='PROPSX022TEXT',
menuZoneName='AIRLOCK',
door=true,
noRoom=true,
customInspector='Door',
width=2,
height=1,
margin=0,
decayPerSecond=0.01,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
-- spriteName='airlock_door_closed',
-- spriteSheetPath='Environments/Tiles/Wall',
customClass='EnvObjects.Airlock',
commandSpriteName='airlock_door_closed',
commandSpriteNameFlipped='airlock_door_closed_flip',
commandSpriteSheet='Environments/Tiles/Wall',
clickSound = '',
showInObjectMenu = true,
placeSound = 'placeairlock',
sidebarIcon = 'icon_airlock_door',
portrait = 'Env_Airlock_Door',
autoFlip=true,
matterCost=15,
sFlavorText = 'OBFLAV016TEXT',
},
Generator=
{
spriteName='generator',
zoneName='POWER',
friendlyNameLinecode='ZONEUI015TEXT',
description='ZONEUI051TEXT',
width=2,
height=2,
margin=2,
decayPerSecond=0.03,
explodeOnFailure=true,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=true,
clickSound = 'fusionreactor',
ambientSound = 'reactorloop',
portrait = 'Env_Power_Generator',
placeSound = 'placereactor',
sidebarIcon = 'icon_generator',
matterCost=200,
nPowerOutput = 1000,
nSabotageDuration = 30,
bCanDeactivate = true,
sFlavorText = 'OBFLAV019TEXT',
},
GeneratorLevel2=
{
spriteName='generator2',
zoneName='POWER',
friendlyNameLinecode='PROPSX096TEXT',
description='PROPSX097TEXT',
width=2,
height=2,
margin=2,
decayPerSecond=0.04,
explodeOnFailure=true,
researchPrereq = 'GeneratorLevel2',
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=true,
clickSound = 'fusionreactor',
ambientSound = 'reactorloop',
portrait = 'Env_Power_Generator',
placeSound = 'placereactor',
sidebarIcon = 'icon_generator',
matterCost=600,
nPowerOutput = 2500,
nSabotageDuration = 30,
bCanDeactivate = true,
sFlavorText = 'OBFLAV022TEXT',
},
GeneratorLevel3=
{
spriteName='ReactorGen3',
zoneName='POWER',
friendlyNameLinecode='PROPSX100TEXT',
description='PROPSX101TEXT',
width=3,
height=3,
margin=2,
decayPerSecond=0.04,
explodeOnFailure=true,
researchPrereq = 'GeneratorLevel3',
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=true,
clickSound = 'fusionreactor',
ambientSound = 'reactorloop',
portrait = 'Env_Power_Generator',
placeSound = 'placereactor',
sidebarIcon = 'icon_generator',
matterCost=2000,
nPowerOutput = 5000,
nSabotageDuration = 30,
bCanDeactivate = true,
sFlavorText = 'OBFLAV037TEXT',
spriteSheetPath = 'Environments/ReactorGen3',
},
GeneratorLevel4=
{
spriteName='ReactorGen4',
zoneName='POWER',
friendlyNameLinecode='PROPSX102TEXT',
description='PROPSX103TEXT',
width=4,
height=4,
margin=2,
decayPerSecond=0.04,
explodeOnFailure=true,
researchPrereq = 'GeneratorLevel4',
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=true,
clickSound = 'fusionreactor',
ambientSound = 'reactorloop',
portrait = 'Env_Power_Generator',
placeSound = 'placereactor',
sidebarIcon = 'icon_generator',
matterCost=5000,
nPowerOutput = 10000,
nSabotageDuration = 30,
bCanDeactivate = true,
sFlavorText = 'OBFLAV038TEXT',
spriteSheetPath = 'Environments/ReactorGen4',
},
--[[
ReactorTileGuts=
{
spriteName='reactor_tileguts',
zoneName='POWER',
friendlyNameLinecode='PROPSX013TEXT',
description='PROPSX014TEXT',
width=1,
height=1,
margin=0,
createJob=Character.BUILDER,
bBlocksPathing=false,
noRoom=true,
matterCost=5,
portrait = 'Env_ReactorTileGuts',
placeSound = 'placereactortile',
},
ReactorServerMachine=
{
spriteName='reactor_server_machine',
zoneName='POWER',
friendlyNameLinecode='PROPSX015TEXT',
description='PROPSX016TEXT',
width=1,
height=1,
margin=0,
createJob=Character.BUILDER,
bBlocksPathing=false,
noRoom=true,
againstWall=true,
matterCost=5,
portrait = 'Env_Reactor_ServerMachine',
placeSound = 'placereactorserver',
},
]]--
FirePanel=
{
spriteName='fire_panel',
friendlyNameLinecode='PROPSX001TEXT',
description='PROPSX002TEXT',
width=1,
height=1,
margin=0,
againstWall=true,
noRoom=true,
decayPerSecond=0.01,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=false,
clickSound = 'spacesuitlocker',
matterCost=50,
portrait = 'Env_Firepanel',
placeSound = 'placefirepanel',
sidebarIcon = 'icon_fire_panel',
sFlavorText = 'OBFLAV029TEXT',
},
FoodReplicator=
{
spriteName='food_replicator',
friendlyNameLinecode='PROPSX027TEXT',
description='PROPSX028TEXT',
width=1,
height=1,
margin=0,
customClass='EnvObjects.FoodReplicator',
againstWall=true,
noRoom=true,
decayPerSecond=0.01,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=false,
clickSound = 'spacesuitlocker',
matterCost=50,
nFoodPrice=1,
portrait = 'Env_Replicator',
placeSound = 'placefoodreplicator',
sidebarIcon = 'icon_replicator',
nPowerDraw = 20,
tIconOffset = {-30, 150},
sFlavorText = 'OBFLAV004TEXT',
bCanDeactivate = true,
},
EmergencyAlarm=
{
spriteName='alarm_panel',
friendlyNameLinecode='PROPSX040TEXT',
description='PROPSX041TEXT',
width=1,
height=1,
margin=0,
customClass='EnvObjects.EmergencyAlarm',
customInspector='EmergencyAlarmControls',
againstWall=true,
noRoom=true,
decayPerSecond=0.01,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=false,
clickSound = 'spacesuitlocker',
matterCost=50,
nFoodPrice=0,
portrait = 'Env_AlarmPanel',
placeSound = 'placefirepanel',
sidebarIcon = 'icon_alarm_panel',
sFlavorText = 'OBFLAV020TEXT',
},
OxygenRecycler=
{
spriteName='oxygen_recycler',
zoneName='LIFESUPPORT',
friendlyNameLinecode='ZONEUI016TEXT',
description='ZONEUI052TEXT',
width=1,
height=1,
margin=1,
decayPerSecond=0.05,
explodeOnFailure=true,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=true,
matterCost=150,
-- This gets added to this tile every 1/10 of a second.
oxygenLevel=50,
clickSound = 'oxygenrecycler',
ambientSound = 'oxygenrecyclerloop',
portrait = 'Env_LifeSupport_OxygenRecycler',
placeSound = 'placerecycler',
sidebarIcon = 'icon_oxygen_recycler',
nPowerDraw = 25,
tIconOffset = {-10, 140},
sFlavorText = 'OBFLAV001TEXT',
bCanDeactivate = true,
},
OxygenRecyclerLevel2=
{
spriteName='oxygen_recycler_level2',
zoneName='LIFESUPPORT',
friendlyNameLinecode='PROPSX062TEXT',
description='PROPSX063TEXT',
width=2,
height=2,
margin=1,
decayPerSecond=0.05,
explodeOnFailure=true,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=true,
matterCost=300,
-- This gets added to this tile every 1/10 of a second.
oxygenLevel=300,
clickSound = 'oxygenrecycler',
ambientSound = 'oxygenrecyclerloop',
portrait = 'Env_LifeSupport_OxygenRecycler2',
placeSound = 'placerecycler',
sidebarIcon = 'icon_oxygen_recycler',
researchPrereq = 'OxygenRecyclerLevel2',
sFunctionality='OxygenRecycler',
nPowerDraw = 30,
tIconOffset = {40, 200},
sFlavorText = 'OBFLAV002TEXT',
bCanDeactivate = true,
},
OxygenRecyclerLevel3=
{
zoneName = 'LIFESUPPORT',
friendlyNameLinecode = 'RECYCLE001TEXT',
description = 'RECYCLE002TEXT',
width = 3,
height = 3,
margin = 1,
decayPerSecond = 0.06,
explodeOnFailure = true,
maintainJob = Character.TECHNICIAN,
createJob = Character.BUILDER,
bBlocksPathing = true,
matterCost = 450,
oxygenLevel = 600,
clickSound = 'oxygenrecycler',
ambientSound = 'oxygenrecyclerloop',
portrait = 'Env_LifeSupport_OxygenRecycler2', -- inspector portrait
placeSound = 'placerecycler',
sidebarIcon = 'icon_oxygen_recycler',
researchPrereq = 'OxygenRecyclerLevel3',
sFunctionality = 'OxygenRecycler',
nPowerDraw = 35,
sFlavorText = 'RECYCLE003TEXT',
bCanDeactivate = true,
spriteName = 'O2Gen3',
spriteSheetPath = 'Environments/O2Gen3'
},
OxygenRecyclerLevel4=
{
zoneName = 'LIFESUPPORT',
friendlyNameLinecode = 'RECYCLE004TEXT',
description = 'RECYCLE005TEXT',
width = 4,
height = 4,
margin = 1,
decayPerSecond = 0.06,
explodeOnFailure = true,
maintainJob = Character.TECHNICIAN,
createJob = Character.BUILDER,
bBlocksPathing = true,
matterCost = 600,
oxygenLevel = 900,
clickSound = 'oxygenrecycler',
ambientSound = 'oxygenrecyclerloop',
portrait = 'Env_LifeSupport_OxygenRecycler2',
placeSound = 'placerecycler',
sidebarIcon = 'icon_oxygen_recycler',
researchPrereq = 'OxygenRecyclerLevel4',
sFunctionality = 'OxygenRecycler',
nPowerDraw = 35,
sFlavorText = 'RECYCLE006TEXT',
bCanDeactivate = true,
spriteName = 'O2Gen4',
spriteSheetPath = 'Environments/O2Gen4'
},
AirScrubber=
{
spriteName='AirScrubber',
customClass='EnvObjects.AirScrubber',
zoneName='LIFESUPPORT',
friendlyNameLinecode='PROPSX078TEXT',
description='PROPSX079TEXT',
width=1,
height=1,
margin=1,
decayPerSecond=0.04,
explodeOnFailure=true,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=true,
againstWall=false,
matterCost=300,
nRange=12,
portrait = 'Env_AirScrubber',
placeSound = 'placeoxygenfilter',
researchPrereq = 'AirScrubber',
sidebarIcon = 'icon_airscrubber',
nPowerDraw = 30,
tIconOffset = {0, 120},
sFlavorText = 'OBFLAV003TEXT',
bCanDeactivate = true,
},
AirlockLocker=
{
spriteName='airlock_locker',
customClass='EnvObjects.AirlockLocker',
--spriteNameFlipped='airlock_locker_flipped',
zoneName='AIRLOCK',
friendlyNameLinecode='ZONEUI040TEXT',
description='ZONEUI053TEXT',
width=1,
height=1,
margin=0,
againstWall=true,
decayPerSecond=0.01,
explodeOnFailure=true,
bAttackable=false,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
clickSound = 'spacesuitlocker',
portrait = 'Env_Airlock_Locker',
matterCost=50,
placeSound = 'placespacesuitlocker',
sidebarIcon = 'icon_airlock_locker',
sFlavorText = 'OBFLAV021TEXT',
},
Bed=
{
spriteName='bed',
zoneName='RESIDENCE',
additionalZones={BRIG=1,},
friendlyNameLinecode='ZONEUI044TEXT',
description='ZONEUI054TEXT',
width=2,
height=1,
margin=1,
--decayPerSecond=0.005,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
customClass='EnvObjects.Bed',
bBlocksPathing=true,
--inherentActivities={ 'SleepInBed', },
clickSound = 'spacebed',
portrait = 'Env_Bed',
matterCost=150,
placeSound = 'placebed',
sidebarIcon = 'icon_bed',
tAnimOffset = {x=55, y=60},
tAnimOffsetFlipped = {x=55, y=25},
--animDirFlipped = 'E',
sFlavorText = 'OBFLAV026TEXT',
},
Bar=
{
spriteName='bar',
zoneName='PUB',
customClass='EnvObjects.Bar',
friendlyNameLinecode='ZONEUI065TEXT',
description='ZONEUI066TEXT',
width=2,
height=1,
margin=1,
decayPerSecond=0.005,
createJob=Character.BUILDER,
bBlocksPathing=true,
matterCost=250,
portrait = 'Env_Bar',
placeSound = 'placebar',
sidebarIcon = 'icon_bar',
sFlavorText = 'OBFLAV030TEXT',
},
Fridge =
{
spriteName='fridge',
interactSprite='fridge_open',
zoneName='PUB',
friendlyNameLinecode='PROPSX033TEXT',
description='PROPSX034TEXT',
width=1,
height=1,
margin=0,
againstWall=true,
decayPerSecond=0.002,
createJob=Character.BUILDER,
bBlocksPathing=true,
matterCost=250,
portrait = 'Env_Pub_Fridge',
customClass='EnvObjects.Fridge',
placeSound = 'placefridge',
sidebarIcon = 'icon_fridge',
bInventory=true,
GenerateStartingInventory={tWhitelist={'Corn','Pod','Glowfruit'},tRange={0,2},tStackRange={1,7},},
nCapacity=7,
nPowerDraw = 35,
sFlavorText = 'OBFLAV013TEXT',
bCanDeactivate = true,
},
FridgeLevel2 =
{
spriteName='fridge_level2',
interactSprite='fridge_level2_open',
zoneName='PUB',
friendlyNameLinecode='PROPSX069TEXT',
description='PROPSX068TEXT',
width=1,
height=1,
margin=0,
againstWall=true,
decayPerSecond=0.002,
createJob=Character.BUILDER,
bBlocksPathing=true,
matterCost=250,
portrait = 'Env_Pub_Fridge',
customClass='EnvObjects.Fridge',
placeSound = 'placefridge',
sidebarIcon = 'icon_fridge',
bInventory=true,
researchPrereq='FridgeLevel2',
nCapacity=50,
sFunctionality='Fridge',
GenerateStartingInventory={tWhitelist={'Corn','Pod','Glowfruit'},tRange={0,2},tStackRange={1,7},},
nPowerDraw = 50,
sFlavorText = 'OBFLAV014TEXT',
bCanDeactivate = true,
},
Stove=
{
spriteName='stove',
zoneName='PUB',
friendlyNameLinecode='PROPSX030TEXT',
description='PROPSX029TEXT',
width=1,
height=1,
margin=0,
againstWall=false,
decayPerSecond=0.005,
createJob=Character.BUILDER,
bBlocksPathing=true,
matterCost=250,
portrait = 'Env_Pub_Stove',
placeSound = 'placestove',
sidebarIcon = 'icon_stove',
nPowerDraw = 30,
bCanDeactivate = true,
sFlavorText = 'OBFLAV035TEXT',
},
StandingTable=
{
spriteName='standing_table',
zoneName='PUB',
friendlyNameLinecode='PROPSX031TEXT',
description='PROPSX032TEXT',
customClass='EnvObjects.PubTable',
width=1,
height=1,
margin=1,
bInventory=true,
decayPerSecond=0.000,
createJob=Character.BUILDER,
bBlocksPathing=true,
matterCost=100,
portrait = 'Env_Pub_StandingTable',
placeSound = 'placetable',
sidebarIcon = 'icon_standingtable',
sFlavorText = 'OBFLAV005TEXT',
},
RefineryDropoff=
{
spriteName='refinery',
zoneName='REFINERY',
friendlyNameLinecode='ZONEUI045TEXT',
description='ZONEUI055TEXT',
width=2,
height=2,
margin=1,
decayPerSecond=0.005,
explodeOnFailure=true,
customClass='EnvObjects.RefineryDropoff',
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=true,
--inherentActivities={ 'DropOffRocks', },
clickSound = 'spacebed',
ambientSound = 'refineryloop',
matterCost=200,
portrait = 'Env_Refinery',
placeSound = 'placerefinery',
sidebarIcon = 'icon_refinery',
nPowerDraw = 40,
tIconOffset = {60, 170},
bCanDeactivate = true,
sFlavorText = 'OBFLAV032TEXT',
},
RefineryDropoffLevel2=
{
spriteName='refinery_level2',
zoneName='REFINERY',
friendlyNameLinecode='PROPSX066TEXT',
description='PROPSX067TEXT',
width=2,
height=2,
margin=1,
decayPerSecond=0.005,
explodeOnFailure=true,
customClass='EnvObjects.RefineryDropoff',
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=true,
--inherentActivities={ 'DropOffRocks', },
clickSound = 'spacebed',
ambientSound = 'refineryloop',
matterCost=400,
portrait = 'Env_Refinery',
placeSound = 'placerefinery',
sidebarIcon = 'icon_refinery',
researchPrereq='RefineryDropoffLevel2',
sFunctionality='RefineryDropoff',
nPowerDraw = 50,
tIconOffset = {60, 170},
bCanDeactivate = true,
sFlavorText = 'OBFLAV033TEXT',
},
HousePlant=
{
spriteName='residence_houseplant',
friendlyNameLinecode='ZONEUI059TEXT',
description='ZONEUI060TEXT',
width=1,
height=1,
margin=0,
createJob=Character.BUILDER,
bBlocksPathing=false,
noRoom=true,
matterCost=150,
portrait = 'Env_Plant_01',
placeSound = 'placeplant',
sidebarIcon = 'icon_plant',
-- plants generate small amounts of oxygen
-- (amount added to tile every 1/10 of a second)
oxygenLevel=5,
nMoraleScore=3,
sFlavorText='OBFLAV015TEXT',
},
Dresser=
{
spriteName='residence_dresser01',
friendlyNameLinecode='ZONEUI061TEXT',
description='ZONEUI062TEXT',
--zoneName='RESIDENCE',
width=1,
height=1,
margin=0,
createJob=Character.BUILDER,
bBlocksPathing=false,
noRoom=true,
matterCost=125,
portrait = 'Env_Residence_Dresser',
placeSound = 'placedresser',
sidebarIcon = 'icon_dresser',
nMoraleScore=1,
bInventory=true,
sFunctionality='Shelving',
sFlavorText='OBFLAV023TEXT',
GenerateStartingInventory={bStuff=true,tRange={0,2}},
tDisplaySlots=
{
--{x=-64,y=50,z=10},
--{x=-32,y=64,z=5},
{x=-155,y=-12,z=10},
{x=-125,y=3,z=5},
},
},
WallShelf=
{
spriteName='ShelvesWallStack',
spriteOffsetX=-15,
spriteOffsetXFlipped=15,
friendlyNameLinecode='PROPSX092TEXT',
description='PROPSX093TEXT',
--zoneName='RESIDENCE',
width=1,
height=1,
margin=0,
againstWall=true,
noRoom=true,
decayPerSecond=0,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=false,
clickSound = 'spacesuitlocker',
matterCost=100,
portrait = 'Env_Shelf',
placeSound = 'placedresser',
sidebarIcon = 'icon_shelf',
nMoraleScore=1,
bInventory=true,
sFunctionality='Shelving',
sFlavorText='OBFLAV036TEXT',
GenerateStartingInventory={bStuff=true,tRange={0,2}},
tDisplaySlots=
{
{x=-183,y=-14,z=6},
{x=-153,y=1,z=3},
{x=-183,y=44,z=12},
{x=-153,y=59,z=9},
},
},
TVScreen1=
{
spriteName='tv_screen01',
friendlyNameLinecode='PROPSX003TEXT',
description='PROPSX004TEXT',
width=1,
height=1,
margin=0,
createJob=Character.BUILDER,
bBlocksPathing=false,
noRoom=true,
againstWall=true,
matterCost=75,
portrait = 'Env_TVScreen',
placeSound = 'placemonitor',
sidebarIcon = 'icon_tv_screen',
nMoraleScore=1,
nPowerDraw = 10,
bCanDeactivate = true,
sFlavorText = 'OBFLAV028TEXT',
},
BurgerSign=
{
spriteName='dec_wall_neon_burger',
friendlyNameLinecode='PROPSX007TEXT',
description='PROPSX008TEXT',
width=1,
height=1,
margin=0,
createJob=Character.BUILDER,
bBlocksPathing=false,
zoneName='PUB',
againstWall=true,
matterCost=225,
portrait = 'Env_Bar_NeonBurger',
placeSound = 'placeneon',
sidebarIcon = 'icon_wall_neon_burger',
bIgnoreLighting=true,
nMoraleScore=2,
nPowerDraw = 5,
sFlavorText = 'OBFLAV010TEXT',
},
PizzaSign=
{
spriteName='dec_wall_neon_pizza',
friendlyNameLinecode='PROPSX011TEXT',
description='PROPSX012TEXT',
width=1,
height=1,
margin=0,
createJob=Character.BUILDER,
bBlocksPathing=false,
zoneName='PUB',
againstWall=true,
matterCost=150,
portrait = 'Env_Bar_NeonPizza',
placeSound = 'placeneon',
sidebarIcon = 'icon_wall_neon_pizza',
nMoraleScore=2,
bIgnoreLighting=true,
nPowerDraw = 5,
sFlavorText = 'OBFLAV011TEXT',
},
FriesSign=
{
spriteName='dec_wall_neon_fries',
friendlyNameLinecode='PROPSX009TEXT',
description='PROPSX010TEXT',
width=1,
height=1,
margin=0,
createJob=Character.BUILDER,
bBlocksPathing=false,
zoneName='PUB',
againstWall=true,
matterCost=75,
portrait = 'Env_Bar_NeonFries',
placeSound = 'placeneon',
sidebarIcon = 'icon_wall_neon_fries',
nMoraleScore=2,
bIgnoreLighting=true,
nPowerDraw = 5,
sFlavorText = 'OBFLAV012TEXT',
},
Rug1=
{
spriteName='residence_rug01',
friendlyNameLinecode='ZONEUI063TEXT',
description='ZONEUI064TEXT',
width=1,
height=1,
margin=0,
createJob=Character.BUILDER,
bBlocksPathing=false,
noRoom=true,
zoneName='RESIDENCE',
matterCost=50,
portrait = 'Env_Rug',
placeSound = 'placerug',
sidebarIcon = 'icon_rug',
nMoraleScore=2,
bHelpsMorale=true,
bSortBack=true,
sFlavorText = 'OBFLAV008TEXT',
},
BaseSeed=
{
spriteName='seedpod01',
friendlyNameLinecode='PROPSX005TEXT',
description='PROPSX006TEXT',
bCanBuildInSpace=true,
width=2,
height=3,
noRoom=true,
bBlocksPathing=true,
clickSound = 'fusionreactor',
showInObjectMenu=false,
matterCost=500,
portrait = 'Env_SeedPod',
nMoraleScore=10,
nPowerOutput = 500,
nSabotageDuration = 30,
sFlavorText = 'OBFLAV027TEXT',
},
HydroPlant=
{
spriteName='hydro_farm',
zoneName='GARDEN',
friendlyNameLinecode='PROPSX025TEXT',
description='PROPSX026TEXT',
width=1,
height=1,
margin=0,
customClass='EnvObjects.HydroPlant',
decayPerSecond=0, -- the planter itself doesn't deteriorate
healthDecayPerSecond=0.01,
maintainJob=Character.BOTANIST,
createJob=Character.BUILDER,
bBlocksPathing=true,
portrait = 'Env_Plant_Tray',
matterCost=150,
placeSound = 'placehydroplant',
sidebarIcon = 'icon_plant_tray',
-- plants generate small amounts of oxygen
-- (amount added to tile every 1/10 of a second)
oxygenLevel=10,
nMoraleScore=4,
sFlavorText = 'OBFLAV034TEXT',
},
WeightBench=
{
spriteName='weightbench',
interactSprite='weightbench_inuse',
zoneName='FITNESS',
additionalZones={BRIG=1,},
friendlyNameLinecode='PROPSX046TEXT',
description='PROPSX047TEXT',
width=2,
height=1,
margin=1,
customClass='EnvObjects.WeightBench',
createJob=Character.BUILDER,
bBlocksPathing=true,
inherentActivities={ 'LiftAtWeightBench', },
clickSound = 'fusionreactor',
matterCost=100,
portrait = 'Env_WeightBench',
sidebarIcon = 'icon_weightbench',
tAnimOffset = {x=25, y=45},
tAnimOffsetFlipped = {x=45, y=25},
sFlavorText = 'OBFLAV009TEXT',
},
ResearchDesk=
{
spriteName='research_desk',
zoneName='RESEARCH',
customClass='EnvObjects.ResearchDesk',
friendlyNameLinecode='PROPSX060TEXT',
description='PROPSX061TEXT',
width=2,
height=1,
margin=1,
decayPerSecond=0.005,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
explodeOnFailure=true,
bBlocksPathing=true,
--inherentActivities={ 'ResearchInLab', },
clickSound = 'spacebed',
portrait = 'Env_Research_Desk',
matterCost=300,
placeSound = 'placebed',
sidebarIcon = 'icon_research_desk',
nPowerDraw = 50,
sFlavorText = 'OBFLAV006TEXT',
bCanDeactivate = true,
},
SecurityDesk=
{
spriteName='research_desk',
zoneName='COMMAND',
friendlyNameLinecode='COMMAND016TEXT',
COMMAND017TEXT='PROPSX061TEXT',
width=2,
height=1,
margin=1,
decayPerSecond=0.005,
maintainJob=Character.EMERGENCY,
createJob=Character.BUILDER,
explodeOnFailure=true,
bBlocksPathing=true,
clickSound = 'spacebed',
portrait = 'Env_Research_Desk',
matterCost=300,
placeSound = 'placebed',
sidebarIcon = 'icon_research_desk',
nPowerDraw = 50,
sFlavorText = 'COMMAND018TEXT',
bCanDeactivate = true,
},
WallMountedTurret=
{
spriteName='turret_frames0003',
spriteOffsetX=-110,
spriteOffsetXFlipped=-20,
customClass='EnvObjects.Turret',
friendlyNameLinecode='PROPSX084TEXT',
description='PROPSX074TEXT',
width=1,
height=1,
margin=1,
againstWall=true,
bCanFlipY=true,
noRoom=true,
bCanBuildInSpace=true,
decayPerSecond=0.01,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=false,
explodeOnFailure=true,
customInspector='TurretControls',
clickSound = 'spacebed',
portrait = 'Env_TurretExt',
matterCost=300,
placeSound = 'placebed',
sidebarIcon = 'icon_turret_ext',
nPowerDraw = 150,
bCanDeactivate = true,
sFunctionality='Turret',
sFlavorText = 'OBFLAV017TEXT',
},
WallMountedTurret2=
{
spriteName='turret_lv2_frames0003',
spriteOffsetX=-110,
spriteOffsetXFlipped=-20,
customClass='EnvObjects.TurretLv2',
friendlyNameLinecode='PROPSX080TEXT',
description='PROPSX081TEXT',
width=1,
height=1,
margin=1,
againstWall=true,
bCanFlipY=true,
noRoom=true,
bCanBuildInSpace=true,
--decayPerSecond=0.01,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=false,
explodeOnFailure=true,
customInspector='TurretControls',
clickSound = 'spacebed',
portrait = 'Env_TurretExtLv2',
matterCost=600,
placeSound = 'placebed',
sidebarIcon = 'icon_turret_ext_lv2',
researchPrereq='WallMountedTurret2',
nPowerDraw = 200,
bCanDeactivate = true,
sFunctionality='Turret',
sFlavorText = 'OBFLAV024TEXT',
},
--[[
InteriorTurret=
{
spriteName='turret_frames0003',
spriteOffset=-128,
customClass='EnvObjects.Turret',
friendlyNameLinecode='PROPSX073TEXT',
description='PROPSX074TEXT',
width=1,
height=1,
margin=1,
againstWall=true,
noRoom=true,
--decayPerSecond=0.01,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=false,
explodeOnFailure=true,
clickSound = 'spacebed',
portrait = 'Env_TurretExt',
matterCost=300,
placeSound = 'placebed',
sidebarIcon = 'icon_turret_ext',
},
]]--
HospitalBed=
{
spriteName='hospital_bed',
interactSprite='hospital_bed_occupied',
customClass='EnvObjects.HospitalBed',
zoneName='INFIRMARY',
friendlyNameLinecode='PROPSX076TEXT',
description='PROPSX077TEXT',
width=2,
height=1,
margin=1,
customInspector='InfirmaryBedControls',
decayPerSecond=0.005,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=true,
--inherentActivities={ 'SleepInBed', },
clickSound = 'spacebed',
portrait = 'Env_HospitalBed',
matterCost=400,
placeSound = 'placebed',
sidebarIcon = 'icon_hospital_bed',
tAnimOffset = {x=55, y=60},
tAnimOffsetFlipped = {x=55, y=25},
nPowerDraw = 30,
tIconOffset = {0, 150},
bCanDeactivate = true,
sFlavorText = 'OBFLAV031TEXT',
},
Jukebox ={
spriteName='Juke',
spriteSheetPath='Environments/Jukebox',
customClass='EnvObjects.Jukebox',
zoneName='PUB',
friendlyNameLinecode='JUKEX001TEXT',
description='JUKEX002TEXT',
width=1,
height=1,
margin=0,
decayPerSecond=0.002,
explodeOnFailure=true,
maintainJob=Character.TECHNICIAN,
createJob=Character.BUILDER,
bBlocksPathing=true,
againstWall=true,
matterCost=300,
bUsePortraitOffsetHack=true,
portrait = 'Stuff_LargeCup',
--sPortraitPath = 'PropSprites/TestStuff',
sPortraitPath = 'Environments/Jukebox',
placeSound = 'placeoxygenfilter',
sidebarIcon = 'icon_airscrubber',
nPowerDraw = 25,
tIconOffset = {0, 0},
sFlavorText = 'JUKEX003TEXT',
bCanDeactivate = true,
nMoraleScore=5,
inherentActivities={ 'ListenToJukebox', },
},
}
EnvObjectData.tAliases=
{
Fridge_level2='FridgeLevel2',
tvScreen1='TVScreen1',
burgerSign='BurgerSign',
pizzaSign='PizzaSign',
friesSign='FriesSign',
}
return EnvObjectData
| 0 | 0.827223 | 1 | 0.827223 | game-dev | MEDIA | 0.940488 | game-dev | 0.624381 | 1 | 0.624381 |
folgerwang/UnrealEngine | 7,097 | Engine/Source/Runtime/MovieSceneCapture/Private/MovieSceneCaptureProtocolBase.cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "MovieSceneCaptureProtocolBase.h"
#include "CoreMinimal.h"
#include "HAL/FileManager.h"
#include "Slate/SceneViewport.h"
#include "Misc/Paths.h"
#include "HAL/PlatformFilemanager.h"
#include "UnrealEngine.h"
#define LOCTEXT_NAMESPACE "MovieSceneCaptureProtocol"
UMovieSceneCaptureProtocolBase::UMovieSceneCaptureProtocolBase(const FObjectInitializer& ObjInit)
: Super(ObjInit)
{
State = EMovieSceneCaptureProtocolState::Idle;
CaptureHost = nullptr;
bFrameRequested[0] = false;
bFrameRequested[1] = false;
}
bool UMovieSceneCaptureProtocolBase::Setup(const FCaptureProtocolInitSettings& InSettings, const ICaptureProtocolHost* Host)
{
InitSettings = InSettings;
CaptureHost = Host;
switch (State)
{
case EMovieSceneCaptureProtocolState::Capturing:
BeginFinalize();
// fallthrough
case EMovieSceneCaptureProtocolState::Finalizing:
Finalize();
// fallthrough
default:
break;
}
State = EMovieSceneCaptureProtocolState::Idle;
if (!SetupImpl())
{
return false;
}
State = EMovieSceneCaptureProtocolState::Initialized;
return true;
}
UWorld* UMovieSceneCaptureProtocolBase::GetWorld() const
{
if (InitSettings.IsSet())
{
// Retrieve the world from the Scene Viewport client.
return InitSettings->SceneViewport->GetClient()->GetWorld();
}
// Otherwise we don't have a world yet - we might be instances created in the
// UI that aren't tied to the world yet. When Setup is called then the world
// will be available. We don't want to rely on the Outer for the world as it requires
// reinitializing the UMovieSceneCaptureProtocolBase just to change the outer.
return nullptr;
}
void UMovieSceneCaptureProtocolBase::WarmUp()
{
if (State == EMovieSceneCaptureProtocolState::Capturing)
{
PauseCaptureImpl();
}
if (State == EMovieSceneCaptureProtocolState::Capturing || State == EMovieSceneCaptureProtocolState::Initialized)
{
State = EMovieSceneCaptureProtocolState::Initialized;
WarmUpImpl();
}
}
bool UMovieSceneCaptureProtocolBase::StartCapture()
{
if (State == EMovieSceneCaptureProtocolState::Idle)
{
return false;
}
else if (State == EMovieSceneCaptureProtocolState::Capturing)
{
return true;
}
ensure(State == EMovieSceneCaptureProtocolState::Initialized);
State = EMovieSceneCaptureProtocolState::Capturing;
if (!StartCaptureImpl())
{
State = EMovieSceneCaptureProtocolState::Initialized;
return false;
}
return true;
}
void UMovieSceneCaptureProtocolBase::CaptureFrame(const FFrameMetrics& FrameMetrics)
{
if (State == EMovieSceneCaptureProtocolState::Capturing)
{
bFrameRequested[GFrameCounter % 2] = true;
CaptureFrameImpl(FrameMetrics);
}
}
bool UMovieSceneCaptureProtocolBase::HasFinishedProcessing() const
{
return bFrameRequested[GFrameCounter % 2] == false && HasFinishedProcessingImpl();
}
void UMovieSceneCaptureProtocolBase::PreTick()
{
// Reset the frame requested bool for the next frame
bFrameRequested[(GFrameCounter + 1) % 2] = false;
PreTickImpl();
}
void UMovieSceneCaptureProtocolBase::Tick()
{
TickImpl();
}
void UMovieSceneCaptureProtocolBase::BeginFinalize()
{
if (State == EMovieSceneCaptureProtocolState::Idle)
{
return;
}
if (State == EMovieSceneCaptureProtocolState::Capturing)
{
PauseCaptureImpl();
}
State = EMovieSceneCaptureProtocolState::Finalizing;
BeginFinalizeImpl();
}
void UMovieSceneCaptureProtocolBase::Finalize()
{
if (State != EMovieSceneCaptureProtocolState::Finalizing)
{
BeginFinalize();
}
if (State == EMovieSceneCaptureProtocolState::Finalizing)
{
State = EMovieSceneCaptureProtocolState::Idle;
FinalizeImpl();
}
}
void UMovieSceneCaptureProtocolBase::AddFormatMappings(TMap<FString, FStringFormatArg>& FormatMappings) const
{
AddFormatMappingsImpl(FormatMappings);
}
void UMovieSceneCaptureProtocolBase::OnReleaseConfig(FMovieSceneCaptureSettings& InSettings)
{
OnReleaseConfigImpl(InSettings);
}
void UMovieSceneCaptureProtocolBase::OnLoadConfig(FMovieSceneCaptureSettings& InSettings)
{
OnLoadConfigImpl(InSettings);
}
bool UMovieSceneCaptureProtocolBase::CanWriteToFile(const TCHAR* InFilename, bool bOverwriteExisting) const
{
return CanWriteToFileImpl(InFilename, bOverwriteExisting);
}
bool UMovieSceneCaptureProtocolBase::CanWriteToFileImpl(const TCHAR* InFilename, bool bOverwriteExisting) const
{
return bOverwriteExisting || IFileManager::Get().FileSize(InFilename) == -1;
}
FCaptureProtocolInitSettings FCaptureProtocolInitSettings::FromSlateViewport(TSharedRef<FSceneViewport> InSceneViewport)
{
FCaptureProtocolInitSettings Settings;
Settings.SceneViewport = InSceneViewport;
Settings.DesiredSize = InSceneViewport->GetSize();
// hack for FORT-94554 -- viewport not yet initialized so pull resolution settings from GSystemResolution
if (Settings.DesiredSize == FIntPoint::ZeroValue)
{
Settings.DesiredSize.X = GSystemResolution.ResX;
Settings.DesiredSize.Y = GSystemResolution.ResY;
InSceneViewport->SetViewportSize(Settings.DesiredSize.X, Settings.DesiredSize.Y);
}
// end hack
return Settings;
}
void UMovieSceneCaptureProtocolBase::EnsureFileWritableImpl(const FString& File) const
{
FString Directory = FPaths::GetPath(File);
if (!IFileManager::Get().DirectoryExists(*Directory))
{
IFileManager::Get().MakeDirectory(*Directory);
}
if (CaptureHost->GetSettings().bOverwriteExisting)
{
// Try and delete it first
while (IFileManager::Get().FileSize(*File) != -1 && !FPlatformFileManager::Get().GetPlatformFile().DeleteFile(*File))
{
// Pop up a message box
FText MessageText = FText::Format(LOCTEXT("UnableToRemoveFile_Format", "The destination file '{0}' could not be deleted because it's in use by another application.\n\nPlease close this application before continuing."), FText::FromString(File));
FPlatformMisc::MessageBoxExt(EAppMsgType::Ok, *MessageText.ToString(), *LOCTEXT("UnableToRemoveFile", "Unable to remove file").ToString());
}
}
}
FString UMovieSceneCaptureProtocolBase::GenerateFilenameImpl(const FFrameMetrics& FrameMetrics, const TCHAR* Extension, const FString* NameFormatString) const
{
FString OutputDirectoryPath = CaptureHost->GetSettings().OutputDirectory.Path;
FPaths::NormalizeFilename(OutputDirectoryPath);
if (!NameFormatString)
{
NameFormatString = &CaptureHost->GetSettings().OutputFormat;
}
const FString BaseFilename = CaptureHost->ResolveFileFormat(OutputDirectoryPath, FrameMetrics) / CaptureHost->ResolveFileFormat(*NameFormatString, FrameMetrics);
FString ThisTry = BaseFilename + Extension;
if (CanWriteToFile(*ThisTry, CaptureHost->GetSettings().bOverwriteExisting))
{
return ThisTry;
}
int32 DuplicateIndex = 2;
for (;;)
{
ThisTry = BaseFilename + FString::Printf(TEXT("_(%d)"), DuplicateIndex) + Extension;
// If the file doesn't exist, we can use that, else, increment the index and try again
if (CanWriteToFile(*ThisTry, CaptureHost->GetSettings().bOverwriteExisting))
{
return ThisTry;
}
++DuplicateIndex;
}
return ThisTry;
}
#undef LOCTEXT_NAMESPACE // "MovieSceneCaptureProtocol" | 0 | 0.968324 | 1 | 0.968324 | game-dev | MEDIA | 0.650506 | game-dev | 0.778045 | 1 | 0.778045 |
flutter-webrtc/dart-sip-ua | 2,946 | lib/src/transactions/non_invite_client.dart | import 'dart:async';
import '../event_manager/event_manager.dart';
import '../event_manager/internal_events.dart';
import '../logger.dart';
import '../sip_message.dart';
import '../socket_transport.dart';
import '../timers.dart';
import '../ua.dart';
import '../utils.dart';
import 'transaction_base.dart';
class NonInviteClientTransaction extends TransactionBase {
NonInviteClientTransaction(UA ua, SocketTransport transport,
OutgoingRequest request, EventManager eventHandlers) {
id = 'z9hG4bK${Math.random().floor()}';
this.ua = ua;
this.transport = transport;
this.request = request;
_eventHandlers = eventHandlers;
String via = 'SIP/2.0/${transport.via_transport}';
via += ' ${ua.configuration.via_host};branch=$id';
request.setHeader('via', via);
ua.newTransaction(this);
}
late EventManager _eventHandlers;
Timer? F, K;
void stateChanged(TransactionState state) {
this.state = state;
emit(EventStateChanged());
}
@override
void send() {
stateChanged(TransactionState.TRYING);
F = setTimeout(() {
timer_F();
}, Timers.TIMER_F);
if (!transport!.send(request)) {
onTransportError();
}
}
@override
void onTransportError() {
logger.d('transport error occurred, deleting transaction $id');
clearTimeout(F);
clearTimeout(K);
stateChanged(TransactionState.TERMINATED);
ua.destroyTransaction(this);
_eventHandlers.emit(EventOnTransportError());
}
void timer_F() {
logger.d('Timer F expired for transaction $id');
stateChanged(TransactionState.TERMINATED);
ua.destroyTransaction(this);
_eventHandlers.emit(EventOnRequestTimeout());
}
void timer_K() {
stateChanged(TransactionState.TERMINATED);
ua.destroyTransaction(this);
}
@override
void receiveResponse(int status_code, IncomingMessage response,
[void Function()? onSuccess, void Function()? onFailure]) {
if (status_code < 200) {
switch (state) {
case TransactionState.TRYING:
case TransactionState.PROCEEDING:
stateChanged(TransactionState.PROCEEDING);
_eventHandlers.emit(
EventOnReceiveResponse(response: response as IncomingResponse?));
break;
default:
break;
}
} else {
switch (state) {
case TransactionState.TRYING:
case TransactionState.PROCEEDING:
stateChanged(TransactionState.COMPLETED);
clearTimeout(F);
if (status_code == 408) {
_eventHandlers.emit(EventOnRequestTimeout());
} else {
_eventHandlers.emit(EventOnReceiveResponse(
response: response as IncomingResponse?));
}
K = setTimeout(() {
timer_K();
}, Timers.TIMER_K);
break;
case TransactionState.COMPLETED:
break;
default:
break;
}
}
}
}
| 0 | 0.992844 | 1 | 0.992844 | game-dev | MEDIA | 0.574295 | game-dev | 0.992483 | 1 | 0.992483 |
pmmp/PocketMine-MP | 1,194 | src/block/DoubleTallGrass.php | <?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program 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.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\block;
use pocketmine\block\utils\TallGrassTrait;
use pocketmine\item\Item;
class DoubleTallGrass extends DoublePlant{
use TallGrassTrait {
getDropsForIncompatibleTool as traitGetDropsForIncompatibleTool;
}
public function canBeReplaced() : bool{
return true;
}
public function getDropsForIncompatibleTool(Item $item) : array{
if($this->top){
return $this->traitGetDropsForIncompatibleTool($item);
}
return [];
}
}
| 0 | 0.85013 | 1 | 0.85013 | game-dev | MEDIA | 0.920056 | game-dev | 0.55105 | 1 | 0.55105 |
hutian23/ETScript | 6,638 | Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Recast/PathfindingComponentSystem.cs | using System;
using System.Collections.Generic;
using Unity.Mathematics;
namespace ET
{
[FriendOf(typeof(PathfindingComponent))]
public static class PathfindingComponentSystem
{
[ObjectSystem]
public class AwakeSystem: AwakeSystem<PathfindingComponent, string>
{
protected override void Awake(PathfindingComponent self, string filterType)
{
self.Name = filterType;
self.NavMesh = NavmeshComponent.Instance.Get(filterType);
if (self.NavMesh == 0)
{
throw new Exception($"nav load fail: {filterType}");
}
}
}
[ObjectSystem]
public class DestroySystem: DestroySystem<PathfindingComponent>
{
protected override void Destroy(PathfindingComponent self)
{
self.Name = string.Empty;
self.NavMesh = 0;
}
}
public static void Find(this PathfindingComponent self, float3 start, float3 target, List<float3> result)
{
if (self.NavMesh == 0)
{
Log.Debug("寻路| Find 失败 pathfinding ptr is zero");
throw new Exception($"pathfinding ptr is zero: {self.DomainScene().Name}");
}
self.StartPos[0] = -start.x;
self.StartPos[1] = start.y;
self.StartPos[2] = start.z;
self.EndPos[0] = -target.x;
self.EndPos[1] = target.y;
self.EndPos[2] = target.z;
//Log.Debug($"start find path: {self.GetParent<Unit>().Id}");
int n = Recast.RecastFind(self.NavMesh, PathfindingComponent.extents, self.StartPos, self.EndPos, self.Result);
for (int i = 0; i < n; ++i)
{
int index = i * 3;
result.Add(new float3(-self.Result[index], self.Result[index + 1], self.Result[index + 2]));
}
//Log.Debug($"finish find path: {self.GetParent<Unit>().Id} {result.ListToString()}");
}
public static void FindWithAdjust(this PathfindingComponent self, float3 start, float3 target, List<float3> result,float adjustRaduis)
{
self.Find(start, target, result);
for (int i = 0; i < result.Count; i++)
{
float3 adjust = self.FindRandomPointWithRaduis(result[i], adjustRaduis);
result[i] = adjust;
}
}
public static float3 FindRandomPointWithRaduis(this PathfindingComponent self, float3 pos, float raduis)
{
if (self.NavMesh == 0)
{
throw new Exception($"pathfinding ptr is zero: {self.DomainScene().Name}");
}
if (raduis > PathfindingComponent.FindRandomNavPosMaxRadius * 0.001f)
{
throw new Exception($"pathfinding raduis is too large,cur: {raduis}, max: {PathfindingComponent.FindRandomNavPosMaxRadius}");
}
int degrees = RandomGenerator.RandomNumber(0, 360);
float r = RandomGenerator.RandomNumber(0, (int) (raduis * 1000)) / 1000f;
float x = r * math.cos(math.radians(degrees));
float z = r * math.sin(math.radians(degrees));
float3 findpos = new float3(pos.x + x, pos.y, pos.z + z);
return self.RecastFindNearestPoint(findpos);
}
/// <summary>
/// 以pos为中心各自在宽和高的左右 前后两个方向延伸
/// </summary>
/// <param name="self"></param>
/// <param name="pos"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static float3 FindRandomPointWithRectangle(this PathfindingComponent self, float3 pos, int width, int height)
{
if (self.NavMesh == 0)
{
throw new Exception($"pathfinding ptr is zero: {self.DomainScene().Name}");
}
if (width > PathfindingComponent.FindRandomNavPosMaxRadius * 0.001f || height > PathfindingComponent.FindRandomNavPosMaxRadius * 0.001f)
{
throw new Exception($"pathfinding rectangle is too large,width: {width} height: {height}, max: {PathfindingComponent.FindRandomNavPosMaxRadius}");
}
float x = RandomGenerator.RandomNumber(-width, width);
float z = RandomGenerator.RandomNumber(-height, height);
float3 findpos = new float3(pos.x + x, pos.y, pos.z + z);
return self.RecastFindNearestPoint(findpos);
}
public static float3 FindRandomPointWithRaduis(this PathfindingComponent self, float3 pos, float minRadius, float maxRadius)
{
if (self.NavMesh == 0)
{
throw new Exception($"pathfinding ptr is zero: {self.DomainScene().Name}");
}
if (maxRadius > PathfindingComponent.FindRandomNavPosMaxRadius * 0.001f)
{
throw new Exception($"pathfinding raduis is too large,cur: {maxRadius}, max: {PathfindingComponent.FindRandomNavPosMaxRadius}");
}
int degrees = RandomGenerator.RandomNumber(0, 360);
float r = RandomGenerator.RandomNumber((int) (minRadius * 1000), (int) (maxRadius * 1000)) / 1000f;
float x = r * math.cos(math.radians(degrees));
float z = r * math.sin(math.radians(degrees));
float3 findpos = new float3(pos.x + x, pos.y, pos.z + z);
return self.RecastFindNearestPoint(findpos);
}
public static float3 RecastFindNearestPoint(this PathfindingComponent self, float3 pos)
{
if (self.NavMesh == 0)
{
throw new Exception($"pathfinding ptr is zero: {self.DomainScene().Name}");
}
self.StartPos[0] = -pos.x;
self.StartPos[1] = pos.y;
self.StartPos[2] = pos.z;
int ret = Recast.RecastFindNearestPoint(self.NavMesh, PathfindingComponent.extents, self.StartPos, self.EndPos);
if (ret == 0)
{
throw new Exception($"RecastFindNearestPoint fail, 可能是位置配置有问题: sceneName:{self.DomainScene().Name} {pos} {self.Name} {self.GetParent<Unit>().Id} {self.GetParent<Unit>().Config.Id} {self.EndPos.ArrayToString()}");
}
return new float3(-self.EndPos[0], self.EndPos[1], self.EndPos[2]);
}
}
} | 0 | 0.82562 | 1 | 0.82562 | game-dev | MEDIA | 0.854928 | game-dev | 0.981096 | 1 | 0.981096 |
Nextpeer/Nextpeer-UFORUN | 8,399 | cocos2d-x-2.2/external/emscripten/tests/bullet/src/BulletCollision/CollisionShapes/btConvexTriangleMeshShape.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btConvexTriangleMeshShape.h"
#include "BulletCollision/CollisionShapes/btCollisionMargin.h"
#include "LinearMath/btQuaternion.h"
#include "BulletCollision/CollisionShapes/btStridingMeshInterface.h"
btConvexTriangleMeshShape ::btConvexTriangleMeshShape (btStridingMeshInterface* meshInterface, bool calcAabb)
: btPolyhedralConvexAabbCachingShape(), m_stridingMesh(meshInterface)
{
m_shapeType = CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE;
if ( calcAabb )
recalcLocalAabb();
}
///It's not nice to have all this virtual function overhead, so perhaps we can also gather the points once
///but then we are duplicating
class LocalSupportVertexCallback: public btInternalTriangleIndexCallback
{
btVector3 m_supportVertexLocal;
public:
btScalar m_maxDot;
btVector3 m_supportVecLocal;
LocalSupportVertexCallback(const btVector3& supportVecLocal)
: m_supportVertexLocal(btScalar(0.),btScalar(0.),btScalar(0.)),
m_maxDot(btScalar(-BT_LARGE_FLOAT)),
m_supportVecLocal(supportVecLocal)
{
}
virtual void internalProcessTriangleIndex(btVector3* triangle,int partId,int triangleIndex)
{
(void)triangleIndex;
(void)partId;
for (int i=0;i<3;i++)
{
btScalar dot = m_supportVecLocal.dot(triangle[i]);
if (dot > m_maxDot)
{
m_maxDot = dot;
m_supportVertexLocal = triangle[i];
}
}
}
btVector3 GetSupportVertexLocal()
{
return m_supportVertexLocal;
}
};
btVector3 btConvexTriangleMeshShape::localGetSupportingVertexWithoutMargin(const btVector3& vec0)const
{
btVector3 supVec(btScalar(0.),btScalar(0.),btScalar(0.));
btVector3 vec = vec0;
btScalar lenSqr = vec.length2();
if (lenSqr < btScalar(0.0001))
{
vec.setValue(1,0,0);
} else
{
btScalar rlen = btScalar(1.) / btSqrt(lenSqr );
vec *= rlen;
}
LocalSupportVertexCallback supportCallback(vec);
btVector3 aabbMax(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
m_stridingMesh->InternalProcessAllTriangles(&supportCallback,-aabbMax,aabbMax);
supVec = supportCallback.GetSupportVertexLocal();
return supVec;
}
void btConvexTriangleMeshShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
//use 'w' component of supportVerticesOut?
{
for (int i=0;i<numVectors;i++)
{
supportVerticesOut[i][3] = btScalar(-BT_LARGE_FLOAT);
}
}
///@todo: could do the batch inside the callback!
for (int j=0;j<numVectors;j++)
{
const btVector3& vec = vectors[j];
LocalSupportVertexCallback supportCallback(vec);
btVector3 aabbMax(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
m_stridingMesh->InternalProcessAllTriangles(&supportCallback,-aabbMax,aabbMax);
supportVerticesOut[j] = supportCallback.GetSupportVertexLocal();
}
}
btVector3 btConvexTriangleMeshShape::localGetSupportingVertex(const btVector3& vec)const
{
btVector3 supVertex = localGetSupportingVertexWithoutMargin(vec);
if ( getMargin()!=btScalar(0.) )
{
btVector3 vecnorm = vec;
if (vecnorm .length2() < (SIMD_EPSILON*SIMD_EPSILON))
{
vecnorm.setValue(btScalar(-1.),btScalar(-1.),btScalar(-1.));
}
vecnorm.normalize();
supVertex+= getMargin() * vecnorm;
}
return supVertex;
}
//currently just for debugging (drawing), perhaps future support for algebraic continuous collision detection
//Please note that you can debug-draw btConvexTriangleMeshShape with the Raytracer Demo
int btConvexTriangleMeshShape::getNumVertices() const
{
//cache this?
return 0;
}
int btConvexTriangleMeshShape::getNumEdges() const
{
return 0;
}
void btConvexTriangleMeshShape::getEdge(int ,btVector3& ,btVector3& ) const
{
btAssert(0);
}
void btConvexTriangleMeshShape::getVertex(int ,btVector3& ) const
{
btAssert(0);
}
int btConvexTriangleMeshShape::getNumPlanes() const
{
return 0;
}
void btConvexTriangleMeshShape::getPlane(btVector3& ,btVector3& ,int ) const
{
btAssert(0);
}
//not yet
bool btConvexTriangleMeshShape::isInside(const btVector3& ,btScalar ) const
{
btAssert(0);
return false;
}
void btConvexTriangleMeshShape::setLocalScaling(const btVector3& scaling)
{
m_stridingMesh->setScaling(scaling);
recalcLocalAabb();
}
const btVector3& btConvexTriangleMeshShape::getLocalScaling() const
{
return m_stridingMesh->getScaling();
}
void btConvexTriangleMeshShape::calculatePrincipalAxisTransform(btTransform& principal, btVector3& inertia, btScalar& volume) const
{
class CenterCallback: public btInternalTriangleIndexCallback
{
bool first;
btVector3 ref;
btVector3 sum;
btScalar volume;
public:
CenterCallback() : first(true), ref(0, 0, 0), sum(0, 0, 0), volume(0)
{
}
virtual void internalProcessTriangleIndex(btVector3* triangle, int partId, int triangleIndex)
{
(void) triangleIndex;
(void) partId;
if (first)
{
ref = triangle[0];
first = false;
}
else
{
btScalar vol = btFabs((triangle[0] - ref).triple(triangle[1] - ref, triangle[2] - ref));
sum += (btScalar(0.25) * vol) * ((triangle[0] + triangle[1] + triangle[2] + ref));
volume += vol;
}
}
btVector3 getCenter()
{
return (volume > 0) ? sum / volume : ref;
}
btScalar getVolume()
{
return volume * btScalar(1. / 6);
}
};
class InertiaCallback: public btInternalTriangleIndexCallback
{
btMatrix3x3 sum;
btVector3 center;
public:
InertiaCallback(btVector3& center) : sum(0, 0, 0, 0, 0, 0, 0, 0, 0), center(center)
{
}
virtual void internalProcessTriangleIndex(btVector3* triangle, int partId, int triangleIndex)
{
(void) triangleIndex;
(void) partId;
btMatrix3x3 i;
btVector3 a = triangle[0] - center;
btVector3 b = triangle[1] - center;
btVector3 c = triangle[2] - center;
btScalar volNeg = -btFabs(a.triple(b, c)) * btScalar(1. / 6);
for (int j = 0; j < 3; j++)
{
for (int k = 0; k <= j; k++)
{
i[j][k] = i[k][j] = volNeg * (btScalar(0.1) * (a[j] * a[k] + b[j] * b[k] + c[j] * c[k])
+ btScalar(0.05) * (a[j] * b[k] + a[k] * b[j] + a[j] * c[k] + a[k] * c[j] + b[j] * c[k] + b[k] * c[j]));
}
}
btScalar i00 = -i[0][0];
btScalar i11 = -i[1][1];
btScalar i22 = -i[2][2];
i[0][0] = i11 + i22;
i[1][1] = i22 + i00;
i[2][2] = i00 + i11;
sum[0] += i[0];
sum[1] += i[1];
sum[2] += i[2];
}
btMatrix3x3& getInertia()
{
return sum;
}
};
CenterCallback centerCallback;
btVector3 aabbMax(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
m_stridingMesh->InternalProcessAllTriangles(¢erCallback, -aabbMax, aabbMax);
btVector3 center = centerCallback.getCenter();
principal.setOrigin(center);
volume = centerCallback.getVolume();
InertiaCallback inertiaCallback(center);
m_stridingMesh->InternalProcessAllTriangles(&inertiaCallback, -aabbMax, aabbMax);
btMatrix3x3& i = inertiaCallback.getInertia();
i.diagonalize(principal.getBasis(), btScalar(0.00001), 20);
inertia.setValue(i[0][0], i[1][1], i[2][2]);
inertia /= volume;
}
| 0 | 0.95666 | 1 | 0.95666 | game-dev | MEDIA | 0.988106 | game-dev | 0.996063 | 1 | 0.996063 |
Crownicles/Crownicles | 1,153 | Core/src/commands/admin/testCommands/Inventory/GiveItemTestCommand.ts | import {
ExecuteTestCommandLike, ITestCommand, TypeKey
} from "../../../../core/CommandsTest";
import { getItemByIdAndCategory } from "../../../../core/utils/ItemUtils";
export const commandInfo: ITestCommand = {
name: "giveitem",
commandFormat: "<category [0-3]> <item id>",
typeWaited: {
"category [0-3]": TypeKey.INTEGER,
"item id": TypeKey.INTEGER
},
description: "Donne un objet spécifique au joueur. Catégories : 0=armes, 1=armures, 2=potions, 3=objets. Voir Core/resources/[category]/ pour les IDs"
};
/**
* Set the weapon of the player
*/
const giveItemTestCommand: ExecuteTestCommandLike = async (player, args) => {
const itemId = parseInt(args[1], 10);
const category = parseInt(args[0], 10);
if (category < 0 || category > 3) {
throw Error("Catégorie inconnue. Elle doit être en 0 et 3");
}
const item = getItemByIdAndCategory(itemId, category);
if (!item) {
throw Error("Aucun objet n'existe dans cette catégorie avec cet id");
}
if (!await player.giveItem(item)) {
throw Error("Aucun emplacement libre dans l'inventaire");
}
return `Vous avez reçu ${item.id} !`;
};
commandInfo.execute = giveItemTestCommand;
| 0 | 0.927552 | 1 | 0.927552 | game-dev | MEDIA | 0.924266 | game-dev | 0.9608 | 1 | 0.9608 |
Singtaa/OneJS | 5,193 | Puerts/Runtime/Src/Default/Translator/ArgumentHelper.cs | /*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
#if PUERTS_DISABLE_IL2CPP_OPTIMIZATION || (!PUERTS_IL2CPP_OPTIMIZATION && UNITY_IPHONE) || !ENABLE_IL2CPP
using System;
namespace Puerts
{
public struct ArgHelper
{
public static T[] GetParams<T>(int jsEnvIdx, IntPtr isolate, IntPtr info, int start, int end, IntPtr v8Value)
{
T[] result = new T[end - start];
for (int i = start; i < end; i++)
{
var val = i == start ? v8Value : PuertsDLL.GetArgumentValue(isolate, info, i);
result[i - start] = StaticTranslate<T>.Get(jsEnvIdx, isolate, NativeValueApi.GetValueFromArgument, val, false);
}
return result;
}
public static bool IsMatchParams(
int jsEnvIdx,
IntPtr isolate,
IntPtr info,
JsValueType expectJsType,
Type expectCsType,
int start,
int end,
IntPtr v8Value,
ref object arg,
ref JsValueType argValueType
)
{
if (!IsMatch(jsEnvIdx, isolate, expectJsType, expectCsType, false, false, v8Value, ref arg, ref argValueType))
{
return false;
}
for (int i = start + 1; i < end; i++)
{
IntPtr value = PuertsDLL.GetArgumentValue(isolate, info, i);
object argObj = null;
JsValueType valueType = JsValueType.Invalid;
if (!ArgHelper.IsMatch(jsEnvIdx, isolate, expectJsType, expectCsType, false, false, value, ref argObj, ref valueType))
{
return false;
}
}
return true;
}
public static bool IsMatch(
int jsEnvIdx,
IntPtr isolate,
JsValueType expectJsType,
Type expectCsType,
bool isByRef,
bool isOut,
IntPtr v8Value,
ref object arg,
ref JsValueType argValueType//,
// ref Type csType
)
{
Type csType = null;
if (argValueType == JsValueType.Invalid)
argValueType = PuertsDLL.GetJsValueType(isolate, v8Value, false);
if (argValueType == JsValueType.JsObject)
{
if (isByRef)
{
if (isOut) return true;
argValueType = PuertsDLL.GetJsValueType(isolate, v8Value, true);
}
else if ((expectJsType & argValueType) == argValueType)
{
return true;
}
else
{
return false;
}
}
if (argValueType == JsValueType.NativeObject && expectCsType.IsPrimitive)
{
if (arg == null)
{
arg = JsEnv.jsEnvs[jsEnvIdx].GeneralGetterManager.AnyTranslator(jsEnvIdx, isolate, NativeValueApi.GetValueFromArgument, v8Value, isByRef);
}
if (arg.GetType() == expectCsType)
{
return true;
}
}
if ((expectJsType & argValueType) != argValueType)
{
return false;
}
if (argValueType == JsValueType.NativeObject)
{
if (expectCsType.IsArray)
{
if (arg == null)
{
arg = JsEnv.jsEnvs[jsEnvIdx].GeneralGetterManager.AnyTranslator(jsEnvIdx, isolate, NativeValueApi.GetValueFromArgument, v8Value, isByRef);
}
return expectCsType != null && expectCsType.IsAssignableFrom(arg.GetType());
}
else
{
if (csType == null)
{
var typeId = NativeValueApi.GetValueFromArgument.GetTypeId(isolate, v8Value, isByRef);
if (typeId >= 0)
{
csType = JsEnv.jsEnvs[jsEnvIdx].TypeManager.GetType(typeId);
}
}
return csType != null && expectCsType != null && expectCsType.IsAssignableFrom(csType);
}
}
return true;
}
}
public struct ResultHelper
{
public static void Set<T>(int jsEnvIdx, IntPtr isolate, IntPtr info, T result)
{
StaticTranslate<T>.Set(jsEnvIdx, isolate, NativeValueApi.SetValueToResult, info, result);
}
}
}
#endif
| 0 | 0.710218 | 1 | 0.710218 | game-dev | MEDIA | 0.237099 | game-dev | 0.928621 | 1 | 0.928621 |
vlad250906/Create-UfoPort | 2,803 | modules/create/src/main/java/com/simibubi/create/content/fluids/particle/BasinFluidParticle.java | package com.simibubi.create.content.fluids.particle;
import org.joml.Quaternionf;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.simibubi.create.AllBlocks;
import com.simibubi.create.content.processing.basin.BasinBlockEntity;
import com.simibubi.create.foundation.utility.VecHelper;
import io.github.fabricators_of_create.porting_lib_ufo.fluids.FluidStack;
import net.minecraft.client.Camera;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.BlockPos;
import net.minecraft.util.Mth;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.phys.Vec3;
public class BasinFluidParticle extends FluidStackParticle {
BlockPos basinPos;
Vec3 targetPos;
Vec3 centerOfBasin;
float yOffset;
public BasinFluidParticle(ClientLevel world, FluidStack fluid, double x, double y, double z, double vx, double vy,
double vz) {
super(world, fluid, x, y, z, vx, vy, vz);
gravity = 0;
xd = 0;
yd = 0;
zd = 0;
yOffset = world.random.nextFloat() * 1 / 32f;
y += yOffset;
quadSize = 0;
lifetime = 60;
Vec3 currentPos = new Vec3(x, y, z);
basinPos = BlockPos.containing(currentPos);
centerOfBasin = VecHelper.getCenterOf(basinPos);
if (vx != 0) {
lifetime = 20;
Vec3 centerOf = VecHelper.getCenterOf(basinPos);
Vec3 diff = currentPos.subtract(centerOf)
.multiply(1, 0, 1)
.normalize()
.scale(.375);
targetPos = centerOf.add(diff);
xo = x = centerOfBasin.x;
zo = z = centerOfBasin.z;
}
}
@Override
public void tick() {
super.tick();
quadSize = targetPos != null ? Math.max(1 / 32f, ((1f * age) / lifetime) / 8)
: 1 / 8f * (1 - ((Math.abs(age - (lifetime / 2)) / (1f * lifetime))));
if (age % 2 == 0) {
if (!AllBlocks.BASIN.has(level.getBlockState(basinPos))) {
remove();
return;
}
BlockEntity blockEntity = level.getBlockEntity(basinPos);
if (blockEntity instanceof BasinBlockEntity) {
float totalUnits = ((BasinBlockEntity) blockEntity).getTotalFluidUnits(0);
if (totalUnits < 1)
totalUnits = 0;
float fluidLevel = Mth.clamp(totalUnits / 2000, 0, 1);
y = 2 / 16f + basinPos.getY() + 12 / 16f * fluidLevel + yOffset;
}
}
if (targetPos != null) {
float progess = (1f * age) / lifetime;
Vec3 currentPos = centerOfBasin.add(targetPos.subtract(centerOfBasin)
.scale(progess));
x = currentPos.x;
z = currentPos.z;
}
}
@Override
public void render(VertexConsumer vb, Camera info, float pt) {
Quaternionf rotation = info.rotation();
Quaternionf prevRotation = new Quaternionf(rotation);
rotation.set(1, 0, 0, 1);
rotation.normalize();
super.render(vb, info, pt);
rotation.set(0, 0, 0, 1);
rotation.mul(prevRotation);
}
@Override
protected boolean canEvaporate() {
return false;
}
}
| 0 | 0.923544 | 1 | 0.923544 | game-dev | MEDIA | 0.912681 | game-dev | 0.958444 | 1 | 0.958444 |
jevonsflash/maui-samples | 4,914 | HoldDownButtonGroup/Controls/Bubbles.xaml.cs | using MauiSample.Common.Controls;
using Microsoft.Maui.Controls;
using SkiaSharp.Views.Maui;
namespace HoldDownButtonGroup.Controls;
public partial class Bubbles : ContentView
{
private Size targetSize = new Size(80, 80);
private static readonly Random rnd = new Random();
public PitGrid CurrentPitView { get; set; }
public Bubbles()
{
InitializeComponent();
}
public static readonly BindableProperty BubbleSizeProperty =
BindableProperty.Create("BubbleSize", typeof(double), typeof(Bubbles), 20.0, propertyChanged: (bindable, oldValue, newValue) =>
{
});
public double BubbleSize
{
get { return (double)GetValue(BubbleSizeProperty); }
set { SetValue(BubbleSizeProperty, value); }
}
public static readonly BindableProperty BubbleCntProperty =
BindableProperty.Create("BubbleCnt", typeof(double), typeof(Bubbles), 60.0, propertyChanged: (bindable, oldValue, newValue) =>
{
});
public double BubbleCnt
{
get { return (double)GetValue(BubbleCntProperty); }
set { SetValue(BubbleCntProperty, value); }
}
public static readonly BindableProperty BrushProperty =
BindableProperty.Create("Brush", typeof(Brush), typeof(Bubbles), SolidColorBrush.Red, propertyChanged: (bindable, oldValue, newValue) =>
{
});
public Brush Brush
{
get { return (Brush)GetValue(BrushProperty); }
set { SetValue(BrushProperty, value); }
}
private Animation InitAnimation(Bubble element, Size targetSize, bool isOnTop = true)
{
var offsetAnimation = new Animation();
if (targetSize == default)
{
targetSize = element.DesiredSize;
}
var easing = Easing.Linear;
var originX = PitContentLayout.Width / 2;
var originY = PitContentLayout.Height / 2;
var targetX = rnd.Next(-(int)targetSize.Width, (int)targetSize.Width) + (int)targetSize.Width / 2 + originX;
var targetY = isOnTop ? rnd.Next(-(int)(targetSize.Height * 1.5), 0) + (int)targetSize.Height / 2 + originY :
rnd.Next(0, (int)(targetSize.Height * 1.5)) + (int)targetSize.Height / 2 + originY
;
var offsetX = targetX - originX;
var offsetY = targetY - originY;
var offsetAnimation1 = new Animation(v => element.TranslationX = v, originX - targetSize.Width / 2, targetX - targetSize.Width / 2, easing);
var offsetAnimation2 = new Animation(v => element.TranslationY = v, originY - targetSize.Height / 2, targetY - targetSize.Height / 2, easing);
offsetAnimation.Add(0.2, 0.8, offsetAnimation1);
offsetAnimation.Add(0.2, 0.8, offsetAnimation2);
offsetAnimation.Add(0, 1, element.BoxAnimation);
offsetAnimation.Finished = () =>
{
element.TranslationX = originX;
element.TranslationY = originY;
element.Rotation = 0;
};
return offsetAnimation;
}
private void ContentView_SizeChanged(object sender, EventArgs e)
{
foreach (var item in this.PitContentLayout.Children)
{
if (item is Bubble)
{
Init(item as Bubble);
}
}
}
public void StartAnimation()
{
Content.AbortAnimation("ReshapeAnimations");
var offsetAnimationGroup = new Animation();
foreach (var item in this.PitContentLayout.Children)
{
if (item is Bubble)
{
var isOntop = this.PitContentLayout.Children.IndexOf(item) > this.PitContentLayout.Children.Count / 2;
var currentAnimation = InitAnimation(item as Bubble, targetSize, isOntop);
offsetAnimationGroup.Add(0, 1, currentAnimation);
}
}
offsetAnimationGroup.Commit(this, "ReshapeAnimations", 16, 400);
}
private void Init(VisualElement element)
{
var originX = (PitContentLayout.Width - BubbleSize) / 2;
var originY = (PitContentLayout.Height - BubbleSize) / 2;
element.TranslationX = originX;
element.TranslationY = originY;
element.Rotation = 0;
}
private void ContentView_Loaded(object sender, EventArgs e)
{
SpawnBubbles();
}
public void SpawnBubbles()
{
this.PitContentLayout.Clear();
for (int i = 0; i < BubbleCnt; i++)
{
var currentBox = new Bubble();
currentBox.FillColor = i % 2 == 0 ? this.Brush : SolidColorBrush.Transparent;
currentBox.BorderColor = this.Brush;
currentBox.HeightRequest = BubbleSize;
currentBox.WidthRequest = BubbleSize;
currentBox.HorizontalOptions = LayoutOptions.Start;
currentBox.VerticalOptions = LayoutOptions.Start;
this.PitContentLayout.Add(currentBox);
}
}
}
| 0 | 0.866615 | 1 | 0.866615 | game-dev | MEDIA | 0.495236 | game-dev,graphics-rendering | 0.973674 | 1 | 0.973674 |
EliotVU/Unreal-Library | 2,477 | src/Branch/UE2/Eon/EonPackageSerializer.cs | namespace UELib.Branch.UE2.Eon;
public class EonPackageSerializer : PackageSerializerBase
{
public override void Serialize(IUnrealStream stream, UNameTableItem item) => item.Serialize(stream);
public override void Deserialize(IUnrealStream stream, UNameTableItem item) => item.Deserialize(stream);
public override void Serialize(IUnrealStream stream, UImportTableItem item)
{
// OuterIndex changed to 16 bits.
if (stream.Version < 141)
{
item.Serialize(stream);
return;
}
stream.Write(item.ClassPackageName);
stream.Write(item.ClassName);
stream.Write((short)item.OuterIndex);
stream.Write(item.ObjectName);
}
public override void Deserialize(IUnrealStream stream, UImportTableItem item)
{
// OuterIndex changed to 16 bits.
if (stream.Version < 141)
{
item.Deserialize(stream);
return;
}
item.ClassPackageName = stream.ReadNameReference();
item.ClassName = stream.ReadNameReference();
item.OuterIndex = stream.ReadInt16();
item.ObjectName = stream.ReadNameReference();
}
public override void Serialize(IUnrealStream stream, UExportTableItem item)
{
// OuterIndex changed to 16 bits.
if (stream.Version < 141)
{
item.Serialize(stream);
return;
}
stream.WriteIndex((short)item.ClassIndex);
stream.WriteIndex((short)item.SuperIndex);
stream.Write((short)item.OuterIndex);
stream.Write(item.ObjectName);
stream.Write((uint)item.ObjectFlags);
stream.WriteIndex(item.SerialSize);
if (item.SerialSize > 0)
{
stream.WriteIndex(item.SerialOffset);
}
}
public override void Deserialize(IUnrealStream stream, UExportTableItem item)
{
// OuterIndex changed to 16 bits.
if (stream.Version < 141)
{
item.Deserialize(stream);
return;
}
item.ClassIndex = (short)stream.ReadIndex();
item.SuperIndex = (short)stream.ReadIndex();
item.OuterIndex = stream.ReadInt16();
item.ObjectName = stream.ReadNameReference();
item.ObjectFlags = stream.ReadUInt32();
item.SerialSize = stream.ReadIndex();
if (item.SerialSize > 0)
{
item.SerialOffset = stream.ReadIndex();
}
}
}
| 0 | 0.792387 | 1 | 0.792387 | game-dev | MEDIA | 0.690796 | game-dev | 0.814712 | 1 | 0.814712 |
IzzelAliz/Arclight | 1,264 | arclight-common/src/main/java/io/izzel/arclight/common/mixin/core/world/level/block/ChestBlockMixin.java | package io.izzel.arclight.common.mixin.core.world.level.block;
import net.minecraft.core.BlockPos;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.ChestBlock;
import net.minecraft.world.level.block.DoubleBlockCombiner;
import net.minecraft.world.level.block.entity.ChestBlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import javax.annotation.Nullable;
import java.util.Optional;
@Mixin(ChestBlock.class)
public abstract class ChestBlockMixin {
// @formatter:off
@Shadow public abstract DoubleBlockCombiner.NeighborCombineResult<? extends ChestBlockEntity> combine(BlockState pState, Level pLevel, BlockPos pPos, boolean pOverride);
@Shadow @Final private static DoubleBlockCombiner.Combiner<ChestBlockEntity, Optional<MenuProvider>> MENU_PROVIDER_COMBINER;
// @formatter:on
@Nullable
public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos, boolean ignoreObstructions) {
return this.combine(state, level, pos, ignoreObstructions).apply(MENU_PROVIDER_COMBINER).orElse(null);
}
}
| 0 | 0.773383 | 1 | 0.773383 | game-dev | MEDIA | 0.999315 | game-dev | 0.655878 | 1 | 0.655878 |
AgriCraft/AgriCraft | 2,101 | src/main/java/com/infinityraider/agricraft/impl/v1/requirement/SeasonPlugin.java | package com.infinityraider.agricraft.impl.v1.requirement;
import com.google.common.collect.Lists;
import com.infinityraider.agricraft.AgriCraft;
import com.infinityraider.agricraft.api.v1.plugin.IAgriPlugin;
import com.infinityraider.agricraft.api.v1.requirement.AgriSeason;
import com.infinityraider.agricraft.api.v1.requirement.IAgriSeasonLogic;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraftforge.fml.ModList;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.function.BiFunction;
public abstract class SeasonPlugin implements IAgriPlugin {
private static final List<String> SEASON_MODS = Lists.newArrayList();
public static List<String> getSeasonMods() {
return SEASON_MODS;
}
protected SeasonPlugin() {
SEASON_MODS.add(this.getId());
}
public static String getConfigComment() {
StringBuilder builder = new StringBuilder();
for(int i = 0; i < SEASON_MODS.size(); i++) {
if(i == 0) {
builder.append("\"");
} else {
builder.append(", \"");
}
builder.append(SEASON_MODS.get(i));
builder.append("\"");
}
return builder.toString();
}
@Override
public final boolean isEnabled() {
return ModList.get().isLoaded(this.getId());
}
@Override
public final void registerSeasonLogic(@Nonnull IAgriSeasonLogic seasonLogic) {
if(SeasonLogic.getInstance().getOwner() == null) {
if(SEASON_MODS.stream().filter(id -> !id.equalsIgnoreCase(this.getId())).anyMatch(id -> ModList.get().isLoaded(id))) {
if(AgriCraft.instance.getConfig().getSeasonLogicMod().equalsIgnoreCase(this.getId())) {
SeasonLogic.getInstance().claim(this, this.getSeasonGetter());
}
} else {
SeasonLogic.getInstance().claim(this, this.getSeasonGetter());
}
}
}
protected abstract BiFunction<Level, BlockPos, AgriSeason> getSeasonGetter();
}
| 0 | 0.946958 | 1 | 0.946958 | game-dev | MEDIA | 0.967576 | game-dev | 0.986065 | 1 | 0.986065 |
ProjectIgnis/CardScripts | 3,032 | official/c11489642.lua | --トライアングル-O
--Triangle O
--Scripted by Hatter
local s,id=GetID()
function s.initial_effect(c)
--Destroy all cards on the field
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,id)
e1:SetCondition(s.descon)
e1:SetTarget(s.destg)
e1:SetOperation(s.desop)
c:RegisterEffect(e1)
--Shuffle 1 "Crystal Skull", 1 "Ashoka Pillar", and 1 "Cabrera Stone" into the Deck
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_TODECK+CATEGORY_DRAW)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetRange(LOCATION_GRAVE)
e2:SetCountLimit(1,id)
e2:SetCost(Cost.SelfBanish)
e2:SetTarget(s.tdtg)
e2:SetOperation(s.tdop)
c:RegisterEffect(e2)
end
s.listed_names={7903368,58996839,84384943}
function s.descon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(aux.FaceupFilter(Card.IsCode,7903368),tp,LOCATION_ONFIELD,0,1,nil)
and Duel.IsExistingMatchingCard(aux.FaceupFilter(Card.IsCode,58996839),tp,LOCATION_ONFIELD,0,1,nil)
and Duel.IsExistingMatchingCard(aux.FaceupFilter(Card.IsCode,84384943),tp,LOCATION_ONFIELD,0,1,nil)
end
function s.destg(e,tp,eg,ep,ev,re,r,rp,chk)
local sg=Duel.GetMatchingGroup(nil,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,e:GetHandler())
if chk==0 then return #sg>0 end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,sg,#sg,0,0)
end
function s.desop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local sg=Duel.GetMatchingGroup(nil,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,c)
if #sg>0 then
Duel.Destroy(sg,REASON_EFFECT)
end
--Reflect effect damage
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,2))
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CLIENT_HINT)
e1:SetCode(EFFECT_REFLECT_DAMAGE)
e1:SetTargetRange(1,0)
e1:SetValue(function(e,_,_,r) return (r&REASON_EFFECT)==REASON_EFFECT end)
e1:SetReset(RESET_PHASE|PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function s.tdfilter(c,e)
return c:IsCode(7903368,58996839,84384943) and c:IsAbleToDeck() and c:IsCanBeEffectTarget(e)
end
function s.tdtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
local c=e:GetHandler()
local g=Duel.GetMatchingGroup(s.tdfilter,tp,LOCATION_GRAVE,0,c,e)
if chk==0 then return Duel.IsPlayerCanDraw(tp,3) and aux.SelectUnselectGroup(g,e,tp,3,3,aux.dncheck,0) end
local g=aux.SelectUnselectGroup(g,e,tp,3,3,aux.dncheck,1,tp,HINTMSG_TODECK)
Duel.SetTargetCard(g)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,3,0,0)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,3)
end
function s.tdop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetTargetCards(e)
if #g>0 and Duel.SendtoDeck(g,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)>0
and g:IsExists(Card.IsLocation,1,nil,LOCATION_DECK|LOCATION_EXTRA) then
if g:IsExists(Card.IsLocation,1,nil,LOCATION_DECK) then
Duel.ShuffleDeck(tp)
end
Duel.BreakEffect()
Duel.Draw(tp,3,REASON_EFFECT)
end
end | 0 | 0.874448 | 1 | 0.874448 | game-dev | MEDIA | 0.978751 | game-dev | 0.951918 | 1 | 0.951918 |
Mafuyu33/neomafishmod | 2,006 | src/main/java/com/mafuyu33/neomafishmod/mixin/itemmixin/entityitemrenderer/lightningitemrenderer/ItemRendererMixin.java | package com.mafuyu33.neomafishmod.mixin.itemmixin.entityitemrenderer.lightningitemrenderer;
import com.mafuyu33.neomafishmod.NeoMafishMod;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.entity.ItemRenderer;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LightningBolt;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ItemRenderer.class)
public class ItemRendererMixin {
@Unique
private final Minecraft mc = Minecraft.getInstance();
// @Inject(method = "render",at= @At("HEAD"),cancellable = true)
// public void renderItem(
// ItemStack itemStack,
// ItemDisplayContext displayContext,
// boolean leftHand,
// PoseStack poseStack,
// MultiBufferSource bufferSource,
// int combinedLight,
// int combinedOverlay,
// BakedModel p_model,
// CallbackInfo ci
// ){
// if (BuiltInRegistries.ITEM.getKey(itemStack.getItem()).equals(ResourceLocation.fromNamespaceAndPath(NeoMafishMod.MODID,"lightning_item")))
// {
// ci.cancel();
// LightningBolt lightningBolt = new LightningBolt(EntityType.LIGHTNING_BOLT,mc.level);
// poseStack.pushPose();
//
// poseStack.scale(0.5f,0.5f,0.5f);
// mc.getEntityRenderDispatcher().render(lightningBolt,0,0,0,0f,1f,poseStack,bufferSource,combinedLight);
// poseStack.popPose();
// }
//
// }
}
| 0 | 0.732874 | 1 | 0.732874 | game-dev | MEDIA | 0.983253 | game-dev | 0.845095 | 1 | 0.845095 |
hotstreams/limitless-engine | 5,289 | include/limitless/fx/effect_builder.hpp | #pragma once
#include <limitless/fx/emitters/unique_emitter.hpp>
#include <limitless/fx/emitters/emitter_spawn.hpp>
#include <limitless/fx/modules/distribution.hpp>
namespace Limitless {
class EffectInstance;
class AbstractMesh;
class AbstractModel;
class Context;
class Assets;
class EmitterSerializer;
namespace ms {
class Material;
}
}
namespace Limitless::fx {
class EffectBuilder {
private:
std::shared_ptr<EffectInstance> effect;
std::string effect_name;
std::string last_emitter;
Assets& assets;
template<typename Emitter>
EffectBuilder& setModules(decltype(Emitter::modules)&& modules);
EffectBuilder& setSpawn(EmitterSpawn&& spawn);
template<template<typename P> class M, typename... Args>
void addModule(Args&&... args);
template<typename Emitter>
UniqueEmitterShader getUniqueEmitterShader(const Emitter& emitter) const noexcept;
friend class Limitless::EmitterSerializer;
public:
explicit EffectBuilder(Assets& assets) noexcept;
~EffectBuilder() = default;
EffectBuilder& setBurstCount(std::unique_ptr<Distribution<uint32_t>> burst_count);
EffectBuilder& setMaterial(std::shared_ptr<ms::Material> material);
EffectBuilder& setMesh(std::shared_ptr<AbstractMesh> mesh);
EffectBuilder& setDuration(std::chrono::duration<float> duration);
EffectBuilder& setLocalPosition(const glm::vec3& local_position);
EffectBuilder& setLocalRotation(const glm::quat& local_rotation);
EffectBuilder& setSpawnMode(EmitterSpawn::Mode mode);
EffectBuilder& setLocalSpace(bool _local_space);
EffectBuilder& setEmitterType(AbstractEmitter::Type type);
EffectBuilder& setMaxCount(uint64_t max_count);
EffectBuilder& setSpawnRate(float spawn_rate);
EffectBuilder& setLoops(int loops);
EffectBuilder& create(std::string name);
template<typename Emitter>
EffectBuilder& createEmitter(const std::string& name);
EffectBuilder& addInitialLocation(std::unique_ptr<Distribution<glm::vec3>> distribution);
EffectBuilder& addInitialRotation(std::unique_ptr<Distribution<glm::vec3>> distribution);
EffectBuilder& addInitialVelocity(std::unique_ptr<Distribution<glm::vec3>> distribution);
EffectBuilder& addInitialColor(std::unique_ptr<Distribution<glm::vec4>> distribution);
EffectBuilder& addInitialSize(std::unique_ptr<Distribution<float>> distribution);
EffectBuilder& addInitialSize(std::unique_ptr<Distribution<glm::vec3>> distribution);
EffectBuilder& addInitialAcceleration(std::unique_ptr<Distribution<glm::vec3>> distribution);
EffectBuilder& addInitialMeshLocation(std::shared_ptr<AbstractMesh> mesh, const glm::vec3& scale, const glm::vec3& rotation);
EffectBuilder& addInitialMeshLocation(std::shared_ptr<AbstractModel> mesh, const glm::vec3& scale, const glm::vec3& rotation);
EffectBuilder& addInitialMeshLocation(std::shared_ptr<AbstractMesh> mesh);
EffectBuilder& addInitialMeshLocation(std::shared_ptr<AbstractModel> mesh);
EffectBuilder& addMeshLocationAttachment(std::shared_ptr<AbstractMesh> mesh);
EffectBuilder& addMeshLocationAttachment(std::shared_ptr<AbstractModel> mesh);
EffectBuilder& addSubUV(const glm::vec2& size, float fps, const glm::vec2& frame_count);
EffectBuilder& addVelocityByLife(std::unique_ptr<Distribution<glm::vec3>> distribution);
EffectBuilder& addColorByLife(std::unique_ptr<Distribution<glm::vec4>> distribution);
EffectBuilder& addRotationRate(std::unique_ptr<Distribution<glm::vec3>> distribution);
EffectBuilder& addSizeByLife(std::unique_ptr<Distribution<float>> distribution);
EffectBuilder& addSizeByLife(std::unique_ptr<Distribution<glm::vec3>> distribution);
EffectBuilder& addLifetime(std::unique_ptr<Distribution<float>> distribution);
EffectBuilder& addTime();
EffectBuilder& addBeamInitialTarget(std::unique_ptr<Distribution<glm::vec3>> distribution);
EffectBuilder& addBeamInitialDisplacement(std::unique_ptr<Distribution<float>> distribution);
EffectBuilder& addBeamInitialOffset(std::unique_ptr<Distribution<float>> distribution);
EffectBuilder& addBeamInitialRebuild(std::unique_ptr<Distribution<float>> distribution);
EffectBuilder& addBeamSpeed(std::unique_ptr<Distribution<float>> distribution);
EffectBuilder& addCustomMaterial(std::unique_ptr<Distribution<float>> p1,
std::unique_ptr<Distribution<float>> p2,
std::unique_ptr<Distribution<float>> p3,
std::unique_ptr<Distribution<float>> p4);
EffectBuilder& addCustomMaterialByLife(std::unique_ptr<Distribution<float>> p1,
std::unique_ptr<Distribution<float>> p2,
std::unique_ptr<Distribution<float>> p3,
std::unique_ptr<Distribution<float>> p4);
std::shared_ptr<EffectInstance> build();
};
}
| 0 | 0.617373 | 1 | 0.617373 | game-dev | MEDIA | 0.533295 | game-dev | 0.525917 | 1 | 0.525917 |
l0y/learnjava6e | 4,477 | ch07/examples/game/Physicist.java | package ch07.examples.game;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static java.awt.Color.*;
/**
* Our player class. A physicist has an apple that they can throw in addition
* to implementing the basic methods for GamePiece. We can also set a custom
* color in case you build on the game and allow multiple physicists to be
* on the screen at the same time.
*/
public class Physicist implements GamePiece {
Color color;
int centerX, centerY;
Apple aimingApple;
float aimingAngle;
float aimingForce;
Field field;
// Some helpers for optimizing the draw() method that can be called many, many times
int x, y;
// Boundary helpers
private final int physicistHeight = (int)(1.5 * Field.PHYSICIST_SIZE_IN_PIXELS);
private Rectangle boundingBox;
/**
* Create a default, blue physicist
*/
public Physicist() {
this(BLUE);
}
/**
* Create a Physicist of the given color
*/
public Physicist(Color color) {
setColor(color);
aimingAngle = 90.0f;
aimingForce = 50.0f;
getNewApple();
}
public void setAimingAngle(Float angle) {
aimingAngle = angle;
}
public void setAimingForce(Float force) {
if (force < 0) {
force = 0.0f;
}
aimingForce = force;
}
/**
* Sets the color for the physicist.
*
* @param color
*/
public void setColor(Color color) {
this.color = color;
}
@Override
public void setPosition(int x, int y) {
// Our position is based on the center of our dome,
// but it will be drawn from the upper left corner.
// Figure out the distance of that gap
int offset = (int)(Field.PHYSICIST_SIZE_IN_PIXELS / 2.0f);
this.centerX = x;
this.centerY = y;
this.x = x - offset;
this.y = y - offset;
boundingBox = new Rectangle(x, y, Field.PHYSICIST_SIZE_IN_PIXELS, physicistHeight);
}
@Override
public int getPositionX() {
return centerX;
}
@Override
public int getPositionY() {
return centerY;
}
@Override
public Rectangle getBoundingBox() {
return boundingBox;
}
/**
* Sets the active field once our physicist is being displayed.
*
* @param field Active game field
*/
public void setField(Field field) {
this.field = field;
}
/**
* Take the current apple away from the physicist. Returns the apple for
* use in animating on the field. Note that if there is no current apple being
* aimed, null is returned.
*
* @return the current apple (if any) being aimed
*/
public Apple takeApple() {
Apple myApple = aimingApple;
aimingApple = null;
return myApple;
}
/**
* Get a new apple ready if we need one. Do not discard an existing apple.
*/
public void getNewApple() {
// Don't drop the current apple if we already have one!
if (aimingApple == null) {
aimingApple = new Apple(this);
}
}
@Override
public void draw(Graphics g) {
// Make sure our physicist is the right color, then draw the semi-circle and box
g.setColor(color);
g.fillArc(x, y, Field.PHYSICIST_SIZE_IN_PIXELS, Field.PHYSICIST_SIZE_IN_PIXELS, 0, 180);
g.fillRect(x, centerY, Field.PHYSICIST_SIZE_IN_PIXELS, Field.PHYSICIST_SIZE_IN_PIXELS);
// Do we have an apple to draw as well?
if (aimingApple != null) {
// Yes. Position the center of the apple on the edge of our semi-circle.
// Use the current aimingAngle to determine where on the edge.
double angleInRadians = Math.toRadians(aimingAngle);
double radius = Field.PHYSICIST_SIZE_IN_PIXELS / 2.0;
int aimingX = centerX + (int)(Math.cos(angleInRadians) * radius);
int aimingY = centerY - (int)(Math.sin(angleInRadians) * radius);
aimingApple.setPosition(aimingX, aimingY);
aimingApple.draw(g);
}
}
@Override
public boolean isTouching(GamePiece otherPiece) {
if (this == otherPiece) {
// By definition we don't collide with ourselves
return false;
}
return GameUtilities.doBoxesIntersect(boundingBox, otherPiece.getBoundingBox());
}
}
| 0 | 0.74298 | 1 | 0.74298 | game-dev | MEDIA | 0.455193 | game-dev,graphics-rendering | 0.741212 | 1 | 0.741212 |
Straw1997/UnityCustomShaderGUI | 4,397 | CustomShaderGUI/Library/PackageCache/com.unity.timeline@1.4.5/Editor/Recording/TimelineRecordingContextualResponder.cs | using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;
namespace UnityEditor.Timeline
{
class TimelineRecordingContextualResponder : IAnimationContextualResponder
{
public WindowState state { get; internal set; }
public TimelineRecordingContextualResponder(WindowState _state)
{
state = _state;
}
//Unsupported stuff
public bool HasAnyCandidates() { return false; }
public bool HasAnyCurves() {return false; }
public void AddCandidateKeys() {}
public void AddAnimatedKeys() {}
public bool IsAnimatable(PropertyModification[] modifications)
{
// search playable assets
for (int i = 0; i < modifications.Length; i++)
{
var iAsset = modifications[i].target as IPlayableAsset;
if (iAsset != null)
{
var curvesOwner = AnimatedParameterUtility.ToCurvesOwner(iAsset, state.editSequence.asset);
if (curvesOwner != null && curvesOwner.HasAnyAnimatableParameters() && curvesOwner.IsParameterAnimatable(modifications[i].propertyPath))
return true;
}
}
// search recordable game objects
foreach (var gameObject in TimelineRecording.GetRecordableGameObjects(state))
{
for (int i = 0; i < modifications.Length; ++i)
{
var modification = modifications[i];
if (AnimationWindowUtility.PropertyIsAnimatable(modification.target, modification.propertyPath, gameObject))
return true;
}
}
return false;
}
public bool IsEditable(Object targetObject)
{
return true; // i.e. all animatable properties are editable
}
public bool KeyExists(PropertyModification[] modifications)
{
if (modifications.Length == 0 || modifications[0].target == null)
return false;
return TimelineRecording.HasKey(modifications, modifications[0].target, state);
}
public bool CandidateExists(PropertyModification[] modifications)
{
return true;
}
public bool CurveExists(PropertyModification[] modifications)
{
if (modifications.Length == 0 || modifications[0].target == null)
return false;
return TimelineRecording.HasCurve(modifications, modifications[0].target, state);
}
public void AddKey(PropertyModification[] modifications)
{
TimelineRecording.AddKey(modifications, state);
state.Refresh();
}
public void RemoveKey(PropertyModification[] modifications)
{
if (modifications.Length == 0)
return;
var target = modifications[0].target;
if (target == null)
return;
TimelineRecording.RemoveKey(modifications[0].target, modifications, state);
var curvesOwner = target as ICurvesOwner;
if (curvesOwner != null)
curvesOwner.SanitizeCurvesData();
state.Refresh();
}
public void RemoveCurve(PropertyModification[] modifications)
{
if (modifications.Length == 0)
return;
var target = modifications[0].target;
if (target == null)
return;
TimelineRecording.RemoveCurve(target, modifications, state);
var curvesOwner = target as ICurvesOwner;
if (curvesOwner != null)
curvesOwner.SanitizeCurvesData();
state.Refresh();
}
public void GoToNextKeyframe(PropertyModification[] modifications)
{
if (modifications.Length == 0 || modifications[0].target == null)
return;
TimelineRecording.NextKey(modifications[0].target, modifications, state);
state.Refresh();
}
public void GoToPreviousKeyframe(PropertyModification[] modifications)
{
TimelineRecording.PrevKey(modifications[0].target, modifications, state);
state.Refresh();
}
}
}
| 0 | 0.914296 | 1 | 0.914296 | game-dev | MEDIA | 0.885665 | game-dev | 0.829876 | 1 | 0.829876 |
hamvocke/doppelkopf | 3,931 | src/models/round.ts | import { Trick } from "@/models/trick";
import { RingQueue } from "@/models/ringQueue";
import { Score } from "@/models/score";
import { options } from "@/models/options";
import { notifier } from "@/models/notifier";
import { extras } from "@/models/extras";
import { PartyName, findParties, Party } from "@/models/party";
import { Player } from "./player";
import { Scorecard } from "./scorecard";
import { findGameType, GameType } from "./reservations";
export enum RoundState {
AskingForReservations,
Started,
Finished,
}
export class Round {
parties: { [name: string]: Party };
scorecard: Scorecard;
score?: Score;
roundState: RoundState;
gameType?: GameType;
previousTrick?: Trick;
currentTrick: Trick;
playerOrder: RingQueue<Player>;
constructor(
players: Player[] = [],
scorecard: any = {},
openingPlayer: Player
) {
this.playerOrder = new RingQueue(players);
this.playerOrder.prioritize(openingPlayer);
this.parties = findParties(players);
this.scorecard = scorecard;
this.score = undefined;
this.roundState = RoundState.AskingForReservations;
this.currentTrick = this.nextTrick();
}
startRound() {
if (this.roundState !== RoundState.AskingForReservations) {
return;
}
this.playerOrder.asList().forEach((p) => p.promptForReservation());
const gameType = findGameType(this.playerOrder);
this.gameType = gameType;
this.roundState = RoundState.Started;
// send notification ("alle gesund", "Hubert spielt ein Solo")
// sort cards on hand
// set trumps for current round
this.nextMove();
}
nextTrick() {
this.previousTrick = this.currentTrick;
const trick = new Trick(this.playerOrder.asList());
if (this.cardsLeft() <= this.playerOrder.length()) {
trick.setLastTrickInRound();
}
return trick;
}
nextPlayer() {
this.playerOrder.next();
}
waitingForPlayer() {
return this.playerOrder.current();
}
async nextMove() {
if (this.waitingForPlayer().isHuman) {
return;
}
if (this.currentTrick.isFinished() || this.isFinished()) {
return;
}
await this.waitingForPlayer().autoplay();
}
noMoreCardsLeft() {
return this.cardsLeft() === 0;
}
cardsLeft() {
const sumCardsFn = (acc: number, player: Player) => acc + player.numberOfCardsLeft();
return this.playerOrder.asList().reduce(sumCardsFn, 0);
}
isFinished() {
return this.roundState === RoundState.Finished;
}
async finishTrick() {
await this.evaluateLatestTrick();
this.currentTrick = this.nextTrick();
if (options.autoplay === true) {
this.nextMove();
}
}
async evaluateLatestTrick() {
const winner = this.currentTrick.winner();
if (!winner) {
return;
}
// TODO: remove this, migrate to an event-based approach (see comment in trick.ts)
this.playerOrder
.asList()
.forEach((player) =>
player.memory.memorizeTrick(
this.currentTrick.id,
this.currentTrick.baseCard()!,
winner
)
);
winner.win(this.currentTrick);
this.playerOrder.prioritize(winner);
await this.showExtras();
}
async showExtras() {
for (const extra of this.currentTrick.extras()) {
switch (extra) {
case extras.doppelkopf:
// todo i18n
await notifier.flash("Doppelkopf");
break;
}
}
}
async finishRound() {
if (!this.noMoreCardsLeft()) {
throw new Error(`Can't finish a round before all cards have been played`);
}
await this.evaluateLatestTrick();
this.currentTrick = this.nextTrick();
this.parties = findParties(this.playerOrder.asList());
this.score = new Score(
this.parties[PartyName.Re],
this.parties[PartyName.Kontra]
);
this.scorecard.addScore(this.score);
this.roundState = RoundState.Finished;
}
}
| 0 | 0.937997 | 1 | 0.937997 | game-dev | MEDIA | 0.491463 | game-dev | 0.987326 | 1 | 0.987326 |
Sigma-Skidder-Team/SigmaRemap | 31,034 | src/main/java/mapped/Class9601.java | package mapped;
import com.google.common.collect.Lists;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CompletableFuture;
import net.minecraft.command.CommandSource;
import net.minecraft.command.ISuggestionProvider;
import net.minecraft.scoreboard.Scoreboard;
import net.minecraft.scoreboard.ServerScoreboard;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextComponentUtils;
import net.minecraft.util.text.TranslationTextComponent;
public class Class9601 {
private static final SimpleCommandExceptionType field44912 = new SimpleCommandExceptionType(
new TranslationTextComponent("commands.scoreboard.objectives.add.duplicate")
);
private static final SimpleCommandExceptionType field44913 = new SimpleCommandExceptionType(
new TranslationTextComponent("commands.scoreboard.objectives.display.alreadyEmpty")
);
private static final SimpleCommandExceptionType field44914 = new SimpleCommandExceptionType(
new TranslationTextComponent("commands.scoreboard.objectives.display.alreadySet")
);
private static final SimpleCommandExceptionType field44915 = new SimpleCommandExceptionType(
new TranslationTextComponent("commands.scoreboard.players.enable.failed")
);
private static final SimpleCommandExceptionType field44916 = new SimpleCommandExceptionType(
new TranslationTextComponent("commands.scoreboard.players.enable.invalid")
);
private static final Dynamic2CommandExceptionType field44917 = new Dynamic2CommandExceptionType(
(var0, var1) -> new TranslationTextComponent("commands.scoreboard.players.get.null", var0, var1)
);
public static void method37271(CommandDispatcher<CommandSource> var0) {
var0.register(
(LiteralArgumentBuilder)((LiteralArgumentBuilder)((LiteralArgumentBuilder) Commands.method18839("scoreboard").requires(var0x -> var0x.method20129(2)))
.then(
((LiteralArgumentBuilder)((LiteralArgumentBuilder)((LiteralArgumentBuilder)((LiteralArgumentBuilder) Commands.method18839("objectives")
.then(Commands.method18839("list").executes(var0x -> method37290((CommandSource)var0x.getSource()))))
.then(
Commands.method18839("add")
.then(
Commands.method18840("objective", StringArgumentType.word())
.then(
((RequiredArgumentBuilder) Commands.method18840("criteria", Class8371.method29322())
.executes(
var0x -> method37289(
(CommandSource)var0x.getSource(),
StringArgumentType.getString(var0x, "objective"),
Class8371.method29323(var0x, "criteria"),
new StringTextComponent(StringArgumentType.getString(var0x, "objective"))
)
))
.then(
Commands.method18840("displayName", Class8010.method27395())
.executes(
var0x -> method37289(
(CommandSource)var0x.getSource(),
StringArgumentType.getString(var0x, "objective"),
Class8371.method29323(var0x, "criteria"),
Class8010.method27394(var0x, "displayName")
)
)
)
)
)
))
.then(
Commands.method18839("modify")
.then(
((RequiredArgumentBuilder) Commands.method18840("objective", Class9263.method34860())
.then(
Commands.method18839("displayname")
.then(
Commands.method18840("displayName", Class8010.method27395())
.executes(
var0x -> method37286(
(CommandSource)var0x.getSource(),
Class9263.method34861(var0x, "objective"),
Class8010.method27394(var0x, "displayName")
)
)
)
))
.then(method37272())
)
))
.then(
Commands.method18839("remove")
.then(
Commands.method18840("objective", Class9263.method34860())
.executes(var0x -> method37288((CommandSource)var0x.getSource(), Class9263.method34861(var0x, "objective")))
)
))
.then(
Commands.method18839("setdisplay")
.then(
((RequiredArgumentBuilder) Commands.method18840("slot", Class9639.method37566())
.executes(var0x -> method37284((CommandSource)var0x.getSource(), Class9639.method37567(var0x, "slot"))))
.then(
Commands.method18840("objective", Class9263.method34860())
.executes(
var0x -> method37285(
(CommandSource)var0x.getSource(), Class9639.method37567(var0x, "slot"), Class9263.method34861(var0x, "objective")
)
)
)
)
)
))
.then(
((LiteralArgumentBuilder)((LiteralArgumentBuilder)((LiteralArgumentBuilder)((LiteralArgumentBuilder)((LiteralArgumentBuilder)((LiteralArgumentBuilder)((LiteralArgumentBuilder) Commands.method18839(
"players"
)
.then(
((LiteralArgumentBuilder) Commands.method18839("list").executes(var0x -> method37282((CommandSource)var0x.getSource())))
.then(
Commands.method18840("target", Class7591.method24862())
.suggests(Class7591.field32590)
.executes(var0x -> method37283((CommandSource)var0x.getSource(), Class7591.method24858(var0x, "target")))
)
))
.then(
Commands.method18839("set")
.then(
Commands.method18840("targets", Class7591.method24863())
.suggests(Class7591.field32590)
.then(
Commands.method18840("objective", Class9263.method34860())
.then(
Commands.method18840("score", IntegerArgumentType.integer())
.executes(
var0x -> method37279(
(CommandSource)var0x.getSource(),
Class7591.method24860(var0x, "targets"),
Class9263.method34862(var0x, "objective"),
IntegerArgumentType.getInteger(var0x, "score")
)
)
)
)
)
))
.then(
Commands.method18839("get")
.then(
Commands.method18840("target", Class7591.method24862())
.suggests(Class7591.field32590)
.then(
Commands.method18840("objective", Class9263.method34860())
.executes(
var0x -> method37274(
(CommandSource)var0x.getSource(),
Class7591.method24858(var0x, "target"),
Class9263.method34861(var0x, "objective")
)
)
)
)
))
.then(
Commands.method18839("add")
.then(
Commands.method18840("targets", Class7591.method24863())
.suggests(Class7591.field32590)
.then(
Commands.method18840("objective", Class9263.method34860())
.then(
Commands.method18840("score", IntegerArgumentType.integer(0))
.executes(
var0x -> method37280(
(CommandSource)var0x.getSource(),
Class7591.method24860(var0x, "targets"),
Class9263.method34862(var0x, "objective"),
IntegerArgumentType.getInteger(var0x, "score")
)
)
)
)
)
))
.then(
Commands.method18839("remove")
.then(
Commands.method18840("targets", Class7591.method24863())
.suggests(Class7591.field32590)
.then(
Commands.method18840("objective", Class9263.method34860())
.then(
Commands.method18840("score", IntegerArgumentType.integer(0))
.executes(
var0x -> method37281(
(CommandSource)var0x.getSource(),
Class7591.method24860(var0x, "targets"),
Class9263.method34862(var0x, "objective"),
IntegerArgumentType.getInteger(var0x, "score")
)
)
)
)
)
))
.then(
Commands.method18839("reset")
.then(
((RequiredArgumentBuilder) Commands.method18840("targets", Class7591.method24863())
.suggests(Class7591.field32590)
.executes(var0x -> method37277((CommandSource)var0x.getSource(), Class7591.method24860(var0x, "targets"))))
.then(
Commands.method18840("objective", Class9263.method34860())
.executes(
var0x -> method37278(
(CommandSource)var0x.getSource(),
Class7591.method24860(var0x, "targets"),
Class9263.method34861(var0x, "objective")
)
)
)
)
))
.then(
Commands.method18839("enable")
.then(
Commands.method18840("targets", Class7591.method24863())
.suggests(Class7591.field32590)
.then(
Commands.method18840("objective", Class9263.method34860())
.suggests((var0x, var1) -> method37273((CommandSource)var0x.getSource(), Class7591.method24860(var0x, "targets"), var1))
.executes(
var0x -> method37276(
(CommandSource)var0x.getSource(),
Class7591.method24860(var0x, "targets"),
Class9263.method34861(var0x, "objective")
)
)
)
)
))
.then(
Commands.method18839("operation")
.then(
Commands.method18840("targets", Class7591.method24863())
.suggests(Class7591.field32590)
.then(
Commands.method18840("targetObjective", Class9263.method34860())
.then(
Commands.method18840("operation", Class6888.method21028())
.then(
Commands.method18840("source", Class7591.method24863())
.suggests(Class7591.field32590)
.then(
Commands.method18840("sourceObjective", Class9263.method34860())
.executes(
var0x -> method37275(
(CommandSource)var0x.getSource(),
Class7591.method24860(var0x, "targets"),
Class9263.method34862(var0x, "targetObjective"),
Class6888.method21029(var0x, "operation"),
Class7591.method24860(var0x, "source"),
Class9263.method34861(var0x, "sourceObjective")
)
)
)
)
)
)
)
)
)
);
}
private static LiteralArgumentBuilder<CommandSource> method37272() {
LiteralArgumentBuilder var2 = Commands.method18839("rendertype");
for (Class2316 var6 : Class2316.values()) {
var2.then(
Commands.method18839(var6.method9088()).executes(var1 -> method37287((CommandSource)var1.getSource(), Class9263.method34861(var1, "objective"), var6))
);
}
return var2;
}
private static CompletableFuture<Suggestions> method37273(CommandSource var0, Collection<String> var1, SuggestionsBuilder var2) {
ArrayList var5 = Lists.newArrayList();
ServerScoreboard var6 = var0.getServer().method1409();
for (ScoreObjective var8 : var6.method20982()) {
if (var8.getCriteria() == Class9008.field41190) {
boolean var9 = false;
for (String var11 : var1) {
if (!var6.method20979(var11, var8) || var6.method20980(var11, var8).isLocked()) {
var9 = true;
break;
}
}
if (var9) {
var5.add(var8.method29336());
}
}
}
return ISuggestionProvider.suggest(var5, var2);
}
private static int method37274(CommandSource var0, String var1, ScoreObjective var2) throws CommandSyntaxException {
ServerScoreboard var5 = var0.getServer().method1409();
if (var5.method20979(var1, var2)) {
Score var6 = var5.method20980(var1, var2);
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.players.get.success", var1, var6.getScorePoints(), var2.method29340()), false);
return var6.getScorePoints();
} else {
throw field44917.create(var2.method29336(), var1);
}
}
private static int method37275(CommandSource var0, Collection<String> var1, ScoreObjective var2, Class8420 var3, Collection<String> var4, ScoreObjective var5) throws CommandSyntaxException {
ServerScoreboard var8 = var0.getServer().method1409();
int var9 = 0;
for (String var11 : var1) {
Score var12 = var8.method20980(var11, var2);
for (String var14 : var4) {
Score var15 = var8.method20980(var14, var5);
var3.method29592(var12, var15);
}
var9 += var12.getScorePoints();
}
if (var1.size() != 1) {
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.players.operation.success.multiple", var2.method29340(), var1.size()), true);
} else {
var0.sendFeedback(
new TranslationTextComponent("commands.scoreboard.players.operation.success.single", var2.method29340(), var1.iterator().next(), var9), true
);
}
return var9;
}
private static int method37276(CommandSource var0, Collection<String> var1, ScoreObjective var2) throws CommandSyntaxException {
if (var2.getCriteria() == Class9008.field41190) {
ServerScoreboard var5 = var0.getServer().method1409();
int var6 = 0;
for (String var8 : var1) {
Score var9 = var5.method20980(var8, var2);
if (var9.isLocked()) {
var9.setLocked(false);
var6++;
}
}
if (var6 != 0) {
if (var1.size() != 1) {
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.players.enable.success.multiple", var2.method29340(), var1.size()), true);
} else {
var0.sendFeedback(
new TranslationTextComponent("commands.scoreboard.players.enable.success.single", var2.method29340(), var1.iterator().next()), true
);
}
return var6;
} else {
throw field44915.create();
}
} else {
throw field44916.create();
}
}
private static int method37277(CommandSource var0, Collection<String> var1) {
ServerScoreboard var4 = var0.getServer().method1409();
for (String var6 : var1) {
var4.method20985(var6, (ScoreObjective)null);
}
if (var1.size() != 1) {
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.players.reset.all.multiple", var1.size()), true);
} else {
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.players.reset.all.single", var1.iterator().next()), true);
}
return var1.size();
}
private static int method37278(CommandSource var0, Collection<String> var1, ScoreObjective var2) {
ServerScoreboard var5 = var0.getServer().method1409();
for (String var7 : var1) {
var5.method20985(var7, var2);
}
if (var1.size() != 1) {
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.players.reset.specific.multiple", var2.method29340(), var1.size()), true);
} else {
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.players.reset.specific.single", var2.method29340(), var1.iterator().next()), true);
}
return var1.size();
}
private static int method37279(CommandSource var0, Collection<String> var1, ScoreObjective var2, int var3) {
ServerScoreboard var6 = var0.getServer().method1409();
for (String var8 : var1) {
Score var9 = var6.method20980(var8, var2);
var9.setScorePoints(var3);
}
if (var1.size() != 1) {
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.players.set.success.multiple", var2.method29340(), var1.size(), var3), true);
} else {
var0.sendFeedback(
new TranslationTextComponent("commands.scoreboard.players.set.success.single", var2.method29340(), var1.iterator().next(), var3), true
);
}
return var3 * var1.size();
}
private static int method37280(CommandSource var0, Collection<String> var1, ScoreObjective var2, int var3) {
ServerScoreboard var6 = var0.getServer().method1409();
int var7 = 0;
for (String var9 : var1) {
Score var10 = var6.method20980(var9, var2);
var10.setScorePoints(var10.getScorePoints() + var3);
var7 += var10.getScorePoints();
}
if (var1.size() != 1) {
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.players.add.success.multiple", var3, var2.method29340(), var1.size()), true);
} else {
var0.sendFeedback(
new TranslationTextComponent("commands.scoreboard.players.add.success.single", var3, var2.method29340(), var1.iterator().next(), var7), true
);
}
return var7;
}
private static int method37281(CommandSource var0, Collection<String> var1, ScoreObjective var2, int var3) {
ServerScoreboard var6 = var0.getServer().method1409();
int var7 = 0;
for (String var9 : var1) {
Score var10 = var6.method20980(var9, var2);
var10.setScorePoints(var10.getScorePoints() - var3);
var7 += var10.getScorePoints();
}
if (var1.size() != 1) {
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.players.remove.success.multiple", var3, var2.method29340(), var1.size()), true);
} else {
var0.sendFeedback(
new TranslationTextComponent("commands.scoreboard.players.remove.success.single", var3, var2.method29340(), var1.iterator().next(), var7), true
);
}
return var7;
}
private static int method37282(CommandSource var0) {
Collection var3 = var0.getServer().method1409().method20984();
if (!var3.isEmpty()) {
var0.sendFeedback(
new TranslationTextComponent("commands.scoreboard.players.list.success", var3.size(), TextComponentUtils.makeGreenSortedList(var3)), false
);
} else {
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.players.list.empty"), false);
}
return var3.size();
}
private static int method37283(CommandSource var0, String var1) {
Map<ScoreObjective, Score> var4 = var0.getServer().method1409().method20986(var1);
if (!var4.isEmpty()) {
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.players.list.entity.success", var1, var4.size()), false);
for (Entry var6 : var4.entrySet()) {
var0.sendFeedback(
new TranslationTextComponent(
"commands.scoreboard.players.list.entity.entry", ((ScoreObjective)var6.getKey()).method29340(), ((Score)var6.getValue()).getScorePoints()
),
false
);
}
} else {
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.players.list.entity.empty", var1), false);
}
return var4.size();
}
private static int method37284(CommandSource var0, int var1) throws CommandSyntaxException {
ServerScoreboard var4 = var0.getServer().method1409();
if (var4.getObjectiveInDisplaySlot(var1) != null) {
var4.method20988(var1, (ScoreObjective)null);
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.objectives.display.cleared", Scoreboard.method21010()[var1]), true);
return 0;
} else {
throw field44913.create();
}
}
private static int method37285(CommandSource var0, int var1, ScoreObjective var2) throws CommandSyntaxException {
ServerScoreboard var5 = var0.getServer().method1409();
if (var5.getObjectiveInDisplaySlot(var1) != var2) {
var5.method20988(var1, var2);
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.objectives.display.set", Scoreboard.method21010()[var1], var2.method29338()), true);
return 0;
} else {
throw field44914.create();
}
}
private static int method37286(CommandSource var0, ScoreObjective var1, ITextComponent var2) {
if (!var1.method29338().equals(var2)) {
var1.method29341(var2);
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.objectives.modify.displayname", var1.method29336(), var1.method29340()), true);
}
return 0;
}
private static int method37287(CommandSource var0, ScoreObjective var1, Class2316 var2) {
if (var1.method29342() != var2) {
var1.method29343(var2);
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.objectives.modify.rendertype", var1.method29340()), true);
}
return 0;
}
private static int method37288(CommandSource var0, ScoreObjective var1) {
ServerScoreboard var4 = var0.getServer().method1409();
var4.method20987(var1);
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.objectives.remove.success", var1.method29340()), true);
return var4.method20982().size();
}
private static int method37289(CommandSource var0, String var1, Class9008 var2, ITextComponent var3) throws CommandSyntaxException {
ServerScoreboard var6 = var0.getServer().method1409();
if (var6.method20976(var1) == null) {
if (var1.length() <= 16) {
var6.method20977(var1, var2, var3, var2.method33282());
ScoreObjective var7 = var6.method20976(var1);
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.objectives.add.success", var7.method29340()), true);
return var6.method20982().size();
} else {
throw Class9263.field42601.create(16);
}
} else {
throw field44912.create();
}
}
private static int method37290(CommandSource var0) {
Collection var3 = var0.getServer().method1409().method20982();
if (!var3.isEmpty()) {
var0.sendFeedback(
new TranslationTextComponent(
"commands.scoreboard.objectives.list.success", var3.size(), TextComponentUtils.func_240649_b_(var3, ScoreObjective::method29340)
),
false
);
} else {
var0.sendFeedback(new TranslationTextComponent("commands.scoreboard.objectives.list.empty"), false);
}
return var3.size();
}
}
| 0 | 0.657022 | 1 | 0.657022 | game-dev | MEDIA | 0.483621 | game-dev | 0.87806 | 1 | 0.87806 |
harvard-acc/ALADDIN | 1,732 | common/ScratchpadDatapath.h | #ifndef __SCRATCHPAD_DATAPATH__
#define __SCRATCHPAD_DATAPATH__
#include <string>
#include "BaseDatapath.h"
#include "ExecNode.h"
#include "Scratchpad.h"
class ScratchpadDatapath : public BaseDatapath {
public:
ScratchpadDatapath(std::string bench,
std::string trace_file,
std::string config_file);
virtual ~ScratchpadDatapath();
void globalOptimizationPass();
void completePartition();
void scratchpadPartition();
virtual void clearDatapath();
virtual void initBaseAddress();
virtual void stepExecutingQueue();
virtual bool step();
virtual double getTotalMemArea();
virtual void getAverageMemPower(unsigned int cycles,
float* avg_power,
float* avg_dynamic,
float* avg_leak);
virtual void getMemoryBlocks(std::vector<std::string>& names);
virtual void updateChildren(ExecNode* node);
virtual int rescheduleNodesWhenNeeded();
protected:
virtual void writeOtherStats();
Scratchpad* scratchpad;
/*True if any of the scratchpads can still service memory requests.
False if non of the scratchpads can service any memory requests.*/
bool scratchpadCanService;
/* Stores number of cycles left for multi-cycle nodes currently in flight. */
std::map<unsigned, unsigned> inflight_multicycle_nodes;
// To streamline code.
const float cycle_time;
// If we invoke the same accelerator more than once, we don't need to create
// scratchpad objects again. (the scratchpads can't change), but we will
// need to assign labels and partitions to the nodes.
bool mem_reg_conversion_executed;
bool scratchpad_partition_executed;
};
#endif
| 0 | 0.859756 | 1 | 0.859756 | game-dev | MEDIA | 0.169157 | game-dev | 0.645614 | 1 | 0.645614 |
NethermindEth/nethermind | 2,564 | src/Nethermind/Nethermind.Taiko/L1OriginDecoder.cs | // SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only
using Nethermind.Core.Crypto;
using Nethermind.Int256;
using Nethermind.Serialization.Rlp;
using System;
namespace Nethermind.Taiko;
public class L1OriginDecoder : IRlpStreamDecoder<L1Origin>
{
const int BuildPayloadArgsIdLength = 8;
public L1Origin Decode(RlpStream rlpStream, RlpBehaviors rlpBehaviors = RlpBehaviors.None)
{
(int _, int contentLength) = rlpStream.ReadPrefixAndContentLength();
int itemsCount = rlpStream.PeekNumberOfItemsRemaining(maxSearch: contentLength);
UInt256 blockId = rlpStream.DecodeUInt256();
Hash256? l2BlockHash = rlpStream.DecodeKeccak();
var l1BlockHeight = rlpStream.DecodeLong();
Hash256 l1BlockHash = rlpStream.DecodeKeccak() ?? throw new RlpException("L1BlockHash is null");
int[]? buildPayloadArgsId = itemsCount == 4 ? null : Array.ConvertAll(rlpStream.DecodeByteArray(), Convert.ToInt32);
return new(blockId, l2BlockHash, l1BlockHeight, l1BlockHash, buildPayloadArgsId);
}
public Rlp Encode(L1Origin? item, RlpBehaviors rlpBehaviors = RlpBehaviors.None)
{
if (item is null)
return Rlp.OfEmptySequence;
RlpStream rlpStream = new(GetLength(item, rlpBehaviors));
Encode(rlpStream, item, rlpBehaviors);
return new(rlpStream.Data.ToArray()!);
}
public void Encode(RlpStream stream, L1Origin item, RlpBehaviors rlpBehaviors = RlpBehaviors.None)
{
stream.StartSequence(GetLength(item, rlpBehaviors));
stream.Encode(item.BlockId);
stream.Encode(item.L2BlockHash);
stream.Encode(item.L1BlockHeight);
stream.Encode(item.L1BlockHash);
if (item.BuildPayloadArgsId is not null)
{
if (item.BuildPayloadArgsId.Length is not BuildPayloadArgsIdLength)
{
throw new RlpException($"{nameof(item.BuildPayloadArgsId)} should be exactly {BuildPayloadArgsIdLength}");
}
stream.Encode(Array.ConvertAll(item.BuildPayloadArgsId, Convert.ToByte));
}
}
public int GetLength(L1Origin item, RlpBehaviors rlpBehaviors)
{
return Rlp.LengthOfSequence(
Rlp.LengthOf(item.BlockId)
+ Rlp.LengthOf(item.L2BlockHash)
+ Rlp.LengthOf(item.L1BlockHeight)
+ Rlp.LengthOf(item.L1BlockHash)
+ (item.BuildPayloadArgsId is null ? 0 : Rlp.LengthOfByteString(BuildPayloadArgsIdLength, 0))
);
}
}
| 0 | 0.842319 | 1 | 0.842319 | game-dev | MEDIA | 0.17927 | game-dev | 0.819238 | 1 | 0.819238 |
Mesh-IGM/rtsg1-spring-2025-mesh-demos | 3,628 | 2pm-Demos/HW3-Starter/HW3/class/Box2D/Collision/Shapes/b2Shape.h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_SHAPE_H
#define B2_SHAPE_H
#include "Box2D/Common/b2BlockAllocator.h"
#include "Box2D/Common/b2Math.h"
#include "Box2D/Collision/b2Collision.h"
/// This holds the mass data computed for a shape.
struct b2MassData
{
/// The mass of the shape, usually in kilograms.
float32 mass;
/// The position of the shape's centroid relative to the shape's origin.
b2Vec2 center;
/// The rotational inertia of the shape about the local origin.
float32 I;
};
/// A shape is used for collision detection. You can create a shape however you like.
/// Shapes used for simulation in b2World are created automatically when a b2Fixture
/// is created. Shapes may encapsulate a one or more child shapes.
class b2Shape
{
public:
enum Type
{
e_circle = 0,
e_edge = 1,
e_polygon = 2,
e_chain = 3,
e_typeCount = 4
};
virtual ~b2Shape() {}
/// Clone the concrete shape using the provided allocator.
virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0;
/// Get the type of this shape. You can use this to down cast to the concrete shape.
/// @return the shape type.
Type GetType() const;
/// Get the number of child primitives.
virtual int32 GetChildCount() const = 0;
/// Test a point for containment in this shape. This only works for convex shapes.
/// @param xf the shape world transform.
/// @param p a point in world coordinates.
virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0;
/// Cast a ray against a child shape.
/// @param output the ray-cast results.
/// @param input the ray-cast input parameters.
/// @param transform the transform to be applied to the shape.
/// @param childIndex the child shape index
virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
const b2Transform& transform, int32 childIndex) const = 0;
/// Given a transform, compute the associated axis aligned bounding box for a child shape.
/// @param aabb returns the axis aligned box.
/// @param xf the world transform of the shape.
/// @param childIndex the child shape
virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const = 0;
/// Compute the mass properties of this shape using its dimensions and density.
/// The inertia tensor is computed about the local origin.
/// @param massData returns the mass data for this shape.
/// @param density the density in kilograms per meter squared.
virtual void ComputeMass(b2MassData* massData, float32 density) const = 0;
Type m_type;
/// Radius of a shape. For polygonal shapes this must be b2_polygonRadius. There is no support for
/// making rounded polygons.
float32 m_radius;
};
inline b2Shape::Type b2Shape::GetType() const
{
return m_type;
}
#endif
| 0 | 0.925214 | 1 | 0.925214 | game-dev | MEDIA | 0.701949 | game-dev | 0.980826 | 1 | 0.980826 |
joostdecock/core | 101,499 | patterns/Beta/CarltonCoat/CarltonCoat.php | <?php
/** Freesewing\Patterns\Beta\CarltonCoat class */
namespace Freesewing\Patterns\Beta;
/**
* A pattern template
*
* If you'd like to add you own pattern, you can copy this class/directory.
* It's an empty skeleton for you to start working with
*
* @author Joost De Cock <joost@decock.org>
* @copyright 2017 Joost De Cock
* @license http://opensource.org/licenses/GPL-3.0 GNU General Public License, Version 3
*/
class CarltonCoat extends BentBodyBlock
{
/*
___ _ _ _ _ _
|_ _|_ __ (_) |_(_) __ _| (_)___ ___
| || '_ \| | __| |/ _` | | / __|/ _ \
| || | | | | |_| | (_| | | \__ \ __/
|___|_| |_|_|\__|_|\__,_|_|_|___/\___|
Things we need to do before we can draft a pattern
*/
/** Length bonus is irrelevant */
const LENGTH_BONUS = 0;
/** Hem from waist factor is always 69% */
const HEM_FROM_WAIST_FACTOR = 0.69;
/** Tailfold width is 11.36% of waist */
const TAILFOLD_WAIST_FACTOR = 0.1136;
/** Collar mid height is 9.6% of the chest circumferce */
const COLLAR_MID_HEIGHT_FACTOR = 0.096;
/** Collar edge height is 8.6% of the chest circumferce */
const COLLAR_EDGE_HEIGHT_FACTOR = 0.086;
/**Cuff height is 15% of sleeve length */
const CUFF_LENGTH_FACTOR = 0.15;
/** Belt height is 7cm */
const BELT_HEIGHT = 70;
/** Vertical button distance = 5.425% of chest circumference */
const VERTICAL_BUTTON_DIST = 0.05425;
/** Horizontal button distance = 9.43% of chest circumference */
const HORIZONTAL_BUTTON_DIST = 0.0943;
/** Belt width = 7cm */
const BELT_WIDTH = 70;
/** Main pocket width = 18.85% of chest circumference */
const MAIN_POCKET_WIDTH = 0.1885;
/** Main pocket height = 21.5% of chest circumference */
const MAIN_POCKET_HEIGHT = 0.215;
/** Main pocket radius = 5cm */
const MAIN_POCKET_RADIUS = 50;
/** Main pocket flap height = 7.78% of chest circumference */
const MAIN_POCKET_FLAP_HEIGHT = 0.0778;
/** Main pocket flap radius = 3cm */
const MAIN_POCKET_FLAP_RADIUS = 30;
/** Chest pocket width = 3.9% of chest circumference */
const CHEST_POCKET_WIDTH = 0.039;
/** Chest pocket height = 17.36% of chest circumference */
const CHEST_POCKET_HEIGHT = 0.1736;
/** Chest pocket rotation = 4 degrees */
const CHEST_POCKET_ROTATION = 4;
/* Distance between pocket and chest pocket = 6.6% of chest */
const INTER_POCKET_DISTANCE = 0.066;
/* Fusible interfacing strip width = 3cm */
const FUSIBLE_WIDTH = 30;
/**
* Sets up options and values for our draft
*
* @param \Freesewing\Model $model The model to sample for
*
* @return void
*/
public function initialize($model)
{
// The (grand)parent pattern's lengthBonus is irrelevant here
$this->setOptionIfUnset('lengthBonus', self::LENGTH_BONUS);
// Fix the hemFromWaistFactor to 69%
$this->setOptionIfUnset('hemFromWaistFactor', self::HEM_FROM_WAIST_FACTOR);
// Make collarMidHeightFactor 9.6% of chest circumference
$this->setOptionIfUnset('collarMidHeightFactor', self::COLLAR_MID_HEIGHT_FACTOR);
// Make collarEdgeHeightFactor 8.6% of chest circumference
$this->setOptionIfUnset('collarEdgeHeightFactor', self::COLLAR_EDGE_HEIGHT_FACTOR);
// Make shoulderToShoulder measurement larger because coat
$model->setMeasurement('shoulderToShoulder', $model->m('shoulderToShoulder') + $this->o('shoulderEase'));
// Waist shaping
$this->setValueIfUnset('waistReduction',
( $model->m('chestCircumference') + $this->o('chestEase') ) -
( $model->m('naturalWaist') + $this->o('waistEase') )
);
// Percentage of the waistReduction that's handled in the side seams
$this->setValueIfUnset('waistSideShapeFactor', 0.5);
$this->setValueIfUnset('waistReductionSide', $this->v('waistReduction') * $this->v('waistSideShapeFactor') / 8);
$this->setValueIfUnset('waistReductionBack', $this->v('waistReduction') * (1-$this->v('waistSideShapeFactor')) / 8);
// Distance between buttons
$this->setValueIfUnset('buttonDistHor', ($model->m('chestCircumference') * self::VERTICAL_BUTTON_DIST));
$this->setValueIfUnset('buttonDistVer', ($model->m('chestCircumference') * self::HORIZONTAL_BUTTON_DIST));
// Fix the tailfoldWaistFactor to 11.36%
$this->setValueIfUnset('tailfoldWaistFactor', self::TAILFOLD_WAIST_FACTOR);
// Width of the belt
$this->setValueIfUnset('beltWidth', self::BELT_WIDTH);
// Width of the main pockets = 18.85% of chest
$this->setValueIfUnset('pocketWidth', $model->m('chestCircumference') * self::MAIN_POCKET_WIDTH);
// Height of the main pockets = 21.5% of chest
$this->setValueIfUnset('pocketHeight', $model->m('chestCircumference') * self::MAIN_POCKET_HEIGHT);
// Radius of the pockets at the bottom
$this->setValueIfUnset('pocketRadius', self::MAIN_POCKET_RADIUS);
// Height of the pocket flap = 7.78% of chest
$this->setValueIfUnset('pocketFlapHeight', $model->m('chestCircumference') * self::MAIN_POCKET_FLAP_HEIGHT);
// Radius of the pocket flap at the bottom
$this->setValueIfUnset('pocketFlapRadius', self::MAIN_POCKET_FLAP_RADIUS);
// Width of the chest pocket = 3.9% of chest
$this->setValueIfUnset('chestPocketWidth', $model->m('chestCircumference') * self::CHEST_POCKET_WIDTH);
// Height of the chest pocket = 17.36% of chest
$this->setValueIfUnset('chestPocketHeight', $model->m('chestCircumference') * self::CHEST_POCKET_HEIGHT);
// Rotation of the chest pocket = 4 degrees
$this->setValueIfUnset('chestPocketRotation', self::CHEST_POCKET_ROTATION);
// Distance between pocket and chest pocket = 6.6% of chest
$this->setValueIfUnset('pocketDistance', $model->m('chestCircumference') * self::INTER_POCKET_DISTANCE);
// Cuff length
$this->setValueIfUnset('cuffLengthFactor' , self::CUFF_LENGTH_FACTOR);
$this->setValueIfUnset('cuffLength' , $model->m('shoulderToWrist') * $this->v('cuffLengthFactor'));
// Belt height
$this->setValueIfUnset('beltHeight' , self::BELT_HEIGHT);
// Width of the fusible interfacing strips
$this->setValueIfUnset('fusibleWidth' , self::FUSIBLE_WIDTH);
parent::initialize($model);
}
/*
____ __ _
| _ \ _ __ __ _ / _| |_
| | | | '__/ _` | |_| __|
| |_| | | | (_| | _| |_
|____/|_| \__,_|_| \__|
The actual sampling/drafting of the pattern
*/
/**
* Generates a sample of the pattern
*
* Here, you create a sample of the pattern for a given model
* and set of options. You should get a barebones pattern with only
* what it takes to illustrate the effect of changes in
* the sampled option or measurement.
*
* @param \Freesewing\Model $model The model to sample for
*
* @return void
*/
public function sample($model)
{
// Setup all options and values we need
$this->initialize($model);
// Get to work
$this->draftBackBlock($model);
$this->draftFrontBlock($model);
$this->draftSleeveBlock($model);
$this->draftTopsleeveBlock($model);
$this->draftUndersleeveBlock($model);
$this->draftFront($model);
$this->draftBack($model);
$this->draftTail($model);
$this->draftCollar($model);
$this->draftCollarStand($model);
$this->draftTopsleeve($model);
$this->draftUndersleeve($model);
$this->draftCuffFacing($model);
$this->draftBelt($model);
$this->draftPocket($model);
$this->draftPocketFlap($model);
$this->draftChestPocketWelt($model);
$this->draftInnerPocketWelt($model);
$this->draftInnerPocketBag($model);
$this->draftInnerPocketTab($model);
// Hide the sleeveBlocks, frontBlock, and backBlock
$this->parts['sleeveBlock']->setRender(false);
$this->parts['topsleeveBlock']->setRender(false);
$this->parts['undersleeveBlock']->setRender(false);
$this->parts['frontBlock']->setRender(false);
$this->parts['backBlock']->setRender(false);
}
/**
* Generates a draft of the pattern
*
* Here, you create the full draft of this pattern for a given model
* and set of options. You get a complete pattern with
* all bels and whistles.
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draft($model)
{
// Continue from sample
$this->sample($model);
$this->finalizeFront($model);
$this->finalizeBack($model);
$this->finalizeTail($model);
$this->finalizeTopsleeve($model);
$this->finalizeUndersleeve($model);
$this->finalizeBelt($model);
$this->finalizeCollarStand($model);
$this->finalizeCollar($model);
$this->finalizeCuffFacing($model);
$this->finalizePocket($model);
$this->finalizePocketFlap($model);
$this->finalizeChestPocketWelt($model);
$this->finalizeInnerPocketWelt($model);
$this->finalizeInnerPocketBag($model);
$this->finalizeInnerPocketTab($model);
// Is this a paperless pattern?
if ($this->isPaperless) {
$this->paperlessFront($model);
$this->paperlessBack($model);
$this->paperlessTail($model);
$this->paperlessTopsleeve($model);
$this->paperlessUndersleeve($model);
$this->paperlessBelt($model);
$this->paperlessCollarStand($model);
$this->paperlessCollar($model);
$this->paperlessCuffFacing($model);
$this->paperlessPocket($model);
$this->paperlessPocketFlap($model);
$this->paperlessChestPocketWelt($model);
$this->paperlessInnerPocketWelt($model);
$this->paperlessInnerPocketBag($model);
$this->paperlessInnerPocketTab($model);
}
}
/**
* Drafts the front
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftFront($model)
{
$this->clonePoints('frontBlock','front');
/** @var \Freesewing\Part $p */
$p = $this->parts['front'];
// Hem length
$p->newPoint('hemMiddle', $p->x(4), $p->y(3) + $model->m('naturalWaistToFloor') * $this->o('hemFromWaistFactor'));
$p->newPoint('hemSide', $p->x(5), $p->y('hemMiddle'));
// Waist shaping
$p->newPoint('waistSide', $p->x(5) - $this->v('waistReductionSide'), $p->y(3));
$p->addPoint('waistSideCpTop', $p->shift('waistSide', 90, $p->deltaY(5,3)/2));
$p->addPoint('waistSideCpBottom', $p->flipY('waistSideCpTop', $p->y('waistSide')));
$p->addPoint('chestSideCp', $p->shift(5,-90,$p->deltaY(5,'waistSideCpTop')/8));
// Seat
$p->newPoint('seatSide', $p->x(3) + ($model->m('seatCircumference') + $this->o('seatEase'))/4, $p->y(4) + $model->m('naturalWaistToSeat') );
$p->addPoint('seatSideCpTop', $p->shift('seatSide', 90, $p->deltaY(4,'seatSide')/2));
// Buttonline
//$this->setValue('buttonDistVer', $p->deltaY(4,5)/2.5);
$p->newPoint('button1Left', $p->x(4) - $this->v('buttonDistHor'), $p->y(4));
$p->addPoint('button2Left', $p->shift('button1Left',90,$this->v('buttonDistVer')*1));
$p->addPoint('button3Left', $p->shift('button1Left',90,$this->v('buttonDistVer')*2));
$p->addPoint('button1Right', $p->flipX('button1Left',$p->x(4)));
$p->addPoint('button2Right', $p->flipX('button2Left',$p->x(4)));
$p->addPoint('button3Right', $p->flipX('button3Left',$p->x(4)));
// Front center edge
$p->addPoint('frontEdge', $p->shift('button1Left',180,25));
// Hem
$p->newPoint('hemSide', $p->x('seatSide'), $p->y('hemMiddle'));
$p->newPoint('hemFrontEdge', $p->x('frontEdge'), $p->y('hemMiddle'));
// Collar
$p->newPoint('collarEdge', $p->x('frontEdge'), $p->y(9));
$p->addPoint('collarTip', $p->shift('collarEdge',0,$this->v('buttonDistHor')/11.5));
$p->newPoint('collarBendPoint', $p->x('collarEdge'), $p->y(5));
$p->addPoint('collarBendPointCpTop', $p->shift('collarBendPoint',90,$p->deltaY('collarEdge','collarBendPoint')*0.8));
// Pocket
$p->newPoint('pocketTopLeft', $p->x('button1Right')+25, $p->y('button1Right')-12.5);
$p->addPoint('pocketTopRight', $p->shift('pocketTopLeft', 0, $this->v('pocketWidth')));
$p->addPoint('pocketBottomLeft', $p->shift('pocketTopLeft', -90, $this->v('pocketHeight')));
$p->addPoint('pocketBottomRight', $p->shift('pocketTopRight', -90, $this->v('pocketHeight')));
$p->addPoint('pocketBottomLeftTop', $p->shift('pocketBottomLeft', 90, $this->v('pocketRadius')));
$p->addPoint('pocketBottomRightTop', $p->shift('pocketBottomRight', 90, $this->v('pocketRadius')));
$p->addPoint('pocketBottomLeftRight', $p->shift('pocketBottomLeft', 0, $this->v('pocketRadius')));
$p->addPoint('pocketBottomRightLeft', $p->shift('pocketBottomRight', 180, $this->v('pocketRadius')));
$p->addPoint('pocketBottomLeftTopCp', $p->shift('pocketBottomLeftTop', -90, \Freesewing\BezierToolbox::bezierCircle($this->v('pocketRadius'))));
$p->addPoint('pocketBottomLeftRightCp', $p->shift('pocketBottomLeftRight', 180, \Freesewing\BezierToolbox::bezierCircle($this->v('pocketRadius'))));
$p->addPoint('pocketBottomRightTopCp', $p->shift('pocketBottomRightTop', -90, \Freesewing\BezierToolbox::bezierCircle($this->v('pocketRadius'))));
$p->addPoint('pocketBottomRightLeftCp', $p->shift('pocketBottomRightLeft', 0, \Freesewing\BezierToolbox::bezierCircle($this->v('pocketRadius'))));
// Pocket flap
$rise = 12.5;
$round = \Freesewing\BezierToolbox::bezierCircle($this->v('pocketFlapRadius'));
$p->newPoint('pocketFlapTopLeft', $p->x('pocketTopLeft'), $p->y('pocketTopLeft')-$rise);
$p->addPoint('pocketFlapTopRight', $p->shift('pocketFlapTopLeft', 0, $this->v('pocketWidth')));
$p->addPoint('pocketFlapBottomLeft', $p->shift('pocketFlapTopLeft', -90, $this->v('pocketFlapHeight')));
$p->addPoint('pocketFlapBottomRight', $p->shift('pocketFlapTopRight', -90, $this->v('pocketFlapHeight')));
$p->addPoint('pocketFlapBottomLeftTop', $p->shift('pocketFlapBottomLeft', 90, $this->v('pocketFlapRadius')));
$p->addPoint('pocketFlapBottomRightTop', $p->shift('pocketFlapBottomRight', 90, $this->v('pocketFlapRadius')));
$p->addPoint('pocketFlapBottomLeftRight', $p->shift('pocketFlapBottomLeft', 0, $this->v('pocketFlapRadius')));
$p->addPoint('pocketFlapBottomRightLeft', $p->shift('pocketFlapBottomRight', 180, $this->v('pocketFlapRadius')));
$p->addPoint('pocketFlapBottomLeftTopCp', $p->shift('pocketFlapBottomLeftTop', -90, $round));
$p->addPoint('pocketFlapBottomLeftRightCp', $p->shift('pocketFlapBottomLeftRight', 180, $round));
$p->addPoint('pocketFlapBottomRightTopCp', $p->shift('pocketFlapBottomRightTop', -90, $round));
$p->addPoint('pocketFlapBottomRightLeftCp', $p->shift('pocketFlapBottomRightLeft', 0, $round));
// Make flap taper inwards a bit
$p->addPoint('pocketFlapBottomLeftTop', $p->shift('pocketFlapBottomLeftTop', 0, 2));
$p->addPoint('pocketFlapBottomRightTop', $p->shift('pocketFlapBottomRightTop', 180, 2));
$p->addPoint('pocketFlapTopLeft', $p->shiftOutwards('pocketFlapBottomLeftTop','pocketTopLeft', $rise));
$p->addPoint('pocketFlapTopRight', $p->shiftOutwards('pocketFlapBottomRightTop','pocketTopRight', $rise));
$p->addPoint('pocketFlapBottomLeftTopCp', $p->shiftOutwards('pocketFlapTopLeft','pocketFlapBottomLeftTop', $round));
$p->addPoint('pocketFlapBottomRightTopCp', $p->shiftOutwards('pocketFlapTopRight','pocketFlapBottomRightTop', $round));
$p->addPoint('pocketFlapBottomLeftRight', $p->shift('pocketFlapBottomLeftRight', 0, 2));
$p->addPoint('pocketFlapBottomLeftRightCp', $p->shift('pocketFlapBottomLeftRightCp', 0, 2));
$p->addPoint('pocketFlapBottomRightLeft', $p->shift('pocketFlapBottomRightLeft', 180, 2));
$p->addPoint('pocketFlapBottomRightLeftCp', $p->shift('pocketFlapBottomRightLeftCp', 180, 2));
// Pocket path
$p->newPath('pocket', 'M pocketTopLeft L pocketBottomLeftTop
C pocketBottomLeftTopCp pocketBottomLeftRightCp pocketBottomLeftRight
L pocketBottomRightLeft
C pocketBottomRightLeftCp pocketBottomRightTopCp pocketBottomRightTop
L pocketTopRight
z', ['class' => 'help']);
$p->newPath('pocketFlap', 'M pocketFlapTopLeft L pocketFlapBottomLeftTop
C pocketFlapBottomLeftTopCp pocketFlapBottomLeftRightCp pocketFlapBottomLeftRight
L pocketFlapBottomRightLeft
C pocketFlapBottomRightLeftCp pocketFlapBottomRightTopCp pocketFlapBottomRightTop
L pocketFlapTopRight
z', ['class' => 'help']);
// Chest pocket
$p->newPoint('chestPocketBottomLeft', $p->x('button2Right')+ 2*$this->v('chestPocketWidth'), $p->y('button2Right')-5);
$p->addPoint('chestPocketBottomRight', $p->shift('chestPocketBottomLeft', 0, $this->v('chestPocketWidth')));
$p->addPoint('chestPocketTopLeft', $p->shift('chestPocketBottomLeft', 90, $this->v('chestPocketHeight')));
$p->addPoint('chestPocketTopRight', $p->shift('chestPocketBottomRight', 90, $this->v('chestPocketHeight')));
// Slightly rotate chest pocket
$angle = $this->v('chestPocketRotation');
$p->addPoint('chestPocketBottomRight', $p->rotate('chestPocketBottomRight','chestPocketBottomLeft',$angle));
$p->addPoint('chestPocketTopLeft', $p->rotate('chestPocketTopLeft','chestPocketBottomLeft',$angle));
$p->addPoint('chestPocketTopRight', $p->rotate('chestPocketTopRight','chestPocketBottomLeft',$angle));
$p->newPath('chestPocket', 'M chestPocketTopLeft L chestPocketTopRight L chestPocketBottomRight L chestPocketBottomLeft z', ['class' => 'help']);
// Inner pocket
// Width = 12 cm, unless coat is really small
if($p->distance('pocketTopLeft', 'pocketTopRight') < 150) $this->setValue('innerPocketWidth',100);
else $this->setValue('innerPocketWidth', 125);
$p->newPoint('innerPocketLeft', $p->x('pocketTopLeft')+12.5, $p->y('waistSide')-2*$p->deltaY('button3Right','waistSide'));
$p->addPoint('innerPocketRight', $p->shift('innerPocketLeft',0,$this->v('innerPocketWidth')));
$p->addPoint('innerPocketTopLeft', $p->shift('innerPocketLeft', 90, 5));
$p->addPoint('innerPocketBottomLeft', $p->shift('innerPocketLeft', -90, 5));
$p->addPoint('innerPocketTopRight', $p->shift('innerPocketRight', 90, 5));
$p->addPoint('innerPocketBottomRight', $p->shift('innerPocketRight', -90, 5));
// Inner pocket path
$p->newPath('innerPocket', 'M innerPocketTopLeft L innerPocketTopRight
L innerPocketBottomRight L innerPocketBottomLeft z
M innerPocketLeft L innerPocketRight'
, ['class' => 'lining help']);
// Paths
$path = 'M 9 L collarTip
C collarTip collarBendPointCpTop collarBendPoint
L hemFrontEdge L hemSide L seatSide
C seatSideCpTop waistSideCpBottom waistSide
C waistSideCpTop chestSideCp 5
C 13 16 14 C 15 18 10 C 17 19 12 L 8 C 20 21 9 z';
$p->newPath('outline', $path);
// Mark path for sample service
$p->paths['outline']->setSample(true);
$p->clonePoint('frontEdge', 'gridAnchor');
// Calculate collar length
$this->setValue('frontCollarLength', $p->curveLen(9, 21, 20, 8));
}
/**
* Drafts the back
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftBack($model)
{
$this->clonePoints('backBlock','back');
/** @var \Freesewing\Part $p */
$p = $this->parts['back'];
// Box pleat
$p->newPoint('bpTop', $p->x(1) - $model->m('chestCircumference') * 0.048, $p->y(10));
$p->newPoint('bpTopIn', $p->x(1), $p->y(10));
$p->newPoint('bpBottom', $p->x('bpTop'), $p->y(3) - $this->v('beltWidth')/2);
// Waist shaping
$p->newPoint('waistSide', $p->x(5) - $this->v('waistReductionSide'), $p->y(3) - $this->v('beltWidth')/2);
$p->addPoint('waistSideCpTop', $p->shift('waistSide', 90, ($p->deltaY(5,3)/2) - ($this->v('beltWidth')/2)));
$p->addPoint('chestSideCp', $p->shift(5,-90,$p->deltaY(5,'waistSideCpTop')/8));
// Darts
$p->newPoint('dartCenter', $p->x('waistSide') * 0.4, $p->y('waistSide'));
$p->addPoint('dartRight', $p->shift('dartCenter', 0, $this->v('waistReductionBack')));
$p->addPoint('dartLeft', $p->shift('dartCenter', 180, $this->v('waistReductionBack')));
$p->newPoint('dartTip', $p->x('dartCenter'), $p->y(5));
$p->addPoint('dartRightCp', $p->shift('dartRight', 90, $p->deltaY(5,'dartCenter')/2));
$p->addPoint('dartLeftCp', $p->shift('dartLeft', 90, $p->deltaY(5,'dartCenter')/2));
// Paths
$path = 'M 1 L bpTopIn L bpTop L bpBottom L dartLeft C dartLeftCp dartTip dartTip C dartTip dartRightCp dartRight L waistSide C waistSideCpTop chestSideCp 5 C 13 16 14 C 15 18 10 C 17 19 12 L 8 C 20 1 1 z';
$p->newPath('outline', $path, ['class' => 'fabric']);
$p->newPath('boxPleat', 'M bpTopIn L bpTop L bpBottom');
$this->setValue('backCollarLength', $p->curveLen(1, 1, 20, 8));
// Mark path for sample service
$p->paths['outline']->setSample(true);
$p->clonePoint('bpBottom', 'gridAnchor');
}
/**
* Drafts the Tail
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftTail($model)
{
/** @var \Freesewing\Part $p */
$b = $this->parts['back'];
$waist = $b->x('waistSide') - $this->v('waistReductionBack')*2;
/** @var \Freesewing\Part $p */
$f = $this->parts['front'];
$length = $f->y('hemSide') - $f->y('waistSide');
/** @var \Freesewing\Part $p */
$p = $this->parts['tail'];
$p->newPoint('cbTop', 0, 0);
$p->newPoint('waistTop', $waist, 0);
$p->newPoint('leftTop', $model->m('naturalWaist') * $this->v('tailfoldWaistFactor') * -2, 0);
$p->newPoint('leftPleat1', $model->m('naturalWaist') * $this->v('tailfoldWaistFactor') * -1.5, 0);
$p->newPoint('leftPleat2', $model->m('naturalWaist') * $this->v('tailfoldWaistFactor') * -1.0, 0);
$p->newPoint('leftPleat3', $model->m('naturalWaist') * $this->v('tailfoldWaistFactor') * 0.5, 0);
foreach($p->points as $id => $point) {
$p->addPoint("$id-1", $p->shift($id,-90,50));
$p->addPoint("$id-2", $p->shift($id,-90,80));
$p->addPoint("$id-3", $p->shift($id,-90,130));
}
$p->addPoint('dimTop', $p->shift('waistTop', 180, 70));
$p->addPoint('dimBottom', $p->shift('waistTop-3', 180, 70));
// Store belt length
$this->setValue('halfBackWidth', $p->distance('leftPleat2', 'waistTop') - (2 * $p->distance('cbTop','leftPleat3')));
$this->setValue('beltLength', $this->v('halfBackWidth') + $p->distance('leftPleat2', 'cbTop') + 20);
$this->dbg('belt length is '.$this->v('beltLength'));
$p->newLinearDimension('dimBottom', 'dimTop', 0, $p->unit($length));
// Paths
$p->newPath('seamline1', 'M leftTop-1 leftTop L cbTop L waistTop L waistTop-1', ['class' => 'fabric']);
$p->newPath('seamline2', 'M leftTop-2 leftTop-3 L cbTop-3 L waistTop-3 L waistTop-2', ['class' => 'fabric']);
$p->newPath('folds', '
M leftPleat1 L leftPleat1-3
M leftPleat2 L leftPleat2-3
M cbTop L cbTop-3
M leftPleat3 L leftPleat3-3
', ['class' => 'dashed']);
$p->newPath('dots', 'M leftTop-1 L leftTop-2 M waistTop-1 L waistTop-2', ['class' => 'help sa']);
// Mark path for sample service
$p->paths['seamline1']->setSample(true);
$p->paths['seamline2']->setSample(true);
$p->clonePoint('leftTop', 'gridAnchor');
}
/**
* Drafts the collar
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftCollar($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['collar'];
$p->newPoint('centerTop', 0, 0);
$p->newPoint('centerBottom', 0, $model->m('chestCircumference') * $this->o('collarMidHeightFactor'));
$p->newPoint('rightTop', $this->v('frontCollarLength') + $this->v('backCollarLength'), 0);
$p->newPoint('rightCorner', $p->x('rightTop'), $p->y('centerBottom'));
$p->addPoint('leftCorner', $p->flipX('rightCorner'));
$p->newPoint('rightBottom', $p->x('rightTop')*0.76, $p->y('centerBottom') + $p->x('rightTop')/8.5);
$p->addPoint('leftTop', $p->flipX('rightTop'));
$p->addPoint('leftBottom', $p->flipX('rightBottom'));
// Control points
$p->newPoint('centerBottomCpRight', $p->x('rightBottom')/2, $p->y('centerBottom'));
$p->addPoint('centerBottomCpLeft', $p->flipX('centerBottomCpRight'));
$p->newPoint('rightBottomCpRight', $p->x('rightBottom') + $p->deltaX('rightBottom', 'rightCorner')/2, $p->y('rightBottom'));
$p->addPoint('rightBottomCpLeft', $p->flipX('rightBottomCpRight', $p->x('rightBottom')));
$p->addPoint('leftBottomCpRight', $p->flipX('rightBottomCpRight'));
$p->addPoint('leftBottomCpLeft', $p->flipX('rightBottomCpLeft'));
// Collar stand points
$p->addPoint('standCenterTop', $p->shift('centerBottom',90,25));
$p->newPoint('standCenterTopCpRight', $p->x('rightBottom')*0.9, $p->y('standCenterTop'));
$p->addPoint('standCenterTopCpLeft', $p->flipX('standCenterTopCpRight'));
// Divide top in 5 parts
$p->addPoint('cutTop1', $p->shift('centerTop',0,$p->x('rightTop')*1/5));
$p->addPoint('cutTop2', $p->shift('centerTop',0,$p->x('rightTop')*2/5));
$p->addPoint('cutTop3', $p->shift('centerTop',0,$p->x('rightTop')*3/5));
$p->addPoint('cutTop4', $p->shift('centerTop',0,$p->x('rightTop')*4/5));
// Divide bottom in 4 parts
$len = $p->curveLen('standCenterTop','standCenterTopCpRight', 'rightBottom','rightBottom');
$p->addPoint('cutBottom1', $p->shiftAlong('standCenterTop','standCenterTopCpRight', 'rightBottom','rightBottom',$len*1/4));
$p->addPoint('cutBottom2', $p->shiftAlong('standCenterTop','standCenterTopCpRight', 'rightBottom','rightBottom',$len*2/4));
$p->addPoint('cutBottom3', $p->shiftAlong('standCenterTop','standCenterTopCpRight', 'rightBottom','rightBottom',$len*3/4));
// Split bottom curve in half
$p->splitCurve('standCenterTop','standCenterTopCpRight', 'rightBottom','rightBottom','cutBottom2','.helpa');
$p->splitCurve('standCenterTop','.helpa2', '.helpa3','cutBottom2','cutBottom1','.helpb');
$p->splitCurve('cutBottom2','.helpa7', 'rightBottom','rightBottom','cutBottom3','.helpc');
$p->clonePoint('.helpb2','curve1Cp1');
$p->clonePoint('.helpb3','curve1Cp2');
$p->clonePoint('.helpb7','curve2Cp1');
$p->clonePoint('.helpb6','curve2Cp2');
$p->clonePoint('.helpc2','curve3Cp1');
$p->clonePoint('.helpc3','curve3Cp2');
$p->clonePoint('.helpc7','curve4Cp1');
/*
$p->newPath('panels','
M cutBottom1 L cutTop1
M cutBottom2 L cutTop2
M cutBottom3 L cutTop3
M rightBottom L cutTop4
', ['class' => 'help']);
*/
// Clone points for collar stand before we fuck shit up
$this->clonePoints('collar','collarStand');
// Slash and rotate
$rotate = [
1 => [
'origin' => 'rightBottom',
'points' => ['rightCorner', 'rightTop', 'cutTop4', 'rightBottomCpRight'],
],
2 => [
'origin' => 'cutBottom3',
'points' => ['rightBottom', 'cutTop4', 'cutTop3', 'curve4Cp1'],
],
3 => [
'origin' => 'cutBottom2',
'points' => ['cutBottom3', 'cutTop3', 'cutTop2', 'curve3Cp1', 'curve3Cp2'],
],
4 => [
'origin' => 'cutBottom1',
'points' => ['cutBottom2', 'cutTop2', 'cutTop1', 'curve2Cp1', 'curve2Cp2'],
],
];
$angle = -5;
$alsoRotate=[];
$prevorg = false;
foreach($rotate as $nr => $step) {
$org= $step['origin'];
// $path="M $org ";
$first = false;
foreach($step['points'] as $pnt) {
if($first === false) $first = $pnt;
$id = "rot-$nr-$pnt";
$p->addPoint($id, $p->rotate($pnt, $org, $angle));
$alsoRotate[]=$id;
// $path .= "L $id ";
// $p->newPath("rot-$nr", $path.'z', ['class' => 'hint']);
}
if($nr <4) foreach($alsoRotate as $pnt) $p->addPoint($pnt, $p->rotate($pnt, $org, $angle));
}
// Shift panel 2 in place
$ang = $p->angle('cutBottom2', 'rot-4-cutBottom2')+180;
$len = -1*$p->distance('cutBottom2', 'rot-4-cutBottom2');
foreach(['cutBottom2', 'rot-3-cutTop2', 'rot-3-cutTop3', 'rot-3-cutBottom3','rot-3-curve3Cp1', 'rot-3-curve3Cp2'] as $pnt) $p->addPoint($pnt, $p->shift($pnt, $ang, $len));
// Shift panel 3 in place
$ang = $p->angle('cutBottom3', 'rot-3-cutBottom3')+180;
$len = -1*$p->distance('cutBottom3', 'rot-3-cutBottom3');
foreach(['cutBottom3', 'rot-2-cutTop3', 'rot-2-cutTop4', 'rot-2-rightBottom', 'rot-2-curve4Cp1'] as $pnt) $p->addPoint($pnt, $p->shift($pnt, $ang, $len));
// Shift panel 4 in place
$ang = $p->angle('rightBottom', 'rot-2-rightBottom')+180;
$len = -1*$p->distance('rightBottom', 'rot-2-rightBottom');
foreach(['rightBottom', 'rot-1-cutTop4', 'rot-1-rightTop', 'rot-1-rightCorner','rot-1-rightBottomCpRight'] as $pnt) $p->addPoint($pnt, $p->shift($pnt, $ang, $len));
// Add 2cm collar shaping
$p->addPoint('shapedTip', $p->shiftTowards('rot-2-cutTop3', 'rot-1-rightTop', $p->distance('rot-2-cutTop3', 'rot-1-rightTop')+20));
$p->newPath("outline", "
M standCenterTop C curve1Cp1 curve1Cp2 cutBottom1
C rot-4-curve2Cp1 rot-4-curve2Cp2 rot-4-cutBottom2
C rot-3-curve3Cp1 rot-3-curve3Cp2 rot-3-cutBottom3
C rot-2-curve4Cp1 rot-2-rightBottom rot-2-rightBottom
L rot-1-rightCorner
L shapedTip
C rot-2-cutTop4 cutTop3 centerTop
z
");
$p->addPoint('tmp', $p->shift('standCenterTopCpRight', 90, 35));
/*
$p->newPath('acrSegments','
M standCenterTop
C curve1Cp1 curve1Cp2 cutBottom1
C curve2Cp1 curve2Cp2 cutBottom2
C curve3Cp1 curve3Cp2 cutBottom3
C curve4Cp1 rightBottom rightBottom
', ['class' => 'debug']);
//$p->splitCurve('standCenterTop','standCenterTopCpRight', 'rightBottom','rightBottom', 0.5, 'cutBottom', true);
$p->newPath('outline', '
M centerTop
L rightTop
L rightCorner
C rightCorner rightBottomCpRight rightBottom
C rightBottom standCenterTopCpRight standCenterTop
C standCenterTopCpLeft leftBottom leftBottom
C leftBottomCpRight leftCorner leftCorner L leftTop z');
//$p->newPath('stand', 'M leftBottom C leftBottom standCenterTopCpLeft standCenterTop C standCenterTopCpRight rightBottom rightBottom', ['class' => 'debug']);
*/
// Mark path for sample service
$p->paths['outline']->setSample(true);
$p->clonePoint('centerTop', 'gridAnchor');
}
/**
* Drafts the collar stand
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftCollarStand($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['collarStand'];
$p->newPath('outline', '
M leftBottom
C leftBottom standCenterTopCpLeft standCenterTop
C standCenterTopCpRight rightBottom rightBottom
C rightBottomCpLeft centerBottomCpRight centerBottom
C centerBottomCpLeft leftBottomCpLeft leftBottom
z
');
//$p->notch(['centerTop', 'centerBottom']);
// Mark path for sample service
$p->paths['outline']->setSample(true);
$p->clonePoint('standCenterTop', 'gridAnchor');
}
protected function collarDelta() {
/** @var \Freesewing\Part $s */
$s = $this->parts['collarStand'];
// Collar stand length
$standLen = $s->curveLen('centerTop', 'rightTopCp', 'rightTop', 'rightBottom');
/** @var \Freesewing\Part $c */
$c = $this->parts['collar'];
// Collar length
$collarLen = $c->curveLen('bottom', 'rightTopCp', 'rightBottom', 'rightBottom');
return $collarLen - $standLen;
}
/**
* Drafts the topssleeve
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftTopsleeve($model)
{
$this->clonePoints('topsleeveBlock','topsleeve');
/** @var \Freesewing\Part $p */
$p = $this->parts['topsleeve'];
// Add cuff
$p->addPoint('cuffBottomRight', $p->shift('topsleeveWristRight', $p->angle('topsleeveWristLeft', 'topsleeveWristRight')-90, $this->v('cuffLength')));
$p->addPoint('cuffBottomLeft', $p->shift('topsleeveWristLeft', $p->angle('topsleeveWristLeft', 'topsleeveWristRight')-90, $this->v('cuffLength')));
$p->addPoint('cuffBottomRightTop', $p->shiftTowards('cuffBottomRight', 'topsleeveWristRight', $this->v('cuffLength') *0.25));
$p->addPoint('cuffBottomRightCpTop', $p->shiftTowards('cuffBottomRightTop', 'cuffBottomRight', \Freesewing\BezierToolbox::bezierCircle($p->distance('cuffBottomRightTop', 'cuffBottomRight'))));
$p->addPoint('cuffBottomRightLeft', $p->rotate('cuffBottomRightTop', 'cuffBottomRight', 90));
$p->addPoint('cuffBottomRightCpLeft', $p->rotate('cuffBottomRightCpTop', 'cuffBottomRight', 90));
// Store cuff width
$this->setValue('topCuffWidth', $p->distance('topsleeveWristRight','topsleeveWristLeft'));
// Paths
$p->newPath('prollem', '
M elbowRight
C elbowRightCpTop topsleeveRightEdgeCpBottom topsleeveRightEdge
C topsleeveRightEdgeCpTop backPitchPoint backPitchPoint
C backPitchPoint sleeveTopCpRight sleeveTop
C sleeveTopCpLeft frontPitchPointCpTop frontPitchPoint
C frontPitchPointCpBottom topsleeveLeftEdgeCpRight topsleeveLeftEdge
C topsleeveLeftEdge topsleeveElbowLeftCpTop topsleeveElbowLeft
L topsleeveWristLeft
L cuffBottomLeft
L cuffBottomRightLeft
C cuffBottomRightCpLeft cuffBottomRightCpTop cuffBottomRightTop
L topsleeveWristRight
z
', ['class' => 'fabric', 'flag' => 'prollem']);
$p->newPath('tmp', 'M topsleeveWristLeft L topsleeveWristRight ', ['class' => 'hint']);
// Mark path for sample service
$p->paths['prollem']->setSample(true);
$p->clonePoint('topsleeveWristRight', 'gridAnchor');
}
/**
* Drafts the undersleeve
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftUndersleeve($model)
{
$this->clonePoints('undersleeveBlock','undersleeve');
/** @var \Freesewing\Part $p */
$p = $this->parts['undersleeve'];
// Add cuff
$p->addPoint('cuffBottomRight', $p->shift('undersleeveWristRight', $p->angle('undersleeveWristLeft', 'undersleeveWristRight')-90, $this->v('cuffLength')));
$p->addPoint('cuffBottomLeft', $p->shift('undersleeveWristLeft', $p->angle('undersleeveWristLeft', 'undersleeveWristRight')-90, $this->v('cuffLength')));
$p->addPoint('cuffBottomRightTop', $p->shiftTowards('cuffBottomRight', 'undersleeveWristRight', $this->v('cuffLength') *0.25));
$p->addPoint('cuffBottomRightCpTop', $p->shiftTowards('cuffBottomRightTop', 'cuffBottomRight', \Freesewing\BezierToolbox::bezierCircle($p->distance('cuffBottomRightTop', 'cuffBottomRight'))));
$p->addPoint('cuffBottomRightLeft', $p->rotate('cuffBottomRightTop', 'cuffBottomRight', 90));
$p->addPoint('cuffBottomRightCpLeft', $p->rotate('cuffBottomRightCpTop', 'cuffBottomRight', 90));
// Store cuff width
$this->setValue('underCuffWidth', $p->distance('undersleeveWristRight','undersleeveWristLeft'));
$p->newPath('outline', '
M elbowRight
C elbowRightCpTop undersleeveRightEdgeCpBottom undersleeveRightEdge
C undersleeveRightEdgeCpTop undersleeveTip undersleeveTip
C undersleeveTipCpBottom undersleeveLeftEdgeCpRight undersleeveLeftEdgeRight
L undersleeveLeftEdge
C undersleeveLeftEdge undersleeveElbowLeftCpTop undersleeveElbowLeft
L undersleeveWristLeft
L cuffBottomLeft
L cuffBottomRightLeft
C cuffBottomRightCpLeft cuffBottomRightCpTop cuffBottomRightTop
L undersleeveWristRight
z
', ['class' => 'fabric']);
$p->newPath('tmp', 'M undersleeveWristLeft L undersleeveWristRight ', ['class' => 'hint']);
// Mark path for sample service
$p->paths['outline']->setSample(true);
}
/**
* Drafts the cuff facing
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftCuffFacing($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['cuffFacing'];
// Make facing 1.5 times the lenght of the cuff
$factor = 1.5;
$width = $this->v('underCuffWidth') + $this->v('topCuffWidth');
$p->newPoint('topLeft', 0, 0);
$p->newPoint('topRight', $width, 0);
$p->newPoint('bottomLeft', 0, $this->v('cuffLength') * $factor);
$p->newPoint('bottomRight', $width, $p->y('bottomLeft'));
$p->addPoint('bottomLeftTop', $p->shiftTowards('bottomLeft', 'topLeft', $this->v('cuffLength') *0.25));
$p->addPoint('bottomLeftCpTop', $p->shiftTowards('bottomLeftTop', 'bottomLeft', \Freesewing\BezierToolbox::bezierCircle($p->distance('bottomLeftTop', 'bottomLeft'))));
$p->addPoint('bottomLeftRight', $p->rotate('bottomLeftTop', 'bottomLeft', -90));
$p->addPoint('bottomLeftCpRight', $p->rotate('bottomLeftCpTop', 'bottomLeft', -90));
$rotateThese = ['bottomLeftTop','bottomLeftCpTop','bottomLeftRight','bottomLeftCpRight'];
foreach($rotateThese as $pid) {
$p->addPoint($pid.'-r', $p->flipX($pid, $width/2));
}
// Mark edge of cuff
$p->addPoint('notchLeft', $p->shift('bottomLeft',90,$this->v('cuffLength')));
$p->addPoint('notchRight', $p->shift('bottomRight',90,$this->v('cuffLength')));
$p->newPath('outline', 'M topLeft L bottomLeftTop C bottomLeftCpTop bottomLeftCpRight bottomLeftRight
L bottomLeftRight-r C bottomLeftCpRight-r bottomLeftCpTop-r bottomLeftTop-r L topRight z');
// Mark path for sample service
$p->paths['outline']->setSample(true);
$p->addPoint('gridAnchor', $p->shiftFractionTowards('topLeft','topRight', 0.5));
}
/**
* Drafts the belt
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftBelt($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['belt'];
$p->newPoint('topLeft', 0, 0);
$p->newPoint('topRight', $this->v('beltLength'), 0);
$p->newPoint('bottomLeft', 0, $this->v('beltHeight'));
$p->newPoint('bottomRight', $p->x('topRight'), $p->y('bottomLeft'));
// Round the edges
$radius = 10;
$p->newPoint('topLeftRight', $radius, 0);
$p->newPoint('topLeftRightCp', $radius - \Freesewing\BezierToolbox::bezierCircle($radius), 0);
$p->newPoint('topLeftBottom', 0, $radius);
$p->newPoint('topLeftBottomCp', 0, $radius - \Freesewing\BezierToolbox::bezierCircle($radius));
$flipThese = ['topLeftRight','topLeftRightCp','topLeftBottom','topLeftBottomCp','topLeftBottomCp'];
foreach($flipThese as $pid) {
$p->addPoint($pid.'-b', $p->flipY($pid, $this->v('beltHeight')/2));
}
// Buttonholes
$p->newPoint('button', 30, $this->v('beltHeight')/2);
$p->newPath('outline', '
M topRight
L topLeftRight
C topLeftRightCp topLeftBottomCp topLeftBottom
L topLeftBottom-b
C topLeftBottomCp-b topLeftRightCp-b topLeftRight-b
L bottomRight L topRight z', ['class' => 'fabric']);
// Mark path for sample service
$p->paths['outline']->setSample(true);
}
/**
* Drafts the pocket
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftPocket($model)
{
$this->clonePoints('front', 'pocket');
/** @var \Freesewing\Part $p */
$p = $this->parts['pocket'];
// Path
$p->newPath('outline', '
M pocketTopLeft
L pocketBottomLeftTop
C pocketBottomLeftTopCp pocketBottomLeftRightCp pocketBottomLeftRight
L pocketBottomRightLeft
C pocketBottomRightLeftCp pocketBottomRightTopCp pocketBottomRightTop
L pocketTopRight
L pocketTopLeft
z', ['class' => 'fabric']);
// Mark path for sample service
$p->paths['outline']->setSample(true);
$p->addPoint('gridAnchor', $p->shiftFractionTowards('pocketTopLeft','pocketTopRight', 0.5));
}
/**
* Drafts the pocket flap
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftPocketFlap($model)
{
$this->clonePoints('front', 'pocketFlap');
/** @var \Freesewing\Part $p */
$p = $this->parts['pocketFlap'];
// Path
$p->newPath('outline', 'M pocketFlapTopLeft L pocketFlapBottomLeftTop
C pocketFlapBottomLeftTopCp pocketFlapBottomLeftRightCp pocketFlapBottomLeftRight
L pocketFlapBottomRightLeft
C pocketFlapBottomRightLeftCp pocketFlapBottomRightTopCp pocketFlapBottomRightTop
L pocketFlapTopRight
z', ['class' => 'fabric']);
// Mark path for sample service
$p->paths['outline']->setSample(true);
$p->addPoint('gridAnchor', $p->shiftFractionTowards('pocketFlapTopLeft','pocketFlapTopRight', 0.5));
}
/**
* Drafts the chest pocket welt
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftChestPocketWelt($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['chestPocketWelt'];
$p->newPoint('topLeft', 0, 0);
$p->newPoint('topRight', $this->v('chestPocketWidth')*2, 0);
$p->newPoint('bottomRight', $p->x('topRight'), $this->v('chestPocketHeight'));
$p->newPoint('bottomLeft', 0, $p->y('bottomRight'));
$p->newPoint('midTop', $p->x('topRight')/2, 0);
$p->newPoint('midBottom', $p->x('midTop'), $p->y('bottomRight'));
// Path
$p->newPath('outline', 'M topLeft L topRight L bottomRight L bottomLeft L topLeft z', ['class' => 'fabric']);
$p->newPath('foldline', 'M midTop L midBottom', ['class' => 'hint']);
// Mark path for sample service
$p->paths['outline']->setSample(true);
}
/**
* Drafts the inner pocket welt
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftInnerPocketWelt($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['innerPocketWelt'];
$p->newPoint('left', -20, 0);
$p->newPoint('leftTopWelt', $p->x('left')+20, $p->y('left')-5);
$p->newPoint('leftBottomWelt', $p->x('left')+20, $p->y('left')+5);
$p->newPoint('leftTopCorner', $p->x('left'), $p->y('left')-15);
$p->newPoint('leftBottomCorner', $p->x('left'), $p->y('left')+15);
$p->newPoint('right', $this->v('innerPocketWidth')+20, 0);
$p->newPoint('rightTopWelt', $p->x('right')-20, $p->y('right')-5);
$p->newPoint('rightBottomWelt', $p->x('right')-20, $p->y('right')+5);
$p->newPoint('rightTopCorner', $p->x('right'), $p->y('right')-15);
$p->newPoint('rightBottomCorner', $p->x('right'), $p->y('right')+15);
// Path
$p->newPath('outline', 'M leftTopCorner L rightTopCorner L rightBottomCorner L leftBottomCorner z', ['class' => 'lining']);
$p->newPath('foldline', 'M left L right', ['class' => 'help']);
$p->newPath('seamline', 'M leftTopWelt L rightTopWelt M leftBottomWelt L rightBottomWelt', ['class' => 'hint']);
// Mark path for sample service
$p->paths['outline']->setSample(true);
}
/**
* Drafts the inner pocket bag
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftInnerPocketBag($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['innerPocketBag'];
$p->newPoint('topLeft', 0, 0);
$p->newPoint('topRight', $this->v('innerPocketWidth')+40, 0);
$p->addPoint('midTopLeft', $p->shift('topLeft', -90, 30));
$p->addPoint('midTopRight', $p->shift('topRight', -90, 30));
$p->addPoint('midBottomLeft', $p->shift('topLeft', -90, 60));
$p->addPoint('midBottomRight', $p->shift('topRight', -90, 60));
$p->addPoint('bottomLeft', $p->shift('topLeft', -90, 90));
$p->addPoint('bottomRight', $p->shift('topRight', -90, 90));
$p->newPath('outline', 'M midTopLeft L topLeft L topRight L midTopRight
M midBottomLeft L bottomLeft L bottomRight L midBottomRight'
, ['class' => 'lining']);
$p->newPath('help', 'M midTopLeft L midBottomLeft M midTopRight L midBottomRight', ['class' => 'help']);
// Mark path for sample service
$p->paths['outline']->setSample(true);
}
/**
* Drafts the inner pocket tab
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function draftInnerPocketTab($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['innerPocketTab'];
$p->newPoint('topLeft', 0, 0);
$p->newPoint('topRight', $this->v('innerPocketWidth')+20, 0);
$p->newPoint('bottom', $this->v('innerPocketWidth')/2+10 , $this->v('innerPocketWidth')/2+10);
$p->newPoint('top', $this->v('innerPocketWidth')/2+10, 0);
$p->newPath('outline', 'M topLeft L topRight L bottom z', ['class' => 'lining']);
$p->newPath('foldline', 'M top L bottom', ['class' => 'help']);
// Mark path for sample service
$p->paths['outline']->setSample(true);
}
/*
_____ _ _ _
| ___(_)_ __ __ _| (_)_______
| |_ | | '_ \ / _` | | |_ / _ \
| _| | | | | | (_| | | |/ / __/
|_| |_|_| |_|\__,_|_|_/___\___|
Adding titles/logos/seam-allowance/grainline and so on
*/
/**
* Finalizes the front
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizeFront($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['front'];
// Fusible interfacing armhole
$fw = $this->getValue("fusibleWidth");
$p->offsetPathString('fuse', 'M 8 L 12 C 19 17 10 C 18 15 14 C 16 13 5', (-1 * $fw), 1, ['class' => 'help']);
$p->newTextOnPath('fuse1', 'M 12 C 19 17 10 C 18 15 14 C 16 13 5', $this->t('Apply fusible interfacing here'), ['dy' => $fw/2], 0);
$p->newTextOnPath('fuse2', 'M 8 L 12', $this->t('Apply fusible interfacing here'), ['dy' => $fw/2], 0);
// Fusible interfacing inner pocket
$p->newPoint('fuseIpTopLeft', $p->x('innerPocketTopLeft')-15, $p->y('innerPocketTopLeft')-15);
$p->newPoint('fuseIpTopRight', $p->x('innerPocketTopRight')+15, $p->y('innerPocketTopLeft')-15);
$p->newPoint('fuseIpBotLeft', $p->x('innerPocketBottomLeft')-15, $p->y('innerPocketBottomLeft')+15);
$p->newPoint('fuseIpBotRight', $p->x('innerPocketBottomRight')+15, $p->y('innerPocketBottomLeft')+15);
$p->newPath('fuseIp', 'M fuseIpTopLeft L fuseIpTopRight L fuseIpBotRight L fuseIpBotLeft z', ['class' => 'lining help']);
$p->newTextOnPath('fuseIp', 'M fuseIpBotLeft L fuseIpBotRight', $this->t('Apply fusible interfacing here'), ['class' => 'center', 'dy' => -2], 0);
// Fusible interfacing hem
$p->newPoint('fuseHemLeft', $p->x('hemFrontEdge'), $p->y('hemFrontEdge')-$fw);
$p->newPoint('fuseHemRight', $p->x('hemSide'), $p->y('hemFrontEdge')-$fw);
$p->newPath('fuseHem', 'M fuseHemLeft L fuseHemRight', ['class' => 'fabric help']);
$p->newTextOnPath('fuseHem', 'M fuseHemLeft L fuseHemRight', $this->t('Apply fusible interfacing here'), ['class' => 'center', 'dy' => $fw/2], 0);
// Breakline
$p->addPoint('rollLineEdge', $p->shiftOutwards(12, 8, 20));
$p->newPoint('rollLineBot',$p->x('frontEdge'), $p->y('button3Left'));
$p->curveCrossesLine(9, 21, 20, 8, 'rollLineBot', 'rollLineEdge', 'bl');
$p->clonePoint('bl1', 'rollLineTop');
$p->newPath('rollLine', 'M rollLineTop L rollLineBot', ['class' => 'canvas help']);
$p->newTextOnPath('rollLine', 'M rollLineBot L rollLineTop', $this->t('Roll line'), ['dy' => -1],0);
$p->newTextOnPath('csp1', 'M rollLineTop L rollLineBot', $this->t('Canvas chest piece'), ['dy' => -1],0);
// Shoulder canvas piece
$p->addPoint('csp1', $p->shift('rollLineBot', $p->angle('rollLineBot', 'rollLineEdge')-110, $p->distance(3,'waistSide')/2));
$p->addPoint('csp2', $p->beamsCross(5, 'waistSideCpTop', 3, 'waistSide'));
$p->newPath('canvasShoulderPiece', 'M rollLineBot C csp1 csp2 5', ['class' => 'help']);
$p->newTextOnPath('csp', 'M rollLineBot C csp1 csp2 5', $this->t('Canvas chest piece'), ['dy' => -1],0);
// Title
$p->newPoint('titleAnchor', $p->x(21), $p->y(10));
$p->addTitle('titleAnchor', 1, $this->t($p->title),
'2x '.
$this->t('from fabric').
"\n2x ".
$this->t('facing from fabric').
"\n2x ".
$this->t('non-facing from lining')
);
// Scalebox
$p->newPoint('scaleboxAnchor', $p->x(21), $p->y(5));
$p->newSnippet('scalebox','scalebox','scaleboxAnchor');
// Logo
$p->addPoint('logoAnchor', $p->shiftFractionTowards('titleAnchor','scaleboxAnchor',0.5));
$p->newSnippet('logo','logo','logoAnchor');
// Grainline
$p->newPoint('grainlineTop', $p->x('collarTip')+30, $p->y('collarTip')+20);
$p->newPoint('grainlineBottom', $p->x('grainlineTop'), $p->y('hemFrontEdge')-20);
$p->newGrainline('grainlineBottom', 'grainlineTop', $this->t('Grainline'));
// Buttons
$p->newSnippet('button1Left','button-lg','button1Left');
$p->newSnippet('button2Left','button-lg','button2Left');
$p->newSnippet('button3Left','button-lg','button3Left');
$p->newSnippet('button1Right','button-lg','button1Right');
$p->newSnippet('button2Right','button-lg','button2Right');
$p->newSnippet('button3Right','button-lg','button3Right');
// Center front helpline
$p->newPath('cf', 'M hemMiddle L 9', ['class' => 'help']);
$p->newTextOnPath('cf1', 'M hemMiddle L 4', $this->t('Center front'), ['dy' => -2], false);
$p->newTextOnPath('cf2', 'M 4 L 3', $this->t('Center front'), ['dy' => -2], false);
$p->newTextOnPath('cf3', 'M 3 L 2', $this->t('Center front'), ['dy' => -2], false);
$p->newTextOnPath('cf4', 'M 2 L 9', $this->t('Center front'), ['dy' => -2], false);
// Facing lining border (flb)
$p->newPoint('flbBottom', $p->x('pocketTopLeft')-12.5, $p->y('hemFrontEdge'));
$p->curveCrossesX(9, 21, 20, 8, $p->x('flbBottom'), 'flb');
$p->clonePoint('flb1', 'flbTop');
$p->newPath('fldFacing', 'M flbTop L flbBottom',['class' => 'fabric']);
$p->newPath('fldLining', 'M flbTop L flbBottom',['class' => 'lining lashed']);
$p->newTextOnPath(1, 'M flbTop L flbBottom', $this->t('Facing/Lining boundary - Lining side'), ['dy' => -2, 'class' => 'fill-lining'], false);
$p->newTextOnPath(2, 'M flbBottom L flbTop', $this->t('Facing/Lining boundary - Facing side'), ['dy' => -2, 'class' => 'fill-fabric'], false);
$p->newPoint('facingNoteAnchor', $p->x('flbBottom'), $p->y('seatSide'));
$p->newNote('flb', 'facingNoteAnchor', $this->t('Add seam allowance at the facing/lining border'), 4, 40 );
// Notches
$p->notch(['collarBendPoint', 10, 'waistSide']);
// Waistline
$p->newPath('waistline', 'M 3 L waistSide', ['class' => 'help']);
// Seam allowance
if($this->o('sa')) {
$p->offsetPath('sa','outline',$this->o('sa')*-1,1,['class' => 'sa fabric']);
// Extra hem SA
$p->addPoint('sa-line-hemFrontEdgeTOhemSide', $p->shift('sa-line-hemFrontEdgeTOhemSide',-90,$this->o('sa')*4));
$p->addPoint('sa-line-hemSideTOhemFrontEdge', $p->shift('sa-line-hemSideTOhemFrontEdge',-90,$this->o('sa')*4));
// Notes
$p->addPoint('noteAnchor1', $p->shift('hemSide', 90, 30));
$p->addPoint('noteAnchor2', $p->shift('hemSide', 180, 120));
$p->newNote('sa1', 'noteAnchor1', $this->t('Standard seam allowance')."\n(".$p->unit($this->o('sa')).')', 10, 40, $this->o('sa')*-0.5);
$p->newNote('sa2', 'noteAnchor2', $this->t('Hem allowance')."\n(".$p->unit($this->o('sa')*5).')', 12, 30, $this->o('sa')*-2.5);
// Straighten hem
$p->newPoint('sa-line-hemFrontEdgeTOhemSide', $p->x('sa-line-hemFrontEdgeTOcollarBendPoint'), $p->y('sa-line-hemFrontEdgeTOhemSide'));
$p->newPoint('sa-line-hemSideTOhemFrontEdge', $p->x('sa-line-hemSideTOseatSide'), $p->y('sa-line-hemSideTOhemFrontEdge'));
}
// Store length to sleeve notch
$this->setValue('toFrontSleeveNotch', $p->curveLen(12,19,17,10));
}
/**
* Finalizes the back
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizeBack($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['back'];
// Back stay
$p->addPoint('backStay1', $p->shiftFractionTowards('bpTopIn', 10, 0.5));
$p->addPoint('backStay2', $p->shiftAlong(5, 'chestSideCp', 'waistSideCpTop', 'waistSide', 30));
$p->addPoint('backStay3', $p->shift('backStay2', 180, $p->distance('backStay2','dartTip')/2));
$p->newPath('backStay', 'M bpTopIn C backStay1 backStay3 backStay2', ['class' => 'help']);
$p->newTextOnPath('backStaye','M bpTopIn C backStay1 backStay3 backStay2', $this->t('Back stay'), ['dy' => -1, 'class' => 'center'], 0);
// Fusible interfacing armhole
$fw = $this->v('fusibleWidth');
$p->offsetPathString('fuse', 'M 1 C 1 7 8 L 12 C 19 17 10 C 18 15 14 C 16 13 5', (-1 * $fw), 1, ['class' => 'help']);
$p->newTextOnPath('fuse1', 'M 12 C 19 17 10 C 18 15 14 C 16 13 5', $this->t('Apply fusible interfacing here'), ['dy' => $fw/2, 'class' => 'center'], 0);
$p->newTextOnPath('fuse2', 'M 1 C 1 7 8 L 12', $this->t('Apply fusible interfacing here'), ['dy' => $fw/2], 0);
// Title
$p->newPoint('titleAnchor', $p->x(8), $p->y(18));
$p->addTitle('titleAnchor', 2, $this->t($p->title),
'2x '.
$this->t('from fabric').
"\n2x ".
$this->t('from lining')
);
// Logo
$p->newSnippet('logo','logo', 21);
// Grainline
$p->newPoint('grainlineTop', $p->x(1)+20, $p->y(1)+20);
$p->newPoint('grainlineBottom', $p->x('grainlineTop'), $p->y('waistSide')-20);
$p->newGrainline('grainlineBottom', 'grainlineTop', $this->t('Grainline'));
// Enforcement triangle
$p->addPoint('triangleRight', $p->shift('bpTopIn', 0, $p->distance('bpTopIn','bpTop')*0.6));
$p->addPoint('triangleTop', $p->rotate('triangleRight','bpTopIn',90));
$p->newPath('triangle', 'M bpTopIn L triangleRight L triangleTop z', ['class' => 'help']);
// Notches
$p->notch([10]);
// Seam allowance
if($this->o('sa')) {
// FIXME : This is a hack because path offset is tricky at this neck curve
$p->addPoint('split', $p->shiftAlong(8, 20, 1, 1, 10));
$p->splitCurve(8,20,1,1,'split','split');
$path = 'M split C split7 1 1 L bpTopIn L bpTop L bpBottom L waistSide C waistSideCpTop chestSideCp 5 C 13 16 14 C 15 18 10 C 17 19 12 L 8';
$p->offsetPathString('sa', $path,$this->o('sa')*-1,1,['class' => 'sa fabric']);
$p->newPath('closeSa', 'M sa-endPoint L sa-startPoint',['class' => 'sa fabric']);
$p->newNote('sa', 'chestSideCp', $this->t('Standard seam allowance')."\n(".$p->unit($this->o('sa')).')', 9, 30, $this->o('sa')*-0.4);
}
// Store length to sleeve notch
$this->setValue('toBackSleeveNotch', $p->curveLen(12,19,17,10));
}
/**
* Finalizes the tail
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizeTail($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['tail'];
// Fusible interfacing tail
$fw = $this->getValue("fusibleWidth");
$p->addPoint('fuseLeft', $p->shift('leftTop-3', 90, $fw));
$p->addPoint('fuseRight', $p->shift('waistTop-3', 90, $fw));
$p->newPath('fuse', 'M fuseLeft L fuseRight', ['class' => 'fabric help']);
$p->newTextOnPath('fuse', 'M fuseLeft L fuseRight', $this->t('Apply fusible interfacing here'), ['dy' => $fw/2], 0);
// Title
$p->newPoint('titleAnchor', $p->x('waistTop')/2, $p->y('leftTop-3')/2);
$p->addTitle('titleAnchor', 3, $this->t($p->title),
'2x '.
$this->t('from fabric').
"\n2x ".
$this->t('from lining')
);
// Logo
$p->newPoint('logoAnchor', $p->x('leftPleat2')/2, $p->y('leftTop-3')/2);
$p->newSnippet('logo','logo', 'logoAnchor');
// Grainline
$p->newPoint('grainlineTop', $p->x('leftTop')+20, $p->y('leftTop')+10);
$p->newPoint('grainlineBottom', $p->x('grainlineTop'), $p->y('leftTop-3')-10);
$p->newGrainline('grainlineBottom', 'grainlineTop', $this->t('Grainline'));
// Seam allowance
if($this->o('sa')) {
$p->offsetPathString('sa','M leftTop L leftTop-3 L waistTop-3 L waistTop L leftTop z',$this->o('sa')*-1,1,['class' => 'sa fabric']);
$p->addPoint('sa-line-leftTop-3TOwaistTop-3', $p->shift('sa-line-leftTop-3TOwaistTop-3',-90,$this->o('sa')*4));
$p->addPoint('sa-line-waistTop-3TOleftTop-3', $p->shift('sa-line-waistTop-3TOleftTop-3',-90,$this->o('sa')*4));
$p->addPoint('noteAnchor1', $p->shift('waistTop', -90, 20));
$p->addPoint('noteAnchor2', $p->shift('leftPleat3-3', -90, 12));
$p->newNote('sa1', 'noteAnchor1', $this->t('Standard seam allowance')."\n(".$p->unit($this->o('sa')).')', 9, 10, $this->o('sa')*-0.5);
$p->newNote('sa2', 'noteAnchor2', $this->t('Hem allowance')."\n(".$p->unit($this->o('sa')*5).')', 2, 40);
// Straighten hem
$p->newPoint('sa-line-waistTop-3TOleftTop-3', $p->x('sa-line-waistTop-3TOwaistTop'), $p->y('sa-line-waistTop-3TOleftTop-3'));
$p->newPoint('sa-line-leftTop-3TOwaistTop-3', $p->x('sa-line-leftTop-3TOleftTop'), $p->y('sa-line-leftTop-3TOwaistTop-3'));
}
}
/**
* Finalizes the topsleeve
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizeTopsleeve($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['topsleeve'];
// Fusible interfacing armhole
$fw = $this->getValue("fusibleWidth");
$fp = 'M topsleeveLeftEdge C topsleeveLeftEdgeCpRight frontPitchPointCpBottom frontPitchPoint C frontPitchPointCpTop sleeveTopCpLeft sleeveTop C sleeveTopCpRight backPitchPoint backPitchPoint';
$p->offsetPathString('fuse', $fp, (-1 * $fw), 1, ['class' => 'help']);
$p->addPoint('fuse1', $p->shiftAlong('backPitchPoint', 'backPitchPoint', 'topsleeveRightEdgeCpTop', 'topsleeveRightEdge', $fw));
$p->newPoint('fuse2',$p->x('fuse-endPoint'), $p->y('fuse1'));
$p->newPath('fuseClosing', 'M fuse-endPoint C fuse-endPoint fuse2 fuse1', ['class' => 'help']);
$p->newTextOnPath('fuse1', $fp, $this->t('Apply fusible interfacing here'), ['dy' => $fw/2], 0);
// Title
$p->newPoint('titleAnchor', $p->x('sleeveTop'), $p->y('topsleeveRightEdge')+80);
$p->addTitle('titleAnchor', 4, $this->t($p->title),
'2x '.
$this->t('from fabric').
"\n2x ".
$this->t('from lining')
);
// Logo
$p->newPoint('logoAnchor', $p->x('sleeveTop'), $p->y('elbowRight')-25);
$p->newSnippet('logo','logo', 'logoAnchor');
// Grainline
$p->newPoint('grainlineTop', $p->x('sleeveTop'), $p->y('sleeveTop')+20);
$p->newPoint('grainlineBottom', $p->x('grainlineTop'), $p->y('topsleeveWristLeft')-20);
$p->newGrainline('grainlineBottom', 'grainlineTop', $this->t('Grainline'));
// Front sleeve notch
$curveLen = $p->curveLen('sleeveTop','sleeveTopCpLeft','frontPitchPointCpTop','frontPitchPoint');
$target = $this->v('toFrontSleeveNotch') + $this->o('sleevecapEase')/2;
if($target > $curveLen) $p->addPoint('frontSleeveNotch', $p->shiftAlong('frontPitchPoint','frontPitchPointCpBottom','topsleeveLeftEdgeCpRight','topsleeveLeftEdge', $target));
else $p->addPoint('frontSleeveNotch', $p->shiftAlong('sleeveTop','sleeveTopCpLeft','frontPitchPointCpTop','frontPitchPoint', $target));
$p->notch(['sleeveTop', 'frontSleeveNotch']);
// Back sleeve notch
$curveLen = $p->curveLen('sleeveTop','sleeveTopCpRight','backPitchPoint','backPitchPoint');
$target = $this->v('toBackSleeveNotch') + $this->o('sleevecapEase')/2;
if($target > $curveLen) {
$this->setValue('backSleeveNotchInUndersleeve', true);
$this->setValue('backSleeveNotchTopsleeveLen', $curveLen);
} else {
$this->setValue('backSleeveNotchInUndersleeve', false);
$p->addPoint('backSleeveNotch', $p->shiftAlong('sleeveTop','sleeveTopCpRight','backPitchPoint','backPitchPoint', $target));
$p->notch(['backSleeveNotch']);
}
// Seam allowance
if($this->o('sa')) {
// FIXME : This is a hack because path offset is tricky at this sleeve curve
$p->addPoint('split', $p->shiftAlong('topsleeveLeftEdge' ,'topsleeveLeftEdgeCpRight', 'frontPitchPointCpBottom', 'frontPitchPoint', 10));
$p->splitCurve('topsleeveLeftEdge' ,'topsleeveLeftEdgeCpRight', 'frontPitchPointCpBottom', 'frontPitchPoint','split','split');
$p->offsetPathString('sa1', 'M split
C split7 split6 frontPitchPoint
C frontPitchPointCpTop sleeveTopCpLeft sleeveTop
C sleeveTopCpRight backPitchPoint backPitchPoint', $this->o('sa'), 1,['class' => 'sa fabric']);
$p->offsetPathString('sa2', 'M backPitchPoint
C backPitchPoint topsleeveRightEdgeCpTop topsleeveRightEdge
C topsleeveRightEdgeCpBottom elbowRightCpTop elbowRight
L topsleeveWristRight
L cuffBottomRightTop
C cuffBottomRightCpTop cuffBottomRightCpLeft cuffBottomRightLeft
L cuffBottomLeft
L topsleeveWristLeft
L topsleeveElbowLeft
C topsleeveElbowLeftCpTop topsleeveLeftEdge topsleeveLeftEdge
', $this->o('sa')/2, 1,['class' => 'sa fabric']);
$p->newPath('sa3', 'M sa1-startPoint L sa2-endPoint M sa1-endPoint L sa2-startPoint',['class' => 'sa fabric']);
$p->newNote('sa1', 'frontPitchPointCpTop', $this->t('Standard seam allowance')."\n(".$p->unit($this->o('sa')).')', 3, 30);
$p->newNote('sa2', 'elbowRightCpTop', $this->t('Half of the standard seam allowance')."\n(".$p->unit($this->o('sa')/2).')', 9, 30);
}
}
/**
* Finalizes the undersleeve
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizeUndersleeve($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['undersleeve'];
// Fusible interfacing armhole
$fw = $this->getValue("fusibleWidth");
$fp = 'M undersleeveLeftEdgeRight C undersleeveLeftEdgeCpRight undersleeveTipCpBottom undersleeveTip';
$p->addPoint('fuseSplit', $p->shiftAlong('undersleeveTip', 'undersleeveTipCpBottom', 'undersleeveLeftEdgeCpRight', 'undersleeveLeftEdgeRight', $fw*2));
$p->splitCurve('undersleeveLeftEdgeRight', 'undersleeveLeftEdgeCpRight', 'undersleeveTipCpBottom', 'undersleeveTip', 'fuseSplit', 'fuseSplit');
$p->offsetPathString('fuse', 'M undersleeveLeftEdgeRight C fuseSplit2 fuseSplit3 fuseSplit', (-1 * $fw), 1, ['class' => 'help']);
$p->curveCrossesY('undersleeveElbowLeft', 'undersleeveElbowLeftCpTop', 'undersleeveLeftEdge', 'undersleeveLeftEdge', $p->y('fuse-startPoint'), '.fuse');
$p->clonePoint('.fuse1', 'fuseLeftEdge');
$p->addPoint('.fuse2', $p->shiftOutwards('fuse-cp2--undersleeveLeftEdgeRight.fuseSplit2.fuseSplit3.fuseSplit', 'fuse-curve-fuseSplitTOundersleeveLeftEdgeRight', 200));
$p->curveCrossesLine('undersleeveTip', 'undersleeveTip', 'undersleeveRightEdgeCpTop', 'undersleeveRightEdge', '.fuse2', 'fuse-curve-fuseSplitTOundersleeveLeftEdgeRight', '.fuse');
$p->clonePoint('.fuse1', 'fuseRightEdge');
$p->newPath('fuseClosing', 'M fuse-endPoint L fuseRightEdge M fuse-startPoint L fuseLeftEdge', ['class' => 'help']);
$p->newTextOnPath('fuse1', $fp, $this->t('Apply fusible interfacing here'), ['dy' => $fw/2, 'class' => 'center'], 0);
// Title
$p->addTitle('undersleeveWristLeftHelperTop', 5, $this->t($p->title),
'2x '.
$this->t('from fabric').
"\n2x ".
$this->t('from lining')
);
// Logo
$p->addPoint('logoAnchor', $p->shift('undersleeveWristLeftHelperTop', 90, 100));
$p->newSnippet('logo','logo-sm', 'logoAnchor');
// Grainline
$p->newPoint('grainlineTop', $p->x('logoAnchor'), $p->y('undersleeveLeftEdge')+20);
$p->newPoint('grainlineBottom', $p->x('grainlineTop'), $p->y('undersleeveWristLeft')-20);
$p->newGrainline('grainlineBottom', 'grainlineTop', $this->t('Grainline'));
// Notches
if($this->v('backSleeveNotchInUndersleeve')) {
$p->addPoint('backSleeveNotch', $p->shiftAlong('undersleeveTip','undersleeveTipCpBottom','undersleeveLeftEdgeCpRight','undersleeveLeftEdgeRight', $this->v('toBackSleeveNotch') - $this->v('backSleeveNotchTopsleeveLen')));
$p->notch(['backSleeveNotch']);
}
// Seam allowance
if($this->o('sa')) {
$p->offsetPathString('sa1', 'M undersleeveLeftEdge
L undersleeveLeftEdgeRight
C undersleeveLeftEdgeCpRight undersleeveTipCpBottom undersleeveTip
', $this->o('sa'), 1,['class' => 'sa fabric']);
$p->offsetPathString('sa2', 'M undersleeveTip
C undersleeveTip undersleeveRightEdgeCpTop undersleeveRightEdge
C undersleeveRightEdgeCpBottom elbowRightCpTop elbowRight
L undersleeveWristRight
L cuffBottomRightTop
C cuffBottomRightCpTop cuffBottomRightCpLeft cuffBottomRightLeft
L cuffBottomLeft
L undersleeveWristLeft
L undersleeveElbowLeft
C undersleeveElbowLeftCpTop undersleeveLeftEdge undersleeveLeftEdge
', $this->o('sa')/2, 1,['class' => 'sa fabric']);
$p->newPoint('sa-join', $p->x('undersleeveLeftEdge') - 0.5*$this->o('sa'), $p->y('undersleeveLeftEdge') - $this->o('sa'));
$p->addPoint('sa-tipjoin1', $p->shiftOutwards('undersleeveRightEdgeCpTop','undersleeveTip', $this->o('sa')));
$p->addPoint('sa-tipjoin1', $p->shift('sa-tipjoin1', $p->angle('undersleeveRightEdgeCpTop','undersleeveTip')-90, $this->o('sa')/2));
$p->newPath('sa3', 'M sa1-startPoint L sa-join L sa2-endPoint M sa1-endPoint L sa-tipjoin1 L sa2-startPoint',['class' => 'sa fabric']);
$p->newNote('sa1', 'undersleeveLeftEdgeRight', $this->t('Standard seam allowance')."\n(".$p->unit($this->o('sa')).')', 5, 30, $this->o('sa')/-2);
$p->newNote('sa2', 'undersleeveRightEdge', $this->t('Half of the standard seam allowance')."\n(".$p->unit($this->o('sa')/2).')', 8, 30, $this->o('sa')/-4);
}
}
/**
* Finalizes the belt
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizeBelt($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['belt'];
// Title
$p->newPoint('titleAnchor', $p->x('bottomRight')/2, $p->y('bottomRight')/2);
$p->addTitle('titleAnchor', 6, $this->t($p->title), '4x '.$this->t('from fabric'), ['scale'=> 80]);
// Button
$p->newSnippet('button','button-lg','button');
// Seam allowance
if($this->o('sa')) {
$p->offsetPath('sa','outline', $this->o('sa')*-0.5,1,['class' => 'sa fabric']);
$p->addPoint('sa-line-topRightTObottomRight', $p->shift('sa-line-topRightTObottomRight',0,$this->o('sa')*0.5));
$p->addPoint('sa-line-bottomRightTOtopRight', $p->shift('sa-line-bottomRightTOtopRight',0,$this->o('sa')*0.5));
$p->addPoint('noteanchor1', $p->shift('bottomRight', 90, 40));
$p->addPoint('noteanchor2', $p->shift('bottomRight', 180, 50));
$p->newNote('sa1', 'noteanchor1', $this->t('Standard seam allowance')."\n(".$p->unit($this->o('sa')).')', 9, 30, $this->o('sa')/-2);
$p->newNote('sa2', 'noteanchor2', $this->t('Half of the standard seam allowance')."\n(".$p->unit($this->o('sa')/2).')', 11, 20, $this->o('sa')/-4);
}
}
/**
* Finalizes the collar stand
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizeCollarStand($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['collarStand'];
// Title
$p->addPoint('titleAnchor', $p->shiftFractionTowards('standCenterTop','centerBottom',0.5));
$p->addTitle('titleAnchor', 7, $this->t($p->title), '2x '.$this->t('from fabric'), ['scale' => 40]);
// Seam allowance
if($this->o('sa')) {
$p->offsetPath('sa','outline', $this->o('sa')/2,1,['class' => 'sa fabric']);
$p->newNote('sa', 'centerBottom', $this->t('Half of the standard seam allowance')."\n(".$p->unit($this->o('sa')/2).')', 6, 20, $this->o('sa')/4);
}
}
/**
* Finalizes the collar
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizeCollar($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['collar'];
// Title
$p->newPoint('titleAnchor', $p->x('rot-4-cutBottom2'),$p->y('shapedTip')-20);
$p->addTitle('titleAnchor', 8, $this->t($p->title), '2x '.$this->t('from fabric'), ['scale' => 75, 'align'=>'left']);
// Cut on fold
$p->newPoint('cofTop', $p->x('centerTop'), $p->y('centerTop')+10);
$p->newPoint('cofBottom', $p->x('standCenterTop'), $p->y('standCenterTop')-10);
$p->newCutOnFold('cofBottom','cofTop',$this->t('cut on fold'));
// Grainline
$p->newPoint('grainlineTop', $p->x('centerTop')+30, $p->y('centerTop')+10);
$p->newPoint('grainlineBottom', $p->x('grainlineTop'), $p->y('standCenterTop')-10);
$p->newGrainline('grainlineBottom','grainlineTop', $this->t('grainline'));
// Seam allowance
if($this->o('sa')) {
$p->offsetPathString('sa','
M standCenterTop C curve1Cp1 curve1Cp2 cutBottom1
C rot-4-curve2Cp1 rot-4-curve2Cp2 rot-4-cutBottom2
C rot-3-curve3Cp1 rot-3-curve3Cp2 rot-3-cutBottom3
C rot-2-curve4Cp1 rot-2-rightBottom rot-2-rightBottom
L rot-1-rightCorner
L shapedTip
C rot-2-cutTop4 cutTop3 centerTop
', $this->o('sa')*-0.5,1,['class' => 'sa fabric']);
$p->newPath('sa-close', 'M sa-endPoint L standCenterTop M sa-startPoint L centerTop', ['class' => 'sa fabric']);
$p->newNote('sa', 'rot-3-cutBottom3', $this->t('Half of the standard seam allowance')."\n(".$p->unit($this->o('sa')/2).')', 9, 30, $this->o('sa')/4);
}
}
/**
* Finalizes the cuff facing
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizeCuffFacing($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['cuffFacing'];
// Title
$p->newPoint('titleAnchor', $p->x('bottomRight')/2, $p->y('bottomRight')/2);
$p->addTitle('titleAnchor', 9, $this->t($p->title), '2x '.$this->t('from fabric')."\n".'2x '.$this->t("from fusible interfacing"));
// Grainline
$p->newPoint('grainlineTop', $p->x('topLeft')+50, $p->y('topLeft')+5);
$p->newPoint('grainlineBottom', $p->x('grainlineTop'), $p->y('bottomLeft')-5);
$p->newGrainline('grainlineBottom','grainlineTop', $this->t('grainline'));
// Seam allowance
if($this->o('sa')) {
$p->offsetPath('sa','outline', $this->o('sa')*-0.5,1,['class' => 'sa fabric']);
$p->newNote('sa', 'notchRight', $this->t('Half of the standard seam allowance')."\n(".$p->unit($this->o('sa')/2).')', 9, 30, $this->o('sa')/-4);
}
}
/**
* Finalizes the pocket
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizePocket($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['pocket'];
// Fusible interfacing
$p->newPath('fuse', 'M pocketFlapBottomLeft L pocketFlapBottomRight', ['class' => 'fusible help']);
$p->newTextOnPath('fuse', 'M pocketFlapBottomLeft L pocketFlapBottomRight', $this->t('Apply fusible interfacing above this line'), ['class' => 'center', 'dy' => -2], 0);
// Title
$p->addPoint('titleAnchor', $p->shift('pocketTopLeft',-40,120));
$p->addTitle('titleAnchor', 10, $this->t($p->title),
'2x '.
$this->t('from fabric').
"\n2x ".
$this->t('from lining')
);
// Grainline
$p->newPoint('grainlineTop', $p->x('pocketTopLeft')+50, $p->y('pocketTopLeft')+5);
$p->newPoint('grainlineBottom', $p->x('grainlineTop'), $p->y('pocketBottomLeftRight')-5);
$p->newGrainline('grainlineBottom','grainlineTop', $this->t('grainline'));
// Seam allowance
if($this->o('sa')) {
$p->offsetPath('sa','outline', $this->o('sa')*-0.5,1,['class' => 'sa fabric']);
$p->addPoint('sa-line-pocketTopLeftTOpocketTopRight', $p->shift('sa-line-pocketTopLeftTOpocketTopRight', 90, $this->o('sa')*1.5));
$p->addPoint('sa-line-pocketTopRightTOpocketTopLeft', $p->shift('sa-line-pocketTopRightTOpocketTopLeft', 90, $this->o('sa')*1.5));
$p->addPoint('note1anchor', $p->shift('pocketTopRight', 180, 60));
$p->newNote('sa1', 'note1anchor', $this->t('Twice the standard seam allowance')."\n(".$p->unit($this->o('sa')*2).')', 6, 20, $this->o('sa')*-1);
$p->newNote('sa2', 'pocketBottomRightTop', $this->t('Half of the standard seam allowance')."\n(".$p->unit($this->o('sa')/2).')', 9, 20, $this->o('sa')/-4);
// Straighten HEM
$p->newPoint('sa-line-pocketTopLeftTOpocketTopRight', $p->x('sa-endPoint'), $p->y('sa-line-pocketTopLeftTOpocketTopRight'));
$p->newPoint('sa-line-pocketTopRightTOpocketTopLeft', $p->x('sa-line-pocketTopRightTOpocketBottomRightTop'), $p->y('sa-line-pocketTopRightTOpocketTopLeft'));
}
}
/**
* Finalizes the pocket flap
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizePocketFlap($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['pocketFlap'];
// Title
$p->addPoint('titleAnchor', $p->shift('pocketTopLeft',-10,100));
$p->addTitle('titleAnchor', 11, $this->t($p->title),
'2x '.
$this->t('from fabric').
"\n2x ".
$this->t('from lining').
"\n2x ".
$this->t('from fusible interfacing')
, ['scale' => 70, 'align'=>'left']);
// Grainline
$p->newPoint('grainlineTop', $p->x('pocketTopLeft')+50, $p->y('pocketTopLeft')-5);
$p->newPoint('grainlineBottom', $p->x('grainlineTop'), $p->y('pocketFlapBottomLeftRight')-5);
$p->newGrainline('grainlineBottom','grainlineTop', $this->t('grainline'));
// Seam allowance
if($this->o('sa')) {
$p->offsetPath('sa','outline', $this->o('sa')*-0.5,1,['class' => 'sa fabric']);
$p->newNote('sa', 'pocketFlapBottomRightTop', $this->t('Half of the standard seam allowance')."\n(".$p->unit($this->o('sa')/2).')', 9, 20, $this->o('sa')/-4);
}
}
/**
* Finalizes the chest pocket welt
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizeChestPocketWelt($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['chestPocketWelt'];
// Title
$p->newPoint('titleAnchor', $p->x('bottomRight')/2, $p->y('bottomRight')/2);
$p->addTitle('titleAnchor', 12, $this->t($p->title), '2x '.$this->t('from fabric'), ['scale' => 60, 'rotate' => -90]);
// Grainline
$p->newPoint('grainlineTop', $p->x('topLeft')+10, $p->y('topLeft')+5);
$p->newPoint('grainlineBottom', $p->x('grainlineTop'), $p->y('bottomLeft')-5);
$p->newGrainline('grainlineBottom','grainlineTop', $this->t('grainline'));
// Note
$p->newNote('fuse', 'grainlineBottom', $this->t('Apply fusible interfacing')."\n".$this->t('to half of the welt'), 2, 20, 10);
// Seam allowance
if($this->o('sa')) {
$p->offsetPath('sa','outline', $this->o('sa')/2,1,['class' => 'sa fabric']);
}
}
/**
* Finalizes the inner pocket welt
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizeInnerPocketWelt($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['innerPocketWelt'];
// Title
$p->newPoint('titleAnchor', $p->x('rightTopWelt')/2, 0);
$p->addTitle('titleAnchor', 13, $this->t($p->title), '4x '.$this->t('from lining'), ['scale' => 50]);
// Note
$p->addPoint('noteAnchor', $p->shift('leftBottomCorner', 0, 30));
$p->newNote('sa', 'noteAnchor', $this->t('Cut out without seam allowance'), 4, 20);
}
/**
* Finalizes the inner pocket bag
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizeInnerPocketBag($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['innerPocketBag'];
// Title
$p->newPoint('titleAnchor', $p->x('bottomRight')/2, $p->y('bottomRight')/2);
$p->addTitle('titleAnchor', 14, $this->t($p->title), '2x '.$this->t('from lining'), ['scale' => 75]);
// Note
$p->addPoint('noteAnchor', $p->shift('bottomLeft', 0, 30));
$p->newNote('sa', 'noteAnchor', $this->t('Cut out without seam allowance'), 2, 20);
// Height
$p->newHeightDimension('bottomLeft','topLeft',$p->x('topLeft')+20, $p->unit(350));
}
/**
* Finalizes the inner pocket tab
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function finalizeInnerPocketTab($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['innerPocketTab'];
// Title
$p->newPoint('titleAnchor', $p->x('bottom'), $p->y('bottom')/2.5);
$p->addTitle('titleAnchor', 15, $this->t($p->title), '2x '.$this->t('from lining'), ['scale' => 50]);
// Buttonhole
$p->addPoint('buttonholeAnchor1', $p->shift('top', -45, 15));
$p->newSnippet('btn1','buttonhole','buttonholeAnchor1', ['transform' => 'rotate(-45, '.$p->x('buttonholeAnchor1').', '.$p->y('buttonholeAnchor1').')']);
// Note
$p->addPoint('noteAnchor', $p->shift('topLeft', 0, 15));
$p->newNote('sa', 'noteAnchor', $this->t('Cut out without seam allowance'), 4, 8, 0);
}
/*
____ _
| _ \ __ _ _ __ ___ _ __| | ___ ___ ___
| |_) / _` | '_ \ / _ \ '__| |/ _ \/ __/ __|
| __/ (_| | |_) | __/ | | | __/\__ \__ \
|_| \__,_| .__/ \___|_| |_|\___||___/___/
|_|
Instructions for paperless patterns
*/
/**
* Adds paperless info for the front part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessFront($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['front'];
// Heigh left side
$xBase = $p->x('hemFrontEdge') - 15;
if($this->o('sa')) {
$xBase -= $this->o('sa');
$sa = $this->o('sa');
} else $sa = 0;
$p->newHeightDimension('collarBendPoint', 'collarTip', $xBase);
$p->newHeightDimension('button1Left', 'button2Left', $xBase-15);
$p->newHeightDimension('button2Left', 'button3Left', $xBase-15);
$p->newHeightDimension('button3Left', 'collarTip', $xBase-15);
$p->newHeightDimension('hemFrontEdge', 'collarTip', $xBase-45);
$p->newHeightDimension('hemFrontEdge', 8, $xBase-60);
$p->newHeightDimension('hemFrontEdge', 3, $xBase-30);
$p->newHeightDimension(3, 'collarTip', $xBase-30);
$p->newHeightDimension('flbTop', 8, $p->x('flbTop')-15-$sa);
$p->newHeightDimension(3, 'button3Right', $p->x(3)+20);
// Heigh right side
$xBase = $p->x('hemSide') + 15;
if($this->o('sa')) $xBase += $this->o('sa');
$p->newHeightDimension('flbTop', 8, $p->x('flbTop')-15-$sa);
$p->newHeightDimension('waistSide', 5, $xBase);
$p->newHeightDimension('waistSide', 10, $xBase+15);
$p->newHeightDimension('waistSide', 12, $xBase+30);
$p->newHeightDimension('waistSide', 8, $xBase+45);
$p->newHeightDimension('pocketFlapTopRight', 'waistSide', $xBase);
$p->newHeightDimension('pocketTopRight', 'waistSide', $xBase+15);
$p->newHeightDimension('hemSide', 'waistSide', $xBase+30);
// Width top
$p->newWidthDimensionSm('collarBendPoint','collarTip', $p->y('collarTip')-15-$sa);
$p->newWidthDimension('collarBendPoint',9, $p->y('collarTip')-30-$sa);
$p->newWidthDimension('collarBendPoint','flbTop', $p->y(8)-15-$sa);
$p->newWidthDimension('collarBendPoint',8, $p->y(8)-30-$sa);
$p->newWidthDimension('collarBendPoint',10, $p->y(8)-45-$sa);
$p->newWidthDimension('collarBendPoint',12, $p->y(8)-60-$sa);
$p->newWidthDimension('collarBendPoint',5, $p->y(8)-75-$sa);
$p->newLinearDimension(3, 'waistSide');
// Width bottom
$p->newWidthDimension('hemFrontEdge','hemMiddle', $p->y('hemFrontEdge')+15+$sa*5);
$p->newWidthDimension('hemFrontEdge','flbBottom', $p->y('hemFrontEdge')+30+$sa*5);
$p->newWidthDimension('hemFrontEdge','hemSide', $p->y('hemFrontEdge')+45+$sa*5);
// Main pocket
$p->newHeightDimension('pocketBottomRightLeft', 'pocketTopRight', $p->x('pocketBottomRightLeft')-10);
$p->newHeightDimension('pocketFlapBottomLeftRight', 'pocketFlapTopLeft', $p->x('pocketFlapBottomLeftRight')+10);
$p->newWidthDimension('pocketBottomLeftTop','pocketBottomRightTop', $p->y('pocketBottomLeft')+15);
$p->newWidthDimension('pocketFlapTopLeft','pocketFlapTopRight', $p->y('pocketFlapTopLeft')-15);
$p->newWidthDimension(4,'pocketFlapBottomLeft', $p->y('pocketFlapBottomLeft'));
// Chest pocket
$p->newLinearDimension('chestPocketTopLeft','chestPocketTopRight', -15);
$p->newLinearDimension('chestPocketBottomRight','chestPocketTopRight', 15);
$p->newNote(1, 'chestPocketTopRight', $this->v('chestPocketRotation').' '.$this->t('degree').' '.$this->t('slant'), 1, 30, -20);
$p->newWidthDimension(3, 'chestPocketTopLeft', $p->y('chestPocketTopLeft')+15);
// Inner pocket
$p->newWidthDimension(3, 'innerPocketBottomLeft', $p->y('innerPocketBottomLeft')+15);
$p->newWidthDimension('innerPocketBottomLeft', 'innerPocketBottomRight', $p->y('innerPocketBottomLeft')+15);
$p->newHeightDimension('waistSide', 'innerPocketRight', $p->x('innerPocketRight')+15);
}
/**
* Adds paperless info for the back part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessBack($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['back'];
// Heigh left side
$xBase = $p->x('bpTop') - 15;
if($this->o('sa')) {
$xBase -= $this->o('sa');
$sa = $this->o('sa');
} else $sa = 0;
// Height left
$p->newHeightDimension('bpBottom', 'bpTop', $xBase);
$p->newHeightDimension('bpBottom', 1, $xBase-15);
$p->newHeightDimension('bpBottom', 8, $xBase-30);
// Height dart
$p->newHeightDimension('dartLeft', 'dartTip', $p->x('dartLeft')-15);
// Height right
$p->newHeightDimension('waistSide', 5, $p->x(5)+15+$sa);
$p->newHeightDimension('waistSide', 10, $p->x(5)+30+$sa);
$p->newHeightDimension('waistSide', 12, $p->x(5)+45+$sa);
// Width top
$p->newWidthDimension('bpTop', 1, $p->y(8)-15-$sa);
$p->newWidthDimension(1, 8, $p->y(8)-15-$sa);
$p->newWidthDimension(1, 10, $p->y(8)-30-$sa);
$p->newWidthDimension(1, 12, $p->y(8)-45-$sa);
$p->newWidthDimension(1, 5, $p->y(8)-60-$sa);
// Width bottom
$p->newWidthDimension('bpBottom', 'dartLeft', $p->y('dartLeft')+15+$sa);
$p->newWidthDimensionSm('dartLeft', 'dartRight', $p->y('dartLeft')+15+$sa);
$p->newWidthDimension('bpBottom', 'waistSide', $p->y('dartLeft')+30+$sa);
$p->newWidthDimension('bpBottom', 5, $p->y('dartLeft')+45+$sa);
// Triangle
$p->newWidthDimensionSm('bpTopIn', 'triangleRight', $p->y('bpTopIn')+15);
$p->newHeightDimensionSm('triangleRight', 'triangleTop', $p->x('triangleRight')+15);
}
/**
* Adds paperless info for the tail part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessTail($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['tail'];
// Width
$yBase = $p->y('leftTop-3') + 15;
if($this->o('sa')) {
$yBase += $this->o('sa');
$sa = $this->o('sa');
} else $sa = 0;
$p->newWidthDimension('leftTop-3', 'leftPleat1-3', $yBase);
$p->newWidthDimension('leftPleat1-3', 'leftPleat2-3', $yBase);
$p->newWidthDimension('leftPleat2-3', 'cbTop-3', $yBase);
$p->newWidthDimension('cbTop-3', 'leftPleat3-3', $yBase);
$p->newWidthDimension('leftPleat3-3', 'dimBottom', $yBase);
$p->newWidthDimension('dimBottom', 'waistTop-3', $yBase);
$p->newWidthDimension('leftTop-3', 'waistTop-3', $yBase+15);
}
/**
* Adds paperless info for the topsleeve part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessTopsleeve($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['topsleeve'];
// Heigh left side
$xBase = $p->x('topsleeveLeftEdge') - 15;
if($this->o('sa')) {
$xBase -= $this->o('sa');
$sa = $this->o('sa');
} else $sa = 0;
// Height left
$p->newHeightDimension('topsleeveWristLeft', 'topsleeveLeftEdge', $xBase);
$p->newHeightDimension('cuffBottomLeft', 'topsleeveLeftEdge', $xBase-15);
$p->newHeightDimension('topsleeveLeftEdge', 'sleeveTop', $xBase);
$p->newHeightDimension('topsleeveRightEdge', 'sleeveTop', $p->x('topsleeveRightEdge')+15+$sa);
$p->newHeightDimension('elbowRight', 'topsleeveRightEdge', $p->x('topsleeveRightEdge')+15+$sa);
$p->newWidthDimension('topsleeveLeftEdge','sleeveTop', $p->y('sleeveTop')-15-$sa);
$p->newWidthDimension('sleeveTop', 'backPitchPoint', $p->y('sleeveTop')-15-$sa);
$p->newWidthDimension('sleeveTop', 'topsleeveRightEdge', $p->y('sleeveTop')-30-$sa);
$p->newWidthDimension('topsleeveLeftEdge', 'topsleeveRightEdge', $p->y('sleeveTop')-45-$sa);
// Linear
$p->newLinearDimension('topsleeveLeftEdge', 'topsleeveRightEdge');
$p->newLinearDimension('cuffBottomLeft', 'topsleeveWristLeft', 15);
$p->newLinearDimension('topsleeveElbowLeft', 'elbowRight');
$p->newLinearDimension('undersleeveWristRight', 'elbowRight', 15+$sa);
$p->newLinearDimension('topsleeveWristLeft', 'topsleeveElbowLeft', -15-$sa);
$p->newLinearDimension('topsleeveWristLeft', 'topsleeveWristRight', -15);
// Note
$p->newNote(1, 'topsleeveWristLeftHelperBottom', $this->o('sleeveBend').' '.$this->t('degree').' '.$this->t('slant'), 6, 30);
}
/**
* Adds paperless info for the undersleeve part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessUndersleeve($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['undersleeve'];
// Heigh left side
$xBase = $p->x('cuffBottomLeft') - 15;
if($this->o('sa')) {
$xBase -= $this->o('sa');
$sa = $this->o('sa');
} else $sa = 0;
// Height left
$p->newHeightDimension('undersleeveLeftEdge', 'undersleeveTip', $xBase-15);
$p->newHeightDimension('undersleeveElbowLeft', 'undersleeveLeftEdge', $xBase);
$p->newHeightDimension('cuffBottomLeft', 'undersleeveLeftEdge', $xBase-15);
$p->newHeightDimension('cuffBottomLeft', 'undersleeveTip', $xBase-30);
$p->newWidthDimension('undersleeveLeftEdge','grainlineTop', $p->y('undersleeveTip')-$sa-15);
$p->newWidthDimension('grainlineTop','undersleeveTip', $p->y('undersleeveTip')-$sa-15);
$p->newWidthDimension('undersleeveLeftEdge','undersleeveTip', $p->y('undersleeveTip')-$sa-30);
$p->newLinearDimension('undersleeveLeftEdge','undersleeveRightEdge');
$p->addPoint('rightEdge', $p->curveEdge('elbowRight','elbowRightCpTop','undersleeveRightEdgeCpBottom','undersleeveRightEdge','right'));
$p->newWidthDimension('undersleeveLeftEdge','rightEdge', $p->y('undersleeveTip')-$sa-45);
$p->newLinearDimension('undersleeveElbowLeft','elbowRight');
$p->newLinearDimension('undersleeveWristLeft','undersleeveWristRight', -15);
$p->newLinearDimension('cuffBottomLeft', 'undersleeveWristLeft', 15);
$p->newLinearDimension('undersleeveWristLeft', 'undersleeveElbowLeft', -15-$sa/2);
$p->newLinearDimension('undersleeveWristRight', 'elbowRight', 15+$sa/2);
// Note
$p->newNote(1, 'topsleeveWristLeftHelperBottom', $this->o('sleeveBend').' '.$this->t('degree').' '.$this->t('slant'), 6, 30);
}
/**
* Adds paperless info for the belt part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessBelt($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['belt'];
$p->newWidthDimension('topLeftBottom-b','bottomRight', $p->y('bottomRight')+$this->o('sa')/2+15);
$p->newHeightDimension('bottomRight', 'topRight', $p->x('bottomRight')+$this->o('sa')+15);
}
/**
* Adds paperless info for the collar stand part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessCollarStand($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['collarStand'];
$p->newLinearDimensionSm('centerBottom','standCenterTop');
$p->newWidthDimension('leftBottom','rightBottom', $p->y('rightBottom')+15+$this->o('sa')/2);
$p->newHeightDimension('rightBottom','standCenterTop', $p->x('rightBottom')+15+$this->o('sa')/2);
}
/**
* Adds paperless info for the collar part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessCollar($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['collar'];
$p->newHeightDimension('standCenterTop','centerTop', $p->x('standCenterTop')-15);
$p->newHeightDimension('rot-2-rightBottom','centerTop', $p->x('standCenterTop')-30);
$p->newHeightDimension('rot-1-rightCorner','centerTop', $p->x('standCenterTop')-45);
$p->newHeightDimension('shapedTip','centerTop', $p->x('shapedTip')+15+$this->o('sa')/2);
$p->newWidthDimension('standCenterTop','rot-2-rightBottom', $p->y('rot-1-rightCorner')+15+$this->o('sa')/2);
$p->newWidthDimension('standCenterTop','rot-1-rightCorner', $p->y('rot-1-rightCorner')+30+$this->o('sa')/2);
$p->newWidthDimension('standCenterTop','shapedTip', $p->y('rot-1-rightCorner')+45+$this->o('sa')/2);
}
/**
* Adds paperless info for the cuff facing part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessCuffFacing($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['cuffFacing'];
$p->newHeightDimension('bottomLeftRight-r','topRight', $p->x('topRight')+15+$this->o('sa')/2);
$p->newWidthDimension('bottomLeftTop','bottomLeftTop-r', $p->y('bottomLeftRight')+15+$this->o('sa')/2);
}
/**
* Adds paperless info for the pocket part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessPocket($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['pocket'];
$p->newHeightDimension('pocketBottomRightLeft','pocketTopRight', $p->x('pocketTopRight')+15+$this->o('sa')/2);
$p->newWidthDimension('pocketBottomLeftTop','pocketBottomRightTop', $p->y('pocketBottomLeftRight')+15+$this->o('sa')/2);
}
/**
* Adds paperless info for the pocket flap part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessPocketFlap($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['pocketFlap'];
$p->newHeightDimension('pocketFlapBottomRightLeft','pocketFlapTopRight', $p->x('pocketFlapTopRight')+30+$this->o('sa')/2);
$p->newHeightDimension('pocketFlapBottomRightLeft','pocketFlapBottomRightTop', $p->x('pocketFlapTopRight')+15+$this->o('sa')/2);
$p->newWidthDimension('pocketFlapTopLeft','pocketFlapTopRight', $p->y('pocketFlapTopRight')-15-$this->o('sa')/2);
$p->newWidthDimension('pocketFlapBottomLeftTop','pocketFlapBottomRightTop', $p->y('pocketFlapBottomLeftRight')+15+$this->o('sa')/2);
}
/**
* Adds paperless info for the chest pocket welt part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessChestPocketWelt($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['chestPocketWelt'];
$p->newHeightDimension('bottomRight','topRight', $p->x('topRight')+15+$this->o('sa')/2);
$p->newWidthDimension('bottomLeft','bottomRight', $p->y('bottomLeft')+15+$this->o('sa')/2);
}
/**
* Adds paperless info for the inner pocket welt part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessInnerPocketWelt($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['innerPocketWelt'];
$p->newWidthDimension('leftBottomWelt','rightBottomWelt', $p->y('leftBottomCorner')+25);
$p->newWidthDimension('leftBottomCorner','rightBottomCorner', $p->y('leftBottomCorner')+40);
$p->newHeightDimensionSm('rightBottomWelt','rightTopWelt', $p->x('rightTopCorner')+15);
$p->newHeightDimension('rightBottomCorner','rightTopCorner', $p->x('rightTopCorner')+30);
}
/**
* Adds paperless info for the inner pocket bag part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessInnerPocketBag($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['innerPocketBag'];
$p->newWidthDimension('bottomLeft', 'bottomRight', $p->y('bottomLeft')+15);
}
/**
* Adds paperless info for the inner pocket tab part
*
* @param \Freesewing\Model $model The model to draft for
*
* @return void
*/
public function paperlessInnerPocketTab($model)
{
/** @var \Freesewing\Part $p */
$p = $this->parts['innerPocketTab'];
$p->newWidthDimension('topLeft', 'topRight', $p->y('top')-15);
$p->newHeightDimension('bottom', 'topRight', $p->x('topRight')+15);
}
}
| 0 | 0.974185 | 1 | 0.974185 | game-dev | MEDIA | 0.294847 | game-dev | 0.927028 | 1 | 0.927028 |
austinmao/reduxity | 3,439 | Assets/Plugins/UniRx/Scripts/Operators/PairWise.cs | using System;
namespace UniRx.Operators
{
internal class PairwiseObservable<T, TR> : OperatorObservableBase<TR>
{
readonly IObservable<T> source;
readonly Func<T, T, TR> selector;
public PairwiseObservable(IObservable<T> source, Func<T, T, TR> selector)
: base(source.IsRequiredSubscribeOnCurrentThread())
{
this.source = source;
this.selector = selector;
}
protected override IDisposable SubscribeCore(IObserver<TR> observer, IDisposable cancel)
{
return source.Subscribe(new Pairwise(this, observer, cancel));
}
class Pairwise : OperatorObserverBase<T, TR>
{
readonly PairwiseObservable<T, TR> parent;
T prev = default(T);
bool isFirst = true;
public Pairwise(PairwiseObservable<T, TR> parent, IObserver<TR> observer, IDisposable cancel)
: base(observer, cancel)
{
this.parent = parent;
}
public override void OnNext(T value)
{
if (isFirst)
{
isFirst = false;
prev = value;
return;
}
TR v;
try
{
v = parent.selector(prev, value);
prev = value;
}
catch (Exception ex)
{
try { observer.OnError(ex); } finally { Dispose(); }
return;
}
observer.OnNext(v);
}
public override void OnError(Exception error)
{
try { observer.OnError(error); } finally { Dispose(); }
}
public override void OnCompleted()
{
try { observer.OnCompleted(); } finally { Dispose(); }
}
}
}
internal class PairwiseObservable<T> : OperatorObservableBase<Pair<T>>
{
readonly IObservable<T> source;
public PairwiseObservable(IObservable<T> source)
: base(source.IsRequiredSubscribeOnCurrentThread())
{
this.source = source;
}
protected override IDisposable SubscribeCore(IObserver<Pair<T>> observer, IDisposable cancel)
{
return source.Subscribe(new Pairwise(observer, cancel));
}
class Pairwise : OperatorObserverBase<T, Pair<T>>
{
T prev = default(T);
bool isFirst = true;
public Pairwise(IObserver<Pair<T>> observer, IDisposable cancel)
: base(observer, cancel)
{
}
public override void OnNext(T value)
{
if (isFirst)
{
isFirst = false;
prev = value;
return;
}
var pair = new Pair<T>(prev, value);
prev = value;
observer.OnNext(pair);
}
public override void OnError(Exception error)
{
try { observer.OnError(error); } finally { Dispose(); }
}
public override void OnCompleted()
{
try { observer.OnCompleted(); } finally { Dispose(); }
}
}
}
} | 0 | 0.896671 | 1 | 0.896671 | game-dev | MEDIA | 0.420597 | game-dev | 0.967583 | 1 | 0.967583 |
McBetaCpp/McBetaCpp | 7,956 | src/world/entity/Mob.cpp | #include "world/entity/Mob.h"
#include "world/level/Level.h"
#include "util/Mth.h"
Mob::Mob(Level &level) : Entity(level)
{
}
void Mob::defineSynchedData()
{
}
bool Mob::canSee(const Entity &entity)
{
return false;
}
jstring Mob::getTexture()
{
return u"/mob/char.png";
}
bool Mob::isPickable()
{
return false;
}
bool Mob::isPushable()
{
return false;
}
float Mob::getHeadHeight()
{
return 0.0f;
}
int_t Mob::getAmbientSoundInterval()
{
return 0;
}
void Mob::baseTick()
{
oAttackAnim = attackAnim;
Entity::baseTick();
if (isAlive() && isInWall())
hurt(nullptr, 1);
if (fireImmune || level.isOnline)
onFire = 0;
// TODO water material
oTilt = tilt;
if (attackTime > 0) attackTime--;
if (hurtTime > 0) hurtTime--;
if (invulnerableTime > 0) invulnerableTime--;
if (health <= 0)
{
deathTime++;
if (deathTime > 20)
{
beforeRemove();
remove();
// TODO
}
}
animStepO = animStep;
yBodyRotO = yBodyRot;
yRotO = yRot;
xRotO = xRot;
}
void Mob::spawnAnim()
{
}
void Mob::rideTick()
{
}
void Mob::lerpTo(double x, double y, double z, float yRot, float xRot, int_t steps)
{
}
void Mob::superTick()
{
Entity::tick();
}
void Mob::tick()
{
Entity::tick();
aiStep();
double fxd = x - xo;
double fzd = z - zo;
float fd = Mth::sqrt(fxd * fxd + fzd * fzd);
float targetBodyRot = yBodyRot;
float speedAnimStep = 0.0f;
oRun = run;
float targetRun = 0.0f;
if (fd > 0.05f)
{
targetRun = 1.0f;
speedAnimStep = fd * 3.0f;
targetBodyRot = std::atan2(fzd, fxd) * 180.0f / Mth::PI - 90.0f;
}
if (attackAnim > 0.0f)
targetBodyRot = yRot;
if (!onGround)
targetRun = 0.0f;
run += (targetRun - run) * 0.3f;
float deltaBodyRot = targetBodyRot - yBodyRot;
while (deltaBodyRot < -180.0f) deltaBodyRot += 360.0f;
while (deltaBodyRot >= 180.0f) deltaBodyRot -= 360.0f;
yBodyRot += deltaBodyRot * 0.3f;
float deltaYRot = yRot - yBodyRot;
while (deltaYRot < -180.0f) deltaYRot += 360.0f;
while (deltaYRot >= 180.0f) deltaYRot -= 360.0f;
bool rotAtLimit = deltaYRot < -90.0f || deltaYRot >= 90.0f;
if (deltaYRot < -75.0f) deltaYRot = -75.0f;
if (deltaYRot >= 75.0f) deltaYRot = 75.0f;
yBodyRot = yRot - deltaYRot;
if (deltaYRot * deltaYRot > 2500.0f)
yBodyRot += deltaYRot * 0.2f;
if (rotAtLimit)
speedAnimStep *= -1.0f;
while (yRot - yRotO < -180.0f) yRotO -= 360.0f;
while (yRot - yRotO >= 180.0f) yRotO += 360.0f;
while (yBodyRot - yBodyRotO < -180.0f) yBodyRotO -= 360.0f;
while (yBodyRot - yBodyRotO >= 180.0f) yBodyRotO += 360.0f;
while (xRot - xRotO < -180.0f) xRotO -= 360.0f;
while (xRot - xRotO >= 180.0f) xRotO += 360.0f;
animStep += speedAnimStep;
}
void Mob::setSize(float width, float height)
{
}
void Mob::heal(int_t heal)
{
}
bool Mob::hurt(Entity *source, int_t dmg)
{
return false;
}
void Mob::animateHurt()
{
}
void Mob::actuallyHurt(int_t dmg)
{
}
float Mob::getSoundVolume()
{
return 0.0f;
}
jstring Mob::getAmbientSound()
{
return u"";
}
jstring Mob::getHurtSound()
{
return u"";
}
jstring Mob::getDeathSound()
{
return u"";
}
void Mob::knockback(Entity &source, int_t unknown, double x, double z)
{
}
void Mob::die(Entity *source)
{
}
void Mob::dropDeathLoot()
{
}
int_t Mob::getDeathLoot()
{
return 0;
}
void Mob::causeFallDamage(float distance)
{
}
void Mob::travel(float x, float z)
{
if (isInWater())
{
double oy = y;
moveRelative(x, z, 0.02f);
move(xd, yd, zd);
xd *= 0.8;
yd *= 0.8;
zd *= 0.8;
yd -= 0.02;
if (horizontalCollision && isFree(xd, yd + 0.6 - y + oy, zd))
yd = 0.3;
}
else if (isInLava())
{
double oy = y;
moveRelative(x, z, 0.02f);
move(xd, yd, zd);
xd *= 0.5;
yd *= 0.5;
zd *= 0.5;
yd -= 0.02;
if (horizontalCollision && isFree(xd, yd + 0.6 - y + oy, zd))
yd = 0.3;
}
else
{
float friction = 0.91f;
if (onGround)
{
friction = 0.546f;
int_t tile = level.getTile(Mth::floor(x), Mth::floor(bb.y0) - 1, Mth::floor(z));
if (tile > 0)
friction = Tile::tiles[tile]->friction * 0.91f;
}
float acceleration = 0.16277136f / (friction * friction * friction);
moveRelative(x, z, onGround ? (0.1f * acceleration) : 0.02f);
friction = 0.91f;
if (onGround)
{
friction = 0.546f;
int_t tile = level.getTile(Mth::floor(x), Mth::floor(bb.y0) - 1, Mth::floor(z));
if (tile > 0)
friction = Tile::tiles[tile]->friction * 0.91f;
}
if (onLadder())
{
fallDistance = 0.0f;
if (yd < -0.15) yd = -0.15;
}
move(xd, yd, zd);
if (horizontalCollision && onLadder())
yd = 0.2;
yd -= 0.08;
yd *= 0.98;
xd *= friction;
zd *= friction;
}
walkAnimSpeedO = walkAnimSpeed;
double fdx = this->x - this->xo;
double fdz = this->z - this->zo;
float targetWalkAnimSpeed = Mth::sqrt(fdx * fdx + fdz * fdz) * 4.0f;
if (targetWalkAnimSpeed > 1.0f) targetWalkAnimSpeed = 1.0f;
walkAnimSpeed += (targetWalkAnimSpeed - walkAnimSpeed) * 0.4f;
walkAnimPos += walkAnimSpeed;
}
bool Mob::onLadder()
{
return false;
}
bool Mob::isShootable()
{
return false;
}
void Mob::addAdditionalSaveData(CompoundTag &tag)
{
}
void Mob::readAdditionalSaveData(CompoundTag &tag)
{
}
bool Mob::isAlive()
{
return false;
}
bool Mob::isWaterMob()
{
return false;
}
void Mob::aiStep()
{
if (lSteps > 0)
{
double xd = x + (lx - x) / lSteps;
double yd = y + (ly - y) / lSteps;
double zd = z + (lz - z) / lSteps;
double deltaYRot = lyr - yRot;
while (deltaYRot < -180.0f) deltaYRot += 360.0f;
while (deltaYRot >= 180.0f) deltaYRot -= 360.0f;
yRot = yRot + deltaYRot / lSteps;
xRot = xRot + (lxr - xRot) / lSteps;
--lSteps;
setPos(xd, yd, zd);
setRot(yRot, xRot);
}
if (health <= 0)
{
jumping = false;
xxa = 0.0f;
yya = 0.0f;
yRotA = 0.0f;
}
else if (!interpolateOnly)
{
updateAi();
}
// Jump
bool inWater = isInWater();
bool inLava = isInLava();
if (jumping)
{
if (inWater)
yd += 0.04;
else if (inLava)
yd += 0.04;
else if (onGround)
jumpFromGround();
}
// Movement
xxa *= 0.98f;
yya *= 0.98f;
yRotA *= 0.98f;
travel(xxa, yya);
const auto &entities = level.getEntities(this, *bb.grow(0.2, 0.0f, 0.2));
if (!entities.empty())
{
for (const auto &entity : entities)
{
if (entity->isPushable())
entity->push(*this);
}
}
}
void Mob::jumpFromGround()
{
yd = 0.42;
}
void Mob::updateAi()
{
}
void Mob::lookAt(Entity &entity, float speed)
{
}
float Mob::rotlerp(float from, float to, float speed)
{
return 0.0f;
}
void Mob::beforeRemove()
{
}
bool Mob::canSpawn()
{
return false;
}
void Mob::outOfWorld()
{
hurt(nullptr, 4);
}
float Mob::getAttackAnim(float a)
{
float f = attackAnim - oAttackAnim;
if (f < 0.0f) f++;
return oAttackAnim + f * a;
}
Vec3 *Mob::getPos(float a)
{
if (a == 1.0f)
return Vec3::newTemp(x, y, z);
double xd = xo + (x - xo) * a;
double yd = yo + (y - yo) * a;
double zd = zo + (z - zo) * a;
return Vec3::newTemp(xd, yd, zd);
}
Vec3 *Mob::getLookAngle()
{
return getViewVector(1.0f);
}
Vec3 *Mob::getViewVector(float a)
{
if (a == 1.0f)
{
float cy = Mth::cos(-yRot * Mth::DEGRAD - Mth::PI);
float sy = Mth::sin(-yRot * Mth::DEGRAD - Mth::PI);
float cx = -Mth::cos(-xRot * Mth::DEGRAD);
float sx = Mth::sin(-xRot * Mth::DEGRAD);
return Vec3::newTemp(sy * cx, sx, cy * cx);
}
else
{
float xa = yRotO + (yRot - yRotO) * a;
float ya = xRotO + (xRot - xRotO) * a;
float cy = Mth::cos(-xa * Mth::DEGRAD - Mth::PI);
float sy = Mth::sin(-xa * Mth::DEGRAD - Mth::PI);
float cx = -Mth::cos(-ya * Mth::DEGRAD);
float sx = Mth::sin(-ya * Mth::DEGRAD);
return Vec3::newTemp(sy * cx, sx, cy * cx);
}
}
HitResult Mob::pick(float length, float a)
{
Vec3 *pos = getPos(a);
Vec3 *look = getLookAngle();
Vec3 *to = pos->add(look->x * length, look->y * length, look->z * length);
return level.clip(*pos, *to);
}
int_t Mob::getMaxSpawnClusterSize()
{
return 0;
}
// TODO
// ItemInstance getCarriedItem
void Mob::handleEntityEvent(byte_t event)
{
}
| 0 | 0.842487 | 1 | 0.842487 | game-dev | MEDIA | 0.992589 | game-dev | 0.988323 | 1 | 0.988323 |
Anuken/Mindustry | 1,815 | core/src/mindustry/entities/comp/ChildComp.java | package mindustry.entities.comp;
import arc.math.*;
import arc.util.*;
import mindustry.annotations.Annotations.*;
import mindustry.gen.*;
import mindustry.world.blocks.*;
@Component
abstract class ChildComp implements Posc, Rotc{
@Import float x, y, rotation;
@Nullable Posc parent;
boolean rotWithParent;
float offsetX, offsetY, offsetPos, offsetRot;
@Override
public void add(){
if(parent != null){
offsetX = x - parent.getX();
offsetY = y - parent.getY();
if(rotWithParent){
if(parent instanceof Rotc r){
offsetPos = -r.rotation();
offsetRot = rotation - r.rotation();
}else if(parent instanceof RotBlock rot){
offsetPos = -rot.buildRotation();
offsetRot = rotation - rot.buildRotation();
}
}
}
}
@Override
public void update(){
if(parent != null){
if(rotWithParent){
if(parent instanceof Rotc r){
x = parent.getX() + Angles.trnsx(r.rotation() + offsetPos, offsetX, offsetY);
y = parent.getY() + Angles.trnsy(r.rotation() + offsetPos, offsetX, offsetY);
rotation = r.rotation() + offsetRot;
}else if(parent instanceof RotBlock rot){
x = parent.getX() + Angles.trnsx(rot.buildRotation() + offsetPos, offsetX, offsetY);
y = parent.getY() + Angles.trnsy(rot.buildRotation() + offsetPos, offsetX, offsetY);
rotation = rot.buildRotation() + offsetRot;
}
}else{
x = parent.getX() + offsetX;
y = parent.getY() + offsetY;
}
}
}
}
| 0 | 0.818021 | 1 | 0.818021 | game-dev | MEDIA | 0.681914 | game-dev | 0.801144 | 1 | 0.801144 |
Team-Beef-Studios/Doom3Quest | 3,104 | app/src/main/jni/d3es-multithread-master/neo/tools/guied/GECheckInDlg.cpp | /*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
Doom 3 Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "tools/edit_gui_common.h"
#include "../../sys/win32/rc/guied_resource.h"
#include "GEApp.h"
typedef struct
{
const char* mFilename;
idStr* mComment;
} GECHECKINDLG;
/*
================
GECheckInDlg_GeneralProc
Dialog procedure for the check in dialog
================
*/
static INT_PTR CALLBACK GECheckInDlg_GeneralProc ( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
GECHECKINDLG* dlg = (GECHECKINDLG*) GetWindowLong ( hwnd, GWL_USERDATA );
switch ( msg )
{
case WM_INITDIALOG:
SetWindowLong ( hwnd, GWL_USERDATA, lParam );
dlg = (GECHECKINDLG*) lParam;
SetWindowText ( GetDlgItem ( hwnd, IDC_GUIED_FILENAME ), dlg->mFilename );
break;
case WM_COMMAND:
switch ( LOWORD ( wParam ) )
{
case IDOK:
{
char* temp;
int tempsize;
tempsize = GetWindowTextLength ( GetDlgItem ( hwnd, IDC_GUIED_COMMENT ) );
temp = new char [ tempsize + 2 ];
GetWindowText ( GetDlgItem ( hwnd, IDC_GUIED_COMMENT ), temp, tempsize + 1 );
*dlg->mComment = temp;
delete[] temp;
EndDialog ( hwnd, 1 );
break;
}
case IDCANCEL:
EndDialog ( hwnd, 0 );
break;
}
break;
}
return FALSE;
}
/*
================
GECheckInDlg_DoModal
Starts the check in dialog
================
*/
bool GECheckInDlg_DoModal ( HWND parent, const char* filename, idStr* comment )
{
GECHECKINDLG dlg;
dlg.mComment = comment;
dlg.mFilename = filename;
if ( !DialogBoxParam ( gApp.GetInstance(), MAKEINTRESOURCE(IDD_GUIED_CHECKIN), parent, GECheckInDlg_GeneralProc, (LPARAM) &dlg ) )
{
return false;
}
return true;
}
| 0 | 0.541651 | 1 | 0.541651 | game-dev | MEDIA | 0.455436 | game-dev | 0.621443 | 1 | 0.621443 |
bergerhealer/TrainCarts | 1,283 | src/main/java/com/bergerkiller/bukkit/tc/statements/StatementPermission.java | package com.bergerkiller.bukkit.tc.statements;
import com.bergerkiller.bukkit.tc.controller.MinecartGroup;
import com.bergerkiller.bukkit.tc.controller.MinecartMember;
import com.bergerkiller.bukkit.tc.events.SignActionEvent;
import org.bukkit.entity.Player;
public class StatementPermission extends Statement {
@Override
public boolean match(String text) {
return false;
}
@Override
public boolean matchArray(String text) {
return text.equals("pm") || text.equals("perm");
}
@Override
public boolean handleArray(MinecartGroup group, String[] text, SignActionEvent event) {
for (MinecartMember<?> member : group) {
if (!handleArray(member, text, event)) {
return false;
}
}
return true;
}
@Override
public boolean handleArray(MinecartMember<?> member, String[] text, SignActionEvent event) {
if (member.getEntity().hasPlayerPassenger()) {
for (Player player : member.getEntity().getPlayerPassengers()) {
for (String perm : text) {
if (!player.hasPermission(perm)) {
return false;
}
}
}
}
return true;
}
}
| 0 | 0.65355 | 1 | 0.65355 | game-dev | MEDIA | 0.927965 | game-dev | 0.521241 | 1 | 0.521241 |
electronicarts/CnC_Renegade | 13,189 | Code/Commando/gdskirmish.cpp | /*
** Command & Conquer Renegade(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/***********************************************************************************************
*** Confidential - Westwood Studios ***
***********************************************************************************************
* *
* Project Name : Commando *
* *
* $Archive:: /Commando/Code/Commando/gdskirmish.cpp $*
* *
* $Author:: Tom_s $*
* *
* $Modtime:: 4/12/02 4:01p $*
* *
* $Revision:: 12 $*
* *
*---------------------------------------------------------------------------------------------*
* Functions: *
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#include "gdskirmish.h"
#include "cnetwork.h"
#include "translatedb.h"
#include "string_ids.h"
#include "assets.h"
#include "multihud.h"
#include "playerdata.h"
#include "player.h"
#include "playertype.h"
#include "gameobjmanager.h"
#include "spawn.h"
//-----------------------------------------------------------------------------
cGameDataSkirmish::cGameDataSkirmish(void) :
IsPlaying (false),
cGameData()
{
//WWDEBUG_SAY(("cGameDataSkirmish::cGameDataSkirmish\n"));
Set_Time_Limit_Minutes(25);
Set_Ini_Filename("svrcfg_skirmish.ini");
BaseDestructionEndsGame.Set(true);
BeaconPlacementEndsGame.Set(true);
StartingCredits = 400;
//IsTeamChangingAllowed.Set(false);
IsTeamChangingAllowed.Set(true);
Set_Max_Players(1);
Set_Radar_Mode(RADAR_TEAMMATES);
Load_From_Server_Config();
Save_To_Server_Config();
//
// Reload again to avoid LastServerConfigModTime issues
//
Load_From_Server_Config();
}
//-----------------------------------------------------------------------------
cGameDataSkirmish::~cGameDataSkirmish(void)
{
//WWDEBUG_SAY(("cGameDataSkirmish::~cGameDataSkirmish\n"));
}
//-----------------------------------------------------------------------------
cGameDataSkirmish& cGameDataSkirmish::operator=(const cGameDataSkirmish& rhs)
{
//
// Call the base class
//
cGameData::operator=(rhs);
BaseDestructionEndsGame = rhs.BaseDestructionEndsGame;
BeaconPlacementEndsGame = rhs.BeaconPlacementEndsGame;
StartingCredits = rhs.StartingCredits;
return (*this);
}
//-----------------------------------------------------------------------------
const WCHAR* cGameDataSkirmish::Get_Static_Game_Name(void)
{
return TRANSLATION(IDS_MP_GAME_TYPE_SKIRMISH);
}
//-----------------------------------------------------------------------------
void cGameDataSkirmish::Reset_Game(bool is_reloaded)
{
WWDEBUG_SAY(("cGameDataSkirmish::Reset_Game\n"));
cGameData::Reset_Game(is_reloaded);
//
// TSS091201 - hack - On_Game_End not called in correct places
//
if (IsPlaying) {
BaseGDI.Shutdown ();
BaseNOD.Shutdown ();
IsPlaying = false;
}
//
// Initialize the base controllers
//
BaseGDI.Initialize ( PLAYERTYPE_GDI );
BaseNOD.Initialize ( PLAYERTYPE_NOD );
return ;
}
//-----------------------------------------------------------------------------
void
cGameDataSkirmish::On_Game_Begin (void)
{
WWDEBUG_SAY(("cGameDataSkirmish::On_Game_Begin\n"));
cGameData::On_Game_Begin();
CombatManager::Set_Beacon_Placement_Ends_Game(BeaconPlacementEndsGame.Get());
//
// Initialize the bases
//
IsPlaying = true;
}
//-----------------------------------------------------------------------------
void
cGameDataSkirmish::On_Game_End (void)
{
WWDEBUG_SAY(("cGameDataSkirmish::On_Game_End\n"));
//
// Close the bases
//
BaseGDI.Shutdown ();
BaseNOD.Shutdown ();
IsPlaying = false;
cGameData::On_Game_End();
return ;
}
//-----------------------------------------------------------------------------
void
cGameDataSkirmish::Soldier_Added (SoldierGameObj *soldier)
{
cGameData::Soldier_Added (soldier);
//
// Give the soldier some starting credits
//
if ( soldier != NULL &&
soldier->Get_Player_Data() != NULL &&
soldier->Get_Player_Data()->Get_Game_Time () == 0)
{
soldier->Get_Player_Data ()->Set_Money (StartingCredits);
}
return ;
}
//-----------------------------------------------------------------------------
void cGameDataSkirmish::Think(void)
{
cGameData::Think();
if (!cNetwork::I_Am_Server()) {
return;
}
//
// Let the bases think
//
if (IsPlaying) {
BaseGDI.Think ();
BaseNOD.Think ();
}
//
// Weed out any soldiers or spawners that shouldn't be present.
//
Filter_Soldiers();
return ;
}
//-----------------------------------------------------------------------------
void cGameDataSkirmish::Set_Starting_Credits(int credits)
{
Set_Generic_Num(credits, 0, MAX_CREDITS, StartingCredits);
}
//-----------------------------------------------------------------------------
void cGameDataSkirmish::Base_Destruction_Score_Tweaking(void)
{
WWASSERT(cNetwork::I_Am_Server());
cTeam * p_nod = cTeamManager::Find_Team(PLAYERTYPE_NOD);
WWASSERT(p_nod != NULL);
cTeam * p_gdi = cTeamManager::Find_Team(PLAYERTYPE_GDI);
WWASSERT(p_gdi != NULL);
float nod_score = p_nod->Get_Score();
float gdi_score = p_gdi->Get_Score();
const int BASE_DESTRUCTION_POINTS_REWARD = 5000;
//
// Base destroyer gets a points reward.
// If this isn't enough to beat other team, nudge score ahead by 1 point.
//
if (BaseGDI.Is_Base_Destroyed()) {
nod_score += BASE_DESTRUCTION_POINTS_REWARD;
if (nod_score <= gdi_score) {
nod_score = gdi_score + 1;
}
p_nod->Set_Score(nod_score);
} else {
WWASSERT(BaseNOD.Is_Base_Destroyed());
gdi_score += BASE_DESTRUCTION_POINTS_REWARD;
if (gdi_score <= nod_score) {
gdi_score = nod_score + 1;
}
p_gdi->Set_Score(gdi_score);
}
}
//-----------------------------------------------------------------------------
bool cGameDataSkirmish::Is_Game_Over(void)
{
WWASSERT(cNetwork::I_Am_Server());
bool is_game_over = cGameData::Is_Game_Over();
if (!is_game_over && BaseDestructionEndsGame.Is_True())
{
//
// If a base is destroyed then the game is over and the other team wins.
// To ensure this we may need to tweak the base-destroyer's score.
//
if (BaseGDI.Is_Base_Destroyed() || BaseNOD.Is_Base_Destroyed()) {
is_game_over = true;
Set_Win_Type(WIN_TYPE_BASE_DESTRUCTION);
Base_Destruction_Score_Tweaking();
}
}
//
// Beacon placement end game works via above base destruction method.
//
return is_game_over;
}
//-----------------------------------------------------------------------------
void cGameDataSkirmish::Load_From_Server_Config(void)
{
cGameData::Load_From_Server_Config(Get_Ini_Filename());
INIClass * p_ini = Get_INI(Get_Ini_Filename());
WWASSERT(p_ini != NULL);
bool b;
int i;
//float f;
i = p_ini->Get_Int( INI_SECTION_NAME, "MaxPlayers", Get_Max_Players());
Set_Max_Players(i);
b = p_ini->Get_Bool( INI_SECTION_NAME, "IsFriendlyFirePermitted", IsFriendlyFirePermitted.Get());
IsFriendlyFirePermitted.Set(b);
b = p_ini->Get_Bool( INI_SECTION_NAME, "IsTeamChangingAllowed", IsTeamChangingAllowed.Get());
IsTeamChangingAllowed.Set(b);
b = p_ini->Get_Bool( INI_SECTION_NAME, "IsClanGame", IsClanGame.Get());
IsClanGame.Set(b);
b = p_ini->Get_Bool( INI_SECTION_NAME, "BaseDestructionEndsGame", BaseDestructionEndsGame.Get());
BaseDestructionEndsGame.Set(b);
b = p_ini->Get_Bool( INI_SECTION_NAME, "BeaconPlacementEndsGame", BeaconPlacementEndsGame.Get());
BeaconPlacementEndsGame.Set(b);
i = p_ini->Get_Int( INI_SECTION_NAME, "StartingCredits", Get_Starting_Credits());
Set_Starting_Credits(i);
Release_INI(p_ini);
return ;
}
//-----------------------------------------------------------------------------
void cGameDataSkirmish::Save_To_Server_Config(void)
{
cGameData::Save_To_Server_Config(Get_Ini_Filename());
INIClass * p_ini = Get_INI(Get_Ini_Filename());
WWASSERT(p_ini != NULL);
p_ini->Put_Bool( INI_SECTION_NAME, "IsFriendlyFirePermitted", IsFriendlyFirePermitted.Get());
p_ini->Put_Bool( INI_SECTION_NAME, "IsTeamChangingAllowed", IsTeamChangingAllowed.Get());
p_ini->Put_Bool( INI_SECTION_NAME, "IsClanGame", IsClanGame.Get());
p_ini->Put_Int( INI_SECTION_NAME, "MaxPlayers", Get_Max_Players());
p_ini->Put_Bool( INI_SECTION_NAME, "BaseDestructionEndsGame", BaseDestructionEndsGame.Get());
p_ini->Put_Bool( INI_SECTION_NAME, "BeaconPlacementEndsGame", BeaconPlacementEndsGame.Get());
p_ini->Put_Int( INI_SECTION_NAME, "StartingCredits", Get_Starting_Credits());
Save_INI(p_ini, Get_Ini_Filename());
Release_INI(p_ini);
}
//-----------------------------------------------------------------------------
void cGameDataSkirmish::Show_My_Money(void)
{
if (cNetwork::I_Am_Client()) {
cPlayer * p_player = cNetwork::Get_My_Player_Object();
if (p_player != NULL) {
WideStringClass text(0,true);
text.Format(L"%s: %d",
TRANSLATION(IDS_MP_MONEY), (int) p_player->Get_Money());
Add_Bottom_Text(text);
}
}
}
//-----------------------------------------------------------------------------
void cGameDataSkirmish::Show_Game_Settings_Limits(void)
{
/*
if (IsIntermission.Is_True()) {
return;
}
*/
Show_My_Money();
cGameData::Show_Game_Settings_Limits();
}
//-----------------------------------------------------------------------------
void cGameDataSkirmish::Filter_Soldiers(void)
{
//
// Remove any soldiers or spawners on your side, leaving only opponents.
//
cPlayer * p_player = cNetwork::Get_My_Player_Object();
if (p_player != NULL) {
//int my_team = p_player->Get_Player_Type();
/*
//
// Remove soldiers
// Whoa, design now wants these... comment out this code.
//
for (
SLNode<SmartGameObj> * objnode = GameObjManager::Get_Smart_Game_Obj_List()->Head();
objnode != NULL;
objnode = objnode->Next())
{
SmartGameObj * p_smart_obj = objnode->Data();
WWASSERT(p_smart_obj != NULL);
if ( p_smart_obj->As_SoldierGameObj() != NULL &&
!p_smart_obj->Is_Delete_Pending() &&
!p_smart_obj->Has_Player() &&
p_smart_obj->Get_Player_Type() == my_team) {
p_smart_obj->Set_Delete_Pending();
}
}
*/
/*
//
// Remove spawners... ugh how do I select just the appropriate ones?
//
DynamicVectorClass<SpawnerClass*> spawner_list = SpawnManager::Get_Spawner_List();
for (int i = 0; i < spawner_list.Count(); i++) {
WWASSERT(spawner_list[i] != NULL);
if (spawner_list[i]->Get_Definition().Get_Player_Type() == my_team) {
spawner_list[i]->Enable(false);
}
}
*/
}
}
//-----------------------------------------------------------------------------
void cGameDataSkirmish::Get_Description(WideStringClass & description)
{
//
// Call base class
//
cGameData::Get_Description(description);
const WideStringClass delimiter = L"\t";
const WideStringClass newline = L"\n";
const WideStringClass yes = TRANSLATE(IDS_YES);
const WideStringClass no = TRANSLATE(IDS_NO);
WideStringClass attribute(0, true);
WideStringClass value(0, true);
//
// Starting Credits
//
attribute = TRANSLATE(IDS_MENU_TEXT349);
value.Format(L"%d", StartingCredits);
description += (attribute + delimiter + value + newline);
//
// Base Destruction Ends Game
//
attribute = TRANSLATE(IDS_MENU_TEXT314);
value = (BaseDestructionEndsGame.Get() ? yes : no);
description += (attribute + delimiter + value + newline);
//
// Beacon Placement Ends Game
//
attribute = TRANSLATE(IDS_MENU_TEXT315);
value = (BeaconPlacementEndsGame.Get() ? yes : no);
description += (attribute + delimiter + value + newline);
}
| 0 | 0.939363 | 1 | 0.939363 | game-dev | MEDIA | 0.943487 | game-dev | 0.972434 | 1 | 0.972434 |
Cultrarius/QuestWeaver | 1,641 | include/QuestModel/QuestModel.h | //
// Created by michael on 10.08.15.
//
#pragma once
#include <QuestModel/Quest.h>
#include <QuestModel/QuestModelAction.h>
#include <Template/QuestPropertyValue.h>
namespace weave {
class QuestModel {
public:
std::vector<std::shared_ptr<Quest>> GetQuestsWithState(QuestState state) const noexcept;
std::vector<std::shared_ptr<Quest>> GetQuests() const noexcept;
std::shared_ptr<Quest> GetQuest(ID questId) const;
QuestState GetState(ID questId) const noexcept;
std::set<std::shared_ptr<WorldEntity>> GetQuestEntities(ID questId) const noexcept;
bool Execute(const QuestModelAction &modelAction);
void RegisterNew(std::shared_ptr<Quest> newQuest,
const std::vector<QuestPropertyValue> &questProperties,
const std::string &storyText);
private:
std::map<ID, std::shared_ptr<Quest>> quests;
std::unordered_map<ID, QuestState> questStates;
std::map<ID, std::set<std::shared_ptr<WorldEntity>>> questEntities;
std::vector<QuestModelAction> actionHistory;
ID idGenerator = 0;
bool activateQuest(ID questId);
bool failQuest(ID questId);
bool succeedQuest(ID questId);
// serialization
friend class cereal::access;
template<class Archive>
void serialize(Archive &archive) {
archive(CEREAL_NVP(idGenerator), CEREAL_NVP(quests), CEREAL_NVP(questStates), CEREAL_NVP(questEntities));
}
bool setNewQuestState(ID questId, const QuestState &requiredState, const QuestState &newState);
};
}
| 0 | 0.858532 | 1 | 0.858532 | game-dev | MEDIA | 0.861494 | game-dev | 0.513581 | 1 | 0.513581 |
DruidMech/MultiplayerCourseBlasterGame | 1,085 | Source/Blaster/Weapon/Casing.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Casing.h"
#include "Kismet/GameplayStatics.h"
#include "Sound/SoundCue.h"
// Sets default values
ACasing::ACasing()
{
PrimaryActorTick.bCanEverTick = false;
CasingMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("CasingMesh"));
SetRootComponent(CasingMesh);
CasingMesh->SetCollisionResponseToChannel(ECollisionChannel::ECC_Camera, ECollisionResponse::ECR_Ignore);
CasingMesh->SetSimulatePhysics(true);
CasingMesh->SetEnableGravity(true);
CasingMesh->SetNotifyRigidBodyCollision(true);
ShellEjectionImpulse = 10.f;
}
void ACasing::BeginPlay()
{
Super::BeginPlay();
CasingMesh->OnComponentHit.AddDynamic(this, &ACasing::OnHit);
CasingMesh->AddImpulse(GetActorForwardVector() * ShellEjectionImpulse);
}
void ACasing::OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
if (ShellSound)
{
UGameplayStatics::PlaySoundAtLocation(this, ShellSound, GetActorLocation());
}
Destroy();
}
| 0 | 0.882672 | 1 | 0.882672 | game-dev | MEDIA | 0.888138 | game-dev | 0.884074 | 1 | 0.884074 |
ShrineGames/UnityMirrorTutorials | 2,896 | Assets/Mirror/Examples/Tanks/Scripts/Tank.cs | using UnityEngine;
using UnityEngine.AI;
namespace Mirror.Examples.Tanks
{
public class Tank : NetworkBehaviour
{
[Header("Components")]
public NavMeshAgent agent;
public Animator animator;
[Header("Movement")]
public float rotationSpeed = 100;
[Header("Firing")]
public KeyCode shootKey = KeyCode.Space;
public GameObject projectilePrefab;
public Transform projectileMount;
[Header("Game Stats")]
[SyncVar]
public int health;
[SyncVar]
public int score;
[SyncVar]
public string playerName;
[SyncVar]
public bool allowMovement;
[SyncVar]
public bool isReady;
public bool isDead => health <= 0;
public TextMesh nameText;
void Update()
{
nameText.text = playerName;
nameText.transform.rotation = Camera.main.transform.rotation;
// movement for local player
if (!isLocalPlayer)
return;
//Set local players name color to green
nameText.color = Color.green;
if (!allowMovement)
return;
if (isDead)
return;
// rotate
float horizontal = Input.GetAxis("Horizontal");
transform.Rotate(0, horizontal * rotationSpeed * Time.deltaTime, 0);
// move
float vertical = Input.GetAxis("Vertical");
Vector3 forward = transform.TransformDirection(Vector3.forward);
agent.velocity = forward * Mathf.Max(vertical, 0) * agent.speed;
animator.SetBool("Moving", agent.velocity != Vector3.zero);
// shoot
if (Input.GetKeyDown(shootKey))
{
CmdFire();
}
}
// this is called on the server
[Command]
void CmdFire()
{
GameObject projectile = Instantiate(projectilePrefab, projectileMount.position, transform.rotation);
projectile.GetComponent<Projectile>().source = gameObject;
NetworkServer.Spawn(projectile);
RpcOnFire();
}
// this is called on the tank that fired for all observers
[ClientRpc]
void RpcOnFire()
{
animator.SetTrigger("Shoot");
}
public void SendReadyToServer(string playername)
{
if (!isLocalPlayer)
return;
CmdReady(playername);
}
[Command]
void CmdReady(string playername)
{
if (string.IsNullOrEmpty(playername))
{
playerName = "PLAYER" + Random.Range(1, 99);
}
else
{
playerName = playername;
}
isReady = true;
}
}
}
| 0 | 0.725794 | 1 | 0.725794 | game-dev | MEDIA | 0.960254 | game-dev | 0.911197 | 1 | 0.911197 |
fgsfdsfgs/doukutsupsx | 34,077 | src/game/npc_act/npc_act_280.c | #include "game/npc_act/npc_act.h"
// Sue (being teleported by Misery)
void npc_act_280(npc_t *npc) {
static const rect_t rc_left[2] = {
{112, 32, 128, 48},
{144, 32, 160, 48},
};
static const rect_t rc_right[2] = {
{112, 48, 128, 64},
{144, 48, 160, 64},
};
switch (npc->act) {
case 0:
npc->act = 1;
npc->anim = 0;
npc->anim_wait = 0;
npc->x += 6 * 0x200;
npc->tgt_x = npc->x;
snd_play_sound(PRIO_NORMAL, 29, FALSE);
// Fallthrough
case 1:
if (++npc->act_wait == 64) {
npc->act = 2;
npc->act_wait = 0;
}
break;
case 2:
npc->anim = 0;
if (npc->flags & 8) {
npc->act = 4;
npc->act_wait = 0;
npc->anim = 1;
snd_play_sound(PRIO_NORMAL, 23, FALSE);
}
break;
}
if (npc->act > 1) {
npc->yvel += 0x20;
if (npc->yvel > 0x5FF) npc->yvel = 0x5FF;
npc->y += npc->yvel;
}
if (npc->dir == 0)
npc->rect = &rc_left[npc->anim];
else
npc->rect = &rc_right[npc->anim];
if (npc->act == 1) {
npc->rect_delta.bottom = npc->rect->top + npc->act_wait / 4 - npc->rect->bottom;
npc->rect_prev = NULL; // force texrect update
if (npc->act_wait / 2 % 2)
npc->x = npc->tgt_x;
else
npc->x = npc->tgt_x + (1 * 0x200);
}
}
// Doctor (red energy form)
void npc_act_281(npc_t *npc) {
static const rect_t rc = {0, 0, 0, 0};
switch (npc->act) {
case 0:
npc->act = 1;
break;
case 10:
npc->act = 11;
npc->act_wait = 0;
// Fallthrough
case 11:
++npc->act_wait;
npc_spawn(270, npc->x, npc->y + (128 * 0x200), 0, 0, 2, npc, 0x100);
if (npc->act_wait > 150) npc->act = 12;
break;
case 20:
npc->act = 21;
npc->act_wait = 0;
// Fallthrough
case 21:
if (++npc->act_wait > 250) {
npc_delete_by_class(270, FALSE);
npc->act = 22;
}
break;
}
npc->rect = &rc;
}
// Mini Undead Core (active)
void npc_act_282(npc_t *npc) {
// Yes, Pixel spelt this wrong (should be 'rc')
static const rect_t tc[3] = {
{256, 80, 320, 120},
{256, 0, 320, 40},
{256, 120, 320, 160},
};
switch (npc->act) {
case 0:
npc->act = 20;
npc->tgt_y = npc->y;
if (m_rand(0, 100) % 2)
npc->yvel = -0x100;
else
npc->yvel = 0x100;
// Fallthrough
case 20:
npc->xvel = -0x200;
if (npc->x < -64 * 0x200) npc->cond = 0;
if (npc->tgt_y < npc->y) npc->yvel -= 0x10;
if (npc->tgt_y > npc->y) npc->yvel += 0x10;
if (npc->yvel > 0x100) npc->yvel = 0x100;
if (npc->yvel < -0x100) npc->yvel = -0x100;
if (player.flags & 8 && player.y < npc->y - (4 * 0x200) && player.x > npc->x - (24 * 0x200) &&
player.x < npc->x + (24 * 0x200)) {
npc->tgt_y = 144 * 0x200;
npc->anim = 2;
} else if (npc->anim != 1) {
npc->anim = 0;
}
if (player.flags & 1 && player.x < npc->x - npc->hit.back && player.x > npc->x - npc->hit.back - (8 * 0x200) &&
player.y + player.hit.bottom > npc->y - npc->hit.top &&
player.y - player.hit.top < npc->y + npc->hit.bottom) {
npc->bits &= ~NPC_SOLID_HARD;
npc->anim = 1;
} else if (player.flags & 4 && player.x > npc->x + npc->hit.back &&
player.x < npc->x + npc->hit.back + (8 * 0x200) &&
player.y + player.hit.bottom > npc->y - npc->hit.top &&
player.y - player.hit.top < npc->y + npc->hit.bottom) {
npc->bits &= ~NPC_SOLID_HARD;
npc->anim = 1;
} else if (player.flags & 2 && player.y < npc->y - npc->hit.top &&
player.y > npc->y - npc->hit.top - (8 * 0x200) &&
player.x + player.hit.front > npc->x - npc->hit.back &&
player.x - player.hit.back < npc->x + npc->hit.front) {
npc->bits &= ~NPC_SOLID_HARD;
npc->anim = 1;
} else if (player.flags & 8 && player.y > npc->y + npc->hit.bottom - (4 * 0x200) &&
player.y < npc->y + npc->hit.bottom + (12 * 0x200) &&
player.x + player.hit.front > npc->x - npc->hit.back - (4 * 0x200) &&
player.x - player.hit.back < npc->x + npc->hit.front + (4 * 0x200)) {
npc->bits &= ~NPC_SOLID_HARD;
npc->anim = 1;
}
}
npc->x += npc->xvel;
npc->y += npc->yvel;
npc->rect = &tc[npc->anim];
}
// Misery (transformed)
void npc_act_283(npc_t *npc) {
int x, y, dir;
static const rect_t rc_left[11] = {
{0, 64, 32, 96}, {32, 64, 64, 96}, {64, 64, 96, 96}, {96, 64, 128, 96},
{128, 64, 160, 96}, {160, 64, 192, 96}, {192, 64, 224, 96}, {224, 64, 256, 96},
{0, 0, 0, 0}, {256, 64, 288, 96}, {288, 64, 320, 96},
};
static const rect_t rc_right[11] = {
{0, 96, 32, 128}, {32, 96, 64, 128}, {64, 96, 96, 128}, {96, 96, 128, 128},
{128, 96, 160, 128}, {160, 96, 192, 128}, {192, 96, 224, 128}, {224, 96, 256, 128},
{0, 0, 0, 0}, {256, 96, 288, 128}, {288, 96, 320, 128},
};
if (npc->act < 100 && (npc_boss[0].cond == 0 || npc->life < 400)) npc->act = 100;
switch (npc->act) {
case 0:
npc->act = 1;
npc->y -= 8 * 0x200;
snd_play_sound(PRIO_NORMAL, 29, FALSE);
// Fallthrough
case 1:
if (++npc->act_wait / 2 % 2)
npc->anim = 9;
else
npc->anim = 0;
break;
case 10:
npc->act = 11;
npc->anim = 9;
break;
case 20:
npc_doctor_state.crystal_x = 0;
npc->act = 21;
npc->act_wait = 0;
npc->anim = 0;
npc->anim_wait = 0;
// Fallthrough
case 21:
npc->xvel = 7 * npc->xvel / 8;
npc->yvel = 7 * npc->yvel / 8;
if (++npc->anim_wait > 20) {
npc->anim_wait = 0;
++npc->anim;
}
if (npc->anim > 1) npc->anim = 0;
if (++npc->act_wait > 100) npc->act = 30;
if (npc->x < player.x)
npc->dir = 2;
else
npc->dir = 0;
break;
case 30:
npc->act = 31;
npc->act_wait = 0;
npc->anim = 2;
npc->count2 = npc->life;
// Fallthrough
case 31:
if (++npc->anim_wait > 1) {
npc->anim_wait = 0;
++npc->anim;
}
if (npc->anim > 3) npc->anim = 2;
if (npc->flags & 8) npc->yvel = -0x200;
if (npc->x > npc_boss[0].x)
npc->xvel -= 0x20;
else
npc->xvel += 0x20;
if (npc->y > player.y)
npc->yvel -= 0x10;
else
npc->yvel += 0x10;
if (npc->xvel > 0x200) npc->xvel = 0x200;
if (npc->xvel < -0x200) npc->xvel = -0x200;
if (npc->yvel > 0x200) npc->yvel = 0x200;
if (npc->yvel < -0x200) npc->yvel = -0x200;
if (npc->x > player.x)
npc->dir = 0;
else
npc->dir = 2;
if (++npc->act_wait > 150 && (npc->life < npc->count2 - 20 || npc_doctor_state.crystal_x)) {
npc_doctor_state.crystal_x = 0;
npc->act = 40;
}
if (npc_boss[0].anim && npc->act_wait > 250) npc->act = 50;
break;
case 40:
npc->act = 41;
npc->act_wait = 0;
npc->xvel = 0;
npc->yvel = 0;
if (npc->x > player.x)
npc->dir = 0;
else
npc->dir = 2;
snd_play_sound(PRIO_NORMAL, 103, FALSE);
if (player.y < 160 * 0x200)
npc->count2 = 290;
else
npc->count2 = 289;
// Fallthrough
case 41:
if (++npc->act_wait / 2 % 2)
npc->anim = 4;
else
npc->anim = 5;
if (npc->act_wait % 6 == 1) {
if (npc->count2 == 289) {
x = npc->x + (m_rand(-0x40, 0x40) * 0x200);
y = npc->y + (m_rand(-0x20, 0x20) * 0x200);
} else {
x = npc->x + (m_rand(-0x20, 0x20) * 0x200);
y = npc->y + (m_rand(-0x40, 0x40) * 0x200);
}
if (x < 32 * 0x200) x = 32 * 0x200;
if (x > (stage_data->width - 2) * 0x200 * 0x10) x = (stage_data->width - 2) * 0x200 * 0x10;
if (y < 32 * 0x200) y = 32 * 0x200;
if (y > (stage_data->height - 2) * 0x200 * 0x10) y = (stage_data->height - 2) * 0x200 * 0x10;
snd_play_sound(PRIO_NORMAL, 39, FALSE);
npc_spawn(npc->count2, x, y, 0, 0, 0, NULL, 0x100);
}
if (npc->act_wait > 50) {
npc->act = 42;
npc->act_wait = 0;
if (npc->x > player.x)
npc->dir = 0;
else
npc->dir = 2;
}
break;
case 42:
++npc->act_wait;
npc->anim = 6;
if (npc->act_wait > 50) {
npc->yvel = -0x200;
if (npc->dir == 0)
npc->xvel = 0x200;
else
npc->xvel = -0x200;
npc->act = 30;
}
break;
case 50:
npc->act = 51;
npc->act_wait = 0;
npc->xvel = 0;
npc->yvel = 0;
if (npc->x > player.x)
npc->dir = 0;
else
npc->dir = 2;
snd_play_sound(PRIO_NORMAL, 103, FALSE);
// Fallthrough
case 51:
if (++npc->act_wait / 2 % 2)
npc->anim = 4;
else
npc->anim = 5;
if (player.equip & EQUIP_BOOSTER_2_0) {
if (npc->act_wait % 10 == 1) {
if (npc->dir == 0) {
x = npc->x + (10 * 0x200);
y = npc->y;
switch (npc->act_wait / 6 % 4) {
case 0:
dir = 0xD8;
break;
case 1:
dir = 0xEC;
break;
case 2:
dir = 0x14;
break;
default:
dir = 0x28;
break;
}
} else {
x = npc->x - (10 * 0x200);
y = npc->y;
switch (npc->act_wait / 6 % 4) {
case 0:
dir = 0x58;
break;
case 1:
dir = 0x6C;
break;
case 2:
dir = 0x94;
break;
default:
dir = 0xA8;
break;
}
}
snd_play_sound(PRIO_NORMAL, 39, FALSE);
npc_spawn(301, x, y, 0, 0, dir, NULL, 0x100);
}
} else if (npc->act_wait % 24 == 1) {
if (npc->dir == 0) {
x = npc->x + (10 * 0x200);
y = npc->y;
switch (npc->act_wait / 6 % 4) {
case 0:
dir = 0xD8;
break;
case 1:
dir = 0xEC;
break;
case 2:
dir = 0x14;
break;
default:
dir = 0x28;
break;
}
} else {
x = npc->x - (10 * 0x200);
y = npc->y;
switch (npc->act_wait / 6 % 4) {
case 0:
dir = 0x58;
break;
case 1:
dir = 0x6C;
break;
case 2:
dir = 0x94;
break;
default:
dir = 0xA8;
break;
}
}
snd_play_sound(PRIO_NORMAL, 39, FALSE);
npc_spawn(301, x, y, 0, 0, dir, NULL, 0x100);
}
if (npc->act_wait > 50) {
npc->act = 42;
npc->act_wait = 0;
if (npc->x > player.x)
npc->dir = 0;
else
npc->dir = 2;
}
break;
case 99:
npc->xvel = 0;
npc->yvel = 0;
npc->anim = 9;
npc->bits &= ~NPC_SHOOTABLE;
break;
case 100:
npc->act = 101;
npc->anim = 9;
npc->damage = 0;
npc->bits &= ~NPC_SHOOTABLE;
npc->bits |= NPC_IGNORE_SOLIDITY;
npc->yvel = -0x200;
npc->shock += 50;
npc->hit.bottom = 12 * 0x200;
++npc_boss[0].anim;
// Fallthrough
case 101:
npc->yvel += 0x20;
if (npc->y > (216 * 0x200) - npc->hit.bottom) {
npc->y = (216 * 0x200) - npc->hit.bottom;
npc->act = 102;
npc->anim = 10;
npc->xvel = 0;
npc->yvel = 0;
}
break;
}
npc->y += npc->yvel;
if (npc->shock)
npc->x += npc->xvel / 2;
else
npc->x += npc->xvel;
if (npc->dir == 0)
npc->rect = &rc_left[npc->anim];
else
npc->rect = &rc_right[npc->anim];
}
// Sue (transformed)
void npc_act_284(npc_t *npc) {
u8 deg;
static const rect_t rc_left[13] = {
{0, 128, 32, 160}, {32, 128, 64, 160}, {64, 128, 96, 160}, {96, 128, 128, 160}, {128, 128, 160, 160},
{160, 128, 192, 160}, {192, 128, 224, 160}, {224, 128, 256, 160}, {0, 0, 0, 0}, {256, 128, 288, 160},
{288, 128, 320, 160}, {224, 64, 256, 96}, {208, 32, 224, 48},
};
static const rect_t rc_right[13] = {
{0, 160, 32, 192}, {32, 160, 64, 192}, {64, 160, 96, 192}, {96, 160, 128, 192}, {128, 160, 160, 192},
{160, 160, 192, 192}, {192, 160, 224, 192}, {224, 160, 256, 192}, {0, 0, 0, 0}, {256, 160, 288, 192},
{288, 160, 320, 192}, {224, 96, 256, 128}, {208, 48, 224, 64},
};
if (npc->act < 100 && (npc_boss[0].cond == 0 || npc->life < 500)) npc->act = 100;
switch (npc->act) {
case 0:
npc->act = 1;
npc->y -= 4 * 0x200;
snd_play_sound(PRIO_NORMAL, 29, FALSE);
npc->count2 = npc->life;
// Fallthrough
case 1:
if (++npc->act_wait / 2 % 2) {
npc->view.top = 16 * 0x200;
npc->view.back = 16 * 0x200;
npc->view.front = 16 * 0x200;
npc->anim = 11;
} else {
npc->view.top = 3 * 0x200;
npc->view.back = 8 * 0x200;
npc->view.front = 8 * 0x200;
npc->anim = 12;
}
if (npc->act_wait > 50) npc->act = 10;
break;
case 10:
npc->act = 11;
npc->anim = 11;
npc->view.top = 16 * 0x200;
npc->view.back = 16 * 0x200;
npc->view.front = 16 * 0x200;
npc_delete_by_class(257, TRUE);
break;
case 20:
npc->act = 21;
npc->act_wait = 0;
npc->anim = 0;
npc->anim_wait = 0;
npc->damage = 0;
npc->bits |= NPC_SHOOTABLE;
npc->bits &= ~NPC_IGNORE_SOLIDITY;
// Fallthrough
case 21:
npc->xvel = (npc->xvel * 7) / 8;
npc->yvel = (npc->yvel * 7) / 8;
if (++npc->anim_wait > 20) {
npc->anim_wait = 0;
++npc->anim;
}
if (npc->anim > 1) npc->anim = 0;
if (++npc->act_wait > 80) npc->act = 30;
if (npc->x < player.x)
npc->dir = 2;
else
npc->dir = 0;
if (npc->life < npc->count2 - 50) {
npc->count2 = npc->life;
npc_doctor_state.crystal_x = 10;
}
break;
case 30:
npc->act = 31;
npc->act_wait = 0;
npc->anim = 2;
npc->xvel = 0;
npc->yvel = 0;
// Fallthrough
case 31:
if (++npc->act_wait > 16) {
++npc->count1;
npc->count1 %= 4;
switch (npc->count1) {
case 1:
case 3:
npc->act = 34;
break;
case 0: // Identical to case 2
npc->act = 32;
break;
case 2: // Identical to case 0
npc->act = 32;
break;
}
}
break;
case 32:
npc->act = 33;
npc->act_wait = 0;
npc->bits &= ~NPC_SHOOTABLE;
if (player.x < npc->x)
npc->tgt_x = player.x - (160 * 0x200);
else
npc->tgt_x = player.x + (160 * 0x200);
npc->tgt_y = player.y;
deg = m_atan2(npc->x - npc->tgt_x, npc->y - npc->tgt_y);
npc->xvel = 3 * m_cos(deg);
npc->yvel = 3 * m_sin(deg);
npc->bits &= ~NPC_IGNORE_SOLIDITY;
if (npc->x < (stage_data->width * 0x200 * 0x10) / 2 && npc->xvel > 0) {
if (npc->y < (stage_data->height * 0x200 * 0x10) / 2 && npc->yvel > 0) npc->bits |= NPC_IGNORE_SOLIDITY;
if (npc->y > (stage_data->height * 0x200 * 0x10) / 2 && npc->yvel < 0) npc->bits |= NPC_IGNORE_SOLIDITY;
}
if (npc->x > (stage_data->width * 0x200 * 0x10) / 2 && npc->xvel < 0) {
if (npc->y < (stage_data->height * 0x200 * 0x10) / 2 && npc->yvel > 0) npc->bits |= NPC_IGNORE_SOLIDITY;
if (npc->y > (stage_data->height * 0x200 * 0x10) / 2 && npc->yvel < 0) npc->bits |= NPC_IGNORE_SOLIDITY;
}
if (npc->xvel > 0)
npc->dir = 2;
else
npc->dir = 0;
// Fallthrough
case 33:
if (++npc->act_wait / 2 % 2)
npc->anim = 3;
else
npc->anim = 8;
if (npc->act_wait > 50 || npc->flags & 5) npc->act = 20;
break;
case 34:
npc->act = 35;
npc->act_wait = 0;
npc->damage = 4;
npc->tgt_x = player.x;
npc->tgt_y = player.y;
deg = m_atan2(npc->x - npc->tgt_x, npc->y - npc->tgt_y);
npc->yvel = 3 * m_sin(deg);
npc->xvel = 3 * m_cos(deg);
npc->bits &= ~NPC_IGNORE_SOLIDITY;
if (npc->x < (stage_data->width * 0x200 * 0x10) / 2 && npc->xvel > 0) {
if (npc->y < (stage_data->height * 0x200 * 0x10) / 2 && npc->yvel > 0) npc->bits |= NPC_IGNORE_SOLIDITY;
if (npc->y > (stage_data->height * 0x200 * 0x10) / 2 && npc->yvel < 0) npc->bits |= NPC_IGNORE_SOLIDITY;
}
if (npc->x > (stage_data->width * 0x200 * 0x10) / 2 && npc->xvel < 0) {
if (npc->y < (stage_data->height * 0x200 * 0x10) / 2 && npc->yvel > 0) npc->bits |= NPC_IGNORE_SOLIDITY;
if (npc->y > (stage_data->height * 0x200 * 0x10) / 2 && npc->yvel < 0) npc->bits |= NPC_IGNORE_SOLIDITY;
}
if (npc->xvel > 0)
npc->dir = 2;
else
npc->dir = 0;
// Fallthrough
case 35:
if (++npc->act_wait > 20 && npc->shock)
npc->act = 40;
else if (npc->act_wait > 50 || npc->flags & 5)
npc->act = 20;
if (++npc->anim_wait > 1) {
npc->anim_wait = 0;
++npc->anim;
}
if (npc->anim > 7) npc->anim = 4;
if (npc->act_wait % 5 == 1) snd_play_sound(PRIO_NORMAL, 109, FALSE);
break;
case 40:
npc->act = 41;
npc->act_wait = 0;
npc->anim = 2;
npc->damage = 0;
npc->bits &= ~NPC_IGNORE_SOLIDITY;
// Fallthrough
case 41:
npc->xvel = (npc->xvel * 7) / 8;
npc->yvel = (npc->yvel * 7) / 8;
if (++npc->act_wait > 6) {
npc->act = 42;
npc->act_wait = 0;
npc->yvel = -0x200;
if (npc->dir == 0)
npc->xvel = 0x200;
else
npc->xvel = -0x200;
}
break;
case 42:
npc->anim = 9;
if (npc->flags & 8) {
npc->act = 43;
npc->act_wait = 0;
npc->anim = 2;
if (npc->x < player.x)
npc->dir = 2;
else
npc->dir = 0;
}
npc->yvel += 0x20;
if (npc->yvel > 0x5FF) npc->yvel = 0x5FF;
break;
case 43:
if (++npc->act_wait > 16) npc->act = 20;
break;
case 99:
npc->xvel = 0;
npc->yvel = 0;
npc->anim = 9;
npc->bits &= ~NPC_SHOOTABLE;
break;
case 100:
npc->act = 101;
npc->anim = 9;
npc->damage = 0;
npc->bits &= ~NPC_SHOOTABLE;
npc->bits |= NPC_IGNORE_SOLIDITY;
npc->yvel = -0x200;
npc->shock += 50;
++npc_boss[0].anim;
// Fallthrough
case 101:
npc->yvel += 0x20;
if (npc->y > (216 * 0x200) - npc->hit.bottom) {
npc->y = (216 * 0x200) - npc->hit.bottom;
npc->act = 102;
npc->anim = 10;
npc->xvel = 0;
npc->yvel = 0;
}
break;
}
npc->y += npc->yvel;
if (npc->shock)
npc->x += npc->xvel / 2;
else
npc->x += npc->xvel;
if (npc->dir == 0)
npc->rect = &rc_left[npc->anim];
else
npc->rect = &rc_right[npc->anim];
}
// Undead Core spiral projectile
void npc_act_285(npc_t *npc) {
static const rect_t rc = {232, 104, 248, 120};
u8 deg;
if (npc->x < 0 || npc->x > stage_data->width * 0x10 * 0x200) {
npc_show_death_damage(npc);
return;
}
switch (npc->act) {
case 0:
npc->act = 1;
npc->tgt_x = npc->x;
npc->tgt_y = npc->y;
npc->count1 = npc->dir / 8;
npc->dir %= 8;
// Fallthrough
case 1:
npc->count1 += 24;
npc->count1 %= 0x100;
deg = npc->count1;
if (npc->act_wait < 128) ++npc->act_wait;
if (npc->dir == 0)
npc->xvel -= 21;
else
npc->xvel += 21;
npc->tgt_x += npc->xvel;
npc->x = npc->tgt_x + (m_cos(deg) * 4);
npc->y = npc->tgt_y + (m_sin(deg) * 6);
npc_spawn(286, npc->x, npc->y, 0, 0, 0, NULL, 0x100);
break;
}
npc->rect = &rc;
}
// Undead Core spiral shot trail
void npc_act_286(npc_t *npc) {
static const rect_t rc[3] = {
{232, 120, 248, 136},
{232, 136, 248, 152},
{232, 152, 248, 168},
};
if (++npc->anim_wait > 0) {
npc->anim_wait = 0;
++npc->anim;
}
if (npc->anim > 2)
npc->cond = 0;
else
npc->rect = &rc[npc->anim];
}
// Orange smoke
void npc_act_287(npc_t *npc) {
static const rect_t rc_left[7] = {
{0, 224, 16, 240}, {16, 224, 32, 240}, {32, 224, 48, 240}, {48, 224, 64, 240},
{64, 224, 80, 240}, {80, 224, 96, 240}, {96, 224, 112, 240},
};
if (npc->act == 0) {
npc->xvel = m_rand(-4, 4) * 0x200;
npc->act = 1;
} else {
npc->xvel = (npc->xvel * 20) / 21;
npc->yvel = (npc->yvel * 20) / 21;
npc->x += npc->xvel;
npc->y += npc->yvel;
}
if (++npc->anim_wait > 1) {
npc->anim_wait = 0;
++npc->anim;
}
if (npc->anim > 6)
npc->cond = 0;
else
npc->rect = &rc_left[npc->anim];
}
// Undead Core exploding rock
void npc_act_288(npc_t *npc) {
static const rect_t rc[5] = {
{232, 72, 248, 88}, {232, 88, 248, 104}, {232, 0, 256, 24},
{232, 24, 256, 48}, {232, 48, 256, 72},
};
switch (npc->act) {
case 0:
npc->act = 1;
npc->xvel = -0x200;
// Fallthrough
case 1:
if (npc->dir == 1) {
npc->yvel -= 0x20;
if (npc->yvel < -0x5FF) npc->yvel = -0x5FF;
if (npc->flags & 2) npc->act = 2;
} else if (npc->dir == 3) {
npc->yvel += 0x20;
if (npc->yvel > 0x5FF) npc->yvel = 0x5FF;
if (npc->flags & 8) npc->act = 2;
}
if (++npc->anim_wait > 3) {
npc->anim_wait = 0;
++npc->anim;
}
if (npc->anim > 1) npc->anim = 0;
break;
case 2:
snd_play_sound(PRIO_NORMAL, 44, FALSE);
npc->act = 3;
npc->act_wait = 0;
npc->bits |= NPC_IGNORE_SOLIDITY;
npc->yvel = 0;
if (npc->x > player.x)
npc->xvel = -0x400;
else
npc->xvel = 0x400;
npc->view.back = 12 * 0x200;
npc->view.front = 12 * 0x200;
npc->view.top = 12 * 0x200;
npc->view.bottom = 12 * 0x200;
// Fallthrough
case 3:
if (++npc->anim > 4) npc->anim = 2;
if (++npc->act_wait % 4 == 1) {
if (npc->dir == 1)
npc_spawn(287, npc->x, npc->y, 0, 0x400, 0, NULL, 0x100);
else
npc_spawn(287, npc->x, npc->y, 0, -0x400, 0, NULL, 0x100);
}
if (npc->x < 1 * 0x200 * 0x10 || npc->x > (stage_data->width * 0x200 * 0x10) - (1 * 0x200 * 0x10)) npc->cond = 0;
break;
}
npc->x += npc->xvel;
npc->y += npc->yvel;
npc->rect = &rc[npc->anim];
}
// Critter (orange, Misery)
void npc_act_289(npc_t *npc) {
static const rect_t rc_left[3] = {
{160, 32, 176, 48},
{176, 32, 192, 48},
{192, 32, 208, 48},
};
static const rect_t rc_right[3] = {
{160, 48, 176, 64},
{176, 48, 192, 64},
{192, 48, 208, 64},
};
switch (npc->act) {
case 0:
npc->act = 1;
npc->anim = 2;
if (npc->x > player.x)
npc->dir = 0;
else
npc->dir = 2;
// Fallthrough
case 1:
if (++npc->act_wait > 16) {
npc->act = 10;
npc->view.top = 8 * 0x200;
npc->view.bottom = 8 * 0x200;
npc->damage = 2;
npc->bits |= NPC_SHOOTABLE;
}
break;
case 10:
if (npc->flags & 8) {
npc->act = 11;
npc->anim = 0;
npc->act_wait = 0;
npc->xvel = 0;
if (npc->x > player.x)
npc->dir = 0;
else
npc->dir = 2;
}
break;
case 11:
if (++npc->act_wait > 10) {
if (++npc->count1 > 4)
npc->act = 12;
else
npc->act = 10;
snd_play_sound(PRIO_NORMAL, 30, FALSE);
npc->yvel = -0x600;
if (npc->dir == 0)
npc->xvel = -0x200;
else
npc->xvel = 0x200;
npc->anim = 2;
}
break;
case 12:
npc->bits |= NPC_IGNORE_SOLIDITY;
if (npc->y > stage_data->height * 0x200 * 0x10) {
npc_show_death_damage(npc);
return;
}
break;
}
if (npc->act >= 10) npc->yvel += 0x40;
if (npc->yvel > 0x5FF) npc->yvel = 0x5FF;
npc->x += npc->xvel;
npc->y += npc->yvel;
if (npc->dir == 0)
npc->rect = &rc_left[npc->anim];
else
npc->rect = &rc_right[npc->anim];
if (npc->act == 1) {
npc->rect_delta.top = 8 - (npc->act_wait / 2);
npc->rect_delta.bottom = -8 - (npc->act_wait / 2);
npc->rect_prev = NULL; // force texrect update
npc->view.top = (npc->act_wait * 0x200) / 2;
npc->view.bottom = (npc->act_wait * 0x200) / 2;
}
}
// Bat (Misery)
void npc_act_290(npc_t *npc) {
static const rect_t rc_left[3] = {
{112, 32, 128, 48},
{128, 32, 144, 48},
{144, 32, 160, 48},
};
static const rect_t rc_right[3] = {
{112, 48, 128, 64},
{128, 48, 144, 64},
{144, 48, 160, 64},
};
switch (npc->act) {
case 0:
npc->act = 1;
npc->anim = 2;
if (npc->x > player.x)
npc->dir = 0;
else
npc->dir = 2;
// Fallthrough
case 1:
if (++npc->act_wait > 16) {
npc->act = 10;
npc->view.top = 8 * 0x200;
npc->view.bottom = 8 * 0x200;
npc->damage = 2;
npc->bits |= NPC_SHOOTABLE;
npc->tgt_y = npc->y;
npc->yvel = 0x400;
}
break;
case 10:
if (++npc->anim_wait > 2) {
npc->anim_wait = 0;
++npc->anim;
}
if (npc->anim > 2) npc->anim = 0;
if (npc->y < npc->tgt_y)
npc->yvel += 0x40;
else
npc->yvel -= 0x40;
if (npc->dir == 0)
npc->xvel -= 0x10;
else
npc->xvel += 0x10;
if (npc->x < 0 || npc->y < 0 || npc->x > stage_data->width * 0x200 * 0x10 ||
npc->y > stage_data->height * 0x200 * 0x10) {
npc_show_death_damage(npc);
return;
}
break;
}
npc->x += npc->xvel;
npc->y += npc->yvel;
if (npc->dir == 0)
npc->rect = &rc_left[npc->anim];
else
npc->rect = &rc_right[npc->anim];
if (npc->act == 1) {
npc->rect_delta.top = 8 - (npc->act_wait / 2);
npc->rect_delta.bottom = -8 - (npc->act_wait / 2);
npc->rect_prev = NULL; // force texrect update
npc->view.top = (npc->act_wait * 0x200) / 2;
npc->view.bottom = (npc->act_wait * 0x200) / 2;
}
}
// Mini Undead Core (inactive)
void npc_act_291(npc_t *npc) {
static const rect_t tc[2] = {
{256, 80, 320, 120},
{256, 0, 320, 40},
};
switch (npc->act) {
case 0:
npc->act = 20;
if (npc->dir == 2) {
npc->bits &= ~NPC_SOLID_HARD;
npc->anim = 1;
}
break;
}
npc->rect = &tc[npc->anim];
}
// Quake
void npc_act_292(npc_t *npc) {
(void)npc;
cam_start_quake_small(10);
}
// Undead Core giant energy shot
void npc_act_293(npc_t *npc) {
static const rect_t rect[2] = {
{240, 200, 280, 240},
{280, 200, 320, 240},
};
switch (npc->act) {
case 0:
npc->act = 1;
// Fallthrough
case 1:
if (++npc->anim > 1) npc->anim = 0;
npc_spawn(4, npc->x + (m_rand(0, 0x10) * 0x200), npc->y + (m_rand(-0x10, 0x10) * 0x200), 0, 0, 0, NULL, 0x100);
npc->x -= 8 * 0x200;
if (npc->x < -32 * 0x200) npc->cond = 0;
break;
}
npc->rect = &rect[npc->anim];
}
// Quake + falling block generator
void npc_act_294(npc_t *npc) {
int x, y, dir;
switch (npc->act) {
case 0:
if (player.x < (stage_data->width - 6) * 0x200 * 0x10) {
npc->act = 1;
npc->act_wait = 0;
}
break;
case 1:
++npc->act_wait;
if (player.equip & EQUIP_BOOSTER_2_0) {
npc->x = player.x + (64 * 0x200);
if (npc->x < 416 * 0x200) npc->x = 416 * 0x200;
} else {
npc->x = player.x + (96 * 0x200);
if (npc->x < 368 * 0x200) npc->x = 368 * 0x200;
}
if (npc->x > (stage_data->width - 10) * 0x200 * 0x10)
npc->x = (stage_data->width - 10) * 0x200 * 0x10;
if (npc->act_wait > 24) {
if (player.equip & EQUIP_BOOSTER_2_0)
x = npc->x + (m_rand(-14, 14) * 0x200 * 0x10);
else
x = npc->x + (m_rand(-11, 11) * 0x200 * 0x10);
y = player.y - (224 * 0x200);
if (m_rand(0, 10) % 2) // Because just doing 'm_rand(0, 1)' is too hard
dir = 0;
else
dir = 2;
npc_spawn(279, x, y, 0, 0, dir, NULL, 0x100);
npc->act_wait = m_rand(0, 15);
}
break;
}
}
// Cloud
void npc_act_295(npc_t *npc) {
static const rect_t rc[4] = {
{0, 0, 208, 64},
{32, 64, 144, 96},
{32, 96, 104, 0x80},
{104, 96, 144, 0x80},
};
switch (npc->act) {
case 0:
npc->act = 1;
npc->anim = npc->dir % 4;
switch (npc->dir) {
case 0:
npc->yvel = -1000;
npc->view.back = 104 * 0x200;
npc->view.front = 104 * 0x200;
break;
case 1:
npc->yvel = -0x800;
npc->view.back = 56 * 0x200;
npc->view.front = 56 * 0x200;
break;
case 2:
npc->yvel = -0x400;
npc->view.back = 32 * 0x200;
npc->view.front = 32 * 0x200;
break;
case 3:
npc->yvel = -0x200;
npc->view.back = 20 * 0x200;
npc->view.front = 20 * 0x200;
break;
case 4:
npc->xvel = -0x400;
npc->view.back = 104 * 0x200;
npc->view.front = 104 * 0x200;
break;
case 5:
npc->xvel = -0x200;
npc->view.back = 56 * 0x200;
npc->view.front = 56 * 0x200;
break;
case 6:
npc->xvel = -0x100;
npc->view.back = 32 * 0x200;
npc->view.front = 32 * 0x200;
break;
case 7:
npc->xvel = -0x80;
npc->view.back = 20 * 0x200;
npc->view.front = 20 * 0x200;
break;
}
break;
case 1:
npc->x += npc->xvel;
npc->y += npc->yvel;
if (npc->x < -64 * 0x200) npc->cond = 0;
if (npc->y < -32 * 0x200) npc->cond = 0;
break;
}
npc->rect = &rc[npc->anim];
}
// Cloud generator
void npc_act_296(npc_t *npc) {
int x, y, dir, pri;
if (++npc->act_wait > 16) {
npc->act_wait = m_rand(0, 16);
dir = m_rand(0, 100) % 4;
if (npc->dir == 0) {
switch (dir) {
case 0:
pri = 0x180;
break;
case 1:
pri = 0x80;
break;
case 2:
pri = 0x40;
break;
default:
pri = 0x00;
break;
}
x = m_rand(-10, 10) * 0x200 * 0x10 + npc->x;
y = npc->y;
npc_spawn(295, x, y, 0, 0, dir, NULL, pri);
} else {
switch (dir) {
case 0:
pri = 0x80;
break;
case 1:
pri = 0x55;
break;
case 2:
pri = 0x40;
break;
default:
pri = 0x00;
break;
}
x = npc->x;
y = m_rand(-7, 7) * 0x200 * 0x10 + npc->y;
npc_spawn(295, x, y, 0, 0, dir + 4, NULL, pri);
}
}
}
// Sue in dragon's mouth
void npc_act_297(npc_t *npc) {
static const rect_t rc = {112, 48, 0x80, 64};
npc->x = npc->parent->x + (16 * 0x200);
npc->y = npc->parent->y + (8 * 0x200);
npc->rect = &rc;
}
// Doctor (opening)
void npc_act_298(npc_t *npc) {
static const rect_t rc[8] = {
{72, 0x80, 88, 160}, {88, 0x80, 104, 160}, {104, 0x80, 120, 160}, {72, 0x80, 88, 160},
{120, 0x80, 136, 160}, {72, 0x80, 88, 160}, {104, 160, 120, 192}, {120, 160, 136, 192},
};
switch (npc->act) {
case 0:
npc->act = 1;
npc->y -= 8 * 0x200;
// Fallthrough
case 1:
npc->anim = 0;
break;
case 10:
npc->act = 11;
npc->anim = 0;
npc->anim_wait = 0;
npc->count1 = 0;
// Fallthrough
case 11:
if (++npc->anim_wait > 6) {
npc->anim_wait = 0;
++npc->anim;
}
if (npc->anim > 1) {
npc->anim = 0;
if (++npc->count1 > 7) {
npc->anim = 0;
npc->act = 1;
}
}
break;
case 20:
npc->act = 21;
npc->anim = 2;
npc->anim_wait = 0;
// Fallthrough
case 21:
if (++npc->anim_wait > 10) {
npc->anim_wait = 0;
++npc->anim;
}
if (npc->anim > 5) npc->anim = 2;
npc->x += 0x100;
break;
case 30:
npc->anim = 6;
break;
case 40:
npc->act = 41;
npc->anim = 6;
npc->anim_wait = 0;
npc->count1 = 0;
// Fallthrough
case 41:
if (++npc->anim_wait > 6) {
npc->anim_wait = 0;
++npc->anim;
}
if (npc->anim > 7) {
npc->anim = 6;
if (++npc->count1 > 7) {
npc->anim = 6;
npc->act = 30;
}
}
break;
}
npc->rect = &rc[npc->anim];
}
// Balrog/Misery (opening)
void npc_act_299(npc_t *npc) {
static const rect_t rc[2] = {
{0, 0, 48, 48},
{48, 0, 96, 48},
};
if (npc->act == 0) {
npc->act = 1;
if (npc->dir == 0) {
npc->anim = 1;
npc->act_wait = 25;
npc->y -= 0x40 * (50 / 2);
} else {
npc->anim = 0;
npc->act_wait = 0;
}
}
if (++npc->act_wait / 50 % 2)
npc->y += 0x40;
else
npc->y -= 0x40;
npc->rect = &rc[npc->anim];
}
| 0 | 0.870654 | 1 | 0.870654 | game-dev | MEDIA | 0.970168 | game-dev | 0.92049 | 1 | 0.92049 |
ixray-team/ixray-1.6-stcop | 25,777 | src/xrGame/visual_memory_manager.cpp | ////////////////////////////////////////////////////////////////////////////
// Module : visual_memory_manager.cpp
// Created : 02.10.2001
// Modified : 19.11.2003
// Author : Dmitriy Iassenev
// Description : Visual memory manager
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "pch_script.h"
#include "visual_memory_manager.h"
#include "ai/stalker/ai_stalker.h"
#include "memory_space_impl.h"
#include "../Include/xrRender/Kinematics.h"
#include "ai_object_location.h"
#include "level_graph.h"
#include "stalker_movement_manager_smart_cover.h"
#include "../xrEngine/GameMtlLib.h"
#include "agent_manager.h"
#include "agent_member_manager.h"
#include "ai_space.h"
#include "Actor.h"
#include "../xrEngine/CameraBase.h"
#include "GamePersistent.h"
#include "actor_memory.h"
#include "client_spawn_manager.h"
#include "client_spawn_manager.h"
#include "memory_manager.h"
#include "ai/monsters/basemonster/base_monster.h"
#ifndef MASTER_GOLD
# include "actor.h"
# include "ai_debug.h"
#endif // MASTER_GOLD
//Alundaio
#include "../../xrScripts/script_engine.h"
#include "script_game_object.h"
using namespace luabind; //Alundaio
//-Alundaio
void SetActorVisibility(u16 who, float value);
struct SRemoveOfflinePredicate {
bool operator() (const CVisibleObject &object) const
{
VERIFY (object.m_object);
return (!!object.m_object->getDestroy() || object.m_object->H_Parent());
}
bool operator() (const CNotYetVisibleObject &object) const
{
VERIFY (object.m_object);
return (!!object.m_object->getDestroy() || object.m_object->H_Parent());
}
};
struct CVisibleObjectPredicate {
u32 m_id;
CVisibleObjectPredicate (u32 id) :
m_id(id)
{
}
bool operator() (const CObject *object) const
{
VERIFY (object);
return (object->ID() == m_id);
}
};
struct CNotYetVisibleObjectPredicate{
const CGameObject *m_game_object;
IC CNotYetVisibleObjectPredicate(const CGameObject *game_object)
{
m_game_object = game_object;
}
IC bool operator() (const CNotYetVisibleObject &object) const
{
return (object.m_object->ID() == m_game_object->ID());
}
};
CVisualMemoryManager::CVisualMemoryManager (CCustomMonster *object)
{
m_object = object;
m_stalker = 0;
m_client = 0;
initialize ();
}
CVisualMemoryManager::CVisualMemoryManager (CAI_Stalker *stalker)
{
m_object = stalker;
m_stalker = stalker;
m_client = 0;
initialize ();
}
CVisualMemoryManager::CVisualMemoryManager (vision_client *client)
{
m_object = 0;
m_stalker = 0;
m_client = client;
initialize ();
m_objects = new VISIBLES();
}
void CVisualMemoryManager::initialize ()
{
LoadCallbackGlobals(m_isGetVisibleValue, m_onGetVisibleValue, "OnGetVisibleValue");
m_max_object_count = 128;
m_enabled = true;
m_objects = 0;
}
CVisualMemoryManager::~CVisualMemoryManager ()
{
clear_delayed_objects ();
if (!m_client)
return;
xr_delete (m_objects);
}
void CVisualMemoryManager::reinit ()
{
if (!m_client)
m_objects = 0;
else {
VERIFY (m_objects);
m_objects->clear ();
}
m_visible_objects.clear ();
// m_visible_objects.reserve (100);
m_not_yet_visible_objects.clear ();
// m_not_yet_visible_objects.reserve (100);
if (m_object)
m_object->feel_vision_clear ();
m_last_update_time = u32(-1);
}
void CVisualMemoryManager::reload (LPCSTR section)
{
// m_max_object_count = READ_IF_EXISTS(pSettings,r_s32,section,"DynamicObjectsCount",1);
if (m_stalker) {
m_free.Load (pSettings->r_string(section,"vision_free_section"),true);
m_danger.Load (pSettings->r_string(section,"vision_danger_section"),true);
}
else if (m_object) {
m_free.Load(READ_IF_EXISTS(pSettings, r_string, section, "vision_free_section", section), !!m_client);
m_danger.Load(READ_IF_EXISTS(pSettings, r_string, section, "vision_danger_section", section), !!m_client);
}
else {
m_free.Load (section,!!m_client);
}
}
const CVisionParameters &CVisualMemoryManager::current_state() const
{
if ( m_stalker ) {
return (m_stalker->movement().mental_state() == eMentalStateDanger) ? m_danger : m_free;
}
else if ( m_object ) {
return m_object->is_base_monster_with_enemy() ? m_danger : m_free;
}
else {
return m_free;
}
}
u32 CVisualMemoryManager::visible_object_time_last_seen (const CObject *object) const
{
VISIBLES::iterator I = std::find(m_objects->begin(),m_objects->end(), CMemoryObject::object_id(object));
if (I != m_objects->end())
return (I->m_level_time);
else
return u32(-1);
}
bool CVisualMemoryManager::visible_right_now (const CGameObject *game_object) const
{
if ( !m_objects )
{
// --> owner is dead
return false;
}
if ( should_ignore_object(game_object) )
{
return false;
}
VISIBLES::const_iterator I = std::find(objects().begin(),objects().end(), CMemoryObject::object_id(game_object));
if ((objects().end() == I))
return (false);
if (!(*I).visible(mask()))
return (false);
if ((*I).m_level_time < m_last_update_time)
return (false);
return (true);
}
bool CVisualMemoryManager::visible_now (const CGameObject *game_object) const
{
if ( !m_objects )
{
// --> owner is dead
return false;
}
if ( should_ignore_object(game_object) )
{
return false;
}
VISIBLES::const_iterator I = std::find(objects().begin(),objects().end(), CMemoryObject::object_id(game_object));
return ((objects().end() != I) && (*I).visible(mask()));
}
void CVisualMemoryManager::enable (const CObject *object, bool enable)
{
VISIBLES::iterator J = std::find(m_objects->begin(),m_objects->end(), CMemoryObject::object_id(object));
if (J == m_objects->end())
return;
(*J).m_enabled = enable;
}
float CVisualMemoryManager::object_visible_distance(const CGameObject *game_object, float &object_distance) const
{
Fvector eye_position = Fvector().set(0.f,0.f,0.f), eye_direction;
Fmatrix eye_matrix;
float object_range = flt_max, object_fov = flt_max;
if (m_object) {
eye_matrix =
PKinematics(
m_object->Visual()
)
->LL_GetTransform (
u16(m_object->eye_bone)
);
Fvector temp;
eye_matrix.transform_tiny (temp,eye_position);
m_object->XFORM().transform_tiny(eye_position,temp);
if (m_stalker) {
eye_direction.setHP (-m_stalker->movement().m_head.current.yaw, -m_stalker->movement().m_head.current.pitch);
} else { // if its a monster
const MonsterSpace::SBoneRotation &head_orient = m_object->head_orientation();
eye_direction.setHP (-head_orient.current.yaw, -head_orient.current.pitch);
}
}
else {
Fvector dummy;
float aspect_ratio_, near_plane_;
m_client->camera (eye_position,eye_direction,dummy,object_fov, aspect_ratio_, near_plane_, object_range);
}
Fvector object_direction;
game_object->Center (object_direction);
object_distance = object_direction.distance_to(eye_position);
object_direction.sub (eye_position);
object_direction.normalize_safe ();
if (m_object)
m_object->update_range_fov (object_range,object_fov,m_object->eye_range,deg2rad(m_object->eye_fov));
float fov = object_fov*.5f;
float cos_alpha = eye_direction.dotproduct(object_direction);
clamp (cos_alpha,-.99999f,.99999f);
float alpha = acosf(cos_alpha);
clamp (alpha,0.f,fov);
float max_view_distance = object_range, min_view_distance = object_range;
max_view_distance *= current_state().m_max_view_distance;
min_view_distance *= current_state().m_min_view_distance;
float distance = (1.f - alpha/fov)*(max_view_distance - min_view_distance) + min_view_distance;
clamp(distance, 0.f, GamePersistent().Environment().CurrentEnv->fog_far);
return (distance);
}
float CVisualMemoryManager::object_luminocity (const CGameObject *game_object) const
{
CGameObject* GO = const_cast<CGameObject*>(game_object);
if (!GO->cast_actor())
return (1.f);
float luminocity = const_cast<CGameObject*>(game_object)->ROS()->get_luminocity();
float power = log(luminocity > .001f ? luminocity : .001f)*current_state().m_luminocity_factor;
return (exp(power));
}
float CVisualMemoryManager::get_object_velocity (const CGameObject *game_object, const CNotYetVisibleObject ¬_yet_visible_object) const
{
//Alundaio: no need to check velocity on anything but stalkers, mutants and actor
if (!smart_cast<CEntityAlive const*>(game_object))
return (0.f);
//-Alundaio
if ((game_object->ps_Size() < 2) || (not_yet_visible_object.m_prev_time == game_object->ps_Element(game_object->ps_Size() - 2).dwTime))
return (0.f);
CObject::SavedPosition pos0 = game_object->ps_Element (game_object->ps_Size() - 2);
CObject::SavedPosition pos1 = game_object->ps_Element (game_object->ps_Size() - 1);
return (
pos1.vPosition.distance_to(pos0.vPosition)/
(
float(pos1.dwTime)/1000.f -
float(pos0.dwTime)/1000.f
)
);
}
float CVisualMemoryManager::get_visible_value(const CGameObject *game_object, float distance, float object_distance, float time_delta, float object_velocity, float luminocity) const
{
float always_visible_distance = current_state().m_always_visible_distance;
if (distance <= always_visible_distance + EPS_L)
return (current_state().m_visibility_threshold);
if (m_isGetVisibleValue)
{
// Alundaio: hijack not_yet_visible_object to lua
luabind::functor<float> funct;
R_ASSERT2(ai().script_engine().functor(m_onGetVisibleValue, funct), "failed to get OnGetVisibleValue functor");
return (funct(m_object ? m_object->lua_game_object() : 0, game_object ? game_object->lua_game_object() : 0, time_delta, current_state().m_time_quant, luminocity, current_state().m_velocity_factor, object_velocity, distance, object_distance, always_visible_distance));
//-Alundaio
}
return (
time_delta /
current_state().m_time_quant *
luminocity *
(1.f + current_state().m_velocity_factor*object_velocity) *
(distance - object_distance) /
(distance - always_visible_distance)
);
}
CNotYetVisibleObject *CVisualMemoryManager::not_yet_visible_object(const CGameObject *game_object)
{
PROF_EVENT("Memory Manager/visuals/not_yet_visible_object")
xr_vector<CNotYetVisibleObject>::iterator I = std::find_if(
m_not_yet_visible_objects.begin(),
m_not_yet_visible_objects.end(),
CNotYetVisibleObjectPredicate(game_object)
);
if (I == m_not_yet_visible_objects.end())
return (0);
return (&*I);
}
void CVisualMemoryManager::add_not_yet_visible_object (const CNotYetVisibleObject ¬_yet_visible_object)
{
xr_vector<CNotYetVisibleObject>::iterator I = std::find_if(
m_not_yet_visible_objects.begin(),
m_not_yet_visible_objects.end(),
CNotYetVisibleObjectPredicate(not_yet_visible_object.m_object)
);
if (I == m_not_yet_visible_objects.end())
m_not_yet_visible_objects.push_back (not_yet_visible_object);
}
u32 CVisualMemoryManager::get_prev_time (const CGameObject *game_object) const
{
if (!game_object->ps_Size())
return (0);
if (game_object->ps_Size() == 1)
return (game_object->ps_Element(0).dwTime);
return (game_object->ps_Element(game_object->ps_Size() - 2).dwTime);
}
bool CVisualMemoryManager::visible (const CGameObject *game_object, float time_delta)
{
VERIFY (game_object);
if ( should_ignore_object(game_object) )
{
return false;
}
if (game_object->getDestroy())
return (false);
#ifndef USE_STALKER_VISION_FOR_MONSTERS
if (!m_stalker && !m_client)
return (true);
#endif
float object_distance, distance = object_visible_distance(game_object,object_distance);
CNotYetVisibleObject *object = not_yet_visible_object(game_object);
if (distance < object_distance) {
if (object) {
object->m_value -= current_state().m_decrease_value;
if (object->m_value < 0.f)
object->m_value = 0.f;
else
object->m_update_time = Device.dwTimeGlobal;
return (object->m_value >= current_state().m_visibility_threshold);
}
return (false);
}
if (!object) {
CNotYetVisibleObject new_object;
new_object.m_object = game_object;
new_object.m_prev_time = 0;
new_object.m_value = get_visible_value(game_object,distance,object_distance,time_delta,get_object_velocity(game_object,new_object),object_luminocity(game_object));
clamp (new_object.m_value,0.f,current_state().m_visibility_threshold + EPS_L);
new_object.m_update_time = Device.dwTimeGlobal;
new_object.m_prev_time = get_prev_time(game_object);
add_not_yet_visible_object (new_object);
return (new_object.m_value >= current_state().m_visibility_threshold);
}
object->m_update_time = Device.dwTimeGlobal;
object->m_value += get_visible_value(game_object,distance,object_distance,time_delta,get_object_velocity(game_object,*object),object_luminocity(game_object));
clamp (object->m_value,0.f,current_state().m_visibility_threshold + EPS_L);
object->m_prev_time = get_prev_time(game_object);
return (object->m_value >= current_state().m_visibility_threshold);
}
bool CVisualMemoryManager::should_ignore_object (CObject const* object) const
{
if ( !object )
{
return true;
}
CObject* O = const_cast<CObject*>(object);
#ifndef MASTER_GOLD
if (O && O->cast_actor() && psAI_Flags.test(aiIgnoreActor))
{
return true;
}
else
#endif // MASTER_GOLD
{
CGameObject* GO = O ? O->cast_game_object() : NULL;
if (CBaseMonster* monster = GO ? GO->cast_base_monster() : NULL)
{
if (!monster->can_be_seen())
{
return true;
}
}
}
return false;
}
void CVisualMemoryManager::add_visible_object(const CObject* object, float time_delta, bool fictitious)
{
if (!fictitious && should_ignore_object(object))
{
return;
}
xr_vector<CVisibleObject>::iterator J;
CObject* O = const_cast<CObject*>(object);
CGameObject* game_object;
CGameObject* self;
game_object = O->cast_game_object();
if (!game_object || (!fictitious && !visible(game_object, time_delta)))
return;
self = m_object;
J = std::find(m_objects->begin(), m_objects->end(), CMemoryObject::object_id(game_object));
if (m_objects->end() == J)
{
CVisibleObject visible_object;
visible_object.fill(game_object, self, mask(), mask());
#ifdef USE_FIRST_GAME_TIME
visible_object.m_first_game_time = Level().GetGameTime();
#endif
#ifdef USE_FIRST_LEVEL_TIME
visible_object.m_first_level_time = Device.dwTimeGlobal;
#endif
if (m_max_object_count <= m_objects->size()) {
xr_vector<CVisibleObject>::iterator I = std::min_element(m_objects->begin(), m_objects->end(), SLevelTimePredicate());
VERIFY(m_objects->end() != I);
*I = visible_object;
}
else
m_objects->push_back(visible_object);
}
else {
if (!fictitious)
(*J).fill(game_object, self, (*J).m_squad_mask.get() | mask(), (*J).m_visible.get() | mask());
else {
(*J).m_visible.assign((*J).m_visible.get() | mask());
(*J).m_squad_mask.assign((*J).m_squad_mask.get() | mask());
(*J).m_enabled = true;
}
}
}
void CVisualMemoryManager::add_visible_object(const CVisibleObject visible_object)
{
if (should_ignore_object(visible_object.m_object))
{
return;
}
VERIFY(m_objects);
xr_vector<CVisibleObject>::iterator J = std::find(m_objects->begin(), m_objects->end(), CMemoryObject::object_id(visible_object.m_object));
if (m_objects->end() != J)
*J = visible_object;
else if (m_max_object_count <= m_objects->size())
{
xr_vector<CVisibleObject>::iterator I = std::min_element(m_objects->begin(), m_objects->end(), SLevelTimePredicate());
VERIFY(m_objects->end() != I);
*I = visible_object;
}
else
m_objects->push_back(visible_object);
}
bool CVisualMemoryManager::visible(u32 _level_vertex_id, float yaw, float eye_fov) const
{
Fvector direction;
direction.sub (ai().level_graph().vertex_position(_level_vertex_id),m_object->Position());
direction.normalize_safe();
float y, p;
direction.getHP (y,p);
if (angle_difference(yaw,y) <= eye_fov*PI/180.f/2.f)
return(ai().level_graph().check_vertex_in_direction(m_object->ai_location().level_vertex_id(),m_object->Position(),_level_vertex_id));
else
return(false);
}
float CVisualMemoryManager::feel_vision_mtl_transp(CObject* O, u32 element)
{
float vis = 1.f;
if (O){
IKinematics* V = PKinematics(O->Visual());
if (0!=V){
CBoneData& B = V->LL_GetData((u16)element);
vis = GMLib.GetMaterialByIdx(B.game_mtl_idx)->fVisTransparencyFactor;
}
}else{
CDB::TRI* T = Level().ObjectSpace.GetStaticTris()+element;
vis = GMLib.GetMaterialByIdx(T->material)->fVisTransparencyFactor;
}
return vis;
}
struct CVisibleObjectPredicateEx {
const CObject *m_object;
CVisibleObjectPredicateEx (const CObject *object) :
m_object (object)
{
}
bool operator() (const MemorySpace::CVisibleObject &visible_object) const
{
if (!m_object)
return (!visible_object.m_object);
if (!visible_object.m_object)
return (false);
return (m_object->ID() == visible_object.m_object->ID());
}
bool operator() (const MemorySpace::CNotYetVisibleObject ¬_yet_visible_object) const
{
if (!m_object)
return (!not_yet_visible_object.m_object);
if (!not_yet_visible_object.m_object)
return (false);
return (m_object->ID() == not_yet_visible_object.m_object->ID());
}
};
void CVisualMemoryManager::remove_links (CObject *object)
{
{
VERIFY (m_objects);
VISIBLES::iterator I = std::find_if(m_objects->begin(),m_objects->end(),CVisibleObjectPredicateEx(object));
if (I != m_objects->end())
m_objects->erase (I);
}
{
NOT_YET_VISIBLES::iterator I = std::find_if(m_not_yet_visible_objects.begin(),m_not_yet_visible_objects.end(),CVisibleObjectPredicateEx(object));
if (I != m_not_yet_visible_objects.end())
m_not_yet_visible_objects.erase (I);
}
}
struct CRemoveVisibleObjectPredicate {
const MemorySpace::CVisibleObject* m_object;
CRemoveVisibleObjectPredicate(const MemorySpace::CVisibleObject* object) : m_object(object)
{
}
bool operator() (const MemorySpace::CVisibleObject& object) const
{
return (m_object == &object);
}
};
void CVisualMemoryManager::remove(const MemorySpace::CVisibleObject* visible_object)
{
VISIBLES::iterator I = std::find_if(m_objects->begin(), m_objects->end(), CRemoveVisibleObjectPredicate(visible_object));
if (I != m_objects->end())
m_objects->erase(I);
}
CVisibleObject *CVisualMemoryManager::visible_object (const CGameObject *game_object)
{
VISIBLES::iterator I = std::find_if(m_objects->begin(),m_objects->end(),CVisibleObjectPredicateEx(game_object));
if (I == m_objects->end())
return (0);
return (&*I);
}
u64 CVisualMemoryManager::mask () const
{
if (!m_stalker)
return (u64(-1));
return (m_stalker->agent_manager().member().mask(m_stalker));
}
void CVisualMemoryManager::update (float time_delta)
{
PROF_EVENT("Memory Manager/visuals/update")
clear_delayed_objects ();
if (!enabled())
return;
m_last_update_time = Device.dwTimeGlobal;
u64 mask = this->mask();
VERIFY (m_objects);
m_visible_objects.clear ();
if (m_object)
m_object->feel_vision_get (m_visible_objects);
else {
VERIFY (m_client);
m_client->feel_vision_get (m_visible_objects);
}
{
PROF_EVENT("make_invisible");
xr_vector<CVisibleObject>::iterator I = m_objects->begin();
xr_vector<CVisibleObject>::iterator E = m_objects->end();
for (; I != E; ++I)
if ((*I).m_level_time + current_state().m_still_visible_time < Device.dwTimeGlobal)
(*I).visible(mask, false);
}
{
PROF_EVENT("add_visibles");
xr_vector<CObject*>::const_iterator I = m_visible_objects.begin();
xr_vector<CObject*>::const_iterator E = m_visible_objects.end();
for ( ; I != E; ++I)
add_visible_object (*I,time_delta);
}
{
PROF_EVENT("make_not_yet_visible");
xr_vector<CNotYetVisibleObject>::iterator I = m_not_yet_visible_objects.begin();
xr_vector<CNotYetVisibleObject>::iterator E = m_not_yet_visible_objects.end();
for ( ; I != E; ++I)
if ((*I).m_update_time < Device.dwTimeGlobal)
(*I).m_value = 0.f;
}
// verifying if object is online
{
PROF_EVENT("removing_offline");
m_objects->erase (
std::remove_if(
m_objects->begin(),
m_objects->end(),
SRemoveOfflinePredicate()
),
m_objects->end()
);
}
// verifying if object is online
{
PROF_EVENT("removing_offline: not vis");
m_not_yet_visible_objects.erase (
std::remove_if(
m_not_yet_visible_objects.begin(),
m_not_yet_visible_objects.end(),
SRemoveOfflinePredicate()
),
m_not_yet_visible_objects.end()
);
}
if (m_object && g_actor && m_object->is_relation_enemy(Actor())) {
xr_vector<CNotYetVisibleObject>::iterator I = std::find_if(
m_not_yet_visible_objects.begin(),
m_not_yet_visible_objects.end(),
CNotYetVisibleObjectPredicate(Actor())
);
if (I != m_not_yet_visible_objects.end()) {
SetActorVisibility (
m_object->ID(),
clampr(
(*I).m_value/visibility_threshold(),
0.f,
1.f
)
);
}
else
SetActorVisibility (m_object->ID(),0.f);
}
}
static inline bool is_object_valuable_to_save ( CCustomMonster const* const self, MemorySpace::CVisibleObject const& object )
{
CGameObject* GO = const_cast<CGameObject*>(object.m_object);
CEntityAlive* entity_alive = GO ? GO->cast_entity_alive() : NULL;
if ( !entity_alive )
return false;
if ( !entity_alive->g_Alive() )
return true;
return self->is_relation_enemy(entity_alive);
}
void CVisualMemoryManager::save (NET_Packet &packet) const
{
if (m_client)
return;
if (!m_object->g_Alive())
return;
// Msg("before saving object %s[%d]", m_object->cName().c_str(), packet.w_tell() );
u32 count = 0;
VISIBLES::const_iterator I = objects().begin();
VISIBLES::const_iterator const E = objects().end();
for ( ; I != E; ++I) {
if ( is_object_valuable_to_save( m_object, *I) )
++count;
}
packet.w_u8 ((u8)count);
if ( !count )
return;
for ( I = objects().begin(); I != E; ++I) {
if ( !is_object_valuable_to_save( m_object, *I) )
continue;
VERIFY ((*I).m_object);
packet.w_u16 ((*I).m_object->ID());
// object params
packet.w_u32 ((*I).m_object_params.m_level_vertex_id);
packet.w_vec3 ((*I).m_object_params.m_position);
// self params
packet.w_u32 ((*I).m_self_params.m_level_vertex_id);
packet.w_vec3 ((*I).m_self_params.m_position);
packet.w_u32 ((Device.dwTimeGlobal >= (*I).m_level_time) ? (Device.dwTimeGlobal - (*I).m_level_time) : 0);
packet.w_u32 ((Device.dwTimeGlobal >= (*I).m_level_time) ? (Device.dwTimeGlobal - (*I).m_last_level_time) : 0);
packet.w_u64 ((*I).m_visible.flags);
}
// Msg("after saving object %s[%d]", m_object->cName().c_str(), packet.w_tell() );
}
void CVisualMemoryManager::load (IReader &packet)
{
if (m_client)
return;
if (!m_object->g_Alive())
return;
typedef CClientSpawnManager::CALLBACK_TYPE CALLBACK_TYPE;
CALLBACK_TYPE callback;
callback.bind (&m_object->memory(),&CMemoryManager::on_requested_spawn);
int count = packet.r_u8();
for (int i=0; i<count; ++i) {
CDelayedVisibleObject delayed_object;
delayed_object.m_object_id = packet.r_u16();
CVisibleObject &object = delayed_object.m_visible_object;
CObject* O = Level().Objects.net_Find(delayed_object.m_object_id);
object.m_object = O ? O->cast_game_object() : NULL;
// object params
object.m_object_params.m_level_vertex_id = packet.r_u32();
packet.r_fvector3 (object.m_object_params.m_position);
// self params
object.m_self_params.m_level_vertex_id = packet.r_u32();
packet.r_fvector3 (object.m_self_params.m_position);
VERIFY (Device.dwTimeGlobal >= object.m_level_time);
object.m_level_time = packet.r_u32();
object.m_level_time = Device.dwTimeGlobal - object.m_level_time;
VERIFY (Device.dwTimeGlobal >= object.m_last_level_time);
object.m_last_level_time = packet.r_u32();
object.m_last_level_time = Device.dwTimeGlobal - object.m_last_level_time;
object.m_visible.assign (packet.r_u64());
if (object.m_object) {
add_visible_object (object);
continue;
}
m_delayed_objects.push_back (delayed_object);
const CClientSpawnManager::CSpawnCallback *spawn_callback = Level().client_spawn_manager().callback(delayed_object.m_object_id,m_object->ID());
if (!spawn_callback || !spawn_callback->m_object_callback)
if(!g_dedicated_server)
Level().client_spawn_manager().add (delayed_object.m_object_id,m_object->ID(),callback);
#ifdef DEBUG
else {
if (spawn_callback && spawn_callback->m_object_callback) {
VERIFY (spawn_callback->m_object_callback == callback);
}
}
#endif // DEBUG
}
}
void CVisualMemoryManager::clear_delayed_objects()
{
if (m_client)
return;
if (m_delayed_objects.empty())
return;
CClientSpawnManager &manager = Level().client_spawn_manager();
DELAYED_VISIBLE_OBJECTS::const_iterator I = m_delayed_objects.begin();
DELAYED_VISIBLE_OBJECTS::const_iterator E = m_delayed_objects.end();
for ( ; I != E; ++I)
manager.remove ((*I).m_object_id,m_object->ID());
m_delayed_objects.clear ();
}
void CVisualMemoryManager::on_requested_spawn (CObject *object)
{
DELAYED_VISIBLE_OBJECTS::iterator I = m_delayed_objects.begin();
DELAYED_VISIBLE_OBJECTS::iterator E = m_delayed_objects.end();
for ( ; I != E; ++I) {
if ((*I).m_object_id != object->ID())
continue;
if (m_object->g_Alive()) {
(*I).m_visible_object.m_object = object->cast_game_object();
VERIFY ((*I).m_visible_object.m_object);
add_visible_object ((*I).m_visible_object);
}
m_delayed_objects.erase (I);
return;
}
}
| 0 | 0.908421 | 1 | 0.908421 | game-dev | MEDIA | 0.953619 | game-dev | 0.834511 | 1 | 0.834511 |
pybox2d/pybox2d | 10,180 | Box2D/Collision/Shapes/b2PolygonShape.cpp | /*
* 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.
*/
#include <Box2D/Collision/Shapes/b2PolygonShape.h>
#include <new>
b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const
{
void* mem = allocator->Allocate(sizeof(b2PolygonShape));
b2PolygonShape* clone = new (mem) b2PolygonShape;
*clone = *this;
return clone;
}
void b2PolygonShape::SetAsBox(float32 hx, float32 hy)
{
m_count = 4;
m_vertices[0].Set(-hx, -hy);
m_vertices[1].Set( hx, -hy);
m_vertices[2].Set( hx, hy);
m_vertices[3].Set(-hx, hy);
m_normals[0].Set(0.0f, -1.0f);
m_normals[1].Set(1.0f, 0.0f);
m_normals[2].Set(0.0f, 1.0f);
m_normals[3].Set(-1.0f, 0.0f);
m_centroid.SetZero();
}
void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle)
{
m_count = 4;
m_vertices[0].Set(-hx, -hy);
m_vertices[1].Set( hx, -hy);
m_vertices[2].Set( hx, hy);
m_vertices[3].Set(-hx, hy);
m_normals[0].Set(0.0f, -1.0f);
m_normals[1].Set(1.0f, 0.0f);
m_normals[2].Set(0.0f, 1.0f);
m_normals[3].Set(-1.0f, 0.0f);
m_centroid = center;
b2Transform xf;
xf.p = center;
xf.q.Set(angle);
// Transform vertices and normals.
for (int32 i = 0; i < m_count; ++i)
{
m_vertices[i] = b2Mul(xf, m_vertices[i]);
m_normals[i] = b2Mul(xf.q, m_normals[i]);
}
}
int32 b2PolygonShape::GetChildCount() const
{
return 1;
}
static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count)
{
b2Assert(count >= 3);
b2Vec2 c; c.Set(0.0f, 0.0f);
float32 area = 0.0f;
// pRef is the reference point for forming triangles.
// It's location doesn't change the result (except for rounding error).
b2Vec2 pRef(0.0f, 0.0f);
#if 0
// This code would put the reference point inside the polygon.
for (int32 i = 0; i < count; ++i)
{
pRef += vs[i];
}
pRef *= 1.0f / count;
#endif
const float32 inv3 = 1.0f / 3.0f;
for (int32 i = 0; i < count; ++i)
{
// Triangle vertices.
b2Vec2 p1 = pRef;
b2Vec2 p2 = vs[i];
b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0];
b2Vec2 e1 = p2 - p1;
b2Vec2 e2 = p3 - p1;
float32 D = b2Cross(e1, e2);
float32 triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
c += triangleArea * inv3 * (p1 + p2 + p3);
}
// Centroid
b2Assert(area > b2_epsilon);
c *= 1.0f / area;
return c;
}
void b2PolygonShape::Set(const b2Vec2* vertices, int32 count)
{
b2Assert(3 <= count && count <= b2_maxPolygonVertices);
if (count < 3)
{
SetAsBox(1.0f, 1.0f);
return;
}
int32 n = b2Min(count, b2_maxPolygonVertices);
// Copy vertices into local buffer
b2Vec2 ps[b2_maxPolygonVertices];
for (int32 i = 0; i < n; ++i)
{
ps[i] = vertices[i];
}
// Create the convex hull using the Gift wrapping algorithm
// http://en.wikipedia.org/wiki/Gift_wrapping_algorithm
// Find the right most point on the hull
int32 i0 = 0;
float32 x0 = ps[0].x;
for (int32 i = 1; i < count; ++i)
{
float32 x = ps[i].x;
if (x > x0 || (x == x0 && ps[i].y < ps[i0].y))
{
i0 = i;
x0 = x;
}
}
int32 hull[b2_maxPolygonVertices];
int32 m = 0;
int32 ih = i0;
for (;;)
{
hull[m] = ih;
int32 ie = 0;
for (int32 j = 1; j < n; ++j)
{
if (ie == ih)
{
ie = j;
continue;
}
b2Vec2 r = ps[ie] - ps[hull[m]];
b2Vec2 v = ps[j] - ps[hull[m]];
float32 c = b2Cross(r, v);
if (c < 0.0f)
{
ie = j;
}
// Collinearity check
if (c == 0.0f && v.LengthSquared() > r.LengthSquared())
{
ie = j;
}
}
++m;
ih = ie;
if (ie == i0)
{
break;
}
}
m_count = m;
// Copy vertices.
for (int32 i = 0; i < m; ++i)
{
m_vertices[i] = ps[hull[i]];
}
// Compute normals. Ensure the edges have non-zero length.
for (int32 i = 0; i < m; ++i)
{
int32 i1 = i;
int32 i2 = i + 1 < m ? i + 1 : 0;
b2Vec2 edge = m_vertices[i2] - m_vertices[i1];
b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon);
m_normals[i] = b2Cross(edge, 1.0f);
m_normals[i].Normalize();
}
// Compute the polygon centroid.
m_centroid = ComputeCentroid(m_vertices, m);
}
bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const
{
b2Vec2 pLocal = b2MulT(xf.q, p - xf.p);
for (int32 i = 0; i < m_count; ++i)
{
float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]);
if (dot > 0.0f)
{
return false;
}
}
return true;
}
bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
const b2Transform& xf, int32 childIndex) const
{
B2_NOT_USED(childIndex);
// Put the ray into the polygon's frame of reference.
b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p);
b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p);
b2Vec2 d = p2 - p1;
float32 lower = 0.0f, upper = input.maxFraction;
int32 index = -1;
for (int32 i = 0; i < m_count; ++i)
{
// p = p1 + a * d
// dot(normal, p - v) = 0
// dot(normal, p1 - v) + a * dot(normal, d) = 0
float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1);
float32 denominator = b2Dot(m_normals[i], d);
if (denominator == 0.0f)
{
if (numerator < 0.0f)
{
return false;
}
}
else
{
// Note: we want this predicate without division:
// lower < numerator / denominator, where denominator < 0
// Since denominator < 0, we have to flip the inequality:
// lower < numerator / denominator <==> denominator * lower > numerator.
if (denominator < 0.0f && numerator < lower * denominator)
{
// Increase lower.
// The segment enters this half-space.
lower = numerator / denominator;
index = i;
}
else if (denominator > 0.0f && numerator < upper * denominator)
{
// Decrease upper.
// The segment exits this half-space.
upper = numerator / denominator;
}
}
// The use of epsilon here causes the assert on lower to trip
// in some cases. Apparently the use of epsilon was to make edge
// shapes work, but now those are handled separately.
//if (upper < lower - b2_epsilon)
if (upper < lower)
{
return false;
}
}
b2Assert(0.0f <= lower && lower <= input.maxFraction);
if (index >= 0)
{
output->fraction = lower;
output->normal = b2Mul(xf.q, m_normals[index]);
return true;
}
return false;
}
void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const
{
B2_NOT_USED(childIndex);
b2Vec2 lower = b2Mul(xf, m_vertices[0]);
b2Vec2 upper = lower;
for (int32 i = 1; i < m_count; ++i)
{
b2Vec2 v = b2Mul(xf, m_vertices[i]);
lower = b2Min(lower, v);
upper = b2Max(upper, v);
}
b2Vec2 r(m_radius, m_radius);
aabb->lowerBound = lower - r;
aabb->upperBound = upper + r;
}
void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const
{
// Polygon mass, centroid, and inertia.
// Let rho be the polygon density in mass per unit area.
// Then:
// mass = rho * int(dA)
// centroid.x = (1/mass) * rho * int(x * dA)
// centroid.y = (1/mass) * rho * int(y * dA)
// I = rho * int((x*x + y*y) * dA)
//
// We can compute these integrals by summing all the integrals
// for each triangle of the polygon. To evaluate the integral
// for a single triangle, we make a change of variables to
// the (u,v) coordinates of the triangle:
// x = x0 + e1x * u + e2x * v
// y = y0 + e1y * u + e2y * v
// where 0 <= u && 0 <= v && u + v <= 1.
//
// We integrate u from [0,1-v] and then v from [0,1].
// We also need to use the Jacobian of the transformation:
// D = cross(e1, e2)
//
// Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
//
// The rest of the derivation is handled by computer algebra.
b2Assert(m_count >= 3);
b2Vec2 center; center.Set(0.0f, 0.0f);
float32 area = 0.0f;
float32 I = 0.0f;
// s is the reference point for forming triangles.
// It's location doesn't change the result (except for rounding error).
b2Vec2 s(0.0f, 0.0f);
// This code would put the reference point inside the polygon.
for (int32 i = 0; i < m_count; ++i)
{
s += m_vertices[i];
}
s *= 1.0f / m_count;
const float32 k_inv3 = 1.0f / 3.0f;
for (int32 i = 0; i < m_count; ++i)
{
// Triangle vertices.
b2Vec2 e1 = m_vertices[i] - s;
b2Vec2 e2 = i + 1 < m_count ? m_vertices[i+1] - s : m_vertices[0] - s;
float32 D = b2Cross(e1, e2);
float32 triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
center += triangleArea * k_inv3 * (e1 + e2);
float32 ex1 = e1.x, ey1 = e1.y;
float32 ex2 = e2.x, ey2 = e2.y;
float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2;
float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2;
I += (0.25f * k_inv3 * D) * (intx2 + inty2);
}
// Total mass
massData->mass = density * area;
// Center of mass
b2Assert(area > b2_epsilon);
center *= 1.0f / area;
massData->center = center + s;
// Inertia tensor relative to the local origin (point s).
massData->I = density * I;
// Shift to center of mass then to original body origin.
massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center));
}
bool b2PolygonShape::Validate() const
{
for (int32 i = 0; i < m_count; ++i)
{
int32 i1 = i;
int32 i2 = i < m_count - 1 ? i1 + 1 : 0;
b2Vec2 p = m_vertices[i1];
b2Vec2 e = m_vertices[i2] - p;
for (int32 j = 0; j < m_count; ++j)
{
if (j == i1 || j == i2)
{
continue;
}
b2Vec2 v = m_vertices[j] - p;
float32 c = b2Cross(e, v);
if (c < 0.0f)
{
return false;
}
}
}
return true;
}
| 0 | 0.888782 | 1 | 0.888782 | game-dev | MEDIA | 0.939757 | game-dev | 0.98614 | 1 | 0.98614 |
LiteLDev/LeviLamina | 1,060 | src-server/mc/editor/RequestLoadRealmsWorldSlotsPayload.h | #pragma once
#include "mc/_HeaderOutputPredefine.h"
// auto generated inclusion list
#include "mc/editor/network/NetworkPayload.h"
namespace Editor::Network {
class RequestLoadRealmsWorldSlotsPayload
: public ::Editor::Network::NetworkPayload<::Editor::Network::RequestLoadRealmsWorldSlotsPayload> {
public:
// member variables
// NOLINTBEGIN
::ll::UntypedStorage<8, 32> mUnk25f716;
// NOLINTEND
public:
// prevent constructor by default
RequestLoadRealmsWorldSlotsPayload& operator=(RequestLoadRealmsWorldSlotsPayload const&);
RequestLoadRealmsWorldSlotsPayload(RequestLoadRealmsWorldSlotsPayload const&);
RequestLoadRealmsWorldSlotsPayload();
public:
// virtual functions
// NOLINTBEGIN
// vIndex: 0
virtual ~RequestLoadRealmsWorldSlotsPayload() /*override*/;
// NOLINTEND
public:
// destructor thunk
// NOLINTBEGIN
MCNAPI void $dtor();
// NOLINTEND
public:
// vftables
// NOLINTBEGIN
MCNAPI static void** $vftable();
// NOLINTEND
};
} // namespace Editor::Network
| 0 | 0.667881 | 1 | 0.667881 | game-dev | MEDIA | 0.494221 | game-dev | 0.584082 | 1 | 0.584082 |
Hiro420/CockPY | 5,632 | server_data/lua/scene/3/scene3_group133102482.lua | --================================================================
--
-- 配置
--
--================================================================
-- 怪物
monsters = {
}
-- NPC
npcs = {
}
-- 装置
gadgets = {
{ config_id = 482001, gadget_id = 70310011, pos = { x = 1384.0, y = 157.4, z = -295.5 }, rot = { x = 0.0, y = 0.0, z = 0.0 }, level = 16, persistent = true },
{ config_id = 482002, gadget_id = 70310011, pos = { x = 1359.1, y = 159.3, z = -279.0 }, rot = { x = 0.0, y = 0.0, z = 0.0 }, level = 16, persistent = true },
{ config_id = 482003, gadget_id = 70310011, pos = { x = 1395.7, y = 158.8, z = -269.6 }, rot = { x = 0.0, y = 0.0, z = 0.0 }, level = 16, persistent = true }
}
-- 区域
regions = {
}
-- 触发器
triggers = {
{ name = "GADGET_STATE_CHANGE_482004", event = EventType.EVENT_GADGET_STATE_CHANGE, source = "", condition = "condition_EVENT_GADGET_STATE_CHANGE_482004", action = "action_EVENT_GADGET_STATE_CHANGE_482004", trigger_count = 0 },
{ name = "GADGET_STATE_CHANGE_482005", event = EventType.EVENT_GADGET_STATE_CHANGE, source = "", condition = "condition_EVENT_GADGET_STATE_CHANGE_482005", action = "action_EVENT_GADGET_STATE_CHANGE_482005", trigger_count = 0 },
{ name = "GADGET_STATE_CHANGE_482006", event = EventType.EVENT_GADGET_STATE_CHANGE, source = "", condition = "condition_EVENT_GADGET_STATE_CHANGE_482006", action = "action_EVENT_GADGET_STATE_CHANGE_482006", trigger_count = 0 },
{ name = "GADGET_STATE_CHANGE_482007", event = EventType.EVENT_GADGET_STATE_CHANGE, source = "", condition = "condition_EVENT_GADGET_STATE_CHANGE_482007", action = "action_EVENT_GADGET_STATE_CHANGE_482007", trigger_count = 0 },
{ name = "GADGET_STATE_CHANGE_482008", event = EventType.EVENT_GADGET_STATE_CHANGE, source = "", condition = "condition_EVENT_GADGET_STATE_CHANGE_482008", action = "action_EVENT_GADGET_STATE_CHANGE_482008", trigger_count = 0 },
{ name = "GADGET_STATE_CHANGE_482009", event = EventType.EVENT_GADGET_STATE_CHANGE, source = "", condition = "condition_EVENT_GADGET_STATE_CHANGE_482009", action = "action_EVENT_GADGET_STATE_CHANGE_482009", trigger_count = 0 },
{ name = "VARIABLE_CHANGE_482010", event = EventType.EVENT_VARIABLE_CHANGE, source = "", condition = "condition_EVENT_VARIABLE_CHANGE_482010", action = "" }
}
-- 变量
variables = {
{ name = "count", value = 0, no_refresh = true }
}
--================================================================
--
-- 初始化配置
--
--================================================================
-- 初始化时创建
init_config = {
suite = 1,
end_suite = 0,
rand_suite = false
}
--================================================================
--
-- 小组配置
--
--================================================================
suites = {
{
-- suite_id = 1,
-- description = ,
monsters = { },
gadgets = { },
regions = { },
triggers = { },
rand_weight = 100
}
}
--================================================================
--
-- 触发器
--
--================================================================
-- 触发条件
function condition_EVENT_GADGET_STATE_CHANGE_482004(context, evt)
if 482003 ~= evt.param2 or GadgetState.GearStart ~= evt.param1 then
return false
end
return true
end
-- 触发操作
function action_EVENT_GADGET_STATE_CHANGE_482004(context, evt)
-- 针对当前group内变量名为 "count" 的变量,进行修改,变化值为 1
if 0 ~= ScriptLib.ChangeGroupVariableValue(context, "count", 1) then
return -1
end
return 0
end
-- 触发条件
function condition_EVENT_GADGET_STATE_CHANGE_482005(context, evt)
if 482003 ~= evt.param2 or GadgetState.Default ~= evt.param1 then
return false
end
return true
end
-- 触发操作
function action_EVENT_GADGET_STATE_CHANGE_482005(context, evt)
-- 针对当前group内变量名为 "count" 的变量,进行修改,变化值为 -1
if 0 ~= ScriptLib.ChangeGroupVariableValue(context, "count", -1) then
return -1
end
return 0
end
-- 触发条件
function condition_EVENT_GADGET_STATE_CHANGE_482006(context, evt)
if 482002 ~= evt.param2 or GadgetState.GearStart ~= evt.param1 then
return false
end
return true
end
-- 触发操作
function action_EVENT_GADGET_STATE_CHANGE_482006(context, evt)
-- 针对当前group内变量名为 "count" 的变量,进行修改,变化值为 1
if 0 ~= ScriptLib.ChangeGroupVariableValue(context, "count", 1) then
return -1
end
return 0
end
-- 触发条件
function condition_EVENT_GADGET_STATE_CHANGE_482007(context, evt)
if 482002 ~= evt.param2 or GadgetState.Default ~= evt.param1 then
return false
end
return true
end
-- 触发操作
function action_EVENT_GADGET_STATE_CHANGE_482007(context, evt)
-- 针对当前group内变量名为 "count" 的变量,进行修改,变化值为 -1
if 0 ~= ScriptLib.ChangeGroupVariableValue(context, "count", -1) then
return -1
end
return 0
end
-- 触发条件
function condition_EVENT_GADGET_STATE_CHANGE_482008(context, evt)
if 482001 ~= evt.param2 or GadgetState.GearStart ~= evt.param1 then
return false
end
return true
end
-- 触发操作
function action_EVENT_GADGET_STATE_CHANGE_482008(context, evt)
-- 针对当前group内变量名为 "count" 的变量,进行修改,变化值为 1
if 0 ~= ScriptLib.ChangeGroupVariableValue(context, "count", 1) then
return -1
end
return 0
end
-- 触发条件
function condition_EVENT_GADGET_STATE_CHANGE_482009(context, evt)
if 482001 ~= evt.param2 or GadgetState.Default ~= evt.param1 then
return false
end
return true
end
-- 触发操作
function action_EVENT_GADGET_STATE_CHANGE_482009(context, evt)
-- 针对当前group内变量名为 "count" 的变量,进行修改,变化值为 -1
if 0 ~= ScriptLib.ChangeGroupVariableValue(context, "count", -1) then
return -1
end
return 0
end
-- 触发条件
function condition_EVENT_VARIABLE_CHANGE_482010(context, evt)
-- 判断变量"count"为3
if ScriptLib.GetGroupVariableValue(context, "count") ~= 3 then
return false
end
return true
end
-- 触发操作
| 0 | 0.937864 | 1 | 0.937864 | game-dev | MEDIA | 0.895065 | game-dev | 0.942832 | 1 | 0.942832 |
staff0rd/polygon-map-unity | 3,326 | demo/Assets/Unity-delaunay/Delaunay/HalfedgePriorityQueue.cs | using UnityEngine;
using System.Collections.Generic;
using Delaunay.Utils;
namespace Delaunay
{
internal sealed class HalfedgePriorityQueue: Utils.IDisposable // also known as heap
{
private Halfedge[] _hash;
private int _count;
private int _minBucket;
private int _hashsize;
private float _ymin;
private float _deltay;
public HalfedgePriorityQueue (float ymin, float deltay, int sqrt_nsites)
{
_ymin = ymin;
_deltay = deltay;
_hashsize = 4 * sqrt_nsites;
Initialize ();
}
public void Dispose ()
{
// get rid of dummies
for (int i = 0; i < _hashsize; ++i) {
_hash [i].Dispose ();
_hash [i] = null;
}
_hash = null;
}
private void Initialize ()
{
int i;
_count = 0;
_minBucket = 0;
_hash = new Halfedge[_hashsize];
// dummy Halfedge at the top of each hash
for (i = 0; i < _hashsize; ++i) {
_hash [i] = Halfedge.CreateDummy ();
_hash [i].nextInPriorityQueue = null;
}
}
public void Insert (Halfedge halfEdge)
{
Halfedge previous, next;
int insertionBucket = Bucket (halfEdge);
if (insertionBucket < _minBucket) {
_minBucket = insertionBucket;
}
previous = _hash [insertionBucket];
while ((next = previous.nextInPriorityQueue) != null
&& (halfEdge.ystar > next.ystar || (halfEdge.ystar == next.ystar && halfEdge.vertex.x > next.vertex.x))) {
previous = next;
}
halfEdge.nextInPriorityQueue = previous.nextInPriorityQueue;
previous.nextInPriorityQueue = halfEdge;
++_count;
}
public void Remove (Halfedge halfEdge)
{
Halfedge previous;
int removalBucket = Bucket (halfEdge);
if (halfEdge.vertex != null) {
previous = _hash [removalBucket];
while (previous.nextInPriorityQueue != halfEdge) {
previous = previous.nextInPriorityQueue;
}
previous.nextInPriorityQueue = halfEdge.nextInPriorityQueue;
_count--;
halfEdge.vertex = null;
halfEdge.nextInPriorityQueue = null;
halfEdge.Dispose ();
}
}
private int Bucket (Halfedge halfEdge)
{
int theBucket = (int)((halfEdge.ystar - _ymin) / _deltay * _hashsize);
if (theBucket < 0)
theBucket = 0;
if (theBucket >= _hashsize)
theBucket = _hashsize - 1;
return theBucket;
}
private bool IsEmpty (int bucket)
{
return (_hash [bucket].nextInPriorityQueue == null);
}
/**
* move _minBucket until it contains an actual Halfedge (not just the dummy at the top);
*
*/
private void AdjustMinBucket ()
{
while (_minBucket < _hashsize - 1 && IsEmpty(_minBucket)) {
++_minBucket;
}
}
public bool Empty ()
{
return _count == 0;
}
/**
* @return coordinates of the Halfedge's vertex in V*, the transformed Voronoi diagram
*
*/
public Vector2 Min ()
{
AdjustMinBucket ();
Halfedge answer = _hash [_minBucket].nextInPriorityQueue;
return new Vector2 (answer.vertex.x, answer.ystar);
}
/**
* remove and return the min Halfedge
* @return
*
*/
public Halfedge ExtractMin ()
{
Halfedge answer;
// get the first real Halfedge in _minBucket
answer = _hash [_minBucket].nextInPriorityQueue;
_hash [_minBucket].nextInPriorityQueue = answer.nextInPriorityQueue;
_count--;
answer.nextInPriorityQueue = null;
return answer;
}
}
} | 0 | 0.871343 | 1 | 0.871343 | game-dev | MEDIA | 0.182558 | game-dev | 0.964433 | 1 | 0.964433 |
followingthefasciaplane/source-engine-diff-check | 2,552 | misc/game/client/tf/vgui/tf_imagepanel.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include <KeyValues.h>
#include <vgui/IScheme.h>
#include <vgui/ISurface.h>
#include <vgui/ISystem.h>
#include <vgui_controls/AnimationController.h>
#include <vgui_controls/EditablePanel.h>
#include <vgui/ISurface.h>
#include <vgui/IImage.h>
#include <vgui_controls/Label.h>
#include "tf_imagepanel.h"
#include "c_tf_player.h"
using namespace vgui;
DECLARE_BUILD_FACTORY( CTFImagePanel );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTFImagePanel::CTFImagePanel( Panel *parent, const char *name ) : ScalableImagePanel( parent, name )
{
for ( int i = 0; i < TF_TEAM_COUNT; i++ )
{
m_szTeamBG[i][0] = '\0';
}
C_TFPlayer *pPlayer = ToTFPlayer( C_BasePlayer::GetLocalPlayer() );
m_iBGTeam = pPlayer ? pPlayer->GetTeamNumber() : TEAM_UNASSIGNED;
ListenForGameEvent( "localplayer_changeteam" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFImagePanel::ApplySettings( KeyValues *inResourceData )
{
for ( int i = 0; i < TF_TEAM_COUNT; i++ )
{
Q_strncpy( m_szTeamBG[i], inResourceData->GetString( VarArgs("teambg_%d", i), "" ), sizeof( m_szTeamBG[i] ) );
if ( m_szTeamBG[i] && m_szTeamBG[i][0] )
{
PrecacheMaterial( VarArgs( "vgui/%s", m_szTeamBG[i] ) );
}
}
BaseClass::ApplySettings( inResourceData );
UpdateBGImage();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFImagePanel::UpdateBGImage( void )
{
if ( m_iBGTeam >= 0 && m_iBGTeam < TF_TEAM_COUNT )
{
if ( m_szTeamBG[m_iBGTeam] && m_szTeamBG[m_iBGTeam][0] )
{
SetImage( m_szTeamBG[m_iBGTeam] );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFImagePanel::FireGameEvent( IGameEvent * event )
{
if ( FStrEq( "localplayer_changeteam", event->GetName() ) )
{
C_TFPlayer *pPlayer = ToTFPlayer( C_BasePlayer::GetLocalPlayer() );
m_iBGTeam = pPlayer ? pPlayer->GetTeamNumber() : TEAM_UNASSIGNED;
UpdateBGImage();
}
} | 0 | 0.731631 | 1 | 0.731631 | game-dev | MEDIA | 0.600285 | game-dev | 0.753129 | 1 | 0.753129 |
mmbot/mmbot | 1,221 | MMBot.Core/Listeners/RosterListener.cs | using System;
using MMBot.Scripts;
namespace MMBot
{
public class RosterListener : IListener
{
private readonly Robot _robot;
private readonly Action<IResponse<EnterMessage>> _enterCallback;
private readonly Action<IResponse<LeaveMessage>> _leaveCallback;
public RosterListener(Robot robot, Action<IResponse<EnterMessage>> callback)
{
_robot = robot;
_enterCallback = callback;
}
public RosterListener(Robot robot, Action<IResponse<LeaveMessage>> callback)
{
_robot = robot;
_leaveCallback = callback;
}
public ScriptSource Source { get; set; }
public bool Call(Message message)
{
var lm = message as LeaveMessage;
if (lm != null && _leaveCallback != null)
{
_leaveCallback(Response.Create(_robot, lm));
return true;
}
var em = message as EnterMessage;
if (em != null && _enterCallback != null)
{
_enterCallback(Response.Create(_robot, em));
return true;
}
return false;
}
}
}
| 0 | 0.814821 | 1 | 0.814821 | game-dev | MEDIA | 0.383953 | game-dev | 0.837663 | 1 | 0.837663 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.