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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Overload-Technologies/Overload | 5,856 | Dependencies/bullet3/bullet/BulletDynamics/Dynamics/btDynamicsWorld.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_DYNAMICS_WORLD_H
#define BT_DYNAMICS_WORLD_H
#include "BulletCollision/CollisionDispatch/btCollisionWorld.h"
#include "BulletDynamics/ConstraintSolver/btContactSolverInfo.h"
class btTypedConstraint;
class btActionInterface;
class btConstraintSolver;
class btDynamicsWorld;
/// Type for the callback for each tick
typedef void (*btInternalTickCallback)(btDynamicsWorld* world, btScalar timeStep);
enum btDynamicsWorldType
{
BT_SIMPLE_DYNAMICS_WORLD = 1,
BT_DISCRETE_DYNAMICS_WORLD = 2,
BT_CONTINUOUS_DYNAMICS_WORLD = 3,
BT_SOFT_RIGID_DYNAMICS_WORLD = 4,
BT_GPU_DYNAMICS_WORLD = 5,
BT_SOFT_MULTIBODY_DYNAMICS_WORLD = 6,
BT_DEFORMABLE_MULTIBODY_DYNAMICS_WORLD = 7
};
///The btDynamicsWorld is the interface class for several dynamics implementation, basic, discrete, parallel, and continuous etc.
class btDynamicsWorld : public btCollisionWorld
{
protected:
btInternalTickCallback m_internalTickCallback;
btInternalTickCallback m_internalPreTickCallback;
void* m_worldUserInfo;
btContactSolverInfo m_solverInfo;
public:
btDynamicsWorld(btDispatcher* dispatcher, btBroadphaseInterface* broadphase, btCollisionConfiguration* collisionConfiguration)
: btCollisionWorld(dispatcher, broadphase, collisionConfiguration), m_internalTickCallback(0), m_internalPreTickCallback(0), m_worldUserInfo(0)
{
}
virtual ~btDynamicsWorld()
{
}
///stepSimulation proceeds the simulation over 'timeStep', units in preferably in seconds.
///By default, Bullet will subdivide the timestep in constant substeps of each 'fixedTimeStep'.
///in order to keep the simulation real-time, the maximum number of substeps can be clamped to 'maxSubSteps'.
///You can disable subdividing the timestep/substepping by passing maxSubSteps=0 as second argument to stepSimulation, but in that case you have to keep the timeStep constant.
virtual int stepSimulation(btScalar timeStep, int maxSubSteps = 1, btScalar fixedTimeStep = btScalar(1.) / btScalar(60.)) = 0;
virtual void debugDrawWorld() = 0;
virtual void addConstraint(btTypedConstraint* constraint, bool disableCollisionsBetweenLinkedBodies = false)
{
(void)constraint;
(void)disableCollisionsBetweenLinkedBodies;
}
virtual void removeConstraint(btTypedConstraint* constraint) { (void)constraint; }
virtual void addAction(btActionInterface* action) = 0;
virtual void removeAction(btActionInterface* action) = 0;
//once a rigidbody is added to the dynamics world, it will get this gravity assigned
//existing rigidbodies in the world get gravity assigned too, during this method
virtual void setGravity(const btVector3& gravity) = 0;
virtual btVector3 getGravity() const = 0;
virtual void synchronizeMotionStates() = 0;
virtual void addRigidBody(btRigidBody* body) = 0;
virtual void addRigidBody(btRigidBody* body, int group, int mask) = 0;
virtual void removeRigidBody(btRigidBody* body) = 0;
virtual void setConstraintSolver(btConstraintSolver* solver) = 0;
virtual btConstraintSolver* getConstraintSolver() = 0;
virtual int getNumConstraints() const { return 0; }
virtual btTypedConstraint* getConstraint(int index)
{
(void)index;
return 0;
}
virtual const btTypedConstraint* getConstraint(int index) const
{
(void)index;
return 0;
}
virtual btDynamicsWorldType getWorldType() const = 0;
virtual void clearForces() = 0;
/// Set the callback for when an internal tick (simulation substep) happens, optional user info
void setInternalTickCallback(btInternalTickCallback cb, void* worldUserInfo = 0, bool isPreTick = false)
{
if (isPreTick)
{
m_internalPreTickCallback = cb;
}
else
{
m_internalTickCallback = cb;
}
m_worldUserInfo = worldUserInfo;
}
void setWorldUserInfo(void* worldUserInfo)
{
m_worldUserInfo = worldUserInfo;
}
void* getWorldUserInfo() const
{
return m_worldUserInfo;
}
btContactSolverInfo& getSolverInfo()
{
return m_solverInfo;
}
const btContactSolverInfo& getSolverInfo() const
{
return m_solverInfo;
}
///obsolete, use addAction instead.
virtual void addVehicle(btActionInterface* vehicle) { (void)vehicle; }
///obsolete, use removeAction instead
virtual void removeVehicle(btActionInterface* vehicle) { (void)vehicle; }
///obsolete, use addAction instead.
virtual void addCharacter(btActionInterface* character) { (void)character; }
///obsolete, use removeAction instead
virtual void removeCharacter(btActionInterface* character) { (void)character; }
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btDynamicsWorldDoubleData
{
btContactSolverInfoDoubleData m_solverInfo;
btVector3DoubleData m_gravity;
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btDynamicsWorldFloatData
{
btContactSolverInfoFloatData m_solverInfo;
btVector3FloatData m_gravity;
};
#endif //BT_DYNAMICS_WORLD_H
| 412 | 0.809749 | 1 | 0.809749 | game-dev | MEDIA | 0.977683 | game-dev | 0.789169 | 1 | 0.789169 |
lzxsz/MIR2 | 6,618 | GameOfMir/Component/DelphiX/Demos/SpriteEngineSample/2 Sprite Collision/scol.pas | unit scol;
{
Additional DelphiX Samples: Sprite Collision
By: Maarten van Gompel (Proycon)
THEMA Corporation
Email: themacorp@usa.net
Homepage: http://thema.cjb.net
Date: February 15, 1999
Description:
This DelphiX Sample will show you how to work with
sprites and collisions. It also demonstrates the use of the DXWaveList Component
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DXClass, DXInput, DXDraws, DXSprite, DXSounds, ExtCtrls;
type
TForm1 = class(TForm)
DXDraw1: TDXDraw;
DXImageList1: TDXImageList;
DXInput1: TDXInput;
DXTimer1: TDXTimer;
DXSpriteEngine1: TDXSpriteEngine;
DXWaveList1: TDXWaveList;
DXSound1: TDXSound;
Timer1: TTimer;
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure DXDraw1Initialize(Sender: TObject);
procedure DXDraw1Finalize(Sender: TObject);
procedure DXTimer1Timer(Sender: TObject; LagCount: Integer);
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure DXSpriteEngine1Items0Collision(Sender: TObject;
var Done: Boolean);
procedure DXSpriteEngine1Items0Move(Sender: TObject;
var MoveCount: Integer);
procedure DXSpriteEngine1Items0GetImage(Sender: TObject;
var Image: TPictureCollectionItem);
procedure DXSpriteEngine1Items1GetImage(Sender: TObject;
var Image: TPictureCollectionItem);
procedure DXSpriteEngine1Items1Move(Sender: TObject;
var MoveCount: Integer);
private
{ Private declarations }
//This variable keeps track of the time
Seconds: Integer;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
//When ESCAPE (ASCII 27) is pressed we'll quit
If Ord(Key) = 27 Then Form1.Close;
end;
procedure TForm1.DXDraw1Initialize(Sender: TObject);
begin
//Enable Timer on startup
DXTimer1.Enabled := True;
end;
procedure TForm1.DXDraw1Finalize(Sender: TObject);
begin
//Disable Timer on exit
DXTimer1.Enabled := False;
end;
procedure TForm1.DXTimer1Timer(Sender: TObject; LagCount: Integer);
begin
//First we update the DXInputComponent so we can receive new input
DXInput1.Update;
//Then we erase the background and make it black again
DXDraw1.Surface.Fill(0);
//Move the sprites, this call exexutes the DoMove method of it's sprites
DXSpriteEngine1.Move(1);
//Now we will process all dead sprites
DXSpriteEngine1.Dead;
//And we draw the other sprites on the screen
DXSpriteEngine1.Draw;
//Now we display the time that has passed
with DXDraw1.Surface.Canvas do
begin
Brush.Style := bsClear;
Font.Color := clRed;
Font.Size := 12;
TextOut(0,0, 'Time: ' + IntToStr(Seconds));
Release;
end;
//And if all enemies are dead and the player is the only one left then we display the final time and we disable the Timers
If DXSpriteEngine1.Engine.AllCount = 1 Then
begin
Timer1.Enabled := False;
DXTimer1.Enabled := False;
with DXDraw1.Surface.Canvas do
begin
Form1.DXWaveList1.Items.Find('Tada').Play(False);
Brush.Style := bsClear;
Font.Color := clYellow;
Font.Size := 26;
TextOut(160,220, 'Your time: ' + IntToStr(Seconds) + ' seconds');
Release;
end;
end;
//At last we flip the buffers to make the final result visible to the user
DXDraw1.Flip;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
//Reset the time counter
Seconds := 0;
//Now we're gonna create the enemy, the red balls, We'll create 50 of them
For i := 1 To 50 do
begin
With DXSpriteEngine1.Items.Add Do Begin
KindSprite := stImageSprite;
Sprite.AsSign(DXSpriteEngine1.Items.Find('EnemySprite').Sprite);
Sprite.X := Random(DXDraw1.SurfaceWidth); //Set the Position Randomly
Sprite.Y := Random(DXDraw1.SurfaceHeight);
Name := Format('EnemySprite%d',[I]);
Sprite.Tag := 0;
End;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
//Increase the time in seconds
Inc(Seconds);
end;
procedure TForm1.DXSpriteEngine1Items0Collision(Sender: TObject;
var Done: Boolean);
begin
//We're hit! If the enemy is a red ball then kill it!
If Sender <> DXSpriteEngine1.Items.Find('MySprite') Then
With (Sender as TImageSprite) Do
begin
Dead; //Kill the one who hit us!
DXWaveList1.Items.Find('Hit').Play(False); //And play a nice wave sound
End;
end;
procedure TForm1.DXSpriteEngine1Items0Move(Sender: TObject;
var MoveCount: Integer);
begin
//Look at the keys that are pressed and move to the right direction
With Sender as TImageSprite Do Begin
If isUp in Form1.DXInput1.States Then
Y := Y - 15;
If isDown in Form1.DXInput1.States Then
Y := Y + 15;
If isLeft in Form1.DXInput1.States Then
X := X - 15;
If isRight in Form1.DXInput1.States Then
X := X + 15;
//When we're out of the screen we pop up on the other side again
If X > Form1.DXDraw1.SurfaceWidth Then X := 1;
If Y > Form1.DXDraw1.SurfaceHeight Then Y := 1;
If X <= 0 Then X := Form1.DXDraw1.SurfaceWidth - 1;
If Y <= 0 Then Y := Form1.DXDraw1.SurfaceHeight - 1;
//Now we're gonna check for collisions with our Green Ball, this procedure results in the execution of one or more TMySprite.DoCollision procedures...
Collision;
End;
end;
procedure TForm1.DXSpriteEngine1Items0GetImage(Sender: TObject;
var Image: TPictureCollectionItem);
begin
Image := DXImageList1.Items.Find('GreenBall');
end;
procedure TForm1.DXSpriteEngine1Items1GetImage(Sender: TObject;
var Image: TPictureCollectionItem);
begin
Image := DXImageList1.Items.Find('RedBall');
end;
procedure TForm1.DXSpriteEngine1Items1Move(Sender: TObject;
var MoveCount: Integer);
begin
If Sender <> DXSpriteEngine1.Items.Find('MySprite') Then
With Sender as TImageSprite do
Begin
//Choose a random new direction at a random time
If (Random(30) = 15) Or (Tag = 0) Then
Tag := Random(5);
//Do the movement
Case Tag of
1: X := X + 15;
2: X := X - 15;
3: Y := Y + 15;
4: Y := Y - 15;
end;
//If we're out of the screen we want to pop up at the other side again
If X > Form1.DXDraw1.SurfaceWidth Then X := 1;
If Y > Form1.DXDraw1.SurfaceHeight Then Y := 1;
If X <= 0 Then X := Form1.DXDraw1.SurfaceWidth - 1;
If Y <= 0 Then Y := Form1.DXDraw1.SurfaceHeight - 1;
End
end;
end.
| 412 | 0.794586 | 1 | 0.794586 | game-dev | MEDIA | 0.649102 | game-dev,graphics-rendering | 0.95936 | 1 | 0.95936 |
azhirnov/FrameGraph | 15,658 | extensions/framework/Window/WindowSDL2.cpp | // Copyright (c) 2018-2020, Zhirnov Andrey. For more information see 'LICENSE'
#include "WindowSDL2.h"
#include "framework/Vulkan/VulkanSurface.h"
#include "stl/Containers/Singleton.h"
#ifdef FG_ENABLE_SDL2
# include "SDL_syswm.h"
namespace FGC
{
namespace {
struct SDL2Instance
{
uint refCounter = 0;
bool initialized = false;
};
}
/*
=================================================
constructor
=================================================
*/
WindowSDL2::WindowSDL2 () :
_window{ null },
_wndID{ 0 }
{
for (auto& state : _keyStates) {
state = EKeyAction(~0u);
}
}
/*
=================================================
destructor
=================================================
*/
WindowSDL2::~WindowSDL2 ()
{
Destroy();
}
/*
=================================================
Create
=================================================
*/
bool WindowSDL2::Create (uint2 surfaceSize, NtStringView title)
{
CHECK_ERR( not _window );
auto& inst = *Singleton<SDL2Instance>();
if ( not inst.initialized )
{
CHECK( SDL_Init( SDL_INIT_EVERYTHING ) == 0 );
inst.initialized = true;
}
++inst.refCounter;
//const int count = SDL_GetNumVideoDisplays();
//const int disp_idx= 0;
//SDL_Rect area = {};
//CHECK( SDL_GetDisplayUsableBounds( disp_idx, OUT &area ));
//const int2 pos = int2(area.x + area.w/2 - surfaceSize.x/2, area.y + area.h/2 - surfaceSize.y/2);
const uint flags = int(SDL_WINDOW_ALLOW_HIGHDPI) | int(SDL_WINDOW_RESIZABLE);
CHECK_ERR( (_window = SDL_CreateWindow( title.c_str(),
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
surfaceSize.x, surfaceSize.y,
flags )) != null );
_wndID = SDL_GetWindowID( _window );
SDL_SetWindowData( _window, "fg", this );
return true;
}
/*
=================================================
AddListener
=================================================
*/
void WindowSDL2::AddListener (IWindowEventListener *listener)
{
ASSERT( listener );
_listeners.insert( listener );
}
/*
=================================================
RemoveListener
=================================================
*/
void WindowSDL2::RemoveListener (IWindowEventListener *listener)
{
ASSERT( listener );
_listeners.erase( listener );
}
/*
=================================================
Update
=================================================
*/
bool WindowSDL2::Update ()
{
const auto OnKeyEvent = [this] (bool down, SDL_Scancode scancode)
{
auto& state = _keyStates[ scancode ];
if ( down ) {
if ( state == EKeyAction::Down or state == EKeyAction::Pressed )
state = EKeyAction::Pressed;
else
state = EKeyAction::Down;
}else
state = EKeyAction::Up;
for (auto& active : _activeKeys)
{
// skip duplicates
if ( active.first == scancode )
{
if ( state == EKeyAction::Up )
active.second = state;
return;
}
}
_activeKeys.push_back({ scancode, state });
};
//---------------------------------------------------------------------------
if ( not _window )
return false;
SDL_Event ev;
while ( SDL_PollEvent( OUT &ev ))
{
// check for events from different window
bool other_wnd = false;
switch ( ev.type )
{
case SDL_WINDOWEVENT : other_wnd = (ev.window.windowID != _wndID); break;
case SDL_KEYDOWN :
case SDL_KEYUP : other_wnd = (ev.key.windowID != _wndID); break;
case SDL_TEXTEDITING : other_wnd = (ev.edit.windowID != _wndID); break;
case SDL_TEXTINPUT : other_wnd = (ev.text.windowID != _wndID); break;
case SDL_MOUSEMOTION : other_wnd = (ev.motion.windowID != _wndID); break;
case SDL_MOUSEBUTTONDOWN :
case SDL_MOUSEBUTTONUP : other_wnd = (ev.button.windowID != _wndID); break;
case SDL_MOUSEWHEEL : other_wnd = (ev.wheel.windowID != _wndID); break;
}
if ( other_wnd )
{
SDL_PushEvent( &ev );
return true;
}
switch ( ev.type )
{
case SDL_QUIT :
case SDL_APP_TERMINATING :
Quit();
return false;
case SDL_APP_WILLENTERBACKGROUND :
break;
case SDL_APP_DIDENTERBACKGROUND :
break;
case SDL_APP_WILLENTERFOREGROUND :
break;
case SDL_APP_DIDENTERFOREGROUND :
break;
case SDL_MOUSEMOTION :
{
float2 pos = { float(ev.motion.x), float(ev.motion.y) };
for (auto& listener : _listeners) {
listener->OnMouseMove( pos );
}
break;
}
case SDL_MOUSEBUTTONDOWN :
case SDL_MOUSEBUTTONUP :
{
OnKeyEvent( ev.type == SDL_MOUSEBUTTONDOWN, SDL_Scancode(SDL_NUM_SCANCODES + ev.button.button) );
break;
}
case SDL_MOUSEWHEEL :
{
break;
}
case SDL_KEYDOWN :
case SDL_KEYUP :
{
OnKeyEvent( ev.type == SDL_KEYDOWN, ev.key.keysym.scancode );
break;
}
case SDL_WINDOWEVENT :
{
switch ( ev.window.event )
{
case SDL_WINDOWEVENT_SHOWN :
{
break;
}
case SDL_WINDOWEVENT_HIDDEN :
{
break;
}
case SDL_WINDOWEVENT_RESIZED :
//case SDL_WINDOWEVENT_MOVED :
//case SDL_WINDOWEVENT_SIZE_CHANGED :
{
if ( _window )
{
int2 size;
SDL_GetWindowSize( _window, OUT &size.x, OUT &size.y );
for (auto& listener : _listeners) {
listener->OnResize( uint2(size) );
}
}
break;
}
case SDL_WINDOWEVENT_CLOSE :
{
Quit();
return false;
}
}
break;
}
}
}
for (auto key_iter = _activeKeys.begin(); key_iter != _activeKeys.end();)
{
StringView key_name = _MapKey( key_iter->first );
EKeyAction& action = key_iter->second;
if ( key_name.size() )
{
for (auto& listener : _listeners) {
listener->OnKey( key_name, action );
}
}
BEGIN_ENUM_CHECKS();
switch ( action ) {
case EKeyAction::Up : key_iter = _activeKeys.erase( key_iter ); break;
case EKeyAction::Down : action = EKeyAction::Pressed; break;
case EKeyAction::Pressed : ++key_iter; break;
}
END_ENUM_CHECKS();
}
if ( not _window )
return false;
for (auto& listener : _listeners) {
listener->OnUpdate();
}
return true;
}
/*
=================================================
Quit
=================================================
*/
void WindowSDL2::Quit ()
{
Destroy();
}
/*
=================================================
Destroy
=================================================
*/
void WindowSDL2::Destroy ()
{
for (auto& listener : _listeners) {
listener->OnDestroy();
}
if ( _window )
{
SDL_DestroyWindow( _window );
_window = null;
_wndID = 0;
auto& inst = *Singleton<SDL2Instance>();
if ( --inst.refCounter == 0 and inst.initialized )
{
SDL_Quit();
inst.initialized = false;
}
}
}
/*
=================================================
SetTitle
=================================================
*/
void WindowSDL2::SetTitle (NtStringView value)
{
CHECK_ERRV( _window );
SDL_SetWindowTitle( _window, value.c_str() );
}
/*
=================================================
SetSize
=================================================
*/
void WindowSDL2::SetSize (const uint2 &value)
{
CHECK_ERRV( _window );
SDL_SetWindowSize( _window, int(value.x), int(value.y) );
}
/*
=================================================
SetPosition
=================================================
*/
void WindowSDL2::SetPosition (const int2 &value)
{
CHECK_ERRV( _window );
SDL_SetWindowPosition( _window, value.x, value.y );
}
/*
=================================================
GetSize
=================================================
*/
uint2 WindowSDL2::GetSize () const
{
CHECK_ERR( _window );
int2 size;
SDL_GetWindowSize( _window, OUT &size.x, OUT &size.y );
return uint2(size);
}
/*
=================================================
_MapKey
=================================================
*/
StringView WindowSDL2::_MapKey (SDL_Scancode code)
{
switch ( int(code) )
{
case SDL_SCANCODE_BACKSPACE : return "backspace";
case SDL_SCANCODE_TAB : return "tab";
case SDL_SCANCODE_CLEAR : return "clear";
case SDL_SCANCODE_RETURN : return "enter";
case SDL_SCANCODE_LCTRL : return "l-ctrl";
case SDL_SCANCODE_RCTRL : return "r-ctrl";
case SDL_SCANCODE_LALT : return "l-alt";
case SDL_SCANCODE_RALT : return "r-alt";
case SDL_SCANCODE_PAUSE : return "pause";
case SDL_SCANCODE_CAPSLOCK : return "caps lock";
case SDL_SCANCODE_ESCAPE : return "escape";
case SDL_SCANCODE_SPACE : return "space";
case SDL_SCANCODE_PAGEUP : return "page up";
case SDL_SCANCODE_PAGEDOWN : return "page down";
case SDL_SCANCODE_END : return "end";
case SDL_SCANCODE_HOME : return "home";
case SDL_SCANCODE_LEFT : return "arrow left";
case SDL_SCANCODE_UP : return "arrow up";
case SDL_SCANCODE_RIGHT : return "arrow right";
case SDL_SCANCODE_DOWN : return "arrow down";
case SDL_SCANCODE_PRINTSCREEN : return "print screen";
case SDL_SCANCODE_INSERT : return "insert";
case SDL_SCANCODE_DELETE : return "delete";
case SDL_SCANCODE_0 : return "0";
case SDL_SCANCODE_1 : return "1";
case SDL_SCANCODE_2 : return "2";
case SDL_SCANCODE_3 : return "3";
case SDL_SCANCODE_4 : return "4";
case SDL_SCANCODE_5 : return "5";
case SDL_SCANCODE_6 : return "6";
case SDL_SCANCODE_7 : return "7";
case SDL_SCANCODE_8 : return "8";
case SDL_SCANCODE_9 : return "9";
case SDL_SCANCODE_A : return "A";
case SDL_SCANCODE_B : return "B";
case SDL_SCANCODE_C : return "C";
case SDL_SCANCODE_D : return "D";
case SDL_SCANCODE_E : return "E";
case SDL_SCANCODE_F : return "F";
case SDL_SCANCODE_G : return "G";
case SDL_SCANCODE_H : return "H";
case SDL_SCANCODE_I : return "I";
case SDL_SCANCODE_J : return "J";
case SDL_SCANCODE_K : return "K";
case SDL_SCANCODE_L : return "L";
case SDL_SCANCODE_M : return "M";
case SDL_SCANCODE_N : return "N";
case SDL_SCANCODE_O : return "O";
case SDL_SCANCODE_P : return "P";
case SDL_SCANCODE_Q : return "Q";
case SDL_SCANCODE_R : return "R";
case SDL_SCANCODE_S : return "S";
case SDL_SCANCODE_T : return "T";
case SDL_SCANCODE_U : return "U";
case SDL_SCANCODE_V : return "V";
case SDL_SCANCODE_W : return "W";
case SDL_SCANCODE_X : return "X";
case SDL_SCANCODE_Y : return "Y";
case SDL_SCANCODE_Z : return "Z";
case SDL_SCANCODE_KP_ENTER : return "numpad enter";
case SDL_SCANCODE_KP_0 : return "numpad 0";
case SDL_SCANCODE_KP_1 : return "numpad 1";
case SDL_SCANCODE_KP_2 : return "numpad 2";
case SDL_SCANCODE_KP_3 : return "numpad 3";
case SDL_SCANCODE_KP_4 : return "numpad 4";
case SDL_SCANCODE_KP_5 : return "numpad 5";
case SDL_SCANCODE_KP_6 : return "numpad 6";
case SDL_SCANCODE_KP_7 : return "numpad 7";
case SDL_SCANCODE_KP_8 : return "numpad 8";
case SDL_SCANCODE_KP_9 : return "numpad 9";
case SDL_SCANCODE_KP_MULTIPLY : return "numpad *";
case SDL_SCANCODE_KP_PLUS : return "numpad +";
case SDL_SCANCODE_SEPARATOR : return "numpad sep";
case SDL_SCANCODE_KP_MINUS : return "numpad -";
case SDL_SCANCODE_KP_PERIOD : return "numpad .";
case SDL_SCANCODE_KP_DIVIDE : return "numpad /";
case SDL_SCANCODE_KP_EQUALS : return "numpad =";
case SDL_SCANCODE_KP_COMMA : return "numpad ,";
case SDL_SCANCODE_F1 : return "F1";
case SDL_SCANCODE_F2 : return "F2";
case SDL_SCANCODE_F3 : return "F3";
case SDL_SCANCODE_F4 : return "F4";
case SDL_SCANCODE_F5 : return "F5";
case SDL_SCANCODE_F6 : return "F6";
case SDL_SCANCODE_F7 : return "F7";
case SDL_SCANCODE_F8 : return "F8";
case SDL_SCANCODE_F9 : return "F9";
case SDL_SCANCODE_F10 : return "F10";
case SDL_SCANCODE_F11 : return "F11";
case SDL_SCANCODE_F12 : return "F12";
case SDL_SCANCODE_NUMLOCKCLEAR : return "num lock";
case SDL_SCANCODE_SCROLLLOCK : return "scroll lock";
case SDL_SCANCODE_SEMICOLON : return ";";
case SDL_SCANCODE_EQUALS : return "=";
case SDL_SCANCODE_COMMA : return ",";
case SDL_SCANCODE_MINUS : return "-";
case SDL_SCANCODE_PERIOD : return ".";
case SDL_SCANCODE_BACKSLASH : return "/";
case SDL_SCANCODE_GRAVE : return "~";
case SDL_SCANCODE_LEFTBRACKET : return "[";
case SDL_SCANCODE_SLASH : return "\\";
case SDL_SCANCODE_RIGHTBRACKET : return "]";
case SDL_SCANCODE_APOSTROPHE : return "'";
case SDL_NUM_SCANCODES + 1 : return "left mb";
case SDL_NUM_SCANCODES + 2 : return "right mb";
case SDL_NUM_SCANCODES + 3 : return "middle mb";
case SDL_NUM_SCANCODES + 4 : return "mouse btn 4";
case SDL_NUM_SCANCODES + 5 : return "mouse btn 5";
case SDL_NUM_SCANCODES + 6 : return "mouse btn 6";
case SDL_NUM_SCANCODES + 7 : return "mouse btn 7";
case SDL_NUM_SCANCODES + 8 : return "mouse btn 8";
}
return "";
}
/*
=================================================
GetVulkanSurface
=================================================
*/
UniquePtr<IVulkanSurface> WindowSDL2::GetVulkanSurface () const
{
#ifdef FG_ENABLE_VULKAN
return UniquePtr<IVulkanSurface>{new VulkanSurface( _window )};
#else
return {};
#endif
}
/*
=================================================
GetPlatformHandle
=================================================
*/
void* WindowSDL2::GetPlatformHandle () const
{
if ( not _window )
return null;
SDL_SysWMinfo info = {};
SDL_VERSION( OUT &info.version );
CHECK_ERR( SDL_GetWindowWMInfo( _window, OUT &info ) == SDL_TRUE );
switch ( info.subsystem )
{
#ifdef PLATFORM_ANDROID
case SDL_SYSWM_ANDROID :
return info.info.android.window;
#endif
#ifdef PLATFORM_WINDOWS
case SDL_SYSWM_WINDOWS :
return info.info.win.window;
#endif
}
return null;
}
//-----------------------------------------------------------------------------
# ifdef FG_ENABLE_VULKAN
/*
=================================================
VulkanSurface
=================================================
*/
WindowSDL2::VulkanSurface::VulkanSurface (SDL_Window *wnd) :
_window{wnd}, _extensions{FGC::VulkanSurface::GetRequiredExtensions()}
{}
/*
=================================================
Create
=================================================
*/
IVulkanSurface::SurfaceVk_t WindowSDL2::VulkanSurface::Create (InstanceVk_t instance) const
{
SDL_SysWMinfo info = {};
SDL_VERSION( OUT &info.version );
CHECK_ERR( SDL_GetWindowWMInfo( _window, OUT &info ) == SDL_TRUE );
switch ( info.subsystem )
{
case SDL_SYSWM_X11 :
return Zero; // TODO
case SDL_SYSWM_WAYLAND :
return Zero; // TODO
case SDL_SYSWM_MIR :
return Zero; // TODO
# if defined(VK_USE_PLATFORM_ANDROID_KHR)
case SDL_SYSWM_ANDROID :
return BitCast<SurfaceVk_t>( FGC::VulkanSurface::CreateAndroidSurface( instance, info.info.android.window ));
# endif
# if defined(PLATFORM_WINDOWS) or defined(VK_USE_PLATFORM_WIN32_KHR)
case SDL_SYSWM_WINDOWS :
return BitCast<SurfaceVk_t>( FGC::VulkanSurface::CreateWin32Surface( instance, info.info.win.hinstance, info.info.win.window ));
# endif
}
RETURN_ERR( "current subsystem type is not supported!" );
}
# endif // FG_ENABLE_VULKAN
} // FGC
#endif // FG_ENABLE_SDL2
| 412 | 0.81324 | 1 | 0.81324 | game-dev | MEDIA | 0.597428 | game-dev | 0.873231 | 1 | 0.873231 |
tgstation/tgstation | 13,687 | code/modules/mob/living/carbon/human/species_types/ethereal.dm | /datum/species/ethereal
name = "\improper Ethereal"
id = SPECIES_ETHEREAL
meat = /obj/item/food/meat/slab/human/mutant/ethereal
mutantlungs = /obj/item/organ/lungs/ethereal
smoker_lungs = /obj/item/organ/lungs/ethereal/ethereal_smoker
mutantstomach = /obj/item/organ/stomach/ethereal
mutanttongue = /obj/item/organ/tongue/ethereal
mutantheart = /obj/item/organ/heart/ethereal
exotic_bloodtype = BLOOD_TYPE_ETHEREAL
siemens_coeff = 0.5 //They thrive on energy
payday_modifier = 1.0
inherent_traits = list(
TRAIT_MUTANT_COLORS,
TRAIT_FIXED_MUTANT_COLORS,
TRAIT_AGENDER,
)
changesource_flags = MIRROR_BADMIN | WABBAJACK | MIRROR_PRIDE | MIRROR_MAGIC | RACE_SWAP | ERT_SPAWN | SLIME_EXTRACT
species_cookie = /obj/item/food/energybar
species_language_holder = /datum/language_holder/ethereal
sexes = FALSE //no fetish content allowed
// Body temperature for ethereals is much higher than humans as they like hotter environments
bodytemp_normal = (BODYTEMP_NORMAL + 50)
bodytemp_heat_damage_limit = FIRE_MINIMUM_TEMPERATURE_TO_SPREAD // about 150C
// Cold temperatures hurt faster as it is harder to move with out the heat energy
bodytemp_cold_damage_limit = (T20C - 10) // about 10c
hair_color_mode = USE_FIXED_MUTANT_COLOR
hair_alpha = 140
facial_hair_alpha = 140
bodypart_overrides = list(
BODY_ZONE_L_ARM = /obj/item/bodypart/arm/left/ethereal,
BODY_ZONE_R_ARM = /obj/item/bodypart/arm/right/ethereal,
BODY_ZONE_HEAD = /obj/item/bodypart/head/ethereal,
BODY_ZONE_L_LEG = /obj/item/bodypart/leg/left/ethereal,
BODY_ZONE_R_LEG = /obj/item/bodypart/leg/right/ethereal,
BODY_ZONE_CHEST = /obj/item/bodypart/chest/ethereal,
)
var/current_color
var/default_color
var/disrupted = FALSE
var/emageffect = FALSE
var/powermult = 1
var/rangemult = 1
var/flickering = FALSE
var/currently_flickered
var/obj/effect/dummy/lighting_obj/ethereal_light
/datum/species/ethereal/Destroy(force)
QDEL_NULL(ethereal_light)
return ..()
/datum/species/ethereal/on_species_gain(mob/living/carbon/human/new_ethereal, datum/species/old_species, pref_load, regenerate_icons)
. = ..()
if(!ishuman(new_ethereal))
return
default_color = new_ethereal.dna.features[FEATURE_ETHEREAL_COLOR]
RegisterSignal(new_ethereal, COMSIG_ATOM_EMAG_ACT, PROC_REF(on_emag_act))
RegisterSignal(new_ethereal, COMSIG_ATOM_EMP_ACT, PROC_REF(on_emp_act))
RegisterSignal(new_ethereal, COMSIG_ATOM_SABOTEUR_ACT, PROC_REF(hit_by_saboteur))
RegisterSignal(new_ethereal, COMSIG_LIGHT_EATER_ACT, PROC_REF(on_light_eater))
RegisterSignal(new_ethereal, COMSIG_LIVING_HEALTH_UPDATE, PROC_REF(refresh_light_color))
ethereal_light = new_ethereal.mob_light(light_type = /obj/effect/dummy/lighting_obj/moblight/species)
refresh_light_color(new_ethereal)
var/obj/item/organ/heart/ethereal/ethereal_heart = new_ethereal.get_organ_slot(ORGAN_SLOT_HEART)
ethereal_heart.ethereal_color = default_color
for(var/obj/item/bodypart/limb as anything in new_ethereal.bodyparts)
if(limb.limb_id == SPECIES_ETHEREAL)
limb.update_limb(is_creating = TRUE)
/datum/species/ethereal/on_species_loss(mob/living/carbon/human/former_ethereal, datum/species/new_species, pref_load)
UnregisterSignal(former_ethereal, list(
COMSIG_ATOM_EMAG_ACT,
COMSIG_ATOM_EMP_ACT,
COMSIG_ATOM_SABOTEUR_ACT,
COMSIG_LIGHT_EATER_ACT,
COMSIG_LIVING_HEALTH_UPDATE,
))
QDEL_NULL(ethereal_light)
return ..()
/datum/species/ethereal/randomize_features()
var/list/features = ..()
features[FEATURE_ETHEREAL_COLOR] = GLOB.color_list_ethereal[pick(GLOB.color_list_ethereal)]
return features
/datum/species/ethereal/proc/refresh_light_color(mob/living/carbon/human/ethereal)
SIGNAL_HANDLER
if(isnull(ethereal_light))
return
if(ethereal.stat != DEAD && !disrupted)
var/healthpercent = max(ethereal.health, 0) / 100
if(!emageffect)
var/static/list/skin_color = rgb2num("#eda495")
var/list/colors = rgb2num(ethereal.dna.features[FEATURE_ETHEREAL_COLOR])
var/list/built_color = list()
for(var/i in 1 to 3)
built_color += skin_color[i] + ((colors[i] - skin_color[i]) * healthpercent)
current_color = rgb(built_color[1], built_color[2], built_color[3])
ethereal_light.set_light_range_power_color((1 + (2 * healthpercent)) * rangemult, (1 + (1 * healthpercent) * powermult), current_color)
if(flickering)
if(currently_flickered)
ethereal_light.set_light_on(FALSE)
else
ethereal_light.set_light_on(TRUE)
else
if(currently_flickered)
currently_flickered = FALSE
ethereal_light.set_light_on(TRUE)
fixed_mut_color = current_color
ethereal.update_body()
ethereal.set_facial_haircolor(current_color, override = TRUE, update = FALSE)
ethereal.set_haircolor(current_color, override = TRUE, update = TRUE)
else
ethereal_light.set_light_on(FALSE)
var/dead_color = rgb(128,128,128)
fixed_mut_color = dead_color
ethereal.update_body()
ethereal.set_facial_haircolor(dead_color, override = TRUE, update = FALSE)
ethereal.set_haircolor(dead_color, override = TRUE, update = TRUE)
/datum/species/ethereal/proc/on_emp_act(mob/living/carbon/human/source, severity, protection)
SIGNAL_HANDLER
if(protection & EMP_PROTECT_SELF)
return
disrupted = TRUE
refresh_light_color(source)
to_chat(source, span_notice("You feel the light of your body leave you."))
switch(severity)
if(EMP_LIGHT)
addtimer(CALLBACK(src, PROC_REF(stop_emp), source), 10 SECONDS, TIMER_UNIQUE|TIMER_OVERRIDE) //We're out for 10 seconds
if(EMP_HEAVY)
addtimer(CALLBACK(src, PROC_REF(stop_emp), source), 20 SECONDS, TIMER_UNIQUE|TIMER_OVERRIDE) //We're out for 20 seconds
/datum/species/ethereal/proc/hit_by_saboteur(mob/living/carbon/human/source, disrupt_duration)
disrupted = TRUE
refresh_light_color(source)
to_chat(source, span_warning("Something inside of you crackles in a bad way."))
source.take_bodypart_damage(burn = 3, wound_bonus = CANT_WOUND)
addtimer(CALLBACK(src, PROC_REF(stop_emp), source), disrupt_duration, TIMER_UNIQUE|TIMER_OVERRIDE)
return TRUE
/datum/species/ethereal/proc/on_emag_act(mob/living/carbon/human/source, mob/user)
SIGNAL_HANDLER
if(emageffect)
return FALSE
emageffect = TRUE
if(user)
to_chat(user, span_notice("You tap [source] on the back with your card."))
source.visible_message(span_danger("[source] starts flickering in an array of colors!"))
handle_emag(source)
addtimer(CALLBACK(src, PROC_REF(stop_emag), source), 2 MINUTES) //Disco mode for 2 minutes! This doesn't affect the ethereal at all besides either annoying some players, or making someone look badass.
return TRUE
/// Special handling for getting hit with a light eater
/datum/species/ethereal/proc/on_light_eater(mob/living/carbon/human/source, datum/light_eater)
SIGNAL_HANDLER
source.emp_act(EMP_LIGHT)
return COMPONENT_BLOCK_LIGHT_EATER
/datum/species/ethereal/proc/stop_emp(mob/living/carbon/human/ethereal)
disrupted = FALSE
refresh_light_color(ethereal)
to_chat(ethereal, span_notice("You feel more energized as your shine comes back."))
/datum/species/ethereal/proc/handle_emag(mob/living/carbon/human/ethereal)
if(!emageffect)
return
current_color = GLOB.color_list_ethereal[pick(GLOB.color_list_ethereal)]
refresh_light_color(ethereal)
addtimer(CALLBACK(src, PROC_REF(handle_emag), ethereal), 0.5 SECONDS)
/datum/species/ethereal/proc/stop_emag(mob/living/carbon/human/ethereal)
emageffect = FALSE
refresh_light_color(ethereal)
ethereal.visible_message(span_danger("[ethereal] stops flickering and goes back to their normal state!"))
/datum/species/ethereal/proc/handle_glow_emote(mob/living/carbon/human/ethereal, power, range, flare = FALSE, duration = 5 SECONDS, flare_time = 0)
powermult = power
rangemult = range
refresh_light_color(ethereal)
addtimer(CALLBACK(src, PROC_REF(stop_glow_emote), ethereal, flare, flare_time), duration)
/datum/species/ethereal/proc/stop_glow_emote(mob/living/carbon/human/ethereal, flare, flare_time)
if(!flare)
powermult = 1
rangemult = 1
refresh_light_color(ethereal)
return
powermult = 0.5
rangemult = 0.75
refresh_light_color(ethereal)
start_flicker(ethereal, duration = 1.5 SECONDS, min = 1, max = 2)
sleep(1.5 SECONDS)
powermult = 1
rangemult = 1
disrupted = TRUE
to_chat(ethereal, span_warning("Your shine flickers and fades."))
addtimer(CALLBACK(src, PROC_REF(stop_emp), ethereal), flare_time, TIMER_UNIQUE|TIMER_OVERRIDE)
/datum/species/ethereal/proc/start_flicker(mob/living/carbon/human/ethereal, duration = 6 SECONDS, min = 1, max = 4)
flickering = TRUE
handle_flicker(ethereal, min, max)
addtimer(CALLBACK(src, PROC_REF(stop_flicker), ethereal), duration)
/datum/species/ethereal/proc/handle_flicker(mob/living/carbon/human/ethereal, flickmin = 1, flickmax = 4)
if(!flickering)
currently_flickered = FALSE
refresh_light_color(ethereal)
return
if(currently_flickered)
currently_flickered = FALSE
else
currently_flickered = TRUE
refresh_light_color(ethereal)
addtimer(CALLBACK(src, PROC_REF(handle_flicker), ethereal), rand(1, 4))
/datum/species/ethereal/proc/stop_flicker(mob/living/carbon/human/ethereal)
flickering = FALSE
currently_flickered = FALSE
/datum/species/ethereal/get_features()
var/list/features = ..()
features += "feature_ethcolor"
return features
/datum/species/ethereal/get_scream_sound(mob/living/carbon/human/ethereal)
return pick(
'sound/mobs/humanoids/ethereal/ethereal_scream_1.ogg',
'sound/mobs/humanoids/ethereal/ethereal_scream_2.ogg',
'sound/mobs/humanoids/ethereal/ethereal_scream_3.ogg',
)
/datum/species/ethereal/get_hiss_sound(mob/living/carbon/human/ethereal)
return 'sound/mobs/humanoids/ethereal/ethereal_hiss.ogg'
/datum/species/ethereal/get_physical_attributes()
return "Ethereals process electricity as their power supply, not food, and are somewhat resistant to it.\
They do so via their crystal core, their equivalent of a human heart, which will also encase them in a reviving crystal if they die.\
However, their skin is very thin and easy to pierce with brute weaponry."
/datum/species/ethereal/get_species_description()
return "Coming from the planet of Sprout, the theocratic ethereals are \
separated socially by caste, and espouse a dogma of aiding the weak and \
downtrodden."
/datum/species/ethereal/get_species_lore()
return list(
"Ethereals are a species native to the planet Sprout. \
When they were originally discovered, they were at a medieval level of technological progression, \
but due to their natural acclimation with electricity, they felt easy among the large Nanotrasen installations.",
)
/datum/species/ethereal/create_pref_unique_perks()
var/list/to_add = list()
to_add += list(
list(
SPECIES_PERK_TYPE = SPECIES_POSITIVE_PERK,
SPECIES_PERK_ICON = "bolt",
SPECIES_PERK_NAME = "Shockingly Tasty",
SPECIES_PERK_DESC = "Ethereals can feed on electricity from APCs, and do not otherwise need to eat.",
),
list(
SPECIES_PERK_TYPE = SPECIES_POSITIVE_PERK,
SPECIES_PERK_ICON = "lightbulb",
SPECIES_PERK_NAME = "Disco Ball",
SPECIES_PERK_DESC = "Ethereals passively generate their own light.",
),
list(
SPECIES_PERK_TYPE = SPECIES_NEUTRAL_PERK,
SPECIES_PERK_ICON = "gem",
SPECIES_PERK_NAME = "Crystal Core",
SPECIES_PERK_DESC = "The Ethereal's heart will encase them in crystal should they die, returning them to life after a time - \
at the cost of a permanent brain trauma.",
),
list(
SPECIES_PERK_TYPE = SPECIES_NEUTRAL_PERK,
SPECIES_PERK_ICON = "fist-raised",
SPECIES_PERK_NAME = "Elemental Attacker",
SPECIES_PERK_DESC = "Ethereals deal burn damage with their punches instead of brute.",
),
list(
SPECIES_PERK_TYPE = SPECIES_NEGATIVE_PERK,
SPECIES_PERK_ICON = "biohazard",
SPECIES_PERK_NAME = "Starving Artist",
SPECIES_PERK_DESC = "Ethereals take toxin damage while starving.",
),
)
return to_add
/datum/species/ethereal/lustrous //Ethereal pirates with an inherent bluespace prophet trauma.
name = "Lustrous"
id = SPECIES_ETHEREAL_LUSTROUS
examine_limb_id = SPECIES_ETHEREAL
mutantbrain = /obj/item/organ/brain/lustrous
changesource_flags = MIRROR_BADMIN | MIRROR_MAGIC | MIRROR_PRIDE | RACE_SWAP | ERT_SPAWN
inherent_traits = list(
TRAIT_MUTANT_COLORS,
TRAIT_FIXED_MUTANT_COLORS,
TRAIT_AGENDER,
TRAIT_NOBREATH,
TRAIT_RESISTHIGHPRESSURE,
TRAIT_RESISTLOWPRESSURE,
TRAIT_VIRUSIMMUNE,
)
bodypart_overrides = list(
BODY_ZONE_HEAD = /obj/item/bodypart/head/ethereal/lustrous,
BODY_ZONE_L_ARM = /obj/item/bodypart/arm/left/ethereal,
BODY_ZONE_R_ARM = /obj/item/bodypart/arm/right/ethereal,
BODY_ZONE_L_LEG = /obj/item/bodypart/leg/left/ethereal,
BODY_ZONE_R_LEG = /obj/item/bodypart/leg/right/ethereal,
BODY_ZONE_CHEST = /obj/item/bodypart/chest/ethereal,
)
/datum/species/ethereal/lustrous/get_physical_attributes()
return "Lustrous are what remains of an Ethereal after freebasing esoteric drugs. \
They are pressure immune, virus immune, can see bluespace tears in reality, and have a really weird scream. They remain vulnerable to physical damage."
/datum/species/ethereal/lustrous/get_scream_sound(mob/living/carbon/human/ethereal)
return pick(
'sound/mobs/humanoids/ethereal/lustrous_scream_1.ogg',
'sound/mobs/humanoids/ethereal/lustrous_scream_2.ogg',
'sound/mobs/humanoids/ethereal/lustrous_scream_3.ogg',
)
/datum/species/ethereal/lustrous/on_species_gain(mob/living/carbon/new_lustrous, datum/species/old_species, pref_load, regenerate_icons)
..()
default_color = new_lustrous.dna.features[FEATURE_ETHEREAL_COLOR]
new_lustrous.dna.features[FEATURE_ETHEREAL_COLOR] = GLOB.color_list_lustrous[pick(GLOB.color_list_lustrous)] //Picks one of 5 lustrous-specific colors.
| 412 | 0.901807 | 1 | 0.901807 | game-dev | MEDIA | 0.960895 | game-dev | 0.776741 | 1 | 0.776741 |
Biomechanical-ToolKit/BTKCore | 1,454 | Documentation/Wrapping/Matlab/btk/@Common/btkSetAnalogLabel.m | function btkSetAnalogLabel(h, idx_or_label, new_label) %#ok
%BTKSETANALOGLABEL Modify analog's label and return updated analogs.
%
% BTKSETANALOGLABEL(H, INDEX, NEWLABEL) modifies analog's label by NEWLABEL for
% the analog at the index INDEX. NEWLABEL must be a non-empty string.
%
% The analog to modify can also be selected by its LABEL.
% BTKSETANALOGLABEL(H, LABEL, NEWLABEL)
%
% This function can also returns an updated list of analogs.
% ANALOGS = BTKSETANALOGLABEL(H, INDEX, NEWLABEL)
% ANALOGS = BTKSETANALOGLABEL(H, LABEL, NEWLABEL)
% The format of ANALOGS is the same than using the function <a href="matlab:help btkGetAnalogs">btkGetAnalogs</a>
%
% This function can also returns an updated list of analogs' informations.
% [ANALOGS, ANALOGSINFO] = BTKSETANALOGLABEL(H, INDEX, NEWLABEL)
% [ANALOGS, ANALOGSINFO] = BTKSETANALOGLABEL(H, LABEL, NEWLABEL)
% The format of ANALOGSINFO is the same than using the function <a href="matlab:help btkGetAnalogs">btkGetAnalogs</a>
%
% The acquisition is represented by the handle H. This handle is obtained
% by the use of a btk* function.
% Author: A. Barré
% Copyright 2009-2014 Biomechanical ToolKit (BTK).
% The following comment, MATLAB compiler pragma, is necessary to avoid
% compiling this M-file instead of linking against the MEX-file. Don't remove.
%# mex
error(generatemsgid('NotSupported'),'MEX file for BTKSETANALOGLABEL not found');
% [EOF] btkSetAnalogLabel.m
| 412 | 0.63269 | 1 | 0.63269 | game-dev | MEDIA | 0.127992 | game-dev | 0.522499 | 1 | 0.522499 |
anegostudios/vssurvivalmod | 40,349 | Entity/Behavior/BehaviorRideable.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vintagestory.API.Client;
using Vintagestory.API.Common;
using Vintagestory.API.Common.Entities;
using Vintagestory.API.Config;
using Vintagestory.API.Datastructures;
using Vintagestory.API.MathTools;
using Vintagestory.API.Server;
#nullable disable
namespace Vintagestory.GameContent
{
public delegate bool CanRideDelegate(IMountableSeat seat, out string errorMessage);
public enum EnumControlScheme
{
Hold,
Press
}
public class EntityBehaviorRideable(Entity entity) : EntityBehaviorSeatable(entity), IMountable, IRenderer, IMountableListener
{
public List<GaitMeta> RideableGaitOrder = new(); // List of gaits in order of increasing speed for the rideable entity
public Vec3f MountAngle { get; set; } = new Vec3f();
public EntityPos SeatPosition => entity.SidedPos;
public double RenderOrder => 1;
public int RenderRange => 100;
public virtual float SpeedMultiplier => 1f;
public Entity Mount => entity;
// current forward speed
public double ForwardSpeed = 0.0;
// current turning speed (rad/tick)
public double AngularVelocity = 0.0;
public bool IsInMidJump;
public event CanRideDelegate CanRide;
public event CanRideDelegate CanTurn;
/// <summary>
/// This is the current animation for the rider
/// </summary>
public AnimationMetaData curAnim;
/// <summary>
/// This is the current animation for any passenger who is not the rider, for example a pillion passenger
/// </summary>
public AnimationMetaData curAnimPassanger;
protected ICoreAPI api;
// Time the player can walk off an edge before gravity applies.
protected float coyoteTimer;
// Time the player last jumped.
protected long lastJumpMs;
protected bool jumpNow;
protected EntityAgent eagent = entity as EntityAgent;
protected long lastGaitChangeMs = 0;
protected float timeSinceLastGaitCheck = 0;
protected float timeSinceLastGaitFatigue = 0;
protected ILoadedSound gaitSound;
protected FastSmallDictionary<string, ControlMeta> Controls;
protected string[] GaitOrderCodes; // List of gaits in order of increasing speed for the rideable entity
protected ICoreClientAPI capi;
protected EntityBehaviorGait ebg;
protected int minGeneration = 0; // Minimum generation for the animal to be rideable
protected GaitMeta saddleBreakGait;
protected string saddleBreakGaitCode;
protected bool onlyTwoGaits = false;
protected bool prevPrevForwardsKey = false; // Used to more reliably filter out long presses of Forwards sometimes detected as two presses (because there is a frame where the control is false, for unknown reasons)
protected bool prevPrevBackwardsKey = false; // Used to more reliably filter out long presses of Backwards sometimes being detected as two presses (because there is a frame where the control is false, for unknown reasons)
protected GaitMeta CurrentGait;
ControlMeta curControlMeta = null;
bool shouldMove = false;
internal string prevSoundCode;
internal string curSoundCode = null;
string curTurnAnim = null;
string curMoveAnim = null;
EnumControlScheme scheme;
#region Semitamed animals
protected float saddleBreakDayInterval;
protected string tamedEntityCode;
public int RemainingSaddleBreaks
{
get
{
return entity.WatchedAttributes.GetInt("remainingSaddleBreaksRequired");
}
set
{
entity.WatchedAttributes.SetInt("remainingSaddleBreaksRequired", value);
}
}
public double LastSaddleBreakTotalDays
{
get
{
return entity.WatchedAttributes.GetDouble("lastSaddlebreakTotalDays");
}
set
{
entity.WatchedAttributes.SetDouble("lastSaddlebreakTotalDays", value);
}
}
#endregion
public double LastDismountTotalHours {
get
{
return entity.WatchedAttributes.GetDouble("lastDismountTotalHours");
}
set
{
entity.WatchedAttributes.SetDouble("lastDismountTotalHours", value);
}
}
protected override IMountableSeat CreateSeat(string seatId, SeatConfig config)
{
return new EntityRideableSeat(this, seatId, config);
}
public override void Initialize(EntityProperties properties, JsonObject attributes)
{
base.Initialize(properties, attributes);
api = entity.Api;
capi = api as ICoreClientAPI;
if (attributes["saddleBreaksRequired"].Exists)
{
if (!entity.WatchedAttributes.HasAttribute("remainingSaddleBreaksRequired") && api.Side == EnumAppSide.Server)
{
RemainingSaddleBreaks = GameMath.RoundRandom(api.World.Rand, attributes["saddleBreaksRequired"].AsObject<NatFloat>().nextFloat(1, api.World.Rand));
}
saddleBreakDayInterval = attributes["saddleBreakDayInterval"].AsFloat();
tamedEntityCode = attributes["tamedEntityCode"].AsString();
saddleBreakGaitCode = attributes["saddleBreakGait"].AsString();
}
Controls = attributes["controls"].AsObject<FastSmallDictionary<string, ControlMeta>>();
minGeneration = attributes["minGeneration"].AsInt(0);
GaitOrderCodes = attributes["rideableGaitOrder"].AsArray<string>();
foreach (var val in Controls.Values)
{
val.RiderAnim?.Init();
val.PassengerAnim?.Init();
}
SetPassengerAnimationsToIdle();
capi?.Event.RegisterRenderer(this, EnumRenderStage.Before, "rideablesim");
if (api.Event is IServerEventAPI serverEvents)
{
serverEvents.MountGaitReceived += ReceiveGaitFromClient;
}
}
private void SetPassengerAnimationsToIdle()
{
var idleControl = Controls["idle"];
curAnim = idleControl.RiderAnim;
curAnimPassanger = idleControl.GetPassengerAnim();
}
/// <summary>
/// Server-side method called when the server has received the gait from the client-authoritative client (i.e. the rider's client)
/// (Helps fix de-sync issues especially for multiplayer observers)
/// </summary>
/// <param name="mountEntity"></param>
/// <param name="gaitCode"></param>
private void ReceiveGaitFromClient(Entity mountEntity, string gaitCode)
{
if (mountEntity != entity || gaitCode == null) return;
foreach (var gait in RideableGaitOrder)
{
if (gait.Code == gaitCode)
{
if (gait == ebg.IdleGait) Stop();
else SetGait(gait);
break;
}
}
}
public override void AfterInitialized(bool onFirstSpawn)
{
base.AfterInitialized(onFirstSpawn);
ebg = eagent.GetBehavior<EntityBehaviorGait>();
// Gaits are required for rideable entities
if (ebg is null)
{
throw new Exception("EntityBehaviorGait not found on rideable entity. Ensure it is properly registered in the entity's properties.");
}
foreach (var str in GaitOrderCodes)
{
GaitMeta gait = ebg?.Gaits[str];
if (gait != null) RideableGaitOrder.Add(gait);
}
onlyTwoGaits = RideableGaitOrder.Count(g => g.MoveSpeed > 0 && g.Backwards == false) == 2;
saddleBreakGait = ebg.Gaits.FirstOrDefault(g => g.Value.Code == saddleBreakGaitCode).Value;
}
public override void OnEntityDespawn(EntityDespawnData despawn)
{
base.OnEntityDespawn(despawn);
capi?.Event.UnregisterRenderer(this, EnumRenderStage.Before);
}
public void UnmnountPassengers()
{
foreach (var seat in Seats)
{
(seat.Passenger as EntityAgent)?.TryUnmount();
}
}
public override void OnEntityLoaded()
{
setupTaskBlocker();
}
public override void OnEntitySpawn()
{
setupTaskBlocker();
}
void setupTaskBlocker()
{
var ebc = entity.GetBehavior<EntityBehaviorAttachable>();
if (api.Side == EnumAppSide.Server)
{
EntityBehaviorTaskAI taskAi = entity.GetBehavior<EntityBehaviorTaskAI>();
taskAi.TaskManager.OnShouldExecuteTask += TaskManager_OnShouldExecuteTask;
if (ebc != null)
{
ebc.Inventory.SlotModified += Inventory_SlotModified;
}
} else
{
if (ebc != null)
{
entity.WatchedAttributes.RegisterModifiedListener(ebc.InventoryClassName, updateControlScheme);
}
}
}
private void Inventory_SlotModified(int obj)
{
updateControlScheme();
ebg?.SetIdle();
CurrentGait = ebg.IdleGait;
}
private void updateControlScheme()
{
var ebc = entity.GetBehavior<EntityBehaviorAttachable>();
if (ebc != null)
{
scheme = EnumControlScheme.Hold;
foreach (var slot in ebc.Inventory)
{
if (slot.Empty) continue;
var sch = slot.Itemstack.ItemAttributes?["controlScheme"].AsString(null);
if (sch != null)
{
if (!Enum.TryParse<EnumControlScheme>(sch, out scheme)) scheme = EnumControlScheme.Hold;
else break;
}
}
}
}
private bool TaskManager_OnShouldExecuteTask(IAiTask task)
{
if (task is AiTaskWander && api.World.Calendar.TotalHours - LastDismountTotalHours < 24) return false;
return !Seats.Any(seat => seat.Passenger != null);
}
bool wasPaused;
public void OnRenderFrame(float dt, EnumRenderStage stage)
{
if (!wasPaused && capi.IsGamePaused)
{
gaitSound?.Pause();
}
if (wasPaused && !capi.IsGamePaused)
{
if (gaitSound?.IsPaused == true) gaitSound?.Start();
}
wasPaused = capi.IsGamePaused;
if (capi.IsGamePaused) return;
CurrentGait ??= ebg.CurrentGait; // Initialize CurrentGait if necessary
updateAngleAndMotion(dt);
}
protected virtual void updateAngleAndMotion(float dt)
{
// Ignore lag spikes
dt = Math.Min(0.5f, dt);
float step = GlobalConstants.PhysicsFrameTime;
var motion = SeatsToMotion(step);
if (jumpNow) updateRidingState();
if (motion != null) // If it's null, it's another player riding the elk in multiplayer, the speed and yaw etc will be governed by packets from the other player
{
ForwardSpeed = Math.Sign(motion.X);
float yawMultiplier = ebg.GetYawMultiplier();
AngularVelocity = motion.Y * yawMultiplier;
entity.SidedPos.Yaw += (float)motion.Y * dt * 30f;
entity.SidedPos.Yaw = entity.SidedPos.Yaw % GameMath.TWOPI;
}
if (entity.World.ElapsedMilliseconds - lastJumpMs < 2000 && entity.World.ElapsedMilliseconds - lastJumpMs > 200 && entity.OnGround)
{
eagent.StopAnimation("jump");
eagent.AnimManager.AnimationsDirty = true;
}
}
bool prevForwardKey, prevBackwardKey, prevSprintKey;
public void SpeedUp() => SetNextGait(true);
public void SlowDown() => SetNextGait(false);
public GaitMeta GetNextGait(bool forward, GaitMeta currentGait = null)
{
currentGait ??= CurrentGait;
if (eagent.Swimming) return forward ? ebg.Gaits["swim"] : ebg.Gaits["swimback"];
if (RideableGaitOrder is not null && RideableGaitOrder.Count > 0 && this.IsBeingControlled())
{
int currentIndex = RideableGaitOrder.IndexOf(currentGait);
int nextIndex = forward ? currentIndex + 1 : currentIndex - 1;
// Boundary behavior
if (nextIndex < 0) nextIndex = 0;
if (nextIndex >= RideableGaitOrder.Count) nextIndex = currentIndex - 1;
return RideableGaitOrder[nextIndex];
}
else
{
return ebg.IdleGait;
}
}
public void SetGait(GaitMeta nextGait)
{
CurrentGait = nextGait;
ebg.CurrentGait = nextGait;
ForwardSpeed = nextGait.Backwards ? - 1 : (nextGait == ebg.IdleGait ? 0 : 1);
}
public void SetNextGait(bool forward, GaitMeta nextGait = null)
{
nextGait ??= GetNextGait(forward);
CurrentGait = nextGait;
}
public GaitMeta GetFirstForwardGait()
{
if (RideableGaitOrder == null || RideableGaitOrder.Count == 0)
return ebg.IdleGait;
// Find the first forward gait
return RideableGaitOrder.FirstOrDefault(g => !g.Backwards && g.MoveSpeed > 0) ?? ebg.IdleGait;
}
public virtual Vec2d SeatsToMotion(float dt)
{
int seatsRowing = 0;
double linearMotion = 0;
double angularMotion = 0;
jumpNow = false;
coyoteTimer -= dt;
Controller = null;
foreach (var seat in Seats)
{
if (seat.Config.Controllable && seat.Passenger != null)
{
Controller = seat.Passenger;
break; // the controller will be the first found passenger who is in a controllable seat; in principle a rideable could have more than one controllable seat
}
}
foreach (var seat in Seats)
{
if (entity.OnGround) coyoteTimer = 0.15f;
if (seat.Passenger == null) continue;
if (seat.Passenger is EntityPlayer eplr)
{
eplr.Controls.LeftMouseDown = seat.Controls.LeftMouseDown;
if (eplr.HeadYawLimits == null)
{
eplr.BodyYawLimits = new AngleConstraint(entity.Pos.Yaw + seat.Config.MountRotation.Y * GameMath.DEG2RAD, seat.Config.BodyYawLimit ?? GameMath.PIHALF);
eplr.HeadYawLimits = new AngleConstraint(entity.Pos.Yaw + seat.Config.MountRotation.Y * GameMath.DEG2RAD, GameMath.PIHALF);
}
else
{
eplr.BodyYawLimits.X = entity.Pos.Yaw + seat.Config.MountRotation.Y * GameMath.DEG2RAD;
eplr.BodyYawLimits.Y = seat.Config.BodyYawLimit ?? GameMath.PIHALF;
eplr.HeadYawLimits.X = entity.Pos.Yaw + seat.Config.MountRotation.Y * GameMath.DEG2RAD;
eplr.HeadYawLimits.Y = GameMath.PIHALF;
}
}
if (Controller != seat.Passenger) continue;
if (capi != null && seat.Passenger != capi.World.Player.Entity) CurrentGait = ebg.CurrentGait; // sync from server to us (through WatchedAttributes system) but don't let the server override if we are the controlling rider client
var controls = seat.Controls;
bool canride = true;
bool canturn = true;
if (RemainingSaddleBreaks > 0)
{
if (api.World.Rand.NextDouble() < 0.05) angularMotionWild = ((float)api.World.Rand.NextDouble() * 2 - 1) / 10f;
angularMotion = angularMotionWild;
canturn = false;
}
if (CanRide != null && (controls.Jump || controls.TriesToMove))
{
foreach (CanRideDelegate dele in CanRide.GetInvocationList())
{
if (!dele(seat, out string errMsg))
{
if (capi != null && seat.Passenger == capi.World.Player.Entity)
{
capi.TriggerIngameError(this, "cantride", Lang.Get("cantride-" + errMsg));
}
canride = false;
break;
}
}
}
if (CanTurn != null && (controls.Left || controls.Right))
{
foreach (CanRideDelegate dele in CanTurn.GetInvocationList())
{
if (!dele(seat, out string errMsg))
{
if (capi != null && seat.Passenger == capi.World.Player.Entity)
{
capi.TriggerIngameError(this, "cantride", Lang.Get("cantride-" + errMsg));
}
canturn = false;
break;
}
}
}
if (!canride) continue;
// Only able to jump every 1500ms. Only works while on the ground. (But for clients on the pillion we omit the ground check, because the elk already left the ground before we receive the Jump control)
if (controls.Jump && entity.World.ElapsedMilliseconds - lastJumpMs > 1500 && entity.Alive && (entity.OnGround || coyoteTimer > 0 || (api.Side == EnumAppSide.Client && entity.EntityId != Controller.EntityId)))
{
lastJumpMs = entity.World.ElapsedMilliseconds;
jumpNow = true;
}
if (scheme == EnumControlScheme.Hold && !controls.TriesToMove) continue;
float str = ++seatsRowing == 1 ? 1 : 0.5f;
// We only let a keypress change the gait and animations if we are a client: this is the client-authoritative system (prevents de-sync as server and client may see keypresses in different ticks or not at all)
if (api.Side != EnumAppSide.Server)
{
// Detect if button currently being pressed
bool nowForwards = controls.Forward;
bool nowBackwards = controls.Backward;
bool nowSprint = controls.Sprint;
// Toggling this off so that the next press of the sprint key will be a fresh press
// Need this to allow cycling up with sprint rather than just treating it as a boolean
// Only applies if there are more than two gaits specified for this mount
controls.Sprint = onlyTwoGaits && controls.Sprint && scheme == EnumControlScheme.Hold;
// Detect if current press is a fresh press
bool backwardPressed = nowBackwards && !prevBackwardKey && !prevPrevBackwardsKey;
bool sprintPressed = nowSprint && !prevSprintKey;
long nowMs = entity.World.ElapsedMilliseconds;
// This ensures we start moving without sprint key
if (nowForwards && !prevForwardKey)
{
if (ebg.IsIdleGait(CurrentGait) && !prevPrevForwardsKey)
{
SpeedUp();
lastGaitChangeMs = nowMs;
}
// Handle backward to idle change without sprint key
else if (ebg.IsBackwards(CurrentGait))
{
CurrentGait = ebg.IdleGait;
lastGaitChangeMs = nowMs;
}
}
// Cycle up with sprint
else if (ebg.IsForwards(CurrentGait) && sprintPressed && nowMs - lastGaitChangeMs > 300)
{
SpeedUp();
lastGaitChangeMs = nowMs;
}
// Cycle down with back or when letting go of sprint when there are only two gaits
bool cycleDown = backwardPressed || (!nowSprint && CurrentGait.IsSprint && scheme == EnumControlScheme.Hold);
if (cycleDown && nowMs - lastGaitChangeMs > 300)
{
controls.Sprint = false;
SlowDown();
lastGaitChangeMs = nowMs;
}
prevSprintKey = nowSprint;
prevPrevForwardsKey = prevForwardKey; // Used to "de-bounce", as sometimes a long-ish press of the Forwards key has a frame client-side when nowForwards is false
prevPrevBackwardsKey = prevBackwardKey; // Used to "de-bounce", as sometimes a long-ish press of the Backwards key has a frame client-side when nowForwards is false
prevForwardKey = (scheme == EnumControlScheme.Press && nowForwards);
prevBackwardKey = scheme == EnumControlScheme.Press && nowBackwards;
}
#region Motion update
if (canturn && (controls.Left || controls.Right))
{
float dir = controls.Left ? 1 : -1;
angularMotion += ebg.GetYawMultiplier() * dir * dt;
}
if (ebg.IsForwards(CurrentGait) || ebg.IsBackwards(CurrentGait))
{
float dir = ebg.IsForwards(CurrentGait) ? 1 : -1;
linearMotion += str * dir * dt * 2f;
}
#endregion
}
return new Vec2d(linearMotion, angularMotion);
}
float angularMotionWild = 1/10f;
bool wasSwimming = false;
protected void updateRidingState()
{
if (!AnyMounted()) return;
if (RemainingSaddleBreaks > 0)
{
if (api.World.Rand.NextDouble() < 0.05) jumpNow = true;
SetGait(saddleBreakGait);
if (api.World.ElapsedMilliseconds - mountedTotalMs > 4000)
{
DoSaddleBreak();
return;
}
}
bool wasMidJump = IsInMidJump;
IsInMidJump &= (entity.World.ElapsedMilliseconds - lastJumpMs < 500 || !entity.OnGround) && !entity.Swimming;
if (wasMidJump && !IsInMidJump)
{
var meta = Controls["jump"];
foreach (var seat in Seats)
{
var anim = meta.GetSeatAnimation(seat);
seat.Passenger?.AnimManager?.StopAnimation(anim.Code);
}
eagent.AnimManager.StopAnimation(meta.Code);
}
// Handle transition from swimming to walking
if (eagent.Swimming)
{
if (ForwardSpeed > 0) CurrentGait = ebg.Gaits["swim"];
else if (ForwardSpeed < 0) CurrentGait = ebg.Gaits["swimback"];
}
else if (wasSwimming)
{
if (ForwardSpeed > 0) CurrentGait = ebg.Gaits["walk"];
else if (ForwardSpeed < 0) CurrentGait = ebg.Gaits["walkback"];
}
wasSwimming = eagent.Swimming;
eagent.Controls.Backward = ForwardSpeed < 0;
eagent.Controls.Forward = ForwardSpeed >= 0;
eagent.Controls.Sprint = CurrentGait.IsSprint && ForwardSpeed > 0;
string nowTurnAnim =null;
if (ForwardSpeed >= 0)
{
if (AngularVelocity > 0.001)
{
nowTurnAnim = "turn-left";
}
else if (AngularVelocity < -0.001)
{
nowTurnAnim = "turn-right";
}
}
// This update fixes idle turn animation not stopping when entity has separate idle turn animations
if (nowTurnAnim != curTurnAnim)
{
if (curTurnAnim != null)
{
eagent.StopAnimation(curTurnAnim);
eagent.AnimManager.AnimationsDirty = true;
}
if (nowTurnAnim == null)
{
curTurnAnim = null;
}
else
{
var anim = (ForwardSpeed == 0 ? "idle-" : "") + nowTurnAnim;
curTurnAnim = anim;
eagent.StartAnimation(anim);
curMoveAnim = null;
}
}
else if (curMoveAnim == null && curControlMeta != null)
{
// Restart normal motion animation after a turn
eagent.AnimManager.StartAnimation(curControlMeta);
curMoveAnim = curControlMeta.Animation;
}
ControlMeta nowControlMeta;
bool doRiders = false;
shouldMove = ForwardSpeed != 0;
if (!shouldMove && !jumpNow)
{
if (curControlMeta != null) Stop();
curAnim = Controls[eagent.Swimming ? "swim" : "idle"].RiderAnim;
curAnimPassanger = Controls[eagent.Swimming ? "swim" : "idle"].GetPassengerAnim();
if (eagent.Swimming)
nowControlMeta = Controls["swim"];
else nowControlMeta = null;
}
else
{
nowControlMeta = Controls.FirstOrDefault(c => c.Key == CurrentGait.Code).Value;
nowControlMeta ??= Controls["idle"];
eagent.Controls.Jump = jumpNow;
if (jumpNow)
{
IsInMidJump = true;
jumpNow = false;
if (eagent.Properties.Client.Renderer is EntityShapeRenderer esr)
esr.LastJumpMs = capi.InWorldEllapsedMilliseconds;
nowControlMeta = Controls["jump"];
if (ForwardSpeed != 0) nowControlMeta.EaseOutSpeed = 30;
foreach (var seat in Seats)
{
if (seat.Passenger != Controller) continue; // Pillion passenger should not use jump animation
var anim = nowControlMeta.GetSeatAnimation(seat);
seat.Passenger?.AnimManager?.StartAnimation(anim);
}
EntityPlayer entityPlayer = entity as EntityPlayer;
IPlayer player = entityPlayer?.World.PlayerByUid(entityPlayer.PlayerUID);
entity.PlayEntitySound("jump", player, false);
}
else
{
doRiders = true;
}
}
StartAnimationsForControl(nowControlMeta, doRiders);
if (api.Side == EnumAppSide.Server)
{
eagent.Controls.Sprint = false; // Uh, why does the elk speed up 2x with this on?
}
}
private void StartAnimationsForControl(ControlMeta nowControlMeta, bool doRiders)
{
if (nowControlMeta != curControlMeta)
{
if (curControlMeta == null)
{
if (nowControlMeta.Code != "jump")
{
eagent.StopAnimation(Controls["idle"].Code);
Controller?.StopAnimation(Controls["idle"].RiderAnim.Code);
eagent.AnimManager.AnimationsDirty = true;
}
}
else if (curControlMeta.Code != "jump")
{
eagent.StopAnimation(curControlMeta.Code);
eagent.AnimManager.AnimationsDirty = true;
}
curControlMeta = nowControlMeta;
if (api.Side == EnumAppSide.Client) nowControlMeta.ClientSide = true;
eagent.AnimManager.StartAnimation(nowControlMeta);
curMoveAnim = nowControlMeta.Animation;
}
if (doRiders)
{
curAnim = nowControlMeta.RiderAnim;
curAnimPassanger = nowControlMeta.GetPassengerAnim();
}
}
protected void DoSaddleBreak()
{
foreach (var seat in Seats)
{
if (seat?.Passenger == null) continue;
var eagent = seat.Passenger as EntityAgent;
if (api.World.Rand.NextDouble() < 0.5) eagent.ReceiveDamage(new DamageSource()
{
CauseEntity = entity,
DamageTier = 1,
Source = EnumDamageSource.Entity,
SourcePos = this.Position.XYZ,
Type = EnumDamageType.BluntAttack
}, 1 + api.World.Rand.Next(8) / 4f);
eagent.TryUnmount();
}
jumpNow = false;
Stop();
if (api.World.Calendar.TotalDays - LastSaddleBreakTotalDays > saddleBreakDayInterval)
{
RemainingSaddleBreaks--;
LastSaddleBreakTotalDays = api.World.Calendar.TotalDays;
if (RemainingSaddleBreaks <= 0)
{
ConvertToTamedAnimal();
return;
}
}
}
private void ConvertToTamedAnimal()
{
var api = entity.World.Api;
if (api.Side == EnumAppSide.Client) return;
var etype = api.World.GetEntityType(AssetLocation.Create(tamedEntityCode, entity.Code.Domain));
if (etype == null) return;
var entitytamed = api.World.ClassRegistry.CreateEntity(etype);
entitytamed.ServerPos.SetFrom(entity.Pos);
entitytamed.WatchedAttributes = (SyncedTreeAttribute)entity.WatchedAttributes.Clone();
entity.Die(EnumDespawnReason.Expire);
api.World.SpawnEntity(entitytamed);
}
public override void OnEntityDeath(DamageSource damageSourceForDeath)
{
foreach (var seat in Seats)
{
(seat?.Entity as EntityAgent)?.TryUnmount();
}
base.OnEntityDeath(damageSourceForDeath);
}
public void Stop()
{
gaitSound?.Stop();
ebg.SetIdle();
CurrentGait = ebg.IdleGait;
ForwardSpeed = 0;
eagent.Controls.StopAllMovement();
eagent.Controls.WalkVector.Set(0, 0, 0);
eagent.Controls.FlyVector.Set(0,0,0);
if (curTurnAnim != null)
{
eagent.StopAnimation(curTurnAnim);
eagent.AnimManager.AnimationsDirty = true;
curTurnAnim = null;
}
shouldMove = false;
if (curControlMeta != null && curControlMeta.Code != "jump")
{
eagent.StopAnimation(curControlMeta.Code);
eagent.AnimManager.AnimationsDirty = true;
}
curControlMeta = null;
curMoveAnim = null;
eagent.StartAnimation("idle");
}
public override void OnGameTick(float dt)
{
CurrentGait ??= ebg.CurrentGait; // Initialize CurrentGait if necessary
if (api.Side == EnumAppSide.Server)
{
updateAngleAndMotion(dt);
}
updateRidingState();
if (!AnyMounted() && eagent.Controls.TriesToMove && eagent?.MountedOn != null)
{
eagent.TryUnmount();
}
if (shouldMove)
{
// Adjust move speed based based on gait and control meta
var curMoveSpeed = curControlMeta.MoveSpeed > 0
? curControlMeta.MoveSpeed
: CurrentGait.MoveSpeed * curControlMeta.MoveSpeedMultiplier;
move(dt, eagent.Controls, curMoveSpeed);
} else
{
if (entity.Swimming) eagent.Controls.FlyVector.Y = 0.2;
}
updateSoundState(dt);
if (api.Side == EnumAppSide.Server) ebg.CurrentGait = CurrentGait;
}
float notOnGroundAccum;
private void updateSoundState(float dt)
{
if (capi == null) return;
if (eagent.OnGround) notOnGroundAccum = 0;
else notOnGroundAccum += dt;
gaitSound?.SetPosition((float)entity.Pos.X, (float)entity.Pos.Y, (float)entity.Pos.Z);
if (Controls.TryGetValue(CurrentGait.Code, out ControlMeta controlMeta))
{
var gaitMeta = CurrentGait;
curSoundCode = eagent.Swimming || notOnGroundAccum > 0.2 ? null : gaitMeta.Sound;
bool nowChange = curSoundCode != prevSoundCode;
if (nowChange)
{
gaitSound?.Stop();
gaitSound?.Dispose();
prevSoundCode = curSoundCode;
if (curSoundCode is null) return;
gaitSound = capi.World.LoadSound(new SoundParams()
{
Location = gaitMeta.Sound.Clone().WithPathPrefix("sounds/"),
DisposeOnFinish = false,
Position = entity.Pos.XYZ.ToVec3f(),
ShouldLoop = true
});
gaitSound?.Start();
}
}
}
private void move(float dt, EntityControls controls, float nowMoveSpeed)
{
double cosYaw = Math.Cos(entity.Pos.Yaw);
double sinYaw = Math.Sin(entity.Pos.Yaw);
controls.WalkVector.Set(sinYaw, 0, cosYaw);
controls.WalkVector.Mul(nowMoveSpeed * GlobalConstants.OverallSpeedMultiplier * ForwardSpeed);
// Make it walk along the wall, but not walk into the wall, which causes it to climb
if (entity.Properties.RotateModelOnClimb && controls.IsClimbing && entity.ClimbingOnFace != null && entity.Alive)
{
BlockFacing facing = entity.ClimbingOnFace;
if (Math.Sign(facing.Normali.X) == Math.Sign(controls.WalkVector.X))
{
controls.WalkVector.X = 0;
}
if (Math.Sign(facing.Normali.Z) == Math.Sign(controls.WalkVector.Z))
{
controls.WalkVector.Z = 0;
}
}
if (entity.Swimming)
{
controls.FlyVector.Set(controls.WalkVector);
Vec3d pos = entity.Pos.XYZ;
Block inblock = entity.World.BlockAccessor.GetBlockRaw((int)pos.X, (int)(pos.Y), (int)pos.Z, BlockLayersAccess.Fluid);
Block aboveblock = entity.World.BlockAccessor.GetBlockRaw((int)pos.X, (int)(pos.Y + 1), (int)pos.Z, BlockLayersAccess.Fluid);
float waterY = (int)pos.Y + inblock.LiquidLevel / 8f + (aboveblock.IsLiquid() ? 9 / 8f : 0);
float bottomSubmergedness = waterY - (float)pos.Y;
// 0 = at swim line
// 1 = completely submerged
float swimlineSubmergedness = GameMath.Clamp(bottomSubmergedness - ((float)entity.SwimmingOffsetY), 0, 1);
swimlineSubmergedness = Math.Min(1, swimlineSubmergedness + 0.075f);
controls.FlyVector.Y = GameMath.Clamp(controls.FlyVector.Y, 0.002f, 0.004f) * swimlineSubmergedness*3;
if (entity.CollidedHorizontally)
{
controls.FlyVector.Y = 0.05f;
}
eagent.Pos.Motion.Y += (swimlineSubmergedness-0.1)/300.0;
}
}
public override string PropertyName() => "rideable";
public void Dispose() { }
public void DidUnmount(EntityAgent entityAgent)
{
Stop();
LastDismountTotalHours = entity.World.Calendar.TotalHours;
foreach (var meta in Controls.Values)
{
if (meta.RiderAnim?.Animation != null)
{
entityAgent.StopAnimation(meta.RiderAnim.Animation);
eagent.AnimManager.AnimationsDirty = true;
}
}
if (eagent.Swimming)
{
eagent.StartAnimation("swim");
}
}
long mountedTotalMs;
public void DidMount(EntityAgent entityAgent)
{
updateControlScheme();
mountedTotalMs = api.World.ElapsedMilliseconds;
}
public override bool ToleratesDamageFrom(Entity eOther, ref EnumHandling handling)
{
if (eOther != null && Controller == eOther)
{
handling = EnumHandling.PreventDefault;
return true;
}
return false;
}
public override void GetInfoText(StringBuilder infotext)
{
if (RemainingSaddleBreaks > 0)
{
infotext.AppendLine(Lang.Get("{0} saddle breaks required every {1} days to fully tame.", RemainingSaddleBreaks, saddleBreakDayInterval));
}
base.GetInfoText(infotext);
}
}
public class ElkAnimationManager : AnimationManager
{
public string animAppendix = "-antlers";
public override void ResetAnimation(string animCode)
{
base.ResetAnimation(animCode);
base.ResetAnimation(animCode + animAppendix);
}
public override void StopAnimation(string code)
{
base.StopAnimation(code);
base.StopAnimation(code + animAppendix);
AnimationsDirty = true;
}
public override bool StartAnimation(AnimationMetaData animdata)
{
return base.StartAnimation(animdata);
}
}
public class ControlMeta : AnimationMetaData
{
public float MoveSpeedMultiplier; // Multiplied by GaitMeta MoveSpeed to get rideable speed
public float MoveSpeed; // Overrides GaitMeta MoveSpeed
public AnimationMetaData RiderAnim;
public AnimationMetaData PassengerAnim;
/// <summary>
/// If we are a passenger try to get the PassengerAnim if it exists else default to RiderAnim
/// </summary>
/// <returns></returns>
public AnimationMetaData GetSeatAnimation(IMountableSeat seat)
{
return !seat.CanControl && PassengerAnim != null ? PassengerAnim : RiderAnim;
}
/// <summary>
/// Return a PassengerAnim if it exists else return the RiderAnim
/// </summary>
/// <returns></returns>
public AnimationMetaData GetPassengerAnim()
{
return PassengerAnim != null ? PassengerAnim : RiderAnim;
}
}
}
| 412 | 0.9438 | 1 | 0.9438 | game-dev | MEDIA | 0.971613 | game-dev | 0.756519 | 1 | 0.756519 |
Citadel-Station-13/Citadel-Station-13 | 9,425 | modular_citadel/code/modules/reagents/chemistry/reagents/astrogen.dm | /*
////////////////////////////////////////////////////////////////////////////////////////////////////
// ASTROGEN
///////////////////////////////////////////////////////////////////////////////////////////////////
More fun chems!
When you take it, it spawns a ghost that the player controls. (No access to deadchat)
This ghost moves pretty quickly and is mostly invisible, but is still visible for people with eyes.
When it's out of your system, you return back to yourself. It doesn't last long and metabolism of the chem is exponential.
Addiction is particularlly brutal, it slowly turns you invisible with flavour text, then kills you at a low enough alpha. (i've also added something to prevent geneticists speeding this up)
There's afairly major catch regarding the death though. I'm not gonna say here, go read the code, it explains it and puts my comments on it in context. I know that anyone reading it without understanding it is going to freak out so, this is my attempt to get you to read it and understand it.
I'd like to point out from my calculations it'll take about 60-80 minutes to die this way too. Plenty of time to visit chem and ask for some pills to quench your addiction.
*/
/datum/reagent/fermi/astral // Gives you the ability to astral project for a moment!
name = "Astrogen"
description = "An opalescent murky liquid that is said to distort your soul from your being."
color = "#A080H4" // rgb: , 0, 255
taste_description = "your mind"
metabolization_rate = 0//Removal is exponential, see code
overdose_threshold = 20
addiction_threshold = 24.5
addiction_stage1_end = 9999//Should never end. There is no escape make your time
var/mob/living/carbon/origin
var/mob/living/simple_animal/astral/G = null
var/datum/mind/originalmind
var/antiGenetics = 255
var/sleepytime = 0
inverse_chem_val = 0.25
can_synth = FALSE
var/datum/action/chem/astral/AS = new/datum/action/chem/astral()
value = REAGENT_VALUE_AMAZING
/datum/action/chem/astral
name = "Return to body"
var/mob/living/carbon/origin
var/datum/mind/originalmind
/datum/action/chem/astral/Trigger()
if(origin.mind && origin.mind != originalmind)
to_chat(originalmind.current, "<span class='warning'><b><i>There's a foreign presence in your body blocking your return!</b></i></span>")
return ..()
if(origin.reagents.has_reagent(/datum/reagent/fermi/astral) )
var/datum/reagent/fermi/astral/As = locate(/datum/reagent/fermi/astral) in origin.reagents.reagent_list
if(As.current_cycle < 10)
to_chat(originalmind.current, "<span class='warning'><b><i>The intensity of the astrogen in your body is too much allow you to return to yourself yet!</b></i></span>")
return ..()
originalmind.transfer_to(origin)
if(origin.mind == originalmind)
qdel(src)
/datum/reagent/fermi/astral/reaction_turf(turf/T, reac_volume)
if(isplatingturf(T) || istype(T, /turf/open/floor/plasteel))
var/turf/open/floor/F = T
F.PlaceOnTop(/turf/open/floor/fakespace, flags = CHANGETURF_INHERIT_AIR)
..()
/datum/reagent/fermi/astral/reaction_obj(obj/O, reac_volume)
if(istype(O, /obj/item/bedsheet))
new /obj/item/bedsheet/cosmos(get_turf(O))
qdel(O)
..()
/datum/reagent/fermi/astral/on_mob_life(mob/living/carbon/M) // Gives you the ability to astral project for a moment!
M.alpha = 255
if(current_cycle == 0)
originalmind = M.mind
log_reagent("FERMICHEM: [M] ckey: [M.key] became an astral ghost")
origin = M
if (G == null)
G = new(get_turf(M.loc))
G.name = "[M]'s astral projection"
//var/datum/action/chem/astral/AS = new(G)
AS.Grant(G)
AS.origin = M
AS.originalmind = originalmind
if(M.mind)
M.mind.transfer_to(G)
SSblackbox.record_feedback("tally", "fermi_chem", 1, "Astral projections")
//INSURANCE
M.apply_status_effect(/datum/status_effect/chem/astral_insurance)
var/datum/status_effect/chem/astral_insurance/AI = M.has_status_effect(/datum/status_effect/chem/astral_insurance)
AI.original = M
AI.originalmind = M.mind
if(overdosed)
if(prob(50))
to_chat(G, "<span class='warning'>The high conentration of Astrogen in your blood causes you to lapse your concentration for a moment, bringing your projection back to yourself!</b></span>")
do_teleport(G, M.loc)
metabolization_rate = current_cycle/10 //exponential
sleepytime+=5
if(G)//This is a mess because of how slow qdel is, so this is all to stop runtimes.
if(G.mind)
if(G.stat == DEAD || G.pseudo_death == TRUE)
G.mind.transfer_to(M)
qdel(G)
..()
/datum/reagent/fermi/astral/on_mob_delete(mob/living/carbon/M)
if(!(G?.mind))
if(!G)
qdel(G)
return ..()
if(M.mind) //Just in case someone else is inside of you, it makes them a ghost and should hopefully bring them home at the end.
var/mob/living/simple_animal/astral/G2 = new(get_turf(M))
M.mind.transfer_to(G2)
to_chat(G2, "<span class='warning'>[M]'s conciousness snaps back to them as [M.p_their()] astrogen runs out, kicking your projected mind out!'</b></span>")
log_reagent("FERMICHEM: [G2.mind.name] has been booted out of [M] as their original mind came back as the Astrogen reagent ran out!")
G.mind.transfer_to(origin)
qdel(G)
if(overdosed)
to_chat(M, "<span class='warning'>The high volume of astrogen you just took causes you to black out momentarily as your mind snaps back to your body.</b></span>")
M.Sleeping(sleepytime, 0)
antiGenetics = 255
log_reagent("FERMICHEM: [M] has astrally returned to their body!")
if(M.mind && M.mind == originalmind)
M.remove_status_effect(/datum/status_effect/chem/astral_insurance)
return ..()
//Okay so, this might seem a bit too good, but my counterargument is that it'll likely take all round to eventually kill you this way, then you have to be revived without a body. It takes approximately 50-80 minutes to die from this.
/datum/reagent/fermi/astral/addiction_act_stage1(mob/living/carbon/M)
if(addiction_stage < 2)
antiGenetics = 255
M.alpha = 255 //Antigenetics is to do with stopping geneticists from turning people invisible to kill them.
if(prob(75))
M.alpha--
antiGenetics--
switch(antiGenetics)
if(245)
to_chat(M, "<span class='warning'>You notice your body starting to disappear, maybe you took too much Astrogen...?</b></span>")
M.alpha--
antiGenetics--
log_reagent("FERMICHEM: [M] ckey: [M.key] has become addicted to Astrogen")
if(220)
to_chat(M, "<span class='notice'>Your addiction is only getting worse as your body disappears. Maybe you should get some more, and fast?</b></span>")
M.alpha--
antiGenetics--
if(200)
to_chat(M, "<span class='notice'>You feel a substantial part of your soul flake off into the ethereal world, rendering yourself unclonable.</b></span>")
M.alpha--
antiGenetics--
ADD_TRAIT(M, TRAIT_NOCLONE, "astral") //So you can't scan yourself, then die, to metacomm. You can only use your memories if you come back as something else.
M.hellbound = TRUE
if(180)
to_chat(M, "<span class='notice'>You feel fear build up in yourself as more and more of your body and consciousness begins to fade.</b></span>")
M.alpha--
antiGenetics--
if(120)
to_chat(M, "<span class='notice'>As you lose more and more of yourself, you start to think that maybe shedding your mortality isn't too bad.</b></span>")
M.alpha--
antiGenetics--
if(80)
to_chat(M, "<span class='notice'>You feel a thrill shoot through your body as what's left of your mind contemplates your forthcoming oblivion.</b></span>")
M.alpha--
antiGenetics--
if(45)
to_chat(M, "<span class='warning'>The last vestiges of your mind eagerly await your imminent annihilation.</b></span>")
M.alpha--
antiGenetics--
if(-INFINITY to 30)
to_chat(M, "<span class='warning'>Your body disperses from existence, as you become one with the universe.</b></span>")
to_chat(M, "<span class='userdanger'>As your body disappears, your consciousness doesn't. Should you find a way back into the mortal coil, your memories of your previous life remain with you. (At the cost of staying in character while dead. Failure to do this may get you banned from this chem. You are still obligated to follow your directives if you play a midround antag, you do not remember the afterlife IC)</span>")//Legalised IC OOK? I have a suspicion this won't make it past the review. At least it'll be presented as a neat idea! If this is unacceptable how about the player can retain living memories across lives if they die in this way only.
deadchat_broadcast(" has become one with the universe, meaning that their IC conciousness is continuous in a new life. If they find a way back to life, they are allowed to remember their previous life. Be careful what you say. If they abuse this, bwoink the FUCK outta them.</span>", "<span class='warning'>[M]", M, message_type=DEADCHAT_ANNOUNCEMENT)
M.visible_message("[M] suddenly disappears, their body evaporating from existence, freeing [M] from their mortal coil.")
message_admins("[M] (ckey: [M.ckey]) has become one with the universe, and have continuous memories thoughout their lives should they find a way to come back to life (such as an inteligence potion, midround antag, ghost role).")
SSblackbox.record_feedback("tally", "fermi_chem", 1, "Astral obliterations")
qdel(M) //Approx 60minutes till death from initial addiction
log_reagent("FERMICHEM: [M] ckey: [M.key] has been obliterated from Astrogen addiction")
..()
| 412 | 0.885963 | 1 | 0.885963 | game-dev | MEDIA | 0.973936 | game-dev | 0.910827 | 1 | 0.910827 |
alrieckert/lazarus | 9,228 | lcl/interfaces/fpgui/fpguiwsmenus.pp | { $Id: FpGuiwsmenus.pp 5319 2004-03-17 20:11:29Z marc $}
{
*****************************************************************************
* FpGuiWSMenus.pp *
* ------------ *
* *
* *
*****************************************************************************
*****************************************************************************
This file is part of the Lazarus Component Library (LCL)
See the file COPYING.LCL, included in this distribution,
for details about the license.
*****************************************************************************
}
unit FpGuiWSMenus;
{$mode delphi}{$H+}
interface
uses
// LCL
SysUtils, Menus, Forms,
// widgetset
WSMenus, WSLCLClasses, LCLType, fpguiobjects, fpguiwsprivate,
// interface
fpg_base, fpg_main, fpg_menu;
type
{ TFpGuiWSMenuItem }
TFpGuiWSMenuItem = class(TWSMenuItem)
private
protected
published
class procedure AttachMenu(const AMenuItem: TMenuItem); override;
class function CreateHandle(const AMenuItem: TMenuItem): HMENU; override;
class procedure DestroyHandle(const AMenuItem: TMenuItem); override;
class procedure SetCaption(const AMenuItem: TMenuItem; const ACaption: string); override;
// class procedure SetShortCut(const AMenuItem: TMenuItem; const ShortCutK1, ShortCutK2: TShortCut); override;
class procedure SetVisible(const AMenuItem: TMenuItem; const Visible: boolean); override;
class function SetCheck(const AMenuItem: TMenuItem; const Checked: boolean): boolean; override;
class function SetEnable(const AMenuItem: TMenuItem; const Enabled: boolean): boolean; override;
// class function SetRadioItem(const AMenuItem: TMenuItem; const RadioItem: boolean): boolean; override;
// class function SetRightJustify(const AMenuItem: TMenuItem; const Justified: boolean): boolean; override;
// class procedure UpdateMenuIcon(const AMenuItem: TMenuItem; const HasIcon: Boolean; const AIcon: TBitmap); override;
end;
{ TFpGuiWSMenu }
TFpGuiWSMenu = class(TWSMenu)
private
protected
published
class function CreateHandle(const AMenu: TMenu): HMENU; override;
// class procedure SetBiDiMode(const AMenu: TMenu; UseRightToLeftAlign, UseRightToLeftReading : Boolean); override;
end;
{ TFpGuiWSMainMenu }
TFpGuiWSMainMenu = class(TWSMainMenu)
private
protected
public
end;
{ TFpGuiWSPopupMenu }
TFpGuiWSPopupMenu = class(TWSPopupMenu)
private
protected
published
class procedure Popup(const APopupMenu: TPopupMenu; const X, Y: integer); override;
end;
implementation
uses
LCLMessageGlue;
{ TFpGuiWSMenuItem }
class procedure TFpGuiWSMenuItem.AttachMenu(const AMenuItem: TMenuItem);
begin
end;
{------------------------------------------------------------------------------
Function: TFpGuiWSMenuItem.CreateHandle
Params: None
Returns: Nothing
Creates a Menu Item
------------------------------------------------------------------------------}
class function TFpGuiWSMenuItem.CreateHandle(const AMenuItem: TMenuItem): HMENU;
var
Menu: TFPGUIPrivateMenuItem;
AMenuName: string;
// hotkeydef: string;
{ Possible parents }
ParentPrivateItem: TFPGUIPrivateMenuItem;
ParentMenuBar: TfpgMenuBar;
ParentPrivatePopUp: TFPGUIPrivatePopUpMenu;
begin
{$ifdef VerboseFPGUIIntf}
WriteLn('trace:> [TFPGuiWSMenuItem.CreateHandle] Caption: ', AMenuItem.Caption,
' Subitems: ' + IntToStr(AMenuItem.Count));
Write('trace:< [TFPGuiWSMenuItem.CreateHandle]');
{$endif}
{------------------------------------------------------------------------------
Set's default values for variables used at several places bellow
------------------------------------------------------------------------------}
AMenuName := AMenuItem.Caption;
Menu := nil;
{------------------------------------------------------------------------------
This case should not happen. A menu item must have a parent, but it seams LCL
will sometimes create a menu item prior to creating it's parent.
So, if we arrive here, we must create this item as if it was a TMenu
------------------------------------------------------------------------------}
if (not AMenuItem.HasParent) then
begin
{$ifdef VerboseFPGUIIntf}
Write(' Parent: Menu without parent');
{$endif}
// Result := TQtWSMenu.CreateHandle(AMenuItem.GetParentMenu);
end
{------------------------------------------------------------------------------
If the parent has no parent, then this item is directly owned by a TMenu
In this case we have to detect if the parent is a TMainMenu or a TPopUpMenu
because TMainMenu uses the special Handle TfpgMenuBar
------------------------------------------------------------------------------}
else
if AMenuItem.Parent.HasParent then begin
{------------------------------------------------------------------------------
If the parent has a parent, then that item's Handle is necessarely a TFPGUIPrivateMenuItem
------------------------------------------------------------------------------}
Menu := TFPGUIPrivateMenuItem.Create;
Menu.LCLMenuItem := AMenuItem;
ParentPrivateItem := TFPGUIPrivateMenuItem(AMenuItem.Parent.Handle);
Menu.MenuItem := ParentPrivateItem.MenuItem.SubMenu.AddMenuItem(AMenuName, '', Menu.HandleOnClick);
Result := HMENU(Menu);
end else if (AMenuItem.GetParentMenu is TMainMenu) then begin
Menu := TFPGUIPrivateMenuItem.Create;
Menu.LCLMenuItem := AMenuItem;
ParentMenuBar := TfpgMenuBar(AMenuItem.GetParentMenu.Handle);
Menu.MenuItem := ParentMenuBar.AddMenuItem(AMenuName, Menu.HandleOnClick);
Result := HMENU(Menu);
end else begin
Menu := TFPGUIPrivateMenuItem.Create;
Menu.LCLMenuItem := AMenuItem;
ParentPrivatePopUp := TFPGUIPrivatePopUpMenu(AMenuItem.GetParentMenu.Handle);
Menu.MenuItem := ParentPrivatePopUp.PopUpMenu.AddMenuItem(AMenuName,'',Menu.HandleOnClick);
Result := HMENU(Menu);
end;
{------------------------------------------------------------------------------
If the menuitem has submenus, create a popupmenu for the submenu
------------------------------------------------------------------------------}
if AMenuItem.Count > 0 then
begin
Menu.MenuItem.SubMenu := TfpgPopupMenu.Create(Menu.MenuItem);
end;
{$ifdef VerboseFPGUIIntf}
WriteLn(' Result: ', IntToStr(Result));
{$endif}
end;
class procedure TFpGuiWSMenuItem.DestroyHandle(const AMenuItem: TMenuItem);
begin
TFPGUIPrivateMenuItem(AMenuItem.Handle).Free;
AMenuItem.Handle:=0;
end;
class procedure TFpGuiWSMenuItem.SetCaption(const AMenuItem: TMenuItem;
const ACaption: string);
var
APrivate: TfpgMenuItem;
begin
APrivate:=TfpgMenuItem(AMenuItem.Handle);
APrivate.Text:=ACaption;
end;
class procedure TFpGuiWSMenuItem.SetVisible(const AMenuItem: TMenuItem;
const Visible: boolean);
var
APrivate: TfpgMenuItem;
begin
APrivate:=TfpgMenuItem(AMenuItem.Handle);
APrivate.Visible:=Visible;
end;
class function TFpGuiWSMenuItem.SetCheck(const AMenuItem: TMenuItem;
const Checked: boolean): boolean;
begin
Result:=false; //Default by now
end;
class function TFpGuiWSMenuItem.SetEnable(const AMenuItem: TMenuItem;
const Enabled: boolean): boolean;
begin
Result:=false; //Default by now
end;
{ TFpGuiWSMenu }
class function TFpGuiWSMenu.CreateHandle(const AMenu: TMenu): HMENU;
var
MenuBar: TfpgMenuBar;
Menu: TFPGUIPrivatePopUpMenu;
msg: TfpgMessageParams;
begin
{------------------------------------------------------------------------------
If the menu is a main menu, there is no need to create a handle for it.
It's already created on the window
------------------------------------------------------------------------------}
if (AMenu is TMainMenu) and (AMenu.Owner is TCustomForm) then
begin
MenuBar := TFPGUIPrivateWindow(TCustomForm(AMenu.Owner).Handle).MenuBar;
MenuBar.Visible := True;
MenuBar.Align := alTop;
Result := HMENU(MenuBar);
//Notify LCL to repaint because MainMenu changes NCBorders
msg.rect:=MenuBar.Parent.GetBoundsRect;
fpgSendMessage(MenuBar,MenuBar.Parent,FPGM_RESIZE,msg);
end
{------------------------------------------------------------------------------
The menu is a popup menu
------------------------------------------------------------------------------}
else if (AMenu is TPopUpMenu) then
begin
Menu := TFPGUIPrivatePopUpMenu.Create(TPopUpMenu(AMenu), AMenu.Items);
Result := HMENU(Menu);
end
else
Result := HMENU(0);
{$ifdef VerboseFPGUIIntf}
Write('[TFpGuiWSMenu.CreateHandle] ');
if (AMenu is TMainMenu) then Write('IsMainMenu ');
WriteLn(' Handle: ', IntToStr(Result), ' Name: ', AMenu.Name);
{$endif}
end;
{ TFpGuiWSPopupMenu }
class procedure TFpGuiWSPopupMenu.Popup(const APopupMenu: TPopupMenu; const X, Y: integer);
begin
TFPGUIPrivatePopUpMenu(APopUpMenu.Handle).PopUp(X, Y);
end;
end.
| 412 | 0.810578 | 1 | 0.810578 | game-dev | MEDIA | 0.730652 | game-dev | 0.936283 | 1 | 0.936283 |
KoffeinFlummi/AGM | 1,297 | AGM_Logistics/functions/fn_openMagazineMenu.sqf | /*
Name: AGM_Logistics_fnc_openMagazineMenu
Author: Garth de Wet (LH)
Description:
Opens the UI for selecting magazines to load into vehicle.
Parameters:
0: OBJECT - vehicle
Returns:
Nothing
Example:
[AGM_Interaction_Target] call AGM_Logistics_fnc_openMagazineMenu;
*/
private ["_vehicle","_magazines"];
AGM_Logistics_targetVehicle = _this select 0;
_magazines = [player, AGM_Logistics_targetVehicle] call AGM_Logistics_fnc_getLoadableMagazines;
_listed = [];
_actions = [localize "STR_AGM_Logistics_MagazineMenu", localize "STR_AGM_Logistics_LoadItem"] call AGM_Interaction_fnc_prepareSelectMenu;
{
if (!(_x in _listed) && {[AGM_Logistics_targetVehicle, _x] call AGM_Logistics_fnc_canLoadMagazine}) then {
_class = ConfigFile >> "CfgMagazines" >> _x;
_actions = [
_actions,
getText (_class >> "DisplayName"),
getText (_class >> "picture"),
_x
] call AGM_Interaction_fnc_AddSelectableItem;
_listed pushBack _x;
};
} count _magazines;
[
_actions,
{
call AGM_Interaction_fnc_hideMenu;
[player, AGM_Logistics_targetVehicle, _this] call AGM_Logistics_fnc_loadMagazine;
},
{if !(profileNamespace getVariable ["AGM_Interaction_AutoCloseMenu", false]) then {"Default" call AGM_Interaction_fnc_openMenu};}
] call AGM_Interaction_fnc_openSelectMenu;
| 412 | 0.610421 | 1 | 0.610421 | game-dev | MEDIA | 0.433278 | game-dev | 0.749494 | 1 | 0.749494 |
Impostor/Impostor | 2,520 | src/Impostor.Server/Net/State/ClientPlayer.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Impostor.Api.Net;
using Impostor.Api.Net.Inner;
using Impostor.Api.Unity;
using Impostor.Server.Net.Inner.Objects;
using Microsoft.Extensions.Logging;
namespace Impostor.Server.Net.State
{
internal partial class ClientPlayer : IClientPlayer
{
private readonly ILogger<ClientPlayer> _logger;
private readonly Timer _spawnTimeout;
private readonly int _spawnTimeoutTime;
public ClientPlayer(ILogger<ClientPlayer> logger, ClientBase client, Game game, int timeOutTime)
{
_logger = logger;
_spawnTimeout = new Timer(RunSpawnTimeout!, null, -1, -1);
_spawnTimeoutTime = timeOutTime;
Game = game;
Client = client;
Limbo = LimboStates.PreSpawn;
}
public ClientBase Client { get; }
public Game Game { get; }
/// <inheritdoc />
public LimboStates Limbo { get; set; }
public InnerPlayerControl? Character { get; internal set; }
public bool IsHost => Game?.Host == this;
public string? Scene { get; internal set; }
public RuntimePlatform? Platform { get; internal set; }
public void InitializeSpawnTimeout()
{
_spawnTimeout.Change(_spawnTimeoutTime, -1);
}
public void DisableSpawnTimeout()
{
_spawnTimeout.Change(-1, -1);
}
/// <inheritdoc />
public bool IsOwner(IInnerNetObject netObject)
{
return Client.Id == netObject.OwnerId;
}
/// <inheritdoc />
public ValueTask KickAsync()
{
return Game.HandleKickPlayer(Client.Id, false);
}
/// <inheritdoc />
public ValueTask BanAsync()
{
return Game.HandleKickPlayer(Client.Id, true);
}
private async void RunSpawnTimeout(object state)
{
try
{
if (Character == null)
{
_logger.LogInformation("{0} - Player {1} spawn timed out, kicking.", Game.Code, Client.Id);
await KickAsync();
}
}
catch (Exception e)
{
_logger.LogError(e, "Exception caught while kicking player for spawn timeout.");
}
finally
{
await _spawnTimeout.DisposeAsync();
}
}
}
}
| 412 | 0.848017 | 1 | 0.848017 | game-dev | MEDIA | 0.575267 | game-dev | 0.878332 | 1 | 0.878332 |
b1inkie/dst-api | 16,926 | scripts_619045/widgets/playerlist.lua | local Widget = require "widgets/widget"
local Text = require "widgets/text"
local ImageButton = require "widgets/imagebutton"
local LobbyChatQueue = require "widgets/lobbychatqueue"
local PlayerBadge = require "widgets/playerbadge"
local ScrollableList = require "widgets/scrollablelist"
local TEMPLATES = require "widgets/templates"
local VOICE_MUTE_COLOUR = { 242 / 255, 99 / 255, 99 / 255, 255 / 255 }
local VOICE_ACTIVE_COLOUR = { 99 / 255, 242 / 255, 99 / 255, 255 / 255 }
local VOICE_IDLE_COLOUR = { 1, 1, 1, 1 }
local function GetCharacterPrefab(data)
if data == nil then
return ""
end
if data.prefab and data.prefab ~= "" then
return data.prefab
end
if data.lobbycharacter and data.lobbycharacter ~= "" then
return data.lobbycharacter
end
return ""
end
local function doButtonFocusHookups(playerListing, nextWidgets)
local rightFocusMoveSet = false
if playerListing.mute:IsVisible() then
playerListing.mute:SetFocusChangeDir(MOVE_LEFT, playerListing.viewprofile)
playerListing.mute:SetFocusChangeDir(MOVE_RIGHT, nextWidgets.right)
playerListing.mute:SetFocusChangeDir(MOVE_DOWN, nextWidgets.down)
rightFocusMoveSet = true
playerListing.focus_forward = playerListing.mute
end
if playerListing.viewprofile:IsVisible() then
if playerListing.mute:IsVisible() then
playerListing.viewprofile:SetFocusChangeDir(MOVE_RIGHT, playerListing.mute)
else
playerListing.viewprofile:SetFocusChangeDir(MOVE_RIGHT, nextWidgets.right)
end
rightFocusMoveSet = true
playerListing.focus_forward:SetFocusChangeDir(MOVE_DOWN, nextWidgets.down)
playerListing.focus_forward = playerListing.viewprofile
end
if not rightFocusMoveSet then
playerListing:SetFocusChangeDir(MOVE_RIGHT, nextWidgets.right)
end
playerListing:SetFocusChangeDir(MOVE_DOWN, nextWidgets.down)
end
local function listingConstructor(v, i, parent, nextWidgets)
local playerListing = parent:AddChild(Widget("playerListing"))
playerListing:SetPosition(5,0)
local empty = v == nil or next(v) == nil
playerListing.userid = not empty and v.userid or nil
local nudge_x = -5
local name_badge_nudge_x = 15
playerListing.bg = playerListing:AddChild(Image("images/ui.xml", "blank.tex"))
playerListing.bg:SetPosition(-5+nudge_x+name_badge_nudge_x, 0)
playerListing.bg:ScaleToSize(186,34)
if empty then
playerListing.bg:Hide()
end
playerListing.highlight = playerListing:AddChild(Image("images/scoreboard.xml", "row_short_goldoutline.tex"))
playerListing.highlight:SetPosition(8+nudge_x+name_badge_nudge_x, 0)
playerListing.highlight:ScaleToSize(183,50)
playerListing.highlight:Hide()
playerListing.characterBadge = nil
if empty then
playerListing.characterBadge = playerListing:AddChild(PlayerBadge("", DEFAULT_PLAYER_COLOUR, false, 0))
playerListing.characterBadge:Hide()
else
--print("player data is ")
--dumptable(v)
playerListing.characterBadge = playerListing:AddChild(PlayerBadge(GetCharacterPrefab(v), v.colour or DEFAULT_PLAYER_COLOUR, v.performance ~= nil, v.userflags or 0))
end
playerListing.characterBadge:SetScale(.45)
playerListing.characterBadge:SetPosition(-77+nudge_x+name_badge_nudge_x,0,0)
playerListing.adminBadge = playerListing:AddChild(ImageButton("images/avatars.xml", "avatar_admin.tex", "avatar_admin.tex", "avatar_admin.tex", nil, nil, {1,1}, {0,0}))
playerListing.adminBadge:Disable()
playerListing.adminBadge:SetPosition(-89+nudge_x+name_badge_nudge_x,-10,0)
playerListing.adminBadge.image:SetScale(.18)
playerListing.adminBadge.scale_on_focus = false
playerListing.adminBadge:SetHoverText(STRINGS.UI.PLAYERSTATUSSCREEN.ADMIN, { font = NEWFONT_OUTLINE, offset_x = 0, offset_y = 30, colour = {1,1,1,1}})
if empty or not v.admin then
playerListing.adminBadge:Hide()
end
local colours = nil --GetAvailablePlayerColours()
playerListing.name = playerListing:AddChild(Text(TALKINGFONT, 24))
playerListing.name._align =
{
maxwidth = 100,
maxchars = 22,
x = -52 + nudge_x+name_badge_nudge_x,
y = -2.5,
}
playerListing.name.SetDisplayNameFromData = function(self, data)
local displayName = ""
if data ~= nil and next(data) ~= nil then
local base = self.parent
while base ~= nil do
if base.name == "PlayerList" then
displayName = base:GetDisplayName(data) or ""
break
end
base = base.parent
end
end
self:SetTruncatedString(displayName, self._align.maxwidth, self._align.maxchars, true)
local w, h = self:GetRegionSize()
self:SetPosition(self._align.x + w * .5, self._align.y, 0)
end
playerListing.name:SetDisplayNameFromData(v)
-- Testing only
if colours then
playerListing.name:SetColour(unpack(colours[math.random(#colours)]))
else
playerListing.name:SetColour(unpack(not empty and v.colour or DEFAULT_PLAYER_COLOUR))
end
local owner = TheNet:GetUserID()
playerListing.viewprofile = playerListing:AddChild(ImageButton("images/scoreboard.xml", "addfriend.tex", "addfriend.tex", "addfriend.tex", "addfriend.tex", nil, {1,1}, {0,0}))
playerListing.viewprofile:SetPosition(60+nudge_x,0,0)
playerListing.viewprofile:SetNormalScale(0.234)
playerListing.viewprofile:SetFocusScale(0.234*1.1)
playerListing.viewprofile:SetFocusSound("dontstarve/HUD/click_mouseover", nil, ClickMouseoverSoundReduction())
playerListing.viewprofile:SetHoverText(STRINGS.UI.PLAYERSTATUSSCREEN.VIEWPROFILE, { font = NEWFONT_OUTLINE, offset_x = 0, offset_y = 30, colour = {1,1,1,1}})
playerListing.viewprofile:SetOnClick(
function()
if v.netid ~= nil then
TheNet:ViewNetProfile(v.netid)
end
end)
if empty or v.userid == owner or not TheNet:IsNetIDPlatformValid(v.netid) then
playerListing.viewprofile:Hide()
end
playerListing.isMuted = v.muted == true
playerListing.mute = playerListing:AddChild(ImageButton("images/scoreboard.xml", "chat.tex", "chat.tex", "chat.tex", "chat.tex", nil, {1,1}, {0,0}))
playerListing.mute:SetPosition(85+nudge_x,0,0)
playerListing.mute:SetNormalScale(0.234)
playerListing.mute:SetFocusScale(0.234*1.1)
playerListing.mute:SetFocusSound("dontstarve/HUD/click_mouseover", nil, ClickMouseoverSoundReduction())
playerListing.mute:SetHoverText(STRINGS.UI.PLAYERSTATUSSCREEN.MUTE, { font = NEWFONT_OUTLINE, offset_x = 0, offset_y = 30, colour = {1,1,1,1}})
playerListing.mute.image.inst.OnUpdateVoice = function(inst)
inst.widget:SetTint(unpack(playerListing.userid ~= nil and TheNet:IsVoiceActive(playerListing.userid) and VOICE_ACTIVE_COLOUR or VOICE_IDLE_COLOUR))
end
playerListing.mute.image.inst.SetMuted = function(inst, muted)
if muted then
inst.widget:SetTint(unpack(VOICE_MUTE_COLOUR))
if inst._task ~= nil then
inst._task:Cancel()
inst._task = nil
end
else
inst:OnUpdateVoice()
if inst._task == nil then
inst._task = inst:DoPeriodicTask(1, inst.OnUpdateVoice)
end
end
end
playerListing.mute.image.inst.DisableMute = function(inst)
inst.widget:SetTint(unpack(VOICE_IDLE_COLOUR))
if inst._task ~= nil then
inst._task:Cancel()
inst._task = nil
end
end
local gainfocusfn = playerListing.mute.OnGainFocus
playerListing.mute:SetOnClick(
function()
if playerListing.userid ~= nil then
playerListing.isMuted = not playerListing.isMuted
TheNet:SetPlayerMuted(playerListing.userid, playerListing.isMuted)
if playerListing.isMuted then
playerListing.mute.image_focus = "mute.tex"
playerListing.mute.image:SetTexture("images/scoreboard.xml", "mute.tex")
playerListing.mute:SetTextures("images/scoreboard.xml", "mute.tex")
playerListing.mute:SetHoverText(STRINGS.UI.PLAYERSTATUSSCREEN.UNMUTE)
else
playerListing.mute.image_focus = "chat.tex"
playerListing.mute.image:SetTexture("images/scoreboard.xml", "chat.tex")
playerListing.mute:SetTextures("images/scoreboard.xml", "chat.tex")
playerListing.mute:SetHoverText(STRINGS.UI.PLAYERSTATUSSCREEN.MUTE)
end
playerListing.mute.image.inst:SetMuted(playerListing.isMuted)
end
end)
if playerListing.isMuted then
playerListing.mute.image_focus = "mute.tex"
playerListing.mute.image:SetTexture("images/scoreboard.xml", "mute.tex")
playerListing.mute:SetTextures("images/scoreboard.xml", "mute.tex")
playerListing.mute:SetHoverText(STRINGS.UI.PLAYERSTATUSSCREEN.UNMUTE)
end
playerListing.mute.image.inst:SetMuted(playerListing.isMuted)
if empty or v.userid == owner then
playerListing.mute:Hide()
playerListing.mute.image.inst:DisableMute()
end
playerListing.OnGainFocus = function()
-- playerListing.name:SetSize(26)
if not empty then
playerListing.highlight:Show()
end
end
playerListing.OnLoseFocus = function()
-- playerListing.name:SetSize(21)
playerListing.highlight:Hide()
end
doButtonFocusHookups(playerListing, nextWidgets)
return playerListing
end
local function UpdatePlayerListing(widget, data, index)
local empty = data == nil or next(data) == nil
widget.userid = not empty and data.userid or nil
if empty then
widget.bg:Hide()
else
widget.bg:Show()
end
if empty then
widget.characterBadge:Hide()
else
widget.characterBadge:Set(GetCharacterPrefab(data), data.colour or DEFAULT_PLAYER_COLOUR, data.performance ~= nil, data.userflags or 0)
widget.characterBadge:Show()
end
if not empty and data.admin then
widget.adminBadge:Show()
else
widget.adminBadge:Hide()
end
widget.name:SetColour(unpack(not empty and data.colour or DEFAULT_PLAYER_COLOUR))
widget.name:SetDisplayNameFromData(data)
local owner = TheNet:GetUserID()
widget.viewprofile:SetOnClick(
function()
if data.netid ~= nil then
TheNet:ViewNetProfile(data.netid)
end
end)
if empty or data.userid == owner or not TheNet:IsNetIDPlatformValid(data.netid) then
widget.viewprofile:Hide()
else
widget.viewprofile:Show()
end
widget.isMuted = data.muted == true
if widget.isMuted then
widget.mute.image_focus = "mute.tex"
widget.mute.image:SetTexture("images/scoreboard.xml", "mute.tex")
widget.mute:SetTextures("images/scoreboard.xml", "mute.tex")
widget.mute:SetHoverText(STRINGS.UI.PLAYERSTATUSSCREEN.UNMUTE)
else
widget.mute.image_focus = "chat.tex"
widget.mute.image:SetTexture("images/scoreboard.xml", "chat.tex")
widget.mute:SetTextures("images/scoreboard.xml", "chat.tex")
widget.mute:SetHoverText(STRINGS.UI.PLAYERSTATUSSCREEN.MUTE)
end
if empty or data.userid == owner then
widget.mute:Hide()
widget.mute.image.inst:DisableMute()
else
widget.mute:Show()
widget.mute.image.inst:SetMuted(widget.isMuted)
end
end
--------------------------------------------------------------------------
-- A list of players for the lobby screen
--
local PlayerList = Class(Widget, function(self, owner, nextWidgets)
self.owner = owner
Widget._ctor(self, "PlayerList")
self.proot = self:AddChild(Widget("ROOT"))
self.numPlayers = 0
self:BuildPlayerList(nil, nextWidgets)
self.focus_forward = self.scroll_list
end)
--For ease of overriding in mods
function PlayerList:GetDisplayName(clientrecord)
return clientrecord.name or ""
end
function PlayerList:BuildPlayerList(players, nextWidgets)
if not self.player_list then
self.player_list = self.proot:AddChild(Widget("player_list"))
self.player_list:SetPosition(75,RESOLUTION_Y-185,0)
end
if not self.title then
self.title = self.player_list:AddChild(Text( UIFONT, 35, STRINGS.UI.LOBBYSCREEN.PLAYERLIST, GOLD))
self.title:SetPosition(-20, 162)
end
if not self.bg then
self.bg = self.player_list:AddChild(Image("images/lobbyscreen.xml", "playerlobby_whitebg_chat.tex"))
self.bg:SetScale(.785, .46)
self.bg:SetTint(1,1,1,.65)
self.bg:SetPosition(60, 18)
end
if not self.upper_horizontal_line then
self.upper_horizontal_line = self.player_list:AddChild(Image("images/ui.xml", "line_horizontal_6.tex"))
self.upper_horizontal_line:SetScale(.66, .2)
self.upper_horizontal_line:SetPosition(57, 115, 0)
end
if not self.right_line then
self.right_line = self.player_list:AddChild(Image("images/ui.xml", "line_vertical_5.tex"))
self.right_line:SetScale(.5, .3)
self.right_line:SetPosition(170, 18)
end
if not self.left_line then
self.left_line = self.player_list:AddChild(Image("images/ui.xml", "line_vertical_5.tex"))
self.left_line:SetScale(.5, .3)
self.left_line:SetPosition(-55, 18)
end
if not self.lower_horizontal_line then
self.lower_horizontal_line = self.player_list:AddChild(Image("images/ui.xml", "line_horizontal_6.tex"))
self.lower_horizontal_line:SetScale(.66, .2)
self.lower_horizontal_line:SetPosition(57, -75, 0)
end
if not self.players_number then
self.players_number = self.player_list:AddChild(Text(NEWFONT, 20, "x/y"))
self.players_number:SetPosition(73, 100)
self.players_number:SetRegionSize(100,20)
self.players_number:SetHAlign(ANCHOR_RIGHT)
self.players_number:SetColour(0, 0, 0, 1)
end
if players == nil then
players = self:GetPlayerTable()
end
self.numPlayers = #players
local maxPlayers = TheNet:GetServerMaxPlayers()
self.players_number:SetString(self.numPlayers.."/"..(maxPlayers or "?"))
if not self.scroll_list then
self.list_root = self.player_list:AddChild(Widget("list_root"))
self.list_root:SetPosition(90, 5)
self.row_root = self.player_list:AddChild(Widget("row_root"))
self.row_root:SetPosition(90, 35)
self.player_widgets = {}
for i=1,4 do
table.insert(self.player_widgets, listingConstructor(players[i] or {}, i, self.row_root, nextWidgets))
end
self.scroll_list = self.list_root:AddChild(ScrollableList(players, 125, 130, 30, 7, UpdatePlayerListing, self.player_widgets, 7, nil, nil, -15, .8))
self.scroll_list:LayOutStaticWidgets(-15)
self.scroll_list:SetPosition(0,0)
else
self.scroll_list:SetList(players)
end
end
function PlayerList:GetPlayerTable()
local ClientObjs = TheNet:GetClientTable()
if ClientObjs == nil then
return {}
elseif TheNet:GetServerIsClientHosted() then
return ClientObjs
end
--remove dedicate host from player list
for i, v in ipairs(ClientObjs) do
if v.performance ~= nil then
table.remove(ClientObjs, i)
break
end
end
return ClientObjs
end
function PlayerList:Refresh(next_widgets)
local players = self:GetPlayerTable()
if #players ~= self.numPlayers then
--rebuild if player count changed
self:BuildPlayerList(players, next_widgets)
else
--rebuild if players changed even though count didn't change
for i, v in ipairs(players) do
local listitem = self.scroll_list.items[i]
if listitem == nil or
v.userid ~= listitem.userid or
(v.performance ~= nil) ~= (listitem.performance ~= nil) then
self:BuildPlayerList(players, next_widgets)
return
end
end
--refresh existing players
for i, widget in ipairs(self.player_widgets) do
for i2, data in ipairs(players) do
if widget.userid == data.userid and widget.characterBadge.ishost == (data.performance ~= nil) then
widget.characterBadge:Set(GetCharacterPrefab(data), data.colour or DEFAULT_PLAYER_COLOUR, widget.characterBadge.ishost, data.userflags or 0)
widget.name:SetDisplayNameFromData(data)
end
end
end
end
end
return PlayerList
| 412 | 0.958981 | 1 | 0.958981 | game-dev | MEDIA | 0.798347 | game-dev | 0.987419 | 1 | 0.987419 |
DanceManiac/Advanced-X-Ray-Public | 4,639 | SourcesAXR/xrGameCS/moving_objects_static.cpp | ////////////////////////////////////////////////////////////////////////////
// Module : moving_objects_static.cpp
// Created : 27.03.2007
// Modified : 14.05.2007
// Author : Dmitriy Iassenev
// Description : moving objects with static objects, i.e stable dynamic objects
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "moving_objects.h"
#include "ai_space.h"
#include "level_graph.h"
#include "moving_object.h"
#include "moving_objects_impl.h"
bool moving_objects::collided_static (const Fvector &position, const float &radius)
{
NEAREST_STATIC::const_iterator I = m_nearest_static.begin();
NEAREST_STATIC::const_iterator E = m_nearest_static.end();
for ( ; I != E; ++I) {
if (collided(*I,position,radius))
return (true);
}
return (false);
}
bool moving_objects::collided_static (moving_object *object, const Fvector &dest_position)
{
float radius = object->radius() + ai().level_graph().header().cell_size()*.5f;
float linear_velocity = dest_position.distance_to(object->position())/time_to_check;
float distance_to_check = time_to_check*linear_velocity;
u32 step_count = iFloor(distance_to_check/step_to_check + .5f);
for (u32 i=0; i<step_count; ++i) {
if (!i) {
if (collided_static(object->position(),radius))
return (true);
continue;
}
if ((i + 1) == step_count) {
if (collided_static(dest_position,radius))
return (true);
continue;
}
if (collided_static(object->predict_position(i*step_to_check),radius))
return (true);
}
return (false);
}
void moving_objects::fill_static (obstacles_query &query)
{
NEAREST_STATIC::const_iterator I = m_nearest_static.begin();
NEAREST_STATIC::const_iterator E = m_nearest_static.end();
for ( ; I != E; ++I)
query.add (smart_cast<const CGameObject*>(*I));
}
void moving_objects::fill_static (obstacles_query &query, const Fvector &position, const float &radius)
{
NEAREST_STATIC::const_iterator I = m_nearest_static.begin();
NEAREST_STATIC::const_iterator E = m_nearest_static.end();
for ( ; I != E; ++I) {
if (!collided(*I,position,radius))
continue;
query.add (smart_cast<const CGameObject*>(*I));
}
}
void moving_objects::fill_all_static (moving_object *object, const Fvector &dest_position)
{
float radius = object->radius() + ai().level_graph().header().cell_size()*.5f;
float linear_velocity = dest_position.distance_to(object->position())/time_to_check;
float distance_to_check = time_to_check*linear_velocity;
u32 step_count = iFloor(distance_to_check/step_to_check + .5f);
for (u32 i=0; i<step_count; ++i) {
if (!i) {
fill_static (object->static_query(),object->position(),radius);
continue;
}
if ((i + 1) == step_count) {
fill_static (object->static_query(),dest_position,radius);
continue;
}
fill_static (object->static_query(),object->predict_position(i*step_to_check),radius);
}
}
class ignore_predicate {
private:
moving_object *m_object;
public:
IC ignore_predicate(moving_object *object) :
m_object (object)
{
}
IC bool operator() (const CObject *object) const
{
if (m_object->ignored(object))
return (true);
const CGameObject *game_object = smart_cast<const CGameObject*>(object);
VERIFY (game_object);
if (!game_object->is_ai_obstacle())
return (true);
return (false);
}
};
void moving_objects::fill_nearest_list (const Fvector &position, const float &radius, moving_object *object)
{
Level().ObjectSpace.GetNearest (
m_spatial_objects,
m_nearest_static,
position,
radius,
const_cast<CEntityAlive*>(&object->object())
);
m_nearest_static.erase (
std::remove_if(
m_nearest_static.begin(),
m_nearest_static.end(),
ignore_predicate(object)
),
m_nearest_static.end()
);
}
void moving_objects::query_action_static (moving_object *object, const Fvector &_start_position, const Fvector &dest_position)
{
Fvector start_position = _start_position;
start_position.average (dest_position);
fill_nearest_list (
start_position,
dest_position.distance_to(start_position) + EPS,
object
);
if (m_nearest_static.empty())
return;
if (!collided_static(object,dest_position))
return;
fill_nearest_list (
start_position,
dest_position.distance_to(start_position) + additional_radius + EPS,
object
);
fill_static (object->static_query());
// fill_all_static (object,dest_position);
}
void moving_objects::query_action_static (moving_object *object)
{
query_action_static (object,object->position(),object->predict_position(time_to_check));
} | 412 | 0.801528 | 1 | 0.801528 | game-dev | MEDIA | 0.316626 | game-dev | 0.980123 | 1 | 0.980123 |
chrislake/7zsfxmm | 4,117 | 7zSfxMod/sources/vs_version.cpp | //
// Code for VS_VERSION resource
// Modified from MIT licensed code published at https://ddverpatch.codeplex.com/
//
#include "stdafx.h"
#include "vs_version.h"
// Stupid helper classes for the version struct
class yybuf
{
PBYTE const m_startptr;
PBYTE m_curptr;
PBYTE const m_endptr;
public:
yybuf(PBYTE start, DWORD size)
: m_startptr(start), m_curptr(start), m_endptr(start + size)
{
// ensure 32-bit alignment
assert((reinterpret_cast<INT_PTR>(m_curptr) & 3) == 0);
assert((reinterpret_cast<INT_PTR>(m_endptr) & 3) == 0);
}
void align4()
{
while (reinterpret_cast<INT_PTR>(m_curptr) & 3)
*m_curptr++ = 0;
}
DWORD cbwritten() const
{
return m_curptr ? static_cast<DWORD>(m_curptr - m_startptr) : 0;
}
PVOID incptr(DWORD n)
{
PVOID p = m_curptr;
m_curptr += n;
if (m_curptr > m_endptr) // overflow?
p = m_curptr = NULL;
return p;
}
void pushw(WORD v)
{
if (PWORD p = static_cast<PWORD>(incptr(sizeof(WORD))))
*p = v;
}
void pushstr(LPCWSTR ws)
{
DWORD n = static_cast<DWORD>(wcslen(ws));
n = (n + 1) * sizeof(WCHAR);
if (PVOID p = incptr(n))
memcpy(p, ws, n);
}
PWORD marksize()
{
return static_cast<PWORD>(incptr(sizeof(WORD)));
}
void patchsize(PWORD mp)
{
if (mp)
*mp = static_cast<WORD>(m_curptr - reinterpret_cast<PBYTE>(mp));
};
void pushTwostr(LPCWSTR name, LPCWSTR val)
{
//struct String {
// WORD wLength;
// WORD wValueLength;
// WORD wType;
// WCHAR szKey[];
// WORD Padding[];
// WORD Value[];
//};
PWORD const porig = marksize();
pushw(static_cast<WORD>(wcslen(val)) + 1);
pushw(1); //type
pushstr(name); // with align
align4();
pushstr(val); // don't align yet
patchsize(porig);
align4();
}
private:
yybuf(yybuf const &); // not copyable
yybuf &operator=(yybuf const &); // not assignable
};
/// Make a version resource from file_ver_data_s
DWORD file_ver_data::makeVersionResource(PBYTE palloc, DWORD cballoc) const
{
yybuf vbuf(palloc, cballoc);
WCHAR temps[256];
// Fill the res header
// struct VS_VERSIONINFO {
// WORD wLength;
// WORD wValueLength;
// WORD wType;
// WCHAR szKey[];
// WORD Padding1[];
// VS_FIXEDFILEINFO Value;
// WORD Padding2[];
// WORD Children[];
// };
PWORD const pTotalLen = vbuf.marksize();
vbuf.pushw(sizeof(VS_FIXEDFILEINFO)); //wValueLength=0x34
vbuf.pushw(0); //wType
vbuf.pushstr(L"VS_VERSION_INFO"); // szKey, Padding1
vbuf.align4();
// Fixed info
VS_FIXEDFILEINFO *const fxi = static_cast<VS_FIXEDFILEINFO *>(vbuf.incptr(sizeof(VS_FIXEDFILEINFO)));
*fxi = m_fxi;
vbuf.align4(); // Padding2
// String File Info
PWORD const stringStart = vbuf.marksize();
vbuf.pushw(0); //wValueLength
vbuf.pushw(1); //wType
vbuf.pushstr(L"StringFileInfo");
vbuf.align4();
PWORD const stringTableStart = vbuf.marksize();
vbuf.pushw(0); // ?
vbuf.pushw(1); //wType
wsprintfW(temps, L"%4.4X04B0", m_langid); /* "040904B0" = LANG_ENGLISH/SUBLANG_ENGLISH_US, Unicode CP */
vbuf.pushstr(temps);
vbuf.align4();
// Strings
for (int k = 0; k < ARRAYSIZE(m_CustomStrNames); k++) {
if (!m_CustomStrNames[k].IsEmpty()) {
vbuf.pushTwostr(m_CustomStrNames[k], m_CustomStrVals[k]);
if (0 == _wcsicmp(L"SpecialBuild", m_CustomStrNames[k]))
fxi->dwFileFlags |= VS_FF_SPECIALBUILD;
if (0 == _wcsicmp(L"PrivateBuild", m_CustomStrNames[k]))
fxi->dwFileFlags |= VS_FF_PRIVATEBUILD;
}
}
vbuf.patchsize(stringTableStart);
vbuf.patchsize(stringStart);
vbuf.align4();
// Var info
// struct VarFileInfo {
// WORD wLength;
// WORD wValueLength;
// WORD wType;
// WCHAR szKey[];
// WORD Padding[];
// Var Children[];
// };
PWORD const varStart = vbuf.marksize();
vbuf.pushw(0);
vbuf.pushw(1);
vbuf.pushstr(L"VarFileInfo");
vbuf.align4();
vbuf.pushw(0x24);
vbuf.pushw(0x04);
vbuf.pushw(0x00);
vbuf.pushstr(L"Translation");
vbuf.align4();
vbuf.pushw(m_langid);
vbuf.pushw(0x04B0); // 0x04B0 = 1200 = Unicode CP
vbuf.patchsize(varStart);
/////////////////////////////
vbuf.patchsize(pTotalLen);
return vbuf.cbwritten();
}
| 412 | 0.86749 | 1 | 0.86749 | game-dev | MEDIA | 0.552725 | game-dev | 0.886405 | 1 | 0.886405 |
exapde/Exasim | 3,690 | kokkos/core/src/Kokkos_MemoryTraits.hpp | //@HEADER
// ************************************************************************
//
// Kokkos v. 4.0
// Copyright (2022) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Part of Kokkos, under the Apache License v2.0 with LLVM Exceptions.
// See https://kokkos.org/LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//@HEADER
#ifndef KOKKOS_IMPL_PUBLIC_INCLUDE
#include <Kokkos_Macros.hpp>
static_assert(false,
"Including non-public Kokkos header files is not allowed.");
#endif
#ifndef KOKKOS_MEMORYTRAITS_HPP
#define KOKKOS_MEMORYTRAITS_HPP
#include <impl/Kokkos_Traits.hpp>
#include <Kokkos_BitManipulation.hpp>
//----------------------------------------------------------------------------
namespace Kokkos {
/** \brief Memory access traits for views, an extension point.
*
* These traits should be orthogonal. If there are dependencies then
* the MemoryTraits template must detect and enforce dependencies.
*
* A zero value is the default for a View, indicating that none of
* these traits are present.
*/
enum MemoryTraitsFlags {
Unmanaged = 0x01,
RandomAccess = 0x02,
Atomic = 0x04,
Restrict = 0x08,
Aligned = 0x10
};
template <unsigned T = 0>
struct MemoryTraits {
//! Tag this class as a kokkos memory traits:
using memory_traits = MemoryTraits<T>;
static constexpr unsigned impl_value = T;
static constexpr bool is_unmanaged =
(unsigned(0) != (T & unsigned(Kokkos::Unmanaged)));
static constexpr bool is_random_access =
(unsigned(0) != (T & unsigned(Kokkos::RandomAccess)));
static constexpr bool is_atomic =
(unsigned(0) != (T & unsigned(Kokkos::Atomic)));
static constexpr bool is_restrict =
(unsigned(0) != (T & unsigned(Kokkos::Restrict)));
static constexpr bool is_aligned =
(unsigned(0) != (T & unsigned(Kokkos::Aligned)));
};
} // namespace Kokkos
//----------------------------------------------------------------------------
namespace Kokkos {
#ifdef KOKKOS_ENABLE_DEPRECATED_CODE_4
using MemoryManaged KOKKOS_DEPRECATED = Kokkos::MemoryTraits<>;
#endif
using MemoryUnmanaged = Kokkos::MemoryTraits<Kokkos::Unmanaged>;
using MemoryRandomAccess =
Kokkos::MemoryTraits<Kokkos::Unmanaged | Kokkos::RandomAccess>;
} // namespace Kokkos
//----------------------------------------------------------------------------
namespace Kokkos {
namespace Impl {
/** \brief Memory alignment settings
*
* Sets global value for memory alignment. Must be a power of two!
* Enable compatibility of views from different devices with static stride.
* Use compiler flag to enable overwrites.
*/
#ifdef KOKKOS_ENABLE_DEPRECATED_CODE_4
static constexpr unsigned MEMORY_ALIGNMENT = KOKKOS_IMPL_MEMORY_ALIGNMENT;
static constexpr unsigned MEMORY_ALIGNMENT_THRESHOLD =
KOKKOS_IMPL_MEMORY_ALIGNMENT_THRESHOLD;
#else
static constexpr unsigned MEMORY_ALIGNMENT = 64;
static constexpr unsigned MEMORY_ALIGNMENT_THRESHOLD = 1;
#endif
static_assert(has_single_bit(MEMORY_ALIGNMENT),
"MEMORY_ALIGNMENT must be a power of 2");
// ------------------------------------------------------------------ //
// this identifies the default memory trait
//
template <typename Tp>
struct is_default_memory_trait : std::false_type {};
template <>
struct is_default_memory_trait<Kokkos::MemoryTraits<>> : std::true_type {};
} // namespace Impl
} // namespace Kokkos
#endif /* #ifndef KOKKOS_MEMORYTRAITS_HPP */
| 412 | 0.912443 | 1 | 0.912443 | game-dev | MEDIA | 0.350868 | game-dev | 0.646271 | 1 | 0.646271 |
EphemeralSpace/ephemeral-space | 17,527 | Content.Shared/Mech/EntitySystems/SharedMechSystem.cs | using System.Linq;
using Content.Shared.Access.Components;
using Content.Shared.ActionBlocker;
using Content.Shared.Actions;
using Content.Shared.Destructible;
using Content.Shared.DoAfter;
using Content.Shared.DragDrop;
using Content.Shared.FixedPoint;
using Content.Shared.Interaction;
using Content.Shared.Interaction.Components;
using Content.Shared.Interaction.Events;
using Content.Shared.Mech.Components;
using Content.Shared.Mech.Equipment.Components;
using Content.Shared.Movement.Components;
using Content.Shared.Movement.Systems;
using Content.Shared.Popups;
using Content.Shared.Storage.Components;
using Content.Shared.Weapons.Melee;
using Content.Shared.Whitelist;
using Robust.Shared.Containers;
using Robust.Shared.Network;
using Robust.Shared.Serialization;
using Robust.Shared.Timing;
namespace Content.Shared.Mech.EntitySystems;
/// <summary>
/// Handles all of the interactions, UI handling, and items shennanigans for <see cref="MechComponent"/>
/// </summary>
public abstract partial class SharedMechSystem : EntitySystem
{
[Dependency] private readonly IGameTiming _timing = default!;
[Dependency] private readonly INetManager _net = default!;
[Dependency] private readonly ActionBlockerSystem _actionBlocker = default!;
[Dependency] private readonly SharedActionsSystem _actions = default!;
[Dependency] private readonly SharedAppearanceSystem _appearance = default!;
[Dependency] private readonly SharedContainerSystem _container = default!;
[Dependency] private readonly SharedInteractionSystem _interaction = default!;
[Dependency] private readonly SharedMoverController _mover = default!;
[Dependency] private readonly SharedPopupSystem _popup = default!;
[Dependency] private readonly SharedDoAfterSystem _doAfter = default!;
[Dependency] private readonly EntityWhitelistSystem _whitelistSystem = default!;
/// <inheritdoc/>
public override void Initialize()
{
SubscribeLocalEvent<MechComponent, MechToggleEquipmentEvent>(OnToggleEquipmentAction);
SubscribeLocalEvent<MechComponent, MechEjectPilotEvent>(OnEjectPilotEvent);
SubscribeLocalEvent<MechComponent, UserActivateInWorldEvent>(RelayInteractionEvent);
SubscribeLocalEvent<MechComponent, ComponentStartup>(OnStartup);
SubscribeLocalEvent<MechComponent, DestructionEventArgs>(OnDestruction);
SubscribeLocalEvent<MechComponent, EntityStorageIntoContainerAttemptEvent>(OnEntityStorageDump);
SubscribeLocalEvent<MechComponent, GetAdditionalAccessEvent>(OnGetAdditionalAccess);
SubscribeLocalEvent<MechComponent, DragDropTargetEvent>(OnDragDrop);
SubscribeLocalEvent<MechComponent, CanDropTargetEvent>(OnCanDragDrop);
SubscribeLocalEvent<MechPilotComponent, GetMeleeWeaponEvent>(OnGetMeleeWeapon);
SubscribeLocalEvent<MechPilotComponent, CanAttackFromContainerEvent>(OnCanAttackFromContainer);
SubscribeLocalEvent<MechPilotComponent, AttackAttemptEvent>(OnAttackAttempt);
InitializeRelay();
}
private void OnToggleEquipmentAction(EntityUid uid, MechComponent component, MechToggleEquipmentEvent args)
{
if (args.Handled)
return;
args.Handled = true;
CycleEquipment(uid);
}
private void OnEjectPilotEvent(EntityUid uid, MechComponent component, MechEjectPilotEvent args)
{
if (args.Handled)
return;
args.Handled = true;
TryEject(uid, component);
}
private void RelayInteractionEvent(EntityUid uid, MechComponent component, UserActivateInWorldEvent args)
{
var pilot = component.PilotSlot.ContainedEntity;
if (pilot == null)
return;
// TODO why is this being blocked?
if (!_timing.IsFirstTimePredicted)
return;
if (component.CurrentSelectedEquipment != null)
{
RaiseLocalEvent(component.CurrentSelectedEquipment.Value, args);
}
}
private void OnStartup(EntityUid uid, MechComponent component, ComponentStartup args)
{
component.PilotSlot = _container.EnsureContainer<ContainerSlot>(uid, component.PilotSlotId);
component.EquipmentContainer = _container.EnsureContainer<Container>(uid, component.EquipmentContainerId);
component.BatterySlot = _container.EnsureContainer<ContainerSlot>(uid, component.BatterySlotId);
UpdateAppearance(uid, component);
}
private void OnDestruction(EntityUid uid, MechComponent component, DestructionEventArgs args)
{
BreakMech(uid, component);
}
private void OnEntityStorageDump(Entity<MechComponent> entity, ref EntityStorageIntoContainerAttemptEvent args)
{
// There's no reason we should dump into /any/ of the mech's containers.
args.Cancelled = true;
}
private void OnGetAdditionalAccess(EntityUid uid, MechComponent component, ref GetAdditionalAccessEvent args)
{
var pilot = component.PilotSlot.ContainedEntity;
if (pilot == null)
return;
args.Entities.Add(pilot.Value);
}
private void SetupUser(EntityUid mech, EntityUid pilot, MechComponent? component = null)
{
if (!Resolve(mech, ref component))
return;
var rider = EnsureComp<MechPilotComponent>(pilot);
// Warning: this bypasses most normal interaction blocking components on the user, like drone laws and the like.
var irelay = EnsureComp<InteractionRelayComponent>(pilot);
_mover.SetRelay(pilot, mech);
_interaction.SetRelay(pilot, mech, irelay);
rider.Mech = mech;
Dirty(pilot, rider);
if (_net.IsClient)
return;
_actions.AddAction(pilot, ref component.MechCycleActionEntity, component.MechCycleAction, mech);
_actions.AddAction(pilot, ref component.MechUiActionEntity, component.MechUiAction, mech);
_actions.AddAction(pilot, ref component.MechEjectActionEntity, component.MechEjectAction, mech);
}
private void RemoveUser(EntityUid mech, EntityUid pilot)
{
if (!RemComp<MechPilotComponent>(pilot))
return;
RemComp<RelayInputMoverComponent>(pilot);
RemComp<InteractionRelayComponent>(pilot);
_actions.RemoveProvidedActions(pilot, mech);
}
/// <summary>
/// Destroys the mech, removing the user and ejecting anything contained.
/// </summary>
/// <param name="uid"></param>
/// <param name="component"></param>
public virtual void BreakMech(EntityUid uid, MechComponent? component = null)
{
if (!Resolve(uid, ref component))
return;
TryEject(uid, component);
var equipment = new List<EntityUid>(component.EquipmentContainer.ContainedEntities);
foreach (var ent in equipment)
{
RemoveEquipment(uid, ent, component, forced: true);
}
component.Broken = true;
UpdateAppearance(uid, component);
}
/// <summary>
/// Cycles through the currently selected equipment.
/// </summary>
/// <param name="uid"></param>
/// <param name="component"></param>
public void CycleEquipment(EntityUid uid, MechComponent? component = null)
{
if (!Resolve(uid, ref component))
return;
var allEquipment = component.EquipmentContainer.ContainedEntities.ToList();
var equipmentIndex = -1;
if (component.CurrentSelectedEquipment != null)
{
bool StartIndex(EntityUid u) => u == component.CurrentSelectedEquipment;
equipmentIndex = allEquipment.FindIndex(StartIndex);
}
equipmentIndex++;
component.CurrentSelectedEquipment = equipmentIndex >= allEquipment.Count
? null
: allEquipment[equipmentIndex];
var popupString = component.CurrentSelectedEquipment != null
? Loc.GetString("mech-equipment-select-popup", ("item", component.CurrentSelectedEquipment))
: Loc.GetString("mech-equipment-select-none-popup");
if (_net.IsServer)
_popup.PopupEntity(popupString, uid);
Dirty(uid, component);
}
/// <summary>
/// Inserts an equipment item into the mech.
/// </summary>
/// <param name="uid"></param>
/// <param name="toInsert"></param>
/// <param name="component"></param>
/// <param name="equipmentComponent"></param>
public void InsertEquipment(EntityUid uid, EntityUid toInsert, MechComponent? component = null,
MechEquipmentComponent? equipmentComponent = null)
{
if (!Resolve(uid, ref component))
return;
if (!Resolve(toInsert, ref equipmentComponent))
return;
if (component.EquipmentContainer.ContainedEntities.Count >= component.MaxEquipmentAmount)
return;
if (_whitelistSystem.IsWhitelistFail(component.EquipmentWhitelist, toInsert))
return;
equipmentComponent.EquipmentOwner = uid;
_container.Insert(toInsert, component.EquipmentContainer);
var ev = new MechEquipmentInsertedEvent(uid);
RaiseLocalEvent(toInsert, ref ev);
UpdateUserInterface(uid, component);
}
/// <summary>
/// Removes an equipment item from a mech.
/// </summary>
/// <param name="uid"></param>
/// <param name="toRemove"></param>
/// <param name="component"></param>
/// <param name="equipmentComponent"></param>
/// <param name="forced">
/// Whether or not the removal can be cancelled, and if non-mech equipment should be ejected.
/// </param>
public void RemoveEquipment(EntityUid uid, EntityUid toRemove, MechComponent? component = null,
MechEquipmentComponent? equipmentComponent = null, bool forced = false)
{
if (!Resolve(uid, ref component))
return;
// When forced, we also want to handle the possibility that the "equipment" isn't actually equipment.
// This /shouldn't/ be possible thanks to OnEntityStorageDump, but there's been quite a few regressions
// with entities being hardlock stuck inside mechs.
if (!Resolve(toRemove, ref equipmentComponent) && !forced)
return;
if (!forced)
{
var attemptev = new AttemptRemoveMechEquipmentEvent();
RaiseLocalEvent(toRemove, ref attemptev);
if (attemptev.Cancelled)
return;
}
var ev = new MechEquipmentRemovedEvent(uid);
RaiseLocalEvent(toRemove, ref ev);
if (component.CurrentSelectedEquipment == toRemove)
CycleEquipment(uid, component);
if (forced && equipmentComponent != null)
equipmentComponent.EquipmentOwner = null;
_container.Remove(toRemove, component.EquipmentContainer);
UpdateUserInterface(uid, component);
}
/// <summary>
/// Attempts to change the amount of energy in the mech.
/// </summary>
/// <param name="uid">The mech itself</param>
/// <param name="delta">The change in energy</param>
/// <param name="component"></param>
/// <returns>If the energy was successfully changed.</returns>
public virtual bool TryChangeEnergy(EntityUid uid, FixedPoint2 delta, MechComponent? component = null)
{
if (!Resolve(uid, ref component))
return false;
if (component.Energy + delta < 0)
return false;
component.Energy = FixedPoint2.Clamp(component.Energy + delta, 0, component.MaxEnergy);
Dirty(uid, component);
UpdateUserInterface(uid, component);
return true;
}
/// <summary>
/// Sets the integrity of the mech.
/// </summary>
/// <param name="uid">The mech itself</param>
/// <param name="value">The value the integrity will be set at</param>
/// <param name="component"></param>
public void SetIntegrity(EntityUid uid, FixedPoint2 value, MechComponent? component = null)
{
if (!Resolve(uid, ref component))
return;
component.Integrity = FixedPoint2.Clamp(value, 0, component.MaxIntegrity);
if (component.Integrity <= 0)
{
BreakMech(uid, component);
}
else if (component.Broken)
{
component.Broken = false;
UpdateAppearance(uid, component);
}
Dirty(uid, component);
UpdateUserInterface(uid, component);
}
/// <summary>
/// Checks if the pilot is present
/// </summary>
/// <param name="component"></param>
/// <returns>Whether or not the pilot is present</returns>
public bool IsEmpty(MechComponent component)
{
return component.PilotSlot.ContainedEntity == null;
}
/// <summary>
/// Checks if an entity can be inserted into the mech.
/// </summary>
/// <param name="uid"></param>
/// <param name="toInsert"></param>
/// <param name="component"></param>
/// <returns></returns>
public bool CanInsert(EntityUid uid, EntityUid toInsert, MechComponent? component = null)
{
if (!Resolve(uid, ref component))
return false;
return IsEmpty(component) && _actionBlocker.CanMove(toInsert);
}
/// <summary>
/// Updates the user interface
/// </summary>
/// <remarks>
/// This is defined here so that UI updates can be accessed from shared.
/// </remarks>
public virtual void UpdateUserInterface(EntityUid uid, MechComponent? component = null)
{
}
/// <summary>
/// Attempts to insert a pilot into the mech.
/// </summary>
/// <param name="uid"></param>
/// <param name="toInsert"></param>
/// <param name="component"></param>
/// <returns>Whether or not the entity was inserted</returns>
public bool TryInsert(EntityUid uid, EntityUid? toInsert, MechComponent? component = null)
{
if (!Resolve(uid, ref component))
return false;
if (toInsert == null || component.PilotSlot.ContainedEntity == toInsert)
return false;
if (!CanInsert(uid, toInsert.Value, component))
return false;
SetupUser(uid, toInsert.Value);
_container.Insert(toInsert.Value, component.PilotSlot);
UpdateAppearance(uid, component);
return true;
}
/// <summary>
/// Attempts to eject the current pilot from the mech
/// </summary>
/// <param name="uid"></param>
/// <param name="component"></param>
/// <returns>Whether or not the pilot was ejected.</returns>
public bool TryEject(EntityUid uid, MechComponent? component = null)
{
if (!Resolve(uid, ref component))
return false;
if (component.PilotSlot.ContainedEntity == null)
return false;
var pilot = component.PilotSlot.ContainedEntity.Value;
RemoveUser(uid, pilot);
_container.RemoveEntity(uid, pilot);
UpdateAppearance(uid, component);
return true;
}
private void OnGetMeleeWeapon(EntityUid uid, MechPilotComponent component, GetMeleeWeaponEvent args)
{
if (args.Handled)
return;
if (!TryComp<MechComponent>(component.Mech, out var mech))
return;
var weapon = mech.CurrentSelectedEquipment ?? component.Mech;
args.Weapon = weapon;
args.Handled = true;
}
private void OnCanAttackFromContainer(EntityUid uid, MechPilotComponent component, CanAttackFromContainerEvent args)
{
args.CanAttack = true;
}
private void OnAttackAttempt(EntityUid uid, MechPilotComponent component, AttackAttemptEvent args)
{
if (args.Target == component.Mech)
args.Cancel();
}
private void UpdateAppearance(EntityUid uid, MechComponent? component = null,
AppearanceComponent? appearance = null)
{
if (!Resolve(uid, ref component, ref appearance, false))
return;
_appearance.SetData(uid, MechVisuals.Open, IsEmpty(component), appearance);
_appearance.SetData(uid, MechVisuals.Broken, component.Broken, appearance);
}
private void OnDragDrop(EntityUid uid, MechComponent component, ref DragDropTargetEvent args)
{
if (args.Handled)
return;
args.Handled = true;
var doAfterEventArgs = new DoAfterArgs(EntityManager, args.Dragged, component.EntryDelay, new MechEntryEvent(), uid, target: uid)
{
BreakOnMove = true,
};
_doAfter.TryStartDoAfter(doAfterEventArgs);
}
private void OnCanDragDrop(EntityUid uid, MechComponent component, ref CanDropTargetEvent args)
{
args.Handled = true;
args.CanDrop |= !component.Broken && CanInsert(uid, args.Dragged, component);
}
}
/// <summary>
/// Event raised when the battery is successfully removed from the mech,
/// on both success and failure
/// </summary>
[Serializable, NetSerializable]
public sealed partial class RemoveBatteryEvent : SimpleDoAfterEvent
{
}
/// <summary>
/// Event raised when a person removes someone from a mech,
/// on both success and failure
/// </summary>
[Serializable, NetSerializable]
public sealed partial class MechExitEvent : SimpleDoAfterEvent
{
}
/// <summary>
/// Event raised when a person enters a mech, on both success and failure
/// </summary>
[Serializable, NetSerializable]
public sealed partial class MechEntryEvent : SimpleDoAfterEvent
{
}
| 412 | 0.936185 | 1 | 0.936185 | game-dev | MEDIA | 0.969485 | game-dev | 0.936392 | 1 | 0.936392 |
PhoenixBladez/SpiritMod | 3,485 | Items/DonatorItems/GoldJadeScythe.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SpiritMod.Items.Material;
using SpiritMod.Projectiles.DonatorItems;
using System;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace SpiritMod.Items.DonatorItems
{
public class GoldJadeScythe : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Crook of the Tormented");
Tooltip.SetDefault("Occasionally spawns ornate scarabs to defend you upon hitting enemies");
SpiritGlowmask.AddGlowMask(item.type, "SpiritMod/Items/DonatorItems/GoldJadeScythe_Glow");
}
public override void SetDefaults()
{
item.damage = 42;
item.melee = true;
item.width = 50;
item.height = 50;
item.useTime = 19;
item.useAnimation = 19;
item.useStyle = ItemUseStyleID.SwingThrow;
item.knockBack = 6;
item.rare = ItemRarityID.Orange;
item.UseSound = SoundID.Item1;
item.autoReuse = true;
item.value = Item.buyPrice(0, 10, 0, 0);
item.value = Item.sellPrice(0, 3, 0, 0);
item.useTurn = true;
item.crit = 9;
}
public override void PostDrawInWorld(SpriteBatch spriteBatch, Color lightColor, Color alphaColor, float rotation, float scale, int whoAmI)
{
Lighting.AddLight(item.position, 0.255f, .509f, .072f);
Texture2D texture;
texture = Main.itemTexture[item.type];
spriteBatch.Draw
(
mod.GetTexture("Items/DonatorItems/GoldJadeScythe_Glow"),
new Vector2
(
item.position.X - Main.screenPosition.X + item.width * 0.5f,
item.position.Y - Main.screenPosition.Y + item.height - texture.Height * 0.5f + 2f
),
new Rectangle(0, 0, texture.Width, texture.Height),
Color.White,
rotation,
texture.Size() * 0.5f,
scale,
SpriteEffects.None,
0f
);
}
public override void OnHitNPC(Player player, NPC target, int damage, float knockBack, bool crit)
{
if (Main.rand.Next(8) == 1) {
Vector2 velocity = new Vector2(player.direction, 0) * 4f;
int proj = Projectile.NewProjectile(player.Center.X, player.position.Y + player.height + -35, velocity.X, velocity.Y, ModContent.ProjectileType<JadeScarab>(), item.damage / 2, item.owner, 0, 0f);
Main.projectile[proj].friendly = true;
Main.projectile[proj].hostile = false;
}
}
public override void UseStyle(Player player)
{
float cosRot = (float)Math.Cos(player.itemRotation - 0.78f * player.direction * player.gravDir);
float sinRot = (float)Math.Sin(player.itemRotation - 0.78f * player.direction * player.gravDir);
for (int i = 0; i < 1; i++) {
float length = (item.width * 1.2f - i * item.width / 9) * item.scale - 4; //length to base + arm displacement
int dust = Dust.NewDust(new Vector2((player.itemLocation.X + length * cosRot * player.direction), (player.itemLocation.Y + length * sinRot * player.direction)), 0, 0, DustID.TerraBlade, player.velocity.X * 0.9f, player.velocity.Y * 0.9f, 100, Color.Transparent, .8f);
Main.dust[dust].velocity *= 0f;
Main.dust[dust].noGravity = true;
}
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ModContent.ItemType<Items.Sets.ScarabeusDrops.Chitin>(), 12);
recipe.AddIngredient(ItemID.Emerald, 4);
recipe.AddRecipeGroup("SpiritMod:GoldBars", 5);
recipe.AddIngredient(ItemID.SoulofLight, 5);
recipe.AddIngredient(ItemID.SoulofNight, 5);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(this, 1);
recipe.AddRecipe();
}
}
} | 412 | 0.846841 | 1 | 0.846841 | game-dev | MEDIA | 0.985739 | game-dev | 0.972249 | 1 | 0.972249 |
doyubkim/fluid-engine-dev | 2,270 | include/jet/rigid_body_collider3.h | // Copyright (c) 2018 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#ifndef INCLUDE_JET_RIGID_BODY_COLLIDER3_H_
#define INCLUDE_JET_RIGID_BODY_COLLIDER3_H_
#include <jet/collider3.h>
#include <jet/quaternion.h>
namespace jet {
//!
//! \brief 3-D rigid body collider class.
//!
//! This class implements 3-D rigid body collider. The collider can only take
//! rigid body motion with linear and rotational velocities.
//!
class RigidBodyCollider3 final : public Collider3 {
public:
class Builder;
//! Linear velocity of the rigid body.
Vector3D linearVelocity;
//! Angular velocity of the rigid body.
Vector3D angularVelocity;
//! Constructs a collider with a surface.
explicit RigidBodyCollider3(const Surface3Ptr& surface);
//! Constructs a collider with a surface and other parameters.
RigidBodyCollider3(
const Surface3Ptr& surface,
const Vector3D& linearVelocity,
const Vector3D& angularVelocity);
//! Returns the velocity of the collider at given \p point.
Vector3D velocityAt(const Vector3D& point) const override;
//! Returns builder fox RigidBodyCollider3.
static Builder builder();
};
//! Shared pointer for the RigidBodyCollider3 type.
typedef std::shared_ptr<RigidBodyCollider3> RigidBodyCollider3Ptr;
//!
//! \brief Front-end to create RigidBodyCollider3 objects step by step.
//!
class RigidBodyCollider3::Builder final {
public:
//! Returns builder with surface.
Builder& withSurface(const Surface3Ptr& surface);
//! Returns builder with linear velocity.
Builder& withLinearVelocity(const Vector3D& linearVelocity);
//! Returns builder with angular velocity.
Builder& withAngularVelocity(const Vector3D& angularVelocity);
//! Builds RigidBodyCollider3.
RigidBodyCollider3 build() const;
//! Builds shared pointer of RigidBodyCollider3 instance.
RigidBodyCollider3Ptr makeShared() const;
private:
Surface3Ptr _surface;
Vector3D _linearVelocity{0, 0, 0};
Vector3D _angularVelocity{0, 0, 0};
};
} // namespace jet
#endif // INCLUDE_JET_RIGID_BODY_COLLIDER3_H_
| 412 | 0.682921 | 1 | 0.682921 | game-dev | MEDIA | 0.932143 | game-dev | 0.624715 | 1 | 0.624715 |
minty-codes/TutorialClient1.8.8 | 5,290 | net/minecraft/entity/ai/EntityAIFollowOwner.java | package net.minecraft.entity.ai;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.passive.EntityTameable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.pathfinding.PathNavigate;
import net.minecraft.pathfinding.PathNavigateGround;
import net.minecraft.util.BlockPos;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
public class EntityAIFollowOwner extends EntityAIBase
{
private EntityTameable thePet;
private EntityLivingBase theOwner;
World theWorld;
private double followSpeed;
private PathNavigate petPathfinder;
private int field_75343_h;
float maxDist;
float minDist;
private boolean field_75344_i;
public EntityAIFollowOwner(EntityTameable thePetIn, double followSpeedIn, float minDistIn, float maxDistIn)
{
this.thePet = thePetIn;
this.theWorld = thePetIn.worldObj;
this.followSpeed = followSpeedIn;
this.petPathfinder = thePetIn.getNavigator();
this.minDist = minDistIn;
this.maxDist = maxDistIn;
this.setMutexBits(3);
if (!(thePetIn.getNavigator() instanceof PathNavigateGround))
{
throw new IllegalArgumentException("Unsupported mob type for FollowOwnerGoal");
}
}
/**
* Returns whether the EntityAIBase should begin execution.
*/
public boolean shouldExecute()
{
EntityLivingBase entitylivingbase = this.thePet.getOwner();
if (entitylivingbase == null)
{
return false;
}
else if (entitylivingbase instanceof EntityPlayer && ((EntityPlayer)entitylivingbase).isSpectator())
{
return false;
}
else if (this.thePet.isSitting())
{
return false;
}
else if (this.thePet.getDistanceSqToEntity(entitylivingbase) < (double)(this.minDist * this.minDist))
{
return false;
}
else
{
this.theOwner = entitylivingbase;
return true;
}
}
/**
* Returns whether an in-progress EntityAIBase should continue executing
*/
public boolean continueExecuting()
{
return !this.petPathfinder.noPath() && this.thePet.getDistanceSqToEntity(this.theOwner) > (double)(this.maxDist * this.maxDist) && !this.thePet.isSitting();
}
/**
* Execute a one shot task or start executing a continuous task
*/
public void startExecuting()
{
this.field_75343_h = 0;
this.field_75344_i = ((PathNavigateGround)this.thePet.getNavigator()).getAvoidsWater();
((PathNavigateGround)this.thePet.getNavigator()).setAvoidsWater(false);
}
/**
* Resets the task
*/
public void resetTask()
{
this.theOwner = null;
this.petPathfinder.clearPathEntity();
((PathNavigateGround)this.thePet.getNavigator()).setAvoidsWater(true);
}
private boolean func_181065_a(BlockPos p_181065_1_)
{
IBlockState iblockstate = this.theWorld.getBlockState(p_181065_1_);
Block block = iblockstate.getBlock();
return block == Blocks.air ? true : !block.isFullCube();
}
/**
* Updates the task
*/
public void updateTask()
{
this.thePet.getLookHelper().setLookPositionWithEntity(this.theOwner, 10.0F, (float)this.thePet.getVerticalFaceSpeed());
if (!this.thePet.isSitting())
{
if (--this.field_75343_h <= 0)
{
this.field_75343_h = 10;
if (!this.petPathfinder.tryMoveToEntityLiving(this.theOwner, this.followSpeed))
{
if (!this.thePet.getLeashed())
{
if (this.thePet.getDistanceSqToEntity(this.theOwner) >= 144.0D)
{
int i = MathHelper.floor_double(this.theOwner.posX) - 2;
int j = MathHelper.floor_double(this.theOwner.posZ) - 2;
int k = MathHelper.floor_double(this.theOwner.getEntityBoundingBox().minY);
for (int l = 0; l <= 4; ++l)
{
for (int i1 = 0; i1 <= 4; ++i1)
{
if ((l < 1 || i1 < 1 || l > 3 || i1 > 3) && World.doesBlockHaveSolidTopSurface(this.theWorld, new BlockPos(i + l, k - 1, j + i1)) && this.func_181065_a(new BlockPos(i + l, k, j + i1)) && this.func_181065_a(new BlockPos(i + l, k + 1, j + i1)))
{
this.thePet.setLocationAndAngles((double)((float)(i + l) + 0.5F), (double)k, (double)((float)(j + i1) + 0.5F), this.thePet.rotationYaw, this.thePet.rotationPitch);
this.petPathfinder.clearPathEntity();
return;
}
}
}
}
}
}
}
}
}
}
| 412 | 0.791753 | 1 | 0.791753 | game-dev | MEDIA | 0.964111 | game-dev | 0.933082 | 1 | 0.933082 |
LiShengYang-yiyi/YIUI | 1,580 | YIUIFramework/YIUIEditor/YIUIAutoTool/Window/UICreate/View/UICreateViewCode.cs | #if UNITY_EDITOR
namespace YIUIFramework.Editor
{
public class UICreateViewCode : BaseTemplate
{
private string m_EventName = "UI继承View代码创建";
public override string EventName => m_EventName;
public override bool Cover => false;
private bool m_AutoRefresh = false;
public override bool AutoRefresh => m_AutoRefresh;
private bool m_ShowTips = false;
public override bool ShowTips => m_ShowTips;
public UICreateViewCode(out bool result, string authorName, UICreateViewData codeData) : base(authorName)
{
var path = $"{UIStaticHelper.UICodeScriptsPath}/{codeData.PkgName}/{codeData.ResName}.cs";
var template = $"{UIStaticHelper.UITemplatePath}/UICreateViewTemplate.txt";
CreateVo = new CreateVo(template, path);
m_EventName = $"{codeData.ResName} 继承 {codeData.ResName}Base 创建";
m_AutoRefresh = codeData.AutoRefresh;
m_ShowTips = codeData.ShowTips;
ValueDic["Namespace"] = codeData.Namespace;
ValueDic["PkgName"] = codeData.PkgName;
ValueDic["ResName"] = codeData.ResName;
if (!TemplateEngine.FileExists(CreateVo.SavePath))
{
result = CreateNewFile();
}
if (codeData.OverrideDic == null)
{
result = true;
return;
}
result = OverrideCheckCodeFile(codeData.OverrideDic);
}
}
}
#endif | 412 | 0.805237 | 1 | 0.805237 | game-dev | MEDIA | 0.344954 | game-dev | 0.828812 | 1 | 0.828812 |
openbullet/OpenBullet2 | 1,151 | RuriLib/Helpers/GZip.cs | using System.IO;
using System.IO.Compression;
namespace RuriLib.Helpers
{
/*
* Taken from https://stackoverflow.com/questions/7343465/compression-decompression-string-with-c-sharp
* */
/// <summary>
/// GZip utilities class.
/// </summary>
public static class GZip
{
/// <summary>
/// GZips a content.
/// </summary>
public static byte[] Zip(byte[] bytes)
{
using var msi = new MemoryStream(bytes);
using var mso = new MemoryStream();
using (var gs = new GZipStream(mso, CompressionMode.Compress))
{
msi.CopyTo(gs);
}
return mso.ToArray();
}
/// <summary>
/// Unzips a GZipped content.
/// </summary>
public static byte[] Unzip(byte[] bytes)
{
using var msi = new MemoryStream(bytes);
using var mso = new MemoryStream();
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
{
gs.CopyTo(mso);
}
return mso.ToArray();
}
}
}
| 412 | 0.712362 | 1 | 0.712362 | game-dev | MEDIA | 0.163157 | game-dev | 0.661146 | 1 | 0.661146 |
KingJiongEN/CivilServer | 2,579 | src/CityCommon/SimAgentBrain.cs | using Plugins.CityCommon.Msg;
using System;
using System.Collections.Generic;
public class SimAgentBrain
{
private SimAgent sim_agent;
public CityState city_state;
public int agent_guid;
public List<AgentPlanItem> plan;
public int cur_index_in_plan;
public LLmResponseAgentDecision decision;
public AgentPlanItem plan_to_execute_on_move_end;
public bool is_waiting_plan;
public bool is_waiting_decision;
public SimAgentBrainHelper agent_brain_helper;
public SimAgentBrain(SimAgent sim_agent, SimAgentBrainHelper agent_brain_helper)
{
this.sim_agent = sim_agent;
this.agent_brain_helper = agent_brain_helper;
}
public ISimAgentState WhatToDoNext()
{
MapObj obj = sim_agent.city_map.city_state.GetRandomMapObj();
sim_agent.target_place_guid = obj.guid;
sim_agent.target_pos = MyRandom.Choose(obj.interactive_pos_list);
return sim_agent.city_map.npc_state_pool.Get<SimAgentStateWalk>().Init(obj.guid, sim_agent.target_pos);
}
internal void OnNewDay()
{
if (agent_brain_helper != null)
{
if (!is_waiting_plan)
{
if (plan == null || plan.Count == 0 || cur_index_in_plan >= plan.Count)
{
//请求行程计划
RequestPlan();
}
}
}
}
/// <summary>
/// 流程:
/// 1. 向LLM发起请求行程决策
/// 2. 接收到决策,将决策写入到智能体的brain,临时存储
/// 3. 逻辑兜底时,执行行程活动,并消耗掉计划
/// 4. 行程计划消耗完,下一轮需请求新的行程
/// </summary>
private void RequestPlan()
{
if(agent_brain_helper!=null)
{
is_waiting_plan = agent_brain_helper.RequestPlan(sim_agent);
}
}
public void SetPlan(List<AgentPlanItem> plan)
{
is_waiting_plan = false;
this.plan = plan;
}
/// <summary>
/// 流程:
/// 1. 到达某个建筑后,发起眼下行为决策
/// 2. 执行决策行为
/// 3. 发起进一步行为决策,进一步执行行为
/// 4. 如果决策失败或决策要离开建筑,则开始向下一个建筑移动
/// </summary>
public void RequestDecision()
{
if (agent_brain_helper != null)
{
is_waiting_decision = agent_brain_helper.RequestDecision(sim_agent);
}
}
public void SetDecision(LLmResponseAgentDecision decision)
{
is_waiting_decision = false;
this.decision = decision;
if(decision!= null)
{
if(decision.place_interaction != null)
{
sim_agent.SetAttr(decision.place_interaction.attr_chagne);
}
}
}
} | 412 | 0.823072 | 1 | 0.823072 | game-dev | MEDIA | 0.378272 | game-dev | 0.876193 | 1 | 0.876193 |
stormcoph/LuminaClient | 1,424 | src/main/java/me/stormcph/lumina/module/impl/misc/ChatHandler.java | package me.stormcph.lumina.module.impl.misc;
import me.stormcph.lumina.event.EventTarget;
import me.stormcph.lumina.event.impl.PacketSendEvent;
import me.stormcph.lumina.module.Category;
import me.stormcph.lumina.module.Module;
import me.stormcph.lumina.module.impl.chat.ChatCommandManager;
import net.minecraft.network.packet.c2s.play.ChatMessageC2SPacket;
import java.util.List;
public class ChatHandler extends Module {
private final String prefix = "$";
public ChatHandler() {
super("ChatCommands", "// TODO", Category.MISC);
ChatCommandManager.init();
}
@EventTarget
public void onPacketSend(PacketSendEvent e){
if(nullCheck()) return;
if(e.getPacket() instanceof ChatMessageC2SPacket cmp) {
if(cmp.chatMessage().startsWith(prefix)){
e.cancel();
ChatCommandManager.findCommand(
cmp.chatMessage().replace(
prefix,
"").split(" ")[0]
).execute(
List.of(
cmp.chatMessage()
.replace(
prefix,
"")
.split(" ")
)
);
}
}
}
}
| 412 | 0.797634 | 1 | 0.797634 | game-dev | MEDIA | 0.644629 | game-dev | 0.840189 | 1 | 0.840189 |
ChaosAwakens/ChaosAwakens | 2,168 | src/main/java/io/github/chaosawakens/common/items/armor/EmeraldArmorItem.java | package io.github.chaosawakens.common.items.armor;
import io.github.chaosawakens.common.util.EnumUtil.CAArmorMaterial;
import io.github.chaosawakens.manager.CAConfigManager;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.ArmorItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import java.util.List;
public class EmeraldArmorItem extends ArmorItem {
public EmeraldArmorItem(CAArmorMaterial armorMaterial, EquipmentSlotType type, Properties properties) {
super(armorMaterial, type, properties);
}
@Override
public void appendHoverText(ItemStack stack, World world, List<ITextComponent> tooltip, ITooltipFlag flag) {
if (!CAConfigManager.MAIN_CLIENT.enableTooltips.get()) return;
super.appendHoverText(stack, world, tooltip, flag);
tooltip.add(new StringTextComponent("Full Set Bonus: ").withStyle(TextFormatting.GOLD).append(new StringTextComponent("Merchant's Aura").withStyle(TextFormatting.DARK_GREEN)).append(new StringTextComponent(" (...)").withStyle(TextFormatting.GREEN)));
if (Screen.hasShiftDown() || Screen.hasControlDown()) {
tooltip.removeIf((s) -> s.toString().contains("(...)"));
tooltip.add(new StringTextComponent("Full Set Bonus: ").withStyle(TextFormatting.GOLD).append(new StringTextComponent("Merchant's Aura").withStyle(TextFormatting.DARK_GREEN))
.append(new StringTextComponent("\nVillagers give you a ~" + (CAConfigManager.MAIN_COMMON.emeraldArmorDiscountMultiplier.get() / 8.0D) * 100 + "% Discount on items. Note that the maximum discount you can get is up to 99%, and that you cannot get a real 100% discount on trades with villagers.").withStyle(TextFormatting.GREEN)));
}
if (!CAConfigManager.MAIN_COMMON.enableEmeraldArmorSetBonus.get()) {
tooltip.add(new StringTextComponent("This full set bonus is disabled in the config!").withStyle(TextFormatting.RED).withStyle(TextFormatting.BOLD));
}
}
}
| 412 | 0.783614 | 1 | 0.783614 | game-dev | MEDIA | 0.992575 | game-dev | 0.980975 | 1 | 0.980975 |
swift/swift | 16,093 | 3rdParty/Breakpad/src/common/dwarf/dwarf2diehandler.h | // -*- mode: c++ -*-
// Copyright (c) 2010 Google Inc. All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * 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.
// Original author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>
// dwarf2reader::CompilationUnit is a simple and direct parser for
// DWARF data, but its handler interface is not convenient to use. In
// particular:
//
// - CompilationUnit calls Dwarf2Handler's member functions to report
// every attribute's value, regardless of what sort of DIE it is.
// As a result, the ProcessAttributeX functions end up looking like
// this:
//
// switch (parent_die_tag) {
// case DW_TAG_x:
// switch (attribute_name) {
// case DW_AT_y:
// handle attribute y of DIE type x
// ...
// } break;
// ...
// }
//
// In C++ it's much nicer to use virtual function dispatch to find
// the right code for a given case than to switch on the DIE tag
// like this.
//
// - Processing different kinds of DIEs requires different sets of
// data: lexical block DIEs have start and end addresses, but struct
// type DIEs don't. It would be nice to be able to have separate
// handler classes for separate kinds of DIEs, each with the members
// appropriate to its role, instead of having one handler class that
// needs to hold data for every DIE type.
//
// - There should be a separate instance of the appropriate handler
// class for each DIE, instead of a single object with tables
// tracking all the dies in the compilation unit.
//
// - It's not convenient to take some action after all a DIE's
// attributes have been seen, but before visiting any of its
// children. The only indication you have that a DIE's attribute
// list is complete is that you get either a StartDIE or an EndDIE
// call.
//
// - It's not convenient to make use of the tree structure of the
// DIEs. Skipping all the children of a given die requires
// maintaining state and returning false from StartDIE until we get
// an EndDIE call with the appropriate offset.
//
// This interface tries to take care of all that. (You're shocked, I'm sure.)
//
// Using the classes here, you provide an initial handler for the root
// DIE of the compilation unit. Each handler receives its DIE's
// attributes, and provides fresh handler objects for children of
// interest, if any. The three classes are:
//
// - DIEHandler: the base class for your DIE-type-specific handler
// classes.
//
// - RootDIEHandler: derived from DIEHandler, the base class for your
// root DIE handler class.
//
// - DIEDispatcher: derived from Dwarf2Handler, an instance of this
// invokes your DIE-type-specific handler objects.
//
// In detail:
//
// - Define handler classes specialized for the DIE types you're
// interested in. These handler classes must inherit from
// DIEHandler. Thus:
//
// class My_DW_TAG_X_Handler: public DIEHandler { ... };
// class My_DW_TAG_Y_Handler: public DIEHandler { ... };
//
// DIEHandler subclasses needn't correspond exactly to single DIE
// types, as shown here; the point is that you can have several
// different classes appropriate to different kinds of DIEs.
//
// - In particular, define a handler class for the compilation
// unit's root DIE, that inherits from RootDIEHandler:
//
// class My_DW_TAG_compile_unit_Handler: public RootDIEHandler { ... };
//
// RootDIEHandler inherits from DIEHandler, adding a few additional
// member functions for examining the compilation unit as a whole,
// and other quirks of rootness.
//
// - Then, create a DIEDispatcher instance, passing it an instance of
// your root DIE handler class, and use that DIEDispatcher as the
// dwarf2reader::CompilationUnit's handler:
//
// My_DW_TAG_compile_unit_Handler root_die_handler(...);
// DIEDispatcher die_dispatcher(&root_die_handler);
// CompilationUnit reader(sections, offset, bytereader, &die_dispatcher);
//
// Here, 'die_dispatcher' acts as a shim between 'reader' and the
// various DIE-specific handlers you have defined.
//
// - When you call reader.Start(), die_dispatcher behaves as follows,
// starting with your root die handler and the compilation unit's
// root DIE:
//
// - It calls the handler's ProcessAttributeX member functions for
// each of the DIE's attributes.
//
// - It calls the handler's EndAttributes member function. This
// should return true if any of the DIE's children should be
// visited, in which case:
//
// - For each of the DIE's children, die_dispatcher calls the
// DIE's handler's FindChildHandler member function. If that
// returns a pointer to a DIEHandler instance, then
// die_dispatcher uses that handler to process the child, using
// this procedure recursively. Alternatively, if
// FindChildHandler returns NULL, die_dispatcher ignores that
// child and its descendants.
//
// - When die_dispatcher has finished processing all the DIE's
// children, it invokes the handler's Finish() member function,
// and destroys the handler. (As a special case, it doesn't
// destroy the root DIE handler.)
//
// This allows the code for handling a particular kind of DIE to be
// gathered together in a single class, makes it easy to skip all the
// children or individual children of a particular DIE, and provides
// appropriate parental context for each die.
#ifndef COMMON_DWARF_DWARF2DIEHANDLER_H__
#define COMMON_DWARF_DWARF2DIEHANDLER_H__
#include <stdint.h>
#include <stack>
#include <string>
#include "common/dwarf/types.h"
#include "common/dwarf/dwarf2enums.h"
#include "common/dwarf/dwarf2reader.h"
#include "common/using_std_string.h"
namespace dwarf2reader {
// A base class for handlers for specific DIE types. The series of
// calls made on a DIE handler is as follows:
//
// - for each attribute of the DIE:
// - ProcessAttributeX()
// - EndAttributes()
// - if that returned true, then for each child:
// - FindChildHandler()
// - if that returns a non-NULL pointer to a new handler:
// - recurse, with the new handler and the child die
// - Finish()
// - destruction
class DIEHandler {
public:
DIEHandler() { }
virtual ~DIEHandler() { }
// When we visit a DIE, we first use these member functions to
// report the DIE's attributes and their values. These have the
// same restrictions as the corresponding member functions of
// dwarf2reader::Dwarf2Handler.
//
// Since DWARF does not specify in what order attributes must
// appear, avoid making decisions in these functions that would be
// affected by the presence of other attributes. The EndAttributes
// function is a more appropriate place for such work, as all the
// DIE's attributes have been seen at that point.
//
// The default definitions ignore the values they are passed.
virtual void ProcessAttributeUnsigned(enum DwarfAttribute attr,
enum DwarfForm form,
uint64 data) { }
virtual void ProcessAttributeSigned(enum DwarfAttribute attr,
enum DwarfForm form,
int64 data) { }
virtual void ProcessAttributeReference(enum DwarfAttribute attr,
enum DwarfForm form,
uint64 data) { }
virtual void ProcessAttributeBuffer(enum DwarfAttribute attr,
enum DwarfForm form,
const uint8_t *data,
uint64 len) { }
virtual void ProcessAttributeString(enum DwarfAttribute attr,
enum DwarfForm form,
const string& data) { }
virtual void ProcessAttributeSignature(enum DwarfAttribute attr,
enum DwarfForm form,
uint64 signture) { }
// Once we have reported all the DIE's attributes' values, we call
// this member function. If it returns false, we skip all the DIE's
// children. If it returns true, we call FindChildHandler on each
// child. If that returns a handler object, we use that to visit
// the child; otherwise, we skip the child.
//
// This is a good place to make decisions that depend on more than
// one attribute. DWARF does not specify in what order attributes
// must appear, so only when the EndAttributes function is called
// does the handler have a complete picture of the DIE's attributes.
//
// The default definition elects to ignore the DIE's children.
// You'll need to override this if you override FindChildHandler,
// but at least the default behavior isn't to pass the children to
// FindChildHandler, which then ignores them all.
virtual bool EndAttributes() { return false; }
// If EndAttributes returns true to indicate that some of the DIE's
// children might be of interest, then we apply this function to
// each of the DIE's children. If it returns a handler object, then
// we use that to visit the child DIE. If it returns NULL, we skip
// that child DIE (and all its descendants).
//
// OFFSET is the offset of the child; TAG indicates what kind of DIE
// it is.
//
// The default definition skips all children.
virtual DIEHandler *FindChildHandler(uint64 offset, enum DwarfTag tag) {
return NULL;
}
// When we are done processing a DIE, we call this member function.
// This happens after the EndAttributes call, all FindChildHandler
// calls (if any), and all operations on the children themselves (if
// any). We call Finish on every handler --- even if EndAttributes
// returns false.
virtual void Finish() { };
};
// A subclass of DIEHandler, with additional kludges for handling the
// compilation unit's root die.
class RootDIEHandler: public DIEHandler {
public:
RootDIEHandler() { }
virtual ~RootDIEHandler() { }
// We pass the values reported via Dwarf2Handler::StartCompilationUnit
// to this member function, and skip the entire compilation unit if it
// returns false. So the root DIE handler is actually also
// responsible for handling the compilation unit metadata.
// The default definition always visits the compilation unit.
virtual bool StartCompilationUnit(uint64 offset, uint8 address_size,
uint8 offset_size, uint64 cu_length,
uint8 dwarf_version) { return true; }
// For the root DIE handler only, we pass the offset, tag and
// attributes of the compilation unit's root DIE. This is the only
// way the root DIE handler can find the root DIE's tag. If this
// function returns true, we will visit the root DIE using the usual
// DIEHandler methods; otherwise, we skip the entire compilation
// unit.
//
// The default definition elects to visit the root DIE.
virtual bool StartRootDIE(uint64 offset, enum DwarfTag tag) { return true; }
};
class DIEDispatcher: public Dwarf2Handler {
public:
// Create a Dwarf2Handler which uses ROOT_HANDLER as the handler for
// the compilation unit's root die, as described for the DIEHandler
// class.
DIEDispatcher(RootDIEHandler *root_handler) : root_handler_(root_handler) { }
// Destroying a DIEDispatcher destroys all active handler objects
// except the root handler.
~DIEDispatcher();
bool StartCompilationUnit(uint64 offset, uint8 address_size,
uint8 offset_size, uint64 cu_length,
uint8 dwarf_version);
bool StartDIE(uint64 offset, enum DwarfTag tag);
void ProcessAttributeUnsigned(uint64 offset,
enum DwarfAttribute attr,
enum DwarfForm form,
uint64 data);
void ProcessAttributeSigned(uint64 offset,
enum DwarfAttribute attr,
enum DwarfForm form,
int64 data);
void ProcessAttributeReference(uint64 offset,
enum DwarfAttribute attr,
enum DwarfForm form,
uint64 data);
void ProcessAttributeBuffer(uint64 offset,
enum DwarfAttribute attr,
enum DwarfForm form,
const uint8_t *data,
uint64 len);
void ProcessAttributeString(uint64 offset,
enum DwarfAttribute attr,
enum DwarfForm form,
const string &data);
void ProcessAttributeSignature(uint64 offset,
enum DwarfAttribute attr,
enum DwarfForm form,
uint64 signature);
void EndDIE(uint64 offset);
private:
// The type of a handler stack entry. This includes some fields
// which don't really need to be on the stack --- they could just be
// single data members of DIEDispatcher --- but putting them here
// makes it easier to see that the code is correct.
struct HandlerStack {
// The offset of the DIE for this handler stack entry.
uint64 offset_;
// The handler object interested in this DIE's attributes and
// children. If NULL, we're not interested in either.
DIEHandler *handler_;
// Have we reported the end of this DIE's attributes to the handler?
bool reported_attributes_end_;
};
// Stack of DIE attribute handlers. At StartDIE(D), the top of the
// stack is the handler of D's parent, whom we may ask for a handler
// for D itself. At EndDIE(D), the top of the stack is D's handler.
// Special cases:
//
// - Before we've seen the compilation unit's root DIE, the stack is
// empty; we'll call root_handler_'s special member functions, and
// perhaps push root_handler_ on the stack to look at the root's
// immediate children.
//
// - When we decide to ignore a subtree, we only push an entry on
// the stack for the root of the tree being ignored, rather than
// pushing lots of stack entries with handler_ set to NULL.
std::stack<HandlerStack> die_handlers_;
// The root handler. We don't push it on die_handlers_ until we
// actually get the StartDIE call for the root.
RootDIEHandler *root_handler_;
};
} // namespace dwarf2reader
#endif // COMMON_DWARF_DWARF2DIEHANDLER_H__
| 412 | 0.94454 | 1 | 0.94454 | game-dev | MEDIA | 0.146121 | game-dev | 0.880857 | 1 | 0.880857 |
CalamityTeam/CalamityModPublic | 1,050 | Items/Placeables/FurnitureAbyss/AbyssLantern.cs | using CalamityMod.Tiles.Furniture.CraftingStations;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Items.Placeables.FurnitureAbyss
{
public class AbyssLantern : ModItem, ILocalizedModType
{
public new string LocalizationCategory => "Items.Placeables";
public override void SetDefaults()
{
Item.width = 26;
Item.height = 26;
Item.maxStack = 9999;
Item.useTurn = true;
Item.autoReuse = true;
Item.useAnimation = 15;
Item.useTime = 10;
Item.useStyle = ItemUseStyleID.Swing;
Item.consumable = true;
Item.value = 0;
Item.createTile = ModContent.TileType<Tiles.FurnitureAbyss.AbyssLantern>();
}
public override void AddRecipes()
{
CreateRecipe().
AddIngredient<SmoothAbyssGravel>(6).
AddIngredient(ItemID.Torch).
AddTile<VoidCondenser>().
Register();
}
}
}
| 412 | 0.755405 | 1 | 0.755405 | game-dev | MEDIA | 0.975432 | game-dev | 0.565476 | 1 | 0.565476 |
MarginaliaSearch/MarginaliaSearch | 3,403 | code/libraries/array/java/nu/marginalia/array/LongArrayFactory.java | package nu.marginalia.array;
import nu.marginalia.array.page.SegmentLongArray;
import nu.marginalia.array.page.UnsafeLongArray;
import java.io.IOException;
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.nio.file.Files;
import java.nio.file.Path;
public class LongArrayFactory {
private static final boolean useUnsafe = !Boolean.getBoolean("system.noSunMiscUnsafe");
public static LongArray onHeapConfined(long size) {
if (useUnsafe)
return UnsafeLongArray.onHeap(Arena.ofConfined(), size);
else
return SegmentLongArray.onHeap(Arena.ofConfined(), size);
}
public static LongArray onHeapShared(long size) {
if (useUnsafe)
return UnsafeLongArray.onHeap(Arena.ofShared(), size);
else
return SegmentLongArray.onHeap(Arena.ofShared(), size);
}
public static LongArray onHeapManaged(Arena arena, long size) {
if (useUnsafe)
return UnsafeLongArray.wrap(arena.allocate(8 * size));
else
return SegmentLongArray.wrap(arena.allocate(8 * size));
}
public static LongArray mmapForReadingConfined(Path filename) throws IOException {
if (useUnsafe)
return UnsafeLongArray.fromMmapReadOnly(Arena.ofConfined(), filename, 0, Files.size(filename) / 8);
else
return SegmentLongArray.fromMmapReadOnly(Arena.ofConfined(), filename, 0, Files.size(filename) / 8);
}
public static LongArray mmapForReadingShared(Path filename) throws IOException {
if (useUnsafe)
return UnsafeLongArray.fromMmapReadOnly(Arena.ofShared(), filename, 0, Files.size(filename) / 8);
else
return SegmentLongArray.fromMmapReadOnly(Arena.ofShared(), filename, 0, Files.size(filename) / 8);
}
public static LongArray mmapForModifyingConfined(Path filename) throws IOException {
if (useUnsafe)
return UnsafeLongArray.fromMmapReadWrite(Arena.ofConfined(), filename, 0, Files.size(filename));
else
return SegmentLongArray.fromMmapReadWrite(Arena.ofConfined(), filename, 0, Files.size(filename));
}
public static LongArray mmapForModifyingShared(Path filename) throws IOException {
if (useUnsafe)
return UnsafeLongArray.fromMmapReadWrite(Arena.ofShared(), filename, 0, Files.size(filename) / 8);
else
return SegmentLongArray.fromMmapReadWrite(Arena.ofShared(), filename, 0, Files.size(filename) / 8);
}
public static LongArray mmapForWritingConfined(Path filename, long size) throws IOException {
if (useUnsafe)
return UnsafeLongArray.fromMmapReadWrite(Arena.ofConfined(), filename, 0, size);
else
return SegmentLongArray.fromMmapReadWrite(Arena.ofConfined(), filename, 0, size);
}
public static LongArray mmapForWritingShared(Path filename, long size) throws IOException {
if (useUnsafe)
return UnsafeLongArray.fromMmapReadWrite(Arena.ofShared(), filename, 0, size);
else
return SegmentLongArray.fromMmapReadWrite(Arena.ofShared(), filename, 0, size);
}
public static LongArray wrap(MemorySegment ms) {
if (useUnsafe) {
return UnsafeLongArray.wrap(ms);
}
else {
return SegmentLongArray.wrap(ms);
}
}
}
| 412 | 0.711139 | 1 | 0.711139 | game-dev | MEDIA | 0.298007 | game-dev | 0.68429 | 1 | 0.68429 |
LangYa466/MCPLite-all-source | 9,816 | src/main/java/net/minecraft/client/gui/GuiVideoSettings.java | /*
* Decompiled with CFR 0.151.
*/
package net.minecraft.client.gui;
import java.io.IOException;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.gui.GuiOptionButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.src.Config;
import net.optifine.Lang;
import net.optifine.gui.GuiAnimationSettingsOF;
import net.optifine.gui.GuiDetailSettingsOF;
import net.optifine.gui.GuiOptionButtonOF;
import net.optifine.gui.GuiOptionSliderOF;
import net.optifine.gui.GuiOtherSettingsOF;
import net.optifine.gui.GuiPerformanceSettingsOF;
import net.optifine.gui.GuiQualitySettingsOF;
import net.optifine.gui.GuiScreenOF;
import net.optifine.gui.TooltipManager;
import net.optifine.gui.TooltipProviderOptions;
import net.optifine.shaders.gui.GuiShaders;
public class GuiVideoSettings
extends GuiScreenOF {
private GuiScreen parentGuiScreen;
protected String screenTitle = "Video SettingsButton";
private GameSettings guiGameSettings;
private static GameSettings.Options[] videoOptions = new GameSettings.Options[]{GameSettings.Options.GRAPHICS, GameSettings.Options.RENDER_DISTANCE, GameSettings.Options.AMBIENT_OCCLUSION, GameSettings.Options.FRAMERATE_LIMIT, GameSettings.Options.AO_LEVEL, GameSettings.Options.VIEW_BOBBING, GameSettings.Options.GUI_SCALE, GameSettings.Options.USE_VBO, GameSettings.Options.GAMMA, GameSettings.Options.BLOCK_ALTERNATIVES, GameSettings.Options.DYNAMIC_LIGHTS, GameSettings.Options.DYNAMIC_FOV};
private TooltipManager tooltipManager = new TooltipManager(this, new TooltipProviderOptions());
public GuiVideoSettings(GuiScreen parentScreenIn, GameSettings gameSettingsIn) {
this.parentGuiScreen = parentScreenIn;
this.guiGameSettings = gameSettingsIn;
}
@Override
public void initGui() {
this.screenTitle = I18n.format("options.videoTitle", new Object[0]);
this.buttonList.clear();
for (int i = 0; i < videoOptions.length; ++i) {
GameSettings.Options gamesettings$options = videoOptions[i];
if (gamesettings$options == null) continue;
int j = this.width / 2 - 155 + i % 2 * 160;
int k = this.height / 6 + 21 * (i / 2) - 12;
if (gamesettings$options.getEnumFloat()) {
this.buttonList.add(new GuiOptionSliderOF(gamesettings$options.returnEnumOrdinal(), j, k, gamesettings$options));
continue;
}
this.buttonList.add(new GuiOptionButtonOF(gamesettings$options.returnEnumOrdinal(), j, k, gamesettings$options, this.guiGameSettings.getKeyBinding(gamesettings$options)));
}
int l = this.height / 6 + 21 * (videoOptions.length / 2) - 12;
int i1 = 0;
i1 = this.width / 2 - 155 + 0;
this.buttonList.add(new GuiOptionButton(231, i1, l, Lang.get("of.options.shaders")));
i1 = this.width / 2 - 155 + 160;
this.buttonList.add(new GuiOptionButton(202, i1, l, Lang.get("of.options.quality")));
i1 = this.width / 2 - 155 + 0;
this.buttonList.add(new GuiOptionButton(201, i1, l += 21, Lang.get("of.options.details")));
i1 = this.width / 2 - 155 + 160;
this.buttonList.add(new GuiOptionButton(212, i1, l, Lang.get("of.options.performance")));
i1 = this.width / 2 - 155 + 0;
this.buttonList.add(new GuiOptionButton(211, i1, l += 21, Lang.get("of.options.animations")));
i1 = this.width / 2 - 155 + 160;
this.buttonList.add(new GuiOptionButton(222, i1, l, Lang.get("of.options.other")));
l += 21;
this.buttonList.add(new GuiButton(200, this.width / 2 - 100, this.height / 6 + 168 + 11, I18n.format("gui.done", new Object[0])));
}
@Override
protected void actionPerformed(GuiButton button) throws IOException {
this.actionPerformed(button, 1);
}
@Override
protected void actionPerformedRightClick(GuiButton p_actionPerformedRightClick_1_) {
if (p_actionPerformedRightClick_1_.id == GameSettings.Options.GUI_SCALE.ordinal()) {
this.actionPerformed(p_actionPerformedRightClick_1_, -1);
}
}
private void actionPerformed(GuiButton p_actionPerformed_1_, int p_actionPerformed_2_) {
if (p_actionPerformed_1_.enabled) {
int i = this.guiGameSettings.guiScale;
if (p_actionPerformed_1_.id < 200 && p_actionPerformed_1_ instanceof GuiOptionButton) {
this.guiGameSettings.setOptionValue(((GuiOptionButton)p_actionPerformed_1_).returnEnumOptions(), p_actionPerformed_2_);
p_actionPerformed_1_.displayString = this.guiGameSettings.getKeyBinding(GameSettings.Options.getEnumOptions(p_actionPerformed_1_.id));
}
if (p_actionPerformed_1_.id == 200) {
this.mc.gameSettings.saveOptions();
this.mc.displayGuiScreen(this.parentGuiScreen);
}
if (this.guiGameSettings.guiScale != i) {
ScaledResolution scaledresolution = new ScaledResolution(this.mc);
int j = scaledresolution.getScaledWidth();
int k = scaledresolution.getScaledHeight();
this.setWorldAndResolution(this.mc, j, k);
}
if (p_actionPerformed_1_.id == 201) {
this.mc.gameSettings.saveOptions();
GuiDetailSettingsOF guidetailsettingsof = new GuiDetailSettingsOF(this, this.guiGameSettings);
this.mc.displayGuiScreen(guidetailsettingsof);
}
if (p_actionPerformed_1_.id == 202) {
this.mc.gameSettings.saveOptions();
GuiQualitySettingsOF guiqualitysettingsof = new GuiQualitySettingsOF(this, this.guiGameSettings);
this.mc.displayGuiScreen(guiqualitysettingsof);
}
if (p_actionPerformed_1_.id == 211) {
this.mc.gameSettings.saveOptions();
GuiAnimationSettingsOF guianimationsettingsof = new GuiAnimationSettingsOF(this, this.guiGameSettings);
this.mc.displayGuiScreen(guianimationsettingsof);
}
if (p_actionPerformed_1_.id == 212) {
this.mc.gameSettings.saveOptions();
GuiPerformanceSettingsOF guiperformancesettingsof = new GuiPerformanceSettingsOF(this, this.guiGameSettings);
this.mc.displayGuiScreen(guiperformancesettingsof);
}
if (p_actionPerformed_1_.id == 222) {
this.mc.gameSettings.saveOptions();
GuiOtherSettingsOF guiothersettingsof = new GuiOtherSettingsOF(this, this.guiGameSettings);
this.mc.displayGuiScreen(guiothersettingsof);
}
if (p_actionPerformed_1_.id == 231) {
if (Config.isAntialiasing() || Config.isAntialiasingConfigured()) {
Config.showGuiMessage(Lang.get("of.message.shaders.aa1"), Lang.get("of.message.shaders.aa2"));
return;
}
if (Config.isAnisotropicFiltering()) {
Config.showGuiMessage(Lang.get("of.message.shaders.af1"), Lang.get("of.message.shaders.af2"));
return;
}
if (Config.isFastRender()) {
Config.showGuiMessage(Lang.get("of.message.shaders.fr1"), Lang.get("of.message.shaders.fr2"));
return;
}
if (Config.getGameSettings().anaglyph) {
Config.showGuiMessage(Lang.get("of.message.shaders.an1"), Lang.get("of.message.shaders.an2"));
return;
}
this.mc.gameSettings.saveOptions();
GuiShaders guishaders = new GuiShaders(this, this.guiGameSettings);
this.mc.displayGuiScreen(guishaders);
}
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
this.drawDefaultBackground();
this.drawCenteredString(this.fontRendererObj, this.screenTitle, this.width / 2, 15, 0xFFFFFF);
String s = Config.getVersion();
String s1 = "HD_U";
if (s1.equals("HD")) {
s = "OptiFine HD M6_pre2";
}
if (s1.equals("HD_U")) {
s = "OptiFine HD M6_pre2 Ultra";
}
if (s1.equals("L")) {
s = "OptiFine M6_pre2 Light";
}
this.drawString(this.fontRendererObj, s, 2, this.height - 10, 0x808080);
String s2 = "Minecraft 1.8.9";
int i = this.fontRendererObj.getStringWidth(s2);
this.drawString(this.fontRendererObj, s2, this.width - i - 2, this.height - 10, 0x808080);
super.drawScreen(mouseX, mouseY, partialTicks);
this.tooltipManager.drawTooltips(mouseX, mouseY, this.buttonList);
}
public static int getButtonWidth(GuiButton p_getButtonWidth_0_) {
return p_getButtonWidth_0_.width;
}
public static int getButtonHeight(GuiButton p_getButtonHeight_0_) {
return p_getButtonHeight_0_.height;
}
public static void drawGradientRect(GuiScreen p_drawGradientRect_0_, int p_drawGradientRect_1_, int p_drawGradientRect_2_, int p_drawGradientRect_3_, int p_drawGradientRect_4_, int p_drawGradientRect_5_, int p_drawGradientRect_6_) {
p_drawGradientRect_0_.drawGradientRect(p_drawGradientRect_1_, p_drawGradientRect_2_, p_drawGradientRect_3_, p_drawGradientRect_4_, p_drawGradientRect_5_, p_drawGradientRect_6_);
}
public static String getGuiChatText(GuiChat p_getGuiChatText_0_) {
return p_getGuiChatText_0_.inputField.getText();
}
}
| 412 | 0.886062 | 1 | 0.886062 | game-dev | MEDIA | 0.843779 | game-dev | 0.961353 | 1 | 0.961353 |
DS-Homebrew/nds-bootstrap | 1,064 | retail/cardenginei/arm9_colorlut/source/card_engine_header.s | @---------------------------------------------------------------------------------
.section ".init"
@---------------------------------------------------------------------------------
.align 4
.arm
card_engine_start:
b applyColorLut
.global flags
flags:
.word 0
.word saveMobiclipFrameDst
.word applyColorLutMobiclip
.word applyColorLutCastlevaniaDoSVideo
saveEarlyMobiclipFrameDst:
mov r10, #0xC0
saveMobiclipFrameDst:
adr r11, mobiclipFrameHeight
str r10, [r11]
ldr r1, [r0,#4]
ldr r2, [r0,#8]
adr r11, mobiclipFrameDst
str r2, [r11]
ldr r2, =0x03733800 @ new frame dst
ldr r0, [r0]
add lr, #4
bx lr
applyColorLutMobiclip:
mov r0, r2
bl applyColorLutBitmap
ldmfd sp!, {r4-r12,pc}
applyColorLutCastlevaniaDoSVideo:
stmfd sp!, {r4-r5,lr}
mov r4, #0xC0
adr r5, mobiclipFrameHeight
str r4, [r5]
adr r5, mobiclipFrameDst
str r2, [r5]
mov r0, r1
add r0, r3
bl applyColorLutBitmap
ldmfd sp!, {r4-r5,pc}
.global mobiclipFrameHeight
mobiclipFrameHeight:
.word 0
.global mobiclipFrameDst
mobiclipFrameDst:
.word 0
.pool
card_engine_end:
| 412 | 0.688662 | 1 | 0.688662 | game-dev | MEDIA | 0.281736 | game-dev | 0.714979 | 1 | 0.714979 |
Midnighter/structurizr-python | 9,243 | src/structurizr/view/deployment_view.py | # 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
#
# https://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.
"""Provide a deployment view.
Used to show the mapping of container instances to deployment nodes.
"""
from typing import Iterable, List, Optional, Union
from ..mixin.model_ref_mixin import ModelRefMixin
from ..model.container_instance import ContainerInstance
from ..model.deployment_element import DeploymentElement
from ..model.deployment_node import DeploymentNode
from ..model.infrastructure_node import InfrastructureNode
from ..model.relationship import Relationship
from ..model.software_system_instance import SoftwareSystemInstance
from ..model.static_structure_element import StaticStructureElement
from .animation import Animation, AnimationIO
from .view import View, ViewIO
__all__ = ("DeploymentView", "DeploymentViewIO")
class DeploymentViewIO(ViewIO):
"""
Represent a deployment view.
Attributes:
environment: the name of the environment that this deployment view is for
(e.g. "Development", "Live", etc.)
animations: the set of animation steps (optional)
"""
environment: Optional[str] = None
animations: List[AnimationIO] = []
class DeploymentView(ModelRefMixin, View):
"""Represent a deployment view.
Deployment views are used to show the mapping of container instances to deployment
nodes.
"""
def __init__(
self,
*,
environment: Optional[str] = None,
animations: Optional[Iterable[Animation]] = None,
**kwargs,
) -> None:
"""Initialize a deployment view."""
super().__init__(**kwargs)
self._environment = environment
self._animations = [] if animations is None else list(animations)
@property
def environment(self):
"""Get the name of the environment that this view is for.
E.g. "Development", "Live", etc.
"""
return self._environment
def add_default_elements(self):
"""Add the default set of elements to this view."""
self.add_all_deployment_nodes()
def add_all_deployment_nodes(self):
"""Add all of the top-level deployment nodes to this view.
If the environment is set in this view, then only nodes from the same
environment will be added.
"""
for deployment_node in self.model.deployment_nodes: # This returns top-level
if (
self.environment is None
or self.environment == deployment_node.environment
):
self.add(deployment_node)
def add(
self, item: Union[DeploymentNode, Relationship], add_relationships: bool = True
):
"""Add a deployment node or relationship to this view."""
if isinstance(item, DeploymentNode):
if self._add_node_children(item, add_relationships):
parent = item.parent
while parent is not None:
self._add_element(parent, add_relationships)
parent = parent.parent
else:
self._add_relationship(item)
def __iadd__(self, item: Union[DeploymentNode, Relationship]) -> "DeploymentView":
"""Add a deployment node or relationship to this view."""
self.add(item)
return self
def remove(
self,
item: Union[
DeploymentNode,
InfrastructureNode,
ContainerInstance,
SoftwareSystemInstance,
],
):
"""Remove the given item from this view."""
if isinstance(item, DeploymentNode):
child_items = (
item.container_instances
+ item.software_system_instances
+ item.infrastructure_nodes
+ item.children
)
for child in child_items:
self.remove(child)
self._remove_element(item)
def _add_node_children(
self, deployment_node: DeploymentNode, add_relationships: bool
):
has_elements_or_relationships = False
for instance in deployment_node.software_system_instances:
self._add_element(instance, add_relationships)
has_elements_or_relationships = True
for instance in deployment_node.container_instances:
container = instance.container
if self.software_system is None or container.parent is self.software_system:
self._add_element(instance, add_relationships)
has_elements_or_relationships = True
for node in deployment_node.infrastructure_nodes:
self._add_element(node, add_relationships)
has_elements_or_relationships = True
for child in deployment_node.children:
has_elements_or_relationships |= self._add_node_children(
child, add_relationships
)
if has_elements_or_relationships:
self._add_element(deployment_node, add_relationships)
return has_elements_or_relationships
@property
def name(self):
"""Get the (computed) name of this view."""
name = (
"Deployment"
if self.software_system is None
else f"{self.software_system.name} - Deployment"
)
if self.environment:
name = f"{name} - {self.environment}"
return name
def add_animation(
self, *element_instances: Union[StaticStructureElement, InfrastructureNode]
):
"""Add an animation step, with the given elements and infrastructure nodes."""
if len(element_instances) == 0:
raise ValueError(
"One or more software system/container instances and/or "
+ "infrastructure nodes must be specified"
)
element_ids_in_previous_steps = set()
for step in self.animations:
element_ids_in_previous_steps = element_ids_in_previous_steps.union(
step.elements
)
element_ids_in_this_step = set()
relationship_ids_in_this_step = set()
for element in element_instances:
if (
self.is_element_in_view(element)
and element.id not in element_ids_in_previous_steps
):
element_ids_in_previous_steps.add(element.id)
element_ids_in_this_step.add(element.id)
deployment_node = self._find_deployment_node(element)
while deployment_node is not None:
if deployment_node.id not in element_ids_in_previous_steps:
element_ids_in_previous_steps.add(deployment_node.id)
element_ids_in_this_step.add(deployment_node.id)
deployment_node = deployment_node.parent
if element_ids_in_this_step == set():
raise ValueError("None of the specified instances exist in this view.")
for relationship_view in self.relationship_views:
relationship = relationship_view.relationship
if (
relationship.source.id in element_ids_in_this_step
and relationship.destination.id in element_ids_in_previous_steps
) or (
relationship.destination.id in element_ids_in_this_step
and relationship.source.id in element_ids_in_previous_steps
):
relationship_ids_in_this_step.add(relationship.id)
self._animations.append(
Animation(
order=len(self._animations) + 1,
elements=element_ids_in_this_step,
relationships=relationship_ids_in_this_step,
)
)
def _find_deployment_node(self, element: DeploymentElement) -> DeploymentNode:
all_deployment_nodes = [
e for e in self.model.get_elements() if isinstance(e, DeploymentNode)
]
for node in all_deployment_nodes:
if (
element in node.container_instances
or element in node.software_system_instances
or element in node.infrastructure_nodes
):
return node
return None
@property
def animations(self) -> Iterable[Animation]:
"""Return the animations for this view."""
return list(self._animations)
@classmethod
def hydrate(cls, deployment_view_io: DeploymentViewIO) -> "DeploymentView":
"""Hydrate a new DeploymentView instance from its IO."""
return cls(
environment=deployment_view_io.environment,
animations=map(Animation.hydrate, deployment_view_io.animations),
**cls.hydrate_arguments(deployment_view_io),
)
| 412 | 0.883529 | 1 | 0.883529 | game-dev | MEDIA | 0.226339 | game-dev | 0.869523 | 1 | 0.869523 |
frogatto/frogatto | 2,438 | data/classes/mook_spawning_tracker.cfg | {
#-------------------------- spawning criterion --------------------------#
max_objects: { type: "int", dynamic_initialization: true },
spawnee_types: { type: "[string]", dynamic_initialization: true },
#-------------------------- culling criterion --------------------------#
_x_bound: { type: "int|null", default: null },
_x2_bound: { type: "int|null", default: null },
_y_bound: { type: "int|null", default: null },
_y2_bound: { type: "int|null", default: null },
is_alive: "def(custom_obj _obj) -> bool (_obj.hitpoints > 0) and (_obj in this_obj.level.chars)",
is_within_x_bounds: "def(custom_obj _obj) -> bool if(not (_x_bound = null or _x2_bound = null) , (_obj.mid_x > _x_bound and _obj.mid_x < _x2_bound), true)",
is_within_y_bounds: "def(custom_obj _obj) -> bool if(not (_y_bound = null or _y2_bound = null) , (_obj.mid_y > _y_bound and _obj.mid_y < _y2_bound), true)",
#-------------------------- storage --------------------------#
this_obj: { type: "custom_obj", dynamic_initialization: true },
#-------------------------- direct tracking logic --------------------------#
/*
An alternate system for our mook trackers is to directly track all the spawned objects via references. Note that this means the provided bounds are meaningless and will not factor into whether an object is tracked, if this setting is used. This is desirable because for some kinds of spawners, there's no good way to arrange the level geometry to keep them from spawning too many enemies.
If we use this, one has the additional requirement to register each object upon spawn.
*/
directly_tracks_objects: { type: "bool", init: "false" },
_tracked_objects: { type: "[custom_obj]", init: "[]" },
register_tracked_object: "def(custom_obj addee) -> commands add(_tracked_objects, [addee])",
#-------------------------- processing --------------------------#
process_list: "commands :: set(_tracked_objects, filter(_tracked_objects, is_alive(value)))",
current_mooks: "[custom_obj] :: if(directly_tracks_objects,
_tracked_objects,
filter(current_level().chars, (value.type in spawnee_types) and is_within_x_bounds(value) and is_within_y_bounds(value) and is_alive(value))
)",
//the client using this must actually do the work of attaching the mook to the level, since that's the behavior that differs between different kinds of objects
should_create_a_new_mook: "(size(current_mooks) < max_objects)",
}
| 412 | 0.824909 | 1 | 0.824909 | game-dev | MEDIA | 0.607047 | game-dev | 0.764759 | 1 | 0.764759 |
fusijie/Airplane_3.0 | 8,786 | cocos2d/external/chipmunk/include/chipmunk/cpArbiter.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.
*/
/// @defgroup cpArbiter cpArbiter
/// The cpArbiter struct controls pairs of colliding shapes.
/// They are also used in conjuction with collision handler callbacks
/// allowing you to retrieve information on the collision and control it.
/// @{
/// Collision begin event function callback type.
/// Returning false from a begin callback causes the collision to be ignored until
/// the the separate callback is called when the objects stop colliding.
typedef cpBool (*cpCollisionBeginFunc)(cpArbiter *arb, cpSpace *space, void *data);
/// Collision pre-solve event function callback type.
/// Returning false from a pre-step callback causes the collision to be ignored until the next step.
typedef cpBool (*cpCollisionPreSolveFunc)(cpArbiter *arb, cpSpace *space, void *data);
/// Collision post-solve event function callback type.
typedef void (*cpCollisionPostSolveFunc)(cpArbiter *arb, cpSpace *space, void *data);
/// Collision separate event function callback type.
typedef void (*cpCollisionSeparateFunc)(cpArbiter *arb, cpSpace *space, void *data);
/// @private
struct cpCollisionHandler {
cpCollisionType a;
cpCollisionType b;
cpCollisionBeginFunc begin;
cpCollisionPreSolveFunc preSolve;
cpCollisionPostSolveFunc postSolve;
cpCollisionSeparateFunc separate;
void *data;
};
typedef struct cpContact cpContact;
#define CP_MAX_CONTACTS_PER_ARBITER 2
/// @private
typedef enum cpArbiterState {
// Arbiter is active and its the first collision.
cpArbiterStateFirstColl,
// Arbiter is active and its not the first collision.
cpArbiterStateNormal,
// Collision has been explicitly ignored.
// Either by returning false from a begin collision handler or calling cpArbiterIgnore().
cpArbiterStateIgnore,
// Collison is no longer active. A space will cache an arbiter for up to cpSpace.collisionPersistence more steps.
cpArbiterStateCached,
} cpArbiterState;
/// @private
struct cpArbiterThread {
// Links to next and previous arbiters in the contact graph.
struct cpArbiter *next, *prev;
};
/// A colliding pair of shapes.
struct cpArbiter {
/// Calculated value to use for the elasticity coefficient.
/// Override in a pre-solve collision handler for custom behavior.
cpFloat e;
/// Calculated value to use for the friction coefficient.
/// Override in a pre-solve collision handler for custom behavior.
cpFloat u;
/// Calculated value to use for applying surface velocities.
/// Override in a pre-solve collision handler for custom behavior.
cpVect surface_vr;
/// User definable data pointer.
/// The value will persist for the pair of shapes until the separate() callback is called.
/// NOTE: If you need to clean up this pointer, you should implement the separate() callback to do it.
cpDataPointer data;
CP_PRIVATE(cpShape *a);
CP_PRIVATE(cpShape *b);
CP_PRIVATE(cpBody *body_a);
CP_PRIVATE(cpBody *body_b);
CP_PRIVATE(struct cpArbiterThread thread_a);
CP_PRIVATE(struct cpArbiterThread thread_b);
CP_PRIVATE(int numContacts);
CP_PRIVATE(cpContact *contacts);
CP_PRIVATE(cpTimestamp stamp);
CP_PRIVATE(cpCollisionHandler *handler);
CP_PRIVATE(cpBool swappedColl);
CP_PRIVATE(cpArbiterState state);
};
#define CP_DefineArbiterStructGetter(type, member, name) \
static inline type cpArbiterGet##name(const cpArbiter *arb){return arb->member;}
#define CP_DefineArbiterStructSetter(type, member, name) \
static inline void cpArbiterSet##name(cpArbiter *arb, type value){arb->member = value;}
#define CP_DefineArbiterStructProperty(type, member, name) \
CP_DefineArbiterStructGetter(type, member, name) \
CP_DefineArbiterStructSetter(type, member, name)
CP_DefineArbiterStructProperty(cpFloat, e, Elasticity)
CP_DefineArbiterStructProperty(cpFloat, u, Friction)
// Get the relative surface velocity of the two shapes in contact.
cpVect cpArbiterGetSurfaceVelocity(cpArbiter *arb);
// Override the relative surface velocity of the two shapes in contact.
// By default this is calculated to be the difference of the two
// surface velocities clamped to the tangent plane.
void cpArbiterSetSurfaceVelocity(cpArbiter *arb, cpVect vr);
CP_DefineArbiterStructProperty(cpDataPointer, data, UserData)
/// Calculate the total impulse that was applied by this arbiter.
/// This function should only be called from a post-solve, post-step or cpBodyEachArbiter callback.
cpVect cpArbiterTotalImpulse(const cpArbiter *arb);
/// Calculate the total impulse including the friction that was applied by this arbiter.
/// This function should only be called from a post-solve, post-step or cpBodyEachArbiter callback.
cpVect cpArbiterTotalImpulseWithFriction(const cpArbiter *arb);
/// Calculate the amount of energy lost in a collision including static, but not dynamic friction.
/// This function should only be called from a post-solve, post-step or cpBodyEachArbiter callback.
cpFloat cpArbiterTotalKE(const cpArbiter *arb);
/// Causes a collision pair to be ignored as if you returned false from a begin callback.
/// If called from a pre-step callback, you will still need to return false
/// if you want it to be ignored in the current step.
void cpArbiterIgnore(cpArbiter *arb);
/// Return the colliding shapes involved for this arbiter.
/// The order of their cpSpace.collision_type values will match
/// the order set when the collision handler was registered.
static inline void cpArbiterGetShapes(const cpArbiter *arb, cpShape **a, cpShape **b)
{
if(arb->CP_PRIVATE(swappedColl)){
(*a) = arb->CP_PRIVATE(b), (*b) = arb->CP_PRIVATE(a);
} else {
(*a) = arb->CP_PRIVATE(a), (*b) = arb->CP_PRIVATE(b);
}
}
/// A macro shortcut for defining and retrieving the shapes from an arbiter.
#define CP_ARBITER_GET_SHAPES(__arb__, __a__, __b__) cpShape *__a__, *__b__; cpArbiterGetShapes(__arb__, &__a__, &__b__);
/// Return the colliding bodies involved for this arbiter.
/// The order of the cpSpace.collision_type the bodies are associated with values will match
/// the order set when the collision handler was registered.
static inline void cpArbiterGetBodies(const cpArbiter *arb, cpBody **a, cpBody **b)
{
CP_ARBITER_GET_SHAPES(arb, shape_a, shape_b);
(*a) = shape_a->body;
(*b) = shape_b->body;
}
/// A macro shortcut for defining and retrieving the bodies from an arbiter.
#define CP_ARBITER_GET_BODIES(__arb__, __a__, __b__) cpBody *__a__, *__b__; cpArbiterGetBodies(__arb__, &__a__, &__b__);
/// A struct that wraps up the important collision data for an arbiter.
typedef struct cpContactPointSet {
/// The number of contact points in the set.
int count;
/// The array of contact points.
struct {
/// The position of the contact point.
cpVect point;
/// The normal of the contact point.
cpVect normal;
/// The depth of the contact point.
cpFloat dist;
} points[CP_MAX_CONTACTS_PER_ARBITER];
} cpContactPointSet;
/// Return a contact set from an arbiter.
cpContactPointSet cpArbiterGetContactPointSet(const cpArbiter *arb);
/// Replace the contact point set for an arbiter.
/// This can be a very powerful feature, but use it with caution!
void cpArbiterSetContactPointSet(cpArbiter *arb, cpContactPointSet *set);
/// Returns true if this is the first step a pair of objects started colliding.
cpBool cpArbiterIsFirstContact(const cpArbiter *arb);
/// Get the number of contact points for this arbiter.
int cpArbiterGetCount(const cpArbiter *arb);
/// Get the normal of the @c ith contact point.
cpVect cpArbiterGetNormal(const cpArbiter *arb, int i);
/// Get the position of the @c ith contact point.
cpVect cpArbiterGetPoint(const cpArbiter *arb, int i);
/// Get the depth of the @c ith contact point.
cpFloat cpArbiterGetDepth(const cpArbiter *arb, int i);
/// @}
| 412 | 0.956237 | 1 | 0.956237 | game-dev | MEDIA | 0.615993 | game-dev | 0.772319 | 1 | 0.772319 |
sonosaurus/sonobus | 9,164 | deps/juce/examples/Assets/Box2DTests/DynamicTreeTest.h | /*
* Copyright (c) 2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef DYNAMIC_TREE_TEST_H
#define DYNAMIC_TREE_TEST_H
class DynamicTreeTest : public Test
{
public:
enum
{
e_actorCount = 128
};
DynamicTreeTest()
{
m_worldExtent = 15.0f;
m_proxyExtent = 0.5f;
srand(888);
for (int32 i = 0; i < e_actorCount; ++i)
{
Actor* actor = m_actors + i;
GetRandomAABB(&actor->aabb);
actor->proxyId = m_tree.CreateProxy(actor->aabb, actor);
}
m_stepCount = 0;
float32 h = m_worldExtent;
m_queryAABB.lowerBound.Set(-3.0f, -4.0f + h);
m_queryAABB.upperBound.Set(5.0f, 6.0f + h);
m_rayCastInput.p1.Set(-5.0, 5.0f + h);
m_rayCastInput.p2.Set(7.0f, -4.0f + h);
//m_rayCastInput.p1.Set(0.0f, 2.0f + h);
//m_rayCastInput.p2.Set(0.0f, -2.0f + h);
m_rayCastInput.maxFraction = 1.0f;
m_automated = false;
}
static Test* Create()
{
return new DynamicTreeTest;
}
void Step(Settings* settings)
{
B2_NOT_USED(settings);
m_rayActor = NULL;
for (int32 i = 0; i < e_actorCount; ++i)
{
m_actors[i].fraction = 1.0f;
m_actors[i].overlap = false;
}
if (m_automated == true)
{
int32 actionCount = b2Max(1, e_actorCount >> 2);
for (int32 i = 0; i < actionCount; ++i)
{
Action();
}
}
Query();
RayCast();
for (int32 i = 0; i < e_actorCount; ++i)
{
Actor* actor = m_actors + i;
if (actor->proxyId == b2_nullNode)
continue;
b2Color c(0.9f, 0.9f, 0.9f);
if (actor == m_rayActor && actor->overlap)
{
c.Set(0.9f, 0.6f, 0.6f);
}
else if (actor == m_rayActor)
{
c.Set(0.6f, 0.9f, 0.6f);
}
else if (actor->overlap)
{
c.Set(0.6f, 0.6f, 0.9f);
}
m_debugDraw.DrawAABB(&actor->aabb, c);
}
b2Color c(0.7f, 0.7f, 0.7f);
m_debugDraw.DrawAABB(&m_queryAABB, c);
m_debugDraw.DrawSegment(m_rayCastInput.p1, m_rayCastInput.p2, c);
b2Color c1(0.2f, 0.9f, 0.2f);
b2Color c2(0.9f, 0.2f, 0.2f);
m_debugDraw.DrawPoint(m_rayCastInput.p1, 6.0f, c1);
m_debugDraw.DrawPoint(m_rayCastInput.p2, 6.0f, c2);
if (m_rayActor)
{
b2Color cr(0.2f, 0.2f, 0.9f);
b2Vec2 p = m_rayCastInput.p1 + m_rayActor->fraction * (m_rayCastInput.p2 - m_rayCastInput.p1);
m_debugDraw.DrawPoint(p, 6.0f, cr);
}
{
int32 height = m_tree.GetHeight();
m_debugDraw.DrawString(5, m_textLine, "dynamic tree height = %d", height);
m_textLine += 15;
}
++m_stepCount;
}
void Keyboard(unsigned char key)
{
switch (key)
{
case 'a':
m_automated = !m_automated;
break;
case 'c':
CreateProxy();
break;
case 'd':
DestroyProxy();
break;
case 'm':
MoveProxy();
break;
}
}
bool QueryCallback(int32 proxyId)
{
Actor* actor = (Actor*)m_tree.GetUserData(proxyId);
actor->overlap = b2TestOverlap(m_queryAABB, actor->aabb);
return true;
}
float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId)
{
Actor* actor = (Actor*)m_tree.GetUserData(proxyId);
b2RayCastOutput output;
bool hit = actor->aabb.RayCast(&output, input);
if (hit)
{
m_rayCastOutput = output;
m_rayActor = actor;
m_rayActor->fraction = output.fraction;
return output.fraction;
}
return input.maxFraction;
}
private:
struct Actor
{
b2AABB aabb;
float32 fraction;
bool overlap;
int32 proxyId;
};
void GetRandomAABB(b2AABB* aabb)
{
b2Vec2 w; w.Set(2.0f * m_proxyExtent, 2.0f * m_proxyExtent);
//aabb->lowerBound.x = -m_proxyExtent;
//aabb->lowerBound.y = -m_proxyExtent + m_worldExtent;
aabb->lowerBound.x = RandomFloat(-m_worldExtent, m_worldExtent);
aabb->lowerBound.y = RandomFloat(0.0f, 2.0f * m_worldExtent);
aabb->upperBound = aabb->lowerBound + w;
}
void MoveAABB(b2AABB* aabb)
{
b2Vec2 d;
d.x = RandomFloat(-0.5f, 0.5f);
d.y = RandomFloat(-0.5f, 0.5f);
//d.x = 2.0f;
//d.y = 0.0f;
aabb->lowerBound += d;
aabb->upperBound += d;
b2Vec2 c0 = 0.5f * (aabb->lowerBound + aabb->upperBound);
b2Vec2 min; min.Set(-m_worldExtent, 0.0f);
b2Vec2 max; max.Set(m_worldExtent, 2.0f * m_worldExtent);
b2Vec2 c = b2Clamp(c0, min, max);
aabb->lowerBound += c - c0;
aabb->upperBound += c - c0;
}
void CreateProxy()
{
for (int32 i = 0; i < e_actorCount; ++i)
{
int32 j = rand() % e_actorCount;
Actor* actor = m_actors + j;
if (actor->proxyId == b2_nullNode)
{
GetRandomAABB(&actor->aabb);
actor->proxyId = m_tree.CreateProxy(actor->aabb, actor);
return;
}
}
}
void DestroyProxy()
{
for (int32 i = 0; i < e_actorCount; ++i)
{
int32 j = rand() % e_actorCount;
Actor* actor = m_actors + j;
if (actor->proxyId != b2_nullNode)
{
m_tree.DestroyProxy(actor->proxyId);
actor->proxyId = b2_nullNode;
return;
}
}
}
void MoveProxy()
{
for (int32 i = 0; i < e_actorCount; ++i)
{
int32 j = rand() % e_actorCount;
Actor* actor = m_actors + j;
if (actor->proxyId == b2_nullNode)
{
continue;
}
b2AABB aabb0 = actor->aabb;
MoveAABB(&actor->aabb);
b2Vec2 displacement = actor->aabb.GetCenter() - aabb0.GetCenter();
m_tree.MoveProxy(actor->proxyId, actor->aabb, displacement);
return;
}
}
void Action()
{
int32 choice = rand() % 20;
switch (choice)
{
case 0:
CreateProxy();
break;
case 1:
DestroyProxy();
break;
default:
MoveProxy();
}
}
void Query()
{
m_tree.Query(this, m_queryAABB);
for (int32 i = 0; i < e_actorCount; ++i)
{
if (m_actors[i].proxyId == b2_nullNode)
{
continue;
}
bool overlap = b2TestOverlap(m_queryAABB, m_actors[i].aabb);
B2_NOT_USED(overlap);
b2Assert(overlap == m_actors[i].overlap);
}
}
void RayCast()
{
m_rayActor = NULL;
b2RayCastInput input = m_rayCastInput;
// Ray cast against the dynamic tree.
m_tree.RayCast(this, input);
// Brute force ray cast.
Actor* bruteActor = NULL;
b2RayCastOutput bruteOutput;
for (int32 i = 0; i < e_actorCount; ++i)
{
if (m_actors[i].proxyId == b2_nullNode)
{
continue;
}
b2RayCastOutput output;
bool hit = m_actors[i].aabb.RayCast(&output, input);
if (hit)
{
bruteActor = m_actors + i;
bruteOutput = output;
input.maxFraction = output.fraction;
}
}
if (bruteActor != NULL)
{
b2Assert(bruteOutput.fraction == m_rayCastOutput.fraction);
}
}
float32 m_worldExtent;
float32 m_proxyExtent;
b2DynamicTree m_tree;
b2AABB m_queryAABB;
b2RayCastInput m_rayCastInput;
b2RayCastOutput m_rayCastOutput;
Actor* m_rayActor;
Actor m_actors[e_actorCount];
int32 m_stepCount;
bool m_automated;
};
#endif
| 412 | 0.774608 | 1 | 0.774608 | game-dev | MEDIA | 0.911164 | game-dev | 0.950036 | 1 | 0.950036 |
alexbatalov/fallout2-ce | 71,242 | src/proto.cc | #include "proto.h"
#include <stdio.h>
#include <string.h>
#include "art.h"
#include "character_editor.h"
#include "combat.h"
#include "config.h"
#include "critter.h"
#include "debug.h"
#include "dialog.h"
#include "game.h"
#include "game_movie.h"
#include "interface.h"
#include "map.h"
#include "memory.h"
#include "object.h"
#include "perk.h"
#include "settings.h"
#include "skill.h"
#include "stat.h"
#include "trait.h"
namespace fallout {
static int objectCritterCombatDataRead(CritterCombatData* data, File* stream);
static int objectCritterCombatDataWrite(CritterCombatData* data, File* stream);
static int _proto_update_gen(Object* obj);
static int _proto_header_load();
static int protoItemDataRead(ItemProtoData* item_data, int type, File* stream);
static int protoSceneryDataRead(SceneryProtoData* scenery_data, int type, File* stream);
static int protoRead(Proto* buf, File* stream);
static int protoItemDataWrite(ItemProtoData* item_data, int type, File* stream);
static int protoSceneryDataWrite(SceneryProtoData* scenery_data, int type, File* stream);
static int protoWrite(Proto* buf, File* stream);
static int _proto_load_pid(int pid, Proto** out_proto);
static int _proto_find_free_subnode(int type, Proto** out_ptr);
static void _proto_remove_some_list(int type);
static void _proto_remove_list(int type);
static int _proto_new_id(int type);
// 0x50CF3C
static char _aProto_0[] = "proto\\";
// 0x50D1B0
static char _aDrugStatSpecia[] = "Drug Stat (Special)";
// 0x50D1C4
static char _aNone_1[] = "None";
// 0x51C18C
char _cd_path_base[COMPAT_MAX_PATH];
// 0x51C290
static ProtoList _protoLists[11] = {
{ nullptr, nullptr, 0, 1 },
{ nullptr, nullptr, 0, 1 },
{ nullptr, nullptr, 0, 1 },
{ nullptr, nullptr, 0, 1 },
{ nullptr, nullptr, 0, 1 },
{ nullptr, nullptr, 0, 1 },
{ nullptr, nullptr, 0, 1 },
{ nullptr, nullptr, 0, 0 },
{ nullptr, nullptr, 0, 0 },
{ nullptr, nullptr, 0, 0 },
{ nullptr, nullptr, 0, 0 },
};
// 0x51C340
static const size_t _proto_sizes[11] = {
sizeof(ItemProto), // 0x84
sizeof(CritterProto), // 0x1A0
sizeof(SceneryProto), // 0x38
sizeof(WallProto), // 0x24
sizeof(TileProto), // 0x1C
sizeof(MiscProto), // 0x1C
0,
0,
0,
0,
0,
};
// 0x51C36C
static int _protos_been_initialized = 0;
// obj_dude_proto
// 0x51C370
static CritterProto gDudeProto = {
0x1000000,
-1,
0x1000001,
0,
0,
0x20000000,
0,
-1,
0,
{ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 18, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 23, 0 },
{ 0 },
{ 0 },
0,
0,
0,
0,
-1,
0,
0,
};
// 0x51C534
static char* _proto_path_base = _aProto_0;
// 0x51C538
static int _init_true = 0;
// 0x51C53C
static int _retval = 0;
// 0x66452C
static char* _mp_perk_code_None;
// 0x664530
static char* _mp_perk_code_strs[PERK_COUNT];
// 0x66470C
static char* _mp_critter_stats_list;
// 0x664710
static char* _critter_stats_list_None;
// 0x664714
static char* _critter_stats_list_strs[STAT_COUNT];
// Message list by object type
// 0 - pro_item.msg
// 1 - pro_crit.msg
// 2 - pro_scen.msg
// 3 - pro_wall.msg
// 4 - pro_tile.msg
// 5 - pro_misc.msg
//
// 0x6647AC
static MessageList _proto_msg_files[6];
// 0x6647DC
static char* gRaceTypeNames[RACE_TYPE_COUNT];
// 0x6647E4
static char* gSceneryTypeNames[SCENERY_TYPE_COUNT];
// proto.msg
//
// 0x6647FC
MessageList gProtoMessageList;
// 0x664804
static char* gMaterialTypeNames[MATERIAL_TYPE_COUNT];
// "<None>" from proto.msg
//
// 0x664824
char* _proto_none_str;
// 0x664828
static char* gBodyTypeNames[BODY_TYPE_COUNT];
// 0x664834
char* gItemTypeNames[ITEM_TYPE_COUNT];
// 0x66484C
static char* gDamageTypeNames[DAMAGE_TYPE_COUNT];
// 0x66486C
static char* gCaliberTypeNames[CALIBER_TYPE_COUNT];
// Perk names.
//
// 0x6648B8
static char** _perk_code_strs;
// Stat names.
//
// 0x6648BC
static char** _critter_stats_list;
// 0x49E270
void proto_make_path(char* path, int pid)
{
strcpy(path, _cd_path_base);
strcat(path, _proto_path_base);
if (pid != -1) {
strcat(path, artGetObjectTypeName(PID_TYPE(pid)));
}
}
// Append proto file name to proto_path from proto.lst.
//
// 0x49E758
int _proto_list_str(int pid, char* proto_path)
{
if (pid == -1) {
return -1;
}
if (proto_path == nullptr) {
return -1;
}
char path[COMPAT_MAX_PATH];
proto_make_path(path, pid);
strcat(path, "\\");
strcat(path, artGetObjectTypeName(PID_TYPE(pid)));
strcat(path, ".lst");
File* stream = fileOpen(path, "rt");
int i = 1;
char string[256];
while (fileReadString(string, sizeof(string), stream)) {
if (i == (pid & 0xFFFFFF)) {
break;
}
i++;
}
fileClose(stream);
if (i != (pid & 0xFFFFFF)) {
return -1;
}
char* pch = strchr(string, ' ');
if (pch != nullptr) {
*pch = '\0';
}
pch = strpbrk(string, "\r\n");
if (pch != nullptr) {
*pch = '\0';
}
strcpy(proto_path, string);
return 0;
}
// 0x49E984
size_t proto_size(int type)
{
return type >= 0 && type < OBJ_TYPE_COUNT ? _proto_sizes[type] : 0;
}
// 0x49E99C
bool _proto_action_can_use(int pid)
{
Proto* proto;
if (protoGetProto(pid, &proto) == -1) {
return false;
}
if ((proto->item.extendedFlags & 0x0800) != 0) {
return true;
}
if (PID_TYPE(pid) == OBJ_TYPE_ITEM && proto->item.type == ITEM_TYPE_CONTAINER) {
return true;
}
return false;
}
// 0x49E9DC
bool _proto_action_can_use_on(int pid)
{
Proto* proto;
if (protoGetProto(pid, &proto) == -1) {
return false;
}
if ((proto->item.extendedFlags & 0x1000) != 0) {
return true;
}
if (PID_TYPE(pid) == OBJ_TYPE_ITEM && proto->item.type == ITEM_TYPE_DRUG) {
return true;
}
return false;
}
// 0x49EA24
bool _proto_action_can_talk_to(int pid)
{
Proto* proto;
if (protoGetProto(pid, &proto) == -1) {
return false;
}
if (PID_TYPE(pid) == OBJ_TYPE_CRITTER) {
return true;
}
if (proto->critter.extendedFlags & 0x4000) {
return true;
}
return false;
}
// Likely returns true if item with given pid can be picked up.
//
// 0x49EA5C
int _proto_action_can_pickup(int pid)
{
if (PID_TYPE(pid) != OBJ_TYPE_ITEM) {
return false;
}
Proto* proto;
if (protoGetProto(pid, &proto) == -1) {
return false;
}
if (proto->item.type == ITEM_TYPE_CONTAINER) {
return (proto->item.extendedFlags & 0x8000) != 0;
}
return true;
}
// 0x49EAA4
char* protoGetMessage(int pid, int message)
{
char* v1 = _proto_none_str;
Proto* proto;
if (protoGetProto(pid, &proto) != -1) {
if (proto->messageId != -1) {
MessageList* messageList = &(_proto_msg_files[PID_TYPE(pid)]);
MessageListItem messageListItem;
messageListItem.num = proto->messageId + message;
if (messageListGetItem(messageList, &messageListItem)) {
v1 = messageListItem.text;
}
}
}
return v1;
}
// 0x49EAFC
char* protoGetName(int pid)
{
if (pid == 0x1000000) {
return critterGetName(gDude);
}
return protoGetMessage(pid, PROTOTYPE_MESSAGE_NAME);
}
// 0x49EB1C
char* protoGetDescription(int pid)
{
return protoGetMessage(pid, PROTOTYPE_MESSAGE_DESCRIPTION);
}
// 0x49EB2C
int proto_item_init(Proto* proto, int a2)
{
int v1 = a2 & 0xFFFFFF;
proto->item.pid = -1;
proto->item.messageId = 100 * v1;
proto->item.fid = buildFid(OBJ_TYPE_ITEM, v1 - 1, 0, 0, 0);
if (!artExists(proto->item.fid)) {
proto->item.fid = buildFid(OBJ_TYPE_ITEM, 0, 0, 0, 0);
}
proto->item.lightDistance = 0;
proto->item.lightIntensity = 0;
proto->item.flags = 0xA0000008;
proto->item.extendedFlags = 0xA000;
proto->item.sid = -1;
proto->item.type = ITEM_TYPE_MISC;
proto_item_subdata_init(proto, proto->item.type);
proto->item.material = 1;
proto->item.size = 1;
proto->item.weight = 10;
proto->item.cost = 0;
proto->item.inventoryFid = -1;
proto->item.field_80 = '0';
return 0;
}
// 0x49EBFC
int proto_item_subdata_init(Proto* proto, int type)
{
int index;
switch (type) {
case ITEM_TYPE_ARMOR:
proto->item.data.armor.armorClass = 0;
for (index = 0; index < DAMAGE_TYPE_COUNT; index++) {
proto->item.data.armor.damageResistance[index] = 0;
proto->item.data.armor.damageThreshold[index] = 0;
}
proto->item.data.armor.perk = -1;
proto->item.data.armor.maleFid = -1;
proto->item.data.armor.femaleFid = -1;
break;
case ITEM_TYPE_CONTAINER:
proto->item.data.container.openFlags = 0;
proto->item.data.container.maxSize = 250;
proto->item.extendedFlags |= 0x800;
break;
case ITEM_TYPE_DRUG:
proto->item.data.drug.stat[0] = STAT_STRENGTH;
proto->item.data.drug.stat[1] = -1;
proto->item.data.drug.stat[2] = -1;
proto->item.data.drug.amount[0] = 0;
proto->item.data.drug.amount[1] = 0;
proto->item.data.drug.amount[2] = 0;
proto->item.data.drug.duration1 = 0;
proto->item.data.drug.amount1[0] = 0;
proto->item.data.drug.amount1[1] = 0;
proto->item.data.drug.amount1[2] = 0;
proto->item.data.drug.duration2 = 0;
proto->item.data.drug.amount2[0] = 0;
proto->item.data.drug.amount2[1] = 0;
proto->item.data.drug.amount2[2] = 0;
proto->item.data.drug.addictionChance = 0;
proto->item.data.drug.withdrawalEffect = 0;
proto->item.data.drug.withdrawalOnset = 0;
proto->item.extendedFlags |= 0x1000;
break;
case ITEM_TYPE_WEAPON:
proto->item.data.weapon.animationCode = 0;
proto->item.data.weapon.minDamage = 0;
proto->item.data.weapon.maxDamage = 0;
proto->item.data.weapon.damageType = 0;
proto->item.data.weapon.maxRange1 = 0;
proto->item.data.weapon.maxRange2 = 0;
proto->item.data.weapon.projectilePid = -1;
proto->item.data.weapon.minStrength = 0;
proto->item.data.weapon.actionPointCost1 = 0;
proto->item.data.weapon.actionPointCost2 = 0;
proto->item.data.weapon.criticalFailureType = 0;
proto->item.data.weapon.perk = -1;
proto->item.data.weapon.rounds = 0;
proto->item.data.weapon.caliber = 0;
proto->item.data.weapon.ammoTypePid = -1;
proto->item.data.weapon.ammoCapacity = 0;
proto->item.data.weapon.soundCode = 0;
break;
case ITEM_TYPE_AMMO:
proto->item.data.ammo.caliber = 0;
proto->item.data.ammo.quantity = 20;
proto->item.data.ammo.armorClassModifier = 0;
proto->item.data.ammo.damageResistanceModifier = 0;
proto->item.data.ammo.damageMultiplier = 1;
proto->item.data.ammo.damageDivisor = 1;
break;
case ITEM_TYPE_MISC:
proto->item.data.misc.powerTypePid = -1;
proto->item.data.misc.powerType = 20;
break;
case ITEM_TYPE_KEY:
proto->item.data.key.keyCode = -1;
proto->item.extendedFlags |= 0x1000;
break;
}
return 0;
}
// 0x49EDB4
int proto_critter_init(Proto* proto, int pid)
{
if (!_protos_been_initialized) {
return -1;
}
int num = pid & 0xFFFFFF;
proto->pid = -1;
proto->messageId = 100 * num;
proto->fid = buildFid(OBJ_TYPE_CRITTER, num - 1, 0, 0, 0);
proto->critter.lightDistance = 0;
proto->critter.lightIntensity = 0;
proto->critter.flags = 0x20000000;
proto->critter.extendedFlags = 0x6000;
proto->critter.sid = -1;
proto->critter.data.flags = 0;
proto->critter.data.bodyType = 0;
proto->critter.headFid = -1;
proto->critter.aiPacket = 1;
if (!artExists(proto->fid)) {
proto->fid = buildFid(OBJ_TYPE_CRITTER, 0, 0, 0, 0);
}
CritterProtoData* data = &(proto->critter.data);
data->experience = 60;
data->killType = 0;
data->damageType = 0;
protoCritterDataResetStats(data);
protoCritterDataResetSkills(data);
return 0;
}
// 0x49EEA4
void objectDataReset(Object* obj)
{
// NOTE: Original code is slightly different. It uses loop to zero object
// data byte by byte.
memset(&(obj->data), 0, sizeof(obj->data));
}
// 0x49EEB8
static int objectCritterCombatDataRead(CritterCombatData* data, File* stream)
{
if (fileReadInt32(stream, &(data->damageLastTurn)) == -1) return -1;
if (fileReadInt32(stream, &(data->maneuver)) == -1) return -1;
if (fileReadInt32(stream, &(data->ap)) == -1) return -1;
if (fileReadInt32(stream, &(data->results)) == -1) return -1;
if (fileReadInt32(stream, &(data->aiPacket)) == -1) return -1;
if (fileReadInt32(stream, &(data->team)) == -1) return -1;
if (fileReadInt32(stream, &(data->whoHitMeCid)) == -1) return -1;
return 0;
}
// 0x49EF40
static int objectCritterCombatDataWrite(CritterCombatData* data, File* stream)
{
if (fileWriteInt32(stream, data->damageLastTurn) == -1) return -1;
if (fileWriteInt32(stream, data->maneuver) == -1) return -1;
if (fileWriteInt32(stream, data->ap) == -1) return -1;
if (fileWriteInt32(stream, data->results) == -1) return -1;
if (fileWriteInt32(stream, data->aiPacket) == -1) return -1;
if (fileWriteInt32(stream, data->team) == -1) return -1;
if (fileWriteInt32(stream, data->whoHitMeCid) == -1) return -1;
return 0;
}
// 0x49F004
int objectDataRead(Object* obj, File* stream)
{
Proto* proto;
int temp;
Inventory* inventory = &(obj->data.inventory);
if (fileReadInt32(stream, &(inventory->length)) == -1) return -1;
if (fileReadInt32(stream, &(inventory->capacity)) == -1) return -1;
// CE: Original code reads inventory items pointer which is meaningless.
if (fileReadInt32(stream, &temp) == -1) return -1;
if (PID_TYPE(obj->pid) == OBJ_TYPE_CRITTER) {
if (fileReadInt32(stream, &(obj->data.critter.field_0)) == -1) return -1;
if (objectCritterCombatDataRead(&(obj->data.critter.combat), stream) == -1) return -1;
if (fileReadInt32(stream, &(obj->data.critter.hp)) == -1) return -1;
if (fileReadInt32(stream, &(obj->data.critter.radiation)) == -1) return -1;
if (fileReadInt32(stream, &(obj->data.critter.poison)) == -1) return -1;
} else {
if (fileReadInt32(stream, &(obj->data.flags)) == -1) return -1;
if (obj->data.flags == 0xCCCCCCCC) {
debugPrint("\nNote: Reading pud: updated_flags was un-Set!");
obj->data.flags = 0;
}
switch (PID_TYPE(obj->pid)) {
case OBJ_TYPE_ITEM:
if (protoGetProto(obj->pid, &proto) == -1) return -1;
switch (proto->item.type) {
case ITEM_TYPE_WEAPON:
if (fileReadInt32(stream, &(obj->data.item.weapon.ammoQuantity)) == -1) return -1;
if (fileReadInt32(stream, &(obj->data.item.weapon.ammoTypePid)) == -1) return -1;
break;
case ITEM_TYPE_AMMO:
if (fileReadInt32(stream, &(obj->data.item.ammo.quantity)) == -1) return -1;
break;
case ITEM_TYPE_MISC:
if (fileReadInt32(stream, &(obj->data.item.misc.charges)) == -1) return -1;
break;
case ITEM_TYPE_KEY:
if (fileReadInt32(stream, &(obj->data.item.key.keyCode)) == -1) return -1;
break;
default:
break;
}
break;
case OBJ_TYPE_SCENERY:
if (protoGetProto(obj->pid, &proto) == -1) return -1;
switch (proto->scenery.type) {
case SCENERY_TYPE_DOOR:
if (fileReadInt32(stream, &(obj->data.scenery.door.openFlags)) == -1) return -1;
break;
case SCENERY_TYPE_STAIRS:
if (fileReadInt32(stream, &(obj->data.scenery.stairs.destinationBuiltTile)) == -1) return -1;
if (fileReadInt32(stream, &(obj->data.scenery.stairs.destinationMap)) == -1) return -1;
break;
case SCENERY_TYPE_ELEVATOR:
if (fileReadInt32(stream, &(obj->data.scenery.elevator.type)) == -1) return -1;
if (fileReadInt32(stream, &(obj->data.scenery.elevator.level)) == -1) return -1;
break;
case SCENERY_TYPE_LADDER_UP:
if (gMapHeader.version == 19) {
if (fileReadInt32(stream, &(obj->data.scenery.ladder.destinationBuiltTile)) == -1) return -1;
} else {
if (fileReadInt32(stream, &(obj->data.scenery.ladder.destinationMap)) == -1) return -1;
if (fileReadInt32(stream, &(obj->data.scenery.ladder.destinationBuiltTile)) == -1) return -1;
}
break;
case SCENERY_TYPE_LADDER_DOWN:
if (gMapHeader.version == 19) {
if (fileReadInt32(stream, &(obj->data.scenery.ladder.destinationBuiltTile)) == -1) return -1;
} else {
if (fileReadInt32(stream, &(obj->data.scenery.ladder.destinationMap)) == -1) return -1;
if (fileReadInt32(stream, &(obj->data.scenery.ladder.destinationBuiltTile)) == -1) return -1;
}
break;
}
break;
case OBJ_TYPE_MISC:
if (isExitGridPid(obj->pid)) {
if (fileReadInt32(stream, &(obj->data.misc.map)) == -1) return -1;
if (fileReadInt32(stream, &(obj->data.misc.tile)) == -1) return -1;
if (fileReadInt32(stream, &(obj->data.misc.elevation)) == -1) return -1;
if (fileReadInt32(stream, &(obj->data.misc.rotation)) == -1) return -1;
}
break;
}
}
return 0;
}
// 0x49F428
int objectDataWrite(Object* obj, File* stream)
{
Proto* proto;
ObjectData* data = &(obj->data);
if (fileWriteInt32(stream, data->inventory.length) == -1) return -1;
if (fileWriteInt32(stream, data->inventory.capacity) == -1) return -1;
// CE: Original code writes inventory items pointer, which is meaningless.
if (fileWriteInt32(stream, 0) == -1) return -1;
if (PID_TYPE(obj->pid) == OBJ_TYPE_CRITTER) {
if (fileWriteInt32(stream, data->flags) == -1) return -1;
if (objectCritterCombatDataWrite(&(obj->data.critter.combat), stream) == -1) return -1;
if (fileWriteInt32(stream, data->critter.hp) == -1) return -1;
if (fileWriteInt32(stream, data->critter.radiation) == -1) return -1;
if (fileWriteInt32(stream, data->critter.poison) == -1) return -1;
} else {
if (fileWriteInt32(stream, data->flags) == -1) return -1;
switch (PID_TYPE(obj->pid)) {
case OBJ_TYPE_ITEM:
if (protoGetProto(obj->pid, &proto) == -1) return -1;
switch (proto->item.type) {
case ITEM_TYPE_WEAPON:
if (fileWriteInt32(stream, data->item.weapon.ammoQuantity) == -1) return -1;
if (fileWriteInt32(stream, data->item.weapon.ammoTypePid) == -1) return -1;
break;
case ITEM_TYPE_AMMO:
if (fileWriteInt32(stream, data->item.ammo.quantity) == -1) return -1;
break;
case ITEM_TYPE_MISC:
if (fileWriteInt32(stream, data->item.misc.charges) == -1) return -1;
break;
case ITEM_TYPE_KEY:
if (fileWriteInt32(stream, data->item.key.keyCode) == -1) return -1;
break;
}
break;
case OBJ_TYPE_SCENERY:
if (protoGetProto(obj->pid, &proto) == -1) return -1;
switch (proto->scenery.type) {
case SCENERY_TYPE_DOOR:
if (fileWriteInt32(stream, data->scenery.door.openFlags) == -1) return -1;
break;
case SCENERY_TYPE_STAIRS:
if (fileWriteInt32(stream, data->scenery.stairs.destinationBuiltTile) == -1) return -1;
if (fileWriteInt32(stream, data->scenery.stairs.destinationMap) == -1) return -1;
break;
case SCENERY_TYPE_ELEVATOR:
if (fileWriteInt32(stream, data->scenery.elevator.type) == -1) return -1;
if (fileWriteInt32(stream, data->scenery.elevator.level) == -1) return -1;
break;
case SCENERY_TYPE_LADDER_UP:
if (fileWriteInt32(stream, data->scenery.ladder.destinationMap) == -1) return -1;
if (fileWriteInt32(stream, data->scenery.ladder.destinationBuiltTile) == -1) return -1;
break;
case SCENERY_TYPE_LADDER_DOWN:
if (fileWriteInt32(stream, data->scenery.ladder.destinationMap) == -1) return -1;
if (fileWriteInt32(stream, data->scenery.ladder.destinationBuiltTile) == -1) return -1;
break;
default:
break;
}
break;
case OBJ_TYPE_MISC:
if (isExitGridPid(obj->pid)) {
if (fileWriteInt32(stream, data->misc.map) == -1) return -1;
if (fileWriteInt32(stream, data->misc.tile) == -1) return -1;
if (fileWriteInt32(stream, data->misc.elevation) == -1) return -1;
if (fileWriteInt32(stream, data->misc.rotation) == -1) return -1;
}
break;
default:
break;
}
}
return 0;
}
// 0x49F73C
static int _proto_update_gen(Object* obj)
{
Proto* proto;
if (!_protos_been_initialized) {
return -1;
}
ObjectData* data = &(obj->data);
data->inventory.length = 0;
data->inventory.capacity = 0;
data->inventory.items = nullptr;
if (protoGetProto(obj->pid, &proto) == -1) {
return -1;
}
switch (PID_TYPE(obj->pid)) {
case OBJ_TYPE_ITEM:
switch (proto->item.type) {
case ITEM_TYPE_CONTAINER:
data->flags = 0;
break;
case ITEM_TYPE_WEAPON:
data->item.weapon.ammoQuantity = proto->item.data.weapon.ammoCapacity;
data->item.weapon.ammoTypePid = proto->item.data.weapon.ammoTypePid;
break;
case ITEM_TYPE_AMMO:
data->item.ammo.quantity = proto->item.data.ammo.quantity;
break;
case ITEM_TYPE_MISC:
data->item.misc.charges = proto->item.data.misc.charges;
break;
case ITEM_TYPE_KEY:
data->item.key.keyCode = proto->item.data.key.keyCode;
break;
}
break;
case OBJ_TYPE_SCENERY:
switch (proto->scenery.type) {
case SCENERY_TYPE_DOOR:
data->scenery.door.openFlags = proto->scenery.data.door.openFlags;
break;
case SCENERY_TYPE_STAIRS:
data->scenery.stairs.destinationBuiltTile = proto->scenery.data.stairs.field_0;
data->scenery.stairs.destinationMap = proto->scenery.data.stairs.field_4;
break;
case SCENERY_TYPE_ELEVATOR:
data->scenery.elevator.type = proto->scenery.data.elevator.type;
data->scenery.elevator.level = proto->scenery.data.elevator.level;
break;
case SCENERY_TYPE_LADDER_UP:
case SCENERY_TYPE_LADDER_DOWN:
data->scenery.ladder.destinationMap = proto->scenery.data.ladder.field_0;
break;
}
break;
case OBJ_TYPE_MISC:
if (isExitGridPid(obj->pid)) {
data->misc.tile = -1;
data->misc.elevation = 0;
data->misc.rotation = 0;
data->misc.map = -1;
}
break;
default:
break;
}
return 0;
}
// 0x49F8A0
int _proto_update_init(Object* obj)
{
if (!_protos_been_initialized) {
return -1;
}
if (obj == nullptr) {
return -1;
}
if (obj->pid == -1) {
return -1;
}
memset(&(obj->data), 0, sizeof(ObjectData));
if (PID_TYPE(obj->pid) != OBJ_TYPE_CRITTER) {
return _proto_update_gen(obj);
}
ObjectData* data = &(obj->data);
data->inventory.length = 0;
data->inventory.capacity = 0;
data->inventory.items = nullptr;
_combat_data_init(obj);
data->critter.hp = critterGetStat(obj, STAT_MAXIMUM_HIT_POINTS);
data->critter.combat.ap = critterGetStat(obj, STAT_MAXIMUM_ACTION_POINTS);
critterUpdateDerivedStats(obj);
obj->data.critter.combat.whoHitMe = nullptr;
Proto* proto;
if (protoGetProto(obj->pid, &proto) != -1) {
data->critter.combat.aiPacket = proto->critter.aiPacket;
data->critter.combat.team = proto->critter.team;
}
return 0;
}
// 0x49F984
int _proto_dude_update_gender()
{
Proto* proto;
if (protoGetProto(0x1000000, &proto) == -1) {
return -1;
}
int nativeLook = DUDE_NATIVE_LOOK_TRIBAL;
if (gameMovieIsSeen(MOVIE_VSUIT)) {
nativeLook = DUDE_NATIVE_LOOK_JUMPSUIT;
}
int frmId;
if (critterGetStat(gDude, STAT_GENDER) == GENDER_MALE) {
frmId = _art_vault_person_nums[nativeLook][GENDER_MALE];
} else {
frmId = _art_vault_person_nums[nativeLook][GENDER_FEMALE];
}
_art_vault_guy_num = frmId;
if (critterGetArmor(gDude) == nullptr) {
int v1 = 0;
if (critterGetItem2(gDude) != nullptr || critterGetItem1(gDude) != nullptr) {
v1 = (gDude->fid & 0xF000) >> 12;
}
int fid = buildFid(OBJ_TYPE_CRITTER, _art_vault_guy_num, 0, v1, 0);
objectSetFid(gDude, fid, nullptr);
}
proto->fid = buildFid(OBJ_TYPE_CRITTER, _art_vault_guy_num, 0, 0, 0);
return 0;
}
// proto_dude_init
// 0x49FA64
int _proto_dude_init(const char* path)
{
gDudeProto.fid = buildFid(OBJ_TYPE_CRITTER, _art_vault_guy_num, 0, 0, 0);
if (_init_true) {
_obj_inven_free(&(gDude->data.inventory));
}
_init_true = 1;
Proto* proto;
if (protoGetProto(0x1000000, &proto) == -1) {
return -1;
}
protoGetProto(gDude->pid, &proto);
_proto_update_init(gDude);
gDude->data.critter.combat.aiPacket = 0;
gDude->data.critter.combat.team = 0;
_ResetPlayer();
if (gcdLoad(path) == -1) {
_retval = -1;
}
proto->critter.data.baseStats[STAT_DAMAGE_RESISTANCE_EMP] = 100;
proto->critter.data.bodyType = 0;
proto->critter.data.experience = 0;
proto->critter.data.killType = 0;
proto->critter.data.damageType = 0;
_proto_dude_update_gender();
_inven_reset_dude();
if ((gDude->flags & OBJECT_FLAT) != 0) {
_obj_toggle_flat(gDude, nullptr);
}
if ((gDude->flags & OBJECT_NO_BLOCK) != 0) {
gDude->flags &= ~OBJECT_NO_BLOCK;
}
critterUpdateDerivedStats(gDude);
critterAdjustHitPoints(gDude, 10000);
if (_retval) {
debugPrint("\n ** Error in proto_dude_init()! **\n");
}
return 0;
}
// 0x49FBBC
int proto_scenery_init(Proto* proto, int pid)
{
int num = pid & 0xFFFFFF;
proto->scenery.pid = -1;
proto->scenery.messageId = 100 * num;
proto->scenery.fid = buildFid(OBJ_TYPE_SCENERY, num - 1, 0, 0, 0);
if (!artExists(proto->scenery.fid)) {
proto->scenery.fid = buildFid(OBJ_TYPE_SCENERY, 0, 0, 0, 0);
}
proto->scenery.lightDistance = 0;
proto->scenery.lightIntensity = 0;
proto->scenery.flags = 0;
proto->scenery.extendedFlags = 0x2000;
proto->scenery.sid = -1;
proto->scenery.type = SCENERY_TYPE_GENERIC;
proto_scenery_subdata_init(proto, proto->scenery.type);
proto->scenery.field_2C = -1;
proto->scenery.field_34 = '0';
return 0;
}
// 0x49FC74
int proto_scenery_subdata_init(Proto* proto, int type)
{
switch (type) {
case SCENERY_TYPE_DOOR:
proto->scenery.data.door.openFlags = 0;
proto->scenery.extendedFlags |= 0x800;
break;
case SCENERY_TYPE_STAIRS:
proto->scenery.data.stairs.field_0 = -1;
proto->scenery.data.stairs.field_4 = -1;
proto->scenery.extendedFlags |= 0x800;
break;
case SCENERY_TYPE_ELEVATOR:
proto->scenery.data.elevator.type = -1;
proto->scenery.data.elevator.level = -1;
proto->scenery.extendedFlags |= 0x800;
break;
case SCENERY_TYPE_LADDER_UP:
proto->scenery.data.ladder.field_0 = -1;
proto->scenery.extendedFlags |= 0x800;
break;
case SCENERY_TYPE_LADDER_DOWN:
proto->scenery.data.ladder.field_0 = -1;
proto->scenery.extendedFlags |= 0x800;
break;
}
return 0;
}
// 0x49FCFC
int proto_wall_init(Proto* proto, int pid)
{
int num = pid & 0xFFFFFF;
proto->wall.pid = -1;
proto->wall.messageId = 100 * num;
proto->wall.fid = buildFid(OBJ_TYPE_WALL, num - 1, 0, 0, 0);
if (!artExists(proto->wall.fid)) {
proto->wall.fid = buildFid(OBJ_TYPE_WALL, 0, 0, 0, 0);
}
proto->wall.lightDistance = 0;
proto->wall.lightIntensity = 0;
proto->wall.flags = 0;
proto->wall.extendedFlags = 0x2000;
proto->wall.sid = -1;
proto->wall.material = 1;
return 0;
}
// 0x49FD84
int proto_tile_init(Proto* proto, int pid)
{
int num = pid & 0xFFFFFF;
proto->tile.pid = -1;
proto->tile.messageId = 100 * num;
proto->tile.fid = buildFid(OBJ_TYPE_TILE, num - 1, 0, 0, 0);
if (!artExists(proto->tile.fid)) {
proto->tile.fid = buildFid(OBJ_TYPE_TILE, 0, 0, 0, 0);
}
proto->tile.flags = 0;
proto->tile.extendedFlags = 0x2000;
proto->tile.sid = -1;
proto->tile.material = 1;
return 0;
}
// 0x49FDFC
int proto_misc_init(Proto* proto, int pid)
{
int num = pid & 0xFFFFFF;
proto->misc.pid = -1;
proto->misc.messageId = 100 * num;
proto->misc.fid = buildFid(OBJ_TYPE_MISC, num - 1, 0, 0, 0);
if (!artExists(proto->misc.fid)) {
proto->misc.fid = buildFid(OBJ_TYPE_MISC, 0, 0, 0, 0);
}
proto->misc.lightDistance = 0;
proto->misc.lightIntensity = 0;
proto->misc.flags = 0;
proto->misc.extendedFlags = 0;
return 0;
}
// 0x49FE74
int proto_copy_proto(int srcPid, int dstPid)
{
int srcType;
int dstType;
Proto* src;
Proto* dst;
srcType = PID_TYPE(srcPid);
dstType = PID_TYPE(dstPid);
if (srcType != dstType) {
return -1;
}
if (protoGetProto(srcPid, &src) == -1) {
return -1;
}
if (protoGetProto(dstPid, &dst) == -1) {
return -1;
}
memcpy(dst, src, _proto_sizes[srcType]);
dst->pid = dstPid;
return 0;
}
// 0x49FEDC
bool proto_is_subtype(Proto* proto, int subtype)
{
if (subtype == -1) {
return true;
}
switch (PID_TYPE(proto->pid)) {
case OBJ_TYPE_ITEM:
return proto->item.type == subtype;
case OBJ_TYPE_SCENERY:
return proto->scenery.type == subtype;
}
return false;
}
// proto_data_member
// 0x49FFD8
int protoGetDataMember(int pid, int member, ProtoDataMemberValue* value)
{
Proto* proto;
if (protoGetProto(pid, &proto) == -1) {
return -1;
}
switch (PID_TYPE(pid)) {
case OBJ_TYPE_ITEM:
switch (member) {
case ITEM_DATA_MEMBER_PID:
value->integerValue = proto->pid;
break;
case ITEM_DATA_MEMBER_NAME:
// NOTE: uninline
value->stringValue = protoGetName(proto->scenery.pid);
return PROTO_DATA_MEMBER_TYPE_STRING;
case ITEM_DATA_MEMBER_DESCRIPTION:
// NOTE: Uninline.
value->stringValue = protoGetDescription(proto->pid);
return PROTO_DATA_MEMBER_TYPE_STRING;
case ITEM_DATA_MEMBER_FID:
value->integerValue = proto->fid;
break;
case ITEM_DATA_MEMBER_LIGHT_DISTANCE:
value->integerValue = proto->item.lightDistance;
break;
case ITEM_DATA_MEMBER_LIGHT_INTENSITY:
value->integerValue = proto->item.lightIntensity;
break;
case ITEM_DATA_MEMBER_FLAGS:
value->integerValue = proto->item.flags;
break;
case ITEM_DATA_MEMBER_EXTENDED_FLAGS:
value->integerValue = proto->item.extendedFlags;
break;
case ITEM_DATA_MEMBER_SID:
value->integerValue = proto->item.sid;
break;
case ITEM_DATA_MEMBER_TYPE:
value->integerValue = proto->item.type;
break;
case ITEM_DATA_MEMBER_MATERIAL:
value->integerValue = proto->item.material;
break;
case ITEM_DATA_MEMBER_SIZE:
value->integerValue = proto->item.size;
break;
case ITEM_DATA_MEMBER_WEIGHT:
value->integerValue = proto->item.weight;
break;
case ITEM_DATA_MEMBER_COST:
value->integerValue = proto->item.cost;
break;
case ITEM_DATA_MEMBER_INVENTORY_FID:
value->integerValue = proto->item.inventoryFid;
break;
case ITEM_DATA_MEMBER_WEAPON_RANGE:
if (proto->item.type == ITEM_TYPE_WEAPON) {
value->integerValue = proto->item.data.weapon.maxRange1;
}
break;
default:
debugPrint("\n\tError: Unimp'd data member in member in proto_data_member!");
break;
}
break;
case OBJ_TYPE_CRITTER:
switch (member) {
case CRITTER_DATA_MEMBER_PID:
value->integerValue = proto->critter.pid;
break;
case CRITTER_DATA_MEMBER_NAME:
// NOTE: Uninline.
value->stringValue = protoGetName(proto->critter.pid);
return PROTO_DATA_MEMBER_TYPE_STRING;
case CRITTER_DATA_MEMBER_DESCRIPTION:
// NOTE: Uninline.
value->stringValue = protoGetDescription(proto->critter.pid);
return PROTO_DATA_MEMBER_TYPE_STRING;
case CRITTER_DATA_MEMBER_FID:
value->integerValue = proto->critter.fid;
break;
case CRITTER_DATA_MEMBER_LIGHT_DISTANCE:
value->integerValue = proto->critter.lightDistance;
break;
case CRITTER_DATA_MEMBER_LIGHT_INTENSITY:
value->integerValue = proto->critter.lightIntensity;
break;
case CRITTER_DATA_MEMBER_FLAGS:
value->integerValue = proto->critter.flags;
break;
case CRITTER_DATA_MEMBER_EXTENDED_FLAGS:
value->integerValue = proto->critter.extendedFlags;
break;
case CRITTER_DATA_MEMBER_SID:
value->integerValue = proto->critter.sid;
break;
case CRITTER_DATA_MEMBER_HEAD_FID:
value->integerValue = proto->critter.headFid;
break;
case CRITTER_DATA_MEMBER_BODY_TYPE:
value->integerValue = proto->critter.data.bodyType;
break;
default:
debugPrint("\n\tError: Unimp'd data member in member in proto_data_member!");
break;
}
break;
case OBJ_TYPE_SCENERY:
switch (member) {
case SCENERY_DATA_MEMBER_PID:
value->integerValue = proto->scenery.pid;
break;
case SCENERY_DATA_MEMBER_NAME:
// NOTE: Uninline.
value->stringValue = protoGetName(proto->scenery.pid);
return PROTO_DATA_MEMBER_TYPE_STRING;
case SCENERY_DATA_MEMBER_DESCRIPTION:
// NOTE: Uninline.
value->stringValue = protoGetDescription(proto->scenery.pid);
return PROTO_DATA_MEMBER_TYPE_STRING;
case SCENERY_DATA_MEMBER_FID:
value->integerValue = proto->scenery.fid;
break;
case SCENERY_DATA_MEMBER_LIGHT_DISTANCE:
value->integerValue = proto->scenery.lightDistance;
break;
case SCENERY_DATA_MEMBER_LIGHT_INTENSITY:
value->integerValue = proto->scenery.lightIntensity;
break;
case SCENERY_DATA_MEMBER_FLAGS:
value->integerValue = proto->scenery.flags;
break;
case SCENERY_DATA_MEMBER_EXTENDED_FLAGS:
value->integerValue = proto->scenery.extendedFlags;
break;
case SCENERY_DATA_MEMBER_SID:
value->integerValue = proto->scenery.sid;
break;
case SCENERY_DATA_MEMBER_TYPE:
value->integerValue = proto->scenery.type;
break;
case SCENERY_DATA_MEMBER_MATERIAL:
value->integerValue = proto->scenery.field_2C;
break;
default:
debugPrint("\n\tError: Unimp'd data member in member in proto_data_member!");
break;
}
break;
case OBJ_TYPE_WALL:
switch (member) {
case WALL_DATA_MEMBER_PID:
value->integerValue = proto->wall.pid;
break;
case WALL_DATA_MEMBER_NAME:
// NOTE: Uninline.
value->stringValue = protoGetName(proto->wall.pid);
return PROTO_DATA_MEMBER_TYPE_STRING;
case WALL_DATA_MEMBER_DESCRIPTION:
// NOTE: Uninline.
value->stringValue = protoGetDescription(proto->wall.pid);
return PROTO_DATA_MEMBER_TYPE_STRING;
case WALL_DATA_MEMBER_FID:
value->integerValue = proto->wall.fid;
break;
case WALL_DATA_MEMBER_LIGHT_DISTANCE:
value->integerValue = proto->wall.lightDistance;
break;
case WALL_DATA_MEMBER_LIGHT_INTENSITY:
value->integerValue = proto->wall.lightIntensity;
break;
case WALL_DATA_MEMBER_FLAGS:
value->integerValue = proto->wall.flags;
break;
case WALL_DATA_MEMBER_EXTENDED_FLAGS:
value->integerValue = proto->wall.extendedFlags;
break;
case WALL_DATA_MEMBER_SID:
value->integerValue = proto->wall.sid;
break;
case WALL_DATA_MEMBER_MATERIAL:
value->integerValue = proto->wall.material;
break;
default:
debugPrint("\n\tError: Unimp'd data member in member in proto_data_member!");
break;
}
break;
case OBJ_TYPE_TILE:
debugPrint("\n\tError: Unimp'd data member in member in proto_data_member!");
break;
case OBJ_TYPE_MISC:
switch (member) {
case MISC_DATA_MEMBER_PID:
value->integerValue = proto->misc.pid;
break;
case MISC_DATA_MEMBER_NAME:
// NOTE: Uninline.
value->stringValue = protoGetName(proto->misc.pid);
return PROTO_DATA_MEMBER_TYPE_STRING;
case MISC_DATA_MEMBER_DESCRIPTION:
// NOTE: Uninline.
value->stringValue = protoGetDescription(proto->misc.pid);
// FIXME: Errornously report type as int, should be string.
return PROTO_DATA_MEMBER_TYPE_INT;
case MISC_DATA_MEMBER_FID:
value->integerValue = proto->misc.fid;
return 1;
case MISC_DATA_MEMBER_LIGHT_DISTANCE:
value->integerValue = proto->misc.lightDistance;
return 1;
case MISC_DATA_MEMBER_LIGHT_INTENSITY:
value->integerValue = proto->misc.lightIntensity;
break;
case MISC_DATA_MEMBER_FLAGS:
value->integerValue = proto->misc.flags;
break;
case MISC_DATA_MEMBER_EXTENDED_FLAGS:
value->integerValue = proto->misc.extendedFlags;
break;
default:
debugPrint("\n\tError: Unimp'd data member in member in proto_data_member!");
break;
}
break;
}
return PROTO_DATA_MEMBER_TYPE_INT;
}
// proto_init
// 0x4A0390
int protoInit()
{
size_t len;
MessageListItem messageListItem;
char path[COMPAT_MAX_PATH];
int i;
snprintf(path, sizeof(path), "%s\\proto", settings.system.master_patches_path.c_str());
len = strlen(path);
compat_mkdir(path);
strcpy(path + len, "\\critters");
compat_mkdir(path);
strcpy(path + len, "\\items");
compat_mkdir(path);
// TODO: Get rid of cast.
proto_critter_init((Proto*)&gDudeProto, 0x1000000);
gDudeProto.pid = 0x1000000;
gDudeProto.fid = buildFid(OBJ_TYPE_CRITTER, 1, 0, 0, 0);
gDude->pid = 0x1000000;
gDude->sid = 1;
for (i = 0; i < 6; i++) {
_proto_remove_list(i);
}
_proto_header_load();
_protos_been_initialized = 1;
_proto_dude_init("premade\\player.gcd");
for (i = 0; i < 6; i++) {
if (!messageListInit(&(_proto_msg_files[i]))) {
debugPrint("\nError: Initing proto message files!");
return -1;
}
}
for (i = 0; i < 6; i++) {
snprintf(path, sizeof(path), "%spro_%.4s%s", asc_5186C8, artGetObjectTypeName(i), ".msg");
if (!messageListLoad(&(_proto_msg_files[i]), path)) {
debugPrint("\nError: Loading proto message files!");
return -1;
}
}
for (i = 0; i < 6; i++) {
messageListRepositorySetProtoMessageList(i, &(_proto_msg_files[i]));
}
_mp_critter_stats_list = _aDrugStatSpecia;
_critter_stats_list = _critter_stats_list_strs;
_critter_stats_list_None = _aNone_1;
for (i = 0; i < STAT_COUNT; i++) {
_critter_stats_list_strs[i] = statGetName(i);
if (_critter_stats_list_strs[i] == nullptr) {
debugPrint("\nError: Finding stat names!");
return -1;
}
}
_mp_perk_code_None = _aNone_1;
_perk_code_strs = _mp_perk_code_strs;
for (i = 0; i < PERK_COUNT; i++) {
_mp_perk_code_strs[i] = perkGetName(i);
if (_mp_perk_code_strs[i] == nullptr) {
debugPrint("\nError: Finding perk names!");
return -1;
}
}
if (!messageListInit(&gProtoMessageList)) {
debugPrint("\nError: Initing main proto message file!");
return -1;
}
snprintf(path, sizeof(path), "%sproto.msg", asc_5186C8);
if (!messageListLoad(&gProtoMessageList, path)) {
debugPrint("\nError: Loading main proto message file!");
return -1;
}
_proto_none_str = getmsg(&gProtoMessageList, &messageListItem, 10);
// material type names
for (i = 0; i < MATERIAL_TYPE_COUNT; i++) {
gMaterialTypeNames[i] = getmsg(&gProtoMessageList, &messageListItem, 100 + i);
}
// item type names
for (i = 0; i < ITEM_TYPE_COUNT; i++) {
gItemTypeNames[i] = getmsg(&gProtoMessageList, &messageListItem, 150 + i);
}
// scenery type names
for (i = 0; i < SCENERY_TYPE_COUNT; i++) {
gSceneryTypeNames[i] = getmsg(&gProtoMessageList, &messageListItem, 200 + i);
}
// damage code types
for (i = 0; i < DAMAGE_TYPE_COUNT; i++) {
gDamageTypeNames[i] = getmsg(&gProtoMessageList, &messageListItem, 250 + i);
}
// caliber types
for (i = 0; i < CALIBER_TYPE_COUNT; i++) {
gCaliberTypeNames[i] = getmsg(&gProtoMessageList, &messageListItem, 300 + i);
}
// race types
for (i = 0; i < RACE_TYPE_COUNT; i++) {
gRaceTypeNames[i] = getmsg(&gProtoMessageList, &messageListItem, 350 + i);
}
// body types
for (i = 0; i < BODY_TYPE_COUNT; i++) {
gBodyTypeNames[i] = getmsg(&gProtoMessageList, &messageListItem, 400 + i);
}
messageListRepositorySetStandardMessageList(STANDARD_MESSAGE_LIST_PROTO, &gProtoMessageList);
return 0;
}
// 0x4A0814
void protoReset()
{
int i;
// TODO: Get rid of cast.
proto_critter_init((Proto*)&gDudeProto, 0x1000000);
gDudeProto.pid = 0x1000000;
gDudeProto.fid = buildFid(OBJ_TYPE_CRITTER, 1, 0, 0, 0);
gDude->pid = 0x1000000;
gDude->sid = -1;
gDude->flags &= ~OBJECT_FLAG_0xFC000;
for (i = 0; i < 6; i++) {
_proto_remove_list(i);
}
_proto_header_load();
_protos_been_initialized = 1;
_proto_dude_init("premade\\player.gcd");
}
// 0x4A0898
void protoExit()
{
int i;
for (i = 0; i < 6; i++) {
_proto_remove_list(i);
}
for (i = 0; i < 6; i++) {
messageListRepositorySetProtoMessageList(i, nullptr);
messageListFree(&(_proto_msg_files[i]));
}
messageListRepositorySetStandardMessageList(STANDARD_MESSAGE_LIST_PROTO, nullptr);
messageListFree(&gProtoMessageList);
}
// Count .pro lines in .lst files.
//
// 0x4A08E0
static int _proto_header_load()
{
for (int index = 0; index < 6; index++) {
ProtoList* ptr = &(_protoLists[index]);
ptr->head = nullptr;
ptr->tail = nullptr;
ptr->length = 0;
ptr->max_entries_num = 1;
char path[COMPAT_MAX_PATH];
proto_make_path(path, index << 24);
strcat(path, "\\");
strcat(path, artGetObjectTypeName(index));
strcat(path, ".lst");
File* stream = fileOpen(path, "rt");
if (stream == nullptr) {
return -1;
}
int ch = '\0';
while (1) {
ch = fileReadChar(stream);
if (ch == -1) {
break;
}
if (ch == '\n') {
ptr->max_entries_num++;
}
}
if (ch != '\n') {
ptr->max_entries_num++;
}
fileClose(stream);
}
return 0;
}
// 0x4A0AEC
static int protoItemDataRead(ItemProtoData* item_data, int type, File* stream)
{
switch (type) {
case ITEM_TYPE_ARMOR:
if (fileReadInt32(stream, &(item_data->armor.armorClass)) == -1) return -1;
if (fileReadInt32List(stream, item_data->armor.damageResistance, 7) == -1) return -1;
if (fileReadInt32List(stream, item_data->armor.damageThreshold, 7) == -1) return -1;
if (fileReadInt32(stream, &(item_data->armor.perk)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->armor.maleFid)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->armor.femaleFid)) == -1) return -1;
return 0;
case ITEM_TYPE_CONTAINER:
if (fileReadInt32(stream, &(item_data->container.maxSize)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->container.openFlags)) == -1) return -1;
return 0;
case ITEM_TYPE_DRUG:
if (fileReadInt32(stream, &(item_data->drug.stat[0])) == -1) return -1;
if (fileReadInt32(stream, &(item_data->drug.stat[1])) == -1) return -1;
if (fileReadInt32(stream, &(item_data->drug.stat[2])) == -1) return -1;
if (fileReadInt32List(stream, item_data->drug.amount, 3) == -1) return -1;
if (fileReadInt32(stream, &(item_data->drug.duration1)) == -1) return -1;
if (fileReadInt32List(stream, item_data->drug.amount1, 3) == -1) return -1;
if (fileReadInt32(stream, &(item_data->drug.duration2)) == -1) return -1;
if (fileReadInt32List(stream, item_data->drug.amount2, 3) == -1) return -1;
if (fileReadInt32(stream, &(item_data->drug.addictionChance)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->drug.withdrawalEffect)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->drug.withdrawalOnset)) == -1) return -1;
return 0;
case ITEM_TYPE_WEAPON:
if (fileReadInt32(stream, &(item_data->weapon.animationCode)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.minDamage)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.maxDamage)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.damageType)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.maxRange1)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.maxRange2)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.projectilePid)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.minStrength)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.actionPointCost1)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.actionPointCost2)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.criticalFailureType)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.perk)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.rounds)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.caliber)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.ammoTypePid)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->weapon.ammoCapacity)) == -1) return -1;
if (fileReadUInt8(stream, &(item_data->weapon.soundCode)) == -1) return -1;
return 0;
case ITEM_TYPE_AMMO:
if (fileReadInt32(stream, &(item_data->ammo.caliber)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->ammo.quantity)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->ammo.armorClassModifier)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->ammo.damageResistanceModifier)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->ammo.damageMultiplier)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->ammo.damageDivisor)) == -1) return -1;
return 0;
case ITEM_TYPE_MISC:
if (fileReadInt32(stream, &(item_data->misc.powerTypePid)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->misc.powerType)) == -1) return -1;
if (fileReadInt32(stream, &(item_data->misc.charges)) == -1) return -1;
return 0;
case ITEM_TYPE_KEY:
if (fileReadInt32(stream, &(item_data->key.keyCode)) == -1) return -1;
return 0;
}
return 0;
}
// 0x4A0ED0
static int protoSceneryDataRead(SceneryProtoData* scenery_data, int type, File* stream)
{
switch (type) {
case SCENERY_TYPE_DOOR:
if (fileReadInt32(stream, &(scenery_data->door.openFlags)) == -1) return -1;
if (fileReadInt32(stream, &(scenery_data->door.keyCode)) == -1) return -1;
return 0;
case SCENERY_TYPE_STAIRS:
if (fileReadInt32(stream, &(scenery_data->stairs.field_0)) == -1) return -1;
if (fileReadInt32(stream, &(scenery_data->stairs.field_4)) == -1) return -1;
return 0;
case SCENERY_TYPE_ELEVATOR:
if (fileReadInt32(stream, &(scenery_data->elevator.type)) == -1) return -1;
if (fileReadInt32(stream, &(scenery_data->elevator.level)) == -1) return -1;
return 0;
case SCENERY_TYPE_LADDER_UP:
case SCENERY_TYPE_LADDER_DOWN:
if (fileReadInt32(stream, &(scenery_data->ladder.field_0)) == -1) return -1;
return 0;
case SCENERY_TYPE_GENERIC:
if (fileReadInt32(stream, &(scenery_data->generic.field_0)) == -1) return -1;
return 0;
}
return 0;
}
// read .pro file
// 0x4A0FA0
static int protoRead(Proto* proto, File* stream)
{
if (fileReadInt32(stream, &(proto->pid)) == -1) return -1;
if (fileReadInt32(stream, &(proto->messageId)) == -1) return -1;
if (fileReadInt32(stream, &(proto->fid)) == -1) return -1;
switch (PID_TYPE(proto->pid)) {
case OBJ_TYPE_ITEM:
if (fileReadInt32(stream, &(proto->item.lightDistance)) == -1) return -1;
if (_db_freadInt(stream, &(proto->item.lightIntensity)) == -1) return -1;
if (fileReadInt32(stream, &(proto->item.flags)) == -1) return -1;
if (fileReadInt32(stream, &(proto->item.extendedFlags)) == -1) return -1;
if (fileReadInt32(stream, &(proto->item.sid)) == -1) return -1;
if (fileReadInt32(stream, &(proto->item.type)) == -1) return -1;
if (fileReadInt32(stream, &(proto->item.material)) == -1) return -1;
if (fileReadInt32(stream, &(proto->item.size)) == -1) return -1;
if (_db_freadInt(stream, &(proto->item.weight)) == -1) return -1;
if (fileReadInt32(stream, &(proto->item.cost)) == -1) return -1;
if (fileReadInt32(stream, &(proto->item.inventoryFid)) == -1) return -1;
if (fileReadUInt8(stream, &(proto->item.field_80)) == -1) return -1;
if (protoItemDataRead(&(proto->item.data), proto->item.type, stream) == -1) return -1;
return 0;
case OBJ_TYPE_CRITTER:
if (fileReadInt32(stream, &(proto->critter.lightDistance)) == -1) return -1;
if (_db_freadInt(stream, &(proto->critter.lightIntensity)) == -1) return -1;
if (fileReadInt32(stream, &(proto->critter.flags)) == -1) return -1;
if (fileReadInt32(stream, &(proto->critter.extendedFlags)) == -1) return -1;
if (fileReadInt32(stream, &(proto->critter.sid)) == -1) return -1;
if (fileReadInt32(stream, &(proto->critter.headFid)) == -1) return -1;
if (fileReadInt32(stream, &(proto->critter.aiPacket)) == -1) return -1;
if (fileReadInt32(stream, &(proto->critter.team)) == -1) return -1;
if (protoCritterDataRead(stream, &(proto->critter.data)) == -1) return -1;
return 0;
case OBJ_TYPE_SCENERY:
if (fileReadInt32(stream, &(proto->scenery.lightDistance)) == -1) return -1;
if (_db_freadInt(stream, &(proto->scenery.lightIntensity)) == -1) return -1;
if (fileReadInt32(stream, &(proto->scenery.flags)) == -1) return -1;
if (fileReadInt32(stream, &(proto->scenery.extendedFlags)) == -1) return -1;
if (fileReadInt32(stream, &(proto->scenery.sid)) == -1) return -1;
if (fileReadInt32(stream, &(proto->scenery.type)) == -1) return -1;
if (fileReadInt32(stream, &(proto->scenery.field_2C)) == -1) return -1;
if (fileReadUInt8(stream, &(proto->scenery.field_34)) == -1) return -1;
if (protoSceneryDataRead(&(proto->scenery.data), proto->scenery.type, stream) == -1) return -1;
return 0;
case OBJ_TYPE_WALL:
if (fileReadInt32(stream, &(proto->wall.lightDistance)) == -1) return -1;
if (_db_freadInt(stream, &(proto->wall.lightIntensity)) == -1) return -1;
if (fileReadInt32(stream, &(proto->wall.flags)) == -1) return -1;
if (fileReadInt32(stream, &(proto->wall.extendedFlags)) == -1) return -1;
if (fileReadInt32(stream, &(proto->wall.sid)) == -1) return -1;
if (fileReadInt32(stream, &(proto->wall.material)) == -1) return -1;
return 0;
case OBJ_TYPE_TILE:
if (fileReadInt32(stream, &(proto->tile.flags)) == -1) return -1;
if (fileReadInt32(stream, &(proto->tile.extendedFlags)) == -1) return -1;
if (fileReadInt32(stream, &(proto->tile.sid)) == -1) return -1;
if (fileReadInt32(stream, &(proto->tile.material)) == -1) return -1;
return 0;
case OBJ_TYPE_MISC:
if (fileReadInt32(stream, &(proto->misc.lightDistance)) == -1) return -1;
if (_db_freadInt(stream, &(proto->misc.lightIntensity)) == -1) return -1;
if (fileReadInt32(stream, &(proto->misc.flags)) == -1) return -1;
if (fileReadInt32(stream, &(proto->misc.extendedFlags)) == -1) return -1;
return 0;
}
return -1;
}
// 0x4A1390
static int protoItemDataWrite(ItemProtoData* item_data, int type, File* stream)
{
switch (type) {
case ITEM_TYPE_ARMOR:
if (fileWriteInt32(stream, item_data->armor.armorClass) == -1) return -1;
if (fileWriteInt32List(stream, item_data->armor.damageResistance, 7) == -1) return -1;
if (fileWriteInt32List(stream, item_data->armor.damageThreshold, 7) == -1) return -1;
if (fileWriteInt32(stream, item_data->armor.perk) == -1) return -1;
if (fileWriteInt32(stream, item_data->armor.maleFid) == -1) return -1;
if (fileWriteInt32(stream, item_data->armor.femaleFid) == -1) return -1;
return 0;
case ITEM_TYPE_CONTAINER:
if (fileWriteInt32(stream, item_data->container.maxSize) == -1) return -1;
if (fileWriteInt32(stream, item_data->container.openFlags) == -1) return -1;
return 0;
case ITEM_TYPE_DRUG:
if (fileWriteInt32(stream, item_data->drug.stat[0]) == -1) return -1;
if (fileWriteInt32(stream, item_data->drug.stat[1]) == -1) return -1;
if (fileWriteInt32(stream, item_data->drug.stat[2]) == -1) return -1;
if (fileWriteInt32List(stream, item_data->drug.amount, 3) == -1) return -1;
if (fileWriteInt32(stream, item_data->drug.duration1) == -1) return -1;
if (fileWriteInt32List(stream, item_data->drug.amount1, 3) == -1) return -1;
if (fileWriteInt32(stream, item_data->drug.duration2) == -1) return -1;
if (fileWriteInt32List(stream, item_data->drug.amount2, 3) == -1) return -1;
if (fileWriteInt32(stream, item_data->drug.addictionChance) == -1) return -1;
if (fileWriteInt32(stream, item_data->drug.withdrawalEffect) == -1) return -1;
if (fileWriteInt32(stream, item_data->drug.withdrawalOnset) == -1) return -1;
return 0;
case ITEM_TYPE_WEAPON:
if (fileWriteInt32(stream, item_data->weapon.animationCode) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.maxDamage) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.minDamage) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.damageType) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.maxRange1) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.maxRange2) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.projectilePid) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.minStrength) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.actionPointCost1) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.actionPointCost2) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.criticalFailureType) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.perk) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.rounds) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.caliber) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.ammoTypePid) == -1) return -1;
if (fileWriteInt32(stream, item_data->weapon.ammoCapacity) == -1) return -1;
if (fileWriteUInt8(stream, item_data->weapon.soundCode) == -1) return -1;
return 0;
case ITEM_TYPE_AMMO:
if (fileWriteInt32(stream, item_data->ammo.caliber) == -1) return -1;
if (fileWriteInt32(stream, item_data->ammo.quantity) == -1) return -1;
if (fileWriteInt32(stream, item_data->ammo.armorClassModifier) == -1) return -1;
if (fileWriteInt32(stream, item_data->ammo.damageResistanceModifier) == -1) return -1;
if (fileWriteInt32(stream, item_data->ammo.damageMultiplier) == -1) return -1;
if (fileWriteInt32(stream, item_data->ammo.damageDivisor) == -1) return -1;
return 0;
case ITEM_TYPE_MISC:
if (fileWriteInt32(stream, item_data->misc.powerTypePid) == -1) return -1;
if (fileWriteInt32(stream, item_data->misc.powerType) == -1) return -1;
if (fileWriteInt32(stream, item_data->misc.charges) == -1) return -1;
return 0;
case ITEM_TYPE_KEY:
if (fileWriteInt32(stream, item_data->key.keyCode) == -1) return -1;
return 0;
}
return 0;
}
// 0x4A16E4
static int protoSceneryDataWrite(SceneryProtoData* scenery_data, int type, File* stream)
{
switch (type) {
case SCENERY_TYPE_DOOR:
if (fileWriteInt32(stream, scenery_data->door.openFlags) == -1) return -1;
if (fileWriteInt32(stream, scenery_data->door.keyCode) == -1) return -1;
return 0;
case SCENERY_TYPE_STAIRS:
if (fileWriteInt32(stream, scenery_data->stairs.field_0) == -1) return -1;
if (fileWriteInt32(stream, scenery_data->stairs.field_4) == -1) return -1;
return 0;
case SCENERY_TYPE_ELEVATOR:
if (fileWriteInt32(stream, scenery_data->elevator.type) == -1) return -1;
if (fileWriteInt32(stream, scenery_data->elevator.level) == -1) return -1;
return 0;
case SCENERY_TYPE_LADDER_UP:
case SCENERY_TYPE_LADDER_DOWN:
if (fileWriteInt32(stream, scenery_data->ladder.field_0) == -1) return -1;
return 0;
case SCENERY_TYPE_GENERIC:
if (fileWriteInt32(stream, scenery_data->generic.field_0) == -1) return -1;
return 0;
}
return 0;
}
// 0x4A17B4
static int protoWrite(Proto* proto, File* stream)
{
if (fileWriteInt32(stream, proto->pid) == -1) return -1;
if (fileWriteInt32(stream, proto->messageId) == -1) return -1;
if (fileWriteInt32(stream, proto->fid) == -1) return -1;
switch (PID_TYPE(proto->pid)) {
case OBJ_TYPE_ITEM:
if (fileWriteInt32(stream, proto->item.lightDistance) == -1) return -1;
if (_db_fwriteLong(stream, proto->item.lightIntensity) == -1) return -1;
if (fileWriteInt32(stream, proto->item.flags) == -1) return -1;
if (fileWriteInt32(stream, proto->item.extendedFlags) == -1) return -1;
if (fileWriteInt32(stream, proto->item.sid) == -1) return -1;
if (fileWriteInt32(stream, proto->item.type) == -1) return -1;
if (fileWriteInt32(stream, proto->item.material) == -1) return -1;
if (fileWriteInt32(stream, proto->item.size) == -1) return -1;
if (_db_fwriteLong(stream, proto->item.weight) == -1) return -1;
if (fileWriteInt32(stream, proto->item.cost) == -1) return -1;
if (fileWriteInt32(stream, proto->item.inventoryFid) == -1) return -1;
if (fileWriteUInt8(stream, proto->item.field_80) == -1) return -1;
if (protoItemDataWrite(&(proto->item.data), proto->item.type, stream) == -1) return -1;
return 0;
case OBJ_TYPE_CRITTER:
if (fileWriteInt32(stream, proto->critter.lightDistance) == -1) return -1;
if (_db_fwriteLong(stream, proto->critter.lightIntensity) == -1) return -1;
if (fileWriteInt32(stream, proto->critter.flags) == -1) return -1;
if (fileWriteInt32(stream, proto->critter.extendedFlags) == -1) return -1;
if (fileWriteInt32(stream, proto->critter.sid) == -1) return -1;
if (fileWriteInt32(stream, proto->critter.headFid) == -1) return -1;
if (fileWriteInt32(stream, proto->critter.aiPacket) == -1) return -1;
if (fileWriteInt32(stream, proto->critter.team) == -1) return -1;
if (protoCritterDataWrite(stream, &(proto->critter.data)) == -1) return -1;
return 0;
case OBJ_TYPE_SCENERY:
if (fileWriteInt32(stream, proto->scenery.lightDistance) == -1) return -1;
if (_db_fwriteLong(stream, proto->scenery.lightIntensity) == -1) return -1;
if (fileWriteInt32(stream, proto->scenery.flags) == -1) return -1;
if (fileWriteInt32(stream, proto->scenery.extendedFlags) == -1) return -1;
if (fileWriteInt32(stream, proto->scenery.sid) == -1) return -1;
if (fileWriteInt32(stream, proto->scenery.type) == -1) return -1;
if (fileWriteInt32(stream, proto->scenery.field_2C) == -1) return -1;
if (fileWriteUInt8(stream, proto->scenery.field_34) == -1) return -1;
if (protoSceneryDataWrite(&(proto->scenery.data), proto->scenery.type, stream) == -1) return -1;
case OBJ_TYPE_WALL:
if (fileWriteInt32(stream, proto->wall.lightDistance) == -1) return -1;
if (_db_fwriteLong(stream, proto->wall.lightIntensity) == -1) return -1;
if (fileWriteInt32(stream, proto->wall.flags) == -1) return -1;
if (fileWriteInt32(stream, proto->wall.extendedFlags) == -1) return -1;
if (fileWriteInt32(stream, proto->wall.sid) == -1) return -1;
if (fileWriteInt32(stream, proto->wall.material) == -1) return -1;
return 0;
case OBJ_TYPE_TILE:
if (fileWriteInt32(stream, proto->tile.flags) == -1) return -1;
if (fileWriteInt32(stream, proto->tile.extendedFlags) == -1) return -1;
if (fileWriteInt32(stream, proto->tile.sid) == -1) return -1;
if (fileWriteInt32(stream, proto->tile.material) == -1) return -1;
return 0;
case OBJ_TYPE_MISC:
if (fileWriteInt32(stream, proto->misc.lightDistance) == -1) return -1;
if (_db_fwriteLong(stream, proto->misc.lightIntensity) == -1) return -1;
if (fileWriteInt32(stream, proto->misc.flags) == -1) return -1;
if (fileWriteInt32(stream, proto->misc.extendedFlags) == -1) return -1;
return 0;
}
return -1;
}
// 0x4A1B30
int _proto_save_pid(int pid)
{
Proto* proto;
if (protoGetProto(pid, &proto) == -1) {
return -1;
}
char path[260];
proto_make_path(path, pid);
strcat(path, "\\");
_proto_list_str(pid, path + strlen(path));
File* stream = fileOpen(path, "wb");
if (stream == nullptr) {
return -1;
}
int rc = protoWrite(proto, stream);
fileClose(stream);
return rc;
}
// 0x4A1C3C
static int _proto_load_pid(int pid, Proto** protoPtr)
{
char path[COMPAT_MAX_PATH];
proto_make_path(path, pid);
strcat(path, "\\");
if (_proto_list_str(pid, path + strlen(path)) == -1) {
return -1;
}
File* stream = fileOpen(path, "rb");
if (stream == nullptr) {
debugPrint("\nError: Can't fopen proto!\n");
*protoPtr = nullptr;
return -1;
}
if (_proto_find_free_subnode(PID_TYPE(pid), protoPtr) == -1) {
fileClose(stream);
return -1;
}
if (protoRead(*protoPtr, stream) != 0) {
fileClose(stream);
return -1;
}
fileClose(stream);
return 0;
}
// 0x4A1D98
static int _proto_find_free_subnode(int type, Proto** protoPtr)
{
Proto* proto = (Proto*)internal_malloc(proto_size(type));
*protoPtr = proto;
if (proto == nullptr) {
return -1;
}
ProtoList* protoList = &(_protoLists[type]);
ProtoListExtent* protoListExtent = protoList->tail;
if (protoList->head != nullptr) {
if (protoListExtent->length == PROTO_LIST_EXTENT_SIZE) {
ProtoListExtent* newExtent = protoListExtent->next = (ProtoListExtent*)internal_malloc(sizeof(ProtoListExtent));
if (protoListExtent == nullptr) {
internal_free(proto);
*protoPtr = nullptr;
return -1;
}
newExtent->length = 0;
newExtent->next = nullptr;
protoList->tail = newExtent;
protoList->length++;
protoListExtent = newExtent;
}
} else {
protoListExtent = (ProtoListExtent*)internal_malloc(sizeof(ProtoListExtent));
if (protoListExtent == nullptr) {
internal_free(proto);
*protoPtr = nullptr;
return -1;
}
protoListExtent->next = nullptr;
protoListExtent->length = 0;
protoList->length = 1;
protoList->tail = protoListExtent;
protoList->head = protoListExtent;
}
protoListExtent->proto[protoListExtent->length] = proto;
protoListExtent->length++;
return 0;
}
// 0x4A1E90
int proto_new(int* pid, int type)
{
Proto* proto;
if (_proto_find_free_subnode(type, &proto) == -1) {
return -1;
}
*pid = _proto_new_id(type) | (type << 24);
switch (type) {
case OBJ_TYPE_ITEM:
proto_item_init(proto, *pid);
proto->item.pid = *pid;
break;
case OBJ_TYPE_CRITTER:
proto_critter_init(proto, *pid);
proto->critter.pid = *pid;
break;
case OBJ_TYPE_SCENERY:
proto_scenery_init(proto, *pid);
proto->scenery.pid = *pid;
break;
case OBJ_TYPE_WALL:
proto_wall_init(proto, *pid);
proto->wall.pid = *pid;
break;
case OBJ_TYPE_TILE:
proto_tile_init(proto, *pid);
proto->tile.pid = *pid;
break;
case OBJ_TYPE_MISC:
proto_misc_init(proto, *pid);
proto->misc.pid = *pid;
break;
default:
return -1;
}
return 0;
}
// Evict top most proto cache block.
//
// 0x4A2040
static void _proto_remove_some_list(int type)
{
ProtoList* protoList = &(_protoLists[type]);
ProtoListExtent* protoListExtent = protoList->head;
if (protoListExtent != nullptr) {
protoList->length--;
protoList->head = protoListExtent->next;
for (int index = 0; index < protoListExtent->length; index++) {
internal_free(protoListExtent->proto[index]);
}
internal_free(protoListExtent);
}
}
// Clear proto cache of given type.
//
// 0x4A2094
static void _proto_remove_list(int type)
{
ProtoList* protoList = &(_protoLists[type]);
ProtoListExtent* curr = protoList->head;
while (curr != nullptr) {
ProtoListExtent* next = curr->next;
for (int index = 0; index < curr->length; index++) {
internal_free(curr->proto[index]);
}
internal_free(curr);
curr = next;
}
protoList->head = nullptr;
protoList->tail = nullptr;
protoList->length = 0;
}
// Clear all proto cache.
//
// 0x4A20F4
void _proto_remove_all()
{
for (int index = 0; index < 6; index++) {
_proto_remove_list(index);
}
}
// proto_ptr
// 0x4A2108
int protoGetProto(int pid, Proto** protoPtr)
{
*protoPtr = nullptr;
if (pid == -1) {
return -1;
}
if (pid == 0x1000000) {
*protoPtr = (Proto*)&gDudeProto;
return 0;
}
ProtoList* protoList = &(_protoLists[PID_TYPE(pid)]);
ProtoListExtent* protoListExtent = protoList->head;
while (protoListExtent != nullptr) {
for (int index = 0; index < protoListExtent->length; index++) {
Proto* proto = (Proto*)protoListExtent->proto[index];
if (pid == proto->pid) {
*protoPtr = proto;
return 0;
}
}
protoListExtent = protoListExtent->next;
}
if (protoList->head != nullptr && protoList->tail != nullptr) {
if (PROTO_LIST_EXTENT_SIZE * protoList->length - (PROTO_LIST_EXTENT_SIZE - protoList->tail->length) > PROTO_LIST_MAX_ENTRIES) {
_proto_remove_some_list(PID_TYPE(pid));
}
}
return _proto_load_pid(pid, protoPtr);
}
// 0x4A21DC
static int _proto_new_id(int type)
{
int result = _protoLists[type].max_entries_num;
_protoLists[type].max_entries_num = result + 1;
return result;
}
// 0x4A2214
int proto_max_id(int type)
{
return _protoLists[type].max_entries_num;
}
// 0x4A22C0
int _ResetPlayer()
{
Proto* proto;
protoGetProto(gDude->pid, &proto);
pcStatsReset();
protoCritterDataResetStats(&(proto->critter.data));
// SFALL: Fix base EMP DR not being properly initialized.
proto->critter.data.baseStats[STAT_DAMAGE_RESISTANCE_EMP] = 100;
critterReset();
characterEditorReset();
protoCritterDataResetSkills(&(proto->critter.data));
skillsReset();
perksReset();
traitsReset();
critterUpdateDerivedStats(gDude);
return 0;
}
} // namespace fallout
| 412 | 0.922974 | 1 | 0.922974 | game-dev | MEDIA | 0.35829 | game-dev | 0.71391 | 1 | 0.71391 |
Space-Stories/space-station-14 | 6,013 | Content.Client/Damage/DamageVisualsComponent.cs | using Content.Shared.FixedPoint;
namespace Content.Client.Damage;
[RegisterComponent]
public sealed partial class DamageVisualsComponent : Component
{
/// <summary>
/// Damage thresholds between damage state changes.
///
/// If there are any negative thresholds, or there is
/// less than one threshold, the visualizer is marked
/// as invalid.
/// </summary>
/// <remarks>
/// A 'zeroth' threshold is automatically added,
/// and this list is automatically sorted for
/// efficiency beforehand. As such, the zeroth
/// threshold is not required - and negative
/// thresholds are automatically caught as
/// invalid. The zeroth threshold automatically
/// sets all layers to invisible, so a sprite
/// isn't required for it.
/// </remarks>
[DataField("thresholds", required: true)]
public List<FixedPoint2> Thresholds = new();
/// <summary>
/// Layers to target, by layerMapKey.
/// If a target layer map key is invalid
/// (in essence, undefined), then the target
/// layer is removed from the list for efficiency.
///
/// If no layers are valid, then the visualizer
/// is marked as invalid.
///
/// If this is not defined, however, the visualizer
/// instead adds an overlay to the sprite.
/// </summary>
/// <remarks>
/// Layers can be disabled here by passing
/// the layer's name as a key to SetData,
/// and passing in a bool set to either 'false'
/// to disable it, or 'true' to enable it.
/// Setting the layer as disabled will make it
/// completely invisible.
/// </remarks>
[DataField("targetLayers")] public List<Enum>? TargetLayers;
/// <summary>
/// The actual sprites for every damage group
/// that the entity should display visually.
///
/// This is keyed by a damage group identifier
/// (for example, Brute), and has a value
/// of a DamageVisualizerSprite (see below)
/// </summary>
[DataField("damageOverlayGroups")] public Dictionary<string, DamageVisualizerSprite>? DamageOverlayGroups;
/// <summary>
/// Sets if you want sprites to overlay the
/// entity when damaged, or if you would
/// rather have each target layer's state
/// replaced by a different state
/// within its RSI.
///
/// This cannot be set to false if:
/// - There are no target layers
/// - There is no damage group
/// </summary>
[DataField("overlay")] public bool Overlay = true;
/// <summary>
/// A single damage group to target.
/// This should only be defined if
/// overlay is set to false.
/// If this is defined with damageSprites,
/// this will be ignored.
/// </summary>
/// <remarks>
/// This is here because otherwise,
/// you would need several permutations
/// of group sprites depending on
/// what kind of damage combination
/// you would want, on which threshold.
/// </remarks>
[DataField("damageGroup")] public string? DamageGroup;
/// <summary>
/// Set this if you want incoming damage to be
/// divided.
/// </summary>
/// <remarks>
/// This is more useful if you have similar
/// damage sprites in between entities,
/// but with different damage thresholds
/// and you want to avoid duplicating
/// these sprites.
/// </remarks>
[DataField("damageDivisor")] public float Divisor = 1;
/// <summary>
/// Set this to track all damage, instead of specific groups.
/// </summary>
/// <remarks>
/// This will only work if you have damageOverlay
/// defined - otherwise, it will not work.
/// </remarks>
[DataField("trackAllDamage")] public bool TrackAllDamage;
/// <summary>
/// This is the overlay sprite used, if _trackAllDamage is
/// enabled. Supports no complex per-group layering,
/// just an actually simple damage overlay. See
/// DamageVisualizerSprite for more information.
/// </summary>
[DataField("damageOverlay")] public DamageVisualizerSprite? DamageOverlay;
public readonly List<Enum> TargetLayerMapKeys = new();
public bool Disabled = false;
public bool Valid = true;
public FixedPoint2 LastDamageThreshold = FixedPoint2.Zero;
public readonly Dictionary<object, bool> DisabledLayers = new();
public readonly Dictionary<object, string> LayerMapKeyStates = new();
public readonly Dictionary<string, FixedPoint2> LastThresholdPerGroup = new();
public string TopMostLayerKey = default!;
}
// deals with the edge case of human damage visuals not
// being in color without making a Dict<Dict<Dict<Dict<Dict<Dict...
[DataDefinition]
public sealed partial class DamageVisualizerSprite
{
/// <summary>
/// The RSI path for the damage visualizer
/// group overlay.
/// </summary>
/// <remarks>
/// States in here will require one of four
/// forms:
///
/// If tracking damage groups:
/// - {base_state}_{group}_{threshold} if targeting
/// a static layer on a sprite (either as an
/// overlay or as a state change)
/// - DamageOverlay_{group}_{threshold} if not
/// targeting a layer on a sprite.
///
/// If not tracking damage groups:
/// - {base_state}_{threshold} if it is targeting
/// a layer
/// - DamageOverlay_{threshold} if not targeting
/// a layer.
/// </remarks>
[DataField("sprite", required: true)] public string Sprite = default!;
/// <summary>
/// The color of this sprite overlay.
/// Supports only hexadecimal format.
/// </summary>
[DataField("color")] public string? Color;
}
| 412 | 0.825596 | 1 | 0.825596 | game-dev | MEDIA | 0.841322 | game-dev | 0.777227 | 1 | 0.777227 |
quiverteam/Engine | 2,065 | src/utils/hammer/blockarray.cpp | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include <windows.h>
#include <stdio.h>
template <class T, int nBlockSize, int nMaxBlocks>
class BlockArray
{
public:
BlockArray()
{
nCount = nBlocks = 0;
}
~BlockArray()
{
GetBlocks(0);
}
T& operator[] (int iIndex);
void SetCount(int nObjects);
int GetCount() { return nCount; }
private:
T * Blocks[nMaxBlocks+1];
short nCount;
short nBlocks;
void GetBlocks(int nNewBlocks);
};
/*
template <class T, int nBlockSize, int nMaxBlocks>
BlockArray<T,BlockSize,nMaxBlocks>::BlockArray()
{
nCount = nBlocks = 0;
}
template <class T, int nBlockSize, int nMaxBlocks>
BlockArray<T,BlockSize,nMaxBlocks>::~BlockArray()
{
GetBlocks(0); // free blocks
}
*/
template <class T, int nBlockSize, int nMaxBlocks>
void BlockArray<T,nBlockSize,nMaxBlocks>::
GetBlocks(int nNewBlocks)
{
for(int i = nBlocks; i < nNewBlocks; i++)
{
Blocks[i] = new T[nBlockSize];
}
for(i = nNewBlocks; i < nBlocks; i++)
{
delete[] Blocks[i];
}
nBlocks = nNewBlocks;
}
template <class T, int nBlockSize, int nMaxBlocks>
void BlockArray<T,nBlockSize,nMaxBlocks>::
SetCount(int nObjects)
{
if(nObjects == nCount)
return;
// find the number of blocks required by nObjects
int nNewBlocks = (nObjects / nBlockSize) + 1;
if(nNewBlocks != nBlocks)
GetBlocks(nNewBlocks);
nCount = nObjects;
}
template <class T, int nBlockSize, int nMaxBlocks>
T& BlockArray<T,nBlockSize,nMaxBlocks>::operator[] (int iIndex)
{
if(iIndex >= nCount)
SetCount(iIndex+1);
return Blocks[iIndex / nBlockSize][iIndex % nBlockSize];
}
typedef struct
{
char Name[128];
int iValue;
} Buffy;
void main(void)
{
BlockArray<Buffy, 16, 16> Buffies;
for(int i = 0; i < 256; i++)
{
Buffies[i].iValue = i;
strcpy(Buffies[i].Name, "Buk bUk buK");
}
for(i = 0; i < 256; i++)
{
printf("%d: %s\n", Buffies[i].iValue, Buffies[i].Name);
}
Buffies.SetCount(10);
} | 412 | 0.728142 | 1 | 0.728142 | game-dev | MEDIA | 0.22537 | game-dev | 0.826047 | 1 | 0.826047 |
etodd/Lemma | 2,108 | Lemma/Factories/WorldFactory.cs | using System; using ComponentBind;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lemma.Components;
using Microsoft.Xna.Framework;
using Lemma.Util;
namespace Lemma.Factories
{
public class WorldFactory : Factory<Main>
{
private Random random = new Random();
private static Entity instance;
public WorldFactory()
{
this.Color = new Vector3(0.1f, 0.1f, 0.1f);
this.EditorCanSpawn = false;
}
public static Entity Instance
{
get
{
if (WorldFactory.instance == null)
return null;
if (!WorldFactory.instance.Active)
WorldFactory.instance = null;
return WorldFactory.instance;
}
}
public override Entity Create(Main main)
{
Entity entity = new Entity(main, "World");
entity.Add("Transform", new Transform());
return entity;
}
public override void Bind(Entity entity, Main main, bool creating = false)
{
entity.CannotSuspend = true;
entity.EditorCanDelete = false;
World world = entity.GetOrCreate<World>("World");
// Zone management
entity.GetOrCreate<Propagator>("Propagator");
this.SetMain(entity, main);
WorldFactory.instance = entity;
AkSoundEngine.DefaultGameObject = entity;
entity.Add("OverlayTexture", world.OverlayTexture, new PropertyEntry.EditorData
{
Options = FileFilter.Get(main, main.Content.RootDirectory, new[] { "Textures" }),
});
entity.Add("OverlayTiling", world.OverlayTiling);
entity.Add("LightRampTexture", world.LightRampTexture, new PropertyEntry.EditorData
{
Options = FileFilter.Get(main, main.Content.RootDirectory, new[] { "LightRamps" }),
});
entity.Add("EnvironmentMap", world.EnvironmentMap, new PropertyEntry.EditorData
{
Options = FileFilter.Get(main, main.Content.RootDirectory, new[] { "EnvironmentMaps" }),
});
entity.Add("EnvironmentColor", world.EnvironmentColor);
entity.Add("BackgroundColor", world.BackgroundColor);
entity.Add("FarPlaneDistance", world.FarPlaneDistance);
entity.Add("Gravity", world.Gravity);
entity.Add("ThumbnailCamera", world.ThumbnailCamera);
}
}
}
| 412 | 0.679001 | 1 | 0.679001 | game-dev | MEDIA | 0.866152 | game-dev | 0.634623 | 1 | 0.634623 |
quakeshack/engine | 10,749 | source/engine/client/SCR.mjs | /* global */
import { gameCapabilities } from '../../shared/Defs.mjs';
import Cmd from '../common/Cmd.mjs';
import Cvar from '../common/Cvar.mjs';
import { eventBus, registry } from '../registry.mjs';
import GL from './GL.mjs';
import VID from './VID.mjs';
let { CL, Con, Draw, Host, Key, M, R, S, Sbar, V } = registry;
eventBus.subscribe('registry.frozen', () => {
CL = registry.CL;
Con = registry.Con;
Draw = registry.Draw;
Host = registry.Host;
Key = registry.Key;
M = registry.M;
R = registry.R;
S = registry.S;
Sbar = registry.Sbar;
V = registry.V;
});
/** @type {WebGL2RenderingContext} */
let gl = null;
eventBus.subscribe('gl.ready', () => {
gl = GL.gl;
});
eventBus.subscribe('gl.shutdown', () => {
gl = null;
});
const SCR = {};
export default SCR;
eventBus.subscribe('vid.resize', () => {
SCR.recalc_refdef = true;
});
eventBus.subscribe('server.spawning', () => {
SCR.centertime_off = 0.0;
});
SCR.con_current = 0;
SCR.centerstring = [];
SCR.centertime_off = 0.0;
SCR._requestedAnimationFrames = 0;
SCR.CenterPrint = function(str) {
SCR.centerstring = [];
let i; let start = 0; let next;
for (i = 0; i < str.length; i++) {
if (str.charCodeAt(i) === 10) {
next = i + 1;
} else if ((i - start) >= 40) {
next = i;
} else {
continue;
}
SCR.centerstring[SCR.centerstring.length] = str.substring(start, i);
start = next;
}
SCR.centerstring[SCR.centerstring.length] = str.substring(start, i);
SCR.centertime_off = SCR.centertime.value;
SCR.centertime_start = CL.state.time;
};
SCR.DrawCenterString = function() {
SCR.centertime_off -= Host.frametime;
if (((SCR.centertime_off <= 0.0) && (CL.state.intermission === 0)) || (Key.dest.value !== Key.dest.game)) {
return;
}
let y;
if (SCR.centerstring.length <= 4) {
y = Math.floor(VID.height * 0.35);
} else {
y = 48;
}
let i;
if (CL.state.intermission) {
let remaining = Math.floor(SCR.printspeed.value * (CL.state.time - SCR.centertime_start));
let str; let x; let j;
for (i = 0; i < SCR.centerstring.length; i++) {
str = SCR.centerstring[i];
x = (VID.width - (str.length * 8)) / 2;
for (j = 0; j < str.length; j++) {
Draw.Character(x, y, str.charCodeAt(j));
if ((remaining--) === 0) {
return;
}
x += 8;
}
y += 8;
}
return;
}
for (i = 0; i < SCR.centerstring.length; i++) {
Draw.String((VID.width - (SCR.centerstring[i].length * 8)) / 2, y, SCR.centerstring[i]);
y += 8;
}
};
SCR.CalcRefdef = function() {
// TODO: we need to emit an event here and the others have to observe (Sbar, R, GL)
SCR.recalc_refdef = false;
if (SCR.viewsize.value < 30) {
Cvar.Set('viewsize', '30');
} else if (SCR.viewsize.value > 120) {
Cvar.Set('viewsize', '120');
}
let size; let full;
if (CL.state.intermission !== 0) {
full = true;
size = 1.0;
Sbar.lines = 0;
} else {
size = SCR.viewsize.value;
if (size >= 120.0) {
Sbar.lines = 0;
} else if (size >= 110.0) {
Sbar.lines = 24;
} else {
Sbar.lines = 48;
}
if (size >= 100.0) {
full = true;
size = 100.0;
}
size *= 0.01;
}
const vrect = R.refdef.vrect;
vrect.width = Math.floor(VID.width * size);
if (vrect.width < 96) {
size = 96.0 / vrect.width;
vrect.width = 96;
}
vrect.height = Math.floor(VID.height * size);
if (vrect.height > (VID.height - Sbar.lines)) {
vrect.height = VID.height - Sbar.lines;
}
vrect.x = (VID.width - vrect.width) / 2;
if (full === true) {
vrect.y = 0;
} else {
vrect.y = (VID.height - Sbar.lines - vrect.height) / 2;
}
if (SCR.fov.value < 10) {
Cvar.Set('fov', '10');
} else if (SCR.fov.value > 170) {
Cvar.Set('fov', '170');
}
if ((vrect.width * 0.75) <= vrect.height) {
R.refdef.fov_x = SCR.fov.value;
R.refdef.fov_y = Math.atan(vrect.height / (vrect.width / Math.tan(SCR.fov.value * Math.PI / 360.0))) * 360.0 / Math.PI;
} else {
R.refdef.fov_x = Math.atan(vrect.width / (vrect.height / Math.tan(SCR.fov.value * 0.82 * Math.PI / 360.0))) * 360.0 / Math.PI;
R.refdef.fov_y = SCR.fov.value * 0.82;
}
const ymax = 4.0 * Math.tan(R.refdef.fov_y * Math.PI / 360.0);
R.perspective[0] = 4.0 / (ymax * R.refdef.vrect.width / R.refdef.vrect.height);
R.perspective[5] = 4.0 / ymax;
R.warpwidth = (vrect.width * VID.pixelRatio) >> 0;
R.warpheight = (vrect.height * VID.pixelRatio) >> 0;
if (R.warpwidth > 2048) {
R.warpwidth = 2048;
}
if (R.warpheight > 2048) {
R.warpheight = 2048;
}
if ((R.oldwarpwidth !== R.warpwidth) || (R.oldwarpheight !== R.warpheight)) {
R.oldwarpwidth = R.warpwidth;
R.oldwarpheight = R.warpheight;
GL.Bind(0, R.warptexture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, R.warpwidth, R.warpheight, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.bindRenderbuffer(gl.RENDERBUFFER, R.warprenderbuffer);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, R.warpwidth, R.warpheight);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
}
};
SCR.SizeUp_f = function() {
Cvar.SetValue('viewsize', SCR.viewsize.value + 10);
SCR.recalc_refdef = true;
};
SCR.SizeDown_f = function() {
Cvar.SetValue('viewsize', SCR.viewsize.value - 10);
SCR.recalc_refdef = true;
};
SCR.disableCrosshair = false;
SCR.Init = async function() {
SCR.fov = new Cvar('fov', '90', Cvar.FLAG.CHEAT); // TODO: move to R?
SCR.viewsize = new Cvar('viewsize', '100', Cvar.FLAG.ARCHIVE);
SCR.conspeed = new Cvar('scr_conspeed', '300');
SCR.showturtle = new Cvar('showturtle', '0');
SCR.showpause = new Cvar('showpause', '1');
SCR.centertime = new Cvar('scr_centertime', '2');
SCR.printspeed = new Cvar('scr_printspeed', '8');
Cmd.AddCommand('screenshot', SCR.ScreenShot_f);
Cmd.AddCommand('sizeup', SCR.SizeUp_f);
Cmd.AddCommand('sizedown', SCR.SizeDown_f);
SCR.net = Draw.LoadPicFromWad('NET');
SCR.turtle = Draw.LoadPicFromWad('TURTLE');
SCR.pause = Draw.LoadPicFromLumpDeferred('pause');
SCR.crosshair = new Cvar('crosshair', '0', Cvar.FLAG.ARCHIVE);
SCR.crossx = new Cvar('cl_crossx', '0', Cvar.FLAG.ARCHIVE);
SCR.crossy = new Cvar('cl_crossy', '0', Cvar.FLAG.ARCHIVE);
SCR.disableCrosshair = CL.gameCapabilities.includes(gameCapabilities.CAP_HUD_INCLUDES_CROSSHAIR);
};
SCR.count = 0;
SCR.DrawTurtle = function() {
if (SCR.showturtle.value === 0) {
return;
}
if (Host.frametime < 0.1) {
SCR.count = 0;
return;
}
if (++SCR.count >= 3) {
Draw.Pic(R.refdef.vrect.x, R.refdef.vrect.y, SCR.turtle);
}
};
SCR.DrawNet = function() {
if (((Host.realtime - CL.state.last_received_message) >= 0.3) && (CL.cls.demoplayback !== true)) {
Draw.Pic(R.refdef.vrect.x, R.refdef.vrect.y, SCR.net);
}
};
SCR.DrawPause = function() {
if ((SCR.showpause.value !== 0) && (CL.state.paused === true)) {
Draw.Pic((VID.width - SCR.pause.width) / 2, (VID.height - 48 - SCR.pause.height) / 2, SCR.pause);
}
};
SCR.SetUpToDrawConsole = function() {
Con.forcedup = (!CL.state.worldmodel) || (CL.cls.signon !== 4);
if (Con.forcedup === true) {
SCR.con_current = 200;
return;
}
let conlines;
if (Key.dest.value === Key.dest.console) {
conlines = 100;
} else {
conlines = 0;
}
if (conlines < SCR.con_current) {
SCR.con_current -= SCR.conspeed.value * Host.frametime;
if (conlines > SCR.con_current) {
SCR.con_current = conlines;
}
} else if (conlines > SCR.con_current) {
SCR.con_current += SCR.conspeed.value * Host.frametime;
if (conlines < SCR.con_current) {
SCR.con_current = conlines;
}
}
};
SCR.DrawConsole = function() {
if (SCR.con_current > 0) {
Con.DrawConsole(SCR.con_current);
return;
}
if ((Key.dest.value === Key.dest.game) || (Key.dest.value === Key.dest.message)) {
Con.DrawNotify();
}
};
SCR.ScreenShot_f = function() {
SCR.screenshot = true;
};
SCR.BeginLoadingPlaque = function() {
S.StopAllSounds();
if ((CL.cls.state !== CL.active.connected) || (CL.cls.signon !== 4)) {
return;
}
SCR.centertime_off = 0.0;
SCR.con_current = 0;
SCR.disabled_for_loading = true;
SCR.disabled_time = Host.realtime + 60.0;
};
SCR.EndLoadingPlaque = function() {
Draw.EndDisc();
SCR.disabled_for_loading = false;
Con.ClearNotify();
};
SCR.UpdateScreen = function() {
// if (SCR.disabled_for_loading === true) {
// if (Host.realtime <= SCR.disabled_time) {
// return;
// }
// SCR.disabled_for_loading = false;
// Con.Print('load failed.\n');
// }
if (SCR.oldfov !== SCR.fov.value) {
SCR.oldfov = SCR.fov.value;
SCR.recalc_refdef = true;
}
if (SCR.oldscreensize !== SCR.viewsize.value) {
SCR.oldscreensize = SCR.viewsize.value;
SCR.recalc_refdef = true;
}
if (SCR.recalc_refdef === true) {
SCR.CalcRefdef();
}
SCR.SetUpToDrawConsole();
if (SCR._requestedAnimationFrames > 0) {
console.assert(SCR._requestedAnimationFrames === 1, 'SCR.UpdateScreen: too many rendering requests active');
return;
}
requestAnimationFrame(() => {
// we are already shutting down
if (!gl) {
return;
}
V.RenderView();
GL.Set2D();
if (R.dowarp === true) {
R.WarpScreen();
}
if (Con.forcedup !== true) {
R.PolyBlend();
}
if (CL.cls.state === CL.active.connecting) {
CL.Draw();
} else if ((CL.state.intermission === 1) && (Key.dest.value === Key.dest.game)) {
if (!CL.sbarDisabled) {
Sbar.IntermissionOverlay();
} else {
CL.DrawHUD();
}
} else if ((CL.state.intermission === 2) && (Key.dest.value === Key.dest.game)) {
if (!CL.sbarDisabled) {
Sbar.FinaleOverlay();
SCR.DrawCenterString();
} else {
CL.DrawHUD();
}
} else if ((CL.state.intermission === 3) && (Key.dest.value === Key.dest.game)) {
if (!CL.sbarDisabled) {
SCR.DrawCenterString();
} else {
CL.DrawHUD();
}
} else {
if (!SCR.disableCrosshair && SCR.crosshair.value !== 0) {
Draw.Character(R.refdef.vrect.x + (R.refdef.vrect.width / 2) + SCR.crossx.value,
R.refdef.vrect.y + (R.refdef.vrect.height / 2) + SCR.crossy.value, 43);
}
SCR.DrawNet();
SCR.DrawTurtle();
SCR.DrawPause();
SCR.DrawCenterString();
CL.DrawHUD();
SCR.DrawConsole();
CL.Draw();
M.Draw();
}
GL.StreamFlush();
gl.disable(gl.BLEND);
SCR._requestedAnimationFrames--;
});
SCR._requestedAnimationFrames++;
if (SCR.screenshot === true) {
SCR.screenshot = false;
gl.finish();
VID.DownloadScreenshot();
}
};
| 412 | 0.770705 | 1 | 0.770705 | game-dev | MEDIA | 0.533175 | game-dev,graphics-rendering | 0.941215 | 1 | 0.941215 |
529324416/MissionSystem | 1,478 | Assets/ParadoxNotion/NodeCanvas/Modules/BehaviourTrees/Nodes/Leafs/ActionNode.cs | using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;
namespace NodeCanvas.BehaviourTrees
{
[Name("Action")]
[Description("Executes an action and returns Success or Failure when the action is finished.\nReturns Running until the action is finished.")]
[ParadoxNotion.Design.Icon("Action")]
// [Color("ff6d53")]
public class ActionNode : BTNode, ITaskAssignable<ActionTask>
{
[SerializeField]
private ActionTask _action;
public Task task {
get { return action; }
set { action = (ActionTask)value; }
}
public ActionTask action {
get { return _action; }
set { _action = value; }
}
public override string name {
get { return base.name.ToUpper(); }
}
protected override Status OnExecute(Component agent, IBlackboard blackboard) {
if ( action == null ) {
return Status.Optional;
}
if ( status == Status.Resting || status == Status.Running ) {
return action.Execute(agent, blackboard);
}
return status;
}
protected override void OnReset() {
if ( action != null ) {
action.EndAction(null);
}
}
public override void OnGraphPaused() {
if ( action != null ) {
action.Pause();
}
}
}
} | 412 | 0.689476 | 1 | 0.689476 | game-dev | MEDIA | 0.809433 | game-dev | 0.920537 | 1 | 0.920537 |
hlrs-vis/covise | 2,780 | src/module/hlrs/ReadFconfig/ReadFconfig.cpp | /* This file is part of COVISE.
You can use it under the terms of the GNU Lesser General Public License
version 2.1 or later, see lgpl-2.1.txt.
* License: LGPL 2+ */
#include <stdlib.h>
#include <stdio.h>
#include <util/coviseCompat.h>
#include <do/coDoUniformGrid.h>
#include <do/coDoData.h>
#include <appl/ApplInterface.h>
#include "ReadFconfig.h"
/*************************************************************
*************************************************************
** **
** K o n s t r u k t o r **
** **
*************************************************************
*************************************************************/
ReadFconfig::ReadFconfig(int argc, char *argv[])
: coSimpleModule(argc, argv, "Simulation coupling")
{
////////// set up default parameters
set_module_description("ReadFconfig Simulation");
fileName = addFileBrowserParam("configFile", "configFile");
fileName->setValue("C:/src/test/testit/Release","Fconfig.txt");
fileName->setFilter("*.txt");
dimX = addInt32Param("X", "DimensionInX");
dimX->setValue(100);
dimY = addInt32Param("Y", "DimensionInY");
dimY->setValue(100);
dimZ = addInt32Param("Z", "DimensionInZ");
dimZ->setValue(100);
// Output ports:
mesh = addOutputPort("mesh", "UniformGrid", "Mesh Output");
data = addOutputPort("data", "Float", "ScalarData");
}
int ReadFconfig::compute(const char *port)
{
(void)port;
// create mesh
createMesh();
int x_dim = dimX->getValue();
int y_dim = dimY->getValue();
int z_dim = dimZ->getValue();
float *fData;
coDoFloat *floatData = new coDoFloat(data->getNewObjectInfo(), x_dim * y_dim * z_dim);
floatData->getAddress(&fData);
memset(fData,0,x_dim * y_dim * z_dim*sizeof(float));
FILE *fp = fopen(fileName->getValue(),"r");
char buf[200];
if(fp !=NULL)
{
while(!feof(fp))
{
fgets(buf,200,fp);
int i,j,k;
sscanf(buf,"%d %d %d",&i,&j,&k);
fData[i*x_dim*y_dim + j*y_dim + k] = 1.0;
}
fclose(fp);
}
return SUCCESS;
}
/*************************************************************
*************************************************************/
// create a Grid
void ReadFconfig::createMesh()
{
int xDim, yDim, zDim;
xDim = dimX->getValue();
yDim = dimY->getValue();
zDim = dimZ->getValue();
coDoUniformGrid *grid = new coDoUniformGrid(mesh->getObjName(), xDim, yDim, zDim, 0, xDim - 1, 0, (float)(yDim - 1), 0, (float)(zDim - 1));
mesh->setCurrentObject(grid);
}
void ReadFconfig::param(const char *paramname, bool inMapLoading)
{
(void)inMapLoading;
}
MODULE_MAIN(IO, ReadFconfig)
| 412 | 0.705003 | 1 | 0.705003 | game-dev | MEDIA | 0.232703 | game-dev | 0.880961 | 1 | 0.880961 |
facebookarchive/fbctf | 1,673 | src/data/configuration.php | <?hh // strict
require_once ($_SERVER['DOCUMENT_ROOT'].'/../vendor/autoload.php');
class ConfigurationController extends DataController {
public async function genGenerateData(): Awaitable<void> {
/* HH_IGNORE_ERROR[1002] */
SessionUtils::sessionStart();
SessionUtils::enforceLogin();
$conf_data = (object) array();
$control = new Control();
$awaitables = Map {
'gameboard' => Configuration::gen('gameboard'),
'gameboard_cycle' => Configuration::gen('gameboard_cycle'),
'conf_cycle' => Configuration::gen('conf_cycle'),
};
$awaitables_results = await \HH\Asio\m($awaitables);
$gameboard = $awaitables_results['gameboard'];
// Refresh rate for teams/leaderboard in milliseconds
// Refresh rate for map/announcements in milliseconds
$gameboard_cycle = $awaitables_results['gameboard_cycle'];
// Refresh rate for configuration values in milliseconds
// Refresh rate for commands in milliseconds
$conf_cycle = $awaitables_results['conf_cycle'];
/* HH_FIXME[1002] */
/* HH_FIXME[2011] */
$conf_data->{'currentTeam'} = SessionUtils::sessionTeamName();
$conf_data->{'gameboard'} = $gameboard->getValue();
$conf_data->{'refreshTeams'} = ($gameboard_cycle->getValue()) * 1000;
$conf_data->{'refreshMap'} = ($gameboard_cycle->getValue()) * 1000;
$conf_data->{'refreshConf'} = ($conf_cycle->getValue()) * 1000;
$conf_data->{'refreshCmd'} = ($conf_cycle->getValue()) * 1000;
$conf_data->{'progressiveCount'} = await Progressive::genCount();
$this->jsonSend($conf_data);
}
}
$confController = new ConfigurationController();
$confController->sendData();
| 412 | 0.895329 | 1 | 0.895329 | game-dev | MEDIA | 0.349434 | game-dev | 0.732832 | 1 | 0.732832 |
KaosSpectrum/KaosGameFramework | 6,781 | Source/KaosGASUtilities/Private/BehaviourTrees/KaosBTDecorator_GameplayTagQuery.cpp | // Copyright (C) 2024, Daniel Moss
//
// 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 "BehaviourTrees/KaosBTDecorator_GameplayTagQuery.h"
#include "AbilitySystemComponent.h"
#include "AbilitySystemGlobals.h"
#include "BehaviorTree/BlackboardComponent.h"
#include "BehaviorTree/Blackboard/BlackboardKeyType_Object.h"
#include UE_INLINE_GENERATED_CPP_BY_NAME(KaosBTDecorator_GameplayTagQuery)
struct FKaosBTDecorator_GameplayTagQueryMemory
{
TWeakObjectPtr<UAbilitySystemComponent> CachedAbilitySystemComponent;
/** Array of handles for our gameplay tag query delegates */
TArray<TTuple<FGameplayTag, FDelegateHandle>> GameplayTagEventHandles;
};
UKaosBTDecorator_GameplayTagQuery::UKaosBTDecorator_GameplayTagQuery(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
NodeName = "Kaos Gameplay Tag Query";
INIT_DECORATOR_NODE_NOTIFY_FLAGS();
// Accept only actors
ActorForGameplayTagQuery.AddObjectFilter(this, GET_MEMBER_NAME_CHECKED(UKaosBTDecorator_GameplayTagQuery, ActorForGameplayTagQuery), AActor::StaticClass());
// Default to using Self Actor
ActorForGameplayTagQuery.SelectedKeyName = FBlackboard::KeySelf;
}
bool UKaosBTDecorator_GameplayTagQuery::CalculateRawConditionValue(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) const
{
const UBlackboardComponent* BlackboardComp = OwnerComp.GetBlackboardComponent();
if (!BlackboardComp)
{
// Not calling super here since it returns true
return false;
}
const IGameplayTagAssetInterface* GameplayTagAssetInterface = Cast<IGameplayTagAssetInterface>(BlackboardComp->GetValue<UBlackboardKeyType_Object>(ActorForGameplayTagQuery.GetSelectedKeyID()));
if (!GameplayTagAssetInterface)
{
// Not calling super here since it returns true
return false;
}
FGameplayTagContainer SelectedActorTags;
GameplayTagAssetInterface->GetOwnedGameplayTags(SelectedActorTags);
return GameplayTagQuery.Matches(SelectedActorTags);
}
void UKaosBTDecorator_GameplayTagQuery::OnGameplayTagInQueryChanged(const FGameplayTag InTag, int32 NewCount, TWeakObjectPtr<UBehaviorTreeComponent> BehaviorTreeComponent, uint8* NodeMemory)
{
if (!BehaviorTreeComponent.IsValid())
{
return;
}
ConditionalFlowAbort(*BehaviorTreeComponent, EBTDecoratorAbortRequest::ConditionResultChanged);
}
FString UKaosBTDecorator_GameplayTagQuery::GetStaticDescription() const
{
return FString::Printf(TEXT("%s: %s"), *Super::GetStaticDescription(), *GameplayTagQuery.GetDescription());
}
void UKaosBTDecorator_GameplayTagQuery::CleanupMemory(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, EBTMemoryClear::Type CleanupType) const
{
const FKaosBTDecorator_GameplayTagQueryMemory* MyMemory = CastInstanceNodeMemory<FKaosBTDecorator_GameplayTagQueryMemory>(NodeMemory);
ensureMsgf(MyMemory->GameplayTagEventHandles.Num() == 0, TEXT("Dangling gameplay tag event handles for decorator %s"), *GetStaticDescription());
}
void UKaosBTDecorator_GameplayTagQuery::OnBecomeRelevant(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
UBlackboardComponent* BlackboardComp = OwnerComp.GetBlackboardComponent();
if (!BlackboardComp)
{
// Not calling super here since it does nothing
return;
}
const AActor* SelectedActor = Cast<AActor>(BlackboardComp->GetValue<UBlackboardKeyType_Object>(ActorForGameplayTagQuery.GetSelectedKeyID()));
if (!SelectedActor)
{
// Not calling super here since it does nothing
return;
}
FKaosBTDecorator_GameplayTagQueryMemory* MyMemory = CastInstanceNodeMemory<FKaosBTDecorator_GameplayTagQueryMemory>(NodeMemory);
MyMemory->CachedAbilitySystemComponent = UAbilitySystemGlobals::GetAbilitySystemComponentFromActor(SelectedActor);
if (MyMemory->CachedAbilitySystemComponent.IsValid())
{
for (const FGameplayTag& CurrentTag : QueryTags)
{
FDelegateHandle GameplayTagEventCallbackDelegate = MyMemory->CachedAbilitySystemComponent.Get()->RegisterGameplayTagEvent(CurrentTag, EGameplayTagEventType::Type::AnyCountChange).AddUObject(
this, &UKaosBTDecorator_GameplayTagQuery::OnGameplayTagInQueryChanged, TWeakObjectPtr<UBehaviorTreeComponent>(&OwnerComp), NodeMemory);
MyMemory->GameplayTagEventHandles.Emplace(CurrentTag, GameplayTagEventCallbackDelegate);
}
}
}
void UKaosBTDecorator_GameplayTagQuery::OnCeaseRelevant(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
FKaosBTDecorator_GameplayTagQueryMemory* MyMemory = CastInstanceNodeMemory<FKaosBTDecorator_GameplayTagQueryMemory>(NodeMemory);
if (MyMemory->CachedAbilitySystemComponent.IsValid())
{
for (const TTuple<FGameplayTag, FDelegateHandle>& GameplayTagEvent : MyMemory->GameplayTagEventHandles)
{
MyMemory->CachedAbilitySystemComponent.Get()->RegisterGameplayTagEvent(GameplayTagEvent.Key, EGameplayTagEventType::Type::AnyCountChange).Remove(GameplayTagEvent.Value);
}
}
MyMemory->GameplayTagEventHandles.Reset();
MyMemory->CachedAbilitySystemComponent = nullptr;
}
uint16 UKaosBTDecorator_GameplayTagQuery::GetInstanceMemorySize() const
{
return sizeof(FKaosBTDecorator_GameplayTagQueryMemory);
}
#if WITH_EDITOR
void UKaosBTDecorator_GameplayTagQuery::CacheGameplayTagsInsideQuery()
{
QueryTags.Reset();
GameplayTagQuery.GetGameplayTagArray(QueryTags);
}
void UKaosBTDecorator_GameplayTagQuery::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
if (PropertyChangedEvent.Property == nullptr)
{
return;
}
CacheGameplayTagsInsideQuery();
}
#endif // WITH_EDITOR
void UKaosBTDecorator_GameplayTagQuery::InitializeFromAsset(UBehaviorTree& Asset)
{
Super::InitializeFromAsset(Asset);
const UBlackboardData* BBAsset = GetBlackboardAsset();
if (ensure(BBAsset))
{
ActorForGameplayTagQuery.ResolveSelectedKey(*BBAsset);
}
}
| 412 | 0.657784 | 1 | 0.657784 | game-dev | MEDIA | 0.97304 | game-dev | 0.783419 | 1 | 0.783419 |
Dr-Rank/GMASExSKGv2 | 1,522 | Plugins/GMCAbilitySystem/Source/GMCAbilitySystem/Public/Ability/Tasks/WaitForGameplayTagChange.h | #pragma once
#include "CoreMinimal.h"
#include "GMCAbilityTaskBase.h"
#include "WaitForGameplayTagChange.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGMCAbilityTaskWaitForGameplayTagChangeAsyncActionPin, FGameplayTagContainer, MatchedTags);
UENUM()
enum EGMCWaitForGameplayTagChangeType : uint8
{
Set UMETA(Tooltip="A matching gameplay tag must be present."),
Unset UMETA(Tooltip="A matching gameplay tag CANNOT be present."),
Changed UMETA(Tooltip="A matching gameplay tag must change state.")
};
/**
* Wait for a change in active gameplay tags matching a provided filter.
*/
UCLASS()
class GMCABILITYSYSTEM_API UGMCAbilityTask_WaitForGameplayTagChange : public UGMCAbilityTaskBase
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintAssignable)
FGMCAbilityTaskWaitForGameplayTagChangeAsyncActionPin Completed;
FGameplayTagContainer Tags;
EGMCWaitForGameplayTagChangeType ChangeType;
UFUNCTION(BlueprintCallable, meta=(BlueprintInternalUseOnly="true", HidePin="OwningAbility", DefaultToSelf="OwningAbility", DisplayName="Wait for Gameplay Tag Change"), Category="GMCAbilitySystem|Tasks")
static UGMCAbilityTask_WaitForGameplayTagChange* WaitForGameplayTagChange(UGMCAbility* OwningAbility, const FGameplayTagContainer& WatchedTags, EGMCWaitForGameplayTagChangeType ChangeType = Changed);
virtual void Activate() override;
virtual void OnGameplayTagChanged(const FGameplayTagContainer& AddedTags, const FGameplayTagContainer& RemovedTags);
private:
FDelegateHandle ChangeDelegate;
};
| 412 | 0.736678 | 1 | 0.736678 | game-dev | MEDIA | 0.896597 | game-dev | 0.622969 | 1 | 0.622969 |
DustinRepo/JexClient | 1,742 | src/main/java/me/dustin/jex/load/mixin/minecraft/MixinInGameOverlayRenderer.java | package me.dustin.jex.load.mixin.minecraft;
import me.dustin.jex.event.render.EventRenderOverlay;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.hud.InGameOverlayRenderer;
import net.minecraft.client.texture.Sprite;
import net.minecraft.client.util.math.MatrixStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(InGameOverlayRenderer.class)
public class MixinInGameOverlayRenderer {
@Inject(method = "renderFireOverlay", at = @At("HEAD"), cancellable = true)
private static void renderFire(MinecraftClient minecraftClient, MatrixStack matrixStack, CallbackInfo ci) {
EventRenderOverlay eventRenderOverlay = new EventRenderOverlay(EventRenderOverlay.Overlay.FIRE).run();
if (eventRenderOverlay.isCancelled())
ci.cancel();
}
@Inject(method = "renderUnderwaterOverlay", at = @At("HEAD"), cancellable = true)
private static void renderUnderWater(MinecraftClient minecraftClient, MatrixStack matrixStack, CallbackInfo ci) {
EventRenderOverlay eventRenderOverlay = new EventRenderOverlay(EventRenderOverlay.Overlay.UNDERWATER).run();
if (eventRenderOverlay.isCancelled())
ci.cancel();
}
@Inject(method = "renderInWallOverlay", at = @At("HEAD"), cancellable = true)
private static void renderInWall(Sprite sprite, MatrixStack matrixStack, CallbackInfo ci) {
EventRenderOverlay eventRenderOverlay = new EventRenderOverlay(EventRenderOverlay.Overlay.IN_WALL).run();
if (eventRenderOverlay.isCancelled())
ci.cancel();
}
}
| 412 | 0.512668 | 1 | 0.512668 | game-dev | MEDIA | 0.879654 | game-dev,graphics-rendering | 0.67012 | 1 | 0.67012 |
kami-blue/client | 16,262 | src/main/kotlin/org/kamiblue/client/module/modules/combat/CombatSetting.kt | package org.kamiblue.client.module.modules.combat
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import net.minecraft.entity.Entity
import net.minecraft.entity.EntityLivingBase
import net.minecraft.entity.item.EntityEnderCrystal
import net.minecraft.entity.passive.AbstractHorse
import net.minecraft.entity.passive.EntityTameable
import net.minecraft.item.ItemFood
import net.minecraft.item.ItemPickaxe
import net.minecraft.util.EnumHand
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Vec3d
import net.minecraftforge.fml.common.gameevent.TickEvent
import org.kamiblue.client.event.SafeClientEvent
import org.kamiblue.client.event.events.RenderOverlayEvent
import org.kamiblue.client.manager.managers.CombatManager
import org.kamiblue.client.module.Category
import org.kamiblue.client.module.Module
import org.kamiblue.client.module.modules.player.AutoEat
import org.kamiblue.client.process.PauseProcess
import org.kamiblue.client.process.PauseProcess.pauseBaritone
import org.kamiblue.client.process.PauseProcess.unpauseBaritone
import org.kamiblue.client.util.*
import org.kamiblue.client.util.color.ColorHolder
import org.kamiblue.client.util.combat.CombatUtils
import org.kamiblue.client.util.combat.CrystalUtils.calcCrystalDamage
import org.kamiblue.client.util.combat.CrystalUtils.getPlacePos
import org.kamiblue.client.util.graphics.*
import org.kamiblue.client.util.math.RotationUtils.getRelativeRotation
import org.kamiblue.client.util.math.Vec2d
import org.kamiblue.client.util.math.VectorUtils.distanceTo
import org.kamiblue.client.util.math.VectorUtils.toVec3dCenter
import org.kamiblue.client.util.threads.defaultScope
import org.kamiblue.client.util.threads.isActiveOrFalse
import org.kamiblue.client.util.threads.runSafeR
import org.kamiblue.client.util.threads.safeListener
import org.kamiblue.commons.extension.ceilToInt
import org.kamiblue.event.listener.listener
import org.lwjgl.opengl.GL11.*
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashSet
import kotlin.collections.LinkedHashMap
internal object CombatSetting : Module(
name = "CombatSetting",
description = "Settings for combat module targeting",
category = Category.COMBAT,
showOnArray = false,
alwaysEnabled = true
) {
private val page = setting("Page", Page.TARGETING)
/* Targeting */
private val filter = setting("Filter", TargetFilter.ALL, { page.value == Page.TARGETING })
private val fov = setting("FOV", 90.0f, 0.0f..180.0f, 5.0f, { page.value == Page.TARGETING && filter.value == TargetFilter.FOV })
private val priority = setting("Priority", TargetPriority.DISTANCE, { page.value == Page.TARGETING })
private val players = setting("Players", true, { page.value == Page.TARGETING })
private val friends = setting("Friends", false, { page.value == Page.TARGETING && players.value })
private val teammates = setting("Teammates", false, { page.value == Page.TARGETING && players.value })
private val sleeping = setting("Sleeping", false, { page.value == Page.TARGETING && players.value })
private val mobs = setting("Mobs", true, { page.value == Page.TARGETING })
private val passive = setting("Passive Mobs", false, { page.value == Page.TARGETING && mobs.value })
private val neutral = setting("Neutral Mobs", false, { page.value == Page.TARGETING && mobs.value })
private val hostile = setting("Hostile Mobs", false, { page.value == Page.TARGETING && mobs.value })
private val tamed = setting("Tamed Mobs", false, { page.value == Page.TARGETING && mobs.value })
private val invisible = setting("Invisible", true, { page.value == Page.TARGETING })
private val ignoreWalls = setting("Ignore Walls", false, { page.value == Page.TARGETING })
private val range = setting("Target Range", 16.0f, 2.0f..64.0f, 2.0f, { page.value == Page.TARGETING })
/* In Combat */
private val pauseForDigging = setting("Pause For Digging", true, { page.value == Page.IN_COMBAT })
private val pauseForEating = setting("Pause For Eating", true, { page.value == Page.IN_COMBAT })
private val ignoreOffhandEating = setting("Ignore Offhand Eating", true, { page.value == Page.IN_COMBAT && pauseForEating.value })
private val pauseBaritone = setting("Pause Baritone", true, { page.value == Page.IN_COMBAT })
private val resumeDelay = setting("Resume Delay", 3, 1..10, 1, { page.value == Page.IN_COMBAT && pauseBaritone.value })
private val motionPrediction = setting("Motion Prediction", true, { page.value == Page.IN_COMBAT })
private val pingSync = setting("Ping Sync", true, { page.value == Page.IN_COMBAT && motionPrediction.value })
private val ticksAhead = setting("Ticks Ahead", 5, 0..20, 1, { page.value == Page.IN_COMBAT && motionPrediction.value && !pingSync.value })
/* Render */
private val renderPredictedPos = setting("Render Predicted Position", false, { page.value == Page.RENDER })
private enum class Page {
TARGETING, IN_COMBAT, RENDER
}
private enum class TargetFilter {
ALL, FOV, MANUAL
}
private enum class TargetPriority {
DAMAGE, HEALTH, CROSS_HAIR, DISTANCE
}
private var overrideRange = range.value
private var paused = false
private val resumeTimer = TickTimer(TimeUnit.SECONDS)
private val jobMap = hashMapOf<(SafeClientEvent) -> Unit, Job?>(
{ it: SafeClientEvent -> it.updateTarget() } to null,
{ it: SafeClientEvent -> it.updatePlacingList() } to null,
{ it: SafeClientEvent -> it.updateCrystalList() } to null
)
val pause
get() = runSafeR {
player.ticksExisted < 10
|| checkDigging()
|| checkEating()
} ?: false
private fun SafeClientEvent.checkDigging() =
pauseForDigging.value
&& player.heldItemMainhand.item is ItemPickaxe
&& playerController.isHittingBlock
private fun SafeClientEvent.checkEating() =
pauseForEating.value
&& (PauseProcess.isPausing(AutoEat) || player.isHandActive && player.activeItemStack.item is ItemFood)
&& (!ignoreOffhandEating.value || player.activeHand != EnumHand.OFF_HAND)
override fun isActive() = KillAura.isActive() || BedAura.isActive() || CrystalAura.isActive() || Surround.isActive()
init {
listener<RenderOverlayEvent> {
if (!renderPredictedPos.value) return@listener
CombatManager.target?.let {
val ticks = if (pingSync.value) (InfoCalculator.ping() / 25f).ceilToInt() else ticksAhead.value
val posCurrent = EntityUtils.getInterpolatedPos(it, KamiTessellator.pTicks())
val posAhead = CombatManager.motionTracker.calcPositionAhead(ticks, true) ?: return@listener
val posAheadEye = posAhead.add(0.0, it.eyeHeight.toDouble(), 0.0)
val posCurrentScreen = Vec2d(ProjectionUtils.toScaledScreenPos(posCurrent))
val posAheadScreen = Vec2d(ProjectionUtils.toScaledScreenPos(posAhead))
val posAheadEyeScreen = Vec2d(ProjectionUtils.toScaledScreenPos(posAheadEye))
val vertexHelper = VertexHelper(GlStateUtils.useVbo())
val vertices = arrayOf(posCurrentScreen, posAheadScreen, posAheadEyeScreen)
glDisable(GL_TEXTURE_2D)
RenderUtils2D.drawLineStrip(vertexHelper, vertices, 2f, ColorHolder(80, 255, 80))
glEnable(GL_TEXTURE_2D)
}
}
safeListener<TickEvent.ClientTickEvent>(5000) {
for ((function, future) in jobMap) {
if (future.isActiveOrFalse) continue // Skip if the previous thread isn't done
jobMap[function] = defaultScope.launch { function(this@safeListener) }
}
if (isActive() && pauseBaritone.value) {
pauseBaritone()
resumeTimer.reset()
paused = true
} else if (resumeTimer.tick(resumeDelay.value.toLong(), false)) {
unpauseBaritone()
paused = false
}
}
}
private fun SafeClientEvent.updateTarget() {
CombatManager.getTopModule()?.let {
overrideRange = if (it is KillAura) it.range else range.value
}
getTargetList().let {
CombatManager.target = getTarget(it)
}
}
private fun SafeClientEvent.updatePlacingList() {
if (CrystalAura.isDisabled && CrystalBasePlace.isDisabled && CrystalESP.isDisabled && player.ticksExisted % 4 != 0) return
val eyePos = player.getPositionEyes(1f) ?: Vec3d.ZERO
val cacheList = ArrayList<Pair<BlockPos, CombatManager.CrystalDamage>>()
val target = CombatManager.target
val prediction = target?.let { getPrediction(it) }
for (pos in getPlacePos(target, player, 8f)) {
val dist = eyePos.distanceTo(pos.toVec3dCenter(0.0, 0.5, 0.0))
val damage = target?.let { calcCrystalDamage(pos, it, prediction?.first, prediction?.second) } ?: 0.0f
val selfDamage = calcCrystalDamage(pos, player)
cacheList.add(Pair(pos, CombatManager.CrystalDamage(damage, selfDamage, dist)))
}
CombatManager.placeMap = LinkedHashMap<BlockPos, CombatManager.CrystalDamage>(cacheList.size).apply {
putAll(cacheList.sortedByDescending { it.second.targetDamage })
}
}
/* Crystal damage calculation */
private fun SafeClientEvent.updateCrystalList() {
if (CrystalAura.isDisabled && CrystalESP.isDisabled && (player.ticksExisted - 2) % 4 != 0) return
val cacheList = ArrayList<Pair<EntityEnderCrystal, CombatManager.CrystalDamage>>()
val eyePos = player.getPositionEyes(1f)
val target = CombatManager.target
val prediction = target?.let { getPrediction(it) }
for (entity in world.loadedEntityList.toList()) {
if (entity.isDead) continue
if (entity !is EntityEnderCrystal) continue
val dist = entity.distanceTo(eyePos)
if (dist > 16.0f) continue
val damage = if (target != null && prediction != null) calcCrystalDamage(entity, target, prediction.first, prediction.second) else 0.0f
val selfDamage = calcCrystalDamage(entity, player)
cacheList.add(entity to CombatManager.CrystalDamage(damage, selfDamage, dist))
}
CombatManager.crystalMap = LinkedHashMap<EntityEnderCrystal, CombatManager.CrystalDamage>(cacheList.size).apply {
putAll(cacheList.sortedByDescending { it.second.targetDamage })
}
}
fun getPrediction(entity: Entity) = CombatManager.target?.let {
if (motionPrediction.value) {
val ticks = if (pingSync.value) (InfoCalculator.ping() / 25f).ceilToInt() else ticksAhead.value
CombatManager.motionTracker.getPositionAndBBAhead(ticks) ?: it.positionVector to it.entityBoundingBox
} else {
it.positionVector to it.entityBoundingBox
}
} ?: entity.positionVector to entity.entityBoundingBox
/* End of crystal damage calculation */
/* Targeting */
private fun SafeClientEvent.getTargetList(): LinkedList<EntityLivingBase> {
val targetList = LinkedList<EntityLivingBase>()
for (entity in getCacheList()) {
if (AntiBot.isBot(entity)) continue
if (!tamed.value
&& (entity is EntityTameable && entity.isTamed
|| entity is AbstractHorse && entity.isTame)) continue
if (!teammates.value
&& player.isOnSameTeam(entity)) continue
if (!shouldIgnoreWall()
&& player.canEntityBeSeen(entity)
&& !EntityUtils.canEntityFeetBeSeen(entity)
&& EntityUtils.canEntityHitboxBeSeen(entity) == null) continue
targetList.add(entity)
}
return targetList
}
private fun SafeClientEvent.getCacheList(): LinkedList<EntityLivingBase> {
val player = arrayOf(players.value, friends.value, sleeping.value)
val mob = arrayOf(mobs.value, passive.value, neutral.value, hostile.value)
val cacheList = LinkedList(EntityUtils.getTargetList(player, mob, invisible.value, overrideRange))
if ((cacheList.isEmpty() || getTarget(cacheList) == null) && overrideRange != range.value) {
cacheList.addAll(EntityUtils.getTargetList(player, mob, invisible.value, range.value))
}
return cacheList
}
private fun shouldIgnoreWall(): Boolean {
val module = CombatManager.getTopModule()
return if (module is KillAura || module is AimBot) ignoreWalls.value
else true
}
private fun SafeClientEvent.getTarget(listIn: LinkedList<EntityLivingBase>): EntityLivingBase? {
val copiedList = LinkedList(listIn)
return filterTargetList(copiedList) ?: CombatManager.target?.let { entity ->
if (!entity.isDead && listIn.contains(entity)) entity else null
}
}
private fun SafeClientEvent.filterTargetList(listIn: LinkedList<EntityLivingBase>): EntityLivingBase? {
if (listIn.isEmpty()) return null
return filterByPriority(filterByFilter(listIn))
}
private fun SafeClientEvent.filterByFilter(listIn: LinkedList<EntityLivingBase>): LinkedList<EntityLivingBase> {
when (filter.value) {
TargetFilter.FOV -> {
listIn.removeIf { getRelativeRotation(it) > fov.value }
}
TargetFilter.MANUAL -> {
if (!mc.gameSettings.keyBindAttack.isKeyDown && !mc.gameSettings.keyBindUseItem.isKeyDown) {
return LinkedList()
}
val eyePos = player.getPositionEyes(KamiTessellator.pTicks())
val lookVec = player.lookVec.scale(range.value.toDouble())
val sightEndPos = eyePos.add(lookVec)
listIn.removeIf { it.entityBoundingBox.calculateIntercept(eyePos, sightEndPos) == null }
}
else -> {
}
}
return listIn
}
private fun SafeClientEvent.filterByPriority(listIn: LinkedList<EntityLivingBase>): EntityLivingBase? {
if (listIn.isEmpty()) return null
if (priority.value == TargetPriority.DAMAGE) filterByDamage(listIn)
if (priority.value == TargetPriority.HEALTH) filterByHealth(listIn)
return if (priority.value == TargetPriority.CROSS_HAIR) filterByCrossHair(listIn) else filterByDistance(listIn)
}
private fun filterByDamage(listIn: LinkedList<EntityLivingBase>) {
if (listIn.isEmpty()) return
var damage = Float.MIN_VALUE
val toKeep = HashSet<Entity>()
for (entity in listIn) {
val currentDamage = CombatUtils.calcDamage(entity, roundDamage = true)
if (currentDamage >= damage) {
if (currentDamage > damage) {
damage = currentDamage
toKeep.clear()
}
toKeep.add(entity)
}
}
listIn.removeIf { !toKeep.contains(it) }
}
private fun filterByHealth(listIn: LinkedList<EntityLivingBase>) {
if (listIn.isEmpty()) return
var health = Float.MAX_VALUE
val toKeep = HashSet<Entity>()
for (e in listIn) {
val currentHealth = e.health
if (currentHealth <= health) {
if (currentHealth < health) {
health = currentHealth
toKeep.clear()
}
toKeep.add(e)
}
}
listIn.removeIf { !toKeep.contains(it) }
}
private fun SafeClientEvent.filterByCrossHair(listIn: LinkedList<EntityLivingBase>): EntityLivingBase? {
if (listIn.isEmpty()) return null
return listIn.sortedBy { getRelativeRotation(it) }[0]
}
private fun SafeClientEvent.filterByDistance(listIn: LinkedList<EntityLivingBase>): EntityLivingBase? {
if (listIn.isEmpty()) return null
return listIn.sortedBy { it.getDistance(player) }[0]
}
/* End of targeting */
}
| 412 | 0.936464 | 1 | 0.936464 | game-dev | MEDIA | 0.854548 | game-dev | 0.973111 | 1 | 0.973111 |
ss14Starlight/space-station-14 | 8,032 | Content.Server/Kitchen/EntitySystems/SharpSystem.cs | using Content.Server.Body.Systems;
using Content.Shared.Administration.Logs;
using Content.Shared.Body.Components;
using Content.Shared.Database;
using Content.Shared.Destructible;
using Content.Shared.DoAfter;
using Content.Shared.IdentityManagement;
using Content.Shared.Interaction;
using Content.Shared.Kitchen;
using Content.Shared.Kitchen.Components;
using Content.Shared.Mobs.Components;
using Content.Shared.Mobs.Systems;
using Content.Shared.Nutrition.Components;
using Content.Shared.Nutrition.EntitySystems;
using Content.Shared.Popups;
using Content.Shared.Storage;
using Content.Shared.Verbs;
using Robust.Server.Containers;
using Robust.Server.GameObjects;
using Robust.Shared.Random;
using Robust.Shared.Utility;
namespace Content.Server.Kitchen.EntitySystems;
public sealed class SharpSystem : EntitySystem
{
[Dependency] private readonly BodySystem _bodySystem = default!;
[Dependency] private readonly SharedDestructibleSystem _destructibleSystem = default!;
[Dependency] private readonly SharedDoAfterSystem _doAfterSystem = default!;
[Dependency] private readonly SharedPopupSystem _popupSystem = default!;
[Dependency] private readonly ContainerSystem _containerSystem = default!;
[Dependency] private readonly MobStateSystem _mobStateSystem = default!;
[Dependency] private readonly TransformSystem _transform = default!;
[Dependency] private readonly IRobustRandom _robustRandom = default!;
[Dependency] private readonly ISharedAdminLogManager _adminLogger = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<SharpComponent, AfterInteractEvent>(OnAfterInteract, before: [typeof(IngestionSystem)]);
SubscribeLocalEvent<SharpComponent, SharpDoAfterEvent>(OnDoAfter);
SubscribeLocalEvent<ButcherableComponent, GetVerbsEvent<InteractionVerb>>(OnGetInteractionVerbs);
}
private void OnAfterInteract(EntityUid uid, SharpComponent component, AfterInteractEvent args)
{
if (args.Handled || args.Target is null || !args.CanReach)
return;
if (TryStartButcherDoafter(uid, args.Target.Value, args.User))
args.Handled = true;
}
private bool TryStartButcherDoafter(EntityUid knife, EntityUid target, EntityUid user)
{
if (!TryComp<ButcherableComponent>(target, out var butcher))
return false;
if (!TryComp<SharpComponent>(knife, out var sharp))
return false;
if (TryComp<MobStateComponent>(target, out var mobState) && !_mobStateSystem.IsDead(target, mobState))
return false;
if (butcher.Type != ButcheringType.Knife && target != user)
{
_popupSystem.PopupEntity(Loc.GetString("butcherable-different-tool", ("target", target)), knife, user);
return false;
}
if (!sharp.Butchering.Add(target))
return false;
// if the user isn't the entity with the sharp component,
// they will need to be holding something with their hands, so we set needHand to true
// so that the doafter can be interrupted if they drop the item in their hands
var needHand = user != knife;
var doAfter =
new DoAfterArgs(EntityManager, user, sharp.ButcherDelayModifier * butcher.ButcherDelay, new SharpDoAfterEvent(), knife, target: target, used: knife)
{
BreakOnDamage = true,
BreakOnMove = true,
NeedHand = needHand,
};
_doAfterSystem.TryStartDoAfter(doAfter);
return true;
}
private void OnDoAfter(EntityUid uid, SharpComponent component, DoAfterEvent args)
{
if (args.Handled || !TryComp<ButcherableComponent>(args.Args.Target, out var butcher))
return;
if (args.Cancelled)
{
component.Butchering.Remove(args.Args.Target.Value);
return;
}
component.Butchering.Remove(args.Args.Target.Value);
var spawnEntities = EntitySpawnCollection.GetSpawns(butcher.SpawnedEntities, _robustRandom);
var coords = _transform.GetMapCoordinates(args.Args.Target.Value);
EntityUid popupEnt = default!;
if (_containerSystem.TryGetContainingContainer(args.Args.Target.Value, out var container))
{
foreach (var proto in spawnEntities)
{
// distribute the spawned items randomly in a small radius around the origin
popupEnt = SpawnInContainerOrDrop(proto, container.Owner, container.ID);
}
}
else
{
foreach (var proto in spawnEntities)
{
// distribute the spawned items randomly in a small radius around the origin
popupEnt = Spawn(proto, coords.Offset(_robustRandom.NextVector2(0.25f)));
}
}
// only show a big popup when butchering living things.
// Meant to differentiate cutting up clothes and cutting up your boss.
var popupType = HasComp<MobStateComponent>(args.Args.Target.Value)
? PopupType.LargeCaution
: PopupType.Small;
_popupSystem.PopupEntity(Loc.GetString("butcherable-knife-butchered-success", ("target", args.Args.Target.Value), ("knife", Identity.Entity(uid, EntityManager))),
popupEnt,
args.Args.User,
popupType);
_bodySystem.GibBody(args.Args.Target.Value); // does nothing if ent can't be gibbed
_destructibleSystem.DestroyEntity(args.Args.Target.Value);
args.Handled = true;
_adminLogger.Add(LogType.Gib,
$"{ToPrettyString(args.User):user} " +
$"has butchered {ToPrettyString(args.Target):target} " +
$"with {ToPrettyString(args.Used):knife}");
}
private void OnGetInteractionVerbs(EntityUid uid, ButcherableComponent component, GetVerbsEvent<InteractionVerb> args)
{
if (component.Type != ButcheringType.Knife || !args.CanAccess || !args.CanInteract)
return;
// if the user has no hands, don't show them the verb if they have no SharpComponent either
if (!TryComp<SharpComponent>(args.User, out var userSharpComp) && args.Hands == null)
return;
var disabled = false;
string? message = null;
// if the held item doesn't have SharpComponent
// and the user doesn't have SharpComponent
// disable the verb
if (!TryComp<SharpComponent>(args.Using, out var usingSharpComp) && userSharpComp == null)
{
disabled = true;
message = Loc.GetString("butcherable-need-knife",
("target", uid));
}
else if (_containerSystem.IsEntityInContainer(uid))
{
disabled = true;
message = Loc.GetString("butcherable-not-in-container",
("target", uid));
}
else if (TryComp<MobStateComponent>(uid, out var state) && !_mobStateSystem.IsDead(uid, state))
{
disabled = true;
message = Loc.GetString("butcherable-mob-isnt-dead");
}
// set the object doing the butchering to the item in the user's hands or to the user themselves
// if either has the SharpComponent
EntityUid sharpObject = default;
if (usingSharpComp != null)
sharpObject = args.Using!.Value;
else if (userSharpComp != null)
sharpObject = args.User;
InteractionVerb verb = new()
{
Act = () =>
{
if (!disabled)
TryStartButcherDoafter(sharpObject, args.Target, args.User);
},
Message = message,
Disabled = disabled,
Icon = new SpriteSpecifier.Texture(new ("/Textures/Interface/VerbIcons/cutlery.svg.192dpi.png")),
Text = Loc.GetString("butcherable-verb-name"),
};
args.Verbs.Add(verb);
}
}
| 412 | 0.934354 | 1 | 0.934354 | game-dev | MEDIA | 0.91333 | game-dev | 0.932867 | 1 | 0.932867 |
katboi01/UmaViewer | 45,112 | Assets/Scripts/UmaViewerBuilder.cs | using CriWareFormats;
using Gallop;
using Gallop.Live;
using NAudio.Wave;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using UmaMusumeAudio;
using UnityEngine;
using UnityEngine.SceneManagement;
using Debug = UnityEngine.Debug;
using Random = UnityEngine.Random;
public class UmaViewerBuilder : MonoBehaviour
{
public static UmaViewerBuilder Instance;
static UmaViewerMain Main => UmaViewerMain.Instance;
static UmaViewerUI UI => UmaViewerUI.Instance;
static UISettingsModel ModelSettings => UmaViewerUI.Instance.ModelSettings;
public List<Shader> ShaderList = new List<Shader>();
public Material TransMaterialCharas;
public UmaContainerCharacter CurrentUMAContainer;
public UmaContainer CurrentOtherContainer;
public UmaHeadData CurrentHead;
public List<AudioSource> CurrentAudioSources = new List<AudioSource>();
public List<UmaLyricsData> CurrentLyrics = new List<UmaLyricsData>();
// Used for keeping track for exports
public List<UmaDatabaseEntry> CurrentLiveSoundAWB = new List<UmaDatabaseEntry>();
public int CurrentLiveSoundAWBIndex = -1;
public AnimatorOverrideController OverrideController;
public AnimatorOverrideController FaceOverrideController;
public AnimatorOverrideController CameraOverrideController;
public Animator AnimationCameraAnimator;
public Camera AnimationCamera;
public GameObject LiveControllerPrefab;
private void Awake()
{
Instance = this;
}
public IEnumerator LoadUma(CharaEntry chara, string costumeId, bool mini, string haedCostumeId = "")
{
int id = chara.Id;
var umaContainer = new GameObject($"Chara_{id}_{costumeId}").AddComponent<UmaContainerCharacter>();
CurrentUMAContainer = umaContainer;
if (mini)
{
umaContainer.CharaData = UmaDatabaseController.ReadCharaData(chara);
LoadMiniUma(umaContainer, chara, costumeId);
}
else if (chara.IsMob)
{
umaContainer.CharaData = UmaDatabaseController.ReadCharaData(chara);
LoadMobUma(umaContainer, chara, costumeId, loadMotion: true);
}
else if (ModelSettings.IsHeadFix && CurrentHead != null && CurrentHead.chara.IsMob)
{
umaContainer.CharaData = UmaDatabaseController.ReadCharaData(CurrentHead.chara);
LoadMobUma(umaContainer, CurrentHead.chara, costumeId, chara.Id, true);
}
else
{
umaContainer.CharaData = UmaDatabaseController.ReadCharaData(chara);
LoadNormalUma(umaContainer, chara, costumeId, true, haedCostumeId);
}
yield break;
}
public void LoadLiveUma(List<LiveCharacterSelect> characters)
{
for (int i = 0; i < characters.Count; i++)
{
if (characters[i].CharaEntry.Name != "")
{
var umaContainer = new GameObject($"Chara_{characters[i].CharaEntry.Id}_{characters[i].CostumeId}").AddComponent<UmaContainerCharacter>();
umaContainer.IsLive = true;
umaContainer.CharaData = UmaDatabaseController.ReadCharaData(characters[i].CharaEntry);
var charObjs = Gallop.Live.Director.instance.charaObjs;
umaContainer.transform.parent = charObjs[i];
umaContainer.transform.localPosition = new Vector3();
if (characters[i].CharaEntry.IsMob)
{
LoadMobUma(umaContainer, characters[i].CharaEntry, characters[i].CostumeId);
}
else
{
LoadNormalUma(umaContainer, characters[i].CharaEntry, characters[i].CostumeId, false, characters[i].HeadCostumeId);
}
Gallop.Live.Director.instance.CharaContainerScript.Add(umaContainer);
}
}
}
private void LoadNormalUma(UmaContainerCharacter umaContainer, CharaEntry chara, string costumeId, bool loadMotion = false, string haedCostumeId = "")
{
int id = chara.Id;
umaContainer.CharaEntry = chara;
DataRow charaData = umaContainer.CharaData;
bool genericCostume = umaContainer.IsGeneric = costumeId.Length >= 4;
string skin, height, socks, bust, sex, shape, costumeIdShort = "";
skin = charaData["skin"].ToString();
height = charaData["height"].ToString();
socks = charaData["socks"].ToString();
bust = charaData["bust"].ToString();
sex = charaData["sex"].ToString();
shape = charaData["shape"].ToString();
UmaDatabaseEntry asset = null;
umaContainer.VarCostumeIdLong = costumeId;
if (genericCostume)
{
costumeIdShort = costumeId.Remove(costumeId.LastIndexOf('_'));
umaContainer.VarCostumeIdShort = costumeIdShort;
umaContainer.VarBust = bust;
umaContainer.VarSkin = skin;
umaContainer.VarSocks = socks;
umaContainer.VarHeight = height;
// Pattern for generic body type is as follows:
//
// (costume id)_(body_type_sub)_(body_setting)_(height)_(shape)_(bust)
//
// body_type_sub is used for variants like the summer/winter uniform or the swimsuit/towel
// body_setting is used for subvariants of each variant like the big belly version of the uniform, and the genders for the tracksuits
//
// Some models will naturally be missing due to how this system is designed.
string body = UmaDatabaseController.BodyPath + $"bdy{costumeIdShort}/pfb_bdy{costumeId}_{height}_{shape}_{bust}";
UmaViewerMain.Instance.AbList.TryGetValue(body, out asset);
}
else UmaViewerMain.Instance.AbList.TryGetValue(UmaDatabaseController.BodyPath + $"bdy{id}_{costumeId}/pfb_bdy{id}_{costumeId}", out asset);
if (asset == null)
{
Debug.LogError("No body, can't load!");
UmaViewerUI.Instance?.ShowMessage("No body, can't load!", UIMessageType.Error);
return;
}
else if (genericCostume)
{
string texPattern1 = "", texPattern2 = "", texPattern3 = "", texPattern4 = "", texPattern5 = "";
switch (costumeId.Split('_')[0])
{
case "0001":
texPattern1 = $"tex_bdy{costumeIdShort}_00_{skin}_{bust}_0{socks}";
texPattern2 = $"tex_bdy{costumeIdShort}_00_0_{bust}";
texPattern3 = $"tex_bdy{costumeIdShort}_zekken";
texPattern4 = $"tex_bdy{costumeIdShort}_00_waku";
texPattern5 = $"tex_bdy{costumeIdShort}_num";
break;
case "0003":
texPattern1 = $"tex_bdy{costumeIdShort}_00_{skin}_{bust}";
texPattern2 = $"tex_bdy{costumeIdShort}_00_0_{bust}";
break;
case "0006": //last var is color?
texPattern1 = $"tex_bdy{costumeId}_{skin}_{bust}_0{0}";
texPattern2 = $"tex_bdy{costumeId}_0_{bust}_00_";
break;
default:
texPattern1 = $"tex_bdy{costumeId}_{skin}_{bust}";
texPattern2 = $"tex_bdy{costumeId}_0_{bust}";
break;
}
Debug.Log(texPattern1 + " " + texPattern2);
//Load Body Textures
foreach (var asset1 in UmaViewerMain.Instance.AbChara.Where(a => a.Name.StartsWith(UmaDatabaseController.BodyPath)
&& (a.Name.Contains(texPattern1)
|| a.Name.Contains(texPattern2)
|| (string.IsNullOrEmpty(texPattern3) ? false : a.Name.Contains(texPattern3))
|| (string.IsNullOrEmpty(texPattern4) ? false : a.Name.Contains(texPattern4))
|| (string.IsNullOrEmpty(texPattern5) ? false : a.Name.Contains(texPattern5)))))
{
umaContainer.LoadTextures(asset1);
}
//Load Body
umaContainer.LoadBody(asset);
//Load Physics
if (Main.AbList.TryGetValue(UmaDatabaseController.BodyPath + $"bdy{costumeIdShort}/clothes/pfb_bdy{costumeIdShort}_cloth00", out _))
{
var asset1 = Main.AbList[UmaDatabaseController.BodyPath + $"bdy{costumeIdShort}/clothes/pfb_bdy{costumeIdShort}_cloth00"];
umaContainer.LoadPhysics(asset1);
asset1 = Main.AbList[UmaDatabaseController.BodyPath + $"bdy{costumeIdShort}/clothes/pfb_bdy{costumeIdShort}_bust{bust}_cloth00"];
umaContainer.LoadPhysics(asset1);
}
}
else
{
umaContainer.LoadBody(asset);
//Load Physics
var asset1 = Main.AbList[UmaDatabaseController.BodyPath + $"bdy{id}_{costumeId}/clothes/pfb_bdy{id}_{costumeId}_cloth00"];
umaContainer.LoadPhysics(asset1);
asset1 = Main.AbList[UmaDatabaseController.BodyPath + $"bdy{id}_{costumeId}/clothes/pfb_bdy{id}_{costumeId}_bust_cloth00"];
umaContainer.LoadPhysics(asset1);
}
// Record Head Data
int head_id;
string head_costumeId;
int tailId = Convert.ToInt32(charaData["tail_model_id"]);
if (ModelSettings.IsHeadFix && CurrentHead != null)
{
head_id = CurrentHead.id;
head_costumeId = CurrentHead.costumeId;
tailId = CurrentHead.tailId;
}
else
{
head_id = id;
head_costumeId = string.IsNullOrEmpty(haedCostumeId) ? costumeId : haedCostumeId;
CurrentHead = new UmaHeadData
{
id = id,
costumeId = head_costumeId,
tailId = tailId,
chara = chara
};
}
string head = UmaDatabaseController.HeadPath + $"chr{head_id}_{head_costumeId}/pfb_chr{head_id}_{head_costumeId}";
asset = null;
Main.AbList.TryGetValue(head, out asset);
bool isDefaultHead = false;
//Some costumes don't have custom heads
if (head_costumeId != "00" && asset == null)
{
asset = Main.AbList[UmaDatabaseController.HeadPath + $"chr{head_id}_00/pfb_chr{head_id}_00"];
isDefaultHead = true;
}
if (asset != null)
{
//Load Hair Textures
foreach (var asset1 in UmaViewerMain.Instance.AbChara.Where(a => a.Name.StartsWith($"{UmaDatabaseController.HeadPath}chr{head_id}_{head_costumeId}/textures")))
{
umaContainer.LoadTextures(asset1);
}
//Load Head
umaContainer.LoadHead(asset);
//Load Physics
if (isDefaultHead)
{
var asset1 = Main.AbList[UmaDatabaseController.HeadPath + $"chr{id}_00/clothes/pfb_chr{id}_00_cloth00"];
umaContainer.LoadPhysics(asset1);
}
else
{
var asset1 = Main.AbList[UmaDatabaseController.HeadPath + $"chr{head_id}_{head_costumeId}/clothes/pfb_chr{head_id}_{head_costumeId}_cloth00"];
umaContainer.LoadPhysics(asset1);
}
}
//修改(载入专用尾巴相关)
if (tailId > 0)
{
string costumePrefixForTail = $"{id}_{costumeId}";
string exclusiveTailName = $"tail{costumePrefixForTail}";
string exclusiveTailPath = $"3d/chara/tail/{exclusiveTailName}/";
string exclusiveTailPfb = $"{exclusiveTailPath}pfb_{exclusiveTailName}";
if (Main.AbList.TryGetValue(exclusiveTailPfb, out asset))
{
umaContainer.LoadExclusiveTail(asset);
string clothPath = $"{exclusiveTailPath}clothes/pfb_{exclusiveTailName}_cloth00";
if (Main.AbList.TryGetValue(clothPath, out var clothAsset))
{
umaContainer.LoadPhysics(clothAsset);
}
}
else
{
string tailName = $"tail{tailId.ToString().PadLeft(4, '0')}_00";
string tailPath = $"3d/chara/tail/{tailName}/";
string tailPfb = $"{tailPath}pfb_{tailName}";
asset = null;
if (Main.AbList.TryGetValue(tailPfb, out asset) && asset != null)
{
foreach (var asset2 in UmaViewerMain.Instance.AbChara.Where(a => a.Name.StartsWith($"{tailPath}textures/tex_{tailName}_{head_id}") || a.Name.StartsWith($"{tailPath}textures/tex_{tailName}_0000")))
{
umaContainer.LoadTextures(asset2);
}
umaContainer.LoadTail(asset);
string clothPath = $"{tailPath}clothes/pfb_{tailName}_cloth00";
if (Main.AbList.TryGetValue(clothPath, out var clothAsset))
{
umaContainer.LoadPhysics(clothAsset);
}
}
else
{
Debug.Log("no tail");
}
}
}
umaContainer.LoadPhysics();
umaContainer.SetDynamicBoneEnable(ModelSettings.DynamicBoneEnable);
umaContainer.LoadFaceMorph(id, costumeId);
umaContainer.TearControllers.ForEach(a => a.SetDir(a.CurrentDir));
umaContainer.HeadBone = (GameObject)umaContainer.Body.GetComponent<AssetHolder>()._assetTable["head"];
umaContainer.EyeHeight = umaContainer.Head.GetComponent<AssetHolder>()._assetTableValue["head_center_offset_y"];
umaContainer.MergeModel();
umaContainer.SetHeight(-1);
umaContainer.Initialize(!ModelSettings.IsTPose);
umaContainer.Position = umaContainer.transform.Find("Position");
umaContainer.SetupBoneHandles();
if (!ModelSettings.IsTPose && loadMotion)
{
if (Main.AbList.TryGetValue($"3d/motion/event/body/chara/chr{id}_00/anm_eve_chr{id}_00_idle01_loop", out UmaDatabaseEntry entry))
{
umaContainer.LoadAnimation(entry);
}
}
//修改(载入通用服装ColorSet相关)
UI.ClearColorSetButtons();
UI.LoadColorSetButtons();
}
private void LoadMobUma(UmaContainerCharacter umaContainer, CharaEntry chara, string costumeId, int bodyid = -1, bool loadMotion = false)
{
int id = chara.Id;
umaContainer.CharaEntry = chara;
umaContainer.IsMob = chara.IsMob;
umaContainer.MobDressColor = UmaDatabaseController.ReadMobDressColor(umaContainer.CharaData["dress_color_id"].ToString());
umaContainer.MobHeadColor = UmaDatabaseController.ReadMobHairColor(umaContainer.CharaData["chara_hair_color"].ToString());
DataRow charaData = umaContainer.CharaData;
bool genericCostume = umaContainer.IsGeneric = costumeId.Length >= 4;
string skin, height, socks, bust, sex, shape, costumeIdShort = "";
string faceid, hairid, personality;
faceid = charaData["chara_face_model"].ToString();
hairid = charaData["chara_hair_model"].ToString();
personality = charaData["default_personality"].ToString();
skin = charaData["chara_skin_color"].ToString();
height = "1";
socks = charaData["socks"].ToString();
bust = charaData["chara_bust_size"].ToString();
sex = charaData["sex"].ToString();
shape = "0";
UmaDatabaseEntry asset = null;
if (genericCostume)
{
costumeIdShort = costumeId.Remove(costumeId.LastIndexOf('_'));
umaContainer.VarCostumeIdShort = costumeIdShort;
umaContainer.VarCostumeIdLong = costumeId;
umaContainer.VarBust = bust;
umaContainer.VarSkin = skin;
umaContainer.VarSocks = socks;
umaContainer.VarHeight = height;
// Pattern for generic body type is as follows:
//
// (costume id)_(body_type_sub)_(body_setting)_(height)_(shape)_(bust)
//
// body_type_sub is used for variants like the summer/winter uniform or the swimsuit/towel
// body_setting is used for subvariants of each variant like the big belly version of the uniform, and the genders for the tracksuits
//
// Some models will naturally be missing due to how this system is designed.
string body = "";
body = UmaDatabaseController.BodyPath + $"bdy{costumeIdShort}/pfb_bdy{costumeId}_{height}_{shape}_{bust}";
Debug.Log("Looking for " + body);
Main.AbList.TryGetValue(body, out asset);
}
else Main.AbList.TryGetValue($"{UmaDatabaseController.BodyPath}bdy{bodyid}_{costumeId}/pfb_bdy{bodyid}_{costumeId}", out asset);
if (asset == null)
{
Debug.LogError("No body, can't load!");
UmaViewerUI.Instance?.ShowMessage("No body, can't load!", UIMessageType.Error);
return;
}
else if (genericCostume)
{
string texPattern1 = "", texPattern2 = "", texPattern3 = "", texPattern4 = "", texPattern5 = "";
switch (costumeId.Split('_')[0])
{
case "0001":
texPattern1 = $"tex_bdy{costumeIdShort}_00_{skin}_{bust}_0{socks}";
texPattern2 = $"tex_bdy{costumeIdShort}_00_0_{bust}";
texPattern3 = $"tex_bdy{costumeIdShort}_zekken";
texPattern4 = $"tex_bdy{costumeIdShort}_00_waku";
texPattern5 = $"tex_bdy{costumeIdShort}_num";
break;
case "0003":
texPattern1 = $"tex_bdy{costumeIdShort}_00_{skin}_{bust}";
texPattern2 = $"tex_bdy{costumeIdShort}_00_0_{bust}";
break;
case "0006": //last var is color?
texPattern1 = $"tex_bdy{costumeId}_{skin}_{bust}_0{0}";
texPattern2 = $"tex_bdy{costumeId}_0_{bust}_00_";
break;
default:
texPattern1 = $"tex_bdy{costumeId}_{skin}_{bust}";
texPattern2 = $"tex_bdy{costumeId}_0_{bust}";
break;
}
Debug.Log(texPattern1 + " " + texPattern2);
//Load Body Textures
foreach (var asset1 in UmaViewerMain.Instance.AbChara.Where(a => a.Name.StartsWith(UmaDatabaseController.BodyPath)
&& (a.Name.Contains(texPattern1)
|| a.Name.Contains(texPattern2)
|| (string.IsNullOrEmpty(texPattern3) ? false : a.Name.Contains(texPattern3))
|| (string.IsNullOrEmpty(texPattern4) ? false : a.Name.Contains(texPattern4))
|| (string.IsNullOrEmpty(texPattern5) ? false : a.Name.Contains(texPattern5)))))
{
umaContainer.LoadTextures(asset1);
}
//Load Body
umaContainer.LoadBody(asset);
//Load Physics
if (Main.AbList.TryGetValue(UmaDatabaseController.BodyPath + $"bdy{costumeIdShort}/clothes/pfb_bdy{costumeIdShort}_cloth00", out _))
{
var asset1 = Main.AbList[UmaDatabaseController.BodyPath + $"bdy{costumeIdShort}/clothes/pfb_bdy{costumeIdShort}_cloth00"];
umaContainer.LoadPhysics(asset1);
asset1 = Main.AbList[UmaDatabaseController.BodyPath + $"bdy{costumeIdShort}/clothes/pfb_bdy{costumeIdShort}_bust{bust}_cloth00"];
umaContainer.LoadPhysics(asset1);
}
}
else
{
umaContainer.LoadBody(asset);
//Load Physics
var asset1 = Main.AbList[UmaDatabaseController.BodyPath + $"bdy{bodyid}_{costumeId}/clothes/pfb_bdy{bodyid}_{costumeId}_cloth00"];
umaContainer.LoadPhysics(asset1);
asset1 = Main.AbList[UmaDatabaseController.BodyPath + $"bdy{bodyid}_{costumeId}/clothes/pfb_bdy{bodyid}_{costumeId}_bust_cloth00"];
umaContainer.LoadPhysics(asset1);
}
// Record Head Data
int head_id = 1;
string head_costumeId = "00";
int tailId = 1;
CurrentHead = new UmaHeadData
{
id = id,
costumeId = costumeId,
tailId = tailId,
chara = chara
};
var head_s = head_id.ToString().PadLeft(4, '0');
string head = UmaDatabaseController.HeadPath + $"chr{head_s}_{head_costumeId}/pfb_chr{head_s}_{head_costumeId}_face{faceid.PadLeft(3, '0')}";
string hair = UmaDatabaseController.HeadPath + $"chr{head_s}_{head_costumeId}/pfb_chr{head_s}_{head_costumeId}_hair{hairid.PadLeft(3, '0')}";
Main.AbList.TryGetValue(head, out asset);
Main.AbList.TryGetValue(hair, out UmaDatabaseEntry hairasset);
bool isDefaultHead = true;
if (asset != null && hairasset != null)
{
//Load Face And Hair Textures
foreach (var asset1 in UmaViewerMain.Instance.AbChara.Where(a => a.Name.StartsWith($"{UmaDatabaseController.HeadPath}chr{head_s}_{head_costumeId}/textures")))
{
if (asset1.Name.Contains($"tex_chr{head_s}_{head_costumeId}_face{faceid.PadLeft(3, '0')}_0")
|| asset1.Name.Contains($"tex_chr{head_s}_{head_costumeId}_face{faceid.PadLeft(3, '0')}_{skin}"))
{
umaContainer.LoadTextures(asset1);
}
if (asset1.Name.Contains($"tex_chr{head_s}_{head_costumeId}_hair{hairid.PadLeft(3, '0')}"))
{
umaContainer.LoadTextures(asset1);
}
}
//Load face
umaContainer.LoadHead(asset);
//Load hair
umaContainer.LoadHair(hairasset);
umaContainer.MergeHairModel();
//Load Physics
if (isDefaultHead)
{
if (Main.AbList.TryGetValue($"{UmaDatabaseController.HeadPath}chr{head_s}_00/clothes/pfb_chr{head_s}_00_hair{hairid.PadLeft(3, '0')}_cloth00", out UmaDatabaseEntry asset1))
{
umaContainer.LoadPhysics(asset1);
}
}
}
if (tailId > 0)
{
string tailName = $"tail{tailId.ToString().PadLeft(4, '0')}_00";
string tailPath = $"3d/chara/tail/{tailName}/";
string tailPfb = tailPath + $"pfb_{tailName}";
asset = UmaViewerMain.Instance.AbChara.FirstOrDefault(a => a.Name == tailPfb);
if (asset != null)
{
foreach (var asset1 in UmaViewerMain.Instance.AbChara.Where(a => a.Name.StartsWith($"{tailPath}textures/tex_{tailName}_{head_s}") || a.Name.StartsWith($"{tailPath}textures/tex_{tailName}_0000")))
{
umaContainer.LoadTextures(asset1);
}
umaContainer.LoadTail(asset);
//Load Physics
if (Main.AbList.TryGetValue($"{tailPath}clothes/pfb_{tailName}_cloth00", out UmaDatabaseEntry asset2))
{
umaContainer.LoadPhysics(asset2);
}
}
else
{
Debug.Log("no tail");
}
}
umaContainer.LoadPhysics(); //Need to load physics before loading FacialMorph
umaContainer.SetDynamicBoneEnable(ModelSettings.DynamicBoneEnable);
//Load FacialMorph
umaContainer.LoadFaceMorph(id, costumeId);
umaContainer.TearControllers.ForEach(a => a.SetDir(a.CurrentDir));
umaContainer.HeadBone = (GameObject)umaContainer.Body.GetComponent<AssetHolder>()._assetTable["head"];
umaContainer.EyeHeight = umaContainer.Head.GetComponent<AssetHolder>()._assetTableValue["head_center_offset_y"];
umaContainer.MergeModel();
umaContainer.SetHeight(-1);
umaContainer.Initialize(!ModelSettings.IsTPose);
umaContainer.Position = umaContainer.transform.Find("Position");
umaContainer.SetupBoneHandles();
if (!ModelSettings.IsTPose && loadMotion)
{
if (Main.AbList.TryGetValue($"3d/motion/event/body/type00/anm_eve_type00_homestand{personality.PadLeft(2, '0')}_loop", out UmaDatabaseEntry entry))
{
umaContainer.LoadAnimation(entry);
}
}
//修改(载入通用服装ColorSet相关)
UI.ClearColorSetButtons();
}
private void LoadMiniUma(UmaContainerCharacter umaContainer, CharaEntry chara, string costumeId)
{
int id = chara.Id;
umaContainer.CharaEntry = chara;
DataRow charaData = umaContainer.CharaData;
umaContainer.IsMini = true;
bool isGeneric = umaContainer.IsGeneric = costumeId.Length >= 4;
int tailId = Convert.ToInt32(charaData["tail_model_id"]);
string skin = charaData["skin"].ToString(),
height = charaData["height"].ToString(),
socks = charaData["socks"].ToString(),
bust = charaData["bust"].ToString(),
sex = charaData["sex"].ToString(),
costumeIdShort = "";
bool customHead = true;
UmaDatabaseEntry asset = null;
if (isGeneric)
{
costumeIdShort = costumeId.Remove(costumeId.LastIndexOf('_'));
string body = $"3d/chara/mini/body/mbdy{costumeIdShort}/pfb_mbdy{costumeId}_0";
Main.AbList.TryGetValue(body,out asset);
}
else Main.AbList.TryGetValue($"3d/chara/mini/body/mbdy{id}_{costumeId}/pfb_mbdy{id}_{costumeId}",out asset);
if (asset == null)
{
Debug.LogError("No body, can't load!");
UmaViewerUI.Instance?.ShowMessage("No body, can't load!", UIMessageType.Error);
return;
}
else if (isGeneric)
{
string texPattern1 = "";
switch (costumeId.Split('_')[0])
{
case "0003":
texPattern1 = $"tex_mbdy{costumeIdShort}_00_{skin}_{0}";
break;
default:
texPattern1 = $"tex_mbdy{costumeId}_{skin}_{0}";
break;
}
//Load Body Textures
foreach (var asset1 in UmaViewerMain.Instance.AbChara.Where(a => a.Name.StartsWith("3d/chara/mini/body/") && a.Name.Contains(texPattern1)))
{
umaContainer.LoadTextures(asset1);
}
//Load Body
umaContainer.LoadBody(asset);
}
else
umaContainer.LoadBody(asset);
string hair = $"3d/chara/mini/head/mchr{id}_{costumeId}/pfb_mchr{id}_{costumeId}_hair";
Main.AbList.TryGetValue(hair, out asset);
if (costumeId != "00" && asset == null)
{
customHead = false;
Main.AbList.TryGetValue($"3d/chara/mini/head/mchr{id}_00/pfb_mchr{id}_00_hair", out asset);
}
if (asset != null)
{
//Load Hair Textures
if (customHead)
{
foreach (var asset1 in UmaViewerMain.Instance.AbChara.Where(a => a.Name.StartsWith($"3d/chara/mini/head/mchr{id}_{costumeId}/textures")))
{
umaContainer.LoadTextures(asset1);
}
}
else
{
foreach (var asset1 in UmaViewerMain.Instance.AbChara.Where(a => a.Name.StartsWith($"3d/chara/mini/head/mchr{id}_00/textures")))
{
umaContainer.LoadTextures(asset1);
}
}
//Load Hair (don't know why loadhead is used)
umaContainer.LoadHead(asset);
}
string head = $"3d/chara/mini/head/mchr0001_00/pfb_mchr0001_00_face0";
Main.AbList.TryGetValue(head,out asset);
if (asset != null)
{
//Load Head Textures
foreach (var asset1 in UmaViewerMain.Instance.AbChara.Where(a => a.Name.StartsWith($"3d/chara/mini/head/mchr0001_00/textures/tex_mchr0001_00_face0_{skin}")))
{
umaContainer.LoadTextures(asset1);
}
//Load Head
umaContainer.LoadHead(asset);
}
if (tailId > 0)
{
string tailName = $"mtail{tailId.ToString().PadLeft(4, '0')}_00";
string tailPath = $"3d/chara/mini/tail/{tailName}/";
string tailPfb = tailPath + $"pfb_{tailName}";
asset = null;
Main.AbList.TryGetValue(tailPfb, out asset);
if (asset != null)
{
foreach (var asset2 in UmaViewerMain.Instance.AbChara.Where(a => a.Name.StartsWith($"{tailPath}textures/tex_{tailName}_{id.ToString().PadLeft(4,'0')}")))
{
umaContainer.LoadTextures(asset2);
}
umaContainer.LoadTail(asset);
//Load Physics
var asset1 = Main.AbList[$"{tailPath}clothes/pfb_{tailName}_cloth00"];
umaContainer.LoadPhysics(asset1);
}
else
{
Debug.Log("no tail");
}
}
umaContainer.MergeModel();
var matList = new List<MeshRenderer>(umaContainer.GetComponentsInChildren<MeshRenderer>());
var eyemat = matList.FirstOrDefault(a => a.gameObject.name.Equals("M_Eye"));
var mouthmat = matList.FirstOrDefault(a => a.gameObject.name.Equals("M_Mouth"));
var eyebrowLmat = matList.FirstOrDefault(a => a.gameObject.name.Equals("M_Mayu_L"));
var eyebrowRmat = matList.FirstOrDefault(a => a.gameObject.name.Equals("M_Mayu_R"));
UI.LoadFacialPanelsMini(eyemat.material, eyebrowLmat.material, eyebrowRmat.material, mouthmat.material);
umaContainer.Position = umaContainer.transform.Find("Position");
umaContainer.SetupBoneHandles();
if (Main.AbList.TryGetValue($"3d/motion/mini/event/body/chara/chr{id}_00/anm_min_eve_chr{id}_00_idle01_loop",out asset))
{
umaContainer.LoadAnimation(asset);
}
//修改(载入通用服装ColorSet相关)
UI.ClearColorSetButtons();
}
public void LoadProp(UmaDatabaseEntry entry)
{
UnloadProp();
UmaAssetManager.UnloadAllBundle();
var prop = new GameObject(Path.GetFileName(entry.Name)).AddComponent<UmaContainerProp>();
prop.LoadProp(entry);
CurrentOtherContainer = prop;
}
public void LoadLive(LiveEntry live, List<LiveCharacterSelect> characters)
{
characters.ForEach(a =>
{
if (a.CharaEntry == null || a.CostumeId == "")
{
a.CharaEntry = Main.Characters[Random.Range(0, Main.Characters.Count / 2)];
a.CostumeId = "0002_00_00";
}
});//fill empty
UmaAssetManager.PreLoadAndRun(Director.GetLiveAllVoiceEntry(live.MusicId, characters),
delegate
{
UmaSceneController.LoadScene("LiveScene",
delegate
{
GameObject MainLive = Instantiate(LiveControllerPrefab);
Director mController = MainLive.GetComponentInChildren<Director>();
mController.live = live;
mController.IsRecordVMD = UI.isRecordVMD;
mController.RequireStage = UI.isRequireStage;
List<GameObject> transferObjs = new List<GameObject>() {
MainLive,
GameObject.Find("ViewerMain"),
GameObject.Find("Directional Light"),
GameObject.Find("GlobalShaderController"),
GameObject.Find("AudioManager")
};
// Move the GameObject (you attach this in the Inspector) to the newly loaded Scene
transferObjs.ForEach(o => SceneManager.MoveGameObjectToScene(o, SceneManager.GetSceneByName("LiveScene")));
mController.Initialize();
var actual_member_count = mController._liveTimelineControl.data.worksheetList[0].charaMotSeqList.Count;
if (actual_member_count > characters.Count)
{
Debug.LogWarning($"actual member count is {actual_member_count} current {characters.Count}");
var actual_characters = new List<LiveCharacterSelect>();
for (int i = 0; i < actual_member_count; i++)
{
actual_characters.Add(characters[i % characters.Count]);
}
characters = actual_characters;
}
LoadLiveUma(characters);
var Lyrics = LoadLiveLyrics(live.MusicId);
if (Lyrics != null)
{
LiveViewerUI.Instance.CurrentLyrics = Lyrics;
}
},
delegate
{
Director.instance.InitializeUI();
Director.instance.InitializeTimeline(characters, UI.LiveMode);
Director.instance.InitializeMusic(live.MusicId, characters);
Director.instance.Play();
});
});
}
//Use decrypt function
public void LoadLiveSound(int songid, UmaDatabaseEntry SongAwb, bool needLyrics = true)
{
CurrentLiveSoundAWBIndex = -1; // mix awb together
ClearLiveSounds();
//load character voice
if (SongAwb != null)
{
PlaySound(SongAwb);
AddLiveSound(SongAwb);
}
//load BG
string nameVar = $"snd_bgm_live_{songid}_oke";
UmaDatabaseEntry BGawb = Main.AbSounds.FirstOrDefault(a => a.Name.Contains(nameVar) && a.Name.EndsWith("awb"));
if (BGawb != null)
{
var BGclip = LoadAudio(BGawb);
if (BGclip.Count > 0)
{
AddAudioSource(BGclip[0]);
AddLiveSound(BGawb);
}
}
if (needLyrics)
{
LoadLiveLyrics(songid);
}
}
public void loadLivePreviewSound(int songid)
{
string nameVar = $"snd_bgm_live_{songid}_preview_02";
UmaDatabaseEntry previewAwb = Main.AbSounds.FirstOrDefault(a => a.Name.Contains(nameVar) && a.Name.EndsWith("awb"));
if (previewAwb != null)
{
PlaySound(previewAwb, volume : 0.4f, loop : true);
}
}
public void PlaySound(UmaDatabaseEntry SongAwb, int subindex = -1, float volume = 1, bool loop = false)
{
CurrentLyrics.Clear();
if (CurrentAudioSources.Count > 0)
{
var tmp = CurrentAudioSources[0];
CurrentAudioSources.Clear();
Destroy(tmp.gameObject);
UI.AudioSettings.ResetPlayer();
}
if (subindex == -1)
{
foreach (AudioClip clip in LoadAudio(SongAwb))
{
AddAudioSource(clip, volume, loop);
}
}
else
{
AddAudioSource(LoadAudio(SongAwb)[subindex], volume, loop);
}
}
public void SetLastAudio(UmaDatabaseEntry AudioAwb, int index)
{
ClearLiveSounds();
AddLiveSound(AudioAwb);
CurrentLiveSoundAWBIndex = index;
}
private void AddAudioSource(AudioClip clip, float volume = 1, bool loop = false)
{
AudioSource source;
if (CurrentAudioSources.Count > 0)
{
source = CurrentAudioSources[0].gameObject.AddComponent<AudioSource>();
}
else
{
source = new GameObject("SoundController").AddComponent<AudioSource>();
}
CurrentAudioSources.Add(source);
source.clip = clip;
source.volume = volume;
source.loop = loop;
source.Play();
}
public List<UmaWaveStream> LoadAudioStreams(UmaDatabaseEntry awb)
{
var streams = new List<UmaWaveStream>();
string awbPath = awb.FilePath;
if (!File.Exists(awbPath)) return streams;
FileStream awbFile = File.OpenRead(awbPath);
AwbReader awbReader = new AwbReader(awbFile);
foreach (Wave wave in awbReader.Waves)
{
var stream = new UmaWaveStream(awbReader, wave.WaveId);
streams.Add(stream);
}
return streams;
}
public static List<AudioClip> LoadAudio(UmaDatabaseEntry awb)
{
List<AudioClip> clips = new List<AudioClip>();
string awbPath = awb.FilePath;
if (!File.Exists(awbPath)) return clips;
FileStream awbFile = File.OpenRead(awbPath);
AwbReader awbReader = new AwbReader(awbFile);
foreach (Wave wave in awbReader.Waves)
{
var stream = new UmaWaveStream(awbReader, wave.WaveId);
var sampleProvider = stream.ToSampleProvider();
int channels = stream.WaveFormat.Channels;
int bytesPerSample = stream.WaveFormat.BitsPerSample / 8;
int sampleRate = stream.WaveFormat.SampleRate;
AudioClip clip = AudioClip.Create(
Path.GetFileNameWithoutExtension(awb.Name) + "_" + wave.WaveId.ToString(),
(int)(stream.Length / channels / bytesPerSample),
channels,
sampleRate,
true,
data => sampleProvider.Read(data, 0, data.Length),
position => stream.Position = position * channels * bytesPerSample);
clips.Add(clip);
}
return clips;
}
public List<UmaLyricsData> LoadLiveLyrics(int songid)
{
if (CurrentLyrics.Count > 0) CurrentLyrics.Clear();
string lyricsVar = $"live/musicscores/m{songid}/m{songid}_lyrics";
UmaDatabaseEntry lyricsAsset = Main.AbList[lyricsVar];
AssetBundle bundle = UmaAssetManager.LoadAssetBundle(lyricsAsset);
TextAsset asset = bundle.LoadAsset<TextAsset>(Path.GetFileNameWithoutExtension(lyricsVar));
string[] lines = asset.text.Split("\n"[0]);
for (int i = 1; i < lines.Length; i++)
{
string[] words = lines[i].Split(',');
if (words.Length > 0)
{
try
{
UmaLyricsData lyricsData = new UmaLyricsData()
{
time = float.Parse(words[0]) / 1000,
text = (words.Length > 1) ? words[1] : ""
};
CurrentLyrics.Add(lyricsData);
}
catch { }
}
}
return CurrentLyrics;
}
public void LoadAssetPath(string path, Transform SetParent)
{
Instantiate(UmaViewerMain.Instance.AbList[path].Get<GameObject>(), SetParent);
}
public void SetPreviewCamera(AnimationClip clip)
{
if (clip)
{
if (!AnimationCameraAnimator.runtimeAnimatorController)
{
AnimationCameraAnimator.runtimeAnimatorController = Instantiate(CameraOverrideController);
}
(AnimationCameraAnimator.runtimeAnimatorController as AnimatorOverrideController)["clip_1"] = clip;
AnimationCamera.enabled = true;
AnimationCameraAnimator.Play("motion_1", 0, 0);
CurrentUMAContainer?.SetHeight(0);
}
else
{
AnimationCamera.enabled = false;
CurrentUMAContainer?.SetHeight(-1);
}
}
public Sprite LoadCharaIcon(string id)
{
string value = $"chara/chr{id}/chr_icon_{id}";
if (UmaViewerMain.Instance.AbList.TryGetValue(value, out UmaDatabaseEntry entry))
{
AssetBundle assetBundle = UmaAssetManager.LoadAssetBundle(entry, true);
if (assetBundle.Contains($"chr_icon_{id}"))
{
Texture2D texture = (Texture2D)assetBundle.LoadAsset($"chr_icon_{id}");
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
assetBundle.Unload(false);
return sprite;
}
}
return null;
}
public Sprite LoadMobCharaIcon(string id)
{
string value = $"mob/mob_chr_icon_{id}_000001_01";
if (UmaViewerMain.Instance.AbList.TryGetValue(value, out UmaDatabaseEntry entry))
{
string path = entry.FilePath;
AssetBundle assetBundle = UmaAssetManager.LoadAssetBundle(entry, true);
if (assetBundle.Contains($"mob_chr_icon_{id}_000001_01"))
{
Texture2D texture = (Texture2D)assetBundle.LoadAsset($"mob_chr_icon_{id}_000001_01");
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
assetBundle.Unload(false);
return sprite;
}
}
return null;
}
public Sprite LoadSprite(UmaDatabaseEntry item)
{
AssetBundle assetBundle = UmaAssetManager.LoadAssetBundle(item, true);
Texture2D texture = (Texture2D)assetBundle.LoadAsset(assetBundle.GetAllAssetNames()[0]);
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
assetBundle.Unload(false);
return sprite;
}
public Sprite LoadLiveIcon(int musicid)
{
string value = $"live/jacket/jacket_icon_l_{musicid}";
if (UmaViewerMain.Instance.AbList.TryGetValue(value, out UmaDatabaseEntry entry))
{
AssetBundle assetBundle = UmaAssetManager.LoadAssetBundle(entry, true);
if (assetBundle.Contains($"jacket_icon_l_{musicid}"))
{
Texture2D texture = (Texture2D)assetBundle.LoadAsset($"jacket_icon_l_{musicid}");
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
assetBundle.Unload(false);
return sprite;
}
}
return null;
}
public void UnloadProp()
{
if (CurrentOtherContainer != null)
{
Destroy(CurrentOtherContainer.gameObject);
}
}
public void UnloadUma()
{
PoseManager.SetPoseModeStatic(false);
if (CurrentUMAContainer != null)
{
//It seems that OnDestroy will executed after new model loaded, which cause new FacialPanels empty...
UI.currentFaceDrivenKeyTarget = null;
UI.LoadEmotionPanels(null);
UI.LoadFacialPanels(null);
if (UI.ModelSettings.MaterialsList)
foreach (Transform t in UI.ModelSettings.MaterialsList.content)
{
Destroy(t.gameObject);
}
if (CurrentUMAContainer.transform.parent && CurrentUMAContainer.transform.parent.name.Contains("Root"))
{
Destroy(CurrentUMAContainer.transform.parent.gameObject);
}
else
{
Destroy(CurrentUMAContainer.gameObject);
}
}
}
public void ClearMorphs()
{
var umaContainer = CurrentUMAContainer;
if (umaContainer != null && umaContainer.FaceDrivenKeyTarget != null)
{
foreach (var container in UI.EmotionList.GetComponentsInChildren<UmaUIContainer>())
{
if (container.Slider != null)
container.Slider.value = 0;
}
foreach (var container in UI.FacialList.GetComponentsInChildren<UmaUIContainer>())
{
if (container.Slider != null)
container.Slider.SetValueWithoutNotify(0);
}
if (umaContainer.FaceDrivenKeyTarget)
{
umaContainer.FaceDrivenKeyTarget.ClearAllWeights();
umaContainer.FaceDrivenKeyTarget.ChangeMorph();
}
}
}
public void UnloadAllBundle() => UmaAssetManager.UnloadAllBundle(true);
private void FixedUpdate()
{
if (AnimationCamera && AnimationCamera.enabled == true)
{
var fov = AnimationCamera.gameObject.transform.parent.transform.localScale.x;
AnimationCamera.fieldOfView = fov;
}
}
private void AddLiveSound(UmaDatabaseEntry entry)
{
UmaAssetManager.LoadAssetBundle(entry, false, false);
CurrentLiveSoundAWB.Add(entry);
}
private void ClearLiveSounds()
{
foreach (var liveSound in CurrentLiveSoundAWB)
{
UmaAssetManager.UnloadAssetBundle(liveSound, true);
}
CurrentLiveSoundAWB.Clear();
}
}
| 412 | 0.914783 | 1 | 0.914783 | game-dev | MEDIA | 0.973355 | game-dev | 0.930276 | 1 | 0.930276 |
chenghanpeng/jdk8u60 | 19,424 | hotspot/src/share/tools/IdealGraphVisualizer/ServerCompiler/src/com/sun/hotspot/igv/servercompiler/ServerCompilerScheduler.java | /*
* Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.hotspot.igv.servercompiler;
import com.sun.hotspot.igv.data.InputBlock;
import com.sun.hotspot.igv.data.InputEdge;
import com.sun.hotspot.igv.data.InputGraph;
import com.sun.hotspot.igv.data.InputNode;
import com.sun.hotspot.igv.data.services.Scheduler;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.Vector;
/**
*
* @author Thomas Wuerthinger
*/
public class ServerCompilerScheduler implements Scheduler {
private static class Node {
public InputNode inputNode;
public Set<Node> succs = new HashSet<Node>();
public List<Node> preds = new ArrayList<Node>();
public InputBlock block;
public boolean isBlockProjection;
public boolean isBlockStart;
}
private InputGraph graph;
private Collection<Node> nodes;
private Map<InputNode, Node> inputNodeToNode;
private Vector<InputBlock> blocks;
private Map<InputBlock, InputBlock> dominatorMap;
private Map<InputBlock, Integer> blockIndex;
private InputBlock[][] commonDominator;
private static final Comparator<InputEdge> edgeComparator = new Comparator<InputEdge>() {
public int compare(InputEdge o1, InputEdge o2) {
return o1.getToIndex() - o2.getToIndex();
}
};
public void buildBlocks() {
blocks = new Vector<InputBlock>();
Node root = findRoot();
if (root == null) {
return;
}
Stack<Node> stack = new Stack<Node>();
Set<Node> visited = new HashSet<Node>();
stack.add(root);
int blockCount = 0;
InputBlock rootBlock = null;
while (!stack.isEmpty()) {
Node proj = stack.pop();
Node parent = proj;
if (proj.isBlockProjection && proj.preds.size() > 0) {
parent = proj.preds.get(0);
}
if (!visited.contains(parent)) {
visited.add(parent);
InputBlock block = new InputBlock(graph, "" + blockCount);
blocks.add(block);
if (parent == root) {
rootBlock = block;
}
blockCount++;
parent.block = block;
if (proj != parent && proj.succs.size() == 1 && proj.succs.contains(root)) {
// Special treatment of Halt-nodes
proj.block = block;
}
Node p = proj;
do {
if (p.preds.size() == 0 || p.preds.get(0) == null) {
p = parent;
break;
}
p = p.preds.get(0);
if (p.block == null) {
p.block = block;
}
} while (!p.isBlockProjection && !p.isBlockStart);
if (block != rootBlock) {
for (Node n : p.preds) {
if (n != null && n != p) {
if (n.isBlockProjection) {
n = n.preds.get(0);
}
if (n.block != null) {
n.block.addSuccessor(block);
}
}
}
}
for (Node n : parent.succs) {
if (n != root && n.isBlockProjection) {
for (Node n2 : n.succs) {
if (n2 != parent && n2.block != null && n2.block != rootBlock) {
block.addSuccessor(n2.block);
}
}
} else {
if (n != parent && n.block != null && n.block != rootBlock) {
block.addSuccessor(n.block);
}
}
}
int num_preds = p.preds.size();
int bottom = -1;
if (isRegion(p) || isPhi(p)) {
bottom = 0;
}
int pushed = 0;
for (int i = num_preds - 1; i > bottom; i--) {
if (p.preds.get(i) != null && p.preds.get(i) != p) {
stack.push(p.preds.get(i));
pushed++;
}
}
if (pushed == 0 && p == root) {
// TODO: special handling when root backedges are not built yet
}
}
}
for (Node n : nodes) {
InputBlock block = n.block;
if (block != null) {
block.addNode(n.inputNode.getId());
}
}
int z = 0;
blockIndex = new HashMap<InputBlock, Integer>();
for (InputBlock b : blocks) {
blockIndex.put(b, z);
z++;
}
}
private String getBlockName(InputNode n) {
return n.getProperties().get("block");
}
public Collection<InputBlock> schedule(InputGraph graph) {
if (graph.getBlocks().size() > 0) {
Collection<InputNode> tmpNodes = new ArrayList<InputNode>(graph.getNodes());
for (InputNode n : tmpNodes) {
String block = getBlockName(n);
if (graph.getBlock(n) == null) {
graph.getBlock(block).addNode(n);
assert graph.getBlock(n) != null;
}
}
return graph.getBlocks();
} else {
nodes = new ArrayList<Node>();
inputNodeToNode = new HashMap<InputNode, Node>();
this.graph = graph;
buildUpGraph();
buildBlocks();
buildDominators();
buildCommonDominators();
scheduleLatest();
for (InputNode n : graph.getNodes()) {
assert graph.getBlock(n) != null;
}
return blocks;
}
}
public void scheduleLatest() {
Node root = findRoot();
// Mark all nodes reachable in backward traversal from root
Set<Node> reachable = new HashSet<Node>();
reachable.add(root);
Stack<Node> stack = new Stack<Node>();
stack.push(root);
while (!stack.isEmpty()) {
Node cur = stack.pop();
for (Node n : cur.preds) {
if (!reachable.contains(n)) {
reachable.add(n);
stack.push(n);
}
}
}
Set<Node> unscheduled = new HashSet<Node>();
for (Node n : this.nodes) {
if (n.block == null && reachable.contains(n)) {
unscheduled.add(n);
}
}
while (unscheduled.size() > 0) {
boolean progress = false;
Set<Node> newUnscheduled = new HashSet<Node>();
for (Node n : unscheduled) {
InputBlock block = null;
if (this.isPhi(n) && n.preds.get(0) != null) {
// Phi nodes in same block as region nodes
block = n.preds.get(0).block;
} else {
for (Node s : n.succs) {
if (reachable.contains(s)) {
if (s.block == null) {
block = null;
break;
} else {
if (block == null) {
block = s.block;
} else {
block = commonDominator[this.blockIndex.get(block)][blockIndex.get(s.block)];
}
}
}
}
}
if (block != null) {
n.block = block;
block.addNode(n.inputNode.getId());
progress = true;
} else {
newUnscheduled.add(n);
}
}
unscheduled = newUnscheduled;
if (!progress) {
break;
}
}
Set<Node> curReachable = new HashSet<Node>(reachable);
for (Node n : curReachable) {
if (n.block != null) {
for (Node s : n.succs) {
if (!reachable.contains(s)) {
markWithBlock(s, n.block, reachable);
}
}
}
}
}
private void markWithBlock(Node n, InputBlock b, Set<Node> reachable) {
assert !reachable.contains(n);
Stack<Node> stack = new Stack<Node>();
stack.push(n);
n.block = b;
b.addNode(n.inputNode.getId());
reachable.add(n);
while (!stack.isEmpty()) {
Node cur = stack.pop();
for (Node s : cur.succs) {
if (!reachable.contains(s)) {
reachable.add(s);
s.block = b;
b.addNode(s.inputNode.getId());
stack.push(s);
}
}
for (Node s : cur.preds) {
if (!reachable.contains(s)) {
reachable.add(s);
s.block = b;
b.addNode(s.inputNode.getId());
stack.push(s);
}
}
}
}
private class BlockIntermediate {
InputBlock block;
int index;
int dominator;
int semi;
int parent;
int label;
int ancestor;
List<Integer> pred;
List<Integer> bucket;
}
public void buildCommonDominators() {
commonDominator = new InputBlock[this.blocks.size()][this.blocks.size()];
for (int i = 0; i < blocks.size(); i++) {
for (int j = 0; j < blocks.size(); j++) {
commonDominator[i][j] = getCommonDominator(i, j);
}
}
}
public InputBlock getCommonDominator(int a, int b) {
InputBlock ba = blocks.get(a);
InputBlock bb = blocks.get(b);
if (ba == bb) {
return ba;
}
Set<InputBlock> visited = new HashSet<InputBlock>();
while (ba != null) {
visited.add(ba);
ba = dominatorMap.get(ba);
}
while (bb != null) {
if (visited.contains(bb)) {
return bb;
}
bb = dominatorMap.get(bb);
}
assert false;
return null;
}
public void buildDominators() {
dominatorMap = new HashMap<InputBlock, InputBlock>();
if (blocks.size() == 0) {
return;
}
Vector<BlockIntermediate> intermediate = new Vector<BlockIntermediate>();
Map<InputBlock, BlockIntermediate> map = new HashMap<InputBlock, BlockIntermediate>();
int z = 0;
for (InputBlock b : blocks) {
BlockIntermediate bi = new BlockIntermediate();
bi.block = b;
bi.index = z;
bi.dominator = -1;
bi.semi = -1;
bi.parent = -1;
bi.label = z;
bi.ancestor = -1;
bi.pred = new ArrayList<Integer>();
bi.bucket = new ArrayList<Integer>();
intermediate.add(bi);
map.put(b, bi);
z++;
}
Stack<Integer> stack = new Stack<Integer>();
stack.add(0);
Vector<BlockIntermediate> array = new Vector<BlockIntermediate>();
intermediate.get(0).dominator = 0;
int n = 0;
while (!stack.isEmpty()) {
int index = stack.pop();
BlockIntermediate ib = intermediate.get(index);
ib.semi = n;
array.add(ib);
n = n + 1;
for (InputBlock b : ib.block.getSuccessors()) {
BlockIntermediate succ = map.get(b);
if (succ.semi == -1) {
succ.parent = index;
stack.push(succ.index); // TODO: check if same node could be pushed twice
}
succ.pred.add(index);
}
}
for (int i = n - 1; i > 0; i--) {
BlockIntermediate block = array.get(i);
int block_index = block.index;
for (int predIndex : block.pred) {
int curIndex = eval(predIndex, intermediate);
BlockIntermediate curBlock = intermediate.get(curIndex);
if (curBlock.semi < block.semi) {
block.semi = curBlock.semi;
}
}
int semiIndex = block.semi;
BlockIntermediate semiBlock = array.get(semiIndex);
semiBlock.bucket.add(block_index);
link(block.parent, block_index, intermediate);
BlockIntermediate parentBlock = intermediate.get(block.parent);
for (int j = 0; j < parentBlock.bucket.size(); j++) {
for (int curIndex : parentBlock.bucket) {
int newIndex = eval(curIndex, intermediate);
BlockIntermediate curBlock = intermediate.get(curIndex);
BlockIntermediate newBlock = intermediate.get(newIndex);
int dom = block.parent;
if (newBlock.semi < curBlock.semi) {
dom = newIndex;
}
curBlock.dominator = dom;
}
}
parentBlock.bucket.clear();
}
for (int i = 1; i < n; i++) {
BlockIntermediate block = array.get(i);
int block_index = block.index;
int semi_index = block.semi;
BlockIntermediate semi_block = array.get(semi_index);
if (block.dominator != semi_block.index) {
int new_dom = intermediate.get(block.dominator).dominator;
block.dominator = new_dom;
}
}
for (BlockIntermediate ib : intermediate) {
if (ib.dominator == -1) {
ib.dominator = 0;
}
}
for (BlockIntermediate bi : intermediate) {
InputBlock b = bi.block;
int dominator = bi.dominator;
InputBlock dominatorBlock = null;
if (dominator != -1) {
dominatorBlock = intermediate.get(dominator).block;
}
if (dominatorBlock == b) {
dominatorBlock = null;
}
this.dominatorMap.put(b, dominatorBlock);
}
}
private void compress(int index, Vector<BlockIntermediate> blocks) {
BlockIntermediate block = blocks.get(index);
int ancestor = block.ancestor;
assert ancestor != -1;
BlockIntermediate ancestor_block = blocks.get(ancestor);
if (ancestor_block.ancestor != -1) {
compress(ancestor, blocks);
int label = block.label;
BlockIntermediate label_block = blocks.get(label);
int ancestor_label = ancestor_block.label;
BlockIntermediate ancestor_label_block = blocks.get(label);
if (ancestor_label_block.semi < label_block.semi) {
block.label = ancestor_label;
}
block.ancestor = ancestor_block.ancestor;
}
}
private int eval(int index, Vector<BlockIntermediate> blocks) {
BlockIntermediate block = blocks.get(index);
if (block.ancestor == -1) {
return index;
} else {
compress(index, blocks);
return block.label;
}
}
private void link(int index1, int index2, Vector<BlockIntermediate> blocks) {
BlockIntermediate block2 = blocks.get(index2);
block2.ancestor = index1;
}
private boolean isRegion(Node n) {
return n.inputNode.getProperties().get("name").equals("Region");
}
private boolean isPhi(Node n) {
return n.inputNode.getProperties().get("name").equals("Phi");
}
private Node findRoot() {
for (Node n : nodes) {
InputNode inputNode = n.inputNode;
if (inputNode.getProperties().get("name").equals("Root")) {
return n;
}
}
return null;
}
public void buildUpGraph() {
for (InputNode n : graph.getNodes()) {
Node node = new Node();
node.inputNode = n;
nodes.add(node);
String p = n.getProperties().get("is_block_proj");
node.isBlockProjection = (p != null && p.equals("true"));
p = n.getProperties().get("is_block_start");
node.isBlockStart = (p != null && p.equals("true"));
inputNodeToNode.put(n, node);
}
Map<Integer, List<InputEdge>> edgeMap = new HashMap<Integer, List<InputEdge>>();
for (InputEdge e : graph.getEdges()) {
int to = e.getTo();
if (!edgeMap.containsKey(to)) {
edgeMap.put(to, new ArrayList<InputEdge>());
}
List<InputEdge> list = edgeMap.get(to);
list.add(e);
}
for (Integer i : edgeMap.keySet()) {
List<InputEdge> list = edgeMap.get(i);
Collections.sort(list, edgeComparator);
int to = i;
InputNode toInputNode = graph.getNode(to);
Node toNode = inputNodeToNode.get(toInputNode);
for (InputEdge e : list) {
assert to == e.getTo();
int from = e.getFrom();
InputNode fromInputNode = graph.getNode(from);
Node fromNode = inputNodeToNode.get(fromInputNode);
fromNode.succs.add(toNode);
toNode.preds.add(fromNode);
}
}
}
}
| 412 | 0.918191 | 1 | 0.918191 | game-dev | MEDIA | 0.385715 | game-dev | 0.972084 | 1 | 0.972084 |
LootrMinecraft/Lootr | 2,048 | common/src/main/java/noobanidus/mods/lootr/common/mixins/MixinCatSitOnBlockGoal.java | package noobanidus.mods.lootr.common.mixins;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.ai.goal.CatSitOnBlockGoal;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import noobanidus.mods.lootr.common.api.LootrAPI;
import noobanidus.mods.lootr.common.api.LootrTags;
import noobanidus.mods.lootr.common.api.data.blockentity.ILootrBlockEntity;
import noobanidus.mods.lootr.common.api.registry.LootrRegistry;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(CatSitOnBlockGoal.class)
public class MixinCatSitOnBlockGoal {
@Redirect(method = "isValidTarget", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockState;is(Lnet/minecraft/world/level/block/Block;)Z"))
protected boolean LootrIsIn(BlockState state, Block block) {
if (LootrRegistry.isReady()) {
return state.is(block) || state.is(LootrTags.Blocks.CATS_CAN_BLOCK);
} else {
return state.is(block);
}
}
@Inject(method = "isValidTarget", at = @At(target = "Lnet/minecraft/world/level/block/entity/ChestBlockEntity;getOpenCount(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;)I", value = "INVOKE"), cancellable = true)
protected void LootrPlayersUsing(LevelReader reader, BlockPos pos, CallbackInfoReturnable<Boolean> info) {
BlockEntity blockEntity = reader.getBlockEntity(pos);
if (LootrAPI.resolveBlockEntity(blockEntity) instanceof ILootrBlockEntity lootrBlockEntity) {
if (lootrBlockEntity.getPhysicalOpenerCount() < 1) {
info.setReturnValue(true);
info.cancel();
}
}
}
// The rest of this is handled in ChestBlock::isCatSittingOnChest
}
| 412 | 0.743264 | 1 | 0.743264 | game-dev | MEDIA | 0.998192 | game-dev | 0.904079 | 1 | 0.904079 |
project-topaz/topaz | 1,081 | scripts/globals/mobskills/claw_storm.lua | ---------------------------------------------
-- Claw Storm
--
-- Description: Slashes a single target in a threefold attack. Additional effect: Poison
-- Type: Physical
-- Utsusemi/Blink absorb: 1 shadow
-- Range: Melee
-- Notes:
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target, mob, skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 3
local accmod = 1
local dmgmod = 1.1
local info = MobPhysicalMove(mob, target, skill, numhits, accmod, dmgmod, TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg, mob, skill, target, tpz.attackType.PHYSICAL, tpz.damageType.SLASHING, info.hitslanded)
target:takeDamage(dmg, mob, tpz.attackType.PHYSICAL, tpz.damageType.SLASHING)
local typeEffect = tpz.effect.POISON
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, mob:getMainLvl()/2.5, 3, 30)
return dmg
end
| 412 | 0.862814 | 1 | 0.862814 | game-dev | MEDIA | 0.988157 | game-dev | 0.800227 | 1 | 0.800227 |
Drake53/War3Net | 1,580 | src/War3Net.Runtime.Core/Enums/UnitState.cs | // ------------------------------------------------------------------------------
// <copyright file="UnitState.cs" company="Drake53">
// Licensed under the MIT license.
// See the LICENSE file in the project root for more information.
// </copyright>
// ------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using War3Net.Runtime.Core;
namespace War3Net.Runtime.Enums
{
public sealed class UnitState : Handle
{
private static readonly Dictionary<int, UnitState> _states = GetTypes().ToDictionary(t => (int)t, t => new UnitState(t));
private readonly Type _type;
private UnitState(Type type)
{
_type = type;
}
public enum Type
{
Life = 0,
MaxLife = 1,
Mana = 2,
MaxMana = 3,
}
public static implicit operator Type(UnitState unitState) => unitState._type;
public static explicit operator int(UnitState unitState) => (int)unitState._type;
public static UnitState GetUnitState(int i)
{
if (!_states.TryGetValue(i, out var unitState))
{
unitState = new UnitState((Type)i);
_states.Add(i, unitState);
}
return unitState;
}
private static IEnumerable<Type> GetTypes()
{
foreach (Type type in Enum.GetValues(typeof(Type)))
{
yield return type;
}
}
}
} | 412 | 0.675897 | 1 | 0.675897 | game-dev | MEDIA | 0.606346 | game-dev | 0.674107 | 1 | 0.674107 |
Squalr/Squally | 2,136 | Source/Scenes/Platformer/Components/Entities/Friendly/Hexus/EndianForest/Tier1EFHexusBehavior.cpp | #include "Tier1EFHexusBehavior.h"
#include "cocos/base/CCValue.h"
#include "Objects/Platformer/ItemPools/HexusPools/EndianForest/HexusPoolEFGeneric.h"
#include "Scenes/Hexus/CardData/CardKeys.h"
#include "Scenes/Hexus/CardData/CardList.h"
#include "Scenes/Hexus/Opponents/HexusOpponentData.h"
#include "Scenes/Hexus/StateOverride.h"
#include "Scenes/Platformer/Components/Entities/Friendly/Hexus/EndianForest/EFHexusConfig.h"
#include "Resources/HexusResources.h"
#include "Resources/SoundResources.h"
#include "Strings/Strings.h"
using namespace cocos2d;
const std::string Tier1EFHexusBehavior::MapKey = "ef-t1-hexus";
Tier1EFHexusBehavior* Tier1EFHexusBehavior::create(GameObject* owner)
{
Tier1EFHexusBehavior* instance = new Tier1EFHexusBehavior(owner);
instance->autorelease();
return instance;
}
Tier1EFHexusBehavior::Tier1EFHexusBehavior(GameObject* owner) : super(owner, SoundResources::Platformer_Entities_Generic_ChatterShort1)
{
}
Tier1EFHexusBehavior::~Tier1EFHexusBehavior()
{
}
MinMaxPool* Tier1EFHexusBehavior::generateReward()
{
ValueMap properties = ValueMap();
return HexusPoolEFGeneric::create(properties);
}
std::string Tier1EFHexusBehavior::getWinLossSaveKey()
{
// Backwards compatibility, use old string for save key
return "bard-hexus"; // Tier1EFHexusBehavior::MapKey;
}
std::string Tier1EFHexusBehavior::getBackgroundResource()
{
return HexusResources::Menus_HexusFrameEndianForest;
}
std::vector<CardData*> Tier1EFHexusBehavior::generateDeck()
{
const float LocalOrder = 1.0f / EFHexusConfig::MaxEntities;
return HexusOpponentData::generateDeck(25, this->calculateStrength(LocalOrder, EFHexusConfig::ZoneOrder),
{
CardList::getInstance()->cardListByName[CardKeys::Binary0],
CardList::getInstance()->cardListByName[CardKeys::Decimal0],
CardList::getInstance()->cardListByName[CardKeys::Hex0],
CardList::getInstance()->cardListByName[CardKeys::Mov],
CardList::getInstance()->cardListByName[CardKeys::Mov],
});
}
StateOverride* Tier1EFHexusBehavior::getStateOverride()
{
return nullptr;
}
std::vector<TutorialBase*> Tier1EFHexusBehavior::getTutorials()
{
return { };
}
| 412 | 0.828769 | 1 | 0.828769 | game-dev | MEDIA | 0.640255 | game-dev | 0.924019 | 1 | 0.924019 |
Wikitude/wikitude-sdk-samples | 7,444 | 11_Video_3_SnappingVideo/js/snappingvideo.js | var World = {
loaded: false,
init: function initFn() {
this.createOverlays();
},
createOverlays: function createOverlaysFn() {
/*
First a AR.TargetCollectionResource is created with the path to the Wikitude Target Collection(.wtc) file.
This .wtc file can be created from images using the Wikitude Studio. More information on how to create them
can be found in the documentation in the TargetManagement section.
Each target in the target collection is identified by its target name. By using this
target name, it is possible to create an AR.ImageTrackable for every target in the target collection.
*/
this.targetCollectionResource = new AR.TargetCollectionResource("assets/magazine.wtc", {
onError: World.onError
});
/*
This resource is then used as parameter to create an AR.ImageTracker. Optional parameters are passed as
object in the last argument. In this case a callback function for the onTargetsLoaded trigger is set. Once
the tracker loaded all of its target images this callback function is invoked. We also set the callback
function for the onError trigger which provides a sting containing a description of the error.
*/
this.tracker = new AR.ImageTracker(this.targetCollectionResource, {
onTargetsLoaded: World.showInfoBar,
onError: World.onError
});
/* Create play button which is used for starting the video. */
var playButtonImg = new AR.ImageResource("assets/playButton.png", {
onError: World.onError
});
var playButton = new AR.ImageDrawable(playButtonImg, 0.3, {
enabled: false,
clicked: false,
zOrder: 2,
onClick: function playButtonClicked() {
World.video.play(1);
World.video.playing = true;
playButton.clicked = true;
},
translate: {
y: -0.3
}
});
/*
Besides images, text and HTML content you are able to display videos in augmented reality. With the
help of AR.VideoDrawables you can add a video on top of any image, object or instant recognition target
(AR.ImageTrackable, AR.ObjectTrackable or AR.InstantTrackable) or have it displayed at any geo location
(AR.GeoObject).
Like any other drawable you can position, scale, rotate and change the opacity of the video drawable.
The video we use for this example is "video.mp4". As with all resources the video can be loaded locally
from the application bundle or remotely from any server. In this example the video file is already
bundled with the application.
The URL and the size are required when creating a new AR.VideoDrawable. Optionally translate, rotate and
scale can be set to position the video on the target.
The class AR.VideoDrawable offers functions and triggers to control playback of the video and get
notified of playback states. The following implementation makes use of the triggers and states to
display an image of a play button on top of the target. Once the user clicks the play button the video
starts to play. Additionally the video will be paused/resumed whenever the target is lost so the user
does not miss any video content when looking away.
Once the user clicks the button the video is played once: video.play(1). Starting the playback fires
the onPlaybackStarted trigger and hides the playButton. When playback finishes the onFinishedPlaying
trigger is called that shows the playButton again.
To give the user the possibility to pause the video the AR.VideoDrawable's click trigger is used. If
the video is playing and the user is clicking the function pause() is called which then pauses
playback. Clicking the video again resumes playback.
*/
this.video = new AR.VideoDrawable("assets/video.mp4", 0.40, {
translate: {
y: playButton.translate.y
},
zOrder: 1,
onLoaded: function videoLoaded() {
playButton.enabled = true;
},
onPlaybackStarted: function videoPlaying() {
playButton.enabled = false;
World.video.enabled = true;
},
onFinishedPlaying: function videoFinished() {
playButton.enabled = true;
World.video.playing = false;
World.video.enabled = false;
},
onClick: function videoClicked() {
if (playButton.clicked) {
playButton.clicked = false;
} else if (World.video.playing) {
World.video.pause();
World.video.playing = false;
} else {
World.video.resume();
World.video.playing = true;
}
},
onError: World.onError
});
/*
Adding the video to the image target is straight forward and similar like adding any other drawable to
an image target.
This time we don't pause/resume the video when target is lost/recognized but instead snap the video to
the screen so that the user can still watch it even when the target image is not visible for the
camera. To Do so we set the 'snapToScreen.enabledOnExitFieldOfVision' property to true which indicates
that the snapping should occur when the onImageLost event occurs. Setting the 'snapToScreen.enabled'
property to true in the onImageLost trigger will not work because the target is already lost then and
snap to screen can only activated for AR.ImageTrackable that are currently in the onImageRecognized state.
When the onImageRecognized event occurs we set 'snapToScreen.enabled' to false which will unsnap the
drawables from the cam and augmentation will stick on the target again.
Of course the video will continue playing back in the meantime so that the user can watch the entire
video without any interruption.
*/
this.pageOne = new AR.ImageTrackable(this.tracker, "pageOne", {
drawables: {
cam: [World.video, playButton]
},
onImageRecognized: function onImageRecognizedFn() {
World.pageOne.snapToScreen.enabled = false;
World.hideInfoBar();
},
snapToScreen: {
enabledOnExitFieldOfVision: true,
snapContainer: document.getElementById('snapContainer')
},
onError: World.onError
});
},
onError: function onErrorFn(error) {
alert(error);
},
hideInfoBar: function hideInfoBarFn() {
document.getElementById("infoBox").style.display = "none";
},
showInfoBar: function worldLoadedFn() {
document.getElementById("infoBox").style.display = "table";
document.getElementById("loadingMessage").style.display = "none";
}
};
World.init(); | 412 | 0.81624 | 1 | 0.81624 | game-dev | MEDIA | 0.649763 | game-dev | 0.647713 | 1 | 0.647713 |
manyxu/Phoenix3D_2.1 | 3,764 | Phoenix3D/PX2Graphics/PX2DepthProperty.cpp | // PX2DepthProperty.cpp
#include "PX2DepthProperty.hpp"
using namespace PX2;
PX2_IMPLEMENT_RTTI(PX2, Object, DepthProperty);
PX2_IMPLEMENT_STREAM(DepthProperty);
PX2_IMPLEMENT_FACTORY(DepthProperty);
PX2_IMPLEMENT_DEFAULT_NAMES(Object, DepthProperty);
//----------------------------------------------------------------------------
DepthProperty::DepthProperty ()
:
Enabled(true),
Writable(true),
Compare(CM_LEQUAL)
{
SetName("DProp");
}
//----------------------------------------------------------------------------
DepthProperty::~DepthProperty ()
{
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Property
//----------------------------------------------------------------------------
void DepthProperty::RegistProperties ()
{
Object::RegistProperties();
AddPropertyClass("DepthProperty");
AddProperty("Enabled", Object::PT_BOOL, Enabled);
AddProperty("Writable", Object::PT_BOOL, Writable);
std::vector<std::string> compares;
compares.push_back("CM_NEVER");
compares.push_back("CM_LESS");
compares.push_back("CM_EQUAL");
compares.push_back("CM_LEQUAL");
compares.push_back("CM_GREATER");
compares.push_back("CM_NOTEQUAL");
compares.push_back("CM_GEQUAL");
compares.push_back("CM_ALWAYS");
AddPropertyEnum("Compare", (int)Compare, compares);
}
//----------------------------------------------------------------------------
void DepthProperty::OnPropertyChanged (const PropertyObject &obj)
{
Object::OnPropertyChanged(obj);
if ("Enabled" == obj.Name)
{
Enabled = PX2_ANY_AS(obj.Data, bool);
}
else if ("Writable" == obj.Name)
{
Writable = PX2_ANY_AS(obj.Data, bool);
}
else if ("Compare" == obj.Name)
{
Compare = (CompareMode)PX2_ANY_AS(obj.Data, int);
}
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// ־û
//----------------------------------------------------------------------------
DepthProperty::DepthProperty (LoadConstructor value)
:
Object(value),
Enabled(false),
Writable(false),
Compare(CM_NEVER)
{
}
//----------------------------------------------------------------------------
void DepthProperty::Load (InStream& source)
{
PX2_BEGIN_DEBUG_STREAM_LOAD(source);
Object::Load(source);
PX2_VERSION_LOAD(source);
source.ReadBool(Enabled);
source.ReadBool(Writable);
source.ReadEnum(Compare);
PX2_END_DEBUG_STREAM_LOAD(DepthProperty, source);
}
//----------------------------------------------------------------------------
void DepthProperty::Link (InStream& source)
{
Object::Link(source);
}
//----------------------------------------------------------------------------
void DepthProperty::PostLink ()
{
Object::PostLink();
}
//----------------------------------------------------------------------------
bool DepthProperty::Register (OutStream& target) const
{
return Object::Register(target);
}
//----------------------------------------------------------------------------
void DepthProperty::Save (OutStream& target) const
{
PX2_BEGIN_DEBUG_STREAM_SAVE(target);
Object::Save(target);
PX2_VERSION_SAVE(target);
target.WriteBool(Enabled);
target.WriteBool(Writable);
target.WriteEnum(Compare);
PX2_END_DEBUG_STREAM_SAVE(DepthProperty, target);
}
//----------------------------------------------------------------------------
int DepthProperty::GetStreamingSize (Stream &stream) const
{
int size = Object::GetStreamingSize(stream);
size += PX2_VERSION_SIZE(mVersion);
size += PX2_BOOLSIZE(Enabled);
size += PX2_BOOLSIZE(Writable);
size += PX2_ENUMSIZE(Compare);
return size;
}
//---------------------------------------------------------------------------- | 412 | 0.786991 | 1 | 0.786991 | game-dev | MEDIA | 0.485784 | game-dev | 0.629043 | 1 | 0.629043 |
HellFirePvP/AstralSorcery | 16,530 | src/main/java/hellfirepvp/astralsorcery/common/crafting/recipe/infusion/ActiveLiquidInfusionRecipe.java | /*******************************************************************************
* HellFirePvP / Astral Sorcery 2022
*
* All rights reserved.
* The source code is available on github: https://github.com/HellFirePvP/AstralSorcery
* For further details, see the License file there.
******************************************************************************/
package hellfirepvp.astralsorcery.common.crafting.recipe.infusion;
import hellfirepvp.astralsorcery.AstralSorcery;
import hellfirepvp.astralsorcery.client.effect.function.RefreshFunction;
import hellfirepvp.astralsorcery.client.effect.function.VFXAlphaFunction;
import hellfirepvp.astralsorcery.client.effect.function.VFXColorFunction;
import hellfirepvp.astralsorcery.client.effect.function.VFXMotionController;
import hellfirepvp.astralsorcery.client.effect.handler.EffectHelper;
import hellfirepvp.astralsorcery.client.effect.source.orbital.FXOrbitalInfuserLiquid;
import hellfirepvp.astralsorcery.client.lib.EffectTemplatesAS;
import hellfirepvp.astralsorcery.client.util.ColorizationHelper;
import hellfirepvp.astralsorcery.client.util.RenderingUtils;
import hellfirepvp.astralsorcery.common.auxiliary.ChaliceHelper;
import hellfirepvp.astralsorcery.common.crafting.recipe.LiquidInfusion;
import hellfirepvp.astralsorcery.common.data.research.ResearchManager;
import hellfirepvp.astralsorcery.common.tile.TileChalice;
import hellfirepvp.astralsorcery.common.tile.TileInfuser;
import hellfirepvp.astralsorcery.common.util.ColorUtils;
import hellfirepvp.astralsorcery.common.util.MiscUtils;
import hellfirepvp.astralsorcery.common.util.RecipeHelper;
import hellfirepvp.astralsorcery.common.util.data.Vector3;
import hellfirepvp.astralsorcery.common.util.item.ItemUtils;
import hellfirepvp.astralsorcery.common.util.nbt.NBTHelper;
import net.minecraft.block.Blocks;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.RecipeManager;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fluids.FluidAttributes;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.LogicalSidedProvider;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.*;
import java.util.List;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* This class is part of the Astral Sorcery Mod
* The complete source code for this mod can be found on github.
* Class: ActiveLiquidInfusionRecipe
* Created by HellFirePvP
* Date: 09.11.2019 / 11:24
*/
public class ActiveLiquidInfusionRecipe {
private static final Random rand = new Random();
private static final int CHALICE_DISTANCE = 8;
private final LiquidInfusion recipeToCraft;
private final UUID playerCraftingUUID;
private int ticksCrafting = 0;
private final Set<BlockPos> supportingChalices = new HashSet<>();
private CompoundNBT craftingData = new CompoundNBT();
private Object orbitalLiquid = null;
public ActiveLiquidInfusionRecipe(World world, BlockPos center, LiquidInfusion recipeToCraft, UUID playerCraftingUUID) {
this(recipeToCraft, playerCraftingUUID);
if (this.recipeToCraft.acceptsChaliceInput()) {
this.findChalices(world, center);
}
}
private ActiveLiquidInfusionRecipe(LiquidInfusion recipeToCraft, UUID playerCraftingUUID) {
this.recipeToCraft = recipeToCraft;
this.playerCraftingUUID = playerCraftingUUID;
}
private void findChalices(World world, BlockPos center) {
ChaliceHelper.findNearbyChalicesCombined(world, center, this.getChaliceRequiredFluidInput(), CHALICE_DISTANCE)
.ifPresent(chalices -> chalices.forEach(chalice -> this.supportingChalices.add(chalice.getPos())));
}
public boolean matches(TileInfuser infuser) {
if (!this.getRecipeToCraft().matches(infuser, this.tryGetCraftingPlayerServer(), LogicalSide.SERVER)) {
return false;
}
if (!this.supportingChalices.isEmpty()) {
if (!ChaliceHelper.doChalicesContainCombined(infuser.getWorld(), this.supportingChalices, this.getChaliceRequiredFluidInput())) {
this.supportingChalices.clear();
}
}
return true;
}
public void tick() {
this.ticksCrafting++;
}
@OnlyIn(Dist.CLIENT)
public void tickClient(TileInfuser infuser) {
FluidStack required = new FluidStack(this.getRecipeToCraft().getLiquidInput(), FluidAttributes.BUCKET_VOLUME);
if (orbitalLiquid == null || ((FXOrbitalInfuserLiquid) orbitalLiquid).isRemoved()) {
ResourceLocation recipeName = this.getRecipeToCraft().getId();
orbitalLiquid = EffectHelper.spawnSource(
new FXOrbitalInfuserLiquid(new Vector3(infuser).add(0.5F, 0, 0.5F), required)
.setOrbitAxis(Vector3.RotAxis.Y_AXIS)
.setOrbitRadius(2F)
.setBranches(4)
.setMaxAge(300)
.refresh(RefreshFunction.tileExistsAnd(infuser,
(tInfuser, fx) -> tInfuser.getActiveRecipe() != null &&
recipeName.equals(tInfuser.getActiveRecipe().getRecipeToCraft().getId()))));
((FXOrbitalInfuserLiquid) orbitalLiquid).setActive();
}
for (int i = 0; i < 2; i++) {
playLiquidEffect(infuser, required);
}
for (int i = 0; i < 7; i++) {
playLiquidPoolEffect(infuser, required);
}
if (!this.supportingChalices.isEmpty()) {
playLiquidDrawEffect(infuser, required);
}
}
@OnlyIn(Dist.CLIENT)
private void playLiquidDrawEffect(TileInfuser infuser, FluidStack required) {
Collection<BlockPos> chalices = this.supportingChalices;
if (chalices.isEmpty()) {
return;
}
Vector3 target = new Vector3(infuser).add(0.5, 1.1, 0.5);
TextureAtlasSprite tas = RenderingUtils.getParticleTexture(required);
VFXColorFunction<?> colorFn = (fx, pTicks) -> new Color(ColorUtils.getOverlayColor(required));
for (int i = 0; i < 2 * this.supportingChalices.size(); i++) {
BlockPos chalice = MiscUtils.getRandomEntry(chalices, rand);
Vector3 pos = new Vector3(chalice).add(0.5, 1.4, 0.5);
int maxAge = 30;
maxAge *= Math.max(pos.distance(target) / 3, 1);
if (rand.nextInt(3) != 0) {
MiscUtils.applyRandomOffset(pos, rand, 0.3F);
EffectHelper.of(EffectTemplatesAS.GENERIC_ATLAS_PARTICLE)
.spawn(pos)
.setSprite(tas)
.selectFraction(0.2F)
.setScaleMultiplier(0.01F + rand.nextFloat() * 0.04F)
.color(colorFn)
.alpha(VFXAlphaFunction.proximity(() -> target, 2F).andThen(VFXAlphaFunction.FADE_OUT))
.motion(VFXMotionController.target(target::clone, 0.08F))
.setMaxAge(maxAge);
} else {
MiscUtils.applyRandomOffset(pos, rand, 0.4F);
EffectHelper.of(EffectTemplatesAS.GENERIC_PARTICLE)
.spawn(pos)
.setScaleMultiplier(0.15F + rand.nextFloat() * 0.1F)
.color(colorFn)
.alpha(VFXAlphaFunction.proximity(() -> target, 2F).andThen(VFXAlphaFunction.FADE_OUT))
.motion(VFXMotionController.target(target::clone, 0.08F))
.setMaxAge(maxAge);
}
}
}
@OnlyIn(Dist.CLIENT)
private void playLiquidEffect(TileInfuser infuser, FluidStack required) {
Vector3 vec = infuser.getRandomInfuserOffset();
MiscUtils.applyRandomOffset(vec, rand, 0.05F);
EffectHelper.of(EffectTemplatesAS.GENERIC_ATLAS_PARTICLE)
.spawn(vec)
.setSprite(RenderingUtils.getParticleTexture(required))
.selectFraction(0.2F)
.setScaleMultiplier(0.03F + rand.nextFloat() * 0.03F)
.color((fx, pTicks) -> new Color(ColorUtils.getOverlayColor(required)))
.alpha(VFXAlphaFunction.FADE_OUT)
.motion(VFXMotionController.target(() -> new Vector3(infuser).add(0.5, 1.1, 0.5), 0.3F))
.setMaxAge(40);
}
@OnlyIn(Dist.CLIENT)
private void playLiquidPoolEffect(TileInfuser infuser, FluidStack required) {
List<BlockPos> posList = TileInfuser.getLiquidOffsets().stream()
.map(pos -> pos.add(infuser.getPos()))
.collect(Collectors.toList());
BlockPos at = MiscUtils.getRandomEntry(posList, rand);
if (at != null) {
EffectHelper.of(EffectTemplatesAS.GENERIC_PARTICLE)
.spawn(new Vector3(at).add(rand.nextFloat(), 1, rand.nextFloat()))
.setScaleMultiplier(0.1F + rand.nextFloat() * 0.15F)
.color((fx, pTicks) -> ColorizationHelper.getColor(required).orElse(Color.WHITE))
.setAlphaMultiplier(1F)
.alpha(VFXAlphaFunction.FADE_OUT)
.setMotion(new Vector3(0, 0.15, 0))
.setGravityStrength(0.005F + rand.nextFloat() * 0.008F);
}
}
public void clearEffects() {
if (orbitalLiquid != null) {
//Only exists on client after all
clearClientEffect();
}
}
@OnlyIn(Dist.CLIENT)
private void clearClientEffect() {
((FXOrbitalInfuserLiquid) orbitalLiquid).requestRemoval();
}
public void createItemOutputs(TileInfuser infuser, Consumer<ItemStack> output) {
Consumer<ItemStack> informer = stack -> ResearchManager.informCraftedInfuser(infuser, this, stack);
ItemStack inputStack = infuser.getItemInput();
Consumer<ItemStack> handleCrafted = informer.andThen(output);
if (this.recipeToCraft.doesCopyNBTToOutputs()) {
handleCrafted = ((Consumer<ItemStack>) stack -> stack.setTag(inputStack.getTag())).andThen(handleCrafted);
}
handleCrafted.accept(this.getRecipeToCraft().getOutput(inputStack));
this.getRecipeToCraft().onRecipeCompletion(infuser);
}
public void consumeInputs(TileInfuser infuser) {
ItemUtils.decrementItem(infuser::getItemInput, infuser::setItemInput, infuser::dropItemOnTop);
}
public void consumeFluidsInput(TileInfuser infuser) {
float chaliceSupplied = 0F;
if (!this.supportingChalices.isEmpty()) {
FluidStack required = this.getChaliceRequiredFluidInput();
Optional<List<TileChalice>> chalices = ChaliceHelper.findNearbyChalicesCombined(infuser.getWorld(), infuser.getPos(), required, CHALICE_DISTANCE);
if (chalices.isPresent()) {
FluidStack left = required.copy();
for (TileChalice chalice : chalices.get()) {
left.shrink(chalice.getTank().drain(left, IFluidHandler.FluidAction.EXECUTE).getAmount());
if (left.isEmpty()) {
break;
}
}
if (left.isEmpty()) {
return; // Chalices provided fluid
}
chaliceSupplied = ((float) required.getAmount()) / left.getAmount();
}
}
LiquidInfusion infusion = this.getRecipeToCraft();
float chance = infusion.getConsumptionChance() * (1F - chaliceSupplied);
if (infusion.doesConsumeMultipleFluids()) {
for (BlockPos at : TileInfuser.getLiquidOffsets()) {
if (rand.nextFloat() < chance) {
infuser.getWorld().setBlockState(at.add(infuser.getPos()), Blocks.AIR.getDefaultState(), Constants.BlockFlags.DEFAULT_AND_RERENDER);
}
}
} else {
BlockPos at = MiscUtils.getRandomEntry(TileInfuser.getLiquidOffsets(), rand).add(infuser.getPos());
if (rand.nextFloat() < chance) {
infuser.getWorld().setBlockState(at, Blocks.AIR.getDefaultState(), Constants.BlockFlags.DEFAULT_AND_RERENDER);
}
}
}
public FluidStack getChaliceRequiredFluidInput() {
int amount = Math.round(FluidAttributes.BUCKET_VOLUME * recipeToCraft.getConsumptionChance());
amount *= 0.75; //Bonus for using chalices
amount = recipeToCraft.doesConsumeMultipleFluids() ? amount * TileInfuser.getLiquidOffsets().size() : amount;
return new FluidStack(this.getRecipeToCraft().getLiquidInput(), amount);
}
public int getTotalCraftingTime() {
int tickTime = this.recipeToCraft.getCraftingTickTime();
int fixTime = Math.round(tickTime * 0.25F);
int chaliceTime = Math.round(tickTime * 0.75F);
chaliceTime /= this.supportingChalices.size() + 1;
return fixTime + chaliceTime;
}
public CompoundNBT getCraftingData() {
return craftingData;
}
public UUID getPlayerCraftingUUID() {
return playerCraftingUUID;
}
public int getTicksCrafting() {
return ticksCrafting;
}
public LiquidInfusion getRecipeToCraft() {
return recipeToCraft;
}
public boolean isFinished() {
return getTicksCrafting() >= getTotalCraftingTime();
}
@Nullable
public PlayerEntity tryGetCraftingPlayerServer() {
MinecraftServer srv = LogicalSidedProvider.INSTANCE.get(LogicalSide.SERVER);
return srv.getPlayerList().getPlayerByUUID(this.getPlayerCraftingUUID());
}
@Nullable
public static ActiveLiquidInfusionRecipe deserialize(CompoundNBT compound, @Nullable ActiveLiquidInfusionRecipe prev) {
RecipeManager mgr = RecipeHelper.getRecipeManager();
if (mgr == null) {
return null;
}
ResourceLocation recipeKey = new ResourceLocation(compound.getString("recipeToCraft"));
Optional<?> recipe = mgr.getRecipe(recipeKey);
if (!recipe.isPresent() || !(recipe.get() instanceof LiquidInfusion)) {
AstralSorcery.log.info("Recipe with unknown/invalid name found: " + recipeKey);
return null;
}
LiquidInfusion altarRecipe = (LiquidInfusion) recipe.get();
UUID uuidCraft = compound.getUniqueId("playerCraftingUUID");
int tick = compound.getInt("ticksCrafting");
ListNBT chalices = compound.getList("supportingChalices", Constants.NBT.TAG_COMPOUND);
Set<BlockPos> chalicePositions = new HashSet<>();
for (int i = 0; i < chalices.size(); i++) {
CompoundNBT tag = chalices.getCompound(i);
chalicePositions.add(NBTHelper.readBlockPosFromNBT(tag));
}
ActiveLiquidInfusionRecipe task = new ActiveLiquidInfusionRecipe(altarRecipe, uuidCraft);
task.ticksCrafting = tick;
task.craftingData = compound.getCompound("craftingData");
task.supportingChalices.addAll(chalicePositions);
if (prev != null && prev.orbitalLiquid != null) {
task.orbitalLiquid = prev.orbitalLiquid;
}
return task;
}
@Nonnull
public CompoundNBT serialize() {
ListNBT chalicePositions = new ListNBT();
this.supportingChalices.forEach(pos -> chalicePositions.add(NBTHelper.writeBlockPosToNBT(pos, new CompoundNBT())));
CompoundNBT compound = new CompoundNBT();
compound.putString("recipeToCraft", getRecipeToCraft().getId().toString());
compound.putUniqueId("playerCraftingUUID", getPlayerCraftingUUID());
compound.putInt("ticksCrafting", getTicksCrafting());
compound.put("craftingData", craftingData);
compound.put("supportingChalices", chalicePositions);
return compound;
}
}
| 412 | 0.880887 | 1 | 0.880887 | game-dev | MEDIA | 0.94519 | game-dev | 0.925764 | 1 | 0.925764 |
chsami/Microbot | 31,224 | runelite-client/src/main/java/net/runelite/client/plugins/microbot/util/grounditem/Rs2GroundItemModel.java | package net.runelite.client.plugins.microbot.util.grounditem;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Constants;
import net.runelite.api.ItemComposition;
import net.runelite.api.Perspective;
import net.runelite.api.Point;
import net.runelite.api.Scene;
import net.runelite.api.Tile;
import net.runelite.api.TileItem;
import net.runelite.api.coords.LocalPoint;
import net.runelite.api.coords.WorldPoint;
import net.runelite.client.plugins.microbot.Microbot;
import net.runelite.client.plugins.microbot.util.grandexchange.Rs2GrandExchange;
import net.runelite.client.plugins.microbot.util.player.Rs2Player;
import net.runelite.client.util.RSTimeUnit;
import java.awt.Rectangle;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
/**
* Enhanced model for ground items with caching, tick tracking, and despawn utilities.
* Provides a comprehensive replacement for the deprecated RS2Item class.
* Includes looting utility methods and value-based filtering for automation.
*
* @author Vox
* @version 2.0
*/
@Data
@Getter
@EqualsAndHashCode
@Slf4j
public class Rs2GroundItemModel {
private final TileItem tileItem;
private final Tile tile;
private ItemComposition itemComposition;
private final WorldPoint location;
private final int id;
private final int quantity;
private String name;
private final boolean isOwned;
private final boolean isLootAble;
private final long creationTime;
private final int creationTick;
// Despawn tracking fields - following GroundItemsOverlay pattern
private final Instant spawnTime;
private final Duration despawnDuration;
private final Duration visibleDuration;
/**
* Creates a new Rs2GroundItemModel from a TileItem and Tile.
*
* @param tileItem The TileItem from the game
* @param tile The tile the item is on
*/
public Rs2GroundItemModel(TileItem tileItem, Tile tile) {
this.tileItem = tileItem;
this.tile = tile;
this.location = tile.getWorldLocation();
this.id = tileItem.getId();
this.quantity = tileItem.getQuantity();
this.isOwned = tileItem.getOwnership() == TileItem.OWNERSHIP_SELF;
this.isLootAble = !(tileItem.getOwnership() == TileItem.OWNERSHIP_OTHER);
this.creationTime = System.currentTimeMillis();
this.creationTick = Microbot.getClient().getTickCount();
// Initialize despawn tracking following GroundItemsPlugin.buildGroundItem() pattern
this.spawnTime = Instant.now();
// Calculate despawn time exactly like GroundItemsPlugin.buildGroundItem()
// final int despawnTime = item.getDespawnTime() - client.getTickCount();
// .despawnTime(Duration.of(despawnTime, RSTimeUnit.GAME_TICKS))
int despawnTime = 0;
int visibleTime = 0;
if (tileItem.getDespawnTime() > this.creationTick){
despawnTime = tileItem.getDespawnTime() - this.creationTick;
}
if (tileItem.getVisibleTime() > this.creationTick) {
visibleTime = tileItem.getVisibleTime() - this.creationTick;
}
// Use the exact same pattern as official RuneLite GroundItemsPlugin
this.despawnDuration = Duration.of(despawnTime, RSTimeUnit.GAME_TICKS);
this.visibleDuration = Duration.of(visibleTime, RSTimeUnit.GAME_TICKS);
// Initialize composition and name as null for lazy loading
this.itemComposition = null;
this.name = null;
log.debug("Created Rs2GroundItemModel: {} x{} at {} | Spawn: {} | Despawn: {} (Local) | tick despawn: {} | current tick: {}",
getName(), quantity, location,
spawnTime.atZone(ZoneOffset.systemDefault()).format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
getDespawnTime().atZone(ZoneOffset.systemDefault()).format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
tileItem.getDespawnTime(),
this.creationTick
);
}
/**
* Lazy loads the ItemComposition if not already loaded.
* This ensures we can work with ground items while minimizing performance impact.
*/
private void ensureCompositionLoaded() {
if (itemComposition == null && id > 0) {
try {
this.itemComposition = Microbot.getClientThread().runOnClientThreadOptional(() ->
Microbot.getClient().getItemDefinition(id)
).orElse(null);
if (itemComposition != null) {
this.name = itemComposition.getName();
} else {
log.warn("Failed to load ItemComposition for ground item id: {}, setting default name", id);
this.name = "Unknown Item";
}
} catch (Exception e) {
log.warn("Error loading ItemComposition for ground item id: {}, using defaults: {}", id, e.getMessage());
this.name = "Unknown Item";
this.itemComposition = null;
}
}
}
/**
* Gets the item name, loading composition if needed.
*
* @return The item name or "Unknown Item" if composition fails to load
*/
public String getName() {
if (name == null) {
ensureCompositionLoaded();
}
return name != null ? name : "Unknown Item";
}
/**
* Gets the item composition, loading it if needed.
*
* @return The ItemComposition or null if it fails to load
*/
public ItemComposition getItemComposition() {
if (itemComposition == null) {
ensureCompositionLoaded();
}
return itemComposition;
}
// ============================================
// Time and Tick Tracking Methods
// ============================================
/**
* Gets the number of ticks since this item was created.
*
* @return The number of ticks since creation
*/
public int getTicksSinceCreation() {
return Microbot.getClient().getTickCount() - creationTick;
}
/**
* Gets the number of ticks since this item spawned (alias for getTicksSinceCreation).
*
* @return The number of ticks since spawn
*/
public int getTicksSinceSpawn() {
return getTicksSinceCreation();
}
/**
* Gets the time in milliseconds since this item was created.
*
* @return Milliseconds since creation
*/
public long getTimeSinceCreation() {
return System.currentTimeMillis() - creationTime;
}
// ============================================
// Despawn Tracking Methods
// ============================================
/**
* Gets the spawn time as an Instant (following GroundItemsOverlay pattern).
*
* @return Instant when the item spawned
*/
public Instant getSpawnTime() {
return spawnTime;
}
/**
* Gets the despawn duration for this item.
*
* @return Duration until despawn from spawn time
*/
public Duration getDespawnDuration() {
return despawnDuration;
}
/**
* Gets the absolute time when this item will despawn (following GroundItemsOverlay pattern).
*
* @return Instant when the item despawns
*/
public Instant getDespawnTime() {
return spawnTime.plus(despawnDuration);
}
/**
* Gets the UTC timestamp when this item will despawn.
*
* @return UTC timestamp in milliseconds when item despawns
*/
public long getDespawnTimestampUtc() {
return getDespawnTime().toEpochMilli();
}
/**
* Gets the duration remaining until this item despawns.
*
* @return Duration until despawn, or Duration.ZERO if already despawned
*/
public Duration getTimeUntilDespawn() {
Instant despawnTime = getDespawnTime();
Instant now = Instant.now();
if (now.isAfter(despawnTime)) {
return Duration.ZERO;
}
return Duration.between(now, despawnTime);
}
/**
* Gets the number of ticks remaining until this item despawns.
*
* @return Ticks until despawn, or 0 if already despawned
*/
public int getTicksUntilDespawn() {
// Convert despawnDuration back to ticks using RSTimeUnit pattern
long despawnTicks = despawnDuration.toMillis() / Constants.GAME_TICK_LENGTH;
int currentTick = Microbot.getClientThread().runOnClientThreadOptional(
() -> Microbot.getClient().getTickCount()
).orElse((int)(creationTick + despawnTicks + 1)); // Fallback assumes despawned
int ticksSinceSpawn = currentTick - creationTick;
long ticksRemaining = despawnTicks - ticksSinceSpawn;
return Math.max(0, (int)ticksRemaining);
}
// ============================================
// UTC Timestamp Getter Methods
// ============================================
/**
* Gets the UTC spawn time as ZonedDateTime.
*
* @return Spawn time in UTC
*/
public ZonedDateTime getSpawnTimeUtc() {
return spawnTime.atZone(ZoneOffset.UTC);
}
/**
* Gets the UTC spawn timestamp in milliseconds.
*
* @return Spawn timestamp in UTC milliseconds
*/
public long getSpawnTimestampUtc() {
return spawnTime.toEpochMilli();
}
/**
* Gets the total number of ticks this item should exist before despawning.
*
* @return Total despawn ticks
*/
public int getDespawnTicks() {
return (int)(despawnDuration.toMillis() / Constants.GAME_TICK_LENGTH);
}
/**
* Gets the number of seconds remaining until this item despawns.
*
* @return Seconds until despawn, or 0 if already despawned
*/
public long getSecondsUntilDespawn() {
return getTimeUntilDespawn().getSeconds();
}
/**
* Checks if this item has despawned based on game ticks.
* This is more accurate than real-time checking since OSRS is tick-based.
*
* @return true if the item should have despawned
*/
public boolean isDespawned() {
if (isPersistened()) {
return false; // Persisted items never despawn
}
return Instant.now().isAfter(getDespawnTime());
// Use tick-based calculation for more accurate game timing
//long despawnTicks = despawnDuration.toMillis() / Constants.GAME_TICK_LENGTH;
//int currentTick = Microbot.getClient().getTickCount();
//int ticksSinceSpawn = currentTick - creationTick;
//return ticksSinceSpawn >= despawnTicks;
}
public boolean isPersistened(){
// Check if the despawn duration is negative or very large
return despawnDuration.isNegative() ||despawnDuration.isZero() || despawnDuration.toMillis() > 24 * 60 * 60 * 1000; // More than 24 hours
}
/**
* Checks if this item has despawned based on UTC timestamp (fallback method).
* Less accurate than tick-based method but useful when client is unavailable.
*
* @return true if the item should have despawned based on time
*/
public boolean isDespawnedByTime() {
return ZonedDateTime.now(ZoneOffset.UTC).isAfter(getDespawnTime().atZone(ZoneOffset.UTC));
} /**
* Checks if this item will despawn within the specified number of seconds.
*
* @param seconds The time threshold in seconds
* @return true if the item will despawn within the given time
*/
public boolean willDespawnWithin(long seconds) {
return getSecondsUntilDespawn() <= seconds;
}
/**
* Checks if this item will despawn within the specified number of ticks.
*
* @param ticks The time threshold in ticks
* @return true if the item will despawn within the given ticks
*/
public boolean willDespawnWithinTicks(int ticks) {
return getTicksUntilDespawn() <= ticks;
}
// ============================================
// Item Property Methods
// ============================================
/**
* Checks if this item is stackable.
*
* @return true if stackable, false otherwise
*/
public boolean isStackable() {
try {
ItemComposition composition = getItemComposition();
return composition != null && composition.isStackable();
} catch (Exception e) {
log.warn("Error checking if item is stackable for id: {}: {}", id, e.getMessage());
return false;
}
}
/**
* Checks if this item is noted.
*
* @return true if noted, false otherwise
*/
public boolean isNoted() {
try {
ItemComposition composition = getItemComposition();
return composition != null && composition.getNote() != -1;
} catch (Exception e) {
log.warn("Error checking if item is noted for id: {}: {}", id, e.getMessage());
return false;
}
}
/**
* Gets the item's store value.
*
* @return The item's store value
*/
public int getValue() {
try {
ItemComposition composition = getItemComposition();
return composition != null ? composition.getPrice() : 0;
} catch (Exception e) {
log.warn("Error getting value for item id: {}: {}", id, e.getMessage());
return 0;
}
}
/**
* Gets the item's Grand Exchange price.
*
* @return The item's GE price
*/
public int getPrice() {
return Rs2GrandExchange.getPrice(this.id);
}
/**
* Gets the total value of this item stack (quantity * unit value).
*
* @return The total stack value
*/
public int getTotalValue() {
return getValue() * quantity;
}
/**
* Gets the total Grand Exchange value of this item stack.
*
* @return The total stack GE value
*/
public int getTotalGeValue() {
return getPrice() * quantity;
}
/**
* Gets the item's high alchemy value.
*
* @return The high alchemy value
*/
public int getHaPrice() {
try {
ItemComposition composition = getItemComposition();
return composition != null ? composition.getHaPrice() : 0;
} catch (Exception e) {
log.warn("Error getting high alchemy price for item id: {}: {}", id, e.getMessage());
return 0;
}
}
/**
* Gets the total high alchemy value of this item stack.
*
* @return The total stack high alchemy value
*/
public int getTotalHaValue() {
return getHaPrice() * quantity;
}
/**
* Gets the item's low alchemy value.
* This is calculated as 40% of the store price.
*
* @return The low alchemy value
*/
public int getLaValue() {
try {
ItemComposition composition = getItemComposition();
return composition != null ? (int)(composition.getPrice() * 0.4) : 0;
} catch (Exception e) {
log.warn("Error getting low alchemy value for item id: {}: {}", id, e.getMessage());
return 0;
}
}
/**
* Gets the total low alchemy value of this item stack.
*
* @return The total stack low alchemy value
*/
public int getTotalLaValue() {
return getLaValue() * quantity;
}
/**
* Checks if this item is members-only.
*
* @return true if members-only, false otherwise
*/
public boolean isMembers() {
try {
ItemComposition composition = getItemComposition();
return composition != null && composition.isMembers();
} catch (Exception e) {
log.warn("Error checking if item is members-only for id: {}: {}", id, e.getMessage());
return false;
}
}
/**
* Checks if this item is tradeable.
*
* @return true if tradeable, false otherwise
*/
public boolean isTradeable() {
try {
ItemComposition composition = getItemComposition();
return composition != null && composition.isTradeable();
} catch (Exception e) {
log.warn("Error checking if item is tradeable for id: {}: {}", id, e.getMessage());
return false;
}
}
/**
* Gets the item's inventory actions.
*
* @return Array of inventory actions
*/
public String[] getInventoryActions() {
try {
ItemComposition composition = getItemComposition();
return composition != null ? composition.getInventoryActions() : new String[0];
} catch (Exception e) {
log.warn("Error getting inventory actions for item id: {}: {}", id, e.getMessage());
return new String[0];
}
}
// ============================================
// Looting Utility Methods
// ============================================
/**
* Checks if this item is worth looting based on minimum value.
*
* @param minValue The minimum value threshold
* @return true if the item's total value meets the threshold
*/
public boolean isWorthLooting(int minValue) {
return getTotalValue() >= minValue;
}
/**
* Checks if this item is worth looting based on Grand Exchange value.
*
* @param minGeValue The minimum GE value threshold
* @return true if the item's total GE value meets the threshold
*/
public boolean isWorthLootingGe(int minGeValue) {
return getTotalGeValue() >= minGeValue;
}
/**
* Checks if this item is worth high alching based on profit margin.
*
* @param minProfit The minimum profit threshold
* @return true if high alching would be profitable
*/
public boolean isProfitableToHighAlch(int minProfit) {
// High alch value minus nature rune cost (estimated)
int profit = getTotalHaValue() - (quantity * 200); // Assuming 200gp nature rune cost
return profit >= minProfit;
}
/**
* Checks if this item is a commonly desired loot type.
* Includes coins, gems, ores, logs, herbs, and high-value items.
*
* @return true if the item is commonly looted
*/
public boolean isCommonLoot() {
if (name == null) return false;
String lowerName = name.toLowerCase();
// Always loot coins
if (lowerName.contains("coins")) return true;
// High value items
if (getTotalValue() >= 1000) return true;
// Common valuable items
return lowerName.contains("gem") ||
lowerName.contains("ore") ||
lowerName.contains("bar") ||
lowerName.contains("log") ||
lowerName.contains("herb") ||
lowerName.contains("seed") ||
lowerName.contains("rune") ||
lowerName.contains("arrow") ||
lowerName.contains("bolt");
}
/**
* Checks if this item should be prioritized for urgent looting.
* Based on high value and short despawn time.
*
* @return true if the item should be prioritized
*/
public boolean shouldPrioritize() {
// High value items or items about to despawn
return getTotalValue() >= 5000 || willDespawnWithin(30);
}
// ============================================
// Distance and Position Methods
// ============================================
/**
* Gets the distance to this item from the player.
*
* @return The distance in tiles
*/
public int getDistanceFromPlayer() {
return Microbot.getClientThread().runOnClientThreadOptional(() -> {
WorldPoint playerLocation =
Rs2Player.getWorldLocation();
return playerLocation.distanceTo(location);
}).orElse(Integer.MAX_VALUE);
}
/**
* Checks if this item is within a certain distance from the player.
*
* @param maxDistance The maximum distance in tiles
* @return true if within distance, false otherwise
*/
public boolean isWithinDistanceFromPlayer(int maxDistance) {
return getDistanceFromPlayer() <= maxDistance;
}
/**
* Gets the distance to this item from a specific point.
*
* @param point The world point to measure from
* @return The distance in tiles
*/
public int getDistanceFrom(WorldPoint point) {
return location.distanceTo(point);
}
/**
* Checks if this item is within a certain distance from a specific point.
*
* @param point The world point to measure from
* @param maxDistance The maximum distance in tiles
* @return true if within distance, false otherwise
*/
public boolean isWithinDistanceFrom(WorldPoint point, int maxDistance) {
return getDistanceFrom(point) <= maxDistance;
}
// ============================================
// Scene and Viewport Detection Methods
// ============================================
/**
* Checks if this ground item is still present in the current scene.
* This verifies that the TileItem still exists on its tile in the scene.
*
* @return true if the item is still in the current scene, false otherwise
*/
public boolean isInCurrentScene() {
return Microbot.getClientThread().runOnClientThreadOptional(() -> {
try {
Scene scene = Microbot.getClient().getTopLevelWorldView().getScene();
// Check if the world point is within current scene bounds using WorldPoint.isInScene
if (!WorldPoint.isInScene(scene, location.getX(), location.getY())) {
return false;
}
// Convert world point to local coordinates for scene tile access
LocalPoint localPoint = LocalPoint.fromWorld(Microbot.getClient().getTopLevelWorldView(), location);
if (localPoint == null) {
return false;
}
// Get the tile from the scene using local coordinates
Tile[][][] sceneTiles = scene.getTiles();
int plane = location.getPlane();
int sceneX = localPoint.getSceneX();
int sceneY = localPoint.getSceneY();
// Validate scene coordinates
if (plane < 0 || plane >= sceneTiles.length ||
sceneX < 0 || sceneX >= Constants.SCENE_SIZE ||
sceneY < 0 || sceneY >= Constants.SCENE_SIZE) {
return false;
}
Tile sceneTile = sceneTiles[plane][sceneX][sceneY];
if (sceneTile == null) {
return false;
}
// Check if our TileItem is still on this tile
if (sceneTile.getGroundItems() != null) {
for (TileItem item : sceneTile.getGroundItems()) {
if (item.getId() == this.id &&
item.getQuantity() == this.quantity &&
item.equals(this.tileItem)) {
return true;
}
}
}
return false;
} catch (Exception e) {
log.warn("Error checking if ground item is in current scene: {}", e.getMessage());
return false;
}
}).orElse(false);
}
/**
* Checks if this ground item is visible and clickable in the current viewport.
* This combines scene presence checking with viewport visibility detection.
*
* @return true if the item is visible and clickable in the viewport, false otherwise
*/
public boolean isVisibleInViewport() {
return Microbot.getClientThread().runOnClientThreadOptional(() -> {
try {
// First check if item is still in scene
if (!isInCurrentScene()) {
return false;
}
// Convert world location to canvas point using Perspective.localToCanvas
LocalPoint localPoint = LocalPoint.fromWorld(Microbot.getClient().getTopLevelWorldView(), location);
if (localPoint == null) {
return false;
}
Point canvasPoint = Perspective.localToCanvas(Microbot.getClient(), localPoint, location.getPlane());
if (canvasPoint == null) {
return false;
}
// Check if the point is within the viewport bounds
// Following the pattern from Rs2ObjectCacheUtils.isPointInViewport
int viewportX = Microbot.getClient().getViewportXOffset();
int viewportY = Microbot.getClient().getViewportYOffset();
int viewportWidth = Microbot.getClient().getViewportWidth();
int viewportHeight = Microbot.getClient().getViewportHeight();
return canvasPoint.getX() >= viewportX &&
canvasPoint.getX() <= viewportX + viewportWidth &&
canvasPoint.getY() >= viewportY &&
canvasPoint.getY() <= viewportY + viewportHeight;
} catch (Exception e) {
log.warn("Error checking if ground item is visible in viewport: {}", e.getMessage());
return false;
}
}).orElse(false);
}
/**
* Gets the canvas point for this ground item if it's visible.
* Useful for click operations and overlay rendering.
*
* @return the Point on the canvas, or null if not visible
*/
public Point getCanvasPoint() {
return Microbot.getClientThread().runOnClientThreadOptional(() -> {
try {
if (!isInCurrentScene()) {
return null;
}
LocalPoint localPoint = LocalPoint.fromWorld(Microbot.getClient().getTopLevelWorldView(), location);
if (localPoint == null) {
return null;
}
return Perspective.localToCanvas(Microbot.getClient(), localPoint, location.getPlane());
} catch (Exception e) {
log.warn("Error getting canvas point for ground item: {}", e.getMessage());
return null;
}
}).orElse(null);
}
/**
* Checks if this ground item is clickable (in scene and in viewport).
* Convenience method that combines isInCurrentScene() and isVisibleInViewport().
*
* @return true if the item can be clicked, false otherwise
*/
public boolean isClickable() {
return isInCurrentScene() && isVisibleInViewport();
}
/**
* Checks if this ground item is currently clickable by the player within a specific distance.
* This combines scene presence, viewport visibility, and distance checks.
*
* @param maxDistance The maximum interaction distance in tiles
* @return true if the item is clickable within the specified distance, false otherwise
*/
public boolean isClickable(int maxDistance) {
// Check if item is lootable first
if (!isLootAble) {
return false;
}
// Check if item has despawned
if (isDespawned()) {
return false;
}
// Check distance from player
if (!isWithinDistanceFromPlayer(maxDistance)) {
return false;
}
// Check if visible in viewport (includes scene presence check)
return isVisibleInViewport();
}
/**
* Gets the viewport bounds as a Rectangle for utility calculations.
* Following the pattern from Rs2ObjectCacheUtils.getViewportBounds.
*
* @return Rectangle representing the current viewport bounds, or null if unavailable
*/
public Rectangle getViewportBounds() {
return Microbot.getClientThread().runOnClientThreadOptional(() -> {
try {
int viewportX = Microbot.getClient().getViewportXOffset();
int viewportY = Microbot.getClient().getViewportYOffset();
int viewportWidth = Microbot.getClient().getViewportWidth();
int viewportHeight = Microbot.getClient().getViewportHeight();
return new Rectangle(viewportX, viewportY, viewportWidth, viewportHeight);
} catch (Exception e) {
log.warn("Error getting viewport bounds: {}", e.getMessage());
return null;
}
}).orElse(null);
}
// ============================================
// Utility Methods
// ============================================
/**
* Gets a string representation of this item with UTC timing information.
*
* @return String representation
*/
@Override
public String toString() {
return String.format("Rs2GroundItemModel{id=%d, name='%s', quantity=%d, location=%s, owned=%s, lootable=%s, value=%d, despawnTicksLeft=%d, spawnTimeUtc='%s', despawnTimeUtc='%s'}",
id, name, quantity, location, isOwned, isLootAble, getTotalValue(), getTicksUntilDespawn(),
getSpawnTimeUtc().toString(), getDespawnTime().atZone(ZoneOffset.UTC).toString());
}
/**
* Gets a detailed string representation including all properties.
*
* @return Detailed string representation
*/
public String toDetailedString() {
return String.format(
"Rs2GroundItemModel{" +
"id=%d, name='%s', quantity=%d, location=%s, " +
"owned=%s, lootable=%s, stackable=%s, noted=%s, tradeable=%s, " +
"value=%d, geValue=%d, haValue=%d, totalValue=%d, " +
"ticksSinceSpawn=%d, ticksUntilDespawn=%d, secondsUntilDespawn=%d" +
"}",
id, name, quantity, location,
isOwned, isLootAble, isStackable(), isNoted(), isTradeable(),
getValue(), getPrice(), getHaPrice(), getTotalValue(),
getTicksSinceSpawn(), getTicksUntilDespawn(), getSecondsUntilDespawn()
);
}
}
| 412 | 0.915438 | 1 | 0.915438 | game-dev | MEDIA | 0.966971 | game-dev | 0.919975 | 1 | 0.919975 |
Fluorohydride/ygopro-scripts | 5,625 | c12800564.lua | --真竜魔王マスターP
local s,id,o=GetID()
function s.initial_effect(c)
--summon with s/t
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_SINGLE)
e0:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e0:SetCode(EFFECT_ADD_EXTRA_TRIBUTE)
e0:SetTargetRange(LOCATION_SZONE,0)
e0:SetTarget(aux.TargetBoolFunction(Card.IsType,TYPE_CONTINUOUS))
e0:SetValue(POS_FACEUP_ATTACK)
c:RegisterEffect(e0)
--summon with 3 tribute
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_LIMIT_SUMMON_PROC)
e1:SetCondition(s.ttcon)
e1:SetOperation(s.ttop)
e1:SetValue(SUMMON_TYPE_ADVANCE)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_LIMIT_SET_PROC)
e2:SetCondition(s.setcon)
c:RegisterEffect(e2)
--negate
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(id,1))
e3:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY)
e3:SetType(EFFECT_TYPE_QUICK_O)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EVENT_CHAINING)
e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL)
e3:SetCountLimit(1,id)
e3:SetCondition(s.negcon)
e3:SetTarget(s.negtg)
e3:SetOperation(s.negop)
c:RegisterEffect(e3)
--skip phase
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(id,2))
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetProperty(EFFECT_FLAG_DELAY)
e4:SetCode(EVENT_DESTROYED)
e4:SetCountLimit(1,id+o)
e4:SetCondition(s.tpcon)
e4:SetOperation(s.tpop)
c:RegisterEffect(e4)
end
function s.otfilter(c)
return c:IsType(TYPE_CONTINUOUS) and c:IsReleasable(REASON_SUMMON)
end
function s.ttcon(e,c,minc)
if c==nil then return true end
return minc<=3 and Duel.CheckTribute(c,3)
end
function s.ttop(e,tp,eg,ep,ev,re,r,rp,c)
local g=Duel.SelectTribute(tp,c,3,3)
c:SetMaterial(g)
Duel.Release(g,REASON_SUMMON+REASON_MATERIAL)
end
function s.setcon(e,c,minc)
if not c then return true end
return false
end
function s.negcon(e,tp,eg,ep,ev,re,r,rp)
local loc=Duel.GetChainInfo(ev,CHAININFO_TRIGGERING_LOCATION)
return ep~=tp and (LOCATION_HAND+LOCATION_ONFIELD)&loc~=0
and re:IsActiveType(TYPE_MONSTER) and Duel.IsChainDisablable(ev)
and e:GetHandler():IsSummonType(SUMMON_TYPE_ADVANCE)
end
function s.negtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0)
if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
end
function s.negop(e,tp,eg,ep,ev,re,r,rp)
if Duel.NegateActivation(ev) and re:GetHandler():IsRelateToChain(ev) then
Duel.Destroy(eg,REASON_EFFECT)
end
end
function s.tpcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return (c:IsReason(REASON_BATTLE) or (c:IsReason(REASON_EFFECT) and c:GetReasonPlayer()==1-tp and c:IsPreviousControler(tp)))
and c:IsPreviousLocation(LOCATION_MZONE) and c:IsSummonType(SUMMON_TYPE_ADVANCE)
end
-- guard for "next opponent turn" skips of Main 1
function s.turncon(e)
return Duel.GetTurnCount()~=e:GetLabel()
end
-- helper to schedule a one‑time skip effect
-- code: EFFECT_SKIP_M1 or EFFECT_SKIP_M2
-- next_turn: if true, skips on opponent’s *next* turn (via turncon);
-- if false, skips the upcoming phase *this* turn
function s.schedule_skip(c,tp,code,next_turn)
local phase=PHASE_MAIN1
if code==EFFECT_SKIP_M2 then
phase=PHASE_MAIN2
end
local e=Effect.CreateEffect(c)
e:SetType(EFFECT_TYPE_FIELD)
e:SetCode(code)
e:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e:SetTargetRange(0,1)
if next_turn then
e:SetLabel(Duel.GetTurnCount())
e:SetCondition(s.turncon)
-- covers end of this opp turn + end of next opp turn
e:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN,2)
else
-- reset as soon as that phase would start on their turn, this turn
e:SetReset(RESET_PHASE+phase+RESET_OPPO_TURN,1)
end
Duel.RegisterEffect(e,tp)
return e
end
function s.tpop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local op=1-tp
local ph=Duel.GetCurrentPhase()
local turn_player=Duel.GetTurnPlayer()
-- My turn → skip their NEXT Main 1 (on turn change)
if turn_player==tp then
s.schedule_skip(c,tp,EFFECT_SKIP_M1,true)
return
end
-- Opponent in Battle Phase → skip their upcoming Main 2
if Duel.IsBattlePhase() then
s.schedule_skip(c,tp,EFFECT_SKIP_M2,false)
return
end
-- Opponent in Main 1 →
-- a) schedule skip of *next* Main 1,
-- b) but pivot to skip M2 if they enter BP
if ph==PHASE_MAIN1 then
-- skip their *next* M1
local skip_m1=s.schedule_skip(c,tp,EFFECT_SKIP_M1,true)
-- b) watch for BP to cancel M1 skip & schedule M2 skip
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_PHASE+PHASE_BATTLE) -- PHASE_BATTLE is the end of BP
e2:SetCountLimit(1)
e2:SetLabelObject(skip_m1)
e2:SetOperation(function(ee,tp2,eg2,ep2,ev2,re2,rp2)
ee:GetLabelObject():Reset() -- cancel skip‑M1
s.schedule_skip(c,tp,EFFECT_SKIP_M2,false)
ee:Reset() -- destroy watcher
end)
-- expires at end of their turn if no BP
e2:SetReset(RESET_PHASE+PHASE_END,1)
Duel.RegisterEffect(e2,op)
return
end
-- Opponent in Main 2/EP → skip their *next* Main 1 (on their next turn)
if ph>=PHASE_MAIN2 then
s.schedule_skip(c,tp,EFFECT_SKIP_M1,true)
return
end
-- Opponent before Main 1 (Draw/Standby) → skip this turn’s Main 1
if ph<PHASE_MAIN1 then
s.schedule_skip(c,tp,EFFECT_SKIP_M1,false)
return
end
assert(false)
end
| 412 | 0.934311 | 1 | 0.934311 | game-dev | MEDIA | 0.969466 | game-dev | 0.97951 | 1 | 0.97951 |
H4PM/Elywing | 1,435 | src/pocketmine/entity/Wolf.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 iTX Technologies
* @link https://itxtech.org
*
*/
namespace pocketmine\entity;
use pocketmine\network\protocol\AddEntityPacket;
use pocketmine\Player;
class Wolf extends Animal{
const NETWORK_ID = 14;
public $width = 0.3;
public $length = 0.9;
public $height = 1.8;
public $dropExp = [1, 3];
public function getName(){
return "Wolf";
}
public function spawnTo(Player $player){
$pk = new AddEntityPacket();
$pk->eid = $this->getId();
$pk->type = Wolf::NETWORK_ID;
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->speedX = $this->motionX;
$pk->speedY = $this->motionY;
$pk->speedZ = $this->motionZ;
$pk->yaw = $this->yaw;
$pk->pitch = $this->pitch;
$pk->metadata = $this->dataProperties;
$player->dataPacket($pk);
parent::spawnTo($player);
}
} | 412 | 0.597994 | 1 | 0.597994 | game-dev | MEDIA | 0.644789 | game-dev | 0.71195 | 1 | 0.71195 |
OpenXRay/xray-16 | 51,257 | src/xrGame/ai/stalker/ai_stalker.cpp | ////////////////////////////////////////////////////////////////////////////
// Module : ai_stalker.cpp
// Created : 25.02.2003
// Modified : 25.02.2003
// Author : Dmitriy Iassenev
// Description : AI Behaviour for monster "Stalker"
////////////////////////////////////////////////////////////////////////////
#include "pch_script.h"
#include "ai_stalker.h"
#include "ai/ai_monsters_misc.h"
#include "Weapon.h"
#include "Hit.h"
#include "PHDestroyable.h"
#include "CharacterPhysicsSupport.h"
#include "script_entity_action.h"
#include "xrAICore/Navigation/game_level_cross_table.h"
#include "xrAICore/Navigation/game_graph.h"
#include "Inventory.h"
#include "Artefact.h"
#include "PHMovementControl.h"
#include "xrServerEntities/xrServer_Objects_ALife_Monsters.h"
#include "cover_evaluators.h"
#include "xrServer.h"
#include "xrEngine/xr_level_controller.h"
#include "Include/xrRender/Kinematics.h"
#include "xrServerEntities/character_info.h"
#include "Actor.h"
#include "relation_registry.h"
#include "stalker_animation_manager.h"
#include "stalker_planner.h"
#include "script_game_object.h"
#include "detail_path_manager.h"
#include "agent_manager.h"
#include "agent_corpse_manager.h"
#include "object_handler_planner.h"
#include "object_handler_space.h"
#include "memory_manager.h"
#include "sight_manager.h"
#include "xrAICore/Navigation/ai_object_location.h"
#include "xrAICore/Navigation/ai_object_location_impl.h"
#include "stalker_movement_manager_smart_cover.h"
#include "EntityCondition.h"
#include "xrScriptEngine/script_engine.hpp"
#include "ai_stalker_impl.h"
#include "sound_player.h"
#include "stalker_sound_data.h"
#include "stalker_sound_data_visitor.h"
#include "ai_stalker_space.h"
#include "mt_config.h"
#include "EffectorShot.h"
#include "visual_memory_manager.h"
#include "enemy_manager.h"
#include "xrServerEntities/alife_human_brain.h"
#include "xrEngine/profiler.h"
#include "BoneProtections.h"
#include "stalker_animation_names.h"
#include "stalker_decision_space.h"
#include "agent_member_manager.h"
#include "location_manager.h"
#include "smart_cover_animation_selector.h"
#include "smart_cover_animation_planner.h"
#include "smart_cover_planner_target_selector.h"
#ifdef DEBUG
#include "alife_simulator.h"
#include "alife_object_registry.h"
#include "Level.h"
#include "map_location.h"
#include "map_manager.h"
#endif // DEBUG
using namespace StalkerSpace;
extern int g_AI_inactive_time;
CAI_Stalker::CAI_Stalker()
: m_sniper_update_rate(false), m_sniper_fire_mode(false), m_take_items_enabled(true), m_death_sound_enabled(true)
{
m_sound_user_data_visitor = 0;
m_movement_manager = 0;
m_group_behaviour = true;
m_boneHitProtection = NULL;
m_power_fx_factor = flt_max;
m_wounded = false;
#ifdef DEBUG
m_debug_planner = 0;
m_dbg_hud_draw = false;
#endif // DEBUG
m_registered_in_combat_on_migration = false;
}
CAI_Stalker::~CAI_Stalker()
{
xr_delete(m_pPhysics_support);
xr_delete(m_animation_manager);
xr_delete(m_brain);
xr_delete(m_sight_manager);
xr_delete(m_weapon_shot_effector);
xr_delete(m_sound_user_data_visitor);
}
void CAI_Stalker::reinit()
{
CObjectHandler::reinit(this);
sight().reinit();
CCustomMonster::reinit();
animation().reinit();
// movement().reinit ();
//загрузка спецевической звуковой схемы для сталкера согласно m_SpecificCharacter
sound().sound_prefix(SpecificCharacter().sound_voice_prefix());
LoadSounds(*cNameSect());
m_pPhysics_support->in_Init();
m_best_item_to_kill = 0;
m_best_item_value = 0.f;
m_best_ammo = 0;
m_best_found_item_to_kill = 0;
m_best_found_ammo = 0;
m_item_actuality = false;
m_sell_info_actuality = false;
m_ce_close = xr_new<CCoverEvaluatorCloseToEnemy>(&movement().restrictions());
m_ce_far = xr_new<CCoverEvaluatorFarFromEnemy>(&movement().restrictions());
m_ce_best = xr_new<CCoverEvaluatorBest>(&movement().restrictions());
m_ce_angle = xr_new<CCoverEvaluatorAngle>(&movement().restrictions());
m_ce_safe = xr_new<CCoverEvaluatorSafe>(&movement().restrictions());
m_ce_ambush = xr_new<CCoverEvaluatorAmbush>(&movement().restrictions());
m_ce_close->set_inertia(3000);
m_ce_far->set_inertia(3000);
m_ce_best->set_inertia(1000);
m_ce_angle->set_inertia(5000);
m_ce_safe->set_inertia(1000);
m_ce_ambush->set_inertia(3000);
m_can_kill_enemy = false;
m_can_kill_member = false;
m_pick_distance = 0.f;
m_pick_frame_id = 0;
m_weapon_shot_random_seed = s32(Level().timeServer_Async());
m_best_cover = 0;
m_best_cover_actual = false;
m_best_cover_value = flt_max;
m_throw_actual = false;
m_computed_object_position = Fvector().set(flt_max, flt_max, flt_max);
m_computed_object_direction = Fvector().set(flt_max, flt_max, flt_max);
m_throw_target_position = Fvector().set(flt_max, flt_max, flt_max);
m_throw_ignore_object = 0;
m_throw_position = Fvector().set(flt_max, flt_max, flt_max);
m_throw_velocity = Fvector().set(flt_max, flt_max, flt_max);
m_throw_collide_position = Fvector().set(flt_max, flt_max, flt_max);
m_throw_enabled = false;
m_last_throw_time = 0;
m_can_throw_grenades = true;
m_throw_time_interval = 20000;
brain().CStalkerPlanner::m_storage.set_property(StalkerDecisionSpace::eWorldPropertyCriticallyWounded, false);
{
m_critical_wound_weights.clear();
// LPCSTR weights = pSettings->r_string(cNameSect(),"critical_wound_weights");
LPCSTR weights = SpecificCharacter().critical_wound_weights();
string16 temp;
for (int i = 0, n = _GetItemCount(weights); i < n; ++i)
m_critical_wound_weights.push_back((float)atof(_GetItem(weights, i, temp)));
}
m_update_rotation_on_frame = false;
}
void CAI_Stalker::LoadSounds(LPCSTR section)
{
LPCSTR head_bone_name = pSettings->r_string(section, "bone_head");
sound().add(pSettings->r_string(section, "sound_death"), 100, SOUND_TYPE_MONSTER_DYING, 0,
u32(eStalkerSoundMaskDie), eStalkerSoundDie, head_bone_name, xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_anomaly_death"), 100, SOUND_TYPE_MONSTER_DYING, 0,
u32(eStalkerSoundMaskDieInAnomaly), eStalkerSoundDieInAnomaly, head_bone_name, 0);
sound().add(pSettings->r_string(section, "sound_hit"), 100, SOUND_TYPE_MONSTER_INJURING, 1,
u32(eStalkerSoundMaskInjuring), eStalkerSoundInjuring, head_bone_name, xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_friendly_fire"), 100, SOUND_TYPE_MONSTER_INJURING, 1,
u32(eStalkerSoundMaskInjuringByFriend), eStalkerSoundInjuringByFriend, head_bone_name,
xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_panic_human"), 100, SOUND_TYPE_MONSTER_TALKING, 2,
u32(eStalkerSoundMaskPanicHuman), eStalkerSoundPanicHuman, head_bone_name, xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_panic_monster"), 100, SOUND_TYPE_MONSTER_TALKING, 2,
u32(eStalkerSoundMaskPanicMonster), eStalkerSoundPanicMonster, head_bone_name, xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_grenade_alarm"), 100, SOUND_TYPE_MONSTER_TALKING, 3,
u32(eStalkerSoundMaskGrenadeAlarm), eStalkerSoundGrenadeAlarm, head_bone_name, xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_friendly_grenade_alarm"), 100, SOUND_TYPE_MONSTER_TALKING, 3,
u32(eStalkerSoundMaskFriendlyGrenadeAlarm), eStalkerSoundFriendlyGrenadeAlarm, head_bone_name,
xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_tolls"), 100, SOUND_TYPE_MONSTER_TALKING, 4,
u32(eStalkerSoundMaskTolls), eStalkerSoundTolls, head_bone_name, xr_new<CStalkerSoundData>(this));
if (pSettings->line_exist(section, "sound_wounded"))
{
sound().add(pSettings->r_string(section, "sound_wounded"), 100, SOUND_TYPE_MONSTER_TALKING, 4,
u32(eStalkerSoundMaskWounded), eStalkerSoundWounded, head_bone_name, xr_new<CStalkerSoundData>(this));
}
else
{
sound().add(pSettings->r_string(section, "sound_tolls"), 100, SOUND_TYPE_MONSTER_TALKING, 4,
u32(eStalkerSoundMaskWounded), eStalkerSoundWounded, head_bone_name, xr_new<CStalkerSoundData>(this));
}
sound().add(pSettings->r_string(section, "sound_alarm"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskAlarm), eStalkerSoundAlarm, head_bone_name, xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_attack_no_allies"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskAttackNoAllies), eStalkerSoundAttackNoAllies, head_bone_name, xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_attack_allies_single_enemy"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskAttackAlliesSingleEnemy), eStalkerSoundAttackAlliesSingleEnemy, head_bone_name,
xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_attack_allies_several_enemies"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskAttackAlliesSeveralEnemies), eStalkerSoundAttackAlliesSeveralEnemies, head_bone_name,
xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_backup"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskBackup), eStalkerSoundBackup, head_bone_name, xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_detour"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskDetour), eStalkerSoundDetour, head_bone_name, xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_search1_no_allies"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskSearch1NoAllies), eStalkerSoundSearch1NoAllies, head_bone_name,
xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_search1_with_allies"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskSearch1WithAllies), eStalkerSoundSearch1WithAllies, head_bone_name,
xr_new<CStalkerSoundData>(this));
if (pSettings->line_exist(section, "sound_enemy_lost_no_allies"))
{
sound().add(pSettings->r_string(section, "sound_enemy_lost_no_allies"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskEnemyLostNoAllies), eStalkerSoundEnemyLostNoAllies, head_bone_name,
xr_new<CStalkerSoundData>(this));
}
else
{
sound().add(pSettings->r_string(section, "sound_search1_no_allies"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskEnemyLostNoAllies), eStalkerSoundEnemyLostNoAllies, head_bone_name,
xr_new<CStalkerSoundData>(this));
}
if (pSettings->line_exist(section, "sound_enemy_lost_with_allies"))
{
sound().add(pSettings->r_string(section, "sound_enemy_lost_with_allies"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskEnemyLostWithAllies), eStalkerSoundEnemyLostWithAllies, head_bone_name,
xr_new<CStalkerSoundData>(this));
}
else
{
sound().add(pSettings->r_string(section, "sound_search1_with_allies"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskEnemyLostWithAllies), eStalkerSoundEnemyLostWithAllies, head_bone_name,
xr_new<CStalkerSoundData>(this));
}
sound().add(pSettings->r_string(section, "sound_humming"), 100, SOUND_TYPE_MONSTER_TALKING, 6,
u32(eStalkerSoundMaskHumming), eStalkerSoundHumming, head_bone_name, 0);
sound().add(pSettings->r_string(section, "sound_need_backup"), 100, SOUND_TYPE_MONSTER_TALKING, 4,
u32(eStalkerSoundMaskNeedBackup), eStalkerSoundNeedBackup, head_bone_name, xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_running_in_danger"), 100, SOUND_TYPE_MONSTER_TALKING, 6,
u32(eStalkerSoundMaskMovingInDanger), eStalkerSoundRunningInDanger, head_bone_name,
xr_new<CStalkerSoundData>(this));
// sound().add (pSettings->r_string(section,"sound_walking_in_danger"), 100,
// SOUND_TYPE_MONSTER_TALKING, 6, u32(eStalkerSoundMaskMovingInDanger), eStalkerSoundWalkingInDanger,
// head_bone_name, new CStalkerSoundData(this));
sound().add(pSettings->r_string(section, "sound_kill_wounded"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskKillWounded), eStalkerSoundKillWounded, head_bone_name, xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_enemy_critically_wounded"), 100, SOUND_TYPE_MONSTER_TALKING, 4,
u32(eStalkerSoundMaskEnemyCriticallyWounded), eStalkerSoundEnemyCriticallyWounded, head_bone_name,
xr_new<CStalkerSoundData>(this));
sound().add(pSettings->r_string(section, "sound_enemy_killed_or_wounded"), 100, SOUND_TYPE_MONSTER_TALKING, 4,
u32(eStalkerSoundMaskEnemyKilledOrWounded), eStalkerSoundEnemyKilledOrWounded, head_bone_name,
xr_new<CStalkerSoundData>(this));
if (pSettings->line_exist(section, "sound_throw_grenade"))
{
sound().add(pSettings->r_string(section, "sound_throw_grenade"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskKillWounded), eStalkerSoundThrowGrenade, head_bone_name, xr_new<CStalkerSoundData>(this));
}
else
{
sound().add(pSettings->r_string(section, "sound_grenade_alarm"), 100, SOUND_TYPE_MONSTER_TALKING, 5,
u32(eStalkerSoundMaskKillWounded), eStalkerSoundThrowGrenade, head_bone_name, xr_new<CStalkerSoundData>(this));
}
}
void CAI_Stalker::reload(LPCSTR section)
{
brain().setup(this);
CCustomMonster::reload(section);
CStepManager::reload(section);
CObjectHandler::reload(section);
sight().reload(section);
movement().reload(section);
m_disp_walk_stand = pSettings->r_float(section, "disp_walk_stand");
m_disp_walk_crouch = pSettings->r_float(section, "disp_walk_crouch");
m_disp_run_stand = pSettings->r_float(section, "disp_run_stand");
m_disp_run_crouch = pSettings->r_float(section, "disp_run_crouch");
m_disp_stand_stand = pSettings->r_float(section, "disp_stand_stand");
m_disp_stand_crouch = pSettings->r_float(section, "disp_stand_crouch");
m_disp_stand_stand_zoom = pSettings->r_float(section, "disp_stand_stand_zoom");
m_disp_stand_crouch_zoom = pSettings->r_float(section, "disp_stand_crouch_zoom");
m_can_select_weapon = true;
LPCSTR queue_sect = READ_IF_EXISTS(pSettings, r_string, *cNameSect(), "fire_queue_section", nullptr);
if (!queue_sect || xr_strcmp(queue_sect, "") != 0 || !pSettings->section_exist(queue_sect))
{
queue_sect = *cNameSect();
}
const auto tryToRead = [&](pcstr lineToRead, u32 defaultValue) -> u32
{
const u32 value = pSettings->read_if_exists<u32>(queue_sect, lineToRead, u32(-1));
if (value != u32(-1))
return value;
return defaultValue;
};
{
m_pstl_min_queue_size_far = tryToRead("pstl_min_queue_size_far", 1);
m_pstl_max_queue_size_far = tryToRead("pstl_max_queue_size_far", 1);
m_pstl_min_queue_interval_far = tryToRead("pstl_min_queue_interval_far", 1000);
m_pstl_max_queue_interval_far = tryToRead("pstl_max_queue_interval_far", 1250);
m_pstl_min_queue_size_medium = tryToRead("pstl_min_queue_size_medium", 2);
m_pstl_max_queue_size_medium = tryToRead("pstl_max_queue_size_medium", 4);
m_pstl_min_queue_interval_medium = tryToRead("pstl_min_queue_interval_medium", 750);
m_pstl_max_queue_interval_medium = tryToRead("pstl_max_queue_interval_medium", 1000);
m_pstl_min_queue_size_close = tryToRead("pstl_min_queue_size_close", 3);
m_pstl_max_queue_size_close = tryToRead("pstl_max_queue_size_close", 5);
m_pstl_min_queue_interval_close = tryToRead("pstl_min_queue_interval_close", 500);
m_pstl_max_queue_interval_close = tryToRead("pstl_max_queue_interval_close", 750);
}
{
m_shtg_min_queue_size_far = tryToRead("shtg_min_queue_size_far", 1);
m_shtg_max_queue_size_far = tryToRead("shtg_max_queue_size_far", 1);
m_shtg_min_queue_interval_far = tryToRead("shtg_min_queue_interval_far", 1250);
m_shtg_max_queue_interval_far = tryToRead("shtg_max_queue_interval_far", 1500);
m_shtg_min_queue_size_medium = tryToRead("shtg_min_queue_size_medium", 1);
m_shtg_max_queue_size_medium = tryToRead("shtg_max_queue_size_medium", 1);
m_shtg_min_queue_interval_medium = tryToRead("shtg_min_queue_interval_medium", 750);
m_shtg_max_queue_interval_medium = tryToRead("shtg_max_queue_interval_medium", 1250);
m_shtg_min_queue_size_close = tryToRead("shtg_min_queue_size_close", 1);
m_shtg_max_queue_size_close = tryToRead("shtg_max_queue_size_close", 1);
m_shtg_min_queue_interval_close = tryToRead("shtg_min_queue_interval_close", 500);
m_shtg_max_queue_interval_close = tryToRead("shtg_max_queue_interval_close", 1000);
}
{
m_snp_min_queue_size_far = tryToRead("snp_min_queue_size_far", 1);
m_snp_max_queue_size_far = tryToRead("snp_max_queue_size_far", 1);
m_snp_min_queue_interval_far = tryToRead("snp_min_queue_interval_far", 3000);
m_snp_max_queue_interval_far = tryToRead("snp_max_queue_interval_far", 4000);
m_snp_min_queue_size_medium = tryToRead("snp_min_queue_size_medium", 1);
m_snp_max_queue_size_medium = tryToRead("snp_max_queue_size_medium", 1);
m_snp_min_queue_interval_medium = tryToRead("snp_min_queue_interval_medium", 3000);
m_snp_max_queue_interval_medium = tryToRead("snp_max_queue_interval_medium", 4000);
m_snp_min_queue_size_close = tryToRead("snp_min_queue_size_close", 1);
m_snp_max_queue_size_close = tryToRead("snp_max_queue_size_close", 1);
m_snp_min_queue_interval_close = tryToRead("snp_min_queue_interval_close", 3000);
m_snp_max_queue_interval_close = tryToRead("snp_max_queue_interval_close", 4000);
}
{
m_mchg_min_queue_size_far = tryToRead("mchg_min_queue_size_far", 1);
m_mchg_max_queue_size_far = tryToRead("mchg_max_queue_size_far", 6);
m_mchg_min_queue_interval_far = tryToRead("mchg_min_queue_interval_far", 500);
m_mchg_max_queue_interval_far = tryToRead("mchg_max_queue_interval_far", 1000);
m_mchg_min_queue_size_medium = tryToRead("mchg_min_queue_size_medium", 4);
m_mchg_max_queue_size_medium = tryToRead("mchg_max_queue_size_medium", 6);
m_mchg_min_queue_interval_medium = tryToRead("mchg_min_queue_interval_medium", 500);
m_mchg_max_queue_interval_medium = tryToRead("mchg_max_queue_interval_medium", 750);
m_mchg_min_queue_size_close = tryToRead("mchg_min_queue_size_close", 4);
m_mchg_max_queue_size_close = tryToRead("mchg_max_queue_size_close", 10);
m_mchg_min_queue_interval_close = tryToRead("mchg_min_queue_interval_close", 300);
m_mchg_max_queue_interval_close = tryToRead("mchg_max_queue_interval_close", 500);
}
{
const u32 min_queue_size_far = pSettings->read_if_exists<u32>(queue_sect, "weapon_min_queue_size_far", 1);
const u32 max_queue_size_far = pSettings->read_if_exists<u32>(queue_sect, "weapon_max_queue_size_far", 6);
const u32 min_queue_interval_far = pSettings->read_if_exists<u32>(queue_sect, "weapon_min_queue_interval_far", 500);
const u32 max_queue_interval_far = pSettings->read_if_exists<u32>(queue_sect, "weapon_max_queue_interval_far", 1000);
const u32 min_queue_size_medium = pSettings->read_if_exists<u32>(queue_sect, "weapon_min_queue_size_medium", 4);
const u32 max_queue_size_medium = pSettings->read_if_exists<u32>(queue_sect, "weapon_max_queue_size_medium", 6);
const u32 min_queue_interval_medium = pSettings->read_if_exists<u32>(queue_sect, "weapon_min_queue_interval_medium", 500);
const u32 max_queue_interval_medium = pSettings->read_if_exists<u32>(queue_sect, "weapon_max_queue_interval_medium", 750);
const u32 min_queue_size_close = pSettings->read_if_exists<u32>(queue_sect, "weapon_min_queue_size_close", 4);
const u32 max_queue_size_close = pSettings->read_if_exists<u32>(queue_sect, "weapon_max_queue_size_close", 10);
const u32 min_queue_interval_close = pSettings->read_if_exists<u32>(queue_sect, "weapon_min_queue_interval_close", 300);
const u32 max_queue_interval_close = pSettings->read_if_exists<u32>(queue_sect, "weapon_max_queue_interval_close", 500);
m_auto_min_queue_size_far = tryToRead("auto_min_queue_size_far", min_queue_size_far);
m_auto_max_queue_size_far = tryToRead("auto_max_queue_size_far", max_queue_size_far);
m_auto_min_queue_interval_far = tryToRead("auto_min_queue_interval_far", min_queue_interval_far);
m_auto_max_queue_interval_far = tryToRead("auto_max_queue_interval_far", max_queue_interval_far);
m_auto_min_queue_size_medium = tryToRead("auto_min_queue_size_medium", min_queue_size_medium);
m_auto_max_queue_size_medium = tryToRead("auto_max_queue_size_medium", max_queue_size_medium);
m_auto_min_queue_interval_medium = tryToRead("auto_min_queue_interval_medium", min_queue_interval_medium);
m_auto_max_queue_interval_medium = tryToRead("auto_max_queue_interval_medium", max_queue_interval_medium);
m_auto_min_queue_size_close = tryToRead("auto_min_queue_size_close", min_queue_size_close);
m_auto_max_queue_size_close = tryToRead("auto_max_queue_size_close", max_queue_size_close);
m_auto_min_queue_interval_close = tryToRead("auto_min_queue_interval_close", min_queue_interval_close);
m_auto_max_queue_interval_close = tryToRead("auto_max_queue_interval_close", max_queue_interval_close);
}
{
// m_pstl_queue_fire_dist_close = READ_IF_EXISTS(pSettings, r_float, queue_sect, "pstl_queue_fire_dist_close", 15.0f);
m_pstl_queue_fire_dist_med = READ_IF_EXISTS(pSettings, r_float, queue_sect, "pstl_queue_fire_dist_med", 15.0f);
m_pstl_queue_fire_dist_far = READ_IF_EXISTS(pSettings, r_float, queue_sect, "pstl_queue_fire_dist_far", 30.0f);
}
{
// m_shtg_queue_fire_dist_close = READ_IF_EXISTS(pSettings, r_float, queue_sect, "shtg_queue_fire_dist_close", 15.0f);
m_shtg_queue_fire_dist_med = READ_IF_EXISTS(pSettings, r_float, queue_sect, "shtg_queue_fire_dist_med", 15.0f);
m_shtg_queue_fire_dist_far = READ_IF_EXISTS(pSettings, r_float, queue_sect, "shtg_queue_fire_dist_far", 30.0f);
}
{
// m_snp_queue_fire_dist_close = READ_IF_EXISTS(pSettings, r_float, queue_sect, "snp_queue_fire_dist_close", 15.0f);
m_snp_queue_fire_dist_med = READ_IF_EXISTS(pSettings, r_float, queue_sect, "snp_queue_fire_dist_med", 15.0f);
m_snp_queue_fire_dist_far = READ_IF_EXISTS(pSettings, r_float, queue_sect, "snp_queue_fire_dist_far", 30.0f);
}
{
// m_mchg_queue_fire_dist_close = READ_IF_EXISTS(pSettings, r_float, queue_sect, "mchg_queue_fire_dist_close", 15.0f);
m_mchg_queue_fire_dist_med = READ_IF_EXISTS(pSettings, r_float, queue_sect, "mchg_queue_fire_dist_med", 15.0f);
m_mchg_queue_fire_dist_far = READ_IF_EXISTS(pSettings, r_float, queue_sect, "mchg_queue_fire_dist_far", 30.0f);
}
{
// m_auto_queue_fire_dist_close = READ_IF_EXISTS(pSettings,r_float,queue_sect,"auto_queue_fire_dist_close", 15.0f);
m_auto_queue_fire_dist_med = READ_IF_EXISTS(pSettings, r_float, queue_sect, "auto_queue_fire_dist_med", 15.0f);
m_auto_queue_fire_dist_far = READ_IF_EXISTS(pSettings, r_float, queue_sect, "auto_queue_fire_dist_far", 30.0f);
}
m_power_fx_factor = pSettings->r_float(section, "power_fx_factor");
}
void CAI_Stalker::Die(IGameObject* who)
{
movement().on_death();
notify_on_wounded_or_killed(who);
SelectAnimation(XFORM().k, movement().detail().direction(), movement().speed());
if (m_death_sound_enabled)
{
sound().set_sound_mask((u32)eStalkerSoundMaskDie);
if (is_special_killer(who))
sound().play(eStalkerSoundDieInAnomaly);
else
sound().play(eStalkerSoundDie);
}
m_hammer_is_clutched = m_clutched_hammer_enabled &&
!CObjectHandler::planner().m_storage.property(ObjectHandlerSpace::eWorldPropertyStrapped) &&
!::Random.randI(0, 2);
inherited::Die(who);
//запретить использование слотов в инвенторе
inventory().SetSlotsUseful(false);
if (inventory().GetActiveSlot() == NO_ACTIVE_SLOT)
return;
CInventoryItem* active_item = inventory().ActiveItem();
if (!active_item)
return;
CWeapon* weapon = smart_cast<CWeapon*>(active_item);
if (!weapon)
return;
{
TIItemContainer::iterator I = inventory().m_all.begin();
TIItemContainer::iterator E = inventory().m_all.end();
for (; I != E; ++I)
{
if (std::find(weapon->m_ammoTypes.begin(), weapon->m_ammoTypes.end(), (*I)->object().cNameSect()) ==
weapon->m_ammoTypes.end())
continue;
NET_Packet packet;
u_EventGen(packet, GE_DESTROY, (*I)->object().ID());
u_EventSend(packet);
}
}
}
void CAI_Stalker::Load(LPCSTR section)
{
CCustomMonster::Load(section);
CObjectHandler::Load(section);
sight().Load(section);
// skeleton physics
m_pPhysics_support->in_Load(section);
m_can_select_items = !!pSettings->r_bool(section, "can_select_items");
}
bool CAI_Stalker::net_Spawn(CSE_Abstract* DC)
{
CSE_Abstract* e = (CSE_Abstract*)(DC);
CSE_ALifeHumanStalker* tpHuman = smart_cast<CSE_ALifeHumanStalker*>(e);
R_ASSERT(tpHuman);
// static bool first_time = true;
// if ( first_time ) {
// tpHuman->o_Position.z -= 3.f;
// first_time = false;
//}
m_group_behaviour = !!tpHuman->m_flags.test(CSE_ALifeObject::flGroupBehaviour);
if (!CObjectHandler::net_Spawn(DC) || !inherited::net_Spawn(DC))
return (false);
set_money(tpHuman->m_dwMoney, false);
animation().reload();
movement().m_head.current.yaw = movement().m_head.target.yaw = movement().m_body.current.yaw =
movement().m_body.target.yaw = angle_normalize_signed(-tpHuman->o_torso.yaw);
movement().m_body.current.pitch = movement().m_body.target.pitch = 0;
if (ai().game_graph().valid_vertex_id(tpHuman->m_tGraphID))
ai_location().game_vertex(tpHuman->m_tGraphID);
if (ai().game_graph().valid_vertex_id(tpHuman->m_tNextGraphID) &&
movement().restrictions().accessible(ai().game_graph().vertex(tpHuman->m_tNextGraphID)->level_point()))
movement().set_game_dest_vertex(tpHuman->m_tNextGraphID);
R_ASSERT2(ai().get_game_graph() && ai().get_level_graph() && ai().get_cross_table() &&
(ai().level_graph().level_id() != u32(-1)),
"There is no AI-Map, level graph, cross table, or graph is not compiled into the game graph!");
setEnabled(TRUE);
if (!Level().CurrentViewEntity())
Level().SetEntity(this);
if (!g_Alive())
sound().set_sound_mask(u32(eStalkerSoundMaskDie));
//загрузить иммунитеты из модельки сталкера
IKinematics* pKinematics = smart_cast<IKinematics*>(Visual());
VERIFY(pKinematics);
CInifile* ini = pKinematics->LL_UserData();
if (ini)
{
if (ini->section_exist("immunities"))
{
LPCSTR imm_sect = ini->r_string("immunities", "immunities_sect");
conditions().LoadImmunities(imm_sect, pSettings);
}
if (ini->line_exist("bone_protection", "bones_protection_sect"))
{
m_boneHitProtection = xr_new<SBoneProtections>();
m_boneHitProtection->reload(ini->r_string("bone_protection", "bones_protection_sect"), pKinematics);
}
}
//вычислить иммунета в зависимости от ранга
static float novice_rank_immunity = pSettings->r_float("ranks_properties", "immunities_novice_k");
static float expirienced_rank_immunity = pSettings->r_float("ranks_properties", "immunities_experienced_k");
static float novice_rank_visibility = pSettings->r_float("ranks_properties", "visibility_novice_k");
static float expirienced_rank_visibility = pSettings->r_float("ranks_properties", "visibility_experienced_k");
static float novice_rank_dispersion = pSettings->r_float("ranks_properties", "dispersion_novice_k");
static float expirienced_rank_dispersion = pSettings->r_float("ranks_properties", "dispersion_experienced_k");
CHARACTER_RANK_VALUE rank = Rank();
clamp(rank, 0, 100);
float rank_k = float(rank) / 100.f;
m_fRankImmunity = novice_rank_immunity + (expirienced_rank_immunity - novice_rank_immunity) * rank_k;
m_fRankVisibility = novice_rank_visibility + (expirienced_rank_visibility - novice_rank_visibility) * rank_k;
m_fRankDisperison =
expirienced_rank_dispersion + (novice_rank_dispersion - expirienced_rank_dispersion) * (1 - rank_k);
if (!fis_zero(SpecificCharacter().panic_threshold()))
m_panic_threshold = SpecificCharacter().panic_threshold();
sight().setup(CSightAction(SightManager::eSightTypeCurrentDirection));
#ifdef _DEBUG
if (ai().get_alife() && !Level().MapManager().HasMapLocation("debug_stalker", ID()))
{
CMapLocation* map_location = Level().MapManager().AddMapLocation("debug_stalker", ID());
map_location->SetHint(cName());
}
#endif // _DEBUG
if (SpecificCharacter().terrain_sect().size())
{
movement().locations().Load(*SpecificCharacter().terrain_sect());
}
sight().update();
Exec_Look(.001f);
m_pPhysics_support->in_NetSpawn(e);
return (true);
}
void CAI_Stalker::net_Destroy()
{
inherited::net_Destroy();
CInventoryOwner::net_Destroy();
m_pPhysics_support->in_NetDestroy();
// XXX: task scheduler
//TaskScheduler->RemoveTask({ this, &CAI_Stalker::update_object_handler });
Device.remove_from_seq_parallel(fastdelegate::FastDelegate0<>(this, &CAI_Stalker::update_object_handler));
#ifdef DEBUG
fastdelegate::FastDelegate0<> f = fastdelegate::FastDelegate0<>(this, &CAI_Stalker::update_object_handler);
xr_vector<fastdelegate::FastDelegate0<>>::const_iterator I;
I = std::find(Device.seqParallel.begin(), Device.seqParallel.end(), f);
VERIFY(I == Device.seqParallel.end());
#endif
xr_delete(m_ce_close);
xr_delete(m_ce_far);
xr_delete(m_ce_best);
xr_delete(m_ce_angle);
xr_delete(m_ce_safe);
xr_delete(m_ce_ambush);
xr_delete(m_boneHitProtection);
}
void CAI_Stalker::net_Save(NET_Packet& P)
{
inherited::net_Save(P);
m_pPhysics_support->in_NetSave(P);
}
bool CAI_Stalker::net_SaveRelevant() { return (inherited::net_SaveRelevant() || (PPhysicsShell() != NULL)); }
void CAI_Stalker::net_Export(NET_Packet& P)
{
R_ASSERT(Local());
// export last known packet
R_ASSERT(!NET.empty());
net_update& N = NET.back();
// P.w_float (inventory().TotalWeight());
// P.w_u32 (m_dwMoney);
P.w_float(GetfHealth());
P.w_u32(N.dwTimeStamp);
P.w_u8(0);
P.w_vec3(N.p_pos);
P.w_float /*w_angle8*/ (N.o_model);
P.w_float /*w_angle8*/ (N.o_torso.yaw);
P.w_float /*w_angle8*/ (N.o_torso.pitch);
P.w_float /*w_angle8*/ (N.o_torso.roll);
P.w_u8(u8(g_Team()));
P.w_u8(u8(g_Squad()));
P.w_u8(u8(g_Group()));
float f1 = 0;
GameGraph::_GRAPH_ID l_game_vertex_id = ai_location().game_vertex_id();
P.w(&l_game_vertex_id, sizeof(l_game_vertex_id));
P.w(&l_game_vertex_id, sizeof(l_game_vertex_id));
// P.w (&f1, sizeof(f1));
// P.w (&f1, sizeof(f1));
if (ai().game_graph().valid_vertex_id(l_game_vertex_id))
{
f1 = Position().distance_to(ai().game_graph().vertex(l_game_vertex_id)->level_point());
P.w(&f1, sizeof(f1));
f1 = Position().distance_to(ai().game_graph().vertex(l_game_vertex_id)->level_point());
P.w(&f1, sizeof(f1));
}
else
{
P.w(&f1, sizeof(f1));
P.w(&f1, sizeof(f1));
}
P.w_stringZ(m_sStartDialog);
}
void CAI_Stalker::net_Import(NET_Packet& P)
{
R_ASSERT(Remote());
net_update N;
u8 flags;
P.r_float();
set_money(P.r_u32(), false);
float health;
P.r_float(health);
SetfHealth(health);
// fEntityHealth = health;
P.r_u32(N.dwTimeStamp);
P.r_u8(flags);
P.r_vec3(N.p_pos);
P.r_float /*r_angle8*/ (N.o_model);
P.r_float /*r_angle8*/ (N.o_torso.yaw);
P.r_float /*r_angle8*/ (N.o_torso.pitch);
P.r_float /*r_angle8*/ (N.o_torso.roll);
id_Team = P.r_u8();
id_Squad = P.r_u8();
id_Group = P.r_u8();
GameGraph::_GRAPH_ID graph_vertex_id = movement().game_dest_vertex_id();
P.r(&graph_vertex_id, sizeof(GameGraph::_GRAPH_ID));
graph_vertex_id = ai_location().game_vertex_id();
P.r(&graph_vertex_id, sizeof(GameGraph::_GRAPH_ID));
if (NET.empty() || (NET.back().dwTimeStamp < N.dwTimeStamp))
{
NET.push_back(N);
NET_WasInterpolating = TRUE;
}
P.r_float();
P.r_float();
P.r_stringZ(m_sStartDialog);
setVisible(TRUE);
setEnabled(TRUE);
}
void CAI_Stalker::update_object_handler()
{
if (!g_Alive())
return;
try
{
try
{
CObjectHandler::update();
}
#if defined(DEBUG) && !defined(LUABIND_NO_EXCEPTIONS)
catch (const luabind::cast_failed& message)
{
Msg("! Expression \"%s\" from luabind::object to %s", message.what(), message.info().name());
throw;
}
#endif
catch (const std::exception& message)
{
Msg("! Expression \"%s\"", message.what());
throw;
}
catch (...)
{
throw;
}
}
catch (...)
{
CObjectHandler::set_goal(eObjectActionIdle);
CObjectHandler::update();
}
}
bool CAI_Stalker::mt_object_handler_update_allowed() const
{
return m_client_updated &&
(g_pGameLevel->WorldRendered() || g_pGamePersistent->IsMainMenuActive())
#ifdef DEBUG
&& !ShouldProcessOnRender()
#endif
;
}
void CAI_Stalker::create_anim_mov_ctrl(CBlend* b, Fmatrix* start_pose, bool local_animation)
{
inherited::create_anim_mov_ctrl(b, start_pose, local_animation);
}
void CAI_Stalker::destroy_anim_mov_ctrl()
{
inherited::destroy_anim_mov_ctrl();
if (!g_Alive())
return;
if (getDestroy())
return;
movement().m_head.current.yaw = movement().m_body.current.yaw;
movement().m_head.current.pitch = movement().m_body.current.pitch;
movement().m_head.target.yaw = movement().m_body.current.yaw;
movement().m_head.target.pitch = movement().m_body.current.pitch;
movement().cleanup_after_animation_selector();
movement().update(0);
}
void CAI_Stalker::UpdateCL()
{
START_PROFILE("stalker")
START_PROFILE("stalker/client_update")
VERIFY2(PPhysicsShell() || getEnabled(), *cName());
if (g_Alive())
{
if (g_mt_config.test(mtObjectHandler) && CObjectHandler::planner().initialized())
{
// XXX: task scheduler
//TaskScheduler->AddTask("CAI_Stalker::update_object_handler",
// { this, &CAI_Stalker::update_object_handler },
// { this, &CAI_Stalker::mt_object_handler_update_allowed });
#ifdef DEBUG
fastdelegate::FastDelegate0<> f = fastdelegate::FastDelegate0<>(this, &CAI_Stalker::update_object_handler);
xr_vector<fastdelegate::FastDelegate0<>>::const_iterator I;
I = std::find(Device.seqParallel.begin(), Device.seqParallel.end(), f);
VERIFY(I == Device.seqParallel.end());
#endif
Device.seqParallel.push_back(fastdelegate::FastDelegate0<>(this, &CAI_Stalker::update_object_handler));
}
else
{
START_PROFILE("stalker/client_update/object_handler")
update_object_handler();
STOP_PROFILE
}
if ((movement().speed(character_physics_support()->movement()) > EPS_L) &&
(eMovementTypeStand != movement().movement_type()) && (eMentalStateDanger == movement().mental_state()))
{
if ((eBodyStateStand == movement().body_state()) && (eMovementTypeRun == movement().movement_type()))
{
sound().play(eStalkerSoundRunningInDanger);
}
else
{
// sound().play (eStalkerSoundWalkingInDanger);
}
}
}
START_PROFILE("stalker/client_update/inherited")
inherited::UpdateCL();
STOP_PROFILE
START_PROFILE("stalker/client_update/physics")
m_pPhysics_support->in_UpdateCL();
STOP_PROFILE
if (g_Alive())
{
START_PROFILE("stalker/client_update/sight_manager")
VERIFY(!m_pPhysicsShell);
try
{
sight().update();
}
catch (...)
{
sight().setup(CSightAction(SightManager::eSightTypeCurrentDirection));
sight().update();
}
Exec_Look(client_update_fdelta());
STOP_PROFILE
START_PROFILE("stalker/client_update/step_manager")
CStepManager::update(false);
STOP_PROFILE
START_PROFILE("stalker/client_update/weapon_shot_effector")
if (weapon_shot_effector().IsActive())
weapon_shot_effector().Update();
STOP_PROFILE
}
#ifdef DEBUG
debug_text();
#endif
STOP_PROFILE
STOP_PROFILE
}
void CAI_Stalker::PHHit(SHit& H) { m_pPhysics_support->in_Hit(H, false); }
CPHDestroyable* CAI_Stalker::ph_destroyable() { return smart_cast<CPHDestroyable*>(character_physics_support()); }
#include "enemy_manager.h"
void CAI_Stalker::shedule_Update(u32 DT)
{
START_PROFILE("stalker")
START_PROFILE("stalker/schedule_update")
VERIFY2(getEnabled() || PPhysicsShell(), *cName());
if (!CObjectHandler::planner().initialized())
{
START_PROFILE("stalker/client_update/object_handler")
update_object_handler();
STOP_PROFILE
}
// if (Position().distance_to(Level().CurrentEntity()->Position()) <= 50.f)
// Msg ("[%6d][SH][%s]",Device.dwTimeGlobal,*cName());
// Queue shrink
VERIFY(_valid(Position()));
u32 dwTimeCL = Level().timeServer() - NET_Latency;
VERIFY(!NET.empty());
while ((NET.size() > 2) && (NET[1].dwTimeStamp < dwTimeCL))
NET.pop_front();
Fvector vNewPosition = Position();
VERIFY(_valid(Position()));
// *** general stuff
float dt = float(DT) / 1000.f;
if (g_Alive())
{
animation().play_delayed_callbacks();
#ifndef USE_SCHEDULER_IN_AGENT_MANAGER
agent_manager().update();
#endif // USE_SCHEDULER_IN_AGENT_MANAGER
// bool check = !!memory().enemy().selected();
#if 0 // def DEBUG
memory().visual().check_visibles();
#endif
if (false && g_mt_config.test(mtAiVision))
Device.seqParallel.push_back(fastdelegate::FastDelegate0<>(this, &CCustomMonster::Exec_Visibility));
else
{
START_PROFILE("stalker/schedule_update/vision")
Exec_Visibility();
STOP_PROFILE
}
START_PROFILE("stalker/schedule_update/memory")
START_PROFILE("stalker/schedule_update/memory/process")
process_enemies();
STOP_PROFILE
START_PROFILE("stalker/schedule_update/memory/update")
memory().update(dt);
STOP_PROFILE
STOP_PROFILE
}
START_PROFILE("stalker/schedule_update/inherited")
CEntityAlive::shedule_Update(DT);
STOP_PROFILE
if (Remote())
{
}
else
{
// here is monster AI call
VERIFY(_valid(Position()));
m_fTimeUpdateDelta = dt;
Level().AIStats.Think.Begin();
if (GetScriptControl())
ProcessScripts();
else
#ifdef DEBUG
if (Device.dwFrame > (spawn_time() + g_AI_inactive_time))
#endif
Think();
m_dwLastUpdateTime = Device.dwTimeGlobal;
Level().AIStats.Think.End();
VERIFY(_valid(Position()));
// Look and action streams
float temp = conditions().health();
if (temp > 0)
{
START_PROFILE("stalker/schedule_update/feel_touch")
Fvector C;
float R;
Center(C);
R = Radius();
feel_touch_update(C, R);
STOP_PROFILE
START_PROFILE("stalker/schedule_update/net_update")
net_update uNext;
uNext.dwTimeStamp = Level().timeServer();
uNext.o_model = movement().m_body.current.yaw;
uNext.o_torso = movement().m_head.current;
uNext.p_pos = vNewPosition;
uNext.fHealth = GetfHealth();
NET.push_back(uNext);
STOP_PROFILE
}
else
{
START_PROFILE("stalker/schedule_update/net_update")
net_update uNext;
uNext.dwTimeStamp = Level().timeServer();
uNext.o_model = movement().m_body.current.yaw;
uNext.o_torso = movement().m_head.current;
uNext.p_pos = vNewPosition;
uNext.fHealth = GetfHealth();
NET.push_back(uNext);
STOP_PROFILE
}
}
VERIFY(_valid(Position()));
START_PROFILE("stalker/schedule_update/inventory_owner")
UpdateInventoryOwner(DT);
STOP_PROFILE
//#ifdef DEBUG
// if (psAI_Flags.test(aiALife)) {
// smart_cast<CSE_ALifeHumanStalker*>(ai().alife().objects().object(ID()))->check_inventory_consistency();
// }
//#endif
START_PROFILE("stalker/schedule_update/physics")
VERIFY(_valid(Position()));
m_pPhysics_support->in_shedule_Update(DT);
VERIFY(_valid(Position()));
STOP_PROFILE
STOP_PROFILE
STOP_PROFILE
}
float CAI_Stalker::Radius() const
{
float R = inherited::Radius();
CWeapon* W = smart_cast<CWeapon*>(inventory().ActiveItem());
if (W)
R += W->Radius();
return R;
}
void CAI_Stalker::spawn_supplies()
{
inherited::spawn_supplies();
CObjectHandler::spawn_supplies();
}
void CAI_Stalker::Think()
{
START_PROFILE("stalker/schedule_update/think")
u32 update_delta = Device.dwTimeGlobal - m_dwLastUpdateTime;
START_PROFILE("stalker/schedule_update/think/brain")
// try {
// try {
brain().update(update_delta);
// }
#ifdef DEBUG
// catch (const luabind::cast_failed &message) {
// Msg ("! Expression \"%s\" from luabind::object to
//%s",message.what(),message.info().name());
// throw;
// }
#endif
// catch (const std::exception &message) {
// Msg ("! Expression \"%s\"",message.what());
// throw;
// }
// catch (...) {
// Msg ("! unknown exception occured");
// throw;
// }
// }
// catch(...) {
#ifdef DEBUG
// Msg ("! Last action being executed : %s",brain().current_action().m_action_name);
#endif
// brain().setup (this);
// brain().update (update_delta);
// }
STOP_PROFILE
START_PROFILE("stalker/schedule_update/think/movement")
if (!g_Alive())
return;
// try {
movement().update(update_delta);
// }
#if 0 // def DEBUG
catch (const luabind::cast_failed& message) {
Msg ("! Expression \"%s\" from luabind::object to %s",message.what(),message.info().name());
movement().initialize ();
movement().update (update_delta);
throw;
}
catch (const std::exception& message) {
Msg ("! Expression \"%s\"",message.what());
movement().initialize ();
movement().update (update_delta);
throw;
}
catch (...) {
Msg ("! unknown exception occured");
movement().initialize ();
movement().update (update_delta);
throw;
}
#endif // DEBUG
STOP_PROFILE
STOP_PROFILE
}
void CAI_Stalker::SelectAnimation(const Fvector& view, const Fvector& move, float speed)
{
if (!Device.Paused())
animation().update();
}
const SRotation CAI_Stalker::Orientation() const { return (movement().m_head.current); }
const MonsterSpace::SBoneRotation& CAI_Stalker::head_orientation() const { return (movement().head_orientation()); }
void CAI_Stalker::net_Relcase(IGameObject* O)
{
inherited::net_Relcase(O);
sight().remove_links(O);
movement().remove_links(O);
if (!g_Alive())
return;
agent_manager().remove_links(O);
m_pPhysics_support->in_NetRelcase(O);
}
CMovementManager* CAI_Stalker::create_movement_manager()
{
return (m_movement_manager = xr_new<stalker_movement_manager_smart_cover>(this));
}
CSound_UserDataVisitor* CAI_Stalker::create_sound_visitor()
{
return (m_sound_user_data_visitor = xr_new<CStalkerSoundDataVisitor>(this));
}
CMemoryManager* CAI_Stalker::create_memory_manager() { return (xr_new<CMemoryManager>(this, create_sound_visitor())); }
IFactoryObject* CAI_Stalker::_construct()
{
m_pPhysics_support = xr_new<CCharacterPhysicsSupport>(CCharacterPhysicsSupport::etStalker, this);
CCustomMonster::_construct();
CObjectHandler::_construct();
CStepManager::_construct();
m_actor_relation_flags.zero();
m_animation_manager = xr_new<CStalkerAnimationManager>(this);
m_brain = xr_new<CStalkerPlanner>();
m_sight_manager = xr_new<CSightManager>(this);
m_weapon_shot_effector = xr_new<CWeaponShotEffector>();
return (this);
}
bool CAI_Stalker::use_center_to_aim() const { return (!wounded() && (movement().body_state() != eBodyStateCrouch)); }
void CAI_Stalker::UpdateCamera()
{
float new_range = eye_range, new_fov = eye_fov;
Fvector temp = eye_matrix.k;
if (g_Alive())
{
update_range_fov(
new_range, new_fov, memory().visual().current_state().m_max_view_distance * eye_range, eye_fov);
if (weapon_shot_effector().IsActive())
temp = weapon_shot_effector_direction(temp);
}
g_pGameLevel->Cameras().Update(eye_matrix.c, temp, eye_matrix.j, new_fov, .75f, new_range, 0);
}
bool CAI_Stalker::can_attach(const CInventoryItem* inventory_item) const
{
return (CObjectHandler::can_attach(inventory_item));
}
void CAI_Stalker::save(NET_Packet& packet)
{
inherited::save(packet);
CInventoryOwner::save(packet);
brain().save(packet);
}
void CAI_Stalker::load(IReader& packet)
{
inherited::load(packet);
CInventoryOwner::load(packet);
brain().load(packet);
}
void CAI_Stalker::load_critical_wound_bones()
{
fill_bones_body_parts("head", critical_wound_type_head);
fill_bones_body_parts("torso", critical_wound_type_torso);
fill_bones_body_parts("hand_left", critical_wound_type_hand_left);
fill_bones_body_parts("hand_right", critical_wound_type_hand_right);
fill_bones_body_parts("leg_left", critical_wound_type_leg_left);
fill_bones_body_parts("leg_right", critical_wound_type_leg_right);
}
void CAI_Stalker::fill_bones_body_parts(LPCSTR bone_id, const ECriticalWoundType& wound_type)
{
LPCSTR body_parts_section_id = pSettings->r_string(cNameSect(), "body_parts_section_id");
VERIFY(body_parts_section_id);
LPCSTR body_part_section_id = pSettings->r_string(body_parts_section_id, bone_id);
VERIFY(body_part_section_id);
IKinematics* kinematics = smart_cast<IKinematics*>(Visual());
VERIFY(kinematics);
CInifile::Sect& body_part_section = pSettings->r_section(body_part_section_id);
auto I = body_part_section.Data.cbegin();
auto E = body_part_section.Data.cend();
for (; I != E; ++I)
m_bones_body_parts.emplace(kinematics->LL_BoneID((*I).first), u32(wound_type));
}
void CAI_Stalker::on_before_change_team()
{
m_registered_in_combat_on_migration = agent_manager().member().registered_in_combat(this);
}
void CAI_Stalker::on_after_change_team()
{
if (!m_registered_in_combat_on_migration)
return;
agent_manager().member().register_in_combat(this);
}
float CAI_Stalker::shedule_Scale() const
{
if (!sniper_update_rate())
return (inherited::shedule_Scale());
return (0.f);
}
void CAI_Stalker::aim_bone_id(shared_str const& bone_id)
{
// IKinematics *kinematics = smart_cast<IKinematics*>(Visual());
// VERIFY2 (kinematics->LL_BoneID(bone_id) != BI_NONE, make_string("Cannot find bone %s",bone_id));
m_aim_bone_id = bone_id;
}
shared_str const& CAI_Stalker::aim_bone_id() const { return (m_aim_bone_id); }
void aim_target(shared_str const& aim_bone_id, Fvector& result, const CGameObject* object)
{
IKinematics* kinematics = smart_cast<IKinematics*>(object->Visual());
VERIFY(kinematics);
u16 bone_id = kinematics->LL_BoneID(aim_bone_id);
VERIFY2(bone_id != BI_NONE, make_string("Cannot find bone %s", bone_id));
Fmatrix const& bone_matrix = kinematics->LL_GetTransform(bone_id);
Fmatrix final;
final.mul_43(object->XFORM(), bone_matrix);
result = final.c;
}
void CAI_Stalker::aim_target(Fvector& result, const CGameObject* object)
{
VERIFY(m_aim_bone_id.size());
::aim_target(m_aim_bone_id, result, object);
}
bool CAI_Stalker::AlwaysTheCrow()
{
VERIFY(character_physics_support());
return (character_physics_support()->is_interactive_motion());
}
smart_cover::cover const* CAI_Stalker::get_current_smart_cover()
{
if (movement().current_params().cover_id() != movement().target_params().cover_id())
return 0;
return movement().current_params().cover();
}
smart_cover::loophole const* CAI_Stalker::get_current_loophole()
{
if (movement().current_params().cover_id() != movement().target_params().cover_id())
return 0;
if (movement().current_params().cover_loophole_id() != movement().target_params().cover_loophole_id())
return 0;
return movement().current_params().cover_loophole();
}
bool CAI_Stalker::can_fire_right_now()
{
if (!ready_to_kill())
return (false);
VERIFY(best_weapon());
CWeapon& best_weapon = smart_cast<CWeapon&>(*this->best_weapon());
return best_weapon.GetAmmoElapsed() > 0;
}
bool CAI_Stalker::unlimited_ammo() { return infinite_ammo() && CObjectHandler::planner().object().g_Alive(); }
void CAI_Stalker::ResetBoneProtections(pcstr imm_sect, pcstr bone_sect)
{
IKinematics* pKinematics = smart_cast<IKinematics*>(Visual());
CInifile* ini = pKinematics->LL_UserData();
if (ini)
{
if (imm_sect || ini->section_exist("immunities"))
{
imm_sect = imm_sect ? imm_sect : ini->r_string("immunities", "immunities_sect");
conditions().LoadImmunities(imm_sect, pSettings);
}
if (bone_sect || ini->line_exist("bone_protection", "bones_protection_sect"))
{
bone_sect = ini->r_string("bone_protection", "bones_protection_sect");
m_boneHitProtection->reload(bone_sect, pKinematics);
}
}
}
| 412 | 0.980093 | 1 | 0.980093 | game-dev | MEDIA | 0.964565 | game-dev | 0.530817 | 1 | 0.530817 |
hojat72elect/libgdx_games | 3,968 | Super_Jumper/core/src/com/nopalsoft/superjumper/screens/Screens.kt | package com.nopalsoft.superjumper.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.InputAdapter
import com.badlogic.gdx.InputMultiplexer
import com.badlogic.gdx.Screen
import com.badlogic.gdx.audio.Music
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.InputListener
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.scenes.scene2d.ui.Image
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.nopalsoft.superjumper.Assets
import com.nopalsoft.superjumper.Settings
import com.nopalsoft.superjumper.SuperJumperGame
import com.nopalsoft.superjumper.game.GameScreen
abstract class Screens(game: SuperJumperGame) : InputAdapter(), Screen {
var game: SuperJumperGame
private var camera: OrthographicCamera
var batch: SpriteBatch?
var stage: Stage? = game.stage
private var music: Music? = null
override fun render(delta: Float) {
var delta = delta
if (delta > .1f) delta = .1f
update(delta)
stage!!.act(delta)
camera.update()
batch!!.projectionMatrix = camera.combined
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
draw(delta)
stage!!.draw()
}
fun addPressEffect(actor: Actor) {
actor.addListener(object : InputListener() {
override fun touchDown(event: InputEvent, x: Float, y: Float, pointer: Int, button: Int): Boolean {
actor.setPosition(actor.x, actor.y - 5)
event.stop()
return true
}
override fun touchUp(event: InputEvent, x: Float, y: Float, pointer: Int, button: Int) {
actor.setPosition(actor.x, actor.y + 5)
}
})
}
private var blackFadeOut: Image? = null
init {
stage!!.clear()
this.batch = game.batch
this.game = game
camera = OrthographicCamera(SCREEN_WIDTH.toFloat(), SCREEN_HEIGHT.toFloat())
camera.position[SCREEN_WIDTH / 2f, SCREEN_HEIGHT / 2f] = 0f
val input = InputMultiplexer(this, stage)
Gdx.input.inputProcessor = input
}
fun changeScreenWithFadeOut(newScreen: Class<*>, game: SuperJumperGame) {
blackFadeOut = Image(Assets.blackPixel)
blackFadeOut!!.setSize(SCREEN_WIDTH.toFloat(), SCREEN_HEIGHT.toFloat())
blackFadeOut!!.color.a = 0f
blackFadeOut!!.addAction(Actions.sequence(Actions.fadeIn(.5f), Actions.run {
if (newScreen == GameScreen::class.java) {
game.screen = GameScreen(game)
} else if (newScreen == MainMenuScreen::class.java) {
game.screen = MainMenuScreen(game)
}
}))
val label = Label("Loading..", Assets.labelStyleLarge)
label.setPosition(SCREEN_WIDTH / 2f - label.width / 2f, SCREEN_HEIGHT / 2f - label.height / 2f)
label.color.a = 0f
label.addAction(Actions.fadeIn(.6f))
stage!!.addActor(blackFadeOut)
stage!!.addActor(label)
}
abstract fun update(delta: Float)
abstract fun draw(delta: Float)
override fun resize(width: Int, height: Int) {
stage!!.viewport.update(width, height, true)
}
override fun show() {
}
override fun hide() {
if (music != null) {
music!!.stop()
music!!.dispose()
music = null
}
Settings.save()
}
override fun pause() {
}
override fun resume() {
}
override fun dispose() {
batch!!.dispose()
}
companion object {
const val SCREEN_WIDTH = 480
const val SCREEN_HEIGHT = 800
const val WORLD_WIDTH = 4.8f
const val WORLD_HEIGHT = 8f
}
}
| 412 | 0.797261 | 1 | 0.797261 | game-dev | MEDIA | 0.874262 | game-dev | 0.986179 | 1 | 0.986179 |
ForeignGods/Animated-Line-Renderer | 11,678 | Library/PackageCache/com.unity.timeline@1.4.8/Editor/Window/TimelineWindow_EditorCallbacks.cs | using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Playables;
using UnityEngine.SceneManagement;
using UnityEngine.Timeline;
namespace UnityEditor.Timeline
{
partial class TimelineWindow
{
private int m_ComponentAddedFrame;
void OnSelectionChangedInactive()
{
// Case 946942 -- when selection changes and the window is open but hidden, timeline
// needs to update selection immediately so preview mode is correctly released
// Case 1123119 -- except when recording
if (!hasFocus)
{
RefreshSelection(!locked && state != null && !state.recording);
}
}
void InitializeEditorCallbacks()
{
Undo.postprocessModifications += PostprocessAnimationRecordingModifications;
Undo.postprocessModifications += ProcessAssetModifications;
Undo.undoRedoPerformed += OnUndoRedo;
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
AnimationUtility.onCurveWasModified += OnCurveModified;
EditorApplication.editorApplicationQuit += OnEditorQuit;
Selection.selectionChanged += OnSelectionChangedInactive;
EditorSceneManager.sceneSaved += OnSceneSaved;
ObjectFactory.componentWasAdded += OnComponentWasAdded;
PrefabUtility.prefabInstanceUpdated += OnPrefabApplied;
EditorApplication.pauseStateChanged += OnPlayModePause;
}
void OnEditorQuit()
{
TimelineWindowViewPrefs.SaveAll();
}
void RemoveEditorCallbacks()
{
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
Undo.undoRedoPerformed -= OnUndoRedo;
Undo.postprocessModifications -= PostprocessAnimationRecordingModifications;
Undo.postprocessModifications -= ProcessAssetModifications;
AnimationUtility.onCurveWasModified -= OnCurveModified;
EditorApplication.editorApplicationQuit -= OnEditorQuit;
Selection.selectionChanged -= OnSelectionChangedInactive;
EditorSceneManager.sceneSaved -= OnSceneSaved;
ObjectFactory.componentWasAdded -= OnComponentWasAdded;
PrefabUtility.prefabInstanceUpdated -= OnPrefabApplied;
EditorApplication.pauseStateChanged -= OnPlayModePause;
}
void OnPlayModePause(PauseState state)
{
// in PlayMode, if the timeline is playing, a constant repaint cycle occurs. Pausing the editor
// breaks the cycle, so this will restart it
Repaint();
}
// Called when a prefab change is applied to the scene.
// Redraw so control tracks that use prefabs can show changes
void OnPrefabApplied(GameObject go)
{
if (!state.previewMode)
return;
// if we added a component this frame, then rebuild, otherwise just let
// the individual playable handle the prefab application
if (Time.frameCount == m_ComponentAddedFrame)
TimelineEditor.Refresh(RefreshReason.ContentsModified);
else
TimelineEditor.Refresh(RefreshReason.SceneNeedsUpdate);
}
// When the scene is save the director time will get reset.
void OnSceneSaved(Scene scene)
{
if (state != null)
state.OnSceneSaved();
}
void OnCurveModified(AnimationClip clip, EditorCurveBinding binding, AnimationUtility.CurveModifiedType type)
{
InspectorWindow.RepaintAllInspectors();
if (state == null || state.rebuildGraph)
return;
//Force refresh of curve when modified by another editor.
Repaint();
if (state.previewMode == false)
return;
bool hasPlayable = m_PlayableLookup.GetPlayableFromAnimClip(clip, out Playable playable);
// mark the timeline clip as dirty
TimelineClip timelineClip = m_PlayableLookup.GetTimelineClipFromCurves(clip);
if (timelineClip != null)
timelineClip.MarkDirty();
if (type == AnimationUtility.CurveModifiedType.CurveModified)
{
if (hasPlayable)
{
playable.SetAnimatedProperties(clip);
}
// updates the duration of the graph without rebuilding
AnimationUtility.SyncEditorCurves(clip); // deleted keys are not synced when this is sent out, so duration could be incorrect
state.UpdateRootPlayableDuration(state.editSequence.duration);
bool isRecording = TimelineRecording.IsRecordingAnimationTrack;
PlayableDirector masterDirector = TimelineEditor.masterDirector;
bool isGraphValid = masterDirector != null && masterDirector.playableGraph.IsValid();
// don't evaluate if this is caused by recording on an animation track, the extra evaluation can cause hiccups
// Prevent graphs to be resurrected by a changed clip.
if (!isRecording && isGraphValid)
state.Evaluate();
}
else if (EditorUtility.IsDirty(clip)) // curve added/removed, or clip added/removed
{
state.rebuildGraph |= timelineClip != null || hasPlayable;
}
}
void OnPlayModeStateChanged(PlayModeStateChange playModeState)
{
// case 923506 - make sure we save view data before switching modes
if (playModeState == PlayModeStateChange.ExitingEditMode ||
playModeState == PlayModeStateChange.ExitingPlayMode)
TimelineWindowViewPrefs.SaveAll();
bool isPlaymodeAboutToChange = playModeState == PlayModeStateChange.ExitingEditMode || playModeState == PlayModeStateChange.ExitingPlayMode;
// Important to stop the graph on any director so temporary objects are properly cleaned up
if (isPlaymodeAboutToChange && state != null)
state.Stop();
}
UndoPropertyModification[] PostprocessAnimationRecordingModifications(UndoPropertyModification[] modifications)
{
DirtyModifiedObjects(modifications);
var remaining = TimelineRecording.ProcessUndoModification(modifications, state);
// if we've changed, we need to repaint the sequence window to show clip length changes
if (remaining != modifications)
{
// only update if us or the sequencer window has focus
// Prevents color pickers and other dialogs from being wrongly dismissed
bool repaint = (focusedWindow == null) ||
(focusedWindow is InspectorWindow) ||
(focusedWindow is TimelineWindow);
if (repaint)
Repaint();
}
return remaining;
}
void DirtyModifiedObjects(UndoPropertyModification[] modifications)
{
foreach (var m in modifications)
{
if (m.currentValue == null || m.currentValue.target == null)
continue;
var track = m.currentValue.target as TrackAsset;
var playableAsset = m.currentValue.target as PlayableAsset;
var editorClip = m.currentValue.target as EditorClip;
if (track != null)
{
track.MarkDirty();
}
else if (playableAsset != null)
{
var clip = TimelineRecording.FindClipWithAsset(state.editSequence.asset, playableAsset);
if (clip != null)
clip.MarkDirty();
}
else if (editorClip != null && editorClip.clip != null)
{
editorClip.clip.MarkDirty();
}
}
}
UndoPropertyModification[] ProcessAssetModifications(UndoPropertyModification[] modifications)
{
bool rebuildGraph = false;
for (int i = 0; i < modifications.Length && !rebuildGraph; i++)
{
var mod = modifications[i];
// check if an Avatar Mask has been modified
if (mod.previousValue != null && mod.previousValue.target is AvatarMask)
{
rebuildGraph = state.editSequence.asset != null &&
state.editSequence.asset.flattenedTracks
.OfType<UnityEngine.Timeline.AnimationTrack>()
.Any(x => mod.previousValue.target == x.avatarMask);
}
}
if (rebuildGraph)
{
state.rebuildGraph = true;
Repaint();
}
return modifications;
}
void OnUndoRedo()
{
var undos = new List<string>();
var redos = new List<string>();
Undo.GetRecords(undos, redos);
var rebuildAll = redos.Any(x => x.StartsWith("Timeline ")) || undos.Any(x => x.StartsWith("Timeline"));
var evalNow = redos.Any(x => x.Contains("Edit Curve")) || undos.Any(x => x.Contains("Edit Curve"));
if (rebuildAll || evalNow)
{
ValidateSelection();
if (state != null)
{
if (evalNow) // when curves change, the new values need to be set in the transform before the inspector handles the undo
state.EvaluateImmediate();
if (rebuildAll)
state.Refresh();
}
Repaint();
}
}
static void ValidateSelection()
{
//get all the clips in the selection
var selectedClips = Selection.GetFiltered<EditorClip>(SelectionMode.Unfiltered).Select(x => x.clip);
foreach (var selectedClip in selectedClips)
{
var parent = selectedClip.parentTrack;
if (selectedClip.parentTrack != null)
{
if (!parent.clips.Contains(selectedClip))
{
SelectionManager.Remove(selectedClip);
}
}
}
}
void OnComponentWasAdded(Component c)
{
m_ComponentAddedFrame = Time.frameCount;
var go = c.gameObject;
foreach (var seq in state.GetAllSequences())
{
if (seq.director == null || seq.asset == null)
{
return;
}
var rebind = seq.asset.GetOutputTracks().Any(track => seq.director.GetGenericBinding(track) == go);
// Either the playable director has a binding for the GameObject or it is a sibling of the director.
// The second case is needed since we have timeline top level markerTracks that do not have a binding, but
// are still "targeting" the playable director
if (rebind || seq.director.gameObject == go)
{
seq.director.RebindPlayableGraphOutputs();
}
}
}
}
}
| 412 | 0.954984 | 1 | 0.954984 | game-dev | MEDIA | 0.972181 | game-dev | 0.993913 | 1 | 0.993913 |
AimTuxOfficial/AimTux | 52,656 | src/settings.cpp | #include "settings.h"
void GetVal(Json::Value &config, int* setting)
{
if (config.isNull())
return;
*setting = config.asInt();
}
void GetVal(Json::Value &config, bool* setting)
{
if (config.isNull())
return;
*setting = config.asBool();
}
void GetVal(Json::Value &config, float* setting)
{
if (config.isNull())
return;
*setting = config.asFloat();
}
void GetVal(Json::Value &config, ImColor* setting)
{
if (config.isNull())
return;
GetVal(config["r"], &setting->Value.x);
GetVal(config["g"], &setting->Value.y);
GetVal(config["b"], &setting->Value.z);
GetVal(config["a"], &setting->Value.w);
}
void GetVal(Json::Value &config, char** setting)
{
if (config.isNull())
return;
*setting = strdup(config.asCString());
}
void GetVal(Json::Value &config, char* setting)
{
if (config.isNull())
return;
strcpy(setting, config.asCString());
}
void GetVal(Json::Value &config, ColorVar* setting)
{
if (config.isNull())
return;
GetVal(config["r"], &setting->color.Value.x);
GetVal(config["g"], &setting->color.Value.y);
GetVal(config["b"], &setting->color.Value.z);
GetVal(config["a"], &setting->color.Value.w);
GetVal(config["rainbow"], &setting->rainbow);
GetVal(config["rainbowSpeed"], &setting->rainbowSpeed);
}
void GetVal(Json::Value &config, HealthColorVar* setting)
{
if (config.isNull())
return;
GetVal(config["r"], &setting->color.Value.x);
GetVal(config["g"], &setting->color.Value.y);
GetVal(config["b"], &setting->color.Value.z);
GetVal(config["a"], &setting->color.Value.w);
GetVal(config["rainbow"], &setting->rainbow);
GetVal(config["rainbowSpeed"], &setting->rainbowSpeed);
GetVal(config["hp"], &setting->hp);
}
template <typename Ord, Ord (*lookupFunction)(std::string)>
void GetOrdinal(Json::Value& config, Ord* setting)
{
if (config.isNull())
return;
Ord value;
if (config.isString())
value = lookupFunction(config.asString());
else
value = (Ord) config.asInt();
*setting = value;
}
void GetButtonCode(Json::Value &config, enum ButtonCode_t* setting)
{
GetOrdinal<enum ButtonCode_t, Util::GetButtonCode>(config, setting);
}
void LoadColor(Json::Value &config, ImColor color)
{
config["r"] = color.Value.x;
config["g"] = color.Value.y;
config["b"] = color.Value.z;
config["a"] = color.Value.w;
}
void LoadColor(Json::Value &config, ColorVar color)
{
config["r"] = color.color.Value.x;
config["g"] = color.color.Value.y;
config["b"] = color.color.Value.z;
config["a"] = color.color.Value.w;
config["rainbow"] = color.rainbow;
config["rainbowSpeed"] = color.rainbowSpeed;
}
void LoadColor(Json::Value &config, HealthColorVar color)
{
config["r"] = color.color.Value.x;
config["g"] = color.color.Value.y;
config["b"] = color.color.Value.z;
config["a"] = color.color.Value.w;
config["rainbow"] = color.rainbow;
config["rainbowSpeed"] = color.rainbowSpeed;
config["hp"] = color.hp;
}
void Settings::LoadDefaultsOrSave(std::string path)
{
Json::Value settings;
Json::StyledWriter styledWriter;
LoadColor(settings["UI"]["mainColor"], Settings::UI::mainColor);
LoadColor(settings["UI"]["bodyColor"], Settings::UI::bodyColor);
LoadColor(settings["UI"]["fontColor"], Settings::UI::fontColor);
settings["UI"]["Fonts"]["ESP"]["family"] = Settings::UI::Fonts::ESP::family;
settings["UI"]["Fonts"]["ESP"]["size"] = Settings::UI::Fonts::ESP::size;
settings["UI"]["Fonts"]["ESP"]["flags"] = Settings::UI::Fonts::ESP::flags;
for (auto i : Settings::Aimbot::weapons)
{
// TODO this is kind of a hack and i'm too tired to find a better way to do this
// yes i tried defining a variable, skinSetting, and giving it the same value but woooooo operator overloading
// in C++ and weird shit
#define weaponSetting settings["Aimbot"]["weapons"][Util::Items::GetItemName((enum ItemDefinitionIndex) i.first)]
weaponSetting["Enabled"] = i.second.enabled;
weaponSetting["Silent"] = i.second.silent;
weaponSetting["Friendly"] = i.second.friendly;
weaponSetting["TargetBone"] = (int) i.second.bone;
weaponSetting["AimKey"] = Util::GetButtonName(i.second.aimkey);
weaponSetting["AimKeyOnly"] = i.second.aimkeyOnly;
weaponSetting["Smooth"]["Enabled"] = i.second.smoothEnabled;
weaponSetting["Smooth"]["Amount"] = i.second.smoothAmount;
weaponSetting["Smooth"]["Type"] = (int) i.second.smoothType;
weaponSetting["Smooth"]["Salting"]["Enabled"] = i.second.smoothSaltEnabled;
weaponSetting["Smooth"]["Salting"]["Multiplier"] = i.second.smoothSaltMultiplier;
weaponSetting["ErrorMargin"]["Enabled"] = i.second.errorMarginEnabled;
weaponSetting["ErrorMargin"]["Value"] = i.second.errorMarginValue;
weaponSetting["AutoAim"]["Enabled"] = i.second.autoAimEnabled;
weaponSetting["AutoAim"]["FOV"] = i.second.autoAimFov;
weaponSetting["AimStep"]["Enabled"] = i.second.aimStepEnabled;
weaponSetting["AimStep"]["Amount"] = i.second.aimStepValue;
weaponSetting["RCS"]["Enabled"] = i.second.rcsEnabled;
weaponSetting["RCS"]["AlwaysOn"] = i.second.rcsAlwaysOn;
weaponSetting["RCS"]["AmountX"] = i.second.rcsAmountX;
weaponSetting["RCS"]["AmountY"] = i.second.rcsAmountY;
weaponSetting["AutoPistol"]["Enabled"] = i.second.autoPistolEnabled;
weaponSetting["AutoShoot"]["Enabled"] = i.second.autoShootEnabled;
weaponSetting["AutoScope"]["Enabled"] = i.second.autoScopeEnabled;
weaponSetting["NoShoot"]["Enabled"] = i.second.noShootEnabled;
weaponSetting["IgnoreJump"]["Enabled"] = i.second.ignoreJumpEnabled;
weaponSetting["SmokeCheck"]["Enabled"] = i.second.smokeCheck;
weaponSetting["FlashCheck"]["Enabled"] = i.second.flashCheck;
weaponSetting["AutoWall"]["Enabled"] = i.second.autoWallEnabled;
weaponSetting["AutoWall"]["Value"] = i.second.autoWallValue;
weaponSetting["AutoSlow"]["enabled"] = i.second.autoSlow;
weaponSetting["Prediction"]["enabled"] = i.second.predEnabled;
weaponSetting["AutoSlow"]["minDamage"] = i.second.autoSlowMinDamage;
for (int bone = (int) Hitbox::HITBOX_HEAD; bone <= (int) Hitbox::HITBOX_ARMS; bone++)
weaponSetting["AutoWall"]["Bones"][bone] = i.second.autoWallBones[bone];
weaponSetting["AutoAim"]["RealDistance"] = i.second.autoAimRealDistance;
#undef weaponSetting
}
settings["Aimbot"]["AutoCrouch"]["enabled"] = Settings::Aimbot::AutoCrouch::enabled;
settings["Resolver"]["resolve_all"] = Settings::Resolver::resolveAll;
settings["Triggerbot"]["enabled"] = Settings::Triggerbot::enabled;
settings["Triggerbot"]["key"] = Util::GetButtonName(Settings::Triggerbot::key);
settings["Triggerbot"]["Filters"]["enemies"] = Settings::Triggerbot::Filters::enemies;
settings["Triggerbot"]["Filters"]["allies"] = Settings::Triggerbot::Filters::allies;
settings["Triggerbot"]["Filters"]["walls"] = Settings::Triggerbot::Filters::walls;
settings["Triggerbot"]["Filters"]["smoke_check"] = Settings::Triggerbot::Filters::smokeCheck;
settings["Triggerbot"]["Filters"]["flash_check"] = Settings::Triggerbot::Filters::flashCheck;
settings["Triggerbot"]["Filters"]["head"] = Settings::Triggerbot::Filters::head;
settings["Triggerbot"]["Filters"]["chest"] = Settings::Triggerbot::Filters::chest;
settings["Triggerbot"]["Filters"]["stomach"] = Settings::Triggerbot::Filters::stomach;
settings["Triggerbot"]["Filters"]["arms"] = Settings::Triggerbot::Filters::arms;
settings["Triggerbot"]["Filters"]["legs"] = Settings::Triggerbot::Filters::legs;
settings["Triggerbot"]["Delay"]["enabled"] = Settings::Triggerbot::Delay::enabled;
settings["Triggerbot"]["Delay"]["value"] = Settings::Triggerbot::Delay::value;
settings["AntiAim"]["Yaw"]["enabled"] = Settings::AntiAim::Yaw::enabled;
settings["AntiAim"]["Yaw"]["type"] = (int) Settings::AntiAim::Yaw::type;
settings["AntiAim"]["Yaw"]["type_fake"] = (int) Settings::AntiAim::Yaw::typeFake;
settings["AntiAim"]["Yaw"]["antiResolver"] = Settings::AntiAim::Yaw::antiResolver;
settings["AntiAim"]["Pitch"]["enabled"] = Settings::AntiAim::Pitch::enabled;
settings["AntiAim"]["Pitch"]["type"] = (int) Settings::AntiAim::Pitch::type;
settings["AntiAim"]["HeadEdge"]["enabled"] = Settings::AntiAim::HeadEdge::enabled;
settings["AntiAim"]["HeadEdge"]["distance"] = Settings::AntiAim::HeadEdge::distance;
settings["AntiAim"]["AutoDisable"]["no_enemy"] = Settings::AntiAim::AutoDisable::noEnemy;
settings["AntiAim"]["AutoDisable"]["knife_held"] = Settings::AntiAim::AutoDisable::knifeHeld;
settings["ESP"]["enabled"] = Settings::ESP::enabled;
LoadColor(settings["ESP"]["enemy_color"], Settings::ESP::enemyColor);
LoadColor(settings["ESP"]["enemy_visible_color"], Settings::ESP::enemyVisibleColor);
LoadColor(settings["ESP"]["ally_color"], Settings::ESP::allyColor);
LoadColor(settings["ESP"]["ally_visible_color"], Settings::ESP::allyVisibleColor);
LoadColor(settings["ESP"]["t_color"], Settings::ESP::tColor);
LoadColor(settings["ESP"]["t_visible_color"], Settings::ESP::tVisibleColor);
LoadColor(settings["ESP"]["ct_color"], Settings::ESP::ctColor);
LoadColor(settings["ESP"]["ct_visible_color"], Settings::ESP::ctVisibleColor);
LoadColor(settings["ESP"]["localplayer_color"], Settings::ESP::localplayerColor);
LoadColor(settings["ESP"]["bomb_color"], Settings::ESP::bombColor);
LoadColor(settings["ESP"]["bomb_defusing_color"], Settings::ESP::bombDefusingColor);
LoadColor(settings["ESP"]["hostage_color"], Settings::ESP::hostageColor);
LoadColor(settings["ESP"]["defuser_color"], Settings::ESP::defuserColor);
LoadColor(settings["ESP"]["weapon_color"], Settings::ESP::weaponColor);
LoadColor(settings["ESP"]["chicken_color"], Settings::ESP::chickenColor);
LoadColor(settings["ESP"]["fish_color"], Settings::ESP::fishColor);
LoadColor(settings["ESP"]["smoke_color"], Settings::ESP::smokeColor);
LoadColor(settings["ESP"]["decoy_color"], Settings::ESP::decoyColor);
LoadColor(settings["ESP"]["flashbang_color"], Settings::ESP::flashbangColor);
LoadColor(settings["ESP"]["grenade_color"], Settings::ESP::grenadeColor);
LoadColor(settings["ESP"]["molotov_color"], Settings::ESP::molotovColor);
settings["ESP"]["Glow"]["enabled"] = Settings::ESP::Glow::enabled;
LoadColor(settings["ESP"]["Glow"]["ally_color"], Settings::ESP::Glow::allyColor);
LoadColor(settings["ESP"]["Glow"]["enemy_color"], Settings::ESP::Glow::enemyColor);
LoadColor(settings["ESP"]["Glow"]["enemy_visible_color"], Settings::ESP::Glow::enemyVisibleColor);
LoadColor(settings["ESP"]["Glow"]["localplayer_color"], Settings::ESP::Glow::localplayerColor);
LoadColor(settings["ESP"]["Glow"]["weapon_color"], Settings::ESP::Glow::weaponColor);
LoadColor(settings["ESP"]["Glow"]["grenade_color"], Settings::ESP::Glow::grenadeColor);
LoadColor(settings["ESP"]["Glow"]["defuser_color"], Settings::ESP::Glow::defuserColor);
LoadColor(settings["ESP"]["Glow"]["chicken_color"], Settings::ESP::Glow::chickenColor);
settings["ESP"]["Filters"]["legit"] = Settings::ESP::Filters::legit;
settings["ESP"]["Filters"]["visibility_check"] = Settings::ESP::Filters::visibilityCheck;
settings["ESP"]["Filters"]["smoke_check"] = Settings::ESP::Filters::smokeCheck;
settings["ESP"]["Filters"]["enemies"] = Settings::ESP::Filters::enemies;
settings["ESP"]["Filters"]["allies"] = Settings::ESP::Filters::allies;
settings["ESP"]["Filters"]["bomb"] = Settings::ESP::Filters::bomb;
settings["ESP"]["Filters"]["hostages"] = Settings::ESP::Filters::hostages;
settings["ESP"]["Filters"]["defusers"] = Settings::ESP::Filters::defusers;
settings["ESP"]["Filters"]["weapons"] = Settings::ESP::Filters::weapons;
settings["ESP"]["Filters"]["chickens"] = Settings::ESP::Filters::chickens;
settings["ESP"]["Filters"]["fishes"] = Settings::ESP::Filters::fishes;
settings["ESP"]["Filters"]["throwables"] = Settings::ESP::Filters::throwables;
settings["ESP"]["Filters"]["localplayer"] = Settings::ESP::Filters::localplayer;
settings["ESP"]["Info"]["name"] = Settings::ESP::Info::name;
settings["ESP"]["Info"]["clan"] = Settings::ESP::Info::clan;
settings["ESP"]["Info"]["steam_id"] = Settings::ESP::Info::steamId;
settings["ESP"]["Info"]["rank"] = Settings::ESP::Info::rank;
settings["ESP"]["Info"]["health"] = Settings::ESP::Info::health;
settings["ESP"]["Info"]["weapon"] = Settings::ESP::Info::weapon;
settings["ESP"]["Info"]["scoped"] = Settings::ESP::Info::scoped;
settings["ESP"]["Info"]["reloading"] = Settings::ESP::Info::reloading;
settings["ESP"]["Info"]["flashed"] = Settings::ESP::Info::flashed;
settings["ESP"]["Info"]["planting"] = Settings::ESP::Info::planting;
settings["ESP"]["Info"]["has_defuser"] = Settings::ESP::Info::hasDefuser;
settings["ESP"]["Info"]["defusing"] = Settings::ESP::Info::defusing;
settings["ESP"]["Info"]["grabbing_hostage"] = Settings::ESP::Info::grabbingHostage;
settings["ESP"]["Info"]["rescuing"] = Settings::ESP::Info::rescuing;
settings["ESP"]["Info"]["location"] = Settings::ESP::Info::location;
settings["ESP"]["Boxes"]["enabled"] = Settings::ESP::Boxes::enabled;
settings["ESP"]["Boxes"]["type"] = (int) Settings::ESP::Boxes::type;
settings["ESP"]["Skeleton"]["enabled"] = Settings::ESP::Skeleton::enabled;
LoadColor(settings["ESP"]["Skeleton"]["color"], Settings::ESP::Skeleton::color);
settings["ESP"]["Bars"]["enabled"] = Settings::ESP::Bars::enabled;
settings["ESP"]["Bars"]["color_type"] = (int) Settings::ESP::Bars::colorType;
settings["ESP"]["Bars"]["type"] = (int) Settings::ESP::Bars::type;
settings["ESP"]["Tracers"]["enabled"] = Settings::ESP::Tracers::enabled;
settings["ESP"]["Tracers"]["type"] = (int) Settings::ESP::Tracers::type;
settings["ESP"]["BulletTracers"]["enabled"] = Settings::ESP::BulletTracers::enabled;
settings["ESP"]["FOVCrosshair"]["enabled"] = Settings::ESP::FOVCrosshair::enabled;
settings["ESP"]["FOVCrosshair"]["filled"] = Settings::ESP::FOVCrosshair::filled;
LoadColor(settings["ESP"]["FOVCrosshair"]["color"], Settings::ESP::FOVCrosshair::color);
settings["ESP"]["Chams"]["Arms"]["enabled"] = Settings::ESP::Chams::Arms::enabled;
settings["ESP"]["Chams"]["Arms"]["type"] = (int) Settings::ESP::Chams::Arms::type;
settings["ESP"]["Chams"]["Weapon"]["enabled"] = Settings::ESP::Chams::Weapon::enabled;
LoadColor(settings["ESP"]["Chams"]["Weapon"]["color"], Settings::ESP::Chams::Weapon::color);
LoadColor(settings["ESP"]["Chams"]["Arms"]["color"], Settings::ESP::Chams::Arms::color);
LoadColor(settings["ESP"]["Chams"]["players_ally_color"], Settings::ESP::Chams::allyColor);
LoadColor(settings["ESP"]["Chams"]["players_ally_visible_color"], Settings::ESP::Chams::allyVisibleColor);
LoadColor(settings["ESP"]["Chams"]["players_enemy_color"], Settings::ESP::Chams::enemyColor);
LoadColor(settings["ESP"]["Chams"]["players_enemy_visible_color"], Settings::ESP::Chams::enemyVisibleColor);
LoadColor(settings["ESP"]["Chams"]["localplayer_color"], Settings::ESP::Chams::localplayerColor);
settings["ESP"]["Chams"]["type"] = (int) Settings::ESP::Chams::type;
settings["ESP"]["Chams"]["enabled"] = Settings::ESP::Chams::enabled;
settings["ESP"]["Sounds"]["enabled"] = Settings::ESP::Sounds::enabled;
settings["ESP"]["Sounds"]["time"] = Settings::ESP::Sounds::time;
settings["ESP"]["Hitmarker"]["enabled"] = Settings::ESP::Hitmarker::enabled;
settings["ESP"]["Hitmarker"]["enemies"] = Settings::ESP::Hitmarker::enemies;
settings["ESP"]["Hitmarker"]["allies"] = Settings::ESP::Hitmarker::allies;
LoadColor(settings["ESP"]["Hitmarker"]["color"], Settings::ESP::Hitmarker::color);
settings["ESP"]["Hitmarker"]["duration"] = Settings::ESP::Hitmarker::duration;
settings["ESP"]["Hitmarker"]["size"] = Settings::ESP::Hitmarker::size;
settings["ESP"]["Hitmarker"]["inner_gap"] = Settings::ESP::Hitmarker::innerGap;
settings["ESP"]["Hitmarker"]["Damage"]["enabled"] = Settings::ESP::Hitmarker::Damage::enabled;
settings["ESP"]["HeadDot"]["enabled"] = Settings::ESP::HeadDot::enabled;
settings["ESP"]["HeadDot"]["size"] = Settings::ESP::HeadDot::size;
settings["Dlights"]["enabled"] = Settings::Dlights::enabled;
settings["Dlights"]["radius"] = Settings::Dlights::radius;
settings["Spammer"]["spammer_type"] = (int) Settings::Spammer::type;
settings["Spammer"]["say_team"] = Settings::Spammer::say_team;
settings["Spammer"]["KillSpammer"]["enabled"] = Settings::Spammer::KillSpammer::enabled;
settings["Spammer"]["KillSpammer"]["say_team"] = Settings::Spammer::KillSpammer::sayTeam;
Json::Value killSpammerMessages;
for (auto it : Settings::Spammer::KillSpammer::messages)
killSpammerMessages.append(it);
settings["Spammer"]["KillSpammer"]["messages"] = killSpammerMessages;
Json::Value normalSpammerMessages;
for (auto it : Settings::Spammer::NormalSpammer::messages)
normalSpammerMessages.append(it);
settings["Spammer"]["NormalSpammer"]["messages"] = normalSpammerMessages;
settings["Spammer"]["PositionSpammer"]["show_name"] = Settings::Spammer::PositionSpammer::showName;
settings["Spammer"]["PositionSpammer"]["show_weapon"] = Settings::Spammer::PositionSpammer::showWeapon;
settings["Spammer"]["PositionSpammer"]["show_rank"] = Settings::Spammer::PositionSpammer::showRank;
settings["Spammer"]["PositionSpammer"]["show_wins"] = Settings::Spammer::PositionSpammer::showWins;
settings["Spammer"]["PositionSpammer"]["show_health"] = Settings::Spammer::PositionSpammer::showHealth;
settings["Spammer"]["PositionSpammer"]["show_money"] = Settings::Spammer::PositionSpammer::showMoney;
settings["Spammer"]["PositionSpammer"]["show_lastplace"] = Settings::Spammer::PositionSpammer::showLastplace;
settings["BHop"]["enabled"] = Settings::BHop::enabled;
settings["AutoStrafe"]["enabled"] = Settings::AutoStrafe::enabled;
settings["AutoStrafe"]["type"] = (int) Settings::AutoStrafe::type;
settings["AutoStrafe"]["silent"] = Settings::AutoStrafe::silent;
settings["Noflash"]["enabled"] = Settings::Noflash::enabled;
settings["Noflash"]["value"] = Settings::Noflash::value;
settings["Radar"]["enabled"] = Settings::Radar::enabled;
settings["Radar"]["zoom"] = Settings::Radar::zoom;
settings["Radar"]["enemies"] = Settings::Radar::enemies;
settings["Radar"]["allies"] = Settings::Radar::allies;
settings["Radar"]["legit"] = Settings::Radar::legit;
settings["Radar"]["visibility_check"] = Settings::Radar::visibilityCheck;
settings["Radar"]["smoke_check"] = Settings::Radar::smokeCheck;
settings["Radar"]["InGame"]["enabled"] = Settings::Radar::InGame::enabled;
LoadColor(settings["Radar"]["enemy_color"], Settings::Radar::enemyColor);
LoadColor(settings["Radar"]["enemy_visible_color"], Settings::Radar::enemyVisibleColor);
LoadColor(settings["Radar"]["ally_color"], Settings::Radar::allyColor);
LoadColor(settings["Radar"]["ally_visible_color"], Settings::Radar::allyVisibleColor);
LoadColor(settings["Radar"]["t_color"], Settings::Radar::tColor);
LoadColor(settings["Radar"]["t_visible_color"], Settings::Radar::tVisibleColor);
LoadColor(settings["Radar"]["ct_color"], Settings::Radar::ctColor);
LoadColor(settings["Radar"]["ct_visible_color"], Settings::Radar::ctVisibleColor);
LoadColor(settings["Radar"]["bomb_color"], Settings::Radar::bombColor);
LoadColor(settings["Radar"]["bomb_defusing_color"], Settings::Radar::bombDefusingColor);
settings["Radar"]["icons_scale"] = Settings::Radar::iconsScale;
settings["Recoilcrosshair"]["enabled"] = Settings::Recoilcrosshair::enabled;
settings["Recoilcrosshair"]["showOnlyWhenShooting"] = Settings::Recoilcrosshair::showOnlyWhenShooting;
settings["FOVChanger"]["enabled"] = Settings::FOVChanger::enabled;
settings["FOVChanger"]["value"] = Settings::FOVChanger::value;
settings["FOVChanger"]["viewmodel_enabled"] = Settings::FOVChanger::viewmodelEnabled;
settings["FOVChanger"]["viewmodel_value"] = Settings::FOVChanger::viewmodelValue;
settings["FOVChanger"]["ignore_scope"] = Settings::FOVChanger::ignoreScope;
settings["Airstuck"]["enabled"] = Settings::Airstuck::enabled;
settings["Airstuck"]["key"] = Util::GetButtonName(Settings::Airstuck::key);
settings["SkinChanger"]["Skins"]["enabled"] = Settings::Skinchanger::Skins::enabled;
settings["SkinChanger"]["Models"]["enabled"] = Settings::Skinchanger::Models::enabled;
settings["SkinChanger"]["Skins"]["perTeam"] = Settings::Skinchanger::Skins::perTeam;
for (const auto& item: Settings::Skinchanger::skinsCT)
{
const AttribItem_t& skin = item.second;
#define skinSetting settings["SkinChanger"]["skinsCT"][Util::Items::GetItemConfigEntityName(item.first)]
skinSetting["ItemDefinitionIndex"] = Util::Items::GetItemConfigEntityName(skin.itemDefinitionIndex);
skinSetting["PaintKit"] = skin.fallbackPaintKit;
skinSetting["Wear"] = skin.fallbackWear;
skinSetting["Seed"] = skin.fallbackSeed;
skinSetting["StatTrak"] = skin.fallbackStatTrak;
skinSetting["CustomName"] = skin.customName;
#undef skinSetting
}
for (const auto& item: Settings::Skinchanger::skinsT)
{
const AttribItem_t& skin = item.second;
#define skinSetting settings["SkinChanger"]["skinsT"][Util::Items::GetItemConfigEntityName(item.first)]
skinSetting["ItemDefinitionIndex"] = Util::Items::GetItemConfigEntityName(skin.itemDefinitionIndex);
skinSetting["PaintKit"] = skin.fallbackPaintKit;
skinSetting["Wear"] = skin.fallbackWear;
skinSetting["Seed"] = skin.fallbackSeed;
skinSetting["StatTrak"] = skin.fallbackStatTrak;
skinSetting["CustomName"] = skin.customName;
#undef skinSetting
}
settings["ShowRanks"]["enabled"] = Settings::ShowRanks::enabled;
settings["ShowSpectators"]["enabled"] = Settings::ShowSpectators::enabled;
settings["ClanTagChanger"]["value"] = Settings::ClanTagChanger::value;
settings["ClanTagChanger"]["enabled"] = Settings::ClanTagChanger::enabled;
settings["ClanTagChanger"]["animation"] = Settings::ClanTagChanger::animation;
settings["ClanTagChanger"]["animation_speed"] = Settings::ClanTagChanger::animationSpeed;
settings["ClanTagChanger"]["type"] = (int) Settings::ClanTagChanger::type;
settings["View"]["NoViewPunch"]["enabled"] = Settings::View::NoViewPunch::enabled;
settings["View"]["NoAimPunch"]["enabled"] = Settings::View::NoAimPunch::enabled;
settings["Teleport"]["enabled"] = Settings::Teleport::enabled;
settings["Teleport"]["key"] = Settings::Teleport::key;
settings["FakeLag"]["enabled"] = Settings::FakeLag::enabled;
settings["FakeLag"]["value"] = Settings::FakeLag::value;
settings["FakeLag"]["adaptive"] = Settings::FakeLag::adaptive;
settings["AutoAccept"]["enabled"] = Settings::AutoAccept::enabled;
settings["NoSky"]["enabled"] = Settings::NoSky::enabled;
LoadColor(settings["NoSky"]["color"], Settings::NoSky::color);
settings["ASUSWalls"]["enabled"] = Settings::ASUSWalls::enabled;
LoadColor(settings["ASUSWalls"]["color"], Settings::ASUSWalls::color);
settings["NoScopeBorder"]["enabled"] = Settings::NoScopeBorder::enabled;
settings["SniperCrosshair"]["enabled"] = Settings::SniperCrosshair::enabled;
settings["Autoblock"]["enabled"] = Settings::Autoblock::enabled;
settings["Autoblock"]["key"] = Settings::Autoblock::key;
settings["AutoDefuse"]["enabled"] = Settings::AutoDefuse::enabled;
settings["NoSmoke"]["enabled"] = Settings::NoSmoke::enabled;
settings["ScreenshotCleaner"]["enabled"] = Settings::ScreenshotCleaner::enabled;
settings["EdgeJump"]["enabled"] = Settings::EdgeJump::enabled;
settings["EdgeJump"]["key"] = Util::GetButtonName(Settings::EdgeJump::key);
settings["NameStealer"]["enabled"] = Settings::NameStealer::enabled;
settings["NameStealer"]["team"] = Settings::NameStealer::team;
settings["ThirdPerson"]["enabled"] = Settings::ThirdPerson::enabled;
settings["ThirdPerson"]["distance"] = Settings::ThirdPerson::distance;
settings["JumpThrow"]["enabled"] = Settings::JumpThrow::enabled;
settings["JumpThrow"]["key"] = Util::GetButtonName(Settings::JumpThrow::key);
settings["DisablePostProcessing"]["enabled"] = Settings::DisablePostProcessing::enabled;
settings["GrenadeHelper"]["enabled"] = Settings::GrenadeHelper::enabled;
settings["GrenadeHelper"]["aimAssist"] = Settings::GrenadeHelper::aimAssist;
settings["GrenadeHelper"]["OnlyMatching"] = Settings::GrenadeHelper::onlyMatchingInfos;
settings["GrenadeHelper"]["aimStep"] = Settings::GrenadeHelper::aimStep;
settings["GrenadeHelper"]["aimDistance"] = Settings::GrenadeHelper::aimDistance;
settings["GrenadeHelper"]["aimFov"] = Settings::GrenadeHelper::aimFov;
LoadColor(settings["GrenadeHelper"]["aimDot"], Settings::GrenadeHelper::aimDot);
LoadColor(settings["GrenadeHelper"]["aimLine"], Settings::GrenadeHelper::aimLine);
LoadColor(settings["GrenadeHelper"]["infoHe"], Settings::GrenadeHelper::infoHE);
LoadColor(settings["GrenadeHelper"]["infoSmoke"], Settings::GrenadeHelper::infoSmoke);
LoadColor(settings["GrenadeHelper"]["infoMolotov"], Settings::GrenadeHelper::infoMolotov);
LoadColor(settings["GrenadeHelper"]["infoFlash"], Settings::GrenadeHelper::infoFlash);
std::ofstream(path) << styledWriter.write(settings);
}
void Settings::LoadConfig(std::string path)
{
if (!std::ifstream(path).good())
{
Settings::LoadDefaultsOrSave(path);
return;
}
Json::Value settings;
std::ifstream configDoc(path, std::ifstream::binary);
configDoc >> settings;
GetVal(settings["UI"]["mainColor"], &Settings::UI::mainColor);
GetVal(settings["UI"]["bodyColor"], &Settings::UI::bodyColor);
GetVal(settings["UI"]["fontColor"], &Settings::UI::fontColor);
GetVal(settings["UI"]["Fonts"]["ESP"]["family"], &Settings::UI::Fonts::ESP::family);
GetVal(settings["UI"]["Fonts"]["ESP"]["size"], &Settings::UI::Fonts::ESP::size);
GetVal(settings["UI"]["Fonts"]["ESP"]["flags"], &Settings::UI::Fonts::ESP::flags);
Fonts::SetupFonts();
Settings::Aimbot::weapons = {
{ ItemDefinitionIndex::INVALID, { false, false, false, Bone::BONE_HEAD, ButtonCode_t::MOUSE_MIDDLE, false, false, 1.0f, SmoothType::SLOW_END, false, 0.0f, false, 0.0f, true, 180.0f, false, 25.0f, false, false, 2.0f, 2.0f, false, false, false, false, false, false, false, false, 10.0f, false, false, false, 5.0f } },
};
for (Json::ValueIterator itr = settings["Aimbot"]["weapons"].begin(); itr != settings["Aimbot"]["weapons"].end(); itr++)
{
std::string weaponDataKey = itr.key().asString();
auto weaponSetting = settings["Aimbot"]["weapons"][weaponDataKey];
// XXX Using exception handling to deal with this is stupid, but I don't care to find a better solution
// XXX We can't use GetOrdinal() since the key type is a string...
ItemDefinitionIndex weaponID;
try
{
weaponID = (ItemDefinitionIndex) std::stoi(weaponDataKey);
}
catch (std::invalid_argument) // Not a number
{
weaponID = Util::Items::GetItemIndex(weaponDataKey);
}
if (Settings::Aimbot::weapons.find(weaponID) == Settings::Aimbot::weapons.end())
Settings::Aimbot::weapons[weaponID] = AimbotWeapon_t();
AimbotWeapon_t weapon = {
weaponSetting["Enabled"].asBool(),
weaponSetting["Silent"].asBool(),
weaponSetting["Friendly"].asBool(),
(Bone) weaponSetting["TargetBone"].asInt(),
Util::GetButtonCode(weaponSetting["AimKey"].asCString()),
weaponSetting["AimKeyOnly"].asBool(),
weaponSetting["Smooth"]["Enabled"].asBool(),
weaponSetting["Smooth"]["Amount"].asFloat(),
(SmoothType) weaponSetting["Smooth"]["Type"].asInt(),
weaponSetting["Smooth"]["Salting"]["Enabled"].asBool(),
weaponSetting["Smooth"]["Salting"]["Multiplier"].asFloat(),
weaponSetting["ErrorMargin"]["Enabled"].asBool(),
weaponSetting["ErrorMargin"]["Value"].asFloat(),
weaponSetting["AutoAim"]["Enabled"].asBool(),
weaponSetting["AutoAim"]["FOV"].asFloat(),
weaponSetting["AimStep"]["Enabled"].asBool(),
weaponSetting["AimStep"]["Amount"].asFloat(),
weaponSetting["RCS"]["Enabled"].asBool(),
weaponSetting["RCS"]["AlwaysOn"].asBool(),
weaponSetting["RCS"]["AmountX"].asFloat(),
weaponSetting["RCS"]["AmountY"].asFloat(),
weaponSetting["AutoPistol"]["Enabled"].asBool(),
weaponSetting["AutoShoot"]["Enabled"].asBool(),
weaponSetting["AutoScope"]["Enabled"].asBool(),
weaponSetting["NoShoot"]["Enabled"].asBool(),
weaponSetting["IgnoreJump"]["Enabled"].asBool(),
weaponSetting["SmokeCheck"]["Enabled"].asBool(),
weaponSetting["FlashCheck"]["Enabled"].asBool(),
weaponSetting["AutoWall"]["Enabled"].asBool(),
weaponSetting["AutoWall"]["Value"].asFloat(),
weaponSetting["AutoAim"]["RealDistance"].asBool(),
weaponSetting["AutoSlow"]["enabled"].asBool(),
weaponSetting["AutoSlow"]["minDamage"].asFloat(),
weaponSetting["Prediction"]["enabled"].asBool()
};
for (int bone = (int) Hitbox::HITBOX_HEAD; bone <= (int) Hitbox::HITBOX_ARMS; bone++)
weapon.autoWallBones[bone] = weaponSetting["AutoWall"]["Bones"][bone].asBool();
Settings::Aimbot::weapons.at(weaponID) = weapon;
}
GetVal(settings["Aimbot"]["AutoCrouch"]["enabled"], &Settings::Aimbot::AutoCrouch::enabled);
GetVal(settings["Resolver"]["resolve_all"], &Settings::Resolver::resolveAll);
GetVal(settings["Triggerbot"]["enabled"], &Settings::Triggerbot::enabled);
GetButtonCode(settings["Triggerbot"]["key"], &Settings::Triggerbot::key);
GetVal(settings["Triggerbot"]["Filters"]["enemies"], &Settings::Triggerbot::Filters::enemies);
GetVal(settings["Triggerbot"]["Filters"]["allies"], &Settings::Triggerbot::Filters::allies);
GetVal(settings["Triggerbot"]["Filters"]["walls"], &Settings::Triggerbot::Filters::walls);
GetVal(settings["Triggerbot"]["Filters"]["smoke_check"], &Settings::Triggerbot::Filters::smokeCheck);
GetVal(settings["Triggerbot"]["Filters"]["flash_check"], &Settings::Triggerbot::Filters::flashCheck);
GetVal(settings["Triggerbot"]["Filters"]["head"], &Settings::Triggerbot::Filters::head);
GetVal(settings["Triggerbot"]["Filters"]["chest"], &Settings::Triggerbot::Filters::chest);
GetVal(settings["Triggerbot"]["Filters"]["stomach"], &Settings::Triggerbot::Filters::stomach);
GetVal(settings["Triggerbot"]["Filters"]["arms"], &Settings::Triggerbot::Filters::arms);
GetVal(settings["Triggerbot"]["Filters"]["legs"], &Settings::Triggerbot::Filters::legs);
GetVal(settings["Triggerbot"]["Delay"]["enabled"], &Settings::Triggerbot::Delay::enabled);
GetVal(settings["Triggerbot"]["Delay"]["value"], &Settings::Triggerbot::Delay::value);
GetVal(settings["AntiAim"]["Yaw"]["enabled"], &Settings::AntiAim::Yaw::enabled);
GetVal(settings["AntiAim"]["Yaw"]["type"], (int*)& Settings::AntiAim::Yaw::type);
GetVal(settings["AntiAim"]["Yaw"]["type_fake"], (int*)& Settings::AntiAim::Yaw::typeFake);
GetVal(settings["AntiAim"]["Yaw"]["antiResolver"], &Settings::AntiAim::Yaw::antiResolver);
GetVal(settings["AntiAim"]["Pitch"]["enabled"], &Settings::AntiAim::Pitch::enabled);
GetVal(settings["AntiAim"]["Pitch"]["type"], (int*)& Settings::AntiAim::Pitch::type);
GetVal(settings["AntiAim"]["HeadEdge"]["enabled"], &Settings::AntiAim::HeadEdge::enabled);
GetVal(settings["AntiAim"]["HeadEdge"]["distance"], &Settings::AntiAim::HeadEdge::distance);
GetVal(settings["AntiAim"]["AutoDisable"]["knife_held"], &Settings::AntiAim::AutoDisable::knifeHeld);
GetVal(settings["AntiAim"]["AutoDisable"]["no_enemy"], &Settings::AntiAim::AutoDisable::noEnemy);
GetVal(settings["ESP"]["enabled"], &Settings::ESP::enabled);
GetVal(settings["ESP"]["enemy_color"], &Settings::ESP::enemyColor);
GetVal(settings["ESP"]["enemy_visible_color"], &Settings::ESP::enemyVisibleColor);
GetVal(settings["ESP"]["ally_color"], &Settings::ESP::allyColor);
GetVal(settings["ESP"]["ally_visible_color"], &Settings::ESP::allyVisibleColor);
GetVal(settings["ESP"]["t_color"], &Settings::ESP::tColor);
GetVal(settings["ESP"]["t_visible_color"], &Settings::ESP::tVisibleColor);
GetVal(settings["ESP"]["ct_color"], &Settings::ESP::ctColor);
GetVal(settings["ESP"]["ct_visible_color"], &Settings::ESP::ctVisibleColor);
GetVal(settings["ESP"]["localplayer_color"], &Settings::ESP::localplayerColor);
GetVal(settings["ESP"]["bomb_color"], &Settings::ESP::bombColor);
GetVal(settings["ESP"]["bomb_defusing_color"], &Settings::ESP::bombDefusingColor);
GetVal(settings["ESP"]["hostage_color"], &Settings::ESP::hostageColor);
GetVal(settings["ESP"]["defuser_color"], &Settings::ESP::defuserColor);
GetVal(settings["ESP"]["weapon_color"], &Settings::ESP::weaponColor);
GetVal(settings["ESP"]["chicken_color"], &Settings::ESP::chickenColor);
GetVal(settings["ESP"]["fish_color"], &Settings::ESP::fishColor);
GetVal(settings["ESP"]["smoke_color"], &Settings::ESP::smokeColor);
GetVal(settings["ESP"]["decoy_color"], &Settings::ESP::decoyColor);
GetVal(settings["ESP"]["flashbang_color"], &Settings::ESP::flashbangColor);
GetVal(settings["ESP"]["grenade_color"], &Settings::ESP::grenadeColor);
GetVal(settings["ESP"]["molotov_color"], &Settings::ESP::molotovColor);
GetVal(settings["ESP"]["Glow"]["enabled"], &Settings::ESP::Glow::enabled);
GetVal(settings["ESP"]["Glow"]["ally_color"], &Settings::ESP::Glow::allyColor);
GetVal(settings["ESP"]["Glow"]["enemy_color"], &Settings::ESP::Glow::enemyColor);
GetVal(settings["ESP"]["Glow"]["enemy_visible_color"], &Settings::ESP::Glow::enemyVisibleColor);
GetVal(settings["ESP"]["Glow"]["localplayer_color"], &Settings::ESP::Glow::localplayerColor);
GetVal(settings["ESP"]["Glow"]["weapon_color"], &Settings::ESP::Glow::weaponColor);
GetVal(settings["ESP"]["Glow"]["grenade_color"], &Settings::ESP::Glow::grenadeColor);
GetVal(settings["ESP"]["Glow"]["defuser_color"], &Settings::ESP::Glow::defuserColor);
GetVal(settings["ESP"]["Glow"]["chicken_color"], &Settings::ESP::Glow::chickenColor);
GetVal(settings["ESP"]["Filters"]["legit"], &Settings::ESP::Filters::legit);
GetVal(settings["ESP"]["Filters"]["visibility_check"], &Settings::ESP::Filters::visibilityCheck);
GetVal(settings["ESP"]["Filters"]["smoke_check"], &Settings::ESP::Filters::smokeCheck);
GetVal(settings["ESP"]["Filters"]["enemies"], &Settings::ESP::Filters::enemies);
GetVal(settings["ESP"]["Filters"]["allies"], &Settings::ESP::Filters::allies);
GetVal(settings["ESP"]["Filters"]["bomb"], &Settings::ESP::Filters::bomb);
GetVal(settings["ESP"]["Filters"]["hostages"], &Settings::ESP::Filters::hostages);
GetVal(settings["ESP"]["Filters"]["defusers"], &Settings::ESP::Filters::defusers);
GetVal(settings["ESP"]["Filters"]["weapons"], &Settings::ESP::Filters::weapons);
GetVal(settings["ESP"]["Filters"]["chickens"], &Settings::ESP::Filters::chickens);
GetVal(settings["ESP"]["Filters"]["fishes"], &Settings::ESP::Filters::fishes);
GetVal(settings["ESP"]["Filters"]["throwables"], &Settings::ESP::Filters::throwables);
GetVal(settings["ESP"]["Filters"]["localplayer"], &Settings::ESP::Filters::localplayer);
GetVal(settings["ESP"]["Info"]["name"], &Settings::ESP::Info::name);
GetVal(settings["ESP"]["Info"]["clan"], &Settings::ESP::Info::clan);
GetVal(settings["ESP"]["Info"]["steam_id"], &Settings::ESP::Info::steamId);
GetVal(settings["ESP"]["Info"]["rank"], &Settings::ESP::Info::rank);
GetVal(settings["ESP"]["Info"]["health"], &Settings::ESP::Info::health);
GetVal(settings["ESP"]["Info"]["weapon"], &Settings::ESP::Info::weapon);
GetVal(settings["ESP"]["Info"]["scoped"], &Settings::ESP::Info::scoped);
GetVal(settings["ESP"]["Info"]["reloading"], &Settings::ESP::Info::reloading);
GetVal(settings["ESP"]["Info"]["flashed"], &Settings::ESP::Info::flashed);
GetVal(settings["ESP"]["Info"]["planting"], &Settings::ESP::Info::planting);
GetVal(settings["ESP"]["Info"]["has_defuser"], &Settings::ESP::Info::hasDefuser);
GetVal(settings["ESP"]["Info"]["defusing"], &Settings::ESP::Info::defusing);
GetVal(settings["ESP"]["Info"]["grabbing_hostage"], &Settings::ESP::Info::grabbingHostage);
GetVal(settings["ESP"]["Info"]["rescuing"], &Settings::ESP::Info::rescuing);
GetVal(settings["ESP"]["Info"]["location"], &Settings::ESP::Info::location);
GetVal(settings["ESP"]["Boxes"]["enabled"], &Settings::ESP::Boxes::enabled);
GetVal(settings["ESP"]["Boxes"]["type"], (int*)& Settings::ESP::Boxes::type);
GetVal(settings["ESP"]["Skeleton"]["enabled"], &Settings::ESP::Skeleton::enabled);
GetVal(settings["ESP"]["Skeleton"]["color"], &Settings::ESP::Skeleton::color);
GetVal(settings["ESP"]["Bars"]["enabled"], &Settings::ESP::Bars::enabled);
GetVal(settings["ESP"]["Bars"]["color_type"], (int*)& Settings::ESP::Bars::colorType);
GetVal(settings["ESP"]["Bars"]["type"], (int*)& Settings::ESP::Bars::type);
GetVal(settings["ESP"]["Tracers"]["enabled"], &Settings::ESP::Tracers::enabled);
GetVal(settings["ESP"]["Tracers"]["type"], (int*)& Settings::ESP::Tracers::type);
GetVal(settings["ESP"]["BulletTracers"]["enabled"], &Settings::ESP::BulletTracers::enabled);
GetVal(settings["ESP"]["FOVCrosshair"]["enabled"], &Settings::ESP::FOVCrosshair::enabled);
GetVal(settings["ESP"]["FOVCrosshair"]["filled"], &Settings::ESP::FOVCrosshair::filled);
GetVal(settings["ESP"]["FOVCrosshair"]["color"], &Settings::ESP::FOVCrosshair::color);
GetVal(settings["ESP"]["Chams"]["Arms"]["enabled"], &Settings::ESP::Chams::Arms::enabled);
GetVal(settings["ESP"]["Chams"]["Arms"]["type"], (int*)& Settings::ESP::Chams::Arms::type);
GetVal(settings["ESP"]["Chams"]["Arms"]["color"], &Settings::ESP::Chams::Arms::color);
GetVal(settings["ESP"]["Chams"]["Weapon"]["enabled"], &Settings::ESP::Chams::Weapon::enabled);
GetVal(settings["ESP"]["Chams"]["Weapon"]["color"], &Settings::ESP::Chams::Weapon::color);
GetVal(settings["ESP"]["Chams"]["players_ally_color"], &Settings::ESP::Chams::allyColor);
GetVal(settings["ESP"]["Chams"]["players_ally_visible_color"], &Settings::ESP::Chams::allyVisibleColor);
GetVal(settings["ESP"]["Chams"]["players_enemy_color"], &Settings::ESP::Chams::enemyColor);
GetVal(settings["ESP"]["Chams"]["players_enemy_visible_color"], &Settings::ESP::Chams::enemyVisibleColor);
GetVal(settings["ESP"]["Chams"]["localplayer_color"], &Settings::ESP::Chams::localplayerColor);
GetVal(settings["ESP"]["Chams"]["type"], (int*)& Settings::ESP::Chams::type);
GetVal(settings["ESP"]["Chams"]["enabled"], &Settings::ESP::Chams::enabled);
GetVal(settings["ESP"]["Sounds"]["enabled"], &Settings::ESP::Sounds::enabled);
GetVal(settings["ESP"]["Sounds"]["time"], &Settings::ESP::Sounds::time);
GetVal(settings["ESP"]["Hitmarker"]["enabled"], &Settings::ESP::Hitmarker::enabled);
GetVal(settings["ESP"]["Hitmarker"]["enemies"], &Settings::ESP::Hitmarker::enemies);
GetVal(settings["ESP"]["Hitmarker"]["allies"], &Settings::ESP::Hitmarker::allies);
GetVal(settings["ESP"]["Hitmarker"]["color"], &Settings::ESP::Hitmarker::color);
GetVal(settings["ESP"]["Hitmarker"]["duration"], &Settings::ESP::Hitmarker::duration);
GetVal(settings["ESP"]["Hitmarker"]["size"], &Settings::ESP::Hitmarker::size);
GetVal(settings["ESP"]["Hitmarker"]["inner_gap"], &Settings::ESP::Hitmarker::innerGap);
GetVal(settings["ESP"]["Hitmarker"]["Damage"]["enabled"], &Settings::ESP::Hitmarker::Damage::enabled);
GetVal(settings["ESP"]["HeadDot"]["enabled"], &Settings::ESP::HeadDot::enabled);
GetVal(settings["ESP"]["HeadDot"]["size"], &Settings::ESP::HeadDot::size);
GetVal(settings["Dlights"]["enabled"], &Settings::Dlights::enabled);
GetVal(settings["Dlights"]["radius"], &Settings::Dlights::radius);
GetVal(settings["Spammer"]["spammer_type"], (int*)& Settings::Spammer::type);
GetVal(settings["Spammer"]["say_team"], &Settings::Spammer::say_team);
GetVal(settings["Spammer"]["KillSpammer"]["enabled"], &Settings::Spammer::KillSpammer::enabled);
GetVal(settings["Spammer"]["KillSpammer"]["say_team"], &Settings::Spammer::KillSpammer::sayTeam);
if (!settings["Spammer"]["KillSpammer"]["messages"].isNull())
{
Settings::Spammer::KillSpammer::messages.clear();
for (const Json::Value& message : settings["Spammer"]["KillSpammer"]["messages"])
Settings::Spammer::KillSpammer::messages.push_back(message.asString());
}
if (!settings["Spammer"]["NormalSpammer"]["messages"].isNull())
{
Settings::Spammer::NormalSpammer::messages.clear();
for (const Json::Value& message : settings["Spammer"]["NormalSpammer"]["messages"])
Settings::Spammer::NormalSpammer::messages.push_back(message.asString());
}
GetVal(settings["Spammer"]["PositionSpammer"]["show_name"], &Settings::Spammer::PositionSpammer::showName);
GetVal(settings["Spammer"]["PositionSpammer"]["show_weapon"], &Settings::Spammer::PositionSpammer::showWeapon);
GetVal(settings["Spammer"]["PositionSpammer"]["show_rank"], &Settings::Spammer::PositionSpammer::showRank);
GetVal(settings["Spammer"]["PositionSpammer"]["show_wins"], &Settings::Spammer::PositionSpammer::showWins);
GetVal(settings["Spammer"]["PositionSpammer"]["show_health"], &Settings::Spammer::PositionSpammer::showHealth);
GetVal(settings["Spammer"]["PositionSpammer"]["show_money"], &Settings::Spammer::PositionSpammer::showMoney);
GetVal(settings["Spammer"]["PositionSpammer"]["show_lastplace"], &Settings::Spammer::PositionSpammer::showLastplace);
GetVal(settings["BHop"]["enabled"], &Settings::BHop::enabled);
GetVal(settings["AutoStrafe"]["enabled"], &Settings::AutoStrafe::enabled);
GetVal(settings["AutoStrafe"]["type"], (int*)& Settings::AutoStrafe::type);
GetVal(settings["AutoStrafe"]["silent"], &Settings::AutoStrafe::silent);
GetVal(settings["Noflash"]["enabled"], &Settings::Noflash::enabled);
GetVal(settings["Noflash"]["value"], &Settings::Noflash::value);
GetVal(settings["Radar"]["enabled"], &Settings::Radar::enabled);
GetVal(settings["Radar"]["zoom"], &Settings::Radar::zoom);
GetVal(settings["Radar"]["enemies"], &Settings::Radar::enemies);
GetVal(settings["Radar"]["allies"], &Settings::Radar::allies);
GetVal(settings["Radar"]["legit"], &Settings::Radar::legit);
GetVal(settings["Radar"]["visibility_check"], &Settings::Radar::visibilityCheck);
GetVal(settings["Radar"]["smoke_check"], &Settings::Radar::smokeCheck);
GetVal(settings["Radar"]["InGame"]["enabled"], &Settings::Radar::InGame::enabled);
GetVal(settings["Radar"]["enemy_color"], &Settings::Radar::enemyColor);
GetVal(settings["Radar"]["enemy_visible_color"], &Settings::Radar::enemyVisibleColor);
GetVal(settings["Radar"]["ally_color"], &Settings::Radar::allyColor);
GetVal(settings["Radar"]["ally_visible_color"], &Settings::Radar::allyVisibleColor);
GetVal(settings["Radar"]["t_color"], &Settings::Radar::tColor);
GetVal(settings["Radar"]["t_visible_color"], &Settings::Radar::tVisibleColor);
GetVal(settings["Radar"]["ct_color"], &Settings::Radar::ctColor);
GetVal(settings["Radar"]["ct_visible_color"], &Settings::Radar::ctVisibleColor);
GetVal(settings["Radar"]["bomb_color"], &Settings::Radar::bombColor);
GetVal(settings["Radar"]["bomb_defusing_color"], &Settings::Radar::bombDefusingColor);
GetVal(settings["Radar"]["icons_scale"], &Settings::Radar::iconsScale);
GetVal(settings["Recoilcrosshair"]["enabled"], &Settings::Recoilcrosshair::enabled);
GetVal(settings["Recoilcrosshair"]["showOnlyWhenShooting"], &Settings::Recoilcrosshair::showOnlyWhenShooting);
GetVal(settings["FOVChanger"]["enabled"], &Settings::FOVChanger::enabled);
GetVal(settings["FOVChanger"]["value"], &Settings::FOVChanger::value);
GetVal(settings["FOVChanger"]["viewmodel_enabled"], &Settings::FOVChanger::viewmodelEnabled);
GetVal(settings["FOVChanger"]["viewmodel_value"], &Settings::FOVChanger::viewmodelValue);
GetVal(settings["FOVChanger"]["ignore_scope"], &Settings::FOVChanger::ignoreScope);
GetVal(settings["Airstuck"]["enabled"], &Settings::Airstuck::enabled);
GetButtonCode(settings["Airstuck"]["key"], &Settings::Airstuck::key);
Settings::Skinchanger::Skins::enabled = false;
Settings::Skinchanger::skinsCT.clear();
Settings::Skinchanger::skinsT.clear();
for (Json::ValueIterator itr = settings["SkinChanger"]["skinsCT"].begin(); itr != settings["SkinChanger"]["skinsCT"].end(); itr++)
{
std::string skinDataKey = itr.key().asString();
auto skinSetting = settings["SkinChanger"]["skinsCT"][skinDataKey];
// XXX Using exception handling to deal with this is stupid, but I don't care to find a better solution
// XXX We can't use GetOrdinal() since the key type is a string...
unsigned int weaponID;
try
{
weaponID = std::stoi(skinDataKey);
}
catch(std::invalid_argument)
{
weaponID = (int) Util::Items::GetItemIndex(skinDataKey);
}
ItemDefinitionIndex defIndex;
GetOrdinal<ItemDefinitionIndex, Util::Items::GetItemIndex>(skinSetting["ItemDefinitionIndex"], &defIndex);
if (Settings::Skinchanger::skinsCT.find((ItemDefinitionIndex) weaponID) == Settings::Skinchanger::skinsCT.end())
Settings::Skinchanger::skinsCT[(ItemDefinitionIndex) weaponID] = AttribItem_t();
AttribItem_t skin = {
defIndex,
skinSetting["PaintKit"].asInt(),
skinSetting["Wear"].asFloat(),
skinSetting["Seed"].asInt(),
skinSetting["StatTrak"].asInt(),
-1,
skinSetting["CustomName"].asString(),
};
Settings::Skinchanger::skinsCT.at((ItemDefinitionIndex) weaponID) = skin;
}
for (Json::ValueIterator itr = settings["SkinChanger"]["skinsT"].begin(); itr != settings["SkinChanger"]["skinsT"].end(); itr++)
{
std::string skinDataKey = itr.key().asString();
auto skinSetting = settings["SkinChanger"]["skinsT"][skinDataKey];
// XXX Using exception handling to deal with this is stupid, but I don't care to find a better solution
// XXX We can't use GetOrdinal() since the key type is a string...
unsigned int weaponID;
try
{
weaponID = std::stoi(skinDataKey);
}
catch(std::invalid_argument)
{
weaponID = (int) Util::Items::GetItemIndex(skinDataKey);
}
ItemDefinitionIndex defIndex;
GetOrdinal<ItemDefinitionIndex, Util::Items::GetItemIndex>(skinSetting["ItemDefinitionIndex"], &defIndex);
if (Settings::Skinchanger::skinsT.find((ItemDefinitionIndex) weaponID) == Settings::Skinchanger::skinsT.end())
Settings::Skinchanger::skinsT[(ItemDefinitionIndex) weaponID] = AttribItem_t();
AttribItem_t skin = {
defIndex,
skinSetting["PaintKit"].asInt(),
skinSetting["Wear"].asFloat(),
skinSetting["Seed"].asInt(),
skinSetting["StatTrak"].asInt(),
-1,
skinSetting["CustomName"].asString(),
};
Settings::Skinchanger::skinsT.at((ItemDefinitionIndex) weaponID) = skin;
}
SkinChanger::forceFullUpdate = true;
GetVal(settings["SkinChanger"]["Skins"]["enabled"], &Settings::Skinchanger::Skins::enabled);
GetVal(settings["SkinChanger"]["Models"]["enabled"], &Settings::Skinchanger::Models::enabled);
GetVal(settings["SkinChanger"]["Skins"]["perTeam"], &Settings::Skinchanger::Skins::perTeam);
GetVal(settings["ShowRanks"]["enabled"], &Settings::ShowRanks::enabled);
GetVal(settings["ShowSpectators"]["enabled"], &Settings::ShowSpectators::enabled);
GetVal(settings["ClanTagChanger"]["value"], (char *)& Settings::ClanTagChanger::value);
GetVal(settings["ClanTagChanger"]["enabled"], &Settings::ClanTagChanger::enabled);
GetVal(settings["ClanTagChanger"]["animation"], &Settings::ClanTagChanger::animation);
GetVal(settings["ClanTagChanger"]["animation_speed"], &Settings::ClanTagChanger::animationSpeed);
GetVal(settings["ClanTagChanger"]["type"], (int*)& Settings::ClanTagChanger::type);
::ClanTagChanger::UpdateClanTagCallback();
GetVal(settings["View"]["NoViewPunch"]["enabled"], &Settings::View::NoViewPunch::enabled);
GetVal(settings["View"]["NoAimPunch"]["enabled"], &Settings::View::NoAimPunch::enabled);
GetVal(settings["Teleport"]["enabled"], &Settings::Teleport::enabled);
GetButtonCode(settings["Teleport"]["key"], &Settings::Teleport::key);
GetVal(settings["FakeLag"]["enabled"], &Settings::FakeLag::enabled);
GetVal(settings["FakeLag"]["value"], &Settings::FakeLag::value);
GetVal(settings["FakeLag"]["adaptive"], &Settings::FakeLag::adaptive);
GetVal(settings["AutoAccept"]["enabled"], &Settings::AutoAccept::enabled);
GetVal(settings["NoSky"]["enabled"], &Settings::NoSky::enabled);
GetVal(settings["NoSky"]["color"], &Settings::NoSky::color);
GetVal(settings["ASUSWalls"]["enabled"], &Settings::ASUSWalls::enabled);
GetVal(settings["ASUSWalls"]["color"], &Settings::ASUSWalls::color);
GetVal(settings["NoScopeBorder"]["enabled"], &Settings::NoScopeBorder::enabled);
GetVal(settings["SniperCrosshair"]["enabled"], &Settings::SniperCrosshair::enabled);
GetVal(settings["Autoblock"]["enabled"], &Settings::Autoblock::enabled);
GetButtonCode(settings["Autoblock"]["key"], &Settings::Autoblock::key);
GetVal(settings["AutoDefuse"]["enabled"], &Settings::AutoDefuse::enabled);
GetVal(settings["NoSmoke"]["enabled"], &Settings::NoSmoke::enabled);
GetVal(settings["ScreenshotCleaner"]["enabled"], &Settings::ScreenshotCleaner::enabled);
GetVal(settings["EdgeJump"]["enabled"], &Settings::EdgeJump::enabled);
GetButtonCode(settings["EdgeJump"]["key"], &Settings::EdgeJump::key);
GetVal(settings["NameStealer"]["enabled"], &Settings::NameStealer::enabled);
GetVal(settings["NameStealer"]["team"], &Settings::NameStealer::team);
GetVal(settings["ThirdPerson"]["enabled"], &Settings::ThirdPerson::enabled);
GetVal(settings["ThirdPerson"]["distance"], &Settings::ThirdPerson::distance);
GetVal(settings["JumpThrow"]["enabled"], &Settings::JumpThrow::enabled);
GetButtonCode(settings["JumpThrow"]["key"], &Settings::JumpThrow::key);
GetVal(settings["DisablePostProcessing"]["enabled"], &Settings::DisablePostProcessing::enabled);
GetVal(settings["GrenadeHelper"]["enabled"], &Settings::GrenadeHelper::enabled);
GetVal(settings["GrenadeHelper"]["aimAssist"], &Settings::GrenadeHelper::aimAssist);
GetVal(settings["GrenadeHelper"]["OnlyMatching"], &Settings::GrenadeHelper::onlyMatchingInfos);
GetVal(settings["GrenadeHelper"]["aimStep"], &Settings::GrenadeHelper::aimStep);
GetVal(settings["GrenadeHelper"]["aimDistance"], &Settings::GrenadeHelper::aimDistance);
GetVal(settings["GrenadeHelper"]["aimFov"], &Settings::GrenadeHelper::aimFov);
GetVal(settings["GrenadeHelper"]["aimDot"], &Settings::GrenadeHelper::aimDot);
GetVal(settings["GrenadeHelper"]["aimLine"], &Settings::GrenadeHelper::aimLine);
GetVal(settings["GrenadeHelper"]["infoHE"], &Settings::GrenadeHelper::infoHE);
GetVal(settings["GrenadeHelper"]["infoSmoke"], &Settings::GrenadeHelper::infoSmoke);
GetVal(settings["GrenadeHelper"]["infoFlash"], &Settings::GrenadeHelper::infoFlash);
GetVal(settings["GrenadeHelper"]["infoMolotov"], &Settings::GrenadeHelper::infoMolotov);
}
void Settings::LoadSettings()
{
pstring directory = getenv("HOME");
directory << "/.config";
if (!DoesDirectoryExist(directory.c_str()))
mkdir(directory.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
directory << "/AimTux/";
if (!DoesDirectoryExist(directory.c_str()))
mkdir(directory.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
void Settings::SaveGrenadeInfo(std::string path)
{
Json::Value grenadeInfos;
for (auto grenadeInfo = GrenadeHelper::grenadeInfos.begin(); grenadeInfo != GrenadeHelper::grenadeInfos.end(); grenadeInfo++)
{
Json::Value act;
act["name"] = grenadeInfo->name.c_str();
act["gType"] = grenadeInfo->gType;
act["tType"] = grenadeInfo->tType;
act["pos"]["x"] = grenadeInfo->pos.x;
act["pos"]["y"] = grenadeInfo->pos.y;
act["pos"]["z"] = grenadeInfo->pos.z;
act["angle"]["x"] = grenadeInfo->angle.x;
act["angle"]["y"] = grenadeInfo->angle.y;
grenadeInfos.append(act);
}
Json::Value data;
Json::StyledWriter styledWriter;
data["smokeinfos"] = grenadeInfos;
std::ofstream(path) << styledWriter.write(data);
}
void Settings::LoadGrenadeInfo(std::string path)
{
if (!std::ifstream(path).good() || !DoesFileExist(path.c_str()))
return;
Json::Value data;
std::ifstream configDoc(path, std::ifstream::binary);
try {
configDoc >> data;
}
catch (...)
{
cvar->ConsoleDPrintf("Error parsing the config file.\n");
return;
}
Json::Value array = data["smokeinfos"];
Settings::GrenadeHelper::grenadeInfos = {};
for(Json::Value::iterator it = array.begin(); it!=array.end(); ++it)
{
Json::Value act = *it;
const char* name = act["name"].asCString();
GrenadeType gType = (GrenadeType)act["gType"].asInt();
ThrowType tType = (ThrowType)act["tType"].asInt();
Json::Value pos = act["pos"];
Vector posVec = Vector(pos["x"].asFloat(), pos["y"].asFloat(), pos["z"].asFloat());
Json::Value angle = act["angle"];
QAngle vAngle = QAngle(angle["x"].asFloat(), angle["y"].asFloat(), 0);
Settings::GrenadeHelper::grenadeInfos.push_back(GrenadeInfo(gType, posVec, vAngle, tType, pstring(name)));
}
}
void remove_directory(const char* path)
{
DIR* dir;
dirent* pdir;
dir = opendir(path);
while ((pdir = readdir(dir)))
{
if (strcmp(pdir->d_name, ".") == 0 || strcmp(pdir->d_name, "..") == 0)
continue;
if (pdir->d_type == DT_DIR)
{
pstring _dir;
_dir << path << "/" << pdir->d_name;
remove_directory(_dir.c_str());
}
else if (pdir->d_type == DT_REG)
{
pstring file;
file << path << "/" << pdir->d_name;
unlink(file.c_str());
}
}
rmdir(path);
}
void Settings::DeleteConfig(std::string path)
{
remove_directory(path.c_str());
}
| 412 | 0.881388 | 1 | 0.881388 | game-dev | MEDIA | 0.347915 | game-dev | 0.862148 | 1 | 0.862148 |
Fluorohydride/ygopro-scripts | 3,270 | c43150717.lua | --Xyz Lay
local s,id,o=GetID()
function s.initial_effect(c)
--Equip
local e1=aux.AddEquipSpellEffect(c,true,true,Card.IsFaceup,nil)
e1:SetCountLimit(1,id+EFFECT_COUNT_CODE_OATH)
c:RegisterEffect(e1)
--set
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_SZONE)
e2:SetCountLimit(1,EFFECT_COUNT_CODE_SINGLE)
e2:SetCondition(s.setcon)
e2:SetCost(s.setcost)
e2:SetTarget(s.settg)
e2:SetOperation(s.setop)
c:RegisterEffect(e2)
--spsummon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(id,2))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_SZONE)
e3:SetCountLimit(1,EFFECT_COUNT_CODE_SINGLE)
e3:SetCondition(s.spcon)
e3:SetTarget(s.sptg)
e3:SetOperation(s.spop)
c:RegisterEffect(e3)
--atkup
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_EQUIP)
e4:SetCode(EFFECT_UPDATE_ATTACK)
e4:SetValue(s.atkval)
c:RegisterEffect(e4)
end
function s.setcon(e,tp,eg,ep,ev,re,r,rp)
local ec=e:GetHandler():GetEquipTarget()
return ec and ec:IsType(TYPE_XYZ)
end
function s.setcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckRemoveOverlayCard(tp,1,0,2,REASON_COST) end
Duel.RemoveOverlayCard(tp,1,0,2,2,REASON_COST)
end
function s.setfilter(c)
return c:IsSetCard(0x73) and c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsSSetable()
end
function s.settg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.setfilter,tp,LOCATION_DECK,0,1,nil) end
end
function s.setop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET)
local g=Duel.SelectMatchingCard(tp,s.setfilter,tp,LOCATION_DECK,0,1,1,nil)
local tc=g:GetFirst()
if tc then
Duel.SSet(tp,tc)
end
end
function s.spcon(e,tp,eg,ep,ev,re,r,rp)
local ec=e:GetHandler():GetEquipTarget()
return ec and not ec:IsType(TYPE_XYZ)
end
function s.spfilter(c,e,tp,lv)
return c:IsLevel(lv)
and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local ec=e:GetHandler():GetEquipTarget()
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and ec:IsLevelAbove(1)
and Duel.IsExistingMatchingCard(s.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp,ec:GetLevel()) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local ec=e:GetHandler():GetEquipTarget()
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,s.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp,ec:GetLevel())
local sc=g:GetFirst()
if #g>0 and Duel.SpecialSummonStep(sc,0,tp,tp,false,false,POS_FACEUP_DEFENSE) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
sc:RegisterEffect(e1)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetValue(RESET_TURN_SET)
e2:SetReset(RESET_EVENT+RESETS_STANDARD)
sc:RegisterEffect(e2)
end
Duel.SpecialSummonComplete()
end
function s.atkval(e,c)
return Duel.GetOverlayCount(e:GetHandlerPlayer(),1,1)*200
end
| 412 | 0.897426 | 1 | 0.897426 | game-dev | MEDIA | 0.987033 | game-dev | 0.944146 | 1 | 0.944146 |
kunitoki/yup | 1,180 | thirdparty/rive/source/animation/listener_align_target.cpp | #include "rive/animation/listener_align_target.hpp"
#include "rive/animation/state_machine_instance.hpp"
#include "rive/node.hpp"
#include "rive/constraints/constraint.hpp"
using namespace rive;
void ListenerAlignTarget::perform(StateMachineInstance* stateMachineInstance,
Vec2D position,
Vec2D previousPosition) const
{
auto coreTarget = stateMachineInstance->artboard()->resolve(targetId());
if (coreTarget == nullptr || !coreTarget->is<Node>())
{
return;
}
auto target = coreTarget->as<Node>();
Mat2D targetParentWorld = getParentWorld(*target);
Mat2D inverse;
if (!targetParentWorld.invert(&inverse))
{
return;
}
if (preserveOffset())
{
auto localPosition = inverse * position;
auto prevLocalPosition = inverse * previousPosition;
target->x(target->x() + localPosition.x - prevLocalPosition.x);
target->y(target->y() + localPosition.y - prevLocalPosition.y);
}
else
{
auto localPosition = inverse * position;
target->x(localPosition.x);
target->y(localPosition.y);
}
}
| 412 | 0.888377 | 1 | 0.888377 | game-dev | MEDIA | 0.933595 | game-dev | 0.945249 | 1 | 0.945249 |
xiaoyaocz/biliuwp | 5,750 | BiliBili.UWP/Modules/RankVM.cs | using BiliBili.UWP.Api;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BiliBili.UWP.Modules
{
public class RankVM : IModules
{
readonly Api.RankAPI rankAPI;
public RankVM()
{
rankAPI = new Api.RankAPI();
TypeFilter = new List<RankFilterItem>()
{
new RankFilterItem()
{
id=1,
name="全站"
},
new RankFilterItem()
{
id=2,
name="原创"
}
};
SelectTypeFilter = TypeFilter[0];
DayFilter = new List<RankFilterItem>() {
new RankFilterItem()
{
id=1,
name="日排行"
},
new RankFilterItem()
{
id=3,
name="3日排行"
},
new RankFilterItem()
{
id=7,
name="周排行"
},
new RankFilterItem()
{
id=30,
name="月排行"
}
};
SelectDayFilter = DayFilter[0];
List<RankRegionModel> regions = new List<RankRegionModel>() {
new RankRegionModel()
{
name="全站",
rid=0,
},
new RankRegionModel()
{
name="国创相关",
rid=168,
}
};
foreach (var item in ApiHelper.regions.Where(x => x.children != null && x.children.Count != 0&&x.tid!=13&& x.tid != 167 && x.name != "广告"))
{
regions.Add(new RankRegionModel() {
name=item.name,
rid=item.tid
});
}
RegionItems = regions;
}
private bool _loading = true;
public bool Loading
{
get { return _loading; }
set { _loading = value; DoPropertyChanged("Loading"); }
}
private RankRegionModel _current;
public RankRegionModel Current
{
get { return _current; }
set { _current = value; DoPropertyChanged("Current"); }
}
private List<RankRegionModel> _RegionItems;
public List<RankRegionModel> RegionItems
{
get { return _RegionItems; }
set { _RegionItems = value; DoPropertyChanged("RegionItems"); }
}
private RankFilterItem _SelectDayFilter;
public RankFilterItem SelectDayFilter
{
get { return _SelectDayFilter; }
set { _SelectDayFilter = value; }
}
public List<RankFilterItem> DayFilter { get; set; }
private RankFilterItem _SelectTypeFilter;
public RankFilterItem SelectTypeFilter
{
get { return _SelectTypeFilter; }
set { _SelectTypeFilter = value; }
}
public List<RankFilterItem> TypeFilter { get; set; }
public async Task LoadRankDetail(RankRegionModel region)
{
try
{
Loading = true;
var results = await rankAPI.Rank(region.rid, SelectTypeFilter.id, SelectDayFilter.id).Request();
if (results.status)
{
var data = await results.GetJson<ApiDataModel<JObject>>();
if (data.success)
{
var result = JsonConvert.DeserializeObject<List<RankItemModel>>(data.data["list"].ToString());
int i = 1;
result = result.Take(36).ToList();
foreach (var item in result)
{
item.rank = i;
i++;
}
region.Items = result;
}
else
{
Utils.ShowMessageToast(data.message);
}
}
else
{
Utils.ShowMessageToast(results.message);
}
}
catch (Exception ex)
{
var handel = HandelError<ApiDataModel<List<RankRegionModel>>>(ex);
Utils.ShowMessageToast(handel.message);
}
finally
{
Loading = false;
}
}
}
public class RankRegionModel : IModules
{
public string name { get; set; }
public int rid { get; set; }
private List<RankItemModel> _Items;
public List<RankItemModel> Items
{
get { return _Items; }
set { _Items = value; DoPropertyChanged("Items"); }
}
}
public class RankFilterItem
{
public string name { get; set; }
public int id { get; set; }
}
public class RankItemModel
{
public int rank { get; set; }
public string aid { get; set; }
public string author { get; set; }
public string mid { get; set; }
public int coins { get; set; }
public int pts { get; set; }
public string duration { get; set; }
public string pic { get; set; }
public string title { get; set; }
public int video_review { get; set; }
public int play { get; set; }
}
}
| 412 | 0.783011 | 1 | 0.783011 | game-dev | MEDIA | 0.782965 | game-dev | 0.946072 | 1 | 0.946072 |
flyver/Flyver-SDK | 25,214 | FlyverCore/src/main/java/co/flyver/flyvercore/MainControllers/MainController.java | package co.flyver.flyvercore.MainControllers;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.os.Environment;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import co.flyver.IPC.IPCContainers;
import co.flyver.IPC.IPCKeys;
import co.flyver.IPC.JSONUtils;
import co.flyver.androidrc.Server.Server;
import co.flyver.androidrc.Server.Status;
import co.flyver.androidrc.Server.interfaces.ServerCallback;
import co.flyver.dataloggerlib.LoggerService;
import co.flyver.flyvercore.DroneTypes.Drone;
import co.flyver.flyvercore.DroneTypes.QuadCopterX;
import co.flyver.flyvercore.MicroControllers.MicroController;
import co.flyver.flyvercore.PIDControllers.PIDAngleController;
import co.flyver.flyvercore.R;
import co.flyver.flyvercore.StateData.Battery;
import co.flyver.flyvercore.StateData.DroneState;
import co.flyver.flyvercore.StateData.LocationServicesProvider;
import co.flyver.flyvercore.StateData.LocationServicesSubsciber;
import co.flyver.flyvercore.StateData.SensorsWrapper;
import co.flyver.utils.flyverMQ.FlyverMQ;
import co.flyver.utils.flyverMQ.FlyverMQMessage;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQConsumer;
import ioio.lib.spi.Log;
import static co.flyver.flyvercore.StateData.Battery.BatteryCells;
/**
* The MainController is the heart of Flyver
* The MainController initialized all the controllers and control algorithms
* TODO: Vertical stabilization, GPS and more
* TODO: Break the MainController into smaller managable pieces
* TODO: Extract the MainController as an interface
*/
public class MainController extends Activity {
/* CONSTANTS*/
public static final double MAX_MOTOR_POWER = 1023.0;
public static final long INT_MAX = Integer.MAX_VALUE;
public static final float MAX_SAFE_PITCH_ROLL = 45; // [deg].
public static final float PID_DERIV_SMOOTHING = 0.5f;
private static final String CONTROLLER = "CONTROLLER";
/* END OF*/
private static MainController instance;
private MicroController microController;
private Battery battery;
private Drone drone;
private float meanThrust;
private float yawAngleTarget;
private float pitchAngleTarget;
private float rollAngleTarget;
private float altitudeTarget;
private float timeWithoutPcRx;
private float timeWithoutAdkRx;
private DroneState droneState;
private Drone.MotorPowers motorsPowers;
private boolean regulatorEnabled;
private boolean altitudeLockEnabled;
private PIDAngleController yawController;
private PIDAngleController pitchController;
private PIDAngleController rollController;
private DroneState.DroneStateData droneStateData;
private long previousTime;
private boolean zeroStateFlag = false; // Flag indicate that droneState should be zeroed
private SensorsWrapper sensors;
private Activity mainActivityRef;
private FlyverMQ messageQueue;
private FlyverMQConsumer dronestateListener;
private LoggerService logger;
/**
* Helper used to build the instance of the MainController
* using the provided host activity, microcontroller and drone type
*/
public static class MainControllerBuilder {
Activity activity;
MicroController microController;
QuadCopterX drone;
public MainControllerBuilder setMicroController(MicroController microController) {
this.microController = microController;
return this;
}
public MainControllerBuilder setDrone(QuadCopterX drone) {
this.drone = drone;
return this;
}
public MainControllerBuilder setActivity(Activity activity) {
this.activity = activity;
return this;
}
/**
* Create the first instance of the MainController
* Throws exception if an instance is already created
*/
public void build() throws MainControllerInstanceExisting {
if(instance == null) {
instance = new MainController(activity, microController, drone);
try {
instance.start();
} catch (Exception e) {
e.printStackTrace();
}
} else {
throw new MainControllerInstanceExisting("Only one instance of the MainController can be existing at a time");
}
}
}
private enum PIDKeys {
PID_YAW_PROPORTIONAL("proportionalY"),
PID_YAW_INTEGRAL("integralY"),
PID_YAW_DERIVATIVE("derivativeY"),
PID_PITCH_PROPORTIONAL("proportionalP"),
PID_PITCH_INTEGRAL("integralP"),
PID_PITCH_DERIVATIVE("derivativeP"),
PID_ROLL_PROPORTIONAL("proportionalR"),
PID_ROLL_INTEGRAL("integralR"),
PID_ROLL_DERIVATIVE("derivativeR");
private String key;
private PIDKeys(String key) {
this.key = key;
}
public String getValue() {
return key;
}
}
public static MainController getInstance() {
return instance;
}
public FlyverMQ getMessageQueue() {
return messageQueue;
}
public Activity getMainActivityRef() {
return mainActivityRef;
}
public float getYawAngleTarget() {
return yawAngleTarget;
}
public void setYawAngleTarget(float yawAngleTarget) {
this.yawAngleTarget = yawAngleTarget;
}
public float getPitchAngleTarget() {
return pitchAngleTarget;
}
public void setPitchAngleTarget(float pitchAngleTarget) {
this.pitchAngleTarget = pitchAngleTarget;
}
public float getRollAngleTarget() {
return rollAngleTarget;
}
public void setRollAngleTarget(float rollAngleTarget) {
this.rollAngleTarget = rollAngleTarget;
}
public float getMeanThrust() {
return meanThrust;
}
public void setMeanThrust(float meanThrust) {
this.meanThrust = meanThrust;
}
public void setMicroController(MicroController microController) {
this.microController = microController;
if (battery != null) {
battery.setMicroController(microController);
}
}
public int getBatteryPercentage() {
return battery.getBatteryStatus();
}
private void initLogger() {
logger = new LoggerService(mainActivityRef.getApplicationContext(), messageQueue);
logger.Start();
logger.LogData("EV_DEBUG", "MainController", "MainController initialized the Logger.");
}
private MainController(Activity activity, MicroController microController, QuadCopterX drone) {
regulatorEnabled = true;
this.drone = drone;
mainActivityRef = activity;
// altitudeRegulator = new PidRegulator(0.0f, 0.0f, 0.0f, PID_DERIV_SMOOTHING, 0.0f);
yawAngleTarget = 0.0f;
pitchAngleTarget = 0.0f;
rollAngleTarget = 0.0f;
altitudeTarget = 0.0f;
}
public void start() throws Exception {
// Initializations.
regulatorEnabled = true;
altitudeLockEnabled = false;
meanThrust = 0.0f;
messageQueue = FlyverMQ.getInstance();
LocationServicesProvider locationServicesProvider = new LocationServicesProvider();
LocationServicesSubsciber locationServicesSubsciber = new LocationServicesSubsciber();
// SimpleMQ.getInstance().registerConsumer(locationServicesSubsciber, LocationServicesSubsciber.TOPIC);
battery = new Battery(microController, BatteryCells.THREE);
battery.setStatusChangeCb(new Battery.StatusChanged() {
@Override
public void onChange(int status) {
Log.d(CONTROLLER, "Battery status : " + status + "%");
IPCContainers.JSONTuple<String, String> batteryInfo = new IPCContainers.JSONTuple<>("battery", String.valueOf(status));
Type type = new TypeToken<IPCContainers.JSONTuple<String, String>>() {
}.getType();
Server.sendMsgToClient(JSONUtils.serialize(batteryInfo, type));
}
}).setBatteryCriticalCallback(new Runnable() {
@Override
public void run() {
Log.e(CONTROLLER, "Battery is almost depleted");
emergencyStop("Low battery!");
}
});
sensors = new SensorsWrapper(getMainActivityRef());
sensors.start();
droneState = new DroneState(sensors);
droneStateData = droneState.new DroneStateData();
// Start the sensors.
droneState.resumed();
//initialize the controller parameters
init();
//initLogger();
}
public void stop() {
// Stop the main controller thread.
// Stop the sensors.
droneState.paused();
}
public DroneState.DroneStateData getSensorsData() {
return droneStateData;
}
public void setMeanTrust(float trust) {
meanThrust = trust;
}
public boolean getRegulatorsState() {
return regulatorEnabled;
}
private int motorSaturation(double val) {
if (val > MAX_MOTOR_POWER)
return (int) MAX_MOTOR_POWER;
else if (val < 0.0)
return 0;
else
return (int) val;
}
/**
* onConnectionEstablished is called when the whole systems starts
* and int working order
*/
public void onConnectionEstablished() {
// Reset the orientation.
droneState.setCurrentStateAsZero();
// TODO: droneState.setCurrentStateAsZero works only on initialization, but can't be accessed after
}
/**
* Called when the communication link between the drone and the RC is lost.
* TODO: Break it into cases and implement algorithms such as Return To Home
*/
public void onConnectionLost() {
// Emergency stop of the quadcopter.
emergencyStop("Connection Lost");
}
public void onIoioConnect() {
Log.e(CONTROLLER, "IOIO Connection established");
battery.resume();
}
public void onIoioDisconnect() {
Log.e(CONTROLLER, "IOIO Connection lost");
battery.pause();
}
/**
* Stops the drone.
* NB! Currently means stopping the motors
*
* @param reason for logging the cause of the emergency
*/
public void emergencyStop(String reason) {
// TODO: Smart Landing
Log.w("Emergency", reason);
yawController.resetIntegrator();
pitchController.resetIntegrator();
rollController.resetIntegrator();
setMeanThrust(0);
}
private void init() {
final Context mainContext = getMainActivityRef().getApplicationContext();
setPIDSettings(mainContext);
initPIDControllers(mainContext);
ServerCallback onValuesChange = new ServerCallback() {
@Override
public void run(String json) {
setMeanTrust(Server.sCurrentStatus.getThrottle());
setPitchAngleTarget(Server.sCurrentStatus.getPitch());
setRollAngleTarget(Server.sCurrentStatus.getRoll());
setYawAngleTarget(Server.sCurrentStatus.getYaw());
if (Server.sCurrentStatus.isEmergency()) {
Log.e(CONTROLLER, "Emergency sequence initiated");
emergencyStop("Server command");
}
}
};
ServerCallback onPidYawChange = new ServerCallback() {
@Override
public void run(String json) {
Log.e("PID", "PID Yaw coefficients have changed!!!");
Status.PID pid = Server.sCurrentStatus.getPidYaw();
changePIDSharedPreference(PIDKeys.PID_YAW_PROPORTIONAL, String.valueOf(pid.getP()), mainContext);
changePIDSharedPreference(PIDKeys.PID_YAW_INTEGRAL, String.valueOf(pid.getI()), mainContext);
changePIDSharedPreference(PIDKeys.PID_YAW_DERIVATIVE, String.valueOf(pid.getD()), mainContext);
yawController.setCoefficients(pid.getP(), pid.getI(), pid.getD());
}
};
ServerCallback onPidPitchChange = new ServerCallback() {
@Override
public void run(String json) {
Log.e("PID", "PID Pitch coefficients have changed!!!");
Status.PID pid = Server.sCurrentStatus.getPidPitch();
changePIDSharedPreference(PIDKeys.PID_PITCH_PROPORTIONAL, String.valueOf(pid.getP()), mainContext);
changePIDSharedPreference(PIDKeys.PID_PITCH_INTEGRAL, String.valueOf(pid.getI()), mainContext);
changePIDSharedPreference(PIDKeys.PID_PITCH_DERIVATIVE, String.valueOf(pid.getD()), mainContext);
pitchController.setCoefficients(pid.getP(), pid.getI(), pid.getD());
}
};
ServerCallback onPidRollChange = new ServerCallback() {
@Override
public void run(String json) {
Log.e("PID", "PID Roll coefficients have changed!!!");
Status.PID pid = Server.sCurrentStatus.getPidRoll();
changePIDSharedPreference(PIDKeys.PID_ROLL_PROPORTIONAL, String.valueOf(pid.getP()), mainContext);
changePIDSharedPreference(PIDKeys.PID_ROLL_INTEGRAL, String.valueOf(pid.getI()), mainContext);
changePIDSharedPreference(PIDKeys.PID_ROLL_DERIVATIVE, String.valueOf(pid.getD()), mainContext);
rollController.setCoefficients(pid.getP(), pid.getI(), pid.getD());
}
};
//Register callbacks to be called when the appropriate JSON is received
Server.registerCallback(IPCKeys.THROTTLE, onValuesChange);
Server.registerCallback(IPCKeys.YAW, onValuesChange);
Server.registerCallback(IPCKeys.COORDINATES, onValuesChange);
Server.registerCallback(IPCKeys.EMERGENCY, onValuesChange);
Server.registerCallback(IPCKeys.PIDPITCH, onPidPitchChange);
Server.registerCallback(IPCKeys.PIDROLL, onPidRollChange);
Server.registerCallback(IPCKeys.PIDYAW, onPidYawChange);
dronestateListener = new FlyverMQConsumer() {
@Override
public void dataReceived(FlyverMQMessage message) {
float yawForce, pitchForce, rollForce, altitudeForce, currentYaw, currentPitch, currentRoll;
if (!zeroStateFlag) {
droneState.setCurrentStateAsZero();
zeroStateFlag = true;
}
// Get the sensors data.
droneStateData = (DroneState.DroneStateData) message.data;
currentYaw = droneStateData.yaw;
currentPitch = droneStateData.pitch;
currentRoll = droneStateData.roll;
long currentTime = droneStateData.time;
float dt = ((float) (currentTime - previousTime)) / 1000000000.0f; // [s].
previousTime = currentTime;
// Check for dangerous situations.
if (regulatorEnabled) {
// If the quadcopter is too inclined, emergency stop it.
if (Math.abs(currentPitch) > MAX_SAFE_PITCH_ROLL ||
Math.abs(currentRoll) > MAX_SAFE_PITCH_ROLL) {
//TODO: Setup safety max rol/pitch values
emergencyStop("Safe pitch or safe roll exceeded");
}
}
// Compute the motors powers.
if (regulatorEnabled && meanThrust > 1.0) {
// Compute the "forces" needed to move the quadcopter to the
// set point.
yawForce = yawController.getInput(yawAngleTarget, currentYaw, dt);
pitchForce = pitchController.getInput(pitchAngleTarget, currentPitch, dt);
rollForce = rollController.getInput(rollAngleTarget, currentRoll, dt);
/*
if(altitudeLockEnabled)
altitudeForce = altitudeRegulator.getInput(altitudeTarget, currentAltitude, dt);
else */
altitudeForce = meanThrust;
drone.updateSpeeds(yawForce, pitchForce, rollForce, altitudeForce);
} else {
drone.setToZero();
yawController.resetIntegrator();
pitchController.resetIntegrator();
rollController.resetIntegrator();
yawForce = 0.0f;
pitchForce = 0.0f;
rollForce = 0.0f;
altitudeForce = 0.0f;
}
}
@Override
public void unregistered() {
}
@Override
public void paused() {
}
@Override
public void resumed() {
}
};
FlyverMQ.getInstance().registerConsumer(dronestateListener, "dronestate.raw");
deployWebpage();
}
private void setPIDSettings(Context context) {
final String PREFERENCES = context.getString(R.string.pid_preferences);
SharedPreferences sharedPreferences = context.getSharedPreferences(PREFERENCES, MODE_PRIVATE);
/* Yaw PID Controller preferences */
if (!sharedPreferences.contains(PIDKeys.PID_YAW_PROPORTIONAL.getValue())) {
changePIDSharedPreference(PIDKeys.PID_YAW_PROPORTIONAL, "2.2", context);
}
if (!sharedPreferences.contains(PIDKeys.PID_YAW_INTEGRAL.getValue())) {
changePIDSharedPreference(PIDKeys.PID_YAW_INTEGRAL, "0", context);
}
if (!sharedPreferences.contains(PIDKeys.PID_YAW_DERIVATIVE.getValue())) {
changePIDSharedPreference(PIDKeys.PID_YAW_DERIVATIVE, "0.2", context);
}
/* End of Yaw PID Controller preferences */
/* Pitch PID Controller preferences */
if (!sharedPreferences.contains(PIDKeys.PID_PITCH_PROPORTIONAL.getValue())) {
changePIDSharedPreference(PIDKeys.PID_PITCH_PROPORTIONAL, "2.4", context);
}
if (!sharedPreferences.contains(PIDKeys.PID_PITCH_INTEGRAL.getValue())) {
changePIDSharedPreference(PIDKeys.PID_PITCH_INTEGRAL, "0.2", context);
}
if (!sharedPreferences.contains(PIDKeys.PID_PITCH_DERIVATIVE.getValue())) {
changePIDSharedPreference(PIDKeys.PID_PITCH_DERIVATIVE, "0.4", context);
}
/* End of Pitch PID controller preferences */
/* Roll PID controller preferences */
if (!sharedPreferences.contains(PIDKeys.PID_ROLL_PROPORTIONAL.getValue())) {
changePIDSharedPreference(PIDKeys.PID_ROLL_PROPORTIONAL, "2.4", context);
}
if (!sharedPreferences.contains(PIDKeys.PID_ROLL_INTEGRAL.getValue())) {
changePIDSharedPreference(PIDKeys.PID_ROLL_INTEGRAL, "0.2", context);
}
if (!sharedPreferences.contains(PIDKeys.PID_ROLL_DERIVATIVE.getValue())) {
changePIDSharedPreference(PIDKeys.PID_ROLL_INTEGRAL, "0.4", context);
}
/* End of Roll PID controller preferences */
float[][] pidValues = getPidValues(context);
Server.sCurrentStatus.getPidYaw().setP(pidValues[0][0]);
Server.sCurrentStatus.getPidYaw().setI(pidValues[0][1]);
Server.sCurrentStatus.getPidYaw().setD(pidValues[0][2]);
Server.sCurrentStatus.getPidPitch().setP(pidValues[1][0]);
Server.sCurrentStatus.getPidPitch().setI(pidValues[1][1]);
Server.sCurrentStatus.getPidPitch().setD(pidValues[1][2]);
Server.sCurrentStatus.getPidRoll().setP(pidValues[2][0]);
Server.sCurrentStatus.getPidRoll().setI(pidValues[2][1]);
Server.sCurrentStatus.getPidRoll().setD(pidValues[2][2]);
}
private void initPIDControllers(Context context) {
float[][] pidValues = getPidValues(context);
yawController = new PIDAngleController(pidValues[0][0], pidValues[0][1], pidValues[0][2], PID_DERIV_SMOOTHING);
pitchController = new PIDAngleController(pidValues[1][0], pidValues[1][1], pidValues[1][2], PID_DERIV_SMOOTHING);
rollController = new PIDAngleController(pidValues[2][0], pidValues[2][1], pidValues[2][2], PID_DERIV_SMOOTHING);
}
private void changePIDSharedPreference(PIDKeys pidKey, String value, Context context) {
final String PREFERENCES = context.getString(R.string.pid_preferences);
SharedPreferences.Editor editor = context.getSharedPreferences(PREFERENCES, MODE_PRIVATE).edit();
editor.putString(pidKey.getValue(), value);
editor.apply();
Log.d(CONTROLLER, "Preference changed for: " + pidKey.getValue() + " with " + value);
}
/**
* returns 3x3 array of PID values
* [0][n] - Yaw values
* [1][n] - Pitch values
* [2][n] - Roll values
* [n][0] - proportional values
* [n][1] - integral values
* [n][2] - derivative values
* @param context
* @return array of PID values
*/
private float[][] getPidValues(Context context) {
final String PREFERENCES = context.getString(R.string.pid_preferences);
final String DEFAULT = "0";
SharedPreferences sharedPreferences = context.getSharedPreferences(PREFERENCES, MODE_PRIVATE);
String preference;
float p;
float i;
float d;
float[][] values = new float[3][3];
preference = sharedPreferences.getString(PIDKeys.PID_YAW_PROPORTIONAL.getValue(), DEFAULT);
p = Float.parseFloat(preference);
preference = sharedPreferences.getString(PIDKeys.PID_YAW_INTEGRAL.getValue(), DEFAULT);
i = Float.parseFloat(preference);
preference = sharedPreferences.getString(PIDKeys.PID_YAW_DERIVATIVE.getValue(), DEFAULT);
d = Float.parseFloat(preference);
values[0][0] = p;
values[0][1] = i;
values[0][2] = d;
preference = sharedPreferences.getString(PIDKeys.PID_PITCH_PROPORTIONAL.getValue(), DEFAULT);
p = Float.parseFloat(preference);
preference = sharedPreferences.getString(PIDKeys.PID_PITCH_INTEGRAL.getValue(), DEFAULT);
i = Float.parseFloat(preference);
preference = sharedPreferences.getString(PIDKeys.PID_PITCH_DERIVATIVE.getValue(), DEFAULT);
d = Float.parseFloat(preference);
values[1][0] = p;
values[1][1] = i;
values[1][2] = d;
preference = sharedPreferences.getString(PIDKeys.PID_ROLL_PROPORTIONAL.getValue(), DEFAULT);
p = Float.parseFloat(preference);
preference = sharedPreferences.getString(PIDKeys.PID_ROLL_INTEGRAL.getValue(), DEFAULT);
i = Float.parseFloat(preference);
preference = sharedPreferences.getString(PIDKeys.PID_ROLL_DERIVATIVE.getValue(), DEFAULT);
d = Float.parseFloat(preference);
values[2][0] = p;
values[2][1] = i;
values[2][2] = d;
return values;
}
/**
* Checks if the flyver webpage files have been copied to sdcard/co.flyver/webpage/
* Copies them if not
*/
private void deployWebpage() {
String path = Environment.getExternalStorageDirectory().toString().concat("/co.flyver/");
File webpageDir = new File(path.concat("/webpage/"));
//TODO:: commented for debugging purposes, uncomment later
// if(!webpageDir.exists()) {
webpageDir.mkdirs();
copyWebpage(path);
// }
}
/**
* Copies the files for the webpage from the assets dir, to the co.flyver/webpage dir on the sdcard
* @param destinationPath
*/
private void copyWebpage(String destinationPath) {
AssetManager assetManager = mainActivityRef.getResources().getAssets();
String[] files = null;
try {
files = assetManager.list("webpage");
} catch (IOException e) {
e.printStackTrace();
}
if (files != null) {
for (String file : files) {
InputStream inputStream;
OutputStream outputStream;
try {
inputStream = assetManager.open("webpage/" + file);
outputStream = new FileOutputStream(destinationPath.concat("/webpage/".concat(file)));
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
inputStream.close();
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} | 412 | 0.738368 | 1 | 0.738368 | game-dev | MEDIA | 0.596666 | game-dev,mobile | 0.689259 | 1 | 0.689259 |
Merchello/Merchello | 4,135 | src/Merchello.FastTrack.Ui/App_Data/NuGetBackup/20160823-095311/Umbraco/lib/tinymce/plugins/autosave/plugin.js | /**
* plugin.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
// Internal unload handler will be called before the page is unloaded
// Needs to be outside the plugin since it would otherwise keep
// a reference to editor in closue scope
/*eslint no-func-assign:0 */
tinymce._beforeUnloadHandler = function() {
var msg;
tinymce.each(tinymce.editors, function(editor) {
// Store a draft for each editor instance
if (editor.plugins.autosave) {
editor.plugins.autosave.storeDraft();
}
// Setup a return message if the editor is dirty
if (!msg && editor.isDirty() && editor.getParam("autosave_ask_before_unload", true)) {
msg = editor.translate("You have unsaved changes are you sure you want to navigate away?");
}
});
return msg;
};
tinymce.PluginManager.add('autosave', function(editor) {
var settings = editor.settings, LocalStorage = tinymce.util.LocalStorage, prefix, started;
prefix = settings.autosave_prefix || 'tinymce-autosave-{path}{query}-{id}-';
prefix = prefix.replace(/\{path\}/g, document.location.pathname);
prefix = prefix.replace(/\{query\}/g, document.location.search);
prefix = prefix.replace(/\{id\}/g, editor.id);
function parseTime(time, defaultTime) {
var multipels = {
s: 1000,
m: 60000
};
time = /^(\d+)([ms]?)$/.exec('' + (time || defaultTime));
return (time[2] ? multipels[time[2]] : 1) * parseInt(time, 10);
}
function hasDraft() {
var time = parseInt(LocalStorage.getItem(prefix + "time"), 10) || 0;
if (new Date().getTime() - time > settings.autosave_retention) {
removeDraft(false);
return false;
}
return true;
}
function removeDraft(fire) {
LocalStorage.removeItem(prefix + "draft");
LocalStorage.removeItem(prefix + "time");
if (fire !== false) {
editor.fire('RemoveDraft');
}
}
function storeDraft() {
if (!isEmpty() && editor.isDirty()) {
LocalStorage.setItem(prefix + "draft", editor.getContent({format: 'raw', no_events: true}));
LocalStorage.setItem(prefix + "time", new Date().getTime());
editor.fire('StoreDraft');
}
}
function restoreDraft() {
if (hasDraft()) {
editor.setContent(LocalStorage.getItem(prefix + "draft"), {format: 'raw'});
editor.fire('RestoreDraft');
}
}
function startStoreDraft() {
if (!started) {
setInterval(function() {
if (!editor.removed) {
storeDraft();
}
}, settings.autosave_interval);
started = true;
}
}
settings.autosave_interval = parseTime(settings.autosave_interval, '30s');
settings.autosave_retention = parseTime(settings.autosave_retention, '20m');
function postRender() {
var self = this;
self.disabled(!hasDraft());
editor.on('StoreDraft RestoreDraft RemoveDraft', function() {
self.disabled(!hasDraft());
});
startStoreDraft();
}
function restoreLastDraft() {
editor.undoManager.beforeChange();
restoreDraft();
removeDraft();
editor.undoManager.add();
}
editor.addButton('restoredraft', {
title: 'Restore last draft',
onclick: restoreLastDraft,
onPostRender: postRender
});
editor.addMenuItem('restoredraft', {
text: 'Restore last draft',
onclick: restoreLastDraft,
onPostRender: postRender,
context: 'file'
});
function isEmpty(html) {
var forcedRootBlockName = editor.settings.forced_root_block;
html = tinymce.trim(typeof html == "undefined" ? editor.getBody().innerHTML : html);
return html === '' || new RegExp(
'^<' + forcedRootBlockName + '[^>]*>((\u00a0| |[ \t]|<br[^>]*>)+?|)<\/' + forcedRootBlockName + '>|<br>$', 'i'
).test(html);
}
if (editor.settings.autosave_restore_when_empty !== false) {
editor.on('init', function() {
if (hasDraft() && isEmpty()) {
restoreDraft();
}
});
editor.on('saveContent', function() {
removeDraft();
});
}
window.onbeforeunload = tinymce._beforeUnloadHandler;
this.hasDraft = hasDraft;
this.storeDraft = storeDraft;
this.restoreDraft = restoreDraft;
this.removeDraft = removeDraft;
this.isEmpty = isEmpty;
}); | 412 | 0.605881 | 1 | 0.605881 | game-dev | MEDIA | 0.358127 | game-dev | 0.939421 | 1 | 0.939421 |
foxtacles/vaultmp | 3,854 | source/vaultserver/NPC.cpp | #include "NPC.hpp"
#include "Race.hpp"
#include "sqlite/sqlite3.h"
#include <algorithm>
using namespace std;
using namespace DB;
unordered_map<unsigned int, NPC*> NPC::npcs;
NPC::NPC(const string& table, sqlite3_stmt* stmt) : new_female(-1), new_race(0x00000000)
{
if (sqlite3_column_count(stmt) != 8)
throw VaultException("Malformed input database (NPCs): %s", table.c_str()).stacktrace();
unsigned int dlc = static_cast<unsigned int>(sqlite3_column_int(stmt, 7));
// if DLC enabled
dlc <<= 24;
baseID = static_cast<unsigned int>(sqlite3_column_int(stmt, 0));
essential = static_cast<bool>(sqlite3_column_int(stmt, 1));
female = static_cast<bool>(sqlite3_column_int(stmt, 2));
race = static_cast<unsigned int>(sqlite3_column_int(stmt, 3));
template_ = static_cast<unsigned int>(sqlite3_column_int(stmt, 4));
flags = static_cast<unsigned short>(sqlite3_column_int(stmt, 5));
deathitem = static_cast<unsigned int>(sqlite3_column_int(stmt, 6));
if (race & 0xFF000000)
{
race &= 0x00FFFFFF;
race |= dlc;
}
if (template_ & 0xFF000000)
{
template_ &= 0x00FFFFFF;
template_ |= dlc;
}
if (deathitem & 0xFF000000)
{
deathitem &= 0x00FFFFFF;
deathitem |= dlc;
}
if (baseID & 0xFF000000)
{
baseID &= 0x00FFFFFF;
baseID |= dlc;
}
else
npcs.erase(baseID);
npcs.emplace(baseID, this);
}
Expected<NPC*> NPC::Lookup(unsigned int baseID)
{
auto it = npcs.find(baseID);
if (it != npcs.end())
return it->second;
return VaultException("No NPC with baseID %08X found", baseID);
}
Expected<NPC*> NPC::GetNPC(const function<bool(const NPC&)>& pred)
{
auto it = find_if(npcs.begin(), npcs.end(), [&pred](const pair<const unsigned int, const NPC*>& npcs) { return pred(*npcs.second); });
if (it != npcs.end())
return it->second;
return VaultException("No NPC found fulfilling the conditions of the given function");
}
unsigned int NPC::GetBase() const
{
return baseID;
}
bool NPC::IsEssential() const
{
if (template_ && (flags & TplFlags::Base))
{
auto npc = Lookup(template_);
if (npc)
return npc->IsEssential();
}
return essential;
}
bool NPC::IsFemale() const
{
if (template_ && (flags & TplFlags::Traits))
{
auto npc = Lookup(template_);
if (npc)
return npc->IsFemale();
}
return ((new_female != -1) ? new_female : female);
}
bool NPC::IsOriginalFemale() const
{
if (template_ && (flags & TplFlags::Traits))
{
auto npc = Lookup(template_);
if (npc)
return npc->IsOriginalFemale();
}
return female;
}
unsigned int NPC::GetRace() const
{
if (template_ && (flags & TplFlags::Traits))
{
auto npc = Lookup(template_);
if (npc)
return npc->GetRace();
}
return (new_race ? new_race : race);
}
unsigned int NPC::GetOriginalRace() const
{
if (template_ && (flags & TplFlags::Traits))
{
auto npc = Lookup(template_);
if (npc)
return npc->GetOriginalRace();
}
return race;
}
unsigned int NPC::GetTemplate() const
{
return template_;
}
unsigned short NPC::GetFlags() const
{
return flags;
}
unsigned int NPC::GetDeathItem() const
{
if (template_ && (flags & TplFlags::Traits))
{
auto npc = Lookup(template_);
if (npc)
return npc->GetDeathItem();
}
return deathitem;
}
const vector<BaseContainer*>& NPC::GetBaseContainer() const
{
if (template_ && (flags & TplFlags::Inventory))
{
auto npc = Lookup(template_);
if (npc)
return npc->GetBaseContainer();
}
return BaseContainer::Lookup(baseID);
}
void NPC::SetRace(unsigned int race)
{
if (template_ && (flags & TplFlags::Traits))
{
auto npc = Lookup(template_);
if (npc)
return npc->SetRace(race);
}
if (Race::Lookup(race))
this->new_race = race;
}
void NPC::SetFemale(bool female)
{
if (template_ && (flags & TplFlags::Traits))
{
auto npc = Lookup(template_);
if (npc)
return npc->SetFemale(female);
}
this->new_female = female;
}
| 412 | 0.948078 | 1 | 0.948078 | game-dev | MEDIA | 0.973783 | game-dev | 0.950354 | 1 | 0.950354 |
Xeno69/Domination | 1,041 | co30_Domination.Altis/missions/ma3a/x_m59.sqf | // by Xeno
//#define __DEBUG__
#include "..\..\x_setup.sqf"
d_x_sm_pos = "d_sm_59" call d_fnc_smmapos; //index:59 Find and eliminate the lonewolf sniper near Dorida
d_x_sm_type = "normal"; // "convoy"
if (hasInterface) then {
d_cur_sm_txt = localize "STR_DOM_MISSIONSTRING_1814";
d_current_mission_resolved_text = localize "STR_DOM_MISSIONSTRING_1545";
};
if (isServer) then {
private _newpos = [d_x_sm_pos # 0, 80] call d_fnc_GetRanPointCircle;
private _ogroup = [d_side_enemy] call d_fnc_creategroup;
private _sm_vec = _ogroup createUnit [d_sniper, _newpos, [], 0, "NONE"];
[_sm_vec] joinSilent _ogroup;
_ogroup deleteGroupWhenEmpty true;
_newpos set [2, 0];
[_sm_vec, _newpos] call d_fnc_setposagls;
_sm_vec call d_fnc_removenvgoggles_fak;
_sm_vec call d_fnc_addkillednormal;
d_x_sm_rem_ar pushBack _sm_vec;
sleep 2.123;
private _leadero = leader _ogroup;
_leadero setRank "COLONEL";
_ogroup allowFleeing 0;
_ogroup setBehaviour "AWARE";
if (d_with_dynsim == 0) then {
[_sm_vec, 1] spawn d_fnc_enabledynsim;
};
};
| 412 | 0.556685 | 1 | 0.556685 | game-dev | MEDIA | 0.82968 | game-dev | 0.70519 | 1 | 0.70519 |
Xiao-MoMi/craft-engine | 1,424 | core/src/main/java/net/momirealms/craftengine/core/block/BlockStateWrapper.java | package net.momirealms.craftengine.core.block;
import net.momirealms.craftengine.core.util.Key;
import net.momirealms.sparrow.nbt.*;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
public interface BlockStateWrapper extends Comparable<BlockStateWrapper> {
Object literalObject();
int registryId();
Key ownerId();
<T> T getProperty(String propertyName);
boolean hasProperty(String propertyName);
BlockStateWrapper withProperty(String propertyName, String propertyValue);
String getAsString();
@Override
default int compareTo(@NotNull BlockStateWrapper o) {
return Integer.compare(registryId(), o.registryId());
}
default BlockStateWrapper withProperties(CompoundTag properties) {
BlockStateWrapper result = this;
for (Map.Entry<String, Tag> entry : properties.entrySet()) {
Tag value = entry.getValue();
if (value instanceof StringTag stringTag) {
result = result.withProperty(entry.getKey(), stringTag.getAsString());
} else if (value instanceof IntTag intTag) {
result = result.withProperty(entry.getKey(), String.valueOf(intTag.getAsInt()));
} else if (value instanceof ByteTag byteTag) {
result = result.withProperty(entry.getKey(), String.valueOf(byteTag.booleanValue()));
}
}
return result;
}
}
| 412 | 0.924036 | 1 | 0.924036 | game-dev | MEDIA | 0.355721 | game-dev | 0.949607 | 1 | 0.949607 |
realms-mud/core-lib | 2,318 | lib/modules/state.c | //*****************************************************************************
// Copyright (c) 2025 - Allen Cummings, RealmsMUD, All rights reserved. See
// the accompanying LICENSE file for details.
//*****************************************************************************
virtual inherit "/lib/core/thing.c";
#include "/lib/modules/secure/state.h"
/////////////////////////////////////////////////////////////////////////////
public void executeStateChange(object caller, string newState)
{
// Overload or shadow this method to do custom state change processing
}
/////////////////////////////////////////////////////////////////////////////
private nomask string getKey(object caller)
{
return sprintf("%s#%s", program_name(caller),
caller->Name() ? caller->Name() : "any");
}
/////////////////////////////////////////////////////////////////////////////
public nomask void onStateChanged(object caller, string newState)
{
if (objectp(caller))
{
object persistence = getModule("secure/persistence");
if (objectp(persistence))
{
persistence->characterState(caller, newState);
}
else
{
characterStates[getKey(caller)] = newState;
}
executeStateChange(caller, newState);
object conversations = getModule("conversations");
if (conversations)
{
conversations->updateConversationState(caller, newState);
}
}
}
/////////////////////////////////////////////////////////////////////////////
public nomask string stateFor(object caller)
{
string ret = 0;
object persistence = getModule("secure/persistence");
if (objectp(persistence))
{
ret = persistence->characterState(caller);
}
else
{
string key = getKey(caller);
if (member(characterStates, key))
{
ret = characterStates[key];
}
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
public nomask void resetCaches()
{
object inventory = getModule("inventory");
if (inventory)
{
inventory->resetInventoryCache();
}
object combat = getModule("combat");
if (combat)
{
combat->resetCombatCache();
}
}
| 412 | 0.696681 | 1 | 0.696681 | game-dev | MEDIA | 0.724475 | game-dev | 0.81322 | 1 | 0.81322 |
ReactiveDrop/reactivedrop_public_src | 4,399 | src/game/client/swarm/gameui/createmultiplayergamedialog.cpp | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "CreateMultiplayerGameDialog.h"
#include "CreateMultiplayerGameServerPage.h"
#include "CreateMultiplayerGameGameplayPage.h"
#include "CreateMultiplayerGameBotPage.h"
#include "EngineInterface.h"
#include "ModInfo.h"
#include "GameUI_Interface.h"
#include <stdio.h>
using namespace vgui;
#include <vgui/ILocalize.h>
#include "FileSystem.h"
#include <KeyValues.h>
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CCreateMultiplayerGameDialog::CCreateMultiplayerGameDialog(vgui::Panel *parent) : PropertyDialog(parent, "CreateMultiplayerGameDialog")
{
m_bBotsEnabled = false;
SetDeleteSelfOnClose(true);
SetSize(348, 460);
SetTitle("#GameUI_CreateServer", true);
SetOKButtonText("#GameUI_Start");
if (!stricmp( ModInfo().GetGameName(), "Counter-Strike Source" ))
{
m_bBotsEnabled = true;
}
m_pServerPage = new CCreateMultiplayerGameServerPage(this, "ServerPage");
m_pGameplayPage = new CCreateMultiplayerGameGameplayPage(this, "GameplayPage");
m_pBotPage = NULL;
AddPage(m_pServerPage, "#GameUI_Server");
AddPage(m_pGameplayPage, "#GameUI_Game");
// create KeyValues object to load/save config options
m_pSavedData = new KeyValues( "ServerConfig" );
// load the config data
if (m_pSavedData)
{
m_pSavedData->LoadFromFile( g_pFullFileSystem, "ServerConfig.vdf", "GAME" ); // this is game-specific data, so it should live in GAME, not CONFIG
const char *startMap = m_pSavedData->GetString("map", "");
if (startMap[0])
{
m_pServerPage->SetMap(startMap);
}
}
if ( m_bBotsEnabled )
{
// add a page of advanced bot controls
// NOTE: These controls will use the bot keys to initialize their values
m_pBotPage = new CCreateMultiplayerGameBotPage( this, "BotPage", m_pSavedData );
AddPage( m_pBotPage, "#GameUI_CPUPlayerOptions" );
m_pServerPage->EnableBots( m_pSavedData );
}
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CCreateMultiplayerGameDialog::~CCreateMultiplayerGameDialog()
{
if (m_pSavedData)
{
m_pSavedData->deleteThis();
m_pSavedData = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose: runs the server when the OK button is pressed
//-----------------------------------------------------------------------------
bool CCreateMultiplayerGameDialog::OnOK(bool applyOnly)
{
// reset server enforced cvars
g_pCVar->RevertFlaggedConVars( FCVAR_REPLICATED );
// Cheats were disabled; revert all cheat cvars to their default values.
// This must be done heading into multiplayer games because people can play
// demos etc and set cheat cvars with sv_cheats 0.
g_pCVar->RevertFlaggedConVars( FCVAR_CHEAT );
DevMsg( "FCVAR_CHEAT cvars reverted to defaults.\n" );
BaseClass::OnOK(applyOnly);
// get these values from m_pServerPage and store them temporarily
char szMapName[64], szHostName[64], szPassword[64];
Q_strncpy(szMapName, m_pServerPage->GetMapName(), sizeof( szMapName ));
Q_strncpy(szHostName, m_pGameplayPage->GetHostName(), sizeof( szHostName ));
Q_strncpy(szPassword, m_pGameplayPage->GetPassword(), sizeof( szPassword ));
// save the config data
if (m_pSavedData)
{
if (m_pServerPage->IsRandomMapSelected())
{
// it's set to random map, just save an
m_pSavedData->SetString("map", "");
}
else
{
m_pSavedData->SetString("map", szMapName);
}
// save config to a file
m_pSavedData->SaveToFile( g_pFullFileSystem, "ServerConfig.vdf", "GAME" );
}
char szMapCommand[1024];
// create the command to execute
Q_snprintf(szMapCommand, sizeof( szMapCommand ), "disconnect\nwait\nwait\nsv_lan 1\nsetmaster enable\nmaxplayers %i\nsv_password \"%s\"\nhostname \"%s\"\nprogress_enable\nmap %s\n",
m_pGameplayPage->GetMaxPlayers(),
szPassword,
szHostName,
szMapName
);
// exec
engine->ClientCmd_Unrestricted(szMapCommand);
return true;
}
| 412 | 0.849364 | 1 | 0.849364 | game-dev | MEDIA | 0.921278 | game-dev | 0.670625 | 1 | 0.670625 |
HongchengQ/HunkyMeow | 1,185 | src/main/java/emu/grasscutter/scripts/SceneTimeAxis.java | package emu.grasscutter.scripts;
import emu.grasscutter.scripts.constants.EventType;
import emu.grasscutter.scripts.data.ScriptArgs;
import java.util.*;
import lombok.*;
@Getter
@RequiredArgsConstructor
public final class SceneTimeAxis {
private final Timer timer = new Timer();
private final SceneScriptManager handle;
private final int groupId;
private final String identifier;
private final int delay;
private final boolean loop;
/** Schedules the task to run. */
public void start() {
if (this.loop) {
this.timer.scheduleAtFixedRate(new Task(), this.delay, this.delay);
} else {
this.timer.schedule(new Task(), this.delay);
}
}
/** Terminates a repeating task. */
public void stop() {
this.timer.cancel();
}
final class Task extends TimerTask {
@Override
public void run() {
// Invoke script event.
SceneTimeAxis.this.handle.callEvent(
new ScriptArgs(SceneTimeAxis.this.groupId, EventType.EVENT_TIME_AXIS_PASS)
.setEventSource(SceneTimeAxis.this.identifier));
}
}
}
| 412 | 0.92499 | 1 | 0.92499 | game-dev | MEDIA | 0.631266 | game-dev | 0.977406 | 1 | 0.977406 |
Divine-Journey-2/Divine-Journey-2 | 24,525 | overrides/scripts/ModSpecific/DivineRPG.zs | // Author: Atricos
import crafttweaker.item.IItemStack;
import crafttweaker.item.IIngredient;
import mods.immersiveengineering.ArcFurnace;
import mods.thermalexpansion.InductionSmelter;
print("STARTING DivineRPG.zs");
// Ghast Block
<divinerpg:ghast_pumpkin>.displayName = "Ghast Block";
recipes.remove(<divinerpg:ghast_pumpkin>);
recipes.addShaped(<divinerpg:ghast_pumpkin>, [[<minecraft:ghast_tear>,<minecraft:ghast_tear>,<minecraft:ghast_tear>],[<minecraft:ghast_tear>,<minecraft:ghast_tear>,<minecraft:ghast_tear>],[<minecraft:ghast_tear>,<minecraft:ghast_tear>,<minecraft:ghast_tear>]]);
recipes.addShapeless(<minecraft:ghast_tear> * 9, [<divinerpg:ghast_pumpkin>]);
// Bedrock Pickaxe too OP
recipes.remove(<divinerpg:bedrock_pickaxe>);
// Bedrock Chunk
recipes.remove(<divinerpg:bedrock_chunk>);
recipes.addShaped(<divinerpg:bedrock_chunk>, [[<extrautils2:compressedcobblestone:3>,<extrautils2:compressedcobblestone:3>,<extrautils2:compressedcobblestone:3>],[<extrautils2:compressedcobblestone:3>,<contenttweaker:compressed_obsidian2>,<extrautils2:compressedcobblestone:3>],[<extrautils2:compressedcobblestone:3>,<extrautils2:compressedcobblestone:3>,<extrautils2:compressedcobblestone:3>]]);
// Snowflake Shurikens into Snowflakes
mods.immersiveengineering.ArcFurnace.addRecipe(<divinerpg:snowflake>, <divinerpg:snowflake_shuriken> * 16, null, 40, 100, [<minecraft:ice> * 4]);
//mods.enderio.AlloySmelter.addRecipe(<divinerpg:snowflake>, [<divinerpg:snowflake_shuriken> * 16, <minecraft:ice> * 4], 2500);
// Alloy Smelter recipe in config/enderio/recipes/user/user_recipes.xml
mods.thermalexpansion.InductionSmelter.addRecipe(<divinerpg:snowflake>, <divinerpg:snowflake_shuriken> * 16, <minecraft:ice> * 4, 2500);
// DivineRPG Furnaces not automatable
<divinerpg:coalstone_furnace>.addTooltip(game.localize("dj2.divinerpg_furnace.desc0"));
<divinerpg:greenlight_furnace>.addTooltip(game.localize("dj2.divinerpg_furnace.desc0"));
<divinerpg:oceanfire_furnace>.addTooltip(game.localize("dj2.divinerpg_furnace.desc0"));
<divinerpg:molten_furnace>.addTooltip(game.localize("dj2.divinerpg_furnace.desc0"));
<divinerpg:whitefire_furnace>.addTooltip(game.localize("dj2.divinerpg_furnace.desc0"));
<divinerpg:moonlight_furnace>.addTooltip(game.localize("dj2.divinerpg_furnace.desc0"));
<divinerpg:demon_furnace>.addTooltip(game.localize("dj2.divinerpg_furnace.desc0"));
// Shadow Stone
recipes.remove(<divinerpg:shadow_stone>);
recipes.addShaped(<divinerpg:shadow_stone>, [[<divinerpg:shadow_bar>,<divinerpg:shadow_bar>,<divinerpg:shadow_bar>],[<divinerpg:shadow_bar>,<divinerpg:shadow_bar>,<divinerpg:shadow_bar>],[<divinerpg:shadow_bar>,<divinerpg:shadow_bar>,<divinerpg:shadow_bar>]]);
// Shadow Coins
recipes.remove(<divinerpg:shadow_coins>);
recipes.addShaped(<divinerpg:shadow_coins> * 10, [[<divinerpg:shadow_stone>,<ore:nuggetGold>,<divinerpg:shadow_stone>],[<ore:nuggetGold>,<divinerpg:shadow_stone>,<ore:nuggetGold>],[<divinerpg:shadow_stone>,<ore:nuggetGold>,<divinerpg:shadow_stone>]]);
// Snow Globe
recipes.remove(<divinerpg:snow_globe>);
recipes.addShaped(<divinerpg:snow_globe>, [[<ore:blockGlassColorless>,<minecraft:snow>,<ore:blockGlassColorless>],[<minecraft:snow>,<contenttweaker:atum_warrior>,<minecraft:snow>],[<divinerpg:shadow_stone>,<divinerpg:shadow_stone>,<divinerpg:shadow_stone>]]);
// Infernal Flame
<divinerpg:infernal_flame>.addTooltip(game.localize("dj2.infernal_flame.desc0"));
// Mysterious Clock
recipes.remove(<divinerpg:mysterious_clock>);
recipes.addShaped(<divinerpg:mysterious_clock>, [[<contenttweaker:steaming_restonia_crystal_block>,<minecraft:clock>,<contenttweaker:steaming_restonia_crystal_block>],[<minecraft:clock>,<extrautils2:decorativesolid:8>,<minecraft:clock>],[<divinerpg:corrupted_stone>,<divinerpg:corrupted_stone>,<divinerpg:corrupted_stone>]]);
<divinerpg:mysterious_clock>.addTooltip(game.localize("dj2.mysterious_clock.desc0"));
// Call of the Watcher
recipes.remove(<divinerpg:call_of_the_watcher>);
recipes.addShaped(<divinerpg:call_of_the_watcher>, [[<enderutilities:enderpart:2>,<divinerpg:watching_eye>,<enderutilities:enderpart:2>],[<divinerpg:watching_eye>,<extrautils2:decorativesolid:8>,<divinerpg:watching_eye>],[<divinerpg:molten_stone>,<divinerpg:molten_stone>,<divinerpg:molten_stone>]]);
<divinerpg:call_of_the_watcher>.addTooltip(game.localize("dj2.call_of_the_watcher.desc0"));
// Horde Horn
recipes.remove(<divinerpg:horde_horn>);
recipes.addShaped(<divinerpg:horde_horn>, [[<thermalfoundation:storage:7>,<actuallyadditions:item_misc:15>,<thermalfoundation:storage:7>],[<actuallyadditions:item_misc:15>,<extrautils2:decorativesolid:8>,<actuallyadditions:item_misc:15>],[<divinerpg:ender_stone>,<divinerpg:ender_stone>,<divinerpg:ender_stone>]]);
<divinerpg:horde_horn>.addTooltip(game.localize("dj2.horde_horn.desc0"));
<divinerpg:horde_horn>.addTooltip(game.localize("dj2.horde_horn.desc1"));
// Angelic Chestplate
recipes.remove(<divinerpg:angelic_chestplate>);
recipes.addShaped(<divinerpg:angelic_chestplate>, [[<divinerpg:bluefire_stone>,null,<divinerpg:bluefire_stone>],[<divinerpg:ice_stone>,<contenttweaker:block_of_elevation>,<divinerpg:ice_stone>],[<divinerpg:ice_stone>,<divinerpg:ice_stone>,<divinerpg:ice_stone>]]);
// Divine Rock
recipes.remove(<divinerpg:divine_rock>);
recipes.addShaped(<divinerpg:divine_rock> * 14, [[<divinerpg:divine_shards>,<divinerpg:divine_shards>,<divinerpg:divine_shards>],[<divinerpg:divine_shards>,<contenttweaker:unholy_token>,<divinerpg:divine_shards>],[<divinerpg:divine_shards>,<divinerpg:divine_stone>,<divinerpg:divine_shards>]]);
// Twilight Clock
recipes.remove(<divinerpg:twilight_clock>);
recipes.addShaped(<divinerpg:twilight_clock>, [[<openblocks:tank>.withTag({tank: {FluidName: "cryotheum", Amount: 16000}}),<divinerpg:bluefire_stone>,<openblocks:tank>.withTag({tank: {FluidName: "cryotheum", Amount: 16000}})],[<divinerpg:bluefire_stone>,<enderutilities:enderpart:54>,<divinerpg:bluefire_stone>],[<enderio:block_alloy:6>,<minecraft:clock>,<enderio:block_alloy:6>]]);
<divinerpg:twilight_clock>.addTooltip(game.localize("dj2.twilight_clock.desc0"));
<divinerpg:twilight_clock>.addTooltip(game.localize("dj2.twilight_clock.desc1"));
function divinerpg_new_gem_and_chunk_recipes(fragments as IItemStack, gem as IItemStack, chunk as IItemStack) {
recipes.remove(gem);
recipes.addShaped(gem, [[null,fragments,null],[fragments,fragments,fragments],[null,fragments,null]]);
recipes.remove(chunk);
recipes.addShaped(chunk, [[null,gem,null],[gem,gem,gem],[null,gem,null]]);
}
// Eden Gem & Chunk
divinerpg_new_gem_and_chunk_recipes(<divinerpg:eden_fragments>, <divinerpg:eden_gem>, <divinerpg:eden_chunk>);
// Wildwood Gem & Chunk
divinerpg_new_gem_and_chunk_recipes(<divinerpg:wildwood_fragments>, <divinerpg:wildwood_gem>, <divinerpg:wildwood_chunk>);
// Apalachia Gem & Chunk
divinerpg_new_gem_and_chunk_recipes(<divinerpg:apalachia_fragments>, <divinerpg:apalachia_gem>, <divinerpg:apalachia_chunk>);
// Skythern Gem & Chunk
divinerpg_new_gem_and_chunk_recipes(<divinerpg:skythern_fragments>, <divinerpg:skythern_gem>, <divinerpg:skythern_chunk>);
// Mortum Gem & Chunk
divinerpg_new_gem_and_chunk_recipes(<divinerpg:mortum_fragments>, <divinerpg:mortum_gem>, <divinerpg:mortum_chunk>);
// Inferno sword
recipes.remove(<divinerpg:inferno_sword>);
recipes.addShaped(<divinerpg:inferno_sword>, [[<minecraft:blaze_powder>,<ore:oreRedstone>,<minecraft:blaze_powder>],[<minecraft:blaze_powder>,<ore:oreRedstone>,<minecraft:blaze_powder>],[<minecraft:blaze_powder>,<ore:stickWood>,<minecraft:blaze_powder>]]);
// Eden Chest
recipes.remove(<divinerpg:eden_chest>);
recipes.addShaped(<divinerpg:eden_chest>, [[<divinerpg:eden_gem>,<divinerpg:eden_gem>,<divinerpg:eden_gem>],[<divinerpg:eden_gem>,<minecraft:iron_nugget>,<divinerpg:eden_gem>],[<divinerpg:eden_gem>,<divinerpg:eden_gem>,<divinerpg:eden_gem>]]);
// Bone Chest
recipes.remove(<divinerpg:bone_chest>);
recipes.addShaped(<divinerpg:bone_chest>, [[<minecraft:bone_block>,<minecraft:bone>,<minecraft:bone_block>],[<minecraft:bone>,<minecraft:iron_nugget>,<minecraft:bone>],[<minecraft:bone_block>,<minecraft:bone>,<minecraft:bone_block>]]);
// Heart of the Sunstorm
<divinerpg:eden_heart>.addTooltip(game.localize("dj2.eden_heart.desc0"));
<divinerpg:eden_heart>.addTooltip(game.localize("dj2.eden_heart.desc1"));
// Eden Block
recipes.remove(<divinerpg:eden_block>);
mods.extendedcrafting.TableCrafting.addShaped(<divinerpg:eden_block> * 14,
[[<divinerpg:eden_chunk>,<abyssalcraft:oblivionshard>,<divinerpg:eden_soul>,<abyssalcraft:oblivionshard>,<divinerpg:eden_chunk>],
[<abyssalcraft:oblivionshard>,<divinerpg:eden_heart>,<abyssalcraft:eoa>,<divinerpg:eden_heart>,<abyssalcraft:oblivionshard>],
[<divinerpg:eden_chunk>,<divinerpg:eden_soul>,<divinerpg:eden_heart>,<divinerpg:eden_soul>,<divinerpg:eden_chunk>],
[<abyssalcraft:oblivionshard>,<divinerpg:eden_heart>,<abyssalcraft:psdl>,<divinerpg:eden_heart>,<abyssalcraft:oblivionshard>],
[<divinerpg:eden_chunk>,<abyssalcraft:oblivionshard>,<divinerpg:eden_soul>,<abyssalcraft:oblivionshard>,<divinerpg:eden_chunk>]]);
// Kraken Scale
recipes.remove(<divinerpg:kraken_scale>);
recipes.addShapedMirrored(<divinerpg:kraken_scale>, [[<minecraft:dye>,<minecraft:dye>,<ore:slimeball>],[<minecraft:dye>,<minecraft:fish>,<minecraft:dye>],[<ore:slimeball>,<minecraft:dye>,<minecraft:dye>]]);
// Kraken Skin
recipes.remove(<divinerpg:kraken_skin>);
recipes.addShapedMirrored(<divinerpg:kraken_skin>, [[<contenttweaker:treated_leather>,<divinerpg:kraken_scale>],[<divinerpg:kraken_scale>,<contenttweaker:treated_leather>]]);
// Aqua Ball
recipes.remove(<divinerpg:aqua_ball>);
recipes.addShaped(<divinerpg:aqua_ball>, [[<liquid:water> * 1000,<ore:slimeball>,<liquid:water> * 1000],[<liquid:water> * 1000,<divinerpg:kraken_skin>,<liquid:water> * 1000],[<liquid:water> * 1000,<ore:slimeball>,<liquid:water> * 1000]]);
// Arlemite Armor
recipes.remove(<divinerpg:arlemite_helmet>);
recipes.addShaped(<divinerpg:arlemite_helmet>, [[<divinerpg:arlemite_block>,<thermalfoundation:material:136>,<divinerpg:arlemite_block>],[<thermalfoundation:material:136>,null,<thermalfoundation:material:136>]]);
recipes.remove(<divinerpg:arlemite_chestplate>);
recipes.addShaped(<divinerpg:arlemite_chestplate>, [[<thermalfoundation:material:136>,null,<thermalfoundation:material:136>],[<divinerpg:arlemite_block>,<thermalfoundation:material:136>,<divinerpg:arlemite_block>],[<thermalfoundation:material:136>,<divinerpg:arlemite_block>,<thermalfoundation:material:136>]]);
recipes.remove(<divinerpg:arlemite_leggings>);
recipes.addShaped(<divinerpg:arlemite_leggings>, [[<thermalfoundation:material:136>,<divinerpg:arlemite_block>,<thermalfoundation:material:136>],[<thermalfoundation:material:136>,null,<thermalfoundation:material:136>],[<divinerpg:arlemite_block>,null,<divinerpg:arlemite_block>]]);
recipes.remove(<divinerpg:arlemite_boots>);
recipes.addShaped(<divinerpg:arlemite_boots>, [[<thermalfoundation:material:136>,null,<thermalfoundation:material:136>],[<divinerpg:arlemite_block>,null,<divinerpg:arlemite_block>]]);
// Rupee Armor
recipes.remove(<divinerpg:rupee_helmet>);
recipes.addShaped(<divinerpg:rupee_helmet>, [[<divinerpg:rupee_block>,<thermalfoundation:material:136>,<divinerpg:rupee_block>],[<thermalfoundation:material:136>,null,<thermalfoundation:material:136>]]);
recipes.remove(<divinerpg:rupee_chestplate>);
recipes.addShaped(<divinerpg:rupee_chestplate>, [[<thermalfoundation:material:136>,null,<thermalfoundation:material:136>],[<divinerpg:rupee_block>,<thermalfoundation:material:136>,<divinerpg:rupee_block>],[<thermalfoundation:material:136>,<divinerpg:rupee_block>,<thermalfoundation:material:136>]]);
recipes.remove(<divinerpg:rupee_leggings>);
recipes.addShaped(<divinerpg:rupee_leggings>, [[<thermalfoundation:material:136>,<divinerpg:rupee_block>,<thermalfoundation:material:136>],[<thermalfoundation:material:136>,null,<thermalfoundation:material:136>],[<divinerpg:rupee_block>,null,<divinerpg:rupee_block>]]);
recipes.remove(<divinerpg:rupee_boots>);
recipes.addShaped(<divinerpg:rupee_boots>, [[<thermalfoundation:material:136>,null,<thermalfoundation:material:136>],[<divinerpg:rupee_block>,null,<divinerpg:rupee_block>]]);
function add_DivineRPG_dimensional_armor_recipes(cur_helmet as IItemStack, cur_chestplate as IItemStack, cur_leggings as IItemStack, cur_boots as IItemStack,
prev_helmet as IItemStack, prev_chestplate as IItemStack, prev_leggings as IItemStack, prev_boots as IItemStack,
drpg_chunk as IItemStack, extra_material as IItemStack) {
recipes.remove(cur_helmet);
recipes.addShaped(cur_helmet, [[extra_material,drpg_chunk,extra_material],[drpg_chunk,prev_helmet,drpg_chunk]]);
recipes.remove(cur_chestplate);
recipes.addShaped(cur_chestplate, [[drpg_chunk,prev_chestplate,drpg_chunk],[extra_material,drpg_chunk,extra_material],[drpg_chunk,extra_material,drpg_chunk]]);
recipes.remove(cur_leggings);
recipes.addShaped(cur_leggings, [[drpg_chunk,extra_material,drpg_chunk],[drpg_chunk,prev_leggings,drpg_chunk],[extra_material,null,extra_material]]);
recipes.remove(cur_boots);
recipes.addShaped(cur_boots, [[drpg_chunk,null,drpg_chunk],[extra_material,prev_boots,extra_material]]);
}
// Wildwood Armor
add_DivineRPG_dimensional_armor_recipes(<divinerpg:wildwood_helmet>,<divinerpg:wildwood_chestplate>,<divinerpg:wildwood_leggings>,<divinerpg:wildwood_boots>,
<divinerpg:eden_helmet>,<divinerpg:eden_chestplate>,<divinerpg:eden_leggings>,<divinerpg:eden_boots>,
<divinerpg:wildwood_chunk>,<botania:storage>);
// Apalachia Armor
add_DivineRPG_dimensional_armor_recipes(<divinerpg:apalachia_helmet>,<divinerpg:apalachia_chestplate>,<divinerpg:apalachia_leggings>,<divinerpg:apalachia_boots>,
<divinerpg:wildwood_helmet>,<divinerpg:wildwood_chestplate>,<divinerpg:wildwood_leggings>,<divinerpg:wildwood_boots>,
<divinerpg:apalachia_chunk>,<botania:storage:2>);
// Skythern Armor
add_DivineRPG_dimensional_armor_recipes(<divinerpg:skythern_helmet>,<divinerpg:skythern_chestplate>,<divinerpg:skythern_leggings>,<divinerpg:skythern_boots>,
<divinerpg:apalachia_helmet>,<divinerpg:apalachia_chestplate>,<divinerpg:apalachia_leggings>,<divinerpg:apalachia_boots>,
<divinerpg:skythern_chunk>,<thaumcraft:plate:3>);
// Mortum Armor
add_DivineRPG_dimensional_armor_recipes(<divinerpg:mortum_helmet>,<divinerpg:mortum_chestplate>,<divinerpg:mortum_leggings>,<divinerpg:mortum_boots>,
<divinerpg:skythern_helmet>,<divinerpg:skythern_chestplate>,<divinerpg:skythern_leggings>,<divinerpg:skythern_boots>,
<divinerpg:mortum_chunk>,<bewitchment:cold_iron_ingot>);
// Wildwood Block
recipes.remove(<divinerpg:wildwood_block>);
mods.extendedcrafting.TableCrafting.addShaped(<divinerpg:wildwood_block> * 14,
[[<botania:storage>,<divinerpg:wildwood_chunk>,<botania:storage:3>,<divinerpg:wildwood_chunk>,<botania:storage>],
[<divinerpg:wildwood_chunk>,<botania:manaresource:22>,<botania:managlass>,<botania:manaresource:22>,<divinerpg:wildwood_chunk>],
[<botania:storage:3>,<botania:managlass>,<botania:managlass>,<botania:managlass>,<botania:storage:3>],
[<divinerpg:wildwood_chunk>,<botania:manaresource:22>,<botania:managlass>,<botania:manaresource:22>,<divinerpg:wildwood_chunk>],
[<botania:storage>,<divinerpg:wildwood_chunk>,<botania:storage:3>,<divinerpg:wildwood_chunk>,<botania:storage>]]);
/*
mods.extendedcrafting.TableCrafting.addShaped(<divinerpg:wildwood_block> * 14,
[[<botania:storage>,<divinerpg:wildwood_chunk>,<botania:storage:3>,<divinerpg:wildwood_chunk>,<botania:storage>],
[<divinerpg:wildwood_chunk>,<botania:spellcloth>.noReturn(),<botania:managlass>,<botania:spellcloth>.noReturn(),<divinerpg:wildwood_chunk>],
[<botania:storage:3>,<botania:managlass>,<botania:managlass>,<botania:managlass>,<botania:storage:3>],
[<divinerpg:wildwood_chunk>,<botania:spellcloth>.noReturn(),<botania:managlass>,<botania:spellcloth>.noReturn(),<divinerpg:wildwood_chunk>],
[<botania:storage>,<divinerpg:wildwood_chunk>,<botania:storage:3>,<divinerpg:wildwood_chunk>,<botania:storage>]]);*/
// Apalachia Block
recipes.remove(<divinerpg:apalachia_block>);
mods.extendedcrafting.TableCrafting.addShaped(<divinerpg:apalachia_block> * 14,
[[<thaumcraft:plate:2>,<thaumcraft:salis_mundus>,<thaumcraft:salis_mundus>,<thaumcraft:salis_mundus>,<thaumcraft:plate:2>],
[<thaumcraft:salis_mundus>,<thaumcraft:crystal_essence>.withTag({Aspects: [{amount: 1, key: "alienis"}]}),<thaumcraft:crystal_essence>.withTag({Aspects: [{amount: 1, key: "alienis"}]}),<thaumcraft:crystal_essence>.withTag({Aspects: [{amount: 1, key: "alienis"}]}),<thaumcraft:salis_mundus>],
[<thaumcraft:salis_mundus>,<thaumcraft:morphic_resonator>,<botania:manaresource:14>,<thaumcraft:morphic_resonator>,<thaumcraft:salis_mundus>],
[<thaumcraft:salis_mundus>,<thaumcraft:crystal_essence>.withTag({Aspects: [{amount: 1, key: "alienis"}]}),<thaumcraft:crystal_essence>.withTag({Aspects: [{amount: 1, key: "alienis"}]}),<thaumcraft:crystal_essence>.withTag({Aspects: [{amount: 1, key: "alienis"}]}),<thaumcraft:salis_mundus>],
[<thaumcraft:plate:2>,<thaumcraft:salis_mundus>,<thaumcraft:salis_mundus>,<thaumcraft:salis_mundus>,<thaumcraft:plate:2>]]);
// Skythern Block
recipes.remove(<divinerpg:skythern_block>);
mods.extendedcrafting.TableCrafting.addShaped(<divinerpg:skythern_block> * 14,
[[<contenttweaker:condensed_vis_crystal_auram>,<contenttweaker:condensed_vis_crystal_spiritus>,<contenttweaker:condensed_vis_crystal_motus>,<contenttweaker:condensed_vis_crystal_spiritus>,<contenttweaker:condensed_vis_crystal_auram>],
[<contenttweaker:condensed_vis_crystal_spiritus>,<thaumcraft:plate:2>,<divinerpg:skythern_heart>,<thaumcraft:plate:2>,<contenttweaker:condensed_vis_crystal_spiritus>],
[<thaumcraft:morphic_resonator>,<thaumcraft:metal_alchemical>,<thaumcraft:mechanism_complex>,<thaumcraft:metal_alchemical>,<thaumcraft:morphic_resonator>],
[<contenttweaker:condensed_vis_crystal_spiritus>,<thaumcraft:plate:2>,<divinerpg:skythern_heart>,<thaumcraft:plate:2>,<contenttweaker:condensed_vis_crystal_spiritus>],
[<contenttweaker:condensed_vis_crystal_auram>,<contenttweaker:condensed_vis_crystal_spiritus>,<contenttweaker:condensed_vis_crystal_motus>,<contenttweaker:condensed_vis_crystal_spiritus>,<contenttweaker:condensed_vis_crystal_auram>]]);
// Arcana Portal Frame
recipes.remove(<divinerpg:arcana_portal_frame>);
mods.extendedcrafting.TableCrafting.addShaped(<divinerpg:arcana_portal_frame> * 12,
[[<divinerpg:bluefire_stone>,<contenttweaker:arcanium_base>,<contenttweaker:arcanium_base>,<divinerpg:bluefire_stone>,<contenttweaker:arcanium_base>,<contenttweaker:arcanium_base>,<divinerpg:bluefire_stone>],
[<contenttweaker:arcanium_base>,<contenttweaker:condensed_vis_crystal_stellae>,<thaumcraft:plate:3>,<contenttweaker:condensed_vis_crystal_tenebrae>,<thaumcraft:plate:3>,<contenttweaker:condensed_vis_crystal_stellae>,<contenttweaker:arcanium_base>],
[<contenttweaker:arcanium_base>,<thaumcraft:plate:3>,<bewitchment:demonic_elixir>.noReturn(),<thaumicaugmentation:material:5>,<bewitchment:demonic_elixir>.noReturn(),<thaumcraft:plate:3>,<contenttweaker:arcanium_base>],
[<divinerpg:bluefire_stone>,<contenttweaker:condensed_vis_crystal_tenebrae>,<thaumicaugmentation:material:5>,<bewitchment:leonards_wand>,<thaumicaugmentation:material:5>,<contenttweaker:condensed_vis_crystal_tenebrae>,<divinerpg:bluefire_stone>],
[<contenttweaker:arcanium_base>,<thaumcraft:plate:3>,<bewitchment:demonic_elixir>.noReturn(),<thaumicaugmentation:material:5>,<bewitchment:demonic_elixir>.noReturn(),<thaumcraft:plate:3>,<contenttweaker:arcanium_base>],
[<contenttweaker:arcanium_base>,<contenttweaker:condensed_vis_crystal_stellae>,<thaumcraft:plate:3>,<contenttweaker:condensed_vis_crystal_tenebrae>,<thaumcraft:plate:3>,<contenttweaker:condensed_vis_crystal_stellae>,<contenttweaker:arcanium_base>],
[<divinerpg:bluefire_stone>,<contenttweaker:arcanium_base>,<contenttweaker:arcanium_base>,<divinerpg:bluefire_stone>,<contenttweaker:arcanium_base>,<contenttweaker:arcanium_base>,<divinerpg:bluefire_stone>]]);
// Dungeon Bookshelf
recipes.remove(<divinerpg:dungeon_bookshelf>);
<divinerpg:dungeon_bookshelf>.addTooltip(game.localize("dj2.dungeon_bookshelf.desc0"));
<divinerpg:dungeon_bookshelf>.addTooltip(game.localize("dj2.dungeon_bookshelf.desc1"));
// Acceleron
<divinerpg:acceleron>.addTooltip(game.localize("dj2.acceleron.desc0"));
// Raw Arcanium
<divinerpg:raw_arcanium>.addTooltip(game.localize("dj2.raw_arcanium.desc0"));
<divinerpg:raw_arcanium>.addTooltip(game.localize("dj2.raw_arcanium.desc1"));
// Molten Furnace
<divinerpg:molten_furnace>.addTooltip(game.localize("dj2.molten_furnace.desc0"));
<divinerpg:molten_furnace>.addTooltip(game.localize("dj2.molten_furnace.desc1"));
// Dungeon Tokens
<divinerpg:dungeon_tokens>.addTooltip(game.localize("dj2.dungeon_tokens.desc0"));
<divinerpg:dungeon_tokens>.addTooltip(game.localize("dj2.dungeon_tokens.desc1"));
<divinerpg:dungeon_tokens>.addTooltip(game.localize("dj2.dungeon_tokens.desc2"));
// Wizards Book
<divinerpg:wizards_book>.addTooltip(game.localize("dj2.wizards_book.desc0"));
// Mortum Block
recipes.remove(<divinerpg:mortum_block>);
mods.extendedcrafting.TableCrafting.addShaped(<divinerpg:mortum_block> * 3,
[[<contenttweaker:condensed_vis_crystal_tenebrae>,<contenttweaker:conducted_impetus>,<thaumcraft:plate:3>,<thaumcraft:plate:3>,<thaumcraft:plate:3>,<contenttweaker:conducted_impetus>,<contenttweaker:condensed_vis_crystal_tenebrae>],
[<contenttweaker:conducted_impetus>,<contenttweaker:conducted_impetus>,<divinerpg:mortum_chunk>,<divinerpg:mortum_soul>,<divinerpg:mortum_chunk>,<contenttweaker:conducted_impetus>,<contenttweaker:conducted_impetus>],
[<thaumcraft:plate:3>,<divinerpg:mortum_chunk>,<divinerpg:mortum_soul>,<divinerpg:mortum_soul>,<divinerpg:mortum_soul>,<divinerpg:mortum_chunk>,<thaumcraft:plate:3>],
[<thaumcraft:plate:3>,<divinerpg:mortum_soul>,<divinerpg:mortum_soul>,<divinerpg:mortum_heart>,<divinerpg:mortum_soul>,<divinerpg:mortum_soul>,<thaumcraft:plate:3>],
[<thaumcraft:plate:3>,<divinerpg:mortum_chunk>,<divinerpg:mortum_soul>,<divinerpg:mortum_soul>,<divinerpg:mortum_soul>,<divinerpg:mortum_chunk>,<thaumcraft:plate:3>],
[<contenttweaker:conducted_impetus>,<contenttweaker:conducted_impetus>,<divinerpg:mortum_chunk>,<divinerpg:mortum_soul>,<divinerpg:mortum_chunk>,<contenttweaker:conducted_impetus>,<contenttweaker:conducted_impetus>],
[<contenttweaker:condensed_vis_crystal_tenebrae>,<contenttweaker:conducted_impetus>,<thaumcraft:plate:3>,<thaumcraft:plate:3>,<thaumcraft:plate:3>,<contenttweaker:conducted_impetus>,<contenttweaker:condensed_vis_crystal_tenebrae>]]);
// Nightmare Bed
recipes.remove(<divinerpg:nightmare_bed>);
recipes.addShaped(<divinerpg:nightmare_bed>, [[<divinerpg:acceleron>,<divinerpg:acceleron>,<divinerpg:acceleron>],[<divinerpg:mortum_block>,<divinerpg:mortum_block>,<divinerpg:mortum_block>]]);
// Eden to Mortum Bows
function addDivineRPGBowRecipe(new_bow as IItemStack, old_bow as IItemStack, new_material as IIngredient) {
recipes.remove(new_bow);
recipes.addShapedMirrored(new_bow, [[null,new_material,<botania:manaresource:16>],[new_material,old_bow,<botania:manaresource:16>],[null,new_material,<botania:manaresource:16>]]);
}
// Eden Bow
addDivineRPGBowRecipe(<divinerpg:eden_bow>,<minecraft:bow>,<divinerpg:eden_chunk>);
// Wildwood Bow
addDivineRPGBowRecipe(<divinerpg:wildwood_bow>,<divinerpg:eden_bow>,<divinerpg:wildwood_chunk>);
// Apalachia Bow
addDivineRPGBowRecipe(<divinerpg:apalachia_bow>,<divinerpg:wildwood_bow>,<divinerpg:apalachia_chunk>);
// Skythern Bow
addDivineRPGBowRecipe(<divinerpg:skythern_bow>,<divinerpg:apalachia_bow>,<divinerpg:skythern_chunk>);
// Mortum Bow
addDivineRPGBowRecipe(<divinerpg:mortum_bow>,<divinerpg:skythern_bow>,<divinerpg:mortum_chunk>);
// Spawn Crystals
recipes.remove(<divinerpg:base_spawn_crystal>);
recipes.remove(<divinerpg:vamacheron_crystal>);
recipes.remove(<divinerpg:twilight_demon_crystal>);
recipes.remove(<divinerpg:soul_fiend_crystal>);
recipes.remove(<divinerpg:reyvor_crystal>);
recipes.remove(<divinerpg:karot_crystal>);
recipes.remove(<divinerpg:densos_crystal>);
print("ENDING DivineRPG.zs");
| 412 | 0.605537 | 1 | 0.605537 | game-dev | MEDIA | 0.96947 | game-dev | 0.599081 | 1 | 0.599081 |
Skitttyy/shoreline-client | 2,441 | src/main/java/net/shoreline/client/util/entity/EntityUtil.java | package net.shoreline.client.util.entity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.mob.*;
import net.minecraft.entity.passive.*;
import net.minecraft.entity.vehicle.BoatEntity;
import net.minecraft.entity.vehicle.ChestMinecartEntity;
import net.minecraft.entity.vehicle.FurnaceMinecartEntity;
import net.minecraft.entity.vehicle.MinecartEntity;
import net.minecraft.util.math.BlockPos;
import net.shoreline.client.util.Globals;
import net.shoreline.client.util.chat.ChatUtil;
/**
* @author linus
* @since 1.0
*/
public class EntityUtil implements Globals
{
/**
*
* @param entity
* @return
*/
public static BlockPos getRoundedBlockPos(Entity entity)
{
return new BlockPos(entity.getBlockX(), (int) Math.round(entity.getY()), entity.getBlockZ());
}
/**
* @param entity
* @return
*/
public static float getHealth(Entity entity)
{
if (entity instanceof LivingEntity e)
{
return e.getHealth() + e.getAbsorptionAmount();
}
return 0.0f;
}
/**
* @param e
* @return
*/
public static boolean isMonster(Entity e)
{
return e instanceof Monster && !isNeutralInternal(e);
}
private static boolean isNeutralInternal(Entity e)
{
return e instanceof EndermanEntity enderman && !enderman.isAttacking()
|| e instanceof ZombifiedPiglinEntity piglin && !piglin.isAttacking()
|| e instanceof WolfEntity wolf && !wolf.isAttacking()
|| e instanceof IronGolemEntity ironGolem && !ironGolem.isAttacking()
|| e instanceof BeeEntity bee && !bee.isAttacking();
}
/**
* @param e
* @return
*/
public static boolean isNeutral(Entity e)
{
return e instanceof EndermanEntity || e instanceof ZombifiedPiglinEntity || e instanceof WolfEntity || e instanceof IronGolemEntity;
}
/**
* @param e
* @return
*/
public static boolean isPassive(Entity e)
{
return e instanceof PassiveEntity || e instanceof AmbientEntity || e instanceof SquidEntity;
}
public static boolean isVehicle(Entity e)
{
return e instanceof BoatEntity || e instanceof MinecartEntity
|| e instanceof FurnaceMinecartEntity
|| e instanceof ChestMinecartEntity;
}
}
| 412 | 0.616625 | 1 | 0.616625 | game-dev | MEDIA | 0.944858 | game-dev | 0.526922 | 1 | 0.526922 |
AlexProgrammerDE/SoulFire | 11,314 | mod/src/main/java/com/soulfiremc/server/pathfinding/RouteFinder.java | /*
* SoulFire
* Copyright (C) 2024 AlexProgrammerDE
*
* 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/>.
*/
package com.soulfiremc.server.pathfinding;
import com.google.common.base.Stopwatch;
import com.soulfiremc.server.pathfinding.execution.MovementAction;
import com.soulfiremc.server.pathfinding.execution.RecalculatePathAction;
import com.soulfiremc.server.pathfinding.execution.WorldAction;
import com.soulfiremc.server.pathfinding.goals.GoalScorer;
import com.soulfiremc.server.pathfinding.graph.GraphInstructions;
import com.soulfiremc.server.pathfinding.graph.MinecraftGraph;
import com.soulfiremc.server.pathfinding.graph.OutOfLevelException;
import com.soulfiremc.server.util.structs.CallLimiter;
import com.soulfiremc.server.util.structs.IntReference;
import com.soulfiremc.server.util.structs.Long2ObjectLRUCache;
import it.unimi.dsi.fastutil.longs.Long2IntMap;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectHeapPriorityQueue;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.VisibleForTesting;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
@Slf4j
public record RouteFinder(MinecraftGraph graph, GoalScorer scorer) {
private static List<WorldAction> reconstructPath(MinecraftRouteNode current) {
var actions = new ArrayList<WorldAction>();
var currentElement = current;
do {
var previousActions = new ArrayList<>(currentElement.actions());
// Insert the actions in reversed order
for (var i = previousActions.size() - 1; i >= 0; i--) {
actions.addFirst(previousActions.get(i));
}
currentElement = currentElement.parent();
} while (currentElement != null);
return actions;
}
private static MinecraftRouteNode findBestNode(Collection<MinecraftRouteNode> values) {
MinecraftRouteNode bestNode = null;
var smallestScore = Double.MAX_VALUE;
for (var node : values) {
// Our implementation calculates the score from this node to the start,
// so we need to get it by subtracting the source cost
var targetScore = node.totalRouteScore() - node.sourceCost();
if (targetScore < smallestScore) {
smallestScore = targetScore;
bestNode = node;
}
}
return Objects.requireNonNull(bestNode, "No best node found");
}
public CompletableFuture<List<WorldAction>> findRouteFuture(NodeState from, boolean requiresRepositioning) {
return CompletableFuture.supplyAsync(() -> repositionIfNeeded(findRouteSync(from), from, requiresRepositioning));
}
@VisibleForTesting
public List<WorldAction> findRouteSync(NodeState from) {
var stopwatch = Stopwatch.createStarted();
var expireTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(Integer.getInteger("sf.pathfinding-expire", 180));
// Store block positions and the best route to them
var blockItemsIndex = new Long2IntOpenHashMap();
var instructionCache = new Long2ObjectLRUCache<GraphInstructions[]>(50_000);
var routeIndex = new Object2ObjectOpenHashMap<NodeState, MinecraftRouteNode>();
// Store block positions that we need to look at
var openSet = new ObjectHeapPriorityQueue<MinecraftRouteNode>();
{
var startScore = scorer.computeScore(graph, from.blockPosition(), List.of());
log.debug("Start score (Usually distance): {}", startScore);
var start =
new MinecraftRouteNode(
from,
List.of(),
0,
startScore,
startScore);
routeIndex.put(from, start);
openSet.enqueue(start);
}
var progressInfo = new CallLimiter(() -> {
if (!log.isInfoEnabled()) {
return;
}
var bestNode = findBestNode(routeIndex.values());
log.info("Still looking for route... {}ms time left, {} nodes left, closest position is {} with distance {}",
expireTime - System.currentTimeMillis(),
openSet.size(),
bestNode.node().blockPosition().formatXYZ(),
bestNode.totalRouteScore() - bestNode.sourceCost()
);
}, 1, TimeUnit.SECONDS, true);
var cleaner = new CallLimiter(() -> {
if (Boolean.getBoolean("sf.pathfinding-no-prune")) {
return;
}
log.info("Pruning route index and open set to avoid branching");
var bestNode = findBestNode(routeIndex.values());
openSet.clear();
openSet.enqueue(bestNode);
routeIndex.clear();
}, 5, TimeUnit.SECONDS, true);
while (!openSet.isEmpty()) {
if (Thread.currentThread().isInterrupted()) {
stopwatch.stop();
log.info("Cancelled pathfinding after {}ms", stopwatch.elapsed().toMillis());
return List.of();
} else if (System.currentTimeMillis() > expireTime) {
stopwatch.stop();
log.info("Expired pathfinding after {}ms", stopwatch.elapsed().toMillis());
throw new IllegalStateException("Pathfinding took too long");
}
progressInfo.run();
cleaner.run();
var current = openSet.dequeue();
log.debug("Looking at node: {}", current.node());
// If we found our destination, we can stop looking
if (scorer.isFinished(current)) {
stopwatch.stop();
log.info("Success! Took {}ms to find route", stopwatch.elapsed().toMillis());
return reconstructPath(current);
}
try {
instructionCache.compute(current.node().blockPosition().asMinecraftLong(), (k, v) -> {
if (v == null) {
var counter = new IntReference();
var list = new GraphInstructions[MinecraftGraph.ACTIONS_SIZE];
graph.insertActions(
current.node().blockPosition(),
current.parentToNodeDirection(),
instructions -> {
list[counter.value++] = instructions;
handleInstructions(openSet, routeIndex, blockItemsIndex, current, instructions);
}
);
return list;
}
for (var instructions : v) {
if (instructions == null) {
break;
}
handleInstructions(openSet, routeIndex, blockItemsIndex, current, instructions);
}
return v;
});
} catch (OutOfLevelException e) {
log.debug("Found a node out of the level: {}", current.node());
stopwatch.stop();
log.info(
"Took {}ms to find route to reach the edge of view distance",
stopwatch.elapsed().toMillis());
// The current node is not always the best node. We need to find the best node.
var bestNode = findBestNode(routeIndex.values());
// This is the best node we found so far
// We will add a recalculating action and return the best route
var recalculateTrace = reconstructPath(bestNode);
if (recalculateTrace.isEmpty()) {
throw new AlreadyClosestException();
}
return addRecalculate(recalculateTrace);
}
}
stopwatch.stop();
log.info("Failed to find route after {}ms", stopwatch.elapsed().toMillis());
throw new NoRouteFoundException();
}
private void handleInstructions(ObjectHeapPriorityQueue<MinecraftRouteNode> openSet,
Map<NodeState, MinecraftRouteNode> routeIndex,
Long2IntMap blockItemsIndex,
MinecraftRouteNode current,
GraphInstructions instructions) {
// Creative mode placing requires us to have at least one block
if (instructions.requiresOneBlock() && current.node().usableBlockItems() < 1) {
return;
}
var newBlocks = current.node().usableBlockItems() + instructions.deltaUsableBlockItems();
// If we don't have enough items to reach this node, we can skip it
if (newBlocks < 0) {
return;
}
var instructionNode = new NodeState(instructions.blockPosition(), newBlocks);
// Pre-check if we can reach this node with the current amount of items
// We don't want to consider nodes again where we have even less usable items
var bestUsableItems = blockItemsIndex.compute(instructionNode.blockPosition().asMinecraftLong(), (k, v) -> {
if (v == null || instructionNode.usableBlockItems() > v) {
return instructionNode.usableBlockItems();
}
return v;
});
if (bestUsableItems > instructionNode.usableBlockItems()) {
return;
}
var actionCost = instructions.actionCost();
var worldActions = instructions.actions();
// Calculate new distance from start to this connection,
// Get distance from the current element
// and add the distance from the current element to the next element
var newSourceCost = current.sourceCost() + actionCost;
var newTargetCost = scorer.computeScore(graph, instructionNode.blockPosition(), worldActions);
var newTotalRouteScore = newSourceCost + newTargetCost;
routeIndex.compute(
instructionNode,
(k, v) -> {
// The first time we see this node
if (v == null) {
var node =
new MinecraftRouteNode(
instructionNode,
current,
instructions.moveDirection(),
worldActions,
newSourceCost,
newTargetCost,
newTotalRouteScore);
log.debug("Found a new node: {}", instructionNode);
openSet.enqueue(node);
return node;
}
// If we found a better route to this node, update it
if (newSourceCost < v.sourceCost()) {
v.setBetterParent(
current,
instructions.moveDirection(),
worldActions,
newSourceCost,
newTargetCost,
newTotalRouteScore);
log.debug("Found a better route to node: {}", instructionNode);
openSet.enqueue(v);
}
return v;
});
}
private List<WorldAction> repositionIfNeeded(List<WorldAction> actions, NodeState from, boolean requiresRepositioning) {
if (!requiresRepositioning) {
return actions;
}
var repositionActions = new ArrayList<WorldAction>();
repositionActions.add(new MovementAction(from.blockPosition(), false));
repositionActions.addAll(actions);
return repositionActions;
}
private List<WorldAction> addRecalculate(List<WorldAction> actions) {
var repositionActions = new ArrayList<>(actions);
repositionActions.add(new RecalculatePathAction());
return repositionActions;
}
}
| 412 | 0.962477 | 1 | 0.962477 | game-dev | MEDIA | 0.925072 | game-dev | 0.993585 | 1 | 0.993585 |
mauge123/mechanical-blender | 5,123 | extern/bullet2/src/BulletCollision/Gimpact/btTriangleShapeEx.h | /*! \file btGImpactShape.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.
*/
#ifndef GIMPACT_TRIANGLE_SHAPE_EX_H
#define GIMPACT_TRIANGLE_SHAPE_EX_H
#include "BulletCollision/CollisionShapes/btCollisionShape.h"
#include "BulletCollision/CollisionShapes/btTriangleShape.h"
#include "btBoxCollision.h"
#include "btClipPolygon.h"
#include "btGeometryOperations.h"
#define MAX_TRI_CLIPPING 16
//! Structure for collision
struct GIM_TRIANGLE_CONTACT
{
btScalar m_penetration_depth;
int m_point_count;
btVector4 m_separating_normal;
btVector3 m_points[MAX_TRI_CLIPPING];
SIMD_FORCE_INLINE void copy_from(const GIM_TRIANGLE_CONTACT& other)
{
m_penetration_depth = other.m_penetration_depth;
m_separating_normal = other.m_separating_normal;
m_point_count = other.m_point_count;
int i = m_point_count;
while(i--)
{
m_points[i] = other.m_points[i];
}
}
GIM_TRIANGLE_CONTACT()
{
}
GIM_TRIANGLE_CONTACT(const GIM_TRIANGLE_CONTACT& other)
{
copy_from(other);
}
//! classify points that are closer
void merge_points(const btVector4 & plane,
btScalar margin, const btVector3 * points, int point_count);
};
class btPrimitiveTriangle
{
public:
btVector3 m_vertices[3];
btVector4 m_plane;
btScalar m_margin;
btScalar m_dummy;
btPrimitiveTriangle():m_margin(0.01f)
{
}
SIMD_FORCE_INLINE void buildTriPlane()
{
btVector3 normal = (m_vertices[1]-m_vertices[0]).cross(m_vertices[2]-m_vertices[0]);
normal.normalize();
m_plane.setValue(normal[0],normal[1],normal[2],m_vertices[0].dot(normal));
}
//! Test if triangles could collide
bool overlap_test_conservative(const btPrimitiveTriangle& other);
//! Calcs the plane which is paralele to the edge and perpendicular to the triangle plane
/*!
\pre this triangle must have its plane calculated.
*/
SIMD_FORCE_INLINE void get_edge_plane(int edge_index, btVector4 &plane) const
{
const btVector3 & e0 = m_vertices[edge_index];
const btVector3 & e1 = m_vertices[(edge_index+1)%3];
bt_edge_plane(e0,e1,m_plane,plane);
}
void applyTransform(const btTransform& t)
{
m_vertices[0] = t(m_vertices[0]);
m_vertices[1] = t(m_vertices[1]);
m_vertices[2] = t(m_vertices[2]);
}
//! Clips the triangle against this
/*!
\pre clipped_points must have MAX_TRI_CLIPPING size, and this triangle must have its plane calculated.
\return the number of clipped points
*/
int clip_triangle(btPrimitiveTriangle & other, btVector3 * clipped_points );
//! Find collision using the clipping method
/*!
\pre this triangle and other must have their triangles calculated
*/
bool find_triangle_collision_clip_method(btPrimitiveTriangle & other, GIM_TRIANGLE_CONTACT & contacts);
};
//! Helper class for colliding Bullet Triangle Shapes
/*!
This class implements a better getAabb method than the previous btTriangleShape class
*/
class btTriangleShapeEx: public btTriangleShape
{
public:
btTriangleShapeEx():btTriangleShape(btVector3(0,0,0),btVector3(0,0,0),btVector3(0,0,0))
{
}
btTriangleShapeEx(const btVector3& p0,const btVector3& p1,const btVector3& p2): btTriangleShape(p0,p1,p2)
{
}
btTriangleShapeEx(const btTriangleShapeEx & other): btTriangleShape(other.m_vertices1[0],other.m_vertices1[1],other.m_vertices1[2])
{
}
virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax)const
{
btVector3 tv0 = t(m_vertices1[0]);
btVector3 tv1 = t(m_vertices1[1]);
btVector3 tv2 = t(m_vertices1[2]);
btAABB trianglebox(tv0,tv1,tv2,m_collisionMargin);
aabbMin = trianglebox.m_min;
aabbMax = trianglebox.m_max;
}
void applyTransform(const btTransform& t)
{
m_vertices1[0] = t(m_vertices1[0]);
m_vertices1[1] = t(m_vertices1[1]);
m_vertices1[2] = t(m_vertices1[2]);
}
SIMD_FORCE_INLINE void buildTriPlane(btVector4 & plane) const
{
btVector3 normal = (m_vertices1[1]-m_vertices1[0]).cross(m_vertices1[2]-m_vertices1[0]);
normal.normalize();
plane.setValue(normal[0],normal[1],normal[2],m_vertices1[0].dot(normal));
}
bool overlap_test_conservative(const btTriangleShapeEx& other);
};
#endif //GIMPACT_TRIANGLE_MESH_SHAPE_H
| 412 | 0.956799 | 1 | 0.956799 | game-dev | MEDIA | 0.980164 | game-dev | 0.975176 | 1 | 0.975176 |
Aussiemon/Darktide-Source-Code | 3,275 | scripts/extension_systems/behavior/trees/renegade/renegade_gunner_behavior_tree.lua | -- chunkname: @scripts/extension_systems/behavior/trees/renegade/renegade_gunner_behavior_tree.lua
local BreedActions = require("scripts/settings/breed/breed_actions")
local action_data = BreedActions.renegade_gunner
local COVER_COMBAT = {
"BtSequenceNode",
condition_args = {
combat_ranges = {
far = true,
},
},
{
"BtMoveToCoverAction",
name = "move_to_cover",
action_data = action_data.move_to_cover,
},
{
"BtInCoverAction",
name = "in_cover",
action_data = action_data.in_cover,
},
condition = "has_cover",
name = "has_cover",
}
local SUPPRESSED = {
"BtSequenceNode",
{
"BtSuppressedAction",
name = "suppressed",
action_data = action_data.suppressed,
},
{
"BtMoveToCombatVectorAction",
name = "move_to_combat_vector",
action_data = action_data.move_to_combat_vector,
},
condition = "is_suppressed",
name = "suppressed",
}
local COMBAT = {
"BtRandomUtilityNode",
{
"BtMeleeAttackAction",
name = "melee_attack",
action_data = action_data.melee_attack,
},
{
"BtShootAction",
condition = "has_clear_shot",
name = "shoot_spray_n_pray",
action_data = action_data.shoot_spray_n_pray,
},
{
"BtMoveToCombatVectorAction",
name = "move_to_combat_vector",
action_data = action_data.move_to_combat_vector,
},
{
"BtMoveToCombatVectorAction",
name = "escape_to_combat_vector",
action_data = action_data.escape_to_combat_vector,
},
condition = "is_aggroed",
name = "combat",
}
local SPECIAL_ACTION = {
"BtSelectorNode",
{
"BtUseStimAction",
name = "use_stim",
action_data = action_data.use_stim,
},
condition = "minion_can_use_special_action",
name = "use_special_action",
}
local behavior_tree = {
"BtSelectorNode",
{
"BtDieAction",
condition = "is_dead",
name = "death",
action_data = action_data.death,
},
{
"BtDisableAction",
condition = "is_minion_disabled",
name = "disable",
action_data = action_data.disable,
},
{
"BtExitSpawnerAction",
condition = "is_exiting_spawner",
name = "exit_spawner",
action_data = action_data.exit_spawner,
},
{
"BtSelectorNode",
{
"BtTeleportAction",
condition = "at_teleport_smart_object",
name = "teleport",
},
{
"BtClimbAction",
condition = "at_climb_smart_object",
name = "climb",
action_data = action_data.climb,
},
{
"BtJumpAcrossAction",
condition = "at_jump_smart_object",
name = "jump_across",
action_data = action_data.jump_across,
},
{
"BtOpenDoorAction",
condition = "at_door_smart_object",
name = "open_door",
action_data = action_data.open_door,
},
condition = "at_smart_object",
name = "smart_object",
},
SPECIAL_ACTION,
{
"BtStaggerAction",
condition = "is_staggered",
name = "stagger",
action_data = action_data.stagger,
},
{
"BtBlockedAction",
condition = "is_blocked",
name = "blocked",
action_data = action_data.blocked,
},
COVER_COMBAT,
SUPPRESSED,
COMBAT,
{
"BtAlertedAction",
condition = "is_alerted",
name = "alerted",
action_data = action_data.alerted,
},
{
"BtPatrolAction",
condition = "should_patrol",
name = "patrol",
action_data = action_data.patrol,
},
{
"BtIdleAction",
name = "idle",
action_data = action_data.idle,
},
name = "renegade_gunner",
}
return behavior_tree
| 412 | 0.936598 | 1 | 0.936598 | game-dev | MEDIA | 0.988172 | game-dev | 0.969203 | 1 | 0.969203 |
LiveSplit/livesplit-core | 1,902 | capi/src/sum_of_best_component.rs | //! The Sum of Best Segments Component shows the fastest possible time to
//! complete a run of this category, based on information collected from all the
//! previous attempts. This often matches up with the sum of the best segment
//! times of all the segments, but that may not always be the case, as skipped
//! segments may introduce combined segments that may be faster than the actual
//! sum of their best segment times. The name is therefore a bit misleading, but
//! sticks around for historical reasons.
use super::{output_vec, Json};
use crate::component::OwnedComponent;
use crate::key_value_component_state::OwnedKeyValueComponentState;
use livesplit_core::component::sum_of_best::Component as SumOfBestComponent;
use livesplit_core::Timer;
/// type
pub type OwnedSumOfBestComponent = Box<SumOfBestComponent>;
/// Creates a new Sum of Best Segments Component.
#[unsafe(no_mangle)]
pub extern "C" fn SumOfBestComponent_new() -> OwnedSumOfBestComponent {
Box::new(SumOfBestComponent::new())
}
/// drop
#[unsafe(no_mangle)]
pub extern "C" fn SumOfBestComponent_drop(this: OwnedSumOfBestComponent) {
drop(this);
}
/// Converts the component into a generic component suitable for using with a
/// layout.
#[unsafe(no_mangle)]
pub extern "C" fn SumOfBestComponent_into_generic(this: OwnedSumOfBestComponent) -> OwnedComponent {
Box::new((*this).into())
}
/// Encodes the component's state information as JSON.
#[unsafe(no_mangle)]
pub extern "C" fn SumOfBestComponent_state_as_json(
this: &SumOfBestComponent,
timer: &Timer,
) -> Json {
output_vec(|o| {
this.state(timer).write_json(o).unwrap();
})
}
/// Calculates the component's state based on the timer provided.
#[unsafe(no_mangle)]
pub extern "C" fn SumOfBestComponent_state(
this: &SumOfBestComponent,
timer: &Timer,
) -> OwnedKeyValueComponentState {
Box::new(this.state(timer))
}
| 412 | 0.733632 | 1 | 0.733632 | game-dev | MEDIA | 0.712172 | game-dev | 0.953888 | 1 | 0.953888 |
kisence-mian/MyUnityFrameWork | 17,487 | Assets/Script/LuaGenerate/UIManagerWrap.cs | //this source code was auto-generated by tolua#, do not modify it
using System;
using LuaInterface;
public class UIManagerWrap
{
public static void Register(LuaState L)
{
L.BeginClass(typeof(UIManager), typeof(UnityEngine.MonoBehaviour));
L.RegFunction("Init", Init);
L.RegFunction("SetEventSystemEnable", SetEventSystemEnable);
L.RegFunction("GetCameraNames", GetCameraNames);
L.RegFunction("GetCamera", GetCamera);
L.RegFunction("ChangeUICamera", ChangeUICamera);
L.RegFunction("ResetUICamera", ResetUICamera);
L.RegFunction("CreateUIWindow", CreateUIWindow);
L.RegFunction("OpenUIWindow", OpenUIWindow);
L.RegFunction("CloseUIWindow", CloseUIWindow);
L.RegFunction("ShowUI", ShowUI);
L.RegFunction("HideUI", HideUI);
L.RegFunction("HideOtherUI", HideOtherUI);
L.RegFunction("ShowOtherUI", ShowOtherUI);
L.RegFunction("CloseAllUI", CloseAllUI);
L.RegFunction("CloseLastUI", CloseLastUI);
L.RegFunction("OpenUIAsync", OpenUIAsync);
L.RegFunction("DestroyUI", DestroyUI);
L.RegFunction("DestroyAllUI", DestroyAllUI);
L.RegFunction("DestroyAllActiveUI", DestroyAllActiveUI);
L.RegFunction("GetUI", GetUI);
L.RegFunction("GetUIBaseByEventKey", GetUIBaseByEventKey);
L.RegFunction("GetNormalUICount", GetNormalUICount);
L.RegFunction("DestroyAllHideUI", DestroyAllHideUI);
L.RegFunction("GetHideUI", GetHideUI);
L.RegFunction("__eq", op_Equality);
L.RegFunction("__tostring", ToLua.op_ToString);
L.RegVar("s_UIs", get_s_UIs, set_s_UIs);
L.RegVar("s_hideUIs", get_s_hideUIs, set_s_hideUIs);
L.RegVar("UILayerManager", get_UILayerManager, set_UILayerManager);
L.RegVar("UIAnimManager", get_UIAnimManager, set_UIAnimManager);
L.RegVar("UIStackManager", get_UIStackManager, set_UIStackManager);
L.RegVar("EventSystem", get_EventSystem, set_EventSystem);
L.RegVar("UIManagerGo", get_UIManagerGo, set_UIManagerGo);
L.EndClass();
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int Init(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 0);
UIManager.Init();
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int SetEventSystemEnable(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
bool arg0 = LuaDLL.luaL_checkboolean(L, 1);
UIManager.SetEventSystemEnable(arg0);
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetCameraNames(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 0);
string[] o = UIManager.GetCameraNames();
ToLua.Push(L, o);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetCamera(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
string arg0 = ToLua.CheckString(L, 1);
UnityEngine.Camera o = UIManager.GetCamera(arg0);
ToLua.Push(L, o);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int ChangeUICamera(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 2);
UIWindowBase arg0 = (UIWindowBase)ToLua.CheckUnityObject(L, 1, typeof(UIWindowBase));
string arg1 = ToLua.CheckString(L, 2);
UIManager.ChangeUICamera(arg0, arg1);
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int ResetUICamera(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
UIWindowBase arg0 = (UIWindowBase)ToLua.CheckUnityObject(L, 1, typeof(UIWindowBase));
UIManager.ResetUICamera(arg0);
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int CreateUIWindow(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
string arg0 = ToLua.CheckString(L, 1);
UIWindowBase o = UIManager.CreateUIWindow(arg0);
ToLua.Push(L, o);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int OpenUIWindow(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
string arg0 = ToLua.CheckString(L, 1);
UICallBack arg1 = null;
LuaTypes funcType2 = LuaDLL.lua_type(L, 2);
if (funcType2 != LuaTypes.LUA_TFUNCTION)
{
arg1 = (UICallBack)ToLua.CheckObject(L, 2, typeof(UICallBack));
}
else
{
LuaFunction func = ToLua.ToLuaFunction(L, 2);
arg1 = DelegateFactory.CreateDelegate(typeof(UICallBack), func) as UICallBack;
}
object[] arg2 = ToLua.ToParamsObject(L, 3, count - 2);
UIWindowBase o = UIManager.OpenUIWindow(arg0, arg1, arg2);
ToLua.Push(L, o);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int CloseUIWindow(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (TypeChecker.CheckTypes(L, 1, typeof(string), typeof(bool), typeof(UICallBack)) && TypeChecker.CheckParamsType(L, typeof(object), 4, count - 3))
{
string arg0 = ToLua.ToString(L, 1);
bool arg1 = LuaDLL.lua_toboolean(L, 2);
UICallBack arg2 = null;
LuaTypes funcType3 = LuaDLL.lua_type(L, 3);
if (funcType3 != LuaTypes.LUA_TFUNCTION)
{
arg2 = (UICallBack)ToLua.ToObject(L, 3);
}
else
{
LuaFunction func = ToLua.ToLuaFunction(L, 3);
arg2 = DelegateFactory.CreateDelegate(typeof(UICallBack), func) as UICallBack;
}
object[] arg3 = ToLua.ToParamsObject(L, 4, count - 3);
UIManager.CloseUIWindow(arg0, arg1, arg2, arg3);
return 0;
}
else if (TypeChecker.CheckTypes(L, 1, typeof(UIWindowBase), typeof(bool), typeof(UICallBack)) && TypeChecker.CheckParamsType(L, typeof(object), 4, count - 3))
{
UIWindowBase arg0 = (UIWindowBase)ToLua.ToObject(L, 1);
bool arg1 = LuaDLL.lua_toboolean(L, 2);
UICallBack arg2 = null;
LuaTypes funcType3 = LuaDLL.lua_type(L, 3);
if (funcType3 != LuaTypes.LUA_TFUNCTION)
{
arg2 = (UICallBack)ToLua.ToObject(L, 3);
}
else
{
LuaFunction func = ToLua.ToLuaFunction(L, 3);
arg2 = DelegateFactory.CreateDelegate(typeof(UICallBack), func) as UICallBack;
}
object[] arg3 = ToLua.ToParamsObject(L, 4, count - 3);
UIManager.CloseUIWindow(arg0, arg1, arg2, arg3);
return 0;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UIManager.CloseUIWindow");
}
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int ShowUI(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 1 && TypeChecker.CheckTypes(L, 1, typeof(UIWindowBase)))
{
UIWindowBase arg0 = (UIWindowBase)ToLua.ToObject(L, 1);
UIWindowBase o = UIManager.ShowUI(arg0);
ToLua.Push(L, o);
return 1;
}
else if (count == 1 && TypeChecker.CheckTypes(L, 1, typeof(string)))
{
string arg0 = ToLua.ToString(L, 1);
UIWindowBase o = UIManager.ShowUI(arg0);
ToLua.Push(L, o);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UIManager.ShowUI");
}
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int HideUI(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 1 && TypeChecker.CheckTypes(L, 1, typeof(UIWindowBase)))
{
UIWindowBase arg0 = (UIWindowBase)ToLua.ToObject(L, 1);
UIWindowBase o = UIManager.HideUI(arg0);
ToLua.Push(L, o);
return 1;
}
else if (count == 1 && TypeChecker.CheckTypes(L, 1, typeof(string)))
{
string arg0 = ToLua.ToString(L, 1);
UIWindowBase o = UIManager.HideUI(arg0);
ToLua.Push(L, o);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UIManager.HideUI");
}
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int HideOtherUI(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
string arg0 = ToLua.CheckString(L, 1);
UIManager.HideOtherUI(arg0);
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int ShowOtherUI(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
string arg0 = ToLua.CheckString(L, 1);
UIManager.ShowOtherUI(arg0);
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int CloseAllUI(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
bool arg0 = LuaDLL.luaL_checkboolean(L, 1);
UIManager.CloseAllUI(arg0);
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int CloseLastUI(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
UIType arg0 = (UIType)ToLua.CheckObject(L, 1, typeof(UIType));
UIManager.CloseLastUI(arg0);
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int OpenUIAsync(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
string arg0 = ToLua.CheckString(L, 1);
UICallBack arg1 = null;
LuaTypes funcType2 = LuaDLL.lua_type(L, 2);
if (funcType2 != LuaTypes.LUA_TFUNCTION)
{
arg1 = (UICallBack)ToLua.CheckObject(L, 2, typeof(UICallBack));
}
else
{
LuaFunction func = ToLua.ToLuaFunction(L, 2);
arg1 = DelegateFactory.CreateDelegate(typeof(UICallBack), func) as UICallBack;
}
object[] arg2 = ToLua.ToParamsObject(L, 3, count - 2);
UIManager.OpenUIAsync(arg0, arg1, arg2);
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int DestroyUI(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
UIWindowBase arg0 = (UIWindowBase)ToLua.CheckUnityObject(L, 1, typeof(UIWindowBase));
UIManager.DestroyUI(arg0);
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int DestroyAllUI(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 0);
UIManager.DestroyAllUI();
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int DestroyAllActiveUI(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 0);
UIManager.DestroyAllActiveUI();
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetUI(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
string arg0 = ToLua.CheckString(L, 1);
UIWindowBase o = UIManager.GetUI(arg0);
ToLua.Push(L, o);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetUIBaseByEventKey(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
string arg0 = ToLua.CheckString(L, 1);
UIBase o = UIManager.GetUIBaseByEventKey(arg0);
ToLua.Push(L, o);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetNormalUICount(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 0);
int o = UIManager.GetNormalUICount();
LuaDLL.lua_pushinteger(L, o);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int DestroyAllHideUI(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 0);
UIManager.DestroyAllHideUI();
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetHideUI(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
string arg0 = ToLua.CheckString(L, 1);
UIWindowBase o = UIManager.GetHideUI(arg0);
ToLua.Push(L, o);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int op_Equality(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 2);
UnityEngine.Object arg0 = (UnityEngine.Object)ToLua.ToObject(L, 1);
UnityEngine.Object arg1 = (UnityEngine.Object)ToLua.ToObject(L, 2);
bool o = arg0 == arg1;
LuaDLL.lua_pushboolean(L, o);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_s_UIs(IntPtr L)
{
try
{
ToLua.PushObject(L, UIManager.s_UIs);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_s_hideUIs(IntPtr L)
{
try
{
ToLua.PushObject(L, UIManager.s_hideUIs);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_UILayerManager(IntPtr L)
{
try
{
ToLua.Push(L, UIManager.UILayerManager);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_UIAnimManager(IntPtr L)
{
try
{
ToLua.Push(L, UIManager.UIAnimManager);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_UIStackManager(IntPtr L)
{
try
{
ToLua.Push(L, UIManager.UIStackManager);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_EventSystem(IntPtr L)
{
try
{
ToLua.Push(L, UIManager.EventSystem);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_UIManagerGo(IntPtr L)
{
try
{
ToLua.Push(L, UIManager.UIManagerGo);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_s_UIs(IntPtr L)
{
try
{
System.Collections.Generic.Dictionary<string,System.Collections.Generic.List<UIWindowBase>> arg0 = (System.Collections.Generic.Dictionary<string,System.Collections.Generic.List<UIWindowBase>>)ToLua.CheckObject(L, 2, typeof(System.Collections.Generic.Dictionary<string,System.Collections.Generic.List<UIWindowBase>>));
UIManager.s_UIs = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_s_hideUIs(IntPtr L)
{
try
{
System.Collections.Generic.Dictionary<string,System.Collections.Generic.List<UIWindowBase>> arg0 = (System.Collections.Generic.Dictionary<string,System.Collections.Generic.List<UIWindowBase>>)ToLua.CheckObject(L, 2, typeof(System.Collections.Generic.Dictionary<string,System.Collections.Generic.List<UIWindowBase>>));
UIManager.s_hideUIs = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_UILayerManager(IntPtr L)
{
try
{
UILayerManager arg0 = (UILayerManager)ToLua.CheckUnityObject(L, 2, typeof(UILayerManager));
UIManager.UILayerManager = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_UIAnimManager(IntPtr L)
{
try
{
UIAnimManager arg0 = (UIAnimManager)ToLua.CheckUnityObject(L, 2, typeof(UIAnimManager));
UIManager.UIAnimManager = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_UIStackManager(IntPtr L)
{
try
{
UIStackManager arg0 = (UIStackManager)ToLua.CheckUnityObject(L, 2, typeof(UIStackManager));
UIManager.UIStackManager = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_EventSystem(IntPtr L)
{
try
{
UnityEngine.EventSystems.EventSystem arg0 = (UnityEngine.EventSystems.EventSystem)ToLua.CheckUnityObject(L, 2, typeof(UnityEngine.EventSystems.EventSystem));
UIManager.EventSystem = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_UIManagerGo(IntPtr L)
{
try
{
UnityEngine.GameObject arg0 = (UnityEngine.GameObject)ToLua.CheckUnityObject(L, 2, typeof(UnityEngine.GameObject));
UIManager.UIManagerGo = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
}
| 412 | 0.723058 | 1 | 0.723058 | game-dev | MEDIA | 0.835849 | game-dev | 0.867039 | 1 | 0.867039 |
CortexFoundation/CortexTheseus | 13,025 | cmd/cortex/main.go | // Copyright 2018 The go-ethereum Authors
// This file is part of CortexFoundation.
//
// CortexFoundation 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.
//
// CortexFoundation 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 CortexFoundation. If not, see <http://www.gnu.org/licenses/>.
// cortex is the official command-line client for Cortex.
package main
import (
"fmt"
"math/big"
"os"
"sort"
"strconv"
"strings"
"time"
_ "github.com/CortexFoundation/statik"
"github.com/arsham/figurine/figurine"
_ "go.uber.org/automaxprocs"
"gopkg.in/urfave/cli.v1"
"github.com/CortexFoundation/CortexTheseus/accounts"
"github.com/CortexFoundation/CortexTheseus/accounts/keystore"
"github.com/CortexFoundation/CortexTheseus/client"
"github.com/CortexFoundation/CortexTheseus/cmd/utils"
"github.com/CortexFoundation/CortexTheseus/console"
"github.com/CortexFoundation/CortexTheseus/ctxc"
"github.com/CortexFoundation/CortexTheseus/internal/debug"
"github.com/CortexFoundation/CortexTheseus/log"
"github.com/CortexFoundation/CortexTheseus/metrics"
"github.com/CortexFoundation/CortexTheseus/node"
// Automatically set GOMAXPROCS to match Linux container CPU quota.
_ "github.com/CortexFoundation/CortexTheseus/ctxc/tracers/js"
_ "github.com/CortexFoundation/CortexTheseus/ctxc/tracers/native"
// Force-load the tracer engines to trigger registration
)
const (
clientIdentifier = "cortex" // Client identifier to advertise over the network
)
var (
// Git SHA1 commit hash of the release (set via linker flags)
gitCommit = ""
// The app that holds all commands and flags.
app = utils.NewApp(gitCommit, "the cortex golang command line interface")
// flags that configure the node
nodeFlags = []cli.Flag{
utils.IdentityFlag,
utils.UnlockedAccountFlag,
utils.PasswordFileFlag,
utils.BootnodesFlag,
utils.BootnodesV4Flag,
// utils.BootnodesV5Flag,
utils.DataDirFlag,
utils.EraFlag,
utils.DBEngineFlag,
utils.AncientFlag,
utils.MinFreeDiskSpaceFlag,
utils.KeyStoreDirFlag,
utils.ExternalSignerFlag,
// utils.NoUSBFlag,
utils.TxPoolLocalsFlag,
utils.TxPoolNoLocalsFlag,
//utils.TxPoolNoInfersFlag,
utils.TxPoolJournalFlag,
utils.TxPoolRejournalFlag,
utils.TxPoolPriceLimitFlag,
utils.TxPoolPriceBumpFlag,
utils.TxPoolAccountSlotsFlag,
utils.TxPoolGlobalSlotsFlag,
utils.TxPoolAccountQueueFlag,
utils.TxPoolGlobalQueueFlag,
utils.TxPoolLifetimeFlag,
utils.SyncModeFlag,
utils.GCModeFlag,
utils.SnapshotFlag,
utils.TxLookupLimitFlag,
utils.WhitelistFlag,
utils.CacheFlag,
utils.CacheDatabaseFlag,
utils.CacheTrieFlag,
utils.CacheTrieJournalFlag,
utils.CacheTrieRejournalFlag,
utils.CacheGCFlag,
utils.CacheSnapshotFlag,
utils.CacheNoPrefetchFlag,
utils.CachePreimagesFlag,
utils.TrieCacheGenFlag,
utils.FDLimitFlag,
utils.CryptoKZGFlag,
utils.ListenPortFlag,
utils.DiscoveryPortFlag,
utils.MaxPeersFlag,
utils.MaxPendingPeersFlag,
utils.ViperFlag,
utils.MiningEnabledFlag,
utils.MinerThreadsFlag,
//utils.MinerNotifyFlag,
utils.MinerGasTargetFlag,
// utils.MinerLegacyGasTargetFlag,
utils.MinerGasLimitFlag,
utils.MinerGasPriceFlag,
// utils.MinerLegacyGasPriceFlag,
utils.MinerCoinbaseFlag,
utils.MinerLegacyCoinbaseFlag,
utils.MinerExtraDataFlag,
// utils.MinerLegacyExtraDataFlag,
utils.MinerRecommitIntervalFlag,
//utils.MinerNoVerfiyFlag,
utils.MinerCudaFlag,
//utils.MinerOpenCLFlag,
utils.MinerDevicesFlag,
//utils.MinerAlgorithmFlag,
utils.NATFlag,
utils.NoDiscoverFlag,
utils.DiscoveryV4Flag,
utils.DiscoveryV5Flag,
utils.NetrestrictFlag,
utils.NodeKeyFileFlag,
utils.NodeKeyHexFlag,
// utils.DeveloperFlag,
// utils.DeveloperPeriodFlag,
utils.BernardFlag,
utils.DoloresFlag,
// utils.TestnetFlag,
// utils.LazynetFlag,
// utils.VMEnableDebugFlag,
utils.NetworkIdFlag,
utils.RPCCORSDomainFlag,
utils.RPCVirtualHostsFlag,
// utils.CortexStatsURLFlag,
// utils.MetricsEnabledFlag,
// utils.FakePoWFlag,
// utils.NoCompactionFlag,
utils.GpoBlocksFlag,
utils.GpoPercentileFlag,
configFileFlag,
// utils.ModelCallInterfaceFlag,
utils.GpoMaxGasPriceFlag,
}
inferFlags = []cli.Flag{
utils.InferDeviceTypeFlag,
utils.InferDeviceIdFlag,
utils.InferPortFlag,
utils.InferMemoryFlag,
}
storageFlags = []cli.Flag{
utils.StorageDirFlag,
utils.StorageRpcFlag,
utils.StorageEngineFlag,
utils.StoragePortFlag,
//utils.StorageEnabledFlag,
utils.StorageMaxSeedingFlag,
utils.StorageMaxActiveFlag,
//utils.StorageBoostNodesFlag,
utils.StorageTrackerFlag,
utils.StorageDHTFlag,
utils.StorageDisableTCPFlag,
utils.StorageEnableUTPFlag,
utils.StorageEnableWormholeFlag,
utils.StorageModeFlag,
utils.StorageBoostFlag,
}
rpcFlags = []cli.Flag{
utils.RPCEnabledFlag,
utils.RPCListenAddrFlag,
utils.RPCPortFlag,
utils.RPCApiFlag,
utils.WSEnabledFlag,
utils.WSListenAddrFlag,
utils.WSPortFlag,
utils.WSApiFlag,
utils.WSAllowedOriginsFlag,
utils.IPCDisabledFlag,
utils.IPCPathFlag,
utils.InsecureUnlockAllowedFlag,
utils.RPCGlobalGasCapFlag,
utils.RPCGlobalTxFeeCapFlag,
utils.AllowUnprotectedTxs,
}
whisperFlags = []cli.Flag{
utils.WhisperEnabledFlag,
utils.WhisperMaxMessageSizeFlag,
utils.WhisperMinPOWFlag,
}
metricsFlags = []cli.Flag{
utils.MetricsEnabledFlag,
utils.MetricsEnabledExpensiveFlag,
utils.MetricsHTTPFlag,
utils.MetricsPortFlag,
utils.MetricsEnableInfluxDBFlag,
utils.MetricsInfluxDBEndpointFlag,
utils.MetricsInfluxDBDatabaseFlag,
utils.MetricsInfluxDBUsernameFlag,
utils.MetricsInfluxDBPasswordFlag,
utils.MetricsInfluxDBTagsFlag,
}
)
func init() {
// Initialize the CLI app and start Ctxc
app.Action = cortex
app.HideVersion = true // we have a command to print the version
app.Copyright = "Copyright 2018-2025 The cortex Authors"
app.Commands = []cli.Command{
// See chaincmd.go:
initCommand,
// importCommand,
// exportCommand,
// importPreimagesCommand,
// exportPreimagesCommand,
// copydbCommand,
removedbCommand,
// dumpCommand,
dumpGenesisCommand,
inspectCommand,
// See monitorcmd.go:
// monitorCommand,
// See accountcmd.go:
accountCommand,
// walletCommand,
// See consolecmd.go:
consoleCommand,
attachCommand,
// javascriptCommand,
// See misccmd.go:
// makecacheCommand,
// makedagCommand,
versionCommand,
cvmCommand,
// bugCommand,
// licenseCommand,
// See config.go
// dumpConfigCommand,
verkleCommand,
}
sort.Sort(cli.CommandsByName(app.Commands))
app.Flags = append(app.Flags, nodeFlags...)
app.Flags = append(app.Flags, rpcFlags...)
app.Flags = append(app.Flags, consoleFlags...)
app.Flags = append(app.Flags, debug.Flags...)
app.Flags = append(app.Flags, whisperFlags...)
app.Flags = append(app.Flags, metricsFlags...)
app.Flags = append(app.Flags, cvmFlags...)
app.Flags = append(app.Flags, storageFlags...)
app.Flags = append(app.Flags, inferFlags...)
//app.Flags = append(app.Flags, utils.NetworkFlags...)
//app.Flags = append(app.Flags, utils.DatabaseFlags...)
//flags.AutoEnvVars(app.Flags, "CORTEX")
app.Before = func(ctx *cli.Context) error {
return debug.Setup(ctx)
}
app.After = func(ctx *cli.Context) error {
debug.Exit()
console.Stdin.Close() // Resets terminal mode.
return nil
}
}
func main() {
if err := app.Run(os.Args); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
// cortex is the main entry point into the system if no special subcommand is ran.
// It creates a default node based on the command line arguments and runs it in
// blocking mode, waiting for it to be shut down.
func cortex(ctx *cli.Context) error {
if args := ctx.Args(); len(args) > 0 {
return fmt.Errorf("invalid command: %q", args[0])
}
err := figurine.Write(os.Stdout, "CORTEX", "3d.flf")
if err != nil {
log.Error("", "err", err)
}
prepare(ctx)
node := makeFullNode(ctx)
defer node.Close()
startNode(ctx, node)
node.Wait()
return nil
}
// prepare manipulates memory cache allowance and setups metric system.
// This function should be called before launching devp2p stack.
func prepare(ctx *cli.Context) {
// If we're a full node on mainnet without --cache specified, bump default cache allowance
if !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) {
// Make sure we're not on any supported preconfigured testnet either
// Nope, we're really on mainnet. Bump that cache up!
log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096)
ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096))
}
// Start metrics export if enabled
utils.SetupMetrics(ctx)
// Start system runtime metrics collection
go func() {
metrics.CollectProcessMetrics(3 * time.Second)
}()
}
// startNode boots up the system node and all registered protocols, after which
// it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
// miner.
func startNode(ctx *cli.Context, stack *node.Node) {
// Start up the node itself
utils.StartNode(ctx, stack)
var unlocks []string
inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
for _, input := range inputs {
if trimmed := strings.TrimSpace(input); trimmed != "" {
unlocks = append(unlocks, trimmed)
}
}
if len(unlocks) > 0 {
if !stack.Config().InsecureUnlockAllowed {
utils.Fatalf("Account unlock with HTTP access is forbidden! account=%v", len(unlocks))
}
// Unlock any account specifically requested
backends := stack.AccountManager().Backends(keystore.KeyStoreType)
if len(backends) == 0 {
utils.Fatalf("Keystore is not available")
}
ks := backends[0].(*keystore.KeyStore)
passwords := utils.MakePasswordList(ctx)
//unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
for i, account := range unlocks {
if trimmed := strings.TrimSpace(account); trimmed != "" {
unlockAccount(ctx, ks, trimmed, i, passwords)
}
}
}
// Register wallet event handlers to open and auto-derive wallets
events := make(chan accounts.WalletEvent, 16)
stack.AccountManager().Subscribe(events)
go func() {
// Create a chain state reader for self-derivation
rpcClient, err := stack.Attach()
if err != nil {
utils.Fatalf("Failed to attach to self: %v", err)
}
stateReader := ctxcclient.NewClient(rpcClient)
// Open any wallets already attached
for _, wallet := range stack.AccountManager().Wallets() {
if err := wallet.Open(""); err != nil {
log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
}
}
// Listen for wallet event till termination
for event := range events {
switch event.Kind {
case accounts.WalletArrived:
if err := event.Wallet.Open(""); err != nil {
log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
}
case accounts.WalletOpened:
status, _ := event.Wallet.Status()
log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
var derivationPaths []accounts.DerivationPath
if event.Wallet.URL().Scheme == "ledger" {
derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
}
derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
event.Wallet.SelfDerive(derivationPaths, stateReader)
case accounts.WalletDropped:
log.Info("Old wallet dropped", "url", event.Wallet.URL())
event.Wallet.Close()
}
}
}()
// Start auxiliary services if enabled
// if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
// Mining only makes sense if a full Cortex node is running
var cortex *ctxc.Cortex
if err := stack.Service(&cortex); err != nil {
utils.Fatalf("Cortex service not running: %v", err)
}
// Set the gas price to the limits from the CLI and start mining
// gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name)
var gasprice *big.Int = nil
if ctx.IsSet(utils.MinerGasPriceFlag.Name) {
gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
}
if gasprice == nil {
gasprice = big.NewInt(0)
}
cortex.TxPool().SetGasPrice(gasprice)
threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name)
if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) {
threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name)
}
if err := cortex.StartMining(threads); err != nil {
utils.Fatalf("Failed to start mining: %v", err)
}
}
}
| 412 | 0.931444 | 1 | 0.931444 | game-dev | MEDIA | 0.571677 | game-dev | 0.70784 | 1 | 0.70784 |
mijagourlay/VorteGrid | 1,911 | Samples/MjgIntelFluidDemo_Part20/Render/system.h | /** \file system.h
\brief Render system
\author Copyright 2010-2013 MJG; All rights reserved.
*/
#ifndef PEGASYS_RENDER_SYSTEM_H
#define PEGASYS_RENDER_SYSTEM_H
#include "Core/Containers/slist.h"
#include "Render/Device/target.h"
#include "Render/Device/api.h"
// Macros ----------------------------------------------------------------------
// Types -----------------------------------------------------------------------
namespace PeGaSys
{
namespace Render
{
/** Render system.
*/
class System
{
public:
System( ApiBase * renderApi ) ;
~System() ;
/// Return address of Render API object.
ApiBase * GetApi() { return mApi ; }
/** Add a Render Target such as a window or texture.
\param target Render Target
*/
void AddTarget( Target * target )
{
mTargets.PushBack( target ) ;
}
void UpdateTargets( const double & currentVirtualTimeInSeconds ) ;
private:
typedef SLIST< Target * > TargetContainer ;
typedef TargetContainer::Iterator TargetIterator ;
typedef TargetContainer::ConstIterator TargetConstIterator ;
TargetContainer mTargets ; /// Render targets
ApiBase * mApi ; /// Address of low-level render system device, which this object owns.
} ;
// Public variables ------------------------------------------------------------
// Public functions ------------------------------------------------------------
#if defined( _DEBUG ) && ! defined( _XBOX )
extern void System_UnitTest() ;
#endif
} ;
} ;
#endif
| 412 | 0.859399 | 1 | 0.859399 | game-dev | MEDIA | 0.777392 | game-dev | 0.774741 | 1 | 0.774741 |
ataulien/GD3D11 | 15,588 | D3D11Engine/include/OpenMesh/Core/Utils/PropertyManager.hh | /*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2015 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh 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 with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
#ifndef PROPERTYMANAGER_HH_
#define PROPERTYMANAGER_HH_
#include <sstream>
#include <stdexcept>
#include <string>
namespace OpenMesh {
/**
* This class is intended to manage the lifecycle of properties.
* It also defines convenience operators to access the encapsulated
* property's value.
*
* Usage example:
*
* \code
* TriMesh mesh;
* PropertyManager<VPropHandleT<bool>, TriMesh> visited(mesh, "visited.plugin-example.i8.informatik.rwth-aachen.de");
*
* for (TriMesh::VertexIter vh_it = mesh.begin(); ... ; ...) {
* if (!visited[*vh_it]) {
* visitComponent(mesh, *vh_it, visited);
* }
* }
* \endcode
*
*/
template<typename PROPTYPE, typename MeshT>
class PropertyManager {
#if __cplusplus > 199711L or __GXX_EXPERIMENTAL_CXX0X__
public:
PropertyManager(const PropertyManager&) = delete;
PropertyManager& operator=(const PropertyManager&) = delete;
#else
private:
/**
* Noncopyable because there aren't no straightforward copy semantics.
*/
PropertyManager(const PropertyManager&);
/**
* Noncopyable because there aren't no straightforward copy semantics.
*/
PropertyManager& operator=(const PropertyManager&);
#endif
public:
/**
* Constructor.
*
* Throws an \p std::runtime_error if \p existing is true and
* no property named \p propname of the appropriate property type
* exists.
*
* @param mesh The mesh on which to create the property.
* @param propname The name of the property.
* @param existing If false, a new property is created and its lifecycle is managed (i.e.
* the property is deleted upon destruction of the PropertyManager instance). If true,
* the instance merely acts as a convenience wrapper around an existing property with no
* lifecycle management whatsoever.
*/
PropertyManager(MeshT &mesh, const char *propname, bool existing = false) : mesh_(&mesh), retain_(existing), name_(propname) {
if (existing) {
if (!mesh_->get_property_handle(prop_, propname)) {
std::ostringstream oss;
oss << "Requested property handle \"" << propname << "\" does not exist.";
throw std::runtime_error(oss.str());
}
} else {
mesh_->add_property(prop_, propname);
}
}
PropertyManager() : mesh_(0), retain_(false) {
}
~PropertyManager() {
deleteProperty();
}
void swap(PropertyManager &rhs) {
std::swap(mesh_, rhs.mesh_);
std::swap(prop_, rhs.prop_);
std::swap(retain_, rhs.retain_);
std::swap(name_, rhs.name_);
}
static bool propertyExists(MeshT &mesh, const char *propname) {
PROPTYPE dummy;
return mesh.get_property_handle(dummy, propname);
}
bool isValid() const { return mesh_ != 0; }
operator bool() const { return isValid(); }
const PROPTYPE &getRawProperty() const { return prop_; }
const std::string &getName() const { return name_; }
MeshT &getMesh() const { return *mesh_; }
#if __cplusplus > 199711L or __GXX_EXPERIMENTAL_CXX0X__
/**
* Move constructor. Transfers ownership (delete responsibility).
*/
PropertyManager(PropertyManager &&rhs) : mesh_(rhs.mesh_), prop_(rhs.prop_), retain_(rhs.retain_), name_(rhs.name_) {
rhs.retain_ = true;
}
/**
* Move assignment. Transfers ownership (delete responsibility).
*/
PropertyManager &operator=(PropertyManager &&rhs) {
deleteProperty();
mesh_ = rhs.mesh_;
prop_ = rhs.prop_;
retain_ = rhs.retain_;
name_ = rhs.name_;
rhs.retain_ = true;
return *this;
}
/**
* Create a property manager for the supplied property and mesh.
* If the property doesn't exist, it is created. In any case,
* lifecycle management is disabled.
*/
static PropertyManager createIfNotExists(MeshT &mesh, const char *propname) {
PROPTYPE dummy_prop;
PropertyManager pm(mesh, propname, mesh.get_property_handle(dummy_prop, propname));
pm.retain();
return std::move(pm);
}
PropertyManager duplicate(const char *clone_name) {
PropertyManager pm(*mesh_, clone_name, false);
pm.mesh_->property(pm.prop_) = mesh_->property(prop_);
return std::move(pm);
}
/**
* Included for backwards compatibility with non-C++11 version.
*/
PropertyManager move() {
return std::move(*this);
}
#else
class Proxy {
private:
Proxy(MeshT *mesh_, PROPTYPE prop_, bool retain_, const std::string &name_) :
mesh_(mesh_), prop_(prop_), retain_(retain_), name_(name_) {}
MeshT *mesh_;
PROPTYPE prop_;
bool retain_;
std::string name_;
friend class PropertyManager;
};
operator Proxy() {
Proxy p(mesh_, prop_, retain_, name_);
mesh_ = 0;
retain_ = true;
return p;
}
Proxy move() {
return (Proxy)*this;
}
PropertyManager(Proxy p) : mesh_(p.mesh_), prop_(p.prop_), retain_(p.retain_), name_(p.name_) {}
PropertyManager &operator=(Proxy p) {
PropertyManager(p).swap(*this);
return *this;
}
/**
* Create a property manager for the supplied property and mesh.
* If the property doesn't exist, it is created. In any case,
* lifecycle management is disabled.
*/
static Proxy createIfNotExists(MeshT &mesh, const char *propname) {
PROPTYPE dummy_prop;
PropertyManager pm(mesh, propname, mesh.get_property_handle(dummy_prop, propname));
pm.retain();
return (Proxy)pm;
}
Proxy duplicate(const char *clone_name) {
PropertyManager pm(*mesh_, clone_name, false);
pm.mesh_->property(pm.prop_) = mesh_->property(prop_);
return (Proxy)pm;
}
#endif
/**
* \brief Disable lifecycle management for this property.
*
* If this method is called, the encapsulated property will not be deleted
* upon destruction of the PropertyManager instance.
*/
inline void retain(bool doRetain = true) {
retain_ = doRetain;
}
/**
* Access the encapsulated property.
*/
inline PROPTYPE &operator* () {
return prop_;
}
/**
* Access the encapsulated property.
*/
inline const PROPTYPE &operator* () const {
return prop_;
}
/**
* Enables convenient access to the encapsulated property.
*
* For a usage example see this class' documentation.
*
* @param handle A handle of the appropriate handle type. (I.e. \p VertexHandle for \p VPropHandleT, etc.)
*/
template<typename HandleType>
inline typename PROPTYPE::reference operator[] (const HandleType &handle) {
return mesh_->property(prop_, handle);
}
/**
* Enables convenient access to the encapsulated property.
*
* For a usage example see this class' documentation.
*
* @param handle A handle of the appropriate handle type. (I.e. \p VertexHandle for \p VPropHandleT, etc.)
*/
template<typename HandleType>
inline typename PROPTYPE::const_reference operator[] (const HandleType &handle) const {
return mesh_->property(prop_, handle);
}
/**
* Conveniently set the property for an entire range of values.
*
* Examples:
* \code
* MeshT mesh;
* PropertyManager<VPropHandleT<double>, MeshT> distance(
* mesh, "distance.plugin-example.i8.informatik.rwth-aachen.de");
* distance.set_range(
* mesh.vertices_begin(), mesh.vertices_end(),
* std::numeric_limits<double>::infinity());
* \endcode
* or
* \code
* MeshT::VertexHandle vh;
* distance.set_range(
* mesh.vv_begin(vh), mesh.vv_end(vh),
* std::numeric_limits<double>::infinity());
* \endcode
*
* @param begin Start iterator. Needs to dereference to HandleType.
* @param end End iterator. (Exclusive.)
* @param value The value the range will be set to.
*/
template<typename HandleTypeIterator>
void set_range(HandleTypeIterator begin, HandleTypeIterator end,
typename PROPTYPE::const_reference value) {
for (; begin != end; ++begin)
(*this)[*begin] = value;
}
/**
* Conveniently transfer the values managed by one property manager
* onto the values managed by a different property manager.
*
* @param begin Start iterator. Needs to dereference to HandleType. Will
* be used with this property manager.
* @param end End iterator. (Exclusive.) Will be used with this property
* manager.
* @param dst_propmanager The destination property manager.
* @param dst_begin Start iterator. Needs to dereference to the
* HandleType of dst_propmanager. Will be used with dst_propmanager.
* @param dst_end End iterator. (Exclusive.)
* Will be used with dst_propmanager. Used to double check the bounds.
*/
template<typename HandleTypeIterator, typename PROPTYPE_2,
typename MeshT_2, typename HandleTypeIterator_2>
void copy_to(HandleTypeIterator begin, HandleTypeIterator end,
PropertyManager<PROPTYPE_2, MeshT_2> &dst_propmanager,
HandleTypeIterator_2 dst_begin, HandleTypeIterator_2 dst_end) const {
for (; begin != end && dst_begin != dst_end; ++begin, ++dst_begin) {
dst_propmanager[*dst_begin] = (*this)[*begin];
}
}
template<typename RangeType, typename PROPTYPE_2,
typename MeshT_2, typename RangeType_2>
void copy_to(const RangeType &range,
PropertyManager<PROPTYPE_2, MeshT_2> &dst_propmanager,
const RangeType_2 &dst_range) const {
copy_to(range.begin(), range.end(), dst_propmanager,
dst_range.begin(), dst_range.end());
}
/**
* Copy the values of a property from a source range to
* a target range. The source range must not be smaller than the
* target range.
*
* @param prop_name Name of the property to copy. Must exist on the
* source mesh. Will be created on the target mesh if it doesn't exist.
*
* @param src_mesh Source mesh from which to copy.
* @param src_range Source range which to copy. Must not be smaller than
* dst_range.
* @param dst_mesh Destination mesh on which to copy.
* @param dst_range Destination range.
*/
template<typename RangeType, typename MeshT_2, typename RangeType_2>
static void copy(const char *prop_name,
MeshT &src_mesh, const RangeType &src_range,
MeshT_2 &dst_mesh, const RangeType_2 &dst_range) {
typedef OpenMesh::PropertyManager<PROPTYPE, MeshT> DstPM;
DstPM dst(DstPM::createIfNotExists(dst_mesh, prop_name));
typedef OpenMesh::PropertyManager<PROPTYPE, MeshT_2> SrcPM;
SrcPM src(src_mesh, prop_name, true);
src.copy_to(src_range, dst, dst_range);
}
private:
void deleteProperty() {
if (!retain_)
mesh_->remove_property(prop_);
}
private:
MeshT *mesh_;
PROPTYPE prop_;
bool retain_;
std::string name_;
};
} /* namespace OpenMesh */
#endif /* PROPERTYMANAGER_HH_ */
| 412 | 0.988945 | 1 | 0.988945 | game-dev | MEDIA | 0.219721 | game-dev | 0.860378 | 1 | 0.860378 |
bozimmerman/CoffeeMud | 4,307 | com/planet_ink/coffee_mud/Items/Basic/GenFood.java | package com.planet_ink.coffee_mud.Items.Basic;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
/*
Copyright 2001-2025 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class GenFood extends StdFood
{
@Override
public String ID()
{
return "GenFood";
}
protected String readableText="";
public GenFood()
{
super();
setName("a generic blob of food");
basePhyStats.setWeight(2);
setDisplayText("a generic blob of food sits here.");
setDescription("");
baseGoldValue=5;
amountOfNourishment=500;
material=RawMaterial.RESOURCE_MEAT;
recoverPhyStats();
decayTime=0;
}
@Override
public boolean isGeneric()
{
return true;
}
@Override
public String text()
{
return CMLib.coffeeMaker().getEnvironmentalMiscTextXML(this,false);
}
@Override
public String readableText()
{
return readableText;
}
@Override
public void setReadableText(final String text)
{
readableText=text;
}
@Override
public void setMiscText(final String newText)
{
miscText="";
CMLib.coffeeMaker().unpackEnvironmentalMiscTextXML(this,newText,false);
recoverPhyStats();
}
@Override
public void destroy()
{
super.destroy();
}
private final static String[] MYCODES={"NOURISHMENT","BITE"};
@Override
public String getStat(final String code)
{
if(CMLib.coffeeMaker().getGenItemCodeNum(code)>=0)
return CMLib.coffeeMaker().getGenItemStat(this,code);
switch(getInternalCodeNum(code))
{
case 0:
return "" + nourishment();
case 1:
return "" + bite();
default:
return CMProps.getStatCodeExtensionValue(getStatCodes(), xtraValues, code);
}
}
@Override
public void setStat(final String code, final String val)
{
if(CMLib.coffeeMaker().getGenItemCodeNum(code)>=0)
CMLib.coffeeMaker().setGenItemStat(this,code,val);
else
switch(getInternalCodeNum(code))
{
case 0:
setNourishment(CMath.s_parseIntExpression(val));
break;
case 1:
setBite(CMath.s_parseIntExpression(val));
break;
default:
CMProps.setStatCodeExtensionValue(getStatCodes(), xtraValues, code, val);
break;
}
}
private int getInternalCodeNum(final String code)
{
for(int i=0;i<MYCODES.length;i++)
{
if(code.equalsIgnoreCase(MYCODES[i]))
return i;
}
return -1;
}
private static String[] codes=null;
@Override
public String[] getStatCodes()
{
if(codes!=null)
return codes;
final String[] MYCODES=CMProps.getStatCodesList(GenFood.MYCODES,this);
final String[] superCodes=CMParms.toStringArray(GenericBuilder.GenItemCode.values());
codes=new String[superCodes.length+MYCODES.length];
int i=0;
for(;i<superCodes.length;i++)
codes[i]=superCodes[i];
for(int x=0;x<MYCODES.length;i++,x++)
codes[i]=MYCODES[x];
return codes;
}
@Override
public boolean sameAs(final Environmental E)
{
if(!(E instanceof GenFood))
return false;
final String[] codes=getStatCodes();
for(int i=0;i<codes.length;i++)
{
if(!E.getStat(codes[i]).equals(getStat(codes[i])))
return false;
}
return true;
}
}
| 412 | 0.630321 | 1 | 0.630321 | game-dev | MEDIA | 0.960634 | game-dev | 0.567522 | 1 | 0.567522 |
Grokmoo/sulis | 2,399 | data/scripts/abilities/monster/acid_spit.lua | function on_activate(parent, ability)
local targets = parent:targets():hostile():visible()
local targeter = parent:create_targeter(ability)
targeter:add_all_selectable(targets)
targeter:add_all_effectable(targets)
targeter:activate()
end
function on_target_select(parent, ability, targets)
local target = targets:first()
local speed = 30.0
local dist = parent:dist_to_entity(target)
local duration = 0.5 + dist / speed
parent_center_y = parent:center_y() - 1.0
local vx = (target:center_x() - parent:center_x()) / duration
local vy = (target:center_y() - parent_center_y) / duration
local cb = ability:create_callback(parent)
cb:add_target(target)
cb:set_on_anim_update_fn("attack_target")
local gen = parent:create_particle_generator("particles/circle8", duration)
gen:set_position(gen:param(parent:center_x(), vx), gen:param(parent_center_y, vy))
gen:set_gen_rate(gen:param(70.0))
gen:set_initial_gen(35.0)
gen:set_particle_size_dist(gen:fixed_dist(0.5), gen:fixed_dist(0.5))
gen:set_particle_position_dist(gen:dist_param(gen:uniform_dist(-0.2, 0.2), gen:uniform_dist(-vx / 5.0, 0.0)),
gen:dist_param(gen:uniform_dist(-0.2, 0.2), gen:uniform_dist(-vy / 5.0, 0.0)))
gen:set_particle_duration_dist(gen:fixed_dist(0.6))
gen:set_color(gen:param(0.0), gen:param(1.0), gen:param(0.1))
gen:add_callback(cb, duration - 0.1)
gen:activate()
ability:activate(parent)
game:play_sfx("sfx/rustle09")
end
function attack_target(parent, ability, targets)
local target = targets:first()
local hit = parent:special_attack(target, "Reflex", "Ranged", 15, 30, 8, "Acid")
local amount = -8
if hit:is_miss() then
return
elseif hit:is_graze() then
amount = amount / 2
elseif hit:is_hit() then
-- do nothing
elseif hit:is_crit() then
amount = amount * 1.5
end
local effect = target:create_effect(ability:name(), 2)
effect:set_tag("sundered_armor")
effect:add_num_bonus("armor", amount)
local anim = target:create_color_anim()
anim:set_color(anim:param(0.4),
anim:param(1.0),
anim:param(0.4),
anim:param(1.0))
anim:set_color_sec(anim:param(0.0),
anim:param(0.5),
anim:param(0.1),
anim:param(0.0))
effect:add_color_anim(anim)
effect:apply()
game:play_sfx("sfx/water")
end
| 412 | 0.780522 | 1 | 0.780522 | game-dev | MEDIA | 0.984338 | game-dev | 0.946216 | 1 | 0.946216 |
ferus-web/bali | 2,006 | src/bali/runtime/vm/heap/manager.nim | ## ===============
## The Heap Manager
## ===============
##
## This type exists to merge all the (horrible) global-based
## allocator states Bali manages.
##
## Copyright (C) 2025 Trayambak Rai
import std/[logging]
import pkg/bali/runtime/vm/heap/[boehm, bump_allocator]
type
AllocationFailed* = object of Defect
## Raised when the heap manager can no longer safely
## allocate any more memory.
AllocationMetrics* = object
#!fmt: off
allocatedBytesTotal*: uint64 ## Number of bytes allocated overall
allocatedBytesBump*: uint64 ## Number of bytes caught by the bump allocator
allocatedBytesGc*: uint64 ## Number of bytes allocated via the GC after the bump allocator is exhausted
#!fmt: on
HeapManager* = ref object
bump*: BumpAllocator
metrics*: AllocationMetrics
proc release*(manager: HeapManager) =
debug "vm/heap: releasing all* held memory; freeing bump allocator buffer"
manager.bump.release()
debug "vm/heap: performing full GC collection"
GC_fullCollect()
proc allocate*(manager: HeapManager, size: SomeUnsignedInt): pointer =
manager.metrics.allocatedBytesTotal += size
if manager.bump.remaining >= size:
# If the bump allocator has some memory remaining, use it.
manager.metrics.allocatedBytesBump += size
return manager.bump.allocate(size)
# Otherwise, try allocating memory with the garbage collector.
let pntr = boehmAlloc(size)
if pntr == nil:
raise newException(
AllocationFailed,
"Cannot allocate buffer of size `" & $size &
"` (Bump allocator buffer is full and GC returned NULL; is this an OOM?)",
)
manager.metrics.allocatedBytesGc += size
pntr
proc initHeapManager*(): HeapManager =
debug "vm/heap: initializing heap manager"
var manager = HeapManager()
debug "vm/heap: initializing bump allocator"
manager.bump = initBumpAllocator()
debug "vm/heap: initializing garbage collector state"
boehmGCinit()
boehmGC_enable()
ensureMove(manager)
| 412 | 0.94422 | 1 | 0.94422 | game-dev | MEDIA | 0.215422 | game-dev | 0.908485 | 1 | 0.908485 |
Euphillya/Skyllia | 1,170 | plugin/src/main/java/fr/euphyllia/skyllia/utils/PlayerUtils.java | package fr.euphyllia.skyllia.utils;
import fr.euphyllia.skyllia.api.SkylliaAPI;
import fr.euphyllia.skyllia.api.event.players.PlayerTeleportSpawnEvent;
import fr.euphyllia.skyllia.configuration.ConfigLoader;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent;
public class PlayerUtils {
public static void teleportPlayerSpawn(Player player) {
if (!ConfigLoader.general.isSpawnEnabled()) return;
player.getScheduler().execute(SkylliaAPI.getPlugin(), () -> {
Location location = ConfigLoader.general.getSpawnLocation();
if (location == null) location = Bukkit.getWorlds().getFirst().getSpawnLocation();
PlayerTeleportSpawnEvent playerTeleportSpawnEvent = new PlayerTeleportSpawnEvent(player, location);
Bukkit.getPluginManager().callEvent(playerTeleportSpawnEvent);
if (playerTeleportSpawnEvent.isCancelled()) {
return;
}
player.teleportAsync(playerTeleportSpawnEvent.getFinalLocation(), PlayerTeleportEvent.TeleportCause.PLUGIN);
}, null, 1L);
}
}
| 412 | 0.776834 | 1 | 0.776834 | game-dev | MEDIA | 0.696508 | game-dev | 0.852849 | 1 | 0.852849 |
dotnet/apireviews | 3,095 | 2023/04-06-quick-reviews/README.md | # API Review 04/06/2023
## System.CommandLine: Parsing
**Approved** | [#runtime/84177](https://github.com/dotnet/runtime/issues/84177#issuecomment-1499477999) | [Video](https://www.youtube.com/watch?v=vDv6CJ-Oa7Q&t=0h0m0s)
* Why is the SymbolResult recursive?
* What is the primary output? `SymbolResult` or `ParseError`?
* `ParseResult`
- `UnmatchedTokens` should probably be an `IReadOnlyList<string>`
* `Cli` prefix isn't used consistently
- We probably don't want all types to be prefixed, but we should probably ensure that types that are commonly used together appear consistent
* `DefaultValueFactory`
- These are invoked when providing help but the example includes cases where those report errors. Can this "mess up" the help page?
* Virtual/Abstract
- If we consider them plumging, we shouldn't have public/protected virtuals
- If we want to support overriding, we should make them more consistent
* Setters should generally not be modified after the first parse but we don't believe we need to enforce that
- We considered using `init` but we believe this negatively affects source generation and/or usability of newing types up, also doesn't work for .NET Standard 2.0 consumers
* Can we make `CliParser` internal?
* `FindResultFor` should probably be `GetResult`, so that it matches `GetValue`
```C#
namespace System.CommandLine.Parsing;
public enum TokenType
{
Argument,
Command,
Option,
DoubleDash,
Directive
}
public sealed class CliToken : IEquatable<CliToken>
{
public CliToken(string? value, TokenType type, CliSymbol symbol);
public string Value { get; }
public TokenType Type { get; }
}
public sealed class ParseError
{
public string Message { get; }
public SymbolResult? SymbolResult { get; }
}
public abstract class SymbolResult
{
public SymbolResult? Parent { get; }
public IReadOnlyList<CliToken> Tokens { get; }
public virtual void AddError(string errorMessage);
public ArgumentResult? FindResultFor(CliArgument argument);
public CommandResult? FindResultFor(CliCommand command);
public OptionResult? FindResultFor(CliOption option);
public DirectiveResult? FindResultFor(CliDirective directive);
public T? GetValue<T>(CliArgument<T> argument);
public T? GetValue<T>(CliOption<T> option);
}
public sealed class ArgumentResult : SymbolResult
{
public CliArgument Argument { get; }
public T GetValueOrDefault<T>();
public void OnlyTake(int numberOfTokens);
}
public sealed class OptionResult : SymbolResult
{
public CliOption Option { get; }
public bool Implicit { get; }
public CliToken? IdentifierToken { get; }
public T? GetValueOrDefault<T>();
}
public sealed class DirectiveResult : SymbolResult
{
public IReadOnlyList<string> Values { get; }
public CliDirective Directive { get; }
public CliToken IdentifierToken { get; }
}
public sealed class CommandResult : SymbolResult
{
public CliCommand Command { get; }
public CliToken IdentifierToken { get; }
public IEnumerable<SymbolResult> Children { get; }
}
```
| 412 | 0.647087 | 1 | 0.647087 | game-dev | MEDIA | 0.122698 | game-dev | 0.770228 | 1 | 0.770228 |
bozimmerman/CoffeeMud | 3,591 | com/planet_ink/coffee_mud/Abilities/Fighter/Fighter_Headlock.java | package com.planet_ink.coffee_mud.Abilities.Fighter;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2022-2025 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Fighter_Headlock extends FighterGrappleSkill
{
@Override
public String ID()
{
return "Fighter_Headlock";
}
private final static String localizedName = CMLib.lang().L("Headlock");
@Override
public String name()
{
return localizedName;
}
@Override
public String displayText()
{
return "(Headlock)";
}
private static final String[] triggerStrings =I(new String[] {"HEADLOCK"});
@Override
public String[] triggerStrings()
{
return triggerStrings;
}
@Override
public void affectPhyStats(final Physical affected, final PhyStats affectableStats)
{
super.affectPhyStats(affected,affectableStats);
}
@Override
public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(target.charStats().getBodyPart(Race.BODY_HEAD)<=0)
{
mob.tell(L("@x1 has no head!",target.name(mob)));
return false;
}
if(!super.invoke(mob,commands,target,auto,asLevel))
return false;
// now see if it worked
final boolean hit=(auto)
||(super.getGrappleA(target)!=null)
||CMLib.combat().rollToHit(mob,target);
boolean success=proficiencyCheck(mob,0,auto)&&(hit);
if(success)
{
invoker=mob;
final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_JUSTICE|(auto?CMMsg.MASK_ALWAYS:0),
auto?L("<T-NAME> get(s) <T-HIMHERSELF> in a(n) @x1!",name().toLowerCase()):
L("^F^<FIGHT^><S-NAME> put(s) <T-NAME> in a @x1!^</FIGHT^>^?",name().toLowerCase()));
CMLib.color().fixSourceFightColor(msg);
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(msg.value()<=0)
success = finishGrapple(mob,4,target, asLevel);
else
return maliciousFizzle(mob,target,L("<T-NAME> fight(s) off <S-YOUPOSS> headlocking move."));
}
}
else
return maliciousFizzle(mob,target,L("<S-NAME> attempt(s) to put <T-NAME> in a @x1, but fail(s).",name().toLowerCase()));
// return whether it worked
return success;
}
}
| 412 | 0.84108 | 1 | 0.84108 | game-dev | MEDIA | 0.960981 | game-dev | 0.832569 | 1 | 0.832569 |
TauCetiStation/TauCetiClassic | 3,210 | code/game/machinery/computer/prisoner.dm | /obj/machinery/computer/prisoner
name = "Implant Management"
icon = 'icons/obj/computer.dmi'
icon_state = "explosive"
state_broken_preset = "securityb"
state_nopower_preset = "security0"
light_color = "#a91515"
req_access = list(access_armory)
circuit = /obj/item/weapon/circuitboard/prisoner
var/id = 0.0
var/temp = null
var/status = 0
var/timeleft = 60
var/stop = 0.0
var/screen = 0 // 0 - No Access Denied, 1 - Access allowed
required_skills = list(/datum/skill/police = SKILL_LEVEL_PRO)
/obj/machinery/computer/prisoner/ui_interact(mob/user)
var/dat = ""
if(screen == 0)
dat += "<HR><A href='byond://?src=\ref[src];lock=1'>Unlock Console</A>"
else if(screen == 1)
dat += "<HR>Chemical Implants<BR>"
var/turf/Tr = null
for(var/obj/item/weapon/implant/chem/C in global.implant_list)
if(!C.implanted_mob)
continue
Tr = get_turf(C)
if(!Tr || Tr.z != src.z) // Out of range
continue
dat += "[C.implanted_mob.name] | Remaining Units: [C.reagents.total_volume] | Inject: "
dat += "<A class='red' href='byond://?src=\ref[src];inject=\ref[C];amount=1'>1</A>"
dat += "<A class='red' href='byond://?src=\ref[src];inject=\ref[C];amount=5'>5</A>"
dat += "<A class='red' href='byond://?src=\ref[src];inject=\ref[C];amount=10'>10</A><BR>"
dat += "********************************<BR>"
dat += "<HR>Tracking Implants<BR>"
for(var/obj/item/weapon/implant/tracking/T in global.implant_list)
if(!T.implanted_mob)
continue
Tr = get_turf(T)
if(!Tr || Tr.z != src.z) // Out of range
continue
var/loc_display = "Unknown"
var/turf/mob_loc = get_turf_loc(T.implanted_mob)
if(!isenvironmentturf(mob_loc))
loc_display = mob_loc.loc
if(T.malfunction)
loc_display = pick(teleportlocs)
dat += "ID: [T.id] | Location: [loc_display]<BR>"
dat += "<A class='red' href='byond://?src=\ref[src];warn=\ref[T]'><i>Message Holder</i></A> |<BR>"
dat += "********************************<BR>"
dat += "<HR><A href='byond://?src=\ref[src];lock=1'>Lock Console</A>"
var/datum/browser/popup = new(user, "computer", "Prisoner Implant Manager System", 400, 500)
popup.set_content(dat)
popup.open()
/obj/machinery/computer/prisoner/process()
if(!..())
updateDialog()
return
/obj/machinery/computer/prisoner/Topic(href, href_list)
. = ..()
if(!.)
return
if(href_list["inject"])
var/obj/item/weapon/implant/chem/I = locate(href_list["inject"])
if(!istype(I) || !I.implanted_mob)
return
var/turf/T = get_turf(I.implanted_mob)
if(!T || T.z != src.z)
return
var/amount = clamp(text2num(href_list["amount"]), 1, 10)
I.use_implant(amount)
else if(href_list["warn"])
var/warning = sanitize(input(usr,"Message:","Enter your message here!",""))
if(!warning)
return
var/obj/item/weapon/implant/tracking/I = locate(href_list["warn"])
if(!istype(I) || !I.implanted_mob)
return
var/turf/T = get_turf(I.implanted_mob)
if(!T || T.z != src.z)
return
to_chat(I.implanted_mob, "<span class='notice'>You hear a voice in your head saying: '[warning]'</span>")
else if(href_list["lock"])
if(allowed(usr))
screen = !screen
else
to_chat(usr, "Unauthorized Access.")
updateUsrDialog()
| 412 | 0.988123 | 1 | 0.988123 | game-dev | MEDIA | 0.970986 | game-dev | 0.926358 | 1 | 0.926358 |
marc2k3/foo_spider_monkey_panel | 12,926 | foobar2000-sdk/libPPUI/TreeMultiSel.h | #pragma once
// ================================================================================
// CTreeMultiSel
// Implementation of multi-selection in a tree view ctrl
// Instantiate with dialog ID of your treeview,
// plug into your dialog's message map.
// Doesn't work correctly with explorer-themed tree controls (glitches happen).
// ================================================================================
#include <set>
#include <vector>
class CTreeMultiSel : public CMessageMap {
public:
typedef std::set<HTREEITEM> selection_t;
typedef std::vector<HTREEITEM> selectionOrdered_t;
CTreeMultiSel(unsigned ID) : m_ID(ID) {}
BEGIN_MSG_MAP_EX(CTreeMultiSel)
NOTIFY_HANDLER_EX(m_ID, TVN_ITEMEXPANDED, OnItemExpanded)
NOTIFY_HANDLER_EX(m_ID, NM_CLICK, OnClick)
NOTIFY_HANDLER_EX(m_ID, TVN_DELETEITEM, OnItemDeleted)
NOTIFY_HANDLER_EX(m_ID, TVN_SELCHANGING, OnSelChanging)
NOTIFY_HANDLER_EX(m_ID, TVN_SELCHANGED, OnSelChangedFilter)
NOTIFY_HANDLER_EX(m_ID, NM_SETFOCUS, OnFocus)
NOTIFY_HANDLER_EX(m_ID, NM_KILLFOCUS, OnFocus)
NOTIFY_HANDLER_EX(m_ID, NM_CUSTOMDRAW, OnCustomDraw)
END_MSG_MAP()
const unsigned m_ID;
// Retrieves selected items - on order of appearance in the view
selectionOrdered_t GetSelectionOrdered(CTreeViewCtrl tree) const {
HTREEITEM first = tree.GetRootItem();
selectionOrdered_t ret; ret.reserve( m_selection.size() );
for(HTREEITEM walk = first; walk != NULL; walk = tree.GetNextVisibleItem(walk)) {
if (m_selection.count(walk) > 0) ret.push_back( walk );
}
return ret;
}
//! Undefined order! Use only when order of selected items is not relevant.
selection_t GetSelection() const { return m_selection; }
selection_t const & GetSelectionRef() const { return m_selection; }
bool IsItemSelected(HTREEITEM item) const {return m_selection.count(item) > 0;}
size_t GetSelCount() const {return m_selection.size();}
//! Retrieves a single-selection item. Null if nothing or more than one item is selected.
HTREEITEM GetSingleSel() const {
if (m_selection.size() != 1) return NULL;
return *m_selection.begin();
}
void OnContextMenu_FixSelection(CTreeViewCtrl tree, CPoint pt) {
if (pt != CPoint(-1, -1)) {
WIN32_OP_D(tree.ScreenToClient(&pt));
UINT flags = 0;
const HTREEITEM item = tree.HitTest(pt, &flags);
if (item != NULL && (flags & TVHT_ONITEM) != 0) {
if (!IsItemSelected(item)) {
SelectSingleItem(tree, item);
}
CallSelectItem(tree, item);
}
}
}
void OnLButtonDown(CTreeViewCtrl tree, WPARAM wp, LPARAM lp) {
if (!IsKeyPressed(VK_CONTROL)) {
UINT flags = 0;
HTREEITEM item = tree.HitTest(CPoint(lp), &flags);
if (item != NULL && (flags & TVHT_ONITEM) != 0) {
if (!IsItemSelected(item)) tree.SelectItem(item);
}
}
}
static bool IsNavKey(UINT vk) {
switch(vk) {
case VK_UP:
case VK_DOWN:
case VK_RIGHT:
case VK_LEFT:
case VK_PRIOR:
case VK_NEXT:
case VK_HOME:
case VK_END:
return true;
default:
return false;
}
}
BOOL OnChar(CTreeViewCtrl tree, WPARAM code) {
switch(code) {
case ' ':
if (IsKeyPressed(VK_CONTROL) || !IsTypingInProgress()) {
HTREEITEM item = tree.GetSelectedItem();
if (item != NULL) SelectToggleItem(tree, item);
return TRUE;
}
break;
}
m_lastTypingTime = GetTickCount(); m_lastTypingTimeValid = true;
return FALSE;
}
BOOL OnKeyDown(CTreeViewCtrl tree, UINT vKey) {
if (IsNavKey(vKey)) m_lastTypingTimeValid = false;
switch(vKey) {
case VK_UP:
if (IsKeyPressed(VK_CONTROL)) {
HTREEITEM item = tree.GetSelectedItem();
if (item != NULL) {
HTREEITEM prev = tree.GetPrevVisibleItem(item);
if (prev != NULL) {
CallSelectItem(tree, prev);
if (IsKeyPressed(VK_SHIFT)) {
if (m_selStart == NULL) m_selStart = item;
SelectItemRange(tree, prev);
}
}
}
return TRUE;
}
break;
case VK_DOWN:
if (IsKeyPressed(VK_CONTROL)) {
HTREEITEM item = tree.GetSelectedItem();
if (item != NULL) {
HTREEITEM next = tree.GetNextVisibleItem(item);
if (next != NULL) {
CallSelectItem(tree, next);
if (IsKeyPressed(VK_SHIFT)) {
if (m_selStart == NULL) m_selStart = item;
SelectItemRange(tree, next);
}
}
}
return TRUE;
}
break;
/*case VK_LEFT:
if (IsKeyPressed(VK_CONTROL)) {
tree.SendMessage(WM_HSCROLL, SB_LINEUP, 0);
}
break;
case VK_RIGHT:
if (IsKeyPressed(VK_CONTROL)) {
tree.SendMessage(WM_HSCROLL, SB_LINEDOWN, 0);
}
break;*/
}
return FALSE;
}
private:
LRESULT OnFocus(LPNMHDR hdr) {
if ( m_selection.size() > 100 ) {
CTreeViewCtrl tree(hdr->hwndFrom);
tree.RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_ERASE);
} else if (m_selection.size() > 0) {
CTreeViewCtrl tree(hdr->hwndFrom);
CRgn rgn; rgn.CreateRectRgn(0,0,0,0);
for(auto walk : m_selection) {
CRect rc;
if (tree.GetItemRect(walk, rc, TRUE)) {
CRgn temp; temp.CreateRectRgnIndirect(rc);
rgn.CombineRgn(temp, RGN_OR);
}
}
tree.RedrawWindow(NULL, rgn, RDW_INVALIDATE | RDW_ERASE);
}
SetMsgHandled(FALSE);
return 0;
}
void CallSelectItem(CTreeViewCtrl tree, HTREEITEM item) {
const bool was = m_ownSelChange; m_ownSelChange = true;
tree.SelectItem(item);
m_ownSelChange = was;
}
LRESULT OnSelChangedFilter(LPNMHDR) {
if (m_ownSelChangeNotify) SetMsgHandled(FALSE);
return 0;
}
LRESULT OnItemDeleted(LPNMHDR pnmh) {
const HTREEITEM item = reinterpret_cast<NMTREEVIEW*>(pnmh)->itemOld.hItem;
m_selection.erase( item );
if (m_selStart == item) m_selStart = NULL;
SetMsgHandled(FALSE);
return 0;
}
LRESULT OnItemExpanded(LPNMHDR pnmh) {
NMTREEVIEW * info = reinterpret_cast<NMTREEVIEW *>(pnmh);
CTreeViewCtrl tree ( pnmh->hwndFrom );
if ((info->itemNew.state & TVIS_EXPANDED) == 0) {
if (DeselectChildren( tree, info->itemNew.hItem )) {
SendOnSelChanged(tree);
}
}
SetMsgHandled(FALSE);
return 0;
}
void FixFocusItem(CTreeViewCtrl tree, HTREEITEM item) {
if (this->IsItemSelected(item) || tree.GetSelectedItem() != item) return;
auto scope = pfc::autoToggle(m_ownSelChange, true);
for(;;) {
if (item == TVI_ROOT || item == NULL || this->IsItemSelected(item)) {
tree.SelectItem(item); return;
}
for (auto walk = tree.GetPrevSiblingItem(item); walk != NULL; walk = tree.GetPrevSiblingItem(walk)) {
if (this->IsItemSelected(walk)) {
tree.SelectItem(walk); return;
}
}
for (auto walk = tree.GetNextSiblingItem(item); walk != NULL; walk = tree.GetNextSiblingItem(walk)) {
if (this->IsItemSelected(walk)) {
tree.SelectItem(walk); return;
}
}
item = tree.GetParentItem(item);
}
}
BOOL HandleClick(CTreeViewCtrl tree, CPoint pt) {
UINT htFlags = 0;
HTREEITEM item = tree.HitTest(pt, &htFlags);
if (item != NULL && (htFlags & TVHT_ONITEM) != 0) {
if (IsKeyPressed(VK_CONTROL)) {
SelectToggleItem(tree, item);
FixFocusItem(tree, item);
return TRUE;
} else if (item == tree.GetSelectedItem() && !IsItemSelected(item)) {
SelectToggleItem(tree, item);
return TRUE;
} else {
//tree.SelectItem(item);
return FALSE;
}
} else {
return FALSE;
}
}
LRESULT OnClick(LPNMHDR pnmh) {
CPoint pt(GetMessagePos());
CTreeViewCtrl tree ( pnmh->hwndFrom );
WIN32_OP_D ( tree.ScreenToClient( &pt ) );
return HandleClick(tree, pt) ? 1 : 0;
}
LRESULT OnSelChanging(LPNMHDR pnmh) {
if (!m_ownSelChange) {
//console::formatter() << "OnSelChanging";
NMTREEVIEW * info = reinterpret_cast<NMTREEVIEW *>(pnmh);
CTreeViewCtrl tree ( pnmh->hwndFrom );
const HTREEITEM item = info->itemNew.hItem;
if (IsTypingInProgress()) {
SelectSingleItem(tree, item);
} else if (IsKeyPressed(VK_SHIFT)) {
SelectItemRange(tree, item);
} else if (IsKeyPressed(VK_CONTROL)) {
SelectToggleItem(tree, item);
} else {
SelectSingleItem(tree, item);
}
}
return 0;
}
void SelectItemRange(CTreeViewCtrl tree, HTREEITEM item) {
if (m_selStart == NULL || m_selStart == item) {
SelectSingleItem(tree, item);
return;
}
selection_t newSel = GrabRange(tree, m_selStart, item );
ApplySelection(tree, std::move(newSel));
}
static selection_t GrabRange(CTreeViewCtrl tree, HTREEITEM item1, HTREEITEM item2) {
selection_t range1, range2;
HTREEITEM walk1 = item1, walk2 = item2;
for(;;) {
if (walk1 != NULL) {
range1.insert( walk1 );
if (walk1 == item2) {
return range1;
}
walk1 = tree.GetNextVisibleItem(walk1);
}
if (walk2 != NULL) {
range2.insert( walk2 );
if (walk2 == item1) {
return range2;
}
walk2 = tree.GetNextVisibleItem(walk2);
}
if (walk1 == NULL && walk2 == NULL) {
// should not get here
return selection_t();
}
}
}
void SelectToggleItem(CTreeViewCtrl tree, HTREEITEM item) {
m_selStart = item;
if ( IsItemSelected( item ) ) {
m_selection.erase( item );
} else {
m_selection.insert( item );
}
UpdateItem(tree, item);
}
LRESULT OnCustomDraw(LPNMHDR hdr) {
NMTVCUSTOMDRAW* info = (NMTVCUSTOMDRAW*)hdr;
switch (info->nmcd.dwDrawStage) {
case CDDS_ITEMPREPAINT:
// NOTE: This doesn't work all the way. Unflagging CDIS_FOCUS isn't respected, causing weird behaviors when using ctrl+cursors or unselecting items.
if (this->IsItemSelected((HTREEITEM)info->nmcd.dwItemSpec)) {
info->nmcd.uItemState |= CDIS_SELECTED;
} else {
info->nmcd.uItemState &= ~(CDIS_FOCUS | CDIS_SELECTED);
}
return CDRF_DODEFAULT;
case CDDS_PREPAINT:
return CDRF_NOTIFYITEMDRAW;
default:
return CDRF_DODEFAULT;
}
}
public:
void SelectSingleItem(CTreeViewCtrl tree, HTREEITEM item) {
m_selStart = item;
if (m_selection.size() == 1 && *m_selection.begin() == item) return;
DeselectAll(tree); SelectItem(tree, item);
}
void ApplySelection(CTreeViewCtrl tree, selection_t && newSel) {
CRgn updateRgn;
bool changed = false;
if (newSel.size() != m_selection.size() && newSel.size() + m_selection.size() > 100) {
// don't bother with regions
changed = true;
} else {
WIN32_OP_D(updateRgn.CreateRectRgn(0, 0, 0, 0) != NULL);
for (auto walk : m_selection) {
if (newSel.count(walk) == 0) {
changed = true;
CRect rc;
if (tree.GetItemRect(walk, rc, TRUE)) {
CRgn temp; WIN32_OP_D(temp.CreateRectRgnIndirect(rc));
WIN32_OP_D(updateRgn.CombineRgn(temp, RGN_OR) != ERROR);
}
}
}
for (auto walk : newSel) {
if (m_selection.count(walk) == 0) {
changed = true;
CRect rc;
if (tree.GetItemRect(walk, rc, TRUE)) {
CRgn temp; WIN32_OP_D(temp.CreateRectRgnIndirect(rc));
WIN32_OP_D(updateRgn.CombineRgn(temp, RGN_OR) != ERROR);
}
}
}
}
if (changed) {
m_selection = std::move(newSel);
tree.RedrawWindow(NULL, updateRgn);
SendOnSelChanged(tree);
}
}
void DeselectItem(CTreeViewCtrl tree, HTREEITEM item) {
if (IsItemSelected(item)) {
m_selection.erase(item); UpdateItem(tree, item);
}
}
void SelectItem(CTreeViewCtrl tree, HTREEITEM item) {
if (!IsItemSelected(item)) {
m_selection.insert(item); UpdateItem(tree, item);
}
}
void DeselectAll(CTreeViewCtrl tree) {
if (m_selection.size() == 0) return;
CRgn updateRgn;
if (m_selection.size() <= 100) {
WIN32_OP_D(updateRgn.CreateRectRgn(0, 0, 0, 0) != NULL);
for (auto walk : m_selection) {
CRect rc;
if (tree.GetItemRect(walk, rc, TRUE)) {
CRgn temp; WIN32_OP_D(temp.CreateRectRgnIndirect(rc));
WIN32_OP_D(updateRgn.CombineRgn(temp, RGN_OR) != ERROR);
}
}
}
m_selection.clear();
tree.RedrawWindow(NULL, updateRgn);
}
private:
void UpdateItem(CTreeViewCtrl tree, HTREEITEM item) {
CRect rc;
if (tree.GetItemRect(item, rc, TRUE) ) {
tree.RedrawWindow(rc);
}
SendOnSelChanged(tree);
}
void SendOnSelChanged(CTreeViewCtrl tree) {
NMHDR hdr = {};
hdr.code = TVN_SELCHANGED;
hdr.hwndFrom = tree;
hdr.idFrom = m_ID;
const bool was = m_ownSelChangeNotify; m_ownSelChangeNotify = true;
tree.GetParent().SendMessage(WM_NOTIFY, m_ID, (LPARAM) &hdr );
m_ownSelChangeNotify = was;
}
bool DeselectChildren( CTreeViewCtrl tree, HTREEITEM item ) {
bool state = false;
for(HTREEITEM walk = tree.GetChildItem( item ); walk != NULL; walk = tree.GetNextSiblingItem( walk ) ) {
if (m_selection.erase(walk) > 0) state = true;
if (m_selStart == walk) m_selStart = NULL;
if (tree.GetItemState( walk, TVIS_EXPANDED ) ) {
if (DeselectChildren( tree, walk )) state = true;
}
}
return state;
}
bool IsTypingInProgress() const {
return m_lastTypingTimeValid && (GetTickCount() - m_lastTypingTime < 500);
}
selection_t m_selection;
HTREEITEM m_selStart = NULL;
bool m_ownSelChangeNotify = false, m_ownSelChange = false;
DWORD m_lastTypingTime = 0; bool m_lastTypingTimeValid = false;
};
| 412 | 0.989886 | 1 | 0.989886 | game-dev | MEDIA | 0.526749 | game-dev,desktop-app | 0.999344 | 1 | 0.999344 |
Unity-Technologies/SharedSpheres | 3,322 | Assets/UnityARKitPlugin/Examples/ARKit2.0/UnityObjectScanner/ObjectScanManager.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.iOS;
using System;
using UnityEngine.UI;
using System.IO;
public class ObjectScanManager : MonoBehaviour {
[SerializeField]
ObjectScanSessionManager m_ARSessionManager;
[SerializeField]
Text listOfObjects;
int objIndex = 0;
List<ARReferenceObject> scannedObjects;
bool detectionMode = false;
private PickBoundingBox pickBoundingBox;
void Start()
{
scannedObjects = new List<ARReferenceObject> ();
pickBoundingBox = GetComponent<PickBoundingBox> ();
}
void OnDestroy()
{
ClearScannedObjects ();
}
static UnityARSessionNativeInterface session
{
get { return UnityARSessionNativeInterface.GetARSessionNativeInterface(); }
}
public void CreateReferenceObject()
{
//this script should be placed on the bounding volume GameObject
CreateReferenceObject (pickBoundingBox.transform, pickBoundingBox.bounds.center-pickBoundingBox.transform.position, pickBoundingBox.bounds.size);
}
public void CreateReferenceObject(Transform objectTransform, Vector3 center, Vector3 extent)
{
session.ExtractReferenceObjectAsync (objectTransform, center, extent, (ARReferenceObject referenceObject) => {
if (referenceObject != null) {
Debug.LogFormat ("ARReferenceObject created: center {0} extent {1}", referenceObject.center, referenceObject.extent);
referenceObject.name = "objScan_" + objIndex++;
Debug.LogFormat ("ARReferenceObject has name {0}", referenceObject.name);
scannedObjects.Add(referenceObject);
UpdateList();
} else {
Debug.Log ("Failed to create ARReferenceObject.");
}
});
}
void UpdateList()
{
string members = "";
foreach (ARReferenceObject arro in scannedObjects) {
members += arro.name + ",";
}
listOfObjects.text = members;
}
public void DetectScannedObjects(Text toChange)
{
detectionMode = !detectionMode;
if (detectionMode) {
StartDetecting ();
toChange.text = "Stop Detecting";
} else {
m_ARSessionManager.StartObjectScanningSession ();
toChange.text = "Detect Objects";
}
}
private void StartDetecting()
{
//create a set out of the scanned objects
IntPtr ptrReferenceObjectsSet = session.CreateNativeReferenceObjectsSet(scannedObjects);
//restart session without resetting tracking
var config = m_ARSessionManager.sessionConfiguration;
//use object set from above to detect objects
config.dynamicReferenceObjectsPtr = ptrReferenceObjectsSet;
//Debug.Log("Restarting session without resetting tracking");
session.RunWithConfigAndOptions(config, UnityARSessionRunOption.ARSessionRunOptionRemoveExistingAnchors | UnityARSessionRunOption.ARSessionRunOptionResetTracking);
}
public void ClearScannedObjects()
{
detectionMode = false;
scannedObjects.Clear ();
UpdateList ();
m_ARSessionManager.StartObjectScanningSession ();
}
public void SaveScannedObjects()
{
if (scannedObjects.Count == 0)
return;
string pathToSaveTo = Path.Combine(Application.persistentDataPath, "ARReferenceObjects");
if (!Directory.Exists (pathToSaveTo))
{
Directory.CreateDirectory (pathToSaveTo);
}
foreach (ARReferenceObject arro in scannedObjects)
{
string fullPath = Path.Combine (pathToSaveTo, arro.name + ".arobject");
arro.Save (fullPath);
}
}
}
| 412 | 0.913112 | 1 | 0.913112 | game-dev | MEDIA | 0.642727 | game-dev | 0.96349 | 1 | 0.96349 |
gdm85/wolfengo | 17,149 | src/level.go | /*
WolfenGo - https://github.com/gdm85/wolfengo
Copyright (C) 2016~2019 gdm85
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.
*/
package main
import (
"fmt"
"math"
"github.com/gdm85/wolfengo/src/gl"
)
const (
spotWidth = 1.0
spotLength = 1.0
spotHeight = 1.0
numTexExp = 4
openDistance = 1.0
doorOpenMovementAmount = 0.9
)
var numTextures = uint32(math.Pow(2, numTexExp))
type Level struct {
mesh Mesh
level *Map
shader *Shader
material *Material
transform *Transform
player *Player
doors []*Door
monsters []*Monster
medkits []*Medkit
medkitsToRemove []*Medkit
exitPoints []*Vector3f
collisionPosStart, collisionPosEnd []*Vector2f
game *Game // parent game
}
var (
_basicShader *Shader
collectionTexture *Texture
)
func getBasicShader() (*Shader, error) {
if _basicShader == nil {
var err error
collectionTexture, err = NewTexture("WolfCollection.png")
if err != nil {
return nil, err
}
_basicShader, err = NewShader(true)
if err != nil {
return nil, err
}
err = _basicShader.addProgramFromFile("basicVertex"+shaderVersion+".vs", gl.VERTEX_SHADER)
if err != nil {
return nil, err
}
err = _basicShader.addProgramFromFile("basicFragment"+shaderVersion+".fs", gl.FRAGMENT_SHADER)
if err != nil {
return nil, err
}
err = _basicShader.compile()
if err != nil {
return nil, err
}
err = _basicShader.addUniform("transform")
if err != nil {
return nil, err
}
err = _basicShader.addUniform("color")
if err != nil {
return nil, err
}
}
return _basicShader, nil
}
func (g *Game) NewLevel(levelNum uint) (*Level, error) {
l := &Level{game: g}
l.transform = l.game.NewTransform()
var fileName string
if debugLevelTest {
fileName = "levelTest.map"
} else {
fileName = fmt.Sprintf("level%d.map", levelNum)
}
var err error
l.level, err = NewMap(fileName)
if err != nil {
return nil, err
}
l.material = NewMaterial(collectionTexture)
l.shader, err = getBasicShader()
if err != nil {
return nil, err
}
err = l.generate()
if err != nil {
return nil, err
}
// some validation
if l.player == nil {
return nil, fmt.Errorf("invalid generated level: no player set")
}
return l, nil
}
func (l *Level) openDoors(position Vector3f, tryExitLevel bool) error {
for _, door := range l.doors {
if door.transform.translation.sub(position).length() < openDistance {
door.open()
}
}
if tryExitLevel {
for _, exitPoint := range l.exitPoints {
if exitPoint.sub(position).length() < openDistance {
err := l.game.loadNextLevel()
if err != nil {
return err
}
}
}
}
return nil
}
func (l *Level) damagePlayer(amt int) {
l.player.damage(amt)
}
func (l *Level) input() error {
return l.player.input()
}
func (l *Level) update() error {
for _, door := range l.doors {
door.update()
}
l.player.update()
for _, medkit := range l.medkits {
medkit.update()
}
for _, monster := range l.monsters {
err := monster.update()
if err != nil {
return err
}
}
if len(l.medkitsToRemove) > 0 {
newMedkits := make([]*Medkit, 0, len(l.medkits)-len(l.medkitsToRemove))
for _, m := range l.medkits {
removed := false
for _, r := range l.medkitsToRemove {
if m == r {
removed = true
break
}
}
if !removed {
newMedkits = append(newMedkits, m)
}
}
l.medkits = newMedkits
}
return nil
}
func (l *Level) removeMedkit(m *Medkit) {
l.medkitsToRemove = append(l.medkitsToRemove, m)
}
func (l *Level) render() {
l.shader.bind()
l.shader.updateUniforms(l.transform.getProjectedTransformation(l.player.camera), l.material)
l.mesh.draw()
for _, door := range l.doors {
door.render()
}
for _, monster := range l.monsters {
monster.render()
}
for _, medkit := range l.medkits {
medkit.render()
}
l.player.render()
}
func rectCollide(oldPos, newPos, size1, pos2, size2 Vector2f) (result Vector2f) {
if newPos.X+size1.X < pos2.X ||
newPos.X-size1.X > pos2.X+size2.X*size2.X ||
oldPos.Y+size1.Y < pos2.Y ||
oldPos.Y-size1.Y > pos2.Y+size2.Y*size2.Y {
result.X = 1
}
if oldPos.X+size1.X < pos2.X ||
oldPos.X-size1.X > pos2.X+size2.X*size2.X ||
newPos.Y+size1.Y < pos2.Y ||
newPos.Y-size1.Y > pos2.Y+size2.Y*size2.Y {
result.Y = 1
}
return
}
func (l *Level) checkCollision(oldPos, newPos Vector3f, objectWidth, objectLength float32) Vector3f {
collisionVector := Vector2f{1, 1}
movementVector := newPos.sub(oldPos)
if movementVector.length() > 0 {
blockSize := Vector2f{spotWidth, spotLength}
objectSize := Vector2f{objectWidth, objectLength}
oldPos2 := Vector2f{oldPos.X, oldPos.Z}
newPos2 := Vector2f{newPos.X, newPos.Z}
for i := 0; i < l.level.width; i++ {
for j := 0; j < l.level.height; j++ {
if l.level.IsEmpty(i, j) {
collisionVector = collisionVector.mul(rectCollide(oldPos2, newPos2, objectSize, blockSize.mul(Vector2f{float32(i), float32(j)}), blockSize))
}
}
}
for _, door := range l.doors {
doorSize := door.getSize()
doorPos3f := &door.transform.translation
doorPos2f := Vector2f{doorPos3f.X, doorPos3f.Z}
collisionVector = collisionVector.mul(rectCollide(oldPos2, newPos2, objectSize, doorPos2f, doorSize))
}
}
return Vector3f{collisionVector.X, 0, collisionVector.Y}
}
func (l *Level) checkIntersections(lineStart, lineEnd Vector2f, hurtMonsters bool) *Vector2f {
var nearestIntersection *Vector2f
for i := 0; i < len(l.collisionPosStart); i++ {
collisionVector := lineIntersect(lineStart, lineEnd, *l.collisionPosStart[i], *l.collisionPosEnd[i])
nearestIntersection = findNearestVector2f(nearestIntersection, collisionVector, lineStart)
}
// doors stop bullets
for _, door := range l.doors {
doorPos3f := door.transform.translation
doorPos2f := Vector2f{doorPos3f.X, doorPos3f.Z}
collisionVector := lineIntersectRect(lineStart, lineEnd, doorPos2f, door.getSize())
nearestIntersection = findNearestVector2f(nearestIntersection, collisionVector, lineStart)
}
if hurtMonsters {
var nearestMonsterIntersect *Vector2f
var nearestMonster *Monster
for _, monster := range l.monsters {
monsterPos3f := monster.transform.translation
monsterPos2f := Vector2f{monsterPos3f.X, monsterPos3f.Z}
collisionVector := lineIntersectRect(lineStart, lineEnd, monsterPos2f, defaultMonsterSize)
nearestMonsterIntersect = findNearestVector2f(nearestMonsterIntersect, collisionVector, lineStart)
if nearestMonsterIntersect == collisionVector {
nearestMonster = monster
}
}
if nearestMonsterIntersect != nil && (nearestIntersection == nil ||
nearestMonsterIntersect.sub(lineStart).length() < nearestIntersection.sub(lineStart).length()) {
if nearestMonster != nil {
nearestMonster.damage(getPlayerDamage())
}
}
}
return nearestIntersection
}
func findNearestVector2f(a, b *Vector2f, positionRelativeTo Vector2f) *Vector2f {
if b != nil && (a == nil ||
a.sub(positionRelativeTo).length() > b.sub(positionRelativeTo).length()) {
return b
}
return a
}
func lineIntersectRect(lineStart, lineEnd, rectPos, rectSize Vector2f) (result *Vector2f) {
collisionVector := lineIntersect(lineStart, lineEnd, rectPos, Vector2f{rectPos.X + rectSize.X, rectPos.Y})
result = findNearestVector2f(result, collisionVector, lineStart)
collisionVector = lineIntersect(lineStart, lineEnd, rectPos, Vector2f{rectPos.X, rectPos.Y + rectSize.Y})
result = findNearestVector2f(result, collisionVector, lineStart)
collisionVector = lineIntersect(lineStart, lineEnd, Vector2f{rectPos.X, rectPos.Y + rectSize.Y}, rectPos.add(rectSize))
result = findNearestVector2f(result, collisionVector, lineStart)
collisionVector = lineIntersect(lineStart, lineEnd, Vector2f{rectPos.X + rectSize.X, rectPos.Y}, rectPos.add(rectSize))
result = findNearestVector2f(result, collisionVector, lineStart)
return
}
func vector2fCross(a, b Vector2f) float32 {
return a.X*b.Y - a.Y*b.X
}
//http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
func lineIntersect(lineStart1, lineEnd1, lineStart2, lineEnd2 Vector2f) *Vector2f {
line1 := lineEnd1.sub(lineStart1)
line2 := lineEnd2.sub(lineStart2)
cross := vector2fCross(line1, line2)
if cross == 0 {
return nil
}
distanceBetweenLineStarts := lineStart2.sub(lineStart1)
a := vector2fCross(distanceBetweenLineStarts, line2) / cross
b := vector2fCross(distanceBetweenLineStarts, line1) / cross
if 0.0 < a && a < 1.0 && 0.0 < b && b < 1.0 {
result := lineStart1.add(line1.mulf(a))
return &result
}
return nil
}
func (l *Level) generate() error {
var vertices []*Vertex
var indices []int32
for i := 0; i < l.level.width; i++ {
for j := 0; j < l.level.height; j++ {
if l.level.IsEmpty(i, j) {
continue
}
err := l.addSpecial(Special(l.level.specials[i][j]), i, j)
if err != nil {
return err
}
//Generate Floor
texCoords := l.level.PlaneTexCoords(i, j)
addFace(&indices, len(vertices), true)
v, err := addVertices(i, j, 0, true, false, true, texCoords[:])
if err != nil {
return err
}
vertices = append(vertices, v...)
//Generate Ceiling
addFace(&indices, len(vertices), false)
v, err = addVertices(i, j, 1, true, false, true, texCoords[:])
if err != nil {
return err
}
vertices = append(vertices, v...)
//Generate Walls
texCoords = l.level.WallTexCoords(i, j)
if l.level.IsEmpty(i, j-1) {
l.collisionPosStart = append(l.collisionPosStart, &Vector2f{float32(i * spotWidth), float32(j * spotLength)})
l.collisionPosEnd = append(l.collisionPosEnd, &Vector2f{float32((i + 1) * spotWidth), float32(j * spotLength)})
addFace(&indices, len(vertices), false)
v, err := addVertices(i, 0, j, true, true, false, texCoords[:])
if err != nil {
return err
}
vertices = append(vertices, v...)
}
if l.level.IsEmpty(i, j+1) {
l.collisionPosStart = append(l.collisionPosStart, &Vector2f{float32(i * spotWidth), float32((j + 1) * spotLength)})
l.collisionPosEnd = append(l.collisionPosEnd, &Vector2f{float32((i + 1) * spotWidth), float32((j + 1) * spotLength)})
addFace(&indices, len(vertices), true)
v, err := addVertices(i, 0, j+1, true, true, false, texCoords[:])
if err != nil {
return err
}
vertices = append(vertices, v...)
}
if l.level.IsEmpty(i-1, j) {
l.collisionPosStart = append(l.collisionPosStart, &Vector2f{float32(i * spotWidth), float32(j * spotLength)})
l.collisionPosEnd = append(l.collisionPosEnd, &Vector2f{float32(i * spotWidth), float32((j + 1) * spotLength)})
addFace(&indices, len(vertices), true)
v, err := addVertices(0, j, i, false, true, true, texCoords[:])
if err != nil {
return err
}
vertices = append(vertices, v...)
}
if l.level.IsEmpty(i+1, j) {
l.collisionPosStart = append(l.collisionPosStart, &Vector2f{float32((i + 1) * spotWidth), float32(j * spotLength)})
l.collisionPosEnd = append(l.collisionPosEnd, &Vector2f{float32((i + 1) * spotWidth), float32((j + 1) * spotLength)})
addFace(&indices, len(vertices), false)
v, err := addVertices(0, j, i+1, false, true, true, texCoords[:])
if err != nil {
return err
}
vertices = append(vertices, v...)
}
}
}
l.mesh = NewMesh(vertices, indices, false)
return nil
}
func calcTexCoords(value uint8) []float32 {
texX := uint32(value) / numTextures
texY := texX % numTexExp
texX /= numTexExp
result := make([]float32, 4)
result[0] = 1.0 - float32(texX)/float32(numTexExp)
result[1] = result[0] - 1.0/float32(numTexExp)
result[3] = 1.0 - float32(texY)/float32(numTexExp)
result[2] = result[3] - 1.0/float32(numTexExp)
return result
}
func (l *Level) addSpecial(special Special, x, y int) error {
switch special {
case Empty:
return nil
case DoorSpecial:
err := l.addDoor(x, y)
if err != nil {
return err
}
case PlayerA:
l.player = l.game.NewPlayer(Vector3f{(float32(x) + 0.5) * spotWidth, 0.4375, (float32(y) + 0.5) * spotLength}, defaultPlayer.mesh, defaultGunMaterial)
case MonsterSpecial:
monsterTransform := l.game.NewTransform()
monsterTransform.translation = Vector3f{(float32(x) + 0.5) * spotWidth, 0, (float32(y) + 0.5) * spotLength}
l.monsters = append(l.monsters, l.game.NewMonster(monsterTransform, _defaultMonster.animations))
case SmallMedkit:
l.medkits = append(l.medkits, l.game.NewMedkit(Vector3f{(float32(x) + 0.5) * spotWidth, 0, (float32(y) + 0.5) * spotLength}))
case ExitSpecial:
l.exitPoints = append(l.exitPoints, &Vector3f{(float32(x) + 0.5) * spotWidth, 0, (float32(y) + 0.5) * spotLength})
default:
panic(fmt.Sprintf("unrecognized blue value: %d", special))
}
return nil
}
func addFace(indices *[]int32, _startLocation int, direction bool) {
startLocation := int32(_startLocation)
var add []int32
if direction {
add = []int32{
startLocation + 2,
startLocation + 1,
startLocation + 0,
startLocation + 3,
startLocation + 2,
startLocation + 0,
}
} else {
add = []int32{
startLocation + 0,
startLocation + 1,
startLocation + 2,
startLocation + 0,
startLocation + 2,
startLocation + 3,
}
}
*indices = append(*indices, add...)
}
func addVertices(_i, _j, _offset int, x, y, z bool, texCoords []float32) (result []*Vertex, err error) {
i, j, offset := float32(_i), float32(_j), float32(_offset)
result = make([]*Vertex, 4)
if x && z {
result[0] = &Vertex{Vector3f{(i * spotWidth), (offset) * spotHeight, j * spotLength}, Vector2f{texCoords[1], texCoords[3]}, Vector3f{}}
result[1] = &Vertex{Vector3f{((i + 1) * spotWidth), (offset) * spotHeight, j * spotLength}, Vector2f{texCoords[0], texCoords[3]}, Vector3f{}}
result[2] = &Vertex{Vector3f{((i + 1) * spotWidth), (offset) * spotHeight, (j + 1) * spotLength}, Vector2f{texCoords[0], texCoords[2]}, Vector3f{}}
result[3] = &Vertex{Vector3f{(i * spotWidth), (offset) * spotHeight, (j + 1) * spotLength}, Vector2f{texCoords[1], texCoords[2]}, Vector3f{}}
} else if x && y {
result[0] = &Vertex{Vector3f{(i * spotWidth), j * spotHeight, offset * spotLength}, Vector2f{texCoords[1], texCoords[3]}, Vector3f{}}
result[1] = &Vertex{Vector3f{((i + 1) * spotWidth), j * spotHeight, offset * spotLength}, Vector2f{texCoords[0], texCoords[3]}, Vector3f{}}
result[2] = &Vertex{Vector3f{((i + 1) * spotWidth), (j + 1) * spotHeight, offset * spotLength}, Vector2f{texCoords[0], texCoords[2]}, Vector3f{}}
result[3] = &Vertex{Vector3f{(i * spotWidth), (j + 1) * spotHeight, offset * spotLength}, Vector2f{texCoords[1], texCoords[2]}, Vector3f{}}
} else if y && z {
result[0] = &Vertex{Vector3f{(offset * spotWidth), i * spotHeight, j * spotLength}, Vector2f{texCoords[1], texCoords[3]}, Vector3f{}}
result[1] = &Vertex{Vector3f{(offset * spotWidth), i * spotHeight, (j + 1) * spotLength}, Vector2f{texCoords[0], texCoords[3]}, Vector3f{}}
result[2] = &Vertex{Vector3f{(offset * spotWidth), (i + 1) * spotHeight, (j + 1) * spotLength}, Vector2f{texCoords[0], texCoords[2]}, Vector3f{}}
result[3] = &Vertex{Vector3f{(offset * spotWidth), (i + 1) * spotHeight, j * spotLength}, Vector2f{texCoords[1], texCoords[2]}, Vector3f{}}
} else {
err = fmt.Errorf("Invalid plane used in level generator")
return
}
return
}
func (l *Level) addDoor(x, y int) error {
doorTransform := l.game.NewTransform()
xDoor := l.level.IsEmpty(x, y-1) && l.level.IsEmpty(x, y+1)
yDoor := l.level.IsEmpty(x-1, y) && l.level.IsEmpty(x+1, y)
if xDoor == yDoor {
return fmt.Errorf("Level Generation has failed! :( You placed a door in an invalid location at %d,%d", x, y)
}
var openPosition *Vector3f
if yDoor {
doorTransform.translation = Vector3f{float32(x), 0, float32(y) + spotLength/2}
t := doorTransform.translation.sub(Vector3f{doorOpenMovementAmount, 0.0, 0.0})
openPosition = &t
}
if xDoor {
doorTransform.translation = Vector3f{float32(x) + spotWidth/2, 0, float32(y)}
doorTransform.rotation = Vector3f{0, 90, 0}
t := doorTransform.translation.sub(Vector3f{0.0, 0.0, doorOpenMovementAmount})
openPosition = &t
}
l.doors = append(l.doors, l.game.NewDoor(doorTransform, l.material, *openPosition))
return nil
}
| 412 | 0.905446 | 1 | 0.905446 | game-dev | MEDIA | 0.910745 | game-dev | 0.906861 | 1 | 0.906861 |
ElunaLuaEngine/ElunaTrinityWotlk | 70,613 | src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp | /*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "BattlegroundAV.h"
#include "BattlegroundPackets.h"
#include "Creature.h"
#include "CreatureAI.h"
#include "DBCStores.h"
#include "GameObject.h"
#include "Log.h"
#include "MotionMaster.h"
#include "ObjectMgr.h"
#include "Player.h"
#include "WorldSession.h"
#include "WorldStatePackets.h"
void BattlegroundAVScore::BuildObjectivesBlock(WorldPackets::Battleground::PVPLogData_Player& playerData)
{
playerData.Stats = { GraveyardsAssaulted, GraveyardsDefended, TowersAssaulted, TowersDefended, MinesCaptured };
}
BattlegroundAV::BattlegroundAV()
{
BgObjects.resize(BG_AV_OBJECT_MAX);
BgCreatures.resize(AV_CPLACE_MAX + AsUnderlyingType(AV_STATICCPLACE_MAX));
for (uint8 i = 0; i < 2; i++)
{
for (uint8 j = 0; j < 9; j++)
m_Team_QuestStatus[i][j] = 0;
m_Team_Scores[i] = 0;
m_IsInformedNearVictory[i] = false;
m_CaptainAlive[i] = true;
m_CaptainBuffTimer[i] = 0;
m_Mine_Owner[i] = 0;
m_Mine_PrevOwner[i] = 0;
m_Mine_Reclaim_Timer[i] = 0;
}
m_Mine_Timer = 0;
for (BG_AV_Nodes i = BG_AV_NODES_FIRSTAID_STATION; i < BG_AV_NODES_MAX; ++i)
InitNode(i, 0, false);
StartMessageIds[BG_STARTING_EVENT_SECOND] = BG_AV_TEXT_START_ONE_MINUTE;
StartMessageIds[BG_STARTING_EVENT_THIRD] = BG_AV_TEXT_START_HALF_MINUTE;
StartMessageIds[BG_STARTING_EVENT_FOURTH] = BG_AV_TEXT_BATTLE_HAS_BEGUN;
}
BattlegroundAV::~BattlegroundAV() { }
void BattlegroundAV::HandleKillPlayer(Player* player, Player* killer)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
Battleground::HandleKillPlayer(player, killer);
UpdateScore(player->GetTeam(), -1);
}
void BattlegroundAV::HandleKillUnit(Creature* unit, Player* killer)
{
TC_LOG_DEBUG("bg.battleground", "bg_av HandleKillUnit {}", unit->GetEntry());
if (GetStatus() != STATUS_IN_PROGRESS)
return;
uint32 entry = unit->GetEntry();
/*
uint32 triggerSpawnID = 0;
if (creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_A_CAPTAIN][0])
triggerSpawnID = AV_CPLACE_TRIGGER16;
else if (creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_A_BOSS][0])
triggerSpawnID = AV_CPLACE_TRIGGER17;
else if (creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_H_CAPTAIN][0])
triggerSpawnID = AV_CPLACE_TRIGGER18;
else if (creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_H_BOSS][0])
triggerSpawnID = AV_CPLACE_TRIGGER19;
*/
if (entry == BG_AV_CreatureInfo[AV_NPC_A_BOSS])
{
CastSpellOnTeam(23658, HORDE); //this is a spell which finishes a quest where a player has to kill the boss
RewardReputationToTeam(729, BG_AV_REP_BOSS, HORDE);
RewardHonorToTeam(GetBonusHonorFromKill(BG_AV_KILL_BOSS), HORDE);
EndBattleground(HORDE);
DelCreature(AV_CPLACE_TRIGGER17);
}
else if (entry == BG_AV_CreatureInfo[AV_NPC_H_BOSS])
{
CastSpellOnTeam(23658, ALLIANCE); //this is a spell which finishes a quest where a player has to kill the boss
RewardReputationToTeam(730, BG_AV_REP_BOSS, ALLIANCE);
RewardHonorToTeam(GetBonusHonorFromKill(BG_AV_KILL_BOSS), ALLIANCE);
EndBattleground(ALLIANCE);
DelCreature(AV_CPLACE_TRIGGER19);
}
else if (entry == BG_AV_CreatureInfo[AV_NPC_A_CAPTAIN])
{
if (!m_CaptainAlive[0])
{
TC_LOG_ERROR("bg.battleground", "Killed a Captain twice, please report this bug, if you haven't done \".respawn\"");
return;
}
m_CaptainAlive[0]=false;
RewardReputationToTeam(729, BG_AV_REP_CAPTAIN, HORDE);
RewardHonorToTeam(GetBonusHonorFromKill(BG_AV_KILL_CAPTAIN), HORDE);
UpdateScore(ALLIANCE, (-1)*BG_AV_RES_CAPTAIN);
//spawn destroyed aura
for (uint8 i=0; i <= 9; i++)
SpawnBGObject(BG_AV_OBJECT_BURN_BUILDING_ALLIANCE+i, RESPAWN_IMMEDIATELY);
DelCreature(AV_CPLACE_TRIGGER16);
if (Creature* herold = GetBGCreature(AV_CPLACE_HERALD))
herold->AI()->Talk(TEXT_STORMPIKE_GENERAL_DEAD);
}
else if (entry == BG_AV_CreatureInfo[AV_NPC_H_CAPTAIN])
{
if (!m_CaptainAlive[1])
{
TC_LOG_ERROR("bg.battleground", "Killed a Captain twice, please report this bug, if you haven't done \".respawn\"");
return;
}
m_CaptainAlive[1]=false;
RewardReputationToTeam(730, BG_AV_REP_CAPTAIN, ALLIANCE);
RewardHonorToTeam(GetBonusHonorFromKill(BG_AV_KILL_CAPTAIN), ALLIANCE);
UpdateScore(HORDE, (-1)*BG_AV_RES_CAPTAIN);
//spawn destroyed aura
for (uint8 i=0; i <= 9; i++)
SpawnBGObject(BG_AV_OBJECT_BURN_BUILDING_HORDE+i, RESPAWN_IMMEDIATELY);
DelCreature(AV_CPLACE_TRIGGER18);
if (Creature* herold = GetBGCreature(AV_CPLACE_HERALD))
herold->AI()->Talk(TEXT_FROSTWOLF_GENERAL_DEAD);
}
else if (entry == BG_AV_CreatureInfo[AV_NPC_N_MINE_N_4] || entry == BG_AV_CreatureInfo[AV_NPC_N_MINE_A_4] || entry == BG_AV_CreatureInfo[AV_NPC_N_MINE_H_4])
ChangeMineOwner(AV_NORTH_MINE, killer->GetTeam());
else if (entry == BG_AV_CreatureInfo[AV_NPC_S_MINE_N_4] || entry == BG_AV_CreatureInfo[AV_NPC_S_MINE_A_4] || entry == BG_AV_CreatureInfo[AV_NPC_S_MINE_H_4])
ChangeMineOwner(AV_SOUTH_MINE, killer->GetTeam());
}
void BattlegroundAV::HandleQuestComplete(uint32 questid, Player* player)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;//maybe we should log this, cause this must be a cheater or a big bug
uint8 team = GetTeamIndexByTeamId(player->GetTeam());
/// @todo add reputation, events (including quest not available anymore, next quest available, go/npc de/spawning)and maybe honor
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed", questid);
switch (questid)
{
case AV_QUEST_A_SCRAPS1:
case AV_QUEST_A_SCRAPS2:
case AV_QUEST_H_SCRAPS1:
case AV_QUEST_H_SCRAPS2:
m_Team_QuestStatus[team][0]+=20;
if (m_Team_QuestStatus[team][0] == 500 || m_Team_QuestStatus[team][0] == 1000 || m_Team_QuestStatus[team][0] == 1500) //25, 50, 75 turn ins
{
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed starting with unit upgrading..", questid);
for (BG_AV_Nodes i = BG_AV_NODES_FIRSTAID_STATION; i <= BG_AV_NODES_FROSTWOLF_HUT; ++i)
if (m_Nodes[i].Owner == player->GetTeam() && m_Nodes[i].State == POINT_CONTROLED)
{
DePopulateNode(i);
PopulateNode(i);
//maybe this is bad, because it will instantly respawn all creatures on every grave..
}
}
break;
case AV_QUEST_A_COMMANDER1:
case AV_QUEST_H_COMMANDER1:
m_Team_QuestStatus[team][1]++;
RewardReputationToTeam(team, 1, player->GetTeam());
if (m_Team_QuestStatus[team][1] == 30)
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed (need to implement some events here", questid);
break;
case AV_QUEST_A_COMMANDER2:
case AV_QUEST_H_COMMANDER2:
m_Team_QuestStatus[team][2]++;
RewardReputationToTeam(team, 1, player->GetTeam());
if (m_Team_QuestStatus[team][2] == 60)
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed (need to implement some events here", questid);
break;
case AV_QUEST_A_COMMANDER3:
case AV_QUEST_H_COMMANDER3:
m_Team_QuestStatus[team][3]++;
RewardReputationToTeam(team, 1, player->GetTeam());
if (m_Team_QuestStatus[team][3] == 120)
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed (need to implement some events here", questid);
break;
case AV_QUEST_A_BOSS1:
case AV_QUEST_H_BOSS1:
m_Team_QuestStatus[team][4] += 9; //you can turn in 10 or 1 item..
[[fallthrough]];
case AV_QUEST_A_BOSS2:
case AV_QUEST_H_BOSS2:
m_Team_QuestStatus[team][4]++;
if (m_Team_QuestStatus[team][4] >= 200)
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed (need to implement some events here", questid);
break;
case AV_QUEST_A_NEAR_MINE:
case AV_QUEST_H_NEAR_MINE:
m_Team_QuestStatus[team][5]++;
if (m_Team_QuestStatus[team][5] == 28)
{
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed (need to implement some events here", questid);
if (m_Team_QuestStatus[team][6] == 7)
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed (need to implement some events here - ground assault ready", questid);
}
break;
case AV_QUEST_A_OTHER_MINE:
case AV_QUEST_H_OTHER_MINE:
m_Team_QuestStatus[team][6]++;
if (m_Team_QuestStatus[team][6] == 7)
{
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed (need to implement some events here", questid);
if (m_Team_QuestStatus[team][5] == 20)
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed (need to implement some events here - ground assault ready", questid);
}
break;
case AV_QUEST_A_RIDER_HIDE:
case AV_QUEST_H_RIDER_HIDE:
m_Team_QuestStatus[team][7]++;
if (m_Team_QuestStatus[team][7] == 25)
{
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed (need to implement some events here", questid);
if (m_Team_QuestStatus[team][8] == 25)
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed (need to implement some events here - rider assault ready", questid);
}
break;
case AV_QUEST_A_RIDER_TAME:
case AV_QUEST_H_RIDER_TAME:
m_Team_QuestStatus[team][8]++;
if (m_Team_QuestStatus[team][8] == 25)
{
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed (need to implement some events here", questid);
if (m_Team_QuestStatus[team][7] == 25)
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed (need to implement some events here - rider assault ready", questid);
}
break;
default:
TC_LOG_DEBUG("bg.battleground", "BG_AV Quest {} completed but is not interesting at all", questid);
return; //was no interesting quest at all
break;
}
}
void BattlegroundAV::UpdateScore(uint16 team, int16 points)
{ //note: to remove reinforcementpoints points must be negative, for adding reinforcements points must be positive
ASSERT(team == ALLIANCE || team == HORDE);
uint8 teamindex = GetTeamIndexByTeamId(team); //0=ally 1=horde
m_Team_Scores[teamindex] += points;
UpdateWorldState(((teamindex == TEAM_HORDE)?AV_Horde_Score:AV_Alliance_Score), m_Team_Scores[teamindex]);
if (points < 0)
{
if (m_Team_Scores[teamindex] < 1)
{
m_Team_Scores[teamindex]=0;
EndBattleground(((teamindex == TEAM_HORDE)?ALLIANCE:HORDE));
}
else if (!m_IsInformedNearVictory[teamindex] && m_Team_Scores[teamindex] < SEND_MSG_NEAR_LOSE)
{
if (teamindex == TEAM_ALLIANCE)
SendBroadcastText(BG_AV_TEXT_ALLIANCE_NEAR_LOSE, CHAT_MSG_BG_SYSTEM_ALLIANCE);
else
SendBroadcastText(BG_AV_TEXT_HORDE_NEAR_LOSE, CHAT_MSG_BG_SYSTEM_HORDE);
PlaySoundToAll(AV_SOUND_NEAR_VICTORY);
m_IsInformedNearVictory[teamindex] = true;
}
}
}
Creature* BattlegroundAV::AddAVCreature(uint16 cinfoid, uint16 type)
{
bool isStatic = false;
Creature* creature = nullptr;
ASSERT(type < AV_CPLACE_MAX + AsUnderlyingType(AV_STATICCPLACE_MAX));
if (type >= AV_CPLACE_MAX) //static
{
type -= AV_CPLACE_MAX;
cinfoid = uint16(BG_AV_StaticCreaturePos[type][4]);
creature = AddCreature(BG_AV_StaticCreatureInfo[cinfoid],
type + AV_CPLACE_MAX,
BG_AV_StaticCreaturePos[type][0],
BG_AV_StaticCreaturePos[type][1],
BG_AV_StaticCreaturePos[type][2],
BG_AV_StaticCreaturePos[type][3]);
isStatic = true;
}
else
{
creature = AddCreature(BG_AV_CreatureInfo[cinfoid], type, BG_AV_CreaturePos[type]);
}
if (!creature)
return nullptr;
if (creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_A_CAPTAIN] || creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_H_CAPTAIN])
creature->SetRespawnDelay(RESPAWN_ONE_DAY); /// @todo look if this can be done by database + also add this for the wingcommanders
if ((isStatic && cinfoid >= 10 && cinfoid <= 14) || (!isStatic && (cinfoid <= AV_NPC_A_GRAVEDEFENSE3 || (cinfoid >= AV_NPC_H_GRAVEDEFENSE0 && cinfoid <= AV_NPC_H_GRAVEDEFENSE3))))
{
if (!isStatic && (cinfoid <= AV_NPC_A_GRAVEDEFENSE3 || (cinfoid >= AV_NPC_H_GRAVEDEFENSE0 && cinfoid <= AV_NPC_H_GRAVEDEFENSE3)))
{
CreatureData &data = sObjectMgr->NewOrExistCreatureData(creature->GetSpawnId());
data.spawnGroupData = sObjectMgr->GetDefaultSpawnGroup();
data.wander_distance = 5;
}
//else wander_distance will be 15, so creatures move maximum=10
//creature->SetDefaultMovementType(RANDOM_MOTION_TYPE);
creature->GetMotionMaster()->Initialize();
creature->setDeathState(JUST_DIED);
creature->Respawn();
/// @todo find a way to add a motionmaster without killing the creature (i
//just copied this code from a gm-command
}
uint32 triggerSpawnID = 0;
uint32 newFaction = 0;
if (creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_A_CAPTAIN])
{
triggerSpawnID = AV_CPLACE_TRIGGER16;
newFaction = 84;
}
else if (creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_A_BOSS])
{
triggerSpawnID = AV_CPLACE_TRIGGER17;
newFaction = 84;
}
else if (creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_H_CAPTAIN])
{
triggerSpawnID = AV_CPLACE_TRIGGER18;
newFaction = 83;
}
else if (creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_H_BOSS])
{
triggerSpawnID = AV_CPLACE_TRIGGER19;
newFaction = 83;
}
if (triggerSpawnID && newFaction)
{
if (Creature* trigger = AddCreature(WORLD_TRIGGER, triggerSpawnID, BG_AV_CreaturePos[triggerSpawnID]))
{
trigger->SetFaction(newFaction);
}
}
return creature;
}
void BattlegroundAV::PostUpdateImpl(uint32 diff)
{
if (GetStatus() == STATUS_IN_PROGRESS)
{
for (uint8 i=0; i <= 1; i++)//0=alliance, 1=horde
{
if (!m_CaptainAlive[i])
continue;
if (m_CaptainBuffTimer[i] > diff)
m_CaptainBuffTimer[i] -= diff;
else
{
if (i == 0)
{
CastSpellOnTeam(AV_BUFF_A_CAPTAIN, ALLIANCE);
if (Creature* creature = GetBGCreature(AV_CPLACE_MAX + 61))
creature->AI()->DoAction(ACTION_BUFF_YELL);
}
else
{
CastSpellOnTeam(AV_BUFF_H_CAPTAIN, HORDE);
if (Creature* creature = GetBGCreature(AV_CPLACE_MAX + 59))
creature->AI()->DoAction(ACTION_BUFF_YELL);
}
m_CaptainBuffTimer[i] = 120000 + urand(0, 4)* 60000; //as far as i could see, the buff is randomly so i make 2minutes (thats the duration of the buff itself) + 0-4minutes @todo get the right times
}
}
//add points from mine owning, and look if he neutral team wanrts to reclaim the mine
m_Mine_Timer -=diff;
for (uint8 mine=0; mine <2; mine++)
{
if (m_Mine_Owner[mine] == ALLIANCE || m_Mine_Owner[mine] == HORDE)
{
if (m_Mine_Timer <= 0)
UpdateScore(m_Mine_Owner[mine], 1);
if (m_Mine_Reclaim_Timer[mine] > diff)
m_Mine_Reclaim_Timer[mine] -= diff;
else{ //we don't need to set this timer to 0 cause this codepart wont get called when this thing is 0
ChangeMineOwner(mine, AV_NEUTRAL_TEAM);
}
}
}
if (m_Mine_Timer <= 0)
m_Mine_Timer = AV_MINE_TICK_TIMER; //this is at the end, cause we need to update both mines
//looks for all timers of the nodes and destroy the building (for graveyards the building wont get destroyed, it goes just to the other team
for (BG_AV_Nodes i = BG_AV_NODES_FIRSTAID_STATION; i < BG_AV_NODES_MAX; ++i)
if (m_Nodes[i].State == POINT_ASSAULTED) //maybe remove this
{
if (m_Nodes[i].Timer > diff)
m_Nodes[i].Timer -= diff;
else
EventPlayerDestroyedPoint(i);
}
}
}
void BattlegroundAV::StartingEventCloseDoors()
{
DoorClose(BG_AV_OBJECT_DOOR_A);
DoorClose(BG_AV_OBJECT_DOOR_H);
}
void BattlegroundAV::StartingEventOpenDoors()
{
TC_LOG_DEBUG("bg.battleground", "BG_AV: start spawning mine stuff");
for (uint16 i= BG_AV_OBJECT_MINE_SUPPLY_N_MIN; i <= BG_AV_OBJECT_MINE_SUPPLY_N_MAX; i++)
SpawnBGObject(i, RESPAWN_IMMEDIATELY);
for (uint16 i= BG_AV_OBJECT_MINE_SUPPLY_S_MIN; i <= BG_AV_OBJECT_MINE_SUPPLY_S_MAX; i++)
SpawnBGObject(i, RESPAWN_IMMEDIATELY);
for (uint8 mine = AV_NORTH_MINE; mine <= AV_SOUTH_MINE; mine++) //mine population
ChangeMineOwner(mine, AV_NEUTRAL_TEAM, true);
UpdateWorldState(AV_SHOW_H_SCORE, 1);
UpdateWorldState(AV_SHOW_A_SCORE, 1);
DoorOpen(BG_AV_OBJECT_DOOR_H);
DoorOpen(BG_AV_OBJECT_DOOR_A);
// Achievement: The Alterac Blitz
StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, BG_AV_EVENT_START_BATTLE);
}
void BattlegroundAV::AddPlayer(Player* player)
{
bool const isInBattleground = IsPlayerInBattleground(player->GetGUID());
Battleground::AddPlayer(player);
if (!isInBattleground)
PlayerScores[player->GetGUID()] = new BattlegroundAVScore(player->GetGUID());
}
void BattlegroundAV::EndBattleground(uint32 winner)
{
//calculate bonuskills for both teams:
//first towers:
uint8 kills[2] = {0, 0}; // 0 = Alliance 1 = Horde
uint8 rep[2] = {0, 0}; // 0 = Alliance 1 = Horde
for (BG_AV_Nodes i = BG_AV_NODES_DUNBALDAR_SOUTH; i <= BG_AV_NODES_FROSTWOLF_WTOWER; ++i)
{
if (m_Nodes[i].State == POINT_CONTROLED)
{
if (m_Nodes[i].Owner == ALLIANCE)
{
rep[0] += BG_AV_REP_SURVIVING_TOWER;
kills[0] += BG_AV_KILL_SURVIVING_TOWER;
}
else
{
rep[0] += BG_AV_KILL_SURVIVING_TOWER;
kills[1] += BG_AV_KILL_SURVIVING_TOWER;
}
}
}
for (int i = TEAM_ALLIANCE; i <= TEAM_HORDE; ++i)
{
if (m_CaptainAlive[i])
{
kills[i] += BG_AV_KILL_SURVIVING_CAPTAIN;
rep[i] += BG_AV_REP_SURVIVING_CAPTAIN;
}
if (rep[i] != 0)
RewardReputationToTeam(i == 0 ? 730 : 729, rep[i], i == 0 ? ALLIANCE : HORDE);
if (kills[i] != 0)
RewardHonorToTeam(GetBonusHonorFromKill(kills[i]), i == 0 ? ALLIANCE : HORDE);
}
/// @todo add enterevademode for all attacking creatures
Battleground::EndBattleground(winner);
}
void BattlegroundAV::RemovePlayer(Player* player, ObjectGuid /*guid*/, uint32 /*team*/)
{
if (!player)
{
TC_LOG_ERROR("bg.battleground", "bg_AV no player at remove");
return;
}
/// @todo search more buffs
player->RemoveAurasDueToSpell(AV_BUFF_ARMOR);
player->RemoveAurasDueToSpell(AV_BUFF_A_CAPTAIN);
player->RemoveAurasDueToSpell(AV_BUFF_H_CAPTAIN);
}
void BattlegroundAV::HandleAreaTrigger(Player* player, uint32 trigger)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
switch (trigger)
{
case 95:
case 2608:
if (player->GetTeam() != ALLIANCE)
player->GetSession()->SendAreaTriggerMessage("Only The Alliance can use that portal");
else
player->LeaveBattleground();
break;
case 2606:
if (player->GetTeam() != HORDE)
player->GetSession()->SendAreaTriggerMessage("Only The Horde can use that portal");
else
player->LeaveBattleground();
break;
case 3326:
case 3327:
case 3328:
case 3329:
case 3330:
case 3331:
//Source->Unmount();
break;
default:
Battleground::HandleAreaTrigger(player, trigger);
break;
}
}
bool BattlegroundAV::UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor)
{
if (!Battleground::UpdatePlayerScore(player, type, value, doAddHonor))
return false;
switch (type)
{
case SCORE_GRAVEYARDS_ASSAULTED:
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE, AV_OBJECTIVE_ASSAULT_GRAVEYARD);
break;
case SCORE_GRAVEYARDS_DEFENDED:
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE, AV_OBJECTIVE_DEFEND_GRAVEYARD);
break;
case SCORE_TOWERS_ASSAULTED:
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE, AV_OBJECTIVE_ASSAULT_TOWER);
break;
case SCORE_TOWERS_DEFENDED:
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE, AV_OBJECTIVE_DEFEND_TOWER);
break;
default:
break;
}
return true;
}
void BattlegroundAV::EventPlayerDestroyedPoint(BG_AV_Nodes node)
{
uint32 object = GetObjectThroughNode(node);
TC_LOG_DEBUG("bg.battleground", "bg_av: player destroyed point node {} object {}", node, object);
//despawn banner
SpawnBGObject(object, RESPAWN_ONE_DAY);
DestroyNode(node);
UpdateNodeWorldState(node);
uint32 owner = m_Nodes[node].Owner;
if (IsTower(node))
{
uint8 tmp = node-BG_AV_NODES_DUNBALDAR_SOUTH;
//despawn marshal
if (!BgCreatures[AV_CPLACE_A_MARSHAL_SOUTH + tmp].IsEmpty())
DelCreature(AV_CPLACE_A_MARSHAL_SOUTH + tmp);
else
TC_LOG_ERROR("bg.battleground", "BG_AV: playerdestroyedpoint: marshal {} doesn't exist", AV_CPLACE_A_MARSHAL_SOUTH + tmp);
//spawn destroyed aura
for (uint8 i=0; i <= 9; i++)
SpawnBGObject(BG_AV_OBJECT_BURN_DUNBALDAR_SOUTH + i + (tmp * 10), RESPAWN_IMMEDIATELY);
UpdateScore((owner == ALLIANCE) ? HORDE : ALLIANCE, -1 * BG_AV_RES_TOWER);
RewardReputationToTeam(owner == ALLIANCE ? 730 : 729, BG_AV_REP_TOWER, owner);
RewardHonorToTeam(GetBonusHonorFromKill(BG_AV_KILL_TOWER), owner);
SpawnBGObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH + uint32(GetTeamIndexByTeamId(owner)) + (2 * tmp), RESPAWN_ONE_DAY);
SpawnBGObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH + uint32(GetTeamIndexByTeamId(owner)) + (2 * tmp), RESPAWN_ONE_DAY);
}
else
{
if (owner == ALLIANCE)
SpawnBGObject(object-11, RESPAWN_IMMEDIATELY);
else
SpawnBGObject(object+11, RESPAWN_IMMEDIATELY);
SpawnBGObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION + 3 * node, RESPAWN_ONE_DAY);
SpawnBGObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION + uint32(GetTeamIndexByTeamId(owner)) + 3 * node, RESPAWN_IMMEDIATELY);
PopulateNode(node);
if (node == BG_AV_NODES_SNOWFALL_GRAVE) //snowfall eyecandy
{
for (uint8 i = 0; i < 4; i++)
{
SpawnBGObject(((owner == ALLIANCE)?BG_AV_OBJECT_SNOW_EYECANDY_PA : BG_AV_OBJECT_SNOW_EYECANDY_PH)+i, RESPAWN_ONE_DAY);
SpawnBGObject(((owner == ALLIANCE)?BG_AV_OBJECT_SNOW_EYECANDY_A : BG_AV_OBJECT_SNOW_EYECANDY_H)+i, RESPAWN_IMMEDIATELY);
}
}
}
if (StaticNodeInfo const* nodeInfo = GetStaticNodeInfo(node))
if (Creature* herold = GetBGCreature(AV_CPLACE_HERALD))
herold->AI()->Talk(owner == ALLIANCE ? nodeInfo->TextIds.AllianceCapture : nodeInfo->TextIds.HordeCapture);
}
void BattlegroundAV::ChangeMineOwner(uint8 mine, uint32 team, bool initial)
{
// mine=0 northmine mine=1 southmin
// changing the owner results in setting respawntim to infinite for current creatures,
// spawning new mine owners creatures and changing the chest-objects so that the current owning team can use them
ASSERT(mine == AV_NORTH_MINE || mine == AV_SOUTH_MINE);
if (team != ALLIANCE && team != HORDE)
team = AV_NEUTRAL_TEAM;
if (m_Mine_Owner[mine] == team && !initial)
return;
m_Mine_PrevOwner[mine] = m_Mine_Owner[mine];
m_Mine_Owner[mine] = team;
if (!initial)
{
TC_LOG_DEBUG("bg.battleground", "bg_av depopulating mine {} (0=north, 1=south)", mine);
if (mine == AV_SOUTH_MINE)
for (uint16 i=AV_CPLACE_MINE_S_S_MIN; i <= AV_CPLACE_MINE_S_S_MAX; i++)
if (!BgCreatures[i].IsEmpty())
DelCreature(i); /// @todo just set the respawntime to 999999
for (uint16 i=((mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_1_MIN:AV_CPLACE_MINE_S_1_MIN); i <= ((mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_3:AV_CPLACE_MINE_S_3); i++)
if (!BgCreatures[i].IsEmpty())
DelCreature(i); /// @todo here also
}
SendMineWorldStates(mine);
TC_LOG_DEBUG("bg.battleground", "bg_av populating mine {} (0=north, 1=south)", mine);
uint16 miner;
//also neutral team exists.. after a big time, the neutral team tries to conquer the mine
if (mine == AV_NORTH_MINE)
{
if (team == ALLIANCE)
miner = AV_NPC_N_MINE_A_1;
else if (team == HORDE)
miner = AV_NPC_N_MINE_H_1;
else
miner = AV_NPC_N_MINE_N_1;
}
else
{
uint16 cinfo;
if (team == ALLIANCE)
miner = AV_NPC_S_MINE_A_1;
else if (team == HORDE)
miner = AV_NPC_S_MINE_H_1;
else
miner = AV_NPC_S_MINE_N_1;
//vermin
TC_LOG_DEBUG("bg.battleground", "spawning vermin");
if (team == ALLIANCE)
cinfo = AV_NPC_S_MINE_A_3;
else if (team == HORDE)
cinfo = AV_NPC_S_MINE_H_3;
else
cinfo = AV_NPC_S_MINE_N_S;
for (uint16 i=AV_CPLACE_MINE_S_S_MIN; i <= AV_CPLACE_MINE_S_S_MAX; i++)
AddAVCreature(cinfo, i);
}
for (uint16 i=((mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_1_MIN:AV_CPLACE_MINE_S_1_MIN); i <= ((mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_1_MAX:AV_CPLACE_MINE_S_1_MAX); i++)
AddAVCreature(miner, i);
//the next chooses randomly between 2 cretures
for (uint16 i=((mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_2_MIN:AV_CPLACE_MINE_S_2_MIN); i <= ((mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_2_MAX:AV_CPLACE_MINE_S_2_MAX); i++)
AddAVCreature(miner+(urand(1, 2)), i);
AddAVCreature(miner+3, (mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_3:AV_CPLACE_MINE_S_3);
if (team == ALLIANCE || team == HORDE)
{
m_Mine_Reclaim_Timer[mine]=AV_MINE_RECLAIM_TIMER;
if (Creature* herold = GetBGCreature(AV_CPLACE_HERALD))
{
if (mine == AV_NORTH_MINE)
herold->AI()->Talk(team == ALLIANCE ? TEXT_IRONDEEP_MINE_ALLIANCE_TAKEN : TEXT_IRONDEEP_MINE_HORDE_TAKEN);
else if (mine == AV_SOUTH_MINE)
herold->AI()->Talk(team == ALLIANCE ? TEXT_COLDTOOTH_MINE_ALLIANCE_TAKEN : TEXT_COLDTOOTH_MINE_HORDE_TAKEN);
}
}
else
{
if (mine == AV_SOUTH_MINE) //i think this gets called all the time
{
if (Creature* creature = GetBGCreature(AV_CPLACE_MINE_S_3))
creature->AI()->Talk(TEXT_SNIVVLE_RANDOM);
}
}
return;
}
bool BattlegroundAV::CanActivateGO(int32 GOId, uint32 team) const
{
if (GOId == BG_AV_OBJECTID_MINE_N)
return (m_Mine_Owner[AV_NORTH_MINE] == team);
if (GOId == BG_AV_OBJECTID_MINE_S)
return (m_Mine_Owner[AV_SOUTH_MINE] == team);
return true; //cause it's no mine'object it is ok if this is true
}
void BattlegroundAV::PopulateNode(BG_AV_Nodes node)
{
uint32 owner = m_Nodes[node].Owner;
ASSERT(owner);
uint32 c_place = AV_CPLACE_DEFENSE_STORM_AID + (4 * node);
uint32 creatureid;
if (IsTower(node))
creatureid=(owner == ALLIANCE)?AV_NPC_A_TOWERDEFENSE:AV_NPC_H_TOWERDEFENSE;
else
{
uint8 team2 = GetTeamIndexByTeamId(owner);
if (m_Team_QuestStatus[team2][0] < 500)
creatureid = (owner == ALLIANCE)? AV_NPC_A_GRAVEDEFENSE0 : AV_NPC_H_GRAVEDEFENSE0;
else if (m_Team_QuestStatus[team2][0] < 1000)
creatureid = (owner == ALLIANCE)? AV_NPC_A_GRAVEDEFENSE1 : AV_NPC_H_GRAVEDEFENSE1;
else if (m_Team_QuestStatus[team2][0] < 1500)
creatureid = (owner == ALLIANCE)? AV_NPC_A_GRAVEDEFENSE2 : AV_NPC_H_GRAVEDEFENSE2;
else
creatureid = (owner == ALLIANCE)? AV_NPC_A_GRAVEDEFENSE3 : AV_NPC_H_GRAVEDEFENSE3;
//spiritguide
if (!BgCreatures[node].IsEmpty())
DelCreature(node);
if (!AddSpiritGuide(node, BG_AV_CreaturePos[node], GetTeamIndexByTeamId(owner)))
TC_LOG_ERROR("bg.battleground", "AV: couldn't spawn spiritguide at node {}", node);
}
for (uint8 i=0; i<4; i++)
AddAVCreature(creatureid, c_place+i);
if (node >= BG_AV_NODES_MAX)//fail safe
return;
Creature* trigger = GetBGCreature(node + 302, false);//0-302 other creatures
if (!trigger)
{
trigger = AddCreature(WORLD_TRIGGER,
node + 302,
BG_AV_CreaturePos[node + 302],
GetTeamIndexByTeamId(owner));
}
// set correct faction for trigger
if (trigger)
{
if (owner != ALLIANCE && owner != HORDE)//node can be neutral, remove trigger
{
DelCreature(node + 302);
return;
}
trigger->SetFaction(owner == ALLIANCE ? FACTION_ALLIANCE_GENERIC : FACTION_HORDE_GENERIC);
}
}
void BattlegroundAV::DePopulateNode(BG_AV_Nodes node)
{
uint32 c_place = AV_CPLACE_DEFENSE_STORM_AID + (4 * node);
for (uint8 i = 0; i < 4; i++)
if (!BgCreatures[c_place + i].IsEmpty())
DelCreature(c_place + i);
//spiritguide
if (!IsTower(node) && !BgCreatures[node].IsEmpty())
DelCreature(node);
//remove bonus honor aura trigger creature when node is lost
if (node < BG_AV_NODES_MAX)//fail safe
DelCreature(node + 302);//NULL checks are in DelCreature! 0-302 spirit guides
}
BG_AV_Nodes BattlegroundAV::GetNodeThroughObject(uint32 object)
{
TC_LOG_DEBUG("bg.battleground", "bg_AV getnodethroughobject {}", object);
if (object <= BG_AV_OBJECT_FLAG_A_STONEHEART_BUNKER)
return BG_AV_Nodes(object);
if (object <= BG_AV_OBJECT_FLAG_C_A_FROSTWOLF_HUT)
return BG_AV_Nodes(object - 11);
if (object <= BG_AV_OBJECT_FLAG_C_A_FROSTWOLF_WTOWER)
return BG_AV_Nodes(object - 7);
if (object <= BG_AV_OBJECT_FLAG_C_H_STONEHEART_BUNKER)
return BG_AV_Nodes(object -22);
if (object <= BG_AV_OBJECT_FLAG_H_FROSTWOLF_HUT)
return BG_AV_Nodes(object - 33);
if (object <= BG_AV_OBJECT_FLAG_H_FROSTWOLF_WTOWER)
return BG_AV_Nodes(object - 29);
if (object == BG_AV_OBJECT_FLAG_N_SNOWFALL_GRAVE)
return BG_AV_NODES_SNOWFALL_GRAVE;
TC_LOG_ERROR("bg.battleground", "BattlegroundAV: ERROR! GetPlace got a wrong object :(");
ABORT();
return BG_AV_Nodes(0);
}
uint32 BattlegroundAV::GetObjectThroughNode(BG_AV_Nodes node)
{ //this function is the counterpart to GetNodeThroughObject()
TC_LOG_DEBUG("bg.battleground", "bg_AV GetObjectThroughNode {}", node);
if (m_Nodes[node].Owner == ALLIANCE)
{
if (m_Nodes[node].State == POINT_ASSAULTED)
{
if (node <= BG_AV_NODES_FROSTWOLF_HUT)
return node+11;
if (node >= BG_AV_NODES_ICEBLOOD_TOWER && node <= BG_AV_NODES_FROSTWOLF_WTOWER)
return node+7;
}
else if (m_Nodes[node].State == POINT_CONTROLED)
if (node <= BG_AV_NODES_STONEHEART_BUNKER)
return node;
}
else if (m_Nodes[node].Owner == HORDE)
{
if (m_Nodes[node].State == POINT_ASSAULTED)
{
if (node <= BG_AV_NODES_STONEHEART_BUNKER)
return node+22;
}
else if (m_Nodes[node].State == POINT_CONTROLED)
{
if (node <= BG_AV_NODES_FROSTWOLF_HUT)
return node+33;
if (node >= BG_AV_NODES_ICEBLOOD_TOWER && node <= BG_AV_NODES_FROSTWOLF_WTOWER)
return node+29;
}
}
else if (m_Nodes[node].Owner == AV_NEUTRAL_TEAM)
return BG_AV_OBJECT_FLAG_N_SNOWFALL_GRAVE;
TC_LOG_ERROR("bg.battleground", "BattlegroundAV: Error! GetPlaceNode couldn't resolve node {}", node);
ABORT();
return 0;
}
//called when using banner
void BattlegroundAV::EventPlayerClickedOnFlag(Player* source, GameObject* target_obj)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
int32 object = GetObjectType(target_obj->GetGUID());
TC_LOG_DEBUG("bg.battleground", "BG_AV using gameobject {} with type {}", target_obj->GetEntry(), object);
if (object < 0)
return;
switch (target_obj->GetEntry())
{
case BG_AV_OBJECTID_BANNER_A:
case BG_AV_OBJECTID_BANNER_A_B:
case BG_AV_OBJECTID_BANNER_H:
case BG_AV_OBJECTID_BANNER_H_B:
case BG_AV_OBJECTID_BANNER_SNOWFALL_N:
EventPlayerAssaultsPoint(source, object);
break;
case BG_AV_OBJECTID_BANNER_CONT_A:
case BG_AV_OBJECTID_BANNER_CONT_A_B:
case BG_AV_OBJECTID_BANNER_CONT_H:
case BG_AV_OBJECTID_BANNER_CONT_H_B:
EventPlayerDefendsPoint(source, object);
break;
default:
break;
}
}
void BattlegroundAV::EventPlayerDefendsPoint(Player* player, uint32 object)
{
ASSERT(GetStatus() == STATUS_IN_PROGRESS);
BG_AV_Nodes node = GetNodeThroughObject(object);
uint32 owner = m_Nodes[node].Owner; //maybe should name it prevowner
uint32 team = player->GetTeam();
if (owner == player->GetTeam() || m_Nodes[node].State != POINT_ASSAULTED)
return;
if (m_Nodes[node].TotalOwner == AV_NEUTRAL_TEAM)
{ //until snowfall doesn't belong to anyone it is better handled in assault-code
ASSERT(node == BG_AV_NODES_SNOWFALL_GRAVE); //currently the only neutral grave
EventPlayerAssaultsPoint(player, object);
return;
}
TC_LOG_DEBUG("bg.battleground", "player defends point object: {} node: {}", object, node);
if (m_Nodes[node].PrevOwner != team)
{
TC_LOG_ERROR("bg.battleground", "BG_AV: player defends point which doesn't belong to his team {}", node);
return;
}
//spawn new go :)
if (m_Nodes[node].Owner == ALLIANCE)
SpawnBGObject(object+22, RESPAWN_IMMEDIATELY); //spawn horde banner
else
SpawnBGObject(object-22, RESPAWN_IMMEDIATELY); //spawn alliance banner
if (!IsTower(node))
{
SpawnBGObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION + 3 * node, RESPAWN_ONE_DAY);
SpawnBGObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION + uint32(GetTeamIndexByTeamId(team)) + 3 * node, RESPAWN_IMMEDIATELY);
}
// despawn old go
SpawnBGObject(object, RESPAWN_ONE_DAY);
DefendNode(node, team);
PopulateNode(node);
UpdateNodeWorldState(node);
if (IsTower(node))
{
//spawn big flag+aura on top of tower
SpawnBGObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (team == ALLIANCE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY);
SpawnBGObject(BG_AV_OBJECT_TAURA_H_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (team == HORDE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY);
SpawnBGObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (team == ALLIANCE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY);
SpawnBGObject(BG_AV_OBJECT_TFLAG_H_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (team == HORDE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY);
}
else if (node == BG_AV_NODES_SNOWFALL_GRAVE) //snowfall eyecandy
{
for (uint8 i = 0; i < 4; i++)
{
SpawnBGObject(((owner == ALLIANCE)?BG_AV_OBJECT_SNOW_EYECANDY_PA : BG_AV_OBJECT_SNOW_EYECANDY_PH)+i, RESPAWN_ONE_DAY);
SpawnBGObject(((team == ALLIANCE)?BG_AV_OBJECT_SNOW_EYECANDY_A : BG_AV_OBJECT_SNOW_EYECANDY_H)+i, RESPAWN_IMMEDIATELY);
}
}
if (StaticNodeInfo const* nodeInfo = GetStaticNodeInfo(node))
if (Creature* herold = GetBGCreature(AV_CPLACE_HERALD))
herold->AI()->Talk(team == ALLIANCE ? nodeInfo->TextIds.AllianceCapture : nodeInfo->TextIds.HordeCapture);
// update the statistic for the defending player
UpdatePlayerScore(player, IsTower(node) ? SCORE_TOWERS_DEFENDED : SCORE_GRAVEYARDS_DEFENDED, 1);
}
void BattlegroundAV::EventPlayerAssaultsPoint(Player* player, uint32 object)
{
ASSERT(GetStatus() == STATUS_IN_PROGRESS);
BG_AV_Nodes node = GetNodeThroughObject(object);
uint32 owner = m_Nodes[node].Owner; //maybe name it prevowner
uint32 team = player->GetTeam();
TC_LOG_DEBUG("bg.battleground", "bg_av: player assaults point object {} node {}", object, node);
if (owner == team || team == m_Nodes[node].TotalOwner)
return; //surely a gm used this object
if (node == BG_AV_NODES_SNOWFALL_GRAVE) //snowfall is a bit special in capping + it gets eyecandy stuff
{
if (object == BG_AV_OBJECT_FLAG_N_SNOWFALL_GRAVE) //initial capping
{
if (!(owner == AV_NEUTRAL_TEAM && m_Nodes[node].TotalOwner == AV_NEUTRAL_TEAM))
return;
if (team == ALLIANCE)
SpawnBGObject(BG_AV_OBJECT_FLAG_C_A_SNOWFALL_GRAVE, RESPAWN_IMMEDIATELY);
else
SpawnBGObject(BG_AV_OBJECT_FLAG_C_H_SNOWFALL_GRAVE, RESPAWN_IMMEDIATELY);
SpawnBGObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION+3*node, RESPAWN_IMMEDIATELY); //neutral aura spawn
}
else if (m_Nodes[node].TotalOwner == AV_NEUTRAL_TEAM) //recapping, when no team owns this node realy
{
if (!(m_Nodes[node].State != POINT_CONTROLED))
return;
if (team == ALLIANCE)
SpawnBGObject(object-11, RESPAWN_IMMEDIATELY);
else
SpawnBGObject(object+11, RESPAWN_IMMEDIATELY);
}
//eyecandy
uint32 spawn, despawn;
if (team == ALLIANCE)
{
despawn = (m_Nodes[node].State == POINT_ASSAULTED)?BG_AV_OBJECT_SNOW_EYECANDY_PH : BG_AV_OBJECT_SNOW_EYECANDY_H;
spawn = BG_AV_OBJECT_SNOW_EYECANDY_PA;
}
else
{
despawn = (m_Nodes[node].State == POINT_ASSAULTED)?BG_AV_OBJECT_SNOW_EYECANDY_PA : BG_AV_OBJECT_SNOW_EYECANDY_A;
spawn = BG_AV_OBJECT_SNOW_EYECANDY_PH;
}
for (uint8 i = 0; i < 4; i++)
{
SpawnBGObject(despawn+i, RESPAWN_ONE_DAY);
SpawnBGObject(spawn+i, RESPAWN_IMMEDIATELY);
}
}
//if snowfall gots capped it can be handled like all other graveyards
if (m_Nodes[node].TotalOwner != AV_NEUTRAL_TEAM)
{
ASSERT(m_Nodes[node].Owner != AV_NEUTRAL_TEAM);
if (team == ALLIANCE)
SpawnBGObject(object-22, RESPAWN_IMMEDIATELY);
else
SpawnBGObject(object+22, RESPAWN_IMMEDIATELY);
if (IsTower(node))
{ //spawning/despawning of bigflag+aura
SpawnBGObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (team == ALLIANCE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY);
SpawnBGObject(BG_AV_OBJECT_TAURA_H_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (team == HORDE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY);
SpawnBGObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (team == ALLIANCE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY);
SpawnBGObject(BG_AV_OBJECT_TFLAG_H_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (team == HORDE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY);
}
else
{
//spawning/despawning of aura
SpawnBGObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION + 3 * node, RESPAWN_IMMEDIATELY); //neutral aura spawn
SpawnBGObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION + uint32(GetTeamIndexByTeamId(owner)) + 3 * node, RESPAWN_ONE_DAY); //teeamaura despawn
RelocateDeadPlayers(BgCreatures[node]);
}
DePopulateNode(node);
}
SpawnBGObject(object, RESPAWN_ONE_DAY); //delete old banner
AssaultNode(node, team);
UpdateNodeWorldState(node);
if (StaticNodeInfo const* nodeInfo = GetStaticNodeInfo(node))
if (Creature* herold = GetBGCreature(AV_CPLACE_HERALD))
herold->AI()->Talk(team == ALLIANCE ? nodeInfo->TextIds.AllianceAttack : nodeInfo->TextIds.HordeAttack);
// update the statistic for the assaulting player
UpdatePlayerScore(player, (IsTower(node)) ? SCORE_TOWERS_ASSAULTED : SCORE_GRAVEYARDS_ASSAULTED, 1);
}
void BattlegroundAV::FillInitialWorldStates(WorldPackets::WorldState::InitWorldStates& packet)
{
for (uint8 itr = BG_AV_NODES_FIRSTAID_STATION; itr < BG_AV_NODES_MAX; ++itr)
{
uint16 owner = m_Nodes[itr].Owner;
BG_AV_States state = m_Nodes[itr].State;
packet.Worldstates.emplace_back(BGAVNodeInfo[itr].WorldStateIds.AllianceAssault, (owner == ALLIANCE && state == POINT_ASSAULTED) ? 1 : 0);
packet.Worldstates.emplace_back(BGAVNodeInfo[itr].WorldStateIds.AllianceControl, (owner == ALLIANCE && state >= POINT_DESTROYED) ? 1 : 0);
packet.Worldstates.emplace_back(BGAVNodeInfo[itr].WorldStateIds.HordeAssault, (owner == HORDE && state == POINT_ASSAULTED) ? 1 : 0);
packet.Worldstates.emplace_back(BGAVNodeInfo[itr].WorldStateIds.HordeControl, (owner == HORDE && state >= POINT_DESTROYED) ? 1 : 0);
}
packet.Worldstates.emplace_back(AV_SNOWFALL_N, (m_Nodes[BG_AV_NODES_SNOWFALL_GRAVE].Owner == AV_NEUTRAL_TEAM ? 1 : 0));
packet.Worldstates.emplace_back(AV_Alliance_Score, m_Team_Scores[0]);
packet.Worldstates.emplace_back(AV_Horde_Score, m_Team_Scores[1]);
// only if game started the teamscores are displayed
if (GetStatus() == STATUS_IN_PROGRESS) {
packet.Worldstates.emplace_back(AV_SHOW_A_SCORE, 1);
packet.Worldstates.emplace_back(AV_SHOW_H_SCORE, 1);
}
else
{
packet.Worldstates.emplace_back(AV_SHOW_A_SCORE, 0);
packet.Worldstates.emplace_back(AV_SHOW_H_SCORE, 0);
}
SendMineWorldStates(AV_NORTH_MINE);
SendMineWorldStates(AV_SOUTH_MINE);
}
void BattlegroundAV::UpdateNodeWorldState(BG_AV_Nodes node)
{
if (StaticNodeInfo const* nodeInfo = GetStaticNodeInfo(node))
{
uint16 owner = m_Nodes[node].Owner;
BG_AV_States state = m_Nodes[node].State;
UpdateWorldState(nodeInfo->WorldStateIds.AllianceAssault, owner == ALLIANCE && state == POINT_ASSAULTED);
UpdateWorldState(nodeInfo->WorldStateIds.AllianceControl, owner == ALLIANCE && state >= POINT_DESTROYED);
UpdateWorldState(nodeInfo->WorldStateIds.HordeAssault, owner == HORDE && state == POINT_ASSAULTED);
UpdateWorldState(nodeInfo->WorldStateIds.HordeControl, owner == HORDE && state >= POINT_DESTROYED);
}
if (node == BG_AV_NODES_SNOWFALL_GRAVE)
UpdateWorldState(AV_SNOWFALL_N, m_Nodes[node].Owner == AV_NEUTRAL_TEAM);
}
void BattlegroundAV::SendMineWorldStates(uint32 mine)
{
ASSERT(mine == AV_NORTH_MINE || mine == AV_SOUTH_MINE);
// currently i'm sure, that this works (:
// ASSERT(m_Mine_PrevOwner[mine] == ALLIANCE || m_Mine_PrevOwner[mine] == HORDE || m_Mine_PrevOwner[mine] == AV_NEUTRAL_TEAM);
// ASSERT(m_Mine_Owner[mine] == ALLIANCE || m_Mine_Owner[mine] == HORDE || m_Mine_Owner[mine] == AV_NEUTRAL_TEAM);
uint8 owner, prevowner, mine2; //those variables are needed to access the right worldstate in the BG_AV_MineWorldStates array
mine2 = (mine == AV_NORTH_MINE)?0:1;
if (m_Mine_PrevOwner[mine] == ALLIANCE)
prevowner = 0;
else if (m_Mine_PrevOwner[mine] == HORDE)
prevowner = 2;
else
prevowner = 1;
if (m_Mine_Owner[mine] == ALLIANCE)
owner = 0;
else if (m_Mine_Owner[mine] == HORDE)
owner = 2;
else
owner = 1;
UpdateWorldState(BG_AV_MineWorldStates[mine2][owner], 1);
if (prevowner != owner)
UpdateWorldState(BG_AV_MineWorldStates[mine2][prevowner], 0);
}
WorldSafeLocsEntry const* BattlegroundAV::GetClosestGraveyard(Player* player)
{
WorldSafeLocsEntry const* pGraveyard = nullptr;
WorldSafeLocsEntry const* entry = nullptr;
float dist = 0;
float minDist = 0;
float x, y;
player->GetPosition(x, y);
pGraveyard = sWorldSafeLocsStore.LookupEntry(BG_AV_GraveyardIds[GetTeamIndexByTeamId(player->GetTeam())+7]);
minDist = (pGraveyard->Loc.X - x)*(pGraveyard->Loc.X - x)+(pGraveyard->Loc.Y - y)*(pGraveyard->Loc.Y - y);
for (uint8 i = BG_AV_NODES_FIRSTAID_STATION; i <= BG_AV_NODES_FROSTWOLF_HUT; ++i)
if (m_Nodes[i].Owner == player->GetTeam() && m_Nodes[i].State == POINT_CONTROLED)
{
entry = sWorldSafeLocsStore.LookupEntry(BG_AV_GraveyardIds[i]);
if (entry)
{
dist = (entry->Loc.X - x)*(entry->Loc.X - x)+(entry->Loc.Y - y)*(entry->Loc.Y - y);
if (dist < minDist)
{
minDist = dist;
pGraveyard = entry;
}
}
}
return pGraveyard;
}
bool BattlegroundAV::SetupBattleground()
{
// Create starting objects
if (// alliance gates
!AddObject(BG_AV_OBJECT_DOOR_A, BG_AV_OBJECTID_GATE_A, BG_AV_DoorPositons[0], BG_AV_DoorRotation[0].x, BG_AV_DoorRotation[0].y, BG_AV_DoorRotation[0].z, BG_AV_DoorRotation[0].w, RESPAWN_IMMEDIATELY)
// horde gates
|| !AddObject(BG_AV_OBJECT_DOOR_H, BG_AV_OBJECTID_GATE_H, BG_AV_DoorPositons[1], BG_AV_DoorRotation[1].x, BG_AV_DoorRotation[1].y, BG_AV_DoorRotation[1].z, BG_AV_DoorRotation[1].w, RESPAWN_IMMEDIATELY))
{
TC_LOG_ERROR("sql.sql", "BatteGroundAV: Failed to spawn some object Battleground not created!1");
return false;
}
//spawn node-objects
for (uint8 i = BG_AV_NODES_FIRSTAID_STATION; i < BG_AV_NODES_MAX; ++i)
{
if (i <= BG_AV_NODES_FROSTWOLF_HUT)
{
if (!AddObject(i, BG_AV_OBJECTID_BANNER_A_B,
BG_AV_ObjectPos[i],
0, 0, std::sin(BG_AV_ObjectPos[i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(i+11, BG_AV_OBJECTID_BANNER_CONT_A_B,
BG_AV_ObjectPos[i],
0, 0, std::sin(BG_AV_ObjectPos[i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(i+33, BG_AV_OBJECTID_BANNER_H_B,
BG_AV_ObjectPos[i],
0, 0, std::sin(BG_AV_ObjectPos[i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(i+22, BG_AV_OBJECTID_BANNER_CONT_H_B,
BG_AV_ObjectPos[i],
0, 0, std::sin(BG_AV_ObjectPos[i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i].GetOrientation()/2), RESPAWN_ONE_DAY)
//aura
|| !AddObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION+i*3, BG_AV_OBJECTID_AURA_N,
BG_AV_ObjectPos[i],
0, 0, std::sin(BG_AV_ObjectPos[i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION+i*3, BG_AV_OBJECTID_AURA_A,
BG_AV_ObjectPos[i],
0, 0, std::sin(BG_AV_ObjectPos[i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(BG_AV_OBJECT_AURA_H_FIRSTAID_STATION+i*3, BG_AV_OBJECTID_AURA_H,
BG_AV_ObjectPos[i],
0, 0, std::sin(BG_AV_ObjectPos[i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i].GetOrientation()/2), RESPAWN_ONE_DAY))
{
TC_LOG_ERROR("bg.battleground", "BatteGroundAV: Failed to spawn some object Battleground not created!2");
return false;
}
}
else //towers
{
if (i <= BG_AV_NODES_STONEHEART_BUNKER) //alliance towers
{
if (!AddObject(i, BG_AV_OBJECTID_BANNER_A,
BG_AV_ObjectPos[i],
0, 0, std::sin(BG_AV_ObjectPos[i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(i+22, BG_AV_OBJECTID_BANNER_CONT_H,
BG_AV_ObjectPos[i],
0, 0, std::sin(BG_AV_ObjectPos[i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_AURA_A,
BG_AV_ObjectPos[i+8],
0, 0, std::sin(BG_AV_ObjectPos[i+8].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i+8].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(BG_AV_OBJECT_TAURA_H_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_AURA_N,
BG_AV_ObjectPos[i+8],
0, 0, std::sin(BG_AV_ObjectPos[i+8].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i+8].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_TOWER_BANNER_A,
BG_AV_ObjectPos[i+8],
0, 0, std::sin(BG_AV_ObjectPos[i+8].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i+8].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(BG_AV_OBJECT_TFLAG_H_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_TOWER_BANNER_PH,
BG_AV_ObjectPos[i+8],
0, 0, std::sin(BG_AV_ObjectPos[i+8].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i+8].GetOrientation()/2), RESPAWN_ONE_DAY))
{
TC_LOG_ERROR("bg.battleground", "BatteGroundAV: Failed to spawn some object Battleground not created!3");
return false;
}
}
else //horde towers
{
if (!AddObject(i+7, BG_AV_OBJECTID_BANNER_CONT_A,
BG_AV_ObjectPos[i],
0, 0, std::sin(BG_AV_ObjectPos[i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(i+29, BG_AV_OBJECTID_BANNER_H,
BG_AV_ObjectPos[i],
0, 0, std::sin(BG_AV_ObjectPos[i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_AURA_N,
BG_AV_ObjectPos[i+8],
0, 0, std::sin(BG_AV_ObjectPos[i+8].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i+8].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(BG_AV_OBJECT_TAURA_H_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_AURA_H,
BG_AV_ObjectPos[i+8],
0, 0, std::sin(BG_AV_ObjectPos[i+8].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i+8].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_TOWER_BANNER_PA,
BG_AV_ObjectPos[i+8],
0, 0, std::sin(BG_AV_ObjectPos[i+8].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i+8].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(BG_AV_OBJECT_TFLAG_H_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_TOWER_BANNER_H,
BG_AV_ObjectPos[i+8],
0, 0, std::sin(BG_AV_ObjectPos[i+8].GetOrientation()/2), std::cos(BG_AV_ObjectPos[i+8].GetOrientation()/2), RESPAWN_ONE_DAY))
{
TC_LOG_ERROR("bg.battleground", "BatteGroundAV: Failed to spawn some object Battleground not created!4");
return false;
}
}
for (uint8 j=0; j <= 9; j++) //burning aura
{
if (!AddObject(BG_AV_OBJECT_BURN_DUNBALDAR_SOUTH+((i-BG_AV_NODES_DUNBALDAR_SOUTH)*10)+j,
BG_AV_OBJECTID_FIRE,
BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH+((i-BG_AV_NODES_DUNBALDAR_SOUTH)*10)+j],
0,
0,
std::sin(BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH+((i-BG_AV_NODES_DUNBALDAR_SOUTH)*10)+j].GetOrientation()/2),
std::cos(BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH+((i-BG_AV_NODES_DUNBALDAR_SOUTH)*10)+j].GetOrientation()/2),
RESPAWN_ONE_DAY))
{
TC_LOG_ERROR("bg.battleground", "BatteGroundAV: Failed to spawn some object Battleground not created!5.{}", i);
return false;
}
}
}
}
for (uint8 i=0; i<2; i++) //burning aura for buildings
{
for (uint8 j=0; j <= 9; j++)
{
if (j<5)
{
if (!AddObject(BG_AV_OBJECT_BURN_BUILDING_ALLIANCE+(i*10)+j,
BG_AV_OBJECTID_SMOKE,
BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j],
0,
0,
std::sin(BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j].GetOrientation()/2),
std::cos(BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j].GetOrientation()/2),
RESPAWN_ONE_DAY))
{
TC_LOG_ERROR("bg.battleground", "BatteGroundAV: Failed to spawn some object Battleground not created!6.{}", i);
return false;
}
}
else
{
if (!AddObject(BG_AV_OBJECT_BURN_BUILDING_ALLIANCE+(i*10)+j,
BG_AV_OBJECTID_FIRE,
BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j],
0,
0,
std::sin(BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j].GetOrientation()/2),
std::cos(BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j].GetOrientation()/2),
RESPAWN_ONE_DAY))
{
TC_LOG_ERROR("bg.battleground", "BatteGroundAV: Failed to spawn some object Battleground not created!7.{}", i);
return false;
}
}
}
}
for (uint16 i= 0; i <= (BG_AV_OBJECT_MINE_SUPPLY_N_MAX-BG_AV_OBJECT_MINE_SUPPLY_N_MIN); i++)
{
if (!AddObject(BG_AV_OBJECT_MINE_SUPPLY_N_MIN+i,
BG_AV_OBJECTID_MINE_N,
BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN+i],
0,
0,
std::sin(BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN+i].GetOrientation()/2),
std::cos(BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN+i].GetOrientation()/2),
RESPAWN_ONE_DAY))
{
TC_LOG_ERROR("bg.battleground", "BatteGroundAV: Failed to spawn some mine supplies Battleground not created!7.5.{}", i);
return false;
}
}
for (uint16 i= 0; i <= (BG_AV_OBJECT_MINE_SUPPLY_S_MAX-BG_AV_OBJECT_MINE_SUPPLY_S_MIN); i++)
{
if (!AddObject(BG_AV_OBJECT_MINE_SUPPLY_S_MIN+i,
BG_AV_OBJECTID_MINE_S,
BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN+i],
0,
0,
std::sin(BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN+i].GetOrientation()/2),
std::cos(BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN+i].GetOrientation()/2),
RESPAWN_ONE_DAY))
{
TC_LOG_ERROR("bg.battleground", "BatteGroundAV: Failed to spawn some mine supplies Battleground not created!7.6.{}", i);
return false;
}
}
if (!AddObject(BG_AV_OBJECT_FLAG_N_SNOWFALL_GRAVE,
BG_AV_OBJECTID_BANNER_SNOWFALL_N,
BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE],
0,
0,
std::sin(BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE].GetOrientation()/2),
std::cos(BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE].GetOrientation()/2),
RESPAWN_ONE_DAY))
{
TC_LOG_ERROR("bg.battleground", "BatteGroundAV: Failed to spawn some object Battleground not created!8");
return false;
}
for (uint8 i = 0; i < 4; i++)
{
if (!AddObject(BG_AV_OBJECT_SNOW_EYECANDY_A+i, BG_AV_OBJECTID_SNOWFALL_CANDY_A,
BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i],
0, 0, std::sin(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(BG_AV_OBJECT_SNOW_EYECANDY_PA+i, BG_AV_OBJECTID_SNOWFALL_CANDY_PA,
BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i],
0, 0, std::sin(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(BG_AV_OBJECT_SNOW_EYECANDY_H+i, BG_AV_OBJECTID_SNOWFALL_CANDY_H,
BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i],
0, 0, std::sin(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i].GetOrientation()/2), RESPAWN_ONE_DAY)
|| !AddObject(BG_AV_OBJECT_SNOW_EYECANDY_PH+i, BG_AV_OBJECTID_SNOWFALL_CANDY_PH,
BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i],
0, 0, std::sin(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i].GetOrientation()/2), std::cos(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i].GetOrientation()/2), RESPAWN_ONE_DAY))
{
TC_LOG_ERROR("bg.battleground", "BatteGroundAV: Failed to spawn some object Battleground not created!9.{}", i);
return false;
}
}
uint16 i;
TC_LOG_DEBUG("bg.battleground", "Alterac Valley: entering state STATUS_WAIT_JOIN ...");
// Initial Nodes
for (i = 0; i < BG_AV_OBJECT_MAX; i++)
SpawnBGObject(i, RESPAWN_ONE_DAY);
for (i = BG_AV_OBJECT_FLAG_A_FIRSTAID_STATION; i <= BG_AV_OBJECT_FLAG_A_STONEHEART_GRAVE; i++)
{
SpawnBGObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION+3*i, RESPAWN_IMMEDIATELY);
SpawnBGObject(i, RESPAWN_IMMEDIATELY);
}
for (i = BG_AV_OBJECT_FLAG_A_DUNBALDAR_SOUTH; i <= BG_AV_OBJECT_FLAG_A_STONEHEART_BUNKER; i++)
SpawnBGObject(i, RESPAWN_IMMEDIATELY);
for (i = BG_AV_OBJECT_FLAG_H_ICEBLOOD_GRAVE; i <= BG_AV_OBJECT_FLAG_H_FROSTWOLF_WTOWER; i++)
{
SpawnBGObject(i, RESPAWN_IMMEDIATELY);
if (i <= BG_AV_OBJECT_FLAG_H_FROSTWOLF_HUT)
SpawnBGObject(BG_AV_OBJECT_AURA_H_FIRSTAID_STATION+3*GetNodeThroughObject(i), RESPAWN_IMMEDIATELY);
}
for (i = BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH; i <= BG_AV_OBJECT_TFLAG_A_STONEHEART_BUNKER; i+=2)
{
SpawnBGObject(i, RESPAWN_IMMEDIATELY); //flag
SpawnBGObject(i+16, RESPAWN_IMMEDIATELY); //aura
}
for (i = BG_AV_OBJECT_TFLAG_H_ICEBLOOD_TOWER; i <= BG_AV_OBJECT_TFLAG_H_FROSTWOLF_WTOWER; i+=2)
{
SpawnBGObject(i, RESPAWN_IMMEDIATELY); //flag
SpawnBGObject(i+16, RESPAWN_IMMEDIATELY); //aura
}
//snowfall and the doors
for (i = BG_AV_OBJECT_FLAG_N_SNOWFALL_GRAVE; i <= BG_AV_OBJECT_DOOR_A; i++)
SpawnBGObject(i, RESPAWN_IMMEDIATELY);
SpawnBGObject(BG_AV_OBJECT_AURA_N_SNOWFALL_GRAVE, RESPAWN_IMMEDIATELY);
//creatures
TC_LOG_DEBUG("bg.battleground", "BG_AV start poputlating nodes");
for (BG_AV_Nodes n = BG_AV_NODES_FIRSTAID_STATION; n < BG_AV_NODES_MAX; ++n)
{
if (m_Nodes[n].Owner)
PopulateNode(n);
}
//all creatures which don't get despawned through the script are static
TC_LOG_DEBUG("bg.battleground", "BG_AV: start spawning static creatures");
for (i = 0; i < AV_STATICCPLACE_MAX; i++)
AddAVCreature(0, i + AV_CPLACE_MAX);
//mainspiritguides:
TC_LOG_DEBUG("bg.battleground", "BG_AV: start spawning spiritguides creatures");
AddSpiritGuide(7, BG_AV_CreaturePos[7], TEAM_ALLIANCE);
AddSpiritGuide(8, BG_AV_CreaturePos[8], TEAM_HORDE);
//spawn the marshals (those who get deleted, if a tower gets destroyed)
TC_LOG_DEBUG("bg.battleground", "BG_AV: start spawning marshal creatures");
for (i = AV_NPC_A_MARSHAL_SOUTH; i <= AV_NPC_H_MARSHAL_WTOWER; i++)
AddAVCreature(i, AV_CPLACE_A_MARSHAL_SOUTH + (i - AV_NPC_A_MARSHAL_SOUTH));
AddAVCreature(AV_NPC_HERALD, AV_CPLACE_HERALD);
return true;
}
void BattlegroundAV::AssaultNode(BG_AV_Nodes node, uint16 team)
{
if (m_Nodes[node].TotalOwner == team)
{
TC_LOG_FATAL("bg.battleground", "Assaulting team is TotalOwner of node");
ABORT();
}
if (m_Nodes[node].Owner == team)
{
TC_LOG_FATAL("bg.battleground", "Assaulting team is owner of node");
ABORT();
}
if (m_Nodes[node].State == POINT_DESTROYED)
{
TC_LOG_FATAL("bg.battleground", "Destroyed node is being assaulted");
ABORT();
}
if (m_Nodes[node].State == POINT_ASSAULTED && m_Nodes[node].TotalOwner) //only assault an assaulted node if no totalowner exists
{
TC_LOG_FATAL("bg.battleground", "Assault on an not assaulted node with total owner");
ABORT();
}
//the timer gets another time, if the previous owner was 0 == Neutral
m_Nodes[node].Timer = (m_Nodes[node].PrevOwner)? BG_AV_CAPTIME : BG_AV_SNOWFALL_FIRSTCAP;
m_Nodes[node].PrevOwner = m_Nodes[node].Owner;
m_Nodes[node].Owner = team;
m_Nodes[node].PrevState = m_Nodes[node].State;
m_Nodes[node].State = POINT_ASSAULTED;
}
void BattlegroundAV::DestroyNode(BG_AV_Nodes node)
{
ASSERT(m_Nodes[node].State == POINT_ASSAULTED);
m_Nodes[node].TotalOwner = m_Nodes[node].Owner;
m_Nodes[node].PrevOwner = m_Nodes[node].Owner;
m_Nodes[node].PrevState = m_Nodes[node].State;
m_Nodes[node].State = (m_Nodes[node].Tower)? POINT_DESTROYED : POINT_CONTROLED;
m_Nodes[node].Timer = 0;
}
void BattlegroundAV::InitNode(BG_AV_Nodes node, uint16 team, bool tower)
{
m_Nodes[node].TotalOwner = team;
m_Nodes[node].Owner = team;
m_Nodes[node].PrevOwner = 0;
m_Nodes[node].State = POINT_CONTROLED;
m_Nodes[node].PrevState = m_Nodes[node].State;
m_Nodes[node].State = POINT_CONTROLED;
m_Nodes[node].Timer = 0;
m_Nodes[node].Tower = tower;
}
void BattlegroundAV::DefendNode(BG_AV_Nodes node, uint16 team)
{
ASSERT(m_Nodes[node].TotalOwner == team);
ASSERT(m_Nodes[node].Owner != team);
ASSERT(m_Nodes[node].State != POINT_CONTROLED && m_Nodes[node].State != POINT_DESTROYED);
m_Nodes[node].PrevOwner = m_Nodes[node].Owner;
m_Nodes[node].Owner = team;
m_Nodes[node].PrevState = m_Nodes[node].State;
m_Nodes[node].State = POINT_CONTROLED;
m_Nodes[node].Timer = 0;
}
void BattlegroundAV::ResetBGSubclass()
{
for (uint8 i=0; i<2; i++) //forloop for both teams (it just make 0 == alliance and 1 == horde also for both mines 0=north 1=south
{
for (uint8 j=0; j<9; j++)
m_Team_QuestStatus[i][j]=0;
m_Team_Scores[i]=BG_AV_SCORE_INITIAL_POINTS;
m_IsInformedNearVictory[i]=false;
m_CaptainAlive[i] = true;
m_CaptainBuffTimer[i] = 120000 + urand(0, 4)* 60; //as far as i could see, the buff is randomly so i make 2minutes (thats the duration of the buff itself) + 0-4minutes @todo get the right times
m_Mine_Owner[i] = AV_NEUTRAL_TEAM;
m_Mine_PrevOwner[i] = m_Mine_Owner[i];
}
for (BG_AV_Nodes i = BG_AV_NODES_FIRSTAID_STATION; i <= BG_AV_NODES_STONEHEART_GRAVE; ++i) //alliance graves
InitNode(i, ALLIANCE, false);
for (BG_AV_Nodes i = BG_AV_NODES_DUNBALDAR_SOUTH; i <= BG_AV_NODES_STONEHEART_BUNKER; ++i) //alliance towers
InitNode(i, ALLIANCE, true);
for (BG_AV_Nodes i = BG_AV_NODES_ICEBLOOD_GRAVE; i <= BG_AV_NODES_FROSTWOLF_HUT; ++i) //horde graves
InitNode(i, HORDE, false);
for (BG_AV_Nodes i = BG_AV_NODES_ICEBLOOD_TOWER; i <= BG_AV_NODES_FROSTWOLF_WTOWER; ++i) //horde towers
InitNode(i, HORDE, true);
InitNode(BG_AV_NODES_SNOWFALL_GRAVE, AV_NEUTRAL_TEAM, false); //give snowfall neutral owner
m_Mine_Timer = AV_MINE_TICK_TIMER;
for (uint16 i = 0; i < AV_CPLACE_MAX + AsUnderlyingType(AV_STATICCPLACE_MAX); i++)
if (!BgCreatures[i].IsEmpty())
DelCreature(i);
}
bool BattlegroundAV::CheckAchievementCriteriaMeet(uint32 criteriaId, Player const* source, Unit const* target, uint32 miscValue)
{
uint32 team = source->GetTeam();
switch (criteriaId)
{
case BG_CRITERIA_CHECK_EVERYTHING_COUNTS:
for (uint8 mine = 0; mine < 2; mine++)
if (m_Mine_Owner[mine] != team)
return false;
return true;
case BG_CRITERIA_CHECK_AV_PERFECTION:
{
if (team == ALLIANCE)
{
for (BG_AV_Nodes i = BG_AV_NODES_DUNBALDAR_SOUTH; i <= BG_AV_NODES_STONEHEART_BUNKER; ++i) // alliance towers controlled
{
if (m_Nodes[i].State == POINT_CONTROLED)
{
if (m_Nodes[i].Owner != ALLIANCE)
return false;
}
else
return false;
}
for (BG_AV_Nodes i = BG_AV_NODES_ICEBLOOD_TOWER; i <= BG_AV_NODES_FROSTWOLF_WTOWER; ++i) // horde towers destroyed
if (m_Nodes[i].State != POINT_DESTROYED)
return false;
if (!m_CaptainAlive[0])
return false;
return true;
}
else if (team == HORDE)
{
for (BG_AV_Nodes i = BG_AV_NODES_ICEBLOOD_TOWER; i <= BG_AV_NODES_FROSTWOLF_WTOWER; ++i) // horde towers controlled
{
if (m_Nodes[i].State == POINT_CONTROLED)
{
if (m_Nodes[i].Owner != HORDE)
return false;
}
else
return false;
}
for (BG_AV_Nodes i = BG_AV_NODES_DUNBALDAR_SOUTH; i <= BG_AV_NODES_STONEHEART_BUNKER; ++i) // alliance towers destroyed
if (m_Nodes[i].State != POINT_DESTROYED)
return false;
if (!m_CaptainAlive[1])
return false;
return true;
}
}
}
return Battleground::CheckAchievementCriteriaMeet(criteriaId, source, target, miscValue);
}
uint32 BattlegroundAV::GetPrematureWinner()
{
uint32 allianceScore = m_Team_Scores[GetTeamIndexByTeamId(ALLIANCE)];
uint32 hordeScore = m_Team_Scores[GetTeamIndexByTeamId(HORDE)];
if (allianceScore > hordeScore)
return ALLIANCE;
else if (hordeScore > allianceScore)
return HORDE;
return Battleground::GetPrematureWinner();
}
| 412 | 0.981385 | 1 | 0.981385 | game-dev | MEDIA | 0.994103 | game-dev | 0.988726 | 1 | 0.988726 |
farhanwazir/laravelgooglemaps | 3,619 | src/FarhanWazir/GoogleMaps/Containers/isInsidePolygon.php | <?php namespace FarhanWazir\GoogleMaps\Containers;
/*
Description: The point-in-polygon algorithm allows you to check if a point is
inside a polygon or outside of it.
Author: Michal Niessen (2009)
Website: http://AssemblySys.com
Tutorial URL::: http://assemblysys.com/php-point-in-polygon-algorithm
If you find this script useful, you can show your
appreciation by getting Michal a cup of coffee ;)
PayPal: michael.niessen@assemblysys.com
As long as this notice (including author name and details) is included and
UNALTERED, this code is licensed under the GNU General Public License version 3:
http://www.gnu.org/licenses/gpl.html
*/
class isInsidePolygon {
var $pointOnVertex = true; // Check if the point sits exactly on one of the vertices?
//Constructor
function isInsidePolygon() {}
function pointInPolygon($point, $polygon, $pointOnVertex = true) {
$this->pointOnVertex = $pointOnVertex;
// Transform string coordinates into arrays with x and y values
$point = $this->pointStringToCoordinates($point);
$vertices = array();
foreach ($polygon as $vertex) {
$vertices[] = $this->pointStringToCoordinates($vertex);
}
// Check if the point sits exactly on a vertex
if ($this->pointOnVertex == true and $this->pointOnVertex($point, $vertices) == true) {
return true; //return "vertex"; //point is on boundary point
}
// Check if the point is inside the polygon or on the boundary
$intersections = 0;
$vertices_count = count($vertices);
for ($i=1; $i < $vertices_count; $i++) {
$vertex1 = $vertices[$i-1];
$vertex2 = $vertices[$i];
if ($vertex1['y'] == $vertex2['y'] and $vertex1['y'] == $point['y'] and $point['x'] > min($vertex1['x'], $vertex2['x']) and $point['x'] < max($vertex1['x'], $vertex2['x'])) { // Check if point is on an horizontal polygon boundary
return true; //return "boundary"; //point is on boundary line
}
if ($point['y'] > min($vertex1['y'], $vertex2['y']) and $point['y'] <= max($vertex1['y'], $vertex2['y']) and $point['x'] <= max($vertex1['x'], $vertex2['x']) and $vertex1['y'] != $vertex2['y']) {
$xinters = ($point['y'] - $vertex1['y']) * ($vertex2['x'] - $vertex1['x']) / ($vertex2['y'] - $vertex1['y']) + $vertex1['x'];
if ($xinters == $point['x']) { // Check if point is on the polygon boundary (other than horizontal)
return true; //return "boundary"; //point is on boundary line
}
if ($vertex1['x'] == $vertex2['x'] || $point['x'] <= $xinters) {
$intersections++;
}
}
}
// If the number of edges we passed through is odd, then it's in the polygon.
if ($intersections % 2 != 0) {
return true; //return "inside"; //point is inside
}
return false; //return "outside"; //point is outside
}
private function pointOnVertex($point, $vertices) {
foreach($vertices as $vertex) {
if ($point == $vertex) {
return true;
}
}
}
private function pointStringToCoordinates($pointString) {
if(strpos($pointString, ", ") !== false) $coordinates = explode(", ", $pointString);
elseif(strpos($pointString, ",") !== false) $coordinates = explode(", ", $pointString);
else $coordinates = explode(" ", $pointString);
return array("x" => $coordinates[0], "y" => $coordinates[1]);
}
}
| 412 | 0.627816 | 1 | 0.627816 | game-dev | MEDIA | 0.285687 | game-dev | 0.666193 | 1 | 0.666193 |
BananaFructa/Apec | 2,112 | src/main/java/Apec/Components/Gui/GuiIngame/GuiElements/XpText.java | package Apec.Components.Gui.GuiIngame.GuiElements;
import Apec.ApecMain;
import Apec.Utils.ApecUtils;
import Apec.Components.Gui.GuiIngame.GUIComponentID;
import Apec.Components.Gui.GuiIngame.TextComponent;
import Apec.DataInterpretation.DataExtractor;
import Apec.Settings.SettingID;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.GlStateManager;
import org.lwjgl.util.vector.Vector2f;
public class XpText extends TextComponent {
public XpText() {
super(GUIComponentID.XP_TEXT);
}
int stringWidth = 0;
@Override
public void draw(DataExtractor.PlayerStats ps, DataExtractor.ScoreBoardData sd, DataExtractor.OtherData od, ScaledResolution sr, boolean editingMode) {
super.draw(ps,sd,od,sr,editingMode);
GlStateManager.pushMatrix();
if (ApecMain.Instance.settingsManager.getSettingState(SettingID.XP_TEXT)) {
GlStateManager.scale(scale, scale, scale);
Vector2f StatBar = ApecUtils.scalarMultiply(getCurrentAnchorPoint(),oneOverScale);
String XPString;
if (ApecMain.Instance.dataExtractor.isInTheCatacombs && ApecMain.Instance.settingsManager.getSettingState(SettingID.XP_BAR)) {
XPString = "Ultimate Cooldown " + ApecUtils.ReduceToTwoDecimals(this.mc.thePlayer.experience * 100 + 0.1f) + "%";
} else {
XPString = "Lvl " + this.mc.thePlayer.experienceLevel + " XP";
}
ApecUtils.drawThiccBorderString(XPString, (int) (StatBar.x - mc.fontRendererObj.getStringWidth(XPString)), (int) (StatBar.y - 10), 0x80ff20);
stringWidth = Minecraft.getMinecraft().fontRendererObj.getStringWidth(XPString);
}
GlStateManager.popMatrix();
}
@Override
public Vector2f getAnchorPointPosition() {
return this.guiModifier.applyGlobalChanges(this,new Vector2f(g_sr.getScaledWidth() - 190 + 112 + 70, 53));
}
@Override
public Vector2f getBoundingPoint() {
return new Vector2f(-stringWidth*scale,-11*scale);
}
}
| 412 | 0.890331 | 1 | 0.890331 | game-dev | MEDIA | 0.81761 | game-dev | 0.976435 | 1 | 0.976435 |
Ideefixze/TutorialUnityMultiplayer | 7,178 | MultiplayerArchitectureUnity/Library/PackageCache/com.unity.2d.animation@4.2.2/Editor/SkinningModule/UserSettings.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.XR.WSA.Input;
namespace UnityEditor.U2D.Animation
{
internal class SkinningModuleSettings
{
public const string kCompactToolbarKey = UserSettings.kSettingsUniqueKey + "AnimationEditorSetting.compactToolbar";
public static readonly GUIContent kCompactToolbarLabel = EditorGUIUtility.TrTextContent("Hide Tool Text");
public static bool compactToolBar
{
get { return EditorPrefs.GetBool(kCompactToolbarKey, false); }
set { EditorPrefs.SetBool(kCompactToolbarKey, value); }
}
public void OnGUI()
{
EditorGUI.BeginChangeCheck();
var c = EditorGUILayout.Toggle(kCompactToolbarLabel, compactToolBar);
if (EditorGUI.EndChangeCheck())
compactToolBar = c;
}
}
internal class VisibilityToolSettings
{
public const string kBoneOpacitykey = UserSettings.kSettingsUniqueKey + "VisibilityToolSettings.boneOpacity";
public const string kMeshOpacityKey = UserSettings.kSettingsUniqueKey + "VisibilityToolSettings.meshOpacity";
public static float boneOpacity
{
get { return EditorPrefs.GetFloat(kBoneOpacitykey, 1.0f); }
set { EditorPrefs.SetFloat(kBoneOpacitykey, value); }
}
public static float meshOpacity
{
get { return EditorPrefs.GetFloat(kMeshOpacityKey, 0.5f); }
set { EditorPrefs.SetFloat(kMeshOpacityKey, value); }
}
}
internal class GenerateGeomertySettings
{
public const int kDefaultOutlineDetail = 10;
public const int kDefaultAlphaTolerance = 10;
public const int kDefaultSubdivide = 20;
public const string kOutlineDetailKey = UserSettings.kSettingsUniqueKey + "GenerateGeomertySetting.outlineDetail";
public const string kAlphaToleranceKey = UserSettings.kSettingsUniqueKey + "GenerateGeomertySetting.alphaTolerance";
public const string kSubdivideKey = UserSettings.kSettingsUniqueKey + "GenerateGeomertySetting.subdivide";
public const string kGenerateWeightsKey = UserSettings.kSettingsUniqueKey + "GenerateGeomertySetting.generateWeights";
public static int outlineDetail
{
get { return EditorPrefs.GetInt(kOutlineDetailKey, kDefaultOutlineDetail); }
set { EditorPrefs.SetInt(kOutlineDetailKey, value); }
}
public static int alphaTolerance
{
get { return EditorPrefs.GetInt(kAlphaToleranceKey, kDefaultAlphaTolerance); }
set { EditorPrefs.SetInt(kAlphaToleranceKey, value); }
}
public static int subdivide
{
get { return EditorPrefs.GetInt(kSubdivideKey, kDefaultSubdivide); }
set { EditorPrefs.SetInt(kSubdivideKey, value); }
}
public static bool generateWeights
{
get { return EditorPrefs.GetBool(kGenerateWeightsKey, true); }
set { EditorPrefs.SetBool(kGenerateWeightsKey, value); }
}
}
internal class SelectionOutlineSettings
{
public const string kSelectedOutlineRedKey = UserSettings.kSettingsUniqueKey + "OutlineColorRed";
public const string kSelectedOutlineGreenKey = UserSettings.kSettingsUniqueKey + "OutlineColorGreen";
public const string kSelectedOutlineBlueKey = UserSettings.kSettingsUniqueKey + "OutlineColorBlue";
public const string kSelectedOutlineAlphaKey = UserSettings.kSettingsUniqueKey + "OutlineColorAlpha";
public const string kSelectedSpriteOutlineSize = UserSettings.kSettingsUniqueKey + "OutlineSize";
public const string kSelectedBoneOutlineSize = UserSettings.kSettingsUniqueKey + "BoneOutlineSize";
public static readonly GUIContent kSelectedOutlineColorLabel = EditorGUIUtility.TrTextContent(TextContent.selectedOutlineColor);
public static readonly GUIContent kSelectedOutlineSizeLabel = EditorGUIUtility.TrTextContent(TextContent.spriteOutlineSize);
public static readonly GUIContent kSelectedBoneOutlineSizeLabel = EditorGUIUtility.TrTextContent(TextContent.boneOutlineSize);
public static Color outlineColor
{
get
{
return new Color()
{
r = EditorPrefs.GetFloat(kSelectedOutlineRedKey, 1),
g = EditorPrefs.GetFloat(kSelectedOutlineGreenKey, 102.0f / 255.0f),
b = EditorPrefs.GetFloat(kSelectedOutlineBlueKey, 0),
a = EditorPrefs.GetFloat(kSelectedOutlineAlphaKey, 1)
};
}
set
{
EditorPrefs.SetFloat(kSelectedOutlineRedKey, value.r);
EditorPrefs.SetFloat(kSelectedOutlineGreenKey, value.g);
EditorPrefs.SetFloat(kSelectedOutlineBlueKey, value.b);
EditorPrefs.SetFloat(kSelectedOutlineAlphaKey, value.a);
}
}
public static int selectedSpriteOutlineSize
{
get { return EditorPrefs.GetInt(kSelectedSpriteOutlineSize, 1); }
set { EditorPrefs.SetInt(kSelectedSpriteOutlineSize, value); }
}
public static float selectedBoneOutlineSize
{
get { return EditorPrefs.GetFloat(kSelectedBoneOutlineSize, 1); }
set { EditorPrefs.SetFloat(kSelectedBoneOutlineSize, value); }
}
public void OnGUI()
{
EditorGUI.BeginChangeCheck();
var c = EditorGUILayout.ColorField(kSelectedOutlineColorLabel, outlineColor);
if (EditorGUI.EndChangeCheck())
outlineColor = c;
EditorGUI.BeginChangeCheck();
var s = EditorGUILayout.IntSlider(kSelectedOutlineSizeLabel, selectedSpriteOutlineSize, 0, 10);
if (EditorGUI.EndChangeCheck())
selectedSpriteOutlineSize = s;
EditorGUI.BeginChangeCheck();
var o = EditorGUILayout.Slider(kSelectedBoneOutlineSizeLabel, selectedBoneOutlineSize, 0, 3);
if (EditorGUI.EndChangeCheck())
selectedBoneOutlineSize = o;
}
}
internal class UserSettings : SettingsProvider
{
public const string kSettingsUniqueKey = "UnityEditor.U2D.Animation/";
private static SelectionOutlineSettings s_SelectionOutlineSettings = new SelectionOutlineSettings();
private static SkinningModuleSettings s_SkinningModuleSettings = new SkinningModuleSettings();
public UserSettings() : base("Preferences/2D/Animation", SettingsScope.User)
{
guiHandler = OnGUI;
}
[SettingsProvider]
private static SettingsProvider CreateSettingsProvider()
{
return new UserSettings()
{
guiHandler = UserSettings.SettingsGUI
};
}
private static void SettingsGUI(string searchContext)
{
s_SkinningModuleSettings.OnGUI();
s_SelectionOutlineSettings.OnGUI();
}
}
}
| 412 | 0.777282 | 1 | 0.777282 | game-dev | MEDIA | 0.735323 | game-dev,desktop-app | 0.921322 | 1 | 0.921322 |
tahoma2d/tahoma2d | 5,607 | toonz/sources/toonz/scriptconsolepanel.cpp |
#include "scriptconsolepanel.h"
#include "toonzqt/scriptconsole.h"
#include "toonz/scriptengine.h"
#include "toonz/scriptbinding.h"
#include "toonz/scriptbinding_level.h"
#include "iocommand.h"
#include "tapp.h"
#include "toonz/toonzscene.h"
#include "toonz/tproject.h"
#include "toonz/tscenehandle.h"
#include "toonz/txsheethandle.h"
#include "toonz/txshlevel.h"
#include "toonz/txshsimplelevel.h"
#include "toonzqt/selection.h"
#include "toonzqt/tselectionhandle.h"
#include "flipbook.h"
#include "tvectorimage.h"
#include <QScriptEngine>
#include <QFile>
#include <QTextStream>
static QScriptValue loadSceneFun(QScriptContext *context,
QScriptEngine *engine) {
if (context->argumentCount() > 0) {
QString fpArg = context->argument(0).toString();
TFilePath fp(fpArg.toStdWString());
IoCmd::loadScene(fp);
}
return QScriptValue();
}
static QScriptValue saveSceneFun(QScriptContext *context,
QScriptEngine *engine) {
if (context->argumentCount() > 0) {
QString fpArg = context->argument(0).toString();
TFilePath fp(fpArg.toStdWString());
IoCmd::saveScene(fp, IoCmd::SILENTLY_OVERWRITE);
}
return QScriptValue();
}
static QScriptValue loadLevelFun(QScriptContext *context,
QScriptEngine *engine) {
if (context->argumentCount() > 0) {
QString fpArg = context->argument(0).toString();
TFilePath fp(fpArg.toStdWString());
int row = 0, col = 0;
if (context->argumentCount() == 3) {
row = context->argument(1).toInteger();
col = context->argument(1).toInteger();
}
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
TXsheet *xsh = scene->getXsheet();
TFilePath actualPath = scene->decodeFilePath(fp);
TXshLevel *xl = scene->loadLevel(actualPath);
if (xl) {
scene->getXsheet()->exposeLevel(row, col, xl);
}
app->getCurrentScene()->notifyCastChange();
app->getCurrentScene()->notifySceneChanged();
app->getCurrentXsheet()->notifyXsheetChanged();
}
return QScriptValue();
}
static QScriptValue dummyFun(QScriptContext *context, QScriptEngine *engine) {
return QScriptValue(engine, 0);
}
static QScriptValue viewFun(QScriptContext *context, QScriptEngine *engine) {
TScriptBinding::Image *image = 0;
TScriptBinding::Level *level = 0;
if (context->argumentCount() == 1) {
image = qscriptvalue_cast<TScriptBinding::Image *>(context->argument(0));
level = qscriptvalue_cast<TScriptBinding::Level *>(context->argument(0));
}
if (image) {
if (!image->getImg())
return context->throwError("Can't view an empty image");
} else if (level) {
if (!level->getSimpleLevel())
return context->throwError("Can't view an empty level");
} else {
return context->throwError("expected one argument : an image or a level");
}
FlipBook *flipBook;
flipBook = FlipBookPool::instance()->pop();
if (image) {
ImageViewer *imageViewer = flipBook->getImageViewer();
imageViewer->setImage(image->getImg());
} else {
flipBook->setLevel(level->getSimpleLevel());
}
return engine->globalObject().property("void");
}
static QScriptValue evaluateOnMainThread(QScriptContext *context,
QScriptEngine *engine) {
QScriptValue fun = context->callee().data();
QObject *obj = fun.data().toQObject();
QString s = fun.toString();
ScriptEngine *se = qobject_cast<ScriptEngine *>(obj);
return se->evaluateOnMainThread(fun, context->argumentsObject());
}
static void def(ScriptEngine *teng, const QString &name,
QScriptEngine::FunctionSignature fun) {
QScriptEngine *eng = teng->getQScriptEngine();
QScriptValue funVal = eng->newFunction(fun);
funVal.setData(eng->newQObject(teng));
QScriptValue evalFun = eng->newFunction(evaluateOnMainThread);
evalFun.setData(funVal);
eng->globalObject().setProperty(name, evalFun);
}
ScriptConsolePanel::ScriptConsolePanel(QWidget *parent, Qt::WindowFlags flags)
: TPanel(parent) {
setPanelType("ScriptConsole");
setIsMaximizable(false);
setWindowTitle(QObject::tr("Script Console"));
m_scriptConsole = new ScriptConsole(this);
ScriptEngine *teng = m_scriptConsole->getEngine();
/*
def(teng, "saveScene", saveSceneFun);
def(teng, "loadScene", loadSceneFun);
def(teng, "loadLevel", loadLevelFun);
*/
def(teng, "view", viewFun);
def(teng, "dummy", dummyFun);
// teng->getQScriptEngine()->evaluate("console={version:'1.0'};function
// version() {print('Toonz '+toonz.version+'\nscript '+script.version);};");
/*
QFile initFile(":/Resources/init.js");
if (initFile.open(QIODevice::ReadOnly))
{
QTextStream stream(&initFile);
QString contents = stream.readAll();
initFile.close();
teng->getQScriptEngine()->evaluate(contents, "init.js");
}
*/
setWidget(m_scriptConsole);
setMinimumHeight(80);
allowMultipleInstances(false);
resize(800, 300);
connect(m_scriptConsole, SIGNAL(selectionChanged()), this,
SLOT(selectNone()));
}
//-----------------------------------------------------------------------------
ScriptConsolePanel::~ScriptConsolePanel() {}
//-----------------------------------------------------------------------------
void ScriptConsolePanel::executeCommand(const QString &cmd) {
m_scriptConsole->executeCommand(cmd);
}
//-----------------------------------------------------------------------------
void ScriptConsolePanel::selectNone() {
TApp::instance()->getCurrentSelection()->setSelection(0);
}
| 412 | 0.817033 | 1 | 0.817033 | game-dev | MEDIA | 0.456134 | game-dev,desktop-app | 0.918669 | 1 | 0.918669 |
kysely-org/kysely | 1,394 | src/operation-node/add-index-node.ts | import { freeze } from '../util/object-utils.js'
import { IdentifierNode } from './identifier-node.js'
import { OperationNode } from './operation-node.js'
import { RawNode } from './raw-node.js'
export type AddIndexNodeProps = Omit<AddIndexNode, 'kind' | 'name'>
export interface AddIndexNode extends OperationNode {
readonly kind: 'AddIndexNode'
readonly name: IdentifierNode
readonly columns?: OperationNode[]
readonly unique?: boolean
readonly using?: RawNode
readonly ifNotExists?: boolean
}
type AddIndexNodeFactory = Readonly<{
is(node: OperationNode): node is AddIndexNode
create(name: string): Readonly<AddIndexNode>
cloneWith(
node: AddIndexNode,
props: Omit<AddIndexNode, 'kind' | 'name'>,
): Readonly<AddIndexNode>
cloneWithColumns(
node: AddIndexNode,
columns: OperationNode[],
): Readonly<AddIndexNode>
}>
/**
* @internal
*/
export const AddIndexNode: AddIndexNodeFactory = freeze<AddIndexNodeFactory>({
is(node): node is AddIndexNode {
return node.kind === 'AddIndexNode'
},
create(name) {
return freeze({
kind: 'AddIndexNode',
name: IdentifierNode.create(name),
})
},
cloneWith(node, props) {
return freeze({
...node,
...props,
})
},
cloneWithColumns(node, columns) {
return freeze({
...node,
columns: [...(node.columns || []), ...columns],
})
},
})
| 412 | 0.576203 | 1 | 0.576203 | game-dev | MEDIA | 0.426231 | game-dev | 0.77708 | 1 | 0.77708 |
andrianfaa/Bedah-APK-Undangan | 4,418 | decompiled classes.dex/sources/androidx/emoji2/text/flatbuffer/MetadataList.java | package androidx.emoji2.text.flatbuffer;
import androidx.emoji2.text.flatbuffer.MetadataItem;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public final class MetadataList extends Table {
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) {
__reset(_vector, _element_size, _bb);
return this;
}
public MetadataList get(int j) {
return get(new MetadataList(), j);
}
public MetadataList get(MetadataList obj, int j) {
return obj.__assign(MetadataList.__indirect(__element(j), this.bb), this.bb);
}
}
public static void ValidateVersion() {
Constants.FLATBUFFERS_1_12_0();
}
public static void addList(FlatBufferBuilder builder, int listOffset) {
builder.addOffset(1, listOffset, 0);
}
public static void addSourceSha(FlatBufferBuilder builder, int sourceShaOffset) {
builder.addOffset(2, sourceShaOffset, 0);
}
public static void addVersion(FlatBufferBuilder builder, int version) {
builder.addInt(0, version, 0);
}
public static int createListVector(FlatBufferBuilder builder, int[] data) {
builder.startVector(4, data.length, 4);
for (int length = data.length - 1; length >= 0; length--) {
builder.addOffset(data[length]);
}
return builder.endVector();
}
public static int createMetadataList(FlatBufferBuilder builder, int version, int listOffset, int sourceShaOffset) {
builder.startTable(3);
addSourceSha(builder, sourceShaOffset);
addList(builder, listOffset);
addVersion(builder, version);
return endMetadataList(builder);
}
public static int endMetadataList(FlatBufferBuilder builder) {
return builder.endTable();
}
public static void finishMetadataListBuffer(FlatBufferBuilder builder, int offset) {
builder.finish(offset);
}
public static void finishSizePrefixedMetadataListBuffer(FlatBufferBuilder builder, int offset) {
builder.finishSizePrefixed(offset);
}
public static MetadataList getRootAsMetadataList(ByteBuffer _bb) {
return getRootAsMetadataList(_bb, new MetadataList());
}
public static MetadataList getRootAsMetadataList(ByteBuffer _bb, MetadataList obj) {
_bb.order(ByteOrder.LITTLE_ENDIAN);
return obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb);
}
public static void startListVector(FlatBufferBuilder builder, int numElems) {
builder.startVector(4, numElems, 4);
}
public static void startMetadataList(FlatBufferBuilder builder) {
builder.startTable(3);
}
public MetadataList __assign(int _i, ByteBuffer _bb) {
__init(_i, _bb);
return this;
}
public void __init(int _i, ByteBuffer _bb) {
__reset(_i, _bb);
}
public MetadataItem list(int j) {
return list(new MetadataItem(), j);
}
public MetadataItem list(MetadataItem obj, int j) {
int __offset = __offset(6);
if (__offset != 0) {
return obj.__assign(__indirect(__vector(__offset) + (j * 4)), this.bb);
}
return null;
}
public int listLength() {
int __offset = __offset(6);
if (__offset != 0) {
return __vector_len(__offset);
}
return 0;
}
public MetadataItem.Vector listVector() {
return listVector(new MetadataItem.Vector());
}
public MetadataItem.Vector listVector(MetadataItem.Vector obj) {
int __offset = __offset(6);
if (__offset != 0) {
return obj.__assign(__vector(__offset), 4, this.bb);
}
return null;
}
public String sourceSha() {
int __offset = __offset(8);
if (__offset != 0) {
return __string(this.bb_pos + __offset);
}
return null;
}
public ByteBuffer sourceShaAsByteBuffer() {
return __vector_as_bytebuffer(8, 1);
}
public ByteBuffer sourceShaInByteBuffer(ByteBuffer _bb) {
return __vector_in_bytebuffer(_bb, 8, 1);
}
public int version() {
int __offset = __offset(4);
if (__offset != 0) {
return this.bb.getInt(this.bb_pos + __offset);
}
return 0;
}
}
| 412 | 0.587116 | 1 | 0.587116 | game-dev | MEDIA | 0.265525 | game-dev | 0.516516 | 1 | 0.516516 |
HyperMC-Team/OpenRoxy | 6,910 | src/main/java/net/minecraft/command/CommandStats.java | package net.minecraft.command;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.CommandResultStats;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.Entity;
import net.minecraft.scoreboard.ScoreObjective;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityCommandBlock;
import net.minecraft.tileentity.TileEntitySign;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
public class CommandStats
extends CommandBase {
@Override
public String getCommandName() {
return "stats";
}
@Override
public int getRequiredPermissionLevel() {
return 2;
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "commands.stats.usage";
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
CommandResultStats commandresultstats;
CommandResultStats.Type commandresultstats$type;
int i;
boolean flag;
if (args.length < 1) {
throw new WrongUsageException("commands.stats.usage", new Object[0]);
}
if (args[0].equals("entity")) {
flag = false;
} else {
if (!args[0].equals("block")) {
throw new WrongUsageException("commands.stats.usage", new Object[0]);
}
flag = true;
}
if (flag) {
if (args.length < 5) {
throw new WrongUsageException("commands.stats.block.usage", new Object[0]);
}
i = 4;
} else {
if (args.length < 3) {
throw new WrongUsageException("commands.stats.entity.usage", new Object[0]);
}
i = 2;
}
String s = args[i++];
if ("set".equals(s)) {
if (args.length < i + 3) {
if (i == 5) {
throw new WrongUsageException("commands.stats.block.set.usage", new Object[0]);
}
throw new WrongUsageException("commands.stats.entity.set.usage", new Object[0]);
}
} else {
if (!"clear".equals(s)) {
throw new WrongUsageException("commands.stats.usage", new Object[0]);
}
if (args.length < i + 1) {
if (i == 5) {
throw new WrongUsageException("commands.stats.block.clear.usage", new Object[0]);
}
throw new WrongUsageException("commands.stats.entity.clear.usage", new Object[0]);
}
}
if ((commandresultstats$type = CommandResultStats.Type.getTypeByName(args[i++])) == null) {
throw new CommandException("commands.stats.failed", new Object[0]);
}
World world = sender.getEntityWorld();
if (flag) {
BlockPos blockpos = CommandStats.parseBlockPos(sender, args, 1, false);
TileEntity tileentity = world.getTileEntity(blockpos);
if (tileentity == null) {
throw new CommandException("commands.stats.noCompatibleBlock", blockpos.getX(), blockpos.getY(), blockpos.getZ());
}
if (tileentity instanceof TileEntityCommandBlock) {
commandresultstats = ((TileEntityCommandBlock)tileentity).getCommandResultStats();
} else {
if (!(tileentity instanceof TileEntitySign)) {
throw new CommandException("commands.stats.noCompatibleBlock", blockpos.getX(), blockpos.getY(), blockpos.getZ());
}
commandresultstats = ((TileEntitySign)tileentity).getStats();
}
} else {
Entity entity = CommandStats.getEntity(sender, args[1]);
commandresultstats = entity.getCommandStats();
}
if ("set".equals(s)) {
String s1 = args[i++];
String s2 = args[i];
if (s1.length() == 0 || s2.length() == 0) {
throw new CommandException("commands.stats.failed", new Object[0]);
}
CommandResultStats.setScoreBoardStat(commandresultstats, commandresultstats$type, s1, s2);
CommandStats.notifyOperators(sender, (ICommand)this, "commands.stats.success", commandresultstats$type.getTypeName(), s2, s1);
} else if ("clear".equals(s)) {
CommandResultStats.setScoreBoardStat(commandresultstats, commandresultstats$type, null, null);
CommandStats.notifyOperators(sender, (ICommand)this, "commands.stats.cleared", commandresultstats$type.getTypeName());
}
if (flag) {
BlockPos blockpos1 = CommandStats.parseBlockPos(sender, args, 1, false);
TileEntity tileentity1 = world.getTileEntity(blockpos1);
tileentity1.markDirty();
}
}
@Override
public List<String> addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) {
return args.length == 1 ? CommandStats.getListOfStringsMatchingLastWord(args, "entity", "block") : (args.length == 2 && args[0].equals("entity") ? CommandStats.getListOfStringsMatchingLastWord(args, this.func_175776_d()) : (args.length >= 2 && args.length <= 4 && args[0].equals("block") ? CommandStats.func_175771_a(args, 1, pos) : (!(args.length == 3 && args[0].equals("entity") || args.length == 5 && args[0].equals("block")) ? (!(args.length == 4 && args[0].equals("entity") || args.length == 6 && args[0].equals("block")) ? (!(args.length == 6 && args[0].equals("entity") || args.length == 8 && args[0].equals("block")) ? null : CommandStats.getListOfStringsMatchingLastWord(args, this.func_175777_e())) : CommandStats.getListOfStringsMatchingLastWord(args, CommandResultStats.Type.getTypeNames())) : CommandStats.getListOfStringsMatchingLastWord(args, "set", "clear"))));
}
protected String[] func_175776_d() {
return MinecraftServer.getServer().getAllUsernames();
}
protected List<String> func_175777_e() {
Collection<ScoreObjective> collection = MinecraftServer.getServer().worldServerForDimension(0).getScoreboard().getScoreObjectives();
ArrayList list = Lists.newArrayList();
for (ScoreObjective scoreobjective : collection) {
if (scoreobjective.getCriteria().isReadOnly()) continue;
list.add(scoreobjective.getName());
}
return list;
}
@Override
public boolean isUsernameIndex(String[] args, int index) {
return args.length > 0 && args[0].equals("entity") && index == 1;
}
}
| 412 | 0.86113 | 1 | 0.86113 | game-dev | MEDIA | 0.913371 | game-dev | 0.852168 | 1 | 0.852168 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.