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
space-wizards/space-station-14
1,242
Content.Server/Atmos/Piping/Binary/EntitySystems/GasValveSystem.cs
using Content.Server.NodeContainer.EntitySystems; using Content.Server.NodeContainer.Nodes; using Content.Shared.Atmos.Piping.Binary.Components; using Content.Shared.Atmos.Piping.Binary.Systems; using Content.Shared.Audio; namespace Content.Server.Atmos.Piping.Binary.EntitySystems; public sealed class GasValveSystem : SharedGasValveSystem { [Dependency] private readonly SharedAmbientSoundSystem _ambientSoundSystem = default!; [Dependency] private readonly NodeContainerSystem _nodeContainer = default!; public override void Set(EntityUid uid, GasValveComponent component, bool value) { base.Set(uid, component, value); if (_nodeContainer.TryGetNodes(uid, component.InletName, component.OutletName, out PipeNode? inlet, out PipeNode? outlet)) { if (component.Open) { inlet.AddAlwaysReachable(outlet); outlet.AddAlwaysReachable(inlet); _ambientSoundSystem.SetAmbience(uid, true); } else { inlet.RemoveAlwaysReachable(outlet); outlet.RemoveAlwaysReachable(inlet); _ambientSoundSystem.SetAmbience(uid, false); } } } }
1
0.729258
1
0.729258
game-dev
MEDIA
0.702139
game-dev
0.631239
1
0.631239
sebbas/blender-mantaflow
1,379
release/scripts/templates_py/operator_modal.py
import bpy from bpy.props import IntProperty, FloatProperty class ModalOperator(bpy.types.Operator): """Move an object with the mouse, example""" bl_idname = "object.modal_operator" bl_label = "Simple Modal Operator" first_mouse_x: IntProperty() first_value: FloatProperty() def modal(self, context, event): if event.type == 'MOUSEMOVE': delta = self.first_mouse_x - event.mouse_x context.object.location.x = self.first_value + delta * 0.01 elif event.type == 'LEFTMOUSE': return {'FINISHED'} elif event.type in {'RIGHTMOUSE', 'ESC'}: context.object.location.x = self.first_value return {'CANCELLED'} return {'RUNNING_MODAL'} def invoke(self, context, event): if context.object: self.first_mouse_x = event.mouse_x self.first_value = context.object.location.x context.window_manager.modal_handler_add(self) return {'RUNNING_MODAL'} else: self.report({'WARNING'}, "No active object, could not finish") return {'CANCELLED'} def register(): bpy.utils.register_class(ModalOperator) def unregister(): bpy.utils.unregister_class(ModalOperator) if __name__ == "__main__": register() # test call bpy.ops.object.modal_operator('INVOKE_DEFAULT')
1
0.763705
1
0.763705
game-dev
MEDIA
0.82586
game-dev
0.866596
1
0.866596
OpenSees/OpenSees
13,797
SRC/analysis/algorithm/equiSolnAlgo/Broyden.cpp
/* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** Frank McKenna (fmckenna@ce.berkeley.edu) ** ** Gregory L. Fenves (fenves@ce.berkeley.edu) ** ** Filip C. Filippou (filippou@ce.berkeley.edu) ** ** ** ** ****************************************************************** */ // $Revision: 1.7 $ // $Date: 2010-04-22 23:42:10 $ // $Source: /usr/local/cvs/OpenSees/SRC/analysis/algorithm/equiSolnAlgo/Broyden.cpp,v $ // Written: Ed C++ Love // Created: 04/01 // Description: This file contains the class definition implementation of // Broyden. // // What: "@(#)Broyden.h, revA" #include <Broyden.h> #include <AnalysisModel.h> #include <StaticAnalysis.h> #include <IncrementalIntegrator.h> #include <LinearSOE.h> #include <Channel.h> #include <FEM_ObjectBroker.h> #include <ConvergenceTest.h> #include <ID.h> #include <math.h> #include <elementAPI.h> void* OPS_Broyden() { int formTangent = CURRENT_TANGENT; int count = -1; while (OPS_GetNumRemainingInputArgs() > 0) { const char* flag = OPS_GetString(); if (strcmp(flag,"-secant") == 0) { formTangent = CURRENT_SECANT; } else if (strcmp(flag,"-initial") == 0) { formTangent = INITIAL_TANGENT; } else if (strcmp(flag,"-count") == 0 && OPS_GetNumRemainingInputArgs()>0) { int numdata = 1; if (OPS_GetIntInput(&numdata, &count) < 0) { opserr << "WARNING Broyden failed to read count\n"; return 0; } } } if (count == -1) return new Broyden(formTangent); else return new Broyden(formTangent, count); } // Constructor Broyden::Broyden(int theTangentToUse, int n ) :EquiSolnAlgo(EquiALGORITHM_TAGS_Broyden), tangent(theTangentToUse), numberLoops(n) { s = new Vector*[numberLoops+3] ; z = new Vector*[numberLoops+3] ; residOld = 0 ; residNew = 0 ; du = 0 ; temp = 0 ; for ( int i =0; i < numberLoops+3; i++ ) { s[i] = 0 ; z[i] = 0 ; //r[i] = 0 ; } localTest = 0; } //Constructor Broyden::Broyden(ConvergenceTest &theT, int theTangentToUse, int n) :EquiSolnAlgo(EquiALGORITHM_TAGS_Broyden), tangent(theTangentToUse), numberLoops(n) { s = new Vector*[numberLoops+3] ; z = new Vector*[numberLoops+3] ; residOld = 0 ; residNew = 0 ; du = 0 ; temp = 0 ; for ( int i =0; i < numberLoops+3; i++ ) { s[i] = 0 ; z[i] = 0 ; } localTest= 0; } // Destructor Broyden::~Broyden() { if ( residOld != 0 ) delete residOld ; residOld = 0 ; if ( residNew != 0 ) delete residNew ; residNew = 0 ; if ( du != 0 ) delete du ; du = 0 ; if ( temp != 0 ) delete temp ; temp = 0 ; for ( int i =0; i < numberLoops+3; i++ ) { if ( s[i] != 0 ) delete s[i] ; if ( z[i] != 0 ) delete z[i] ; s[i] = 0 ; z[i] = 0 ; } //end for i if ( s != 0 ) delete[] s ; if ( z != 0 ) delete[] z ; s = 0 ; z = 0 ; if ( localTest != 0 ) delete localTest ; localTest = 0; } void Broyden::setLinks(AnalysisModel &theModel, IncrementalIntegrator &theIntegrator, LinearSOE &theSOE, ConvergenceTest *theTest) { this->EquiSolnAlgo::setLinks(theModel, theIntegrator, theSOE, theTest); if (theTest == 0) return; if ( localTest != 0 ) delete localTest ; localTest = theTest->getCopy(this->numberLoops); if (localTest == 0) { opserr << "Broyden::setTest() - could not get a copy\n"; } } int Broyden::setConvergenceTest(ConvergenceTest *newTest) { this->EquiSolnAlgo::setConvergenceTest(newTest); if (theTest == 0) return 0; if ( localTest != 0 ) delete localTest ; localTest = theTest->getCopy( this->numberLoops ) ; if (localTest == 0) { opserr << "Broyden::setTest() - could not get a copy\n"; return -1; } return 0; } int Broyden::solveCurrentStep(void) { // set up some pointers and check they are valid // NOTE this could be taken away if we set Ptrs as protecetd in superclass AnalysisModel *theAnaModel = this->getAnalysisModelPtr(); IncrementalIntegrator *theIntegrator = this->getIncrementalIntegratorPtr(); LinearSOE *theSOE = this->getLinearSOEptr(); if ((theAnaModel == 0) || (theIntegrator == 0) || (theSOE == 0) || (theTest == 0)){ opserr << "WARNING Broyden::solveCurrentStep() - setLinks() has"; opserr << " not been called - or no ConvergenceTest has been set\n"; return -5; } // set itself as the ConvergenceTest objects EquiSolnAlgo theTest->setEquiSolnAlgo(*this); if (theTest->start() < 0) { opserr << "Broyden::solveCurrentStep() -"; opserr << "the ConvergenceTest object failed in start()\n"; return -3; } localTest->setEquiSolnAlgo(*this); int result = -1 ; int count = 0 ; do { // opserr << " Broyden -- Forming New Tangent" << endln ; //form the initial tangent if (theIntegrator->formTangent(tangent) < 0){ opserr << "WARNING Broyden::solveCurrentStep() -"; opserr << "the Integrator failed in formTangent()\n"; return -1; } //form the initial residual if (theIntegrator->formUnbalance() < 0) { opserr << "WARNING Broyden::solveCurrentStep() -"; opserr << "the Integrator failed in formUnbalance()\n"; } //solve if (theSOE->solve() < 0) { opserr << "WARNING Broyden::solveCurrentStep() -"; opserr << "the LinearSysOfEqn failed in solve()\n"; return -3; } //update if ( theIntegrator->update(theSOE->getX() ) < 0) { opserr << "WARNING Broyden::solveCurrentStep() -"; opserr << "the Integrator failed in update()\n"; return -4; } // int systemSize = ( theSOE->getB() ).Size(); int systemSize = theSOE->getNumEqn( ) ; //temporary vector if ( temp == 0 ) temp = new Vector(systemSize) ; //initial displacement increment if ( s[1] == 0 ) s[1] = new Vector(systemSize) ; *s[1] = theSOE->getX( ) ; //initial residual /* if ( r[0] == 0 ) r[0] = new Vector(systemSize) ; *r[0] = theSOE->getB( ) ; *r[0] *= (-1.0 ) ; */ if ( residOld == 0 ) residOld = new Vector(systemSize) ; *residOld = theSOE->getB( ) ; *residOld *= (-1.0 ) ; //form the residual again if (theIntegrator->formUnbalance() < 0) { opserr << "WARNING Broyden::solveCurrentStep() -"; opserr << "the Integrator failed in formUnbalance()\n"; } if ( residNew == 0 ) residNew = new Vector(systemSize) ; if ( du == 0 ) du = new Vector(systemSize) ; localTest->start() ; int nBroyden = 1 ; do { //save residual /* if ( r[nBroyden] == 0 ) r[nBroyden] = new Vector(systemSize) ; *r[nBroyden] = theSOE->getB( ) ; *r[nBroyden] *= (-1.0 ) ; */ *residNew = theSOE->getB( ) ; *residNew *= (-1.0 ) ; //solve if (theSOE->solve() < 0) { opserr << "WARNING Broyden::solveCurrentStep() -"; opserr << "the LinearSysOfEqn failed in solve()\n"; return -3; } //save displacement increment *du = theSOE->getX( ) ; //broyden modifications to du BroydenUpdate( theIntegrator, theSOE, *du, nBroyden ) ; if ( theIntegrator->update( *du ) < 0 ) { opserr << "WARNING Broyden::solveCurrentStep() -"; opserr << "the Integrator failed in update()\n"; return -4; } /* opserr << " Broyden Iteration " << nBroyden << " Residual Norm = " << sqrt( (*residNew) ^ (*residNew) ) << endln ; */ //increment broyden counter nBroyden += 1 ; //save displacement increment if ( s[nBroyden] == 0 ) s[nBroyden] = new Vector(systemSize) ; *s[nBroyden] = *du ; //swap residuals *residOld = *residNew ; //form the residual again if (theIntegrator->formUnbalance() < 0) { opserr << "WARNING Broyden::solveCurrentStep() -"; opserr << "the Integrator failed in formUnbalance()\n"; } result = localTest->test() ; } while ( result == -1 && nBroyden <= numberLoops ); result = theTest->test(); this->record(count++); } while (result == -1); if (result == -2) { opserr << "Broyden::solveCurrentStep() -"; opserr << "the ConvergenceTest object failed in test()\n"; return -3; } // note - if positive result we are returning what the convergence test returned // which should be the number of iterations return result; } void Broyden::BroydenUpdate( IncrementalIntegrator *theIntegrator, LinearSOE *theSOE, Vector &du, int nBroyden ) { static const double eps = 1.0e-16 ; // int systemSize = ( theSOE->getB() ).Size(); int systemSize = theSOE->getNumEqn( ) ; //compute z // theSOE->setB( (*r[nBroyden]) - (*r[nBroyden-1]) ) ; // theSOE->setB( (*residNew) - (*residOld) ) ; *temp = (*residNew) ; *temp -= (*residOld) ; theSOE->setB( *temp ) ; if (theSOE->solve() < 0) { opserr << "WARNING Broyden::solveCurrentStep() -"; opserr << "the LinearSysOfEqn failed in solve()\n"; } if ( z[nBroyden] == 0 ) z[nBroyden] = new Vector(systemSize) ; *z[nBroyden] = theSOE->getX() ; *z[nBroyden] *= (-1.0) ; int i; for ( i=1; i<=(nBroyden-1); i++ ) { double p = - ( (*s[i]) ^ (*z[i]) ) ; if ( fabs(p) < eps ) break ; double sdotz = (*s[i]) ^ (*z[nBroyden]) ; //*z[nBroyden] += (1.0/p) * sdotz * ( *s[i] + *z[i] ) ; *temp = (*s[i]) ; *temp += (*z[i]) ; *temp *= ( (1.0/p) * sdotz ) ; *z[nBroyden] += (*temp) ; } //end for i //broyden modifications to du for ( i=1; i<=nBroyden; i++ ) { double p = - ( (*s[i]) ^ (*z[i]) ) ; if ( fabs(p) < eps ) break ; double sdotdu = (*s[i]) ^ du ; //du += (1.0/p) * sdotdu * ( *s[i] + *z[i] ) ; *temp = (*s[i]) ; *temp += (*z[i]) ; *temp *= ( (1.0/p) * sdotdu ) ; du += (*temp) ; } //end for i } ConvergenceTest * Broyden::getConvergenceTest(void) { return theTest; } int Broyden::sendSelf(int cTag, Channel &theChannel) { static ID data(2); data(0) = tangent; data(1) = numberLoops; if (theChannel.sendID(0, cTag, data) < 0) { opserr << "Broyden::sendSelf() - failed to send data\n"; return -1; } return 0; } int Broyden::recvSelf(int cTag, Channel &theChannel, FEM_ObjectBroker &theBroker) { static ID data(2); if (theChannel.recvID(0, cTag, data) < 0) { opserr << "Broyden::recvSelf() - failed to recv data\n"; return -1; } tangent = data(0); if (numberLoops != data(1)) { // remove old if (s != 0 && z != 0) { for ( int i =0; i < numberLoops+3; i++ ) { if ( s[i] != 0 ) delete s[i] ; if ( z[i] != 0 ) delete z[i] ; } delete [] s; delete [] z; } numberLoops = data(1); // create new s = new Vector*[numberLoops+3] ; z = new Vector*[numberLoops+3] ; for ( int i =0; i < numberLoops+3; i++ ) { s[i] = 0 ; z[i] = 0 ; } } return 0; } void Broyden::Print(OPS_Stream &s, int flag) { if (flag == 0) { s << "Broyden" << endln ; s << " Number of Iterations = " << numberLoops << endln ; } } //const Vector &pi = *p[i] ; // //residual at this iteration before next solve // Resid0 = theSOE->getB() ; // //line search direction // dx0 = theSOE->getX() ; /* //first solve step if (theIntegrator->formTangent(tangent) < 0){ opserr << "WARNING Broyden::solveCurrentStep() -"; opserr << "the Integrator failed in formTangent()\n"; return -1; } if (theSOE->solve() < 0) { opserr << "WARNING Broyden::solveCurrentStep() -"; opserr << "the LinearSysOfEqn failed in solve()\n"; return -3; } if (theIntegrator->update(theSOE->getX()) < 0) { opserr << "WARNING Broyden::solveCurrentStep() -"; opserr << "the Integrator failed in update()\n"; return -4; } if (theIntegrator->formUnbalance() < 0) { opserr << "WARNING Broyden::solveCurrentStep() -"; opserr << "the Integrator failed in formUnbalance()\n"; return -2; } result = theTest->test(); this->record(nBroyden++); const Vector &du = BroydengetX( theIntegrator, theSOE, nBroyden ) ; */
1
0.928046
1
0.928046
game-dev
MEDIA
0.200421
game-dev
0.97234
1
0.97234
9chu/LuaSTGPlus
1,867
src/v2/Asset/HgeFontAssetFactory.cpp
/** * @file * @date 2022/7/13 * @author 9chu * 此文件为 LuaSTGPlus 项目的一部分,版权与许可声明详见 COPYRIGHT.txt。 */ #include <lstg/v2/Asset/HgeFontAssetFactory.hpp> #include <lstg/Core/Text/JsonHelper.hpp> #include <lstg/Core/Subsystem/Asset/AssetError.hpp> #include <lstg/v2/Asset/HgeFontAsset.hpp> #include <lstg/v2/Asset/HgeFontAssetLoader.hpp> using namespace std; using namespace lstg; using namespace lstg::v2::Asset; using namespace lstg::Text; HgeFontAssetFactory::HgeFontAssetFactory() { m_pHGEFontFactory = Subsystem::Render::Font::CreateHgeFontFactory(); } std::string_view HgeFontAssetFactory::GetAssetTypeName() const noexcept { return "HgeFont"; } Subsystem::Asset::AssetTypeId HgeFontAssetFactory::GetAssetTypeId() const noexcept { return HgeFontAsset::GetAssetTypeIdStatic(); } Result<Subsystem::Asset::CreateAssetResult> HgeFontAssetFactory::CreateAsset(Subsystem::AssetSystem& assetSystem, Subsystem::Asset::AssetPoolPtr pool, std::string_view name, const nlohmann::json& arguments, Subsystem::Asset::IAssetDependencyResolver* resolver) noexcept { auto path = JsonHelper::ReadValue<string>(arguments, "/path"); auto mipmaps = JsonHelper::ReadValue<bool>(arguments, "/mipmaps", true); if (!path) return make_error_code(Subsystem::Asset::AssetError::MissingRequiredArgument); try { auto asset = make_shared<HgeFontAsset>(std::string{name}, std::move(*path), mipmaps); auto loader = make_shared<HgeFontAssetLoader>(asset, m_pHGEFontFactory); return Subsystem::Asset::CreateAssetResult { static_pointer_cast<Subsystem::Asset::Asset>(asset), static_pointer_cast<Subsystem::Asset::AssetLoader>(loader) }; } catch (const std::system_error& ex) { return ex.code(); } catch (...) { return make_error_code(errc::not_enough_memory); } }
1
0.917241
1
0.917241
game-dev
MEDIA
0.513996
game-dev
0.549645
1
0.549645
PotRooms/StarResonanceData
1,909
lua/level/scene_1403.lua
local Scene = {} function Scene:InitScene(sceneId) self:InitEvents() end function Scene:LoadComplete() end Scene.Seasons = {} function Scene:InitEvents() self.EventItems = {} self.EventItems[67] = { eventType = E.LevelEventType.OnZoneEnterClient, enable = true, group = 0, eventId = 67, count = -1, entity = {actorType = 5, tableUid = 188}, action = function(localSelf, isGroup, groupId, zoneEntId, entity) Panda.ZGame.ZEventParser.WeatherCtrlClient(false, 6) end } self.EventItems[53] = { eventType = E.LevelEventType.OnSceneLeave, enable = true, group = 0, eventId = 53, count = -1, action = function(localSelf) Panda.ZGame.CameraManager.Instance:CameraInvoke(0, true, {2032}, false) Panda.ZGame.CameraManager.Instance:SwitchCameraTemplate({0}, {2030}, -1) end } self.EventItems[102182] = { eventType = E.LevelEventType.OnZoneEnterClient, enable = true, group = 0, eventId = 102182, count = -1, entity = {actorType = 5, tableUid = 104126}, action = function(localSelf, isGroup, groupId, zoneEntId, entity) Panda.ZGame.ZEventParser.WeatherCtrlClient(false, 0) end } self.EventItems[102120] = { eventType = E.LevelEventType.OnZoneEnterClient, enable = true, group = 0, eventId = 102120, count = -1, entity = {actorType = 5, tableUid = 103933}, action = function(localSelf, isGroup, groupId, zoneEntId, entity) Panda.ZGame.ZEventParser.WeatherCtrlClient(false, 4) end } self.EventItems[102121] = { eventType = E.LevelEventType.OnZoneEnterClient, enable = true, group = 0, eventId = 102121, count = -1, entity = {actorType = 5, tableUid = 103934}, action = function(localSelf, isGroup, groupId, zoneEntId, entity) Panda.ZGame.ZEventParser.WeatherCtrlClient(false, 5) end } end return Scene
1
0.757048
1
0.757048
game-dev
MEDIA
0.967911
game-dev
0.794117
1
0.794117
kurapica/PLoop
11,082
System/IO/Resource/IResourceManager.lua
--===========================================================================-- -- -- -- System.IO.Resource.IResourceManager -- -- -- --===========================================================================-- --===========================================================================-- -- Author : kurapica125@outlook.com -- -- URL : http://github.com/kurapica/PLoop -- -- Create Date : 2018/04/01 -- -- Update Date : 2018/04/01 -- -- Version : 1.0.0 -- --===========================================================================-- PLoop(function(_ENV) --- Represents the interface of resource manager __Sealed__() __AnonymousClass__() interface "System.IO.Resource.IResourceManager" (function(_ENV) export { tostring = tostring, rawget = rawget, safeset = Toolset.safeset, pairs = pairs, Trace = Logger.Default[Logger.LogLevel.Trace], Debug = Logger.Default[Logger.LogLevel.Debug], existfile = IO.File.Exist, loadresource = IO.Resource.IResourceLoader.LoadResource, isanonymous = Namespace.IsAnonymousNamespace, IResourceManager, } local _ResourcePathMap = {} local _ResourceMapInfo = {} local preparepath = pcall(_G.require, [[PLoop.System.IO.Resource.casesensitivetest]]) and string.lower or function(path) return path end ----------------------------------------------------------------------- -- LoadFileInfo -- ----------------------------------------------------------------------- --- the loaded resource info __NoRawSet__(false) __NoNilValue__(false) local LoadFileInfo = class { AddRelatedPath = function (self, info) if self.reloadWhenModified then self.relativeFiles = self.relativeFiles or {} self.relativeFiles[info] = true info.notifyFileInfo = safeset(info.notifyFileInfo or {}, self, true) info.notifyFileInfo = info.notifyFileInfo or {} info.notifyFileInfo[self] = true end end; CheckReload = function (self) local path = self.resourcePath local requireReload = self.requireReLoad Trace("[System.IO.Resource][CheckReload] %s - %s", path, tostring(requireReload)) -- Check the file if not requireReload then if not self.resource then if existfile(path) then Trace("[System.IO.Resource][CheckReload] Reload because File existed") requireReload = true end else local lastWriteTime = IResourceManager.Manager.GetLastWriteTime(path) if not lastWriteTime then if not existfile(path) then Trace("[System.IO.Resource][CheckReload] Reload because File not existed") requireReload = true else Trace("[System.IO.Resource][CheckReload] Can't get changed status of the file") end elseif lastWriteTime ~= self.lastWriteTime then Trace("[System.IO.Resource][CheckReload] Reload because File changed at %s", lastWriteTime) requireReload = true else Trace("[System.IO.Resource][CheckReload] no file modified") end end end -- Check the required files if not requireReload and self.relativeFiles then for info in pairs(self.relativeFiles) do info:Load() end end Trace("[System.IO.Resource][CheckReload] Result %s", tostring(requireReload or self.requireReLoad)) -- the requireReLoad maybe changed by required files return requireReload or self.requireReLoad end; LoadFile = function (self, env) local path = self.resourcePath local ok, res if self.resource then res = loadresource(path, nil, env, true) if not res then res = self.resource else Debug("[System.IO.Resource][ReGenerate] %s [For] %s", tostring(res), path) if res then self.lastWriteTime = IResourceManager.Manager.GetLastWriteTime(path) end end else res = loadresource(path, nil, env, false) Debug("[System.IO.Resource][Generate] %s [For] %s", tostring(res), path) if res then self.lastWriteTime = IResourceManager.Manager.GetLastWriteTime(path) end end self.requireReLoad = false return res end; Load = function (self, env) local res = self.resource if res ~= nil and self.reloadWhenModified and self:CheckReload() then self.requireReLoad = false res = nil end if not res then res = self:LoadFile(env) if res ~= self.resource then -- notify the other files if self.resource and self.notifyFileInfo then for info in pairs(self.notifyFileInfo) do if info.resource then info.requireReLoad = true end end end if res then _ResourceMapInfo = safeset(_ResourceMapInfo, res, self) end self.resource = res end end return res end; __new = function (_, path) return { resource = false, resourcePath = path, relativeFiles = false, notifyFileInfo = false, requireReLoad = false, lastWriteTime = false, reloadWhenModified = IResourceManager.ReloadWhenModified, }, true end; __ctor = function (self) _ResourcePathMap = safeset(_ResourcePathMap, self.resourcePath, self) end; } ----------------------------------------------------------------------- -- static property -- ----------------------------------------------------------------------- --- the unique resource manager __Static__() property "Manager" { type = IResourceManager, handler = function(self, new, old) if old then old:Dispose() end end, default = function() return IResourceManager() end } --- whether reload the file when modified __Static__() property "ReloadWhenModified" { type = Boolean } ----------------------------------------------------------------------- -- static method -- ----------------------------------------------------------------------- --- Load the resource -- @param context the http context -- @param path the resource path -- @param env the environment to load the file __Static__() function LoadResource(path, env) path = preparepath(path) local info = _ResourcePathMap[path] or LoadFileInfo(path) return info:Load(env) end --- Get the resource's path -- @param resource the resource -- @return path the resource's file path __Static__() function GetResourcePath(res) return _ResourceMapInfo[res] and _ResourceMapInfo[res].resourcePath end --- Add a related path to the resource path for reload checking -- @param path the resource path -- @param relative the relative path __Static__() function AddRelatedPath(path, relative) path = preparepath(path) relative = preparepath(relative) local info = _ResourcePathMap[path] or LoadFileInfo(path) local rela = _ResourcePathMap[relative] or LoadFileInfo(relative) info:AddRelatedPath(rela) end --- Mark the path reload when modified __Static__() function SetReloadWhenModified(path, flag) path = preparepath(path) local info = _ResourcePathMap[path] or LoadFileInfo(path) info.reloadWhenModified = (flag ~= false) end ----------------------------------------------------------------------- -- method -- ----------------------------------------------------------------------- --- Get the resource last modified time __Abstract__() GetLastWriteTime = IO.File.GetLastWriteTime ----------------------------------------------------------------------- -- initializer -- ----------------------------------------------------------------------- function __init(self) IResourceManager.Manager = self end end) end)
1
0.964779
1
0.964779
game-dev
MEDIA
0.320545
game-dev
0.956712
1
0.956712
deavid/unhaunter
20,962
unplayer/src/systems/waypoint.rs
use bevy::{prelude::*, window::PrimaryWindow}; use uncore::{ behavior::{Behavior, component::Interactive, component::Stairs}, components::{ board::{PERSPECTIVE_X, PERSPECTIVE_Y, PERSPECTIVE_Z, position::Position}, game::{GCameraArena, GameSprite}, player_sprite::PlayerSprite, waypoint::{Waypoint, WaypointOwner, WaypointQueue, WaypointType}, }, events::roomchanged::{InteractionExecutionType, RoomChangedEvent}, resources::{ board_data::BoardData, mouse_visibility::MouseVisibility, player_input::PlayerInput, visibility_data::VisibilityData, }, }; use unstd::systemparam::interactivestuff::InteractiveStuff; use super::pathfinding::{detect_stair_area, find_path, find_path_to_interactive}; /// System that creates waypoint entities when the player clicks. /// Handles both interactive objects (via picking) and ground clicks (via raw mouse input). /// Only allows clicks on interactive entities that are on the same floor as the player. pub fn waypoint_creation_system( mut commands: Commands, q_window: Query<&Window, With<PrimaryWindow>>, q_camera: Query<(&Camera, &GlobalTransform), With<GCameraArena>>, q_player: Query<(Entity, &Position), With<PlayerSprite>>, mut q_player_queue: Query<&mut WaypointQueue, With<PlayerSprite>>, q_existing_waypoints: Query<Entity, (With<Waypoint>, With<WaypointOwner>)>, q_interactives: Query<( Entity, &Position, &Interactive, &Behavior, Option<&uncore::behavior::component::RoomState>, )>, q_stairs: Query<(Entity, &Position, &Stairs, &Behavior)>, mut click_events: EventReader<bevy::picking::events::Pointer<bevy::picking::events::Click>>, mouse: Res<ButtonInput<MouseButton>>, mouse_visibility: Res<MouseVisibility>, board_data: Res<BoardData>, visibility_data: Res<VisibilityData>, ) { // Only process clicks when mouse is visible if !mouse_visibility.is_visible { return; } let Ok((player_entity, player_pos)) = q_player.single() else { return; }; let Ok(mut waypoint_queue) = q_player_queue.single_mut() else { return; }; // Find the active player's position and floor let player_floor = player_pos.z.round() as i32; // Track if any interactive object was clicked via picking events let mut interactive_clicked = false; // First, handle picking events for interactive objects for click_event in click_events.read() { // Only handle left clicks if click_event.button != PointerButton::Primary { continue; } // Check if clicked on an interactive entity if let Ok((interactive_entity, interactive_pos, _interactive, _behavior, _room_state)) = q_interactives.get(click_event.target) { let interactive_floor = interactive_pos.z.round() as i32; // Only allow clicks on interactives that are on the same floor as the player if interactive_floor != player_floor { debug!( "waypoint_creation_system: Ignoring click on interactive entity {:?} - player on floor {}, interactive on floor {}", interactive_entity, player_floor, interactive_floor ); continue; // Skip this click } debug!( "waypoint_creation_system: Creating waypoint to interactive entity {:?} on floor {}", interactive_entity, interactive_floor ); // Clear existing waypoints when creating new ones clear_player_waypoints( &mut commands, &q_existing_waypoints, player_entity, &mut waypoint_queue, ); // Check if we're close enough to interact directly const INTERACTION_DISTANCE: f32 = 1.2; let distance = player_pos.distance(interactive_pos); if distance <= INTERACTION_DISTANCE { // Close enough - create direct interaction waypoint create_interaction_waypoint( &mut commands, player_entity, *interactive_pos, interactive_entity, &mut waypoint_queue, ); } else { // Too far - use pathfinding to get close, then create interaction waypoint create_pathfinding_waypoints_to_interaction( &mut commands, &q_existing_waypoints, player_entity, *player_pos, *interactive_pos, interactive_entity, &mut waypoint_queue, &board_data, &visibility_data, ); } interactive_clicked = true; } } // If no interactive was clicked, check for ground clicks via raw mouse input if !interactive_clicked && mouse.just_pressed(MouseButton::Left) { let Ok(window) = q_window.single() else { return; }; let Some(cursor_pos) = window.cursor_position() else { return; }; let Ok((camera, camera_transform)) = q_camera.single() else { return; }; // Convert cursor position to world coordinates if let Some(target) = screen_to_world_coords(cursor_pos, player_pos.z, camera, camera_transform) { debug!("Ground click detected at {:?}", target); // First check if the click is in a stairs area if let Some(( _stair_entity, _stair_pos, _stair_component, _behavior, start_waypoint, end_waypoint, )) = detect_stair_area(target, &q_stairs) { debug!( "Stair area detected! Creating waypoints from {:?} to {:?}", start_waypoint, end_waypoint ); // Create stair traversal waypoints create_stair_waypoints( &mut commands, &q_existing_waypoints, player_entity, start_waypoint, end_waypoint, &mut waypoint_queue, ); } else { // Use pathfinding to create a sequence of waypoints create_pathfinding_waypoints( &mut commands, &q_existing_waypoints, player_entity, *player_pos, target, &mut waypoint_queue, &board_data, &visibility_data, ); } } } } /// System that makes the player follow waypoints. /// Replaces the old click-to-move update system. pub fn waypoint_following_system( mut commands: Commands, q_player: Query<(Entity, &Position, &WaypointQueue), With<PlayerSprite>>, q_waypoints: Query<(&Position, &Waypoint), (With<WaypointOwner>, Without<PlayerSprite>)>, q_interactives: Query<( Entity, &Position, &Interactive, &Behavior, Option<&uncore::behavior::component::RoomState>, )>, mut player_input: ResMut<PlayerInput>, mut interactive_stuff: InteractiveStuff, mut ev_room: EventWriter<RoomChangedEvent>, ) { for (player_entity, player_pos, waypoint_queue) in q_player.iter() { if let Some(current_waypoint_entity) = waypoint_queue.next() { if let Ok((waypoint_pos, waypoint)) = q_waypoints.get(current_waypoint_entity) { let current = Vec2::new(player_pos.x, player_pos.y); let target = Vec2::new(waypoint_pos.x, waypoint_pos.y); let to_target = target - current; const ARRIVAL_THRESHOLD: f32 = 0.1; const INTERACTION_DISTANCE: f32 = 1.2; // Check if we should handle the waypoint action let should_complete_waypoint = match &waypoint.waypoint_type { WaypointType::MoveTo => { // For movement waypoints, complete when we reach the position to_target.length_squared() <= ARRIVAL_THRESHOLD * ARRIVAL_THRESHOLD } WaypointType::Interact(interaction_target) => { // For interaction waypoints, try to interact as soon as we're close enough if let Ok((_, interactive_pos, interactive, behavior, room_state)) = q_interactives.get(*interaction_target) { let distance = player_pos.distance(interactive_pos); if distance <= INTERACTION_DISTANCE { // Execute the interaction if interactive_stuff.execute_interaction( *interaction_target, interactive_pos, Some(interactive), behavior, room_state, InteractionExecutionType::ChangeState, ) { ev_room.write(RoomChangedEvent::default()); } true // Complete the waypoint after interaction } else { // Still too far, keep moving false } } else { // Target entity no longer exists, complete waypoint true } } }; if should_complete_waypoint { // Complete waypoint and stop moving player_input.movement = Vec2::ZERO; complete_waypoint(&mut commands, player_entity, current_waypoint_entity); } else { // Continue moving towards waypoint player_input.movement = to_target.normalize(); } } else { // Waypoint entity no longer exists, remove it from queue complete_waypoint(&mut commands, player_entity, current_waypoint_entity); } } } } /// Helper function to clear all waypoints belonging to a player fn clear_player_waypoints( commands: &mut Commands, q_existing_waypoints: &Query<Entity, (With<Waypoint>, With<WaypointOwner>)>, _player_entity: Entity, waypoint_queue: &mut WaypointQueue, ) { // Despawn all waypoint entities belonging to this player for waypoint_entity in &waypoint_queue.0 { if q_existing_waypoints.contains(*waypoint_entity) { commands.entity(*waypoint_entity).despawn(); } } waypoint_queue.clear(); } /// Helper function to create an interaction waypoint fn create_interaction_waypoint( commands: &mut Commands, player_entity: Entity, position: Position, interaction_target: Entity, waypoint_queue: &mut WaypointQueue, ) { let waypoint_entity = commands .spawn(Sprite { color: Color::srgba(1.0, 1.0, 0.0, 0.6), // Yellow for interaction waypoints custom_size: Some(Vec2::new(1.0, 1.0)), ..default() }) .insert(position) .insert(GameSprite) .insert(Waypoint { waypoint_type: WaypointType::Interact(interaction_target), order: 0, }) .insert(WaypointOwner(player_entity)) .id(); waypoint_queue.push(waypoint_entity); } /// Helper function to create a move-to waypoint pub fn create_move_waypoint( commands: &mut Commands, player_entity: Entity, position: Position, waypoint_queue: &mut WaypointQueue, ) { let waypoint_entity = commands .spawn(Sprite { color: Color::srgba(1.0, 0.0, 0.6, 0.8), // Red for move waypoints custom_size: Some(Vec2::new(1.0, 1.0)), ..default() }) .insert(position) .insert(GameSprite) .insert(Waypoint { waypoint_type: WaypointType::MoveTo, order: 0, }) .insert(WaypointOwner(player_entity)) .id(); waypoint_queue.push(waypoint_entity); } /// Helper function to complete a waypoint (remove it and advance queue) fn complete_waypoint(commands: &mut Commands, _player_entity: Entity, waypoint_entity: Entity) { // Despawn the waypoint entity commands.entity(waypoint_entity).despawn(); // Remove from player's queue (will be handled by queue management system) // For now we'll update it in the next system run } /// System that cleans up waypoint queues by removing despawned waypoint entities pub fn waypoint_queue_cleanup_system( mut q_player_queue: Query<&mut WaypointQueue, With<PlayerSprite>>, q_waypoints: Query<Entity, With<Waypoint>>, ) { for mut waypoint_queue in q_player_queue.iter_mut() { // Remove any waypoint entities that no longer exist waypoint_queue .0 .retain(|&waypoint_entity| q_waypoints.contains(waypoint_entity)); } } /// Converts screen coordinates to world coordinates using the game's isometric projection. fn screen_to_world_coords( screen_pos: Vec2, target_z: f32, camera: &Camera, camera_transform: &GlobalTransform, ) -> Option<Position> { // Get the world position on the camera's near plane using Bevy's built-in conversion let world_pos_on_near_plane = camera .viewport_to_world_2d(camera_transform, screen_pos) .ok()?; // Calculate the determinant of the 2x2 isometric projection matrix let det = PERSPECTIVE_X[0] * PERSPECTIVE_Y[1] - PERSPECTIVE_Y[0] * PERSPECTIVE_X[1]; if det.abs() < 1e-6 { return None; // Matrix is not invertible } let inv_det = 1.0 / det; // Adjust screen coordinates by removing the Z-level contribution let b_x = world_pos_on_near_plane.x - target_z * PERSPECTIVE_Z[0]; let b_y = world_pos_on_near_plane.y - target_z * PERSPECTIVE_Z[1]; // Apply the inverse transformation matrix to find world X and Y coordinates let world_x = inv_det * (b_x * PERSPECTIVE_Y[1] - PERSPECTIVE_Y[0] * b_y); let world_y = inv_det * (PERSPECTIVE_X[0] * b_y - b_x * PERSPECTIVE_X[1]); Some(Position { x: world_x, y: world_y, z: target_z, global_z: 0.0, }) } /// Helper function to create waypoints using pathfinding fn create_pathfinding_waypoints( commands: &mut Commands, q_existing_waypoints: &Query<Entity, (With<Waypoint>, With<WaypointOwner>)>, player_entity: Entity, start_pos: Position, target_pos: Position, waypoint_queue: &mut WaypointQueue, board_data: &BoardData, visibility_data: &VisibilityData, ) { // Clear existing waypoints first clear_player_waypoints( commands, q_existing_waypoints, player_entity, waypoint_queue, ); // Use pathfinding to get a sequence of board positions let path = find_path(start_pos, target_pos, board_data, visibility_data); if path.is_empty() { debug!("No path found from {:?} to {:?}", start_pos, target_pos); return; } // Skip the first position (current player position) and create waypoints for the rest for (i, board_pos) in path.iter().skip(1).enumerate() { let world_pos = board_pos.to_position(); let waypoint_entity = commands .spawn(Sprite { color: Color::srgba(1.0, 0.0, 0.6, 0.8), // Red for move waypoints custom_size: Some(Vec2::new(1.0, 1.0)), ..default() }) .insert(world_pos) .insert(GameSprite) .insert(Waypoint { waypoint_type: WaypointType::MoveTo, order: i as u32, }) .insert(WaypointOwner(player_entity)) .id(); waypoint_queue.push(waypoint_entity); } debug!("Created {} waypoints for pathfinding", path.len() - 1); } /// Helper function to create waypoints using pathfinding that end with an interaction fn create_pathfinding_waypoints_to_interaction( commands: &mut Commands, q_existing_waypoints: &Query<Entity, (With<Waypoint>, With<WaypointOwner>)>, player_entity: Entity, start_pos: Position, target_pos: Position, interaction_target: Entity, waypoint_queue: &mut WaypointQueue, board_data: &BoardData, visibility_data: &VisibilityData, ) { // Clear existing waypoints first clear_player_waypoints( commands, q_existing_waypoints, player_entity, waypoint_queue, ); // Use pathfinding to get a sequence of board positions (treating target as walkable) let path = find_path_to_interactive(start_pos, target_pos, board_data, visibility_data); if path.is_empty() { debug!("No path found from {:?} to {:?}", start_pos, target_pos); // If no path, create direct interaction waypoint as fallback create_interaction_waypoint( commands, player_entity, target_pos, interaction_target, waypoint_queue, ); return; } // Create movement waypoints for all but the last position let path_len = path.len(); for (i, board_pos) in path.iter().skip(1).enumerate() { // If this is the last waypoint, create an interaction waypoint instead if i == path_len - 2 { // Last iteration (path_len - 1 because we skip(1)) create_interaction_waypoint( commands, player_entity, target_pos, interaction_target, waypoint_queue, ); } else { // Create regular movement waypoint let world_pos = board_pos.to_position(); let waypoint_entity = commands .spawn(Sprite { color: Color::srgba(1.0, 0.0, 0.6, 0.8), // Red for move waypoints custom_size: Some(Vec2::new(1.0, 1.0)), ..default() }) .insert(world_pos) .insert(GameSprite) .insert(Waypoint { waypoint_type: WaypointType::MoveTo, order: i as u32, }) .insert(WaypointOwner(player_entity)) .id(); waypoint_queue.push(waypoint_entity); } } debug!( "Created {} waypoints for pathfinding to interaction", path_len - 1 ); } /// Helper function to create waypoints for stair traversal fn create_stair_waypoints( commands: &mut Commands, q_existing_waypoints: &Query<Entity, (With<Waypoint>, With<WaypointOwner>)>, player_entity: Entity, start_waypoint: Position, end_waypoint: Position, waypoint_queue: &mut WaypointQueue, ) { // Clear existing waypoints first clear_player_waypoints( commands, q_existing_waypoints, player_entity, waypoint_queue, ); debug!( "Creating stair waypoints from {:?} to {:?}", start_waypoint, end_waypoint ); // Create start waypoint (on current floor) let start_waypoint_entity = commands .spawn(Sprite { color: Color::srgba(0.0, 1.0, 1.0, 0.8), // Cyan for stair start custom_size: Some(Vec2::new(1.0, 1.0)), ..default() }) .insert(start_waypoint) .insert(GameSprite) .insert(Waypoint { waypoint_type: WaypointType::MoveTo, order: 0, }) .insert(WaypointOwner(player_entity)) .id(); waypoint_queue.push(start_waypoint_entity); // Create end waypoint (on destination floor) let end_waypoint_entity = commands .spawn(Sprite { color: Color::srgba(1.0, 1.0, 0.0, 0.8), // Yellow for stair end custom_size: Some(Vec2::new(1.0, 1.0)), ..default() }) .insert(end_waypoint) .insert(GameSprite) .insert(Waypoint { waypoint_type: WaypointType::MoveTo, order: 1, }) .insert(WaypointOwner(player_entity)) .id(); waypoint_queue.push(end_waypoint_entity); debug!("Created 2 waypoints for stair traversal"); }
1
0.929274
1
0.929274
game-dev
MEDIA
0.692092
game-dev
0.820288
1
0.820288
StrongHold/runescape-667
55,818
runescape/src/main/java/LoginManager.java
import com.jagex.Client; import com.jagex.LoginProt; import com.jagex.ServerProt; import com.jagex.StockmarketOffer; import com.jagex.core.constants.LoginResponseCode; import com.jagex.core.constants.LoginStep; import com.jagex.core.constants.MainLogicStep; import com.jagex.core.constants.ModeWhere; import com.jagex.core.crypto.Isaac; import com.jagex.core.datastruct.key.Deque; import com.jagex.core.datastruct.key.IterableHashTable; import com.jagex.core.io.BitPacket; import com.jagex.core.io.ConnectionInfo; import com.jagex.core.io.Packet; import com.jagex.core.io.connection.Connection; import com.jagex.core.stringtools.general.Base37; import com.jagex.core.util.JavaScript; import com.jagex.core.util.SystemTimer; import com.jagex.game.DelayedStateChange; import com.jagex.game.LocalisedText; import com.jagex.game.camera.CameraMode; import com.jagex.game.runetek6.client.GameShell; import com.jagex.game.runetek6.config.iftype.SubInterface; import com.jagex.game.runetek6.config.loctype.LocType; import com.jagex.game.runetek6.config.loctype.LocTypeList; import com.jagex.game.runetek6.config.npctype.NPCType; import com.jagex.game.runetek6.config.npctype.NPCTypeList; import com.jagex.game.runetek6.config.objtype.ObjType; import com.jagex.game.runetek6.config.objtype.ObjTypeList; import com.jagex.game.runetek6.config.vartype.TimedVarDomain; import com.jagex.graphics.ToolkitType; import com.jagex.js5.js5; import com.jagex.sign.SignedResourceStatus; import org.openrs2.deob.annotation.OriginalArg; import org.openrs2.deob.annotation.OriginalMember; import org.openrs2.deob.annotation.Pc; import rs2.client.loading.library.LibraryManager; import rs2.client.web.ClientURLTools; import rs2.client.web.OpenUrlType; import java.io.IOException; import java.math.BigInteger; import java.net.Socket; import java.net.URL; public final class LoginManager { private static final int TYPE_LOBBY = 1; private static final int TYPE_GAME = 2; @OriginalMember(owner = "client!rw", name = "B", descriptor = "J") public static final long clientSessionKey = (long) (Math.random() * 9.999999999E9D); @OriginalMember(owner = "client!ee", name = "M", descriptor = "I") public static int step = LoginStep.DELAY; @OriginalMember(owner = "client!iu", name = "b", descriptor = "I") public static int lobbyLoginResponse = LoginResponseCode.DEFAULT; @OriginalMember(owner = "client!fe", name = "p", descriptor = "I") public static int gameLoginResponse = LoginResponseCode.DEFAULT; @OriginalMember(owner = "client!or", name = "Z", descriptor = "I") public static int anInt7113 = -1; @OriginalMember(owner = "client!bv", name = "l", descriptor = "Ljava/lang/String;") public static String password = ""; @OriginalMember(owner = "client!od", name = "d", descriptor = "Ljava/lang/String;") public static String username = ""; @OriginalMember(owner = "client!eaa", name = "o", descriptor = "I") public static int socialNetworkId = -1; @OriginalMember(owner = "client!kba", name = "P", descriptor = "Ljava/lang/String;") public static String previousUsername = ""; @OriginalMember(owner = "client!cja", name = "l", descriptor = "I") public static int pendingResponse; @OriginalMember(owner = "client!nja", name = "N", descriptor = "J") public static long ssoKey = 0L; @OriginalMember(owner = "client!cha", name = "h", descriptor = "I") public static int errors = 0; @OriginalMember(owner = "client!jia", name = "a", descriptor = "I") public static int type; @OriginalMember(owner = "client!kha", name = "m", descriptor = "I") public static int ticks = 0; @OriginalMember(owner = "client!js", name = "P", descriptor = "Z") public static boolean socialNetworkLogin = false; @OriginalMember(owner = "client!lp", name = "b", descriptor = "Ljava/math/BigInteger;") public static BigInteger RSA_MODULUS = new BigInteger("a76cba054be8a8cb683bf47c5e5b4950b60647f74da5ea7d87f0ba7d24bb6580dec4809afa07e26db0d0c88ca41bdb697fc6ae0def8afc0bacd841bb57fb8851", 16); @OriginalMember(owner = "client!ica", name = "j", descriptor = "Ljava/math/BigInteger;") public static BigInteger RSA_EXPONENT = new BigInteger("10001", 16); @OriginalMember(owner = "client!dm", name = "h", descriptor = "I") public static int profileTransferTicks = 0; @OriginalMember(owner = "client!kh", name = "hb", descriptor = "I") public static int disallowResult = -1; @OriginalMember(owner = "client!le", name = "i", descriptor = "I") public static int disallowTrigger = -1; @OriginalMember(owner = "client!cv", name = "k", descriptor = "I") public static int okLength; @OriginalMember(owner = "client!rla", name = "c", descriptor = "Z") public static boolean aBoolean640 = false; @OriginalMember(owner = "client!cj", name = "o", descriptor = "I") public static int lastGameLoginResponse = -2; @OriginalMember(owner = "client!vf", name = "F", descriptor = "I") public static int lastDisallowTrigger = -1; @OriginalMember(owner = "client!ma", name = "o", descriptor = "I") public static int lastDisallowResult = -1; @OriginalMember(owner = "client!wo", name = "x", descriptor = "Z") public static boolean reconnectToPrevious; @OriginalMember(owner = "client!uu", name = "q", descriptor = "I") public static int positionInQueue = 0; @OriginalMember(owner = "client!he", name = "a", descriptor = "(IZ)V") public static void logout(@OriginalArg(1) boolean toLobby) { @Pc(12) ServerConnection[] connections = ServerConnection.VALUES; for (@Pc(14) int i = 0; i < connections.length; i++) { @Pc(19) ServerConnection connection = connections[i]; connection.close(); } reset(); client.cacheReset(); Static563.method7461(); for (@Pc(36) int level = 0; level < 4; level++) { Client.collisionMaps[level].reset(); } WorldMap.reset(false); System.gc(); SongManager.stop(); SongManager.playing = -1; Static501.aBoolean575 = false; AudioRenderer.mixBussReset(); SoundManager.removeActiveStreams(true); WorldMap.resetoreToolkit(); WorldMap.resetDisabledElements(); Static187.method2842(); if (toLobby) { MainLogicManager.setStep(MainLogicStep.STEP_LOGGING_IN_FROM_GAMESCREEN_TO_LOBBY); } else { MainLogicManager.setStep(MainLogicStep.STEP_LOGIN_SCREEN); try { JavaScript.call("loggedout", GameShell.loaderApplet); } catch (@Pc(86) Throwable ignored) { /* empty */ } } } @OriginalMember(owner = "client!eo", name = "a", descriptor = "(III)V") public static void requestLoginFromSocialNetwork(@OriginalArg(0) int socialNetworkId, @OriginalArg(1) int anInt7113) { if (!isAtLoginScreen()) { return; } LoginManager.anInt7113 = anInt7113; if (LoginManager.socialNetworkId != socialNetworkId) { previousUsername = ""; } LoginManager.socialNetworkId = socialNetworkId; MainLogicManager.setStep(MainLogicStep.STEP_LOGGING_IN_FROM_LOGINSCREEN_TO_GAME); } @OriginalMember(owner = "client!bt", name = "a", descriptor = "(ILjava/lang/String;Ljava/lang/String;I)V") public static void requestLoginWithUsername(@OriginalArg(0) int anInt7113, @OriginalArg(1) String password, @OriginalArg(2) String username) { if (username.length() > 320 || !isAtLoginScreen()) { return; } resetSocialNetwork(); LoginManager.anInt7113 = anInt7113; LoginManager.password = password; LoginManager.username = username; MainLogicManager.setStep(MainLogicStep.STEP_LOGGING_IN_FROM_LOGINSCREEN_TO_GAME); } @OriginalMember(owner = "client!wg", name = "a", descriptor = "(B)V") public static void reset() { lobbyLoginResponse = LoginResponseCode.DEFAULT; gameLoginResponse = LoginResponseCode.DEFAULT; step = LoginStep.DELAY; } @OriginalMember(owner = "client!or", name = "a", descriptor = "(Z)Z") public static boolean isAtLoginScreen() { if (MainLogicManager.step == MainLogicStep.STEP_LOGIN_SCREEN) { return step == LoginStep.DELAY && LobbyManager.step == LoginStep.DELAY; } else { return false; } } @OriginalMember(owner = "client!lk", name = "a", descriptor = "(B)V") public static void resetSocialNetwork() { socialNetworkId = -1; ssoKey = 0L; previousUsername = ""; } @OriginalMember(owner = "client!hj", name = "a", descriptor = "(I)Z") public static boolean inProgress() { return step != LoginStep.DELAY; } @OriginalMember(owner = "client!lia", name = "a", descriptor = "(B)V") public static void changeMainState() { if (step == LoginStep.DELAY || step == LoginStep.WAIT_FOR_VIDEO_ADVERTISEMENT) { return; } try { @Pc(25) short maxTicks; if (errors == 0) { maxTicks = 250; } else { maxTicks = 2000; } if (type != TYPE_GAME || step != LoginStep.WAIT_FOR_QUEUE_POSITION && gameLoginResponse != LoginResponseCode.IN_QUEUE) { ticks++; } if (socialNetworkLogin && step >= LoginStep.WAIT_FOR_SSO_KEY_RESPONSE) { maxTicks = 6000; } if (maxTicks < ticks) { ServerConnection.active.close(); if (errors >= 3) { step = LoginStep.DELAY; setLoginResponse(LoginResponseCode.CONNECTION_TIMED_OUT); return; } if (type == TYPE_GAME) { ConnectionInfo.login.rotateMethods(); } else { ConnectionInfo.lobby.rotateMethods(); } step = LoginStep.CONNECT; ticks = 0; errors++; } if (step == LoginStep.CONNECT) { if (type == TYPE_GAME) { ServerConnection.active.gameSocketRequest = ConnectionInfo.login.openSocket(GameShell.signLink); } else { ServerConnection.active.gameSocketRequest = ConnectionInfo.lobby.openSocket(GameShell.signLink); } step = LoginStep.WAIT_FOR_CONNECTION_ACK; } if (step == LoginStep.WAIT_FOR_CONNECTION_ACK) { if (ServerConnection.active.gameSocketRequest.status == SignedResourceStatus.ERROR) { throw new IOException(); } if (ServerConnection.active.gameSocketRequest.status != SignedResourceStatus.SUCCESS) { return; } ServerConnection.active.connection = Connection.create((Socket) ServerConnection.active.gameSocketRequest.result); ServerConnection.active.gameSocketRequest = null; ServerConnection.active.clear(); @Pc(186) ClientMessage message = ClientMessage.createRaw(); if (socialNetworkLogin) { message.bitPacket.p1(LoginProt.INIT_SOCIAL_NETWORK_CONNECTION.opcode); message.bitPacket.p2(0); @Pc(203) int pos = message.bitPacket.pos; message.bitPacket.p4(Client.BUILD); if (type == TYPE_GAME) { message.bitPacket.p1(MainLogicManager.step == MainLogicStep.STEP_RECONNECTING ? 1 : 0); } @Pc(229) Packet packet = Packet.createXtea(); packet.p1(socialNetworkId); packet.p2((int) (Math.random() * 9.9999999E7D)); packet.p1(Client.language); packet.p4(Client.affid); for (@Pc(250) int i = 0; i < 6; i++) { packet.p4((int) (Math.random() * 9.9999999E7D)); } packet.p8(clientSessionKey); packet.p1(Client.modeGame.id); packet.p1((int) (Math.random() * 9.9999999E7D)); packet.rsaenc(RSA_MODULUS, RSA_EXPONENT); message.bitPacket.pdata(packet.pos, packet.data, 0); message.bitPacket.psize2(message.bitPacket.pos - pos); } else { message.bitPacket.p1(LoginProt.INIT_GAME_CONNECTION.opcode); } ServerConnection.active.send(message); ServerConnection.active.flush(); step = LoginStep.SEND_LOGIN_REQUEST; } if (step == LoginStep.SEND_LOGIN_REQUEST) { if (!ServerConnection.active.connection.hasAvailable(1)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, 1, 0); @Pc(360) int responseCode = ServerConnection.active.bitPacket.data[0] & 0xFF; if (responseCode != LoginResponseCode.EXCHANGE_KEYS) { step = LoginStep.DELAY; setLoginResponse(responseCode); ServerConnection.active.close(); updateMainState(); return; } if (socialNetworkLogin) { step = LoginStep.WAIT_FOR_SOCIAL_NETWORK_TOKEN_LENGTH; } else { step = LoginStep.SEND_LOGIN_PACKET; } } if (step == LoginStep.WAIT_FOR_SOCIAL_NETWORK_TOKEN_LENGTH) { if (!ServerConnection.active.connection.hasAvailable(2)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, 2, 0); ServerConnection.active.bitPacket.pos = 0; ServerConnection.active.bitPacket.pos = ServerConnection.active.bitPacket.g2(); step = LoginStep.WAIT_FOR_SOCIAL_NETWORK_TOKEN; } if (step == LoginStep.WAIT_FOR_SOCIAL_NETWORK_TOKEN) { if (!ServerConnection.active.connection.hasAvailable(ServerConnection.active.bitPacket.pos)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, ServerConnection.active.bitPacket.pos, 0); ServerConnection.active.bitPacket.tinydec(Packet.xteaKey); ServerConnection.active.bitPacket.pos = 0; @Pc(465) String path = ServerConnection.active.bitPacket.gjstr2(); ServerConnection.active.bitPacket.pos = 0; @Pc(473) String function = "opensn"; if (!Client.js || ClientURLTools.openURL(GameShell.signLink, path, function, OpenUrlType.CALL).status == SignedResourceStatus.ERROR) { ClientURLTools.openURL(path, function, GameShell.signLink, ClientOptions.instance.toolkit.getValue() == ToolkitType.GL, true); } step = LoginStep.WAIT_FOR_SSO_KEY_RESPONSE; } if (step == LoginStep.WAIT_FOR_SSO_KEY_RESPONSE) { if (!ServerConnection.active.connection.hasAvailable(1)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, 1, 0); if ((ServerConnection.active.bitPacket.data[0] & 0xFF) == 1) { step = LoginStep.WAIT_FOR_SSO_KEY; } } if (step == LoginStep.WAIT_FOR_SSO_KEY) { if (!ServerConnection.active.connection.hasAvailable(16)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, 16, 0); ServerConnection.active.bitPacket.pos = 16; ServerConnection.active.bitPacket.tinydec(Packet.xteaKey); ServerConnection.active.bitPacket.pos = 0; username = previousUsername = Base37.decode(ServerConnection.active.bitPacket.g8()); ssoKey = ServerConnection.active.bitPacket.g8(); step = LoginStep.SEND_LOGIN_PACKET; } if (step == LoginStep.SEND_LOGIN_PACKET) { ServerConnection.active.bitPacket.pos = 0; ServerConnection.active.clear(); @Pc(186) ClientMessage message = ClientMessage.createRaw(); @Pc(618) BitPacket bitPacket = message.bitPacket; if (type == TYPE_GAME) { @Pc(627) LoginProt prot; if (socialNetworkLogin) { prot = LoginProt.SOCIAL_NETWORK_LOGIN; } else { prot = LoginProt.GAMELOGIN; } bitPacket.p1(prot.opcode); bitPacket.p2(0); @Pc(250) int startPos = bitPacket.pos; @Pc(646) int credentialsPos = bitPacket.pos; if (!socialNetworkLogin) { bitPacket.p4(Client.BUILD); bitPacket.p1(MainLogicManager.step == MainLogicStep.STEP_RECONNECTING ? 1 : 0); credentialsPos = bitPacket.pos; @Pc(672) Packet credentials = credentialsPacket(); bitPacket.pdata(credentials.pos, credentials.data, 0); credentialsPos = bitPacket.pos; bitPacket.pjstr(username); } bitPacket.p1(anInt7113); bitPacket.p1(InterfaceManager.getWindowMode()); bitPacket.p2(GameShell.canvasWid); bitPacket.p2(GameShell.canvasHei); bitPacket.p1(ClientOptions.instance.antialiasingQuality.getValue()); GameShell.pushUID192(bitPacket); bitPacket.pjstr(Client.settings); bitPacket.p4(Client.affid); @Pc(672) Packet clientOptions = ClientOptions.instance.encode(); bitPacket.p1(clientOptions.pos); bitPacket.pdata(clientOptions.pos, clientOptions.data, 0); Static503.sentPreferences = true; @Pc(748) Packet systemInfo = new Packet(SystemInfo.instance.size()); SystemInfo.instance.encode(systemInfo); bitPacket.pdata(systemInfo.data.length, systemInfo.data, 0); bitPacket.p4(VerifyId.getValue()); bitPacket.p8(Client.userFlow); bitPacket.p1(Client.additionalInfo != null ? 1 : 0); if (Client.additionalInfo != null) { bitPacket.pjstr(Client.additionalInfo); } bitPacket.p1(LibraryManager.isNativeLoaded("jagtheora") ? 1 : 0); bitPacket.p1(Client.js ? 1 : 0); bitPacket.p1(Client.hc ? 1 : 0); pushJs5Checksums(bitPacket); bitPacket.tinyenc(Packet.xteaKey, credentialsPos, bitPacket.pos); bitPacket.psize2(bitPacket.pos - startPos); } else { @Pc(627) LoginProt prot; if (socialNetworkLogin) { prot = LoginProt.SOCIAL_NETWORK_LOGIN; } else { prot = LoginProt.LOBBYLOGIN; } bitPacket.p1(prot.opcode); bitPacket.p2(0); @Pc(250) int startPos = bitPacket.pos; @Pc(646) int credentialsPos = bitPacket.pos; if (!socialNetworkLogin) { bitPacket.p4(Client.BUILD); @Pc(672) Packet credentials = credentialsPacket(); bitPacket.pdata(credentials.pos, credentials.data, 0); credentialsPos = bitPacket.pos; bitPacket.pjstr(username); } bitPacket.p1(Client.modeGame.id); bitPacket.p1(Client.language); GameShell.pushUID192(bitPacket); bitPacket.pjstr(Client.settings); bitPacket.p4(Client.affid); pushJs5Checksums(bitPacket); bitPacket.tinyenc(Packet.xteaKey, credentialsPos, bitPacket.pos); bitPacket.psize2(bitPacket.pos - startPos); } ServerConnection.active.send(message); ServerConnection.active.flush(); ServerConnection.active.isaac = new Isaac(Packet.xteaKey); for (@Pc(938) int i = 0; i < 4; i++) { Packet.xteaKey[i] += 50; } ServerConnection.active.bitPacket.initIsaac(Packet.xteaKey); Packet.xteaKey = null; step = LoginStep.WAIT_FOR_LOGIN_RESPONSE; } if (step == LoginStep.WAIT_FOR_LOGIN_RESPONSE) { if (!ServerConnection.active.connection.hasAvailable(1)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, 1, 0); @Pc(360) int responseCode = ServerConnection.active.bitPacket.data[0] & 0xFF; if (responseCode == LoginResponseCode.HOP_BLOCKED) { step = LoginStep.WAIT_FOR_HOP_BLOCK_DURATION; } else if (responseCode == LoginResponseCode.DISALLOWED_BY_SCRIPT || responseCode == LoginResponseCode.CANNOT_ENTER_INSTANCE) { step = LoginStep.WAIT_FOR_SCRIPT_DISALLOW_REASON; pendingResponse = responseCode; } else if (responseCode == LoginResponseCode.VIDEO_ADVERTISEMENT) { step = LoginStep.WAIT_FOR_VIDEO_ADVERTISEMENT; setLoginResponse(responseCode); return; } else if (responseCode == LoginResponseCode.OK) { step = LoginStep.WAIT_FOR_LOGIN_OK_LENGTH; } else if (responseCode == LoginResponseCode.RECONNECT_OK) { step = LoginStep.WAIT_FOR_LOGIN_RECONNECT; ServerConnection.active.currentPacketSize = -2; } else if (responseCode == LoginResponseCode.LOGIN_SERVER_NO_REPLY && errors < 3) { ticks = 0; step = LoginStep.CONNECT; errors++; ServerConnection.active.connection.close(); ServerConnection.active.connection = null; return; } else if (responseCode == LoginResponseCode.IN_QUEUE) { step = LoginStep.WAIT_FOR_QUEUE_POSITION; setLoginResponse(responseCode); return; } else if (!aBoolean640 || socialNetworkLogin || socialNetworkId == -1 || responseCode != LoginResponseCode.INVALID_SINGLE_SIGNON) { step = LoginStep.DELAY; setLoginResponse(responseCode); ServerConnection.active.connection.close(); ServerConnection.active.connection = null; updateMainState(); return; } else { socialNetworkLogin = true; step = LoginStep.CONNECT; ticks = 0; ServerConnection.active.connection.close(); ServerConnection.active.connection = null; return; } } if (step == LoginStep.VIDEO_ADVERTISEMENT_FINISHED) { ServerConnection.active.clear(); @Pc(186) ClientMessage message = ClientMessage.createRaw(); @Pc(618) BitPacket bitPacket = message.bitPacket; bitPacket.setIsaac(ServerConnection.active.isaac); bitPacket.startPacket(LoginProt.GAMELOGIN_CONTINUE.opcode); ServerConnection.active.send(message); ServerConnection.active.flush(); step = LoginStep.WAIT_FOR_LOGIN_RESPONSE; } else if (step == LoginStep.WAIT_FOR_HOP_BLOCK_DURATION) { if (!ServerConnection.active.connection.hasAvailable(1)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, 1, 0); @Pc(360) int seconds = ServerConnection.active.bitPacket.data[0] & 0xFF; step = LoginStep.DELAY; profileTransferTicks = seconds * 50; setLoginResponse(LoginResponseCode.HOP_BLOCKED); ServerConnection.active.connection.close(); ServerConnection.active.connection = null; updateMainState(); } else if (step == LoginStep.WAIT_FOR_QUEUE_POSITION) { if (!ServerConnection.active.connection.hasAvailable(2)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, 2, 0); positionInQueue = (ServerConnection.active.bitPacket.data[1] & 0xFF) + ((ServerConnection.active.bitPacket.data[0] & 0xFF) << 8); step = LoginStep.WAIT_FOR_LOGIN_RESPONSE; } else if (step == LoginStep.WAIT_FOR_SCRIPT_DISALLOW_REASON) { if (pendingResponse == LoginResponseCode.DISALLOWED_BY_SCRIPT) { if (!ServerConnection.active.connection.hasAvailable(1)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, 1, 0); disallowResult = ServerConnection.active.bitPacket.data[0] & 0xFF; } else if (pendingResponse == LoginResponseCode.CANNOT_ENTER_INSTANCE) { if (!ServerConnection.active.connection.hasAvailable(3)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, 3, 0); disallowTrigger = (ServerConnection.active.bitPacket.data[2] & 0xFF) + ((ServerConnection.active.bitPacket.data[1] & 0xFF) << 8); disallowResult = ServerConnection.active.bitPacket.data[0] & 0xFF; } else { throw new IllegalStateException("Login step 18 not valid for pendingResponse=" + pendingResponse); } step = LoginStep.DELAY; setLoginResponse(pendingResponse); ServerConnection.active.connection.close(); ServerConnection.active.connection = null; updateMainState(); } else if (step == LoginStep.WAIT_FOR_LOGIN_OK_LENGTH) { if (!ServerConnection.active.connection.hasAvailable(1)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, 1, 0); okLength = ServerConnection.active.bitPacket.data[0] & 0xFF; step = LoginStep.WAIT_FOR_LOGIN_DETAILS; } else { if (step == LoginStep.WAIT_FOR_LOGIN_DETAILS) { @Pc(1435) BitPacket bitPacket = ServerConnection.active.bitPacket; if (type == TYPE_GAME) { if (!ServerConnection.active.connection.hasAvailable(okLength)) { return; } ServerConnection.active.connection.read(bitPacket.data, okLength, 0); bitPacket.pos = 0; Client.staffModLevel = bitPacket.g1(); Static38.playerModLevel = bitPacket.g1(); UserDetail.underage = bitPacket.g1() == 1; UserDetail.parentalChatConsent = bitPacket.g1() == 1; Static298.parentalAdvertConsent = bitPacket.g1() == 1; Static617.quickChatWorld = bitPacket.g1() == 1; PlayerList.activePlayerSlot = bitPacket.g2(); Client.isMember = bitPacket.g1() == 1; UserDetail.dob = bitPacket.g3s(); Static174.mapMembers = bitPacket.g1() == 1; Static416.mapOwner = bitPacket.gjstr(); LocTypeList.instance.setAllowMembers(Static174.mapMembers); ObjTypeList.instance.setAllowMembers(Static174.mapMembers); NPCTypeList.instance.setAllowMembers(Static174.mapMembers); } else { if (!ServerConnection.active.connection.hasAvailable(okLength)) { return; } ServerConnection.active.connection.read(bitPacket.data, okLength, 0); bitPacket.pos = 0; Client.staffModLevel = bitPacket.g1(); Static38.playerModLevel = bitPacket.g1(); UserDetail.underage = bitPacket.g1() == 1; UserDetail.parentalChatConsent = bitPacket.g1() == 1; Static298.parentalAdvertConsent = bitPacket.g1() == 1; Static416.subscriptionExpiration = bitPacket.g8(); Static94.remainingSubscription = Static416.subscriptionExpiration - SystemTimer.safetime() - bitPacket.g5(); @Pc(203) int membershipInfo = bitPacket.g1(); Client.isMember = (membershipInfo & 0x1) != 0; UserDetail.activeSubscription = (membershipInfo & 0x2) != 0; UserDetail.lobbyJcoinsBalance = bitPacket.g4(); UserDetail.lobbyLoyalty = bitPacket.g1() == 1; UserDetail.lobbyLoyaltyBalance = bitPacket.g4(); UserDetail.lobbyRecoveryDay = bitPacket.g2(); UserDetail.lobbyUnreadMessages = bitPacket.g2(); UserDetail.lobbyLastLoginDay = bitPacket.g2(); UserDetail.lastLoginAddress = bitPacket.g4(); Static439.hostnameResource = GameShell.signLink.lookupHostname(UserDetail.lastLoginAddress); UserDetail.lobbyEmailStatus = bitPacket.g1(); UserDetail.lobbyCCExpiry = bitPacket.g2(); UserDetail.lobbyGraceExpiry = bitPacket.g2(); UserDetail.lobbyDOBRequested = bitPacket.g1() == 1; PlayerEntity.self.nameUnfiltered = PlayerEntity.self.displayName = Client.playerDisplayName = bitPacket.gjstr2(); UserDetail.lobbyMembersStats = bitPacket.g1(); UserDetail.lobbyPlayAge = bitPacket.g4(); Static587.aBoolean663 = bitPacket.g1() == 1; ConnectionInfo.auto = new ConnectionInfo(); ConnectionInfo.auto.world = bitPacket.g2(); if (ConnectionInfo.auto.world == 65535) { ConnectionInfo.auto.world = -1; } ConnectionInfo.auto.address = bitPacket.gjstr2(); if (ModeWhere.LIVE != Client.modeWhere) { ConnectionInfo.auto.defaultPort = ConnectionInfo.auto.world + 40000; ConnectionInfo.auto.alternatePort = ConnectionInfo.auto.world + 50000; } if ((ModeWhere.LOCAL != Client.modeWhere) && ((Client.modeWhere != ModeWhere.WTQA) || (Client.staffModLevel < 2)) && ConnectionInfo.login.equalTo(ConnectionInfo.game)) { WorldList.selectAutoWorld(); } } if (UserDetail.underage && !Static298.parentalAdvertConsent || Client.isMember) { try { JavaScript.call("zap", GameShell.loaderApplet); } catch (@Pc(1850) Throwable ignored) { if (Client.advert) { try { GameShell.loaderApplet.getAppletContext().showDocument(new URL(GameShell.loaderApplet.getCodeBase(), "blank.ws"), "tbi"); } catch (@Pc(1868) Exception ignored2) { /* empty */ } } } } else { try { JavaScript.call("unzap", GameShell.loaderApplet); } catch (@Pc(1879) Throwable ignored) { /* empty */ } } if (Client.modeWhere == ModeWhere.LIVE) { try { JavaScript.call("loggedin", GameShell.loaderApplet); } catch (@Pc(1892) Throwable ignored) { /* empty */ } } if (type != TYPE_GAME) { step = LoginStep.DELAY; setLoginResponse(LoginResponseCode.OK); Static249.method3538(); MainLogicManager.setStep(MainLogicStep.STEP_LOBBY_SCREEN); ServerConnection.active.currentProt = null; return; } step = LoginStep.WAIT_FOR_PLAYER_PACKET_LENGTH1; } if (step == LoginStep.WAIT_FOR_PLAYER_PACKET_LENGTH1) { if (!ServerConnection.active.connection.hasAvailable(3)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, 3, 0); step = LoginStep.WAIT_FOR_PLAYER_PACKET_LENGTH2; } if (step == LoginStep.WAIT_FOR_PLAYER_PACKET_LENGTH2) { @Pc(1435) BitPacket bitPacket = ServerConnection.active.bitPacket; bitPacket.pos = 0; if (bitPacket.largeOpcode()) { if (!ServerConnection.active.connection.hasAvailable(1)) { return; } ServerConnection.active.connection.read(bitPacket.data, 1, 3); } ServerConnection.active.currentProt = ServerProt.values()[bitPacket.readOpcode()]; ServerConnection.active.currentPacketSize = bitPacket.g2(); step = LoginStep.WAIT_FOR_PLAYER_PACKET; } if (step == LoginStep.WAIT_FOR_PLAYER_PACKET) { if (!ServerConnection.active.connection.hasAvailable(ServerConnection.active.currentPacketSize)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, ServerConnection.active.currentPacketSize, 0); ServerConnection.active.bitPacket.pos = 0; @Pc(360) int size = ServerConnection.active.currentPacketSize; step = LoginStep.DELAY; setLoginResponse(LoginResponseCode.OK); connected(); PlayerList.getSnapShotPlayer(ServerConnection.active.bitPacket); Static62.areaCenterX = -1; if (ServerConnection.active.currentProt == ServerProt.REBUILD_REGION) { Static466.rebuildRegion(); } else { Static434.rebuildNormal(); } if (ServerConnection.active.bitPacket.pos != size) { throw new RuntimeException("lswp pos:" + ServerConnection.active.bitPacket.pos + " psize:" + size); } ServerConnection.active.currentProt = null; } else if (step == LoginStep.WAIT_FOR_LOGIN_RECONNECT) { if (ServerConnection.active.currentPacketSize == -2) { if (!ServerConnection.active.connection.hasAvailable(2)) { return; } ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, 2, 0); ServerConnection.active.bitPacket.pos = 0; ServerConnection.active.currentPacketSize = ServerConnection.active.bitPacket.g2(); } if (ServerConnection.active.connection.hasAvailable(ServerConnection.active.currentPacketSize)) { ServerConnection.active.connection.read(ServerConnection.active.bitPacket.data, ServerConnection.active.currentPacketSize, 0); ServerConnection.active.bitPacket.pos = 0; step = LoginStep.DELAY; @Pc(360) int size = ServerConnection.active.currentPacketSize; setLoginResponse(LoginResponseCode.RECONNECT_OK); reconnected(); PlayerList.getSnapShotPlayer(ServerConnection.active.bitPacket); if (size != ServerConnection.active.bitPacket.pos) { throw new RuntimeException("lswpr pos:" + ServerConnection.active.bitPacket.pos + " psize:" + size); } ServerConnection.active.currentProt = null; } } } } catch (@Pc(2184) IOException exception) { ServerConnection.active.close(); if (errors < 3) { if (type == TYPE_GAME) { ConnectionInfo.login.rotateMethods(); } else { ConnectionInfo.lobby.rotateMethods(); } step = LoginStep.CONNECT; errors++; ticks = 0; } else { step = LoginStep.DELAY; setLoginResponse(LoginResponseCode.ERROR_CONNECTING_TO_SERVER); updateMainState(); } } } @OriginalMember(owner = "client!bs", name = "b", descriptor = "(I)V") public static void cancel() { if (step != LoginStep.DELAY) { ServerConnection.active.close(); reset(); updateMainState(); } } @OriginalMember(owner = "client!cc", name = "b", descriptor = "(I)V") public static void videoAdvertisementFinished() { if (step == LoginStep.WAIT_FOR_VIDEO_ADVERTISEMENT) { step = LoginStep.VIDEO_ADVERTISEMENT_FINISHED; } } @OriginalMember(owner = "client!vfa", name = "a", descriptor = "(II)V") public static void loginToGame(@OriginalArg(0) int arg0) { if (MainLogicManager.step == MainLogicStep.STEP_LOBBY_SCREEN && (step == LoginStep.DELAY && LobbyManager.step == LoginStep.DELAY)) { anInt7113 = arg0; MainLogicManager.setStep(MainLogicStep.STEP_LOGGING_IN_FROM_LOBBYSCREEN_TO_GAME); } } @OriginalMember(owner = "client!hh", name = "a", descriptor = "(ZLjava/lang/String;ZZLjava/lang/String;)V") public static void doLogin(@OriginalArg(0) boolean socialNetworkLogin, @OriginalArg(1) String username, @OriginalArg(3) boolean aBoolean640, @OriginalArg(4) String password) { if (!aBoolean640) { socialNetworkId = -1; } LoginManager.password = password; LoginManager.username = username; LoginManager.socialNetworkLogin = socialNetworkLogin; LoginManager.aBoolean640 = aBoolean640; if (!LoginManager.aBoolean640 && (LoginManager.username.equals("") || LoginManager.password.equals(""))) { setLoginResponse(LoginResponseCode.INVALID_USERNAME_OR_PASSWORD); return; } ServerConnection.active.errored = false; if (type != TYPE_LOBBY) { profileTransferTicks = 0; disallowResult = -1; disallowTrigger = -1; } setLoginResponse(LoginResponseCode.LOGGING_IN); step = LoginStep.CONNECT; ticks = 0; errors = 0; } @OriginalMember(owner = "client!kp", name = "a", descriptor = "(IZ)V") public static void setLoginResponse(@OriginalArg(0) int response) { if (type == TYPE_LOBBY) { lobbyLoginResponse = response; } else if (type == TYPE_GAME) { gameLoginResponse = response; } } @OriginalMember(owner = "client!ut", name = "d", descriptor = "(B)Lclient!ge;") public static Packet credentialsPacket() { @Pc(6) Packet packet = Packet.createXtea(); packet.p8(0L); packet.pjstr(password); packet.p8(ssoKey); packet.p8(clientSessionKey); packet.rsaenc(RSA_MODULUS, RSA_EXPONENT); return packet; } @OriginalMember(owner = "client!fe", name = "a", descriptor = "(ILclient!rka;)V") public static void pushJs5Checksums(@OriginalArg(1) BitPacket bitPacket) { bitPacket.p4(js5.ANIMS.indexCrc()); bitPacket.p4(js5.BASES.indexCrc()); bitPacket.p4(js5.CONFIG.indexCrc()); bitPacket.p4(js5.INTERFACES.indexCrc()); bitPacket.p4(js5.SYNTH_SOUNDS.indexCrc()); bitPacket.p4(js5.MAPS.indexCrc()); bitPacket.p4(js5.MIDI_SONGS.indexCrc()); bitPacket.p4(js5.MODELS.indexCrc()); bitPacket.p4(js5.SPRITES.indexCrc()); bitPacket.p4(js5.TEXTURES.indexCrc()); bitPacket.p4(js5.BINARY.indexCrc()); bitPacket.p4(js5.MIDI_JINGLES.indexCrc()); bitPacket.p4(js5.CLIENTSCRIPTS.indexCrc()); bitPacket.p4(js5.FONTMETRICS.indexCrc()); bitPacket.p4(js5.VORBIS.indexCrc()); bitPacket.p4(js5.js5_15.indexCrc()); bitPacket.p4(js5.CONFIG_LOC.indexCrc()); bitPacket.p4(js5.CONFIG_ENUM.indexCrc()); bitPacket.p4(js5.CONFIG_NPC.indexCrc()); bitPacket.p4(js5.CONFIG_OBJ.indexCrc()); bitPacket.p4(js5.CONFIG_SEQ.indexCrc()); bitPacket.p4(js5.CONFIG_SPOT.indexCrc()); bitPacket.p4(js5.CONFIG_STRUCT.indexCrc()); bitPacket.p4(js5.WORLDMAPDATA.indexCrc()); bitPacket.p4(js5.QUICKCHAT.indexCrc()); bitPacket.p4(js5.QUICKCHAT_GLOBAL.indexCrc()); bitPacket.p4(js5.MATERIALS.indexCrc()); bitPacket.p4(js5.CONFIG_PARTICLE.indexCrc()); bitPacket.p4(js5.DEFAULTS.indexCrc()); bitPacket.p4(js5.CONFIG_BILLBOARD.indexCrc()); bitPacket.p4(js5.DLLS.indexCrc()); bitPacket.p4(js5.SHADERS.indexCrc()); bitPacket.p4(js5.CUTSCENES.indexCrc()); bitPacket.p4(Loading.getSpritesCrc()); bitPacket.p4(Loading.getScreensCrc()); bitPacket.p4(js5.VIDEOS.indexCrc()); } @OriginalMember(owner = "client!hr", name = "c", descriptor = "(I)V") public static void connected() { js5.CONFIG.discardunpacked = 1; if (MainLogicManager.step == MainLogicStep.STEP_SWITCH_WORLD) { Static187.method2842(); } Static408.method5632(); Static694.anInt10405 = 0; Static618.anInt9449 = 0; ObjType.shadowCount = 0; Static373.anInt5903 = 0; ServerConnection.LOBBY.close(); Static50.previousFocus = true; GameShell.focus = true; Static230.method3374(); for (@Pc(8628) int i = 0; i < Static527.hintArrows.length; i++) { Static527.hintArrows[i] = null; } InterfaceManager.targetMode = false; SoundManager.reset(); Camera.yawOffset = (int) (Math.random() * 120.0D) - 60; Static288.anInt4621 = (int) (Math.random() * 80.0D) - 40; Static145.anInt2561 = (int) (Math.random() * 110.0D) - 55; Camera.scaleOffset = (int) (Math.random() * 30.0D) - 20; Static508.anInt7627 = (int) (Math.random() * 100.0D) - 50; Camera.playerCameraYaw = (float) ((int) (Math.random() * 160.0D) - 80 & 0x3FFF); Minimap.resetToggle(); for (@Pc(8697) int local8697 = 0; local8697 < PlayerList.COUNT; local8697++) { PlayerList.highResolutionPlayers[local8697] = null; } NPCList.size = 0; NPCList.newSize = 0; NPCList.local.clear(); Static505.projectiles.clear(); Static346.spotAnimations.clear(); TextCoordList.textCoords.clear(); Static497.objStacks.clear(); Static159.changes = new Deque(); Static227.customisations = new Deque(); TimedVarDomain.instance.reset(); DelayedStateChange.clear(); Camera.moveToX = 0; Camera.lookY = 0; Camera.lookZ = 0; Camera.lookX = 0; Camera.lookStep = 0; Camera.moveToRate = 0; Camera.moveToY = 0; Camera.lookSpeed = 0; Camera.moveToZ = 0; Camera.moveToStep = 0; for (@Pc(8765) int i = 0; i < Static511.varcs.length; i++) { if (!Static118.permVarcs[i]) { Static511.varcs[i] = -1; } } if (InterfaceManager.topLevelInterface != -1) { InterfaceManager.discard(InterfaceManager.topLevelInterface); } for (@Pc(8803) SubInterface sub = (SubInterface) InterfaceManager.subInterfaces.first(); sub != null; sub = (SubInterface) InterfaceManager.subInterfaces.next()) { if (!sub.isLinked()) { sub = (SubInterface) InterfaceManager.subInterfaces.first(); if (sub == null) { break; } } InterfaceManager.closeSubInterface(sub, true, false); } InterfaceManager.topLevelInterface = -1; InterfaceManager.subInterfaces = new IterableHashTable(8); InterfaceList.reset(); InterfaceManager.dialog = null; for (@Pc(8849) int i = 0; i < 8; i++) { MiniMenu.playerOps[i] = null; MiniMenu.playerOpsReducedPriority[i] = false; MiniMenu.playerOpCursors[i] = -1; } ClientInventory.cacheClear(); Static426.aBoolean72 = true; for (@Pc(8877) int i = 0; i < 100; i++) { InterfaceManager.dirtyRectangles[i] = true; } for (@Pc(8893) int i = 0; i < 6; i++) { StockmarketManager.offers[i] = new StockmarketOffer(); } for (@Pc(8911) int i = 0; i < 25; i++) { Static581.statLevels[i] = 0; Static498.statBaseLevels[i] = 0; Static237.statXps[i] = 0; } InterfaceManager.loginOpened(); Camera.angleUpdated = true; Client.clientpalette = LocType.clientpalette = NPCType.clientpalette = ObjType.clientpalette = new short[256]; Static331.moveText = LocalisedText.WALKHERE.localise(Client.language); ClientOptions.instance.update(ClientOptions.instance.removeRoofs.getValue(), ClientOptions.instance.removeRoofsOverride); ClientOptions.instance.update(ClientOptions.instance.animateBackgroundDefault.getValue(), ClientOptions.instance.animateBackground); VerifyId.reset(); MiniMenu.resetAndClose(); ServerConnectionReader.sendWindowStatus(); Static211.pingRequest = null; Static675.nextPing = 0L; js5.CONFIG.discardunpacked = 2; } @OriginalMember(owner = "client!cv", name = "b", descriptor = "(I)V") public static void reconnected() { ServerConnection.active.clear(); ServerConnection.active.currentProt = null; ServerConnection.active.bitPacket.pos = 0; ServerConnection.active.idleReadTicks = 0; ServerConnection.active.antepenultimateProt = null; ServerConnection.active.penultimateProt = null; ServerConnection.active.currentPacketSize = 0; Static249.rebootTimer = 0; ServerConnection.active.lastProt = null; MiniMenu.resetAndClose(); Minimap.resetFlag(); for (@Pc(36) int i = 0; i < PlayerList.COUNT; i++) { PlayerList.highResolutionPlayers[i] = null; } PlayerEntity.self = null; for (@Pc(49) int i = 0; i < NPCList.newSize; i++) { @Pc(55) NPCEntity npc = NPCList.entities[i].npc; if (npc != null) { npc.target = -1; } } ClientInventory.cacheClear(); Camera.mode = CameraMode.MODE_DEFAULT; Camera.anInt10383 = -1; Camera.anInt10376 = -1; MainLogicManager.setStep(MainLogicStep.STEP_GAME_SCREEN); for (@Pc(79) int i = 0; i < 100; i++) { InterfaceManager.dirtyRectangles[i] = true; } ServerConnectionReader.sendWindowStatus(); Static675.nextPing = 0L; Static211.pingRequest = null; } @OriginalMember(owner = "client!fu", name = "a", descriptor = "(Ljava/lang/String;ILjava/lang/String;I)V") public static void doGameLogin(@OriginalArg(0) String password, @OriginalArg(1) int arg1, @OriginalArg(2) String username) { ServerConnection.active = ServerConnection.GAME; type = TYPE_GAME; anInt7113 = arg1; doLogin(false, username, false, password); } @OriginalMember(owner = "client!tia", name = "a", descriptor = "(Ljava/lang/String;Ljava/lang/String;B)V") public static void doLobbyLogin(@OriginalArg(0) String password, @OriginalArg(1) String username) { anInt7113 = -1; ServerConnection.active = ServerConnection.LOBBY; type = TYPE_LOBBY; doLogin(false, username, false, password); } @OriginalMember(owner = "client!tk", name = "a", descriptor = "(II)V") public static void checkGameSession(@OriginalArg(0) int arg0) { type = TYPE_GAME; ServerConnection.active = ServerConnection.GAME; anInt7113 = arg0; @Pc(18) String key = null; if (Client.ssKey != null) { @Pc(25) Packet packet = new Packet(Client.ssKey); key = Base37.decode(packet.g8()); ssoKey = packet.g8(); } if (key == null) { setLoginResponse(LoginResponseCode.INVALID_SINGLE_SIGNON); } else { doLogin(false, key, true, ""); } } @OriginalMember(owner = "client!jea", name = "b", descriptor = "(I)V") public static void checkLobbySession() { anInt7113 = -1; ServerConnection.active = ServerConnection.LOBBY; type = TYPE_LOBBY; @Pc(16) String key = null; if (Client.ssKey != null) { @Pc(23) Packet packet = new Packet(Client.ssKey); key = Base37.decode(packet.g8()); ssoKey = packet.g8(); } if (key == null) { setLoginResponse(LoginResponseCode.INVALID_SINGLE_SIGNON); } else { doLogin(false, key, true, ""); } } @OriginalMember(owner = "client!vw", name = "a", descriptor = "(I)V") public static void doLobbySnLogin() { anInt7113 = -1; type = TYPE_LOBBY; ServerConnection.active = ServerConnection.LOBBY; doLogin(previousUsername.equals(""), previousUsername, true, ""); } @OriginalMember(owner = "client!dja", name = "b", descriptor = "(II)V") public static void doGameSnLogin(@OriginalArg(1) int arg0) { ServerConnection.active = ServerConnection.GAME; type = TYPE_GAME; anInt7113 = arg0; doLogin(previousUsername.equals(""), previousUsername, true, ""); } @OriginalMember(owner = "client!vda", name = "g", descriptor = "(I)V") public static void loginToGame() { if (Client.ssKey != null) { checkGameSession(anInt7113); } else if (socialNetworkId == -1) { doGameLogin(password, anInt7113, username); } else { doGameSnLogin(anInt7113); } } @OriginalMember(owner = "client!vaa", name = "a", descriptor = "(ILclient!fk;)[I") public static int[] pushXtea(@OriginalArg(1) ClientMessage message) { @Pc(8) Packet packet = new Packet(518); @Pc(11) int[] parts = new int[4]; for (@Pc(13) int i = 0; i < 4; i++) { parts[i] = (int) (Math.random() * 9.9999999E7D); } packet.p1(10); packet.p4(parts[0]); packet.p4(parts[1]); packet.p4(parts[2]); packet.p4(parts[3]); for (@Pc(70) int i = 0; i < 10; i++) { packet.p4((int) (Math.random() * 9.9999999E7D)); } packet.p2((int) (Math.random() * 9.9999999E7D)); packet.rsaenc(RSA_MODULUS, RSA_EXPONENT); message.bitPacket.pdata(packet.pos, packet.data, 0); return parts; } private LoginManager() { /* empty */ } @OriginalMember(owner = "client!rp", name = "b", descriptor = "(B)V") public static void updateMainState() { if (Static656.method6691(MainLogicManager.step)) { if (ServerConnection.LOBBY.connection == null) { MainLogicManager.setStep(MainLogicStep.STEP_LOGGING_IN_FROM_LOGINSCREEN_TO_LOBBY); } else { MainLogicManager.setStep(MainLogicStep.STEP_LOBBY_SCREEN); } } else if (MainLogicManager.step == MainLogicStep.STEP_LOGGING_IN_FROM_LOGINSCREEN_TO_LOBBY || MainLogicManager.step == MainLogicStep.STEP_LOGGING_IN_FROM_LOGINSCREEN_TO_GAME) { MainLogicManager.setStep(MainLogicStep.STEP_LOGIN_SCREEN); } else if (MainLogicManager.step == MainLogicStep.STEP_LOGGING_IN_FROM_GAMESCREEN_TO_LOBBY) { MainLogicManager.setStep(MainLogicStep.STEP_LOGIN_SCREEN); } } @OriginalMember(owner = "client!jka", name = "a", descriptor = "(IB)V") public static void loginToLobby(@OriginalArg(0) int arg0) { if (!isAtLoginScreen()) { return; } if (socialNetworkId != arg0) { previousUsername = ""; } socialNetworkId = arg0; ServerConnection.LOBBY.close(); MainLogicManager.setStep(MainLogicStep.STEP_LOGGING_IN_FROM_LOGINSCREEN_TO_LOBBY); } @OriginalMember(owner = "client!go", name = "a", descriptor = "(Ljava/lang/String;Ljava/lang/String;B)V") public static void enterLobby(@OriginalArg(1) String username, @OriginalArg(0) String password) { if (username.length() > 320 || !isAtLoginScreen()) { return; } ServerConnection.LOBBY.close(); resetSocialNetwork(); LoginManager.password = password; LoginManager.username = username; MainLogicManager.setStep(MainLogicStep.STEP_LOGGING_IN_FROM_LOGINSCREEN_TO_LOBBY); } }
1
0.927352
1
0.927352
game-dev
MEDIA
0.447958
game-dev
0.904792
1
0.904792
ameliaWhite92/CertoraProver
1,829
Public/TestEVM/Regressions/CERT-8995/Test.sol
contract Test { uint256 constant my_selector = 0xdeadbeef; function getThing(address other, uint value) internal returns (uint toRet) { assembly { mstore(0x0, my_selector) mstore(0x20, value) if iszero(staticcall(gas(), other, 0x1c, 0x24, 0x00, 0x20)) { revert(0,0) } toRet := mload(0x0) } } function summarizeMe(address other, uint value) internal returns (uint) { return getThing(other, value); } function doOtherThing(uint a) internal returns (uint) { return a + 1; } modifier blowStack(uint a) { _; assembly { log1(a, 0,0) } } /** * What is with this weird repetition? Well, it turns out you have to work pretty hard to get the * auto generated indices and stack heights to hash in a way that makes the temp variable generated in * getThing to be chosen as the return value alias. This is the configuration I found through kinda brute force. */ function useSummary(address other, uint value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) blowStack(value) external returns (uint) { summarizeMe(other, value); summarizeMe(other, value); summarizeMe(other, value); summarizeMe(other, value); summarizeMe(other, value); summarizeMe(other, value); summarizeMe(other, value); summarizeMe(other, value); summarizeMe(other, value); summarizeMe(other, value); summarizeMe(other, value); summarizeMe(other, value); summarizeMe(other, value); summarizeMe(other, value); return doOtherThing(summarizeMe(other, value)); } }
1
0.686574
1
0.686574
game-dev
MEDIA
0.505753
game-dev
0.515697
1
0.515697
mcpq/mcpq-python
18,786
mcpq/minecraft.py
from __future__ import annotations import grpc from . import logger from ._base import _HasServer, _SharedBase from ._proto import MinecraftStub from ._proto import minecraft_pb2 as pb from ._server import _Server from ._util import deprecated from .entity import Entity from .entitytype import EntityTypeFilter from .events import EventHandler from .exception import raise_on_error from .material import MaterialFilter from .nbt import NBT, Block, EntityType from .player import Player from .vec3 import Vec3 from .world import World, _DefaultWorld __all__ = ["Minecraft"] class Minecraft(_DefaultWorld, _SharedBase, _HasServer): """:class:`Minecraft` is the main object of interacting with Minecraft servers that have the mcpq-plugin_. When constructing the class, a ``host`` and ``port`` of the server should be provided to which a connection will be built. They default to ``"localhost"`` and ``1789`` respectively. All other worlds, events, entities and more are then received via the methods of that instance. .. _mcpq-plugin: https://github.com/mcpq/mcpq-plugin .. code-block:: python from mcpq import Minecraft mc = Minecraft() # connect to localhost mc.postToChat("Hello Minecraft") # send message in chat .. note:: Generally, it is sufficient to construct one :class:`Minecraft` instance per server or active connection, as this connection is thread-safe and reusable. However, it is also possible to connect with multiple instances from the same or different hosts at the same time. .. caution:: The connection used by the server is not encrypted or otherwise secured, meaning that any man-in-the-middle can read and modify any information sent between the program and the Minecraft server. For security reasons it is recommended to connect from the same host as the server is running on. By default, the plugin does only allow connections from ``localhost`` to prevent access from third parties. The :class:`Minecraft` instance is also the default :class:`~mcpq.world.World` and can be used to query :class:`~mcpq.entity.Entity`, :class:`~mcpq.player.Player` and :class:`Event <mcpq.events.EventHandler>` objects from the server. Checkout the corresponding classes for more information. .. code:: from mcpq import Minecraft mc = Minecraft() # connect to server on localhost with mcpq-plugin mc.postToChat("Players online:", mc.getPlayerList()) # show online players mc.events.block_hit.register(mc.postToChat) # print whenever a player hits a block to chat mc.setBlock("obsidian", mc.Vec3(0, 0, 0)) # set obsidian block at origin pos = mc.getHighestPos(0, 0).up(1) # get position above highest ground at 0 0 stairs = mc.blocks.endswith("_stairs").choice() # get random block ending in "_stairs" mc.setBlock(stairs.withData({"waterlogged": True}), pos) # set waterlogged stairs above ground creeper = mc.spawnEntity("creeper", pos.up(1)) # spawn creeper on stairs creeper.giveEffect("invisibility") # give creeper permanent invisibility effect creeper.pos = mc.getPlayer().pos # teleport creeper to player position # and many more ... """ def __init__(self, host: str = "localhost", port: int = 1789) -> None: self._addr = (host, port) self._channel = grpc.insecure_channel(f"{host}:{port}") server = _Server(MinecraftStub(self._channel)) super().__init__(server) self._event_handler = EventHandler(server) # deprecated functions self.stopEventPollingAndClearCallbacks = deprecated( "Call to deprecated function stopEventPollingAndClearCallbacks. Use events.stopEventPollingAndClearCallbacks instead." )(self.events.stopEventPollingAndClearCallbacks) self.pollPlayerJoinEvents = deprecated( "Call to deprecated function pollPlayerJoinEvents. Use events.player_join.poll instead." )(self.events.player_join.poll) self.pollPlayerLeaveEvents = deprecated( "Call to deprecated function pollPlayerLeaveEvents. Use events.player_leave.poll instead." )(self.events.player_leave.poll) self.pollPlayerDeathEvents = deprecated( "Call to deprecated function pollPlayerDeathEvents. Use events.player_death.poll instead." )(self.events.player_death.poll) self.pollChatEvents = deprecated( "Call to deprecated function pollChatEvents. Use events.chat.poll instead." )(self.events.chat.poll) self.pollBlockHitEvents = deprecated( "Call to deprecated function pollBlockHitEvents. Use events.block_hit.poll instead." )(self.events.block_hit.poll) self.pollProjectileHitEvents = deprecated( "Call to deprecated function pollProjectileHitEvents. Use events.projectile_hit.poll instead." )(self.events.projectile_hit.poll) self.registerCallbackPlayerJoinEvent = deprecated( "Call to deprecated function registerCallbackPlayerJoinEvent. Use events.player_join.register instead." )(self.events.player_join.register) self.registerCallbackPlayerLeaveEvent = deprecated( "Call to deprecated function registerCallbackPlayerLeaveEvent. Use events.player_leave.register instead." )(self.events.player_leave.register) self.registerCallbackPlayerDeathEvents = deprecated( "Call to deprecated function registerCallbackPlayerDeathEvents. Use events.player_death.register instead." )(self.events.player_death.register) self.registerCallbackChatEvent = deprecated( "Call to deprecated function registerCallbackChatEvent. Use events.chat.register instead." )(self.events.chat.register) self.registerCallbackBlockHitEvent = deprecated( "Call to deprecated function registerCallbackBlockHitEvent. Use events.block_hit.register instead." )(self.events.block_hit.register) self.registerCallbackProjectileHitEvent = deprecated( "Call to deprecated function registerCallbackProjectileHitEvent. Use events.projectile_hit.register instead." )(self.events.projectile_hit.register) self.getPlayers = deprecated( "Call to deprecated function getPlayers. Use getPlayerList instead." )(self.getPlayerList) self.getPlayerNames = deprecated( "Call to deprecated function getPlayerNames. Use [player.name for player in self.getPlayerList()] instead." )(lambda: [player.name for player in self.getPlayerList()]) def __repr__(self) -> str: host, port = self._addr return f"{self.__class__.__name__}({host=}, {port=})" def _cleanup(self) -> None: logger.debug("Minecraft: _cleanup: called, closing channel...") old_handler, self._event_handler = self._event_handler, None old_handler._cleanup() self._channel.close() logger.debug("Minecraft: _cleanup: done") def __del__(self) -> None: logger.debug("Minecraft: __del__: called") self._cleanup() @property def host(self) -> str: """The Minecraft server host address this instance is connected to, default is ``localhost``.""" return self._addr[0] @property def port(self) -> int: """The Minecraft server port this instance is connected to, default is ``1789``.""" return self._addr[1] @property def Block(self) -> type[Block]: """Alias for constructing :class:`~mcpq.nbt.Block`, e.g., ``mc.Block("acacia_stairs")``""" return Block @property def EntityType(self) -> type[EntityType]: """Alias for constructing :class:`~mcpq.nbt.EntityType`, e.g., ``mc.EntityType("creeper")``""" return EntityType @property def NBT(self) -> type[NBT]: """Alias for constructing :class:`~mcpq.nbt.NBT`, e.g., ``mc.NBT({"unbreakable": {}})``""" return NBT @property def Vec3(self) -> type[Vec3]: """Alias for constructing :class:`~mcpq.vec3.Vec3`, e.g., ``mc.Vec3(1, 2, 3)``""" return Vec3 @property def vec(self) -> type[Vec3]: """Alias for constructing :class:`~mcpq.vec3.Vec3`, e.g., ``mc.vec(1, 2, 3)``""" return Vec3 @property def events(self) -> EventHandler: """The :class:`~mcpq.events.EventHandler` for receiving events from the server. Checkout the :class:`~mcpq.events.EventHandler` class for examples for receiving events.""" return self._event_handler @property def blocks(self) -> MaterialFilter: """The :class:`~mcpq.material.MaterialFilter` containing all types of blocks on the server. Equivalent to ``mc.materials.block()``. Checkout the :class:`~mcpq.material.MaterialFilter` class for examples on filtering. """ return self.materials.block() @property def materials(self) -> MaterialFilter: """The :class:`~mcpq.material.MaterialFilter` containing all materials on the server, including types of blocks, items and more. Checkout the :class:`~mcpq.material.MaterialFilter` class for examples on filtering. """ return MaterialFilter(self._server, []) @property def entity_types(self) -> EntityTypeFilter: """The :class:`~mcpq.entitytype.EntityTypeFilter` containing all entity-types on the server. Checkout the :class:`~mcpq.entitytype.EntityTypeFilter` class for examples on filtering. .. note:: You probably want to use :attr:`.spawnables` to get spawnable entity-types only """ return EntityTypeFilter(self._server, []) @property def spawnables(self) -> EntityTypeFilter: """The :class:`~mcpq.entitytype.EntityTypeFilter` containing all entity-types on the server that can be spawned with :func:`spawnEntity`. Equivalent to ``mc.entity_types.spawnable()``. Checkout the :class:`~mcpq.entitytype.EntityTypeFilter` class for examples on filtering. """ return self.entity_types.spawnable() def postToChat(self, *objects, sep: str = " ") -> None: """Print `objects` in chat separated by `sep`. All objects are converted to strings using :func:`str()` first. .. code-block:: python mc.postToChat("Hello Minecraft") # print all only players mc.postToChat("Players online:", *mc.getPlayerList()) # print every block hit event into chat (good for learning events) mc.events.block_hit.register(mc.postToChat) You can also use the module `mcpq.text` to color or markup your chat messages: .. code-block:: python from mcpq import Minecraft, text mc.postToChat(text.RED + text.BOLD + "super " + text.RESET + text.BLUE + "cool!") # prints "super cool!", where "super" is red and bold, and "cool!" is blue :param sep: the separator between each object, defaults to " " :type sep: str, optional """ response = self._server.stub.postToChat( pb.ChatPostRequest(message=sep.join(map(str, objects))) ) raise_on_error(response) def getEntityById(self, entity_id: str) -> Entity: """Get an entity with a certain `entity_id`, even if it is not loaded. Normally the `entity_id` is not known ahead of time. Prefer using :func:`getEntities`, :func:`getEntitiesAround` and :func:`spawnEntity`, which all return entities. :param entity_id: the unique entity identified :type entity_id: str :return: the corresponding entity with that id, even if not loaded :rtype: Entity """ entity = self._server.get_or_create_entity(entity_id) entity._update_on_check() return entity def getOfflinePlayer(self, name: str) -> Player: """Get the :class:`~mcpq.player.Player` with the given `name` no matter if the player is online or not. Does not raise any errors if the player is offline. :param name: player name/id :type name: str :return: the player with the given `name` :rtype: Player """ return self._server.get_or_create_player(name) def getPlayer(self, name: str | None = None) -> Player: """Get any currently online player or get the online player with given `name`. Will raise an error if either no player is online, or if the player with given `name` is not online. If you want to check for any currently online players, use :func:`getPlayerList` instead. .. note:: There is no guarantee that the player returned will be the same across multiple calls of this function. It may change depending on the order the players joined the server or the implementation of the server. :param name: name of the online :class:`~mcpq.player.Player` that should be returned, or None if any online player will do, defaults to None :type name: str | None, optional :return: the player with `name` if name is given, else any online player :rtype: Player """ if name is None: players = self.getPlayerList() if players: return players[0] else: raise_on_error(pb.Status(code=pb.PLAYER_NOT_FOUND)) return None # type: ignore players = self.getPlayerList([name]) if players: return players[0] return None # type: ignore def getPlayerList(self, names: list[str] | None = None) -> list[Player]: """Get all currently online players on the entire server. If `names` is provided get all players with the given names only if they are online. Will raise an error if `names` is provided and at least one player with given name is offline. :param names: if given return only players with given names or error if one of the given players is offline, otherwise if `names` is `None` will return all currently online players, defaults to None :type names: list[str] | None, optional :return: the list of all currently online players, or if `names` is provided, only those online players :rtype: list[Player] """ if names is None: response = self._server.stub.getPlayers(pb.PlayerRequest()) else: response = self._server.stub.getPlayers(pb.PlayerRequest(names=names)) raise_on_error(response.status) return [self._server.get_or_create_player(player.name) for player in response.players] @property def worlds(self) -> tuple[World, ...]: """Give a tuple of all worlds loaded on the server. Does not automatically call :func:`refreshWorlds`. :return: A tuple of all worlds loaded on the server :rtype: tuple[World, ...] """ return self._server.get_worlds() @property def overworld(self) -> World: """Identical to :func:`getWorldByKey` with key ``"minecraft:overworld"``. :return: The overworld world :class:`~mcpq.world.World` object :rtype: World """ return self.getWorldByKey("minecraft:overworld") @property def nether(self) -> World: """Identical to :func:`getWorldByKey` with key ``"minecraft:the_nether"``. :return: The nether world :class:`~mcpq.world.World` object :rtype: World """ return self.getWorldByKey("minecraft:the_nether") @property def end(self) -> World: """Identical to :func:`getWorldByKey` with key ``"minecraft:the_end"``. :return: The end world :class:`~mcpq.world.World` object :rtype: World """ return self.getWorldByKey("minecraft:the_end") def getWorldByKey(self, key: str) -> World: """The `key` of a world is the dimensions internal name/id. Typically a regular server has the following worlds/keys: - ``"minecraft:overworld"`` - ``"minecraft:the_nether"`` - ``"minecraft:the_end"`` The ``"minecraft:"`` prefix may be omitted, e.g., ``"the_nether"``. If the given `key` does not exist an exception is raised. :param key: Internal name/id of the world, such as ``"minecraft:the_nether"`` or ``"the_nether"`` :type key: str :return: The corresponding :class:`~mcpq.world.World` object :rtype: World """ return self._server.get_world_by_key(key) def getWorldByName(self, name: str) -> World: """The `name` of a world is the folder or namespace the world resides in. The setting for the world the server opens is found in ``server.properties``. A typical, unmodified PaperMC_ server will save the worlds in the following folders: .. _PaperMC: https://papermc.io/ - ``"world"``, for the overworld - ``"world_nether"``, for the nether - ``"world_the_end"``, for the end The name of the overworld (default ``world``) is used as the prefix for the other folders. If the given `name` does not exist an exception is raised. :param name: Foldername the world is saved in, such as ``world`` :type name: str :return: The corresponding :class:`~mcpq.world.World` object :rtype: World """ return self._server.get_world_by_name(name) def refreshWorlds(self) -> None: """Fetches the currently loaded worlds from server and updates the world objects. This should only be called if the loaded worlds on the server change, for example, with the Multiverse Core Plugin. By default, the worlds will be refreshed on first use only. """ self._server.world_by_name_cache(force_update=True) def getMinecraftVersion(self) -> str: """The Minecraft version of the server this instance is connected to or None if the version cannot be identified.""" return self._server.get_mc_version_string() def getMinecraftVersionTuple(self) -> tuple[int, ...]: """The Minecraft version of the server this instance is connected to as a integer tuple or None if the version cannot be identified (e.g. from non-release candidate servers).""" return self._server.get_mc_version() def getPluginVersion(self) -> str: """The MCPQ Plugin version running on the server this instance is connected to.""" return self._server.get_mcpq_version() def getServerVersion(self) -> str: """The full name and version of the server this instance is connected to.""" return self._server.get_server_version()
1
0.70625
1
0.70625
game-dev
MEDIA
0.951566
game-dev
0.861535
1
0.861535
MACURD/Hearthbuddy8.7.6
1,624
Routines/DefaultRoutine/Silverfish/cards/1635-怀旧/Sim_DS1_175.cs
using System; using System.Collections.Generic; using System.Text; namespace HREngine.Bots { class Sim_DS1_175 : SimTemplate //* 森林狼 Timber Wolf { //Your other Beasts have +1_Attack. //你的其他野兽获得+1攻击力。 public override void onAuraStarts(Playfield p, Minion own) { if (own.own) { p.anzOwnTimberWolfs++; foreach (Minion m in p.ownMinions) { if ((TAG_RACE)m.handcard.card.race == TAG_RACE.PET && m.entitiyID != own.entitiyID) p.minionGetBuffed(m, 1, 0); } } else { p.anzEnemyTimberWolfs++; foreach (Minion m in p.enemyMinions) { if ((TAG_RACE)m.handcard.card.race == TAG_RACE.PET && m.entitiyID != own.entitiyID) p.minionGetBuffed(m, 1, 0); } } } public override void onAuraEnds(Playfield p, Minion own) { if (own.own) { p.anzOwnTimberWolfs--; foreach (Minion m in p.ownMinions) { if ((TAG_RACE)m.handcard.card.race == TAG_RACE.PET && m.entitiyID != own.entitiyID) p.minionGetBuffed(m, -1, 0); } } else { p.anzEnemyTimberWolfs--; foreach (Minion m in p.enemyMinions) { if ((TAG_RACE)m.handcard.card.race == TAG_RACE.PET && m.entitiyID != own.entitiyID) p.minionGetBuffed(m, -1, 0); } } } } }
1
0.780905
1
0.780905
game-dev
MEDIA
0.958328
game-dev
0.826405
1
0.826405
smilehao/xlua-hotfix-framework
1,858
Assets/Scripts/test/HotfixTest/HotfixTest.cs
using UnityEngine; using XLua; using UnityEngine.UI; [Hotfix] [LuaCallCSharp] public class BaseClass : MonoBehaviour { protected Text text = null; public Text TextCmp { get { return text; } } protected virtual void Awake() { text = transform.GetComponent<Text>(); if (text == null) { text = gameObject.AddComponent<Text>(); } } public virtual void SetText(string textValue) { if (text != null) { text.text = textValue; } } public virtual void ShowTextValue() { if (text != null) { Debug.Log(text.text); } } protected void TestProtectedFun() { Debug.Log("TestProtectedFun"); } } [Hotfix] [LuaCallCSharp] public class DriveClass : BaseClass { public override void SetText(string textValue) { textValue += "!"; base.SetText(textValue); } public void BaseSetText(string ss) { base.SetText(ss); } } [Hotfix(HotfixFlag.Stateful)] [LuaCallCSharp] public class HotfixTest : MonoBehaviour { [HideInInspector] public BaseClass testClass = null; public int tick = 0; //如果是private的,在lua设置xlua.private_accessible(CS.HotfixTest)后即可访问 // Use this for initialization void Start () { testClass = gameObject.AddComponent<DriveClass>(); } // Update is called once per frame void Update () { if (++tick % 50 == 0) { Debug.Log(">>>>>>>>Update in C#, tick = " + tick); if (testClass != null) { testClass.SetText("TTick " + tick.ToString()); testClass.ShowTextValue(); } } } public void TestCall() { Debug.Log("Call in c#"); } }
1
0.835774
1
0.835774
game-dev
MEDIA
0.767583
game-dev,desktop-app
0.670657
1
0.670657
neraliu/tainted-phantomjs
9,298
src/qt/src/3rdparty/webkit/Source/WebCore/generated/JSBeforeProcessEvent.cpp
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "JSBeforeProcessEvent.h" #include "BeforeProcessEvent.h" #include "ExceptionCode.h" #include "JSDOMBinding.h" #include "KURL.h" #include <runtime/Error.h> #include <runtime/JSString.h> #include <wtf/GetPtr.h> using namespace JSC; namespace WebCore { ASSERT_CLASS_FITS_IN_CELL(JSBeforeProcessEvent); /* Hash table */ #if ENABLE(JIT) #define THUNK_GENERATOR(generator) , generator #else #define THUNK_GENERATOR(generator) #endif static const HashTableValue JSBeforeProcessEventTableValues[3] = { { "text", DontDelete, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsBeforeProcessEventText), (intptr_t)setJSBeforeProcessEventText THUNK_GENERATOR(0) }, { "constructor", DontEnum | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsBeforeProcessEventConstructor), (intptr_t)0 THUNK_GENERATOR(0) }, { 0, 0, 0, 0 THUNK_GENERATOR(0) } }; #undef THUNK_GENERATOR static JSC_CONST_HASHTABLE HashTable JSBeforeProcessEventTable = { 4, 3, JSBeforeProcessEventTableValues, 0 }; /* Hash table for constructor */ #if ENABLE(JIT) #define THUNK_GENERATOR(generator) , generator #else #define THUNK_GENERATOR(generator) #endif static const HashTableValue JSBeforeProcessEventConstructorTableValues[1] = { { 0, 0, 0, 0 THUNK_GENERATOR(0) } }; #undef THUNK_GENERATOR static JSC_CONST_HASHTABLE HashTable JSBeforeProcessEventConstructorTable = { 1, 0, JSBeforeProcessEventConstructorTableValues, 0 }; class JSBeforeProcessEventConstructor : public DOMConstructorObject { public: JSBeforeProcessEventConstructor(JSC::ExecState*, JSC::Structure*, JSDOMGlobalObject*); virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&); virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&); static const JSC::ClassInfo s_info; static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype) { return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info); } protected: static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::ImplementsHasInstance | DOMConstructorObject::StructureFlags; }; const ClassInfo JSBeforeProcessEventConstructor::s_info = { "BeforeProcessEventConstructor", &DOMConstructorObject::s_info, &JSBeforeProcessEventConstructorTable, 0 }; JSBeforeProcessEventConstructor::JSBeforeProcessEventConstructor(ExecState* exec, Structure* structure, JSDOMGlobalObject* globalObject) : DOMConstructorObject(structure, globalObject) { ASSERT(inherits(&s_info)); putDirect(exec->globalData(), exec->propertyNames().prototype, JSBeforeProcessEventPrototype::self(exec, globalObject), DontDelete | ReadOnly); } bool JSBeforeProcessEventConstructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticValueSlot<JSBeforeProcessEventConstructor, JSDOMWrapper>(exec, &JSBeforeProcessEventConstructorTable, this, propertyName, slot); } bool JSBeforeProcessEventConstructor::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { return getStaticValueDescriptor<JSBeforeProcessEventConstructor, JSDOMWrapper>(exec, &JSBeforeProcessEventConstructorTable, this, propertyName, descriptor); } /* Hash table for prototype */ #if ENABLE(JIT) #define THUNK_GENERATOR(generator) , generator #else #define THUNK_GENERATOR(generator) #endif static const HashTableValue JSBeforeProcessEventPrototypeTableValues[2] = { { "initBeforeProcessEvent", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsBeforeProcessEventPrototypeFunctionInitBeforeProcessEvent), (intptr_t)3 THUNK_GENERATOR(0) }, { 0, 0, 0, 0 THUNK_GENERATOR(0) } }; #undef THUNK_GENERATOR static JSC_CONST_HASHTABLE HashTable JSBeforeProcessEventPrototypeTable = { 2, 1, JSBeforeProcessEventPrototypeTableValues, 0 }; const ClassInfo JSBeforeProcessEventPrototype::s_info = { "BeforeProcessEventPrototype", &JSC::JSObjectWithGlobalObject::s_info, &JSBeforeProcessEventPrototypeTable, 0 }; JSObject* JSBeforeProcessEventPrototype::self(ExecState* exec, JSGlobalObject* globalObject) { return getDOMPrototype<JSBeforeProcessEvent>(exec, globalObject); } bool JSBeforeProcessEventPrototype::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticFunctionSlot<JSObject>(exec, &JSBeforeProcessEventPrototypeTable, this, propertyName, slot); } bool JSBeforeProcessEventPrototype::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { return getStaticFunctionDescriptor<JSObject>(exec, &JSBeforeProcessEventPrototypeTable, this, propertyName, descriptor); } const ClassInfo JSBeforeProcessEvent::s_info = { "BeforeProcessEvent", &JSEvent::s_info, &JSBeforeProcessEventTable, 0 }; JSBeforeProcessEvent::JSBeforeProcessEvent(Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<BeforeProcessEvent> impl) : JSEvent(structure, globalObject, impl) { ASSERT(inherits(&s_info)); } JSObject* JSBeforeProcessEvent::createPrototype(ExecState* exec, JSGlobalObject* globalObject) { return new (exec) JSBeforeProcessEventPrototype(exec->globalData(), globalObject, JSBeforeProcessEventPrototype::createStructure(exec->globalData(), JSEventPrototype::self(exec, globalObject))); } bool JSBeforeProcessEvent::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticValueSlot<JSBeforeProcessEvent, Base>(exec, &JSBeforeProcessEventTable, this, propertyName, slot); } bool JSBeforeProcessEvent::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { return getStaticValueDescriptor<JSBeforeProcessEvent, Base>(exec, &JSBeforeProcessEventTable, this, propertyName, descriptor); } JSValue jsBeforeProcessEventText(ExecState* exec, JSValue slotBase, const Identifier&) { JSBeforeProcessEvent* castedThis = static_cast<JSBeforeProcessEvent*>(asObject(slotBase)); UNUSED_PARAM(exec); BeforeProcessEvent* imp = static_cast<BeforeProcessEvent*>(castedThis->impl()); JSValue result = jsString(exec, imp->text()); return result; } JSValue jsBeforeProcessEventConstructor(ExecState* exec, JSValue slotBase, const Identifier&) { JSBeforeProcessEvent* domObject = static_cast<JSBeforeProcessEvent*>(asObject(slotBase)); return JSBeforeProcessEvent::getConstructor(exec, domObject->globalObject()); } void JSBeforeProcessEvent::put(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot) { lookupPut<JSBeforeProcessEvent, Base>(exec, propertyName, value, &JSBeforeProcessEventTable, this, slot); } void setJSBeforeProcessEventText(ExecState* exec, JSObject* thisObject, JSValue value) { JSBeforeProcessEvent* castedThis = static_cast<JSBeforeProcessEvent*>(thisObject); BeforeProcessEvent* imp = static_cast<BeforeProcessEvent*>(castedThis->impl()); imp->setText(ustringToString(value.toString(exec))); } JSValue JSBeforeProcessEvent::getConstructor(ExecState* exec, JSGlobalObject* globalObject) { return getDOMConstructor<JSBeforeProcessEventConstructor>(exec, static_cast<JSDOMGlobalObject*>(globalObject)); } EncodedJSValue JSC_HOST_CALL jsBeforeProcessEventPrototypeFunctionInitBeforeProcessEvent(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSBeforeProcessEvent::s_info)) return throwVMTypeError(exec); JSBeforeProcessEvent* castedThis = static_cast<JSBeforeProcessEvent*>(asObject(thisValue)); BeforeProcessEvent* imp = static_cast<BeforeProcessEvent*>(castedThis->impl()); const String& type(ustringToString(exec->argument(0).toString(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); bool canBubble(exec->argument(1).toBoolean(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); bool cancelable(exec->argument(2).toBoolean(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); imp->initBeforeProcessEvent(type, canBubble, cancelable); return JSValue::encode(jsUndefined()); } }
1
0.642416
1
0.642416
game-dev
MEDIA
0.580854
game-dev
0.750928
1
0.750928
eliotsykes/asset_fingerprint
1,041
lib/asset_fingerprint/asset_tag_helper.rb
require 'asset_fingerprint/asset' module ActionView module Helpers module AssetTagHelper # Replaces the Rails method of the same name in AssetTagHelper. def rewrite_asset_path(source) AssetFingerprint.rewrite_asset_path(source) end # Allows AssetFingerprint to do any handling it needs to if a new # asset file is created at runtime. def write_asset_file_contents_with_fire_new_asset_file_event(joined_asset_path, asset_paths) write_asset_file_contents_without_fire_new_asset_file_event(joined_asset_path, asset_paths) AssetFingerprint.fire_new_asset_file_event(joined_asset_path) end alias_method_chain :write_asset_file_contents, :fire_new_asset_file_event def asset_file_path_with_remove_fingerprint(path) path = AssetFingerprint.path_rewriter.remove_fingerprint(path) asset_file_path_without_remove_fingerprint(path) end alias_method_chain :asset_file_path, :remove_fingerprint end end end
1
0.815195
1
0.815195
game-dev
MEDIA
0.562912
game-dev
0.589493
1
0.589493
jzyong/ugk-server
23,122
ugk-game/game-galactic-kittens/galactic-kittens-game/Assets/Scripts/Game/Manager/RoomManager.cs
using System.Collections; using System.Collections.Generic; using System.Linq; using Common.Network.Sync; using Common.Tools; using Game.Manager; using Game.Messages; using Game.Room.Boss; using Game.Room.Enemy; using UGK.Common.Network.Sync; using UGK.Common.Tools; using ugk.Game.Room.Boss; using UGK.Game.Room.Enemy; using ugk.Game.Room.Player; using UGK.Game.Room.Player; using UnityEngine; using Random = UnityEngine.Random; namespace UGK.Game.Manager { /// <summary> /// 房间管理 /// </summary> public class RoomManager : SingletonPersistent<RoomManager> { [SerializeField] [Tooltip("飞船,服务器只需要一个简单对象即可")] private SpaceShip _spaceShipPrefab; [SerializeField] [Tooltip("子弹")] private SpaceshipBullet _spaceshipBulletPrefab; [SerializeField] [Tooltip("敌人子弹")] private EnemyBullet _enemyBulletPrefab; [SerializeField] [Tooltip("Boss小子弹")] private BossSmallBullet _bossSmallBulletPrefab; [SerializeField] [Tooltip("Boss环形子弹")] private BossCircularBullet _bossCircularBulletPrefab; [SerializeField] [Tooltip("Boss自动跟踪导弹")] private BossHomingMisile _bossHomingMisilePrefab; [SerializeField] [Tooltip("不射击的敌人")] private SpaceGhostEnemy _spaceGhostEnemyPrefab; [SerializeField] [Tooltip("击的敌人")] private SpaceShooterEnemy _spaceShooterEnemyPrefab; [SerializeField] [Tooltip("陨石")] private Meteor _meteorPrefab; [SerializeField] [Tooltip("Boss")] private Boss _bossPrefab; [SerializeField] [Tooltip("能量道具")] private PowerUp _powerUpPrefab; [Header("Enemies")] [SerializeField] private float m_EnemySpawnTime = 1.8f; [SerializeField] private float m_meteorSpawningTime = 1f; [SerializeField] private float m_bossSpawnTime = 45; private Vector3 m_CurrentNewEnemyPosition = new Vector3(); private float m_CurrentEnemySpawnTime = 0f; private Vector3 m_CurrentNewMeteorPosition = new Vector3(); private float m_CurrentMeteorSpawnTime = 0f; private float m_CurrentBossSpawnTime = 0f; private bool m_IsSpawning = true; private long bossId; /// <summary> /// 飞船出生坐标 /// </summary> private readonly Vector3[] shipSpawnPositions = new[] { new Vector3(-8, 3), new Vector3(-8, 1f), new Vector3(-8, -1f), new Vector3(-8, -3f) }; private Dictionary<long, SpaceShip> _spaceShips = new Dictionary<long, SpaceShip>(4); /// <summary> /// 对象同步Id /// </summary> private long SyncId { get; set; } private void Start() { // Initialize the enemy and meteor spawn position based on my owning GO's x position m_CurrentNewEnemyPosition.x = 9; m_CurrentNewEnemyPosition.z = 0f; m_CurrentNewMeteorPosition.x = 10; //客户端对象出生计算位置时会快速移动一小段,因此从屏幕外出生 m_CurrentNewMeteorPosition.z = 0f; SyncId = short.MaxValue; //防止和玩家id冲突 } private void Update() { if (m_IsSpawning) { SpawnEnemy(); SpawnMeteor(); SpawnBoss(); } } /// <summary> /// 出生玩家 /// </summary> public void SpawnPlayers(List<Player> players) { GalacticKittensObjectSpawnResponse spawnResponse = new GalacticKittensObjectSpawnResponse(); for (int i = 0; i < players.Count; i++) { // 根据角色创建对应的实体对象,添加SnapTransform组件 var player = players[i]; var spawnPosition = shipSpawnPositions[i]; var spaceShip = Instantiate(_spaceShipPrefab, spawnPosition, Quaternion.identity, Instance.transform); var snapTransform = spaceShip.GetComponent<SnapTransform>(); snapTransform.Id = player.Id; if (player.Id > SyncId) //防止ID重复 { SyncId = player.Id; } GalacticKittensObjectSpawnResponse.Types.SpawnInfo spawnInfo = new GalacticKittensObjectSpawnResponse.Types.SpawnInfo() { OwnerId = player.Id, Id = player.Id, ConfigId = (uint)player.CharacterId, //0-3 SyncInterval = snapTransform.sendInterval, Position = ProtoUtil.BuildVector3D(spawnPosition) }; snapTransform.InitTransform(spawnPosition, null); SyncManager.Instance.AddSnapTransform(snapTransform); //添加同步对象 spawnResponse.Spawn.Add(spawnInfo); _spaceShips[player.Id] = spaceShip; Log.Info($"{player.Id} born in {spawnPosition}"); } PlayerManager.Instance.BroadcastMsg(MID.GalacticKittensObjectSpawnRes, spawnResponse); } /// <summary> /// 出生敌人 /// </summary> private void SpawnEnemy() { m_CurrentEnemySpawnTime += Time.deltaTime; if (m_CurrentEnemySpawnTime >= m_EnemySpawnTime) { // update the new enemy's spawn position(y value). This way we don't have to allocate // a new Vector3 each time. m_CurrentNewEnemyPosition.y = Random.Range(-5f, 5f); int randomPick = Random.Range(0, 99); GalacticKittensObjectSpawnResponse spawnResponse = new GalacticKittensObjectSpawnResponse(); GameObject gameObject; uint configId = 40; //40射击敌人、41幽灵敌人、41陨石 //射击 if (randomPick < 50) { gameObject = Instantiate(_spaceShooterEnemyPrefab, m_CurrentNewEnemyPosition, Quaternion.identity, Instance.transform).gameObject; } else { gameObject = Instantiate(_spaceGhostEnemyPrefab, m_CurrentNewEnemyPosition, Quaternion.identity, Instance.transform).gameObject; configId = 41; } var snapTransform = gameObject.GetComponent<SnapTransform>(); snapTransform.Id = SyncId++; snapTransform.Onwer = true; gameObject.name = $"SpaceEnemy-{snapTransform.Id}"; GalacticKittensObjectSpawnResponse.Types.SpawnInfo spawnInfo = new GalacticKittensObjectSpawnResponse.Types.SpawnInfo() { OwnerId = 0, Id = snapTransform.Id, ConfigId = configId, SyncInterval = snapTransform.sendInterval, Position = ProtoUtil.BuildVector3D(m_CurrentNewEnemyPosition), }; snapTransform.InitTransform(m_CurrentNewEnemyPosition, null); SyncManager.Instance.AddSnapTransform(snapTransform); //添加同步对象 spawnResponse.Spawn.Add(spawnInfo); Log.Info($"enemy {snapTransform.Id} born in {m_CurrentNewEnemyPosition}"); PlayerManager.Instance.BroadcastMsg(MID.GalacticKittensObjectSpawnRes, spawnResponse); m_CurrentEnemySpawnTime = 0f; } } /// <summary> /// 出生能量提升 /// </summary> public void SpawnPowerUp(Vector3 position) { //概率控制 int randomPick = Random.Range(1, 100); if (randomPick > 10) { return; } GalacticKittensObjectSpawnResponse spawnResponse = new GalacticKittensObjectSpawnResponse(); PowerUp powerUp = Instantiate(_powerUpPrefab, position, Quaternion.identity, Instance.transform); uint configId = 50; var snapTransform = powerUp.GetComponent<SnapTransform>(); snapTransform.Id = SyncId++; snapTransform.Onwer = true; powerUp.name = $"PowerUp-{snapTransform.Id}"; snapTransform.InitTransform(position, null); GalacticKittensObjectSpawnResponse.Types.SpawnInfo spawnInfo = new GalacticKittensObjectSpawnResponse.Types.SpawnInfo() { OwnerId = 0, Id = snapTransform.Id, ConfigId = configId, Position = ProtoUtil.BuildVector3D(position), }; SyncManager.Instance.AddSnapTransform(snapTransform); //添加同步对象 spawnResponse.Spawn.Add(spawnInfo); Log.Info($"PowerUp {snapTransform.Id} born in {position}"); PlayerManager.Instance.BroadcastMsg(MID.GalacticKittensObjectSpawnRes, spawnResponse); m_CurrentMeteorSpawnTime = 0f; } /// <summary> /// 出生陨石 /// </summary> private void SpawnMeteor() { m_CurrentMeteorSpawnTime += Time.deltaTime; if (m_CurrentMeteorSpawnTime >= m_meteorSpawningTime) { m_CurrentNewMeteorPosition.y = Random.Range(-5f, 6f); GalacticKittensObjectSpawnResponse spawnResponse = new GalacticKittensObjectSpawnResponse(); Meteor meteor = Instantiate(_meteorPrefab, m_CurrentNewMeteorPosition, Quaternion.identity, Instance.transform); meteor.SpawnInit(); uint configId = 42; //40射击敌人、41幽灵敌人、42陨石 var predictionTransform = meteor.GetComponent<PredictionTransform>(); predictionTransform.Id = SyncId++; predictionTransform.Onwer = true; predictionTransform.LinearVelocity = Vector3.left * 4; meteor.name = $"Meteor-{predictionTransform.Id}"; GalacticKittensObjectSpawnResponse.Types.SpawnInfo spawnInfo = new GalacticKittensObjectSpawnResponse.Types.SpawnInfo() { OwnerId = 0, Id = predictionTransform.Id, ConfigId = configId, Position = ProtoUtil.BuildVector3D(m_CurrentNewMeteorPosition), LinearVelocity = ProtoUtil.BuildVector3D(predictionTransform.LinearVelocity), Scale = ProtoUtil.BuildVector3D(meteor.transform.localScale) }; SyncManager.Instance.AddPredictionTransform(predictionTransform); //添加同步对象 spawnResponse.Spawn.Add(spawnInfo); Log.Info($"meteor {predictionTransform.Id} born in {m_CurrentNewMeteorPosition}"); PlayerManager.Instance.BroadcastMsg(MID.GalacticKittensObjectSpawnRes, spawnResponse); m_CurrentMeteorSpawnTime = 0f; } } /// <summary> /// 出生Boss /// </summary> private void SpawnBoss() { m_CurrentBossSpawnTime += Time.deltaTime; if (m_CurrentBossSpawnTime >= m_bossSpawnTime) { m_IsSpawning = false; StartCoroutine(BossAppear()); } } IEnumerator BossAppear() { // Warning title and sound SpawnBoss(20); // Same time as audio length yield return new WaitForSeconds(5.5f); SpawnBoss(21); } /// <summary> /// /// </summary> /// <param name="type">20Boss预警,21Boss</param> public void SpawnBoss(uint type) { GalacticKittensObjectSpawnResponse spawnResponse = new GalacticKittensObjectSpawnResponse(); GalacticKittensObjectSpawnResponse.Types.SpawnInfo spawnInfo = new GalacticKittensObjectSpawnResponse.Types.SpawnInfo(); spawnInfo.ConfigId = type; spawnResponse.Spawn.Add(spawnInfo); if (type == 20) { PlayerManager.Instance.BroadcastMsg(MID.GalacticKittensObjectSpawnRes, spawnResponse); return; } var spawnPosition = new Vector3(5, 0, 0); Boss boss = Instantiate(_bossPrefab, spawnPosition, Quaternion.identity, Instance.transform); boss.StartBoss(spawnPosition); var snapTransform = boss.GetComponent<SnapTransform>(); snapTransform.Id = SyncId++; bossId = snapTransform.Id; snapTransform.Onwer = true; snapTransform.InitTransform(spawnPosition, null); boss.name = $"Boss-{snapTransform.Id}"; spawnInfo.OwnerId = 0; spawnInfo.Id = snapTransform.Id; spawnInfo.Position = ProtoUtil.BuildVector3D(spawnPosition); spawnInfo.Hp = boss.helath; SyncManager.Instance.AddSnapTransform(snapTransform); //添加同步对象 Log.Info($"Boss {snapTransform.Id} born in {m_CurrentNewMeteorPosition}"); PlayerManager.Instance.BroadcastMsg(MID.GalacticKittensObjectSpawnRes, spawnResponse); } /// <summary> /// 创建子弹 /// </summary> /// <param name="player"></param> public void SpawnBullet(Player player) { GalacticKittensObjectSpawnResponse spawnResponse = new GalacticKittensObjectSpawnResponse(); SpaceShip spaceShip = _spaceShips[player.Id]; var spawnPosition = spaceShip.transform.position; spawnPosition = new Vector3(spawnPosition.x + 1f, spawnPosition.y - 0.3f, spawnPosition.z); //y轴下移一点 var spaceshipBullet = Instantiate(_spaceshipBulletPrefab, spawnPosition, Quaternion.identity, Instance.transform); var predictionTransform = spaceshipBullet.GetComponent<PredictionTransform>(); predictionTransform.Id = SyncId++; spaceshipBullet.name = $"SpaceBullet{player.Id}-{predictionTransform.Id}"; spaceshipBullet.OwnerId = player.Id; predictionTransform.LinearVelocity = spaceshipBullet.linearVelocity; GalacticKittensObjectSpawnResponse.Types.SpawnInfo spawnInfo = new GalacticKittensObjectSpawnResponse.Types.SpawnInfo() { OwnerId = player.Id, Id = predictionTransform.Id, ConfigId = 30, Position = ProtoUtil.BuildVector3D(spawnPosition), LinearVelocity = ProtoUtil.BuildVector3D(spaceshipBullet.linearVelocity), }; SyncManager.Instance.AddPredictionTransform(predictionTransform); //添加同步对象 spawnResponse.Spawn.Add(spawnInfo); Log.Info($"{player.Id} bullet born in {spawnPosition}"); PlayerManager.Instance.BroadcastMsg(MID.GalacticKittensObjectSpawnRes, spawnResponse); } /// <summary> /// 创建敌人子弹 /// </summary> /// <param name="enemy"></param> public void SpawnEnemyBullet(SpaceShooterEnemy enemy) { GalacticKittensObjectSpawnResponse spawnResponse = new GalacticKittensObjectSpawnResponse(); var spawnPosition = enemy.transform.position; var bullet = Instantiate(_enemyBulletPrefab, spawnPosition, Quaternion.identity, Instance.transform); var predictionTransform = bullet.GetComponent<PredictionTransform>(); predictionTransform.Id = SyncId++; bullet.name = $"EnemyBullet-{predictionTransform.Id}"; predictionTransform.LinearVelocity = bullet.linearVelocity; GalacticKittensObjectSpawnResponse.Types.SpawnInfo spawnInfo = new GalacticKittensObjectSpawnResponse.Types.SpawnInfo() { OwnerId = enemy.GetComponent<SnapTransform>().Id, Id = predictionTransform.Id, ConfigId = 31, Position = ProtoUtil.BuildVector3D(spawnPosition), LinearVelocity = ProtoUtil.BuildVector3D(bullet.linearVelocity), }; SyncManager.Instance.AddPredictionTransform(predictionTransform); //添加同步对象 spawnResponse.Spawn.Add(spawnInfo); Log.Info($"enemy bullet born in {spawnPosition}"); PlayerManager.Instance.BroadcastMsg(MID.GalacticKittensObjectSpawnRes, spawnResponse); } /// <summary> /// 产生boss子弹 /// </summary> /// <param name="type">32 boss三角形小子弹,33 boss环形分裂后小子弹,34 boss环形分裂子弹,35 boss导弹</param> /// <param name="position"></param> /// <param name="rotation"></param> public void SpawnBossBullet(uint type, Vector3 position, Vector3 rotation) { GalacticKittensObjectSpawnResponse spawnResponse = new GalacticKittensObjectSpawnResponse(); GameObject bullet = null; switch (type) { case 32: case 33: bullet = Instantiate(_bossSmallBulletPrefab, position, Quaternion.Euler(rotation), Instance.transform).gameObject; break; case 34: bullet = Instantiate(_bossCircularBulletPrefab, position, Quaternion.Euler(rotation), Instance.transform).gameObject; break; case 35: bullet = Instantiate(_bossHomingMisilePrefab, position, _bossHomingMisilePrefab.transform.rotation, Instance.transform).gameObject; break; default: Log.Warn($"bullet type:{type} not find"); return; } var snapTransform = bullet.GetComponent<SnapTransform>(); snapTransform.Id = SyncId++; snapTransform.Onwer = true; bullet.name = $"BossBullet-{snapTransform.Id}"; snapTransform.InitTransform(position, null); GalacticKittensObjectSpawnResponse.Types.SpawnInfo spawnInfo = new GalacticKittensObjectSpawnResponse.Types.SpawnInfo() { OwnerId = bossId, Id = snapTransform.Id, ConfigId = type, Position = ProtoUtil.BuildVector3D(position), }; SyncManager.Instance.AddSnapTransform(snapTransform); //添加同步对象 spawnResponse.Spawn.Add(spawnInfo); Log.Info($"Boss bullet born in {position}"); PlayerManager.Instance.BroadcastMsg(MID.GalacticKittensObjectSpawnRes, spawnResponse); } /// <summary> /// 对象死亡 /// </summary> public void DespawnObject(long killerId, long dieId, bool removeObject = true) { if (removeObject) { //移除的对象全部使用预测 SyncManager.Instance.RemoveSyncObject(dieId); } GalacticKittensObjectDieResponse response = new GalacticKittensObjectDieResponse() { KillerId = killerId, Id = dieId, // OwnerId = //TOD }; PlayerManager.Instance.BroadcastMsg(MID.GalacticKittensObjectDieRes, response); } /// <summary> /// 广播属性改变 /// </summary> /// <param name="spaceShip"></param> public void BroadcastPlayerProperty(SpaceShip spaceShip) { GalacticKittensPlayerPropertyResponse response = new GalacticKittensPlayerPropertyResponse(); GalacticKittensPlayerPropertyResponse.Types.PlayerProperty property = new GalacticKittensPlayerPropertyResponse.Types.PlayerProperty() { PlayerId = spaceShip.GetComponent<SnapTransform>().Id, Hp = spaceShip.hp, PowerUpCount = spaceShip.powerUpCount }; response.PlayerProperty.Add(property); PlayerManager.Instance.BroadcastMsg(MID.GalacticKittensPlayerPropertyRes, response); } public SpaceShip GetSpaceShip(long id) { if (_spaceShips.TryGetValue(id, out SpaceShip spaceShip)) { return spaceShip; } Log.Warn($"ship {id} not find"); return null; } public int PlayerCount() { return _spaceShips.Count; } /// <summary> /// 失败结束 /// </summary> public void GameFinishFail() { if (_spaceShips.Values.Any((ship => ship.gameObject.activeSelf))) { return; } m_IsSpawning = false; SyncManager.Instance.ResetData(); BroadcastReslut(false); } public void GameFinishSuccess() { foreach (var component in transform.GetComponents<PredictionTransform>()) { DespawnObject(0, component.Id); Destroy(component); } foreach (var component in transform.GetComponents<SnapTransform>()) { DespawnObject(0, component.Id); Destroy(component); } SyncManager.Instance.ResetData(); BroadcastReslut(true); } private void BroadcastReslut(bool victory) { GalacticKittensGameFinishRequest request = new GalacticKittensGameFinishRequest(); request.Victory = victory; request.RoomId = GalacticKittensNetworkManager.Instance.ServerId; foreach (var kv in _spaceShips) { var space = kv.Value; GalacticKittensGameFinishRequest.Types.PlayerStatistics statistics = new GalacticKittensGameFinishRequest.Types.PlayerStatistics() { PlayerId = space.GetComponent<SnapTransform>().Id, KillCount = space.KillEnemyCount, UsePowerCount = space.UsePopwerCount, Victory = space.hp > 0 }; request.Statistics.Add(statistics); } var client = new GalacticKittensMatchService.GalacticKittensMatchServiceClient(GalacticKittensNetworkManager .Instance.MatchChannel); var response = client.gameFinishAsync(request).ResponseAsync.Result; Log.Info($"上报战况 :{response.Result}"); if (response.Result != null && response.Result.Status != 200) { Log.Error($"game finish error:{response.Result.Msg}"); return; } // 解绑玩家网关映射 // PlayerManager.Instance.BindGateGameMapReq(false); Application.Quit(); } } }
1
0.818512
1
0.818512
game-dev
MEDIA
0.983767
game-dev
0.868649
1
0.868649
ReactVision/virocore
30,948
wasm/libs/bullet/src/BulletSoftBody/btSoftBody.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ ///btSoftBody implementation by Nathanael Presson #ifndef _BT_SOFT_BODY_H #define _BT_SOFT_BODY_H #include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btTransform.h" #include "LinearMath/btIDebugDraw.h" #include "BulletDynamics/Dynamics/btRigidBody.h" #include "BulletCollision/CollisionShapes/btConcaveShape.h" #include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" #include "btSparseSDF.h" #include "BulletCollision/BroadphaseCollision/btDbvt.h" //#ifdef BT_USE_DOUBLE_PRECISION //#define btRigidBodyData btRigidBodyDoubleData //#define btRigidBodyDataName "btRigidBodyDoubleData" //#else #define btSoftBodyData btSoftBodyFloatData #define btSoftBodyDataName "btSoftBodyFloatData" //#endif //BT_USE_DOUBLE_PRECISION class btBroadphaseInterface; class btDispatcher; class btSoftBodySolver; /* btSoftBodyWorldInfo */ struct btSoftBodyWorldInfo { btScalar air_density; btScalar water_density; btScalar water_offset; btScalar m_maxDisplacement; btVector3 water_normal; btBroadphaseInterface* m_broadphase; btDispatcher* m_dispatcher; btVector3 m_gravity; btSparseSdf<3> m_sparsesdf; btSoftBodyWorldInfo() :air_density((btScalar)1.2), water_density(0), water_offset(0), m_maxDisplacement(1000.f),//avoid soft body from 'exploding' so use some upper threshold of maximum motion that a node can travel per frame water_normal(0,0,0), m_broadphase(0), m_dispatcher(0), m_gravity(0,-10,0) { } }; ///The btSoftBody is an class to simulate cloth and volumetric soft bodies. ///There is two-way interaction between btSoftBody and btRigidBody/btCollisionObject. class btSoftBody : public btCollisionObject { public: btAlignedObjectArray<const class btCollisionObject*> m_collisionDisabledObjects; // The solver object that handles this soft body btSoftBodySolver *m_softBodySolver; // // Enumerations // ///eAeroModel struct eAeroModel { enum _ { V_Point, ///Vertex normals are oriented toward velocity V_TwoSided, ///Vertex normals are flipped to match velocity V_TwoSidedLiftDrag, ///Vertex normals are flipped to match velocity and lift and drag forces are applied V_OneSided, ///Vertex normals are taken as it is F_TwoSided, ///Face normals are flipped to match velocity F_TwoSidedLiftDrag, ///Face normals are flipped to match velocity and lift and drag forces are applied F_OneSided, ///Face normals are taken as it is END };}; ///eVSolver : velocities solvers struct eVSolver { enum _ { Linear, ///Linear solver END };}; ///ePSolver : positions solvers struct ePSolver { enum _ { Linear, ///Linear solver Anchors, ///Anchor solver RContacts, ///Rigid contacts solver SContacts, ///Soft contacts solver END };}; ///eSolverPresets struct eSolverPresets { enum _ { Positions, Velocities, Default = Positions, END };}; ///eFeature struct eFeature { enum _ { None, Node, Link, Face, Tetra, END };}; typedef btAlignedObjectArray<eVSolver::_> tVSolverArray; typedef btAlignedObjectArray<ePSolver::_> tPSolverArray; // // Flags // ///fCollision struct fCollision { enum _ { RVSmask = 0x000f, ///Rigid versus soft mask SDF_RS = 0x0001, ///SDF based rigid vs soft CL_RS = 0x0002, ///Cluster vs convex rigid vs soft SVSmask = 0x0030, ///Rigid versus soft mask VF_SS = 0x0010, ///Vertex vs face soft vs soft handling CL_SS = 0x0020, ///Cluster vs cluster soft vs soft handling CL_SELF = 0x0040, ///Cluster soft body self collision /* presets */ Default = SDF_RS, END };}; ///fMaterial struct fMaterial { enum _ { DebugDraw = 0x0001, /// Enable debug draw /* presets */ Default = DebugDraw, END };}; // // API Types // /* sRayCast */ struct sRayCast { btSoftBody* body; /// soft body eFeature::_ feature; /// feature type int index; /// feature index btScalar fraction; /// time of impact fraction (rayorg+(rayto-rayfrom)*fraction) }; /* ImplicitFn */ struct ImplicitFn { virtual btScalar Eval(const btVector3& x)=0; }; // // Internal types // typedef btAlignedObjectArray<btScalar> tScalarArray; typedef btAlignedObjectArray<btVector3> tVector3Array; /* sCti is Softbody contact info */ struct sCti { const btCollisionObject* m_colObj; /* Rigid body */ btVector3 m_normal; /* Outward normal */ btScalar m_offset; /* Offset from origin */ }; /* sMedium */ struct sMedium { btVector3 m_velocity; /* Velocity */ btScalar m_pressure; /* Pressure */ btScalar m_density; /* Density */ }; /* Base type */ struct Element { void* m_tag; // User data Element() : m_tag(0) {} }; /* Material */ struct Material : Element { btScalar m_kLST; // Linear stiffness coefficient [0,1] btScalar m_kAST; // Area/Angular stiffness coefficient [0,1] btScalar m_kVST; // Volume stiffness coefficient [0,1] int m_flags; // Flags }; /* Feature */ struct Feature : Element { Material* m_material; // Material }; /* Node */ struct Node : Feature { btVector3 m_x; // Position btVector3 m_q; // Previous step position btVector3 m_v; // Velocity btVector3 m_f; // Force accumulator btVector3 m_n; // Normal btScalar m_im; // 1/mass btScalar m_area; // Area btDbvtNode* m_leaf; // Leaf data int m_battach:1; // Attached }; /* Link */ struct Link : Feature { Node* m_n[2]; // Node pointers btScalar m_rl; // Rest length int m_bbending:1; // Bending link btScalar m_c0; // (ima+imb)*kLST btScalar m_c1; // rl^2 btScalar m_c2; // |gradient|^2/c0 btVector3 m_c3; // gradient }; /* Face */ struct Face : Feature { Node* m_n[3]; // Node pointers btVector3 m_normal; // Normal btScalar m_ra; // Rest area btDbvtNode* m_leaf; // Leaf data }; /* Tetra */ struct Tetra : Feature { Node* m_n[4]; // Node pointers btScalar m_rv; // Rest volume btDbvtNode* m_leaf; // Leaf data btVector3 m_c0[4]; // gradients btScalar m_c1; // (4*kVST)/(im0+im1+im2+im3) btScalar m_c2; // m_c1/sum(|g0..3|^2) }; /* RContact */ struct RContact { sCti m_cti; // Contact infos Node* m_node; // Owner node btMatrix3x3 m_c0; // Impulse matrix btVector3 m_c1; // Relative anchor btScalar m_c2; // ima*dt btScalar m_c3; // Friction btScalar m_c4; // Hardness }; /* SContact */ struct SContact { Node* m_node; // Node Face* m_face; // Face btVector3 m_weights; // Weigths btVector3 m_normal; // Normal btScalar m_margin; // Margin btScalar m_friction; // Friction btScalar m_cfm[2]; // Constraint force mixing }; /* Anchor */ struct Anchor { Node* m_node; // Node pointer btVector3 m_local; // Anchor position in body space btRigidBody* m_body; // Body btScalar m_influence; btMatrix3x3 m_c0; // Impulse matrix btVector3 m_c1; // Relative anchor btScalar m_c2; // ima*dt }; /* Note */ struct Note : Element { const char* m_text; // Text btVector3 m_offset; // Offset int m_rank; // Rank Node* m_nodes[4]; // Nodes btScalar m_coords[4]; // Coordinates }; /* Pose */ struct Pose { bool m_bvolume; // Is valid bool m_bframe; // Is frame btScalar m_volume; // Rest volume tVector3Array m_pos; // Reference positions tScalarArray m_wgh; // Weights btVector3 m_com; // COM btMatrix3x3 m_rot; // Rotation btMatrix3x3 m_scl; // Scale btMatrix3x3 m_aqq; // Base scaling }; /* Cluster */ struct Cluster { tScalarArray m_masses; btAlignedObjectArray<Node*> m_nodes; tVector3Array m_framerefs; btTransform m_framexform; btScalar m_idmass; btScalar m_imass; btMatrix3x3 m_locii; btMatrix3x3 m_invwi; btVector3 m_com; btVector3 m_vimpulses[2]; btVector3 m_dimpulses[2]; int m_nvimpulses; int m_ndimpulses; btVector3 m_lv; btVector3 m_av; btDbvtNode* m_leaf; btScalar m_ndamping; /* Node damping */ btScalar m_ldamping; /* Linear damping */ btScalar m_adamping; /* Angular damping */ btScalar m_matching; btScalar m_maxSelfCollisionImpulse; btScalar m_selfCollisionImpulseFactor; bool m_containsAnchor; bool m_collide; int m_clusterIndex; Cluster() : m_leaf(0),m_ndamping(0),m_ldamping(0),m_adamping(0),m_matching(0) ,m_maxSelfCollisionImpulse(100.f), m_selfCollisionImpulseFactor(0.01f), m_containsAnchor(false) {} }; /* Impulse */ struct Impulse { btVector3 m_velocity; btVector3 m_drift; int m_asVelocity:1; int m_asDrift:1; Impulse() : m_velocity(0,0,0),m_drift(0,0,0),m_asVelocity(0),m_asDrift(0) {} Impulse operator -() const { Impulse i=*this; i.m_velocity=-i.m_velocity; i.m_drift=-i.m_drift; return(i); } Impulse operator*(btScalar x) const { Impulse i=*this; i.m_velocity*=x; i.m_drift*=x; return(i); } }; /* Body */ struct Body { Cluster* m_soft; btRigidBody* m_rigid; const btCollisionObject* m_collisionObject; Body() : m_soft(0),m_rigid(0),m_collisionObject(0) {} Body(Cluster* p) : m_soft(p),m_rigid(0),m_collisionObject(0) {} Body(const btCollisionObject* colObj) : m_soft(0),m_collisionObject(colObj) { m_rigid = (btRigidBody*)btRigidBody::upcast(m_collisionObject); } void activate() const { if(m_rigid) m_rigid->activate(); if (m_collisionObject) m_collisionObject->activate(); } const btMatrix3x3& invWorldInertia() const { static const btMatrix3x3 iwi(0,0,0,0,0,0,0,0,0); if(m_rigid) return(m_rigid->getInvInertiaTensorWorld()); if(m_soft) return(m_soft->m_invwi); return(iwi); } btScalar invMass() const { if(m_rigid) return(m_rigid->getInvMass()); if(m_soft) return(m_soft->m_imass); return(0); } const btTransform& xform() const { static const btTransform identity=btTransform::getIdentity(); if(m_collisionObject) return(m_collisionObject->getWorldTransform()); if(m_soft) return(m_soft->m_framexform); return(identity); } btVector3 linearVelocity() const { if(m_rigid) return(m_rigid->getLinearVelocity()); if(m_soft) return(m_soft->m_lv); return(btVector3(0,0,0)); } btVector3 angularVelocity(const btVector3& rpos) const { if(m_rigid) return(btCross(m_rigid->getAngularVelocity(),rpos)); if(m_soft) return(btCross(m_soft->m_av,rpos)); return(btVector3(0,0,0)); } btVector3 angularVelocity() const { if(m_rigid) return(m_rigid->getAngularVelocity()); if(m_soft) return(m_soft->m_av); return(btVector3(0,0,0)); } btVector3 velocity(const btVector3& rpos) const { return(linearVelocity()+angularVelocity(rpos)); } void applyVImpulse(const btVector3& impulse,const btVector3& rpos) const { if(m_rigid) m_rigid->applyImpulse(impulse,rpos); if(m_soft) btSoftBody::clusterVImpulse(m_soft,rpos,impulse); } void applyDImpulse(const btVector3& impulse,const btVector3& rpos) const { if(m_rigid) m_rigid->applyImpulse(impulse,rpos); if(m_soft) btSoftBody::clusterDImpulse(m_soft,rpos,impulse); } void applyImpulse(const Impulse& impulse,const btVector3& rpos) const { if(impulse.m_asVelocity) { // printf("impulse.m_velocity = %f,%f,%f\n",impulse.m_velocity.getX(),impulse.m_velocity.getY(),impulse.m_velocity.getZ()); applyVImpulse(impulse.m_velocity,rpos); } if(impulse.m_asDrift) { // printf("impulse.m_drift = %f,%f,%f\n",impulse.m_drift.getX(),impulse.m_drift.getY(),impulse.m_drift.getZ()); applyDImpulse(impulse.m_drift,rpos); } } void applyVAImpulse(const btVector3& impulse) const { if(m_rigid) m_rigid->applyTorqueImpulse(impulse); if(m_soft) btSoftBody::clusterVAImpulse(m_soft,impulse); } void applyDAImpulse(const btVector3& impulse) const { if(m_rigid) m_rigid->applyTorqueImpulse(impulse); if(m_soft) btSoftBody::clusterDAImpulse(m_soft,impulse); } void applyAImpulse(const Impulse& impulse) const { if(impulse.m_asVelocity) applyVAImpulse(impulse.m_velocity); if(impulse.m_asDrift) applyDAImpulse(impulse.m_drift); } void applyDCImpulse(const btVector3& impulse) const { if(m_rigid) m_rigid->applyCentralImpulse(impulse); if(m_soft) btSoftBody::clusterDCImpulse(m_soft,impulse); } }; /* Joint */ struct Joint { struct eType { enum _ { Linear=0, Angular, Contact };}; struct Specs { Specs() : erp(1),cfm(1),split(1) {} btScalar erp; btScalar cfm; btScalar split; }; Body m_bodies[2]; btVector3 m_refs[2]; btScalar m_cfm; btScalar m_erp; btScalar m_split; btVector3 m_drift; btVector3 m_sdrift; btMatrix3x3 m_massmatrix; bool m_delete; virtual ~Joint() {} Joint() : m_delete(false) {} virtual void Prepare(btScalar dt,int iterations); virtual void Solve(btScalar dt,btScalar sor)=0; virtual void Terminate(btScalar dt)=0; virtual eType::_ Type() const=0; }; /* LJoint */ struct LJoint : Joint { struct Specs : Joint::Specs { btVector3 position; }; btVector3 m_rpos[2]; void Prepare(btScalar dt,int iterations); void Solve(btScalar dt,btScalar sor); void Terminate(btScalar dt); eType::_ Type() const { return(eType::Linear); } }; /* AJoint */ struct AJoint : Joint { struct IControl { virtual void Prepare(AJoint*) {} virtual btScalar Speed(AJoint*,btScalar current) { return(current); } static IControl* Default() { static IControl def;return(&def); } }; struct Specs : Joint::Specs { Specs() : icontrol(IControl::Default()) {} btVector3 axis; IControl* icontrol; }; btVector3 m_axis[2]; IControl* m_icontrol; void Prepare(btScalar dt,int iterations); void Solve(btScalar dt,btScalar sor); void Terminate(btScalar dt); eType::_ Type() const { return(eType::Angular); } }; /* CJoint */ struct CJoint : Joint { int m_life; int m_maxlife; btVector3 m_rpos[2]; btVector3 m_normal; btScalar m_friction; void Prepare(btScalar dt,int iterations); void Solve(btScalar dt,btScalar sor); void Terminate(btScalar dt); eType::_ Type() const { return(eType::Contact); } }; /* Config */ struct Config { eAeroModel::_ aeromodel; // Aerodynamic model (default: V_Point) btScalar kVCF; // Velocities correction factor (Baumgarte) btScalar kDP; // Damping coefficient [0,1] btScalar kDG; // Drag coefficient [0,+inf] btScalar kLF; // Lift coefficient [0,+inf] btScalar kPR; // Pressure coefficient [-inf,+inf] btScalar kVC; // Volume conversation coefficient [0,+inf] btScalar kDF; // Dynamic friction coefficient [0,1] btScalar kMT; // Pose matching coefficient [0,1] btScalar kCHR; // Rigid contacts hardness [0,1] btScalar kKHR; // Kinetic contacts hardness [0,1] btScalar kSHR; // Soft contacts hardness [0,1] btScalar kAHR; // Anchors hardness [0,1] btScalar kSRHR_CL; // Soft vs rigid hardness [0,1] (cluster only) btScalar kSKHR_CL; // Soft vs kinetic hardness [0,1] (cluster only) btScalar kSSHR_CL; // Soft vs soft hardness [0,1] (cluster only) btScalar kSR_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only) btScalar kSK_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only) btScalar kSS_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only) btScalar maxvolume; // Maximum volume ratio for pose btScalar timescale; // Time scale int viterations; // Velocities solver iterations int piterations; // Positions solver iterations int diterations; // Drift solver iterations int citerations; // Cluster solver iterations int collisions; // Collisions flags tVSolverArray m_vsequence; // Velocity solvers sequence tPSolverArray m_psequence; // Position solvers sequence tPSolverArray m_dsequence; // Drift solvers sequence }; /* SolverState */ struct SolverState { btScalar sdt; // dt*timescale btScalar isdt; // 1/sdt btScalar velmrg; // velocity margin btScalar radmrg; // radial margin btScalar updmrg; // Update margin }; /// RayFromToCaster takes a ray from, ray to (instead of direction!) struct RayFromToCaster : btDbvt::ICollide { btVector3 m_rayFrom; btVector3 m_rayTo; btVector3 m_rayNormalizedDirection; btScalar m_mint; Face* m_face; int m_tests; RayFromToCaster(const btVector3& rayFrom,const btVector3& rayTo,btScalar mxt); void Process(const btDbvtNode* leaf); static inline btScalar rayFromToTriangle(const btVector3& rayFrom, const btVector3& rayTo, const btVector3& rayNormalizedDirection, const btVector3& a, const btVector3& b, const btVector3& c, btScalar maxt=SIMD_INFINITY); }; // // Typedefs // typedef void (*psolver_t)(btSoftBody*,btScalar,btScalar); typedef void (*vsolver_t)(btSoftBody*,btScalar); typedef btAlignedObjectArray<Cluster*> tClusterArray; typedef btAlignedObjectArray<Note> tNoteArray; typedef btAlignedObjectArray<Node> tNodeArray; typedef btAlignedObjectArray<btDbvtNode*> tLeafArray; typedef btAlignedObjectArray<Link> tLinkArray; typedef btAlignedObjectArray<Face> tFaceArray; typedef btAlignedObjectArray<Tetra> tTetraArray; typedef btAlignedObjectArray<Anchor> tAnchorArray; typedef btAlignedObjectArray<RContact> tRContactArray; typedef btAlignedObjectArray<SContact> tSContactArray; typedef btAlignedObjectArray<Material*> tMaterialArray; typedef btAlignedObjectArray<Joint*> tJointArray; typedef btAlignedObjectArray<btSoftBody*> tSoftBodyArray; // // Fields // Config m_cfg; // Configuration SolverState m_sst; // Solver state Pose m_pose; // Pose void* m_tag; // User data btSoftBodyWorldInfo* m_worldInfo; // World info tNoteArray m_notes; // Notes tNodeArray m_nodes; // Nodes tLinkArray m_links; // Links tFaceArray m_faces; // Faces tTetraArray m_tetras; // Tetras tAnchorArray m_anchors; // Anchors tRContactArray m_rcontacts; // Rigid contacts tSContactArray m_scontacts; // Soft contacts tJointArray m_joints; // Joints tMaterialArray m_materials; // Materials btScalar m_timeacc; // Time accumulator btVector3 m_bounds[2]; // Spatial bounds bool m_bUpdateRtCst; // Update runtime constants btDbvt m_ndbvt; // Nodes tree btDbvt m_fdbvt; // Faces tree btDbvt m_cdbvt; // Clusters tree tClusterArray m_clusters; // Clusters btAlignedObjectArray<bool>m_clusterConnectivity;//cluster connectivity, for self-collision btTransform m_initialWorldTransform; btVector3 m_windVelocity; btScalar m_restLengthScale; // // Api // /* ctor */ btSoftBody( btSoftBodyWorldInfo* worldInfo,int node_count, const btVector3* x, const btScalar* m); /* ctor */ btSoftBody( btSoftBodyWorldInfo* worldInfo); void initDefaults(); /* dtor */ virtual ~btSoftBody(); /* Check for existing link */ btAlignedObjectArray<int> m_userIndexMapping; btSoftBodyWorldInfo* getWorldInfo() { return m_worldInfo; } ///@todo: avoid internal softbody shape hack and move collision code to collision library virtual void setCollisionShape(btCollisionShape* collisionShape) { } bool checkLink( int node0, int node1) const; bool checkLink( const Node* node0, const Node* node1) const; /* Check for existring face */ bool checkFace( int node0, int node1, int node2) const; /* Append material */ Material* appendMaterial(); /* Append note */ void appendNote( const char* text, const btVector3& o, const btVector4& c=btVector4(1,0,0,0), Node* n0=0, Node* n1=0, Node* n2=0, Node* n3=0); void appendNote( const char* text, const btVector3& o, Node* feature); void appendNote( const char* text, const btVector3& o, Link* feature); void appendNote( const char* text, const btVector3& o, Face* feature); /* Append node */ void appendNode( const btVector3& x,btScalar m); /* Append link */ void appendLink(int model=-1,Material* mat=0); void appendLink( int node0, int node1, Material* mat=0, bool bcheckexist=false); void appendLink( Node* node0, Node* node1, Material* mat=0, bool bcheckexist=false); /* Append face */ void appendFace(int model=-1,Material* mat=0); void appendFace( int node0, int node1, int node2, Material* mat=0); void appendTetra(int model,Material* mat); // void appendTetra(int node0, int node1, int node2, int node3, Material* mat=0); /* Append anchor */ void appendAnchor( int node, btRigidBody* body, bool disableCollisionBetweenLinkedBodies=false,btScalar influence = 1); void appendAnchor(int node,btRigidBody* body, const btVector3& localPivot,bool disableCollisionBetweenLinkedBodies=false,btScalar influence = 1); /* Append linear joint */ void appendLinearJoint(const LJoint::Specs& specs,Cluster* body0,Body body1); void appendLinearJoint(const LJoint::Specs& specs,Body body=Body()); void appendLinearJoint(const LJoint::Specs& specs,btSoftBody* body); /* Append linear joint */ void appendAngularJoint(const AJoint::Specs& specs,Cluster* body0,Body body1); void appendAngularJoint(const AJoint::Specs& specs,Body body=Body()); void appendAngularJoint(const AJoint::Specs& specs,btSoftBody* body); /* Add force (or gravity) to the entire body */ void addForce( const btVector3& force); /* Add force (or gravity) to a node of the body */ void addForce( const btVector3& force, int node); /* Add aero force to a node of the body */ void addAeroForceToNode(const btVector3& windVelocity,int nodeIndex); /* Add aero force to a face of the body */ void addAeroForceToFace(const btVector3& windVelocity,int faceIndex); /* Add velocity to the entire body */ void addVelocity( const btVector3& velocity); /* Set velocity for the entire body */ void setVelocity( const btVector3& velocity); /* Add velocity to a node of the body */ void addVelocity( const btVector3& velocity, int node); /* Set mass */ void setMass( int node, btScalar mass); /* Get mass */ btScalar getMass( int node) const; /* Get total mass */ btScalar getTotalMass() const; /* Set total mass (weighted by previous masses) */ void setTotalMass( btScalar mass, bool fromfaces=false); /* Set total density */ void setTotalDensity(btScalar density); /* Set volume mass (using tetrahedrons) */ void setVolumeMass( btScalar mass); /* Set volume density (using tetrahedrons) */ void setVolumeDensity( btScalar density); /* Transform */ void transform( const btTransform& trs); /* Translate */ void translate( const btVector3& trs); /* Rotate */ void rotate( const btQuaternion& rot); /* Scale */ void scale( const btVector3& scl); /* Get link resting lengths scale */ btScalar getRestLengthScale(); /* Scale resting length of all springs */ void setRestLengthScale(btScalar restLength); /* Set current state as pose */ void setPose( bool bvolume, bool bframe); /* Set current link lengths as resting lengths */ void resetLinkRestLengths(); /* Return the volume */ btScalar getVolume() const; /* Cluster count */ int clusterCount() const; /* Cluster center of mass */ static btVector3 clusterCom(const Cluster* cluster); btVector3 clusterCom(int cluster) const; /* Cluster velocity at rpos */ static btVector3 clusterVelocity(const Cluster* cluster,const btVector3& rpos); /* Cluster impulse */ static void clusterVImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse); static void clusterDImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse); static void clusterImpulse(Cluster* cluster,const btVector3& rpos,const Impulse& impulse); static void clusterVAImpulse(Cluster* cluster,const btVector3& impulse); static void clusterDAImpulse(Cluster* cluster,const btVector3& impulse); static void clusterAImpulse(Cluster* cluster,const Impulse& impulse); static void clusterDCImpulse(Cluster* cluster,const btVector3& impulse); /* Generate bending constraints based on distance in the adjency graph */ int generateBendingConstraints( int distance, Material* mat=0); /* Randomize constraints to reduce solver bias */ void randomizeConstraints(); /* Release clusters */ void releaseCluster(int index); void releaseClusters(); /* Generate clusters (K-mean) */ ///generateClusters with k=0 will create a convex cluster for each tetrahedron or triangle ///otherwise an approximation will be used (better performance) int generateClusters(int k,int maxiterations=8192); /* Refine */ void refine(ImplicitFn* ifn,btScalar accurary,bool cut); /* CutLink */ bool cutLink(int node0,int node1,btScalar position); bool cutLink(const Node* node0,const Node* node1,btScalar position); ///Ray casting using rayFrom and rayTo in worldspace, (not direction!) bool rayTest(const btVector3& rayFrom, const btVector3& rayTo, sRayCast& results); /* Solver presets */ void setSolver(eSolverPresets::_ preset); /* predictMotion */ void predictMotion(btScalar dt); /* solveConstraints */ void solveConstraints(); /* staticSolve */ void staticSolve(int iterations); /* solveCommonConstraints */ static void solveCommonConstraints(btSoftBody** bodies,int count,int iterations); /* solveClusters */ static void solveClusters(const btAlignedObjectArray<btSoftBody*>& bodies); /* integrateMotion */ void integrateMotion(); /* defaultCollisionHandlers */ void defaultCollisionHandler(const btCollisionObjectWrapper* pcoWrap); void defaultCollisionHandler(btSoftBody* psb); // // Functionality to deal with new accelerated solvers. // /** * Set a wind velocity for interaction with the air. */ void setWindVelocity( const btVector3 &velocity ); /** * Return the wind velocity for interaction with the air. */ const btVector3& getWindVelocity(); // // Set the solver that handles this soft body // Should not be allowed to get out of sync with reality // Currently called internally on addition to the world void setSoftBodySolver( btSoftBodySolver *softBodySolver ) { m_softBodySolver = softBodySolver; } // // Return the solver that handles this soft body // btSoftBodySolver *getSoftBodySolver() { return m_softBodySolver; } // // Return the solver that handles this soft body // btSoftBodySolver *getSoftBodySolver() const { return m_softBodySolver; } // // Cast // static const btSoftBody* upcast(const btCollisionObject* colObj) { if (colObj->getInternalType()==CO_SOFT_BODY) return (const btSoftBody*)colObj; return 0; } static btSoftBody* upcast(btCollisionObject* colObj) { if (colObj->getInternalType()==CO_SOFT_BODY) return (btSoftBody*)colObj; return 0; } // // ::btCollisionObject // virtual void getAabb(btVector3& aabbMin,btVector3& aabbMax) const { aabbMin = m_bounds[0]; aabbMax = m_bounds[1]; } // // Private // void pointersToIndices(); void indicesToPointers(const int* map=0); int rayTest(const btVector3& rayFrom,const btVector3& rayTo, btScalar& mint,eFeature::_& feature,int& index,bool bcountonly) const; void initializeFaceTree(); btVector3 evaluateCom() const; bool checkContact(const btCollisionObjectWrapper* colObjWrap,const btVector3& x,btScalar margin,btSoftBody::sCti& cti) const; void updateNormals(); void updateBounds(); void updatePose(); void updateConstants(); void updateLinkConstants(); void updateArea(bool averageArea = true); void initializeClusters(); void updateClusters(); void cleanupClusters(); void prepareClusters(int iterations); void solveClusters(btScalar sor); void applyClusters(bool drift); void dampClusters(); void applyForces(); static void PSolve_Anchors(btSoftBody* psb,btScalar kst,btScalar ti); static void PSolve_RContacts(btSoftBody* psb,btScalar kst,btScalar ti); static void PSolve_SContacts(btSoftBody* psb,btScalar,btScalar ti); static void PSolve_Links(btSoftBody* psb,btScalar kst,btScalar ti); static void VSolve_Links(btSoftBody* psb,btScalar kst); static psolver_t getSolver(ePSolver::_ solver); static vsolver_t getSolver(eVSolver::_ solver); virtual int calculateSerializeBufferSize() const; ///fills the dataBuffer and returns the struct name (and 0 on failure) virtual const char* serialize(void* dataBuffer, class btSerializer* serializer) const; //virtual void serializeSingleObject(class btSerializer* serializer) const; }; #endif //_BT_SOFT_BODY_H
1
0.985655
1
0.985655
game-dev
MEDIA
0.991581
game-dev
0.943053
1
0.943053
worldforge/cyphesis
1,548
data/rulesets/basic/scripts/mind/goals/animal/domestic.py
# This file is distributed under the terms of the GNU General Public license. # Copyright (C) 2007 Al Riddoch (See the file COPYING for details). import re from atlas import Operation, Entity from physics import Vector3D from rules import Location sowee_pattern = re.compile("[Ss]owee") from mind.goals.dynamic.DynamicGoal import DynamicGoal class Driven(DynamicGoal): """Move away from a herder when touched.""" def __init__(self, desc="Move away when touched, as by a swineherd"): DynamicGoal.__init__(self, trigger="touch", desc=desc) def event(self, me, original_op, op): direction = me.steering.direction_to(me.map.get(op.from_).location) destination = Location() destination.velocity = -direction.unit_vector() return Operation("move", Entity(me.entity.id, location=destination)) class Summons(DynamicGoal): """Stop moving when the herder gives a cry.""" def __init__(self, verb, desc="Come to a stop when commanded to"): DynamicGoal.__init__(self, trigger="sound_talk", desc=desc) def event(self, me, original_op, op): # FIXME Trigger this on interlinguish instead # FIXME Use the verb rather than the hardcoded RE talk_entity = op[0] if hasattr(talk_entity, "say"): say = talk_entity.say if sowee_pattern.match(say): destination = Location() destination.velocity = Vector3D(0, 0, 0) return Operation("move", Entity(me.entity.id, location=destination))
1
0.704808
1
0.704808
game-dev
MEDIA
0.6288
game-dev
0.877528
1
0.877528
runuo/runuo
8,716
Scripts/Gumps/Props/SetBodyGump.cs
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using Server; using Server.Network; using Server.HuePickers; using Server.Commands; namespace Server.Gumps { public class SetBodyGump : Gump { private PropertyInfo m_Property; private Mobile m_Mobile; private object m_Object; private Stack<StackEntry> m_Stack; private int m_Page; private ArrayList m_List; private int m_OurPage; private ArrayList m_OurList; private ModelBodyType m_OurType; private const int LabelColor32 = 0xFFFFFF; private const int SelectedColor32 = 0x8080FF; private const int TextColor32 = 0xFFFFFF; public SetBodyGump( PropertyInfo prop, Mobile mobile, object o, Stack<StackEntry> stack, int page, ArrayList list ) : this( prop, mobile, o, stack, page, list, 0, null, ModelBodyType.Invalid ) { } public string Center( string text ) { return String.Format( "<CENTER>{0}</CENTER>", text ); } public string Color( string text, int color ) { return String.Format( "<BASEFONT COLOR=#{0:X6}>{1}</BASEFONT>", color, text ); } public void AddTypeButton( int x, int y, int buttonID, string text, ModelBodyType type ) { bool isSelection = (m_OurType == type); AddButton( x, y - 1, isSelection ? 4006 : 4005, 4007, buttonID, GumpButtonType.Reply, 0 ); AddHtml( x + 35, y, 200, 20, Color( text, isSelection ? SelectedColor32 : LabelColor32 ), false, false ); } public SetBodyGump(PropertyInfo prop, Mobile mobile, object o, Stack<StackEntry> stack, int page, ArrayList list, int ourPage, ArrayList ourList, ModelBodyType ourType) : base( 20, 30 ) { m_Property = prop; m_Mobile = mobile; m_Object = o; m_Stack = stack; m_Page = page; m_List = list; m_OurPage = ourPage; m_OurList = ourList; m_OurType = ourType; AddPage( 0 ); AddBackground( 0, 0, 525, 328, 5054 ); AddImageTiled( 10, 10, 505, 20, 0xA40 ); AddAlphaRegion( 10, 10, 505, 20 ); AddImageTiled( 10, 35, 505, 283, 0xA40 ); AddAlphaRegion( 10, 35, 505, 283 ); AddTypeButton( 10, 10, 1, "Monster", ModelBodyType.Monsters ); AddTypeButton( 130, 10, 2, "Animal", ModelBodyType.Animals ); AddTypeButton( 250, 10, 3, "Marine", ModelBodyType.Sea ); AddTypeButton( 370, 10, 4, "Human", ModelBodyType.Human ); AddImage( 480, 12, 0x25EA ); AddImage( 497, 12, 0x25E6 ); if( ourList == null ) { AddLabel( 15, 40, 0x480, "Choose a body type above." ); } else if( ourList.Count == 0 ) { AddLabel( 15, 40, 0x480, "The server must have UO:3D installed to use this feature." ); } else { for( int i = 0, index = (ourPage * 12); i < 12 && index >= 0 && index < ourList.Count; ++i, ++index ) { InternalEntry entry = (InternalEntry)ourList[index]; int itemID = entry.ItemID; Rectangle2D bounds = ItemBounds.Table[itemID & 0x3FFF]; int x = 15 + ((i % 4) * 125); int y = 40 + ((i / 4) * 93); AddItem( x + ((120 - bounds.Width) / 2) - bounds.X, y + ((69 - bounds.Height) / 2) - bounds.Y, itemID ); AddButton( x + 6, y + 66, 0x98D, 0x98D, 7 + index, GumpButtonType.Reply, 0 ); x += 6; y += 67; AddHtml( x + 0, y - 1, 108, 21, Center( entry.DisplayName ), false, false ); AddHtml( x + 0, y + 1, 108, 21, Center( entry.DisplayName ), false, false ); AddHtml( x - 1, y + 0, 108, 21, Center( entry.DisplayName ), false, false ); AddHtml( x + 1, y + 0, 108, 21, Center( entry.DisplayName ), false, false ); AddHtml( x + 0, y + 0, 108, 21, Color( Center( entry.DisplayName ), TextColor32 ), false, false ); } if( ourPage > 0 ) AddButton( 480, 12, 0x15E3, 0x15E7, 5, GumpButtonType.Reply, 0 ); if( (ourPage + 1) * 12 < ourList.Count ) AddButton( 497, 12, 0x15E1, 0x15E5, 6, GumpButtonType.Reply, 0 ); } } public override void OnResponse( NetState sender, RelayInfo info ) { int index = info.ButtonID - 1; if( index == -1 ) { m_Mobile.SendGump( new PropertiesGump( m_Mobile, m_Object, m_Stack, m_List, m_Page ) ); } else if( index >= 0 && index < 4 ) { if( m_Monster == null ) LoadLists(); ModelBodyType type; ArrayList list; switch( index ) { default: case 0: type = ModelBodyType.Monsters; list = m_Monster; break; case 1: type = ModelBodyType.Animals; list = m_Animal; break; case 2: type = ModelBodyType.Sea; list = m_Sea; break; case 3: type = ModelBodyType.Human; list = m_Human; break; } m_Mobile.SendGump( new SetBodyGump( m_Property, m_Mobile, m_Object, m_Stack, m_Page, m_List, 0, list, type ) ); } else if( m_OurList != null ) { index -= 4; if( index == 0 && m_OurPage > 0 ) { m_Mobile.SendGump( new SetBodyGump( m_Property, m_Mobile, m_Object, m_Stack, m_Page, m_List, m_OurPage - 1, m_OurList, m_OurType ) ); } else if( index == 1 && ((m_OurPage + 1) * 12) < m_OurList.Count ) { m_Mobile.SendGump( new SetBodyGump( m_Property, m_Mobile, m_Object, m_Stack, m_Page, m_List, m_OurPage + 1, m_OurList, m_OurType ) ); } else { index -= 2; if( index >= 0 && index < m_OurList.Count ) { try { InternalEntry entry = (InternalEntry)m_OurList[index]; CommandLogging.LogChangeProperty( m_Mobile, m_Object, m_Property.Name, entry.Body.ToString() ); m_Property.SetValue( m_Object, entry.Body, null ); PropertiesGump.OnValueChanged( m_Object, m_Property, m_Stack ); } catch { m_Mobile.SendMessage( "An exception was caught. The property may not have changed." ); } m_Mobile.SendGump( new SetBodyGump( m_Property, m_Mobile, m_Object, m_Stack, m_Page, m_List, m_OurPage, m_OurList, m_OurType ) ); } } } } private static ArrayList m_Monster, m_Animal, m_Sea, m_Human; private static void LoadLists() { m_Monster = new ArrayList(); m_Animal = new ArrayList(); m_Sea = new ArrayList(); m_Human = new ArrayList(); List<BodyEntry> entries = Docs.LoadBodies(); for( int i = 0; i < entries.Count; ++i ) { BodyEntry oldEntry = (BodyEntry)entries[i]; int bodyID = oldEntry.Body.BodyID; if( ((Body)bodyID).IsEmpty ) continue; ArrayList list = null; switch( oldEntry.BodyType ) { case ModelBodyType.Monsters: list = m_Monster; break; case ModelBodyType.Animals: list = m_Animal; break; case ModelBodyType.Sea: list = m_Sea; break; case ModelBodyType.Human: list = m_Human; break; } if( list == null ) continue; int itemID = ShrinkTable.Lookup( bodyID, -1 ); if( itemID != -1 ) list.Add( new InternalEntry( bodyID, itemID, oldEntry.Name ) ); } m_Monster.Sort(); m_Animal.Sort(); m_Sea.Sort(); m_Human.Sort(); } private class InternalEntry : IComparable { private int m_Body; private int m_ItemID; private string m_Name; private string m_DisplayName; public int Body { get { return m_Body; } } public int ItemID { get { return m_ItemID; } } public string Name { get { return m_Name; } } public string DisplayName { get { return m_DisplayName; } } private static string[] m_GroupNames = new string[] { "ogres_", "ettins_", "walking_dead_", "gargoyles_", "orcs_", "flails_", "daemons_", "arachnids_", "dragons_", "elementals_", "serpents_", "gazers_", "liche_", "spirits_", "harpies_", "headless_", "lizard_race_", "mongbat_", "rat_race_", "scorpions_", "trolls_", "slimes_", "skeletons_", "ethereals_", "terathan_", "imps_", "cyclops_", "krakens_", "frogs_", "ophidians_", "centaurs_", "mages_", "fey_race_", "genies_", "paladins_", "shadowlords_", "succubi_", "lizards_", "rodents_", "birds_", "bovines_", "bruins_", "canines_", "deer_", "equines_", "felines_", "fowl_", "gorillas_", "kirin_", "llamas_", "ostards_", "porcines_", "ruminants_", "walrus_", "dolphins_", "sea_horse_", "sea_serpents_", "character_", "h_", "titans_" }; public InternalEntry( int body, int itemID, string name ) { m_Body = body; m_ItemID = itemID; m_Name = name; m_DisplayName = name.ToLower(); for( int i = 0; i < m_GroupNames.Length; ++i ) { if( m_DisplayName.StartsWith( m_GroupNames[i] ) ) { m_DisplayName = m_DisplayName.Substring( m_GroupNames[i].Length ); break; } } m_DisplayName = m_DisplayName.Replace( '_', ' ' ); } public int CompareTo( object obj ) { InternalEntry comp = (InternalEntry)obj; int v = m_Name.CompareTo( comp.m_Name ); if( v == 0 ) m_Body.CompareTo( comp.m_Body ); return v; } } } }
1
0.933168
1
0.933168
game-dev
MEDIA
0.933006
game-dev
0.96449
1
0.96449
q315523275/FamilyBucket
5,333
src/EventBus/Bucket.EventBus/Implementation/InMemoryEventBusSubscriptionsManager.cs
using Bucket.EventBus.Abstractions; using Bucket.EventBus.Attributes; using Bucket.EventBus.Events; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Bucket.EventBus.Implementation { public partial class InMemoryEventBusSubscriptionsManager : IEventBusSubscriptionsManager { private readonly Dictionary<string, List<SubscriptionInfo>> _handlers; private readonly List<Type> _eventTypes; public event EventHandler<string> OnEventRemoved; public InMemoryEventBusSubscriptionsManager() { _handlers = new Dictionary<string, List<SubscriptionInfo>>(); _eventTypes = new List<Type>(); } public bool IsEmpty => !_handlers.Keys.Any(); public void Clear() => _handlers.Clear(); public void AddDynamicSubscription<TH>(string eventName) where TH : IDynamicIntegrationEventHandler { DoAddSubscription(typeof(TH), eventName, isDynamic: true); } public void AddSubscription<T, TH>() where T : IntegrationEvent where TH : IIntegrationEventHandler<T> { var eventName = GetEventKey<T>(); DoAddSubscription(typeof(TH), eventName, isDynamic: false); if (!_eventTypes.Contains(typeof(T))) { _eventTypes.Add(typeof(T)); } } private void DoAddSubscription(Type handlerType, string eventName, bool isDynamic) { if (!HasSubscriptionsForEvent(eventName)) { _handlers.Add(eventName, new List<SubscriptionInfo>()); } if (_handlers[eventName].Any(s => s.HandlerType == handlerType)) { throw new ArgumentException( $"Handler Type {handlerType.Name} already registered for '{eventName}'", nameof(handlerType)); } if (isDynamic) { _handlers[eventName].Add(SubscriptionInfo.Dynamic(handlerType)); } else { _handlers[eventName].Add(SubscriptionInfo.Typed(handlerType)); } } public void RemoveDynamicSubscription<TH>(string eventName) where TH : IDynamicIntegrationEventHandler { var handlerToRemove = FindDynamicSubscriptionToRemove<TH>(eventName); DoRemoveHandler(eventName, handlerToRemove); } public void RemoveSubscription<T, TH>() where TH : IIntegrationEventHandler<T> where T : IntegrationEvent { var handlerToRemove = FindSubscriptionToRemove<T, TH>(); var eventName = GetEventKey<T>(); DoRemoveHandler(eventName, handlerToRemove); } private void DoRemoveHandler(string eventName, SubscriptionInfo subsToRemove) { if (subsToRemove != null) { _handlers[eventName].Remove(subsToRemove); if (!_handlers[eventName].Any()) { _handlers.Remove(eventName); var eventType = _eventTypes.SingleOrDefault(e => e.Name == eventName); if (eventType != null) { _eventTypes.Remove(eventType); } RaiseOnEventRemoved(eventName); } } } public IEnumerable<SubscriptionInfo> GetHandlersForEvent<T>() where T : IntegrationEvent { var key = GetEventKey<T>(); return GetHandlersForEvent(key); } public IEnumerable<SubscriptionInfo> GetHandlersForEvent(string eventName) => _handlers[eventName]; private void RaiseOnEventRemoved(string eventName) { var handler = OnEventRemoved; handler?.Invoke(this, eventName); } private SubscriptionInfo FindDynamicSubscriptionToRemove<TH>(string eventName) where TH : IDynamicIntegrationEventHandler { return DoFindSubscriptionToRemove(eventName, typeof(TH)); } private SubscriptionInfo FindSubscriptionToRemove<T, TH>() where T : IntegrationEvent where TH : IIntegrationEventHandler<T> { var eventName = GetEventKey<T>(); return DoFindSubscriptionToRemove(eventName, typeof(TH)); } private SubscriptionInfo DoFindSubscriptionToRemove(string eventName, Type handlerType) { if (!HasSubscriptionsForEvent(eventName)) { return null; } return _handlers[eventName].SingleOrDefault(s => s.HandlerType == handlerType); } public bool HasSubscriptionsForEvent<T>() where T : IntegrationEvent { var key = GetEventKey<T>(); return HasSubscriptionsForEvent(key); } public bool HasSubscriptionsForEvent(string eventName) => _handlers.ContainsKey(eventName); public Type GetEventTypeByName(string eventName) => _eventTypes.SingleOrDefault(t => t.Name == eventName); public string GetEventKey<T>() { return typeof(T).Name; } } }
1
0.906837
1
0.906837
game-dev
MEDIA
0.373111
game-dev
0.91124
1
0.91124
cheops/JC1060P470C_I_W
11,855
1-Demo/Demo_Arduino/1_2_Lvgl_V9/lvgl/src/libs/thorvg/tvgLoader.cpp
/* * Copyright (c) 2020 - 2024 the ThorVG project. All rights reserved. * 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 "../../lv_conf_internal.h" #if LV_USE_THORVG_INTERNAL #include <string.h> #include "tvgInlist.h" #include "tvgLoader.h" #include "tvgLock.h" #ifdef THORVG_SVG_LOADER_SUPPORT #include "tvgSvgLoader.h" #endif #ifdef THORVG_PNG_LOADER_SUPPORT #include "tvgPngLoader.h" #endif #ifdef THORVG_TVG_LOADER_SUPPORT #include "tvgTvgLoader.h" #endif #ifdef THORVG_JPG_LOADER_SUPPORT #include "tvgJpgLoader.h" #endif #ifdef THORVG_WEBP_LOADER_SUPPORT #include "tvgWebpLoader.h" #endif #ifdef THORVG_TTF_LOADER_SUPPORT #include "tvgTtfLoader.h" #endif #ifdef THORVG_LOTTIE_LOADER_SUPPORT #include "tvgLottieLoader.h" #endif #include "tvgRawLoader.h" uintptr_t HASH_KEY(const char* data) { return reinterpret_cast<uintptr_t>(data); } /************************************************************************/ /* Internal Class Implementation */ /************************************************************************/ ColorSpace ImageLoader::cs = ColorSpace::ARGB8888; static Key key; static Inlist<LoadModule> _activeLoaders; static LoadModule* _find(FileType type) { switch(type) { case FileType::Png: { #ifdef THORVG_PNG_LOADER_SUPPORT return new PngLoader; #endif break; } case FileType::Jpg: { #ifdef THORVG_JPG_LOADER_SUPPORT return new JpgLoader; #endif break; } case FileType::Webp: { #ifdef THORVG_WEBP_LOADER_SUPPORT return new WebpLoader; #endif break; } case FileType::Tvg: { #ifdef THORVG_TVG_LOADER_SUPPORT return new TvgLoader; #endif break; } case FileType::Svg: { #ifdef THORVG_SVG_LOADER_SUPPORT return new SvgLoader; #endif break; } case FileType::Ttf: { #ifdef THORVG_TTF_LOADER_SUPPORT return new TtfLoader; #endif break; } case FileType::Lottie: { #ifdef THORVG_LOTTIE_LOADER_SUPPORT return new LottieLoader; #endif break; } case FileType::Raw: { return new RawLoader; break; } default: { break; } } #ifdef THORVG_LOG_ENABLED const char *format; switch(type) { case FileType::Tvg: { format = "TVG"; break; } case FileType::Svg: { format = "SVG"; break; } case FileType::Ttf: { format = "TTF"; break; } case FileType::Lottie: { format = "lottie(json)"; break; } case FileType::Raw: { format = "RAW"; break; } case FileType::Png: { format = "PNG"; break; } case FileType::Jpg: { format = "JPG"; break; } case FileType::Webp: { format = "WEBP"; break; } default: { format = "???"; break; } } TVGLOG("RENDERER", "%s format is not supported", format); #endif return nullptr; } static LoadModule* _findByPath(const string& path) { auto ext = path.substr(path.find_last_of(".") + 1); if (!ext.compare("tvg")) return _find(FileType::Tvg); if (!ext.compare("svg")) return _find(FileType::Svg); if (!ext.compare("json")) return _find(FileType::Lottie); if (!ext.compare("png")) return _find(FileType::Png); if (!ext.compare("jpg")) return _find(FileType::Jpg); if (!ext.compare("webp")) return _find(FileType::Webp); if (!ext.compare("ttf") || !ext.compare("ttc")) return _find(FileType::Ttf); if (!ext.compare("otf") || !ext.compare("otc")) return _find(FileType::Ttf); return nullptr; } static FileType _convert(const string& mimeType) { auto type = FileType::Unknown; if (mimeType == "tvg") type = FileType::Tvg; else if (mimeType == "svg" || mimeType == "svg+xml") type = FileType::Svg; else if (mimeType == "ttf" || mimeType == "otf") type = FileType::Ttf; else if (mimeType == "lottie") type = FileType::Lottie; else if (mimeType == "raw") type = FileType::Raw; else if (mimeType == "png") type = FileType::Png; else if (mimeType == "jpg" || mimeType == "jpeg") type = FileType::Jpg; else if (mimeType == "webp") type = FileType::Webp; else TVGLOG("RENDERER", "Given mimetype is unknown = \"%s\".", mimeType.c_str()); return type; } static LoadModule* _findByType(const string& mimeType) { return _find(_convert(mimeType)); } static LoadModule* _findFromCache(const string& path) { ScopedLock lock(key); auto loader = _activeLoaders.head; while (loader) { if (loader->pathcache && !strcmp(loader->hashpath, path.c_str())) { ++loader->sharing; return loader; } loader = loader->next; } return nullptr; } static LoadModule* _findFromCache(const char* data, uint32_t size, const string& mimeType) { auto type = _convert(mimeType); if (type == FileType::Unknown) return nullptr; ScopedLock lock(key); auto loader = _activeLoaders.head; auto key = HASH_KEY(data); while (loader) { if (loader->type == type && loader->hashkey == key) { ++loader->sharing; return loader; } loader = loader->next; } return nullptr; } /************************************************************************/ /* External Class Implementation */ /************************************************************************/ bool LoaderMgr::init() { return true; } bool LoaderMgr::term() { auto loader = _activeLoaders.head; //clean up the remained font loaders which is globally used. while (loader && loader->type == FileType::Ttf) { auto ret = loader->close(); auto tmp = loader; loader = loader->next; _activeLoaders.remove(tmp); if (ret) delete(tmp); } return true; } bool LoaderMgr::retrieve(LoadModule* loader) { if (!loader) return false; if (loader->close()) { if (loader->cached()) { ScopedLock lock(key); _activeLoaders.remove(loader); } delete(loader); } return true; } LoadModule* LoaderMgr::loader(const string& path, bool* invalid) { *invalid = false; //TODO: lottie is not sharable. auto allowCache = true; auto ext = path.substr(path.find_last_of(".") + 1); if (!ext.compare("json")) allowCache = false; if (allowCache) { if (auto loader = _findFromCache(path)) return loader; } if (auto loader = _findByPath(path)) { if (loader->open(path)) { if (allowCache) { loader->hashpath = strdup(path.c_str()); loader->pathcache = true; { ScopedLock lock(key); _activeLoaders.back(loader); } } return loader; } delete(loader); } //Unknown MimeType. Try with the candidates in the order for (int i = 0; i < static_cast<int>(FileType::Raw); i++) { if (auto loader = _find(static_cast<FileType>(i))) { if (loader->open(path)) { if (allowCache) { loader->hashpath = strdup(path.c_str()); loader->pathcache = true; { ScopedLock lock(key); _activeLoaders.back(loader); } } return loader; } delete(loader); } } *invalid = true; return nullptr; } bool LoaderMgr::retrieve(const string& path) { return retrieve(_findFromCache(path)); } LoadModule* LoaderMgr::loader(const char* key) { auto loader = _activeLoaders.head; while (loader) { if (loader->pathcache && strstr(loader->hashpath, key)) { ++loader->sharing; return loader; } loader = loader->next; } return nullptr; } LoadModule* LoaderMgr::loader(const char* data, uint32_t size, const string& mimeType, bool copy) { //Note that users could use the same data pointer with the different content. //Thus caching is only valid for shareable. auto allowCache = !copy; //TODO: lottie is not sharable. if (allowCache) { auto type = _convert(mimeType); if (type == FileType::Lottie) allowCache = false; } if (allowCache) { if (auto loader = _findFromCache(data, size, mimeType)) return loader; } //Try with the given MimeType if (!mimeType.empty()) { if (auto loader = _findByType(mimeType)) { if (loader->open(data, size, copy)) { if (allowCache) { loader->hashkey = HASH_KEY(data); ScopedLock lock(key); _activeLoaders.back(loader); } return loader; } else { TVGLOG("LOADER", "Given mimetype \"%s\" seems incorrect or not supported.", mimeType.c_str()); delete(loader); } } } //Unknown MimeType. Try with the candidates in the order for (int i = 0; i < static_cast<int>(FileType::Raw); i++) { auto loader = _find(static_cast<FileType>(i)); if (loader) { if (loader->open(data, size, copy)) { if (allowCache) { loader->hashkey = HASH_KEY(data); ScopedLock lock(key); _activeLoaders.back(loader); } return loader; } delete(loader); } } return nullptr; } LoadModule* LoaderMgr::loader(const uint32_t *data, uint32_t w, uint32_t h, bool copy) { //Note that users could use the same data pointer with the different content. //Thus caching is only valid for shareable. if (!copy) { //TODO: should we check premultiplied?? if (auto loader = _findFromCache((const char*)(data), w * h, "raw")) return loader; } //function is dedicated for raw images only auto loader = new RawLoader; if (loader->open(data, w, h, copy)) { if (!copy) { loader->hashkey = HASH_KEY((const char*)data); ScopedLock lock(key); _activeLoaders.back(loader); } return loader; } delete(loader); return nullptr; } #endif /* LV_USE_THORVG_INTERNAL */
1
0.894026
1
0.894026
game-dev
MEDIA
0.240904
game-dev
0.772697
1
0.772697
cxong/cdogs-sdl
17,447
src/cdogs/map_object.c
/* C-Dogs SDL A port of the legendary (and fun) action/arcade cdogs. Copyright (C) 1995 Ronny Wester Copyright (C) 2003 Jeremy Chin Copyright (C) 2003-2007 Lucas Martin-King This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA This file incorporates work covered by the following copyright and permission notice: Copyright (c) 2014, 2016-2017, 2019, 2021, 2024-2025 Cong Xu All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "map_object.h" #include "json_utils.h" #include "log.h" #include "map.h" #include "net_util.h" #include "objs.h" #include "pics.h" MapObjects gMapObjects; const char *PlacementFlagStr(const int i) { switch (i) { T2S(PLACEMENT_OUTSIDE, "Outside"); T2S(PLACEMENT_INSIDE, "Inside"); T2S(PLACEMENT_NO_WALLS, "NoWalls"); T2S(PLACEMENT_ONE_WALL, "OneWall"); T2S(PLACEMENT_ONE_OR_MORE_WALLS, "OneOrMoreWalls"); T2S(PLACEMENT_FREE_IN_FRONT, "FreeInFront"); T2S(PLACEMENT_ON_WALL, "OnWall"); default: return ""; } } static PlacementFlags StrPlacementFlag(const char *s) { S2T(PLACEMENT_OUTSIDE, "Outside"); S2T(PLACEMENT_INSIDE, "Inside"); S2T(PLACEMENT_NO_WALLS, "NoWalls"); S2T(PLACEMENT_ONE_WALL, "OneWall"); S2T(PLACEMENT_ONE_OR_MORE_WALLS, "OneOrMoreWalls"); S2T(PLACEMENT_FREE_IN_FRONT, "FreeInFront"); S2T(PLACEMENT_ON_WALL, "OnWall"); return PLACEMENT_NONE; } static MapObjectType StrMapObjectType(const char *s) { S2T(MAP_OBJECT_TYPE_NORMAL, "Normal"); S2T(MAP_OBJECT_TYPE_PICKUP_SPAWNER, "PickupSpawner"); S2T(MAP_OBJECT_TYPE_ACTOR_SPAWNER, "ActorSpawner"); CASSERT(false, "unknown map object name"); return MAP_OBJECT_TYPE_NORMAL; } MapObject *StrMapObject(const char *s) { if (s == NULL || strlen(s) == 0) { return NULL; } CA_FOREACH(MapObject, c, gMapObjects.CustomClasses) if (strcmp(s, c->Name) == 0) { return c; } CA_FOREACH_END() CA_FOREACH(MapObject, c, gMapObjects.Classes) if (strcmp(s, c->Name) == 0) { return c; } CA_FOREACH_END() return NULL; } MapObject *IntMapObject(const int m) { // Note: do not edit; legacy integer mapping static const char *oldMapObjects[] = { "barrel_blue", "box", "box2", "cabinet", "plant", "bench", "chair", "column", "barrel_skull", "barrel_wood", "box_gray", "box_green", "statue_ogre", "table_wood_candle", "table_wood", "tree_dead", "bookshelf", "box_wood", "table_clothed", "table_steel", "tree_autumn", "tree", "box_metal_green", "safe", "box_red", "table_lab", "terminal", "barrel", "rocket", "egg", "bloodstain", "wall_skull", "bone_blood", "bulletmarks", "skull", "blood0", "scratch", "wall_stuff", "wall_goo", "goo"}; if (m < 0 || m > (int)(sizeof oldMapObjects / sizeof oldMapObjects[0])) { LOG(LM_MAIN, LL_ERROR, "cannot find map object %d", m); return NULL; } return StrMapObject(oldMapObjects[m]); } MapObject *IndexMapObject(const int i) { CASSERT( i >= 0 && i < (int)gMapObjects.Classes.size + (int)gMapObjects.CustomClasses.size, "Map object index out of bounds"); if (i < (int)gMapObjects.Classes.size) { return CArrayGet(&gMapObjects.Classes, i); } return CArrayGet(&gMapObjects.CustomClasses, i - gMapObjects.Classes.size); } int DestructibleMapObjectIndex(const MapObject *mo) { if (mo == NULL) { return 0; } CA_FOREACH(const char *, name, gMapObjects.Destructibles) const MapObject *d = StrMapObject(*name); if (d == mo) { return _ca_index; } CA_FOREACH_END() CASSERT(false, "cannot find destructible map object"); return -1; } const MapObject *GetRandomBloodPool(void) { const int idx = rand() % (int)gMapObjects.Bloods.size; const char **name = CArrayGet(&gMapObjects.Bloods, idx); return StrMapObject(*name); } int MapObjectGetFlags(const MapObject *mo) { int flags = 0; if (mo->DrawBelow) { flags |= THING_DRAW_BELOW; } if (mo->DrawAbove) { flags |= THING_DRAW_ABOVE; } if (mo->Health > 0) { flags |= THING_IMPASSABLE; flags |= THING_CAN_BE_SHOT; } return flags; } #define VERSION 4 void MapObjectsInit( MapObjects *classes, const char *filename, const AmmoClasses *ammo, const WeaponClasses *guns) { CArrayInit(&classes->Classes, sizeof(MapObject)); CArrayInit(&classes->CustomClasses, sizeof(MapObject)); CArrayInit(&classes->Destructibles, sizeof(char *)); CArrayInit(&classes->Bloods, sizeof(char *)); char buf[CDOGS_PATH_MAX]; GetDataFilePath(buf, filename); FILE *f = fopen(buf, "r"); json_t *root = NULL; if (f == NULL) { LOG(LM_MAIN, LL_ERROR, "Error: cannot load map objects file %s", buf); goto bail; } enum json_error e = json_stream_parse(f, &root); if (e != JSON_OK) { LOG(LM_MAIN, LL_ERROR, "Error parsing map objects file %s", buf); goto bail; } MapObjectsLoadJSON(&classes->Classes, root); // Load initial ammo/weapon spawners MapObjectsLoadAmmoAndGunSpawners(classes, ammo, guns, false); bail: if (f != NULL) { fclose(f); } json_free_value(&root); } static bool TryLoadMapObject(MapObject *m, json_t *node, const int version); static void ReloadDestructibles(MapObjects *mo); void MapObjectsLoadJSON(CArray *classes, json_t *root) { int version; LoadInt(&version, root, "Version"); if (version > VERSION || version <= 0) { CASSERT(false, "cannot read map objects file version"); return; } json_t *pickupsNode = json_find_first_label(root, "MapObjects")->child; for (json_t *child = pickupsNode->child; child; child = child->next) { MapObject m; if (TryLoadMapObject(&m, child, version)) { CArrayPushBack(classes, &m); } } ReloadDestructibles(&gMapObjects); // Load blood objects CArrayClear(&gMapObjects.Bloods); for (int i = 0;; i++) { char buf[CDOGS_FILENAME_MAX]; sprintf(buf, "blood%d", i); if (StrMapObject(buf) == NULL) { break; } char *tmp; CSTRDUP(tmp, buf); CArrayPushBack(&gMapObjects.Bloods, &tmp); } } static bool TryLoadMapObject(MapObject *m, json_t *node, const int version) { char *tmp = NULL; memset(m, 0, sizeof *m); m->Name = GetString(node, "Name"); // Pic json_t *normalNode = json_find_first_label(node, "Pic"); if (normalNode != NULL && normalNode->child != NULL) { if (version < 2) { CPicLoadNormal(&m->Pic, normalNode->child); } else { CPicLoadJSON(&m->Pic, normalNode->child); } // Pic required for map object if (!CPicIsLoaded(&m->Pic)) { LOG(LM_MAIN, LL_ERROR, "pic not found for map object(%s)", m->Name); goto bail; } } if (CPicIsLoaded(&m->Pic)) { // Default offset: centered X, align bottom of tile and sprite const struct vec2i size = CPicGetSize(&m->Pic); m->Offset = svec2i(-size.x / 2, TILE_HEIGHT / 2 - size.y); LoadVec2i(&m->Offset, node, "Offset"); } // Wreck m->Wreck.Sound = StrSound("bang"); if (version < 4) { if (version < 3) { // Assume old wreck pic is wreck json_t *wreckNode = json_find_first_label(node, "WreckPic"); if (wreckNode != NULL && wreckNode->child != NULL) { if (version < 2) { LoadStr(&m->Wreck.MO, node, "WreckPic"); } else { LoadStr(&m->Wreck.MO, wreckNode, "Pic"); } } } else { LoadStr(&m->Wreck.MO, node, "Wreck"); } } else { json_t *wreckNode = json_find_first_label(node, "Wreck"); if (wreckNode != NULL && wreckNode->child != NULL) { LoadStr(&m->Wreck.MO, wreckNode->child, "MapObject"); tmp = NULL; LoadStr(&tmp, wreckNode->child, "Sound"); if (tmp != NULL) { m->Wreck.Sound = StrSound(tmp); CFREE(tmp); } LoadStr(&m->Wreck.Bullet, wreckNode->child, "Bullet"); } } if (m->Wreck.Bullet == NULL) { CSTRDUP(m->Wreck.Bullet, "fireball_wreck"); } // Default tile size m->Size = TILE_SIZE; LoadVec2i(&m->Size, node, "Size"); LoadVec2(&m->PosOffset, node, "PosOffset"); LoadInt(&m->Health, node, "Health"); LoadBulletGuns(&m->DestroyGuns, node, "DestroyGuns"); // Flags json_t *flagsNode = json_find_first_label(node, "Flags"); if (flagsNode != NULL && flagsNode->child != NULL) { for (json_t *flagNode = flagsNode->child->child; flagNode; flagNode = flagNode->next) { m->Flags |= 1 << StrPlacementFlag(flagNode->text); } } LoadBool(&m->DrawBelow, node, "DrawBelow"); LoadBool(&m->DrawAbove, node, "DrawAbove"); LoadStr(&m->FootstepSound, node, "FootstepSound"); LoadColor(&m->FootprintMask, node, "FootprintMask"); // Special types JSON_UTILS_LOAD_ENUM(m->Type, node, "Type", StrMapObjectType); switch (m->Type) { case MAP_OBJECT_TYPE_NORMAL: // Do nothing break; case MAP_OBJECT_TYPE_PICKUP_SPAWNER: { tmp = GetString(node, "Pickup"); m->u.PickupClass = StrPickupClass(tmp); CFREE(tmp); } break; case MAP_OBJECT_TYPE_ACTOR_SPAWNER: LoadInt(&m->u.Character.CharId, node, "CharId"); LoadInt(&m->u.Character.Counter, node, "Counter"); break; default: CASSERT(false, "unknown error"); break; } // DestroySpawn - pickups to spawn on destruction json_t *destroySpawnNode = json_find_first_label(node, "DestroySpawn"); if (destroySpawnNode != NULL && destroySpawnNode->child != NULL) { CArrayInit(&m->DestroySpawn, sizeof(MapObjectDestroySpawn)); for (json_t *dsNode = destroySpawnNode->child->child; dsNode; dsNode = dsNode->next) { MapObjectDestroySpawn mods; memset(&mods, 0, sizeof mods); JSON_UTILS_LOAD_ENUM(mods.Type, dsNode, "Type", StrPickupType); LoadDouble(&mods.SpawnChance, dsNode, "SpawnChance"); CArrayPushBack(&m->DestroySpawn, &mods); } } // Initialise to negative so zero health map objects don't smoke m->DamageSmoke.HealthThreshold = -1; json_t *dSmokeNode = json_find_first_label(node, "DamageSmoke"); if (dSmokeNode != NULL && dSmokeNode->child != NULL) { LoadStr(&m->DamageSmoke.ParticleClass, dSmokeNode->child, "Particle"); if (m->DamageSmoke.ParticleClass == NULL) { CSTRDUP(m->DamageSmoke.ParticleClass, "smoke_big"); } LoadFloat( &m->DamageSmoke.HealthThreshold, dSmokeNode->child, "HealthThreshold"); LoadFloat(&m->DamageSmoke.Z, dSmokeNode->child, "Z"); m->DamageSmoke.Ticks = 20; LoadInt(&m->DamageSmoke.Ticks, dSmokeNode->child, "Ticks"); } return true; bail: return false; } static void AddDestructibles(MapObjects *mo, const CArray *classes); static void ReloadDestructibles(MapObjects *mo) { CA_FOREACH(char *, s, mo->Destructibles) CFREE(*s); CA_FOREACH_END() CArrayClear(&mo->Destructibles); AddDestructibles(mo, &mo->Classes); AddDestructibles(mo, &mo->CustomClasses); } static void AddDestructibles(MapObjects *m, const CArray *classes) { for (int i = 0; i < (int)classes->size; i++) { const MapObject *mo = CArrayGet(classes, i); if (mo->Health > 0) { char *s; CSTRDUP(s, mo->Name); CArrayPushBack(&m->Destructibles, &s); } } } static void LoadAmmoSpawners(CArray *classes, const CArray *ammo); static void LoadGunSpawners(CArray *classes, const CArray *guns); void MapObjectsLoadAmmoAndGunSpawners( MapObjects *classes, const AmmoClasses *ammo, const WeaponClasses *guns, const bool isCustom) { if (isCustom) { LoadAmmoSpawners(&classes->CustomClasses, &ammo->CustomAmmo); LoadGunSpawners(&classes->CustomClasses, &guns->CustomGuns); } else { // Load built-in classes LoadAmmoSpawners(&classes->Classes, &ammo->Ammo); LoadGunSpawners(&classes->Classes, &guns->Guns); } } static void SetupSpawner( MapObject *m, const char *spawnerName, const char *pickupClassName); static void LoadAmmoSpawners(CArray *classes, const CArray *ammo) { for (int i = 0; i < (int)ammo->size; i++) { const Ammo *a = CArrayGet(ammo, i); MapObject m; char spawnerName[256]; char pickupClassName[256]; sprintf(spawnerName, "%s ammo spawner", a->Name); sprintf(pickupClassName, "ammo_%s", a->Name); SetupSpawner(&m, spawnerName, pickupClassName); CArrayPushBack(classes, &m); } } static void LoadGunSpawners(CArray *classes, const CArray *guns) { for (int i = 0; i < (int)guns->size; i++) { const WeaponClass *wc = CArrayGet(guns, i); if (!wc->IsRealGun) { continue; } MapObject m; char spawnerName[256]; char pickupClassName[256]; sprintf(spawnerName, "%s spawner", wc->name); sprintf(pickupClassName, "gun_%s", wc->name); SetupSpawner(&m, spawnerName, pickupClassName); CArrayPushBack(classes, &m); } } static void SetupSpawner( MapObject *m, const char *spawnerName, const char *pickupClassName) { memset(m, 0, sizeof *m); CSTRDUP(m->Name, spawnerName); m->Pic.Type = PICTYPE_ANIMATED; m->Pic.u.Animated.Sprites = &PicManagerGetSprites(&gPicManager, "spawn_pad")->pics; m->Pic.u.Animated.TicksPerFrame = 8; m->Pic.Mask = colorWhite; const struct vec2i size = CPicGetSize(&m->Pic); m->Offset = svec2i(-size.x / 2, TILE_HEIGHT / 2 - size.y); m->Size = TILE_SIZE; m->Health = 0; m->DrawBelow = true; m->Type = MAP_OBJECT_TYPE_PICKUP_SPAWNER; m->u.PickupClass = StrPickupClass(pickupClassName); } void MapObjectsClear(CArray *classes) { for (int i = 0; i < (int)classes->size; i++) { MapObject *c = CArrayGet(classes, i); CFREE(c->Name); CFREE(c->Wreck.MO); CFREE(c->Wreck.Bullet); CFREE(c->FootstepSound); CFREE(c->DamageSmoke.ParticleClass); CArrayTerminate(&c->DestroyGuns); CArrayTerminate(&c->DestroySpawn); } CArrayClear(classes); } void MapObjectsTerminate(MapObjects *classes) { MapObjectsClear(&classes->Classes); CArrayTerminate(&classes->Classes); MapObjectsClear(&classes->CustomClasses); CArrayTerminate(&classes->CustomClasses); CA_FOREACH(char *, s, classes->Destructibles) CFREE(*s); CA_FOREACH_END() CArrayTerminate(&classes->Destructibles); CA_FOREACH(char *, s, classes->Bloods) CFREE(*s); CA_FOREACH_END() CArrayTerminate(&classes->Bloods); } int MapObjectsCount(const MapObjects *classes) { return (int)classes->Classes.size + (int)classes->CustomClasses.size; } const Pic *MapObjectGetPic(const MapObject *mo, struct vec2i *offset) { *offset = mo->Offset; return CPicGetPic(&mo->Pic, 0); } bool MapObjectIsTileOK( const MapObject *mo, const Tile *tile, const Tile *tileAbove) { if (tile == NULL) { return false; } if (mo->DrawAbove) { // Check there are no draw above objects CA_FOREACH(const ThingId, tid, tile->things) if (tid->Kind == KIND_OBJECT && ((TObject *)CArrayGet(&gObjs, tid->Id))->Class->DrawAbove) return false; CA_FOREACH_END() } else if (mo->DrawBelow) { // Check there are no draw below objects CA_FOREACH(const ThingId, tid, tile->things) if (tid->Kind == KIND_OBJECT && ((TObject *)CArrayGet(&gObjs, tid->Id))->Class->DrawBelow) return false; CA_FOREACH_END() } else { if (!TileCanWalk(tile)) { return false; } // Check if tile has no things on it, excluding particles and pickups // and non-draw-above/below objects CA_FOREACH(const ThingId, tid, tile->things) if (tid->Kind == KIND_OBJECT) { const TObject *obj = CArrayGet(&gObjs, tid->Id); if (!obj->Class->DrawAbove && !obj->Class->DrawBelow) { return false; } } else if (tid->Kind != KIND_PARTICLE && tid->Kind != KIND_PICKUP) return false; CA_FOREACH_END() } if (MapObjectIsOnWall(mo) && (tileAbove == NULL || tileAbove->Class->Type != TILE_CLASS_WALL)) { return false; } return true; } struct vec2 MapObjectGetPlacementPos( const MapObject *mo, const struct vec2i tilePos) { struct vec2 pos = Vec2CenterOfTile(tilePos); pos = svec2_add(pos, mo->PosOffset); // For on-wall objects, set their position to the top of the tile // This guarantees that they are drawn last if (MapObjectIsOnWall(mo)) { pos.y -= TILE_HEIGHT / 2 + 1; } return pos; } bool MapObjectIsOnWall(const MapObject *mo) { return mo->Flags & (1 << PLACEMENT_ON_WALL); }
1
0.990448
1
0.990448
game-dev
MEDIA
0.941788
game-dev
0.9709
1
0.9709
EllanJiang/GameFramework
8,685
GameFramework/Resource/ResourceManager.ResourceGroupCollection.cs
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2021 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ using System.Collections.Generic; namespace GameFramework.Resource { internal sealed partial class ResourceManager : GameFrameworkModule, IResourceManager { /// <summary> /// 资源组集合。 /// </summary> private sealed class ResourceGroupCollection : IResourceGroupCollection { private readonly ResourceGroup[] m_ResourceGroups; private readonly Dictionary<ResourceName, ResourceInfo> m_ResourceInfos; private readonly HashSet<ResourceName> m_ResourceNames; private long m_TotalLength; private long m_TotalCompressedLength; /// <summary> /// 初始化资源组集合的新实例。 /// </summary> /// <param name="resourceGroups">资源组集合。</param> /// <param name="resourceInfos">资源信息引用。</param> public ResourceGroupCollection(ResourceGroup[] resourceGroups, Dictionary<ResourceName, ResourceInfo> resourceInfos) { if (resourceGroups == null || resourceGroups.Length < 1) { throw new GameFrameworkException("Resource groups is invalid."); } if (resourceInfos == null) { throw new GameFrameworkException("Resource infos is invalid."); } int lastIndex = resourceGroups.Length - 1; for (int i = 0; i < lastIndex; i++) { if (resourceGroups[i] == null) { throw new GameFrameworkException(Utility.Text.Format("Resource group index '{0}' is invalid.", i)); } for (int j = i + 1; j < resourceGroups.Length; j++) { if (resourceGroups[i] == resourceGroups[j]) { throw new GameFrameworkException(Utility.Text.Format("Resource group '{0}' duplicated.", resourceGroups[i].Name)); } } } if (resourceGroups[lastIndex] == null) { throw new GameFrameworkException(Utility.Text.Format("Resource group index '{0}' is invalid.", lastIndex)); } m_ResourceGroups = resourceGroups; m_ResourceInfos = resourceInfos; m_ResourceNames = new HashSet<ResourceName>(); m_TotalLength = 0L; m_TotalCompressedLength = 0L; List<ResourceName> cachedResourceNames = new List<ResourceName>(); foreach (ResourceGroup resourceGroup in m_ResourceGroups) { resourceGroup.InternalGetResourceNames(cachedResourceNames); foreach (ResourceName resourceName in cachedResourceNames) { ResourceInfo resourceInfo = null; if (!m_ResourceInfos.TryGetValue(resourceName, out resourceInfo)) { throw new GameFrameworkException(Utility.Text.Format("Resource info '{0}' is invalid.", resourceName.FullName)); } if (m_ResourceNames.Add(resourceName)) { m_TotalLength += resourceInfo.Length; m_TotalCompressedLength += resourceInfo.CompressedLength; } } } } /// <summary> /// 获取资源组集合是否准备完毕。 /// </summary> public bool Ready { get { return ReadyCount >= TotalCount; } } /// <summary> /// 获取资源组集合包含资源数量。 /// </summary> public int TotalCount { get { return m_ResourceNames.Count; } } /// <summary> /// 获取资源组集合中已准备完成资源数量。 /// </summary> public int ReadyCount { get { int readyCount = 0; foreach (ResourceName resourceName in m_ResourceNames) { ResourceInfo resourceInfo = null; if (m_ResourceInfos.TryGetValue(resourceName, out resourceInfo) && resourceInfo.Ready) { readyCount++; } } return readyCount; } } /// <summary> /// 获取资源组集合包含资源的总大小。 /// </summary> public long TotalLength { get { return m_TotalLength; } } /// <summary> /// 获取资源组集合包含资源压缩后的总大小。 /// </summary> public long TotalCompressedLength { get { return m_TotalCompressedLength; } } /// <summary> /// 获取资源组集合中已准备完成资源的总大小。 /// </summary> public long ReadyLength { get { long readyLength = 0L; foreach (ResourceName resourceName in m_ResourceNames) { ResourceInfo resourceInfo = null; if (m_ResourceInfos.TryGetValue(resourceName, out resourceInfo) && resourceInfo.Ready) { readyLength += resourceInfo.Length; } } return readyLength; } } /// <summary> /// 获取资源组集合中已准备完成资源压缩后的总大小。 /// </summary> public long ReadyCompressedLength { get { long readyCompressedLength = 0L; foreach (ResourceName resourceName in m_ResourceNames) { ResourceInfo resourceInfo = null; if (m_ResourceInfos.TryGetValue(resourceName, out resourceInfo) && resourceInfo.Ready) { readyCompressedLength += resourceInfo.CompressedLength; } } return readyCompressedLength; } } /// <summary> /// 获取资源组集合的完成进度。 /// </summary> public float Progress { get { return m_TotalLength > 0L ? (float)ReadyLength / m_TotalLength : 1f; } } /// <summary> /// 获取资源组集合包含的资源组列表。 /// </summary> /// <returns>资源组包含的资源名称列表。</returns> public IResourceGroup[] GetResourceGroups() { return m_ResourceGroups; } /// <summary> /// 获取资源组集合包含的资源名称列表。 /// </summary> /// <returns>资源组包含的资源名称列表。</returns> public string[] GetResourceNames() { int index = 0; string[] resourceNames = new string[m_ResourceNames.Count]; foreach (ResourceName resourceName in m_ResourceNames) { resourceNames[index++] = resourceName.FullName; } return resourceNames; } /// <summary> /// 获取资源组集合包含的资源名称列表。 /// </summary> /// <param name="results">资源组包含的资源名称列表。</param> public void GetResourceNames(List<string> results) { if (results == null) { throw new GameFrameworkException("Results is invalid."); } results.Clear(); foreach (ResourceName resourceName in m_ResourceNames) { results.Add(resourceName.FullName); } } } } }
1
0.605885
1
0.605885
game-dev
MEDIA
0.460512
game-dev
0.802281
1
0.802281
ifcquery/ifcplusplus
1,482
IfcPlusPlus/src/ifcpp/IFC4X3/include/IfcElectricFlowStorageDeviceTypeEnum.h
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #pragma once #include <vector> #include <map> #include <sstream> #include <string> #include "ifcpp/model/GlobalDefines.h" #include "ifcpp/model/BasicTypes.h" #include "ifcpp/model/BuildingObject.h" namespace IFC4X3 { // TYPE IfcElectricFlowStorageDeviceTypeEnum = ENUMERATION OF (BATTERY ,CAPACITOR ,CAPACITORBANK ,COMPENSATOR ,HARMONICFILTER ,INDUCTOR ,INDUCTORBANK ,RECHARGER ,UPS ,USERDEFINED ,NOTDEFINED); class IFCQUERY_EXPORT IfcElectricFlowStorageDeviceTypeEnum : virtual public BuildingObject { public: enum IfcElectricFlowStorageDeviceTypeEnumEnum { ENUM_BATTERY, ENUM_CAPACITOR, ENUM_CAPACITORBANK, ENUM_COMPENSATOR, ENUM_HARMONICFILTER, ENUM_INDUCTOR, ENUM_INDUCTORBANK, ENUM_RECHARGER, ENUM_UPS, ENUM_USERDEFINED, ENUM_NOTDEFINED }; IfcElectricFlowStorageDeviceTypeEnum() = default; IfcElectricFlowStorageDeviceTypeEnum( IfcElectricFlowStorageDeviceTypeEnumEnum e ) { m_enum = e; } virtual uint32_t classID() const { return 3044747827; } virtual void getStepParameter( std::stringstream& stream, bool is_select_type, size_t precision ) const; static shared_ptr<IfcElectricFlowStorageDeviceTypeEnum> createObjectFromSTEP( const std::string& arg, const BuildingModelMapType<int,shared_ptr<BuildingEntity> >& map, std::stringstream& errorStream, std::unordered_set<int>& entityIdNotFound ); IfcElectricFlowStorageDeviceTypeEnumEnum m_enum; }; }
1
0.812839
1
0.812839
game-dev
MEDIA
0.599933
game-dev
0.531965
1
0.531965
Squalr/Squally
1,970
Source/Scenes/Platformer/Level/Huds/Components/CurrencyDisplay.cpp
#include "CurrencyDisplay.h" #include "cocos/2d/CCSprite.h" #include "Engine/Inventory/CurrencyInventory.h" #include "Engine/Localization/ConstantString.h" #include "Engine/Localization/LocalizedLabel.h" #include "Scenes/Platformer/Inventory/Currencies/IOU.h" #include "Resources/ItemResources.h" using namespace cocos2d; const int CurrencyDisplay::CacheCipher = 0x6942069; CurrencyDisplay* CurrencyDisplay::create() { CurrencyDisplay* instance = new CurrencyDisplay(); instance->autorelease(); return instance; } CurrencyDisplay::CurrencyDisplay() { this->emblem = Sprite::create(ItemResources::Collectables_Currency_IOU); this->value = ConstantString::create("0"); this->label = LocalizedLabel::create(LocalizedLabel::FontStyle::Main, LocalizedLabel::FontSize::H2, this->value); this->emblem->setScale(0.4f); this->label->setAnchorPoint(Vec2(0.0f, 0.5f)); this->label->enableOutline(Color4B::BLACK, 2); this->cachedCurrency = (0 ^ CurrencyDisplay::CacheCipher); this->addChild(this->emblem); this->addChild(this->label); } CurrencyDisplay::~CurrencyDisplay() { } void CurrencyDisplay::onEnter() { super::onEnter(); this->scheduleUpdate(); } void CurrencyDisplay::initializePositions() { super::initializePositions(); this->label->setPosition(Vec2(20.0f, 0.0f)); } void CurrencyDisplay::initializeListeners() { super::initializeListeners(); } void CurrencyDisplay::update(float dt) { super::update(dt); if (this->inventory == nullptr) { return; } int iouCount = this->inventory->getCurrencyCount(IOU::getIOUIdentifier()); if (iouCount != (this->cachedCurrency ^ CurrencyDisplay::CacheCipher)) { this->cachedCurrency = (iouCount ^ CurrencyDisplay::CacheCipher); this->value->setString(std::to_string(iouCount)); } } void CurrencyDisplay::setCurrencyInventory(CurrencyInventory* inventory) { this->value->setString("0"); this->cachedCurrency = (0 ^ CurrencyDisplay::CacheCipher); this->inventory = inventory; }
1
0.524144
1
0.524144
game-dev
MEDIA
0.444139
game-dev
0.789179
1
0.789179
Hekili/hekili
1,453
TheBurningCrusade/Items.lua
-- TheBurningCrusade/Items.lua local addon, ns = ... local Hekili = _G[ addon ] local class, state = Hekili.Class, Hekili.State local all = Hekili.Class.specs[ 0 ] --[[ WiP: Timewarped Trinkets do local timewarped_trinkets = { { "runed_fungalcap", 127184, "shell_of_deterrence", 31771, 20, 1 }, { "icon_of_the_silver_crescent", 129850, "blessing_of_the_silver_crescent", 194645, 20, 1 }, { "essence_of_the_martyr", 129851, "essence_of_the_martyr", 194637, 20, 1 }, { "gnomeregan_autoblocker_601", 129849, "gnome_ingenuity", 194543, 40, 1 }, { "emblem_of_fury", 129937, "lust_for_battle_str", 194638, 20, 1 }, { "bloodlust_brooch", 129848, "lust_for_battle_agi", 194632, 20, 1 }, {} } { "vial_of_the_sunwell", 133462, "vessel_of_the_naaru", 45059, 3600, 1 }, -- vessel_of_the_naaru on-use 45064, 120 sec CD. end ]] all:RegisterAbility( "shadowmoon_insignia", { cast = 0, cooldown = 60, gcd = "off", item = 150526, toggle = "defensives", proc = "health", handler = function () applyBuff( "protectors_vigor" ) end, auras = { protectors_vigor = { id = 244189, duration = 20, max_stack = 1 } } } )
1
0.606812
1
0.606812
game-dev
MEDIA
0.984053
game-dev
0.674376
1
0.674376
semyon422/soundsphere
2,453
ui/views/InputView.lua
local just = require("just") local imgui = require("imgui") local gfx_util = require("gfx_util") local ModalImView = require("ui.imviews.ModalImView") local spherefonts = require("sphere.assets.fonts") local transform = {{1 / 2, -16 / 9 / 2}, 0, 0, {0, 1 / 1080}, {0, 1 / 1080}, 0, 0, 0, 0} local scrollY = 0 local w, h = 768, 1080 / 2 local _w, _h = w / 2, 55 local r = 8 local window_id = "InputView" return ModalImView(function(self, quit) if quit then return true end imgui.setSize(w, h, _w, _h) local inputMode = tostring(self.game.selectController.state.inputMode) local inputs = self.game.inputModel:getInputs(inputMode) if #inputs == 0 then return true end love.graphics.setFont(spherefonts.get("Noto Sans", 24)) love.graphics.replaceTransform(gfx_util.transform(transform)) love.graphics.translate((1920 - w) / 2, (1080 - h) / 2) love.graphics.setColor(0, 0, 0, 0.8) love.graphics.rectangle("fill", 0, 0, w, h, r) love.graphics.setColor(1, 1, 1, 1) just.push() imgui.Container(window_id, w, h, _h / 3, _h * 2, scrollY) local inputModel = self.game.inputModel local font = love.graphics.getFont() local max_vk_width = 0 for i = 1, #inputs do max_vk_width = math.max(max_vk_width, font:getWidth(inputs[i])) end local binds_count = inputModel:getBindsCount(inputMode) local inputIdPattern = "input hotkey %s %s" for i = 1, #inputs do local virtualKey = inputs[i] just.indent(8) imgui.Label("input label" .. i, virtualKey, _h) just.sameline() just.offset(max_vk_width + 16) for j = 1, binds_count + 1 do local hotkey_id = inputIdPattern:format(i, j) local _key, _device, _device_id = inputModel:getKey(inputMode, virtualKey, j) local text = _key or "" local width = font:getWidth(text) local changed, key, device, device_id = imgui.Hotkey(hotkey_id, text, width + _h, _h) if changed then inputModel:setKey(inputMode, virtualKey, j, device, device_id, key) if i + 1 <= #inputs then just.focus(inputIdPattern:format(i + 1, j)) end end just.sameline() if _device and just.mouse_over(hotkey_id, false, "mouse") then self.tooltip = ("%s (%s)"):format(_device, _device_id) end end just.next() end if imgui.button("reset bindings", "reset") then inputModel:resetInputs(inputMode) end just.emptyline(8) scrollY = imgui.Container() just.pop() love.graphics.setColor(1, 1, 1, 1) love.graphics.rectangle("line", 0, 0, w, h, r) end)
1
0.726141
1
0.726141
game-dev
MEDIA
0.7767
game-dev,desktop-app
0.961439
1
0.961439
sjbrown/writing_games_tutorial
14,350
code_examples/example.py
#! /usr/bin/env python ''' Example ''' def Debug( msg ): print msg DIRECTION_UP = 0 DIRECTION_DOWN = 1 DIRECTION_LEFT = 2 DIRECTION_RIGHT = 3 class Event: """this is a superclass for any events that might be generated by an object and sent to the EventManager""" def __init__(self): self.name = "Generic Event" class TickEvent(Event): def __init__(self): self.name = "CPU Tick Event" class QuitEvent(Event): def __init__(self): self.name = "Program Quit Event" class MapBuiltEvent(Event): def __init__(self, gameMap): self.name = "Map Finished Building Event" self.map = gameMap class GameStartedEvent(Event): def __init__(self, game): self.name = "Game Started Event" self.game = game class CharactorMoveRequest(Event): def __init__(self, direction): self.name = "Charactor Move Request" self.direction = direction class CharactorPlaceEvent(Event): """this event occurs when a Charactor is *placed* in a sector, ie it doesn't move there from an adjacent sector.""" def __init__(self, charactor): self.name = "Charactor Placement Event" self.charactor = charactor class CharactorMoveEvent(Event): def __init__(self, charactor): self.name = "Charactor Move Event" self.charactor = charactor #------------------------------------------------------------------------------ class EventManager: """this object is responsible for coordinating most communication between the Model, View, and Controller.""" def __init__(self): from weakref import WeakKeyDictionary self.listeners = WeakKeyDictionary() self.eventQueue= [] #---------------------------------------------------------------------- def RegisterListener( self, listener ): self.listeners[ listener ] = 1 #---------------------------------------------------------------------- def UnregisterListener( self, listener ): if listener in self.listeners: del self.listeners[ listener ] #---------------------------------------------------------------------- def Post( self, event ): if not isinstance(event, TickEvent): Debug( " Message: " + event.name ) for listener in self.listeners: #NOTE: If the weakref has died, it will be #automatically removed, so we don't have #to worry about it. listener.Notify( event ) #------------------------------------------------------------------------------ class KeyboardController: """KeyboardController takes Pygame events generated by the keyboard and uses them to control the model, by sending Requests or to control the Pygame display directly, as with the QuitEvent """ def __init__(self, evManager): self.evManager = evManager self.evManager.RegisterListener( self ) #---------------------------------------------------------------------- def Notify(self, event): if isinstance( event, TickEvent ): #Handle Input Events for event in pygame.event.get(): ev = None if event.type == QUIT: ev = QuitEvent() elif event.type == KEYDOWN \ and event.key == K_ESCAPE: ev = QuitEvent() elif event.type == KEYDOWN \ and event.key == K_UP: direction = DIRECTION_UP ev = CharactorMoveRequest(direction) elif event.type == KEYDOWN \ and event.key == K_DOWN: direction = DIRECTION_DOWN ev = CharactorMoveRequest(direction) elif event.type == KEYDOWN \ and event.key == K_LEFT: direction = DIRECTION_LEFT ev = CharactorMoveRequest(direction) elif event.type == KEYDOWN \ and event.key == K_RIGHT: direction = DIRECTION_RIGHT ev = CharactorMoveRequest(direction) if ev: self.evManager.Post( ev ) #------------------------------------------------------------------------------ class CPUSpinnerController: """...""" def __init__(self, evManager): self.evManager = evManager self.evManager.RegisterListener( self ) self.keepGoing = 1 #---------------------------------------------------------------------- def Run(self): while self.keepGoing: event = TickEvent() self.evManager.Post( event ) #---------------------------------------------------------------------- def Notify(self, event): if isinstance( event, QuitEvent ): #this will stop the while loop from running self.keepGoing = False import pygame from pygame.locals import * #------------------------------------------------------------------------------ class SectorSprite(pygame.sprite.Sprite): def __init__(self, sector, group=None): pygame.sprite.Sprite.__init__(self, group) self.image = pygame.Surface( (128,128) ) self.image.fill( (0,255,128) ) self.sector = sector #------------------------------------------------------------------------------ class CharactorSprite(pygame.sprite.Sprite): def __init__(self, group=None): pygame.sprite.Sprite.__init__(self, group) charactorSurf = pygame.Surface( (64,64) ) charactorSurf = charactorSurf.convert_alpha() charactorSurf.fill((0,0,0,0)) #make transparent pygame.draw.circle( charactorSurf, (255,0,0), (32,32), 32 ) self.image = charactorSurf self.rect = charactorSurf.get_rect() self.moveTo = None #---------------------------------------------------------------------- def update(self): if self.moveTo: self.rect.center = self.moveTo self.moveTo = None #------------------------------------------------------------------------------ class PygameView: def __init__(self, evManager): self.evManager = evManager self.evManager.RegisterListener( self ) pygame.init() self.window = pygame.display.set_mode( (424,440) ) pygame.display.set_caption( 'Example Game' ) self.background = pygame.Surface( self.window.get_size() ) self.background.fill( (0,0,0) ) font = pygame.font.Font(None, 30) text = """Press SPACE BAR to start""" textImg = font.render( text, 1, (255,0,0)) self.background.blit( textImg, (0,0) ) self.window.blit( self.background, (0,0) ) pygame.display.flip() self.backSprites = pygame.sprite.RenderUpdates() self.frontSprites = pygame.sprite.RenderUpdates() #---------------------------------------------------------------------- def ShowMap(self, gameMap): # clear the screen first self.background.fill( (0,0,0) ) self.window.blit( self.background, (0,0) ) pygame.display.flip() # use this squareRect as a cursor and go through the # columns and rows and assign the rect # positions of the SectorSprites squareRect = pygame.Rect( (-128,10, 128,128 ) ) column = 0 for sector in gameMap.sectors: if column < 3: squareRect = squareRect.move( 138,0 ) else: column = 0 squareRect = squareRect.move( -(138*2), 138 ) column += 1 newSprite = SectorSprite( sector, self.backSprites ) newSprite.rect = squareRect newSprite = None #---------------------------------------------------------------------- def ShowCharactor(self, charactor): sector = charactor.sector charactorSprite = CharactorSprite( self.frontSprites ) sectorSprite = self.GetSectorSprite( sector ) charactorSprite.rect.center = sectorSprite.rect.center #---------------------------------------------------------------------- def MoveCharactor(self, charactor): charactorSprite = self.GetCharactorSprite( charactor ) sector = charactor.sector sectorSprite = self.GetSectorSprite( sector ) charactorSprite.moveTo = sectorSprite.rect.center #---------------------------------------------------------------------- def GetCharactorSprite(self, charactor): #there will be only one for s in self.frontSprites: return s return None #---------------------------------------------------------------------- def GetSectorSprite(self, sector): for s in self.backSprites: if hasattr(s, "sector") and s.sector == sector: return s #---------------------------------------------------------------------- def Notify(self, event): if isinstance( event, TickEvent ): #Draw Everything self.backSprites.clear( self.window, self.background ) self.frontSprites.clear( self.window, self.background ) self.backSprites.update() self.frontSprites.update() dirtyRects1 = self.backSprites.draw( self.window ) dirtyRects2 = self.frontSprites.draw( self.window ) dirtyRects = dirtyRects1 + dirtyRects2 pygame.display.update( dirtyRects ) elif isinstance( event, MapBuiltEvent ): gameMap = event.map self.ShowMap( gameMap ) elif isinstance( event, CharactorPlaceEvent ): self.ShowCharactor( event.charactor ) elif isinstance( event, CharactorMoveEvent ): self.MoveCharactor( event.charactor ) #------------------------------------------------------------------------------ class Game: """...""" STATE_PREPARING = 'preparing' STATE_RUNNING = 'running' STATE_PAUSED = 'paused' #---------------------------------------------------------------------- def __init__(self, evManager): self.evManager = evManager self.evManager.RegisterListener( self ) self.state = Game.STATE_PREPARING self.players = [ Player(evManager) ] self.map = Map( evManager ) #---------------------------------------------------------------------- def Start(self): self.map.Build() self.state = Game.STATE_RUNNING ev = GameStartedEvent( self ) self.evManager.Post( ev ) #---------------------------------------------------------------------- def Notify(self, event): if isinstance( event, TickEvent ): if self.state == Game.STATE_PREPARING: self.Start() #------------------------------------------------------------------------------ class Player(object): """...""" def __init__(self, evManager): self.evManager = evManager self.game = None self.name = "" self.evManager.RegisterListener( self ) self.charactors = [ Charactor(evManager) ] #---------------------------------------------------------------------- def __str__(self): return '<Player %s %s>' % (self.name, id(self)) #---------------------------------------------------------------------- def Notify(self, event): pass #------------------------------------------------------------------------------ class Charactor: """...""" STATE_INACTIVE = 0 STATE_ACTIVE = 1 def __init__(self, evManager): self.evManager = evManager self.evManager.RegisterListener( self ) self.sector = None self.state = Charactor.STATE_INACTIVE #---------------------------------------------------------------------- def __str__(self): return '<Charactor %s>' % id(self) #---------------------------------------------------------------------- def Move(self, direction): if self.state == Charactor.STATE_INACTIVE: return if self.sector.MovePossible( direction ): newSector = self.sector.neighbors[direction] self.sector = newSector ev = CharactorMoveEvent( self ) self.evManager.Post( ev ) #---------------------------------------------------------------------- def Place(self, sector): self.sector = sector self.state = Charactor.STATE_ACTIVE ev = CharactorPlaceEvent( self ) self.evManager.Post( ev ) #---------------------------------------------------------------------- def Notify(self, event): if isinstance( event, GameStartedEvent ): gameMap = event.game.map self.Place( gameMap.sectors[gameMap.startSectorIndex] ) elif isinstance( event, CharactorMoveRequest ): self.Move( event.direction ) #------------------------------------------------------------------------------ class Map: """...""" STATE_PREPARING = 0 STATE_BUILT = 1 #---------------------------------------------------------------------- def __init__(self, evManager): self.evManager = evManager #self.evManager.RegisterListener( self ) self.state = Map.STATE_PREPARING self.sectors = [] self.startSectorIndex = 0 #---------------------------------------------------------------------- def Build(self): for i in range(9): self.sectors.append( Sector(self.evManager) ) self.sectors[3].neighbors[DIRECTION_UP] = self.sectors[0] self.sectors[4].neighbors[DIRECTION_UP] = self.sectors[1] self.sectors[5].neighbors[DIRECTION_UP] = self.sectors[2] self.sectors[6].neighbors[DIRECTION_UP] = self.sectors[3] self.sectors[7].neighbors[DIRECTION_UP] = self.sectors[4] self.sectors[8].neighbors[DIRECTION_UP] = self.sectors[5] self.sectors[0].neighbors[DIRECTION_DOWN] = self.sectors[3] self.sectors[1].neighbors[DIRECTION_DOWN] = self.sectors[4] self.sectors[2].neighbors[DIRECTION_DOWN] = self.sectors[5] self.sectors[3].neighbors[DIRECTION_DOWN] = self.sectors[6] self.sectors[4].neighbors[DIRECTION_DOWN] = self.sectors[7] self.sectors[5].neighbors[DIRECTION_DOWN] = self.sectors[8] self.sectors[1].neighbors[DIRECTION_LEFT] = self.sectors[0] self.sectors[2].neighbors[DIRECTION_LEFT] = self.sectors[1] self.sectors[4].neighbors[DIRECTION_LEFT] = self.sectors[3] self.sectors[5].neighbors[DIRECTION_LEFT] = self.sectors[4] self.sectors[7].neighbors[DIRECTION_LEFT] = self.sectors[6] self.sectors[8].neighbors[DIRECTION_LEFT] = self.sectors[7] self.sectors[0].neighbors[DIRECTION_RIGHT] = self.sectors[1] self.sectors[1].neighbors[DIRECTION_RIGHT] = self.sectors[2] self.sectors[3].neighbors[DIRECTION_RIGHT] = self.sectors[4] self.sectors[4].neighbors[DIRECTION_RIGHT] = self.sectors[5] self.sectors[6].neighbors[DIRECTION_RIGHT] = self.sectors[7] self.sectors[7].neighbors[DIRECTION_RIGHT] = self.sectors[8] self.state = Map.STATE_BUILT ev = MapBuiltEvent( self ) self.evManager.Post( ev ) #------------------------------------------------------------------------------ class Sector: """...""" def __init__(self, evManager): self.evManager = evManager #self.evManager.RegisterListener( self ) self.neighbors = range(4) self.neighbors[DIRECTION_UP] = None self.neighbors[DIRECTION_DOWN] = None self.neighbors[DIRECTION_LEFT] = None self.neighbors[DIRECTION_RIGHT] = None #---------------------------------------------------------------------- def MovePossible(self, direction): if self.neighbors[direction]: return 1 #------------------------------------------------------------------------------ def main(): """...""" evManager = EventManager() keybd = KeyboardController( evManager ) spinner = CPUSpinnerController( evManager ) pygameView = PygameView( evManager ) game = Game( evManager ) spinner.Run() if __name__ == "__main__": main()
1
0.666183
1
0.666183
game-dev
MEDIA
0.949003
game-dev
0.756697
1
0.756697
GarageGames/Torque2D
7,638
engine/source/spine/SkeletonBounds.c
/****************************************************************************** * Spine Runtimes Software License * Version 2 * * Copyright (c) 2013, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to install, execute and perform the Spine Runtimes * Software (the "Software") solely for internal use. Without the written * permission of Esoteric Software, you may not (a) modify, translate, adapt or * otherwise create derivative works, improvements of the Software or develop * new applications using the Software or (b) remove, delete, alter or obscure * any trademarks or any copyright, trademark, patent or other intellectual * property or proprietary rights notices on or in the Software, including * any copy thereof. Redistributions in binary or source form must include * this license and terms. THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE * "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 ESOTERIC SOFTARE BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #include <spine/SkeletonBounds.h> #include <limits.h> #include <spine/extension.h> spPolygon* spPolygon_create (int capacity) { spPolygon* self = NEW(spPolygon); self->capacity = capacity; CONST_CAST(float*, self->vertices) = MALLOC(float, capacity); return self; } void spPolygon_dispose (spPolygon* self) { FREE(self->vertices); FREE(self); } int/*bool*/spPolygon_containsPoint (spPolygon* self, float x, float y) { int prevIndex = self->count - 2; int inside = 0; int i; for (i = 0; i < self->count; i += 2) { float vertexY = self->vertices[i + 1]; float prevY = self->vertices[prevIndex + 1]; if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) { float vertexX = self->vertices[i]; if (vertexX + (y - vertexY) / (prevY - vertexY) * (self->vertices[prevIndex] - vertexX) < x) inside = !inside; } prevIndex = i; } return inside; } int/*bool*/spPolygon_intersectsSegment (spPolygon* self, float x1, float y1, float x2, float y2) { float width12 = x1 - x2, height12 = y1 - y2; float det1 = x1 * y2 - y1 * x2; float x3 = self->vertices[self->count - 2], y3 = self->vertices[self->count - 1]; int i; for (i = 0; i < self->count; i += 2) { float x4 = self->vertices[i], y4 = self->vertices[i + 1]; float det2 = x3 * y4 - y3 * x4; float width34 = x3 - x4, height34 = y3 - y4; float det3 = width12 * height34 - height12 * width34; float x = (det1 * width34 - width12 * det2) / det3; if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) { float y = (det1 * height34 - height12 * det2) / det3; if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) return 1; } x3 = x4; y3 = y4; } return 0; } /**/ typedef struct { spSkeletonBounds super; int capacity; } _spSkeletonBounds; spSkeletonBounds* spSkeletonBounds_create () { return SUPER(NEW(_spSkeletonBounds)); } void spSkeletonBounds_dispose (spSkeletonBounds* self) { int i; for (i = 0; i < SUB_CAST(_spSkeletonBounds, self)->capacity; ++i) if (self->polygons[i]) spPolygon_dispose(self->polygons[i]); FREE(self->polygons); FREE(self->boundingBoxes); FREE(self); } void spSkeletonBounds_update (spSkeletonBounds* self, spSkeleton* skeleton, int/*bool*/updateAabb) { int i; _spSkeletonBounds* internal = SUB_CAST(_spSkeletonBounds, self); if (internal->capacity < skeleton->slotCount) { spPolygon** newPolygons; FREE(self->boundingBoxes); self->boundingBoxes = MALLOC(spBoundingBoxAttachment*, skeleton->slotCount); newPolygons = CALLOC(spPolygon*, skeleton->slotCount); memcpy(newPolygons, self->polygons, internal->capacity); FREE(self->polygons); self->polygons = newPolygons; internal->capacity = skeleton->slotCount; } self->minX = (float)INT_MAX; self->minY = (float)INT_MAX; self->maxX = (float)INT_MIN; self->maxY = (float)INT_MIN; self->count = 0; for (i = 0; i < skeleton->slotCount; ++i) { spPolygon* polygon; spBoundingBoxAttachment* boundingBox; spSlot* slot = skeleton->slots[i]; spAttachment* attachment = slot->attachment; if (!attachment || attachment->type != ATTACHMENT_BOUNDING_BOX) continue; boundingBox = (spBoundingBoxAttachment*)attachment; self->boundingBoxes[self->count] = boundingBox; polygon = self->polygons[self->count]; if (!polygon || polygon->capacity < boundingBox->verticesCount) { if (polygon) spPolygon_dispose(polygon); self->polygons[self->count] = polygon = spPolygon_create(boundingBox->verticesCount); } polygon->count = boundingBox->verticesCount; spBoundingBoxAttachment_computeWorldVertices(boundingBox, skeleton->x, skeleton->y, slot->bone, polygon->vertices); if (updateAabb) { int ii = 0; for (; ii < polygon->count; ii += 2) { float x = polygon->vertices[ii]; float y = polygon->vertices[ii + 1]; if (x < self->minX) self->minX = x; if (y < self->minY) self->minY = y; if (x > self->maxX) self->maxX = x; if (y > self->maxY) self->maxY = y; } } ++self->count; } } int/*bool*/spSkeletonBounds_aabbContainsPoint (spSkeletonBounds* self, float x, float y) { return x >= self->minX && x <= self->maxX && y >= self->minY && y <= self->maxY; } int/*bool*/spSkeletonBounds_aabbIntersectsSegment (spSkeletonBounds* self, float x1, float y1, float x2, float y2) { float m, x, y; if ((x1 <= self->minX && x2 <= self->minX) || (y1 <= self->minY && y2 <= self->minY) || (x1 >= self->maxX && x2 >= self->maxX) || (y1 >= self->maxY && y2 >= self->maxY)) return 0; m = (y2 - y1) / (x2 - x1); y = m * (self->minX - x1) + y1; if (y > self->minY && y < self->maxY) return 1; y = m * (self->maxX - x1) + y1; if (y > self->minY && y < self->maxY) return 1; x = (self->minY - y1) / m + x1; if (x > self->minX && x < self->maxX) return 1; x = (self->maxY - y1) / m + x1; if (x > self->minX && x < self->maxX) return 1; return 0; } int/*bool*/spSkeletonBounds_aabbIntersectsSkeleton (spSkeletonBounds* self, spSkeletonBounds* bounds) { return self->minX < bounds->maxX && self->maxX > bounds->minX && self->minY < bounds->maxY && self->maxY > bounds->minY; } spBoundingBoxAttachment* spSkeletonBounds_containsPoint (spSkeletonBounds* self, float x, float y) { int i; for (i = 0; i < self->count; ++i) if (spPolygon_containsPoint(self->polygons[i], x, y)) return self->boundingBoxes[i]; return 0; } spBoundingBoxAttachment* spSkeletonBounds_intersectsSegment (spSkeletonBounds* self, float x1, float y1, float x2, float y2) { int i; for (i = 0; i < self->count; ++i) if (spPolygon_intersectsSegment(self->polygons[i], x1, y1, x2, y2)) return self->boundingBoxes[i]; return 0; } spPolygon* spSkeletonBounds_getPolygon (spSkeletonBounds* self, spBoundingBoxAttachment* boundingBox) { int i; for (i = 0; i < self->count; ++i) if (self->boundingBoxes[i] == boundingBox) return self->polygons[i]; return 0; }
1
0.865853
1
0.865853
game-dev
MEDIA
0.586857
game-dev,graphics-rendering
0.990879
1
0.990879
pubnub/c-sharp
2,292
src/Api/PubnubApi/EndPoint/Presence/PresenceOperation.cs
using System; using System.Collections.Generic; using System.Globalization; using PubnubApi.EventEngine.Core; using PubnubApi.EventEngine.Presence; using PubnubApi.EventEngine.Presence.Events; namespace PubnubApi.EndPoint { public class PresenceOperation<T> { private PresenceEventEngineFactory presenceEventEngineFactory; private PNConfiguration configuration; private PresenceEventEngine presenceEventEngine; private IPubnubUnitTest unit; public PresenceOperation(Pubnub instance, string instanceId, PNConfiguration configuration, TokenManager tokenManager, IPubnubUnitTest unit, PresenceEventEngineFactory presenceEventEngineFactory) { this.unit = unit; this.configuration = configuration; this.presenceEventEngineFactory = presenceEventEngineFactory; if (unit != null) { unit.PresenceActivityList = new List<KeyValuePair<string, string>>(); } if (this.presenceEventEngineFactory.HasEventEngine(instanceId)) { presenceEventEngine = this.presenceEventEngineFactory.GetEventEngine(instanceId); } else { presenceEventEngine = this.presenceEventEngineFactory.InitializeEventEngine<T>(instanceId, instance, tokenManager); presenceEventEngine.OnEffectDispatch += OnEffectDispatch; presenceEventEngine.OnEventQueued += OnEventQueued; } } private void OnEventQueued(IEvent e) { try { unit?.PresenceActivityList.Add(new KeyValuePair<string, string>("event", e?.Name)); } catch (Exception ex) { configuration.Logger?.Error( $"presence event engine OnEventQueued : CurrentState = {presenceEventEngine.CurrentState.GetType().Name} => EXCEPTION = {ex}"); } } private void OnEffectDispatch(IEffectInvocation invocation) { try { unit?.PresenceActivityList.Add(new KeyValuePair<string, string>("invocation", invocation?.Name)); } catch (Exception ex) { configuration.Logger?.Error( $"presence event engine OnEffectDispatch : CurrentState = {presenceEventEngine.CurrentState.GetType().Name} => EXCEPTION = {ex}"); } } public void Start(string[] channels, string[] channelGroups) { this.presenceEventEngine.EventQueue.Enqueue(new JoinedEvent() { Input = new EventEngine.Presence.Common.PresenceInput() { Channels = channels, ChannelGroups = channelGroups } }); } } }
1
0.698713
1
0.698713
game-dev
MEDIA
0.553893
game-dev,networking
0.744497
1
0.744497
luttje/Key2Joy
1,873
Core/Key2Joy.Core/LowLevelInput/XInput/XInputState.cs
using System; using System.Runtime.InteropServices; namespace Key2Joy.LowLevelInput.XInput; /// <summary> /// Represents the state of an Xbox 360 controller. /// </summary> /// <remarks> /// The <see cref="PacketNumber"/> member is incremented only if the status of the controller has changed since the controller was last polled. /// </remarks> [StructLayout(LayoutKind.Explicit)] public struct XInputState : IEquatable<XInputState> { /// <summary> /// State packet number. Indicates whether there have been any changes in the state of the controller. /// If the <see cref="PacketNumber"/> member is the same in sequentially returned XInputState structures, the controller state has not changed. /// </summary> [FieldOffset(0)] public int PacketNumber; /// <summary> /// XINPUT_GAMEPAD structure containing the current state of an Xbox 360 Controller. /// </summary> [FieldOffset(4)] public XInputGamePad Gamepad; /// <summary> /// Copies the state from another XInputState object. /// </summary> /// <param name="source">The source XInputState to copy from.</param> public void Copy(XInputState source) { this.PacketNumber = source.PacketNumber; this.Gamepad.Copy(source.Gamepad); } /// <inheritdoc/> public override readonly bool Equals(object obj) => obj is XInputState state && this.Equals(state); /// <inheritdoc/> public readonly bool Equals(XInputState other) => this.PacketNumber == other.PacketNumber && this.Gamepad.Equals(other.Gamepad); /// <inheritdoc/> public override int GetHashCode() { var hashCode = -1459879740; hashCode = (hashCode * -1521134295) + this.PacketNumber.GetHashCode(); hashCode = (hashCode * -1521134295) + this.Gamepad.GetHashCode(); return hashCode; } }
1
0.936906
1
0.936906
game-dev
MEDIA
0.796029
game-dev
0.760973
1
0.760973
ecmwf/magics
1,759
src/attributes/LegendMethodAttributes.cc
/****************************** LICENSE ******************************* * (C) Copyright 1996-2017 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. ******************************* LICENSE *******************************/ /*! \\file LegendMethodAttributes.h \\brief Definition of LegendMethod Attributes class. This file is automatically generated. Do Not Edit! */ #include "LegendMethodAttributes.h" #include "MagicsParameter.h" #include "ParameterSettings.h" using namespace magics; LegendMethodAttributes::LegendMethodAttributes() { } LegendMethodAttributes::~LegendMethodAttributes() { } void LegendMethodAttributes::set(const std::map<string, string>& params) { vector<string> prefix(1); int i = 0; prefix[i++] = ""; } void LegendMethodAttributes::copy(const LegendMethodAttributes& other) { } bool LegendMethodAttributes::accept(const string& node) { if ( magCompare(node, "") ) return true; return false; } void LegendMethodAttributes::set(const XmlNode& node) { bool apply = false; if ( this->accept(node.name()) == false ) return; if ( magCompare(node.name(), "") ) apply = true; if ( apply ) set(node.attributes()); else { } for (auto &elt : node.elements()) { } } void LegendMethodAttributes::print(ostream& out) const { out << "Attributes["; out << "]" << "\n"; } void LegendMethodAttributes::toxml(ostream& out) const { out << "\"\""; }
1
0.802402
1
0.802402
game-dev
MEDIA
0.496765
game-dev
0.604363
1
0.604363
Jakz/openmom
3,866
src/ui/animations/Animations.h
// // Animations.h // OpenMoM // // Created by Jack on 7/19/14. // Copyright (c) 2014 Jack. All rights reserved. // #ifndef _ANIMATIONS_H_ #define _ANIMATIONS_H_ #include "common/Common.h" #include "ui/EventListener.h" #include "game/world/Pathfind.h" #include "gfx/Gfx.h" #include <list> class LocalPlayer; namespace anims { class Animation : public EventListener { protected: bool forceFinished; std::unique_ptr<Animation> nextAnim; virtual void step() = 0; public: Animation() : forceFinished(false) { } virtual bool hasFinished() = 0; std::unique_ptr<Animation>& next() { return nextAnim; } void setNext(Animation *animation) { this->nextAnim = std::unique_ptr<Animation>(animation); } void finish() { forceFinished = true; } virtual void reset() = 0; virtual void doStep() = 0; virtual ~Animation() { } }; class InstantAnimation : public Animation { protected: bool _called; public: InstantAnimation() : _called(false) { } void reset() override { _called = false; } void doStep() override { _called = true; } bool hasFinished() override { return _called; } }; class LambdaAnimation : public InstantAnimation { protected: std::function<void(void)> lambda; public: LambdaAnimation(std::function<void(void)> lambda) : lambda(lambda) { } void doStep() override { lambda(); InstantAnimation::doStep(); } }; class DiscreteAnimation : public Animation { protected: u32 start; u32 duration; u32 elapsed; public: DiscreteAnimation(u32 duration) : start(Gfx::fticks), duration(duration), elapsed(0) { } void reset() override { start = Gfx::fticks; } bool hasFinished() override { return forceFinished || elapsed >= duration; } void doStep() override { elapsed = Gfx::fticks - start; if (!hasFinished()) step(); } }; class ContinuousAnimation : public Animation { protected: u32 start; u32 duration; void setDuration(u32 duration) { this->duration = duration; } public: ContinuousAnimation(u32 duration) : start(Gfx::ticks), duration(duration) { } void reset() override { start = Gfx::ticks; } float position() { return std::min(1.0f, (Gfx::ticks - start) / (float)duration); } void doStep() override { step(); } bool hasFinished() override { return forceFinished || Gfx::ticks > duration + start; } }; class ContinuousEndlessAnimation : public ContinuousAnimation { protected: public: ContinuousEndlessAnimation(u32 duration) : ContinuousAnimation(duration) { } void reset() override { start = Gfx::ticks; } bool hasFinished() override { return forceFinished; } }; class Blink : public ContinuousAnimation { private: const Color color; const SDL_Rect rect; u8 maxAlpha; // TODO: true colors and maybe check duration/alpha static const Color SCHOOL_COLORS[]; public: Blink(School school) : Blink(800, SCHOOL_COLORS[school], {0,0,320,200}, 220) { } Blink(Color color, SDL_Rect rect, u8 maxAlpha) : Blink(800, color, rect, maxAlpha) { } Blink(u32 duration, Color color, SDL_Rect rect, u8 maxAlpha) : ContinuousAnimation(duration), color(color), rect(rect), maxAlpha(maxAlpha) { } void step() override; }; class UnitMovement : public ContinuousAnimation { private: s16 tx, ty; s16 sx, sy; const Army* army; std::list<pathfind::Route::step_type> moves; LocalPlayer *player; public: UnitMovement(LocalPlayer* player, const Army* army, const decltype(moves)& moves); void step() override; bool hasFinished() override; }; } #include "SpellEffectAnim.h" #endif
1
0.858962
1
0.858962
game-dev
MEDIA
0.421552
game-dev,desktop-app
0.641325
1
0.641325
Protocentral/AFE4490_Oximeter
3,569
gui/Libraries/G4P/examples/G4P_Timer/G4P_Timer.pde
/* Balls of Vesuvius. A simple program to demonstrate the use of the GTimer class which is part of the G4P (GUI for Processing) library. for Processing V2 and V3 (c) 2015 Peter Lager */ import g4p_controls.*; GSlider sdrRate; GButton btnStart, btnStop; GTimer timer; ArrayList liveBalls, deadBalls; int rate; PImage rear, front; void setup() { size(768, 600); // Create 2 buttons to start and stop the balls btnStart = new GButton(this, 10, 10, 100, 20, "Start"); btnStop = new GButton(this, 120, 10, 100, 20, "Stop"); // Create a slider to control rate of balls erupted. sdrRate = new GSlider(this, 230, 10, 360, 20, 10); sdrRate.setLimits(50, 10, 120); // (init, min, max) sdrRate.setEasing(5); // Get timer interval based on initial slider value and limits rate = 130 - sdrRate.getValueI(); // Create a GTimer object that will call the method // fireBall // Parameter 1 : the PApplet class i.e. 'this' // 2 : the object that has the method to call // 3 : the name of the method (parameterless) to call // 4 : the interval in millisecs bewteen method calls timer = new GTimer(this, this, "fireBall", rate); // Balls in the air alive liveBalls = new ArrayList(2000); // Balls that are below the level of the window deadBalls = new ArrayList(100); front = loadImage("vfront.png"); rear = loadImage("vrear.jpg"); // try and keep it at 30fps frameRate(30); // Register the pre() method for this class. Pick the line // to match the version of Processing being used. // registerPre(this); // Use this for PS 1.5.1 registerMethod("pre", this); // Use this for PS 2.0b6 } // This method is now called before each call to draw() public void pre() { Ball b; int i; // Update all live balls for (i = 0; i < liveBalls.size(); i++) { b = (Ball)liveBalls.get(i); b.update(); // See if this ball should die if so remember it if (b.y > height + 20) deadBalls.add(b); } // Remove dead balls from the list of live balls for (i = 0; i < deadBalls.size(); i++) { liveBalls.remove(deadBalls.get(i)); } // Done with dead balls deadBalls.clear(); } void draw() { int i; Ball b; background(rear); for (i = 0; i < liveBalls.size(); i++) { b = (Ball)liveBalls.get(i); b.display(); } image(front, 0, 0); } // This is called when the user drags on the slider void handleSliderEvents(GValueControl slider, GEvent event) { rate = 130 - sdrRate.getValueI(); timer.setInterval(rate); } // This method is called when a button is clicked void handleButtonEvents(GButton button, GEvent event) { if (button == btnStart && event == GEvent.CLICKED) timer.start(); if (button == btnStop && event == GEvent.CLICKED) timer.stop(); } // This method is called by the timer void fireBall(GTimer timer) { Ball ball = new Ball(); liveBalls.add(ball); } // Simple class to represent a ball class Ball { public float radius; public int col; public float x, y; public float vx, vy; public float gravity = 0.07f; public float drag = 0.99; public float shrink = 0.999; public Ball() { x = random(500, 540); y = 290; col = color(random(200, 255), random(20, 55), 0); radius = random(3, 10); vx = random(-3.0, 1.9); vy = random(5.5, 8.2); } public void update() { x += vx; y -= vy; vy -= gravity; if (vy < 0) vx *= drag; radius *= shrink; } public void display() { noStroke(); fill(col); ellipse(x, y, radius, radius); } }
1
0.537948
1
0.537948
game-dev
MEDIA
0.505902
game-dev
0.814896
1
0.814896
ServerOpenMC/PluginV2
5,544
src/main/java/fr/openmc/core/features/city/sub/mayor/perks/basic/DemonFruitPerk.java
package fr.openmc.core.features.city.sub.mayor.perks.basic; import fr.openmc.core.features.city.City; import fr.openmc.core.features.city.CityManager; import fr.openmc.core.features.city.sub.mayor.managers.MayorManager; import fr.openmc.core.features.city.sub.mayor.managers.PerkManager; import fr.openmc.core.features.city.sub.mayor.perks.Perks; import org.bukkit.NamespacedKey; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeModifier; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; public class DemonFruitPerk implements Listener { private static final NamespacedKey RANGE_MODIFIER_KEY = new NamespacedKey("mayor_perks","demon_fruit"); private static final double BONUS_VALUE = 1.0; /** * Applies the reach bonus to the player. * * @param player The player to apply the bonus to. */ public static void applyReachBonus(Player player) { if (player.getAttribute(Attribute.ENTITY_INTERACTION_RANGE) == null && player.getAttribute(Attribute.BLOCK_INTERACTION_RANGE) == null) { return; } player.getAttribute(Attribute.ENTITY_INTERACTION_RANGE) .getModifiers() .forEach(modifierEntity -> { if (modifierEntity.getKey().equals(RANGE_MODIFIER_KEY)) { player.getAttribute(Attribute.ENTITY_INTERACTION_RANGE).removeModifier(modifierEntity); } }); AttributeModifier modifierEntity = new AttributeModifier(RANGE_MODIFIER_KEY, BONUS_VALUE, AttributeModifier.Operation.ADD_NUMBER); player.getAttribute(Attribute.ENTITY_INTERACTION_RANGE).addModifier(modifierEntity); player.getAttribute(Attribute.BLOCK_INTERACTION_RANGE) .getModifiers() .forEach(modifierBlock -> { if (modifierBlock.getKey().equals(RANGE_MODIFIER_KEY)) { player.getAttribute(Attribute.BLOCK_INTERACTION_RANGE).removeModifier(modifierBlock); } }); AttributeModifier modifierBlock = new AttributeModifier(RANGE_MODIFIER_KEY, BONUS_VALUE, AttributeModifier.Operation.ADD_NUMBER); player.getAttribute(Attribute.BLOCK_INTERACTION_RANGE).addModifier(modifierBlock); } /** * Removes the reach bonus from the player. * * @param player The player to remove the bonus from. */ public static void removeReachBonus(Player player) { if (player.getAttribute(Attribute.ENTITY_INTERACTION_RANGE) == null && player.getAttribute(Attribute.BLOCK_INTERACTION_RANGE) == null) return; try { player.getAttribute(Attribute.ENTITY_INTERACTION_RANGE) .getModifiers() .stream() .filter(modifier -> modifier.getKey().equals(RANGE_MODIFIER_KEY)) .forEach(modifier -> { player.getAttribute(Attribute.ENTITY_INTERACTION_RANGE).removeModifier(modifier); }); player.getAttribute(Attribute.BLOCK_INTERACTION_RANGE) .getModifiers() .stream() .filter(modifier -> modifier.getKey().equals(RANGE_MODIFIER_KEY)) .forEach(modifier -> { player.getAttribute(Attribute.BLOCK_INTERACTION_RANGE).removeModifier(modifier); }); } catch (Exception e) { throw new RuntimeException(e); } } /** * Checks if the player has the reach attribute bonus. * * @param player The player to check. * @return true if the player has the reach attribute bonus, false otherwise. */ public static boolean hasRangeAttribute(Player player) { if (player.getAttribute(Attribute.ENTITY_INTERACTION_RANGE) == null && player.getAttribute(Attribute.BLOCK_INTERACTION_RANGE) == null) return false; double baseValueEntity = player.getAttribute(Attribute.ENTITY_INTERACTION_RANGE).getBaseValue(); double currentValueEntity = player.getAttribute(Attribute.ENTITY_INTERACTION_RANGE).getValue(); double expectedValueEntity = baseValueEntity + BONUS_VALUE; double baseValueBlock = player.getAttribute(Attribute.BLOCK_INTERACTION_RANGE).getBaseValue(); double currentValueBlock = player.getAttribute(Attribute.BLOCK_INTERACTION_RANGE).getValue(); double expectedValueBlock = baseValueBlock + BONUS_VALUE; return Math.abs(currentValueEntity - expectedValueEntity) < 0.01 && Math.abs(currentValueBlock - expectedValueBlock) < 0.01; } @EventHandler public void onJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); int phase = MayorManager.phaseMayor; if (phase == 2) { City playerCity = CityManager.getPlayerCity(player.getUniqueId()); if (playerCity == null) return; if (!PerkManager.hasPerk(playerCity.getMayor(), Perks.FRUIT_DEMON.getId())) return; if (!hasRangeAttribute(player)) applyReachBonus(player); } else { removeReachBonus(player); } } @EventHandler public void onQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); if (hasRangeAttribute(player)) { removeReachBonus(player); } } }
1
0.861401
1
0.861401
game-dev
MEDIA
0.947793
game-dev
0.906553
1
0.906553
LordOfDragons/dragengine
2,475
src/modules/scripting/dragonscript/src/deDSEngineManager.h
/* * MIT License * * Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef _DEDSENGINEMANAGER_H_ #define _DEDSENGINEMANAGER_H_ #include <dragengine/common/string/decString.h> #include <dragengine/common/file/decPath.h> #include <libdscript/libdscript.h> class deScriptingDragonScript; class decPath; /** * DragonScript Engine Manager. */ class deDSEngineManager : public dsDefaultEngineManager{ private: deScriptingDragonScript &pDS; const decPath pPathContrib; const decPath pVfsPathContrib; public: /** \name Constructors and Destructors */ /*@{*/ /** Create dragonscript engine manager. */ deDSEngineManager(deScriptingDragonScript &ds, const decPath &pathContrib, const decPath &vfsPathContrib); /** Clean up dragonscript engine manager. */ ~deDSEngineManager() override; /*@}*/ /** \name Management */ /*@{*/ void OutputMessage(const char *message) override; void OutputWarning(const char *message, int warnID, dsScriptSource *script, int line, int position) override; void OutputWarningMore(const char *message) override; void OutputError(const char *message, int errorID, dsScriptSource *script, int line, int position) override; void OutputErrorMore(const char *message) override; bool ContinueParsing() override; void AddPackageScriptFiles(dsPackage &package, const char *baseDirectory) override; /*@}*/ }; #endif
1
0.682942
1
0.682942
game-dev
MEDIA
0.302378
game-dev
0.573794
1
0.573794
Interkarma/daggerfall-unity
4,925
Assets/Scripts/Game/AutomapModel.cs
// Project: Daggerfall Unity // Copyright: Copyright (C) 2009-2023 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: XJDHDR // Contributors: // // Notes: // using DaggerfallWorkshop; using DaggerfallWorkshop.Game; using DaggerfallWorkshop.Utility; using UnityEngine; namespace DaggerfallWorkshop { /// <summary> /// Attached to all Automap models to perform various functions specific to them. /// </summary> public sealed class AutomapModel : MonoBehaviour { [SerializeField] [HideInInspector] private bool subscribedToEvents = false; void Awake() { if (!subscribedToEvents) { Automap.OnInjectMeshAndMaterialProperties += Automap_OnInjectMeshAndMaterialProperties; subscribedToEvents = true; } } private void OnDestroy() { if (subscribedToEvents) { Automap.OnInjectMeshAndMaterialProperties -= Automap_OnInjectMeshAndMaterialProperties; subscribedToEvents = false; } } private void Automap_OnInjectMeshAndMaterialProperties(bool playerIsInsideBuilding, Vector3 playerAdvancedPos, Material automapMaterial, bool resetDiscoveryState = true) { Automap.OnInjectMeshAndMaterialProperties -= Automap_OnInjectMeshAndMaterialProperties; subscribedToEvents = false; // get rid of animated materials (will not break automap rendering but is not necessary) AnimatedMaterial[] animatedMaterials = gameObject.GetComponentsInChildren<AnimatedMaterial>(); foreach (AnimatedMaterial animatedMaterial in animatedMaterials) { UnityEngine.Object.Destroy(animatedMaterial); } MeshRenderer[] meshRenderers = gameObject.GetComponentsInChildren<MeshRenderer>(); if (meshRenderers == null) return; // Update materials. If inside an interior, set visitedInThisEntering parameter to True so that they are always coloured. // Otherwise, mark meshes as not visited in this run (so "Dungeon" geometry that has been discovered in a previous dungeon run is rendered in grayscale) foreach (MeshRenderer meshRenderer in meshRenderers) { UpdateMaterialsOfMeshRenderer(playerAdvancedPos, automapMaterial, meshRenderer, playerIsInsideBuilding); // if player is inside dungeon or castle and forced reset of discovery state. if ((!playerIsInsideBuilding) && (resetDiscoveryState)) { // mark meshRenderer as undiscovered meshRenderer.enabled = false; } } } private void UpdateMaterialsOfMeshRenderer(Vector3 playerAdvancedPos, Material automapMaterial, MeshRenderer meshRenderer, bool visitedInThisEntering = false) { Material[] newMaterials = new Material[meshRenderer.materials.Length]; for (int i = 0; i < meshRenderer.materials.Length; i++) { Material curMaterial = meshRenderer.materials[i]; Material newMaterial = Instantiate(automapMaterial); //newMaterial.CopyPropertiesFromMaterial(material); newMaterial.name = "AutomapBelowSclicePlane injected for: " + curMaterial.name; if (curMaterial.HasProperty(Uniforms.MainTex)) newMaterial.SetTexture(Uniforms.MainTex, curMaterial.GetTexture(Uniforms.MainTex)); if (curMaterial.HasProperty(Uniforms.BumpMap)) newMaterial.SetTexture(Uniforms.BumpMap, curMaterial.GetTexture(Uniforms.BumpMap)); if (curMaterial.HasProperty(Uniforms.EmissionMap)) newMaterial.SetTexture(Uniforms.EmissionMap, curMaterial.GetTexture(Uniforms.EmissionMap)); if (curMaterial.HasProperty(Uniforms.EmissionColor)) newMaterial.SetColor(Uniforms.EmissionColor, curMaterial.GetColor(Uniforms.EmissionColor)); Vector4 playerPosition = new Vector4(playerAdvancedPos.x, playerAdvancedPos.y + Camera.main.transform.localPosition.y, playerAdvancedPos.z, 0.0f); newMaterial.SetVector("_PlayerPosition", playerPosition); if (visitedInThisEntering == true) newMaterial.DisableKeyword("RENDER_IN_GRAYSCALE"); else newMaterial.EnableKeyword("RENDER_IN_GRAYSCALE"); newMaterials[i] = newMaterial; } meshRenderer.materials = newMaterials; } } }
1
0.880677
1
0.880677
game-dev
MEDIA
0.954589
game-dev
0.971885
1
0.971885
mapbox/mapbox-ar-unity
2,163
Assets/UnityARKitPlugin/Examples/AddRemoveAnchorExample/UnityARUserAnchorExample.cs
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.XR.iOS; /** This Class will place a game object with an UnityARUserAnchorComponent attached to it. It will then call the RemoveAnchor API after 5 seconds. This scipt will subscribe to the AnchorRemoved event and remove the game object from the scene. */ public class UnityARUserAnchorExample : MonoBehaviour { public GameObject prefabObject; // Distance in Meters public int distanceFromCamera = 1; private HashSet<string> m_Clones; private float m_TimeUntilRemove = 5.0f; void Awake() { UnityARSessionNativeInterface.ARUserAnchorAddedEvent += ExampleAddAnchor; UnityARSessionNativeInterface.ARUserAnchorRemovedEvent += AnchorRemoved; m_Clones = new HashSet<string>(); } public void ExampleAddAnchor(ARUserAnchor anchor) { if (m_Clones.Contains(anchor.identifier)) { Console.WriteLine("Our anchor was added!"); } } public void AnchorRemoved(ARUserAnchor anchor) { if (m_Clones.Contains(anchor.identifier)) { m_Clones.Remove(anchor.identifier); Console.WriteLine("AnchorRemovedExample: " + anchor.identifier); } } // Update is called once per frame void Update () { if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) { GameObject clone = Instantiate(prefabObject, Camera.main.transform.position + (this.distanceFromCamera * Camera.main.transform.forward), Quaternion.identity); UnityARUserAnchorComponent component = clone.GetComponent<UnityARUserAnchorComponent>(); m_Clones.Add(component.AnchorId); m_TimeUntilRemove = 4.0f; } // just remove anchors afte a certain amount of time for example's sake. m_TimeUntilRemove -= Time.deltaTime; if (m_TimeUntilRemove <= 0.0f) { foreach (string id in m_Clones) { Console.WriteLine("Removing anchor with id: " + id); UnityARSessionNativeInterface.GetARSessionNativeInterface().RemoveUserAnchor(id); break; } m_TimeUntilRemove = 4.0f; } } }
1
0.812314
1
0.812314
game-dev
MEDIA
0.973958
game-dev
0.699005
1
0.699005
KaijuEngine/kaiju
1,525
src/engine/systems/visual2d/sprite/sprite_group.go
package sprite import ( "kaiju/debug" "kaiju/engine" "kaiju/klib" "slices" "weak" ) type SpriteGroupId = int type IndexedSprite struct { id SpriteGroupId sprite Sprite updates bool } type SpriteGroup struct { host weak.Pointer[engine.Host] nextId int index []IndexedSprite updateId int } func (g *SpriteGroup) Init(host *engine.Host) { g.host = weak.Make(host) host.Updater.AddUpdate(g.update) } func (g *SpriteGroup) Reserve(count int) { g.index = klib.SliceSetCap(g.index, count) } func (g *SpriteGroup) Find(id SpriteGroupId) *Sprite { for i := range g.index { if g.index[i].id == id { return &g.index[i].sprite } } return nil } func (g *SpriteGroup) Add(sprite Sprite) SpriteGroupId { g.nextId++ if g.updateId > 0 { host := g.host.Value() debug.EnsureNotNil(host) host.Updater.RemoveUpdate(sprite.updateId) } sprite.updateId = 0 entry := IndexedSprite{ id: g.nextId, sprite: sprite, updates: sprite.isSpriteSheet() || sprite.isFlipBook() || sprite.isUVAnimated(), } g.index = append(g.index, entry) return entry.id } func (g *SpriteGroup) AddBlank() *IndexedSprite { g.Add(Sprite{}) return &g.index[len(g.index)-1] } func (g *SpriteGroup) Remove(id SpriteGroupId) { for i := range g.index { if g.index[i].id == id { g.index = slices.Delete(g.index, i, i+1) break } } } func (g *SpriteGroup) update(deltaTime float64) { for i := range g.index { if !g.index[i].updates { continue } g.index[i].sprite.update(deltaTime) } }
1
0.554596
1
0.554596
game-dev
MEDIA
0.67231
game-dev,graphics-rendering
0.61773
1
0.61773
onixary/shape-shifter-curse-fabric
10,987
src/main/java/net/onixary/shapeShifterCurseFabric/player_form_render/OriginalFurClient.java
package net.onixary.shapeShifterCurseFabric.player_form_render; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import dev.kosmx.playerAnim.minecraftApi.PlayerAnimationFactory; import mod.azure.azurelib.renderer.GeoObjectRenderer; import net.onixary.shapeShifterCurseFabric.integration.origins.origin.Origin; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents; import net.fabricmc.fabric.api.resource.ResourceManagerHelper; import net.fabricmc.fabric.api.resource.SimpleSynchronousResourceReloadListener; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.VertexConsumer; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.resource.Resource; import net.minecraft.resource.ResourceManager; import net.minecraft.resource.ResourceType; import net.minecraft.util.Identifier; import net.onixary.shapeShifterCurseFabric.integration.origins.origin.OriginRegistry; import net.onixary.shapeShifterCurseFabric.player_form.PlayerFormBase; import net.onixary.shapeShifterCurseFabric.player_form.RegPlayerForms; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.LinkedHashMap; import static net.onixary.shapeShifterCurseFabric.ShapeShifterCurseFabric.MOD_ID; public class OriginalFurClient implements ClientModInitializer { public static class ItemRendererFeatureAnim extends dev.kosmx.playerAnim.api.layered.PlayerAnimationFrame { PlayerEntity player; ItemRendererFeatureAnim(PlayerEntity player) { super(); this.player = player; } private int time = 0; @Override public void tick(){ time++; } @Override public void setupAnim(float v) { if (player instanceof ClientPlayerEntity cPE && player instanceof IPlayerEntityMixins iPE) { for (var m : iPE.originalFur$getCurrentModels()) { if (m == null) { return; } var lP = m.getLeftOffset(); var rP = m.getRightOffset(); } } } } public static class OriginFur extends GeoObjectRenderer<OriginFurAnimatable> { public Origin currentAssociatedOrigin = Origin.EMPTY; public static final OriginFur NULL_OR_DEFAULT_FUR = new OriginFur(JsonParser.parseString("{}").getAsJsonObject()); public void renderBone(String name, MatrixStack poseStack, @Nullable VertexConsumerProvider bufferSource, @Nullable RenderLayer renderType, @Nullable VertexConsumer buffer, int packedLight) { poseStack.push(); var b = this.getGeoModel().getBone(name).orElse(null); if (b == null) {return;} if (buffer == null) {buffer = bufferSource.getBuffer(renderType);} var cubes = b.getCubes(); int packedOverlay = this.getPackedOverlay(animatable, 0.0F, MinecraftClient.getInstance().getTickDelta()); for (var child_bones : b.getChildBones()) { cubes.addAll(child_bones.getCubes()); } @Nullable VertexConsumer finalBuffer = buffer; cubes.forEach(geoCube -> { renderRecursively(poseStack, this.animatable, b, renderType, bufferSource, finalBuffer, false, MinecraftClient.getInstance().getTickDelta(), packedLight, packedOverlay, 1, 1, 1, 1); }); poseStack.pop(); } public void setPlayer(PlayerEntity e) { this.animatable.setPlayer(e); } public OriginFur(JsonObject json) { super(new OriginFurModel(json)); this.animatable = new OriginFurAnimatable(); } } public static boolean isRenderingInWorld = false; public static LinkedHashMap<Identifier, OriginFur> FUR_REGISTRY = new LinkedHashMap<>(); public static LinkedHashMap<Identifier, Resource> FUR_RESOURCES = new LinkedHashMap<>(); @Override public void onInitializeClient() { if (FabricLoader.getInstance().isModLoaded("player-animator") || FabricLoader.getInstance().isModLoaded("playeranimator")) { PlayerAnimationFactory.ANIMATION_DATA_FACTORY.registerFactory(new Identifier("originfurs", "item_renderer"), 9999, ItemRendererFeatureAnim::new); } WorldRenderEvents.END.register(context -> isRenderingInWorld = false); WorldRenderEvents.START.register(context -> isRenderingInWorld = true); ResourceManagerHelper.get(ResourceType.CLIENT_RESOURCES).registerReloadListener(new SimpleSynchronousResourceReloadListener() { @Override public Identifier getFabricId() { return new Identifier("originalfur", "furs"); } final String r_M = "\\/([A-Za-z0-9_.-]+)\\.json"; @Override public void reload(ResourceManager manager) { FUR_REGISTRY.clear(); FUR_RESOURCES.clear(); var resources = manager.findResources("furs", identifier -> identifier.getPath().endsWith(".json")); for (var res : resources.keySet()) { String itemName = res.getPath().substring(res.getPath().indexOf('/')+1, res.getPath().lastIndexOf('.')); //System.out.println(itemName); Identifier id = new Identifier("origins", itemName); var p = itemName.split("\\.", 2); if (p.length > 1) { id = Identifier.of(p[0], p[1]); } //System.out.println(id); assert id != null; id = new Identifier(id.getNamespace(), id.getPath().replace('/', '.').replace('\\', '.')); if (!res.getNamespace().contentEquals("orif-defaults")) { FUR_REGISTRY.remove(id); FUR_RESOURCES.remove(id); } if (FUR_REGISTRY.containsKey(id)) { OriginFurModel m = (OriginFurModel) FUR_REGISTRY.get(id).getGeoModel(); try { //System.out.println(id); m.recompile(JsonParser.parseString(new String(resources.get(res).getInputStream().readAllBytes())).getAsJsonObject()); } catch (IOException e) { throw new RuntimeException(e); } } else { //System.out.println(id); FUR_RESOURCES.put(id, resources.get(res)); // 原来的为了防止漏加载,现在不需要了 try { OriginalFurClient.FUR_REGISTRY.put(id, new OriginFur(JsonParser.parseString(new String(resources.get(res).getInputStream().readAllBytes())).getAsJsonObject())); } catch (IOException e) { throw new RuntimeException(e); } } } // 添加 Origins 默认的形态 正常运行不需要注册 OriginalFurClient.FUR_REGISTRY.put(Origin.EMPTY.getIdentifier(), new OriginFur(JsonParser.parseString("{}").getAsJsonObject())); // 手动处理各形态的映射关系: /* if(FabricLoader.getInstance().isModLoaded(MOD_ID)){ RegPlayerForms.playerForms.forEach((playerFormBaseID, playerFormBase) -> { var id = playerFormBase.getFormOriginID(); var fur = OriginalFurClient.FUR_RESOURCES.getOrDefault(id, null); if(fur == null){ fur = OriginalFurClient.FUR_RESOURCES.getOrDefault(id, null); } if (fur == null) { OriginalFurClient.FUR_REGISTRY.put(id, new OriginFur(JsonParser.parseString("{}").getAsJsonObject())); } else{ try{ OriginalFurClient.FUR_REGISTRY.put(id, new OriginFur(JsonParser.parseString(new String(fur.getInputStream().readAllBytes())).getAsJsonObject())); System.out.println(FUR_REGISTRY.get(id)); System.out.println(id.getPath()); } catch (IOException e) { System.err.println(e.getMessage()); } } }); } */ // 旧的加载方法由于加载顺序失效 /* assert FabricLoader.getInstance().isModLoaded("origins"); try { OriginRegistry.entries().forEach(identifierOriginEntry -> { var oID = identifierOriginEntry.getKey(); var o = identifierOriginEntry.getValue(); Identifier id = oID; var fur = OriginalFurClient.FUR_RESOURCES.getOrDefault(id, null); if (fur == null) { id = Identifier.of("origins", oID.getPath()); fur = OriginalFurClient.FUR_RESOURCES.getOrDefault(id, null); } if (fur == null) { OriginalFurClient.FUR_REGISTRY.put(id, new OriginFur(JsonParser.parseString("{}").getAsJsonObject())); } else { try { OriginalFurClient.FUR_REGISTRY.put(id, new OriginFur(JsonParser.parseString(new String(fur.getInputStream().readAllBytes())).getAsJsonObject())); if(FUR_REGISTRY.get(id) == null){ System.out.println("null"); }else{ System.out.println(FUR_REGISTRY.get(id)); } //System.out.println(new String(fur.getInputStream().readAllBytes())); } catch (IOException e) { System.err.println(e.getMessage()); } } }); } catch(Exception e) { System.out.println("[ORIF] Failed to load origins registry! Ensure the Origins mod is loaded! Some models may not work, and crashes may occur!"); e.printStackTrace(); } */ } }); } }
1
0.937237
1
0.937237
game-dev
MEDIA
0.876691
game-dev
0.874339
1
0.874339
sandstranger/Underworld-Exporter-Android
2,637
Assets/com.unity.uiextensions/Runtime/Scripts/Primitives/UIGridRenderer.cs
/// Credit John Hattan (http://thecodezone.com/) /// Sourced from - https://bitbucket.org/UnityUIExtensions/unity-ui-extensions/issues/117/uigridrenderer namespace UnityEngine.UI.Extensions { [AddComponentMenu("UI/Extensions/Primitives/UIGridRenderer")] public class UIGridRenderer : UILineRenderer { [SerializeField] private int m_GridColumns = 10; [SerializeField] private int m_GridRows = 10; /// <summary> /// Number of columns in the Grid /// </summary> public int GridColumns { get { return m_GridColumns; } set { if (m_GridColumns == value) return; m_GridColumns = value; SetAllDirty(); } } /// <summary> /// Number of rows in the grid. /// </summary> public int GridRows { get { return m_GridRows; } set { if (m_GridRows == value) return; m_GridRows = value; SetAllDirty(); } } protected override void OnPopulateMesh(VertexHelper vh) { relativeSize = true; int ArraySize = (GridRows * 3) + 1; if(GridRows % 2 == 0) ++ArraySize; // needs one more line ArraySize += (GridColumns * 3) + 1; m_points = new Vector2[ArraySize]; int Index = 0; for(int i = 0; i < GridRows; ++i) { float xFrom = 1; float xTo = 0; if(i % 2 == 0) { // reach left instead xFrom = 0; xTo = 1; } float y = ((float)i) / GridRows; m_points[Index].x = xFrom; m_points[Index].y = y; ++Index; m_points[Index].x = xTo; m_points[Index].y = y; ++Index; m_points[Index].x = xTo; m_points[Index].y = (float)(i + 1) / GridRows; ++Index; } if(GridRows % 2 == 0) { // two lines to get to 0, 1 m_points[Index].x = 1; m_points[Index].y = 1; ++Index; } m_points[Index].x = 0; m_points[Index].y = 1; ++Index; // line is now at 0,1, so we can draw the columns for(int i = 0; i < GridColumns; ++i) { float yFrom = 1; float yTo = 0; if(i % 2 == 0) { // reach up instead yFrom = 0; yTo = 1; } float x = ((float)i) / GridColumns; m_points[Index].x = x; m_points[Index].y = yFrom; ++Index; m_points[Index].x = x; m_points[Index].y = yTo; ++Index; m_points[Index].x = (float)(i + 1) / GridColumns; m_points[Index].y = yTo; ++Index; } if(GridColumns % 2 == 0) { // one more line to get to 1, 1 m_points[Index].x = 1; m_points[Index].y = 1; } else { // one more line to get to 1, 0 m_points[Index].x = 1; m_points[Index].y = 0; } base.OnPopulateMesh(vh); } } }
1
0.849743
1
0.849743
game-dev
MEDIA
0.709657
game-dev,graphics-rendering
0.958394
1
0.958394
jjbali/Extended-Experienced-PD
14,356
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/wands/WandOfRegrowth.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2024 Evan Debenham * * Experienced Pixel Dungeon * Copyright (C) 2019-2024 Trashbox Bobylev * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.items.wands; import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.Statistics; import com.shatteredpixel.shatteredpixeldungeon.actors.Actor; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.*; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.abilities.mage.WildMagic; import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.DwarfKing; import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs.NPC; import com.shatteredpixel.shatteredpixeldungeon.effects.MagicMissile; import com.shatteredpixel.shatteredpixeldungeon.items.Dewdrop; import com.shatteredpixel.shatteredpixeldungeon.items.Generator; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.MagesStaff; import com.shatteredpixel.shatteredpixeldungeon.levels.Level; import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain; import com.shatteredpixel.shatteredpixeldungeon.mechanics.Ballistica; import com.shatteredpixel.shatteredpixeldungeon.mechanics.ConeAOE; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.plants.Plant; import com.shatteredpixel.shatteredpixeldungeon.plants.Sungrass; import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene; import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet; import com.shatteredpixel.shatteredpixeldungeon.sprites.LotusSprite; import com.watabou.noosa.audio.Sample; import com.watabou.utils.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class WandOfRegrowth extends Wand { { image = ItemSpriteSheet.WAND_REGROWTH; //only used for targeting, actual projectile logic is Ballistica.STOP_SOLID collisionProperties = Ballistica.WONT_STOP; } private int totChrgUsed = 0; private int chargesOverLimit = 0; ConeAOE cone; int target; @Override public List<Integer> aimTiles(int target) { if (cursed && cursedKnown) { return super.aimTiles(target); } Ballistica b = new Ballistica(Dungeon.hero.pos, target, Ballistica.WONT_STOP); long maxDist = 2 + 2*chargesPerCast(); ConeAOE tempCone = new ConeAOE( b, maxDist, 20 + 10*chargesPerCast(), Ballistica.STOP_SOLID | Ballistica.STOP_TARGET); return Arrays.asList(tempCone.cells.toArray(new Integer[0])); } @Override public boolean tryToZap(Hero owner, int target) { if (super.tryToZap(owner, target)){ this.target = target; return true; } else { return false; } } @Override public void onZap(Ballistica bolt) { ArrayList<Integer> cells = new ArrayList<>(cone.cells); float furrowedChance = 0; if (totChrgUsed >= chargeLimit(Dungeon.hero.lvl)){ furrowedChance = (chargesOverLimit+1)/5f; } long chrgUsed = chargesPerCast(); int grassToPlace = Math.round((3.67f+buffedLvl()/3f)*chrgUsed); //ignore cells which can't have anything grow in them. for (Iterator<Integer> i = cells.iterator(); i.hasNext();) { int cell = i.next(); int terr = Dungeon.level.map[cell]; if (!(terr == Terrain.EMPTY || terr == Terrain.EMBERS || terr == Terrain.EMPTY_DECO || terr == Terrain.GRASS || terr == Terrain.HIGH_GRASS || terr == Terrain.FURROWED_GRASS)) { i.remove(); } else if (Char.hasProp(Actor.findChar(cell), Char.Property.IMMOVABLE)) { i.remove(); } else if (Dungeon.level.plants.get(cell) != null){ i.remove(); } else { if (terr != Terrain.HIGH_GRASS && terr != Terrain.FURROWED_GRASS) { Level.set(cell, Terrain.GRASS); GameScene.updateMap( cell ); } Char ch = Actor.findChar(cell); if (ch != null){ if (ch instanceof DwarfKing){ Statistics.qualifiedForBossChallengeBadge = false; } wandProc(ch, chargesPerCast()); Buff.prolong( ch, Roots.class, 4f * chrgUsed ); } } } Random.shuffle(cells); if (chargesPerCast() >= 3){ Lotus l = new Lotus(); l.setLevel(buffedLvl()); if (cells.contains(target) && Actor.findChar(target) == null){ cells.remove((Integer)target); l.pos = target; GameScene.add(l); } else { for (int i = bolt.path.size()-1; i >= 0; i--){ int c = bolt.path.get(i); if (cells.contains(c) && Actor.findChar(c) == null){ cells.remove((Integer)c); l.pos = c; GameScene.add(l); break; } } } } //places grass along center of cone for (int cell : bolt.path){ if (grassToPlace > 0 && cells.contains(cell)){ if (Random.Float() > furrowedChance) { Level.set(cell, Terrain.HIGH_GRASS); } else { Level.set(cell, Terrain.FURROWED_GRASS); } GameScene.updateMap( cell ); grassToPlace--; //moves cell to the back cells.remove((Integer)cell); cells.add(cell); } } if (!cells.isEmpty() && Random.Float() > furrowedChance && (Random.Int(6) < chrgUsed)){ // 16%/33%/50% chance to spawn a seed pod or dewcatcher int cell = cells.remove(0); Dungeon.level.plant( Dungeon.Int(2) == 0 ? new Seedpod.Seed() : new Dewcatcher.Seed(), cell); } if (!cells.isEmpty() && Random.Float() > furrowedChance && (Random.Int(3) < chrgUsed)){ // 33%/66%/100% chance to spawn a plant int cell = cells.remove(0); Dungeon.level.plant((Plant.Seed) Generator.randomUsingDefaults(Generator.Category.SEED), cell); } for (int cell : cells){ if (grassToPlace <= 0 || bolt.path.contains(cell)) break; if (Dungeon.level.map[cell] == Terrain.HIGH_GRASS) continue; if (Random.Float() > furrowedChance) { Level.set(cell, Terrain.HIGH_GRASS); } else { Level.set(cell, Terrain.FURROWED_GRASS); } GameScene.updateMap( cell ); grassToPlace--; } if (totChrgUsed < chargeLimit(Dungeon.hero.lvl)) { chargesOverLimit = 0; totChrgUsed += chrgUsed; if (totChrgUsed > chargeLimit(Dungeon.hero.lvl)){ chargesOverLimit = totChrgUsed - chargeLimit(Dungeon.hero.lvl); totChrgUsed = chargeLimit(Dungeon.hero.lvl); } } else { chargesOverLimit += chrgUsed; } } private int chargeLimit( int heroLvl ){ if (level() >= 10){ return Integer.MAX_VALUE; } else { //20 charges at base, plus: //2/3.1/4.2/5.5/6.8/8.4/10.4/13.2/18.0/30.8/inf. charges per hero level, at wand level: //0/1 /2 /3 /4 /5 /6 /7 /8 /9 /10 float lvl = level(); return Math.round(20 + heroLvl * (2+lvl) * (1f + (lvl/(50 - 5*lvl)))); } } @Override public void onHit(MagesStaff staff, Char attacker, Char defender, long damage) { //like pre-nerf vampiric enchantment, except with herbal healing buff, only in grass boolean grass = false; int terr = Dungeon.level.map[attacker.pos]; if (terr == Terrain.GRASS || terr == Terrain.HIGH_GRASS || terr == Terrain.FURROWED_GRASS){ grass = true; } terr = Dungeon.level.map[defender.pos]; if (terr == Terrain.GRASS || terr == Terrain.HIGH_GRASS || terr == Terrain.FURROWED_GRASS){ grass = true; } if (grass) { long level = Math.max(0, staff.buffedLvl()); // lvl 0 - 16% // lvl 1 - 21% // lvl 2 - 25% int healing = Math.round(damage * (level + 2f) / (level + 6f) / 2f); healing = Math.round(healing * procChanceMultiplier(attacker)); Buff.affect(attacker, Sungrass.Health.class).boost(healing); } } public void fx(Ballistica bolt, Callback callback) { // 4/6/8 distance int maxDist = (int) (2 + 2*chargesPerCast()); cone = new ConeAOE( bolt, maxDist, 20 + 10*chargesPerCast(), Ballistica.STOP_SOLID | Ballistica.STOP_TARGET); //cast to cells at the tip, rather than all cells, better performance. Ballistica longestRay = null; for (Ballistica ray : cone.outerRays){ if (longestRay == null || ray.dist > longestRay.dist){ longestRay = ray; } ((MagicMissile)curUser.sprite.parent.recycle( MagicMissile.class )).reset( MagicMissile.FOLIAGE_CONE, curUser.sprite, ray.path.get(ray.dist), null ); } //final zap at half distance of the longest ray, for timing of the actual wand effect MagicMissile.boltFromChar( curUser.sprite.parent, MagicMissile.FOLIAGE_CONE, curUser.sprite, longestRay.path.get(longestRay.dist/2), callback ); Sample.INSTANCE.play( Assets.Sounds.ZAP ); } @Override protected long chargesPerCast() { if (cursed || charger != null && charger.target.buff(WildMagic.WildMagicTracker.class) != null){ return 1; } //consumes 30% of current charges, rounded up, with a min of 1 and a max of 3. return (long) GameMath.gate(1, (long)Math.ceil(curCharges*0.3d), 3); } @Override public String statsDesc() { String desc = Messages.get(this, "stats_desc", chargesPerCast()) + "\n\n" + Messages.get(Wand.class, "charges", curCharges, maxCharges); if (isIdentified()){ int chargeLeft = chargeLimit(Dungeon.hero.lvl) - totChrgUsed; if (chargeLeft < 10000) desc += " " + Messages.get(this, "degradation", Math.max(chargeLeft, 0)); } return desc; } @Override public void staffFx(MagesStaff.StaffParticle particle) { particle.color( ColorMath.random(0x004400, 0x88CC44) ); particle.am = 1f; particle.setLifespan(1f); particle.setSize( 1f, 1.5f); particle.shuffleXY(0.5f); float dst = Random.Float(11f); particle.x -= dst; particle.y += dst; } private static final String TOTAL = "totChrgUsed"; private static final String OVER = "chargesOverLimit"; @Override public void storeInBundle(Bundle bundle) { super.storeInBundle(bundle); bundle.put( TOTAL, totChrgUsed ); bundle.put( OVER, chargesOverLimit); } @Override public void restoreFromBundle(Bundle bundle) { super.restoreFromBundle(bundle); totChrgUsed = bundle.getInt(TOTAL); chargesOverLimit = bundle.getInt(OVER); } public static class Dewcatcher extends Plant{ { image = 13; } @Override public void activate( Char ch ) { int nDrops = Dungeon.NormalIntRange(3, 6); ArrayList<Integer> candidates = new ArrayList<>(); for (int i : PathFinder.NEIGHBOURS8){ if (Dungeon.level.passable[pos+i] && pos+i != Dungeon.level.entrance() && pos+i != Dungeon.level.exit()){ candidates.add(pos+i); } } for (int i = 0; i < nDrops && !candidates.isEmpty(); i++){ Integer c = Random.element(candidates); if (Dungeon.level.heaps.get(c) == null) { Dungeon.level.drop(new Dewdrop(), c).sprite.drop(pos); } else { Dungeon.level.drop(new Dewdrop(), c).sprite.drop(c); } candidates.remove(c); } } //seed is never dropped, only care about plant class public static class Seed extends Plant.Seed { { plantClass = Dewcatcher.class; } } } public static class Seedpod extends Plant{ { image = 14; } @Override public void activate( Char ch ) { int nSeeds = Dungeon.NormalIntRange(2, 4); ArrayList<Integer> candidates = new ArrayList<>(); for (int i : PathFinder.NEIGHBOURS8){ if (Dungeon.level.passable[pos+i] && pos+i != Dungeon.level.entrance() && pos+i != Dungeon.level.exit()){ candidates.add(pos+i); } } for (int i = 0; i < nSeeds && !candidates.isEmpty(); i++){ Integer c = Random.element(candidates); Dungeon.level.drop(Generator.randomUsingDefaults(Generator.Category.SEED), c).sprite.drop(pos); candidates.remove(c); } } //seed is never dropped, only care about plant class public static class Seed extends Plant.Seed { { plantClass = Seedpod.class; } } } public static class Lotus extends NPC { { alignment = Alignment.NEUTRAL; properties.add(Property.IMMOVABLE); spriteClass = LotusSprite.class; viewDistance = 1; } private long wandLvl = 0; private void setLevel( long lvl ){ wandLvl = lvl; HP = HT = (25 + 3*lvl); } public boolean inRange(int pos){ return Dungeon.level.trueDistance(this.pos, pos) <= wandLvl; } public float seedPreservation(){ return 0.40f + 0.04f*wandLvl; } @Override public boolean canInteract(Char c) { return false; } @Override protected boolean act() { super.act(); if (--HP <= 0){ destroy(); sprite.die(); } return true; } @Override public void damage( long dmg, Object src ) { //do nothing } @Override public boolean add( Buff buff ) { return false; } @Override public void destroy() { super.destroy(); Dungeon.observe(); GameScene.updateFog(pos, viewDistance+1); } @Override public boolean isInvulnerable(Class effect) { return true; } { immunities.add( Paralysis.class ); immunities.add( Amok.class ); immunities.add( Sleep.class ); immunities.add( Terror.class ); immunities.add( Dread.class ); immunities.add( Vertigo.class ); immunities.add( AllyBuff.class ); immunities.add( Doom.class ); } @Override public String description() { int preservation = Math.round(seedPreservation()*100); return Messages.get(this, "desc", wandLvl, preservation, preservation); } private static final String WAND_LVL = "wand_lvl"; @Override public void storeInBundle(Bundle bundle) { super.storeInBundle(bundle); bundle.put(WAND_LVL, wandLvl); } @Override public void restoreFromBundle(Bundle bundle) { super.restoreFromBundle(bundle); wandLvl = bundle.getInt(WAND_LVL); } } }
1
0.917542
1
0.917542
game-dev
MEDIA
0.977966
game-dev
0.993824
1
0.993824
CorgiTaco-MC/Enhanced-Celestials
1,585
Common/src/main/java/dev/corgitaco/enhancedcelestials/mixin/MixinConfiguredFeature.java
package dev.corgitaco.enhancedcelestials.mixin; import dev.corgitaco.enhancedcelestials.EnhancedCelestials; import dev.corgitaco.enhancedcelestials.world.level.levelgen.structure.ECStructures; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.Registries; import net.minecraft.util.RandomSource; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.structure.Structure; 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.CallbackInfoReturnable; @Mixin(ConfiguredFeature.class) public class MixinConfiguredFeature { @Inject(method = "place", at = @At("HEAD"), cancellable = true) private void cancelPlacementNearCraters(WorldGenLevel level, ChunkGenerator generator, RandomSource source, BlockPos pos, CallbackInfoReturnable<Boolean> cir) { if (EnhancedCelestials.NEW_CONTENT) { Structure structure = level.registryAccess().registryOrThrow(Registries.STRUCTURE).get(ECStructures.CRATER); ChunkAccess chunk = level.getChunk(pos); boolean hasCrater = chunk.getAllStarts().containsKey(structure) || chunk.getAllReferences().containsKey(structure); if (hasCrater) { cir.setReturnValue(false); } } } }
1
0.818613
1
0.818613
game-dev
MEDIA
0.988813
game-dev
0.650807
1
0.650807
modio/modio-unity-legacy
3,772
Runtime/UI/Utility/EnumDropdown.cs
using System; using UnityEngine; using UnityEngine.UI; namespace ModIO.UI { /// <summary>Binds the values of an enum to a Dropdown control.</summary> public class EnumDropdown<TEnum> : EnumDropdownBase where TEnum : struct, IConvertible { // ---------[ Functionality ]--------- /// <summary>Returns the selected value of the dropdown as an enum representation.</summary> public bool TryGetSelectedValue(out TEnum enumValue) { int selectionIndex = this.GetComponent<Dropdown>().value; EnumDropdownBase.EnumSelectionPair pair; if(this.TryGetPairForSelection(selectionIndex, out pair) && Enum.IsDefined(typeof(TEnum), pair.enumValue)) { enumValue = (TEnum)Enum.ToObject(typeof(TEnum), pair.enumValue); return true; } enumValue = default(TEnum); return false; } // ---------[ Utility ]--------- /// <summary>Gets the names of the enum options.</summary> public override string[] GetEnumNames() { return Enum.GetNames(typeof(TEnum)); } /// <summary>Gets the values of the enum options.</summary> public override int[] GetEnumValues() { return (int[])Enum.GetValues(typeof(TEnum)); } } /// <summary>Binds the values of an enum to a Dropdown control.</summary> [DisallowMultipleComponent] public abstract class EnumDropdownBase : MonoBehaviour { // ---------[ Nested Data-Types ]--------- /// <summary>Enum-Dropdown Selection index pairing.</summary> [Serializable] public struct EnumSelectionPair { public int selectionIndex; public int enumValue; } // ---------[ Fields ]--------- /// <summary>Enum-Dropdown Selection index pairing.</summary> public EnumSelectionPair[] enumSelectionPairings = new EnumSelectionPair[0]; // ---------[ Interface ]--------- /// <summary>Gets the names of the enum options.</summary> public abstract string[] GetEnumNames(); /// <summary>Gets the values of the enum options.</summary> public abstract int[] GetEnumValues(); // ---------[ Functionality ]--------- /// <summary>Gets the enum-selection pair for the given selection index.</summary> public bool TryGetPairForSelection(int selectionIndex, out EnumSelectionPair result) { if(this.enumSelectionPairings != null && this.enumSelectionPairings.Length > 0) { foreach(var pair in this.enumSelectionPairings) { if(pair.selectionIndex == selectionIndex) { result = pair; return true; } } } result = new EnumSelectionPair() { selectionIndex = -1, enumValue = -1 }; return false; } /// <summary>Gets the enum-selection pair for the given enum value.</summary> public bool TryGetPairForEnum(int enumValue, out EnumSelectionPair result) { if(this.enumSelectionPairings != null && this.enumSelectionPairings.Length > 0) { foreach(var pair in this.enumSelectionPairings) { if(pair.enumValue == enumValue) { result = pair; return true; } } } result = new EnumSelectionPair() { selectionIndex = -1, enumValue = -1 }; return false; } } }
1
0.835719
1
0.835719
game-dev
MEDIA
0.356584
game-dev
0.963708
1
0.963708
azerothcore/mod-progression-system
44,248
src/Bracket_60_2_1/scripts/TheMasquerade/quest_the_masquerade.cpp
/* * This file is part of the AzerothCore 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 Affero General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "Player.h" #include "SpellInfo.h" #include "ProgressionSystem.h" enum TheGreatMasquerade { QUEST_STORMWIND_RENDEZVOUZ = 6402, QUEST_THE_GREAT_MASQUERADE = 6403, NPC_SQUIRE_ROWE = 17804, NPC_REGINALD_WINDSOR = 12580, NPC_MERCUTIO = 12581, NPC_KATRANA_PRESTOR = 1749, NPC_JONATHAN = 466, NPC_ROYAL_GUARD = 1756, NPC_SW_GUARD = 68, NPC_SW_PATROL = 1976, NPC_VARIAN = 29611, NPC_ONYXIA_GUARD = 12739, NPC_BOLVAR = 1748, NPC_ANDUINN = 1747, NPC_LADY_ONYXIA = 12756, ACTION_START_ESCORT = 0, ACTION_RESET_MASQUERADE = 2, ACTION_START_MASQUERADE = 3, ACTION_INCREASE_DEATH_COUNTER = 4, EVENT_DISMOUNT = 4, EVENT_END_INTRO = 5, EVENT_REGINALD_SAY_2 = 6, EVENT_KATRANA_SAY_1 = 7, EVENT_CHECK_PLAYER = 67, // Speech SAY_REGINALD_SHOO_HORSE = 0, SAY_REGINALD_END_INTRO = 1, SAY_REGINALD_MASQUERADE_1 = 2, SAY_REGINALD_MASQUERADE_2 = 3, SAY_REGINALD_TO_MARCUS_1 = 4, SAY_REGINALD_TO_MARCUS_2 = 5, SAY_REGINALD_TO_MARCUS_3 = 6, SAY_REGINALD_TO_MARCUS_4 = 7, SAY_REGINALD_TO_MARCUS_5 = 8, SAY_REGINALD_MASQUERADE_3 = 9, SAY_REGINALD_BEFORE_KEEP = 10, SAY_REGINALD_MOVE_IN_KEEP = 11, SAY_REGINALD_TO_ANDUINN = 12, SAY_REGINALD_MASQUERADE_OVER = 13, SAY_REGINALD_NO_ESCAPE_FATE = 14, SAY_REGINALD_TABLETS = 15, SAY_REGINALD_LISTEN_DRAGON = 16, EMOTE_READ_TABLETS = 17, SAY_REGINALD_DONT_LET_ESCAPE = 18, SAY_REGINALD_BOLVAR_MEDALION = 19, EMOTE_REGINALD_DIES = 20, EMOTE_REACH_TABLETS = 21, SAY_KATRANA_1 = 0, EMOTE_KATRANA_LAUGH = 1, SAY_KATRANA_2 = 2, SAY_KATRANA_3 = 3, SAY_ONYXIA_CURIOUS = 0, SAY_ONYXIA_COME_GUARDS = 1, SAY_ONYXYA_WAS_THIS_FATED = 2, SAY_ONYXIA_FAREWELL = 3, SAY_BOLVAR_TO_ANDUINN = 0, EMOTE_BOLVAR_GASP = 1, SAY_BOLVAR_YELL_GUARDS = 2, SAY_BOLVAR_TO_REGINALD = 3, SAY_GUARD_GREET = 10, SAY_SQUIRE_ROWE = 0, SAY_JONATHAN_TO_REGINALD_1 = 1, EMOTE_CONTEMPLATION = 2, SAY_JONATHAN_TO_REGINALD_2 = 3, SAY_JONATHAN_TO_REGINALD_3 = 4, SAY_JONATHAN_TO_GUARDS_1 = 5, SAY_JONATHAN_TO_GUARDS_2 = 6, SAY_JONATHAN_TO_GUARDS_3 = 7, SAY_JONATHAN_TO_REGINALD_4 = 8, GUID_PRESTOR = 500800, GUID_REGINALD = 86900, GUID_ROWE = 79862, SUMMON_GROUP_ROYAL_GUARDS = 0, DATA_GUARD_INDEX = 1, SPELL_WINDSOR_READ = 20358, SPELL_WINDSOR_DEATH = 20465 }; class DelayedEmoteEvent : public BasicEvent { public: DelayedEmoteEvent(Creature* invoker, uint32 emoteId) : _invoker(invoker), _emoteId(emoteId) { } bool Execute(uint64 /*time*/, uint32 /*diff*/) { _invoker->HandleEmoteCommand(_emoteId); return true; } private: Creature* _invoker; uint32 _emoteId; }; class DelayedAttackStartEvent : public BasicEvent { public: DelayedAttackStartEvent(Creature* invoker) : _invoker(invoker) { } bool Execute(uint64 /*time*/, uint32 /*diff*/) { _invoker->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NON_ATTACKABLE); if (Creature* bolvar = _invoker->FindNearestCreature(NPC_BOLVAR, 50.0f)) { _invoker->AI()->AttackStart(bolvar); _invoker->AddThreat(bolvar, 500.0f); } return true; } private: Creature* _invoker; }; class DelayedResetEvent : public BasicEvent { public: DelayedResetEvent(Creature* invoker) : _invoker(invoker) { } bool Execute(uint64 /*time*/, uint32 /*diff*/) { _invoker->DespawnOrUnsummon(); _invoker->SetRespawnTime(5); return true; } private: Creature* _invoker; }; class npc_squire_rowe : public CreatureScript { public: npc_squire_rowe() : CreatureScript("npc_squire_rowe") { } struct npc_squire_roweAI : public ScriptedAI { npc_squire_roweAI(Creature* creature) : ScriptedAI(creature) { } void DoAction(int32 actionId) override { if (actionId == ACTION_RESET_MASQUERADE) me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER); } void SetGUID(ObjectGuid guid, int32 index) override { if (index == ACTION_START_ESCORT) { _events.ScheduleEvent(1, 2000); _playerGUID = guid; } } void MovementInform(uint32 type, uint32 point) override { if (type != POINT_MOTION_TYPE) return; switch (point) { case 1: _events.ScheduleEvent(point + 1, 1); break; case 2: me->HandleEmoteCommand(EMOTE_ONESHOT_KNEEL); if (Creature* reginald = me->SummonCreature(NPC_REGINALD_WINDSOR, -9161.673828f, 351.799713f, 87.906525f, TEMPSUMMON_MANUAL_DESPAWN)) { reginald->setActive(true); reginald->AI()->SetGUID(_playerGUID, ACTION_START_ESCORT); reginald->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER); } _events.ScheduleEvent(point + 1, 5000); break; case 3: _events.ScheduleEvent(point + 1, 1); break; case 4: me->GetMotionMaster()->Clear(); me->SetFacingTo(me->GetHomePosition().GetOrientation()); _events.ScheduleEvent(5, 1000); break; default: break; } } void UpdateAI(uint32 diff) override { _events.Update(diff); while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case 1: me->GetMotionMaster()->MovePoint(1, -9053.81f, 442.66f, 93.05f, false); break; case 2: me->GetMotionMaster()->MovePoint(2, -9082.63f, 421.29f, 92.55f, false); break; case 3: me->GetMotionMaster()->MovePoint(3, -9057.101563f, 439.136200f, 93.050003f, false); break; case 4: me->GetMotionMaster()->MovePoint(4, -9043.89f, 434.39f, 93.29f, false); break; case 5: Talk(SAY_SQUIRE_ROWE); break; default: break; } } } private: EventMap _events; ObjectGuid _playerGUID; }; bool OnGossipSelect(Player* player, Creature* me, uint32 /*menuId*/, uint32 gossipListId) override { CloseGossipMenuFor(player); uint32 const action = player->PlayerTalkClass->GetGossipOptionAction(gossipListId); if (action == 0) { me->AI()->SetGUID(player->GetGUID(), ACTION_START_ESCORT); me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER); return true; } return true; } CreatureAI* GetAI(Creature* creature) const override { return new npc_squire_roweAI(creature); } }; Position const GuardsPos[] = { { -8968.510f, 512.556f, 96.352f, 3.849f }, { -8969.780f, 515.012f, 96.593f, 3.955f }, { -8972.410f, 518.228f, 96.594f, 4.281f }, { -8965.170f, 508.565f, 96.352f, 3.825f }, { -8962.960f, 506.583f, 96.593f, 3.802f }, { -8961.080f, 503.828f, 96.593f, 3.465f } }; class npc_reginald_windsor : public CreatureScript { public: npc_reginald_windsor() : CreatureScript("npc_reginald_windsor") { } struct npc_reginald_windsorAI : public ScriptedAI { npc_reginald_windsorAI(Creature* creature) : ScriptedAI(creature), Summons(creature) { _canGreet = false; creature->SetUnitFlag(UNIT_FLAG_IMMUNE_TO_PC); } void DoAction(int32 actionId) override { if (actionId == ACTION_RESET_MASQUERADE) { me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER); ObjectGuid::LowType guid = GUID_ROWE; if (Creature* rowe = GetCreature(guid)) { me->GetMap()->LoadGrid(-9042.23f, 434.24f); rowe->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER); } guid = GUID_PRESTOR; if (Creature* prestor = GetCreature(guid)) { prestor->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER); } } if (actionId == ACTION_START_ESCORT) _events.ScheduleEvent(46, 3000); if (actionId == ACTION_INCREASE_DEATH_COUNTER) { if (!me->FindNearestCreature(NPC_ONYXIA_GUARD, 20.0f)) _events.ScheduleEvent(68, 3000); } } void SetGUID(ObjectGuid guid, int32 index) override { if (index == ACTION_START_ESCORT) { if (ObjectAccessor::FindConnectedPlayer(_playerGUID)) { // Prevent starting the escort script multiple times. return; } _events.ScheduleEvent(1, 2000); _playerGUID = guid; } else if (index == ACTION_START_MASQUERADE) { _events.ScheduleEvent(EVENT_REGINALD_SAY_2, 5000); } } void MoveInLineOfSight(Unit* who) override { if (who->IsWithinDistInMap(me, 10.0f) && !who->IsInCombat()) { if ((who->GetEntry() == NPC_SW_GUARD || who->GetEntry() == NPC_SW_PATROL || who->GetEntry() == NPC_ROYAL_GUARD) && _canGreet) { if (_swGuardsSaluted.find(who->GetGUID()) == _swGuardsSaluted.end()) { who->GetMotionMaster()->Clear(); who->GetMotionMaster()->MoveIdle(); who->SetFacingToObject(me); who->m_Events.AddEvent(new DelayedEmoteEvent(who->ToCreature(), EMOTE_ONESHOT_SALUTE), who->m_Events.CalculateTime(1000)); who->m_Events.AddEvent(new DelayedResetEvent(who->ToCreature()), who->m_Events.CalculateTime(30000)); who->ToCreature()->AI()->Talk(SAY_GUARD_GREET); _swGuardsSaluted.insert(who->GetGUID()); } } } } void MovementInform(uint32 type, uint32 point) override { if (type != POINT_MOTION_TYPE) return; switch (point) { case 1: _events.ScheduleEvent(2, 1); break; case 2: _events.ScheduleEvent(3, 1); break; case 3: me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER); _events.ScheduleEvent(EVENT_DISMOUNT, 3000); break; case 4: _events.ScheduleEvent(9, 1); break; case 5: if (Creature* jonathan = me->FindNearestCreature(NPC_JONATHAN, 20.0f)) jonathan->AI()->Talk(SAY_JONATHAN_TO_REGINALD_1); _events.ScheduleEvent(10, 3000); break; case 6: _events.ScheduleEvent(26, 1); break; case 7: _events.ScheduleEvent(27, 1); break; case 8: _events.ScheduleEvent(28, 1); break; case 9: _events.ScheduleEvent(29, 1); break; case 10: _events.ScheduleEvent(30, 1); break; case 11: _events.ScheduleEvent(31, 1); break; case 12: _events.ScheduleEvent(32, 1); break; case 13: _events.ScheduleEvent(33, 1); break; case 14: _events.ScheduleEvent(34, 1); break; case 15: _events.ScheduleEvent(35, 1); break; case 16: _events.ScheduleEvent(36, 1); break; case 17: _events.ScheduleEvent(37, 1); break; case 18: _events.ScheduleEvent(38, 1); break; case 19: _events.ScheduleEvent(39, 1); break; case 20: _events.ScheduleEvent(40, 1); break; case 21: _events.ScheduleEvent(41, 1); break; case 22: _events.ScheduleEvent(42, 1); break; case 23: _events.ScheduleEvent(43, 1); break; case 24: _events.ScheduleEvent(44, 1); break; case 25: _events.ScheduleEvent(45, 1); break; case 26: // Keep gossip _events.ScheduleEvent(EVENT_CHECK_PLAYER, 5 * MINUTE * IN_MILLISECONDS); Talk(SAY_REGINALD_BEFORE_KEEP); me->GetMotionMaster()->Clear(); me->SetFacingTo(5.41f); me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); break; case 27: _events.ScheduleEvent(47, 1); break; case 28: _events.ScheduleEvent(48, 1); break; case 29: if (Creature* katrana = me->FindNearestCreature(NPC_KATRANA_PRESTOR, 50.0f)) { katrana->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER); me->GetMotionMaster()->Clear(); me->SetFacingToObject(katrana); } _canGreet = false; Talk(SAY_REGINALD_TO_ANDUINN); _events.ScheduleEvent(49, 1); break; default: break; } } void JustSummoned(Creature* creature) override { Summons.Summon(creature); } void SpellHit(Unit*, const SpellInfo* spell) override { if (spell->Id == SPELL_WINDSOR_DEATH) { Talk(SAY_REGINALD_DONT_LET_ESCAPE); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); me->SetStandState(UNIT_STAND_STATE_DEAD); } } Creature* GetCreature(uint64 guid) { auto bounds = me->GetMap()->GetCreatureBySpawnIdStore().equal_range(guid); if (bounds.first == bounds.second) return nullptr; if (Creature* creature = bounds.first->second) return creature; return nullptr; }; void UpdateAI(uint32 diff) override { _events.Update(diff); while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case 1: // Along the road me->GetMotionMaster()->MovePoint(1, -9141.894531f, 376.348145f, 90.683403f); break; case 2: // Along the road, straight up his path me->GetMotionMaster()->MovePoint(2, -9110.274414f, 395.779083f, 92.516273f); break; case 3: // End point by the Stormwind Bridge me->GetMotionMaster()->MovePoint(3, -9049.892578f, 445.026917f, 93.056046f); break; case EVENT_DISMOUNT: me->Dismount(); if (Creature* mercutio = me->SummonCreature(NPC_MERCUTIO, -9049.408203f, 446.522705f, 93.056198f)) { me->HandleEmoteCommand(EMOTE_ONESHOT_ATTACK_UNARMED); Talk(SAY_REGINALD_SHOO_HORSE); mercutio->GetMotionMaster()->MovePoint(1, -9150.777344f, 370.672607f, 90.537186f, false); mercutio->DespawnOrUnsummon(10000); } _events.ScheduleEvent(EVENT_END_INTRO, 3000); break; case EVENT_END_INTRO: _events.ScheduleEvent(EVENT_CHECK_PLAYER, 5 * MINUTE * IN_MILLISECONDS); me->SetFacingTo(3.760818f); me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER); if (Player* player = ObjectAccessor::FindConnectedPlayer(_playerGUID)) Talk(SAY_REGINALD_END_INTRO, player); break; case EVENT_REGINALD_SAY_2: me->SetFacingTo(0.717398f); me->HandleEmoteCommand(EMOTE_ONESHOT_SHOUT); Talk(SAY_REGINALD_MASQUERADE_2); _events.ScheduleEvent(EVENT_KATRANA_SAY_1, 5000); break; case EVENT_KATRANA_SAY_1: { ObjectGuid::LowType guid = GUID_PRESTOR; if (Creature* katrana = GetCreature(guid)) { if (!katrana->IsAlive()) katrana->Respawn(true); me->GetMap()->LoadGrid(8435.00f, 335.55f); katrana->AI()->Talk(SAY_KATRANA_1); } if (Creature* jonathan = me->FindNearestCreature(NPC_JONATHAN, 200.0f)) { _marcusGUID = jonathan->GetGUID(); jonathan->Dismount(); jonathan->setActive(true); jonathan->GetMotionMaster()->MovePoint(0, -8967.960f, 510.008f, 96.351f); for (uint8 counter = 0; counter <= 5; ++counter) { if (Creature* guard = me->SummonCreature(NPC_ROYAL_GUARD, GuardsPos[counter])) { _guardsGUID[counter] = guard->GetGUID(); guard->AI()->SetData(DATA_GUARD_INDEX, 1); _swGuardsSaluted.insert(guard->GetGUID()); } } } _events.ScheduleEvent(8, 3000); break; } case 8: me->GetMotionMaster()->MovePoint(4, -8997.63f, 486.402f, 96.622f); break; case 9: me->GetMotionMaster()->MovePoint(5, -8971.08f, 507.541f, 96.349f); break; case 10: Talk(SAY_REGINALD_TO_MARCUS_1); _events.ScheduleEvent(11, 10000); break; case 11: Talk(SAY_REGINALD_TO_MARCUS_2); _events.ScheduleEvent(12, 4000); break; case 12: if (Creature* jonathan = me->FindNearestCreature(NPC_JONATHAN, 20.0f)) jonathan->AI()->Talk(EMOTE_CONTEMPLATION); _events.ScheduleEvent(13, 6000); break; case 13: if (Creature* jonathan = me->FindNearestCreature(NPC_JONATHAN, 20.0f)) jonathan->AI()->Talk(SAY_JONATHAN_TO_REGINALD_2); _events.ScheduleEvent(14, 10000); break; case 14: if (Creature* jonathan = me->FindNearestCreature(NPC_JONATHAN, 20.0f)) jonathan->AI()->Talk(SAY_JONATHAN_TO_REGINALD_3); _events.ScheduleEvent(15, 6000); break; case 15: Talk(SAY_REGINALD_TO_MARCUS_3); _events.ScheduleEvent(16, 10000); break; case 16: Talk(SAY_REGINALD_TO_MARCUS_4); _events.ScheduleEvent(17, 10000); break; case 17: if (Creature* jonathan = me->FindNearestCreature(NPC_JONATHAN, 20.0f)) { jonathan->SetFacingTo(5.830352f); jonathan->HandleEmoteCommand(EMOTE_ONESHOT_EXCLAMATION); jonathan->AI()->Talk(SAY_JONATHAN_TO_GUARDS_1); } if (Creature* guard = ObjectAccessor::GetCreature(*me, _guardsGUID[5])) { guard->SetFacingTo(2.234f); guard->SetStandState(UNIT_STAND_STATE_KNEEL); } if (Creature* guard = ObjectAccessor::GetCreature(*me, _guardsGUID[4])) guard->GetMotionMaster()->MovePoint(1, -8959.440f, 505.424f, 96.595f); if (Creature* guard = ObjectAccessor::GetCreature(*me, _guardsGUID[3])) guard->GetMotionMaster()->MovePoint(1, -8957.670f, 507.056f, 96.595f); _events.ScheduleEvent(18, 5000); break; case 18: if (Creature* jonathan = me->FindNearestCreature(NPC_JONATHAN, 20.0f)) { jonathan->SetFacingTo(2.234f); jonathan->HandleEmoteCommand(EMOTE_ONESHOT_EXCLAMATION); jonathan->AI()->Talk(SAY_JONATHAN_TO_GUARDS_2); } if (Creature* guard = ObjectAccessor::GetCreature(*me, _guardsGUID[2])) { guard->SetFacingTo(5.375f); guard->SetStandState(UNIT_STAND_STATE_KNEEL); } if (Creature* guard = ObjectAccessor::GetCreature(*me, _guardsGUID[1])) guard->GetMotionMaster()->MovePoint(2, -8970.680f, 519.252f, 96.595f); if (Creature* guard = ObjectAccessor::GetCreature(*me, _guardsGUID[0])) guard->GetMotionMaster()->MovePoint(2, -8969.100f, 520.395f, 96.595f); _events.ScheduleEvent(19, 5000); break; case 19: if (Creature* jonathan = me->FindNearestCreature(NPC_JONATHAN, 20.0f)) { jonathan->HandleEmoteCommand(EMOTE_ONESHOT_SHOUT); jonathan->AI()->Talk(SAY_JONATHAN_TO_GUARDS_3); } _events.ScheduleEvent(20, 3000); break; case 20: if (Creature* jonathan = me->FindNearestCreature(NPC_JONATHAN, 20.0f)) { jonathan->SetFacingToObject(me); jonathan->AI()->Talk(SAY_JONATHAN_TO_REGINALD_4); jonathan->m_Events.AddEvent(new DelayedEmoteEvent(jonathan, EMOTE_ONESHOT_SALUTE), jonathan->m_Events.CalculateTime(1000)); } _events.ScheduleEvent(21, 5000); break; case 21: if (Creature* jonathan = me->FindNearestCreature(NPC_JONATHAN, 20.0f)) { jonathan->SetWalk(true); jonathan->GetMotionMaster()->MovePoint(1, -8974.590f, 516.213f, 96.590f); } _events.ScheduleEvent(22, 5000); break; case 22: if (Creature* jonathan = me->FindNearestCreature(NPC_JONATHAN, 20.0f)) { jonathan->GetMotionMaster()->Clear(); jonathan->SetFacingToObject(me); jonathan->SetStandState(UNIT_STAND_STATE_KNEEL); } _events.ScheduleEvent(23, 3000); break; case 23: if (Creature* jonathan = me->FindNearestCreature(NPC_JONATHAN, 20.0f)) { me->GetMotionMaster()->Clear(); me->SetFacingToObject(jonathan); Talk(SAY_REGINALD_TO_MARCUS_5); jonathan->m_Events.AddEvent(new DelayedResetEvent(jonathan), jonathan->m_Events.CalculateTime(60000)); } _events.ScheduleEvent(24, 4000); break; case 24: me->GetMotionMaster()->Clear(); me->SetFacingTo(0.06f); Talk(SAY_REGINALD_MASQUERADE_3); me->m_Events.AddEvent(new DelayedEmoteEvent(me, EMOTE_ONESHOT_POINT), me->m_Events.CalculateTime(1000)); _events.ScheduleEvent(25, 5000); break; case 25: _canGreet = true; me->GetMotionMaster()->MovePoint(6, -8953.17f, 518.537f, 96.355f, false); break; case 26: me->GetMotionMaster()->MovePoint(7, -8936.33f, 501.777f, 94.066f, false); break; case 27: me->GetMotionMaster()->MovePoint(8, -8922.52f, 498.45f, 93.869f, false); break; case 28: me->GetMotionMaster()->MovePoint(9, -8907.64f, 509.941f, 93.840f, false); break; case 29: me->GetMotionMaster()->MovePoint(10, -8925.26f, 542.51f, 94.274f, false); break; case 30: me->GetMotionMaster()->MovePoint(11, -8832.28f, 622.285f, 93.686f, false); break; case 31: me->GetMotionMaster()->MovePoint(12, -8824.8f, 621.713f, 94.084f, false); break; case 32: me->GetMotionMaster()->MovePoint(13, -8796.46f, 590.922f, 97.466f, false); break; case 33: me->GetMotionMaster()->MovePoint(14, -8769.85f, 607.883f, 97.118f, false); break; case 34: me->GetMotionMaster()->MovePoint(15, -8737.14f, 574.741f, 97.398f, false); break; case 35: me->GetMotionMaster()->MovePoint(16, -8746.27f, 563.446f, 97.399f, false); break; case 36: me->GetMotionMaster()->MovePoint(17, -8745.5f, 557.877f, 97.704f, false); break; case 37: me->GetMotionMaster()->MovePoint(18, -8730.95f, 541.477f, 101.12f, false); break; case 38: me->GetMotionMaster()->MovePoint(19, -8713.16f, 520.692f, 97.227f, false); break; case 39: me->GetMotionMaster()->MovePoint(20, -8677.09f, 549.614f, 97.438f, false); break; case 40: me->GetMotionMaster()->MovePoint(21, -8655.72f, 552.732f, 96.941f, false); break; case 41: me->GetMotionMaster()->MovePoint(22, -8641.68f, 540.516f, 98.972f, false); break; case 42: me->GetMotionMaster()->MovePoint(23, -8620.08f, 520.120f, 102.812f, false); break; case 43: me->GetMotionMaster()->MovePoint(24, -8591.09f, 492.553f, 104.032f, false); break; case 44: me->GetMotionMaster()->MovePoint(25, -8562.45f, 463.583f, 104.517f, false); break; case 45: // Break here, before keep. Summons.DespawnAll(); me->GetMotionMaster()->MovePoint(26, -8548.63f, 467.38f, 104.517f); break; case 46: me->GetMotionMaster()->MovePoint(27, -8487.77f, 391.44f, 108.386f); break; case 47: me->GetMotionMaster()->MovePoint(28, -8455.95f, 351.225f, 120.88f); break; case 48: // Say something me->GetMotionMaster()->MovePoint(29, -8446.87f, 339.904f, 121.33f, false); break; case 49: _events.ScheduleEvent(50, 9000); _events.ScheduleEvent(64, 4000); _events.ScheduleEvent(59, 2000); break; case 50: if (Creature* katrana = me->FindNearestCreature(NPC_KATRANA_PRESTOR, 20.0f)) { katrana->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER); katrana->AI()->Talk(EMOTE_KATRANA_LAUGH); katrana->m_Events.AddEvent(new DelayedEmoteEvent(katrana, EMOTE_ONESHOT_LAUGH), katrana->m_Events.CalculateTime(1000)); } _events.ScheduleEvent(51, 4000); break; case 51: if (Creature* katrana = me->FindNearestCreature(NPC_KATRANA_PRESTOR, 20.0f)) katrana->AI()->Talk(SAY_KATRANA_2); _events.ScheduleEvent(52, 8000); break; case 52: if (Creature* katrana = me->FindNearestCreature(NPC_KATRANA_PRESTOR, 20.0f)) katrana->AI()->Talk(SAY_KATRANA_3); _events.ScheduleEvent(53, 15000); _events.ScheduleEvent(65, 10000); break; case 53: Talk(EMOTE_REACH_TABLETS); _events.ScheduleEvent(54, 6000); break; case 54: Talk(SAY_REGINALD_TABLETS); _events.ScheduleEvent(55, 5000); break; case 55: Talk(SAY_REGINALD_LISTEN_DRAGON); _events.ScheduleEvent(56, 5000); break; case 56: DoCastAOE(SPELL_WINDSOR_READ); Talk(EMOTE_READ_TABLETS); _events.ScheduleEvent(57, 11000); break; case 57: if (Creature* katrana = me->FindNearestCreature(NPC_KATRANA_PRESTOR, 20.0f)) { katrana->UpdateEntry(NPC_LADY_ONYXIA, nullptr); katrana->AI()->Talk(SAY_ONYXIA_CURIOUS); } if (Creature* bolvar = me->FindNearestCreature(NPC_BOLVAR, 20.0f)) { bolvar->SetWalk(true); bolvar->AI()->Talk(EMOTE_BOLVAR_GASP); bolvar->GetMotionMaster()->MovePoint(1, -8448.690f, 337.074f, 121.330f, false); } _events.ScheduleEvent(58, 2000); _events.ScheduleEvent(60, 6000); break; case 58: if (Creature* onyxia = me->FindNearestCreature(NPC_LADY_ONYXIA, 20.0f)) if (Creature* bolvar = me->FindNearestCreature(NPC_BOLVAR, 20.0f)) { bolvar->GetMotionMaster()->Clear(); bolvar->SetFacingToObject(onyxia); bolvar->AI()->Talk(SAY_BOLVAR_YELL_GUARDS); bolvar->SetUInt32Value(UNIT_NPC_EMOTESTATE, 45); } break; case 59: if (Creature* bolvar = me->FindNearestCreature(NPC_BOLVAR, 20.0f)) { bolvar->SetFaction(11); bolvar->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER); bolvar->AI()->Talk(SAY_BOLVAR_TO_ANDUINN); } if (Creature* anduinn = me->FindNearestCreature(NPC_ANDUINN, 20.0f)) { anduinn->SetWalk(true); anduinn->GetMotionMaster()->MovePoint(1, -8505.770f, 338.312f, 120.886f, true); anduinn->DespawnOrUnsummon(5000); } break; case 60: { if (Creature* onyxia = me->FindNearestCreature(NPC_LADY_ONYXIA, 20.0f)) onyxia->AI()->Talk(SAY_ONYXIA_COME_GUARDS); std::list<Creature*> guardList; me->GetCreatureListWithEntryInGrid(guardList, NPC_ROYAL_GUARD, 25.0f); if (!guardList.empty()) { int8 counter = 0; for (auto itr : guardList) { if (counter >= 8) continue; if (!itr->IsAlive()) itr->Respawn(true); itr->UpdateEntry(NPC_ONYXIA_GUARD, nullptr); itr->AI()->SetGUID(me->GetGUID()); itr->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NON_ATTACKABLE); itr->m_Events.AddEvent(new DelayedAttackStartEvent(itr), itr->m_Events.CalculateTime(8000)); counter++; } } _events.ScheduleEvent(61, 5000); _events.ScheduleEvent(66, 6000); break; } case 61: if (Creature* onyxia = me->FindNearestCreature(NPC_LADY_ONYXIA, 20.0f)) onyxia->AI()->Talk(SAY_ONYXYA_WAS_THIS_FATED); _events.ScheduleEvent(62, 10000); break; case 62: if (Creature* onyxia = me->FindNearestCreature(NPC_LADY_ONYXIA, 20.0f)) onyxia->AI()->Talk(SAY_ONYXIA_FAREWELL); _events.ScheduleEvent(63, 8000); break; case 63: if (Creature* onyxia = me->FindNearestCreature(NPC_LADY_ONYXIA, 20.0f)) { onyxia->CastSpell(onyxia, 20466, true); onyxia->DespawnOrUnsummon(2000); } break; case 64: Talk(SAY_REGINALD_MASQUERADE_OVER); if (Creature* katrana = me->FindNearestCreature(NPC_KATRANA_PRESTOR, 20.0f)) { me->GetMotionMaster()->Clear(); me->SetFacingToObject(katrana); me->m_Events.AddEvent(new DelayedEmoteEvent(me, EMOTE_ONESHOT_POINT), me->m_Events.CalculateTime(1000)); } break; case 65: Talk(SAY_REGINALD_NO_ESCAPE_FATE); break; case 66: if (Creature* onyxia = me->FindNearestCreature(NPC_LADY_ONYXIA, 20.0f)) onyxia->AI()->DoCastAOE(SPELL_WINDSOR_DEATH, true); break; case EVENT_CHECK_PLAYER: if (!ObjectAccessor::FindPlayer(_playerGUID)) { DoAction(ACTION_RESET_MASQUERADE); me->DespawnOrUnsummon(10000); } else if (Player* player = ObjectAccessor::FindConnectedPlayer(_playerGUID)) { if (!player->IsInMap(me) || !player->IsWithinDist(me, 100.0f)) { DoAction(ACTION_RESET_MASQUERADE); me->DespawnOrUnsummon(10000); } } _events.Repeat(5min); break; case 68: if (Creature* bolvar = me->FindNearestCreature(NPC_BOLVAR, 20.0f)) { bolvar->SetUInt32Value(UNIT_NPC_EMOTESTATE, 0); bolvar->GetMotionMaster()->Clear(); bolvar->GetMotionMaster()->MovePoint(1, -8448.279f, 338.398f, 121.329f, false); bolvar->SetFacingToObject(me); bolvar->SetStandState(UNIT_STAND_STATE_KNEEL); } _events.ScheduleEvent(69, 3000); break; case 69: if (Creature* bolvar = me->FindNearestCreature(NPC_BOLVAR, 20.0f)) bolvar->AI()->Talk(SAY_BOLVAR_TO_REGINALD); _events.ScheduleEvent(70, 3000); break; case 70: Talk(SAY_REGINALD_BOLVAR_MEDALION); _events.ScheduleEvent(71, 3000); break; case 71: Talk(EMOTE_REGINALD_DIES); _events.ScheduleEvent(72, 5000); break; case 72: if (Creature* bolvar = me->FindNearestCreature(NPC_BOLVAR, 20.0f)) { bolvar->SetStandState(UNIT_STAND_STATE_STAND); bolvar->SetSpeed(MOVE_WALK, 1.0f); bolvar->SetWalk(true); bolvar->GetMotionMaster()->MoveTargetedHome(); bolvar->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER); if (Player* player = ObjectAccessor::FindConnectedPlayer(_playerGUID)) player->GroupEventHappens(QUEST_THE_GREAT_MASQUERADE, me); DoAction(ACTION_RESET_MASQUERADE); me->DespawnOrUnsummon(10000); } break; default: break; } if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } } private: EventMap _events; ObjectGuid _playerGUID; SummonList Summons; ObjectGuid _guardsGUID[6]; ObjectGuid _marcusGUID; GuidSet _swGuardsSaluted; bool _canGreet; }; bool OnGossipSelect(Player* player, Creature* me, uint32 /*menuId*/, uint32 gossipListId) override { CloseGossipMenuFor(player); uint32 const action = player->PlayerTalkClass->GetGossipOptionAction(gossipListId); if (action == 0) { me->m_Events.AddEvent(new DelayedEmoteEvent(me, EMOTE_ONESHOT_POINT), me->m_Events.CalculateTime(1000)); me->AI()->Talk(SAY_REGINALD_MOVE_IN_KEEP); me->AI()->DoAction(ACTION_START_ESCORT); me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); return true; } return true; } bool OnQuestAccept(Player* player, Creature* me, Quest const* quest) override { if (quest->GetQuestId() == QUEST_THE_GREAT_MASQUERADE) { me->AI()->SetGUID(player->GetGUID(), ACTION_START_MASQUERADE); me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER); me->AI()->Talk(SAY_REGINALD_MASQUERADE_1); me->SetWalk(true); if (Creature* rowe = me->FindNearestCreature(NPC_SQUIRE_ROWE, 20.0f)) rowe->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER); } return false; } CreatureAI* GetAI(Creature* creature) const override { return new npc_reginald_windsorAI(creature); } }; class npc_royal_stormwind_guard : public CreatureScript { public: npc_royal_stormwind_guard() : CreatureScript("npc_royal_stormwind_guard") { } struct npc_royal_stormwind_guardAI : public ScriptedAI { npc_royal_stormwind_guardAI(Creature* creature) : ScriptedAI(creature) { _inEvent = false; } void SetData(uint32 type, uint32 data) override { if (type == DATA_GUARD_INDEX) _inEvent = data == 1 ? true : false; } void SetGUID(ObjectGuid guid, int32 /*data*/) override { _invokerGUID = guid; } void JustDied(Unit* /*killer*/) override { if (me->GetEntry() == NPC_ONYXIA_GUARD) { if (Creature* windsor = ObjectAccessor::GetCreature(*me, _invokerGUID)) windsor->AI()->DoAction(ACTION_INCREASE_DEATH_COUNTER); } } void JustEngagedWith(Unit* /*victim*/) override { if (me->GetEntry() == NPC_ONYXIA_GUARD) { _events.ScheduleEvent(5, 3000); _events.ScheduleEvent(6, 4000); } } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case 5: DoCastVictim(15284); // Cleave _events.ScheduleEvent(5, urand(5000, 8000)); break; } } DoMeleeAttackIfReady(); } void MovementInform(uint32 type, uint32 point) override { if (type != POINT_MOTION_TYPE || !_inEvent) return; me->GetMotionMaster()->Clear(); if (point == 1) me->SetFacingTo(2.234f); else if (point == 2) me->SetFacingTo(5.375f); me->SetStandState(UNIT_STAND_STATE_KNEEL); } private: bool _inEvent; ObjectGuid _invokerGUID; EventMap _events; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_royal_stormwind_guardAI(creature); } }; void AddSC_quest_the_masquerade_60_2() { new npc_reginald_windsor(); new npc_squire_rowe(); new npc_royal_stormwind_guard(); }
1
0.98232
1
0.98232
game-dev
MEDIA
0.993303
game-dev
0.974946
1
0.974946
glKarin/com.n0n3m4.diii4a
25,257
Q3E/src/main/jni/quake3/code/game/g_syscalls.c
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Quake III Arena source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Quake III Arena source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ // #include "g_local.h" // this file is only included when building a dll // g_syscalls.asm is included instead when building a qvm #ifdef Q3_VM #error "Do not use in VM build" #endif static intptr_t (QDECL *syscall)( intptr_t arg, ... ) = (intptr_t (QDECL *)( intptr_t, ...))-1; Q_EXPORT void dllEntry( intptr_t (QDECL *syscallptr)( intptr_t arg,... ) ) { syscall = syscallptr; } int PASSFLOAT( float x ) { floatint_t fi; fi.f = x; return fi.i; } void trap_Print( const char *text ) { syscall( G_PRINT, text ); } void trap_Error( const char *text ) { syscall( G_ERROR, text ); // shut up GCC warning about returning functions, because we know better exit(1); } int trap_Milliseconds( void ) { return syscall( G_MILLISECONDS ); } int trap_Argc( void ) { return syscall( G_ARGC ); } void trap_Argv( int n, char *buffer, int bufferLength ) { syscall( G_ARGV, n, buffer, bufferLength ); } int trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode ) { return syscall( G_FS_FOPEN_FILE, qpath, f, mode ); } void trap_FS_Read( void *buffer, int len, fileHandle_t f ) { syscall( G_FS_READ, buffer, len, f ); } void trap_FS_Write( const void *buffer, int len, fileHandle_t f ) { syscall( G_FS_WRITE, buffer, len, f ); } void trap_FS_FCloseFile( fileHandle_t f ) { syscall( G_FS_FCLOSE_FILE, f ); } int trap_FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) { return syscall( G_FS_GETFILELIST, path, extension, listbuf, bufsize ); } int trap_FS_Seek( fileHandle_t f, long offset, int origin ) { return syscall( G_FS_SEEK, f, offset, origin ); } void trap_SendConsoleCommand( int exec_when, const char *text ) { syscall( G_SEND_CONSOLE_COMMAND, exec_when, text ); } void trap_Cvar_Register( vmCvar_t *cvar, const char *var_name, const char *value, int flags ) { syscall( G_CVAR_REGISTER, cvar, var_name, value, flags ); } void trap_Cvar_Update( vmCvar_t *cvar ) { syscall( G_CVAR_UPDATE, cvar ); } void trap_Cvar_Set( const char *var_name, const char *value ) { syscall( G_CVAR_SET, var_name, value ); } int trap_Cvar_VariableIntegerValue( const char *var_name ) { return syscall( G_CVAR_VARIABLE_INTEGER_VALUE, var_name ); } void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) { syscall( G_CVAR_VARIABLE_STRING_BUFFER, var_name, buffer, bufsize ); } void trap_LocateGameData( gentity_t *gEnts, int numGEntities, int sizeofGEntity_t, playerState_t *clients, int sizeofGClient ) { syscall( G_LOCATE_GAME_DATA, gEnts, numGEntities, sizeofGEntity_t, clients, sizeofGClient ); } void trap_DropClient( int clientNum, const char *reason ) { syscall( G_DROP_CLIENT, clientNum, reason ); } void trap_SendServerCommand( int clientNum, const char *text ) { syscall( G_SEND_SERVER_COMMAND, clientNum, text ); } void trap_SetConfigstring( int num, const char *string ) { syscall( G_SET_CONFIGSTRING, num, string ); } void trap_GetConfigstring( int num, char *buffer, int bufferSize ) { syscall( G_GET_CONFIGSTRING, num, buffer, bufferSize ); } void trap_GetUserinfo( int num, char *buffer, int bufferSize ) { syscall( G_GET_USERINFO, num, buffer, bufferSize ); } void trap_SetUserinfo( int num, const char *buffer ) { syscall( G_SET_USERINFO, num, buffer ); } void trap_GetServerinfo( char *buffer, int bufferSize ) { syscall( G_GET_SERVERINFO, buffer, bufferSize ); } void trap_SetBrushModel( gentity_t *ent, const char *name ) { syscall( G_SET_BRUSH_MODEL, ent, name ); } void trap_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask ) { syscall( G_TRACE, results, start, mins, maxs, end, passEntityNum, contentmask ); } void trap_TraceCapsule( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask ) { syscall( G_TRACECAPSULE, results, start, mins, maxs, end, passEntityNum, contentmask ); } int trap_PointContents( const vec3_t point, int passEntityNum ) { return syscall( G_POINT_CONTENTS, point, passEntityNum ); } qboolean trap_InPVS( const vec3_t p1, const vec3_t p2 ) { return syscall( G_IN_PVS, p1, p2 ); } qboolean trap_InPVSIgnorePortals( const vec3_t p1, const vec3_t p2 ) { return syscall( G_IN_PVS_IGNORE_PORTALS, p1, p2 ); } void trap_AdjustAreaPortalState( gentity_t *ent, qboolean open ) { syscall( G_ADJUST_AREA_PORTAL_STATE, ent, open ); } qboolean trap_AreasConnected( int area1, int area2 ) { return syscall( G_AREAS_CONNECTED, area1, area2 ); } void trap_LinkEntity( gentity_t *ent ) { syscall( G_LINKENTITY, ent ); } void trap_UnlinkEntity( gentity_t *ent ) { syscall( G_UNLINKENTITY, ent ); } int trap_EntitiesInBox( const vec3_t mins, const vec3_t maxs, int *list, int maxcount ) { return syscall( G_ENTITIES_IN_BOX, mins, maxs, list, maxcount ); } qboolean trap_EntityContact( const vec3_t mins, const vec3_t maxs, const gentity_t *ent ) { return syscall( G_ENTITY_CONTACT, mins, maxs, ent ); } qboolean trap_EntityContactCapsule( const vec3_t mins, const vec3_t maxs, const gentity_t *ent ) { return syscall( G_ENTITY_CONTACTCAPSULE, mins, maxs, ent ); } int trap_BotAllocateClient( void ) { return syscall( G_BOT_ALLOCATE_CLIENT ); } void trap_BotFreeClient( int clientNum ) { syscall( G_BOT_FREE_CLIENT, clientNum ); } void trap_GetUsercmd( int clientNum, usercmd_t *cmd ) { syscall( G_GET_USERCMD, clientNum, cmd ); } qboolean trap_GetEntityToken( char *buffer, int bufferSize ) { return syscall( G_GET_ENTITY_TOKEN, buffer, bufferSize ); } int trap_DebugPolygonCreate(int color, int numPoints, vec3_t *points) { return syscall( G_DEBUG_POLYGON_CREATE, color, numPoints, points ); } void trap_DebugPolygonDelete(int id) { syscall( G_DEBUG_POLYGON_DELETE, id ); } int trap_RealTime( qtime_t *qtime ) { return syscall( G_REAL_TIME, qtime ); } void trap_SnapVector( float *v ) { syscall( G_SNAPVECTOR, v ); } // BotLib traps start here int trap_BotLibSetup( void ) { return syscall( BOTLIB_SETUP ); } int trap_BotLibShutdown( void ) { return syscall( BOTLIB_SHUTDOWN ); } int trap_BotLibVarSet(char *var_name, char *value) { return syscall( BOTLIB_LIBVAR_SET, var_name, value ); } int trap_BotLibVarGet(char *var_name, char *value, int size) { return syscall( BOTLIB_LIBVAR_GET, var_name, value, size ); } int trap_BotLibDefine(char *string) { return syscall( BOTLIB_PC_ADD_GLOBAL_DEFINE, string ); } int trap_BotLibStartFrame(float time) { return syscall( BOTLIB_START_FRAME, PASSFLOAT( time ) ); } int trap_BotLibLoadMap(const char *mapname) { return syscall( BOTLIB_LOAD_MAP, mapname ); } int trap_BotLibUpdateEntity(int ent, void /* struct bot_updateentity_s */ *bue) { return syscall( BOTLIB_UPDATENTITY, ent, bue ); } int trap_BotLibTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3) { return syscall( BOTLIB_TEST, parm0, parm1, parm2, parm3 ); } int trap_BotGetSnapshotEntity( int clientNum, int sequence ) { return syscall( BOTLIB_GET_SNAPSHOT_ENTITY, clientNum, sequence ); } int trap_BotGetServerCommand(int clientNum, char *message, int size) { return syscall( BOTLIB_GET_CONSOLE_MESSAGE, clientNum, message, size ); } void trap_BotUserCommand(int clientNum, usercmd_t *ucmd) { syscall( BOTLIB_USER_COMMAND, clientNum, ucmd ); } void trap_AAS_EntityInfo(int entnum, void /* struct aas_entityinfo_s */ *info) { syscall( BOTLIB_AAS_ENTITY_INFO, entnum, info ); } int trap_AAS_Initialized(void) { return syscall( BOTLIB_AAS_INITIALIZED ); } void trap_AAS_PresenceTypeBoundingBox(int presencetype, vec3_t mins, vec3_t maxs) { syscall( BOTLIB_AAS_PRESENCE_TYPE_BOUNDING_BOX, presencetype, mins, maxs ); } float trap_AAS_Time(void) { floatint_t fi; fi.i = syscall( BOTLIB_AAS_TIME ); return fi.f; } int trap_AAS_PointAreaNum(vec3_t point) { return syscall( BOTLIB_AAS_POINT_AREA_NUM, point ); } int trap_AAS_PointReachabilityAreaIndex(vec3_t point) { return syscall( BOTLIB_AAS_POINT_REACHABILITY_AREA_INDEX, point ); } int trap_AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas) { return syscall( BOTLIB_AAS_TRACE_AREAS, start, end, areas, points, maxareas ); } int trap_AAS_BBoxAreas(vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas) { return syscall( BOTLIB_AAS_BBOX_AREAS, absmins, absmaxs, areas, maxareas ); } int trap_AAS_AreaInfo( int areanum, void /* struct aas_areainfo_s */ *info ) { return syscall( BOTLIB_AAS_AREA_INFO, areanum, info ); } int trap_AAS_PointContents(vec3_t point) { return syscall( BOTLIB_AAS_POINT_CONTENTS, point ); } int trap_AAS_NextBSPEntity(int ent) { return syscall( BOTLIB_AAS_NEXT_BSP_ENTITY, ent ); } int trap_AAS_ValueForBSPEpairKey(int ent, char *key, char *value, int size) { return syscall( BOTLIB_AAS_VALUE_FOR_BSP_EPAIR_KEY, ent, key, value, size ); } int trap_AAS_VectorForBSPEpairKey(int ent, char *key, vec3_t v) { return syscall( BOTLIB_AAS_VECTOR_FOR_BSP_EPAIR_KEY, ent, key, v ); } int trap_AAS_FloatForBSPEpairKey(int ent, char *key, float *value) { return syscall( BOTLIB_AAS_FLOAT_FOR_BSP_EPAIR_KEY, ent, key, value ); } int trap_AAS_IntForBSPEpairKey(int ent, char *key, int *value) { return syscall( BOTLIB_AAS_INT_FOR_BSP_EPAIR_KEY, ent, key, value ); } int trap_AAS_AreaReachability(int areanum) { return syscall( BOTLIB_AAS_AREA_REACHABILITY, areanum ); } int trap_AAS_AreaTravelTimeToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags) { return syscall( BOTLIB_AAS_AREA_TRAVEL_TIME_TO_GOAL_AREA, areanum, origin, goalareanum, travelflags ); } int trap_AAS_EnableRoutingArea( int areanum, int enable ) { return syscall( BOTLIB_AAS_ENABLE_ROUTING_AREA, areanum, enable ); } int trap_AAS_PredictRoute(void /*struct aas_predictroute_s*/ *route, int areanum, vec3_t origin, int goalareanum, int travelflags, int maxareas, int maxtime, int stopevent, int stopcontents, int stoptfl, int stopareanum) { return syscall( BOTLIB_AAS_PREDICT_ROUTE, route, areanum, origin, goalareanum, travelflags, maxareas, maxtime, stopevent, stopcontents, stoptfl, stopareanum ); } int trap_AAS_AlternativeRouteGoals(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags, void /*struct aas_altroutegoal_s*/ *altroutegoals, int maxaltroutegoals, int type) { return syscall( BOTLIB_AAS_ALTERNATIVE_ROUTE_GOAL, start, startareanum, goal, goalareanum, travelflags, altroutegoals, maxaltroutegoals, type ); } int trap_AAS_Swimming(vec3_t origin) { return syscall( BOTLIB_AAS_SWIMMING, origin ); } int trap_AAS_PredictClientMovement(void /* struct aas_clientmove_s */ *move, int entnum, vec3_t origin, int presencetype, int onground, vec3_t velocity, vec3_t cmdmove, int cmdframes, int maxframes, float frametime, int stopevent, int stopareanum, int visualize) { return syscall( BOTLIB_AAS_PREDICT_CLIENT_MOVEMENT, move, entnum, origin, presencetype, onground, velocity, cmdmove, cmdframes, maxframes, PASSFLOAT(frametime), stopevent, stopareanum, visualize ); } void trap_EA_Say(int client, char *str) { syscall( BOTLIB_EA_SAY, client, str ); } void trap_EA_SayTeam(int client, char *str) { syscall( BOTLIB_EA_SAY_TEAM, client, str ); } void trap_EA_Command(int client, char *command) { syscall( BOTLIB_EA_COMMAND, client, command ); } void trap_EA_Action(int client, int action) { syscall( BOTLIB_EA_ACTION, client, action ); } void trap_EA_Gesture(int client) { syscall( BOTLIB_EA_GESTURE, client ); } void trap_EA_Talk(int client) { syscall( BOTLIB_EA_TALK, client ); } void trap_EA_Attack(int client) { syscall( BOTLIB_EA_ATTACK, client ); } void trap_EA_Use(int client) { syscall( BOTLIB_EA_USE, client ); } void trap_EA_Respawn(int client) { syscall( BOTLIB_EA_RESPAWN, client ); } void trap_EA_Crouch(int client) { syscall( BOTLIB_EA_CROUCH, client ); } void trap_EA_MoveUp(int client) { syscall( BOTLIB_EA_MOVE_UP, client ); } void trap_EA_MoveDown(int client) { syscall( BOTLIB_EA_MOVE_DOWN, client ); } void trap_EA_MoveForward(int client) { syscall( BOTLIB_EA_MOVE_FORWARD, client ); } void trap_EA_MoveBack(int client) { syscall( BOTLIB_EA_MOVE_BACK, client ); } void trap_EA_MoveLeft(int client) { syscall( BOTLIB_EA_MOVE_LEFT, client ); } void trap_EA_MoveRight(int client) { syscall( BOTLIB_EA_MOVE_RIGHT, client ); } void trap_EA_SelectWeapon(int client, int weapon) { syscall( BOTLIB_EA_SELECT_WEAPON, client, weapon ); } void trap_EA_Jump(int client) { syscall( BOTLIB_EA_JUMP, client ); } void trap_EA_DelayedJump(int client) { syscall( BOTLIB_EA_DELAYED_JUMP, client ); } void trap_EA_Move(int client, vec3_t dir, float speed) { syscall( BOTLIB_EA_MOVE, client, dir, PASSFLOAT(speed) ); } void trap_EA_View(int client, vec3_t viewangles) { syscall( BOTLIB_EA_VIEW, client, viewangles ); } void trap_EA_EndRegular(int client, float thinktime) { syscall( BOTLIB_EA_END_REGULAR, client, PASSFLOAT(thinktime) ); } void trap_EA_GetInput(int client, float thinktime, void /* struct bot_input_s */ *input) { syscall( BOTLIB_EA_GET_INPUT, client, PASSFLOAT(thinktime), input ); } void trap_EA_ResetInput(int client) { syscall( BOTLIB_EA_RESET_INPUT, client ); } int trap_BotLoadCharacter(char *charfile, float skill) { return syscall( BOTLIB_AI_LOAD_CHARACTER, charfile, PASSFLOAT(skill)); } void trap_BotFreeCharacter(int character) { syscall( BOTLIB_AI_FREE_CHARACTER, character ); } float trap_Characteristic_Float(int character, int index) { floatint_t fi; fi.i = syscall( BOTLIB_AI_CHARACTERISTIC_FLOAT, character, index ); return fi.f; } float trap_Characteristic_BFloat(int character, int index, float min, float max) { floatint_t fi; fi.i = syscall( BOTLIB_AI_CHARACTERISTIC_BFLOAT, character, index, PASSFLOAT(min), PASSFLOAT(max) ); return fi.f; } int trap_Characteristic_Integer(int character, int index) { return syscall( BOTLIB_AI_CHARACTERISTIC_INTEGER, character, index ); } int trap_Characteristic_BInteger(int character, int index, int min, int max) { return syscall( BOTLIB_AI_CHARACTERISTIC_BINTEGER, character, index, min, max ); } void trap_Characteristic_String(int character, int index, char *buf, int size) { syscall( BOTLIB_AI_CHARACTERISTIC_STRING, character, index, buf, size ); } int trap_BotAllocChatState(void) { return syscall( BOTLIB_AI_ALLOC_CHAT_STATE ); } void trap_BotFreeChatState(int handle) { syscall( BOTLIB_AI_FREE_CHAT_STATE, handle ); } void trap_BotQueueConsoleMessage(int chatstate, int type, char *message) { syscall( BOTLIB_AI_QUEUE_CONSOLE_MESSAGE, chatstate, type, message ); } void trap_BotRemoveConsoleMessage(int chatstate, int handle) { syscall( BOTLIB_AI_REMOVE_CONSOLE_MESSAGE, chatstate, handle ); } int trap_BotNextConsoleMessage(int chatstate, void /* struct bot_consolemessage_s */ *cm) { return syscall( BOTLIB_AI_NEXT_CONSOLE_MESSAGE, chatstate, cm ); } int trap_BotNumConsoleMessages(int chatstate) { return syscall( BOTLIB_AI_NUM_CONSOLE_MESSAGE, chatstate ); } void trap_BotInitialChat(int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7 ) { syscall( BOTLIB_AI_INITIAL_CHAT, chatstate, type, mcontext, var0, var1, var2, var3, var4, var5, var6, var7 ); } int trap_BotNumInitialChats(int chatstate, char *type) { return syscall( BOTLIB_AI_NUM_INITIAL_CHATS, chatstate, type ); } int trap_BotReplyChat(int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7 ) { return syscall( BOTLIB_AI_REPLY_CHAT, chatstate, message, mcontext, vcontext, var0, var1, var2, var3, var4, var5, var6, var7 ); } int trap_BotChatLength(int chatstate) { return syscall( BOTLIB_AI_CHAT_LENGTH, chatstate ); } void trap_BotEnterChat(int chatstate, int client, int sendto) { syscall( BOTLIB_AI_ENTER_CHAT, chatstate, client, sendto ); } void trap_BotGetChatMessage(int chatstate, char *buf, int size) { syscall( BOTLIB_AI_GET_CHAT_MESSAGE, chatstate, buf, size); } int trap_StringContains(char *str1, char *str2, int casesensitive) { return syscall( BOTLIB_AI_STRING_CONTAINS, str1, str2, casesensitive ); } int trap_BotFindMatch(char *str, void /* struct bot_match_s */ *match, unsigned long int context) { return syscall( BOTLIB_AI_FIND_MATCH, str, match, context ); } void trap_BotMatchVariable(void /* struct bot_match_s */ *match, int variable, char *buf, int size) { syscall( BOTLIB_AI_MATCH_VARIABLE, match, variable, buf, size ); } void trap_UnifyWhiteSpaces(char *string) { syscall( BOTLIB_AI_UNIFY_WHITE_SPACES, string ); } void trap_BotReplaceSynonyms(char *string, unsigned long int context) { syscall( BOTLIB_AI_REPLACE_SYNONYMS, string, context ); } int trap_BotLoadChatFile(int chatstate, char *chatfile, char *chatname) { return syscall( BOTLIB_AI_LOAD_CHAT_FILE, chatstate, chatfile, chatname ); } void trap_BotSetChatGender(int chatstate, int gender) { syscall( BOTLIB_AI_SET_CHAT_GENDER, chatstate, gender ); } void trap_BotSetChatName(int chatstate, char *name, int client) { syscall( BOTLIB_AI_SET_CHAT_NAME, chatstate, name, client ); } void trap_BotResetGoalState(int goalstate) { syscall( BOTLIB_AI_RESET_GOAL_STATE, goalstate ); } void trap_BotResetAvoidGoals(int goalstate) { syscall( BOTLIB_AI_RESET_AVOID_GOALS, goalstate ); } void trap_BotRemoveFromAvoidGoals(int goalstate, int number) { syscall( BOTLIB_AI_REMOVE_FROM_AVOID_GOALS, goalstate, number); } void trap_BotPushGoal(int goalstate, void /* struct bot_goal_s */ *goal) { syscall( BOTLIB_AI_PUSH_GOAL, goalstate, goal ); } void trap_BotPopGoal(int goalstate) { syscall( BOTLIB_AI_POP_GOAL, goalstate ); } void trap_BotEmptyGoalStack(int goalstate) { syscall( BOTLIB_AI_EMPTY_GOAL_STACK, goalstate ); } void trap_BotDumpAvoidGoals(int goalstate) { syscall( BOTLIB_AI_DUMP_AVOID_GOALS, goalstate ); } void trap_BotDumpGoalStack(int goalstate) { syscall( BOTLIB_AI_DUMP_GOAL_STACK, goalstate ); } void trap_BotGoalName(int number, char *name, int size) { syscall( BOTLIB_AI_GOAL_NAME, number, name, size ); } int trap_BotGetTopGoal(int goalstate, void /* struct bot_goal_s */ *goal) { return syscall( BOTLIB_AI_GET_TOP_GOAL, goalstate, goal ); } int trap_BotGetSecondGoal(int goalstate, void /* struct bot_goal_s */ *goal) { return syscall( BOTLIB_AI_GET_SECOND_GOAL, goalstate, goal ); } int trap_BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelflags) { return syscall( BOTLIB_AI_CHOOSE_LTG_ITEM, goalstate, origin, inventory, travelflags ); } int trap_BotChooseNBGItem(int goalstate, vec3_t origin, int *inventory, int travelflags, void /* struct bot_goal_s */ *ltg, float maxtime) { return syscall( BOTLIB_AI_CHOOSE_NBG_ITEM, goalstate, origin, inventory, travelflags, ltg, PASSFLOAT(maxtime) ); } int trap_BotTouchingGoal(vec3_t origin, void /* struct bot_goal_s */ *goal) { return syscall( BOTLIB_AI_TOUCHING_GOAL, origin, goal ); } int trap_BotItemGoalInVisButNotVisible(int viewer, vec3_t eye, vec3_t viewangles, void /* struct bot_goal_s */ *goal) { return syscall( BOTLIB_AI_ITEM_GOAL_IN_VIS_BUT_NOT_VISIBLE, viewer, eye, viewangles, goal ); } int trap_BotGetLevelItemGoal(int index, char *classname, void /* struct bot_goal_s */ *goal) { return syscall( BOTLIB_AI_GET_LEVEL_ITEM_GOAL, index, classname, goal ); } int trap_BotGetNextCampSpotGoal(int num, void /* struct bot_goal_s */ *goal) { return syscall( BOTLIB_AI_GET_NEXT_CAMP_SPOT_GOAL, num, goal ); } int trap_BotGetMapLocationGoal(char *name, void /* struct bot_goal_s */ *goal) { return syscall( BOTLIB_AI_GET_MAP_LOCATION_GOAL, name, goal ); } float trap_BotAvoidGoalTime(int goalstate, int number) { floatint_t fi; fi.i = syscall( BOTLIB_AI_AVOID_GOAL_TIME, goalstate, number ); return fi.f; } void trap_BotSetAvoidGoalTime(int goalstate, int number, float avoidtime) { syscall( BOTLIB_AI_SET_AVOID_GOAL_TIME, goalstate, number, PASSFLOAT(avoidtime)); } void trap_BotInitLevelItems(void) { syscall( BOTLIB_AI_INIT_LEVEL_ITEMS ); } void trap_BotUpdateEntityItems(void) { syscall( BOTLIB_AI_UPDATE_ENTITY_ITEMS ); } int trap_BotLoadItemWeights(int goalstate, char *filename) { return syscall( BOTLIB_AI_LOAD_ITEM_WEIGHTS, goalstate, filename ); } void trap_BotFreeItemWeights(int goalstate) { syscall( BOTLIB_AI_FREE_ITEM_WEIGHTS, goalstate ); } void trap_BotInterbreedGoalFuzzyLogic(int parent1, int parent2, int child) { syscall( BOTLIB_AI_INTERBREED_GOAL_FUZZY_LOGIC, parent1, parent2, child ); } void trap_BotSaveGoalFuzzyLogic(int goalstate, char *filename) { syscall( BOTLIB_AI_SAVE_GOAL_FUZZY_LOGIC, goalstate, filename ); } void trap_BotMutateGoalFuzzyLogic(int goalstate, float range) { syscall( BOTLIB_AI_MUTATE_GOAL_FUZZY_LOGIC, goalstate, PASSFLOAT(range) ); } int trap_BotAllocGoalState(int state) { return syscall( BOTLIB_AI_ALLOC_GOAL_STATE, state ); } void trap_BotFreeGoalState(int handle) { syscall( BOTLIB_AI_FREE_GOAL_STATE, handle ); } void trap_BotResetMoveState(int movestate) { syscall( BOTLIB_AI_RESET_MOVE_STATE, movestate ); } void trap_BotAddAvoidSpot(int movestate, vec3_t origin, float radius, int type) { syscall( BOTLIB_AI_ADD_AVOID_SPOT, movestate, origin, PASSFLOAT(radius), type); } void trap_BotMoveToGoal(void /* struct bot_moveresult_s */ *result, int movestate, void /* struct bot_goal_s */ *goal, int travelflags) { syscall( BOTLIB_AI_MOVE_TO_GOAL, result, movestate, goal, travelflags ); } int trap_BotMoveInDirection(int movestate, vec3_t dir, float speed, int type) { return syscall( BOTLIB_AI_MOVE_IN_DIRECTION, movestate, dir, PASSFLOAT(speed), type ); } void trap_BotResetAvoidReach(int movestate) { syscall( BOTLIB_AI_RESET_AVOID_REACH, movestate ); } void trap_BotResetLastAvoidReach(int movestate) { syscall( BOTLIB_AI_RESET_LAST_AVOID_REACH,movestate ); } int trap_BotReachabilityArea(vec3_t origin, int testground) { return syscall( BOTLIB_AI_REACHABILITY_AREA, origin, testground ); } int trap_BotMovementViewTarget(int movestate, void /* struct bot_goal_s */ *goal, int travelflags, float lookahead, vec3_t target) { return syscall( BOTLIB_AI_MOVEMENT_VIEW_TARGET, movestate, goal, travelflags, PASSFLOAT(lookahead), target ); } int trap_BotPredictVisiblePosition(vec3_t origin, int areanum, void /* struct bot_goal_s */ *goal, int travelflags, vec3_t target) { return syscall( BOTLIB_AI_PREDICT_VISIBLE_POSITION, origin, areanum, goal, travelflags, target ); } int trap_BotAllocMoveState(void) { return syscall( BOTLIB_AI_ALLOC_MOVE_STATE ); } void trap_BotFreeMoveState(int handle) { syscall( BOTLIB_AI_FREE_MOVE_STATE, handle ); } void trap_BotInitMoveState(int handle, void /* struct bot_initmove_s */ *initmove) { syscall( BOTLIB_AI_INIT_MOVE_STATE, handle, initmove ); } int trap_BotChooseBestFightWeapon(int weaponstate, int *inventory) { return syscall( BOTLIB_AI_CHOOSE_BEST_FIGHT_WEAPON, weaponstate, inventory ); } void trap_BotGetWeaponInfo(int weaponstate, int weapon, void /* struct weaponinfo_s */ *weaponinfo) { syscall( BOTLIB_AI_GET_WEAPON_INFO, weaponstate, weapon, weaponinfo ); } int trap_BotLoadWeaponWeights(int weaponstate, char *filename) { return syscall( BOTLIB_AI_LOAD_WEAPON_WEIGHTS, weaponstate, filename ); } int trap_BotAllocWeaponState(void) { return syscall( BOTLIB_AI_ALLOC_WEAPON_STATE ); } void trap_BotFreeWeaponState(int weaponstate) { syscall( BOTLIB_AI_FREE_WEAPON_STATE, weaponstate ); } void trap_BotResetWeaponState(int weaponstate) { syscall( BOTLIB_AI_RESET_WEAPON_STATE, weaponstate ); } int trap_GeneticParentsAndChildSelection(int numranks, float *ranks, int *parent1, int *parent2, int *child) { return syscall( BOTLIB_AI_GENETIC_PARENTS_AND_CHILD_SELECTION, numranks, ranks, parent1, parent2, child ); } int trap_PC_LoadSource( const char *filename ) { return syscall( BOTLIB_PC_LOAD_SOURCE, filename ); } int trap_PC_FreeSource( int handle ) { return syscall( BOTLIB_PC_FREE_SOURCE, handle ); } int trap_PC_ReadToken( int handle, pc_token_t *pc_token ) { return syscall( BOTLIB_PC_READ_TOKEN, handle, pc_token ); } int trap_PC_SourceFileAndLine( int handle, char *filename, int *line ) { return syscall( BOTLIB_PC_SOURCE_FILE_AND_LINE, handle, filename, line ); }
1
0.888465
1
0.888465
game-dev
MEDIA
0.251207
game-dev
0.805485
1
0.805485
uvcat7/ArrowVortex
1,648
src/Simfile/Parsing.h
#pragma once #include <Simfile/Simfile.h> namespace Vortex { // ================================================================================================ // Parsing utilities. /// Opens and reads a text file, removing comments, tabs, and carriage returns. bool ParseSimfile(String& out, StringRef path); /// Parses the next tag-value pair in a list of sm-style tags (e.g. #TAG:VAL;). bool ParseNextTag(char*& p, char*& outTag, char*& outVal); /// Parses the next item in a list of values (e.g. "V1,V2,..."). bool ParseNextItem(char*& p, char*& outVal, char seperator = ','); /// Parses the next item in a list of value sets (e.g. "V1=V2=V3,V4=V5=V6,..."). bool ParseNextItem(char*& p, char** outVals, int numVals, char setSeperator = ',', char valSeperator = '='); /// Parses the given string and converts it to bool. bool ParseBool(const char* str, bool& outVal); /// Parses the given string and converts it to double. bool ParseVal(const char* str, double& outVal); /// Parses the given string and converts it to int. bool ParseVal(const char* str, int& outInt); /// Parses the given beat and converts it to a row. bool ParseBeat(const char* str, int& outRow); // ================================================================================================ // Simfile importing and exporting. /// Loads a simfile from the given path and writes the output data to song and charts. bool LoadSimfile(Simfile& simfile, StringRef path); /// Saves the given simfile, to the path specified in the simfile, in the given save format. bool SaveSimfile(const Simfile& simfile, SimFormat format, bool backup); }; // namespace Vortex
1
0.63678
1
0.63678
game-dev
MEDIA
0.236783
game-dev
0.641823
1
0.641823
OpenXRay/xray-16
6,660
src/xrGame/detail_path_manager_inline.h
//////////////////////////////////////////////////////////////////////////// // Module : detailed_path_manager_inline.h // Created : 02.10.2001 // Modified : 12.11.2003 // Author : Dmitriy Iassenev // Description : Detail path manager inline functions //////////////////////////////////////////////////////////////////////////// #pragma once IC bool CDetailPathManager::actual() const { return (m_actuality); } IC void CDetailPathManager::make_inactual() { m_actuality = false; } IC bool CDetailPathManager::failed() const { return (m_failed); } IC bool CDetailPathManager::completed( const Fvector& position, bool bRealCompleted, const u32& travel_point_point_index) const { if (m_path.empty()) return true; if (bRealCompleted || !m_state_patrol_path) { u32 const path_size = m_path.size(); return travel_point_point_index == (path_size - 1); } else { return travel_point_point_index >= m_last_patrol_point; } } IC bool CDetailPathManager::completed(const Fvector& position, bool bRealCompleted) const { return (completed(position, bRealCompleted, m_current_travel_point)); } IC const xr_vector<DetailPathManager::STravelPathPoint>& CDetailPathManager::path() const { return (m_path); } IC xr_vector<DetailPathManager::STravelPathPoint>& CDetailPathManager::path() { return (m_path); } IC const DetailPathManager::STravelPathPoint& CDetailPathManager::curr_travel_point() const { return (m_path[curr_travel_point_index()]); } IC u32 CDetailPathManager::curr_travel_point_index() const { VERIFY2(!m_path.empty() && (m_current_travel_point < m_path.size()), make_string("path[%d], current[%d]", m_path.size(), m_current_travel_point)); return (m_current_travel_point); } IC void CDetailPathManager::set_start_position(const Fvector& start_position) { m_start_position = start_position; } IC void CDetailPathManager::set_start_direction(const Fvector& start_direction) { m_start_direction = start_direction; } IC void CDetailPathManager::set_dest_position(const Fvector& dest_position) { #ifdef DEBUG if (!(!m_restricted_object || m_restricted_object->accessible(dest_position))) { xrDebug::LogStackTrace("error call stack"); } #endif // DEBUG THROW2(!m_restricted_object || m_restricted_object->accessible(dest_position), "Old movement destination is not accessible after changing restrictions!"); bool value = !!m_dest_position.similar(dest_position, .1f); if (!value) m_corrected_dest_position = dest_position; m_actuality = m_actuality && value; m_dest_position = dest_position; } IC void CDetailPathManager::set_dest_direction(const Fvector& dest_direction) { m_actuality = m_actuality && m_dest_direction.similar(dest_direction); m_dest_direction = dest_direction; } IC const Fvector& CDetailPathManager::start_position() const { return (m_start_position); } IC const Fvector& CDetailPathManager::start_direction() const { return (m_start_direction); } IC const Fvector& CDetailPathManager::dest_position() const { return (m_dest_position); } IC const Fvector& CDetailPathManager::dest_direction() const { return (m_dest_direction); } IC void CDetailPathManager::set_path_type(const EDetailPathType path_type) { m_actuality = m_actuality && (path_type == m_path_type); m_path_type = path_type; } IC void CDetailPathManager::adjust_point(const Fvector2& source, float yaw, float magnitude, Fvector2& dest) const { dest.x = -_sin(yaw); dest.y = _cos(yaw); dest.mad(source, dest, magnitude); } IC void CDetailPathManager::set_velocity_mask(const u32 velocity_mask) { m_actuality = m_actuality && (velocity_mask == m_velocity_mask); m_velocity_mask = velocity_mask; } IC const u32 CDetailPathManager::velocity_mask() const { return (m_velocity_mask); } IC void CDetailPathManager::set_desirable_mask(const u32 desirable_mask) { m_actuality = m_actuality && (desirable_mask == m_desirable_mask); m_desirable_mask = desirable_mask; } IC const u32 CDetailPathManager::desirable_mask() const { return (m_desirable_mask); } IC void CDetailPathManager::set_try_min_time(const bool try_min_time) { m_actuality = m_actuality && (try_min_time == m_try_min_time); m_try_min_time = try_min_time; } IC const bool CDetailPathManager::try_min_time() const { return (m_try_min_time); } IC void CDetailPathManager::set_use_dest_orientation(const bool use_dest_orientation) { m_actuality = m_actuality && (use_dest_orientation == m_use_dest_orientation); m_use_dest_orientation = use_dest_orientation; } IC const bool CDetailPathManager::use_dest_orientation() const { return (m_use_dest_orientation); } IC bool CDetailPathManager::check_mask(u32 mask, u32 test) const { return ((mask & test) == test); } IC void CDetailPathManager::set_state_patrol_path(const bool state_patrol_path) { m_actuality = m_actuality && (state_patrol_path == m_state_patrol_path); m_state_patrol_path = state_patrol_path; } IC bool CDetailPathManager::state_patrol_path() const { return (m_state_patrol_path); } IC const u32 CDetailPathManager::time_path_built() const { return (m_time_path_built); } IC const CDetailPathManager::STravelParams& CDetailPathManager::velocity(const u32& velocity_id) const { VELOCITIES::const_iterator I = m_movement_params.find(velocity_id); VERIFY(m_movement_params.end() != I); return ((*I).second); } IC void CDetailPathManager::add_velocity(const u32& velocity_id, const STravelParams& params) { m_movement_params.emplace(velocity_id, params); } IC void CDetailPathManager::extrapolate_length(float extrapolate_length) { m_actuality = m_actuality && (fsimilar(m_extrapolate_length, extrapolate_length)); m_extrapolate_length = extrapolate_length; } IC float CDetailPathManager::extrapolate_length() const { return (m_extrapolate_length); } IC const CDetailPathManager::VELOCITIES& CDetailPathManager::velocities() const { return (m_movement_params); } IC const float& CDetailPathManager::distance_to_target() { if (m_distance_to_target_actual) return (m_distance_to_target); update_distance_to_target(); return (m_distance_to_target); } IC const u32& CDetailPathManager::dest_vertex_id() const { return (m_dest_vertex_id); } IC const u32& CDetailPathManager::last_patrol_point() const { return (m_last_patrol_point); } IC void CDetailPathManager::last_patrol_point(const u32& last_patrol_point) { m_last_patrol_point = last_patrol_point; } #ifdef DEBUG IC xr_vector<CDetailPathManager::STravelPoint>& CDetailPathManager::key_points() { return (m_key_points); } #endif // DEBUG
1
0.911669
1
0.911669
game-dev
MEDIA
0.364966
game-dev
0.657171
1
0.657171
ill-inc/biomes-game
7,576
src/shared/npc/behavior/swim.ts
import type { ReadonlyEntity } from "@/shared/ecs/gen/entities"; import { CollisionHelper } from "@/shared/game/collision"; import { add, centerAndSideLengthToAABB, normalizev, scale, zeroVector, } from "@/shared/math/linear"; import type { AABB, Vec3 } from "@/shared/math/types"; import { awayFromBlocksAndBounds, awayFromPlayer, getDirectionTowardsAABBIntersection, getRandomDirection, getVolumeTakenByBox, towardsCurrentDirection, } from "@/shared/npc/behavior/shared_actions"; import type { Environment } from "@/shared/npc/environment"; import type { SimulatedNpc } from "@/shared/npc/simulated"; import { toForce } from "@/shared/physics/forces"; import type { Force } from "@/shared/physics/types"; import { ok } from "assert"; export function swimTick( env: Environment, npc: SimulatedNpc ): { force: Force; } { ok(npc.type.behavior.swim); const { towardsCurrentDirectionStrength, awayFromBlocksAndBoundsRadius, awayFromBlocksAndBoundsStrength, stayInWaterStrength, randomForceProbability, randomForceStrength, } = npc.type.behavior.swim; let forceDirection = zeroVector; if (npc.type.behavior.swim.isShyOfPlayers) { // Go away from players. const { awayFromPlayerRadius, awayFromPlayerStrength } = npc.type.behavior.swim.isShyOfPlayers; forceDirection = add( forceDirection, awayFromPlayer({ env, npc, radius: awayFromPlayerRadius, strength: awayFromPlayerStrength, }) ); } // Go towards current direction but only in xz-plane. forceDirection = add( forceDirection, towardsCurrentDirection({ npc, strength: towardsCurrentDirectionStrength, }) ); if (npc.type.behavior.swim.shouldFlock) { // Go towards other NPCs and in the same direction as other NPCs. const { attractOtherEntitiesStrength, followOtherEntitiesStrength, towardsOtherEntitiesRadius, } = npc.type.behavior.swim.shouldFlock; forceDirection = add( forceDirection, towardsOtherEntitiesDirection({ env, npc, attractOtherEntitiesStrength, followOtherEntitiesStrength, towardsOtherEntitiesRadius, }) ); } // Make large npcs move slower. const npcSize = npc.size; const npcAverageLength = (npcSize[0] + npcSize[1] + npcSize[2]) / 3; const defaultAverageLength = (npc.type.boxSize[0] + npc.type.boxSize[1] + npc.type.boxSize[2]) / 3; if (npcAverageLength > defaultAverageLength) { forceDirection = scale( defaultAverageLength / npcAverageLength, forceDirection ); } // Go away from blocks and world bounds. forceDirection = add( forceDirection, awayFromBlocksAndBounds({ env, npc, radius: awayFromBlocksAndBoundsRadius, strength: awayFromBlocksAndBoundsStrength, }) ); // Once in a while, have a random force. if (Math.random() < randomForceProbability) { forceDirection = add( forceDirection, getRandomDirection({ length: randomForceStrength }) ); } // Stay in the water. const depth = getDepthInWater({ env, npc, maxDepthToCheck: 1 }); // The fish cannot swim when it is out of the water so zero out the force. if (depth <= 0) { forceDirection = zeroVector; } forceDirection = add( forceDirection, stayInWater({ depth, stayInWaterStrength }) ); return { force: toForce(forceDirection), }; } // Determines how deep in water the entity is. // Only checks up to the `maxDepthToCheck` so if the entity is deeper // than `maxDepthToCheck`, it will just return `maxDepthToCheck`. function getDepthInWater({ npc, env, maxDepthToCheck, }: { npc: SimulatedNpc; env: Environment; maxDepthToCheck: number; }): number { // Create a box column above the entity and see how much of it is filled with water. const anchor = npc.position; const columnWidth = 0.25; const collisionBox: AABB = [ [anchor[0] - columnWidth / 2, anchor[1], anchor[2] - columnWidth / 2], [ anchor[0] + columnWidth / 2, anchor[1] + maxDepthToCheck, anchor[2] + columnWidth / 2, ], ]; const volumeInColumn = getVolumeTakenByBox({ aabb: collisionBox, boxesIndex: (id) => env.resources.get("/water/boxes", id), }); return volumeInColumn / (columnWidth * columnWidth); } function stayInWater({ depth, stayInWaterStrength, }: { depth: number; stayInWaterStrength: number; }): Vec3 { if (depth <= 0) { return [0, -2 * stayInWaterStrength, 0]; } if (depth <= 0.5) { return [0, -1 * stayInWaterStrength, 0]; } return zeroVector; } function towardsOtherEntitiesDirection({ env, npc, attractOtherEntitiesStrength, followOtherEntitiesStrength, towardsOtherEntitiesRadius, }: { env: Environment; npc: SimulatedNpc; attractOtherEntitiesStrength: number; followOtherEntitiesStrength: number; towardsOtherEntitiesRadius: number; }): Vec3 { const boxSize = towardsOtherEntitiesRadius * 2; const collisionBox = centerAndSideLengthToAABB(npc.position, boxSize); let entityAttraction = zeroVector; let entityFollow = zeroVector; CollisionHelper.intersectEntities( env.table, collisionBox, (hit: AABB, entity) => { const isEntitySameType = entity?.npc_metadata?.type_id === npc.metadata.type_id; if (!entity || entity.id === npc.id || !isEntitySameType) { return; } // Go towards other fish. entityAttraction = add( entityAttraction, getEntityAttractionDirection({ hit, collisionBox, npc, attractOtherEntitiesStrength, }) ); // Go in the same direction as other close by fish. entityFollow = add( entityFollow, getEntityFollowDirection({ hit, collisionBox, npc, entity, followOtherEntitiesStrength, }) ); } ); return add(entityAttraction, scale(0.5, entityFollow)); } function getEntityAttractionDirection({ hit, collisionBox, npc, attractOtherEntitiesStrength, }: { hit: AABB; collisionBox: AABB; npc: SimulatedNpc; attractOtherEntitiesStrength: number; }): Vec3 { const directionAndLength = getDirectionTowardsAABBIntersection({ point: npc.position, box1: hit, box2: collisionBox, }); if (!directionAndLength) { return zeroVector; } const { direction, length } = directionAndLength; // Sweet spot is to have fish 2.5 voxels apart. When further than // 2.5 voxels, have an attracting force and when closer than 2.5 voxels // have a repelling force. const optimalDistanceApart = 2.5; const yIntercept = -1 * attractOtherEntitiesStrength * optimalDistanceApart; return scale( length * attractOtherEntitiesStrength + yIntercept, normalizev(direction) ); } function getEntityFollowDirection({ hit, collisionBox, npc, entity, followOtherEntitiesStrength, }: { hit: AABB; collisionBox: AABB; npc: SimulatedNpc; entity: ReadonlyEntity; followOtherEntitiesStrength: number; }): Vec3 { const otherVelocity = entity.rigid_body?.velocity; const directionAndLength = getDirectionTowardsAABBIntersection({ point: npc.position, box1: hit, box2: collisionBox, }); if (!directionAndLength || !otherVelocity) { return zeroVector; } const { length } = directionAndLength; return scale( (1 / Math.max(length, 0.01)) * followOtherEntitiesStrength, normalizev(otherVelocity) ); }
1
0.854978
1
0.854978
game-dev
MEDIA
0.97058
game-dev
0.981263
1
0.981263
MKhayle/XIVComboExpanded
11,839
XIVComboExpanded/Combos/SMN.cs
using Dalamud.Game.ClientState.JobGauge.Types; namespace XIVComboExpandedPlugin.Combos; internal static class SMN { public const byte ClassID = 26; public const byte JobID = 27; public const uint Ruin = 163, Ruin2 = 172, Ruin3 = 3579, Ruin4 = 7426, Fester = 181, Painflare = 3578, DreadwyrmTrance = 3581, Deathflare = 3582, SummonBahamut = 7427, EnkindleBahamut = 7429, Physick = 16230, EnergySyphon = 16510, Outburst = 16511, EnkindlePhoenix = 16516, EnergyDrain = 16508, SummonCarbuncle = 25798, RadiantAegis = 25799, Aethercharge = 25800, SearingLight = 25801, SummonRuby = 25802, SummonTopaz = 25803, SummonEmerald = 25804, SummonIfrit = 25805, SummonTitan = 25806, SummonGaruda = 25807, AstralFlow = 25822, TriDisaster = 25826, Rekindle = 25830, SummonPhoenix = 25831, CrimsonCyclone = 25835, MountainBuster = 25836, Slipstream = 25837, SummonIfrit2 = 25838, SummonTitan2 = 25839, SummonGaruda2 = 25840, CrimsonStrike = 25885, Gemshine = 25883, PreciousBrilliance = 25884, Necrosis = 36990, SearingFlash = 36991, SummonSolarBahamut = 36992, Sunflare = 36996, LuxSolaris = 36997, EnkindleSolarBahamut = 36998; public static class Buffs { public const ushort Aetherflow = 304, FurtherRuin = 2701, SearingLight = 2703, IfritsFavor = 2724, GarudasFavor = 2725, TitansFavor = 2853, RubysGlimmer = 3873, LuxSolarisReady = 3874, CrimsonStrikeReady = 4403; } public static class Debuffs { public const ushort Placeholder = 0; } public static class Levels { public const byte SummonCarbuncle = 2, RadiantAegis = 2, Gemshine = 6, EnergyDrain = 10, Fester = 10, PreciousBrilliance = 26, Painflare = 40, EnergySyphon = 52, Ruin3 = 54, Ruin4 = 62, SearingLight = 66, EnkindleBahamut = 70, Rekindle = 80, ElementalMastery = 86, SummonPhoenix = 80, Necrosis = 92, SummonSolarBahamut = 100, LuxSolaris = 100; } } internal class SummonerFester : CustomCombo { protected internal override CustomComboPreset Preset { get; } = CustomComboPreset.SummonerEDFesterFeature; protected override uint Invoke(uint actionID, uint lastComboMove, float comboTime, byte level) { if (actionID == SMN.Fester || actionID == SMN.Necrosis) { var gauge = GetJobGauge<SMNGauge>(); if (level >= SMN.Levels.EnergyDrain && !gauge.HasAetherflowStacks) return SMN.EnergyDrain; } return actionID; } } internal class SummonerPainflare : CustomCombo { protected internal override CustomComboPreset Preset { get; } = CustomComboPreset.SummonerESPainflareFeature; protected override uint Invoke(uint actionID, uint lastComboMove, float comboTime, byte level) { if (actionID == SMN.Painflare) { var gauge = GetJobGauge<SMNGauge>(); if (level >= SMN.Levels.EnergySyphon && !gauge.HasAetherflowStacks) return SMN.EnergySyphon; if (level >= SMN.Levels.EnergyDrain && !gauge.HasAetherflowStacks) return SMN.EnergyDrain; if (level < SMN.Levels.Painflare) return SMN.Fester; } return actionID; } } internal class SummonerRuin : CustomCombo { protected internal override CustomComboPreset Preset { get; } = CustomComboPreset.SmnAny; protected override uint Invoke(uint actionID, uint lastComboMove, float comboTime, byte level) { if (actionID == SMN.Ruin || actionID == SMN.Ruin2 || actionID == SMN.Ruin3) { var gauge = GetJobGauge<SMNGauge>(); if (IsEnabled(CustomComboPreset.SummonerRuinTitansFavorFeature)) { if (level >= SMN.Levels.ElementalMastery && HasEffect(SMN.Buffs.TitansFavor)) return SMN.MountainBuster; } if (IsEnabled(CustomComboPreset.SummonerRuinFeature)) { if (level >= SMN.Levels.Gemshine) { if (gauge.Attunement > 0) return OriginalHook(SMN.Gemshine); } } if (IsEnabled(CustomComboPreset.SummonerFurtherRuinFeature)) { if (level >= SMN.Levels.Ruin4 && gauge.SummonTimerRemaining == 0 && gauge.AttunementTimerRemaining == 0 && HasEffect(SMN.Buffs.FurtherRuin)) return SMN.Ruin4; } } return actionID; } } internal class SummonerOutburstTriDisaster : CustomCombo { protected internal override CustomComboPreset Preset { get; } = CustomComboPreset.SmnAny; protected override uint Invoke(uint actionID, uint lastComboMove, float comboTime, byte level) { if (actionID == SMN.Outburst || actionID == SMN.TriDisaster) { var gauge = GetJobGauge<SMNGauge>(); if (IsEnabled(CustomComboPreset.SummonerOutburstTitansFavorFeature)) { if (level >= SMN.Levels.ElementalMastery && HasEffect(SMN.Buffs.TitansFavor)) return SMN.MountainBuster; } if (IsEnabled(CustomComboPreset.SummonerOutburstFeature)) { if (level >= SMN.Levels.PreciousBrilliance) { if (gauge.Attunement > 0) return OriginalHook(SMN.PreciousBrilliance); } } if (IsEnabled(CustomComboPreset.SummonerFurtherOutburstFeature)) { if (level >= SMN.Levels.Ruin4 && gauge.SummonTimerRemaining == 0 && gauge.AttunementTimerRemaining == 0 && HasEffect(SMN.Buffs.FurtherRuin)) return SMN.Ruin4; } } return actionID; } } internal class SummonerGemshinePreciousBrilliance : CustomCombo { protected internal override CustomComboPreset Preset { get; } = CustomComboPreset.SmnAny; protected override uint Invoke(uint actionID, uint lastComboMove, float comboTime, byte level) { if (actionID == SMN.Gemshine || actionID == SMN.PreciousBrilliance) { var gauge = GetJobGauge<SMNGauge>(); if (IsEnabled(CustomComboPreset.SummonerShinyTitansFavorFeature)) { if (level >= SMN.Levels.ElementalMastery && HasEffect(SMN.Buffs.TitansFavor)) return SMN.MountainBuster; } if (IsEnabled(CustomComboPreset.SummonerShinyEnkindleFeature)) { if (level >= SMN.Levels.EnkindleBahamut && gauge.SummonTimerRemaining > 0 && gauge.AttunementTimerRemaining == 0) // Rekindle return OriginalHook(SMN.EnkindleBahamut); } if (IsEnabled(CustomComboPreset.SummonerFurtherShinyFeature)) { if (level >= SMN.Levels.Ruin4 && gauge.SummonTimerRemaining == 0 && gauge.AttunementTimerRemaining == 0 && HasEffect(SMN.Buffs.FurtherRuin)) return SMN.Ruin4; } } return actionID; } } internal class SummonerDemiFeature : CustomCombo { protected internal override CustomComboPreset Preset { get; } = CustomComboPreset.SmnAny; protected override uint Invoke(uint actionID, uint lastComboMove, float comboTime, byte level) { if (actionID == SMN.Aethercharge || actionID == SMN.DreadwyrmTrance || actionID == SMN.SummonBahamut) { if (IsEnabled(CustomComboPreset.SummonerDemiCarbuncleFeature) && !HasPetPresent()) return SMN.SummonCarbuncle; var gauge = GetJobGauge<SMNGauge>(); if (IsEnabled(CustomComboPreset.SummonerSearingDemiFlashFeature)) { if (level >= SMN.Levels.SearingLight && !CanUseAction(SMN.SummonBahamut) && !CanUseAction(SMN.SummonPhoenix) && !CanUseAction(SMN.SummonSolarBahamut) && InCombat()) if (IsCooldownUsable(SMN.SearingLight)) return SMN.SearingLight; else if (HasEffect(SMN.Buffs.RubysGlimmer)) return SMN.SearingFlash; } if (IsEnabled(CustomComboPreset.SummonerDemiSearingLightFeature)) { if (level >= SMN.Levels.SearingLight && CanUseAction(SMN.SummonBahamut) && CanUseAction(SMN.SummonPhoenix) && CanUseAction(SMN.SummonSolarBahamut) && InCombat() && IsCooldownUsable(SMN.SearingLight)) return SMN.SearingLight; } if (IsEnabled(CustomComboPreset.SummonerDemiEnkindleFeature)) { if (level >= SMN.Levels.EnkindleBahamut && gauge.Attunement == 0 && gauge.SummonTimerRemaining > 0) // Rekindle return OriginalHook(SMN.EnkindleBahamut); } } return actionID; } } internal class SummonerRadiantCarbuncleFeature : CustomCombo { protected internal override CustomComboPreset Preset { get; } = CustomComboPreset.SmnAny; protected override uint Invoke(uint actionID, uint lastComboMove, float comboTime, byte level) { if (actionID == SMN.RadiantAegis) { if (IsEnabled(CustomComboPreset.SummonerRadiantLuxSolarisFeature)) { if (HasEffect(SMN.Buffs.LuxSolarisReady)) return SMN.LuxSolaris; } var gauge = GetJobGauge<SMNGauge>(); if (level >= SMN.Levels.SummonCarbuncle && !HasPetPresent() && IsEnabled(CustomComboPreset.SummonerRadiantCarbuncleFeature)) return SMN.SummonCarbuncle; } return actionID; } } internal class SummonerLuxSolarisFeature : CustomCombo { protected internal override CustomComboPreset Preset { get; } = CustomComboPreset.SummonerSummonLuxSolarisFeature; protected override uint Invoke(uint actionID, uint lastComboMove, float comboTime, byte level) { if (actionID == SMN.SummonBahamut) { if (HasEffect(SMN.Buffs.LuxSolarisReady)) return SMN.LuxSolaris; } return actionID; } } internal class SummonerPrimalSummons : CustomCombo { protected internal override CustomComboPreset Preset { get; } = CustomComboPreset.SummonerPrimalFavorFeature; protected override uint Invoke(uint actionID, uint lastComboMove, float comboTime, byte level) { if (actionID == SMN.SummonRuby || actionID == SMN.SummonIfrit || actionID == SMN.SummonIfrit2) { if (HasEffect(SMN.Buffs.IfritsFavor) || HasEffect(SMN.Buffs.CrimsonStrikeReady)) return OriginalHook(SMN.AstralFlow); } if (actionID == SMN.SummonEmerald || actionID == SMN.SummonGaruda || actionID == SMN.SummonGaruda2) { if (HasEffect(SMN.Buffs.GarudasFavor)) return OriginalHook(SMN.AstralFlow); } if (actionID == SMN.SummonTopaz || actionID == SMN.SummonTitan || actionID == SMN.SummonTitan2) { if (HasEffect(SMN.Buffs.TitansFavor)) return OriginalHook(SMN.AstralFlow); } return actionID; } }
1
0.886089
1
0.886089
game-dev
MEDIA
0.9505
game-dev
0.985576
1
0.985576
LogicalError/realtime-CSG-for-unity
9,524
Plugins/Editor/Scripts/View/Units.cs
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using UnityEngine; namespace RealtimeCSG { public enum DistanceUnit { Meters, Centimeters, Millimeters, Feet, Inches } public enum PixelUnit { Relative, Pixels } public static class Units { static string[] pixelUnitStrings = { string.Empty, "pixels" }; static GUIContent[] pixelUnitGUIContent = { new GUIContent(pixelUnitStrings[0]), new GUIContent(pixelUnitStrings[1]) }; public static string GetUnitString (PixelUnit unit) { return pixelUnitStrings[(int)unit]; } public static GUIContent GetUnitGUIContent (PixelUnit unit) { return pixelUnitGUIContent[(int)unit]; } static string[] distanceUnitStrings = { "m", "cm", "mm", "ft", "\"" }; static GUIContent[] distanceUnitGUIContent = { new GUIContent(distanceUnitStrings[0]), new GUIContent(distanceUnitStrings[1]), new GUIContent(distanceUnitStrings[2]), new GUIContent(distanceUnitStrings[3]), new GUIContent(distanceUnitStrings[4]) }; public static string GetUnitString (DistanceUnit unit) { return distanceUnitStrings[(int)unit]; } public static GUIContent GetUnitGUIContent (DistanceUnit unit) { return distanceUnitGUIContent[(int)unit]; } public static DistanceUnit CycleToNextUnit (DistanceUnit unit) { if (unit < DistanceUnit.Meters) return DistanceUnit.Meters; return (DistanceUnit)((int)(unit + 1) % (((int)DistanceUnit.Inches) + 1)); } public static string ToPixelsString (PixelUnit unit, Vector2 value) { string unitString = GetUnitString(unit); if (!String.IsNullOrEmpty(unitString)) unitString = " " + unitString; return string.Format(CultureInfo.InvariantCulture, "x:{0:F}{2}\ny:{1:F}{2}", UnityToPixelsUnit(value.x), UnityToPixelsUnit(value.y), unitString); } public static string ToPixelsString (Vector2 value) { return ToPixelsString(RealtimeCSG.CSGSettings.PixelUnit, value); } public static string ToRoundedPixelsString(PixelUnit unit, Vector2 value) { string unitString = GetUnitString(unit); if (!String.IsNullOrEmpty(unitString)) unitString = " " + unitString; float x = (long)Math.Round((double)value.x * 16384) / 16384.0f; float y = (long)Math.Round((double)value.y * 16384) / 16384.0f; return string.Format(CultureInfo.InvariantCulture, "u:{0:F}{2}\nv:{1:F}{2}", UnityToPixelsUnit(x), UnityToPixelsUnit(y), unitString); } public static string ToRoundedPixelsString(Vector2 value) { return ToRoundedPixelsString(RealtimeCSG.CSGSettings.PixelUnit, value); } public static double UnityToPixelsUnit (PixelUnit unit, float value) { switch (unit) { case PixelUnit.Relative: return (double)value; case PixelUnit.Pixels: return (double)(value * 4096.0); } Debug.LogWarning("Tried to convert value to unknown pixel unit"); return (double)value; } public static double UnityToPixelsUnit (float value) { return UnityToPixelsUnit(RealtimeCSG.CSGSettings.PixelUnit, value); } public static float UnityFromPixelsUnit (PixelUnit unit, double value) { switch (unit) { case PixelUnit.Relative: return (float)value; case PixelUnit.Pixels: return (float)(value / 4096.0); } Debug.LogWarning("Tried to convert value to unknown pixel unit"); return (float)value; } public static float UnityFromPixelsUnit (double value) { return UnityFromPixelsUnit(RealtimeCSG.CSGSettings.PixelUnit, value); } public static string ToDistanceString (DistanceUnit unit, float value) { return string.Format(CultureInfo.InvariantCulture, "{0} {1}", UnityToDistanceUnit(unit, value), GetUnitString(unit)); } public static string ToDistanceString (float value) { return ToDistanceString(RealtimeCSG.CSGSettings.DistanceUnit, value); } public static string ToDistanceString (DistanceUnit unit, Vector3 value, bool lockX = false, bool lockY = false, bool lockZ = false) { var builder = new StringBuilder(); var unit_string = GetUnitString(unit); if (lockX) builder.Append("x: --\n"); else builder.AppendFormat(CultureInfo.InvariantCulture, "x: {0} {1}\n", UnityToDistanceUnit(unit, value.x), unit_string); if (lockY) builder.Append("y: --\n"); else builder.AppendFormat(CultureInfo.InvariantCulture, "y: {0} {1}\n", UnityToDistanceUnit(unit, value.y), unit_string); if (lockZ) builder.Append("z: --"); else builder.AppendFormat(CultureInfo.InvariantCulture, "z: {0} {1}", UnityToDistanceUnit(unit, value.z), unit_string); return builder.ToString(); } public static string ToDistanceString (Vector3 value, bool lockX = false, bool lockY = false, bool lockZ = false) { return ToDistanceString(RealtimeCSG.CSGSettings.DistanceUnit, value, lockX, lockY, lockZ); } public static string ToRoundedDistanceString (DistanceUnit unit, float value) { if (float.IsNaN(value)) return "??"; return string.Format(CultureInfo.InvariantCulture, "{0:F} {1}", UnityToDistanceUnit(unit, value), GetUnitString(unit)); } public static string ToRoundedDistanceString (float value) { return ToRoundedDistanceString(RealtimeCSG.CSGSettings.DistanceUnit, value); } public static string ToRoundedDistanceString (DistanceUnit unit, Vector3 value, bool lockX = false, bool lockY = false, bool lockZ = false) { var builder = new StringBuilder(); var unit_string = GetUnitString(unit); if (lockX) builder.Append("x: --\n"); else builder.AppendFormat(CultureInfo.InvariantCulture, "x: {0:F} {1}\n", UnityToDistanceUnit(unit, value.x), unit_string); if (lockY) builder.Append("y: --\n"); else builder.AppendFormat(CultureInfo.InvariantCulture, "y: {0:F} {1}\n", UnityToDistanceUnit(unit, value.y), unit_string); if (lockZ) builder.Append("z: --"); else builder.AppendFormat(CultureInfo.InvariantCulture, "z: {0:F} {1}", UnityToDistanceUnit(unit, value.z), unit_string); return builder.ToString(); } public static string ToRoundedDistanceString (Vector3 value, bool lockX = false, bool lockY = false, bool lockZ = false) { return ToRoundedDistanceString(RealtimeCSG.CSGSettings.DistanceUnit, value, lockX, lockY, lockZ); } public static string ToRoundedScaleString (Vector3 value, bool lockX = false, bool lockY = false, bool lockZ = false) { var builder = new StringBuilder(); if (lockX) builder.Append("x: --\n"); else builder.AppendFormat(CultureInfo.InvariantCulture, "x: {0:F} %\n", value.x * 100); if (lockY) builder.Append("y: --\n"); else builder.AppendFormat(CultureInfo.InvariantCulture, "y: {0:F} %\n", value.y * 100); if (lockZ) builder.Append("z: --"); else builder.AppendFormat(CultureInfo.InvariantCulture, "z: {0:F} %", value.z * 100); return builder.ToString(); } public static string ToAngleString (float value) { return string.Format(CultureInfo.InvariantCulture, "{0,4}°", value);//(value % 360)); } public static string ToRoundedAngleString(float value) { return string.Format(CultureInfo.InvariantCulture, "{0:F}°", value);// (value % 360)); } const double meter_to_centimeter = 100.0; const double meter_to_millimeter = 1000.0; const double meter_to_inches = 39.37007874; const double meter_to_feet = 3.28084; const double emperial_rounding = 10000000; public static double UnityToDistanceUnit (DistanceUnit unit, float value) { if (float.IsNaN(value) || float.IsInfinity(value)) return (double)value; double result = (double)value; switch (unit) { // values are in meters by default in unity case DistanceUnit.Meters: break; case DistanceUnit.Centimeters: result *= meter_to_centimeter; break; case DistanceUnit.Millimeters: result *= meter_to_millimeter; break; case DistanceUnit.Inches: result *= meter_to_inches; result = Math.Round(result * emperial_rounding) / emperial_rounding; break; case DistanceUnit.Feet: result *= meter_to_feet; result = Math.Round(result * emperial_rounding) / emperial_rounding; break; default: { Debug.LogWarning("Tried to convert value to unknown distance unit"); return value; } } return (double)result; } public static double UnityToDistanceUnit (float value) { return UnityToDistanceUnit(RealtimeCSG.CSGSettings.DistanceUnit, value); } public static float DistanceUnitToUnity (DistanceUnit unit, double value) { if (double.IsNaN(value) || double.IsInfinity(value)) return (float)value; double result = (double)value; switch (unit) { // values are in meters by default in unity case DistanceUnit.Meters: break; case DistanceUnit.Centimeters: result /= meter_to_centimeter; break; case DistanceUnit.Millimeters: result /= meter_to_millimeter; break; case DistanceUnit.Inches: result /= meter_to_inches; result = Math.Round(result * emperial_rounding) / emperial_rounding; break; case DistanceUnit.Feet: result /= meter_to_feet; result = Math.Round(result * emperial_rounding) / emperial_rounding; break; default: { Debug.LogWarning("Tried to convert value from unknown distance unit"); return (float)value; } } return (float)result; } public static float DistanceUnitToUnity (double value) { return DistanceUnitToUnity(RealtimeCSG.CSGSettings.DistanceUnit, value); } } }
1
0.631084
1
0.631084
game-dev
MEDIA
0.329531
game-dev
0.650532
1
0.650532
FirstGearGames/FishNet
2,302
Assets/FishNet/Runtime/Generated/Component/TickSmoothing/Editor/NetworkTickSmootherEditor.cs
#if UNITY_EDITOR using UnityEditor; using UnityEngine; namespace FishNet.Component.Transforming.Beta { [CustomEditor(typeof(NetworkTickSmoother), true)] [CanEditMultipleObjects] public class NetworkTickSmootherEditor : Editor { private SerializedProperty _initializationSettings; private SerializedProperty _controllerMovementSettings; private SerializedProperty _spectatorMovementSettings; private bool _showControllerSmoothingSettings; private bool _showSpectatorSmoothingSettings; protected virtual void OnEnable() { _initializationSettings = serializedObject.FindProperty(nameof(_initializationSettings)); _controllerMovementSettings = serializedObject.FindProperty(nameof(_controllerMovementSettings)); _spectatorMovementSettings = serializedObject.FindProperty(nameof(_spectatorMovementSettings)); } public override void OnInspectorGUI() { serializedObject.Update(); GUI.enabled = false; EditorGUILayout.ObjectField("Script:", MonoScript.FromMonoBehaviour((NetworkTickSmoother)target), typeof(NetworkTickSmoother), false); GUI.enabled = true; // EditorGUILayout.LabelField("Initialization Settings", EditorStyles.boldLabel); EditorGUILayout.PropertyField(_initializationSettings); _showControllerSmoothingSettings = EditorGUILayout.Foldout(_showControllerSmoothingSettings, new GUIContent("Controller Smoothing", "Smoothing applied when object controller. This would be the owner, or if there is no owner and are also server.")); if (_showControllerSmoothingSettings) EditorGUILayout.PropertyField(_controllerMovementSettings); _showSpectatorSmoothingSettings = EditorGUILayout.Foldout(_showSpectatorSmoothingSettings, new GUIContent("Spectator Smoothing", "Smoothing applied when object not the owner. This is when server and there is an owner, or when client and not the owner.")); if (_showSpectatorSmoothingSettings) EditorGUILayout.PropertyField(_spectatorMovementSettings); // EditorGUI.indentLevel--; serializedObject.ApplyModifiedProperties(); } } } #endif
1
0.712817
1
0.712817
game-dev
MEDIA
0.967514
game-dev
0.657288
1
0.657288
koordinator-sh/koordinator
25,725
pkg/slo-controller/noderesource/plugins/util/util.go
/* Copyright 2022 The Koordinator Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package util import ( "fmt" "math" "sort" "strconv" topologyv1alpha1 "github.com/k8stopologyawareschedwg/noderesourcetopology-api/pkg/apis/topology/v1alpha1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/util/sets" quotav1 "k8s.io/apiserver/pkg/quota/v1" "k8s.io/klog/v2" "k8s.io/utils/ptr" "github.com/koordinator-sh/koordinator/apis/configuration" "github.com/koordinator-sh/koordinator/apis/extension" slov1alpha1 "github.com/koordinator-sh/koordinator/apis/slo/v1alpha1" "github.com/koordinator-sh/koordinator/pkg/slo-controller/noderesource/framework" "github.com/koordinator-sh/koordinator/pkg/util" "github.com/koordinator-sh/koordinator/pkg/util/sloconfig" ) var ( updateNRTResourceSet = sets.NewString(string(extension.BatchCPU), string(extension.BatchMemory)) ) const ( MidCPUThreshold = "midCPUThreshold" MidMemoryThreshold = "midMemoryThreshold" MidUnallocatedPercent = "midUnallocatedPercent" BatchCPUThreshold = "batchCPUThreshold" BatchMemoryThreshold = "batchMemoryThreshold" ) func CalculateBatchResourceByPolicy(strategy *configuration.ColocationStrategy, nodeCapacity, nodeSafetyMargin, nodeReserved, systemUsed, podHPReq, podHPUsed, podHPMaxUsedReq corev1.ResourceList) (corev1.ResourceList, string, string) { // Node(Batch).Alloc[usage] := Node.Total - Node.SafetyMargin - System.Used - sum(Pod(Prod/Mid).Used) // System.Used = max(Node.Used - Pod(All).Used, Node.Anno.Reserved, Node.Kubelet.Reserved) systemUsed = quotav1.Max(systemUsed, nodeReserved) batchAllocatableByUsage := quotav1.Max(quotav1.Subtract(quotav1.Subtract(quotav1.Subtract( nodeCapacity, nodeSafetyMargin), systemUsed), podHPUsed), util.NewZeroResourceList()) // Node(Batch).Alloc[request] := Node.Total - Node.SafetyMargin - System.Reserved - sum(Pod(Prod/Mid).Request) // System.Reserved = max(Node.Anno.Reserved, Node.Kubelet.Reserved) batchAllocatableByRequest := quotav1.Max(quotav1.Subtract(quotav1.Subtract(quotav1.Subtract( nodeCapacity, nodeSafetyMargin), nodeReserved), podHPReq), util.NewZeroResourceList()) // Node(Batch).Alloc[maxUsageRequest] := Node.Total - Node.SafetyMargin - System.Used - sum(max(Pod(Prod/Mid).Request, Pod(Prod/Mid).Used)) batchAllocatableByMaxUsageRequest := quotav1.Max(quotav1.Subtract(quotav1.Subtract(quotav1.Subtract( nodeCapacity, nodeSafetyMargin), systemUsed), podHPMaxUsedReq), util.NewZeroResourceList()) batchAllocatable := batchAllocatableByUsage var cpuMsg string // while batchCPU/MEMThresholdPercent != nil, use BatchXXXThresholdPercent of nodeCapacity to limit batchAllocatable // Node(Batch).Alloc = min(nodeCapacity * BatchXXXThresholdPercent, Node(Batch).Alloc[Policy]) // while batchCPU/MEMThresholdPercent == nil // Node(Batch).Alloc = Node(Batch).Alloc[Policy] var batchCPUThresholdPercent *float64 if strategy != nil && strategy.BatchCPUThresholdPercent != nil { batchCPUThresholdPercent = ptr.To(float64(*strategy.BatchCPUThresholdPercent) / 100) } // batch cpu support policy "usage" and "maxUsageRequest" if strategy != nil && strategy.CPUCalculatePolicy != nil && *strategy.CPUCalculatePolicy == configuration.CalculateByPodMaxUsageRequest { if batchCPUThresholdPercent == nil { batchAllocatable[corev1.ResourceCPU] = *batchAllocatableByMaxUsageRequest.Cpu() cpuMsg = fmt.Sprintf("batchAllocatable[CPU(Milli-Core)]:%v = nodeCapacity:%v - nodeSafetyMargin:%v - systemUsageOrNodeReserved:%v - podHPMaxUsedRequest:%v", batchAllocatable.Cpu().MilliValue(), nodeCapacity.Cpu().MilliValue(), nodeSafetyMargin.Cpu().MilliValue(), systemUsed.Cpu().MilliValue(), podHPMaxUsedReq.Cpu().MilliValue()) } else { batchAllocatable[corev1.ResourceCPU] = util.MinQuant(*batchAllocatableByMaxUsageRequest.Cpu(), util.MultiplyMilliQuant(*nodeCapacity.Cpu(), *batchCPUThresholdPercent)) cpuMsg = fmt.Sprintf("batchAllocatable[CPU(Milli-Core)]:%v = min(nodeCapacity:%v * thresholdRatio:%v, nodeCapacity:%v - nodeSafetyMargin:%v - systemUsageOrNodeReserved:%v - podHPMaxUsedRequest:%v)", batchAllocatable.Cpu().MilliValue(), nodeCapacity.Cpu().MilliValue(), *batchCPUThresholdPercent, nodeCapacity.Cpu().MilliValue(), nodeSafetyMargin.Cpu().MilliValue(), systemUsed.Cpu().MilliValue(), podHPMaxUsedReq.Cpu().MilliValue()) } } else { // use CalculatePolicy "usage" by default if batchCPUThresholdPercent == nil { cpuMsg = fmt.Sprintf("batchAllocatable[CPU(Milli-Core)]:%v = nodeCapacity:%v - nodeSafetyMargin:%v - systemUsageOrNodeReserved:%v - podHPUsed:%v", batchAllocatable.Cpu().MilliValue(), nodeCapacity.Cpu().MilliValue(), nodeSafetyMargin.Cpu().MilliValue(), systemUsed.Cpu().MilliValue(), podHPUsed.Cpu().MilliValue()) } else { batchAllocatable[corev1.ResourceCPU] = util.MinQuant(*batchAllocatable.Cpu(), util.MultiplyMilliQuant(*nodeCapacity.Cpu(), float64(*strategy.BatchCPUThresholdPercent)/100)) cpuMsg = fmt.Sprintf("batchAllocatable[CPU(Milli-Core)]:%v = min(nodeCapacity:%v * thresholdRatio:%v, nodeCapacity:%v - nodeSafetyMargin:%v - systemUsageOrNodeReserved:%v - podHPUsed:%v)", batchAllocatable.Cpu().MilliValue(), nodeCapacity.Cpu().MilliValue(), *batchCPUThresholdPercent, nodeCapacity.Cpu().MilliValue(), nodeSafetyMargin.Cpu().MilliValue(), systemUsed.Cpu().MilliValue(), podHPUsed.Cpu().MilliValue()) } } var memMsg string var batchMemThresholdPercent *float64 if strategy != nil && strategy.BatchMemoryThresholdPercent != nil { batchMemThresholdPercent = ptr.To(float64(*strategy.BatchMemoryThresholdPercent) / 100) } // batch memory support policy "usage", "request" and "maxUsageRequest" if strategy != nil && strategy.MemoryCalculatePolicy != nil && *strategy.MemoryCalculatePolicy == configuration.CalculateByPodRequest { if batchMemThresholdPercent == nil { batchAllocatable[corev1.ResourceMemory] = *batchAllocatableByRequest.Memory() memMsg = fmt.Sprintf("batchAllocatable[Mem(GB)]:%v = nodeCapacity:%v - nodeSafetyMargin:%v - nodeReserved:%v - podHPRequest:%v", batchAllocatable.Memory().ScaledValue(resource.Giga), nodeCapacity.Memory().ScaledValue(resource.Giga), nodeSafetyMargin.Memory().ScaledValue(resource.Giga), nodeReserved.Memory().ScaledValue(resource.Giga), podHPReq.Memory().ScaledValue(resource.Giga)) } else { batchAllocatable[corev1.ResourceMemory] = util.MinQuant(*batchAllocatableByRequest.Memory(), util.MultiplyQuant(*nodeCapacity.Memory(), float64(*strategy.BatchMemoryThresholdPercent)/100)) memMsg = fmt.Sprintf("batchAllocatable[Mem(GB)]:%v = min(nodeCapacity:%v * thresholdRatio:%v, nodeCapacity:%v - nodeSafetyMargin:%v - nodeReserved:%v - podHPRequest:%v)", batchAllocatable.Memory().ScaledValue(resource.Giga), nodeCapacity.Memory().ScaledValue(resource.Giga), *batchMemThresholdPercent, nodeCapacity.Memory().ScaledValue(resource.Giga), nodeSafetyMargin.Memory().ScaledValue(resource.Giga), nodeReserved.Memory().ScaledValue(resource.Giga), podHPReq.Memory().ScaledValue(resource.Giga)) } } else if strategy != nil && strategy.MemoryCalculatePolicy != nil && *strategy.MemoryCalculatePolicy == configuration.CalculateByPodMaxUsageRequest { if batchMemThresholdPercent == nil { batchAllocatable[corev1.ResourceMemory] = *batchAllocatableByMaxUsageRequest.Memory() memMsg = fmt.Sprintf("batchAllocatable[Mem(GB)]:%v = nodeCapacity:%v - nodeSafetyMargin:%v - systemUsage:%v - podHPMaxUsedRequest:%v", batchAllocatable.Memory().ScaledValue(resource.Giga), nodeCapacity.Memory().ScaledValue(resource.Giga), nodeSafetyMargin.Memory().ScaledValue(resource.Giga), systemUsed.Memory().ScaledValue(resource.Giga), podHPMaxUsedReq.Memory().ScaledValue(resource.Giga)) } else { batchAllocatable[corev1.ResourceMemory] = util.MinQuant(*batchAllocatableByMaxUsageRequest.Memory(), util.MultiplyQuant(*nodeCapacity.Memory(), float64(*strategy.BatchMemoryThresholdPercent)/100)) memMsg = fmt.Sprintf("batchAllocatable[Mem(GB)]:%v = min(nodeCapacity:%v * thresholdRatio:%v, nodeCapacity:%v - nodeSafetyMargin:%v - systemUsage:%v - podHPMaxUsedRequest:%v)", batchAllocatable.Memory().ScaledValue(resource.Giga), nodeCapacity.Memory().ScaledValue(resource.Giga), *batchMemThresholdPercent, nodeCapacity.Memory().ScaledValue(resource.Giga), nodeSafetyMargin.Memory().ScaledValue(resource.Giga), systemUsed.Memory().ScaledValue(resource.Giga), podHPMaxUsedReq.Memory().ScaledValue(resource.Giga)) } } else { // use CalculatePolicy "usage" by default if batchMemThresholdPercent == nil { memMsg = fmt.Sprintf("batchAllocatable[Mem(GB)]:%v = nodeCapacity:%v - nodeSafetyMargin:%v - systemUsage:%v - podHPUsed:%v", batchAllocatable.Memory().ScaledValue(resource.Giga), nodeCapacity.Memory().ScaledValue(resource.Giga), nodeSafetyMargin.Memory().ScaledValue(resource.Giga), systemUsed.Memory().ScaledValue(resource.Giga), podHPUsed.Memory().ScaledValue(resource.Giga)) } else { batchAllocatable[corev1.ResourceMemory] = util.MinQuant(*batchAllocatable.Memory(), util.MultiplyQuant(*nodeCapacity.Memory(), float64(*strategy.BatchMemoryThresholdPercent)/100)) memMsg = fmt.Sprintf("batchAllocatable[Mem(GB)]:%v = min(nodeCapacity:%v * thresholdRatio:%v, nodeCapacity:%v - nodeSafetyMargin:%v - systemUsage:%v - podHPMaxUsedRequest:%v)", batchAllocatable.Memory().ScaledValue(resource.Giga), nodeCapacity.Memory().ScaledValue(resource.Giga), *batchMemThresholdPercent, nodeCapacity.Memory().ScaledValue(resource.Giga), nodeSafetyMargin.Memory().ScaledValue(resource.Giga), systemUsed.Memory().ScaledValue(resource.Giga), podHPMaxUsedReq.Memory().ScaledValue(resource.Giga)) } } return batchAllocatable, cpuMsg, memMsg } func CalculateMidResourceByPolicy(strategy *configuration.ColocationStrategy, nodeCapacity, unallocated, nodeUnused corev1.ResourceList, allocatableMilliCPU, allocatableMemory int64, prodReclaimableCPU, prodReclaimableMemory *resource.Quantity, nodeName string) (*resource.Quantity, *resource.Quantity, string, string) { defaultStrategy := sloconfig.DefaultColocationStrategy() cpuThresholdRatio := getPercentFromStrategy(strategy, &defaultStrategy, MidCPUThreshold) if maxMilliCPU := float64(nodeCapacity.Cpu().MilliValue()) * cpuThresholdRatio; allocatableMilliCPU > int64(maxMilliCPU) { allocatableMilliCPU = int64(maxMilliCPU) } if allocatableMilliCPU > nodeUnused.Cpu().MilliValue() { allocatableMilliCPU = nodeUnused.Cpu().MilliValue() } if allocatableMilliCPU < 0 { klog.V(5).Infof("mid allocatable milli cpu of node %s is %v less than zero, set to zero", nodeName, allocatableMilliCPU) allocatableMilliCPU = 0 } cpuInMilliCores := resource.NewQuantity(allocatableMilliCPU, resource.DecimalSI) memThresholdRatio := getPercentFromStrategy(strategy, &defaultStrategy, MidMemoryThreshold) if maxMemory := float64(nodeCapacity.Memory().Value()) * memThresholdRatio; allocatableMemory > int64(maxMemory) { allocatableMemory = int64(maxMemory) } if allocatableMemory > nodeUnused.Memory().Value() { allocatableMemory = nodeUnused.Memory().Value() } if allocatableMemory < 0 { klog.V(5).Infof("mid allocatable memory of node %s is %v less than zero, set to zero", nodeName, allocatableMemory) allocatableMemory = 0 } memory := resource.NewQuantity(allocatableMemory, resource.BinarySI) // CPU need turn into milli value unallocatedMilliCPU, unallocatedMemory := resource.NewQuantity(unallocated.Cpu().MilliValue(), resource.DecimalSI), unallocated.Memory() midUnallocatedRatio := getPercentFromStrategy(strategy, &defaultStrategy, MidUnallocatedPercent) adjustedUnallocatedMilliCPU := resource.NewQuantity(int64(float64(unallocatedMilliCPU.Value())*midUnallocatedRatio), resource.DecimalSI) adjustedUnallocatedMemory := resource.NewQuantity(int64(float64(unallocatedMemory.Value())*midUnallocatedRatio), resource.BinarySI) cpuInMilliCores.Add(*adjustedUnallocatedMilliCPU) memory.Add(*adjustedUnallocatedMemory) cpuMsg := fmt.Sprintf("midAllocatable[CPU(milli-core)]:%v = min(nodeCapacity:%v * thresholdRatio:%v, ProdReclaimable:%v, NodeUnused:%v) + Unallocated:%v * midUnallocatedRatio:%v", cpuInMilliCores.Value(), nodeCapacity.Cpu().MilliValue(), cpuThresholdRatio, prodReclaimableCPU.MilliValue(), nodeUnused.Cpu().MilliValue(), unallocatedMilliCPU.Value(), midUnallocatedRatio) memMsg := fmt.Sprintf("midAllocatable[Memory(GB)]:%v = min(nodeCapacity:%v * thresholdRatio:%v, ProdReclaimable:%v, NodeUnused:%v) + Unallocated:%v * midUnallocatedRatio:%v", memory.ScaledValue(resource.Giga), nodeCapacity.Memory().ScaledValue(resource.Giga), memThresholdRatio, prodReclaimableMemory.ScaledValue(resource.Giga), nodeUnused.Memory().ScaledValue(resource.Giga), unallocatedMemory.ScaledValue(resource.Giga), midUnallocatedRatio) return cpuInMilliCores, memory, cpuMsg, memMsg } func PrepareNodeForResource(node *corev1.Node, nr *framework.NodeResource, name corev1.ResourceName) { q := nr.Resources[name] if q == nil || nr.Resets[name] { // if the specified resource has no quantity delete(node.Status.Capacity, name) delete(node.Status.Allocatable, name) return } // TODO mv to post-calculate stage for merging multiple calculate results // amplify batch cpu according to cpu normalization ratio if name == extension.BatchCPU { ratio, err := getCPUNormalizationRatio(nr) if err != nil { klog.V(5).InfoS("failed to get cpu normalization ratio for node extended resources", "node", node.Name, "err", err) } if ratio > 1.0 { // skip for invalid ratio newQuantity := util.MultiplyMilliQuant(*q, ratio) q = &newQuantity } } // NOTE: extended resource would be validated as an integer, so it should be checked before the update if _, ok := q.AsInt64(); !ok { klog.V(4).InfoS("node resource's quantity is not int64 and will be rounded", "node", node.Name, "resource", name, "original", *q, "rounded", q.Value()) q.Set(q.Value()) } node.Status.Capacity[name] = *q node.Status.Allocatable[name] = *q } // GetPodMetricUsage gets pod usage from the PodMetricInfo func GetPodMetricUsage(info *slov1alpha1.PodMetricInfo) corev1.ResourceList { return GetResourceListForCPUAndMemory(info.PodUsage.ResourceList) } func GetHostAppHPUsed(resourceMetrics *framework.ResourceMetrics, resPriority extension.PriorityClass) corev1.ResourceList { hostAppHPUsed := util.NewZeroResourceList() for _, hostAppMetric := range resourceMetrics.NodeMetric.Status.HostApplicationMetric { if extension.GetDefaultPriorityByPriorityClass(hostAppMetric.Priority) <= extension.GetDefaultPriorityByPriorityClass(resPriority) { // consider higher priority usage for mid or batch allocatable // now only support product and batch(hadoop-yarn) priority for host application continue } hostAppHPUsed = quotav1.Add(hostAppHPUsed, GetHostAppMetricUsage(hostAppMetric)) } return hostAppHPUsed } // GetHostAppMetricUsage gets host application usage from HostApplicationMetricInfo func GetHostAppMetricUsage(info *slov1alpha1.HostApplicationMetricInfo) corev1.ResourceList { return GetResourceListForCPUAndMemory(info.Usage.ResourceList) } // GetPodNUMARequestAndUsage returns the pod request and usage on each NUMA nodes. // It averages the metrics over all sharepools when the pod does not allocate any sharepool or use all sharepools. func GetPodNUMARequestAndUsage(pod *corev1.Pod, podRequest, podUsage corev1.ResourceList, numaNum int) ([]corev1.ResourceList, []corev1.ResourceList) { // get pod NUMA allocation var podAlloc *extension.ResourceStatus if pod.Annotations == nil { podAlloc = &extension.ResourceStatus{} } else if podAllocFromAnnotations, err := extension.GetResourceStatus(pod.Annotations); err != nil { podAlloc = &extension.ResourceStatus{} klog.V(5).Infof("failed to get NUMA resource status of the pod %s, suppose it is LS, err: %s", util.GetPodKey(pod), err) } else { podAlloc = podAllocFromAnnotations } // NOTE: For the pod which does not set NUMA-aware allocation policy, it has set particular cpuset cpus but may not // have NUMA allocation information in annotations. In this case, it can be inaccurate to average the // request/usage over all NUMA nodes. podNUMARequest := make([]corev1.ResourceList, numaNum) podNUMAUsage := make([]corev1.ResourceList, numaNum) allocatedNUMAMap := map[int]struct{}{} allocatedNUMANum := 0 // the number of allocated NUMA node for _, numaResource := range podAlloc.NUMANodeResources { allocatedNUMAMap[int(numaResource.Node)] = struct{}{} // The invalid allocated NUMA ids will be ignored since it cannot be successfully bind on the node either. if int(numaResource.Node) < numaNum && numaResource.Node >= 0 { allocatedNUMANum++ } } if allocatedNUMANum <= 0 { // share all NUMAs for i := 0; i < numaNum; i++ { podNUMARequest[i] = DivideResourceList(podRequest, float64(numaNum)) podNUMAUsage[i] = DivideResourceList(podUsage, float64(numaNum)) } } else { for i := 0; i < numaNum; i++ { _, ok := allocatedNUMAMap[i] if !ok { podNUMARequest[i] = util.NewZeroResourceList() podNUMAUsage[i] = util.NewZeroResourceList() continue } podNUMARequest[i] = DivideResourceList(podRequest, float64(allocatedNUMANum)) podNUMAUsage[i] = DivideResourceList(podUsage, float64(allocatedNUMANum)) } } return podNUMARequest, podNUMAUsage } func GetPodUnknownNUMAUsage(podUsage corev1.ResourceList, numaNum int) []corev1.ResourceList { if numaNum <= 0 { return nil } podNUMAUsage := make([]corev1.ResourceList, numaNum) for i := 0; i < numaNum; i++ { podNUMAUsage[i] = DivideResourceList(podUsage, float64(numaNum)) } return podNUMAUsage } // GetNodeCapacity gets node capacity and filters out non-CPU and non-Mem resources func GetNodeCapacity(node *corev1.Node) corev1.ResourceList { return GetResourceListForCPUAndMemory(node.Status.Capacity) } // GetNodeSafetyMargin gets node-level safe-guarding reservation with the node's allocatable func GetNodeSafetyMargin(strategy *configuration.ColocationStrategy, nodeCapacity corev1.ResourceList) corev1.ResourceList { cpuReserveQuant := util.MultiplyMilliQuant(nodeCapacity[corev1.ResourceCPU], getReserveRatio(*strategy.CPUReclaimThresholdPercent)) memReserveQuant := util.MultiplyQuant(nodeCapacity[corev1.ResourceMemory], getReserveRatio(*strategy.MemoryReclaimThresholdPercent)) return corev1.ResourceList{ corev1.ResourceCPU: cpuReserveQuant, corev1.ResourceMemory: memReserveQuant, } } func DivideResourceList(rl corev1.ResourceList, divisor float64) corev1.ResourceList { if divisor == 0 { return rl } divided := corev1.ResourceList{} for resourceName, q := range rl { divided[resourceName] = *resource.NewMilliQuantity(int64(math.Ceil(float64(q.MilliValue())/divisor)), q.Format) } return divided } func zoneResourceListHandler(a, b []corev1.ResourceList, zoneNum int, handleFn func(a corev1.ResourceList, b corev1.ResourceList) corev1.ResourceList) []corev1.ResourceList { // assert len(a) == len(b) == zoneNum result := make([]corev1.ResourceList, zoneNum) for i := 0; i < zoneNum; i++ { result[i] = handleFn(a[i], b[i]) } return result } func AddZoneResourceList(a, b []corev1.ResourceList, zoneNum int) []corev1.ResourceList { return zoneResourceListHandler(a, b, zoneNum, quotav1.Add) } func MaxZoneResourceList(a, b []corev1.ResourceList, zoneNum int) []corev1.ResourceList { return zoneResourceListHandler(a, b, zoneNum, quotav1.Max) } func GetResourceListForCPUAndMemory(rl corev1.ResourceList) corev1.ResourceList { return quotav1.Mask(rl, []corev1.ResourceName{corev1.ResourceCPU, corev1.ResourceMemory}) } func MixResourceListCPUAndMemory(resourcesForCPU, resourcesForMemory corev1.ResourceList) corev1.ResourceList { return corev1.ResourceList{ corev1.ResourceCPU: resourcesForCPU[corev1.ResourceCPU], corev1.ResourceMemory: resourcesForMemory[corev1.ResourceMemory], } } func MinxZoneResourceListCPUAndMemory(resourcesForCPU, resourcesForMemory []corev1.ResourceList, zoneNum int) []corev1.ResourceList { // assert len(a) == len(b) == zoneNum result := make([]corev1.ResourceList, zoneNum) for i := 0; i < zoneNum; i++ { result[i] = MixResourceListCPUAndMemory(resourcesForCPU[i], resourcesForMemory[i]) } return result } // getReserveRatio returns resource reserved ratio func getReserveRatio(reclaimThreshold int64) float64 { return float64(100-reclaimThreshold) / 100.0 } func UpdateNRTZoneListIfNeeded(node *corev1.Node, zoneList topologyv1alpha1.ZoneList, nr *framework.NodeResource, diffThreshold float64) bool { ratio, err := getCPUNormalizationRatio(nr) if err != nil { klog.V(5).InfoS("failed to get cpu normalization ratio for zone resources", "node", node.Name, "err", err) } needUpdate := false for i := range zoneList { zone := zoneList[i] zoneResource, ok := nr.ZoneResources[zone.Name] if !ok { // the resources of the zone should be reset for _, resourceInfo := range zone.Resources { if !updateNRTResourceSet.Has(resourceInfo.Name) { continue } // FIXME: currently we set value to zero instead of deleting resource if resourceInfo.Capacity.IsZero() && resourceInfo.Allocatable.IsZero() && resourceInfo.Available.IsZero() { // already reset continue } needUpdate = true resourceInfo.Capacity = *resource.NewQuantity(0, resourceInfo.Capacity.Format) resourceInfo.Allocatable = *resource.NewQuantity(0, resourceInfo.Allocatable.Format) resourceInfo.Available = *resource.NewQuantity(0, resourceInfo.Available.Format) klog.V(6).InfoS("reset batch resource for zone", "node", node.Name, "zone", zone.Name, "resource", resourceInfo.Name) } } for resourceName := range zoneResource { quantity := zoneResource[resourceName] // amplify batch cpu according to cpu normalization ratio if resourceName == extension.BatchCPU && ratio > 1.0 { quantity = util.MultiplyMilliQuant(quantity, ratio) } oldHasResource := false for j, resourceInfo := range zone.Resources { if resourceInfo.Name == string(resourceName) { // old has the resource key if util.IsQuantityDiff(resourceInfo.Capacity, quantity, diffThreshold) { needUpdate = true resourceInfo.Capacity = quantity } if util.IsQuantityDiff(resourceInfo.Allocatable, quantity, diffThreshold) { needUpdate = true resourceInfo.Allocatable = quantity } if util.IsQuantityDiff(resourceInfo.Available, quantity, diffThreshold) { needUpdate = true resourceInfo.Available = quantity } zone.Resources[j] = resourceInfo oldHasResource = true klog.V(6).InfoS("update batch resource for zone", "node", node.Name, "zone", zone.Name, "resource", resourceName) break } } if !oldHasResource { // old has no resource key needUpdate = true zone.Resources = append(zone.Resources, topologyv1alpha1.ResourceInfo{ Name: string(resourceName), Capacity: quantity, Allocatable: quantity, Available: quantity, }) sort.Slice(zone.Resources, func(p, q int) bool { // keep the resources order return zone.Resources[p].Name < zone.Resources[q].Name }) klog.V(6).InfoS("add batch resource for zone", "node", node.Name, "zone", zone.Name, "resource", resourceName) } } zoneList[i] = zone } return needUpdate } func getCPUNormalizationRatio(nr *framework.NodeResource) (float64, error) { ratioStr, ok := nr.Annotations[extension.AnnotationCPUNormalizationRatio] if !ok { return -1, nil } ratio, err := strconv.ParseFloat(ratioStr, 64) if err != nil { return -1, fmt.Errorf("failed to parse ratio in NodeResource, err: %w", err) } return ratio, nil } func getPercentFromStrategy(strategy, defaultStrategy *configuration.ColocationStrategy, strategyType string) float64 { switch strategyType { case MidCPUThreshold: if strategy == nil || strategy.MidCPUThresholdPercent == nil { return float64(*defaultStrategy.MidCPUThresholdPercent) / 100 } return float64(*strategy.MidCPUThresholdPercent) / 100 case MidMemoryThreshold: if strategy == nil || strategy.MidMemoryThresholdPercent == nil { return float64(*defaultStrategy.MidMemoryThresholdPercent) / 100 } return float64(*strategy.MidMemoryThresholdPercent) / 100 case MidUnallocatedPercent: if strategy == nil || strategy.MidUnallocatedPercent == nil { return float64(*defaultStrategy.MidUnallocatedPercent) / 100 } return float64(*strategy.MidUnallocatedPercent) / 100 default: return 0 } } func IsValidNodeUsage(nodeMetric *slov1alpha1.NodeMetric) (bool, string) { if nodeMetric == nil || nodeMetric.Status.NodeMetric == nil || nodeMetric.Status.NodeMetric.NodeUsage.ResourceList == nil { return false, "node metric is incomplete" } _, ok := nodeMetric.Status.NodeMetric.NodeUsage.ResourceList[corev1.ResourceCPU] if !ok { return false, "cpu usage is missing" } _, ok = nodeMetric.Status.NodeMetric.NodeUsage.ResourceList[corev1.ResourceMemory] if !ok { return false, "memory usage is missing" } return true, "" }
1
0.899346
1
0.899346
game-dev
MEDIA
0.305163
game-dev
0.899371
1
0.899371
mchorse/metamorph
1,817
src/main/java/mchorse/vanilla_pack/actions/Explode.java
package mchorse.vanilla_pack.actions; import javax.annotation.Nullable; import mchorse.metamorph.api.abilities.IAction; import mchorse.metamorph.api.morphs.AbstractMorph; import mchorse.metamorph.api.morphs.EntityMorph; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityCreeper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.DamageSource; import net.minecraftforge.fml.relauncher.ReflectionHelper; /** * Explode action * * This action makes an explosion and also kills the player. Why kill also the * player? Because it won't be so creeper if he won't die. * * EXPLOSIONS!!! Mr. Torgue approves this action. */ public class Explode implements IAction { @Override public void execute(EntityLivingBase target, @Nullable AbstractMorph morph) { if (target.world.isRemote) { return; } int explosionPower = 3; boolean isPowered = false; if (morph instanceof EntityMorph) { EntityLivingBase entity = ((EntityMorph) morph).getEntity(); if (entity instanceof EntityCreeper) { explosionPower = ReflectionHelper.getPrivateValue(EntityCreeper.class, (EntityCreeper) entity, "explosionRadius", "field_82226_g"); isPowered = ((EntityCreeper) entity).getPowered(); } } float f = isPowered ? 2.0F : 1.0F; target.world.createExplosion(target, target.posX, target.posY, target.posZ, explosionPower * f, true); if (!(target instanceof EntityPlayer) || (target instanceof EntityPlayer && !((EntityPlayer) target).isCreative())) { target.attackEntityFrom(DamageSource.OUT_OF_WORLD, target.getMaxHealth()); } } }
1
0.894558
1
0.894558
game-dev
MEDIA
0.995094
game-dev
0.88707
1
0.88707
natintosh/intl_phone_number_input
2,251
lib/src/widgets/item.dart
import 'package:flutter/material.dart'; import 'package:intl_phone_number_input/src/models/country_model.dart'; import 'package:intl_phone_number_input/src/utils/util.dart'; /// [Item] class Item extends StatelessWidget { final Country? country; final bool? showFlag; final bool? useEmoji; final TextStyle? textStyle; final bool withCountryNames; final double? leadingPadding; final bool trailingSpace; const Item({ Key? key, this.country, this.showFlag, this.useEmoji, this.textStyle, this.withCountryNames = false, this.leadingPadding = 12, this.trailingSpace = true, }) : super(key: key); @override Widget build(BuildContext context) { String dialCode = (country?.dialCode ?? ''); if (trailingSpace) { dialCode = dialCode.padRight(5, " "); } return Container( child: Row( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox(width: leadingPadding), _Flag( country: country, showFlag: showFlag, useEmoji: useEmoji, ), SizedBox(width: 12.0), Text( '$dialCode', textDirection: TextDirection.ltr, style: textStyle, ), ], ), ); } } class _Flag extends StatelessWidget { final Country? country; final bool? showFlag; final bool? useEmoji; const _Flag({Key? key, this.country, this.showFlag, this.useEmoji}) : super(key: key); @override Widget build(BuildContext context) { return country != null && showFlag! ? Container( child: useEmoji! ? Text( Utils.generateFlagEmojiUnicode(country?.alpha2Code ?? ''), style: Theme.of(context).textTheme.headlineSmall, ) : Image.asset( country!.flagUri, width: 32.0, package: 'intl_phone_number_input', errorBuilder: (context, error, stackTrace) { return SizedBox.shrink(); }, ), ) : SizedBox.shrink(); } }
1
0.869139
1
0.869139
game-dev
MEDIA
0.965285
game-dev
0.962861
1
0.962861
FairyProject/fairy
1,271
framework/platforms/mc-platform/src/main/java/io/fairyproject/mc/MCWorld.java
package io.fairyproject.mc; import io.fairyproject.data.MetaStorage; import io.fairyproject.event.EventNode; import io.fairyproject.mc.data.MCMetadata; import io.fairyproject.mc.event.trait.MCWorldEvent; import io.fairyproject.mc.util.AudienceProxy; import io.fairyproject.metadata.MetadataMap; import lombok.experimental.UtilityClass; import java.util.List; public interface MCWorld extends AudienceProxy { static <T> MCWorld from(T world) { return Companion.BRIDGE.from(world); } static MCWorld getByName(String name) { return Companion.BRIDGE.getByName(name); } static List<MCWorld> all() { return Companion.BRIDGE.all(); } <T> T as(Class<T> worldClass); int getMaxY(); int getMaxSectionY(); String getName(); EventNode<MCWorldEvent> getEventNode(); @Deprecated MetadataMap getMetadata(); default MetaStorage getMetaStorage() { return MCMetadata.provideWorld(this.getName()); } List<MCPlayer> getPlayers(); @UtilityClass @Deprecated class Companion { public Bridge BRIDGE; } @Deprecated interface Bridge { MCWorld from(Object world); MCWorld getByName(String name); List<MCWorld> all(); } }
1
0.751279
1
0.751279
game-dev
MEDIA
0.86768
game-dev
0.594718
1
0.594718
cocos/cocos-engine
17,022
native/cocos/editor-support/spine/4.2/spine/PathConstraint.cpp
/****************************************************************************** * Spine Runtimes License Agreement * Last updated July 28, 2023. Replaces all prior versions. * * Copyright (c) 2013-2023, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software or * otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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 THE * SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #include <spine/PathConstraint.h> #include <spine/Bone.h> #include <spine/PathAttachment.h> #include <spine/PathConstraintData.h> #include <spine/Skeleton.h> #include <spine/Slot.h> #include <spine/BoneData.h> #include <spine/SlotData.h> using namespace spine; RTTI_IMPL(PathConstraint, Updatable) const float PathConstraint::EPSILON = 0.00001f; const int PathConstraint::NONE = -1; const int PathConstraint::BEFORE = -2; const int PathConstraint::AFTER = -3; PathConstraint::PathConstraint(PathConstraintData &data, Skeleton &skeleton) : Updatable(), _data(data), _target(skeleton.findSlot( data.getTarget()->getName())), _position(data.getPosition()), _spacing(data.getSpacing()), _mixRotate(data.getMixRotate()), _mixX(data.getMixX()), _mixY(data.getMixY()), _active(false) { _bones.ensureCapacity(_data.getBones().size()); for (size_t i = 0; i < _data.getBones().size(); i++) { BoneData *boneData = _data.getBones()[i]; _bones.add(skeleton.findBone(boneData->getName())); } _segments.setSize(10, 0); } void PathConstraint::update(Physics) { Attachment *baseAttachment = _target->getAttachment(); if (baseAttachment == NULL || !baseAttachment->getRTTI().instanceOf(PathAttachment::rtti)) { return; } PathAttachment *attachment = static_cast<PathAttachment *>(baseAttachment); float mixRotate = _mixRotate, mixX = _mixX, mixY = _mixY; if (mixRotate == 0 && mixX == 0 && mixY == 0) return; PathConstraintData &data = _data; bool tangents = data._rotateMode == RotateMode_Tangent, scale = data._rotateMode == RotateMode_ChainScale; size_t boneCount = _bones.size(); size_t spacesCount = tangents ? boneCount : boneCount + 1; _spaces.setSize(spacesCount, 0); if (scale) _lengths.setSize(boneCount, 0); float spacing = _spacing; switch (data._spacingMode) { case SpacingMode_Percent: { if (scale) { for (size_t i = 0, n = spacesCount - 1; i < n; i++) { Bone *boneP = _bones[i]; Bone &bone = *boneP; float setupLength = bone._data.getLength(); float x = setupLength * bone._a; float y = setupLength * bone._c; _lengths[i] = MathUtil::sqrt(x * x + y * y); } } for (size_t i = 1; i < spacesCount; ++i) { _spaces[i] = spacing; } break; } case SpacingMode_Proportional: { float sum = 0; for (size_t i = 0, n = spacesCount - 1; i < n;) { Bone *boneP = _bones[i]; Bone &bone = *boneP; float setupLength = bone._data.getLength(); if (setupLength < PathConstraint::EPSILON) { if (scale) _lengths[i] = 0; _spaces[++i] = spacing; } else { float x = setupLength * bone._a, y = setupLength * bone._c; float length = MathUtil::sqrt(x * x + y * y); if (scale) _lengths[i] = length; _spaces[++i] = length; sum += length; } } if (sum > 0) { sum = spacesCount / sum * spacing; for (size_t i = 1; i < spacesCount; i++) { _spaces[i] *= sum; } } break; } default: { bool lengthSpacing = data._spacingMode == SpacingMode_Length; for (size_t i = 0, n = spacesCount - 1; i < n;) { Bone *boneP = _bones[i]; Bone &bone = *boneP; float setupLength = bone._data.getLength(); if (setupLength < PathConstraint::EPSILON) { if (scale) _lengths[i] = 0; _spaces[++i] = spacing; } else { float x = setupLength * bone._a, y = setupLength * bone._c; float length = MathUtil::sqrt(x * x + y * y); if (scale) _lengths[i] = length; _spaces[++i] = (lengthSpacing ? setupLength + spacing : spacing) * length / setupLength; } } } } Vector<float> &positions = computeWorldPositions(*attachment, (int) spacesCount, tangents); float boneX = positions[0]; float boneY = positions[1]; float offsetRotation = data.getOffsetRotation(); bool tip; if (offsetRotation == 0) { tip = data._rotateMode == RotateMode_Chain; } else { tip = false; Bone &p = _target->getBone(); offsetRotation *= p.getA() * p.getD() - p.getB() * p.getC() > 0 ? MathUtil::Deg_Rad : -MathUtil::Deg_Rad; } for (size_t i = 0, p = 3; i < boneCount; i++, p += 3) { Bone *boneP = _bones[i]; Bone &bone = *boneP; bone._worldX += (boneX - bone._worldX) * mixX; bone._worldY += (boneY - bone._worldY) * mixY; float x = positions[p]; float y = positions[p + 1]; float dx = x - boneX; float dy = y - boneY; if (scale) { float length = _lengths[i]; if (length >= PathConstraint::EPSILON) { float s = (MathUtil::sqrt(dx * dx + dy * dy) / length - 1) * mixRotate + 1; bone._a *= s; bone._c *= s; } } boneX = x; boneY = y; if (mixRotate > 0) { float a = bone._a, b = bone._b, c = bone._c, d = bone._d, r, cos, sin; if (tangents) r = positions[p - 1]; else if (_spaces[i + 1] < PathConstraint::EPSILON) r = positions[p + 2]; else r = MathUtil::atan2(dy, dx); r -= MathUtil::atan2(c, a); if (tip) { cos = MathUtil::cos(r); sin = MathUtil::sin(r); float length = bone._data.getLength(); boneX += (length * (cos * a - sin * c) - dx) * mixRotate; boneY += (length * (sin * a + cos * c) - dy) * mixRotate; } else r += offsetRotation; if (r > MathUtil::Pi) r -= MathUtil::Pi_2; else if (r < -MathUtil::Pi) r += MathUtil::Pi_2; r *= mixRotate; cos = MathUtil::cos(r); sin = MathUtil::sin(r); bone._a = cos * a - sin * c; bone._b = cos * b - sin * d; bone._c = sin * a + cos * c; bone._d = sin * b + cos * d; } bone.updateAppliedTransform(); } } int PathConstraint::getOrder() { return (int) _data.getOrder(); } float PathConstraint::getPosition() { return _position; } void PathConstraint::setPosition(float inValue) { _position = inValue; } float PathConstraint::getSpacing() { return _spacing; } void PathConstraint::setSpacing(float inValue) { _spacing = inValue; } float PathConstraint::getMixRotate() { return _mixRotate; } void PathConstraint::setMixRotate(float inValue) { _mixRotate = inValue; } float PathConstraint::getMixX() { return _mixX; } void PathConstraint::setMixX(float inValue) { _mixX = inValue; } float PathConstraint::getMixY() { return _mixY; } void PathConstraint::setMixY(float inValue) { _mixY = inValue; } Vector<Bone *> &PathConstraint::getBones() { return _bones; } Slot *PathConstraint::getTarget() { return _target; } void PathConstraint::setTarget(Slot *inValue) { _target = inValue; } PathConstraintData &PathConstraint::getData() { return _data; } Vector<float> & PathConstraint::computeWorldPositions(PathAttachment &path, int spacesCount, bool tangents) { Slot &target = *_target; float position = _position; _positions.setSize(spacesCount * 3 + 2, 0); Vector<float> &out = _positions; Vector<float> &world = _world; bool closed = path.isClosed(); int verticesLength = (int) path.getWorldVerticesLength(); int curveCount = verticesLength / 6; int prevCurve = NONE; float pathLength; if (!path.isConstantSpeed()) { Vector<float> &lengths = path.getLengths(); curveCount -= closed ? 1 : 2; pathLength = lengths[curveCount]; if (_data._positionMode == PositionMode_Percent) position *= pathLength; float multiplier = 0; switch (_data._spacingMode) { case SpacingMode_Percent: multiplier = pathLength; break; case SpacingMode_Proportional: multiplier = pathLength / spacesCount; break; default: multiplier = 1; } world.setSize(8, 0); for (int i = 0, o = 0, curve = 0; i < spacesCount; i++, o += 3) { float space = _spaces[i] * multiplier; position += space; float p = position; if (closed) { p = MathUtil::fmod(p, pathLength); if (p < 0) p += pathLength; curve = 0; } else if (p < 0) { if (prevCurve != BEFORE) { prevCurve = BEFORE; path.computeWorldVertices(target, 2, 4, world, 0); } addBeforePosition(p, world, 0, out, o); continue; } else if (p > pathLength) { if (prevCurve != AFTER) { prevCurve = AFTER; path.computeWorldVertices(target, verticesLength - 6, 4, world, 0); } addAfterPosition(p - pathLength, world, 0, out, o); continue; } // Determine curve containing position. for (;; curve++) { float length = lengths[curve]; if (p > length) continue; if (curve == 0) p /= length; else { float prev = lengths[curve - 1]; p = (p - prev) / (length - prev); } break; } if (curve != prevCurve) { prevCurve = curve; if (closed && curve == curveCount) { path.computeWorldVertices(target, verticesLength - 4, 4, world, 0); path.computeWorldVertices(target, 0, 4, world, 4); } else path.computeWorldVertices(target, curve * 6 + 2, 8, world, 0); } addCurvePosition(p, world[0], world[1], world[2], world[3], world[4], world[5], world[6], world[7], out, o, tangents || (i > 0 && space < EPSILON)); } return out; } // World vertices. if (closed) { verticesLength += 2; world.setSize(verticesLength, 0); path.computeWorldVertices(target, 2, verticesLength - 4, world, 0); path.computeWorldVertices(target, 0, 2, world, verticesLength - 4); world[verticesLength - 2] = world[0]; world[verticesLength - 1] = world[1]; } else { curveCount--; verticesLength -= 4; world.setSize(verticesLength, 0); path.computeWorldVertices(target, 2, verticesLength, world, 0); } // Curve lengths. _curves.setSize(curveCount, 0); pathLength = 0; float x1 = world[0], y1 = world[1], cx1 = 0, cy1 = 0, cx2 = 0, cy2 = 0, x2 = 0, y2 = 0; float tmpx, tmpy, dddfx, dddfy, ddfx, ddfy, dfx, dfy; for (int i = 0, w = 2; i < curveCount; i++, w += 6) { cx1 = world[w]; cy1 = world[w + 1]; cx2 = world[w + 2]; cy2 = world[w + 3]; x2 = world[w + 4]; y2 = world[w + 5]; tmpx = (x1 - cx1 * 2 + cx2) * 0.1875f; tmpy = (y1 - cy1 * 2 + cy2) * 0.1875f; dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.09375f; dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.09375f; ddfx = tmpx * 2 + dddfx; ddfy = tmpy * 2 + dddfy; dfx = (cx1 - x1) * 0.75f + tmpx + dddfx * 0.16666667f; dfy = (cy1 - y1) * 0.75f + tmpy + dddfy * 0.16666667f; pathLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); dfx += ddfx; dfy += ddfy; ddfx += dddfx; ddfy += dddfy; pathLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); dfx += ddfx; dfy += ddfy; pathLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); dfx += ddfx + dddfx; dfy += ddfy + dddfy; pathLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); _curves[i] = pathLength; x1 = x2; y1 = y2; } if (_data._positionMode == PositionMode_Percent) position *= pathLength; float multiplier = 0; switch (_data._spacingMode) { case SpacingMode_Percent: multiplier = pathLength; break; case SpacingMode_Proportional: multiplier = pathLength / spacesCount; break; default: multiplier = 1; } float curveLength = 0; for (int i = 0, o = 0, curve = 0, segment = 0; i < spacesCount; i++, o += 3) { float space = _spaces[i] * multiplier; position += space; float p = position; if (closed) { p = MathUtil::fmod(p, pathLength); if (p < 0) p += pathLength; curve = 0; } else if (p < 0) { addBeforePosition(p, world, 0, out, o); continue; } else if (p > pathLength) { addAfterPosition(p - pathLength, world, verticesLength - 4, out, o); continue; } // Determine curve containing position. for (;; curve++) { float length = _curves[curve]; if (p > length) continue; if (curve == 0) p /= length; else { float prev = _curves[curve - 1]; p = (p - prev) / (length - prev); } break; } // Curve segment lengths. if (curve != prevCurve) { prevCurve = curve; int ii = curve * 6; x1 = world[ii]; y1 = world[ii + 1]; cx1 = world[ii + 2]; cy1 = world[ii + 3]; cx2 = world[ii + 4]; cy2 = world[ii + 5]; x2 = world[ii + 6]; y2 = world[ii + 7]; tmpx = (x1 - cx1 * 2 + cx2) * 0.03f; tmpy = (y1 - cy1 * 2 + cy2) * 0.03f; dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.006f; dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.006f; ddfx = tmpx * 2 + dddfx; ddfy = tmpy * 2 + dddfy; dfx = (cx1 - x1) * 0.3f + tmpx + dddfx * 0.16666667f; dfy = (cy1 - y1) * 0.3f + tmpy + dddfy * 0.16666667f; curveLength = MathUtil::sqrt(dfx * dfx + dfy * dfy); _segments[0] = curveLength; for (ii = 1; ii < 8; ii++) { dfx += ddfx; dfy += ddfy; ddfx += dddfx; ddfy += dddfy; curveLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); _segments[ii] = curveLength; } dfx += ddfx; dfy += ddfy; curveLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); _segments[8] = curveLength; dfx += ddfx + dddfx; dfy += ddfy + dddfy; curveLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); _segments[9] = curveLength; segment = 0; } // Weight by segment length. p *= curveLength; for (;; segment++) { float length = _segments[segment]; if (p > length) continue; if (segment == 0) p /= length; else { float prev = _segments[segment - 1]; p = segment + (p - prev) / (length - prev); } break; } addCurvePosition(p * 0.1f, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, tangents || (i > 0 && space < EPSILON)); } return out; } void PathConstraint::addBeforePosition(float p, Vector<float> &temp, int i, Vector<float> &output, int o) { float x1 = temp[i]; float y1 = temp[i + 1]; float dx = temp[i + 2] - x1; float dy = temp[i + 3] - y1; float r = MathUtil::atan2(dy, dx); output[o] = x1 + p * MathUtil::cos(r); output[o + 1] = y1 + p * MathUtil::sin(r); output[o + 2] = r; } void PathConstraint::addAfterPosition(float p, Vector<float> &temp, int i, Vector<float> &output, int o) { float x1 = temp[i + 2]; float y1 = temp[i + 3]; float dx = x1 - temp[i]; float dy = y1 - temp[i + 1]; float r = MathUtil::atan2(dy, dx); output[o] = x1 + p * MathUtil::cos(r); output[o + 1] = y1 + p * MathUtil::sin(r); output[o + 2] = r; } void PathConstraint::addCurvePosition(float p, float x1, float y1, float cx1, float cy1, float cx2, float cy2, float x2, float y2, Vector<float> &output, int o, bool tangents) { if (p < EPSILON || MathUtil::isNan(p)) { output[o] = x1; output[o + 1] = y1; output[o + 2] = MathUtil::atan2(cy1 - y1, cx1 - x1); return; } float tt = p * p, ttt = tt * p, u = 1 - p, uu = u * u, uuu = uu * u; float ut = u * p, ut3 = ut * 3, uut3 = u * ut3, utt3 = ut3 * p; float x = x1 * uuu + cx1 * uut3 + cx2 * utt3 + x2 * ttt, y = y1 * uuu + cy1 * uut3 + cy2 * utt3 + y2 * ttt; output[o] = x; output[o + 1] = y; if (tangents) { if (p < 0.001) output[o + 2] = MathUtil::atan2(cy1 - y1, cx1 - x1); else output[o + 2] = MathUtil::atan2(y - (y1 * uu + cy1 * ut * 2 + cy2 * tt), x - (x1 * uu + cx1 * ut * 2 + cx2 * tt)); } } bool PathConstraint::isActive() { return _active; } void PathConstraint::setActive(bool inValue) { _active = inValue; } void PathConstraint::setToSetupPose() { PathConstraintData &data = this->_data; this->_position = data._position; this->_spacing = data._spacing; this->_mixRotate = data._mixRotate; this->_mixX = data._mixX; this->_mixY = data._mixY; }
1
0.948047
1
0.948047
game-dev
MEDIA
0.813111
game-dev
0.997533
1
0.997533
akarnokd/ThePlanetCrafterMods
11,091
UIShowAutoCrafterRecipe/Plugin.cs
// Copyright (c) 2022-2025, David Karnok & Contributors // Licensed under the Apache License, Version 2.0 using BepInEx; using SpaceCraft; using HarmonyLib; using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; using BepInEx.Configuration; using System.Text; using BepInEx.Bootstrap; using BepInEx.Logging; using System.Collections; namespace UIShowAutoCrafterRecipe { [BepInPlugin("akarnokd.theplanetcraftermods.uishowautocrafterrecipe", "(UI) Show Auto-Crafter Recipe", PluginInfo.PLUGIN_VERSION)] [BepInDependency(modCheatInventoryStackingGuid, BepInDependency.DependencyFlags.SoftDependency)] public class Plugin : BaseUnityPlugin { const string modCheatInventoryStackingGuid = "akarnokd.theplanetcraftermods.cheatinventorystacking"; // static ManualLogSource logger; static Plugin me; static ConfigEntry<bool> modEnabled; static ConfigEntry<int> fontSize; static ConfigEntry<string> colorAvail; static ConfigEntry<string> colorMissing; static AccessTools.FieldRef<MachineAutoCrafter, List<(GameObject, Group)>> fMachineAutoCrafterGosInRangeForListing; static bool stackingRangeCheckAugment; static AccessTools.FieldRef<object, List<(GameObject, Group)>> fInventoryStackingGosInRangeForListing; static AccessTools.FieldRef<object, Dictionary<Group, List<WorldObject>>> fInventoryStackingAutocrafterWorldObjects; static AccessTools.FieldRef<MachineAutoCrafter, HashSet<WorldObject>> fMachineAutoCrafterWorldObjectsInRange; static Font font; private void Awake() { LibCommon.BepInExLoggerFix.ApplyFix(); // logger = Logger; me = this; // Plugin startup logic Logger.LogInfo($"Plugin is loaded!"); modEnabled = Config.Bind("General", "Enabled", true, "Is the mod enabled?"); fontSize = Config.Bind("General", "FontSize", 16, "The font size of the text"); colorAvail = Config.Bind("General", "ColorAvailable", "#FFFFFF", "The color for when an ingredient is fully available, as #RRGGBB hex."); colorMissing = Config.Bind("General", "ColorMissing", "#FFFF00", "The color for when an ingredient is partially or fully missing, as #RRGGBB hex."); fMachineAutoCrafterGosInRangeForListing = AccessTools.FieldRefAccess<List<(GameObject, Group)>>(typeof(MachineAutoCrafter), "_gosInRangeForListing"); font = Resources.GetBuiltinResource<Font>("Arial.ttf"); if (Chainloader.PluginInfos.TryGetValue(modCheatInventoryStackingGuid, out var pi)) { Logger.LogInfo("Mod " + modCheatInventoryStackingGuid + " found, accessing its range check data."); fInventoryStackingGosInRangeForListing = AccessTools.FieldRefAccess<List<(GameObject, Group)>>(pi.Instance.GetType(), "_gosInRangeForListingRef"); fInventoryStackingAutocrafterWorldObjects = AccessTools.FieldRefAccess<Dictionary<Group, List<WorldObject>>>(pi.Instance.GetType(), "autocrafterWorldObjects"); stackingRangeCheckAugment = true; } else { Logger.LogInfo("Optional mod " + modCheatInventoryStackingGuid + " not found."); } fMachineAutoCrafterWorldObjectsInRange = AccessTools.FieldRefAccess<HashSet<WorldObject>>(typeof(MachineAutoCrafter), "_worldObjectsInRange"); LibCommon.HarmonyIntegrityCheck.Check(typeof(Plugin)); Harmony.CreateAndPatchAll(typeof(Plugin)); } static void OnModConfigChanged(ConfigEntryBase _) { Destroy(parent); } static GameObject parent; static Text parentText; static RectTransform parentRectTransform; static RectTransform imageRectTransform; static Coroutine rangeCoroutine; [HarmonyPostfix] [HarmonyPatch(typeof(UiWindowGroupSelector), "Start")] static void UiWindowGroupSelector_Start(UiWindowGroupSelector __instance) { if (modEnabled.Value) { __instance.StopAllCoroutines(); } } [HarmonyPrefix] [HarmonyPatch(typeof(UiWindowGroupSelector), nameof(UiWindowGroupSelector.OnOpenAutoCrafter))] static void UiWindowGroupSelector_OnOpenAutoCrafter(UiWindowGroupSelector __instance) { if (rangeCoroutine != null) { me.StopCoroutine(rangeCoroutine); rangeCoroutine = null; } if (modEnabled.Value) { rangeCoroutine = me.StartCoroutine(GetRangeCoroutine(__instance)); } } static IEnumerator GetRangeCoroutine(UiWindowGroupSelector __instance) { for (; ; ) { yield return new WaitForSeconds(1.5f); __instance.UpdateListInRange(); } } [HarmonyPrefix] [HarmonyPatch(typeof(UiWindowGroupSelector), nameof(UiWindowGroupSelector.UpdateListInRange))] static void UiWindowGroupSelector_UpdateListInRange_Pre( LinkedGroupsProxy ____worldObjectProxy, MachineAutoCrafter ____autoCrafter) { if (stackingRangeCheckAugment && ____autoCrafter != null && modEnabled.Value) { fInventoryStackingGosInRangeForListing() = []; var linkedGroups = ____worldObjectProxy.GetLinkedGroups(); var dict = fInventoryStackingAutocrafterWorldObjects(); dict.Clear(); if (linkedGroups != null && linkedGroups.Count != 0) { var recipe = linkedGroups[0].GetRecipe().GetIngredientsGroupInRecipe(); foreach (var group in recipe) { dict.TryAdd(group, new(10)); } } } } [HarmonyPostfix] [HarmonyPatch(typeof(UiWindowGroupSelector), "UpdateGroupSelectorDisplay")] static void UiWindowGroupSelector_UpdateGroupSelectorDisplay(UiWindowGroupSelector __instance) { if (modEnabled.Value) { __instance.UpdateListInRange(); } } [HarmonyPostfix] [HarmonyPatch(typeof(UiWindowGroupSelector), nameof(UiWindowGroupSelector.UpdateListInRange))] static void UiWindowGroupSelector_UpdateListInRange( MachineAutoCrafter ____autoCrafter, Image ___loadingAutoCrafterImage, LinkedGroupsProxy ____worldObjectProxy) { if (____autoCrafter == null || !modEnabled.Value) { return; } if (parent == null) { parent = new GameObject("UIShowAutoCrafterRecipe"); parent.transform.SetParent(___loadingAutoCrafterImage.transform.parent, false); parentText = parent.AddComponent<Text>(); parentText.fontSize = fontSize.Value; parentText.font = font; parentText.alignment = TextAnchor.MiddleLeft; parentText.horizontalOverflow = HorizontalWrapMode.Overflow; parentText.verticalOverflow = VerticalWrapMode.Overflow; parentText.color = Color.white; parentText.supportRichText = true; parentRectTransform = parent.GetComponent<RectTransform>(); imageRectTransform = ___loadingAutoCrafterImage.GetComponent<RectTransform>(); } var inRange = fMachineAutoCrafterWorldObjectsInRange(); if (stackingRangeCheckAugment) { inRange.Clear(); var dict = fInventoryStackingAutocrafterWorldObjects(); foreach (var list in dict.Values) { foreach (var worldObject in list) { inRange.Add(worldObject); } } dict.Clear(); fInventoryStackingGosInRangeForListing() = null; } var inRangeCounts = new Dictionary<Group, int>(); foreach (var objGroup in inRange) { var gr = objGroup.GetGroup(); inRangeCounts.TryGetValue(gr, out var c); inRangeCounts[gr] = c + 1; } var linkedGroups = ____worldObjectProxy.GetLinkedGroups(); var linkedGroupCounts = new Dictionary<Group, int>(); if (linkedGroups != null && linkedGroups.Count != 0) { var recipe = linkedGroups[0].GetRecipe().GetIngredientsGroupInRecipe(); foreach (var group in recipe) { linkedGroupCounts.TryGetValue(group, out var c); linkedGroupCounts[group] = c + 1; } } var sb = new StringBuilder(128); if (linkedGroupCounts.Count != 0) { // sb.Append("Recipe:\n"); foreach (var group in linkedGroupCounts) { int required = group.Value; inRangeCounts.TryGetValue(group.Key, out var available); available = Mathf.Min(available, required); sb.Append("- <color="); if (required > available) { sb.Append(colorMissing.Value); } else { sb.Append(colorAvail.Value); } sb.Append('>'); sb.Append(Readable.GetGroupName(group.Key)); sb.Append(" ( "); sb.Append(available); sb.Append(" / "); sb.Append(required); sb.Append(" )</color>"); sb.Append('\n'); } sb.Length--; } parentText.text = sb.ToString(); parentRectTransform.localPosition = imageRectTransform.localPosition + new Vector3(imageRectTransform.sizeDelta.x / 2 + 20 + parentText.preferredWidth / 2, 0, 0); parentRectTransform.sizeDelta = new Vector2(parentText.preferredWidth, parentText.preferredHeight); parent.SetActive(true); } [HarmonyPostfix] [HarmonyPatch(typeof(UiWindowGroupSelector), nameof(UiWindowGroupSelector.OnClose))] static void UiWindowGroupSelector_OnClose(UiWindowGroupSelector __instance) { if (parent != null) { parent.SetActive(false); } if (rangeCoroutine != null) { me.StopCoroutine(rangeCoroutine); rangeCoroutine = null; } } } }
1
0.748488
1
0.748488
game-dev
MEDIA
0.937153
game-dev
0.933959
1
0.933959
Goob-Station/Goob-Station
1,746
Content.Shared/Stunnable/SharedStunSystem.Visualizer.cs
using Content.Shared.Bed.Sleep; using Content.Shared.Mobs; using Robust.Shared.Serialization; namespace Content.Shared.Stunnable; public abstract partial class SharedStunSystem { public void InitializeAppearance() { SubscribeLocalEvent<StunVisualsComponent, MobStateChangedEvent>(OnStunMobStateChanged); SubscribeLocalEvent<StunVisualsComponent, SleepStateChangedEvent>(OnSleepStateChanged); } private bool GetStarsData(Entity<StunVisualsComponent, StunnedComponent?> entity) { if (!Resolve(entity, ref entity.Comp2, false)) return false; return Blocker.CanConsciouslyPerformAction(entity); } private void OnStunMobStateChanged(Entity<StunVisualsComponent> entity, ref MobStateChangedEvent args) { Appearance.SetData(entity, StunVisuals.SeeingStars, GetStarsData(entity)); } private void OnSleepStateChanged(Entity<StunVisualsComponent> entity, ref SleepStateChangedEvent args) { Appearance.SetData(entity, StunVisuals.SeeingStars, GetStarsData(entity)); } public void TrySeeingStars(Entity<AppearanceComponent?> entity) { if (!Resolve(entity, ref entity.Comp)) return; // Here so server can tell the client to do things // Don't dirty the component if we don't need to if (!Appearance.TryGetData<bool>(entity, StunVisuals.SeeingStars, out var stars, entity.Comp) && stars) return; if (!Blocker.CanConsciouslyPerformAction(entity)) return; Appearance.SetData(entity, StunVisuals.SeeingStars, true); Dirty(entity); } [Serializable, NetSerializable, Flags] public enum StunVisuals { SeeingStars, } }
1
0.945495
1
0.945495
game-dev
MEDIA
0.979244
game-dev
0.945707
1
0.945707
PotRooms/StarResonanceData
1,039
lua/ui/component/weaponhero/weapon_hero_skill_loop_item.lua
local super = require("ui.component.loopscrollrectitem") local WeaponHeroSkillLoopItem = class("WeaponHeroSkillLoopItem", super) function WeaponHeroSkillLoopItem:ctor() end function WeaponHeroSkillLoopItem:OnInit() self:AddClick(self.unit.img_bg.Btn, function() Z.EventMgr:Dispatch(Z.ConstValue.Hero.SkillSelect, self.index_, self.data_) end) self:Selected(false) end function WeaponHeroSkillLoopItem:Refresh() self.index_ = self.component.Index + 1 self.data_ = self.parent:GetDataByIndex(self.index_) self:setUI() end function WeaponHeroSkillLoopItem:setUI() local config = Z.TableMgr.GetTable("SkillTableMgr").GetRow(self.data_) self.unit.lab_name:SetVisible(false) self.unit.lab_grade:SetVisible(false) if config then self.unit.img_icon.Img:SetImage(config.Icon) end end function WeaponHeroSkillLoopItem:Selected(isSelected) self.unit.img_on:SetVisible(isSelected) end function WeaponHeroSkillLoopItem:OnReset() end function WeaponHeroSkillLoopItem:OnUnInit() end return WeaponHeroSkillLoopItem
1
0.728183
1
0.728183
game-dev
MEDIA
0.954491
game-dev
0.832236
1
0.832236
chris81605/DOL-BJXExtende_for_ML_Project
6,629
DATA/TEMP/Addon_Replace/0.4.5.3/已篩選/twee/Widgets pregnancyVar.twee
:: Widgets pregnancyVar [widget] <<widget "pregnancyVar">> <<if $pregnancyStats is undefined>> <<set $pregnancyStats to { playerChildren:0, humanChildren:0, wolfChildren:0, npcChildren:0, npcChildrenUnrelatedToPlayer:0, npcTotalBirthEvents:0, humanToysUnlocked: false, wolfToysUnlocked: false, mother: 0, aftermorningpills: 0, pregnancyTestsTaken: 0, parasiteBook: 0, parasiteDoctorEvents: 0, awareOfBirthId: {}, }>> <</if>> <<containersInit>> <<if $objectVersion.prenancyObjectRepair isnot 2>> <<prenancyObjectRepair>> <<set $objectVersion.prenancyObjectRepair to 2>> <</if>> <<if $pregnancyStats.morningSicknessGeneral is undefined>> <<set $pregnancyStats.morningSicknessGeneral to 0>> <<set $pregnancyStats.morningSicknessWaking to 0>> <<set $pregnancyStats.parasiteBook to 0>> <</if>> <<if $pregnancyStats.awareOfBirthId is undefined>> /* This will track when the player or npc is aware of a specific pregnancy 'birthid:["pc","NPCNameIndex"]' */ <<set $pregnancyStats.awareOfBirthId to {}>> <</if>> <<if $pregnancyStats.childInteractions is undefined>> <<set $pregnancyStats.childInteractions to 0>> <<set $pregnancyStats.childBreastfedInteractions to 0>> <<set $pregnancyStats.childBottlefedInteractions to 0>> <<set $pregnancyStats.childFirstWordInteractions to 0>> <<set $pregnancyStats.orphanageInteractions to 0>> <<set $pregnancyStats.orphanageMilkBottles to 0>> <<set $pregnancyStats.orphanageMilkBottlesTotal to 0>> <</if>> <<if $pregnancyStats.playerVirginBirths is undefined>> <<set $pregnancyStats.playerVirginBirths to []>> <<set $pregnancyStats.totalDaysPregnant to 0>> <<set $pregnancyStats.totalDaysPregnancyKnown to 0>> <</if>> <<if $pregnancyStats.parasiteBook is undefined>> <<set $pregnancyStats.parasiteBook to 0>> <</if>> <<if $pregnancyStats.parasiteDoctorEvents is undefined>> <<set $pregnancyStats.parasiteDoctorEvents to 0>> <</if>> <<if $pregnancyStats.talkedAboutPregnancy is undefined>> /* This will track when the player or npc has ever talked about specific pregnancy, the set should be during the pregnancy only 'birthid:["pc","NPCNameIndex"]' */ <<set $pregnancyStats.talkedAboutPregnancy to {}>> <</if>> <</widget>> <<widget "containersInit">> <<if $container is undefined>> <<set $container to { "lastLocation": null, "list":["home", "lake"], "home":{ "upgrades":{ "capacity":0, "foodStorage":0, "luxury":0 }, "name": "迷你鱼缸", "count": 0, "maxCount": 1, "daysSinceFed": 0, "maxDaysWithoutFood": 3, "creatures":{ 0: null }, "deadCreatures": 0, "visited": false, "leaveLink": "Bedroom" }, "portable":{ "creatures":[], "value":0 }, "lake":{ "upgrades":{ "capacity":0, "foodStorage":0, "luxury":0 }, "name": "水塘", "count": 0, "maxCount": 3, "daysSinceFed": 0, "maxDaysWithoutFood": 31, "creatures":{ 0: null }, "deadCreatures": 0, "visited": false, "leaveLink": "Lake Waterfall" } }>> <</if>> <<if $container.home.kylarDelay is undefined>> <<set $container.home.kylarDelay to 0>> <<set $container.home.kylarFed to false>> <<set $container.home.kylarHelp to false>> <</if>> <<if $container.farm is undefined>> <<set $container.farm to { "upgrades":{ "capacity":0, "foodStorage":0, "luxury":0 }, "name": "寄生物畜棚", "count": 0, "maxCount": 5, "daysSinceFed": 0, "maxDaysWithoutFood": 14, "creatures":{ 0: null }, "deadCreatures": 0, "visited": false, "leaveLink": "Farm Work" }>> <<set $container.list.pushUnique("farm")>> <</if>> /* 北极星模组 */ <<if $container.lakehouse is undefined>> <<set $container.lakehouse to { "upgrades":{ "capacity":0, "foodStorage":0, "luxury":0 }, "name": "迷你鱼缸", "count": 0, "maxCount": 5, "daysSinceFed": 0, "maxDaysWithoutFood": 14, "creatures":{ 0: null }, "deadCreatures": 0, "visited": false, "leaveLink": "Lake House Bedroom" }>> <<set $container.list.pushUnique("lakehouse")>> <</if>> /* 北极星 */ <<if $pregnancyStats.parasiteTypesSeen is undefined or $pregnancyStats.parasiteVariantsSeen is undefined>> <<set $pregnancyStats.parasiteTypesSeen to []>><<set $pregnancyStats.parasiteVariantsSeen to []>> <<for _i range $container.list>> <<for _o to 0; _o lt $container[_i].maxCount; _o++>> <<if $container[_i].creatures[_o] isnot undefined and $container[_i].creatures[_o] isnot null>> <<if $container[_i].creatures[_o].creature.includes("Tentacle")>> <<set $pregnancyStats.parasiteTypesSeen.pushUnique("Tentacle")>> <<elseif $container[_i].creatures[_o].creature.includes("Vine")>> <<set $pregnancyStats.parasiteTypesSeen.pushUnique("Vine")>> <<elseif $container[_i].creatures[_o].creature.includes("Slime")>> <<set $pregnancyStats.parasiteTypesSeen.pushUnique("Slime")>> <<else>> <<set $pregnancyStats.parasiteTypesSeen.pushUnique($container[_i].creatures[_o].creature)>> <</if>> <<if $container[_i].creatures[_o].creature.includes("Pale")>> <<set $pregnancyStats.parasiteVariantsSeen.pushUnique("Pale")>> <<elseif $container[_i].creatures[_o].creature.includes("Metal")>> <<set $pregnancyStats.parasiteVariantsSeen.pushUnique("Metal")>> <</if>> <<else>> <<break>> <</if>> <</for>> <</for>> <</if>> <<if $containerVine or $containerMetal or $containerPale>> <<unset $containerVine, $containerMetal, $containerPale>> <</if>> <</widget>> <<widget "prenancyObjectRepair">> <<set _pregnancy to $sexStats.anus.pregnancy>> <<if _pregnancy.type is "parasite">> <<for _i to 0; _i lt 4; _i++>> <<if _pregnancy.fetus[_i]>> <<if _pregnancy.fetus[_i].creature is undefined>> <<set _pregnancy.fetus[_i].creature to either("Tentacle","Spider","Fish","Snake","Eel")>> <</if>> <</if>> <</for>> <</if>> <<set _list to ["home", "lake", "farm", "portable"]>> <<for _i to 0; _i lt _list.length; _i++>> <<set _container to $container[_list[_i]]>> <<for _j to 0; _j lt _container.maxCount; _j++>> <<if _container.creatures[_j] isnot undefined and _container.creatures[_j] isnot null>> <<if _container.creatures[_j].creature is undefined>> <<set _container.creatures[_j].creature to either("Tentacle","Spider","Fish","Snake","Eel")>> <</if>> <</if>> <<if _container.upgrades.luxury is undefined>> <<set _container.upgrades.luxury to 0>> <</if>> <</for>> <</for>> <</widget>>
1
0.798926
1
0.798926
game-dev
MEDIA
0.943548
game-dev
0.749909
1
0.749909
hebohang/HEngine
7,258
Engine/Source/ThirdParty/bullet3/examples/Importers/ImportBsp/ImportBspExample.cpp
/* 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. */ #include "ImportBspExample.h" #include "btBulletDynamicsCommon.h" #include "LinearMath/btQuickprof.h" #define QUAKE_BSP_IMPORTING 1 #ifdef QUAKE_BSP_IMPORTING #include "BspLoader.h" #include "BspConverter.h" #endif //QUAKE_BSP_IMPORTING #include <stdio.h> //printf debugging #include "LinearMath/btAlignedObjectArray.h" #include "../CommonInterfaces/CommonRigidBodyBase.h" ///BspDemo shows the convex collision detection, by converting a Quake BSP file into convex objects and allowing interaction with boxes. class BspDemo : public CommonRigidBodyBase { public: //keep the collision shapes, for deletion/cleanup BspDemo(struct GUIHelperInterface* helper) : CommonRigidBodyBase(helper) { } virtual ~BspDemo(); virtual void initPhysics(); void initPhysics(const char* bspfilename); virtual void resetCamera() { float dist = 43; float pitch = -12; float yaw = -175; float targetPos[3] = {4, -25, -6}; m_guiHelper->resetCamera(dist, yaw, pitch, targetPos[0], targetPos[1], targetPos[2]); } }; #define CUBE_HALF_EXTENTS 1 #define EXTRA_HEIGHT -20.f ///BspToBulletConverter extends the BspConverter to convert to Bullet datastructures class BspToBulletConverter : public BspConverter { BspDemo* m_demoApp; public: BspToBulletConverter(BspDemo* demoApp) : m_demoApp(demoApp) { } virtual void addConvexVerticesCollider(btAlignedObjectArray<btVector3>& vertices, bool isEntity, const btVector3& entityTargetLocation) { ///perhaps we can do something special with entities (isEntity) ///like adding a collision Triggering (as example) if (vertices.size() > 0) { float mass = 0.f; btTransform startTransform; //can use a shift startTransform.setIdentity(); startTransform.setOrigin(btVector3(0, 0, -10.f)); //this create an internal copy of the vertices btCollisionShape* shape = new btConvexHullShape(&(vertices[0].getX()), vertices.size()); m_demoApp->m_collisionShapes.push_back(shape); //btRigidBody* body = m_demoApp->localCreateRigidBody(mass, startTransform,shape); m_demoApp->createRigidBody(mass, startTransform, shape); } } }; //////////////////////////////////// BspDemo::~BspDemo() { exitPhysics(); //will delete all default data } void BspDemo::initPhysics() { const char* bspfilename = "BspDemo.bsp"; initPhysics(bspfilename); } void BspDemo::initPhysics(const char* bspfilename) { int cameraUpAxis = 2; m_guiHelper->setUpAxis(cameraUpAxis); btVector3 grav(0, 0, 0); grav[cameraUpAxis] = -10; m_guiHelper->setUpAxis(cameraUpAxis); //_cameraUp = btVector3(0,0,1); //_forwardAxis = 1; //etCameraDistance(22.f); ///Setup a Physics Simulation Environment m_collisionConfiguration = new btDefaultCollisionConfiguration(); // btCollisionShape* groundShape = new btBoxShape(btVector3(50,3,50)); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); btVector3 worldMin(-1000, -1000, -1000); btVector3 worldMax(1000, 1000, 1000); m_broadphase = new btDbvtBroadphase(); //m_broadphase = new btAxisSweep3(worldMin,worldMax); //btOverlappingPairCache* broadphase = new btSimpleBroadphase(); m_solver = new btSequentialImpulseConstraintSolver(); //ConstraintSolver* solver = new OdeConstraintSolver; m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration); m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld); m_dynamicsWorld->setGravity(grav); #ifdef QUAKE_BSP_IMPORTING void* memoryBuffer = 0; const char* filename = "BspDemo.bsp"; const char* prefix[] = {"./", "./data/", "../data/", "../../data/", "../../../data/", "../../../../data/"}; int numPrefixes = sizeof(prefix) / sizeof(const char*); char relativeFileName[1024]; FILE* file = 0; for (int i = 0; i < numPrefixes; i++) { sprintf(relativeFileName, "%s%s", prefix[i], filename); file = fopen(relativeFileName, "r"); if (file) break; } if (file) { BspLoader bspLoader; int size = 0; if (fseek(file, 0, SEEK_END) || (size = ftell(file)) == EOF || fseek(file, 0, SEEK_SET)) { /* File operations denied? ok, just close and return failure */ printf("Error: cannot get filesize from %s\n", bspfilename); } else { //how to detect file size? memoryBuffer = malloc(size + 1); fread(memoryBuffer, 1, size, file); bspLoader.loadBSPFile(memoryBuffer); BspToBulletConverter bsp2bullet(this); float bspScaling = 0.1f; bsp2bullet.convertBsp(bspLoader, bspScaling); } fclose(file); } #endif m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld); } //some code that de-mangles the windows filename passed in as argument char cleaned_filename[512]; char* getLastFileName() { return cleaned_filename; } char* makeExeToBspFilename(const char* lpCmdLine) { // We might get a windows-style path on the command line, this can mess up the DOM which expects // all paths to be URI's. This block of code does some conversion to try and make the input // compliant without breaking the ability to accept a properly formatted URI. Right now this only // displays the first filename const char* in = lpCmdLine; char* out = cleaned_filename; *out = '\0'; // If the first character is a ", skip it (filenames with spaces in them are quoted) if (*in == '\"') { in++; } int i; for (i = 0; i < 512; i++) { //if we get '.' we stop as well, unless it's the first character. Then we add .bsp as extension // If we hit a null or a quote, stop copying. This will get just the first filename. if (i && (in[0] == '.') && (in[1] == 'e') && (in[2] == 'x') && (in[3] == 'e')) break; // If we hit a null or a quote, stop copying. This will get just the first filename. if (*in == '\0' || *in == '\"') break; // Copy while swapping backslashes for forward ones if (*in == '\\') { *out = '/'; } else { *out = *in; } in++; out++; } *(out++) = '.'; *(out++) = 'b'; *(out++) = 's'; *(out++) = 'p'; *(out++) = 0; return cleaned_filename; } CommonExampleInterface* ImportBspCreateFunc(struct CommonExampleOptions& options) { BspDemo* demo = new BspDemo(options.m_guiHelper); demo->initPhysics("BspDemo.bsp"); return demo; } /* static DemoApplication* Create() { BspDemo* demo = new BspDemo; demo->myinit(); demo->initPhysics("BspDemo.bsp"); return demo; } */
1
0.886029
1
0.886029
game-dev
MEDIA
0.935024
game-dev
0.957858
1
0.957858
OpenCL/GEGL-OpenCL
6,292
gegl/buffer/gegl-tile-handler.c
/* This file is part of GEGL. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. * * Copyright 2006,2007 Øyvind Kolås <pippin@gimp.org> */ #include "config.h" #include <string.h> #include <glib-object.h> #include "gegl-buffer-types.h" #include "gegl-tile-handler-cache.h" #include "gegl-tile-handler-private.h" #include "gegl-tile-storage.h" #include "gegl-buffer-private.h" struct _GeglTileHandlerPrivate { GeglTileStorage *tile_storage; GeglTileHandlerCache *cache; }; G_DEFINE_TYPE (GeglTileHandler, gegl_tile_handler, GEGL_TYPE_TILE_SOURCE) enum { PROP0, PROP_SOURCE }; gboolean gegl_tile_storage_cached_release (GeglTileStorage *storage); static void gegl_tile_handler_dispose (GObject *object) { GeglTileHandler *handler = GEGL_TILE_HANDLER (object); if (handler->source) { g_object_unref (handler->source); handler->source = NULL; } G_OBJECT_CLASS (gegl_tile_handler_parent_class)->dispose (object); } static gpointer gegl_tile_handler_command (GeglTileSource *gegl_tile_source, GeglTileCommand command, gint x, gint y, gint z, gpointer data) { GeglTileHandler *handler = (GeglTileHandler*)gegl_tile_source; return gegl_tile_handler_source_command (handler, command, x, y, z, data); } static void gegl_tile_handler_get_property (GObject *gobject, guint property_id, GValue *value, GParamSpec *pspec) { GeglTileHandler *handler = GEGL_TILE_HANDLER (gobject); switch (property_id) { case PROP_SOURCE: g_value_set_object (value, handler->source); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (gobject, property_id, pspec); break; } } static void gegl_tile_handler_set_property (GObject *gobject, guint property_id, const GValue *value, GParamSpec *pspec) { GeglTileHandler *handler = GEGL_TILE_HANDLER (gobject); switch (property_id) { case PROP_SOURCE: gegl_tile_handler_set_source (handler, g_value_get_object (value)); return; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (gobject, property_id, pspec); break; } } static void gegl_tile_handler_class_init (GeglTileHandlerClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); gobject_class->set_property = gegl_tile_handler_set_property; gobject_class->get_property = gegl_tile_handler_get_property; gobject_class->dispose = gegl_tile_handler_dispose; g_object_class_install_property (gobject_class, PROP_SOURCE, g_param_spec_object ("source", "GeglBuffer", "The tilestore to be a facade for", G_TYPE_OBJECT, G_PARAM_READWRITE | G_PARAM_CONSTRUCT)); g_type_class_add_private (gobject_class, sizeof (GeglTileHandlerPrivate)); } static void gegl_tile_handler_init (GeglTileHandler *self) { ((GeglTileSource *) self)->command = gegl_tile_handler_command; self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GEGL_TYPE_TILE_HANDLER, GeglTileHandlerPrivate); } void gegl_tile_handler_set_source (GeglTileHandler *handler, GeglTileSource *source) { if (source != handler->source) { if (handler->source) g_object_unref (handler->source); handler->source = source; if (handler->source) g_object_ref (handler->source); } } void _gegl_tile_handler_set_tile_storage (GeglTileHandler *handler, GeglTileStorage *tile_storage) { handler->priv->tile_storage = tile_storage; } void _gegl_tile_handler_set_cache (GeglTileHandler *handler, GeglTileHandlerCache *cache) { handler->priv->cache = cache; } GeglTileStorage * _gegl_tile_handler_get_tile_storage (GeglTileHandler *handler) { return handler->priv->tile_storage; } GeglTileHandlerCache * _gegl_tile_handler_get_cache (GeglTileHandler *handler) { return handler->priv->cache; } GeglTile * gegl_tile_handler_create_tile (GeglTileHandler *handler, gint x, gint y, gint z) { GeglTile *tile; tile = gegl_tile_new (handler->priv->tile_storage->tile_size); tile->tile_storage = handler->priv->tile_storage; tile->x = x; tile->y = y; tile->z = z; if (handler->priv->cache) gegl_tile_handler_cache_insert (handler->priv->cache, tile, x, y, z); return tile; } GeglTile * gegl_tile_handler_dup_tile (GeglTileHandler *handler, GeglTile *tile, gint x, gint y, gint z) { tile = gegl_tile_dup (tile); tile->x = x; tile->y = y; tile->z = z; if (handler->priv->cache) gegl_tile_handler_cache_insert (handler->priv->cache, tile, x, y, z); return tile; }
1
0.908376
1
0.908376
game-dev
MEDIA
0.66229
game-dev
0.74738
1
0.74738
CentecNetworks/Lantern
6,632
platform/linux/drivers/staging/iio/accel/accel.h
#include "../sysfs.h" /* Accelerometer types of attribute */ #define IIO_DEV_ATTR_ACCEL_X_OFFSET(_mode, _show, _store, _addr) \ IIO_DEVICE_ATTR(accel_x_offset, _mode, _show, _store, _addr) #define IIO_DEV_ATTR_ACCEL_Y_OFFSET(_mode, _show, _store, _addr) \ IIO_DEVICE_ATTR(accel_y_offset, _mode, _show, _store, _addr) #define IIO_DEV_ATTR_ACCEL_Z_OFFSET(_mode, _show, _store, _addr) \ IIO_DEVICE_ATTR(accel_z_offset, _mode, _show, _store, _addr) #define IIO_DEV_ATTR_ACCEL_X_GAIN(_mode, _show, _store, _addr) \ IIO_DEVICE_ATTR(accel_x_gain, _mode, _show, _store, _addr) #define IIO_DEV_ATTR_ACCEL_Y_GAIN(_mode, _show, _store, _addr) \ IIO_DEVICE_ATTR(accel_y_gain, _mode, _show, _store, _addr) #define IIO_DEV_ATTR_ACCEL_Z_GAIN(_mode, _show, _store, _addr) \ IIO_DEVICE_ATTR(accel_z_gain, _mode, _show, _store, _addr) #define IIO_DEV_ATTR_ACCEL_X(_show, _addr) \ IIO_DEVICE_ATTR(accel_x, S_IRUGO, _show, NULL, _addr) #define IIO_DEV_ATTR_ACCEL_Y(_show, _addr) \ IIO_DEVICE_ATTR(accel_y, S_IRUGO, _show, NULL, _addr) #define IIO_DEV_ATTR_ACCEL_Z(_show, _addr) \ IIO_DEVICE_ATTR(accel_z, S_IRUGO, _show, NULL, _addr) /* Thresholds are somewhat chip dependent - may need quite a few defs here */ /* For unified thesholds (shared across all directions */ /** * IIO_DEV_ATTR_ACCEL_THRESH: unified threshold * @_mode: read/write * @_show: read detector threshold value * @_store: write detector theshold value * @_addr: driver specific data, typically a register address * * This one is for cases where as single threshold covers all directions **/ #define IIO_DEV_ATTR_ACCEL_THRESH(_mode, _show, _store, _addr) \ IIO_DEVICE_ATTR(thresh, _mode, _show, _store, _addr) /** * IIO_DEV_ATTR_ACCEL_THRESH_X: independant direction threshold, x axis * @_mode: readable / writable * @_show: read x axis detector theshold value * @_store: write x axis detector threshold value * @_addr: device driver dependant, typically a register address **/ #define IIO_DEV_ATTR_ACCEL_THRESH_X(_mode, _show, _store, _addr) \ IIO_DEVICE_ATTR(thresh_accel_x, _mode, _show, _store, _addr) #define IIO_DEV_ATTR_ACCEL_THRESH_Y(_mode, _show, _store, _addr) \ IIO_DEVICE_ATTR(thresh_accel_y, _mode, _show, _store, _addr) #define IIO_DEV_ATTR_ACCEL_THRESH_Z(_mode, _show, _store, _addr) \ IIO_DEVICE_ATTR(thresh_accel_z, _mode, _show, _store, _addr) /** * IIO_EVENT_ATTR_ACCEL_X_HIGH: threshold event, x acceleration * @_show: read x acceleration high threshold * @_store: write x acceleration high threshold * @_mask: device dependant, typically a bit mask * @_handler: the iio_handler associated with this attribute **/ #define IIO_EVENT_ATTR_ACCEL_X_HIGH(_show, _store, _mask, _handler) \ IIO_EVENT_ATTR(accel_x_high, _show, _store, _mask, _handler) /** * IIO_EVENT_ATTR_ACCEL_X_HIGH_SH: threshold event, x accel high, shared handler * @_evlist: event list used to share the handler * @_show: attribute read * @_store: attribute write * @_mask: driver specific data, typically a bit mask **/ #define IIO_EVENT_ATTR_ACCEL_X_HIGH_SH(_evlist, _show, _store, _mask) \ IIO_EVENT_ATTR_SH(accel_x_high, _evlist, _show, _store, _mask) /** * IIO_EVENT_CODE_ACCEL_X_HIGH - event code for x axis high accel threshold **/ #define IIO_EVENT_CODE_ACCEL_X_HIGH IIO_EVENT_CODE_ACCEL_BASE #define IIO_EVENT_ATTR_ACCEL_Y_HIGH(_show, _store, _mask, _handler) \ IIO_EVENT_ATTR(accel_y_high, _show, _store, _mask, _handler) #define IIO_EVENT_ATTR_ACCEL_Y_HIGH_SH(_evlist, _show, _store, _mask) \ IIO_EVENT_ATTR_SH(accel_y_high, _evlist, _show, _store, _mask) #define IIO_EVENT_CODE_ACCEL_Y_HIGH (IIO_EVENT_CODE_ACCEL_BASE + 1) #define IIO_EVENT_ATTR_ACCEL_Z_HIGH(_show, _store, _mask, _handler) \ IIO_EVENT_ATTR(accel_z_high, _show, _store, _mask, _handler) #define IIO_EVENT_ATTR_ACCEL_Z_HIGH_SH(_evlist, _show, _store, _mask) \ IIO_EVENT_ATTR_SH(accel_z_high, _evlist, _show, _store, _mask) #define IIO_EVENT_CODE_ACCEL_Z_HIGH (IIO_EVENT_CODE_ACCEL_BASE + 2) #define IIO_EVENT_ATTR_ACCEL_X_LOW(_show, _store, _mask, _handler) \ IIO_EVENT_ATTR(accel_x_low, _show, _store, _mask, _handler) #define IIO_EVENT_ATTR_ACCEL_X_LOW_SH(_evlist, _show, _store, _mask) \ IIO_EVENT_ATTR_SH(accel_x_low, _evlist, _show, _store, _mask) #define IIO_EVENT_CODE_ACCEL_X_LOW (IIO_EVENT_CODE_ACCEL_BASE + 3) #define IIO_EVENT_ATTR_ACCEL_Y_LOW(_show, _store, _mask, _handler) \ IIO_EVENT_ATTR(accel_y_low, _show, _store, _mask, _handler) #define IIO_EVENT_ATTR_ACCEL_Y_LOW_SH(_evlist, _show, _store, _mask)\ IIO_EVENT_ATTR_SH(accel_y_low, _evlist, _show, _store, _mask) #define IIO_EVENT_CODE_ACCEL_Y_LOW (IIO_EVENT_CODE_ACCEL_BASE + 4) #define IIO_EVENT_ATTR_ACCEL_Z_LOW(_show, _store, _mask, _handler) \ IIO_EVENT_ATTR(accel_z_low, _show, _store, _mask, _handler) #define IIO_EVENT_ATTR_ACCEL_Z_LOW_SH(_evlist, _show, _store, _mask) \ IIO_EVENT_ATTR_SH(accel_z_low, _evlist, _show, _store, _mask) #define IIO_EVENT_CODE_ACCEL_Z_LOW (IIO_EVENT_CODE_ACCEL_BASE + 5) #define IIO_EVENT_ATTR_FREE_FALL_DETECT(_show, _store, _mask, _handler) \ IIO_EVENT_ATTR(free_fall, _show, _store, _mask, _handler) #define IIO_EVENT_ATTR_FREE_FALL_DETECT_SH(_evlist, _show, _store, _mask) \ IIO_EVENT_ATTR_SH(free_fall, _evlist, _show, _store, _mask) #define IIO_EVENT_CODE_FREE_FALL (IIO_EVENT_CODE_ACCEL_BASE + 6) #define IIO_EVENT_ATTR_ACCEL_X_ROC_HIGH_SH(_evlist, _show, _store, _mask) \ IIO_EVENT_ATTR_SH(accel_x_roc_high, _evlist, _show, _store, _mask) #define IIO_EVENT_CODE_ACCEL_X_ROC_HIGH (IIO_EVENT_CODE_ACCEL_BASE + 10) #define IIO_EVENT_ATTR_ACCEL_X_ROC_LOW_SH(_evlist, _show, _store, _mask) \ IIO_EVENT_ATTR_SH(accel_x_roc_low, _evlist, _show, _store, _mask) #define IIO_EVENT_CODE_ACCEL_X_ROC_LOW (IIO_EVENT_CODE_ACCEL_BASE + 11) #define IIO_EVENT_ATTR_ACCEL_Y_ROC_HIGH_SH(_evlist, _show, _store, _mask) \ IIO_EVENT_ATTR_SH(accel_y_roc_high, _evlist, _show, _store, _mask) #define IIO_EVENT_CODE_ACCEL_Y_ROC_HIGH (IIO_EVENT_CODE_ACCEL_BASE + 12) #define IIO_EVENT_ATTR_ACCEL_Y_ROC_LOW_SH(_evlist, _show, _store, _mask) \ IIO_EVENT_ATTR_SH(accel_y_roc_low, _evlist, _show, _store, _mask) #define IIO_EVENT_CODE_ACCEL_Y_ROC_LOW (IIO_EVENT_CODE_ACCEL_BASE + 13) #define IIO_EVENT_ATTR_ACCEL_Z_ROC_HIGH_SH(_evlist, _show, _store, _mask) \ IIO_EVENT_ATTR_SH(accel_z_roc_high, _evlist, _show, _store, _mask) #define IIO_EVENT_CODE_ACCEL_Z_ROC_HIGH (IIO_EVENT_CODE_ACCEL_BASE + 14) #define IIO_EVENT_ATTR_ACCEL_Z_ROC_LOW_SH(_evlist, _show, _store, _mask) \ IIO_EVENT_ATTR_SH(accel_z_roc_low, _evlist, _show, _store, _mask) #define IIO_EVENT_CODE_ACCEL_Z_ROC_LOW (IIO_EVENT_CODE_ACCEL_BASE + 15)
1
0.792894
1
0.792894
game-dev
MEDIA
0.605465
game-dev
0.822145
1
0.822145
Ragebones/StormCore
5,547
src/server/game/AI/ScriptedAI/ScriptedEscortAI.h
/* * Copyright (C) 2014-2017 StormCore * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SC_ESCORTAI_H #define SC_ESCORTAI_H #include "ScriptSystem.h" #define DEFAULT_MAX_PLAYER_DISTANCE 50 struct Escort_Waypoint { Escort_Waypoint(uint32 _id, float _x, float _y, float _z, uint32 _w) { id = _id; x = _x; y = _y; z = _z; WaitTimeMs = _w; } uint32 id; float x; float y; float z; uint32 WaitTimeMs; }; enum eEscortState { STATE_ESCORT_NONE = 0x000, //nothing in progress STATE_ESCORT_ESCORTING = 0x001, //escort are in progress STATE_ESCORT_RETURNING = 0x002, //escort is returning after being in combat STATE_ESCORT_PAUSED = 0x004 //will not proceed with waypoints before state is removed }; struct TC_GAME_API npc_escortAI : public ScriptedAI { public: explicit npc_escortAI(Creature* creature); ~npc_escortAI() { } // CreatureAI functions void AttackStart(Unit* who) override; void MoveInLineOfSight(Unit* who) override; void JustDied(Unit*) override; void JustRespawned() override; void ReturnToLastPoint(); void EnterEvadeMode(EvadeReason /*why*/ = EVADE_REASON_OTHER) override; void UpdateAI(uint32 diff) override; // the "internal" update, calls UpdateEscortAI() virtual void UpdateEscortAI(uint32 diff); // used when it's needed to add code in update (abilities, scripted events, etc) void MovementInform(uint32, uint32) override; // EscortAI functions void AddWaypoint(uint32 id, float x, float y, float z, uint32 waitTime = 0); // waitTime is in ms //this will set the current position to x/y/z/o, and the current WP to pointId. bool SetNextWaypoint(uint32 pointId, float x, float y, float z, float orientation); //this will set the current position to WP start position (if setPosition == true), //and the current WP to pointId bool SetNextWaypoint(uint32 pointId, bool setPosition = true, bool resetWaypointsOnFail = true); bool GetWaypointPosition(uint32 pointId, float& x, float& y, float& z); virtual void WaypointReached(uint32 pointId) = 0; virtual void WaypointStart(uint32 /*pointId*/) { } void Start(bool isActiveAttacker = true, bool run = false, ObjectGuid playerGUID = ObjectGuid::Empty, Quest const* quest = NULL, bool instantRespawn = false, bool canLoopPath = false, bool resetWaypoints = true); void SetRun(bool on = true); void SetEscortPaused(bool on); bool HasEscortState(uint32 escortState) { return (m_uiEscortState & escortState) != 0; } virtual bool IsEscorted() const override { return (m_uiEscortState & STATE_ESCORT_ESCORTING); } void SetMaxPlayerDistance(float newMax) { MaxPlayerDistance = newMax; } float GetMaxPlayerDistance() const { return MaxPlayerDistance; } void SetDespawnAtEnd(bool despawn) { DespawnAtEnd = despawn; } void SetDespawnAtFar(bool despawn) { DespawnAtFar = despawn; } bool GetAttack() const { return m_bIsActiveAttacker; }//used in EnterEvadeMode override void SetCanAttack(bool attack) { m_bIsActiveAttacker = attack; } ObjectGuid GetEventStarterGUID() const { return m_uiPlayerGUID; } protected: Player* GetPlayerForEscort() { return ObjectAccessor::GetPlayer(*me, m_uiPlayerGUID); } private: bool AssistPlayerInCombatAgainst(Unit* who); bool IsPlayerOrGroupInRange(); void FillPointMovementListForCreature(); void AddEscortState(uint32 escortState) { m_uiEscortState |= escortState; } void RemoveEscortState(uint32 escortState) { m_uiEscortState &= ~escortState; } ObjectGuid m_uiPlayerGUID; uint32 m_uiWPWaitTimer; uint32 m_uiPlayerCheckTimer; uint32 m_uiEscortState; float MaxPlayerDistance; Quest const* m_pQuestForEscort; //generally passed in Start() when regular escort script. std::list<Escort_Waypoint> WaypointList; std::list<Escort_Waypoint>::iterator CurrentWP; bool m_bIsActiveAttacker; //obsolete, determined by faction. bool m_bIsRunning; //all creatures are walking by default (has flag MOVEMENTFLAG_WALK) bool m_bCanInstantRespawn; //if creature should respawn instantly after escort over (if not, database respawntime are used) bool m_bCanReturnToStart; //if creature can walk same path (loop) without despawn. Not for regular escort quests. bool DespawnAtEnd; bool DespawnAtFar; bool ScriptWP; bool HasImmuneToNPCFlags; }; #endif
1
0.891351
1
0.891351
game-dev
MEDIA
0.918324
game-dev
0.59689
1
0.59689
RedPandaProjects/UnrealEngine
2,722
Source/Engine/Classes/Carcass.uc
//============================================================================= // Carcass. //============================================================================= class Carcass expands Decoration intrinsic; // Sprite. #exec Texture Import File=Textures\Corpse.pcx Name=S_Corpse Mips=Off Flags=2 // Variables. var bool bPlayerCarcass; var() byte flies; var() byte rats; var() bool bReducedHeight; var bool bDecorative; var bool bSlidingCarcass; var int CumulativeDamage; replication { // Functions server can call. reliable if( Role==ROLE_Authority ) ClientExtraChunks; } var Pawn Bugs; function CreateReplacement() { if (Bugs != None) Bugs.Destroy(); } function Destroyed() { local Actor A; if (Bugs != None) Bugs.Destroy(); Super.Destroyed(); } function Initfor(actor Other) { //implemented in subclasses } function ChunkUp(int Damage) { destroy(); } function ClientExtraChunks() { } function TakeDamage( int Damage, Pawn instigatedBy, Vector hitlocation, Vector momentum, name damageType) { if ( !bDecorative ) { bBobbing = false; SetPhysics(PHYS_Falling); } if ( (Physics == PHYS_None) && (Momentum.Z < 0) ) Momentum.Z *= -1; Velocity += 3 * momentum/(Mass + 200); if ( DamageType == 'shot' ) Damage *= 0.4; CumulativeDamage += Damage; if ( (((Damage > 30) || !IsAnimating()) && (CumulativeDamage > 0.8 * Mass)) || (Damage > 0.4 * Mass) || ((Velocity.Z > 150) && !IsAnimating()) ) ChunkUp(Damage); if ( bDecorative ) Velocity = vect(0,0,0); } auto state Dying { ignores TakeDamage; Begin: Sleep(0.2); GotoState('Dead'); } state Dead { function Timer() { local bool bSeen; local Pawn aPawn; local float dist; if ( Region.Zone.NumCarcasses <= Region.Zone.MaxCarcasses ) { if ( !PlayerCanSeeMe() ) Destroy(); else SetTimer(2.0, false); } else Destroy(); } function AddFliesAndRats() { } function CheckZoneCarcasses() { } function BeginState() { if ( bDecorative ) lifespan = 0.0; else SetTimer(18.0, false); } Begin: FinishAnim(); Sleep(5.0); CheckZoneCarcasses(); Sleep(7.0); if ( !bDecorative && !bHidden && !Region.Zone.bWaterZone && !Region.Zone.bPainZone ) AddFliesAndRats(); } defaultproperties { bDecorative=True bStatic=False DrawType=DT_Mesh Texture=S_Corpse bMeshCurvy=True bStasis=False CollisionRadius=+00018.000000 CollisionHeight=+00004.000000 bCollideActors=True bCollideWorld=True bProjTarget=True Physics=PHYS_Falling Mass=+00180.000000 Buoyancy=+00105.000000 LifeSpan=+00180.000000 AnimSequence=Dead AnimFrame=+00000.900000 }
1
0.962048
1
0.962048
game-dev
MEDIA
0.993958
game-dev
0.994166
1
0.994166
basketoengine/Basketo
14,657
src/ecs/systems/StateMachineSystem.cpp
#include "StateMachineSystem.h" #include <algorithm> StateMachineSystem::StateMachineSystem() { std::cout << "[StateMachineSystem] Initialized" << std::endl; } void StateMachineSystem::update(ComponentManager* componentManager, float deltaTime) { frameStartTime = std::chrono::high_resolution_clock::now(); // Reset frame metrics metrics.stateTransitions = 0; metrics.stateUpdates = 0; metrics.eventTriggeredTransitions = 0; metrics.timerTriggeredTransitions = 0; metrics.totalStateMachines = 0; metrics.activeStateMachines = 0; // Process all state machines for (auto const& entity : entities) { if (!componentManager->hasComponent<StateMachineComponent>(entity)) continue; metrics.totalStateMachines++; auto& stateMachine = componentManager->getComponent<StateMachineComponent>(entity); if (!stateMachine.enabled) continue; metrics.activeStateMachines++; // Initialize state machine if needed if (stateMachine.currentState.empty() && !stateMachine.initialState.empty()) { stateMachine.initialize(); if (!stateMachine.currentState.empty()) { executeStateEnter(entity, *stateMachine.getCurrentState(), componentManager); sendStateEvent(entity, stateMachine.currentState, EventType::STATE_ENTER, componentManager); } } // Update the state machine updateStateMachine(entity, componentManager, deltaTime); // Reset frame counters stateMachine.resetFrameCounters(); } // Update performance metrics auto endTime = std::chrono::high_resolution_clock::now(); metrics.processingTime = std::chrono::duration<float, std::milli>(endTime - frameStartTime).count(); } void StateMachineSystem::updateStateMachine(Entity entity, ComponentManager* componentManager, float deltaTime) { auto& stateMachine = componentManager->getComponent<StateMachineComponent>(entity); // Update current state time stateMachine.currentStateTime += deltaTime; // Handle transition delay if (stateMachine.inTransition) { stateMachine.transitionDelay -= deltaTime; if (stateMachine.transitionDelay <= 0.0f) { stateMachine.inTransition = false; } return; // Don't process transitions or state updates during transition delay } // Process state transitions processStateTransitions(entity, componentManager, deltaTime); // Update current state const State* currentState = stateMachine.getCurrentState(); if (currentState) { executeStateUpdate(entity, *currentState, componentManager, deltaTime); updateAnimationForState(entity, *currentState, componentManager); metrics.stateUpdates++; stateMachine.stateUpdatesThisFrame++; } } void StateMachineSystem::processStateTransitions(Entity entity, ComponentManager* componentManager, float deltaTime) { auto& stateMachine = componentManager->getComponent<StateMachineComponent>(entity); if (stateMachine.currentState.empty()) return; int transitionsProcessed = 0; // Check all transitions from current state for (const auto& transition : stateMachine.transitions) { if (transitionsProcessed >= maxTransitionsPerFrame) break; // Only check transitions from current state if (transition.fromState != stateMachine.currentState) continue; // Check if transition condition is met if (checkTransitionCondition(transition, entity, componentManager, deltaTime)) { // Check minimum state duration const State* currentState = stateMachine.getCurrentState(); if (currentState && stateMachine.currentStateTime < currentState->minDuration) { continue; // Haven't been in state long enough } // Execute the transition executeStateTransition(entity, transition.fromState, transition.toState, componentManager); // Set transition delay if specified if (transition.delay > 0.0f) { stateMachine.inTransition = true; stateMachine.transitionDelay = transition.delay; } transitionsProcessed++; metrics.stateTransitions++; stateMachine.transitionsThisFrame++; // Only process one transition per frame per entity break; } } } bool StateMachineSystem::checkTransitionCondition(const StateTransition& transition, Entity entity, ComponentManager* componentManager, float deltaTime) { switch (transition.condition) { case TransitionCondition::ALWAYS: return true; case TransitionCondition::ON_EVENT: return checkEventCondition(transition, entity, componentManager); case TransitionCondition::ON_TIMER: return checkTimerCondition(transition, entity, componentManager, deltaTime); case TransitionCondition::ON_PARAMETER: return checkParameterCondition(transition, entity, componentManager); case TransitionCondition::ON_SCRIPT_CONDITION: return checkScriptCondition(transition, entity, componentManager); default: return false; } } bool StateMachineSystem::checkEventCondition(const StateTransition& transition, Entity entity, ComponentManager* componentManager) { if (!componentManager->hasComponent<EventComponent>(entity)) return false; auto& eventComp = componentManager->getComponent<EventComponent>(entity); // Check recent events in history for (const auto& event : eventComp.eventHistory) { if (event.type == transition.eventType || (event.type == EventType::CUSTOM_EVENT && event.eventName == transition.eventName)) { // Check if event is recent enough (within last few frames) float currentTime = std::chrono::duration<float>( std::chrono::steady_clock::now().time_since_epoch()).count(); if (currentTime - event.timestamp < 0.1f) { // 100ms window metrics.eventTriggeredTransitions++; return true; } } } return false; } bool StateMachineSystem::checkTimerCondition(const StateTransition& transition, Entity entity, ComponentManager* componentManager, float deltaTime) { auto& stateMachine = componentManager->getComponent<StateMachineComponent>(entity); if (stateMachine.currentStateTime >= transition.timerDuration) { metrics.timerTriggeredTransitions++; return true; } return false; } bool StateMachineSystem::checkParameterCondition(const StateTransition& transition, Entity entity, ComponentManager* componentManager) { auto& stateMachine = componentManager->getComponent<StateMachineComponent>(entity); const State* currentState = stateMachine.getCurrentState(); if (!currentState) return false; std::string paramValue = currentState->getParameter(transition.parameterName); return paramValue == transition.parameterValue; } bool StateMachineSystem::checkScriptCondition(const StateTransition& transition, Entity entity, ComponentManager* componentManager) { // This would integrate with the script system to evaluate Lua conditions // For now, return false as placeholder return false; } void StateMachineSystem::executeStateTransition(Entity entity, const std::string& fromState, const std::string& toState, ComponentManager* componentManager) { auto& stateMachine = componentManager->getComponent<StateMachineComponent>(entity); if (!isValidState(stateMachine, toState)) { if (debugLogging) { std::cerr << "[StateMachineSystem] Invalid state transition to: " << toState << std::endl; } return; } // Execute exit callback for current state const State* currentState = stateMachine.getCurrentState(); if (currentState) { executeStateExit(entity, *currentState, componentManager); sendStateEvent(entity, fromState, EventType::STATE_EXIT, componentManager); } // Change state stateMachine.previousState = stateMachine.currentState; stateMachine.currentState = toState; stateMachine.currentStateTime = 0.0f; stateMachine.addToHistory(toState); // Execute enter callback for new state const State* newState = stateMachine.getCurrentState(); if (newState) { executeStateEnter(entity, *newState, componentManager); sendStateEvent(entity, toState, EventType::STATE_ENTER, componentManager); } if (debugLogging) { logStateChange(entity, fromState, toState); } } void StateMachineSystem::executeStateEnter(Entity entity, const State& state, ComponentManager* componentManager) { if (state.onEnter) { try { state.onEnter(entity); } catch (const std::exception& e) { std::cerr << "[StateMachineSystem] Error in state enter callback: " << e.what() << std::endl; } } // Play enter sound if (!state.enterSoundId.empty()) { playAudioForState(entity, state, "enter", componentManager); } } void StateMachineSystem::executeStateUpdate(Entity entity, const State& state, ComponentManager* componentManager, float deltaTime) { if (state.onUpdate) { try { state.onUpdate(entity, deltaTime); } catch (const std::exception& e) { std::cerr << "[StateMachineSystem] Error in state update callback: " << e.what() << std::endl; } } } void StateMachineSystem::executeStateExit(Entity entity, const State& state, ComponentManager* componentManager) { if (state.onExit) { try { state.onExit(entity); } catch (const std::exception& e) { std::cerr << "[StateMachineSystem] Error in state exit callback: " << e.what() << std::endl; } } // Play exit sound if (!state.exitSoundId.empty()) { playAudioForState(entity, state, "exit", componentManager); } } void StateMachineSystem::updateAnimationForState(Entity entity, const State& state, ComponentManager* componentManager) { if (state.animationName.empty()) return; if (componentManager->hasComponent<AnimationComponent>(entity)) { auto& animComp = componentManager->getComponent<AnimationComponent>(entity); // Only change animation if it's different if (animComp.currentAnimationName != state.animationName) { animComp.play(state.animationName, true); // Force restart the animation } } } void StateMachineSystem::playAudioForState(Entity entity, const State& state, const std::string& audioType, ComponentManager* componentManager) { if (!componentManager->hasComponent<AudioComponent>(entity)) return; auto& audioComp = componentManager->getComponent<AudioComponent>(entity); std::string soundId; if (audioType == "enter") soundId = state.enterSoundId; else if (audioType == "exit") soundId = state.exitSoundId; else if (audioType == "loop") soundId = state.loopSoundId; if (!soundId.empty()) { // Check if it's a SoundEffectsComponent instead if (componentManager->hasComponent<SoundEffectsComponent>(entity)) { auto& soundEffectsComp = componentManager->getComponent<SoundEffectsComponent>(entity); soundEffectsComp.playQueue.push_back(soundId); } else { // For basic AudioComponent, just set the audioId audioComp.audioId = soundId; audioComp.playOnStart = true; } } } void StateMachineSystem::sendStateEvent(Entity entity, const std::string& stateName, EventType eventType, ComponentManager* componentManager) { if (!eventSystem || !componentManager->hasComponent<EventComponent>(entity)) return; EventData event(eventType, entity, NO_ENTITY, stateName); event.setParameter("stateName", stateName); event.setParameter("entity", static_cast<int>(entity)); eventSystem->broadcastEvent(event); } void StateMachineSystem::changeState(Entity entity, const std::string& newState, ComponentManager* componentManager) { if (!componentManager->hasComponent<StateMachineComponent>(entity)) return; auto& stateMachine = componentManager->getComponent<StateMachineComponent>(entity); if (isValidState(stateMachine, newState)) { executeStateTransition(entity, stateMachine.currentState, newState, componentManager); } } void StateMachineSystem::forceStateChange(Entity entity, const std::string& newState, ComponentManager* componentManager) { // Same as changeState but bypasses transition conditions changeState(entity, newState, componentManager); } std::string StateMachineSystem::getCurrentState(Entity entity, ComponentManager* componentManager) const { if (!componentManager->hasComponent<StateMachineComponent>(entity)) return ""; const auto& stateMachine = componentManager->getComponent<StateMachineComponent>(entity); return stateMachine.currentState; } bool StateMachineSystem::isInState(Entity entity, const std::string& stateName, ComponentManager* componentManager) const { return getCurrentState(entity, componentManager) == stateName; } float StateMachineSystem::getStateTime(Entity entity, ComponentManager* componentManager) const { if (!componentManager->hasComponent<StateMachineComponent>(entity)) return 0.0f; const auto& stateMachine = componentManager->getComponent<StateMachineComponent>(entity); return stateMachine.currentStateTime; } void StateMachineSystem::logStateChange(Entity entity, const std::string& fromState, const std::string& toState) const { std::cout << "[StateMachineSystem] Entity " << entity << " transitioned from '" << fromState << "' to '" << toState << "'" << std::endl; } bool StateMachineSystem::isValidState(const StateMachineComponent& stateMachine, const std::string& stateName) const { return stateMachine.hasState(stateName); } void StateMachineSystem::resetMetrics() { metrics = PerformanceMetrics{}; }
1
0.837798
1
0.837798
game-dev
MEDIA
0.826734
game-dev
0.845666
1
0.845666
abcdabcd987/compiler2016
3,562
src/com/abcdabcd987/compiler2016/IR/Branch.java
package com.abcdabcd987.compiler2016.IR; import com.abcdabcd987.compiler2016.BackEnd.SSATransformer; import java.util.*; import java.util.function.Function; /** * Created by abcdabcd987 on 2016-04-07. */ public class Branch extends BranchInstruction { private IntValue cond; private BasicBlock then; private BasicBlock otherwise; public Branch(BasicBlock BB, IntValue cond, BasicBlock then, BasicBlock otherwise) { super(BB); this.cond = cond; this.then = then; this.otherwise = otherwise; reloadUsedRegisterCollection(); } @Override public void accept(IIRVisitor visitor) { visitor.visit(this); } @Override public VirtualRegister getDefinedRegister() { return null; } @Override protected void reloadUsedRegisterCollection() { usedRegister.clear(); if (cond instanceof Register) usedRegister.add((Register) cond); usedIntValue.clear(); usedIntValue.add(cond); } @Override public void setDefinedRegister(Register newReg) { assert false; } @Override public void setUsedRegister(Map<Register, Register> regMap) { if (cond instanceof Register) cond = regMap.get(cond); reloadUsedRegisterCollection(); } @Override public void renameDefinedRegister(Function<VirtualRegister, Integer> idSupplier) { } @Override public void renameUsedRegister(Function<VirtualRegister, Integer> idSupplier) { if (cond instanceof VirtualRegister) cond = ((VirtualRegister) cond).getSSARenamedRegister(idSupplier.apply((VirtualRegister) cond)); reloadUsedRegisterCollection(); } @Override public void replaceIntValueUse(IntValue oldValue, IntValue newValue) { if (cond == oldValue) cond = newValue; reloadUsedRegisterCollection(); } @Override public Collection<BasicBlock> getUsedBasicBlock() { return Arrays.asList(then, otherwise); } @Override public Branch copyAndRename(Map<Object, Object> renameMap) { return new Branch( (BasicBlock) renameMap.getOrDefault(curBB, curBB), (IntValue) renameMap.getOrDefault(cond, cond), (BasicBlock) renameMap.getOrDefault(then, then), (BasicBlock) renameMap.getOrDefault(otherwise, otherwise) ); } public IntValue getCond() { return cond; } public BasicBlock getThen() { return then; } public BasicBlock getElse() { return otherwise; } /** * <pre> * change from: curBB -> toBB * to: curBB -> insertedBB -> toBB * </pre> * used in ssa destruction. * @param toBB old jump destination * @return inserted split block * @see SSATransformer#removePhiInstruction() */ public BasicBlock insertSplitBlock(BasicBlock toBB) { assert (then == toBB ? 1 : 0) + (otherwise == toBB ? 1 : 0) == 1; BasicBlock target = then == toBB ? then : otherwise; BasicBlock insertedBB = new BasicBlock(curBB.getParent(), "CEP"); insertedBB.end(new Jump(insertedBB, target)); if (then == toBB) then = insertedBB; else otherwise = insertedBB; curBB.getSucc().remove(toBB); curBB.getSucc().add(insertedBB); toBB.getPred().remove(curBB); toBB.getPred().add(insertedBB); insertedBB.getPred().add(curBB); insertedBB.getSucc().add(toBB); return insertedBB; } }
1
0.862817
1
0.862817
game-dev
MEDIA
0.37299
game-dev
0.886567
1
0.886567
Tuinity/Moonrise
2,855
neoforge/src/main/java/ca/spottedleaf/moonrise/neoforge/mixin/chunk_system/NeoForgeTicketStorageMixin.java
package ca.spottedleaf.moonrise.neoforge.mixin.chunk_system; import ca.spottedleaf.concurrentutil.map.ConcurrentLong2LongChainedHashTable; import ca.spottedleaf.moonrise.common.util.CoordinateUtils; import ca.spottedleaf.moonrise.patches.chunk_system.level.ChunkSystemServerLevel; import ca.spottedleaf.moonrise.patches.chunk_system.ticket.ChunkSystemTicketStorage; import ca.spottedleaf.moonrise.patches.chunk_system.ticket.ChunkSystemTicketType; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.LongSet; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.TicketStorage; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(TicketStorage.class) abstract class NeoForgeTicketStorageMixin implements ChunkSystemTicketStorage { @Shadow private LongSet chunksWithForceNaturalSpawning; /** * @reason Destroy old chunk system state * @author Spottedleaf */ @Inject( method = "<init>(Lit/unimi/dsi/fastutil/longs/Long2ObjectOpenHashMap;Lit/unimi/dsi/fastutil/longs/Long2ObjectOpenHashMap;)V", at = @At( value = "RETURN" ) ) private void destroyFields(Long2ObjectOpenHashMap p_393873_, Long2ObjectOpenHashMap p_394615_, CallbackInfo ci) { this.chunksWithForceNaturalSpawning = null; } /** * @reason The forced natural spawning chunks would be empty, as tickets should always be empty. * We need to do this to avoid throwing immediately. * @author Spottedleaf */ @Redirect( method = "<init>(Lit/unimi/dsi/fastutil/longs/Long2ObjectOpenHashMap;Lit/unimi/dsi/fastutil/longs/Long2ObjectOpenHashMap;)V", at = @At( value = "INVOKE", target = "Lnet/minecraft/world/level/TicketStorage;updateForcedNaturalSpawning()V" ) ) private void avoidUpdatingForcedNaturalChunks(final TicketStorage instance) {} /** * @reason Route to new chunk system * @author Spottedleaf */ @Overwrite public boolean shouldForceNaturalSpawning(final ChunkPos pos) { final ConcurrentLong2LongChainedHashTable counters = ((ChunkSystemServerLevel)this.moonrise$getChunkMap().level).moonrise$getChunkTaskScheduler() .chunkHolderManager.getTicketCounters(ChunkSystemTicketType.COUNTER_TYPER_NATURAL_SPAWNING_FORCED); if (counters == null || counters.isEmpty()) { return false; } return counters.containsKey(CoordinateUtils.getChunkKey(pos)); } }
1
0.898804
1
0.898804
game-dev
MEDIA
0.959041
game-dev
0.967048
1
0.967048
QYhB05/FinalTECH-Changed
4,506
src/main/java/io/taraxacum/finaltech/core/item/machine/MatrixItemDeserializeParser.java
package io.taraxacum.finaltech.core.item.machine; import io.github.thebusybiscuit.slimefun4.api.items.ItemGroup; import io.github.thebusybiscuit.slimefun4.api.items.SlimefunItem; import io.github.thebusybiscuit.slimefun4.api.items.SlimefunItemStack; import io.github.thebusybiscuit.slimefun4.api.recipes.RecipeType; import io.github.thebusybiscuit.slimefun4.core.handlers.BlockBreakHandler; import io.github.thebusybiscuit.slimefun4.core.handlers.BlockPlaceHandler; import io.github.thebusybiscuit.slimefun4.implementation.Slimefun; import io.taraxacum.common.util.StringNumberUtil; import io.taraxacum.finaltech.FinalTechChanged; import io.taraxacum.finaltech.core.interfaces.RecipeItem; import io.taraxacum.finaltech.core.menu.AbstractMachineMenu; import io.taraxacum.finaltech.core.menu.machine.ItemDeserializeParserMenu; import io.taraxacum.finaltech.setup.FinalTechItems; import io.taraxacum.finaltech.util.MachineUtil; import io.taraxacum.finaltech.util.RecipeUtil; import io.taraxacum.libs.plugin.util.ItemStackUtil; import io.taraxacum.libs.plugin.util.StringItemUtil; import me.mrCookieSlime.CSCoreLibPlugin.Configuration.Config; import me.mrCookieSlime.Slimefun.api.BlockStorage; import me.mrCookieSlime.Slimefun.api.inventory.BlockMenu; import org.bukkit.block.Block; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import javax.annotation.Nonnull; /** * This is a slimefun machine * it will be used in gameplay * It's not a function class! * * @author Final_ROOT * @since 1.0 */ public class MatrixItemDeserializeParser extends AbstractMachine implements RecipeItem { public MatrixItemDeserializeParser(ItemGroup itemGroup, SlimefunItemStack item, RecipeType recipeType, ItemStack[] recipe) { super(itemGroup, item, recipeType, recipe); } @Nonnull @Override protected BlockPlaceHandler onBlockPlace() { return MachineUtil.BLOCK_PLACE_HANDLER_PLACER_DENY; } @Nonnull @Override protected BlockBreakHandler onBlockBreak() { return MachineUtil.simpleBlockBreakerHandler(this); } @Nonnull @Override protected AbstractMachineMenu setMachineMenu() { return new ItemDeserializeParserMenu(this); } @Override protected void tick(@Nonnull Block block, @Nonnull SlimefunItem slimefunItem, @Nonnull Config config) { BlockMenu blockMenu = BlockStorage.getInventory(block); Inventory inventory = blockMenu.toInventory(); if (MachineUtil.slotCount(inventory, this.getOutputSlot()) == this.getOutputSlot().length) { return; } for (int slot : this.getInputSlot()) { ItemStack itemStack = blockMenu.getItemInSlot(slot); if (FinalTechItems.COPY_CARD.verifyItem(itemStack)) { ItemMeta itemMeta = itemStack.getItemMeta(); ItemStack stringItem = StringItemUtil.parseItemInCard(itemMeta); if (!ItemStackUtil.isItemNull(stringItem)) { int amount = itemStack.getAmount(); String amountInCardStr = StringItemUtil.parseAmountInCard(itemMeta); if (StringNumberUtil.compare(amountInCardStr, "3456") >= 0) { amount = 3456; } else { amount *= Integer.parseInt(amountInCardStr); } if (amount <= 0) { return; } int count; for (int outputSlot : this.getOutputSlot()) { if (!ItemStackUtil.isItemNull(blockMenu.getItemInSlot(outputSlot))) { continue; } count = Math.min(amount, stringItem.getMaxStackSize()); stringItem.setAmount(count); blockMenu.pushItem(stringItem, outputSlot); amount -= count; if (amount == 0) { break; } } } } } } @Override protected boolean isSynchronized() { return false; } @Override public void registerDefaultRecipes() { RecipeUtil.registerDescriptiveRecipe(FinalTechChanged.getLanguageManager(), this, String.format("%.2f", Slimefun.getTickerTask().getTickRate() / 20.0)); } }
1
0.864072
1
0.864072
game-dev
MEDIA
0.983483
game-dev
0.95655
1
0.95655
OpenArena/gamecode
2,076
code/botlib/be_aas_main.h
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Quake III Arena source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Quake III Arena source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ /***************************************************************************** * name: be_aas_main.h * * desc: AAS * * $Archive: /source/code/botlib/be_aas_main.h $ * *****************************************************************************/ #ifdef AASINTERN extern aas_t aasworld; //AAS error message void QDECL AAS_Error(char *fmt, ...); //set AAS initialized void AAS_SetInitialized(void); //setup AAS with the given number of entities and clients int AAS_Setup(void); //shutdown AAS void AAS_Shutdown(void); //start a new map int AAS_LoadMap(const char *mapname); //start a new time frame int AAS_StartFrame(float time); #endif //AASINTERN //returns true if AAS is initialized int AAS_Initialized(void); //returns true if the AAS file is loaded int AAS_Loaded(void); //returns the model name from the given index char *AAS_ModelFromIndex(int index); //returns the index from the given model name int AAS_IndexFromModel(char *modelname); //returns the current time float AAS_Time(void); // void AAS_ProjectPointOntoVector( vec3_t point, vec3_t vStart, vec3_t vEnd, vec3_t vProj );
1
0.64909
1
0.64909
game-dev
MEDIA
0.68992
game-dev
0.531049
1
0.531049
MinecraftModdedClients/Resilience-Client-Source
2,899
net/minecraft/command/CommandGameRule.java
package net.minecraft.command; import java.util.List; import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentText; import net.minecraft.world.GameRules; public class CommandGameRule extends CommandBase { private static final String __OBFID = "CL_00000475"; public String getCommandName() { return "gamerule"; } /** * Return the required permission level for this command. */ public int getRequiredPermissionLevel() { return 2; } public String getCommandUsage(ICommandSender par1ICommandSender) { return "commands.gamerule.usage"; } public void processCommand(ICommandSender par1ICommandSender, String[] par2ArrayOfStr) { String var6; if (par2ArrayOfStr.length == 2) { var6 = par2ArrayOfStr[0]; String var7 = par2ArrayOfStr[1]; GameRules var8 = this.getGameRules(); if (var8.hasRule(var6)) { var8.setOrCreateGameRule(var6, var7); notifyAdmins(par1ICommandSender, "commands.gamerule.success", new Object[0]); } else { notifyAdmins(par1ICommandSender, "commands.gamerule.norule", new Object[] {var6}); } } else if (par2ArrayOfStr.length == 1) { var6 = par2ArrayOfStr[0]; GameRules var4 = this.getGameRules(); if (var4.hasRule(var6)) { String var5 = var4.getGameRuleStringValue(var6); par1ICommandSender.addChatMessage((new ChatComponentText(var6)).appendText(" = ").appendText(var5)); } else { notifyAdmins(par1ICommandSender, "commands.gamerule.norule", new Object[] {var6}); } } else if (par2ArrayOfStr.length == 0) { GameRules var3 = this.getGameRules(); par1ICommandSender.addChatMessage(new ChatComponentText(joinNiceString(var3.getRules()))); } else { throw new WrongUsageException("commands.gamerule.usage", new Object[0]); } } /** * Adds the strings available in this command to the given list of tab completion options. */ public List addTabCompletionOptions(ICommandSender par1ICommandSender, String[] par2ArrayOfStr) { return par2ArrayOfStr.length == 1 ? getListOfStringsMatchingLastWord(par2ArrayOfStr, this.getGameRules().getRules()) : (par2ArrayOfStr.length == 2 ? getListOfStringsMatchingLastWord(par2ArrayOfStr, new String[] {"true", "false"}): null); } /** * Return the game rule set this command should be able to manipulate. */ private GameRules getGameRules() { return MinecraftServer.getServer().worldServerForDimension(0).getGameRules(); } }
1
0.841876
1
0.841876
game-dev
MEDIA
0.840678
game-dev
0.825627
1
0.825627
Aussiemon/Darktide-Source-Code
5,989
dialogues/generated/adamant_male_a_zealot_male_c.lua
-- chunkname: @dialogues/generated/adamant_male_a_zealot_male_c.lua local adamant_male_a_zealot_male_c = { adamant_male_a_zealot_bonding_conversation_21_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_21_b_01", }, sound_events_duration = { [1] = 4.441406, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_21_d = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_21_d_01", }, sound_events_duration = { [1] = 4.392656, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_22_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_22_b_01", }, sound_events_duration = { [1] = 5.513292, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_22_d = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_22_d_01", }, sound_events_duration = { [1] = 2.84625, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_23_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_23_b_01", }, sound_events_duration = { [1] = 7.214375, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_23_d = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_23_d_01", }, sound_events_duration = { [1] = 3.686094, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_24_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_24_b_01", }, sound_events_duration = { [1] = 6.381073, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_24_d = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_24_d_01", }, sound_events_duration = { [1] = 2.713917, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_25_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_25_b_01", }, sound_events_duration = { [1] = 3.428719, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_25_d = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_25_d_01", }, sound_events_duration = { [1] = 2.588802, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_26_a = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_26_a_01", }, sound_events_duration = { [1] = 6.253219, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_26_c = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_26_c_01", }, sound_events_duration = { [1] = 2.497615, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_27_a = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_27_a_01", }, sound_events_duration = { [1] = 4.276229, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_27_c = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_27_c_01", }, sound_events_duration = { [1] = 6.663573, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_28_a = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_28_a_01", }, sound_events_duration = { [1] = 5.285604, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_28_c = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_28_c_01", }, sound_events_duration = { [1] = 4.977719, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_29_a = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_29_a_01", }, sound_events_duration = { [1] = 4.716427, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_29_c = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_29_c_01", }, sound_events_duration = { [1] = 4.861167, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_30_a = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_30_a_01", }, sound_events_duration = { [1] = 1.618708, }, randomize_indexes = {}, }, adamant_male_a_zealot_bonding_conversation_30_c = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_c__adamant_male_a_zealot_bonding_conversation_30_c_01", }, sound_events_duration = { [1] = 7.447177, }, randomize_indexes = {}, }, } return settings("adamant_male_a_zealot_male_c", adamant_male_a_zealot_male_c)
1
0.61403
1
0.61403
game-dev
MEDIA
0.494306
game-dev
0.785998
1
0.785998
moonbit-community/selene
2,342
selene-core/src/backend/pkg.mbti
// Copyright 2025 International Digital Economy Academy // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package "Milky2018/selene/backend" import( "Milky2018/selene/inputs" "Milky2018/selene/math" ) fn initialize( startup~ : () -> Unit, render_loop~ : (Double) -> Unit, game_loop~ : (Double) -> Unit, canvas_width~ : Double, canvas_height~ : Double, fps~ : UInt, image_smooth~ : Bool, zoom~ : Double ) -> () -> Unit fn draw_picture( png~ : String, x~ : Double, y~ : Double, width~ : Double, height~ : Double, transform~ : @math.Transform, repeat~ : @math.RepeatMode ) -> Unit fn draw_sprite( sprite_path~ : String, x~ : Double, y~ : Double, offset_x~ : Double, offset_y~ : Double, width~ : Double, height~ : Double, transform~ : @math.Transform ) -> Unit fn register_key_events(Set[@inputs.Code]) -> Unit fn register_mouse_events(@inputs.Mouse, @inputs.MouseMovement) -> Unit fn lock_mouse(Ref[Bool]) -> Unit fn draw_stroke_rect( x~ : Double, y~ : Double, width~ : Double, height~ : Double, color~ : String ) -> Unit fn draw_text( text~ : String, x~ : Double, y~ : Double, font~ : String, color~ : String, align~ : @math.HAlign, baseline~ : @math.VAlign ) -> Unit fn draw_color_rect( x~ : Double, y~ : Double, width~ : Double, height~ : Double, color~ : String ) -> Unit fn draw_gradient_rect( x~ : Double, y~ : Double, width~ : Double, height~ : Double, color_start~ : String, color_end~ : String ) -> Unit fn play_audio(audio_path~ : String, volume~ : Double, loop_~ : Bool) -> Unit fn get_canvas_size() -> @math.Vec2D fn get_zoom() -> Double fn get_realtime_delta() -> Double fn preload_img(String) -> Unit fn preload_audio(String) -> Unit fn set_time_scale(Double) -> Unit fn load_font(String, String) -> Unit
1
0.823815
1
0.823815
game-dev
MEDIA
0.599645
game-dev,graphics-rendering
0.682517
1
0.682517
Relic/AuthoritativeMovementExample
3,846
Assets/Bearded Man Studios Inc/Generated/UserGenerated/NetworkCameraNetworkObject.cs
using BeardedManStudios.Forge.Networking.Frame; using BeardedManStudios.Forge.Networking.Unity; using System; using UnityEngine; namespace BeardedManStudios.Forge.Networking.Generated { [GeneratedInterpol("{\"inter\":[0.15]")] public partial class NetworkCameraNetworkObject : NetworkObject { public const int IDENTITY = 6; private byte[] _dirtyFields = new byte[1]; #pragma warning disable 0067 public event FieldChangedEvent fieldAltered; #pragma warning restore 0067 private Vector3 _position; public event FieldEvent<Vector3> positionChanged; public InterpolateVector3 positionInterpolation = new InterpolateVector3() { LerpT = 0.15f, Enabled = true }; public Vector3 position { get { return _position; } set { // Don't do anything if the value is the same if (_position == value) return; // Mark the field as dirty for the network to transmit _dirtyFields[0] |= 0x1; _position = value; hasDirtyFields = true; } } public void SetpositionDirty() { _dirtyFields[0] |= 0x1; hasDirtyFields = true; } private void RunChange_position(ulong timestep) { if (positionChanged != null) positionChanged(_position, timestep); if (fieldAltered != null) fieldAltered("position", _position, timestep); } protected override void OwnershipChanged() { base.OwnershipChanged(); SnapInterpolations(); } public void SnapInterpolations() { positionInterpolation.current = positionInterpolation.target; } public override int UniqueIdentity { get { return IDENTITY; } } protected override BMSByte WritePayload(BMSByte data) { UnityObjectMapper.Instance.MapBytes(data, _position); return data; } protected override void ReadPayload(BMSByte payload, ulong timestep) { _position = UnityObjectMapper.Instance.Map<Vector3>(payload); positionInterpolation.current = _position; positionInterpolation.target = _position; RunChange_position(timestep); } protected override BMSByte SerializeDirtyFields() { dirtyFieldsData.Clear(); dirtyFieldsData.Append(_dirtyFields); if ((0x1 & _dirtyFields[0]) != 0) UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _position); return dirtyFieldsData; } protected override void ReadDirtyFields(BMSByte data, ulong timestep) { if (readDirtyFlags == null) Initialize(); Buffer.BlockCopy(data.byteArr, data.StartIndex(), readDirtyFlags, 0, readDirtyFlags.Length); data.MoveStartIndex(readDirtyFlags.Length); if ((0x1 & readDirtyFlags[0]) != 0) { if (positionInterpolation.Enabled) { positionInterpolation.target = UnityObjectMapper.Instance.Map<Vector3>(data); positionInterpolation.Timestep = timestep; } else { _position = UnityObjectMapper.Instance.Map<Vector3>(data); RunChange_position(timestep); } } } public override void InterpolateUpdate() { if (IsOwner) return; if (positionInterpolation.Enabled && !positionInterpolation.current.UnityNear(positionInterpolation.target, 0.0015f)) { _position = (Vector3)positionInterpolation.Interpolate(); //RunChange_position(positionInterpolation.Timestep); } } private void Initialize() { if (readDirtyFlags == null) readDirtyFlags = new byte[1]; } public NetworkCameraNetworkObject() : base() { Initialize(); } public NetworkCameraNetworkObject(NetWorker networker, INetworkBehavior networkBehavior = null, int createCode = 0, byte[] metadata = null) : base(networker, networkBehavior, createCode, metadata) { Initialize(); } public NetworkCameraNetworkObject(NetWorker networker, uint serverId, FrameStream frame) : base(networker, serverId, frame) { Initialize(); } // DO NOT TOUCH, THIS GETS GENERATED PLEASE EXTEND THIS CLASS IF YOU WISH TO HAVE CUSTOM CODE ADDITIONS } }
1
0.778355
1
0.778355
game-dev
MEDIA
0.312991
game-dev
0.945011
1
0.945011
frank-w/BPI-Router-Linux
1,408
scripts/gdb/linux/kasan.py
# SPDX-License-Identifier: GPL-2.0 # # Copyright 2024 Canonical Ltd. # # Authors: # Kuan-Ying Lee <kuan-ying.lee@canonical.com> # import gdb from linux import constants, mm def help(): t = """Usage: lx-kasan_mem_to_shadow [Hex memory addr] Example: lx-kasan_mem_to_shadow 0xffff000008eca008\n""" gdb.write("Unrecognized command\n") raise gdb.GdbError(t) class KasanMemToShadow(gdb.Command): """Translate memory address to kasan shadow address""" p_ops = None def __init__(self): if constants.LX_CONFIG_KASAN_GENERIC or constants.LX_CONFIG_KASAN_SW_TAGS: super(KasanMemToShadow, self).__init__("lx-kasan_mem_to_shadow", gdb.COMMAND_SUPPORT) def invoke(self, args, from_tty): if not constants.LX_CONFIG_KASAN_GENERIC or constants.LX_CONFIG_KASAN_SW_TAGS: raise gdb.GdbError('CONFIG_KASAN_GENERIC or CONFIG_KASAN_SW_TAGS is not set') argv = gdb.string_to_argv(args) if len(argv) == 1: if self.p_ops is None: self.p_ops = mm.page_ops().ops addr = int(argv[0], 16) shadow_addr = self.kasan_mem_to_shadow(addr) gdb.write('shadow addr: 0x%x\n' % shadow_addr) else: help() def kasan_mem_to_shadow(self, addr): return (addr >> self.p_ops.KASAN_SHADOW_SCALE_SHIFT) + self.p_ops.KASAN_SHADOW_OFFSET KasanMemToShadow()
1
0.916381
1
0.916381
game-dev
MEDIA
0.660824
game-dev
0.759733
1
0.759733
FreeFalcon/freefalcon-central
22,619
src/campaign/camplib/aiinput.cpp
#include <windows.h> #include "FalcLib.h" #include "F4Find.h" #include "ClassTbl.h" #include "CampLib.h" // ATM Inputs short IMMEDIATE_MIN_TIME; short IMMEDIATE_MAX_TIME; short LONGRANGE_MIN_TIME; short LONGRANGE_MAX_TIME; short ATM_ASSIGN_RATIO; short MAX_FLYMISSION_THREAT; short MAX_FLYMISSION_HIGHTHREAT; short MAX_FLYMISSION_NOTHREAT; short MIN_SEADESCORT_THREAT; short MIN_AVOID_THREAT; short MIN_AP_DISTANCE; short BREAKPOINT_DISTANCE; short ATM_TARGET_CLEAR_RADIUS; short LOITER_DIST; short SWEEP_DISTANCE; short MINIMUM_BDA_PRIORITY; short MINIMUM_AWACS_DISTANCE; short MAXIMUM_AWACS_DISTANCE; short MINIMUM_JSTAR_DISTANCE; short MAXIMUM_JSTAR_DISTANCE; short MINIMUM_TANKER_DISTANCE; short MAXIMUM_TANKER_DISTANCE; short MINIMUM_ECM_DISTANCE; short MAXIMUM_ECM_DISTANCE; short FIRST_COLONEL; // Indexes into our pilot name array short FIRST_COMMANDER; short FIRST_WINGMAN; short LAST_WINGMAN; short MAX_AA_STR_FOR_ESCORT; short BARCAP_REQUEST_INTERVAL; // Minimum time between BARCAP mission requests short ONCALL_CAS_FLIGHTS_PER_REQUEST; // How many CAS flights to plan per ONCALL request short MIN_TASK_AIR; // Retask time, in minutes short MIN_PLAN_AIR; // Replan time (KCK NOTE: PLAN_AIR max is 8) short VICTORY_CHECK_TIME; // Check the victory conditions in a Tactical Engagement short FLIGHT_MOVE_CHECK_INTERVAL; // How often to check a flight for movement (in seconds) short FLIGHT_COMBAT_CHECK_INTERVAL; // How often to check a flight for combat (in seconds) short AIR_UPDATE_CHECK_INTERVAL; // How often to check squadrons/packages for movement/update (in seconds) short FLIGHT_COMBAT_RATE; // Amount of time between weapon shots (in seconds) short PACKAGE_CYCLES_TO_WAIT; // How many planning cycles to wait for tankers/barcap/etc short AIR_PATH_MAX; // Max amount of nodes to search for air paths float MIN_IGNORE_RANGE; // Minimum range (km) at which we'll ignore an air target short MAX_SAR_DIST; // Max distance from front to fly sar choppers into. (km) short MAX_BAI_DIST; // Max distance from front to fly BAI missions into. (km) long PILOT_ASSIGN_TIME; // Time before takeoff to assign pilots short AIRCRAFT_TURNAROUND_TIME_MINUTES; // Time to wait between missions before an aircraft is available again // GTM Inputs short PRIMARY_OBJ_PRIORITY; // Priorities for primary and secondary objectives short SECONDARY_OBJ_PRIORITY; // Only cities and towns can be POs and SOs short MAX_OFFENSES; // Maximum number of offensive POs short MIN_OFFENSIVE_UNITS; // Minimum number of units to constitute an offensive short MINIMUM_ADJUSTED_LEVEL; // Minimum % strength of unit assigned to offense. short MINIMUM_VIABLE_LEVEL; // Minimum % strength in order to be considered a viable unit short MAX_ASSIGNMENT_DIST; // Maximum distance from an object we'll assign a unit to short MAXLINKS_FROM_SO_OFFENSIVE; // Maximum objective links from our secondary objective we'll place units short MAXLINKS_FROM_SO_DEFENSIVE; // Same as above for defensive units short BRIGADE_BREAK_BASE; // Base moral a brigade breaks at (modified by objective priority) short ROLE_SCORE_MODIFIER; // Used to adjust role score for scoring purposes short MIN_TASK_GROUND; // Retask time, in minutes short MIN_PLAN_GROUND; // Replan time, in minutes short MIN_REPAIR_OBJECTIVES; // How often to repair objectives (in minutes); short MIN_RESUPPLY; // How often to resupply troops (in minutes) short MORALE_REGAIN_RATE; // How much morale per hour a typical unit will regain short REGAIN_RATE_MULTIPLIER_FOR_TE; // Morale/Fatigue regain rate multiplier for TE missions short FOOT_MOVE_CHECK_INTERVAL; // How often to check a foot battalion for movement (in seconds) short TRACKED_MOVE_CHECK_INTERVAL; // How often to check a tracked/wheeled battalion for combat (in seconds) short GROUND_COMBAT_CHECK_INTERVAL; // How often to check ground battalions for combat short GROUND_UPDATE_CHECK_INTERVAL; // How often to check brigades for update (in seconds) short GROUND_COMBAT_RATE; // Amount of time between weapon shots (in seconds) short GROUND_PATH_MAX; // Max amount of nodes to search for ground paths short OBJ_GROUND_PATH_MAX_SEARCH; // Max amount of nodes to search for objective paths short OBJ_GROUND_PATH_MAX_COST; // Max amount of nodes to search for objective paths short MIN_FULL_OFFENSIVE_INITIATIVE; // Minimum initiative required to launch a full offensive short MIN_COUNTER_ATTACK_INITIATIVE; // Minimum initiative required to launch a counter-attack short MIN_SECURE_INITIATIVE; // Minimum initiative required to secure defensive objectives short MINIMUM_EXP_TO_FIRE_PREGUIDE; // Minimum experience needed to fire SAMs before going to guide mode long OFFENSIVE_REINFORCEMENT_TIME; // How often we get reinforcements when on the offensive long DEFENSIVE_REINFORCEMENT_TIME; // How often we get reinforcements when on the defensive long CONSOLIDATE_REINFORCEMENT_TIME; // How often we get reinforcements when consolidating long ACTION_PREP_TIME; // How far in advance to plan any offensives // NTM Inputs short MIN_TASK_NAVAL; // Retask time, in minutes short MIN_PLAN_NAVAL; // Replan time, in minutes short NAVAL_MOVE_CHECK_INTERVAL; // How often to check a task force for movement (in seconds) short NAVAL_COMBAT_CHECK_INTERVAL; // How often to fire naval units (in seconds) short NAVAL_COMBAT_RATE; // Amount of time between weapon shots (in seconds) // Other variables short LOW_ALTITUDE_CUTOFF; short MAX_GROUND_SEARCH; // How far to look for surface units or objectives short MAX_AIR_SEARCH; // How far to look for air threats short NEW_CLOUD_CHANCE; short DEL_CLOUD_CHANCE; short PLAYER_BUBBLE_MOVERS; // The # of objects we try to keep in player bubble short FALCON_PLAYER_TEAM; // What team the player starts on short CAMP_RESYNC_TIME; // How often to resync campaigns (in seconds) unsigned short BUBBLE_REBUILD_TIME; // How often to rebuild the player bubble (in seconds) short STANDARD_EVENT_LENGTH; // Length of stored event queues short PRIORITY_EVENT_LENGTH; short MIN_RECALCULATE_STATISTICS; // How often to do the unit statistics stuff float LOWAIR_RANGE_MODIFIER; // % of Air range to get LowAir range from short MINIMUM_STRENGTH; // Minimum strength points we'll bother appling with colateral damage short MAX_DAMAGE_TRIES; // Max # of times we'll attempt to find a random target vehicle/feature float REAGREGATION_RATIO; // Ratio over 1.0 which things will reaggregate at short MIN_REINFORCE_TIME; // Value, in minutes, of each reinforcement cycle float SIM_BUBBLE_SIZE; // Radius (in feet) of the Sim's campaign lists. short INITIATIVE_LEAK_PER_HOUR; // How much initiative is adjusted automatically per hour int F4_GENERIC_US_TRUCK_TYPE_SMALL; // Small US tractor vehicle int F4_GENERIC_US_TRUCK_TYPE_LARGE; // Large US tractor vehicle int F4_GENERIC_US_TRUCK_TYPE_TRAILER; // Tractor US for trailers int F4_GENERIC_OPFOR_TRUCK_TYPE_SMALL; // Small OPFOR tractor vehicle int F4_GENERIC_OPFOR_TRUCK_TYPE_LARGE; // Large OPFOR tractor vehicle int F4_GENERIC_OPFOR_TRUCK_TYPE_TRAILER;// Tractor OPFOR for trailers int SWITCH_TRACTORS_IN_TE; // Because in standard Korea we have switched teams in TE // A.S. Campaign variables -> MPS original values int StartOffBonusRepl; // Replacement bonus when a team goes offensive int StartOffBonusSup; // Supply Bonus when a team goes offensive int StartOffBonusFuel; // Fuel Bonus when a team goes offensive int ActionRate; // How often we can start a new action (in hours) int ActionTimeOut; // Maximum time an offensive action can last float DataRateModRepl; // Modification factor for production data rate for replacements float DataRateModSup; // Modification factor for production data rate for fuel and supply float RelSquadBonus; // Relative replacements of squadrons to ground units // in fact bools int NoActionBonusProd; // No action bonus for production int NoTypeBonusRepl; // No type bonus for replacements, new supply system, bugfix in "supplies units" function int NewInitiativePoints; // New initative points setting; int CampBugFixes; // Smaller bugfixes float HitChanceAir; // 2D hitchance air target modulation float HitChanceGround; // 2D hitchance ground target modulation float MIN_DEAD_PCT; // Strength below which a reaggregating vehicle will be considered dead float FLOTDrawDistance; // Distance between objectives at which we won't draw a line between them (in km^2) int FLOTSortDirection; // sort FLOT list from north to south (1) or east to west (0) int TheaterXPosition; // central X position for theater - used for finding best bullseye position int TheaterYPosition; // central Y position for theater - used for finding best bullseye position // A.S. // Reader Function void ReadCampAIInputs(char * name) { char fileName[256], tmpName[80]; int off, len; short temp; sprintf(tmpName, "%s.AII", name); if( not F4FindFile(tmpName, fileName, 256, &off, &len)) exit(0); /* ATM Inputs */ IMMEDIATE_MIN_TIME = (short)GetPrivateProfileInt("ATM", "ImmediatePlanMinTime", 0, fileName); IMMEDIATE_MAX_TIME = (short)GetPrivateProfileInt("ATM", "ImmediatePlanMaxTime", 0, fileName); LONGRANGE_MIN_TIME = (short)GetPrivateProfileInt("ATM", "LongrangePlanMinTime", 0, fileName); LONGRANGE_MAX_TIME = (short)GetPrivateProfileInt("ATM", "LongrangePlanMaxTime", 0, fileName); ATM_ASSIGN_RATIO = (short)GetPrivateProfileInt("ATM", "AircraftAssignmentRatio", 0, fileName); MAX_FLYMISSION_THREAT = (short)GetPrivateProfileInt("ATM", "MaxFlymissionThreat", 0, fileName); MAX_FLYMISSION_HIGHTHREAT = (short)GetPrivateProfileInt("ATM", "MaxFlymissionHighThreat", 0, fileName); MAX_FLYMISSION_NOTHREAT = (short)GetPrivateProfileInt("ATM", "MaxFlymissionNoThreat", 0, fileName); MIN_SEADESCORT_THREAT = (short)GetPrivateProfileInt("ATM", "MinSeadescortThreat", 0, fileName); MIN_AVOID_THREAT = (short)GetPrivateProfileInt("ATM", "MinAvoidThreat", 0, fileName); MIN_AP_DISTANCE = (short)GetPrivateProfileInt("ATM", "MinAssemblyPtDist", 0, fileName); BREAKPOINT_DISTANCE = (short)GetPrivateProfileInt("ATM", "BreakpointDist", 0, fileName); ATM_TARGET_CLEAR_RADIUS = (short)GetPrivateProfileInt("ATM", "TargetClearRadius", 0, fileName); LOITER_DIST = (short)GetPrivateProfileInt("ATM", "LoiterTurnDistance", 0, fileName); SWEEP_DISTANCE = (short)GetPrivateProfileInt("ATM", "SweepRadius", 0, fileName); MINIMUM_BDA_PRIORITY = (short)GetPrivateProfileInt("ATM", "MinimumBDAPriority", 0, fileName); MINIMUM_AWACS_DISTANCE = (short)GetPrivateProfileInt("ATM", "MinimumAWACSDistance", 0, fileName); MAXIMUM_AWACS_DISTANCE = (short)GetPrivateProfileInt("ATM", "MaximumAWACSDistance", 0, fileName); MINIMUM_JSTAR_DISTANCE = (short)GetPrivateProfileInt("ATM", "MinimumJSTARDistance", 0, fileName); MAXIMUM_JSTAR_DISTANCE = (short)GetPrivateProfileInt("ATM", "MaximumJSTARDistance", 0, fileName); MINIMUM_TANKER_DISTANCE = (short)GetPrivateProfileInt("ATM", "MinimumTankerDistance", 0, fileName); MAXIMUM_TANKER_DISTANCE = (short)GetPrivateProfileInt("ATM", "MaximumTankerDistance", 0, fileName); MINIMUM_ECM_DISTANCE = (short)GetPrivateProfileInt("ATM", "MinimumECMDistance", 0, fileName); MAXIMUM_ECM_DISTANCE = (short)GetPrivateProfileInt("ATM", "MaximumECMDistance", 0, fileName); FIRST_COLONEL = (short)GetPrivateProfileInt("ATM", "FirstColonel", 0, fileName); FIRST_COMMANDER = (short)GetPrivateProfileInt("ATM", "FirstCommander", 0, fileName); FIRST_WINGMAN = (short)GetPrivateProfileInt("ATM", "FirstWingman", 0, fileName); LAST_WINGMAN = (short)GetPrivateProfileInt("ATM", "LastWingman", 0, fileName); MAX_AA_STR_FOR_ESCORT = (short)GetPrivateProfileInt("ATM", "MaxEscortAAStrength", 0, fileName); BARCAP_REQUEST_INTERVAL = (short)GetPrivateProfileInt("ATM", "BARCAPRequestInterval", 0, fileName); ONCALL_CAS_FLIGHTS_PER_REQUEST = (short)GetPrivateProfileInt("ATM", "OnCallFlightsPerRequest", 0, fileName); MIN_TASK_AIR = (short)GetPrivateProfileInt("ATM", "AirTaskTime", 0, fileName); MIN_PLAN_AIR = (short)GetPrivateProfileInt("ATM", "AirPlanTime", 0, fileName); VICTORY_CHECK_TIME = (short)GetPrivateProfileInt("ATM", "VictoryConditionTime", 0, fileName); FLIGHT_MOVE_CHECK_INTERVAL = (short)GetPrivateProfileInt("ATM", "FlightMoveCheckInterval", 0, fileName); FLIGHT_COMBAT_CHECK_INTERVAL = (short)GetPrivateProfileInt("ATM", "FlightCombatCheckInterval", 0, fileName); AIR_UPDATE_CHECK_INTERVAL = (short)GetPrivateProfileInt("ATM", "AirUpdateCheckInterval", 0, fileName); FLIGHT_COMBAT_RATE = (short)GetPrivateProfileInt("ATM", "FlightCombatRate", 0, fileName); PACKAGE_CYCLES_TO_WAIT = (short)GetPrivateProfileInt("ATM", "PackageCyclesToWait", 0, fileName); AIR_PATH_MAX = (short)GetPrivateProfileInt("ATM", "AirPathMax", 0, fileName); MIN_IGNORE_RANGE = (float)GetPrivateProfileInt("ATM", "MinimumIgnoreRange", 0, fileName); MAX_SAR_DIST = (short)GetPrivateProfileInt("ATM", "MaxSARDistance", 0, fileName); MAX_BAI_DIST = (short)GetPrivateProfileInt("ATM", "MaxBAIDistance", 0, fileName); PILOT_ASSIGN_TIME = (long)GetPrivateProfileInt("ATM", "PilotAssignTime", 0, fileName); AIRCRAFT_TURNAROUND_TIME_MINUTES = (short)GetPrivateProfileInt("ATM", "AircraftTurnaroundMinutes", 0, fileName); /* GTM Inputs */ PRIMARY_OBJ_PRIORITY = (short)GetPrivateProfileInt("GTM", "PrimaryObjPriority", 0, fileName); SECONDARY_OBJ_PRIORITY = (short)GetPrivateProfileInt("GTM", "SecondaryObjPriority", 0, fileName); MAX_OFFENSES = (short)GetPrivateProfileInt("GTM", "MaximumOffenses", 0, fileName); MIN_OFFENSIVE_UNITS = (short)GetPrivateProfileInt("GTM", "MinimumOffensiveUnits", 0, fileName); MINIMUM_ADJUSTED_LEVEL = (short)GetPrivateProfileInt("GTM", "MinimumAdjustedLevel", 0, fileName); MINIMUM_VIABLE_LEVEL = (short)GetPrivateProfileInt("GTM", "MinimumViableLevel", 0, fileName); MAX_ASSIGNMENT_DIST = (short)GetPrivateProfileInt("GTM", "MaximumAssignmentDist", 0, fileName); MAXLINKS_FROM_SO_OFFENSIVE = (short)GetPrivateProfileInt("GTM", "MaximumOffensiveLinks", 0, fileName); MAXLINKS_FROM_SO_DEFENSIVE = (short)GetPrivateProfileInt("GTM", "MaximumDefensiveLinks", 0, fileName); BRIGADE_BREAK_BASE = (short)GetPrivateProfileInt("GTM", "BrigadeBreakBase", 0, fileName); ROLE_SCORE_MODIFIER = (short)GetPrivateProfileInt("GTM", "RoleScoreModifier", 0, fileName); MIN_TASK_GROUND = (short)GetPrivateProfileInt("GTM", "TaskGroundTime", 0, fileName); MIN_PLAN_GROUND = (short)GetPrivateProfileInt("GTM", "PlanGroundTime", 0, fileName); MIN_REPAIR_OBJECTIVES = (short)GetPrivateProfileInt("GTM", "ObjectiveRepairInterval", 0, fileName); MIN_RESUPPLY = (short)GetPrivateProfileInt("GTM", "ResupplyInterval", 0, fileName); MORALE_REGAIN_RATE = (short)GetPrivateProfileInt("GTM", "MoraleRegainRate", 0, fileName); REGAIN_RATE_MULTIPLIER_FOR_TE = (short)GetPrivateProfileInt("GTM", "TERegainRateMultiplier", 0, fileName); FOOT_MOVE_CHECK_INTERVAL = (short)GetPrivateProfileInt("GTM", "FootMoveCheckInterval", 0, fileName); TRACKED_MOVE_CHECK_INTERVAL = (short)GetPrivateProfileInt("GTM", "TrackedMoveCheckInterval", 0, fileName); GROUND_COMBAT_CHECK_INTERVAL = (short)GetPrivateProfileInt("GTM", "GroundCombatCheckInterval", 0, fileName); GROUND_UPDATE_CHECK_INTERVAL = (short)GetPrivateProfileInt("GTM", "GroundUpdateCheckInterval", 0, fileName); GROUND_COMBAT_RATE = (short)GetPrivateProfileInt("GTM", "GroundCombatRate", 0, fileName); GROUND_PATH_MAX = (short)GetPrivateProfileInt("GTM", "GroundPathMax", 0, fileName); OBJ_GROUND_PATH_MAX_SEARCH = (short)GetPrivateProfileInt("GTM", "ObjGroundPathMaxSearch", 0, fileName); OBJ_GROUND_PATH_MAX_COST = (short)GetPrivateProfileInt("GTM", "ObjGroundPathMaxCost", 0, fileName); MIN_FULL_OFFENSIVE_INITIATIVE = (short)GetPrivateProfileInt("GTM", "MinFullOffensiveInitiative", 0, fileName); MIN_COUNTER_ATTACK_INITIATIVE = (short)GetPrivateProfileInt("GTM", "MinCounterAttackInitiative", 0, fileName); MIN_SECURE_INITIATIVE = (short)GetPrivateProfileInt("GTM", "MinSecureInitiative", 0, fileName); MINIMUM_EXP_TO_FIRE_PREGUIDE = (short)GetPrivateProfileInt("GTM", "MinExpToFirePreGuide", 0, fileName); OFFENSIVE_REINFORCEMENT_TIME = (long)GetPrivateProfileInt("GTM", "OffensiveReinforcementTime", 0, fileName) * CampaignMinutes; DEFENSIVE_REINFORCEMENT_TIME = (long)GetPrivateProfileInt("GTM", "DefensiveReinforcementTime", 0, fileName) * CampaignMinutes; CONSOLIDATE_REINFORCEMENT_TIME = (long)GetPrivateProfileInt("GTM", "ConsolidateReinforcementTime", 0, fileName) * CampaignMinutes; ACTION_PREP_TIME = (long)GetPrivateProfileInt("GTM", "ActionPrepTime", 0, fileName) * CampaignMinutes; /* NTM Inputs */ MIN_TASK_NAVAL = (short)GetPrivateProfileInt("NTM", "TaskNavalTime", 0, fileName); MIN_PLAN_NAVAL = (short)GetPrivateProfileInt("NTM", "PlanNavalTime", 0, fileName); NAVAL_COMBAT_CHECK_INTERVAL = (short)GetPrivateProfileInt("NTM", "NavalCombatCheckInterval", 0, fileName); NAVAL_MOVE_CHECK_INTERVAL = (short)GetPrivateProfileInt("NTM", "NavalMoveCheckInterval", 0, fileName); NAVAL_COMBAT_RATE = (short)GetPrivateProfileInt("NTM", "NavalCombatRate", 0, fileName); /* Other */ LOW_ALTITUDE_CUTOFF = (short)GetPrivateProfileInt("Other", "LowAltitudeCutoff", 0, fileName); MAX_GROUND_SEARCH = (short)GetPrivateProfileInt("Other", "GroundSearchDistance", 0, fileName); MAX_AIR_SEARCH = (short)GetPrivateProfileInt("Other", "AirSearchDistance", 0, fileName); NEW_CLOUD_CHANCE = (short)GetPrivateProfileInt("Other", "NewCloudPercentage", 0, fileName); DEL_CLOUD_CHANCE = (short)GetPrivateProfileInt("Other", "DeleteCloudPercentage", 0, fileName); PLAYER_BUBBLE_MOVERS = (short)GetPrivateProfileInt("Other", "PlayerBubbleObjects", 0, fileName); FALCON_PLAYER_TEAM = (short)GetPrivateProfileInt("Other", "PlayerTeam", 0, fileName); CAMP_RESYNC_TIME = (short)GetPrivateProfileInt("Other", "CampaignResyncTime", 0, fileName); BUBBLE_REBUILD_TIME = (unsigned short)GetPrivateProfileInt("Other", "BubbleRebuildTime", 0, fileName); STANDARD_EVENT_LENGTH = (short)GetPrivateProfileInt("Other", "StandardEventqueueLength", 0, fileName); // Length of stored event queues PRIORITY_EVENT_LENGTH = (short)GetPrivateProfileInt("Other", "PriorityEventqueueLength", 0, fileName); MIN_RECALCULATE_STATISTICS = (short)GetPrivateProfileInt("Other", "StatisticsRecalculationInterval", 0, fileName); temp = (short)GetPrivateProfileInt("Other", "LowAirRangeModifier", 0, fileName); LOWAIR_RANGE_MODIFIER = (float)(temp / 100.0F); MINIMUM_STRENGTH = (short)GetPrivateProfileInt("Other", "MinimumStrength", 0, fileName); MAX_DAMAGE_TRIES = (short)GetPrivateProfileInt("Other", "MaximumDamageTries", 0, fileName); temp = (short)GetPrivateProfileInt("Other", "ReaggregationRatio", 0, fileName); REAGREGATION_RATIO = (float)(temp / 100.0F); MIN_REINFORCE_TIME = (short)GetPrivateProfileInt("Other", "ReinforcementTime", 0, fileName); SIM_BUBBLE_SIZE = (float)GetPrivateProfileInt("Other", "SimBubbleSize", 0, fileName); INITIATIVE_LEAK_PER_HOUR = (short)GetPrivateProfileInt("Other", "InitiativeLeakPerHour", 0, fileName); // RV - Biker - Read tractor vehicles from here F4_GENERIC_US_TRUCK_TYPE_SMALL = (int)GetPrivateProfileInt("Campaign", "US_TRUCK_TYPE_SMALL", 534, fileName); // HMMWV F4_GENERIC_US_TRUCK_TYPE_LARGE = (int)GetPrivateProfileInt("Campaign", "US_TRUCK_TYPE_LARGE", 548, fileName); // M997 F4_GENERIC_US_TRUCK_TYPE_TRAILER = (int)GetPrivateProfileInt("Campaign", "US_TRUCK_TYPE_TRAILER", 548, fileName); //TBD F4_GENERIC_OPFOR_TRUCK_TYPE_SMALL = (int)GetPrivateProfileInt("Campaign", "OPFOR_TRUCK_TYPE_SMALL", 707, fileName); //KrAz T 255B F4_GENERIC_OPFOR_TRUCK_TYPE_LARGE = (int)GetPrivateProfileInt("Campaign", "OPFOR_TRUCK_TYPE_LARGE", 707, fileName); //TBD F4_GENERIC_OPFOR_TRUCK_TYPE_TRAILER = (int)GetPrivateProfileInt("Campaign", "OPFOR_TRUCK_TYPE_TRAILER", 835, fileName); //ZIL-135 SWITCH_TRACTORS_IN_TE = (int)GetPrivateProfileInt("Campaign", "SWITCH_TRACTORS_IN_TE", 1, fileName); // Because in standard Korea we have switched teams in TE /* Campaign - MPS defaults */ StartOffBonusRepl = (int)GetPrivateProfileInt("Campaign", "StartOffBonusRepl", 1000, fileName); StartOffBonusSup = (int)GetPrivateProfileInt("Campaign", "StartOffBonusSup", 5000, fileName); StartOffBonusFuel = (int)GetPrivateProfileInt("Campaign", "StartOffBonusFuel", 5000, fileName); ActionRate = (int)GetPrivateProfileInt("Campaign", "ActionRate", 8, fileName); ActionTimeOut = (int)GetPrivateProfileInt("Campaign", "ActionTimeOut", 24, fileName); GetPrivateProfileString("Campaign", "DataRateModRepl", "1.0", tmpName, 40, fileName); DataRateModRepl = (float)atof(tmpName); GetPrivateProfileString("Campaign", "DataRateModSup", "1.0", tmpName, 40, fileName); DataRateModSup = (float)atof(tmpName); GetPrivateProfileString("Campaign", "RelSquadBonus", "4.0", tmpName, 40, fileName); RelSquadBonus = (float)atof(tmpName); NoActionBonusProd = (int)GetPrivateProfileInt("Campaign", "NoActionBonusProd", 0, fileName); NoTypeBonusRepl = (int)GetPrivateProfileInt("Campaign", "NoTypeBonusRepl", 0, fileName); NewInitiativePoints = (int)GetPrivateProfileInt("Campaign", "NewInitiativePoints", 0, fileName); CampBugFixes = (int)GetPrivateProfileInt("Campaign", "CampBugFixes", 0, fileName); GetPrivateProfileString("Campaign", "2DHitChanceAir", "3.5", tmpName, 40, fileName); HitChanceAir = (float)atof(tmpName); GetPrivateProfileString("Campaign", "2DHitChanceGround", "1.5", tmpName, 40, fileName); HitChanceGround = (float)atof(tmpName); GetPrivateProfileString("Campaign", "MinDeadPct", "0.6", tmpName, 40, fileName); MIN_DEAD_PCT = (float)atof(tmpName); // 2002-04-17 MN these are now read from the campaign trigger files to have them definable per campaign. // GetPrivateProfileString("Campaign","FLOTDrawDistance", "2500.0", tmpName, 40, fileName); // 50 km // FLOTDrawDistance = (float)atof(tmpName); // FLOTSortDirection = (int)GetPrivateProfileInt("Campaign","SortNorthSouth", 0, fileName); // TheaterXPosition = (int)GetPrivateProfileInt("Campaign","TheaterXPosit", 512, fileName); // default place in center of korea sized theaters // TheaterYPosition = (int)GetPrivateProfileInt("Campaign","TheaterYPosit", 512, fileName); // default place in center of korea sized theaters }
1
0.760627
1
0.760627
game-dev
MEDIA
0.967099
game-dev
0.707889
1
0.707889
kmatheussen/radium
11,450
pluginhost/JuceLibraryCode/modules/juce_data_structures/undomanager/juce_UndoManager.h
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2022 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 7 End-User License Agreement and JUCE Privacy Policy. End User License Agreement: www.juce.com/juce-7-licence Privacy Policy: www.juce.com/juce-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { //============================================================================== /** Manages a list of undo/redo commands. An UndoManager object keeps a list of past actions and can use these actions to move backwards and forwards through an undo history. To use it, create subclasses of UndoableAction which perform all the actions you need, then when you need to actually perform an action, create one and pass it to the UndoManager's perform() method. The manager also uses the concept of 'transactions' to group the actions together - all actions performed between calls to beginNewTransaction() are grouped together and are all undone/redone as a group. The UndoManager is a ChangeBroadcaster, so listeners can register to be told when actions are performed or undone. @see UndoableAction @tags{DataStructures} */ class JUCE_API UndoManager : public ChangeBroadcaster { public: //============================================================================== /** Creates an UndoManager. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value to indicate how much storage it takes up (UndoableAction::getSizeInUnits()), so this lets you specify the maximum total number of units that the undomanager is allowed to keep in memory before letting the older actions drop off the end of the list. @param minimumTransactionsToKeep this specifies the minimum number of transactions that will be kept, even if this involves exceeding the amount of space specified in maxNumberOfUnitsToKeep */ UndoManager (int maxNumberOfUnitsToKeep = 30000, int minimumTransactionsToKeep = 30); /** Destructor. */ ~UndoManager() override; //============================================================================== /** Deletes all stored actions in the list. */ void clearUndoHistory(); /** Returns the current amount of space to use for storing UndoableAction objects. @see setMaxNumberOfStoredUnits */ int getNumberOfUnitsTakenUpByStoredCommands() const; /** Sets the amount of space that can be used for storing UndoableAction objects. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value to indicate how much storage it takes up (UndoableAction::getSizeInUnits()), so this lets you specify the maximum total number of units that the undomanager is allowed to keep in memory before letting the older actions drop off the end of the list. @param minimumTransactionsToKeep this specifies the minimum number of transactions that will be kept, even if this involves exceeding the amount of space specified in maxNumberOfUnitsToKeep @see getNumberOfUnitsTakenUpByStoredCommands */ void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep, int minimumTransactionsToKeep); //============================================================================== /** Performs an action and adds it to the undo history list. @param action the action to perform - this object will be deleted by the UndoManager when no longer needed @returns true if the command succeeds - see UndoableAction::perform @see beginNewTransaction */ bool perform (UndoableAction* action); /** Performs an action and also gives it a name. @param action the action to perform - this object will be deleted by the UndoManager when no longer needed @param actionName if this string is non-empty, the current transaction will be given this name; if it's empty, the current transaction name will be left unchanged. See setCurrentTransactionName() @returns true if the command succeeds - see UndoableAction::perform @see beginNewTransaction */ bool perform (UndoableAction* action, const String& actionName); /** Starts a new group of actions that together will be treated as a single transaction. All actions that are passed to the perform() method between calls to this method are grouped together and undone/redone together by a single call to undo() or redo(). */ void beginNewTransaction(); /** Starts a new group of actions that together will be treated as a single transaction. All actions that are passed to the perform() method between calls to this method are grouped together and undone/redone together by a single call to undo() or redo(). @param actionName a description of the transaction that is about to be performed */ void beginNewTransaction (const String& actionName); /** Changes the name stored for the current transaction. Each transaction is given a name when the beginNewTransaction() method is called, but this can be used to change that name without starting a new transaction. */ void setCurrentTransactionName (const String& newName); /** Returns the name of the current transaction. @see setCurrentTransactionName */ String getCurrentTransactionName() const; //============================================================================== /** Returns true if there's at least one action in the list to undo. @see getUndoDescription, undo, canRedo */ bool canUndo() const; /** Tries to roll-back the last transaction. @returns true if the transaction can be undone, and false if it fails, or if there aren't any transactions to undo @see undoCurrentTransactionOnly */ bool undo(); /** Tries to roll-back any actions that were added to the current transaction. This will perform an undo() only if there are some actions in the undo list that were added after the last call to beginNewTransaction(). This is useful because it lets you call beginNewTransaction(), then perform an operation which may or may not actually perform some actions, and then call this method to get rid of any actions that might have been done without it rolling back the previous transaction if nothing was actually done. @returns true if any actions were undone. */ bool undoCurrentTransactionOnly(); /** Returns the name of the transaction that will be rolled-back when undo() is called. @see undo, canUndo, getUndoDescriptions */ String getUndoDescription() const; /** Returns the names of the sequence of transactions that will be performed if undo() is repeatedly called. Note that for transactions where no name was provided, the corresponding string will be empty. @see undo, canUndo, getUndoDescription */ StringArray getUndoDescriptions() const; /** Returns the time to which the state would be restored if undo() was to be called. If an undo isn't currently possible, it'll return Time(). */ Time getTimeOfUndoTransaction() const; /** Returns a list of the UndoableAction objects that have been performed during the transaction that is currently open. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly() were to be called now. The first item in the list is the earliest action performed. */ void getActionsInCurrentTransaction (Array<const UndoableAction*>& actionsFound) const; /** Returns the number of UndoableAction objects that have been performed during the transaction that is currently open. @see getActionsInCurrentTransaction */ int getNumActionsInCurrentTransaction() const; //============================================================================== /** Returns true if there's at least one action in the list to redo. @see getRedoDescription, redo, canUndo */ bool canRedo() const; /** Tries to redo the last transaction that was undone. @returns true if the transaction can be redone, and false if it fails, or if there aren't any transactions to redo */ bool redo(); /** Returns the name of the transaction that will be redone when redo() is called. @see redo, canRedo, getRedoDescriptions */ String getRedoDescription() const; /** Returns the names of the sequence of transactions that will be performed if redo() is repeatedly called. Note that for transactions where no name was provided, the corresponding string will be empty. @see redo, canRedo, getRedoDescription */ StringArray getRedoDescriptions() const; /** Returns the time to which the state would be restored if redo() was to be called. If a redo isn't currently possible, it'll return Time::getCurrentTime(). @see redo, canRedo */ Time getTimeOfRedoTransaction() const; /** Returns true if the caller code is in the middle of an undo or redo action. */ bool isPerformingUndoRedo() const; private: //============================================================================== struct ActionSet; OwnedArray<ActionSet> transactions, stashedFutureTransactions; String newTransactionName; int totalUnitsStored = 0, maxNumUnitsToKeep = 0, minimumTransactionsToKeep = 0, nextIndex = 0; bool newTransaction = true, isInsideUndoRedoCall = false; ActionSet* getCurrentSet() const; ActionSet* getNextSet() const; void moveFutureTransactionsToStash(); void restoreStashedFutureTransactions(); void dropOldTransactionsIfTooLarge(); JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UndoManager) }; } // namespace juce
1
0.867153
1
0.867153
game-dev
MEDIA
0.206563
game-dev
0.978441
1
0.978441
TartaricAcid/TouhouLittleMaid
1,869
src/main/java/com/github/tartaricacid/touhoulittlemaid/util/ByteBufUtils.java
package com.github.tartaricacid.touhoulittlemaid.util; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import it.unimi.dsi.fastutil.objects.Object2FloatOpenHashMap; import net.minecraft.network.FriendlyByteBuf; import java.util.List; import java.util.Set; public final class ByteBufUtils { public static void writeStringSet(Set<String> set, FriendlyByteBuf buf) { buf.writeVarInt(set.size()); for (String s : set) { buf.writeUtf(s); } } public static Set<String> readStringSet(FriendlyByteBuf buf) { int size = buf.readVarInt(); Set<String> set = Sets.newHashSet(); for (int i = 0; i < size; i++) { set.add(buf.readUtf()); } return set; } public static void writeStringList(List<String> list, FriendlyByteBuf buf) { buf.writeVarInt(list.size()); for (String s : list) { buf.writeUtf(s); } } public static List<String> readStringList(FriendlyByteBuf buf) { int size = buf.readVarInt(); List<String> list = Lists.newArrayList(); for (int i = 0; i < size; i++) { list.add(buf.readUtf()); } return list; } public static void writeObject2FloatOpenHashMap(Object2FloatOpenHashMap<String> map, FriendlyByteBuf buf) { buf.writeVarInt(map.size()); map.forEach((key, value) -> { buf.writeUtf(key); buf.writeFloat(value); }); } public static Object2FloatOpenHashMap<String> readObject2FloatOpenHashMap(FriendlyByteBuf buf) { int size = buf.readVarInt(); Object2FloatOpenHashMap<String> map = new Object2FloatOpenHashMap<>(); for (int i = 0; i < size; i++) { map.put(buf.readUtf(), buf.readFloat()); } return map; } }
1
0.57591
1
0.57591
game-dev
MEDIA
0.412302
game-dev
0.697921
1
0.697921
cmangos/mangos-tbc
5,652
src/game/Entities/ItemEnchantmentMgr.cpp
/* * This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "Entities/ItemEnchantmentMgr.h" #include "Database/DatabaseEnv.h" #include "Log/Log.h" #include "Globals/ObjectMgr.h" #include "Util/ProgressBar.h" #include "Util/Util.h" #include <list> #include <vector> struct EnchStoreItem { uint32 ench; float chance; EnchStoreItem() : ench(0), chance(0) {} EnchStoreItem(uint32 _ench, float _chance) : ench(_ench), chance(_chance) {} }; typedef std::vector<EnchStoreItem> EnchStoreList; typedef std::unordered_map<uint32, EnchStoreList> EnchantmentStore; static EnchantmentStore RandomItemEnch; void LoadRandomEnchantmentsTable() { RandomItemEnch.clear(); // for reload case uint32 count = 0; auto queryResult = WorldDatabase.Query("SELECT entry, ench, chance FROM item_enchantment_template"); if (queryResult) { BarGoLink bar(queryResult->GetRowCount()); do { Field* fields = queryResult->Fetch(); bar.step(); uint32 entry = fields[0].GetUInt32(); uint32 ench = fields[1].GetUInt32(); float chance = fields[2].GetFloat(); if (chance > 0.000001f && chance <= 100.0f) RandomItemEnch[entry].push_back(EnchStoreItem(ench, chance)); ++count; } while (queryResult->NextRow()); sLog.outString(">> Loaded %u Item Enchantment definitions", count); } else sLog.outErrorDb(">> Loaded 0 Item Enchantment definitions. DB table `item_enchantment_template` is empty."); sLog.outString(); } uint32 GetItemEnchantMod(uint32 entry) { if (!entry) return 0; EnchantmentStore::const_iterator tab = RandomItemEnch.find(entry); if (tab == RandomItemEnch.end()) { sLog.outErrorDb("Item RandomProperty / RandomSuffix id #%u used in `item_template` but it doesn't have records in `item_enchantment_template` table.", entry); return 0; } double dRoll = rand_chance(); float fCount = 0; const EnchStoreList& enchantList = tab->second; for (auto ench_iter : enchantList) { fCount += ench_iter.chance; if (fCount > dRoll) return ench_iter.ench; } // we could get here only if sum of all enchantment chances is lower than 100% dRoll = (irand(0, (int)floor(fCount * 100) + 1)) / 100; fCount = 0; for (auto ench_iter : enchantList) { fCount += ench_iter.chance; if (fCount > dRoll) return ench_iter.ench; } return 0; } uint32 GenerateEnchSuffixFactor(uint32 item_id) { ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_id); if (!itemProto) return 0; if (!itemProto->RandomSuffix) return 0; RandomPropertiesPointsEntry const* randomProperty = sRandomPropertiesPointsStore.LookupEntry(itemProto->ItemLevel); if (!randomProperty) return 0; uint32 suffixFactor; switch (itemProto->InventoryType) { // Items of that type don`t have points case INVTYPE_NON_EQUIP: case INVTYPE_BAG: case INVTYPE_TABARD: case INVTYPE_AMMO: case INVTYPE_QUIVER: case INVTYPE_RELIC: return 0; // Select point coefficient case INVTYPE_HEAD: case INVTYPE_BODY: case INVTYPE_CHEST: case INVTYPE_LEGS: case INVTYPE_2HWEAPON: case INVTYPE_ROBE: suffixFactor = 0; break; case INVTYPE_SHOULDERS: case INVTYPE_WAIST: case INVTYPE_FEET: case INVTYPE_HANDS: case INVTYPE_TRINKET: suffixFactor = 1; break; case INVTYPE_NECK: case INVTYPE_WRISTS: case INVTYPE_FINGER: case INVTYPE_SHIELD: case INVTYPE_CLOAK: case INVTYPE_HOLDABLE: suffixFactor = 2; break; case INVTYPE_WEAPON: case INVTYPE_WEAPONMAINHAND: case INVTYPE_WEAPONOFFHAND: suffixFactor = 3; break; case INVTYPE_RANGED: case INVTYPE_THROWN: case INVTYPE_RANGEDRIGHT: suffixFactor = 4; break; default: return 0; } // Select rare/epic modifier switch (itemProto->Quality) { case ITEM_QUALITY_UNCOMMON: return randomProperty->UncommonPropertiesPoints[suffixFactor]; case ITEM_QUALITY_RARE: return randomProperty->RarePropertiesPoints[suffixFactor]; case ITEM_QUALITY_EPIC: return randomProperty->EpicPropertiesPoints[suffixFactor]; case ITEM_QUALITY_LEGENDARY: case ITEM_QUALITY_ARTIFACT: return 0; // not have random properties default: break; } return 0; }
1
0.913001
1
0.913001
game-dev
MEDIA
0.872474
game-dev
0.990251
1
0.990251
Amethyst-szs/MoonFlow
8,697
MoonFlow/scene/editor/event/node/EventFlowNodeCommon.cs
using Godot; using System; using System.Collections.Generic; using Nindot.Al.EventFlow; using MoonFlow.Project; namespace MoonFlow.Scene.EditorEvent; [GlobalClass, SceneUid("uid://dn6k75166p7ua")] public partial class EventFlowNodeCommon : EventFlowNodeBase { #region Properties // ~~~~~~~~~~~ Node References ~~~~~~~~~~~ // public EventFlowNodeCommon[] Connections = []; // ~~~~~~~~~~~~~~~~~ Data ~~~~~~~~~~~~~~~~ // public Nindot.Al.EventFlow.Node Content { get; protected set; } = null; // ~~~~~~~~~ Internal References ~~~~~~~~~ // [Export, ExportGroup("Internal References")] public VBoxContainer ParamHolder { get; private set; } [Export] public VBoxContainer ParamAddDropdownHolder { get; private set; } [Export] public MenuButton NameOptionButton { get; private set; } [Export] public LineEdit NameLineEdit { get; private set; } // ~~~~~~~~~~~~~~~ Signals ~~~~~~~~~~~~~~~ // [Signal] public delegate void MetadataEditRequestEventHandler(EventFlowNodeCommon self); #endregion #region Initilization public override void _Ready() { base._Ready(); // Setup additional signal connections Connect(SignalName.MetadataEditRequest, Callable.From( new Action<EventFlowNodeCommon>(Application.OnMetadataEditRequest) )); } public override void InitContent(Nindot.Al.EventFlow.Node content, Graph graph) { // Setup state Graph = graph; Content = content; Name = content.Id.ToString(); // Setup name and type headers var labelType = GetNode<Label>("%Label_Type"); labelType.Text = Tr(Content.TypeBase, "EVENT_GRAPH_NODE_TYPE"); var labelName = GetNode<Label>("%Label_Name"); labelName.Text = Content.Name; // Setup default colors var category = MetaCategoryTable.Lookup(Content.GetFactoryType()); var color = MetaDefaultColorLookupTable.Lookup(category); RootPanel.SelfModulate = color; // Initilize properties and connections InitParamEditor(); var edgeCount = Math.Max(content.GetNextIdCount(), content.GetMaxOutgoingEdges()); for (var i = 0; i < edgeCount; i++) CreatePortOut(); DrawDebugLabel(); // Ensure connection array has enough space for ports Array.Resize(ref Connections, edgeCount); } public override void InitContent(string entryName, Graph graph, EventFlowNodeCommon target) { throw new NotImplementedException("Wrong InitContent call! Use EventFlowEntryPoint class or correct init"); } public override void SetupConnections(List<EventFlowNodeCommon> list) { if (list.Count > Connections.Length) Array.Resize(ref Connections, list.Count); for (int i = 0; i < Math.Min(list.Count, PortOutList.GetChildCount()); i++) { if (list[i] == null) continue; var port = PortOutList.GetChild(i) as PortOut; port.Connection = list[i]; } } protected override void InitParamEditor() { // Setup node name selection var nameType = Content.GetNodeNameOptions(out string[] options); switch (nameType) { case Nindot.Al.EventFlow.Node.NodeOptionType.NO_OPTIONS: NameOptionButton.QueueFree(); NameLineEdit.QueueFree(); break; case Nindot.Al.EventFlow.Node.NodeOptionType.PRESET_LIST: SetupNameOptions(options); if (IsInstanceValid(NameLineEdit)) NameLineEdit.QueueFree(); break; case Nindot.Al.EventFlow.Node.NodeOptionType.ANY_VALUE: if (IsInstanceValid(NameOptionButton)) NameOptionButton.QueueFree(); GetNode<Label>("%Label_Name").Hide(); if (!NameLineEdit.HasMeta("InitComplete")) { NameLineEdit.Text = Content.Name; NameLineEdit.SetMeta("InitComplete", true); } break; } // Reset current param editors ParamHolder.Show(); FoldableContainer additionalParamHolder = ParamAddDropdownHolder.GetParent() as FoldableContainer; additionalParamHolder.Show(); foreach (var child in ParamHolder.GetChildren()) child.QueueFree(); foreach (var child in ParamAddDropdownHolder.GetChildren()) child.QueueFree(); // Lookup param list for content var type = Content.GetSupportedParams(out Dictionary<string, Type> pList); if (type == Nindot.Al.EventFlow.Node.NodeOptionType.NO_OPTIONS) { additionalParamHolder.Hide(); ParamHolder.Hide(); return; } if (type == Nindot.Al.EventFlow.Node.NodeOptionType.ANY_VALUE) { additionalParamHolder.Hide(); foreach (var p in Content.Params) EventNodeParamFactory.CreateParamEditor(this, (string)p.Key, p.Value.GetType()); return; } // Create all param editors foreach (var p in pList) EventNodeParamFactory.CreateParamEditor(this, p.Key, p.Value); // If there are no additional properties to add, remove dropdown if (ParamAddDropdownHolder.GetChildCount() == 0) additionalParamHolder.Hide(); } private void SetupNameOptions(string[] opt) { if (!IsInstanceValid(NameOptionButton)) return; var popup = NameOptionButton.GetPopup(); popup.Clear(); foreach (var item in opt) popup.AddItem(item); var call = Callable.From(new Action<int>(OnSetName)); if (!popup.IsConnected(PopupMenu.SignalName.IdPressed, call)) popup.Connect(PopupMenu.SignalName.IdPressed, call); } public override bool InitContentMetadata(GraphMetaBucketCommon holder, GraphMetaBucketNode data) { if (!base.InitContentMetadata(holder, data)) { holder.Nodes.Add(Content.Id, Metadata); return false; } return true; } protected override PortOut CreatePortOut() { var port = base.CreatePortOut(); if ((Content.GetMaxOutgoingEdges() > 1 || !Content.IsForceOutgoingEdgeCount()) && PortColorList.Count > 0) { var idx = Math.Min(port.Index, PortColorList.Count - 1); port.PortColor = PortColorList[idx]; } // Ensure connection array has enough space for this port Array.Resize(ref Connections, Math.Max(port.Index + 1, Connections.Length)); return port; } #endregion #region Signals protected override void OnConnectionChanged(PortOut port, PortIn connection) { SetNodeModified(); // Clear self from current connection's incoming list Connections[port.Index]?.PortIn.RemoveIncoming(port); // Set connection Connections[port.Index] = connection?.Parent; // Add self to the new connection incoming list Connections[port.Index]?.PortIn.AddIncoming(port); if (connection == null) { Content.RemoveNextNode(port.Index); DrawDebugLabel(); return; } if (!Content.TrySetNextNode(connection.Parent.Content, port.Index)) throw new Exception("Failed to connect " + Content.Id + " to " + connection.Parent.Content.Id); DrawDebugLabel(); } public override void DeleteNode() { // Remove self from outgoing connections foreach (var con in Connections) con?.PortIn?.RemoveIncoming(this); // Remove self from incoming connections foreach (var incoming in PortIn.IncomingList) incoming?.CallDeferred("RemoveConnection"); SetNodeModified(); // Delete content and godot object Graph.RemoveNode(Content); QueueFree(); } public void OnSetName(int index) { Content.SetName(index); var labelName = GetNode<Label>("%Label_Name"); labelName.Text = Content.Name; InitParamEditor(); OnNodeNameModified(); } public void OnSetName(string name) { Content.Name = name; var labelName = GetNode<Label>("%Label_Name"); labelName.Text = Content.Name; InitParamEditor(); OnNodeNameModified(); } public void OnSetNameLineEdit(string name) { Content.Name = name; OnNodeNameModified(); DrawDebugLabel(); } protected virtual void OnNodeNameModified() { } private void OnMetadataEditRequest() { EmitSignal(SignalName.MetadataEditRequest, this); } #endregion #region Utility public override void SetNodeColor() { base.SetNodeColor(); if (!Metadata.IsOverrideColor) { // Setup default colors var category = MetaCategoryTable.Lookup(Content.GetFactoryType()); var color = MetaDefaultColorLookupTable.Lookup(category); RootPanel.SelfModulate = color; } } #endregion #region Debug protected override void DrawDebugLabel() { if (DebugDataDisplay == null) return; string txt = ""; txt += AppendDebugLabel(nameof(Type), GetType().Name); txt += AppendDebugLabel(nameof(RawPosition), RawPosition.ToString("0")); txt += AppendDebugLabel(nameof(Position), Position); if (Content != null) { txt += AppendDebugLabel(nameof(Content.Id), Content.Id) + '\n'; txt += "Next: "; foreach (var id in Content.GetNextIds()) txt += id.ToString() + ", "; txt += '\n'; txt += AppendDebugLabel(nameof(Content.TypeBase), Content.TypeBase); txt += AppendDebugLabel(nameof(Content.Name), Content.Name); txt += AppendDebugLabel("C# Type", Content.GetType().Name); } DebugDataDisplay.Text = txt; } #endregion }
1
0.930617
1
0.930617
game-dev
MEDIA
0.402225
game-dev,networking,desktop-app
0.960646
1
0.960646
phon-ca/phon
1,989
query/src/main/java/ca/phon/query/script/params/TierSelectionScriptParam.java
package ca.phon.query.script.params; import ca.phon.script.params.*; public class TierSelectionScriptParam extends ScriptParam { public static final String PROMPT_PROP = StringScriptParam.class.getName() + ".promptText"; public static final String VALIDATE_PROP = StringScriptParam.class.getName() + ".validate"; public static final String TOOLTIP_TEXT_PROP = StringScriptParam.class.getName() + ".tooltipText"; private String promptText = new String(); private boolean validate = true; private boolean required = false; private String tooltipText = null; public TierSelectionScriptParam(String id, String title, String def) { super(); setParamType("tierselect"); setParamDesc(title); setValue(id, null); setDefaultValue(id, def); } public String getTier() { return (String) this.getValue(getParamId()); } public void setTier(String tier) { setValue(getParamId(), tier); } public void setPrompt(String text) { String oldText = promptText; promptText = text; super.propSupport.firePropertyChange(PROMPT_PROP, oldText, text); } public String getPrompt() { return this.promptText; } public boolean isValidate() { return (isRequired() ? getValue(getParamId()).toString().length() > 0 && validate : validate); } public boolean isRequired() { return this.required; } public void setRequired(boolean required) { this.required = required; } public void setValidate(boolean validate) { boolean old = this.validate; this.validate = validate; super.propSupport.firePropertyChange(VALIDATE_PROP, old, this.validate); } public void setTooltipText(String tooltipText) { String oldVal = this.tooltipText; this.tooltipText = tooltipText; super.propSupport.firePropertyChange(TOOLTIP_TEXT_PROP, oldVal, this.tooltipText); } public String getTooltipText() { return this.tooltipText; } @Override public String getStringRepresentation() { return "{tierselect " + super.getValue(super.getParamId()) + "}"; } }
1
0.817986
1
0.817986
game-dev
MEDIA
0.354398
game-dev
0.827832
1
0.827832
sebas77/Svelto.MiniExamples
23,272
Example8-NET-ComputeSharp/Svelto/com.sebaslab.svelto.ecs/Core/SpecialEnumerators/DoubleIterationEnumerator.cs
using System; using Svelto.ECS.Internal; namespace Svelto.ECS { public readonly ref struct DoubleEntitiesEnumerator<T1> where T1 : struct, _IInternalEntityComponent { public DoubleEntitiesEnumerator(GroupsEnumerable<T1> groupsEnumerable) { _groupsEnumerable = groupsEnumerable; } public EntityGroupsIterator GetEnumerator() { return new EntityGroupsIterator(_groupsEnumerable); } readonly GroupsEnumerable<T1> _groupsEnumerable; public ref struct EntityGroupsIterator { public EntityGroupsIterator(GroupsEnumerable<T1> groupsEnumerable) : this() { _groupsEnumerableA = groupsEnumerable.GetEnumerator(); _groupsEnumerableA.MoveNext(); _groupsEnumerableB = _groupsEnumerableA; _indexA = 0; _indexB = 0; } public bool MoveNext() { //once GroupEnumerables complete, they reset. If they reset and moveNext doesn't happen, they are invalid while (_groupsEnumerableA.isValid) { var (buffersA, _) = _groupsEnumerableA.Current; var (buffersB, _) = _groupsEnumerableB.Current; //current index A must iterate as long as is less than the current A group count while (_indexA < buffersA.count) { //current index B must iterate as long as is less than the current B group count if (++_indexB < buffersB.count) { return true; } //if B iteration is over, move to the next group if (_groupsEnumerableB.MoveNext() == false) { //if there is no valid next groups, we reset B and we need to move to the next A element _groupsEnumerableB = _groupsEnumerableA; (buffersB, _) = _groupsEnumerableB.Current; ++_indexA; //next A element _indexB = _indexA; } else //otherwise the current A will be checked against the new B group. IndexB must be reset //to work on the new group { _indexB = -1; } } //the current group A iteration is done, so we move to the next A group if (_groupsEnumerableA.MoveNext() == true) { //there is a new group, we reset the iteration _indexA = 0; _indexB = 0; _groupsEnumerableB = _groupsEnumerableA; } else return false; } return false; } public void Reset() { throw new Exception(); } public ValueRef Current { get { var valueRef = new ValueRef(_groupsEnumerableA.Current, _indexA, _groupsEnumerableB.Current , _indexB); return valueRef; } } public void Dispose() { } GroupsEnumerable<T1>.GroupsIterator _groupsEnumerableA; GroupsEnumerable<T1>.GroupsIterator _groupsEnumerableB; int _indexA; int _indexB; } public readonly ref struct ValueRef { readonly GroupsEnumerable<T1>.RefCurrent _current; readonly int _indexA; readonly GroupsEnumerable<T1>.RefCurrent _refCurrent; readonly int _indexB; public ValueRef (GroupsEnumerable<T1>.RefCurrent current, int indexA, GroupsEnumerable<T1>.RefCurrent refCurrent , int indexB) { _current = current; _indexA = indexA; _refCurrent = refCurrent; _indexB = indexB; } public void Deconstruct (out EntityCollection<T1> buffers, out int indexA, out EntityCollection<T1> refCurrent, out int indexB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; } public void Deconstruct (out EntityCollection<T1> buffers, out int indexA, out ExclusiveGroupStruct groupA , out EntityCollection<T1> refCurrent, out int indexB, out ExclusiveGroupStruct groupB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; groupA = _current._group; groupB = _refCurrent._group; } } } public readonly ref struct DoubleIterationEnumerator<T1, T2> where T1 : struct, _IInternalEntityComponent where T2 : struct, _IInternalEntityComponent { public DoubleIterationEnumerator(GroupsEnumerable<T1, T2> groupsEnumerable) { _groupsEnumerable = groupsEnumerable; } public EntityGroupsIterator GetEnumerator() { return new EntityGroupsIterator(_groupsEnumerable); } readonly GroupsEnumerable<T1, T2> _groupsEnumerable; public ref struct EntityGroupsIterator { public EntityGroupsIterator(GroupsEnumerable<T1, T2> groupsEnumerable) : this() { _groupsEnumerableA = groupsEnumerable.GetEnumerator(); _groupsEnumerableA.MoveNext(); _groupsEnumerableB = _groupsEnumerableA; _indexA = 0; _indexB = 0; } public bool MoveNext() { //once GroupEnumerables complete, they reset. If they reset and moveNext doesn't happen, they are invalid while (_groupsEnumerableA.isValid) { var (buffersA, _) = _groupsEnumerableA.Current; var (buffersB, _) = _groupsEnumerableB.Current; //current index A must iterate as long as is less than the current A group count while (_indexA < buffersA.count) { //current index B must iterate as long as is less than the current B group count if (++_indexB < buffersB.count) { return true; } //if B iteration is over, move to the next group if (_groupsEnumerableB.MoveNext() == false) { //if there is no valid next groups, we reset B and we need to move to the next A element _groupsEnumerableB = _groupsEnumerableA; (buffersB, _) = _groupsEnumerableB.Current; ++_indexA; //next A element _indexB = _indexA; } else //otherwise the current A will be checked against the new B group. IndexB must be reset //to work on the new group { _indexB = -1; } } //the current group A iteration is done, so we move to the next A group if (_groupsEnumerableA.MoveNext() == true) { //there is a new group, we reset the iteration _indexA = 0; _indexB = 0; _groupsEnumerableB = _groupsEnumerableA; } else return false; } return false; } public void Reset() { throw new Exception(); } public ValueRef Current { get { var valueRef = new ValueRef(_groupsEnumerableA.Current, _indexA, _groupsEnumerableB.Current , _indexB); return valueRef; } } public void Dispose() { } GroupsEnumerable<T1, T2>.GroupsIterator _groupsEnumerableA; GroupsEnumerable<T1, T2>.GroupsIterator _groupsEnumerableB; int _indexA; int _indexB; } public readonly ref struct ValueRef { public readonly GroupsEnumerable<T1, T2>.RefCurrent _current; public readonly int _indexA; public readonly GroupsEnumerable<T1, T2>.RefCurrent _refCurrent; public readonly int _indexB; public ValueRef (GroupsEnumerable<T1, T2>.RefCurrent current, int indexA, GroupsEnumerable<T1, T2>.RefCurrent refCurrent , int indexB) { _current = current; _indexA = indexA; _refCurrent = refCurrent; _indexB = indexB; } public void Deconstruct(out EntityCollection<T1, T2> buffers, out int indexA, out EntityCollection<T1, T2> refCurrent, out int indexB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; } public void Deconstruct (out EntityCollection<T1, T2> buffers, out int indexA, out ExclusiveGroupStruct groupA , out EntityCollection<T1, T2> refCurrent, out int indexB, out ExclusiveGroupStruct groupB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; groupA = _current._group; groupB = _refCurrent._group; } } } /// <summary> /// Special Enumerator to iterate a group of entities against themselves with complexity n*(n+1)/2 (skips already tested couples) /// </summary> /// <typeparam name="T1"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> public readonly ref struct DoubleEntitiesEnumerator<T1, T2, T3> where T1 : struct, _IInternalEntityComponent where T2 : struct, _IInternalEntityComponent where T3 : struct, _IInternalEntityComponent { public DoubleEntitiesEnumerator(GroupsEnumerable<T1, T2, T3> groupsEnumerable) { _groupsEnumerable = groupsEnumerable; } public EntityGroupsIterator GetEnumerator() { return new EntityGroupsIterator(_groupsEnumerable); } readonly GroupsEnumerable<T1, T2, T3> _groupsEnumerable; public ref struct EntityGroupsIterator { public EntityGroupsIterator(GroupsEnumerable<T1, T2, T3> groupsEnumerable) : this() { _groupsEnumerableA = groupsEnumerable.GetEnumerator(); _groupsEnumerableA.MoveNext(); _groupsEnumerableB = _groupsEnumerableA; _indexA = 0; _indexB = 0; } public bool MoveNext() { //once GroupEnumerables complete, they reset. If they reset and moveNext doesn't happen, they are invalid while (_groupsEnumerableA.isValid) { var (buffersA, _) = _groupsEnumerableA.Current; var (buffersB, _) = _groupsEnumerableB.Current; //current index A must iterate as long as is less than the current A group count while (_indexA < buffersA.count) { //current index B must iterate as long as is less than the current B group count if (++_indexB < buffersB.count) { return true; } //if B iteration is over, move to the next group if (_groupsEnumerableB.MoveNext() == false) { //if there is no valid next groups, we reset B and we need to move to the next A element _groupsEnumerableB = _groupsEnumerableA; (buffersB, _) = _groupsEnumerableB.Current; ++_indexA; //next A element _indexB = _indexA; } else //otherwise the current A will be checked against the new B group. IndexB must be reset //to work on the new group { _indexB = -1; } } //the current group A iteration is done, so we move to the next A group if (_groupsEnumerableA.MoveNext() == true) { //there is a new group, we reset the iteration _indexA = 0; _indexB = 0; _groupsEnumerableB = _groupsEnumerableA; } else return false; } return false; } public void Reset() { throw new Exception(); } public ValueRef Current { get { var valueRef = new ValueRef(_groupsEnumerableA.Current, _indexA, _groupsEnumerableB.Current , _indexB); return valueRef; } } public void Dispose() { } GroupsEnumerable<T1, T2, T3>.GroupsIterator _groupsEnumerableA; GroupsEnumerable<T1, T2, T3>.GroupsIterator _groupsEnumerableB; int _indexA; int _indexB; } public readonly ref struct ValueRef { readonly GroupsEnumerable<T1, T2, T3>.RefCurrent _current; readonly int _indexA; readonly GroupsEnumerable<T1, T2, T3>.RefCurrent _refCurrent; readonly int _indexB; public ValueRef (GroupsEnumerable<T1, T2, T3>.RefCurrent current, int indexA , GroupsEnumerable<T1, T2, T3>.RefCurrent refCurrent, int indexB) { _current = current; _indexA = indexA; _refCurrent = refCurrent; _indexB = indexB; } public void Deconstruct (out EntityCollection<T1, T2, T3> buffers, out int indexA, out EntityCollection<T1, T2, T3> refCurrent , out int indexB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; } public void Deconstruct (out EntityCollection<T1, T2, T3> buffers, out int indexA, out ExclusiveGroupStruct groupA , out EntityCollection<T1, T2, T3> refCurrent, out int indexB, out ExclusiveGroupStruct groupB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; groupA = _current._group; groupB = _refCurrent._group; } } } /// <summary> /// Special Enumerator to iterate a group of entities against themselves with complexity n*(n+1)/2 (skips already tested couples) /// </summary> /// <typeparam name="T1"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> public readonly ref struct DoubleEntitiesEnumerator<T1, T2, T3, T4> where T1 : struct, _IInternalEntityComponent where T2 : struct, _IInternalEntityComponent where T3 : struct, _IInternalEntityComponent where T4 : struct, _IInternalEntityComponent { public DoubleEntitiesEnumerator(GroupsEnumerable<T1, T2, T3, T4> groupsEnumerable) { _groupsEnumerable = groupsEnumerable; } public EntityGroupsIterator GetEnumerator() { return new EntityGroupsIterator(_groupsEnumerable); } readonly GroupsEnumerable<T1, T2, T3, T4> _groupsEnumerable; public ref struct EntityGroupsIterator { public EntityGroupsIterator(GroupsEnumerable<T1, T2, T3, T4> groupsEnumerable) : this() { _groupsEnumerableA = groupsEnumerable.GetEnumerator(); _groupsEnumerableA.MoveNext(); _groupsEnumerableB = _groupsEnumerableA; _indexA = 0; _indexB = 0; } public bool MoveNext() { //once GroupEnumerables complete, they reset. If they reset and moveNext doesn't happen, they are invalid while (_groupsEnumerableA.isValid) { var (buffersA, _) = _groupsEnumerableA.Current; var (buffersB, _) = _groupsEnumerableB.Current; //current index A must iterate as long as is less than the current A group count while (_indexA < buffersA.count) { //current index B must iterate as long as is less than the current B group count if (++_indexB < buffersB.count) { return true; } //if B iteration is over, move to the next group if (_groupsEnumerableB.MoveNext() == false) { //if there is no valid next groups, we reset B and we need to move to the next A element _groupsEnumerableB = _groupsEnumerableA; (buffersB, _) = _groupsEnumerableB.Current; ++_indexA; //next A element _indexB = _indexA; } else //otherwise the current A will be checked against the new B group. IndexB must be reset //to work on the new group { _indexB = -1; } } //the current group A iteration is done, so we move to the next A group if (_groupsEnumerableA.MoveNext() == true) { //there is a new group, we reset the iteration _indexA = 0; _indexB = 0; _groupsEnumerableB = _groupsEnumerableA; } else return false; } return false; } public void Reset() { throw new Exception(); } public ValueRef Current { get { var valueRef = new ValueRef(_groupsEnumerableA.Current, _indexA, _groupsEnumerableB.Current , _indexB); return valueRef; } } public void Dispose() { } GroupsEnumerable<T1, T2, T3, T4>.GroupsIterator _groupsEnumerableA; GroupsEnumerable<T1, T2, T3, T4>.GroupsIterator _groupsEnumerableB; int _indexA; int _indexB; } public ref struct ValueRef { public readonly GroupsEnumerable<T1, T2, T3, T4>.RefCurrent _current; public readonly int _indexA; public readonly GroupsEnumerable<T1, T2, T3, T4>.RefCurrent _refCurrent; public readonly int _indexB; public ValueRef (GroupsEnumerable<T1, T2, T3, T4>.RefCurrent current, int indexA , GroupsEnumerable<T1, T2, T3, T4>.RefCurrent refCurrent, int indexB) { _current = current; _indexA = indexA; _refCurrent = refCurrent; _indexB = indexB; } public void Deconstruct (out EntityCollection<T1, T2, T3, T4> buffers, out int indexA, out EntityCollection<T1, T2, T3, T4> refCurrent , out int indexB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; } public void Deconstruct (out EntityCollection<T1, T2, T3, T4> buffers, out int indexA, out ExclusiveGroupStruct groupA , out EntityCollection<T1, T2, T3, T4> refCurrent, out int indexB, out ExclusiveGroupStruct groupB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; groupA = _current._group; groupB = _refCurrent._group; } } } }
1
0.843699
1
0.843699
game-dev
MEDIA
0.564564
game-dev
0.844592
1
0.844592
Roll20/roll20-api-scripts
73,663
Its A Trap/3.5.1/ItsATrap.js
/** * Initialize the state for the It's A Trap script. */ (() => { 'use strict'; /** * The ItsATrap state data. * @typedef {object} ItsATrapState * @property {object} noticedTraps * The set of IDs for traps that have been noticed by passive perception. * @property {string} theme * The name of the TrapTheme currently being used. */ state.ItsATrap = state.ItsATrap || {}; _.defaults(state.ItsATrap, { noticedTraps: {}, userOptions: {} }); _.defaults(state.ItsATrap.userOptions, { revealTrapsToMap: false, announcer: 'Admiral Ackbar' }); // Set the theme from the useroptions. let useroptions = globalconfig && globalconfig.itsatrap; if(useroptions) { state.ItsATrap.userOptions = { revealTrapsToMap: useroptions.revealTrapsToMap === 'true' || false, announcer: useroptions.announcer || 'Admiral Ackbar' }; } })(); /** * The main interface and bootstrap script for It's A Trap. */ var ItsATrap = (() => { 'use strict'; const REMOTE_ACTIVATE_CMD = '!itsATrapRemoteActivate'; // The collection of registered TrapThemes keyed by name. let trapThemes = {}; // The installed trap theme that is being used. let curTheme = 'default'; /** * Activates a trap. * @param {Graphic} trap * @param {Graphic} [activatingVictim] * The victim that triggered the trap. */ function activateTrap(trap, activatingVictim) { let theme = getTheme(); // Apply the trap's effects to any victims in its area and to the // activating victim, using the configured trap theme. let victims = getTrapVictims(trap, activatingVictim); if(victims.length > 0) _.each(victims, victim => { let effect = new TrapEffect(trap, victim); theme.activateEffect(effect); }); else { // In the absence of any victims, activate the trap with the default // theme, which will only display the trap's message. let defaultTheme = trapThemes['default']; let effect = new TrapEffect(trap); defaultTheme.activateEffect(effect); } } /** * Checks if a token passively searched for any traps during its last * movement. * @private * @param {TrapTheme} theme * @param {Graphic} token */ function _checkPassiveSearch(theme, token) { if(theme.passiveSearch && theme.passiveSearch !== _.noop) { _.chain(getSearchableTraps(token)) .filter(trap => { // Only search for traps that are close enough to be spotted. let effect = new TrapEffect(trap, token); let dist = getSearchDistance(token, trap); let searchDist = trap.get('aura2_radius') || effect.searchDist; return (!searchDist || dist < searchDist); }) .each(trap => { theme.passiveSearch(trap, token); }); } } /** * Checks if a token activated or passively spotted any traps during * its last movement. * @private * @param {Graphic} token */ function _checkTrapInteractions(token) { // Objects on the GM layer don't set off traps. if(token.get("layer") === "objects") { try { let theme = getTheme(); if(!theme) { log('ERROR - It\'s A Trap!: TrapTheme does not exist - ' + curTheme + '. Using default TrapTheme.'); theme = trapThemes['default']; } // Did the character set off a trap? _checkTrapActivations(theme, token); // If the theme has passive searching, do a passive search for traps. _checkPassiveSearch(theme, token); } catch(err) { log('ERROR - It\'s A Trap!: ' + err.message); log(err.stack); } } } /** * Checks if a token activated any traps during its last movement. * @private * @param {TrapTheme} theme * @param {Graphic} token */ function _checkTrapActivations(theme, token) { let collisions = getTrapCollisions(token); _.find(collisions, collision => { let trap = collision.other; // Skip if the trap is disabled. if(trap.get('status_interdiction')) return false; let trapEffect = (new TrapEffect(trap, token)).json; trapEffect.stopAt = trapEffect.stopAt || 'center'; // Figure out where to stop the token. if(trapEffect.stopAt === 'edge' && !trapEffect.gmOnly) { let x = collision.pt[0]; let y = collision.pt[1]; token.set("lastmove",""); token.set("left", x); token.set("top", y); } else if(trapEffect.stopAt === 'center' && !trapEffect.gmOnly) { let x = trap.get("left"); let y = trap.get("top"); token.set("lastmove",""); token.set("left", x); token.set("top", y); } // Apply the trap's effects to any victims in its area. if(collision.triggeredByPath) activateTrap(trap); else activateTrap(trap, token); // Stop activating traps if this trap stopped the token. return (trapEffect.stopAt !== 'none'); }); } /** * Gets the point for a token. * @private * @param {Graphic} token * @return {vec3} */ function _getPt(token) { return [token.get('left'), token.get('top'), 1]; } /** * Gets all the traps that a token has line-of-sight to, with no limit for * range. Line-of-sight is blocked by paths on the dynamic lighting layer. * @param {Graphic} charToken * @return {Graphic[]} * The list of traps that charToken has line-of-sight to. */ function getSearchableTraps(charToken) { let pageId = charToken.get('_pageid'); let traps = getTrapsOnPage(pageId); return LineOfSight.filterTokens(charToken, traps); } /** * Gets the distance between two tokens in their page's units. * @param {Graphic} token1 * @param {Graphic} token2 * @return {number} */ function getSearchDistance(token1, token2) { let p1 = _getPt(token1); let p2 = _getPt(token2); let r1 = token1.get('width')/2; let r2 = token2.get('width')/2; let page = getObj('page', token1.get('_pageid')); let scale = page.get('scale_number'); let pixelDist = Math.max(0, VecMath.dist(p1, p2) - r1 - r2); return pixelDist/70*scale; } /** * Gets the theme currently being used to interpret TrapEffects spawned * when a character activates a trap. * @return {TrapTheme} */ function getTheme() { return trapThemes[curTheme]; } /** * Returns the list of all traps a token would collide with during its last * movement. The traps are sorted in the order that the token will collide * with them. * @param {Graphic} token * @return {TokenCollisions.Collision[]} */ function getTrapCollisions(token) { let pageId = token.get('_pageid'); let traps = getTrapsOnPage(pageId); // A llambda to test if a token is flying. let isFlying = x => { return x.get("status_fluffy-wing"); }; let pathsToTraps = {}; // Some traps don't affect flying tokens. traps = _.chain(traps) .filter(trap => { return !isFlying(token) || isFlying(trap); }) // Use paths for collisions if trigger paths are set. .map(trap => { let effect = new TrapEffect(trap); if(effect.triggerPaths) { return _.map(effect.triggerPaths, id => { if(pathsToTraps[id]) pathsToTraps[id].push(trap); else pathsToTraps[id] = [trap]; return getObj('path', id) || trap; }); } else return trap; }) .flatten() .value(); // Get the collisions. return _.chain(TokenCollisions.getCollisions(token, traps, {detailed: true})) .map(collision => { // Convert path collisions back into trap token collisions. if(collision.other.get('_type') === 'path') { let pathId = collision.other.get('_id'); return _.map(pathsToTraps[pathId], trap => { return { token: collision.token, other: trap, pt: collision.pt, dist: collision.dist, triggeredByPath: true }; }); } else return collision; }) .flatten() .value(); } /** * Gets the list of all the traps on the specified page. * @param {string} pageId * @return {Graphic[]} */ function getTrapsOnPage(pageId) { return findObjs({ _pageid: pageId, _type: "graphic", status_cobweb: true, layer: "gmlayer" }); } /** * Gets the list of victims within an activated trap's area of effect. * @param {Graphic} trap * @param {Graphic} triggerVictim * @return {Graphic[]} */ function getTrapVictims(trap, triggerVictim) { let range = trap.get('aura1_radius'); let pageId = trap.get('_pageid'); let victims = [triggerVictim]; if(range !== '') { let otherTokens = findObjs({ _pageid: pageId, _type: 'graphic', layer: 'objects' }); let pageScale = getObj('page', pageId).get('scale_number'); range *= 70/pageScale; let squareArea = trap.get('aura1_square'); victims = victims.concat(LineOfSight.filterTokens(trap, otherTokens, range, squareArea)); } return _.chain(victims) .unique() .compact() .value(); } /** * Marks a trap with a circle and a ping. * @private * @param {Graphic} trap */ function _markTrap(trap) { let radius = trap.get('width')/2; let x = trap.get('left'); let y = trap.get('top'); let pageId = trap.get('_pageid'); // Circle the trap's trigger area. let circle = new PathMath.Circle([x, y, 1], radius); circle.render(pageId, 'objects', { stroke: '#ffff00', // yellow stroke_width: 5 }); sendPing(x, y, pageId); } /** * Marks a trap as being noticed by a character's passive search. * @param {Graphic} trap * @param {string} noticeMessage A message to display when the trap is noticed. * @return {boolean} * true if the trap has not been noticed yet. */ function noticeTrap(trap, noticeMessage) { let id = trap.get('_id'); let effect = new TrapEffect(trap); let announcer = state.ItsATrap.userOptions.announcer; if(!state.ItsATrap.noticedTraps[id]) { state.ItsATrap.noticedTraps[id] = true; sendChat(announcer, noticeMessage); if(effect.revealWhenSpotted) revealTrap(trap); else _markTrap(trap); return true; } else return false; } /** * Registers a TrapTheme. * @param {TrapTheme} theme */ function registerTheme(theme) { log('It\'s A Trap!: Registered TrapTheme - ' + theme.name + '.'); trapThemes[theme.name] = theme; curTheme = theme.name; } /** * Reveals a trap to the objects or map layer. * @param {Graphic} trap */ function revealTrap(trap) { let effect = new TrapEffect(trap); if(effect.revealLayer === 'objects') { trap.set('layer', 'objects'); toBack(trap); } else { trap.set('layer', 'map'); toFront(trap); } sendPing(trap.get('left'), trap.get('top'), trap.get('_pageid')); } /** * Removes a trap from the state's collection of noticed traps. * @private * @param {Graphic} trap */ function _unNoticeTrap(trap) { let id = trap.get('_id'); if(state.ItsATrap.noticedTraps[id]) delete state.ItsATrap.noticedTraps[id]; } // Create macro for the remote activation command. on('ready', () => { let numRetries = 3; let interval = setInterval(() => { let theme = getTheme(); if(theme) { log(`☒☠☒ Initialized It's A Trap! using theme '${getTheme().name}' ☒☠☒`); clearInterval(interval); } else if(numRetries > 0) numRetries--; else clearInterval(interval); }, 1000); }); // Handle macro commands. on('chat:message', msg => { try { if(msg.content === REMOTE_ACTIVATE_CMD) { let theme = getTheme(); _.each(msg.selected, item => { let trap = getObj('graphic', item._id); activateTrap(trap); }); } } catch(err) { log(`It's A Trap ERROR: ${err.msg}`); log(err.stack); } }); /** * When a graphic on the objects layer moves, run the script to see if it * passed through any traps. */ on("change:graphic:lastmove", function(token) { try { // Check for trap interactions if the token isn't also a trap. if(!token.get('status_cobweb')) _checkTrapInteractions(token); } catch(err) { log(`It's A Trap ERROR: ${err.msg}`); log(err.stack); } }); // If a trap is moved back to the GM layer, remove it from the set of noticed traps. on('change:graphic:layer', token => { if(token.get('layer') === 'gmlayer') _unNoticeTrap(token); }); // When a trap's token is destroyed, remove it from the set of noticed traps. on('destroy:graphic', function(token) { _unNoticeTrap(token); }); return { activateTrap, getSearchDistance, getTheme, getTrapCollisions, getTrapsOnPage, noticeTrap, registerTheme, revealTrap, REMOTE_ACTIVATE_CMD }; })(); /** * The configured JSON properties of a trap. This can be extended to add * additional properties for system-specific themes. */ var TrapEffect = (() => { 'use strict'; const DEFAULT_FX = { maxParticles: 100, emissionRate: 3, size: 35, sizeRandom: 15, lifeSpan: 10, lifeSpanRandom: 3, speed: 3, speedRandom: 1.5, gravity: {x: 0.01, y: 0.01}, angle: 0, angleRandom: 180, duration: -1, startColour: [220, 35, 0, 1], startColourRandom: [62, 0, 0, 0.25], endColour: [220, 35, 0, 0], endColourRandom:[60, 60, 60, 0] }; return class TrapEffect { /** * An API chat command that will be executed when the trap is activated. * If the constants TRAP_ID and VICTIM_ID are provided, * they will be replaced by the IDs for the trap token and the token for * the trap's victim, respectively in the API chat command message. * @type {string} */ get api() { return this._effect.api; } /** * Specifications for an AreasOfEffect script graphic that is spawned * when a trap is triggered. * @typedef {object} TrapEffect.AreaOfEffect * @property {String} name The name of the AoE effect. * @property {vec2} [direction] The direction of the effect. If omitted, * it will be extended toward the triggering token. */ /** * JSON defining a graphic to spawn with the AreasOfEffect script if * it is installed and the trap is triggered. * @type {TrapEffect.AreaOfEffect} */ get areaOfEffect() { return this._effect.areaOfEffect; } /** * Configuration for special FX that are created when the trap activates. * @type {object} * @property {(string | FxJsonDefinition)} name * Either the name of the FX that is created * (built-in or user-made), or a custom FX JSON defintion. * @property {vec2} offset * The offset of the special FX, in units from the trap's token. * @property {vec2} direction * For beam-like FX, this specifies the vector for the FX's * direction. If left blank, it will fire towards the token * that activated the trap. */ get fx() { return this._effect.fx; } /** * Whether the trap should only be announced to the GM when it is activated. * @type {boolean} */ get gmOnly() { return this._effect.gmOnly; } /** * Gets a copy of the trap's JSON properties. * @readonly * @type {object} */ get json() { return _.clone(this._effect); } /** * JSON defining options to produce an explosion/implosion effect with * the KABOOM script. * @type {object} */ get kaboom() { return this._effect.kaboom; } /** * The flavor message displayed when the trap is activated. If left * blank, a default message will be generated based on the name of the * trap's token. * @type {string} */ get message() { return this._effect.message || this._createDefaultTrapMessage(); } /** * The trap's name. * @type {string} */ get name() { return this._trap.get('name'); } /** * Secret notes for the GM. * @type {string} */ get notes() { return this._effect.notes; } /** * The layer that the trap gets revealed to. * @type {string} */ get revealLayer() { return this._effect.revealLayer; } /** * Whether the trap is revealed when it is spotted. * @type {boolean} */ get revealWhenSpotted() { return this._effect.revealWhenSpotted; } /** * The name of a sound played when the trap is activated. * @type {string} */ get sound() { return this._effect.sound; } /** * This is where the trap stops the token. * If "edge", then the token is stopped at the trap's edge. * If "center", then the token is stopped at the trap's center. * If "none", the token is not stopped by the trap. * @type {string} */ get stopAt() { return this._effect.stopAt; } /** * Command arguments for integration with the TokenMod script by The Aaron. * @type {string} */ get tokenMod() { return this._effect.tokenMod; } /** * The trap this TrapEffect represents. * @type {Graphic} */ get trap() { return this._trap; } /** * The ID of the trap. * @type {uuid} */ get trapId() { return this._trap.get('_id'); } /** * A list of path IDs defining an area that triggers this trap. * @type {string[]} */ get triggerPaths() { return this._effect.triggerPaths; } /** * A list of names or IDs for traps that will also be triggered when this * trap is activated. * @type {string[]} */ get triggers() { return this._effect.triggers; } /** * The name for the trap/secret's type displayed in automated messages. * @type {string} */ get type() { return this._effect.type; } /** * The victim who activated the trap. * @type {Graphic} */ get victim() { return this._victim; } /** * The ID of the trap's victim. * @type {uuid} */ get victimId() { return this._victim && this._victim.get('_id'); } /** * @param {Graphic} trap * The trap's token. * @param {Graphic} [victim] * The token for the character that activated the trap. */ constructor(trap, victim) { let effect = {}; // URI-escape the notes and remove the HTML elements. let notes = trap.get('gmnotes'); try { notes = decodeURIComponent(notes).trim(); } catch(err) { notes = unescape(notes).trim(); } if(notes) { try { notes = notes.split(/<[/]?.+?>/g).join(''); effect = JSON.parse(notes); } catch(err) { effect.message = 'ERROR: invalid TrapEffect JSON.'; } } this._effect = effect; this._trap = trap; this._victim = victim; } /** * Activates the traps that are triggered by this trap. */ activateTriggers() { let triggers = this.triggers; if(triggers) { let otherTraps = ItsATrap.getTrapsOnPage(this._trap.get('_pageid')); let triggeredTraps = _.filter(otherTraps, trap => { // Skip if the trap is disabled. if(trap.get('status_interdiction')) return false; return triggers.indexOf(trap.get('name')) !== -1 || triggers.indexOf(trap.get('_id')) !== -1; }); _.each(triggeredTraps, trap => { ItsATrap.activateTrap(trap); }); } } /** * Announces the activated trap. * This should be called by TrapThemes to inform everyone about a trap * that has been triggered and its results. Fancy HTML formatting for * the message is encouraged. If the trap's effect has gmOnly set, * then the message will only be shown to the GM. * This also takes care of playing the trap's sound, FX, and API command, * they are provided. * @param {string} [message] * The message for the trap results displayed in the chat. If * omitted, then the trap's raw message will be displayed. */ announce(message) { message = message || this.message; let announcer = state.ItsATrap.userOptions.announcer; // Display the message to everyone, unless it's a secret. if(this.gmOnly) { message = '/w gm ' + message; sendChat(announcer, message); // Whisper any secret notes to the GM. if(this.notes) sendChat(announcer, '/w gm Trap Notes:<br/>' + this.notes); } else { sendChat(announcer, message); // Whisper any secret notes to the GM. if(this.notes) sendChat(announcer, '/w gm Trap Notes:<br/>' + this.notes); // Reveal the trap if it's set to become visible. if(this.trap.get('status_bleeding-eye')) ItsATrap.revealTrap(this.trap); // Produce special outputs if it has any. this.playSound(); this.playFX(); this.playAreaOfEffect(); this.playKaboom(); this.playTokenMod(); this.playApi(); // Allow traps to trigger each other using the 'triggers' property. this.activateTriggers(); } } /** * Creates a default message for the trap. * @private * @return {string} */ _createDefaultTrapMessage() { if(this.victim) { if(this.name) return `${this.victim.get('name')} set off a trap: ${this.name}!`; else return `${this.victim.get('name')} set off a trap!`; } else { if(this.name) return `${this.name} was activated!`; else return `A trap was activated!`; } } /** * Executes the trap's API chat command if it has one. */ playApi() { let api = this.api; if(api) { api = api.split('TRAP_ID').join(this.trapId); api = api.split('VICTIM_ID').join(this.victimId); sendChat('ItsATrap-api', api); } } /** * Spawns the AreasOfEffect graphic for this trap. If AreasOfEffect is * not installed, then this has no effect. */ playAreaOfEffect() { if(typeof AreasOfEffect !== 'undefined' && this.areaOfEffect) { let direction = (this.areaOfEffect.direction && VecMath.scale(this.areaOfEffect.direction, 70)) || (() => { if(this._victim) return [ this._victim.get('left') - this._trap.get('left'), this._victim.get('top') - this._trap.get('top') ]; else return [0, 0]; })(); direction[2] = 0; let p1 = [this._trap.get('left'), this._trap.get('top'), 1]; let p2 = VecMath.add(p1, direction); if(VecMath.dist(p1, p2) > 0) { let segments = [[p1, p2]]; let pathJson = PathMath.segmentsToPath(segments); let path = createObj('path', _.extend(pathJson, { _pageid: this._trap.get('_pageid'), layer: 'objects', stroke: '#ff0000' })); let aoeGraphic = AreasOfEffect.applyEffect('', this.areaOfEffect.name, path); aoeGraphic.set('layer', 'map'); toFront(aoeGraphic); } } } /** * Spawns built-in or custom FX for an activated trap. */ playFX() { var pageId = this._trap.get('_pageid'); if(this.fx) { var offset = this.fx.offset || [0, 0]; var origin = [ this._trap.get('left') + offset[0]*70, this._trap.get('top') + offset[1]*70 ]; var direction = this.fx.direction || (() => { if(this._victim) return [ this._victim.get('left') - origin[0], this._victim.get('top') - origin[1] ]; else return [ 0, 1 ]; })(); this._playFXNamed(this.fx.name, pageId, origin, direction); } } /** * Play FX using a named effect. * @private * @param {string} name * @param {uuid} pageId * @param {vec2} origin * @param {vec2} direction */ _playFXNamed(name, pageId, origin, direction) { let x = origin[0]; let y = origin[1]; let fx = name; let isBeamLike = false; var custFx = findObjs({ _type: 'custfx', name: name })[0]; if(custFx) { fx = custFx.get('_id'); isBeamLike = custFx.get('definition').angle === -1; } else isBeamLike = !!_.find(['beam-', 'breath-', 'splatter-'], type => { return name.startsWith(type); }); if(isBeamLike) { let p1 = { x: x, y: y }; let p2 = { x: x + direction[0], y: y + direction[1] }; spawnFxBetweenPoints(p1, p2, fx, pageId); } else spawnFx(x, y, fx, pageId); } /** * Produces an explosion/implosion effect with the KABOOM script. */ playKaboom() { if(typeof KABOOM !== 'undefined' && this.kaboom) { let center = [this.trap.get('left'), this.trap.get('top')]; let options = { effectPower: this.kaboom.power, effectRadius: this.kaboom.radius, type: this.kaboom.type, scatter: this.kaboom.scatter }; KABOOM.NOW(options, center); } } /** * Plays a TrapEffect's sound, if it has one. */ playSound() { if(this.sound) { var sound = findObjs({ _type: 'jukeboxtrack', title: this.sound })[0]; if(sound) { sound.set('playing', true); sound.set('softstop', false); } else { let msg = 'Could not find sound "' + this.sound + '".'; sendChat('ItsATrap-api', msg); } } } /** * Invokes TokenMod on the victim's token. */ playTokenMod() { if(typeof TokenMod !== 'undefined' && this.tokenMod && this._victim) { let victimId = this._victim.get('id'); let command = '!token-mod ' + this.tokenMod + ' --ids ' + victimId; // Since playerIsGM fails for the player ID "API", we'll need to // temporarily switch TokenMod's playersCanUse_ids option to true. if(!TrapEffect.tokenModTimeout) { let temp = state.TokenMod.playersCanUse_ids; TrapEffect.tokenModTimeout = setTimeout(() => { state.TokenMod.playersCanUse_ids = temp; TrapEffect.tokenModTimeout = undefined; }, 1000); } state.TokenMod.playersCanUse_ids = true; sendChat('It\'s A Trap', command); } } }; })(); /** * A small library for checking if a token has line of sight to other tokens. */ var LineOfSight = (() => { 'use strict'; /** * Gets the point for a token. * @private * @param {Graphic} token * @return {vec3} */ function _getPt(token) { return [token.get('left'), token.get('top'), 1]; } return class LineOfSight { /** * Gets the tokens that a token has line of sight to. * @private * @param {Graphic} token * @param {Graphic[]} otherTokens * @param {number} [range=Infinity] * The line-of-sight range in pixels. * @param {boolean} [isSquareRange=false] * @return {Graphic[]} */ static filterTokens(token, otherTokens, range, isSquareRange) { if(_.isUndefined(range)) range = Infinity; let pageId = token.get('_pageid'); let tokenPt = _getPt(token); let tokenRW = token.get('width')/2-1; let tokenRH = token.get('height')/2-1; let wallPaths = findObjs({ _type: 'path', _pageid: pageId, layer: 'walls' }); let wallSegments = PathMath.toSegments(wallPaths); return _.filter(otherTokens, other => { let otherPt = _getPt(other); let otherRW = other.get('width')/2; let otherRH = other.get('height')/2; // Skip tokens that are out of range. if(isSquareRange && ( Math.abs(tokenPt[0]-otherPt[0]) >= range + otherRW + tokenRW || Math.abs(tokenPt[1]-otherPt[1]) >= range + otherRH + tokenRH)) return false; else if(!isSquareRange && VecMath.dist(tokenPt, otherPt) >= range + tokenRW + otherRW) return false; let segToOther = [tokenPt, otherPt]; return !_.find(wallSegments, wallSeg => { return PathMath.segmentIntersection(segToOther, wallSeg); }); }); } }; })(); /** * A module that presents a wizard for setting up traps instead of * hand-crafting the JSON for them. */ var ItsATrapCreationWizard = (() => { 'use strict'; const DISPLAY_WIZARD_CMD = '!ItsATrap_trapCreationWizard_showMenu'; const MODIFY_CORE_PROPERTY_CMD = '!ItsATrap_trapCreationWizard_modifyTrapCore'; const MODIFY_THEME_PROPERTY_CMD = '!ItsATrap_trapCreationWizard_modifyTrapTheme'; const MENU_CSS = { 'optionsTable': { 'width': '100%' }, 'menu': { 'background': '#fff', 'border': 'solid 1px #000', 'border-radius': '5px', 'font-weight': 'bold', 'margin-bottom': '1em', 'overflow': 'hidden' }, 'menuBody': { 'padding': '5px', 'text-align': 'center' }, 'menuHeader': { 'background': '#000', 'color': '#fff', 'text-align': 'center' } }; // The last trap that was edited in the wizard. let curTrap; /** * Displays the menu for setting up a trap. * @param {string} who * @param {string} playerid * @param {Graphic} trapToken */ function displayWizard(who, playerId, trapToken) { curTrap = trapToken; let content = new HtmlBuilder('div'); // Core properties content.append('h4', 'Core properties'); let coreProperties = getCoreProperties(trapToken); content.append(_displayWizardProperties(MODIFY_CORE_PROPERTY_CMD, coreProperties)); // Shape properties content.append('h4', 'Shape properties', { style: { 'margin-top' : '2em' } }); let shapeProperties = getShapeProperties(trapToken); content.append(_displayWizardProperties(MODIFY_CORE_PROPERTY_CMD, shapeProperties)); // Trigger properties content.append('h4', 'Trigger properties', { style: { 'margin-top' : '2em' } }); let triggerProperties = getTriggerProperties(trapToken); content.append(_displayWizardProperties(MODIFY_CORE_PROPERTY_CMD, triggerProperties)); // Reveal properties content.append('h4', 'Reveal properties', { style: { 'margin-top' : '2em' } }); let revealProperties = getRevealProperties(trapToken); content.append(_displayWizardProperties(MODIFY_CORE_PROPERTY_CMD, revealProperties)); // Special properties content.append('h4', 'Special properties', { style: { 'margin-top' : '2em' } }); let specialProperties = getSpecialProperties(trapToken); content.append(_displayWizardProperties(MODIFY_CORE_PROPERTY_CMD, specialProperties)); // Theme properties let theme = ItsATrap.getTheme(); if(theme.getThemeProperties) { content.append('h4', 'Theme-specific properties', { style: { 'margin-top' : '2em' } }); let properties = theme.getThemeProperties(trapToken); content.append(_displayWizardProperties(MODIFY_THEME_PROPERTY_CMD, properties)); } // Remote activate button content.append('div', `[Activate Trap](${ItsATrap.REMOTE_ACTIVATE_CMD})`, { style: { 'margin-top' : '2em' } }); let menu = _showMenuPanel('Trap Configuration', content); _whisper(who, menu.toString(MENU_CSS)); trapToken.set('status_cobweb', true); } /** * Creates the table for a list of trap properties. * @private */ function _displayWizardProperties(modificationCommand, properties) { let table = new HtmlBuilder('table'); _.each(properties, prop => { let row = table.append('tr', undefined, { title: prop.desc }); // Construct the list of parameter prompts. let params = []; let paramProperties = prop.properties || [prop]; _.each(paramProperties, item => { let options = ''; if(item.options) options = '|' + item.options.join('|'); params.push(`?{${item.name} ${item.desc} ${options}}`); }); row.append('td', `[${prop.name}](${modificationCommand} ${prop.id}&&${params.join('&&')})`, { style: { 'font-size': '0.8em' } }); row.append('td', `${prop.value || ''}`, { style: { 'font-size': '0.8em' } }); }); return table; } /** * Fixes msg.who. * @param {string} who * @return {string} */ function _fixWho(who) { return who.replace(/\(GM\)/, '').trim(); } /** * Gets a list of the core trap properties for a trap token. * @param {Graphic} token * @return {object[]} */ function getCoreProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; let LPAREN = '&#40;'; let RPAREN = '&#41;'; let LBRACE = '&#91;'; let RBRACE = '&#93;'; return [ { id: 'name', name: 'Name', desc: 'The name of the trap', value: trapToken.get('name') }, { id: 'type', name: 'Type', desc: 'Is this a trap, or some other hidden secret?', value: trapEffect.type || 'trap' }, { id: 'message', name: 'Message', desc: 'The message displayed when the trap is activated.', value: trapEffect.message }, { id: 'disabled', name: 'Disabled', desc: 'A disabled trap will not activate when triggered, but can still be spotted with passive perception.', value: trapToken.get('status_interdiction') ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'gmOnly', name: 'GM Only', desc: 'When the trap is activated, should its results only be displayed to the GM?', value: trapEffect.gmOnly ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'notes', name: 'GM Notes', desc: 'Additional secret notes shown only to the GM when the trap is activated.', value: trapEffect.notes } ]; } /** * Gets a list of the core trap properties for a trap token dealing * with revealing the trap. * @param {Graphic} token * @return {object[]} */ function getRevealProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; let LPAREN = '&#40;'; let RPAREN = '&#41;'; let LBRACE = '&#91;'; let RBRACE = '&#93;'; return [ { id: 'searchDist', name: 'Max Search Distance', desc: 'How far away can characters passively search for this trap?', value: trapToken.get('aura2_radius') || trapEffect.searchDist }, { id: 'revealToPlayers', name: 'When Activated', desc: 'Should this trap be revealed to the players when it is activated?', value: trapToken.get('status_bleeding-eye') ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'revealWhenSpotted', name: 'When Spotted', desc: 'Should this trap be revealed to the players when a character notices it by passive searching?', value: trapEffect.revealWhenSpotted ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'revealLayer', name: 'Layer', desc: 'When this trap is revealed, which layer is it revealed on?', value: trapEffect.revealLayer || 'map', options: ['map', 'objects'] } ]; } /** * Gets a list of the core trap properties for a trap token defining * the shape of the trap. * @param {Graphic} token * @return {object[]} */ function getShapeProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; let LPAREN = '&#40;'; let RPAREN = '&#41;'; let LBRACE = '&#91;'; let RBRACE = '&#93;'; return [ { id: 'flying', name: 'Affects Flying Tokens', desc: 'Should this trap affect flying tokens ' + LPAREN + 'fluffy-wing status ' + RPAREN + '?', value: trapToken.get('status_fluffy-wing') ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'effectDistance', name: 'Blast distance', desc: 'How far away can the trap affect other tokens?', value: trapToken.get('aura1_radius') || 0 }, { id: 'stopAt', name: 'Stops Tokens At', desc: 'Does this trap stop tokens that pass through its trigger area?', value: trapEffect.stopAt, options: ['center', 'edge', 'none'] }, { id: 'effectShape', name: 'Trap shape', desc: 'Is the shape of the trap\'s effect circular or square?', value: trapToken.get('aura1_square') ? 'square' : 'circle', options: [ 'circle', 'square' ] }, ]; } /** * Gets a list of the core trap properties for a trap token dealing * with special side effects such as FX, sound, and API commands. * @param {Graphic} token * @return {object[]} */ function getSpecialProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; let LPAREN = '&#40;'; let RPAREN = '&#41;'; let LBRACE = '&#91;'; let RBRACE = '&#93;'; return _.compact([ { id: 'api', name: 'API Command', desc: 'An API command which the trap runs when it is activated. The constants TRAP_ID and VICTIM_ID will be replaced by the object IDs for the trap and victim.', value: trapEffect.api }, // Requires AreasOfEffect script. (() => { if(typeof AreasOfEffect !== 'undefined') return { id: 'areaOfEffect', name: 'Areas of Effect script', desc: 'Specifies an AoE graphic to be spawned by the trap.', value: (() => { let aoe = trapEffect.areaOfEffect; if(aoe) { let result = aoe.name; if(aoe.direction) result += '; Direction: ' + aoe.direction; return result; } else return 'None'; })(), properties: [ { id: 'name', name: 'AoE Name', desc: 'The name of the saved AreasOfEffect effect.', }, { id: 'direction', name: 'AoE Direction', desc: 'The direction of the AoE effect. Optional. If omitted, then the effect will be directed toward affected tokens. Format: ' + LBRACE + 'X,Y' + RBRACE } ] }; })(), { id: 'fx', name: 'Special FX', desc: 'What special FX are displayed when the trap is activated?', value: (() => { let fx = trapEffect.fx; if(fx) { let result = fx.name; if(fx.offset) result += '; Offset: ' + fx.offset; if(fx.direction) result += '; Direction: ' + fx.direction; return result; } else return 'None'; })(), properties: [ { id: 'name', name: 'FX Name', desc: 'The name of the special FX.' }, { id: 'offset', name: 'FX Offset', desc: 'The offset ' + LPAREN + 'in units' + RPAREN + ' of the special FX from the trap\'s center. Format: ' + LBRACE + 'X,Y' + RBRACE }, { id: 'direction', name: 'FX Direction', desc: 'The directional vector for the special FX ' + LPAREN + 'Leave blank to direct it towards characters' + RPAREN + '. Format: ' + LBRACE + 'X,Y' + RBRACE } ] }, // Requires KABOOM script by PaprikaCC (Bodin Punyaprateep). (() => { if(typeof KABOOM !== 'undefined') return { id: 'kaboom', name: 'KABOOM script', desc: 'An explosion/implosion generated by the trap with the KABOOM script by PaprikaCC.', value: (() => { let props = trapEffect.kaboom; if(props) { let result = props.power + ' ' + props.radius + ' ' + (props.type || 'default'); if(props.scatter) result += ' ' + 'scatter'; return result; } else return 'None'; })(), properties: [ { id: 'power', name: 'Power', desc: 'The power of the KABOOM effect.' }, { id: 'radius', name: 'Radius', desc: 'The radius of the KABOOM effect.' }, { id: 'type', name: 'FX Type', desc: 'The type of element to use for the KABOOM FX.' }, { id: 'scatter', name: 'Scatter', desc: 'Whether to apply scattering to tokens affected by the KABOOM effect.', options: ['no', 'yes'] } ] }; })(), { id: 'sound', name: 'Sound', desc: 'A sound from your jukebox that will play when the trap is activated.', value: trapEffect.sound }, (() => { if(typeof TokenMod !== 'undefined') return { id: 'tokenMod', name: 'TokenMod script', desc: 'Modify affected tokens with the TokenMod script by The Aaron.', value: trapEffect.tokenMod }; })() ]); } /** * Gets a list of the core trap properties for a trap token. * @param {Graphic} token * @return {object[]} */ function getTriggerProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; let LPAREN = '&#40;'; let RPAREN = '&#41;'; let LBRACE = '&#91;'; let RBRACE = '&#93;'; return [ { id: 'triggerPaths', name: 'Set Trigger', desc: 'To set paths, you must also select the paths that trigger the trap.', value: trapEffect.triggerPaths || 'self', options: ['self', 'paths'] }, { id: 'triggers', name: 'Other Traps Triggered', desc: 'A list of the names or token IDs for other traps that are triggered when this trap is activated.', value: (() => { let triggers = trapEffect.triggers; if(_.isString(triggers)) triggers = [triggers]; if(triggers) return triggers.join(', '); else return undefined; })() } ]; } /** * Changes a property for a trap. * @param {Graphic} trapToken * @param {Array} argv * @param {(Graphic|Path)[]} selected */ function modifyTrapProperty(trapToken, argv, selected) { let trapEffect = (new TrapEffect(trapToken)).json; let prop = argv[0]; let params = argv.slice(1); if(prop === 'name') trapToken.set('name', params[0]); if(prop === 'type') trapEffect.type = params[0]; if(prop === 'api') trapEffect.api = params[0]; if(prop === 'areaOfEffect') if(params[0]) { trapEffect.areaOfEffect = {}; trapEffect.areaOfEffect.name = params[0]; try { trapEffect.areaOfEffect.direction = JSON.parse(params[1]); } catch(err) {} } else trapEffect.areaOfEffect = undefined; if(prop === 'disabled') trapToken.set('status_interdiction', params[0] === 'yes'); if(prop === 'effectDistance') trapToken.set('aura1_radius', parseInt(params[0])); if(prop === 'effectShape') trapToken.set('aura1_square', params[0] === 'square'); if(prop === 'flying') trapToken.set('status_fluffy-wing', params[0] === 'yes'); if(prop === 'fx') { if(params[0]) { trapEffect.fx = {}; trapEffect.fx.name = params[0]; try { trapEffect.fx.offset = JSON.parse(params[1]); } catch(err) {} try { trapEffect.fx.direction = JSON.parse(params[2]); } catch(err) {} } else trapEffect.fx = undefined; } if(prop === 'gmOnly') trapEffect.gmOnly = params[0] === 'yes'; if(prop === 'kaboom') if(params[0]) trapEffect.kaboom = { power: parseInt(params[0]), radius: parseInt(params[1]), type: params[2] || undefined, scatter: params[3] === 'yes' }; else trapEffect.kaboom = undefined; if(prop === 'message') trapEffect.message = params[0]; if(prop === 'notes') trapEffect.notes = params[0]; if(prop === 'revealLayer') trapEffect.revealLayer = params[0]; if(prop === 'revealToPlayers') trapToken.set('status_bleeding-eye', params[0] === 'yes'); if(prop === 'revealWhenSpotted') trapEffect.revealWhenSpotted = params[0] === 'yes'; if(prop === 'searchDist') trapToken.set('aura2_radius', parseInt(params[0])); if(prop === 'sound') trapEffect.sound = params[0]; if(prop === 'stopAt') trapEffect.stopAt = params[0]; if(prop === 'tokenMod') trapEffect.tokenMod = params[0]; if(prop === 'triggers') trapEffect.triggers = _.map(params[0].split(','), trigger => { return trigger.trim(); }); if(prop === 'triggerPaths') if(params[0] === 'paths' && selected) trapEffect.triggerPaths = _.map(selected, path => { return path.get('_id'); }); else trapEffect.triggerPaths = undefined; trapToken.set('gmnotes', JSON.stringify(trapEffect)); } /** * Displays one of the script's menus. * @param {string} header * @param {(string|HtmlBuilder)} content * @return {HtmlBuilder} */ function _showMenuPanel(header, content) { let menu = new HtmlBuilder('.menu'); menu.append('.menuHeader', header); menu.append('.menuBody', content); return menu; } /** * @private * Whispers a Marching Order message to someone. */ function _whisper(who, msg) { sendChat('Its A Trap! script', '/w "' + _fixWho(who) + '" ' + msg); } on('ready', () => { let macro = findObjs({ _type: 'macro', name: 'ItsATrap_trapCreationWizard' })[0]; if(!macro) { let players = findObjs({ _type: 'player' }); let gms = _.filter(players, player => { return playerIsGM(player.get('_id')); }); _.each(gms, gm => { createObj('macro', { _playerid: gm.get('_id'), name: 'ItsATrap_trapCreationWizard', action: DISPLAY_WIZARD_CMD, istokenaction: true }); }); } }); on('chat:message', msg => { try { // Get the selected tokens/paths if any. let selected; if(msg.selected) { selected = _.map(msg.selected, sel => { return getObj(sel._type, sel._id); }); } if(msg.content.startsWith(DISPLAY_WIZARD_CMD)) { let trapToken = getObj('graphic', msg.selected[0]._id); displayWizard(msg.who, msg.playerId, trapToken); } if(msg.content.startsWith(MODIFY_CORE_PROPERTY_CMD)) { let params = msg.content.replace(MODIFY_CORE_PROPERTY_CMD + ' ', '').split('&&'); modifyTrapProperty(curTrap, params, selected); displayWizard(msg.who, msg.playerId, curTrap); } if(msg.content.startsWith(MODIFY_THEME_PROPERTY_CMD)) { let params = msg.content.replace(MODIFY_THEME_PROPERTY_CMD + ' ', '').split('&&'); let theme = ItsATrap.getTheme(); theme.modifyTrapProperty(curTrap, params, selected); displayWizard(msg.who, msg.playerId, curTrap); } } catch(err) { log('ItsATrapCreationWizard: ' + err.message); log(err.stack); } }); return { displayWizard, DISPLAY_WIZARD_CMD, MODIFY_CORE_PROPERTY_CMD, MODIFY_THEME_PROPERTY_CMD }; })(); /** * Base class for trap themes: System-specific strategies for handling * automation of trap activation results and passive searching. * @abstract */ var TrapTheme = (() => { 'use strict'; /** * The name of the theme used to register it. * @type {string} */ return class TrapTheme { /** * A sample CSS object for trap HTML messages created with HTML Builder. */ static get css() { return { 'bold': { 'font-weight': 'bold' }, 'critFail': { 'border': '2px solid #B31515' }, 'critSuccess': { 'border': '2px solid #3FB315' }, 'hit': { 'color': '#f00', 'font-weight': 'bold' }, 'miss': { 'color': '#620', 'font-weight': 'bold' }, 'paddedRow': { 'padding': '1px 1em' }, 'rollResult': { 'background-color': '#FEF68E', 'cursor': 'help', 'font-size': '1.1em', 'font-weight': 'bold', 'padding': '0 3px' }, 'trapMessage': { 'background-color': '#ccc', 'font-style': 'italic' }, 'trapTable': { 'background-color': '#fff', 'border': 'solid 1px #000', 'border-collapse': 'separate', 'border-radius': '10px', 'overflow': 'hidden', 'width': '100%' }, 'trapTableHead': { 'background-color': '#000', 'color': '#fff', 'font-weight': 'bold' } }; } get name() { throw new Error('Not implemented.'); } /** * Activates a TrapEffect by displaying the trap's message and * automating any system specific trap mechanics for it. * @abstract * @param {TrapEffect} effect */ activateEffect(effect) { throw new Error('Not implemented.'); } /** * Attempts to force a calculated attribute to be corrected by * setting it. * @param {Character} character * @param {string} attr */ static forceAttrCalculation(character, attr) { // Attempt to force the calculation of the save modifier by setting it. createObj('attribute', { _characterid: character.get('_id'), name: attr, current: -9999 }); // Then try again. return CharSheetUtils.getSheetAttr(character, attr) .then(result => { if(_.isNumber(result)) return result; else log('Could not calculate attribute: ' + attr + ' - ' + result); }); } /** * Asynchronously gets the value of a character sheet attribute. * @param {Character} character * @param {string} attr * @return {Promise<number>} * Contains the value of the attribute. */ static getSheetAttr(character, attr) { if(attr.includes('/')) return CharSheetUtils.getSheetRepeatingAttr(character, attr); else { let rollExpr = '@{' + character.get('name') + '|' + attr + '}'; return CharSheetUtils.rollAsync(rollExpr) .then((roll) => { if(roll) return roll.total; else throw new Error('Could not resolve roll expression: ' + rollExpr); }) .then(value => { if(_.isNumber(value)) return value; // If the attribute is autocalculated, but could its current value // could not be resolved, try to force it to calculate its value as a // last-ditch effort. else return TrapTheme.forceAttrCalculation(character, attr); }); } } /** * Asynchronously gets the value of a character sheet attribute from a * repeating row. * @param {Character} character * @param {string} attr * Here, attr has the format "sectionName/nameFieldName/nameFieldValue/valueFieldName". * For example: "skills/name/perception/total" * @return {Promise<number>} * Contains the value of the attribute. */ static getSheetRepeatingAttr(character, attr) { let parts = attr.split('/'); let sectionName = parts[0]; let nameFieldName = parts[1]; let nameFieldValue = parts[2].toLowerCase(); let valueFieldName = parts[3]; // Find the row with the given name. return CharSheetUtils.getSheetRepeatingRow(character, sectionName, rowAttrs => { let nameField = rowAttrs[nameFieldName]; return nameField.get('current').toLowerCase().trim() === nameFieldValue; }) // Get the current value of that row. .then(rowAttrs => { let valueField = rowAttrs[valueFieldName]; return valueField.get('current'); }); } /** * Gets the map of attributes inside of a repeating section row. * @param {Character} character * @param {string} section * The name of the repeating section. * @param {func} rowFilter * A filter function to find the correct row. The argument passed to it is a * map of attribute names (without the repeating section ID part - e.g. "name" * instead of "repeating_skills_-123abc_name") to their actual attributes in * the current row being filtered. The function should return true iff it is * the correct row we're looking for. * @return {Promise<any>} * Contains the map of attributes. */ static getSheetRepeatingRow(character, section, rowFilter) { // Get all attributes in this section and group them by row. let attrs = findObjs({ _type: 'attribute', _characterid: character.get('_id') }); // Group the attributes by row. let rows = {}; _.each(attrs, attr => { let regex = new RegExp(`repeating_${section}_(-([0-9a-zA-Z\-_](?!_storage))+?|\$\d+?)_([0-9a-zA-Z\-_]+)`); let match = attr.get('name').match(regex); if(match) { let rowId = match[1]; let attrName = match[3]; if(!rows[rowId]) rows[rowId] = {}; rows[rowId][attrName] = attr; } }); // Find the row that matches our filter. return Promise.resolve(_.find(rows, rowAttrs => { return rowFilter(rowAttrs); })); } /** * Gets a list of a trap's theme-specific configured properties. * @param {Graphic} trap * @return {TrapProperty[]} */ getThemeProperties(trap) { return []; } /** * Displays the message to notice a trap. * @param {Character} character * @param {Graphic} trap */ static htmlNoticeTrap(character, trap) { let content = new HtmlBuilder(); let effect = new TrapEffect(trap, character); content.append('.paddedRow trapMessage', character.get('name') + ' notices a ' + (effect.type || 'trap') + ':'); content.append('.paddedRow', trap.get('name')); return TrapTheme.htmlTable(content, '#000', effect); } /** * Sends an HTML-stylized message about a noticed trap. * @param {(HtmlBuilder|string)} content * @param {string} borderColor * @param {TrapEffect} [effect] * @return {HtmlBuilder} */ static htmlTable(content, borderColor, effect) { let type = (effect && effect.type) || 'trap'; let table = new HtmlBuilder('table.trapTable', '', { style: { 'border-color': borderColor } }); table.append('thead.trapTableHead', '', { style: { 'background-color': borderColor } }).append('th', 'IT\'S A ' + type.toUpperCase() + '!!!'); table.append('tbody').append('tr').append('td', content, { style: { 'padding': '0' } }); return table; } /** * Changes a theme-specific property for a trap. * @param {Graphic} trapToken * @param {Array} params */ modifyTrapProperty(trapToken, argv) { // Default implementation: Do nothing. } /** * The system-specific behavior for a character passively noticing a trap. * @abstract * @param {Graphic} trap * The trap's token. * @param {Graphic} charToken * The character's token. */ passiveSearch(trap, charToken) { throw new Error('Not implemented.'); } /** * Asynchronously rolls a dice roll expression and returns the result's total in * a callback. The result is undefined if an invalid expression is given. * @param {string} expr * @return {Promise<int>} */ static rollAsync(expr) { return new Promise((resolve, reject) => { sendChat('TrapTheme', '/w gm [[' + expr + ']]', (msg) => { try { let results = msg[0].inlinerolls[0].results; resolve(results); } catch(err) { reject(err); } }); }); } }; })(); /** * A base class for trap themes using the D20 system (D&D 3.5, 4E, 5E, Pathfinder, etc.) * @abstract */ var D20TrapTheme = (() => { 'use strict'; return class D20TrapTheme extends TrapTheme { /** * @inheritdoc */ activateEffect(effect) { let character = getObj('character', effect.victim.get('represents')); let effectResults = effect.json; // Automate trap attack/save mechanics. Promise.resolve() .then(() => { effectResults.character = character; if(character) { if(effectResults.attack) return this._doTrapAttack(character, effectResults); else if(effectResults.save && effectResults.saveDC) return this._doTrapSave(character, effectResults); } return effectResults; }) .then(effectResults => { let html = D20TrapTheme.htmlTrapActivation(effectResults); effect.announce(html.toString(TrapTheme.css)); }) .catch(err => { sendChat('TrapTheme: ' + this.name, '/w gm ' + err.message); log(err.stack); }); } /** * Does a trap's attack roll. * @private */ _doTrapAttack(character, effectResults) { return Promise.all([ this.getAC(character), CharSheetUtils.rollAsync('1d20 + ' + effectResults.attack) ]) .then(tuple => { let ac = tuple[0]; let atkRoll = tuple[1]; ac = ac || 10; effectResults.ac = ac; effectResults.roll = atkRoll; effectResults.trapHit = atkRoll.total >= ac; return effectResults; }); } /** * Does a trap's save. * @private */ _doTrapSave(character, effectResults) { return this.getSaveBonus(character, effectResults.save) .then(saveBonus => { saveBonus = saveBonus || 0; effectResults.saveBonus = saveBonus; return CharSheetUtils.rollAsync('1d20 + ' + saveBonus); }) .then((saveRoll) => { effectResults.roll = saveRoll; effectResults.trapHit = saveRoll.total < effectResults.saveDC; return effectResults; }); } /** * Gets a character's AC. * @abstract * @param {Character} character * @return {Promise<int>} */ getAC(character) { throw new Error('Not implemented.'); } /** * Gets a character's passive wisdom (Perception). * @abstract * @param {Character} character * @return {Promise<int>} */ getPassivePerception(character) { throw new Error('Not implemented.'); } /** * Gets a character's saving throw bonus. * @abstract * @param {Character} character * @return {Promise<int>} */ getSaveBonus(character, saveName) { throw new Error('Not implemented.'); } /** * @inheritdoc */ getThemeProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; let LPAREN = '&#40;'; let RPAREN = '&#41;'; let LBRACE = '&#91;'; let RBRACE = '&#93;'; return [ { id: 'attack', name: 'Attack Bonus', desc: `The trap's attack roll bonus vs AC.`, value: trapEffect.attack }, { id: 'damage', name: 'Damage', desc: `The dice roll expression for the trap's damage.`, value: trapEffect.damage }, { id: 'hideSave', name: 'Hide Save Result', desc: 'Show the Saving Throw result only to the GM?', value: trapEffect.hideSave ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'missHalf', name: 'Miss - Half Damage', desc: 'Does the trap deal half damage on a miss?', value: trapEffect.missHalf ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'save', name: 'Saving Throw', desc: 'The type of saving throw used by the trap.', value: trapEffect.save, options: [ 'none', 'str', 'dex', 'con', 'int', 'wis', 'cha' ] }, { id: 'saveDC', name: 'Saving Throw DC', desc: `The DC for the trap's saving throw.`, value: trapEffect.saveDC }, { id: 'spotDC', name: 'Spot DC', desc: 'The skill check DC to spot the trap.', value: trapEffect.spotDC } ]; } /** * Produces HTML for a faked inline roll result for d20 systems. * @param {int} result * @param {string} tooltip * @return {HtmlBuilder} */ static htmlRollResult(result, tooltip) { let d20 = result.rolls[0].results[0].v; let clazzes = ['rollResult']; if(d20 === 20) clazzes.push('critSuccess'); if(d20 === 1) clazzes.push('critFail'); return new HtmlBuilder('span.' + clazzes.join(' '), result.total, { title: tooltip }); } /** * Produces the HTML for a trap activation message for most d20 systems. * @param {object} effectResults * @return {HtmlBuilder} */ static htmlTrapActivation(effectResults) { let content = new HtmlBuilder('div'); // Add the flavor message. content.append('.paddedRow trapMessage', effectResults.message); if(effectResults.character) { var row = content.append('.paddedRow'); row.append('span.bold', 'Target:'); row.append('span', effectResults.character.get('name')); // Add the attack roll message. if(effectResults.attack) { let rollResult = D20TrapTheme.htmlRollResult(effectResults.roll, '1d20 + ' + effectResults.attack); content.append('.paddedRow') .append('span.bold', 'Attack roll:') .append('span', rollResult) .append('span', ' vs AC ' + effectResults.ac); } // Add the saving throw message. if(effectResults.save) { let rollResult = D20TrapTheme.htmlRollResult(effectResults.roll, '1d20 + ' + effectResults.saveBonus); let saveMsg = new HtmlBuilder('.paddedRow'); saveMsg.append('span.bold', effectResults.save.toUpperCase() + ' save:'); saveMsg.append('span', rollResult); saveMsg.append('span', ' vs DC ' + effectResults.saveDC); // If the save result is a secret, whisper it to the GM. if(effectResults.hideSave) sendChat('Admiral Ackbar', '/w gm ' + saveMsg.toString(TrapTheme.css)); else content.append(saveMsg); } // Add the hit/miss message. if(effectResults.trapHit === 'AC unknown') { content.append('.paddedRow', 'AC could not be determined with the current version of your character sheet. For the time being, please resolve the attack against AC manually.'); if(effectResults.damage) content.append('.paddedRow', 'Damage: [[' + effectResults.damage + ']]'); } else if(effectResults.trapHit) { let row = content.append('.paddedRow'); row.append('span.hit', 'HIT! '); if(effectResults.damage) row.append('span', 'Damage: [[' + effectResults.damage + ']]'); else row.append('span', 'You fall prey to the ' + (effectResults.type || 'trap') + '\'s effects!'); } else { let row = content.append('.paddedRow'); row.append('span.miss', 'MISS! '); if(effectResults.damage && effectResults.missHalf) row.append('span', 'Half damage: [[floor((' + effectResults.damage + ')/2)]].'); } } return TrapTheme.htmlTable(content, '#a22', effectResults); } /** * @inheritdoc */ modifyTrapProperty(trapToken, argv) { let trapEffect = (new TrapEffect(trapToken)).json; let prop = argv[0]; let params = argv.slice(1); log(prop); log(params); if(prop === 'attack') trapEffect.attack = parseInt(params[0]); if(prop === 'damage') trapEffect.damage = params[0]; if(prop === 'hideSave') trapEffect.hideSave = params[0] === 'yes'; if(prop === 'missHalf') trapEffect.missHalf = params[0] === 'yes'; if(prop === 'save') trapEffect.save = params[0] === 'none' ? undefined : params[0]; if(prop === 'saveDC') trapEffect.saveDC = parseInt(params[0]); if(prop === 'spotDC') trapEffect.spotDC = parseInt(params[0]); trapToken.set('gmnotes', JSON.stringify(trapEffect)); } /** * @inheritdoc */ passiveSearch(trap, charToken) { let effect = (new TrapEffect(trap, charToken)).json; let character = getObj('character', charToken.get('represents')); // Only do passive search for traps that have a spotDC. if(effect.spotDC && character) { // If the character's passive perception beats the spot DC, then // display a message and mark the trap's trigger area. return this.getPassivePerception(character) .then(passWis => { if(passWis >= effect.spotDC) { let html = TrapTheme.htmlNoticeTrap(character, trap); ItsATrap.noticeTrap(trap, html.toString(TrapTheme.css)); } }) .catch(err => { sendChat('Trap theme: ' + this.name, '/w gm ' + err.message); log(err.stack); }); } } }; })(); /** * Base class for TrapThemes using D&D 4E-ish rules. * @abstract */ var D20TrapTheme4E = (() => { 'use strict'; return class D20TrapTheme4E extends D20TrapTheme { /** * @inheritdoc */ activateEffect(effect) { let character = getObj('character', effect.victim.get('represents')); let effectResult = effect.json; Promise.resolve() .then(() => { effectResult.character = character; // Automate trap attack mechanics. if(character && effectResult.defense && effectResult.attack) { return Promise.all([ this.getDefense(character, effectResult.defense), CharSheetUtils.rollAsync('1d20 + ' + effectResult.attack) ]) .then(tuple => { let defenseValue = tuple[0]; let attackRoll = tuple[1]; defenseValue = defenseValue || 0; effectResult.defenseValue = defenseValue; effectResult.roll = attackRoll; effectResult.trapHit = attackRoll.total >= defenseValue; return effectResult; }); } return effectResult; }) .then(effectResult => { let html = D20TrapTheme4E.htmlTrapActivation(effectResult); effect.announce(html.toString(TrapTheme.css)); }) .catch(err => { sendChat('Trap theme: ' + this.name, '/w gm ' + err.message); log(err.stack); }); } /** * Gets the value for one of a character's defenses. * @param {Character} character * @param {string} defenseName * @return {Promise<int>} */ getDefense(character, defenseName) { throw new Error('Not implemented.'); } /** * @inheritdoc */ getThemeProperties(trapToken) { let trapEffect = (new TrapEffect(trapToken)).json; return [ { id: 'attack', name: 'Attack Bonus', desc: `The trap's attack roll bonus vs AC.`, value: trapEffect.attack }, { id: 'damage', name: 'Damage', desc: `The dice roll expression for the trap's damage.`, value: trapEffect.damage }, { id: 'defense', name: 'Defense', desc: `The defense targeted by the trap's attack.`, value: trapEffect.defense, options: [ 'none', 'ac', 'fort', 'ref', 'will' ] }, { id: 'missHalf', name: 'Miss - Half Damage', desc: 'Does the trap deal half damage on a miss?', value: trapEffect.missHalf ? 'yes' : 'no', options: ['yes', 'no'] }, { id: 'spotDC', name: 'Spot DC', desc: 'The skill check DC to spot the trap.', value: trapEffect.spotDC } ]; } /** * Creates the HTML for an activated trap's result. * @param {object} effectResult * @return {HtmlBuilder} */ static htmlTrapActivation(effectResult) { let content = new HtmlBuilder('div'); // Add the flavor message. content.append('.paddedRow trapMessage', effectResult.message); if(effectResult.character) { // Add the attack roll message. if(_.isNumber(effectResult.attack)) { let rollHtml = D20TrapTheme.htmlRollResult(effectResult.roll, '1d20 + ' + effectResult.attack); let row = content.append('.paddedRow'); row.append('span.bold', 'Attack roll: '); row.append('span', rollHtml + ' vs ' + effectResult.defense + ' ' + effectResult.defenseValue); } // Add the hit/miss message. if(effectResult.trapHit) { let row = content.append('.paddedRow'); row.append('span.hit', 'HIT! '); if(effectResult.damage) row.append('span', 'Damage: [[' + effectResult.damage + ']]'); else row.append('span', effectResult.character.get('name') + ' falls prey to the trap\'s effects!'); } else { let row = content.append('.paddedRow'); row.append('span.miss', 'MISS! '); if(effectResult.damage && effectResult.missHalf) row.append('span', 'Half damage: [[floor((' + effectResult.damage + ')/2)]].'); } } return TrapTheme.htmlTable(content, '#a22', effectResult); } /** * @inheritdoc */ modifyTrapProperty(trapToken, argv) { let trapEffect = (new TrapEffect(trapToken)).json; let prop = argv[0]; let params = argv.slice(1); if(prop === 'attack') trapEffect.attack = parseInt(params[0]); if(prop === 'damage') trapEffect.damage = params[0]; if(prop === 'defense') trapEffect.defense = params[0] === 'none' ? undefined : params[0]; if(prop === 'missHalf') trapEffect.missHalf = params[0] === 'yes'; if(prop === 'spotDC') trapEffect.spotDC = parseInt(params[0]); trapToken.set('gmnotes', JSON.stringify(trapEffect)); } }; })(); /** * The default system-agnostic Admiral Ackbar theme. * @implements TrapTheme */ (() => { 'use strict'; class DefaultTheme { /** * @inheritdoc */ get name() { return 'default'; } /** * @inheritdoc */ activateEffect(effect) { let content = new HtmlBuilder('div'); var row = content.append('.paddedRow'); if(effect.victim) { row.append('span.bold', 'Target:'); row.append('span', effect.victim.get('name')); } content.append('.paddedRow', effect.message); let table = TrapTheme.htmlTable(content, '#a22', effect); let tableView = table.toString(TrapTheme.css); effect.announce(tableView); } /** * @inheritdoc */ passiveSearch(trap, charToken) { // Do nothing. } } ItsATrap.registerTheme(new DefaultTheme()); })();
1
0.914409
1
0.914409
game-dev
MEDIA
0.714902
game-dev
0.956112
1
0.956112
lijx10/uwb-localization
1,407
slam_pp/src/slam/thread_slam.cpp
#include "slam/thread_slam.hpp" void uavos::SLAM_Controller::start(){ m_slam_thread = boost::thread(&SLAM_Controller::thread_slam, this); } void uavos::SLAM_Controller::thread_slam(){ // load parameters double slam_frequency; m_nh.param<double>("slam_fps", slam_frequency, 50); if(std::fabs(slam_frequency)<0.1){ slam_frequency = 0.1; } bool is_enable_visualization; m_nh.param<bool>("is_enable_visualization", is_enable_visualization, false); boost::shared_ptr<uavos::UWB_Localization> p_uwb_localization(new uavos::UWB_Localization(m_nh)); ros::Timer solve_slam_timer = m_nh.createTimer(ros::Duration(1.0/slam_frequency), &uavos::UWB_Localization::solveSLAM, p_uwb_localization); if(true==is_enable_visualization){ ros::Timer visualization_timer = m_nh.createTimer(ros::Duration(0.02), &uavos::SLAM_System::visualizeTrajectoryCallback, boost::dynamic_pointer_cast<uavos::SLAM_System>(p_uwb_localization)); } // spin for this thread const double timeout = 0.001; ros::WallDuration timeout_duration(timeout); while(m_nh.ok()){ m_p_slam_callback_queue->callAvailable(timeout_duration); } }
1
0.778251
1
0.778251
game-dev
MEDIA
0.491291
game-dev
0.682903
1
0.682903
appsquickly/typhoon-example
1,031
Pods/Typhoon/Source/Definition/Internal/TyphoonDefinition+InstanceBuilder.h
//////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Typhoon Framework Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// #import "TyphoonDefinition.h" @protocol TyphoonPropertyInjection; @protocol TyphoonInjection; @class TyphoonComponentFactory; @class TyphoonRuntimeArguments; @interface TyphoonDefinition (InstanceBuilder) - (id)initializeInstanceWithArgs:(TyphoonRuntimeArguments *)args factory:(TyphoonComponentFactory *)factory; - (void)doInjectionEventsOn:(id)instance withArgs:(TyphoonRuntimeArguments *)args factory:(TyphoonComponentFactory *)factory; - (void)doAfterAllInjectionsOn:(id)instance; - (id)targetForInitializerWithFactory:(TyphoonComponentFactory *)factory args:(TyphoonRuntimeArguments *)args; @end
1
0.609692
1
0.609692
game-dev
MEDIA
0.287085
game-dev
0.583066
1
0.583066
cCorax2/Source_code
6,545
game/questlua_forked.cpp
#include "stdafx.h" #include "threeway_war.h" #include "../../common/stl.h" #include "questlua.h" #include "questmanager.h" #include "char.h" #include "dungeon.h" #include "p2p.h" #include "locale_service.h" #include "threeway_war.h" extern int passes_per_sec; namespace quest { // // "forked_" lua functions // int forked_set_dead_count( lua_State* L ) { LPCHARACTER ch = CQuestManager::instance().GetCurrentCharacterPtr(); CQuestManager& q = CQuestManager::instance(); if (NULL != ch) { CThreeWayWar::instance().SetReviveTokenForPlayer( ch->GetPlayerID(), q.GetEventFlag("threeway_war_dead_count") ); } return 0; } int forked_get_dead_count( lua_State* L ) { LPCHARACTER ch = CQuestManager::instance().GetCurrentCharacterPtr(); if (NULL != ch) { lua_pushnumber( L, CThreeWayWar::instance().GetReviveTokenForPlayer(ch->GetPlayerID()) ); } else { lua_pushnumber( L, 0 ); } return 1; } int forked_init_kill_count_per_empire( lua_State* L ) { LPCHARACTER ch = CQuestManager::instance().GetCurrentCharacterPtr(); CThreeWayWar::instance().SetKillScore( ch->GetEmpire(), 0 ); return 0; } int forked_init( lua_State* L ) { CThreeWayWar::instance().Initialize(); CThreeWayWar::instance().RandomEventMapSet(); return 0; } int forked_sungzi_start_pos( lua_State* L ) { LPCHARACTER ch = CQuestManager::instance().GetCurrentCharacterPtr(); const ForkedSungziMapInfo& info = CThreeWayWar::instance().GetEventSungZiMapInfo(); lua_pushnumber( L, info.m_iForkedSungziStartPosition[ch->GetEmpire()-1][0] ); lua_pushnumber( L, info.m_iForkedSungziStartPosition[ch->GetEmpire()-1][1] ); return 2; } int forked_pass_start_pos( lua_State* L ) { LPCHARACTER ch = CQuestManager::instance().GetCurrentCharacterPtr(); const ForkedPassMapInfo& info = CThreeWayWar::instance().GetEventPassMapInfo(); lua_pushnumber( L, info.m_iForkedPassStartPosition[ch->GetEmpire()-1][0] ); lua_pushnumber( L, info.m_iForkedPassStartPosition[ch->GetEmpire()-1][1] ); return 2; } int forked_sungzi_mapindex (lua_State *L ) { lua_pushnumber( L, GetSungziMapIndex() ); if ( test_server ) sys_log ( 0, "forked_sungzi_map_index_by_empire %d", GetSungziMapIndex() ); return 1; } int forked_pass_mapindex_by_empire( lua_State *L ) { lua_pushnumber( L, GetPassMapIndex(lua_tonumber(L,1)) ); return 1; } int forked_get_pass_path_my_empire( lua_State *L ) { LPCHARACTER ch = CQuestManager::instance().GetCurrentCharacterPtr(); lua_pushstring( L, GetPassMapPath( ch->GetEmpire() ) ); sys_log (0, "[PASS_PATH] Empire %d Path %s", ch->GetEmpire(), GetPassMapPath( ch->GetEmpire() ) ); return 1; } int forked_get_pass_path_by_empire( lua_State *L ) { int iEmpire = (int)lua_tonumber(L, 1); lua_pushstring( L, GetPassMapPath(iEmpire) ); sys_log (0, "[PASS_PATH] Empire %d Path %s", iEmpire, GetPassMapPath( iEmpire ) ); return 1; } int forked_is_forked_mapindex( lua_State * L ) { lua_pushboolean( L, CThreeWayWar::instance().IsThreeWayWarMapIndex(lua_tonumber(L,1)) ); return 1; } int forked_is_sungzi_mapindex( lua_State * L ) { lua_pushboolean( L, CThreeWayWar::instance().IsSungZiMapIndex(lua_tonumber(L,1)) ); return 1; } struct FWarpInMap { int m_iMapIndexTo; int m_x; int m_y; void operator()(LPENTITY ent) { if (ent->IsType(ENTITY_CHARACTER)) { LPCHARACTER ch = (LPCHARACTER) ent; if (ch->IsPC()) { ch->WarpSet( m_x+(number(0,5)*100), m_y+(number(0,5)*100), m_iMapIndexTo); } } } }; EVENTINFO(warp_all_to_map_event_info) { int m_iMapIndexFrom; int m_iMapIndexTo; int m_x; int m_y; warp_all_to_map_event_info() : m_iMapIndexFrom( 0 ) , m_iMapIndexTo( 0 ) , m_x( 0 ) , m_y( 0 ) { } }; EVENTFUNC(warp_all_to_map_event) { warp_all_to_map_event_info * info = dynamic_cast<warp_all_to_map_event_info *>(event->info); if ( info == NULL ) { sys_err( "warp_all_to_map_event> <Factor> Null pointer" ); return 0; } LPSECTREE_MAP pSecMap = SECTREE_MANAGER::instance().GetMap( info->m_iMapIndexFrom ); if ( pSecMap ) { FWarpInMap f; f.m_iMapIndexTo = info->m_iMapIndexTo; f.m_x = info->m_x; f.m_y = info->m_y; pSecMap->for_each( f ); } return 0; } int forked_warp_all_in_map( lua_State * L ) { int iMapIndexFrom = (int)lua_tonumber(L, 1 ); int iMapIndexTo = (int)lua_tonumber(L, 2 ); int ix = (int)lua_tonumber(L, 3 ); int iy = (int)lua_tonumber(L, 4 ); int iTime = (int)lua_tonumber(L, 5 ); warp_all_to_map_event_info* info = AllocEventInfo<warp_all_to_map_event_info>(); info->m_iMapIndexFrom = iMapIndexFrom; info->m_iMapIndexTo = iMapIndexTo; info->m_x = ix; info->m_y = iy; event_create(warp_all_to_map_event, info, PASSES_PER_SEC(iTime)); return 0; } int forked_is_registered_user( lua_State* L ) { LPCHARACTER ch = CQuestManager::instance().GetCurrentCharacterPtr(); if (NULL != ch) { lua_pushboolean( L, CThreeWayWar::instance().IsRegisteredUser(ch->GetPlayerID()) ); } else { lua_pushboolean( L, false ); } return 1; } int forked_register_user( lua_State* L ) { LPCHARACTER ch = CQuestManager::instance().GetCurrentCharacterPtr(); if (NULL != ch) { CThreeWayWar::instance().RegisterUser( ch->GetPlayerID() ); } return 0; } int forked_purge_all_monsters( lua_State* L ) { CThreeWayWar::instance().RemoveAllMonstersInThreeWay(); return 0; } void RegisterForkedFunctionTable() { luaL_reg forked_functions[] = { { "setdeadcount", forked_set_dead_count }, { "getdeadcount", forked_get_dead_count }, { "initkillcount", forked_init_kill_count_per_empire }, { "initforked", forked_init }, { "get_sungzi_start_pos", forked_sungzi_start_pos }, { "get_pass_start_pos", forked_pass_start_pos }, { "getsungzimapindex", forked_sungzi_mapindex }, { "getpassmapindexbyempire", forked_pass_mapindex_by_empire }, { "getpasspathbyempire", forked_get_pass_path_by_empire }, { "isforkedmapindex", forked_is_forked_mapindex }, { "issungzimapindex", forked_is_sungzi_mapindex }, { "warp_all_in_map", forked_warp_all_in_map }, { "is_registered_user", forked_is_registered_user }, { "register_user", forked_register_user }, { "purge_all_monsters", forked_purge_all_monsters }, { NULL, NULL } }; CQuestManager::instance().AddLuaFunctionTable("forked", forked_functions); } }
1
0.977678
1
0.977678
game-dev
MEDIA
0.369292
game-dev
0.98248
1
0.98248
oot-pc-port/oot-pc-port
2,172
asm/non_matchings/overlays/actors/ovl_En_Dodojr/func_809F6AC4.s
glabel func_809F6AC4 /* 00704 809F6AC4 27BDFFD8 */ addiu $sp, $sp, 0xFFD8 ## $sp = FFFFFFD8 /* 00708 809F6AC8 AFA40028 */ sw $a0, 0x0028($sp) /* 0070C 809F6ACC AFBF0024 */ sw $ra, 0x0024($sp) /* 00710 809F6AD0 3C040600 */ lui $a0, 0x0600 ## $a0 = 06000000 /* 00714 809F6AD4 0C028800 */ jal SkelAnime_GetFrameCount /* 00718 809F6AD8 248405F0 */ addiu $a0, $a0, 0x05F0 ## $a0 = 060005F0 /* 0071C 809F6ADC 44822000 */ mtc1 $v0, $f4 ## $f4 = 0.00 /* 00720 809F6AE0 44800000 */ mtc1 $zero, $f0 ## $f0 = 0.00 /* 00724 809F6AE4 8FA40028 */ lw $a0, 0x0028($sp) /* 00728 809F6AE8 468021A0 */ cvt.s.w $f6, $f4 /* 0072C 809F6AEC 3C050600 */ lui $a1, 0x0600 ## $a1 = 06000000 /* 00730 809F6AF0 44070000 */ mfc1 $a3, $f0 /* 00734 809F6AF4 24A505F0 */ addiu $a1, $a1, 0x05F0 ## $a1 = 060005F0 /* 00738 809F6AF8 3C063F80 */ lui $a2, 0x3F80 ## $a2 = 3F800000 /* 0073C 809F6AFC AFA00014 */ sw $zero, 0x0014($sp) /* 00740 809F6B00 E7A60010 */ swc1 $f6, 0x0010($sp) /* 00744 809F6B04 2484014C */ addiu $a0, $a0, 0x014C ## $a0 = 0000014C /* 00748 809F6B08 0C029468 */ jal SkelAnime_ChangeAnimation /* 0074C 809F6B0C E7A00018 */ swc1 $f0, 0x0018($sp) /* 00750 809F6B10 8FA20028 */ lw $v0, 0x0028($sp) /* 00754 809F6B14 44804000 */ mtc1 $zero, $f8 ## $f8 = 0.00 /* 00758 809F6B18 3C01809F */ lui $at, %hi(D_809F7F7C) ## $at = 809F0000 /* 0075C 809F6B1C E4480060 */ swc1 $f8, 0x0060($v0) ## 00000060 /* 00760 809F6B20 C42A7F7C */ lwc1 $f10, %lo(D_809F7F7C)($at) /* 00764 809F6B24 E44A006C */ swc1 $f10, 0x006C($v0) ## 0000006C /* 00768 809F6B28 8FBF0024 */ lw $ra, 0x0024($sp) /* 0076C 809F6B2C 27BD0028 */ addiu $sp, $sp, 0x0028 ## $sp = 00000000 /* 00770 809F6B30 03E00008 */ jr $ra /* 00774 809F6B34 00000000 */ nop
1
0.672484
1
0.672484
game-dev
MEDIA
0.940659
game-dev
0.567872
1
0.567872
rapid7/metasploit-framework
2,721
lib/msf/ui/console/module_action_commands.rb
# -*- coding: binary -*- require 'msf/ui/console/command_dispatcher' require 'msf/ui/console/module_argument_parsing' module Msf module Ui module Console ### # # A mixin to enable the ModuleCommandDispatcher to leverage module ACTIONs as commands. # ### module ModuleActionCommands include Msf::Ui::Console::ModuleArgumentParsing # # Returns the hash of commands specific to auxiliary modules. # def action_commands return {} unless mod.respond_to?(:actions) mod.actions.map { |action| [action.name.downcase, action.description] }.to_h end def commands super.merge(action_commands) { |k, old_val, new_val| old_val} end # # Allow modules to define their own commands # Note: A change to this method will most likely require a corresponding change to respond_to_missing? # def method_missing(meth, *args) if mod && mod.respond_to?(meth.to_s, true) # Initialize user interaction mod.init_ui(driver.input, driver.output) return mod.send(meth.to_s, *args) end action = meth.to_s.delete_prefix('cmd_').delete_suffix('_tabs') if mod && mod.kind_of?(Msf::Module::HasActions) && mod.actions.map(&:name).any? { |a| a.casecmp?(action) } return cmd_run_tabs(*args) if meth.end_with?('_tabs') return do_action(action, *args) end super end # # Note: A change to this method will most likely require a corresponding change to method_missing # def respond_to_missing?(meth, _include_private = true) if mod && mod.respond_to?(meth.to_s, true) return true end action = meth.to_s.delete_prefix('cmd_').delete_suffix('_tabs') if mod && mod.kind_of?(Msf::Module::HasActions) && mod.actions.map(&:name).any? { |a| a.casecmp?(action) } return true end super end # # Execute the module with a set action # def do_action(meth, *args) action = mod.actions.find { |action| action.name.casecmp?(meth) } raise Msf::MissingActionError.new(meth) if action.nil? cmd_run(*args, action: action.name) end def cmd_action_help(action) print_module_run_or_check_usage(command: action.downcase, description: 'Launches a specific module action') end # # Tab completion for the run command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed # def cmd_run_tabs(str, words) flags = @@module_opts_with_action_support.option_keys options = tab_complete_option(active_module, str, words) flags + options end end end end end
1
0.817831
1
0.817831
game-dev
MEDIA
0.398575
game-dev,cli-devtools
0.926411
1
0.926411
X-Hax/SA-Mod-Manager
19,210
SA-Mod-Manager/Configuration/SA2/GameSettings.cs
using System.Collections.Generic; using System.ComponentModel; using SAModManager.Ini; using System.IO; using System.Text.Json; using SAModManager.UI; using System.Text.Json.Serialization; using System.ComponentModel.Design; using System; using SAModManager.Management; // TODO: Build SA2 Game Settings namespace SAModManager.Configuration.SA2 { public enum SA2Lang { English = 0, Deutsch = 1, Espanol = 2, Francais = 3, Japanese = 4, } public class GraphicsSettings { public enum DisplayMode { Windowed, Borderless, CustomWindow, Fullscreen } /// <summary> /// Index for the screen the game will boot on. /// </summary> [DefaultValue(1)] public int SelectedScreen { get; set; } = 1; // SA2LoaderInfo.ScreenNum /// <summary> /// Rendering Horizontal Resolution. /// </summary> [DefaultValue(640)] public int HorizontalResolution { get; set; } = 640; // SA2LoaderInfo.HorizontalResolution /// <summary> /// Rendering Vertical Resolution. /// </summary> [DefaultValue(480)] public int VerticalResolution { get; set; } = 480; // SA2LoaderInfo.VerticalResolution /// <summary> /// Enables the window to be paused when not focused. /// </summary> [DefaultValue(true)] public bool EnablePauseOnInactive { get; set; } = true; // SA2LoaderInfo.PauseWhenInactive /// <summary> /// Sets the Width of the Custom Window Size. /// </summary> [DefaultValue(640)] public int CustomWindowWidth { get; set; } = 640; // SA2LoaderInfo.WindowWidth /// <summary> /// Sets the Height of the Custom Window Size. /// </summary> [DefaultValue(480)] public int CustomWindowHeight { get; set; } = 480; // SA2LoaderInfo.WindowHeight /// <summary> /// Keeps the Resolution's ratio for the Custom Window size. /// </summary> [DefaultValue(false)] public bool EnableKeepResolutionRatio { get; set; } // SA2LoaderInfo.MaintainWindowAspectRatio /// <summary> /// Enables resizing of the game window. /// </summary> [DefaultValue(false)] public bool EnableResizableWindow { get; set; } // SA2LoaderInfo.ResizableWindow /// <summary> /// Sets the Screen Mode (Windowed, Fullscreen, Borderless, or Custom Window) /// </summary> [DefaultValue(DisplayMode.Windowed)] public int ScreenMode { get; set; } = (int)DisplayMode.Windowed; /// <summary> /// Stretches the inner window (game render) to the outer window's size. /// </summary> [DefaultValue(false)] public bool StretchToWindow { get; set; } = false; /// <summary> /// Placed here to provide parity with the launcher as it also allows a language selection. /// This will be saved and used on each boot. /// </summary> [DefaultValue((int)SA2Lang.English)] public int GameTextLanguage { get; set; } = (int)SA2Lang.English; /// <summary> /// Allows skipping the intro to the game. /// </summary> [DefaultValue(false)] public bool SkipIntro { get; set; } = false; /// <summary> /// Sets the monitor's refresh rate when in exclusive full screen mode. /// </summary> [DefaultValue(60)] public int RefreshRate { get; set; } = 60; /// <summary> /// Disables the Border Image from being loaded and rendered. /// </summary> [DefaultValue(false)] public bool DisableBorderImage { get; set; } = false; /// <summary> /// Converts from the original settings file. /// </summary> /// <param name="oldSettings"></param> public void ConvertFromV0(SA2LoaderInfo oldSettings) { SelectedScreen = oldSettings.ScreenNum; HorizontalResolution = oldSettings.HorizontalResolution; VerticalResolution = oldSettings.VerticalResolution; EnablePauseOnInactive = oldSettings.PauseWhenInactive; CustomWindowWidth = oldSettings.WindowWidth; CustomWindowHeight = oldSettings.WindowHeight; EnableKeepResolutionRatio = oldSettings.MaintainAspectRatio; EnableResizableWindow = oldSettings.ResizableWindow; GameTextLanguage = oldSettings.TextLanguage; SkipIntro = oldSettings.SkipIntro; } public void LoadGameConfig(ref SA2GameConfig config) { SelectedScreen = config.Display; HorizontalResolution = config.Width; VerticalResolution = config.Height; GameTextLanguage = config.Language; RefreshRate = config.RefreshRate; } public void LoadConfigs(ref SA2GameConfig config) { LoadGameConfig(ref config); } public void ToGameConfig(ref SA2GameConfig config) { switch ((DisplayMode)ScreenMode) { case DisplayMode.Fullscreen: config.FullScreen = 1; break; default: config.FullScreen = 0; break; } int screenID = SelectedScreen; if (screenID > 0) //adjust offset because the official launcher doesn't have "all screen support" which means first monitor is index 0. screenID -= 1; config.Display = screenID; config.Width = HorizontalResolution; config.Height = VerticalResolution; config.Language = GameTextLanguage; config.RefreshRate = RefreshRate; } public void ToConfigs(ref SA2GameConfig config) { ToGameConfig(ref config); } } public class TestSpawnSettings { public enum GameLanguage { English = 0, German, Spanish, French, Italian, Japanese } /// <summary> /// Enables Character options when launching. /// </summary> [DefaultValue(false)] public bool UseCharacter { get; set; } = false; /// <summary> /// Enables Player 2 options when launching. /// </summary> [DefaultValue(false)] public bool UsePlayer2 { get; set; } = false; /// <summary> /// Enables the Level, Act, and Time of Day options when launching. /// </summary> [DefaultValue(false)] public bool UseLevel { get; set; } = false; /// <summary> /// Enables the Event options when launching. /// </summary> [DefaultValue(false)] public bool UseEvent { get; set; } = false; /// <summary> /// Enables the Save options when launching. /// </summary> [DefaultValue(false)] public bool UseSave { get; set; } = false; /// <summary> /// Selected index for the level used by test spawn. /// </summary> [DefaultValue(-1)] public int LevelIndex { get; set; } = -1; // SA2LoaderInfo.TestSpawnLevel /// <summary> /// Selected index for the act used by test spawn. /// </summary> [DefaultValue(0)] public int MissionIndex { get; set; } = 0; // SA2LoaderInfo.TestSpawnAct /// <summary> /// Selected index for the character used by test spawn. /// </summary> [DefaultValue(-1)] public int CharacterIndex { get; set; } = -1; // SA2LoaderInfo.TestSpawnPlayer2 /// Selected index for the player 2 used by test spawn. /// </summary> [DefaultValue(-1)] public int Player2Index { get; set; } = -1; // SA2LoaderInfo.TestSpawnPlayer2 /// <summary> /// Selected index of an event used by test spawn. /// </summary> [DefaultValue(-1)] public int EventIndex { get; set; } = -1; // SA2LoaderInfo.TestSpawnEvent /// <summary> /// Selected save file index used by test spawn. /// </summary> [DefaultValue(-1)] public int SaveIndex { get; set; } = -1; // SA2LoaderInfo.TestSpawnSaveID /// <summary> /// Sets the game's Text Language. /// </summary> [DefaultValue((int)GameLanguage.English)] public int GameTextLanguage { get; set; } = 0; // SA2LoaderInfo.TextLanguage /// <summary> /// Sets the game's Voice Language. /// </summary> [DefaultValue(1)] public int GameVoiceLanguage { get; set; } = 1; // SA2LoaderInfo.VoiceLanguage /// <summary> /// Enables the Manual settings for Character, Level, and Act. /// </summary> [DefaultValue(false)] public bool UseManual { get; set; } = false; /// <summary> /// Enables the Manual settings for Events/Cutscenes. /// </summary> [DefaultValue(false)] public bool UseEventManual { get; set; } = false; /// <summary> /// Enables manually modifying the start position when using test spawn. /// </summary> [DefaultValue(false)] public bool UsePosition { get; set; } = false; // SA2LoaderInfo.TestSpawnPositionEnabled /// <summary> /// X Position where the player will spawn using test spawn. /// </summary> [DefaultValue(0f)] public float XPosition { get; set; } = 0f; // SA2LoaderInfo.TestSpawnX /// <summary> /// Y Position where the player will spawn using test spawn. /// </summary> [DefaultValue(0f)] public float YPosition { get; set; } = 0f; // SA2LoaderInfo.TestSpawnY /// <summary> /// Z Position where the player will spawn using test spawn. /// </summary> [DefaultValue(0f)] public float ZPosition { get; set; } = 0f; // SA2LoaderInfo.TestSpawnZ /// <summary> /// Initial Y Rotation for the player when using test spawn. /// </summary> [DefaultValue(0)] public int Rotation { get; set; } = 0; // SA2LoaderInfo.TestSpawnRotation /// <summary> /// Converts from original settings file. /// </summary> /// <param name="oldSettings"></param> public void ConvertFromV0(SA2LoaderInfo oldSettings) { LevelIndex = oldSettings.TestSpawnLevel; CharacterIndex = oldSettings.TestSpawnCharacter; Player2Index = oldSettings.TestSpawnPlayer2; EventIndex = oldSettings.TestSpawnEvent; SaveIndex = oldSettings.TestSpawnEvent; GameTextLanguage = oldSettings.TextLanguage; GameVoiceLanguage = oldSettings.VoiceLanguage; UsePosition = oldSettings.TestSpawnPositionEnabled; XPosition = oldSettings.TestSpawnX; YPosition = oldSettings.TestSpawnY; ZPosition = oldSettings.TestSpawnZ; } } [Obsolete] public class GamePatches { [DefaultValue(true)] public bool FramerateLimiter { get; set; } = true; [DefaultValue(true)] public bool DisableExitPrompt { get; set; } = true; [DefaultValue(true)] public bool SyncLoad { get; set; } = true; //disable Omochao loading animation (reduce crash on startup probability) [DefaultValue(true)] public bool ExtendVertexBuffer { get; set; } = true; //incrase the vertex limit per mesh to 32k [DefaultValue(true)] public bool EnvMapFix { get; set; } = true; [DefaultValue(true)] public bool ScreenFadeFix { get; set; } = true; [DefaultValue(true)] public bool CECarFix { get; set; } = true; //intel GPU issue [DefaultValue(true)] public bool ParticlesFix { get; set; } = true; //intel GPU issue } public class GameSettings { /// <summary> /// Versioning. /// </summary> public enum SA2SettingsVersions { v0, // Version 0: Original LoaderInfo Version v1, // Version 1: Launch Version, functional parity with SA2GameSettings. v2, // Version 2: Removed KeepAspectOnResize option, added StretchToWindow and DisableBorderImage v3, // Version 3: Removed old Patch system entirely, moving to new modular system. MAX, // Do Not Modify, new versions are placed above this. } /// <summary> /// Versioning for the SA2 Settings file. /// </summary> [DefaultValue((int)(SA2SettingsVersions.MAX - 1))] public int SettingsVersion { get; set; } = (int)(SA2SettingsVersions.MAX - 1); /// <summary> /// Graphics Settings for SA2. /// </summary> public GraphicsSettings Graphics { get; set; } = new(); /// <summary> /// TestSpawn Settings for SA2. /// </summary> public TestSpawnSettings TestSpawn { get; set; } = new(); /// <summary> /// Game Patch List for SA2. /// </summary> public Dictionary<string, bool> Patches { get; set; } = new Dictionary<string, bool>(); /// <summary> /// Debug Settings. /// </summary> public DebugSettings DebugSettings { get; set; } = new(); /// <summary> /// Path to the game install saved with this configuration. /// </summary> public string GamePath { get; set; } = string.Empty; /// <summary> /// Enabled Mods for SA2. /// </summary> [IniName("Mod")] [IniCollection(IniCollectionMode.NoSquareBrackets, StartIndex = 1)] public List<string> EnabledMods { get; set; } // SA2LoaderInfo.Mods /// <summary> /// Enabled Codes for SA2. /// </summary> [IniName("Code")] [IniCollection(IniCollectionMode.NoSquareBrackets, StartIndex = 1)] public List<string> EnabledCodes { get; set; } // SA2LoaderInfo.EnabledCodes public List<string> ModsList { get; set; } = new(); // used for consistent mod order option /// <summary> /// Converts from original settings file. /// </summary> /// <param name="oldSettings"></param> public void ConvertFromV0(SA2LoaderInfo oldSettings) { Graphics.ConvertFromV0(oldSettings); TestSpawn.ConvertFromV0(oldSettings); DebugSettings.ConvertFromV0(oldSettings); SettingsVersion = (int)SA2SettingsVersions.v1; GamePath = App.CurrentGame.gameDirectory; EnabledMods = oldSettings.Mods; EnabledCodes = oldSettings.EnabledCodes; } /// <summary> /// Writes LoaderInfo and SA2Config files. /// </summary> public void WriteConfigs() { SA2GameConfig config = new SA2GameConfig(); Graphics.ToConfigs(ref config); if (Directory.Exists(GamePath)) { string configfolder = Path.Combine(GamePath, "Config"); Util.CreateSafeDirectory(configfolder); string keyboardPath = Path.GetFullPath(Path.Combine(GamePath, App.CurrentGame.GameConfigFile[0])); //if keyboard config is missing add it (fix game crashes if official launcher was never used) if (File.Exists(keyboardPath) == false) { App.ExtractResource("SA2Keyboard.cfg", keyboardPath); } string configPath = Path.Combine(GamePath, App.CurrentGame.GameConfigFile[1]); config.Serialize(configPath); } else { MessageWindow message = new MessageWindow(Lang.GetString("MessageWindow.Errors.LoaderFailedToSave.Title"), Lang.GetString("MessageWindow.Errors.LoaderFailedToSave"), icon: MessageWindow.Icons.Error); message.ShowDialog(); } } /// <summary> /// Deserializes an SA2 GameSettings JSON File and returns a populated class. /// </summary> /// <param name="path"></param> /// <returns></returns> public static GameSettings Deserialize(string path) { try { if (File.Exists(path)) { string jsonContent = File.ReadAllText(path); GameSettings settings = JsonSerializer.Deserialize<GameSettings>(jsonContent); // This is where the settings versions get bumped on load. // Set in a switch case in the event we need to make changes on a specific version. switch (settings.SettingsVersion) { default: if (settings.SettingsVersion < (int)(SA2SettingsVersions.MAX - 1)) settings.SettingsVersion = (int)(SA2SettingsVersions.MAX - 1); break; } return settings; } else return new(); } catch { return new(); } } /// <summary> /// Serializes an SA2 GameSettings JSON File. /// </summary> /// <param name="path"></param> public void Serialize(string profileName) { if (!profileName.Contains(".json")) profileName += ".json"; // TODO: Fix this function. string path = Path.Combine(ProfileManager.GetProfilesDirectory(), profileName); try { if (Directory.Exists(ProfileManager.GetProfilesDirectory())) { if (profileName == "Default" || profileName == "Default.json") { if (!Path.Exists(path)) { System.Drawing.Rectangle rect = GraphicsManager.GetDisplayBounds(1); if (rect.Height > 0) { Graphics.VerticalResolution = rect.Height; Graphics.HorizontalResolution = rect.Width; Graphics.ScreenMode = (int)GraphicsSettings.DisplayMode.Borderless; } } } string jsonContent = JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true }); File.WriteAllText(path, jsonContent); } } catch { } } } }
1
0.908482
1
0.908482
game-dev
MEDIA
0.843003
game-dev
0.630082
1
0.630082
kunitoki/yup
8,119
thirdparty/rive/include/rive/generated/text/text_base.hpp
#ifndef _RIVE_TEXT_BASE_HPP_ #define _RIVE_TEXT_BASE_HPP_ #include "rive/core/field_types/core_bool_type.hpp" #include "rive/core/field_types/core_double_type.hpp" #include "rive/core/field_types/core_uint_type.hpp" #include "rive/drawable.hpp" namespace rive { class TextBase : public Drawable { protected: typedef Drawable Super; public: static const uint16_t typeKey = 134; /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. bool isTypeOf(uint16_t typeKey) const override { switch (typeKey) { case TextBase::typeKey: case DrawableBase::typeKey: case NodeBase::typeKey: case TransformComponentBase::typeKey: case WorldTransformComponentBase::typeKey: case ContainerComponentBase::typeKey: case ComponentBase::typeKey: return true; default: return false; } } uint16_t coreType() const override { return typeKey; } static const uint16_t alignValuePropertyKey = 281; static const uint16_t sizingValuePropertyKey = 284; static const uint16_t overflowValuePropertyKey = 287; static const uint16_t widthPropertyKey = 285; static const uint16_t heightPropertyKey = 286; static const uint16_t originXPropertyKey = 366; static const uint16_t originYPropertyKey = 367; static const uint16_t paragraphSpacingPropertyKey = 371; static const uint16_t originValuePropertyKey = 377; static const uint16_t wrapValuePropertyKey = 683; static const uint16_t verticalAlignValuePropertyKey = 685; static const uint16_t fitFromBaselinePropertyKey = 703; protected: uint32_t m_AlignValue = 0; uint32_t m_SizingValue = 0; uint32_t m_OverflowValue = 0; float m_Width = 0.0f; float m_Height = 0.0f; float m_OriginX = 0.0f; float m_OriginY = 0.0f; float m_ParagraphSpacing = 0.0f; uint32_t m_OriginValue = 0; uint32_t m_WrapValue = 0; uint32_t m_VerticalAlignValue = 0; bool m_FitFromBaseline = true; public: inline uint32_t alignValue() const { return m_AlignValue; } void alignValue(uint32_t value) { if (m_AlignValue == value) { return; } m_AlignValue = value; alignValueChanged(); } inline uint32_t sizingValue() const { return m_SizingValue; } void sizingValue(uint32_t value) { if (m_SizingValue == value) { return; } m_SizingValue = value; sizingValueChanged(); } inline uint32_t overflowValue() const { return m_OverflowValue; } void overflowValue(uint32_t value) { if (m_OverflowValue == value) { return; } m_OverflowValue = value; overflowValueChanged(); } inline float width() const { return m_Width; } void width(float value) { if (m_Width == value) { return; } m_Width = value; widthChanged(); } inline float height() const { return m_Height; } void height(float value) { if (m_Height == value) { return; } m_Height = value; heightChanged(); } inline float originX() const { return m_OriginX; } void originX(float value) { if (m_OriginX == value) { return; } m_OriginX = value; originXChanged(); } inline float originY() const { return m_OriginY; } void originY(float value) { if (m_OriginY == value) { return; } m_OriginY = value; originYChanged(); } inline float paragraphSpacing() const { return m_ParagraphSpacing; } void paragraphSpacing(float value) { if (m_ParagraphSpacing == value) { return; } m_ParagraphSpacing = value; paragraphSpacingChanged(); } inline uint32_t originValue() const { return m_OriginValue; } void originValue(uint32_t value) { if (m_OriginValue == value) { return; } m_OriginValue = value; originValueChanged(); } inline uint32_t wrapValue() const { return m_WrapValue; } void wrapValue(uint32_t value) { if (m_WrapValue == value) { return; } m_WrapValue = value; wrapValueChanged(); } inline uint32_t verticalAlignValue() const { return m_VerticalAlignValue; } void verticalAlignValue(uint32_t value) { if (m_VerticalAlignValue == value) { return; } m_VerticalAlignValue = value; verticalAlignValueChanged(); } inline bool fitFromBaseline() const { return m_FitFromBaseline; } void fitFromBaseline(bool value) { if (m_FitFromBaseline == value) { return; } m_FitFromBaseline = value; fitFromBaselineChanged(); } Core* clone() const override; void copy(const TextBase& object) { m_AlignValue = object.m_AlignValue; m_SizingValue = object.m_SizingValue; m_OverflowValue = object.m_OverflowValue; m_Width = object.m_Width; m_Height = object.m_Height; m_OriginX = object.m_OriginX; m_OriginY = object.m_OriginY; m_ParagraphSpacing = object.m_ParagraphSpacing; m_OriginValue = object.m_OriginValue; m_WrapValue = object.m_WrapValue; m_VerticalAlignValue = object.m_VerticalAlignValue; m_FitFromBaseline = object.m_FitFromBaseline; Drawable::copy(object); } bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { switch (propertyKey) { case alignValuePropertyKey: m_AlignValue = CoreUintType::deserialize(reader); return true; case sizingValuePropertyKey: m_SizingValue = CoreUintType::deserialize(reader); return true; case overflowValuePropertyKey: m_OverflowValue = CoreUintType::deserialize(reader); return true; case widthPropertyKey: m_Width = CoreDoubleType::deserialize(reader); return true; case heightPropertyKey: m_Height = CoreDoubleType::deserialize(reader); return true; case originXPropertyKey: m_OriginX = CoreDoubleType::deserialize(reader); return true; case originYPropertyKey: m_OriginY = CoreDoubleType::deserialize(reader); return true; case paragraphSpacingPropertyKey: m_ParagraphSpacing = CoreDoubleType::deserialize(reader); return true; case originValuePropertyKey: m_OriginValue = CoreUintType::deserialize(reader); return true; case wrapValuePropertyKey: m_WrapValue = CoreUintType::deserialize(reader); return true; case verticalAlignValuePropertyKey: m_VerticalAlignValue = CoreUintType::deserialize(reader); return true; case fitFromBaselinePropertyKey: m_FitFromBaseline = CoreBoolType::deserialize(reader); return true; } return Drawable::deserialize(propertyKey, reader); } protected: virtual void alignValueChanged() {} virtual void sizingValueChanged() {} virtual void overflowValueChanged() {} virtual void widthChanged() {} virtual void heightChanged() {} virtual void originXChanged() {} virtual void originYChanged() {} virtual void paragraphSpacingChanged() {} virtual void originValueChanged() {} virtual void wrapValueChanged() {} virtual void verticalAlignValueChanged() {} virtual void fitFromBaselineChanged() {} }; } // namespace rive #endif
1
0.910168
1
0.910168
game-dev
MEDIA
0.407302
game-dev
0.891773
1
0.891773
vagenv/Rade
1,057
Source/RLoadingScreenLib/RWidgets/SLoadingCompleteText.h
// Copyright 2015-2023 Vagen Ayrapetyan #pragma once #include "Widgets/SCompoundWidget.h" struct FLoadingCompleteTextSettings; /** * */ class SLoadingCompleteText : public SCompoundWidget { private: // Complete text color FLinearColor CompleteTextColor = FLinearColor::White; // Complete text fade in or fade out animation bool bCompleteTextReverseAnim = false; // Complete text animation speed float CompleteTextAnimationSpeed = 1.0f; // Active timer registered flag bool bIsActiveTimerRegistered = false; public: SLATE_BEGIN_ARGS(SLoadingCompleteText) {} SLATE_END_ARGS() void Construct(const FArguments& InArgs, const FLoadingCompleteTextSettings& CompleteTextSettings); // Getter for text visibility EVisibility GetLoadingCompleteTextVisibility() const; // Getter for complete text color and opacity FSlateColor GetLoadingCompleteTextColor() const; /** Active timer event for animating the image sequence */ EActiveTimerReturnType AnimateText(double InCurrentTime, float InDeltaTime); };
1
0.794286
1
0.794286
game-dev
MEDIA
0.48043
game-dev
0.67217
1
0.67217
tsunhua/egret_demo
6,551
day23_use_layout/src/Main.ts
////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014-present, Egret Technology. // 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 the Egret 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 EGRET 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 EGRET AND 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. // ////////////////////////////////////////////////////////////////////////////////////// class Main extends eui.UILayer { /** * 加载进度界面 * loading process interface */ private loadingView: LoadingUI; protected createChildren(): void { super.createChildren(); //inject the custom material parser //注入自定义的素材解析器 let assetAdapter = new AssetAdapter(); egret.registerImplementation("eui.IAssetAdapter", assetAdapter); egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter()); //Config loading process interface //设置加载进度界面 this.loadingView = new LoadingUI(); this.stage.addChild(this.loadingView); // initialize the Resource loading library //初始化Resource资源加载库 RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this); RES.loadConfig("resource/default.res.json", "resource/"); } /** * 配置文件加载完成,开始预加载皮肤主题资源和preload资源组。 * Loading of configuration file is complete, start to pre-load the theme configuration file and the preload resource group */ private onConfigComplete(event: RES.ResourceEvent): void { RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this); // load skin theme configuration file, you can manually modify the file. And replace the default skin. //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。 let theme = new eui.Theme("resource/default.thm.json", this.stage); theme.addEventListener(eui.UIEvent.COMPLETE, this.onThemeLoadComplete, this); RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this); RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this); RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this); RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this); RES.loadGroup("preload"); } private isThemeLoadEnd: boolean = false; /** * 主题文件加载完成,开始预加载 * Loading of theme configuration file is complete, start to pre-load the */ private onThemeLoadComplete(): void { this.isThemeLoadEnd = true; this.createScene(); } private isResourceLoadEnd: boolean = false; /** * preload资源组加载完成 * preload resource group is loaded */ private onResourceLoadComplete(event: RES.ResourceEvent): void { if (event.groupName == "preload") { this.stage.removeChild(this.loadingView); RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this); RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this); RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this); RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this); this.isResourceLoadEnd = true; this.createScene(); } } private createScene() { if (this.isThemeLoadEnd && this.isResourceLoadEnd) { this.startCreateScene(); } } /** * 资源组加载出错 * The resource group loading failed */ private onItemLoadError(event: RES.ResourceEvent): void { console.warn("Url:" + event.resItem.url + " has failed to load"); } /** * 资源组加载出错 * Resource group loading failed */ private onResourceLoadError(event: RES.ResourceEvent): void { //TODO console.warn("Group:" + event.groupName + " has failed to load"); //忽略加载失败的项目 //ignore loading failed projects this.onResourceLoadComplete(event); } /** * preload资源组加载进度 * loading process of preload resource */ private onResourceProgress(event: RES.ResourceEvent): void { if (event.groupName == "preload") { this.loadingView.setProgress(event.itemsLoaded, event.itemsTotal); } } /** * 创建场景界面 * Create scene interface */ protected startCreateScene(): void { // this.addChild(new ABasicLayout()); // this.addChild(new BHorizontalLayout()); // this.addChild(new CVerticalLayout()); // this.addChild(new DGridLayout()); this.addChild(new ECustomLayout()); } /** * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。 * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json. */ private createBitmapByName(name: string): egret.Bitmap { let result = new egret.Bitmap(); let texture: egret.Texture = RES.getRes(name); result.texture = texture; return result; } }
1
0.964457
1
0.964457
game-dev
MEDIA
0.605435
game-dev
0.898793
1
0.898793
mojontwins/MK2
16,191
examples/journey/dev/engine/enems.h
// MT Engine MK2 v0.90b // Copyleft 2016 the Mojon Twins // enems.h // Enemy management, new style // Ninjajar Clouds not supported, sorry! // Type 5 "random respawn" not supported sorry! (but easily punchable!) // There are new, more suitable defines now. // ENABLE_FANTIES // ENABLE_LINEAR_ENEMIES // ENABLE_PURSUE_ENEMIES // ENABLE_SHOOTERS #include "engine/enemmods/helper_funcs.h" #if WAYS_TO_DIE > 1 #include "engine/enemmods/kill_enemy_multiple.h" #elif defined ENEMS_MAY_DIE #include "engine/enemmods/kill_enemy.h" #endif void enems_init (void) { // Enemies' "t" is now slightly more complex: // XTTTTDNN where // X = dead // TTTT = type 1000 = platform // 0001 = linear // 0010 = flying // 0011 = pursuing // Reserved (addons) // 1001 = drops // 1010 = arrows // 1011 = Hanna Type 11 // 1100 = Hanna Punchos // 01001000 #ifdef COUNT_SCR_ENEMS_ON_FLAG flags [COUNT_SCR_ENEMS_ON_FLAG] = 0; #endif for (gpit = 0; gpit < 3; gpit ++) { //en_an_frame [gpit] = 0; en_an_count [gpit] = 3; en_an_state [gpit] = 0; enoffsmasi = enoffs + gpit; #ifdef RESPAWN_ON_ENTER #ifndef RESPAWN_ON_REENTER if (do_respawn) #endif // Back to life! { baddies [enoffsmasi].t &= 0x7f; en_an_state [gpit] = 0; #if defined (PLAYER_CAN_FIRE) || defined (PLAYER_CAN_PUNCH) || defined (PLAYER_HAZ_SWORD) #ifdef COMPRESSED_LEVELS baddies [enoffsmasi].life = level_data.enems_life; #else baddies [enoffsmasi].life = ENEMS_LIFE_GAUGE; #endif #endif } #endif // Init enems: // - Asign "base frame" // - Init coordinates for flying people // Remember XTTTTDNN, TTTT = type, D = fires balls, NN = sprite number _en_t = baddies [enoffsmasi].t; gpt = _en_t >> 3; if (gpt && gpt < 16) { en_an_base_frame [gpit] = (_en_t & 3) << 1; switch (gpt) { #if defined ENABLE_PATROLLERS && defined PATROLLERS_RESET case 1: // Reset baddies [enoffsmasi].x = baddies [enoffsmasi].x1; baddies [enoffsmasi].y = baddies [enoffsmasi].y1; break; #endif #ifdef ENABLE_FANTIES case 2: // Flying #ifdef FANTIES_FIXED_CELL en_an_base_frame [gpit] = FANTIES_FIXED_CELL << 1; #endif #ifdef FANTIES_INIT_ON_CURRENT en_an_x [gpit] = baddies [enoffsmasi].x << FIXBITS; en_an_y [gpit] = baddies [enoffsmasi].y << FIXBITS; #else en_an_x [gpit] = baddies [enoffsmasi].x1 << FIXBITS; baddies [enoffsmasi].x = baddies [enoffsmasi].x1; en_an_y [gpit] = baddies [enoffsmasi].y1 << FIXBITS; baddies [enoffsmasi].y = baddies [enoffsmasi].y1; #endif en_an_vx [gpit] = en_an_vy [gpit] = 0; #ifdef FANTIES_SIGHT_DISTANCE en_an_state [gpit] = FANTIES_IDLE; #endif break; #endif #ifdef ENABLE_PURSUE_ENEMIES case 3: // Pursuing en_an_alive [gpit] = 0; en_an_dead_row [gpit] = 0;//DEATH_COUNT_EXPRESSION; break; #endif #ifdef ENABLE_CLOUDS case 4: // Make sure mx is positive! baddies [enoffsmasi].mx = abs (baddies [enoffsmasi].mx); break; #endif #ifdef ENABLE_DROPS case 9: #include "addons/drops/init.h" break; #endif #ifdef ENABLE_HANNA_MONSTERS_11 case 11: en_an_state [gpit] = 0; break; #endif #include "my/extra_enems_init.h" default: break; } #ifdef COUNT_SCR_ENEMS_ON_FLAG #if defined (DISABLE_PLATFORMS) || defined (PLAYER_GENITAL) flags [COUNT_SCR_ENEMS_ON_FLAG] ++; #else if (16 != gpt) flags [COUNT_SCR_ENEMS_ON_FLAG] ++; #endif #endif } } } void enems_move_spr_abs (void) { //sp_MoveSprAbs (sp_moviles [enit], spritesClip, en_an_n_f [enit] - en_an_c_f [enit], VIEWPORT_Y + (_en_y >> 3), VIEWPORT_X + (_en_x >> 3), _en_x & 7, _en_y & 7); #asm ; enter: IX = sprite structure address ; IY = clipping rectangle, set it to "ClipStruct" for full screen ; BC = animate bitdef displacement (0 for no animation) ; H = new row coord in chars ; L = new col coord in chars ; D = new horizontal rotation (0..7) ie horizontal pixel position ; E = new vertical rotation (0..7) ie vertical pixel position // sp_moviles [enit] = sp_moviles + enit*2 ld a, (_enit) sla a ld c, a ld b, 0 // BC = offset to [enit] in 16bit arrays ld hl, _sp_moviles add hl, bc ld e, (hl) inc hl ld d, (hl) push de pop ix // Clipping rectangle ld iy, vpClipStruct // Animation // en_an_n_f [enit] - en_an_c_f [enit] ld hl, _en_an_c_f add hl, bc // HL -> en_an_current_frame [enit] ld e, (hl) inc hl ld d, (hl) // DE = en_an_current_frame [enit] ld hl, _en_an_n_f add hl, bc // HL -> en_an_next_frame [enit] ld a, (hl) inc hl ld h, (hl) ld l, a // HL = en_an_next_frame [enit] or a // clear carry sbc hl, de // en_an_next_frame [enit] - en_an_current_frame [enit] push bc // Save for later ld b, h ld c, l // ** BC = animate bitdef ** //VIEWPORT_Y + (_en_y >> 3), VIEWPORT_X + (_en_x >> 3) ld a, (__en_y) srl a srl a srl a add VIEWPORT_Y ld h, a ld a, (__en_x) srl a srl a srl a add VIEWPORT_X ld l, a // _en_x & 7, _en_y & 7 ld a, (__en_x) and 7 ld d, a ld a, (__en_y) and 7 ld e, a call SPMoveSprAbs // en_an_c_f [enit] = en_an_n_f [enit]; pop bc // Retrieve index ld hl, _en_an_c_f add hl, bc ex de, hl // DE -> en_an_c_f [enit] ld hl, _en_an_n_f add hl, bc // HL -> en_an_n_f [enit] ldi ldi #endasm } void enems_move (void) { #if !defined (PLAYER_GENITAL) || defined (PLAYER_NEW_GENITAL) p_gotten = ptgmy = ptgmx = 0; #endif tocado = 0; #ifdef ENEMS_MAY_DIE enemy_was_killed = 0; #endif for (enit = 0; enit < 3; ++ enit) { active = killable = animate = 0; enoffsmasi = enoffs + enit; // Copy array values to temporary variables as fast as possible #asm // Those values are stores in this order: // x, y, x1, y1, x2, y2, mx, my, t, life // Point HL to baddies [enoffsmasi]. The struct is 10 bytes long // so this is baddies + enoffsmasi*10 ld hl, (_enoffsmasi) ld h, 0 add hl, hl // x2 ld d, h ld e, l // DE = x2 add hl, hl // x4 add hl, hl // x8 add hl, de // HL = x8 + x2 = x10 ld de, _baddies add hl, de ld (__baddies_pointer), hl // Save address for later ld a, (hl) ld (__en_x), a inc hl ld a, (hl) ld (__en_y), a inc hl ld a, (hl) ld (__en_x1), a inc hl ld a, (hl) ld (__en_y1), a inc hl ld a, (hl) ld (__en_x2), a inc hl ld a, (hl) ld (__en_y2), a inc hl ld a, (hl) ld (__en_mx), a inc hl ld a, (hl) ld (__en_my), a inc hl ld a, (hl) ld (__en_t), a inc hl ld a, (hl) ld (__en_life), a #endasm if (_en_t == 0) { en_an_n_f [enit] = sprite_18_a; } #ifdef ENEMS_MAY_DIE else if (en_an_state [enit] == GENERAL_DYING) { if (en_an_count [enit]) { -- en_an_count [enit]; en_an_n_f [enit] = sprite_17_a; } else { #ifndef MODE_128K beep_fx (SFX_KILL_ENEMY); #endif en_an_state [enit] = 0; en_an_n_f [enit] = sprite_18_a; } } #endif else { #if defined (ENABLE_SHOOTERS) || defined (ENABLE_ARROWS) if (_en_t & 4) { enemy_shoots = 1; } else enemy_shoots = 0; #endif gpt = _en_t >> 3; // Gotten preliminary: if (gpt == 8) { #ifdef PLAYER_NEW_GENITAL /* pregotten = (gpx + 12 >= _en_x && gpx <= _en_x + 12) && (gpy + 15 >= _en_y && gpy <= _en_y); */ #asm // gpx + 12 >= _en_x ld a, (__en_x) ld c, a ld a, (_gpx) add 12 cp c jp c, _enems_move_pregotten_not // branch if < // gpx <= _en_x + 12; _en_x + 12 >= gpx ld a, (_gpx) ld c, a ld a, (__en_x) add 12 cp c jp c, _enems_move_pregotten_not // branch if < // gpy + 15 >= _en_y ld a, (__en_y) ld c, a ld a, (_gpy) add 15 cp c jp c, _enems_move_pregotten_not // branch if < // gpy <= _en_y; _en_y >= gpy ld a, (_gpy) ld c, a ld a, (__en_y) cp c jp c, _enems_move_pregotten_not // branch if < ld a, 1 jr _enems_move_pregotten_set ._enems_move_pregotten_not xor a ._enems_move_pregotten_set ld (_pregotten), a // enemy_shoots = (_en_t & 4); // gpt = _en_t >> 3; ld a, (__en_t) ld c, a and 4 ld (_enemy_shoots), a ld a, c srl a srl a srl a ld (_gpt), a #endasm #elif !defined (PLAYER_GENITAL) #if defined (BOUNDING_BOX_8_CENTERED) || defined (BOUNDING_BOX_8_BOTTOM) // pregotten = (gpx + 12 >= _en_x && gpx <= _en_x + 12); #asm // gpx + 12 >= _en_x ld a, (__en_x) ld c, a ld a, (_gpx) add 12 cp c jp c, _enems_move_pregotten_not // branch if < // gpx <= _en_x + 12; _en_x + 12 >= gpx ld a, (_gpx) ld c, a ld a, (__en_x) add 12 cp c jp c, _enems_move_pregotten_not // branch if < ld a, 1 jr _enems_move_pregotten_set ._enems_move_pregotten_not xor a ._enems_move_pregotten_set ld (_pregotten), a #endasm #else // pregotten = (gpx + 12 >= _en_x && gpx <= _en_x + 12); #asm // gpx + 15 >= _en_x ld a, (__en_x) ld c, a ld a, (_gpx) add 12 cp c jp c, _enems_move_pregotten_not // branch if < // gpx <= _en_x + 15; _en_x + 12 >= gpx ld a, (_gpx) ld c, a ld a, (__en_x) add 12 cp c jp c, _enems_move_pregotten_not // branch if < ld a, 1 jr _enems_move_pregotten_set ._enems_move_pregotten_not xor a ._enems_move_pregotten_set ld (_pregotten), a #endasm #endif #endif } switch (gpt) { #ifdef ENABLE_PATROLLERS case 1: // linear killable = 1; case 8: // moving platforms #include "engine/enemmods/move_linear.h" break; #endif #ifdef ENABLE_FANTIES case 2: // flying #include "engine/enemmods/move_fanty_asm.h" break; #endif #ifdef ENABLE_PURSUERS case 3: // pursuers #include "engine/enemmods/move_pursuers.h" break; #endif #ifdef ENABLE_CLOUDS case 4: #include "engine/enemmods/move_clouds.h" break; #endif #ifdef ENABLE_DROPS case 9: // drops #ifdef DROPS_KILLABLE killable = 1; #endif #include "addons/drops/move.h" break; #endif #ifdef ENABLE_ARROWS case 10: // arrows #ifdef ARROWS_KILLABLE killable = 1; #endif #include "addons/arrows/move.h" break; #endif #ifdef ENABLE_HANNA_MONSTERS_11 case 11: // Hanna monsters type 11 #include "engine/enemmods/move_hanna_11.h" break; #endif #include "my/extra_enems_move.h" default: en_an_n_f [enit] = sprite_18_a; } if (active) { if (animate) { #ifdef FANTIES_WITH_FACING if (gpt == 2) { gpjt = (gpx > _en_x); } else #endif { gpjt = _en_mx ? ((_en_x + 4) >> 3) & 1 : ((_en_y + 4) >> 3) & 1; } en_an_n_f [enit] = enem_frames [en_an_base_frame [enit] + gpjt]; } // Carriable box launched and hit... #ifdef ENABLE_FO_CARRIABLE_BOXES #ifdef CARRIABLE_BOXES_THROWABLE #include "engine/enemmods/throwable.h" #endif #endif // Hitter #if defined (PLAYER_CAN_PUNCH) || defined (PLAYER_HAZ_SWORD) || defined (PLAYER_HAZ_WHIP) #include "engine/enemmods/hitter.h" #endif // Bombs #if defined (PLAYER_SIMPLE_BOMBS) #include "engine/enemmods/bombs.h" #endif // Bullets #ifdef PLAYER_CAN_FIRE #include "engine/enemmods/bullets.h" #endif // Collide with player #if !defined (DISABLE_PLATFORMS) #ifdef PLAYER_NEW_GENITAL #include "engine/enemmods/platforms_25d.h" #elif !defined (PLAYER_GENITAL) #include "engine/enemmods/platforms.h" #endif #endif // ends with } else //if ((tocado == 0) && collide (gpx, gpy, _en_x, _en_y) && p_state == EST_NORMAL) #asm ld a, (_tocado) or a jp nz, _enems_collision_skip ld a, (_p_state) or a jp nz, _enems_collision_skip // (gpx + 8 >= _en_x && gpx <= _en_x + 8 && gpy + 8 >= _en_y && gpy <= _en_y + 8) // gpx + 8 >= _en_x ld a, (__en_x) ld c, a ld a, (_gpx) #ifdef SMALL_COLLISION add 8 #else add 12 #endif cp c jp c, _enems_collision_skip // gpx <= _en_x + 8; _en_x + 8 >= gpx ld a, (_gpx) ld c, a ld a, (__en_x) #ifdef SMALL_COLLISION add 8 #else add 12 #endif cp c jp c, _enems_collision_skip // gpy + 8 >= _en_y ld a, (__en_y) ld c, a ld a, (_gpy) #ifdef SMALL_COLLISION add 8 #else add 12 #endif cp c jp c, _enems_collision_skip // gpy <= _en_y + 8; _en_y + 8 >= gpy ld a, (_gpy) ld c, a ld a, (__en_y) #ifdef SMALL_COLLISION add 8 #else add 12 #endif cp c jp c, _enems_collision_skip #endasm { #ifdef PLAYER_KILLS_ENEMIES #include "engine/enemmods/step_on.h" #endif if (p_life) { tocado = 1; } #if defined (SLOW_DRAIN) && defined (PLAYER_BOUNCES) if ((lasttimehit == 0) || ((maincounter & 3) == 0)) { p_killme = SFX_PLAYER_DEATH_ENEMY; #ifdef CUSTOM_HIT was_hit_by_type = gpt; #endif } #else p_killme = SFX_PLAYER_DEATH_ENEMY; #ifdef CUSTOM_HIT was_hit_by_type = gpt; #endif #endif #ifdef FANTIES_KILL_ON_TOUCH if (gpt == 2) enems_kill (FANTIES_LIFE_GAUGE); #endif #ifdef PLAYER_BOUNCES #ifndef PLAYER_GENITAL p_vx = addsign (_en_mx, PLAYER_VX_MAX << 1); p_vy = addsign (_en_my, PLAYER_VX_MAX << 1); #else if (_en_mx) { p_vx = addsign (gpx - _en_x, abs (_en_mx) << (2+FIXBITS)); } if (_en_my) { p_vy = addsign (gpy - _en_y, abs (_en_my) << (2+FIXBITS)); } #endif #endif } #asm ._enems_collision_skip #endasm } } enems_loop_continue: #asm .enems_loop_continue_a #endasm // Render #ifdef PIXEL_SHIFT if ((_en_t & 0x78) == 8) gpen_y -= PIXEL_SHIFT; #endif enems_move_spr_abs (); #asm // Those values are stores in this order: // x, y, x1, y1, x2, y2, mx, my, t, life ld hl, (__baddies_pointer) // Restore pointer ld a, (__en_x) ld (hl), a inc hl ld a, (__en_y) ld (hl), a inc hl ld a, (__en_x1) ld (hl), a inc hl ld a, (__en_y1) ld (hl), a inc hl ld a, (__en_x2) ld (hl), a inc hl ld a, (__en_y2) ld (hl), a inc hl ld a, (__en_mx) ld (hl), a inc hl ld a, (__en_my) ld (hl), a inc hl ld a, (__en_t) ld (hl), a inc hl ld a, (__en_life) ld (hl), a #endasm } #if defined (SLOW_DRAIN) && defined (PLAYER_BOUNCES) lasttimehit = tocado; #endif #ifdef ENEMS_MAY_DIE if (enemy_was_killed) { // Run script on kill #ifdef ACTIVATE_SCRIPTING #ifdef RUN_SCRIPT_ON_KILL run_script (2 * MAP_W * MAP_H + 5); #endif #endif } #endif }
1
0.885284
1
0.885284
game-dev
MEDIA
0.942215
game-dev
0.944311
1
0.944311
jonthysell/Mzinga
2,647
src/Mzinga.Viewer/BoardExtensions.cs
// Copyright (c) Jon Thysell <http://jonthysell.com> // Licensed under the MIT License. using System; using System.Collections.Generic; using Mzinga.Core; namespace Mzinga.Viewer { static class BoardExtensions { public static IEnumerable<PieceName> GetPiecesInPlay(this Board board) { for (int pn = 0; pn < (int)PieceName.NumPieceNames; pn++) { var pieceName = (PieceName)pn; if (board.PieceInPlay(pieceName) && Enums.PieceNameIsEnabledForGameType(pieceName, board.GameType)) { yield return pieceName; } } } public static IEnumerable<PieceName> GetWhiteHand(this Board board) { for (int pn = (int)PieceName.wQ; pn < (int)PieceName.bQ; pn++) { var pieceName = (PieceName)pn; if (board.PieceInHand(pieceName) && Enums.PieceNameIsEnabledForGameType(pieceName, board.GameType)) { yield return pieceName; } } } public static IEnumerable<PieceName> GetBlackHand(this Board board) { for (int pn = (int)PieceName.bQ; pn < (int)PieceName.NumPieceNames; pn++) { var pieceName = (PieceName)pn; if (board.PieceInHand(pieceName) && Enums.PieceNameIsEnabledForGameType(pieceName, board.GameType)) { yield return pieceName; } } } public static int GetHeight(this Board board) { bool pieceInPlay = false; int minY = int.MaxValue; int maxY = int.MinValue; foreach (PieceName pieceName in board.GetPiecesInPlay()) { pieceInPlay = true; Position pos = board.GetPosition(pieceName); minY = Math.Min(minY, 1 - pos.Q - pos.R); maxY = Math.Max(maxY, 1- pos.Q - pos.R); } return pieceInPlay ? (maxY - minY) : 0; } public static int GetWidth(this Board board) { bool pieceInPlay = false; int minX = int.MaxValue; int maxX = int.MinValue; foreach (PieceName pieceName in board.GetPiecesInPlay()) { pieceInPlay = true; Position pos = board.GetPosition(pieceName); minX = Math.Min(minX, pos.Q); maxX = Math.Max(maxX, pos.Q); } return pieceInPlay ? (maxX - minX) : 0; } } }
1
0.898776
1
0.898776
game-dev
MEDIA
0.886068
game-dev
0.926168
1
0.926168
DataDog/dd-trace-dotnet
2,630
tracer/src/Datadog.Trace/Generated/netcoreapp3.1/Datadog.Trace.SourceGenerators/TagListGenerator/AwsKinesisTags.g.cs
// <copyright company="Datadog"> // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // </copyright> // <auto-generated/> #nullable enable using Datadog.Trace.Processors; using Datadog.Trace.Tagging; using System; namespace Datadog.Trace.Tagging { partial class AwsKinesisTags { // StreamNameBytes = MessagePack.Serialize("streamname"); private static ReadOnlySpan<byte> StreamNameBytes => new byte[] { 170, 115, 116, 114, 101, 97, 109, 110, 97, 109, 101 }; // SpanKindBytes = MessagePack.Serialize("span.kind"); private static ReadOnlySpan<byte> SpanKindBytes => new byte[] { 169, 115, 112, 97, 110, 46, 107, 105, 110, 100 }; public override string? GetTag(string key) { return key switch { "streamname" => StreamName, "span.kind" => SpanKind, _ => base.GetTag(key), }; } public override void SetTag(string key, string value) { switch(key) { case "streamname": StreamName = value; break; case "span.kind": Logger.Value.Warning("Attempted to set readonly tag {TagName} on {TagType}. Ignoring.", key, nameof(AwsKinesisTags)); break; default: base.SetTag(key, value); break; } } public override void EnumerateTags<TProcessor>(ref TProcessor processor) { if (StreamName is not null) { processor.Process(new TagItem<string>("streamname", StreamName, StreamNameBytes)); } if (SpanKind is not null) { processor.Process(new TagItem<string>("span.kind", SpanKind, SpanKindBytes)); } base.EnumerateTags(ref processor); } protected override void WriteAdditionalTags(System.Text.StringBuilder sb) { if (StreamName is not null) { sb.Append("streamname (tag):") .Append(StreamName) .Append(','); } if (SpanKind is not null) { sb.Append("span.kind (tag):") .Append(SpanKind) .Append(','); } base.WriteAdditionalTags(sb); } } }
1
0.917164
1
0.917164
game-dev
MEDIA
0.730426
game-dev
0.910569
1
0.910569
lge-ros2/cloisim
5,890
Assets/Scripts/Tools/SDF/Helper/Link.cs
/* * Copyright (c) 2020 LG Electronics Inc. * * SPDX-License-Identifier: MIT */ using System.Collections.Generic; using UE = UnityEngine; namespace SDF { namespace Helper { public class Link : Base { private Model _parentModelHelper = null; private UE.ArticulationBody _artBody = null; private UE.ArticulationBody _parentArtBody = null; private Link _parentLink = null; private UE.Pose _jointPose = UE.Pose.identity; private bool _isParentLinkModel = false; [UE.Header("Properties")] public bool drawInertia = false; public bool drawContact = true; [UE.Header("SDF Properties")] public bool isSelfCollide = false; public bool useGravity = true; [UE.Header("Joint related")] private string jointName = string.Empty; private string jointParentLinkName = string.Empty; private string jointChildLinkName = string.Empty; private UE.Pose _jointAnchorPose = new UE.Pose(); #if true // TODO: Candidate to remove due to AriticulationBody.maxJointVelocity private float _jointAxisLimitVelocity = float.NaN; private float _jointAxis2LimitVelocity = float.NaN; #endif private List<UE.ContactPoint> collisionContacts = new List<UE.ContactPoint>(); private SensorDevices.Battery _battery = null; public SensorDevices.Battery Battery => _battery; public string JointName { get => this.jointName; set => this.jointName = value; } public string JointParentLinkName { get => this.jointParentLinkName; set => this.jointParentLinkName = value; } public string JointChildLinkName { get => this.jointChildLinkName; set => this.jointChildLinkName = value; } #if true // TODO: Candidate to remove due to AriticulationBody.maxJointVelocity public float JointAxisLimitVelocity { get => this._jointAxisLimitVelocity; set => this._jointAxisLimitVelocity = value; } public float JointAxis2LimitVelocity { get => this._jointAxis2LimitVelocity; set => this._jointAxis2LimitVelocity = value; } #endif public UE.Pose LinkJointPose => _jointPose; public Model Model => _parentModelHelper; new protected void Awake() { base.Awake(); _parentModelHelper = transform.parent?.GetComponent<Model>(); _jointAnchorPose = UE.Pose.identity; } // Start is called before the first frame update new protected void Start() { base.Start(); var parentArtBodies = GetComponentsInParent<UE.ArticulationBody>(); if (parentArtBodies.Length > 0) { _artBody = parentArtBodies[0]; if (parentArtBodies.Length > 1) { _parentArtBody = parentArtBodies[1]; _parentLink = _parentArtBody.gameObject.GetComponent<Link>(); } } if (transform.parent.CompareTag("Link")) { _isParentLinkModel = true; } // Handle self collision if (!isSelfCollide) { IgnoreSelfCollision(); } } void LateUpdate() { SetPose(transform.localPosition, transform.localRotation, 1); if (_artBody != null) { _jointAnchorPose.position = _artBody.anchorPosition; _jointAnchorPose.rotation = _artBody.anchorRotation; } _jointPose.position = transform.localPosition + _jointAnchorPose.position; _jointPose.rotation = transform.localRotation * _jointAnchorPose.rotation; if (_parentLink != null && _isParentLinkModel == false) { _jointPose.position -= _parentLink._jointPose.position; } } void OnDrawGizmos() { if (_artBody && drawInertia) { UE.Gizmos.color = new UE.Color(0.45f, 0.1f, 0.15f, 0.3f); var region = _artBody.inertiaTensor; if (region.x < 1f && region.y < 1f && region.z < 1f) { region.Set(region.magnitude / region.x, region.magnitude / region.y, region.magnitude / region.z); } region = region.normalized; UE.Gizmos.DrawCube(transform.position, region); } lock (this.collisionContacts) { if (drawContact && collisionContacts != null && collisionContacts.Count > 0) { var contactColor = UE.Color.cyan; contactColor.b = UE.Random.Range(0.5f, 1.0f); // Debug-draw all contact points and normals for (var i = 0; i < collisionContacts.Count; i++) { var contact = collisionContacts[i]; UE.Debug.DrawRay(contact.point, contact.normal, contactColor); } collisionContacts.Clear(); } } } void OnJointBreak(float breakForce) { UE.Debug.Log("A joint has just been broken!, force: " + breakForce); } #if UNITY_EDITOR void OnCollisionStay(UE.Collision collisionInfo) { lock (this.collisionContacts) { // UE.Debug.Log(name + " |Stay| " + collisionInfo.gameObject.name); collisionInfo.GetContacts(this.collisionContacts); } } #endif private UE.Collider[] GetCollidersInChildren() { return GetComponentsInChildren<UE.Collider>(); } private void IgnoreSelfCollision() { if (RootModel == null) { return; } var otherLinkPlugins = RootModel.GetComponentsInChildren<Link>(); var thisColliders = GetCollidersInChildren(); foreach (var otherLinkPlugin in otherLinkPlugins) { if (otherLinkPlugin.Equals(this)) { // Debug.LogWarningFormat("Skip, this Component{0} is same!!!", name); continue; } foreach (var otherCollider in otherLinkPlugin.GetCollidersInChildren()) { foreach (var thisCollider in thisColliders) { UE.Physics.IgnoreCollision(thisCollider, otherCollider); // Debug.Log("Ignore Collision(" + name + "): " + thisCollider.name + " <-> " + otherCollider.name); } } } } public void AttachBattery(in string name, in float initVoltage) { if (_battery == null) { _battery = new SensorDevices.Battery(name); } _battery.SetMax(initVoltage); } } } }
1
0.886479
1
0.886479
game-dev
MEDIA
0.938073
game-dev
0.947126
1
0.947126
RedpointArchive/Protogame
2,614
Protogame/Core/TemporaryFinalTransform.cs
// ReSharper disable CheckNamespace #pragma warning disable 1591 using Microsoft.Xna.Framework; using Protoinject; namespace Protogame { /// <summary> /// An implementation of <see cref="IFinalTransform"/> which is used in temporary contexts, /// like network replay scenarios. /// </summary> /// <module>Core API</module> /// <internal>True</internal> /// <interface_ref>Protogame.IFinalTransform</interface_ref> public class TemporaryFinalTransform : IFinalTransform { private IHasTransform _parent; private IHasTransform _child; public TemporaryFinalTransform(IHasTransform parent, IHasTransform child) { _parent = parent; _child = child; } public Matrix AbsoluteMatrix { get { if (_parent != null) { return _child.Transform.LocalMatrix * _parent.FinalTransform.AbsoluteMatrix; } return _child.Transform.LocalMatrix; } } public Matrix AbsoluteMatrixWithoutScale { get { if (_parent != null) { return _child.Transform.LocalMatrixWithoutScale * _parent.FinalTransform.AbsoluteMatrixWithoutScale; } return _child.Transform.LocalMatrixWithoutScale; } } public Vector3 AbsolutePosition => Vector3.Transform(Vector3.Zero, AbsoluteMatrix); public Quaternion AbsoluteRotation { get { Vector3 scale, translation; Quaternion rotation; if (AbsoluteMatrixWithoutScale.Decompose(out scale, out rotation, out translation)) { return rotation; } return Quaternion.Identity; } } public IFinalTransform Parent => _parent?.FinalTransform; public IHasTransform ParentObject => _parent; public ITransform Child => _child.Transform; public IHasTransform ChildObject => _child; public override string ToString() { if (_child.Transform.IsSRTMatrix) { if ((_parent != null && _parent.Transform.IsSRTMatrix) || _parent == null) { return "AT SRT P: " + AbsolutePosition + " R: " + AbsoluteRotation + " M: " + AbsoluteMatrix; } } return "AT CUS M: " + AbsoluteMatrix; } } }
1
0.970207
1
0.970207
game-dev
MEDIA
0.348823
game-dev
0.977129
1
0.977129
iZeStudios/iZeMod
3,458
src/main/java/net/izestudios/izemod/component/command/impl/HelpCommand.java
/* * This file is part of iZeMod - https://github.com/iZeStudios/iZeMod * Copyright (C) 2025 iZeStudios and GitHub contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.izestudios.izemod.component.command.impl; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import java.util.ArrayList; import java.util.List; import net.izestudios.izemod.api.command.AbstractCommand; import net.izestudios.izemod.component.command.CommandHandlerImpl; import net.minecraft.ChatFormatting; import net.minecraft.commands.SharedSuggestionProvider; import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.HoverEvent; import net.minecraft.network.chat.MutableComponent; public final class HelpCommand extends AbstractCommand { private static final int CMDS_PER_PAGE = 5; public HelpCommand() { super(Component.translatable("commands.help"), "help"); } private int execute(final int page) { final List<AbstractCommand> commands = new ArrayList<>(CommandHandlerImpl.INSTANCE.getCommands()); final int pageCount = Math.max((int) Math.ceil((double) commands.size() / CMDS_PER_PAGE), 1); if (page > pageCount || page < 1) { printErrorMessage(Component.translatable("commands.help.invalid", page)); return FAILURE; } printEmptyLine(); printPrefixedChatMessage(Component.translatable("commands.help.success", page, pageCount).withStyle(ChatFormatting.GOLD)); printEmptyLine(); final int start = (page - 1) * CMDS_PER_PAGE; final int end = Math.min(page * CMDS_PER_PAGE, commands.size()); for (int i = start; i < end; i++) { final AbstractCommand command = commands.get(i); final String alias = CommandHandlerImpl.PREFIX + command.getCommand(); final MutableComponent commandComponent = Component.literal(alias).withStyle(ChatFormatting.RED); printChatMessage(commandComponent.withStyle(style -> { if (command.getDescription() != null) { style = style.withHoverEvent(new HoverEvent.ShowText(command.getDescription())); } return style.withClickEvent(new ClickEvent.SuggestCommand(alias)); } )); } printEmptyLine(); return SUCCESS; } @Override public void builder(final LiteralArgumentBuilder<SharedSuggestionProvider> builder) { builder.executes(context -> execute(1)).then(argument("page", IntegerArgumentType.integer(1)).executes(context -> { final int page = IntegerArgumentType.getInteger(context, "page"); return execute(page); })); } }
1
0.841341
1
0.841341
game-dev
MEDIA
0.82306
game-dev
0.933689
1
0.933689
Dawn-of-Light/DOLSharp
56,194
GameServerScripts/quests/Albion/epic/Shadows50.cs
/* *Author : Etaew - Fallen Realms *Editor : Gandulf *Source : http://camelot.allakhazam.com *Date : 8 December 2004 *Quest Name : Feast of the Decadent (level 50) *Quest Classes : Cabalist, Reaver, Mercenary, Necromancer and Infiltrator (Guild of Shadows), Heretic *Quest Version : v1 * *ToDo: * Add Bonuses to Epic Items * Add correct Text * Find Helm ModelID for epics.. */ using System; using System.Reflection; using DOL.Database; using DOL.Events; using DOL.GS.Geometry; using DOL.GS.PacketHandler; using log4net; namespace DOL.GS.Quests.Albion { public class Shadows_50 : BaseQuest { /// <summary> /// Defines a logger for this class. /// </summary> private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected const string questTitle = "Feast of the Decadent"; protected const int minimumLevel = 50; protected const int maximumLevel = 50; private static GameNPC Lidmann = null; // Start NPC private static GameNPC Uragaig = null; // Mob to kill private static ItemTemplate sealed_pouch = null; //sealed pouch private static ItemTemplate MercenaryEpicBoots = null; // of the Shadowy Embers Boots private static ItemTemplate MercenaryEpicHelm = null; // of the Shadowy Embers Coif private static ItemTemplate MercenaryEpicGloves = null; // of the Shadowy Embers Gloves private static ItemTemplate MercenaryEpicVest = null; // of the Shadowy Embers Hauberk private static ItemTemplate MercenaryEpicLegs = null; // of the Shadowy Embers Legs private static ItemTemplate MercenaryEpicArms = null; // of the Shadowy Embers Sleeves private static ItemTemplate ReaverEpicBoots = null; //Shadow Shrouded Boots private static ItemTemplate ReaverEpicHelm = null; //Shadow Shrouded Coif private static ItemTemplate ReaverEpicGloves = null; //Shadow Shrouded Gloves private static ItemTemplate ReaverEpicVest = null; //Shadow Shrouded Hauberk private static ItemTemplate ReaverEpicLegs = null; //Shadow Shrouded Legs private static ItemTemplate ReaverEpicArms = null; //Shadow Shrouded Sleeves private static ItemTemplate CabalistEpicBoots = null; //Valhalla Touched Boots private static ItemTemplate CabalistEpicHelm = null; //Valhalla Touched Coif private static ItemTemplate CabalistEpicGloves = null; //Valhalla Touched Gloves private static ItemTemplate CabalistEpicVest = null; //Valhalla Touched Hauberk private static ItemTemplate CabalistEpicLegs = null; //Valhalla Touched Legs private static ItemTemplate CabalistEpicArms = null; //Valhalla Touched Sleeves private static ItemTemplate InfiltratorEpicBoots = null; //Subterranean Boots private static ItemTemplate InfiltratorEpicHelm = null; //Subterranean Coif private static ItemTemplate InfiltratorEpicGloves = null; //Subterranean Gloves private static ItemTemplate InfiltratorEpicVest = null; //Subterranean Hauberk private static ItemTemplate InfiltratorEpicLegs = null; //Subterranean Legs private static ItemTemplate InfiltratorEpicArms = null; //Subterranean Sleeves private static ItemTemplate NecromancerEpicBoots = null; //Subterranean Boots private static ItemTemplate NecromancerEpicHelm = null; //Subterranean Coif private static ItemTemplate NecromancerEpicGloves = null; //Subterranean Gloves private static ItemTemplate NecromancerEpicVest = null; //Subterranean Hauberk private static ItemTemplate NecromancerEpicLegs = null; //Subterranean Legs private static ItemTemplate NecromancerEpicArms = null; //Subterranean Sleeves private static ItemTemplate HereticEpicBoots = null; private static ItemTemplate HereticEpicHelm = null; private static ItemTemplate HereticEpicGloves = null; private static ItemTemplate HereticEpicVest = null; private static ItemTemplate HereticEpicLegs = null; private static ItemTemplate HereticEpicArms = null; // Constructors public Shadows_50() : base() { } public Shadows_50(GamePlayer questingPlayer) : base(questingPlayer) { } public Shadows_50(GamePlayer questingPlayer, int step) : base(questingPlayer, step) { } public Shadows_50(GamePlayer questingPlayer, DBQuest dbQuest) : base(questingPlayer, dbQuest) { } [ScriptLoadedEvent] public static void ScriptLoaded(DOLEvent e, object sender, EventArgs args) { if (!ServerProperties.Properties.LOAD_QUESTS) return; if (log.IsInfoEnabled) log.Info("Quest \"" + questTitle + "\" initializing ..."); #region NPC Declarations GameNPC[] npcs = WorldMgr.GetNPCsByName("Lidmann Halsey", eRealm.Albion); if (npcs.Length > 0) foreach (GameNPC npc in npcs) if (npc.CurrentRegionID == 1) { Lidmann = npc; break; } if (Lidmann == null) { if (log.IsWarnEnabled) log.Warn("Could not find Lidmann Halsey, creating it ..."); Lidmann = new GameNPC(); Lidmann.Model = 64; Lidmann.Name = "Lidmann Halsey"; Lidmann.GuildName = ""; Lidmann.Realm = eRealm.Albion; Lidmann.Size = 50; Lidmann.Level = 50; Lidmann.Position = Position.Create(regionID: 1, x: 466464, y: 634554, z: 1954, heading: 1809); Lidmann.AddToWorld(); if (SAVE_INTO_DATABASE) { Lidmann.SaveIntoDatabase(); } } // end npc npcs = WorldMgr.GetNPCsByName("Cailleach Uragaig", eRealm.None); if (npcs.Length > 0) foreach (GameNPC npc in npcs) if (npc.CurrentRegionID == 1) { Uragaig = npc; break; } if (Uragaig == null) { if (log.IsWarnEnabled) log.Warn("Could not find Uragaig , creating it ..."); Uragaig = new GameNPC(); Uragaig.Model = 349; Uragaig.Name = "Cailleach Uragaig"; Uragaig.GuildName = ""; Uragaig.Realm = eRealm.None; Uragaig.Size = 55; Uragaig.Level = 70; Uragaig.Position = Position.Create(regionID: 1, x: 316218, y: 664484, z: 2736, heading: 3072); Uragaig.AddToWorld(); if (SAVE_INTO_DATABASE) { Uragaig.SaveIntoDatabase(); } } // end npc #endregion #region Item Declarations #region misc sealed_pouch = GameServer.Database.FindObjectByKey<ItemTemplate>("sealed_pouch"); if (sealed_pouch == null) { if (log.IsWarnEnabled) log.Warn("Could not find Sealed Pouch , creating it ..."); sealed_pouch = new ItemTemplate(); sealed_pouch.Id_nb = "sealed_pouch"; sealed_pouch.Name = "Sealed Pouch"; sealed_pouch.Level = 8; sealed_pouch.Item_Type = 29; sealed_pouch.Model = 488; sealed_pouch.IsDropable = false; sealed_pouch.IsPickable = false; sealed_pouch.DPS_AF = 0; sealed_pouch.SPD_ABS = 0; sealed_pouch.Object_Type = 41; sealed_pouch.Hand = 0; sealed_pouch.Type_Damage = 0; sealed_pouch.Quality = 100; sealed_pouch.Weight = 12; if (SAVE_INTO_DATABASE) { GameServer.Database.AddObject(sealed_pouch); } } #endregion // end item ItemTemplate i = null; #region Mercenary MercenaryEpicBoots = GameServer.Database.FindObjectByKey<ItemTemplate>("MercenaryEpicBoots"); if (MercenaryEpicBoots == null) { i = new ItemTemplate(); i.Id_nb = "MercenaryEpicBoots"; i.Name = "Boots of the Shadowy Embers"; i.Level = 50; i.Item_Type = 23; i.Model = 722; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 100; i.SPD_ABS = 27; i.Object_Type = 35; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 15; i.Bonus1Type = (int)eStat.DEX; i.Bonus2 = 16; i.Bonus2Type = (int)eStat.QUI; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Cold; i.Bonus4 = 9; i.Bonus4Type = (int)eStat.STR; { GameServer.Database.AddObject(i); } MercenaryEpicBoots = i; } //end item // of the Shadowy Embers Coif MercenaryEpicHelm = GameServer.Database.FindObjectByKey<ItemTemplate>("MercenaryEpicHelm"); if (MercenaryEpicHelm == null) { i = new ItemTemplate(); i.Id_nb = "MercenaryEpicHelm"; i.Name = "Coif of the Shadowy Embers"; i.Level = 50; i.Item_Type = 21; i.Model = 1290; //NEED TO WORK ON.. i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 100; i.SPD_ABS = 27; i.Object_Type = 35; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 16; i.Bonus1Type = (int)eStat.DEX; i.Bonus2 = 18; i.Bonus2Type = (int)eStat.STR; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Body; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Thrust; { GameServer.Database.AddObject(i); } MercenaryEpicHelm = i; } //end item // of the Shadowy Embers Gloves MercenaryEpicGloves = GameServer.Database.FindObjectByKey<ItemTemplate>("MercenaryEpicGloves"); if (MercenaryEpicGloves == null) { i = new ItemTemplate(); i.Id_nb = "MercenaryEpicGloves"; i.Name = "Gauntlets of the Shadowy Embers"; i.Level = 50; i.Item_Type = 22; i.Model = 721; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 100; i.SPD_ABS = 27; i.Object_Type = 35; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 19; i.Bonus1Type = (int)eStat.STR; i.Bonus2 = 15; i.Bonus2Type = (int)eStat.CON; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Crush; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Matter; { GameServer.Database.AddObject(i); } MercenaryEpicGloves = i; } // of the Shadowy Embers Hauberk MercenaryEpicVest = GameServer.Database.FindObjectByKey<ItemTemplate>("MercenaryEpicVest"); if (MercenaryEpicVest == null) { i = new ItemTemplate(); i.Id_nb = "MercenaryEpicVest"; i.Name = "Haurberk of the Shadowy Embers"; i.Level = 50; i.Item_Type = 25; i.Model = 718; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 100; i.SPD_ABS = 27; i.Object_Type = 35; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 15; i.Bonus1Type = (int)eStat.DEX; i.Bonus2 = 48; i.Bonus2Type = (int)eProperty.MaxHealth; i.Bonus3 = 4; i.Bonus3Type = (int)eResist.Cold; i.Bonus4 = 6; i.Bonus4Type = (int)eResist.Thrust; { GameServer.Database.AddObject(i); } MercenaryEpicVest = i; } // of the Shadowy Embers Legs MercenaryEpicLegs = GameServer.Database.FindObjectByKey<ItemTemplate>("MercenaryEpicLegs"); if (MercenaryEpicLegs == null) { i = new ItemTemplate(); i.Id_nb = "MercenaryEpicLegs"; i.Name = "Chausses of the Shadowy Embers"; i.Level = 50; i.Item_Type = 27; i.Model = 719; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 100; i.SPD_ABS = 27; i.Object_Type = 35; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 18; i.Bonus1Type = (int)eStat.CON; i.Bonus2 = 16; i.Bonus2Type = (int)eStat.STR; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Heat; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Slash; { GameServer.Database.AddObject(i); } MercenaryEpicLegs = i; } // of the Shadowy Embers Sleeves MercenaryEpicArms = GameServer.Database.FindObjectByKey<ItemTemplate>("MercenaryEpicArms"); if (MercenaryEpicArms == null) { i = new ItemTemplate(); i.Id_nb = "MercenaryEpicArms"; i.Name = "Sleeves of the Shadowy Embers"; i.Level = 50; i.Item_Type = 28; i.Model = 720; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 100; i.SPD_ABS = 27; i.Object_Type = 35; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 15; i.Bonus1Type = (int)eStat.CON; i.Bonus2 = 16; i.Bonus2Type = (int)eStat.DEX; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Cold; i.Bonus4 = 12; i.Bonus4Type = (int)eStat.QUI; { GameServer.Database.AddObject(i); } MercenaryEpicArms = i; } #endregion #region Reaver //Reaver Epic Sleeves End ReaverEpicBoots = GameServer.Database.FindObjectByKey<ItemTemplate>("ReaverEpicBoots"); if (ReaverEpicBoots == null) { i = new ItemTemplate(); i.Id_nb = "ReaverEpicBoots"; i.Name = "Boots of Murky Secrets"; i.Level = 50; i.Item_Type = 23; i.Model = 1270; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 100; i.SPD_ABS = 27; i.Object_Type = 35; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 14; i.Bonus1Type = (int)eProperty.MaxMana; i.Bonus2 = 9; i.Bonus2Type = (int)eStat.STR; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Cold; // i.Bonus4 = 10; // i.Bonus4Type = (int)eResist.Energy; { GameServer.Database.AddObject(i); } ReaverEpicBoots = i; } //end item //of Murky Secrets Coif ReaverEpicHelm = GameServer.Database.FindObjectByKey<ItemTemplate>("ReaverEpicHelm"); if (ReaverEpicHelm == null) { i = new ItemTemplate(); i.Id_nb = "ReaverEpicHelm"; i.Name = "Coif of Murky Secrets"; i.Level = 50; i.Item_Type = 21; i.Model = 1290; //NEED TO WORK ON.. i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 100; i.SPD_ABS = 27; i.Object_Type = 35; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 16; i.Bonus1Type = (int)eStat.PIE; i.Bonus2 = 6; i.Bonus2Type = (int)eProperty.Skill_Flexible_Weapon; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Body; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Thrust; { GameServer.Database.AddObject(i); } ReaverEpicHelm = i; } //end item //of Murky Secrets Gloves ReaverEpicGloves = GameServer.Database.FindObjectByKey<ItemTemplate>("ReaverEpicGloves"); if (ReaverEpicGloves == null) { i = new ItemTemplate(); i.Id_nb = "ReaverEpicGloves"; i.Name = "Gauntlets of Murky Secrets"; i.Level = 50; i.Item_Type = 22; i.Model = 1271; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 100; i.SPD_ABS = 27; i.Object_Type = 35; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 19; i.Bonus1Type = (int)eStat.STR; i.Bonus2 = 15; i.Bonus2Type = (int)eStat.CON; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Matter; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Crush; { GameServer.Database.AddObject(i); } ReaverEpicGloves = i; } //of Murky Secrets Hauberk ReaverEpicVest = GameServer.Database.FindObjectByKey<ItemTemplate>("ReaverEpicVest"); if (ReaverEpicVest == null) { i = new ItemTemplate(); i.Id_nb = "ReaverEpicVest"; i.Name = "Hauberk of Murky Secrets"; i.Level = 50; i.Item_Type = 25; i.Model = 1267; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 100; i.SPD_ABS = 27; i.Object_Type = 35; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 48; i.Bonus1Type = (int)eProperty.MaxHealth; i.Bonus2 = 15; i.Bonus2Type = (int)eStat.PIE; i.Bonus3 = 4; i.Bonus3Type = (int)eResist.Cold; i.Bonus4 = 6; i.Bonus4Type = (int)eResist.Thrust; { GameServer.Database.AddObject(i); } ReaverEpicVest = i; } //of Murky Secrets Legs ReaverEpicLegs = GameServer.Database.FindObjectByKey<ItemTemplate>("ReaverEpicLegs"); if (ReaverEpicLegs == null) { i = new ItemTemplate(); i.Id_nb = "ReaverEpicLegs"; i.Name = "Chausses of Murky Secrets"; i.Level = 50; i.Item_Type = 27; i.Model = 1268; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 100; i.SPD_ABS = 27; i.Object_Type = 35; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 18; i.Bonus1Type = (int)eStat.CON; i.Bonus2 = 16; i.Bonus2Type = (int)eStat.STR; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Heat; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Slash; { GameServer.Database.AddObject(i); } ReaverEpicLegs = i; } //of Murky Secrets Sleeves ReaverEpicArms = GameServer.Database.FindObjectByKey<ItemTemplate>("ReaverEpicArms"); if (ReaverEpicArms == null) { i = new ItemTemplate(); i.Id_nb = "ReaverEpicArms"; i.Name = "Sleeves of Murky Secrets"; i.Level = 50; i.Item_Type = 28; i.Model = 1269; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 100; i.SPD_ABS = 27; i.Object_Type = 35; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 16; i.Bonus1Type = (int)eStat.CON; i.Bonus2 = 15; i.Bonus2Type = (int)eStat.DEX; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Cold; i.Bonus4 = 4; i.Bonus4Type = (int)eProperty.Skill_Slashing; { GameServer.Database.AddObject(i); } ReaverEpicArms = i; } #endregion #region Infiltrator InfiltratorEpicBoots = GameServer.Database.FindObjectByKey<ItemTemplate>("InfiltratorEpicBoots"); if (InfiltratorEpicBoots == null) { InfiltratorEpicBoots = new ItemTemplate(); InfiltratorEpicBoots.Id_nb = "InfiltratorEpicBoots"; InfiltratorEpicBoots.Name = "Shadow-Woven Boots"; InfiltratorEpicBoots.Level = 50; InfiltratorEpicBoots.Item_Type = 23; InfiltratorEpicBoots.Model = 796; InfiltratorEpicBoots.IsDropable = true; InfiltratorEpicBoots.IsPickable = true; InfiltratorEpicBoots.DPS_AF = 100; InfiltratorEpicBoots.SPD_ABS = 10; InfiltratorEpicBoots.Object_Type = 33; InfiltratorEpicBoots.Quality = 100; InfiltratorEpicBoots.Weight = 22; InfiltratorEpicBoots.Bonus = 35; InfiltratorEpicBoots.MaxCondition = 50000; InfiltratorEpicBoots.MaxDurability = 50000; InfiltratorEpicBoots.Condition = 50000; InfiltratorEpicBoots.Durability = 50000; InfiltratorEpicBoots.Bonus1 = 13; InfiltratorEpicBoots.Bonus1Type = (int)eStat.QUI; InfiltratorEpicBoots.Bonus2 = 13; InfiltratorEpicBoots.Bonus2Type = (int)eStat.DEX; InfiltratorEpicBoots.Bonus3 = 8; InfiltratorEpicBoots.Bonus3Type = (int)eResist.Cold; InfiltratorEpicBoots.Bonus4 = 13; InfiltratorEpicBoots.Bonus4Type = (int)eStat.CON; { GameServer.Database.AddObject(InfiltratorEpicBoots); } } //end item //Shadow-Woven Coif InfiltratorEpicHelm = GameServer.Database.FindObjectByKey<ItemTemplate>("InfiltratorEpicHelm"); if (InfiltratorEpicHelm == null) { InfiltratorEpicHelm = new ItemTemplate(); InfiltratorEpicHelm.Id_nb = "InfiltratorEpicHelm"; InfiltratorEpicHelm.Name = "Shadow-Woven Coif"; InfiltratorEpicHelm.Level = 50; InfiltratorEpicHelm.Item_Type = 21; InfiltratorEpicHelm.Model = 1290; //NEED TO WORK ON.. InfiltratorEpicHelm.IsDropable = true; InfiltratorEpicHelm.IsPickable = true; InfiltratorEpicHelm.DPS_AF = 100; InfiltratorEpicHelm.SPD_ABS = 10; InfiltratorEpicHelm.Object_Type = 33; InfiltratorEpicHelm.Quality = 100; InfiltratorEpicHelm.Weight = 22; InfiltratorEpicHelm.Bonus = 35; InfiltratorEpicHelm.MaxCondition = 50000; InfiltratorEpicHelm.MaxDurability = 50000; InfiltratorEpicHelm.Condition = 50000; InfiltratorEpicHelm.Durability = 50000; InfiltratorEpicHelm.Bonus1 = 13; InfiltratorEpicHelm.Bonus1Type = (int)eStat.DEX; InfiltratorEpicHelm.Bonus2 = 13; InfiltratorEpicHelm.Bonus2Type = (int)eStat.QUI; InfiltratorEpicHelm.Bonus3 = 8; InfiltratorEpicHelm.Bonus3Type = (int)eResist.Spirit; InfiltratorEpicHelm.Bonus4 = 13; InfiltratorEpicHelm.Bonus4Type = (int)eStat.STR; { GameServer.Database.AddObject(InfiltratorEpicHelm); } } //end item //Shadow-Woven Gloves InfiltratorEpicGloves = GameServer.Database.FindObjectByKey<ItemTemplate>("InfiltratorEpicGloves"); if (InfiltratorEpicGloves == null) { InfiltratorEpicGloves = new ItemTemplate(); InfiltratorEpicGloves.Id_nb = "InfiltratorEpicGloves"; InfiltratorEpicGloves.Name = "Shadow-Woven Gloves"; InfiltratorEpicGloves.Level = 50; InfiltratorEpicGloves.Item_Type = 22; InfiltratorEpicGloves.Model = 795; InfiltratorEpicGloves.IsDropable = true; InfiltratorEpicGloves.IsPickable = true; InfiltratorEpicGloves.DPS_AF = 100; InfiltratorEpicGloves.SPD_ABS = 10; InfiltratorEpicGloves.Object_Type = 33; InfiltratorEpicGloves.Quality = 100; InfiltratorEpicGloves.Weight = 22; InfiltratorEpicGloves.Bonus = 35; InfiltratorEpicGloves.MaxCondition = 50000; InfiltratorEpicGloves.MaxDurability = 50000; InfiltratorEpicGloves.Condition = 50000; InfiltratorEpicGloves.Durability = 50000; InfiltratorEpicGloves.Bonus1 = 18; InfiltratorEpicGloves.Bonus1Type = (int)eStat.STR; InfiltratorEpicGloves.Bonus2 = 21; InfiltratorEpicGloves.Bonus2Type = (int)eProperty.MaxHealth; InfiltratorEpicGloves.Bonus3 = 3; InfiltratorEpicGloves.Bonus3Type = (int)eProperty.Skill_Envenom; InfiltratorEpicGloves.Bonus4 = 3; InfiltratorEpicGloves.Bonus4Type = (int)eProperty.Skill_Critical_Strike; { GameServer.Database.AddObject(InfiltratorEpicGloves); } } //Shadow-Woven Hauberk InfiltratorEpicVest = GameServer.Database.FindObjectByKey<ItemTemplate>("InfiltratorEpicVest"); if (InfiltratorEpicVest == null) { InfiltratorEpicVest = new ItemTemplate(); InfiltratorEpicVest.Id_nb = "InfiltratorEpicVest"; InfiltratorEpicVest.Name = "Shadow-Woven Jerkin"; InfiltratorEpicVest.Level = 50; InfiltratorEpicVest.Item_Type = 25; InfiltratorEpicVest.Model = 792; InfiltratorEpicVest.IsDropable = true; InfiltratorEpicVest.IsPickable = true; InfiltratorEpicVest.DPS_AF = 100; InfiltratorEpicVest.SPD_ABS = 10; InfiltratorEpicVest.Object_Type = 33; InfiltratorEpicVest.Quality = 100; InfiltratorEpicVest.Weight = 22; InfiltratorEpicVest.Bonus = 35; InfiltratorEpicVest.MaxCondition = 50000; InfiltratorEpicVest.MaxDurability = 50000; InfiltratorEpicVest.Condition = 50000; InfiltratorEpicVest.Durability = 50000; InfiltratorEpicVest.Bonus1 = 36; InfiltratorEpicVest.Bonus1Type = (int)eProperty.MaxHealth; InfiltratorEpicVest.Bonus2 = 16; InfiltratorEpicVest.Bonus2Type = (int)eStat.DEX; InfiltratorEpicVest.Bonus3 = 8; InfiltratorEpicVest.Bonus3Type = (int)eResist.Cold; InfiltratorEpicVest.Bonus4 = 8; InfiltratorEpicVest.Bonus4Type = (int)eResist.Body; { GameServer.Database.AddObject(InfiltratorEpicVest); } } //Shadow-Woven Legs InfiltratorEpicLegs = GameServer.Database.FindObjectByKey<ItemTemplate>("InfiltratorEpicLegs"); if (InfiltratorEpicLegs == null) { InfiltratorEpicLegs = new ItemTemplate(); InfiltratorEpicLegs.Id_nb = "InfiltratorEpicLegs"; InfiltratorEpicLegs.Name = "Shadow-Woven Leggings"; InfiltratorEpicLegs.Level = 50; InfiltratorEpicLegs.Item_Type = 27; InfiltratorEpicLegs.Model = 793; InfiltratorEpicLegs.IsDropable = true; InfiltratorEpicLegs.IsPickable = true; InfiltratorEpicLegs.DPS_AF = 100; InfiltratorEpicLegs.SPD_ABS = 10; InfiltratorEpicLegs.Object_Type = 33; InfiltratorEpicLegs.Quality = 100; InfiltratorEpicLegs.Weight = 22; InfiltratorEpicLegs.Bonus = 35; InfiltratorEpicLegs.MaxCondition = 50000; InfiltratorEpicLegs.MaxDurability = 50000; InfiltratorEpicLegs.Condition = 50000; InfiltratorEpicLegs.Durability = 50000; InfiltratorEpicLegs.Bonus1 = 21; InfiltratorEpicLegs.Bonus1Type = (int)eStat.CON; InfiltratorEpicLegs.Bonus2 = 16; InfiltratorEpicLegs.Bonus2Type = (int)eStat.QUI; InfiltratorEpicLegs.Bonus3 = 6; InfiltratorEpicLegs.Bonus3Type = (int)eResist.Heat; InfiltratorEpicLegs.Bonus4 = 6; InfiltratorEpicLegs.Bonus4Type = (int)eResist.Crush; { GameServer.Database.AddObject(InfiltratorEpicLegs); } } //Shadow-Woven Sleeves InfiltratorEpicArms = GameServer.Database.FindObjectByKey<ItemTemplate>("InfiltratorEpicArms"); if (InfiltratorEpicArms == null) { InfiltratorEpicArms = new ItemTemplate(); InfiltratorEpicArms.Id_nb = "InfiltratorEpicArms"; InfiltratorEpicArms.Name = "Shadow-Woven Sleeves"; InfiltratorEpicArms.Level = 50; InfiltratorEpicArms.Item_Type = 28; InfiltratorEpicArms.Model = 794; InfiltratorEpicArms.IsDropable = true; InfiltratorEpicArms.IsPickable = true; InfiltratorEpicArms.DPS_AF = 100; InfiltratorEpicArms.SPD_ABS = 10; InfiltratorEpicArms.Object_Type = 33; InfiltratorEpicArms.Quality = 100; InfiltratorEpicArms.Weight = 22; InfiltratorEpicArms.Bonus = 35; InfiltratorEpicArms.MaxCondition = 50000; InfiltratorEpicArms.MaxDurability = 50000; InfiltratorEpicArms.Condition = 50000; InfiltratorEpicArms.Durability = 50000; InfiltratorEpicArms.Bonus1 = 21; InfiltratorEpicArms.Bonus1Type = (int)eStat.DEX; InfiltratorEpicArms.Bonus2 = 18; InfiltratorEpicArms.Bonus2Type = (int)eStat.STR; InfiltratorEpicArms.Bonus3 = 6; InfiltratorEpicArms.Bonus3Type = (int)eResist.Matter; InfiltratorEpicArms.Bonus4 = 4; InfiltratorEpicArms.Bonus4Type = (int)eResist.Slash; { GameServer.Database.AddObject(InfiltratorEpicArms); } } #endregion #region Cabalist CabalistEpicBoots = GameServer.Database.FindObjectByKey<ItemTemplate>("CabalistEpicBoots"); if (CabalistEpicBoots == null) { CabalistEpicBoots = new ItemTemplate(); CabalistEpicBoots.Id_nb = "CabalistEpicBoots"; CabalistEpicBoots.Name = "Warm Boots of the Construct"; CabalistEpicBoots.Level = 50; CabalistEpicBoots.Item_Type = 23; CabalistEpicBoots.Model = 143; CabalistEpicBoots.IsDropable = true; CabalistEpicBoots.IsPickable = true; CabalistEpicBoots.DPS_AF = 50; CabalistEpicBoots.SPD_ABS = 0; CabalistEpicBoots.Object_Type = 32; CabalistEpicBoots.Quality = 100; CabalistEpicBoots.Weight = 22; CabalistEpicBoots.Bonus = 35; CabalistEpicBoots.MaxCondition = 50000; CabalistEpicBoots.MaxDurability = 50000; CabalistEpicBoots.Condition = 50000; CabalistEpicBoots.Durability = 50000; CabalistEpicBoots.Bonus1 = 22; CabalistEpicBoots.Bonus1Type = (int)eStat.DEX; CabalistEpicBoots.Bonus2 = 3; CabalistEpicBoots.Bonus2Type = (int)eProperty.Skill_Matter; CabalistEpicBoots.Bonus3 = 8; CabalistEpicBoots.Bonus3Type = (int)eResist.Slash; CabalistEpicBoots.Bonus4 = 8; CabalistEpicBoots.Bonus4Type = (int)eResist.Thrust; { GameServer.Database.AddObject(CabalistEpicBoots); } } //end item //Warm of the Construct Coif CabalistEpicHelm = GameServer.Database.FindObjectByKey<ItemTemplate>("CabalistEpicHelm"); if (CabalistEpicHelm == null) { i = new ItemTemplate(); i.Id_nb = "CabalistEpicHelm"; i.Name = "Warm Coif of the Construct"; i.Level = 50; i.Item_Type = 21; i.Model = 1290; //NEED TO WORK ON.. i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 21; i.Bonus1Type = (int)eStat.INT; i.Bonus2 = 13; i.Bonus2Type = (int)eStat.DEX; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Heat; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Matter; { GameServer.Database.AddObject(i); } CabalistEpicHelm = i; } //end item //Warm of the Construct Gloves CabalistEpicGloves = GameServer.Database.FindObjectByKey<ItemTemplate>("CabalistEpicGloves"); if (CabalistEpicGloves == null) { i = new ItemTemplate(); i.Id_nb = "CabalistEpicGloves"; i.Name = "Warm Gloves of the Construct"; i.Level = 50; i.Item_Type = 22; i.Model = 142; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 10; i.Bonus1Type = (int)eStat.DEX; i.Bonus2 = 10; i.Bonus2Type = (int)eStat.INT; i.Bonus3 = 8; i.Bonus3Type = (int)eProperty.MaxMana; i.Bonus4 = 10; i.Bonus4Type = (int)eResist.Energy; { GameServer.Database.AddObject(i); } CabalistEpicGloves = i; } //Warm of the Construct Hauberk CabalistEpicVest = GameServer.Database.FindObjectByKey<ItemTemplate>("CabalistEpicVest"); if (CabalistEpicVest == null) { i = new ItemTemplate(); i.Id_nb = "CabalistEpicVest"; i.Name = "Warm Robe of the Construct"; i.Level = 50; i.Item_Type = 25; i.Model = 682; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 24; i.Bonus1Type = (int)eProperty.MaxHealth; i.Bonus2 = 14; i.Bonus2Type = (int)eProperty.MaxMana; i.Bonus3 = 4; i.Bonus3Type = (int)eResist.Crush; // i.Bonus4 = 10; // i.Bonus4Type = (int)eResist.Energy; { GameServer.Database.AddObject(i); } CabalistEpicVest = i; } //Warm of the Construct Legs CabalistEpicLegs = GameServer.Database.FindObjectByKey<ItemTemplate>("CabalistEpicLegs"); if (CabalistEpicLegs == null) { i = new ItemTemplate(); i.Id_nb = "CabalistEpicLegs"; i.Name = "Warm Leggings of the Construct"; i.Level = 50; i.Item_Type = 27; i.Model = 140; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 22; i.Bonus1Type = (int)eStat.CON; i.Bonus2 = 4; i.Bonus2Type = (int)eProperty.Skill_Spirit; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Cold; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Matter; { GameServer.Database.AddObject(i); } CabalistEpicLegs = i; } //Warm of the Construct Sleeves CabalistEpicArms = GameServer.Database.FindObjectByKey<ItemTemplate>("CabalistEpicArms"); if (CabalistEpicArms == null) { i = new ItemTemplate(); i.Id_nb = "CabalistEpicArms"; i.Name = "Warm Sleeves of the Construct"; i.Level = 50; i.Item_Type = 28; i.Model = 141; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 18; i.Bonus1Type = (int)eStat.INT; i.Bonus2 = 4; i.Bonus2Type = (int)eProperty.Skill_Body; i.Bonus3 = 16; i.Bonus3Type = (int)eStat.DEX; // i.Bonus4 = 10; // i.Bonus4Type = (int)eResist.Energy; { GameServer.Database.AddObject(i); } CabalistEpicArms = i; } #endregion #region Necromancer NecromancerEpicBoots = GameServer.Database.FindObjectByKey<ItemTemplate>("NecromancerEpicBoots"); if (NecromancerEpicBoots == null) { i = new ItemTemplate(); i.Id_nb = "NecromancerEpicBoots"; i.Name = "Boots of Forbidden Rites"; i.Level = 50; i.Item_Type = 23; i.Model = 143; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 22; i.Bonus1Type = (int)eStat.INT; i.Bonus2 = 4; i.Bonus2Type = (int)eProperty.Skill_Pain_working; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Slash; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Thrust; { GameServer.Database.AddObject(i); } NecromancerEpicBoots = i; } //end item //of Forbidden Rites Coif NecromancerEpicHelm = GameServer.Database.FindObjectByKey<ItemTemplate>("NecromancerEpicHelm"); if (NecromancerEpicHelm == null) { i = new ItemTemplate(); i.Id_nb = "NecromancerEpicHelm"; i.Name = "Cap of Forbidden Rites"; i.Level = 50; i.Item_Type = 21; i.Model = 1290; //NEED TO WORK ON.. i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 21; i.Bonus1Type = (int)eStat.INT; i.Bonus2 = 13; i.Bonus2Type = (int)eStat.QUI; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Heat; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Matter; { GameServer.Database.AddObject(i); } NecromancerEpicHelm = i; } //end item //of Forbidden Rites Gloves NecromancerEpicGloves = GameServer.Database.FindObjectByKey<ItemTemplate>("NecromancerEpicGloves"); if (NecromancerEpicGloves == null) { i = new ItemTemplate(); i.Id_nb = "NecromancerEpicGloves"; i.Name = "Gloves of Forbidden Rites"; i.Level = 50; i.Item_Type = 22; i.Model = 142; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 10; i.Bonus1Type = (int)eStat.STR; i.Bonus2 = 10; i.Bonus2Type = (int)eStat.INT; i.Bonus3 = 8; i.Bonus3Type = (int)eProperty.MaxMana; i.Bonus4 = 10; i.Bonus4Type = (int)eResist.Energy; { GameServer.Database.AddObject(i); } NecromancerEpicGloves = i; } //of Forbidden Rites Hauberk NecromancerEpicVest = GameServer.Database.FindObjectByKey<ItemTemplate>("NecromancerEpicVest"); if (NecromancerEpicVest == null) { i = new ItemTemplate(); i.Id_nb = "NecromancerEpicVest"; i.Name = "Robe of Forbidden Rites"; i.Level = 50; i.Item_Type = 25; i.Model = 1266; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 24; i.Bonus1Type = (int)eProperty.MaxHealth; i.Bonus2 = 14; i.Bonus2Type = (int)eProperty.MaxMana; i.Bonus3 = 4; i.Bonus3Type = (int)eResist.Crush; // i.Bonus4 = 10; // i.Bonus4Type = (int)eResist.Energy; { GameServer.Database.AddObject(i); } NecromancerEpicVest = i; } //of Forbidden Rites Legs NecromancerEpicLegs = GameServer.Database.FindObjectByKey<ItemTemplate>("NecromancerEpicLegs"); if (NecromancerEpicLegs == null) { i = new ItemTemplate(); i.Id_nb = "NecromancerEpicLegs"; i.Name = "Leggings of Forbidden Rites"; i.Level = 50; i.Item_Type = 27; i.Model = 140; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 22; i.Bonus1Type = (int)eStat.CON; i.Bonus2 = 4; i.Bonus2Type = (int)eProperty.Skill_Death_Servant; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Cold; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Matter; { GameServer.Database.AddObject(i); } NecromancerEpicLegs = i; } //of Forbidden Rites Sleeves NecromancerEpicArms = GameServer.Database.FindObjectByKey<ItemTemplate>("NecromancerEpicArms"); if (NecromancerEpicArms == null) { i = new ItemTemplate(); i.Id_nb = "NecromancerEpicArms"; i.Name = "Sleeves of Forbidden Rites"; i.Level = 50; i.Item_Type = 28; i.Model = 141; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; i.Bonus1 = 18; i.Bonus1Type = (int)eStat.INT; i.Bonus2 = 4; i.Bonus2Type = (int)eProperty.Skill_DeathSight; i.Bonus3 = 16; i.Bonus3Type = (int)eStat.DEX; // i.Bonus4 = 10; // i.Bonus4Type = (int)eResist.Energy; { GameServer.Database.AddObject(i); } NecromancerEpicArms = i; //Item Descriptions End } #endregion #region Heretic HereticEpicBoots = GameServer.Database.FindObjectByKey<ItemTemplate>("HereticEpicBoots"); if (HereticEpicBoots == null) { i = new ItemTemplate(); i.Id_nb = "HereticEpicBoots"; i.Name = "Boots of the Zealous Renegade"; i.Level = 50; i.Item_Type = 23; i.Model = 143; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; /* * Strength: 16 pts * Constitution: 18 pts * Slash Resist: 8% * Heat Resist: 8% */ i.Bonus1 = 16; i.Bonus1Type = (int)eStat.STR; i.Bonus2 = 18; i.Bonus2Type = (int)eStat.CON; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Slash; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Heat; { GameServer.Database.AddObject(i); } HereticEpicBoots = i; } //end item //of Forbidden Rites Coif HereticEpicHelm = GameServer.Database.FindObjectByKey<ItemTemplate>("HereticEpicHelm"); if (HereticEpicHelm == null) { i = new ItemTemplate(); i.Id_nb = "HereticEpicHelm"; i.Name = "Cap of the Zealous Renegade"; i.Level = 50; i.Item_Type = 21; i.Model = 1290; //NEED TO WORK ON.. i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; /* * Piety: 15 pts * Thrust Resist: 6% * Cold Resist: 4% * Hits: 48 pts */ i.Bonus1 = 15; i.Bonus1Type = (int)eStat.PIE; i.Bonus2 = 6; i.Bonus2Type = (int)eResist.Thrust; i.Bonus3 = 4; i.Bonus3Type = (int)eResist.Cold; i.Bonus4 = 48; i.Bonus4Type = (int)eProperty.MaxHealth; { GameServer.Database.AddObject(i); } HereticEpicHelm = i; } //end item //of Forbidden Rites Gloves HereticEpicGloves = GameServer.Database.FindObjectByKey<ItemTemplate>("HereticEpicGloves"); if (HereticEpicGloves == null) { i = new ItemTemplate(); i.Id_nb = "HereticEpicGloves"; i.Name = "Gloves of the Zealous Renegade"; i.Level = 50; i.Item_Type = 22; i.Model = 142; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; /* * Strength: 9 pts * Power: 14 pts * Cold Resist: 8% */ i.Bonus1 = 9; i.Bonus1Type = (int)eStat.STR; i.Bonus2 = 14; i.Bonus2Type = (int)eProperty.MaxMana; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Cold; { GameServer.Database.AddObject(i); } HereticEpicGloves = i; } //of Forbidden Rites Hauberk HereticEpicVest = GameServer.Database.FindObjectByKey<ItemTemplate>("HereticEpicVest"); if (HereticEpicVest == null) { i = new ItemTemplate(); i.Id_nb = "HereticEpicVest"; i.Name = "Robe of the Zealous Renegade"; i.Level = 50; i.Item_Type = 25; i.Model = 2921; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; /* * Crush: +4 pts * Constitution: 16 pts * Dexterity: 15 pts * Cold Resist: 8% */ i.Bonus1 = 4; i.Bonus1Type = (int)eProperty.Skill_Crushing; i.Bonus2 = 16; i.Bonus2Type = (int)eStat.CON; i.Bonus3 = 15; i.Bonus3Type = (int)eStat.DEX; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Cold; { GameServer.Database.AddObject(i); } HereticEpicVest = i; } //of Forbidden Rites Legs HereticEpicLegs = GameServer.Database.FindObjectByKey<ItemTemplate>("HereticEpicLegs"); if (HereticEpicLegs == null) { i = new ItemTemplate(); i.Id_nb = "HereticEpicLegs"; i.Name = "Pants of the Zealous Renegade"; i.Level = 50; i.Item_Type = 27; i.Model = 140; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; /* * Strength: 19 pts * Constitution: 15 pts * Crush Resist: 8% * Matter Resist: 8% */ i.Bonus1 = 19; i.Bonus1Type = (int)eStat.STR; i.Bonus2 = 15; i.Bonus2Type = (int)eStat.CON; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Crush; i.Bonus4 = 8; i.Bonus4Type = (int)eResist.Matter; { GameServer.Database.AddObject(i); } HereticEpicLegs = i; } //of Forbidden Rites Sleeves HereticEpicArms = GameServer.Database.FindObjectByKey<ItemTemplate>("HereticEpicArms"); if (HereticEpicArms == null) { i = new ItemTemplate(); i.Id_nb = "HereticEpicArms"; i.Name = "Sleeves of the Zealous Renegade"; i.Level = 50; i.Item_Type = 28; i.Model = 141; i.IsDropable = true; i.IsPickable = true; i.DPS_AF = 50; i.SPD_ABS = 0; i.Object_Type = 32; i.Quality = 100; i.Weight = 22; i.Bonus = 35; i.MaxCondition = 50000; i.MaxDurability = 50000; i.Condition = 50000; i.Durability = 50000; /* * Piety: 16 pts * Thrust Resist: 8% * Body Resist: 8% * Flexible: 6 pts */ i.Bonus1 = 16; i.Bonus1Type = (int)eStat.PIE; i.Bonus2 = 8; i.Bonus2Type = (int)eResist.Thrust; i.Bonus3 = 8; i.Bonus3Type = (int)eResist.Body; i.Bonus4 = 6; i.Bonus4Type = (int)eProperty.Skill_Flexible_Weapon; { GameServer.Database.AddObject(i); } HereticEpicArms = i; //Item Descriptions End } #endregion #endregion GameEventMgr.AddHandler(GamePlayerEvent.AcceptQuest, new DOLEventHandler(SubscribeQuest)); GameEventMgr.AddHandler(GamePlayerEvent.DeclineQuest, new DOLEventHandler(SubscribeQuest)); GameEventMgr.AddHandler(Lidmann, GameObjectEvent.Interact, new DOLEventHandler(TalkToLidmann)); GameEventMgr.AddHandler(Lidmann, GameLivingEvent.WhisperReceive, new DOLEventHandler(TalkToLidmann)); /* Now we bring to Lidmann the possibility to give this quest to players */ Lidmann.AddQuestToGive(typeof(Shadows_50)); if (log.IsInfoEnabled) log.Info("Quest \"" + questTitle + "\" initialized"); } [ScriptUnloadedEvent] public static void ScriptUnloaded(DOLEvent e, object sender, EventArgs args) { if (!ServerProperties.Properties.LOAD_QUESTS) return; //if not loaded, don't worry if (Lidmann == null) return; // remove handlers GameEventMgr.RemoveHandler(GamePlayerEvent.AcceptQuest, new DOLEventHandler(SubscribeQuest)); GameEventMgr.RemoveHandler(GamePlayerEvent.DeclineQuest, new DOLEventHandler(SubscribeQuest)); GameEventMgr.RemoveHandler(Lidmann, GameObjectEvent.Interact, new DOLEventHandler(TalkToLidmann)); GameEventMgr.RemoveHandler(Lidmann, GameLivingEvent.WhisperReceive, new DOLEventHandler(TalkToLidmann)); /* Now we remove to Lidmann the possibility to give this quest to players */ Lidmann.RemoveQuestToGive(typeof(Shadows_50)); } protected static void TalkToLidmann(DOLEvent e, object sender, EventArgs args) { //We get the player from the event arguments and check if he qualifies GamePlayer player = ((SourceEventArgs)args).Source as GamePlayer; if (player == null) return; if (Lidmann.CanGiveQuest(typeof(Shadows_50), player) <= 0) return; //We also check if the player is already doing the quest Shadows_50 quest = player.IsDoingQuest(typeof(Shadows_50)) as Shadows_50; if (e == GameObjectEvent.Interact) { // Nag to finish quest if (quest != null) { Lidmann.SayTo(player, "Check your Journal for instructions!"); return; } else { // Check if player is qualifed for quest Lidmann.SayTo(player, "Albion needs your [services]"); return; } } // The player whispered to the NPC else if (e == GameLivingEvent.WhisperReceive) { WhisperReceiveEventArgs wArgs = (WhisperReceiveEventArgs)args; //Check player is already doing quest if (quest == null) { switch (wArgs.Text) { case "services": player.Out.SendQuestSubscribeCommand(Lidmann, QuestMgr.GetIDForQuestType(typeof(Shadows_50)), "Will you help Lidmann [Defenders of Albion Level 50 Epic]?"); break; } } else { switch (wArgs.Text) { case "abort": player.Out.SendCustomDialog("Do you really want to abort this quest, \nall items gained during quest will be lost?", new CustomDialogResponse(CheckPlayerAbortQuest)); break; } } } } public override bool CheckQuestQualification(GamePlayer player) { // if the player is already doing the quest his level is no longer of relevance if (player.IsDoingQuest(typeof(Shadows_50)) != null) return true; if (player.CharacterClass.ID != (byte)eCharacterClass.Reaver && player.CharacterClass.ID != (byte)eCharacterClass.Mercenary && player.CharacterClass.ID != (byte)eCharacterClass.Cabalist && player.CharacterClass.ID != (byte)eCharacterClass.Necromancer && player.CharacterClass.ID != (byte)eCharacterClass.Infiltrator && player.CharacterClass.ID != (byte)eCharacterClass.Heretic) return false; // This checks below are only performed is player isn't doing quest already //if (player.HasFinishedQuest(typeof(Academy_47)) == 0) return false; //if (!CheckPartAccessible(player,typeof(CityOfCamelot))) // return false; if (player.Level < minimumLevel || player.Level > maximumLevel) return false; return true; } /* This is our callback hook that will be called when the player clicks * on any button in the quest offer dialog. We check if he accepts or * declines here... */ private static void CheckPlayerAbortQuest(GamePlayer player, byte response) { Shadows_50 quest = player.IsDoingQuest(typeof(Shadows_50)) as Shadows_50; if (quest == null) return; if (response == 0x00) { SendSystemMessage(player, "Good, no go out there and finish your work!"); } else { SendSystemMessage(player, "Aborting Quest " + questTitle + ". You can start over again if you want."); quest.AbortQuest(); } } protected static void SubscribeQuest(DOLEvent e, object sender, EventArgs args) { QuestEventArgs qargs = args as QuestEventArgs; if (qargs == null) return; if (qargs.QuestID != QuestMgr.GetIDForQuestType(typeof(Shadows_50))) return; if (e == GamePlayerEvent.AcceptQuest) CheckPlayerAcceptQuest(qargs.Player, 0x01); else if (e == GamePlayerEvent.DeclineQuest) CheckPlayerAcceptQuest(qargs.Player, 0x00); } private static void CheckPlayerAcceptQuest(GamePlayer player, byte response) { if (Lidmann.CanGiveQuest(typeof(Shadows_50), player) <= 0) return; if (player.IsDoingQuest(typeof(Shadows_50)) != null) return; if (response == 0x00) { player.Out.SendMessage("Our God forgives your laziness, just look out for stray lightning bolts.", eChatType.CT_Say, eChatLoc.CL_PopupWindow); } else { // Check to see if we can add quest if (!Lidmann.GiveQuest(typeof(Shadows_50), player, 1)) return; player.Out.SendMessage("Kill Cailleach Uragaig in Lyonesse loc 29k, 33k!", eChatType.CT_System, eChatLoc.CL_PopupWindow); } } //Set quest name public override string Name { get { return "Feast of the Decadent (Level 50 Guild of Shadows Epic)"; } } // Define Steps public override string Description { get { switch (Step) { case 1: return "[Step #1] Seek out Cailleach Uragaig in Lyonesse Loc 29k,33k kill her!"; case 2: return "[Step #2] Return to Lidmann Halsey for your reward!"; } return base.Description; } } public override void Notify(DOLEvent e, object sender, EventArgs args) { GamePlayer player = sender as GamePlayer; if (player == null || player.IsDoingQuest(typeof(Shadows_50)) == null) return; if (Step == 1 && e == GameLivingEvent.EnemyKilled) { EnemyKilledEventArgs gArgs = (EnemyKilledEventArgs)args; if (gArgs != null && gArgs.Target != null && Uragaig != null) { if (gArgs.Target.Name == Uragaig.Name) { m_questPlayer.Out.SendMessage("Take the pouch to Lidmann Halsey", eChatType.CT_System, eChatLoc.CL_SystemWindow); GiveItem(m_questPlayer, sealed_pouch); Step = 2; return; } } } if (Step == 2 && e == GamePlayerEvent.GiveItem) { GiveItemEventArgs gArgs = (GiveItemEventArgs)args; if (gArgs.Target.Name == Lidmann.Name && gArgs.Item.Id_nb == sealed_pouch.Id_nb) { Lidmann.SayTo(player, "You have earned this Epic Armor, wear it with honor!"); FinishQuest(); return; } } } public override void AbortQuest() { base.AbortQuest(); //Defined in Quest, changes the state, stores in DB etc ... RemoveItem(m_questPlayer, sealed_pouch, false); } public override void FinishQuest() { if (m_questPlayer.Inventory.IsSlotsFree(6, eInventorySlot.FirstBackpack, eInventorySlot.LastBackpack)) { RemoveItem(Lidmann, m_questPlayer, sealed_pouch); base.FinishQuest(); //Defined in Quest, changes the state, stores in DB etc ... switch ((eCharacterClass)m_questPlayer.CharacterClass.ID) { case eCharacterClass.Reaver: { GiveItem(m_questPlayer, ReaverEpicArms); GiveItem(m_questPlayer, ReaverEpicBoots); GiveItem(m_questPlayer, ReaverEpicGloves); GiveItem(m_questPlayer, ReaverEpicHelm); GiveItem(m_questPlayer, ReaverEpicLegs); GiveItem(m_questPlayer, ReaverEpicVest); break; } case eCharacterClass.Mercenary: { GiveItem(m_questPlayer, MercenaryEpicArms); GiveItem(m_questPlayer, MercenaryEpicBoots); GiveItem(m_questPlayer, MercenaryEpicGloves); GiveItem(m_questPlayer, MercenaryEpicHelm); GiveItem(m_questPlayer, MercenaryEpicLegs); GiveItem(m_questPlayer, MercenaryEpicVest); break; } case eCharacterClass.Cabalist: { GiveItem(m_questPlayer, CabalistEpicArms); GiveItem(m_questPlayer, CabalistEpicBoots); GiveItem(m_questPlayer, CabalistEpicGloves); GiveItem(m_questPlayer, CabalistEpicHelm); GiveItem(m_questPlayer, CabalistEpicLegs); GiveItem(m_questPlayer, CabalistEpicVest); break; } case eCharacterClass.Infiltrator: { GiveItem(m_questPlayer, InfiltratorEpicArms); GiveItem(m_questPlayer, InfiltratorEpicBoots); GiveItem(m_questPlayer, InfiltratorEpicGloves); GiveItem(m_questPlayer, InfiltratorEpicHelm); GiveItem(m_questPlayer, InfiltratorEpicLegs); GiveItem(m_questPlayer, InfiltratorEpicVest); break; } case eCharacterClass.Necromancer: { GiveItem(m_questPlayer, NecromancerEpicArms); GiveItem(m_questPlayer, NecromancerEpicBoots); GiveItem(m_questPlayer, NecromancerEpicGloves); GiveItem(m_questPlayer, NecromancerEpicHelm); GiveItem(m_questPlayer, NecromancerEpicLegs); GiveItem(m_questPlayer, NecromancerEpicVest); break; } case eCharacterClass.Heretic: { GiveItem(m_questPlayer, HereticEpicArms); GiveItem(m_questPlayer, HereticEpicBoots); GiveItem(m_questPlayer, HereticEpicGloves); GiveItem(m_questPlayer, HereticEpicHelm); GiveItem(m_questPlayer, HereticEpicLegs); GiveItem(m_questPlayer, HereticEpicVest); break; } } m_questPlayer.GainExperience(GameLiving.eXPSource.Quest, 1937768448, true); //m_questPlayer.AddMoney(Money.GetMoney(0,0,0,2,Util.Random(50)), "You recieve {0} as a reward."); } else { m_questPlayer.Out.SendMessage("You do not have enough free space in your inventory!", eChatType.CT_Important, eChatLoc.CL_SystemWindow); } } #region Allakhazam Epic Source /* *#25 talk to Lidmann *#26 seek out Loken in Raumarik Loc 47k, 25k, 4k, and kill him purp and 2 blue adds *#27 return to Lidmann *#28 give her the ball of flame *#29 talk with Lidmann about Loken's demise *#30 go to MorlinCaan in Jordheim *#31 give her the sealed pouch *#32 you get your epic armor as a reward */ /* * of the Shadowy Embers Boots * of the Shadowy Embers Coif * of the Shadowy Embers Gloves * of the Shadowy Embers Hauberk * of the Shadowy Embers Legs * of the Shadowy Embers Sleeves *Shadow Shrouded Boots *Shadow Shrouded Coif *Shadow Shrouded Gloves *Shadow Shrouded Hauberk *Shadow Shrouded Legs *Shadow Shrouded Sleeves */ #endregion } }
1
0.884014
1
0.884014
game-dev
MEDIA
0.802503
game-dev
0.904427
1
0.904427
dieletro/tinjecttelegram_delphi
8,427
v1.3.5/TInjectTelegram/Source/TinjectTelegram.Types.ReplyMarkups.pas
unit TinjectTelegram.Types.ReplyMarkups; interface uses REST.Json.Types, TInjectTelegram.Types; type TtdButtonBase = class private [JSONName('text')] FText: string; public property Text: string read FText write FText; end; TtdKeyboardButtonPollType = class private [JSONName('type')] FType: string; public property &Type: string read FType write FType; constructor Create(const AType: string); overload; end; TtdInlineKeyboardButton = class(TtdButtonBase) private [JSONName('callback_data')] FCallbackData: string; [JSONName('pay')] FPay: Boolean; [JSONName('url')] FURL: string; [JSONName('loginurl')] FLoginURL : ItdLoginURL; [JSONName('switch_inline_query')] FSwitchInlineQuery: string; [JSONName('switch_inline_query_current_chat')] FSwitchInlineQueryCurrentChat: string; [JSONName('callback_game')] FCallbackGame: string; public constructor Create(const AText: string); overload; constructor Create(const AText, ACallbackData: string); overload; property Url: string read FURL write FURL; property LoginURL : ItdLoginURL read FLoginURL write FLoginURL; property CallbackData: string read FCallbackData write FCallbackData; property SwitchInlineQuery: string read FSwitchInlineQuery write FSwitchInlineQuery; property SwitchInlineQueryCurrentChat: string read FSwitchInlineQueryCurrentChat write FSwitchInlineQueryCurrentChat; property CallbackGame: string read FCallbackGame write FCallbackGame; property Pay: Boolean read FPay write FPay; end; TtdKeyboardButton = class(TtdButtonBase) private [JSONName('request_location')] FRequestLocation: Boolean; [JSONName('request_contact')] FRequestContact: Boolean; FRequestPoll : TtdKeyboardButtonPollType; public constructor Create(Const ARequestPoll: TtdKeyboardButtonPollType; AText: string; ARequestContact: Boolean = False; ARequestLocation: Boolean = False); overload; constructor Create(const AText: string; ARequestContact: Boolean = False; ARequestLocation: Boolean = False); overload; property RequestContact: Boolean read FRequestContact write FRequestContact; property RequestLocation: Boolean read FRequestLocation write FRequestLocation; [JSONName('request_poll')] //Resolvido property RequestPoll : TtdKeyboardButtonPollType read FRequestPoll write FRequestPoll; end; TtdReplyMarkup = class abstract(TInterfacedObject, IReplyMarkup) private [JSONName('selective')] FSelective: Boolean; public property Selective: Boolean read FSelective write FSelective; end; TtdForceReply = class(TtdReplyMarkup) private [JSONName('force_reply')] FForce: Boolean; [JSONName('input_field_placeholder')] FInputFieldPlaceholder: String; public property Force: Boolean read FForce write FForce; property InputFieldPlaceholder: String read FInputFieldPlaceholder write FInputFieldPlaceholder; end; TtdInlineKeyboardMarkup = class(TInterfacedObject, IReplyMarkup) private [JSONName('inline_keyboard')] FKeyboard: TArray<TArray<TtdInlineKeyboardButton>>; public procedure AddRow(AKeyboardRow: TArray<TtdInlineKeyboardButton>); constructor Create; overload; constructor Create(AInlineKeyboardRow: TArray<TtdInlineKeyboardButton>); overload; constructor Create(AInlineKeyboard: TArray<TArray<TtdInlineKeyboardButton>>); overload; destructor Destroy; override; property Keyboard: TArray<TArray<TtdInlineKeyboardButton>> read FKeyboard write FKeyboard; end; TtdReplyKeyboardMarkup = class(TtdReplyMarkup) private [JSONName('resize_keyboard')] FResizeKeyboard: Boolean; [JSONName('one_time_keyboard')] FOneTimeKeyboard: Boolean; [JSONName('selective')] FSelective: Boolean; [JSONName('keyboard')] FKeyboard: TArray<TArray<TtdKeyboardButton>>; [JSONName('input_field_placeholder')] FInputFieldPlaceholder: String; public procedure AddRow(AKeyboardRow: TArray<TtdKeyboardButton>); constructor Create(AResizeKeyboard, AOneTimeKeyboard: Boolean); overload; constructor Create(AKeyboardRow: TArray<TtdKeyboardButton>; AResizeKeyboard: Boolean = False; AOneTimeKeyboard: Boolean = False); overload; constructor Create(AKeyboard: TArray<TArray<TtdKeyboardButton>>; AResizeKeyboard: Boolean = False; AOneTimeKeyboard: Boolean = False); overload; destructor Destroy; override; property Keyboard: TArray<TArray<TtdKeyboardButton>> read FKeyboard write FKeyboard; property OneTimeKeyboard: Boolean read FOneTimeKeyboard write FOneTimeKeyboard; property ResizeKeyboard: Boolean read FResizeKeyboard write FResizeKeyboard; property Selective: Boolean read FSelective write FSelective; property InputFieldPlaceholder: String read FInputFieldPlaceholder write FInputFieldPlaceholder; end; TtdReplyKeyboardRemove = class(TtdReplyMarkup) private [JSONName('remove_keyboard')] FRemoveKeyboard: Boolean; public constructor Create(ARemoveKeyboard: Boolean = True); property RemoveKeyboard: Boolean read FRemoveKeyboard write FRemoveKeyboard; end; implementation uses System.SysUtils; constructor TtdInlineKeyboardButton.Create(const AText: string); begin Text := AText; end; constructor TtdInlineKeyboardButton.Create(const AText, ACallbackData: string); begin Self.Create(AText); Self.CallbackData := ACallbackData; end; constructor TtdKeyboardButton.Create(Const ARequestPoll: TtdKeyboardButtonPollType; AText: string; ARequestContact: Boolean = False; ARequestLocation: Boolean = False); begin inherited Create; Self.Text := AText; Self.RequestContact := ARequestContact; Self.RequestLocation := ARequestLocation; if ARequestPoll <> nil then Begin Self.RequestPoll := ARequestPoll; End; end; constructor TtdInlineKeyboardMarkup.Create(AInlineKeyboardRow: TArray< TtdInlineKeyboardButton>); begin inherited Create; AddRow(AInlineKeyboardRow); end; procedure TtdInlineKeyboardMarkup.AddRow(AKeyboardRow: TArray<TtdInlineKeyboardButton>); begin SetLength(FKeyboard, Length(FKeyboard) + 1); FKeyboard[High(FKeyboard)] := AKeyboardRow; end; constructor TtdInlineKeyboardMarkup.Create(AInlineKeyboard: TArray<TArray< TtdInlineKeyboardButton>>); var i: Integer; begin Self.Create; for i := Low(AInlineKeyboard) to High(AInlineKeyboard) do AddRow(AInlineKeyboard[i]); end; destructor TtdInlineKeyboardMarkup.Destroy; var i, j: Integer; begin for i := Low(FKeyboard) to High(FKeyboard) do for j := Low(FKeyboard[i]) to High(FKeyboard[i]) do FKeyboard[i, j].Free; inherited; end; constructor TtdInlineKeyboardMarkup.Create; begin inherited Create; end; constructor TtdReplyKeyboardMarkup.Create(AKeyboardRow: TArray<TtdKeyboardButton >; AResizeKeyboard, AOneTimeKeyboard: Boolean); begin inherited Create; AddRow(AKeyboardRow); ResizeKeyboard := AResizeKeyboard; OneTimeKeyboard := AOneTimeKeyboard; end; procedure TtdReplyKeyboardMarkup.AddRow(AKeyboardRow: TArray<TtdKeyboardButton>); begin SetLength(FKeyboard, Length(FKeyboard) + 1); FKeyboard[High(FKeyboard)] := AKeyboardRow; end; constructor TtdReplyKeyboardMarkup.Create(AKeyboard: TArray<TArray< TtdKeyboardButton>>; AResizeKeyboard, AOneTimeKeyboard: Boolean); begin inherited Create; Keyboard := AKeyboard; ResizeKeyboard := AResizeKeyboard; OneTimeKeyboard := AOneTimeKeyboard; end; destructor TtdReplyKeyboardMarkup.Destroy; var i, j: Integer; begin for i := Low(FKeyboard) to High(FKeyboard) do for j := Low(FKeyboard[i]) to High(FKeyboard[i]) do FKeyboard[i, j].Free; inherited; end; constructor TtdReplyKeyboardMarkup.Create(AResizeKeyboard, AOneTimeKeyboard: Boolean); begin inherited Create; ResizeKeyboard := AResizeKeyboard; OneTimeKeyboard := AOneTimeKeyboard; end; constructor TtdReplyKeyboardRemove.Create(ARemoveKeyboard: Boolean); begin inherited Create; RemoveKeyboard := ARemoveKeyboard; end; { TtdKeyboardButtonPollType } constructor TtdKeyboardButtonPollType.Create(const AType: string); begin &Type := AType; end; constructor TtdKeyboardButton.Create(const AText: string; ARequestContact, ARequestLocation: Boolean); begin inherited Create; Self.Text := AText; Self.RequestContact := ARequestContact; Self.RequestLocation := ARequestLocation; end; end.
1
0.835519
1
0.835519
game-dev
MEDIA
0.913076
game-dev
0.912157
1
0.912157