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
libsdl-org/SDL-1.2
4,655
src/joystick/riscos/SDL_sysjoystick.c
/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 Sam Lantinga 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #include "SDL_config.h" #ifdef SDL_JOYSTICK_RISCOS /* RISC OS - Joystick support by Alan Buckley (alan_baa@hotmail.com) - 10 April 2003 Note: Currently assumes joystick is present if joystick module is loaded and that there is one joystick with eight buttons. */ /* This is the system specific header for the SDL joystick API */ #include "SDL_events.h" #include "SDL_joystick.h" #include "../SDL_sysjoystick.h" #include "../SDL_joystick_c.h" #include "kernel.h" #ifndef Joystick_Read #define Joystick_Read 0x43F40 #endif struct joystick_hwdata { int joystate; }; /* Function to scan the system for joysticks. * This function should set SDL_numjoysticks to the number of available * joysticks. Joystick 0 should be the system default joystick. * It should return number of joysticks, or -1 on an unrecoverable fatal error. */ int SDL_SYS_JoystickInit(void) { _kernel_swi_regs regs; /* Try to read joystick 0 */ regs.r[0] = 0; if (_kernel_swi(Joystick_Read, &regs, &regs) == NULL) { /* Switch works so assume we've got a joystick */ return 1; } /* Switch fails so it looks like there's no joystick here */ return(0); } /* Function to get the device-dependent name of a joystick */ const char *SDL_SYS_JoystickName(int index) { if (index == 0) { return "RISC OS Joystick 0"; } SDL_SetError("No joystick available with that index"); return(NULL); } /* Function to open a joystick for use. The joystick to open is specified by the index field of the joystick. This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) { if(!(joystick->hwdata=SDL_malloc(sizeof(struct joystick_hwdata)))) { SDL_OutOfMemory(); return -1; } /* Don't know how to get exact count of buttons so assume max of 8 for now */ joystick->nbuttons=8; joystick->nhats=0; joystick->nballs=0; joystick->naxes=2; joystick->hwdata->joystate=0; return 0; } /* Function to update the state of a joystick - called as a device poll. * This function shouldn't update the joystick structure directly, * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick) { _kernel_swi_regs regs; regs.r[0] = joystick->index; if (_kernel_swi(Joystick_Read, &regs, &regs) == NULL) { int newstate = regs.r[0]; int oldstate = joystick->hwdata->joystate; if (newstate != oldstate) { if ((newstate & 0xFF) != (oldstate & 0xFF)) { int y = regs.r[0] & 0xFF; /* Convert to signed values */ if (y >= 128) y -= 256; SDL_PrivateJoystickAxis(joystick,1,-y * 256); /* Up and down opposite to result in SDL */ } if ((newstate & 0xFF00) != (oldstate & 0xFF00)) { int x = (regs.r[0] & 0xFF00) >> 8; if (x >= 128) x -= 256; SDL_PrivateJoystickAxis(joystick,0,x * 256); } if ((newstate & 0xFF0000) != (oldstate & 0xFF0000)) { int buttons = (regs.r[0] & 0xFF0000) >> 16; int oldbuttons = (oldstate & 0xFF0000) >> 16; int i; for (i = 0; i < joystick->nbuttons; i++) { if ((buttons & (1<<i)) != (oldbuttons & (1<<i))) { if (buttons & (1<<i)) SDL_PrivateJoystickButton(joystick,i,SDL_PRESSED); else SDL_PrivateJoystickButton(joystick,i,SDL_RELEASED); } } } joystick->hwdata->joystate = newstate; } } return; } /* Function to close a joystick after use */ void SDL_SYS_JoystickClose(SDL_Joystick *joystick) { if(joystick->hwdata) SDL_free(joystick->hwdata); return; } /* Function to perform any system-specific joystick related cleanup */ void SDL_SYS_JoystickQuit(void) { SDL_numjoysticks=0; return; } #endif /* SDL_JOYSTICK_RISCOS */
0
0.679688
1
0.679688
game-dev
MEDIA
0.853658
game-dev,drivers
0.679998
1
0.679998
Elfansoer/dota-2-lua-abilities
3,286
scripts/vscripts/lua_abilities/centaur_warrunner_return_lua/modifier_centaur_warrunner_return_lua.lua
modifier_centaur_warrunner_return_lua = class({}) -------------------------------------------------------------------------------- -- Classifications function modifier_centaur_warrunner_return_lua:IsHidden() return true end function modifier_centaur_warrunner_return_lua:IsPurgable() return false end -------------------------------------------------------------------------------- -- Initializations function modifier_centaur_warrunner_return_lua:OnCreated( kv ) -- references self.base_damage = self:GetAbility():GetSpecialValueFor( "return_damage" ) -- special value self.strength_pct = self:GetAbility():GetSpecialValueFor( "strength_pct" ) -- special value end function modifier_centaur_warrunner_return_lua:OnRefresh( kv ) -- references self.base_damage = self:GetAbility():GetSpecialValueFor( "return_damage" ) -- special value self.strength_pct = self:GetAbility():GetSpecialValueFor( "strength_pct" ) -- special value end function modifier_centaur_warrunner_return_lua:OnDestroy( kv ) end -------------------------------------------------------------------------------- -- Modifier Effects function modifier_centaur_warrunner_return_lua:DeclareFunctions() local funcs = { MODIFIER_EVENT_ON_ATTACKED, } return funcs end function modifier_centaur_warrunner_return_lua:OnAttacked( params ) if IsServer() then if self:GetParent():IsIllusion() or self:GetParent():PassivesDisabled() then return end if params.unit==self:GetParent() or self:FlagExist( params.damage_flags, DOTA_DAMAGE_FLAG_REFLECTION ) then return end -- get damage local damage = self.base_damage + self:GetParent():GetStrength()*(self.strength_pct/100) -- Apply Damage local damageTable = { victim = params.attacker, attacker = self:GetParent(), damage = damage, damage_type = DAMAGE_TYPE_PHYSICAL, damage_flags = DOTA_DAMAGE_FLAG_REFLECTION, ability = self:GetAbility(), --Optional. } ApplyDamage(damageTable) -- Play effects if params.attacker:IsConsideredHero() then self:PlayEffects( params.attacker ) end end end -- Helper: Flag operations function modifier_centaur_warrunner_return_lua:FlagExist(a,b)--Bitwise Exist local p,c,d=1,0,b while a>0 and b>0 do local ra,rb=a%2,b%2 if ra+rb>1 then c=c+p end a,b,p=(a-ra)/2,(b-rb)/2,p*2 end return c==d end -------------------------------------------------------------------------------- -- Graphics & Animations -- function modifier_centaur_warrunner_return_lua:GetEffectName() -- return "particles/string/here.vpcf" -- end -- function modifier_centaur_warrunner_return_lua:GetEffectAttachType() -- return PATTACH_ABSORIGIN_FOLLOW -- end function modifier_centaur_warrunner_return_lua:PlayEffects( target ) local particle_cast = "particles/units/heroes/hero_centaur/centaur_return.vpcf" local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_ABSORIGIN_FOLLOW, self:GetParent() ) ParticleManager:SetParticleControlEnt( effect_cast, 0, self:GetParent(), PATTACH_POINT_FOLLOW, "attach_hitloc", self:GetParent():GetOrigin(), -- unknown true -- unknown, true ) ParticleManager:SetParticleControlEnt( effect_cast, 1, target, PATTACH_POINT_FOLLOW, "attach_hitloc", target:GetOrigin(), -- unknown true -- unknown, true ) end
0
0.976835
1
0.976835
game-dev
MEDIA
0.955242
game-dev
0.976493
1
0.976493
fnmwolf/Anaconda
1,236
Chowdren/base/objects/advdir.cpp
#include "objects/advdir.h" #include "mathcommon.h" // AdvancedDirection AdvancedDirection::AdvancedDirection(int x, int y, int type_id) : FrameObject(x, y, type_id) { } void AdvancedDirection::find_closest(ObjectList & instances, int x, int y) { float lowest_dist; closest = NULL; for (ObjectIterator it(instances); !it.end(); ++it) { FrameObject * instance = *it; float dist = get_distance(x, y, instance->x, instance->y); if (closest != NULL && dist > lowest_dist) continue; closest = instance; lowest_dist = dist; } } void AdvancedDirection::find_closest(QualifierList & instances, int x, int y) { float lowest_dist; closest = NULL; for (QualifierIterator it(instances); !it.end(); ++it) { FrameObject * instance = *it; float dist = get_distance(x, y, instance->x, instance->y); if (closest != NULL && dist > lowest_dist) continue; closest = instance; lowest_dist = dist; } } FixedValue AdvancedDirection::get_closest(int n) { return closest->get_fixed(); } float AdvancedDirection::get_object_angle(FrameObject * a, FrameObject * b) { return ::get_angle(a->x, a->y, b->x, b->y); }
0
0.799528
1
0.799528
game-dev
MEDIA
0.419995
game-dev
0.791428
1
0.791428
pablopalafox/npms
11,145
external/gaps/pkgs/R3Shapes/R3Quaternion.cpp
/* Source file for the GAPS quaternion class */ /* Include files */ #include "R3Shapes.h" // Namespace namespace gaps { /* Public variables */ const R3Quaternion R3null_quaternion(0.0, 0.0, 0.0, 0.0); const R3Quaternion R3zero_quaternion(0.0, 0.0, 0.0, 0.0); const R3Quaternion R3identity_quaternion(1.0, 0.0, 0.0, 0.0); /* Public functions */ int R3InitQuaternion() { /* Return success */ return TRUE; } void R3StopQuaternion() { } R3Quaternion:: R3Quaternion(void) { } R3Quaternion:: R3Quaternion(RNScalar a, RNScalar b, RNScalar c, RNScalar d) { v[0] = a; v[1] = b; v[2] = c; v[3] = d; Normalize(); } R3Quaternion:: R3Quaternion(const R3Quaternion& quaternion) { v[0] = quaternion.v[0]; v[1] = quaternion.v[1]; v[2] = quaternion.v[2]; v[3] = quaternion.v[3]; } R3Quaternion:: R3Quaternion(const R3Quaternion& quaternion1, const R3Quaternion& quaternion2, RNScalar t) { *this = R3QuaternionSlerp(quaternion1, quaternion2, t); } R3Quaternion:: R3Quaternion(const R3Vector& axis, RNAngle theta) { RNAngle half_theta = 0.5 * theta; RNScalar sine_half_theta = sin(half_theta); R3Vector normalized_axis = axis; normalized_axis.Normalize(); v[0] = cos(half_theta); v[1] = normalized_axis[0] * sine_half_theta; v[2] = normalized_axis[1] * sine_half_theta; v[3] = normalized_axis[2] * sine_half_theta; Normalize(); } R3Quaternion:: R3Quaternion(int dimension, RNAngle theta) { RNAngle half_theta = 0.5 * theta; RNScalar sine_half_theta = sin(half_theta); R3Vector axis = R3xyz_triad[dimension]; v[0] = cos(half_theta); v[1] = axis[0] * sine_half_theta; v[2] = axis[1] * sine_half_theta; v[3] = axis[2] * sine_half_theta; Normalize(); } R3Quaternion:: R3Quaternion(const R4Matrix& m, int /* dummy */) { #if 1 // From http://www.cg.info.hiroshima-cu.ac.jp/~miyazaki/knowledge/teche52.html v[0] = ( m[0][0] + m[1][1] + m[2][2] + 1.0) / 4.0; v[1] = ( m[0][0] - m[1][1] - m[2][2] + 1.0) / 4.0; v[2] = (-m[0][0] + m[1][1] - m[2][2] + 1.0) / 4.0; v[3] = (-m[0][0] - m[1][1] + m[2][2] + 1.0) / 4.0; if (v[0] < 0.0) v[0] = 0.0; if (v[1] < 0.0) v[1] = 0.0; if (v[2] < 0.0) v[2] = 0.0; if (v[3] < 0.0) v[3] = 0.0; v[0] = sqrt(v[0]); v[1] = sqrt(v[1]); v[2] = sqrt(v[2]); v[3] = sqrt(v[3]); if ((v[0] >= v[1]) && (v[0] >= v[2]) && (v[0] >= v[3])) { v[1] *= RNSign(m[2][1] - m[1][2]); v[2] *= RNSign(m[0][2] - m[2][0]); v[3] *= RNSign(m[1][0] - m[0][1]); } else if ((v[1] >= v[0]) && (v[1] >= v[2]) && (v[1] >= v[3])) { v[0] *= RNSign(m[2][1] - m[1][2]); v[2] *= RNSign(m[1][0] + m[0][1]); v[3] *= RNSign(m[0][2] + m[2][0]); } else if ((v[2] >= v[0]) && (v[2] >= v[1]) && (v[2] >= v[3])) { v[0] *= RNSign(m[0][2] - m[2][0]); v[1] *= RNSign(m[1][0] + m[0][1]); v[3] *= RNSign(m[2][1] + m[1][2]); } else if ((v[3] >= v[0]) && (v[3] >= v[1]) && (v[3] >= v[2])) { v[0] *= RNSign(m[1][0] - m[0][1]); v[1] *= RNSign(m[2][0] + m[0][2]); v[2] *= RNSign(m[2][1] + m[1][2]); } else { v[0] = 0; v[1] = 0; v[2] = 0; v[3] = 0; } #elif 0 // Also probably works // From http://vamos.sourceforge.net/matrixfaq.htm#Q48 RNScalar T = m[0][0] + m[1][1] + m[2][2] + 1.0; if (T > 0.0) { RNScalar S = 0.5 / sqrt(T); v[0] = 0.25 / S; v[1] = ( m[2][1] - m[1][2] ) * S; v[2] = ( m[0][2] - m[2][0] ) * S; v[3] = ( m[1][0] - m[0][1] ) * S; } else { if ((m[0][0] >= m[1][1]) && (m[0][0] >= m[2][2])) { RNScalar S = sqrt( 1.0 + m[0][0] - m[1][1] - m[2][2] ) * 2.0; v[1] = 0.5 / S; v[2] = (m[0][1] + m[1][0] ) / S; v[3] = (m[0][2] + m[2][0] ) / S; v[0] = (m[1][2] + m[2][1] ) / S; } else if ((m[1][1] >= m[0][0]) && (m[1][1] >= m[2][2])) { RNScalar S = sqrt( 1.0 + m[1][1] - m[0][0] - m[2][2] ) * 2; v[1] = (m[0][1] + m[1][0] ) / S; v[2] = 0.5 / S; v[3] = (m[1][2] + m[2][1] ) / S; v[0] = (m[0][2] + m[2][0] ) / S; } else if ((m[2][2] >= m[0][0]) && (m[2][2] >= m[1][1])) { RNScalar S = sqrt( 1.0 + m[2][2] - m[0][0] - m[1][1] ) * 2; v[1] = (m[0][2] + m[2][0] ) / S; v[2] = (m[1][2] + m[2][1] ) / S; v[3] = 0.5 / S; v[0] = (m[0][1] + m[1][0] ) / S; } } #else RNAbort("Not implemented"); #endif // Normalize Normalize(); } R3Quaternion:: R3Quaternion(RNAngle pitch, RNAngle yaw, RNAngle roll) { *this = R3Quaternion(R3Vector(pitch, yaw), roll); } R3Quaternion:: R3Quaternion(const RNScalar array[4]) { v[0] = array[0]; v[1] = array[1]; v[2] = array[2]; v[3] = array[3]; Normalize(); } const R4Matrix R3Quaternion:: Matrix(void) const { // Return rotation matrix RNScalar a = v[0]; RNScalar b = v[1]; RNScalar c = v[2]; RNScalar d = v[3]; R4Matrix m = R4identity_matrix; m[0][0] = a*a + b*b - c*c - d*d; m[0][1] = 2*b*c - 2*a*d; m[0][2] = 2*b*d + 2*a*c; m[1][0] = 2*b*c + 2*a*d; m[1][1] = a*a - b*b + c*c - d*d; m[1][2] = 2*c*d - 2*a*b; m[2][0] = 2*b*d - 2*a*c; m[2][1] = 2*c*d + 2*a*b; m[2][2] = a*a - b*b - c*c + d*d; return m; } const R3Quaternion R3Quaternion:: Inverse(void) const { // Return inverse rotation return R3Quaternion(v[0], -v[1], -v[2], -v[3]); } const RNBoolean R3Quaternion:: operator==(const R3Quaternion& quaternion) const { // Return whether quaternion is equal return ((v[0] == quaternion.v[0]) && (v[1] == quaternion.v[1]) && (v[2] == quaternion.v[2]) && (v[3] == quaternion.v[3])); } const RNBoolean R3Quaternion:: operator!=(const R3Quaternion& quaternion) const { // Return whether quaternion is not equal return ((v[0] != quaternion.v[0]) || (v[1] != quaternion.v[1]) || (v[2] != quaternion.v[2]) || (v[3] != quaternion.v[3])); } void R3Quaternion:: Flip(void) { // Negate all numbers (does not change rotation) v[0] = -v[0]; v[1] = -v[1]; v[2] = -v[2]; v[3] = -v[3]; } void R3Quaternion:: Multiply(const R3Quaternion& q2) { // Multiply quaternion (equivalent to concatenating rotations) RNScalar q1[4]; q1[0] = v[0]; q1[1] = v[1]; q1[2] = v[2]; q1[3] = v[3]; v[0] = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3]; v[1] = q1[0]*q2[1] + q1[1]*q2[0] + q1[2]*q2[3] - q1[3]*q2[2]; v[2] = q1[0]*q2[2] - q1[1]*q2[3] + q1[2]*q2[0] + q1[3]*q2[1]; v[3] = q1[0]*q2[3] + q1[1]*q2[2] - q1[2]*q2[1] + q1[3]*q2[0]; // Normalize(); } void R3Quaternion:: XRotate(RNAngle radians) { // Rotate quaternion around X axis Rotate(R3posx_vector, radians); } void R3Quaternion:: YRotate(RNAngle radians) { // Rotate quaternion around Y axis Rotate(R3posy_vector, radians); } void R3Quaternion:: ZRotate(RNAngle radians) { // Rotate quaternion around Z axis Rotate(R3posz_vector, radians); } void R3Quaternion:: Rotate(int dimension, RNAngle radians) { // Rotate quaternion around Z axis (probably could be faster) Rotate(R3xyz_triad[dimension], radians); } void R3Quaternion:: Rotate(const R3Vector& xyz_radians) { // Rotate first around X, then around Y, and finally around Z ZRotate(xyz_radians.Z()); YRotate(xyz_radians.Y()); XRotate(xyz_radians.X()); } void R3Quaternion:: Rotate(const R3Vector& axis, RNAngle radians) { // Rotate quaternion around axis Rotate(R3Quaternion(axis, radians)); } void R3Quaternion:: Rotate(const R3Quaternion& q2) { // Multiply quaternion (equivalent to concatenating rotations) Multiply(q2); } void R3Quaternion:: Rotate(const R4Matrix& matrix) { // Rotate quaternion by rotation encoded in matrix Rotate(R3Quaternion(matrix, 0)); } R3Quaternion& R3Quaternion:: operator=(const R3Quaternion& quaternion) { // Assign quaternion v[0] = quaternion.v[0]; v[1] = quaternion.v[1]; v[2] = quaternion.v[2]; v[3] = quaternion.v[3]; return *this; } R3Quaternion& R3Quaternion:: operator*=(const R3Quaternion& quaternion) { Multiply(quaternion); return *this; } R3Quaternion operator*(const R3Quaternion& quaternion1, const R3Quaternion& quaternion2) { R3Quaternion q(quaternion1); q *= quaternion2; return q; } R3Point operator*(const R3Quaternion& q, const R3Point& p) { // Rotate point by quaternion R3Vector v = q * p.Vector(); return v.Point(); } R3Vector operator*(const R3Quaternion& q, const R3Vector& v) { // Compute quaternion representation of vector RNLength length = v.Length(); if (RNIsZero(length)) return v; R3Quaternion vector(0, v[0] / length, v[1] / length, v[2] / length); // Compute quaternion representation of rotated vector R3Quaternion conjugate(q[0], -q[1], -q[2], -q[3]); R3Quaternion result = q; result.Multiply(vector); result.Multiply(conjugate); assert(RNIsZero(result[0])); // Return rotated vector return R3Vector(length * result[1], length * result[2], length * result[3]); } R3Quaternion R3QuaternionSlerp(const R3Quaternion& quaternion1, const R3Quaternion& quaternion2, RNScalar t) { // Get convenient variables RNScalar q1[4] = { quaternion1[0], quaternion1[1], quaternion1[2], quaternion1[3] }; RNScalar q2[4] = { quaternion2[0], quaternion2[1], quaternion2[2], quaternion2[3] }; // Make sure going short way around sphere (q2 is same rotation as -q2) RNScalar dot = q1[0]*q2[0] + q1[1]*q2[1] + q1[2]*q2[2] + q1[3]*q2[3]; if (dot < 0) { q2[0] = -q2[0]; q2[1] = -q2[1]; q2[2] = -q2[2]; q2[3] = -q2[3]; dot = -dot; } // Compute/check angle on 4D sphere RNAngle theta = (dot < 1) ? acos(dot) : 0; RNScalar denom = sin(theta); if (RNIsZero(denom)) { // Small angle, use linear interpolation RNScalar q[4]; q[0] = (1-t)*q1[0] + t*q2[0]; q[1] = (1-t)*q1[1] + t*q2[1]; q[2] = (1-t)*q1[2] + t*q2[2]; q[3] = (1-t)*q1[3] + t*q2[3]; return R3Quaternion(q); } else { // Spherical interpolation RNScalar q[4]; RNScalar t1 = sin((1.0-t)*theta) / denom; RNScalar t2 = sin(t*theta) / denom; q[0] = t1*q1[0] + t2*q2[0]; q[1] = t1*q1[1] + t2*q2[1]; q[2] = t1*q1[2] + t2*q2[2]; q[3] = t1*q1[3] + t2*q2[3]; return R3Quaternion(q); } } void R3Quaternion:: Normalize(void) { // Normalize -- internal function because all R3Quaternions are normalized RNScalar sum = 0; sum += v[0]*v[0]; sum += v[1]*v[1]; sum += v[2]*v[2]; sum += v[3]*v[3]; RNScalar length = sqrt(sum); if (RNIsZero(length)) return; v[0] /= length; v[1] /= length; v[2] /= length; v[3] /= length; } void R3Quaternion:: Conjugate(void) { // Take conjugate v[1] = -v[1]; v[2] = -v[2]; v[3] = -v[3]; } } // namespace gaps
0
0.782145
1
0.782145
game-dev
MEDIA
0.592583
game-dev
0.996175
1
0.996175
Wintel/gEdge-GPU
16,440
runtime/gamecode-master/code/q3_ui/ui_teamorders.c
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena 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 2 of the License, or (at your option) any later version. Quake III Arena 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 Quake III Arena source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ // /* ======================================================================= TEAM ORDERS MENU ======================================================================= */ #include "ui_local.h" #define ART_FRAME "menu/" MENU_ART_DIR "/addbotframe" #define ART_BACK0 "menu/" MENU_ART_DIR "/back_0" #define ART_BACK1 "menu/" MENU_ART_DIR "/back_1" #define ID_LIST_BOTS 10 #define ID_LIST_CTF_ORDERS 11 #define ID_LIST_CTF1F_ORDERS 12 #define ID_LIST_BASE_ORDERS 13 #define ID_LIST_TEAM_ORDERS 14 #define ID_LIST_DD_ORDERS 15 typedef struct { menuframework_s menu; menutext_s banner; menubitmap_s frame; menulist_s list; menubitmap_s back; int gametype; int numBots; int selectedBot; char *bots[9]; char botNames[9][16]; } teamOrdersMenuInfo_t; static teamOrdersMenuInfo_t teamOrdersMenuInfo; #define NUM_CTF_ORDERS 7 static const char *ctfOrders[] = {"I Am the Leader", "Defend the Base", "Follow Me", "Get Enemy Flag", "Camp Here", "Report", "I Relinquish Command", NULL}; static const char *ctfMessages[] = {"i am the leader", "%s defend the base", "%s follow me", "%s get the enemy flag", "%s camp here", "%s report", "i stop being the leader", NULL}; #define NUM_CTF1F_ORDERS 7 static const char *ctf1fOrders[] = {"I Am the Leader", "Defend the Base", "Follow Me", "Get The Flag", "Camp Here", "Report", "I Relinquish Command", NULL}; static const char *ctf1fMessages[] = {"i am the leader", "%s defend the base", "%s follow me", "%s get the flag", "%s camp here", "%s report", "i stop being the leader", NULL}; #define NUM_BASE_ORDERS 7 static const char *baseOrders[] = {"I Am the Leader", "Defend the Base", "Follow Me", "Attack the Enemy Base", "Camp Here", "Report", "I Relinquish Command", NULL}; static const char *baseMessages[] = {"i am the leader", "%s defend the base", "%s follow me", "%s attack the base", "%s camp here", "%s report", "i stop being the leader", NULL}; #define NUM_TEAM_ORDERS 6 static const char *teamOrders[] = { "I Am the Leader", "Follow Me", "Roam", "Camp Here", "Report", "I Relinquish Command", NULL}; static const char *teamMessages[] = {"i am the leader", "%s follow me", "%s roam", "%s camp here", "%s report", "i stop being the leader", NULL}; #define NUM_DD_ORDERS 8 static const char *ddOrders[] = {"I Am the Leader", "Follow Me", "Roam", "Dominate Point A", "Dominate Point B", "Camp Here", "Report", "I Relinquish Command", NULL}; static const char *ddMessages[] = {"i am the leader", "%s follow me", "%s roam", "%s dominate point A", "%s dominate point B", "%s camp here", "%s report", "i stop being the leader", NULL}; /* =============== UI_TeamOrdersMenu_BackEvent =============== */ static void UI_TeamOrdersMenu_BackEvent(void *ptr, int event) { if (event != QM_ACTIVATED) { return; } UI_PopMenu(); } /* =============== UI_TeamOrdersMenu_SetList =============== */ static void UI_TeamOrdersMenu_SetList(int id) { switch (id) { default: case ID_LIST_BOTS: teamOrdersMenuInfo.list.generic.id = id; teamOrdersMenuInfo.list.numitems = teamOrdersMenuInfo.numBots; teamOrdersMenuInfo.list.itemnames = (const char **)teamOrdersMenuInfo.bots; break; case ID_LIST_CTF_ORDERS: teamOrdersMenuInfo.list.generic.id = id; teamOrdersMenuInfo.list.numitems = NUM_CTF_ORDERS; teamOrdersMenuInfo.list.itemnames = ctfOrders; break; case ID_LIST_CTF1F_ORDERS: teamOrdersMenuInfo.list.generic.id = id; teamOrdersMenuInfo.list.numitems = NUM_CTF1F_ORDERS; teamOrdersMenuInfo.list.itemnames = ctf1fOrders; break; case ID_LIST_BASE_ORDERS: teamOrdersMenuInfo.list.generic.id = id; teamOrdersMenuInfo.list.numitems = NUM_BASE_ORDERS; teamOrdersMenuInfo.list.itemnames = baseOrders; break; case ID_LIST_TEAM_ORDERS: teamOrdersMenuInfo.list.generic.id = id; teamOrdersMenuInfo.list.numitems = NUM_TEAM_ORDERS; teamOrdersMenuInfo.list.itemnames = teamOrders; break; case ID_LIST_DD_ORDERS: teamOrdersMenuInfo.list.generic.id = id; teamOrdersMenuInfo.list.numitems = NUM_DD_ORDERS; teamOrdersMenuInfo.list.itemnames = ddOrders; break; } teamOrdersMenuInfo.list.generic.bottom = teamOrdersMenuInfo.list.generic.top + teamOrdersMenuInfo.list.numitems * PROP_HEIGHT; } /* ================= UI_TeamOrdersMenu_Key ================= */ sfxHandle_t UI_TeamOrdersMenu_Key(int key) { menulist_s *l; int x; int y; int index; l = (menulist_s *)Menu_ItemAtCursor(&teamOrdersMenuInfo.menu); if (l != &teamOrdersMenuInfo.list) { return Menu_DefaultKey(&teamOrdersMenuInfo.menu, key); } switch (key) { case K_MOUSE1: x = l->generic.left; y = l->generic.top; if (UI_CursorInRect(x, y, l->generic.right - x, l->generic.bottom - y)) { index = (uis.cursory - y) / PROP_HEIGHT; l->oldvalue = l->curvalue; l->curvalue = index; if (l->generic.callback) { l->generic.callback(l, QM_ACTIVATED); return menu_move_sound; } } return menu_null_sound; case K_KP_UPARROW: case K_UPARROW: l->oldvalue = l->curvalue; if (l->curvalue == 0) { l->curvalue = l->numitems - 1; } else { l->curvalue--; } return menu_move_sound; case K_KP_DOWNARROW: case K_DOWNARROW: l->oldvalue = l->curvalue; if (l->curvalue == l->numitems - 1) { l->curvalue = 0; ; } else { l->curvalue++; } return menu_move_sound; } return Menu_DefaultKey(&teamOrdersMenuInfo.menu, key); } /* ================= UI_TeamOrdersMenu_ListDraw ================= */ static void UI_TeamOrdersMenu_ListDraw(void *self) { menulist_s *l; int x; int y; int i; float *color; qboolean hasfocus; int style; l = (menulist_s *)self; hasfocus = (l->generic.parent->cursor == l->generic.menuPosition); x = 320; // l->generic.x; y = l->generic.y; for (i = 0; i < l->numitems; i++) { style = UI_LEFT | UI_SMALLFONT | UI_CENTER; if (i == l->curvalue) { color = color_yellow; if (hasfocus) { style |= UI_PULSE; } } else { color = color_orange; } UI_DrawProportionalString(x, y, l->itemnames[i], style, color); y += PROP_HEIGHT; } } /* =============== UI_TeamOrdersMenu_ListEvent =============== */ static void UI_TeamOrdersMenu_ListEvent(void *ptr, int event) { int id; int selection; char message[256]; if (event != QM_ACTIVATED) return; id = ((menulist_s *)ptr)->generic.id; selection = ((menulist_s *)ptr)->curvalue; if (id == ID_LIST_BOTS) { teamOrdersMenuInfo.selectedBot = selection; if (teamOrdersMenuInfo.gametype == GT_CTF || teamOrdersMenuInfo.gametype == GT_CTF_ELIMINATION) { UI_TeamOrdersMenu_SetList(ID_LIST_CTF_ORDERS); } if (teamOrdersMenuInfo.gametype == GT_1FCTF) { UI_TeamOrdersMenu_SetList(ID_LIST_CTF1F_ORDERS); } if (teamOrdersMenuInfo.gametype == GT_OBELISK || teamOrdersMenuInfo.gametype == GT_HARVESTER) { UI_TeamOrdersMenu_SetList(ID_LIST_BASE_ORDERS); } if (teamOrdersMenuInfo.gametype == GT_TEAM || teamOrdersMenuInfo.gametype == GT_ELIMINATION || teamOrdersMenuInfo.gametype == GT_DOMINATION) { UI_TeamOrdersMenu_SetList(ID_LIST_TEAM_ORDERS); } if (teamOrdersMenuInfo.gametype == GT_DOUBLE_D) { UI_TeamOrdersMenu_SetList(ID_LIST_DD_ORDERS); } return; } if (id == ID_LIST_CTF_ORDERS) { Com_sprintf(message, sizeof(message), ctfMessages[selection], teamOrdersMenuInfo.botNames[teamOrdersMenuInfo.selectedBot]); } if (id == ID_LIST_CTF1F_ORDERS) { Com_sprintf(message, sizeof(message), ctf1fMessages[selection], teamOrdersMenuInfo.botNames[teamOrdersMenuInfo.selectedBot]); } if (id == ID_LIST_BASE_ORDERS) { Com_sprintf(message, sizeof(message), baseMessages[selection], teamOrdersMenuInfo.botNames[teamOrdersMenuInfo.selectedBot]); } if (id == ID_LIST_TEAM_ORDERS) { Com_sprintf(message, sizeof(message), teamMessages[selection], teamOrdersMenuInfo.botNames[teamOrdersMenuInfo.selectedBot]); } if (id == ID_LIST_DD_ORDERS) { Com_sprintf(message, sizeof(message), ddMessages[selection], teamOrdersMenuInfo.botNames[teamOrdersMenuInfo.selectedBot]); } trap_Cmd_ExecuteText(EXEC_APPEND, va("say_team \"%s\"\n", message)); UI_PopMenu(); } /* =============== UI_TeamOrdersMenu_BuildBotList =============== */ static void UI_TeamOrdersMenu_BuildBotList(void) { uiClientState_t cs; int numPlayers; int isBot; int n; char playerTeam = '3'; char botTeam; char info[MAX_INFO_STRING]; for (n = 0; n < 9; n++) { teamOrdersMenuInfo.bots[n] = teamOrdersMenuInfo.botNames[n]; } trap_GetClientState(&cs); Q_strncpyz(teamOrdersMenuInfo.botNames[0], "Everyone", 16); teamOrdersMenuInfo.numBots = 1; trap_GetConfigString(CS_SERVERINFO, info, sizeof(info)); numPlayers = atoi(Info_ValueForKey(info, "sv_maxclients")); teamOrdersMenuInfo.gametype = atoi(Info_ValueForKey(info, "g_gametype")); for (n = 0; n < numPlayers && teamOrdersMenuInfo.numBots < 9; n++) { trap_GetConfigString(CS_PLAYERS + n, info, MAX_INFO_STRING); if (n == cs.clientNum) { playerTeam = *Info_ValueForKey(info, "t"); continue; } isBot = atoi(Info_ValueForKey(info, "skill")); if (!isBot) { continue; } botTeam = *Info_ValueForKey(info, "t"); if (botTeam != playerTeam) { continue; } Q_strncpyz(teamOrdersMenuInfo.botNames[teamOrdersMenuInfo.numBots], Info_ValueForKey(info, "n"), 16); Q_CleanStr(teamOrdersMenuInfo.botNames[teamOrdersMenuInfo.numBots]); teamOrdersMenuInfo.numBots++; } } /* =============== UI_TeamOrdersMenu_Init =============== */ static void UI_TeamOrdersMenu_Init(void) { UI_TeamOrdersMenu_Cache(); memset(&teamOrdersMenuInfo, 0, sizeof(teamOrdersMenuInfo)); teamOrdersMenuInfo.menu.fullscreen = qfalse; teamOrdersMenuInfo.menu.key = UI_TeamOrdersMenu_Key; UI_TeamOrdersMenu_BuildBotList(); teamOrdersMenuInfo.banner.generic.type = MTYPE_BTEXT; teamOrdersMenuInfo.banner.generic.x = 320; teamOrdersMenuInfo.banner.generic.y = 16; teamOrdersMenuInfo.banner.string = "TEAM ORDERS"; teamOrdersMenuInfo.banner.color = color_white; teamOrdersMenuInfo.banner.style = UI_CENTER; teamOrdersMenuInfo.frame.generic.type = MTYPE_BITMAP; teamOrdersMenuInfo.frame.generic.flags = QMF_INACTIVE; teamOrdersMenuInfo.frame.generic.name = ART_FRAME; teamOrdersMenuInfo.frame.generic.x = 320 - 233; teamOrdersMenuInfo.frame.generic.y = 240 - 166; teamOrdersMenuInfo.frame.width = 466; teamOrdersMenuInfo.frame.height = 332; teamOrdersMenuInfo.list.generic.type = MTYPE_SCROLLLIST; teamOrdersMenuInfo.list.generic.flags = QMF_PULSEIFFOCUS; teamOrdersMenuInfo.list.generic.ownerdraw = UI_TeamOrdersMenu_ListDraw; teamOrdersMenuInfo.list.generic.callback = UI_TeamOrdersMenu_ListEvent; teamOrdersMenuInfo.list.generic.x = 320 - 64; teamOrdersMenuInfo.list.generic.y = 120; teamOrdersMenuInfo.back.generic.type = MTYPE_BITMAP; teamOrdersMenuInfo.back.generic.name = ART_BACK0; teamOrdersMenuInfo.back.generic.flags = QMF_LEFT_JUSTIFY | QMF_PULSEIFFOCUS; teamOrdersMenuInfo.back.generic.callback = UI_TeamOrdersMenu_BackEvent; teamOrdersMenuInfo.back.generic.x = 0; teamOrdersMenuInfo.back.generic.y = 480 - 64; teamOrdersMenuInfo.back.width = 128; teamOrdersMenuInfo.back.height = 64; teamOrdersMenuInfo.back.focuspic = ART_BACK1; Menu_AddItem(&teamOrdersMenuInfo.menu, &teamOrdersMenuInfo.banner); Menu_AddItem(&teamOrdersMenuInfo.menu, &teamOrdersMenuInfo.frame); Menu_AddItem(&teamOrdersMenuInfo.menu, &teamOrdersMenuInfo.list); Menu_AddItem(&teamOrdersMenuInfo.menu, &teamOrdersMenuInfo.back); teamOrdersMenuInfo.list.generic.left = 220; teamOrdersMenuInfo.list.generic.top = teamOrdersMenuInfo.list.generic.y; teamOrdersMenuInfo.list.generic.right = 420; UI_TeamOrdersMenu_SetList(ID_LIST_BOTS); } /* ================= UI_TeamOrdersMenu_Cache ================= */ void UI_TeamOrdersMenu_Cache(void) { trap_R_RegisterShaderNoMip(ART_FRAME); trap_R_RegisterShaderNoMip(ART_BACK0); trap_R_RegisterShaderNoMip(ART_BACK1); } /* =============== UI_TeamOrdersMenu =============== */ void UI_TeamOrdersMenu(void) { UI_TeamOrdersMenu_Init(); UI_PushMenu(&teamOrdersMenuInfo.menu); } /* =============== UI_TeamOrdersMenu_f =============== */ void UI_TeamOrdersMenu_f(void) { uiClientState_t cs; char info[MAX_INFO_STRING]; int team; // make sure it's a team game trap_GetConfigString(CS_SERVERINFO, info, sizeof(info)); teamOrdersMenuInfo.gametype = atoi(Info_ValueForKey(info, "g_gametype")); if (teamOrdersMenuInfo.gametype < GT_TEAM || teamOrdersMenuInfo.gametype == GT_LMS || teamOrdersMenuInfo.gametype == GT_POSSESSION) { return; } // not available to spectators trap_GetClientState(&cs); trap_GetConfigString(CS_PLAYERS + cs.clientNum, info, MAX_INFO_STRING); team = atoi(Info_ValueForKey(info, "t")); if (team == TEAM_SPECTATOR) { return; } UI_TeamOrdersMenu(); }
0
0.903514
1
0.903514
game-dev
MEDIA
0.752018
game-dev
0.976264
1
0.976264
egordorichev/BurningKnight
2,543
BurningKnight/entity/item/use/ModifyBombsUse.cs
using System; using BurningKnight.entity.bomb; using BurningKnight.entity.component; using BurningKnight.entity.events; using BurningKnight.entity.projectile; using BurningKnight.util; using ImGuiNET; using Lens.entity; using Lens.lightJson; using Lens.util.math; namespace BurningKnight.entity.item.use { public class ModifyBombsUse : ItemUse { public bool SpawnBullets; public bool SpawnBombs; public bool SetFuseTime; public float FuseTime; public float RadiusMod; public override void Setup(JsonValue settings) { base.Setup(settings); SpawnBullets = settings["spawn_bullets"].Bool(false); SpawnBombs = settings["spawn_bombs"].Bool(false); SetFuseTime = settings["set_fuse"].Bool(false); FuseTime = settings["fuse_time"].Number(1); RadiusMod = settings["radius"].Number(1); } public static void RenderDebug(JsonValue root) { var spawnBullets = root["spawn_bullets"].Bool(false); if (ImGui.Checkbox("Spawn Bullets?", ref spawnBullets)) { root["spawn_bullets"] = spawnBullets; } var spawnBombs = root["spawn_bombs"].Bool(false); if (ImGui.Checkbox("Spawn Bombs?", ref spawnBombs)) { root["spawn_bombs"] = spawnBombs; } root.InputFloat("Radius Modifier", "radius", 1f); var setFuseTime = root["set_fuse"].Bool(false); if (ImGui.Checkbox("Set fuse?", ref setFuseTime)) { root["set_fuse"] = setFuseTime; } if (!setFuseTime) { return; } var fuseTime = root["fuse_time"].Number(1); if (ImGui.InputFloat("Fuse time", ref fuseTime)) { root["fuse_time"] = fuseTime; } } public override bool HandleEvent(Event e) { if (e is BombPlacedEvent bpe) { var bomb = bpe.Bomb; var c = bomb.GetComponent<ExplodeComponent>(); c.Radius *= RadiusMod; if (SetFuseTime) { c.Timer = FuseTime + Rnd.Float(-0.1f, 1f); } if (SpawnBombs) { bomb.OnDeath += b => { if (b.Parent != null) { return; } for (var i = 0; i < 4; i++) { var bm = new Bomb(b.Owner, Bomb.ExplosionTime, b); b.Area.Add(bm); bm.Center = b.Center + Rnd.Vector(-4, 4); bm.VelocityTo(i / 2f * (float) Math.PI, 300f); } }; } if (SpawnBullets) { bomb.OnDeath += b => { var builder = new ProjectileBuilder(b.Owner, "rect") { Scale = b.Scale }; for (var i = 0; i < 8; i++) { builder.Shoot((float) i / 8 * (float) Math.PI * 2, 8).Build().Center = b.Center; } }; } } return base.HandleEvent(e); } } }
0
0.708289
1
0.708289
game-dev
MEDIA
0.981221
game-dev
0.716135
1
0.716135
MrCrayfish/Backpacked
3,782
fabric/src/main/java/com/mrcrayfish/backpacked/client/ClientHandler.java
package com.mrcrayfish.backpacked.client; import com.mojang.blaze3d.vertex.PoseStack; import com.mrcrayfish.backpacked.client.gui.screen.inventory.BackpackManagementScreen; import com.mrcrayfish.backpacked.client.gui.screen.inventory.BackpackScreen; import com.mrcrayfish.backpacked.client.gui.screen.inventory.BackpackShelfScreen; import com.mrcrayfish.backpacked.client.renderer.FirstPersonEffectsRenderer; import com.mrcrayfish.backpacked.client.renderer.entity.layers.BackpackLayer; import com.mrcrayfish.backpacked.client.renderer.blockentity.ShelfRenderer; import com.mrcrayfish.backpacked.client.renderer.entity.layers.VillagerBackpackLayer; import com.mrcrayfish.backpacked.common.backpack.loader.FabricModelMetaLoader; import com.mrcrayfish.backpacked.core.ModBlockEntities; import com.mrcrayfish.backpacked.core.ModContainers; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.model.loading.v1.ModelLoadingPlugin; import net.fabricmc.fabric.api.client.rendering.v1.LivingEntityFeatureRendererRegistrationCallback; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderContext; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents; import net.fabricmc.fabric.api.resource.ResourceManagerHelper; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.MenuScreens; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.blockentity.BlockEntityRenderers; import net.minecraft.client.renderer.entity.WanderingTraderRenderer; import net.minecraft.client.renderer.entity.player.PlayerRenderer; import net.minecraft.server.packs.PackType; /** * Author: MrCrayfish */ public class ClientHandler implements ClientModInitializer { @Override public void onInitializeClient() { ClientBootstrap.earlyInit(); ClientBootstrap.init(); ModelLoadingPlugin.register(new BackpackedModelLoadingPlugin()); MenuScreens.register(ModContainers.BACKPACK.get(), BackpackScreen::new); MenuScreens.register(ModContainers.MANAGEMENT.get(), BackpackManagementScreen::new); MenuScreens.register(ModContainers.BACKPACK_SHELF.get(), BackpackShelfScreen::new); BlockEntityRenderers.register(ModBlockEntities.SHELF.get(), ShelfRenderer::new); // Add backpack layers for player and wandering trader LivingEntityFeatureRendererRegistrationCallback.EVENT.register((entityType, entityRenderer, registrationHelper, context) -> { if(entityRenderer instanceof WanderingTraderRenderer renderer) { registrationHelper.register(new VillagerBackpackLayer<>(renderer, context.getItemRenderer())); } else if(entityRenderer instanceof PlayerRenderer renderer) { registrationHelper.register(new BackpackLayer<>(renderer, context.getItemRenderer())); } }); ResourceManagerHelper.get(PackType.CLIENT_RESOURCES).registerReloadListener(new FabricModelMetaLoader()); WorldRenderEvents.AFTER_ENTITIES.register(this::afterDrawEntities); } private void afterDrawEntities(WorldRenderContext context) { Minecraft mc = Minecraft.getInstance(); if(mc.player == null || mc.level == null) return; if(!mc.options.getCameraType().isFirstPerson()) return; PoseStack stack = context.matrixStack(); if(stack == null) return; MultiBufferSource source = mc.renderBuffers().bufferSource(); boolean frozen = mc.level.tickRateManager().isEntityFrozen(mc.player); float partialTick = context.tickCounter().getGameTimeDeltaPartialTick(!frozen); FirstPersonEffectsRenderer.draw(mc.player, stack, source, partialTick); } }
0
0.847227
1
0.847227
game-dev
MEDIA
0.963997
game-dev
0.944086
1
0.944086
PetterS/monolith
5,606
third-party/protobuf/src/google/protobuf/map_field_lite.h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER 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. #ifndef GOOGLE_PROTOBUF_MAP_FIELD_LITE_H__ #define GOOGLE_PROTOBUF_MAP_FIELD_LITE_H__ #include <google/protobuf/map.h> #include <google/protobuf/map_entry_lite.h> #include <google/protobuf/wire_format_lite.h> namespace google { namespace protobuf { namespace internal { // This class provides access to map field using generated api. It is used for // internal generated message implentation only. Users should never use this // directly. template <typename Derived, typename Key, typename T, WireFormatLite::FieldType key_wire_type, WireFormatLite::FieldType value_wire_type, int default_enum_value = 0> class MapFieldLite { // Define message type for internal repeated field. typedef Derived EntryType; public: typedef Map<Key, T> MapType; typedef EntryType EntryTypeTrait; MapFieldLite() : arena_(NULL) { SetDefaultEnumValue(); } explicit MapFieldLite(Arena* arena) : arena_(arena), map_(arena) { SetDefaultEnumValue(); } // Accessors const Map<Key, T>& GetMap() const { return map_; } Map<Key, T>* MutableMap() { return &map_; } // Convenient methods for generated message implementation. int size() const { return static_cast<int>(map_.size()); } void Clear() { return map_.clear(); } void MergeFrom(const MapFieldLite& other) { for (typename Map<Key, T>::const_iterator it = other.map_.begin(); it != other.map_.end(); ++it) { map_[it->first] = it->second; } } void Swap(MapFieldLite* other) { map_.swap(other->map_); } // Set default enum value only for proto2 map field whose value is enum type. void SetDefaultEnumValue() { MutableMap()->SetDefaultEnumValue(default_enum_value); } // Used in the implementation of parsing. Caller should take the ownership iff // arena_ is NULL. EntryType* NewEntry() const { if (arena_ == NULL) { return new EntryType(); } else { return Arena::CreateMessage<EntryType>(arena_); } } // Used in the implementation of serializing enum value type. Caller should // take the ownership iff arena_ is NULL. EntryType* NewEnumEntryWrapper(const Key& key, const T t) const { return EntryType::EnumWrap(key, t, arena_); } // Used in the implementation of serializing other value types. Caller should // take the ownership iff arena_ is NULL. EntryType* NewEntryWrapper(const Key& key, const T& t) const { return EntryType::Wrap(key, t, arena_); } private: typedef void DestructorSkippable_; Arena* arena_; Map<Key, T> map_; friend class ::google::protobuf::Arena; }; // True if IsInitialized() is true for value field in all elements of t. T is // expected to be message. It's useful to have this helper here to keep the // protobuf compiler from ever having to emit loops in IsInitialized() methods. // We want the C++ compiler to inline this or not as it sees fit. template <typename Key, typename T> bool AllAreInitialized(const Map<Key, T>& t) { for (typename Map<Key, T>::const_iterator it = t.begin(); it != t.end(); ++it) { if (!it->second.IsInitialized()) return false; } return true; } template <typename MEntry> struct MapEntryToMapField : MapEntryToMapField<typename MEntry::SuperType> {}; template <typename T, typename Key, typename Value, WireFormatLite::FieldType kKeyFieldType, WireFormatLite::FieldType kValueFieldType, int default_enum_value> struct MapEntryToMapField<MapEntryLite<T, Key, Value, kKeyFieldType, kValueFieldType, default_enum_value> > { typedef MapFieldLite<MapEntryLite<T, Key, Value, kKeyFieldType, kValueFieldType, default_enum_value>, Key, Value, kKeyFieldType, kValueFieldType, default_enum_value> MapFieldType; }; } // namespace internal } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_MAP_FIELD_LITE_H__
0
0.959485
1
0.959485
game-dev
MEDIA
0.184566
game-dev
0.967162
1
0.967162
magefree/mage
1,222
Mage.Sets/src/mage/cards/k/KinjallisDawnrunner.java
package mage.cards.k; import mage.MageInt; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.effects.keyword.ExploreSourceEffect; import mage.abilities.keyword.DoubleStrikeAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import java.util.UUID; /** * @author TheElk801 */ public final class KinjallisDawnrunner extends CardImpl { public KinjallisDawnrunner(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{W}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.SCOUT); this.power = new MageInt(1); this.toughness = new MageInt(1); // Double strike this.addAbility(DoubleStrikeAbility.getInstance()); // When Kinjalli's Dawnrunner enters the battlefield, it explores. this.addAbility(new EntersBattlefieldTriggeredAbility(new ExploreSourceEffect())); } private KinjallisDawnrunner(final KinjallisDawnrunner card) { super(card); } @Override public KinjallisDawnrunner copy() { return new KinjallisDawnrunner(this); } }
0
0.886083
1
0.886083
game-dev
MEDIA
0.885399
game-dev
0.989947
1
0.989947
thmxv/bevy_blendy_cameras
9,007
examples/basic.rs
//! A basic example showing all the functionalities use bevy::{ ecs::schedule::{LogLevel, ScheduleBuildSettings}, input::{ keyboard::{Key, KeyboardInput}, ButtonState, }, prelude::*, }; use bevy_blendy_cameras::{ BlendyCamerasPlugin, FlyCameraController, FrameEvent, OrbitCameraController, SwitchProjection, SwitchToFlyController, SwitchToOrbitController, Viewpoint, ViewpointEvent, }; // FIXME: Make fly mode work in ortho projection const GENERAL_HELP_TEXT: &str = "\ Press F to switch to Fly camera controler\n\ Press O to switch to Orbit camera controler\n\ Press Numpad 5 to switch between orthographic/perspective \ projections\n (In Orbit mode only, Fly mode only works in \ perspective)\n\ Press Home to frame the whole scene\n\ Press C to frame the cube\n\ Press Numpad 1 to view from the front\n\ Press Shift + Numpad 1 to view from the rear\n\ Press Numpad 3 to view from the right\n\ Press Shift + Numpad 1 to view from the left\n\ Press Numpad 7 to view from the top\n\ Press Shift + Numpad 7 to view from the bottom\n\ "; const ORBIT_HELP_TEXT: &str = "\ Press Middle Mouse button and drag to orbit camera\n\ Press Shift + Middle Mouse button and drag to pan camera\n\ Scoll the mouse wheel to zoom\n\ "; const FLY_HELP_TEXT: &str = "\ Press Middle Mouse button and drag to rotate camera\n\ Scoll the mouse wheel to change de camera mouvement speed\n\ Press W to pan down\n\ Press R to pan up\n\ Press E to zoom forward\n\ Press D to zoom backward\n\ Press S to pan left\n\ Press F to pan right\n\ "; #[derive(Resource)] struct Scene { pub camera_entity: Entity, pub scene_entity: Entity, pub cube_entity: Entity, } #[derive(Resource)] struct HelpText { pub help_text_entity: Entity, } fn main() { let mut app = App::new(); app.configure_schedules(ScheduleBuildSettings { ambiguity_detection: LogLevel::Warn, ..default() }); app.add_plugins(DefaultPlugins) .add_plugins(BlendyCamerasPlugin) .add_systems(Startup, setup_system) .add_systems( Update, ( switch_camera_controler_system, switch_camera_projection_system, switch_camera_viewpoint_system, frame_camera_system, ), ) .run(); } fn setup_system( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // Scene let mut cube_entity = Entity::PLACEHOLDER; let scene_entity = commands .spawn((Transform::default(), Visibility::default())) .with_children(|parent| { // Ground parent.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(5.0, 5.0))), MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))), )); // Cube cube_entity = parent .spawn(( Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))), MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))), Transform::from_xyz(0.0, 0.5, 0.0), )) .id(); }) .id(); // Light commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(4.0, 8.0, 4.0), )); // Camera let camera_entity = commands .spawn(( Camera3d::default(), Transform::from_translation(Vec3::new(0.0, 1.5, 5.0)), OrbitCameraController::default(), FlyCameraController { is_enabled: false, ..default() }, )) .id(); // Help text let help_text_entity = commands .spawn(( Text::new(format!("{GENERAL_HELP_TEXT}\n{ORBIT_HELP_TEXT}")), TextFont { font_size: 14.0, ..default() }, )) .id(); // Resources commands.insert_resource(Scene { camera_entity, scene_entity, cube_entity, }); commands.insert_resource(HelpText { help_text_entity }); } // FIXME: Use the same event with parameter to switch fn switch_camera_controler_system( mut commands: Commands, key_input: Res<ButtonInput<KeyCode>>, mut orbit_ev_writer: EventWriter<SwitchToOrbitController>, mut fly_ev_writer: EventWriter<SwitchToFlyController>, mut help_text: ResMut<HelpText>, scene: Res<Scene>, ) { if key_input.just_pressed(KeyCode::KeyF) { fly_ev_writer.write(SwitchToFlyController { camera_entity: scene.camera_entity, }); change_help_text( format!("{GENERAL_HELP_TEXT}\n{FLY_HELP_TEXT}"), &mut commands, &mut help_text, ); } if key_input.just_pressed(KeyCode::KeyO) { orbit_ev_writer.write(SwitchToOrbitController { camera_entity: scene.camera_entity, }); change_help_text( format!("{GENERAL_HELP_TEXT}\n{ORBIT_HELP_TEXT}"), &mut commands, &mut help_text, ); } } fn switch_camera_projection_system( key_input: Res<ButtonInput<KeyCode>>, mut ev_writer: EventWriter<SwitchProjection>, scene: Res<Scene>, ) { if key_input.just_pressed(KeyCode::Numpad5) { ev_writer.write(SwitchProjection { camera_entity: scene.camera_entity, }); } } fn switch_camera_viewpoint_system( key_input: Res<ButtonInput<KeyCode>>, mut ev_writer: EventWriter<ViewpointEvent>, scene: Res<Scene>, ) { if !key_input.pressed(KeyCode::ShiftLeft) && !key_input.pressed(KeyCode::ShiftRight) && key_input.pressed(KeyCode::Numpad1) { ev_writer.write(ViewpointEvent { camera_entity: scene.camera_entity, viewpoint: Viewpoint::Front, }); } if (key_input.pressed(KeyCode::ShiftLeft) || key_input.pressed(KeyCode::ShiftRight)) && key_input.pressed(KeyCode::Numpad1) { ev_writer.write(ViewpointEvent { camera_entity: scene.camera_entity, viewpoint: Viewpoint::Back, }); } if !key_input.pressed(KeyCode::ShiftLeft) && !key_input.pressed(KeyCode::ShiftRight) && key_input.pressed(KeyCode::Numpad3) { ev_writer.write(ViewpointEvent { camera_entity: scene.camera_entity, viewpoint: Viewpoint::Right, }); } if (key_input.pressed(KeyCode::ShiftLeft) || key_input.pressed(KeyCode::ShiftRight)) && key_input.pressed(KeyCode::Numpad3) { ev_writer.write(ViewpointEvent { camera_entity: scene.camera_entity, viewpoint: Viewpoint::Left, }); } if !key_input.pressed(KeyCode::ShiftLeft) && !key_input.pressed(KeyCode::ShiftRight) && key_input.pressed(KeyCode::Numpad7) { ev_writer.write(ViewpointEvent { camera_entity: scene.camera_entity, viewpoint: Viewpoint::Top, }); } if (key_input.pressed(KeyCode::ShiftLeft) || key_input.pressed(KeyCode::ShiftRight)) && key_input.pressed(KeyCode::Numpad7) { ev_writer.write(ViewpointEvent { camera_entity: scene.camera_entity, viewpoint: Viewpoint::Bottom, }); } } fn frame_camera_system( mut ev_reader: EventReader<KeyboardInput>, mut ev_writer: EventWriter<FrameEvent>, scene: Res<Scene>, ) { for ev in ev_reader.read() { if ev.state == ButtonState::Pressed { match &ev.logical_key { Key::Home => { ev_writer.write(FrameEvent { camera_entity: scene.camera_entity, entities_to_be_framed: vec![scene.scene_entity], include_children: true, }); } Key::Character(str) => { if str == "c" { ev_writer.write(FrameEvent { camera_entity: scene.camera_entity, entities_to_be_framed: vec![scene.cube_entity], include_children: false, }); } } _ => {} } } } } fn change_help_text( text: String, commands: &mut Commands, help_text: &mut HelpText, ) { commands.entity(help_text.help_text_entity).despawn(); let help_text_entity = commands .spawn(( Text::new(text), TextFont { font_size: 14.0, ..default() }, )) .id(); help_text.help_text_entity = help_text_entity; }
0
0.963048
1
0.963048
game-dev
MEDIA
0.847989
game-dev
0.921008
1
0.921008
gemrb/gemrb
79,106
gemrb/plugins/AREImporter/AREImporter.cpp
/* GemRB - Infinity Engine Emulator * Copyright (C) 2003 The GemRB Project * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * */ #include "AREImporter.h" #include "ie_cursors.h" #include "ie_stats.h" #include "strrefs.h" #include "ActorMgr.h" #include "AnimationFactory.h" #include "DataFileMgr.h" #include "DisplayMessage.h" #include "EffectMgr.h" #include "Game.h" #include "GameData.h" #include "ImageMgr.h" #include "Interface.h" #include "PluginMgr.h" #include "ProjectileServer.h" #include "RNG.h" #include "Audio/Ambient.h" #include "GameScript/GameScript.h" #include "Logging/Logging.h" #include "Plugins/TileMapMgr.h" #include "Scriptable/Container.h" #include "Scriptable/Door.h" #include "Scriptable/InfoPoint.h" #include "Scriptable/TileObject.h" #include "Streams/FileStream.h" #include "Streams/SlicedStream.h" #include <cstdlib> using namespace GemRB; #define DEF_OPEN 0 #define DEF_CLOSE 1 #define DEF_HOPEN 2 #define DEF_HCLOSE 3 //something non signed, non ascii #define UNINITIALIZED_BYTE 0x11 static std::vector<TrackingData> tracks; PluginHolder<DataFileMgr> INInote; static void ReadAutonoteINI() { INInote = MakePluginHolder<DataFileMgr>(IE_INI_CLASS_ID); path_t tINInote = PathJoin(core->config.GamePath, "autonote.ini"); FileStream* fs = FileStream::OpenFile(tINInote); INInote->Open(std::unique_ptr<DataStream> { fs }); } struct PathFinderCosts { PathMapFlags Passable[16] = { PathMapFlags::NO_SEE, PathMapFlags::PASSABLE, PathMapFlags::PASSABLE, PathMapFlags::PASSABLE, PathMapFlags::PASSABLE, PathMapFlags::PASSABLE, PathMapFlags::PASSABLE, PathMapFlags::PASSABLE, PathMapFlags::IMPASSABLE, PathMapFlags::PASSABLE, PathMapFlags::SIDEWALL, PathMapFlags::IMPASSABLE, PathMapFlags::IMPASSABLE, PathMapFlags::IMPASSABLE, PathMapFlags::PASSABLE | PathMapFlags::TRAVEL, PathMapFlags::PASSABLE }; int NormalCost = 10; int AdditionalCost = 4; static const PathFinderCosts& Get() { static PathFinderCosts pathfinder; return pathfinder; } private: PathFinderCosts() noexcept { AutoTable tm = gamedata->LoadTable("terrain"); if (!tm) { return; } const char* poi; for (int i = 0; i < 16; i++) { poi = tm->QueryField(0, i).c_str(); if (*poi != '*') Passable[i] = PathMapFlags(atoi(poi)); } poi = tm->QueryField(1, 0).c_str(); if (*poi != '*') NormalCost = atoi(poi); poi = tm->QueryField(1, 1).c_str(); if (*poi != '*') AdditionalCost = atoi(poi); } PathFinderCosts(const PathFinderCosts&) = delete; PathFinderCosts(PathFinderCosts&&) = delete; }; static int GetTrackString(const ResRef& areaName) { bool trackFlag = DisplayMessage::HasStringReference(HCStrings::Tracking); if (tracks.empty()) { AutoTable tm = gamedata->LoadTable("tracking", true); if (!tm) return -1; TableMgr::index_t trackcount = tm->GetRowCount(); tracks.resize(trackcount); for (TableMgr::index_t i = 0; i < trackcount; i++) { const char* poi = tm->QueryField(i, 0).c_str(); if (poi[0] == 'O' && poi[1] == '_') { tracks[i].enabled = false; poi += 2; } else { tracks[i].enabled = trackFlag; } tracks[i].text = ieStrRef(atoi(poi)); tracks[i].difficulty = tm->QueryFieldSigned<int>(i, 1); tracks[i].areaName = tm->GetRowName(i); } } for (int i = 0; i < int(tracks.size()); i++) { if (tracks[i].areaName == areaName) { return i; } } return -1; } static Holder<Sprite2D> LoadImageAs8bit(const ResRef& resref) { ResourceHolder<ImageMgr> im = gamedata->GetResourceHolder<ImageMgr>(resref); if (!im) { return nullptr; } auto spr = im->GetSprite2D(); if (spr->Format().Bpp > 1) { static const PixelFormat fmt = PixelFormat::Paletted8Bit(nullptr, false); spr->ConvertFormatTo(fmt); } assert(spr->Format().Bpp == 1); // convert format can fail (but never should here) return spr; } // override some diagonal-only transitions to save on pathfinding time static void OverrideMaterialMap(const ResRef& wedRef, Holder<Sprite2D> searchMap) { AutoTable smOverride = gamedata->LoadTable("smoverri", true); if (!smOverride) return; TableMgr::index_t areaCount = smOverride->GetRowCount(); for (TableMgr::index_t row = 0; row < areaCount; row++) { if (wedRef != smOverride->GetRowName(row)) continue; int x = smOverride->QueryFieldSigned<int>(row, 0); int y = smOverride->QueryFieldSigned<int>(row, 1); uint8_t material = smOverride->QueryFieldUnsigned<uint8_t>(row, 2); Point badPoint(x, y); auto it = searchMap->GetIterator(); auto end = PixelFormatIterator::end(it); while (it != end) { if (it.Position() == badPoint) { *it = material; break; } ++it; } } } static TileProps MakeTileProps(const TileMap* tm, const ResRef& wedref, bool day_or_night) { ResRef TmpResRef; if (day_or_night) { TmpResRef.Format("{:.6}LM", wedref); } else { TmpResRef.Format("{:.6}LN", wedref); } auto lightmap = LoadImageAs8bit(TmpResRef); if (!lightmap) { throw std::runtime_error("No lightmap available."); } TmpResRef.Format("{:.6}SR", wedref); auto searchmap = LoadImageAs8bit(TmpResRef); if (!searchmap) { throw std::runtime_error("No searchmap available."); } OverrideMaterialMap(wedref, searchmap); TmpResRef.Format("{:.6}HT", wedref); auto heightmap = LoadImageAs8bit(TmpResRef); if (!heightmap) { throw std::runtime_error("No heightmap available."); } const Size propsize(tm->XCellCount * 4, CeilDiv(tm->YCellCount * 64, 12)); PixelFormat fmt = TileProps::pixelFormat; fmt.palette = lightmap->GetPalette(); auto propImg = VideoDriver->CreateSprite(Region(Point(), propsize), nullptr, fmt); auto propit = propImg->GetIterator(); auto end = Sprite2D::Iterator::end(propit); auto hmpal = heightmap->GetPalette(); auto smit = searchmap->GetIterator(); auto hmit = heightmap->GetIterator(); auto lmit = lightmap->GetIterator(); // Sadly, the original data is occasionally cropped poorly and some images are a few pixels smaller than they ought to be // an example of this is BG2 AR0325 // therefore, we must have some out-of-bounds defaults and only advance iterators when they are inside propsize for (; propit != end; ++propit) { const Point& pos = propit.Position(); uint8_t r = TileProps::defaultSearchMap; uint8_t g = TileProps::defaultMaterial; uint8_t b = TileProps::defaultElevation; uint8_t a = TileProps::defaultLighting; if (smit.clip.PointInside(pos)) { uint8_t smval = *smit; // r + g assert((smval & 0xf0) == 0); r = uint8_t(PathFinderCosts::Get().Passable[smval]); g = smval; ++smit; } if (hmit.clip.PointInside(pos)) { b = hmpal->GetColorAt(*hmit).r; // pick any channel, they are all the same ++hmit; } if (lmit.clip.PointInside(pos)) { a = *lmit; ++lmit; } propit.WriteRGBA(r, g, b, a); } return TileProps(std::move(propImg)); } bool AREImporter::Import(DataStream* str) { char Signature[8]; str->Read(Signature, 8); if (strncmp(Signature, "AREAV1.0", 8) != 0) { if (strncmp(Signature, "AREAV9.1", 8) != 0) { return false; } else { bigheader = 16; } } else { bigheader = 0; } str->ReadResRef(WEDResRef); str->ReadDword(LastSave); str->ReadDword(AreaFlags); //skipping bg1 area connection fields str->Seek(0x48, GEM_STREAM_START); str->ReadEnum<MapEnv>(AreaType); str->ReadWord(WRain); str->ReadWord(WSnow); str->ReadWord(WFog); str->ReadWord(WLightning); // unused wind speed, TODO: EEs use it for transparency // a single byte was re-purposed to control the alpha on the stencil water for more or less transparency. // If you set it to 0, then the water should be appropriately 50% transparent. // If you set it to any other number, it will be that transparent. // It's 1 byte, so setting it to 128 you'll have the same as the default of 0 str->ReadWord(WUnknown); AreaDifficulty = 0; if (bigheader) { // are9.1 difficulty bits for level2/level3 // ar4000 for example has a bunch of actors for all area difficulty levels, so these here are likely just the allowed levels AreaDifficulty = 1; ieByte tmp = 0; int avgPartyLevel = core->GetGame()->GetTotalPartyLevel(false) / core->GetGame()->GetPartySize(false); str->Read(&tmp, 1); // 0x54 if (tmp && avgPartyLevel >= tmp) { AreaDifficulty = 2; } tmp = 0; str->Read(&tmp, 1); // 0x55 if (tmp && avgPartyLevel >= tmp) { AreaDifficulty = 4; } // 0x56 held the average party level at load time (usually 1, since it had no access yet), // but we resolve everything here and store AreaDifficulty instead } //bigheader gap is here str->Seek(0x54 + bigheader, GEM_STREAM_START); str->ReadDword(ActorOffset); str->ReadWord(ActorCount); str->ReadWord(InfoPointsCount); str->ReadDword(InfoPointsOffset); str->ReadDword(SpawnOffset); str->ReadDword(SpawnCount); str->ReadDword(EntrancesOffset); str->ReadDword(EntrancesCount); str->ReadDword(ContainersOffset); str->ReadWord(ContainersCount); str->ReadWord(ItemsCount); str->ReadDword(ItemsOffset); str->ReadDword(VerticesOffset); str->ReadWord(VerticesCount); str->ReadWord(AmbiCount); str->ReadDword(AmbiOffset); str->ReadDword(VariablesOffset); str->ReadDword(VariablesCount); ieDword tmp; // unused TiledObjectFlagCount and TiledObjectFlagOffset str->ReadDword(tmp); str->ReadResRef(Script); str->ReadDword(ExploredBitmapSize); str->ReadDword(ExploredBitmapOffset); str->ReadDword(DoorsCount); str->ReadDword(DoorsOffset); str->ReadDword(AnimCount); str->ReadDword(AnimOffset); str->ReadDword(TileCount); str->ReadDword(TileOffset); str->ReadDword(SongHeader); str->ReadDword(RestHeader); if (core->HasFeature(GFFlags::AUTOMAP_INI)) { str->ReadDword(tmp); //skipping unknown in PST } str->ReadDword(NoteOffset); str->ReadDword(NoteCount); str->ReadDword(TrapOffset); str->ReadDword(TrapCount); str->ReadResRef(Dream1); str->ReadResRef(Dream2); // 56 bytes of reserved space return true; } //alter a map to the night/day version in case of an extended night map (bg2 specific) //return true, if change happened, in which case a movie is played by the Game object bool AREImporter::ChangeMap(Map* map, bool day_or_night) { ResRef TmpResRef; //get the right tilemap name if (day_or_night) { TmpResRef = map->WEDResRef; } else { TmpResRef.Format("{:.7}N", map->WEDResRef); } PluginHolder<TileMapMgr> tmm = MakePluginHolder<TileMapMgr>(IE_WED_CLASS_ID); DataStream* wedfile = gamedata->GetResourceStream(TmpResRef, IE_WED_CLASS_ID); tmm->Open(wedfile); tmm->SetExtendedNight(!day_or_night); //alter the tilemap object, not all parts of that object are coming from the wed/tis //this is why we have to be careful //TODO: consider refactoring TileMap so invariable data coming from the .ARE file //are not handled by it, then TileMap could be simply swapped TileMap* tm = map->GetTileMap(); if (tm) { tm->ClearOverlays(); } tm = tmm->GetTileMap(tm); if (!tm) { Log(ERROR, "AREImporter", "No tile map available."); return false; } try { TileProps props = MakeTileProps(tm, map->WEDResRef, day_or_night); // Small map for MapControl ResourceHolder<ImageMgr> sm = gamedata->GetResourceHolder<ImageMgr>(TmpResRef); if (sm) { // night small map is *optional*! // keep the existing map if this one is null map->SmallMap = sm->GetSprite2D(); } //the map state was altered, no need to hold this off for any later map->DayNight = day_or_night; tm->UpdateDoors(); map->SetTileMapProps(std::move(props)); } catch (const std::exception& e) { Log(ERROR, "AREImporter", "{}", e); return false; } // update the tiles and tilecount (eg. door0304 in Edwin's Docks (ar0300) entrance for (const auto& door : tm->GetDoors()) { bool baseClosed, oldOpen = door->IsOpen(); door->SetTiles(tmm->GetDoorIndices(door->ID, baseClosed)); // reset open state to the one in the old wed door->SetDoorOpen(oldOpen, false, 0); } return true; } // everything is the same up to DOOR_FOUND, but then it gets messy (see Door.h) static const ieDword gemrbDoorFlags[6] = { DOOR_TRANSPARENT, DOOR_KEY, DOOR_SLIDE, DOOR_USEUPKEY, DOOR_LOCKEDINFOTEXT, DOOR_WARNINGINFOTEXT }; // the last two are 0, since they are outside the original bit range, so all the constants can coexist static const ieDword iwd2DoorFlags[6] = { DOOR_LOCKEDINFOTEXT, DOOR_TRANSPARENT, DOOR_WARNINGINFOTEXT, DOOR_KEY, 0, 0 }; inline ieDword FixIWD2DoorFlags(ieDword Flags, bool reverse) { ieDword bit, otherbit, maskOff = 0, maskOn = 0; for (int i = 0; i < 6; i++) { if (!reverse) { bit = gemrbDoorFlags[i]; otherbit = iwd2DoorFlags[i]; } else { bit = iwd2DoorFlags[i]; otherbit = gemrbDoorFlags[i]; } if (Flags & bit) { maskOff |= bit; maskOn |= otherbit; } } // delayed bad bit removal due to chain overlapping return (Flags & ~maskOff) | maskOn; } Ambient* AREImporter::SetupMainAmbients(const Map::MainAmbients& mainAmbients) { ResRef mainAmbient; if (!mainAmbients.Ambient1.IsEmpty()) { mainAmbient = mainAmbients.Ambient1; } // the second ambient is always longer, was meant as a memory optimisation w/ IE_AMBI_HIMEM // however that was implemented only for the normal ambients // nowadays we can just skip the first if (!mainAmbients.Ambient2.IsEmpty()) { mainAmbient = mainAmbients.Ambient2; } if (mainAmbient.IsEmpty()) return nullptr; Ambient* ambi = new Ambient(); ambi->flags = IE_AMBI_ENABLED | IE_AMBI_LOOPING | IE_AMBI_MAIN | IE_AMBI_NOSAVE; ambi->gain = static_cast<ieWord>(mainAmbients.AmbientVol); // sounds and name ambi->sounds.emplace_back(mainAmbient); ambi->name = mainAmbient; ambi->appearance = (1 << 25) - 1; // default to all 24 bits enabled, one per hour ambi->radius = 50; // REFERENCE_DISTANCE return ambi; } void AREImporter::GetSongs(DataStream* str, Map* map, std::vector<Ambient*>& ambients) const { // 5 is the number of song indices for (auto& list : map->SongList) { str->ReadDword(list); } Map::MainAmbients& dayAmbients = map->dayAmbients; str->ReadResRef(dayAmbients.Ambient1); str->ReadResRef(dayAmbients.Ambient2); str->ReadDword(dayAmbients.AmbientVol); Map::MainAmbients& nightAmbients = map->nightAmbients; str->ReadResRef(nightAmbients.Ambient1); str->ReadResRef(nightAmbients.Ambient2); str->ReadDword(nightAmbients.AmbientVol); // check for existence of main ambients (bg1) constexpr int dayBits = ((1 << 18) - 1) ^ ((1 << 6) - 1); // day: bits 6-18 per DLTCEP Ambient* ambi = SetupMainAmbients(dayAmbients); if (!ambi) return; // schedule for day/night // if the two ambients are the same, just add one, so there's no restart if (dayAmbients.Ambient2 != nightAmbients.Ambient2) { ambi->appearance = dayBits; ambients.push_back(ambi); // night ambi = SetupMainAmbients(nightAmbients); if (ambi) { ambi->appearance ^= dayBits; // night: bits 0-5 + 19-23, [dusk till dawn] } } // bgt ar7300 has a night ambient only in the first slot if (ambi) { ambients.push_back(ambi); } } void AREImporter::GetRestHeader(DataStream* str, Map* map) const { for (auto& ref : map->RestHeader.Strref) { str->ReadStrRef(ref); } for (auto& ref : map->RestHeader.CreResRef) { str->ReadResRef(ref); } str->ReadWord(map->RestHeader.CreatureNum); if (map->RestHeader.CreatureNum > MAX_RESCOUNT) { map->RestHeader.CreatureNum = MAX_RESCOUNT; } str->ReadWord(map->RestHeader.Difficulty); // difficulty? str->ReadDword(map->RestHeader.Duration); str->ReadWord(map->RestHeader.RandomWalkDistance); str->ReadWord(map->RestHeader.FollowDistance); str->ReadWord(map->RestHeader.Maximum); // maximum number of creatures str->ReadWord(map->RestHeader.Enabled); str->ReadWord(map->RestHeader.DayChance); str->ReadWord(map->RestHeader.NightChance); // 14 reserved dwords } void AREImporter::GetInfoPoint(DataStream* str, int idx, Map* map) const { str->Seek(InfoPointsOffset + idx * 0xC4, GEM_STREAM_START); ieWord ipType; ieWord vertexCount; ieDword firstVertex; ieDword cursor; ieDword ipFlags; ieWord trapDetDiff; ieWord trapRemDiff; ieWord trapped; ieWord trapDetected; Point launchP; Point pos; Point talkPos; Region bbox; ieVariable ipName; ieVariable entrance; ResRef script0; ResRef keyResRef; ResRef destination; // two adopted pst specific fields ResRef dialogResRef; ResRef wavResRef; ieStrRef dialogName; str->ReadVariable(ipName); str->ReadWord(ipType); str->ReadRegion(bbox, true); str->ReadWord(vertexCount); str->ReadDword(firstVertex); ieDword triggerValue; str->ReadDword(triggerValue); // named triggerValue in the IE source str->ReadDword(cursor); str->ReadResRef(destination); str->ReadVariable(entrance); str->ReadDword(ipFlags); ieStrRef overheadRef; str->ReadStrRef(overheadRef); str->ReadWord(trapDetDiff); str->ReadWord(trapRemDiff); str->ReadWord(trapped); str->ReadWord(trapDetected); str->ReadPoint(launchP); str->ReadResRef(keyResRef); str->ReadResRef(script0); // ARE 9.1: 4B per position after that. if (16 == map->version) { str->ReadPoint(pos); // OverridePoint in NI if (pos.IsZero()) { str->ReadScalar(pos.x); // AlternatePoint in NI str->ReadScalar(pos.y); } else { str->Seek(8, GEM_CURRENT_POS); } str->Seek(26, GEM_CURRENT_POS); } else { str->ReadPoint(pos); // TransitionWalkToX, TransitionWalkToY // maybe we have to store this // bg2: 15 reserved dwords, the above point is actually in dwords (+1), // but since it's the last thing the underseek doesn't matter str->Seek(36, GEM_CURRENT_POS); } if (core->HasFeature(GFFlags::INFOPOINT_DIALOGS)) { str->ReadResRef(wavResRef); str->ReadPoint(talkPos); str->ReadStrRef(dialogName); str->ReadResRef(dialogResRef); } else { wavResRef.Reset(); dialogName = ieStrRef::INVALID; dialogResRef.Reset(); } InfoPoint* ip = nullptr; str->Seek(VerticesOffset + firstVertex * 4, GEM_STREAM_START); if (vertexCount <= 1) { // this is exactly the same as bbox.origin if (vertexCount == 1) { Point pos2; str->ReadPoint(pos2); assert(pos2 == bbox.origin); } if (bbox.size.IsInvalid()) { // we approximate a bounding box equivalent to a small radius // we copied this from the Container code that seems to indicate // this is how the originals behave. It is probably "good enough" bbox.x = pos.x - 7; bbox.y = pos.y - 5; bbox.w = 16; bbox.h = 12; } ip = map->TMap->AddInfoPoint(ipName, ipType, nullptr); ip->BBox = bbox; } else if (vertexCount == 2) { #define MSG "Encountered a bogus polygon with 2 vertices!" #if NDEBUG Log(ERROR, "AREImporter", MSG); return; #else // make this fatal on debug builds error("AREImporter", MSG); #endif #undef MSG } else { std::vector<Point> points(vertexCount); for (int x = 0; x < vertexCount; x++) { str->ReadPoint(points[x]); } // recalculate the bbox if it was not provided auto poly = std::make_shared<Gem_Polygon>(std::move(points), bbox.size.IsInvalid() ? nullptr : &bbox); bbox = poly->BBox; ip = map->TMap->AddInfoPoint(ipName, ipType, poly); } ip->TrapDetectionDiff = trapDetDiff; ip->TrapRemovalDiff = trapRemDiff; ip->Trapped = trapped; ip->TrapDetected = trapDetected; ip->TrapLaunch = launchP; // translate door cursor on infopoint to correct cursor if (cursor == IE_CURSOR_DOOR) cursor = IE_CURSOR_PASS; ip->Cursor = cursor; ip->overHead.SetText(core->GetString(overheadRef), false); ip->StrRef = overheadRef; //we need this when saving area ip->SetMap(map); ip->Flags = ipFlags; ip->UsePoint = pos; // FIXME: PST doesn't use this field if (ip->GetUsePoint()) { ip->SetPos(ip->UsePoint); } else { ip->SetPos(bbox.Center()); } ip->Destination = destination; ip->EntranceName = entrance; ip->KeyResRef = keyResRef; // these appear only in PST, but we could support them everywhere // HOWEVER they did not use them as witnessed in ar0101 (0101prt1 and 0101prt2) :( if (core->HasFeature(GFFlags::PST_STATE_FLAGS)) { talkPos = ip->Pos; } ip->TalkPos = talkPos; ip->DialogName = dialogName; // PST has garbage here and there if (dialogResRef.IsASCII()) { ip->SetDialog(dialogResRef); } if (wavResRef.IsASCII()) { ip->SetEnter(wavResRef); } if (script0.IsEmpty()) { ip->Scripts[0] = nullptr; } else { ip->Scripts[0] = new GameScript(script0, ip); } if (ip->Type != ST_TRAVEL || !ip->outline) return; // mark the searchmap under travel regions as passable (not travel) for (int i = 0; i < ip->BBox.w; i += 8) { for (int j = 0; j < ip->BBox.h; j += 6) { NavmapPoint sample(ip->BBox.x + i, ip->BBox.y + j); if (!ip->outline->PointIn(sample)) continue; SearchmapPoint below { sample }; PathMapFlags tmp = map->tileProps.QuerySearchMap(below); map->tileProps.PaintSearchMap(below, tmp | PathMapFlags::PASSABLE); } } } void AREImporter::GetContainer(DataStream* str, int idx, Map* map) { str->Seek(ContainersOffset + idx * 0xC0, GEM_STREAM_START); ieVariable containerName; ieWord containerType; ieWord lockDiff; ieWord trapDetDiff; ieWord trapRemDiff; ieWord trapped; ieWord trapDetected; ieWord vertCount; ieWord unknown; Point pos; Point launchPos; Region bbox; ieDword containerFlags; ieDword itemIndex; ieDword itemCount; ieDword firstIndex; ResRef keyResRef; ieStrRef openFail; str->ReadVariable(containerName); str->ReadPoint(pos); str->ReadWord(containerType); str->ReadWord(lockDiff); str->ReadDword(containerFlags); str->ReadWord(trapDetDiff); str->ReadWord(trapRemDiff); str->ReadWord(trapped); str->ReadWord(trapDetected); str->ReadPoint(launchPos); str->ReadRegion(bbox, true); str->ReadDword(itemIndex); str->ReadDword(itemCount); str->ReadResRef(Script); str->ReadDword(firstIndex); // the vertex count is only 16 bits, there is a weird flag // after it, which is usually 0, but sometimes set to 1 str->ReadWord(vertCount); str->ReadWord(unknown); // trigger range //str->Read(Name, 32); // owner's scriptname str->Seek(32, GEM_CURRENT_POS); str->ReadResRef(keyResRef); str->Seek(4, GEM_CURRENT_POS); // break difficulty str->ReadStrRef(openFail); // 14 reserved dwords str->Seek(VerticesOffset + firstIndex * 4, GEM_STREAM_START); Container* c = nullptr; if (vertCount == 0) { // piles have no polygons and no bounding box in some areas, // but bg2 gives them this bounding box at first load, // should we specifically check for Type == IE_CONTAINER_PILE? if (bbox.size.IsInvalid()) { bbox.x = pos.x - 7; bbox.y = pos.y - 5; bbox.w = 16; bbox.h = 12; } c = map->AddContainer(containerName, containerType, nullptr); c->BBox = bbox; } else { std::vector<Point> points(vertCount); for (int x = 0; x < vertCount; x++) { str->ReadPoint(points[x]); } auto poly = std::make_shared<Gem_Polygon>(std::move(points), &bbox); c = map->AddContainer(containerName, containerType, poly); } c->SetPos(pos); c->LockDifficulty = lockDiff; c->Flags = containerFlags; c->TrapDetectionDiff = trapDetDiff; c->TrapRemovalDiff = trapRemDiff; c->Trapped = trapped; c->TrapDetected = trapDetected; c->TrapLaunch = launchPos; // reading items into a container str->Seek(ItemsOffset + itemIndex * 0x14, GEM_STREAM_START); while (itemCount--) { // cannot add directly to inventory (ground piles) c->AddItem(core->ReadItem(str)); } if (containerType == IE_CONTAINER_PILE) Script.Reset(); if (Script.IsEmpty()) { c->Scripts[0] = nullptr; } else { c->Scripts[0] = new GameScript(Script, c); } c->KeyResRef = keyResRef; if (!openFail) openFail = ieStrRef(-1); // rewrite 0 to -1 c->OpenFail = openFail; } void AREImporter::GetDoor(DataStream* str, int idx, Map* map, PluginHolder<TileMapMgr> tmm) const { str->Seek(DoorsOffset + idx * 0xC8, GEM_STREAM_START); ieDword doorFlags; ieDword openFirstVertex; ieDword closedFirstVertex; ieDword openFirstImpeded; ieDword closedFirstImpeded; ieDword cursor; ieDword discoveryDiff; ieDword lockRemoval; ieVariable longName; ieVariable linkedInfo; ResRef shortName; ResRef openResRef; ResRef closeResRef; ResRef keyResRef; ResRef script0; ResRef dialog; ieWord openVerticesCount; ieWord closedVerticesCount; ieWord openImpededCount; ieWord closedImpededCount; ieWord trapDetect; ieWord trapRemoval; ieWord trapped; ieWord trapDetected; ieWord hp; ieWord ac; Point launchP; Point toOpen[2]; Region closedBBox; Region openedBBox; ieStrRef openStrRef; ieStrRef nameStrRef; str->ReadVariable(longName); str->ReadResRef(shortName); str->ReadDword(doorFlags); if (map->version == 16) { doorFlags = FixIWD2DoorFlags(doorFlags, false); } if (AreaType & AT_OUTDOOR) doorFlags |= DOOR_TRANSPARENT; // actually true only for fog-of-war, excluding other actors str->ReadDword(openFirstVertex); str->ReadWord(openVerticesCount); str->ReadWord(closedVerticesCount); str->ReadDword(closedFirstVertex); str->ReadRegion(openedBBox, true); str->ReadRegion(closedBBox, true); str->ReadDword(openFirstImpeded); str->ReadWord(openImpededCount); str->ReadWord(closedImpededCount); str->ReadDword(closedFirstImpeded); str->ReadWord(hp); // hitpoints str->ReadWord(ac); // AND armorclass, according to IE dev info str->ReadResRef(openResRef); str->ReadResRef(closeResRef); str->ReadDword(cursor); str->ReadWord(trapDetect); str->ReadWord(trapRemoval); str->ReadWord(trapped); str->ReadWord(trapDetected); str->ReadPoint(launchP); str->ReadResRef(keyResRef); str->ReadResRef(script0); str->ReadDword(discoveryDiff); str->ReadDword(lockRemoval); str->ReadPoint(toOpen[0]); str->ReadPoint(toOpen[1]); str->ReadStrRef(openStrRef); if (core->HasFeature(GFFlags::AUTOMAP_INI) || map->version == 16) { // true in all games? IESDP has 24 bits for v1 too char tmp[25]; str->Read(tmp, 24); tmp[24] = 0; linkedInfo = tmp; // linkedInfo unused in pst anyway? } else { str->ReadVariable(linkedInfo); } str->ReadStrRef(nameStrRef); // trigger name str->ReadResRef(dialog); if (core->HasFeature(GFFlags::AUTOMAP_INI)) { // maybe this is important? but seems not str->Seek(8, GEM_CURRENT_POS); } // Reading Open Polygon std::shared_ptr<Gem_Polygon> open = nullptr; str->Seek(VerticesOffset + openFirstVertex * 4, GEM_STREAM_START); if (openVerticesCount) { std::vector<Point> points(openVerticesCount); for (int x = 0; x < openVerticesCount; x++) { str->ReadPoint(points[x]); } open = std::make_shared<Gem_Polygon>(std::move(points), &openedBBox); } // Reading Closed Polygon std::shared_ptr<Gem_Polygon> closed = nullptr; str->Seek(VerticesOffset + closedFirstVertex * 4, GEM_STREAM_START); if (closedVerticesCount) { std::vector<Point> points(closedVerticesCount); for (int x = 0; x < closedVerticesCount; x++) { str->ReadPoint(points[x]); } closed = std::make_shared<Gem_Polygon>(std::move(points), &closedBBox); } // Getting Door Information from the WED File bool baseClosed; auto indices = tmm->GetDoorIndices(shortName, baseClosed); if (core->HasFeature(GFFlags::REVERSE_DOOR)) { baseClosed = !baseClosed; } // iwd2 workaround: two ar6051 doors, acting as switches have detectable traps in the original, yet are missing the bit // looking at the original, it checks it, no script sets it on them, it's just bonkers // they are marked as detected already in the data, but don't appear as such if (longName == "AR6051_Lava_Switch" || longName == "AR6051_Acid_Switch") { doorFlags |= DOOR_DETECTABLE; trapDetect = 30; trapDetected = 0; } auto closedPolys = tmm->ClosedDoorPolygons(); auto openPolys = tmm->OpenDoorPolygons(); DoorTrigger dt(std::move(open), std::move(openPolys), std::move(closed), std::move(closedPolys)); Door* door = map->TMap->AddDoor(shortName, longName, doorFlags, baseClosed, std::move(indices), std::move(dt)); door->OpenBBox = openedBBox; door->ClosedBBox = closedBBox; // Reading Open Impeded blocks str->Seek(VerticesOffset + openFirstImpeded * 4, GEM_STREAM_START); door->open_ib.resize(openImpededCount); for (SearchmapPoint& point : door->open_ib) { str->ReadPoint(point); } // Reading Closed Impeded blocks str->Seek(VerticesOffset + closedFirstImpeded * 4, GEM_STREAM_START); door->closed_ib.resize(closedImpededCount); for (SearchmapPoint& point : door->closed_ib) { str->ReadPoint(point); } door->SetMap(map); door->hp = hp; door->ac = ac; door->TrapDetectionDiff = trapDetect; door->TrapRemovalDiff = trapRemoval; door->Trapped = trapped; door->TrapDetected = trapDetected; door->TrapLaunch = launchP; door->Cursor = cursor; door->KeyResRef = keyResRef; if (script0.IsEmpty()) { door->Scripts[0] = nullptr; } else { door->Scripts[0] = new GameScript(script0, door); } door->toOpen[0] = toOpen[0]; door->toOpen[1] = toOpen[1]; // Leave the default sound untouched if (!openResRef.IsEmpty()) { door->OpenSound = openResRef; } else if (doorFlags & DOOR_SECRET) { door->OpenSound = gamedata->defaultSounds[DEF_HOPEN]; } else { door->OpenSound = gamedata->defaultSounds[DEF_OPEN]; } if (!closeResRef.IsEmpty()) { door->CloseSound = closeResRef; } else if (doorFlags & DOOR_SECRET) { door->CloseSound = gamedata->defaultSounds[DEF_HCLOSE]; } else { door->CloseSound = gamedata->defaultSounds[DEF_CLOSE]; } if (!openStrRef) openStrRef = ieStrRef(-1); // rewrite 0 to -1 door->LockedStrRef = openStrRef; door->DiscoveryDiff = discoveryDiff; door->LockDifficulty = lockRemoval; door->LinkedInfo = MakeVariable(linkedInfo); // these 2 fields are not sure door->NameStrRef = nameStrRef; door->SetDialog(dialog); } void AREImporter::GetSpawnPoint(DataStream* str, int idx, Map* map) const { str->Seek(SpawnOffset + idx * 0xC8, GEM_STREAM_START); ieVariable spName; Point pos; ieWord spawningFrequency; ieWord creatureCount; std::vector<ResRef> creatures(MAX_RESCOUNT); str->ReadVariable(spName); str->ReadPoint(pos); for (auto& creature : creatures) { str->ReadResRef(creature); } str->ReadWord(creatureCount); assert(creatureCount <= MAX_RESCOUNT); creatures.resize(creatureCount); Spawn* sp = map->AddSpawn(spName, pos, std::move(creatures)); str->ReadWord(sp->Difficulty); str->ReadWord(spawningFrequency); // this value is used in a division, better make it nonzero now // this will fix any old gemrb saves vs. the original engine if (!spawningFrequency) { spawningFrequency = 1; } sp->Frequency = spawningFrequency; str->ReadWord(sp->Method); if (sp->Method & SPF_BGT) { sp->Difficulty /= 100; } str->ReadDword(sp->sduration); // time to live for spawns str->ReadWord(sp->rwdist); // random walk distance (0 is unlimited), hunting range str->ReadWord(sp->owdist); // other walk distance (inactive in all engines?), follow range str->ReadWord(sp->Maximum); str->ReadWord(sp->Enabled); str->ReadDword(sp->appearance); str->ReadWord(sp->DayChance); str->ReadWord(sp->NightChance); // 14 reserved dwords // TODO: ee added several more fields; check if they're actually used first } bool AREImporter::GetActor(DataStream* str, PluginHolder<ActorMgr> actorMgr, Map* map) const { static int pst = core->HasFeature(GFFlags::AUTOMAP_INI); ieVariable defaultName; ResRef creResRef; ResRef dialog; ResRef scripts[8]; // the original order is shown in scrlev.ids ieDword talkCount; ieDword orientation; ieDword schedule; ieDword removalTime; ieDword flags; ieDword creOffset; ieDword creSize; Point pos; Point destination; ieWord maxDistance; ieWord spawned; ieByte difficultyMargin; DataStream* creFile; str->ReadVariable(defaultName); str->ReadPoint(pos); str->ReadPoint(destination); str->ReadDword(flags); str->ReadWord(spawned); // "type" str->Seek(1, GEM_CURRENT_POS); // one letter of a ResRef, changed to * at runtime, purpose unknown (portraits?), but not needed either str->Read(&difficultyMargin, 1); // iwd2 only, "alignbyte" in bg2 (padding) str->Seek(4, GEM_CURRENT_POS); //actor animation, unused str->ReadDword(orientation); // was word + padding in bg2 str->ReadDword(removalTime); str->ReadWord(maxDistance); // hunting range str->Seek(2, GEM_CURRENT_POS); // apparently unused https://gibberlings3.net/forums/topic/21724-a (follow range) str->ReadDword(schedule); str->ReadDword(talkCount); str->ReadResRef(dialog); str->ReadResRef(scripts[SCR_OVERRIDE]); str->ReadResRef(scripts[SCR_GENERAL]); str->ReadResRef(scripts[SCR_CLASS]); str->ReadResRef(scripts[SCR_RACE]); str->ReadResRef(scripts[SCR_DEFAULT]); str->ReadResRef(scripts[SCR_SPECIFICS]); str->ReadResRef(creResRef); str->ReadDword(creOffset); str->ReadDword(creSize); // another iwd2 script slot str->ReadResRef(scripts[SCR_AREA]); str->Seek(120, GEM_CURRENT_POS); // not iwd2, this field is garbage if (!core->HasFeature(GFFlags::IWD2_SCRIPTNAME)) { scripts[SCR_AREA].Reset(); } // actually, Flags&1 signs that the creature // is not loaded yet, so !(Flags&1) means it is embedded if (creOffset != 0 && !(flags & AF_CRE_NOT_LOADED)) { creFile = SliceStream(str, creOffset, creSize, true); } else { creFile = gamedata->GetResourceStream(creResRef, IE_CRE_CLASS_ID); } if (!actorMgr->Open(creFile)) { Log(ERROR, "AREImporter", "Couldn't read actor: {}!", creResRef); return false; } Actor* act = actorMgr->GetActor(0); if (!act) return false; // PST generally doesn't appear to use the starting MC_ bits, but for some reason // there's a coaxmetal copy in the mortuary with both KEEP and REMOVE corpse // set that should never be seen. The actor is also already dead, so we don't end // up doing any of the regular cleanup on it (it's mrtghost.cre). Banish it instead. if (pst && act->GetBase(IE_STATE_ID) & STATE_DEAD && act->GetBase(IE_MC_FLAGS) & MC_REMOVE_CORPSE) { return false; } map->AddActor(act, false); act->SetPos(pos); act->Destination = destination; act->HomeLocation = destination; act->maxWalkDistance = maxDistance; act->Spawned = spawned; act->appearance = schedule; // copying the scripting name into the actor // if the CreatureAreaFlag was set to 8 // AF_NAME_OVERRIDE == AF_ENABLED, used for something else in IWD2 if ((flags & AF_NAME_OVERRIDE) || core->HasFeature(GFFlags::IWD2_SCRIPTNAME)) { act->SetScriptName(defaultName); } // IWD2 specific hacks if (core->HasFeature(GFFlags::RULES_3ED)) { if (flags & AF_SEEN_PARTY) { act->SetMCFlag(MC_SEENPARTY, BitOp::OR); } if (flags & AF_INVULNERABLE) { act->SetMCFlag(MC_INVULNERABLE, BitOp::OR); } if (flags & AF_ENABLED) { act->BaseStats[IE_EA] = EA_EVILCUTOFF; act->SetMCFlag(MC_ENABLED, BitOp::OR); } else { // DifficultyMargin - only enable actors that are difficult enough vs the area difficulty // 1 - area difficulty 1 // 2 - area difficulty 2 // 4 - area difficulty 3 if (difficultyMargin && !(difficultyMargin & map->AreaDifficulty)) { act->DestroySelf(); } } // temporary hack while ar6104 causes pathfinding problems if (act->GetScriptName() == "Troll_11" && map->GetScriptName() == "ar6104") { act->DestroySelf(); } } act->ignoredFields.difficultyMargin = difficultyMargin; act->SetDialog(dialog); for (int j = 0; j < 8; j++) { if (!scripts[j].IsEmpty()) { act->SetScript(scripts[j], j); } } act->SetOrientation(ClampToOrientation(orientation), false); act->TalkCount = talkCount; act->Timers.removalTime = removalTime; act->RefreshEffects(); return true; } void AREImporter::GetAreaAnimation(DataStream* str, Map* map) const { AreaAnimation anim = AreaAnimation(); str->ReadVariable(anim.Name); str->ReadPoint(anim.Pos); str->ReadDword(anim.appearance); str->ReadResRef(anim.BAM); str->ReadWord(anim.sequence); str->ReadWord(anim.frame); str->ReadEnum(anim.flags); anim.originalFlags = anim.flags; str->ReadScalar(anim.height); if (core->HasFeature(GFFlags::IMPLICIT_AREAANIM_BACKGROUND)) { anim.height = ANI_PRI_BACKGROUND; anim.flags |= AreaAnimation::Flags::NoWall; } str->ReadWord(anim.transparency); ieWord startFrameRange; str->ReadWord(startFrameRange); str->Read(&anim.startchance, 1); if (anim.startchance <= 0) { anim.startchance = 100; // percentage of starting a cycle } if (startFrameRange && bool(anim.flags & AreaAnimation::Flags::RandStart)) { anim.frame = RAND<AreaAnimation::index_t>(0, startFrameRange - 1); } anim.startFrameRange = 0; // this will never get resaved (iirc) str->Read(&anim.skipcycle, 1); // how many cycles are skipped (100% skippage), "period" in bg2 str->ReadResRef(anim.PaletteRef); // TODO: EE: word with anim width for PVRZ/WBM resources (if flag bits are set, see A_ANI_ defines) // 0x4a holds the height str->ReadDword(anim.unknown48); static int pst = core->HasFeature(GFFlags::AUTOMAP_INI); if (pst) { AdjustPSTFlags(anim); } // set up the animation, it cannot be done here // because a StaticSequence action can change it later map->AddAnimation(std::move(anim)); } void AREImporter::GetAmbient(DataStream* str, std::vector<Ambient*>& ambients) const { ResRef sounds[MAX_RESCOUNT]; ieWord soundCount; ieDword interval; Ambient* ambient = new Ambient(); str->Read(&ambient->name, 32); str->ReadPoint(ambient->origin); str->ReadWord(ambient->radius); str->Seek(2, GEM_CURRENT_POS); // alignment padding str->ReadDword(ambient->pitchVariance); str->ReadWord(ambient->gainVariance); str->ReadWord(ambient->gain); for (auto& sound : sounds) { str->ReadResRef(sound); } str->ReadWord(soundCount); str->Seek(2, GEM_CURRENT_POS); // alignment padding str->ReadDword(interval); ambient->interval = interval * 1000; str->ReadDword(interval); ambient->intervalVariance = interval * 1000; // schedule bits str->ReadDword(ambient->appearance); str->ReadDword(ambient->flags); str->Seek(64, GEM_CURRENT_POS); // this is a physical limit if (soundCount > MAX_RESCOUNT) { soundCount = MAX_RESCOUNT; } for (int j = 0; j < soundCount; j++) { ambient->sounds.emplace_back(sounds[j]); } ambients.push_back(ambient); } void AREImporter::GetAutomapNotes(DataStream* str, Map* map) const { static int pst = core->HasFeature(GFFlags::AUTOMAP_INI); Point point; if (!pst) { for (ieDword i = 0; i < NoteCount; i++) { str->ReadPoint(point); ieStrRef strref = ieStrRef::INVALID; str->ReadStrRef(strref); ieWord location; // (0=External (TOH/TOT), 1=Internal (TLK) str->ReadWord(location); ieWord color; str->ReadWord(color); // dword: ID in bg2 str->Seek(40, GEM_CURRENT_POS); // BG2 allows editing the builtin notes, PST does not, iwd1 and bg1 have no notes and iwd2 only user notes map->AddMapNote(point, color, strref, false); } return; } // Don't bother with autonote.ini if the area has autonotes (ie. it is a saved area) auto flag = gamedata->GetFactoryResourceAs<AnimationFactory>("FLAG1", IE_BAM_CLASS_ID); if (flag == nullptr) { ResourceHolder<ImageMgr> roImg = gamedata->GetResourceHolder<ImageMgr>("RONOTE"); ResourceHolder<ImageMgr> userImg = gamedata->GetResourceHolder<ImageMgr>("USERNOTE"); AnimationFactory af("FLAG1", { roImg->GetSprite2D(), userImg->GetSprite2D() }, { { 1, 0 }, { 1, 1 } }, { 0, 1 }); gamedata->AddFactoryResource<AnimationFactory>(std::move(af)); } if (NoteCount) { for (ieDword i = 0; i < NoteCount; i++) { ieDword px; ieDword py; str->ReadDword(px); str->ReadDword(py); // in PST the coordinates are stored in small map space // our MapControl wants them in large map space so we must convert // its what other games use and its what our custom map note code uses const Size mapsize = map->GetSize(); point.x = static_cast<int>(px * double(mapsize.w) / map->SmallMap->Frame.w); point.y = static_cast<int>(py * double(mapsize.h) / map->SmallMap->Frame.h); char bytes[501]; // 500 + null str->Read(bytes, 500); bytes[500] = '\0'; ieDword readonly; str->ReadDword(readonly); // readonly == 1 map->AddMapNote(point, 0, StringFromTLK(StringView(bytes)), readonly); str->Seek(20, GEM_CURRENT_POS); } } else { if (!INInote) { ReadAutonoteINI(); } if (!INInote) return; // add autonote.ini entries const ieVariable& scriptName = map->GetScriptName(); int count = INInote->GetKeyAsInt(scriptName, "count", 0); while (count) { ieVariable key; int value; key.Format("xPos{}", count); value = INInote->GetKeyAsInt(scriptName, key, 0); point.x = value; key.Format("yPos{}", count); value = INInote->GetKeyAsInt(scriptName, key, 0); point.y = value; key.Format("text{}", count); value = INInote->GetKeyAsInt(scriptName, key, 0); map->AddMapNote(point, 0, ieStrRef(value), true); count--; } } } bool AREImporter::GetTrap(DataStream* str, int idx, Map* map) const { str->Seek(TrapOffset + idx * 0x1C, GEM_STREAM_START); ResRef trapResRef; ieDword trapEffOffset; ieWord trapSize; ieWord proID; ieByte owner; Point pos; // currently unused: Point point; ieDword ticks; ieByte targetType; str->ReadResRef(trapResRef); str->ReadDword(trapEffOffset); str->ReadWord(trapSize); int trapEffectCount = trapSize / 0x108; if (trapEffectCount * 0x108 != trapSize) { Log(ERROR, "AREImporter", "TrapEffectSize in game: {} != {}. Clearing it", trapSize, trapEffectCount * 0x108); return false; } str->ReadWord(proID); str->ReadDword(ticks); // actually, delaycount/repetitioncount str->ReadPoint(point); str->Seek(2, GEM_CURRENT_POS); // unknown/unused 'Z' str->Read(&targetType, 1); // according to dev info, this is 'targettype'; "Enemy-ally targeting" on IESDP str->Read(&owner, 1); // party member index that created this projectile (0-5) // The projectile is always created, the worst that can happen // is a dummy projectile // The projectile ID is 214 for TRAPSNAR // It is off by one compared to projectl.ids, but the same as missile.ids Projectile* pro = core->GetProjectileServer()->GetProjectileByIndex(proID - 1); EffectQueue fxqueue = EffectQueue(); DataStream* fs = new SlicedStream(str, trapEffOffset, trapSize); ReadEffects(fs, &fxqueue, trapEffectCount); const Actor* caster = core->GetGame()->FindPC(owner + 1); pro->SetEffects(std::move(fxqueue)); if (caster) { // Since the level info isn't stored, we assume it's the same as if the trap was just placed. // It matters for the normal thief traps (they scale with level 4 times), while the rest don't scale. // To be more flexible and better handle disabled dualclasses, we don't hardcode it to the thief level. // Perhaps simplify and store the level in Z? Would need a check in the original (don't break saves). ieDword level = caster->GetThiefLevel(); pro->SetCaster(caster->GetGlobalID(), level ? level : caster->GetXPLevel(false)); } map->AddProjectile(pro, pos, pos); return true; } void AREImporter::GetTile(DataStream* str, Map* map) const { ieVariable tileName; ResRef tileID; ieDword tileFlags; // these fields could be different size: ieDword ClosedCount, OpenCount; ieWord closedCount; ieWord openCount; ieDword closedIndex; ieDword openIndex; str->ReadVariable(tileName); str->ReadResRef(tileID); str->ReadDword(tileFlags); // IE dev info says this: str->ReadDword(openIndex); // PrimarySearchSquareStart in bg2 str->ReadWord(openCount); // PrimarySearchSquareCount str->ReadWord(closedCount); // SecondarySearchSquareCount str->ReadDword(closedIndex); // SecondarySearcHSquareStart // end of disputed section str->Seek(48, GEM_CURRENT_POS); // 12 reserved dwords // absolutely no idea where these 'tile indices' are stored // are they tileset tiles or impeded block tiles map->TMap->AddTile(tileID, tileName, tileFlags, nullptr, 0, nullptr, 0); } Map* AREImporter::GetMap(const ResRef& resRef, bool day_or_night) { // if this area does not have extended night, force it to day mode if (!(AreaFlags & AT_EXTENDED_NIGHT)) day_or_night = true; PluginHolder<TileMapMgr> tmm = MakePluginHolder<TileMapMgr>(IE_WED_CLASS_ID); DataStream* wedfile = gamedata->GetResourceStream(WEDResRef, IE_WED_CLASS_ID); tmm->Open(wedfile); //there was no tilemap set yet, so lets just send a NULL TileMap* tm = tmm->GetTileMap(NULL); if (!tm) { Log(ERROR, "AREImporter", "No tile map available."); return nullptr; } ResRef TmpResRef; if (day_or_night) { TmpResRef = WEDResRef; } else { TmpResRef.Format("{:.7}N", WEDResRef); } // Small map for MapControl ResourceHolder<ImageMgr> sm = gamedata->GetResourceHolder<ImageMgr>(TmpResRef); if (!sm) { //fall back to day minimap sm = gamedata->GetResourceHolder<ImageMgr>(WEDResRef); } Map* map = nullptr; try { map = new Map(tm, MakeTileProps(tm, WEDResRef, day_or_night), sm ? sm->GetSprite2D() : nullptr); } catch (const std::exception& e) { Log(ERROR, "AREImporter", "{}", e); return nullptr; } if (core->config.SaveAsOriginal) { map->version = bigheader; } map->AreaFlags = AreaFlags; map->Rain = WRain; map->Snow = WSnow; map->Fog = WFog; map->Lightning = WLightning; map->AreaType = AreaType; map->DayNight = day_or_night; map->AreaDifficulty = AreaDifficulty; map->WEDResRef = WEDResRef; map->Dream[0] = Dream1; map->Dream[1] = Dream2; //we have to set this here because the actors will receive their //current area setting here, areas' 'scriptname' is their name map->SetScriptName(resRef); // reset MasterArea, since the script name wasn't available in the constructor map->MasterArea = core->GetGame()->MasterArea(map->GetScriptRef()); int idx = GetTrackString(resRef); if (idx >= 0) { map->SetTrackString(tracks[idx].text, tracks[idx].enabled, tracks[idx].difficulty); } else { map->SetTrackString(ieStrRef(-1), false, 0); } //if the Script field is empty, the area name will be copied into it on first load //this works only in the iwd branch of the games if (Script.IsEmpty() && core->HasFeature(GFFlags::FORCE_AREA_SCRIPT)) { Script = resRef; } if (!Script.IsEmpty()) { //for some reason the area's script is run from the last slot //at least one area script depends on this, if you need something //more customisable, add a game flag map->Scripts[MAX_SCRIPTS - 1] = new GameScript(Script, map); } Log(DEBUG, "AREImporter", "Loading songs"); std::vector<Ambient*> ambients; str->Seek(SongHeader, GEM_STREAM_START); GetSongs(str, map, ambients); // reverb to match against reverb.2da or iwd reverb.ids // (if the 2da doesn't exist - which we provide for all; they use the same values) ieDword reverbID; // set in PST, IWD1, 0 (NO_REVERB) elsewhere str->ReadDword(reverbID); // ignore 0 and use an area-type heuristic instead if (reverbID == 0) reverbID = EFX_PROFILE_REVERB_INVALID; str->Seek(RestHeader + 32, GEM_STREAM_START); // skip the name GetRestHeader(str, map); Log(DEBUG, "AREImporter", "Loading regions"); core->LoadProgress(70); //Loading InfoPoints for (int i = 0; i < InfoPointsCount; i++) { GetInfoPoint(str, i, map); } Log(DEBUG, "AREImporter", "Loading containers"); for (int i = 0; i < ContainersCount; i++) { GetContainer(str, i, map); } Log(DEBUG, "AREImporter", "Loading doors"); for (ieDword i = 0; i < DoorsCount; i++) { GetDoor(str, i, map, tmm); } Log(DEBUG, "AREImporter", "Loading spawnpoints"); for (ieDword i = 0; i < SpawnCount; i++) { GetSpawnPoint(str, i, map); } core->LoadProgress(75); Log(DEBUG, "AREImporter", "Loading actors"); str->Seek(ActorOffset, GEM_STREAM_START); assert(core->IsAvailable(IE_CRE_CLASS_ID)); auto actmgr = GetImporter<ActorMgr>(IE_CRE_CLASS_ID); for (int i = 0; i < ActorCount; i++) { if (!GetActor(str, actmgr, map)) continue; } core->LoadProgress(90); Log(DEBUG, "AREImporter", "Loading animations"); str->Seek(AnimOffset, GEM_STREAM_START); for (ieDword i = 0; i < AnimCount; i++) { GetAreaAnimation(str, map); } Log(DEBUG, "AREImporter", "Loading entrances"); str->Seek(EntrancesOffset, GEM_STREAM_START); for (ieDword i = 0; i < EntrancesCount; i++) { ieVariable Name; Point Pos; ieWord Face; str->ReadVariable(Name); str->ReadPoint(Pos); str->ReadWord(Face); str->Seek(66, GEM_CURRENT_POS); // just reserved bytes map->AddEntrance(Name, Pos, Face); } Log(DEBUG, "AREImporter", "Loading variables"); core->LoadInitialValues(resRef, map->locals); str->Seek(VariablesOffset, GEM_STREAM_START); for (ieDword i = 0; i < VariablesCount; i++) { ieVariable Name; ieDword Value; str->ReadVariable(Name); str->Seek(8, GEM_CURRENT_POS); // type + resreftype, part of the partly implemented type system (uint, int, float, str) str->ReadDword(Value); str->Seek(40, GEM_CURRENT_POS); // values as an int32, float64, string map->locals[Name] = Value; } Log(DEBUG, "AREImporter", "Loading ambients"); str->Seek(AmbiOffset, GEM_STREAM_START); for (int i = 0; i < AmbiCount; ++i) { GetAmbient(str, ambients); } map->SetAmbients(std::move(ambients), reverbID); Log(DEBUG, "AREImporter", "Loading automap notes"); str->Seek(NoteOffset, GEM_STREAM_START); GetAutomapNotes(str, map); //this is a ToB feature (saves the unexploded projectiles) Log(DEBUG, "AREImporter", "Loading traps"); for (ieDword i = 0; i < TrapCount; i++) { if (!GetTrap(str, i, map)) continue; } Log(DEBUG, "AREImporter", "Loading tiles"); //Loading Tiled objects (if any) str->Seek(TileOffset, GEM_STREAM_START); for (ieDword i = 0; i < TileCount; i++) { GetTile(str, map); } Log(DEBUG, "AREImporter", "Loading explored bitmap"); ieDword mapSize = ieDword(map->ExploredBitmap.Bytes()); mapSize = std::min(mapSize, ExploredBitmapSize); str->Seek(ExploredBitmapOffset, GEM_STREAM_START); str->Read(map->ExploredBitmap.begin(), mapSize); Log(DEBUG, "AREImporter", "Loading wallgroups"); map->SetWallGroups(tmm->GetWallGroups()); // setting up doors - doing it here instead when reading doors, so actors can be bumped if needed for (ieDword i = 0; i < DoorsCount; i++) { Door* door = tm->GetDoor(i); door->SetDoorOpen(door->IsOpen(), false, 0); } return map; } void AREImporter::AdjustPSTFlags(AreaAnimation& areaAnim) const { /** * For PST, map animation flags work differently to a degree that they * should not be mixed together with the rest as they even tend to * break things (like stopping early, hiding under FoW). * * So far, a better approximation towards handling animations is: * - zero everything * - always set A_ANI_SYNC * - copy/map known flags (A_ANI_ACTIVE, A_ANI_NO_WALL, A_ANI_BLEND) * * Note that WF_COVERANIMS is enabled by default for PST, so ANI_NO_WALL * is important. * * The actual use of bits in PST map anims isn't fully solved here. */ // rename flags for clarity #define PST_ANI_NO_WALL AreaAnimation::Flags::Once #define PST_ANI_BLEND AreaAnimation::Flags::Background areaAnim.flags = AreaAnimation::Flags::None; // Clear everything // Set default-on flags (currently only A_ANI_SYNC) areaAnim.flags |= AreaAnimation::Flags::Sync; // Copy still-relevant A_ANI_* flags areaAnim.flags |= areaAnim.originalFlags & AreaAnimation::Flags::Active; // Map known flags if (bool(areaAnim.originalFlags & PST_ANI_BLEND)) { areaAnim.flags |= AreaAnimation::Flags::BlendBlack; } if (bool(areaAnim.originalFlags & PST_ANI_NO_WALL)) { areaAnim.flags |= AreaAnimation::Flags::NoWall; } } void AREImporter::ReadEffects(DataStream* ds, EffectQueue* fxqueue, ieDword EffectsCount) const { PluginHolder<EffectMgr> eM = MakePluginHolder<EffectMgr>(IE_EFF_CLASS_ID); eM->Open(ds); for (unsigned int i = 0; i < EffectsCount; i++) { fxqueue->AddEffect(eM->GetEffectV20()); } } int AREImporter::GetStoredFileSize(Map* map) { int headersize = map->version + 0x11c; ActorOffset = headersize; //get only saved actors (no familiars or partymembers) //summons? ActorCount = (ieWord) map->GetActorCount(false); headersize += ActorCount * 0x110; auto am = GetImporter<ActorMgr>(IE_CRE_CLASS_ID); EmbeddedCreOffset = headersize; for (unsigned int i = 0; i < ActorCount; i++) { headersize += am->GetStoredFileSize(map->GetActor(i, false)); } InfoPointsOffset = headersize; InfoPointsCount = (ieWord) map->TMap->GetInfoPointCount(); headersize += InfoPointsCount * 0xc4; SpawnOffset = headersize; SpawnCount = map->GetSpawnCount(); headersize += SpawnCount * 0xc8; EntrancesOffset = headersize; EntrancesCount = (ieDword) map->GetEntranceCount(); headersize += EntrancesCount * 0x68; ContainersOffset = headersize; //this one removes empty heaps and counts items, should be before //getting ContainersCount ItemsCount = (ieWord) map->ConsolidateContainers(); ContainersCount = (ieWord) map->TMap->GetContainerCount(); headersize += ContainersCount * 0xc0; ItemsOffset = headersize; headersize += ItemsCount * 0x14; DoorsOffset = headersize; DoorsCount = (ieDword) map->TMap->GetDoorCount(); headersize += DoorsCount * 0xc8; VerticesOffset = headersize; VerticesCount = 0; for (unsigned int i = 0; i < InfoPointsCount; i++) { const InfoPoint* ip = map->TMap->GetInfoPoint(i); if (ip->outline) { VerticesCount += ip->outline->Count(); } else { VerticesCount++; } } for (unsigned int i = 0; i < ContainersCount; i++) { const Container* c = map->TMap->GetContainer(i); if (c->outline) VerticesCount += c->outline->Count(); } for (unsigned int i = 0; i < DoorsCount; i++) { const Door* d = map->TMap->GetDoor(i); auto open = d->OpenTriggerArea(); auto closed = d->ClosedTriggerArea(); if (open) VerticesCount += open->Count(); if (closed) VerticesCount += closed->Count(); VerticesCount += d->open_ib.size() + d->closed_ib.size(); } headersize += VerticesCount * 4; AmbiOffset = headersize; headersize += SavedAmbientCount(map) * 0xd4; VariablesOffset = headersize; VariablesCount = (ieDword) map->locals.size(); headersize += VariablesCount * 0x54; AnimOffset = headersize; AnimCount = (ieDword) map->GetAnimationCount(); headersize += AnimCount * 0x4c; TileOffset = headersize; TileCount = (ieDword) map->TMap->GetTileCount(); headersize += TileCount * 0x6c; ExploredBitmapOffset = headersize; ExploredBitmapSize = map->ExploredBitmap.Bytes(); headersize += ExploredBitmapSize; EffectOffset = headersize; proIterator piter; TrapCount = (ieDword) map->GetTrapCount(piter); for (unsigned int i = 0; i < TrapCount; i++) { const Projectile* pro = map->GetNextTrap(piter); if (pro) { const EffectQueue& fxqueue = pro->GetEffects(); if (fxqueue) { headersize += fxqueue.GetSavedEffectsCount() * 0x108; } } } TrapOffset = headersize; headersize += TrapCount * 0x1c; NoteOffset = headersize; NoteCount = map->GetMapNoteCount(); headersize += NoteCount * (core->HasFeature(GFFlags::AUTOMAP_INI) ? 0x214 : 0x34); SongHeader = headersize; headersize += 0x90; RestHeader = headersize; headersize += 0xe4; return headersize; } int AREImporter::PutHeader(DataStream* stream, const Map* map) const { ResRef signature = "AREAV1.0"; if (map->version == 16) { signature[5] = '9'; signature[7] = '1'; } stream->WriteResRef(signature); stream->WriteResRef(map->WEDResRef); uint32_t time = core->GetGame()->GameTime; stream->WriteDword(time); //lastsaved stream->WriteDword(map->AreaFlags); stream->WriteFilling(12); // northref stream->WriteFilling(12); // westref stream->WriteFilling(12); // southref stream->WriteFilling(12); // eastref stream->WriteWord(map->AreaType); stream->WriteWord(map->Rain); stream->WriteWord(map->Snow); stream->WriteWord(map->Fog); stream->WriteWord(map->Lightning); stream->WriteFilling(2); if (map->version == 16) { //writing 14 bytes of 0's char tmp[1] = { '0' }; if (map->AreaDifficulty == 2) { tmp[0] = 1; } stream->Write(tmp, 1); tmp[0] = 0; if (map->AreaDifficulty == 4) { tmp[0] = 1; } stream->Write(tmp, 1); stream->WriteFilling(6); stream->WriteFilling(8); } stream->WriteDword(ActorOffset); stream->WriteWord(ActorCount); stream->WriteWord(InfoPointsCount); stream->WriteDword(InfoPointsOffset); stream->WriteDword(SpawnOffset); stream->WriteDword(SpawnCount); stream->WriteDword(EntrancesOffset); stream->WriteDword(EntrancesCount); stream->WriteDword(ContainersOffset); stream->WriteWord(ContainersCount); stream->WriteWord(ItemsCount); stream->WriteDword(ItemsOffset); stream->WriteDword(VerticesOffset); stream->WriteWord(VerticesCount); stream->WriteWord(SavedAmbientCount(map)); stream->WriteDword(AmbiOffset); stream->WriteDword(VariablesOffset); stream->WriteDword(VariablesCount); stream->WriteFilling(4); //the saved area script is in the last script slot! const GameScript* s = map->Scripts[MAX_SCRIPTS - 1]; if (s) { stream->WriteResRefLC(s->GetName()); } else { stream->WriteFilling(8); } stream->WriteDword(ExploredBitmapSize); stream->WriteDword(ExploredBitmapOffset); stream->WriteDword(DoorsCount); stream->WriteDword(DoorsOffset); stream->WriteDword(AnimCount); stream->WriteDword(AnimOffset); stream->WriteDword(TileCount); stream->WriteDword(TileOffset); stream->WriteDword(SongHeader); stream->WriteDword(RestHeader); //an empty dword for pst int i = 56; if (core->HasFeature(GFFlags::AUTOMAP_INI)) { stream->WriteDword(0xffffffff); i = 52; } stream->WriteDword(NoteOffset); stream->WriteDword(NoteCount); stream->WriteDword(TrapOffset); stream->WriteDword(TrapCount); stream->WriteResRef(map->Dream[0]); stream->WriteResRef(map->Dream[1]); //usually 56 empty bytes (but pst used up 4 elsewhere) stream->WriteFilling(i); return 0; } int AREImporter::PutDoors(DataStream* stream, const Map* map, ieDword& VertIndex) const { for (unsigned int i = 0; i < DoorsCount; i++) { Door* d = map->TMap->GetDoor(i); stream->WriteVariable(d->GetScriptName()); stream->WriteResRef(d->ID); ieDword flags = d->Flags; if (map->version == 16) { flags = FixIWD2DoorFlags(d->Flags, true); } stream->WriteDword(flags); stream->WriteDword(VertIndex); auto open = d->OpenTriggerArea(); ieWord tmpWord = static_cast<ieWord>(open ? open->Count() : 0); stream->WriteWord(tmpWord); VertIndex += tmpWord; auto closed = d->ClosedTriggerArea(); tmpWord = static_cast<ieWord>(closed ? closed->Count() : 0); stream->WriteWord(tmpWord); stream->WriteDword(VertIndex); VertIndex += tmpWord; //open bounding box stream->WriteWord(d->OpenBBox.x); stream->WriteWord(d->OpenBBox.y); stream->WriteWord(d->OpenBBox.x + d->OpenBBox.w); stream->WriteWord(d->OpenBBox.y + d->OpenBBox.h); //closed bounding box stream->WriteWord(d->ClosedBBox.x); stream->WriteWord(d->ClosedBBox.y); stream->WriteWord(d->ClosedBBox.x + d->ClosedBBox.w); stream->WriteWord(d->ClosedBBox.y + d->ClosedBBox.h); //open and closed impeded blocks stream->WriteDword(VertIndex); tmpWord = (ieWord) d->open_ib.size(); stream->WriteWord(tmpWord); VertIndex += tmpWord; tmpWord = (ieWord) d->closed_ib.size(); stream->WriteWord(tmpWord); stream->WriteDword(VertIndex); VertIndex += tmpWord; stream->WriteWord(d->hp); stream->WriteWord(d->ac); stream->WriteResRef(d->OpenSound); stream->WriteResRef(d->CloseSound); stream->WriteDword(d->Cursor); stream->WriteWord(d->TrapDetectionDiff); stream->WriteWord(d->TrapRemovalDiff); stream->WriteWord(d->Trapped); stream->WriteWord(d->TrapDetected); stream->WritePoint(d->TrapLaunch); stream->WriteResRefLC(d->KeyResRef); const GameScript* s = d->Scripts[0]; if (s) { stream->WriteResRefLC(s->GetName()); } else { stream->WriteFilling(8); } stream->WriteDword(d->DiscoveryDiff); //lock difficulty field stream->WriteDword(d->LockDifficulty); //opening locations stream->WritePoint(d->toOpen[0]); stream->WritePoint(d->toOpen[1]); stream->WriteStrRef(d->LockedStrRef); if (core->HasFeature(GFFlags::AUTOMAP_INI)) { stream->WriteString(d->LinkedInfo, 24); } else { stream->WriteVariable(d->LinkedInfo); } stream->WriteStrRef(d->NameStrRef); stream->WriteResRef(d->GetDialog()); if (core->HasFeature(GFFlags::AUTOMAP_INI)) { stream->WriteFilling(8); } } return 0; } int AREImporter::PutPoints(DataStream* stream, const std::vector<Point>& points) const { for (const Point& p : points) { stream->WritePoint(p); } return 0; } int AREImporter::PutPoints(DataStream* stream, const std::vector<SearchmapPoint>& points) const { for (const SearchmapPoint& p : points) { stream->WritePoint(p); } return 0; } int AREImporter::PutVertices(DataStream* stream, const Map* map) const { //regions for (unsigned int i = 0; i < InfoPointsCount; i++) { const InfoPoint* ip = map->TMap->GetInfoPoint(i); if (ip->outline) { PutPoints(stream, ip->outline->vertices); } else { Point origin = ip->BBox.origin; stream->WritePoint(origin); } } //containers for (size_t i = 0; i < ContainersCount; i++) { const Container* c = map->TMap->GetContainer(i); if (c->outline) { PutPoints(stream, c->outline->vertices); } } //doors for (unsigned int i = 0; i < DoorsCount; i++) { const Door* d = map->TMap->GetDoor(i); auto open = d->OpenTriggerArea(); auto closed = d->ClosedTriggerArea(); if (open) PutPoints(stream, open->vertices); if (closed) PutPoints(stream, closed->vertices); PutPoints(stream, d->open_ib); PutPoints(stream, d->closed_ib); } return 0; } int AREImporter::PutItems(DataStream* stream, const Map* map) const { for (size_t i = 0; i < ContainersCount; i++) { const Container* c = map->TMap->GetContainer(i); for (int j = 0; j < c->inventory.GetSlotCount(); j++) { const CREItem* ci = c->inventory.GetSlotItem(j); stream->WriteResRefUC(ci->ItemResRef); stream->WriteWord(ci->Expired); stream->WriteWord(ci->Usages[0]); stream->WriteWord(ci->Usages[1]); stream->WriteWord(ci->Usages[2]); stream->WriteDword(ci->Flags); } } return 0; } int AREImporter::PutContainers(DataStream* stream, const Map* map, ieDword& VertIndex) const { ieDword ItemIndex = 0; for (size_t i = 0; i < ContainersCount; i++) { const Container* c = map->TMap->GetContainer(i); //this is the editor name stream->WriteVariable(c->GetScriptName()); stream->WritePoint(c->Pos); stream->WriteWord(c->containerType); stream->WriteWord(c->LockDifficulty); stream->WriteDword(c->Flags); stream->WriteWord(c->TrapDetectionDiff); stream->WriteWord(c->TrapRemovalDiff); stream->WriteWord(c->Trapped); stream->WriteWord(c->TrapDetected); stream->WritePoint(c->TrapLaunch); //outline bounding box stream->WriteWord(c->BBox.x); stream->WriteWord(c->BBox.y); stream->WriteWord(c->BBox.x + c->BBox.w); stream->WriteWord(c->BBox.y + c->BBox.h); //item index and offset ieDword tmpDword = c->inventory.GetSlotCount(); stream->WriteDword(ItemIndex); stream->WriteDword(tmpDword); ItemIndex += tmpDword; const GameScript* s = c->Scripts[0]; if (s) { stream->WriteResRefLC(s->GetName()); } else { stream->WriteFilling(8); } //outline polygon index and count ieWord tmpWord = static_cast<ieWord>(c->outline ? c->outline->Count() : 0); stream->WriteDword(VertIndex); stream->WriteWord(tmpWord); VertIndex += tmpWord; tmpWord = 0; stream->WriteWord(tmpWord); //vertex count is made short //this is the real scripting name stream->WriteVariable(c->GetScriptName()); stream->WriteResRefLC(c->KeyResRef); stream->WriteDword(0); //unknown80 stream->WriteStrRef(c->OpenFail); stream->WriteFilling(56); //unknown or unused stuff } return 0; } int AREImporter::PutRegions(DataStream* stream, const Map* map, ieDword& VertIndex) const { for (unsigned int i = 0; i < InfoPointsCount; i++) { const InfoPoint* ip = map->TMap->GetInfoPoint(i); stream->WriteVariable(ip->GetScriptName()); //this is a hack, we abuse a coincidence //ST_PROXIMITY = 1, ST_TRIGGER = 2, ST_TRAVEL = 3 //translates to trap = 0, info = 1, travel = 2 stream->WriteWord(((ieWord) ip->Type) - 1); //outline bounding box stream->WriteWord(ip->BBox.x); stream->WriteWord(ip->BBox.y); stream->WriteWord(ip->BBox.x + ip->BBox.w); stream->WriteWord(ip->BBox.y + ip->BBox.h); ieWord tmpWord = static_cast<ieWord>(ip->outline ? ip->outline->Count() : 1); stream->WriteWord(tmpWord); stream->WriteDword(VertIndex); VertIndex += tmpWord; stream->WriteDword(0); //unknown30 stream->WriteDword(ip->Cursor); stream->WriteResRefUC(ip->Destination); stream->WriteVariableUC(ip->EntranceName); stream->WriteDword(ip->Flags); stream->WriteStrRef(ip->StrRef); stream->WriteWord(ip->TrapDetectionDiff); stream->WriteWord(ip->TrapRemovalDiff); stream->WriteWord(ip->Trapped); //unknown??? stream->WriteWord(ip->TrapDetected); stream->WritePoint(ip->TrapLaunch); stream->WriteResRefLC(ip->KeyResRef); const GameScript* s = ip->Scripts[0]; if (s) { stream->WriteResRefLC(s->GetName()); } else { stream->WriteFilling(8); } stream->WritePoint(ip->UsePoint); if (16 == map->version) { stream->WriteDword(ip->UsePoint.x); stream->WriteDword(ip->UsePoint.y); stream->WriteFilling(28); //unknown } else { stream->WriteFilling(36); //unknown } //these are probably only in PST stream->WriteResRef(ip->EnterWav); stream->WritePoint(ip->TalkPos); stream->WriteStrRef(ip->DialogName); stream->WriteResRef(ip->GetDialog()); } return 0; } int AREImporter::PutSpawns(DataStream* stream, const Map* map) const { ieWord tmpWord; for (unsigned int i = 0; i < SpawnCount; i++) { const Spawn* sp = map->GetSpawn(i); stream->WriteVariable(sp->Name); tmpWord = (ieWord) sp->Pos.x; stream->WriteWord(tmpWord); tmpWord = (ieWord) sp->Pos.y; stream->WriteWord(tmpWord); tmpWord = ieWord(sp->Creatures.size()); int j; for (j = 0; j < tmpWord; j++) { stream->WriteResRef(sp->Creatures[j]); } while (j++ < MAX_RESCOUNT) { stream->WriteFilling(8); } stream->WriteWord(tmpWord); stream->WriteWord(sp->Difficulty); stream->WriteWord(sp->Frequency); stream->WriteWord(sp->Method); stream->WriteDword(sp->sduration); //spawn duration stream->WriteWord(sp->rwdist); //random walk distance stream->WriteWord(sp->owdist); //other walk distance stream->WriteWord(sp->Maximum); stream->WriteWord(sp->Enabled); stream->WriteDword(sp->appearance); stream->WriteWord(sp->DayChance); stream->WriteWord(sp->NightChance); stream->WriteFilling(56); //most likely unused crap } return 0; } void AREImporter::PutScript(DataStream* stream, const Actor* ac, unsigned int index) const { const GameScript* s = ac->Scripts[index]; if (s) { stream->WriteResRefLC(s->GetName()); } else { stream->WriteFilling(8); } } int AREImporter::PutActors(DataStream* stream, const Map* map) const { ieDword CreatureOffset = EmbeddedCreOffset; auto am = GetImporter<ActorMgr>(IE_CRE_CLASS_ID); for (unsigned int i = 0; i < ActorCount; i++) { const Actor* ac = map->GetActor(i, false); stream->WriteVariable(ac->GetScriptName()); stream->WritePoint(ac->Pos); stream->WritePoint(ac->HomeLocation); stream->WriteDword(0); //used fields flag always 0 for saved areas stream->WriteWord(ac->Spawned); stream->WriteFilling(1); // letter stream->WriteScalar(ac->ignoredFields.difficultyMargin); stream->WriteDword(0); //actor animation, unused stream->WriteWord(ac->GetOrientation()); stream->WriteWord(0); //unknown stream->WriteDword(ac->Timers.removalTime); stream->WriteWord(ac->maxWalkDistance); stream->WriteWord(0); //more unknowns stream->WriteDword(ac->appearance); stream->WriteDword(ac->TalkCount); stream->WriteResRefLC(ac->GetDialog()); PutScript(stream, ac, SCR_OVERRIDE); PutScript(stream, ac, SCR_GENERAL); PutScript(stream, ac, SCR_CLASS); PutScript(stream, ac, SCR_RACE); PutScript(stream, ac, SCR_DEFAULT); PutScript(stream, ac, SCR_SPECIFICS); //creature reference is empty because we are embedding it //the original engine used a '*' stream->WriteFilling(8); stream->WriteDword(CreatureOffset); ieDword CreatureSize = am->GetStoredFileSize(ac); stream->WriteDword(CreatureSize); CreatureOffset += CreatureSize; PutScript(stream, ac, SCR_AREA); stream->WriteFilling(120); } CreatureOffset = EmbeddedCreOffset; for (unsigned int i = 0; i < ActorCount; i++) { assert(stream->GetPos() == CreatureOffset); const Actor* ac = map->GetActor(i, false); //reconstructing offsets again CreatureOffset += am->GetStoredFileSize(ac); am->PutActor(stream, ac); } assert(stream->GetPos() == CreatureOffset); return 0; } int AREImporter::PutAnimations(DataStream* stream, const Map* map) const { auto iter = map->GetFirstAnimation(); while (const AreaAnimation* an = map->GetNextAnimation(iter)) { stream->WriteVariable(an->Name); stream->WritePoint(an->Pos); stream->WriteDword(an->appearance); stream->WriteResRef(an->BAM); stream->WriteWord(an->sequence); stream->WriteWord(an->frame); if (core->HasFeature(GFFlags::AUTOMAP_INI)) { /* PST toggles the active bit only, and we need to keep the rest. */ auto flags = (an->originalFlags & ~AreaAnimation::Flags::Active) | (an->flags & AreaAnimation::Flags::Active); stream->WriteEnum(flags); } else { stream->WriteEnum(an->flags); } stream->WriteScalar(an->height); stream->WriteWord(an->transparency); stream->WriteWord(an->startFrameRange); //used by A_ANI_RANDOM_START stream->Write(&an->startchance, 1); stream->Write(&an->skipcycle, 1); stream->WriteResRef(an->PaletteRef); stream->WriteDword(an->unknown48); //seems utterly unused } return 0; } int AREImporter::PutEntrances(DataStream* stream, const Map* map) const { for (unsigned int i = 0; i < EntrancesCount; i++) { const Entrance* e = map->GetEntrance(i); stream->WriteVariable(e->Name); stream->WritePoint(e->Pos); stream->WriteWord(e->Face); //a large empty piece of crap stream->WriteFilling(66); } return 0; } int AREImporter::PutVariables(DataStream* stream, const Map* map) const { for (const auto& entry : map->locals) { size_t len = entry.first.length(); stream->Write(entry.first.c_str(), len); if (len < 40) { stream->WriteFilling(40 - len); } stream->WriteDword(entry.second); //40 bytes of empty crap stream->WriteFilling(40); } return 0; } int AREImporter::PutAmbients(DataStream* stream, const Map* map) const { for (const auto& am : map->GetAmbients()) { if (am->flags & IE_AMBI_NOSAVE) continue; stream->WriteVariable(am->name); stream->WritePoint(am->origin); stream->WriteWord(am->radius); stream->WriteFilling(2); stream->WriteDword(am->pitchVariance); stream->WriteWord(am->gainVariance); stream->WriteWord(am->gain); size_t j = 0; for (; j < am->sounds.size(); j++) { stream->WriteResRef(am->sounds[j]); } while (j++ < MAX_RESCOUNT) { stream->WriteFilling(8); } stream->WriteWord(am->sounds.size()); stream->WriteFilling(2); stream->WriteDword(ieDword(am->interval / 1000)); stream->WriteDword(ieDword(am->intervalVariance / 1000)); stream->WriteDword(am->appearance); stream->WriteDword(am->flags); stream->WriteFilling(64); } return 0; } int AREImporter::PutMapnotes(DataStream* stream, const Map* map) const { //different format int pst = core->HasFeature(GFFlags::AUTOMAP_INI); for (unsigned int i = 0; i < NoteCount; i++) { const MapNote& mn = map->GetMapNote(i); if (pst) { // in PST the coordinates are stored in small map space const Size& mapsize = map->GetSize(); stream->WriteDword(static_cast<ieDword>(mn.Pos.x * double(map->SmallMap->Frame.w) / mapsize.w)); stream->WriteDword(static_cast<ieDword>(mn.Pos.y * double(map->SmallMap->Frame.h) / mapsize.h)); size_t len = 0; // limited to 500 *bytes* of text, convert to a multibyte encoding. // we convert to MB because it fits more than if we wrote the wide characters std::string mbstring = TLKStringFromString(mn.text); len = std::min<size_t>(mbstring.length(), 500); stream->Write(mbstring.c_str(), len); // pad the remaining space size_t x = 500 - len; for (size_t j = 0; j < x / 8; ++j) { stream->WriteFilling(8); } x = x % 8; if (x) { stream->WriteFilling(x); } stream->WriteDword(mn.readonly); for (x = 0; x < 5; x++) { //5 empty dwords stream->WriteFilling(4); } } else { stream->WritePoint(mn.Pos); stream->WriteStrRef(mn.strref); stream->WriteWord(mn.Pos.y); stream->WriteWord(mn.color); stream->WriteDword(1); for (int x = 0; x < 9; ++x) { //9 empty dwords stream->WriteFilling(4); } } } return 0; } int AREImporter::PutEffects(DataStream* stream, const EffectQueue& fxqueue) const { PluginHolder<EffectMgr> eM = MakePluginHolder<EffectMgr>(IE_EFF_CLASS_ID); assert(eM != nullptr); auto f = fxqueue.GetFirstEffect(); ieDword EffectsCount = fxqueue.GetSavedEffectsCount(); for (unsigned int i = 0; i < EffectsCount; i++) { const Effect* fx = fxqueue.GetNextSavedEffect(f); assert(fx != NULL); eM->PutEffectV2(stream, fx); } return 0; } int AREImporter::PutTraps(DataStream* stream, const Map* map) const { ieDword Offset; ResRef name; ieWord type = 0; Point dest(0, 0); Offset = EffectOffset; proIterator iter; ieDword i = map->GetTrapCount(iter); while (i--) { ieWord tmpWord = 0; ieByte tmpByte = 0xff; const Projectile* pro = map->GetNextTrap(iter); if (pro) { //The projectile ID is based on missile.ids which is //off by one compared to projectl.ids type = pro->GetType() + 1; dest = pro->GetDestination(); const ResRef& proName = pro->GetName(); name = proName; const EffectQueue& fxqueue = pro->GetEffects(); if (fxqueue) { tmpWord = static_cast<ieWord>(fxqueue.GetSavedEffectsCount()); } ieDword ID = pro->GetCaster(); // lookup caster via Game, since the the current map can already be empty when switching them const Actor* actor = core->GetGame()->GetActorByGlobalID(ID); //0xff if not in party //party slot if in party if (actor) tmpByte = (ieByte) (actor->InParty - 1); } stream->WriteResRefUC(name); stream->WriteDword(Offset); //size of fxqueue; assert(tmpWord < 256); tmpWord *= 0x108; Offset += tmpWord; stream->WriteWord(tmpWord); //size in bytes stream->WriteWord(type); //missile.ids stream->WriteDword(0); // unknown field, Ticks stream->WritePoint(dest); stream->WriteWord(0); // unknown field, Z stream->Write(&tmpByte, 1); // unknown field, TargetType stream->Write(&tmpByte, 1); // Owner } return 0; } int AREImporter::PutExplored(DataStream* stream, const Map* map) const { stream->Write(map->ExploredBitmap.begin(), ExploredBitmapSize); return 0; } int AREImporter::PutTiles(DataStream* stream, const Map* map) const { for (unsigned int i = 0; i < TileCount; i++) { const TileObject* am = map->TMap->GetTile(i); stream->WriteVariable(am->name); stream->WriteResRef(am->tileset); stream->WriteDword(am->flags); stream->WriteDword(am->openCount); //can't write tiles, otherwise now we should write a tile index stream->WriteDword(0); stream->WriteDword(am->closedCount); //can't write tiles otherwise now we should write a tile index stream->WriteDword(0); stream->WriteFilling(48); } return 0; } ieWord AREImporter::SavedAmbientCount(const Map* map) const { ieWord count = 0; for (const Ambient* am : map->GetAmbients()) { if (am->flags & IE_AMBI_NOSAVE) continue; ++count; } return count; } int AREImporter::PutMapAmbients(DataStream* stream, const Map* map) const { //day stream->WriteResRef(map->dayAmbients.Ambient1); stream->WriteResRef(map->dayAmbients.Ambient2); stream->WriteDword(map->dayAmbients.AmbientVol); //night stream->WriteResRef(map->nightAmbients.Ambient1); stream->WriteResRef(map->nightAmbients.Ambient2); stream->WriteDword(map->nightAmbients.AmbientVol); //song flag stream->WriteDword(map->reverbID); //lots of empty crap (15x4) stream->WriteFilling(60); return 0; } int AREImporter::PutRestHeader(DataStream* stream, const Map* map) const { stream->WriteFilling(32); //empty label for (const auto& ref : map->RestHeader.Strref) { stream->WriteStrRef(ref); } for (const auto& ref : map->RestHeader.CreResRef) { stream->WriteResRef(ref); } stream->WriteWord(map->RestHeader.CreatureNum); stream->WriteWord(map->RestHeader.Difficulty); stream->WriteDword(map->RestHeader.Duration); stream->WriteWord(map->RestHeader.RandomWalkDistance); stream->WriteWord(map->RestHeader.FollowDistance); stream->WriteWord(map->RestHeader.Maximum); stream->WriteWord(map->RestHeader.Enabled); stream->WriteWord(map->RestHeader.DayChance); stream->WriteWord(map->RestHeader.NightChance); stream->WriteFilling(56); return 0; } /* no saving of tiled objects, are they used anywhere? */ int AREImporter::PutArea(DataStream* stream, const Map* map) const { ieDword VertIndex = 0; int ret; if (!stream || !map) { return -1; } ret = PutHeader(stream, map); if (ret) { return ret; } ret = PutActors(stream, map); if (ret) { return ret; } ret = PutRegions(stream, map, VertIndex); if (ret) { return ret; } ret = PutSpawns(stream, map); if (ret) { return ret; } ret = PutEntrances(stream, map); if (ret) { return ret; } ret = PutContainers(stream, map, VertIndex); if (ret) { return ret; } ret = PutItems(stream, map); if (ret) { return ret; } ret = PutDoors(stream, map, VertIndex); if (ret) { return ret; } ret = PutVertices(stream, map); if (ret) { return ret; } ret = PutAmbients(stream, map); if (ret) { return ret; } ret = PutVariables(stream, map); if (ret) { return ret; } ret = PutAnimations(stream, map); if (ret) { return ret; } ret = PutTiles(stream, map); if (ret) { return ret; } ret = PutExplored(stream, map); if (ret) { return ret; } proIterator iter; ieDword i = map->GetTrapCount(iter); while (i--) { const Projectile* trap = map->GetNextTrap(iter); if (!trap) { continue; } const EffectQueue& fxqueue = trap->GetEffects(); if (!fxqueue) { continue; } ret = PutEffects(stream, fxqueue); if (ret) { return ret; } } ret = PutTraps(stream, map); if (ret) { return ret; } ret = PutMapnotes(stream, map); if (ret) { return ret; } for (const auto& list : map->SongList) { stream->WriteDword(list); } ret = PutMapAmbients(stream, map); if (ret) { return ret; } ret = PutRestHeader(stream, map); return ret; } #include "plugindef.h" GEMRB_PLUGIN(0x145B60F0, "ARE File Importer") PLUGIN_CLASS(IE_ARE_CLASS_ID, ImporterPlugin<AREImporter>) END_PLUGIN()
0
0.971957
1
0.971957
game-dev
MEDIA
0.609833
game-dev
0.994078
1
0.994078
ClassiCube/MCGalaxy
3,222
MCGalaxy/Blocks/Physics/BirdPhysics.cs
/* Copyright 2010 MCSharp team (Modified for use with MCZall/MCLawl/MCForge) Dual-licensed under the Educational Community License, Version 2.0 and the GNU General Public License, Version 3 (the "Licenses"); you may not use this file except in compliance with the Licenses. You may obtain a copy of the Licenses at https://opensource.org/license/ecl-2-0/ https://www.gnu.org/licenses/gpl-3.0.html Unless required by applicable law or agreed to in writing, software distributed under the Licenses are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licenses for the specific language governing permissions and limitations under the Licenses. */ using System; using BlockID = System.UInt16; namespace MCGalaxy.Blocks.Physics { public static class BirdPhysics { public static void Do(Level lvl, ref PhysInfo C) { Random rand = lvl.physRandom; ushort x = C.X, y = C.Y, z = C.Z; BlockID block = lvl.GetBlock(x, y, z); int index; switch (rand.Next(1, 15)) { case 1: if (lvl.IsAirAt(x, (ushort)(y - 1), z, out index)) { lvl.AddUpdate(index, block); } else goto case 3; break; case 2: if (lvl.IsAirAt(x, (ushort)(y + 1), z, out index)) { lvl.AddUpdate(index, block); } else goto case 6; break; case 3: case 4: case 5: FlyTo(lvl, ref C, (ushort)(x - 1), y, z, block); break; case 6: case 7: case 8: FlyTo(lvl, ref C, (ushort)(x + 1), y, z, block); break; case 9: case 10: case 11: FlyTo(lvl, ref C, x, y, (ushort)(z - 1), block); break; default: FlyTo(lvl, ref C, x, y, (ushort)(z + 1), block); break; } lvl.AddUpdate(C.Index, Block.Air, default(PhysicsArgs)); C.Data.Data = PhysicsArgs.RemoveFromChecks; } static void FlyTo(Level lvl, ref PhysInfo C, ushort x, ushort y, ushort z, BlockID block) { int index; BlockID neighbour = lvl.GetBlock(x, y, z, out index); if (neighbour == Block.Invalid) return; switch (neighbour) { case Block.Air: lvl.AddUpdate(index, block); break; case Block.Op_Air: break; default: // bird died by hitting a block PhysicsArgs args = default(PhysicsArgs); args.Type1 = PhysicsArgs.Dissipate; args.Value1 = 25; lvl.AddUpdate(C.Index, Block.Red, args); break; } } } }
0
0.868892
1
0.868892
game-dev
MEDIA
0.879266
game-dev
0.9553
1
0.9553
BindaCMS/binda
1,245
app/models/concerns/binda/fieldable_association_helpers/fieldable_repeater_helpers.rb
module Binda module FieldableAssociationHelpers module FieldableRepeaterHelpers # Check if exists any repeater with that slug # # @param field_slug [string] The slug of the field setting # @return [boolean] def has_repeaters(field_slug) obj = self.repeaters.find_all{ |t| t.field_setting_id == FieldSetting.get_id( field_slug ) } raise ArgumentError, "There isn't any repeater associated to the current slug (#{field_slug}) on instance (#{self.class.name} ##{self.id}).", caller if obj.nil? return obj.present? end def has_repeater(field_slug) has_repeaters(field_slug) end # Get the all repeater instances sorted by position # # @param field_slug [string] The slug of the field setting # @return [array] An array of repeater items which have all sorts of fields attached def get_repeaters(field_slug) obj = self.repeaters.find_all{ |t| t.field_setting_id == FieldSetting.get_id( field_slug ) } raise ArgumentError, "There isn't any repeater associated to the current slug (#{field_slug}) on instance (#{self.class.name} ##{self.id}).", caller if obj.nil? obj.sort_by(&:position) end def get_repeater(field_slug) get_repeaters(field_slug) end end end end
0
0.611028
1
0.611028
game-dev
MEDIA
0.727629
game-dev
0.728562
1
0.728562
ffxivcode/AutoDuty
6,882
AutoDuty/Helpers/MapHelper.cs
using ECommons.DalamudServices; using ECommons.MathHelpers; using System.Numerics; using System.Linq; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.UI.Agent; using ECommons.Throttlers; using AutoDuty.IPC; using ECommons; using FFXIVClientStructs.FFXIV.Component.GUI; namespace AutoDuty.Helpers { using Lumina.Excel.Sheets; internal static class MapHelper { internal static unsafe bool IsFlagMarkerSet => AgentMap.Instance()->FlagMarkerCount > 0; internal static unsafe FlagMapMarker GetFlagMarker => IsFlagMarkerSet ? AgentMap.Instance()->FlagMapMarkers[0] : default; internal static Vector2 ConvertWorldXZToMap(Vector2 coords, Map map) => Dalamud.Utility.MapUtil.WorldToMap(coords, map.OffsetX, map.OffsetY, map.SizeFactor); internal static Vector2 ConvertMarkerToMap(MapMarker mapMarker, Map map) => new((float)(mapMarker.X * 42.0 / 2048 / map.SizeFactor * 100 + 1), (float)(mapMarker.Y * 42.0 / 2048 / map.SizeFactor * 100 + 1)); internal static Aetheryte? GetAetheryteForAethernet(Aetheryte aetheryte) => Svc.Data.GetExcelSheet<Aetheryte>()?.FirstOrDefault(x => x.IsAetheryte == true && x.AethernetGroup == aetheryte.AethernetGroup); internal static Aetheryte? GetClosestAethernet(uint territoryType, Vector3 location) { var closestDistance = float.MaxValue; Aetheryte? closestAetheryte = null; var map = Svc.Data.GetExcelSheet<TerritoryType>().GetRowOrDefault(territoryType)?.Map.Value; var aetherytes = Svc.Data.GetExcelSheet<Aetheryte>(); if (aetherytes == null || map == null) return null; foreach (var aetheryte in aetherytes) { if (( aetheryte.IsAetheryte && aetheryte.Territory.RowId != territoryType ) || aetheryte.Territory.ValueNullable == null || aetheryte.Territory.Value.RowId != territoryType) continue; MapMarker mapMarker = Svc.Data.GetSubrowExcelSheet<MapMarker>().AllRows().FirstOrDefault(m => m.DataType == 4 && m.DataKey.RowId == aetheryte.AethernetName.RowId); if (mapMarker.RowId > 0) { var distance = Vector2.Distance(ConvertWorldXZToMap(location.ToVector2(), map.Value), ConvertMarkerToMap(mapMarker, map.Value)); if (distance < closestDistance) { closestDistance = distance; closestAetheryte = aetheryte; } } } return closestAetheryte; } internal static Aetheryte? GetClosestAetheryte(uint territoryType, Vector3 location) { var closestDistance = float.MaxValue; Aetheryte? closestAetheryte = null; var map = Svc.Data.GetExcelSheet<TerritoryType>()?.GetRowOrDefault(territoryType)?.Map.Value; var aetherytes = Svc.Data.GetExcelSheet<Aetheryte>(); if (aetherytes == null || map == null) return null; foreach (var aetheryte in aetherytes) { if (!aetheryte.IsAetheryte || aetheryte.Territory.ValueNullable == null || aetheryte.Territory.Value.RowId != territoryType || aetheryte.PlaceName.ValueNullable == null) continue; var mapMarker = Svc.Data.GetSubrowExcelSheet<MapMarker>().Flatten().FirstOrDefault(m => m.DataType == 3 && m.DataKey.RowId == aetheryte.RowId); var distance = Vector2.Distance(ConvertWorldXZToMap(location.ToVector2(), map.Value), ConvertMarkerToMap(mapMarker, map.Value)); if (distance < closestDistance) { closestDistance = distance; closestAetheryte = aetheryte; } } return closestAetheryte; } internal static void MoveToMapMarker() { if (!IsFlagMarkerSet) { Svc.Log.Info("There is no flag marker set"); return; } Svc.Log.Info("Moving to Flag Marker"); State = ActionState.Running; Plugin.States |= PluginState.Other; if (!Plugin.States.HasFlag(PluginState.Looping)) Plugin.SetGeneralSettings(false); Svc.Framework.Update += MoveToMapMarkerUpdate; } internal static ActionState State = ActionState.None; private static Vector3? flagMapMarkerVector3 = Vector3.Zero; private static FlagMapMarker? flagMapMarker = null; internal static unsafe void StopMoveToMapMarker() { Svc.Framework.Update -= MoveToMapMarkerUpdate; VNavmesh_IPCSubscriber.Path_Stop(); State = ActionState.None; Plugin.States &= ~PluginState.Other; if (!Plugin.States.HasFlag(PluginState.Looping)) Plugin.SetGeneralSettings(true); flagMapMarker = null; } internal static unsafe void MoveToMapMarkerUpdate(IFramework _) { if (!EzThrottler.Throttle("MoveToMapMarker")) return; if (!PlayerHelper.IsReady) return; if (flagMapMarker != null && Svc.ClientState.TerritoryType == flagMapMarker.Value.TerritoryId && ObjectHelper.GetDistanceToPlayer(flagMapMarkerVector3!.Value) < 2) { StopMoveToMapMarker(); GotoHelper.ForceStop(); return; } if (flagMapMarker != null && Svc.ClientState.TerritoryType == flagMapMarker.Value.TerritoryId && flagMapMarkerVector3 != null && flagMapMarkerVector3.Value.Y == 0) { flagMapMarkerVector3 = VNavmesh_IPCSubscriber.Query_Mesh_PointOnFloor(new(flagMapMarker.Value.XFloat, 1024, flagMapMarker.Value.YFloat), false, 5); GotoHelper.ForceStop(); GotoHelper.Invoke(flagMapMarker.Value.TerritoryId, [flagMapMarkerVector3.Value], 0.25f, 0.25f, false, MovementHelper.IsFlyingSupported); return; } if (GotoHelper.State == ActionState.Running) return; if (VNavmesh_IPCSubscriber.Path_IsRunning()) return; if (GenericHelpers.TryGetAddonByName("AreaMap", out AtkUnitBase* addonAreaMap) && GenericHelpers.IsAddonReady(addonAreaMap)) addonAreaMap->Close(true); if (IsFlagMarkerSet) { flagMapMarker = GetFlagMarker; flagMapMarkerVector3 = new Vector3(flagMapMarker.Value.XFloat, 0, flagMapMarker.Value.YFloat); GotoHelper.Invoke(flagMapMarker.Value.TerritoryId, [flagMapMarkerVector3.Value], 0.25f, 0.25f, false, MovementHelper.IsFlyingSupported); } } } }
0
0.874172
1
0.874172
game-dev
MEDIA
0.878829
game-dev
0.96488
1
0.96488
ppy/osu
1,855
osu.Game/Overlays/SkinEditor/SkinSettingsToolbox.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Configuration; using osu.Game.Localisation; using osu.Game.Overlays.Settings; using osu.Game.Screens.Edit; using osu.Game.Screens.Edit.Components; using osuTK; namespace osu.Game.Overlays.SkinEditor { internal partial class SkinSettingsToolbox : EditorSidebarSection { [Resolved] private IEditorChangeHandler? changeHandler { get; set; } protected override Container<Drawable> Content { get; } private readonly Drawable component; public SkinSettingsToolbox(Drawable component) : base(SkinEditorStrings.Settings(component.GetType().Name)) { this.component = component; base.Content.Add(Content = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(10), }); } [BackgroundDependencyLoader] private void load() { var controls = component.CreateSettingsControls().ToArray(); Content.AddRange(controls); // track any changes to update undo states. foreach (var c in controls.OfType<ISettingsItem>()) { // TODO: SettingChanged is called too often for cases like SettingsTextBox and SettingsSlider. // We will want to expose a SettingCommitted or similar to make this work better. c.SettingChanged += () => changeHandler?.SaveState(); } } } }
0
0.801791
1
0.801791
game-dev
MEDIA
0.561765
game-dev,desktop-app
0.920422
1
0.920422
Eaglercraft-Archive/EaglercraftX-1.8-workspace
4,071
src/game/java/net/minecraft/world/pathfinder/SwimNodeProcessor.java
package net.minecraft.world.pathfinder; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.pathfinding.PathPoint; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; /**+ * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. * * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * * EaglercraftX 1.8 patch files (c) 2022-2025 lax1dude, ayunami2000. All Rights Reserved. * * 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. * */ public class SwimNodeProcessor extends NodeProcessor { public void initProcessor(IBlockAccess iblockaccess, Entity entity) { super.initProcessor(iblockaccess, entity); } /**+ * This method is called when all nodes have been processed and * PathEntity is created.\n {@link * net.minecraft.world.pathfinder.WalkNodeProcessor * WalkNodeProcessor} uses this to change its field {@link * net.minecraft.world.pathfinder.WalkNodeProcessor#avoidsWater * avoidsWater} */ public void postProcess() { super.postProcess(); } /**+ * Returns given entity's position as PathPoint */ public PathPoint getPathPointTo(Entity entity) { return this.openPoint(MathHelper.floor_double(entity.getEntityBoundingBox().minX), MathHelper.floor_double(entity.getEntityBoundingBox().minY + 0.5D), MathHelper.floor_double(entity.getEntityBoundingBox().minZ)); } /**+ * Returns PathPoint for given coordinates */ public PathPoint getPathPointToCoords(Entity entity, double d0, double d1, double d2) { return this.openPoint(MathHelper.floor_double(d0 - (double) (entity.width / 2.0F)), MathHelper.floor_double(d1 + 0.5D), MathHelper.floor_double(d2 - (double) (entity.width / 2.0F))); } public int findPathOptions(PathPoint[] apathpoint, Entity entity, PathPoint pathpoint, PathPoint pathpoint1, float f) { int i = 0; EnumFacing[] facings = EnumFacing._VALUES; for (int j = 0; j < facings.length; ++j) { EnumFacing enumfacing = facings[j]; PathPoint pathpoint2 = this.getSafePoint(entity, pathpoint.xCoord + enumfacing.getFrontOffsetX(), pathpoint.yCoord + enumfacing.getFrontOffsetY(), pathpoint.zCoord + enumfacing.getFrontOffsetZ()); if (pathpoint2 != null && !pathpoint2.visited && pathpoint2.distanceTo(pathpoint1) < f) { apathpoint[i++] = pathpoint2; } } return i; } /**+ * Returns a point that the entity can safely move to */ private PathPoint getSafePoint(Entity entityIn, int x, int y, int z) { int i = this.func_176186_b(entityIn, x, y, z); return i == -1 ? this.openPoint(x, y, z) : null; } private int func_176186_b(Entity entityIn, int x, int y, int z) { BlockPos blockpos$mutableblockpos = new BlockPos(); for (int i = x; i < x + this.entitySizeX; ++i) { for (int j = y; j < y + this.entitySizeY; ++j) { for (int k = z; k < z + this.entitySizeZ; ++k) { Block block = this.blockaccess.getBlockState(blockpos$mutableblockpos.func_181079_c(i, j, k)) .getBlock(); if (block.getMaterial() != Material.water) { return 0; } } } } return -1; } }
0
0.903248
1
0.903248
game-dev
MEDIA
0.968533
game-dev
0.952776
1
0.952776
magefree/mage
1,488
Mage.Sets/src/mage/cards/e/ElvishSkysweeper.java
package mage.cards.e; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.SacrificeTargetCost; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.DestroyTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.StaticFilters; import mage.target.TargetPermanent; import java.util.UUID; /** * @author Loki */ public final class ElvishSkysweeper extends CardImpl { public ElvishSkysweeper(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{G}"); this.subtype.add(SubType.ELF); this.subtype.add(SubType.WARRIOR); this.power = new MageInt(1); this.toughness = new MageInt(1); // {4}{G}, Sacrifice a creature: Destroy target creature with flying. Ability ability = new SimpleActivatedAbility(new DestroyTargetEffect(), new ManaCostsImpl<>("{4}{G}")); ability.addCost(new SacrificeTargetCost(StaticFilters.FILTER_PERMANENT_CREATURE)); ability.addTarget(new TargetPermanent(StaticFilters.FILTER_CREATURE_FLYING)); this.addAbility(ability); } private ElvishSkysweeper(final ElvishSkysweeper card) { super(card); } @Override public ElvishSkysweeper copy() { return new ElvishSkysweeper(this); } }
0
0.953904
1
0.953904
game-dev
MEDIA
0.957318
game-dev
0.995475
1
0.995475
FTL13/FTL13
4,247
code/_onclick/adjacent.dm
/* Adjacency proc for determining touch range This is mostly to determine if a user can enter a square for the purposes of touching something. Examples include reaching a square diagonally or reaching something on the other side of a glass window. This is calculated by looking for border items, or in the case of clicking diagonally from yourself, dense items. This proc will NOT notice if you are trying to attack a window on the other side of a dense object in its turf. There is a window helper for that. Note that in all cases the neighbor is handled simply; this is usually the user's mob, in which case it is up to you to check that the mob is not inside of something */ /atom/proc/Adjacent(atom/neighbor) // basic inheritance, unused return 0 // Not a sane use of the function and (for now) indicative of an error elsewhere /area/Adjacent(var/atom/neighbor) CRASH("Call to /area/Adjacent(), unimplemented proc") /* Adjacency (to turf): * If you are in the same turf, always true * If you are vertically/horizontally adjacent, ensure there are no border objects * If you are diagonally adjacent, ensure you can pass through at least one of the mutually adjacent square. * Passing through in this case ignores anything with the LETPASSTHROW pass flag, such as tables, racks, and morgue trays. */ /turf/Adjacent(atom/neighbor, atom/target = null, atom/movable/mover = null) var/turf/T0 = get_turf(neighbor) if(T0 == src) //same turf return 1 if(get_dist(src,T0) > 1) //too far return 0 // Non diagonal case if(T0.x == x || T0.y == y) // Check for border blockages return T0.ClickCross(get_dir(T0,src), border_only = 1, target_atom = target, mover = mover) && src.ClickCross(get_dir(src,T0), border_only = 1, target_atom = target, mover = mover) // Diagonal case var/in_dir = get_dir(T0,src) // eg. northwest (1+8) = 9 (00001001) var/d1 = in_dir&3 // eg. north (1+8)&3 (0000 0011) = 1 (0000 0001) var/d2 = in_dir&12 // eg. west (1+8)&12 (0000 1100) = 8 (0000 1000) for(var/d in list(d1,d2)) if(!T0.ClickCross(d, border_only = 1, target_atom = target, mover = mover)) continue // could not leave T0 in that direction var/turf/T1 = get_step(T0,d) if(!T1 || T1.density) continue if(!T1.ClickCross(get_dir(T1,src), border_only = 0, target_atom = target, mover = mover) || !T1.ClickCross(get_dir(T1,T0), border_only = 0, target_atom = target, mover = mover)) continue // couldn't enter or couldn't leave T1 if(!src.ClickCross(get_dir(src,T1), border_only = 1, target_atom = target, mover = mover)) continue // could not enter src return 1 // we don't care about our own density return 0 /* Adjacency (to anything else): * Must be on a turf */ /atom/movable/Adjacent(var/atom/neighbor) if(neighbor == loc) return TRUE if(!isturf(loc)) return FALSE if(loc.Adjacent(neighbor,target = neighbor, mover = src)) return TRUE return FALSE // This is necessary for storage items not on your person. /obj/item/Adjacent(var/atom/neighbor, var/recurse = 1) if(neighbor == loc) return 1 if(isitem(loc)) if(recurse > 0) return loc.Adjacent(neighbor,recurse - 1) return 0 return ..() /* This checks if you there is uninterrupted airspace between that turf and this one. This is defined as any dense ON_BORDER object, or any dense object without LETPASSTHROW. The border_only flag allows you to not objects (for source and destination squares) */ /turf/proc/ClickCross(target_dir, border_only, target_atom = null, atom/movable/mover = null) for(var/obj/O in src) if((mover && O.CanPass(mover,get_step(src,target_dir))) || (!mover && !O.density)) continue if(O == target_atom || (O.pass_flags & LETPASSTHROW)) //check if there's a dense object present on the turf continue // LETPASSTHROW is used for anything you can click through (or the firedoor special case, see above) if( O.flags&ON_BORDER) // windows are on border, check them first if( O.dir & target_dir || O.dir & (O.dir-1) ) // full tile windows are just diagonals mechanically return 0 //O.dir&(O.dir-1) is false for any cardinal direction, but true for diagonal ones else if( !border_only ) // dense, not on border, cannot pass over return 0 return 1
0
0.969524
1
0.969524
game-dev
MEDIA
0.84811
game-dev
0.974804
1
0.974804
modernuo/ModernUO
3,816
Projects/UOContent/Engines/Plants/EmptyTheBowlGump.cs
using Server.Engines.Help; using Server.Gumps; using Server.Network; namespace Server.Engines.Plants { public class EmptyTheBowlGump : Gump { private readonly PlantItem m_Plant; public EmptyTheBowlGump(PlantItem plant) : base(20, 20) { m_Plant = plant; DrawBackground(); AddLabel(90, 70, 0x44, "Empty the bowl?"); DrawPicture(); AddButton(98, 150, 0x47E, 0x480, 1); // Cancel AddButton(138, 151, 0xD2, 0xD2, 2); // Help AddLabel(143, 151, 0x835, "?"); AddButton(168, 150, 0x481, 0x483, 3); // Ok } private void DrawBackground() { AddBackground(50, 50, 200, 150, 0xE10); AddItem(45, 45, 0xCEF); AddItem(45, 118, 0xCF0); AddItem(211, 45, 0xCEB); AddItem(211, 118, 0xCEC); } private void DrawPicture() { AddItem(90, 100, 0x1602); AddImage(140, 102, 0x15E1); AddItem(160, 100, 0x15FD); if (m_Plant.PlantStatus != PlantStatus.BowlOfDirt && m_Plant.PlantStatus < PlantStatus.Plant) { AddItem(156, 130, 0xDCF); // Seed } } public override void OnResponse(NetState sender, in RelayInfo info) { var from = sender.Mobile; if (info.ButtonID == 0 || m_Plant.Deleted || m_Plant.PlantStatus >= PlantStatus.DecorativePlant) { return; } if (info.ButtonID == 3 && !from.InRange(m_Plant.GetWorldLocation(), 3)) { from.LocalOverheadMessage(MessageType.Regular, 0x3E9, 500446); // That is too far away. return; } if (!m_Plant.IsUsableBy(from)) { m_Plant.LabelTo(from, 1061856); // You must have the item in your backpack or locked down in order to use it. return; } switch (info.ButtonID) { case 1: // Cancel { from.SendGump(new MainPlantGump(m_Plant)); break; } case 2: // Help { from.NetState.SendDisplayHelpTopic(HelpTopic.EmptyingBowl); from.SendGump(new EmptyTheBowlGump(m_Plant)); break; } case 3: // Ok { var bowl = new PlantBowl(); if (!from.PlaceInBackpack(bowl)) { bowl.Delete(); m_Plant.LabelTo(from, 1053047); // You cannot empty a bowl with a full pack! from.SendGump(new MainPlantGump(m_Plant)); break; } if (m_Plant.PlantStatus != PlantStatus.BowlOfDirt && m_Plant.PlantStatus < PlantStatus.Plant) { var seed = new Seed(m_Plant.PlantType, m_Plant.PlantHue, m_Plant.ShowType); if (!from.PlaceInBackpack(seed)) { bowl.Delete(); seed.Delete(); m_Plant.LabelTo(from, 1053047); // You cannot empty a bowl with a full pack! from.SendGump(new MainPlantGump(m_Plant)); break; } } m_Plant.Delete(); break; } } } } }
0
0.53859
1
0.53859
game-dev
MEDIA
0.650626
game-dev
0.739454
1
0.739454
Special-K-s-Flightsim-Bots/DCSServerBot
7,593
plugins/slotblocking/lua/callbacks.lua
local base = _G local dcsbot = base.dcsbot local utils = base.require("DCSServerBotUtils") local slotblock = slotblock or {} local function has_value(tab, value) if not tab then return false end for idx1, value1 in ipairs(tab) do if type(value) == "table" then for idx2, value2 in ipairs(value) do if value1 == value2 then return true end end elseif value1 == value then return true end end return false end local function is_vip(ucid) if not dcsbot.params then return false end local cfg = dcsbot.params['slotblocking']['VIP'] if not cfg then return false end if cfg['ucid'] and has_value(cfg['ucid'], ucid) then return true end if cfg['discord'] and dcsbot.userInfo[ucid].roles ~= nil and has_value(cfg['discord'], dcsbot.userInfo[ucid].roles) then return true end return false end function slotblock.onPlayerTryConnect(addr, name, ucid, playerID) if playerID == 1 then return end log.write('DCSServerBot', log.DEBUG, 'Slotblocking: onPlayerTryConnect()') if not dcsbot.params or not dcsbot.params['slotblocking'] then return end local cfg = dcsbot.params['slotblocking']['VIP'] if not cfg then return end if cfg['slots'] then local max = tonumber(utils.loadSettingsRaw()['maxPlayers']) local current = #net.get_player_list() + 1 if current >= (max - tonumber(cfg['slots'])) then if not is_vip(ucid) then return false, cfg['message_server_full'] or 'The server is full, please try again later!' end end end end function restrict_slots(playerID, side, slotID) local player = net.get_player_info(playerID, 'ucid') local unit_name = DCS.getUnitProperty(slotID, DCS.UNIT_NAME) local group_name = DCS.getUnitProperty(slotID, DCS.UNIT_GROUPNAME) local unit_type = DCS.getUnitType(slotID) local points -- check levels if any for id, unit in pairs(dcsbot.params['slotblocking']['restricted']) do local is_unit_type_match = (unit['unit_type'] and unit['unit_type'] == unit_type) or (unit['unit_type'] == 'dynamic' and utils.isDynamic(slotID)) local is_unit_name_match = unit['unit_name'] and string.match(unit_name, unit['unit_name']) local is_group_name_match = unit['group_name'] and string.match(group_name, unit['group_name']) local is_side = (tonumber(unit['side']) or side) == side if is_side and (is_unit_type_match or is_unit_name_match or is_group_name_match) then -- blocking slots by points // check multicrew if tonumber(slotID) then points = tonumber(unit['points']) else points = tonumber(unit['crew']) end if points then if not dcsbot.userInfo[player].points then log.write('DCSServerBot', log.ERROR, 'Slotblocking: User has no points, but points are configured. Check your creditsystem.yaml and make sure a campaign is running.') return end if dcsbot.userInfo[player].points < points then local message = 'You need at least ' .. points .. ' points to enter this slot. You currently have ' .. dcsbot.userInfo[player].points .. ' points.' net.send_chat_to(message, playerID) return false end end if unit['ucid'] and player ~= unit['ucid'] then local message = unit['message'] or 'This slot is only accessible to a certain user.' net.send_chat_to(message, playerID) return false elseif unit['ucids'] and not has_value(unit['ucids'], player) then local message = unit['message'] or 'This slot is only accessible to certain users.' net.send_chat_to(message, playerID) return false -- blocking slots by discord groups elseif unit['discord'] and not has_value(unit['discord'], dcsbot.userInfo[player].roles) then local message = unit['message'] or 'This slot is only accessible to members with a specific Discord role.' net.send_chat_to(message, playerID) return false elseif unit['VIP'] and not is_vip(player) then local message = unit['message'] or 'This slot is only accessible to VIP users.' net.send_chat_to(message, playerID) return false end end end end function calculate_balance(numPlayersBlue, numPlayersRed, blue_vs_red) local total = numPlayersBlue + numPlayersRed local balance if total ~= 0 then balance = numPlayersBlue / total else balance = blue_vs_red end return balance end function balance_slots(playerID, side, slotID) local config = dcsbot.params['slotblocking']['balancing'] local blue_vs_red = config['blue_vs_red'] or 0.5 local threshold = config['threshold'] or 0.1 local activation_threshold = tonumber(config['activation_threshold'] or 0) local message = config['message'] or 'You need to take a slot of the opposite coalition to keep the balance!' local players = net.get_player_list() local numPlayersBlue = 0 local numPlayersRed = 0 log.write('DCSServerBot', log.DEBUG, 'Slotblocking: balance_slots()') if #players < activation_threshold then log.write('DCSServerBot', log.DEBUG, 'Slotblocking: activation_threshold not reached') return end for _, id in base.pairs(players) do local side = net.get_player_info(id, 'side') local _, slot, sub_slot = utils.getMulticrewAllParameters(id) -- only count real seats if sub_slot == 0 and slot ~= -1 then if side == 2 then numPlayersBlue = numPlayersBlue + 1 end if side == 1 then numPlayersRed = numPlayersRed + 1 end end end local balance = calculate_balance(numPlayersBlue, numPlayersRed, blue_vs_red) log.write('DCSServerBot', log.DEBUG, 'Slotblocking: balance: ' .. tostring(balance)) if (side == 2 and balance > blue_vs_red + threshold) or (side == 1 and balance < blue_vs_red - threshold) then net.send_chat_to(message, playerID) return false end end function slotblock.onPlayerTryChangeSlot(playerID, side, slotID) log.write('DCSServerBot', log.DEBUG, 'Slotblocking: onPlayerTryChangeSlot()') -- we will not block spectator slots if side == 0 then return end if not dcsbot.params or not dcsbot.params['slotblocking'] then log.write('DCSServerBot', log.ERROR, 'Slotblocking: No configuration found, skipping.') return end -- check slot restrictions by role and points if dcsbot.params['slotblocking']['restricted'] then if restrict_slots(playerID, side, slotID) == false then return false end end -- check slot restrictions by balance local old_side = net.get_player_info(playerID, 'side') -- if not side change happens or they want in a sub-slot, do not run balancing if old_side ~= side and tonumber(slotID) and dcsbot.params['slotblocking']['balancing'] then return balance_slots(playerID, side, slotID) end end DCS.setUserCallbacks(slotblock)
0
0.885909
1
0.885909
game-dev
MEDIA
0.585571
game-dev,networking
0.983096
1
0.983096
FlaxEngine/FlaxEngine
33,083
Source/Engine/Physics/Physics.h
// Copyright (c) Wojciech Figat. All rights reserved. #pragma once #include "Engine/Core/Math/Quaternion.h" #include "Types.h" /// <summary> /// Physics simulation system. /// </summary> API_CLASS(Static) class FLAXENGINE_API Physics { DECLARE_SCRIPTING_TYPE_NO_SPAWN(Physics); /// <summary> /// The default physics scene. /// </summary> API_FIELD(ReadOnly) static PhysicsScene* DefaultScene; /// <summary> /// List with all physics scenes (readonly). /// </summary> API_FIELD(ReadOnly) static Array<PhysicsScene*, HeapAllocation> Scenes; /// <summary> /// Finds an existing <see cref="PhysicsScene"/> or creates it if it does not exist. /// </summary> API_FUNCTION() static PhysicsScene* FindOrCreateScene(const StringView& name); /// <summary> /// Finds an existing scene. /// </summary> API_FUNCTION() static PhysicsScene* FindScene(const StringView& name); public: /// <summary> /// The automatic simulation feature. True if perform physics simulation after on fixed update by auto, otherwise user should do it. /// </summary> API_PROPERTY() static bool GetAutoSimulation(); /// <summary> /// Gets the current gravity force. /// </summary> API_PROPERTY(Attributes="DebugCommand") static Vector3 GetGravity(); /// <summary> /// Sets the current gravity force. /// </summary> API_PROPERTY() static void SetGravity(const Vector3& value); /// <summary> /// Gets the CCD feature enable flag. /// </summary> API_PROPERTY() static bool GetEnableCCD(); /// <summary> /// Sets the CCD feature enable flag. /// </summary> API_PROPERTY() static void SetEnableCCD(bool value); /// <summary> /// Gets the minimum relative velocity required for an object to bounce. /// </summary> API_PROPERTY() static float GetBounceThresholdVelocity(); /// <summary> /// Sets the minimum relative velocity required for an object to bounce. /// </summary> API_PROPERTY() static void SetBounceThresholdVelocity(float value); /// <summary> /// The collision layers masks. Used to define layer-based collision detection. /// </summary> static uint32 LayerMasks[32]; public: /// <summary> /// Called during main engine loop to start physic simulation. Use CollectResults after. /// </summary> /// <param name="dt">The delta time (in seconds).</param> API_FUNCTION() static void Simulate(float dt); /// <summary> /// Called during main engine loop to collect physic simulation results and apply them as well as fire collision events. /// </summary> API_FUNCTION() static void CollectResults(); /// <summary> /// Checks if physical simulation is running. /// </summary> API_PROPERTY() static bool IsDuringSimulation(); /// <summary> /// Flushes any latent physics actions (eg. object destroy, actor add/remove to the scene, etc.). /// </summary> API_FUNCTION() static void FlushRequests(); public: /// <summary> /// Performs a line between two points in the scene. /// </summary> /// <param name="start">The start position of the line.</param> /// <param name="end">The end position of the line.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if ray hits an matching object, otherwise false.</returns> API_FUNCTION() static bool LineCast(const Vector3& start, const Vector3& end, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a line between two points in the scene. /// </summary> /// <param name="start">The start position of the line.</param> /// <param name="end">The end position of the line.</param> /// <param name="hitInfo">The result hit information. Valid only when method returns true.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if ray hits an matching object, otherwise false.</returns> API_FUNCTION() static bool LineCast(const Vector3& start, const Vector3& end, API_PARAM(Out) RayCastHit& hitInfo, uint32 layerMask = MAX_uint32, bool hitTriggers = true); // <summary> /// Performs a line between two points in the scene, returns all hitpoints infos. /// </summary> /// <param name="start">The origin of the ray.</param> /// <param name="end">The end position of the line.</param> /// <param name="results">The result hits. Valid only when method returns true.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if ray hits an matching object, otherwise false.</returns> API_FUNCTION() static bool LineCastAll(const Vector3& start, const Vector3& end, API_PARAM(Out) Array<RayCastHit, HeapAllocation>& results, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a raycast against objects in the scene. /// </summary> /// <param name="origin">The origin of the ray.</param> /// <param name="direction">The normalized direction of the ray.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if ray hits an matching object, otherwise false.</returns> API_FUNCTION() static bool RayCast(const Vector3& origin, const Vector3& direction, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a raycast against objects in the scene, returns results in a RayCastHit structure. /// </summary> /// <param name="origin">The origin of the ray.</param> /// <param name="direction">The normalized direction of the ray.</param> /// <param name="hitInfo">The result hit information. Valid only when method returns true.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if ray hits an matching object, otherwise false.</returns> API_FUNCTION() static bool RayCast(const Vector3& origin, const Vector3& direction, API_PARAM(Out) RayCastHit& hitInfo, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a raycast against objects in the scene, returns results in a RayCastHit structure. /// </summary> /// <param name="origin">The origin of the ray.</param> /// <param name="direction">The normalized direction of the ray.</param> /// <param name="results">The result hits. Valid only when method returns true.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if ray hits an matching object, otherwise false.</returns> API_FUNCTION() static bool RayCastAll(const Vector3& origin, const Vector3& direction, API_PARAM(Out) Array<RayCastHit, HeapAllocation>& results, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a sweep test against objects in the scene using a box geometry. /// </summary> /// <param name="center">The box center.</param> /// <param name="halfExtents">The half size of the box in each direction.</param> /// <param name="direction">The normalized direction in which cast a box.</param> /// <param name="rotation">The box rotation.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if box hits an matching object, otherwise false.</returns> API_FUNCTION() static bool BoxCast(const Vector3& center, const Vector3& halfExtents, const Vector3& direction, const Quaternion& rotation = Quaternion::Identity, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a sweep test against objects in the scene using a box geometry. /// </summary> /// <param name="center">The box center.</param> /// <param name="halfExtents">The half size of the box in each direction.</param> /// <param name="direction">The normalized direction in which cast a box.</param> /// <param name="hitInfo">The result hit information. Valid only when method returns true.</param> /// <param name="rotation">The box rotation.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if box hits an matching object, otherwise false.</returns> API_FUNCTION() static bool BoxCast(const Vector3& center, const Vector3& halfExtents, const Vector3& direction, API_PARAM(Out) RayCastHit& hitInfo, const Quaternion& rotation = Quaternion::Identity, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a sweep test against objects in the scene using a box geometry. /// </summary> /// <param name="center">The box center.</param> /// <param name="halfExtents">The half size of the box in each direction.</param> /// <param name="direction">The normalized direction in which cast a box.</param> /// <param name="results">The result hits. Valid only when method returns true.</param> /// <param name="rotation">The box rotation.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if box hits an matching object, otherwise false.</returns> API_FUNCTION() static bool BoxCastAll(const Vector3& center, const Vector3& halfExtents, const Vector3& direction, API_PARAM(Out) Array<RayCastHit, HeapAllocation>& results, const Quaternion& rotation = Quaternion::Identity, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a sweep test against objects in the scene using a sphere geometry. /// </summary> /// <param name="center">The sphere center.</param> /// <param name="radius">The radius of the sphere.</param> /// <param name="direction">The normalized direction in which cast a sphere.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if sphere hits an matching object, otherwise false.</returns> API_FUNCTION() static bool SphereCast(const Vector3& center, float radius, const Vector3& direction, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a sweep test against objects in the scene using a sphere geometry. /// </summary> /// <param name="center">The sphere center.</param> /// <param name="radius">The radius of the sphere.</param> /// <param name="direction">The normalized direction in which cast a sphere.</param> /// <param name="hitInfo">The result hit information. Valid only when method returns true.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if sphere hits an matching object, otherwise false.</returns> API_FUNCTION() static bool SphereCast(const Vector3& center, float radius, const Vector3& direction, API_PARAM(Out) RayCastHit& hitInfo, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a sweep test against objects in the scene using a sphere geometry. /// </summary> /// <param name="center">The sphere center.</param> /// <param name="radius">The radius of the sphere.</param> /// <param name="direction">The normalized direction in which cast a sphere.</param> /// <param name="results">The result hits. Valid only when method returns true.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if sphere hits an matching object, otherwise false.</returns> API_FUNCTION() static bool SphereCastAll(const Vector3& center, float radius, const Vector3& direction, API_PARAM(Out) Array<RayCastHit, HeapAllocation>& results, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a sweep test against objects in the scene using a capsule geometry. /// </summary> /// <param name="center">The capsule center.</param> /// <param name="radius">The radius of the capsule.</param> /// <param name="height">The height of the capsule, excluding the top and bottom spheres.</param> /// <param name="direction">The normalized direction in which cast a capsule.</param> /// <param name="rotation">The capsule rotation.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if capsule hits an matching object, otherwise false.</returns> API_FUNCTION() static bool CapsuleCast(const Vector3& center, float radius, float height, const Vector3& direction, const Quaternion& rotation = Quaternion::Identity, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a sweep test against objects in the scene using a capsule geometry. /// </summary> /// <param name="center">The capsule center.</param> /// <param name="radius">The radius of the capsule.</param> /// <param name="height">The height of the capsule, excluding the top and bottom spheres.</param> /// <param name="direction">The normalized direction in which cast a capsule.</param> /// <param name="hitInfo">The result hit information. Valid only when method returns true.</param> /// <param name="rotation">The capsule rotation.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if capsule hits an matching object, otherwise false.</returns> API_FUNCTION() static bool CapsuleCast(const Vector3& center, float radius, float height, const Vector3& direction, API_PARAM(Out) RayCastHit& hitInfo, const Quaternion& rotation = Quaternion::Identity, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a sweep test against objects in the scene using a capsule geometry. /// </summary> /// <param name="center">The capsule center.</param> /// <param name="radius">The radius of the capsule.</param> /// <param name="height">The height of the capsule, excluding the top and bottom spheres.</param> /// <param name="direction">The normalized direction in which cast a capsule.</param> /// <param name="results">The result hits. Valid only when method returns true.</param> /// <param name="rotation">The capsule rotation.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if capsule hits an matching object, otherwise false.</returns> API_FUNCTION() static bool CapsuleCastAll(const Vector3& center, float radius, float height, const Vector3& direction, API_PARAM(Out) Array<RayCastHit, HeapAllocation>& results, const Quaternion& rotation = Quaternion::Identity, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a sweep test against objects in the scene using a convex mesh. /// </summary> /// <param name="center">The convex mesh center.</param> /// <param name="convexMesh">Collision data of the convex mesh.</param> /// <param name="scale">The scale of the convex mesh.</param> /// <param name="direction">The normalized direction in which cast a convex mesh.</param> /// <param name="rotation">The convex mesh rotation.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if convex mesh hits an matching object, otherwise false.</returns> API_FUNCTION() static bool ConvexCast(const Vector3& center, const CollisionData* convexMesh, const Vector3& scale, const Vector3& direction, const Quaternion& rotation = Quaternion::Identity, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a sweep test against objects in the scene using a convex mesh. /// </summary> /// <param name="center">The convex mesh center.</param> /// <param name="convexMesh">Collision data of the convex mesh.</param> /// <param name="scale">The scale of the convex mesh.</param> /// <param name="direction">The normalized direction in which cast a convex mesh.</param> /// <param name="hitInfo">The result hit information. Valid only when method returns true.</param> /// <param name="rotation">The convex mesh rotation.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if convex mesh hits an matching object, otherwise false.</returns> API_FUNCTION() static bool ConvexCast(const Vector3& center, const CollisionData* convexMesh, const Vector3& scale, const Vector3& direction, API_PARAM(Out) RayCastHit& hitInfo, const Quaternion& rotation = Quaternion::Identity, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Performs a sweep test against objects in the scene using a convex mesh. /// </summary> /// <param name="center">The convex mesh center.</param> /// <param name="convexMesh">Collision data of the convex mesh.</param> /// <param name="scale">The scale of the convex mesh.</param> /// <param name="direction">The normalized direction in which cast a convex mesh.</param> /// <param name="results">The result hits. Valid only when method returns true.</param> /// <param name="rotation">The convex mesh rotation.</param> /// <param name="maxDistance">The maximum distance the ray should check for collisions.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if convex mesh hits an matching object, otherwise false.</returns> API_FUNCTION() static bool ConvexCastAll(const Vector3& center, const CollisionData* convexMesh, const Vector3& scale, const Vector3& direction, API_PARAM(Out) Array<RayCastHit, HeapAllocation>& results, const Quaternion& rotation = Quaternion::Identity, float maxDistance = MAX_float, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Checks whether the given box overlaps with other colliders or not. /// </summary> /// <param name="center">The box center.</param> /// <param name="halfExtents">The half size of the box in each direction.</param> /// <param name="rotation">The box rotation.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if box overlaps any matching object, otherwise false.</returns> API_FUNCTION() static bool CheckBox(const Vector3& center, const Vector3& halfExtents, const Quaternion& rotation = Quaternion::Identity, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Checks whether the given sphere overlaps with other colliders or not. /// </summary> /// <param name="center">The sphere center.</param> /// <param name="radius">The radius of the sphere.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if sphere overlaps any matching object, otherwise false.</returns> API_FUNCTION() static bool CheckSphere(const Vector3& center, float radius, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Checks whether the given capsule overlaps with other colliders or not. /// </summary> /// <param name="center">The capsule center.</param> /// <param name="radius">The radius of the capsule.</param> /// <param name="height">The height of the capsule, excluding the top and bottom spheres.</param> /// <param name="rotation">The capsule rotation.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if capsule overlaps any matching object, otherwise false.</returns> API_FUNCTION() static bool CheckCapsule(const Vector3& center, float radius, float height, const Quaternion& rotation = Quaternion::Identity, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Checks whether the given convex mesh overlaps with other colliders or not. /// </summary> /// <param name="center">The convex mesh center.</param> /// <param name="convexMesh">Collision data of the convex mesh.</param> /// <param name="scale">The scale of the convex mesh.</param> /// <param name="rotation">The convex mesh rotation.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if convex mesh overlaps any matching object, otherwise false.</returns> API_FUNCTION() static bool CheckConvex(const Vector3& center, const CollisionData* convexMesh, const Vector3& scale, const Quaternion& rotation = Quaternion::Identity, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Finds all colliders touching or inside of the given box. /// </summary> /// <param name="center">The box center.</param> /// <param name="halfExtents">The half size of the box in each direction.</param> /// <param name="rotation">The box rotation.</param> /// <param name="results">The result colliders that overlap with the given box. Valid only when method returns true.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if box overlaps any matching object, otherwise false.</returns> API_FUNCTION() static bool OverlapBox(const Vector3& center, const Vector3& halfExtents, API_PARAM(Out) Array<Collider*, HeapAllocation>& results, const Quaternion& rotation = Quaternion::Identity, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Finds all colliders touching or inside of the given sphere. /// </summary> /// <param name="center">The sphere center.</param> /// <param name="radius">The radius of the sphere.</param> /// <param name="results">The result colliders that overlap with the given sphere. Valid only when method returns true.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if sphere overlaps any matching object, otherwise false.</returns> API_FUNCTION() static bool OverlapSphere(const Vector3& center, float radius, API_PARAM(Out) Array<Collider*, HeapAllocation>& results, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Finds all colliders touching or inside of the given capsule. /// </summary> /// <param name="center">The capsule center.</param> /// <param name="radius">The radius of the capsule.</param> /// <param name="height">The height of the capsule, excluding the top and bottom spheres.</param> /// <param name="results">The result colliders that overlap with the given capsule. Valid only when method returns true.</param> /// <param name="rotation">The capsule rotation.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if capsule overlaps any matching object, otherwise false.</returns> API_FUNCTION() static bool OverlapCapsule(const Vector3& center, float radius, float height, API_PARAM(Out) Array<Collider*, HeapAllocation>& results, const Quaternion& rotation = Quaternion::Identity, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Finds all colliders touching or inside of the given convex mesh. /// </summary> /// <param name="center">The convex mesh center.</param> /// <param name="convexMesh">Collision data of the convex mesh.</param> /// <param name="scale">The scale of the convex mesh.</param> /// <param name="results">The result colliders that overlap with the given convex mesh. Valid only when method returns true.</param> /// <param name="rotation">The convex mesh rotation.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if convex mesh overlaps any matching object, otherwise false.</returns> API_FUNCTION() static bool OverlapConvex(const Vector3& center, const CollisionData* convexMesh, const Vector3& scale, API_PARAM(Out) Array<Collider*, HeapAllocation>& results, const Quaternion& rotation = Quaternion::Identity, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Finds all colliders touching or inside of the given box. /// </summary> /// <param name="center">The box center.</param> /// <param name="halfExtents">The half size of the box in each direction.</param> /// <param name="rotation">The box rotation.</param> /// <param name="results">The result colliders that overlap with the given box. Valid only when method returns true.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if box overlaps any matching object, otherwise false.</returns> API_FUNCTION() static bool OverlapBox(const Vector3& center, const Vector3& halfExtents, API_PARAM(Out) Array<PhysicsColliderActor*, HeapAllocation>& results, const Quaternion& rotation = Quaternion::Identity, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Finds all colliders touching or inside of the given sphere. /// </summary> /// <param name="center">The sphere center.</param> /// <param name="radius">The radius of the sphere.</param> /// <param name="results">The result colliders that overlap with the given sphere. Valid only when method returns true.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if sphere overlaps any matching object, otherwise false.</returns> API_FUNCTION() static bool OverlapSphere(const Vector3& center, float radius, API_PARAM(Out) Array<PhysicsColliderActor*, HeapAllocation>& results, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Finds all colliders touching or inside of the given capsule. /// </summary> /// <param name="center">The capsule center.</param> /// <param name="radius">The radius of the capsule.</param> /// <param name="height">The height of the capsule, excluding the top and bottom spheres.</param> /// <param name="results">The result colliders that overlap with the given capsule. Valid only when method returns true.</param> /// <param name="rotation">The capsule rotation.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if capsule overlaps any matching object, otherwise false.</returns> API_FUNCTION() static bool OverlapCapsule(const Vector3& center, float radius, float height, API_PARAM(Out) Array<PhysicsColliderActor*, HeapAllocation>& results, const Quaternion& rotation = Quaternion::Identity, uint32 layerMask = MAX_uint32, bool hitTriggers = true); /// <summary> /// Finds all colliders touching or inside of the given convex mesh. /// </summary> /// <param name="center">The convex mesh center.</param> /// <param name="convexMesh">Collision data of the convex mesh.</param> /// <param name="scale">The scale of the convex mesh.</param> /// <param name="results">The result colliders that overlap with the given convex mesh. Valid only when method returns true.</param> /// <param name="rotation">The convex mesh rotation.</param> /// <param name="layerMask">The layer mask used to filter the results.</param> /// <param name="hitTriggers">If set to <c>true</c> triggers will be hit, otherwise will skip them.</param> /// <returns>True if convex mesh overlaps any matching object, otherwise false.</returns> API_FUNCTION() static bool OverlapConvex(const Vector3& center, const CollisionData* convexMesh, const Vector3& scale, API_PARAM(Out) Array<PhysicsColliderActor*, HeapAllocation>& results, const Quaternion& rotation = Quaternion::Identity, uint32 layerMask = MAX_uint32, bool hitTriggers = true); };
0
0.93375
1
0.93375
game-dev
MEDIA
0.68668
game-dev
0.810203
1
0.810203
OpenBMB/AgentVerse
2,650
ui/src/phaser3-rex-plugins/plugins/utils/grid/hexagon/CubeTransfer.js
import CONST from './const.js'; const ODD_R = CONST.ODD_R; const EVEN_R = CONST.EVEN_R; const ODD_Q = CONST.ODD_Q; const EVEN_Q = CONST.EVEN_Q; var cr2cube = function (mode, col, row, out) { if (out === undefined) { out = {}; } else if (out === true) { out = globCube; } switch (mode) { case ODD_R: out.x = col - (row - (row & 1)) / 2; out.z = row; break; case EVEN_R: out.x = col - (row + (row & 1)) / 2; out.z = row; break; case ODD_Q: out.x = col; out.z = row - (col - (col & 1)) / 2; break; case EVEN_Q: out.x = col; out.z = row - (col + (col & 1)) / 2; break; } out.y = -out.x - out.z; return out; } var roundcube = function (x, y, z, out) { if (typeof (x) !== 'number') { out = x; x = out.x; y = out.y; z = out.z; } if (out === undefined) { out = {}; } else if (out === true) { out = globCube; } var rx = Math.round(x); var ry = Math.round(y); var rz = Math.round(z); var dx = Math.abs(rx - x); var dy = Math.abs(ry - y); var dz = Math.abs(rz - z); if ((dx > dy) && (dx > dz)) { rx = -ry - rz; } else if (dy > dz) { ry = -rx - rz; } else { rz = -rx - ry; } out.x = rx; out.y = ry; out.z = rz; return out; } var cube2cr = function (mode, x, y, z, out) { if (out === undefined) { out = {}; } else if (out === true) { out = globCR; } switch (mode) { case ODD_R: out.x = x + (z - (z & 1)) / 2; out.y = z; break; case EVEN_R: out.x = x + (z + (z & 1)) / 2; out.y = z; break; case ODD_Q: out.x = x; out.y = z + (x - (x & 1)) / 2; break; case EVEN_Q: out.x = x; out.y = z + (x + (x & 1)) / 2; break; } return out; } var qr2cube = function (q, r, out) { if (out === undefined) { out = {} } else if (out === true) { out = globCube; } out.x = q; out.y = -q - r; out.z = r; return out; } var cube2qr = function (x, y, z, out) { if (out === undefined) { out = {} } else if (out === true) { out = globQR; } out.q = x; out.r = z; return out; } var globCube = {}; var globCR = {}; var globQR = {}; export { cr2cube, roundcube, cube2cr, qr2cube, cube2qr, };
0
0.722144
1
0.722144
game-dev
MEDIA
0.484574
game-dev
0.666183
1
0.666183
Ragebones/StormCore
2,392
src/server/game/Server/Packets/BattlenetPackets.cpp
/* * Copyright (C) 2014-2017 StormCore * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "BattlenetPackets.h" ByteBuffer& operator<<(ByteBuffer& data, WorldPackets::Battlenet::MethodCall const& method) { data << uint64(method.Type); data << uint64(method.ObjectId); data << uint32(method.Token); return data; } ByteBuffer& operator>>(ByteBuffer& data, WorldPackets::Battlenet::MethodCall& method) { data >> method.Type; data >> method.ObjectId; data >> method.Token; return data; } WorldPacket const* WorldPackets::Battlenet::Notification::Write() { _worldPacket << Method; _worldPacket << uint32(Data.size()); _worldPacket.append(Data); return &_worldPacket; } WorldPacket const* WorldPackets::Battlenet::Response::Write() { _worldPacket << uint32(BnetStatus); _worldPacket << Method; _worldPacket << uint32(Data.size()); _worldPacket.append(Data); return &_worldPacket; } WorldPacket const* WorldPackets::Battlenet::SetSessionState::Write() { _worldPacket.WriteBits(State, 2); _worldPacket.FlushBits(); return &_worldPacket; } WorldPacket const* WorldPackets::Battlenet::RealmListTicket::Write() { _worldPacket << uint32(Token); _worldPacket.WriteBit(Allow); _worldPacket << uint32(Ticket.size()); _worldPacket.append(Ticket); return &_worldPacket; } void WorldPackets::Battlenet::Request::Read() { uint32 protoSize; _worldPacket >> Method; _worldPacket >> protoSize; Data.Resize(protoSize); _worldPacket.read(Data.GetWritePointer(), Data.GetRemainingSpace()); Data.WriteCompleted(protoSize); } void WorldPackets::Battlenet::RequestRealmListTicket::Read() { _worldPacket >> Token; _worldPacket.read(Secret.data(), Secret.size()); }
0
0.808629
1
0.808629
game-dev
MEDIA
0.473222
game-dev
0.542854
1
0.542854
CyberdyneCC/Thermos
3,602
patches/org/bukkit/command/defaults/VersionCommand.java.patch
--- ../src-base/minecraft/org/bukkit/command/defaults/VersionCommand.java +++ ../src-work/minecraft/org/bukkit/command/defaults/VersionCommand.java @@ -29,43 +29,19 @@ if (!testPermission(sender)) return true; if (args.length == 0) { - sender.sendMessage("This server is running " + Bukkit.getName() + " version " + Bukkit.getVersion() + " (Implementing API version " + Bukkit.getBukkitVersion() + ")"); + sender.sendMessage("This server is running Thermos | https://github.com/CyberdyneCC/Thermos | " + Bukkit.getBukkitVersion() + " | " + Bukkit.getVersion()); } else { - StringBuilder name = new StringBuilder(); - for (String arg : args) { - if (name.length() > 0) { - name.append(' '); - } - - name.append(arg); + if (true) { + sender.sendMessage("This server is not running any plugins."); } - - String pluginName = name.toString(); - Plugin exactPlugin = Bukkit.getPluginManager().getPlugin(pluginName); - if (exactPlugin != null) { - describeToSender(exactPlugin, sender); - return true; - } - - boolean found = false; - pluginName = pluginName.toLowerCase(); - for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - if (plugin.getName().toLowerCase().contains(pluginName)) { - describeToSender(plugin, sender); - found = true; - } - } - - if (!found) { - sender.sendMessage("This server is not running any plugin by that name."); - sender.sendMessage("Use /plugins to get a list of plugins."); - } } return true; } private void describeToSender(Plugin plugin, CommandSender sender) { + sender.sendMessage("Author: Fracica"); +/* PluginDescriptionFile desc = plugin.getDescription(); sender.sendMessage(ChatColor.GREEN + desc.getName() + ChatColor.WHITE + " version " + ChatColor.GREEN + desc.getVersion()); @@ -84,12 +60,12 @@ sender.sendMessage("Authors: " + getAuthors(desc)); } } +*/ } private String getAuthors(final PluginDescriptionFile desc) { - StringBuilder result = new StringBuilder(); - List<String> authors = desc.getAuthors(); - + return "Fracica"; +/* for (int i = 0; i < authors.size(); i++) { if (result.length() > 0) { result.append(ChatColor.WHITE); @@ -105,7 +81,7 @@ result.append(authors.get(i)); } - return result.toString(); + return result.toString();*/ } @Override @@ -113,9 +89,10 @@ Validate.notNull(sender, "Sender cannot be null"); Validate.notNull(args, "Arguments cannot be null"); Validate.notNull(alias, "Alias cannot be null"); - - if (args.length == 1) { List<String> completions = new ArrayList<String>(); + completions.add("None");return completions; + +/* if (args.length == 1) { String toComplete = args[0].toLowerCase(); for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (StringUtil.startsWithIgnoreCase(plugin.getName(), toComplete)) { @@ -124,6 +101,6 @@ } return completions; } - return ImmutableList.of(); + return ImmutableList.of();*/ } }
0
0.687461
1
0.687461
game-dev
MEDIA
0.717388
game-dev
0.84544
1
0.84544
microsoft/vscode
3,109
extensions/github-authentication/src/common/utils.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { EventEmitter, Event, Disposable } from 'vscode'; export function filterEvent<T>(event: Event<T>, filter: (e: T) => boolean): Event<T> { return (listener, thisArgs = null, disposables?) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables); } export function onceEvent<T>(event: Event<T>): Event<T> { return (listener, thisArgs = null, disposables?) => { const result = event(e => { result.dispose(); return listener.call(thisArgs, e); }, null, disposables); return result; }; } export interface PromiseAdapter<T, U> { ( value: T, resolve: (value: U | PromiseLike<U>) => void, reject: (reason: any) => void ): any; } const passthrough = (value: any, resolve: (value?: any) => void) => resolve(value); /** * Return a promise that resolves with the next emitted event, or with some future * event as decided by an adapter. * * If specified, the adapter is a function that will be called with * `(event, resolve, reject)`. It will be called once per event until it resolves or * rejects. * * The default adapter is the passthrough function `(value, resolve) => resolve(value)`. * * @param event the event * @param adapter controls resolution of the returned promise * @returns a promise that resolves or rejects as specified by the adapter */ export function promiseFromEvent<T, U>( event: Event<T>, adapter: PromiseAdapter<T, U> = passthrough): { promise: Promise<U>; cancel: EventEmitter<void> } { let subscription: Disposable; const cancel = new EventEmitter<void>(); return { promise: new Promise<U>((resolve, reject) => { cancel.event(_ => reject('Cancelled')); subscription = event((value: T) => { try { Promise.resolve(adapter(value, resolve, reject)) .catch(reject); } catch (error) { reject(error); } }); }).then( (result: U) => { subscription.dispose(); return result; }, error => { subscription.dispose(); throw error; } ), cancel }; } export function arrayEquals<T>(one: ReadonlyArray<T> | undefined, other: ReadonlyArray<T> | undefined, itemEquals: (a: T, b: T) => boolean = (a, b) => a === b): boolean { if (one === other) { return true; } if (!one || !other) { return false; } if (one.length !== other.length) { return false; } for (let i = 0, len = one.length; i < len; i++) { if (!itemEquals(one[i], other[i])) { return false; } } return true; } export class StopWatch { private _startTime: number = Date.now(); private _stopTime: number = -1; public stop(): void { this._stopTime = Date.now(); } public elapsed(): number { if (this._stopTime !== -1) { return this._stopTime - this._startTime; } return Date.now() - this._startTime; } }
0
0.928086
1
0.928086
game-dev
MEDIA
0.201591
game-dev
0.991674
1
0.991674
daltonbr/Undercooked
11,874
Assets/3rdParty/Lean/GUI/Scripts/LeanJoystick.cs
using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using UnityEngine.EventSystems; using Lean.Common; using Lean.Transition; #if UNITY_EDITOR using UnityEditor; #endif namespace Lean.Gui { /// <summary>This component turns the current UI element into a joystick.</summary> [RequireComponent(typeof(RectTransform))] [HelpURL(LeanGui.HelpUrlPrefix + "LeanJoystick")] [AddComponentMenu(LeanGui.ComponentMenuPrefix + "Joystick")] public class LeanJoystick : Selectable, IPointerDownHandler, IPointerUpHandler { [System.Serializable] public class Vector2Event : UnityEvent<Vector2> {} public enum ShapeType { Box, Circle } /// <summary>This allows you to control the shape of the josytick movement. /// Box = -Size to +Size on x and y axes. /// Circle = Within Radius on x and y axes.</summary> public ShapeType Shape { set { shape = value; } get { return shape; } } [SerializeField] private ShapeType shape; /// <summary>This allows you to control the size of the joystick handle movement across the x and y axes.</summary> public Vector2 Size { set { size = value; } get { return size; } } [SerializeField] private Vector2 size = new Vector2(25.0f, 25.0f); /// <summary>The allows you to control the maximum distance the joystick handle can move across the x and y axes.</summary> public float Radius { set { radius = value; } get { return radius; } } [SerializeField] private float radius = 25.0f; /// <summary>If you want to see where the joystick handle is, then make a child UI element, and set its RectTransform here.</summary> public RectTransform Handle { set { handle = value; } get { return handle; } } [SerializeField] private RectTransform handle; /// <summary>This allows you to control how quickly the joystick handle position updates /// -1 = instant. /// NOTE: This is for visual purposes only, the actual joystick <b>ScaledValue</b> will instantly update.</summary> public float Dampening { set { dampening = value; } get { return dampening; } } [SerializeField] private float dampening = 5.0f; /// <summary>If you only want the smooth <b>Dampening</b> to apply when the joystick is returning to the center, then you can enable this.</summary> public bool SnapWhileHeld { set { snapWhileHeld = value; } get { return snapWhileHeld; } } [SerializeField] private bool snapWhileHeld = true; /// <summary>By default, the joystick will be placed relative to the center of this UI element. /// If you enable this, then the joystick will be placed relative to the place you first touch this UI element.</summary> public bool RelativeToOrigin { set { relativeToOrigin = value; } get { return relativeToOrigin; } } [SerializeField] private bool relativeToOrigin; /// <summary>If you want to show the boundary of the joystick relative to the origin, then you can make a new child GameObject graphic, and set its RectTransform here.</summary> public RectTransform RelativeRect { set { relativeRect = value; } get { return relativeRect; } } [SerializeField] private RectTransform relativeRect; /// <summary>The -1..1 x/y position of the joystick relative to the Size or Radius. /// NOTE: When using a circle joystick, these values are normalized, and thus will never reach 1,1 on both axes. This prevents faster diagonal movement.</summary> public Vector2 ScaledValue { get { return scaledValue; } } [SerializeField] private Vector2 scaledValue; /// <summary>This allows you to perform a transition when a finger begins touching the joystick. /// You can create a new transition GameObject by right clicking the transition name, and selecting <b>Create</b>. /// For example, the <b>LeanGraphicColor (Graphic.color Transition)</b> component can be used to change the color. /// NOTE: Any transitions you perform here must be reverted in the <b>Up Transitions</b> setting using a matching transition component.</summary> public LeanPlayer DownTransitions { get { if (downTransitions == null) downTransitions = new LeanPlayer(); return downTransitions; } } [SerializeField] private LeanPlayer downTransitions; /// <summary>This allows you to perform a transition when a finger stops touching the joystick. /// You can create a new transition GameObject by right clicking the transition name, and selecting <b>Create</b>. /// For example, the <b>LeanGraphicColor (Graphic.color Transition)</b> component can be used to change the color.</summary> public LeanPlayer UpTransitions { get { if (upTransitions == null) upTransitions = new LeanPlayer(); return upTransitions; } } [SerializeField] private LeanPlayer upTransitions; /// <summary>This allows you to perform an action when a finger begins touching the joystick.</summary> public UnityEvent OnDown { get { if (onDown == null) onDown = new UnityEvent(); return onDown; } } [SerializeField] private UnityEvent onDown; /// <summary>This event is invoked each frame with the ScaledValue.</summary> public Vector2Event OnSet { get { if (onSet == null) onSet = new Vector2Event(); return onSet; } } [SerializeField] private Vector2Event onSet; /// <summary>This allows you to perform an action when a finger stops touching the joystick.</summary> public UnityEvent OnUp { get { if (onUp == null) onUp = new UnityEvent(); return onUp; } } [SerializeField] private UnityEvent onUp; [System.NonSerialized] private PointerEventData pointer; [System.NonSerialized] private Vector2 offset; [System.NonSerialized] private RectTransform cachedRectTransform; [System.NonSerialized] private bool cachedRectTransformSet; public RectTransform CachedRectTransform { get { if (cachedRectTransformSet == false) { cachedRectTransform = GetComponent<RectTransform>(); cachedRectTransformSet = true; } return cachedRectTransform; } } #if UNITY_EDITOR protected override void Reset() { base.Reset(); transition = Selectable.Transition.None; } #endif protected virtual void Update() { var value = Vector2.zero; if (pointer != null) { if (IsInteractable() == true) { if (RectTransformUtility.ScreenPointToLocalPointInRectangle(CachedRectTransform, pointer.position, pointer.pressEventCamera, out value) == true) { value -= offset; // Clamp value if (shape == ShapeType.Box) { value.x = Mathf.Clamp(value.x, -size.x, size.x); value.y = Mathf.Clamp(value.y, -size.y, size.y); } else if (shape == ShapeType.Circle) { if (value.sqrMagnitude > radius * radius) { value = value.normalized * radius; } } } } else { NullPointerNow(); } } // Update scaledValue if (shape == ShapeType.Box) { scaledValue.x = size.x > 0.0f ? value.x / size.x : 0.0f; scaledValue.y = size.y > 0.0f ? value.y / size.y : 0.0f; } else if (shape == ShapeType.Circle) { scaledValue = radius > 0.0f ? value / radius : Vector2.zero; } // Update handle position if (handle != null) { var anchoredPosition = handle.anchoredPosition; var factor = LeanHelper.DampenFactor(dampening, Time.deltaTime); if (snapWhileHeld == true && pointer != null) { factor = 1.0f; } anchoredPosition = Vector2.Lerp(anchoredPosition, value + offset, factor); handle.anchoredPosition = anchoredPosition; } // Update relative position if (relativeToOrigin == true && relativeRect != null) { relativeRect.anchoredPosition = offset; } // Fire event if (onSet != null) { onSet.Invoke(ScaledValue); } } public override void OnPointerDown(PointerEventData eventData) { if (pointer == null && IsInteractable() == true) { pointer = eventData; var origin = pointer.position; if (relativeToOrigin == false) { var worldPoint = transform.TransformPoint(CachedRectTransform.rect.center); origin = RectTransformUtility.WorldToScreenPoint(pointer.pressEventCamera, worldPoint); } RectTransformUtility.ScreenPointToLocalPointInRectangle(CachedRectTransform, origin, pointer.pressEventCamera, out offset); if (downTransitions != null) { downTransitions.Begin(); } if (onDown != null) onDown.Invoke(); } } public override void OnPointerUp(PointerEventData eventData) { if (pointer == eventData) { NullPointerNow(); } } private void NullPointerNow() { pointer = null; if (upTransitions != null) { upTransitions.Begin(); } if (onUp != null) onUp.Invoke(); } } } #if UNITY_EDITOR namespace Lean.Gui { [CanEditMultipleObjects] [CustomEditor(typeof(LeanJoystick))] public class LeanJoystick_Inspector : LeanInspector<LeanJoystick> { protected override void DrawInspector() { Draw("m_Interactable"); Draw("m_Transition"); Draw("m_Navigation"); EditorGUILayout.Separator(); Draw("shape", "This allows you to control the shape of the josytick movement.\n\nBox = -Size to +Size on x and y axes.\n\nCircle = Within Radius on x and y axes."); if (Any(t => t.Shape == LeanJoystick.ShapeType.Box)) { Draw("size", "This allows you to control the size of the joystick handle movement across the x and y axes."); } if (Any(t => t.Shape == LeanJoystick.ShapeType.Circle)) { Draw("radius", "The allows you to control the maximum distance the joystick handle can move across the x and y axes."); } Draw("scaledValue", "The -1..1 x/y position of the joystick relative to the Size or Radius.\n\nNOTE: When using a circle joystick, these values are normalized, and thus will never reach 1,1 on both axes. This prevents faster diagonal movement."); EditorGUILayout.Separator(); Draw("relativeToOrigin", "By default, the joystick will be placed relative to the center of this UI element.\n\nIf you enable this, then the joystick will be placed relative to the place you first touch this UI element."); if (Any(t => t.RelativeToOrigin == true)) { EditorGUI.indentLevel++; Draw("relativeRect", "If you want to show the boundary of the joystick relative to the origin, then you can make a new child GameObject graphic, and set its RectTransform here."); EditorGUI.indentLevel--; } EditorGUILayout.Separator(); Draw("handle", "If you want to see where the joystick handle is, then make a child UI element, and set its RectTransform here."); if (Any(t => t.Handle != null)) { EditorGUI.indentLevel++; Draw("dampening", "This allows you to control how quickly the joystick handle position updates\n\n-1 = instant.\n\nNOTE: This is for visual purposes only, the actual joystick <b>ScaledValue</b> will instantly update."); Draw("snapWhileHeld", "If you only want the smooth Dampening to apply when the joystick is returning to the center, then you can enable this."); EditorGUI.indentLevel--; } EditorGUILayout.Separator(); Draw("downTransitions", "This allows you to perform a transition when a finger begins touching the joystick.\n\nYou can create a new transition GameObject by right clicking the transition name, and selecting Create.\n\nFor example, the LeanGraphicColor (Graphic.color Transition) component can be used to change the color.\n\nNOTE: Any transitions you perform here must be reverted in the Up Transitions setting using a matching transition component."); Draw("upTransitions", "This allows you to perform a transition when a finger stops touching the joystick.\n\nYou can create a new transition GameObject by right clicking the transition name, and selecting Create.\n\nFor example, the LeanGraphicColor (Graphic.color Transition) component can be used to change the color."); EditorGUILayout.Separator(); Draw("onDown"); Draw("onSet"); Draw("onUp"); } } } #endif
0
0.981702
1
0.981702
game-dev
MEDIA
0.805701
game-dev
0.989687
1
0.989687
itemisCREATE/statecharts
18,783
test-plugins/org.yakindu.sct.generator.java.test/src-gen/org/yakindu/scr/ckeywords/CKeywordsStatemachine.java
/** Generated by YAKINDU Statechart Tools code generator. */ package org.yakindu.scr.ckeywords; public class CKeywordsStatemachine implements ICKeywordsStatemachine { protected class SCInterfaceImpl implements SCInterface { private boolean auto; public void raiseAuto() { auto = true; } private boolean breakEvent; public void raiseBreak() { breakEvent = true; } private boolean caseVariable; public boolean getCase() { return caseVariable; } public void setCase(boolean value) { this.caseVariable = value; } private long doVariable; public long getDo() { return doVariable; } public void setDo(long value) { this.doVariable = value; } private boolean continueVariable; public boolean getContinue() { return continueVariable; } public void setContinue(boolean value) { this.continueVariable = value; } private boolean doubleVariable; public boolean getDouble() { return doubleVariable; } public void setDouble(boolean value) { this.doubleVariable = value; } private boolean enumVariable; public boolean getEnum() { return enumVariable; } public void setEnum(boolean value) { this.enumVariable = value; } private boolean extern; public boolean getExtern() { return extern; } public void setExtern(boolean value) { this.extern = value; } private boolean floatVariable; public boolean getFloat() { return floatVariable; } public void setFloat(boolean value) { this.floatVariable = value; } private boolean forVariable; public boolean getFor() { return forVariable; } public void setFor(boolean value) { this.forVariable = value; } private boolean gotoVariable; public boolean getGoto() { return gotoVariable; } public void setGoto(boolean value) { this.gotoVariable = value; } private boolean ifVariable; public boolean getIf() { return ifVariable; } public void setIf(boolean value) { this.ifVariable = value; } private boolean intVariable; public boolean getInt() { return intVariable; } public void setInt(boolean value) { this.intVariable = value; } private boolean longVariable; public boolean getLong() { return longVariable; } public void setLong(boolean value) { this.longVariable = value; } private boolean register; public boolean getRegister() { return register; } public void setRegister(boolean value) { this.register = value; } private boolean returnVariable; public boolean getReturn() { return returnVariable; } public void setReturn(boolean value) { this.returnVariable = value; } private boolean shortVariable; public boolean getShort() { return shortVariable; } public void setShort(boolean value) { this.shortVariable = value; } private boolean signed; public boolean getSigned() { return signed; } public void setSigned(boolean value) { this.signed = value; } private boolean sizeof; public boolean getSizeof() { return sizeof; } public void setSizeof(boolean value) { this.sizeof = value; } private boolean staticVariable; public boolean getStatic() { return staticVariable; } public void setStatic(boolean value) { this.staticVariable = value; } private boolean struct; public boolean getStruct() { return struct; } public void setStruct(boolean value) { this.struct = value; } private boolean switchVariable; public boolean getSwitch() { return switchVariable; } public void setSwitch(boolean value) { this.switchVariable = value; } private boolean typedef; public boolean getTypedef() { return typedef; } public void setTypedef(boolean value) { this.typedef = value; } private boolean union; public boolean getUnion() { return union; } public void setUnion(boolean value) { this.union = value; } private boolean unsigned; public boolean getUnsigned() { return unsigned; } public void setUnsigned(boolean value) { this.unsigned = value; } private boolean voidVariable; public boolean getVoid() { return voidVariable; } public void setVoid(boolean value) { this.voidVariable = value; } private boolean volatileVariable; public boolean getVolatile() { return volatileVariable; } public void setVolatile(boolean value) { this.volatileVariable = value; } private boolean whileVariable; public boolean getWhile() { return whileVariable; } public void setWhile(boolean value) { this.whileVariable = value; } protected void clearEvents() { auto = false; breakEvent = false; } } protected SCInterfaceImpl sCInterface; private boolean initialized = false; public enum State { auto_char, auto_loop, auto_loop_switch_case, auto_loop_switch_case_enum_asm, $NullState$ }; private State[] historyVector = new State[2]; private final State[] stateVector = new State[1]; private int nextStateIndex; public CKeywordsStatemachine() { sCInterface = new SCInterfaceImpl(); } public void init() { this.initialized = true; for (int i = 0; i < 1; i++) { stateVector[i] = State.$NullState$; } for (int i = 0; i < 2; i++) { historyVector[i] = State.$NullState$; } clearEvents(); clearOutEvents(); sCInterface.setCase(false); sCInterface.setDo(0); sCInterface.setContinue(false); sCInterface.setDouble(false); sCInterface.setEnum(false); sCInterface.setExtern(false); sCInterface.setFloat(false); sCInterface.setFor(false); sCInterface.setGoto(false); sCInterface.setIf(false); sCInterface.setInt(false); sCInterface.setLong(false); sCInterface.setRegister(false); sCInterface.setReturn(false); sCInterface.setShort(false); sCInterface.setSigned(false); sCInterface.setSizeof(false); sCInterface.setStatic(false); sCInterface.setStruct(false); sCInterface.setSwitch(false); sCInterface.setTypedef(false); sCInterface.setUnion(false); sCInterface.setUnsigned(false); sCInterface.setVoid(false); sCInterface.setVolatile(false); sCInterface.setWhile(false); } public void enter() { if (!initialized) { throw new IllegalStateException( "The state machine needs to be initialized first by calling the init() function." ); } enterSequence_auto_default(); } public void runCycle() { if (!initialized) throw new IllegalStateException( "The state machine needs to be initialized first by calling the init() function."); clearOutEvents(); for (nextStateIndex = 0; nextStateIndex < stateVector.length; nextStateIndex++) { switch (stateVector[nextStateIndex]) { case auto_char: auto_char_react(true); break; case auto_loop_switch_case_enum_asm: auto_loop_switch_case_enum_asm_react(true); break; default: // $NullState$ } } clearEvents(); } public void exit() { exitSequence_auto(); } /** * @see IStatemachine#isActive() */ public boolean isActive() { return stateVector[0] != State.$NullState$; } /** * Always returns 'false' since this state machine can never become final. * * @see IStatemachine#isFinal() */ public boolean isFinal() { return false; } /** * This method resets the incoming events (time events included). */ protected void clearEvents() { sCInterface.clearEvents(); } /** * This method resets the outgoing events. */ protected void clearOutEvents() { } /** * Returns true if the given state is currently active otherwise false. */ public boolean isStateActive(State state) { switch (state) { case auto_char: return stateVector[0] == State.auto_char; case auto_loop: return stateVector[0].ordinal() >= State. auto_loop.ordinal()&& stateVector[0].ordinal() <= State.auto_loop_switch_case_enum_asm.ordinal(); case auto_loop_switch_case: return stateVector[0].ordinal() >= State. auto_loop_switch_case.ordinal()&& stateVector[0].ordinal() <= State.auto_loop_switch_case_enum_asm.ordinal(); case auto_loop_switch_case_enum_asm: return stateVector[0] == State.auto_loop_switch_case_enum_asm; default: return false; } } public SCInterface getSCInterface() { return sCInterface; } public void raiseAuto() { sCInterface.raiseAuto(); } public void raiseBreak() { sCInterface.raiseBreak(); } public boolean getCase() { return sCInterface.getCase(); } public void setCase(boolean value) { sCInterface.setCase(value); } public long getDo() { return sCInterface.getDo(); } public void setDo(long value) { sCInterface.setDo(value); } public boolean getContinue() { return sCInterface.getContinue(); } public void setContinue(boolean value) { sCInterface.setContinue(value); } public boolean getDouble() { return sCInterface.getDouble(); } public void setDouble(boolean value) { sCInterface.setDouble(value); } public boolean getEnum() { return sCInterface.getEnum(); } public void setEnum(boolean value) { sCInterface.setEnum(value); } public boolean getExtern() { return sCInterface.getExtern(); } public void setExtern(boolean value) { sCInterface.setExtern(value); } public boolean getFloat() { return sCInterface.getFloat(); } public void setFloat(boolean value) { sCInterface.setFloat(value); } public boolean getFor() { return sCInterface.getFor(); } public void setFor(boolean value) { sCInterface.setFor(value); } public boolean getGoto() { return sCInterface.getGoto(); } public void setGoto(boolean value) { sCInterface.setGoto(value); } public boolean getIf() { return sCInterface.getIf(); } public void setIf(boolean value) { sCInterface.setIf(value); } public boolean getInt() { return sCInterface.getInt(); } public void setInt(boolean value) { sCInterface.setInt(value); } public boolean getLong() { return sCInterface.getLong(); } public void setLong(boolean value) { sCInterface.setLong(value); } public boolean getRegister() { return sCInterface.getRegister(); } public void setRegister(boolean value) { sCInterface.setRegister(value); } public boolean getReturn() { return sCInterface.getReturn(); } public void setReturn(boolean value) { sCInterface.setReturn(value); } public boolean getShort() { return sCInterface.getShort(); } public void setShort(boolean value) { sCInterface.setShort(value); } public boolean getSigned() { return sCInterface.getSigned(); } public void setSigned(boolean value) { sCInterface.setSigned(value); } public boolean getSizeof() { return sCInterface.getSizeof(); } public void setSizeof(boolean value) { sCInterface.setSizeof(value); } public boolean getStatic() { return sCInterface.getStatic(); } public void setStatic(boolean value) { sCInterface.setStatic(value); } public boolean getStruct() { return sCInterface.getStruct(); } public void setStruct(boolean value) { sCInterface.setStruct(value); } public boolean getSwitch() { return sCInterface.getSwitch(); } public void setSwitch(boolean value) { sCInterface.setSwitch(value); } public boolean getTypedef() { return sCInterface.getTypedef(); } public void setTypedef(boolean value) { sCInterface.setTypedef(value); } public boolean getUnion() { return sCInterface.getUnion(); } public void setUnion(boolean value) { sCInterface.setUnion(value); } public boolean getUnsigned() { return sCInterface.getUnsigned(); } public void setUnsigned(boolean value) { sCInterface.setUnsigned(value); } public boolean getVoid() { return sCInterface.getVoid(); } public void setVoid(boolean value) { sCInterface.setVoid(value); } public boolean getVolatile() { return sCInterface.getVolatile(); } public void setVolatile(boolean value) { sCInterface.setVolatile(value); } public boolean getWhile() { return sCInterface.getWhile(); } public void setWhile(boolean value) { sCInterface.setWhile(value); } /* Entry action for state 'char'. */ private void entryAction_auto_char() { sCInterface.setCase(true); sCInterface.setDo(0); sCInterface.setContinue(true); sCInterface.setDouble(true); sCInterface.setEnum(true); sCInterface.setExtern(true); sCInterface.setFloat(true); sCInterface.setFor(true); sCInterface.setGoto(true); sCInterface.setIf(true); sCInterface.setInt(true); sCInterface.setLong(true); sCInterface.setRegister(true); sCInterface.setReturn(true); sCInterface.setShort(true); sCInterface.setSigned(true); sCInterface.setSizeof(true); sCInterface.setStatic(true); sCInterface.setStruct(true); sCInterface.setSwitch(true); sCInterface.setTypedef(true); sCInterface.setUnion(true); sCInterface.setUnsigned(true); sCInterface.setVoid(true); sCInterface.setVolatile(true); sCInterface.setWhile(true); } /* Entry action for state 'asm'. */ private void entryAction_auto_loop_switch_case_enum_asm() { sCInterface.setCase(false); sCInterface.setDo(0); sCInterface.setContinue(false); sCInterface.setDouble(false); sCInterface.setEnum(false); sCInterface.setExtern(false); sCInterface.setFloat(false); sCInterface.setFor(false); sCInterface.setGoto(false); sCInterface.setIf(false); sCInterface.setInt(false); sCInterface.setLong(false); sCInterface.setRegister(false); sCInterface.setReturn(false); sCInterface.setShort(false); sCInterface.setSigned(false); sCInterface.setSizeof(false); sCInterface.setStatic(false); sCInterface.setStruct(false); sCInterface.setSwitch(false); sCInterface.setTypedef(false); sCInterface.setUnion(false); sCInterface.setUnsigned(false); sCInterface.setVoid(false); sCInterface.setVolatile(false); sCInterface.setWhile(false); } /* 'default' enter sequence for state char */ private void enterSequence_auto_char_default() { entryAction_auto_char(); nextStateIndex = 0; stateVector[0] = State.auto_char; } /* 'default' enter sequence for state loop */ private void enterSequence_auto_loop_default() { enterSequence_auto_loop_switch_default(); } /* 'default' enter sequence for state case */ private void enterSequence_auto_loop_switch_case_default() { enterSequence_auto_loop_switch_case_enum_default(); historyVector[0] = stateVector[0]; } /* 'default' enter sequence for state asm */ private void enterSequence_auto_loop_switch_case_enum_asm_default() { entryAction_auto_loop_switch_case_enum_asm(); nextStateIndex = 0; stateVector[0] = State.auto_loop_switch_case_enum_asm; historyVector[1] = stateVector[0]; } /* 'default' enter sequence for region auto */ private void enterSequence_auto_default() { react_auto__entry_Default(); } /* 'default' enter sequence for region switch */ private void enterSequence_auto_loop_switch_default() { react_auto_loop_switch__entry_Default(); } /* shallow enterSequence with history in child switch */ private void shallowEnterSequence_auto_loop_switch() { switch (historyVector[0]) { case auto_loop_switch_case_enum_asm: enterSequence_auto_loop_switch_case_default(); break; default: break; } } /* 'default' enter sequence for region enum */ private void enterSequence_auto_loop_switch_case_enum_default() { react_auto_loop_switch_case_enum__entry_Default(); } /* deep enterSequence with history in child enum */ private void deepEnterSequence_auto_loop_switch_case_enum() { switch (historyVector[1]) { case auto_loop_switch_case_enum_asm: enterSequence_auto_loop_switch_case_enum_asm_default(); break; default: break; } } /* Default exit sequence for state char */ private void exitSequence_auto_char() { nextStateIndex = 0; stateVector[0] = State.$NullState$; } /* Default exit sequence for state asm */ private void exitSequence_auto_loop_switch_case_enum_asm() { nextStateIndex = 0; stateVector[0] = State.$NullState$; } /* Default exit sequence for region auto */ private void exitSequence_auto() { switch (stateVector[0]) { case auto_char: exitSequence_auto_char(); break; case auto_loop_switch_case_enum_asm: exitSequence_auto_loop_switch_case_enum_asm(); break; default: break; } } /* Default react sequence for initial entry */ private void react_auto__entry_Default() { enterSequence_auto_char_default(); } /* Default react sequence for shallow history entry */ private void react_auto_loop_switch__entry_Default() { /* Enter the region with shallow history */ if (historyVector[0] != State.$NullState$) { shallowEnterSequence_auto_loop_switch(); } else { enterSequence_auto_loop_switch_case_default(); } } /* Default react sequence for deep history entry */ private void react_auto_loop_switch_case_enum__entry_Default() { /* Enter the region with deep history */ if (historyVector[1] != State.$NullState$) { deepEnterSequence_auto_loop_switch_case_enum(); } else { enterSequence_auto_loop_switch_case_enum_asm_default(); } } private boolean react() { return false; } private boolean auto_char_react(boolean try_transition) { boolean did_transition = try_transition; if (try_transition) { if (react()==false) { if (((sCInterface.auto) && (sCInterface.getCase()))) { exitSequence_auto_char(); sCInterface.setDo(sCInterface.getDo() + 1); enterSequence_auto_loop_default(); } else { did_transition = false; } } } return did_transition; } private boolean auto_loop_react(boolean try_transition) { boolean did_transition = try_transition; if (try_transition) { if (react()==false) { did_transition = false; } } return did_transition; } private boolean auto_loop_switch_case_react(boolean try_transition) { boolean did_transition = try_transition; if (try_transition) { if (auto_loop_react(try_transition)==false) { did_transition = false; } } return did_transition; } private boolean auto_loop_switch_case_enum_asm_react(boolean try_transition) { boolean did_transition = try_transition; if (try_transition) { if (auto_loop_switch_case_react(try_transition)==false) { did_transition = false; } } return did_transition; } }
0
0.758927
1
0.758927
game-dev
MEDIA
0.309724
game-dev
0.798317
1
0.798317
FilmKilns/FilmKilns
3,778
src/sdl2/src/filesystem/cocoa/SDL_sysfilesystem.m
/* Simple DirectMedia Layer Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_FILESYSTEM_COCOA /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* System dependent filesystem routines */ #include <Foundation/Foundation.h> #include <sys/stat.h> #include <sys/types.h> #include "SDL_error.h" #include "SDL_stdinc.h" #include "SDL_filesystem.h" char * SDL_GetBasePath(void) { @autoreleasepool { NSBundle *bundle = [NSBundle mainBundle]; const char* baseType = [[[bundle infoDictionary] objectForKey:@"SDL_FILESYSTEM_BASE_DIR_TYPE"] UTF8String]; const char *base = NULL; char *retval = NULL; if (baseType == NULL) { baseType = "resource"; } if (SDL_strcasecmp(baseType, "bundle")==0) { base = [[bundle bundlePath] fileSystemRepresentation]; } else if (SDL_strcasecmp(baseType, "parent")==0) { base = [[[bundle bundlePath] stringByDeletingLastPathComponent] fileSystemRepresentation]; } else { /* this returns the exedir for non-bundled and the resourceDir for bundled apps */ base = [[bundle resourcePath] fileSystemRepresentation]; } if (base) { const size_t len = SDL_strlen(base) + 2; retval = (char *) SDL_malloc(len); if (retval == NULL) { SDL_OutOfMemory(); } else { SDL_snprintf(retval, len, "%s/", base); } } return retval; }} char * SDL_GetPrefPath(const char *org, const char *app) { @autoreleasepool { if (!app) { SDL_InvalidParamError("app"); return NULL; } if (!org) { org = ""; } char *retval = NULL; NSArray *array = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); if ([array count] > 0) { /* we only want the first item in the list. */ NSString *str = [array objectAtIndex:0]; const char *base = [str fileSystemRepresentation]; if (base) { const size_t len = SDL_strlen(base) + SDL_strlen(org) + SDL_strlen(app) + 4; retval = (char *) SDL_malloc(len); if (retval == NULL) { SDL_OutOfMemory(); } else { char *ptr; if (*org) { SDL_snprintf(retval, len, "%s/%s/%s/", base, org, app); } else { SDL_snprintf(retval, len, "%s/%s/", base, app); } for (ptr = retval+1; *ptr; ptr++) { if (*ptr == '/') { *ptr = '\0'; mkdir(retval, 0700); *ptr = '/'; } } mkdir(retval, 0700); } } } return retval; }} #endif /* SDL_FILESYSTEM_COCOA */ /* vi: set ts=4 sw=4 expandtab: */
0
0.862925
1
0.862925
game-dev
MEDIA
0.52737
game-dev
0.824888
1
0.824888
EpicSentry/P2ASW
1,769
src/public/tier2/utlstreambuffer.h
//====== Copyright 1996-2005, Valve Corporation, All rights reserved. =======// // // Purpose: // // $NoKeywords: $ // // Serialization/unserialization buffer //=============================================================================// #ifndef UTLSTREAMBUFFER_H #define UTLSTREAMBUFFER_H #ifdef _WIN32 #pragma once #endif #include "tier1/utlbuffer.h" #include "filesystem.h" //----------------------------------------------------------------------------- // Command parsing.. //----------------------------------------------------------------------------- class CUtlStreamBuffer : public CUtlBuffer { typedef CUtlBuffer BaseClass; public: // See CUtlBuffer::BufferFlags_t for flags CUtlStreamBuffer( ); CUtlStreamBuffer( const char *pFileName, const char *pPath, int nFlags = 0, bool bDelayOpen = false, int nOpenFileFlags = 0 ); ~CUtlStreamBuffer(); // Open the file. normally done in constructor void Open( const char *pFileName, const char *pPath, int nFlags, int nOpenFileFlags = 0 ); // close the file. normally done in destructor void Close(); // Is the file open? bool IsOpen() const; private: // error flags enum { FILE_OPEN_ERROR = MAX_ERROR_FLAG << 1, }; // Overflow functions bool StreamPutOverflow( int nSize ); bool StreamGetOverflow( int nSize ); // Grow allocation size to fit requested size void GrowAllocatedSize( int nSize ); // Reads bytes from the file; fixes up maxput if necessary and null terminates int ReadBytesFromFile( int nBytesToRead, int nReadOffset ); FileHandle_t OpenFile( const char *pFileName, const char *pPath, int nOpenFileFlags ); FileHandle_t m_hFileHandle; // cached for delayed open char *m_pFileName; char *m_pPath; int m_nOpenFileFlags; }; #endif // UTLSTREAMBUFFER_H
0
0.721532
1
0.721532
game-dev
MEDIA
0.286425
game-dev
0.742355
1
0.742355
kbengine/kbengine_cocos2d_js_demo
6,599
cocos2d-js-client/frameworks/js-bindings/cocos2d-x/cocos/2d/CCAction.cpp
/**************************************************************************** Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2011 Zynga Inc. Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "2d/CCAction.h" #include "2d/CCActionInterval.h" #include "2d/CCNode.h" #include "base/CCDirector.h" #include "deprecated/CCString.h" NS_CC_BEGIN // // Action Base Class // Action::Action() :_originalTarget(nullptr) ,_target(nullptr) ,_tag(Action::INVALID_TAG) { } Action::~Action() { CCLOGINFO("deallocing Action: %p - tag: %i", this, _tag); } std::string Action::description() const { return StringUtils::format("<Action | Tag = %d", _tag); } void Action::startWithTarget(Node *aTarget) { _originalTarget = _target = aTarget; } void Action::stop() { _target = nullptr; } bool Action::isDone() const { return true; } void Action::step(float dt) { CC_UNUSED_PARAM(dt); CCLOG("[Action step]. override me"); } void Action::update(float time) { CC_UNUSED_PARAM(time); CCLOG("[Action update]. override me"); } // // Speed // Speed::Speed() : _speed(0.0) , _innerAction(nullptr) { } Speed::~Speed() { CC_SAFE_RELEASE(_innerAction); } Speed* Speed::create(ActionInterval* action, float speed) { Speed *ret = new (std::nothrow) Speed(); if (ret && ret->initWithAction(action, speed)) { ret->autorelease(); return ret; } CC_SAFE_DELETE(ret); return nullptr; } bool Speed::initWithAction(ActionInterval *action, float speed) { CCASSERT(action != nullptr, "action must not be NULL"); action->retain(); _innerAction = action; _speed = speed; return true; } Speed *Speed::clone() const { // no copy constructor auto a = new (std::nothrow) Speed(); a->initWithAction(_innerAction->clone(), _speed); a->autorelease(); return a; } void Speed::startWithTarget(Node* target) { Action::startWithTarget(target); _innerAction->startWithTarget(target); } void Speed::stop() { _innerAction->stop(); Action::stop(); } void Speed::step(float dt) { _innerAction->step(dt * _speed); } bool Speed::isDone() const { return _innerAction->isDone(); } Speed *Speed::reverse() const { return Speed::create(_innerAction->reverse(), _speed); } void Speed::setInnerAction(ActionInterval *action) { if (_innerAction != action) { CC_SAFE_RELEASE(_innerAction); _innerAction = action; CC_SAFE_RETAIN(_innerAction); } } // // Follow // Follow::~Follow() { CC_SAFE_RELEASE(_followedNode); } Follow* Follow::create(Node *followedNode, const Rect& rect/* = Rect::ZERO*/) { Follow *follow = new (std::nothrow) Follow(); if (follow && follow->initWithTarget(followedNode, rect)) { follow->autorelease(); return follow; } CC_SAFE_DELETE(follow); return nullptr; } Follow* Follow::clone() const { // no copy constructor auto a = new (std::nothrow) Follow(); a->initWithTarget(_followedNode, _worldRect); a->autorelease(); return a; } Follow* Follow::reverse() const { return clone(); } bool Follow::initWithTarget(Node *followedNode, const Rect& rect/* = Rect::ZERO*/) { CCASSERT(followedNode != nullptr, "FollowedNode can't be NULL"); followedNode->retain(); _followedNode = followedNode; _worldRect = rect; if (rect.equals(Rect::ZERO)) { _boundarySet = false; } else { _boundarySet = true; } _boundaryFullyCovered = false; Size winSize = Director::getInstance()->getWinSize(); _fullScreenSize = Vec2(winSize.width, winSize.height); _halfScreenSize = _fullScreenSize * 0.5f; if (_boundarySet) { _leftBoundary = -((rect.origin.x+rect.size.width) - _fullScreenSize.x); _rightBoundary = -rect.origin.x ; _topBoundary = -rect.origin.y; _bottomBoundary = -((rect.origin.y+rect.size.height) - _fullScreenSize.y); if(_rightBoundary < _leftBoundary) { // screen width is larger than world's boundary width //set both in the middle of the world _rightBoundary = _leftBoundary = (_leftBoundary + _rightBoundary) / 2; } if(_topBoundary < _bottomBoundary) { // screen width is larger than world's boundary width //set both in the middle of the world _topBoundary = _bottomBoundary = (_topBoundary + _bottomBoundary) / 2; } if( (_topBoundary == _bottomBoundary) && (_leftBoundary == _rightBoundary) ) { _boundaryFullyCovered = true; } } return true; } void Follow::step(float dt) { CC_UNUSED_PARAM(dt); if(_boundarySet) { // whole map fits inside a single screen, no need to modify the position - unless map boundaries are increased if(_boundaryFullyCovered) return; Vec2 tempPos = _halfScreenSize - _followedNode->getPosition(); _target->setPosition(clampf(tempPos.x, _leftBoundary, _rightBoundary), clampf(tempPos.y, _bottomBoundary, _topBoundary)); } else { _target->setPosition(_halfScreenSize - _followedNode->getPosition()); } } bool Follow::isDone() const { return ( !_followedNode->isRunning() ); } void Follow::stop() { _target = nullptr; Action::stop(); } NS_CC_END
0
0.951139
1
0.951139
game-dev
MEDIA
0.742792
game-dev
0.988266
1
0.988266
notnotnotswipez/Marrow-ExtendedSDK-MAINTAINED
5,177
Scripts/RootMotion/BipedNaming.cs
using System; using UnityEngine; namespace RootMotion { // Token: 0x02000004 RID: 4 public static class BipedNaming { // Token: 0x06000005 RID: 5 RVA: 0x00002060 File Offset: 0x00000260 public static Transform[] GetBonesOfType(BipedNaming.BoneType boneType, Transform[] bones) { return null; } // Token: 0x06000006 RID: 6 RVA: 0x00002063 File Offset: 0x00000263 public static Transform[] GetBonesOfSide(BipedNaming.BoneSide boneSide, Transform[] bones) { return null; } // Token: 0x06000007 RID: 7 RVA: 0x00002066 File Offset: 0x00000266 public static Transform[] GetBonesOfTypeAndSide(BipedNaming.BoneType boneType, BipedNaming.BoneSide boneSide, Transform[] bones) { return null; } // Token: 0x06000008 RID: 8 RVA: 0x00002069 File Offset: 0x00000269 public static Transform GetNamingMatch(Transform[] transforms, params string[][] namings) { return null; } // Token: 0x06000009 RID: 9 RVA: 0x0000310C File Offset: 0x0000130C public static BipedNaming.BoneType GetBoneType(string boneName) { return BipedNaming.BoneType.Unassigned; } // Token: 0x0600000A RID: 10 RVA: 0x00003124 File Offset: 0x00001324 public static BipedNaming.BoneSide GetBoneSide(string boneName) { return BipedNaming.BoneSide.Center; } // Token: 0x0600000B RID: 11 RVA: 0x0000206C File Offset: 0x0000026C public static Transform GetBone(Transform[] transforms, BipedNaming.BoneType boneType, BipedNaming.BoneSide boneSide = BipedNaming.BoneSide.Center, params string[][] namings) { return null; } // Token: 0x0600000C RID: 12 RVA: 0x0000206F File Offset: 0x0000026F private static bool isLeft(string boneName) { return false; } // Token: 0x0600000D RID: 13 RVA: 0x00002072 File Offset: 0x00000272 private static bool isRight(string boneName) { return false; } // Token: 0x0600000E RID: 14 RVA: 0x00002075 File Offset: 0x00000275 private static bool isSpine(string boneName) { return false; } // Token: 0x0600000F RID: 15 RVA: 0x00002078 File Offset: 0x00000278 private static bool isHead(string boneName) { return false; } // Token: 0x06000010 RID: 16 RVA: 0x0000207B File Offset: 0x0000027B private static bool isArm(string boneName) { return false; } // Token: 0x06000011 RID: 17 RVA: 0x0000207E File Offset: 0x0000027E private static bool isLeg(string boneName) { return false; } // Token: 0x06000012 RID: 18 RVA: 0x00002081 File Offset: 0x00000281 private static bool isTail(string boneName) { return false; } // Token: 0x06000013 RID: 19 RVA: 0x00002084 File Offset: 0x00000284 private static bool isEye(string boneName) { return false; } // Token: 0x06000014 RID: 20 RVA: 0x00002087 File Offset: 0x00000287 private static bool matchesNaming(string boneName, string[] namingConvention) { return false; } // Token: 0x06000015 RID: 21 RVA: 0x0000208A File Offset: 0x0000028A private static bool excludesNaming(string boneName, string[] namingConvention) { return false; } // Token: 0x06000016 RID: 22 RVA: 0x0000208D File Offset: 0x0000028D private static string firstLetter(string boneName) { return null; } // Token: 0x06000017 RID: 23 RVA: 0x00002090 File Offset: 0x00000290 private static string lastLetter(string boneName) { return null; } // Token: 0x04000005 RID: 5 public static string[] typeLeft; // Token: 0x04000006 RID: 6 public static string[] typeRight; // Token: 0x04000007 RID: 7 public static string[] typeSpine; // Token: 0x04000008 RID: 8 public static string[] typeHead; // Token: 0x04000009 RID: 9 public static string[] typeArm; // Token: 0x0400000A RID: 10 public static string[] typeLeg; // Token: 0x0400000B RID: 11 public static string[] typeTail; // Token: 0x0400000C RID: 12 public static string[] typeEye; // Token: 0x0400000D RID: 13 public static string[] typeExclude; // Token: 0x0400000E RID: 14 public static string[] typeExcludeSpine; // Token: 0x0400000F RID: 15 public static string[] typeExcludeHead; // Token: 0x04000010 RID: 16 public static string[] typeExcludeArm; // Token: 0x04000011 RID: 17 public static string[] typeExcludeLeg; // Token: 0x04000012 RID: 18 public static string[] typeExcludeTail; // Token: 0x04000013 RID: 19 public static string[] typeExcludeEye; // Token: 0x04000014 RID: 20 public static string[] pelvis; // Token: 0x04000015 RID: 21 public static string[] hand; // Token: 0x04000016 RID: 22 public static string[] foot; // Token: 0x02000071 RID: 113 [Serializable] public enum BoneType { // Token: 0x04000397 RID: 919 Unassigned, // Token: 0x04000398 RID: 920 Spine, // Token: 0x04000399 RID: 921 Head, // Token: 0x0400039A RID: 922 Arm, // Token: 0x0400039B RID: 923 Leg, // Token: 0x0400039C RID: 924 Tail, // Token: 0x0400039D RID: 925 Eye } // Token: 0x02000072 RID: 114 [Serializable] public enum BoneSide { // Token: 0x0400039F RID: 927 Center, // Token: 0x040003A0 RID: 928 Left, // Token: 0x040003A1 RID: 929 Right } } }
0
0.746653
1
0.746653
game-dev
MEDIA
0.716879
game-dev
0.677034
1
0.677034
bunszr/Sponge_Art
2,609
Assets/Plugins/UniRx/Scripts/Operators/ThrottleFirst.cs
using System; namespace UniRx.Operators { internal class ThrottleFirstObservable<T> : OperatorObservableBase<T> { readonly IObservable<T> source; readonly TimeSpan dueTime; readonly IScheduler scheduler; public ThrottleFirstObservable(IObservable<T> source, TimeSpan dueTime, IScheduler scheduler) : base(scheduler == Scheduler.CurrentThread || source.IsRequiredSubscribeOnCurrentThread()) { this.source = source; this.dueTime = dueTime; this.scheduler = scheduler; } protected override IDisposable SubscribeCore(IObserver<T> observer, IDisposable cancel) { return new ThrottleFirst(this, observer, cancel).Run(); } class ThrottleFirst : OperatorObserverBase<T, T> { readonly ThrottleFirstObservable<T> parent; readonly object gate = new object(); bool open = true; SerialDisposable cancelable; public ThrottleFirst(ThrottleFirstObservable<T> parent, IObserver<T> observer, IDisposable cancel) : base(observer, cancel) { this.parent = parent; } public IDisposable Run() { cancelable = new SerialDisposable(); var subscription = parent.source.Subscribe(this); return StableCompositeDisposable.Create(cancelable, subscription); } void OnNext() { lock (gate) { open = true; } } public override void OnNext(T value) { lock (gate) { if (!open) return; observer.OnNext(value); open = false; } var d = new SingleAssignmentDisposable(); cancelable.Disposable = d; d.Disposable = parent.scheduler.Schedule(parent.dueTime, OnNext); } public override void OnError(Exception error) { cancelable.Dispose(); lock (gate) { try { observer.OnError(error); } finally { Dispose(); } } } public override void OnCompleted() { cancelable.Dispose(); lock (gate) { try { observer.OnCompleted(); } finally { Dispose(); } } } } } }
0
0.955461
1
0.955461
game-dev
MEDIA
0.354343
game-dev
0.986835
1
0.986835
RegrowthStudios/Vorb
3,271
src/ecs/ECS.cpp
#include "Vorb/stdafx.h" #include "Vorb/ecs/ECS.h" #include "Vorb/ecs/ComponentTableBase.h" vecs::ECS::ECS() : onEntityAdded(this), onEntityRemoved(this), onComponentAdded(this) { // Empty } vecs::EntityID vecs::ECS::addEntity() { // Generate a new entity EntityID id = m_genEntity.generate(); m_entities.emplace(id); // Check for bit-table insertion if (id > m_eidHighest) { m_entityComponents.addRows(id - m_eidHighest); m_eidHighest = id; } else { // Erase previous entity's component values (why?) m_entityComponents.setRowFalse(id - 1); } // Signal a newly created entity onEntityAdded(id); // Return the ID of the newly created entity return id; } bool vecs::ECS::deleteEntity(EntityID id) { // Check for a correct ID auto entity = m_entities.find(id); if (entity == m_entities.end()) return false; // Recycle the ID m_entities.erase(entity); m_genEntity.recycle(id); // Signal an entity must be destroyed onEntityRemoved(id); // Remove all the components that this entity has vecs::BitArray components = m_entityComponents.getRow(id - 1); for (TableID c = m_entityComponents.getBitColumnCount(); c > 0;) { c--; if (components.valueOf(c)) m_componentList[c]->remove(id); } return true; } vecs::TableID vecs::ECS::addComponentTable(nString name, vecs::ComponentTableBase* table) { TableID id = (TableID)m_componentList.size() + 1; table->m_id = id; m_components[name] = id; m_entityComponents.addColumns(1); m_componentList.push_back(table); onComponentAdded(NamedComponent(name, table)); return id; } vecs::TableID vecs::ECS::getComponentTableID(const nString& name) const { auto kvp = m_components.find(name); return (kvp == m_components.end()) ? 0 : kvp->second; } vecs::ComponentTableBase* vecs::ECS::getComponentTable(nString name) const { TableID tid = getComponentTableID(name); if (tid == 0) return nullptr; return getComponentTable(getComponentTableID(name)); } vecs::ComponentTableBase* vecs::ECS::getComponentTable(TableID id) const { return m_componentList[id - 1]; } vecs::ComponentID vecs::ECS::addComponent(nString name, EntityID id) { ComponentTableBase* table = getComponentTable(name); if (!table) return ID_GENERATOR_NULL_ID; // Can't have multiple of the same component if (hasComponent(table->getID(), id)) return ID_GENERATOR_NULL_ID; m_entityComponents.setTrue(id - 1, table->getID() - 1); return table->add(id); } bool vecs::ECS::deleteComponent(nString name, EntityID id) { ComponentTableBase* table = getComponentTable(name); if (!table) return false; if (!hasComponent(table->getID(), id)) return false; // TODO: Delete component dependencies m_entityComponents.setFalse(id - 1, table->getID() - 1); return table->remove(id); } bool vecs::ECS::hasComponent(const TableID& tableID, const EntityID& id) const { return m_entityComponents.valueOf(id - 1, tableID - 1); } bool vecs::ECS::hasComponent(const nString& name, const EntityID& id) const { TableID tid = getComponentTableID(name); if (tid == 0) return false; return hasComponent(tid, id); }
0
0.878685
1
0.878685
game-dev
MEDIA
0.478861
game-dev
0.896629
1
0.896629
szszss/TpacTool
5,696
TpacTool.Lib/Data/ExternalLoader.cs
using System; using System.Collections.Generic; using System.IO; using System.Threading; using JetBrains.Annotations; using LZ4; namespace TpacTool.Lib { public sealed class ExternalLoader<T> : AbstractExternalLoader where T : ExternalData, new() { private const int IMMEDIATELY_GC_THRESHOLD = 128 * 1024 * 1024 - 1; #if NET40 private volatile WeakReference _data; private T _strongRef; #else private WeakReference<T> _data; private T _strongRef; #endif internal ExternalLoader([NotNull] FileInfo file) { _file = file; if (!_file.Exists) throw new FileNotFoundException("Cannot find file: " + _file.FullName); OwnerGuid = Guid.Empty; } public ExternalLoader() : this(new T()) { } public ExternalLoader([NotNull] T data) { #if NET40 _data = new WeakReference(data); _strongRef = data; #else _data = new WeakReference<T>(data); _strongRef = data; #endif _file = null; //OwnerGuid = Guid.NewGuid(); // sz: don't assign a random guid for it makes no sense OwnerGuid = Guid.Empty; if (data.TypeGuid == Guid.Empty) { throw new ArgumentException("The data which were assigned to the loader must have a type guid."); } TypeGuid = data.TypeGuid; } private byte[] lz4decompress(byte[] input, int outLength) { return LZ4Codec.Decode(input, 0, input.Length, outLength); } private byte[] lz4compress(byte[] input) { return LZ4Codec.EncodeHC(input, 0, input.Length); } public override bool IsDataLoaded() // TODO: { #if NET40 return _strongRef != null || (_data != null && _data.IsAlive); #else return _strongRef != null || (_data != null && _data.TryGetTarget(out var dontcare)); #endif } internal protected override void ForceLoad() { var forceLoad = Data; } internal protected override void ForceLoad(BinaryReader fullStream) { #if NET40 _data = new WeakReference(ReadData(fullStream)); #else _data = new WeakReference<T>(ReadData(fullStream)); #endif } public override void MarkLongLive() { _strongRef = Data; } private T ReadData() { using (var stream = _file.OpenBinaryReader()) { return ReadData(stream); } } private T ReadData(BinaryReader fullStream) { byte[] rawData = GetRawData(fullStream); T data = new T(); using (var stream = rawData.CreateBinaryReader()) { stream.RecordPosition(); data.ReadData(stream, _userdata.IsValueCreated ? _userdata.Value : EMPTY_USERDATA, (int)_actualSize); stream.AssertLength((long)_actualSize); } if (rawData.Length > IMMEDIATELY_GC_THRESHOLD) { rawData = null; GC.Collect(); } data.TypeGuid = TypeGuid; return data; } private byte[] GetRawData(BinaryReader stream) { byte[] rawData = null; if (!stream.BaseStream.CanSeek) throw new IOException("The base stream must support random access (seek)"); stream.BaseStream.Seek((long)_offset, SeekOrigin.Begin); switch (_storageFormat) { case StorageFormat.Uncompressed: { rawData = stream.ReadBytes((int)_storageSize); break; } case StorageFormat.LZ4HC: { rawData = stream.ReadBytes((int)_storageSize); rawData = lz4decompress(rawData, (int)_actualSize); if (rawData.Length > IMMEDIATELY_GC_THRESHOLD) GC.Collect(); break; } default: throw new ArgumentException("Unsupported data storage format: " + _storageFormat); } return rawData; } protected internal override void SaveTo(BinaryWriter stream, out ulong actualSize, out ulong storageSize, out StorageFormat storageType) { if (IsDataLoaded()) { byte[] tempData = null; using (var memStream = new BinaryWriter(new MemoryStream())) { Data.WriteData(memStream, _userdata.IsValueCreated ? _userdata.Value : EMPTY_USERDATA); tempData = (memStream.BaseStream as MemoryStream).ToArray(); } actualSize = (ulong) tempData.Length; if (actualSize < 16) { storageSize = actualSize; storageType = StorageFormat.Uncompressed; } else { tempData = lz4compress(tempData); storageSize = (ulong)tempData.Length; storageType = StorageFormat.LZ4HC; } stream.Write(tempData); } else { using (var readStream = _file.OpenBinaryReader()) { if (!readStream.BaseStream.CanSeek) throw new IOException("The base stream must support random access (seek)"); readStream.BaseStream.Seek((long)_offset, SeekOrigin.Begin); stream.Write(readStream.ReadBytes((int) _storageSize)); actualSize = _actualSize; storageSize = _storageSize; storageType = _storageFormat; } } } #if NET40 public T Data { get { if (_strongRef != null) return _strongRef; T loadedData = null; if (_data == null || (loadedData = _data.Target as T) == null) { lock (_file) { if (_data == null || (loadedData = _data.Target as T) == null) { loadedData = ReadData(); _data = new WeakReference(loadedData); } } } return loadedData; } set { _data = new WeakReference(value); } } #else public T Data { get { if (_strongRef != null) return _strongRef; if (_data == null || !_data.TryGetTarget(out T loadedData)) { lock (_file) { var weakRef = Volatile.Read(ref _data); if (weakRef == null || !weakRef.TryGetTarget(out loadedData)) { loadedData = ReadData(); Volatile.Write(ref _data, new WeakReference<T>(loadedData)); } } } return loadedData; } set { Volatile.Write(ref _data, new WeakReference<T>(value)); } } #endif } }
0
0.974202
1
0.974202
game-dev
MEDIA
0.362438
game-dev
0.985836
1
0.985836
qnpiiz/rich-2.0
1,634
src/main/java/net/minecraft/command/impl/SetWorldSpawnCommand.java
package net.minecraft.command.impl; import com.mojang.brigadier.CommandDispatcher; import net.minecraft.command.CommandSource; import net.minecraft.command.Commands; import net.minecraft.command.arguments.AngleArgument; import net.minecraft.command.arguments.BlockPosArgument; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TranslationTextComponent; public class SetWorldSpawnCommand { public static void register(CommandDispatcher<CommandSource> dispatcher) { dispatcher.register(Commands.literal("setworldspawn").requires((p_198704_0_) -> { return p_198704_0_.hasPermissionLevel(2); }).executes((p_198700_0_) -> { return setSpawn(p_198700_0_.getSource(), new BlockPos(p_198700_0_.getSource().getPos()), 0.0F); }).then(Commands.argument("pos", BlockPosArgument.blockPos()).executes((p_198703_0_) -> { return setSpawn(p_198703_0_.getSource(), BlockPosArgument.getBlockPos(p_198703_0_, "pos"), 0.0F); }).then(Commands.argument("angle", AngleArgument.func_242991_a()).executes((p_244377_0_) -> { return setSpawn(p_244377_0_.getSource(), BlockPosArgument.getBlockPos(p_244377_0_, "pos"), AngleArgument.func_242992_a(p_244377_0_, "angle")); })))); } private static int setSpawn(CommandSource source, BlockPos pos, float p_198701_2_) { source.getWorld().func_241124_a__(pos, p_198701_2_); source.sendFeedback(new TranslationTextComponent("commands.setworldspawn.success", pos.getX(), pos.getY(), pos.getZ(), p_198701_2_), true); return 1; } }
0
0.558095
1
0.558095
game-dev
MEDIA
0.969161
game-dev
0.71291
1
0.71291
lagom/lagom
19,453
persistence/javadsl/src/main/scala/com/lightbend/lagom/javadsl/persistence/PersistentEntity.scala
/* * Copyright (C) Lightbend Inc. <https://www.lightbend.com> */ package com.lightbend.lagom.javadsl.persistence import akka.japi.Util.immutableSeq import scala.collection.immutable import java.util.function.{ BiFunction => JBiFunction } import java.util.function.{ Consumer => JConsumer } import java.util.function.{ BiConsumer => JBiConsumer } import java.util.function.{ Function => JFunction } import java.util.{ List => JList } import java.util.Optional import akka.event.LoggingAdapter import scala.annotation.varargs import scala.util.control.NoStackTrace import scala.annotation.tailrec import akka.japi.Effect import akka.event.Logging object PersistentEntity { /** * Commands to a `PersistentEntity` must implement this interface * to define the reply type. * * `akka.Done` can optionally be used as a "standard" acknowledgment message. * * Type parameter `R` is the type of the reply message. */ trait ReplyType[R] /** * Standard exception when rejecting invalid commands. */ final case class InvalidCommandException(message: String) extends IllegalArgumentException(message) with NoStackTrace /** * Exception that is used when command is not handled */ final case class UnhandledCommandException(message: String) extends IllegalArgumentException(message) with NoStackTrace /** * Exception that is used when persist fails. */ final case class PersistException(message: String) extends IllegalArgumentException(message) with NoStackTrace } /** * A `PersistentEntity` has a stable entity identifier, with which * it can be accessed from anywhere in the cluster. It is run by an actor * and the state is persistent using event sourcing. * * `initialBehavior` is an abstract method that your concrete subclass must implement. * It returns the `Behavior` of the entity. The behavior consists of current state * and functions to process incoming commands and persisted events. * * The `PersistentEntity` receives commands of type `Command` that can be validated before * persisting state changes as events of type `Event`. The functions that process incoming * commands are registered in the `Behavior` using `setCommandHandler` of the * `BehaviorBuilder`. * * A command may also be read-only and only perform some side-effect, such as replying * to the request. Such command handlers are registered using `setReadOnlyCommandHandler` * of the `BehaviorBuilder`. Replies are sent with the `reply` method of the context that * is passed to the command handler function. * * A command handler returns a `Persist` directive that defines what event or events, * if any, to persist. Use the `thenPersist`, `thenPersistAll` or `done` methods of the * context that is passed to the command handler function to create the `Persist` directive. * * When an event has been persisted successfully the state of type `State` is updated by * applying the event to the current state. The functions for updating the state are * registered with the `setEventHandler` method of the `BehaviorBuilder`. * The event handler returns the new state. The state must be immutable, so you return * a new instance of the state. Current state can be accessed from the event handler with * the `state` method of the `PersistentEntity`. The same event handlers are also used when * the entity is started up to recover its state from the stored events. * * After persisting an event, external side effects can be performed in the `afterPersist` * function that can be defined when creating the `Persist` directive. * A typical side effect is to reply to the request to confirm that it was performed * successfully. Replies are sent with the `reply` method of the context that is passed * to the command handler function. * * The command handlers may emit zero, one or many events. When many events are emitted, * they are stored atomically and in the same order they were emitted. Only after persisting * all the events external side effects will be performed. * * The event handlers are typically only updating the state, but they may also change * the behavior of the entity in the sense that new functions for processing commands * and events may be defined. This is useful when implementing finite state machine (FSM) * like entities. Event handlers that change the behavior are registered with the * `setEventHandlerChangingBehavior` of the `BehaviorBuilder`. Such an event handler * returns the new `Behavior` instead of just returning the new state. You can * access current behavior with the `behavior` method of the `PersistentEntity` * and using the `builder` method of the `Behavior`. * * When the entity is started the state is recovered by replaying stored events. * To reduce this recovery time the entity may start the recovery from a snapshot * of the state and then only replaying the events that were stored after the snapshot. * Such snapshots are automatically saved after a configured number of persisted events. * The snapshot if any is passed as a parameter to the `initialBehavior` method and * you should use that state as the state of the returned `Behavior`. * One thing to keep in mind is that if you are using event handlers that change the * behavior (`setEventHandlerChangingBehavior`) you must also restore corresponding * `Behavior` from the snapshot state that is passed as a parameter to the `initialBehavior` * method. * * Type parameter `Command`: * the super type of all commands, must implement [[PersistentEntity.ReplyType]] * to define the reply type of each command type * Type parameter `Event`: * the super type of all events * Type parameter `State`: * the type of the state */ abstract class PersistentEntity[Command, Event, State] { import PersistentEntity.ReplyType private var _entityId: String = _ protected final def entityId: String = _entityId /** * INTERNAL API */ private[lagom] def internalSetEntityId(id: String) = _entityId = id private var _behavior: Behavior = _ final def behavior: Behavior = _behavior /** * INTERNAL API */ private[lagom] def internalSetCurrentBehavior(b: Behavior) = _behavior = b /** * The name of this entity type. It should be unique among the entity * types of the service. By default it is using the short class name * of the concrete `PersistentEntity` class. Subclass may override * to define other type names. It is needed to override and retain * the original name when the class name is changed because this name * is part of the key of the store data (it is part of the `persistenceId` * of the underlying `PersistentActor`). */ def entityTypeName: String = Logging.simpleName(getClass) /** * Abstract method that must be implemented by concrete subclass to define * the behavior of the entity. Use [[#newBehaviorBuilder]] to create a mutable builder * for defining the behavior. */ def initialBehavior(snapshotState: Optional[State]): Behavior /** * This method is called to notify the entity that the recovery process * is finished. */ def recoveryCompleted(): Behavior = _behavior /** * Current state of the entity. Typically accessed from event and command handlers. */ protected final def state: State = _behavior.state /** * Create a new empty `Behavior` with a given state. */ final def newBehavior(state: State): Behavior = new Behavior(state, Map.empty, Map.empty) /** * Create a new empty `BehaviorBuilder` with a given state. */ final def newBehaviorBuilder(state: State): BehaviorBuilder = new BehaviorBuilderImpl(state) /** * Behavior consists of current state and functions to process incoming commands * and persisted events. `Behavior` is an immutable class. Use the mutable [[BehaviorBuilder]] * for defining command and event handlers. */ case class Behavior( state: State, eventHandlers: Map[Class[_ <: Event], JFunction[_ <: Event, Behavior]], commandHandlers: Map[Class[_ <: Command], JBiFunction[_ <: Command, CommandContext[Any], Persist[_ <: Event]]] ) { /** * @return new instance with the given state */ def withState(newState: State): Behavior = copy(state = newState) /** * Create a `BehaviorBuilder` that corresponds to this `Behavior`, i.e. the builder * is populated with same state, same event and command handler functions. */ def builder(): BehaviorBuilder = new BehaviorBuilderImpl(state, eventHandlers, commandHandlers) } // in order to keep all the constructors protected but still generate javadocs this class // extends a public sealed trait where documentation is provided. private final class BehaviorBuilderImpl( state: State, evtHandlers: Map[Class[_ <: Event], JFunction[_ <: Event, Behavior]], cmdHandlers: Map[Class[_ <: Command], JBiFunction[_ <: Command, CommandContext[Any], Persist[_ <: Event]]] ) extends BehaviorBuilder { def this(state: State) = this(state, Map.empty, Map.empty) private var _state = state private var eventHandlers: Map[Class[_ <: Event], JFunction[_ <: Event, Behavior]] = evtHandlers private var commandHandlers : Map[Class[_ <: Command], JBiFunction[_ <: Command, CommandContext[Any], Persist[_ <: Event]]] = cmdHandlers @scala.deprecated("The method is deprecated because it was deemed obsolete", since = "1.5.0") def getState(): State = _state @scala.deprecated("The method is deprecated because it was deemed obsolete", since = "1.5.0") def setState(state: State): Unit = { _state = state } def setEventHandler[A <: Event](eventClass: Class[A], handler: JFunction[A, State]): Unit = setEventHandlerChangingBehavior[A](eventClass, new JFunction[A, Behavior] { override def apply(evt: A): Behavior = behavior.withState(handler.apply(evt)) }) def setEventHandlerChangingBehavior[A <: Event](eventClass: Class[A], handler: JFunction[A, Behavior]): Unit = eventHandlers = eventHandlers.updated(eventClass, handler) def removeEventHandler(eventClass: Class[_ <: Event]): Unit = eventHandlers -= eventClass def setCommandHandler[R, A <: Command with ReplyType[R]]( commandClass: Class[A], handler: JBiFunction[A, CommandContext[R], Persist[_ <: Event]] ): Unit = { commandHandlers = commandHandlers.updated( commandClass, handler.asInstanceOf[JBiFunction[A, CommandContext[Any], Persist[_ <: Event]]] ) } def removeCommandHandler(commandClass: Class[_ <: Command]): Unit = commandHandlers -= commandClass def setReadOnlyCommandHandler[R, A <: Command with ReplyType[R]]( commandClass: Class[A], handler: JBiConsumer[A, ReadOnlyCommandContext[R]] ): Unit = { setCommandHandler[R, A]( commandClass, new JBiFunction[A, CommandContext[R], Persist[_ <: Event]] { override def apply(cmd: A, ctx: CommandContext[R]): Persist[Event] = { handler.accept(cmd, ctx) ctx.done() } } ); } def build(): Behavior = Behavior(_state, eventHandlers, commandHandlers) } /** * Mutable builder that is used for defining the event and command handlers. * Use [[BehaviorBuilder#build]] to create the immutable [[PersistentEntity.Behavior]]. */ // In order to provide javadoc preventing instantiation or extension this sealed abstract class is added // to hold docs and BehaviorBuilderImpl is made private to hold implementation. // It is required to be an abstract class, not a trait, because it refers to type variables from the enclosing scope. // This would be legal in Scala, but causes inter-operation problems with some Java compilers (such as Eclipse). // See https://github.com/lagom/lagom/pull/1395 sealed abstract class BehaviorBuilder { @scala.deprecated("The method is deprecated because it was deemed obsolete", since = "1.5.0") def getState(): State @scala.deprecated("The method is deprecated because it was deemed obsolete", since = "1.5.0") def setState(state: State): Unit /** * Register an event handler for a given event class. The `handler` function * is supposed to return the new state after applying the event to the current state. * Current state can be accessed with the `state` method of the `PersistentEntity`. * * Invoking this method a second time for the same `eventClass` will override the existing `handler`. */ def setEventHandler[A <: Event](eventClass: Class[A], handler: JFunction[A, State]): Unit /** * Register an event handler that is updating the behavior for a given event class. * The `handler` function is supposed to return the new behavior after applying the * event to the current state. Current behavior can be accessed with the `behavior` * method of the `PersistentEntity`. * * Invoking this method a second time for the same `eventClass` will override the existing `handler`. */ def setEventHandlerChangingBehavior[A <: Event](eventClass: Class[A], handler: JFunction[A, Behavior]): Unit /** * Remove an event handler for a given event class. */ def removeEventHandler(eventClass: Class[_ <: Event]): Unit /** * Register a command handler for a given command class. * * The `handler` function is supposed to return a `Persist` directive that defines * what event or events, if any, to persist. Use the `thenPersist`, `thenPersistAll` * or `done` methods of the context that is passed to the handler function to create the * `Persist` directive. * * After persisting an event external side effects can be performed in the `afterPersist` * function that can be defined when creating the `Persist` directive. * A typical side effect is to reply to the request to confirm that it was performed * successfully. Replies are sent with the `reply` method of the context that is passed * to the command handler function. * * The `handler` function may validate the incoming command and reject it by * sending a `reply` and returning `ctx.done()`. * * Invoking this method a second time for the same `commandClass` will override the existing `handler`. */ def setCommandHandler[R, A <: Command with ReplyType[R]]( commandClass: Class[A], handler: JBiFunction[A, CommandContext[R], Persist[_ <: Event]] ): Unit /** * Remove a command handler for a given command class. */ def removeCommandHandler(commandClass: Class[_ <: Command]): Unit /** * Register a read-only command handler for a given command class. A read-only command * handler does not persist events (i.e. it does not change state) but it may perform side * effects, such as replying to the request. Replies are sent with the `reply` method of the * context that is passed to the command handler function. * * Invoking this method a second time for the same `commandClass` will override the existing `handler`. */ def setReadOnlyCommandHandler[R, A <: Command with ReplyType[R]]( commandClass: Class[A], handler: JBiConsumer[A, ReadOnlyCommandContext[R]] ): Unit /** * Construct the corresponding immutable `Behavior`. */ def build(): Behavior } /** * The context that is passed to read-only command handlers. */ abstract class ReadOnlyCommandContext[R] { /** * Send reply to a command. The type `R` must be the type defined by * the command. */ def reply(msg: R): Unit /** * Reply with a negative acknowledgment. */ def commandFailed(cause: Throwable): Unit /** * Reply with a negative acknowledgment using the standard * `InvalidCommandException`. */ def invalidCommand(message: String): Unit = commandFailed(new PersistentEntity.InvalidCommandException(message)) } /** * The context that is passed to command handler function. */ abstract class CommandContext[R] extends ReadOnlyCommandContext[R] { /** * A command handler may return this `Persist` directive to define * that one event is to be persisted. */ def thenPersist[B <: Event](event: B): Persist[B] = return new PersistOne(event, afterPersist = null) /** * A command handler may return this `Persist` directive to define * that one event is to be persisted. External side effects can be * performed after successful persist in the `afterPersist` function. */ def thenPersist[B <: Event](event: B, afterPersist: JConsumer[B]): Persist[B] = return new PersistOne(event, afterPersist) /** * A command handler may return this `Persist` directive to define * that several events are to be persisted. Events will be persisted * atomically and in the same order as they are passed here. */ def thenPersistAll[B <: Event](events: JList[B]): Persist[B] = return new PersistAll(immutableSeq(events), afterPersist = null) /** * A command handler may return this `Persist` directive to define * that several events are to be persisted. External side effects can be * performed after successful persist in the `afterPersist` function. * `afterPersist` is invoked once when all events have been persisted * successfully. Events will be persisted atomically and in the same * order as they are passed here. */ def thenPersistAll[B <: Event](events: JList[B], afterPersist: Effect): Persist[B] = return new PersistAll(immutableSeq(events), afterPersist) /** * A command handler may return this `Persist` directive to define * that several events are to be persisted. External side effects can be * performed after successful persist in the `afterPersist` function. * `afterPersist` is invoked once when all events have been persisted * successfully. */ @varargs def thenPersistAll[B <: Event](afterPersist: Effect, events: B*): Persist[B] = return new PersistAll(events.toList, afterPersist) /** * A command handler may return this `Persist` directive to define * that no events are to be persisted. */ def done[B <: Event](): Persist[B] = persistNone.asInstanceOf[Persist[B]] } /** * A command handler returns a `Persist` directive that defines what event or events, * if any, to persist. Use the `thenPersist`, `thenPersistAll` or `done` methods of the context * that is passed to the command handler function to create the `Persist` directive. */ abstract class Persist[B <: Event] /** * INTERNAL API */ private[lagom] case class PersistOne[B <: Event](val event: B, val afterPersist: JConsumer[B]) extends Persist[B] /** * INTERNAL API */ private[lagom] case class PersistAll[B <: Event](val events: immutable.Seq[B], val afterPersist: Effect) extends Persist[B] /** * INTERNAL API */ private[lagom] case class PersistNone[B <: Event]() extends Persist[B] { override def toString: String = "PersistNone" } private val persistNone: PersistNone[Nothing] = PersistNone[Nothing] }
0
0.896666
1
0.896666
game-dev
MEDIA
0.333488
game-dev
0.696488
1
0.696488
BlueLightJapan/BlueLight
1,348
src/pocketmine/block/CoalOre.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\item\Item; use pocketmine\item\ItemFactory; use pocketmine\item\Tool; class CoalOre extends Solid{ protected $id = self::COAL_ORE; public function __construct(int $meta = 0){ $this->meta = $meta; } public function getHardness() : float{ return 3; } public function getToolType() : int{ return Tool::TYPE_PICKAXE; } public function getName() : string{ return "Coal Ore"; } public function getDrops(Item $item) : array{ if($item->isPickaxe() >= Tool::TIER_WOODEN){ return [ ItemFactory::get(Item::COAL, 0, 1) ]; } return []; } }
0
0.93584
1
0.93584
game-dev
MEDIA
0.980104
game-dev
0.871083
1
0.871083
morty6688/cs61b-sp18
2,302
hw3/hw3/hash/SimpleOomage.java
package hw3.hash; import java.awt.Color; import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.StdDraw; public class SimpleOomage implements Oomage { protected int red; protected int green; protected int blue; private static final double WIDTH = 0.01; private static final boolean USE_PERFECT_HASH = true; @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof SimpleOomage)) { return false; } SimpleOomage so = (SimpleOomage) o; return this.red == so.red && this.green == so.green && this.blue == so.blue; } @Override public int hashCode() { if (!USE_PERFECT_HASH) { return red + green + blue; } else { int res = Integer.hashCode(red / 5); res = res * 53 + Integer.hashCode(green / 5); res = res * 71 + Integer.hashCode(blue / 5); return res; } } public SimpleOomage(int r, int g, int b) { if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) { throw new IllegalArgumentException(); } if ((r % 5 != 0) || (g % 5 != 0) || (b % 5 != 0)) { throw new IllegalArgumentException("red/green/blue values must all be multiples of 5!"); } red = r; green = g; blue = b; } @Override public void draw(double x, double y, double scalingFactor) { StdDraw.setPenColor(new Color(red, green, blue)); StdDraw.filledSquare(x, y, WIDTH * scalingFactor); } public static SimpleOomage randomSimpleOomage() { int red = StdRandom.uniform(0, 51) * 5; int green = StdRandom.uniform(0, 51) * 5; int blue = StdRandom.uniform(0, 51) * 5; return new SimpleOomage(red, green, blue); } public static void main(String[] args) { System.out.println("Drawing 4 random simple Oomages."); randomSimpleOomage().draw(0.25, 0.25, 1); randomSimpleOomage().draw(0.75, 0.75, 1); randomSimpleOomage().draw(0.25, 0.75, 1); randomSimpleOomage().draw(0.75, 0.25, 1); } public String toString() { return "R: " + red + ", G: " + green + ", B: " + blue; } }
0
0.721574
1
0.721574
game-dev
MEDIA
0.49931
game-dev
0.925926
1
0.925926
SlimeKnights/TinkersConstruct
2,416
src/main/java/slimeknights/tconstruct/library/client/book/sectiontransformer/materials/AbstractMaterialSectionTransformer.java
package slimeknights.tconstruct.library.client.book.sectiontransformer.materials; import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.SectionData; import slimeknights.mantle.client.book.transformer.SectionTransformer; import slimeknights.tconstruct.library.client.book.content.AbstractMaterialContent; import slimeknights.tconstruct.library.client.book.content.MeleeHarvestMaterialContent; import slimeknights.tconstruct.library.materials.definition.IMaterial; import slimeknights.tconstruct.library.materials.definition.MaterialVariantId; import java.util.function.Function; import java.util.function.Predicate; /** @deprecated use {@link TierRangeMaterialSectionTransformer} */ @Deprecated(forRemoval = true) public abstract class AbstractMaterialSectionTransformer extends SectionTransformer { protected final boolean detailed; public AbstractMaterialSectionTransformer(String sectionName, boolean detailed) { super(sectionName); this.detailed = detailed; } /** * Determines if a material should show in this book * @param material Material to check * @return True if it should show */ protected abstract boolean isValidMaterial(IMaterial material); /** * Gets the page for the given material, can override if you use a different page type * @param material Material to display * @return Material page */ protected AbstractMaterialContent getPageContent(MaterialVariantId material) { return new MeleeHarvestMaterialContent(material, detailed); } @Override public void transform(BookData book, SectionData sectionData) { createPages(book, sectionData, this::isValidMaterial, this::getPageContent); } /** * Creates all the pages for the materials * @param book Book data * @param sectionData Section data * @param validMaterial Predicate to validate materials * @param pageCreator Logic to create a page * @deprecated use {@link TierRangeMaterialSectionTransformer#createPages(BookData, SectionData, Predicate, Function)} */ @Deprecated(forRemoval = true) public static void createPages(BookData book, SectionData sectionData, Predicate<IMaterial> validMaterial, Function<MaterialVariantId,AbstractMaterialContent> pageCreator) { TierRangeMaterialSectionTransformer.createPages(book, sectionData, validMaterial, pageCreator, null); } }
0
0.81465
1
0.81465
game-dev
MEDIA
0.74849
game-dev
0.854858
1
0.854858
Gegy/tic-tacs
2,643
src/main/java/net/gegy1000/tictacs/client/LevelMapOverlay.java
package net.gegy1000.tictacs.client; import net.gegy1000.tictacs.TicTacs; import net.gegy1000.tictacs.chunk.ChunkController; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.DrawableHelper; import net.minecraft.client.texture.NativeImage; import net.minecraft.client.texture.NativeImageBackedTexture; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.client.world.ClientWorld; import net.minecraft.server.integrated.IntegratedServer; import net.minecraft.server.world.ServerWorld; import net.minecraft.server.world.ThreadedAnvilChunkStorage; import net.minecraft.util.Identifier; public final class LevelMapOverlay extends DrawableHelper implements AutoCloseable { private static final MinecraftClient CLIENT = MinecraftClient.getInstance(); private static final Identifier TEXTURE_ID = new Identifier(TicTacs.ID, "level_map"); private NativeImageBackedTexture texture; private int textureWidth; private int textureHeight; private long lastTextureUpdate; public void render(MatrixStack transform) { ClientWorld clientWorld = CLIENT.world; if (clientWorld == null) { return; } IntegratedServer server = CLIENT.getServer(); if (server == null) { return; } long time = clientWorld.getTime(); if (time - this.lastTextureUpdate > 20) { ServerWorld serverWorld = server.getWorld(clientWorld.getRegistryKey()); ThreadedAnvilChunkStorage tacs = serverWorld.getChunkManager().threadedAnvilChunkStorage; ChunkController controller = (ChunkController) tacs; NativeImage image = LevelMapRenderer.render(CLIENT.player.getPos(), controller); this.updateTexture(image); this.lastTextureUpdate = time; } CLIENT.getTextureManager().bindTexture(TEXTURE_ID); DrawableHelper.drawTexture(transform, 0, 0, 0.0F, 0.0F, this.textureWidth, this.textureHeight, this.textureWidth, this.textureHeight); } private void updateTexture(NativeImage image) { this.releaseTexture(); this.texture = new NativeImageBackedTexture(image); this.textureWidth = image.getWidth(); this.textureHeight = image.getHeight(); CLIENT.getTextureManager().registerTexture(TEXTURE_ID, this.texture); } @Override public void close() { this.releaseTexture(); CLIENT.getTextureManager().destroyTexture(TEXTURE_ID); } private void releaseTexture() { if (this.texture != null) { this.texture.close(); } } }
0
0.825464
1
0.825464
game-dev
MEDIA
0.799495
game-dev,graphics-rendering
0.801345
1
0.801345
Negodya1/Create-Vintage-Improvements
2,951
src/main/java/com/negodya1/vintageimprovements/compat/jei/category/LaserCuttingCategory.java
package com.negodya1.vintageimprovements.compat.jei.category; import com.negodya1.vintageimprovements.VintageImprovements; import com.negodya1.vintageimprovements.compat.jei.category.animations.AnimatedCentrifuge; import com.negodya1.vintageimprovements.compat.jei.category.animations.AnimatedLaser; import com.negodya1.vintageimprovements.content.kinetics.centrifuge.CentrifugationRecipe; import com.negodya1.vintageimprovements.content.kinetics.helve_hammer.HammeringRecipe; import com.negodya1.vintageimprovements.content.kinetics.laser.LaserCuttingRecipe; import com.simibubi.create.compat.jei.category.CreateRecipeCategory; import com.simibubi.create.content.processing.recipe.ProcessingOutput; import com.simibubi.create.foundation.fluid.FluidIngredient; import com.simibubi.create.foundation.gui.AllGuiTextures; import mezz.jei.api.forge.ForgeTypes; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.gui.ingredient.IRecipeSlotsView; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; import net.minecraft.world.item.Items; import net.minecraft.world.item.crafting.Ingredient; import net.minecraftforge.fluids.FluidStack; import javax.annotation.ParametersAreNonnullByDefault; import java.util.List; @ParametersAreNonnullByDefault public class LaserCuttingCategory extends CreateRecipeCategory<LaserCuttingRecipe> { private final AnimatedLaser laser = new AnimatedLaser(); public LaserCuttingCategory(Info<LaserCuttingRecipe> info) { super(info); } @Override public void setRecipe(IRecipeLayoutBuilder builder, LaserCuttingRecipe recipe, IFocusGroup focuses) { List<Ingredient> inputs = recipe.getIngredients(); int i = 0; for (Ingredient ingredient : inputs) { int xOffset = i * 19; builder .addSlot(RecipeIngredientRole.INPUT, 4 + xOffset, 36) .setBackground(getRenderedSlot(), -1, -1) .addIngredients(ingredient); i++; } i = 0; List<ProcessingOutput> results = recipe.getRollableResults(); for (ProcessingOutput result : results) { builder .addSlot(RecipeIngredientRole.OUTPUT, 148 - (10 * results.size()) + 19 * i, 48) .setBackground(getRenderedSlot(result), -1, -1) .addItemStack(result.getStack()) .addTooltipCallback(addStochasticTooltip(result)); i++; } } @Override public void draw(LaserCuttingRecipe recipe, IRecipeSlotsView iRecipeSlotsView, GuiGraphics graphics, double mouseX, double mouseY) { AllGuiTextures.JEI_DOWN_ARROW.render(graphics, 132, 28); AllGuiTextures.JEI_LONG_ARROW.render(graphics, 2, 55); laser.draw(graphics, 86, 22); graphics.drawCenteredString(Minecraft.getInstance().font, Component.translatable(VintageImprovements.MODID + ".jei.text.energy") .append(" " + recipe.getEnergy() + "fe"), 88, 75, 0xFFFFFF); } }
0
0.636406
1
0.636406
game-dev
MEDIA
0.947184
game-dev
0.624731
1
0.624731
gamingdotme/opensource-casino-v10
41,375
casino/app/Games/OceanParadiseVP/SlotSettings.php
<?php namespace VanguardLTE\Games\OceanParadiseVP { class SlotSettings { public $playerId = null; public $splitScreen = null; public $reelStrip1 = null; public $reelStrip2 = null; public $reelStrip3 = null; public $reelStrip4 = null; public $reelStrip5 = null; public $reelStrip6 = null; public $reelStripBonus1 = null; public $reelStripBonus2 = null; public $reelStripBonus3 = null; public $reelStripBonus4 = null; public $reelStripBonus5 = null; public $reelStripBonus6 = null; public $slotId = ''; public $slotDBId = ''; public $Line = null; public $scaleMode = null; public $numFloat = null; public $gameLine = null; public $Bet = null; public $isBonusStart = null; public $Balance = null; public $SymbolGame = null; public $GambleType = null; public $lastEvent = null; public $Jackpots = []; public $keyController = null; public $slotViewState = null; public $hideButtons = null; public $slotReelsConfig = null; public $slotFreeCount = null; public $slotFreeMpl = null; public $slotWildMpl = null; public $slotExitUrl = null; public $slotBonus = null; public $slotBonusType = null; public $slotScatterType = null; public $slotGamble = null; public $Paytable = []; public $slotSounds = []; private $jpgs = null; private $Bank = null; private $Percent = null; private $WinLine = null; private $WinGamble = null; private $Bonus = null; public $shop_id = null; public $currency = null; public $user = null; public $game = null; public $shop = null; public $jpgPercentZero = false; public $count_balance = null; public function __construct($sid, $playerId) { $this->slotId = $sid; $this->playerId = $playerId; $user = \VanguardLTE\User::lockForUpdate()->find($this->playerId); $this->user = $user; $this->username = $user->username; $this->shop_id = $user->shop_id; $gamebank = \VanguardLTE\GameBank::where(['shop_id' => $this->shop_id])->lockForUpdate()->get(); $game = \VanguardLTE\Game::where([ 'name' => $this->slotId, 'shop_id' => $this->shop_id ])->lockForUpdate()->first(); $this->shop = \VanguardLTE\Shop::find($this->shop_id); $this->game = $game; $this->MaxWin = $this->shop->max_win; $this->increaseRTP = 1; $this->Denominations = \VanguardLTE\Game::$values['denomination']; $this->CurrentDenom = 1; $this->scaleMode = 0; $this->numFloat = 0; $this->Paytable['Fish_1'] = [2]; $this->Paytable['Fish_2'] = [3]; $this->Paytable['Fish_3'] = [4]; $this->Paytable['Fish_4'] = [5]; $this->Paytable['Fish_5'] = [6]; $this->Paytable['Fish_6'] = [7]; $this->Paytable['Fish_7'] = [8]; $this->Paytable['Fish_8'] = [9]; $this->Paytable['Fish_9'] = [10]; $this->Paytable['Fish_10'] = [12]; $this->Paytable['Fish_11'] = [15]; $this->Paytable['Fish_12'] = [18]; $this->Paytable['Fish_13'] = [20]; $this->Paytable['Fish_14'] = [ 10, 30 ]; $this->Paytable['Fish_15'] = [ 10, 30 ]; $this->Paytable['Fish_16'] = [ 10, 30 ]; $this->Paytable['Fish_17'] = [ 20, 60 ]; $this->Paytable['Fish_18'] = [ 30, 100 ]; $this->Paytable['Fish_19'] = [100]; $this->Paytable['Fish_20'] = [0]; $this->Paytable['Fish_21'] = [0]; $this->Paytable['Fish_22'] = [0]; $this->Paytable['Fish_23'] = [0]; $this->Paytable['Fish_24'] = [0]; $this->Paytable['Fish_25'] = [0]; $this->Paytable['Fish_26'] = [0]; $this->Paytable['Fish_27'] = [0]; $this->Paytable['Fish_28'] = [0]; $this->Paytable['Fish_29'] = [0]; $this->Paytable['Fish_30'] = [0]; $this->FishDamage = []; $this->FishDamage['Fish_1'] = [4]; $this->FishDamage['Fish_2'] = [5]; $this->FishDamage['Fish_3'] = [6]; $this->FishDamage['Fish_4'] = [7]; $this->FishDamage['Fish_5'] = [8]; $this->FishDamage['Fish_6'] = [9]; $this->FishDamage['Fish_7'] = [10]; $this->FishDamage['Fish_8'] = [10]; $this->FishDamage['Fish_9'] = [10]; $this->FishDamage['Fish_10'] = [15]; $this->FishDamage['Fish_11'] = [15]; $this->FishDamage['Fish_12'] = [20]; $this->FishDamage['Fish_13'] = [25]; $this->FishDamage['Fish_14'] = [25]; $this->FishDamage['Fish_15'] = [30]; $this->FishDamage['Fish_16'] = [30]; $this->FishDamage['Fish_17'] = [40]; $this->FishDamage['Fish_18'] = [40]; $this->FishDamage['Fish_19'] = [40]; $this->FishDamage['Fish_20'] = [50]; $this->FishDamage['Fish_21'] = [50]; $this->FishDamage['Fish_22'] = [50]; $this->FishDamage['Fish_23'] = [50]; $this->FishDamage['Fish_24'] = [100]; $this->FishDamage['Fish_25'] = [100]; $this->FishDamage['Fish_26'] = [100]; $this->FishDamage['Fish_27'] = [200]; $this->FishDamage['Fish_28'] = [200]; $this->FishDamage['Fish_29'] = [200]; $this->FishDamage['Fish_30'] = [200]; $reel = new GameReel(); foreach( [ 'reelStrip1', 'reelStrip2', 'reelStrip3', 'reelStrip4', 'reelStrip5', 'reelStrip6' ] as $reelStrip ) { if( count($reel->reelsStrip[$reelStrip]) ) { $this->$reelStrip = $reel->reelsStrip[$reelStrip]; } } $this->keyController = [ '13' => 'uiButtonSpin,uiButtonSkip', '49' => 'uiButtonInfo', '50' => 'uiButtonCollect', '51' => 'uiButtonExit2', '52' => 'uiButtonLinesMinus', '53' => 'uiButtonLinesPlus', '54' => 'uiButtonBetMinus', '55' => 'uiButtonBetPlus', '56' => 'uiButtonGamble', '57' => 'uiButtonRed', '48' => 'uiButtonBlack', '189' => 'uiButtonAuto', '187' => 'uiButtonSpin' ]; $this->slotReelsConfig = [ [ 425, 142, 3 ], [ 669, 142, 3 ], [ 913, 142, 3 ], [ 1157, 142, 3 ], [ 1401, 142, 3 ] ]; $this->slotBonusType = 1; $this->slotScatterType = 0; $this->splitScreen = false; $this->slotBonus = false; $this->slotGamble = false; $this->slotFastStop = 1; $this->slotExitUrl = '/'; $this->slotWildMpl = 1; $this->GambleType = 1; $this->slotFreeCount = 1; $this->slotFreeMpl = 1; $this->slotViewState = ($game->slotViewState == '' ? 'Normal' : $game->slotViewState); $this->hideButtons = []; $this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get(); $this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get(); $this->slotJackPercent = []; $this->slotJackpot = []; for( $jp = 0; $jp < 4; $jp++ ) { if( $this->jpgs[$jp]->balance != '' ) { $this->slotJackpot[$jp] = sprintf('%01.4f', $this->jpgs[$jp]->balance); $this->slotJackpot[$jp] = substr($this->slotJackpot[$jp], 0, strlen($this->slotJackpot[$jp]) - 2); $this->slotJackPercent[] = $this->jpgs[$jp]->percent; } } $this->Line = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]; $this->gameLine = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]; $this->Bet = explode(',', $game->bet); $this->Bet = array_slice($this->Bet, 0, 5); $this->Balance = $user->balance; $this->SymbolGame = [ '0', '1', 2, 3, 4, 5, 6, 7, 8 ]; $this->Bank = $game->get_gamebank(); $this->Percent = $this->shop->percent; $this->WinGamble = $game->rezerv; $this->slotDBId = $game->id; $this->slotCurrency = $user->shop->currency; $this->count_balance = $user->count_balance; if( $user->address > 0 && $user->count_balance == 0 ) { $this->Percent = 0; $this->jpgPercentZero = true; } else if( $user->count_balance == 0 ) { $this->Percent = 100; } if( !isset($this->user->session) || strlen($this->user->session) <= 0 ) { $this->user->session = serialize([]); } $this->gameData = unserialize($this->user->session); if( count($this->gameData) > 0 ) { foreach( $this->gameData as $key => $vl ) { if( $vl['timelife'] <= time() ) { unset($this->gameData[$key]); } } } } public function is_active() { if( $this->game && $this->shop && $this->user && (!$this->game->view || $this->shop->is_blocked || $this->user->is_blocked || $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED) ) { \VanguardLTE\Session::where('user_id', $this->user->id)->delete(); $this->user->update(['remember_token' => null]); return false; } if( !$this->game->view ) { return false; } if( $this->shop->is_blocked ) { return false; } if( $this->user->is_blocked ) { return false; } if( $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED ) { return false; } return true; } public function SetGameData($key, $value) { $timeLife = 86400; $this->gameData[$key] = [ 'timelife' => time() + $timeLife, 'payload' => $value ]; } public function GetGameData($key) { if( isset($this->gameData[$key]) ) { return $this->gameData[$key]['payload']; } else { return 0; } } public function FormatFloat($num) { $str0 = explode('.', $num); if( isset($str0[1]) ) { if( strlen($str0[1]) > 4 ) { return round($num * 100) / 100; } else if( strlen($str0[1]) > 2 ) { return floor($num * 100) / 100; } else { return $num; } } else { return $num; } } public function SaveGameData() { $this->user->session = serialize($this->gameData); $this->user->save(); } public function CheckBonusWin() { $allRateCnt = 0; $allRate = 0; foreach( $this->Paytable as $vl ) { foreach( $vl as $vl2 ) { if( $vl2 > 0 ) { $allRateCnt++; $allRate += $vl2; break; } } } return $allRate / $allRateCnt; } public function HasGameData($key) { if( isset($this->gameData[$key]) ) { return true; } else { return false; } } public function GetHistory() { $history = \VanguardLTE\GameLog::whereRaw('game_id=? and user_id=? ORDER BY id DESC LIMIT 10', [ $this->slotDBId, $this->playerId ])->get(); $this->lastEvent = 'NULL'; foreach( $history as $log ) { if( $log->str == 'NONE' ) { return 'NULL'; } $tmpLog = json_decode($log->str); if( $tmpLog->responseEvent != 'gambleResult' && $tmpLog->responseEvent != 'jackpot' ) { $this->lastEvent = $log->str; break; } } if( isset($tmpLog) ) { return $tmpLog; } else { return 'NULL'; } } public function ClearJackpot($jid) { $this->jpgs[$jid]->balance = sprintf('%01.4f', 0); $this->jpgs[$jid]->save(); } public function UpdateJackpots($bet) { $bet = $bet * $this->CurrentDenom; $count_balance = $this->count_balance; $jsum = []; $payJack = 0; for( $i = 0; $i < count($this->jpgs); $i++ ) { if( $count_balance == 0 || $this->jpgPercentZero ) { $jsum[$i] = $this->jpgs[$i]->balance; } else if( $count_balance < $bet ) { $jsum[$i] = $count_balance / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance; } else { $jsum[$i] = $bet / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance; } if( $this->jpgs[$i]->get_pay_sum() < $jsum[$i] && $this->jpgs[$i]->get_pay_sum() > 0 ) { if( $this->jpgs[$i]->user_id && $this->jpgs[$i]->user_id != $this->user->id ) { } else { $payJack = $this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom; $jsum[$i] = $jsum[$i] - $this->jpgs[$i]->get_pay_sum(); $this->SetBalance($this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom); if( $this->jpgs[$i]->get_pay_sum() > 0 ) { \VanguardLTE\StatGame::create([ 'user_id' => $this->playerId, 'balance' => $this->Balance * $this->CurrentDenom, 'bet' => 0, 'win' => $this->jpgs[$i]->get_pay_sum(), 'game' => $this->game->name . ' JPG ' . $this->jpgs[$i]->id, 'in_game' => 0, 'in_jpg' => 0, 'in_profit' => 0, 'shop_id' => $this->shop_id, 'date_time' => \Carbon\Carbon::now() ]); } } } $this->jpgs[$i]->balance = $jsum[$i]; $this->jpgs[$i]->save(); if( $this->jpgs[$i]->balance < $this->jpgs[$i]->get_min('start_balance') ) { $summ = $this->jpgs[$i]->get_start_balance(); if( $summ > 0 ) { $this->jpgs[$i]->add_jpg('add', $summ); } } } if( $payJack > 0 ) { $payJack = sprintf('%01.2f', $payJack); $this->Jackpots['jackPay'] = $payJack; } } public function GetBank($slotState = '') { if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' ) { $slotState = 'bonus'; } else { $slotState = ''; } $game = $this->game; $this->Bank = $game->get_gamebank($slotState); return $this->Bank / $this->CurrentDenom; } public function GetPercent() { return $this->Percent; } public function GetCountBalanceUser() { return $this->user->count_balance; } public function InternalErrorSilent($errcode) { $strLog = ''; $strLog .= "\n"; $strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}'); $strLog .= "\n"; $strLog .= ' ############################################### '; $strLog .= "\n"; $slg = ''; if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') ) { $slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log'); } file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog); } public function InternalError($errcode) { $strLog = ''; $strLog .= "\n"; $strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}'); $strLog .= "\n"; $strLog .= ' ############################################### '; $strLog .= "\n"; $slg = ''; if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') ) { $slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log'); } file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog); exit( '' ); } public function SetBank($slotState = '', $sum, $slotEvent = '') { if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' ) { $slotState = 'bonus'; } else { $slotState = ''; } if( $this->GetBank($slotState) + $sum < 0 ) { $this->InternalError('Bank_ ' . $sum . ' CurrentBank_ ' . $this->GetBank($slotState) . ' CurrentState_ ' . $slotState . ' Trigger_ ' . ($this->GetBank($slotState) + $sum)); } $sum = $sum * $this->CurrentDenom; $game = $this->game; $bankBonusSum = 0; if( $sum > 0 && $slotEvent == 'bet' ) { $this->toGameBanks = 0; $this->toSlotJackBanks = 0; $this->toSysJackBanks = 0; $this->betProfit = 0; $prc = $this->GetPercent(); $prc_b = 10; if( $prc <= $prc_b ) { $prc_b = 0; } $count_balance = $this->count_balance; $gameBet = $sum / $this->GetPercent() * 100; if( $count_balance < $gameBet && $count_balance > 0 ) { $firstBid = $count_balance; $secondBid = $gameBet - $firstBid; if( isset($this->betRemains0) ) { $secondBid = $this->betRemains0; } $bankSum = $firstBid / 100 * $this->GetPercent(); $sum = $bankSum + $secondBid; $bankBonusSum = $firstBid / 100 * $prc_b; } else if( $count_balance > 0 ) { $bankBonusSum = $gameBet / 100 * $prc_b; } for( $i = 0; $i < count($this->jpgs); $i++ ) { if( !$this->jpgPercentZero ) { if( $count_balance < $gameBet && $count_balance > 0 ) { $this->toSlotJackBanks += ($count_balance / 100 * $this->jpgs[$i]->percent); } else if( $count_balance > 0 ) { $this->toSlotJackBanks += ($gameBet / 100 * $this->jpgs[$i]->percent); } } } $this->toGameBanks = $sum; $this->betProfit = $gameBet - $this->toGameBanks - $this->toSlotJackBanks - $this->toSysJackBanks; } if( $sum > 0 ) { $this->toGameBanks = $sum; } if( $bankBonusSum > 0 ) { $sum -= $bankBonusSum; $game->set_gamebank($bankBonusSum, 'inc', 'bonus'); } if( $sum == 0 && $slotEvent == 'bet' && isset($this->betRemains) ) { $sum = $this->betRemains; } $game->set_gamebank($sum, 'inc', $slotState); $game->save(); return $game; } public function SetBalance($sum, $slotEvent = '') { if( $this->GetBalance() + $sum < 0 ) { $this->InternalError('Balance_ ' . $sum); } $sum = $sum * $this->CurrentDenom; if( $sum < 0 && $slotEvent == 'bet' ) { $user = $this->user; if( $user->count_balance == 0 ) { $remains = []; $this->betRemains = 0; $sm = abs($sum); if( $user->address < $sm && $user->address > 0 ) { $remains[] = $sm - $user->address; } for( $i = 0; $i < count($remains); $i++ ) { if( $this->betRemains < $remains[$i] ) { $this->betRemains = $remains[$i]; } } } if( $user->count_balance > 0 && $user->count_balance < abs($sum) ) { $remains0 = []; $sm = abs($sum); $tmpSum = $sm - $user->count_balance; $this->betRemains0 = $tmpSum; if( $user->address > 0 ) { $this->betRemains0 = 0; if( $user->address < $tmpSum && $user->address > 0 ) { $remains0[] = $tmpSum - $user->address; } for( $i = 0; $i < count($remains0); $i++ ) { if( $this->betRemains0 < $remains0[$i] ) { $this->betRemains0 = $remains0[$i]; } } } } $sum0 = abs($sum); if( $user->count_balance == 0 ) { $sm = abs($sum); if( $user->address < $sm && $user->address > 0 ) { $user->address = 0; } else if( $user->address > 0 ) { $user->address -= $sm; } } else if( $user->count_balance > 0 && $user->count_balance < $sum0 ) { $sm = $sum0 - $user->count_balance; if( $user->address < $sm && $user->address > 0 ) { $user->address = 0; } else if( $user->address > 0 ) { $user->address -= $sm; } } $this->user->count_balance = $this->user->updateCountBalance($sum, $this->count_balance); $this->user->count_balance = $this->FormatFloat($this->user->count_balance); } $this->user->increment('balance', $sum); $this->user->balance = $this->FormatFloat($this->user->balance); $this->user->save(); return $this->user; } public function GetBalance() { $user = $this->user; $this->Balance = $user->balance / $this->CurrentDenom; return $this->Balance; } public function SaveLogReport($spinSymbols, $bet, $lines, $win, $slotState) { $reportName = $this->slotId . ' ' . $slotState; if( $slotState == 'freespin' ) { $reportName = $this->slotId . ' FG'; } else if( $slotState == 'bet' ) { $reportName = $this->slotId . ''; } else if( $slotState == 'slotGamble' ) { $reportName = $this->slotId . ' DG'; } $game = $this->game; if( $slotState == 'bet' ) { $this->user->update_level('bet', $bet * $this->CurrentDenom); } if( $slotState != 'freespin' ) { $game->increment('stat_in', $bet * $this->CurrentDenom); } $game->increment('stat_out', $win * $this->CurrentDenom); $game->tournament_stat($slotState, $this->user->id, $bet * $this->CurrentDenom, $win * $this->CurrentDenom); $this->user->update(['last_bid' => \Carbon\Carbon::now()]); if( !isset($this->betProfit) ) { $this->betProfit = 0; $this->toGameBanks = 0; $this->toSlotJackBanks = 0; $this->toSysJackBanks = 0; } if( !isset($this->toGameBanks) ) { $this->toGameBanks = 0; } $this->game->increment('bids'); $this->game->refresh(); $gamebank = \VanguardLTE\GameBank::where(['shop_id' => $game->shop_id])->first(); if( $gamebank ) { list($slotsBank, $bonusBank, $fishBank, $tableBank, $littleBank) = \VanguardLTE\Lib\Banker::get_all_banks($game->shop_id); } else { $slotsBank = $game->get_gamebank('', 'slots'); $bonusBank = $game->get_gamebank('bonus', 'bonus'); $fishBank = $game->get_gamebank('', 'fish'); $tableBank = $game->get_gamebank('', 'table_bank'); $littleBank = $game->get_gamebank('', 'little'); } $totalBank = $slotsBank + $bonusBank + $fishBank + $tableBank + $littleBank; \VanguardLTE\GameLog::create([ 'game_id' => $this->slotDBId, 'user_id' => $this->playerId, 'ip' => $_SERVER['REMOTE_ADDR'], 'str' => $spinSymbols, 'shop_id' => $this->shop_id ]); \VanguardLTE\StatGame::create([ 'user_id' => $this->playerId, 'balance' => $this->Balance * $this->CurrentDenom, 'bet' => $bet * $this->CurrentDenom, 'win' => $win * $this->CurrentDenom, 'game' => $reportName, 'in_game' => $this->toGameBanks, 'in_jpg' => $this->toSlotJackBanks, 'in_profit' => $this->betProfit, 'denomination' => $this->CurrentDenom, 'shop_id' => $this->shop_id, 'slots_bank' => (double)$slotsBank, 'bonus_bank' => (double)$bonusBank, 'fish_bank' => (double)$fishBank, 'table_bank' => (double)$tableBank, 'little_bank' => (double)$littleBank, 'total_bank' => (double)$totalBank, 'date_time' => \Carbon\Carbon::now() ]); } public function GetSpinSettings($bet, $lines) { $pref = ''; $garantType = 'bet'; $curField = 10; switch( $lines ) { case 10: $curField = 10; break; case 9: case 8: $curField = 9; break; case 7: case 6: $curField = 7; break; case 5: case 4: $curField = 5; break; case 3: case 2: $curField = 3; break; case 1: $curField = 1; break; default: $curField = 10; break; } $this->AllBet = $bet * $lines; $linesPercentConfigSpin = $this->game->get_lines_percent_config('spin'); $linesPercentConfigBonus = $this->game->get_lines_percent_config('bonus'); $currentPercent = $this->shop->percent; $currentSpinWinChance = 0; $currentBonusWinChance = 0; $percentLevel = ''; foreach( $linesPercentConfigSpin['line' . $curField . $pref] as $k => $v ) { $l = explode('_', $k); $l0 = $l[0]; $l1 = $l[1]; if( $l0 <= $currentPercent && $currentPercent <= $l1 ) { $percentLevel = $k; break; } } $currentSpinWinChance = $linesPercentConfigSpin['line' . $curField . $pref][$percentLevel]; $currentBonusWinChance = $linesPercentConfigBonus['line' . $curField . $pref][$percentLevel]; $RtpControlCount = 200; if( !$this->HasGameDataStatic('SpinWinLimit') ) { $this->SetGameDataStatic('SpinWinLimit', 0); } if( !$this->HasGameDataStatic('RtpControlCount') ) { $this->SetGameDataStatic('RtpControlCount', $RtpControlCount); } if( $this->game->stat_in > 0 ) { $rtpRange = $this->game->stat_out / $this->game->stat_in * 100; } else { $rtpRange = 0; } if( $this->GetGameDataStatic('RtpControlCount') == 0 ) { if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 ) { $this->SetGameDataStatic('SpinWinLimit', rand(25, 50)); } if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 ) { $currentBonusWinChance = 5000; $currentSpinWinChance = 20; $this->MaxWin = rand(1, 5); if( $rtpRange < ($currentPercent - 1) ) { $this->SetGameDataStatic('SpinWinLimit', 0); $this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1); } } } else if( $this->GetGameDataStatic('RtpControlCount') < 0 ) { if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 ) { $this->SetGameDataStatic('SpinWinLimit', rand(25, 50)); } $this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1); if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 ) { $currentBonusWinChance = 5000; $currentSpinWinChance = 20; $this->MaxWin = rand(1, 5); if( $rtpRange < ($currentPercent - 1) ) { $this->SetGameDataStatic('SpinWinLimit', 0); } } if( $this->GetGameDataStatic('RtpControlCount') < (-1 * $RtpControlCount) && $currentPercent - 1 <= $rtpRange && $rtpRange <= ($currentPercent + 2) ) { $this->SetGameDataStatic('RtpControlCount', $RtpControlCount); } } else { $this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1); } $bonusWin = rand(1, $currentBonusWinChance); $spinWin = rand(1, $currentSpinWinChance); $return = [ 'none', 0 ]; if( $bonusWin == 1 && $this->slotBonus ) { $this->isBonusStart = true; $garantType = 'bonus'; $winLimit = $this->GetBank($garantType); $return = [ 'bonus', $winLimit ]; if( $this->game->stat_in < ($this->CheckBonusWin() * $bet + $this->game->stat_out) || $winLimit < ($this->CheckBonusWin() * $bet) ) { $return = [ 'none', 0 ]; } } else if( $spinWin == 1 ) { $winLimit = $this->GetBank($garantType); $return = [ 'win', $winLimit ]; } if( $garantType == 'bet' && $this->GetBalance() <= (2 / $this->CurrentDenom) ) { $randomPush = rand(1, 10); if( $randomPush == 1 ) { $winLimit = $this->GetBank(''); $return = [ 'win', $winLimit ]; } } return $return; } public function GetRandomScatterPos($rp) { $rpResult = []; for( $i = 0; $i < count($rp); $i++ ) { if( $rp[$i] == '7' ) { if( isset($rp[$i + 1]) && isset($rp[$i - 1]) ) { array_push($rpResult, $i); } if( isset($rp[$i - 1]) && isset($rp[$i - 2]) ) { array_push($rpResult, $i - 1); } if( isset($rp[$i + 1]) && isset($rp[$i + 2]) ) { array_push($rpResult, $i + 1); } } } shuffle($rpResult); if( !isset($rpResult[0]) ) { $rpResult[0] = rand(2, count($rp) - 3); } return $rpResult[0]; } public function GetGambleSettings() { $spinWin = rand(1, $this->WinGamble); return $spinWin; } public function GetReelStrips($winType, $slotEvent) { $game = $this->game; if( $slotEvent == 'freespin' ) { $reel = new GameReel(); $fArr = $reel->reelsStripBonus; foreach( [ 'reelStrip1', 'reelStrip2', 'reelStrip3', 'reelStrip4', 'reelStrip5', 'reelStrip6' ] as $reelStrip ) { $curReel = array_shift($fArr); if( count($curReel) ) { $this->$reelStrip = $curReel; } } } if( $winType != 'bonus' ) { $prs = []; foreach( [ 'reelStrip1', 'reelStrip2', 'reelStrip3', 'reelStrip4', 'reelStrip5', 'reelStrip6' ] as $index => $reelStrip ) { if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 ) { $prs[$index + 1] = mt_rand(0, count($this->$reelStrip) - 3); } } } else { $reelsId = []; foreach( [ 'reelStrip1', 'reelStrip2', 'reelStrip3', 'reelStrip4', 'reelStrip5', 'reelStrip6' ] as $index => $reelStrip ) { if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 ) { $prs[$index + 1] = $this->GetRandomScatterPos($this->$reelStrip); $reelsId[] = $index + 1; } } $scattersCnt = rand(3, count($reelsId)); shuffle($reelsId); for( $i = 0; $i < count($reelsId); $i++ ) { if( $i < $scattersCnt ) { $prs[$reelsId[$i]] = $this->GetRandomScatterPos($this->{'reelStrip' . $reelsId[$i]}); } else { $prs[$reelsId[$i]] = rand(0, count($this->{'reelStrip' . $reelsId[$i]}) - 3); } } } $reel = [ 'rp' => [] ]; foreach( $prs as $index => $value ) { $key = $this->{'reelStrip' . $index}; $cnt = count($key); $key[-1] = $key[$cnt - 1]; $key[$cnt] = $key[0]; $reel['reel' . $index][0] = $key[$value - 1]; $reel['reel' . $index][1] = $key[$value]; $reel['reel' . $index][2] = $key[$value + 1]; $reel['reel' . $index][3] = ''; $reel['rp'][] = $value; } return $reel; } } }
0
0.575057
1
0.575057
game-dev
MEDIA
0.361395
game-dev
0.712868
1
0.712868
Spaghetticode-Boon-Tobias/RETROLauncher
45,049
RETROLauncher/System/RetroarchPS2/Nintendo Game Boy Color/retroarch/retroarch.cfg
accessibility_enable = "false" accessibility_narrator_speech_speed = "5" ai_service_enable = "false" ai_service_mode = "1" ai_service_pause = "false" ai_service_poll_delay = "0" ai_service_source_lang = "0" ai_service_target_lang = "0" ai_service_text_padding = "5" ai_service_text_position = "0" all_users_control_menu = "false" always_reload_core_on_run_content = "true" app_icon = "default" apply_cheats_after_load = "false" apply_cheats_after_toggle = "false" aspect_ratio_index = "0" assets_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/assets" audio_block_frames = "0" audio_device = "" audio_driver = "ps2" audio_dsp_plugin = "" audio_enable = "true" audio_enable_menu = "false" audio_enable_menu_bgm = "false" audio_enable_menu_cancel = "false" audio_enable_menu_notice = "false" audio_enable_menu_ok = "false" audio_enable_menu_scroll = "false" audio_fastforward_mute = "false" audio_fastforward_speedup = "false" audio_filter_dir = "default" audio_latency = "64" audio_max_timing_skew = "0.050000" audio_mixer_mute_enable = "true" audio_mixer_volume = "0.000000" audio_mute_enable = "false" audio_out_rate = "48000" audio_rate_control = "false" audio_rate_control_delta = "0.005000" audio_resampler = "sinc" audio_resampler_quality = "1" audio_sync = "true" audio_volume = "0.000000" auto_overrides_enable = "false" auto_remaps_enable = "true" auto_screenshot_filename = "true" auto_shaders_enable = "true" autosave_interval = "0" block_sram_overwrite = "false" bluetooth_driver = "null" builtin_imageviewer_enable = "false" builtin_mediaplayer_enable = "false" bundle_assets_dst_path = "" bundle_assets_dst_path_subdir = "" bundle_assets_extract_enable = "false" bundle_assets_extract_last_version = "0" bundle_assets_extract_version_current = "0" bundle_assets_src_path = "" cache_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/temp" camera_allow = "false" camera_device = "" camera_driver = "null" cheat_database_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/cheats" check_firmware_before_loading = "false" cloud_sync_destructive = "false" cloud_sync_driver = "" cloud_sync_enable = "false" cloud_sync_sync_configs = "true" cloud_sync_sync_saves = "true" cloud_sync_sync_system = "false" cloud_sync_sync_thumbs = "false" config_save_on_exit = "true" content_database_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/database/rdb" content_favorites_directory = "default" content_favorites_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/content_favorites.lpl" content_favorites_size = "0" content_history_directory = "default" content_history_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/content_history.lpl" content_history_size = "200" content_image_history_directory = "default" content_image_history_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/content_image_history.lpl" content_music_history_directory = "default" content_music_history_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/content_music_history.lpl" content_runtime_log = "false" content_runtime_log_aggregate = "false" content_show_add = "false" content_show_add_entry = "0" content_show_contentless_cores = "2" content_show_explore = "false" content_show_favorites = "false" content_show_history = "false" content_show_music = "false" content_show_playlists = "false" content_show_settings = "true" content_show_settings_password = "" content_video_directory = "default" content_video_history_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/content_video_history.lpl" core_assets_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/downloads" core_info_cache_enable = "true" core_info_savestate_bypass = "true" core_option_category_enable = "true" core_options_path = "" core_set_supports_no_game_enable = "true" core_updater_auto_backup = "false" core_updater_auto_backup_history_size = "1" core_updater_auto_extract_archive = "true" core_updater_buildbot_assets_url = "http://buildbot.libretro.com/assets/" core_updater_buildbot_cores_url = "" core_updater_show_experimental_cores = "false" crt_switch_center_adjust = "0" crt_switch_hires_menu = "false" crt_switch_porch_adjust = "0" crt_switch_resolution = "0" crt_switch_resolution_super = "2560" crt_switch_resolution_use_custom_refresh_rate = "false" crt_switch_timings = "" crt_video_refresh_rate = "59.940063" current_resolution_id = "0" custom_viewport_height = "0" custom_viewport_width = "0" custom_viewport_x = "0" custom_viewport_y = "0" desktop_menu_enable = "true" discord_allow = "false" driver_switch_enable = "true" dynamic_wallpapers_directory = "default" enable_device_vibration = "false" fastforward_frameskip = "false" fastforward_ratio = "0.000000" filter_by_current_core = "false" flicker_filter_enable = "false" flicker_filter_index = "0" fps_show = "false" fps_update_interval = "256" frame_time_counter_reset_after_fastforwarding = "false" frame_time_counter_reset_after_load_state = "false" frame_time_counter_reset_after_save_state = "false" framecount_show = "false" frontend_log_level = "1" game_specific_options = "true" gamemode_enable = "true" gamma_correction = "0" global_core_options = "false" history_list_enable = "false" initial_disk_change_enable = "false" input_ai_service = "nul" input_ai_service_axis = "nul" input_ai_service_btn = "nul" input_ai_service_mbtn = "nul" input_allow_turbo_dpad = "false" input_analog_deadzone = "0.000000" input_analog_sensitivity = "1.000000" input_audio_mute = "f9" input_audio_mute_axis = "nul" input_audio_mute_btn = "nul" input_audio_mute_mbtn = "nul" input_auto_game_focus = "0" input_auto_mouse_grab = "false" input_autodetect_enable = "true" input_axis_threshold = "0.500000" input_bind_hold = "0" input_bind_timeout = "3" input_cheat_index_minus = "t" input_cheat_index_minus_axis = "nul" input_cheat_index_minus_btn = "nul" input_cheat_index_minus_mbtn = "nul" input_cheat_index_plus = "y" input_cheat_index_plus_axis = "nul" input_cheat_index_plus_btn = "nul" input_cheat_index_plus_mbtn = "nul" input_cheat_toggle = "u" input_cheat_toggle_axis = "nul" input_cheat_toggle_btn = "nul" input_cheat_toggle_mbtn = "nul" input_close_content = "nul" input_close_content_axis = "nul" input_close_content_btn = "nul" input_close_content_mbtn = "nul" input_descriptor_hide_unbound = "false" input_descriptor_label_show = "true" input_desktop_menu_toggle = "f5" input_desktop_menu_toggle_axis = "nul" input_desktop_menu_toggle_btn = "nul" input_desktop_menu_toggle_mbtn = "nul" input_device_p1 = "0" input_device_p2 = "0" input_device_p3 = "0" input_device_p4 = "0" input_disk_eject_toggle = "nul" input_disk_eject_toggle_axis = "nul" input_disk_eject_toggle_btn = "nul" input_disk_eject_toggle_mbtn = "nul" input_disk_next = "nul" input_disk_next_axis = "nul" input_disk_next_btn = "nul" input_disk_next_mbtn = "nul" input_disk_prev = "nul" input_disk_prev_axis = "nul" input_disk_prev_btn = "nul" input_disk_prev_mbtn = "nul" input_driver = "ps2" input_duty_cycle = "3" input_enable_hotkey = "nul" input_enable_hotkey_axis = "nul" input_enable_hotkey_btn = "nul" input_enable_hotkey_mbtn = "nul" input_exit_emulator = "escape" input_exit_emulator_axis = "nul" input_exit_emulator_btn = "nul" input_exit_emulator_mbtn = "nul" input_fps_toggle = "f3" input_fps_toggle_axis = "nul" input_fps_toggle_btn = "nul" input_fps_toggle_mbtn = "nul" input_frame_advance = "k" input_frame_advance_axis = "nul" input_frame_advance_btn = "nul" input_frame_advance_mbtn = "nul" input_game_focus_toggle = "scroll_lock" input_game_focus_toggle_axis = "nul" input_game_focus_toggle_btn = "nul" input_game_focus_toggle_mbtn = "nul" input_grab_mouse_toggle = "f11" input_grab_mouse_toggle_axis = "nul" input_grab_mouse_toggle_btn = "nul" input_grab_mouse_toggle_mbtn = "nul" input_halt_replay = "nul" input_halt_replay_axis = "nul" input_halt_replay_btn = "nul" input_halt_replay_mbtn = "nul" input_hold_fast_forward = "l" input_hold_fast_forward_axis = "nul" input_hold_fast_forward_btn = "nul" input_hold_fast_forward_mbtn = "nul" input_hold_slowmotion = "e" input_hold_slowmotion_axis = "nul" input_hold_slowmotion_btn = "nul" input_hold_slowmotion_mbtn = "nul" input_hotkey_block_delay = "5" input_hotkey_device_merge = "false" input_joypad_driver = "ps2" input_keyboard_layout = "" input_load_state = "f4" input_load_state_axis = "nul" input_load_state_btn = "nul" input_load_state_mbtn = "nul" input_max_users = "2" input_menu_toggle = "f1" input_menu_toggle_axis = "nul" input_menu_toggle_btn = "nul" input_menu_toggle_gamepad_combo = "10" input_menu_toggle_mbtn = "nul" input_netplay_fade_chat_toggle = "nul" input_netplay_fade_chat_toggle_axis = "nul" input_netplay_fade_chat_toggle_btn = "nul" input_netplay_fade_chat_toggle_mbtn = "nul" input_netplay_game_watch = "i" input_netplay_game_watch_axis = "nul" input_netplay_game_watch_btn = "nul" input_netplay_game_watch_mbtn = "nul" input_netplay_host_toggle = "nul" input_netplay_host_toggle_axis = "nul" input_netplay_host_toggle_btn = "nul" input_netplay_host_toggle_mbtn = "nul" input_netplay_ping_toggle = "nul" input_netplay_ping_toggle_axis = "nul" input_netplay_ping_toggle_btn = "nul" input_netplay_ping_toggle_mbtn = "nul" input_netplay_player_chat = "tilde" input_netplay_player_chat_axis = "nul" input_netplay_player_chat_btn = "nul" input_netplay_player_chat_mbtn = "nul" input_osk_toggle = "nul" input_osk_toggle_axis = "nul" input_osk_toggle_btn = "nul" input_osk_toggle_mbtn = "nul" input_overlay_next = "nul" input_overlay_next_axis = "nul" input_overlay_next_btn = "nul" input_overlay_next_mbtn = "nul" input_pause_toggle = "p" input_pause_toggle_axis = "nul" input_pause_toggle_btn = "nul" input_pause_toggle_mbtn = "nul" input_play_replay = "nul" input_play_replay_axis = "nul" input_play_replay_btn = "nul" input_play_replay_mbtn = "nul" input_player1_a = "x" input_player1_a_axis = "nul" input_player1_a_btn = "nul" input_player1_a_mbtn = "nul" input_player1_analog_dpad_mode = "0" input_player1_b = "z" input_player1_b_axis = "nul" input_player1_b_btn = "nul" input_player1_b_mbtn = "nul" input_player1_device_reservation_type = "0" input_player1_down = "down" input_player1_down_axis = "nul" input_player1_down_btn = "nul" input_player1_down_mbtn = "nul" input_player1_gun_aux_a = "nul" input_player1_gun_aux_a_axis = "nul" input_player1_gun_aux_a_btn = "nul" input_player1_gun_aux_a_mbtn = "nul" input_player1_gun_aux_b = "nul" input_player1_gun_aux_b_axis = "nul" input_player1_gun_aux_b_btn = "nul" input_player1_gun_aux_b_mbtn = "nul" input_player1_gun_aux_c = "nul" input_player1_gun_aux_c_axis = "nul" input_player1_gun_aux_c_btn = "nul" input_player1_gun_aux_c_mbtn = "nul" input_player1_gun_dpad_down = "nul" input_player1_gun_dpad_down_axis = "nul" input_player1_gun_dpad_down_btn = "nul" input_player1_gun_dpad_down_mbtn = "nul" input_player1_gun_dpad_left = "nul" input_player1_gun_dpad_left_axis = "nul" input_player1_gun_dpad_left_btn = "nul" input_player1_gun_dpad_left_mbtn = "nul" input_player1_gun_dpad_right = "nul" input_player1_gun_dpad_right_axis = "nul" input_player1_gun_dpad_right_btn = "nul" input_player1_gun_dpad_right_mbtn = "nul" input_player1_gun_dpad_up = "nul" input_player1_gun_dpad_up_axis = "nul" input_player1_gun_dpad_up_btn = "nul" input_player1_gun_dpad_up_mbtn = "nul" input_player1_gun_offscreen_shot = "nul" input_player1_gun_offscreen_shot_axis = "nul" input_player1_gun_offscreen_shot_btn = "nul" input_player1_gun_offscreen_shot_mbtn = "2" input_player1_gun_select = "nul" input_player1_gun_select_axis = "nul" input_player1_gun_select_btn = "nul" input_player1_gun_select_mbtn = "nul" input_player1_gun_start = "nul" input_player1_gun_start_axis = "nul" input_player1_gun_start_btn = "nul" input_player1_gun_start_mbtn = "nul" input_player1_gun_trigger = "nul" input_player1_gun_trigger_axis = "nul" input_player1_gun_trigger_btn = "nul" input_player1_gun_trigger_mbtn = "1" input_player1_joypad_index = "0" input_player1_l = "q" input_player1_l2 = "nul" input_player1_l2_axis = "nul" input_player1_l2_btn = "nul" input_player1_l2_mbtn = "nul" input_player1_l3 = "nul" input_player1_l3_axis = "nul" input_player1_l3_btn = "nul" input_player1_l3_mbtn = "nul" input_player1_l_axis = "nul" input_player1_l_btn = "nul" input_player1_l_mbtn = "nul" input_player1_l_x_minus = "nul" input_player1_l_x_minus_axis = "nul" input_player1_l_x_minus_btn = "nul" input_player1_l_x_minus_mbtn = "nul" input_player1_l_x_plus = "nul" input_player1_l_x_plus_axis = "nul" input_player1_l_x_plus_btn = "nul" input_player1_l_x_plus_mbtn = "nul" input_player1_l_y_minus = "nul" input_player1_l_y_minus_axis = "nul" input_player1_l_y_minus_btn = "nul" input_player1_l_y_minus_mbtn = "nul" input_player1_l_y_plus = "nul" input_player1_l_y_plus_axis = "nul" input_player1_l_y_plus_btn = "nul" input_player1_l_y_plus_mbtn = "nul" input_player1_left = "left" input_player1_left_axis = "nul" input_player1_left_btn = "nul" input_player1_left_mbtn = "nul" input_player1_mouse_index = "0" input_player1_r = "w" input_player1_r2 = "nul" input_player1_r2_axis = "nul" input_player1_r2_btn = "nul" input_player1_r2_mbtn = "nul" input_player1_r3 = "nul" input_player1_r3_axis = "nul" input_player1_r3_btn = "nul" input_player1_r3_mbtn = "nul" input_player1_r_axis = "nul" input_player1_r_btn = "nul" input_player1_r_mbtn = "nul" input_player1_r_x_minus = "nul" input_player1_r_x_minus_axis = "nul" input_player1_r_x_minus_btn = "nul" input_player1_r_x_minus_mbtn = "nul" input_player1_r_x_plus = "nul" input_player1_r_x_plus_axis = "nul" input_player1_r_x_plus_btn = "nul" input_player1_r_x_plus_mbtn = "nul" input_player1_r_y_minus = "nul" input_player1_r_y_minus_axis = "nul" input_player1_r_y_minus_btn = "nul" input_player1_r_y_minus_mbtn = "nul" input_player1_r_y_plus = "nul" input_player1_r_y_plus_axis = "nul" input_player1_r_y_plus_btn = "nul" input_player1_r_y_plus_mbtn = "nul" input_player1_reserved_device = "" input_player1_right = "right" input_player1_right_axis = "nul" input_player1_right_btn = "nul" input_player1_right_mbtn = "nul" input_player1_select = "rshift" input_player1_select_axis = "nul" input_player1_select_btn = "nul" input_player1_select_mbtn = "nul" input_player1_start = "enter" input_player1_start_axis = "nul" input_player1_start_btn = "nul" input_player1_start_mbtn = "nul" input_player1_turbo = "nul" input_player1_turbo_axis = "nul" input_player1_turbo_btn = "nul" input_player1_turbo_mbtn = "nul" input_player1_up = "up" input_player1_up_axis = "nul" input_player1_up_btn = "nul" input_player1_up_mbtn = "nul" input_player1_x = "s" input_player1_x_axis = "nul" input_player1_x_btn = "nul" input_player1_x_mbtn = "nul" input_player1_y = "a" input_player1_y_axis = "nul" input_player1_y_btn = "nul" input_player1_y_mbtn = "nul" input_player2_a = "nul" input_player2_a_axis = "nul" input_player2_a_btn = "nul" input_player2_a_mbtn = "nul" input_player2_analog_dpad_mode = "0" input_player2_b = "nul" input_player2_b_axis = "nul" input_player2_b_btn = "nul" input_player2_b_mbtn = "nul" input_player2_device_reservation_type = "0" input_player2_down = "nul" input_player2_down_axis = "nul" input_player2_down_btn = "nul" input_player2_down_mbtn = "nul" input_player2_gun_aux_a = "nul" input_player2_gun_aux_a_axis = "nul" input_player2_gun_aux_a_btn = "nul" input_player2_gun_aux_a_mbtn = "nul" input_player2_gun_aux_b = "nul" input_player2_gun_aux_b_axis = "nul" input_player2_gun_aux_b_btn = "nul" input_player2_gun_aux_b_mbtn = "nul" input_player2_gun_aux_c = "nul" input_player2_gun_aux_c_axis = "nul" input_player2_gun_aux_c_btn = "nul" input_player2_gun_aux_c_mbtn = "nul" input_player2_gun_dpad_down = "nul" input_player2_gun_dpad_down_axis = "nul" input_player2_gun_dpad_down_btn = "nul" input_player2_gun_dpad_down_mbtn = "nul" input_player2_gun_dpad_left = "nul" input_player2_gun_dpad_left_axis = "nul" input_player2_gun_dpad_left_btn = "nul" input_player2_gun_dpad_left_mbtn = "nul" input_player2_gun_dpad_right = "nul" input_player2_gun_dpad_right_axis = "nul" input_player2_gun_dpad_right_btn = "nul" input_player2_gun_dpad_right_mbtn = "nul" input_player2_gun_dpad_up = "nul" input_player2_gun_dpad_up_axis = "nul" input_player2_gun_dpad_up_btn = "nul" input_player2_gun_dpad_up_mbtn = "nul" input_player2_gun_offscreen_shot = "nul" input_player2_gun_offscreen_shot_axis = "nul" input_player2_gun_offscreen_shot_btn = "nul" input_player2_gun_offscreen_shot_mbtn = "2" input_player2_gun_select = "nul" input_player2_gun_select_axis = "nul" input_player2_gun_select_btn = "nul" input_player2_gun_select_mbtn = "nul" input_player2_gun_start = "nul" input_player2_gun_start_axis = "nul" input_player2_gun_start_btn = "nul" input_player2_gun_start_mbtn = "nul" input_player2_gun_trigger = "nul" input_player2_gun_trigger_axis = "nul" input_player2_gun_trigger_btn = "nul" input_player2_gun_trigger_mbtn = "1" input_player2_joypad_index = "1" input_player2_l = "nul" input_player2_l2 = "nul" input_player2_l2_axis = "nul" input_player2_l2_btn = "nul" input_player2_l2_mbtn = "nul" input_player2_l3 = "nul" input_player2_l3_axis = "nul" input_player2_l3_btn = "nul" input_player2_l3_mbtn = "nul" input_player2_l_axis = "nul" input_player2_l_btn = "nul" input_player2_l_mbtn = "nul" input_player2_l_x_minus = "nul" input_player2_l_x_minus_axis = "nul" input_player2_l_x_minus_btn = "nul" input_player2_l_x_minus_mbtn = "nul" input_player2_l_x_plus = "nul" input_player2_l_x_plus_axis = "nul" input_player2_l_x_plus_btn = "nul" input_player2_l_x_plus_mbtn = "nul" input_player2_l_y_minus = "nul" input_player2_l_y_minus_axis = "nul" input_player2_l_y_minus_btn = "nul" input_player2_l_y_minus_mbtn = "nul" input_player2_l_y_plus = "nul" input_player2_l_y_plus_axis = "nul" input_player2_l_y_plus_btn = "nul" input_player2_l_y_plus_mbtn = "nul" input_player2_left = "nul" input_player2_left_axis = "nul" input_player2_left_btn = "nul" input_player2_left_mbtn = "nul" input_player2_mouse_index = "1" input_player2_r = "nul" input_player2_r2 = "nul" input_player2_r2_axis = "nul" input_player2_r2_btn = "nul" input_player2_r2_mbtn = "nul" input_player2_r3 = "nul" input_player2_r3_axis = "nul" input_player2_r3_btn = "nul" input_player2_r3_mbtn = "nul" input_player2_r_axis = "nul" input_player2_r_btn = "nul" input_player2_r_mbtn = "nul" input_player2_r_x_minus = "nul" input_player2_r_x_minus_axis = "nul" input_player2_r_x_minus_btn = "nul" input_player2_r_x_minus_mbtn = "nul" input_player2_r_x_plus = "nul" input_player2_r_x_plus_axis = "nul" input_player2_r_x_plus_btn = "nul" input_player2_r_x_plus_mbtn = "nul" input_player2_r_y_minus = "nul" input_player2_r_y_minus_axis = "nul" input_player2_r_y_minus_btn = "nul" input_player2_r_y_minus_mbtn = "nul" input_player2_r_y_plus = "nul" input_player2_r_y_plus_axis = "nul" input_player2_r_y_plus_btn = "nul" input_player2_r_y_plus_mbtn = "nul" input_player2_reserved_device = "" input_player2_right = "nul" input_player2_right_axis = "nul" input_player2_right_btn = "nul" input_player2_right_mbtn = "nul" input_player2_select = "nul" input_player2_select_axis = "nul" input_player2_select_btn = "nul" input_player2_select_mbtn = "nul" input_player2_start = "nul" input_player2_start_axis = "nul" input_player2_start_btn = "nul" input_player2_start_mbtn = "nul" input_player2_turbo = "nul" input_player2_turbo_axis = "nul" input_player2_turbo_btn = "nul" input_player2_turbo_mbtn = "nul" input_player2_up = "nul" input_player2_up_axis = "nul" input_player2_up_btn = "nul" input_player2_up_mbtn = "nul" input_player2_x = "nul" input_player2_x_axis = "nul" input_player2_x_btn = "nul" input_player2_x_mbtn = "nul" input_player2_y = "nul" input_player2_y_axis = "nul" input_player2_y_btn = "nul" input_player2_y_mbtn = "nul" input_player3_a = "nul" input_player3_a_axis = "nul" input_player3_a_btn = "nul" input_player3_a_mbtn = "nul" input_player3_analog_dpad_mode = "0" input_player3_b = "nul" input_player3_b_axis = "nul" input_player3_b_btn = "nul" input_player3_b_mbtn = "nul" input_player3_device_reservation_type = "0" input_player3_down = "nul" input_player3_down_axis = "nul" input_player3_down_btn = "nul" input_player3_down_mbtn = "nul" input_player3_gun_aux_a = "nul" input_player3_gun_aux_a_axis = "nul" input_player3_gun_aux_a_btn = "nul" input_player3_gun_aux_a_mbtn = "nul" input_player3_gun_aux_b = "nul" input_player3_gun_aux_b_axis = "nul" input_player3_gun_aux_b_btn = "nul" input_player3_gun_aux_b_mbtn = "nul" input_player3_gun_aux_c = "nul" input_player3_gun_aux_c_axis = "nul" input_player3_gun_aux_c_btn = "nul" input_player3_gun_aux_c_mbtn = "nul" input_player3_gun_dpad_down = "nul" input_player3_gun_dpad_down_axis = "nul" input_player3_gun_dpad_down_btn = "nul" input_player3_gun_dpad_down_mbtn = "nul" input_player3_gun_dpad_left = "nul" input_player3_gun_dpad_left_axis = "nul" input_player3_gun_dpad_left_btn = "nul" input_player3_gun_dpad_left_mbtn = "nul" input_player3_gun_dpad_right = "nul" input_player3_gun_dpad_right_axis = "nul" input_player3_gun_dpad_right_btn = "nul" input_player3_gun_dpad_right_mbtn = "nul" input_player3_gun_dpad_up = "nul" input_player3_gun_dpad_up_axis = "nul" input_player3_gun_dpad_up_btn = "nul" input_player3_gun_dpad_up_mbtn = "nul" input_player3_gun_offscreen_shot = "nul" input_player3_gun_offscreen_shot_axis = "nul" input_player3_gun_offscreen_shot_btn = "nul" input_player3_gun_offscreen_shot_mbtn = "2" input_player3_gun_select = "nul" input_player3_gun_select_axis = "nul" input_player3_gun_select_btn = "nul" input_player3_gun_select_mbtn = "nul" input_player3_gun_start = "nul" input_player3_gun_start_axis = "nul" input_player3_gun_start_btn = "nul" input_player3_gun_start_mbtn = "nul" input_player3_gun_trigger = "nul" input_player3_gun_trigger_axis = "nul" input_player3_gun_trigger_btn = "nul" input_player3_gun_trigger_mbtn = "1" input_player3_joypad_index = "2" input_player3_l = "nul" input_player3_l2 = "nul" input_player3_l2_axis = "nul" input_player3_l2_btn = "nul" input_player3_l2_mbtn = "nul" input_player3_l3 = "nul" input_player3_l3_axis = "nul" input_player3_l3_btn = "nul" input_player3_l3_mbtn = "nul" input_player3_l_axis = "nul" input_player3_l_btn = "nul" input_player3_l_mbtn = "nul" input_player3_l_x_minus = "nul" input_player3_l_x_minus_axis = "nul" input_player3_l_x_minus_btn = "nul" input_player3_l_x_minus_mbtn = "nul" input_player3_l_x_plus = "nul" input_player3_l_x_plus_axis = "nul" input_player3_l_x_plus_btn = "nul" input_player3_l_x_plus_mbtn = "nul" input_player3_l_y_minus = "nul" input_player3_l_y_minus_axis = "nul" input_player3_l_y_minus_btn = "nul" input_player3_l_y_minus_mbtn = "nul" input_player3_l_y_plus = "nul" input_player3_l_y_plus_axis = "nul" input_player3_l_y_plus_btn = "nul" input_player3_l_y_plus_mbtn = "nul" input_player3_left = "nul" input_player3_left_axis = "nul" input_player3_left_btn = "nul" input_player3_left_mbtn = "nul" input_player3_mouse_index = "2" input_player3_r = "nul" input_player3_r2 = "nul" input_player3_r2_axis = "nul" input_player3_r2_btn = "nul" input_player3_r2_mbtn = "nul" input_player3_r3 = "nul" input_player3_r3_axis = "nul" input_player3_r3_btn = "nul" input_player3_r3_mbtn = "nul" input_player3_r_axis = "nul" input_player3_r_btn = "nul" input_player3_r_mbtn = "nul" input_player3_r_x_minus = "nul" input_player3_r_x_minus_axis = "nul" input_player3_r_x_minus_btn = "nul" input_player3_r_x_minus_mbtn = "nul" input_player3_r_x_plus = "nul" input_player3_r_x_plus_axis = "nul" input_player3_r_x_plus_btn = "nul" input_player3_r_x_plus_mbtn = "nul" input_player3_r_y_minus = "nul" input_player3_r_y_minus_axis = "nul" input_player3_r_y_minus_btn = "nul" input_player3_r_y_minus_mbtn = "nul" input_player3_r_y_plus = "nul" input_player3_r_y_plus_axis = "nul" input_player3_r_y_plus_btn = "nul" input_player3_r_y_plus_mbtn = "nul" input_player3_reserved_device = "" input_player3_right = "nul" input_player3_right_axis = "nul" input_player3_right_btn = "nul" input_player3_right_mbtn = "nul" input_player3_select = "nul" input_player3_select_axis = "nul" input_player3_select_btn = "nul" input_player3_select_mbtn = "nul" input_player3_start = "nul" input_player3_start_axis = "nul" input_player3_start_btn = "nul" input_player3_start_mbtn = "nul" input_player3_turbo = "nul" input_player3_turbo_axis = "nul" input_player3_turbo_btn = "nul" input_player3_turbo_mbtn = "nul" input_player3_up = "nul" input_player3_up_axis = "nul" input_player3_up_btn = "nul" input_player3_up_mbtn = "nul" input_player3_x = "nul" input_player3_x_axis = "nul" input_player3_x_btn = "nul" input_player3_x_mbtn = "nul" input_player3_y = "nul" input_player3_y_axis = "nul" input_player3_y_btn = "nul" input_player3_y_mbtn = "nul" input_player4_a = "nul" input_player4_a_axis = "nul" input_player4_a_btn = "nul" input_player4_a_mbtn = "nul" input_player4_analog_dpad_mode = "0" input_player4_b = "nul" input_player4_b_axis = "nul" input_player4_b_btn = "nul" input_player4_b_mbtn = "nul" input_player4_device_reservation_type = "0" input_player4_down = "nul" input_player4_down_axis = "nul" input_player4_down_btn = "nul" input_player4_down_mbtn = "nul" input_player4_gun_aux_a = "nul" input_player4_gun_aux_a_axis = "nul" input_player4_gun_aux_a_btn = "nul" input_player4_gun_aux_a_mbtn = "nul" input_player4_gun_aux_b = "nul" input_player4_gun_aux_b_axis = "nul" input_player4_gun_aux_b_btn = "nul" input_player4_gun_aux_b_mbtn = "nul" input_player4_gun_aux_c = "nul" input_player4_gun_aux_c_axis = "nul" input_player4_gun_aux_c_btn = "nul" input_player4_gun_aux_c_mbtn = "nul" input_player4_gun_dpad_down = "nul" input_player4_gun_dpad_down_axis = "nul" input_player4_gun_dpad_down_btn = "nul" input_player4_gun_dpad_down_mbtn = "nul" input_player4_gun_dpad_left = "nul" input_player4_gun_dpad_left_axis = "nul" input_player4_gun_dpad_left_btn = "nul" input_player4_gun_dpad_left_mbtn = "nul" input_player4_gun_dpad_right = "nul" input_player4_gun_dpad_right_axis = "nul" input_player4_gun_dpad_right_btn = "nul" input_player4_gun_dpad_right_mbtn = "nul" input_player4_gun_dpad_up = "nul" input_player4_gun_dpad_up_axis = "nul" input_player4_gun_dpad_up_btn = "nul" input_player4_gun_dpad_up_mbtn = "nul" input_player4_gun_offscreen_shot = "nul" input_player4_gun_offscreen_shot_axis = "nul" input_player4_gun_offscreen_shot_btn = "nul" input_player4_gun_offscreen_shot_mbtn = "2" input_player4_gun_select = "nul" input_player4_gun_select_axis = "nul" input_player4_gun_select_btn = "nul" input_player4_gun_select_mbtn = "nul" input_player4_gun_start = "nul" input_player4_gun_start_axis = "nul" input_player4_gun_start_btn = "nul" input_player4_gun_start_mbtn = "nul" input_player4_gun_trigger = "nul" input_player4_gun_trigger_axis = "nul" input_player4_gun_trigger_btn = "nul" input_player4_gun_trigger_mbtn = "1" input_player4_joypad_index = "3" input_player4_l = "nul" input_player4_l2 = "nul" input_player4_l2_axis = "nul" input_player4_l2_btn = "nul" input_player4_l2_mbtn = "nul" input_player4_l3 = "nul" input_player4_l3_axis = "nul" input_player4_l3_btn = "nul" input_player4_l3_mbtn = "nul" input_player4_l_axis = "nul" input_player4_l_btn = "nul" input_player4_l_mbtn = "nul" input_player4_l_x_minus = "nul" input_player4_l_x_minus_axis = "nul" input_player4_l_x_minus_btn = "nul" input_player4_l_x_minus_mbtn = "nul" input_player4_l_x_plus = "nul" input_player4_l_x_plus_axis = "nul" input_player4_l_x_plus_btn = "nul" input_player4_l_x_plus_mbtn = "nul" input_player4_l_y_minus = "nul" input_player4_l_y_minus_axis = "nul" input_player4_l_y_minus_btn = "nul" input_player4_l_y_minus_mbtn = "nul" input_player4_l_y_plus = "nul" input_player4_l_y_plus_axis = "nul" input_player4_l_y_plus_btn = "nul" input_player4_l_y_plus_mbtn = "nul" input_player4_left = "nul" input_player4_left_axis = "nul" input_player4_left_btn = "nul" input_player4_left_mbtn = "nul" input_player4_mouse_index = "3" input_player4_r = "nul" input_player4_r2 = "nul" input_player4_r2_axis = "nul" input_player4_r2_btn = "nul" input_player4_r2_mbtn = "nul" input_player4_r3 = "nul" input_player4_r3_axis = "nul" input_player4_r3_btn = "nul" input_player4_r3_mbtn = "nul" input_player4_r_axis = "nul" input_player4_r_btn = "nul" input_player4_r_mbtn = "nul" input_player4_r_x_minus = "nul" input_player4_r_x_minus_axis = "nul" input_player4_r_x_minus_btn = "nul" input_player4_r_x_minus_mbtn = "nul" input_player4_r_x_plus = "nul" input_player4_r_x_plus_axis = "nul" input_player4_r_x_plus_btn = "nul" input_player4_r_x_plus_mbtn = "nul" input_player4_r_y_minus = "nul" input_player4_r_y_minus_axis = "nul" input_player4_r_y_minus_btn = "nul" input_player4_r_y_minus_mbtn = "nul" input_player4_r_y_plus = "nul" input_player4_r_y_plus_axis = "nul" input_player4_r_y_plus_btn = "nul" input_player4_r_y_plus_mbtn = "nul" input_player4_reserved_device = "" input_player4_right = "nul" input_player4_right_axis = "nul" input_player4_right_btn = "nul" input_player4_right_mbtn = "nul" input_player4_select = "nul" input_player4_select_axis = "nul" input_player4_select_btn = "nul" input_player4_select_mbtn = "nul" input_player4_start = "nul" input_player4_start_axis = "nul" input_player4_start_btn = "nul" input_player4_start_mbtn = "nul" input_player4_turbo = "nul" input_player4_turbo_axis = "nul" input_player4_turbo_btn = "nul" input_player4_turbo_mbtn = "nul" input_player4_up = "nul" input_player4_up_axis = "nul" input_player4_up_btn = "nul" input_player4_up_mbtn = "nul" input_player4_x = "nul" input_player4_x_axis = "nul" input_player4_x_btn = "nul" input_player4_x_mbtn = "nul" input_player4_y = "nul" input_player4_y_axis = "nul" input_player4_y_btn = "nul" input_player4_y_mbtn = "nul" input_poll_type_behavior = "2" input_preempt_toggle = "nul" input_preempt_toggle_axis = "nul" input_preempt_toggle_btn = "nul" input_preempt_toggle_mbtn = "nul" input_quit_gamepad_combo = "0" input_record_replay = "nul" input_record_replay_axis = "nul" input_record_replay_btn = "nul" input_record_replay_mbtn = "nul" input_recording_toggle = "nul" input_recording_toggle_axis = "nul" input_recording_toggle_btn = "nul" input_recording_toggle_mbtn = "nul" input_remap_binds_enable = "true" input_remap_sort_by_controller_enable = "false" input_remapping_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/config/remaps" input_replay_slot_decrease = "nul" input_replay_slot_decrease_axis = "nul" input_replay_slot_decrease_btn = "nul" input_replay_slot_decrease_mbtn = "nul" input_replay_slot_increase = "nul" input_replay_slot_increase_axis = "nul" input_replay_slot_increase_btn = "nul" input_replay_slot_increase_mbtn = "nul" input_reset = "h" input_reset_axis = "nul" input_reset_btn = "nul" input_reset_mbtn = "nul" input_rewind = "r" input_rewind_axis = "nul" input_rewind_btn = "nul" input_rewind_mbtn = "nul" input_rumble_gain = "100" input_runahead_toggle = "nul" input_runahead_toggle_axis = "nul" input_runahead_toggle_btn = "nul" input_runahead_toggle_mbtn = "nul" input_save_state = "f2" input_save_state_axis = "nul" input_save_state_btn = "nul" input_save_state_mbtn = "nul" input_screenshot = "f8" input_screenshot_axis = "nul" input_screenshot_btn = "nul" input_screenshot_mbtn = "nul" input_sensors_enable = "true" input_shader_next = "m" input_shader_next_axis = "nul" input_shader_next_btn = "nul" input_shader_next_mbtn = "nul" input_shader_prev = "n" input_shader_prev_axis = "nul" input_shader_prev_btn = "nul" input_shader_prev_mbtn = "nul" input_shader_toggle = "comma" input_shader_toggle_axis = "nul" input_shader_toggle_btn = "nul" input_shader_toggle_mbtn = "nul" input_state_slot_decrease = "f6" input_state_slot_decrease_axis = "nul" input_state_slot_decrease_btn = "nul" input_state_slot_decrease_mbtn = "nul" input_state_slot_increase = "f7" input_state_slot_increase_axis = "nul" input_state_slot_increase_btn = "nul" input_state_slot_increase_mbtn = "nul" input_streaming_toggle = "nul" input_streaming_toggle_axis = "nul" input_streaming_toggle_btn = "nul" input_streaming_toggle_mbtn = "nul" input_toggle_fast_forward = "space" input_toggle_fast_forward_axis = "nul" input_toggle_fast_forward_btn = "nul" input_toggle_fast_forward_mbtn = "nul" input_toggle_fullscreen = "f" input_toggle_fullscreen_axis = "nul" input_toggle_fullscreen_btn = "nul" input_toggle_fullscreen_mbtn = "nul" input_toggle_slowmotion = "nul" input_toggle_slowmotion_axis = "nul" input_toggle_slowmotion_btn = "nul" input_toggle_slowmotion_mbtn = "nul" input_toggle_statistics = "nul" input_toggle_statistics_axis = "nul" input_toggle_statistics_btn = "nul" input_toggle_statistics_mbtn = "nul" input_toggle_vrr_runloop = "nul" input_toggle_vrr_runloop_axis = "nul" input_toggle_vrr_runloop_btn = "nul" input_toggle_vrr_runloop_mbtn = "nul" input_touch_scale = "1" input_turbo_default_button = "0" input_turbo_mode = "0" input_turbo_period = "6" input_volume_down = "subtract" input_volume_down_axis = "nul" input_volume_down_btn = "nul" input_volume_down_mbtn = "nul" input_volume_up = "add" input_volume_up_axis = "nul" input_volume_up_btn = "nul" input_volume_up_mbtn = "nul" joypad_autoconfig_dir = "" keyboard_gamepad_enable = "true" keyboard_gamepad_mapping_type = "1" kiosk_mode_enable = "false" kiosk_mode_password = "" led_driver = "null" libretro_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//cores" libretro_info_path = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//info" libretro_log_level = "1" load_dummy_on_core_shutdown = "false" location_allow = "false" location_driver = "null" log_dir = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/logs" log_to_file = "false" log_to_file_timestamp = "false" log_verbosity = "false" memory_show = "false" memory_update_interval = "256" menu_battery_level_enable = "false" menu_core_enable = "true" menu_disable_info_button = "true" menu_disable_left_analog = "false" menu_disable_right_analog = "true" menu_disable_search_button = "true" menu_driver = "rgui" menu_dynamic_wallpaper_enable = "false" menu_enable_widgets = "false" menu_footer_opacity = "1.000000" menu_framebuffer_opacity = "0.900000" menu_header_opacity = "1.000000" menu_horizontal_animation = "true" menu_icon_thumbnails = "0" menu_insert_disk_resume = "true" menu_left_thumbnails = "0" menu_linear_filter = "true" menu_mouse_enable = "false" menu_navigation_browser_filter_supported_extensions_enable = "true" menu_navigation_wraparound_enable = "true" menu_pause_libretro = "true" menu_pointer_enable = "false" menu_rgui_full_width_layout = "true" menu_rgui_shadows = "false" menu_rgui_transparency = "true" menu_savestate_resume = "false" menu_scale_factor = "1.000000" menu_screensaver_timeout = "0" menu_scroll_delay = "256" menu_scroll_fast = "false" menu_show_advanced_settings = "true" menu_show_configurations = "false" menu_show_core_updater = "false" menu_show_help = "false" menu_show_information = "false" menu_show_latency = "false" menu_show_load_content = "false" menu_show_load_content_animation = "false" menu_show_load_core = "false" menu_show_online_updater = "false" menu_show_overlays = "false" menu_show_quit_retroarch = "false" menu_show_reboot = "true" menu_show_restart_retroarch = "true" menu_show_rewind = "false" menu_show_shutdown = "false" menu_show_sublabels = "true" menu_swap_ok_cancel_buttons = "true" menu_swap_scroll_buttons = "false" menu_throttle_framerate = "true" menu_thumbnail_upscale_threshold = "0" menu_thumbnails = "0" menu_ticker_smooth = "true" menu_ticker_speed = "2.000000" menu_ticker_type = "1" menu_timedate_date_separator = "0" menu_timedate_enable = "false" menu_timedate_style = "11" menu_unified_controls = "false" menu_use_preferred_system_color_theme = "false" menu_wallpaper = "" menu_wallpaper_opacity = "1.000000" menu_widget_scale_auto = "true" menu_widget_scale_factor = "1.000000" midi_driver = "null" midi_input = "OFF" midi_output = "OFF" midi_volume = "100" notification_show_autoconfig = "false" notification_show_cheats_applied = "false" notification_show_config_override_load = "false" notification_show_disk_control = "false" notification_show_fast_forward = "true" notification_show_patch_applied = "true" notification_show_refresh_rate = "false" notification_show_remap_load = "false" notification_show_save_state = "true" notification_show_screenshot = "false" notification_show_screenshot_duration = "0" notification_show_screenshot_flash = "0" notification_show_set_initial_disk = "false" notification_show_when_menu_is_alive = "false" pause_nonactive = "true" pause_on_disconnect = "false" perfcnt_enable = "false" playlist_allow_non_png = "false" playlist_compression = "false" playlist_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/playlists" playlist_entry_remove_enable = "2" playlist_entry_rename = "false" playlist_fuzzy_archive_match = "false" playlist_portable_paths = "false" playlist_show_entry_idx = "false" playlist_show_history_icons = "1" playlist_show_inline_core_name = "2" playlist_show_sublabels = "false" playlist_sort_alphabetical = "true" playlist_sublabel_last_played_style = "1" playlist_sublabel_runtime_type = "0" playlist_use_filename = "false" playlist_use_old_format = "false" preemptive_frames_enable = "false" preemptive_frames_hide_warnings = "false" quick_menu_show_add_to_favorites = "false" quick_menu_show_add_to_playlist = "false" quick_menu_show_cheats = "true" quick_menu_show_close_content = "false" quick_menu_show_controls = "true" quick_menu_show_core_options_flush = "false" quick_menu_show_information = "false" quick_menu_show_options = "true" quick_menu_show_replay = "false" quick_menu_show_reset_core_association = "false" quick_menu_show_restart_content = "true" quick_menu_show_resume_content = "true" quick_menu_show_save_content_dir_overrides = "false" quick_menu_show_save_core_overrides = "false" quick_menu_show_save_game_overrides = "false" quick_menu_show_save_load_state = "true" quick_menu_show_savestate_submenu = "true" quick_menu_show_set_core_association = "false" quick_menu_show_shaders = "false" quick_menu_show_start_recording = "false" quick_menu_show_start_streaming = "false" quick_menu_show_take_screenshot = "false" quick_menu_show_undo_save_load_state = "false" quit_on_close_content = "0" quit_press_twice = "false" record_driver = "null" recording_config_directory = "" recording_output_directory = "" remap_save_on_exit = "false" replay_auto_index = "true" replay_checkpoint_interval = "0" replay_max_keep = "0" replay_slot = "0" resampler_directory = "" rewind_buffer_size = "20971520" rewind_buffer_size_step = "10" rewind_enable = "false" rewind_granularity = "1" rgui_aspect_ratio = "11" rgui_aspect_ratio_lock = "0" rgui_background_filler_thickness_enable = "false" rgui_border_filler_enable = "true" rgui_border_filler_thickness_enable = "false" rgui_browser_directory = "default" rgui_config_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/config" rgui_extended_ascii = "false" rgui_inline_thumbnails = "false" rgui_internal_upscale_level = "0" rgui_menu_color_theme = "3" rgui_menu_theme_preset = "" rgui_particle_effect = "0" rgui_particle_effect_screensaver = "true" rgui_particle_effect_speed = "1.000000" rgui_show_start_screen = "false" rgui_swap_thumbnails = "false" rgui_switch_icons = "true" rgui_thumbnail_delay = "256" rgui_thumbnail_downscaler = "0" run_ahead_enabled = "false" run_ahead_frames = "1" run_ahead_hide_warnings = "false" run_ahead_secondary_instance = "true" runtime_log_directory = "default" save_file_compression = "true" savefile_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/savefiles" savefiles_in_content_dir = "false" savestate_auto_index = "false" savestate_auto_load = "false" savestate_auto_save = "false" savestate_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/savestates" savestate_file_compression = "true" savestate_max_keep = "0" savestate_thumbnail_enable = "false" savestates_in_content_dir = "false" scan_serial_and_crc = "false" scan_without_core_match = "false" screen_brightness = "100" screen_orientation = "0" screenshot_directory = "default" screenshots_in_content_dir = "false" settings_show_accessibility = "false" settings_show_achievements = "false" settings_show_ai_service = "false" settings_show_audio = "false" settings_show_configuration = "false" settings_show_core = "false" settings_show_directory = "false" settings_show_drivers = "false" settings_show_file_browser = "false" settings_show_frame_throttle = "false" settings_show_input = "false" settings_show_latency = "false" settings_show_logging = "false" settings_show_network = "false" settings_show_onscreen_display = "false" settings_show_playlists = "false" settings_show_power_management = "false" settings_show_recording = "false" settings_show_saving = "false" settings_show_user = "false" settings_show_user_interface = "true" settings_show_video = "true" show_hidden_files = "false" slowmotion_ratio = "3.000000" soft_filter_enable = "false" soft_filter_index = "0" sort_savefiles_by_content_enable = "false" sort_savefiles_enable = "false" sort_savestates_by_content_enable = "false" sort_savestates_enable = "false" sort_screenshots_by_content_enable = "false" state_slot = "0" statistics_show = "false" suspend_screensaver_enable = "true" sustained_performance_mode = "false" system_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/system" systemfiles_in_content_dir = "false" thumbnails_directory = "mass:/RetroLauncher/System/RetroarchPS2/Nintendo Game Boy Color//retroarch/thumbnails" ui_companion_enable = "false" ui_companion_start_on_boot = "true" ui_companion_toggle = "false" ui_menubar_enable = "true" use_last_start_directory = "false" vibrate_on_keypress = "false" video_adaptive_vsync = "false" video_allow_rotate = "true" video_aspect_ratio = "1.253300" video_aspect_ratio_auto = "false" video_autoswitch_pal_threshold = "54.500000" video_autoswitch_refresh_rate = "0" video_bfi_dark_frames = "1" video_black_frame_insertion = "0" video_context_driver = "" video_crop_overscan = "true" video_ctx_scaling = "false" video_disable_composition = "false" video_driver = "ps2" video_filter = "" video_filter_dir = "default" video_font_enable = "true" video_font_path = "" video_font_size = "16.000000" video_force_aspect = "true" video_force_srgb_disable = "false" video_frame_delay = "0" video_frame_delay_auto = "false" video_frame_rest = "false" video_fullscreen = "false" video_fullscreen_x = "0" video_fullscreen_y = "0" video_gpu_record = "false" video_gpu_screenshot = "true" video_hard_sync = "false" video_hard_sync_frames = "0" video_hdr_display_contrast = "5.000000" video_hdr_enable = "false" video_hdr_expand_gamut = "true" video_hdr_max_nits = "1000.000000" video_hdr_paper_white_nits = "200.000000" video_max_frame_latency = "1" video_max_swapchain_images = "3" video_message_color = "f6f6f6" video_message_pos_x = "0.050000" video_message_pos_y = "0.050000" video_monitor_index = "0" video_msg_bgcolor_blue = "0" video_msg_bgcolor_enable = "true" video_msg_bgcolor_green = "0" video_msg_bgcolor_opacity = "1.000000" video_msg_bgcolor_red = "0" video_notch_write_over_enable = "false" video_post_filter_record = "false" video_record_config = "" video_record_quality = "2" video_record_scale_factor = "1" video_record_threads = "2" video_refresh_rate = "59.940063" video_rotation = "0" video_scale = "3" video_scale_integer = "true" video_scale_integer_axis = "0" video_scale_integer_overscale = "true" video_scale_integer_scaling = "0" video_scan_subframes = "false" video_shader_delay = "0" video_shader_dir = "default" video_shader_enable = "true" video_shader_preset_save_reference_enable = "true" video_shader_remember_last_dir = "false" video_shader_subframes = "1" video_shader_watch_files = "false" video_shared_context = "false" video_smooth = "false" video_stream_config = "" video_stream_port = "56400" video_stream_quality = "11" video_stream_scale_factor = "1" video_stream_url = "" video_swap_interval = "1" video_threaded = "false" video_viewport_bias_x = "0.500000" video_viewport_bias_y = "0.500000" video_vsync = "true" video_waitable_swapchains = "true" video_window_auto_height_max = "1080" video_window_auto_width_max = "1920" video_window_custom_size_enable = "false" video_window_offset_x = "0" video_window_offset_y = "0" video_window_opacity = "100" video_window_save_positions = "false" video_window_show_decorations = "true" video_windowed_fullscreen = "true" video_windowed_position_height = "720" video_windowed_position_width = "1280" video_windowed_position_x = "0" video_windowed_position_y = "0" vrr_runloop_enable = "false" wifi_driver = "null" wifi_enabled = "true" xmb_font = ""
0
0.686942
1
0.686942
game-dev
MEDIA
0.618426
game-dev,desktop-app
0.765033
1
0.765033
aajiwani/EasyNDK-for-cocos2dx
13,628
Sample iOS Project/SampleNDK/libs/extensions/GUI/CCScrollView/CCTableView.cpp
/**************************************************************************** Copyright (c) 2012 cocos2d-x.org Copyright (c) 2010 Sangwoo Im http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "cocos2d.h" #include "CCTableView.h" #include "CCTableViewCell.h" #include "menu_nodes/CCMenu.h" #include "support/CCPointExtension.h" #include "CCSorting.h" #include "layers_scenes_transitions_nodes/CCLayer.h" NS_CC_EXT_BEGIN CCTableView* CCTableView::create(CCTableViewDataSource* dataSource, CCSize size) { return CCTableView::create(dataSource, size, NULL); } CCTableView* CCTableView::create(CCTableViewDataSource* dataSource, CCSize size, CCNode *container) { CCTableView *table = new CCTableView(); table->initWithViewSize(size, container); table->autorelease(); table->setDataSource(dataSource); table->_updateContentSize(); return table; } bool CCTableView::initWithViewSize(CCSize size, CCNode* container/* = NULL*/) { if (CCScrollView::initWithViewSize(size,container)) { m_pCellsUsed = new CCArrayForObjectSorting(); m_pCellsFreed = new CCArrayForObjectSorting(); m_pIndices = new std::set<unsigned int>(); m_pTableViewDelegate = NULL; m_eVordering = kCCTableViewFillBottomUp; this->setDirection(kCCScrollViewDirectionVertical); CCScrollView::setDelegate(this); return true; } return false; } CCTableView::CCTableView() : m_pIndices(NULL) , m_pCellsUsed(NULL) , m_pCellsFreed(NULL) , m_pDataSource(NULL) , m_pTableViewDelegate(NULL) , m_eOldDirection(kCCScrollViewDirectionNone) { } CCTableView::~CCTableView() { CC_SAFE_DELETE(m_pIndices); CC_SAFE_RELEASE(m_pCellsUsed); CC_SAFE_RELEASE(m_pCellsFreed); } void CCTableView::setVerticalFillOrder(CCTableViewVerticalFillOrder fillOrder) { if (m_eVordering != fillOrder) { m_eVordering = fillOrder; if (m_pCellsUsed->count() > 0) { this->reloadData(); } } } CCTableViewVerticalFillOrder CCTableView::getVerticalFillOrder() { return m_eVordering; } void CCTableView::reloadData() { CCObject* pObj = NULL; CCARRAY_FOREACH(m_pCellsUsed, pObj) { CCTableViewCell* cell = (CCTableViewCell*)pObj; m_pCellsFreed->addObject(cell); cell->reset(); if (cell->getParent() == this->getContainer()) { this->getContainer()->removeChild(cell, true); } } m_pIndices->clear(); m_pCellsUsed->release(); m_pCellsUsed = new CCArrayForObjectSorting(); this->_updateContentSize(); if (m_pDataSource->numberOfCellsInTableView(this) > 0) { this->scrollViewDidScroll(this); } } CCTableViewCell *CCTableView::cellAtIndex(unsigned int idx) { return this->_cellWithIndex(idx); } void CCTableView::updateCellAtIndex(unsigned int idx) { if (idx == CC_INVALID_INDEX || idx > m_pDataSource->numberOfCellsInTableView(this)-1) { return; } CCTableViewCell *cell; cell = this->_cellWithIndex(idx); if (cell) { this->_moveCellOutOfSight(cell); } cell = m_pDataSource->tableCellAtIndex(this, idx); this->_setIndexForCell(idx, cell); this->_addCellIfNecessary(cell); } void CCTableView::insertCellAtIndex(unsigned int idx) { if (idx == CC_INVALID_INDEX || idx > m_pDataSource->numberOfCellsInTableView(this)-1) { return; } CCTableViewCell *cell; int newIdx; cell = (CCTableViewCell*)m_pCellsUsed->objectWithObjectID(idx); if (cell) { newIdx = m_pCellsUsed->indexOfSortedObject(cell); for (unsigned int i=newIdx; i<m_pCellsUsed->count(); i++) { cell = (CCTableViewCell*)m_pCellsUsed->objectAtIndex(i); this->_setIndexForCell(cell->getIdx()+1, cell); } } // [m_pIndices shiftIndexesStartingAtIndex:idx by:1]; //insert a new cell cell = m_pDataSource->tableCellAtIndex(this, idx); this->_setIndexForCell(idx, cell); this->_addCellIfNecessary(cell); this->_updateContentSize(); } void CCTableView::removeCellAtIndex(unsigned int idx) { if (idx == CC_INVALID_INDEX || idx > m_pDataSource->numberOfCellsInTableView(this)-1) { return; } CCTableViewCell *cell; unsigned int newIdx; cell = this->_cellWithIndex(idx); if (!cell) { return; } newIdx = m_pCellsUsed->indexOfSortedObject(cell); //remove first this->_moveCellOutOfSight(cell); m_pIndices->erase(idx); // [m_pIndices shiftIndexesStartingAtIndex:idx+1 by:-1]; for (unsigned int i=m_pCellsUsed->count()-1; i > newIdx; i--) { cell = (CCTableViewCell*)m_pCellsUsed->objectAtIndex(i); this->_setIndexForCell(cell->getIdx()-1, cell); } } CCTableViewCell *CCTableView::dequeueCell() { CCTableViewCell *cell; if (m_pCellsFreed->count() == 0) { cell = NULL; } else { cell = (CCTableViewCell*)m_pCellsFreed->objectAtIndex(0); cell->retain(); m_pCellsFreed->removeObjectAtIndex(0); cell->autorelease(); } return cell; } void CCTableView::_addCellIfNecessary(CCTableViewCell * cell) { if (cell->getParent() != this->getContainer()) { this->getContainer()->addChild(cell); } m_pCellsUsed->insertSortedObject(cell); m_pIndices->insert(cell->getIdx()); // [m_pIndices addIndex:cell.idx]; } void CCTableView::_updateContentSize() { CCSize size, cellSize; unsigned int cellCount; cellSize = m_pDataSource->cellSizeForTable(this); cellCount = m_pDataSource->numberOfCellsInTableView(this); switch (this->getDirection()) { case kCCScrollViewDirectionHorizontal: size = CCSizeMake(cellCount * cellSize.width, cellSize.height); break; default: size = CCSizeMake(cellSize.width, cellCount * cellSize.height); break; } this->setContentSize(size); if (m_eOldDirection != m_eDirection) { if (m_eDirection == kCCScrollViewDirectionHorizontal) { this->setContentOffset(ccp(0,0)); } else { this->setContentOffset(ccp(0,this->minContainerOffset().y)); } m_eOldDirection = m_eDirection; } } CCPoint CCTableView::_offsetFromIndex(unsigned int index) { CCPoint offset = this->__offsetFromIndex(index); const CCSize cellSize = m_pDataSource->cellSizeForTable(this); if (m_eVordering == kCCTableViewFillTopDown) { offset.y = this->getContainer()->getContentSize().height - offset.y - cellSize.height; } return offset; } CCPoint CCTableView::__offsetFromIndex(unsigned int index) { CCPoint offset; CCSize cellSize; cellSize = m_pDataSource->cellSizeForTable(this); switch (this->getDirection()) { case kCCScrollViewDirectionHorizontal: offset = ccp(cellSize.width * index, 0.0f); break; default: offset = ccp(0.0f, cellSize.height * index); break; } return offset; } unsigned int CCTableView::_indexFromOffset(CCPoint offset) { int index = 0; const int maxIdx = m_pDataSource->numberOfCellsInTableView(this)-1; const CCSize cellSize = m_pDataSource->cellSizeForTable(this); if (m_eVordering == kCCTableViewFillTopDown) { offset.y = this->getContainer()->getContentSize().height - offset.y - cellSize.height; } index = MAX(0, this->__indexFromOffset(offset)); index = MIN(index, maxIdx); return index; } int CCTableView::__indexFromOffset(CCPoint offset) { int index = 0; CCSize cellSize; cellSize = m_pDataSource->cellSizeForTable(this); switch (this->getDirection()) { case kCCScrollViewDirectionHorizontal: index = offset.x/cellSize.width; break; default: index = offset.y/cellSize.height; break; } return index; } CCTableViewCell* CCTableView::_cellWithIndex(unsigned int cellIndex) { CCTableViewCell *found; found = NULL; // if ([m_pIndices containsIndex:cellIndex]) if (m_pIndices->find(cellIndex) != m_pIndices->end()) { found = (CCTableViewCell *)m_pCellsUsed->objectWithObjectID(cellIndex); } return found; } void CCTableView::_moveCellOutOfSight(CCTableViewCell *cell) { m_pCellsFreed->addObject(cell); m_pCellsUsed->removeSortedObject(cell); m_pIndices->erase(cell->getIdx()); // [m_pIndices removeIndex:cell.idx]; cell->reset(); if (cell->getParent() == this->getContainer()) { this->getContainer()->removeChild(cell, true);; } } void CCTableView::_setIndexForCell(unsigned int index, CCTableViewCell *cell) { cell->setAnchorPoint(ccp(0.0f, 0.0f)); cell->setPosition(this->_offsetFromIndex(index)); cell->setIdx(index); } void CCTableView::scrollViewDidScroll(CCScrollView* view) { unsigned int startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0; CCPoint offset; offset = ccpMult(this->getContentOffset(), -1); maxIdx = MAX(m_pDataSource->numberOfCellsInTableView(this)-1, 0); const CCSize cellSize = m_pDataSource->cellSizeForTable(this); if (m_eVordering == kCCTableViewFillTopDown) { offset.y = offset.y + m_tViewSize.height/this->getContainer()->getScaleY() - cellSize.height; } startIdx = this->_indexFromOffset(offset); if (m_eVordering == kCCTableViewFillTopDown) { offset.y -= m_tViewSize.height/this->getContainer()->getScaleY(); } else { offset.y += m_tViewSize.height/this->getContainer()->getScaleY(); } offset.x += m_tViewSize.width/this->getContainer()->getScaleX(); endIdx = this->_indexFromOffset(offset); #if 0 // For Testing. CCObject* pObj; int i = 0; CCARRAY_FOREACH(m_pCellsUsed, pObj) { CCTableViewCell* pCell = (CCTableViewCell*)pObj; CCLog("cells Used index %d, value = %d", i, pCell->getIdx()); i++; } CCLog("---------------------------------------"); i = 0; CCARRAY_FOREACH(m_pCellsFreed, pObj) { CCTableViewCell* pCell = (CCTableViewCell*)pObj; CCLog("cells freed index %d, value = %d", i, pCell->getIdx()); i++; } CCLog("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); #endif if (m_pCellsUsed->count() > 0) { CCTableViewCell* cell = (CCTableViewCell*)m_pCellsUsed->objectAtIndex(0); idx = cell->getIdx(); while(idx <startIdx) { this->_moveCellOutOfSight(cell); if (m_pCellsUsed->count() > 0) { cell = (CCTableViewCell*)m_pCellsUsed->objectAtIndex(0); idx = cell->getIdx(); } else { break; } } } if (m_pCellsUsed->count() > 0) { CCTableViewCell *cell = (CCTableViewCell*)m_pCellsUsed->lastObject(); idx = cell->getIdx(); while(idx <= maxIdx && idx > endIdx) { this->_moveCellOutOfSight(cell); if (m_pCellsUsed->count() > 0) { cell = (CCTableViewCell*)m_pCellsUsed->lastObject(); idx = cell->getIdx(); } else { break; } } } for (unsigned int i=startIdx; i <= endIdx; i++) { //if ([m_pIndices containsIndex:i]) if (m_pIndices->find(i) != m_pIndices->end()) { continue; } this->updateCellAtIndex(i); } } void CCTableView::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) { if (!this->isVisible()) { return; } if (m_pTouches->count() == 1 && !this->isTouchMoved()) { unsigned int index; CCTableViewCell *cell; CCPoint point; point = this->getContainer()->convertTouchToNodeSpace(pTouch); if (m_eVordering == kCCTableViewFillTopDown) { CCSize cellSize = m_pDataSource->cellSizeForTable(this); point.y -= cellSize.height; } index = this->_indexFromOffset(point); cell = this->_cellWithIndex(index); if (cell) { m_pTableViewDelegate->tableCellTouched(this, cell); } } CCScrollView::ccTouchEnded(pTouch, pEvent); } NS_CC_EXT_END
0
0.990643
1
0.990643
game-dev
MEDIA
0.663097
game-dev
0.997295
1
0.997295
MinecraftForge/MCPConfig
1,271
versions/release/1.18/patches/shared/net/minecraft/util/datafix/fixes/LeavesFix.java.patch
--- a/net/minecraft/util/datafix/fixes/LeavesFix.java +++ b/net/minecraft/util/datafix/fixes/LeavesFix.java @@ -298,7 +298,7 @@ throw new IllegalStateException("Block state type is not what was expected."); } else { Optional<List<Pair<String, Dynamic<?>>>> optional = p_16286_.getOptional(this.f_16280_); - this.f_16281_ = optional.map((p_16297_) -> { + this.f_16281_ = optional.<List<Dynamic<?>>>map((p_16297_) -> { return p_16297_.stream().map(Pair::getSecond).collect(Collectors.toList()); }).orElse(ImmutableList.of()); Dynamic<?> dynamic = p_16286_.get(DSL.remainderFinder()); @@ -321,7 +321,7 @@ public Typed<?> m_16288_(Typed<?> p_16289_) { return this.m_16298_() ? p_16289_ : p_16289_.update(DSL.remainderFinder(), (p_16305_) -> { return p_16305_.set("BlockStates", p_16305_.createLongList(Arrays.stream(this.f_16283_.m_14561_()))); - }).set(this.f_16280_, this.f_16281_.stream().map((p_16300_) -> { + }).set(this.f_16280_, this.f_16281_.stream().<Pair<String, Dynamic<?>>>map((p_16300_) -> { return Pair.of(References.f_16783_.typeName(), p_16300_); }).collect(Collectors.toList())); }
0
0.659853
1
0.659853
game-dev
MEDIA
0.186145
game-dev
0.81471
1
0.81471
Kaedrin/nwn2cc
11,630
NWN2 WIP/Override/override_latest/Scripts/nw_s1_barbrage.NSS
//:://///////////////////////////////////////////// //:: Barbarian Rage //:: NW_S1_BarbRage //:: Copyright (c) 2001 Bioware Corp. //::////////////////////////////////////////////// /* The Str and Con of the Barbarian increases, Will Save are +2, AC -2. Greater Rage starts at level 15. */ //::////////////////////////////////////////////// //:: Created By: Preston Watamaniuk //:: Created On: Aug 13, 2001 //::////////////////////////////////////////////// //:: AFW-OEI 04/12/2006: Made Greater and Mighty rage work as per 3.5 rules. //:: Added fatigue after raging. //:: Added Tireless Rage feat. //::////////////////////////////////////////////// //:: AFW-OEI 07/11/2007: New GetHasFeat() function call //:: now returns false if a feat is not useable due to cooldown. //:: So use new parameter to ignore remaining uses as we're merely doing //:: an existence check. //:: AFW-OEI 02/16/2007: Implement Epic Rage. //:: AFW-OEI 06/25/2007: Implement Ice Troll Berserker. #include "x2_i0_spells" #include "nwn2_inc_spells" #include "cmi_ginc_chars" void ApplyFatigue2(object oTarget, int nFatigueDuration, float fDelay = 0.0f); void ApplyFatigue3(object oTarget, int nFatigueDuration); void main() { int nBarb = GetLevelByClass(CLASS_TYPE_BARBARIAN); // If you're already in a rage, don't apply effects again if(!GetHasFeatEffect(FEAT_BARBARIAN_RAGE)) { RemoveEffectsFromSpell(OBJECT_SELF, FATIGUE); //Remove debuff when you start raging again // JLR - OEI 06/21/05 NWN2 3.5 // AFW-OEI 04/11/2006: Implement Mighty Rage. int nIncrease; int nSave; int nNaturalAC = 0; if (GetHasFeat(FEAT_EPIC_BARBARIAN_RAGE, OBJECT_SELF, TRUE)) // Epic Rage { nIncrease = 10; nSave = 8; // Intentional extra Will boost for Epic Barbs. nNaturalAC = 8; } else if (GetHasFeat(FEAT_BARBARIAN_RAGE7, OBJECT_SELF, TRUE)) // Mighty Rage { //SpeakString("nw_s1_barbrage: Has FEAT_BARBARIAN_RAGE7."); // DEBUG nIncrease = 8; nSave = 4; nNaturalAC = 6; } else if (GetHasFeat(FEAT_BARBARIAN_RAGE4, OBJECT_SELF, TRUE)) // Greater Rage { //SpeakString("nw_s1_barbrage: Has FEAT_BARBARIAN_RAGE4."); // DEBUG nIncrease = 6; nSave = 3; nNaturalAC = 4; } else // Regular old rage { //SpeakString("nw_s1_barbrage: Default bonuses."); // DEBUG nIncrease = 4; nSave = 2; nNaturalAC = 2; } //Determine the duration by getting the con modifier after being modified int nRageDuration = 4 + GetAbilityModifier(ABILITY_CONSTITUTION) + (nIncrease/2); if (GetHasFeat(FEAT_EXTEND_RAGE)) { nRageDuration += 5; if (GetHasFeat(FEAT_EXTEND_RAGE_II)) { nRageDuration += 5; if (GetHasFeat(FEAT_EXTEND_RAGE_III)) { nRageDuration += 5; if (GetHasFeat(FEAT_EXTEND_RAGE_IV)) { nRageDuration += 5; } } } } int isPC = GetIsPC(OBJECT_SELF); if (!isPC) { nRageDuration = nRageDuration*10; } float fRageDuration = RoundsToSeconds(nRageDuration); // Add Indomitable Will save bonus, if you have it if (GetHasFeat(FEAT_INDOMITABLE_WILL, OBJECT_SELF, TRUE)) { effect eWill = EffectSavingThrowIncrease(SAVING_THROW_WILL, 4, SAVING_THROW_TYPE_MIND_SPELLS); eWill = SetEffectSpellId(eWill, -GetSpellId()); eWill = ExtraordinaryEffect(eWill); ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eWill, OBJECT_SELF, fRageDuration); } //Level 14 effect eDmgBonus = EffectDamageIncrease(DAMAGE_BONUS_1d6, DAMAGE_TYPE_FIRE); if (GetHasFeat(FEAT_ICE_TROLL_BERSERKER)) eDmgBonus = EffectDamageIncrease(DAMAGE_BONUS_1d6, DAMAGE_TYPE_COLD); //Level 8 int nRegenBonus = nBarb/6; if (nRegenBonus == 0) nRegenBonus = 1; effect eRegen = EffectRegenerate(nRegenBonus, 6.0); //Level 6 if (nBarb > 5) { int nHealValue = 0; int nHealDice = 1; if (nBarb > 4) nHealDice = (nBarb/4); nHealValue = d8(nHealDice) + GetAbilityModifier(ABILITY_CONSTITUTION) + (nIncrease/2); effect eHeal = EffectHeal(nHealValue); effect eHealVis = EffectVisualEffect(VFX_IMP_HEALING_S); DelayCommand(0.1f, ApplyEffectToObject(DURATION_TYPE_INSTANT, eHeal, OBJECT_SELF)); DelayCommand(0.2f, ApplyEffectToObject(DURATION_TYPE_INSTANT, eHealVis, OBJECT_SELF)); } //Level 24 Renewed Vitality effect eImmuneAbilDmg = EffectImmunity(IMMUNITY_TYPE_ABILITY_DECREASE); effect eDeath = EffectImmunity(IMMUNITY_TYPE_DEATH); effect eNeg = EffectDamageResistance(DAMAGE_TYPE_NEGATIVE, 9999, 0); effect eLevel = EffectImmunity(IMMUNITY_TYPE_NEGATIVE_LEVEL); if (GetHasFeat(FEAT_BARB_WHIRLWIND_FRENZY)) { if (nRageDuration > 0) { effect eAB = EffectAttackDecrease(2); effect eAtks = EffectModifyAttacks(1); // Put together the positive rage effects effect eStr = EffectAbilityIncrease(ABILITY_STRENGTH, nIncrease); effect eSave = EffectSavingThrowIncrease(SAVING_THROW_REFLEX, nIncrease/2); effect eAC = EffectACIncrease(nIncrease/2, AC_DODGE_BONUS); effect eDur = EffectVisualEffect( VFX_DUR_SPELL_RAGE ); effect eLink = EffectLinkEffects(eStr, eSave); eLink = EffectLinkEffects(eLink, eAC); eLink = EffectLinkEffects(eLink, eDur); if (nBarb > 7) { eLink = EffectLinkEffects(eLink, eRegen); } if (nBarb > 13) { eLink = EffectLinkEffects(eLink, eDmgBonus); } if (nBarb > 23) { eLink = EffectLinkEffects(eLink, eImmuneAbilDmg); eLink = EffectLinkEffects(eLink, eDeath); eLink = EffectLinkEffects(eLink, eNeg); eLink = EffectLinkEffects(eLink, eLevel); } if (!GetHasSpellEffect(SPELL_HASTE,OBJECT_SELF)) { eLink = EffectLinkEffects(eLink, eAB); eLink = EffectLinkEffects(eLink, eAtks); } effect eNaturalAC; if (GetHasFeat(FEAT_ICE_TROLL_BERSERKER, OBJECT_SELF, TRUE)) { eNaturalAC = EffectACIncrease(nNaturalAC, AC_NATURAL_BONUS); eLink = EffectLinkEffects(eLink, eNaturalAC); } eLink = ExtraordinaryEffect(eLink); //Make effect extraordinary PlayVoiceChat(VOICE_CHAT_BATTLECRY1); if ( PlayCustomAnimation(OBJECT_SELF, "sp_warcry", 0) ) { //FloatingTextStringOnCreature( "I HAVE THE WARCRY ANIMATION!", OBJECT_SELF ); } SignalEvent(OBJECT_SELF, EventSpellCastAt(OBJECT_SELF, SPELLABILITY_BARBARIAN_RAGE, FALSE)); //Apply the VFX impact and effects ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eLink, OBJECT_SELF, fRageDuration); //ApplyEffectToObject(DURATION_TYPE_INSTANT, eVis, OBJECT_SELF) ; if (GetHasFeat(FEAT_SHARED_FURY, OBJECT_SELF)) { object oMyPet = GetAssociate(ASSOCIATE_TYPE_ANIMALCOMPANION, OBJECT_SELF); if (GetIsObjectValid(oMyPet)) DelayCommand(0.1f, ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eLink, oMyPet, fRageDuration)); } // 2003-07-08, Georg: Rage Epic Feat Handling CheckAndApplyEpicRageFeats(nRageDuration); // Unless you have Tireless Rage, you're going to feel it in the morning if (!GetHasFeat(FEAT_TIRELESS_RAGE, OBJECT_SELF, TRUE)) { if (!GetHasFeat(FEAT_TIRELESS)) // Start the fatigue logic half a second before the rage ends DelayCommand(fRageDuration - 0.5f, ApplyFatigue2(OBJECT_SELF, 5, 0.6f)); // Fatigue duration fixed to 5 rounds } } } else { // Apply rage bonuses, but only if your rage is going to last more than 0 rounds if (nRageDuration > 0) { // Put together the positive rage effects effect eCon = EffectAbilityIncrease(ABILITY_CONSTITUTION, nIncrease); effect eStr = EffectAbilityIncrease(ABILITY_STRENGTH, nIncrease); effect eSave = EffectSavingThrowIncrease(SAVING_THROW_WILL, nSave); effect eAC = EffectACDecrease(2, AC_DODGE_BONUS); effect eDur = EffectVisualEffect( VFX_DUR_SPELL_RAGE ); effect eLink = EffectLinkEffects(eCon, eStr); eLink = EffectLinkEffects(eLink, eSave); eLink = EffectLinkEffects(eLink, eAC); eLink = EffectLinkEffects(eLink, eDur); if (nBarb > 7) { eLink = EffectLinkEffects(eLink, eRegen); } if (nBarb > 13) { eLink = EffectLinkEffects(eLink, eDmgBonus); } if (nBarb > 23) { eLink = EffectLinkEffects(eLink, eImmuneAbilDmg); eLink = EffectLinkEffects(eLink, eDeath); eLink = EffectLinkEffects(eLink, eNeg); eLink = EffectLinkEffects(eLink, eLevel); } effect eNaturalAC; if (GetHasFeat(FEAT_ICE_TROLL_BERSERKER, OBJECT_SELF, TRUE)) { eNaturalAC = EffectACIncrease(nNaturalAC, AC_NATURAL_BONUS); eLink = EffectLinkEffects(eLink, eNaturalAC); } eLink = ExtraordinaryEffect(eLink); //Make effect extraordinary // Create the visual effect //effect eVis = EffectVisualEffect(VFX_IMP_IMPROVE_ABILITY_SCORE); //Change to the Rage VFX // "Cast" rage PlayVoiceChat(VOICE_CHAT_BATTLECRY1); if ( PlayCustomAnimation(OBJECT_SELF, "sp_warcry", 0) ) { //FloatingTextStringOnCreature( "I HAVE THE WARCRY ANIMATION!", OBJECT_SELF ); } SignalEvent(OBJECT_SELF, EventSpellCastAt(OBJECT_SELF, SPELLABILITY_BARBARIAN_RAGE, FALSE)); //Apply the VFX impact and effects ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eLink, OBJECT_SELF, fRageDuration); //ApplyEffectToObject(DURATION_TYPE_INSTANT, eVis, OBJECT_SELF) ; effect eHeal = EffectHeal(1); if ( GetCurrentHitPoints(OBJECT_SELF) > GetMaxHitPoints(OBJECT_SELF)) { ApplyEffectToObject(DURATION_TYPE_INSTANT, eHeal, OBJECT_SELF); } if (GetHasFeat(FEAT_SHARED_FURY, OBJECT_SELF)) { object oMyPet = GetAssociate(ASSOCIATE_TYPE_ANIMALCOMPANION, OBJECT_SELF); if (GetIsObjectValid(oMyPet)) DelayCommand(0.1f, ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eLink, oMyPet, fRageDuration)); } // 2003-07-08, Georg: Rage Epic Feat Handling CheckAndApplyEpicRageFeats(nRageDuration); // Unless you have Tireless Rage, you're going to feel it in the morning if (!GetHasFeat(FEAT_TIRELESS_RAGE, OBJECT_SELF, TRUE)) { if (!GetHasFeat(FEAT_TIRELESS)) // Start the fatigue logic half a second before the rage ends DelayCommand(fRageDuration - 0.5f, ApplyFatigue2(OBJECT_SELF, 5, 0.6f)); // Fatigue duration fixed to 5 rounds } } } } } void ApplyFatigue2(object oTarget, int nFatigueDuration, float fDelay = 0.0f) { //SpeakString("Entering ApplyFatigue"); // Only apply fatigue ifyou're not resting. // This is to keep you from getting fatigued if you rest while raging. if( !GetIsResting() && (GetHasFeatEffect(FEAT_BARBARIAN_RAGE)) ) { //SpeakString("Actually applying fatigue effect in ApplyFatigue"); DelayCommand(fDelay, ApplyFatigue3(oTarget, nFatigueDuration)); } } void ApplyFatigue3(object oTarget, int nFatigueDuration) { if( !GetHasFeatEffect(FEAT_BARBARIAN_RAGE) ) { // Create the fatigue penalty effect eFatigue = EffectCMIFatigue(); float fFatigueDuration = RoundsToSeconds(nFatigueDuration); ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eFatigue, oTarget, fFatigueDuration); } }
0
0.866302
1
0.866302
game-dev
MEDIA
0.924385
game-dev
0.930968
1
0.930968
kuronekotei/ElinMOD
1,581
TpAfCatsGoods/PatchAfCatsGoods.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Xml.Linq; using BepInEx; using HarmonyLib; using ReflexCLI.Attributes; using UnityEngine; namespace TpAfCatsGoods { [HarmonyPatch] public class PatchAfCatsGoods { [HarmonyPrefix, HarmonyPatch(typeof(LayerInventory), nameof(LayerInventory.CreateContainer), new Type[] { typeof(Card) })] public static bool CreateContainer(LayerInventory __instance, ref LayerInventory __result, Card owner) { if (owner.trait is TraitTpCatsBag) { if (LayerInventory.listInv.Find(x => x.Inv.owner == owner) is LayerInventory inv) { inv.Close(); } else { __result = LayerInventory.CreateContainer(owner, owner); } LayerInventory.SetDirty(owner.Thing); return false; } return true; } [HarmonyPrefix, HarmonyPatch(typeof(ThingContainer), nameof(ThingContainer.MaxCapacity), MethodType.Getter)] public static bool MaxCapacity(ThingContainer __instance, ref int __result) { if (__instance.owner.trait is TraitTpCatsBag) { __result = 860 + __instance.owner.c_containerUpgrade.cap; return false; } return true; } [HarmonyPrefix, HarmonyPatch(typeof(ThingContainer), nameof(ThingContainer.IsFull), new Type[] { typeof(int) })] public static bool IsFull(ThingContainer __instance, ref bool __result) { if (__instance.owner.trait is TraitTpCatsBag) { __result = __instance.Count >= __instance.MaxCapacity; return false; } return true; } } }
0
0.967193
1
0.967193
game-dev
MEDIA
0.89145
game-dev
0.988134
1
0.988134
RighteousRyan1/TanksRebirth
4,059
GameContent/Systems/PingSystem/PingMenu.cs
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using TanksRebirth.GameContent.ID; using TanksRebirth.GameContent.Globals; using TanksRebirth.Internals; using TanksRebirth.Internals.Common.Utilities; using TanksRebirth.Net; using TanksRebirth.GameContent.UI.MainMenu; using TanksRebirth.GameContent.UI.LevelEditor; using TanksRebirth.Internals.Common; namespace TanksRebirth.GameContent.Systems.PingSystem; public static class PingMenu { public static Dictionary<int, Texture2D> PingIdToTexture = []; // TODO: localize public static Dictionary<int, string> PingIdToName = new() { [PingID.Generic] = "Generic", [PingID.StayHere] = "Stay Here", [PingID.WatchHere] = "Watch Here", [PingID.AvoidHere] = "Avoid Here", [PingID.GoHere] = "Go Here", [PingID.FocusHere] = "Focus Here", [PingID.GroupHere] = "Group Here" }; public static void Initialize() { static string specialReplace(string s) => s.Replace(' ', '_').ToLower(); for (int i = 0; i < PingIdToName.Count; i++) { PingIdToTexture[i] = GameResources.GetGameResource<Texture2D>($"Assets/textures/ui/ping/{specialReplace(PingIdToName[i])}"); } } // for now just a graphic on the top right static float _uiOpacity; static int _pickedPingId; public static void DrawPingHUD() { if (InputUtils.MouseMiddle && !InputUtils.OldMouseMiddle) { if (MainMenuUI.IsActive || LevelEditorUI.IsActive || !CampaignGlobals.ShouldMissionsProgress || ChatSystem.ActiveHandle) return; IngamePing.CreateFromTankSender(MatrixUtils.GetWorldPosition(MouseUtils.MousePosition), _pickedPingId, NetPlay.GetMyClientId(), Client.IsConnected()); } _pickedPingId = Math.Abs(InputUtils.DeltaScrollWheel) % 7; if (_pickedPingId >= PingIdToName.Count) _pickedPingId = 0; else if (_pickedPingId < 0) _pickedPingId = PingIdToName.Count - 1; float offY = 0f; float scale = 0.5f; var basePos = WindowUtils.WindowRight - new Vector2(60, 300).ToResolution(); var padding = 10f; var rect = new Rectangle() { X = (int)(basePos.X - padding * 4), Y = (int)basePos.Y, Width = 0 }; for (int i = 0; i < PingIdToTexture.Count; i++) { var texture = PingIdToTexture[i]; if (texture.Width > rect.Width) rect.Width = (int)(texture.Width * scale); rect.Height += (int)(texture.Height * scale + padding); var isPicked = i == _pickedPingId; float pickOpacity = isPicked ? 0.8f : _uiOpacity; // draw the texture and the name of the ping type var pos = basePos + new Vector2(0, offY); DrawUtils.DrawStringWithBorder(TankGame.SpriteRenderer, FontGlobals.RebirthFontLarge, $"{i + 1}. {PingIdToName[i]}", pos, PlayerID.PlayerTankColors[NetPlay.GetMyClientId()] * pickOpacity, Color.White * pickOpacity, scale.ToResolution() * 0.35f, 0f, Anchor.TopCenter, 0.75f); TankGame.SpriteRenderer.Draw(PingIdToTexture[i], pos + new Vector2(0, 15), null, Color.White * pickOpacity, 0f, Anchor.TopCenter.GetAnchor(PingIdToTexture[i].Size()), scale.ToResolution(), default, 0f); offY += (PingIdToTexture[i].Height * scale + padding).ToResolutionX(); } if (rect.Contains(MouseUtils.MouseX, MouseUtils.MouseY)) { _uiOpacity += 0.04f * RuntimeData.DeltaTime; if (_uiOpacity > 0.85f) _uiOpacity = 0.85f; } else { _uiOpacity -= 0.04f * RuntimeData.DeltaTime; if (_uiOpacity < 0.1f) _uiOpacity = 0.1f; } } } // i dont think a radial would be optimal. Scroll wheel would even be better //public static Radial RadialMenu = new(2, new Circle()); //private static int _curPingId; // todo: finish impl
0
0.842762
1
0.842762
game-dev
MEDIA
0.835406
game-dev
0.953169
1
0.953169
Igoorx/PyRoyale
7,767
match.py
from twisted.internet import reactor from buffer import Buffer import os import json import random import jsonschema levelJsonSchema = json.loads(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "levelSchema.json"), "r").read()) class Match(object): def __init__(self, server, roomName, private): self.server = server self.forceLevel = "" self.customLevelData = "" self.world = "lobby" self.roomName = roomName self.closed = False self.private = private self.playing = False self.autoStartTimer = None self.startTimer = int() self.votes = int() self.winners = int() self.lastId = -1 self.players = list() self.goldFlowerTaken = bool() def getNextPlayerId(self): self.lastId += 1 return self.lastId def addPlayer(self, player): self.players.append(player) return self.getNextPlayerId() def removePlayer(self, player): if player not in self.players: return self.players.remove(player) if len(self.players) == 0: try: self.autoStartTimer.cancel() except: pass self.server.removeMatch(self) return if not player.dead and not player.win: # Don't kill podium players self.broadBin(0x11, Buffer().writeInt16(player.id)) # KILL_PLAYER_OBJECT self.broadPlayerList() if player.voted: self.votes -= 1 elif self.server.enableVoteStart and not self.playing and self.votes >= len(self.players) * self.server.voteRateToStart: self.start() def getPlayer(self, pid): for player in self.players: if player.id == pid: return player return None def getWinners(self): self.winners += 1 return self.winners def broadJSON(self, j): for player in self.players: if not player.loaded: continue player.sendJSON(j) def broadBin(self, code, buff, ignore = None): buff = buff.toBytes() if isinstance(buff, Buffer) else buff for player in self.players: if not player.loaded or (ignore is not None and player.id == ignore): continue player.sendBin(code, buff) def broadLoadWorld(self): for player in self.players: player.loadWorld(self.world, self.customLevelData) def broadStartTimer(self, time): self.startTimer = time * 30 for player in self.players: if not player.loaded: continue player.setStartTimer(self.startTimer) if time > 0: reactor.callLater(1, self.broadStartTimer, time - 1) else: self.closed = True def broadPlayerList(self): if self.closed: return # Don't broad player list when in main game data = {"packets": [ {"players": self.getPlayersData(), "type": "g12"} ], "type": "s01"} for player in self.players: if not player.loaded: continue player.sendJSON(data) def getPlayersData(self): playersData = [] for player in self.players: # We need to include even not loaded players as the remaining player count # only updates on the start timer screen playersData.append(player.getSimpleData()) return playersData def broadPlayerUpdate(self, player, pktData): data = Buffer().writeInt16(player.id).write(pktData).toBytes() for p in self.players: if not p.loaded or p.id == player.id: continue if not p.win and (p.level != player.level or p.zone != player.zone): continue p.sendBin(0x12, data) def onPlayerEnter(self, player): pass def onPlayerReady(self, player): if (not self.private or self.roomName != "") and not self.playing: # Ensure that the game starts even with fewer players if self.autoStartTimer is not None: try: self.autoStartTimer.reset(self.server.autoStartTime) except: pass else: self.autoStartTimer = reactor.callLater(self.server.autoStartTime, self.start, True) if self.world == "lobby" and self.goldFlowerTaken: self.broadBin(0x20, Buffer().writeInt16(-1).writeInt8(0).writeInt8(0).writeInt32(458761).writeInt8(0)) if self.world == "lobby" or not player.lobbier or self.closed: for p in self.players: if not p.loaded or p == player: continue player.sendBin(0x10, p.serializePlayerObject()) if self.startTimer != 0 or self.closed: player.setStartTimer(self.startTimer) self.broadPlayerList() if not self.playing: if len(self.players) >= self.server.playerCap: self.start(True) # This is needed because if the votes is sufficient to start but there isn't sufficient players, # when someone enters the game, it can make it possible to start the game. elif self.server.enableVoteStart and self.votes >= len(self.players) * self.server.voteRateToStart: self.start() def onPlayerWarp(self, player, level, zone): for p in self.players: if not p.loaded or p.lastUpdatePkt is None or p.id == player.id: continue # Tell fellows that the player warped if p.level == player.level and p.zone == player.zone: p.sendBin(0x12, Buffer().writeInt16(player.id).writeInt8(level).writeInt8(zone).write(player.lastUpdatePkt[2:])) continue elif p.level != level or p.zone != zone: continue player.sendBin(0x12, Buffer().writeInt16(p.id).write(p.lastUpdatePkt)) def voteStart(self): self.votes += 1 if self.server.enableVoteStart and not self.playing and self.votes >= len(self.players) * self.server.voteRateToStart: self.start() def start(self, forced = False): if self.playing or (not forced and len(self.players) < (1 if self.private and self.roomName == "" else self.server.playerMin)): # We need at-least 10 players to start return self.playing = True try: self.autoStartTimer.cancel() except: pass self.world = self.forceLevel if self.forceLevel != "" else self.server.getRandomWorld() if not self.private: reactor.callLater(3, self.broadLoadWorld) reactor.callLater(4, self.broadStartTimer, self.server.startTimer) else: self.broadLoadWorld() reactor.callLater(1, self.broadStartTimer, self.server.startTimer) def validateCustomLevel(self, level): lk = json.loads(level) jsonschema.validate(instance=lk, schema=levelJsonSchema) def selectLevel(self, level): if level == "" or level in self.server.worlds: self.forceLevel = level self.broadLevelSelect() def broadLevelSelect(self): data = {"type":"gsl", "name":self.forceLevel, "status":"update", "message":""} for player in self.players: player.sendJSON(data) def selectCustomLevel(self, level): self.validateCustomLevel(level) self.forceLevel = "custom" self.customLevelData = level self.broadLevelSelect()
0
0.796233
1
0.796233
game-dev
MEDIA
0.526465
game-dev,networking
0.903947
1
0.903947
opentomb/OpenTomb
4,411
extern/bullet/BulletCollision/Gimpact/btClipPolygon.h
#ifndef BT_CLIP_POLYGON_H_INCLUDED #define BT_CLIP_POLYGON_H_INCLUDED /*! \file btClipPolygon.h \author Francisco Leon Najera */ /* This source file is part of GIMPACT Library. For the latest info, see http://gimpact.sourceforge.net/ Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371. email: projectileman@yahoo.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "LinearMath/btTransform.h" #include "LinearMath/btGeometryUtil.h" SIMD_FORCE_INLINE btScalar bt_distance_point_plane(const btVector4 & plane,const btVector3 &point) { return point.dot(plane) - plane[3]; } /*! Vector blending Takes two vectors a, b, blends them together*/ SIMD_FORCE_INLINE void bt_vec_blend(btVector3 &vr, const btVector3 &va,const btVector3 &vb, btScalar blend_factor) { vr = (1-blend_factor)*va + blend_factor*vb; } //! This function calcs the distance from a 3D plane SIMD_FORCE_INLINE void bt_plane_clip_polygon_collect( const btVector3 & point0, const btVector3 & point1, btScalar dist0, btScalar dist1, btVector3 * clipped, int & clipped_count) { bool _prevclassif = (dist0>SIMD_EPSILON); bool _classif = (dist1>SIMD_EPSILON); if(_classif!=_prevclassif) { btScalar blendfactor = -dist0/(dist1-dist0); bt_vec_blend(clipped[clipped_count],point0,point1,blendfactor); clipped_count++; } if(!_classif) { clipped[clipped_count] = point1; clipped_count++; } } //! Clips a polygon by a plane /*! *\return The count of the clipped counts */ SIMD_FORCE_INLINE int bt_plane_clip_polygon( const btVector4 & plane, const btVector3 * polygon_points, int polygon_point_count, btVector3 * clipped) { int clipped_count = 0; //clip first point btScalar firstdist = bt_distance_point_plane(plane,polygon_points[0]);; if(!(firstdist>SIMD_EPSILON)) { clipped[clipped_count] = polygon_points[0]; clipped_count++; } btScalar olddist = firstdist; for(int i=1;i<polygon_point_count;i++) { btScalar dist = bt_distance_point_plane(plane,polygon_points[i]); bt_plane_clip_polygon_collect( polygon_points[i-1],polygon_points[i], olddist, dist, clipped, clipped_count); olddist = dist; } //RETURN TO FIRST point bt_plane_clip_polygon_collect( polygon_points[polygon_point_count-1],polygon_points[0], olddist, firstdist, clipped, clipped_count); return clipped_count; } //! Clips a polygon by a plane /*! *\param clipped must be an array of 16 points. *\return The count of the clipped counts */ SIMD_FORCE_INLINE int bt_plane_clip_triangle( const btVector4 & plane, const btVector3 & point0, const btVector3 & point1, const btVector3& point2, btVector3 * clipped // an allocated array of 16 points at least ) { int clipped_count = 0; //clip first point0 btScalar firstdist = bt_distance_point_plane(plane,point0);; if(!(firstdist>SIMD_EPSILON)) { clipped[clipped_count] = point0; clipped_count++; } // point 1 btScalar olddist = firstdist; btScalar dist = bt_distance_point_plane(plane,point1); bt_plane_clip_polygon_collect( point0,point1, olddist, dist, clipped, clipped_count); olddist = dist; // point 2 dist = bt_distance_point_plane(plane,point2); bt_plane_clip_polygon_collect( point1,point2, olddist, dist, clipped, clipped_count); olddist = dist; //RETURN TO FIRST point0 bt_plane_clip_polygon_collect( point2,point0, olddist, firstdist, clipped, clipped_count); return clipped_count; } #endif // GIM_TRI_COLLISION_H_INCLUDED
0
0.824084
1
0.824084
game-dev
MEDIA
0.963944
game-dev
0.980029
1
0.980029
icepeng/loa-calc
3,051
src/app/dps/models/stat.ts
export interface InternalStat { weaponAtt: number; mainStat: number; pmainStat: number; crit: number; special: number; swift: number; } export interface Stat { crit: number; critDamage: number; critDamageHead: number; critDamageBack: number; pdamage: number; pdamageIndep: number; pdamageIndepHead: number; pdamageIndepBack: number; armorIgnore: number; pattCommon: number; pattJob: number; pattIndep: number; att: number; movingSpeed: number; } export function addPdamageIndep(a: number, b: number): number { return a + b + a * b * 0.01; } export function subPdamageIndep(a: number, b: number): number { return ((100 + a) / (100 + b)) * 100 - 100; } export function InternalStat(obj: Partial<InternalStat> = {}): InternalStat { return { weaponAtt: 0, mainStat: 0, pmainStat: 0, crit: 0, special: 0, swift: 0, ...obj, }; } export function Stat(obj: Partial<Stat> = {}): Stat { return { crit: 0, critDamage: 0, critDamageHead: 0, critDamageBack: 0, pdamage: 0, pdamageIndep: 0, pdamageIndepHead: 0, pdamageIndepBack: 0, armorIgnore: 0, pattCommon: 0, pattJob: 0, pattIndep: 0, att: 0, movingSpeed: 0, ...obj, }; } export function translateStat(internalStat: InternalStat): Stat { return Stat({ crit: internalStat.crit * 0.03577, critDamage: 200, att: Math.sqrt( (internalStat.weaponAtt * ((internalStat.mainStat * (100 + internalStat.pmainStat)) / 100)) / 6 ), movingSpeed: internalStat.swift * 0.01717, }); } export function addInternalStat( a: InternalStat, b: InternalStat ): InternalStat { return { weaponAtt: a.weaponAtt + b.weaponAtt, mainStat: a.mainStat + b.mainStat, pmainStat: a.pmainStat + b.pmainStat, crit: a.crit + b.crit, special: a.special + b.special, swift: a.swift + b.swift, }; } export function addStat(a: Stat, b: Stat): Stat { return { crit: a.crit + b.crit, critDamage: a.critDamage + b.critDamage, critDamageHead: a.critDamageHead + b.critDamageHead, critDamageBack: a.critDamageBack + b.critDamageBack, pdamage: a.pdamage + b.pdamage, pdamageIndep: addPdamageIndep(a.pdamageIndep, b.pdamageIndep), pdamageIndepHead: addPdamageIndep(a.pdamageIndepHead, b.pdamageIndepHead), pdamageIndepBack: addPdamageIndep(a.pdamageIndepBack, b.pdamageIndepBack), armorIgnore: 100 - 0.01 * ((100 - a.armorIgnore) * (100 - b.armorIgnore)), pattCommon: a.pattCommon + b.pattCommon, pattJob: a.pattJob + b.pattJob, pattIndep: addPdamageIndep(a.pattIndep, b.pattIndep), att: a.att + b.att, movingSpeed: a.movingSpeed + b.movingSpeed, }; } export function getTotalAtt(stat: Stat): number { const patt = addPdamageIndep( addPdamageIndep(stat.pattCommon, stat.pattJob), stat.pattIndep ); return stat.att * (1 + patt / 100); } export function getMultiplier(stat: Stat): number { return (1 + stat.pdamageIndep / 100) * (1 + stat.pdamage / 100); }
0
0.606754
1
0.606754
game-dev
MEDIA
0.73447
game-dev
0.670512
1
0.670512
fholger/openvr_fsr
1,716
samples/unity_keyboard_sample/Assets/SteamVR/Extras/SteamVR_TestThrow.cs
using UnityEngine; using System.Collections; [RequireComponent(typeof(SteamVR_TrackedObject))] public class SteamVR_TestThrow : MonoBehaviour { public GameObject prefab; public Rigidbody attachPoint; SteamVR_TrackedObject trackedObj; FixedJoint joint; void Awake() { trackedObj = GetComponent<SteamVR_TrackedObject>(); } void FixedUpdate() { var device = SteamVR_Controller.Input((int)trackedObj.index); if (joint == null && device.GetTouchDown(SteamVR_Controller.ButtonMask.Trigger)) { var go = GameObject.Instantiate(prefab); go.transform.position = attachPoint.transform.position; joint = go.AddComponent<FixedJoint>(); joint.connectedBody = attachPoint; } else if (joint != null && device.GetTouchUp(SteamVR_Controller.ButtonMask.Trigger)) { var go = joint.gameObject; var rigidbody = go.GetComponent<Rigidbody>(); Object.DestroyImmediate(joint); joint = null; Object.Destroy(go, 15.0f); // We should probably apply the offset between trackedObj.transform.position // and device.transform.pos to insert into the physics sim at the correct // location, however, we would then want to predict ahead the visual representation // by the same amount we are predicting our render poses. var origin = trackedObj.origin ? trackedObj.origin : trackedObj.transform.parent; if (origin != null) { rigidbody.velocity = origin.TransformVector(device.velocity); rigidbody.angularVelocity = origin.TransformVector(device.angularVelocity); } else { rigidbody.velocity = device.velocity; rigidbody.angularVelocity = device.angularVelocity; } rigidbody.maxAngularVelocity = rigidbody.angularVelocity.magnitude; } } }
0
0.830982
1
0.830982
game-dev
MEDIA
0.984972
game-dev
0.744732
1
0.744732
alttester/AltTester-Unity-SDK
5,392
Assets/AltTester/Runtime/Commands/ObjectCommands/AltCallComponentMethodForObjectCommand.cs
/* Copyright(C) 2025 Altom Consulting This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ using System; using System.Linq; using System.Reflection; using AltTester.AltTesterSDK.Driver; using AltTester.AltTesterSDK.Driver.Commands; namespace AltTester.AltTesterUnitySDK.Commands { class AltCallComponentMethodForObjectCommand : AltReflectionMethodsCommand<AltCallComponentMethodForObjectParams, object> { public AltCallComponentMethodForObjectCommand(AltCallComponentMethodForObjectParams cmdParams) : base(cmdParams) { } public override object Execute() { if (CommandParams.typeOfParameters != null && CommandParams.typeOfParameters.Length != 0 && CommandParams.parameters.Length != CommandParams.typeOfParameters.Length) { throw new InvalidParameterTypeException("Number of parameters different than number of types of parameters"); } System.Reflection.MethodInfo methodInfoToBeInvoked; var componentType = GetType(CommandParams.component, CommandParams.assembly); var methodPathSplited = CommandParams.method.Split('.'); string methodName; object instance; if (CommandParams.altObject != null) { UnityEngine.GameObject gameObject = AltRunner.GetGameObject(CommandParams.altObject.id); if (componentType == typeof(UnityEngine.GameObject)) { instance = gameObject; if (instance == null) { throw new ObjectWasNotFoundException("Object with name=" + CommandParams.altObject.name + " and id=" + CommandParams.altObject.id + " was not found"); } } else { instance = gameObject.GetComponent(componentType); if (instance == null) throw new ComponentNotFoundException(); } instance = GetInstance(instance, methodPathSplited); } else { instance = GetInstance(null, methodPathSplited, componentType); } if (methodPathSplited.Length > 1) { methodName = methodPathSplited[methodPathSplited.Length - 1]; } else { methodName = CommandParams.method; } System.Reflection.MethodInfo[] methodInfos; if (instance == null) { methodInfos = GetMethodInfoWithSpecificName(componentType, methodName); } else { methodInfos = GetMethodInfoWithSpecificName(instance.GetType(), methodName); } methodInfoToBeInvoked = GetMethodToBeInvoked(methodInfos); return InvokeMethod(methodInfoToBeInvoked, CommandParams.parameters, instance); } private MethodInfo GetMethodToBeInvoked(MethodInfo[] methodInfos) { var parameterTypes = getParameterTypes(CommandParams.typeOfParameters); foreach (var methodInfo in methodInfos.Where(method => method.GetParameters().Length == CommandParams.parameters.Length)) { var methodParameters = methodInfo.GetParameters(); bool methodSignatureMatches = true; for (int counter = 0; counter < parameterTypes.Length && counter < methodParameters.Length; counter++) { if (methodParameters[counter].ParameterType != parameterTypes[counter]) methodSignatureMatches = false; } if (methodSignatureMatches) return methodInfo; } var errorMessage = "No method found with " + CommandParams.parameters.Length + " parameters matching signature: " + CommandParams.method + "(" + CommandParams.typeOfParameters + ")"; throw new MethodWithGivenParametersNotFoundException(errorMessage); } private Type[] getParameterTypes(string[] typeOfParameters) { if (typeOfParameters == null || typeOfParameters.Length == 0) return new Type[0]; var types = new Type[typeOfParameters.Length]; for (int i = 0; i < typeOfParameters.Length; i++) { var type = Type.GetType(typeOfParameters[i]); if (type == null) throw new InvalidParameterTypeException("Parameter type " + typeOfParameters[i] + " not found."); types[i] = type; } return types; } } }
0
0.921269
1
0.921269
game-dev
MEDIA
0.486165
game-dev
0.921165
1
0.921165
smogon/pokemon-showdown
1,588
test/sim/moves/toxicspikes.js
'use strict'; const assert = require('./../../assert'); const common = require('./../../common'); let battle; describe('Toxic Spikes', () => { afterEach(() => { battle.destroy(); }); it('should be absorbed by grounded Poison types', () => { battle = common.createBattle([[ { species: 'Muk', moves: ['toxicspikes', 'sleeptalk'] }, ], [ { species: 'Glalie', moves: ['sleeptalk'] }, { species: 'Koffing', ability: 'levitate', moves: ['sleeptalk'] }, { species: 'Qwilfish', item: 'heavydutyboots', moves: ['sleeptalk'] }, ]]); battle.makeChoices(); assert(battle.p2.sideConditions.toxicspikes); battle.makeChoices('move sleeptalk', 'switch 2'); assert(battle.p2.sideConditions.toxicspikes, 'Levitate Koffing should not have absorbed Toxic Spikes'); battle.makeChoices('move sleeptalk', 'switch 3'); assert.false(battle.p2.sideConditions.toxicspikes, 'Heavy Duty Boots Qwilfish should have absorbed Toxic Spikes'); }); it('should be disabled immediately when absorbed', () => { battle = common.createBattle({ gameType: 'doubles' }, [[ { species: 'Muk', moves: ['toxicspikes', 'sleeptalk'] }, { species: 'Cufant', moves: ['sleeptalk'] }, ], [ { species: 'Glalie', moves: ['memento'] }, { species: 'Koffing', moves: ['memento'] }, { species: 'Qwilfish', moves: ['sleeptalk'] }, { species: 'Bergmite', moves: ['sleeptalk'] }, ]]); battle.makeChoices(); battle.makeChoices(); assert.false(battle.p2.sideConditions.toxicspikes); assert.false(battle.p2.active[1].status, 'Bergmite should not have been poisoned'); }); });
0
0.793161
1
0.793161
game-dev
MEDIA
0.895306
game-dev,testing-qa
0.580942
1
0.580942
Plugily-Projects/Village_Defense
3,381
src/main/java/plugily/projects/villagedefense/kits/level/LooterKit.java
/* * Village Defense - Protect villagers from hordes of zombies * Copyright (c) 2023 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package plugily.projects.villagedefense.kits.level; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.ItemStack; import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; import plugily.projects.minigamesbox.classic.kits.basekits.LevelKit; import plugily.projects.minigamesbox.classic.utils.helper.ArmorHelper; import plugily.projects.minigamesbox.classic.utils.helper.WeaponHelper; import plugily.projects.minigamesbox.classic.utils.version.xseries.XMaterial; import plugily.projects.villagedefense.creatures.CreatureUtils; import java.util.List; /** * Created by Tom on 21/07/2015. */ public class LooterKit extends LevelKit implements Listener { public LooterKit() { setName(new MessageBuilder("KIT_CONTENT_LOOTER_NAME").asKey().build()); setKey("Looter"); List<String> description = getPlugin().getLanguageManager().getLanguageListFromKey("KIT_CONTENT_LOOTER_DESCRIPTION"); setDescription(description); setLevel(getKitsConfig().getInt("Required-Level.Looter")); getPlugin().getServer().getPluginManager().registerEvents(this, getPlugin()); getPlugin().getKitRegistry().registerKit(this); } @Override public boolean isUnlockedByPlayer(Player player) { return getPlugin().getUserManager().getUser(player).getStatistic("LEVEL") >= getLevel() || player.hasPermission("villagedefense.kit.looter"); } @Override public void giveKitItems(Player player) { player.getInventory().addItem(WeaponHelper.getUnBreakingSword(WeaponHelper.ResourceType.STONE, 10)); ArmorHelper.setColouredArmor(Color.ORANGE, player); player.getInventory().addItem(new ItemStack(XMaterial.COOKED_PORKCHOP.parseMaterial(), 8)); } @Override public Material getMaterial() { return Material.ROTTEN_FLESH; } @Override public void reStock(Player player) { //no restock items for this kit } @EventHandler public void onDeath(EntityDeathEvent event) { org.bukkit.entity.LivingEntity entity = event.getEntity(); if(!(CreatureUtils.isEnemy(entity)) || entity.getKiller() == null) { return; } Player player = entity.getKiller(); if(getPlugin().getArenaRegistry().getArena(player) == null) { return; } if(getPlugin().getUserManager().getUser(player).getKit() instanceof LooterKit) { player.getInventory().addItem(new ItemStack(getMaterial(), 1)); } } }
0
0.909404
1
0.909404
game-dev
MEDIA
0.851705
game-dev
0.877069
1
0.877069
mcclure/bitbucket-backup
5,810
repos/bodyhack/contents/desktop/static_lib/cpVect.h
/* Copyright (c) 2007 Scott Lembcke * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /// Constant for the zero vector. static const cpVect cpvzero = {0.0f,0.0f}; /// Convenience constructor for cpVect structs. static inline cpVect cpv(const cpFloat x, const cpFloat y) { cpVect v = {x, y}; return v; } // non-inlined functions /// Returns the length of v. cpFloat cpvlength(const cpVect v); /// Spherical linearly interpolate between v1 and v2. cpVect cpvslerp(const cpVect v1, const cpVect v2, const cpFloat t); /// Spherical linearly interpolate between v1 towards v2 by no more than angle a radians cpVect cpvslerpconst(const cpVect v1, const cpVect v2, const cpFloat a); /// Returns the unit length vector for the given angle (in radians). cpVect cpvforangle(const cpFloat a); /// Returns the angular direction v is pointing in (in radians). cpFloat cpvtoangle(const cpVect v); /** Returns a string representation of v. Intended mostly for debugging purposes and not production use. @attention The string points to a static local and is reset every time the function is called. If you want to print more than one vector you will have to split up your printing onto separate lines. */ char *cpvstr(const cpVect v); /// Check if two vectors are equal. (Be careful when comparing floating point numbers!) static inline cpBool cpveql(const cpVect v1, const cpVect v2) { return (v1.x == v2.x && v1.y == v2.y); } /// Add two vectors static inline cpVect cpvadd(const cpVect v1, const cpVect v2) { return cpv(v1.x + v2.x, v1.y + v2.y); } /// Negate a vector. static inline cpVect cpvneg(const cpVect v) { return cpv(-v.x, -v.y); } /// Subtract two vectors. static inline cpVect cpvsub(const cpVect v1, const cpVect v2) { return cpv(v1.x - v2.x, v1.y - v2.y); } /// Scalar multiplication. static inline cpVect cpvmult(const cpVect v, const cpFloat s) { return cpv(v.x*s, v.y*s); } /// Vector dot product. static inline cpFloat cpvdot(const cpVect v1, const cpVect v2) { return v1.x*v2.x + v1.y*v2.y; } /** 2D vector cross product analog. The cross product of 2D vectors results in a 3D vector with only a z component. This function returns the magnitude of the z value. */ static inline cpFloat cpvcross(const cpVect v1, const cpVect v2) { return v1.x*v2.y - v1.y*v2.x; } /// Returns a perpendicular vector. (90 degree rotation) static inline cpVect cpvperp(const cpVect v) { return cpv(-v.y, v.x); } /// Returns a perpendicular vector. (-90 degree rotation) static inline cpVect cpvrperp(const cpVect v) { return cpv(v.y, -v.x); } /// Returns the vector projection of v1 onto v2. static inline cpVect cpvproject(const cpVect v1, const cpVect v2) { return cpvmult(v2, cpvdot(v1, v2)/cpvdot(v2, v2)); } /// Uses complex number multiplication to rotate v1 by v2. Scaling will occur if v1 is not a unit vector. static inline cpVect cpvrotate(const cpVect v1, const cpVect v2) { return cpv(v1.x*v2.x - v1.y*v2.y, v1.x*v2.y + v1.y*v2.x); } /// Inverse of cpvrotate(). static inline cpVect cpvunrotate(const cpVect v1, const cpVect v2) { return cpv(v1.x*v2.x + v1.y*v2.y, v1.y*v2.x - v1.x*v2.y); } /// Returns the squared length of v. Faster than cpvlength() when you only need to compare lengths. static inline cpFloat cpvlengthsq(const cpVect v) { return cpvdot(v, v); } /// Linearly interpolate between v1 and v2. static inline cpVect cpvlerp(const cpVect v1, const cpVect v2, const cpFloat t) { return cpvadd(cpvmult(v1, 1.0f - t), cpvmult(v2, t)); } /// Returns a normalized copy of v. static inline cpVect cpvnormalize(const cpVect v) { return cpvmult(v, 1.0f/cpvlength(v)); } /// Returns a normalized copy of v or cpvzero if v was already cpvzero. Protects against divide by zero errors. static inline cpVect cpvnormalize_safe(const cpVect v) { return (v.x == 0.0f && v.y == 0.0f ? cpvzero : cpvnormalize(v)); } /// Clamp v to length len. static inline cpVect cpvclamp(const cpVect v, const cpFloat len) { return (cpvdot(v,v) > len*len) ? cpvmult(cpvnormalize(v), len) : v; } /// Linearly interpolate between v1 towards v2 by distance d. static inline cpVect cpvlerpconst(cpVect v1, cpVect v2, cpFloat d) { return cpvadd(v1, cpvclamp(cpvsub(v2, v1), d)); } /// Returns the distance between v1 and v2. static inline cpFloat cpvdist(const cpVect v1, const cpVect v2) { return cpvlength(cpvsub(v1, v2)); } /// Returns the squared distance between v1 and v2. Faster than cpvdist() when you only need to compare distances. static inline cpFloat cpvdistsq(const cpVect v1, const cpVect v2) { return cpvlengthsq(cpvsub(v1, v2)); } /// Returns true if the distance between v1 and v2 is less than dist. static inline cpBool cpvnear(const cpVect v1, const cpVect v2, const cpFloat dist) { return cpvdistsq(v1, v2) < dist*dist; }
0
0.712642
1
0.712642
game-dev
MEDIA
0.769742
game-dev
0.798138
1
0.798138
goonstation/goonstation-2016
30,051
code/datums/chemistry/Reagents-Drugs.dm
//Contains wacky space drugs datum reagent drug/ name = "some drug" drug/bathsalts name = "bath salts" id = "bathsalts" description = "Sometimes packaged as a refreshing bathwater additive, these crystals are definitely not for human consumption." reagent_state = SOLID fluid_r = 250 fluid_g = 250 fluid_b = 250 transparency = 100 addiction_prob = 80 overdose = 20 depletion_rate = 0.6 var/remove_buff = 0 pooled() ..() remove_buff = 0 on_add() if(istype(holder) && istype(holder.my_atom) && hascall(holder.my_atom,"add_stam_mod_regen")) remove_buff = holder.my_atom:add_stam_mod_regen("consumable_good", 3) return on_remove() if(remove_buff) if(istype(holder) && istype(holder.my_atom) && hascall(holder.my_atom,"remove_stam_mod_regen")) holder.my_atom:remove_stam_mod_regen("consumable_good") return on_mob_life(var/mob/M) // commence bad times if(!M) M = holder.my_atom if(ishuman(M)) var/mob/living/carbon/human/K = M if (K.sims) K.sims.affectMotive("energy", 2) K.sims.affectMotive("fun", 1) K.sims.affectMotive("bladder", -0.5) K.sims.affectMotive("hunger", -1) K.sims.affectMotive("thirst", -2) var/mob/living/carbon/human/H = M var/check = rand(0,100) if (istype(H)) if (check < 8 && H.cust_two_state != "tramp") // M.is_hobo = very yes H.cust_two_state = "tramp" H.set_face_icon_dirty() boutput(M, "<span style=\"color:red\"><b>You feel gruff!</b></span>") spawn(3) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> has a wild look in their eyes!</span>") if(check < 60) if(H.paralysis) H.paralysis = 0 if(H.stunned) H.stunned = 0 if(H.weakened) H.weakened = 0 if(check < 30) H.emote(pick("twitch", "twitch_s", "scream", "drool", "grumble", "mumble")) M.druggy = max(M.druggy, 15) if(check < 20) M.change_misstep_chance(10) // a really shitty form of traitor stimulants - you'll be tough to take down but nearly uncontrollable anyways and you won't heal the way stims do if(check < 8) M.reagents.add_reagent(pick("methamphetamine", "crank", "neurotoxin"), rand(1,5)) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> scratches at something under their skin!</span>") random_brute_damage(M, 5) else if (check < 16) switch(rand(1,2)) if(1) if(prob(20)) fake_attackEx(M, 'icons/misc/critter.dmi', "death", "death") boutput(M, "<span style=\"color:red\"><b>OH GOD LOOK OUT!!!</b>!</span>") M.emote("scream") M.playsound_local(M.loc, 'sound/effects/bell.ogg', 50, 1) else if(prob(50)) fake_attackEx(M, 'icons/misc/critter.dmi', "mimicface", "smiling thing") boutput(M, "<span style=\"color:red\"><b>The smiling thing</b> laughs!</span>") M.playsound_local(M.loc, pick("sound/voice/cluwnelaugh1.ogg", "sound/voice/cluwnelaugh2.ogg", "sound/voice/cluwnelaugh3.ogg"), 50, 1) else M.playsound_local(M.loc, pick('sound/machines/ArtifactEld1.ogg', 'sound/machines/ArtifactEld2.ogg'), 50, 1) boutput(M, "<span style=\"color:red\"><b>You hear something strange behind you...</b></span>") var/ants = rand(1,3) for(var/i = 0, i < ants, i++) fake_attackEx(M, 'icons/effects/genetics.dmi', "epileptic", "stranger") if(2) var/halluc_state = null var/halluc_name = null switch(rand(1,5)) if(1) halluc_state = "husk" halluc_name = pick("dad", "mom") if(2) halluc_state = "fire3" halluc_name = pick("vision of your future", "dad", "mom") if(3) halluc_state = "eaten" halluc_name = pick("???", "bad bad BAD") if(4) halluc_state = "decomp3" halluc_name = pick("result of your poor life decisions", "grampa") if(5) halluc_state = "fire2" halluc_name = pick("mom", "dad", "why are they burning WHY") fake_attackEx(M, 'icons/mob/human.dmi', halluc_state, halluc_name) else if(check < 24) boutput(M, "<span style=\"color:red\"><b>They're coming for you!</b></span>") else if(check < 28) boutput(M, "<span style=\"color:red\"><b>THEY'RE GONNA GET YOU!</b></span>") ..(M) return reaction_mob(var/mob/M, var/method=TOUCH, var/volume) if(method == INGEST) boutput(M, "<span style=\"color:red\"><font face='[pick("Curlz MT", "Comic Sans MS")]' size='[rand(4,6)]'>You feel FUCKED UP!!!!!!</font></span>") M.playsound_local(M.loc, 'sound/effects/heartbeat.ogg', 50, 1) M.emote("faint") //var/mob/living/carbon/human/H = M //if (istype(H)) M.irradiate(5,1) M.take_toxin_damage(5) M.take_brain_damage(10) M.updatehealth() else boutput(M, "<span style=\"color:blue\">You feel a bit more salty than usual.</span>") return do_overdose(var/severity, var/mob/M) var/effect = ..(severity, M) if (severity == 1) if (effect <= 2) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> flails around like a lunatic!</span>") M.change_misstep_chance(25) M.make_jittery(10) M.emote("scream") M.reagents.add_reagent("salts1", 5) else if (effect <= 4) M.visible_message("<span style=\"color:red\"><b>[M.name]'s</b> eyes dilate!</span>") M.emote("twitch_s") M.take_toxin_damage(2) M.take_brain_damage(1) M.updatehealth() M.stunned += 3 M.change_eye_blurry(7, 7) M.reagents.add_reagent("salts1", 5) else if (effect <= 7) M.emote("faint") M.reagents.add_reagent("salts1", 5) else if (severity == 2) if (effect <= 2) M.visible_message("<span style=\"color:red\"><b>[M.name]'s</b> eyes dilate!</span>") M.take_toxin_damage(2) M.take_brain_damage(1) M.updatehealth() M.stunned += 3 M.change_eye_blurry(7, 7) M.reagents.add_reagent("salts1", 5) else if (effect <= 4) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> convulses violently and falls to the floor!</span>") M.make_jittery(50) M.take_toxin_damage(2) M.take_brain_damage(1) M.updatehealth() M.weakened += 8 M.emote("gasp") M.reagents.add_reagent("salts1", 5) else if (effect <= 7) M.emote("scream") M.visible_message("<span style=\"color:red\"><b>[M.name]</b> tears at their own skin!</span>") random_brute_damage(M, 5) M.reagents.add_reagent("salts1", 5) M.emote("twitch") drug/jenkem name = "jenkem" id = "jenkem" description = "Jenkem is a prison drug made from fermenting feces in a solution of urine. Extremely disgusting." reagent_state = LIQUID fluid_r = 100 fluid_g = 70 fluid_b = 0 transparency = 255 addiction_prob = 30 value = 2 // 1 1 :I on_mob_life(var/mob/M) if(!M) M = holder.my_atom if(ishuman(M)) var/mob/living/carbon/human/H = M if (H.sims) H.sims.affectMotive("energy", -1) H.sims.affectMotive("fun", 3) H.sims.affectMotive("bladder", -0.5) H.sims.affectMotive("thirst", -2) M.make_dizzy(5) if(prob(10)) M.emote(pick("twitch","drool","moan")) M.take_toxin_damage(1) M.updatehealth() ..(M) return drug/crank name = "crank" // sort of a shitty version of methamphetamine that can be made by assistants id = "crank" description = "A cheap and dirty stimulant drug, commonly used by space biker gangs." reagent_state = SOLID fluid_r = 250 fluid_b = 0 fluid_g = 200 transparency = 40 addiction_prob = 50 overdose = 20 value = 20 // 10 2 1 3 1 heat explosion :v on_mob_life(var/mob/M) if(!M) M = holder.my_atom if(ishuman(M)) var/mob/living/carbon/human/H = M if (H.sims) H.sims.affectMotive("energy", 1) H.sims.affectMotive("fun", 0.25) H.sims.affectMotive("bladder", -0.25) H.sims.affectMotive("hunger", -0.5) H.sims.affectMotive("thirst", -0.5) H.sims.affectMotive("comfort", -0.25) if(M.paralysis) M.paralysis-=2 if(M.stunned) M.stunned-=2 if(M.weakened) M.weakened-=2 if(prob(15)) M.emote(pick("twitch", "twitch_s", "grumble", "laugh")) if(prob(8)) boutput(M, "<span style=\"color:blue\"><b>You feel great!</b></span>") M.reagents.add_reagent("methamphetamine", rand(1,2)) M.emote(pick("laugh", "giggle")) if(prob(6)) boutput(M, "<span style=\"color:blue\"><b>You feel warm.</b></span>") M.bodytemperature += rand(1,10) if(prob(4)) boutput(M, "<span style=\"color:red\"><b>You feel kinda awful!</b></span>") M.take_toxin_damage(1) M.updatehealth() M.make_jittery(30) M.emote(pick("groan", "moan")) ..(M) return do_overdose(var/severity, var/mob/M) var/effect = ..(severity, M) if (severity == 1) if (effect <= 2) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> looks confused!</span>") M.change_misstep_chance(20) M.make_jittery(20) M.emote("scream") else if (effect <= 4) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> is all sweaty!</span>") M.bodytemperature += rand(5,30) M.take_brain_damage(1) M.take_toxin_damage(1) M.updatehealth() M.stunned += 2 else if (effect <= 7) M.make_jittery(30) M.emote("grumble") else if (severity == 2) if (effect <= 2) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> is sweating like a pig!</span>") M.bodytemperature += rand(20,100) M.take_toxin_damage(5) M.updatehealth() M.stunned += 3 else if (effect <= 4) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> starts tweaking the hell out!</span>") M.make_jittery(100) M.take_toxin_damage(2) M.take_brain_damage(8) M.updatehealth() M.weakened += 3 M.change_misstep_chance(25) M.emote("scream") M.reagents.add_reagent("salts1", 5) else if (effect <= 7) M.emote("scream") M.visible_message("<span style=\"color:red\"><b>[M.name]</b> nervously scratches at their skin!</span>") M.make_jittery(10) random_brute_damage(M, 5) M.emote("twitch") drug/LSD name = "lysergic acid diethylamide" id = "LSD" description = "A highly potent hallucinogenic substance. Far out, maaaan." reagent_state = LIQUID fluid_r = 0 fluid_g = 0 fluid_b = 255 transparency = 20 value = 6 // 4 2 on_mob_life(var/mob/M) if(!M) M = holder.my_atom if(ishuman(M)) var/mob/living/carbon/human/H = M if (H.sims) H.sims.affectMotive("fun", 2) H.sims.affectMotive("thirst", -2) M.druggy = max(M.druggy, 15) // TODO. Write awesome hallucination algorithm! // if(M.canmove) step(M, pick(cardinal)) // if(prob(7)) M.emote(pick("twitch","drool","moan","giggle")) if(prob(6)) switch(rand(1,2)) if(1) if(prob(50)) fake_attack(M) else var/monkeys = rand(1,3) for(var/i = 0, i < monkeys, i++) fake_attackEx(M, 'icons/mob/monkey.dmi', "monkey1", "monkey ([rand(1, 1000)])") if(2) var/halluc_state = null var/halluc_name = null switch(rand(1,5)) if(1) halluc_state = "pig" halluc_name = pick("pig", "DAT FUKKEN PIG") if(2) halluc_state = "spider" halluc_name = pick("giant black widow", "queen bitch spider", "OH FUCK A SPIDER") if(3) halluc_state = "dragon" halluc_name = pick("dragon", "Lord Cinderbottom", "SOME FUKKEN LIZARD THAT BREATHES FIRE") if(4) halluc_state = "slime" halluc_name = pick("red slime", "some gooey thing", "ANGRY CRIMSON POO") if(5) halluc_state = "shambler" halluc_name = pick("shambler", "strange creature", "OH GOD WHAT THE FUCK IS THAT THING?") fake_attackEx(M, 'icons/effects/hallucinations.dmi', halluc_state, halluc_name) if(prob(9)) M.playsound_local(M.loc, pick("explosion", "punch", 'sound/vox/poo-vox.ogg', "clownstep", 'sound/weapons/armbomb.ogg', 'sound/weapons/Gunshot.ogg'), 50, 1) if(prob(8)) boutput(M, "<b>You hear a voice in your head... <i>[pick(loggedsay)]</i></b>") ..(M) return reaction_mob(var/mob/M, var/method=TOUCH, var/volume) if(method == INGEST) boutput(M, "<span style=\"color:red\"><font face='[pick("Arial", "Georgia", "Impact", "Mucida Console", "Symbol", "Tahoma", "Times New Roman", "Verdana")]' size='[rand(3,6)]'>Holy shit, you start tripping balls!</font></span>") return drug/space_drugs name = "space drugs" id = "space_drugs" description = "An illegal chemical compound used as a cheap drug." reagent_state = LIQUID fluid_r = 200 fluid_g = 185 fluid_b = 230 addiction_prob = 65 depletion_rate = 0.2 value = 3 // 1c + 1c + 1c reaction_temperature(exposed_temperature, exposed_volume) var/myvol = volume if(exposed_temperature > T0C + 400) //Turns into a neurotoxin. volume = 0 holder.add_reagent("neurotoxin", myvol, null) return on_mob_life(var/mob/M) if(!M) M = holder.my_atom if(ishuman(M)) var/mob/living/carbon/human/H = M if (H.sims) H.sims.affectMotive("fun", 1) H.sims.affectMotive("thirst", -1) M.druggy = max(M.druggy, 15) if(M.canmove && isturf(M.loc)) step(M, pick(cardinal)) if(prob(7)) M.emote(pick("twitch","drool","moan","giggle")) ..(M) return drug/THC name = "tetrahydrocannabinol" id = "THC" description = "A mild psychoactive chemical extracted from the cannabis plant." reagent_state = LIQUID fluid_r = 0 fluid_g = 225 fluid_b = 0 transparency = 200 value = 3 on_mob_life(var/mob/M) if(!M) M = holder.my_atom if(ishuman(M)) var/mob/living/carbon/human/H = M if (H.sims) H.sims.affectMotive("fun", 2.5) H.sims.affectMotive("hunger", -2) H.sims.affectMotive("thirst", -2) H.sims.affectMotive("comfort", 2.5) M.stuttering += rand(0,2) if(prob(5)) M.emote(pick("laugh","giggle","smile")) if(prob(5)) boutput(M, "[pick("You feel hungry.","Your stomach rumbles.","You feel cold.","You feel warm.")]") if(prob(4)) M.change_misstep_chance(10) if (holder.get_reagent_amount(src.id) >= 50 && prob(25)) if(prob(10)) M.drowsyness = 10 ..(M) return drug/nicotine name = "nicotine" id = "nicotine" description = "A highly addictive stimulant extracted from the tobacco plant." reagent_state = LIQUID fluid_r = 0 fluid_g = 0 fluid_b = 0 transparency = 190 addiction_prob = 70 overdose = 35 // raise if too low - trying to aim for one sleepypen load being problematic, two being deadlyish //var/counter = 1 //note that nicotine is also horribly poisonous in concentrated form IRM - could be used as a poor-man's toxin? //just comment that out if you don't think it's any good. // Gonna try this out. Not good for you but won't horribly maim you from taking a quick puff of a cigarette - ISN var/remove_buff = 0 value = 3 pooled() ..() remove_buff = 0 on_add() if(istype(holder) && istype(holder.my_atom) && hascall(holder.my_atom,"add_stam_mod_regen")) remove_buff = holder.my_atom:add_stam_mod_regen("consumable_good", 1) return on_remove() if(remove_buff) if(istype(holder) && istype(holder.my_atom) && hascall(holder.my_atom,"remove_stam_mod_regen")) holder.my_atom:remove_stam_mod_regen("consumable_good") return on_mob_life(var/mob/M) if(ishuman(M)) var/mob/living/carbon/human/H = M if (H.sims) H.sims.affectMotive("fun", 0.2) if(prob(50)) M.make_jittery(5) if(M.paralysis) M.paralysis-- if(M.stunned) M.stunned-- if(M.weakened) M.weakened-- if(src.volume > src.overdose) M.take_toxin_damage(1) M.updatehealth() ..(M) //cogwerks - improved nicotine poisoning? do_overdose(var/severity, var/mob/M) var/effect = ..(severity, M) if (severity == 1) if (effect <= 2) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> looks nervous!</span>") M.change_misstep_chance(15) M.take_toxin_damage(2) M.make_jittery(10) M.emote("twitch") else if (effect <= 4) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> is all sweaty!</span>") M.bodytemperature += rand(15,30) M.take_toxin_damage(3) M.updatehealth() else if (effect <= 7) M.take_toxin_damage(4) M.updatehealth() M.emote("twitch_v") M.make_jittery(10) else if (severity == 2) if (effect <= 2) M.emote("gasp") boutput(M, "<span style=\"color:red\"><b>You can't breathe!</b></span>") M.take_oxygen_deprivation(15) M.take_toxin_damage(3) M.updatehealth() M.stunned++ else if (effect <= 4) boutput(M, "<span style=\"color:red\"><b>You feel terrible!</b></span>") M.emote("drool") M.make_jittery(10) M.take_toxin_damage(5) M.updatehealth() M.weakened++ M.change_misstep_chance(33) else if (effect <= 7) M.emote("collapse") boutput(M, "<span style=\"color:red\"><b>Your heart is pounding!</b></span>") M << sound('sound/effects/heartbeat.ogg') M.paralysis = max(M.paralysis, 5) M.make_jittery(30) M.take_toxin_damage(6) M.take_oxygen_deprivation(20) M.updatehealth() drug/psilocybin name = "psilocybin" id = "psilocybin" description = "A powerful hallucinogenic chemical produced by certain mushrooms." reagent_state = LIQUID fluid_r = 255 fluid_g = 230 fluid_b = 200 transparency = 200 value = 3 on_mob_life(var/mob/M) if(!M) M = holder.my_atom if(ishuman(M)) var/mob/living/carbon/human/H = M if (H.sims) H.sims.affectMotive("fun", 1.5) H.sims.affectMotive("thirst", -2) M.druggy = max(M.druggy, 15) if(prob(8)) boutput(M, "<b>You hear a voice in your head... <i>[pick(loggedsay)]</i></b>") if(prob(8)) M.emote(pick("scream","cry","laugh","moan","shiver")) if(prob(3)) switch (rand(1,3)) if(1) boutput(M, "<B>The Emergency Shuttle has docked with the station! You have 3 minutes to board the Emergency Shuttle.</B>") if(2) boutput(M, "<span style=\"color:red\"><b>Restarting world!</b> </span><span style=\"color:blue\">Initiated by Administrator!</span>") spawn(20) M.playsound_local(M.loc, pick('sound/misc/NewRound.ogg', 'sound/misc/NewRound2.ogg', 'sound/misc/NewRound3.ogg', 'sound/misc/NewRound4.ogg'), 50, 1) if(3) switch (rand(1,4)) if(1) boutput(M, "<span style=\"color:red\"><b>Unknown fires the revolver at [M]!</b></span>") M.playsound_local(M.loc, 'sound/weapons/Gunshot.ogg', 50, 1) if(2) boutput(M, "<span style=\"color:red\"><b>[M] has been attacked with the fire extinguisher by Unknown</b></span>") M.playsound_local(M.loc, 'sound/weapons/smash.ogg', 50, 1) if(3) boutput(M, "<span style=\"color:red\"><b>Unknown has punched [M]</b></span>") boutput(M, "<span style=\"color:red\"><b>Unknown has weakened [M]</b></span>") M.weakened += 10 M.playsound_local(M.loc, 'sound/weapons/punch1.ogg', 50, 1) if(4) boutput(M, "<span style=\"color:red\"><b>[M] has been attacked with the taser gun by Unknown</b></span>") boutput(M, "<i>You can almost hear someone talking...</i>") M.paralysis = max(M.paralysis, 3) ..(M) drug/krokodil name = "krokodil" id = "krokodil" description = "A sketchy homemade opiate, often used by disgruntled Cosmonauts." reagent_state = SOLID fluid_r = 0 fluid_g = 100 fluid_b = 180 transparency = 250 addiction_prob = 50 overdose = 20 on_mob_life(var/mob/M) if(!M) M = holder.my_atom if(ishuman(M)) var/mob/living/carbon/human/H = M if (H.sims) H.sims.affectMotive("fun", 5) H.sims.affectMotive("hunger", -3) H.sims.affectMotive("thirst", -3) M.jitteriness -= 40 if(prob(25)) M.take_brain_damage(1) if(prob(15)) M.emote(pick("smile", "grin", "yawn", "laugh", "drool")) if(prob(10)) boutput(M, "<span style=\"color:blue\"><b>You feel pretty chill.</b></span>") M.bodytemperature-- M.emote("smile") if(prob(5)) boutput(M, "<span style=\"color:red\"><b>You feel too chill!</b></span>") M.emote(pick("yawn", "drool")) M.stunned++ M.take_toxin_damage(1) M.take_brain_damage(1) M.bodytemperature -= 20 M.updatehealth() if(prob(2)) boutput(M, "<span style=\"color:red\"><b>Your skin feels all rough and dry.</b></span>") random_brute_damage(M, 2) ..(M) return do_overdose(var/severity, var/mob/M) var/effect = ..(severity, M) if (severity == 1) if (effect <= 2) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> looks dazed!</span>") M.stunned += 3 M.emote("drool") else if (effect <= 4) M.emote("shiver") M.bodytemperature -= 40 else if (effect <= 7) boutput(M, "<span style=\"color:red\"><b>Your skin is cracking and bleeding!</b></span>") random_brute_damage(M, 5) M.take_toxin_damage(2) M.take_brain_damage(1) M.updatehealth() M.emote("cry") else if (severity == 2) if (effect <= 2) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> sways and falls over!</span>") M.take_toxin_damage(3) M.take_brain_damage(3) M.updatehealth() M.weakened += 8 M.emote("faint") else if (effect <= 4) if(ishuman(M)) M.visible_message("<span style=\"color:red\"><b>[M.name]'s</b> skin is rotting away!</span>") random_brute_damage(M, 25) M.emote("scream") M.bioHolder.AddEffect("eaten") //grody. changed line in human.dm to use decomp1 now M.emote("faint") else if (effect <= 7) M.emote("shiver") M.bodytemperature -= 70 drug/catdrugs name = "cat drugs" id = "catdrugs" description = "Uhhh..." reagent_state = LIQUID fluid_r = 200 fluid_g = 200 fluid_b = 0 transparency = 20 on_mob_life(var/mob/M) if(!M) M = holder.my_atom if(ishuman(M)) var/mob/living/carbon/human/H = M if (H.sims) H.sims.affectMotive("fun", 1) H.sims.affectMotive("thirst", -1) M.druggy = max(M.druggy, 15) if(prob(11)) M.visible_message("<span style=\"color:blue\"><b>[M.name]</b> hisses!</span>") playsound(M.loc, "sound/effects/cat_hiss.ogg", 50, 1) if(prob(9)) M.visible_message("<span style=\"color:blue\"><b>[M.name]</b> meows! What the fuck?</span>") playsound(M.loc, "sound/effects/cat.ogg", 50, 1) if(prob(7)) switch(rand(1,2)) if(1) var/ghostcats = rand(1,3) for(var/i = 0, i < ghostcats, i++) fake_attackEx(M, 'icons/misc/critter.dmi', "cat-ghost", "ghost cat") M.playsound_local(M.loc, pick('sound/effects/cat.ogg', 'sound/effects/cat_hiss.ogg'), 50, 1) if(2) var/spazcats = rand(1,3) for(var/i = 0, i < spazcats, i++) fake_attackEx(M, 'icons/misc/critter.dmi', "cat1-spaz", "wild cat") M.playsound_local(M.loc, pick('sound/effects/cat.ogg', 'sound/effects/cat_hiss.ogg'), 50, 1) if(prob(20)) M.playsound_local(M.loc, pick('sound/effects/cat.ogg', 'sound/effects/cat_hiss.ogg'), 50, 1) ..(M) return reaction_mob(var/mob/M, var/method=TOUCH, var/volume) if(method == INGEST) M.playsound_local(M.loc, pick('sound/effects/cat.ogg', 'sound/effects/cat_hiss.ogg'), 50, 1) boutput(M, "<span style=\"color:red\"><font face='[pick("Arial", "Georgia", "Impact", "Mucida Console", "Symbol", "Tahoma", "Times New Roman", "Verdana")]' size='[rand(3,6)]'>Holy shit, you start tripping balls!</font></span>") return drug/triplemeth name = "triple meth" id = "triplemeth" description = "Hot damn ... i don't even ..." reagent_state = SOLID fluid_r = 250 fluid_g = 250 fluid_b = 250 transparency = 220 addiction_prob = 100 overdose = 20 depletion_rate = 0.2 value = 39 // 13c * 3 :v on_add() return on_remove() if(istype(holder) && istype(holder.my_atom) && hascall(holder.my_atom,"remove_stam_mod_regen")) holder.my_atom:remove_stam_mod_regen("triplemeth") if(hascall(holder.my_atom,"removeOverlayComposition")) holder.my_atom:removeOverlayComposition(/datum/overlayComposition/triplemeth) return on_mob_life(var/mob/M) if(!M) M = holder.my_atom if(ishuman(M)) var/mob/living/carbon/human/H = M if (H.sims) H.sims.affectMotive("energy", 5) H.sims.affectMotive("fun", 2.5) H.sims.affectMotive("bladder", -2.5) H.sims.affectMotive("hunger", -3) H.sims.affectMotive("thirst", -3) H.sims.affectMotive("comfort", -2) if(holder.has_reagent("methamphetamine")) return ..(M) //Since is created by a meth overdose, dont react while meth is in their system. if(istype(holder) && istype(holder.my_atom) && hascall(holder.my_atom,"add_stam_mod_regen")) holder.my_atom:add_stam_mod_regen("triplemeth", 1000) if(hascall(holder.my_atom,"addOverlayComposition")) holder.my_atom:addOverlayComposition(/datum/overlayComposition/triplemeth) if(prob(50)) M.emote(pick("twitch","blink_r","shiver")) M.make_jittery(5) M.make_dizzy(5) M.change_misstep_chance(15) M.take_brain_damage(1) if(M.paralysis) M.paralysis = 0 if(M.stunned) M.stunned = 0 if(M.weakened) M.weakened = 0 if(M.sleeping) M.sleeping = 0 ..(M) return do_overdose(var/severity, var/mob/M) var/effect = ..(severity, M) if(holder.has_reagent("methamphetamine")) return ..(M) //Since is created by a meth overdose, dont react while meth is in their system. if (severity == 1) if (effect <= 2) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> can't seem to control their legs!</span>") M.change_misstep_chance(12) M.weakened += 4 else if (effect <= 4) M.visible_message("<span style=\"color:red\"><b>[M.name]'s</b> hands flip out and flail everywhere!</span>") M.drop_item() M.hand = !M.hand M.drop_item() M.hand = !M.hand else if (effect <= 7) M.emote("laugh") else if (severity == 2) if (effect <= 2) M.visible_message("<span style=\"color:red\"><b>[M.name]'s</b> hands flip out and flail everywhere!</span>") M.drop_item() M.hand = !M.hand M.drop_item() M.hand = !M.hand else if (effect <= 4) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> falls to the floor and flails uncontrollably!</span>") M.make_jittery(10) M.weakened += 10 else if (effect <= 7) M.emote("laugh") drug/methamphetamine // // COGWERKS CHEM REVISION PROJECT. marked for revision name = "methamphetamine" id = "methamphetamine" description = "Methamphetamine is a highly effective and dangerous stimulant drug." reagent_state = SOLID fluid_r = 250 fluid_g = 250 fluid_b = 250 transparency = 220 addiction_prob = 60 overdose = 20 depletion_rate = 0.6 value = 13 // 9c + 1c + 1c + 1c + heat var/remove_buff = 0 pooled() ..() remove_buff = 0 on_add() if(istype(holder) && istype(holder.my_atom) && hascall(holder.my_atom,"add_stam_mod_regen")) remove_buff = holder.my_atom:add_stam_mod_regen("consumable_good", 3) return on_remove() if(remove_buff) if(istype(holder) && istype(holder.my_atom) && hascall(holder.my_atom,"remove_stam_mod_regen")) holder.my_atom:remove_stam_mod_regen("consumable_good") if(holder && ismob(holder.my_atom)) holder.del_reagent("triplemeth") return on_mob_life(var/mob/M) if(!M) M = holder.my_atom if(ishuman(M)) var/mob/living/carbon/human/H = M if (H.sims) H.sims.affectMotive("energy", 3) H.sims.affectMotive("fun", 1) H.sims.affectMotive("bladder", -1) H.sims.affectMotive("hunger", -0.5) H.sims.affectMotive("thirst", -1) H.sims.affectMotive("comfort", -0.5) if(prob(5)) M.emote(pick("twitch","blink_r","shiver")) M.make_jittery(5) M.drowsyness = max(M.drowsyness-10, 0) if(M.paralysis) M.paralysis-=2.5 if(M.stunned) M.stunned-=2.5 if(M.weakened) M.weakened-=2.5 if(M.sleeping) M.sleeping = 0 if(prob(50)) M.take_brain_damage(1) ..(M) return do_overdose(var/severity, var/mob/M) var/effect = ..(severity, M) if (severity == 1) if (effect <= 2) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> can't seem to control their legs!</span>") M.change_misstep_chance(20) M.weakened += 4 else if (effect <= 4) M.visible_message("<span style=\"color:red\"><b>[M.name]'s</b> hands flip out and flail everywhere!</span>") M.drop_item() M.hand = !M.hand M.drop_item() M.hand = !M.hand else if (effect <= 7) M.emote("laugh") else if (severity == 2) if(!holder.has_reagent("triplemeth", 10)) holder.add_reagent("triplemeth", 10, null) if (effect <= 2) M.visible_message("<span style=\"color:red\"><b>[M.name]'s</b> hands flip out and flail everywhere!</span>") M.drop_item() M.hand = !M.hand M.drop_item() M.hand = !M.hand else if (effect <= 4) M.visible_message("<span style=\"color:red\"><b>[M.name]</b> falls to the floor and flails uncontrollably!</span>") M.make_jittery(10) M.weakened += 10 else if (effect <= 7) M.emote("laugh")
0
0.965556
1
0.965556
game-dev
MEDIA
0.994365
game-dev
0.987511
1
0.987511
Mqzn/Lotus
6,000
src/main/java/io/github/mqzen/menus/base/MenuContentImpl.java
package io.github.mqzen.menus.base; import com.google.common.collect.Lists; import io.github.mqzen.menus.misc.Capacity; import io.github.mqzen.menus.misc.Slot; import io.github.mqzen.menus.misc.Slots; import io.github.mqzen.menus.misc.button.Button; import io.github.mqzen.menus.misc.button.ButtonCondition; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.stream.Stream; final class MenuContentImpl implements Content { private final Capacity capacity; private final ConcurrentHashMap<Slot, Button> map = new ConcurrentHashMap<>(); public MenuContentImpl(Capacity capacity) { this.capacity = capacity; } @Override public Capacity capacity() { return capacity; } @Override public Optional<Button> getButton(Slot slot) { return Optional.ofNullable(map.get(slot)); } @Override public Optional<Button> getConditionalButton(ButtonCondition condition) { for(Map.Entry<Slot, Button> entry : map.entrySet()) { if(condition.accepts(entry.getKey(), entry.getValue())) { return Optional.ofNullable(entry.getValue()); } } return Optional.empty(); } @Override public int nextEmptySlot(int start) { for (int slot = start; slot < capacity.getTotalSize(); slot++) { if (!getButton(slot).isPresent()) return slot; } return -1; } @Override public ConcurrentHashMap<Slot, Button> getButtonMap() { return map; } @Override public void setButton(Slot slot, Button item) { map.put(slot, item.copy()); } @Override public void removeButton(Slot slot) { map.remove(slot); } @Override public Slots getItemSlots(ItemStack item) { List<Slot> slots = Lists.newArrayList(); for (Map.Entry<Slot, Button> buttonEntry : map.entrySet()) { Slot slot = buttonEntry.getKey(); Button button = buttonEntry.getValue(); if (item.isSimilar(button.getItem())) { slots.add(slot); } } return Slots.of(slots.toArray(new Slot[0])); } @Override public void fill(Button button) { for (int slot = 0; slot < capacity.getTotalSize(); slot++) setButton(slot, button); } @Override public void fillRow(int row, Button button) { fillRow(row, capacity.getColumns()-1, button); } @Override public void fillRow(int row, int endColumn, Button button) { for (int column = 0; column <= endColumn; column++) setButton(row, column, button); } @Override public void fillRow(final int row, Button button, List<Integer> exceptColumns) { for (int column = 0; column < capacity.getColumns(); column++) { if (exceptColumns.contains(column)) continue; setButton(row, column, button); } } @Override public void fillRowRepeatedly(final int row, Button... buttons) { if (buttons.length > capacity.getColumns()) throw new IllegalStateException("Couldn't repeat " + buttons.length + " buttons as it's greater than the column slots (" + capacity.getColumns() + ")"); int column = 0; int buttonIndex = 0; while (column < capacity.getColumns()) { if (buttonIndex >= buttons.length) //repeating buttonIndex = 0; setButton(row, column, buttons[buttonIndex]); column++; buttonIndex++; } } @Override public void fillColumn(final int column, final int endRow, Button button) { for (int row = 0; row <= endRow; row++) setButton(row, column, button); } @Override public void fillColumn(final int column, Button button) { fillColumn(column, capacity.getRows()-1, button); } @Override public void fillColumn(int column, Button button, List<Integer> exceptRows) { for (int row = 0; row < capacity.getRows(); row++) { if (exceptRows.contains(row)) continue; setButton(row, column, button); } } @Override public void fillColumnRepeatedly(final int column, Button... buttons) { if (buttons.length > capacity.getRows()) throw new IllegalStateException("Couldn't repeat " + buttons.length + " buttons as it's greater than the row slots (" + capacity.getRows() + ")"); int row = 0; int buttonIndex = 0; while (row < capacity.getRows()) { if (buttonIndex >= buttons.length) //repeating buttonIndex = 0; setButton(row, column, buttons[buttonIndex]); row++; buttonIndex++; } } @Override public void fillBorder(Button button) { fillRow(0, button); fillColumn(0, button); fillRow(capacity.getRows() - 1, button); fillColumn(capacity.getColumns() - 1, button); } @Override public void fillRectangle(Slot pos1, Slot pos2, Slot pos3, Slot pos4, Button button) { fillRow(pos1.getRow(), pos2.getColumn(), button); fillColumn(pos1.getColumn(), pos3.getRow(), button); fillRow(pos3.getRow(), pos4.getColumn(), button); fillColumn(pos2.getColumn(), pos4.getRow(), button); } @Override public void fillBorderRepeatedly(Button... buttons) { fillRowRepeatedly(0, buttons); fillColumnRepeatedly(0, buttons); fillRowRepeatedly(capacity.getRows() - 1, buttons); fillColumnRepeatedly(capacity.getColumns() - 1, buttons); } @Override public void forEachItem(final BiConsumer<Slot, Button> consumer) { map.forEach(consumer); } @Override public @NotNull Collection<? extends Button> getAllButtons() { return map.values(); } @Override public Content mergeWith(Content other) { map.putAll(((MenuContentImpl) other).map); return this; } @Override public void updateButton(Slot slot, Consumer<Button> buttonUpdate) { map.compute(slot, (s, oldButton) -> { buttonUpdate.accept(oldButton); return oldButton; }); } @Override public void trim(int maxButtonsCount) { LinkedList<Slot> slots = new LinkedList<>(map.keySet()); for (int i = 0; i < maxButtonsCount; i++) { Slot removed = slots.removeLast(); map.remove(removed); } } @Override public Stream<Map.Entry<Slot, Button>> stream() { return map.entrySet().stream(); } }
0
0.91698
1
0.91698
game-dev
MEDIA
0.808012
game-dev
0.955626
1
0.955626
st0x0ef/stellaris
1,725
common/src/main/java/com/st0x0ef/stellaris/client/renderers/entities/pygro/PygroBruteRenderer.java
package com.st0x0ef.stellaris.client.renderers.entities.pygro; import com.st0x0ef.stellaris.common.entities.mobs.PygroBrute; import com.st0x0ef.stellaris.common.utils.ResourceLocationUtils; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.model.geom.EntityModelSet; import net.minecraft.client.model.geom.ModelLayerLocation; import net.minecraft.client.renderer.culling.Frustum; import net.minecraft.client.renderer.entity.EntityRendererProvider; import net.minecraft.client.renderer.entity.HumanoidMobRenderer; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Mob; @Environment(EnvType.CLIENT) public class PygroBruteRenderer extends HumanoidMobRenderer<PygroBrute, PygroModel<PygroBrute>> { public static final ResourceLocation TEXTURE = ResourceLocationUtils.texture("entity/pygro_brute"); public PygroBruteRenderer(EntityRendererProvider.Context context) { super(context, new PygroModel<>(context.bakeLayer(PygroModel.LAYER_LOCATION)), 0.5f); } private static PygroModel<Mob> createModel(EntityModelSet p_174350_, ModelLayerLocation p_174351_) { return new PygroModel<>(p_174350_.bakeLayer(p_174351_)); } public ResourceLocation getTextureLocation(PygroBrute p_115708_) { return TEXTURE; } protected boolean isShaking(PygroBrute p_115712_) { return super.isShaking(p_115712_) || p_115712_ != null && p_115712_.isConverting(); } @Override public boolean shouldRender(PygroBrute livingEntity, Frustum camera, double camX, double camY, double camZ) { return livingEntity != null && camera.isVisible(livingEntity.getBoundingBoxForCulling()); } }
0
0.753104
1
0.753104
game-dev
MEDIA
0.680396
game-dev
0.606658
1
0.606658
LambdaInnovation/AcademyCraft
6,597
src/main/java/cn/academy/block/tileentity/TileNode.java
package cn.academy.block.tileentity; import cn.academy.block.block.BlockNode; import cn.academy.client.render.block.RenderDynamicBlock; import cn.academy.energy.api.IFItemManager; import cn.academy.energy.api.WirelessHelper; import cn.academy.energy.api.block.IWirelessNode; import cn.academy.block.block.BlockNode.NodeType; import cn.academy.energy.impl.WirelessNet; import cn.lambdalib2.registry.mc.RegTileEntity; import cn.lambdalib2.s11n.network.TargetPoints; import cn.lambdalib2.s11n.network.NetworkMessage; import cn.lambdalib2.s11n.network.NetworkMessage.Listener; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.util.ITickable; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; /** * @author WeathFolD * */ @RegTileEntity public class TileNode extends TileInventory implements IWirelessNode, IInventory, ITickable { static IFItemManager itemManager = IFItemManager.instance; static final String MSG_SYNC = "sync"; protected double energy; private int updateTicker; private String password = ""; /** * Client-only flag. Only *roughly* indicates whether the block is linked. * Used for just rendering. */ public boolean enabled = false; public boolean chargingIn = false; public boolean chargingOut = false; private String placerName = ""; public TileNode() { super("wireless_node", 2); } public void setPlacer(EntityPlayer player) { placerName = player.getName(); } public String getPlacerName() { return placerName; } @Override public void update() { if(!getWorld().isRemote) { ++updateTicker; if(updateTicker == 10) { updateTicker = 0; WirelessNet net = WirelessHelper.getWirelessNet(this); enabled = net != null; NetworkMessage.sendToAllAround(TargetPoints.convert(this, 20), this, MSG_SYNC, enabled, chargingIn, chargingOut, energy, name, password, placerName); rebuildBlockState(); } updateChargeIn(); updateChargeOut(); } } public void setPassword(String _pass) { password = _pass; } private void updateChargeIn() { ItemStack stack = this.getStackInSlot(0); if(stack != null && itemManager.isSupported(stack)) { //Charge into the node. double req = Math.min(getBandwidth(), getMaxEnergy() - energy); double pull = itemManager.pull(stack, req, false); chargingIn = pull != 0; this.setEnergy(energy + pull); } else { chargingIn = false; } } private void updateChargeOut() { ItemStack stack = this.getStackInSlot(1); if(stack != null && itemManager.isSupported(stack)) { double cur = getEnergy(); if(cur > 0) { cur = Math.min(getBandwidth(), cur); double left = itemManager.charge(stack, cur); chargingOut = left != cur; this.setEnergy(getEnergy() - (cur - left)); } } else { chargingOut = false; } } private void rebuildBlockState() { IBlockState curState = world.getBlockState(pos); Block block = curState.getBlock(); // sometime block and tileentity are mismatch if (block instanceof BlockNode) { boolean lastConnected = curState.getValue(BlockNode.CONNECTED); int lastPct = curState.getValue(BlockNode.ENERGY); int pct = (int) Math.min(4, Math.round((4 * getEnergy() / getMaxEnergy()))); if (pct != lastPct || lastConnected != enabled) { world.setBlockState(pos, curState .withProperty(BlockNode.CONNECTED, enabled) .withProperty(BlockNode.ENERGY, pct), 0); } } } @Override public double getMaxEnergy() { return getType().maxEnergy; } @Override public double getEnergy() { return energy; } @Override public void setEnergy(double value) { energy = value; rebuildBlockState(); } @Override public double getBandwidth() { return getType().bandwidth; } @Override public double getRange() { return getType().range; } public NodeType getType() { return NodeType.values()[getBlockMetadata()]; } @Override public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); energy = tag.getDouble("energy"); name = tag.getString("nodeName"); password = tag.getString("password"); placerName = tag.getString("placer"); } @Override public NBTTagCompound writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); tag.setDouble("energy", energy); tag.setString("nodeName", name); tag.setString("password", password); tag.setString("placer", placerName); return tag; } String name = "Unnamed"; @Override public String getNodeName() { return name; } @Override public String getPassword() { return password; } public void setNodeName(String name) { this.name = name; } @Listener(channel=MSG_SYNC, side=Side.CLIENT) void hSync(boolean enabled, boolean chargingIn, boolean chargingOut, double energy, String name, String pass, String placerName) { this.enabled = enabled; this.chargingIn = chargingIn; this.chargingOut = chargingOut; this.energy = energy; this.name = name; this.password = pass; this.placerName = placerName; } @Override public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate) { return oldState.getBlock() != newSate.getBlock(); } @Override public int getCapacity() { return getType().capacity; } }
0
0.870379
1
0.870379
game-dev
MEDIA
0.963795
game-dev
0.966874
1
0.966874
magefree/mage
5,520
Mage.Sets/src/mage/cards/a/AoTheDawnSky.java
package mage.cards.a; import mage.MageInt; import mage.MageObject; import mage.abilities.Ability; import mage.abilities.Mode; import mage.abilities.common.DiesSourceTriggeredAbility; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.counter.AddCountersAllEffect; import mage.abilities.keyword.FlyingAbility; import mage.abilities.keyword.VigilanceAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.cards.Cards; import mage.cards.CardsImpl; import mage.constants.*; import mage.counters.CounterType; import mage.filter.FilterCard; import mage.filter.FilterPermanent; import mage.filter.common.FilterControlledPermanent; import mage.filter.common.FilterPermanentCard; import mage.filter.predicate.Predicates; import mage.game.Game; import mage.players.Player; import mage.target.TargetCard; import mage.target.common.TargetCardInLibrary; import mage.util.CardUtil; import java.util.Objects; import java.util.Set; import java.util.UUID; /** * @author TheElk801 */ public final class AoTheDawnSky extends CardImpl { private static final FilterPermanent filter = new FilterControlledPermanent("permanent you control that's a creature or Vehicle"); static { filter.add(Predicates.or( CardType.CREATURE.getPredicate(), SubType.VEHICLE.getPredicate() )); } public AoTheDawnSky(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{W}{W}"); this.supertype.add(SuperType.LEGENDARY); this.subtype.add(SubType.DRAGON); this.subtype.add(SubType.SPIRIT); this.power = new MageInt(5); this.toughness = new MageInt(4); // Flying this.addAbility(FlyingAbility.getInstance()); // Vigilance this.addAbility(VigilanceAbility.getInstance()); // When Ao, the Dawn Sky dies, choose one — // • Look at the top seven cards of your library. Put any number of nonland permanent cards with total mana value 4 or less from among them onto the battlefield. Put the rest on the bottom of your library in a random order. Ability ability = new DiesSourceTriggeredAbility(new AoTheDawnSkyEffect()); // • Put two +1/+1 counters on each permanent you control that's a creature or Vehicle. ability.addMode(new Mode(new AddCountersAllEffect(CounterType.P1P1.createInstance(2), filter))); this.addAbility(ability); } private AoTheDawnSky(final AoTheDawnSky card) { super(card); } @Override public AoTheDawnSky copy() { return new AoTheDawnSky(this); } } class AoTheDawnSkyEffect extends OneShotEffect { AoTheDawnSkyEffect() { super(Outcome.Benefit); staticText = "look at the top seven cards of your library. Put any number of nonland permanent cards " + "with total mana value 4 or less from among them onto the battlefield. " + "Put the rest on the bottom of your library in a random order"; } private AoTheDawnSkyEffect(final AoTheDawnSkyEffect effect) { super(effect); } @Override public AoTheDawnSkyEffect copy() { return new AoTheDawnSkyEffect(this); } @Override public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getControllerId()); if (player == null) { return false; } Cards cards = new CardsImpl(player.getLibrary().getTopCards(game, 7)); TargetCard target = new AoTheDawnSkyTarget(); player.choose(outcome, cards, target, source, game); player.moveCards(new CardsImpl(target.getTargets()), Zone.BATTLEFIELD, source, game); cards.retainZone(Zone.LIBRARY, game); player.putCardsOnBottomOfLibrary(cards, game, source, false); return true; } } class AoTheDawnSkyTarget extends TargetCardInLibrary { private static final FilterCard filterStatic = new FilterPermanentCard("nonland permanent cards with total mana value 4 or less from your graveyard"); static { filterStatic.add(Predicates.not(CardType.LAND.getPredicate())); } AoTheDawnSkyTarget() { super(0, Integer.MAX_VALUE, filterStatic); } private AoTheDawnSkyTarget(final AoTheDawnSkyTarget target) { super(target); } @Override public AoTheDawnSkyTarget copy() { return new AoTheDawnSkyTarget(this); } @Override public boolean canTarget(UUID playerId, UUID id, Ability source, Game game) { return super.canTarget(playerId, id, source, game) && CardUtil.checkCanTargetTotalValueLimit( this.getTargets(), id, MageObject::getManaValue, 4, game); } @Override public Set<UUID> possibleTargets(UUID sourceControllerId, Ability source, Game game) { return CardUtil.checkPossibleTargetsTotalValueLimit(this.getTargets(), super.possibleTargets(sourceControllerId, source, game), MageObject::getManaValue, 4, game); } @Override public String getMessage(Game game) { // shows selected total int selectedValue = this.getTargets().stream() .map(game::getObject) .filter(Objects::nonNull) .mapToInt(MageObject::getManaValue) .sum(); return super.getMessage(game) + " (selected total mana value " + selectedValue + ")"; } }
0
0.986859
1
0.986859
game-dev
MEDIA
0.992207
game-dev
0.997899
1
0.997899
googlecreativelab/balloon-pop
1,347
Assets/Plugins/Unity-Tweens/Runtime/CameraFieldOfViewTween.cs
using ElRaccoone.Tweens.Core; using UnityEngine; namespace ElRaccoone.Tweens { public static class CameraFieldOfViewTween { public static Tween<float> TweenCameraFieldOfView (this Component self, float to, float duration) => Tween<float>.Add<Driver> (self).Finalize (to, duration); public static Tween<float> TweenCameraFieldOfView (this GameObject self, float to, float duration) => Tween<float>.Add<Driver> (self).Finalize (to, duration); /// <summary> /// The driver is responsible for updating the tween's state. /// </summary> private class Driver : Tween<float, Camera> { /// <summary> /// Overriden method which is called when the tween starts and should /// return the tween's initial value. /// </summary> public override float OnGetFrom () { return this.component.fieldOfView; } /// <summary> /// Overriden method which is called every tween update and should be used /// to update the tween's value. /// </summary> /// <param name="easedTime">The current eased time of the tween's step.</param> public override void OnUpdate (float easedTime) { this.valueCurrent = this.InterpolateValue (this.valueFrom, this.valueTo, easedTime); this.component.fieldOfView = this.valueCurrent; } } } }
0
0.807636
1
0.807636
game-dev
MEDIA
0.958192
game-dev
0.971484
1
0.971484
kkamagui/mint64os-examples
18,832
source_code/chap55/02.Kernel64/Source/Keyboard.c
/** * file Main.c * date 2009/01/09 * author kkamagui * Copyright(c)2008 All rights reserved by kkamagui * brief 키보드 디바이스 드라이버에 관련된 소스 파일 */ #include "Types.h" #include "AssemblyUtility.h" #include "Keyboard.h" #include "Queue.h" #include "Synchronization.h" //////////////////////////////////////////////////////////////////////////////// // // 키보드 컨트롤러 및 키보드 제어에 관련된 함수들 // //////////////////////////////////////////////////////////////////////////////// /** * 출력 버퍼(포트 0x60)에 수신된 데이터가 있는지 여부를 반환 */ BOOL kIsOutputBufferFull( void ) { // 상태 레지스터(포트 0x64)에서 읽은 값에 출력 버퍼 상태 비트(비트 0)가 // 1로 설정되어 있으면 출력 버퍼에 키보드가 전송한 데이터가 존재함 if( kInPortByte( 0x64 ) & 0x01 ) { return TRUE; } return FALSE; } /** * 입력 버퍼(포트 0x60)에 프로세서가 쓴 데이터가 남아있는지 여부를 반환 */ BOOL kIsInputBufferFull( void ) { // 상태 레지스터(포트 0x64)에서 읽은 값에 입력 버퍼 상태 비트(비트 1)가 // 1로 설정되어 있으면 아직 키보드가 데이터를 가져가지 않았음 if( kInPortByte( 0x64 ) & 0x02 ) { return TRUE; } return FALSE; } /** * ACK를 기다림 * ACK가 아닌 다른 코드는 키보드 데이터와 마우스 데이터를 구분하여 큐에 삽입 */ BOOL kWaitForACKAndPutOtherScanCode( void ) { int i, j; BYTE bData; BOOL bResult = FALSE; BOOL bMouseData; // ACK가 오기 전에 키보드 출력 버퍼(포트 0x60)에 키 데이터가 저장되어 있을 수 있으므로 // 키보드에서 전달된 데이터를 최대 100개까지 수신하여 ACK를 확인 for( j = 0 ; j < 100 ; j++ ) { // 0xFFFF만큼 루프를 수행할 시간이면 충분히 커맨드의 응답이 올 수 있음 // 0xFFFF 루프를 수행한 이후에도 출력 버퍼(포트 0x60)가 차 있지 않으면 무시하고 읽음 for( i = 0 ; i < 0xFFFF ; i++ ) { // 출력 버퍼(포트 0x60)가 차있으면 데이터를 읽을 수 있음 if( kIsOutputBufferFull() == TRUE ) { break; } } // 출력 버퍼(포트 0x60을 읽기 전에 먼저 상태 레지스터(포트 0x64)를 읽어서 // 마우스 데이터인지를 확인 if( kIsMouseDataInOutputBuffer() == TRUE ) { bMouseData = TRUE; } else { bMouseData = FALSE; } // 출력 버퍼(포트 0x60)에서 읽은 데이터가 ACK(0xFA)이면 성공 bData = kInPortByte( 0x60 ); if( bData == 0xFA ) { bResult = TRUE; break; } // ACK(0xFA)가 아니면 데이터가 수신된 디바이스에 따라 키보드 큐나 마우스 큐에 삽입 else { if( bMouseData == FALSE ) { kConvertScanCodeAndPutQueue( bData ); } else { kAccumulateMouseDataAndPutQueue( bData ); } } } return bResult; } /** * 키보드를 활성화 함 */ BOOL kActivateKeyboard( void ) { int i, j; BOOL bPreviousInterrupt; BOOL bResult; // 인터럽트 불가 bPreviousInterrupt = kSetInterruptFlag( FALSE ); // 컨트롤 레지스터(포트 0x64)에 키보드 활성화 커맨드(0xAE)를 전달하여 키보드 디바이스 활성화 kOutPortByte( 0x64, 0xAE ); // 입력 버퍼(포트 0x60)가 빌 때까지 기다렸다가 키보드에 활성화 커맨드를 전송 // 0xFFFF만큼 루프를 수행할 시간이면 충분히 커맨드가 전송될 수 있음 // 0xFFFF 루프를 수행한 이후에도 입력 버퍼(포트 0x60)가 비지 않으면 무시하고 전송 for( i = 0 ; i < 0xFFFF ; i++ ) { // 입력 버퍼(포트 0x60)가 비어있으면 키보드 커맨드 전송 가능 if( kIsInputBufferFull() == FALSE ) { break; } } // 입력 버퍼(포트 0x60)로 키보드 활성화(0xF4) 커맨드를 전달하여 키보드로 전송 kOutPortByte( 0x60, 0xF4 ); // ACK가 올 때까지 대기함 bResult = kWaitForACKAndPutOtherScanCode(); // 이전 인터럽트 상태 복원 kSetInterruptFlag( bPreviousInterrupt ); return bResult; } /** * 출력 버퍼(포트 0x60)에서 키를 읽음 */ BYTE kGetKeyboardScanCode( void ) { // 출력 버퍼(포트 0x60)에 데이터가 있을 때까지 대기 while( kIsOutputBufferFull() == FALSE ) { ; } return kInPortByte( 0x60 ); } /** * 키보드 LED의 ON/OFF를 변경 */ BOOL kChangeKeyboardLED( BOOL bCapsLockOn, BOOL bNumLockOn, BOOL bScrollLockOn ) { int i, j; BOOL bPreviousInterrupt; BOOL bResult; BYTE bData; // 인터럽트 불가 bPreviousInterrupt = kSetInterruptFlag( FALSE ); // 키보드에 LED 변경 커맨드 전송하고 커맨드가 처리될 때까지 대기 for( i = 0 ; i < 0xFFFF ; i++ ) { // 출력 버퍼(포트 0x60)가 비었으면 커맨드 전송 가능 if( kIsInputBufferFull() == FALSE ) { break; } } // 출력 버퍼(포트 0x60)로 LED 상태 변경 커맨드(0xED) 전송 kOutPortByte( 0x60, 0xED ); for( i = 0 ; i < 0xFFFF ; i++ ) { // 입력 버퍼(포트 0x60)가 비어있으면 키보드가 커맨드를 가져간 것임 if( kIsInputBufferFull() == FALSE ) { break; } } // ACK가 올때까지 대기함 bResult = kWaitForACKAndPutOtherScanCode(); if( bResult == FALSE ) { // 이전 인터럽트 상태 복원 kSetInterruptFlag( bPreviousInterrupt ); return FALSE; } // LED 변경 값을 키보드로 전송하고 데이터가 처리가 완료될 때까지 대기 kOutPortByte( 0x60, ( bCapsLockOn << 2 ) | ( bNumLockOn << 1 ) | bScrollLockOn ); for( i = 0 ; i < 0xFFFF ; i++ ) { // 입력 버퍼(포트 0x60)가 비어있으면 키보드가 LED 데이터를 가져간 것임 if( kIsInputBufferFull() == FALSE ) { break; } } // ACK가 올 때까지 대기함 bResult = kWaitForACKAndPutOtherScanCode(); // 이전 인터럽트 상태 복원 kSetInterruptFlag( bPreviousInterrupt ); return bResult; } /** * A20 게이트를 활성화 */ void kEnableA20Gate( void ) { BYTE bOutputPortData; int i; // 컨트롤 레지스터(포트 0x64)에 키보드 컨트롤러의 출력 포트 값을 읽는 커맨드(0xD0) 전송 kOutPortByte( 0x64, 0xD0 ); // 출력 포트의 데이터를 기다렸다가 읽음 for( i = 0 ; i < 0xFFFF ; i++ ) { // 출력 버퍼(포트 0x60)가 차있으면 데이터를 읽을 수 있음 if( kIsOutputBufferFull() == TRUE ) { break; } } // 출력 포트(포트 0x60)에 수신된 키보드 컨트롤러의 출력 포트 값을 읽음 bOutputPortData = kInPortByte( 0x60 ); // A20 게이트 비트 설정 bOutputPortData |= 0x01; // 입력 버퍼(포트 0x60)에 데이터가 비어있으면 출력 포트에 값을 쓰는 커맨드와 출력 포트 데이터 전송 for( i = 0 ; i < 0xFFFF ; i++ ) { // 입력 버퍼(포트 0x60)가 비었으면 커맨드 전송 가능 if( kIsInputBufferFull() == FALSE ) { break; } } // 커맨드 레지스터(0x64)에 출력 포트 설정 커맨드(0xD1)을 전달 kOutPortByte( 0x64, 0xD1 ); // 입력 버퍼(0x60)에 A20 게이트 비트가 1로 설정된 값을 전달 kOutPortByte( 0x60, bOutputPortData ); } /** * 프로세서를 리셋(Reset) */ void kReboot( void ) { int i; // 입력 버퍼(포트 0x60)에 데이터가 비어있으면 출력 포트에 값을 쓰는 커맨드와 출력 포트 데이터 전송 for( i = 0 ; i < 0xFFFF ; i++ ) { // 입력 버퍼(포트 0x60)가 비었으면 커맨드 전송 가능 if( kIsInputBufferFull() == FALSE ) { break; } } // 커맨드 레지스터(0x64)에 출력 포트 설정 커맨드(0xD1)을 전달 kOutPortByte( 0x64, 0xD1 ); // 입력 버퍼(0x60)에 0을 전달하여 프로세서를 리셋(Reset)함 kOutPortByte( 0x60, 0x00 ); while( 1 ) { ; } } //////////////////////////////////////////////////////////////////////////////// // // 스캔 코드를 ASCII 코드로 변환하는 기능에 관련된 함수들 // //////////////////////////////////////////////////////////////////////////////// // 키보드 상태를 관리하는 키보드 매니저 static KEYBOARDMANAGER gs_stKeyboardManager = { 0, }; // 키를 저장하는 큐와 버퍼 정의 static QUEUE gs_stKeyQueue; static KEYDATA gs_vstKeyQueueBuffer[ KEY_MAXQUEUECOUNT ]; // 스캔 코드를 ASCII 코드로 변환하는 테이블 static KEYMAPPINGENTRY gs_vstKeyMappingTable[ KEY_MAPPINGTABLEMAXCOUNT ] = { /* 0 */ { KEY_NONE , KEY_NONE }, /* 1 */ { KEY_ESC , KEY_ESC }, /* 2 */ { '1' , '!' }, /* 3 */ { '2' , '@' }, /* 4 */ { '3' , '#' }, /* 5 */ { '4' , '$' }, /* 6 */ { '5' , '%' }, /* 7 */ { '6' , '^' }, /* 8 */ { '7' , '&' }, /* 9 */ { '8' , '*' }, /* 10 */ { '9' , '(' }, /* 11 */ { '0' , ')' }, /* 12 */ { '-' , '_' }, /* 13 */ { '=' , '+' }, /* 14 */ { KEY_BACKSPACE , KEY_BACKSPACE }, /* 15 */ { KEY_TAB , KEY_TAB }, /* 16 */ { 'q' , 'Q' }, /* 17 */ { 'w' , 'W' }, /* 18 */ { 'e' , 'E' }, /* 19 */ { 'r' , 'R' }, /* 20 */ { 't' , 'T' }, /* 21 */ { 'y' , 'Y' }, /* 22 */ { 'u' , 'U' }, /* 23 */ { 'i' , 'I' }, /* 24 */ { 'o' , 'O' }, /* 25 */ { 'p' , 'P' }, /* 26 */ { '[' , '{' }, /* 27 */ { ']' , '}' }, /* 28 */ { '\n' , '\n' }, /* 29 */ { KEY_CTRL , KEY_CTRL }, /* 30 */ { 'a' , 'A' }, /* 31 */ { 's' , 'S' }, /* 32 */ { 'd' , 'D' }, /* 33 */ { 'f' , 'F' }, /* 34 */ { 'g' , 'G' }, /* 35 */ { 'h' , 'H' }, /* 36 */ { 'j' , 'J' }, /* 37 */ { 'k' , 'K' }, /* 38 */ { 'l' , 'L' }, /* 39 */ { ';' , ':' }, /* 40 */ { '\'' , '\"' }, /* 41 */ { '`' , '~' }, /* 42 */ { KEY_LSHIFT , KEY_LSHIFT }, /* 43 */ { '\\' , '|' }, /* 44 */ { 'z' , 'Z' }, /* 45 */ { 'x' , 'X' }, /* 46 */ { 'c' , 'C' }, /* 47 */ { 'v' , 'V' }, /* 48 */ { 'b' , 'B' }, /* 49 */ { 'n' , 'N' }, /* 50 */ { 'm' , 'M' }, /* 51 */ { ',' , '<' }, /* 52 */ { '.' , '>' }, /* 53 */ { '/' , '?' }, /* 54 */ { KEY_RSHIFT , KEY_RSHIFT }, /* 55 */ { '*' , '*' }, /* 56 */ { KEY_LALT , KEY_LALT }, /* 57 */ { ' ' , ' ' }, /* 58 */ { KEY_CAPSLOCK , KEY_CAPSLOCK }, /* 59 */ { KEY_F1 , KEY_F1 }, /* 60 */ { KEY_F2 , KEY_F2 }, /* 61 */ { KEY_F3 , KEY_F3 }, /* 62 */ { KEY_F4 , KEY_F4 }, /* 63 */ { KEY_F5 , KEY_F5 }, /* 64 */ { KEY_F6 , KEY_F6 }, /* 65 */ { KEY_F7 , KEY_F7 }, /* 66 */ { KEY_F8 , KEY_F8 }, /* 67 */ { KEY_F9 , KEY_F9 }, /* 68 */ { KEY_F10 , KEY_F10 }, /* 69 */ { KEY_NUMLOCK , KEY_NUMLOCK }, /* 70 */ { KEY_SCROLLLOCK , KEY_SCROLLLOCK }, /* 71 */ { KEY_HOME , '7' }, /* 72 */ { KEY_UP , '8' }, /* 73 */ { KEY_PAGEUP , '9' }, /* 74 */ { '-' , '-' }, /* 75 */ { KEY_LEFT , '4' }, /* 76 */ { KEY_CENTER , '5' }, /* 77 */ { KEY_RIGHT , '6' }, /* 78 */ { '+' , '+' }, /* 79 */ { KEY_END , '1' }, /* 80 */ { KEY_DOWN , '2' }, /* 81 */ { KEY_PAGEDOWN , '3' }, /* 82 */ { KEY_INS , '0' }, /* 83 */ { KEY_DEL , '.' }, /* 84 */ { KEY_NONE , KEY_NONE }, /* 85 */ { KEY_NONE , KEY_NONE }, /* 86 */ { KEY_NONE , KEY_NONE }, /* 87 */ { KEY_F11 , KEY_F11 }, /* 88 */ { KEY_F12 , KEY_F12 } }; /** * 스캔 코드가 알파벳 범위인지 여부를 반환 */ BOOL kIsAlphabetScanCode( BYTE bScanCode ) { // 변환 테이블을 값을 직접 읽어서 알파벳 범위인지 확인 if( ( 'a' <= gs_vstKeyMappingTable[ bScanCode ].bNormalCode ) && ( gs_vstKeyMappingTable[ bScanCode ].bNormalCode <= 'z' ) ) { return TRUE; } return FALSE; } /** * 숫자 또는 기호 범위인지 여부를 반환 */ BOOL kIsNumberOrSymbolScanCode( BYTE bScanCode ) { // 숫자 패드나 확장 키 범위를 제외한 범위(스캔 코드 2~53)에서 영문자가 아니면 // 숫자 또는 기호임 if( ( 2 <= bScanCode ) && ( bScanCode <= 53 ) && ( kIsAlphabetScanCode( bScanCode ) == FALSE ) ) { return TRUE; } return FALSE; } /** * 숫자 패드 범위인지 여부를 반환 */ BOOL kIsNumberPadScanCode( BYTE bScanCode ) { // 숫자 패드는 스캔 코드의 71~83에 있음 if( ( 71 <= bScanCode ) && ( bScanCode <= 83 ) ) { return TRUE; } return FALSE; } /** * 조합된 키 값을 사용해야 하는지 여부를 반환 */ BOOL kIsUseCombinedCode( BOOL bScanCode ) { BYTE bDownScanCode; BOOL bUseCombinedKey; bDownScanCode = bScanCode & 0x7F; // 알파벳 키라면 Shift 키와 Caps Lock의 영향을 받음 if( kIsAlphabetScanCode( bDownScanCode ) == TRUE ) { // 만약 Shift 키와 Caps Lock 키 중에 하나만 눌러져있으면 조합된 키를 되돌려 줌 if( gs_stKeyboardManager.bShiftDown ^ gs_stKeyboardManager.bCapsLockOn ) { bUseCombinedKey = TRUE; } else { bUseCombinedKey = FALSE; } } // 숫자와 기호 키라면 Shift 키의 영향을 받음 else if( kIsNumberOrSymbolScanCode( bDownScanCode ) == TRUE ) { // Shift 키가 눌러져있으면 조합된 키를 되돌려 줌 if( gs_stKeyboardManager.bShiftDown == TRUE ) { bUseCombinedKey = TRUE; } else { bUseCombinedKey = FALSE; } } // 숫자 패드 키라면 Num Lock 키의 영향을 받음 // 0xE0만 제외하면 확장 키 코드와 숫자 패드의 코드가 겹치므로, // 확장 키 코드가 수신되지 않았을 때만처리 조합된 코드 사용 else if( ( kIsNumberPadScanCode( bDownScanCode ) == TRUE ) && ( gs_stKeyboardManager.bExtendedCodeIn == FALSE ) ) { // Num Lock 키가 눌러져있으면, 조합된 키를 되돌려 줌 if( gs_stKeyboardManager.bNumLockOn == TRUE ) { bUseCombinedKey = TRUE; } else { bUseCombinedKey = FALSE; } } return bUseCombinedKey; } /** * 조합 키의 상태를 갱신하고 LED 상태도 동기화 함 */ void UpdateCombinationKeyStatusAndLED( BYTE bScanCode ) { BOOL bDown; BYTE bDownScanCode; BOOL bLEDStatusChanged = FALSE; // 눌림 또는 떨어짐 상태처리, 최상위 비트(비트 7)가 1이면 키가 떨어졌음을 의미하고 // 0이면 떨어졌음을 의미함 if( bScanCode & 0x80 ) { bDown = FALSE; bDownScanCode = bScanCode & 0x7F; } else { bDown = TRUE; bDownScanCode = bScanCode; } // 조합 키 검색 // Shift 키의 스캔 코드(42 or 54)이면 Shift 키의 상태 갱신 if( ( bDownScanCode == 42 ) || ( bDownScanCode == 54 ) ) { gs_stKeyboardManager.bShiftDown = bDown; } // Caps Lock 키의 스캔 코드(58)이면 Caps Lock의 상태 갱신하고 LED 상태 변경 else if( ( bDownScanCode == 58 ) && ( bDown == TRUE ) ) { gs_stKeyboardManager.bCapsLockOn ^= TRUE; bLEDStatusChanged = TRUE; } // Num Lock 키의 스캔 코드(69)이면 Num Lock의 상태를 갱신하고 LED 상태 변경 else if( ( bDownScanCode == 69 ) && ( bDown == TRUE ) ) { gs_stKeyboardManager.bNumLockOn ^= TRUE; bLEDStatusChanged = TRUE; } // Scroll Lock 키의 스캔 코드(70)이면 Scroll Lock의 상태를 갱신하고 LED 상태 변경 else if( ( bDownScanCode == 70 ) && ( bDown == TRUE ) ) { gs_stKeyboardManager.bScrollLockOn ^= TRUE; bLEDStatusChanged = TRUE; } // LED 상태가 변했으면 키보드로 커맨드를 전송하여 LED를 변경 if( bLEDStatusChanged == TRUE ) { kChangeKeyboardLED( gs_stKeyboardManager.bCapsLockOn, gs_stKeyboardManager.bNumLockOn, gs_stKeyboardManager.bScrollLockOn ); } } /** * 스캔 코드를 ASCII 코드로 변환 */ BOOL kConvertScanCodeToASCIICode( BYTE bScanCode, BYTE* pbASCIICode, BOOL* pbFlags ) { BOOL bUseCombinedKey; // 이전에 Pause 키가 수신되었다면, Pause의 남은 스캔 코드를 무시 if( gs_stKeyboardManager.iSkipCountForPause > 0 ) { gs_stKeyboardManager.iSkipCountForPause--; return FALSE; } // Pause 키는 특별히 처리 if( bScanCode == 0xE1 ) { *pbASCIICode = KEY_PAUSE; *pbFlags = KEY_FLAGS_DOWN; gs_stKeyboardManager.iSkipCountForPause = KEY_SKIPCOUNTFORPAUSE; return TRUE; } // 확장 키 코드가 들어왔을 때, 실제 키 값은 다음에 들어오므로 플래그 설정만 하고 종료 else if( bScanCode == 0xE0 ) { gs_stKeyboardManager.bExtendedCodeIn = TRUE; return FALSE; } // 조합된 키를 반환해야 하는가? bUseCombinedKey = kIsUseCombinedCode( bScanCode ); // 키 값 설정 if( bUseCombinedKey == TRUE ) { *pbASCIICode = gs_vstKeyMappingTable[ bScanCode & 0x7F ].bCombinedCode; } else { *pbASCIICode = gs_vstKeyMappingTable[ bScanCode & 0x7F ].bNormalCode; } // 확장 키 유무 설정 if( gs_stKeyboardManager.bExtendedCodeIn == TRUE ) { *pbFlags = KEY_FLAGS_EXTENDEDKEY; gs_stKeyboardManager.bExtendedCodeIn = FALSE; } else { *pbFlags = 0; } // 눌러짐 또는 떨어짐 유무 설정 if( ( bScanCode & 0x80 ) == 0 ) { *pbFlags |= KEY_FLAGS_DOWN; } // 조합 키 눌림 또는 떨어짐 상태를 갱신 UpdateCombinationKeyStatusAndLED( bScanCode ); return TRUE; } /** * 키보드 초기화 */ BOOL kInitializeKeyboard( void ) { // 큐 초기화 kInitializeQueue( &gs_stKeyQueue, gs_vstKeyQueueBuffer, KEY_MAXQUEUECOUNT, sizeof( KEYDATA ) ); // 스핀락 초기화 kInitializeSpinLock( &( gs_stKeyboardManager.stSpinLock ) ); // 키보드 활성화 return kActivateKeyboard(); } /** * 스캔 코드를 내부적으로 사용하는 키 데이터로 바꾼 후 키 큐에 삽입 */ BOOL kConvertScanCodeAndPutQueue( BYTE bScanCode ) { KEYDATA stData; BOOL bResult = FALSE; stData.bScanCode = bScanCode; if( kConvertScanCodeToASCIICode( bScanCode, &( stData.bASCIICode ), &( stData.bFlags ) ) == TRUE ) { // 임계 영역 시작 kLockForSpinLock( &( gs_stKeyboardManager.stSpinLock ) ); bResult = kPutQueue( &gs_stKeyQueue, &stData ); // 임계 영역 끝 kUnlockForSpinLock( &( gs_stKeyboardManager.stSpinLock ) ); } return bResult; } /** * 키 큐에서 데이터를 제거 */ BOOL kGetKeyFromKeyQueue( KEYDATA* pstData ) { BOOL bResult; // 임계 영역 시작 kLockForSpinLock( &( gs_stKeyboardManager.stSpinLock ) ); bResult = kGetQueue( &gs_stKeyQueue, pstData ); // 임계 영역 끝 kUnlockForSpinLock( &( gs_stKeyboardManager.stSpinLock ) ); return bResult; }
0
0.789828
1
0.789828
game-dev
MEDIA
0.561208
game-dev
0.659969
1
0.659969
icza/scelight
8,450
src-app/hu/scelight/sc2/rep/model/gameevents/cmd/CmdEvent.java
/* * Project Scelight * * Copyright (c) 2013 Andras Belicza <iczaaa@gmail.com> * * This software is the property of Andras Belicza. * Copying, modifying, distributing, refactoring without the author's permission * is prohibited and protected by Law. */ package hu.scelight.sc2.rep.model.gameevents.cmd; import hu.belicza.andras.util.ArrayMap; import hu.scelight.gui.icon.Icons; import hu.scelight.sc2.balancedata.BalanceData; import hu.scelight.sc2.balancedata.model.Ability; import hu.scelight.sc2.balancedata.model.Command; import hu.scelight.sc2.rep.s2prot.Event; import hu.scelight.sc2.textures.Textures; import hu.scelight.service.env.Env; import hu.scelightapi.sc2.balancedata.IBalanceData; import hu.scelightapi.sc2.balancedata.model.IUnit; import hu.scelightapi.sc2.rep.model.gameevents.cmd.ICmdEvent; import hu.scelightapi.sc2.rep.repproc.IRepProcessor; import hu.scelightapi.sc2.rep.repproc.IUser; import hu.scelightapibase.gui.icon.IRIcon; import hu.sllauncher.util.Pair; import java.util.Map; /** * Cmd game event. * * @author Andras Belicza */ public class CmdEvent extends Event implements ICmdEvent { /** Cached command. */ public final Command command; /** Cached flags. */ private final int flags; /** Target unit of the cmd event. */ private final TargetUnit targetUnit; /** Target point of the cmd event. */ private final TargetPoint targetPoint; /** * Creates a new {@link CmdEvent}. * * @param struct event data structure * @param id id of the event * @param name type name of the event * @param loop game loop when the event occurred * @param userId user id causing the event * @param baseBuild base build of the replay being parsed, there are structural differences in event structures in different versions * @param balanceData balance data of the game / replay */ public CmdEvent( final Map< String, Object > struct, final int id, final String name, final int loop, final int userId, final int baseBuild, final BalanceData balanceData ) { super( struct, id, name, loop, userId ); // In the first retail version (1.0) fields of the abil and data structs are enumerated // directly in the cmd struct (except the target point). Simulate those structs. if ( baseBuild < 16561 ) { final Integer abilLink = (Integer) struct.remove( P_ABIL_LINK[ 1 ] ); if ( abilLink != 65535 ) { // in 1.0 65535 means right click (which is also indicated in the cmdFlags) final Map< String, Object > abilStruct = new ArrayMap< >( 2 ); abilStruct.put( P_ABIL_LINK[ 1 ], abilLink ); abilStruct.put( P_ABIL_CMD_INDEX[ 1 ], struct.remove( P_ABIL_CMD_INDEX[ 1 ] ) ); struct.put( P_ABIL_LINK[ 0 ], abilStruct ); } @SuppressWarnings( "unchecked" ) final Map< String, Object > targetPoint_ = (Map< String, Object >) struct.remove( "targetPoint" ); final Integer targetUnitTag = (Integer) struct.remove( "targetUnitTag" ); final Integer targetUnitSnapshotLink = (Integer) struct.remove( "targetUnitSnapshotUnitLink" ); if ( targetUnitSnapshotLink != null && targetUnitSnapshotLink != 0 ) { // Simulate a "TargetUnit" final Pair< String, Map< String, Object > > data = new Pair< String, Map< String, Object > >( "TargetUnit", new ArrayMap< String, Object >( 5 ) ); data.value2.put( TargetUnit.F_TARGET_UNIT_FLAGS, struct.remove( "targetUnitFlags" ) ); data.value2.put( TargetUnit.F_TIMER, struct.remove( "targetUnitTimer" ) ); data.value2.put( TargetUnit.F_TAG, targetUnitTag ); data.value2.put( TargetUnit.F_SNAPSHOT_UNIT_LINK, targetUnitSnapshotLink ); data.value2.put( TargetUnit.F_SNAPSHOT_PLAYER_ID, struct.remove( "targetUnitSnapshotPlayerId" ) ); // Does the simulated "TargetUnit" have a snapshotPoint? if ( (Integer) targetPoint_.get( "x" ) != 0 ) data.value2.put( TargetUnit.F_SNAPSHOT_POINT, targetPoint_ ); struct.put( F_DATA, data ); } else if ( (Integer) targetPoint_.get( "x" ) != 0 ) { // Simulate a "TargetPoint" final Pair< String, Map< String, Object > > data = new Pair< >( "TargetPoint", targetPoint_ ); struct.put( F_DATA, data ); } else if ( targetUnitTag != 0 ) { // Simulate a "Data" final Pair< String, Integer > data = new Pair< >( "Data", targetUnitTag ); struct.put( F_DATA, data ); } } // Cache command Command command_ = null; final Integer abilLink = getAbilLink(); final Integer abilCmdIndex = getAbilCmdIndex(); if ( abilLink != null && abilCmdIndex != null ) { // There is surely a command here, the question is: is it known or unknown? if ( balanceData != null ) { final Ability ability = balanceData.getAbility( abilLink ); if ( ability != null ) command_ = ability.getCommand( abilCmdIndex ); } if ( command_ == null ) { command_ = new Command( null ); command_.text = "Unknown Command " + abilLink + "_" + abilCmdIndex; command_.icon = Textures.MISSING_ICON_NAME; // Note: Setting this icon will classify the command as non-essential } } command = command_; flags = get( F_CMD_FLAGS ); // Cache target final Pair< String, Object > data = getData(); if ( data == null ) { targetUnit = null; targetPoint = null; } else switch ( data.value1 ) { case "TargetUnit" : @SuppressWarnings( "unchecked" ) final Map< String, Object > tuStruct = (Map< String, Object >) data.value2; targetUnit = new TargetUnit( tuStruct ); targetPoint = new TargetPoint( targetUnit.getSnapshotPoint() ); break; case "TargetPoint" : targetUnit = null; @SuppressWarnings( "unchecked" ) final Map< String, Object > tpStruct = (Map< String, Object >) data.value2; targetPoint = new TargetPoint( tpStruct ); break; case "Data" : // TODO // In case of [Wireframe click][Wireframe unload] this is the unit tag // In case of [Wireframe click][Wireframe cancel] this is maybe the ability index (that is cancelled) // data.value2 is of type Integer default : targetUnit = null; targetPoint = null; break; } } @Override public Command getCommand() { return command; } @Override public Integer getCmdFlags() { return flags; } @Override public Integer getAbilLink() { return get( P_ABIL_LINK ); } @Override public Integer getAbilCmdIndex() { return get( P_ABIL_CMD_INDEX ); } @Override public Pair< String, Object > getData() { return get( F_DATA ); } @Override public TargetUnit getTargetUnit() { return targetUnit; } @Override public TargetPoint getTargetPoint() { return targetPoint; } @Override public String getParameters( final IRepProcessor repProc ) { final StringBuilder sb = new StringBuilder(); for ( final CmdFlag flag : CmdFlag.VALUES ) { if ( ( flags & flag.mask ) != 0 ) sb.append( flag.text ); } if ( command != null ) sb.append( command.text ); if ( targetUnit != null ) { final IBalanceData balanceData = repProc.getReplay().getBalanceData(); final IUnit unit = balanceData == null ? null : balanceData.getUnit( targetUnit.getSnapshotUnitLink() ); sb.append( "; target unit: " ).append( unit == null ? "Unknown " + targetUnit.getSnapshotUnitLink() : unit.getText() ); sb.append( " (tag=" ).append( repProc.getTagTransformation().tagToString( targetUnit.getTag() ) ); final Integer playerId = targetUnit.getSnapshotControlPlayerId(); if ( playerId != null && playerId != 0 ) {// Neutral units have playerId=0 (e.g. mineral field) // In multiplayer custom games (e.g.) may contain hostile units with playerId=15 but no associated player/user, so check for null: final IUser user = repProc.getUsersByPlayerId()[ playerId ]; if ( user != null ) { sb.append( "; owner=" ).append( user.getFullName() ); } } sb.append( ')' ); } if ( targetPoint != null ) { sb.append( "; target point: x=" ).append( Env.LANG.formatNumber( targetPoint.getXFloat(), 3 ) ).append( ", y=" ) .append( Env.LANG.formatNumber( targetPoint.getYFloat(), 3 ) ).append( ", z=" ) .append( Env.LANG.formatNumber( targetPoint.getZFloat(), 3 ) ); } return sb.toString(); } @Override public IRIcon getRicon() { return ( flags & CmdFlag.SMART_CLICK.mask ) != 0 ? Icons.F_MOUSE_SELECT_RIGHT : command == null ? super.getRicon() : command.getRicon(); } }
0
0.775881
1
0.775881
game-dev
MEDIA
0.482578
game-dev
0.924395
1
0.924395
microsoft/Recognizers-Text
8,741
.NET/Microsoft.Recognizers.Text.DateTime/Extractors/CJK/BaseCJKDurationExtractor.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Microsoft.Recognizers.Text.Utilities; using DateObject = System.DateTime; namespace Microsoft.Recognizers.Text.DateTime { public class BaseCJKDurationExtractor : IDateTimeExtractor { public static readonly string ExtractorName = Constants.SYS_DATETIME_DURATION; private readonly ICJKDurationExtractorConfiguration config; private readonly bool merge; public BaseCJKDurationExtractor(ICJKDurationExtractorConfiguration config, bool merge = true) { this.config = config; this.merge = merge; } public List<ExtractResult> Extract(string text) { return Extract(text, DateObject.Now); } public List<ExtractResult> Extract(string source, DateObject referenceTime) { // Use Unit to extract var retList = this.config.InternalExtractor.Extract(source); var res = new List<ExtractResult>(); foreach (var ret in retList) { // filter var match = this.config.YearRegex.Match(ret.Text); if (match.Success) { continue; } res.Add(ret); } // handle "all day", "more days", "few days" res.AddRange(ImplicitDuration(source)); res = ExtractResultExtension.MergeAllResults(res); if (this.merge) { res = MergeMultipleDuration(source, res); res = ExtractResultExtension.FilterAmbiguity(res, source, this.config.AmbiguityDurationFiltersDict); } return res; } private List<ExtractResult> MergeMultipleDuration(string text, List<ExtractResult> extractorResults) { if (extractorResults.Count <= 1) { return extractorResults; } var unitMap = this.config.UnitMap; var unitValueMap = this.config.UnitValueMap; var unitRegex = this.config.DurationUnitRegex; List<ExtractResult> ret = new List<ExtractResult>(); var firstExtractionIndex = 0; var timeUnit = 0; var totalUnit = 0; while (firstExtractionIndex < extractorResults.Count) { string curUnit = null; var unitMatch = unitRegex.Match(extractorResults[firstExtractionIndex].Text); if (unitMatch.Success && unitMap.ContainsKey(unitMatch.Groups[Constants.UnitGroupName].ToString())) { curUnit = unitMatch.Groups[Constants.UnitGroupName].ToString(); totalUnit++; if (DurationParsingUtil.IsTimeDurationUnit(unitMap[curUnit])) { timeUnit++; } } if (string.IsNullOrEmpty(curUnit)) { firstExtractionIndex++; continue; } var secondExtractionIndex = firstExtractionIndex + 1; while (secondExtractionIndex < extractorResults.Count) { var valid = false; var midStrBegin = extractorResults[secondExtractionIndex - 1].Start + extractorResults[secondExtractionIndex - 1].Length ?? 0; var midStrEnd = extractorResults[secondExtractionIndex].Start ?? 0; if (midStrBegin > midStrEnd) { return extractorResults; } var midStr = text.Substring(midStrBegin, midStrEnd - midStrBegin); var match = this.config.DurationConnectorRegex.Match(midStr); if (match.Success) { // If the second element of a group is a modifier, it should not be merged with subsequent elements. // For example "4 days or more and 1 week or less" should return 2 separate extractions. if (secondExtractionIndex > 1 && extractorResults[secondExtractionIndex - 1].Metadata != null && extractorResults[secondExtractionIndex - 1].Metadata.HasMod) { break; } unitMatch = unitRegex.Match(extractorResults[secondExtractionIndex].Text); if (unitMatch.Success && unitMap.ContainsKey(unitMatch.Groups[Constants.UnitGroupName].ToString())) { var nextUnitStr = unitMatch.Groups[Constants.UnitGroupName].ToString(); if (unitValueMap[unitMap[nextUnitStr]] != unitValueMap[unitMap[curUnit]]) { valid = true; if (unitValueMap[unitMap[nextUnitStr]] < unitValueMap[unitMap[curUnit]]) { curUnit = nextUnitStr; } } totalUnit++; if (DurationParsingUtil.IsTimeDurationUnit(unitMap[nextUnitStr])) { timeUnit++; } } } if (!valid) { break; } secondExtractionIndex++; } if (secondExtractionIndex - 1 > firstExtractionIndex) { var node = new ExtractResult(); node.Start = extractorResults[firstExtractionIndex].Start; node.Length = extractorResults[secondExtractionIndex - 1].Start + extractorResults[secondExtractionIndex - 1].Length - node.Start; node.Text = text.Substring(node.Start ?? 0, node.Length ?? 0); node.Type = extractorResults[firstExtractionIndex].Type; // Add multiple duration type to extract result string type = Constants.MultipleDuration_DateTime; // Default type if (timeUnit == totalUnit) { type = Constants.MultipleDuration_Time; } else if (timeUnit == 0) { type = Constants.MultipleDuration_Date; } node.Data = type; ret.Add(node); timeUnit = 0; totalUnit = 0; } else { ret.Add(extractorResults[firstExtractionIndex]); } firstExtractionIndex = secondExtractionIndex; } return ret; } private List<ExtractResult> ImplicitDuration(string text) { var ret = new List<Token>(); // handle "all day", "all year" ret.AddRange(Token.GetTokenFromRegex(config.AllRegex, text)); // handle "half day", "half year" ret.AddRange(Token.GetTokenFromRegex(config.HalfRegex, text)); // handle "next day", "last year" ret.AddRange(Token.GetTokenFromRegex(config.RelativeDurationUnitRegex, text)); // handle "more day", "more year" ret.AddRange(Token.GetTokenFromRegex(config.MoreOrLessRegex, text)); // handle "few days", "few months" ret.AddRange(Token.GetTokenFromRegex(config.SomeRegex, text)); // handle "during/for the day/week/month/year" if ((config.Options & DateTimeOptions.CalendarMode) != 0) { ret.AddRange(Token.GetTokenFromRegex(config.DuringRegex, text)); } var result = new List<ExtractResult>(); foreach (var e in ret) { var node = new ExtractResult(); node.Start = e.Start; node.Length = e.Length; node.Text = text.Substring(node.Start ?? 0, node.Length ?? 0); node.Type = ExtractorName; node.Metadata = new Metadata { HasMod = true }; result.Add(node); } return result; } } }
0
0.782103
1
0.782103
game-dev
MEDIA
0.550773
game-dev
0.930391
1
0.930391
jrbudda/Vivecraft_115
1,334
src/org/vivecraft/gameplay/trackers/SneakTracker.java
package org.vivecraft.gameplay.trackers; import org.vivecraft.provider.MCOpenVR; import org.vivecraft.settings.AutoCalibration; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.player.ClientPlayerEntity; public class SneakTracker extends Tracker { public boolean sneakOverride=false; public int sneakCounter = 0; public SneakTracker(Minecraft mc) { super(mc); } public boolean isActive(ClientPlayerEntity p){ if(Minecraft.getInstance().vrSettings.seated) return false; if(!Minecraft.getInstance().vrPlayer.getFreeMove() && !Minecraft.getInstance().vrSettings.simulateFalling) return false; if(!Minecraft.getInstance().vrSettings.realisticSneakEnabled) return false; if(mc.playerController == null) return false; if(p==null || !p.isAlive() || !p.onGround) return false; if(p.isPassenger()) return false; return true; } @Override public void reset(ClientPlayerEntity player) { sneakOverride = false; } public void doProcess(ClientPlayerEntity player){ if(!mc.isGamePaused()) { if (mc.sneakTracker.sneakCounter > 0) mc.sneakTracker.sneakCounter--; } if(( AutoCalibration.getPlayerHeight() - MCOpenVR.hmdPivotHistory.latest().y )> mc.vrSettings.sneakThreshold){ sneakOverride=true; }else{ sneakOverride=false; } } }
0
0.71278
1
0.71278
game-dev
MEDIA
0.723937
game-dev
0.884653
1
0.884653
icsharpcode/NRefactory
7,994
ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/CompilerErrors/ProhibitedModifiersIssue.cs
// // ProhibitedModifiersIssue.cs // // Author: // Mike Krüger <mkrueger@xamarin.com> // // Copyright (c) 2013 Xamarin Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using ICSharpCode.NRefactory.Refactoring; using System.Linq; namespace ICSharpCode.NRefactory.CSharp.Refactoring { [IssueDescription( "Checks for prohibited modifiers", Description = "Checks for prohibited modifiers", Category = IssueCategories.CompilerErrors, Severity = Severity.Error)] public class ProhibitedModifiersIssue : GatherVisitorCodeIssueProvider { protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context) { return new GatherVisitor(context); } class GatherVisitor : GatherVisitorBase<ProhibitedModifiersIssue> { public GatherVisitor(BaseRefactoringContext ctx) : base (ctx) { } readonly Stack<TypeDeclaration> curType = new Stack<TypeDeclaration> (); public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) { curType.Push(typeDeclaration); base.VisitTypeDeclaration(typeDeclaration); curType.Pop(); } void AddStaticRequiredError (EntityDeclaration entity, AstNode node) { AddIssue(new CodeIssue( node, ctx.TranslateString("'static' modifier is required inside a static class"), ctx.TranslateString("Add 'static' modifier"), s => { s.ChangeModifier(entity, (entity.Modifiers & ~(Modifiers.Virtual | Modifiers.Override)) | Modifiers.Static); } )); } void CheckStaticRequired(EntityDeclaration entity) { if (!curType.Peek().HasModifier(Modifiers.Static) || entity.HasModifier(Modifiers.Static) || entity.HasModifier(Modifiers.Const)) return; var fd = entity as FieldDeclaration; if (fd != null) { foreach (var init in fd.Variables) AddStaticRequiredError(entity, init.NameToken); return; } var ed = entity as EventDeclaration; if (ed != null) { foreach (var init in ed.Variables) AddStaticRequiredError(entity, init.NameToken); return; } AddStaticRequiredError(entity, entity.NameToken); } void CheckVirtual(EntityDeclaration entity) { if (!curType.Peek().HasModifier(Modifiers.Static) && !curType.Peek().HasModifier(Modifiers.Sealed) && entity.HasModifier(Modifiers.Virtual)) { if (!entity.HasModifier(Modifiers.Public) && !entity.HasModifier(Modifiers.Protected) && !entity.HasModifier(Modifiers.Internal)) { AddIssue(new CodeIssue( entity.NameToken, ctx.TranslateString("'virtual' members can't be private") )); return; } } if (entity.HasModifier(Modifiers.Sealed) && !entity.HasModifier(Modifiers.Override)) { AddIssue(new CodeIssue( entity.ModifierTokens.First(t => t.Modifier == Modifiers.Sealed), ctx.TranslateString("'sealed' modifier is not usable without override"), ctx.TranslateString("Remove 'sealed' modifier"), s => { s.ChangeModifier(entity, entity.Modifiers & ~Modifiers.Sealed); } )); } if (!curType.Peek().HasModifier(Modifiers.Sealed) || !entity.HasModifier(Modifiers.Virtual)) return; AddIssue(new CodeIssue( entity.ModifierTokens.First(t => t.Modifier == Modifiers.Virtual), ctx.TranslateString("'virtual' modifier is not usable in a sealed class"), ctx.TranslateString("Remove 'virtual' modifier"), s => s.ChangeModifier(entity, entity.Modifiers & ~Modifiers.Virtual) )); } public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration) { CheckStaticRequired(methodDeclaration); CheckVirtual(methodDeclaration); if (methodDeclaration.IsExtensionMethod) { var parent = methodDeclaration.Parent as TypeDeclaration; if (parent != null && !parent.HasModifier(Modifiers.Static)) { var actions = new List<CodeAction>(); var token = methodDeclaration.Parameters.First().FirstChild; actions.Add(new CodeAction( ctx.TranslateString("Make class 'static'"), s => s.ChangeModifier(parent, (parent.Modifiers & ~Modifiers.Sealed) | Modifiers.Static), token )); actions.Add(new CodeAction( ctx.TranslateString("Remove 'this'"), s => s.ChangeModifier(methodDeclaration.Parameters.First(), ParameterModifier.None), token )); AddIssue(new CodeIssue( token, ctx.TranslateString("Extension methods are only allowed in static classes"), actions )); } } base.VisitMethodDeclaration(methodDeclaration); } public override void VisitFieldDeclaration(FieldDeclaration fieldDeclaration) { CheckStaticRequired(fieldDeclaration); base.VisitFieldDeclaration(fieldDeclaration); } public override void VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration) { CheckStaticRequired(fixedFieldDeclaration); base.VisitFixedFieldDeclaration(fixedFieldDeclaration); } public override void VisitEventDeclaration(EventDeclaration eventDeclaration) { CheckStaticRequired(eventDeclaration); base.VisitEventDeclaration(eventDeclaration); } public override void VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration) { CheckStaticRequired(eventDeclaration); CheckVirtual(eventDeclaration); base.VisitCustomEventDeclaration(eventDeclaration); } public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration) { CheckStaticRequired(constructorDeclaration); if (constructorDeclaration.HasModifier(Modifiers.Static)) { if ((constructorDeclaration.Modifiers & Modifiers.Static) != 0) { foreach (var mod in constructorDeclaration.ModifierTokens) { if (mod.Modifier == Modifiers.Static) continue; AddIssue(new CodeIssue( mod, ctx.TranslateString("Static constructors can't have any other modifier"), ctx.TranslateString("Remove prohibited modifier"), s => { s.ChangeModifier(constructorDeclaration, Modifiers.Static); } )); } } } base.VisitConstructorDeclaration(constructorDeclaration); } public override void VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration) { base.VisitDestructorDeclaration(destructorDeclaration); } public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration) { CheckStaticRequired(propertyDeclaration); CheckVirtual(propertyDeclaration); base.VisitPropertyDeclaration(propertyDeclaration); } public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration) { CheckVirtual(indexerDeclaration); base.VisitIndexerDeclaration(indexerDeclaration); } public override void VisitBlockStatement(BlockStatement blockStatement) { // SKIP } } } }
0
0.95272
1
0.95272
game-dev
MEDIA
0.338629
game-dev
0.908029
1
0.908029
VisualGMQ/NickelEngine
4,943
engine/engine/3rdlibs/physx/physx/source/lowlevel/software/include/PxsContactManagerState.h
// 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. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''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 OWNER 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. // // Copyright (c) 2008-2024 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PXS_CONTACT_MANAGER_STATE_H #define PXS_CONTACT_MANAGER_STATE_H #include "foundation/PxSimpleTypes.h" namespace physx { struct PxsShapeCore; /** There is an implicit 1:1 mapping between PxgContactManagerInput and PxsContactManagerOutput. The structures are split because PxgNpContactManagerInput contains constant data that is produced by the CPU code and PxgNpContactManagerOutput contains per-frame contact information produced by the NP. There is also a 1:1 mapping between the PxgNpContactManager and PxsContactManager. This mapping is handled within the PxgNPhaseCore. The previous contact states are implicitly cached in PxsContactManager and will be propagated to the solver. Friction correlation is also done implicitly using cached information in PxsContactManager. The NP will produce a list of pairs that found/lost patches for the solver along with updating the PxgNpContactManagerOutput for all pairs. */ struct PxsContactManagerStatusFlag { enum Enum { eHAS_NO_TOUCH = (1 << 0), eHAS_TOUCH = (1 << 1), //eHAS_SOLVER_CONSTRAINTS = (1 << 2), eREQUEST_CONSTRAINTS = (1 << 3), eHAS_CCD_RETOUCH = (1 << 4), // Marks pairs that are touching at a CCD pass and were touching at discrete collision or at a previous CCD pass already // but we can not tell whether they lost contact in a pass before. We send them as pure eNOTIFY_TOUCH_CCD events to the // contact report callback if requested. eDIRTY_MANAGER = (1 << 5), eTOUCH_KNOWN = eHAS_NO_TOUCH | eHAS_TOUCH, // The touch status is known (if narrowphase never ran for a pair then no flag will be set) eSTATIC_OR_KINEMATIC = (1 << 6) }; }; struct PX_ALIGN_PREFIX(16) PxsContactManagerOutput { PxU8* contactPatches; //Start index/ptr for contact patches PxU8* contactPoints; //Start index/ptr for contact points PxReal* contactForces; //Start index/ptr for contact forces PxU8* frictionPatches; //Contact patches friction information PxU8 allflagsStart; //padding for compatibility with existing code PxU8 nbPatches; //Num patches PxU8 statusFlag; //Status flag (has touch etc.) PxU8 prevPatches; //Previous number of patches PxU16 nbContacts; //Num contacts PxU16 flags; //Not really part of outputs, but we have 4 bytes of padding, so why not? PxU8 pad[8]; PX_FORCE_INLINE PxU32* getInternalFaceIndice() const { return contactForces ? reinterpret_cast<PxU32*>(contactForces + nbContacts) : NULL; } } PX_ALIGN_SUFFIX(16); PX_COMPILE_TIME_ASSERT((sizeof(PxsContactManagerOutput) & 0xf) == 0); struct PX_ALIGN_PREFIX(4) PxsContactManagerOutputCounts { PxU8 nbPatches; //Num patches PxU8 prevPatches; //Previous number of patches PxU8 statusFlag; //Status flag; PxU8 unused; //Unused } PX_ALIGN_SUFFIX(4); struct PX_ALIGN_PREFIX(8) PxsTorsionalFrictionData { PxReal mTorsionalPatchRadius; PxReal mMinTorsionalRadius; PxsTorsionalFrictionData() {} PxsTorsionalFrictionData(const PxReal patchRadius, const PxReal minPatchRadius) : mTorsionalPatchRadius(patchRadius), mMinTorsionalRadius(minPatchRadius) {} } PX_ALIGN_SUFFIX(8); } #endif //PXG_CONTACT_MANAGER_H
0
0.946579
1
0.946579
game-dev
MEDIA
0.509658
game-dev,graphics-rendering
0.884121
1
0.884121
Citadel-Station-13/Citadel-Station-13
1,891
code/modules/vending/medical_wall.dm
/obj/machinery/vending/wallmed name = "\improper NanoMed" desc = "Wall-mounted Medical Equipment dispenser." icon_state = "wallmed" icon_deny = "wallmed-deny" density = FALSE products = list(/obj/item/reagent_containers/syringe = 3, /obj/item/reagent_containers/pill/patch/styptic = 5, /obj/item/reagent_containers/pill/patch/silver_sulf = 5, /obj/item/reagent_containers/medspray/styptic = 2, /obj/item/reagent_containers/medspray/silver_sulf = 2, /obj/item/reagent_containers/pill/charcoal = 2, /obj/item/reagent_containers/medspray/sterilizine = 1, /obj/item/healthanalyzer/wound = 2, /obj/item/stack/medical/bone_gel = 2, /obj/item/stack/medical/nanogel = 2, /obj/item/reagent_containers/syringe/dart = 10) contraband = list(/obj/item/reagent_containers/pill/tox = 2, /obj/item/reagent_containers/pill/morphine = 2) premium = list(/obj/item/reagent_containers/medspray/synthflesh = 2) refill_canister = /obj/item/vending_refill/wallmed default_price = PRICE_FREE extra_price = PRICE_NORMAL payment_department = ACCOUNT_MED tiltable = FALSE light_mask = "wallmed-light-mask" /obj/machinery/vending/wallmed/directional/north dir = SOUTH pixel_y = 32 /obj/machinery/vending/wallmed/directional/south dir = NORTH pixel_y = -32 /obj/machinery/vending/wallmed/directional/east dir = WEST pixel_x = 32 /obj/machinery/vending/wallmed/directional/west dir = EAST pixel_x = -32 /obj/item/vending_refill/wallmed machine_name = "NanoMed" icon_state = "refill_medical" /obj/machinery/vending/wallmed/pubby products = list(/obj/item/reagent_containers/syringe = 3, /obj/item/reagent_containers/pill/patch/styptic = 1, /obj/item/reagent_containers/pill/patch/silver_sulf = 1, /obj/item/reagent_containers/medspray/sterilizine = 1) premium = list(/obj/item/reagent_containers/medspray/synthflesh = 2)
0
0.626241
1
0.626241
game-dev
MEDIA
0.986356
game-dev
0.517599
1
0.517599
o3de/o3de-extras
4,692
Gems/SimulationInterfaces/Code/Include/SimulationInterfaces/SimulationMangerRequestBus.h
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include "SimulationInterfacesTypeIds.h" #include <AzCore/Outcome/Outcome.h> #include "Result.h" #include <AzCore/EBus/EBus.h> #include <AzCore/Interface/Interface.h> #include <AzCore/std/smart_ptr/shared_ptr.h> #include <AzFramework/Physics/ShapeConfiguration.h> #include <simulation_interfaces/msg/simulation_state.hpp> namespace SimulationInterfaces { using SimulationState = simulation_interfaces::msg::SimulationState::_state_type; class SimulationManagerRequests { public: AZ_RTTI(SimulationManagerRequests, SimulationManagerRequestsTypeId); virtual ~SimulationManagerRequests() = default; using ReloadLevelCallback = AZStd::function<void(void)>; //! Reload level and remove all spawned simulation entities. virtual AZ::Outcome<void, FailedResult> ResetSimulation(ReloadLevelCallback completionCallback) = 0; //! Set the simulation to paused or unpaused, //! expect always to succeed virtual void SetSimulationPaused(bool paused) = 0; //! Step the simulation by a number of steps //! expect always to succeed virtual void StepSimulation(AZ::u64 steps) = 0; //! Check whether the simulation is paused or not //! @return boolean value indicating the pause state of the simulation virtual bool IsSimulationPaused() const = 0; //! Cancel executing the simulation steps, if there are remaining steps left virtual void CancelStepSimulation() = 0; //! Check if the SimulationSteps is active //! @return boolean value indicating if the SimulationSteps is active virtual bool IsSimulationStepsActive() const = 0; //! Get current simulation state //! @return enum value indicating simulation state based on //! https://github.com/ros-simulation/simulation_interfaces/blob/main/msg/SimulationState.msg virtual SimulationState GetSimulationState() const = 0; //! Set simulation state //! @param stateToSet id of the next state to set, based on //! https://github.com/ros-simulation/simulation_interfaces/blob/main/msg/SimulationState.msg //! @return outcome indicating if setting state succeed. In case of failure error message with error code is returned virtual AZ::Outcome<void, FailedResult> SetSimulationState(SimulationState stateToSet) = 0; //! Check if it possible to work with entities. These operations should be possible only if world is loaded //! @return bool indicating if simulator is ready for taking requests related to spawning/despawning setting entity state etc virtual bool EntitiesOperationsPossible() = 0; }; class SimulationMangerRequestBusTraits : public AZ::EBusTraits { public: ////////////////////////////////////////////////////////////////////////// // EBusTraits overrides static constexpr AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; static constexpr AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; ////////////////////////////////////////////////////////////////////////// }; using SimulationManagerRequestBus = AZ::EBus<SimulationManagerRequests, SimulationMangerRequestBusTraits>; using SimulationManagerRequestBusInterface = AZ::Interface<SimulationManagerRequests>; class SimulationManagerNotifications { public: AZ_RTTI(SimulationManagerNotifications, SimulationManagerNotificationsTypeId); virtual ~SimulationManagerNotifications() = default; //! Notify about simulation step finish //! @param remainingSteps - remaining steps to pause simulation virtual void OnSimulationStepFinish(const AZ::u64 remainingSteps) = 0; }; class SimulationMangerNotificationsBusTraits : public AZ::EBusTraits { public: ////////////////////////////////////////////////////////////////////////// // EBusTraits overrides static constexpr AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; static constexpr AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; ////////////////////////////////////////////////////////////////////////// }; using SimulationManagerNotificationsBus = AZ::EBus<SimulationManagerNotifications, SimulationMangerNotificationsBusTraits>; } // namespace SimulationInterfaces
0
0.736457
1
0.736457
game-dev
MEDIA
0.560884
game-dev
0.713423
1
0.713423
nasa/World-Wind-Java
27,956
WorldWind/src/gov/nasa/worldwind/util/BasicQuadTree.java
/* * Copyright (C) 2011 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. * All Rights Reserved. */ package gov.nasa.worldwind.util; import gov.nasa.worldwind.geom.*; import gov.nasa.worldwind.terrain.*; import java.util.*; /** * Implements a quadtree backed by a bit-set index. A bit-set provides a minimal-memory index. Each bit identifies one * cell in the quadtree. * <p/> * This class provides methods to add and remove items from the quadtree, and to determine the items intersecting * specified regions. * <p/> * Items can be added with an associated name, and can be retrieved and removed by name. * * @author tag * @version $Id$ */ public class BasicQuadTree<T> extends BitSetQuadTreeFilter implements Iterable<T> { protected ArrayList<double[]> levelZeroCells; protected Map<String, List<T>> items; // the tree's list of items protected T currentItem; // used during add() to pass the added item to doOperation(). protected String currentName; // used during add() to pass the optional name of the added item to doOperation(). protected HashMap<String, T> nameMap = new HashMap<String, T>(); // maps names to items /** * Constructs a quadtree of a specified level and spanning a specified region. * <p/> * The number of levels in the quadtree must be specified to the constructor. The more levels there are the more * discriminating searches will be, but at the cost of some performance because more cells are searched. For the * Earth, a level count of 8 provides leaf cells about 75 km along their meridian edges (edges of constant Earth, a * level count of 8 provides leaf cells about 75 km along their meridian edges (edges of constant longitude). * Additional levels successfully halve the distance, fewer levels double that distance. * * @param numLevels the number of levels in the quadtree. The more levels there are the more discriminating searches * will be, but at the cost of some performance. * @param sector the region the tree spans. * @param itemMap a {@link Map} to hold the items added to the quadtree. May be null, in which case a new map is * created. * * @throws IllegalArgumentException if <code>numLevels</code> is less than 1. */ public BasicQuadTree(int numLevels, Sector sector, Map<String, List<T>> itemMap) { super(numLevels, null); if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.makeLevelZeroCells(sector); this.items = itemMap != null ? itemMap : new HashMap<String, List<T>>(); } /** * Creates the quadtree's level-zero cells. * * @param sector the sector to subdivide to create the cells. */ protected void makeLevelZeroCells(Sector sector) { Sector[] subSectors = sector.subdivide(); this.levelZeroCells = new ArrayList<double[]>(4); this.levelZeroCells.add(subSectors[0].asDegreesArray()); this.levelZeroCells.add(subSectors[1].asDegreesArray()); this.levelZeroCells.add(subSectors[3].asDegreesArray()); this.levelZeroCells.add(subSectors[2].asDegreesArray()); } /** * Indicates whether the tree contains any items. * * @return true if the tree contains items, otherwise false. */ synchronized public boolean hasItems() { return !this.items.isEmpty(); } /** * Indicates whether an item is contained in the tree. * * @param item the item to check. If null, false is returned. * * @return true if the item is in the tree, otherwise false. */ synchronized public boolean contains(T item) { if (item == null) return false; for (Map.Entry<String, List<T>> entry : this.items.entrySet()) { List<T> itemList = entry.getValue(); if (itemList == null) continue; if (itemList.contains(item)) return true; } return false; } /** * Add a named item to the quadtree. Any item duplicates are duplicated in the tree. Any name duplicates replace the * current name assocation; the name then refers to the item added. * * @param item the item to add. * @param itemCoords an array specifying the region or location of the item. If the array's length is 2 it * represents a location in [latitude, longitude]. If its length is 4 it represents a region, with * the same layout as the <code>nodeRegion</code> argument. * @param itemName the item name. If null, the item is added without a name. * * @throws IllegalArgumentException if either <code>item</code> or <code>itemCoords</code> is null. */ synchronized public void add(T item, double[] itemCoords, String itemName) { this.addItem(item, itemCoords, itemName); } /** * Add an item to the quadtree. Any duplicates are duplicated in the tree. * * @param item the item to add. * @param itemCoords an array specifying the region or location of the item. If the array's length is 2 it * represents a location in [latitude, longitude]. If its length is 4 it represents a region, with * the same layout as the <code>nodeRegion</code> argument. * * @throws IllegalArgumentException if either <code>item</code> or <code>itemCoords</code> is null. */ synchronized public void add(T item, double[] itemCoords) { this.addItem(item, itemCoords, null); } protected void addItem(T item, double[] itemCoords, String name) { if (item == null) { String message = Logging.getMessage("nullValue.ItemIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (itemCoords == null) { String message = Logging.getMessage("nullValue.CoordinatesAreNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.currentItem = item; this.currentName = name; for (int i = 0; i < levelZeroCells.size(); i++) { this.testAndDo(0, i, levelZeroCells.get(i), itemCoords); } } /** * Removes an item from the tree. * <p/> * <em>Note:</em> For large collections, this can be an expensive operation. * * @param item the item to remove. If null, no item is removed. */ synchronized public void remove(T item) { if (item == null) return; List<String> bitsToClear = new ArrayList<String>(); for (Map.Entry<String, List<T>> entry : this.items.entrySet()) { List<T> itemList = entry.getValue(); if (itemList == null) continue; if (itemList.contains(item)) itemList.remove(item); if (itemList.size() == 0) bitsToClear.add(entry.getKey()); } for (String bitNum : bitsToClear) { this.bits.clear(Integer.parseInt(bitNum)); } } /** * Removes an item from the tree by name. * <p/> * <em>Note:</em> For large collections, this can be an expensive operation. * * @param name the name of the item to remove. If null, no item is removed. */ synchronized public void removeByName(String name) { T item = this.getByName(name); this.nameMap.remove(name); if (item == null) return; for (Map.Entry<String, List<T>> entry : this.items.entrySet()) { List<T> itemList = entry.getValue(); if (itemList == null) continue; if (itemList.contains(item)) itemList.remove(item); } } /** Removes all items from the tree. */ synchronized public void clear() { this.items.clear(); this.bits.clear(); } /** * Returns a named item. * * @param name the item name. If null, null is returned. * * @return the named item, or null if the item is not in the tree or the specified name is null. */ synchronized public T getByName(String name) { return name != null ? this.nameMap.get(name) : null; } /** * Returns an iterator over the items in the tree. There is no specific iteration order. * <p/> * <em>Note</em> The {@link java.util.Iterator#remove()} operation is not supported. * * @return an iterator over the items in the tree. */ synchronized public Iterator<T> iterator() { return new Iterator<T>() { // The items are stored in lists associated with each cell (each bit of the bit-set), so two internal // iterators are needed: one for the map of populated cells and one for a cell's list of items. private Iterator<List<T>> mapIterator; private Iterator<T> listIterator; private T nextItem; { // constructor mapIterator = BasicQuadTree.this.items.values().iterator(); } /** {@inheritDoc} **/ public boolean hasNext() { // This is the only method that causes the list to increment, so call it before every call to next(). if (this.nextItem != null) return true; this.moveToNextItem(); return this.nextItem != null; } /** {@inheritDoc} **/ public T next() { if (!this.hasNext()) throw new NoSuchElementException("Iteration has no more elements."); T lastNext = this.nextItem; this.nextItem = null; return lastNext; } /** * This operation is not supported and will produce a {@link UnsupportedOperationException} if invoked. */ public void remove() { throw new UnsupportedOperationException("The remove() operations is not supported by this Iterator."); } private void moveToNextItem() { // Use the next item in a cell's item list, if there is an item list and it has a next item. if (this.listIterator != null && this.listIterator.hasNext()) { this.nextItem = this.listIterator.next(); return; } // Find the next map entry with a non-null item list. Use the first item in that list. this.listIterator = null; while (this.mapIterator.hasNext()) { if (this.mapIterator.hasNext()) this.listIterator = this.mapIterator.next().iterator(); if (this.listIterator != null && this.listIterator.hasNext()) { this.nextItem = this.listIterator.next(); return; } } } }; } /** * Finds and returns the items within a tree cell containing a specified location. * * @param location the location of interest. * @param outItems a {@link Set} in which to place the items. If null, a new set is created. * * @return the set of intersecting items. The same set passed as the <code>outItems</code> argument is returned, or * a new set if that argument is null. * * @throws IllegalArgumentException if <code>location</code> is null. */ synchronized public Set<T> getItemsAtLocation(LatLon location, Set<T> outItems) { if (location == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FindIntersectingBitsOp op = new FindIntersectingBitsOp(this); List<Integer> bitIds = op.getOnBits(this.levelZeroCells, location.asDegreesArray(), new ArrayList<Integer>()); return this.buildItemSet(bitIds, outItems); } /** * Finds and returns the items within tree cells containing specified locations. * * @param locations the locations of interest. * @param outItems a {@link Set} in which to place the items. If null, a new set is created. * * @return the set of intersecting items. The same set passed as the <code>outItems</code> argument is returned, or * a new set if that argument is null. * * @throws IllegalArgumentException if <code>locations</code> is null. */ synchronized public Set<T> getItemsAtLocation(Iterable<LatLon> locations, Set<T> outItems) { if (locations == null) { String message = Logging.getMessage("nullValue.LatLonListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FindIntersectingBitsOp op = new FindIntersectingBitsOp(this); List<Integer> bitIds = new ArrayList<Integer>(); for (LatLon location : locations) { if (location != null) bitIds = op.getOnBits(this.levelZeroCells, location.asDegreesArray(), bitIds); } return this.buildItemSet(bitIds, outItems); } /** * Finds and returns the items intersecting a specified sector. * * @param testSector the sector of interest. * @param outItems a {@link Set} in which to place the items. If null, a new set is created. * * @return the set of intersecting items. The same set passed as the <code>outItems</code> argument is returned, or * a new set if that argument is null. * * @throws IllegalArgumentException if <code>testSector</code> is null. */ synchronized public Set<T> getItemsInRegion(Sector testSector, Set<T> outItems) { if (testSector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FindIntersectingBitsOp op = new FindIntersectingBitsOp(this); List<Integer> bitIds = op.getOnBits(this.levelZeroCells, testSector, new ArrayList<Integer>()); return this.buildItemSet(bitIds, outItems); } /** * Finds and returns the items intersecting a specified collection of sectors. * * @param testSectors the sectors of interest. * @param outItems a {@link Set} in which to place the items. If null, a new set is created. * * @return the set of intersecting items. The same set passed as the <code>outItems</code> argument is returned, or * a new set if that argument is null. * * @throws IllegalArgumentException if <code>testSectors</code> is null. */ public Set<T> getItemsInRegions(Iterable<Sector> testSectors, Set<T> outItems) { if (testSectors == null) { String message = Logging.getMessage("nullValue.SectorListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FindIntersectingBitsOp op = new FindIntersectingBitsOp(this); List<Integer> bitIds = new ArrayList<Integer>(); for (Sector testSector : testSectors) { if (testSector != null) bitIds = op.getOnBits(this.levelZeroCells, testSector, bitIds); } return this.buildItemSet(bitIds, outItems); } /** * Finds and returns the items intersecting a specified collection of {@link gov.nasa.worldwind.terrain.SectorGeometry}. * This method is a convenience for finding the items intersecting the current visible regions. * * @param geometryList the list of sector geometry. * @param outItems a {@link Set} in which to place the items. If null, a new set is created. * * @return the set of intersecting items. The same set passed as the <code>outItems</code> argument is returned, or * a new set if that argument is null. * * @throws IllegalArgumentException if <code>geometryList</code> is null. */ synchronized public Set<T> getItemsInRegions(SectorGeometryList geometryList, Set<T> outItems) { if (geometryList == null) { String message = Logging.getMessage("nullValue.SectorGeometryListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FindIntersectingBitsOp op = new FindIntersectingBitsOp(this); List<Integer> bitIds = new ArrayList<Integer>(); for (SectorGeometry testSector : geometryList) { if (testSector != null) bitIds = op.getOnBits(this.levelZeroCells, testSector.getSector(), bitIds); } return this.buildItemSet(bitIds, outItems); } /** * Adds the items identified by a list of bit IDs to the set returned by the get methods. * * @param bitIds the bit numbers of the cells containing the items to return. * @param outItems a {@link Set} in which to place the items. If null, a new set is created. * * @return the set of items. The value passed as the <code>outItems</code> is returned. */ protected Set<T> buildItemSet(List<Integer> bitIds, Set<T> outItems) { if (outItems == null) outItems = new HashSet<T>(); if (bitIds == null) return outItems; for (Integer id : bitIds) { List<T> regionItems = this.items.get(id.toString()); if (regionItems == null) continue; for (T item : regionItems) { outItems.add(item); } } return outItems; } /** * Performs the add operation of the quadtree. * * @param level the quadtree level currently being traversed. * @param position the position of the cell in its parent cell, either 0, 1, 2, or 3. Cell positions starts with 0 * at the southwest corner of the parent cell and increment counter-clockwise: cell 1 is SE, cell * 2 is NE and cell 3 is NW. * @param cellRegion an array specifying the coordinates of the cell's region. The first two entries are the minimum * and maximum values on the Y axis (typically latitude). The last two entries are the minimum and * maximum values on the X axis, (typically longitude). * @param itemCoords an array specifying the region or location of the intersecting item. If the array's length is 2 * it represents a location in [latitude, longitude]. If its length is 4 it represents a region, * with the same layout as the <code>nodeRegion</code> argument. * * @return true if traversal should continue to the cell's descendants, false if traversal should not continue to * the cell's descendants. */ protected boolean doOperation(int level, int position, double[] cellRegion, double[] itemCoords) { int bitNum = this.computeBitPosition(level, position); this.bits.set(bitNum); if (level < this.maxLevel) return true; String bitName = Integer.toString(bitNum); List<T> regionItems = this.items.get(bitName); if (regionItems == null) { regionItems = new ArrayList<T>(); this.items.put(bitName, regionItems); } regionItems.add(this.currentItem); if (this.currentName != null) this.nameMap.put(this.currentName, this.currentItem); return false; } ////////////////////// ONLY TEST CODE BELOW //////////////////////////////////////////// // public static void main(String[] args) // { //// basicTest(); //// iteratorTest(); //// perfTestVisit(); // perfTestFind(); // } // // public abstract static class PerfTestRunner // { // protected abstract void doOp(); // // protected int numIterations; // // protected long run(int numIterations) // { // this.numIterations = numIterations; // long start = System.currentTimeMillis(); // // for (int i = 0; i < numIterations; i++) // { // this.doOp(); // } // // return System.currentTimeMillis() - start; // } // // public void print(long elapsedTime) // { // System.out.printf("Elapsed time for %d iterations = %d milliseconds\n", this.numIterations, elapsedTime); // } // } // // protected static void basicTest() // { // final int treeDepth = 8; // // HashMap<String, List<String>> map = new HashMap<String, List<String>>(); // final BasicQuadTree<String> tree = new BasicQuadTree<String>(treeDepth, Sector.FULL_SPHERE, map); // // LatLon ll = LatLon.fromDegrees(0, 0); // tree.add(ll.toString(), ll.asDegreesArray()); // // ll = LatLon.fromDegrees(40, 50); // tree.add(ll.toString(), ll.asDegreesArray()); // // ll = LatLon.fromDegrees(-60, -80); // tree.add(ll.toString(), ll.asDegreesArray()); // // Set<String> items = tree.getItemsInRegion(Sector.fromDegrees(0, 45, 0, 55), new HashSet<String>()); // // System.out.printf("Tree depth %d, %d items found\n", treeDepth, items.size()); // // for (String item : items) // { // System.out.println(item); // } // } // // protected static void perfTestVisit() // { // VisitOp filter = new VisitOp<String>(10, Sector.FULL_SPHERE); // // long start = System.currentTimeMillis(); // for (int i = 0; i < 10; i++) // { // filter.visit(Sector.FULL_SPHERE); // } // long end = System.currentTimeMillis(); // // System.out.println( // "DONE " + filter.bits.cardinality() + " bits set in " + (end - start) / 10 + " milliseconds"); // } // // // protected static void perfTestFind() // { // final int treeDepth = 8; // // Map<String, List<String>> map = new HashMap<String, List<String>>(); // final BasicQuadTree<String> tree = new BasicQuadTree<String>(treeDepth, Sector.FULL_SPHERE, map); // // LatLon ll = LatLon.fromDegrees(0, 0); // tree.add(ll.toString(), ll.asDegreesArray()); // // ll = LatLon.fromDegrees(40, 50); // tree.add(ll.toString(), ll.asDegreesArray()); // // ll = LatLon.fromDegrees(-60, -80); // tree.add(ll.toString(), ll.asDegreesArray()); // // int count = 0; // for (double lat = -45; lat <= 45; lat += 0.25) // { // for (double lon = 6; lon <= 100; lon += 0.25) // { // ll = LatLon.fromDegrees(lat, lon); // tree.add(ll.toString(), ll.asDegreesArray()); // ++count; //// if (lat >= 1 && lat <= 5 && lon >= 1 && lon <= 5) //// System.out.println(ll); // } // } // // final int finalCount = count; // PerfTestRunner runner = new PerfTestRunner() // { // public Set<String> items; // // protected void doOp() // { // this.items = tree.getItemsInRegion(Sector.fromDegrees(-22, 22, 6, 54), new HashSet<String>()); // } // // @Override // public void print(long elapsedMillis) // { // System.out.printf("Tree depth %d, %d locations in tree, %d items found\n", // treeDepth, finalCount, items.size()); // super.print(elapsedMillis); // //// for (String item : this.items) //// { //// System.out.println(item); //// } // } // }; // System.out.println("STARTING"); // runner.print(runner.run(100)); // } // // protected static void iteratorTest() // { // final int treeDepth = 8; // // HashMap<String, List<String>> map = new HashMap<String, List<String>>(); // final BasicQuadTree<String> tree = new BasicQuadTree<String>(treeDepth, Sector.FULL_SPHERE, map); // // int count = 0; // for (double lat = -5; lat <= 5; lat += 1) // { // for (double lon = 5; lon <= 10; lon += 1) // { // LatLon ll = LatLon.fromDegrees(lat, lon); // tree.add(ll.toString(), ll.asDegreesArray()); // ++count; // } // } // // int actualCount = 0; // for (String s : tree) // { // ++actualCount; // System.out.println(s); // } // // System.out.printf("Actual count (%d) == Total count (%d): %b\n", actualCount, count, (actualCount == count)); // } // // /** // * A test class that prints the set bits in the quadtree. // * @param <T> the item type. // */ // protected static class PrintBitsOp<T> extends BasicQuadTree<T> // { // public PrintBitsOp(int maxLevel) // { // super(maxLevel, Sector.FULL_SPHERE, null); // } // // protected boolean doOperation(int level, int position, double[] nodeRegion, double[] testRegion) // { // int bitNum = this.computeBitPosition(level, position); // // this.bits.set(bitNum); // // System.out.printf("Level %d, %s, Position %d\n", level, this.makePathString(this.path, level), bitNum); // // return level < this.maxLevel; // } // // private String makePathString(int[] path, int endIndex) // { // StringBuilder sb = new StringBuilder(); // // for (int i = 0; i <= endIndex; i++) // { // sb.append(Integer.toString(path[i])); // } // // return sb.toString(); // } // // public void printBits() // { // for (int i = 0; i < levelZeroCells.size(); i++) // { // this.testAndDo(0, i, levelZeroCells.get(i), Sector.FULL_SPHERE.asDegreesArray()); // } // } // } // // /** // * A test class that visits all the cells in the quadtree and sets their bit in the bit-set. // * @param <T> the item type. // */ // protected static class VisitOp<T> extends BasicQuadTree<T> // { // public VisitOp(int maxLevel, Sector region) // { // super(maxLevel, region, null); // } // // protected boolean doOperation(int level, int position, double[] nodeRegion, double[] testRegion) // { // int bitNum = this.computeBitPosition(level, position); // // this.bits.set(bitNum); // // return level < this.maxLevel; // } // // public void visit(Sector sector) // { // for (int i = 0; i < levelZeroCells.size(); i++) // { // this.testAndDo(0, i, levelZeroCells.get(i), sector.asDegreesArray()); // } // } // } }
0
0.966322
1
0.966322
game-dev
MEDIA
0.476763
game-dev
0.989941
1
0.989941
LiteLDev/LeviLamina
1,451
src-server/mc/world/level/levelgen/feature/helpers/tree_helper/TreeHelper.h
#pragma once #include "mc/_HeaderOutputPredefine.h" // auto generated forward declare list // clang-format off class Block; class BlockDescriptor; class BlockPos; class IBlockWorldGenAPI; class Random; namespace TreeHelper { struct TreeParams; } // clang-format on namespace TreeHelper { // functions // NOLINTBEGIN MCAPI bool isValidTreePosition( ::IBlockWorldGenAPI const& target, ::BlockPos const& pos, ::TreeHelper::TreeParams const& treeParams ); MCAPI ::std::optional<::BlockPos> placeBaseBlock( ::IBlockWorldGenAPI& target, ::BlockPos const& pos, ::std::vector<::BlockDescriptor> const& validBaseBlocks ); MCAPI ::std::optional<::BlockPos> placeRadialBlockGroup( ::IBlockWorldGenAPI& target, ::BlockPos const& pos, ::Random&, ::Block const& block, int radius, int coreWidth, bool simplify, ::std::vector<::BlockDescriptor> const& mayGrowThrough ); MCAPI bool prepareSpawn( ::IBlockWorldGenAPI const& target, ::BlockPos const& pos, int treeHeight, ::std::vector<::BlockDescriptor> const& mayGrowOn, ::std::vector<::BlockDescriptor> const& mayGrowThrough ); // NOLINTEND } // namespace TreeHelper
0
0.922702
1
0.922702
game-dev
MEDIA
0.284947
game-dev
0.634934
1
0.634934
osgcc/ryzom
10,388
nel/include/nel/pacs/u_move_container.h
// NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/> // Copyright (C) 2010 Winch Gate Property Limited // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef NL_U_MOVE_CONTAINER_H #define NL_U_MOVE_CONTAINER_H #include "nel/misc/types_nl.h" #include "nel/misc/vector.h" #include <vector> namespace NLMISC { class CVectorD; class CMatrix; } namespace NLPACS { class UMovePrimitive; class UTriggerInfo; class UGlobalRetriever; class UPrimitiveBlock; #define NELPACS_DEFAULT_OT_SIZE 100 #define NELPACS_DEFAULT_MAX_TEST_ITERATION 100 #define NELPACS_DEFAULT_NUM_WORLD_IMAGE 1 /** * A container for movable objects * Some constraints: * * The move bounding box must be lower than the cell size * * \author Cyril 'Hulud' Corvazier * \author Nevrax France * \date 2001 */ class UMoveContainer { public: /** * destructor */ virtual ~UMoveContainer () { } /// \name Manage primitives. /** * Add a collisionable primitive in the container. Return the pointer on the primitive. * This primitive will generate collisions when the system evaluate other primitives against. * * You must specify the ids of each world image where the primitive can be inserted. * Thoses ids are consecutives. If you choose 5 as first id and 3 as id count, * this primitive could be inserted in the world image #5, #6 and #7. * * This primtive should be inserted in a world image before use. See UMovePrimitive::insertInWorldImage. * * \param firstWorldImage is the first world image where the primitive can be inserted. * \param numWorldImage is the count of world image where the primitive can be inserted. * \return a pointer on the new primitive. */ virtual UMovePrimitive *addCollisionablePrimitive (uint8 firstWorldImage, uint8 numWorldImage, const UMovePrimitive *copyFrom = NULL) =0; /** * Add a noncollisionable primitive in the container. Return the pointer on the primitive. * This primitive won't generate collisions when the system evaluate other primitives against. * * This primitive can't be inserted in a world image. * * \param copyFrom is an optional primitive to copy attributes from (so the primitive is initialised with same values) * \return a pointer on the new primitive. */ virtual UMovePrimitive *addNonCollisionablePrimitive (const UMovePrimitive *copyFrom = NULL) =0; /** * Load a PACS primitive block. (*.pacs_prim) * * Add a set of collisionable primitive in the container. If success, fill an array with primitives's pointers. * The primitive are inserted in the requested world image of the container. Then a setGlobalPosition * is done to place the primitives in the world image. The world images are not evaluated. * * You must specify the ids of each world image where the primitives can be inserted. * Thoses ids are consecutives. If you choose 5 as first id and 3 as id count, * those primitives could be inserted in the world image #5, #6 and #7. * * Those primtives should be inserted in a world image before use. See UMovePrimitive::insertInWorldImage. * * Return false if the world image numbers are not present in the move container. * * Can raise unhandled NLMISC::Exception if trouble during serialisation. * * \param filename is the file to load. * \param firstWorldImage is the first world image where the primitive can be inserted. * \param numWorldImage is the count of world image where the primitive can be inserted. * \param primitives is a pointer on an array of primitive pointer to fill if success. If NULL, Do return nothing. * \param orientation is the orientation to give to the primitives. * \param position is the position to give to the primitives. * \param primitives is a pointer on an array of primitive pointer to fill if success. If NULL, Do return nothing. * \param dontSnapToGround force the inserted primitive to be flagged as 'DontSnapToGround' * \see addCollisionablePrimitive * \see getPACSCoordsFromMatrix * \return true if the file is successfully loaded, else return false. */ virtual bool loadCollisionablePrimitiveBlock (const char *filename, uint8 firstWorldImage, uint8 numWorldImage, std::vector<UMovePrimitive*> *primitives, float orientation, const NLMISC::CVector &position, bool dontSnapToGround = false) =0; /** The same as loadCollisionablePrimitiveBlock, but the primitive block is provided by the caller */ virtual void addCollisionnablePrimitiveBlock(UPrimitiveBlock *pb, uint8 firstWorldImage, uint8 numWorldImage, std::vector<UMovePrimitive*> *primitives, float orientation, const NLMISC::CVector &position, bool dontSnapToGround = false, const NLMISC::CVector &scale = NLMISC::CVector(1.0f, 1.0f, 1.0f)) = 0; /** * Remove a primitive from the container. * * \param primitive is the pointer on the primitive to remove. */ virtual void removePrimitive (UMovePrimitive* primitive) =0; /// Get all the primitives in the container virtual void getPrimitives(std::vector<const UMovePrimitive *> &dest) const = 0; /// \name Primitive evaluation. /** * Evaluation of a worldImage of the collision system. * This method will evaluate the move of each modified collisionable primitives inserted in the world image. * The method first test collisions against the terrain, then test collisions against primitives * inserted in the world images declared as static, * then test collisions against the primitives inserted in the world image to evaluate. * * \param deltaTime is the delta time of the system evaluation. * \param worldImage is the world image to eval. */ virtual void evalCollision (double deltaTime, uint8 worldImage) =0; /** * Evaluation of a single non collisionable primitive. * The method first test collisions against the terrain, then test collisions against primitives * inserted in the world images declared as static, * then test collisions against the primitives inserted in the world image to evaluate. * * \param deltaTime is the delta time of the system evaluation. * \param primitive is the primitive pointer * \param worldImage is the world image to eval. * \return false if the primitive is a collisionable primitive. */ virtual bool evalNCPrimitiveCollision (double deltaTime, UMovePrimitive *primitive, uint8 worldImage) = 0; /** * Test the move of a primitive in a specific world image. * * This method will test the move of each modified primitives inserted in the world image. * The method will first test collisions against primitives inserted in the world images declared as static, * then test collisions against the primitives inserted in the world image choosed to test the move of the primitive. * * \param primitive is a pointer on the primitive * \param speed is the wanted speed of the primitive * \param deltaTime is the deltaTime of the move of the primitive. * \param worldImage is the world image where you want to test the move of the primitive. * \param contactNormal is a pointer to CVectorD to store contactNormal with terrain, if not NULL * \return true if the move is successful, false else. */ virtual bool testMove (UMovePrimitive* primitive, const NLMISC::CVectorD& speed, double deltaTime, uint8 worldImage, NLMISC::CVectorD *contactNormal) =0; /// \name World image management. /** * Set world image as static world image. * * This method set this world image as static. It means that primitives inserted there don't move. * Each primitive evaluation methods will first test all the primitives in the world images declared as static. * Then, the evalutation test the primtive in the asked worldImage. * * \param worldImage is the id of the world image to set as static. */ virtual void setAsStatic (uint8 worldImage) =0; /** * Duplicate a world image in another. * * All primitive will be removed from the destination world image. * Then, the source world image will be copied in the destination world image. * * Warning, only primitives from the source that have been declared as using the destination * world image will be copied. * * The source world image remain the same. * * \param source is the id of the source world image for the copy. * \param dest is the id of the destination world image for the copy. */ virtual void duplicateWorldImage (uint8 source, uint8 dest) =0; /// \name Triggers info. /// Get number of trigger information virtual uint getNumTriggerInfo() const=0; /// Get the n-th trigger information virtual const UTriggerInfo &getTriggerInfo (uint id) const=0; /// \name Create methods. // Create method static UMoveContainer *createMoveContainer (double xmin, double ymin, double xmax, double ymax, uint widthCellCount, uint heightCellCount, double primitiveMaxSize, uint8 numWorldImage=NELPACS_DEFAULT_NUM_WORLD_IMAGE, uint maxIteration=NELPACS_DEFAULT_MAX_TEST_ITERATION, uint otSize=NELPACS_DEFAULT_OT_SIZE); // Create method static UMoveContainer *createMoveContainer (UGlobalRetriever* retriever, uint widthCellCount, uint heightCellCount, double primitiveMaxSize, uint8 numWorldImage=NELPACS_DEFAULT_NUM_WORLD_IMAGE, uint maxIteration=NELPACS_DEFAULT_MAX_TEST_ITERATION, uint otSize=NELPACS_DEFAULT_OT_SIZE); // Delete method static void deleteMoveContainer (UMoveContainer *container); /** Get a pacs position and an orientation from a matrix */ static void getPACSCoordsFromMatrix(NLMISC::CVector &pos, float &angle, const NLMISC::CMatrix &mat); }; } // NLPACS #endif // NL_U_MOVE_CONTAINER_H /* End of u_move_container.h */
0
0.652243
1
0.652243
game-dev
MEDIA
0.808018
game-dev
0.706653
1
0.706653
ErnSur/QuickEye-Utility
3,693
Editor/EditorColorPaletteWindow.cs
using System; using System.Collections.Generic; using UnityEditor; using UnityEditor.IMGUI.Controls; using UnityEngine; using static UnityEditor.EditorGUILayout; namespace QuickEye.Utility.Editor { internal class EditorColorPaletteWindow : EditorWindow { [MenuItem("Window/Editor Color Palette")] public static void OpenWindow() { GetWindow<EditorColorPaletteWindow>(); } [SerializeField] private EditorColorPalette light = EditorColorPalette.Light; [SerializeField] private EditorColorPalette dark = EditorColorPalette.Dark; [SerializeField] private Vector2 scrollPos; [SerializeField] private bool isDarkSkinSelected; [SerializeField] private bool initialized; [SerializeField] private string searchString; private SearchField _searchField; private void OnEnable() { UpdateTitle(); if (!initialized) { isDarkSkinSelected = EditorGUIUtility.isProSkin; initialized = true; } _searchField = new SearchField(); } private void UpdateTitle() { try { var iconContent = EditorGUIUtility.IconContent("SceneViewRGB"); titleContent = iconContent; } catch { } titleContent.text = "Editor Color Palette"; } private void OnGUI() { using (new HorizontalScope(EditorStyles.toolbar)) { isDarkSkinSelected = !GUILayout.Toggle(!isDarkSkinSelected, "Light", EditorStyles.toolbarButton); isDarkSkinSelected = GUILayout.Toggle(isDarkSkinSelected, "Dark", EditorStyles.toolbarButton); } searchString = _searchField.OnGUI(searchString); var so = new SerializedObject(this); var prop = so.FindProperty(isDarkSkinSelected ? nameof(dark) : nameof(light)); EditorGUIUtility.labelWidth = 270; using (var scrollScope = new ScrollViewScope(scrollPos)) { foreach (var property in GetPropChildren(prop)) { var label = GetDisplayNameOfPropertyBackingField(property.displayName); if (!string.IsNullOrWhiteSpace(searchString) && !label.ToUpperInvariant().Contains(searchString.ToUpperInvariant())) continue; PropertyField(property, new GUIContent(label)); } scrollPos = scrollScope.scrollPosition; } } private static string GetDisplayNameOfPropertyBackingField(string backingFieldName) { const int indexOfLessThanSign = 1; if (backingFieldName.StartsWith("<", StringComparison.CurrentCulture)) { backingFieldName = backingFieldName.Substring(indexOfLessThanSign, backingFieldName.IndexOf('>') - indexOfLessThanSign); } return backingFieldName; } private static IEnumerable<SerializedProperty> GetPropChildren(SerializedProperty property) { var iterator = property.Copy(); var end = iterator.GetEndProperty(); iterator.NextVisible(true); while (!SerializedProperty.EqualContents(iterator, end)) { yield return iterator.Copy(); if (!iterator.NextVisible(false)) break; } } } }
0
0.902989
1
0.902989
game-dev
MEDIA
0.886248
game-dev
0.970939
1
0.970939
Facepunch/garrysmod
9,251
garrysmod/lua/includes/modules/saverestore.lua
local Msg = Msg local type = type local pairs = pairs local gmod = gmod local table = table --[[ This module is to help bind the engine's saverestore stuff to Lua. This is so we can save Lua stuff in the save game file. The entities should automatically save most of their table contents to the save file. !!Warning!!: Editing this file may render old saves useless. You can hook into this system like so local function MySaveFunction( save ) saverestore.WriteTable( my_table, save ) end local function MyRestoreFunction( restore ) my_table = saverestore.ReadTable( restore ) end saverestore.AddSaveHook( "HookNameHere", MySaveFunction ) saverestore.AddRestoreHook( "HookNameHere", MyRestoreFunction ) --]] module( "saverestore" ) local TYPE_NONE = 0 local TYPE_FLOAT = 1 -- Treat all numbers as floats (they're all the same to Lua) local TYPE_STRING = 2 local TYPE_ENTITY = 3 local TYPE_VECTOR = 4 local TYPE_TABLE = 5 local TYPE_BOOL = 6 local TYPE_ANGLE = 7 local SaveHooks = {} local RestoreHooks = {} local TableRefs = {} local TableRef = 1 function PreSave() TableRefs = {} TableRef = 1 end function PreRestore() TableRefs = {} TableRef = 1 end --[[--------------------------------------------------------- Name: GetTypeStr Desc: Given a string returns a TYPE_ -----------------------------------------------------------]] local function GetTypeStr( name ) if ( name == "function" ) then return TYPE_NONE end if ( name == "number" ) then return TYPE_FLOAT end if ( name == "string" ) then return TYPE_STRING end if ( name == "Entity" ) then return TYPE_ENTITY end if ( name == "Vehicle" ) then return TYPE_ENTITY end if ( name == "NPC" ) then return TYPE_ENTITY end if ( name == "Player" ) then return TYPE_ENTITY end if ( name == "Weapon" ) then return TYPE_ENTITY end if ( name == "Vector" ) then return TYPE_VECTOR end if ( name == "Angle" ) then return TYPE_ANGLE end if ( name == "table" ) then return TYPE_TABLE end if ( name == "boolean" ) then return TYPE_BOOL end -- These aren't saved if ( name == "ConVar" ) then return TYPE_NONE end if ( name == "PhysObj" ) then return TYPE_NONE end -- Bitch about it incase I've forgot to hook a savable type up Msg( "Can't save or load unknown type " .. name .. "\n" ) return TYPE_NONE end --[[--------------------------------------------------------- Name: GetType Desc: Given a variable returns a TYPE_ -----------------------------------------------------------]] local function GetType( var ) return GetTypeStr( type(var) ) end --[[--------------------------------------------------------- Name: IsWritable Desc: Returns true if we can save the K/V pair -----------------------------------------------------------]] local function IsWritable( k, v ) local itype = GetType( k ) if ( itype == TYPE_NONE ) then return false end if ( itype == TYPE_STRING && k == "SR_Recursion" ) then return false end local itype = GetType( v ) if ( itype == TYPE_NONE ) then return false end return true end --[[--------------------------------------------------------- Name: WriteVar Desc: Writes a single variable to the save -----------------------------------------------------------]] function WritableKeysInTable( t ) local i = 0 for k, v in pairs( t ) do if ( IsWritable( k, v ) ) then i = i + 1 end end return i end --[[--------------------------------------------------------- Name: WriteVar Desc: Writes a single variable to the save -----------------------------------------------------------]] function WriteVar( var, save ) local itype = GetType( var ) if ( itype == TYPE_NONE ) then return end save:StartBlock( type( var ) ) if ( itype == TYPE_FLOAT ) then save:WriteFloat( var ) elseif ( itype == TYPE_BOOL ) then save:WriteBool( var ) elseif ( itype == TYPE_STRING ) then save:WriteString( var ) elseif ( itype == TYPE_ENTITY ) then save:WriteEntity( var ) elseif ( itype == TYPE_ANGLE ) then save:WriteAngle( var ) elseif ( itype == TYPE_VECTOR ) then save:WriteVector( var ) elseif ( itype == TYPE_TABLE ) then WriteTable( var, save ) else Msg( "Error! Saving unsupported Type: " .. type( var ) .. "\n" ) end save:EndBlock() end --[[--------------------------------------------------------- Name: ReadVar Desc: Reads a single variable -----------------------------------------------------------]] function ReadVar( restore ) local retval = 0 local typename = restore:StartBlock() local itype = GetTypeStr( typename ) if ( itype == TYPE_FLOAT ) then retval = restore:ReadFloat() elseif ( itype == TYPE_BOOL ) then retval = restore:ReadBool() elseif ( itype == TYPE_STRING ) then retval = restore:ReadString() elseif ( itype == TYPE_ENTITY ) then retval = restore:ReadEntity() elseif ( itype == TYPE_ANGLE ) then retval = restore:ReadAngle() elseif ( itype == TYPE_VECTOR ) then retval = restore:ReadVector() elseif ( itype == TYPE_TABLE ) then retval = ReadTable( restore ) else Msg( "Error! Loading unsupported Type: " .. typename .. "\n" ) end restore:EndBlock() return retval end --[[--------------------------------------------------------- Name: WriteTable Desc: Writes a table to the save -----------------------------------------------------------]] function WriteTable( tab, save ) -- Write a blank table (because read will be expecting one) if ( tab == nil ) then save:StartBlock( "Table" ) save:EndBlock() end -- We have already saved this table if ( TableRefs[ tab ] ) then save:StartBlock( "TableRef" ) save:WriteInt( TableRefs[ tab ] ) save:EndBlock() return end TableRefs[ tab ] = TableRef save:StartBlock( "Table" ) local iCount = WritableKeysInTable( tab ) save:WriteInt( TableRef ) TableRef = TableRef + 1 save:WriteInt( iCount ) for k, v in pairs( tab ) do if ( IsWritable( k, v ) ) then WriteVar( k, save ) WriteVar( v, save ) end end save:EndBlock() end --[[--------------------------------------------------------- Name: ReadTable Desc: Assumes a table is waiting to be read, returns a table -----------------------------------------------------------]] function ReadTable( restore ) local name = restore:StartBlock() local tab = {} if ( name == "TableRef" ) then local ref = restore:ReadInt() if ( !TableRefs[ ref ] ) then TableRefs[ ref ] = {} restore:EndBlock() ErrorNoHaltWithStack( "Failed to read SaveRestore table!" ) return end tab = TableRefs[ ref ] else local iRef = restore:ReadInt() local iCount = restore:ReadInt() if ( TableRefs[ iRef ] ) then tab = TableRefs[ iRef ] end for i = 0, iCount - 1 do local k = ReadVar( restore ) local v = ReadVar( restore ) tab[ k ] = v end TableRefs[ iRef ] = tab end restore:EndBlock() return tab end --[[--------------------------------------------------------- Name: SaveEntity Desc: Called by the engine for each entity -----------------------------------------------------------]] function SaveEntity( ent, save ) save:StartBlock( "EntityTable" ) WriteTable( ent:GetTable(), save ) save:EndBlock() end --[[--------------------------------------------------------- Name: LoadEntity Desc: Called by the engine for each entity -----------------------------------------------------------]] function LoadEntity( ent, restore ) local EntTable = ent:GetTable() local name = restore:StartBlock() if ( name == "EntityTable" ) then table.Merge( EntTable, ReadTable( restore ) ) end restore:EndBlock() ent:SetTable( EntTable ) end --[[--------------------------------------------------------- Name: AddSaveHook Desc: Adds a hook enabling something to save something.. -----------------------------------------------------------]] function AddSaveHook( name, func ) local h = {} h.Name = name h.Func = func SaveHooks[ name ] = h end --[[--------------------------------------------------------- Name: AddRestoreHook Desc: Adds a hook enabling something to restore something.. -----------------------------------------------------------]] function AddRestoreHook( name, func ) local h = {} h.Name = name h.Func = func RestoreHooks[ name ] = h end --[[--------------------------------------------------------- Name: SaveGlobal Desc: Should save any Lua stuff that isn't entity based. -----------------------------------------------------------]] function SaveGlobal( save ) save:StartBlock( "GameMode" ) WriteTable( gmod.GetGamemode(), save ) save:EndBlock() for k, v in pairs( SaveHooks ) do save:StartBlock( v.Name ) v.Func( save ) save:EndBlock() end end --[[--------------------------------------------------------- Name: LoadGlobal Desc: ... -----------------------------------------------------------]] function LoadGlobal( restore ) local name = restore:StartBlock() if ( name == "GameMode" ) then table.Merge( gmod.GetGamemode(), ReadTable( restore ) ) end restore:EndBlock() while ( name != "EndGlobal" ) do name = restore:StartBlock() local tab = RestoreHooks[ name ] if ( tab ) then tab.Func( restore ) end restore:EndBlock() end end
0
0.749312
1
0.749312
game-dev
MEDIA
0.914725
game-dev
0.969083
1
0.969083
dolphin-emu/dolphin
2,548
Source/Core/Core/FifoPlayer/FifoDataFile.h
// Copyright 2011 Dolphin Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #pragma once #include <array> #include <memory> #include <string> #include <vector> #include "Common/CommonTypes.h" #include "VideoCommon/XFMemory.h" namespace File { class IOFile; } struct MemoryUpdate { enum class Type : u8 { TextureMap = 0x01, XFData = 0x02, VertexStream = 0x04, TMEM = 0x08, }; u32 fifoPosition = 0; u32 address = 0; std::vector<u8> data; Type type{}; }; struct FifoFrameInfo { std::vector<u8> fifoData; u32 fifoStart = 0; u32 fifoEnd = 0; // Must be sorted by fifoPosition std::vector<MemoryUpdate> memoryUpdates; }; class FifoDataFile { public: enum { BP_MEM_SIZE = 256, CP_MEM_SIZE = 256, XF_MEM_SIZE = 4096, XF_REGS_SIZE = 88, TEX_MEM_SIZE = 1024 * 1024, }; static_assert((XF_MEM_SIZE + XF_REGS_SIZE) * sizeof(u32) == sizeof(XFMemory)); FifoDataFile(); ~FifoDataFile(); void SetIsWii(bool isWii); bool GetIsWii() const; bool HasBrokenEFBCopies() const; static bool ShouldGenerateFakeVIUpdates(); u32* GetBPMem() { return m_BPMem.data(); } u32* GetCPMem() { return m_CPMem.data(); } u32* GetXFMem() { return m_XFMem.data(); } u32* GetXFRegs() { return m_XFRegs.data(); } u8* GetTexMem() { return m_TexMem.data(); } u32 GetRamSizeReal() { return m_ram_size_real; } u32 GetExRamSizeReal() { return m_exram_size_real; } void AddFrame(const FifoFrameInfo& frameInfo); const FifoFrameInfo& GetFrame(u32 frame) const { return m_Frames[frame]; } u32 GetFrameCount() const { return static_cast<u32>(m_Frames.size()); } bool Save(const std::string& filename); static std::unique_ptr<FifoDataFile> Load(const std::string& filename, bool flagsOnly); private: enum { FLAG_IS_WII = 1 }; static void PadFile(size_t numBytes, File::IOFile& file); void SetFlag(u32 flag, bool set); bool GetFlag(u32 flag) const; u64 WriteMemoryUpdates(const std::vector<MemoryUpdate>& memUpdates, File::IOFile& file); static void ReadMemoryUpdates(u64 fileOffset, u32 numUpdates, std::vector<MemoryUpdate>& memUpdates, File::IOFile& file); std::array<u32, BP_MEM_SIZE> m_BPMem{}; std::array<u32, CP_MEM_SIZE> m_CPMem{}; std::array<u32, XF_MEM_SIZE> m_XFMem{}; std::array<u32, XF_REGS_SIZE> m_XFRegs{}; std::array<u8, TEX_MEM_SIZE> m_TexMem{}; u32 m_ram_size_real = 0; u32 m_exram_size_real = 0; u32 m_Flags = 0; u32 m_Version = 0; std::vector<FifoFrameInfo> m_Frames; };
0
0.967729
1
0.967729
game-dev
MEDIA
0.199193
game-dev
0.724033
1
0.724033
Sgt-Imalas/Sgt_Imalas-Oni-Mods
14,911
Radiator_Mod/Util/radiatorBase.cs
using KSerialization; using STRINGS; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UtilLibs; namespace Radiator_Mod { public class RadiatorBase : StateMachineComponent<RadiatorBase.SMInstance>, ISaveLoadable, IBridgedNetworkItem //, IGameObjectEffectDescriptor { [MyCmpReq] protected Operational operational; [MyCmpGet] private KSelectable selectable; [MyCmpGet] private KPrefabID prefab; [MyCmpGet] private Building building; [MyCmpGet] private Rotatable rotatable; [MyCmpGet] private PrimaryElement panel_mat; [Serialize] bool RocketInteriorModule = false; public static string Category = "BUILDING", InSpaceRadiating = "RadiatorInSpaceRadiating", NotInSpace = "RadiatorNotInSpace", BunkerDown = "RadiatorBunkeredDown"; public StatusItem _radiating_status; public StatusItem _no_space_status; public StatusItem _protected_from_impacts_status; private int inputCell; private int outputCell; public float CurrentCoolingRadiation { get; private set; } private static readonly double stefanBoltzmanConstant = 5.67e-8; public float emissivity = .9f; public List<CellOffset> RadiatorArea; private HandleVector<int>.Handle accumulator = HandleVector<int>.InvalidHandle; private HandleVector<int>.Handle structureTemperature; public float buildingDefSHC_Modifier = 1f; #region NetworkStuff public ConduitType type = ConduitType.Liquid; public void AddNetworks(ICollection<UtilityNetwork> networks) { var networkManager = Conduit.GetNetworkManager(type); var networkForCell1 = networkManager.GetNetworkForCell(inputCell); if (networkForCell1 != null) networks.Add(networkForCell1); var networkForCell2 = networkManager.GetNetworkForCell(outputCell); if (networkForCell2 == null) return; networks.Add(networkForCell2); } public bool IsConnectedToNetworks(ICollection<UtilityNetwork> networks) { var flag = false; var networkManager = Conduit.GetNetworkManager(type); return flag || networks.Contains(networkManager.GetNetworkForCell(inputCell)) || networks.Contains(networkManager.GetNetworkForCell(outputCell)); } public int GetNetworkCell() { return inputCell; } internal void SetRocketInternal() { RocketInteriorModule = true; } #endregion /// <summary> /// Method that runs while radiating, deletes the heat from the building "into space" /// </summary> public void RadiateIntoSpace(float dt) { var temperature = gameObject.GetComponent<PrimaryElement>().Temperature; if (temperature < 5f) return; float cooling = (float)heatRadiationAmount(temperature); if (cooling > 1f) { CurrentCoolingRadiation = (float)cooling; GameComps.StructureTemperatures.ProduceEnergy(structureTemperature, -(cooling * dt) / 1000f, BUILDING.STATUSITEMS.OPERATINGENERGY.PIPECONTENTS_TRANSFER, -(cooling * dt) / 1000f); UpdateRadiation(); } } /// <summary> /// Sets the Bunker state to make the building immune to meteors, also updates the status message to show up in that state /// </summary> /// <param name="on"></param> public void SetBunkerState(bool on) { if (on) { prefab.AddTag(GameTags.Bunker); } else { prefab.RemoveTag(GameTags.Bunker); } if (selectable != null) selectable.ToggleStatusItem(_protected_from_impacts_status, on); } /// <summary> /// Shows/hides the dtu/sec status msg /// </summary> /// <param name="isOn"></param> public void UpdateRadiation(bool isOn = true) { if (selectable != null) selectable.ToggleStatusItem(_radiating_status, isOn, this); } /// <summary> /// formatting for dtu/s status msg /// </summary> /// <param name="formatstr"></param> /// <param name="data"></param> /// <returns></returns> private static string _FormatStatusCallback(string formatstr, object data) { var radiator = (RadiatorBase)data; var radiation_rate = GameUtil.GetFormattedHeatEnergyRate(radiator.CurrentCoolingRadiation); formatstr = formatstr.Replace("{0}", radiation_rate); formatstr = formatstr.Replace("{AREAPERCENTAGE}", Mathf.RoundToInt(100f * radiator.AreaPercentage()).ToString()); return formatstr; } #region Spawn&Cleanup public override void OnSpawn() { base.OnSpawn(); inputCell = building.GetUtilityInputCell(); outputCell = building.GetUtilityOutputCell(); RocketInteriorModule = this.GetMyWorld().IsModuleInterior; SetRadiatorArea(); Conduit.GetFlowManager(type).AddConduitUpdater(ConduitUpdate); structureTemperature = GameComps.StructureTemperatures.GetHandle(gameObject); _radiating_status = new StatusItem(InSpaceRadiating, Category, string.Empty, StatusItem.IconType.Info, NotificationType.Neutral, false, OverlayModes.HeatFlow.ID); _radiating_status.resolveTooltipCallback = _FormatStatusCallback; _radiating_status.resolveStringCallback = _FormatStatusCallback; _no_space_status = new StatusItem(NotInSpace, Category, string.Empty, StatusItem.IconType.Exclamation, NotificationType.Neutral, false, OverlayModes.TileMode.ID); _protected_from_impacts_status = new StatusItem(BunkerDown, Category, string.Empty, StatusItem.IconType.Info, NotificationType.Good, false, OverlayModes.TileMode.ID); AmIInSpace(); smi.StartSM(); } public void SetRadiatorArea() { RadiatorArea = new List<CellOffset>(); if (!RocketInteriorModule) { //SgtLogger.l("Not a Rocket interior"); for (int i = 1; i < 6; i++) { for (int j = 0; j <= 1; j++) { //Debug.Log("x: " + i + ", y: " + j); RadiatorArea.Add(new CellOffset(j, i)); } } } else { //SgtLogger.l("RocketInterior"); for (int i = -2; i > -7; i--) { for (int j = 0; j <= 1; j++) { //Debug.Log("x: " + i + ", y: " + j); RadiatorArea.Add(new CellOffset(i, j)); } } } } public override void OnPrefabInit() { base.OnPrefabInit(); accumulator = Game.Instance.accumulators.Add("Flow", this); } public override void OnCleanUp() { Conduit.GetFlowManager(type).RemoveConduitUpdater(ConduitUpdate); Game.Instance.accumulators.Remove(accumulator); base.OnCleanUp(); } #endregion /// <summary> /// Updates for Liquids inside the radiator + connected liquid networks /// </summary> /// <param name="dt"></param> public void ConduitUpdate(float dt) { var flowManager = Conduit.GetFlowManager(type); if (!flowManager.HasConduit(inputCell) || !flowManager.HasConduit(outputCell)) return; if (!flowManager.GetContents(outputCell).Equals(ConduitFlow.ConduitContents.Empty)) { return; } var contents = flowManager.GetContents(inputCell); if (contents.mass <= 0f) return; float panel_mat_temperature = panel_mat.Temperature; float content_mat_temperature = contents.temperature; if (panel_mat_temperature <= 0f) return; var element = ElementLoader.FindElementByHash(contents.element); var maxWattsTransferred = MaxWattsTransferedPerSecond(element, contents.temperature, panel_mat.Element, panel_mat_temperature); //SgtLogger.l("potential heat transfer: " + maxWattsTransferred); var panel_heat_capacity = Config.Instance.UseOldHeatDeletion ? building.Def.MassForTemperatureModification : building.Def.MassForTemperatureModification * panel_mat.Element.specificHeatCapacity;// (RadiatorBaseConfig.matCosts[0] * panel_mat.Element.specificHeatCapacity); var liquid_heat_capacity = contents.mass * element.specificHeatCapacity; float actualKJtransferred = ActualWattsTransferred(dt, maxWattsTransferred, panel_mat_temperature, content_mat_temperature, panel_heat_capacity, liquid_heat_capacity); //SgtLogger.l("actual heat transfer: " + actualKJtransferred); float newLiquidTemperature = ContactConductivePipeBridge.GetFinalContentTemperature(actualKJtransferred, panel_mat_temperature, panel_heat_capacity, content_mat_temperature, liquid_heat_capacity); float newPanelTemperature = ContactConductivePipeBridge.GetFinalBuildingTemperature(content_mat_temperature, newLiquidTemperature, liquid_heat_capacity, panel_mat_temperature, panel_heat_capacity); //SgtLogger.l(content_mat_temperature+ "<- old liquid temp, new liquid temp->" + newLiquidTemperature); //SgtLogger.l(panel_mat_temperature+"<- old panel temp, new panel temp->" + newPanelTemperature); if (newPanelTemperature <= 0f || newLiquidTemperature <= 0f || newPanelTemperature >= 10000f || newLiquidTemperature >= 10000f) { var delta = flowManager.AddElement(outputCell, contents.element, contents.mass, contents.temperature, contents.diseaseIdx, contents.diseaseCount); if (delta <= 0f) return; flowManager.RemoveElement(inputCell, delta); Game.Instance.accumulators.Accumulate(accumulator, contents.mass); } else { var delta = flowManager.AddElement(outputCell, contents.element, contents.mass, newLiquidTemperature, contents.diseaseIdx, contents.diseaseCount); panel_mat.Temperature = newPanelTemperature; if (delta <= 0f) return; flowManager.RemoveElement(inputCell, delta); Game.Instance.accumulators.Accumulate(accumulator, contents.mass); } } public static float ActualWattsTransferred(float dt, float maxWattsTransferred, float panel_mat_temperature, float content_mat_temperature, float panel_heat_capacity, float liquid_heat_capacity) { float wattsTransferredDt = maxWattsTransferred * dt; float lowTemp = Mathf.Min(panel_mat_temperature, content_mat_temperature); float highTemp = Mathf.Max(panel_mat_temperature, content_mat_temperature); var delta_temp_panel = (wattsTransferredDt / panel_heat_capacity); var delta_temp_liquid = (-wattsTransferredDt / liquid_heat_capacity); float clampedNewLiquidTemp = Mathf.Clamp((content_mat_temperature + delta_temp_liquid), lowTemp, highTemp); float clampedNewPanelTemperature = Mathf.Clamp((panel_mat_temperature + delta_temp_panel), lowTemp, highTemp); float clampDiffLiquid = Mathf.Abs(clampedNewLiquidTemp - content_mat_temperature); float clampDiffPanel = Mathf.Abs(clampedNewPanelTemperature - panel_mat_temperature); return Mathf.Min(clampDiffLiquid * liquid_heat_capacity, clampDiffPanel * panel_heat_capacity) * Mathf.Sign(maxWattsTransferred); } public static float MaxWattsTransferedPerSecond(Element from, float from_temp, Element panel_material, float panel_temp) { //var conductivity = Math.Min(from.thermalConductivity, panel_material.thermalConductivity); var conductivity = (from.thermalConductivity + panel_material.thermalConductivity) / 2f; return conductivity * (from_temp - panel_temp); } /// <summary> /// Calculates Thermal radiation based on temperature & some fancy formula thats based on the Stefan-Boltzman-Constant /// </summary> /// <param name="temp"></param> /// <returns></returns> private double heatRadiationAmount(float temp) { return Math.Pow(temp, 4) * stefanBoltzmanConstant * emissivity * CalculateActualSpaceRadiatorArea() * Config.Instance.RadiationMultiplicator; } /// <summary> /// float value that indicates the percentage of radiator tiles that are currently radiating /// </summary> /// <returns></returns> public float AreaPercentage() { float total = RadiatorArea.Count(); float current = CalculateActualSpaceRadiatorArea(); return (current / total); } /// <summary> /// the amount of tiles that can radiate into space /// </summary> /// <returns></returns> private int CalculateActualSpaceRadiatorArea() { int radiatorCellCount = 0; var root_cell = Grid.PosToCell(this); foreach (var _cell in RadiatorArea) { var _cellRotated = Rotatable.GetRotatedCellOffset(_cell, rotatable.Orientation); if (UtilMethods.IsCellInSpaceAndVacuum(Grid.OffsetCell(root_cell, _cellRotated), root_cell)) { radiatorCellCount++; } } bool canRadiateAtAll = radiatorCellCount > 0; selectable.ToggleStatusItem(_no_space_status, !canRadiateAtAll); smi.sm.IsInTrueSpace.Set(canRadiateAtAll, smi); return radiatorCellCount; } /// <summary> /// Checks if all panel tiles are space exposed & in vacuum, updates the status msg and the state bool of the state machine /// </summary> /// <returns></returns> public bool AmIInSpace() { bool currentlyInSpace = true; var root_cell = Grid.PosToCell(this); foreach (var _cell in RadiatorArea) { var _cellRotated = Rotatable.GetRotatedCellOffset(_cell, rotatable.Orientation); if (!UtilMethods.IsCellInSpaceAndVacuum(Grid.OffsetCell(root_cell, _cellRotated), root_cell)) { currentlyInSpace = false; break; } } selectable.ToggleStatusItem(_no_space_status, !currentlyInSpace); smi.sm.IsInTrueSpace.Set(currentlyInSpace, smi); return currentlyInSpace; } #region StateMachine public class SMInstance : GameStateMachine<States, SMInstance, RadiatorBase, object>.GameInstance { private readonly Operational _operational; public readonly KSelectable _selectable; public SMInstance(RadiatorBase master) : base(master) { _operational = master.GetComponent<Operational>(); _selectable = master.GetComponent<KSelectable>(); } public bool IsOperational => _operational.IsFunctional && _operational.IsOperational; } public class States : GameStateMachine<States, SMInstance, RadiatorBase> { public BoolParameter IsInTrueSpace; public State Radiating; public State Retracting; public State Extending; public State Protecting; public State NotRadiating; public override void InitializeStates(out BaseState defaultState) { defaultState = NotRadiating; NotRadiating .QueueAnim("on") //.Update((smi, dt) => smi.master.AmIInSpace()) .Update((smi, dt) => smi.master.CalculateActualSpaceRadiatorArea()) .EventTransition(GameHashes.OperationalChanged, Retracting, smi => !smi.IsOperational) .ParamTransition(this.IsInTrueSpace, Radiating, IsTrue); Radiating .Update("Radiating", (smi, dt) => { smi.master.RadiateIntoSpace(dt); //smi.master.AmIInSpace(); }, UpdateRate.SIM_200ms) .QueueAnim("on_rad", true) .Exit(smi => smi.master.UpdateRadiation(false)) .EventTransition(GameHashes.OperationalChanged, Retracting, smi => !smi.IsOperational) .ParamTransition(this.IsInTrueSpace, NotRadiating, IsFalse); Retracting .PlayAnim("on_pst") .OnAnimQueueComplete(Protecting); Protecting .Enter(smi => smi.master.SetBunkerState(true)) .Exit(smi => smi.master.SetBunkerState(false)) .QueueAnim("off", true) .EventTransition(GameHashes.OperationalChanged, Extending, smi => smi.IsOperational); Extending .PlayAnim("on_pre") .OnAnimQueueComplete(NotRadiating); } } #endregion } }
0
0.977434
1
0.977434
game-dev
MEDIA
0.388611
game-dev
0.953914
1
0.953914
ComputationalBiomechanicsLab/opensim-creator
26,741
third_party/libosim/opensim-core/OpenSim/Simulation/Control/ControlLinear.cpp
/* -------------------------------------------------------------------------- * * OpenSim: ControlLinear.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Frank C. Anderson * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ /* Note: This code was originally developed by Realistic Dynamics Inc. * Author: Frank C. Anderson */ #include <OpenSim/Common/Signal.h> #include <OpenSim/Common/PropertySet.h> #include "ControlLinear.h" using namespace OpenSim; using namespace std; //============================================================================= // CONSTRUCTOR(S) //============================================================================= //_____________________________________________________________________________ ControlLinear::~ControlLinear() { } //_____________________________________________________________________________ ControlLinear:: ControlLinear() : _useSteps(_propUseSteps.getValueBool()), _xNodes((ArrayPtrs<ControlLinearNode>&)_propXNodes.getValueObjArray()), _minNodes((ArrayPtrs<ControlLinearNode>&)_propMinNodes.getValueObjArray()), _maxNodes((ArrayPtrs<ControlLinearNode>&)_propMaxNodes.getValueObjArray()), _kp(_propKp.getValueDbl()), _kv(_propKv.getValueDbl()) { setNull(); } //_____________________________________________________________________________ ControlLinear::ControlLinear(const ControlLinear &aControl) : Control(aControl), _useSteps(_propUseSteps.getValueBool()), _xNodes((ArrayPtrs<ControlLinearNode>&)_propXNodes.getValueObjArray()), _minNodes((ArrayPtrs<ControlLinearNode>&)_propMinNodes.getValueObjArray()), _maxNodes((ArrayPtrs<ControlLinearNode>&)_propMaxNodes.getValueObjArray()), _kp(_propKp.getValueDbl()), _kv(_propKv.getValueDbl()) { setNull(); copyData(aControl); } //============================================================================= // CONSTRUCTION/DESTRUCTION //============================================================================= //_____________________________________________________________________________ void ControlLinear:: setNull() { setupProperties(); } //_____________________________________________________________________________ void ControlLinear:: setupProperties() { _propUseSteps.setName("use_steps"); _propUseSteps.setValue(false); _propertySet.append( &_propUseSteps ); ArrayPtrs<ControlLinearNode> nodes; _propXNodes.setName("x_nodes"); _propXNodes.setValue(nodes); _propertySet.append( &_propXNodes ); _propMinNodes.setName("min_nodes"); _propMinNodes.setValue(nodes); _propertySet.append( &_propMinNodes ); _propMaxNodes.setName("max_nodes"); _propMaxNodes.setValue(nodes); _propertySet.append( &_propMaxNodes ); _propKp.setName("kp"); _propKp.setValue(100); _propertySet.append( &_propKp ); _propKv.setName("kv"); _propKv.setValue(20); _propertySet.append( &_propKv ); } //_____________________________________________________________________________ void ControlLinear:: copyData(const ControlLinear &aControl) { _useSteps = aControl.getUseSteps(); _xNodes = aControl._xNodes; _minNodes = aControl._minNodes; _maxNodes = aControl._maxNodes; _kp = aControl.getKp(); _kv = aControl.getKv(); } //============================================================================= // OPERATORS //============================================================================= //----------------------------------------------------------------------------- // ASSIGNMENT //----------------------------------------------------------------------------- //_____________________________________________________________________________ ControlLinear& ControlLinear:: operator=(const ControlLinear &aControl) { // BASE CLASS Control::operator=(aControl); // DATA copyData(aControl); return(*this); } //============================================================================= // GET AND SET //============================================================================= //----------------------------------------------------------------------------- // USE STEPS //----------------------------------------------------------------------------- //_____________________________________________________________________________ void ControlLinear:: setUseSteps(bool aTrueFalse) { _useSteps = aTrueFalse; } //_____________________________________________________________________________ bool ControlLinear:: getUseSteps() const { return(_useSteps); } //----------------------------------------------------------------------------- // KP //----------------------------------------------------------------------------- //_____________________________________________________________________________ void ControlLinear:: setKp(double aKp) { _kp = aKp; } //_____________________________________________________________________________ double ControlLinear:: getKp() const { return(_kp); } //----------------------------------------------------------------------------- // KV //----------------------------------------------------------------------------- //_____________________________________________________________________________ void ControlLinear:: setKv(double aKv) { _kv = aKv; } //_____________________________________________________________________________ double ControlLinear:: getKv() const { return(_kv); } //----------------------------------------------------------------------------- // NUMBER OF PARAMETERS //----------------------------------------------------------------------------- //_____________________________________________________________________________ int ControlLinear:: getNumParameters() const { return(_xNodes.getSize()); } //----------------------------------------------------------------------------- // PARAMETER MIN //----------------------------------------------------------------------------- //_____________________________________________________________________________ void ControlLinear:: setParameterMin(int aI,double aMin) { _minNodes.get(aI)->setValue(aMin); } //_____________________________________________________________________________ double ControlLinear:: getParameterMin(int aI) const { return(_minNodes.get(aI)->getValue()); } //----------------------------------------------------------------------------- // PARAMETER MAX //----------------------------------------------------------------------------- //_____________________________________________________________________________ void ControlLinear:: setParameterMax(int aI,double aMax) { _maxNodes.get(aI)->setValue(aMax); } //_____________________________________________________________________________ double ControlLinear:: getParameterMax(int aI) const { return(_maxNodes.get(aI)->getValue()); } //----------------------------------------------------------------------------- // PARAMETER TIME //----------------------------------------------------------------------------- //_____________________________________________________________________________ double ControlLinear:: getParameterTime(int aI) const { return(_xNodes.get(aI)->getTime()); } //----------------------------------------------------------------------------- // PARAMETER NEIGHBORHOOD //----------------------------------------------------------------------------- //_____________________________________________________________________________ void ControlLinear:: getParameterNeighborhood(int aI,double &rTLower,double &rTUpper) const { rTLower = SimTK::NaN; rTUpper = SimTK::NaN; // CHECK THAT THE NODE EXISTS // An exception is thrown if aI is out of bounds. _xNodes.get(aI); // NEIGHBORING NODES int size = _xNodes.getSize(); if(size==1) { rTLower = -SimTK::Infinity; rTUpper = SimTK::Infinity; return; } int lower = aI - 1; if(lower<0) lower = 0; int upper; if(_useSteps) upper = aI; else upper = aI + 1; if(upper>=size) upper = size-1; rTLower = _xNodes.get(lower)->getTime(); rTUpper = _xNodes.get(upper)->getTime(); } //----------------------------------------------------------------------------- // PARAMETER LIST //----------------------------------------------------------------------------- //_____________________________________________________________________________ int ControlLinear:: getParameterList(double aT,Array<int> &rList) { rList.setSize(0); // CHECK SIZE int size = _xNodes.getSize(); if(size<=0) return(0); // FIND THE NODE _searchNode.setTime(aT); int i = _xNodes.searchBinary(_searchNode); // LESS THAN TIME OF FIRST NODE if(i<0) { rList.append(0); // GREATER THAN TIME OF LAST NODE } else if(i>=(size-1)) { rList.append(size-1); // EQUAL & LINEAR INTERPOLATION } else if((!_useSteps) && (_searchNode == (*_xNodes.get(i)) )) { rList.append(i); // BETWEEN & LINEAR INTERPOLATION } else if(!_useSteps) { rList.append(i); rList.append(i+1); // STEPS } else { rList.append(i+1); } return(rList.getSize()); } //_____________________________________________________________________________ int ControlLinear:: getParameterList(double aTLower,double aTUpper,Array<int> &rList) { rList.setSize(0); // CHECK SIZE int size = _xNodes.getSize(); if(size<=0) return(0); // CHECK FOR VALID INTERVAL if(aTLower>aTUpper) return(0); // LOWER NODE _searchNode.setTime(aTLower); int iL = _xNodes.searchBinary(_searchNode); if(iL==-1) { iL += 1; } else if(iL==(size-1)) { return(0); } else if( (*_xNodes.get(iL)) == _searchNode ) { iL += 1; } else { iL += 2; } // UPPER NODE _searchNode.setTime(aTUpper); int iU = _xNodes.searchBinary(_searchNode); if(iU==-1) { return(0); } else if( (*_xNodes.get(iU)) < _searchNode) { iU += 1; } // FORM LIST while(iL<=iU) { if(iL>=size) return(rList.getSize()); rList.append(iL); iL++; } return(rList.getSize()); } //----------------------------------------------------------------------------- // PARAMETER VALUE //----------------------------------------------------------------------------- //_____________________________________________________________________________ void ControlLinear:: setParameterValue(int aI,double aX) { _xNodes.get(aI)->setValue(aX); } //_____________________________________________________________________________ double ControlLinear:: getParameterValue(int aI) const { return(_xNodes.get(aI)->getValue()); } //----------------------------------------------------------------------------- // UTILITY //----------------------------------------------------------------------------- void ControlLinear:: setControlValue(ArrayPtrs<ControlLinearNode> &aNodes,double aT,double aValue) { ControlLinearNode node(aT,aValue); int lower = aNodes.searchBinary(node); // NO NODE if(lower<0) { aNodes.insert(0, node.clone() ); // CHECK NODE } else { int upper = lower + 1; // EQUAL TO LOWER NODE if( (*aNodes[lower]) == node) { aNodes[lower]->setTime(aT); aNodes[lower]->setValue(aValue); // NOT AT END OF ARRAY } else if(upper<aNodes.getSize()) { // EQUAL TO UPPER NODE if( (*aNodes[upper]) == node) { aNodes[upper]->setTime(aT); aNodes[upper]->setValue(aValue); // NOT EQUAL } else { aNodes.insert(upper, node.clone()); } // AT END OF ARRAY } else { aNodes.append(node.clone()); } } } double ControlLinear:: getControlValue(ArrayPtrs<ControlLinearNode> &aNodes,double aT) { // CHECK SIZE int size = aNodes.getSize(); // CMC expects NaN's to be returned if the Control set size is zero if(size<=0) return(SimTK::NaN); // GET NODE _searchNode.setTime(aT); int i = aNodes.searchBinary(_searchNode); // BEFORE FIRST double value; if(i<0) { if(!_useSteps && getExtrapolate()) { value = extrapolateBefore(aNodes, aT); } else { value = aNodes[0]->getValue(); } // AFTER LAST } else if(i>=(size-1)) { if(!_useSteps && getExtrapolate()) { value = extrapolateAfter(aNodes, aT); } else { value = aNodes.getLast()->getValue(); } // IN BETWEEN } else { // LINEAR INTERPOLATION if(!_useSteps) { double t1,v1,t2,v2; t1 = aNodes[i]->getTime(); v1 = aNodes[i]->getValue(); t2 = aNodes[i+1]->getTime(); v2 = aNodes[i+1]->getValue(); value = Interpolate(t1,v1,t2,v2,aT); // STEPS } else { // Eran: Changed semantics of piecewise constant controls so that // the control value stored at time t(i+1) is applied to the time // interval (t(i),t(i+1)] *exclusive* of time t(i). // This was essential to get forward simulation to match cmcgait simulation // much better. During cmcgait simulation of interval [t1,t2] when the // integrator reaches time t2 it would pick up the control value at t2 // because it had yet to compute the piecewise linear control value // at time t3. During forward simulation, when the integrator reaches t2 // the control at t3 is known but for consistency with cmcgait we need to // use the control value at t2. Hence the (t(i),t(i+1)] choice. if (aT == aNodes[i]->getTime()) value = aNodes[i]->getValue(); else value = aNodes[i+1]->getValue(); } } return(value); } double ControlLinear:: extrapolateBefore(const ArrayPtrs<ControlLinearNode> &aNodes,double aT) const { if(aNodes.getSize()<=0) return(SimTK::NaN); if(aNodes.getSize()==1) return(aNodes[0]->getValue()); double t1,v1,t2,v2; t1 = aNodes[0]->getTime(); v1 = aNodes[0]->getValue(); t2 = aNodes[1]->getTime(); v2 = aNodes[1]->getValue(); double value = Interpolate(t1,v1,t2,v2,aT); return(value); } double ControlLinear:: extrapolateAfter(ArrayPtrs<ControlLinearNode> &aNodes,double aT) const { int size = aNodes.getSize(); if(size<=0) return(SimTK::NaN); if(size==1) return(aNodes[0]->getValue()); int n1 = size - 2; int n2 = size - 1; double t1,v1,t2,v2; t1 = aNodes[n1]->getTime(); v1 = aNodes[n1]->getValue(); t2 = aNodes[n2]->getTime(); v2 = aNodes[n2]->getValue(); double value = Interpolate(t1,v1,t2,v2,aT); return(value); } //----------------------------------------------------------------------------- // CONTROL VALUE //----------------------------------------------------------------------------- //_____________________________________________________________________________ void ControlLinear:: setControlValue(double aT,double aX) { setControlValue(_xNodes,aT,aX); } //_____________________________________________________________________________ double ControlLinear:: getControlValue(double aT) { return getControlValue(_xNodes,aT); } //_____________________________________________________________________________ double ControlLinear:: extrapolateBefore(double aT) const { return extrapolateBefore(_xNodes,aT); } //_____________________________________________________________________________ double ControlLinear:: extrapolateAfter(double aT) const { return extrapolateAfter(_xNodes,aT); } //----------------------------------------------------------------------------- // CONTROL VALUE MINIMUM //----------------------------------------------------------------------------- //_____________________________________________________________________________ void ControlLinear:: setControlValueMin(double aT,double aMin) { setControlValue(_minNodes,aT,aMin); } //_____________________________________________________________________________ double ControlLinear:: getControlValueMin(double aT) { if(_minNodes.getSize()==0) return _defaultMin; else return getControlValue(_minNodes,aT); } //_____________________________________________________________________________ double ControlLinear:: extrapolateMinBefore(double aT) const { return extrapolateBefore(_minNodes,aT); } //_____________________________________________________________________________ double ControlLinear:: extrapolateMinAfter(double aT) const { return extrapolateAfter(_minNodes,aT); } //----------------------------------------------------------------------------- // CONTROL VALUE MAXIMUM //----------------------------------------------------------------------------- //_____________________________________________________________________________ void ControlLinear:: setControlValueMax(double aT,double aMax) { setControlValue(_maxNodes,aT,aMax); } //_____________________________________________________________________________ double ControlLinear:: getControlValueMax(double aT) { if(_minNodes.getSize()==0) return _defaultMax; else return getControlValue(_maxNodes,aT); } //_____________________________________________________________________________ double ControlLinear:: extrapolateMaxBefore(double aT) const { return extrapolateBefore(_maxNodes,aT); } //_____________________________________________________________________________ double ControlLinear:: extrapolateMaxAfter(double aT) const { return extrapolateAfter(_maxNodes,aT); } //----------------------------------------------------------------------------- // NODE ARRAY //----------------------------------------------------------------------------- void ControlLinear:: clearControlNodes() { _xNodes.setSize(0); } //_____________________________________________________________________________ double ControlLinear::getFirstTime() const { const ControlLinearNode *node=_xNodes.get(0); return node->getTime(); } //_____________________________________________________________________________ double ControlLinear::getLastTime() const { const ControlLinearNode *node=_xNodes.getLast(); return node->getTime(); } //----------------------------------------------------------------------------- // SIMPLIFY //----------------------------------------------------------------------------- //_____________________________________________________________________________ void ControlLinear:: simplify(const PropertySet &aProperties) { // INITIAL SIZE int size = _xNodes.getSize(); log_info("ControlLinear.simplify: initial size = {}.", size); // GET THE NODE TIMES int i; Array<double> t(0.0,size); for(i=0;i<size;i++) { t[i] = _xNodes[i]->getTime(); } // SEARCH FOR THE MINIMUM TIME INTERVAL double dt,dtMin= SimTK::Infinity; for(i=0;i<(size-1);i++) { dt = t[i+1] - t[i]; if(dt<dtMin) { dtMin = dt; if(dtMin<=SimTK::Zero) { string msg = "ControlLinear.simplify: zero or negative dt!"; throw(Exception(msg,__FILE__,__LINE__)); } } } // RESAMPLE THE NODE VALUES int n = (int)(1.0 + (t[size-1] - t[0])/dtMin); double time; Array<double> x(0.0,n); t.setSize(n); for(time=t[0],i=0;i<n;i++,time+=dtMin) { t[i] = time; x[i] = getControlValue(time); } // FILTER double cutoffFrequency = aProperties.get("cutoff_frequency")->getValueDbl(); if(cutoffFrequency < SimTK::Zero) { throw(Exception()); } Array<double> xFilt(0.0,n); int order = 50; if(order>(n/2)) order = n/2; if(order<10) { log_warn("ControlLinear.simplify: too few data points (n={}) to filter {}.", n, getName()); } else { if(order<20) { log_warn("ControlLinear.simplify: order of FIR filter had to be" " low due to small number of data points (n={}) in control {}.", n, getName()); } log_info("ControlLinear.simplify: lowpass filtering with a cutoff " "frequency of {} and order of {}.", cutoffFrequency, order); Signal::LowpassFIR(order,dtMin,cutoffFrequency,n,&x[0],&xFilt[0]); } // REMOVE POINTS double distance = aProperties.get("distance")->getValueDbl(); log_info("ControlLinear.simplify: reducing points with distance tolerance = {}.", distance); Signal::ReduceNumberOfPoints(distance,t,xFilt); // CLEAR OLD NODES _xNodes.trim(); _xNodes.setSize(0); // ADD NEW NODES int newSize = t.getSize(); ControlLinearNode *node; for(i=0;i<newSize;i++) { char name[32]; node = new ControlLinearNode(t[i],xFilt[i]); snprintf(name, 32, "%d", i); node->setName(name); _xNodes.append(node); } log_info("ControlLinear.simplify: final size = {}.", _xNodes.getSize()); } bool ControlLinear:: simplify(const double& cutoffFrequency, const double& distance) { PropertySet params; params.append(new PropertyDbl("cutoff_frequency", cutoffFrequency)); // Will be deleted by the destructor params.append(new PropertyDbl("distance", distance)); try { simplify(params); return true; } catch(const Exception&) { return(false); } } //----------------------------------------------------------------------------- // FILTER CONTROL //----------------------------------------------------------------------------- //_____________________________________________________________________________ void ControlLinear:: filter(double aT) { // CHECK WHETHER FILTER IS ON // TO DO - should we print some error/warning message here? if (!_filterOn) return; // CHECK SIZE // TO DO - should we print some error/warning message here? int size = _xNodes.getSize(); if(size<=0) return; // FIND CONTROL NODE // Find the control node at time aT _searchNode.setTime(aT); int i = _xNodes.searchBinary(_searchNode); // The following property is true after binary search: // _xNodes[i].getValue() <= getControlValue(aT) // i.e. the node whose index (i) was returned is the node // that occurs immediately before, or exactly at, the time aT. // An equivalent property is that // _searchNode >= (*_xNodes.get(i)) // which is computed below as the "nodeOccursAtGivenTime" variable. // COMPUTE AND SET CONTROL VALUE // HANDLE CASE WITH LESS THAN TWO PREVIOUS CONTROL NODES // If there are less than two control nodes occurring before // time aT, then set the value zero. The PD follower needs // at least two nodes to occur before the time aT in order to // compute a new control value for the time aT. // The first if statement represents the following cases: // i < 0: aT occurs before the first node // i == 0: the first node occurs before or at aT if (i <= 0) { setControlValue(aT, 0.0); return; } // True iff _xNodes[i] occurs at aT bool nodeOccursAtGivenTime = (_searchNode == (*_xNodes.get(i))); // This if statement represents the case where the second // node occurs at aT. if ((i == 1) && nodeOccursAtGivenTime) { setControlValue(aT, 0.0); return; } // HANDLE ALL OTHER CASES double dt, dtPrev, xPrev, xPrevPrev; // If the time of the node at index i is equal to aT (where // "equal" is determined by the operator== function of the // ControlLinearNode class): // (i <= 1 cases were handled above) if (nodeOccursAtGivenTime) { dt = _xNodes[i]->getTime() - _xNodes[i-1]->getTime(); dtPrev = _xNodes[i-1]->getTime() - _xNodes[i-2]->getTime(); xPrev = _xNodes[i-1]->getValue(); xPrevPrev = _xNodes[i-2]->getValue(); // If the time of the node at index i is less than aT: } else { dt = aT - _xNodes[i]->getTime(); dtPrev = _xNodes[i]->getTime() - _xNodes[i-1]->getTime(); xPrev = _xNodes[i]->getValue(); xPrevPrev = _xNodes[i-1]->getValue(); } // GET CURRENT CONTROL VALUE // aT occurs before first node double xDes = getControlValue(aT); // COMPUTE AND SET NEW FILTERED CONTROL VALUE double xDotPrev = (xPrev - xPrevPrev) / dtPrev; double xDotDotPrev = -_kv*xDotPrev + _kp*(xDes - xPrev); double x = xPrev + xDotPrev*dt + 0.5*xDotDotPrev*dt*dt; // Set the control value to the newly computed value setControlValue(aT, x); } //_____________________________________________________________________________ double ControlLinear:: Interpolate(double aX1,double aY1,double aX2,double aY2,double aX) { double y; double dx = aX2 - aX1; if(fabs(dx)<SimTK::Zero) { y = aY1; } else { double dy = aY2 - aY1; double m = dy / dx; y = aY1 + m*(aX-aX1); } return(y); }
0
0.963971
1
0.963971
game-dev
MEDIA
0.380502
game-dev
0.799736
1
0.799736
HarikrishnanBalagopal/wasm2js
30,274
docs/assets/wasm/match3.wat
(import "Math" "random" (func $random (result f32))) ;; Memory map: ;; ;; [0x0000 .. 0x00001] x, y mouse position ;; [0x0002 .. 0x00002] mouse buttons ;; [0x0003 .. 0x00004] x, y mouse click position ;; [0x00c0 .. 0x00100] 16 RGBA colors u32[16] ;; [0x0100 .. 0x00500] 16x16 emojis 4bpp u8[8][128] ;; [0x0500 .. 0x00550] 8x8 digits 1bpp u8[10][8] ;; [0x0550 .. 0x00578] gameover 1bpp u8[5][8] ;; [0x0578 .. 0x005c0] 18 match patterns u32[18] ;; [0x05c0 .. 0x00650] 18 shift masks u64[18] ;; [0x0700 .. 0x00740] 8x8 grid bitmap u64[8] ;; [0x0900 .. 0x00a00] current offset {s8 x, s8 y, s8 w, s8 h}[64] ;; [0x0a00 .. 0x00b00] start offset {s8 x, s8 y, s8 w, s8 h}[64] ;; [0x0b00 .. 0x00c00] end offset {s8 x, s8 y, s8 w, s8 h}[64] ;; [0x0c00 .. 0x00d00] time [0..1) f32[64] ;; [0x0d00 .. 0x0109c] compressed data ;; [0x1100 .. 0x11090] 150x150xRGBA data (4 bytes per pixel) (memory (export "mem") 2) (global $score (mut i32) (i32.const 0)) (global $matched (mut i64) (i64.const -1)) (global $state (mut i32) (i32.const 0)) ;; init (global $animating (mut i32) (i32.const 1)) (global $prev-mouse-bit (mut i64) (i64.const 0)) (global $click-mouse-bit (mut i64) (i64.const 0)) (func (export "run") (local $src i32) (local $dst i32) (local $dist i32) (local $copy-end i32) (local $byte-or-len i32) (local $i i32) (local $grid-offset i32) (local $random-grid i32) (local $t-addr i32) (local $i-addr i32) (local $a i32) (local $mouse-src*4 i32) (local $click-mouse-src*4 i32) (local $x i32) (local $divisor i32) (local $mouse-bit i64) (local $empty i64) (local $idx i64) (local $1<<idx i64) (local $above-bits i64) (local $above-idx i64) (local $mouse-dx f32) (local $mouse-dy f32) (local $t f32) (local $mul-t f32) ;; clear screen to transparent black (loop $loop ;; mem[0x1100 + i] = 0 (i32.store offset=0x1100 (local.get $i) (i32.const 0)) ;; i += 4 ;; loop if i < 90000 (br_if $loop (i32.lt_s (local.tee $i (i32.add (local.get $i) (i32.const 4))) (i32.const 90000)))) block $done block $matched block $gameover block $falling block $removing block $init block $reset-prev-mouse block $reset-all-mouse block $mouse-down block $idle (br_table $init $idle $mouse-down $removing $falling $gameover (global.get $state)) end $idle ;; Animate mouse-bit scaling up, as long as it isn't the same as ;; prev-mouse-bit: mouse-bit & ~prev-mouse-bit (call $animate-cells (i64.and (local.tee $mouse-bit (call $get-mouse-bit (i32.load8_u (i32.const 0)) ;; mousex (i32.load8_u (i32.const 1)))) ;; mousey (i64.xor (global.get $prev-mouse-bit) (i64.const -1))) (i32.const 0x08_08_fc_fc)) (global.set $click-mouse-bit (local.get $mouse-bit)) ;; If the mouse was not clicked, or if it is an invalid cell, then skip. (br_if $reset-prev-mouse (i32.or (i32.eqz (i32.load8_u (i32.const 2))) (i64.eqz (local.get $mouse-bit)))) ;; Save the current mouse x/y. (i32.store16 (i32.const 3) (i32.load16_u (i32.const 0))) ;; Set the current state to $mouse-down. (global.set $state (i32.const 2)) (br $reset-prev-mouse) end $mouse-down ;; if abs(mouse-dx) < abs(mouse-dy) ... (if (result f32) (f32.lt (f32.abs ;; mouse-dx = mouse-x - mouse-click-x (local.tee $mouse-dx (f32.convert_i32_s (i32.sub (i32.load8_u (i32.const 0)) (i32.load8_u (i32.const 3)))))) (f32.abs ;; mouse-dy = mouse-y - mouse-click-y (local.tee $mouse-dy (f32.convert_i32_s (i32.sub (i32.load8_u (i32.const 1)) (i32.load8_u (i32.const 4))))))) (then ;; mouse-dy = copysign(min(abs(mouse-dy), 17), mouse-dy) (local.set $mouse-dy (f32.copysign (f32.min (f32.abs (local.get $mouse-dy)) (f32.const 17)) (local.get $mouse-dy))) ;; mouse-dx = 0 (f32.const 0)) (else ;; mouse-dy = 0 (local.set $mouse-dy (f32.const 0)) ;; mouse-dx = copysign(min(abs(mouse-dx), 17), mouse-dx) (f32.copysign (f32.min (f32.abs (local.get $mouse-dx)) (f32.const 17)) (local.get $mouse-dx)))) (local.set $mouse-src*4 (call $bit-to-src*4 (local.tee $mouse-bit (call $get-mouse-bit (i32.add (i32.trunc_f32_s (local.tee $mouse-dx (; `if` result ;))) (i32.load8_u (i32.const 3))) (i32.add (i32.trunc_f32_s (local.get $mouse-dy)) (i32.load8_u (i32.const 4))))))) ;; If mouse-bit is valid (if (i32.eqz (i64.eqz (local.get $mouse-bit))) (then ;; end[click-mouse-bit].x = mouse-dx ;; end[click-mouse-bit].y = mouse-dy (i32.store16 offset=0xb00 (local.tee $click-mouse-src*4 (call $bit-to-src*4 (global.get $click-mouse-bit))) (i32.or (i32.shl (i32.trunc_f32_s (local.get $mouse-dy)) (i32.const 8)) (i32.trunc_f32_s (local.get $mouse-dx)))) ;; If mouse-bit != click-mouse-bit (if (i64.ne (global.get $click-mouse-bit) (local.get $mouse-bit)) (then ;; end[mouse-bit].x = -mouse-dx ;; end[mouse-bit].y = -mouse-dy (i32.store16 offset=0xb00 (local.get $mouse-src*4) (i32.or (i32.shl (i32.trunc_f32_s (f32.neg (local.get $mouse-dy))) (i32.const 8)) (i32.trunc_f32_s (f32.neg (local.get $mouse-dx))))))))) ;; Skip the following if the button is still pressed. (br_if $reset-prev-mouse (i32.load8_u (i32.const 2))) (global.set $state (i32.const 1)) ;; Skip the following if mouse-bit is not valid or is different from ;; the clicked cell. Since we know that the button was released, we branch ;; to $reset-all-mouse, which will reset the clicked mouse too. (br_if $reset-all-mouse (i32.or (i64.eqz (local.get $mouse-bit)) (i64.eq (global.get $click-mouse-bit) (local.get $mouse-bit)))) ;; swap the mouse-bit and click-mouse-bit bits in all grids. (call $swap-all-grids-bits (local.get $mouse-bit) (global.get $click-mouse-bit)) (global.set $matched (call $match-all-grids-patterns (i32.const 8))) ;; Try to find matches. If none, then reset the swap. (if (i64.eqz (global.get $matched)) (then ;; Swap back (call $swap-all-grids-bits (local.get $mouse-bit) (global.get $click-mouse-bit))) (else ;; force the cells back to 0,0 (i32.store16 offset=0x900 (local.get $mouse-src*4) (i32.const 0)) (i32.store16 offset=0x900 (local.get $click-mouse-src*4) (i32.const 0)) (i32.store16 offset=0xb00 (local.get $mouse-src*4) (i32.const 0)) (i32.store16 offset=0xb00 (local.get $click-mouse-src*4) (i32.const 0)) (br $matched))) ;; fallthrough end $reset-all-mouse ;; Animate mouse and click-mouse cells back to their original place (call $animate-cells (i64.or (local.get $mouse-bit) (global.get $click-mouse-bit)) (i32.const 0)) ;; fallthrough end $reset-prev-mouse ;; Reset prev-mouse-bit, as long as it isn't the same as mouse-bit: ;; prev-mouse-bit & ~mouse-bit (call $animate-cells (i64.and (global.get $prev-mouse-bit) (i64.xor (local.get $mouse-bit) (i64.const -1))) (i32.const 0)) (global.set $prev-mouse-bit (local.get $mouse-bit)) (br $done) end $init ;; Decompress from [0xd00,0x109c] -> 0xc4. ;; ;; While src < 0x109c: ;; byte = readbyte() ;; if byte <= 7: ;; len = byte + 3 ;; dist = readbyte() ;; copy data from mem[dst-dist:dst-dist+len] to mem[dst:dst+len] ;; else: ;; mem[dst] = byte + 230 ;; (loop $loop (if (result i32) (i32.le_s (local.tee $byte-or-len (i32.load8_u offset=0xd00 (local.get $src))) (i32.const 7)) (then ;; back-reference (local.set $copy-end (i32.add (i32.add (local.get $dst) (local.get $byte-or-len)) (i32.const 3))) (loop $copy-loop (i32.store8 offset=0xc4 (local.get $dst) (i32.load8_u offset=0xc4 (i32.sub (local.get $dst) (i32.load8_u offset=0xd01 (local.get $src))))) (br_if $copy-loop (i32.lt_s (local.tee $dst (i32.add (local.get $dst) (i32.const 1))) (local.get $copy-end)))) ;; src addend (i32.const 2)) (else ;; literal data (i32.store8 offset=0xc3 (local.tee $dst (i32.add (local.get $dst) (i32.const 1))) (i32.add (local.get $byte-or-len) (i32.const 230))) ;; src addend (i32.const 1))) (br_if $loop (i32.lt_s (local.tee $src (i32.add (; result ;) (local.get $src))) (i32.const 0x39c)))) ;; fallthrough end $removing (br_if $done (global.get $animating)) ;; Remove the matched cells... (loop $loop ;; grid-bitmap[grid-offset] &= ~pattern (i64.store offset=0x700 (local.get $grid-offset) (i64.and (i64.load offset=0x700 (local.get $grid-offset)) (i64.xor (global.get $matched) (i64.const -1)))) ;; grid-offset += 8 ;; loop if grid-offset < 64 (br_if $loop (i32.lt_u (local.tee $grid-offset (i32.add (local.get $grid-offset) (i32.const 8))) (i32.const 64)))) ;; ... and move down cells to fill the holes (local.set $empty (global.get $matched)) (block $move-down-exit (loop $move-down-loop ;; Exit the loop if there are no further bits. (br_if $move-down-exit (i64.eqz (local.get $empty))) (local.set $1<<idx (i64.shl (i64.const 1) ;; Get the index of the lowest set bit (local.tee $idx (i64.ctz (local.get $empty))))) ;; If there is not a cell above this one... (if (i64.eqz ;; Find the next cell above that is not empty: invert the empty ;; pattern and mask it with a column, shifted by idx. (local.tee $above-bits (i64.and (i64.xor (local.get $empty) (i64.const -1)) (i64.shl (i64.const 0x0101010101010101) (local.get $idx))))) (then ;; then we need to fill with a new random cell. ;; ;; random-grid = int(random() * 8) << 3 ;; grid-bitmap[random-grid] |= (1 << idx) (i64.store offset=0x700 (local.tee $random-grid (i32.shl (i32.trunc_f32_u (f32.mul (call $random) (f32.const 8))) (i32.const 3))) (i64.or (i64.load offset=0x700 (local.get $random-grid)) (local.get $1<<idx))) ;; Set above-idx so it is always the maximum value (used below) (local.set $above-idx (i64.add (local.get $idx) (i64.const 56)))) (else ;; If there is cell above, move iti down (call $swap-all-grids-bits (i64.shl (i64.const 1) ;; Find the lowest set bit in $above-bits (local.tee $above-idx (i64.ctz (local.get $above-bits)))) (local.get $1<<idx)) ;; Set above-bit in empty so we will fill it. (local.set $empty (i64.or (local.get $empty) (i64.shl (i64.const 1) (local.get $above-idx)))))) ;; Reset the x,w,h to 0, but set the y pixel offset to the y cell ;; difference * 17. (i64.store32 offset=0x900 (i32.wrap_i64 (i64.shl (local.get $idx) (i64.const 2))) (i64.shl (i64.and (i64.mul (i64.shr_s (i64.sub (local.get $idx) (local.get $above-idx)) (i64.const 3)) (i64.const 17)) (i64.const 0xff)) (i64.const 8))) ;; Now animate it back to 0. (call $animate-cells (local.get $1<<idx) (i32.const 0)) ;; Clear this bit (it has now been filled). (local.set $empty (i64.and (local.get $empty) (i64.sub (local.get $empty) (i64.const 1)))) ;; Always loop (br $move-down-loop))) ;; Set state to $falling (global.set $state (i32.const 4)) (br $done) end $falling (br_if $done (global.get $animating)) ;; Check whether any new matches (without swaps) occurred. (global.set $matched (call $match-all-grids-patterns (i32.const 8))) ;; If there are any matches (including swaps), then keep going. (br_if $matched (i32.eqz (i64.eqz (call $match-all-grids-patterns (i32.const 72))))) ;; otherwise fallthrough to gameover, with a brief animation. (call $animate-cells (i64.const -1) (i32.const 0x04_04_fe_fe)) (global.set $state (i32.const 5)) end $gameover ;; draw game over sprite (call $draw-sprite (i32.const 8) (i32.const 1) (i32.const 0x450) (i32.const 40) (i32.const 8) (i32.const 80) (i32.const 8) (i32.const 3) (i32.const 7) (i32.const 1)) ;; don't reset until animation is finished and mouse is clicked (br_if $done (i32.or (global.get $animating) (i32.eqz (i32.load8_u (i32.const 2))))) ;; Reset the entire board. (global.set $matched (i64.const -1)) ;; Reset the score (use -64 since 64 will be added below) (global.set $score (i32.const -64)) end $matched ;; Add score (global.set $score (i32.add (global.get $score) (i32.wrap_i64 (i64.popcnt (global.get $matched))))) ;; Animate the matched cells (call $animate-cells (global.get $matched) (i32.const 0xf1_f1_08_08)) ;; If there are new matches, then remove them, otherwise go back to $idle (global.set $state (select (i32.const 1) (i32.const 3) (i64.eqz (global.get $matched)))) end $done ;; Animate ;; mul-t = 1 (local.set $mul-t (f32.const 1)) (loop $animate-loop ;; ilerp = (a,b,t) => return a + (b - a) * t ;; easeOutCubic(t) = t => t * (3 + t * (t - 3)) ;; current[i] = ilerp(start[i], end[i], easeOutCubic(t)) (i32.store8 offset=0x900 (local.get $i-addr) (i32.add (local.tee $a (i32.load8_s offset=0xa00 (local.get $i-addr))) (i32.trunc_f32_s (f32.mul (f32.convert_i32_s (i32.sub (i32.load8_s offset=0xb00 (local.get $i-addr)) (local.get $a))) (f32.mul ;; t = Math.min(t[i] + speed, 1) (local.tee $t (f32.min (f32.add (f32.load offset=0xc00 (local.get $t-addr)) (f32.const 0.005)) (f32.const 1))) (f32.add (f32.const 3) (f32.mul (local.get $t) (f32.sub (local.get $t) (f32.const 3))))))))) ;; t[i] = t (f32.store offset=0xc00 (local.get $t-addr) (local.get $t)) ;; mul-t *= t (local.set $mul-t (f32.mul (local.get $mul-t) (local.get $t))) ;; i-addr += 1 ;; t-addr = i-addr & ~3 (local.set $t-addr (i32.and (local.tee $i-addr (i32.add (local.get $i-addr) (i32.const 1))) (i32.const 0xfc))) ;; loop if i-addr < 256 (br_if $animate-loop (i32.lt_s (local.get $i-addr) (i32.const 256)))) ;; If all t values are 1 (i.e. all animations are finished), then multiplying ;; them together will also be 1. (global.set $animating (f32.ne (local.get $mul-t) (f32.const 1))) (call $draw-grids (i64.const -1)) ;; Mask with all 1s ;; Draw the moused-over cell again, so they're on top (call $draw-grids (local.get $mouse-bit)) ;; Draw score (local.set $x (i32.const 111)) (local.set $divisor (i32.const 1000)) (loop $digit-loop (call $draw-sprite (local.tee $x (i32.add (local.get $x) (i32.const 8))) (i32.const 1) (i32.add (i32.const 0x400) (i32.shl (i32.rem_u (i32.div_u (global.get $score) (local.get $divisor)) (i32.const 10)) (i32.const 3))) (i32.const 8) (i32.const 8) (i32.const 8) (i32.const 8) (i32.const 3) (i32.const 7) (i32.const 1)) ;; divisor /= 10 ;; looop if divisor != 0 (br_if $digit-loop (local.tee $divisor (i32.div_u (local.get $divisor) (i32.const 10))))) ) (func $match-all-grids-patterns (param $last-pattern i32) (result i64) (local $result i64) (local $grid i64) (local $pattern i64) (local $shifts i64) (local $grid-offset i32) (local $i i32) (loop $grid-loop ;; grid = grids[i] (local.set $grid (i64.load offset=0x700 (local.get $grid-offset))) ;; i = 0; (local.set $i (i32.const 0)) (loop $pattern-loop ;; pattern = match-patterns[i] (local.set $pattern (i64.load32_u offset=0x578 (local.get $i))) ;; shifts = match-shifts[i] (local.set $shifts (i64.load offset=0x5c0 (i32.shl (local.get $i) (i32.const 1)))) (loop $bit-loop ;; if ((shifts & 1) && ((grid & pattern) == pattern)) ... (if (i32.and (i32.wrap_i64 (i64.and (local.get $shifts) (i64.const 1))) (i64.eq (i64.and (local.get $grid) (local.get $pattern)) (local.get $pattern))) (then ;; result |= pattern (local.set $result (i64.or (local.get $result) (local.get $pattern))))) ;; pattern <<= 1 (local.set $pattern (i64.shl (local.get $pattern) (i64.const 1))) ;; shifts >>= 1 ;; loop if shifts != 0 (br_if $bit-loop (i32.eqz (i64.eqz (local.tee $shifts (i64.shr_u (local.get $shifts) (i64.const 1))))))) ;; i += 4 ;; loop if i < last-pattern (br_if $pattern-loop (i32.lt_u (local.tee $i (i32.add (local.get $i) (i32.const 4))) (local.get $last-pattern)))) ;; grid-offset += 8 ;; loop if grid-offset < 64 (br_if $grid-loop (i32.lt_u (local.tee $grid-offset (i32.add (local.get $grid-offset) (i32.const 8))) (i32.const 64)))) ;; return result (local.get $result) ) (func $swap-all-grids-bits (param $a i64) (param $b i64) (local $grid-offset i32) (local $bits i64) (local $a|b i64) (loop $loop ;; if popcnt(bits & (a | b)) == 1 ;; i.e. bits are different (if (i64.eq (i64.popcnt (i64.and ;; bits = mem[grid-offset] (local.tee $bits (i64.load offset=0x700 (local.get $grid-offset))) (local.tee $a|b (i64.or (local.get $a) (local.get $b))))) (i64.const 1)) (then ;; mem[grid-offset] = bits ^ (a | b) (i64.store offset=0x700 (local.get $grid-offset) (i64.xor (local.get $bits) (local.get $a|b))))) ;; grid-offset += 8 ;; loop if grid-offset < 64 (br_if $loop (i32.lt_s (local.tee $grid-offset (i32.add (local.get $grid-offset) (i32.const 8))) (i32.const 64)))) ) (func $get-mouse-bit (param $x i32) (param $y i32) (result i64) ;; return ... (select ;; 1 << ((y / 17) * 8 + (x / 17)) (i64.shl (i64.const 1) (i64.extend_i32_u (i32.add (i32.mul (i32.div_s ;; y = 147 - y (local.tee $y (i32.sub (i32.const 147) (local.get $y))) (i32.const 17)) (i32.const 8)) (i32.div_s ;; x -= 7 (local.tee $x (i32.sub (local.get $x) (i32.const 7))) (i32.const 17))))) ;; -1 (i64.const 0) ;; if (x < 136) && (y < 136) (i32.and (i32.lt_u (local.get $x) (i32.const 136)) (i32.lt_u (local.get $y) (i32.const 136)))) ) (func $bit-to-src*4 (param $bit i64) (result i32) (i32.shl (i32.wrap_i64 (i64.ctz (local.get $bit))) (i32.const 2)) ) (func $animate-cells (param $bits i64) (param $h_w_y_x i32) (local $src*4 i32) (loop $loop ;; Exit the function if there are no further bits. (br_if 1 (i64.eqz (local.get $bits))) ;; Set the start x/y/w/h to the current x/y/w/h. (i32.store offset=0xa00 (local.tee $src*4 (call $bit-to-src*4 (local.get $bits))) (i32.load offset=0x900 (local.get $src*4))) ;; Set the destination x/y/w/h (i32.store offset=0xb00 (local.get $src*4) (local.get $h_w_y_x)) ;; Set the time value to 1 - time. (f32.store offset=0xc00 (local.get $src*4) (f32.sub (f32.const 1) (f32.load offset=0xc00 (local.get $src*4)))) ;; Clear the lowest set bit: bits &= bits - 1 (local.set $bits (i64.and (local.get $bits) (i64.sub (local.get $bits) (i64.const 1)))) ;; Always loop (br $loop) ) ) (func $draw-grids (param $mask i64) (local $grid-offset i32) (local $cell-idx i32) (local $anim-idx i32) (local $bits i64) (loop $grid-loop ;; bits = grid[grid-offset] & mask (local.set $bits (i64.and (i64.load offset=0x700 (local.get $grid-offset)) (local.get $mask))) (block $cell-exit (loop $cell-loop ;; Break out of the loop if bits == 0 (br_if $cell-exit (i64.eqz (local.get $bits))) ;; Draw the cell at that index (call $draw-sprite (i32.add ;; base x-coordinate: 7 + (idx & 7) * 17 (i32.add (i32.const 7) (i32.mul (i32.and ;; Get the index of the lowest set bit (local.tee $cell-idx (i32.wrap_i64 (i64.ctz (local.get $bits)))) (i32.const 7)) (i32.const 17))) ;; x offset (i32.load8_s offset=0x900 (local.tee $anim-idx (i32.shl (local.get $cell-idx) (i32.const 2))))) (i32.add ;; base y-coordinate: (150 - 17 - 2) - (idx >> 3) * 17 (i32.sub (i32.const 131) (i32.mul (i32.shr_u (local.get $cell-idx) (i32.const 3)) (i32.const 17))) ;; y offset (i32.load8_s offset=0x901 (local.get $anim-idx))) ;; src (i32.shl (local.get $grid-offset) (i32.const 4)) ;; sw / sh (i32.const 16) (i32.const 16) ;; base w (i32.add (i32.const 16) ;; w offset (i32.load8_s offset=0x902 (local.get $anim-idx))) ;; base h (i32.add (i32.const 16) ;; h offset (i32.load8_s offset=0x903 (local.get $anim-idx))) (i32.const 1) (i32.const 1) (i32.const 0xf)) ;; Clear the lowest set bit: bits &= bits - 1 (local.set $bits (i64.and (local.get $bits) (i64.sub (local.get $bits) (i64.const 1)))) ;; Always loop (br $cell-loop))) ;; grid-offset += 8 ;; loop if grid-offset < 64 (br_if $grid-loop (i32.lt_s (local.tee $grid-offset (i32.add (local.get $grid-offset) (i32.const 8))) (i32.const 64)))) ) (func $draw-sprite (param $x i32) (param $y i32) (param $src i32) (param $sw i32) (param $sh i32) (param $dw i32) (param $dh i32) (param $pixels-per-byte i32) (param $src-offset-mask i32) (param $palidx-mask i32) (local $i i32) (local $j i32) (local $x+i i32) (local $y+j i32) (local $src-offset i32) (local $palidx i32) (local $dx f32) (local $dy f32) ;; dx = sw / dw (local.set $dx (f32.div (f32.convert_i32_s (local.get $sw)) (f32.convert_i32_s (local.get $dw)))) ;; dy = sh / dh (local.set $dy (f32.div (f32.convert_i32_s (local.get $sh)) (f32.convert_i32_s (local.get $dh)))) ;; for (j = 0; j < dh; j++) (loop $y-loop (local.set $i (i32.const 0)) ;; for (i = 0; i < dw; i++) (loop $x-loop ;; src-offset = (sw * j * dy) + i * dx ;; palidx = (mem[src + (src-offset >> pixels-per-byte)] >> ;; ((src-offset & src-offset-mask) << (3 - pixels-per-byte))) & ;; palidx-mask; (local.set $palidx (i32.and (i32.shr_u (i32.load8_u offset=0x100 (i32.add (local.get $src) (i32.shr_u (local.tee $src-offset (i32.add (i32.mul (local.get $sw) (i32.trunc_f32_s (f32.mul (f32.convert_i32_s (local.get $j)) (local.get $dy)))) (i32.trunc_f32_s (f32.mul (f32.convert_i32_s (local.get $i)) (local.get $dx))))) (local.get $pixels-per-byte)))) (i32.shl (i32.and (local.get $src-offset) (local.get $src-offset-mask)) (i32.sub (i32.const 3) (local.get $pixels-per-byte)))) (local.get $palidx-mask))) ;; if (palidx != 0) (if (local.get $palidx) (then ;; skip if the x/y coordinate is out of bounds (br_if 0 (i32.or (i32.ge_u (local.tee $x+i (i32.add (local.get $x) (local.get $i))) (i32.const 150)) (i32.ge_u (local.tee $y+j (i32.add (local.get $y) (local.get $j))) (i32.const 150)))) ;; color = mem[0xc0 + (palidx << 2)] ;; mem[0x1100 + (y * 150 + x) * 4] = color (i32.store offset=0x1100 (i32.mul (i32.add (i32.mul (local.get $y+j) (i32.const 150)) (local.get $x+i)) (i32.const 4)) (i32.load offset=0xc0 (i32.shl (local.get $palidx) (i32.const 2)))))) ;; loop if i < w (br_if $x-loop (i32.lt_s ;; i += 1 (local.tee $i (i32.add (local.get $i) (i32.const 1))) (local.get $dw))) ) ;; loop if j < h (br_if $y-loop (i32.lt_s ;; j += 1 (local.tee $j (i32.add (local.get $j) (i32.const 1))) (local.get $dh))) ) ) (data (i32.const 0xd00) "\f9\8b\40\19\15\0c\50\19\80\53\4b\19\01\01\c6\4c" "\4c\19\7d\b5\19\19\79\e7\fe\19\f3\71\7d\19\e5\f5" "\16\19\a2\70\55\19\5f\42\56\19\75\88\fb\19\b3\ff" "\6a\19\60\1a\7a\19\9a\1a\b0\19\1a\1a\1a\2b\2b\00" "\05\00\07\3c\3c\01\09\2a\3c\00\01\1b\1a\1a\3b\01" "\08\2c\01\0f\4d\00\02\1b\05\08\00\17\01\08\2c\3b" "\3d\01\08\4c\2c\3b\4d\01\28\01\08\02\01\2c\2a\4c" "\5e\00\01\3d\00\30\01\0f\00\49\3b\4c\4d\4d\3d\2c" "\01\58\4c\01\0f\06\68\05\78\2a\01\08\00\18\6b\01" "\18\2f\1a\2b\6f\2f\2b\2c\6b\6f\2b\6f\00\01\6b\01" "\05\6f\6f\2f\6c\03\0c\3b\2c\00\0c\06\08\2f\01\08" "\6b\2f\6a\3b\6b\3b\2c\2f\2c\1f\2a\2c\2b\00\01\3b" "\1b\07\80\01\80\3b\01\80\5e\5e\2e\02\80\4b\01\0f" "\07\80\05\f8\05\08\00\73\01\09\2a\01\73\01\90\02" "\7b\00\0f\4f\6d\4f\6d\6f\1b\2a\6f\4d\6f\00\03\1b" "\6b\00\0d\00\13\01\88\02\21\6b\03\20\2f\6b\7f\03" "\08\2a\8f\02\18\1b\2a\90\70\02\08\7a\91\81\4d\4d" "\6d\2f\1a\00\08\9d\9d\6d\00\58\90\30\9d\a2\2d\00" "\68\7a\1a\9b\a2\03\80\91\91\03\07\80\80\01\09\8a" "\80\00\01\21\1a\1a\81\01\08\90\03\0f\00\11\05\08" "\81\80\50\7d\80\4d\80\90\07\08\02\01\06\08\93\80" "\4e\5e\5d\4e\7e\21\93\80\00\ff\4d\7d\21\23\83\01" "\10\8e\23\1a\93\02\3f\23\1a\23\01\68\23\23\1a\00" "\09\91\1a\00\07\1a\1a\4d\4d\02\80\4a\4d\4d\1d\00" "\06\1d\01\38\02\06\bd\c4\01\0b\4d\4d\c4\01\08\cd" "\d5\d5\c4\c4\d4\d5\55\2d\3c\cc\d5\d5\d5\3c\4b\2a" "\3c\02\01\1b\00\08\4d\00\02\07\08\06\18\01\3b\3c" "\1b\1a\3b\4c\4d\4d\3d\2c\1a\1a\2a\3c\4c\01\0f\1a" "\1a\2b\3c\3c\2b\02\71\2b\03\07\1a\e6\e6\03\07\5e" "\5e\01\09\da\63\00\01\26\1a\1a\b6\50\b0\b0\50\e0" "\1a\da\80\5d\7d\00\03\26\da\50\5e\4e\00\03\26\86" "\03\08\e0\f6\57\5e\4e\00\03\e7\f6\f7\5d\ed\00\03" "\e7\3b\47\47\47\4d\ec\ec\2c\00\80\4c\4d\3d\00\80" "\2b\01\08\2c\00\88\00\81\3d\3b\00\18\3b\00\9f\3b" "\2c\3b\3c\01\80\00\08\2c\01\80\2a\3c\03\83\1a\1a" "\28\03\07\fa\08\03\08\08\18\08\fa\08\08\00\04\18" "\19\18\19\19\19\18\09\01\06\00\01\09\fa\18\d9\d5" "\19\d9\d5\08\fa\19\19\d5\15\d5\15\28\00\08\01\01" "\01\08\d9\15\d5\07\08\1a\02\31\09\1a\00\08\d5\d5" "\d5\00\08\fa\00\36\15\01\66\08\19\19\03\65\08\04" "\6c\05\01\4a\1d\04\08\4d\03\08\55\4d\02\11\ca\d5" "\d5\25\02\17\00\48\01\08\4d\5e\4d\5e\01\19\d5\ce" "\4d\ce\00\2a\ca\d5\5e\00\02\00\1f\cd\00\20\00\2a" "\4d\02\01\1d\ca\55\4d\5e\5e\5e\4d\4d\00\3e\65\5e" "\ce\d5\d5\03\1f\00\42\4a\03\20\05\75\58\99\7d\00" "\01\99\58\4a\56\56\4a\4a\4a\98\98\58\98\7a\98\59" "\1d\99\99\00\18\92\52\7d\99\98\80\81\7d\99\99\7a" "\7a\7a\99\99\1d\59\99\7a\99\59\56\58\21\59\99\00" "\30\99\99\4a\32\32\26\26\26\36\58\00\0d\00\03\00" "\30\99\98\4a\58\38\a8\f3\38\6d\91\f9\15\b8\71\11" "\5b\c4\9c\6e\ab\f7\c5\b8\6e\11\f7\a5\b8\6e\91\6b" "\a4\00\0f\79\a4\b8\91\b1\68\a4\38\3d\b1\21\00\7c" "\1b\1b\1b\1a\1d\1e\1a\1a\1f\1c\1a\1a\20\1b\1a\1a" "\1e\00\96\1c\1f\00\18\20\1a\1a\01\f3\27\02\24\1c" "\1a\1b\1c\1b\1a\1c\00\2c\1c\02\08\01\10\00\04\1b" "\03\03\59\04\01\19\02\01\1a\1a\04\0f\07\08\07\08" "\07\08\07\08\1a\39\07\01\02\01\99\02\01\1a\1a\07" "\08\07\08\07\08\07\08\04\77\02\08\19" )
0
0.697091
1
0.697091
game-dev
MEDIA
0.823095
game-dev
0.861622
1
0.861622
LmeSzinc/StarRailCopilot
8,265
route/rogue/Combat/Luofu_StargazerNavalia_F1.py
from tasks.map.control.waypoint import Waypoint from tasks.map.keywords.plane import Luofu_StargazerNavalia from tasks.map.route.base import locked_position from tasks.rogue.route.base import RouteBase class Route(RouteBase): def Luofu_StargazerNavalia_F1_X183Y315(self): """ | Waypoint | Position | Direction | Rotation | | -------- | ------------------------- | --------- | -------- | | spawn | Waypoint((183.4, 315.6)), | 98.9 | 89 | | item | Waypoint((208.5, 306.1)), | 82.5 | 80 | | enemy | Waypoint((247.4, 320.2)), | 114.1 | 112 | | exit_ | Waypoint((243.4, 319.4)), | 274.2 | 89 | | exit1 | Waypoint((251.4, 311.5)), | 96.9 | 89 | | exit2 | Waypoint((251.4, 323.5)), | 96.9 | 89 | """ self.map_init(plane=Luofu_StargazerNavalia, floor="F1", position=(183.4, 315.6)) self.register_domain_exit( Waypoint((243.4, 319.4)), end_rotation=89, left_door=Waypoint((251.4, 311.5)), right_door=Waypoint((251.4, 323.5))) item = Waypoint((208.5, 306.1)) enemy = Waypoint((247.4, 320.2)) # ===== End of generated waypoints ===== self.minimap.lock_rotation(90) self.clear_item(item) self.clear_enemy(enemy) @locked_position def Luofu_StargazerNavalia_F1_X203Y317(self): """ | Waypoint | Position | Direction | Rotation | | -------------- | ------------------------- | --------- | -------- | | spawn | Waypoint((203.8, 317.4)), | 96.7 | 91 | | enemy | Waypoint((254.2, 318.9)), | 96.8 | 91 | | exit_ | Waypoint((254.2, 318.9)), | 96.8 | 91 | | exit1_X258Y313 | Waypoint((258.1, 313.3)), | 94.2 | 91 | | exit2 | Waypoint((257.6, 325.5)), | 94.2 | 91 | """ self.map_init(plane=Luofu_StargazerNavalia, floor="F1", position=(203.8, 317.4)) self.register_domain_exit( Waypoint((254.2, 318.9)), end_rotation=91, left_door=Waypoint((258.1, 313.3)), right_door=Waypoint((257.6, 325.5))) enemy = Waypoint((254.2, 318.9)) # ===== End of generated waypoints ===== self.minimap.lock_rotation(90) self.clear_enemy(enemy) def Luofu_StargazerNavalia_F1_X215Y192(self): """ | Waypoint | Position | Direction | Rotation | | ----------- | ------------------------- | --------- | -------- | | spawn | Waypoint((215.5, 192.6)), | 190.1 | 184 | | item1 | Waypoint((212.0, 241.6)), | 194.8 | 204 | | enemy1 | Waypoint((188.6, 248.2)), | 223.8 | 221 | | node2 | Waypoint((178.9, 278.9)), | 198.7 | 195 | | enemy4 | Waypoint((247.6, 317.2)), | 198.7 | 96 | | enemy2left | Waypoint((216.6, 322.8)), | 101.1 | 96 | | enemy2right | Waypoint((176.6, 318.6)), | 206.2 | 103 | | exit_ | Waypoint((247.6, 317.2)), | 198.7 | 96 | | exit1 | Waypoint((252.6, 312.0)), | 96.9 | 89 | | exit2 | Waypoint((252.8, 324.8)), | 96.2 | 89 | """ self.map_init(plane=Luofu_StargazerNavalia, floor="F1", position=(215.5, 192.6)) self.register_domain_exit( Waypoint((247.6, 317.2)), end_rotation=96, left_door=Waypoint((252.6, 312.0)), right_door=Waypoint((252.8, 324.8))) item1 = Waypoint((212.0, 241.6)) enemy1 = Waypoint((188.6, 248.2)) node2 = Waypoint((178.9, 278.9)) enemy4 = Waypoint((247.6, 317.2)) enemy2left = Waypoint((216.6, 322.8)) enemy2right = Waypoint((176.6, 318.6)) # ===== End of generated waypoints ===== # Ignore items self.clear_enemy(enemy1.straight_run()) self.rotation_set(120) self.minimap.lock_rotation(120) self.clear_enemy( node2, enemy2right, enemy2left, ) self.clear_enemy( enemy2left, enemy4, ) def Luofu_StargazerNavalia_F1_X432Y593(self): """ | Waypoint | Position | Direction | Rotation | | -------------- | ------------------------- | --------- | -------- | | spawn | Waypoint((432.7, 593.4)), | 96.7 | 91 | | event | Waypoint((449.6, 606.4)), | 135.8 | 131 | | item1_X464Y586 | Waypoint((464.6, 586.5)), | 64.9 | 61 | | enemy1 | Waypoint((506.2, 596.2)), | 96.8 | 94 | | item2 | Waypoint((522.8, 589.0)), | 64.9 | 64 | | enemy3 | Waypoint((560.5, 601.8)), | 96.8 | 96 | | exit_ | Waypoint((565.6, 603.3)), | 94.2 | 91 | | exit1 | Waypoint((571.0, 597.0)), | 81.1 | 78 | | exit2 | Waypoint((570.8, 610.8)), | 96.8 | 96 | """ self.map_init(plane=Luofu_StargazerNavalia, floor="F1", position=(432.7, 593.4)) self.register_domain_exit( Waypoint((565.6, 603.3)), end_rotation=91, left_door=Waypoint((571.0, 597.0)), right_door=Waypoint((570.8, 610.8))) event = Waypoint((449.6, 606.4)) item1_X464Y586 = Waypoint((464.6, 586.5)) enemy1 = Waypoint((506.2, 596.2)) item2 = Waypoint((522.8, 589.0)) enemy3 = Waypoint((560.5, 601.8)) # ===== End of generated waypoints ===== self.minimap.lock_rotation(90) # Ignore items self.clear_enemy(enemy1) # Ignore enemy2 self.clear_enemy(enemy3) if self.minimap.position_diff(enemy3.position) > 35: self.clear_enemy(enemy3) @locked_position def Luofu_StargazerNavalia_F1_X499Y581(self): """ | Waypoint | Position | Direction | Rotation | | ------------- | ------------------------- | --------- | -------- | | spawn | Waypoint((499.6, 581.5)), | 157.2 | 151 | | item_X502Y605 | Waypoint((502.6, 605.0)), | 180.0 | 179 | | enemy | Waypoint((519.0, 623.0)), | 149.8 | 149 | | exit_ | Waypoint((524.4, 624.7)), | 166.7 | 161 | | exit1 | Waypoint((533.4, 631.2)), | 160.8 | 158 | | exit2 | Waypoint((517.9, 636.5)), | 160.9 | 158 | """ self.map_init(plane=Luofu_StargazerNavalia, floor="F1", position=(499.6, 581.5)) self.register_domain_exit( Waypoint((524.4, 624.7)), end_rotation=161, left_door=Waypoint((533.4, 631.2)), right_door=Waypoint((517.9, 636.5))) item_X502Y605 = Waypoint((502.6, 605.0)) enemy = Waypoint((519.0, 623.0)) # ===== End of generated waypoints ===== self.minimap.lock_rotation(151) self.clear_item(item_X502Y605) self.clear_enemy(enemy) def Luofu_StargazerNavalia_F1_X521Y447(self): """ | Waypoint | Position | Direction | Rotation | | -------- | ------------------------- | --------- | -------- | | spawn | Waypoint((521.4, 447.5)), | 188.1 | 181 | | enemy | Waypoint((521.2, 507.2)), | 98.8 | 186 | | exit_ | Waypoint((521.2, 507.2)), | 98.8 | 186 | | exit1 | Waypoint((530.8, 514.9)), | 183.8 | 181 | | exit2 | Waypoint((514.8, 514.8)), | 183.8 | 181 | """ self.map_init(plane=Luofu_StargazerNavalia, floor="F1", position=(521.4, 447.5)) self.register_domain_exit( Waypoint((521.2, 507.2)), end_rotation=186, left_door=Waypoint((530.8, 514.9)), right_door=Waypoint((514.8, 514.8))) enemy = Waypoint((521.2, 507.2)) # ===== End of generated waypoints ===== self.minimap.lock_rotation(180) self.clear_enemy(enemy)
0
0.757264
1
0.757264
game-dev
MEDIA
0.949329
game-dev
0.762837
1
0.762837
eccentricdevotion/TARDIS
6,895
src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISQuitListener.java
/* * Copyright (C) 2025 eccentric_nz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.eccentric_nz.TARDIS.listeners; import me.eccentric_nz.TARDIS.TARDIS; import me.eccentric_nz.TARDIS.arch.TARDISArchPersister; import me.eccentric_nz.TARDIS.artron.TARDISAdaptiveBoxLampToggler; import me.eccentric_nz.TARDIS.artron.TARDISBeaconToggler; import me.eccentric_nz.TARDIS.artron.TARDISLampToggler; import me.eccentric_nz.TARDIS.camera.TARDISCameraTracker; import me.eccentric_nz.TARDIS.database.data.Tardis; import me.eccentric_nz.TARDIS.database.resultset.ResultSetCurrentFromId; import me.eccentric_nz.TARDIS.database.resultset.ResultSetTardis; import me.eccentric_nz.TARDIS.enumeration.ChameleonPreset; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; import java.util.HashMap; import java.util.Optional; import java.util.UUID; /** * @author eccentric_nz */ public class TARDISQuitListener implements Listener { private final TARDIS plugin; public TARDISQuitListener(TARDIS plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); UUID uuid = player.getUniqueId(); // remove camera viewers if (TARDISCameraTracker.SPECTATING.containsKey(uuid)) { // set their location back to the TARDIS interior plugin.getTrackerKeeper().getJunkRelog().put(uuid, TARDISCameraTracker.SPECTATING.get(uuid).location()); TARDISCameraTracker.SPECTATING.remove(uuid); } // remove if Junk TARDIS traveller if (plugin.getGeneralKeeper().getJunkTravellers().contains(uuid)) { // check if they are in the vortex if (plugin.getUtils().inTARDISWorld(player)) { // set their location to the junk TARDISes destination plugin.getTrackerKeeper().getJunkRelog().put(uuid, plugin.getGeneralKeeper().getJunkDestination()); } plugin.getGeneralKeeper().getJunkTravellers().remove(uuid); } // if player is flying TARDIS exterior stop sound loop Optional.ofNullable(plugin.getTrackerKeeper().getFlyingReturnLocation().get(uuid)).ifPresent(value -> plugin.getServer().getScheduler().cancelTask(value.sound())); // forget the players Police Box chunk HashMap<String, Object> wherep = new HashMap<>(); wherep.put("uuid", uuid.toString()); ResultSetTardis rs = new ResultSetTardis(plugin, wherep, "", false); if (rs.resultSet()) { Tardis tardis = rs.getTardis(); if (plugin.getConfig().getBoolean("police_box.keep_chunk_force_loaded")) { ResultSetCurrentFromId rsc = new ResultSetCurrentFromId(plugin, tardis.getTardisId()); if (rsc.resultSet()) { World w = rsc.getCurrent().location().getWorld(); if (w != null) { Chunk chunk = w.getChunkAt(rsc.getCurrent().location()); chunk.removePluginChunkTicket(plugin); } } } // power down TARDIS if (plugin.getConfig().getBoolean("allow.power_down") && plugin.getConfig().getBoolean("allow.power_down_on_quit")) { // check if powered on if (tardis.isPoweredOn()) { // not if flying or uninitialised int id = tardis.getTardisId(); if (!tardis.isTardisInit() || isTravelling(id) || !tardis.isHandbrakeOn()) { return; } // power off ChameleonPreset preset = tardis.getPreset(); boolean hidden = tardis.isHidden(); boolean lights = tardis.isLightsOn(); // police box lamp, delay it incase the TARDIS needs rebuilding long delay = 1L; // if hidden, rebuild if (hidden) { plugin.getServer().dispatchCommand(plugin.getConsole(), "tardisremote " + player.getName() + " rebuild"); delay = 20L; } if (preset.equals(ChameleonPreset.ADAPTIVE) || preset.usesArmourStand()) { plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> new TARDISAdaptiveBoxLampToggler(plugin).toggleLamp(id, false, preset), delay); } // if lights are on, turn them off if (lights) { new TARDISLampToggler(plugin).flickSwitch(id, uuid, true, tardis.getSchematic().getLights()); } // if beacon is on turn it off new TARDISBeaconToggler(plugin).flickSwitch(uuid, id, false); // turn force field off plugin.getTrackerKeeper().getActiveForceFields().remove(uuid); // update database HashMap<String, Object> wheret = new HashMap<>(); wheret.put("tardis_id", id); HashMap<String, Object> sett = new HashMap<>(); sett.put("powered_on", 0); plugin.getQueryFactory().doUpdate("tardis", sett, wheret); } } // save arched status if (plugin.isDisguisesOnServer()) { if (plugin.getConfig().getBoolean("arch.enabled") && plugin.getTrackerKeeper().getJohnSmith().containsKey(uuid)) { new TARDISArchPersister(plugin).save(uuid); } plugin.getTrackerKeeper().getGeneticallyModified().remove(uuid); } } } private boolean isTravelling(int id) { return (plugin.getTrackerKeeper().getDematerialising().contains(id) || plugin.getTrackerKeeper().getMaterialising().contains(id) || plugin.getTrackerKeeper().getInVortex().contains(id)); } }
0
0.857194
1
0.857194
game-dev
MEDIA
0.741192
game-dev
0.902225
1
0.902225
SethRobinson/proton
4,030
shared/Entity/InputTextRenderComponent.h
// *************************************************************** // InputTextRenderComponent - Creation date: 07/21/2009 // ------------------------------------------------------------- // Robinson Technologies Copyright (C) 2009 - All Rights Reserved // // *************************************************************** // Programmer(s): Seth A. Robinson (seth@rtsoft.com) // *************************************************************** #ifndef InputTextRenderComponent_h__ #define InputTextRenderComponent_h__ #include "Component.h" #include "Entity.h" #include "Renderer/Surface.h" /* Single line input and render component. Example of usage in RTSimpleApp Can listen to its "hasFocus" variant to know when it gets/loses focus. Examples of some parms you can change: //control how many characters the user can enter pButtonEntity->GetComponentByName("InputTextRender")->GetVar("inputLengthMax")->Set(uint32(18)); //show *'s, password mode pButtonEntity->GetComponentByName("InputTextRender")->GetVar("visualStyle")->Set((uint32)InputTextRenderComponent::STYLE_PASSWORD); //Truncate text to fit input box pButtonEntity->GetComponentByName("InputTextRender")->GetVar("truncateTextIfNeeded")->Set(uint32(1)); To close the keyboard and cause the current thing being edited to lose focus, you can do this: Entity *pEnt = GetEntityWithNativeUIFocus(); if (pEnt) { pEnt->GetComponentByName("InputTextRender")->GetFunction("CloseKeyboard")->sig_function(NULL); } Calling function "ActivateKeyboard" can be used to give it focus and bring up the touch keyboard (if applicable) */ class InputTextRenderComponent: public EntityComponent { public: InputTextRenderComponent(); virtual ~InputTextRenderComponent(); virtual void OnAdd(Entity *pEnt); virtual void OnRemove(); enum eVisualStyle { STYLE_NORMAL, STYLE_PASSWORD //shows *'s instead of the real text }; enum eInputType { INPUT_TYPE_ASCII, //allows letters and numbers, no spaces. Good for entering names INPUT_TYPE_NUMBERS, //numbers only (also negative symbol if filtering is LOOSE) INPUT_TYPE_URL, INPUT_TYPE_ASCII_FULL, //allows things like spaces, commas, ect. Good for text chat input INPUT_TYPE_EMAIL, INPUT_TYPE_ALL //allows to type everything }; enum eInputFiltering { FILTERING_STRICT, //no spaces or weird symbols allowed FILTERING_LOOSE //allows everything that could be a say, a URL }; private: void OnRender(VariantList *pVList); void OnTextChanged(Variant *pDataObject); void OnScaleChanged(Variant *pDataObject); void OnFontChanged(Variant *pDataObject); void ActivateKeyboard(VariantList *pVList); void CloseKeyboard(VariantList *pVList); void OnTouchEnd(VariantList *pVList); void OnTouchStart(VariantList *pVList); void OnUpdate(VariantList *pVList); void OnInput( VariantList *pVList ); void OnLosingNativeGUIFocus(VariantList *pVList); void OnEnterForeground(VariantList *pVList); void OnEnterBackground(VariantList *pVList); void OnVisibilityChanged(Variant *pDataObject); void OnVisualStyleChanged(Variant *pDataObject); void OnDisabledChanged(Variant *pDataObject); string TrimText(string *pText); void OnTruncateTextIfNeededChanged(Variant *pDataObject); CL_Vec2f *m_pPos2d; CL_Vec2f *m_pTextOffsetPos2d; CL_Vec2f *m_pSize2d; CL_Vec2f *m_pTextSize2d; uint32 *m_pColor; uint32 *m_pColorMod; float *m_pAlpha; string *m_pText; string *m_pPlaceHolderText; CL_Vec2f *m_pScale2d; uint32 *m_pAlignment; uint32 *m_pFontID; uint32 *m_pVisualStyle; uint32 *m_pCursorColor; uint32 *m_pHasFocus; uint32 *m_pInputLengthMax; uint32 *m_pBorderColor; uint32 *m_pDisabled; uint32 *m_pInputType; uint32 *m_pFiltering; uint32 *m_pVisible; uint32 *m_pGetFocusOnEnter; //if true, hitting enter (while no keyboard is on the screen and nothing else has focus) will automatically give this focus uint32 *m_pTruncateTextIfNeeded ; //if true, will truncate text to match screen size, and also limit input string m_displayText; }; #endif // InputTextRenderComponent_h__
0
0.944274
1
0.944274
game-dev
MEDIA
0.438632
game-dev
0.965957
1
0.965957
Lux-AI-Challenge/Lux-Design-S1
2,877
kits/ts/simple/main.ts
import {Agent, GameState} from "./lux/Agent"; import GAME_CONSTANTS from "./lux/game_constants.json"; import {Cell} from "./lux/Cell"; import {City} from "./lux/City"; import {CityTile} from "./lux/CityTile"; // any state can be stored between ticks by defining variable here // note that game objects are recreated every tick so make sure to update them const agent = new Agent(); // agent.run takes care of running your code per tick agent.run((gameState: GameState): Array<string> => { const actions = new Array<string>(); const player = gameState.players[gameState.id]; const opponent = gameState.players[(gameState.id + 1) % 2]; const gameMap = gameState.map; const resourceTiles: Array<Cell> = []; for (let y = 0; y < gameMap.height; y++) { for (let x = 0; x < gameMap.width; x++) { const cell = gameMap.getCell(x, y); if (cell.hasResource()) { resourceTiles.push(cell); } } } // we iterate over all our units and do something with them for (let i = 0; i < player.units.length; i++) { const unit = player.units[i]; if (unit.isWorker() && unit.canAct()) { if (unit.getCargoSpaceLeft() > 0) { // if the unit is a worker and we have space in cargo, lets find the nearest resource tile and try to mine it let closestResourceTile: Cell = null; let closestDist = 9999999; resourceTiles.forEach((cell) => { if (cell.resource.type === GAME_CONSTANTS.RESOURCE_TYPES.COAL && !player.researchedCoal()) return; if (cell.resource.type === GAME_CONSTANTS.RESOURCE_TYPES.URANIUM && !player.researchedUranium()) return; const dist = cell.pos.distanceTo(unit.pos); if (dist < closestDist) { closestDist = dist; closestResourceTile = cell; } }) if (closestResourceTile != null) { const dir = unit.pos.directionTo(closestResourceTile.pos); // move the unit in the direction towards the closest resource tile's position. actions.push(unit.move(dir)); } } else { // if unit is a worker and there is no cargo space left, and we have cities, lets return to them if (player.cities.size > 0) { const city: City = player.cities.values().next().value let closestDist = 999999; let closestCityTile: CityTile = null; city.citytiles.forEach((citytile) => { const dist = citytile.pos.distanceTo(unit.pos); if (dist < closestDist) { closestCityTile = citytile; closestDist = dist; } }); if (closestCityTile != null) { const dir = unit.pos.directionTo(closestCityTile.pos); actions.push(unit.move(dir)); } } } } } // return the array of actions return actions; });
0
0.862497
1
0.862497
game-dev
MEDIA
0.939283
game-dev
0.932592
1
0.932592
pmmp/PocketMine-MP
1,903
src/item/GoatHorn.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\item; use pocketmine\data\runtime\RuntimeDataDescriber; use pocketmine\math\Vector3; use pocketmine\player\Player; use pocketmine\world\sound\GoatHornSound; class GoatHorn extends Item implements Releasable{ private GoatHornType $goatHornType = GoatHornType::PONDER; protected function describeState(RuntimeDataDescriber $w) : void{ $w->enum($this->goatHornType); } public function getHornType() : GoatHornType{ return $this->goatHornType; } /** * @return $this */ public function setHornType(GoatHornType $type) : self{ $this->goatHornType = $type; return $this; } public function getMaxStackSize() : int{ return 1; } public function getCooldownTicks() : int{ return 140; } public function getCooldownTag() : ?string{ return ItemCooldownTags::GOAT_HORN; } public function canStartUsingItem(Player $player) : bool{ return true; } public function onClickAir(Player $player, Vector3 $directionVector, array &$returnedItems) : ItemUseResult{ $position = $player->getPosition(); $position->getWorld()->addSound($position, new GoatHornSound($this->goatHornType)); return ItemUseResult::SUCCESS; } }
0
0.859475
1
0.859475
game-dev
MEDIA
0.979573
game-dev
0.929731
1
0.929731
oot-pc-port/oot-pc-port
2,009
asm/non_matchings/overlays/actors/ovl_En_Goroiwa/func_80A4BD04.s
glabel func_80A4BD04 /* 00064 80A4BD04 27BDFFD0 */ addiu $sp, $sp, 0xFFD0 ## $sp = FFFFFFD0 /* 00068 80A4BD08 AFB00020 */ sw $s0, 0x0020($sp) /* 0006C 80A4BD0C 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000 /* 00070 80A4BD10 AFA50034 */ sw $a1, 0x0034($sp) /* 00074 80A4BD14 00A02025 */ or $a0, $a1, $zero ## $a0 = 00000000 /* 00078 80A4BD18 AFBF0024 */ sw $ra, 0x0024($sp) /* 0007C 80A4BD1C 26050150 */ addiu $a1, $s0, 0x0150 ## $a1 = 00000150 /* 00080 80A4BD20 0C016EFE */ jal func_8005BBF8 /* 00084 80A4BD24 AFA50028 */ sw $a1, 0x0028($sp) /* 00088 80A4BD28 3C0780A5 */ lui $a3, %hi(D_80A4DEA4) ## $a3 = 80A50000 /* 0008C 80A4BD2C 260E0170 */ addiu $t6, $s0, 0x0170 ## $t6 = 00000170 /* 00090 80A4BD30 8FA50028 */ lw $a1, 0x0028($sp) /* 00094 80A4BD34 AFAE0010 */ sw $t6, 0x0010($sp) /* 00098 80A4BD38 24E7DEA4 */ addiu $a3, $a3, %lo(D_80A4DEA4) ## $a3 = 80A4DEA4 /* 0009C 80A4BD3C 8FA40034 */ lw $a0, 0x0034($sp) /* 000A0 80A4BD40 0C017014 */ jal func_8005C050 /* 000A4 80A4BD44 02003025 */ or $a2, $s0, $zero ## $a2 = 00000000 /* 000A8 80A4BD48 0C292F28 */ jal func_80A4BCA0 /* 000AC 80A4BD4C 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 /* 000B0 80A4BD50 8E18016C */ lw $t8, 0x016C($s0) ## 0000016C /* 000B4 80A4BD54 240F003A */ addiu $t7, $zero, 0x003A ## $t7 = 0000003A /* 000B8 80A4BD58 A70F0036 */ sh $t7, 0x0036($t8) ## 00000036 /* 000BC 80A4BD5C 8FBF0024 */ lw $ra, 0x0024($sp) /* 000C0 80A4BD60 8FB00020 */ lw $s0, 0x0020($sp) /* 000C4 80A4BD64 27BD0030 */ addiu $sp, $sp, 0x0030 ## $sp = 00000000 /* 000C8 80A4BD68 03E00008 */ jr $ra /* 000CC 80A4BD6C 00000000 */ nop
0
0.724385
1
0.724385
game-dev
MEDIA
0.909943
game-dev
0.816034
1
0.816034
cmss13-devs/cmss13
5,280
code/game/machinery/kitchen/processor.dm
/obj/structure/machinery/processor name = "Food Processor" icon = 'icons/obj/structures/machinery/kitchen.dmi' icon_state = "processor" layer = ABOVE_TABLE_LAYER density = TRUE anchored = TRUE wrenchable = TRUE var/broken = 0 var/processing = 0 use_power = USE_POWER_IDLE idle_power_usage = 5 active_power_usage = 50 /datum/food_processor_process var/input var/output var/time = 40 /datum/food_processor_process/process(loc, what) if (src.output && loc) var/obj/item/reagent_container/food/snacks/created_food = new src.output(loc) var/obj/item/reagent_container/food/snacks/original_food = what if(original_food.made_from_player) created_food.made_from_player = original_food.made_from_player created_food.name = (created_food.made_from_player + created_food.name) if (what) qdel(what) /datum/food_processor_process/proc/can_use(mob/user) // By default, anyone can do it. return TRUE /* objs */ /datum/food_processor_process/xenomeat input = /obj/item/reagent_container/food/snacks/meat/xenomeat output = /obj/item/reagent_container/food/snacks/meat/xenomeat/processed /datum/food_processor_process/xenomeat/can_use(mob/user) if(!skillcheck(user, SKILL_DOMESTIC, SKILL_DOMESTIC_MASTER)) to_chat(user, SPAN_DANGER("You aren't trained to remove dangerous substances from food!")) return FALSE return TRUE /datum/food_processor_process/meat input = /obj/item/reagent_container/food/snacks/meat output = /obj/item/reagent_container/food/snacks/rawmeatball /datum/food_processor_process/carpmeat input = /obj/item/reagent_container/food/snacks/carpmeat output = /obj/item/reagent_container/food/snacks/carpmeat/processed /datum/food_processor_process/carpmeat/can_use(mob/user) if(!skillcheck(user, SKILL_DOMESTIC, SKILL_DOMESTIC_MASTER)) to_chat(user, SPAN_DANGER("You aren't trained to remove dangerous substances from food!")) return FALSE return TRUE /datum/food_processor_process/potato input = /obj/item/reagent_container/food/snacks/grown/potato output = /obj/item/reagent_container/food/snacks/rawsticks /datum/food_processor_process/carrot input = /obj/item/reagent_container/food/snacks/grown/carrot output = /obj/item/reagent_container/food/snacks/carrotfries /datum/food_processor_process/soybeans input = /obj/item/reagent_container/food/snacks/grown/soybeans output = /obj/item/reagent_container/food/snacks/soydope /datum/food_processor_process/wheat input = /obj/item/reagent_container/food/snacks/grown/wheat output = /obj/item/reagent_container/food/snacks/flour /datum/food_processor_process/spaghetti input = /obj/item/reagent_container/food/snacks/flour output = /obj/item/reagent_container/food/snacks/spagetti /datum/food_processor_process/chocolatebar input = /obj/item/reagent_container/food/snacks/grown/cocoapod output = /obj/item/reagent_container/food/snacks/chocolatebar /* mobs */ /datum/food_processor_process/mob/process(loc, what) ..() /obj/structure/machinery/processor/initialize_pass_flags(datum/pass_flags_container/PF) ..() if (PF) PF.flags_can_pass_all = PASS_HIGH_OVER_ONLY|PASS_AROUND|PASS_OVER_THROW_ITEM /obj/structure/machinery/processor/proc/select_recipe(X) for (var/Type in typesof(/datum/food_processor_process) - /datum/food_processor_process - /datum/food_processor_process/mob) var/datum/food_processor_process/P = new Type() if (!istype(X, P.input)) continue return P return 0 /obj/structure/machinery/processor/attackby(obj/item/O as obj, mob/user as mob) if(processing) to_chat(user, SPAN_DANGER("The processor is in the process of processing.")) return 1 if(length(contents) > 0) //TODO: several items at once? several different items? to_chat(user, SPAN_DANGER("Something is already in the processing chamber.")) return 1 if(HAS_TRAIT(O, TRAIT_TOOL_WRENCH)) . = ..() return var/obj/what = O if (istype(O, /obj/item/grab)) var/obj/item/grab/G = O what = G.grabbed_thing var/datum/food_processor_process/P = select_recipe(what) if (!P) to_chat(user, SPAN_DANGER("That probably won't blend.")) return 1 if(!P.can_use(user)) return 1 user.visible_message("[user] put [what] into [src].", "You put [what] into [src].") user.drop_held_item() what.forceMove(src) /obj/structure/machinery/processor/attack_hand(mob/user as mob) if (src.stat != 0) //NOPOWER etc return if(src.processing) to_chat(user, SPAN_DANGER("The processor is in the process of processing.")) return 1 if(length(src.contents) == 0) to_chat(user, SPAN_DANGER("The processor is empty.")) return 1 for(var/O in src.contents) var/datum/food_processor_process/P = select_recipe(O) if (!P) log_admin("DEBUG: [O] in processor havent suitable recipe. How do you put it in?") //-rastaf0 continue src.processing = 1 user.visible_message(SPAN_NOTICE("[user] turns on [src]."), "You turn on [src].", "You hear a food processor.") playsound(src.loc, 'sound/machines/blender.ogg', 25, 1) use_power(500) sleep(P.time) P.process(src.loc, O) src.processing = 0 src.visible_message(SPAN_NOTICE("\the [src] finished processing."), "You hear the food processor stopping/") /obj/structure/machinery/processor/yautja name = "food grinder" icon = 'icons/obj/structures/machinery/yautja_machines.dmi'
0
0.846924
1
0.846924
game-dev
MEDIA
0.899312
game-dev
0.608167
1
0.608167
Moulberry/Graphite
2,509
crates/graphite_core_server/src/registry/dimension_type.rs
use graphite_binary::nbt::NBT; #[derive(Copy, Clone, Debug)] pub enum DimensionEffects { // Clouds at 192, normal sky type, normal light map and normal ambient light Overworld, // No clouds, nether sky type, normal light map, constant ambient light TheNether, // No clouds, end sky type, forced light map, normal ambient light TheEnd } impl DimensionEffects { pub fn as_str(self) -> &'static str { match self { DimensionEffects::Overworld => "minecraft:overworld", DimensionEffects::TheNether => "minecraft:the_nether", DimensionEffects::TheEnd => "minecraft:the_end", } } } pub struct DimensionType { pub has_skylight: bool, // When true, client will calculate/predict skylight pub natural: bool, // When false, compasses spin randomly pub min_y: i32, pub height: i32, pub effects: DimensionEffects, // See enum definition pub ambient_light: f32, pub piglin_safe: bool, // If false, piglins shake } impl DimensionType { pub fn to_nbt(&self) -> NBT { let mut nbt = NBT::new(); let mut compound = nbt.as_compound_mut().unwrap(); compound.insert_byte("has_skylight", self.has_skylight as i8); compound.insert_byte("has_ceiling", 0); compound.insert_byte("ultrawarm", 0); compound.insert_byte("natural", self.natural as i8); compound.insert_double("coordinate_scale", 1.0); compound.insert_byte("bed_works", 1); compound.insert_byte("respawn_anchor_works", 1); compound.insert_int("min_y", self.min_y); compound.insert_int("height", self.height); compound.insert_int("logical_height", self.height); compound.insert_string("infiniburn", "#mincraft:infiniburn".into()); compound.insert_string("effects", self.effects.as_str().to_owned()); compound.insert_float("ambient_light", self.ambient_light); compound.insert_byte("piglin_safe", self.piglin_safe as i8); compound.insert_byte("has_raids", 0); compound.insert_int("monster_spawn_light_level", 0); compound.insert_int("monster_spawn_block_light_limit", 0); nbt } } impl Default for DimensionType { fn default() -> Self { Self { has_skylight: true, natural: true, min_y: 0, height: 384, effects: DimensionEffects::Overworld, ambient_light: 0.0, piglin_safe: true } } }
0
0.92571
1
0.92571
game-dev
MEDIA
0.924872
game-dev
0.829554
1
0.829554
MothCocoon/FlowGraph
1,745
Source/Flow/Public/Nodes/Graph/FlowNode_DefineProperties.h
// Copyright https://github.com/MothCocoon/FlowGraph/graphs/contributors #pragma once #include "Interfaces/FlowDataPinGeneratorNodeInterface.h" #include "Nodes/FlowNode.h" #include "Types/FlowDataPinProperties.h" #include "FlowNode_DefineProperties.generated.h" /** * FlowNode to define data pin property literals for use connecting to data pin inputs in a flow graph */ UCLASS(Blueprintable, meta = (DisplayName = "Define Properties")) class FLOW_API UFlowNode_DefineProperties : public UFlowNode, public IFlowDataPinGeneratorNodeInterface { GENERATED_UCLASS_BODY() protected: // Instance-defined properties. // These will auto-generate a matching pin that is bound to its property as its data source. UPROPERTY(EditAnywhere, Category = "Configuration", DisplayName = Properties) TArray<FFlowNamedDataPinProperty> NamedProperties; public: #if WITH_EDITOR // IFlowContextPinSupplierInterface virtual bool SupportsContextPins() const override { return Super::SupportsContextPins() || !NamedProperties.IsEmpty(); } // -- // UObject virtual void PostEditChangeChainProperty(FPropertyChangedChainEvent& PropertyChangedEvent) override; // -- // IFlowDataPinGeneratorNodeInterface virtual void AutoGenerateDataPins(TMap<FName, FName>& PinNameToBoundPropertyMap, TArray<FFlowPin>& InputDataPins, TArray<FFlowPin>& OutputDataPins) const override; // -- #endif bool TryFormatTextWithNamedPropertiesAsParameters(const FText& FormatText, FText& OutFormattedText) const; protected: virtual bool TryFindPropertyByRemappedPinName( const FName& RemappedPinName, const FProperty*& OutFoundProperty, TInstancedStruct<FFlowDataPinProperty>& OutFoundInstancedStruct, EFlowDataPinResolveResult& InOutResult) const override; };
0
0.950582
1
0.950582
game-dev
MEDIA
0.730439
game-dev
0.726483
1
0.726483
ipodtouch0218/NSMB-MarioVsLuigi
1,595
Assets/QuantumUser/Simulation/NSMB/Map/EnterablePipe/EnterablePipeSystem.cs
namespace Quantum { public unsafe class EnterablePipeSystem : SystemSignalsOnly { public override void OnInit(Frame f) { f.Context.Interactions.Register<EnterablePipe, MarioPlayer>(f, OnPipeMarioInteraction); } public static void OnPipeMarioInteraction(Frame f, EntityRef pipeEntity, EntityRef marioEntity) { var pipe = f.Unsafe.GetPointer<EnterablePipe>(pipeEntity); if (!pipe->IsEnterable) { return; } var mario = f.Unsafe.GetPointer<MarioPlayer>(marioEntity); if (pipe->IsMiniOnly && mario->CurrentPowerupState != PowerupState.MiniMushroom) { return; } if (mario->IsCrouchedInShell || mario->IsInKnockback || mario->IsStuckInBlock || mario->CurrentPowerupState == PowerupState.MegaMushroom || mario->MegaMushroomEndFrames > 0) { return; } var marioPhysicsObject = f.Unsafe.GetPointer<PhysicsObject>(marioEntity); Input input = default; if (mario->PlayerRef.IsValid) { input = *f.GetPlayerInput(mario->PlayerRef); } if (pipe->IsCeilingPipe) { if (!marioPhysicsObject->IsTouchingCeiling || !input.Up.IsDown) { return; } } else { if (!marioPhysicsObject->IsTouchingGround || !input.Down.IsDown) { return; } } mario->EnterPipe(f, marioEntity, pipeEntity); } } }
0
0.665699
1
0.665699
game-dev
MEDIA
0.76908
game-dev
0.760188
1
0.760188
sebas77/Svelto.MiniExamples
4,498
Example8-NET-ComputeSharp/Svelto/com.sebaslab.svelto.ecs/Core/EntityDescriptor/GenericEntityDescriptor.cs
using Svelto.ECS.Internal; namespace Svelto.ECS { public abstract class GenericEntityDescriptor<T>: IEntityDescriptor where T : struct, _IInternalEntityComponent { static readonly IComponentBuilder[] _componentBuilders; static GenericEntityDescriptor() { _componentBuilders = new IComponentBuilder[] { new ComponentBuilder<T>() }; } public IComponentBuilder[] componentsToBuild => _componentBuilders; } public abstract class GenericEntityDescriptor<T, U>: IEntityDescriptor where T : struct, _IInternalEntityComponent where U : struct, _IInternalEntityComponent { static readonly IComponentBuilder[] _componentBuilders; static GenericEntityDescriptor() { _componentBuilders = new IComponentBuilder[] { new ComponentBuilder<T>(), new ComponentBuilder<U>() }; } public IComponentBuilder[] componentsToBuild => _componentBuilders; } public abstract class GenericEntityDescriptor<T, U, V>: IEntityDescriptor where T : struct, _IInternalEntityComponent where U : struct, _IInternalEntityComponent where V : struct, _IInternalEntityComponent { static readonly IComponentBuilder[] _componentBuilders; static GenericEntityDescriptor() { _componentBuilders = new IComponentBuilder[] { new ComponentBuilder<T>(), new ComponentBuilder<U>(), new ComponentBuilder<V>() }; } public IComponentBuilder[] componentsToBuild => _componentBuilders; } public abstract class GenericEntityDescriptor<T, U, V, W>: IEntityDescriptor where T : struct, _IInternalEntityComponent where U : struct, _IInternalEntityComponent where V : struct, _IInternalEntityComponent where W : struct, _IInternalEntityComponent { static readonly IComponentBuilder[] _componentBuilders; static GenericEntityDescriptor() { _componentBuilders = new IComponentBuilder[] { new ComponentBuilder<T>(), new ComponentBuilder<U>(), new ComponentBuilder<V>(), new ComponentBuilder<W>() }; } public IComponentBuilder[] componentsToBuild => _componentBuilders; } public abstract class GenericEntityDescriptor<T, U, V, W, X>: IEntityDescriptor where T : struct, _IInternalEntityComponent where U : struct, _IInternalEntityComponent where V : struct, _IInternalEntityComponent where W : struct, _IInternalEntityComponent where X : struct, _IInternalEntityComponent { static readonly IComponentBuilder[] _componentBuilders; static GenericEntityDescriptor() { _componentBuilders = new IComponentBuilder[] { new ComponentBuilder<T>(), new ComponentBuilder<U>(), new ComponentBuilder<V>(), new ComponentBuilder<W>(), new ComponentBuilder<X>() }; } public IComponentBuilder[] componentsToBuild => _componentBuilders; } public abstract class GenericEntityDescriptor<T, U, V, W, X, Y>: IEntityDescriptor where T : struct, _IInternalEntityComponent where U : struct, _IInternalEntityComponent where V : struct, _IInternalEntityComponent where W : struct, _IInternalEntityComponent where X : struct, _IInternalEntityComponent where Y : struct, _IInternalEntityComponent { static readonly IComponentBuilder[] _componentBuilders; static GenericEntityDescriptor() { _componentBuilders = new IComponentBuilder[] { new ComponentBuilder<T>(), new ComponentBuilder<U>(), new ComponentBuilder<V>(), new ComponentBuilder<W>(), new ComponentBuilder<X>(), new ComponentBuilder<Y>() }; } public IComponentBuilder[] componentsToBuild => _componentBuilders; } }
0
0.598397
1
0.598397
game-dev
MEDIA
0.532029
game-dev
0.557941
1
0.557941
discordia-space/CEV-Eris
18,042
code/modules/economy/cash_register.dm
/obj/machinery/cash_register name = "cash register" desc = "Swipe your ID card to make purchases electronically." icon = 'icons/obj/stationobjs.dmi' icon_state = "register_idle" flags = NOBLUDGEON req_access = list() anchored = TRUE var/locked = 1 var/cash_locked = 1 var/cash_open = 0 var/machine_id = "" var/transaction_amount = 0 // cumulatd amount of money to pay in a single purchase var/transaction_purpose = null // text that gets used in ATM transaction logs var/list/transaction_logs = list() // list of strings using html code to visualise data var/list/item_list = list() // entities and according var/list/price_list = list() // prices for each purchase var/manipulating = 0 var/pin_code = null var/cash_stored = 0 var/obj/item/confirm_item var/datum/money_account/linked_account var/account_to_connect = null // Claim machine ID /obj/machinery/cash_register/New() . = ..() machine_id = "[station_name] RETAIL #[num_financial_terminals++]" cash_stored = rand(10, 70)*10 transaction_devices += src // Global reference list to be properly set up by /proc/setup_economy() /obj/machinery/cash_register/examine(mob/user, extra_description = "") if(cash_open) if(cash_stored) extra_description += "It holds [cash_stored] Credit\s of money." else extra_description += "It's completely empty." ..(user, extra_description) /obj/machinery/cash_register/attack_hand(mob/user as mob) // Don't be accessible from the wrong side of the machine if(get_dir(src, user) & reverse_dir[src.dir]) return if(cash_open) if(cash_stored) spawn_money(cash_stored, loc, user) cash_stored = 0 overlays -= "register_cash" else open_cash_box() else user.set_machine(src) interact(user) /obj/machinery/cash_register/AltClick(mob/user) if(Adjacent(user)) open_cash_box() /obj/machinery/cash_register/interact(mob/user as mob) var/dat = "<h2>Cash Register<hr></h2>" if (locked) dat += "<a href='?src=\ref[src];choice=toggle_lock'>Unlock</a><br>" dat += "Linked account: <b>[linked_account ? linked_account.owner_name : "None"]</b><br>" dat += "<b>[cash_locked? "Unlock" : "Lock"] Cash Box</b> | " else dat += "<a href='?src=\ref[src];choice=toggle_lock'>Lock</a><br>" dat += "Linked account: <a href='?src=\ref[src];choice=link_account'>[linked_account ? linked_account.owner_name : "None"]</a><br>" dat += "<a href='?src=\ref[src];choice=toggle_cash_lock'>[cash_locked? "Unlock" : "Lock"] Cash Box</a> | " dat += "<a href='?src=\ref[src];choice=custom_order'>Custom Order</a><hr>" if(item_list.len) dat += get_current_transaction() dat += "<br>" for(var/i=transaction_logs.len, i>=1, i--) dat += "[transaction_logs[i]]<br>" if(transaction_logs.len) dat += locked ? "<br>" : "<a href='?src=\ref[src];choice=reset_log'>Reset Log</a><br>" dat += "<br>" dat += "<i>Device ID:</i> [machine_id]" user << browse(dat, "window=cash_register;size=350x500") onclose(user, "cash_register") /obj/machinery/cash_register/Topic(var/href, var/href_list) if(..()) return usr.set_machine(src) if(href_list["choice"]) switch(href_list["choice"]) if("toggle_lock") if(pin_code == null) pin_code = input("Please set a lock code") as num if(locked == 1) if(pin_code != null) var/try_pin = input("Cash register lock code") as num if(try_pin == pin_code) locked = !locked else to_chat(usr, "\icon[src]<span class='warning'>Insufficient access.</span>") else locked = !locked to_chat(usr, "You lock cash register.") if("toggle_cash_lock") cash_locked = !cash_locked if("link_account") var/attempt_account_num = input("Enter account number", "New account number") as num var/attempt_pin = input("Enter PIN", "Account PIN") as num linked_account = attempt_account_access(attempt_account_num, attempt_pin, 2) if(linked_account) if(linked_account.suspended) linked_account = null src.visible_message("\icon[src]<span class='warning'>Account has been suspended.</span>") else to_chat(usr, "\icon[src]<span class='warning'>Account not found.</span>") if("custom_order") var/t_purpose = sanitize(input("Enter purpose", "New purpose") as text) if (!t_purpose || !Adjacent(usr)) return transaction_purpose = t_purpose item_list += t_purpose var/t_amount = round(input("Enter price", "New price") as num) if (!t_amount || !Adjacent(usr)) return transaction_amount += t_amount price_list += t_amount playsound(src, 'sound/machines/twobeep.ogg', 25) src.visible_message("\icon[src][transaction_purpose]: [t_amount] Credit\s.") if("set_amount") var/item_name = locate(href_list["item"]) var/n_amount = round(input("Enter amount", "New amount") as num) n_amount = CLAMP(n_amount, 0, 20) if (!item_list[item_name] || !Adjacent(usr)) return transaction_amount += (n_amount - item_list[item_name]) * price_list[item_name] if(!n_amount) item_list -= item_name price_list -= item_name else item_list[item_name] = n_amount if("subtract") var/item_name = locate(href_list["item"]) if(item_name) transaction_amount -= price_list[item_name] item_list[item_name]-- if(item_list[item_name] <= 0) item_list -= item_name price_list -= item_name if("add") var/item_name = locate(href_list["item"]) if(item_list[item_name] >= 20) return transaction_amount += price_list[item_name] item_list[item_name]++ if("clear") var/item_name = locate(href_list["item"]) if(item_name) transaction_amount -= price_list[item_name] * item_list[item_name] item_list -= item_name price_list -= item_name else transaction_amount = 0 item_list.Cut() price_list.Cut() if("reset_log") transaction_logs.Cut() to_chat(usr, "\icon[src]<span class='notice'>Transaction log reset.</span>") updateDialog() /obj/machinery/cash_register/attackby(obj/O as obj, user as mob) // Check for a method of paying (ID, PDA, e-wallet, cash, ect.) var/obj/item/card/id/I = O.GetIdCard() if(I) scan_card(I, O) else if (istype(O, /obj/item/spacecash/ewallet)) var/obj/item/spacecash/ewallet/E = O scan_wallet(E) else if (istype(O, /obj/item/spacecash)) var/obj/item/spacecash/SC = O if(cash_open) to_chat(user, "You neatly sort the cash into the box.") cash_stored += SC.worth overlays |= "register_cash" if(ishuman(user)) var/mob/living/carbon/human/H = user H.drop_from_inventory(SC) qdel(SC) else scan_cash(SC) else if(istype(O, /obj/item/card/emag)) return ..() else if(istype(O, /obj/item/tool/wrench)) var/obj/item/tool/wrench/W = O toggle_anchors(W, user) // Not paying: Look up price and add it to transaction_amount else scan_item_price(O) /obj/machinery/cash_register/MouseDrop_T(atom/dropping, mob/user) if(Adjacent(dropping) && Adjacent(user) && !user.stat) attackby(dropping, user) /obj/machinery/cash_register/proc/confirm(obj/item/I) if(confirm_item == I) return 1 else confirm_item = I src.visible_message("\icon[src]<b>Total price:</b> [transaction_amount] Credit\s. Swipe again to confirm.") playsound(src, 'sound/machines/twobeep.ogg', 25) return 0 /obj/machinery/cash_register/proc/scan_card(obj/item/card/id/I, obj/item/ID_container) if (!transaction_amount) return if (cash_open) playsound(src, 'sound/machines/buzz-sigh.ogg', 25) to_chat(usr, "\icon[src]<span class='warning'>The cash box is open.</span>") return if((item_list.len > 1 || item_list[item_list[1]] > 1) && !confirm(I)) return if (!linked_account) usr.visible_message("\icon[src]<span class='warning'>Unable to connect to linked account.</span>") return // Access account for transaction if(check_account()) var/datum/money_account/D = get_account(I.associated_account_number) var/attempt_pin = "" if(D && D.security_level) attempt_pin = input("Enter PIN", "Transaction") as num D = null D = attempt_account_access(I.associated_account_number, attempt_pin, 2) if(!D) src.visible_message("\icon[src]<span class='warning'>Unable to access account. Check security settings and try again.</span>") else if(D.suspended) src.visible_message("\icon[src]<span class='warning'>Your account has been suspended.</span>") else if(transaction_amount > D.money) src.visible_message("\icon[src]<span class='warning'>Not enough funds.</span>") else // Transfer the money D.money -= transaction_amount linked_account.money += transaction_amount // Create log entry in client's account var/datum/transaction/T = new(transaction_amount, linked_account.owner_name, transaction_purpose, machine_id, current_date_string, stationtime2text()) D.transaction_log.Add(T) // Create log entry in owner's account T = new() T.target_name = D.owner_name T.purpose = transaction_purpose T.amount = "[transaction_amount]" T.source_terminal = machine_id T.date = current_date_string T.time = stationtime2text() linked_account.transaction_log.Add(T) // Save log add_transaction_log(I.registered_name ? I.registered_name : "n/A", "ID Card", transaction_amount) // Confirm and reset transaction_complete() /obj/machinery/cash_register/proc/scan_wallet(obj/item/spacecash/ewallet/E) if (!transaction_amount) return if (cash_open) playsound(src, 'sound/machines/buzz-sigh.ogg', 25) to_chat(usr, "\icon[src]<span class='warning'>The cash box is open.</span>") return if((item_list.len > 1 || item_list[item_list[1]] > 1) && !confirm(E)) return // Access account for transaction if(check_account()) if(transaction_amount > E.worth) src.visible_message("\icon[src]<span class='warning'>Not enough funds.</span>") else // Transfer the money E.worth -= transaction_amount linked_account.money += transaction_amount // Create log entry in owner's account var/datum/transaction/T = new(transaction_amount, E.owner_name, transaction_purpose, machine_id, current_date_string, stationtime2text()) linked_account.transaction_log.Add(T) // Save log add_transaction_log(E.owner_name, "E-Wallet", transaction_amount) // Confirm and reset transaction_complete() /obj/machinery/cash_register/proc/scan_cash(obj/item/spacecash/SC) if (!transaction_amount) return if (cash_open) playsound(src, 'sound/machines/buzz-sigh.ogg', 25) to_chat(usr, "\icon[src]<span class='warning'>The cash box is open.</span>") return if((item_list.len > 1 || item_list[item_list[1]] > 1) && !confirm(SC)) return if(transaction_amount > SC.worth) src.visible_message("\icon[src]<span class='warning'>Not enough money.</span>") else // Insert cash into magical slot SC.worth -= transaction_amount SC.update_icon() if(!SC.worth) if(ishuman(SC.loc)) var/mob/living/carbon/human/H = SC.loc H.drop_from_inventory(SC) qdel(SC) cash_stored += transaction_amount // Save log add_transaction_log("n/A", "Cash", transaction_amount) // Confirm and reset transaction_complete() /obj/machinery/cash_register/proc/scan_item_price(obj/O) if(!istype(O)) return if(item_list.len > 10) src.visible_message("\icon[src]<span class='warning'>Only up to ten different items allowed per purchase.</span>") return if (cash_open) playsound(src, 'sound/machines/buzz-sigh.ogg', 25) to_chat(usr, "\icon[src]<span class='warning'>The cash box is open.</span>") return // First check if item has a valid price var/price = O.get_item_cost() if(isnull(price)) src.visible_message("\icon[src]<span class='warning'>Unable to find item in database.</span>") return // Call out item cost src.visible_message("\icon[src]\A [O]: [price ? "[price] Credit\s" : "free of charge"].") // Note the transaction purpose for later use if(transaction_purpose) transaction_purpose += "<br>" transaction_purpose += "[O]: [price] Credit\s" transaction_amount += price for(var/previously_scanned in item_list) if(price == price_list[previously_scanned] && O.name == previously_scanned) . = item_list[previously_scanned]++ if(!.) item_list[O.name] = 1 price_list[O.name] = price . = 1 // Animation and sound playsound(src, 'sound/machines/twobeep.ogg', 25) // Reset confirmation confirm_item = null updateDialog() /obj/machinery/cash_register/proc/get_current_transaction() var/dat = {" <head><style> .tx-title-r {text-align: center; background-color:#ffdddd; font-weight: bold} .tx-name-r {background-color: #eebbbb} .tx-data-r {text-align: right; background-color: #ffcccc;} </head></style> <table width=300> <tr><td colspan="2" class="tx-title-r">New Entry</td></tr> <tr></tr>"} var/item_name for(var/i=1, i<=item_list.len, i++) item_name = item_list[i] dat += "<tr><td class=\"tx-name-r\">[item_list[item_name] ? "<a href='?src=\ref[src];choice=subtract;item=\ref[item_name]'>-</a> <a href='?src=\ref[src];choice=set_amount;item=\ref[item_name]'>Set</a> <a href='?src=\ref[src];choice=add;item=\ref[item_name]'>+</a> [item_list[item_name]] x " : ""][item_name] <a href='?src=\ref[src];choice=clear;item=\ref[item_name]'>Remove</a></td><td class=\"tx-data-r\" width=50>[price_list[item_name] * item_list[item_name]] &thorn</td></tr>" dat += "</table><table width=300>" dat += "<tr><td class=\"tx-name-r\"><a href='?src=\ref[src];choice=clear'>Clear Entry</a></td><td class=\"tx-name-r\" style='text-align: right'><b>Total Amount: [transaction_amount] &thorn</b></td></tr>" dat += "</table></html>" return dat /obj/machinery/cash_register/proc/add_transaction_log(var/c_name, var/p_method, var/t_amount) var/dat = {" <head><style> .tx-title {text-align: center; background-color:#ddddff; font-weight: bold} .tx-name {background-color: #bbbbee} .tx-data {text-align: right; background-color: #ccccff;} </head></style> <table width=300> <tr><td colspan="2" class="tx-title">Transaction #[transaction_logs.len+1]</td></tr> <tr></tr> <tr><td class="tx-name">Customer</td><td class="tx-data">[c_name]</td></tr> <tr><td class="tx-name">Pay Method</td><td class="tx-data">[p_method]</td></tr> <tr><td class="tx-name">Ship Time</td><td class="tx-data">[stationtime2text()]</td></tr> </table> <table width=300> "} var/item_name for(var/i=1, i<=item_list.len, i++) item_name = item_list[i] dat += "<tr><td class=\"tx-name\">[item_list[item_name] ? "[item_list[item_name]] x " : ""][item_name]</td><td class=\"tx-data\" width=50>[price_list[item_name] * item_list[item_name]] &thorn</td></tr>" dat += "<tr></tr><tr><td colspan=\"2\" class=\"tx-name\" style='text-align: right'><b>Total Amount: [transaction_amount] &thorn</b></td></tr>" dat += "</table></html>" transaction_logs += dat /obj/machinery/cash_register/proc/check_account() if (!linked_account) usr.visible_message("\icon[src]<span class='warning'>Unable to connect to linked account.</span>") return 0 if(linked_account.suspended) src.visible_message("\icon[src]<span class='warning'>Connected account has been suspended.</span>") return 0 return 1 /obj/machinery/cash_register/proc/transaction_complete() /// Visible confirmation playsound(src, 'sound/machines/chime.ogg', 25) src.visible_message("\icon[src]<span class='notice'>Transaction complete.</span>") flick("register_approve", src) reset_memory() updateDialog() /obj/machinery/cash_register/proc/reset_memory() transaction_amount = null transaction_purpose = "" item_list.Cut() price_list.Cut() confirm_item = null /obj/machinery/cash_register/verb/open_cash_box() set category = "Object" set name = "Open Cash Box" set desc = "Open/closes the register's cash box." set src in view(1) if(usr.stat) return if(cash_open) cash_open = 0 overlays -= "register_approve" overlays -= "register_open" overlays -= "register_cash" else if(!cash_locked) cash_open = 1 overlays += "register_approve" overlays += "register_open" if(cash_stored) overlays += "register_cash" else to_chat(usr, SPAN_WARNING("The cash box is locked.")) /obj/machinery/cash_register/proc/toggle_anchors(obj/item/tool/wrench/W, mob/user) if(manipulating) return manipulating = 1 if(!anchored) user.visible_message("\The [user] begins securing \the [src] to the floor.", "You begin securing \the [src] to the floor.") else user.visible_message(SPAN_WARNING("\The [user] begins unsecuring \the [src] from the floor."), "You begin unsecuring \the [src] from the floor.") playsound(src.loc, 'sound/items/Ratchet.ogg', 50, 1) if(!do_after(user, 20)) manipulating = 0 return if(!anchored) user.visible_message(SPAN_NOTICE("\The [user] has secured \the [src] to the floor."), SPAN_NOTICE("You have secured \the [src] to the floor.")) else user.visible_message(SPAN_WARNING("\The [user] has unsecured \the [src] from the floor."), SPAN_NOTICE("You have unsecured \the [src] from the floor.")) anchored = !anchored manipulating = 0 return /obj/machinery/cash_register/emag_act(var/remaining_charges, var/mob/user) if(!emagged) src.visible_message(SPAN_DANGER("The [src]'s cash box springs open as [user] swipes the card through the scanner!")) playsound(src, "sparks", 50, 1) req_access = list() emagged = 1 locked = 0 cash_locked = 0 open_cash_box() /* //--Premades--// /obj/machinery/cash_register/command account_to_connect = "Command" ..() /obj/machinery/cash_register/medical account_to_connect = "Medical" ..() /obj/machinery/cash_register/engineering account_to_connect = "Engineering" ..() /obj/machinery/cash_register/science account_to_connect = "Science" ..() /obj/machinery/cash_register/security account_to_connect = "Security" ..() /obj/machinery/cash_register/cargo account_to_connect = "Guild" ..() /obj/machinery/cash_register/civilian account_to_connect = "Civilian" ..() */
0
0.863918
1
0.863918
game-dev
MEDIA
0.953834
game-dev
0.94533
1
0.94533
watir/watir-classic
3,966
lib/watir-classic/element_collection.rb
module Watir # This class is the super class for the iterator classes (buttons, links, spans etc). # It would normally only be accessed by the iterator methods (spans, links etc) of {Container}. class ElementCollection include Enumerable # Super class for all the iterator classes # @param [Element] container container element instance. # @param [Hash] specifiers locators for elements. def initialize(container, specifiers) if specifiers[:index] raise Exception::MissingWayOfFindingObjectException, "#{self.class} does not support attribute :index in #{specifiers.inspect}" end @container = container @specifiers = specifiers @page_container = container.page_container end # @return [Fixnum] count of elements in this collection. def length count = 0 each {|element| count += 1 } count end alias_method :size, :length # Iterate through each of the elements in the collection in turn. # @yieldparam [Element] element element instance. def each @container.locator_for(TaggedElementLocator, @specifiers, element_class).each {|element| yield element} end # Access a specific item in the collection. # # @note {Element} will be always returned even if the index is out of # bounds. Use {Element#exists?} to verify if the element actually exists. # @param [Fixnum] n n-th element to retrieve. # @return [Element] element with specified index from this collection. def [](n) non_existing_element = element_class.new(@container, @specifiers.merge(:index => n)) def non_existing_element.locate; nil end iterator_object(n) || non_existing_element end # @return [Element] first element from this collection. def first iterator_object(0) end # @return [Element] last element from this collection. def last iterator_object(length - 1) end # @return [String] String representation of each element in this collection # separated by line-feed. def to_s map { |e| e.to_s }.join("\n") end def inspect '#<%s:0x%x length=%s container=%s>' % [self.class, hash*2, length.inspect, @container.inspect] end private def iterator_object(i) count = 0 each do |e| return e if (i >= 0 && count == i) || (i < 0 && count == length + i) count += 1 end end def element_class Watir.const_get self.class.name.split("::").last.scan(/(.*)Collection/).flatten.first end end # This class represents table elements collection. class TableElementCollection < ElementCollection def initialize(container, specifiers, ole_collection=nil) super container, specifiers @ole_collection = ole_collection end # @see ElementCollection#each def each if @ole_collection elements = [] @ole_collection.each {|element| elements << element_class.new(@container, :ole_object => element)} super do |element| yield element if elements.include?(element) end else super end end end # This class represents table row elements collection. class TableRowCollection < TableElementCollection; end # This class represents table cell elements collection. class TableCellCollection < TableElementCollection; end # This class represents input elements collection. class InputElementCollection < ElementCollection # @see ElementCollection#each def each @container.locator_for(InputElementLocator, @specifiers, element_class).each {|element| yield element} end end # This class represents general elements collection. class HTMLElementCollection < ElementCollection # @see ElementCollection#each def each @container.locator_for(TaggedElementLocator, @specifiers, Element).each { |element| yield element } end end end
0
0.864597
1
0.864597
game-dev
MEDIA
0.362284
game-dev
0.845208
1
0.845208
ldtteam/minecolonies
5,271
src/main/java/com/minecolonies/core/items/ItemScrollColonyAreaTP.java
package com.minecolonies.core.items; import com.minecolonies.api.colony.IColony; import com.minecolonies.api.util.ItemStackUtils; import com.minecolonies.api.util.SoundUtils; import com.minecolonies.core.Network; import com.minecolonies.core.network.messages.client.VanillaParticleMessage; import com.minecolonies.core.util.TeleportHelper; import net.minecraft.ChatFormatting; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.Style; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.Level; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; import java.util.List; import static com.minecolonies.api.util.constant.translation.ToolTranslationConstants.*; /** * Colony teleport scroll, which teleports the user and any nearby players to the colony, invite a friend-style */ public class ItemScrollColonyAreaTP extends AbstractItemScroll { /** * Sets the name, creative tab, and registers the item. * * @param properties the properties. */ public ItemScrollColonyAreaTP(final Properties properties) { super("scroll_area_tp", properties); } @Override public int getUseDuration(ItemStack itemStack) { return 64; } @Override protected ItemStack onItemUseSuccess(final ItemStack itemStack, final Level world, final ServerPlayer player) { if (world.random.nextInt(10) == 0) { // Fail chance player.displayClientMessage(Component.translatable( "minecolonies.scroll.failed" + (world.random.nextInt(FAIL_RESPONSES_TOTAL) + 1)).setStyle(Style.EMPTY.withColor( ChatFormatting.GOLD)), true); itemStack.shrink(1); if (!ItemStackUtils.isEmpty(itemStack)) { player.drop(itemStack.copy(), true, false); itemStack.setCount(0); } for (final ServerPlayer sPlayer : getAffectedPlayers(player)) { SoundUtils.playSoundForPlayer(sPlayer, SoundEvents.EVOKER_PREPARE_SUMMON, 0.3f, 1.0f); } } else { for (final ServerPlayer sPlayer : getAffectedPlayers(player)) { doTeleport(sPlayer, getColony(itemStack), itemStack); SoundUtils.playSoundForPlayer(sPlayer, SoundEvents.UI_TOAST_CHALLENGE_COMPLETE, 0.1f, 1.0f); } itemStack.shrink(1); } return itemStack; } @Override protected boolean needsColony() { return true; } /** * Does the teleport action * * @param player user of the item * @param colony colony to teleport to */ protected void doTeleport(final ServerPlayer player, final IColony colony, final ItemStack stack) { TeleportHelper.colonyTeleport(player, colony); } @Override public void onUseTick(Level worldIn, LivingEntity entity, ItemStack stack, int count) { if (!worldIn.isClientSide && worldIn.getGameTime() % 5 == 0 && entity instanceof Player) { final ServerPlayer sPlayer = (ServerPlayer) entity; for (final Entity player : getAffectedPlayers(sPlayer)) { Network.getNetwork() .sendToTrackingEntity(new VanillaParticleMessage(player.getX(), player.getY(), player.getZ(), ParticleTypes.INSTANT_EFFECT), player); } Network.getNetwork() .sendToPlayer(new VanillaParticleMessage(sPlayer.getX(), sPlayer.getY(), sPlayer.getZ(), ParticleTypes.INSTANT_EFFECT), sPlayer); } } /** * Get the list of players affected by the area teleport */ private List<ServerPlayer> getAffectedPlayers(final ServerPlayer user) { return user.level.getEntitiesOfClass(ServerPlayer.class, user.getBoundingBox().inflate(10, 2, 10)); } @Override public void appendHoverText( @NotNull final ItemStack stack, @Nullable final Level worldIn, @NotNull final List<Component> tooltip, @NotNull final TooltipFlag flagIn) { final MutableComponent guiHint = Component.translatable(TOOL_COLONY_TELEPORT_AREA_SCROLL_DESCRIPTION); guiHint.setStyle(Style.EMPTY.withColor(ChatFormatting.DARK_GREEN)); tooltip.add(guiHint); MutableComponent colonyDesc = Component.translatable(TOOL_COLONY_TELEPORT_SCROLL_NO_COLONY); final IColony colony = getColonyView(stack); if (colony != null) { colonyDesc = Component.literal(colony.getName()); } final MutableComponent guiHint2 = Component.translatable(TOOL_COLONY_TELEPORT_SCROLL_COLONY_NAME, colonyDesc); guiHint2.setStyle(Style.EMPTY.withColor(ChatFormatting.GOLD)); tooltip.add(guiHint2); } }
0
0.766925
1
0.766925
game-dev
MEDIA
0.967843
game-dev
0.87412
1
0.87412
warxander/los-santos-v
3,980
resources/[los-santos-v]/lsv-main/client/spawn.lua
-- TODO Make me module? DeathTimer = nil TimeToRespawn = Settings.spawn.deathTime local _isSpawnInProcess = false function spawnPlayer(spawnPoint) if _isSpawnInProcess then return end local isFirstSpawn = spawnPoint ~= nil _isSpawnInProcess = true if not GetIsLoadingScreenActive() then DoScreenFadeOut(500) while not IsScreenFadedOut() do Citizen.Wait(0) end end if spawnPoint then spawnPoint.z = spawnPoint.z - 1.0 else local playerPos = Player.Position() local startingPosition = nil if Player.CrewLeader and Player.CrewLeader ~= Player.ServerId() then local leaderCoords = GetEntityCoords(GetPlayerPed(GetPlayerFromServerId(Player.CrewLeader))) if World.GetDistance(playerPos, leaderCoords, true) <= Settings.crew.spawnDistance then startingPosition = leaderCoords end end if not startingPosition then startingPosition = playerPos end local radius = Settings.spawn.radius.min local z = 1500. local tryCount = 0 local startSpawnTimer = Timer.New() while true do Citizen.Wait(0) local diff = { r = radius * math.sqrt(GetRandomFloatInRange(0.0, 1.0)), theta = GetRandomFloatInRange(0.0, 1.0) * 2 * math.pi } local xDiff = diff.r * math.cos(diff.theta) if xDiff >= 0 then xDiff = math.max(radius, xDiff) else xDiff = math.min(-radius, xDiff) end local yDiff = diff.r * math.sin(diff.theta) if yDiff >= 0 then yDiff = math.max(radius, yDiff) else yDiff = math.min(-radius, yDiff) end local x = startingPosition.x + xDiff local y = startingPosition.y + yDiff local _, groundZ = GetGroundZFor_3dCoord(x, y, z) local validCoords, coords = GetSafeCoordForPed(x, y, groundZ + 1., false, 16) if validCoords then for _, i in ipairs(GetActivePlayers()) do if i ~= PlayerId() then local ped = GetPlayerPed(i) if DoesEntityExist(ped) then local pedCoords = GetEntityCoords(ped) if Vdist(coords.x, coords.y, coords.z, pedCoords.x, pedCoords.y, pedCoords.z) < Settings.spawn.radius.minDistanceToPlayer then validCoords = false break end end end end end if validCoords then spawnPoint = { } spawnPoint.x, spawnPoint.y, spawnPoint.z = coords.x, coords.y, coords.z else if tryCount ~= Settings.spawn.tryCount then tryCount = tryCount + 1 else radius = radius + Settings.spawn.radius.increment tryCount = 0 end end if spawnPoint then break end if startSpawnTimer:elapsed() >= Settings.spawn.timeout then spawnPoint = table.random(Settings.spawn.points) Gui.DisplayPersonalNotification('Unable to find suitable place for spawning.') end end end Player.SetPassiveMode(true, not isFirstSpawn) local ped = PlayerPedId() RequestCollisionAtCoord(spawnPoint.x, spawnPoint.y, spawnPoint.z) SetEntityCoordsNoOffset(ped, spawnPoint.x, spawnPoint.y, spawnPoint.z, false, false, false, true) NetworkResurrectLocalPlayer(spawnPoint.x, spawnPoint.y, spawnPoint.z, GetRandomFloatInRange(0.0, 360.0), true, true, false) ClearPedTasksImmediately(ped) StopEntityFire(ped) ClearPedEnvDirt(ped) ClearPedBloodDamage(ped) ClearPedWetness(ped) if GetIsLoadingScreenActive() then ShutdownLoadingScreen() end if IsScreenFadedOut() then DoScreenFadeIn(500) while not IsScreenFadedIn() do Citizen.Wait(0) end end TriggerEvent('playerSpawned') _isSpawnInProcess = false end AddEventHandler('lsv:init', function() while true do Citizen.Wait(0) if DoesEntityExist(PlayerPedId()) then if NetworkIsPlayerActive(PlayerId()) then if not _isSpawnInProcess then if DeathTimer and GetTimeDifference(GetGameTimer(), DeathTimer) > TimeToRespawn then spawnPlayer() end end end if IsPlayerDead(PlayerId()) then if not DeathTimer then DeathTimer = GetGameTimer() TimeToRespawn = Settings.spawn.deathTime end else DeathTimer = nil end end end end)
0
0.856526
1
0.856526
game-dev
MEDIA
0.991094
game-dev
0.8148
1
0.8148
Pico-Developer/PICO-Unity-Integration-SDK
3,551
Runtime/Debugger/Scripts/UI/Inspector/PXR_InspectorManager.cs
/******************************************************************************* Copyright © 2015-2022 PICO Technology Co., Ltd.All rights reserved. NOTICE:All information contained herein is, and remains the property of PICO Technology Co., Ltd. The intellectual and technical concepts contained herein are proprietary to PICO Technology Co., Ltd. and may be covered by patents, patents in process, and are protected by trade secret or copyright law. Dissemination of this information or reproduction of this material is strictly forbidden unless prior written permission is obtained from PICO Technology Co., Ltd. *******************************************************************************/ using UnityEngine; using UnityEngine.UI; #if UNITY_EDITOR || DEVELOPMENT_BUILD namespace Unity.XR.PXR.Debugger { public class PXR_InspectorManager : MonoBehaviour, IPXR_PanelManager { public static PXR_InspectorManager Instance; private void Awake(){ if(Instance == null){ Instance = this; } } public GameObject inspectItem; public Transform content; public Text positionText; public Text rotationText; public Text scaleText; public GameObject transformInfoNode; private Transform target; void Update(){ ShowTransformInfo(); } private void ClearAllChildren(){ int childCount = content.childCount; for (int i = childCount - 1; i >= 0; i--) { DestroyImmediate(content.GetChild(i).gameObject); } } public void CreateInspector() { GenerateInspectorTree(); } public void Init(){ CreateInspector(); } public void Reset(){ for (int i = 0; i < content.childCount; i++) { LayoutRebuilder.ForceRebuildLayoutImmediate(content.GetChild(i).GetComponent<RectTransform>()); } } public void SetTransformInfo(GameObject target){ this.target = target.transform; transformInfoNode.SetActive(true); ShowTransformInfo(); } public void Refresh(){ ClearAllChildren(); GenerateInspectorTree(); } private void GenerateInspectorTree(){ GameObject[] rootObjects = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects(); // 遍历所有根GameObject foreach (GameObject obj in rootObjects) { if(!obj.TryGetComponent<PXR_UIController>(out _) && !obj.TryGetComponent<PXR_UIManager>(out _) && obj.activeSelf){ var go = Instantiate(inspectItem, content); if(go.TryGetComponent(out PXR_InspectorItem item)){ item.Init(obj.transform); } } } Reset(); } private void ShowTransformInfo(){ if(target != null){ positionText.text = $"x:{target.position.x} y:{target.position.y} z:{target.position.z}"; rotationText.text = $"x:{target.eulerAngles.x} y:{target.eulerAngles.y} z:{target.eulerAngles.z} "; scaleText.text = $"x:{target.localScale.x} y:{target.localScale.y} z:{target.localScale.z}"; }else{ transformInfoNode.SetActive(false); Refresh(); } } } } #endif
0
0.859001
1
0.859001
game-dev
MEDIA
0.968039
game-dev
0.844219
1
0.844219
Baystation12/Baystation12
3,635
code/modules/paperwork/paperbin.dm
/obj/item/paper_bin name = "paper bin" icon = 'icons/obj/bureaucracy.dmi' icon_state = "paper_bin1" item_state = "sheet-metal" randpixel = 0 throwforce = 1 w_class = ITEM_SIZE_NORMAL throw_speed = 3 throw_range = 7 layer = BELOW_OBJ_LAYER var/amount = 30 //How much paper is in the bin. var/list/papers = list() //List of papers put in the bin for reference. /obj/item/paper_bin/MouseDrop(mob/user as mob) if((user == usr && (!( usr.restrained() ) && (!( usr.stat ) && (usr.contents.Find(src) || in_range(src, usr)))))) if(!istype(usr, /mob/living/carbon/slime) && !istype(usr, /mob/living/simple_animal)) if( !usr.get_active_hand() ) //if active hand is empty var/mob/living/carbon/human/H = user var/obj/item/organ/external/temp = H.organs_by_name[BP_R_HAND] if (H.hand) temp = H.organs_by_name[BP_L_HAND] if(temp && !temp.is_usable()) to_chat(user, SPAN_NOTICE("You try to move your [temp.name], but cannot!")) return to_chat(user, SPAN_NOTICE("You pick up the [src].")) user.put_in_hands(src) return /obj/item/paper_bin/attack_hand(mob/user as mob) if(ishuman(user)) var/mob/living/carbon/human/H = user var/obj/item/organ/external/temp = H.organs_by_name[BP_R_HAND] if (H.hand) temp = H.organs_by_name[BP_L_HAND] if(temp && !temp.is_usable()) to_chat(user, SPAN_NOTICE("You try to move your [temp.name], but cannot!")) return var/response = "" if(!length(papers) > 0) response = alert(user, "Do you take regular paper, or Carbon copy paper?", "Paper type request", "Regular", "Carbon-Copy", "Cancel") if (response != "Regular" && response != "Carbon-Copy") add_fingerprint(user) return if(amount >= 1) amount-- if(amount==0) update_icon() var/obj/item/paper/P if(length(papers) > 0) //If there's any custom paper on the stack, use that instead of creating a new paper. P = papers[length(papers)] papers.Remove(P) else if(response == "Regular") P = new /obj/item/paper else if (response == "Carbon-Copy") P = new /obj/item/paper/carbon user.put_in_hands(P) to_chat(user, SPAN_NOTICE("You take [P] out of the [src].")) else to_chat(user, SPAN_NOTICE("[src] is empty!")) add_fingerprint(user) return /obj/item/paper_bin/use_tool(obj/item/i, mob/living/user, list/click_params) if(istype(i, /obj/item/paper)) if(!user.unEquip(i, src)) FEEDBACK_UNEQUIP_FAILURE(user, i) return TRUE to_chat(user, SPAN_NOTICE("You put \the [i] in \the [src].")) papers.Add(i) update_icon() amount++ return TRUE if (istype(i, /obj/item/paper_bundle)) to_chat(user, SPAN_NOTICE("You loosen \the [i] and add its papers into \the [src].")) var/was_there_a_photo = 0 for(var/obj/item/bundleitem in i) //loop through items in bundle if(istype(bundleitem, /obj/item/paper)) //if item is paper, add into the bin papers.Add(bundleitem) update_icon() amount++ else if(istype(bundleitem, /obj/item/photo)) //if item is photo, drop it on the ground was_there_a_photo = 1 bundleitem.dropInto(user.loc) bundleitem.reset_plane_and_layer() qdel(i) if(was_there_a_photo) to_chat(user, SPAN_NOTICE("The photo cannot go into \the [src].")) return TRUE return ..() /obj/item/paper_bin/examine(mob/user, distance) . = ..() if(distance <= 1) if(amount) to_chat(user, SPAN_NOTICE("There " + (amount > 1 ? "are [amount] papers" : "is one paper") + " in the bin.")) else to_chat(user, SPAN_NOTICE("There are no papers in the bin.")) /obj/item/paper_bin/on_update_icon() if(amount < 1) icon_state = "paper_bin0" else icon_state = "paper_bin1"
0
0.672412
1
0.672412
game-dev
MEDIA
0.400761
game-dev
0.90556
1
0.90556
Fluorohydride/ygopro-scripts
2,553
c88413677.lua
--ドヨン@イグニスター function c88413677.initial_effect(c) --to hand local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(88413677,0)) e1:SetCategory(CATEGORY_TOHAND) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetCountLimit(1,88413677) e1:SetTarget(c88413677.thtg1) e1:SetOperation(c88413677.thop1) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e2) --to hand local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(88413677,1)) e3:SetCategory(CATEGORY_TOHAND) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_CARD_TARGET) e3:SetCode(EVENT_BE_MATERIAL) e3:SetCountLimit(1,88413678) e3:SetCondition(c88413677.thcon2) e3:SetTarget(c88413677.thtg2) e3:SetOperation(c88413677.thop2) c:RegisterEffect(e3) end function c88413677.thfilter1(c) return c:IsSetCard(0x135) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand() end function c88413677.thtg1(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c88413677.thfilter1(chkc) end if chk==0 then return Duel.IsExistingTarget(c88413677.thfilter1,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectTarget(tp,c88413677.thfilter1,tp,LOCATION_GRAVE,0,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0) end function c88413677.thop1(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SendtoHand(tc,nil,REASON_EFFECT) end end function c88413677.thcon2(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return r==REASON_LINK and c:GetReasonCard():IsRace(RACE_CYBERSE) and c:IsLocation(LOCATION_GRAVE) end function c88413677.thfilter2(c) return c:IsSetCard(0x136) and c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsAbleToHand() end function c88413677.thtg2(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c88413677.thfilter2(chkc) end if chk==0 then return Duel.IsExistingTarget(c88413677.thfilter2,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectTarget(tp,c88413677.thfilter2,tp,LOCATION_GRAVE,0,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0) end function c88413677.thop2(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SendtoHand(tc,nil,REASON_EFFECT) end end
0
0.900258
1
0.900258
game-dev
MEDIA
0.96705
game-dev
0.956445
1
0.956445
jakevn/MassiveNet
5,577
Unity3d.Examples/Assets/MassiveNet/Examples/NetAdvanced/Client/Scripts/TextFieldInput.cs
// MIT License (MIT) - Copyright (c) 2014 jakevn - Please see included LICENSE file using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Massive.Examples.NetAdvanced { public class TextFieldInput : MonoBehaviour { private static readonly List<TextFieldInput> Fields = new List<TextFieldInput>(); private static readonly Dictionary<string, Action> Listeners = new Dictionary<string, Action>(); private static TextFieldInput currentlySelected; public static bool ListenForSubmit(string fieldName, Action listener) { foreach (var field in Fields) { if (field.name != fieldName) continue; if (Listeners.ContainsKey(fieldName)) return false; Listeners.Add(fieldName, listener); return true; } return false; } public static void StopListenForSubmit(Action listener) { string key = (from kv in Listeners where kv.Value == listener select kv.Key).FirstOrDefault(); if (key != null) Listeners.Remove(key); } public static bool TryGetText(string fieldName, out string text) { foreach (var field in Fields) { if (field.gameObject.name != fieldName) continue; text = field.Text(); return true; } text = null; return false; } public bool PasswordField; public int MaxLength = 64; public int LineLength = 20; public TextFieldInput TabTarget; private TextMesh textMesh; private string initialValue; private string backingText = ""; private void OnEnable() { if (textMesh == null) { textMesh = GetComponentInChildren<TextMesh>(); if (textMesh == null) { Debug.LogError("No TextMesh found in children."); return; } initialValue = textMesh.text; } if (!Fields.Contains(this)) Fields.Add(this); Button.ListenForClick(gameObject.name, Clicked); } private void OnDisable() { if (Fields.Contains(this)) Fields.Remove(this); if (initialValue != null) { textMesh.text = initialValue; backingText = ""; } Button.StopListenForClick(gameObject.name, Clicked); Deselected(); } private void Clicked() { if (currentlySelected == this) return; Selected(); } private void MissedClick() { Deselected(); } public void Selected() { currentlySelected = this; if (textMesh.text == initialValue) textMesh.text = ""; textMesh.text += '|'; InputHandler.Instance.ListenToKeyDown(Tab, KeyCode.Tab); InputHandler.Instance.ListenToKeyDown(Return, KeyCode.Return); Button.ListenForMissedClick(gameObject.name, MissedClick); InputHandler.Instance.ListenToChars(OnInput); InputHandler.Instance.ListenToKey(OnBackspace, KeyCode.Backspace); } private void Deselected() { if (currentlySelected == this) currentlySelected = null; if (textMesh.text[textMesh.text.Length - 1] == '|') textMesh.text = textMesh.text.Remove(textMesh.text.Length - 1); if (backingText.Length == 0) textMesh.text = initialValue; InputHandler.Instance.StopListenToKeyDown(Tab, KeyCode.Tab); InputHandler.Instance.StopListenToKeyDown(Return, KeyCode.Return); Button.StopListenForMissedClick(gameObject.name, MissedClick); InputHandler.Instance.StopListenToChars(OnInput); InputHandler.Instance.StopListenToKey(OnBackspace, KeyCode.Backspace); } private void OnDestroy() { OnDisable(); } private float lastBackspace; private const float BackspaceDelay = 0.1f; void OnBackspace() { if (Time.time - lastBackspace < BackspaceDelay) return; if (backingText.Length == 0) return; lastBackspace = Time.time; backingText = backingText.Remove(backingText.Length - 1); if (textMesh.text[textMesh.text.Length - 2] == '\n') textMesh.text = textMesh.text.Remove(textMesh.text.Length - 2, 1); textMesh.text = textMesh.text.Remove(textMesh.text.Length - 2, 1); } void OnInput(char c) { if (backingText.Length >= MaxLength || c == '\n' || c == '\t') return; backingText += c; c = PasswordField ? '*' : c; if (backingText.Length != 0 && backingText.Length % LineLength == 0) { textMesh.text = textMesh.text.Insert(textMesh.text.Length - 1, "\n" + c); } else { textMesh.text = textMesh.text.Insert(textMesh.text.Length - 1, c.ToString()); } } private void Tab() { if (TabTarget == null) return; Deselected(); TabTarget.Selected(); } private void Return() { if (currentlySelected != this) return; Submit(); } public void Submit() { if (!Listeners.ContainsKey(gameObject.name)) return; Listeners[gameObject.name](); } public string Text() { return backingText; } } }
0
0.845028
1
0.845028
game-dev
MEDIA
0.762996
game-dev
0.968351
1
0.968351
fcscript/CSharpHotUpdate
1,042
UEPlugin/Plugins/FCScript/Source/FCScript/Private/FCObjectReferencer.h
#pragma once #include "Containers/Set.h" #include "UObject/GCObject.h" class FCObjectReferencer : public FGCObject { public: void Add(UObject* Object) { if (Object == nullptr) return; ReferencedObjects.Add(Object); } // ReSharper disable once CppParameterMayBeConstPtrOrRef void Remove(UObject* Object) { if (Object == nullptr) return; ReferencedObjects.Remove(Object); } void Clear() { return ReferencedObjects.Empty(); } void SetName(const FString& InName) { Name = InName; } virtual void AddReferencedObjects(FReferenceCollector& Collector) override { Collector.AddReferencedObjects(ReferencedObjects); } virtual FString GetReferencerName() const override { return Name; } const TSet<UObject*> &GetReferencedObjects() const { return ReferencedObjects; } private: TSet<UObject*> ReferencedObjects; FString Name = TEXT("FObjectReferencer"); };
0
0.811274
1
0.811274
game-dev
MEDIA
0.425624
game-dev
0.732885
1
0.732885
EddyRivasLab/hmmer
3,392
profmark/x-fps-ncbiblast+
#! /usr/bin/perl -w # Do a piece of a profmark benchmark, for NCBI BLASTP+ searches by FPS # (family-pairwise-search; best E-value of all individual queries). # # This script is normally called by pmark_master.pl; its command line # syntax is tied to pmark_master.pl. # # Usage: x-ncbiblast+-fps <top_builddir> <top_srcdir> <resultdir> <tblfile> <msafile> <fafile> <outfile> # Example: ./x-ncbiblast+-fps /usr/local/ncbi-blast-2.2.21+ ~/src/hmmer/trunk testdir test.tbl pmark.msa test.fa test.out # # SRE, Tue Mar 8 09:12:11 2011 # SVN $Id$ BEGIN { $top_builddir = shift; $top_srcdir = shift; $wrkdir = shift; $tblfile = shift; $msafile = shift; $fafile = shift; $outfile = shift; } use lib "${top_srcdir}/easel/demotic"; use demotic_blast; $blastp = "${top_builddir}/bin/blastp"; $blastopts = "-num_threads 1 -num_descriptions 9999 -num_alignments 0"; if (! -d $top_builddir) { die "didn't find BLAST build directory $top_builddir"; } if (! -d $top_srcdir) { die "didn't find H3 source directory $top_srcdir"; } if (! -x $blastp) { die "didn't find executable $blastp"; } if (! -e $wrkdir) { die "$wrkdir doesn't exist"; } open(OUTFILE,">$outfile") || die "failed to open $outfile"; open(TABLE, "$tblfile") || die "failed to open $tblfile"; MSA: while (<TABLE>) { ($msaname) = split; %seen = (); %best_pval = (); %best_bitscore = (); `esl-afetch -o $wrkdir/$msaname.sto $msafile $msaname`; if ($?) { print "FAILED: esl-afetch -o $wrkdir/$msaname.sto $msafile $msaname\n"; next MSA; } # Extract a list of individual sequence names from the multiple alignment. $output = `esl-seqstat -a $wrkdir/$msaname.sto | grep "^=" | awk '{print \$2}'`; if ($?) { print "FAILED: esl-seqstat -a $wrkdir/$msaname.sto\n"; next MSA; } @qnames = split(/^/,$output); chop (@qnames); # Loop over each query; blast; accumulate best pval for each target foreach $qname (@qnames) { $output = `esl-sfetch -o $wrkdir/$msaname.query.fa $wrkdir/$msaname.sto $qname`; if ($?) { print "FAILED: esl-sfetch -o $wrkdir/$msaname.query.fa $wrkdir/$msaname.sto $qname\n"; next MSA; } if (! open(BLASTP, "$blastp -db $fafile -query $wrkdir/$msaname.query.fa $blastopts |")) { print "FAILED: $blastp -db $fafile -query $wrkdir/$msaname.query.fa $blastopts |\n"; next MSA; } if (! demotic_blast::parse(\*BLASTP)) { print "FAILED: demotic parser for blastp output\n"; next MSA; } for ($i = 0; $i < $demotic_blast::nhits; $i++) { $target = $demotic_blast::hit_target[$i]; $pval = $demotic_blast::hit_Eval[$i]; $bitscore = $demotic_blast::hit_bitscore[$i]; if (! $seen{$target} || $pval < $best_pval{$target}) { $seen{$target} = 1; $best_pval{$target} = $pval; $best_bitscore{$target} = $bitscore; } } close BLASTP; } # Append to the outfile. foreach $target (keys(%seen)) { printf OUTFILE "%g %.1f %s %s\n", $best_pval{$target}, $best_bitscore{$target}, $target, $msaname; } unlink "$wrkdir/$msaname.sto"; unlink "$wrkdir/$msaname.query.fa"; } close TABLE; close OUTFILE;
0
0.933664
1
0.933664
game-dev
MEDIA
0.240029
game-dev
0.881518
1
0.881518