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
Planimeter/hl2sb-src
5,278
src/game/client/hud_posture.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "hud.h" #include "hudelement.h" #include "hud_numericdisplay.h" #include "hud_macros.h" #include "iclientmode.h" #include <vgui_controls/AnimationController.h> #include <vgui/ISurface.h> #include <vgui/ILocalize.h> #include <vgui_controls/Panel.h> #include <vgui/IVGui.h> using namespace vgui; // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define HUD_POSTURE_UPDATES_PER_SECOND 10 #define HUD_POSTURE_FADE_TIME 0.4f #define CROUCHING_CHARACTER_INDEX 92 // index of the crouching dude in the TTF font //----------------------------------------------------------------------------- // Purpose: Shows the sprint power bar //----------------------------------------------------------------------------- class CHudPosture : public CHudElement, public vgui::Panel { DECLARE_CLASS_SIMPLE( CHudPosture, vgui::Panel ); public: CHudPosture( const char *pElementName ); bool ShouldDraw( void ); #ifdef _X360 // if not xbox 360, don't waste code space on this virtual void Init( void ); virtual void Reset( void ); virtual void OnTick( void ); protected: virtual void Paint(); float m_duckTimeout; /// HUD_POSTURE_FADE_TIME after the last known time the player was ducking private: CPanelAnimationVar( vgui::HFont, m_hFont, "Font", "WeaponIconsSmall" ); CPanelAnimationVarAliasType( float, m_IconX, "icon_xpos", "4", "proportional_float" ); CPanelAnimationVarAliasType( float, m_IconY, "icon_ypos", "4", "proportional_float" ); enum { NOT_FADING, FADING_UP, FADING_DOWN } m_kIsFading; #endif }; DECLARE_HUDELEMENT( CHudPosture ); namespace { // Don't pass a null pPlayer. Doesn't check for it. inline bool PlayerIsDucking(C_BasePlayer *pPlayer) { return pPlayer->m_Local.m_bDucked && // crouching pPlayer->GetGroundEntity() != NULL ; // but not jumping } } //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CHudPosture::CHudPosture( const char *pElementName ) : CHudElement( pElementName ), BaseClass( NULL, "HudPosture" ) { vgui::Panel *pParent = g_pClientMode->GetViewport(); SetParent( pParent ); SetHiddenBits( HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT ); if( IsX360() ) { vgui::ivgui()->AddTickSignal( GetVPanel(), (1000/HUD_POSTURE_UPDATES_PER_SECOND) ); } } //----------------------------------------------------------------------------- // Purpose: Save CPU cycles by letting the HUD system early cull // costly traversal. Called per frame, return true if thinking and // painting need to occur. //----------------------------------------------------------------------------- bool CHudPosture::ShouldDraw() { #ifdef _X360 return ( m_duckTimeout >= gpGlobals->curtime && CHudElement::ShouldDraw() ); #else return false; #endif } #ifdef _X360 //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHudPosture::Init( void ) { m_duckTimeout = 0.0f; m_kIsFading = NOT_FADING; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHudPosture::Reset( void ) { Init(); } void CHudPosture::OnTick( void ) { C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if (!pPlayer) return; if ( PlayerIsDucking(pPlayer) ) { m_duckTimeout = gpGlobals->curtime + HUD_POSTURE_FADE_TIME; // kick the timer forward if (GetAlpha() < 255) { // if not fully faded in, and not fading in, start fading in. if (m_kIsFading != FADING_UP) { m_kIsFading = FADING_UP; GetAnimationController()->RunAnimationCommand( this, "alpha", 255, 0, HUD_POSTURE_FADE_TIME, vgui::AnimationController::INTERPOLATOR_SIMPLESPLINE ); } } else { m_kIsFading = NOT_FADING; } } else // player is not ducking { if (GetAlpha() > 0) { // if not faded out or fading out, fade out. if (m_kIsFading != FADING_DOWN) { m_kIsFading = FADING_DOWN; GetAnimationController()->RunAnimationCommand( this, "alpha", 0, 0, HUD_POSTURE_FADE_TIME, vgui::AnimationController::INTERPOLATOR_SIMPLESPLINE ); } } else { m_kIsFading = NOT_FADING; } } } //----------------------------------------------------------------------------- // Purpose: draws the posture elements we want. //----------------------------------------------------------------------------- void CHudPosture::Paint() { C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( !pPlayer ) return; SetPaintBackgroundEnabled( true ); Color clr; clr = gHUD.m_clrNormal; clr[3] = 255; // Pick the duck character wchar_t duck_char = CROUCHING_CHARACTER_INDEX; surface()->DrawSetTextFont( m_hFont ); surface()->DrawSetTextColor( clr ); surface()->DrawSetTextPos( m_IconX, m_IconY ); surface()->DrawUnicodeChar( duck_char ); } #endif
0
0.897346
1
0.897346
game-dev
MEDIA
0.835008
game-dev
0.55731
1
0.55731
LunaMultiplayer/LunaMultiplayer
4,567
LmpClient/Systems/Warp/WarpEntryDisplay.cs
using System.Collections.Generic; using System.Linq; using LmpClient.Base; using LmpClient.Systems.SettingsSys; using LmpCommon.Enums; namespace LmpClient.Systems.Warp { /// <summary> /// This subsystem is in charge of sending to the status window the users and it's subspaces /// </summary> public class WarpEntryDisplay : SubSystem<WarpSystem> { /// <summary> /// Get the list of player and subspaces depending on the warp mode /// </summary> /// <returns></returns> public List<SubspaceDisplayEntry> GetSubspaceDisplayEntries() { if (SettingsSystem.ServerSettings.WarpMode == WarpMode.Subspace) FillSubspaceDisplayEntriesSubspace(); else FillSubspaceDisplayEntriesNoneSubspace(); return System.SubspaceEntries; } #region private methods /// <summary> /// Retrieve the list of subspaces and players when the warp mode is ADMIN or NONE /// </summary> private static void FillSubspaceDisplayEntriesNoneSubspace() { if (System.SubspaceEntries.Count != 1 || System.ClientSubspaceList.Keys.Count != System.SubspaceEntries[0].Players.Count) { System.SubspaceEntries.Clear(); var allPlayers = new List<string> { SettingsSystem.CurrentSettings.PlayerName }; allPlayers.AddRange(System.ClientSubspaceList.Keys); allPlayers.Sort(PlayerSorter); System.SubspaceEntries.Add(new SubspaceDisplayEntry { Players = allPlayers, SubspaceId = 0, SubspaceTime = 0 }); } } /// <summary> /// Retrieve the list of subspaces and players when the warp mode is SUBSPACE /// </summary> private static void FillSubspaceDisplayEntriesSubspace() { //Redo the list only if the subspaces have changed. if (PlayersInSubspacesHaveChanged()) { System.SubspaceEntries.Clear(); var groupedPlayers = System.ClientSubspaceList.GroupBy(s => s.Value); SubspaceDisplayEntry warpingSubspace = null; foreach (var subspace in groupedPlayers) { var newSubspaceDisplay = new SubspaceDisplayEntry { SubspaceTime = System.GetSubspaceTime(subspace.Key), SubspaceId = subspace.Key, Players = subspace.Select(u => u.Key).ToList() }; if (newSubspaceDisplay.SubspaceId == -1) { warpingSubspace = newSubspaceDisplay; continue; } System.SubspaceEntries.Add(newSubspaceDisplay); } System.SubspaceEntries = System.SubspaceEntries.OrderByDescending(s => s.SubspaceTime).ToList(); if (warpingSubspace != null) System.SubspaceEntries.Insert(0, warpingSubspace); } } private static bool PlayersInSubspacesHaveChanged() { //We add 1 as subspace always contain the -1 subspace if (System.SubspaceEntries.Count + 1 != System.Subspaces.Count) return true; if (System.SubspaceEntries.Sum(s => s.Players.Count) != System.ClientSubspaceList.Keys.Count) return true; for (var i = 0; i < System.SubspaceEntries.Count; i++) { for (var j = 0; j < System.SubspaceEntries[i].Players.Count; j++) { var player = System.SubspaceEntries[i].Players[j]; var expectedSubspace = System.SubspaceEntries[i].SubspaceId; if (!System.ClientSubspaceList.TryGetValue(player, out var realSubspace) || realSubspace != expectedSubspace) return true; } } return false; } /// <summary> /// Sorts the players /// </summary> private static int PlayerSorter(string lhs, string rhs) { var ourName = SettingsSystem.CurrentSettings.PlayerName; if (lhs == ourName) return -1; return rhs == ourName ? 1 : string.CompareOrdinal(lhs, rhs); } #endregion } }
0
0.635731
1
0.635731
game-dev
MEDIA
0.697778
game-dev
0.819785
1
0.819785
microsoft/referencesource
1,304
mscorlib/system/diagnostics/symbolstore/token.cs
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: SymbolToken ** ** Small value class used by the SymbolStore package for passing ** around metadata tokens. ** ===========================================================*/ namespace System.Diagnostics.SymbolStore { using System; using System.Runtime.InteropServices; [ComVisible(true)] public struct SymbolToken { internal int m_token; public SymbolToken(int val) {m_token=val;} public int GetToken() {return m_token;} public override int GetHashCode() {return m_token;} public override bool Equals(Object obj) { if (obj is SymbolToken) return Equals((SymbolToken)obj); else return false; } public bool Equals(SymbolToken obj) { return obj.m_token == m_token; } public static bool operator ==(SymbolToken a, SymbolToken b) { return a.Equals(b); } public static bool operator !=(SymbolToken a, SymbolToken b) { return !(a == b); } } }
0
0.762452
1
0.762452
game-dev
MEDIA
0.317943
game-dev
0.664636
1
0.664636
divjackdiv/ProceduralMapShowcase
1,424
MapCreationShowcase/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_StyleAssetMenu.cs
using UnityEngine; using UnityEditor; using System.IO; using System.Collections; namespace TMPro.EditorUtilities { public static class TMP_StyleAssetMenu { [MenuItem("Assets/Create/TextMeshPro/Style Sheet", false, 120)] public static void CreateTextMeshProObjectPerform() { string filePath; if (Selection.assetGUIDs.Length == 0) { // No asset selected. filePath = "Assets"; } else { // Get the path of the selected folder or asset. filePath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]); // Get the file extension of the selected asset as it might need to be removed. string fileExtension = Path.GetExtension(filePath); if (fileExtension != "") { filePath = Path.GetDirectoryName(filePath); } } string filePathWithName = AssetDatabase.GenerateUniqueAssetPath(filePath + "/TMP StyleSheet.asset"); //// Create new Style Sheet Asset. TMP_StyleSheet styleSheet = ScriptableObject.CreateInstance<TMP_StyleSheet>(); AssetDatabase.CreateAsset(styleSheet, filePathWithName); EditorUtility.SetDirty(styleSheet); AssetDatabase.SaveAssets(); } } }
0
0.815804
1
0.815804
game-dev
MEDIA
0.900411
game-dev
0.504399
1
0.504399
ThePaperLuigi/The-Stars-Above
2,040
Projectiles/Bosses/WarriorOfLight/WarriorLightblast.cs
 using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace StarsAbove.Projectiles.Bosses.WarriorOfLight { public class WarriorLightblast : ModProjectile { public override void SetStaticDefaults() { ProjectileID.Sets.TrailCacheLength[Projectile.type] = 30; //The length of old position to be recorded ProjectileID.Sets.TrailingMode[Projectile.type] = 3; Main.projFrames[Projectile.type] = 11; } public override void SetDefaults() { Projectile.width = 40; Projectile.height = 40; Projectile.timeLeft = 680; Projectile.penetrate = -1; Projectile.aiStyle = 1; Projectile.scale = 1f; Projectile.alpha = 0; Projectile.localNPCHitCooldown = -1; Projectile.ownerHitCheck = true; Projectile.tileCollide = false; Projectile.friendly = false; Projectile.hostile = true; Projectile.netUpdate = true; AIType = ProjectileID.Bullet; DrawOriginOffsetY = -25; DrawOffsetX = -25; } public override bool PreDraw(ref Color lightColor) { default(Effects.YellowTrail).Draw(Projectile); return true; } public override void OnHitPlayer(Player target, Player.HurtInfo info) { Projectile.timeLeft = 50; } public override void AI() { Lighting.AddLight(Projectile.Center, new Vector3(0.99f, 0.6f, 0.3f)); if (++Projectile.frameCounter >= 4) { Projectile.frameCounter = 0; if (++Projectile.frame >= 11 && Projectile.timeLeft < 50) { //Main.PlaySound(SoundID.Drip, projectile.Center, 0); Projectile.Kill(); } if (++Projectile.frame >= 4 && Projectile.timeLeft > 50) { Projectile.frame = 0; } } Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.ToRadians(135f); // Offset by 90 degrees here if (Projectile.spriteDirection == -1) { Projectile.rotation -= MathHelper.ToRadians(90f); } // These dusts are added later, for the 'ExampleMod' effect } } }
0
0.728411
1
0.728411
game-dev
MEDIA
0.989908
game-dev
0.957943
1
0.957943
realnc/qtads
11,000
tads2/appctx.h
/* $Header: d:/cvsroot/tads/TADS2/appctx.h,v 1.2 1999/05/17 02:52:14 MJRoberts Exp $ */ /* * Copyright (c) 1997, 2002 Michael J. Roberts. All Rights Reserved. * * Please see the accompanying license file, LICENSE.TXT, for information * on using and copying this software. */ /* Name appctx.h - Application container context definitions Function Defines structures related to the TADS runtime application Notes Modified 9/05/98 CNebel - Spliced off from trd.h. */ #ifndef APPCTX_H #define APPCTX_H #ifdef __cplusplus extern "C" { #endif /* * Application container context. The TADS run-time is a subsystem that * can be invoked from different types of applications; in fact, even * when only the standard stand-alone run-time is considered, multiple * application containers must be supported because of differences * between operating systems. The application container context is an * optional mechanism that the main application can use to provide * structured interaction between itself and the TADS run-time subsystem. * * The function pointers contained herein are intended to allow the * run-time subsystem to call the host system to notify it of certain * events, or obtain optional services from the host system. Any of * these function pointers can be null, in which case the run-time * subsystem will skip calling them. * * Note that each function has an associated callback context. This * allows the host system to recover any necessary context information * when the callback is invoked. */ typedef struct appctxdef appctxdef; struct appctxdef { /* * Get the .GAM file name. The run-time will call this only if it * can't find a game file to load through some other means first. * The run-time determines the game file first by looking at the * command line, then by checking to see if a .GAM file is attached * to the executable. If none of these checks yields a game, the * run-time will call this routine to see if the host system wants * to provide a game. This routine can be implemented on a GUI * system, for example, to display a dialog prompting the user to * select a game file to open. A trivial implementation of this * routine (that merely returns false) is okay. * * This routine should return true (any non-zero value) if it * provides the name of a file to open, false (zero) if not. */ int (*get_game_name)(void *appctxdat, char *buf, size_t buflen); void *get_game_name_ctx; /* * Set the .GAM file name. When the run-time determines the name of * the file it will use to read the game, it calls this routine. * The host system should note the game filename if it will need to * access the game file itself (for example, to load resources). */ void (*set_game_name)(void *appctxdat, const char *fname); void *set_game_name_ctx; /* * Set the root path for individual resources. By default, we use the * directory containing the game file, but this can be used to override * that. */ void (*set_res_dir)(void *appctxdat, const char *fname); void *set_res_dir_ctx; /* * Set the resource map address in the game file. If the .GAM * reader encounters a resource map in the file, it calls this * routine with the seek offset of the first resource. Each * resource's address is given as an offset from this point. * * fileno is the file number assigned by the host system in * add_resfile. File number zero is always the .GAM file. */ void (*set_resmap_seek)(void *appctxdat, unsigned long seekpos, int fileno); void *set_resmap_seek_ctx; /* * Add a resource entry. The 'ofs' entry is the byte offset of the * start of the resource, relative to the seek position previously * set with set_resmap_seek. 'siz' is the size of the resource in * bytes; the resource is stored as contiguous bytes starting at the * given offset for the given size. Note that resources may be * added before the resource map seek position is set, so the host * system must simply store the resource information for later use. * The 'fileno' is zero for the .GAM file, or the number assigned by * the host system in add_resfile for other resource files. */ void (*add_resource)(void *appctxdat, unsigned long ofs, unsigned long siz, const char *nm, size_t nmlen, int fileno); void *add_resource_ctx; /* * Add a resource link entry. 'fname' and 'fnamelen' give the name of * a local file containing the resource data; 'resname' and * 'resnamelen' give the name of the resource as it appears within the * compiled game file. This creates a link from a .GAM resource name * to a local filename, where the actual binary resource data reside, * so that we can retrieve a resource by .GAM resource name without * actually copying the data into the .GAM file. This is used mostly * for debugging purposes: it allows the compiler to skip the step of * copying the resource data into the .GAM file, but still allows the * game to load resources by .GAM resource name, to create a testing * environment that's consistent with the full build version (where the * resources would actually be copied). */ void (*add_resource_link)(void *appctxdat, const char *fname, size_t fnamelen, const char *resname, size_t resnamelen); void *add_resource_link_ctx; /* * Add a resource path. 'path' is a string giving a directory prefix * in local system notation. * * This adds a directory to the list of directories that we'll search * when we're looking for an individual resource as an external file * (such as a ".jpg" image file or ".ogg" sound file). This can be * called zero or more times; each call adds another directory to * search after any previous directories. We'll always search the * default directory first (this is the directory containing the game * file); then we'll search directories added with this call in the * order in which the directories were added. */ void (*add_res_path)(void *appctxdat, const char *path, size_t len); void *add_res_path_ctx; /* * Find a resource entry. If the resource can be found, this must * return an osfildef* handle to the resource, with its seek position * set to the first byte of the resource data, and set *res_size to * the size in bytes of the resource data in the file. If the * resource cannot be found, returns null. */ osfildef *(*find_resource)(void *appctxdat, const char *resname, size_t resnamelen, unsigned long *res_size); void *find_resource_ctx; /* * Add a resource file. The return value is a non-zero file number * assigned by the host system; we'll use this number in subsequent * calls to add_resource to add the resources from this file. * * After calling this routine to add the file, we'll parse the file * and add any resources using add_resource. */ int (*add_resfile)(void *appctxdat, const char *fname); void *add_resfile_ctx; /* * Determine if a resource exists. Returns true if the resource can * be loaded, false if not. The resource name is in the standard * URL-style format. */ int (*resfile_exists)(void *appctxdat, const char *res_name, size_t res_name_len); void *resfile_exists_ctx; /* * Resource file path. If we should look for resource files in a * different location than the .GAM file, the host system can set * this to a path that we should use to look for resource files. If * it's null, we'll look in the directory that contains the .GAM * file. Note that if the path is provided, it must be set up with * a trailing path separator character, so that we can directly * append a name to this path to form a valid fully-qualified * filename. */ const char *ext_res_path; /* * File safety level get/set. During initialization, we'll call the * host system to tell it the file safety level selected by the user on * the command line; if the host system is saving preference * information, it should temporarily override its saved preferences * and use the command line setting (and it may, if appropriate, want * to save the command line setting as the saved preference setting, * depending on how it handles preferences). During execution, any * time the game tries to open a file (using the fopen built-in * function), we'll call the host system to ask it for the current * setting, and use this new setting rather than the original command * line setting. * * Refer to bif.c for information on the meanings of the file safety * levels. */ void (*set_io_safety_level)(void *ctx, int read, int write); void (*get_io_safety_level)(void *ctx, int *read, int *write); void *io_safety_level_ctx; /* * Network safety level get/set. This is analogous to the file safety * level scheme, but controls access to network resources. There are * two components to the network safety setting: client and server. * The client component controls the game's ability to open network * connections to access information on remote machines, such as * opening http connections to access web sites. The server component * controls the game's ability to create servers of its own and accept * incoming connections. Each component can be set to one of the * following: * *. 0 = no restrictions (least "safety"): all network access granted *. 1 = 'localhost' access only *. 2 = no network access * * This only applies to the TADS 3 VM. TADS 2 doesn't support any * network features, so this doesn't apply. */ void (*set_net_safety_level)(void *ctx, int client_level, int srv_level); void (*get_net_safety_level)(void *ctx, int *client_level, int *srv_level); void *net_safety_level_ctx; /* * Name of run-time application for usage messages. If this is * null, the default run-time application name will be used for * usage messages. */ const char *usage_app_name; }; #ifdef __cplusplus } #endif #endif
0
0.961211
1
0.961211
game-dev
MEDIA
0.676632
game-dev
0.667808
1
0.667808
IamLation/lation_mining
13,934
bridge/server.lua
-- Initialize global variables to store framework & inventory Framework, Inventory = nil, nil -- Initialize config(s) local sh_config = require 'config.shared' -- Get framework local function InitializeFramework() if GetResourceState('es_extended') == 'started' then ESX = exports['es_extended']:getSharedObject() Framework = 'esx' elseif GetResourceState('qbx_core') == 'started' then Framework = 'qbx' elseif GetResourceState('qb-core') == 'started' then QBCore = exports['qb-core']:GetCoreObject() Framework = 'qb' elseif GetResourceState('ox_core') == 'started' then Ox = require '@ox_core.lib.init' Framework = 'ox' else -- Add custom framework here end end -- Get inventory local function InitializeInventory() if GetResourceState('ox_inventory') == 'started' then Inventory = 'ox_inventory' elseif GetResourceState('qb-inventory') == 'started' then Inventory = 'qb-inventory' elseif GetResourceState('qs-inventory') == 'started' then Inventory = 'qs-inventory' elseif GetResourceState('ps-inventory') == 'started' then Inventory = 'ps-inventory' elseif GetResourceState('origen_inventory') == 'started' then Inventory = 'origen_inventory' elseif GetResourceState('codem-inventory') == 'started' then Inventory = 'codem-inventory' elseif GetResourceState('core_inventory') == 'started' then Inventory = 'core_inventory' else -- Add custom inventory here end end -- Get player from source --- @param source number Player ID function GetPlayer(source) if not source then return end if Framework == 'esx' then return ESX.GetPlayerFromId(source) elseif Framework == 'qb' then return QBCore.Functions.GetPlayer(source) elseif Framework == 'qbx' then return exports.qbx_core:GetPlayer(source) elseif Framework == 'ox' then return Ox.GetPlayer(source) else -- Add custom framework here end end -- Function to get a player identifier by source --- @param source number Player ID function GetIdentifier(source) local player = GetPlayer(source) if not player then return end if Framework == 'esx' then return player.identifier elseif Framework == 'qb' or Framework == 'qbx' then return player.PlayerData.citizenid elseif Framework == 'ox' then return player.stateId else -- Add custom framework here end end -- Function to get a player's name --- @param source number Player ID --- @return string function GetName(source) local player = GetPlayer(source) if not player then return 'Unknown' end if Framework == 'esx' then return player.getName() elseif Framework == 'qb' or Framework == 'qbx' then return player.PlayerData.charinfo.firstname.. ' ' ..player.PlayerData.charinfo.lastname elseif Framework == 'ox' then return player.get('firstName').. ' ' ..player.get('lastName') else -- Add custom framework here end return 'Unknown' end -- Returns number of players with police job(s) --- @return number function GetPoliceCount() local count, jobs = 0, {} for _, job in pairs(sh_config.police.jobs) do jobs[job] = true end if Framework == 'esx' then for _, player in pairs(ESX.GetExtendedPlayers()) do if jobs[player.getJob().name] then count += 1 end end elseif Framework == 'qb' then for _, playerId in pairs(QBCore.Functions.GetPlayers()) do local player = QBCore.Functions.GetPlayer(playerId) if jobs[player.PlayerData.job.name] and player.PlayerData.job.onduty then count += 1 end end elseif Framework == 'qbx' then for job, _ in pairs(jobs) do count += exports.qbx_core:GetDutyCountJob(job) end elseif Framework == 'ox' then for _, player in pairs(Ox.GetPlayers()) do if jobs[player.getGroupByType('job')] then count += 1 end end else -- Add custom framework here end return count end -- Returns number of specified item in players inventory --- @param source number Player ID --- @param item string Item to search --- @return number function GetItemCount(source, item) if not source or not item then return 0 end local player = GetPlayer(source) if not player then return 0 end if Inventory then if Inventory == 'ox_inventory' then return exports[Inventory]:Search(source, 'count', item) or 0 elseif Inventory == 'core_inventory' then return exports[Inventory]:getItemCount(source, item) elseif Inventory == 'qs-inventory' then return exports[Inventory]:GetItemTotalAmount(source, item) elseif Inventory == 'origen_inventory' then -- Origen has depricated the GetItemByName export, so we need to use the getItemCount export instead return exports[Inventory]:getItemCount(source, item) or 0 else local itemData = exports[Inventory]:GetItemByName(source, item) if not itemData then return 0 end return itemData.amount or itemData.count or 0 end else if Framework == 'esx' then local itemData = player.getInventoryItem(item) if not itemData then return 0 end return itemData.count or itemData.amount or 0 elseif Framework == 'qb' then local itemData = player.Functions.GetItemByName(item) if not itemData then return 0 end return itemData.amount or itemData.count or 0 else -- Add custom framework here end end return 0 end -- Returns correct framework money type if needed --- @param type string Money type --- @return string local function ConvertMoneyType(type) if type == 'money' and (Framework == 'qb' or Framework == 'qbx') then type = 'cash' elseif type == 'cash' and (Framework == 'esx' or Framework == 'ox') then type = 'money' else -- Add custom framework here end return type end -- Returns balance of players account --- @param source number Player ID --- @param type string Account to check --- @return number function GetPlayerBalance(source, type) local player = GetPlayer(source) if not player then return 0 end if Framework == 'esx' then return player.getAccount(ConvertMoneyType(type)).money or 0 elseif Framework == 'qb' then return player.PlayerData.money[ConvertMoneyType(type)] or 0 elseif Framework == 'qbx' then return player.Functions.GetMoney(ConvertMoneyType(type)) or 0 elseif Framework == 'ox' then if type == 'cash' or type == 'money' then return GetItemCount(source, ConvertMoneyType(type)) or 0 end return Ox.GetCharacterAccount(source).balance or 0 else -- Add custom framework here end return 0 end -- Add money to players account --- @param source number Player ID --- @param type string Account to add to --- @param amount number Amount to add function AddMoney(source, type, amount) local player = GetPlayer(source) if not player then return end if Framework == 'esx' then player.addAccountMoney(ConvertMoneyType(type), amount) elseif Framework == 'qb' or Framework == 'qbx' then player.Functions.AddMoney(ConvertMoneyType(type), amount) elseif Framework == 'ox' then if type == 'cash' or type == 'money' then exports.ox_inventory:AddItem(source, ConvertMoneyType(type), amount) else local accountId = Ox.GetCharacterAccount(source).id Ox.DepositMoney(source, accountId, amount) end else -- Add custom framework here end end -- Remove money from players account --- @param source number Player ID --- @param type string Account to remove from --- @param amount number Amount to remove function RemoveMoney(source, type, amount) local player = GetPlayer(source) if not player then return end if Framework == 'esx' then player.removeAccountMoney(ConvertMoneyType(type), amount) elseif Framework == 'qb' or Framework == 'qbx' then player.Functions.RemoveMoney(ConvertMoneyType(type), amount) elseif Framework == 'ox' then if type == 'cash' or type == 'money' then RemoveItem(source, ConvertMoneyType(type), amount) else local accountId = Ox.GetCharacterAccount(source).id Ox.WithdrawMoney(source, accountId, amount) end else -- Add custom framework here end end -- Returns if player can carry item --- @param source number Player ID --- @param item string Item name --- @param count number Item quantity function CanCarry(source, item, count) if count <= 0 then return true end local player = GetPlayer(source) if not player then return true end if Inventory then if Inventory == 'ox_inventory' then return exports[Inventory]:CanCarryItem(source, item, count) elseif Inventory == 'qb-inventory' then return exports[Inventory]:CanAddItem(source, item, count) elseif Inventory == 'qs-inventory' then return exports[Inventory]:CanCarryItem(source, item, count) elseif Inventory == 'ps-inventory' then -- ps sucks, why do they not have a dedicated export for this..? -- TODO: PR a dedicated export for CanCarryItem local totalWeight = exports[Inventory]:GetTotalWeight(player.PlayerData.items) if not totalWeight then return false end local itemInfo = QBCore.Shared.Items[item:lower()] if not itemInfo then return false end if (totalWeight + (itemInfo['weight'] * count)) <= 120000 then return true end return false elseif Inventory == 'origen_inventory' then return exports[Inventory]:canCarryItem(source, item, count) elseif Inventory == 'codem-inventory' then -- CodeM docs dont specify an export for this so.. return true elseif Inventory == 'core_inventory' then -- Core's canCarry export not working as expected, just return true return true else -- Add custom inventory here return true end else if Framework == 'esx' then if player.canCarryItem(item, count) then return true end return false elseif Framework == 'qb' then local totalWeight = QBCore.Player.GetTotalWeight(player.PlayerData.items) if not totalWeight then return false end local itemInfo = QBCore.Shared.Items[item:lower()] if not itemInfo then return false end if (totalWeight + (itemInfo['weight'] * count)) <= 120000 then return true end return false else -- Add custom framework here end end end -- Adds an item to players inventory --- @param source number Player ID --- @param item string Item to add --- @param count number Quantity to add --- @param metadata any|table Optional metadata function AddItem(source, item, count, metadata) if count <= 0 then return end local player = GetPlayer(source) if not player then return end if Inventory then if Inventory == 'ox_inventory' then exports[Inventory]:AddItem(source, item, count, metadata) elseif Inventory == 'core_inventory' then exports[Inventory]:addItem(source, item, count, metadata) elseif Inventory == 'qs-inventory' then exports[Inventory]:AddItem(source, item, count, false, metadata) elseif Inventory == 'origen_inventory' then local success, msgOrItem = exports.origen_inventory:addItem(source, item, count, metadata) if not success then print('^1[ERROR]: Failed to add item to inventory: '.. msgOrItem.. '^0') return end else exports[Inventory]:AddItem(source, item, count, nil, metadata) if Framework == 'qb' then TriggerClientEvent(Inventory.. ':client:ItemBox', source, QBCore.Shared.Items[item], 'add') end end else if Framework == 'esx' then player.addInventoryItem(item, count) elseif Framework == 'qb' then player.Functions.AddItem(item, count, nil, metadata) else -- Add custom framework here end end end -- Removes an item from players inventory --- @param source number Player ID --- @param item string Item to remove --- @param count number Quantity to remove function RemoveItem(source, item, count) local player = GetPlayer(source) if not player then return end if Inventory then if Inventory == 'core_inventory' then exports[Inventory]:removeItem(source, item, count) elseif Inventory == 'qs-inventory' then exports[Inventory]:RemoveItem(source, item, count) else exports[Inventory]:RemoveItem(source, item, count) if Framework == 'qb' then TriggerClientEvent(Inventory.. ':client:ItemBox', source, QBCore.Shared.Items[item], 'remove') end end else if Framework == 'esx' then player.removeInventoryItem(item, count) elseif Framework == 'qb' then player.Functions.RemoveItem(item, count) else -- Add custom framework here end end end -- Initialize defaults InitializeFramework() InitializeInventory()
0
0.745139
1
0.745139
game-dev
MEDIA
0.380202
game-dev
0.910156
1
0.910156
SpookTM/setorian-cityrp
3,850
plugins/typewriter_ix/derma/cl_typewriter.lua
local PANEL = {} local frame_background = Color(20, 20, 20) local frame_header_background = Color(40, 40, 40) local red_button_hovered = Color(189, 32, 0) local red_button = Color(138, 23, 0) local gray_button = Color(35, 35, 35) function PANEL:Init() self:SetSize(ScrW() * 0.3, ScrH() * 0.196) self:SetTitle("") self:SetDraggable(false) self:Center() self:MakePopup() self.Paint = function(self, w, h) draw.RoundedBoxEx(6, 0, 0, w, h, frame_background) draw.RoundedBoxEx(6, 0, 0, w, 30, frame_header_background, true, true, false, false) draw.DrawText("Typewriter Machine", "TypewriterTitleFont", w * 0.5, 8, color_white, TEXT_ALIGN_CENTER) end self.btnClose:Hide() self.FrameClose = self:Add("DButton") self.FrameClose:SetSize(50, 30) self.FrameClose:SetText("X") self.FrameClose:SetFont("TypewriterGeneralFont") self.FrameClose:SetColor(color_white) function self.FrameClose.PerformLayout(this,w, h) this:SetPos(self:GetWide() - w) end function self.FrameClose:Paint(w,h) if self:IsHovered() then draw.RoundedBoxEx(6, 0, 0, w, h, red_button_hovered, false, true) else draw.RoundedBoxEx(6, 0, 0, w, h, red_button, false, true) end end function self.FrameClose.DoClick() self:Close() end self:SetAlpha(0) timer.Simple(0.05, function() if not self or not IsValid(self) then return end local x,y = self:GetPos() self:SetPos(x + 50, y + 50) self:MoveTo(x, y, 0.3, 0, -1) self:AlphaTo(255, 0.3, 0.15) end) self.OpenText = self:Add("DLabel") self.OpenText:SetZPos(1) self.OpenText:Dock(TOP) self.OpenText:DockMargin(0, 10, 0, 10) self.OpenText:SetText("Use this Typewriter to turn a Google Doc into an in-game item in your inventory.") self.OpenText:SetContentAlignment(5) self.OpenText:SetFont("TypewriterGeneralFont") self.Title = self:Add("DTextEntry") self.Title:SetZPos(2) self.Title:Dock(TOP) self.Title:SetPlaceholderText("Document Title") self.Body = self:Add("DTextEntry") self.Body:SetZPos(3) self.Body:DockMargin(0, 15, 0, 0) self.Body:Dock(TOP) self.Body:SetPlaceholderText("Document Body (Google Doc Link)") self.QuantityPanel = self:Add("DPanel") self.QuantityPanel:SetZPos(4) self.QuantityPanel:Dock(TOP) self.QuantityPanel:DockMargin(10, 10, 0, 0) self.QuantityPanel:SetSize(self:GetWide(), 30) self.QuantityPanel:SetPaintBackground(false) self.OpenText = self.QuantityPanel:Add("DLabel") self.OpenText:Dock(LEFT) self.OpenText:SetText("How many copies would you like? (Max " .. ix.config.Get("MaxQuantityAmount") .. ")") self.OpenText:SetContentAlignment(4) self.OpenText:SetFont("TypewriterGeneralFont") self.OpenText:SizeToContents() self.Amount = self.QuantityPanel:Add("DNumberWang") self.Amount:DockMargin(20, 0, 0, 0) self.Amount:Dock(LEFT) self.Amount:SetValue(1) self.Amount:SetMin(1) self.Amount:SetMax(ix.config.Get("MaxQuantityAmount")) self.CreateButton = self:Add("DButton") self.CreateButton:SetZPos(5) self.CreateButton:Dock(BOTTOM) self.CreateButton:SetSize(self:GetWide() * 0.95, 30) self.CreateButton:SetColor(color_white) self.CreateButton:SetFont("TypewriterGeneralFont") self.CreateButton:SetText("Create Document") self.CreateButton.Paint = function(self, w, h) if self:IsHovered() then draw.RoundedBox(0, 0, 0, w, h, gray_button) else draw.RoundedBox(0, 0, 0, w, h, red_button) end end self.CreateButton.DoClick = function(btn) net.Start("MascoType::CreateDocumentInv") net.WriteString(self.Title:GetText()) net.WriteString(self.Body:GetText()) net.WriteInt(self.Amount:GetValue(), 32) net.SendToServer() self:Close() end end vgui.Register("ixTypewriter", PANEL, "DFrame")
0
0.744275
1
0.744275
game-dev
MEDIA
0.640063
game-dev,desktop-app
0.895963
1
0.895963
dpiers/Jedi-Academy
32,830
codemp/game/g_turret_G2.c
#include "g_local.h" #include "../ghoul2/G2.h" #include "q_shared.h" void G_SetEnemy( gentity_t *self, gentity_t *enemy ); void finish_spawning_turretG2( gentity_t *base ); void ObjectDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ); void turretG2_base_use( gentity_t *self, gentity_t *other, gentity_t *activator ); #define SPF_TURRETG2_CANRESPAWN 4 #define SPF_TURRETG2_TURBO 8 #define SPF_TURRETG2_LEAD_ENEMY 16 #define SPF_SHOWONRADAR 32 #define ARM_ANGLE_RANGE 60 #define HEAD_ANGLE_RANGE 90 #define name "models/map_objects/imp_mine/turret_canon.glm" #define name2 "models/map_objects/imp_mine/turret_damage.md3" #define name3 "models/map_objects/wedge/laser_cannon_model.glm" //special routine for tracking angles between client and server -rww void G2Tur_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) { #ifdef _XBOX byte *thebone = &ent->s.boneIndex1; byte *firstFree = NULL; #else int *thebone = &ent->s.boneIndex1; int *firstFree = NULL; #endif int i = 0; int boneIndex = G_BoneIndex(bone); int flags, up, right, forward; vec3_t *boneVector = &ent->s.boneAngles1; vec3_t *freeBoneVec = NULL; while (thebone) { if (!*thebone && !firstFree) { //if the value is 0 then this index is clear, we can use it if we don't find the bone we want already existing. firstFree = thebone; freeBoneVec = boneVector; } else if (*thebone) { if (*thebone == boneIndex) { //this is it break; } } switch (i) { case 0: thebone = &ent->s.boneIndex2; boneVector = &ent->s.boneAngles2; break; /* case 1: thebone = &ent->s.boneIndex3; boneVector = &ent->s.boneAngles3; break; case 2: thebone = &ent->s.boneIndex4; boneVector = &ent->s.boneAngles4; break; */ default: thebone = NULL; boneVector = NULL; break; } i++; } if (!thebone) { //didn't find it, create it if (!firstFree) { //no free bones.. can't do a thing then. #ifndef FINAL_BUILD Com_Printf("WARNING: NPC has no free bone indexes\n"); #endif return; } thebone = firstFree; *thebone = boneIndex; boneVector = freeBoneVec; } //If we got here then we have a vector and an index. //Copy the angles over the vector in the entitystate, so we can use the corresponding index //to set the bone angles on the client. VectorCopy(angles, *boneVector); //Now set the angles on our server instance if we have one. if (!ent->ghoul2) { return; } flags = BONE_ANGLES_POSTMULT; up = POSITIVE_Y; right = NEGATIVE_Z; forward = NEGATIVE_X; //first 3 bits is forward, second 3 bits is right, third 3 bits is up ent->s.boneOrient = ((forward)|(right<<3)|(up<<6)); trap_G2API_SetBoneAngles( ent->ghoul2, 0, bone, angles, flags, up, right, forward, NULL, 100, level.time ); } void turretG2_set_models( gentity_t *self, qboolean dying ) { if ( dying ) { if ( !(self->spawnflags&SPF_TURRETG2_TURBO) ) { self->s.modelindex = G_ModelIndex( name2 ); self->s.modelindex2 = G_ModelIndex( name ); } trap_G2API_RemoveGhoul2Model( &self->ghoul2, 0 ); G_KillG2Queue( self->s.number ); self->s.modelGhoul2 = 0; /* trap_G2API_InitGhoul2Model( &self->ghoul2, name2, 0, //base->s.modelindex, //note, this is not the same kind of index - this one's referring to the actual //index of the model in the g2 instance, whereas modelindex is the index of a //configstring -rww 0, 0, 0, 0); */ } else { if ( !(self->spawnflags&SPF_TURRETG2_TURBO) ) { self->s.modelindex = G_ModelIndex( name ); self->s.modelindex2 = G_ModelIndex( name2 ); //set the new onw trap_G2API_InitGhoul2Model( &self->ghoul2, name, 0, //base->s.modelindex, //note, this is not the same kind of index - this one's referring to the actual //index of the model in the g2 instance, whereas modelindex is the index of a //configstring -rww 0, 0, 0, 0); } else { self->s.modelindex = G_ModelIndex( name3 ); //set the new onw trap_G2API_InitGhoul2Model( &self->ghoul2, name3, 0, //base->s.modelindex, //note, this is not the same kind of index - this one's referring to the actual //index of the model in the g2 instance, whereas modelindex is the index of a //configstring -rww 0, 0, 0, 0); } self->s.modelGhoul2 = 1; if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) {//larger self->s.g2radius = 128; } else { self->s.g2radius = 80; } if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) {//different pitch bone and muzzle flash points G2Tur_SetBoneAngles(self, "pitch", vec3_origin); self->genericValue11 = trap_G2API_AddBolt( self->ghoul2, 0, "*muzzle1" ); self->genericValue12 = trap_G2API_AddBolt( self->ghoul2, 0, "*muzzle2" ); } else { G2Tur_SetBoneAngles(self, "Bone_body", vec3_origin); self->genericValue11 = trap_G2API_AddBolt( self->ghoul2, 0, "*flash03" ); } } } //------------------------------------------------------------------------------------------------------------ void TurretG2Pain( gentity_t *self, gentity_t *attacker, int damage ) //------------------------------------------------------------------------------------------------------------ { if (self->paintarget && self->paintarget[0]) { if (self->genericValue8 < level.time) { G_UseTargets2(self, self, self->paintarget); self->genericValue8 = level.time + self->genericValue4; } } if ( attacker->client && attacker->client->ps.weapon == WP_DEMP2 ) { self->attackDebounceTime = level.time + 2000 + random() * 500; self->painDebounceTime = self->attackDebounceTime; } if ( !self->enemy ) {//react to being hit G_SetEnemy( self, attacker ); } //self->s.health = self->health; //mmm..yes..bad. } //------------------------------------------------------------------------------------------------------------ void turretG2_die ( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) //------------------------------------------------------------------------------------------------------------ { vec3_t forward = { 0,0,-1 }, pos; // Turn off the thinking of the base & use it's targets //self->think = NULL; self->use = NULL; // clear my data self->die = NULL; self->pain = NULL; self->takedamage = qfalse; self->s.health = self->health = 0; self->s.loopSound = 0; self->s.shouldtarget = qfalse; //self->s.owner = MAX_CLIENTS; //not owned by any client // hack the effect angle so that explode death can orient the effect properly if ( self->spawnflags & 2 ) { VectorSet( forward, 0, 0, 1 ); } // VectorCopy( self->r.currentOrigin, self->s.pos.trBase ); VectorMA( self->r.currentOrigin, 12, forward, pos ); G_PlayEffect( EFFECT_EXPLOSION_TURRET, pos, forward ); if ( self->splashDamage > 0 && self->splashRadius > 0 ) { G_RadiusDamage( self->r.currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, NULL, MOD_UNKNOWN ); } if ( self->s.eFlags & EF_SHADER_ANIM ) { self->s.frame = 1; // black } self->s.weapon = 0; // crosshair code uses this to mark crosshair red if ( self->s.modelindex2 ) { // switch to damage model if we should turretG2_set_models( self, qtrue ); VectorCopy( self->r.currentAngles, self->s.apos.trBase ); VectorClear( self->s.apos.trDelta ); if ( self->target ) { G_UseTargets( self, attacker ); } if (self->spawnflags & SPF_TURRETG2_CANRESPAWN) {//respawn if (self->health < 1 && !self->genericValue5) { //we are dead, set our respawn delay if we have one self->genericValue5 = level.time + self->count; } } } else { ObjectDie( self, inflictor, attacker, damage, meansOfDeath ); } } #define START_DIS 15 //start an animation on model_root both server side and client side void TurboLaser_SetBoneAnim(gentity_t *eweb, int startFrame, int endFrame) { //set info on the entity so it knows to start the anim on the client next snapshot. eweb->s.eFlags |= EF_G2ANIMATING; if (eweb->s.torsoAnim == startFrame && eweb->s.legsAnim == endFrame) { //already playing this anim, let's flag it to restart eweb->s.torsoFlip = !eweb->s.torsoFlip; } else { eweb->s.torsoAnim = startFrame; eweb->s.legsAnim = endFrame; } //now set the animation on the server ghoul2 instance. assert(eweb->ghoul2); trap_G2API_SetBoneAnim(eweb->ghoul2, 0, "model_root", startFrame, endFrame, (BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND), 1.0f, level.time, -1, 100); } extern void WP_FireTurboLaserMissile( gentity_t *ent, vec3_t start, vec3_t dir ); //---------------------------------------------------------------- static void turretG2_fire ( gentity_t *ent, vec3_t start, vec3_t dir ) //---------------------------------------------------------------- { vec3_t org, ang; gentity_t *bolt; if ( (trap_PointContents( start, ent->s.number )&MASK_SHOT) ) { return; } VectorMA( start, -START_DIS, dir, org ); // dumb.... if ( ent->random ) { vectoangles( dir, ang ); ang[PITCH] += flrand( -ent->random, ent->random ); ang[YAW] += flrand( -ent->random, ent->random ); AngleVectors( ang, dir, NULL, NULL ); } vectoangles(dir, ang); if ( (ent->spawnflags&SPF_TURRETG2_TURBO) ) { //muzzle flash G_PlayEffectID( ent->genericValue13, org, ang ); WP_FireTurboLaserMissile( ent, start, dir ); if ( ent->alt_fire ) { TurboLaser_SetBoneAnim( ent, 2, 3 ); } else { TurboLaser_SetBoneAnim( ent, 0, 1 ); } } else { G_PlayEffectID( G_EffectIndex("blaster/muzzle_flash"), org, ang ); bolt = G_Spawn(); bolt->classname = "turret_proj"; bolt->nextthink = level.time + 10000; bolt->think = G_FreeEntity; bolt->s.eType = ET_MISSILE; bolt->s.weapon = WP_BLASTER; bolt->r.ownerNum = ent->s.number; bolt->damage = ent->damage; bolt->alliedTeam = ent->alliedTeam; bolt->teamnodmg = ent->teamnodmg; bolt->dflags = (DAMAGE_NO_KNOCKBACK|DAMAGE_HEAVY_WEAP_CLASS); // Don't push them around, or else we are constantly re-aiming bolt->splashDamage = ent->splashDamage; bolt->splashRadius = ent->splashDamage; bolt->methodOfDeath = MOD_TARGET_LASER;//MOD_ENERGY; bolt->splashMethodOfDeath = MOD_TARGET_LASER;//MOD_ENERGY; bolt->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; //bolt->trigger_formation = qfalse; // don't draw tail on first frame VectorSet( bolt->r.maxs, 1.5, 1.5, 1.5 ); VectorScale( bolt->r.maxs, -1, bolt->r.mins ); bolt->s.pos.trType = TR_LINEAR; bolt->s.pos.trTime = level.time; VectorCopy( start, bolt->s.pos.trBase ); VectorScale( dir, ent->mass, bolt->s.pos.trDelta ); SnapVector( bolt->s.pos.trDelta ); // save net bandwidth VectorCopy( start, bolt->r.currentOrigin); } } void turretG2_respawn( gentity_t *self ) { self->use = turretG2_base_use; self->pain = TurretG2Pain; self->die = turretG2_die; self->takedamage = qtrue; self->s.shouldtarget = qtrue; //self->s.owner = MAX_CLIENTS; //not owned by any client if ( self->s.eFlags & EF_SHADER_ANIM ) { self->s.frame = 0; // normal } self->s.weapon = WP_TURRET; // crosshair code uses this to mark crosshair red turretG2_set_models( self, qfalse ); self->s.health = self->health = self->genericValue6; if (self->maxHealth) { G_ScaleNetHealth(self); } self->genericValue5 = 0;//clear this now } //----------------------------------------------------- void turretG2_head_think( gentity_t *self ) //----------------------------------------------------- { // if it's time to fire and we have an enemy, then gun 'em down! pushDebounce time controls next fire time if ( self->enemy && self->setTime < level.time && self->attackDebounceTime < level.time ) { vec3_t fwd, org; mdxaBone_t boltMatrix; // set up our next fire time self->setTime = level.time + self->wait; // Getting the flash bolt here trap_G2API_GetBoltMatrix( self->ghoul2, 0, (self->alt_fire?self->genericValue12:self->genericValue11), &boltMatrix, self->r.currentAngles, self->r.currentOrigin, level.time, NULL, self->modelScale ); if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) { self->alt_fire = !self->alt_fire; } BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, org ); //BG_GiveMeVectorFromMatrix( &boltMatrix, POSITIVE_Y, fwd ); if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) { BG_GiveMeVectorFromMatrix( &boltMatrix, POSITIVE_X, fwd ); } else { BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_X, fwd ); } VectorMA( org, START_DIS, fwd, org ); turretG2_fire( self, org, fwd ); self->fly_sound_debounce_time = level.time;//used as lastShotTime } } //----------------------------------------------------- static void turretG2_aim( gentity_t *self ) //----------------------------------------------------- { vec3_t enemyDir, org, org2; vec3_t desiredAngles, setAngle; float diffYaw = 0.0f, diffPitch = 0.0f; float maxYawSpeed = (self->spawnflags&SPF_TURRETG2_TURBO)?30.0f:14.0f; float maxPitchSpeed = (self->spawnflags&SPF_TURRETG2_TURBO)?15.0f:3.0f; // move our gun base yaw to where we should be at this time.... BG_EvaluateTrajectory( &self->s.apos, level.time, self->r.currentAngles ); self->r.currentAngles[YAW] = AngleNormalize360( self->r.currentAngles[YAW] ); self->speed = AngleNormalize360( self->speed ); if ( self->enemy ) { mdxaBone_t boltMatrix; // ...then we'll calculate what new aim adjustments we should attempt to make this frame // Aim at enemy if ( self->enemy->client ) { VectorCopy( self->enemy->client->renderInfo.eyePoint, org ); } else { VectorCopy( self->enemy->r.currentOrigin, org ); } if ( self->spawnflags & 2 ) { org[2] -= 15; } else { org[2] -= 5; } if ( (self->spawnflags&SPF_TURRETG2_LEAD_ENEMY) ) {//we want to lead them a bit vec3_t diff, velocity; float dist; VectorSubtract( org, self->s.origin, diff ); dist = VectorNormalize( diff ); if ( self->enemy->client ) { VectorCopy( self->enemy->client->ps.velocity, velocity ); } else { VectorCopy( self->enemy->s.pos.trDelta, velocity ); } VectorMA( org, (dist/self->mass), velocity, org ); } // Getting the "eye" here trap_G2API_GetBoltMatrix( self->ghoul2, 0, (self->alt_fire?self->genericValue12:self->genericValue11), &boltMatrix, self->r.currentAngles, self->s.origin, level.time, NULL, self->modelScale ); BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, org2 ); VectorSubtract( org, org2, enemyDir ); vectoangles( enemyDir, desiredAngles ); diffYaw = AngleSubtract( self->r.currentAngles[YAW], desiredAngles[YAW] ); diffPitch = AngleSubtract( self->speed, desiredAngles[PITCH] ); } else { // no enemy, so make us slowly sweep back and forth as if searching for a new one // diffYaw = sin( level.time * 0.0001f + self->count ) * 5.0f; // don't do this for now since it can make it go into walls. } if ( diffYaw ) { // cap max speed.... if ( fabs(diffYaw) > maxYawSpeed ) { diffYaw = ( diffYaw >= 0 ? maxYawSpeed : -maxYawSpeed ); } // ...then set up our desired yaw VectorSet( setAngle, 0.0f, diffYaw, 0.0f ); VectorCopy( self->r.currentAngles, self->s.apos.trBase ); VectorScale( setAngle,- 5, self->s.apos.trDelta ); self->s.apos.trTime = level.time; self->s.apos.trType = TR_LINEAR; } if ( diffPitch ) { if ( fabs(diffPitch) > maxPitchSpeed ) { // cap max speed self->speed += (diffPitch > 0.0f) ? -maxPitchSpeed : maxPitchSpeed; } else { // small enough, so just add half the diff so we smooth out the stopping self->speed -= ( diffPitch );//desiredAngles[PITCH]; } // Note that this is NOT interpolated, so it will be less smooth...On the other hand, it does use Ghoul2 to blend, so it may smooth it out a bit? if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) { if ( self->spawnflags & 2 ) { VectorSet( desiredAngles, 0.0f, 0.0f, -self->speed ); } else { VectorSet( desiredAngles, 0.0f, 0.0f, self->speed ); } G2Tur_SetBoneAngles(self, "pitch", desiredAngles); } else { if ( self->spawnflags & 2 ) { VectorSet( desiredAngles, self->speed, 0.0f, 0.0f ); } else { VectorSet( desiredAngles, -self->speed, 0.0f, 0.0f ); } G2Tur_SetBoneAngles(self, "Bone_body", desiredAngles); } /* trap_G2API_SetBoneAngles( self->ghoul2, 0, "Bone_body", desiredAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 100, level.time ); */ } if ( diffYaw || diffPitch ) {//FIXME: turbolaser sounds if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) { self->s.loopSound = G_SoundIndex( "sound/vehicles/weapons/turbolaser/turn.wav" ); } else { self->s.loopSound = G_SoundIndex( "sound/chars/turret/move.wav" ); } } else { self->s.loopSound = 0; } } //----------------------------------------------------- static void turretG2_turnoff( gentity_t *self ) //----------------------------------------------------- { if ( self->enemy == NULL ) { // we don't need to turnoff return; } if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) { TurboLaser_SetBoneAnim( self, 4, 5 ); } // shut-down sound if ( !(self->spawnflags&SPF_TURRETG2_TURBO) ) { G_Sound( self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); } // make turret play ping sound for 5 seconds self->aimDebounceTime = level.time + 5000; // Clear enemy self->enemy = NULL; } //----------------------------------------------------- static qboolean turretG2_find_enemies( gentity_t *self ) //----------------------------------------------------- { qboolean found = qfalse; int i, count; float bestDist = self->radius * self->radius; float enemyDist; vec3_t enemyDir, org, org2; qboolean foundClient = qfalse; gentity_t *entity_list[MAX_GENTITIES], *target, *bestTarget = NULL; if ( self->aimDebounceTime > level.time ) // time since we've been shut off { // We were active and alert, i.e. had an enemy in the last 3 secs if ( self->painDebounceTime < level.time ) { if ( !(self->spawnflags&SPF_TURRETG2_TURBO) ) { G_Sound(self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/ping.wav" )); } self->painDebounceTime = level.time + 1000; } } VectorCopy( self->r.currentOrigin, org2 ); if ( self->spawnflags & 2 ) { org2[2] += 20; } else { org2[2] -= 20; } count = G_RadiusList( org2, self->radius, self, qtrue, entity_list ); for ( i = 0; i < count; i++ ) { trace_t tr; target = entity_list[i]; if ( !target->client ) { // only attack clients if ( !(target->flags&FL_BBRUSH)//not a breakable brush || !target->takedamage//is a bbrush, but invincible || (target->NPC_targetname&&self->targetname&&Q_stricmp(target->NPC_targetname,self->targetname)!=0) )//not in invicible bbrush, but can only be broken by an NPC that is not me { continue; } //else: we will shoot at bbrushes! } if ( target == self || !target->takedamage || target->health <= 0 || ( target->flags & FL_NOTARGET )) { continue; } if ( target->client && target->client->sess.sessionTeam == TEAM_SPECTATOR ) { continue; } if ( self->alliedTeam ) { if ( target->client ) { if ( target->client->sess.sessionTeam == self->alliedTeam ) { // A bot/client/NPC we don't want to shoot continue; } } else if ( target->teamnodmg == self->alliedTeam ) { // An ent we don't want to shoot continue; } } if ( !trap_InPVS( org2, target->r.currentOrigin )) { continue; } if ( target->client ) { VectorCopy( target->client->renderInfo.eyePoint, org ); } else { VectorCopy( target->r.currentOrigin, org ); } if ( self->spawnflags & 2 ) { org[2] -= 15; } else { org[2] += 5; } trap_Trace( &tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT ); if ( !tr.allsolid && !tr.startsolid && ( tr.fraction == 1.0 || tr.entityNum == target->s.number )) { // Only acquire if have a clear shot, Is it in range and closer than our best? VectorSubtract( target->r.currentOrigin, self->r.currentOrigin, enemyDir ); enemyDist = VectorLengthSquared( enemyDir ); if ( enemyDist < bestDist || (target->client && !foundClient))// all things equal, keep current { if ( self->attackDebounceTime < level.time ) { // We haven't fired or acquired an enemy in the last 2 seconds-start-up sound if ( !(self->spawnflags&SPF_TURRETG2_TURBO) ) { G_Sound( self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/startup.wav" )); } // Wind up turrets for a bit self->attackDebounceTime = level.time + 1400; } bestTarget = target; bestDist = enemyDist; found = qtrue; if ( target->client ) {//prefer clients over non-clients foundClient = qtrue; } } } } if ( found ) { /* if ( !self->enemy ) {//just aquired one AddSoundEvent( bestTarget, self->r.currentOrigin, 256, AEL_DISCOVERED ); AddSightEvent( bestTarget, self->r.currentOrigin, 512, AEL_DISCOVERED, 20 ); } */ G_SetEnemy( self, bestTarget ); if ( VALIDSTRING( self->target2 )) { G_UseTargets2( self, self, self->target2 ); } } return found; } //----------------------------------------------------- void turretG2_base_think( gentity_t *self ) //----------------------------------------------------- { qboolean turnOff = qtrue; float enemyDist; vec3_t enemyDir, org, org2; self->nextthink = level.time + FRAMETIME; if ( self->health <= 0 ) {//dead if (self->spawnflags & SPF_TURRETG2_CANRESPAWN) {//can respawn if ( self->genericValue5 && self->genericValue5 < level.time ) { //we are dead, see if it's time to respawn turretG2_respawn( self ); } } return; } else if ( self->spawnflags & 1 ) {// not turned on turretG2_turnoff( self ); turretG2_aim( self ); // No target self->flags |= FL_NOTARGET; return; } else { // I'm all hot and bothered self->flags &= ~FL_NOTARGET; } if ( self->enemy ) { if ( self->enemy->health < 0 || !self->enemy->inuse ) { self->enemy = NULL; } } if ( self->last_move_time < level.time ) {//MISNOMER: used a enemy recalcing debouncer if ( turretG2_find_enemies( self ) ) {//found one turnOff = qfalse; if ( self->enemy->client ) {//hold on to clients for a min of 3 seconds self->last_move_time = level.time + 3000; } else {//hold less self->last_move_time = level.time + 500; } } } if ( self->enemy != NULL ) { if ( self->enemy->client && self->enemy->client->sess.sessionTeam == TEAM_SPECTATOR ) {//don't keep going after spectators self->enemy = NULL; } else {//FIXME: remain single-minded or look for a new enemy every now and then? // enemy is alive VectorSubtract( self->enemy->r.currentOrigin, self->r.currentOrigin, enemyDir ); enemyDist = VectorLengthSquared( enemyDir ); if ( enemyDist < self->radius * self->radius ) { // was in valid radius if ( trap_InPVS( self->r.currentOrigin, self->enemy->r.currentOrigin ) ) { // Every now and again, check to see if we can even trace to the enemy trace_t tr; if ( self->enemy->client ) { VectorCopy( self->enemy->client->renderInfo.eyePoint, org ); } else { VectorCopy( self->enemy->r.currentOrigin, org ); } VectorCopy( self->r.currentOrigin, org2 ); if ( self->spawnflags & 2 ) { org2[2] += 10; } else { org2[2] -= 10; } trap_Trace( &tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT ); if ( !tr.allsolid && !tr.startsolid && tr.entityNum == self->enemy->s.number ) { turnOff = qfalse; // Can see our enemy } } } } } if ( turnOff ) { if ( self->bounceCount < level.time ) // bounceCount is used to keep the thing from ping-ponging from on to off { turretG2_turnoff( self ); } } else { // keep our enemy for a minimum of 2 seconds from now self->bounceCount = level.time + 2000 + random() * 150; } turretG2_aim( self ); if ( !turnOff ) { turretG2_head_think( self ); } } //----------------------------------------------------------------------------- void turretG2_base_use( gentity_t *self, gentity_t *other, gentity_t *activator ) //----------------------------------------------------------------------------- { // Toggle on and off self->spawnflags = (self->spawnflags ^ 1); if (( self->s.eFlags & EF_SHADER_ANIM ) && ( self->spawnflags & 1 )) // Start_Off { self->s.frame = 1; // black } else { self->s.frame = 0; // glow } } /*QUAKED misc_turretG2 (1 0 0) (-8 -8 -22) (8 8 0) START_OFF UPSIDE_DOWN CANRESPAWN TURBO LEAD SHOWRADAR Turret that hangs from the ceiling, will aim and shoot at enemies START_OFF - Starts off UPSIDE_DOWN - make it rest on a surface/floor instead of hanging from the ceiling CANRESPAWN - will respawn after being killed (use count) TURBO - Big-ass, Boxy Death Star Turbo Laser version LEAD - Turret will aim ahead of moving targets ("lead" them) SHOWRADAR - show on radar radius - How far away an enemy can be for it to pick it up (default 512) wait - Time between shots (default 150 ms) dmg - How much damage each shot does (default 5) health - How much damage it can take before exploding (default 100) count - if CANRESPAWN spawnflag, decides how long it is before gun respawns (in ms) - defaults to 20000 (20 seconds) paintarget - target to fire off upon being hurt painwait - ms to wait between firing off pain targets random - random error (in degrees) of projectile direction when it comes out of the muzzle (default is 2) shotspeed - the speed of the missile it fires travels at (default is 1100 for regular turrets, 20000 for TURBOLASERS) splashDamage - How much damage the explosion does splashRadius - The radius of the explosion targetname - Toggles it on/off target - What to use when destroyed target2 - What to use when it decides to start shooting at an enemy showhealth - set to 1 to show health bar on this entity when crosshair is over it teamowner - crosshair shows green for this team, red for opposite team 0 - none 1 - red 2 - blue alliedTeam - team that this turret won't target 0 - none 1 - red 2 - blue teamnodmg - team that turret does not take damage from 0 - none 1 - red 2 - blue customscale - custom scaling size. 100 is normal size, 1024 is the max scaling. this will change the bounding box size, so be careful of starting in solid! */ //----------------------------------------------------- void SP_misc_turretG2( gentity_t *base ) //----------------------------------------------------- { int customscaleVal; turretG2_set_models( base, qfalse ); G_SpawnInt("painwait", "0", &base->genericValue4); base->genericValue8 = 0; G_SpawnInt("customscale", "0", &customscaleVal); base->s.iModelScale = customscaleVal; if (base->s.iModelScale) { if (base->s.iModelScale > 1023) { base->s.iModelScale = 1023; } base->modelScale[0] = base->modelScale[1] = base->modelScale[2] = base->s.iModelScale/100.0f; } finish_spawning_turretG2( base ); if (( base->spawnflags & 1 )) // Start_Off { base->s.frame = 1; // black } else { base->s.frame = 0; // glow } if ( !(base->spawnflags&SPF_TURRETG2_TURBO) ) { base->s.eFlags |= EF_SHADER_ANIM; } if (base->spawnflags & SPF_SHOWONRADAR) { base->s.eFlags |= EF_RADAROBJECT; } #undef name #undef name2 #undef name3 } //----------------------------------------------------- void finish_spawning_turretG2( gentity_t *base ) { vec3_t fwd; int t; if ( (base->spawnflags&2) ) { base->s.angles[ROLL] += 180; base->s.origin[2] -= 22.0f; } G_SetAngles( base, base->s.angles ); AngleVectors( base->r.currentAngles, fwd, NULL, NULL ); G_SetOrigin(base, base->s.origin); base->s.eType = ET_GENERAL; if ( base->team && base->team[0] && //g_gametype.integer == GT_SIEGE && !base->teamnodmg) { base->teamnodmg = atoi(base->team); } base->team = NULL; // Set up our explosion effect for the ExplodeDeath code.... G_EffectIndex( "turret/explode" ); G_EffectIndex( "sparks/spark_exp_nosnd" ); base->use = turretG2_base_use; base->pain = TurretG2Pain; // don't start working right away base->think = turretG2_base_think; base->nextthink = level.time + FRAMETIME * 5; // this is really the pitch angle..... base->speed = 0; // respawn time defaults to 20 seconds if ( (base->spawnflags&SPF_TURRETG2_CANRESPAWN) && !base->count ) { base->count = 20000; } G_SpawnFloat( "shotspeed", "0", &base->mass ); if ( (base->spawnflags&SPF_TURRETG2_TURBO) ) { if ( !base->random ) {//error worked into projectile direction base->random = 2.0f; } if ( !base->mass ) {//misnomer: speed of projectile base->mass = 20000; } if ( !base->health ) { base->health = 2000; } // search radius if ( !base->radius ) { base->radius = 32768; } // How quickly to fire if ( !base->wait ) { base->wait = 1000;// + random() * 500; } if ( !base->splashDamage ) { base->splashDamage = 200; } if ( !base->splashRadius ) { base->splashRadius = 500; } // how much damage each shot does if ( !base->damage ) { base->damage = 500; } if ( (base->spawnflags&SPF_TURRETG2_TURBO) ) { VectorSet( base->r.maxs, 64.0f, 64.0f, 30.0f ); VectorSet( base->r.mins, -64.0f, -64.0f, -30.0f ); } //start in "off" anim TurboLaser_SetBoneAnim( base, 4, 5 ); if ( g_gametype.integer == GT_SIEGE ) {//FIXME: designer-specified? //FIXME: put on other entities, too, particularly siege objectives and bbrushes... base->s.eFlags2 |= EF2_BRACKET_ENTITY; } } else { if ( !base->random ) {//error worked into projectile direction base->random = 2.0f; } if ( !base->mass ) {//misnomer: speed of projectile base->mass = 1100; } if ( !base->health ) { base->health = 100; } // search radius if ( !base->radius ) { base->radius = 512; } // How quickly to fire if ( !base->wait ) { base->wait = 150 + random() * 55; } if ( !base->splashDamage ) { base->splashDamage = 10; } if ( !base->splashRadius ) { base->splashRadius = 25; } // how much damage each shot does if ( !base->damage ) { base->damage = 5; } if ( base->spawnflags & 2 ) {//upside-down, invert r.mins and maxe VectorSet( base->r.maxs, 10.0f, 10.0f, 30.0f ); VectorSet( base->r.mins, -10.0f, -10.0f, 0.0f ); } else { VectorSet( base->r.maxs, 10.0f, 10.0f, 0.0f ); VectorSet( base->r.mins, -10.0f, -10.0f, -30.0f ); } } //stash health off for respawn. NOTE: cannot use maxhealth because that might not be set if not showing the health bar base->genericValue6 = base->health; G_SpawnInt( "showhealth", "0", &t ); if (t) { //a non-0 maxhealth value will mean we want to show the health on the hud base->maxHealth = base->health; G_ScaleNetHealth(base); base->s.shouldtarget = qtrue; //base->s.owner = MAX_CLIENTS; //not owned by any client } if (base->s.iModelScale) { //let's scale the bbox too... float fScale = base->s.iModelScale/100.0f; VectorScale(base->r.mins, fScale, base->r.mins); VectorScale(base->r.maxs, fScale, base->r.maxs); } // Precache special FX and moving sounds if ( (base->spawnflags&SPF_TURRETG2_TURBO) ) { base->genericValue13 = G_EffectIndex( "turret/turb_muzzle_flash" ); base->genericValue14 = G_EffectIndex( "turret/turb_shot" ); base->genericValue15 = G_EffectIndex( "turret/turb_impact" ); //FIXME: Turbo Laser Cannon sounds! G_SoundIndex( "sound/vehicles/weapons/turbolaser/turn.wav" ); } else { G_SoundIndex( "sound/chars/turret/startup.wav" ); G_SoundIndex( "sound/chars/turret/shutdown.wav" ); G_SoundIndex( "sound/chars/turret/ping.wav" ); G_SoundIndex( "sound/chars/turret/move.wav" ); } base->r.contents = CONTENTS_BODY|CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_SHOTCLIP; //base->max_health = base->health; base->takedamage = qtrue; base->die = turretG2_die; base->material = MAT_METAL; //base->r.svFlags |= SVF_NO_TELEPORT|SVF_NONNPC_ENEMY|SVF_SELF_ANIMATING; // Register this so that we can use it for the missile effect RegisterItem( BG_FindItemForWeapon( WP_BLASTER )); // But set us as a turret so that we can be identified as a turret base->s.weapon = WP_TURRET; trap_LinkEntity( base ); }
0
0.941961
1
0.941961
game-dev
MEDIA
0.988255
game-dev
0.92058
1
0.92058
jcweaver997/vgdextension
1,340
examples/shooter2d/src/main.v
module main import log import vgdextension as gd pub fn init_gd(v voidptr, l gd.GDExtensionInitializationLevel) { // Register classes at scene initialization if l == .initialization_level_scene { gd.register_class_with_name[FollowCamera]('Camera2D', 'FollowCamera') gd.register_class_with_name[Player]('CharacterBody2D', 'Player') gd.register_class_with_name[Enemy]('CharacterBody2D', 'Enemy') gd.register_class_with_name[Bullet]('Area2D', 'Bullet') gd.register_class_with_name[Smoother2D]('Node', 'Smoother2D') gd.register_class_with_name[Spawner]('Node', 'Spawner') } } pub fn deinit_gd(v voidptr, l gd.GDExtensionInitializationLevel) { if l == .initialization_level_scene { println('deinit') } } // Godot entry function, is called by godot when our shared library is loaded @[export: 'hello_extension_entry'] pub fn hello_extension_entry(gpaddr fn (&i8) gd.GDExtensionInterfaceFunctionPtr, clp gd.GDExtensionClassLibraryPtr, mut gdnit gd.GDExtensionInitialization) gd.GDExtensionBool { gd.setup_lib(gpaddr, clp) ver := gd.GDExtensionGodotVersion{} gdf.get_godot_version(&ver) println('version ${ver}') // setup the `initialize` function gdnit.initialize = init_gd // setup the `deinitialize` function gdnit.deinitialize = deinit_gd // setup godot logger log.set_logger(&gd.GodotLogger{}) return 1 }
0
0.773067
1
0.773067
game-dev
MEDIA
0.55195
game-dev,graphics-rendering
0.618476
1
0.618476
Rinnegatamante/vitaQuakeIII
18,988
oa-0.8.8/code/ui/ui_sppostgame.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 =========================================================================== */ // /* ============================================================================= SINGLE PLAYER POSTGAME MENU ============================================================================= */ #include "ui_local.h" #define MAX_SCOREBOARD_CLIENTS 8 #define AWARD_PRESENTATION_TIME 2000 #define ART_MENU0 "menu/art_blueish/menu_0" #define ART_MENU1 "menu/art_blueish/menu_1" #define ART_REPLAY0 "menu/art_blueish/replay_0" #define ART_REPLAY1 "menu/art_blueish/replay_1" #define ART_NEXT0 "menu/art_blueish/next_0" #define ART_NEXT1 "menu/art_blueish/next_1" #define ID_AGAIN 10 #define ID_NEXT 11 #define ID_MENU 12 typedef struct { menuframework_s menu; menubitmap_s item_again; menubitmap_s item_next; menubitmap_s item_menu; int phase; int ignoreKeysTime; int starttime; int scoreboardtime; int serverId; int clientNums[MAX_SCOREBOARD_CLIENTS]; int ranks[MAX_SCOREBOARD_CLIENTS]; int scores[MAX_SCOREBOARD_CLIENTS]; char placeNames[3][64]; int level; int numClients; int won; int numAwards; int awardsEarned[6]; int awardsLevels[6]; qboolean playedSound[6]; int lastTier; sfxHandle_t winnerSound; } postgameMenuInfo_t; static postgameMenuInfo_t postgameMenuInfo; static char arenainfo[MAX_INFO_VALUE]; char *ui_medalNames[] = {"Accuracy", "Impressive", "Excellent", "Gauntlet", "Frags", "Perfect"}; char *ui_medalPicNames[] = { "menu/medals/medal_accuracy", "menu/medals/medal_impressive", "menu/medals/medal_excellent", "menu/medals/medal_gauntlet", "menu/medals/medal_frags", "menu/medals/medal_victory" }; char *ui_medalSounds[] = { "sound/feedback/accuracy.wav", "sound/feedback/impressive_a.wav", "sound/feedback/excellent_a.wav", "sound/feedback/gauntlet.wav", "sound/feedback/frags.wav", "sound/feedback/perfect.wav" }; /* ================= UI_SPPostgameMenu_AgainEvent ================= */ static void UI_SPPostgameMenu_AgainEvent( void* ptr, int event ) { if (event != QM_ACTIVATED) { return; } UI_PopMenu(); trap_Cmd_ExecuteText( EXEC_APPEND, "map_restart 0\n" ); } /* ================= UI_SPPostgameMenu_NextEvent ================= */ static void UI_SPPostgameMenu_NextEvent( void* ptr, int event ) { int currentSet; int levelSet; int level; int currentLevel; const char *arenaInfo; if (event != QM_ACTIVATED) { return; } UI_PopMenu(); // handle specially if we just won the training map if( postgameMenuInfo.won == 0 ) { level = 0; } else { level = postgameMenuInfo.level + 1; } levelSet = level / ARENAS_PER_TIER; currentLevel = UI_GetCurrentGame(); if( currentLevel == -1 ) { currentLevel = postgameMenuInfo.level; } currentSet = currentLevel / ARENAS_PER_TIER; if( levelSet > currentSet || levelSet == UI_GetNumSPTiers() ) { level = currentLevel; } arenaInfo = UI_GetArenaInfoByNumber( level ); if ( !arenaInfo ) { return; } UI_SPArena_Start( arenaInfo ); } /* ================= UI_SPPostgameMenu_MenuEvent ================= */ static void UI_SPPostgameMenu_MenuEvent( void* ptr, int event ) { if (event != QM_ACTIVATED) { return; } UI_PopMenu(); trap_Cvar_Set( "nextmap", "" ); trap_Cmd_ExecuteText( EXEC_APPEND, "disconnect; levelselect\n" ); } /* ================= UI_SPPostgameMenu_MenuKey ================= */ static sfxHandle_t UI_SPPostgameMenu_MenuKey( int key ) { if ( uis.realtime < postgameMenuInfo.ignoreKeysTime ) { return 0; } if( postgameMenuInfo.phase == 1 ) { trap_Cmd_ExecuteText( EXEC_APPEND, "abort_podium\n" ); postgameMenuInfo.phase = 2; postgameMenuInfo.starttime = uis.realtime; postgameMenuInfo.ignoreKeysTime = uis.realtime + 250; return 0; } if( postgameMenuInfo.phase == 2 ) { postgameMenuInfo.phase = 3; postgameMenuInfo.starttime = uis.realtime; postgameMenuInfo.ignoreKeysTime = uis.realtime + 250; return 0; } if( key == K_ESCAPE || key == K_MOUSE2 ) { return 0; } return Menu_DefaultKey( &postgameMenuInfo.menu, key ); } static int medalLocations[6] = {144, 448, 88, 504, 32, 560}; static void UI_SPPostgameMenu_DrawAwardsMedals( int max ) { int n; int medal; int amount; int x, y; char buf[16]; for( n = 0; n < max; n++ ) { x = medalLocations[n]; y = 64; medal = postgameMenuInfo.awardsEarned[n]; amount = postgameMenuInfo.awardsLevels[n]; UI_DrawNamedPic( x, y, 48, 48, ui_medalPicNames[medal] ); if( medal == AWARD_ACCURACY ) { Com_sprintf( buf, sizeof(buf), "%i%%", amount ); } else { if( amount == 1 ) { continue; } Com_sprintf( buf, sizeof(buf), "%i", amount ); } UI_DrawString( x + 24, y + 52, buf, UI_CENTER, color_yellow ); } } static void UI_SPPostgameMenu_DrawAwardsPresentation( int timer ) { int awardNum; int atimer; vec4_t color; awardNum = timer / AWARD_PRESENTATION_TIME; atimer = timer % AWARD_PRESENTATION_TIME; color[0] = color[1] = color[2] = 1.0f; color[3] = (float)( AWARD_PRESENTATION_TIME - atimer ) / (float)AWARD_PRESENTATION_TIME; UI_DrawProportionalString( 320, 64, ui_medalNames[postgameMenuInfo.awardsEarned[awardNum]], UI_CENTER, color ); UI_SPPostgameMenu_DrawAwardsMedals( awardNum + 1 ); if( !postgameMenuInfo.playedSound[awardNum] ) { postgameMenuInfo.playedSound[awardNum] = qtrue; trap_S_StartLocalSound( trap_S_RegisterSound( ui_medalSounds[postgameMenuInfo.awardsEarned[awardNum]], qfalse ), CHAN_ANNOUNCER ); } } /* ================= UI_SPPostgameMenu_MenuDrawScoreLine ================= */ static void UI_SPPostgameMenu_MenuDrawScoreLine( int n, int y ) { int rank; char name[64]; char info[MAX_INFO_STRING]; if( n > (postgameMenuInfo.numClients + 1) ) { n -= (postgameMenuInfo.numClients + 2); } if( n >= postgameMenuInfo.numClients ) { return; } rank = postgameMenuInfo.ranks[n]; if( rank & RANK_TIED_FLAG ) { UI_DrawString( 640 - 31 * SMALLCHAR_WIDTH, y, "(tie)", UI_LEFT|UI_SMALLFONT, color_white ); rank &= ~RANK_TIED_FLAG; } trap_GetConfigString( CS_PLAYERS + postgameMenuInfo.clientNums[n], info, MAX_INFO_STRING ); Q_strncpyz( name, Info_ValueForKey( info, "n" ), sizeof(name) ); Q_CleanStr( name ); UI_DrawString( 640 - 25 * SMALLCHAR_WIDTH, y, va( "#%i: %-16s %2i", rank + 1, name, postgameMenuInfo.scores[n] ), UI_LEFT|UI_SMALLFONT, color_white ); } /* ================= UI_SPPostgameMenu_MenuDraw ================= */ static void UI_SPPostgameMenu_MenuDraw( void ) { int timer; int serverId; int n; char info[MAX_INFO_STRING]; trap_GetConfigString( CS_SYSTEMINFO, info, sizeof(info) ); serverId = atoi( Info_ValueForKey( info, "sv_serverid" ) ); if( serverId != postgameMenuInfo.serverId ) { UI_PopMenu(); return; } // phase 1 if ( postgameMenuInfo.numClients > 2 ) { UI_DrawProportionalString( 510, 480 - 64 - PROP_HEIGHT, postgameMenuInfo.placeNames[2], UI_CENTER, color_white ); } UI_DrawProportionalString( 130, 480 - 64 - PROP_HEIGHT, postgameMenuInfo.placeNames[1], UI_CENTER, color_white ); UI_DrawProportionalString( 320, 480 - 64 - 2 * PROP_HEIGHT, postgameMenuInfo.placeNames[0], UI_CENTER, color_white ); if( postgameMenuInfo.phase == 1 ) { timer = uis.realtime - postgameMenuInfo.starttime; if( timer >= 1000 && postgameMenuInfo.winnerSound ) { trap_S_StartLocalSound( postgameMenuInfo.winnerSound, CHAN_ANNOUNCER ); postgameMenuInfo.winnerSound = 0; } if( timer < 5000 ) { return; } postgameMenuInfo.phase = 2; postgameMenuInfo.starttime = uis.realtime; } // phase 2 if( postgameMenuInfo.phase == 2 ) { timer = uis.realtime - postgameMenuInfo.starttime; if( timer >= ( postgameMenuInfo.numAwards * AWARD_PRESENTATION_TIME ) ) { if( timer < 5000 ) { return; } postgameMenuInfo.phase = 3; postgameMenuInfo.starttime = uis.realtime; } else { UI_SPPostgameMenu_DrawAwardsPresentation( timer ); } } // phase 3 if( postgameMenuInfo.phase == 3 ) { if( uis.demoversion ) { if( postgameMenuInfo.won == 1 && UI_ShowTierVideo( 8 )) { trap_Cvar_Set( "nextmap", "" ); trap_Cmd_ExecuteText( EXEC_APPEND, "disconnect; cinematic demoEnd.RoQ\n" ); return; } } else if( postgameMenuInfo.won > -1 && UI_ShowTierVideo( postgameMenuInfo.won + 1 )) { if( postgameMenuInfo.won == postgameMenuInfo.lastTier ) { trap_Cvar_Set( "nextmap", "" ); trap_Cmd_ExecuteText( EXEC_APPEND, "disconnect; cinematic end.RoQ\n" ); return; } trap_Cvar_SetValue( "ui_spSelection", postgameMenuInfo.won * ARENAS_PER_TIER ); trap_Cvar_Set( "nextmap", "levelselect" ); trap_Cmd_ExecuteText( EXEC_APPEND, va( "disconnect; cinematic tier%i.RoQ\n", postgameMenuInfo.won + 1 ) ); return; } postgameMenuInfo.item_again.generic.flags &= ~QMF_INACTIVE; postgameMenuInfo.item_next.generic.flags &= ~QMF_INACTIVE; postgameMenuInfo.item_menu.generic.flags &= ~QMF_INACTIVE; UI_SPPostgameMenu_DrawAwardsMedals( postgameMenuInfo.numAwards ); Menu_Draw( &postgameMenuInfo.menu ); } // draw the scoreboard if( !trap_Cvar_VariableValue( "ui_spScoreboard" ) ) { return; } timer = uis.realtime - postgameMenuInfo.scoreboardtime; if( postgameMenuInfo.numClients <= 3 ) { n = 0; } else { n = timer / 1500 % (postgameMenuInfo.numClients + 2); } UI_SPPostgameMenu_MenuDrawScoreLine( n, 0 ); UI_SPPostgameMenu_MenuDrawScoreLine( n + 1, 0 + SMALLCHAR_HEIGHT ); UI_SPPostgameMenu_MenuDrawScoreLine( n + 2, 0 + 2 * SMALLCHAR_HEIGHT ); } /* ================= UI_SPPostgameMenu_Cache ================= */ void UI_SPPostgameMenu_Cache( void ) { int n; qboolean buildscript; buildscript = trap_Cvar_VariableValue("com_buildscript"); trap_R_RegisterShaderNoMip( ART_MENU0 ); trap_R_RegisterShaderNoMip( ART_MENU1 ); trap_R_RegisterShaderNoMip( ART_REPLAY0 ); trap_R_RegisterShaderNoMip( ART_REPLAY1 ); trap_R_RegisterShaderNoMip( ART_NEXT0 ); trap_R_RegisterShaderNoMip( ART_NEXT1 ); for( n = 0; n < 6; n++ ) { trap_R_RegisterShaderNoMip( ui_medalPicNames[n] ); trap_S_RegisterSound( ui_medalSounds[n], qfalse ); } if( buildscript ) { trap_S_RegisterSound( "music/loss.wav", qfalse ); trap_S_RegisterSound( "music/win.wav", qfalse ); trap_S_RegisterSound( "sound/player/announce/youwin.wav", qfalse ); } } /* ================= UI_SPPostgameMenu_Init ================= */ static void UI_SPPostgameMenu_Init( void ) { postgameMenuInfo.menu.wrapAround = qtrue; postgameMenuInfo.menu.key = UI_SPPostgameMenu_MenuKey; postgameMenuInfo.menu.draw = UI_SPPostgameMenu_MenuDraw; postgameMenuInfo.ignoreKeysTime = uis.realtime + 1500; UI_SPPostgameMenu_Cache(); postgameMenuInfo.item_menu.generic.type = MTYPE_BITMAP; postgameMenuInfo.item_menu.generic.name = ART_MENU0; postgameMenuInfo.item_menu.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_INACTIVE; postgameMenuInfo.item_menu.generic.x = 0; postgameMenuInfo.item_menu.generic.y = 480-64; postgameMenuInfo.item_menu.generic.callback = UI_SPPostgameMenu_MenuEvent; postgameMenuInfo.item_menu.generic.id = ID_MENU; postgameMenuInfo.item_menu.width = 128; postgameMenuInfo.item_menu.height = 64; postgameMenuInfo.item_menu.focuspic = ART_MENU1; postgameMenuInfo.item_again.generic.type = MTYPE_BITMAP; postgameMenuInfo.item_again.generic.name = ART_REPLAY0; postgameMenuInfo.item_again.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS|QMF_INACTIVE; postgameMenuInfo.item_again.generic.x = 320; postgameMenuInfo.item_again.generic.y = 480-64; postgameMenuInfo.item_again.generic.callback = UI_SPPostgameMenu_AgainEvent; postgameMenuInfo.item_again.generic.id = ID_AGAIN; postgameMenuInfo.item_again.width = 128; postgameMenuInfo.item_again.height = 64; postgameMenuInfo.item_again.focuspic = ART_REPLAY1; postgameMenuInfo.item_next.generic.type = MTYPE_BITMAP; postgameMenuInfo.item_next.generic.name = ART_NEXT0; postgameMenuInfo.item_next.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_INACTIVE; postgameMenuInfo.item_next.generic.x = 640; postgameMenuInfo.item_next.generic.y = 480-64; postgameMenuInfo.item_next.generic.callback = UI_SPPostgameMenu_NextEvent; postgameMenuInfo.item_next.generic.id = ID_NEXT; postgameMenuInfo.item_next.width = 128; postgameMenuInfo.item_next.height = 64; postgameMenuInfo.item_next.focuspic = ART_NEXT1; Menu_AddItem( &postgameMenuInfo.menu, ( void * )&postgameMenuInfo.item_menu ); Menu_AddItem( &postgameMenuInfo.menu, ( void * )&postgameMenuInfo.item_again ); Menu_AddItem( &postgameMenuInfo.menu, ( void * )&postgameMenuInfo.item_next ); } static void Prepname( int index ) { int len; char name[64]; char info[MAX_INFO_STRING]; trap_GetConfigString( CS_PLAYERS + postgameMenuInfo.clientNums[index], info, MAX_INFO_STRING ); Q_strncpyz( name, Info_ValueForKey( info, "n" ), sizeof(name) ); Q_CleanStr( name ); len = strlen( name ); while( len && UI_ProportionalStringWidth( name ) > 256 ) { len--; name[len] = 0; } Q_strncpyz( postgameMenuInfo.placeNames[index], name, sizeof(postgameMenuInfo.placeNames[index]) ); } /* ================= UI_SPPostgameMenu_f ================= */ void UI_SPPostgameMenu_f( void ) { int playerGameRank; int playerClientNum; int n; int oldFrags, newFrags; const char *arena; int awardValues[6]; char map[MAX_QPATH]; char info[MAX_INFO_STRING]; memset( &postgameMenuInfo, 0, sizeof(postgameMenuInfo) ); trap_GetConfigString( CS_SYSTEMINFO, info, sizeof(info) ); postgameMenuInfo.serverId = atoi( Info_ValueForKey( info, "sv_serverid" ) ); trap_GetConfigString( CS_SERVERINFO, info, sizeof(info) ); Q_strncpyz( map, Info_ValueForKey( info, "mapname" ), sizeof(map) ); arena = UI_GetArenaInfoByMap( map ); if ( !arena ) { return; } Q_strncpyz( arenainfo, arena, sizeof(arenainfo) ); postgameMenuInfo.level = atoi( Info_ValueForKey( arenainfo, "num" ) ); postgameMenuInfo.numClients = atoi( UI_Argv( 1 ) ); playerClientNum = atoi( UI_Argv( 2 ) ); playerGameRank = 8; // in case they ended game as a spectator if( postgameMenuInfo.numClients > MAX_SCOREBOARD_CLIENTS ) { postgameMenuInfo.numClients = MAX_SCOREBOARD_CLIENTS; } for( n = 0; n < postgameMenuInfo.numClients; n++ ) { postgameMenuInfo.clientNums[n] = atoi( UI_Argv( 8 + n * 3 + 1 ) ); postgameMenuInfo.ranks[n] = atoi( UI_Argv( 8 + n * 3 + 2 ) ); postgameMenuInfo.scores[n] = atoi( UI_Argv( 8 + n * 3 + 3 ) ); if( postgameMenuInfo.clientNums[n] == playerClientNum ) { playerGameRank = (postgameMenuInfo.ranks[n] & ~RANK_TIED_FLAG) + 1; } } UI_SetBestScore( postgameMenuInfo.level, playerGameRank ); // process award stats and prepare presentation data awardValues[AWARD_ACCURACY] = atoi( UI_Argv( 3 ) ); awardValues[AWARD_IMPRESSIVE] = atoi( UI_Argv( 4 ) ); awardValues[AWARD_EXCELLENT] = atoi( UI_Argv( 5 ) ); awardValues[AWARD_GAUNTLET] = atoi( UI_Argv( 6 ) ); awardValues[AWARD_FRAGS] = atoi( UI_Argv( 7 ) ); awardValues[AWARD_PERFECT] = atoi( UI_Argv( 8 ) ); postgameMenuInfo.numAwards = 0; if( awardValues[AWARD_ACCURACY] >= 50 ) { UI_LogAwardData( AWARD_ACCURACY, 1 ); postgameMenuInfo.awardsEarned[postgameMenuInfo.numAwards] = AWARD_ACCURACY; postgameMenuInfo.awardsLevels[postgameMenuInfo.numAwards] = awardValues[AWARD_ACCURACY]; postgameMenuInfo.numAwards++; } if( awardValues[AWARD_IMPRESSIVE] ) { UI_LogAwardData( AWARD_IMPRESSIVE, awardValues[AWARD_IMPRESSIVE] ); postgameMenuInfo.awardsEarned[postgameMenuInfo.numAwards] = AWARD_IMPRESSIVE; postgameMenuInfo.awardsLevels[postgameMenuInfo.numAwards] = awardValues[AWARD_IMPRESSIVE]; postgameMenuInfo.numAwards++; } if( awardValues[AWARD_EXCELLENT] ) { UI_LogAwardData( AWARD_EXCELLENT, awardValues[AWARD_EXCELLENT] ); postgameMenuInfo.awardsEarned[postgameMenuInfo.numAwards] = AWARD_EXCELLENT; postgameMenuInfo.awardsLevels[postgameMenuInfo.numAwards] = awardValues[AWARD_EXCELLENT]; postgameMenuInfo.numAwards++; } if( awardValues[AWARD_GAUNTLET] ) { UI_LogAwardData( AWARD_GAUNTLET, awardValues[AWARD_GAUNTLET] ); postgameMenuInfo.awardsEarned[postgameMenuInfo.numAwards] = AWARD_GAUNTLET; postgameMenuInfo.awardsLevels[postgameMenuInfo.numAwards] = awardValues[AWARD_GAUNTLET]; postgameMenuInfo.numAwards++; } oldFrags = UI_GetAwardLevel( AWARD_FRAGS ) / 100; UI_LogAwardData( AWARD_FRAGS, awardValues[AWARD_FRAGS] ); newFrags = UI_GetAwardLevel( AWARD_FRAGS ) / 100; if( newFrags > oldFrags ) { postgameMenuInfo.awardsEarned[postgameMenuInfo.numAwards] = AWARD_FRAGS; postgameMenuInfo.awardsLevels[postgameMenuInfo.numAwards] = newFrags * 100; postgameMenuInfo.numAwards++; } if( awardValues[AWARD_PERFECT] ) { UI_LogAwardData( AWARD_PERFECT, 1 ); postgameMenuInfo.awardsEarned[postgameMenuInfo.numAwards] = AWARD_PERFECT; postgameMenuInfo.awardsLevels[postgameMenuInfo.numAwards] = 1; postgameMenuInfo.numAwards++; } if ( playerGameRank == 1 ) { postgameMenuInfo.won = UI_TierCompleted( postgameMenuInfo.level ); } else { postgameMenuInfo.won = -1; } postgameMenuInfo.starttime = uis.realtime; postgameMenuInfo.scoreboardtime = uis.realtime; trap_Key_SetCatcher( KEYCATCH_UI ); uis.menusp = 0; UI_SPPostgameMenu_Init(); UI_PushMenu( &postgameMenuInfo.menu ); if ( playerGameRank == 1 ) { Menu_SetCursorToItem( &postgameMenuInfo.menu, &postgameMenuInfo.item_next ); } else { Menu_SetCursorToItem( &postgameMenuInfo.menu, &postgameMenuInfo.item_again ); } Prepname( 0 ); Prepname( 1 ); Prepname( 2 ); if ( playerGameRank != 1 ) { postgameMenuInfo.winnerSound = trap_S_RegisterSound( va( "sound/player/announce/%s_wins.wav", postgameMenuInfo.placeNames[0] ), qfalse ); trap_Cmd_ExecuteText( EXEC_APPEND, "music music/loss\n" ); } else { postgameMenuInfo.winnerSound = trap_S_RegisterSound( "sound/player/announce/youwin.wav", qfalse ); trap_Cmd_ExecuteText( EXEC_APPEND, "music music/win\n" ); } postgameMenuInfo.phase = 1; postgameMenuInfo.lastTier = UI_GetNumSPTiers(); if ( UI_GetSpecialArenaInfo( "final" ) ) { postgameMenuInfo.lastTier++; } }
0
0.887909
1
0.887909
game-dev
MEDIA
0.682021
game-dev
0.870835
1
0.870835
Sandern/lambdawars
2,100
src/game/server/point_event_proxy.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: An entity for creating instructor hints entirely with map logic // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "baseentity.h" #include "world.h" #ifdef INFESTED_DLL #include "asw_marine.h" #include "asw_player.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CPointEventProxy : public CPointEntity { public: DECLARE_CLASS( CPointEventProxy, CPointEntity ); DECLARE_DATADESC(); private: void InputGenerateEvent( inputdata_t &inputdata ); string_t m_iszEventName; bool m_bActivatorAsUserID; }; LINK_ENTITY_TO_CLASS( point_event_proxy, CPointEventProxy ); BEGIN_DATADESC( CPointEventProxy ) DEFINE_KEYFIELD( m_iszEventName, FIELD_STRING, "EventName" ), DEFINE_KEYFIELD( m_bActivatorAsUserID, FIELD_BOOLEAN, "ActivatorAsUserID" ), DEFINE_INPUTFUNC( FIELD_VOID, "GenerateEvent", InputGenerateEvent ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: Input handler for showing the message and/or playing the sound. //----------------------------------------------------------------------------- void CPointEventProxy::InputGenerateEvent( inputdata_t &inputdata ) { IGameEvent * event = gameeventmanager->CreateEvent( m_iszEventName.ToCStr() ); if ( event ) { CBasePlayer *pActivator = NULL; #ifdef INFESTED_DLL CASW_Marine *pMarine = dynamic_cast< CASW_Marine* >( inputdata.pActivator ); if ( pMarine ) { pActivator = pMarine->GetCommander(); } #else pActivator = dynamic_cast< CBasePlayer* >( inputdata.pActivator ); #endif if ( m_bActivatorAsUserID ) { event->SetInt( "userid", ( pActivator ? pActivator->GetUserID() : 0 ) ); } gameeventmanager->FireEvent( event ); } }
0
0.945902
1
0.945902
game-dev
MEDIA
0.98313
game-dev
0.889865
1
0.889865
neostarfall/neostarfall
45,172
lua/starfall/libs_sv/entities.lua
-- Global to all starfalls local checkluatype = SF.CheckLuaType local registerprivilege = SF.Permissions.registerPrivilege local haspermission = SF.Permissions.hasAccess local dgetmeta = debug.getmetatable local ENT_META, NPC_META, PHYS_META, PLY_META, VEH_META, WEP_META = FindMetaTable("Entity"), FindMetaTable("NPC"), FindMetaTable("PhysObj"), FindMetaTable("Player"), FindMetaTable("Vehicle"), FindMetaTable("Weapon") local isentity = isentity local Ent_AddCallback, Ent_GetTable, Ent_IsScripted, Ent_IsValid, Ent_RemoveCallback = ENT_META.AddCallback, ENT_META.GetTable, ENT_META.IsScripted, ENT_META.IsValid, ENT_META.RemoveCallback local Ply_InVehicle = PLY_META.InVehicle -- Register privileges registerprivilege( "entities.applyDamage", "Apply damage", "Allows the user to apply damage to an entity", { entities = {} } ) registerprivilege( "entities.applyForce", "Apply force", "Allows the user to apply force to an entity", { entities = {} } ) registerprivilege( "entities.setPos", "Set Position", "Allows the user to teleport an entity to another location", { entities = {} } ) registerprivilege( "entities.setAngles", "Set Angles", "Allows the user to rotate an entity to another orientation", { entities = {} } ) registerprivilege( "entities.setEyeAngles", "Set eye angles", "Allows the user to rotate the view of an entity to another orientation", { entities = {} } ) registerprivilege( "entities.setVelocity", "Set Velocity", "Allows the user to change the velocity of an entity", { entities = {} } ) registerprivilege( "entities.setSolid", "Set Solid", "Allows the user to change the solidity of an entity", { entities = {} } ) registerprivilege( "entities.setContents", "Set Contents", "Allows the user to change the contents flag of an entity", { entities = {} } ) registerprivilege("entities.setMass", "Set Mass", "Allows the user to change the mass of an entity", { entities = {} }) registerprivilege( "entities.setInertia", "Set Inertia", "Allows the user to change the inertia of an entity", { entities = {} } ) registerprivilege( "entities.enableGravity", "Enable gravity", "Allows the user to change whether an entity is affected by gravity", { entities = {} } ) registerprivilege( "entities.enableMotion", "Set Motion", "Allows the user to disable an entity's motion", { entities = {} } ) registerprivilege( "entities.enableDrag", "Set Drag", "Allows the user to disable an entity's air resistance and change it's coefficient", { entities = {} } ) registerprivilege( "entities.setDamping", "Set Damping", "Allows the user to change entity's air friction damping", { entities = {} } ) registerprivilege("entities.remove", "Remove", "Allows the user to remove entities", { entities = {} }) registerprivilege("entities.ignite", "Ignite", "Allows the user to ignite entities", { entities = {} }) registerprivilege( "entities.canTool", "CanTool", "Whether or not the user can use the toolgun on the entity", { entities = {} } ) registerprivilege("entities.use", "Use", "Whether or not the user can use the entity", { entities = {} }) registerprivilege( "entities.getTable", "GetTable", "Allows the user to get an entity's table", { entities = {}, usergroups = { default = 1 } } ) local function table_find(tbl, val) for i = 1, #tbl do if tbl[i] == val then return i end end end local collisionListenerLimit = SF.LimitObject( "collisionlistener", "collisionlistner", 128, "The number of concurrent neostarfall collision listeners" ) local base_physicscollide SF.GlobalCollisionListeners = { __index = { create = function(self, ent) local listenertable = {} local ent_tbl = Ent_GetTable(ent) local queue = {} local nqueue = 0 local function collisionQueueProcess() if Ent_IsValid(ent) then for _, listener in ipairs(listenertable) do local instance = listener.instance for i = 1, nqueue do listener:run(instance, SF.StructWrapper(instance, queue[i], "CollisionData")) end end end for i = 1, nqueue do queue[i] = nil end nqueue = 0 end local function collisionQueueCallback(ent, data) nqueue = nqueue + 1 queue[nqueue] = data if nqueue == 1 then timer.Simple(0, collisionQueueProcess) end end if Ent_IsScripted(ent) then local oldPhysicsCollide = ent_tbl.PhysicsCollide or base_physicscollide ent_tbl.SF_OldPhysicsCollide = oldPhysicsCollide function ent_tbl:PhysicsCollide(data, phys) oldPhysicsCollide(self, data, phys) collisionQueueCallback(self, data) end else ent_tbl.SF_CollisionCallback = Ent_AddCallback(ent, "PhysicsCollide", collisionQueueCallback) end SF.CallOnRemove(ent, "RemoveCollisionListeners", function(e) self:destroy(e) end) self.listeners[ent] = listenertable return listenertable end, destroy = function(self, ent) local entlisteners = self.listeners[ent] if entlisteners == nil then return end self.listeners[ent] = nil for _, listener in ipairs(entlisteners) do listener.manager:free(ent) end if Ent_IsValid(ent) then local ent_tbl = Ent_GetTable(ent) local oldPhysicsCollide = ent_tbl.SF_OldPhysicsCollide if oldPhysicsCollide then ent_tbl.PhysicsCollide = oldPhysicsCollide else Ent_RemoveCallback(ent, "PhysicsCollide", ent_tbl.SF_CollisionCallback) end SF.RemoveCallOnRemove(ent, "RemoveCollisionListeners") end end, add = function(self, ent, listener) local entlisteners = self.listeners[ent] if entlisteners == nil then entlisteners = self:create(ent) elseif table_find(entlisteners, listener) then return end entlisteners[#entlisteners + 1] = listener end, remove = function(self, ent, listener) local entlisteners = self.listeners[ent] if entlisteners == nil then return end local i = table_find(entlisteners, listener) if i == nil then return end entlisteners[i] = entlisteners[#entlisteners] entlisteners[#entlisteners] = nil if entlisteners[1] == nil then self:destroy(ent) end end, }, __call = function(p) return setmetatable({ listeners = {}, }, p) end, } setmetatable(SF.GlobalCollisionListeners, SF.GlobalCollisionListeners) local globalListeners = SF.GlobalCollisionListeners() SF.InstanceCollisionListeners = { __index = { add = function(self, ent, name, func) local created = false local listener = self.hooksPerEnt[ent] if listener == nil then collisionListenerLimit:checkuse(self.instance.player, 1) listener = SF.HookTable() listener.manager = self listener.instance = self.instance self.hooksPerEnt[ent] = listener globalListeners:add(ent, listener) created = true elseif not listener:exists(name) then collisionListenerLimit:checkuse(self.instance.player, 1) created = true end listener:add(name, func) if created then collisionListenerLimit:free(self.instance.player, -1) end end, remove = function(self, ent, name) local listener = self.hooksPerEnt[ent] if listener and listener:exists(name) then listener:remove(name) collisionListenerLimit:free(self.instance.player, 1) if listener:isEmpty() then self.hooksPerEnt[ent] = nil globalListeners:remove(ent, listener) end end end, free = function(self, ent) local listener = self.hooksPerEnt[ent] if listener then collisionListenerLimit:free(self.instance.player, listener.n) self.hooksPerEnt[ent] = nil end end, destroy = function(self) for ent, listener in pairs(self.hooksPerEnt) do collisionListenerLimit:free(self.instance.player, listener.n) self.hooksPerEnt[ent] = nil globalListeners:remove(ent, listener) end end, }, __call = function(p, instance) return setmetatable({ instance = instance, hooksPerEnt = {}, }, p) end, } setmetatable(SF.InstanceCollisionListeners, SF.InstanceCollisionListeners) local function checknumber(n) if n < -1e12 or n > 1e12 or n ~= n then SF.Throw("Input number too large or NAN", 3) end end local function checkvector(v) if v[1] < -1e12 or v[1] > 1e12 or v[1] ~= v[1] or v[2] < -1e12 or v[2] > 1e12 or v[2] ~= v[2] or v[3] < -1e12 or v[3] > 1e12 or v[3] ~= v[3] then SF.Throw("Input vector too large or NAN", 3) end end return function(instance) local checkpermission = instance.player ~= SF.Superuser and SF.Permissions.check or function() end local Ent_AddCallback, Ent_DrawShadow, Ent_Extinguish, Ent_Fire, Ent_GetChildren, Ent_GetClass, Ent_GetCreationID, Ent_GetForward, Ent_GetFriction, Ent_GetMoveType, Ent_GetParent, Ent_GetPhysicsObject, Ent_GetRight, Ent_GetTable, Ent_GetUp, Ent_GetVar, Ent_Ignite, Ent_IsConstraint, Ent_IsPlayer, Ent_IsPlayerHolding, Ent_IsScripted, Ent_IsValid, Ent_IsVehicle, Ent_IsWorld, Ent_OBBMaxs, Ent_OBBMins, Ent_PhysicsInit, Ent_PhysicsInitSphere, Ent_Remove, Ent_RemoveCallback, Ent_SetAngles, Ent_SetCollisionBounds, Ent_SetCollisionGroup, Ent_SetElasticity, Ent_SetFriction, Ent_SetLightingOriginEntity, Ent_SetLocalAngles, Ent_SetLocalPos, Ent_SetMoveType, Ent_SetNotSolid, Ent_SetPos, Ent_SetSolid, Ent_SetVelocity, Ent_TestPVS, Ent_Use = ENT_META.AddCallback, ENT_META.DrawShadow, ENT_META.Extinguish, ENT_META.Fire, ENT_META.GetChildren, ENT_META.GetClass, ENT_META.GetCreationID, ENT_META.GetForward, ENT_META.GetFriction, ENT_META.GetMoveType, ENT_META.GetParent, ENT_META.GetPhysicsObject, ENT_META.GetRight, ENT_META.GetTable, ENT_META.GetUp, ENT_META.GetVar, ENT_META.Ignite, ENT_META.IsConstraint, ENT_META.IsPlayer, ENT_META.IsPlayerHolding, ENT_META.IsScripted, ENT_META.IsValid, ENT_META.IsVehicle, ENT_META.IsWorld, ENT_META.OBBMaxs, ENT_META.OBBMins, ENT_META.PhysicsInit, ENT_META.PhysicsInitSphere, ENT_META.Remove, ENT_META.RemoveCallback, ENT_META.SetAngles, ENT_META.SetCollisionBounds, ENT_META.SetCollisionGroup, ENT_META.SetElasticity, ENT_META.SetFriction, ENT_META.SetLightingOriginEntity, ENT_META.SetLocalAngles, ENT_META.SetLocalPos, ENT_META.SetMoveType, ENT_META.SetNotSolid, ENT_META.SetPos, ENT_META.SetSolid, ENT_META.SetVelocity, ENT_META.TestPVS, ENT_META.Use local function Ent_IsNPC(ent) return dgetmeta(ent) == NPC_META end local function Ent_IsPlayer(ent) return dgetmeta(ent) == PLY_META end local function Ent_IsVehicle(ent) return dgetmeta(ent) == VEH_META end local function Ent_IsWeapon(ent) return dgetmeta(ent) == WEP_META end local Phys_AddAngleVelocity, Phys_AddVelocity, Phys_ApplyForceCenter, Phys_ApplyForceOffset, Phys_ApplyTorqueCenter, Phys_EnableDrag, Phys_EnableGravity, Phys_EnableMotion, Phys_GetAngleVelocity, Phys_GetMass, Phys_GetMaterial, Phys_IsMoveable, Phys_IsValid, Phys_SetContents, Phys_SetInertia, Phys_SetMass, Phys_Wake = PHYS_META.AddAngleVelocity, PHYS_META.AddVelocity, PHYS_META.ApplyForceCenter, PHYS_META.ApplyForceOffset, PHYS_META.ApplyTorqueCenter, PHYS_META.EnableDrag, PHYS_META.EnableGravity, PHYS_META.EnableMotion, PHYS_META.GetAngleVelocity, PHYS_META.GetMass, PHYS_META.GetMaterial, PHYS_META.IsMoveable, PHYS_META.IsValid, PHYS_META.SetContents, PHYS_META.SetInertia, PHYS_META.SetMass, PHYS_META.Wake local owrap, ounwrap = instance.WrapObject, instance.UnwrapObject local ents_methods, ent_meta, ewrap, eunwrap = instance.Types.Entity.Methods, instance.Types.Entity, instance.Types.Entity.Wrap, instance.Types.Entity.Unwrap local ang_meta, awrap, aunwrap = instance.Types.Angle, instance.Types.Angle.Wrap, instance.Types.Angle.Unwrap local vec_meta, vwrap, vunwrap = instance.Types.Vector, instance.Types.Vector.Wrap, instance.Types.Vector.Unwrap local cunwrap = instance.Types.Color.Unwrap local collisionListeners = SF.InstanceCollisionListeners(instance) base_physicscollide = baseclass.Get("base_gmodentity").PhysicsCollide local getent local vunwrap1, vunwrap2, aunwrap1 instance:AddHook("initialize", function() getent = ent_meta.GetEntity vunwrap1, vunwrap2, aunwrap1 = vec_meta.QuickUnwrap1, vec_meta.QuickUnwrap2, ang_meta.QuickUnwrap1 end) instance:AddHook("deinitialize", function() collisionListeners:destroy() end) -- ------------------------- Methods ------------------------- -- --- Links starfall components to a starfall processor or vehicle. Screen can only connect to processor. HUD can connect to processor and vehicle. -- @param Entity? e Entity to link the component to, a vehicle or starfall for huds, or a starfall for screens. nil to clear links. function ents_methods:linkComponent(e) local ent = getent(self) checkpermission(instance, ent, "entities.canTool") if e then local link = getent(e) checkpermission(instance, link, "entities.canTool") if Ent_GetClass(link) == "starfall_processor" and (Ent_GetClass(ent) == "starfall_screen" or Ent_GetClass(ent) == "starfall_hud") then SF.LinkEnt(ent, link) elseif Ent_IsVehicle(link) and Ent_GetClass(ent) == "starfall_hud" then ent:LinkVehicle(link) else SF.Throw("Invalid Link Entity", 2) end else if Ent_GetClass(ent) == "starfall_screen" then SF.LinkEnt(ent, nil) elseif Ent_GetClass(ent) == "starfall_hud" then SF.LinkEnt(ent, nil) ent:LinkVehicle(nil) else SF.Throw("Invalid Link Entity", 2) end end end --- Sets a component's ability to lock a player's controls -- @param boolean enable Whether the component will lock the player's controls when used function ents_methods:setComponentLocksControls(enable) local ent = getent(self) checkluatype(enable, TYPE_BOOL) checkpermission(instance, ent, "entities.canTool") if Ent_GetClass(ent) == "starfall_screen" or Ent_GetClass(ent) == "starfall_hud" then Ent_GetTable(ent).locksControls = enable else SF.Throw("Entity must be a starfall_screen or starfall_hud", 2) end end --- Applies damage to an entity -- @param number amt Damage amount -- @param Entity? attacker Damage attacker. Defaults to chip owner -- @param Entity? inflictor Damage inflictor -- @param number? dmgtype The damage type number enum -- @param Vector? pos The position of the damage function ents_methods:applyDamage(amt, attacker, inflictor, dmgtype, pos) local ent = getent(self) checkluatype(amt, TYPE_NUMBER) checkpermission(instance, ent, "entities.applyDamage") local dmg = DamageInfo() dmg:SetDamage(amt) if attacker ~= nil then dmg:SetAttacker(getent(attacker)) else dmg:SetAttacker(instance.player) end if inflictor ~= nil then dmg:SetInflictor(getent(inflictor)) end if dmgtype ~= nil then checkluatype(dmgtype, TYPE_NUMBER) dmg:SetDamageType(dmgtype) end if pos ~= nil then pos = vunwrap1(pos) checkvector(pos) dmg:SetDamagePosition(pos) end ent:TakeDamageInfo(dmg) end --- Sets a custom prop's physics simulation forces. Thrusters and balloons use this. -- This takes precedence over Entity.setCustomPropShadowForce and cannot be used together -- @param Vector ang Angular Force (Torque) -- @param Vector lin Linear Force -- @param number mode The physics mode to use. 0 = Off (disables custom physics entirely), 1 = Local acceleration, 2 = Local force, 3 = Global Acceleration, 4 = Global force function ents_methods:setCustomPropForces(ang, lin, mode) local ent = getent(self) local ent_tbl = Ent_GetTable(ent) if Ent_GetClass(ent) ~= "starfall_prop" then SF.Throw("The entity isn't a custom prop", 2) end checkpermission(instance, ent, "entities.applyForce") if mode == 0 then ent_tbl.EnableCustomPhysics(ent, false) elseif mode == 1 or mode == 2 or mode == 3 or mode == 4 then ang = vunwrap1(ang) checkvector(ang) lin = vunwrap2(lin) checkvector(lin) ent_tbl.customForceMode = mode ent_tbl.customForceLinear:Set(lin) ent_tbl.customForceAngular:Set(ang) ent_tbl.EnableCustomPhysics(ent, 1) else SF.Throw("Invalid mode, see the SIM enum", 2) end end --- Sets a custom prop's shadow forces, moving the entity to the desired position and angles -- This gets overriden by Entity.setCustomPropForces and cannot be used together -- See available parameters here: https://wiki.facepunch.com/gmod/PhysObj:ComputeShadowControl -- @param table|boolean data Shadow physics data, excluding 'deltatime'. 'teleportdistance' higher than 0 requires 'entities.setPos'. Pass a falsy value to disable custom physics entirely function ents_methods:setCustomPropShadowForce(data) local ent = getent(self) local ent_tbl = Ent_GetTable(ent) if Ent_GetClass(ent) ~= "starfall_prop" then SF.Throw("The entity isn't a custom prop", 2) end checkpermission(instance, ent, "entities.applyForce") if data then local pos = vunwrap1(data.pos) checkvector(pos) local ang = aunwrap1(data.angle) checkvector(ang) checkluatype(data.teleportdistance, TYPE_NUMBER) if data.teleportdistance > 0 and not haspermission(instance, ent, "entities.setPos") then SF.Throw( "Shadow force property 'teleportdistance' higher than 0 requires 'entities.setPos' permission access", 2 ) end checkluatype(data.secondstoarrive, TYPE_NUMBER) if data.secondstoarrive < 1e-3 then SF.Throw("Shadow force property 'secondstoarrive' cannot be lower than 0.001", 2) end checkluatype(data.dampfactor, TYPE_NUMBER) if data.dampfactor > 1 or data.dampfactor < 0 then SF.Throw("Shadow force property 'dampfactor' cannot be higher than 1 or lower than 0", 2) end checkluatype(data.maxangular, TYPE_NUMBER) checkluatype(data.maxangulardamp, TYPE_NUMBER) checkluatype(data.maxspeed, TYPE_NUMBER) checkluatype(data.maxspeeddamp, TYPE_NUMBER) local customShadowForce = ent_tbl.customShadowForce customShadowForce.pos:Set(pos) customShadowForce.angle:Set(ang) customShadowForce.secondstoarrive = data.secondstoarrive customShadowForce.dampfactor = data.dampfactor customShadowForce.maxangular = data.maxangular customShadowForce.maxangulardamp = data.maxangulardamp customShadowForce.maxspeed = data.maxspeed customShadowForce.maxspeeddamp = data.maxspeeddamp customShadowForce.teleportdistance = data.teleportdistance ent_tbl.EnableCustomPhysics(ent, 2) else ent_tbl.EnableCustomPhysics(ent, false) end end --- Set the angular velocity of an object -- @param Vector angvel The local angvel vector to set function ents_methods:setAngleVelocity(angvel) local ent = getent(self) angvel = vunwrap1(angvel) checkvector(angvel) local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkpermission(instance, ent, "entities.applyForce") angvel:Sub(Phys_GetAngleVelocity(phys)) Phys_AddAngleVelocity(phys, angvel) end --- Applies a angular velocity to an object -- @param Vector angvel The local angvel vector to apply function ents_methods:addAngleVelocity(angvel) local ent = getent(self) angvel = vunwrap1(angvel) checkvector(angvel) local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkpermission(instance, ent, "entities.applyForce") Phys_AddAngleVelocity(phys, angvel) end --- Returns how much friction the entity has, default is 1 (100%) -- @return number friction function ents_methods:getFriction() return Ent_GetFriction(getent(self)) end --- Sets the entity's friction multiplier -- @param number friction function ents_methods:setFriction(friction) local ent = getent(self) checkpermission(instance, ent, "entities.canTool") checknumber(friction) Ent_SetFriction(ent, friction) end --- Sets the elasticity of the entity -- @param number elasticity function ents_methods:setElasticity(elasticity) local ent = getent(self) checkpermission(instance, ent, "entities.canTool") checknumber(elasticity) Ent_SetElasticity(ent, elasticity) end --- Applies linear force to the entity -- @param Vector vec The force vector function ents_methods:applyForceCenter(vec) local ent = getent(self) vec = vunwrap1(vec) checkvector(vec) local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkpermission(instance, ent, "entities.applyForce") Phys_ApplyForceCenter(phys, vec) end --- Applies linear force to the entity with an offset -- @param Vector force The force vector in world coordinates -- @param Vector position The force position in world coordinates function ents_methods:applyForceOffset(force, position) local ent = getent(self) force = vunwrap1(force) checkvector(force) position = vunwrap2(position) checkvector(position) local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkpermission(instance, ent, "entities.applyForce") Phys_ApplyForceOffset(phys, force, position) end --- Applies angular force to the entity (This function is garbage, use applyTorque instead) -- @param Angle ang The force angle function ents_methods:applyAngForce(ang) local ent = getent(self) ang = aunwrap1(ang) checkvector(ang) local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkpermission(instance, ent, "entities.applyForce") -- assign vectors local up = Ent_GetUp(ent) local left = Ent_GetRight(ent) * -1 local forward = Ent_GetForward(ent) -- apply pitch force if ang.p ~= 0 then local pitch = up * (ang.p * 0.5) Phys_ApplyForceOffset(phys, forward, pitch) Phys_ApplyForceOffset(phys, forward * -1, pitch * -1) end -- apply yaw force if ang.y ~= 0 then local yaw = forward * (ang.y * 0.5) Phys_ApplyForceOffset(phys, left, yaw) Phys_ApplyForceOffset(phys, left * -1, yaw * -1) end -- apply roll force if ang.r ~= 0 then local roll = left * (ang.r * 0.5) Phys_ApplyForceOffset(phys, up, roll) Phys_ApplyForceOffset(phys, up * -1, roll * -1) end end --- Applies torque -- @param Vector torque The torque vector function ents_methods:applyTorque(torque) local ent = getent(self) torque = vunwrap1(torque) checkvector(torque) local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkpermission(instance, ent, "entities.applyForce") Phys_ApplyTorqueCenter(phys, torque) end --- Allows detecting collisions on an entity. -- @param function func The callback function with argument, table collsiondata, http://wiki.facepunch.com/gmod/Structures/CollisionData -- @param string? name Optional name to distinguish multiple collision listeners and remove them individually later. (default: "") function ents_methods:addCollisionListener(func, name) checkluatype(func, TYPE_FUNCTION) if name ~= nil then checkluatype(name, TYPE_STRING) else name = "" end local ent = getent(self) checkpermission(instance, ent, "entities.canTool") collisionListeners:add(ent, name, func) end --- Removes a collision listener from the entity -- @param string? name The name of the collision listener to remove. (default: "") function ents_methods:removeCollisionListener(name) if name ~= nil then checkluatype(name, TYPE_STRING) else name = "" end local ent = getent(self) checkpermission(instance, ent, "entities.canTool") collisionListeners:remove(ent, name) end --- Sets whether an entity's shadow should be drawn -- @param boolean draw Whether the shadow should draw function ents_methods:setDrawShadow(draw) local ent = getent(self) checkpermission(instance, ent, "entities.setRenderProperty") checkluatype(draw, TYPE_BOOL) Ent_DrawShadow(ent, draw) end --- Sets the entity's position. No interpolation will occur clientside, use physobj.setPos to have interpolation. -- @param Vector vec New position function ents_methods:setPos(vec) local ent = getent(self) checkpermission(instance, ent, "entities.setPos") Ent_SetPos(ent, SF.clampPos(vunwrap1(vec))) end --- Sets the entity's angles -- @param Angle ang New angles function ents_methods:setAngles(ang) local ent = getent(self) checkpermission(instance, ent, "entities.setAngles") Ent_SetAngles(ent, aunwrap1(ang)) end --- Sets the entity's position local to its parent -- @param Vector vec New position function ents_methods:setLocalPos(vec) local ent = getent(self) checkpermission(instance, ent, "entities.setPos") Ent_SetLocalPos(ent, SF.clampPos(vunwrap1(vec))) end --- Sets the entity's angles local to its parent -- @param Angle ang New angles function ents_methods:setLocalAngles(ang) local ent = getent(self) checkpermission(instance, ent, "entities.setAngles") Ent_SetLocalAngles(ent, aunwrap1(ang)) end --- Sets the entity's linear velocity. Physics entities, use physobj:setVelocity -- @param Vector vel New velocity function ents_methods:setVelocity(vel) local ent = getent(self) vel = vunwrap1(vel) checkvector(vel) checkpermission(instance, ent, "entities.setVelocity") Ent_SetVelocity(ent, vel) end --- Applies velocity to an object -- @param Vector vel The world velocity vector to apply function ents_methods:addVelocity(vel) local ent = getent(self) vel = vunwrap1(vel) checkvector(vel) local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkpermission(instance, ent, "entities.applyForce") Phys_AddVelocity(phys, vel) end --- Removes an entity function ents_methods:remove() local ent = getent(self) if Ent_IsWorld(ent) or Ent_IsPlayer(ent) then SF.Throw("Cannot remove world or player", 2) end checkpermission(instance, ent, "entities.remove") Ent_Remove(ent) end --- Invokes the entity's breaking animation and removes it. function ents_methods:breakEnt() local ent = getent(self) local ent_tbl = Ent_GetTable(ent) if Ent_IsPlayer(ent) or ent_tbl.WasBroken then SF.Throw("Entity is not valid", 2) end checkpermission(instance, ent, "entities.remove") ent_tbl.WasBroken = true Ent_Fire(ent, "break", 1, 0) end --- Ignites an entity -- @param number length How long the fire lasts -- @param number? radius (optional) How large the fire hitbox is (entity obb is the max) function ents_methods:ignite(length, radius) local ent = getent(self) checkluatype(length, TYPE_NUMBER) checkpermission(instance, ent, "entities.ignite") if radius ~= nil then checkluatype(radius, TYPE_NUMBER) local obbmins, obbmaxs = Ent_OBBMins(ent), Ent_OBBMaxs(ent) radius = math.Clamp(radius, 0, (obbmaxs.x - obbmins.x + obbmaxs.y - obbmins.y) / 2) end Ent_Ignite(ent, length, radius) end --- Extinguishes an entity function ents_methods:extinguish() local ent = getent(self) checkpermission(instance, ent, "entities.ignite") Ent_Extinguish(ent) end --- Simulate a Use action on the entity by the chip owner -- @param number? usetype The USE_ enum use type. (Default: USE_ON) -- @param number? value The use value (Default: 0) function ents_methods:use(usetype, value) local ent = getent(self) checkpermission(instance, ent, "entities.use") if usetype ~= nil then checkluatype(usetype, TYPE_NUMBER) end if value ~= nil then checkluatype(value, TYPE_NUMBER) end if Ply_InVehicle(instance.player) and Ent_IsVehicle(ent) then return end -- Prevent source engine bug when using vehicle while in a vehicle Ent_Use(ent, instance.player, instance.entity, usetype, value) end --- Sets the entity to be Solid or not. -- @param boolean solid Should the entity be solid? function ents_methods:setSolid(solid) local ent = getent(self) if Ent_IsPlayer(ent) then SF.Throw("Target is a player!", 2) end checkpermission(instance, ent, "entities.setSolid") Ent_SetNotSolid(ent, not solid) end --- Sets the entity's collision group -- @param number group The COLLISION_GROUP value to set it to function ents_methods:setCollisionGroup(group) checkluatype(group, TYPE_NUMBER) if group < 0 or group >= LAST_SHARED_COLLISION_GROUP then SF.Throw("Invalid collision group value", 2) end local ent = getent(self) if Ent_IsPlayer(ent) then SF.Throw("Target is a player!", 2) end checkpermission(instance, ent, "entities.setSolid") Ent_SetCollisionGroup(ent, group) end --- Set's the entity to collide with nothing but the world. Alias to entity:setCollisionGroup(COLLISION_GROUP_WORLD) -- @param boolean nocollide Whether to collide with nothing except world or not. function ents_methods:setNocollideAll(nocollide) local ent = getent(self) if Ent_IsPlayer(ent) then SF.Throw("Target is a player!", 2) end checkpermission(instance, ent, "entities.setSolid") Ent_SetCollisionGroup(ent, nocollide and COLLISION_GROUP_WORLD or COLLISION_GROUP_NONE) end --- Sets the entity's mass -- @param number mass Mass to set to function ents_methods:setMass(mass) local ent = getent(self) if Ent_IsPlayer(ent) then SF.Throw("Target is a player!", 2) end checkluatype(mass, TYPE_NUMBER) local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkpermission(instance, ent, "entities.setMass") local m = math.Clamp(mass, 1, 50000) Phys_SetMass(phys, m) duplicator.StoreEntityModifier(ent, "mass", { Mass = m }) end --- Sets the entity's inertia -- @param Vector vec Inertia tensor function ents_methods:setInertia(vec) local ent = getent(self) if Ent_IsPlayer(ent) then SF.Throw("Target is a player!", 2) end checkpermission(instance, ent, "entities.setInertia") local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end vec = vunwrap1(vec) checkvector(vec) vec[1] = math.Clamp(vec[1], 1, 100000) vec[2] = math.Clamp(vec[2], 1, 100000) vec[3] = math.Clamp(vec[3], 1, 100000) Phys_SetInertia(phys, vec) end --- Sets the physical material of the entity -- @param string materialName Material to use function ents_methods:setPhysMaterial(mat) local ent = getent(self) if Ent_IsPlayer(ent) then SF.Throw("Target is a player!", 2) end checkluatype(mat, TYPE_STRING) local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkpermission(instance, ent, "entities.setMass") construct.SetPhysProp(nil, ent, 0, phys, { Material = mat }) end --- Get the physical material of the entity -- @return string The physical material function ents_methods:getPhysMaterial() local ent = getent(self) local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end return Phys_GetMaterial(phys) end --- Checks whether entity has physics -- @return boolean If entity has physics function ents_methods:isValidPhys() return Phys_IsValid(Ent_GetPhysicsObject(getent(self))) end --- Returns true if the entity is being held by a player. Either by Physics gun, Gravity gun or Use-key. -- @server -- @return boolean If the entity is being held or not function ents_methods:isPlayerHolding() return Ent_IsPlayerHolding(getent(self)) end --- Returns if the entity is a constraint. -- @server -- @return boolean If the entity is a constraint function ents_methods:isConstraint() return Ent_IsConstraint(getent(self)) end --- Sets entity gravity -- @param boolean grav Should the entity respect gravity? function ents_methods:enableGravity(grav) local ent = getent(self) if Ent_IsPlayer(ent) then SF.Throw("Target is a player!", 2) end local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkpermission(instance, ent, "entities.enableGravity") Phys_EnableGravity(phys, grav and true or false) Phys_Wake(phys) end --- Sets the entity drag state -- @param boolean drag Should the entity have air resistance? function ents_methods:enableDrag(drag) local ent = getent(self) if Ent_IsPlayer(ent) then SF.Throw("Target is a player!", 2) end local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkpermission(instance, ent, "entities.enableDrag") Phys_EnableDrag(phys, drag and true or false) end --- Sets the contents flag of the physobject -- @server -- @param number contents The CONTENTS enum function ents_methods:setContents(contents) local ent = getent(self) if Ent_IsPlayer(ent) then SF.Throw("Target is a player!", 2) end local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkluatype(contents, TYPE_NUMBER) checkpermission(instance, ent, "entities.setContents") Phys_SetContents(phys, contents) end --- Sets the entity movement state -- @param boolean move Should the entity move? function ents_methods:enableMotion(move) local ent = getent(self) if Ent_IsPlayer(ent) then SF.Throw("Target is a player!", 2) end local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkpermission(instance, ent, "entities.enableMotion") Phys_EnableMotion(phys, move and true or false) Phys_Wake(phys) end --- Sets the entity frozen state, same as `Entity.enableMotion` but inverted -- @param boolean freeze Should the entity be frozen? function ents_methods:setFrozen(freeze) self:enableMotion(not freeze) end --- Checks the entities frozen state -- @return boolean True if entity is frozen function ents_methods:isFrozen() local ent = getent(self) local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end return not Phys_IsMoveable(phys) end --- Sets the physics of an entity to be a sphere -- @param boolean enabled Should the entity be spherical? -- @param number? radius Optional custom radius to use (max 500). Otherwise the prop's obb is used function ents_methods:enableSphere(enabled, radius) local ent = getent(self) if Ent_GetClass(ent) ~= "prop_physics" then SF.Throw("This function only works for prop_physics", 2) end local phys = Ent_GetPhysicsObject(ent) if not Phys_IsValid(phys) then SF.Throw("Physics object is invalid", 2) end checkpermission(instance, ent, "entities.enableMotion") local ismove = Phys_IsMoveable(phys) local mass = Phys_GetMass(phys) if enabled then if Ent_GetMoveType(ent) == MOVETYPE_VPHYSICS then if radius ~= nil then checkluatype(radius, TYPE_NUMBER) radius = math.Clamp(radius, 0.2, 500) else local OBB = Ent_OBBMaxs(ent) - Ent_OBBMins(ent) radius = math.max(OBB.x, OBB.y, OBB.z) / 2 end Ent_PhysicsInitSphere(ent, radius, phys:GetMaterial()) Ent_SetCollisionBounds(ent, Vector(-radius, -radius, -radius), Vector(radius, radius, radius)) -- https://github.com/daveth/makespherical/blob/80b702ba04ba4b64d6c378df8d405b2c113dec53/lua/weapons/gmod_tool/stools/makespherical.lua#L117 local info = { obbcenter = ent.obbcenter, noradius = radius, radius = radius, mass = mass, enabled = enabled, isrenderoffset = 0, } duplicator.StoreEntityModifier(ent, "MakeSphericalCollisions", info) end else Ent_PhysicsInit(ent, SOLID_VPHYSICS) Ent_SetMoveType(ent, MOVETYPE_VPHYSICS) Ent_SetSolid(ent, SOLID_VPHYSICS) duplicator.ClearEntityModifier(ent, "MakeSphericalCollisions") end -- New physobject after applying spherical collisions phys = Ent_GetPhysicsObject(ent) Phys_SetMass(phys, mass) Phys_EnableMotion(phys, ismove) Phys_Wake(phys) end --- Gets what the entity is welded to. If the entity is parented, returns the parent. -- @return Entity The first welded/parent entity function ents_methods:isWeldedTo() local ent = getent(self) local constr = constraint.FindConstraint(ent, "Weld") if constr then return owrap(constr.Ent1 == ent and constr.Ent2 or constr.Ent1) end local parent = Ent_GetParent(ent) if Ent_IsValid(parent) then return owrap(parent) end return nil end --- Gets a table of all constrained entities to each other -- @param table? filter Optional constraint type filter table where keys are the type name and values are 'true'. "Wire" and "Parent" are used for wires and parents. function ents_methods:getAllConstrained(filter) if filter ~= nil then checkluatype(filter, TYPE_TABLE) end local entity_lookup = {} local entity_table = {} local function recursive_find(ent) if entity_lookup[ent] then return end entity_lookup[ent] = true if Ent_IsValid(ent) then entity_table[#entity_table + 1] = owrap(ent) local constraints = constraint.GetTable(ent) for _, v in pairs(constraints) do if not filter or filter[v.Type] then if v.Ent1 then recursive_find(v.Ent1) end if v.Ent2 then recursive_find(v.Ent2) end end end if not filter or filter.Parent then local parent = Ent_GetParent(ent) if parent then recursive_find(parent) end for _, child in pairs(Ent_GetChildren(ent)) do recursive_find(child) end end if not filter or filter.Wire then local ent_tbl = Ent_GetTable(ent) local inputs = ent_tbl.Inputs if istable(inputs) then for _, v in pairs(inputs) do if isentity(v.Src) and Ent_IsValid(v.Src) then recursive_find(v.Src) end end end local outputs = ent_tbl.Outputs if istable(outputs) then for _, v in pairs(outputs) do if istable(v.Connected) then for _, v in pairs(v.Connected) do if isentity(v.Entity) and Ent_IsValid(v.Entity) then recursive_find(v.Entity) end end end end end end end end recursive_find(getent(self)) return entity_table end --- Adds a trail to the entity with the specified attributes. -- @param number startSize The start size of the trail (0-128) -- @param number endSize The end size of the trail (0-128) -- @param number length The length size of the trail -- @param string material The material of the trail -- @param Color color The color of the trail -- @param number? attachmentID Optional attachmentid the trail should attach to -- @param boolean? additive If the trail's rendering is additive function ents_methods:setTrails(startSize, endSize, length, material, color, attachmentID, additive) local ent = getent(self) local ent_tbl = Ent_GetTable(ent) checkluatype(material, TYPE_STRING) local time = CurTime() if ent_tbl._lastTrailSet == time then SF.Throw("Can't modify trail more than once per frame", 2) end ent_tbl._lastTrailSet = time if string.find(material, '"', 1, true) then SF.Throw("Invalid Material", 2) end checkpermission(instance, ent, "entities.setRenderProperty") local Data = { Color = cunwrap(color), Length = length, StartSize = math.Clamp(startSize, 0, 128), EndSize = math.Clamp(endSize, 0, 128), Material = material, AttachmentID = attachmentID, Additive = additive, } duplicator.EntityModifiers.trail(instance.player, ent, Data) end --- Removes trails from the entity function ents_methods:removeTrails() local ent = getent(self) checkpermission(instance, ent, "entities.setRenderProperty") duplicator.EntityModifiers.trail(instance.player, ent, nil) end --- Sets a prop_physics to be unbreakable -- @param boolean on Whether to make the prop unbreakable function ents_methods:setUnbreakable(on) local ent = getent(self) checkluatype(on, TYPE_BOOL) checkpermission(instance, ent, "entities.canTool") if Ent_GetClass(ent) ~= "prop_physics" then SF.Throw("setUnbreakable can only be used on prop_physics", 2) end if not Ent_IsValid(SF.UnbreakableFilter) then local FilterDamage = ents.FindByName("FilterDamage")[1] if not FilterDamage then FilterDamage = ents.Create("filter_activator_name") FilterDamage:SetKeyValue("TargetName", "FilterDamage") FilterDamage:SetKeyValue("negated", "1") FilterDamage:Spawn() end SF.UnbreakableFilter = FilterDamage end Ent_Fire(ent, "SetDamageFilter", on and "FilterDamage" or "", 0) end --- Check if the given Entity or Vector is within this entity's PVS (Potentially Visible Set). See: https://developer.valvesoftware.com/wiki/PVS -- @param Entity|Vector other Entity or Vector to test -- @return boolean If the Entity/Vector is within the PVS function ents_methods:testPVS(other) local ent = getent(self) local meta = debug.getmetatable(other) if meta == vec_meta then other = vunwrap1(other) elseif meta == ent_meta or (meta and meta.supertype == ent_meta) then other = getent(other) else SF.ThrowTypeError("Entity or Vector", SF.GetType(other), 2) end return Ent_TestPVS(ent, other) end --- Returns entity's creation ID (similar to entIndex, but increments monotonically) -- @return number The creation ID function ents_methods:getCreationID() return Ent_GetCreationID(getent(self)) end local physUpdateWhitelist = { ["starfall_prop"] = true, ["starfall_processor"] = true, } --- Set the function to run whenever the physics of the entity are updated. --- This won't be called if the physics object goes asleep. --- --- You can only use this function on these classes: --- - starfall_prop --- - starfall_processor -- @param function|nil func The callback function. Use nil to remove an existing callback. function ents_methods:setPhysicsUpdateListener(func) local ent = getent(self) checkpermission(instance, ent, "entities.canTool") local class = Ent_GetClass(ent) if not physUpdateWhitelist[class] then SF.Throw("Cannot use physics update listener on " .. class, 2) end if func then checkluatype(func, TYPE_FUNCTION) Ent_GetTable(ent).PhysicsUpdate = function() instance:runFunction(func) end else Ent_GetTable(ent).PhysicsUpdate = nil end end --- Marks an entity as a trigger, setting callback functions to run whenever other objects enter or leave the bounds of the first entity. --- The entity will still invoke the callbacks even if not solid and no physical collision occurs, unlike Entity:addCollisionListener. --- Set both functiions to nil to unmark this entity as a trigger. --- https://developer.valvesoftware.com/wiki/Triggers --- --- You can only use this function on these classes: --- - starfall_prop --- - starfall_processor -- @param function|nil func The StartTouch callback function. Arguments: (Entity object), the object entering our entity's bounds. -- @param function|nil func The EndTouch callback function. Arguments: (Entity object), the object leaving our entity's bounds. function ents_methods:setTriggerListener(startTouchCB, endTouchCB) local ent = getent(self) checkpermission(instance, ent, "entities.canTool") local class = Ent_GetClass(ent) if not physUpdateWhitelist[class] then SF.Throw("Cannot use trigger listener on " .. class, 2) end local entTable = Ent_GetTable(ent) if not startTouchCB and not endTouchCB then ent:SetTrigger(false) entTable.StartTouch = nil entTable.EndTouch = nil return end if startTouchCB then checkluatype(startTouchCB, TYPE_FUNCTION) ent:SetTrigger(true) entTable.StartTouch = function(_, touchingEnt) instance:runFunction(startTouchCB, owrap(touchingEnt)) end else entTable.StartTouch = nil end if endTouchCB then checkluatype(endTouchCB, TYPE_FUNCTION) ent:SetTrigger(true) entTable.EndTouch = function(_, touchingEnt) instance:runFunction(endTouchCB, owrap(touchingEnt)) end else entTable.EndTouch = nil end end --- Returns a copy of the entity's sanitized internal glua table. -- @return table The entity's table. function ents_methods:getTable() local ent = getent(self) checkpermission(instance, ent, "entities.getTable") return instance.Sanitize(Ent_GetTable(ent)) end --- Returns a variable from the entity's internal glua table. -- @param string key The variable's key. -- @return any The variable. function ents_methods:getVar(key) local ent = getent(self) checkpermission(instance, ent, "entities.getTable") local var = Ent_GetVar(ent, key) return istable(var) and instance.Sanitize(var) or owrap(var) end --- Sets the entity to be used as the light origin position for this entity. -- @param Entity? lightOrigin The lighting entity or nil to reset. function ents_methods:setLightingOriginEntity(lightOrigin) local ent = getent(self) checkpermission(instance, ent, "entities.setRenderProperty") if lightOrigin then lightOrigin = getent(lightOrigin) end Ent_SetLightingOriginEntity(ent, lightOrigin) end end
0
0.730472
1
0.730472
game-dev
MEDIA
0.954919
game-dev
0.910904
1
0.910904
InfernumTeam/InfernumMode
5,690
Content/BehaviorOverrides/BossAIs/Draedon/Thanatos/LightOverloadRay.cs
using System.Collections.Generic; using CalamityMod; using CalamityMod.NPCs; using InfernumMode.Assets.Effects; using InfernumMode.Assets.ExtraTextures; using InfernumMode.Common.Graphics.Interfaces; using InfernumMode.Common.Graphics.Primitives; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace InfernumMode.Content.BehaviorOverrides.BossAIs.Draedon.Thanatos { public class LightOverloadRay : ModProjectile, IPixelPrimitiveDrawer { public PrimitiveTrailCopy LaserDrawer; public static NPC Thanatos => Main.npc[CalamityGlobalNPC.draedonExoMechWorm]; public Vector2 StartingPosition => Thanatos.Center - (Thanatos.rotation - PiOver2).ToRotationVector2() * Projectile.Opacity * 5f; // This is only used in drawing to represent increments as a semi-hack. Don't mess with it. public float RayHue; public const int Lifetime = 45; public ref float Time => ref Projectile.ai[0]; public ref float LaserSpread => ref Projectile.ai[1]; public ref float LaserLength => ref Projectile.localAI[0]; public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; public override void SetStaticDefaults() { // DisplayName.SetDefault("Prismatic Overload Beam"); } public override void SetDefaults() { Projectile.width = Projectile.height = 14; Projectile.alpha = 255; Projectile.penetrate = -1; Projectile.tileCollide = false; Projectile.ignoreWater = true; Projectile.timeLeft = Lifetime; Projectile.hostile = true; CooldownSlot = ImmunityCooldownID.Bosses; } public override void AI() { if (CalamityGlobalNPC.draedonExoMechWorm == -1) { Projectile.Kill(); return; } DelegateMethods.v3_1 = Vector3.One * 0.7f; Utils.PlotTileLine(StartingPosition, StartingPosition + (Thanatos.rotation - PiOver2).ToRotationVector2() * Projectile.Opacity * 400f, 8f, DelegateMethods.CastLight); Projectile.Opacity = Utils.GetLerpValue(0f, 10f, Time, true) * Utils.GetLerpValue(0f, 8f, Projectile.timeLeft, true); Projectile.velocity = Vector2.Zero; Projectile.Center = StartingPosition; LaserLength = Lerp(LaserLength, 9000f, 0.1f); Time++; } public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) { if (Projectile.Opacity < 1f) return false; for (int i = 0; i < 45; i++) { float _ = 0f; float offsetAngle = Lerp(-LaserSpread, LaserSpread, i / 44f); Vector2 start = StartingPosition; Vector2 end = start + (Thanatos.rotation - PiOver2 + offsetAngle).ToRotationVector2() * LaserLength; if (Collision.CheckAABBvLineCollision(targetHitbox.TopLeft(), targetHitbox.Size(), start, end, Projectile.scale * 50f, ref _)) return true; } return false; } public float LaserWidthFunction(float completionRatio) => Projectile.Opacity * Utils.GetLerpValue(0.96f, 0.8f, completionRatio, true) * 45f; public Color LaserColorFunction(float completionRatio) { float hue = (RayHue * 2.4f + Main.GlobalTimeWrappedHourly * 0.77f) % 1f; Color color = LumUtils.MulticolorLerp(hue, CalamityUtils.ExoPalette); color = Color.Lerp(color, Color.Wheat, 0.4f) * Projectile.Opacity; color *= Utils.GetLerpValue(0.96f, 0.8f, completionRatio, true); return color; } public override bool PreDraw(ref Color lightColor) => false; public void DrawPixelPrimitives(SpriteBatch spriteBatch) { spriteBatch.SetBlendState(BlendState.Additive); LaserDrawer ??= new PrimitiveTrailCopy(LaserWidthFunction, LaserColorFunction, null, true, InfernumEffectsRegistry.FireVertexShader); InfernumEffectsRegistry.FireVertexShader.UseSaturation(0.14f); InfernumEffectsRegistry.FireVertexShader.SetShaderTexture(InfernumTextureRegistry.CultistRayMap); List<float> rotationPoints = []; List<Vector2> drawPoints = []; var oldBlendState = Main.instance.GraphicsDevice.BlendState; Main.instance.GraphicsDevice.BlendState = BlendState.Additive; for (int i = 0; i < 45; i++) { RayHue = i / 44f; rotationPoints.Clear(); drawPoints.Clear(); float offsetAngle = Thanatos.rotation - PiOver2 + Lerp(-LaserSpread * Projectile.Opacity, LaserSpread * Projectile.Opacity, i / 44f); for (int j = 0; j < 8; j++) { rotationPoints.Add(offsetAngle); Vector2 start = StartingPosition; Vector2 end = start + offsetAngle.ToRotationVector2() * LaserLength; drawPoints.Add(Vector2.Lerp(start, end, j / 8f)); } LaserDrawer.DrawPixelated(drawPoints, -Main.screenPosition, 20); LaserDrawer.DrawPixelated(drawPoints, -Main.screenPosition, 20); } Main.instance.GraphicsDevice.BlendState = oldBlendState; } public override Color? GetAlpha(Color lightColor) => new Color(Projectile.Opacity, Projectile.Opacity, Projectile.Opacity, 0); } }
0
0.850484
1
0.850484
game-dev
MEDIA
0.870848
game-dev,graphics-rendering
0.987485
1
0.987485
alliedmodders/hl2sdk
18,658
game/server/movement.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: MOVEMENT ENTITIES TEST // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "entitylist.h" #include "entityoutput.h" #include "keyframe/keyframe.h" // BUG: this needs to move if keyframe is a standard thing #include "mathlib/mathlib.h" // FIXME: why do we still need this? // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // Hack, sort of. These interpolators don't get to hold state, but the ones // that need state (like the rope simulator) should NOT be used as paths here. IPositionInterpolator *g_pPositionInterpolators[8] = {0,0,0,0,0,0,0,0}; IPositionInterpolator* GetPositionInterpolator( int iInterp ) { if( !g_pPositionInterpolators[iInterp] ) g_pPositionInterpolators[iInterp] = Motion_GetPositionInterpolator( iInterp ); return g_pPositionInterpolators[iInterp]; } static float Fix( float angle ) { while ( angle < 0 ) angle += 360; while ( angle > 360 ) angle -= 360; return angle; } void FixupAngles( QAngle &v ) { v.x = Fix( v.x ); v.y = Fix( v.y ); v.z = Fix( v.z ); } //----------------------------------------------------------------------------- // // Purpose: Contains a description of a keyframe // has no networked representation, so has to store origin, etc. itself // //----------------------------------------------------------------------------- class CPathKeyFrame : public CLogicalEntity { public: DECLARE_CLASS( CPathKeyFrame, CLogicalEntity ); void Spawn( void ); void Activate( void ); void Link( void ); Vector m_Origin; QAngle m_Angles; // euler angles PITCH YAW ROLL (Y Z X) Quaternion m_qAngle; // quaternion angle (generated from m_Angles) string_t m_iNextKey; float m_flNextTime; CPathKeyFrame *NextKey( int direction ); CPathKeyFrame *PrevKey( int direction ); float Speed( void ) { return m_flSpeed; } void SetKeyAngles( QAngle angles ); CPathKeyFrame *InsertNewKey( Vector newPos, QAngle newAngles ); void CalculateFrameDuration( void ); protected: CPathKeyFrame *m_pNextKey; CPathKeyFrame *m_pPrevKey; float m_flSpeed; DECLARE_DATADESC(); }; LINK_ENTITY_TO_CLASS( keyframe_track, CPathKeyFrame ); BEGIN_DATADESC( CPathKeyFrame ) DEFINE_FIELD( m_Origin, FIELD_VECTOR ), DEFINE_FIELD( m_Angles, FIELD_VECTOR ), DEFINE_FIELD( m_qAngle, FIELD_QUATERNION ), DEFINE_KEYFIELD( m_iNextKey, FIELD_STRING, "NextKey" ), DEFINE_FIELD( m_flNextTime, FIELD_FLOAT ), // derived from speed DEFINE_KEYFIELD( m_flSpeed, FIELD_FLOAT, "MoveSpeed" ), DEFINE_FIELD( m_pNextKey, FIELD_CLASSPTR ), DEFINE_FIELD( m_pPrevKey, FIELD_CLASSPTR ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: Converts inputed euler angles to internal angle format (quaternions) //----------------------------------------------------------------------------- void CPathKeyFrame::Spawn( void ) { m_Origin = GetLocalOrigin(); m_Angles = GetLocalAngles(); SetKeyAngles( m_Angles ); } //----------------------------------------------------------------------------- // Purpose: Adds the keyframe into the path after all the other keys have spawned //----------------------------------------------------------------------------- void CPathKeyFrame::Activate( void ) { BaseClass::Activate(); Link(); CalculateFrameDuration(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPathKeyFrame::CalculateFrameDuration( void ) { // calculate time from speed if ( m_pNextKey && m_flSpeed > 0 ) { m_flNextTime = (m_Origin - m_pNextKey->m_Origin).Length() / m_flSpeed; // couldn't get time from distance, get it from rotation instead if ( !m_flNextTime ) { // speed is in degrees per second // find the largest rotation component and use that QAngle ang = m_Angles - m_pNextKey->m_Angles; FixupAngles( ang ); float x = 0; for ( int i = 0; i < 3; i++ ) { if ( abs(ang[i]) > x ) { x = abs(ang[i]); } } m_flNextTime = x / m_flSpeed; } } } //----------------------------------------------------------------------------- // Purpose: Links the key frame into the key frame list //----------------------------------------------------------------------------- void CPathKeyFrame::Link( void ) { m_pNextKey = dynamic_cast<CPathKeyFrame*>( gEntList.FindEntityByName(NULL, m_iNextKey ) ); if ( m_pNextKey ) { m_pNextKey->m_pPrevKey = this; } } //----------------------------------------------------------------------------- // Purpose: // Input : angles - //----------------------------------------------------------------------------- void CPathKeyFrame::SetKeyAngles( QAngle angles ) { m_Angles = angles; AngleQuaternion( m_Angles, m_qAngle ); } //----------------------------------------------------------------------------- // Purpose: // Input : direction - // Output : CPathKeyFrame //----------------------------------------------------------------------------- CPathKeyFrame* CPathKeyFrame::NextKey( int direction ) { if ( direction == 1 ) { return m_pNextKey; } else if ( direction == -1 ) { return m_pPrevKey; } return this; } //----------------------------------------------------------------------------- // Purpose: // Input : direction - // Output : CPathKeyFrame //----------------------------------------------------------------------------- CPathKeyFrame *CPathKeyFrame::PrevKey( int direction ) { if ( direction == 1 ) { return m_pPrevKey; } else if ( direction == -1 ) { return m_pNextKey; } return this; } //----------------------------------------------------------------------------- // Purpose: Creates and insterts a new keyframe into the sequence // Input : newPos - // newAngles - // Output : CPathKeyFrame //----------------------------------------------------------------------------- CPathKeyFrame *CPathKeyFrame::InsertNewKey( Vector newPos, QAngle newAngles ) { CPathKeyFrame *newKey = CREATE_ENTITY( CPathKeyFrame, "keyframe_track" ); // copy data across newKey->SetKeyAngles( newAngles ); newKey->m_Origin = newPos; newKey->m_flSpeed = m_flSpeed; newKey->SetEFlags( GetEFlags() ); if ( m_iParent != NULL_STRING ) { newKey->SetParent( m_iParent, NULL ); } // link forward newKey->m_pNextKey = m_pNextKey; m_pNextKey->m_pPrevKey = newKey; // link back m_pNextKey = newKey; newKey->m_pPrevKey = this; // calculate new times CalculateFrameDuration(); newKey->CalculateFrameDuration(); return newKey; } //----------------------------------------------------------------------------- // // Purpose: Basic keyframed movement behavior // //----------------------------------------------------------------------------- class CBaseMoveBehavior : public CPathKeyFrame { public: DECLARE_CLASS( CBaseMoveBehavior, CPathKeyFrame ); void Spawn( void ); void Activate( void ); void MoveDone( void ); float SetObjectPhysicsVelocity( float moveTime ); // methods virtual bool StartMoving( int direction ); virtual void StopMoving( void ); virtual bool IsMoving( void ); // derived classes should override this to get notification of arriving at new keyframes // virtual void ArrivedAtKeyFrame( CPathKeyFrame * ) {} bool IsAtSequenceStart( void ); bool IsAtSequenceEnd( void ); // interpolation functions // int m_iTimeModifier; int m_iPositionInterpolator; int m_iRotationInterpolator; // animation vars float m_flAnimStartTime; float m_flAnimEndTime; float m_flAverageSpeedAcrossFrame; // for advancing time with speed (not the normal visa-versa) CPathKeyFrame *m_pCurrentKeyFrame; // keyframe currently moving from CPathKeyFrame *m_pTargetKeyFrame; // keyframe being moved to CPathKeyFrame *m_pPreKeyFrame, *m_pPostKeyFrame; // pre- and post-keyframe's for spline interpolation float m_flTimeIntoFrame; int m_iDirection; // 1 for forward, -1 for backward, and 0 for at rest float CalculateTimeAdvancementForSpeed( float moveTime, float speed ); DECLARE_DATADESC(); }; LINK_ENTITY_TO_CLASS( move_keyframed, CBaseMoveBehavior ); BEGIN_DATADESC( CBaseMoveBehavior ) // DEFINE_KEYFIELD( m_iTimeModifier, FIELD_INTEGER, "TimeModifier" ), DEFINE_KEYFIELD( m_iPositionInterpolator, FIELD_INTEGER, "PositionInterpolator" ), DEFINE_KEYFIELD( m_iRotationInterpolator, FIELD_INTEGER, "RotationInterpolator" ), DEFINE_FIELD( m_pCurrentKeyFrame, FIELD_CLASSPTR ), DEFINE_FIELD( m_pTargetKeyFrame, FIELD_CLASSPTR ), DEFINE_FIELD( m_pPreKeyFrame, FIELD_CLASSPTR ), DEFINE_FIELD( m_pPostKeyFrame, FIELD_CLASSPTR ), DEFINE_FIELD( m_flAnimStartTime, FIELD_FLOAT ), DEFINE_FIELD( m_flAnimEndTime, FIELD_FLOAT ), DEFINE_FIELD( m_flAverageSpeedAcrossFrame, FIELD_FLOAT ), DEFINE_FIELD( m_flTimeIntoFrame, FIELD_FLOAT ), DEFINE_FIELD( m_iDirection, FIELD_INTEGER ), END_DATADESC() void CBaseMoveBehavior::Spawn( void ) { m_pCurrentKeyFrame = this; m_flTimeIntoFrame = 0; SetMoveType( MOVETYPE_PUSH ); // a move behavior is also it's first keyframe m_Origin = GetLocalOrigin(); m_Angles = GetLocalAngles(); BaseClass::Spawn(); } void CBaseMoveBehavior::Activate( void ) { BaseClass::Activate(); SetMoveDoneTime( 0.5 ); // start moving in 0.2 seconds time // if we are just the basic keyframed entity, cycle our animation if ( !stricmp(GetClassname(), "move_keyframed") ) { StartMoving( 1 ); } } //----------------------------------------------------------------------------- // Purpose: Checks to see if the we're at the start of the keyframe sequence // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CBaseMoveBehavior::IsAtSequenceStart( void ) { if ( !m_pCurrentKeyFrame ) return true; if ( m_flAnimStartTime && m_flAnimStartTime >= GetLocalTime() ) { if ( !m_pCurrentKeyFrame->PrevKey(1) && !m_pTargetKeyFrame ) return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Checks to see if we're at the end of the keyframe sequence // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CBaseMoveBehavior::IsAtSequenceEnd( void ) { if ( !m_pCurrentKeyFrame ) return false; if ( !m_pCurrentKeyFrame->NextKey(1) && !m_pTargetKeyFrame ) return true; return false; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CBaseMoveBehavior::IsMoving( void ) { if ( m_iDirection != 0 ) return true; return false; } //----------------------------------------------------------------------------- // Purpose: Starts the object moving from it's current position, in the direction indicated // Input : direction - 1 is forward through the sequence, -1 is backwards, and 0 is stop // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CBaseMoveBehavior::StartMoving( int direction ) { // 0 direction is to stop moving if ( direction == 0 ) { StopMoving(); return false; } // check to see if we should keep moving in the current direction if ( m_iDirection == direction ) { // if we're at the end of the current anim key, move to the next one if ( GetLocalTime() >= m_flAnimEndTime ) { m_pCurrentKeyFrame = m_pTargetKeyFrame; m_flTimeIntoFrame = 0; if ( !m_pTargetKeyFrame->NextKey(direction) ) { // we've hit the end of the sequence m_flAnimEndTime = 0; m_flAnimStartTime = 0; StopMoving(); return false; } // advance the target keyframe m_pTargetKeyFrame = m_pTargetKeyFrame->NextKey(direction); } } else { // we're changing direction // need to calculate current position in the frame // stop first, then start again if ( m_iDirection != 0 ) { StopMoving(); } m_iDirection = direction; // if we're going in reverse, swap the currentkey and targetkey (since we're going opposite dir) if ( direction == 1 ) { m_pTargetKeyFrame = m_pCurrentKeyFrame->NextKey( direction ); } else if ( direction == -1 ) { if ( m_flTimeIntoFrame > 0 ) { m_pTargetKeyFrame = m_pCurrentKeyFrame; m_pCurrentKeyFrame = m_pCurrentKeyFrame->NextKey( 1 ); } else { m_pTargetKeyFrame = m_pCurrentKeyFrame->PrevKey( 1 ); } } // recalculate our movement from the stored data if ( !m_pTargetKeyFrame ) { StopMoving(); return false; } // calculate the keyframes before and after the keyframes we're interpolating between m_pPostKeyFrame = m_pTargetKeyFrame->NextKey( direction ); if ( !m_pPostKeyFrame ) { m_pPostKeyFrame = m_pTargetKeyFrame; } m_pPreKeyFrame = m_pCurrentKeyFrame->PrevKey( direction ); if ( !m_pPreKeyFrame ) { m_pPreKeyFrame = m_pCurrentKeyFrame; } } // no target, can't move if ( !m_pTargetKeyFrame ) return false; // calculate start/end time // ->m_flNextTime is the time to traverse to the NEXT key, so we need the opposite if travelling backwards if ( m_iDirection == 1 ) { m_flAnimStartTime = GetLocalTime() - m_flTimeIntoFrame; m_flAnimEndTime = GetLocalTime() + m_pCurrentKeyFrame->m_flNextTime - m_flTimeIntoFrame; } else { // flip the timing, since we're in reverse if ( m_flTimeIntoFrame ) m_flTimeIntoFrame = m_pTargetKeyFrame->m_flNextTime - m_flTimeIntoFrame; m_flAnimStartTime = GetLocalTime() - m_flTimeIntoFrame; m_flAnimEndTime = GetLocalTime() + m_pTargetKeyFrame->m_flNextTime - m_flTimeIntoFrame; } // calculate the average speed at which we cross float animDuration = (m_flAnimEndTime - m_flAnimStartTime); float dist = (m_pCurrentKeyFrame->m_Origin - m_pTargetKeyFrame->m_Origin).Length(); m_flAverageSpeedAcrossFrame = animDuration / dist; SetMoveDoneTime( m_flAnimEndTime - GetLocalTime() ); return true; } //----------------------------------------------------------------------------- // Purpose: stops the object from moving // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- void CBaseMoveBehavior::StopMoving( void ) { // remember exactly where we are in the frame m_flTimeIntoFrame = 0; if ( m_iDirection == 1 ) { // record the time if we're not at the end of the frame if ( GetLocalTime() < m_flAnimEndTime ) { m_flTimeIntoFrame = GetLocalTime() - m_flAnimStartTime; } else { // we're actually at the end if ( m_pTargetKeyFrame ) { m_pCurrentKeyFrame = m_pTargetKeyFrame; } } } else if ( m_iDirection == -1 ) { // store it only as a forward movement m_pCurrentKeyFrame = m_pTargetKeyFrame; if ( GetLocalTime() < m_flAnimEndTime ) { m_flTimeIntoFrame = m_flAnimEndTime - GetLocalTime(); } } // stop moving totally SetMoveDoneTime( -1 ); m_iDirection = 0; m_flAnimStartTime = 0; m_flAnimEndTime = 0; m_pTargetKeyFrame = NULL; SetAbsVelocity(vec3_origin); SetLocalAngularVelocity( vec3_angle ); } //----------------------------------------------------------------------------- // Purpose: We have just arrived at a key, move onto the next keyframe //----------------------------------------------------------------------------- void CBaseMoveBehavior::MoveDone( void ) { // if we're just a base then keep playing the anim if ( !stricmp(STRING(m_iClassname), "move_keyframed") ) { int direction = m_iDirection; // start moving from the keyframe we've just reached if ( !StartMoving(direction) ) { // try moving in the other direction StartMoving( -direction ); } } BaseClass::MoveDone(); } //----------------------------------------------------------------------------- // Purpose: Calculates a new moveTime based on the speed and the current point // in the animation. // used to advance keyframed objects that have dynamic speeds. // Input : moveTime - // Output : float - the new time in the keyframing sequence //----------------------------------------------------------------------------- float CBaseMoveBehavior::CalculateTimeAdvancementForSpeed( float moveTime, float speed ) { return (moveTime * speed * m_flAverageSpeedAcrossFrame); } //----------------------------------------------------------------------------- // Purpose: // GetLocalTime() is the objects local current time // Input : destTime - new time that is being moved to // moveTime - amount of time to be advanced this frame // Output : float - the actual amount of time to move (usually moveTime) //----------------------------------------------------------------------------- float CBaseMoveBehavior::SetObjectPhysicsVelocity( float moveTime ) { // make sure we have a valid set up if ( !m_pCurrentKeyFrame || !m_pTargetKeyFrame ) return moveTime; // if we're not moving, we're not moving if ( !IsMoving() ) return moveTime; float destTime = moveTime + GetLocalTime(); // work out where we want to be, using destTime m_flTimeIntoFrame = destTime - m_flAnimStartTime; float newTime = (destTime - m_flAnimStartTime) / (m_flAnimEndTime - m_flAnimStartTime); Vector newPos; QAngle newAngles; IPositionInterpolator *pInterp = GetPositionInterpolator( m_iPositionInterpolator ); if( pInterp ) { // setup key frames pInterp->SetKeyPosition( -1, m_pPreKeyFrame->m_Origin ); Motion_SetKeyAngles( -1, m_pPreKeyFrame->m_qAngle ); pInterp->SetKeyPosition( 0, m_pCurrentKeyFrame->m_Origin ); Motion_SetKeyAngles( 0, m_pCurrentKeyFrame->m_qAngle ); pInterp->SetKeyPosition( 1, m_pTargetKeyFrame->m_Origin ); Motion_SetKeyAngles( 1, m_pTargetKeyFrame->m_qAngle ); pInterp->SetKeyPosition( 2, m_pPostKeyFrame->m_Origin ); Motion_SetKeyAngles( 2, m_pPostKeyFrame->m_qAngle ); // find new interpolated position & rotation pInterp->InterpolatePosition( newTime, newPos ); } else { newPos.Init(); } Quaternion qRot; Motion_InterpolateRotation( newTime, m_iRotationInterpolator, qRot ); QuaternionAngles( qRot, newAngles ); // find our velocity vector (newPos - currentPos) and scale velocity vector according to the movetime float oneOnMoveTime = 1 / moveTime; SetAbsVelocity( (newPos - GetLocalOrigin()) * oneOnMoveTime ); SetLocalAngularVelocity( (newAngles - GetLocalAngles()) * oneOnMoveTime ); return moveTime; }
0
0.787171
1
0.787171
game-dev
MEDIA
0.892879
game-dev
0.608268
1
0.608268
kunitoki/juced
8,374
juce/extras/the jucer/src/model/components/jucer_GenericComponentHandler.h
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-9 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #ifndef __JUCER_GENERICCOMPONENTHANDLER_JUCEHEADER__ #define __JUCER_GENERICCOMPONENTHANDLER_JUCEHEADER__ //============================================================================== /** */ class GenericComponent : public Component { public: GenericComponent() : Component (T("new component")), actualClassName (T("Component")) { } ~GenericComponent() { } void paint (Graphics& g) { g.fillAll (Colours::white.withAlpha (0.25f)); g.setColour (Colours::black.withAlpha (0.5f)); g.drawRect (0, 0, getWidth(), getHeight()); g.drawLine (0.0f, 0.0f, (float) getWidth(), (float) getHeight()); g.drawLine (0.0f, (float) getHeight(), (float) getWidth(), 0.0f); g.setFont (14.0f); g.drawText (actualClassName, 0, 0, getWidth(), getHeight() / 2, Justification::centred, true); } void setClassName (const String& newName) { if (actualClassName != newName) { actualClassName = newName; repaint(); } } void setParams (const String& newParams) { if (constructorParams != newParams) { constructorParams = newParams; repaint(); } } String actualClassName, constructorParams; }; //============================================================================== /** */ class GenericComponentHandler : public ComponentTypeHandler { public: //============================================================================== GenericComponentHandler() : ComponentTypeHandler ("Generic Component", "GenericComponent", typeid (GenericComponent), 150, 24) {} //============================================================================== Component* createNewComponent (JucerDocument*) { return new GenericComponent(); } XmlElement* createXmlFor (Component* comp, const ComponentLayout* layout) { XmlElement* e = ComponentTypeHandler::createXmlFor (comp, layout); e->setAttribute (T("class"), ((GenericComponent*) comp)->actualClassName); e->setAttribute (T("params"), ((GenericComponent*) comp)->constructorParams); return e; } bool restoreFromXml (const XmlElement& xml, Component* comp, const ComponentLayout* layout) { if (! ComponentTypeHandler::restoreFromXml (xml, comp, layout)) return false; ((GenericComponent*) comp)->actualClassName = xml.getStringAttribute (T("class"), T("Component")); ((GenericComponent*) comp)->constructorParams = xml.getStringAttribute (T("params"), String::empty); return true; } void getEditableProperties (Component* component, JucerDocument& document, Array <PropertyComponent*>& properties) { ComponentTypeHandler::getEditableProperties (component, document, properties); properties.add (new GenericCompClassProperty (dynamic_cast <GenericComponent*> (component), document)); properties.add (new GenericCompParamsProperty (dynamic_cast <GenericComponent*> (component), document)); } const String getClassName (Component* comp) const { return ((GenericComponent*) comp)->actualClassName; } const String getCreationParameters (Component* comp) { return ((GenericComponent*) comp)->constructorParams; } void fillInCreationCode (GeneratedCode& code, Component* component, const String& memberVariableName) { ComponentTypeHandler::fillInCreationCode (code, component, memberVariableName); if (component->getName().isNotEmpty()) code.constructorCode << memberVariableName << "->setName (" << quotedString (component->getName()) << ");\n\n"; else code.constructorCode << "\n"; } juce_UseDebuggingNewOperator private: class GenericCompClassProperty : public ComponentTextProperty <GenericComponent> { public: GenericCompClassProperty (GenericComponent* comp, JucerDocument& document) : ComponentTextProperty <GenericComponent> (T("class"), 300, false, comp, document) { } void setText (const String& newText) { document.perform (new GenericCompClassChangeAction (component, *document.getComponentLayout(), makeValidCppIdentifier (newText, false, false, true)), T("Change generic component class")); } const String getText() const { return component->actualClassName; } private: class GenericCompClassChangeAction : public ComponentUndoableAction <GenericComponent> { public: GenericCompClassChangeAction (GenericComponent* const comp, ComponentLayout& layout, const String& newState_) : ComponentUndoableAction <GenericComponent> (comp, layout), newState (newState_) { oldState = comp->actualClassName; } bool perform() { showCorrectTab(); getComponent()->setClassName (newState); changed(); return true; } bool undo() { showCorrectTab(); getComponent()->setClassName (oldState); changed(); return true; } String newState, oldState; }; }; class GenericCompParamsProperty : public ComponentTextProperty <GenericComponent> { public: GenericCompParamsProperty (GenericComponent* comp, JucerDocument& document) : ComponentTextProperty <GenericComponent> (T("constructor params"), 1024, true, comp, document) { } void setText (const String& newText) { document.perform (new GenericCompParamsChangeAction (component, *document.getComponentLayout(), newText), T("Change generic component class")); } const String getText() const { return component->constructorParams; } private: class GenericCompParamsChangeAction : public ComponentUndoableAction <GenericComponent> { public: GenericCompParamsChangeAction (GenericComponent* const comp, ComponentLayout& layout, const String& newState_) : ComponentUndoableAction <GenericComponent> (comp, layout), newState (newState_) { oldState = comp->constructorParams; } bool perform() { showCorrectTab(); getComponent()->setParams (newState); changed(); return true; } bool undo() { showCorrectTab(); getComponent()->setParams (oldState); changed(); return true; } String newState, oldState; }; }; }; #endif // __JUCER_GENERICCOMPONENTHANDLER_JUCEHEADER__
0
0.865709
1
0.865709
game-dev
MEDIA
0.465041
game-dev,desktop-app
0.864071
1
0.864071
cocos/cocos-engine
16,904
cocos/physics/framework/components/character-controllers/character-controller.ts
/* Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. https://www.cocos.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { ccclass, disallowMultiple, tooltip, displayOrder, type, serializable } from 'cc.decorator'; import { DEBUG } from 'internal:constants'; import { Vec3, warn, CCFloat, Eventify } from '../../../../core'; import { Component } from '../../../../scene-graph'; import { IBaseCharacterController } from '../../../spec/i-character-controller'; import { ECharacterControllerType } from '../../physics-enum'; import { CharacterCollisionEventType, CharacterTriggerEventType } from '../../physics-interface'; import { selector, createCharacterController } from '../../physics-selector'; import { PhysicsSystem } from '../../physics-system'; type Callback = (...args: any[]) => any; /** * @en * Base class for Character Controller component. * @zh * 角色控制器组件基类。 */ @ccclass('cc.CharacterController') @disallowMultiple export class CharacterController extends Eventify(Component) { /// PUBLIC PROPERTY GETTER\SETTER /// /** * @en * Gets or sets the group of the character controller. * @zh * 获取或设置分组。 */ @type(PhysicsSystem.PhysicsGroup) @displayOrder(-2) @tooltip('i18n:physics3d.character_controller.group') public get group (): number { return this._group; } public set group (v: number) { if (DEBUG && !Number.isInteger(Math.log2(v >>> 0))) { warn('[Physics]: The group should only have one bit.'); } this._group = v; if (this._cct) { // The judgment is added here because the data exists in two places if (this._cct.getGroup() !== v) this._cct.setGroup(v); } } /** * @en * Gets or sets the minimum movement distance of the character controller. * @zh * 获取或设置角色控制器的最小移动距离。 */ @tooltip('i18n:physics3d.character_controller.minMoveDistance') @type(CCFloat) public get minMoveDistance (): number { return this._minMoveDistance; } public set minMoveDistance (value) { if (this._minMoveDistance === value) return; this._minMoveDistance = Math.abs(value); } /** * @en 、 * Gets or sets the maximum height the character controller can automatically climb. * @zh * 获取或设置角色控制器的最大自动爬台阶高度。 */ @tooltip('i18n:physics3d.character_controller.stepOffset') @type(CCFloat) public get stepOffset (): number { return this._stepOffset; } public set stepOffset (value) { if (this._stepOffset === value) return; this._stepOffset = Math.abs(value); if (this._cct) { this._cct.setStepOffset(value); } } /** * @en * Gets or sets the slope limit of the character controller in degree. * @zh * 获取或设置角色控制器的最大爬坡角度。 */ @tooltip('i18n:physics3d.character_controller.slopeLimit') @type(CCFloat) public get slopeLimit (): number { return this._slopeLimit; } public set slopeLimit (value) { if (this._slopeLimit === value) return; this._slopeLimit = Math.abs(value); if (this._cct) { this._cct.setSlopeLimit(value); } } /** * @en * Gets or sets the skin width of the character controller. * @zh * 获取或设置角色控制器的皮肤宽度。 */ @tooltip('i18n:physics3d.character_controller.skinWidth') @type(CCFloat) public get skinWidth (): number { return this._skinWidth; } public set skinWidth (value) { if (this._skinWidth === value) return; this._skinWidth = Math.abs(value); if (this._cct) { this._cct.setContactOffset(Math.max(0.0001, value)); } } // /** // * @en // * Gets or sets if the character controller can collide with other objects. // * @zh // * 获取或设置角色控制器是否和发生碰撞。 // */ // @tooltip('i18n:physics3d.character_controller.detectCollisions') // @type(CCBoolean) // public get detectCollisions () { // return this._detectCollisions; // } // public set detectCollisions (value) { // if (this._detectCollisions === value) return; // this._detectCollisions = value; // if (this._cct) { // this._cct.setDetectCollisions(value); // } // } // /** // * @en // * Gets or sets if the character controller enables overlap recovery when penetrating with other colliders. // * @zh // * 获取或设置角色控制器和其他碰撞体穿透时是否恢复。 // */ // @tooltip('i18n:physics3d.character_controller.enableOverlapRecovery') // @type(CCBoolean) // public get enableOverlapRecovery () { // return this._enableOverlapRecovery; // } // public set enableOverlapRecovery (value) { // if (this._enableOverlapRecovery === value) return; // this._enableOverlapRecovery = value; // if (this._cct) { // this._cct.setOverlapRecovery(value); // } // } /** * @en * Gets or sets the center of the character controller in local space. * @zh * 获取或设置角色控制器的中心点在局部坐标系中的位置。 */ @tooltip('i18n:physics3d.character_controller.center') @type(Vec3) public get center (): Readonly<Vec3> { return this._center; } public set center (value: Readonly<Vec3>) { if (Vec3.equals(this._center, value)) return; Vec3.copy(this._center, value); // if (this._cct) { //update cct position // Vec3.copy(VEC3_0, this.node.worldPosition); // VEC3_0.add(this.scaledCenter);//cct world position // this._cct.setPosition(VEC3_0); // } } /** * @en * Gets the type of this character controller. * @zh * 获取此角色控制器的类型。 */ readonly type: ECharacterControllerType; constructor (type: ECharacterControllerType) { super(); this.type = type; } protected _cct: IBaseCharacterController | null = null; //lowLevel instance /// PRIVATE PROPERTY /// @serializable private _group: number = PhysicsSystem.PhysicsGroup.DEFAULT; @serializable private _minMoveDistance = 0.001; //[ 0, infinity ] @serializable private _stepOffset = 0.5; @serializable private _slopeLimit = 45.0; //degree[ 0, 180] @serializable private _skinWidth = 0.01; //[ 0.0001, infinity ] // @serializable // private _detectCollisions = true; // @serializable // private _enableOverlapRecovery = true; @serializable private _center: Vec3 = new Vec3(); private _initialized = false; private _prevPos: Vec3 = new Vec3(); private _currentPos: Vec3 = new Vec3(); private _velocity: Vec3 = new Vec3(); private _centerWorldPosition: Vec3 = new Vec3(); protected _needCollisionEvent = false; protected _needTriggerEvent = false; protected get _isInitialized (): boolean { if (this._cct === null || !this._initialized) { //error('[Physics]: This component has not been call onLoad yet, please make sure the node has been added to the scene.'); return false; } else { return true; } } /// COMPONENT LIFECYCLE /// protected onLoad (): void { if (!selector.runInEditor) return; this._cct = createCharacterController(this.type); this._initialized = this._cct.initialize(this); this._cct.onLoad!(); } protected onEnable (): void { if (this._cct) { this._cct.onEnable!(); } } protected onDisable (): void { if (this._cct) { this._cct.onDisable!(); } } protected onDestroy (): void { if (this._cct) { this._needCollisionEvent = false; this._needTriggerEvent = false; this._cct.updateEventListener(); this._cct.onDestroy!(); this._cct = null; } } /// PUBLIC METHOD /// /** * @en * Gets world position of center. * @zh * 获取中心的世界坐标。 */ public get centerWorldPosition (): Readonly<Vec3> { if (this._isInitialized) this._cct!.getPosition(this._centerWorldPosition); return this._centerWorldPosition; } /** * @en * Sets world position of center. * Note: Calling this function will immediately synchronize the position of * the character controller in the physics world to the node. * @zh * 设置中心的世界坐标。 * 注意:调用该函数会立刻将角色控制器在物理世界中的位置同步到节点上。 */ public set centerWorldPosition (value: Readonly<Vec3>) { if (this._isInitialized) this._cct!.setPosition(value); } /** * @en * Gets the velocity. * Note: velocity is only updated after move() is called. * @zh * 获取速度。 * 注意:velocity 只会在 move() 调用后更新。 */ public get velocity (): Readonly<Vec3> { return this._velocity; } /** * @en * Gets whether the character is on the ground. * Note: isGrounded is only updated after move() is called. * @zh * 获取是否在地面上。 * 注意:isGrounded 只会在 move() 调用后更新。 */ public get isGrounded (): boolean { return this._cct!.onGround(); } /** * @en * Move the character. * @zh * 移动角色控制器。 * @param movement @zh 移动向量 @en The movement vector */ public move (movement: Vec3): void { if (!this._isInitialized) { return; } this._prevPos.set(this.centerWorldPosition); const elapsedTime = PhysicsSystem.instance.fixedTimeStep; this._cct!.move(movement, this._minMoveDistance, elapsedTime); this._currentPos.set(this.centerWorldPosition); this._velocity = this._currentPos.subtract(this._prevPos).multiplyScalar(1.0 / elapsedTime); this._cct!.syncPhysicsToScene(); } /// EVENT INTERFACE /// /** * @en * Registers callbacks associated with triggered or collision events. * @zh * 注册触发或碰撞事件相关的回调。 * @param type - The event type, onControllerColliderHit; * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. * @param target - The event callback target. */ public on<TFunction extends Callback> ( type: CharacterTriggerEventType | CharacterCollisionEventType, callback: TFunction, target?, once?: boolean, ): any { const ret = super.on(type, callback, target, once); this._updateNeedEvent(type); return ret; } /** * @en * Unregisters callbacks associated with trigger or collision events that have been registered. * @zh * 取消已经注册的触发或碰撞事件相关的回调。 * @param type - The event type, onControllerColliderHit; * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. * @param target - The event callback target. */ public off (type: CharacterTriggerEventType | CharacterCollisionEventType, callback?: Callback, target?): void { super.off(type, callback, target); this._updateNeedEvent(); } /** * @en * Registers a callback associated with a trigger or collision event, which is automatically unregistered once executed. * @zh * 注册触发或碰撞事件相关的回调,执行一次后会自动取消注册。 * @param type - The event type, onControllerColliderHit; * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. * @param target - The event callback target. */ public once<TFunction extends Callback> ( type: CharacterTriggerEventType | CharacterCollisionEventType, callback: TFunction, target?, ): any { // TODO: callback invoker now is a entity, after `once` will not calling the upper `off`. const ret = super.once(type, callback, target); this._updateNeedEvent(type); return ret; } /// GROUP MASK /// /** * @en * Gets the group value. * @zh * 获取分组值。 * @returns @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ public getGroup (): number { if (this._isInitialized) return this._cct!.getGroup(); return 0; } /** * @en * Sets the group value. * @zh * 设置分组值。 * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ public setGroup (v: number): void { if (this._isInitialized) this._cct!.setGroup(v); } /** * @en * Add a grouping value to fill in the group you want to join. * @zh * 添加分组值,可填要加入的 group。 * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ public addGroup (v: number): void { if (this._isInitialized) this._cct!.addGroup(v); } /** * @en * Subtract the grouping value to fill in the group to be removed. * @zh * 减去分组值,可填要移除的 group。 * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ public removeGroup (v: number): void { if (this._isInitialized) this._cct!.removeGroup(v); } /** * @en * Gets the mask value. * @zh * 获取掩码值。 * @returns {number} @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ public getMask (): number { if (this._isInitialized) return this._cct!.getMask(); return 0; } /** * @en * Sets the mask value. * @zh * 设置掩码值。 * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ public setMask (v: number): void { if (this._isInitialized) this._cct!.setMask(v); } /** * @en * Add mask values to fill in groups that need to be checked. * @zh * 添加掩码值,可填入需要检查的 group。 * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ public addMask (v: number): void { if (this._isInitialized) this._cct!.addMask(v); } /** * @en * Subtract the mask value to fill in the group that does not need to be checked. * @zh * 减去掩码值,可填入不需要检查的 group。 * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ public removeMask (v: number): void { if (this._isInitialized) this._cct!.removeMask(v); } public get needCollisionEvent (): boolean { return this._needCollisionEvent; } public get needTriggerEvent (): boolean { return this._needTriggerEvent; } private _updateNeedEvent (type?: string): void { if (this.isValid) { if (type !== undefined) { if (type === 'onControllerColliderHit') { this._needCollisionEvent = true; } if (type === 'onControllerTriggerEnter' || type === 'onControllerTriggerStay' || type === 'onControllerTriggerExit') { this._needTriggerEvent = true; } } else { if (!this.hasEventListener('onControllerColliderHit')) { this._needCollisionEvent = false; } if (!(this.hasEventListener('onControllerTriggerEnter') || this.hasEventListener('onControllerTriggerStay') || this.hasEventListener('onControllerTriggerExit'))) { this._needTriggerEvent = false; } } if (this._cct) this._cct.updateEventListener(); } } }
0
0.974114
1
0.974114
game-dev
MEDIA
0.74356
game-dev
0.803624
1
0.803624
ImLegiitXD/Dream-Advanced
28,065
dll/back/1.20/net/minecraft/world/level/chunk/ChunkGenerator.java
package net.minecraft.world.level.chunk; import com.google.common.base.Suppliers; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; import it.unimi.dsi.fastutil.ints.IntArraySet; import it.unimi.dsi.fastutil.ints.IntSet; import it.unimi.dsi.fastutil.longs.LongSet; import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; import it.unimi.dsi.fastutil.objects.ObjectArraySet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import javax.annotation.Nullable; import net.minecraft.CrashReport; import net.minecraft.CrashReportCategory; import net.minecraft.ReportedException; import net.minecraft.SharedConstants; import net.minecraft.Util; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.core.HolderLookup; import net.minecraft.core.HolderSet; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; import net.minecraft.core.SectionPos; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.network.protocol.game.DebugPackets; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.WorldGenRegion; import net.minecraft.util.random.WeightedRandomList; import net.minecraft.world.entity.MobCategory; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.LevelHeightAccessor; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.NoiseColumn; import net.minecraft.world.level.StructureManager; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.BiomeGenerationSettings; import net.minecraft.world.level.biome.BiomeManager; import net.minecraft.world.level.biome.BiomeSource; import net.minecraft.world.level.biome.FeatureSorter; import net.minecraft.world.level.biome.MobSpawnSettings; import net.minecraft.world.level.levelgen.GenerationStep; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.LegacyRandomSource; import net.minecraft.world.level.levelgen.RandomState; import net.minecraft.world.level.levelgen.RandomSupport; import net.minecraft.world.level.levelgen.WorldgenRandom; import net.minecraft.world.level.levelgen.XoroshiroRandomSource; import net.minecraft.world.level.levelgen.blending.Blender; import net.minecraft.world.level.levelgen.placement.PlacedFeature; import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.structure.Structure; import net.minecraft.world.level.levelgen.structure.StructureCheckResult; import net.minecraft.world.level.levelgen.structure.StructureSet; import net.minecraft.world.level.levelgen.structure.StructureSpawnOverride; import net.minecraft.world.level.levelgen.structure.StructureStart; import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement; import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStructurePlacement; import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; import org.apache.commons.lang3.mutable.MutableBoolean; public abstract class ChunkGenerator { public static final Codec<ChunkGenerator> CODEC = BuiltInRegistries.CHUNK_GENERATOR.byNameCodec().dispatchStable(ChunkGenerator::codec, Function.identity()); protected final BiomeSource biomeSource; private final Supplier<List<FeatureSorter.StepFeatureData>> featuresPerStep; private final Function<Holder<Biome>, BiomeGenerationSettings> generationSettingsGetter; public ChunkGenerator(BiomeSource p_256133_) { this(p_256133_, (p_223234_) -> { return p_223234_.value().getGenerationSettings(); }); } public ChunkGenerator(BiomeSource p_255838_, Function<Holder<Biome>, BiomeGenerationSettings> p_256216_) { this.biomeSource = p_255838_; this.generationSettingsGetter = p_256216_; this.featuresPerStep = Suppliers.memoize(() -> { return FeatureSorter.buildFeaturesPerStep(List.copyOf(p_255838_.possibleBiomes()), (p_223216_) -> { return p_256216_.apply(p_223216_).features(); }, true); }); } protected abstract Codec<? extends ChunkGenerator> codec(); public ChunkGeneratorStructureState createState(HolderLookup<StructureSet> p_256405_, RandomState p_256101_, long p_256018_) { return ChunkGeneratorStructureState.createForNormal(p_256101_, p_256018_, this.biomeSource, p_256405_); } public Optional<ResourceKey<Codec<? extends ChunkGenerator>>> getTypeNameForDataFixer() { return BuiltInRegistries.CHUNK_GENERATOR.getResourceKey(this.codec()); } public CompletableFuture<ChunkAccess> createBiomes(Executor p_223159_, RandomState p_223160_, Blender p_223161_, StructureManager p_223162_, ChunkAccess p_223163_) { return CompletableFuture.supplyAsync(Util.wrapThreadWithTaskName("init_biomes", () -> { p_223163_.fillBiomesFromNoise(this.biomeSource, p_223160_.sampler()); return p_223163_; }), Util.backgroundExecutor()); } public abstract void applyCarvers(WorldGenRegion p_223043_, long p_223044_, RandomState p_223045_, BiomeManager p_223046_, StructureManager p_223047_, ChunkAccess p_223048_, GenerationStep.Carving p_223049_); @Nullable public Pair<BlockPos, Holder<Structure>> findNearestMapStructure(ServerLevel p_223038_, HolderSet<Structure> p_223039_, BlockPos p_223040_, int p_223041_, boolean p_223042_) { ChunkGeneratorStructureState chunkgeneratorstructurestate = p_223038_.getChunkSource().getGeneratorState(); Map<StructurePlacement, Set<Holder<Structure>>> map = new Object2ObjectArrayMap<>(); for(Holder<Structure> holder : p_223039_) { for(StructurePlacement structureplacement : chunkgeneratorstructurestate.getPlacementsForStructure(holder)) { map.computeIfAbsent(structureplacement, (p_223127_) -> { return new ObjectArraySet(); }).add(holder); } } if (map.isEmpty()) { return null; } else { Pair<BlockPos, Holder<Structure>> pair2 = null; double d2 = Double.MAX_VALUE; StructureManager structuremanager = p_223038_.structureManager(); List<Map.Entry<StructurePlacement, Set<Holder<Structure>>>> list = new ArrayList<>(map.size()); for(Map.Entry<StructurePlacement, Set<Holder<Structure>>> entry : map.entrySet()) { StructurePlacement structureplacement1 = entry.getKey(); if (structureplacement1 instanceof ConcentricRingsStructurePlacement) { ConcentricRingsStructurePlacement concentricringsstructureplacement = (ConcentricRingsStructurePlacement)structureplacement1; Pair<BlockPos, Holder<Structure>> pair = this.getNearestGeneratedStructure(entry.getValue(), p_223038_, structuremanager, p_223040_, p_223042_, concentricringsstructureplacement); if (pair != null) { BlockPos blockpos = pair.getFirst(); double d0 = p_223040_.distSqr(blockpos); if (d0 < d2) { d2 = d0; pair2 = pair; } } } else if (structureplacement1 instanceof RandomSpreadStructurePlacement) { list.add(entry); } } if (!list.isEmpty()) { int i = SectionPos.blockToSectionCoord(p_223040_.getX()); int j = SectionPos.blockToSectionCoord(p_223040_.getZ()); for(int k = 0; k <= p_223041_; ++k) { boolean flag = false; for(Map.Entry<StructurePlacement, Set<Holder<Structure>>> entry1 : list) { RandomSpreadStructurePlacement randomspreadstructureplacement = (RandomSpreadStructurePlacement)entry1.getKey(); Pair<BlockPos, Holder<Structure>> pair1 = getNearestGeneratedStructure(entry1.getValue(), p_223038_, structuremanager, i, j, k, p_223042_, chunkgeneratorstructurestate.getLevelSeed(), randomspreadstructureplacement); if (pair1 != null) { flag = true; double d1 = p_223040_.distSqr(pair1.getFirst()); if (d1 < d2) { d2 = d1; pair2 = pair1; } } } if (flag) { return pair2; } } } return pair2; } } @Nullable private Pair<BlockPos, Holder<Structure>> getNearestGeneratedStructure(Set<Holder<Structure>> p_223182_, ServerLevel p_223183_, StructureManager p_223184_, BlockPos p_223185_, boolean p_223186_, ConcentricRingsStructurePlacement p_223187_) { List<ChunkPos> list = p_223183_.getChunkSource().getGeneratorState().getRingPositionsFor(p_223187_); if (list == null) { throw new IllegalStateException("Somehow tried to find structures for a placement that doesn't exist"); } else { Pair<BlockPos, Holder<Structure>> pair = null; double d0 = Double.MAX_VALUE; BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); for(ChunkPos chunkpos : list) { blockpos$mutableblockpos.set(SectionPos.sectionToBlockCoord(chunkpos.x, 8), 32, SectionPos.sectionToBlockCoord(chunkpos.z, 8)); double d1 = blockpos$mutableblockpos.distSqr(p_223185_); boolean flag = pair == null || d1 < d0; if (flag) { Pair<BlockPos, Holder<Structure>> pair1 = getStructureGeneratingAt(p_223182_, p_223183_, p_223184_, p_223186_, p_223187_, chunkpos); if (pair1 != null) { pair = pair1; d0 = d1; } } } return pair; } } @Nullable private static Pair<BlockPos, Holder<Structure>> getNearestGeneratedStructure(Set<Holder<Structure>> p_223189_, LevelReader p_223190_, StructureManager p_223191_, int p_223192_, int p_223193_, int p_223194_, boolean p_223195_, long p_223196_, RandomSpreadStructurePlacement p_223197_) { int i = p_223197_.spacing(); for(int j = -p_223194_; j <= p_223194_; ++j) { boolean flag = j == -p_223194_ || j == p_223194_; for(int k = -p_223194_; k <= p_223194_; ++k) { boolean flag1 = k == -p_223194_ || k == p_223194_; if (flag || flag1) { int l = p_223192_ + i * j; int i1 = p_223193_ + i * k; ChunkPos chunkpos = p_223197_.getPotentialStructureChunk(p_223196_, l, i1); Pair<BlockPos, Holder<Structure>> pair = getStructureGeneratingAt(p_223189_, p_223190_, p_223191_, p_223195_, p_223197_, chunkpos); if (pair != null) { return pair; } } } } return null; } @Nullable private static Pair<BlockPos, Holder<Structure>> getStructureGeneratingAt(Set<Holder<Structure>> p_223199_, LevelReader p_223200_, StructureManager p_223201_, boolean p_223202_, StructurePlacement p_223203_, ChunkPos p_223204_) { for(Holder<Structure> holder : p_223199_) { StructureCheckResult structurecheckresult = p_223201_.checkStructurePresence(p_223204_, holder.value(), p_223202_); if (structurecheckresult != StructureCheckResult.START_NOT_PRESENT) { if (!p_223202_ && structurecheckresult == StructureCheckResult.START_PRESENT) { return Pair.of(p_223203_.getLocatePos(p_223204_), holder); } ChunkAccess chunkaccess = p_223200_.getChunk(p_223204_.x, p_223204_.z, ChunkStatus.STRUCTURE_STARTS); StructureStart structurestart = p_223201_.getStartForStructure(SectionPos.bottomOf(chunkaccess), holder.value(), chunkaccess); if (structurestart != null && structurestart.isValid() && (!p_223202_ || tryAddReference(p_223201_, structurestart))) { return Pair.of(p_223203_.getLocatePos(structurestart.getChunkPos()), holder); } } } return null; } private static boolean tryAddReference(StructureManager p_223060_, StructureStart p_223061_) { if (p_223061_.canBeReferenced()) { p_223060_.addReference(p_223061_); return true; } else { return false; } } public void applyBiomeDecoration(WorldGenLevel p_223087_, ChunkAccess p_223088_, StructureManager p_223089_) { ChunkPos chunkpos = p_223088_.getPos(); if (!SharedConstants.debugVoidTerrain(chunkpos)) { SectionPos sectionpos = SectionPos.of(chunkpos, p_223087_.getMinSection()); BlockPos blockpos = sectionpos.origin(); Registry<Structure> registry = p_223087_.registryAccess().registryOrThrow(Registries.STRUCTURE); Map<Integer, List<Structure>> map = registry.stream().collect(Collectors.groupingBy((p_223103_) -> { return p_223103_.step().ordinal(); })); List<FeatureSorter.StepFeatureData> list = this.featuresPerStep.get(); WorldgenRandom worldgenrandom = new WorldgenRandom(new XoroshiroRandomSource(RandomSupport.generateUniqueSeed())); long i = worldgenrandom.setDecorationSeed(p_223087_.getSeed(), blockpos.getX(), blockpos.getZ()); Set<Holder<Biome>> set = new ObjectArraySet<>(); ChunkPos.rangeClosed(sectionpos.chunk(), 1).forEach((p_223093_) -> { ChunkAccess chunkaccess = p_223087_.getChunk(p_223093_.x, p_223093_.z); for(LevelChunkSection levelchunksection : chunkaccess.getSections()) { levelchunksection.getBiomes().getAll(set::add); } }); set.retainAll(this.biomeSource.possibleBiomes()); int j = list.size(); try { Registry<PlacedFeature> registry1 = p_223087_.registryAccess().registryOrThrow(Registries.PLACED_FEATURE); int i1 = Math.max(GenerationStep.Decoration.values().length, j); for(int k = 0; k < i1; ++k) { int l = 0; if (p_223089_.shouldGenerateStructures()) { for(Structure structure : map.getOrDefault(k, Collections.emptyList())) { worldgenrandom.setFeatureSeed(i, l, k); Supplier<String> supplier = () -> { return registry.getResourceKey(structure).map(Object::toString).orElseGet(structure::toString); }; try { p_223087_.setCurrentlyGenerating(supplier); p_223089_.startsForStructure(sectionpos, structure).forEach((p_223086_) -> { p_223086_.placeInChunk(p_223087_, p_223089_, this, worldgenrandom, getWritableArea(p_223088_), chunkpos); }); } catch (Exception exception) { CrashReport crashreport1 = CrashReport.forThrowable(exception, "Feature placement"); crashreport1.addCategory("Feature").setDetail("Description", supplier::get); throw new ReportedException(crashreport1); } ++l; } } if (k < j) { IntSet intset = new IntArraySet(); for(Holder<Biome> holder : set) { List<HolderSet<PlacedFeature>> list1 = this.generationSettingsGetter.apply(holder).features(); if (k < list1.size()) { HolderSet<PlacedFeature> holderset = list1.get(k); FeatureSorter.StepFeatureData featuresorter$stepfeaturedata1 = list.get(k); holderset.stream().map(Holder::value).forEach((p_223174_) -> { intset.add(featuresorter$stepfeaturedata1.indexMapping().applyAsInt(p_223174_)); }); } } int j1 = intset.size(); int[] aint = intset.toIntArray(); Arrays.sort(aint); FeatureSorter.StepFeatureData featuresorter$stepfeaturedata = list.get(k); for(int k1 = 0; k1 < j1; ++k1) { int l1 = aint[k1]; PlacedFeature placedfeature = featuresorter$stepfeaturedata.features().get(l1); Supplier<String> supplier1 = () -> { return registry1.getResourceKey(placedfeature).map(Object::toString).orElseGet(placedfeature::toString); }; worldgenrandom.setFeatureSeed(i, l1, k); try { p_223087_.setCurrentlyGenerating(supplier1); placedfeature.placeWithBiomeCheck(p_223087_, this, worldgenrandom, blockpos); } catch (Exception exception1) { CrashReport crashreport2 = CrashReport.forThrowable(exception1, "Feature placement"); crashreport2.addCategory("Feature").setDetail("Description", supplier1::get); throw new ReportedException(crashreport2); } } } } p_223087_.setCurrentlyGenerating((Supplier<String>)null); } catch (Exception exception2) { CrashReport crashreport = CrashReport.forThrowable(exception2, "Biome decoration"); crashreport.addCategory("Generation").setDetail("CenterX", chunkpos.x).setDetail("CenterZ", chunkpos.z).setDetail("Seed", i); throw new ReportedException(crashreport); } } } private static BoundingBox getWritableArea(ChunkAccess p_187718_) { ChunkPos chunkpos = p_187718_.getPos(); int i = chunkpos.getMinBlockX(); int j = chunkpos.getMinBlockZ(); LevelHeightAccessor levelheightaccessor = p_187718_.getHeightAccessorForGeneration(); int k = levelheightaccessor.getMinBuildHeight() + 1; int l = levelheightaccessor.getMaxBuildHeight() - 1; return new BoundingBox(i, k, j, i + 15, l, j + 15); } public abstract void buildSurface(WorldGenRegion p_223050_, StructureManager p_223051_, RandomState p_223052_, ChunkAccess p_223053_); public abstract void spawnOriginalMobs(WorldGenRegion p_62167_); public int getSpawnHeight(LevelHeightAccessor p_156157_) { return 64; } public BiomeSource getBiomeSource() { return this.biomeSource; } public abstract int getGenDepth(); public WeightedRandomList<MobSpawnSettings.SpawnerData> getMobsAt(Holder<Biome> p_223134_, StructureManager p_223135_, MobCategory p_223136_, BlockPos p_223137_) { Map<Structure, LongSet> map = p_223135_.getAllStructuresAt(p_223137_); for(Map.Entry<Structure, LongSet> entry : map.entrySet()) { Structure structure = entry.getKey(); StructureSpawnOverride structurespawnoverride = structure.spawnOverrides().get(p_223136_); if (structurespawnoverride != null) { MutableBoolean mutableboolean = new MutableBoolean(false); Predicate<StructureStart> predicate = structurespawnoverride.boundingBox() == StructureSpawnOverride.BoundingBoxType.PIECE ? (p_223065_) -> { return p_223135_.structureHasPieceAt(p_223137_, p_223065_); } : (p_223130_) -> { return p_223130_.getBoundingBox().isInside(p_223137_); }; p_223135_.fillStartsForStructure(structure, entry.getValue(), (p_223220_) -> { if (mutableboolean.isFalse() && predicate.test(p_223220_)) { mutableboolean.setTrue(); } }); if (mutableboolean.isTrue()) { return structurespawnoverride.spawns(); } } } return p_223134_.value().getMobSettings().getMobs(p_223136_); } public void createStructures(RegistryAccess p_255835_, ChunkGeneratorStructureState p_256505_, StructureManager p_255934_, ChunkAccess p_255767_, StructureTemplateManager p_255832_) { ChunkPos chunkpos = p_255767_.getPos(); SectionPos sectionpos = SectionPos.bottomOf(p_255767_); RandomState randomstate = p_256505_.randomState(); p_256505_.possibleStructureSets().forEach((p_255564_) -> { StructurePlacement structureplacement = p_255564_.value().placement(); List<StructureSet.StructureSelectionEntry> list = p_255564_.value().structures(); for(StructureSet.StructureSelectionEntry structureset$structureselectionentry : list) { StructureStart structurestart = p_255934_.getStartForStructure(sectionpos, structureset$structureselectionentry.structure().value(), p_255767_); if (structurestart != null && structurestart.isValid()) { return; } } if (structureplacement.isStructureChunk(p_256505_, chunkpos.x, chunkpos.z)) { if (list.size() == 1) { this.tryGenerateStructure(list.get(0), p_255934_, p_255835_, randomstate, p_255832_, p_256505_.getLevelSeed(), p_255767_, chunkpos, sectionpos); } else { ArrayList<StructureSet.StructureSelectionEntry> arraylist = new ArrayList<>(list.size()); arraylist.addAll(list); WorldgenRandom worldgenrandom = new WorldgenRandom(new LegacyRandomSource(0L)); worldgenrandom.setLargeFeatureSeed(p_256505_.getLevelSeed(), chunkpos.x, chunkpos.z); int i = 0; for(StructureSet.StructureSelectionEntry structureset$structureselectionentry1 : arraylist) { i += structureset$structureselectionentry1.weight(); } while(!arraylist.isEmpty()) { int j = worldgenrandom.nextInt(i); int k = 0; for(StructureSet.StructureSelectionEntry structureset$structureselectionentry2 : arraylist) { j -= structureset$structureselectionentry2.weight(); if (j < 0) { break; } ++k; } StructureSet.StructureSelectionEntry structureset$structureselectionentry3 = arraylist.get(k); if (this.tryGenerateStructure(structureset$structureselectionentry3, p_255934_, p_255835_, randomstate, p_255832_, p_256505_.getLevelSeed(), p_255767_, chunkpos, sectionpos)) { return; } arraylist.remove(k); i -= structureset$structureselectionentry3.weight(); } } } }); } private boolean tryGenerateStructure(StructureSet.StructureSelectionEntry p_223105_, StructureManager p_223106_, RegistryAccess p_223107_, RandomState p_223108_, StructureTemplateManager p_223109_, long p_223110_, ChunkAccess p_223111_, ChunkPos p_223112_, SectionPos p_223113_) { Structure structure = p_223105_.structure().value(); int i = fetchReferences(p_223106_, p_223111_, p_223113_, structure); HolderSet<Biome> holderset = structure.biomes(); Predicate<Holder<Biome>> predicate = holderset::contains; StructureStart structurestart = structure.generate(p_223107_, this, this.biomeSource, p_223108_, p_223109_, p_223110_, p_223112_, i, p_223111_, predicate); if (structurestart.isValid()) { p_223106_.setStartForStructure(p_223113_, structure, structurestart, p_223111_); return true; } else { return false; } } private static int fetchReferences(StructureManager p_223055_, ChunkAccess p_223056_, SectionPos p_223057_, Structure p_223058_) { StructureStart structurestart = p_223055_.getStartForStructure(p_223057_, p_223058_, p_223056_); return structurestart != null ? structurestart.getReferences() : 0; } public void createReferences(WorldGenLevel p_223077_, StructureManager p_223078_, ChunkAccess p_223079_) { int i = 8; ChunkPos chunkpos = p_223079_.getPos(); int j = chunkpos.x; int k = chunkpos.z; int l = chunkpos.getMinBlockX(); int i1 = chunkpos.getMinBlockZ(); SectionPos sectionpos = SectionPos.bottomOf(p_223079_); for(int j1 = j - 8; j1 <= j + 8; ++j1) { for(int k1 = k - 8; k1 <= k + 8; ++k1) { long l1 = ChunkPos.asLong(j1, k1); for(StructureStart structurestart : p_223077_.getChunk(j1, k1).getAllStarts().values()) { try { if (structurestart.isValid() && structurestart.getBoundingBox().intersects(l, i1, l + 15, i1 + 15)) { p_223078_.addReferenceForStructure(sectionpos, structurestart.getStructure(), l1, p_223079_); DebugPackets.sendStructurePacket(p_223077_, structurestart); } } catch (Exception exception) { CrashReport crashreport = CrashReport.forThrowable(exception, "Generating structure reference"); CrashReportCategory crashreportcategory = crashreport.addCategory("Structure"); Optional<? extends Registry<Structure>> optional = p_223077_.registryAccess().registry(Registries.STRUCTURE); crashreportcategory.setDetail("Id", () -> { return optional.map((p_258977_) -> { return p_258977_.getKey(structurestart.getStructure()).toString(); }).orElse("UNKNOWN"); }); crashreportcategory.setDetail("Name", () -> { return BuiltInRegistries.STRUCTURE_TYPE.getKey(structurestart.getStructure().type()).toString(); }); crashreportcategory.setDetail("Class", () -> { return structurestart.getStructure().getClass().getCanonicalName(); }); throw new ReportedException(crashreport); } } } } } public abstract CompletableFuture<ChunkAccess> fillFromNoise(Executor p_223209_, Blender p_223210_, RandomState p_223211_, StructureManager p_223212_, ChunkAccess p_223213_); public abstract int getSeaLevel(); public abstract int getMinY(); public abstract int getBaseHeight(int p_223032_, int p_223033_, Heightmap.Types p_223034_, LevelHeightAccessor p_223035_, RandomState p_223036_); public abstract NoiseColumn getBaseColumn(int p_223028_, int p_223029_, LevelHeightAccessor p_223030_, RandomState p_223031_); public int getFirstFreeHeight(int p_223222_, int p_223223_, Heightmap.Types p_223224_, LevelHeightAccessor p_223225_, RandomState p_223226_) { return this.getBaseHeight(p_223222_, p_223223_, p_223224_, p_223225_, p_223226_); } public int getFirstOccupiedHeight(int p_223236_, int p_223237_, Heightmap.Types p_223238_, LevelHeightAccessor p_223239_, RandomState p_223240_) { return this.getBaseHeight(p_223236_, p_223237_, p_223238_, p_223239_, p_223240_) - 1; } public abstract void addDebugScreenInfo(List<String> p_223175_, RandomState p_223176_, BlockPos p_223177_); /** @deprecated */ @Deprecated public BiomeGenerationSettings getBiomeGenerationSettings(Holder<Biome> p_223132_) { return this.generationSettingsGetter.apply(p_223132_); } }
0
0.914315
1
0.914315
game-dev
MEDIA
0.996378
game-dev
0.905834
1
0.905834
Korchy/blender_autocomplete
1,359
2.83/bpy/ops/boid.py
import sys import typing def rule_add(type: typing.Union[str, int] = 'GOAL'): ''' Add a boid rule to the current boid state :param type: Type * GOAL Goal, Go to assigned object or loudest assigned signal source. * AVOID Avoid, Get away from assigned object or loudest assigned signal source. * AVOID_COLLISION Avoid Collision, Maneuver to avoid collisions with other boids and deflector objects in near future. * SEPARATE Separate, Keep from going through other boids. * FLOCK Flock, Move to center of neighbors and match their velocity. * FOLLOW_LEADER Follow Leader, Follow a boid or assigned object. * AVERAGE_SPEED Average Speed, Maintain speed, flight level or wander. * FIGHT Fight, Go to closest enemy and attack when in range. :type type: typing.Union[str, int] ''' pass def rule_del(): ''' Delete current boid rule ''' pass def rule_move_down(): ''' Move boid rule down in the list ''' pass def rule_move_up(): ''' Move boid rule up in the list ''' pass def state_add(): ''' Add a boid state to the particle system ''' pass def state_del(): ''' Delete current boid state ''' pass def state_move_down(): ''' Move boid state down in the list ''' pass def state_move_up(): ''' Move boid state up in the list ''' pass
0
0.635934
1
0.635934
game-dev
MEDIA
0.938312
game-dev
0.747772
1
0.747772
caelan-douglas/tinybox
11,231
src/Editor.gd
# Tinybox # Copyright (C) 2023-present Caelan Douglas # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # Runs all Editor functions. extends Map class_name Editor @onready var editor_canvas : EditorCanvas = get_tree().current_scene.get_node("EditorCanvas") @onready var editor_tool_inventory : ToolInventory = get_node("EditorToolInventory") @onready var property_editor : PropertyEditor = get_tree().current_scene.get_node("EditorCanvas/LeftPanel/PropertyEditor") var selected_item_properties : Dictionary = {} var test_mode : bool = false func toggle_player_visual() -> void: $CameraTarget/PlayerVisual.visible = !$CameraTarget/PlayerVisual.visible func _ready() -> void: super() await disable_player() # for when a new .tbw map is loaded Global.get_world().connect("tbw_loaded", _on_tbw_loaded) var camera : Camera3D = get_viewport().get_camera_3d() if camera is Camera: camera.set_target($CameraTarget) camera.set_camera_mode(Camera.CameraMode.CONTROLLED) editor_canvas.toggle_player_visual_button.connect("pressed", toggle_player_visual) # load default world Global.get_world().load_tbw("editor_default", false, false) func _on_tbw_loaded() -> void: # Check if map has water for obj in Global.get_world().get_children(): if obj is Water: active_water = obj # update height display water_height = active_water.global_position.y editor_canvas.water_height_adj.set_value(water_height) # Set map height adjusters editor_canvas.death_lim_low_adj.set_value(death_limit_low) editor_canvas.death_lim_hi_adj.set_value(death_limit_high) # Set map respawn adjuster editor_canvas.respawn_time_adj.set_value(respawn_time) # Set gravity adjuster editor_canvas.grav_slider.set_value(gravity_scale) # Update environment text var env : Node = get_environment() if env != null: editor_canvas.env_button.text = JsonHandler.find_entry_in_file(str("tbw_objects/", env.environment_name)) # Update background text var bg : TBWObject = get_background() if bg != null: editor_canvas.bg_button.text = JsonHandler.find_entry_in_file(str("tbw_objects/", bg.tbw_object_type)) # Update song list var song_list : VBoxContainer = editor_canvas.get_node("PauseMenu/ScrollContainer/Sections/World Properties/SongList/List") for old_entry : Node in song_list.get_children(): old_entry.queue_free() for song : String in MusicHandler.ALL_SONGS_LIST: var check := CheckBox.new() # display name check.text = str(JsonHandler.find_entry_in_file(str("songs/", song))) # internal name, ex. mus1 mus2 check.name = song # if loaded map has the song, check it if songs.has(song): check.button_pressed = true song_list.add_child(check) check.connect("toggled", set_song.bind(song)) MusicHandler.switch_song(songs) func get_object_properties_visible() -> bool: return editor_canvas.get_node("PropertyEditor").visible var active_water : Water = null var water_height : float = 42 # in case water is turned off and on again, save the type var water_type : int = 0 @onready var obj_water : PackedScene = preload("res://data/scene/editor_obj/WorldWater.tscn") func toggle_water() -> void: if active_water != null: active_water.queue_free() active_water = null else: var water_inst : Water = obj_water.instantiate() Global.get_world().add_child(water_inst, true) water_inst.global_position = Vector3(0, water_height, 0) active_water = water_inst active_water.set_water_type(water_type) func switch_water_type(update_text_path : String) -> void: if active_water != null: water_type = active_water.water_type water_type += 1 if water_type >= Water.WaterType.size(): water_type = 0 active_water.set_water_type(water_type) if "text" in get_node_or_null(update_text_path): get_node(update_text_path).text = active_water.water_types_as_strings[water_type] func adjust_water_height(amt : float) -> void: water_height = amt if active_water != null: active_water.global_position.y = water_height func adjust_death_limit_low(new_val : int) -> void: death_limit_low = new_val func adjust_death_limit_high(new_val : int) -> void: death_limit_high = new_val func adjust_respawn_time(new_val : int) -> void: respawn_time = new_val func delete_environment() -> void: for obj in Global.get_world().get_children(): if obj is TBWEnvironment: obj.queue_free() func get_environment() -> TBWEnvironment: for obj in Global.get_world().get_children(): if obj is TBWEnvironment: return obj return null func delete_background() -> void: for obj in Global.get_world().get_children(): if obj is TBWObject: if obj.tbw_object_type.begins_with("bg_"): obj.queue_free() func get_background() -> TBWObject: for obj in Global.get_world().get_children(): if obj is TBWObject: if obj.tbw_object_type.begins_with("bg_"): return obj return null func switch_environment() -> void: var env : Node = null for obj in Global.get_world().get_children(): if obj is TBWEnvironment: env = obj var current_env_name := "" if env != null: current_env_name = env.environment_name # delete old environment delete_environment() # get list of envs var env_list : Array[String] = [] for obj : String in SpawnableObjects.objects.keys(): if obj.begins_with("env_"): env_list.append(obj) var current_idx : int = env_list.find(current_env_name) current_idx += 1 if current_idx >= env_list.size(): current_idx = 0 var new_env : Node = SpawnableObjects.objects[env_list[current_idx]].instantiate() Global.get_world().add_child(new_env, true) current_env_name = new_env.environment_name editor_canvas.get_node("PauseMenu/ScrollContainer/Sections/World Properties/Environment").text = JsonHandler.find_entry_in_file(str("tbw_objects/", current_env_name)) func switch_background() -> void: var bg : TBWObject = null for obj in Global.get_world().get_children(): if obj is TBWObject: if obj.tbw_object_type.begins_with("bg_"): bg = obj var current_bg_name := "" if bg != null: current_bg_name = bg.tbw_object_type # delete old delete_background() # get list of envs var bg_list : Array[String] = [] for obj : String in SpawnableObjects.objects.keys(): if obj.begins_with("bg_"): bg_list.append(obj) var current_idx : int = bg_list.find(current_bg_name) current_idx += 1 if current_idx >= bg_list.size(): # for "none" background current_idx = -1 var new_bg : Node = null if current_idx > -1: new_bg = SpawnableObjects.objects[bg_list[current_idx]].instantiate() if new_bg != null: Global.get_world().add_child(new_bg, true) current_bg_name = new_bg.tbw_object_type editor_canvas.get_node("PauseMenu/ScrollContainer/Sections/World Properties/Background").text = JsonHandler.find_entry_in_file(str("tbw_objects/", current_bg_name)) else: current_bg_name = "(none)" editor_canvas.get_node("PauseMenu/ScrollContainer/Sections/World Properties/Background").text = "(none)" # Hide player and make them invulnerable. func disable_player() -> int: var player : RigidPlayer = Global.get_player() while player == null: await get_tree().process_frame player = Global.get_player() player.despawn() await get_tree().process_frame return 0 const PLAYER : PackedScene = preload("res://data/scene/character/RigidPlayer.tscn") # show player and game tools. func enable_player(at_spot : Variant = null) -> int: var player : RigidPlayer = PLAYER.instantiate() player.name = str(1) Global.get_world().add_child(player, true) # grace period for invincibility await player.teleported await get_tree().physics_frame if at_spot != null: if at_spot is Vector3: player.teleport(at_spot as Vector3) await get_tree().process_frame return 0 var test_mode_world_name : String = "" func enter_test_mode(world_name : String, at_spot : bool = false) -> void: test_mode = true var player_spot : Variant = null if at_spot: var camera : Camera3D = get_viewport().get_camera_3d() if camera != null: if camera is Camera: player_spot = camera.controlled_cam_pos # save in case player makes any changes / destroys things in testing var ok : Variant = await Global.get_world().save_tbw(str(world_name)) if ok == false: return test_mode_world_name = world_name # load world so that brick groups and joints are generated Global.get_world().load_tbw(str(test_mode_world_name), false, false) while Global.get_world().tbw_loading: await get_tree().process_frame await enable_player(player_spot) editor_canvas.visible = false var game_canvas : CanvasLayer = get_tree().current_scene.get_node("GameCanvas") game_canvas.visible = true game_canvas.hide_pause_menu() Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) UIHandler.show_alert("Changes you make in testing mode will not be saved.\nPause to return to the editor.", 10) func exit_test_mode() -> void: test_mode = false # delete all bombs, rockets, etc in the world for obj in Global.get_world().get_children(): if obj is Bomb || obj is Rocket || obj is ClayBall: obj.queue_free() # don't reset player and cameras Global.get_world().load_tbw(str(test_mode_world_name), false, false) await disable_player() await get_tree().process_frame editor_canvas.visible = true var game_canvas : CanvasLayer = get_tree().current_scene.get_node("GameCanvas") game_canvas.visible = false var camera : Camera3D = get_viewport().get_camera_3d() # in case player died and exited while respawning camera.locked = false if camera is Camera: camera.set_target($CameraTarget) camera.set_camera_mode(Camera.CameraMode.CONTROLLED) # reset fov in case we died camera.fov = UserPreferences.camera_fov editor_canvas.hide_pause_menu() Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) var brick_selected : Brick = null func _process(delta : float) -> void: # don't release / unrelease mouse when editing text if Input.is_action_just_pressed("pause") && !Global.is_text_focused: # if pause menu is shown hide that first if editor_canvas.pause_menu.visible: editor_canvas.hide_pause_menu() Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) elif Input.mouse_mode == Input.MOUSE_MODE_VISIBLE: var focused : Control = get_viewport().gui_get_focus_owner() # release focus of any property editor buttons if focused != null: focused.release_focus() Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) else: Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE) var camera := get_viewport().get_camera_3d() if camera is Camera: editor_canvas.coordinates_tooltip.text =\ str("x", camera.controlled_cam_pos.x, " y", camera.controlled_cam_pos.y, " z", camera.controlled_cam_pos.z)
0
0.948329
1
0.948329
game-dev
MEDIA
0.876747
game-dev
0.938591
1
0.938591
sigeer/RuaMS
3,280
src/Application.Resources/scripts/npc/1052004.js
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Denma the Owner Henesys VIP Eye Change. GMS-like revised by Ronan -- contents found thanks to Mitsune (GamerBewbs), Waltzing, AyumiLove */ var status = 0; var beauty = 0; var price = 1000000; var mface_v = Array(20000, 20001, 20003, 20004, 20005, 20006, 20007, 20008, 20012, 20014, 20015, 20022, 20028, 20031); var fface_v = Array(21000, 21001, 21002, 21003, 21004, 21005, 21006, 21007, 21008, 21012, 21013, 21014, 21023, 21026); var facenew = Array(); function pushIfItemExists(array, itemid) { if ((itemid = cm.getCosmeticItem(itemid)) != -1 && !cm.isCosmeticEquipped(itemid)) { array.push(itemid); } } function start() { status = -1; action(1, 0, 0); } function action(mode, type, selection) { if (mode < 1) // disposing issue with stylishs found thanks to Vcoc { cm.dispose(); } else { if (mode == 1) { status++; } else { status--; } if (status == 0) { cm.sendSimple("嗨,你好!欢迎来到射手村整形外科!你想把你的脸变成全新的样子吗?使用 #b#t5152001##k,你可以让我们来照顾剩下的事情,拥有你一直想要的脸~!\r\n#L2#整形外科:#i5152001##t5152001##l"); } else if (status == 1) { if (selection == 2) { facenew = Array(); if (cm.getPlayer().getGender() == 0) { for (var i = 0; i < mface_v.length; i++) { pushIfItemExists(facenew, mface_v[i] + cm.getPlayer().getFace() % 1000 - (cm.getPlayer().getFace() % 100)); } } if (cm.getPlayer().getGender() == 1) { for (var i = 0; i < fface_v.length; i++) { pushIfItemExists(facenew, fface_v[i] + cm.getPlayer().getFace() % 1000 - (cm.getPlayer().getFace() % 100)); } } cm.sendStyle("让我看看... 我完全可以把你的脸变成新的。 你不想试试吗? 使用 #b#t5152001##k, 花点时间选择你可以得到你喜欢的面孔。", facenew); } } else if (status == 2) { cm.dispose(); if (cm.haveItem(5152001) == true) { cm.gainItem(5152001, -1); cm.setFace(facenew[selection]); cm.sendOk("享受你的新面容吧!"); } else { cm.sendOk("嗯...看起来你没有这个地方专门的优惠券。很抱歉要说这个,但没有优惠券,你就不能进行整形手术了..."); } } } }
0
0.588832
1
0.588832
game-dev
MEDIA
0.453489
game-dev
0.800138
1
0.800138
Kaedrin/nwn2cc
1,277
Source/KaedPRCPack_v1.42.1_Override_Dialogtlk/Scripts/cmi_s0_skincact.nss
//:://///////////////////////////////////////////// //:: Skin of the Cactus //:: cmi_s0_skincact //:: Purpose: //:: Created By: Kaedrin (Matt) //:: Created On: January 23, 2010 //::////////////////////////////////////////////// #include "cmi_ginc_spells" #include "x2_inc_spellhook" #include "x0_i0_spells" void main() { if (!X2PreSpellCastCode()) { // If code within the PreSpellCastHook (i.e. UMD) reports FALSE, do not run this spell return; } object oTarget = GetSpellTargetObject(); int nSpellId = GetSpellId(); int nCasterLvl = GetPalRngCasterLevel(); float fDuration = TurnsToSeconds( nCasterLvl ) * 10; fDuration = ApplyMetamagicDurationMods(fDuration); int nBonus = 3; nBonus += (nCasterLvl - 7) / 3; if (nBonus > 5) nBonus = 5; effect eAC = EffectACIncrease(nBonus, AC_NATURAL_BONUS); effect eDS = EffectDamageShield(0, DAMAGE_BONUS_1d6, DAMAGE_TYPE_PIERCING); effect eVis = EffectVisualEffect(VFX_DUR_SPELL_PREMONITION); effect eLink = EffectLinkEffects(eAC, eDS); eLink = EffectLinkEffects(eLink, eVis); RemoveEffectsFromSpell(oTarget, nSpellId); SignalEvent(oTarget, EventSpellCastAt(OBJECT_SELF, nSpellId, FALSE)); ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eLink, oTarget, fDuration); }
0
0.605318
1
0.605318
game-dev
MEDIA
0.907719
game-dev
0.895916
1
0.895916
PipeWire/wireplumber
2,544
lib/wp/iterator.h
/* WirePlumber * * Copyright © 2020 Collabora Ltd. * @author Julian Bouzas <julian.bouzas@collabora.com> * * SPDX-License-Identifier: MIT */ #ifndef __WIREPLUMBER_ITERATOR_H__ #define __WIREPLUMBER_ITERATOR_H__ #include <gio/gio.h> #include "defs.h" G_BEGIN_DECLS /*! * \brief A function to be passed to wp_iterator_fold() * \param item the item to fold * \param ret the value collecting the result * \param data data passed to wp_iterator_fold() * \returns TRUE if the fold should continue, FALSE if it should stop. * \ingroup wpiterator */ typedef gboolean (*WpIteratorFoldFunc) (const GValue *item, GValue *ret, gpointer data); /*! * \brief A function that is called by wp_iterator_foreach(). * \param item the item * \param data the data passed to wp_iterator_foreach() * \ingroup wpiterator */ typedef void (*WpIteratorForeachFunc) (const GValue *item, gpointer data); /*! * \brief The WpIterator GType * \ingroup wpiterator */ #define WP_TYPE_ITERATOR (wp_iterator_get_type ()) WP_API GType wp_iterator_get_type (void); typedef struct _WpIterator WpIterator; typedef struct _WpIteratorMethods WpIteratorMethods; /*! * \brief The version to set to _WpIteratorMethods::version. * This allows future expansion of the struct * \ingroup wpiterator */ #define WP_ITERATOR_METHODS_VERSION 0U struct _WpIteratorMethods { guint32 version; void (*reset) (WpIterator *self); gboolean (*next) (WpIterator *self, GValue *item); gboolean (*fold) (WpIterator *self, WpIteratorFoldFunc func, GValue *ret, gpointer data); gboolean (*foreach) (WpIterator *self, WpIteratorForeachFunc func, gpointer data); void (*finalize) (WpIterator *self); }; /* ref count */ WP_API WpIterator *wp_iterator_ref (WpIterator *self); WP_API void wp_iterator_unref (WpIterator *self); /* iteration api */ WP_API void wp_iterator_reset (WpIterator *self); WP_API gboolean wp_iterator_next (WpIterator *self, GValue *item); WP_API gboolean wp_iterator_fold (WpIterator *self, WpIteratorFoldFunc func, GValue *ret, gpointer data); WP_API gboolean wp_iterator_foreach (WpIterator *self, WpIteratorForeachFunc func, gpointer data); /* constructors */ WP_API WpIterator * wp_iterator_new_ptr_array (GPtrArray * items, GType item_type); WP_API WpIterator * wp_iterator_new (const WpIteratorMethods * methods, size_t user_size); /* private */ WP_API gpointer wp_iterator_get_user_data (WpIterator * self); G_DEFINE_AUTOPTR_CLEANUP_FUNC (WpIterator, wp_iterator_unref) G_END_DECLS #endif
0
0.80264
1
0.80264
game-dev
MEDIA
0.114993
game-dev
0.772122
1
0.772122
skyra-project/skyra
6,338
src/commands/Management/AutoModeration/automod-words.ts
import { readSettingsWordFilterRegExp, writeSettingsTransaction, type GuildDataValue, type ReadonlyGuildData, type SchemaDataKey } from '#lib/database'; import { LanguageKeys } from '#lib/i18n/languageKeys'; import { getSupportedUserLanguageT } from '#lib/i18n/translate'; import { AutoModerationCommand } from '#lib/moderation'; import { IncomingType, OutgoingType } from '#lib/moderation/workers'; import type { SkyraSubcommand } from '#lib/structures'; import type { GuildMessage } from '#lib/types'; import { addAutomaticFields } from '#utils/functions'; import { chatInputApplicationCommandMention, type SlashCommandBuilder, type SlashCommandSubcommandBuilder } from '@discordjs/builders'; import { ApplyOptions } from '@sapphire/decorators'; import { send } from '@sapphire/plugin-editable-commands'; import { applyLocalizedBuilder, type TFunction } from '@sapphire/plugin-i18next'; import { isNullishOrEmpty, type Awaitable } from '@sapphire/utilities'; import { remove as removeConfusables } from 'confusables'; import { inlineCode, MessageFlags, type Guild } from 'discord.js'; const Root = LanguageKeys.Commands.AutoModeration; @ApplyOptions<AutoModerationCommand.Options>({ aliases: ['filter-mode', 'word-filter-mode', 'manage-filter', 'filter'], description: Root.WordsDescription, localizedNameKey: Root.WordsName, subcommands: [ { name: 'add', chatInputRun: 'chatInputRunAdd', messageRun: 'messageRunAdd' }, { name: 'remove', chatInputRun: 'chatInputRunRemove', messageRun: 'messageRunRemove' } ], resetKeys: [{ key: Root.OptionsKeyWords, value: 'words' }], adderPropertyName: 'words', keyEnabled: 'selfmodFilterEnabled', keyOnInfraction: 'selfmodFilterSoftAction', keyPunishment: 'selfmodFilterHardAction', keyPunishmentDuration: 'selfmodFilterHardActionDuration', keyPunishmentThreshold: 'selfmodFilterThresholdMaximum', keyPunishmentThresholdPeriod: 'selfmodFilterThresholdDuration', idHints: [ '1226164940847583322', // skyra production '1277288907414966272' // skyra-beta production ] }) export class UserAutoModerationCommand extends AutoModerationCommand { /** @deprecated */ public messageRunAdd(message: GuildMessage, args: SkyraSubcommand.Args) { const command = chatInputApplicationCommandMention(this.name, 'add', this.getGlobalCommandId()); return send(message, args.t(LanguageKeys.Commands.Shared.DeprecatedMessage, { command })); } /** @deprecated */ public messageRunRemove(message: GuildMessage, args: SkyraSubcommand.Args) { const command = chatInputApplicationCommandMention(this.name, 'remove', this.getGlobalCommandId()); return send(message, args.t(LanguageKeys.Commands.Shared.DeprecatedMessage, { command })); } public async chatInputRunAdd(interaction: AutoModerationCommand.Interaction) { const word = this.#getWord(interaction); const { guild } = interaction; const t = getSupportedUserLanguageT(interaction); using trx = await writeSettingsTransaction(guild); if (await this.#hasWord(trx.settings, word)) { return interaction.reply({ content: t(Root.WordAddFiltered, { word }), flags: MessageFlags.Ephemeral }); } await trx.write({ selfmodFilterRaw: trx.settings.selfmodFilterRaw.concat(word) }).submit(); return interaction.reply({ content: t(Root.EditSuccess), flags: MessageFlags.Ephemeral }); } public async chatInputRunRemove(interaction: AutoModerationCommand.Interaction) { const word = this.#getWord(interaction); const { guild } = interaction; const t = getSupportedUserLanguageT(interaction); using trx = await writeSettingsTransaction(guild); const index = trx.settings.selfmodFilterRaw.indexOf(word); if (index === -1) { return interaction.reply({ content: t(Root.WordRemoveNotFiltered, { word }), flags: MessageFlags.Ephemeral }); } await trx.write({ selfmodFilterRaw: trx.settings.selfmodFilterRaw.toSpliced(index, 1) }).submit(); return interaction.reply({ content: t(Root.EditSuccess), flags: MessageFlags.Ephemeral }); } protected override showEnabled(t: TFunction, settings: ReadonlyGuildData) { const embed = super.showEnabled(t, settings); const words = settings.selfmodFilterRaw; if (isNullishOrEmpty(words)) { const command = chatInputApplicationCommandMention(this.name, 'add', this.getGlobalCommandId()); embed.addFields({ name: t(Root.WordShowListTitleEmpty), value: t(Root.WordShowListEmpty, { command }) }); } else { addAutomaticFields( embed, t(Root.WordShowListTitle, { count: words.length }), t(Root.WordShowList, { words: words.map((word) => inlineCode(word)) }) ); } return embed; } protected override registerSubcommands(builder: SlashCommandBuilder) { return super .registerSubcommands(builder) .addSubcommand((subcommand) => this.registerAddSubcommand(subcommand)) .addSubcommand((subcommand) => this.registerRemoveSubcommand(subcommand)); } protected registerAddSubcommand(subcommand: SlashCommandSubcommandBuilder) { return applyLocalizedBuilder(subcommand, Root.AddName, Root.WordAddDescription) // .addStringOption((option) => applyLocalizedBuilder(option, Root.OptionsWord).setRequired(true).setMinLength(2).setMaxLength(32)); } protected registerRemoveSubcommand(subcommand: SlashCommandSubcommandBuilder) { return applyLocalizedBuilder(subcommand, Root.RemoveName, Root.WordRemoveDescription) // .addStringOption((option) => applyLocalizedBuilder(option, Root.OptionsWord).setRequired(true).setMinLength(2).setMaxLength(32)); } protected override resetGetKeyValuePairFallback(guild: Guild, key: string): Awaitable<readonly [SchemaDataKey, GuildDataValue]> { if (key === 'words') return ['selfmodFilterRaw', []]; return super.resetGetKeyValuePairFallback(guild, key); } #getWord(interaction: AutoModerationCommand.Interaction) { return removeConfusables(interaction.options.getString('word', true).toLowerCase()); } async #hasWord(settings: ReadonlyGuildData, word: string) { const words = settings.selfmodFilterRaw; if (words.includes(word)) return true; const regExp = readSettingsWordFilterRegExp(settings); if (regExp === null) return false; try { const result = await this.container.workers.send({ type: IncomingType.RunRegExp, content: word, regExp }); return result.type === OutgoingType.RegExpMatch; } catch { return false; } } }
0
0.914496
1
0.914496
game-dev
MEDIA
0.380306
game-dev
0.968779
1
0.968779
apostoli-karpouzis/Fishing-Game
5,032
src/species.rs
use bevy::prelude::*; use crate::weather::*; use crate::fishing_view::*; #[derive(Clone, Copy, Debug)] pub enum Behavior { Aggressive, // moves in circles or just random idk yet (higher multiplier for anger) Evasive, // moves away from the rod x y and z (medium multiplier for anger) Passive, // moves slowly / minimal (lower multiplier for anger) Elusive // for the rare fish } //Species struct #[derive(Component)] pub struct Species{ pub name: &'static str, pub hook_pos: Vec2, pub length: (f32, f32), pub width: (f32, f32), pub weight: (f32, f32), pub cd: (f32, f32), pub time_of_day: (usize, usize), pub weather: Weather, //bounds pub depth: (i32, i32), //x, y, z pub position: (i32, i32), //length, width, depth pub bounds: (i32, i32), pub catch_prob: f32, pub obj_pref: (ObstType, i32), pub behavior: Behavior, pub lure_pref: Lure } impl Species { pub const fn new (in_name: &'static str, in_hook_pos: Vec2, in_length: (f32, f32), in_width: (f32, f32), in_weight: (f32,f32), in_cd: (f32, f32), in_tod: (usize, usize), in_weather: Weather, in_depth: (i32, i32), in_position: (i32, i32), in_bounds: (i32, i32), in_catch_prob: f32, in_obj_pref: (ObstType, i32), in_behavior: Behavior, in_lure: Lure) -> Self{ Self{ name: in_name, hook_pos: in_hook_pos, length: in_length, width: in_width, weight: in_weight, cd: in_cd, time_of_day: in_tod, weather: in_weather, depth: in_depth, position: in_position, bounds: in_bounds, catch_prob: in_catch_prob, obj_pref: in_obj_pref, behavior: in_behavior, lure_pref: in_lure } } } //SpeciesTable #[derive(Resource)] pub struct SpeciesTable { sp_table: Vec<Species>, } impl SpeciesTable { pub fn new() -> Self{ let table: Vec<Species> = vec![BASS, CATFISH]; Self{ sp_table: table, } } } //#[derive(Hash, Component, Eq, PartialEq, Debug)] //pub struct FishHash(HashMap<String, Species>); //This but as a hash set /*pub struct SpeciesSet<'a>{ sp_table: Vec<Species<'a>>, } impl<'a> SpeciesTable<'a> { pub fn new() -> Self{ let table: Vec<Species> = vec![BASS, CATFISH]; Self{ sp_table: table, } } } */ //Fish library starts here //Bass pub const BASS: Species = Species::new( "Bass", Vec2::new(-36., 0.), (10.,15.), (5.,7.), (20.,40.), (0.06, 0.94), (0,22), Weather::Sunny, (0,20), (FISHING_ROOM_X as i32 + 90, FISHING_ROOM_Y as i32 + 50), (10,10), 0.5, (ObstType::Pad, 2), Behavior::Evasive, Lure::BOBBER, ); //Catfish pub const CATFISH: Species = Species::new( "Catfish", Vec2::new(-36., 0.), (15.,25.), (10.,12.), (50., 70.), (0.05, 0.89), (0,18), Weather::Rainy, (20,40), (FISHING_ROOM_X as i32, FISHING_ROOM_Y as i32 + 120), (5, 4), 0.4, (ObstType::Fissure, 1), Behavior::Aggressive, Lure::FROG, ); //Tuna pub const TUNA: Species = Species::new( "Tuna", Vec2::new(-36., 0.), (30., 50.), (90., 130.), (90., 230.), (0.37, 0.95), (1, 7), Weather::Thunderstorm, (5, 20), (FISHING_ROOM_X as i32, FISHING_ROOM_Y as i32 + 120), (5,4), 0.5, (ObstType::Pad, 2), Behavior::Passive, Lure::BOBBER, ); //Mahi-mahi pub const MAHIMAHI: Species = Species::new( "Mahi-mahi", Vec2::new(-36., 0.), (50., 80.), (20., 30.), (80., 130.), (0.27, 0.95), (9, 18), Weather::Thunderstorm, (25, 200), (FISHING_ROOM_X as i32, FISHING_ROOM_Y as i32 + 120), (5,4), 0.4, (ObstType::Fissure, 1), Behavior::Aggressive, Lure::FISH, ); //Swordfish pub const SWORDFISH: Species = Species::new( "Swordfish", Vec2::new(-36., 0.), (130., 150.), (50., 70.), (60., 100.), (0.17, 0.95), (18, 24), //is sunny just clear at night? Weather::Sunny, (100, 200), (FISHING_ROOM_X as i32, FISHING_ROOM_Y as i32 + 120), (5,4), 0.4, (ObstType::Fissure, 3), Behavior::Evasive, Lure::FISH, ); //Red Handfsih // our "rare" fish, can only be caught on sea floor during its 1 hour feed time pub const REDHANDFISH: Species = Species::new( "Red Handfish", Vec2::new(-36., 0.), (13., 22.), (5., 7.), (60., 100.), (0.06, 0.12), (20, 21), //is sunny just clear at night? Weather::Sunny, (148, 150), (FISHING_ROOM_X as i32, FISHING_ROOM_Y as i32 + 120), (5,4), 0.1, (ObstType::Fissure, 0), Behavior::Elusive, Lure::FROG, );
0
0.941155
1
0.941155
game-dev
MEDIA
0.446332
game-dev
0.736045
1
0.736045
wwwwwwzx/3DSRNGTool
8,532
3DSRNGTool/Gen7/Wild7.cs
using System.Linq; using PKHeX.Core; using Pk3DSRNGTool.Core; namespace Pk3DSRNGTool { public class Wild7 : WildRNG { private static ulong getrand => RNGPool.getrand64; private static uint getsosrand => SOSRNG.getrand; private static void time_elapse(int n) => RNGPool.time_elapse7(n); private static void Advance(int n) => RNGPool.Advance(n); public byte SpecialEnctr; // !=0 means there is ub/qr present public byte Levelmin, Levelmax; public byte SpecialLevel; public bool CompoundEye; public bool UB; public bool Fishing; public bool SOS; public bool Crabrawler; public byte DelayType; public int DelayTime; private bool IsSpecial; private bool IsMinior => SpecForm[slot] == 774; private bool IsUB => UB && IsSpecial; private bool IsShinyLocked => IsUB && SpecForm[0] <= 800; // Not USUM UB private bool NormalSlot => !IsSpecial || Fishing; protected override int PIDroll_count => (ShinyCharm && !IsShinyLocked ? 3 : 1) + (SOS ? SOSRNG.PIDBonus : 0); // UM v1.2 sub_3A7FE8 protected override void CheckLeadAbility(ulong rand100) { SynchroPass = rand100 >= 50; CuteCharmPass = CuteCharmGender > 0 && rand100 < 67; StaticMagnetPass = StaticMagnet && rand100 >= 50; LevelModifierPass = ModifiedLevel != 0 && rand100 >= 50; } public override void Delay() => RNGPool.WildDelay7(); private void InlineDelay() { switch (DelayType) { case 1: time_elapse(DelayTime - 2); RNGPool.modelnumber--; time_elapse(2); break; default: time_elapse(DelayTime); break; } } public override RNGResult Generate() { ResultW7 rt = new ResultW7(); rt.Level = SpecialLevel; if (Fishing) { IsSpecial = rt.IsSpecial = getrand % 100 >= SpecialEnctr; time_elapse(12); if (IsSpecial) // Predict hooked item { int mark = RNGPool.index; time_elapse(34); rt.SpecialVal = (byte)(getrand % 100); RNGPool.Rewind(mark); // Don't need to put modelstatus back } } else if (SpecialEnctr > 0) IsSpecial = rt.IsSpecial = getrand % 100 < SpecialEnctr; if (SOS) { SOSRNG.Reset(); SOSRNG.Advance(2); // Call Rate Check CheckLeadAbility(getsosrand % 100); if (SOSRNG.Weather && (rt.Slot = slot = SOSRNG.getWeatherSlot(getsosrand % 100)) > 7) // No Electric/Steel Type in weather sos slots rt.IsSpecial = true; else rt.Slot = StaticMagnetPass ? getsmslot(getsosrand) : getslot((int)(getsosrand % 100)); rt.Level = (byte)(getsosrand % (uint)(Levelmax - Levelmin + 1) + Levelmin); FluteBoost = getFluteBoost(getsosrand % 100); ModifyLevel(rt); } else if (Crabrawler) { CheckLeadAbility(getrand % 100); rt.Slot = slot = 1; rt.Level = ModifiedLevel; } else if (NormalSlot) // Normal wild { CheckLeadAbility(getrand % 100); rt.Slot = StaticMagnetPass ? getsmslot(getrand) : getslot((int)(getrand % 100)); rt.Level = (byte)(getrand % (ulong)(Levelmax - Levelmin + 1) + Levelmin); FluteBoost = getFluteBoost(getrand % 100); ModifyLevel(rt); if (IsMinior) rt.Forme = (byte)(getrand % 7); } else // UB or QR { slot = 0; time_elapse(7); CheckLeadAbility(getrand % 100); time_elapse(3); } rt.Species = (short)(SpecForm[slot] & 0x7FF); if (DelayTime > 0) InlineDelay(); if (!SOS) Advance(60); //Encryption Constant rt.EC = (uint)getrand; //PID for (int i = PIDroll_count; i > 0; i--) { rt.PID = (uint)getrand; if (rt.PSV == TSV) { if (IsShinyLocked) rt.PID ^= 0x10000000; else { rt.Shiny = true; rt.SquareShiny = rt.PRV == TRV; } break; } } //IV rt.IVs = new int[6]; for (int i = PerfectIVCount; i > 0;) { int tmp = (int)(getrand % 6); if (rt.IVs[tmp] == 0) { i--; rt.IVs[tmp] = 31; } } for (int i = 0; i < 6; i++) if (rt.IVs[i] == 0) rt.IVs[i] = (int)(getrand & 0x1F); //Ability rt.Ability = (byte)(IsUB ? 1 : (getrand & 1) + 1); //Nature rt.Nature = (rt.Synchronize = SynchroPass) && Synchro_Stat < 25 ? Synchro_Stat : (byte)(getrand % 25); //Gender rt.Gender = RandomGender[slot] ? (CuteCharmPass ? CuteCharmGender : (byte)(getrand % 252 >= Gender[slot] ? 1 : 2)) : Gender[slot]; //Item rt.Item = getHeldItem(SOS ? getsosrand % 100 : NormalSlot ? getrand % 100 : 100, CompoundEye); if (Fishing && rt.IsSpecial) rt.Slot = getHookedItemSlot(rt.SpecialVal); //Fishing item slots else if (SOS) SOSRNG.PostGeneration(rt); // IVs and HA return rt; } public override void Markslots() { IV3 = new bool[SpecForm.Length]; RandomGender = new bool[SpecForm.Length]; Gender = new byte[SpecForm.Length]; var smslot = new int[0].ToList(); for (int i = 0; i < SpecForm.Length; i++) { if (SpecForm[i] == 0) continue; PersonalInfo info = PersonalTable.USUM.getFormeEntry(SpecForm[i] & 0x7FF, SpecForm[i] >> 11); byte genderratio = (byte)info.Gender; IV3[i] = info.EggGroups[0] == 0xF && !Pokemon.BabyMons.Contains(SpecForm[i] & 0x7FF); Gender[i] = FuncUtil.getGenderRatio(genderratio); RandomGender[i] = FuncUtil.IsRandomGender(genderratio); if (Static && info.Types.Contains(Pokemon.electric) || Magnet && info.Types.Contains(Pokemon.steel)) // Collect slots smslot.Add(i); } StaticMagnetSlot = smslot.Select(s => (byte)s).ToArray(); if (0 == (NStaticMagnetSlot = (ulong)smslot.Count)) Static = Magnet = false; if (ModifiedLevel == 101) ModifiedLevel = Levelmax; if (UB) IV3[0] = true; // For UB Template } private byte getsmslot(ulong rand) => slot = StaticMagnetSlot[rand % NStaticMagnetSlot]; public static byte getHeldItem(ulong rand, bool CompoundEye = false) { if (rand < (CompoundEye ? 60u : 50)) return 0; // 50% if (rand < (CompoundEye ? 80u : 55)) return 1; // 5% return 3; // None } public static byte getSpecialRate(int category) { switch (category) { case 1: return 80; case 2: return 50; case 3: return 80; default: return 0; } } public byte[] HookedItemSlot; public byte getHookedItemSlot(byte? rand) { if (rand == null) return 0; if (rand < HookedItemSlot[0]) return 1; if (rand < HookedItemSlot[1]) return 2; return 3; } } public struct FishingSetting { public int basedelay; public bool suctioncups; public int platdelay; public int pkmdelay; } }
0
0.971178
1
0.971178
game-dev
MEDIA
0.618119
game-dev
0.975927
1
0.975927
manisha-v/Number-Cruncher
7,832
Codes/Minor2d/Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/Raycasters/PhysicsRaycaster.cs
using System.Collections.Generic; using UnityEngine.UI; namespace UnityEngine.EventSystems { /// <summary> /// Simple event system using physics raycasts. /// </summary> [AddComponentMenu("Event/Physics Raycaster")] [RequireComponent(typeof(Camera))] /// <summary> /// Raycaster for casting against 3D Physics components. /// </summary> public class PhysicsRaycaster : BaseRaycaster { /// <summary> /// Const to use for clarity when no event mask is set /// </summary> protected const int kNoEventMaskSet = -1; protected Camera m_EventCamera; /// <summary> /// Layer mask used to filter events. Always combined with the camera's culling mask if a camera is used. /// </summary> [SerializeField] protected LayerMask m_EventMask = kNoEventMaskSet; /// <summary> /// The max number of intersections allowed. 0 = allocating version anything else is non alloc. /// </summary> [SerializeField] protected int m_MaxRayIntersections = 0; protected int m_LastMaxRayIntersections = 0; #if PACKAGE_PHYSICS RaycastHit[] m_Hits; #endif protected PhysicsRaycaster() {} public override Camera eventCamera { get { if (m_EventCamera == null) m_EventCamera = GetComponent<Camera>(); return m_EventCamera ?? Camera.main; } } /// <summary> /// Depth used to determine the order of event processing. /// </summary> public virtual int depth { get { return (eventCamera != null) ? (int)eventCamera.depth : 0xFFFFFF; } } /// <summary> /// Event mask used to determine which objects will receive events. /// </summary> public int finalEventMask { get { return (eventCamera != null) ? eventCamera.cullingMask & m_EventMask : kNoEventMaskSet; } } /// <summary> /// Layer mask used to filter events. Always combined with the camera's culling mask if a camera is used. /// </summary> public LayerMask eventMask { get { return m_EventMask; } set { m_EventMask = value; } } /// <summary> /// Max number of ray intersection allowed to be found. /// </summary> /// <remarks> /// A value of zero will represent using the allocating version of the raycast function where as any other value will use the non allocating version. /// </remarks> public int maxRayIntersections { get { return m_MaxRayIntersections; } set { m_MaxRayIntersections = value; } } /// <summary> /// Returns a ray going from camera through the event position and the distance between the near and far clipping planes along that ray. /// </summary> /// <param name="eventData">The pointer event for which we will cast a ray.</param> /// <param name="ray">The ray to use.</param> /// <param name="eventDisplayIndex">The display index used.</param> /// <param name="distanceToClipPlane">The distance between the near and far clipping planes along the ray.</param> /// <returns>True if the operation was successful. false if it was not possible to compute, such as the eventPosition being outside of the view.</returns> protected bool ComputeRayAndDistance(PointerEventData eventData, ref Ray ray, ref int eventDisplayIndex, ref float distanceToClipPlane) { if (eventCamera == null) return false; var eventPosition = Display.RelativeMouseAt(eventData.position); if (eventPosition != Vector3.zero) { // We support multiple display and display identification based on event position. eventDisplayIndex = (int)eventPosition.z; // Discard events that are not part of this display so the user does not interact with multiple displays at once. if (eventDisplayIndex != eventCamera.targetDisplay) return false; } else { // The multiple display system is not supported on all platforms, when it is not supported the returned position // will be all zeros so when the returned index is 0 we will default to the event data to be safe. eventPosition = eventData.position; } // Cull ray casts that are outside of the view rect. (case 636595) if (!eventCamera.pixelRect.Contains(eventPosition)) return false; ray = eventCamera.ScreenPointToRay(eventPosition); // compensate far plane distance - see MouseEvents.cs float projectionDirection = ray.direction.z; distanceToClipPlane = Mathf.Approximately(0.0f, projectionDirection) ? Mathf.Infinity : Mathf.Abs((eventCamera.farClipPlane - eventCamera.nearClipPlane) / projectionDirection); return true; } public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList) { #if PACKAGE_PHYSICS Ray ray = new Ray(); int displayIndex = 0; float distanceToClipPlane = 0; if (!ComputeRayAndDistance(eventData, ref ray, ref displayIndex, ref distanceToClipPlane)) return; int hitCount = 0; if (m_MaxRayIntersections == 0) { if (ReflectionMethodsCache.Singleton.raycast3DAll == null) return; m_Hits = ReflectionMethodsCache.Singleton.raycast3DAll(ray, distanceToClipPlane, finalEventMask); hitCount = m_Hits.Length; } else { if (ReflectionMethodsCache.Singleton.getRaycastNonAlloc == null) return; if (m_LastMaxRayIntersections != m_MaxRayIntersections) { m_Hits = new RaycastHit[m_MaxRayIntersections]; m_LastMaxRayIntersections = m_MaxRayIntersections; } hitCount = ReflectionMethodsCache.Singleton.getRaycastNonAlloc(ray, m_Hits, distanceToClipPlane, finalEventMask); } if (hitCount != 0) { if (hitCount > 1) System.Array.Sort(m_Hits, 0, hitCount, RaycastHitComparer.instance); for (int b = 0, bmax = hitCount; b < bmax; ++b) { var result = new RaycastResult { gameObject = m_Hits[b].collider.gameObject, module = this, distance = m_Hits[b].distance, worldPosition = m_Hits[b].point, worldNormal = m_Hits[b].normal, screenPosition = eventData.position, displayIndex = displayIndex, index = resultAppendList.Count, sortingLayer = 0, sortingOrder = 0 }; resultAppendList.Add(result); } } #endif } #if PACKAGE_PHYSICS private class RaycastHitComparer : IComparer<RaycastHit> { public static RaycastHitComparer instance = new RaycastHitComparer(); public int Compare(RaycastHit x, RaycastHit y) { return x.distance.CompareTo(y.distance); } } #endif } }
0
0.877109
1
0.877109
game-dev
MEDIA
0.898885
game-dev
0.98099
1
0.98099
runceel/Livet
8,688
LivetCask.Generated.Behaviors/GridSplitterSetStateToSourceAction.generated.cs
//このコードはT4 Templateによって自動生成されています。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Windows; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Controls; using System.Windows.Documents; using Microsoft.Xaml.Behaviors; using System.Windows.Controls.Primitives; using System.ComponentModel; using System.Windows.Interop; namespace Livet.Behaviors.ControlBinding.OneWay { /// <summary> /// GridSplitterクラスの、標準ではバインドできないプロパティを表します。 /// </summary> public enum GridSplitterUnbindableCanReadProperty { IsDragging, ActualWidth, ActualHeight, IsInitialized, IsLoaded, HasAnimatedProperties, IsMeasureValid, IsArrangeValid, IsMouseDirectlyOver, IsMouseOver, IsStylusOver, IsKeyboardFocusWithin, IsMouseCaptured, IsMouseCaptureWithin, IsStylusDirectlyOver, IsStylusCaptured, IsStylusCaptureWithin, IsKeyboardFocused, IsInputMethodEnabled, IsFocused, IsVisible, AreAnyTouchesOver, AreAnyTouchesDirectlyOver, AreAnyTouchesCapturedWithin, AreAnyTouchesCaptured, IsSealed } /// <summary> /// GridSplitterクラスのバインドできないプロパティから、値を指定されたソースに反映するためのアクションです。 /// </summary> public class GridSplitterSetStateToSourceAction : TriggerAction<GridSplitter> { public GridSplitterSetStateToSourceAction() { } /// <summary> /// 値を設定したいプロパティを取得または設定します。 /// </summary> public GridSplitterUnbindableCanReadProperty Property { get { return (GridSplitterUnbindableCanReadProperty)GetValue(PropertyProperty); } set { SetValue(PropertyProperty, value); } } public static readonly DependencyProperty PropertyProperty = DependencyProperty.Register("Property", typeof(GridSplitterUnbindableCanReadProperty), typeof(GridSplitterSetStateToSourceAction), new PropertyMetadata()); /// <summary> /// Propertyプロパティで指定されたプロパティから値が設定されるソースを取得または設定します。 /// </summary> [Bindable(BindableSupport.Default,BindingDirection.TwoWay)] public object Source { get { return (object)GetValue(SourceProperty); } set { SetValue(SourceProperty, value); } } public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(object), typeof(GridSplitterSetStateToSourceAction), new PropertyMetadata(null)); protected override void Invoke(object parameter) { switch (Property) { case GridSplitterUnbindableCanReadProperty.IsDragging: if((System.Boolean)Source != AssociatedObject.IsDragging) { Source = AssociatedObject.IsDragging; } break; case GridSplitterUnbindableCanReadProperty.ActualWidth: if((System.Double)Source != AssociatedObject.ActualWidth) { Source = AssociatedObject.ActualWidth; } break; case GridSplitterUnbindableCanReadProperty.ActualHeight: if((System.Double)Source != AssociatedObject.ActualHeight) { Source = AssociatedObject.ActualHeight; } break; case GridSplitterUnbindableCanReadProperty.IsInitialized: if((System.Boolean)Source != AssociatedObject.IsInitialized) { Source = AssociatedObject.IsInitialized; } break; case GridSplitterUnbindableCanReadProperty.IsLoaded: if((System.Boolean)Source != AssociatedObject.IsLoaded) { Source = AssociatedObject.IsLoaded; } break; case GridSplitterUnbindableCanReadProperty.HasAnimatedProperties: if((System.Boolean)Source != AssociatedObject.HasAnimatedProperties) { Source = AssociatedObject.HasAnimatedProperties; } break; case GridSplitterUnbindableCanReadProperty.IsMeasureValid: if((System.Boolean)Source != AssociatedObject.IsMeasureValid) { Source = AssociatedObject.IsMeasureValid; } break; case GridSplitterUnbindableCanReadProperty.IsArrangeValid: if((System.Boolean)Source != AssociatedObject.IsArrangeValid) { Source = AssociatedObject.IsArrangeValid; } break; case GridSplitterUnbindableCanReadProperty.IsMouseDirectlyOver: if((System.Boolean)Source != AssociatedObject.IsMouseDirectlyOver) { Source = AssociatedObject.IsMouseDirectlyOver; } break; case GridSplitterUnbindableCanReadProperty.IsMouseOver: if((System.Boolean)Source != AssociatedObject.IsMouseOver) { Source = AssociatedObject.IsMouseOver; } break; case GridSplitterUnbindableCanReadProperty.IsStylusOver: if((System.Boolean)Source != AssociatedObject.IsStylusOver) { Source = AssociatedObject.IsStylusOver; } break; case GridSplitterUnbindableCanReadProperty.IsKeyboardFocusWithin: if((System.Boolean)Source != AssociatedObject.IsKeyboardFocusWithin) { Source = AssociatedObject.IsKeyboardFocusWithin; } break; case GridSplitterUnbindableCanReadProperty.IsMouseCaptured: if((System.Boolean)Source != AssociatedObject.IsMouseCaptured) { Source = AssociatedObject.IsMouseCaptured; } break; case GridSplitterUnbindableCanReadProperty.IsMouseCaptureWithin: if((System.Boolean)Source != AssociatedObject.IsMouseCaptureWithin) { Source = AssociatedObject.IsMouseCaptureWithin; } break; case GridSplitterUnbindableCanReadProperty.IsStylusDirectlyOver: if((System.Boolean)Source != AssociatedObject.IsStylusDirectlyOver) { Source = AssociatedObject.IsStylusDirectlyOver; } break; case GridSplitterUnbindableCanReadProperty.IsStylusCaptured: if((System.Boolean)Source != AssociatedObject.IsStylusCaptured) { Source = AssociatedObject.IsStylusCaptured; } break; case GridSplitterUnbindableCanReadProperty.IsStylusCaptureWithin: if((System.Boolean)Source != AssociatedObject.IsStylusCaptureWithin) { Source = AssociatedObject.IsStylusCaptureWithin; } break; case GridSplitterUnbindableCanReadProperty.IsKeyboardFocused: if((System.Boolean)Source != AssociatedObject.IsKeyboardFocused) { Source = AssociatedObject.IsKeyboardFocused; } break; case GridSplitterUnbindableCanReadProperty.IsInputMethodEnabled: if((System.Boolean)Source != AssociatedObject.IsInputMethodEnabled) { Source = AssociatedObject.IsInputMethodEnabled; } break; case GridSplitterUnbindableCanReadProperty.IsFocused: if((System.Boolean)Source != AssociatedObject.IsFocused) { Source = AssociatedObject.IsFocused; } break; case GridSplitterUnbindableCanReadProperty.IsVisible: if((System.Boolean)Source != AssociatedObject.IsVisible) { Source = AssociatedObject.IsVisible; } break; case GridSplitterUnbindableCanReadProperty.AreAnyTouchesOver: if((System.Boolean)Source != AssociatedObject.AreAnyTouchesOver) { Source = AssociatedObject.AreAnyTouchesOver; } break; case GridSplitterUnbindableCanReadProperty.AreAnyTouchesDirectlyOver: if((System.Boolean)Source != AssociatedObject.AreAnyTouchesDirectlyOver) { Source = AssociatedObject.AreAnyTouchesDirectlyOver; } break; case GridSplitterUnbindableCanReadProperty.AreAnyTouchesCapturedWithin: if((System.Boolean)Source != AssociatedObject.AreAnyTouchesCapturedWithin) { Source = AssociatedObject.AreAnyTouchesCapturedWithin; } break; case GridSplitterUnbindableCanReadProperty.AreAnyTouchesCaptured: if((System.Boolean)Source != AssociatedObject.AreAnyTouchesCaptured) { Source = AssociatedObject.AreAnyTouchesCaptured; } break; case GridSplitterUnbindableCanReadProperty.IsSealed: if((System.Boolean)Source != AssociatedObject.IsSealed) { Source = AssociatedObject.IsSealed; } break; } } } }
0
0.941377
1
0.941377
game-dev
MEDIA
0.640134
game-dev
0.972281
1
0.972281
Kagamia/WzComparerR2
48,261
WzComparerR2.Avatar/UI/AvatarForm.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using DevComponents.DotNetBar; using DevComponents.Editors; using DevComponents.DotNetBar.Controls; using WzComparerR2.Common; using WzComparerR2.WzLib; using WzComparerR2.PluginBase; using WzComparerR2.Config; namespace WzComparerR2.Avatar.UI { internal partial class AvatarForm : DevComponents.DotNetBar.OfficeForm { public AvatarForm() { InitializeComponent(); this.avatar = new AvatarCanvas(); this.animator = new Animator(); btnReset_Click(btnReset, EventArgs.Empty); FillWeaponIdx(); FillEarSelection(); } public SuperTabControlPanel GetTabPanel() { this.TopLevel = false; this.Dock = DockStyle.Fill; this.FormBorderStyle = FormBorderStyle.None; this.DoubleBuffered = true; var pnl = new SuperTabControlPanel(); pnl.Controls.Add(this); pnl.Padding = new System.Windows.Forms.Padding(1); this.Visible = true; return pnl; } public Entry PluginEntry { get; set; } AvatarCanvas avatar; bool inited; string partsTag; bool suspendUpdate; bool needUpdate; Animator animator; /// <summary> /// wz1节点选中事件。 /// </summary> public void OnSelectedNode1Changed(object sender, WzNodeEventArgs e) { if (PluginEntry.Context.SelectedTab != PluginEntry.Tab || e.Node == null || this.btnLock.Checked) { return; } Wz_File file = e.Node.GetNodeWzFile(); if (file == null) { return; } switch (file.Type) { case Wz_Type.Character: //读取装备 Wz_Image wzImg = e.Node.GetValue<Wz_Image>(); if (wzImg != null && wzImg.TryExtract()) { this.SuspendUpdateDisplay(); LoadPart(wzImg.Node); this.ResumeUpdateDisplay(); } break; } } public void OnWzClosing(object sender, WzStructureEventArgs e) { bool hasChanged = false; for (int i = 0; i < avatar.Parts.Length; i++) { var part = avatar.Parts[i]; if (part != null) { var wzFile = part.Node.GetNodeWzFile(); if (wzFile != null && e.WzStructure.wz_files.Contains(wzFile))//将要关闭文件 移除 { avatar.Parts[i] = null; hasChanged = true; } } } if (hasChanged) { this.FillAvatarParts(); UpdateDisplay(); } } /// <summary> /// 初始化纸娃娃资源。 /// </summary> private bool AvatarInit() { this.inited = this.avatar.LoadZ() && this.avatar.LoadActions() && this.avatar.LoadEmotions(); if (this.inited) { this.FillBodyAction(); this.FillEmotion(); } return this.inited; } /// <summary> /// 加载装备部件。 /// </summary> /// <param name="imgNode"></param> private void LoadPart(Wz_Node imgNode) { if (!this.inited && !this.AvatarInit() && imgNode == null) { return; } AvatarPart part = this.avatar.AddPart(imgNode); if (part != null) { OnNewPartAdded(part); FillAvatarParts(); UpdateDisplay(); } } private void OnNewPartAdded(AvatarPart part) { if (part == null) { return; } if (part == avatar.Body) //同步head { int headID = 10000 + part.ID.Value % 10000; if (avatar.Head == null || avatar.Head.ID != headID) { var headImgNode = PluginBase.PluginManager.FindWz(string.Format("Character\\{0:D8}.img", headID)); if (headImgNode != null) { this.avatar.AddPart(headImgNode); } } } else if (part == avatar.Head) //同步body { int bodyID = part.ID.Value % 10000; if (avatar.Body == null || avatar.Body.ID != bodyID) { var bodyImgNode = PluginBase.PluginManager.FindWz(string.Format("Character\\{0:D8}.img", bodyID)); if (bodyImgNode != null) { this.avatar.AddPart(bodyImgNode); } } } else if (part == avatar.Face) //同步表情 { this.avatar.LoadEmotions(); FillEmotion(); } else if (part == avatar.Taming) //同步座驾动作 { this.avatar.LoadTamingActions(); FillTamingAction(); SetTamingDefaultBodyAction(); SetTamingDefault(); } else if (part == avatar.Weapon) //同步武器类型 { FillWeaponTypes(); } else if (part == avatar.Pants || part == avatar.Coat) //隐藏套装 { if (avatar.Longcoat != null) { avatar.Longcoat.Visible = false; } } else if (part == avatar.Longcoat) //还是。。隐藏套装 { if (avatar.Pants != null && avatar.Pants.Visible || avatar.Coat != null && avatar.Coat.Visible) { avatar.Longcoat.Visible = false; } } } private void SuspendUpdateDisplay() { this.suspendUpdate = true; this.needUpdate = false; } private void ResumeUpdateDisplay() { if (this.suspendUpdate) { this.suspendUpdate = false; if (this.needUpdate) { this.UpdateDisplay(); } } } /// <summary> /// 更新画布。 /// </summary> private void UpdateDisplay() { if (suspendUpdate) { this.needUpdate = true; return; } string newPartsTag = GetAllPartsTag(); if (this.partsTag != newPartsTag) { this.partsTag = newPartsTag; this.avatarContainer1.ClearAllCache(); } ComboItem selectedItem; //同步角色动作 selectedItem = this.cmbActionBody.SelectedItem as ComboItem; this.avatar.ActionName = selectedItem != null ? selectedItem.Text : null; //同步表情 selectedItem = this.cmbEmotion.SelectedItem as ComboItem; this.avatar.EmotionName = selectedItem != null ? selectedItem.Text : null; //同步骑宠动作 selectedItem = this.cmbActionTaming.SelectedItem as ComboItem; this.avatar.TamingActionName = selectedItem != null ? selectedItem.Text : null; //获取动作帧 this.GetSelectedBodyFrame(out int bodyFrame, out _); this.GetSelectedEmotionFrame(out int emoFrame, out _); this.GetSelectedTamingFrame(out int tamingFrame, out _); //获取武器状态 selectedItem = this.cmbWeaponType.SelectedItem as ComboItem; this.avatar.WeaponType = selectedItem != null ? Convert.ToInt32(selectedItem.Text) : 0; selectedItem = this.cmbWeaponIdx.SelectedItem as ComboItem; this.avatar.WeaponIndex = selectedItem != null ? Convert.ToInt32(selectedItem.Text) : 0; //获取耳朵状态 selectedItem = this.cmbEar.SelectedItem as ComboItem; this.avatar.EarType = selectedItem != null ? Convert.ToInt32(selectedItem.Text) : 0; if (bodyFrame < 0 && emoFrame < 0 && tamingFrame < 0) { return; } string actionTag = string.Format("{0}:{1},{2}:{3},{4}:{5},{6},{7},{8},{9},{10}", this.avatar.ActionName, bodyFrame, this.avatar.EmotionName, emoFrame, this.avatar.TamingActionName, tamingFrame, this.avatar.HairCover ? 1 : 0, this.avatar.ShowHairShade ? 1 : 0, this.avatar.EarType, this.avatar.WeaponType, this.avatar.WeaponIndex); if (!avatarContainer1.HasCache(actionTag)) { try { var actionFrames = avatar.GetActionFrames(avatar.ActionName); var bone = avatar.CreateFrame(bodyFrame, emoFrame, tamingFrame); var layers = avatar.CreateFrameLayers(bone); avatarContainer1.AddCache(actionTag, layers); } catch { } } avatarContainer1.SetKey(actionTag); } private string GetAllPartsTag() { string[] partsID = new string[avatar.Parts.Length]; for (int i = 0; i < avatar.Parts.Length; i++) { var part = avatar.Parts[i]; if (part != null && part.Visible) { partsID[i] = part.ID.ToString(); } } return string.Join(",", partsID); } void AddPart(string imgPath) { Wz_Node imgNode = PluginManager.FindWz(imgPath); if (imgNode != null) { this.avatar.AddPart(imgNode); } } private void SelectBodyAction(string actionName) { for (int i = 0; i < cmbActionBody.Items.Count; i++) { ComboItem item = cmbActionBody.Items[i] as ComboItem; if (item != null && item.Text == actionName) { cmbActionBody.SelectedIndex = i; return; } } } private void SelectEmotion(string emotionName) { for (int i = 0; i < cmbEmotion.Items.Count; i++) { ComboItem item = cmbEmotion.Items[i] as ComboItem; if (item != null && item.Text == emotionName) { cmbEmotion.SelectedIndex = i; return; } } } #region 同步界面 private void FillBodyAction() { var oldSelection = cmbActionBody.SelectedItem as ComboItem; int? newSelection = null; cmbActionBody.BeginUpdate(); cmbActionBody.Items.Clear(); foreach (var action in this.avatar.Actions) { ComboItem cmbItem = new ComboItem(action.Name); switch (action.Level) { case 0: cmbItem.FontStyle = FontStyle.Bold; cmbItem.ForeColor = Color.Indigo; break; case 1: cmbItem.ForeColor = Color.Indigo; break; } cmbItem.Tag = action; cmbActionBody.Items.Add(cmbItem); if (newSelection == null && oldSelection != null) { if (cmbItem.Text == oldSelection.Text) { newSelection = cmbActionBody.Items.Count - 1; } } } if (cmbActionBody.Items.Count > 0) { cmbActionBody.SelectedIndex = newSelection ?? 0; } cmbActionBody.EndUpdate(); } private void FillEmotion() { FillComboItems(cmbEmotion, avatar.Emotions); } private void FillTamingAction() { FillComboItems(cmbActionTaming, avatar.TamingActions); } private void FillWeaponTypes() { List<int> weaponTypes = avatar.GetCashWeaponTypes(); FillComboItems(cmbWeaponType, weaponTypes.ConvertAll(i => i.ToString())); } private void SetTamingDefaultBodyAction() { string actionName; var tamingAction = (this.cmbActionTaming.SelectedItem as ComboItem)?.Text; switch (tamingAction) { case "ladder": case "rope": actionName = tamingAction; break; default: actionName = "sit"; break; } SelectBodyAction(actionName); } private void SetTamingDefault() { if (this.avatar.Taming != null) { var tamingAction = (this.cmbActionTaming.SelectedItem as ComboItem)?.Text; if (tamingAction != null) { string forceAction = this.avatar.Taming.Node.FindNodeByPath($@"characterAction\{tamingAction}").GetValueEx<string>(null); if (forceAction != null) { this.SelectBodyAction(forceAction); } string forceEmotion = this.avatar.Taming.Node.FindNodeByPath($@"characterEmotion\{tamingAction}").GetValueEx<string>(null); if (forceEmotion != null) { this.SelectEmotion(forceEmotion); } } } } /// <summary> /// 更新当前显示部件列表。 /// </summary> private void FillAvatarParts() { itemPanel1.BeginUpdate(); itemPanel1.Items.Clear(); foreach (var part in avatar.Parts) { if (part != null) { var btn = new AvatarPartButtonItem(); var stringLinker = this.PluginEntry.Context.DefaultStringLinker; StringResult sr; string text; if (part.ID != null && stringLinker.StringEqp.TryGetValue(part.ID.Value, out sr)) { text = string.Format("{0}\r\n{1}", sr.Name, part.ID); } else { text = string.Format("{0}\r\n{1}", "(null)", part.ID == null ? "-" : part.ID.ToString()); } btn.Text = text; btn.SetIcon(part.Icon.Bitmap); btn.Tag = part; btn.Checked = part.Visible; btn.btnItemShow.Click += BtnItemShow_Click; btn.btnItemDel.Click += BtnItemDel_Click; btn.CheckedChanged += Btn_CheckedChanged; itemPanel1.Items.Add(btn); } } itemPanel1.EndUpdate(); } private void BtnItemShow_Click(object sender, EventArgs e) { var btn = (sender as BaseItem).Parent as AvatarPartButtonItem; if (btn != null) { btn.Checked = !btn.Checked; } } private void BtnItemDel_Click(object sender, EventArgs e) { var btn = (sender as BaseItem).Parent as AvatarPartButtonItem; if (btn != null) { var part = btn.Tag as AvatarPart; if (part != null) { int index = Array.IndexOf(this.avatar.Parts, part); if (index > -1) { this.avatar.Parts[index] = null; this.FillAvatarParts(); this.UpdateDisplay(); } } } } private void Btn_CheckedChanged(object sender, EventArgs e) { var btn = sender as AvatarPartButtonItem; if (btn != null) { var part = btn.Tag as AvatarPart; if (part != null) { part.Visible = btn.Checked; this.UpdateDisplay(); } } } private void FillBodyActionFrame() { ComboItem actionItem = cmbActionBody.SelectedItem as ComboItem; if (actionItem != null) { var frames = avatar.GetActionFrames(actionItem.Text); FillComboItems(cmbBodyFrame, frames); } else { cmbBodyFrame.Items.Clear(); } } private void FillEmotionFrame() { ComboItem emotionItem = cmbEmotion.SelectedItem as ComboItem; if (emotionItem != null) { var frames = avatar.GetFaceFrames(emotionItem.Text); FillComboItems(cmbEmotionFrame, frames); } else { cmbEmotionFrame.Items.Clear(); } } private void FillTamingActionFrame() { ComboItem actionItem = cmbActionTaming.SelectedItem as ComboItem; if (actionItem != null) { var frames = avatar.GetTamingFrames(actionItem.Text); FillComboItems(cmbTamingFrame, frames); } else { cmbTamingFrame.Items.Clear(); } } private void FillWeaponIdx() { FillComboItems(cmbWeaponIdx, 0, 4); } private void FillEarSelection() { FillComboItems(cmbEar, 0, 4); } private void FillComboItems(ComboBoxEx comboBox, int start, int count) { List<ComboItem> items = new List<ComboItem>(count); for (int i = 0; i < count; i++) { ComboItem item = new ComboItem(); item.Text = (start + i).ToString(); items.Add(item); } FillComboItems(comboBox, items); } private void FillComboItems(ComboBoxEx comboBox, IEnumerable<string> items) { List<ComboItem> _items = new List<ComboItem>(); foreach (var itemText in items) { ComboItem item = new ComboItem(); item.Text = itemText; _items.Add(item); } FillComboItems(comboBox, _items); } private void FillComboItems(ComboBoxEx comboBox, IEnumerable<ActionFrame> frames) { List<ComboItem> items = new List<ComboItem>(); int i = 0; foreach (var f in frames) { ComboItem item = new ComboItem(); item.Text = (i++).ToString(); item.Tag = f; items.Add(item); } FillComboItems(comboBox, items); } private void FillComboItems(ComboBoxEx comboBox, IEnumerable<ComboItem> items) { //保持原有选项 var oldSelection = comboBox.SelectedItem as ComboItem; int? newSelection = null; comboBox.BeginUpdate(); comboBox.Items.Clear(); foreach (var item in items) { comboBox.Items.Add(item); if (newSelection == null && oldSelection != null) { if (item.Text == oldSelection.Text) { newSelection = comboBox.Items.Count - 1; } } } //恢复原有选项 if (comboBox.Items.Count > 0) { comboBox.SelectedIndex = newSelection ?? 0; } comboBox.EndUpdate(); } private bool GetSelectedActionFrame(ComboBoxEx comboBox, out int frameIndex, out ActionFrame actionFrame) { var selectedItem = comboBox.SelectedItem as ComboItem; if (selectedItem != null && int.TryParse(selectedItem.Text, out frameIndex) && selectedItem?.Tag is ActionFrame _actionFrame) { actionFrame = _actionFrame; return true; } else { frameIndex = -1; actionFrame = null; return false; } } private bool GetSelectedBodyFrame(out int frameIndex, out ActionFrame actionFrame) { return this.GetSelectedActionFrame(this.cmbBodyFrame, out frameIndex, out actionFrame); } private bool GetSelectedEmotionFrame(out int frameIndex, out ActionFrame actionFrame) { return this.GetSelectedActionFrame(this.cmbEmotionFrame, out frameIndex, out actionFrame); } private bool GetSelectedTamingFrame(out int frameIndex, out ActionFrame actionFrame) { return this.GetSelectedActionFrame(this.cmbTamingFrame, out frameIndex, out actionFrame); } #endregion private void cmbActionBody_SelectedIndexChanged(object sender, EventArgs e) { this.SuspendUpdateDisplay(); FillBodyActionFrame(); this.ResumeUpdateDisplay(); UpdateDisplay(); } private void cmbEmotion_SelectedIndexChanged(object sender, EventArgs e) { this.SuspendUpdateDisplay(); FillEmotionFrame(); this.ResumeUpdateDisplay(); UpdateDisplay(); } private void cmbActionTaming_SelectedIndexChanged(object sender, EventArgs e) { this.SuspendUpdateDisplay(); FillTamingActionFrame(); SetTamingDefaultBodyAction(); SetTamingDefault(); this.ResumeUpdateDisplay(); UpdateDisplay(); } private void cmbBodyFrame_SelectedIndexChanged(object sender, EventArgs e) { UpdateDisplay(); } private void cmbEmotionFrame_SelectedIndexChanged(object sender, EventArgs e) { UpdateDisplay(); } private void cmbTamingFrame_SelectedIndexChanged(object sender, EventArgs e) { UpdateDisplay(); } private void cmbWeaponType_SelectedIndexChanged(object sender, EventArgs e) { UpdateDisplay(); } private void cmbWeaponIdx_SelectedIndexChanged(object sender, EventArgs e) { UpdateDisplay(); } private void cmbEar_SelectedIndexChanged(object sender, EventArgs e) { UpdateDisplay(); } private void chkBodyPlay_CheckedChanged(object sender, EventArgs e) { if (chkBodyPlay.Checked) { if (!this.timer1.Enabled) { AnimateStart(); } if (this.GetSelectedBodyFrame(out _, out var actionFrame) && actionFrame.AbsoluteDelay > 0) { this.animator.BodyDelay = actionFrame.AbsoluteDelay; } } else { this.animator.BodyDelay = -1; TimerEnabledCheck(); } } private void chkEmotionPlay_CheckedChanged(object sender, EventArgs e) { if (chkEmotionPlay.Checked) { if (!this.timer1.Enabled) { AnimateStart(); } if (this.GetSelectedEmotionFrame(out _, out var actionFrame) && actionFrame.AbsoluteDelay > 0) { this.animator.EmotionDelay = actionFrame.AbsoluteDelay; } } else { this.animator.EmotionDelay = -1; TimerEnabledCheck(); } } private void chkTamingPlay_CheckedChanged(object sender, EventArgs e) { if (chkTamingPlay.Checked) { if (!this.timer1.Enabled) { AnimateStart(); } if (this.GetSelectedTamingFrame(out _, out var actionFrame) && actionFrame.AbsoluteDelay > 0) { this.animator.TamingDelay = actionFrame.AbsoluteDelay; } } else { this.animator.TamingDelay = -1; TimerEnabledCheck(); } } private void chkHairCover_CheckedChanged(object sender, EventArgs e) { avatar.HairCover = chkHairCover.Checked; UpdateDisplay(); } private void chkHairShade_CheckedChanged(object sender, EventArgs e) { avatar.ShowHairShade = chkHairShade.Checked; UpdateDisplay(); } private void timer1_Tick(object sender, EventArgs e) { this.animator.Elapse(timer1.Interval); this.AnimateUpdate(); int interval = this.animator.NextFrameDelay; if (interval <= 0) { this.timer1.Stop(); } else { this.timer1.Interval = interval; } } private void AnimateUpdate() { this.SuspendUpdateDisplay(); if (this.animator.BodyDelay == 0 && FindNextFrame(cmbBodyFrame) && this.GetSelectedBodyFrame(out _, out var bodyFrame)) { this.animator.BodyDelay = bodyFrame.AbsoluteDelay; } if (this.animator.EmotionDelay == 0 && FindNextFrame(cmbEmotionFrame) && this.GetSelectedEmotionFrame(out _, out var emoFrame)) { this.animator.EmotionDelay = emoFrame.AbsoluteDelay; } if (this.animator.TamingDelay == 0 && FindNextFrame(cmbTamingFrame) && this.GetSelectedTamingFrame(out _, out var tamingFrame)) { this.animator.TamingDelay = tamingFrame.AbsoluteDelay; } this.ResumeUpdateDisplay(); } private void AnimateStart() { TimerEnabledCheck(); if (timer1.Enabled) { AnimateUpdate(); } } private void TimerEnabledCheck() { if (chkBodyPlay.Checked || chkEmotionPlay.Checked || chkTamingPlay.Checked) { if (!this.timer1.Enabled) { this.timer1.Interval = 1; this.timer1.Start(); } } else { AnimateStop(); } } private void AnimateStop() { chkBodyPlay.Checked = false; chkEmotionPlay.Checked = false; chkTamingPlay.Checked = false; this.timer1.Stop(); } private bool FindNextFrame(ComboBoxEx cmbFrames) { ComboItem item = cmbFrames.SelectedItem as ComboItem; if (item == null) { if (cmbFrames.Items.Count > 0) { cmbFrames.SelectedIndex = 0; return true; } else { return false; } } int selectedIndex = cmbFrames.SelectedIndex; int i = selectedIndex; do { i = (++i) % cmbFrames.Items.Count; item = cmbFrames.Items[i] as ComboItem; if (item != null && item.Tag is ActionFrame actionFrame && actionFrame.AbsoluteDelay > 0) { cmbFrames.SelectedIndex = i; return true; } } while (i != selectedIndex); return false; } private void btnCode_Click(object sender, EventArgs e) { var dlg = new AvatarCodeForm(); string code = GetAllPartsTag(); dlg.CodeText = code; if (dlg.ShowDialog() == DialogResult.OK) { if (dlg.CodeText != code && !string.IsNullOrEmpty(dlg.CodeText)) { LoadCode(dlg.CodeText, dlg.LoadType); } } } private void btnMale_Click(object sender, EventArgs e) { if (this.avatar.Parts.All(part => part == null) || MessageBoxEx.Show("初始化为男性角色?", "提示") == DialogResult.OK) { LoadCode("2000,12000,20000,30000,1040036,1060026", 0); } } private void btnFemale_Click(object sender, EventArgs e) { if (this.avatar.Parts.All(part => part == null) || MessageBoxEx.Show("初始化为女性角色?", "提示") == DialogResult.OK) { LoadCode("2000,12000,21000,31000,1041046,1061039", 0); } } private void btnReset_Click(object sender, EventArgs e) { this.avatarContainer1.Origin = new Point(this.avatarContainer1.Width / 2, this.avatarContainer1.Height / 2 + 40); this.avatarContainer1.Invalidate(); } private void btnSaveAsGif_Click(object sender, EventArgs e) { bool bodyPlaying = chkBodyPlay.Checked && cmbBodyFrame.Items.Count > 1; bool emoPlaying = chkEmotionPlay.Checked && cmbEmotionFrame.Items.Count > 1; bool tamingPlaying = chkTamingPlay.Checked && cmbTamingFrame.Items.Count > 1; int aniCount = new[] { bodyPlaying, emoPlaying, tamingPlaying }.Count(b => b); if (aniCount == 0) { // no animation is playing, save as png var dlg = new SaveFileDialog() { Title = "Save avatar frame", Filter = "*.png|*.png|*.*|*.*", FileName = "avatar.png" }; if (dlg.ShowDialog() != DialogResult.OK) { return; } this.GetSelectedBodyFrame(out int bodyFrame, out _); this.GetSelectedEmotionFrame(out int emoFrame, out _); this.GetSelectedTamingFrame(out int tamingFrame, out _); var bone = this.avatar.CreateFrame(bodyFrame, emoFrame, tamingFrame); var frame = this.avatar.DrawFrame(bone); frame.Bitmap.Save(dlg.FileName, System.Drawing.Imaging.ImageFormat.Png); } else { // get default encoder var config = ImageHandlerConfig.Default; using var encoder = AnimateEncoderFactory.CreateEncoder(config); var cap = encoder.Compatibility; string extensionFilter = string.Join(";", cap.SupportedExtensions.Select(ext => $"*{ext}")); var dlg = new SaveFileDialog() { Title = "Save avatar", Filter = string.Format("{0} Supported Files ({1})|{1}|All files (*.*)|*.*", encoder.Name, extensionFilter), FileName = string.Format("avatar{0}", cap.DefaultExtension) }; if (dlg.ShowDialog() != DialogResult.OK) { return; } string outputFileName = dlg.FileName; var actPlaying = new[] { bodyPlaying, emoPlaying, tamingPlaying }; var actFrames = new[] { cmbBodyFrame, cmbEmotionFrame, cmbTamingFrame } .Select((cmb, i) => { if (actPlaying[i]) { return cmb.Items.OfType<ComboItem>().Select(cmbItem => new { index = int.Parse(cmbItem.Text), actionFrame = cmbItem.Tag as ActionFrame, }).ToArray(); } else if (this.GetSelectedActionFrame(cmb, out var index, out var actionFrame)) { return new[] { new { index, actionFrame } }; } else { return null; } }).ToArray(); var gifLayer = new GifLayer(); if (aniCount == 1 && !cap.IsFixedFrameRate) { int aniActIndex = Array.FindIndex(actPlaying, b => b); for (int fIdx = 0, fCnt = actFrames[aniActIndex].Length; fIdx < fCnt; fIdx++) { int[] actionIndices = new int[] { -1, -1, -1 }; int delay = 0; for (int i = 0; i < actFrames.Length; i++) { var act = actFrames[i]; if (i == aniActIndex) { actionIndices[i] = act[fIdx].index; delay = act[fIdx].actionFrame.AbsoluteDelay; } else if (act != null) { actionIndices[i] = act[0].index; } } var bone = this.avatar.CreateFrame(actionIndices[0], actionIndices[1], actionIndices[2]); var frameData = this.avatar.DrawFrame(bone); gifLayer.AddFrame(new GifFrame(frameData.Bitmap, frameData.Origin, delay)); } } else { // more than 2 animating action parts, for simplicity, we use fixed frame delay. int aniLength = actFrames.Max(layer => layer == null ? 0 : layer.Sum(f => f.actionFrame.AbsoluteDelay)); int aniDelay = config.MinDelay; // pipeline functions IEnumerable<int> RenderDelay() { int t = 0; while (t < aniLength) { int frameDelay = Math.Min(aniLength - t, aniDelay); t += frameDelay; yield return frameDelay; } } IEnumerable<Tuple<int[], int>> GetFrameActionIndices(IEnumerable<int> delayEnumerator) { int[] time = new int[actFrames.Length]; int[] actionState = new int[actFrames.Length]; for (int i = 0; i < actionState.Length; i++) { actionState[i] = actFrames[i] != null ? 0 : -1; } foreach (int delay in delayEnumerator) { // return state int[] actIndices = new int[actionState.Length]; for (int i = 0; i < actionState.Length; i++) { actIndices[i] = actionState[i] > -1 ? actFrames[i][actionState[i]].index : -1; } yield return Tuple.Create(actIndices, delay); // update state for (int i = 0; i < actionState.Length; i++) { if (actPlaying[i]) { var act = actFrames[i]; time[i] += delay; int frameIndex = actionState[i]; while (time[i] >= act[frameIndex].actionFrame.AbsoluteDelay) { time[i] -= act[frameIndex].actionFrame.AbsoluteDelay; frameIndex = (frameIndex + 1) % act.Length; } actionState[i] = frameIndex; } } } } IEnumerable<Tuple<int[], int>> MergeFrames(IEnumerable<Tuple<int[], int>> frames) { int[] prevFrame = null; int prevDelay = 0; foreach (var frame in frames) { int[] currentFrame = frame.Item1; int currentDelay = frame.Item2; if (prevFrame == null) { prevFrame = currentFrame; prevDelay = currentDelay; } else if (prevFrame.SequenceEqual(currentFrame)) { prevDelay += currentDelay; } else { yield return Tuple.Create(prevFrame, prevDelay); prevFrame = currentFrame; prevDelay = currentDelay; } } if (prevFrame != null) { yield return Tuple.Create(prevFrame, prevDelay); } } GifFrame ApplyFrame(int[] actionIndices, int delay) { var bone = this.avatar.CreateFrame(actionIndices[0], actionIndices[1], actionIndices[2]); var frameData = this.avatar.DrawFrame(bone); return new GifFrame(frameData.Bitmap, frameData.Origin, delay); } // build pipeline var step1 = RenderDelay(); var step2 = GetFrameActionIndices(step1); var step3 = cap.IsFixedFrameRate ? step2 : MergeFrames(step2); var step4 = step3.Select(tp => ApplyFrame(tp.Item1, tp.Item2)); // run pipeline foreach(var gifFrame in step4) { gifLayer.AddFrame(gifFrame); } } if (gifLayer.Frames.Count <= 0) { MessageBoxEx.Show(this, "计算动画数据失败。", "Error"); return; } Rectangle clientRect = gifLayer.Frames .Select(f => new Rectangle(-f.Origin.X, -f.Origin.Y, f.Bitmap.Width, f.Bitmap.Height)) .Aggregate((rect1, rect2) => { int left = Math.Min(rect1.X, rect2.X); int top = Math.Min(rect1.Y, rect2.Y); int right = Math.Max(rect1.Right, rect2.Right); int bottom = Math.Max(rect1.Bottom, rect2.Bottom); return new Rectangle(left, top, right - left, bottom - top); }); Brush CreateBackgroundBrush() { switch (config.BackgroundType.Value) { default: case ImageBackgroundType.Transparent: return null; case ImageBackgroundType.Color: return new SolidBrush(config.BackgroundColor.Value); case ImageBackgroundType.Mosaic: int blockSize = Math.Max(1, config.MosaicInfo.BlockSize); var texture = new Bitmap(blockSize * 2, blockSize * 2); using (var g = Graphics.FromImage(texture)) using (var brush0 = new SolidBrush(config.MosaicInfo.Color0)) using (var brush1 = new SolidBrush(config.MosaicInfo.Color1)) { g.FillRectangle(brush0, 0, 0, blockSize, blockSize); g.FillRectangle(brush0, blockSize, blockSize, blockSize, blockSize); g.FillRectangle(brush1, 0, blockSize, blockSize, blockSize); g.FillRectangle(brush1, blockSize, 0, blockSize, blockSize); } return new TextureBrush(texture); } } using var bgBrush = CreateBackgroundBrush(); encoder.Init(outputFileName, clientRect.Width, clientRect.Height); foreach (IGifFrame gifFrame in gifLayer.Frames) { using (var bmp = new Bitmap(clientRect.Width, clientRect.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)) { using (var g = Graphics.FromImage(bmp)) { // draw background if (bgBrush != null) { g.FillRectangle(bgBrush, 0, 0, bmp.Width, bmp.Height); } gifFrame.Draw(g, clientRect); } encoder.AppendFrame(bmp, Math.Max(cap.MinFrameDelay, gifFrame.Delay)); } } } } private void LoadCode(string code, int loadType) { //解析 var matches = Regex.Matches(code, @"(\d+)([,\s]|$)"); if (matches.Count <= 0) { MessageBoxEx.Show("无法解析的装备代码。", "错误"); return; } if (PluginManager.FindWz(Wz_Type.Base) == null) { MessageBoxEx.Show("没有打开Base.Wz。", "错误"); return; } var characWz = PluginManager.FindWz(Wz_Type.Character); //试图初始化 if (!this.inited && !this.AvatarInit()) { MessageBoxEx.Show("Avatar初始化失败。", "错误"); return; } var sl = this.PluginEntry.Context.DefaultStringLinker; if (!sl.HasValues) //生成默认stringLinker { sl.Load(PluginManager.FindWz(Wz_Type.String).GetValueEx<Wz_File>(null)); } if (loadType == 0) //先清空。。 { Array.Clear(this.avatar.Parts, 0, this.avatar.Parts.Length); } List<int> failList = new List<int>(); foreach (Match m in matches) { int gearID; if (Int32.TryParse(m.Result("$1"), out gearID)) { Wz_Node imgNode = FindNodeByGearID(characWz, gearID); if (imgNode != null) { var part = this.avatar.AddPart(imgNode); OnNewPartAdded(part); } else { failList.Add(gearID); } } } //刷新 this.FillAvatarParts(); this.UpdateDisplay(); //其他提示 if (failList.Count > 0) { StringBuilder sb = new StringBuilder(); sb.AppendLine("以下部件没有找到:"); foreach (var gearID in failList) { sb.Append(" ").AppendLine(gearID.ToString("D8")); } MessageBoxEx.Show(sb.ToString(), "嗯.."); } } private Wz_Node FindNodeByGearID(Wz_Node characWz, int id) { string imgName = id.ToString("D8") + ".img"; Wz_Node imgNode = null; foreach (var node1 in characWz.Nodes) { if (node1.Text == imgName) { imgNode = node1; break; } else if (node1.Nodes.Count > 0) { foreach (var node2 in node1.Nodes) { if (node2.Text == imgName) { imgNode = node2; break; } } if (imgNode != null) { break; } } } if (imgNode != null) { Wz_Image img = imgNode.GetValue<Wz_Image>(); if (img != null && img.TryExtract()) { return img.Node; } } return null; } private class Animator { public Animator() { this.delays = new int[3] { -1, -1, -1 }; } private int[] delays; public int NextFrameDelay { get; private set; } public int BodyDelay { get { return this.delays[0]; } set { this.delays[0] = value; Update(); } } public int EmotionDelay { get { return this.delays[1]; } set { this.delays[1] = value; Update(); } } public int TamingDelay { get { return this.delays[2]; } set { this.delays[2] = value; Update(); } } public void Elapse(int millisecond) { for (int i = 0; i < delays.Length; i++) { if (delays[i] >= 0) { delays[i] = delays[i] > millisecond ? (delays[i] - millisecond) : 0; } } } private void Update() { int nextFrame = 0; foreach (int delay in this.delays) { if (delay > 0) { nextFrame = nextFrame <= 0 ? delay : Math.Min(nextFrame, delay); } } this.NextFrameDelay = nextFrame; } } } }
0
0.928378
1
0.928378
game-dev
MEDIA
0.623826
game-dev
0.964479
1
0.964479
OGSR/OGSR-Engine
48,130
ogsr_engine/xrGame/PHElement.cpp
#include "StdAfx.h" #include "PHDynamicData.h" #include "Physics.h" #include "tri-colliderknoopc/dTriList.h" #include "PHFracture.h" #include "PHContactBodyEffector.h" #include "MathUtils.h" #include "PhysicsShellHolder.h" #include "game_object_space.h" #include "../Include/xrRender/Kinematics.h" #include "..\Include/xrRender/KinematicsAnimated.h" #include "ode/src/util.h" #ifdef DEBUG #include "PHDebug.h" #endif /////////////////////////////////////////////////////////////// #pragma warning(disable : 4995) #include "ode/src/collision_kernel.h" #pragma warning(default : 4995) /////////////////////////////////////////////////////////////////// #include "ExtendedGeom.h" #include "PHShell.h" #include "PHElement.h" #include "PHElementInline.h" extern CPHWorld* ph_world; ///////////////////////////////////////////////////////////////////////////////////////////////////////// //////Implementation for CPhysicsElement CPHElement::CPHElement() // aux { m_w_limit = default_w_limit; m_l_limit = default_l_limit; m_l_scale = default_l_scale; m_w_scale = default_w_scale; // push_untill=0; // temp_for_push_out=NULL; m_body = NULL; // bActive=false; // bActivating=false; m_flags.set(flActive, FALSE); m_flags.set(flActivating, FALSE); m_parent_element = NULL; m_shell = NULL; k_w = default_k_w; k_l = default_k_l; // 1.8f; m_fratures_holder = NULL; // b_enabled_onstep=false; // m_flags.set(flEnabledOnStep,FALSE); m_flags.assign(0); mXFORM.identity(); m_mass.setZero(); m_mass_center.set(0, 0, 0); m_volume = 0.f; } void CPHElement::add_Box(const Fobb& V) { CPHGeometryOwner::add_Box(V); } void CPHElement::add_Sphere(const Fsphere& V) { CPHGeometryOwner::add_Sphere(V); } void CPHElement::add_Cylinder(const Fcylinder& V) { CPHGeometryOwner::add_Cylinder(V); } void CPHElement::add_geom(CODEGeom* g) { Fmatrix gf; g->get_xform(gf); Fmatrix bf; PHDynamicData::DMXPStoFMX(dBodyGetRotation(m_body), dBodyGetPosition(m_body), bf); Fmatrix diff = Fmatrix().mul_43(Fmatrix().invert(bf), gf); dMatrix3 m; PHDynamicData::FMXtoDMX(diff, m); VERIFY(g->geom()); dGeomSetPosition(g->geom(), diff.c.x, diff.c.y, diff.c.z); dGeomSetRotation(g->geom(), m); g->set_body(m_body); CPHGeometryOwner::add_geom(g); } void CPHElement::remove_geom(CODEGeom* g) { g->set_body(0); CPHGeometryOwner::remove_geom(g); } void CPHElement::build() { m_body = dBodyCreate(0); // phWorld // m_saved_contacts=dJointGroupCreate (0); // b_contacts_saved=false; dBodyDisable(m_body); // dBodySetFiniteRotationMode(m_body,1); // dBodySetFiniteRotationAxis(m_body,0,0,0); VERIFY2(dMass_valide(&m_mass), "Element has bad mass"); if (m_geoms.empty()) { Fix(); } else { VERIFY2(m_mass.mass > 0.f, "Element has bad mass"); dBodySetMass(m_body, &m_mass); } VERIFY_BOUNDARIES2(m_mass_center, phBoundaries, PhysicsRefObject(), "m_mass_center") dBodySetPosition(m_body, m_mass_center.x, m_mass_center.y, m_mass_center.z); CPHDisablingTranslational::Reinit(); /////////////////////////////////////////////////////////////////////////////////////// CPHGeometryOwner::build(); set_body(m_body); } void CPHElement::RunSimulation() { // if(push_untill) // push_untill+=Device.dwTimeGlobal; if (m_group) dSpaceAdd(m_shell->dSpace(), (dGeomID)m_group); else if (!m_geoms.empty()) (*m_geoms.begin())->add_to_space(m_shell->dSpace()); if (!m_body->world) { // dWorldAddBody(phWorld, m_body); m_shell->Island().AddBody(m_body); } dBodyEnable(m_body); } void CPHElement::destroy() { // dJointGroupDestroy(m_saved_contacts); CPHGeometryOwner::destroy(); if (m_body) //&&m_body->world { if (m_body->world) m_shell->Island().RemoveBody(m_body); dBodyDestroy(m_body); m_body = NULL; } if (m_group) { dGeomDestroy(m_group); m_group = NULL; } } void CPHElement::calculate_it_data(const Fvector& mc, float mas) { float density = mas / m_volume; calculate_it_data_use_density(mc, density); } static float static_dencity; void CPHElement::calc_it_fract_data_use_density(const Fvector& mc, float density) { m_mass_center.set(mc); dMassSetZero(&m_mass); static_dencity = density; recursive_mass_summ(0, m_fratures_holder->m_fractures.begin()); } void CPHElement::set_local_mass_center(const Fvector& mc) { m_mass_center.set(mc); dVectorSet(m_mass.c, cast_fp(mc)); } dMass CPHElement::recursive_mass_summ(u16 start_geom, FRACTURE_I cur_fracture) { dMass end_mass; dMassSetZero(&end_mass); GEOM_I i_geom = m_geoms.begin() + start_geom, e = m_geoms.begin() + cur_fracture->m_start_geom_num; for (; i_geom != e; ++i_geom) (*i_geom)->add_self_mass(end_mass, m_mass_center, static_dencity); dMassAdd(&m_mass, &end_mass); start_geom = cur_fracture->m_start_geom_num; ++cur_fracture; if (m_fratures_holder->m_fractures.end() != cur_fracture) cur_fracture->SetMassParts(m_mass, recursive_mass_summ(start_geom, cur_fracture)); return end_mass; } void CPHElement::setDensity(float M) { calculate_it_data_use_density(get_mc_data(), M); } void CPHElement::setMass(float M) { calculate_it_data(get_mc_data(), M); } void CPHElement::setDensityMC(float M, const Fvector& mass_center) { m_mass_center.set(mass_center); calc_volume_data(); calculate_it_data_use_density(mass_center, M); } void CPHElement::setMassMC(float M, const Fvector& mass_center) { m_mass_center.set(mass_center); calc_volume_data(); calculate_it_data(mass_center, M); } void CPHElement::Start() { build(); RunSimulation(); } void CPHElement::Deactivate() { VERIFY(isActive()); destroy(); m_flags.set(flActive, FALSE); m_flags.set(flActivating, FALSE); // bActive=false; // bActivating=false; IKinematics* K = m_shell->PKinematics(); if (K) { K->LL_GetBoneInstance(m_SelfID).reset_callback(); } } void CPHElement::SetTransform(const Fmatrix& m0) { VERIFY2(_valid(m0), "invalid_form_in_set_transform"); Fvector mc; CPHGeometryOwner::get_mc_vs_transform(mc, m0); VERIFY_BOUNDARIES2(mc, phBoundaries, PhysicsRefObject(), "mass center in set transform"); dBodySetPosition(m_body, mc.x, mc.y, mc.z); Fmatrix33 m33; m33.set(m0); dMatrix3 R; PHDynamicData::FMX33toDMX(m33, R); dBodySetRotation(m_body, R); CPHDisablingFull::Reinit(); VERIFY2(dBodyGetPosition(m_body), "not valide safe position"); VERIFY2(dBodyGetLinearVel(m_body), "not valide safe velocity"); m_flags.set(flUpdate, TRUE); m_shell->spatial_move(); } void CPHElement::getQuaternion(Fquaternion& quaternion) { if (!isActive()) return; const float* q = dBodyGetQuaternion(m_body); quaternion.set(-q[0], q[1], q[2], q[3]); VERIFY(_valid(quaternion)); } void CPHElement::setQuaternion(const Fquaternion& quaternion) { VERIFY(_valid(quaternion)); if (!isActive()) return; dQuaternion q = {-quaternion.w, quaternion.x, quaternion.y, quaternion.z}; dBodySetQuaternion(m_body, q); CPHDisablingRotational::Reinit(); m_flags.set(flUpdate, TRUE); m_shell->spatial_move(); } void CPHElement::GetGlobalPositionDynamic(Fvector* v) { if (!isActive()) return; v->set((*(Fvector*)dBodyGetPosition(m_body))); VERIFY(_valid(*v)); } void CPHElement::SetGlobalPositionDynamic(const Fvector& position) { if (!isActive()) return; VERIFY(_valid(position)); VERIFY_BOUNDARIES2(position, phBoundaries, PhysicsRefObject(), "SetGlobalPosition argument "); dBodySetPosition(m_body, position.x, position.y, position.z); CPHDisablingTranslational::Reinit(); m_flags.set(flUpdate, TRUE); m_shell->spatial_move(); } void CPHElement::TransformPosition(const Fmatrix& form) { if (!isActive()) return; VERIFY(_valid(form)); R_ASSERT2(m_body, "body is not created"); Fmatrix bm; PHDynamicData::DMXPStoFMX(dBodyGetRotation(m_body), dBodyGetPosition(m_body), bm); Fmatrix new_bm; new_bm.mul(form, bm); dMatrix3 dBM; PHDynamicData::FMXtoDMX(new_bm, dBM); dBodySetRotation(m_body, dBM); VERIFY_BOUNDARIES2(new_bm.c, phBoundaries, PhysicsRefObject(), "TransformPosition dest pos") dBodySetPosition(m_body, new_bm.c.x, new_bm.c.y, new_bm.c.z); CPHDisablingFull::Reinit(); m_body_interpolation.ResetPositions(); m_body_interpolation.ResetRotations(); m_flags.set(flUpdate, TRUE); m_shell->spatial_move(); } CPHElement::~CPHElement() { VERIFY(!isActive()); DeleteFracturesHolder(); } void CPHElement::Activate(const Fmatrix& transform, const Fvector& lin_vel, const Fvector& ang_vel, bool disable) { VERIFY(!isActive()); mXFORM.set(transform); Start(); SetTransform(transform); dBodySetLinearVel(m_body, lin_vel.x, lin_vel.y, lin_vel.z); dBodySetAngularVel(m_body, ang_vel.x, ang_vel.y, ang_vel.z); VERIFY(dBodyStateValide(m_body)); // dVectorSet(m_safe_position,dBodyGetPosition(m_body)); // dQuaternionSet(m_safe_quaternion,dBodyGetQuaternion(m_body)); // dVectorSet(m_safe_velocity,dBodyGetLinearVel(m_body)); m_body_interpolation.SetBody(m_body); if (disable) dBodyDisable(m_body); m_flags.set(flActive, TRUE); m_flags.set(flActivating, TRUE); IKinematics* K = m_shell->PKinematics(); if (K) { K->LL_GetBoneInstance(m_SelfID).set_callback(bctPhysics, m_shell->GetBonesCallback(), static_cast<CPhysicsElement*>(this)); } } void CPHElement::Activate(const Fmatrix& m0, float dt01, const Fmatrix& m2, bool disable) { Fvector lvel, avel; lvel.set(m2.c.x - m0.c.x, m2.c.y - m0.c.y, m2.c.z - m0.c.z); avel.set(0.f, 0.f, 0.f); Activate(m0, lvel, avel, disable); } void CPHElement::Activate(bool disable, bool) { Fvector lvel, avel; lvel.set(0.f, 0.f, 0.f); avel.set(0.f, 0.f, 0.f); Activate(mXFORM, lvel, avel, disable); } void CPHElement::Activate(const Fmatrix& start_from, bool disable) { VERIFY(_valid(start_from)); Fmatrix globe; globe.mul_43(start_from, mXFORM); Fvector lvel, avel; lvel.set(0.f, 0.f, 0.f); avel.set(0.f, 0.f, 0.f); Activate(globe, lvel, avel, disable); } void CPHElement::Update() { if (!isActive()) return; if (m_flags.test(flActivating)) m_flags.set(flActivating, FALSE); if (!dBodyIsEnabled(m_body) && !m_flags.test(flUpdate) /*!bUpdate*/) return; InterpolateGlobalTransform(&mXFORM); VERIFY2(_valid(mXFORM), "invalid position in update"); } void CPHElement::PhTune(dReal step) { if (!isActive()) return; CPHContactBodyEffector* contact_effector = (CPHContactBodyEffector*)dBodyGetData(m_body); if (contact_effector) contact_effector->Apply(); VERIFY_BOUNDARIES2(cast_fv(dBodyGetPosition(m_body)), phBoundaries, PhysicsRefObject(), "PhTune body position"); } void CPHElement::PhDataUpdate(dReal step) { if (!isActive()) return; if (isFixed()) { dBodySetLinearVel(m_body, 0, 0, 0); dBodySetAngularVel(m_body, 0, 0, 0); dBodySetForce(m_body, 0, 0, 0); dBodySetTorque(m_body, 0, 0, 0); return; } ///////////////skip for disabled elements//////////////////////////////////////////////////////////// // b_enabled_onstep=!!dBodyIsEnabled(m_body); // VERIFY_BOUNDARIES2(cast_fv(dBodyGetPosition(m_body)),phBoundaries,PhysicsRefObject(),"PhDataUpdate begin, body position"); #ifdef DEBUG if (ph_dbg_draw_mask.test(phDbgDrawMassCenters)) { DBG_DrawPoint(cast_fv(dBodyGetPosition(m_body)), 0.03f, D3DCOLOR_XRGB(255, 0, 0)); } #endif m_flags.set(flEnabledOnStep, !!dBodyIsEnabled(m_body)); if (!m_flags.test(flEnabledOnStep) /*!b_enabled_onstep*/) return; //////////////////////////////////base pointers///////////////////////////////////////////////// const dReal* linear_velocity = dBodyGetLinearVel(m_body); const dReal* angular_velocity = dBodyGetAngularVel(m_body); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////scale velocity/////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// VERIFY(dV_valid(linear_velocity)); #ifdef DEBUG if (!dV_valid(angular_velocity)) { Msg("angular vel %f,%f,%f", angular_velocity[0], angular_velocity[1], angular_velocity[2]); Msg("linear vel %f,%f,%f", linear_velocity[0], linear_velocity[1], linear_velocity[2]); Msg("position %f,%f,%f", dBodyGetPosition(m_body)[0], dBodyGetPosition(m_body)[1], dBodyGetPosition(m_body)[2]); Msg("quaternion %f,%f,%f,%f", dBodyGetQuaternion(m_body)[0], dBodyGetQuaternion(m_body)[1], dBodyGetQuaternion(m_body)[2], dBodyGetQuaternion(m_body)[3]); Msg("matrix"); Msg("x %f,%f,%f", dBodyGetRotation(m_body)[0], dBodyGetRotation(m_body)[4], dBodyGetRotation(m_body)[8]); Msg("y %f,%f,%f", dBodyGetRotation(m_body)[1], dBodyGetRotation(m_body)[5], dBodyGetRotation(m_body)[9]); Msg("z %f,%f,%f", dBodyGetRotation(m_body)[2], dBodyGetRotation(m_body)[6], dBodyGetRotation(m_body)[10]); CPhysicsShellHolder* ph = PhysicsRefObject(); Msg("name visual %s", *ph->cNameVisual()); Msg("name obj %s", ph->Name()); Msg("name section %s", *ph->cNameSect()); VERIFY2(0, "bad angular velocity"); } #endif VERIFY(!fis_zero(m_l_scale)); VERIFY(!fis_zero(m_w_scale)); dBodySetLinearVel(m_body, linear_velocity[0] / m_l_scale, linear_velocity[1] / m_l_scale, linear_velocity[2] / m_l_scale); dBodySetAngularVel(m_body, angular_velocity[0] / m_w_scale, angular_velocity[1] / m_w_scale, angular_velocity[2] / m_w_scale); ///////////////////scale changes values directly so get base values after it///////////////////////// /////////////////////////////base values//////////////////////////////////////////////////////////// dReal linear_velocity_smag = dDOT(linear_velocity, linear_velocity); dReal linear_velocity_mag = _sqrt(linear_velocity_smag); dReal angular_velocity_smag = dDOT(angular_velocity, angular_velocity); dReal angular_velocity_mag = _sqrt(angular_velocity_smag); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////limit velocity & secure ///////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////limit linear vel//////////////////////////////////////////////////////////////////////////////////////// VERIFY(dV_valid(linear_velocity)); if (linear_velocity_mag > m_l_limit) { CutVelocity(m_l_limit, m_w_limit); VERIFY_BOUNDARIES2(cast_fv(dBodyGetPosition(m_body)), phBoundaries, PhysicsRefObject(), "PhDataUpdate end, body position"); linear_velocity_smag = dDOT(linear_velocity, linear_velocity); linear_velocity_mag = _sqrt(linear_velocity_smag); angular_velocity_smag = dDOT(angular_velocity, angular_velocity); angular_velocity_mag = _sqrt(angular_velocity_smag); } ////////////////secure position/////////////////////////////////////////////////////////////////////////////////// VERIFY(dV_valid(dBodyGetPosition(m_body))); /////////////////limit & secure angular vel/////////////////////////////////////////////////////////////////////////////// VERIFY(dV_valid(angular_velocity)); if (angular_velocity_mag > m_w_limit) { CutVelocity(m_l_limit, m_w_limit); angular_velocity_smag = dDOT(angular_velocity, angular_velocity); angular_velocity_mag = _sqrt(angular_velocity_smag); linear_velocity_smag = dDOT(linear_velocity, linear_velocity); linear_velocity_mag = _sqrt(linear_velocity_smag); } ////////////////secure rotation//////////////////////////////////////////////////////////////////////////////////////// { VERIFY(dQ_valid(dBodyGetQuaternion(m_body))); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////disable/////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (dBodyIsEnabled(m_body)) Disabling(); if (!dBodyIsEnabled(m_body)) return; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////air resistance///////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (!fis_zero(k_w)) dBodyAddTorque(m_body, -angular_velocity[0] * k_w, -angular_velocity[1] * k_w, -angular_velocity[2] * k_w); dMass mass; dBodyGetMass(m_body, &mass); dReal l_air = linear_velocity_mag * k_l; // force/velocity !!! if (l_air > mass.mass / fixed_step) l_air = mass.mass / fixed_step; // validate if (!fis_zero(l_air)) dBodyAddForce(m_body, -linear_velocity[0] * l_air, -linear_velocity[1] * l_air, -linear_velocity[2] * l_air); VERIFY(dBodyStateValide(m_body)); VERIFY2(dV_valid(dBodyGetPosition(m_body)), "invalid body position"); VERIFY2(dV_valid(dBodyGetQuaternion(m_body)), "invalid body rotation"); /* if(!valid_pos(cast_fv(dBodyGetPosition(m_body)),phBoundaries)) //hack { //hack Fvector pos; //hack m_body_interpolation.GetPosition(pos,0); //hack dBodySetPosition(m_body,pos.x,pos.y,pos.z); //hack } //hack */ VERIFY_BOUNDARIES2(cast_fv(dBodyGetPosition(m_body)), phBoundaries, PhysicsRefObject(), "PhDataUpdate end, body position"); UpdateInterpolation(); } void CPHElement::Enable() { if (!isActive()) return; m_shell->EnableObject(0); if (dBodyIsEnabled(m_body)) return; dBodyEnable(m_body); } void CPHElement::Disable() { // return; if (!isActive() || !dBodyIsEnabled(m_body)) return; FillInterpolation(); dBodyDisable(m_body); } void CPHElement::ReEnable() { // dJointGroupEmpty(m_saved_contacts); // b_contacts_saved=false; } void CPHElement::Freeze() { if (!m_body) return; m_flags.set(flWasEnabledBeforeFreeze, !!dBodyIsEnabled(m_body)); dBodyDisable(m_body); } void CPHElement::UnFreeze() { if (!m_body) return; if (m_flags.test(flWasEnabledBeforeFreeze) /*was_enabled_before_freeze*/) dBodyEnable(m_body); } void CPHElement::applyImpulseVsMC(const Fvector& pos, const Fvector& dir, float val) { if (!isActive() || m_flags.test(flFixed)) return; if (!dBodyIsEnabled(m_body)) dBodyEnable(m_body); ///////////////////////////////////////////////////////////////////////// Fvector impulse; val /= fixed_step; impulse.set(dir); impulse.mul(val); dBodyAddForceAtRelPos(m_body, impulse.x, impulse.y, impulse.z, pos.x, pos.y, pos.z); BodyCutForce(m_body, m_l_limit, m_w_limit); //////////////////////////////////////////////////////////////////////// } void CPHElement::applyImpulseVsGF(const Fvector& pos, const Fvector& dir, float val) { VERIFY(_valid(pos) && _valid(dir) && _valid(val)); if (!isActive() || m_flags.test(flFixed)) return; if (!dBodyIsEnabled(m_body)) dBodyEnable(m_body); ///////////////////////////////////////////////////////////////////////// Fvector impulse; val /= fixed_step; impulse.set(dir); impulse.mul(val); dBodyAddForceAtPos(m_body, impulse.x, impulse.y, impulse.z, pos.x, pos.y, pos.z); BodyCutForce(m_body, m_l_limit, m_w_limit); VERIFY(dBodyStateValide(m_body)); //////////////////////////////////////////////////////////////////////// } void CPHElement::applyImpulseTrace(const Fvector& pos, const Fvector& dir, float val, u16 id) { VERIFY(_valid(pos) && _valid(dir) && _valid(val)); if (!isActive() || m_flags.test(flFixed)) return; Fvector body_pos; if (id != BI_NONE) { if (id == m_SelfID) { body_pos.sub(pos, m_mass_center); } else { IKinematics* K = m_shell->PKinematics(); if (K) { Fmatrix m; m.set(K->LL_GetTransform(m_SelfID)); m.invert(); m.mulB_43(K->LL_GetTransform(id)); m.transform(body_pos, pos); body_pos.sub(m_mass_center); } else { body_pos.set(0.f, 0.f, 0.f); } } } else { body_pos.set(0.f, 0.f, 0.f); } #ifdef DEBUG if (ph_dbg_draw_mask.test(phHitApplicationPoints)) { DBG_OpenCashedDraw(); Fvector dbg_position; dbg_position.set(body_pos); dMULTIPLY0_331(cast_fp(dbg_position), dBodyGetRotation(m_body), cast_fp(body_pos)); dbg_position.add(cast_fv(dBodyGetPosition(m_body))); DBG_DrawPoint(dbg_position, 0.01f, D3DCOLOR_XRGB(255, 255, 255)); DBG_DrawLine(cast_fv(dBodyGetPosition(m_body)), dbg_position, D3DCOLOR_XRGB(255, 255, 255)); DBG_DrawLine(dbg_position, Fvector().add(dbg_position, Fvector().mul(dir, 0.4f)), D3DCOLOR_XRGB(255, 0, 255)); DBG_ClosedCashedDraw(10000); } #endif applyImpulseVsMC(body_pos, dir, val); if (m_fratures_holder) { /// impulse.add(*((Fvector*)dBodyGetPosition(m_body))); Fvector impulse; impulse.set(dir); impulse.mul(val / fixed_step); m_fratures_holder->AddImpact(impulse, body_pos, m_shell->BoneIdToRootGeom(id)); } } void CPHElement::applyImpact(const SPHImpact& I) { Fvector pos; pos.add(I.point, m_mass_center); Fvector dir; dir.set(I.force); float val = I.force.magnitude(); if (!fis_zero(val) && GeomByBoneID(I.geom)) { dir.mul(1.f / val); applyImpulseTrace(pos, dir, val, I.geom); } } void CPHElement::InterpolateGlobalTransform(Fmatrix* m) { if (!m_flags.test(flUpdate)) { GetGlobalTransformDynamic(m); VERIFY(_valid(*m)); return; } m_body_interpolation.InterpolateRotation(*m); m_body_interpolation.InterpolatePosition(m->c); MulB43InverceLocalForm(*m); m_flags.set(flUpdate, FALSE); VERIFY(_valid(*m)); } void CPHElement::GetGlobalTransformDynamic(Fmatrix* m) { PHDynamicData::DMXPStoFMX(dBodyGetRotation(m_body), dBodyGetPosition(m_body), *m); MulB43InverceLocalForm(*m); VERIFY(_valid(*m)); } void CPHElement::InterpolateGlobalPosition(Fvector* v) { m_body_interpolation.InterpolatePosition(*v); VERIFY(_valid(*v)); } void CPHElement::build(bool disable) { if (isActive()) return; // bActive=true; // bActivating=true; m_flags.set(flActive, TRUE); m_flags.set(flActivating, TRUE); build(); // if(place_current_forms) { SetTransform(mXFORM); } m_body_interpolation.SetBody(m_body); // previous_f[0]=dInfinity; if (disable) dBodyDisable(m_body); } void CPHElement::RunSimulation(const Fmatrix& start_from) { RunSimulation(); // if(place_current_forms) { Fmatrix globe; globe.mul(start_from, mXFORM); SetTransform(globe); } // dVectorSet(m_safe_position,dBodyGetPosition(m_body)); // dQuaternionSet(m_safe_quaternion,dBodyGetQuaternion(m_body)); // dVectorSet(m_safe_velocity,dBodyGetLinearVel(m_body)); } void CPHElement::StataticRootBonesCallBack(CBoneInstance* B) { Fmatrix parent; VERIFY2(isActive(), "the element is not active"); VERIFY(_valid(m_shell->mXFORM)); // VERIFY2(fsimilar(DET(B->mTransform),1.f,DET_CHECK_EPS),"Bones callback resive 0 matrix"); VERIFY_RMATRIX(B->mTransform); VERIFY(valid_pos(B->mTransform.c, phBoundaries)); if (m_flags.test(flActivating)) { // if(!dBodyIsEnabled(m_body)) // dBodyEnable(m_body); VERIFY(!ph_world->Processing()); VERIFY(_valid(B->mTransform)); VERIFY(!m_shell->dSpace()->lock_count); mXFORM.set(B->mTransform); // m_start_time=Device.fTimeGlobal; Fmatrix global_transform; // if(m_parent_element) global_transform.mul_43(m_shell->mXFORM, mXFORM); SetTransform(global_transform); FillInterpolation(); // bActivating=false; m_flags.set(flActivating, FALSE); if (!m_parent_element) { m_shell->m_object_in_root.set(mXFORM); m_shell->m_object_in_root.invert(); m_shell->SetNotActivating(); } B->set_callback_overwrite(TRUE); // VERIFY2(fsimilar(DET(B->mTransform),1.f,DET_CHECK_EPS),"Bones callback returns 0 matrix"); VERIFY_RMATRIX(B->mTransform); VERIFY(valid_pos(B->mTransform.c, phBoundaries)); // return; } // VERIFY2(fsimilar(DET(B->mTransform),1.f,DET_CHECK_EPS),"Bones callback returns 0 matrix"); VERIFY_RMATRIX(B->mTransform); VERIFY(valid_pos(B->mTransform.c, phBoundaries)); // if( !m_shell->is_active() && !m_flags.test(flUpdate)/*!bUpdate*/ ) return; { // InterpolateGlobalTransform(&mXFORM); parent.invert(m_shell->mXFORM); B->mTransform.mul_43(parent, mXFORM); } // VERIFY2(fsimilar(DET(B->mTransform),1.f,DET_CHECK_EPS),"Bones callback returns 0 matrix"); VERIFY_RMATRIX(B->mTransform); VERIFY(valid_pos(B->mTransform.c, phBoundaries)); VERIFY2(_valid(B->mTransform), "Bones callback returns bad matrix"); // else //{ // InterpolateGlobalTransform(&m_shell->mXFORM); // mXFORM.identity(); // B->mTransform.set(mXFORM); // parent.set(B->mTransform); // parent.invert(); // m_shell->mXFORM.mulB(parent); //} } void CPHElement::BoneGlPos(Fmatrix& m, CBoneInstance* B) { VERIFY(m_shell); m.mul_43(m_shell->mXFORM, B->mTransform); } void CPHElement::GetAnimBonePos(Fmatrix& bp) { VERIFY(m_shell->PKinematics()); IKinematics* ak = m_shell->PKinematics(); VERIFY(ak); CBoneInstance* BI = &ak->LL_GetBoneInstance(m_SelfID); if (!BI->callback()) //. { bp.set(BI->mTransform); return; } ak->Bone_GetAnimPos(bp, m_SelfID, u8(-1), true); } IC bool put_in_range(Fvector& v, float range) { VERIFY(range > EPS_S); float sq_mag = v.square_magnitude(); if (sq_mag > range * range) { float mag = _sqrt(sq_mag); v.mul(range / mag); return true; } return false; } bool CPHElement::AnimToVel(float dt, float l_limit, float a_limit) { VERIFY(m_shell); VERIFY(m_shell->PKinematics()); // CBoneInstance *BI = &m_shell->PKinematics()->LL_GetBoneInstance(m_SelfID); // // Fmatrix bp;BoneGlPos(bp,BI); // CPhysicsShellHolder* ph = PhysicsRefObject(); VERIFY(ph); Fmatrix bpl; GetAnimBonePos(bpl); Fmatrix bp; bp.mul_43(ph->XFORM(), bpl); // BoneGlPos(bp,BI); Fmatrix cp; GetGlobalTransformDynamic(&cp); // Fquaternion q0; q0.set(cp); cp.invert(); Fmatrix diff; diff.mul_43(cp, bp); if (dt < EPS_S) dt = EPS_S; Fvector mc1; CPHGeometryOwner::get_mc_vs_transform(mc1, bp); Fvector mc0 = cast_fv(dBodyGetPosition(m_body)); // Fvector mc1;diff.transform_tiny(mc1,mc0); Fvector lv; lv.mul(Fvector().sub(mc1, mc0), (1.f / dt)); Fvector aw; aw.set((diff._32 - diff._23) / 2.f / dt, (diff._13 - diff._31) / 2.f / dt, (diff._21 - diff._12) / 2.f / dt); // Fquaternion q1; q1.set(bp); // twoq_2w(q0,q1,dt,aw); bool ret = aw.square_magnitude() < a_limit * a_limit && lv.square_magnitude() < l_limit * l_limit; put_in_range(lv, m_l_limit); put_in_range(aw, m_w_limit); VERIFY(_valid(lv)); VERIFY(_valid(aw)); dBodySetLinearVel(m_body, lv.x, lv.y, lv.z); dBodySetAngularVel(m_body, aw.x, aw.y, aw.z); // set_LinearVel(lv); // set_AngularVel(aw); return ret; } void CPHElement::ToBonePos(CBoneInstance* B) { VERIFY2(!ph_world->Processing(), *PhysicsRefObject()->cNameSect()); VERIFY(_valid(B->mTransform)); VERIFY(!m_shell->dSpace()->lock_count); mXFORM.set(B->mTransform); Fmatrix global_transform; BoneGlPos(global_transform, B); SetTransform(global_transform); FillInterpolation(); } void CPHElement::SetBoneCallbackOverwrite(bool v) { VERIFY(m_shell); VERIFY(m_shell->PKinematics()); m_shell->PKinematics()->LL_GetBoneInstance(m_SelfID).set_callback_overwrite(v); } void CPHElement::BonesCallBack(CBoneInstance* B) { Fmatrix parent; VERIFY(isActive()); VERIFY(_valid(m_shell->mXFORM)); // VERIFY2(fsimilar(DET(B->mTransform),1.f,DET_CHECK_EPS),"Bones callback receive 0 matrix"); VERIFY_RMATRIX(B->mTransform); VERIFY_BOUNDARIES2(B->mTransform.c, phBoundaries, PhysicsRefObject(), "BonesCallBack incoming bone position"); if (m_flags.test(flActivating)) { ToBonePos(B); m_flags.set(flActivating, FALSE); if (!m_parent_element) { m_shell->m_object_in_root.set(mXFORM); m_shell->m_object_in_root.invert(); m_shell->SetNotActivating(); } B->set_callback_overwrite(TRUE); // VERIFY2(fsimilar(DET(B->mTransform),1.f,DET_CHECK_EPS),"Bones callback returns 0 matrix"); VERIFY_RMATRIX(B->mTransform); VERIFY(valid_pos(B->mTransform.c, phBoundaries)); return; } VERIFY_RMATRIX(B->mTransform); VERIFY(valid_pos(B->mTransform.c, phBoundaries)); { parent.invert(m_shell->mXFORM); B->mTransform.mul_43(parent, mXFORM); } // VERIFY2(fsimilar(DET(B->mTransform),1.f,DET_CHECK_EPS),"Bones callback returns 0 matrix"); VERIFY_RMATRIX(B->mTransform); VERIFY(valid_pos(B->mTransform.c, phBoundaries)); VERIFY2(_valid(B->mTransform), "Bones callback returns bad matrix"); // else //{ // InterpolateGlobalTransform(&m_shell->mXFORM); // mXFORM.identity(); // B->mTransform.set(mXFORM); // parent.set(B->mTransform); // parent.invert(); // m_shell->mXFORM.mulB(parent); //} } void CPHElement::set_PhysicsRefObject(CPhysicsShellHolder* ref_object) { CPHGeometryOwner::set_PhysicsRefObject(ref_object); } void CPHElement::set_ObjectContactCallback(ObjectContactCallbackFun* callback) { CPHGeometryOwner::set_ObjectContactCallback(callback); } void CPHElement::add_ObjectContactCallback(ObjectContactCallbackFun* callback) { CPHGeometryOwner::add_ObjectContactCallback(callback); } void CPHElement::remove_ObjectContactCallback(ObjectContactCallbackFun* callback) { CPHGeometryOwner::remove_ObjectContactCallback(callback); } ObjectContactCallbackFun* CPHElement::get_ObjectContactCallback() { return CPHGeometryOwner::get_ObjectContactCallback(); } void CPHElement::set_CallbackData(void* cd) { CPHGeometryOwner::set_CallbackData(cd); } void* CPHElement::get_CallbackData() { return CPHGeometryOwner::get_CallbackData(); } void CPHElement::set_ContactCallback(ContactCallbackFun* callback) { // push_untill=0; CPHGeometryOwner::set_ContactCallback(callback); } void CPHElement::SetMaterial(u16 m) { CPHGeometryOwner::SetMaterial(m); } dMass* CPHElement::getMassTensor() // aux { return &m_mass; } void CPHElement::setInertia(const dMass& M) { m_mass = M; if (!isActive() || m_flags.test(flFixed)) return; dBodySetMass(m_body, &M); } void CPHElement::addInertia(const dMass& M) { dMassAdd(&m_mass, &M); if (!isActive()) return; dBodySetMass(m_body, &m_mass); } void CPHElement::get_LinearVel(Fvector& velocity) { if (!isActive() || (!m_flags.test(flAnimated) && !dBodyIsEnabled(m_body))) { velocity.set(0, 0, 0); return; } dVectorSet((dReal*)&velocity, dBodyGetLinearVel(m_body)); } void CPHElement::get_AngularVel(Fvector& velocity) { if (!isActive() || (!m_flags.test(flAnimated) && !dBodyIsEnabled(m_body))) { velocity.set(0, 0, 0); return; } dVectorSet((dReal*)&velocity, dBodyGetAngularVel(m_body)); } void CPHElement::set_LinearVel(const Fvector& velocity) { if (!isActive() || m_flags.test(flFixed)) return; VERIFY2(_valid(velocity), "not valid arqument velocity"); Fvector vel = velocity; #ifdef DEBUG if (velocity.magnitude() > m_l_limit) Msg(" CPHElement::set_LinearVel set velocity magnitude is too large %f", velocity.magnitude()); #endif put_in_range(vel, m_l_limit); dBodySetLinearVel(m_body, vel.x, vel.y, vel.z); // dVectorSet(m_safe_velocity,dBodyGetLinearVel(m_body)); } void CPHElement::set_AngularVel(const Fvector& velocity) { VERIFY(_valid(velocity)); if (!isActive() || m_flags.test(flFixed)) return; Fvector vel = velocity; #ifdef DEBUG if (velocity.magnitude() > m_w_limit) Msg("CPHElement::set_AngularVel set velocity magnitude is too large %f", velocity.magnitude()); #endif put_in_range(vel, m_w_limit); dBodySetAngularVel(m_body, vel.x, vel.y, vel.z); } void CPHElement::getForce(Fvector& force) { if (!isActive()) return; force.set(*(Fvector*)dBodyGetForce(m_body)); VERIFY(dBodyStateValide(m_body)); } void CPHElement::getTorque(Fvector& torque) { if (!isActive()) return; torque.set(*(Fvector*)dBodyGetTorque(m_body)); VERIFY(dBodyStateValide(m_body)); } void CPHElement::setForce(const Fvector& force) { if (!isActive() || m_flags.test(flFixed)) return; if (!dBodyIsEnabled(m_body)) dBodyEnable(m_body); m_shell->EnableObject(0); dBodySetForce(m_body, force.x, force.y, force.z); BodyCutForce(m_body, m_l_limit, m_w_limit); VERIFY(dBodyStateValide(m_body)); } void CPHElement::setTorque(const Fvector& torque) { if (!isActive() || m_flags.test(flFixed)) return; if (!dBodyIsEnabled(m_body)) dBodyEnable(m_body); m_shell->EnableObject(0); dBodySetTorque(m_body, torque.x, torque.y, torque.z); BodyCutForce(m_body, m_l_limit, m_w_limit); VERIFY(dBodyStateValide(m_body)); } void CPHElement::applyForce(const Fvector& dir, float val) // aux { applyForce(dir.x * val, dir.y * val, dir.z * val); } void CPHElement::applyForce(float x, float y, float z) // called anywhere ph state influent { VERIFY(_valid(x) && _valid(y) && _valid(z)); if (!isActive()) return; // hack?? if (m_flags.test(flFixed)) return; if (!dBodyIsEnabled(m_body)) dBodyEnable(m_body); m_shell->EnableObject(0); dBodyAddForce(m_body, x, y, z); BodyCutForce(m_body, m_l_limit, m_w_limit); VERIFY(dBodyStateValide(m_body)); } void CPHElement::applyImpulse(const Fvector& dir, float val) // aux { applyForce(dir.x * val / fixed_step, dir.y * val / fixed_step, dir.z * val / fixed_step); } void CPHElement::add_Shape(const SBoneShape& shape, const Fmatrix& offset) { CPHGeometryOwner::add_Shape(shape, offset); } void CPHElement::add_Shape(const SBoneShape& shape) { CPHGeometryOwner::add_Shape(shape); } #pragma todo(remake it using Geometry functions) void CPHElement::add_Mass(const SBoneShape& shape, const Fmatrix& offset, const Fvector& mass_center, float mass, CPHFracture* fracture) { dMass m; dMatrix3 DMatx; switch (shape.type) { case SBoneShape::stBox: { dMassSetBox(&m, 1.f, shape.box.m_halfsize.x * 2.f, shape.box.m_halfsize.y * 2.f, shape.box.m_halfsize.z * 2.f); dMassAdjust(&m, mass); Fmatrix box_transform; shape.box.xform_get(box_transform); PHDynamicData::FMX33toDMX(shape.box.m_rotate, DMatx); dMassRotate(&m, DMatx); dMassTranslate(&m, shape.box.m_translate.x - mass_center.x, shape.box.m_translate.y - mass_center.y, shape.box.m_translate.z - mass_center.z); break; } case SBoneShape::stSphere: { // shape.sphere; dMassSetSphere(&m, 1.f, shape.sphere.R); dMassAdjust(&m, mass); dMassTranslate(&m, shape.sphere.P.x - mass_center.x, shape.sphere.P.y - mass_center.y, shape.sphere.P.z - mass_center.z); break; } case SBoneShape::stCylinder: { const Fvector& pos = shape.cylinder.m_center; Fvector l; l.sub(pos, mass_center); dMassSetCylinder(&m, 1.f, 2, shape.cylinder.m_radius, shape.cylinder.m_height); dMassAdjust(&m, mass); dMatrix3 DMatx; Fmatrix33 m33; m33.j.set(shape.cylinder.m_direction); Fvector::generate_orthonormal_basis(m33.j, m33.k, m33.i); PHDynamicData::FMX33toDMX(m33, DMatx); dMassRotate(&m, DMatx); dMassTranslate(&m, l.x, l.y, l.z); break; } case SBoneShape::stNone: break; default: NODEFAULT; } PHDynamicData::FMXtoDMX(offset, DMatx); dMassRotate(&m, DMatx); Fvector mc; offset.transform_tiny(mc, mass_center); // calculate _new mass_center // new_mc=(m_mass_center*m_mass.mass+mc*mass)/(mass+m_mass.mass) Fvector tmp1; tmp1.set(m_mass_center); tmp1.mul(m_mass.mass); Fvector tmp2; tmp2.set(mc); tmp2.mul(mass); Fvector new_mc; new_mc.add(tmp1, tmp2); new_mc.mul(1.f / (mass + m_mass.mass)); mc.sub(new_mc); dMassTranslate(&m, mc.x, mc.y, mc.z); m_mass_center.sub(new_mc); dMassTranslate(&m_mass, m_mass_center.x, m_mass_center.y, m_mass_center.z); if (m_fratures_holder) { m_fratures_holder->DistributeAdditionalMass(u16(m_geoms.size() - 1), m); } if (fracture) { fracture->MassAddToSecond(m); } R_ASSERT2(dMass_valide(&m), "bad bone mass params"); dMassAdd(&m_mass, &m); R_ASSERT2(dMass_valide(&m), "bad result mass params"); m_mass_center.set(new_mc); } void CPHElement::set_BoxMass(const Fobb& box, float mass) { dMassSetZero(&m_mass); m_mass_center.set(box.m_translate); const Fvector& hside = box.m_halfsize; dMassSetBox(&m_mass, 1, hside.x * 2.f, hside.y * 2.f, hside.z * 2.f); dMassAdjust(&m_mass, mass); dMatrix3 DMatx; PHDynamicData::FMX33toDMX(box.m_rotate, DMatx); dMassRotate(&m_mass, DMatx); } void CPHElement::calculate_it_data_use_density(const Fvector& mc, float density) { dMassSetZero(&m_mass); GEOM_I i_geom = m_geoms.begin(), e = m_geoms.end(); for (; i_geom != e; ++i_geom) (*i_geom)->add_self_mass(m_mass, mc, density); VERIFY2(dMass_valide(&m_mass), "non valide mass obtained!"); } float CPHElement::getRadius() { return CPHGeometryOwner::getRadius(); } void CPHElement::set_DynamicLimits(float l_limit, float w_limit) { m_l_limit = l_limit; m_w_limit = w_limit; } void CPHElement::set_DynamicScales(float l_scale /* =default_l_scale */, float w_scale /* =default_w_scale */) { m_l_scale = l_scale; m_w_scale = w_scale; } void CPHElement::set_DisableParams(const SAllDDOParams& params) { CPHDisablingFull::set_DisableParams(params); } void CPHElement::get_Extensions(const Fvector& axis, float center_prg, float& lo_ext, float& hi_ext) { CPHGeometryOwner::get_Extensions(axis, center_prg, lo_ext, hi_ext); } const Fvector& CPHElement::mass_Center() { VERIFY(dBodyStateValide(m_body)); return *((const Fvector*)dBodyGetPosition(m_body)); } CPhysicsShell* CPHElement::PhysicsShell() { return smart_cast<CPhysicsShell*>(m_shell); } CPHShell* CPHElement::PHShell() { return (m_shell); } void CPHElement::SetShell(CPHShell* p) { if (!m_body || !m_shell) { m_shell = p; return; } if (m_shell != p) { m_shell->Island().RemoveBody(m_body); p->Island().AddBody(m_body); m_shell = p; } } void CPHElement::PassEndGeoms(u16 from, u16 to, CPHElement* dest) { GEOM_I i_from = m_geoms.begin() + from, e = m_geoms.begin() + to; u16 shift = to - from; GEOM_I i = i_from; for (; i != e; ++i) { (*i)->remove_from_space(m_group); //(*i)->add_to_space(dest->m_group); //(*i)->set_body(dest->m_body); (*i)->set_body(0); u16& element_pos = (*i)->element_position(); element_pos = element_pos - shift; } GEOM_I last = m_geoms.end(); for (; i != last; ++i) { u16& element_pos = (*i)->element_position(); element_pos = element_pos - shift; } dest->m_geoms.insert(dest->m_geoms.end(), i_from, e); dest->b_builded = true; m_geoms.erase(i_from, e); } void CPHElement::SplitProcess(ELEMENT_PAIR_VECTOR& new_elements) { m_fratures_holder->SplitProcess(this, new_elements); if (!m_fratures_holder->m_fractures.size()) xr_delete(m_fratures_holder); } void CPHElement::DeleteFracturesHolder() { xr_delete(m_fratures_holder); } void CPHElement::CreateSimulBase() { m_body = dBodyCreate(0); m_shell->Island().AddBody(m_body); // m_saved_contacts=dJointGroupCreate (0); // b_contacts_saved=false; dBodyDisable(m_body); CPHGeometryOwner::CreateSimulBase(); } void CPHElement::ReAdjustMassPositions(const Fmatrix& shift_pivot, float density) { GEOM_I i = m_geoms.begin(), e = m_geoms.end(); for (; i != e; ++i) { (*i)->move_local_basis(shift_pivot); } if (m_shell->PKinematics()) { float mass; get_mc_kinematics(m_shell->PKinematics(), m_mass_center, mass); calculate_it_data(m_mass_center, mass); } else { setDensity(density); } dBodySetMass(m_body, &m_mass); // m_inverse_local_transform.identity(); // m_inverse_local_transform.c.set(m_mass_center); // m_inverse_local_transform.invert(); // dBodySetPosition(m_body,m_mass_center.x,m_mass_center.y,m_mass_center.z); } void CPHElement::ResetMass(float density) { Fvector tmp, shift_mc; tmp.set(m_mass_center); setDensity(density); dBodySetMass(m_body, &m_mass); shift_mc.sub(m_mass_center, tmp); tmp.set(*(Fvector*)dBodyGetPosition(m_body)); tmp.add(shift_mc); // bActivating = true; m_flags.set(flActivating, TRUE); CPHGeometryOwner::setPosition(m_mass_center); } void CPHElement::ReInitDynamics(const Fmatrix& shift_pivot, float density) { VERIFY(_valid(shift_pivot) && _valid(density)); ReAdjustMassPositions(shift_pivot, density); GEOM_I i = m_geoms.begin(), e = m_geoms.end(); for (; i != e; ++i) { (*i)->set_position(m_mass_center); (*i)->set_body(m_body); // if(object_contact_callback)geom.set_obj_contact_cb(object_contact_callback); // if(m_phys_ref_object) geom.set_ref_object(m_phys_ref_object); if (m_group) { (*i)->add_to_space((dSpaceID)m_group); } } } void CPHElement::PresetActive() { if (isActive()) return; CBoneInstance& B = m_shell->PKinematics()->LL_GetBoneInstance(m_SelfID); mXFORM.set(B.mTransform); // m_start_time=Device.fTimeGlobal; Fmatrix global_transform; global_transform.mul_43(m_shell->mXFORM, mXFORM); SetTransform(global_transform); if (!m_parent_element) { m_shell->m_object_in_root.set(mXFORM); m_shell->m_object_in_root.invert(); } // dVectorSet(m_safe_position,dBodyGetPosition(m_body)); // dQuaternionSet(m_safe_quaternion,dBodyGetQuaternion(m_body)); // dVectorSet(m_safe_velocity,dBodyGetLinearVel(m_body)); ////////////////////////////////////////////////////////////// // initializing values for disabling////////////////////////// ////////////////////////////////////////////////////////////// VERIFY(dBodyStateValide(m_body)); m_body_interpolation.SetBody(m_body); FillInterpolation(); // bActive=true; m_flags.set(flActive, TRUE); RunSimulation(); VERIFY(dBodyStateValide(m_body)); } bool CPHElement::isBreakable() { return !!m_fratures_holder; } u16 CPHElement::setGeomFracturable(CPHFracture& fracture) { if (!m_fratures_holder) m_fratures_holder = xr_new<CPHFracturesHolder>(); return m_fratures_holder->AddFracture(fracture); } CPHFracture& CPHElement::Fracture(u16 num) { R_ASSERT2(m_fratures_holder, "no fractures!"); return m_fratures_holder->Fracture(num); } u16 CPHElement::numberOfGeoms() { return CPHGeometryOwner::numberOfGeoms(); } void CPHElement::cv2bone_Xfrom(const Fquaternion& q, const Fvector& pos, Fmatrix& xform) { VERIFY2(_valid(q) && _valid(pos), "cv2bone_Xfrom receive wrong data"); xform.rotation(q); xform.c.set(pos); // xform.mulB(m_inverse_local_transform); MulB43InverceLocalForm(xform); VERIFY2(_valid(xform), "cv2bone_Xfrom returns wrong data"); } void CPHElement::cv2obj_Xfrom(const Fquaternion& q, const Fvector& pos, Fmatrix& xform) { cv2bone_Xfrom(q, pos, xform); xform.mulB_43(m_shell->m_object_in_root); VERIFY2(_valid(xform), "cv2obj_Xfrom returns wrong data"); } void CPHElement::set_ApplyByGravity(bool flag) { if (!isActive() || m_flags.test(flFixed)) return; dBodySetGravityMode(m_body, flag); } bool CPHElement::get_ApplyByGravity() { return (!!dBodyGetGravityMode(m_body)); } void CPHElement::Fix() { if (isFixed()) return; dBodySetNoUpdatePosMode(m_body, 1); m_flags.set(flFixed, TRUE); FixBody(m_body); } void CPHElement::ReleaseFixed() { if (!isFixed()) return; dBodySetNoUpdatePosMode(m_body, 0); m_flags.set(flFixed, FALSE); if (!isActive()) return; dBodySetMass(m_body, &m_mass); dBodySetGravityMode(m_body, 1); } void CPHElement::applyGravityAccel(const Fvector& accel) { VERIFY(_valid(accel)); if (m_flags.test(flFixed)) return; if (!dBodyIsEnabled(m_body)) dBodyEnable(m_body); m_shell->EnableObject(0); Fvector val; val.set(accel); val.mul(m_mass.mass); // ApplyGravityAccel(m_body,(const dReal*)(&accel)); applyForce(val.x, val.y, val.z); } void CPHElement::CutVelocity(float l_limit, float a_limit) { if (!isActive()) return; VERIFY(_valid(l_limit) && _valid(a_limit)); dVector3 limitedl, limiteda, diffl, diffa; bool blimitl = dVectorLimit(dBodyGetLinearVel(m_body), l_limit, limitedl); bool blimita = dVectorLimit(dBodyGetAngularVel(m_body), a_limit, limiteda); if (blimitl || blimita) { dVectorSub(diffl, limitedl, dBodyGetLinearVel(m_body)); dVectorSub(diffa, limiteda, dBodyGetAngularVel(m_body)); dBodySetLinearVel(m_body, diffl[0], diffl[1], diffl[2]); dBodySetAngularVel(m_body, diffa[0], diffa[1], diffa[2]); dxStepBody(m_body, fixed_step); dBodySetLinearVel(m_body, limitedl[0], limitedl[1], limitedl[2]); dBodySetAngularVel(m_body, limiteda[0], limiteda[1], limiteda[2]); } } void CPHElement::ClearDestroyInfo() { xr_delete(m_fratures_holder); } // bool CPHElement::CheckBreakConsistent() //{ // if(!m_fratures_holder) return true; // m_fratures_holder->m_fractures // m_fratures_holder->Fracture() // }) return true; // m_fratures_holder->m_fractures // m_fratures_holder->Fracture() // }
0
0.933863
1
0.933863
game-dev
MEDIA
0.881998
game-dev
0.593486
1
0.593486
Sin365/AxibugEmuOnline
14,810
AxibugEmuOnline.Client/Assets/Script/AppMain/Common/ObjectPoolAuto.cs
using AxibugEmuOnline.Client.ClientCore; using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace AxibugEmuOnline.Client.Common { public static class ObjectPoolAuto { /************************************************************************************************************************/ /// <summary> /// 获取或者创建一个新的 /// </summary> /// <remarks>Remember to <see cref="Release{T}(T)"/> 需要回收参见这个</remarks> public static T Acquire<T>() where T : class, new() => ObjectPool<T>.Acquire(); /// <summary> /// 获取或者创建一个新的 /// </summary> /// <remarks>Remember to <see cref="Release{T}(T)"/> 需要回收参见这个</remarks> public static void Acquire<T>(out T item) where T : class, new() => item = ObjectPool<T>.Acquire(); /************************************************************************************************************************/ /// <summary> /// 回收对象 /// </summary> public static void Release<T>(T item) where T : class, new() => ObjectPool<T>.Release(item); /// <summary> /// 回收对象 /// </summary> public static void Release<T>(ref T item) where T : class, new() { if (item != null) { ObjectPool<T>.Release(item); item = null; } } /************************************************************************************************************************/ public const string NotClearError = " They must be cleared before being released to the pool and not modified after that."; /************************************************************************************************************************/ /// <summary> /// 获取或创建List /// </summary> /// <remarks>Remember to <see cref="Release{T}(List{T})"/> 回收参见此方法</remarks> public static List<T> AcquireList<T>() { var list = ObjectPool<List<T>>.Acquire(); App.log.Assert(list.Count == 0, "A pooled list is not empty." + NotClearError); return list; } /// <summary> /// 回收List /// </summary> public static void Release<T>(List<T> list) { list.Clear(); ObjectPool<List<T>>.Release(list); } /************************************************************************************************************************/ /// <summary> /// 获取或创建Queue /// </summary> /// <remarks>Remember to <see cref="Release{T}(Queue{T})"/> 回收参见此方法</remarks> public static Queue<T> AcquireQueue<T>() { var queue = ObjectPool<Queue<T>>.Acquire(); App.log.Assert(queue.Count == 0, "A pooled list is not empty." + NotClearError); return queue; } /// <summary> /// 回收Queue /// </summary> public static void Release<T>(Queue<T> list) { list.Clear(); ObjectPool<Queue<T>>.Release(list); } /************************************************************************************************************************/ /// <summary> /// 获取或创建HashSet /// </summary> public static HashSet<T> AcquireSet<T>() { var set = ObjectPool<HashSet<T>>.Acquire(); App.log.Assert(set.Count == 0, "A pooled set is not empty." + NotClearError); return set; } /// <summary> /// 释放HashSet /// </summary> public static void Release<T>(HashSet<T> set) { set.Clear(); ObjectPool<HashSet<T>>.Release(set); } /************************************************************************************************************************/ /// <summary> /// 获取一个字符串StringBuilder /// </summary> /// <remarks>Remember to <see cref="Release(StringBuilder)"/>回收参见这个</remarks> public static StringBuilder AcquireStringBuilder() { var builder = ObjectPool<StringBuilder>.Acquire(); App.log.Assert(builder.Length == 0, $"A pooled {nameof(StringBuilder)} is not empty." + NotClearError); return builder; } /// <summary> /// 回收 StringBuilder /// </summary> public static void Release(StringBuilder builder) { builder.Length = 0; ObjectPool<StringBuilder>.Release(builder); } /// <summary> /// 回收 StringBuilder /// </summary> public static string ReleaseToString(this StringBuilder builder) { var result = builder.ToString(); Release(builder); return result; } /************************************************************************************************************************/ private static class Cache<T> { public static readonly Dictionary<MethodInfo, KeyValuePair<Func<T>, T>> Results = new Dictionary<MethodInfo, KeyValuePair<Func<T>, T>>(); } /// <summary> /// 此方法主要用于频繁绘制缓存,比如说GUI绘制 /// </summary> public static T GetCachedResult<T>(Func<T> function) { var method = function.Method; if (!Cache<T>.Results.TryGetValue(method, out var result)) { result = new KeyValuePair<Func<T>, T>(function, function()); Cache<T>.Results.Add(method, result); } else if (result.Key != function) { App.log.Warning( $"{nameof(GetCachedResult)}<{typeof(T).Name}>" + $" was previously called on {method.Name} with a different target." + " This likely means that a new delegate is being passed into every call" + " so it can't actually return the same cached object."); } return result.Value; } /************************************************************************************************************************/ public static class Disposable { /************************************************************************************************************************/ /// <summary> /// Calls <see cref="ObjectPool{T}.Disposable.Acquire"/> to get a spare <see cref="List{T}"/> if /// </summary> public static IDisposable Acquire<T>(out T item) where T : class, new() => ObjectPool<T>.Disposable.Acquire(out item); /************************************************************************************************************************/ /// <summary> /// Calls <see cref="ObjectPool{T}.Disposable.Acquire"/> to get a spare <see cref="List{T}"/> if /// </summary> public static IDisposable AcquireList<T>(out List<T> list) { var disposable = ObjectPool<List<T>>.Disposable.Acquire(out list, onRelease: (l) => l.Clear()); App.log.Assert(list.Count == 0, "A pooled list is not empty." + NotClearError); return disposable; } /************************************************************************************************************************/ /// <summary> /// Calls <see cref="ObjectPool{T}.Disposable.Acquire"/> to get a spare <see cref="HashSet{T}"/> if /// </summary> public static IDisposable AcquireSet<T>(out HashSet<T> set) { var disposable = ObjectPool<HashSet<T>>.Disposable.Acquire(out set, onRelease: (s) => s.Clear()); App.log.Assert(set.Count == 0, "A pooled set is not empty." + NotClearError); return disposable; } /************************************************************************************************************************/ } /************************************************************************************************************************/ } public static class ObjectPool<T> where T : class, new() { /************************************************************************************************************************/ private static readonly List<T> Items = new List<T>(); /************************************************************************************************************************/ /// <summary>The number of spare items currently in the pool.</summary> public static int Count { get => Items.Count; set { var count = Items.Count; if (count < value) { if (Items.Capacity < value) Items.Capacity = NextPowerOfTwo(value); do { Items.Add(new T()); count++; } while (count < value); } else if (count > value) { Items.RemoveRange(value, count - value); } } } public static int NextPowerOfTwo(int value) { if (value <= 0) { throw new ArgumentException("Value must be greater than zero."); } int powerOfTwo = 1; while (powerOfTwo < value) { powerOfTwo <<= 1; // equivalent to multiplying by 2 } return powerOfTwo; } /************************************************************************************************************************/ /// <summary> /// If the <see cref="Count"/> is less than the specified value, this method increases it to that value by /// creating new objects. /// </summary> public static void SetMinCount(int count) { if (Count < count) Count = count; } /************************************************************************************************************************/ /// <summary>The <see cref="List{T}.Capacity"/> of the internal list of spare items.</summary> public static int Capacity { get => Items.Capacity; set { if (Items.Count > value) Items.RemoveRange(value, Items.Count - value); Items.Capacity = value; } } /************************************************************************************************************************/ /// <summary>Returns a spare item if there are any, or creates a new one.</summary> /// <remarks>Remember to <see cref="Release(T)"/> it when you are done.</remarks> public static T Acquire() { var count = Items.Count; if (count == 0) { return new T(); } else { count--; var item = Items[count]; Items.RemoveAt(count); return item; } } /************************************************************************************************************************/ /// <summary>Adds the `item` to the list of spares so it can be reused.</summary> public static void Release(T item) { Items.Add(item); } /************************************************************************************************************************/ /// <summary>Returns a description of the state of this pool.</summary> public static string GetDetails() { return $"{typeof(T).Name}" + $" ({nameof(Count)} = {Items.Count}" + $", {nameof(Capacity)} = {Items.Capacity}" + ")"; } /************************************************************************************************************************/ /// <summary> /// An <see cref="IDisposable"/> system to allow pooled objects to be acquired and released within <c>using</c> /// statements instead of needing to manually release everything. /// </summary> public sealed class Disposable : IDisposable { /************************************************************************************************************************/ private static readonly List<Disposable> LazyStack = new List<Disposable>(); private static int _ActiveDisposables; private T _Item; private Action<T> _OnRelease; /************************************************************************************************************************/ private Disposable() { } /// <summary> /// Calls <see cref="ObjectPool{T}.Acquire"/> to set the `item` and returns an <see cref="IDisposable"/> /// that will call <see cref="Release(T)"/> on the `item` when disposed. /// </summary> public static IDisposable Acquire(out T item, Action<T> onRelease = null) { Disposable disposable; if (LazyStack.Count <= _ActiveDisposables) { LazyStack.Add(disposable = new Disposable()); } else { disposable = LazyStack[_ActiveDisposables]; } _ActiveDisposables++; disposable._Item = item = ObjectPool<T>.Acquire(); disposable._OnRelease = onRelease; return disposable; } /************************************************************************************************************************/ void IDisposable.Dispose() { _OnRelease?.Invoke(_Item); Release(_Item); _ActiveDisposables--; } /************************************************************************************************************************/ } } }
0
0.760481
1
0.760481
game-dev
MEDIA
0.363758
game-dev
0.778529
1
0.778529
EaW-Team/equestria_dev
11,448
interface/focus/shine/focus_WAR_shine.gfx
spriteTypes = { SpriteType = { name = "GFX_WAR_proper_coronation_shine" texturefile = "gfx/interface/goals/WAR/WAR_A_Proper_Coronation.tga" effectFile = "gfx/FX/buttonstate.lua" animation = { animationmaskfile = "gfx/interface/goals/WAR/WAR_A_Proper_Coronation.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = -90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } animation = { animationmaskfile = "gfx/interface/goals/WAR/WAR_A_Proper_Coronation.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = 90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } legacy_lazy_load = no } SpriteType = { name = "GFX_WAR_purge_the_radicals_shine" texturefile = "gfx/interface/goals/WAR/WAR_Purge_The_Radicals.tga" effectFile = "gfx/FX/buttonstate.lua" animation = { animationmaskfile = "gfx/interface/goals/WAR/WAR_Purge_The_Radicals.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = -90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } animation = { animationmaskfile = "gfx/interface/goals/WAR/WAR_Purge_The_Radicals.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = 90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } legacy_lazy_load = no } SpriteType = { name = "GFX_WAR_reeling_from_shock_shine" texturefile = "gfx/interface/goals/WAR/WAR_Reeling_From_The_Shock.tga" effectFile = "gfx/FX/buttonstate.lua" animation = { animationmaskfile = "gfx/interface/goals/WAR/WAR_Reeling_From_The_Shock.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = -90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } animation = { animationmaskfile = "gfx/interface/goals/WAR/WAR_Reeling_From_The_Shock.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = 90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } legacy_lazy_load = no } SpriteType = { name = "GFX_goal_all_tools_of_war_shine" texturefile = "gfx/interface/goals/ZAR/All_The_Tools_Of_War.tga" effectFile = "gfx/FX/buttonstate.lua" animation = { animationmaskfile = "gfx/interface/goals/ZAR/All_The_Tools_Of_War.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = -90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } animation = { animationmaskfile = "gfx/interface/goals/ZAR/All_The_Tools_Of_War.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = 90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } legacy_lazy_load = no } SpriteType = { name = "GFX_goal_intervene_in_the_great_war_shine" texturefile = "gfx/interface/goals/HIP/Intervene_In_The_Great_War.tga" effectFile = "gfx/FX/buttonstate.lua" animation = { animationmaskfile = "gfx/interface/goals/HIP/Intervene_In_The_Great_War.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = -90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } animation = { animationmaskfile = "gfx/interface/goals/HIP/Intervene_In_The_Great_War.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = 90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } legacy_lazy_load = no } SpriteType = { name = "GFX_goal_north_war_commission_shine" texturefile = "gfx/interface/goals/HIP/The_North_Zebrican_War_Commision.tga" effectFile = "gfx/FX/buttonstate.lua" animation = { animationmaskfile = "gfx/interface/goals/HIP/The_North_Zebrican_War_Commision.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = -90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } animation = { animationmaskfile = "gfx/interface/goals/HIP/The_North_Zebrican_War_Commision.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = 90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } legacy_lazy_load = no } SpriteType = { name = "GFX_goal_people_at_war_shine" texturefile = "gfx/interface/goals/ZAR/A_People_At_War.tga" effectFile = "gfx/FX/buttonstate.lua" animation = { animationmaskfile = "gfx/interface/goals/ZAR/A_People_At_War.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = -90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } animation = { animationmaskfile = "gfx/interface/goals/ZAR/A_People_At_War.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = 90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } legacy_lazy_load = no } SpriteType = { name = "GFX_goal_prepare_second_war_shine" texturefile = "gfx/interface/goals/HIP/Prepare_For_The_Second_War.tga" effectFile = "gfx/FX/buttonstate.lua" animation = { animationmaskfile = "gfx/interface/goals/HIP/Prepare_For_The_Second_War.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = -90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } animation = { animationmaskfile = "gfx/interface/goals/HIP/Prepare_For_The_Second_War.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = 90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } legacy_lazy_load = no } SpriteType = { name = "GFX_highill_post_civil_war_shine" texturefile = "gfx/interface/goals/GRF/highill_post_civil_war.tga" effectFile = "gfx/FX/buttonstate.lua" animation = { animationmaskfile = "gfx/interface/goals/GRF/highill_post_civil_war.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = -90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } animation = { animationmaskfile = "gfx/interface/goals/GRF/highill_post_civil_war.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = 90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } legacy_lazy_load = no } SpriteType = { name = "GFX_ironclaw_post_civil_war_shine" texturefile = "gfx/interface/goals/GRF/ironclaw_post_civil_war.tga" effectFile = "gfx/FX/buttonstate.lua" animation = { animationmaskfile = "gfx/interface/goals/GRF/ironclaw_post_civil_war.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = -90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } animation = { animationmaskfile = "gfx/interface/goals/GRF/ironclaw_post_civil_war.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = 90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } legacy_lazy_load = no } SpriteType = { name = "GFX_wildcard_post_civil_war_shine" texturefile = "gfx/interface/goals/GRF/wildcard_post_civil_war.tga" effectFile = "gfx/FX/buttonstate.lua" animation = { animationmaskfile = "gfx/interface/goals/GRF/wildcard_post_civil_war.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = -90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } animation = { animationmaskfile = "gfx/interface/goals/GRF/wildcard_post_civil_war.tga" animationtexturefile = "gfx/interface/goals/shine_overlay.dds" animationrotation = 90.0 animationlooping = no animationtime = 0.75 animationdelay = 0 animationblendmode = "add" animationtype = "scrolling" animationrotationoffset = { x = 0.0 y = 0.0 } animationtexturescale = { x = 1.0 y = 1.0 } } legacy_lazy_load = no } }
0
0.753172
1
0.753172
game-dev
MEDIA
0.90961
game-dev
0.565745
1
0.565745
libraryaddict/LibsDisguises
2,073
plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ShulkerWatcher.java
package me.libraryaddict.disguise.disguisetypes.watchers; import com.github.retrooper.packetevents.util.Vector3i; import me.libraryaddict.disguise.disguisetypes.AnimalColor; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; import org.bukkit.DyeColor; import org.bukkit.block.BlockFace; import java.util.Optional; /** * @author Navid */ public class ShulkerWatcher extends InsentientWatcher { public ShulkerWatcher(Disguise disguise) { super(disguise); } public BlockFace getFacingDirection() { return BlockFace.valueOf(getData(MetaIndex.SHULKER_FACING).name()); } public void setFacingDirection(BlockFace face) { sendData(MetaIndex.SHULKER_FACING, com.github.retrooper.packetevents.protocol.world.BlockFace.valueOf(face.name())); } public Vector3i getAttachmentPosition() { return getData(MetaIndex.SHULKER_ATTACHED).orElse(Vector3i.zero()); } public void setAttachmentPosition(Vector3i pos) { sendData(MetaIndex.SHULKER_ATTACHED, Optional.ofNullable(pos)); } public int getShieldHeight() { return getData(MetaIndex.SHULKER_PEEKING); } public void setShieldHeight(int newHeight) { if (newHeight < 0) { newHeight = 0; } if (newHeight > 127) { newHeight = 127; } sendData(MetaIndex.SHULKER_PEEKING, (byte) newHeight); } public DyeColor getColor() { if (!hasValue(MetaIndex.SHULKER_COLOR) || getData(MetaIndex.SHULKER_COLOR) == (byte) 16) { return DyeColor.PURPLE; } return AnimalColor.getColorByWool(getData(MetaIndex.SHULKER_COLOR)).getDyeColor(); } @Deprecated public void setColor(AnimalColor color) { setColor(color.getDyeColor()); } public void setColor(DyeColor newColor) { if (newColor == getColor()) { return; } sendData(MetaIndex.SHULKER_COLOR, newColor == null ? (byte) 16 : newColor.getWoolData()); } }
0
0.794601
1
0.794601
game-dev
MEDIA
0.582949
game-dev
0.898141
1
0.898141
ServUO/ServUO
1,244
Scripts/Services/Quests/Regions/QuestOfferRegion.cs
using System; using System.Xml; using Server.Mobiles; using Server.Regions; namespace Server.Engines.Quests { public class QuestOfferRegion : BaseRegion { private readonly Type m_Quest; public QuestOfferRegion(XmlElement xml, Map map, Region parent) : base(xml, map, parent) { ReadType(xml["quest"], "type", ref this.m_Quest); } public Type Quest { get { return this.m_Quest ; } } public override void OnEnter(Mobile m) { base.OnEnter(m); if (this.m_Quest == null) return; PlayerMobile player = m as PlayerMobile; if (player != null && player.Quest == null && QuestSystem.CanOfferQuest(m, this.m_Quest)) { try { QuestSystem qs = (QuestSystem)Activator.CreateInstance(this.m_Quest, new object[] { player }); qs.SendOffer(); } catch (Exception ex) { Console.WriteLine("Error creating quest {0}: {1}", this.m_Quest, ex); } } } } }
0
0.904933
1
0.904933
game-dev
MEDIA
0.917047
game-dev
0.872973
1
0.872973
fish-li/ClownFish.net
8,879
src/ClownFish.net/Base/Debug/DebugReport.cs
using ClownFish.Data.CodeDom; using ClownFish.Tasks; namespace ClownFish.Base; /// <summary> /// 运行时诊断报告,由Venus提供页面支持 /// </summary> public static class DebugReport { /// <summary> /// 查看状态数据 /// </summary> private static readonly List<Func<DebugReportBlock>> s_statusInfoCbList = new List<Func<DebugReportBlock>>(32); /// <summary> /// 查看系统信息 /// </summary> private static readonly List<DebugReportBlock> s_sysInfoList = new List<DebugReportBlock>(5); /// <summary> /// 查看配置参数 /// </summary> private static readonly List<DebugReportBlock> s_configList = new List<DebugReportBlock>(5); /// <summary> /// 查看参数变量 /// </summary> private static readonly List<object> s_optionList = new(20); /// <summary> /// 查看程序集信息 /// </summary> private static readonly List<DebugReportBlock> s_asmInfoList = new List<DebugReportBlock>(5); /// <summary> /// 注册一个包含“配置参数”定义的类型,用于在 “查看参数变量” 时展示其中的属性和字段 /// </summary> /// <param name="optionType"></param> public static void RegisterOptionsType(Type optionType) { if( optionType != null ) { lock( s_optionList ) { s_optionList.Add(optionType); } } } /// <summary> /// 注册一个包含“配置参数”定义的对象实例,用于在 “查看参数变量” 时展示其中的属性和字段 /// </summary> /// <param name="optionObject"></param> public static void RegisterOptionsObject(object optionObject) { if( optionObject != null ) { lock( s_optionList ) { s_optionList.Add(optionObject); } } } /// <summary> /// 注册回调委托,用于在 “查看参数变量” 时执行 /// </summary> /// <param name="cb"></param> public static void RegisterOptionsCallback(Func<NameValue> cb) { if( cb != null ) { lock( s_optionList ) { s_optionList.Add(cb); } } } /// <summary> /// 注册回调委托,用于在 “查看状态数据” 时执行 /// </summary> /// <param name="callback"></param> public static void RegisterStatusInfoCallback(Func<DebugReportBlock> callback) { if( callback != null ) { lock( s_statusInfoCbList ) { s_statusInfoCbList.Add(callback); } } } /// <summary> /// 注册一个报告片段,用于在 “查看系统信息” 时展示 /// </summary> /// <param name="block"></param> public static void RegisterSysInfoBlock(DebugReportBlock block) { if( block != null ) { lock( s_sysInfoList ) { s_sysInfoList.Add(block); } } } /// <summary> /// 注册一个报告片段,用于在 “查看配置参数” 时展示 /// </summary> /// <param name="block"></param> public static void RegisterConfigDataBlock(DebugReportBlock block) { if( block != null ) { lock( s_configList ) { s_configList.Add(block); } } } /// <summary> /// 注册一个报告片段,用于在 “查看程序集信息” 时展示 /// </summary> /// <param name="block"></param> public static void RegisterAssemblyInfoBlock(DebugReportBlock block) { if( block != null ) { lock( s_asmInfoList ) { s_asmInfoList.Add(block); } } } /// <summary> /// /// </summary> public static readonly string HeaderText = @$" ============================================================= {EnvUtils.GetAppName()}/{EnvUtils.AppRuntimeId} ============================================================= ".TrimStart(); #if NET9_0_OR_GREATER private static readonly Lock s_lock = new Lock(); #else private static readonly object s_lock = new object(); #endif private static bool s_inited = false; /// <summary> /// Init /// </summary> public static void Init() { if( s_inited == false ) { lock( s_lock ) { if( s_inited == false ) { RegisterSysInfoBlock(DebugReportBlocks.GetSystemInfo()); RegisterSysInfoBlock(NHttpApplication.Instance.GetDebugReportBlock()); RegisterConfigDataBlock(DebugReportBlocks.GetEnvironmentVariables()); RegisterConfigDataBlock(MemoryConfig.GetDebugReportBlock()); RegisterConfigDataBlock(AppConfig.GetDebugReportBlock()); RegisterConfigDataBlock(LogConfig.GetDebugReportBlock()); RegisterAssemblyInfoBlock(ProxyLoader.EntityProxyAssemblyListReportBlock); RegisterAssemblyInfoBlock(ProxyBuilder.CompileEntityListReportBlock); RegisterAssemblyInfoBlock(DebugReportBlocks.GetEntityProxyLoaderList()); RegisterAssemblyInfoBlock(DebugReportBlocks.GetAssemblyListInfo()); RegisterOptionsType(typeof(LoggingOptions)); RegisterOptionsType(typeof(LoggingOptions.Http)); RegisterOptionsType(typeof(LoggingOptions.HttpClient)); RegisterOptionsType(typeof(LoggingLimit)); RegisterOptionsType(typeof(LoggingLimit.OprLog)); RegisterOptionsType(typeof(LoggingLimit.SQL)); RegisterOptionsType(typeof(HttpClientDefaults)); RegisterOptionsType(typeof(CacheOption)); RegisterOptionsType(typeof(ClownFishOptions)); RegisterOptionsType(typeof(ClownFishPubOptions)); #if NETCOREAPP RegisterStatusInfoCallback(DebugReportBlocks.GetThreadPoolInfo); RegisterStatusInfoCallback(DebugReportBlocks.GetGCInfo); RegisterStatusInfoCallback(MemoryStreamPool.GetStatus); #endif RegisterStatusInfoCallback(DebugReportBlocks.GetLoggingCounters); RegisterStatusInfoCallback(DebugReportBlocks.GetCacheStatus); s_inited = true; } } } } /// <summary> /// 获取某个部分报告 /// </summary> /// <param name="name"></param> /// <returns></returns> public static string GetReport(string name) { Init(); return name switch { "ALL" => GetAllData().ToText(), "StatusInfo" => GetStatusInfo().ToText(), "SysInfo" => GetSysInfo().ToText(), "AsmInfo" => GetAsmInfo().ToText(), "ConfigInfo" => GetConfigInfo().ToText(), "StaticVariables" => GetStaticVariables().ToText(), _ => "_NULL_" }; } internal static List<DebugReportBlock> GetStatusInfo() { List<DebugReportBlock> blocks = new List<DebugReportBlock>(30); foreach( var cb in s_statusInfoCbList ) { DebugReportBlock block = cb.Invoke(); if( block != null ) { blocks.Add(block); } } return blocks; } internal static List<DebugReportBlock> GetSysInfo() { List<DebugReportBlock> blocks = new List<DebugReportBlock>(10); return blocks.AddRange2(s_sysInfoList); } internal static List<DebugReportBlock> GetConfigInfo() { List<DebugReportBlock> blocks = new List<DebugReportBlock>(5); return blocks.AddRange2(s_configList); } internal static List<DebugReportBlock> GetStaticVariables() { List<DebugReportBlock> blocks = new List<DebugReportBlock>(1); DebugReportBlock block = DebugReportBlocks.GetStaticVariablesReportBlock(s_optionList); blocks.Add(block); return blocks; } internal static List<DebugReportBlock> GetAsmInfo() { List<DebugReportBlock> blocks = new List<DebugReportBlock>(5); return blocks.AddRange2(s_asmInfoList); } internal static List<DebugReportBlock> GetAllData() { return GetStatusInfo().AddRange2(s_sysInfoList).AddRange2(s_configList).AddRange2(s_asmInfoList); } internal static string ToText(this List<DebugReportBlock> blocks) { StringBuilder sb = StringBuilderPool.Get(); try { sb.AppendLineRN(HeaderText); foreach( var b in blocks.Where(x => x != null).OrderBy(x => x.Order) ) { b.GetText(sb); sb.AppendLine("\r\n"); } return sb.ToString(); } finally { StringBuilderPool.Return(sb); } } /// <summary> /// Write all info to DebugReport.txt /// </summary> public static void WriteAllToFile() { if( LocalSettings.GetBool("ClownFish_CreateDebugReport_AtAppStartup") ) { // 获取所有的诊断信息,并写入到临时文件中 string text = DebugReport.GetReport("ALL"); string filePath = Path.Combine(EnvUtils.GetTempPath(), "DebugReport.txt"); RetryFile.WriteAllText(filePath, text); } } }
0
0.89861
1
0.89861
game-dev
MEDIA
0.50157
game-dev
0.804955
1
0.804955
hannibal002/SkyHanni
2,664
versions/1.21.5/src/main/java/at/hannibal2/skyhanni/features/hunting/InvisibugHighlighter.kt
package at.hannibal2.skyhanni.features.hunting import at.hannibal2.skyhanni.SkyHanniMod import at.hannibal2.skyhanni.api.event.HandleEvent import at.hannibal2.skyhanni.config.ConfigUpdaterMigrator import at.hannibal2.skyhanni.data.IslandType import at.hannibal2.skyhanni.events.ReceiveParticleEvent import at.hannibal2.skyhanni.events.SecondPassedEvent import at.hannibal2.skyhanni.events.minecraft.SkyHanniRenderWorldEvent import at.hannibal2.skyhanni.skyhannimodule.SkyHanniModule import at.hannibal2.skyhanni.utils.ColorUtils.toColor import at.hannibal2.skyhanni.utils.EntityUtils import at.hannibal2.skyhanni.utils.EntityUtils.canBeSeen import at.hannibal2.skyhanni.utils.LocationUtils.distanceTo import at.hannibal2.skyhanni.utils.LorenzVec import at.hannibal2.skyhanni.utils.MobUtils.isCompletelyDefault import at.hannibal2.skyhanni.utils.getLorenzVec import at.hannibal2.skyhanni.utils.render.WorldRenderUtils.drawWaypointFilled import net.minecraft.entity.LivingEntity import net.minecraft.entity.decoration.ArmorStandEntity import net.minecraft.particle.ParticleTypes @SkyHanniModule object InvisibugHighlighter { private val config get() = SkyHanniMod.feature.hunting.mobHighlight.invisibug private val invisibugEntities = mutableListOf<LivingEntity>() @HandleEvent(onlyOnIsland = IslandType.GALATEA) fun onParticle(event: ReceiveParticleEvent) { if (!config.enabled) return val particle = event.type if (particle != ParticleTypes.CRIT) return val nearestArmorStand = EntityUtils.getEntitiesNearby<ArmorStandEntity>(event.location, 5.0) .minByOrNull { it.distanceTo(event.location) } if (nearestArmorStand == null || !nearestArmorStand.isCompletelyDefault()) return invisibugEntities.add(nearestArmorStand) } @HandleEvent(onlyOnIsland = IslandType.GALATEA) fun onRenderWorld(event: SkyHanniRenderWorldEvent) { if (!config.enabled) return for (entity in invisibugEntities.toList()) { if (!entity.canBeSeen(32)) continue event.drawWaypointFilled( entity.getLorenzVec() - LorenzVec(0.4, -0.2, 0.4), config.color.toColor(), extraSize = -0.2, ) } } @HandleEvent(onlyOnIsland = IslandType.GALATEA) fun onSecondPassed(event: SecondPassedEvent) { if (!config.enabled) return EntityUtils.removeInvalidEntities(invisibugEntities) } @HandleEvent fun onConfigFixEvent(event: ConfigUpdaterMigrator.ConfigFixEvent) { event.move(100, "foraging.mobHighlight.invisibug", "hunting.mobHighlight.invisibug") } }
0
0.635082
1
0.635082
game-dev
MEDIA
0.959553
game-dev
0.574379
1
0.574379
Syrent/SayanVanish
5,624
sayanvanish-proxy/sayanvanish-proxy-velocity/src/main/kotlin/org/sayandev/sayanvanish/velocity/command/SayanVanishProxyCommandVelocity.kt
package org.sayandev.sayanvanish.velocity.command import com.velocitypowered.api.proxy.Player import javassist.compiler.ast.Pair import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder import org.incendo.cloud.component.CommandComponent import org.incendo.cloud.context.CommandContext import org.incendo.cloud.description.Description import org.incendo.cloud.kotlin.MutableCommandBuilder import org.incendo.cloud.parser.standard.StringParser import org.incendo.cloud.suggestion.Suggestion import org.incendo.cloud.velocity.VelocityCommandManager import org.incendo.cloud.velocity.parser.PlayerParser import org.sayandev.sayanvanish.api.Permission import org.sayandev.sayanvanish.api.VanishOptions import org.sayandev.sayanvanish.api.feature.Features import org.sayandev.sayanvanish.proxy.command.SayanVanishProxyCommand import org.sayandev.sayanvanish.proxy.config.language import org.sayandev.sayanvanish.proxy.config.settings import org.sayandev.sayanvanish.velocity.api.SayanVanishVelocityAPI.Companion.getOrAddUser import org.sayandev.sayanvanish.velocity.feature.features.FeatureUpdate import org.sayandev.sayanvanish.velocity.utils.PlayerUtils.sendComponent import org.sayandev.stickynote.velocity.StickyNote import org.sayandev.stickynote.velocity.command.VelocityCommand import org.sayandev.stickynote.velocity.command.VelocitySender import org.sayandev.stickynote.velocity.command.commandManager import org.sayandev.stickynote.velocity.plugin import org.sayandev.stickynote.velocity.utils.AdventureUtils.component import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import kotlin.jvm.optionals.getOrNull class SayanVanishProxyCommandVelocity : VelocityCommand(settings.command.name, *settings.command.aliases.toTypedArray()) { override fun rootBuilder(builder: MutableCommandBuilder<VelocitySender>) { builder.permission("${plugin.container.description.name.get().lowercase()}.commands.use") builder.optional("player", PlayerParser.playerParser()) builder.flag( "state", emptyArray(), Description.empty(), CommandComponent.builder<VelocitySender, String>("state", StringParser.stringParser()) .suggestionProvider { _, _ -> CompletableFuture.completedFuture(listOf("on", "off").map { Suggestion.suggestion(it) }) } ) builder.flag("silent", arrayOf("s")) } override fun rootHandler(context: CommandContext<VelocitySender>) { val sender = context.sender().platformSender() val target = context.optional<Player>("player") val state = context.flags().get<String>("state") if (!target.isPresent && sender !is Player) { sender.sendComponent(language.general.haveToProvidePlayer.component()) return } if (target.isPresent && !sender.hasPermission(Permission.VANISH_OTHERS.permission())) { sender.sendComponent(language.general.dontHavePermission.component()) return } val player = if (target.isPresent) context.optional<Player>("player").get() else context.sender().player() ?: return val user = player.getOrAddUser() if (!user.hasPermission(Permission.VANISH)) { user.sendComponent(language.general.dontHavePermission, Pair("permission", Permission.VANISH.permission())) return } val options = VanishOptions.defaultOptions().apply { if (context.flags().hasFlag("silent")) { this.sendMessage = false } } val targetPlayer = target.getOrNull() ?: sender as? Player ?: let { sender.sendMessage(language.general.haveToProvidePlayer.component()) return } when (state) { "on" -> user.vanish(options) "off" -> user.unVanish(options) else -> user.toggleVanish(options) } context.sender().platformSender().sendComponent(language.vanish.vanishToggle.component(Placeholder.unparsed("player", targetPlayer.username), Placeholder.parsed("state", user.stateText(!user.isVanished)))) } init { var forceUpdateConfirm = false rawCommandBuilder().registerCopy { literalWithPermission("forceupdate") handler { context -> val sender = context.sender().platformSender() if (!forceUpdateConfirm) { sender.sendComponent(language.general.confirmUpdate.component()) forceUpdateConfirm = true StickyNote.run({ forceUpdateConfirm = false }, 5, TimeUnit.SECONDS) return@handler } sender.sendComponent(language.general.updating.component()) StickyNote.run { val updateFeature = Features.getFeature<FeatureUpdate>() updateFeature.updatePlugin().whenComplete { isSuccessful, error -> error?.printStackTrace() StickyNote.run { if (isSuccessful) { sender.sendComponent(language.general.updated.component(Placeholder.unparsed("version", updateFeature.latestVersion()))) } else { sender.sendComponent(language.general.updateFailed.component()) } } } } } } } }
0
0.897373
1
0.897373
game-dev
MEDIA
0.632359
game-dev
0.950584
1
0.950584
Sidekick-Poe/Sidekick
2,371
src/Sidekick.Apis.Poe.Trade/Parser/Properties/Definitions/ItemRarityProperty.cs
using System.Text.RegularExpressions; using Sidekick.Apis.Poe.Items; using Sidekick.Apis.Poe.Languages; using Sidekick.Apis.Poe.Trade.Parser.Properties.Filters; using Sidekick.Apis.Poe.Trade.Trade.Requests; using Sidekick.Apis.Poe.Trade.Trade.Requests.Filters; using Sidekick.Apis.Poe.Trade.Trade.Results; using Sidekick.Common.Settings; namespace Sidekick.Apis.Poe.Trade.Parser.Properties.Definitions; public class ItemRarityProperty(IGameLanguageProvider gameLanguageProvider) : PropertyDefinition { private Regex Pattern { get; } = gameLanguageProvider.Language.DescriptionItemRarity.ToRegexIntCapture(); private Regex IsAugmentedPattern { get; } = gameLanguageProvider.Language.DescriptionItemRarity.ToRegexIsAugmented(); public override List<Category> ValidCategories { get; } = [Category.Map, Category.Contract, Category.Logbook]; public override void Parse(Item item) { var propertyBlock = item.Text.Blocks[1]; item.Properties.ItemRarity = GetInt(Pattern, propertyBlock); if (item.Properties.ItemRarity == 0) return; propertyBlock.Parsed = true; if (GetBool(IsAugmentedPattern, propertyBlock)) item.Properties.AugmentedProperties.Add(nameof(ItemProperties.ItemRarity)); } public override Task<PropertyFilter?> GetFilter(Item item, double normalizeValue, FilterType filterType) { if (item.Properties.ItemRarity <= 0) return Task.FromResult<PropertyFilter?>(null); var filter = new IntPropertyFilter(this) { Text = gameLanguageProvider.Language.DescriptionItemRarity, NormalizeEnabled = true, NormalizeValue = normalizeValue, Value = item.Properties.ItemRarity, ValuePrefix = "+", ValueSuffix = "%", Checked = false, Type = item.Properties.AugmentedProperties.Contains(nameof(ItemProperties.ItemRarity)) ? LineContentType.Augmented : LineContentType.Simple, }; filter.ChangeFilterType(filterType); return Task.FromResult<PropertyFilter?>(filter); } public override void PrepareTradeRequest(Query query, Item item, PropertyFilter filter) { if (!filter.Checked || filter is not IntPropertyFilter intFilter) return; query.Filters.GetOrCreateMapFilters().Filters.ItemRarity = new StatFilterValue(intFilter); } }
0
0.697987
1
0.697987
game-dev
MEDIA
0.604566
game-dev
0.807939
1
0.807939
flutter/codelabs
2,315
forge2d_game/step_07/lib/components/enemy.dart
// Copyright 2024 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math'; import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flutter/material.dart'; import 'body_component_with_user_data.dart'; const enemySize = 5.0; enum EnemyColor { pink(color: 'pink', boss: false), blue(color: 'blue', boss: false), green(color: 'green', boss: false), yellow(color: 'yellow', boss: false), pinkBoss(color: 'pink', boss: true), blueBoss(color: 'blue', boss: true), greenBoss(color: 'green', boss: true), yellowBoss(color: 'yellow', boss: true); final bool boss; final String color; const EnemyColor({required this.color, required this.boss}); static EnemyColor get randomColor => EnemyColor.values[Random().nextInt(EnemyColor.values.length)]; String get fileName => 'alien${color.capitalize}_${boss ? 'suit' : 'square'}.png'; } class Enemy extends BodyComponentWithUserData with ContactCallbacks { Enemy(Vector2 position, Sprite sprite) : super( renderBody: false, bodyDef: BodyDef() ..position = position ..type = BodyType.dynamic, fixtureDefs: [ FixtureDef( PolygonShape()..setAsBoxXY(enemySize / 2, enemySize / 2), friction: 0.3, ), ], children: [ SpriteComponent( anchor: Anchor.center, sprite: sprite, size: Vector2.all(enemySize), position: Vector2(0, 0), ), ], ); @override void beginContact(Object other, Contact contact) { var interceptVelocity = (contact.bodyA.linearVelocity - contact.bodyB.linearVelocity).length .abs(); if (interceptVelocity > 35) { removeFromParent(); } super.beginContact(other, contact); } @override void update(double dt) { super.update(dt); if (position.x > camera.visibleWorldRect.right + 10 || position.x < camera.visibleWorldRect.left - 10) { removeFromParent(); } } } extension on String { String get capitalize => characters.first.toUpperCase() + characters.skip(1).toLowerCase().join(); }
0
0.876131
1
0.876131
game-dev
MEDIA
0.85061
game-dev
0.952909
1
0.952909
Albeoris/Memoria
3,337
Assembly-CSharp/Global/UI/UI2/UI2DSpriteAnimation.cs
using System; using UnityEngine; public class UI2DSpriteAnimation : MonoBehaviour { public Boolean isPlaying { get { return base.enabled; } } public Int32 framesPerSecond { get { return this.framerate; } set { this.framerate = value; } } public void Play() { if (this.frames != null && (Int32)this.frames.Length > 0) { if (!base.enabled && !this.loop) { Int32 num = (Int32)((this.framerate <= 0) ? (this.mIndex - 1) : (this.mIndex + 1)); if (num < 0 || num >= (Int32)this.frames.Length) { this.mIndex = (Int32)((this.framerate >= 0) ? 0 : ((Int32)this.frames.Length - 1)); } } base.enabled = true; this.UpdateSprite(); } } public void Pause() { base.enabled = false; } public void ResetToBeginning() { this.mIndex = (Int32)((this.framerate >= 0) ? 0 : ((Int32)this.frames.Length - 1)); this.UpdateSprite(); } private void Start() { this.Play(); } private void Update() { if (this.frames == null || this.frames.Length == 0) { base.enabled = false; } else if (this.framerate != 0) { Single num = (!this.ignoreTimeScale) ? Time.time : RealTime.time; if (this.mUpdate < num) { this.mUpdate = num; Int32 num2 = (Int32)((this.framerate <= 0) ? (this.mIndex - 1) : (this.mIndex + 1)); if (!this.loop && (num2 < 0 || num2 >= (Int32)this.frames.Length)) { base.enabled = false; return; } this.mIndex = NGUIMath.RepeatIndex(num2, (Int32)this.frames.Length); this.UpdateSprite(); } } } private void UpdateSprite() { if (this.mUnitySprite == (UnityEngine.Object)null && this.mNguiSprite == (UnityEngine.Object)null) { this.mUnitySprite = base.GetComponent<SpriteRenderer>(); this.mNguiSprite = base.GetComponent<UI2DSprite>(); if (this.mUnitySprite == (UnityEngine.Object)null && this.mNguiSprite == (UnityEngine.Object)null) { base.enabled = false; return; } } Single num = (!this.ignoreTimeScale) ? Time.time : RealTime.time; if (this.framerate != 0) { this.mUpdate = num + Mathf.Abs(1f / (Single)this.framerate); } if (this.mUnitySprite != (UnityEngine.Object)null) { this.mUnitySprite.sprite = this.frames[this.mIndex]; } else if (this.mNguiSprite != (UnityEngine.Object)null) { this.mNguiSprite.nextSprite = this.frames[this.mIndex]; } } [SerializeField] protected Int32 framerate = 20; public Boolean ignoreTimeScale = true; public Boolean loop = true; public Sprite[] frames; private SpriteRenderer mUnitySprite; private UI2DSprite mNguiSprite; private Int32 mIndex; private Single mUpdate; }
0
0.588877
1
0.588877
game-dev
MEDIA
0.728265
game-dev,graphics-rendering
0.934676
1
0.934676
hieki-chan/Supermarket-Simulator-Prototype
7,809
Library/PackageCache/com.unity.addressables@1.21.21/Editor/Build/AnalyzeRules/AnalyzeSystem.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor.AddressableAssets.Build.AnalyzeRules; using UnityEditor.AddressableAssets.GUI; using UnityEditor.AddressableAssets.Settings; using UnityEngine; using UnityEngine.AddressableAssets; namespace UnityEditor.AddressableAssets.Build { /// <summary> /// Static system to manage Analyze functionality. /// </summary> [Serializable] public static class AnalyzeSystem { /// <summary> /// Method used to register any custom AnalyzeRules with the AnalyzeSystem. This replaces calling into the AnalyzeWindow /// directly to remove logic from the GUI. The recommended pattern is to create /// your rules like so: /// <code> /// class MyRule : AnalyzeRule {} /// [InitializeOnLoad] /// class RegisterMyRule /// { /// static RegisterMyRule() /// { /// AnalyzeSystem.RegisterNewRule&lt;MyRule&gt;(); /// } /// } /// </code> /// </summary> /// <typeparam name="TRule">The rule type.</typeparam> public static void RegisterNewRule<TRule>() where TRule : AnalyzeRule, new() { foreach (var rule in Rules) { if (rule.GetType().Equals(typeof(TRule))) return; } Rules.Add(new TRule()); } internal static string AnalyzeRuleDataFolder { get { return $"{Addressables.LibraryPath}/AnalyzeData"; } } internal static string AnalyzeRuleDataName => "AnalyzeRuleData.json"; internal static string AnalyzeRuleDataPath => AnalyzeRuleDataFolder + "/" + AnalyzeRuleDataName; internal static string AnalyzeRuleDataAssetsFolderPath { get { var settings = AddressableAssetSettingsDefaultObject.Settings; var path = AddressableAssetSettingsDefaultObject.kDefaultConfigFolder; if (settings != null && settings.IsPersisted) path = settings.ConfigFolder; return path + "/AnalyzeData/"; } } internal static AddressableAssetSettings Settings => AddressableAssetSettingsDefaultObject.Settings; internal static List<AnalyzeRule> Rules { get; } = new List<AnalyzeRule>(); [SerializeField] private static AddressablesAnalyzeResultData m_AnalyzeData; internal static AssetSettingsAnalyzeTreeView TreeView { get; set; } internal static AddressablesAnalyzeResultData AnalyzeData { get { if (m_AnalyzeData == null) { if (!Directory.Exists(AnalyzeRuleDataFolder)) Directory.CreateDirectory(AnalyzeRuleDataFolder); DeserializeData(); } return m_AnalyzeData; } } internal static void ReloadUI() { TreeView?.Reload(); } internal static void SerializeData() { SerializeData(AnalyzeRuleDataPath); } internal static void DeserializeData() { DeserializeData(AnalyzeRuleDataPath); } /// <summary> /// Serialize the analysis data to json and save to disk /// </summary> /// <param name="path">File path to save to</param> public static void SerializeData(string path) { File.WriteAllText(path, JsonUtility.ToJson(m_AnalyzeData)); } /// <summary> /// Load and deserialize analysis data from json file and reload /// </summary> /// <param name="path">File path to load from</param> public static void DeserializeData(string path) { if (!File.Exists(path)) File.WriteAllText(path, JsonUtility.ToJson(new AddressablesAnalyzeResultData())); //Cleans up the previous result data if (Directory.Exists(AnalyzeRuleDataAssetsFolderPath)) Directory.Delete(AnalyzeRuleDataAssetsFolderPath, true); m_AnalyzeData = JsonUtility.FromJson<AddressablesAnalyzeResultData>(File.ReadAllText(path)); if (m_AnalyzeData == null) Addressables.LogWarning($"Unable to load Analyze Result Data at {path}."); else { if (m_AnalyzeData.Data == null) m_AnalyzeData.Data = new Dictionary<string, List<AnalyzeRule.AnalyzeResult>>(); foreach (var rule in Rules) { if (rule == null) { Addressables.LogWarning("An unknown Analyze rule is being skipped because it is null."); continue; } if (!m_AnalyzeData.Data.ContainsKey(rule.ruleName)) m_AnalyzeData.Data.Add(rule.ruleName, new List<AnalyzeRule.AnalyzeResult>()); } } ReloadUI(); } internal static void SaveDataForRule(AnalyzeRule rule, object data) { string jsonData = JsonUtility.ToJson(data); string path = $"{AnalyzeRuleDataFolder}/{rule.ruleName}Data.json"; File.WriteAllText(path, jsonData); } internal static T GetDataForRule<T>(AnalyzeRule rule) { string path = $"{AnalyzeRuleDataFolder}/{rule.ruleName}Data.json"; if (!File.Exists(path)) return default; string fileRead = File.ReadAllText(path); return JsonUtility.FromJson<T>(fileRead); } internal static void ReplaceAnalyzeData(AnalyzeRule rule, List<AnalyzeRule.AnalyzeResult> results) { m_AnalyzeData.Data[rule.ruleName] = results; } internal static List<AnalyzeRule.AnalyzeResult> RefreshAnalysis<TRule>() where TRule : AnalyzeRule { return RefreshAnalysis(FindRule<TRule>()); } internal static List<AnalyzeRule.AnalyzeResult> RefreshAnalysis(AnalyzeRule rule) { if (rule == null) return null; if (!AnalyzeData.Data.ContainsKey(rule.ruleName)) AnalyzeData.Data.Add(rule.ruleName, new List<AnalyzeRule.AnalyzeResult>()); AnalyzeData.Data[rule.ruleName] = rule.RefreshAnalysis(Settings); return AnalyzeData.Data[rule.ruleName]; } internal static void ClearAnalysis<TRule>() where TRule : AnalyzeRule { ClearAnalysis(FindRule<TRule>()); } internal static void ClearAnalysis(AnalyzeRule rule) { if (rule == null) return; if (!AnalyzeData.Data.ContainsKey(rule.ruleName)) AnalyzeData.Data.Add(rule.ruleName, new List<AnalyzeRule.AnalyzeResult>()); rule.ClearAnalysis(); ; AnalyzeData.Data[rule.ruleName].Clear(); } internal static void FixIssues<TRule>() where TRule : AnalyzeRule { FixIssues(FindRule<TRule>()); } internal static void FixIssues(AnalyzeRule rule) { rule?.FixIssues(Settings); } private static AnalyzeRule FindRule<TRule>() where TRule : AnalyzeRule { var rule = Rules.FirstOrDefault(r => r.GetType().IsAssignableFrom(typeof(TRule))); if (rule == null) throw new ArgumentException($"No rule found corresponding to type {typeof(TRule)}"); return rule; } } }
0
0.863909
1
0.863909
game-dev
MEDIA
0.157536
game-dev
0.970612
1
0.970612
plusls/oh-my-minecraft-client
2,496
src/main/java/com/plusls/ommc/mixin/feature/highlightLavaSource/canvas/MixinSimpleFluidSpriteProvider.java
package com.plusls.ommc.mixin.feature.highlightLavaSource.canvas; import com.plusls.ommc.config.Configs; import com.plusls.ommc.feature.highlightLavaSource.LavaSourceResourceLoader; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.FluidTags; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.LiquidBlock; import net.minecraft.world.level.material.FluidState; import org.spongepowered.asm.mixin.Dynamic; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import top.hendrixshen.magiclib.dependency.annotation.Dependencies; import top.hendrixshen.magiclib.dependency.annotation.Dependency; @Dependencies(and = @Dependency("frex")) @Pseudo @Mixin(targets = "io.vram.frex.impl.model.SimpleFluidSpriteProvider", remap = false) public abstract class MixinSimpleFluidSpriteProvider { private boolean isLava; private final TextureAtlasSprite[] lavaSourceSpites = new TextureAtlasSprite[3]; @Dynamic @Inject(method = "<init>", at = @At(value = "RETURN")) private void preInit(ResourceLocation stillSpriteName, ResourceLocation flowingSpriteName, ResourceLocation overlaySpriteName, CallbackInfo ci) { this.isLava = stillSpriteName.toString().equals("minecraft:block/lava_still"); } @Dynamic @Inject(method = "getFluidSprites", at = @At(value = "RETURN"), cancellable = true) private void setLavaSprite(BlockAndTintGetter view, BlockPos pos, FluidState state, CallbackInfoReturnable<TextureAtlasSprite[]> cir) { if (this.isLava) { if (lavaSourceSpites[0] != LavaSourceResourceLoader.lavaSourceSpites[0]) { lavaSourceSpites[0] = LavaSourceResourceLoader.lavaSourceSpites[0]; lavaSourceSpites[1] = LavaSourceResourceLoader.lavaSourceSpites[1]; } if (Configs.highlightLavaSource && state.is(FluidTags.LAVA) && view.getBlockState(pos).getValue(LiquidBlock.LEVEL) == 0) { cir.setReturnValue(lavaSourceSpites); } } } }
0
0.93966
1
0.93966
game-dev
MEDIA
0.980085
game-dev
0.948347
1
0.948347
cping/LGame
1,949
Java/Loon-Neo/src/loon/action/sprite/painting/DrawableGameComponent.java
/** * Copyright 2008 - 2012 * * 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. * * @project loon * @author cping * @email:javachenpeng@yahoo.com * @version 0.3.3 */ package loon.action.sprite.painting; import loon.action.sprite.SpriteBatch; import loon.utils.timer.GameTime; public class DrawableGameComponent extends GameComponent implements IDrawable { private boolean _isInitialized; private boolean _isVisible; private int _drawOrder; public DrawableGameComponent(DrawableScreen game) { super(game); setVisible(true); } @Override public void initialize() { if (!_isInitialized) { _isInitialized = true; loadContent(); } } protected void loadContent() { } protected void unloadContent() { } public final int getDrawOrder() { return _drawOrder; } private ComponentEvent DrawOrder; public final void setDrawOrder(int value) { _drawOrder = value; if (DrawOrder != null) { DrawOrder.invoke(this); } } public final boolean getVisible() { return _isVisible; } private ComponentEvent Visible; public final void setVisible(boolean value) { if (_isVisible != value) { _isVisible = value; if (Visible != null) { Visible.invoke(this); } } } public void draw(SpriteBatch batch, GameTime gameTime) { } public void setDrawOrder(ComponentEvent drawOrder) { DrawOrder = drawOrder; } public void setVisible(ComponentEvent visible) { Visible = visible; } }
0
0.756994
1
0.756994
game-dev
MEDIA
0.922067
game-dev
0.611488
1
0.611488
ikr4-m/simple-memory-game
3,874
src/lib/generateBlock.ts
import { CardList, InitialDimension, MaximumDimension } from "./config"; type TBlockDirection = "vertical" | "horizontal"; type TCardValidation = "opened" | "rejected" | "levelUp" | "paired"; interface ICardPosition { alt: number, position: { x: number; y: number; } } export default class GenerateBlock { private dimension: number = 0; private blockDirection: TBlockDirection = "vertical"; private cardList: typeof CardList = [...CardList]; private arenaKey: typeof CardList[] = []; private arena: string[][] = []; private openedCard: ICardPosition[] = []; private revealedCard: ICardPosition[] = []; public reachingLimitLevel: boolean = false; constructor() { this.dimension = InitialDimension; this.generateArena(); } // Using Schwartzian Transform algorithm to shuffle multiply card private multiplyShuffleCard(randomCard: typeof CardList): typeof CardList { randomCard = randomCard.concat(randomCard); return randomCard .map(v => ({ v, sort: Math.random() })) .sort((a, b) => a.sort - b.sort) .map(v => v.v); } // Using Fisher Yates algorithm to dick-pick shuffle card private pullRandomCard(cardTotal: number): typeof CardList { const pulledCard: typeof CardList = []; for (let i = 0; i < cardTotal; i++) { if (this.cardList.length <= 0) this.cardList = [...CardList]; const indexCard = Math.floor(Math.random() * this.cardList.length); const randCard = this.cardList[indexCard]; pulledCard.push(randCard); this.cardList.splice(indexCard, 1); } return pulledCard; } public getEstimateCard(x: number = this.arena[0].length, y: number = this.arena.length): number { return Math.floor((x * y) / 2); } public generateArena(xTotal: number = this.dimension, yTotal: number = this.dimension) { if (this.reachingLimitLevel) return; if (Math.pow(MaximumDimension, 2) < (xTotal * yTotal)) { this.reachingLimitLevel = true; return; } const randomCard = this.pullRandomCard(this.getEstimateCard(xTotal, yTotal)); const shuffled = this.multiplyShuffleCard(randomCard); this.arena = []; this.arenaKey = []; for (let y = 0; y < yTotal; y++) { this.arena.push([]); this.arenaKey.push([]); for (let x = 0; x < xTotal; x++) { this.arena[y].push(""); this.arenaKey[y].push(shuffled.pop()!); } } } public expandArena(): void { let yRange = this.arenaKey.length; let xRange = this.arenaKey[0].length; if (this.blockDirection === "vertical") { yRange += this.dimension; this.blockDirection = "horizontal"; } else { xRange += this.dimension; this.blockDirection = "vertical"; } this.generateArena(xRange, yRange); } public validateCard(x: number, y:number): TCardValidation { const card = this.arenaKey[y][x]; let status: TCardValidation = "opened"; const position = { x: x, y: y }; // Assume double clicking the tile that opened is invalid if (this.arena[y][x]) return "opened"; this.arena[y][x] = card.img!; this.openedCard.push({ alt: card.alt, position }); if (this.openedCard.length === 2) { const [card1, card2] = this.openedCard; if (card1.alt !== card2.alt) status = "rejected"; else { this.revealedCard.push(card1); this.openedCard = []; status = "paired"; } } if (this.revealedCard.length === this.getEstimateCard()) { status = "levelUp"; this.revealedCard = []; } return status; } public closeRejectedCard(): void { this.openedCard.forEach(v => { this.arena[v.position.y][v.position.x] = ""; }); this.openedCard = []; } public getArena(): [typeof this.arena, typeof CardList[]] { return [this.arena, this.arenaKey]; } }
0
0.786095
1
0.786095
game-dev
MEDIA
0.845881
game-dev
0.959068
1
0.959068
iwiniwin/unity-remote-file-explorer
7,818
Editor/UI/ObjectItem.cs
using UnityEngine.UIElements; using UnityEditor; using UnityEngine; using System.IO; using System; using UnityEditor.Experimental; namespace RemoteFileExplorer.Editor.UI { public class ObjectItem : VisualElement { public Action<ObjectItem> clickItemCallback; public Action<ObjectItem> doubleClickItemCallback; public Action<ObjectItem> rightClickItemCallback; public Action<ObjectItem, string> completeInputCallback; const string k_UxmlFilesPath = "Packages/com.iwin.remotefileexplorer/Resources/UXML/ObjectItem.uxml"; public VisualElement objectView { get; } public Image objectIcon { get; } public Label objectLabel { get; } public TextField objectTextField { get; } private ObjectData m_Data; private Vector2 m_Size; public Vector2 Size { set { m_Size = value; this.style.width = value.x; this.style.height = value.y; } } public ObjectData Data { get { return m_Data; } } public ObjectItem(Vector2 size) { this.Size = size; var tree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(k_UxmlFilesPath); tree.CloneTree(this); objectView = this.Q<VisualElement>("objectView"); objectIcon = this.Q<Image>("objectIcon"); objectTextField = this.Q<TextField>("objectTextField"); objectLabel = this.Q<Label>("objectLabel"); this.RegisterCallback<MouseDownEvent>(this.OnMouseDown); this.RegisterCallback<MouseUpEvent>(this.OnMouseUp); objectLabel.RegisterCallback<GeometryChangedEvent>(this.OnLabelGeometryChanged); objectTextField.RegisterCallback<GeometryChangedEvent>(this.OnTextFieldGeometryChanged); objectTextField.RegisterCallback<FocusOutEvent>((FocusOutEvent e) => { if(completeInputCallback != null) { completeInputCallback(this, objectTextField.value); } }); objectTextField.RegisterCallback<KeyDownEvent>(e => { if (e.keyCode == KeyCode.Return || e.keyCode == KeyCode.KeypadEnter) { if(completeInputCallback != null) { completeInputCallback(this, objectTextField.value); } } }); } public void UpdateView(ObjectData data) { m_Data = data; SwitchToEdit(data.state == ObjectState.Editing); UpdateText(data.path); UpdateState(); } public void SwitchToEdit(bool edit) { if(edit) { objectLabel.style.display = DisplayStyle.None; objectTextField.style.display = DisplayStyle.Flex; } else { objectLabel.style.display = DisplayStyle.Flex; objectTextField.style.display = DisplayStyle.None; } } public void UpdateState() { switch (m_Data.state) { case ObjectState.Normal: if(EditorGUIUtility.isProSkin) { objectLabel.style.color = Color.white; } else { objectLabel.style.color = Color.black; } break; case ObjectState.Selected: Color c; ColorUtility.TryParseHtmlString("#5576bd", out c); objectLabel.style.color = c; break; default: break; } objectIcon.image = GetTexture(); } public Texture2D GetTexture() { string key = null; if(m_Data.type == ObjectType.Folder || m_Data.type == ObjectType.TempFolder) { key = "folder"; } else { key = Path.GetExtension(m_Data.path); if(key.StartsWith(".")) { key = key.Substring(1, key.Length - 1); } } if(m_Data.state == ObjectState.Selected) { key += " active"; } return TextureUtility.GetTexture(key); } public void UpdateText(string path) { string name = Path.GetFileName(path); string text = name; if(!FitWithinWidth(text)) { string ellipsis = "\u2026"; text = ""; for(int i = 0; i < name.Length; i ++) { if(!FitWithinWidth(text + ellipsis)) { break; } text += name[i]; } text += ellipsis; } objectLabel.text = text; } public bool FitWithinWidth(string text) { var rect = objectLabel.contentRect; if(float.NaN.Equals(rect.width)) { return true; // Label仍未初始化完成,将在OnGeometryChanged时重新计算 } float width = objectLabel.MeasureTextSize(text, rect.width, MeasureMode.AtMost, rect.height, MeasureMode.AtMost).x; return width < rect.width; } public void OnLabelGeometryChanged(GeometryChangedEvent e) { if(m_Data.state != ObjectState.Editing) { UpdateText(m_Data.path); } } public void OnTextFieldGeometryChanged(GeometryChangedEvent e) { if(m_Data.state == ObjectState.Editing) { objectTextField.value = Path.GetFileName(m_Data.path); var l = objectTextField.Q<VisualElement>("unity-text-input"); l.Focus(); objectTextField.SelectAll(); } } public void OnMouseDown(MouseDownEvent e) { if (e.button == 0) { if (clickItemCallback != null) { clickItemCallback(this); } if (e.clickCount == 2) { doubleClickItemCallback(this); } } else if(e.button == 1) { if(clickItemCallback != null) { clickItemCallback(this); } } e.StopImmediatePropagation(); } public void OnMouseUp(MouseUpEvent e) { if(e.button == 1) { if(rightClickItemCallback != null) { rightClickItemCallback(this); } } e.StopImmediatePropagation(); } } public enum ObjectType { File, TempFile, Folder, TempFolder, } public enum ObjectState { Normal, Selected, Editing, } public class ObjectData { public ObjectType type; public string path; public ObjectState state; public ObjectData() {} public ObjectData(ObjectType type, string path, ObjectState state = ObjectState.Normal) { this.type = type; this.path = path; this.state = state; } } }
0
0.812065
1
0.812065
game-dev
MEDIA
0.659558
game-dev,desktop-app
0.959224
1
0.959224
LengSicong/Tell2Design
2,088
T5/transformers_src/models/splinter/__init__.py
# flake8: noqa # There's no way to ignore "F401 '...' imported but unused" warnings in this # module, but to preserve other warnings. So, don't check this module at all. # Copyright 2021 The HuggingFace Team. All rights reserved. # # 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. from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available _import_structure = { "configuration_splinter": ["SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP", "SplinterConfig"], "tokenization_splinter": ["SplinterTokenizer"], } if is_tokenizers_available(): _import_structure["tokenization_splinter_fast"] = ["SplinterTokenizerFast"] if is_torch_available(): _import_structure["modeling_splinter"] = [ "SPLINTER_PRETRAINED_MODEL_ARCHIVE_LIST", "SplinterForQuestionAnswering", "SplinterLayer", "SplinterModel", "SplinterPreTrainedModel", ] if TYPE_CHECKING: from .configuration_splinter import SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP, SplinterConfig from .tokenization_splinter import SplinterTokenizer if is_tokenizers_available(): from .tokenization_splinter_fast import SplinterTokenizerFast if is_torch_available(): from .modeling_splinter import ( SPLINTER_PRETRAINED_MODEL_ARCHIVE_LIST, SplinterForQuestionAnswering, SplinterLayer, SplinterModel, SplinterPreTrainedModel, ) else: import sys sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)
0
0.543019
1
0.543019
game-dev
MEDIA
0.249961
game-dev
0.543463
1
0.543463
tttsaurus/Ingame-Info-Reborn
3,556
src/main/java/com/tttsaurus/ingameinfo/common/impl/igievent/modcompat/SereneSeasonsEvent.java
package com.tttsaurus.ingameinfo.common.impl.igievent.modcompat; import com.tttsaurus.ingameinfo.common.core.function.IAction_1Param; import com.tttsaurus.ingameinfo.common.core.igievent.EventBase; import crafttweaker.annotations.ZenRegister; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; public final class SereneSeasonsEvent extends EventBase<IAction_1Param<SereneSeasonsEvent.SereneSeasonsData>> { @Override public void addListener(IAction_1Param<SereneSeasonsData> listener) { addListenerInternal(listener); } @ZenRegister @ZenClass("mods.ingameinfo.compat.sereneseasons.SereneSeasonsData") public static class SereneSeasonsData { private final int dayDuration; private final int subSeasonDuration; private final int seasonDuration; private final int cycleDuration; private final int seasonCycleTicks; private final int day; private final String seasonName; private final String subSeasonName; private final String tropicalSeasonName; private final int seasonOrdinal; private final int subSeasonOrdinal; private final int tropicalSeasonOrdinal; private final int dayOfSeason; public SereneSeasonsData( int dayDuration, int subSeasonDuration, int seasonDuration, int cycleDuration, int seasonCycleTicks, int day, String seasonName, String subSeasonName, String tropicalSeasonName, int seasonOrdinal, int subSeasonOrdinal, int tropicalSeasonOrdinal, int dayOfSeason) { this.dayDuration = dayDuration; this.subSeasonDuration = subSeasonDuration; this.seasonDuration = seasonDuration; this.cycleDuration = cycleDuration; this.seasonCycleTicks = seasonCycleTicks; this.day = day; this.seasonName = seasonName; this.subSeasonName = subSeasonName; this.tropicalSeasonName = tropicalSeasonName; this.seasonOrdinal = seasonOrdinal; this.subSeasonOrdinal = subSeasonOrdinal; this.tropicalSeasonOrdinal = tropicalSeasonOrdinal; this.dayOfSeason = dayOfSeason; } @ZenMethod public int getDayDuration() { return dayDuration; } @ZenMethod public int getSubSeasonDuration() { return subSeasonDuration; } @ZenMethod public int getSeasonDuration() { return seasonDuration; } @ZenMethod public int getCycleDuration() { return cycleDuration; } @ZenMethod public int getSeasonCycleTicks() { return seasonCycleTicks; } @ZenMethod public int getDay() { return day; } @ZenMethod public String getSeasonName() { return seasonName; } @ZenMethod public String getSubSeasonName() { return subSeasonName; } @ZenMethod public String getTropicalSeasonName() { return tropicalSeasonName; } @ZenMethod public int getSeasonOrdinal() { return seasonOrdinal; } @ZenMethod public int getSubSeasonOrdinal() { return subSeasonOrdinal;} @ZenMethod public int getTropicalSeasonOrdinal() { return tropicalSeasonOrdinal; } @ZenMethod public int getDayOfSeason() { return dayOfSeason; } } }
0
0.576914
1
0.576914
game-dev
MEDIA
0.734828
game-dev
0.613241
1
0.613241
AlmasB/FXGL
3,241
fxgl-samples/src/main/java/intermediate/ai/pathfinding/AStarPathfindingSample.java
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB (almaslvl@gmail.com). * See LICENSE for details. */ package intermediate.ai.pathfinding; import com.almasb.fxgl.app.GameApplication; import com.almasb.fxgl.app.GameSettings; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.pathfinding.CellMoveComponent; import com.almasb.fxgl.pathfinding.CellState; import com.almasb.fxgl.pathfinding.astar.AStarGrid; import com.almasb.fxgl.pathfinding.astar.AStarMoveComponent; import javafx.scene.input.MouseButton; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.shape.StrokeType; import static com.almasb.fxgl.dsl.FXGL.debug; import static com.almasb.fxgl.dsl.FXGL.entityBuilder; /** * Demo that uses A* search to find a path between 2 cells in a grid. * Right click to place a wall, left click to move. * * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com) */ public class AStarPathfindingSample extends GameApplication { private Entity agent; @Override protected void initSettings(GameSettings settings) { settings.setWidth(1280); settings.setHeight(720); settings.setDeveloperMenuEnabled(true); } @Override protected void initGame() { var grid = new AStarGrid(1280 / 40, 720 / 40); agent = entityBuilder() .viewWithBBox(new Rectangle(40, 40, Color.BLUE)) .with(new CellMoveComponent(40, 40, 150)) .with(new AStarMoveComponent(grid)) .zIndex(1) .anchorFromCenter() .buildAndAttach(); agent.getComponent(CellMoveComponent.class).atDestinationProperty().addListener((o, old, isAtDestination) -> { if (isAtDestination) { debug("CellMoveComponent: reached destination"); } }); agent.getComponent(AStarMoveComponent.class).atDestinationProperty().addListener((o, old, isAtDestination) -> { if (isAtDestination) { debug("AStarMoveComponent: reached destination"); } }); for (int y = 0; y < 720 / 40; y++) { for (int x = 0; x < 1280 / 40; x++) { final var finalX = x; final var finalY = y; var view = new Rectangle(40, 40, Color.WHITE); view.setStroke(Color.color(0, 0, 0, 0.25)); view.setStrokeType(StrokeType.INSIDE); var e = entityBuilder() .at(x * 40, y * 40) .view(view) .buildAndAttach(); e.getViewComponent().addOnClickHandler(event -> { if (event.getButton() == MouseButton.PRIMARY) { agent.getComponent(AStarMoveComponent.class).moveToCell(finalX, finalY); } else if (event.getButton() == MouseButton.SECONDARY) { grid.get(finalX, finalY).setState(CellState.NOT_WALKABLE); view.setFill(Color.RED); } }); } } } public static void main(String[] args) { launch(args); } }
0
0.724221
1
0.724221
game-dev
MEDIA
0.576304
game-dev,desktop-app
0.98638
1
0.98638
beyond-aion/aion-server
1,376
game-server/src/com/aionemu/gameserver/network/aion/clientpackets/CM_VIEW_PLAYER_DETAILS.java
package com.aionemu.gameserver.network.aion.clientpackets; import java.util.Set; import com.aionemu.gameserver.configs.administration.AdminConfig; import com.aionemu.gameserver.model.gameobjects.player.DeniedStatus; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.AionClientPacket; import com.aionemu.gameserver.network.aion.AionConnection.State; import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE; import com.aionemu.gameserver.network.aion.serverpackets.SM_VIEW_PLAYER_DETAILS; /** * @author Avol */ public class CM_VIEW_PLAYER_DETAILS extends AionClientPacket { private int targetObjectId; public CM_VIEW_PLAYER_DETAILS(int opcode, Set<State> validStates) { super(opcode, validStates); } @Override protected void readImpl() { targetObjectId = readD(); } @Override protected void runImpl() { Player player = getConnection().getActivePlayer(); Player target = player.getKnownList().getPlayer(targetObjectId); if (target == null) return; if (!target.getPlayerSettings().isInDeniedStatus(DeniedStatus.VIEW_DETAILS) || player.hasAccess(AdminConfig.VIEW_PLAYER_DETAILS)) sendPacket(new SM_VIEW_PLAYER_DETAILS(target.getEquipment().getEquippedItemsWithoutStigma(), target)); else sendPacket(SM_SYSTEM_MESSAGE.STR_MSG_REJECTED_WATCH(target.getName())); } }
0
0.923258
1
0.923258
game-dev
MEDIA
0.675522
game-dev
0.789064
1
0.789064
ReikaKalseki/ChromatiCraft
7,406
TileEntity/Storage/TileEntityToolStorage.java
package Reika.ChromatiCraft.TileEntity.Storage; import net.minecraft.client.Minecraft; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemAxe; import net.minecraft.item.ItemBow; import net.minecraft.item.ItemEnchantedBook; import net.minecraft.item.ItemPickaxe; import net.minecraft.item.ItemPotion; import net.minecraft.item.ItemShears; import net.minecraft.item.ItemSpade; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.Potion; import Reika.ChromatiCraft.Base.TileEntity.TileEntityMassStorage; import Reika.ChromatiCraft.Registry.ChromaTiles; import Reika.DragonAPI.ModList; import Reika.DragonAPI.Instantiable.InertItem; import Reika.DragonAPI.Instantiable.Data.KeyedItemStack; import Reika.DragonAPI.Libraries.ReikaPotionHelper; import Reika.DragonAPI.Libraries.Java.ReikaStringParser; import Reika.DragonAPI.ModInteract.Bees.ReikaBeeHelper; import Reika.DragonAPI.ModInteract.ItemHandlers.AppEngHandler; import Reika.DragonAPI.ModInteract.ItemHandlers.TinkerToolHandler; import Reika.DragonAPI.ModRegistry.InterfaceCache; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class TileEntityToolStorage extends TileEntityMassStorage { private static final int MAX_COUNT = 360000; private ToolType filter = ToolType.OTHER; public boolean stepMode() { if (this.getPendingInput() == null && this.getItems().isEmpty()) { filter = filter.next(); while (!filter.isValid()) filter = filter.next(); this.resetWorkTimer(); return true; } return false; } @Override public InertItem getFilterItemRender() { return filter.getRenderItem(); } @Override public ChromaTiles getTile() { return ChromaTiles.TOOLSTORAGE; } @Override protected KeyedItemStack key(ItemStack is) { return new KeyedItemStack(is).setIgnoreMetadata(!filter.isDamageImportant()).setIgnoreNBT(!filter.isNBTImportant()).setSized(false).setSimpleHash(true); } @Override public boolean isItemValid(ItemStack is) { return filter.isItemValid(is); } @Override public int maxItemCount() { return MAX_COUNT; } @Override public void writeToNBT(NBTTagCompound NBT) { super.writeToNBT(NBT); NBT.setInteger("mode", filter.ordinal()); } @Override public void readFromNBT(NBTTagCompound NBT) { super.readFromNBT(NBT); filter = ToolType.list[NBT.getInteger("mode")]; } @Override protected void writeSyncTag(NBTTagCompound NBT) { super.writeSyncTag(NBT); } @Override protected void readSyncTag(NBTTagCompound NBT) { super.readSyncTag(NBT); } public static enum ToolType { PICK(Items.diamond_pickaxe), AXE(Items.iron_axe), SHOVEL(Items.golden_shovel), SWORD(Items.diamond_sword), BOW(Items.bow), SHEARS(Items.shears), HELMET(Items.diamond_helmet), CHESTPLATE(Items.diamond_chestplate), LEGS(Items.diamond_leggings), BOOTS(Items.diamond_boots), BOOK(Items.enchanted_book), HORSEARMOR(Items.golden_horse_armor), POTION(ReikaPotionHelper.getPotionItem(Potion.regeneration, false, false, false)), TINKER(ModList.TINKERER.isLoaded() ? TinkerToolHandler.Tools.HAMMER.getToolOfMaterials(1, 1, 1, 1) : (ItemStack)null), OTHER((ItemStack)null); private static final ToolType[] list = values(); private final ItemStack icon; private InertItem render; @SideOnly(Side.CLIENT) public InertItem getRenderItem() { if (render == null && icon != null) { render = new InertItem(Minecraft.getMinecraft().theWorld, icon); } return render; } public ToolType next() { return list[(this.ordinal()+1)%list.length]; } public boolean isDamageImportant() { switch(this) { case POTION: case OTHER: return true; default: return false; } } public boolean isValid() { switch(this) { case TINKER: return ModList.TINKERER.isLoaded(); default: return true; } } public boolean isNBTImportant() { switch(this) { case TINKER: case BOOK: case OTHER: return true; default: return false; } } private ToolType(Item i) { this(new ItemStack(i)); } private ToolType(ItemStack is) { icon = is; } public boolean isItemValid(ItemStack is) { return this.getTypeForTool(is) == this; /* if (this.isTinker(is)) return this == TINKER; int type = -1; if (is.getItem() instanceof ItemArmor) { type = ((ItemArmor)is.getIt em()).armorType; } switch(this) { case AXE: return is.getItem() instanceof ItemAxe; case BOW: return is.getItem() instanceof ItemBow; case PICK: return is.getItem() instanceof ItemPickaxe; case SHEARS: return is.getItem() instanceof ItemShears; case SHOVEL: return is.getItem() instanceof ItemSpade; case SWORD: return is.getItem() instanceof ItemSword; case HELMET: return type == 0; case CHESTPLATE: return type == 1; case LEGS: return type == 2; case BOOTS: return type == 3; case TINKER: return this.isTinker(is); default: break; } return this == OTHER;*/ } private static ToolType getTypeForTool(ItemStack is) { if (isTinker(is)) return TINKER; if (is.getItem() instanceof ItemArmor) { int type = ((ItemArmor)is.getItem()).armorType; switch(type) { case 0: return HELMET; case 1: return CHESTPLATE; case 2: return LEGS; case 3: return BOOTS; } } if (is.getItem() instanceof ItemAxe) return AXE; if (is.getItem() instanceof ItemBow) return BOW; if (is.getItem() instanceof ItemPickaxe) return PICK; if (is.getItem() instanceof ItemShears) return SHEARS; if (is.getItem() instanceof ItemSpade) return SHOVEL; if (is.getItem() instanceof ItemSword) return SWORD; if (is.getItem() instanceof ItemEnchantedBook) return BOOK; if (is.getItem() == Items.iron_horse_armor || is.getItem() == Items.golden_horse_armor || is.getItem() == Items.diamond_horse_armor) return HORSEARMOR; if (is.getItem() instanceof ItemPotion) return POTION; if (ModList.BOTANIA.isLoaded() && InterfaceCache.BREWITEM.instanceOf(is.getItem())) return POTION; return isValidMiscToolItem(is) ? OTHER : null; } private static boolean isValidMiscToolItem(ItemStack is) { if (ModList.APPENG.isLoaded()) { Item i = is.getItem(); if (i == AppEngHandler.getInstance().get1KCell() || i == AppEngHandler.getInstance().get4KCell()) return false; if (i == AppEngHandler.getInstance().get16KCell() || i == AppEngHandler.getInstance().get64KCell()) return false; } if (ModList.FORESTRY.isLoaded() && ReikaBeeHelper.isGenedItem(is)) return false; return is.getMaxStackSize() == 1; } private static boolean isTinker(ItemStack is) { return ModList.TINKERER.isLoaded() && (TinkerToolHandler.getInstance().isTool(is) || TinkerToolHandler.getInstance().isWeapon(is)); } public static String getTypesAsString() { StringBuilder sb = new StringBuilder(); for (ToolType type : list) { sb.append(type.displayName()); if (type != ToolType.OTHER) sb.append(", "); } return sb.toString(); } public String displayName() { return ReikaStringParser.capFirstChar(this.name()); } } }
0
0.887926
1
0.887926
game-dev
MEDIA
0.997017
game-dev
0.980935
1
0.980935
mangosfour/server
5,039
src/modules/SD3/scripts/eastern_kingdoms/blackrock_mountain/molten_core/boss_gehennas.cpp
/** * ScriptDev3 is an extension for mangos providing enhanced features for * area triggers, creatures, game objects, instances, items, and spells beyond * the default database scripting in mangos. * * Copyright (C) 2006-2013 ScriptDev2 <http://www.scriptdev2.com/> * Copyright (C) 2014-2023 MaNGOS <https://getmangos.eu> * * 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 * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ /** * ScriptData * SDName: Boss_Gehennas * SD%Complete: 90 * SDComment: None * SDCategory: Molten Core * EndScriptData */ #include "precompiled.h" #include "molten_core.h" enum { SPELL_SHADOW_BOLT = 19728, // 19729 exists too, but can be reflected SPELL_RAIN_OF_FIRE = 19717, SPELL_GEHENNAS_CURSE = 19716 }; struct boss_gehennas : public CreatureScript { boss_gehennas() : CreatureScript("boss_gehennas") {} struct boss_gehennasAI : public ScriptedAI { boss_gehennasAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); } ScriptedInstance* m_pInstance; uint32 m_uiShadowBoltTimer; uint32 m_uiRainOfFireTimer; uint32 m_uiGehennasCurseTimer; void Reset() override { m_uiShadowBoltTimer = 6000; m_uiRainOfFireTimer = 10000; m_uiGehennasCurseTimer = 12000; } void Aggro(Unit* /*pwho*/) override { if (m_pInstance) { m_pInstance->SetData(TYPE_GEHENNAS, IN_PROGRESS); } } void JustDied(Unit* /*pKiller*/) override { if (m_pInstance) { m_pInstance->SetData(TYPE_GEHENNAS, DONE); } } void JustReachedHome() override { if (m_pInstance) { m_pInstance->SetData(TYPE_GEHENNAS, FAIL); } } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) { return; } // ShadowBolt Timer if (m_uiShadowBoltTimer < uiDiff) { if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1)) { if (DoCastSpellIfCan(pTarget, SPELL_SHADOW_BOLT) == CAST_OK) { m_uiShadowBoltTimer = 7000; } } else // In case someone attempts soloing, we don't need to scan for targets every tick { m_uiShadowBoltTimer = 7000; } } else { m_uiShadowBoltTimer -= uiDiff; } // Rain of Fire Timer if (m_uiRainOfFireTimer < uiDiff) { if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) { if (DoCastSpellIfCan(pTarget, SPELL_RAIN_OF_FIRE) == CAST_OK) { m_uiRainOfFireTimer = urand(4000, 12000); } } } else { m_uiRainOfFireTimer -= uiDiff; } // GehennasCurse Timer if (m_uiGehennasCurseTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_GEHENNAS_CURSE) == CAST_OK) { m_uiGehennasCurseTimer = 30000; } } else { m_uiGehennasCurseTimer -= uiDiff; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* pCreature) override { return new boss_gehennasAI(pCreature); } }; void AddSC_boss_gehennas() { Script* s; s = new boss_gehennas(); s->RegisterSelf(); //pNewScript = new Script; //pNewScript->Name = "boss_gehennas"; //pNewScript->GetAI = &GetAI_boss_gehennas; //pNewScript->RegisterSelf(); }
0
0.943505
1
0.943505
game-dev
MEDIA
0.988858
game-dev
0.980165
1
0.980165
ProjectIgnis/CardScripts
2,429
official/c10449150.lua
--シャトルロイド --Shuttleroid local s,id=GetID() function s.initial_effect(c) --remove local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_REMOVE) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_BE_BATTLE_TARGET) e1:SetTarget(s.rmtg) e1:SetOperation(s.rmop) c:RegisterEffect(e1) --spsummon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_PHASE|PHASE_STANDBY) e2:SetRange(LOCATION_REMOVED) e2:SetCondition(s.spcon) e2:SetTarget(s.sptg) e2:SetOperation(s.spop) c:RegisterEffect(e2) --damage local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(id,2)) e3:SetCategory(CATEGORY_DAMAGE) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e3:SetCode(EVENT_SPSUMMON_SUCCESS) e3:SetCondition(s.damcon) e3:SetTarget(s.damtg) e3:SetOperation(s.damop) c:RegisterEffect(e3) end function s.rmtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemove() end Duel.SetOperationInfo(0,CATEGORY_REMOVE,e:GetHandler(),1,0,0) end function s.rmop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and Duel.Remove(c,POS_FACEUP,REASON_EFFECT)~=0 then c:RegisterFlagEffect(id,RESET_EVENT|RESETS_STANDARD|RESET_PHASE|PHASE_STANDBY|RESET_SELF_TURN,0,1) end end function s.spcon(e,tp,eg,ep,ev,re,r,rp) return Duel.IsTurnPlayer(tp) end function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetFlagEffect(id)~=0 end e:GetHandler():ResetFlagEffect(id) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,1000) end function s.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end Duel.SpecialSummon(c,1,tp,tp,false,false,POS_FACEUP) end function s.damcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetSummonType()==SUMMON_TYPE_SPECIAL+1 end function s.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(1000) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,1000) end function s.damop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end
0
0.813507
1
0.813507
game-dev
MEDIA
0.985605
game-dev
0.867074
1
0.867074
JavidPack/TerraCustom
1,540
patches/tModLoader/Terraria/Item_tML.cs
using Microsoft.Xna.Framework; using System; using Terraria.ID; using Terraria.ModLoader.IO; namespace Terraria { public partial class Item : TagSerializable { public static readonly Func<TagCompound, Item> DESERIALIZER = ItemIO.Load; public TagCompound SerializeData() => ItemIO.Save(this); internal static void PopulateMaterialCache() { for (int i = 0; i < Recipe.numRecipes; i++) { int num = 0; while (Main.recipe[i].requiredItem[num].type > 0) { ItemID.Sets.IsAMaterial[Main.recipe[i].requiredItem[num].type] = true; num++; } } foreach (RecipeGroup recipeGroup in RecipeGroup.recipeGroups.Values) { foreach (var item in recipeGroup.ValidItems) { ItemID.Sets.IsAMaterial[item] = true; } } ItemID.Sets.IsAMaterial[71] = false; ItemID.Sets.IsAMaterial[72] = false; ItemID.Sets.IsAMaterial[73] = false; ItemID.Sets.IsAMaterial[74] = false; } public static int NewItem(Rectangle rectangle, int Type, int Stack = 1, bool noBroadcast = false, int prefixGiven = 0, bool noGrabDelay = false, bool reverseLookup = false) => Item.NewItem(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, Type, Stack, noBroadcast, prefixGiven, noGrabDelay, reverseLookup); public static int NewItem(Vector2 position, int Type, int Stack = 1, bool noBroadcast = false, int prefixGiven = 0, bool noGrabDelay = false, bool reverseLookup = false) => NewItem((int)position.X, (int)position.Y, 0, 0, Type, Stack, noBroadcast, prefixGiven, noGrabDelay, reverseLookup); } }
0
0.683343
1
0.683343
game-dev
MEDIA
0.958384
game-dev
0.923638
1
0.923638
austinmao/reduxity
4,550
Assets/Plugins/UniRx/Scripts/UnityEngineBridge/Operators/FromCoroutine.cs
using System; using System.Collections; using System.Threading; namespace UniRx.Operators { internal class FromCoroutineObservable<T> : OperatorObservableBase<T> { readonly Func<IObserver<T>, CancellationToken, IEnumerator> coroutine; public FromCoroutineObservable(Func<IObserver<T>, CancellationToken, IEnumerator> coroutine) : base(false) { this.coroutine = coroutine; } protected override IDisposable SubscribeCore(IObserver<T> observer, IDisposable cancel) { var fromCoroutineObserver = new FromCoroutine(observer, cancel); #if (ENABLE_MONO_BLEEDING_EDGE_EDITOR || ENABLE_MONO_BLEEDING_EDGE_STANDALONE) var moreCancel = new CancellationDisposable(); var token = moreCancel.Token; #else var moreCancel = new BooleanDisposable(); var token = new CancellationToken(moreCancel); #endif MainThreadDispatcher.SendStartCoroutine(coroutine(fromCoroutineObserver, token)); return moreCancel; } class FromCoroutine : OperatorObserverBase<T, T> { public FromCoroutine(IObserver<T> observer, IDisposable cancel) : base(observer, cancel) { } public override void OnNext(T value) { try { base.observer.OnNext(value); } catch { Dispose(); throw; } } public override void OnError(Exception error) { try { observer.OnError(error); } finally { Dispose(); } } public override void OnCompleted() { try { observer.OnCompleted(); } finally { Dispose(); } } } } internal class FromMicroCoroutineObservable<T> : OperatorObservableBase<T> { readonly Func<IObserver<T>, CancellationToken, IEnumerator> coroutine; readonly FrameCountType frameCountType; public FromMicroCoroutineObservable(Func<IObserver<T>, CancellationToken, IEnumerator> coroutine, FrameCountType frameCountType) : base(false) { this.coroutine = coroutine; this.frameCountType = frameCountType; } protected override IDisposable SubscribeCore(IObserver<T> observer, IDisposable cancel) { var microCoroutineObserver = new FromMicroCoroutine(observer, cancel); #if (ENABLE_MONO_BLEEDING_EDGE_EDITOR || ENABLE_MONO_BLEEDING_EDGE_STANDALONE) var moreCancel = new CancellationDisposable(); var token = moreCancel.Token; #else var moreCancel = new BooleanDisposable(); var token = new CancellationToken(moreCancel); #endif switch (frameCountType) { case FrameCountType.Update: MainThreadDispatcher.StartUpdateMicroCoroutine(coroutine(microCoroutineObserver, token)); break; case FrameCountType.FixedUpdate: MainThreadDispatcher.StartFixedUpdateMicroCoroutine(coroutine(microCoroutineObserver, token)); break; case FrameCountType.EndOfFrame: MainThreadDispatcher.StartEndOfFrameMicroCoroutine(coroutine(microCoroutineObserver, token)); break; default: throw new ArgumentException("Invalid FrameCountType:" + frameCountType); } return moreCancel; } class FromMicroCoroutine : OperatorObserverBase<T, T> { public FromMicroCoroutine(IObserver<T> observer, IDisposable cancel) : base(observer, cancel) { } public override void OnNext(T value) { try { base.observer.OnNext(value); } catch { Dispose(); throw; } } public override void OnError(Exception error) { try { observer.OnError(error); } finally { Dispose(); } } public override void OnCompleted() { try { observer.OnCompleted(); } finally { Dispose(); } } } } }
0
0.913263
1
0.913263
game-dev
MEDIA
0.206425
game-dev
0.973789
1
0.973789
SirNeirda/godot_procedural_infinite_world
6,868
_script/CharacterMob.cs
using Godot; using System; using Bouncerock; using Bouncerock.Terrain; using Bouncerock.UI; public partial class CharacterMob : CharacterBody3D { [Export] public string CharacterName = "Mob"; [ExportGroup("Player Objects")] public WorldSpaceUI PopupInfo; [Export] public Node3D CameraPivot; [Export] public AnimationTree Animator; [ExportGroup("Player Attributes")] Vector3 Direction = Vector3.Zero; float mouse_speed = 0.05f; [Export] public float WalkingSpeed = 6; [Export] public float WalkToRunSpeedIncrease = 1; [Export] public float RunningSpeed = 20; [Export] public float PunchedVelocity = 10; /*[Export] float MaxSpeed = 4;*/ float speed = 1; public float SpeedMultiplier = 1; float velocity = 0; public enum MobStates {Aggressive, Punched, Passive} public MobStates CurrentState = MobStates.Passive; // Get the gravity from the project settings to be synced with RigidBody nodes. public float gravity = ProjectSettings.GetSetting("physics/3d/default_gravity").AsSingle(); public override void _Ready() { Initialization(); } protected virtual void Initialization() { //Input.MouseMode = Input.MouseModeEnum.Captured; FloorMaxAngle = Mathf.DegToRad(50); } public override void _PhysicsProcess(double delta) { float deltaFloat = (float)delta; UpdateMovement(deltaFloat); } public override void _Process(double delta) { float deltaFloat = (float)delta; //GD.Print(RaycastDown.IsColliding()); //UpdateCamera(deltaFloat); UpdateHelpers(deltaFloat); //UpdateInput(deltaFloat); UpdateAnimations(); } /*public override void _Input(InputEvent keyEvent) { if (keyEvent is InputEventMouseButton _mouseButton) { switch (_mouseButton.ButtonIndex) { case MouseButton.Right: Input.MouseMode = _mouseButton.Pressed? Input.MouseModeEnum.Captured:Input.MouseModeEnum.Visible; break; } if (_mouseButton.ButtonIndex == MouseButton.Left && _mouseButton.Pressed) { RigidBody3D newCube = Cube.Instantiate() as RigidBody3D; GetTree().Root.AddChild(newCube); Vector3 forwardDirection = GlobalTransform.Basis.Z; newCube.Position = GlobalTransform.Origin + (forwardDirection*2)+Vector3.Up; Vector3 velocityDirection = (forwardDirection*2 + Vector3.Up).Normalized(); newCube.LinearVelocity = velocityDirection * 5; //newCube.Position = this.Position + Vector3.Back +Vector3.Up; // newCube.Rotation = this.Rotation; //newCube.LinearVelocity = (Vector3.Back+Vector3.Up)*10; } } if (keyEvent is InputEventMouseMotion motion) { cam_rot_x = Mathf.Clamp((cam_rot_x +(-motion.Relative.Y * mouse_speed)), -25,60); cam_rot_y += -motion.Relative.X * mouse_speed; } if (Input.IsActionPressed("action")) { float height = TerrainManager.Instance.GetTerrainHeightAtGlobalCoordinate(new Vector2(GlobalPosition.X, GlobalPosition.Z)); float degree = TerrainManager.Instance.GetTerrainInclinationAtGlobalCoordinate(new Vector2(GlobalPosition.X, GlobalPosition.Z)); Vector3 location = new Vector3(GlobalPosition.X, height, GlobalPosition.Z); GD.Print("Degree inclination: " + degree); } }*/ protected void UpdateAnimations() { Animator.Set("parameters/conditions/falling", false); Animator.Set("parameters/conditions/idle", false); Animator.Set("parameters/conditions/sprinting", false); Animator.Set("parameters/conditions/running", true); Animator.Set("parameters/conditions/tossing", false); return; if (!IsOnFloor()) { Animator.Set("parameters/conditions/falling", true); return; } if (Direction.Z == 0 && IsOnFloor()) { Animator.Set("parameters/conditions/idle", true); return; } if (Direction.Z != 0) { if (Input.IsActionPressed("run")) { Animator.Set("parameters/conditions/sprinting", true); return; } Animator.Set("parameters/conditions/running", true); return; } } protected void ChangeAnimState() { } protected void ChangeCharacterState(MobStates newState) { if (newState != CurrentState) { CurrentState = newState; } } public void DeathPunched() { ChangeCharacterState(MobStates.Punched); } public Vector3 GetDirection() { return GameManager.Instance.GetMainCharacterPosition(); } protected void UpdateMovement(float deltaFloat) { Vector3 velocity = Velocity; if (CurrentState == MobStates.Punched && IsOnFloor()) { velocity.Y = PunchedVelocity; } Vector3 goal = GetDirection(); // Assume this is your goal position. LookAt(goal); Rotate(Vector3.Up, Mathf.Pi); speed = WalkingSpeed*SpeedMultiplier; Vector3 forwardDirection = GlobalTransform.Basis.Z; // Handle movement and gravity when the character is on the floor. if (IsOnFloor()) { velocity.X = 1; velocity.Y = 1; velocity.X = forwardDirection.X*speed; velocity.Y = forwardDirection.Y; velocity.Z = forwardDirection.Z*speed; } else { // Apply gravity when not on the floor. velocity.Y -= gravity * deltaFloat; } // Assign the updated velocity Velocity = velocity; // Perform movement with collision response MoveAndSlide(); } protected void UpdateCamera(float deltaFloat) { } public void UpdateHelpers(float deltaFloat) { string text = CharacterName; string dist = GetDirection().DistanceTo(Position).ToString("0.00"); if (PopupInfo == null) { PopupInfo = Debug.SetTextHelper(text, CameraPivot.Position, CameraPivot); PopupInfo.MaxViewDistance = 30; } if (PopupInfo != null) { //text = text+ "\n" + Mathf.RadToDeg(GetFloorAngle()) + " Pos: X: " + string.Format("{0:0. #}", Position.X) + " Y: " + string.Format("{0:0. #}", Position.Y) + " Z: " + string.Format("{0:0. #}", Position.Z) ; //GD.Print(TerrainGenerator.Instance.CameraInChunk()); PopupInfo.SetText(text); PopupInfo.Position = CameraPivot.Position+ Vector3.Down*0.7f; //GD.Print("Position " + PopupInfo.Position); } if (GetDirection().DistanceTo(Position) < 1.5f) { GameManager.Instance.OnLoseGame(); } /*string text = "Adrien" + "\n" + TerrainManager.Instance.CameraInChunk(); if (PopupInfo == null) { PopupInfo = Debug.SetTextHelper(text, CameraPivot.Position, CameraPivot); PopupInfo.MaxViewDistance = 1000; } if (PopupInfo != null) { text = "AdrienSetup" + "\n" + Mathf.RadToDeg(GetFloorAngle()) + " Pos: \nX: " + string.Format("{0:0. #}", Position.X) + "\nY: " + string.Format("{0:0. #}", Position.Y) + "\nZ: " + string.Format("{0:0. #}", Position.Z) ; //GD.Print(TerrainGenerator.Instance.CameraInChunk()); PopupInfo.SetText(text); //PopupInfo.Position = CameraPivot.Position+ Vector3.Up *0.2f; }*/ } public override void _Input(InputEvent keyEvent) { } }
0
0.80024
1
0.80024
game-dev
MEDIA
0.898248
game-dev
0.989996
1
0.989996
SourceEngine-CommunityEdition/source
15,825
engine/cl_entityreport.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "client_pch.h" #include "ivideomode.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" ConVar cl_entityreport( "cl_entityreport", "0", FCVAR_CHEAT, "For debugging, draw entity states to console" ); ConVar cl_entityreport_sorted( "cl_entityreport_sorted", "0", FCVAR_CHEAT, "For debugging, draw entity states to console in sorted order. [0 = disabled, 1 = average, 2 = current, 3 = peak" ); enum { ENTITYSORT_NONE = 0, ENTITYSORT_AVG = 1, ENTITYSORT_CURRENT = 2, ENTITYSORT_PEAK = 3, }; // How quickly to move rolling average for entityreport #define BITCOUNT_AVERAGE 0.95f // How long to flush item when something important happens #define EFFECT_TIME 1.5f // How long to latch peak bit count for item #define PEAK_LATCH_TIME 2.0f; //----------------------------------------------------------------------------- // Purpose: Entity report event types //----------------------------------------------------------------------------- enum { FENTITYBITS_ZERO = 0, FENTITYBITS_ADD = 0x01, FENTITYBITS_LEAVEPVS = 0x02, FENTITYBITS_DELETE = 0x04, }; //----------------------------------------------------------------------------- // Purpose: Data about an entity //----------------------------------------------------------------------------- typedef struct { // Bits used for last message int bits; // Rolling average of bits used float average; // Last bit peak int peak; // Time at which peak was last reset float peaktime; // Event info int flags; // If doing effect, when it will finish float effectfinishtime; // If event was deletion, remember client class for a little bit ClientClass *deletedclientclass; } ENTITYBITS; // List of entities we are keeping data bout static ENTITYBITS s_EntityBits[ MAX_EDICTS ]; // Used to sort by average int CompareEntityBits(const void* pIndexA, const void* pIndexB ) { int indexA = *(int*)pIndexA; int indexB = *(int*)pIndexB; ENTITYBITS *pEntryA = &s_EntityBits[indexA]; ENTITYBITS *pEntryB = &s_EntityBits[indexB]; /* if ( pEntryA->flags == FENTITYBITS_ZERO ) { if ( pEntryB->flags == FENTITYBITS_ZERO ) { return 0; } return 1; } else if ( pEntryB->flags == FENTITYBITS_ZERO ) { return -1; } */ // sort dormant, out-of-pvs to the end IClientNetworkable *pNetA = entitylist->GetClientNetworkable( indexA ); IClientNetworkable *pNetB = entitylist->GetClientNetworkable( indexB ); bool bDormantA = pNetA == NULL || pNetA->IsDormant(); bool bDormantB = pNetB == NULL || pNetB->IsDormant(); if ( bDormantA != bDormantB ) { return bDormantA ? 1 : -1; } switch ( cl_entityreport_sorted.GetInt() ) { case ENTITYSORT_AVG: if ( pEntryA->average > pEntryB->average ) { return -1; } if ( pEntryA->average < pEntryB->average ) { return 1; } break; case ENTITYSORT_CURRENT: if ( pEntryA->bits > pEntryB->bits ) { return -1; } if ( pEntryA->bits < pEntryB->bits ) { return 1; } break; case ENTITYSORT_PEAK: default: if ( pEntryA->peak > pEntryB->peak ) { return -1; } if ( pEntryA->peak < pEntryB->peak ) { return 1; } } return 0; } //----------------------------------------------------------------------------- // Purpose: Zero out structure ( level transition/startup ) //----------------------------------------------------------------------------- void CL_ResetEntityBits( void ) { memset( s_EntityBits, 0, sizeof( s_EntityBits ) ); } //----------------------------------------------------------------------------- // Purpose: Record activity // Input : entnum - // bitcount - //----------------------------------------------------------------------------- void CL_RecordEntityBits( int entnum, int bitcount ) { if ( entnum < 0 || entnum >= MAX_EDICTS ) { return; } ENTITYBITS *slot = &s_EntityBits[ entnum ]; slot->bits = bitcount; // Update average slot->average = ( BITCOUNT_AVERAGE ) * slot->average + ( 1.f - BITCOUNT_AVERAGE ) * bitcount; // Recompute peak if ( realtime >= slot->peaktime ) { slot->peak = 0.0f; slot->peaktime = realtime + PEAK_LATCH_TIME; } // Store off peak if ( bitcount > slot->peak ) { slot->peak = bitcount; } } //----------------------------------------------------------------------------- // Purpose: Record entity add event // Input : entnum - //----------------------------------------------------------------------------- void CL_RecordAddEntity( int entnum ) { if ( !cl_entityreport.GetBool() || entnum < 0 || entnum >= MAX_EDICTS ) { return; } ENTITYBITS *slot = &s_EntityBits[ entnum ]; slot->flags = FENTITYBITS_ADD; slot->effectfinishtime = realtime + EFFECT_TIME; } //----------------------------------------------------------------------------- // Purpose: record entity leave event // Input : entnum - //----------------------------------------------------------------------------- void CL_RecordLeavePVS( int entnum ) { if ( !cl_entityreport.GetBool() || entnum < 0 || entnum >= MAX_EDICTS ) { return; } ENTITYBITS *slot = &s_EntityBits[ entnum ]; slot->flags = FENTITYBITS_LEAVEPVS; slot->effectfinishtime = realtime + EFFECT_TIME; } //----------------------------------------------------------------------------- // Purpose: record entity deletion event // Input : entnum - // *pclass - //----------------------------------------------------------------------------- void CL_RecordDeleteEntity( int entnum, ClientClass *pclass ) { if ( !cl_entityreport.GetBool() || entnum < 0 || entnum >= MAX_EDICTS ) { return; } ENTITYBITS *slot = &s_EntityBits[ entnum ]; slot->flags = FENTITYBITS_DELETE; slot->effectfinishtime = realtime + EFFECT_TIME; slot->deletedclientclass = pclass; } //----------------------------------------------------------------------------- // Purpose: Shows entity status report if cl_entityreport cvar is set //----------------------------------------------------------------------------- class CEntityReportPanel : public CBasePanel { typedef CBasePanel BaseClass; public: // Construction CEntityReportPanel( vgui::Panel *parent ); virtual ~CEntityReportPanel( void ); // Refresh virtual void Paint(); virtual void ApplySchemeSettings( vgui::IScheme *pScheme ); virtual bool ShouldDraw( void ); // Helpers void ApplyEffect( ENTITYBITS *entry, int& r, int& g, int& b ); bool DrawEntry( int row, int col, int rowheight, int colwidth, int entityIdx ); private: // Font to use for drawing vgui::HFont m_hFont; }; static CEntityReportPanel *g_pEntityReportPanel = NULL; //----------------------------------------------------------------------------- // Purpose: Creates the CEntityReportPanel VGUI panel // Input : *parent - //----------------------------------------------------------------------------- void CL_CreateEntityReportPanel( vgui::Panel *parent ) { g_pEntityReportPanel = new CEntityReportPanel( parent ); } //----------------------------------------------------------------------------- // Purpose: Instances the entity report panel // Input : *parent - //----------------------------------------------------------------------------- CEntityReportPanel::CEntityReportPanel( vgui::Panel *parent ) : CBasePanel( parent, "CEntityReportPanel" ) { // Need parent here, before loading up textures, so getSurfaceBase // will work on this panel ( it's null otherwise ) SetSize( videomode->GetModeStereoWidth(), videomode->GetModeStereoHeight() ); SetPos( 0, 0 ); SetVisible( true ); SetCursor( null ); m_hFont = vgui::INVALID_FONT; SetFgColor( Color( 0, 0, 0, 255 ) ); SetPaintBackgroundEnabled( false ); SetPaintBorderEnabled(false); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CEntityReportPanel::~CEntityReportPanel( void ) { } void CEntityReportPanel::ApplySchemeSettings( vgui::IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); // If you change this font, be sure to mark it with // $use_in_fillrate_mode in its .vmt file m_hFont = pScheme->GetFont( "DefaultVerySmall", false ); Assert( m_hFont ); } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CEntityReportPanel::ShouldDraw( void ) { if ( !cl_entityreport.GetInt() ) { return false; } return true; } //----------------------------------------------------------------------------- // Purpose: Helper to flash colors // Input : cycle - // value - // Output : static int //----------------------------------------------------------------------------- static int MungeColorValue( float cycle, int& value ) { int midpoint; int remaining; bool invert = false; if ( value < 128 ) { invert = true; value = 255 - value; } midpoint = value / 2; remaining = value - midpoint; midpoint = midpoint + remaining / 2; value = midpoint + ( remaining / 2 ) * cycle; if ( invert ) { value = 255 - value; } value = max( 0, value ); value = min( 255, value ); return value; } //----------------------------------------------------------------------------- // Purpose: // Input : frac - // r - // g - // b - //----------------------------------------------------------------------------- void CEntityReportPanel::ApplyEffect( ENTITYBITS *entry, int& r, int& g, int& b ) { bool effectactive = ( realtime <= entry->effectfinishtime ) ? true : false; if ( !effectactive ) return; float frequency = 3.0f; float frac = ( EFFECT_TIME - ( entry->effectfinishtime - realtime ) ) / EFFECT_TIME; frac = min( 1.f, frac ); frac = max( 0.f, frac ); frac *= 2.0 * M_PI; frac = sin( frequency * frac ); if ( entry->flags & FENTITYBITS_LEAVEPVS ) { r = MungeColorValue( frac, r ); } else if ( entry->flags & FENTITYBITS_ADD ) { g = MungeColorValue( frac, g ); } else if ( entry->flags & FENTITYBITS_DELETE ) { r = MungeColorValue( frac, r ); g = MungeColorValue( frac, g ); b = MungeColorValue( frac, b ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CEntityReportPanel::DrawEntry( int row, int col, int rowheight, int colwidth, int entityIdx ) { IClientNetworkable *pNet; ClientClass *pClientClass; bool inpvs; int r, g, b, a; bool effectactive; ENTITYBITS *entry; int top = 5; int left = 5; pNet = entitylist->GetClientNetworkable( entityIdx ); entry = &s_EntityBits[ entityIdx ]; effectactive = ( realtime <= entry->effectfinishtime ) ? true : false; if ( pNet && ((pClientClass = pNet->GetClientClass())) != NULL ) { inpvs = !pNet->IsDormant(); if ( inpvs ) { if ( entry->average >= 5 ) { r = 200; g = 200; b = 250; a = 255; } else { r = 200; g = 255; b = 100; a = 255; } } else { r = 255; g = 150; b = 100; a = 255; } ApplyEffect( entry, r, g, b ); char text[256]; wchar_t unicode[ 256 ]; Q_snprintf( text, sizeof(text), "(%i) %s", entityIdx, pClientClass->m_pNetworkName ); g_pVGuiLocalize->ConvertANSIToUnicode( text, unicode, sizeof( unicode ) ); DrawColoredText( m_hFont, left + col * colwidth, top + row * rowheight, r, g, b, a, unicode ); if ( inpvs ) { float fracs[ 3 ]; fracs[ 0 ] = (float)( entry->bits >> 3 ) / 100.0f; fracs[ 1 ] = (float)( entry->peak >> 3 ) / 100.0f; fracs[ 2 ] = (float)( (int)entry->average >> 3 ) / 100.0f; for ( int j = 0; j < 3; j++ ) { fracs[ j ] = max( 0.0f, fracs[ j ] ); fracs[ j ] = min( 1.0f, fracs[ j ] ); } int rcright = left + col * colwidth + colwidth-2; int wide = colwidth / 3; int rcleft = rcright - wide; int rctop = top + row * rowheight; int rcbottom = rctop + rowheight - 1; vgui::surface()->DrawSetColor( 63, 63, 63, 127 ); vgui::surface()->DrawFilledRect( rcleft, rctop, rcright, rcbottom ); // draw a box around it vgui::surface()->DrawSetColor( 200, 200, 200, 127 ); vgui::surface()->DrawOutlinedRect( rcleft, rctop, rcright, rcbottom ); // Draw current as a filled rect vgui::surface()->DrawSetColor( 200, 255, 100, 192 ); vgui::surface()->DrawFilledRect( rcleft, rctop + rowheight / 2, rcleft + wide * fracs[ 0 ], rcbottom - 1 ); // Draw average a vertical bar vgui::surface()->DrawSetColor( 192, 192, 192, 255 ); vgui::surface()->DrawFilledRect( rcleft + wide * fracs[ 2 ], rctop + rowheight / 2, rcleft + wide * fracs[ 2 ] + 1, rcbottom - 1 ); // Draw peak as a vertical red tick vgui::surface()->DrawSetColor( 192, 0, 0, 255 ); vgui::surface()->DrawFilledRect( rcleft + wide * fracs[ 1 ], rctop + 1, rcleft + wide * fracs[ 1 ] + 1, rctop + rowheight / 2 ); } // drew something... return true; } /*else { r = 63; g = 63; b = 63; a = 220; ApplyEffect( entry, r, g, b ); wchar_t unicode[ 256 ]; g_pVGuiLocalize->ConvertANSIToUnicode( ( effectactive && entry->deletedclientclass ) ? entry->deletedclientclass->m_pNetworkName : "unused", unicode, sizeof( unicode ) ); DrawColoredText( m_hFont, left + col * colwidth, top + row * rowheight, r, g, b, a, L"(%i) %s", i, unicode ); }*/ return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CEntityReportPanel::Paint() { VPROF( "CEntityReportPanel::Paint" ); if ( !m_hFont ) return; if ( !cl.IsActive() ) return; if ( !entitylist ) return; int top = 5; int left = 5; int row = 0; int col = 0; int colwidth = 160; int rowheight = vgui::surface()->GetFontTall( m_hFont ); IClientNetworkable *pNet; bool effectactive; ENTITYBITS *entry; int lastused = entitylist->GetMaxEntities()-1; while ( lastused > 0 ) { pNet = entitylist->GetClientNetworkable( lastused ); entry = &s_EntityBits[ lastused ]; effectactive = ( realtime <= entry->effectfinishtime ) ? true : false; if ( pNet && pNet->GetClientClass() ) { break; } if ( effectactive ) break; lastused--; } int start = 0; if ( cl_entityreport.GetInt() > 1 ) { start = cl_entityreport.GetInt(); } // draw sorted if ( cl_entityreport_sorted.GetInt() != ENTITYSORT_NONE ) { // copy and sort int entityIndices[MAX_EDICTS]; int count = lastused - start + 1; for ( int i = 0, entityIdx = start; entityIdx <= lastused; ++i, ++entityIdx ) { entityIndices[i] = entityIdx; } qsort( entityIndices, count, sizeof(int), CompareEntityBits ); // now draw for ( int i = 0; i < count; ++i ) { int entityIdx = entityIndices[i]; if ( DrawEntry( row, col, rowheight, colwidth, entityIdx ) ) { row++; if ( top + row * rowheight > videomode->GetModeStereoHeight() - rowheight ) { row = 0; col++; // No more space anyway, give up if ( left + ( col + 1 ) * 200 > videomode->GetModeStereoWidth() ) return; } } } } // not sorted, old method with items scattered across the screen else { for ( int i = start; i <= lastused; i++ ) { DrawEntry( row, col, rowheight, colwidth, i ); row++; if ( top + row * rowheight > videomode->GetModeStereoHeight() - rowheight ) { row = 0; col++; // No more space anyway, give up if ( left + ( col + 1 ) * 200 > videomode->GetModeStereoWidth() ) return; } } } }
0
0.970671
1
0.970671
game-dev
MEDIA
0.477688
game-dev
0.952572
1
0.952572
magefree/mage
1,609
Mage.Sets/src/mage/cards/s/SoldierOfThePantheon.java
package mage.cards.s; import java.util.UUID; import mage.MageInt; import mage.abilities.common.SpellCastOpponentTriggeredAbility; import mage.abilities.effects.common.GainLifeEffect; import mage.abilities.keyword.ProtectionAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Zone; import mage.filter.FilterObject; import mage.filter.StaticFilters; import mage.filter.predicate.mageobject.MulticoloredPredicate; /** * * @author LevelX2 */ public final class SoldierOfThePantheon extends CardImpl { private static final FilterObject filter = new FilterObject("multicolored"); static { filter.add(MulticoloredPredicate.instance); } public SoldierOfThePantheon(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{W}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.SOLDIER); this.power = new MageInt(2); this.toughness = new MageInt(1); // Protection from multicolored this.addAbility(new ProtectionAbility(filter)); // Whenever an opponent casts a multicolored spell, you gain 1 life. this.addAbility(new SpellCastOpponentTriggeredAbility(Zone.BATTLEFIELD, new GainLifeEffect(1), StaticFilters.FILTER_SPELL_A_MULTICOLORED, false)); } private SoldierOfThePantheon(final SoldierOfThePantheon card) { super(card); } @Override public SoldierOfThePantheon copy() { return new SoldierOfThePantheon(this); } }
0
0.900674
1
0.900674
game-dev
MEDIA
0.991593
game-dev
0.97905
1
0.97905
makspll/bevy_mod_scripting
6,673
crates/bevy_mod_scripting_bindings/src/function/into.rs
//! Implementations of the [`IntoScript`] trait for various types. use super::{DynamicScriptFunction, DynamicScriptFunctionMut, Union, Val}; use crate::{ReflectReference, ScriptValue, WorldGuard, error::InteropError}; use bevy_platform::collections::HashMap; use bevy_reflect::Reflect; use std::{borrow::Cow, ffi::OsString, path::PathBuf}; /// Converts a value into a [`ScriptValue`]. pub trait IntoScript { /// Convert this value into a [`ScriptValue`]. fn into_script(self, world: WorldGuard) -> Result<ScriptValue, InteropError>; /// Convert this value into a [`ScriptValue`], returning an error as a ScriptValue if an error occurs. fn into_script_inline_error(self, world: WorldGuard) -> ScriptValue where Self: Sized, { self.into_script(world).unwrap_or_else(ScriptValue::Error) } } impl IntoScript for ScriptValue { fn into_script(self, _world: WorldGuard) -> Result<ScriptValue, InteropError> { Ok(self) } } #[profiling::all_functions] impl IntoScript for () { fn into_script(self, _world: WorldGuard) -> Result<ScriptValue, InteropError> { Ok(ScriptValue::Unit) } } #[profiling::all_functions] impl IntoScript for DynamicScriptFunctionMut { fn into_script(self, _world: WorldGuard) -> Result<ScriptValue, InteropError> { Ok(ScriptValue::FunctionMut(self)) } } #[profiling::all_functions] impl IntoScript for DynamicScriptFunction { fn into_script(self, _world: WorldGuard) -> Result<ScriptValue, InteropError> { Ok(ScriptValue::Function(self)) } } #[profiling::all_functions] impl IntoScript for bool { fn into_script(self, _world: WorldGuard) -> Result<ScriptValue, InteropError> { Ok(ScriptValue::Bool(self)) } } macro_rules! impl_into_with_downcast { ($variant:tt as $cast:ty [$($ty:ty),*]) => { $( #[profiling::all_functions] impl IntoScript for $ty { fn into_script(self, _world: WorldGuard) -> Result<ScriptValue, InteropError> { Ok(ScriptValue::$variant(self as $cast)) } } )* } } impl_into_with_downcast!(Integer as i64 [i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, usize, isize]); impl_into_with_downcast!(Float as f64 [f32, f64]); macro_rules! impl_into_stringlike { ($id:ident,[ $(($ty:ty => $conversion:expr)),*]) => { $( #[profiling::all_functions] impl IntoScript for $ty { fn into_script(self, _world: WorldGuard) -> Result<ScriptValue, InteropError> { let $id = self; let converted: String = $conversion; Ok(ScriptValue::String(converted.into())) } } )* } } impl_into_stringlike!( s, [ (String => s), (char => s.to_string()), (PathBuf => s.to_string_lossy().to_string()), (OsString => s.into_string().map_err(|e| InteropError::unsupported_operation(None, Some(Box::new(e)), "Could not convert OsString to String".to_owned()))?) ] ); #[profiling::all_functions] impl IntoScript for &'static str { fn into_script(self, _world: WorldGuard) -> Result<ScriptValue, InteropError> { Ok(ScriptValue::String(Cow::Borrowed(self))) } } #[profiling::all_functions] impl IntoScript for ReflectReference { fn into_script(self, _world: WorldGuard) -> Result<ScriptValue, InteropError> { Ok(ScriptValue::Reference(self)) } } #[profiling::all_functions] impl<T: Reflect> IntoScript for Val<T> { fn into_script(self, world: WorldGuard) -> Result<ScriptValue, InteropError> { let boxed = Box::new(self.0); let allocator = world.allocator(); let mut allocator = allocator.write(); Ok(ScriptValue::Reference( ReflectReference::new_allocated_boxed(boxed, &mut allocator), )) } } #[profiling::all_functions] impl<T: IntoScript> IntoScript for Option<T> { fn into_script(self, world: WorldGuard) -> Result<ScriptValue, InteropError> { match self { Some(val) => val.into_script(world), None => Ok(ScriptValue::Unit), } } } #[profiling::all_functions] impl<T: IntoScript> IntoScript for Vec<T> { fn into_script(self, world: WorldGuard) -> Result<ScriptValue, InteropError> { let mut values = Vec::with_capacity(self.len()); for val in self { values.push(val.into_script(world.clone())?); } Ok(ScriptValue::List(values)) } } #[profiling::all_functions] impl<T: IntoScript, const N: usize> IntoScript for [T; N] { fn into_script(self, world: WorldGuard) -> Result<ScriptValue, InteropError> { let mut values = Vec::with_capacity(N); for val in self { values.push(val.into_script(world.clone())?); } Ok(ScriptValue::List(values)) } } #[profiling::all_functions] impl<T1: IntoScript, T2: IntoScript> IntoScript for Union<T1, T2> { fn into_script(self, world: WorldGuard) -> Result<ScriptValue, InteropError> { match self.into_left() { Ok(left) => left.into_script(world), Err(right) => right.into_script(world), } } } #[profiling::all_functions] impl<V: IntoScript> IntoScript for HashMap<String, V> { fn into_script(self, world: WorldGuard) -> Result<ScriptValue, InteropError> { let mut map = HashMap::new(); for (key, value) in self { map.insert(key, value.into_script(world.clone())?); } Ok(ScriptValue::Map(map)) } } #[profiling::all_functions] impl<V: IntoScript> IntoScript for std::collections::HashMap<String, V> { fn into_script(self, world: WorldGuard) -> Result<ScriptValue, InteropError> { let mut map = HashMap::new(); for (key, value) in self { map.insert(key, value.into_script(world.clone())?); } Ok(ScriptValue::Map(map)) } } #[profiling::all_functions] impl IntoScript for InteropError { fn into_script(self, _world: WorldGuard) -> Result<ScriptValue, InteropError> { Ok(ScriptValue::Error(self)) } } macro_rules! impl_into_script_tuple { ($( $ty:ident ),* ) => { #[allow(non_snake_case)] #[profiling::all_functions] impl<$($ty: IntoScript),*> IntoScript for ($($ty,)*) { fn into_script(self, world: WorldGuard) -> Result<ScriptValue, InteropError> { let ($($ty,)*) = self; Ok(ScriptValue::List(vec![$($ty.into_script(world.clone())?),*])) } } } } variadics_please::all_tuples!(impl_into_script_tuple, 1, 14, T);
0
0.90473
1
0.90473
game-dev
MEDIA
0.586829
game-dev
0.793974
1
0.793974
sigeer/RuaMS
1,962
src/Application.Core.Login/ServerData/GachaponManager.cs
using Application.Core.Login.Models.Gachpons; using Application.Core.Login.Shared; using Application.EF; using AutoMapper; using ItemProto; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace Application.Core.Login.ServerData { public class GachaponManager: IStorage { readonly IDbContextFactory<DBContext> _dbContextFactory; readonly ILogger<GachaponManager> _logger; readonly MasterServer _server; readonly IMapper _mapper; List<GachaponPoolModel> _pools = new(); List<GachaponPoolLevelChanceModel> _itemChance = new(); List<GachaponPoolItemModel> _item = new(); public GachaponManager(IDbContextFactory<DBContext> dbContextFactory, ILogger<GachaponManager> logger, MasterServer server, IMapper mapper) { _dbContextFactory = dbContextFactory; _logger = logger; _server = server; _mapper = mapper; } public async Task InitializeAsync(DBContext dbContext) { _pools = _mapper.Map<List<GachaponPoolModel>>(await dbContext.GachaponPools.AsNoTracking().ToListAsync()); _itemChance = _mapper.Map<List<GachaponPoolLevelChanceModel>>(await dbContext.GachaponPoolLevelChances.AsNoTracking().ToListAsync()); _item = _mapper.Map<List<GachaponPoolItemModel>>(await dbContext.GachaponPoolItems.AsNoTracking().ToListAsync()); } public GacheponDataDto GetGachaponData() { var res = new GacheponDataDto(); res.Pools.AddRange(_mapper.Map<ItemProto.GachaponPoolDto[]>(_pools)); res.Items.AddRange(_mapper.Map<ItemProto.GachaponPoolItemDto[]>(_item)); res.Chances.AddRange(_mapper.Map<ItemProto.GachaponPoolChanceDto[]>(_itemChance)); return res; } public Task Commit(DBContext dbContext) { return Task.CompletedTask; } } }
0
0.716154
1
0.716154
game-dev
MEDIA
0.761028
game-dev
0.786562
1
0.786562
Dimbreath/AzurLaneData
4,272
zh-CN/mod/battle/view/character/battleaircraftcharacter.lua
ys = ys or {} slot0 = ys slot1 = slot0.Battle.BattleUnitEvent slot0.Battle.BattleAircraftCharacter = class("BattleAircraftCharacter", slot0.Battle.BattleCharacter) slot0.Battle.BattleAircraftCharacter.__name = "BattleAircraftCharacter" slot2 = slot0.Battle.BattleAircraftCharacter function slot2.Ctor(slot0) uv0.super.Ctor(slot0) slot0._hpBarOffset = Vector3(0, 1.6, 0) slot0:SetYShakeMin() slot0:SetYShakeMax() slot0.shadowScale = Vector3.one slot0.shadowPos = Vector3.zero end function slot2.SetUnitData(slot0, slot1) slot0._unitData = slot1 slot0:AddUnitEvent() end function slot2.InitWeapon(slot0) slot0._weapon = slot0._unitData:GetWeapon() for slot4, slot5 in ipairs(slot0._weapon) do slot5:RegisterEventListener(slot0, uv0.CREATE_BULLET, slot0.onCreateBullet) end end function slot2.GetModleID(slot0) return slot0._unitData:GetSkinID() end function slot2.GetInitScale(slot0) return 1 end function slot2.AddUnitEvent(slot0) end function slot2.RemoveUnitEvent(slot0) for slot4, slot5 in ipairs(slot0._weapon) do slot5:UnregisterEventListener(slot0, uv0.CREATE_BULLET) end if slot0._unitData:GetIFF() == uv1.Battle.BattleConfig.FOE_CODE then slot0._unitData:UnregisterEventListener(slot0, uv0.UPDATE_AIR_CRAFT_HP) end end function slot2.PlayAction(slot0) end function slot2.Update(slot0) slot0:UpdateMatrix() slot0:UpdateDirection() slot0:UpdateUIComponentPosition() slot0:UpdateShadow() slot0:UpdatePosition() if slot0._unitData:GetIFF() == uv0.Battle.BattleConfig.FOE_CODE then slot0:UpdateHPPop() slot0:UpdateHPBarPostition() slot0:UpdateHpBar() end end function slot2.UpdatePosition(slot0) slot0._tf.localPosition = slot0._unitData:GetPosition() slot0._characterPos = slot0._unitData:GetPosition() end function slot2.UpdateDirection(slot0) if slot0._unitData:GetCurrentState() ~= slot0._unitData.STATE_CREATE then return end slot1 = slot0._unitData:GetSize() if slot0._unitData:GetDirection() == uv0.Battle.BattleConst.UnitDir.RIGHT then slot0._tf.localScale = Vector3(slot1, slot1, slot1) elseif slot0._unitData:GetDirection() == uv0.Battle.BattleConst.UnitDir.LEFT then slot0._tf.localScale = Vector3(-slot1, slot1, slot1) end end function slot2.UpdateHPBarPostition(slot0) slot0._hpBarPos:Copy(slot0._referenceVector):Add(slot0._hpBarOffset) slot0._HPBarTf.position = slot0._hpBarPos end function slot2.UpdateShadow(slot0) if slot0._shadow and slot0._unitData:GetCurrentState() == slot0._unitData.STATE_CREATE then slot1 = slot0._unitData:GetPosition() slot2 = math.min(4, math.max(2, 4 - 4 * slot1.y / uv0.Battle.BattleConfig.AircraftHeight)) slot0.shadowScale.z = slot2 slot0.shadowScale.x = slot2 slot0._shadowTF.localScale = slot0.shadowScale slot0.shadowPos.z = slot1.z slot0.shadowPos.x = slot1.x slot0._shadowTF.position = slot0.shadowPos end end function slot2.GetYShake(slot0) slot0._YShakeCurrent = slot0._YShakeCurrent or 0 slot0._YShakeDir = slot0._YShakeDir or 1 slot0._YShakeCurrent = slot0._YShakeCurrent + 0.1 * slot0._YShakeDir if slot0._YShakeMax < slot0._YShakeCurrent and slot0._YShakeDir == 1 then slot0._YShakeDir = -1 slot0:SetYShakeMin() elseif slot0._YShakeCurrent < slot0._YShakeMin and slot0._YShakeDir == -1 then slot0._YShakeDir = 1 slot0:SetYShakeMax() end return slot0._YShakeCurrent end function slot2.SetYShakeMin(slot0) slot0._YShakeMin = -1 - 2 * math.random() end function slot2.SetYShakeMax(slot0) slot0._YShakeMax = 1 + 2 * math.random() end function slot2.AddModel(slot0, slot1) slot0:SetGO(slot1) slot0._hpBarOffset = Vector3(0, slot0._unitData:GetBoxSize().y, 0) slot0:SetBoneList() slot0._tf.position = slot0._unitData:GetPosition() slot0:UpdateMatrix() slot0._unitData:ActiveCldBox() end function slot2.AddShadow(slot0, slot1) slot0._shadow = slot0:GetTf():Find("model/shadow").gameObject slot0._shadowTF = slot0._shadow.transform end function slot2.AddHPBar(slot0, slot1) slot0._HPBar = slot1 slot0._HPBarTf = slot1.transform slot0._HPProgress = slot0._HPBarTf:Find("blood"):GetComponent(typeof(Image)) slot1:SetActive(true) slot0._unitData:RegisterEventListener(slot0, uv0.UPDATE_AIR_CRAFT_HP, slot0.OnUpdateHP) slot0:UpdateHpBar() end function slot2.updateSomkeFX(slot0) end
0
0.657573
1
0.657573
game-dev
MEDIA
0.981929
game-dev
0.893498
1
0.893498
SinlessDevil/AudioVibrationKit
3,331
Assets/Plugins/Zenject/OptionalExtras/TestFramework/SceneTestFixture.cs
using System.Collections; using System.Collections.Generic; using System.Linq; using ModestTree; using NUnit.Framework; using UnityEngine; using UnityEngine.SceneManagement; using Zenject.Internal; using Assert = ModestTree.Assert; // Ignore warning about using SceneManager.UnloadScene instead of SceneManager.UnloadSceneAsync #pragma warning disable 618 namespace Zenject { public abstract class SceneTestFixture { readonly List<DiContainer> _sceneContainers = new List<DiContainer>(); bool _hasLoadedScene; DiContainer _sceneContainer; protected DiContainer SceneContainer { get { return _sceneContainer; } } protected IEnumerable<DiContainer> SceneContainers { get { return _sceneContainers; } } public IEnumerator LoadScene(string sceneName) { return LoadScenes(sceneName); } public IEnumerator LoadScenes(params string[] sceneNames) { Assert.That(!_hasLoadedScene, "Attempted to load scene twice!"); _hasLoadedScene = true; // Clean up any leftovers from previous test ZenjectTestUtil.DestroyEverythingExceptTestRunner(false); Assert.That(SceneContainers.IsEmpty()); for (int i = 0; i < sceneNames.Length; i++) { var sceneName = sceneNames[i]; Assert.That(Application.CanStreamedLevelBeLoaded(sceneName), "Cannot load scene '{0}' for test '{1}'. The scenes used by SceneTestFixture derived classes must be added to the build settings for the test to work", sceneName, GetType()); Log.Info("Loading scene '{0}' for testing", sceneName); var loader = SceneManager.LoadSceneAsync(sceneName, i == 0 ? LoadSceneMode.Single : LoadSceneMode.Additive); while (!loader.isDone) { yield return null; } SceneContext sceneContext = null; if (ProjectContext.HasInstance) // ProjectContext might be null if scene does not have a scene context { var scene = SceneManager.GetSceneByName(sceneName); sceneContext = ProjectContext.Instance.Container.Resolve<SceneContextRegistry>() .TryGetSceneContextForScene(scene); } _sceneContainers.Add(sceneContext == null ? null : sceneContext.Container); } _sceneContainer = _sceneContainers.Where(x => x != null).LastOrDefault(); if (_sceneContainer != null) { _sceneContainer.Inject(this); } } [SetUp] public virtual void SetUp() { StaticContext.Clear(); SetMemberDefaults(); } void SetMemberDefaults() { _hasLoadedScene = false; _sceneContainer = null; _sceneContainers.Clear(); } [TearDown] public virtual void Teardown() { ZenjectTestUtil.DestroyEverythingExceptTestRunner(true); StaticContext.Clear(); SetMemberDefaults(); } } }
0
0.800325
1
0.800325
game-dev
MEDIA
0.520241
game-dev,testing-qa
0.852934
1
0.852934
lynx-family/lynx
1,456
platform/harmony/lynx_harmony/src/main/cpp/module/native_module_capi.h
// Copyright 2024 The Lynx Authors. All rights reserved. // Licensed under the Apache License Version 2.0 that can be found in the // LICENSE file in the root directory of this source tree. #ifndef PLATFORM_HARMONY_LYNX_HARMONY_SRC_MAIN_CPP_MODULE_NATIVE_MODULE_CAPI_H_ #define PLATFORM_HARMONY_LYNX_HARMONY_SRC_MAIN_CPP_MODULE_NATIVE_MODULE_CAPI_H_ #include <memory> #include <string> #include <unordered_map> #include <utility> #include "core/public/jsb/lynx_native_module.h" #include "platform/harmony/lynx_harmony/src/main/cpp/lynx_context.h" namespace lynx { namespace harmony { class NativeModuleCAPI : public piper::LynxNativeModule { public: ~NativeModuleCAPI() override = default; base::expected<std::unique_ptr<pub::Value>, std::string> InvokeMethod( const std::string& method_name, std::unique_ptr<pub::Value> args, size_t count, const piper::CallbackMap& callbacks) override; protected: // Register your own invocation. You can varify method by NativeModuleMethod void RegisterMethod( const piper::NativeModuleMethod& method, piper::LynxNativeModule::NativeModuleInvocation invocation) { methods_.emplace(method.name, method); invocations_.emplace(method.name, std::move(invocation)); } std::unordered_map<std::string, NativeModuleInvocation> invocations_; }; } // namespace harmony } // namespace lynx #endif // PLATFORM_HARMONY_LYNX_HARMONY_SRC_MAIN_CPP_MODULE_NATIVE_MODULE_CAPI_H_
0
0.623175
1
0.623175
game-dev
MEDIA
0.46558
game-dev
0.561386
1
0.561386
Grauenwolf/TravellerTools
7,206
TravellerTools/Grauenwolf.TravellerTools.Characters/Imperium/Careers/Merchant.cs
namespace Grauenwolf.TravellerTools.Characters.Careers.Humaniti; abstract class Merchant(string assignment, SpeciesCharacterBuilder speciesCharacterBuilder) : NormalCareer("Merchant", assignment, speciesCharacterBuilder) { public override CareerGroup CareerGroup => CareerGroup.ImperiumCareer; public override string? Source => "Traveller Core, page 34"; protected override int AdvancedEductionMin => 8; internal override void BasicTrainingSkills(Character character, Dice dice, bool all) { AddBasicSkills(character, dice, all, "Drive", "Vacc Suit", "Broker", "Steward", "Electronics", "Persuade"); } internal override void Event(Character character, Dice dice) { switch (dice.D(2, 6)) { case 2: MishapRollAge(character, dice); character.NextTermBenefits.MusterOut = false; return; case 3: if (dice.NextBoolean()) { character.AddHistory($"Smuggle illegal items onto a planet.", dice); if (dice.RollHigh(character.Skills.BestSkillLevel("Deception", "Persuade"), 8)) { character.Skills.Add("Streetwise", 1); character.BenefitRolls += 1; } } else { character.AddHistory($"Refuse to smuggle illegal items onto a planet. Gain an Enemy.", dice); character.AddEnemy(); } return; case 4: AddOneSkill(character, dice, "Profession", "Electronics", "Engineer", "Animals", "Science"); return; case 5: if (dice.RollHigh(character.Skills.BestSkillLevel("Gambler", "Broker"), 8)) { character.AddHistory($"Risk {character.Name}'s fortune on a possibility lucrative deal and win.", dice); character.BenefitRolls *= 2; } else character.BenefitRolls = 0; IncreaseOneSkill(character, dice, "Broker", "Gambler"); return; case 6: character.AddHistory($"Make an unexpected connection outside {character.Name}'s normal circles. Gain a Contact.", dice); character.AddContact(); return; case 7: LifeEvent(character, dice); return; case 8: character.AddHistory($"Embroiled in legal trouble.", dice); { var skillList = new SkillTemplateCollection(); skillList.Add("Advocate"); skillList.Add("Admin"); skillList.Add("Diplomat"); skillList.Add("Investigate"); } if (dice.D(2, 6) == 2) { character.NextTermBenefits.MusterOut = true; character.NextTermBenefits.MustEnroll = "Prisoner"; } return; case 9: character.AddHistory($"Given advanced training in a specialist field", dice); if (dice.RollHigh(character.EducationDM, 8)) dice.Choose(character.Skills).Level += 1; return; case 10: character.AddHistory($"A good deal ensures {character.Name} is living the high life for a few years.", dice); character.BenefitRollDMs.Add(1); return; case 11: character.AddHistory($"Befriend a useful ally in one sphere. Gain an Ally.", dice); character.AddAlly(); switch (dice.D(2)) { case 1: character.Skills.Add("Carouse", 1); return; case 2: character.CurrentTermBenefits.AdvancementDM += 4; return; } return; case 12: character.AddHistory($"{character.Name}'s business or ship thrives.", dice); character.CurrentTermBenefits.AdvancementDM += 100; return; } } internal override decimal MedicalPaymentPercentage(Character character, Dice dice) { var roll = dice.D(2, 6) + (character.LastCareer?.Rank ?? 0); if (roll >= 12) return 1.0M; if (roll >= 8) return 0.75M; if (roll >= 4) return 0.50M; return 0; } internal override void Mishap(Character character, Dice dice, int age) { switch (dice.D(6)) { case 1: SevereInjury(character, dice, age); return; case 2: character.AddHistory($"Bankrupted by a rival. Gain the other trader as a Rival.", age); character.AddRival(); character.BenefitRolls = 0; return; case 3: character.AddHistory($"A sudden war destroys {character.Name}'s trade routes and contacts, forcing {character.Name} to flee that region of space.", age); character.AddHistory($"Gain rebels as Enemy", age); character.AddEnemy(); AddOneSkill(character, dice, "Gun Combat", "Pilot"); return; case 4: character.AddHistory($"{character.Name}'s ship or starport is destroyed by criminals. Gain them as an Enemy.", age); character.AddEnemy(); return; case 5: character.AddHistory($"Imperial trade restrictions force {character.Name} out of business.", age); character.NextTermBenefits.EnlistmentDM.Add("Rogue", 100); return; case 6: character.AddHistory($"A series of bad deals and decisions force {character.Name} into bankruptcy. {character.Name} salvages what {character.Name} can.", age); character.BenefitRolls += 1; return; } } internal override void ServiceSkill(Character character, Dice dice) { Increase(character, dice, "Drive", "Vacc Suit", "Broker", "Steward", "Electronics", "Persuade"); } protected override void AdvancedEducation(Character character, Dice dice) { Increase(character, dice, "Engineer", "Astrogation", "Electronics", "Pilot", "Admin", "Advocate"); } protected override bool OnQualify(Character character, Dice dice, bool isPrecheck) { var dm = character.IntellectDM; dm += -1 * character.CareerHistory.Count; dm += character.GetEnlistmentBonus(Career, Assignment); dm += QualifyDM; return dice.RollHigh(dm, 4, isPrecheck); } protected override void PersonalDevelopment(Character character, Dice dice) { Increase(character, dice, "Strength", "Dexterity", "Endurance", "Intellect", "Language", "Streetwise"); } }
0
0.718838
1
0.718838
game-dev
MEDIA
0.228858
game-dev
0.949055
1
0.949055
Geant4/geant4
5,413
examples/extended/biasing/GB01/exampleGB01.cc
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // /// \file GB01/exampleGB01.cc /// \brief Main program of the GB01 example // // #include "FTFP_BERT.hh" #include "GB01ActionInitialization.hh" #include "GB01DetectorConstruction.hh" #include "GB01PrimaryGeneratorAction.hh" #include "G4GenericBiasingPhysics.hh" #include "G4RunManagerFactory.hh" #include "G4Types.hh" #include "G4UIExecutive.hh" #include "G4UImanager.hh" #include "G4VisExecutive.hh" //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... namespace { void PrintUsage() { G4cerr << " Usage: " << G4endl; G4cerr << " ./exampleGB01 [-m macro ] " << " [-b biasing {'on','off'}]" << "\n or\n ./exampleGB01 [macro.mac]" << G4endl; } } // namespace //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... int main(int argc, char** argv) { // Evaluate arguments // if (argc > 5) { PrintUsage(); return 1; } G4String macro(""); G4String onOffBiasing(""); if (argc == 2) macro = argv[1]; else { for (G4int i = 1; i < argc; i = i + 2) { if (G4String(argv[i]) == "-m") macro = argv[i + 1]; else if (G4String(argv[i]) == "-b") onOffBiasing = argv[i + 1]; else { PrintUsage(); return 1; } } } if (onOffBiasing == "") onOffBiasing = "on"; // Instantiate G4UIExecutive if interactive mode G4UIExecutive* ui = nullptr; if (macro == "") { ui = new G4UIExecutive(argc, argv); } // -- Construct the run manager : MT or sequential one auto* runManager = G4RunManagerFactory::CreateRunManager(); runManager->SetNumberOfThreads(4); G4bool biasingFlag = (onOffBiasing == "on"); // -- Set mandatory initialization classes auto detector = new GB01DetectorConstruction(biasingFlag); runManager->SetUserInitialization(detector); // -- Select a physics list: auto physicsList = new FTFP_BERT; if (biasingFlag) { // -- and augment it with biasing facilities: auto biasingPhysics = new G4GenericBiasingPhysics(); biasingPhysics->Bias("gamma"); biasingPhysics->Bias("neutron"); biasingPhysics->Bias("kaon0L"); biasingPhysics->Bias("kaon0S"); physicsList->RegisterPhysics(biasingPhysics); G4cout << " ********************************************************* " << G4endl; G4cout << " ********** processes are wrapped for biasing ************ " << G4endl; G4cout << " ********************************************************* " << G4endl; } else { G4cout << " ************************************************* " << G4endl; G4cout << " ********** processes are not wrapped ************ " << G4endl; G4cout << " ************************************************* " << G4endl; } runManager->SetUserInitialization(physicsList); // -- Action initialization: runManager->SetUserInitialization(new GB01ActionInitialization); // Initialize G4 kernel runManager->Initialize(); // Initialize visualization auto visManager = new G4VisExecutive; // G4VisExecutive can take a verbosity argument - see /vis/verbose guidance. visManager->Initialize(); // Get the pointer to the User Interface manager auto UImanager = G4UImanager::GetUIpointer(); if (!ui) // batch mode { G4String command = "/control/execute "; UImanager->ApplyCommand(command + macro); } else { // interactive mode : define UI session UImanager->ApplyCommand("/control/execute vis.mac"); // if (ui->IsGUI()) // UImanager->ApplyCommand("/control/execute gui.mac"); ui->SessionStart(); delete ui; } delete visManager; delete runManager; return 0; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.....
0
0.67609
1
0.67609
game-dev
MEDIA
0.619605
game-dev
0.861722
1
0.861722
Papela/Nitrox-Cracked-Mod
1,654
NitroxClient/GameLogic/PlayerLogic/PlayerPreferences/UnityPreferenceStateProvider.cs
using System; using System.Collections.Generic; using LitJson; using UnityEngine; namespace NitroxClient.GameLogic.PlayerLogic.PlayerPreferences { /// <summary> /// This abstraction allows us to write tests against the preferences manager. Otherwise - we are unduly tied to Unity. /// </summary> public class UnityPreferenceStateProvider : IPreferenceStateProvider { private const string UNITY_PREF_KEY_NAME = "NITROX_PLAYER_PREFS"; public PlayerPreferenceState GetPreferenceState() { JsonMapper.RegisterImporter((double value) => Convert.ToSingle(value)); JsonMapper.RegisterExporter<float>((value, writer) => writer.Write(Convert.ToDouble(value))); string playerPreferencesJson = PlayerPrefs.GetString(UNITY_PREF_KEY_NAME); if (string.IsNullOrEmpty(playerPreferencesJson) || playerPreferencesJson == "{}") { return new PlayerPreferenceState { Preferences = new Dictionary<string, PlayerPreference>() }; } return JsonMapper.ToObject<PlayerPreferenceState>(playerPreferencesJson); } public void SavePreferenceState(PlayerPreferenceState preferenceState) { JsonMapper.RegisterImporter((double value) => Convert.ToSingle(value)); JsonMapper.RegisterExporter<float>((value, writer) => writer.Write(Convert.ToDouble(value))); string playerPreferencesJson = JsonMapper.ToJson(preferenceState); PlayerPrefs.SetString(UNITY_PREF_KEY_NAME, playerPreferencesJson); } } }
0
0.632968
1
0.632968
game-dev
MEDIA
0.858146
game-dev
0.75964
1
0.75964
Ruin0x11/OpenNefia
2,373
src/mod/elona/data/dialog/role/guard.lua
local Chara = require("api.Chara") local I18N = require("api.I18N") local Pos = require("api.Pos") local function cardinal_direction(x1, y1, x2, y2) -- >>>>>>>> shade2/module.hsp:2390 #module ... if math.abs(x1-x2) > math.abs(y1-y2) then if x1 > x2 then return "west" else return "east" end else if y1 > y2 then return "north" else return "south" end end -- <<<<<<<< shade2/module.hsp:2397 .. end local DIR_KEYS = { west = "talk.npc.guard.where_is.direction.west", east = "talk.npc.guard.where_is.direction.east", north = "talk.npc.guard.where_is.direction.north", south = "talk.npc.guard.where_is.direction.south" } local function locate_chara_text(speaker, chara) -- >>>>>>>> shade2/chat.hsp:2967 if chatVal>=headChatListClientGuide{ ... if not Chara.is_alive(chara) then return I18N.get("talk.npc.guard.where_is.dead", speaker) end local player = Chara.player() local dir = cardinal_direction(player.x, player.y, chara.x, chara.y) local dir_key = I18N.get(DIR_KEYS[dir]) local dist = Pos.dist(player.x, player.y, chara.x, chara.y) if speaker.uid == chara.uid then return I18N.get("talk.npc.common.you_kidding", speaker, chara, dir_key) elseif dist < 6 then return I18N.get("talk.npc.guard.where_is.very_close", speaker, chara, dir_key) elseif dist < 12 then return I18N.get("talk.npc.guard.where_is.close", speaker, chara, dir_key) elseif dist < 20 then return I18N.get("talk.npc.guard.where_is.moderate", speaker, chara, dir_key) elseif dist < 35 then return I18N.get("talk.npc.guard.where_is.far", speaker, chara, dir_key) end return I18N.get("talk.npc.guard.where_is.very_far", speaker, chara, dir_key) -- <<<<<<<< shade2/chat.hsp:2983 } .. end data:add { _type = "elona_sys.dialog", _id = "guard", nodes = { where_is = { text = function(t, state, params) local speaker = t.speaker local chara_uid = params.chara_uid local chara = speaker:current_map():get_object_of_type("base.chara", chara_uid) return locate_chara_text(t.speaker, chara) end, jump_to = "elona.default:talk" }, lost_item = function(t) -- TODO return "elona.default:talk" end, } }
0
0.863378
1
0.863378
game-dev
MEDIA
0.985394
game-dev
0.850484
1
0.850484
EvergineTeam/Samples-2.5
3,323
Graphics3D/Billboard/Launchers/MacOS/MainWindow.cs
using System; using Foundation; using WaveEngine.Framework.Graphics; using WaveEngine.Framework.Services; using WaveEngine.Common.Graphics; using System.IO; using WaveEngine.Common.Input; using WaveEngine.Common.Math; namespace Billboard { public partial class MainWindow : WaveEngine.Adapter.Application, WaveEngine.Common.IApplication { #region Computed Properties private SpriteBatch spriteBatch; private Texture2D splashScreen; private bool splashState = true; private TimeSpan time; private Vector2 position; private Color backgroundSplashColor; private Billboard.Game game; #endregion #region Constructors public MainWindow (IntPtr handle) : base (handle) { this.WindowTitle = "Billboard"; this.ResizeScreen(1280, 720); } [Export ("initWithCoder:")] public MainWindow (NSCoder coder) : base (coder) { } #endregion #region Override Methods /// <summary> /// Initialize this instance. /// </summary> public override void Initialize() { this.game = new Billboard.Game(); this.game.Initialize(this); #region DEFAULT SPLASHSCREEN this.backgroundSplashColor = Color.White; this.spriteBatch = new SpriteBatch(WaveServices.GraphicsDevice); var resourceNames = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames(); string name = string.Empty; foreach (string item in resourceNames) { if (item.Contains("SplashScreen.png")) { name = item; break; } } if (string.IsNullOrWhiteSpace(name)) { throw new InvalidProgramException("License terms not agreed."); } using (Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(name)) { this.splashScreen = Texture2D.FromFile(WaveServices.GraphicsDevice, stream); } #endregion } /// <summary> /// Update the specified elapsedTime. /// </summary> /// <param name="elapsedTime">Elapsed time.</param> public override void Update(TimeSpan elapsedTime) { if (this.game != null && !this.game.HasExited) { if (this.splashState) { #region DEFAULT SPLASHSCREEN position.X = (this.Width / 2.0f) - (this.splashScreen.Width / 2.0f); position.Y = (this.Height / 2.0f) - (this.splashScreen.Height / 2.0f); this.time += elapsedTime; if (time > TimeSpan.FromSeconds(2)) { this.splashState = false; } #endregion } else { if (WaveServices.Input.KeyboardState.Escape == ButtonState.Pressed) { WaveServices.Platform.Exit(); } else { this.game.UpdateFrame(elapsedTime); } } } } /// <summary> /// Draw the specified elapsedTime. /// </summary> /// <param name="elapsedTime">Elapsed time.</param> public override void Draw(TimeSpan elapsedTime) { if (this.game != null && !this.game.HasExited) { if (this.splashState) { #region DEFAULT SPLASHSCREEN WaveServices.GraphicsDevice.RenderTargets.SetRenderTarget(null); WaveServices.GraphicsDevice.Clear(ref this.backgroundSplashColor, ClearFlags.Target, 1); this.spriteBatch.Draw(this.splashScreen, this.position, Color.White); this.spriteBatch.Render(); #endregion } else { this.game.DrawFrame(elapsedTime); } } } #endregion } }
0
0.94933
1
0.94933
game-dev
MEDIA
0.675546
game-dev,graphics-rendering
0.997197
1
0.997197
OwlGamingCommunity/MTA
1,910
mods/deathmatch/resources/item-system/s_shellcasings.lua
function createGunNote(weapon, calibre, x, y, z, multiple, count) if not multiple then giveItem(client, 271, calibre.." casing") local itemExists, itemID, itemValue = hasItem(client, 271, calibre.." casing") if itemID then triggerEvent("dropItem", client, itemID, x, y, z, false, false, true) end elseif multiple then giveItem(client, 271, tostring(count).." casings of " ..calibre) local itemExists, itemID, itemValue = hasItem(client, 271, tostring(count).." casings of " ..calibre) if itemID then triggerEvent("dropItem", client, itemID, x, y, z, false, false, true) end end end addEvent("item-system:dropGunNote", true) addEventHandler( "item-system:dropGunNote", root, createGunNote) -- Called from payday function startOldCasingsCheck() local connection = exports.mysql:getConn("mta") dbQuery(checkOldCasings, connection, "SELECT id FROM `worlditems` WHERE itemid=271 AND protected=0 AND creationdate IS NOT NULL AND DATEDIFF(NOW(), creationdate) > 7") end addEvent("item-system:shellcasings", false) addEventHandler("item-system:shellcasings", root, startOldCasingsCheck) function checkOldCasings(query) local connection = exports.mysql:getConn("mta") local objectsTable = {} local pollResult = dbPoll(query, 0) if not pollResult then dbFree(query) else for index, value in ipairs(pollResult) do local id = value["id"] local theObject = exports.pool:getElement("object", tonumber(id)) if (theObject) then destroyElement(theObject) end end -- Blanket query to remove all results from the previous query dbExec(connection, "DELETE FROM `worlditems` WHERE itemid=271 AND protected=0 AND creationdate IS NOT NULL AND DATEDIFF(NOW(), creationdate) > 7") end end
0
0.911789
1
0.911789
game-dev
MEDIA
0.509159
game-dev,databases
0.9434
1
0.9434
ParadiseSS13/Paradise
1,292
code/modules/martial_arts/combos/adminfu/healing_palm.dm
/datum/martial_combo/healing_palm name = "Healing Palm" steps = list(MARTIAL_COMBO_STEP_GRAB, MARTIAL_COMBO_STEP_HELP) explaination_text = "Heals or revives a creature." combo_text_override = "Grab, switch hands, Help" /datum/martial_combo/healing_palm/perform_combo(mob/living/carbon/human/user, mob/living/target, datum/martial_art/MA) user.do_attack_animation(target) target.visible_message("<span class='warning'>[user] smacks [target] in the forehead!</span>") //its the staff of healing code..hush if(ismob(target)) var/old_stat = target.stat if(isanimal(target) && target.stat == DEAD) var/mob/living/simple_animal/O = target var/mob/living/simple_animal/P = new O.type(O.loc) P.real_name = O.real_name P.name = O.name if(O.mind) O.mind.transfer_to(P) else P.key = O.key qdel(O) target = P else target.revive() target.suiciding = 0 if(!target.ckey) for(var/mob/dead/observer/ghost in GLOB.player_list) if(target.real_name == ghost.real_name) ghost.reenter_corpse() break if(old_stat != DEAD) to_chat(target, "<span class='notice'>You feel great!</span>") else to_chat(target, "<span class='notice'>You rise with a start, you're alive!!!</span>") return MARTIAL_COMBO_DONE return MARTIAL_COMBO_FAIL
0
0.761631
1
0.761631
game-dev
MEDIA
0.995073
game-dev
0.883255
1
0.883255
bigai-ai/civrealm
5,214
tests/unit/test_cultivate.py
# Copyright (C) 2023 The CivRealm project # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation, either version 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/>. import pytest from civrealm.freeciv.civ_controller import CivController import civrealm.freeciv.map.map_const as map_const import civrealm.freeciv.units.unit_helpers as unit_helpers from civrealm.freeciv.utils.freeciv_logging import fc_logger from civrealm.configs import fc_args from civrealm.freeciv.utils.test_utils import get_first_observation_option @pytest.fixture def controller(): controller = CivController(fc_args['username']) controller.set_parameter( 'debug.load_game', 'testcontroller_T27_2023-07-10-05_23') yield controller # Delete gamesave saved in handle_begin_turn controller.handle_end_turn(None) controller.close() def test_cultivate(controller): fc_logger.info("test_cultivate") _, options = get_first_observation_option(controller) # Class: UnitActions unit_opt = options['unit'] test_action_list = [] worker_ids = [137, 138, 139] for unit_id in worker_ids: punit = unit_opt.unit_ctrl.units[unit_id] unit_tile = unit_opt.map_ctrl.index_to_tile(punit['tile']) terrain = unit_opt.rule_ctrl.tile_terrain(unit_tile) print( f"Unit id: {unit_id}, position: ({unit_tile['x']}, {unit_tile['y']}), move left: {unit_helpers.get_unit_moves_left(unit_opt.rule_ctrl, punit)}.") # print(terrain) assert (terrain['cultivate_time'] == 0) # Get valid actions valid_actions = unit_opt.get_actions(unit_id, valid_only=True) if unit_id == 137: assert ('cultivate' not in valid_actions) test_action_list.append( valid_actions[f'goto_{map_const.DIR8_EAST}']) elif unit_id == 139: assert ('cultivate' not in valid_actions) test_action_list.append( valid_actions[f'goto_{map_const.DIR8_WEST}']) # Perform goto action for the worker for action in test_action_list: action.trigger_action(controller.ws_client) # Get unit new state controller.send_end_turn() # # Tile info won't update unless options get assigned here controller.get_info_and_observation() for unit_id in worker_ids: punit = unit_opt.unit_ctrl.units[unit_id] unit_tile = unit_opt.map_ctrl.index_to_tile(punit['tile']) terrain = unit_opt.rule_ctrl.tile_terrain(unit_tile) print( f"Unit id: {unit_id}, position: ({unit_tile['x']}, {unit_tile['y']}), move left: {unit_helpers.get_unit_moves_left(unit_opt.rule_ctrl, punit)}.") if unit_id == 139: # Forest's cultivate is larger than 0. assert (terrain['cultivate_time'] > 0) # Get valid actions valid_actions = unit_opt.get_actions(unit_id, valid_only=True) if unit_id == 137 or unit_id == 138: # Plant forest valid_actions[f'plant'].trigger_action(controller.ws_client) if unit_id == 139: assert ('cultivate' in valid_actions) # Wait for 15 turns to finish plant for _ in range(15): controller.send_end_turn() controller.get_info_and_observation() for unit_id in worker_ids: punit = unit_opt.unit_ctrl.units[unit_id] unit_tile = unit_opt.map_ctrl.index_to_tile(punit['tile']) terrain = unit_opt.rule_ctrl.tile_terrain(unit_tile) assert (terrain['cultivate_time'] > 0) assert (terrain['name'] == 'Forest') valid_actions = unit_opt.get_actions(unit_id, valid_only=True) assert ('cultivate' in valid_actions) # Perform cultivate action valid_actions[f'cultivate'].trigger_action(controller.ws_client) # Wait for 5 turns to finish cultivate. for _ in range(5): controller.send_end_turn() controller.get_info_and_observation() for unit_id in worker_ids: punit = unit_opt.unit_ctrl.units[unit_id] unit_tile = unit_opt.map_ctrl.index_to_tile(punit['tile']) terrain = unit_opt.rule_ctrl.tile_terrain(unit_tile) # Forest has been removed. assert (terrain['name'] != 'Forest') valid_actions = unit_opt.get_actions(unit_id, valid_only=True) assert ('cultivate' not in valid_actions) # The terrain which had forest before should allow plant action. assert ('plant' in valid_actions) def main(): controller = CivController(fc_args['username']) controller.set_parameter( 'debug.load_game', 'testcontroller_T27_2023-07-10-05_23') test_cultivate(controller) if __name__ == '__main__': main()
0
0.81583
1
0.81583
game-dev
MEDIA
0.669663
game-dev
0.964784
1
0.964784
RyanLua/Satchel
70,720
src/init.luau
--!nolint DeprecatedApi --[[ This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ]] local ContextActionService = game:GetService("ContextActionService") local TextChatService = game:GetService("TextChatService") local UserInputService = game:GetService("UserInputService") local StarterGui = game:GetService("StarterGui") local GuiService = game:GetService("GuiService") local RunService = game:GetService("RunService") local VRService = game:GetService("VRService") local Players = game:GetService("Players") local PlayerGui: Instance = Players.LocalPlayer:WaitForChild("PlayerGui") local BackpackScript = {} BackpackScript.OpenClose = nil :: any -- Function to toggle open/close BackpackScript.IsOpen = false :: boolean BackpackScript.StateChanged = Instance.new("BindableEvent") :: BindableEvent -- Fires after any open/close, passes IsNowOpen BackpackScript.ModuleName = "Backpack" :: string BackpackScript.KeepVRTopbarOpen = true :: boolean BackpackScript.VRIsExclusive = true :: boolean BackpackScript.VRClosesNonExclusive = true :: boolean BackpackScript.BackpackEmpty = Instance.new("BindableEvent") :: BindableEvent -- Fires when the backpack is empty (no tools BackpackScript.BackpackEmpty.Name = "BackpackEmpty" BackpackScript.BackpackItemAdded = Instance.new("BindableEvent") :: BindableEvent -- Fires when an item is added to the backpack BackpackScript.BackpackItemAdded.Name = "BackpackAdded" BackpackScript.BackpackItemRemoved = Instance.new("BindableEvent") :: BindableEvent -- Fires when an item is removed from the backpack BackpackScript.BackpackItemRemoved.Name = "BackpackRemoved" local targetScript: ModuleScript = script require(script.Attribution) -- Constants -- local PREFERRED_TRANSPARENCY: number = GuiService.PreferredTransparency or 1 -- Legacy behavior for backpack local LEGACY_EDGE_ENABLED: boolean = not targetScript:GetAttribute("OutlineEquipBorder") or false -- Instead of the edge selection being inset, it will be on the outlined. LEGACY_PADDING must be enabled for this to work or this will do nothing local LEGACY_PADDING_ENABLED: boolean = targetScript:GetAttribute("InsetIconPadding") -- Instead of the icon taking up the full slot, it will be padded on each side. -- Background local BACKGROUND_TRANSPARENCY_DEFAULT: number = targetScript:GetAttribute("BackgroundTransparency") or 0.3 local BACKGROUND_TRANSPARENCY: number = BACKGROUND_TRANSPARENCY_DEFAULT * PREFERRED_TRANSPARENCY local BACKGROUND_CORNER_RADIUS: UDim = UDim.new(0, 8) local BACKGROUND_COLOR: Color3 = targetScript:GetAttribute("BackgroundColor3") or Color3.new(25 / 255, 27 / 255, 29 / 255) -- Slots local SLOT_EQUIP_COLOR: Color3 = targetScript:GetAttribute("EquipBorderColor3") or Color3.new(0 / 255, 162 / 255, 1) local SLOT_LOCKED_TRANSPARENCY_DEFAULT: number = targetScript:GetAttribute("BackgroundTransparency") or 0.3 -- Locked means undraggable local SLOT_LOCKED_TRANSPARENCY: number = SLOT_LOCKED_TRANSPARENCY_DEFAULT * PREFERRED_TRANSPARENCY local SLOT_EQUIP_THICKNESS: number = targetScript:GetAttribute("EquipBorderSizePixel") or 5 -- Relative local SLOT_CORNER_RADIUS: UDim = targetScript:GetAttribute("CornerRadius") or UDim.new(0, 8) local SLOT_BORDER_COLOR: Color3 = Color3.new(1, 1, 1) -- Appears when dragging -- Tooltips local TOOLTIP_CORNER_RADIUS: UDim = SLOT_CORNER_RADIUS - UDim.new(0, 5) or UDim.new(0, 3) local TOOLTIP_BACKGROUND_COLOR: Color3 = targetScript:GetAttribute("BackgroundColor3") or Color3.new(25 / 255, 27 / 255, 29 / 255) local TOOLTIP_PADDING: number = 4 local TOOLTIP_HEIGHT: number = 16 local TOOLTIP_OFFSET: number = -5 -- From to -- Topbar icons local ARROW_IMAGE_OPEN: string = "rbxasset://textures/ui/TopBar/inventoryOn.png" local ARROW_IMAGE_CLOSE: string = "rbxasset://textures/ui/TopBar/inventoryOff.png" -- local ARROW_HOTKEY: { Enum.KeyCode } = { Enum.KeyCode.Backquote, Enum.KeyCode.DPadUp } --TODO: Hookup '~' too? -- Hotbar slots local HOTBAR_SLOTS_FULL: number = 10 -- 10 is the max local HOTBAR_SLOTS_VR: number = 6 local HOTBAR_SLOTS_MINI: number = 6 -- Mobile gets 6 slots instead of default 3 it had before local HOTBAR_SLOTS_WIDTH_CUTOFF: number = 1024 -- Anything smaller is MINI local INVENTORY_ROWS_FULL: number = 4 local INVENTORY_ROWS_VR: number = 3 local INVENTORY_ROWS_MINI: number = 2 local INVENTORY_HEADER_SIZE: number = 40 local INVENTORY_ARROWS_BUFFER_VR: number = 40 -- Text local TEXT_COLOR: Color3 = targetScript:GetAttribute("TextColor3") or Color3.new(1, 1, 1) local TEXT_STROKE_TRANSPARENCY: number = targetScript:GetAttribute("TextStrokeTransparency") or 0.5 local TEXT_STROKE_COLOR: Color3 = targetScript:GetAttribute("TextStrokeColor3") or Color3.new(0, 0, 0) -- Search local SEARCH_BACKGROUND_COLOR: Color3 = Color3.new(25 / 255, 27 / 255, 29 / 255) local SEARCH_BACKGROUND_TRANSPARENCY_DEFAULT: number = 0.2 local SEARCH_BACKGROUND_TRANSPARENCY: number = SEARCH_BACKGROUND_TRANSPARENCY_DEFAULT * PREFERRED_TRANSPARENCY local SEARCH_BORDER_COLOR: Color3 = Color3.new(1, 1, 1) local SEARCH_BORDER_TRANSPARENCY: number = 0.8 local SEARCH_BORDER_THICKNESS: number = 1 local SEARCH_TEXT_PLACEHOLDER: string = "Search" local SEARCH_TEXT_OFFSET: number = 8 local SEARCH_TEXT: string = "" local SEARCH_CORNER_RADIUS: UDim = UDim.new(0, 3) local SEARCH_IMAGE_X: string = "rbxasset://textures/ui/InspectMenu/x.png" local SEARCH_BUFFER_PIXELS: number = 5 local SEARCH_WIDTH_PIXELS: number = 200 -- Misc local FONT_FAMILY: Font = targetScript:GetAttribute("FontFace") or Font.new("rbxasset://fonts/families/BuilderSans.json") local FONT_SIZE: number = targetScript:GetAttribute("TextSize") or 16 local DROP_HOTKEY_VALUE: number = Enum.KeyCode.Backspace.Value local ZERO_KEY_VALUE: number = Enum.KeyCode.Zero.Value local DOUBLE_CLICK_TIME: number = 0.5 local ICON_BUFFER_PIXELS: number = 5 local ICON_SIZE_PIXELS: number = 60 local MOUSE_INPUT_TYPES: { [Enum.UserInputType]: boolean } = { -- These are the input types that will be used for mouse -- [[ADDED]], Optional [Enum.UserInputType.MouseButton1] = true, [Enum.UserInputType.MouseButton2] = true, [Enum.UserInputType.MouseButton3] = true, [Enum.UserInputType.MouseMovement] = true, [Enum.UserInputType.MouseWheel] = true, } local GAMEPAD_INPUT_TYPES: { [Enum.UserInputType]: boolean } = { -- These are the input types that will be used for gamepad [Enum.UserInputType.Gamepad1] = true, [Enum.UserInputType.Gamepad2] = true, [Enum.UserInputType.Gamepad3] = true, [Enum.UserInputType.Gamepad4] = true, [Enum.UserInputType.Gamepad5] = true, [Enum.UserInputType.Gamepad6] = true, [Enum.UserInputType.Gamepad7] = true, [Enum.UserInputType.Gamepad8] = true, } -- Topbar logic local BackpackEnabled: boolean = true local Icon: any = require(script.Parent.topbarplus) local inventoryIcon: any = Icon.new() :setName("Inventory") :setImage(ARROW_IMAGE_OPEN, "Selected") :setImage(ARROW_IMAGE_CLOSE, "Deselected") :setImageScale(1) :setCaption("Inventory") :bindToggleKey(Enum.KeyCode.Backquote) :autoDeselect(false) :setOrder(-1) inventoryIcon.toggled:Connect(function(): () if not GuiService.MenuIsOpen then BackpackScript.OpenClose() end end) local BackpackGui: ScreenGui = Instance.new("ScreenGui") BackpackGui.DisplayOrder = 120 BackpackGui.IgnoreGuiInset = true BackpackGui.ResetOnSpawn = false BackpackGui.Name = "BackpackGui" BackpackGui.Parent = PlayerGui local IsTenFootInterface: boolean = GuiService:IsTenFootInterface() if IsTenFootInterface then ICON_SIZE_PIXELS = 100 FONT_SIZE = 24 end local GamepadActionsBound: boolean = false local IS_PHONE: boolean = UserInputService.TouchEnabled and workspace.CurrentCamera.ViewportSize.X < HOTBAR_SLOTS_WIDTH_CUTOFF local Player: Player = Players.LocalPlayer local MainFrame: Frame = nil local HotbarFrame: Frame = nil local InventoryFrame: Frame = nil local VRInventorySelector: any = nil local ScrollingFrame: ScrollingFrame = nil local UIGridFrame: Frame = nil local UIGridLayout: UIGridLayout = nil local ScrollUpInventoryButton: any = nil local ScrollDownInventoryButton: any = nil local changeToolFunc: any = nil local Character: Model = Player.Character or Player.CharacterAdded:Wait() local Humanoid: any = Character:WaitForChild("Humanoid") local Backpack: Instance = Player:WaitForChild("Backpack") local Slots = {} -- List of all Slots by index local LowestEmptySlot: any = nil local SlotsByTool = {} -- Map of Tools to their assigned Slots local HotkeyFns = {} -- Map of KeyCode values to their assigned behaviors local Dragging: { boolean } = {} -- Only used to check if anything is being dragged, to disable other input local FullHotbarSlots: number = 0 -- Now being used to also determine whether or not LB and RB on the gamepad are enabled. local ActiveHopper = nil -- NOTE: HopperBin local StarterToolFound: boolean = false -- Special handling is required for the gear currently equipped on the site local WholeThingEnabled: boolean = false local TextBoxFocused: boolean = false -- ANY TextBox, not just the search box local ViewingSearchResults: boolean = false -- If the results of a search are currently being viewed -- local HotkeyStrings = {} -- Used for eating/releasing hotkeys local CharConns: { RBXScriptConnection } = {} -- Holds character Connections to be cleared later local GamepadEnabled: boolean = false -- determines if our gui needs to be gamepad friendly local IsVR: boolean = VRService.VREnabled -- Are we currently using a VR device? local NumberOfHotbarSlots: number = IsVR and HOTBAR_SLOTS_VR or (IS_PHONE and HOTBAR_SLOTS_MINI or HOTBAR_SLOTS_FULL) -- Number of slots shown at the bottom local NumberOfInventoryRows: number = IsVR and INVENTORY_ROWS_VR or (IS_PHONE and INVENTORY_ROWS_MINI or INVENTORY_ROWS_FULL) -- How many rows in the popped-up inventory local BackpackPanel = nil local lastEquippedSlot: any = nil local function EvaluateBackpackPanelVisibility(enabled: boolean): boolean return enabled and inventoryIcon.enabled and BackpackEnabled and VRService.VREnabled end local function ShowVRBackpackPopup(): () if BackpackPanel and EvaluateBackpackPanelVisibility(true) then BackpackPanel:ForceShowForSeconds(2) end end local function FindLowestEmpty(): number? for i: number = 1, NumberOfHotbarSlots do local slot: any = Slots[i] if not slot.Tool then return slot end end return nil end local function isInventoryEmpty(): boolean for i: number = NumberOfHotbarSlots + 1, #Slots do local slot: any = Slots[i] if slot and slot.Tool then return false end end return true end BackpackScript.IsInventoryEmpty = isInventoryEmpty local function UseGazeSelection(): boolean return false -- disabled in new VR system end local function AdjustHotbarFrames(): () local inventoryOpen: boolean = InventoryFrame.Visible -- (Show all) local visualTotal: number = inventoryOpen and NumberOfHotbarSlots or FullHotbarSlots local visualIndex: number = 0 for i: number = 1, NumberOfHotbarSlots do local slot: any = Slots[i] if slot.Tool or inventoryOpen then visualIndex = visualIndex + 1 slot:Readjust(visualIndex, visualTotal) slot.Frame.Visible = true else slot.Frame.Visible = false end end end local function UpdateScrollingFrameCanvasSize(): () local countX: number = math.floor(ScrollingFrame.AbsoluteSize.X / (ICON_SIZE_PIXELS + ICON_BUFFER_PIXELS)) local maxRow: number = math.ceil((#UIGridFrame:GetChildren() - 1) / countX) local canvasSizeY: number = maxRow * (ICON_SIZE_PIXELS + ICON_BUFFER_PIXELS) + ICON_BUFFER_PIXELS ScrollingFrame.CanvasSize = UDim2.fromOffset(0, canvasSizeY) end local function AdjustInventoryFrames(): () for i: number = NumberOfHotbarSlots + 1, #Slots do local slot: any = Slots[i] slot.Frame.LayoutOrder = slot.Index slot.Frame.Visible = (slot.Tool ~= nil) end UpdateScrollingFrameCanvasSize() end local function UpdateBackpackLayout(): () HotbarFrame.Size = UDim2.new( 0, ICON_BUFFER_PIXELS + (NumberOfHotbarSlots * (ICON_SIZE_PIXELS + ICON_BUFFER_PIXELS)), 0, ICON_BUFFER_PIXELS + ICON_SIZE_PIXELS + ICON_BUFFER_PIXELS ) HotbarFrame.Position = UDim2.new(0.5, -HotbarFrame.Size.X.Offset / 2, 1, -HotbarFrame.Size.Y.Offset) InventoryFrame.Size = UDim2.new( 0, HotbarFrame.Size.X.Offset, 0, (HotbarFrame.Size.Y.Offset * NumberOfInventoryRows) + INVENTORY_HEADER_SIZE + (IsVR and 2 * INVENTORY_ARROWS_BUFFER_VR or 0) ) InventoryFrame.Position = UDim2.new( 0.5, -InventoryFrame.Size.X.Offset / 2, 1, HotbarFrame.Position.Y.Offset - InventoryFrame.Size.Y.Offset ) ScrollingFrame.Size = UDim2.new( 1, ScrollingFrame.ScrollBarThickness + 1, 1, -INVENTORY_HEADER_SIZE - (IsVR and 2 * INVENTORY_ARROWS_BUFFER_VR or 0) ) ScrollingFrame.Position = UDim2.fromOffset(0, INVENTORY_HEADER_SIZE + (IsVR and INVENTORY_ARROWS_BUFFER_VR or 0)) AdjustHotbarFrames() AdjustInventoryFrames() end local function Clamp(low: number, high: number, num: number): number return math.min(high, math.max(low, num)) end local function CheckBounds(guiObject: GuiObject, x: number, y: number): boolean local pos: Vector2 = guiObject.AbsolutePosition local size: Vector2 = guiObject.AbsoluteSize return (x > pos.X and x <= pos.X + size.X and y > pos.Y and y <= pos.Y + size.Y) end local function GetOffset(guiObject: GuiObject, point: Vector2): number local centerPoint: Vector2 = guiObject.AbsolutePosition + (guiObject.AbsoluteSize / 2) return (centerPoint - point).Magnitude end local function DisableActiveHopper(): () --NOTE: HopperBin ActiveHopper:ToggleSelect() SlotsByTool[ActiveHopper]:UpdateEquipView() ActiveHopper = nil :: any end local function UnequipAllTools(): () --NOTE: HopperBin if Humanoid then Humanoid:UnequipTools() if ActiveHopper then DisableActiveHopper() end end end local function EquipNewTool(tool: Tool): () --NOTE: HopperBin UnequipAllTools() Humanoid:EquipTool(tool) --NOTE: This would also unequip current Tool --tool.Parent = Character --TODO: Switch back to above line after EquipTool is fixed! end local function IsEquipped(tool: Tool): boolean return tool and tool.Parent == Character --NOTE: HopperBin end -- Create a slot local function MakeSlot(parent: Instance, initIndex: number?): GuiObject local index: number = initIndex or (#Slots + 1) -- Slot Definition -- local slot: any = {} slot.Tool = nil :: any slot.Index = index :: number slot.Frame = nil :: any local SlotFrame: any = nil local FakeSlotFrame: Frame = nil local ToolIcon: ImageLabel = nil local ToolName: TextLabel = nil local ToolChangeConn: any = nil local HighlightFrame: any = nil -- UIStroke local SelectionObj: ImageLabel = nil --NOTE: The following are only defined for Hotbar Slots local ToolTip: TextLabel = nil local SlotNumber: TextLabel = nil -- Slot Functions -- -- Update slot transparency local function UpdateSlotFading(): () SlotFrame.SelectionImageObject = nil SlotFrame.BackgroundTransparency = SlotFrame.Draggable and 0 or SLOT_LOCKED_TRANSPARENCY end -- Adjust the slots to the centered function slot:Readjust(visualIndex: number, visualTotal: number): ...any --NOTE: Only used for Hotbar slots local centered: number = HotbarFrame.Size.X.Offset / 2 local sizePlus: number = ICON_BUFFER_PIXELS + ICON_SIZE_PIXELS local midpointish: number = (visualTotal / 2) + 0.5 local factor: number = visualIndex - midpointish SlotFrame.Position = UDim2.fromOffset(centered - (ICON_SIZE_PIXELS / 2) + (sizePlus * factor), ICON_BUFFER_PIXELS) end -- Fill the slot with a tool function slot:Fill(tool: Tool): ...any -- Clear slot if it has no tool else assign the tool if not tool then return self:Clear() end self.Tool = tool :: Tool -- Update the slot with tool data local function assignToolData(): () local icon: string = tool.TextureId ToolIcon.Image = icon if icon ~= "" then -- Enable the tool name on the slot if there is no icon ToolName.Visible = false else ToolName.Visible = true end ToolName.Text = tool.Name -- If there is a tooltip, then show it if ToolTip and tool:IsA("Tool") then --NOTE: HopperBin ToolTip.Text = tool.ToolTip ToolTip.Size = UDim2.fromOffset(0, TOOLTIP_HEIGHT) ToolTip.Position = UDim2.new(0.5, 0, 0, TOOLTIP_OFFSET) end end assignToolData() -- Disconnect tool event if it exists if ToolChangeConn then ToolChangeConn:Disconnect() ToolChangeConn = nil end -- Update the slot with new tool data if the tool's properties changes ToolChangeConn = tool.Changed:Connect(function(property: string): () if property == "TextureId" or property == "Name" or property == "ToolTip" then assignToolData() end end) local hotbarSlot: boolean = (self.Index <= NumberOfHotbarSlots) local inventoryOpen: boolean = InventoryFrame.Visible if (not hotbarSlot or inventoryOpen) and not UserInputService.VREnabled then SlotFrame.Draggable = true end self:UpdateEquipView() if hotbarSlot then FullHotbarSlots = FullHotbarSlots + 1 -- If using a controller, determine whether or not we can enable BindCoreAction("BackpackHotbarEquip", etc) if WholeThingEnabled and FullHotbarSlots >= 1 and not GamepadActionsBound then -- Player added first item to a hotbar slot, enable BindCoreAction GamepadActionsBound = true ContextActionService:BindAction( "BackpackHotbarEquip", changeToolFunc, false, Enum.KeyCode.ButtonL1, Enum.KeyCode.ButtonR1 ) end end SlotsByTool[tool] = self LowestEmptySlot = FindLowestEmpty() end -- Empty the slot of any tool data function slot:Clear(): ...any if not self.Tool then return end -- Disconnect tool event if it exists if ToolChangeConn then ToolChangeConn:Disconnect() ToolChangeConn = nil end ToolIcon.Image = "" ToolName.Text = "" if ToolTip then ToolTip.Text = "" ToolTip.Visible = false end SlotFrame.Draggable = false self:UpdateEquipView(true) -- Show as unequipped if self.Index <= NumberOfHotbarSlots then FullHotbarSlots = FullHotbarSlots - 1 if FullHotbarSlots < 1 then -- Player removed last item from hotbar; UnbindCoreAction("BackpackHotbarEquip"), allowing the developer to use LB and RB. GamepadActionsBound = false ContextActionService:UnbindAction("BackpackHotbarEquip") end end SlotsByTool[self.Tool] = nil self.Tool = nil LowestEmptySlot = FindLowestEmpty() end function slot:UpdateEquipView(unequippedOverride: boolean?): ...any local override = unequippedOverride or false if not override and IsEquipped(self.Tool) then -- Equipped lastEquippedSlot = slot if not HighlightFrame then HighlightFrame = Instance.new("UIStroke") HighlightFrame.Name = "Border" HighlightFrame.Thickness = SLOT_EQUIP_THICKNESS HighlightFrame.Color = SLOT_EQUIP_COLOR HighlightFrame.ApplyStrokeMode = Enum.ApplyStrokeMode.Border end if LEGACY_EDGE_ENABLED == true then HighlightFrame.Parent = ToolIcon else HighlightFrame.Parent = SlotFrame end else -- In the Backpack if HighlightFrame then HighlightFrame.Parent = nil end end UpdateSlotFading() end function slot:IsEquipped(): boolean return IsEquipped(self.Tool) end function slot:Delete(): ...any SlotFrame:Destroy() --NOTE: Also clears connections table.remove(Slots, self.Index) local newSize: number = #Slots -- Now adjust the rest (both visually and representationally) for slotIndex: number = self.Index :: number, newSize :: number do Slots[slotIndex]:SlideBack() end UpdateScrollingFrameCanvasSize() end function slot:Swap(targetSlot: any): ...any --NOTE: This slot (self) must not be empty! local myTool: any, otherTool: any = self.Tool, targetSlot.Tool self:Clear() if otherTool then -- (Target slot might be empty) targetSlot:Clear() self:Fill(otherTool) end if myTool then targetSlot:Fill(myTool) else targetSlot:Clear() end end function slot:SlideBack(): ...any -- For inventory slot shifting self.Index = self.Index - 1 SlotFrame.Name = self.Index SlotFrame.LayoutOrder = self.Index end function slot:TurnNumber(on: boolean): ...any if SlotNumber then SlotNumber.Visible = on end end function slot:SetClickability(on: boolean): ...any -- (Happens on open/close arrow) if self.Tool then if UserInputService.VREnabled then SlotFrame.Draggable = false else SlotFrame.Draggable = not on end UpdateSlotFading() end end function slot:CheckTerms(terms: any): number local hits: number = 0 local function checkEm(str: string, term: any): () local _, n: number = str:lower():gsub(term, "") hits = hits + n end local tool: Tool = self.Tool if tool then for term: any in pairs(terms) do checkEm(ToolName.Text, term) if tool:IsA("Tool") then --NOTE: HopperBin local toolTipText: string = ToolTip and ToolTip.Text or "" checkEm(toolTipText, term) end end end return hits end -- Slot select logic, activated by clicking or pressing hotkey function slot:Select(): ...any local tool: Tool = slot.Tool if tool then if IsEquipped(tool) then --NOTE: HopperBin UnequipAllTools() elseif tool.Parent == Backpack then EquipNewTool(tool) end end end -- Slot Init Logic -- SlotFrame = Instance.new("TextButton") SlotFrame.Name = tostring(index) SlotFrame.BackgroundColor3 = BACKGROUND_COLOR SlotFrame.BorderColor3 = SLOT_BORDER_COLOR SlotFrame.Text = "" SlotFrame.BorderSizePixel = 0 SlotFrame.Size = UDim2.fromOffset(ICON_SIZE_PIXELS, ICON_SIZE_PIXELS) SlotFrame.Active = true SlotFrame.Draggable = false SlotFrame.BackgroundTransparency = SLOT_LOCKED_TRANSPARENCY SlotFrame.MouseButton1Click:Connect(function(): () changeSlot(slot) end) local searchFrameCorner: UICorner = Instance.new("UICorner") searchFrameCorner.Name = "Corner" searchFrameCorner.CornerRadius = SLOT_CORNER_RADIUS searchFrameCorner.Parent = SlotFrame slot.Frame = SlotFrame do local selectionObjectClipper: Frame = Instance.new("Frame") selectionObjectClipper.Name = "SelectionObjectClipper" selectionObjectClipper.BackgroundTransparency = 1 selectionObjectClipper.Visible = false selectionObjectClipper.Parent = SlotFrame SelectionObj = Instance.new("ImageLabel") SelectionObj.Name = "Selector" SelectionObj.BackgroundTransparency = 1 SelectionObj.Size = UDim2.fromScale(1, 1) SelectionObj.Image = "rbxasset://textures/ui/Keyboard/key_selection_9slice.png" SelectionObj.ScaleType = Enum.ScaleType.Slice SelectionObj.SliceCenter = Rect.new(12, 12, 52, 52) SelectionObj.Parent = selectionObjectClipper end ToolIcon = Instance.new("ImageLabel") ToolIcon.BackgroundTransparency = 1 ToolIcon.Name = "Icon" ToolIcon.Size = UDim2.fromScale(1, 1) ToolIcon.Position = UDim2.fromScale(0.5, 0.5) ToolIcon.AnchorPoint = Vector2.new(0.5, 0.5) if LEGACY_PADDING_ENABLED == true then ToolIcon.Size = UDim2.new(1, -SLOT_EQUIP_THICKNESS * 2, 1, -SLOT_EQUIP_THICKNESS * 2) else ToolIcon.Size = UDim2.fromScale(1, 1) end ToolIcon.Parent = SlotFrame local ToolIconCorner: UICorner = Instance.new("UICorner") ToolIconCorner.Name = "Corner" if LEGACY_PADDING_ENABLED == true then ToolIconCorner.CornerRadius = SLOT_CORNER_RADIUS - UDim.new(0, SLOT_EQUIP_THICKNESS) else ToolIconCorner.CornerRadius = SLOT_CORNER_RADIUS end ToolIconCorner.Parent = ToolIcon ToolName = Instance.new("TextLabel") ToolName.BackgroundTransparency = 1 ToolName.Name = "ToolName" ToolName.Text = "" ToolName.TextColor3 = TEXT_COLOR ToolName.TextStrokeTransparency = TEXT_STROKE_TRANSPARENCY ToolName.TextStrokeColor3 = TEXT_STROKE_COLOR ToolName.FontFace = Font.new(FONT_FAMILY.Family, Enum.FontWeight.Medium, Enum.FontStyle.Normal) ToolName.TextSize = FONT_SIZE ToolName.Size = UDim2.new(1, -SLOT_EQUIP_THICKNESS * 2, 1, -SLOT_EQUIP_THICKNESS * 2) ToolName.Position = UDim2.fromScale(0.5, 0.5) ToolName.AnchorPoint = Vector2.new(0.5, 0.5) ToolName.TextWrapped = true ToolName.TextTruncate = Enum.TextTruncate.AtEnd ToolName.Parent = SlotFrame slot.Frame.LayoutOrder = slot.Index if index <= NumberOfHotbarSlots then -- Hotbar-Specific Slot Stuff -- ToolTip stuff ToolTip = Instance.new("TextLabel") ToolTip.Name = "ToolTip" ToolTip.Text = "" ToolTip.Size = UDim2.fromScale(1, 1) ToolTip.TextColor3 = TEXT_COLOR ToolTip.TextStrokeTransparency = TEXT_STROKE_TRANSPARENCY ToolTip.TextStrokeColor3 = TEXT_STROKE_COLOR ToolTip.FontFace = Font.new(FONT_FAMILY.Family, Enum.FontWeight.Medium, Enum.FontStyle.Normal) ToolTip.TextSize = FONT_SIZE ToolTip.ZIndex = 2 ToolTip.TextWrapped = false ToolTip.TextYAlignment = Enum.TextYAlignment.Center ToolTip.BackgroundColor3 = TOOLTIP_BACKGROUND_COLOR ToolTip.BackgroundTransparency = SLOT_LOCKED_TRANSPARENCY ToolTip.AnchorPoint = Vector2.new(0.5, 1) ToolTip.BorderSizePixel = 0 ToolTip.Visible = false ToolTip.AutomaticSize = Enum.AutomaticSize.X ToolTip.Parent = SlotFrame local ToolTipCorner: UICorner = Instance.new("UICorner") ToolTipCorner.Name = "Corner" ToolTipCorner.CornerRadius = TOOLTIP_CORNER_RADIUS ToolTipCorner.Parent = ToolTip local ToolTipPadding: UIPadding = Instance.new("UIPadding") ToolTipPadding.PaddingLeft = UDim.new(0, TOOLTIP_PADDING) ToolTipPadding.PaddingRight = UDim.new(0, TOOLTIP_PADDING) ToolTipPadding.PaddingTop = UDim.new(0, TOOLTIP_PADDING) ToolTipPadding.PaddingBottom = UDim.new(0, TOOLTIP_PADDING) ToolTipPadding.Parent = ToolTip SlotFrame.MouseEnter:Connect(function(): () if ToolTip.Text ~= "" then ToolTip.Visible = true end end) SlotFrame.MouseLeave:Connect(function(): () ToolTip.Visible = false end) function slot:MoveToInventory(): ...any if slot.Index <= NumberOfHotbarSlots then -- From a Hotbar slot local tool: any = slot.Tool self:Clear() --NOTE: Order matters here local newSlot: any = MakeSlot(UIGridFrame) newSlot:Fill(tool) if IsEquipped(tool) then -- Also unequip it --NOTE: HopperBin UnequipAllTools() end -- Also hide the inventory slot if we're showing results right now if ViewingSearchResults then newSlot.Frame.Visible = false newSlot.Parent = InventoryFrame end end end -- Show label and assign hotkeys for 1-9 and 0 (zero is always last slot when > 10 total) if index < 10 or index == NumberOfHotbarSlots then -- NOTE: Hardcoded on purpose! local slotNum: number = (index < 10) and index or 0 SlotNumber = Instance.new("TextLabel") SlotNumber.BackgroundTransparency = 1 SlotNumber.Name = "Number" SlotNumber.TextColor3 = TEXT_COLOR SlotNumber.TextStrokeTransparency = TEXT_STROKE_TRANSPARENCY SlotNumber.TextStrokeColor3 = TEXT_STROKE_COLOR SlotNumber.TextSize = FONT_SIZE SlotNumber.Text = tostring(slotNum) SlotNumber.FontFace = Font.new(FONT_FAMILY.Family, Enum.FontWeight.Heavy, Enum.FontStyle.Normal) SlotNumber.Size = UDim2.fromScale(0.4, 0.4) SlotNumber.Visible = false SlotNumber.Parent = SlotFrame HotkeyFns[ZERO_KEY_VALUE + slotNum] = slot.Select end end do -- Dragging Logic local startPoint: UDim2 = SlotFrame.Position local lastUpTime: number = 0 local startParent: any = nil SlotFrame.DragBegin:Connect(function(dragPoint: UDim2): () Dragging[SlotFrame] = true startPoint = dragPoint SlotFrame.BorderSizePixel = 2 inventoryIcon:lock() -- Raise above other slots SlotFrame.ZIndex = 2 ToolIcon.ZIndex = 2 ToolName.ZIndex = 2 SlotFrame.Parent.ZIndex = 2 if SlotNumber then SlotNumber.ZIndex = 2 end -- if HighlightFrame then -- HighlightFrame.ZIndex = 2 -- for _, child in pairs(HighlightFrame:GetChildren()) do -- child.ZIndex = 2 -- end -- end -- Circumvent the ScrollingFrame's ClipsDescendants property startParent = SlotFrame.Parent if startParent == UIGridFrame then local newPosition: UDim2 = UDim2.new( 0, SlotFrame.AbsolutePosition.X - InventoryFrame.AbsolutePosition.X, 0, SlotFrame.AbsolutePosition.Y - InventoryFrame.AbsolutePosition.Y ) SlotFrame.Parent = InventoryFrame SlotFrame.Position = newPosition FakeSlotFrame = Instance.new("Frame") FakeSlotFrame.Name = "FakeSlot" FakeSlotFrame.LayoutOrder = SlotFrame.LayoutOrder FakeSlotFrame.Size = SlotFrame.Size FakeSlotFrame.BackgroundTransparency = 1 FakeSlotFrame.Parent = UIGridFrame end end) SlotFrame.DragStopped:Connect(function(x: number, y: number): () if FakeSlotFrame then FakeSlotFrame:Destroy() end local now: number = os.clock() SlotFrame.Position = startPoint SlotFrame.Parent = startParent SlotFrame.BorderSizePixel = 0 inventoryIcon:unlock() -- Restore height SlotFrame.ZIndex = 1 ToolIcon.ZIndex = 1 ToolName.ZIndex = 1 startParent.ZIndex = 1 if SlotNumber then SlotNumber.ZIndex = 1 end -- if HighlightFrame then -- HighlightFrame.ZIndex = 1 -- for _, child in pairs(HighlightFrame:GetChildren()) do -- child.ZIndex = 1 -- end -- end Dragging[SlotFrame] = nil -- Make sure the tool wasn't dropped if not slot.Tool then return end -- Check where we were dropped if CheckBounds(InventoryFrame, x, y) then if slot.Index <= NumberOfHotbarSlots then slot:MoveToInventory() end -- Check for double clicking on an inventory slot, to move into empty hotbar slot if slot.Index > NumberOfHotbarSlots and now - lastUpTime < DOUBLE_CLICK_TIME then if LowestEmptySlot then local myTool: any = slot.Tool slot:Clear() LowestEmptySlot:Fill(myTool) slot:Delete() end now = 0 -- Resets the timer end elseif CheckBounds(HotbarFrame, x, y) then local closest: { number } = { math.huge, nil :: any } for i: number = 1, NumberOfHotbarSlots do local otherSlot: any = Slots[i] local offset: number = GetOffset(otherSlot.Frame, Vector2.new(x, y)) if offset < closest[1] then closest = { offset, otherSlot } end end local closestSlot: any = closest[2] if closestSlot ~= slot then slot:Swap(closestSlot) if slot.Index > NumberOfHotbarSlots then local tool: Tool = slot.Tool if not tool then -- Clean up after ourselves if we're an inventory slot that's now empty slot:Delete() else -- Moved inventory slot to hotbar slot, and gained a tool that needs to be unequipped if IsEquipped(tool) then --NOTE: HopperBin UnequipAllTools() end -- Also hide the inventory slot if we're showing results right now if ViewingSearchResults then slot.Frame.Visible = false slot.Frame.Parent = InventoryFrame end end end end else -- local tool = slot.Tool -- if tool.CanBeDropped then --TODO: HopperBins -- tool.Parent = workspace -- --TODO: Move away from character -- end if slot.Index <= NumberOfHotbarSlots then slot:MoveToInventory() --NOTE: Temporary end end lastUpTime = now end) end -- All ready! SlotFrame.Parent = parent Slots[index] = slot if index > NumberOfHotbarSlots then UpdateScrollingFrameCanvasSize() -- Scroll to new inventory slot, if we're open and not viewing search results if InventoryFrame.Visible and not ViewingSearchResults then local offset: number = ScrollingFrame.CanvasSize.Y.Offset - ScrollingFrame.AbsoluteSize.Y ScrollingFrame.CanvasPosition = Vector2.new(0, math.max(0, offset)) end end return slot end local function OnChildAdded(child: Instance): () -- To Character or Backpack if not child:IsA("Tool") and not child:IsA("HopperBin") then --NOTE: HopperBin if child:IsA("Humanoid") and child.Parent == Character then Humanoid = child end return end local tool: any = child if tool.Parent == Character then ShowVRBackpackPopup() end if ActiveHopper and tool.Parent == Character then --NOTE: HopperBin DisableActiveHopper() end --TODO: Optimize / refactor / do something else if not StarterToolFound and tool.Parent == Character and not SlotsByTool[tool] then local starterGear: Instance? = Player:FindFirstChild("StarterGear") if starterGear then if starterGear:FindFirstChild(tool.Name) then StarterToolFound = true local slot: any = LowestEmptySlot or MakeSlot(UIGridFrame) for i: number = slot.Index, 1, -1 do local curr = Slots[i] -- An empty slot, because above local pIndex: number = i - 1 if pIndex > 0 then local prev = Slots[pIndex] -- Guaranteed to be full, because above prev:Swap(curr) else curr:Fill(tool) end end -- Have to manually unequip a possibly equipped tool for _, children: Instance in pairs(Character:GetChildren()) do if children:IsA("Tool") and children ~= tool then children.Parent = Backpack end end AdjustHotbarFrames() return -- We're done here end end end -- The tool is either moving or new local slot: any = SlotsByTool[tool] if slot then slot:UpdateEquipView() else -- New! Put into lowest hotbar slot or new inventory slot slot = LowestEmptySlot or MakeSlot(UIGridFrame) slot:Fill(tool) if slot.Index <= NumberOfHotbarSlots and not InventoryFrame.Visible then AdjustHotbarFrames() end if tool:IsA("HopperBin") then --NOTE: HopperBin if tool.Active then UnequipAllTools() ActiveHopper = tool end end end BackpackScript.BackpackItemAdded:Fire() end local function OnChildRemoved(child: Instance): () -- From Character or Backpack if not child:IsA("Tool") and not child:IsA("HopperBin") then --NOTE: HopperBin return end local tool: Tool | any = child ShowVRBackpackPopup() -- Ignore this event if we're just moving between the two local newParent: any = tool.Parent if newParent == Character or newParent == Backpack then return end local slot: any = SlotsByTool[tool] if slot then slot:Clear() if slot.Index > NumberOfHotbarSlots then -- Inventory slot slot:Delete() elseif not InventoryFrame.Visible then AdjustHotbarFrames() end end if tool :: any == ActiveHopper then --NOTE: HopperBin ActiveHopper = nil :: any end BackpackScript.BackpackItemRemoved:Fire() if isInventoryEmpty() then BackpackScript.BackpackEmpty:Fire() end end local function OnCharacterAdded(character: Model): () -- First, clean up any old slots for i: number = #Slots, 1, -1 do local slot = Slots[i] if slot.Tool then slot:Clear() end if i > NumberOfHotbarSlots then slot:Delete() end end ActiveHopper = nil :: any --NOTE: HopperBin -- And any old Connections for _, conn: RBXScriptConnection in pairs(CharConns) do conn:Disconnect() end CharConns = {} -- Hook up the new character Character = character table.insert(CharConns, character.ChildRemoved:Connect(OnChildRemoved)) table.insert(CharConns, character.ChildAdded:Connect(OnChildAdded)) for _, child: Instance in pairs(character:GetChildren()) do OnChildAdded(child) end --NOTE: Humanoid is set inside OnChildAdded -- And the new backpack, when it gets here Backpack = Player:WaitForChild("Backpack") table.insert(CharConns, Backpack.ChildRemoved:Connect(OnChildRemoved)) table.insert(CharConns, Backpack.ChildAdded:Connect(OnChildAdded)) for _, child: Instance in pairs(Backpack:GetChildren()) do OnChildAdded(child) end AdjustHotbarFrames() end local function OnInputBegan(input: InputObject, isProcessed: boolean): () local ChatInputBarConfiguration = TextChatService:FindFirstChildOfClass("ChatInputBarConfiguration") :: ChatInputBarConfiguration -- Pass through keyboard hotkeys when not typing into a TextBox and not disabled (except for the Drop key) if input.UserInputType == Enum.UserInputType.Keyboard and not TextBoxFocused and not ChatInputBarConfiguration.IsFocused and (WholeThingEnabled or input.KeyCode.Value == DROP_HOTKEY_VALUE) then local hotkeyBehavior: any = HotkeyFns[input.KeyCode.Value] if hotkeyBehavior then hotkeyBehavior(isProcessed) end end local inputType: Enum.UserInputType = input.UserInputType if not isProcessed then if inputType == Enum.UserInputType.MouseButton1 or inputType == Enum.UserInputType.Touch then if InventoryFrame.Visible then inventoryIcon:deselect() end end end end local function OnUISChanged(): () -- Detect if player is using Touch if UserInputService:GetLastInputType() == Enum.UserInputType.Touch then for i: number = 1, NumberOfHotbarSlots do Slots[i]:TurnNumber(false) end return end -- Detect if player is using Keyboard if UserInputService:GetLastInputType() == Enum.UserInputType.Keyboard then for i: number = 1, NumberOfHotbarSlots do Slots[i]:TurnNumber(true) end return end -- Detect if player is using Mouse for _, mouse: any in pairs(MOUSE_INPUT_TYPES) do if UserInputService:GetLastInputType() == mouse then for i: number = 1, NumberOfHotbarSlots do Slots[i]:TurnNumber(true) end return end end -- Detect if player is using Controller for _, gamepad: any in pairs(GAMEPAD_INPUT_TYPES) do if UserInputService:GetLastInputType() == gamepad then for i: number = 1, NumberOfHotbarSlots do Slots[i]:TurnNumber(false) end return end end end local lastChangeToolInputObject: InputObject = nil local lastChangeToolInputTime: number = nil local maxEquipDeltaTime: number = 0.06 local noOpFunc = function() end -- local selectDirection = Vector2.new(0, 0) function unbindAllGamepadEquipActions(): () ContextActionService:UnbindAction("BackpackHasGamepadFocus") ContextActionService:UnbindAction("BackpackCloseInventory") end -- local function setHotbarVisibility(visible: boolean, isInventoryScreen: boolean) -- for i: number = 1, NumberOfHotbarSlots do -- local hotbarSlot = Slots[i] -- if hotbarSlot and hotbarSlot.Frame and (isInventoryScreen or hotbarSlot.Tool) then -- hotbarSlot.Frame.Visible = visible -- end -- end -- end -- local function getInputDirection(inputObject: InputObject): Vector2 -- local buttonModifier = 1 -- if inputObject.UserInputState == Enum.UserInputState.End then -- buttonModifier = -1 -- end -- if inputObject.KeyCode == Enum.KeyCode.Thumbstick1 then -- local Magnitude = inputObject.Position.Magnitude -- if Magnitude > 0.98 then -- local normalizedVector = -- Vector2.new(inputObject.Position.X / Magnitude, -inputObject.Position.Y / Magnitude) -- selectDirection = normalizedVector -- else -- selectDirection = Vector2.new(0, 0) -- end -- elseif inputObject.KeyCode == Enum.KeyCode.DPadLeft then -- selectDirection = Vector2.new(selectDirection.X - 1 * buttonModifier, selectDirection.Y) -- elseif inputObject.KeyCode == Enum.KeyCode.DPadRight then -- selectDirection = Vector2.new(selectDirection.X + 1 * buttonModifier, selectDirection.Y) -- elseif inputObject.KeyCode == Enum.KeyCode.DPadUp then -- selectDirection = Vector2.new(selectDirection.X, selectDirection.Y - 1 * buttonModifier) -- elseif inputObject.KeyCode == Enum.KeyCode.DPadDown then -- selectDirection = Vector2.new(selectDirection.X, selectDirection.Y + 1 * buttonModifier) -- else -- selectDirection = Vector2.new(0, 0) -- end -- return selectDirection -- end -- local selectToolExperiment = function(actionName: string, inputState: Enum.UserInputState, inputObject: InputObject) -- local inputDirection = getInputDirection(inputObject) -- if inputDirection == Vector2.new(0, 0) then -- return -- end -- local angle = math.atan2(inputDirection.Y, inputDirection.X) - math.atan2(-1, 0) -- if angle < 0 then -- angle = angle + (math.pi * 2) -- end -- local quarterPi = (math.pi * 0.25) -- local index = (angle / quarterPi) + 1 -- index = math.floor(index + 0.5) -- round index to whole number -- if index > NumberOfHotbarSlots then -- index = 1 -- end -- if index > 0 then -- local selectedSlot = Slots[index] -- if selectedSlot and selectedSlot.Tool and not selectedSlot:IsEquipped() then -- selectedSlot:Select() -- end -- else -- UnequipAllTools() -- end -- end -- selene: allow(unused_variable) changeToolFunc = function(actionName: string, inputState: Enum.UserInputState, inputObject: InputObject): () if inputState ~= Enum.UserInputState.Begin then return end if lastChangeToolInputObject then if ( lastChangeToolInputObject.KeyCode == Enum.KeyCode.ButtonR1 and inputObject.KeyCode == Enum.KeyCode.ButtonL1 ) or ( lastChangeToolInputObject.KeyCode == Enum.KeyCode.ButtonL1 and inputObject.KeyCode == Enum.KeyCode.ButtonR1 ) then if (os.clock() - lastChangeToolInputTime) <= maxEquipDeltaTime then UnequipAllTools() lastChangeToolInputObject = inputObject lastChangeToolInputTime = os.clock() return end end end lastChangeToolInputObject = inputObject lastChangeToolInputTime = os.clock() task.delay(maxEquipDeltaTime, function(): () if lastChangeToolInputObject ~= inputObject then return end local moveDirection: number = 0 if inputObject.KeyCode == Enum.KeyCode.ButtonL1 then moveDirection = -1 else moveDirection = 1 end for i: number = 1, NumberOfHotbarSlots do local hotbarSlot: any = Slots[i] if hotbarSlot:IsEquipped() then local newSlotPosition: number = moveDirection + i local hitEdge: boolean = false if newSlotPosition > NumberOfHotbarSlots then newSlotPosition = 1 hitEdge = true elseif newSlotPosition < 1 then newSlotPosition = NumberOfHotbarSlots hitEdge = true end local origNewSlotPos: number = newSlotPosition while not Slots[newSlotPosition].Tool do newSlotPosition = newSlotPosition + moveDirection if newSlotPosition == origNewSlotPos then return end if newSlotPosition > NumberOfHotbarSlots then newSlotPosition = 1 hitEdge = true elseif newSlotPosition < 1 then newSlotPosition = NumberOfHotbarSlots hitEdge = true end end if hitEdge then UnequipAllTools() lastEquippedSlot = nil else Slots[newSlotPosition]:Select() end return end end if lastEquippedSlot and lastEquippedSlot.Tool then lastEquippedSlot:Select() return end local startIndex: number = moveDirection == -1 and NumberOfHotbarSlots or 1 local endIndex: number = moveDirection == -1 and 1 or NumberOfHotbarSlots for i: number = startIndex, endIndex, moveDirection do if Slots[i].Tool then Slots[i]:Select() return end end end) end function getGamepadSwapSlot(): any for i: number = 1, #Slots do if Slots[i].Frame.BorderSizePixel > 0 then return Slots[i] end end return end -- selene: allow(unused_variable) function changeSlot(slot: any): () local swapInVr: boolean = not VRService.VREnabled or InventoryFrame.Visible if slot.Frame == GuiService.SelectedObject and swapInVr then local currentlySelectedSlot: any = getGamepadSwapSlot() if currentlySelectedSlot then currentlySelectedSlot.Frame.BorderSizePixel = 0 if currentlySelectedSlot ~= slot then slot:Swap(currentlySelectedSlot) VRInventorySelector.SelectionImageObject.Visible = false if slot.Index > NumberOfHotbarSlots and not slot.Tool then if GuiService.SelectedObject == slot.Frame then GuiService.SelectedObject = currentlySelectedSlot.Frame end slot:Delete() end if currentlySelectedSlot.Index > NumberOfHotbarSlots and not currentlySelectedSlot.Tool then if GuiService.SelectedObject == currentlySelectedSlot.Frame then GuiService.SelectedObject = slot.Frame end currentlySelectedSlot:Delete() end end else local startSize: UDim2 = slot.Frame.Size local startPosition: UDim2 = slot.Frame.Position slot.Frame:TweenSizeAndPosition( startSize + UDim2.fromOffset(10, 10), startPosition - UDim2.fromOffset(5, 5), Enum.EasingDirection.Out, Enum.EasingStyle.Quad, 0.1, true, function(): () slot.Frame:TweenSizeAndPosition( startSize, startPosition, Enum.EasingDirection.In, Enum.EasingStyle.Quad, 0.1, true ) end ) slot.Frame.BorderSizePixel = 3 VRInventorySelector.SelectionImageObject.Visible = true end else slot:Select() VRInventorySelector.SelectionImageObject.Visible = false end end function vrMoveSlotToInventory(): () if not VRService.VREnabled then return end local currentlySelectedSlot: any = getGamepadSwapSlot() if currentlySelectedSlot and currentlySelectedSlot.Tool then currentlySelectedSlot.Frame.BorderSizePixel = 0 currentlySelectedSlot:MoveToInventory() VRInventorySelector.SelectionImageObject.Visible = false end end function enableGamepadInventoryControl(): () local goBackOneLevel = function(): () -- if inputState ~= Enum.UserInputState.Begin then -- return -- end local selectedSlot: any = getGamepadSwapSlot() if selectedSlot then -- selene: allow(shadowing) local selectedSlot: any = getGamepadSwapSlot() if selectedSlot then selectedSlot.Frame.BorderSizePixel = 0 return end elseif InventoryFrame.Visible then inventoryIcon:deselect() end end ContextActionService:BindAction("BackpackHasGamepadFocus", noOpFunc, false, Enum.UserInputType.Gamepad1) ContextActionService:BindAction( "BackpackCloseInventory", goBackOneLevel, false, Enum.KeyCode.ButtonB, Enum.KeyCode.ButtonStart ) -- Gaze select will automatically select the object for us! if not UseGazeSelection() then GuiService.SelectedObject = HotbarFrame:FindFirstChild("1") end end function disableGamepadInventoryControl(): () unbindAllGamepadEquipActions() for i: number = 1, NumberOfHotbarSlots do local hotbarSlot: any = Slots[i] if hotbarSlot and hotbarSlot.Frame then hotbarSlot.Frame.BorderSizePixel = 0 end end if GuiService.SelectedObject and GuiService.SelectedObject:IsDescendantOf(MainFrame) then GuiService.SelectedObject = nil end end local function bindBackpackHotbarAction(): () if WholeThingEnabled and not GamepadActionsBound then GamepadActionsBound = true ContextActionService:BindAction( "BackpackHotbarEquip", changeToolFunc, false, Enum.KeyCode.ButtonL1, Enum.KeyCode.ButtonR1 ) end end local function unbindBackpackHotbarAction(): () disableGamepadInventoryControl() GamepadActionsBound = false ContextActionService:UnbindAction("BackpackHotbarEquip") end function gamepadDisconnected(): () GamepadEnabled = false disableGamepadInventoryControl() end function gamepadConnected(): () GamepadEnabled = true GuiService:AddSelectionParent("BackpackSelection", MainFrame) if FullHotbarSlots >= 1 then bindBackpackHotbarAction() end if InventoryFrame.Visible then enableGamepadInventoryControl() end end local function OnIconChanged(enabled: boolean): () -- Check for enabling/disabling the whole thing local success, _topbarEnabled = pcall(function() return enabled and StarterGui:GetCore("TopbarEnabled") end) if not success then return end WholeThingEnabled = enabled MainFrame.Visible = enabled -- Eat/Release hotkeys (Doesn't affect UserInputService) -- for _, keyString in pairs(HotkeyStrings) do -- if enabled then -- GuiService:AddKey(keyString) -- else -- GuiService:RemoveKey(keyString) -- end -- end if enabled then if FullHotbarSlots >= 1 then bindBackpackHotbarAction() end else unbindBackpackHotbarAction() end end local function MakeVRRoundButton(name: string, image: string): (ImageButton, ImageLabel, ImageLabel) local newButton: ImageButton = Instance.new("ImageButton") newButton.BackgroundTransparency = 1 newButton.Name = name newButton.Size = UDim2.fromOffset(40, 40) newButton.Image = "rbxasset://textures/ui/Keyboard/close_button_background.png" local buttonIcon: ImageLabel = Instance.new("ImageLabel") buttonIcon.Name = "Icon" buttonIcon.BackgroundTransparency = 1 buttonIcon.Size = UDim2.fromScale(0.5, 0.5) buttonIcon.Position = UDim2.fromScale(0.25, 0.25) buttonIcon.Image = image buttonIcon.Parent = newButton local buttonSelectionObject: ImageLabel = Instance.new("ImageLabel") buttonSelectionObject.BackgroundTransparency = 1 buttonSelectionObject.Name = "Selection" buttonSelectionObject.Size = UDim2.fromScale(0.9, 0.9) buttonSelectionObject.Position = UDim2.fromScale(0.05, 0.05) buttonSelectionObject.Image = "rbxasset://textures/ui/Keyboard/close_button_selection.png" newButton.SelectionImageObject = buttonSelectionObject return newButton, buttonIcon, buttonSelectionObject end -- Make the main frame, which (mostly) covers the screen MainFrame = Instance.new("Frame") MainFrame.BackgroundTransparency = 1 MainFrame.Name = "Backpack" MainFrame.Size = UDim2.fromScale(1, 1) MainFrame.Visible = false MainFrame.Parent = BackpackGui -- Make the HotbarFrame, which holds only the Hotbar Slots HotbarFrame = Instance.new("Frame") HotbarFrame.BackgroundTransparency = 1 HotbarFrame.Name = "Hotbar" HotbarFrame.Size = UDim2.fromScale(1, 1) HotbarFrame.Parent = MainFrame -- Make all the Hotbar Slots for index: number = 1, NumberOfHotbarSlots do local slot: any = MakeSlot(HotbarFrame, index) slot.Frame.Visible = false if not LowestEmptySlot then LowestEmptySlot = slot end end local LeftBumperButton: ImageLabel = Instance.new("ImageLabel") LeftBumperButton.BackgroundTransparency = 1 LeftBumperButton.Name = "LeftBumper" LeftBumperButton.Size = UDim2.fromOffset(40, 40) LeftBumperButton.Position = UDim2.new(0, -LeftBumperButton.Size.X.Offset, 0.5, -LeftBumperButton.Size.Y.Offset / 2) local RightBumperButton: ImageLabel = Instance.new("ImageLabel") RightBumperButton.BackgroundTransparency = 1 RightBumperButton.Name = "RightBumper" RightBumperButton.Size = UDim2.fromOffset(40, 40) RightBumperButton.Position = UDim2.new(1, 0, 0.5, -RightBumperButton.Size.Y.Offset / 2) -- Make the Inventory, which holds the ScrollingFrame, the header, and the search box InventoryFrame = Instance.new("Frame") InventoryFrame.Name = "Inventory" InventoryFrame.Size = UDim2.fromScale(1, 1) InventoryFrame.BackgroundTransparency = BACKGROUND_TRANSPARENCY InventoryFrame.BackgroundColor3 = BACKGROUND_COLOR InventoryFrame.Active = true InventoryFrame.Visible = false InventoryFrame.Parent = MainFrame -- Add corners to the InventoryFrame local corner: UICorner = Instance.new("UICorner") corner.Name = "Corner" corner.CornerRadius = BACKGROUND_CORNER_RADIUS corner.Parent = InventoryFrame VRInventorySelector = Instance.new("TextButton") VRInventorySelector.Name = "VRInventorySelector" VRInventorySelector.Position = UDim2.new(0, 0, 0, 0) VRInventorySelector.Size = UDim2.fromScale(1, 1) VRInventorySelector.BackgroundTransparency = 1 VRInventorySelector.Text = "" VRInventorySelector.Parent = InventoryFrame local selectorImage: ImageLabel = Instance.new("ImageLabel") selectorImage.BackgroundTransparency = 1 selectorImage.Name = "Selector" selectorImage.Size = UDim2.fromScale(1, 1) selectorImage.Image = "rbxasset://textures/ui/Keyboard/key_selection_9slice.png" selectorImage.ScaleType = Enum.ScaleType.Slice selectorImage.SliceCenter = Rect.new(12, 12, 52, 52) selectorImage.Visible = false VRInventorySelector.SelectionImageObject = selectorImage VRInventorySelector.MouseButton1Click:Connect(function(): () vrMoveSlotToInventory() end) -- Make the ScrollingFrame, which holds the rest of the Slots (however many) ScrollingFrame = Instance.new("ScrollingFrame") ScrollingFrame.BackgroundTransparency = 1 ScrollingFrame.Name = "ScrollingFrame" ScrollingFrame.Size = UDim2.fromScale(1, 1) ScrollingFrame.Selectable = false ScrollingFrame.ScrollingDirection = Enum.ScrollingDirection.Y ScrollingFrame.BorderSizePixel = 0 ScrollingFrame.ScrollBarThickness = 8 ScrollingFrame.ScrollBarImageColor3 = Color3.new(1, 1, 1) ScrollingFrame.VerticalScrollBarInset = Enum.ScrollBarInset.ScrollBar ScrollingFrame.CanvasSize = UDim2.new(0, 0, 0, 0) ScrollingFrame.Parent = InventoryFrame UIGridFrame = Instance.new("Frame") UIGridFrame.BackgroundTransparency = 1 UIGridFrame.Name = "UIGridFrame" UIGridFrame.Selectable = false UIGridFrame.Size = UDim2.new(1, -(ICON_BUFFER_PIXELS * 2), 1, 0) UIGridFrame.Position = UDim2.fromOffset(ICON_BUFFER_PIXELS, 0) UIGridFrame.Parent = ScrollingFrame UIGridLayout = Instance.new("UIGridLayout") UIGridLayout.SortOrder = Enum.SortOrder.LayoutOrder UIGridLayout.CellSize = UDim2.fromOffset(ICON_SIZE_PIXELS, ICON_SIZE_PIXELS) UIGridLayout.CellPadding = UDim2.fromOffset(ICON_BUFFER_PIXELS, ICON_BUFFER_PIXELS) UIGridLayout.Parent = UIGridFrame ScrollUpInventoryButton = MakeVRRoundButton("ScrollUpButton", "rbxasset://textures/ui/Backpack/ScrollUpArrow.png") ScrollUpInventoryButton.Size = UDim2.fromOffset(34, 34) ScrollUpInventoryButton.Position = UDim2.new(0.5, -ScrollUpInventoryButton.Size.X.Offset / 2, 0, INVENTORY_HEADER_SIZE + 3) ScrollUpInventoryButton.Icon.Position = ScrollUpInventoryButton.Icon.Position - UDim2.fromOffset(0, 2) ScrollUpInventoryButton.MouseButton1Click:Connect(function(): () ScrollingFrame.CanvasPosition = Vector2.new( ScrollingFrame.CanvasPosition.X, Clamp( 0, ScrollingFrame.CanvasSize.Y.Offset - ScrollingFrame.AbsoluteWindowSize.Y, ScrollingFrame.CanvasPosition.Y - (ICON_BUFFER_PIXELS + ICON_SIZE_PIXELS) ) ) end) ScrollDownInventoryButton = MakeVRRoundButton("ScrollDownButton", "rbxasset://textures/ui/Backpack/ScrollUpArrow.png") ScrollDownInventoryButton.Rotation = 180 ScrollDownInventoryButton.Icon.Position = ScrollDownInventoryButton.Icon.Position - UDim2.fromOffset(0, 2) ScrollDownInventoryButton.Size = UDim2.fromOffset(34, 34) ScrollDownInventoryButton.Position = UDim2.new(0.5, -ScrollDownInventoryButton.Size.X.Offset / 2, 1, -ScrollDownInventoryButton.Size.Y.Offset - 3) ScrollDownInventoryButton.MouseButton1Click:Connect(function(): () ScrollingFrame.CanvasPosition = Vector2.new( ScrollingFrame.CanvasPosition.X, Clamp( 0, ScrollingFrame.CanvasSize.Y.Offset - ScrollingFrame.AbsoluteWindowSize.Y, ScrollingFrame.CanvasPosition.Y + (ICON_BUFFER_PIXELS + ICON_SIZE_PIXELS) ) ) end) ScrollingFrame.Changed:Connect(function(prop: string): () if prop == "AbsoluteWindowSize" or prop == "CanvasPosition" or prop == "CanvasSize" then local canScrollUp: boolean = ScrollingFrame.CanvasPosition.Y ~= 0 local canScrollDown: boolean = ScrollingFrame.CanvasPosition.Y < ScrollingFrame.CanvasSize.Y.Offset - ScrollingFrame.AbsoluteWindowSize.Y ScrollUpInventoryButton.Visible = canScrollUp ScrollDownInventoryButton.Visible = canScrollDown end end) -- Position the frames and sizes for the Backpack GUI elements UpdateBackpackLayout() --Make the gamepad hint frame local gamepadHintsFrame: Frame = Instance.new("Frame") gamepadHintsFrame.Name = "GamepadHintsFrame" gamepadHintsFrame.Size = UDim2.fromOffset(HotbarFrame.Size.X.Offset, (IsTenFootInterface and 95 or 60)) gamepadHintsFrame.BackgroundTransparency = BACKGROUND_TRANSPARENCY gamepadHintsFrame.BackgroundColor3 = BACKGROUND_COLOR gamepadHintsFrame.Visible = false gamepadHintsFrame.Parent = MainFrame local gamepadHintsFrameLayout: UIListLayout = Instance.new("UIListLayout") gamepadHintsFrameLayout.Name = "Layout" gamepadHintsFrameLayout.Padding = UDim.new(0, 25) gamepadHintsFrameLayout.FillDirection = Enum.FillDirection.Horizontal gamepadHintsFrameLayout.HorizontalAlignment = Enum.HorizontalAlignment.Center gamepadHintsFrameLayout.SortOrder = Enum.SortOrder.LayoutOrder gamepadHintsFrameLayout.Parent = gamepadHintsFrame local gamepadHintsFrameCorner: UICorner = Instance.new("UICorner") gamepadHintsFrameCorner.Name = "Corner" gamepadHintsFrameCorner.CornerRadius = BACKGROUND_CORNER_RADIUS gamepadHintsFrameCorner.Parent = gamepadHintsFrame local function addGamepadHint(hintImageString: string, hintTextString: string): () local hintFrame: Frame = Instance.new("Frame") hintFrame.Name = "HintFrame" hintFrame.AutomaticSize = Enum.AutomaticSize.XY hintFrame.BackgroundTransparency = 1 hintFrame.Parent = gamepadHintsFrame local hintLayout: UIListLayout = Instance.new("UIListLayout") hintLayout.Name = "Layout" hintLayout.Padding = (IsTenFootInterface and UDim.new(0, 20) or UDim.new(0, 12)) hintLayout.FillDirection = Enum.FillDirection.Horizontal hintLayout.SortOrder = Enum.SortOrder.LayoutOrder hintLayout.VerticalAlignment = Enum.VerticalAlignment.Center hintLayout.Parent = hintFrame local hintImage: ImageLabel = Instance.new("ImageLabel") hintImage.Name = "HintImage" hintImage.Size = (IsTenFootInterface and UDim2.fromOffset(60, 60) or UDim2.fromOffset(30, 30)) hintImage.BackgroundTransparency = 1 hintImage.Image = hintImageString hintImage.Parent = hintFrame local hintText: TextLabel = Instance.new("TextLabel") hintText.Name = "HintText" hintText.AutomaticSize = Enum.AutomaticSize.XY hintText.FontFace = Font.new(FONT_FAMILY.Family, Enum.FontWeight.Medium, Enum.FontStyle.Normal) hintText.TextSize = (IsTenFootInterface and 32 or 19) hintText.BackgroundTransparency = 1 hintText.Text = hintTextString hintText.TextColor3 = Color3.new(1, 1, 1) hintText.TextXAlignment = Enum.TextXAlignment.Left hintText.TextYAlignment = Enum.TextYAlignment.Center hintText.TextWrapped = true hintText.Parent = hintFrame local textSizeConstraint: UITextSizeConstraint = Instance.new("UITextSizeConstraint") textSizeConstraint.MaxTextSize = hintText.TextSize textSizeConstraint.Parent = hintText end addGamepadHint(UserInputService:GetImageForKeyCode(Enum.KeyCode.ButtonX), "Remove From Hotbar") addGamepadHint(UserInputService:GetImageForKeyCode(Enum.KeyCode.ButtonA), "Select/Swap") addGamepadHint(UserInputService:GetImageForKeyCode(Enum.KeyCode.ButtonB), "Close Backpack") local function resizeGamepadHintsFrame(): () gamepadHintsFrame.Size = UDim2.new(HotbarFrame.Size.X.Scale, HotbarFrame.Size.X.Offset, 0, (IsTenFootInterface and 95 or 60)) gamepadHintsFrame.Position = UDim2.new( HotbarFrame.Position.X.Scale, HotbarFrame.Position.X.Offset, InventoryFrame.Position.Y.Scale, InventoryFrame.Position.Y.Offset - gamepadHintsFrame.Size.Y.Offset - ICON_BUFFER_PIXELS ) local spaceTaken: number = 0 local gamepadHints: { Instance } = gamepadHintsFrame:GetChildren() local filteredGamepadHints: any = {} for _, child: Instance in pairs(gamepadHints) do if child:IsA("GuiObject") then table.insert(filteredGamepadHints, child) end end --First get the total space taken by all the hints for guiObjects = 1, #filteredGamepadHints do if filteredGamepadHints[guiObjects]:IsA("GuiObject") then filteredGamepadHints[guiObjects].Size = UDim2.new(1, 0, 1, -5) filteredGamepadHints[guiObjects].Position = UDim2.new(0, 0, 0, 0) spaceTaken = spaceTaken + ( filteredGamepadHints[guiObjects].HintText.Position.X.Offset + filteredGamepadHints[guiObjects].HintText.TextBounds.X ) end end --The space between all the frames should be equal local spaceBetweenElements: number = (gamepadHintsFrame.AbsoluteSize.X - spaceTaken) / (#filteredGamepadHints - 1) for i: number = 1, #filteredGamepadHints do filteredGamepadHints[i].Position = ( i == 1 and UDim2.new(0, 0, 0, 0) or UDim2.new( 0, filteredGamepadHints[i - 1].Position.X.Offset + filteredGamepadHints[i - 1].Size.X.Offset + spaceBetweenElements, 0, 0 ) ) filteredGamepadHints[i].Size = UDim2.new( 0, (filteredGamepadHints[i].HintText.Position.X.Offset + filteredGamepadHints[i].HintText.TextBounds.X), 1, -5 ) end end local searchFrame: Frame = Instance.new("Frame") do -- Search stuff searchFrame.Name = "Search" searchFrame.BackgroundColor3 = SEARCH_BACKGROUND_COLOR searchFrame.BackgroundTransparency = SEARCH_BACKGROUND_TRANSPARENCY searchFrame.Size = UDim2.new( 0, SEARCH_WIDTH_PIXELS - (SEARCH_BUFFER_PIXELS * 2), 0, INVENTORY_HEADER_SIZE - (SEARCH_BUFFER_PIXELS * 2) ) searchFrame.Position = UDim2.new(1, -searchFrame.Size.X.Offset - SEARCH_BUFFER_PIXELS, 0, SEARCH_BUFFER_PIXELS) searchFrame.Parent = InventoryFrame local searchFrameCorner: UICorner = Instance.new("UICorner") searchFrameCorner.Name = "Corner" searchFrameCorner.CornerRadius = SEARCH_CORNER_RADIUS searchFrameCorner.Parent = searchFrame local searchFrameBorder: UIStroke = Instance.new("UIStroke") searchFrameBorder.Name = "Border" searchFrameBorder.Color = SEARCH_BORDER_COLOR searchFrameBorder.Thickness = SEARCH_BORDER_THICKNESS searchFrameBorder.Transparency = SEARCH_BORDER_TRANSPARENCY searchFrameBorder.Parent = searchFrame local searchBox: TextBox = Instance.new("TextBox") searchBox.BackgroundTransparency = 1 searchBox.Name = "TextBox" searchBox.Text = "" searchBox.TextColor3 = TEXT_COLOR searchBox.TextStrokeTransparency = TEXT_STROKE_TRANSPARENCY searchBox.TextStrokeColor3 = TEXT_STROKE_COLOR searchBox.FontFace = Font.new(FONT_FAMILY.Family, Enum.FontWeight.Medium, Enum.FontStyle.Normal) searchBox.PlaceholderText = SEARCH_TEXT_PLACEHOLDER searchBox.TextColor3 = TEXT_COLOR searchBox.TextTransparency = TEXT_STROKE_TRANSPARENCY searchBox.TextStrokeColor3 = TEXT_STROKE_COLOR searchBox.ClearTextOnFocus = false searchBox.TextTruncate = Enum.TextTruncate.AtEnd searchBox.TextSize = FONT_SIZE searchBox.TextXAlignment = Enum.TextXAlignment.Left searchBox.TextYAlignment = Enum.TextYAlignment.Center searchBox.Size = UDim2.new( 0, (SEARCH_WIDTH_PIXELS - (SEARCH_BUFFER_PIXELS * 2)) - (SEARCH_TEXT_OFFSET * 2) - 20, 0, INVENTORY_HEADER_SIZE - (SEARCH_BUFFER_PIXELS * 2) - (SEARCH_TEXT_OFFSET * 2) ) searchBox.AnchorPoint = Vector2.new(0, 0.5) searchBox.Position = UDim2.new(0, SEARCH_TEXT_OFFSET, 0.5, 0) searchBox.ZIndex = 2 searchBox.Parent = searchFrame local xButton: TextButton = Instance.new("TextButton") xButton.Name = "X" xButton.Text = "" xButton.Size = UDim2.fromOffset(30, 30) xButton.Position = UDim2.new(1, -xButton.Size.X.Offset, 0.5, -xButton.Size.Y.Offset / 2) xButton.ZIndex = 4 xButton.Visible = false xButton.BackgroundTransparency = 1 xButton.Parent = searchFrame local xImage: ImageButton = Instance.new("ImageButton") xImage.Name = "X" xImage.Image = SEARCH_IMAGE_X xImage.BackgroundTransparency = 1 xImage.Size = UDim2.new( 0, searchFrame.Size.Y.Offset - (SEARCH_BUFFER_PIXELS * 4), 0, searchFrame.Size.Y.Offset - (SEARCH_BUFFER_PIXELS * 4) ) xImage.AnchorPoint = Vector2.new(0.5, 0.5) xImage.Position = UDim2.fromScale(0.5, 0.5) xImage.ZIndex = 1 xImage.BorderSizePixel = 0 xImage.Parent = xButton local function search(): () local terms: { [string]: boolean } = {} for word: string in searchBox.Text:gmatch("%S+") do terms[word:lower()] = true end local hitTable = {} for i: number = NumberOfHotbarSlots + 1, #Slots do -- Only search inventory slots local slot = Slots[i] local hits: any = slot:CheckTerms(terms) table.insert(hitTable, { slot, hits }) slot.Frame.Visible = false slot.Frame.Parent = InventoryFrame end table.sort(hitTable, function(left: any, right: any): boolean return left[2] > right[2] end) ViewingSearchResults = true local hitCount: number = 0 for _, data in ipairs(hitTable) do local slot, hits: any = data[1], data[2] if hits > 0 then slot.Frame.Visible = true slot.Frame.Parent = UIGridFrame slot.Frame.LayoutOrder = NumberOfHotbarSlots + hitCount hitCount = hitCount + 1 end end ScrollingFrame.CanvasPosition = Vector2.new(0, 0) UpdateScrollingFrameCanvasSize() xButton.ZIndex = 3 end local function clearResults(): () if xButton.ZIndex > 0 then ViewingSearchResults = false for i: number = NumberOfHotbarSlots + 1, #Slots do local slot = Slots[i] slot.Frame.LayoutOrder = slot.Index slot.Frame.Parent = UIGridFrame slot.Frame.Visible = true end xButton.ZIndex = 0 end UpdateScrollingFrameCanvasSize() end local function reset(): () clearResults() searchBox.Text = "" end local function onChanged(property: string): () if property == "Text" then local text: string = searchBox.Text if text == "" then searchBox.TextTransparency = TEXT_STROKE_TRANSPARENCY clearResults() elseif text ~= SEARCH_TEXT then searchBox.TextTransparency = 0 search() end xButton.Visible = text ~= "" and text ~= SEARCH_TEXT end end local function focusLost(enterPressed: boolean): () if enterPressed then --TODO: Could optimize search() end end xButton.MouseButton1Click:Connect(reset) searchBox.Changed:Connect(onChanged) searchBox.FocusLost:Connect(focusLost) BackpackScript.StateChanged.Event:Connect(function(isNowOpen: boolean): () -- InventoryIcon:getInstance("iconButton").Modal = isNowOpen -- Allows free mouse movement even in first person if not isNowOpen then reset() end end) HotkeyFns[Enum.KeyCode.Escape.Value] = function(isProcessed: any): () if isProcessed then -- Pressed from within a TextBox reset() end end local function detectGamepad(lastInputType: Enum.UserInputType): () if lastInputType == Enum.UserInputType.Gamepad1 and not UserInputService.VREnabled then searchFrame.Visible = false else searchFrame.Visible = true end end UserInputService.LastInputTypeChanged:Connect(detectGamepad) end -- When menu is opend, disable backpack GuiService.MenuOpened:Connect(function(): () BackpackGui.Enabled = false inventoryIcon:setEnabled(false) end) -- When menu is closed, enable backpack GuiService.MenuClosed:Connect(function(): () BackpackGui.Enabled = true inventoryIcon:setEnabled(true) end) do -- Make the Inventory expand/collapse arrow (unless TopBar) -- selene: allow(unused_variable) local removeHotBarSlot = function(name: string, state: Enum.UserInputState, input: InputObject): () if state ~= Enum.UserInputState.Begin then return end if not GuiService.SelectedObject then return end for i: number = 1, NumberOfHotbarSlots do if Slots[i].Frame == GuiService.SelectedObject and Slots[i].Tool then Slots[i]:MoveToInventory() return end end end local function openClose(): () if not next(Dragging) then -- Only continue if nothing is being dragged InventoryFrame.Visible = not InventoryFrame.Visible local nowOpen: boolean = InventoryFrame.Visible AdjustHotbarFrames() HotbarFrame.Active = not HotbarFrame.Active for i: number = 1, NumberOfHotbarSlots do Slots[i]:SetClickability(not nowOpen) end end if InventoryFrame.Visible then if GamepadEnabled then if GAMEPAD_INPUT_TYPES[UserInputService:GetLastInputType()] then resizeGamepadHintsFrame() gamepadHintsFrame.Visible = not UserInputService.VREnabled end enableGamepadInventoryControl() end if BackpackPanel and VRService.VREnabled then BackpackPanel:SetVisible(true) BackpackPanel:RequestPositionUpdate() end else if GamepadEnabled then gamepadHintsFrame.Visible = false end disableGamepadInventoryControl() end if InventoryFrame.Visible then ContextActionService:BindAction("BackpackRemoveSlot", removeHotBarSlot, false, Enum.KeyCode.ButtonX) else ContextActionService:UnbindAction("BackpackRemoveSlot") end BackpackScript.IsOpen = InventoryFrame.Visible BackpackScript.StateChanged:Fire(InventoryFrame.Visible) end StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.Backpack, false) BackpackScript.OpenClose = openClose -- Exposed end -- Now that we're done building the GUI, we Connect to all the major events -- Wait for the player if LocalPlayer wasn't ready earlier while not Player do task.wait() Player = Players.LocalPlayer end -- Listen to current and all future characters of our player Player.CharacterAdded:Connect(OnCharacterAdded) if Player.Character then OnCharacterAdded(Player.Character) end do -- Hotkey stuff -- Listen to key down UserInputService.InputBegan:Connect(OnInputBegan) -- Listen to ANY TextBox gaining or losing focus, for disabling all hotkeys UserInputService.TextBoxFocused:Connect(function(): () TextBoxFocused = true end) UserInputService.TextBoxFocusReleased:Connect(function(): () TextBoxFocused = false end) -- Manual unequip for HopperBins on drop button pressed HotkeyFns[DROP_HOTKEY_VALUE] = function(): () --NOTE: HopperBin if ActiveHopper then UnequipAllTools() end end -- Listen to keyboard status, for showing/hiding hotkey labels UserInputService.LastInputTypeChanged:Connect(OnUISChanged) OnUISChanged() -- Listen to gamepad status, for allowing gamepad style selection/equip if UserInputService:GetGamepadConnected(Enum.UserInputType.Gamepad1) then gamepadConnected() end UserInputService.GamepadConnected:Connect(function(gamepadEnum: Enum.UserInputType): () if gamepadEnum == Enum.UserInputType.Gamepad1 then gamepadConnected() end end) UserInputService.GamepadDisconnected:Connect(function(gamepadEnum: Enum.UserInputType): () if gamepadEnum == Enum.UserInputType.Gamepad1 then gamepadDisconnected() end end) end -- Sets whether the backpack is enabled or not function BackpackScript:SetBackpackEnabled(Enabled: boolean): () BackpackEnabled = Enabled end -- Returns if the backpack's inventory is open function BackpackScript:IsOpened(): boolean return BackpackScript.IsOpen end -- Returns on if the backpack is enabled or not function BackpackScript:GetBackpackEnabled(): boolean return BackpackEnabled end -- Returns the BindableEvent for when the backpack state changes function BackpackScript:GetStateChangedEvent(): BindableEvent return BackpackScript.StateChanged end -- Update every heartbeat the icon state RunService.Heartbeat:Connect(function(): () OnIconChanged(BackpackEnabled) end) -- Update the transparency of the backpack based on GuiService.PreferredTransparency local function OnPreferredTransparencyChanged(): () local preferredTransparency: number = GuiService.PreferredTransparency BACKGROUND_TRANSPARENCY = BACKGROUND_TRANSPARENCY_DEFAULT * preferredTransparency InventoryFrame.BackgroundTransparency = BACKGROUND_TRANSPARENCY SLOT_LOCKED_TRANSPARENCY = SLOT_LOCKED_TRANSPARENCY_DEFAULT * preferredTransparency for _, slot in ipairs(Slots) do slot.Frame.BackgroundTransparency = SLOT_LOCKED_TRANSPARENCY end SEARCH_BACKGROUND_TRANSPARENCY = SEARCH_BACKGROUND_TRANSPARENCY_DEFAULT * preferredTransparency searchFrame.BackgroundTransparency = SEARCH_BACKGROUND_TRANSPARENCY end GuiService:GetPropertyChangedSignal("PreferredTransparency"):Connect(OnPreferredTransparencyChanged) return BackpackScript
0
0.960077
1
0.960077
game-dev
MEDIA
0.953961
game-dev
0.983075
1
0.983075
Legacy-Visuals-Project/Animatium
4,080
src/main/java/btw/mixces/animatium/mixins/renderer/entity/layer/MixinCapeLayer.java
/** * Animatium * The all-you-could-want legacy animations mod for modern minecraft versions. * Brings back animations from the 1.7/1.8 era and more. * <p> * Copyright (C) 2024-2025 lowercasebtw * Copyright (C) 2024-2025 mixces * Copyright (C) 2024-2025 Contributors to the project retain their copyright * <p> * 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. * <p> * 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. * <p> * 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 btw.mixces.animatium.mixins.renderer.entity.layer; import btw.mixces.animatium.AnimatiumClient; import btw.mixces.animatium.config.AnimatiumConfig; import com.llamalad7.mixinextras.injector.ModifyExpressionValue; import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.model.HumanoidModel; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.entity.layers.CapeLayer; import net.minecraft.client.renderer.entity.state.PlayerRenderState; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(CapeLayer.class) public abstract class MixinCapeLayer { @Shadow @Final private HumanoidModel<PlayerRenderState> model; @ModifyExpressionValue(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/client/renderer/entity/state/PlayerRenderState;FF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/layers/CapeLayer;hasLayer(Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/client/resources/model/EquipmentClientInfo$LayerType;)Z", ordinal = 1)) private boolean animatium$capeChestplateTranslation(boolean original) { if (AnimatiumClient.isEnabled() && !AnimatiumConfig.instance().capeChestplateTranslation) { return false; } else { return original; } } @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/client/renderer/entity/state/PlayerRenderState;FF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/MultiBufferSource;getBuffer(Lnet/minecraft/client/renderer/RenderType;)Lcom/mojang/blaze3d/vertex/VertexConsumer;")) private void animatium$capeSneakPosition(PoseStack poseStack, MultiBufferSource multiBufferSource, int i, PlayerRenderState playerRenderState, float f, float g, CallbackInfo ci) { if (AnimatiumClient.isEnabled() && AnimatiumConfig.instance().capeSneakPosition && playerRenderState.isCrouching) { poseStack.translate(0.0F, playerRenderState.scale * 2.0F / 16.0F, 0.0F); } } @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/client/renderer/entity/state/PlayerRenderState;FF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/HumanoidModel;setupAnim(Lnet/minecraft/client/renderer/entity/state/HumanoidRenderState;)V", shift = At.Shift.AFTER)) private void animatium$capeSwingRotation(PoseStack poseStack, MultiBufferSource multiBufferSource, int i, PlayerRenderState playerRenderState, float f, float g, CallbackInfo ci) { if (AnimatiumClient.isEnabled() && !AnimatiumConfig.instance().capeSwingRotation) { model.body.yRot = 0; } } }
0
0.736571
1
0.736571
game-dev
MEDIA
0.891657
game-dev,graphics-rendering
0.801075
1
0.801075
gkursi/Pulse-client
1,199
src/main/java/xyz/qweru/pulse/client/mixin/mixins/PlayerInteractEntityC2SPacketMixin.java
package xyz.qweru.pulse.client.mixin.mixins; import net.minecraft.network.packet.c2s.play.PlayerInteractBlockC2SPacket; import net.minecraft.network.packet.c2s.play.PlayerInteractEntityC2SPacket; import net.minecraft.util.Hand; import net.minecraft.util.hit.HitResult; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.gen.Invoker; import xyz.qweru.pulse.client.mixin.iinterface.IPlayerInteractEntityC2SPacket; @Mixin(PlayerInteractEntityC2SPacket.class) public class PlayerInteractEntityC2SPacketMixin implements IPlayerInteractEntityC2SPacket { @Mutable @Shadow @Final private int entityId; // @Shadow @Final private PlayerInteractEntityC2SPacket.InteractTypeHandler type; // // @Shadow @Final // static PlayerInteractEntityC2SPacket.InteractTypeHandler ATTACK; @Override public void pulse$setID(int id) { this.entityId = id; } // this is peak code trust me // nvm it doesn't work :( // @Override // public boolean pulse$isAttack() { // return this.type == ATTACK; // } }
0
0.822302
1
0.822302
game-dev
MEDIA
0.956073
game-dev
0.856478
1
0.856478
michael007js/SpectrumForAndroid
2,328
app/src/main/java/com/sss/VisualizerHelper.java
package com.sss; import android.os.Handler; import android.os.Looper; import com.sss.processor.FFTListener; import com.sss.spectrum.AppConstant; import java.util.ArrayList; import java.util.List; @SuppressWarnings("ALL") public class VisualizerHelper { private static VisualizerHelper helper; public static synchronized VisualizerHelper getInstance() { synchronized (VisualizerHelper.class) { if (helper == null) { helper = new VisualizerHelper(); } return helper; } } private List<OnVisualizerEnergyCallBack> onEnergyCallBacks = new ArrayList<>(); private final FFTListener fftListener = new FFTListener() { Handler mainHandler = new Handler(Looper.getMainLooper()); float[] fft; float energy; Runnable runnable = new Runnable() { @Override public void run() { for (int i = 0; i < onEnergyCallBacks.size(); i++) { if (!onEnergyCallBacks.isEmpty() && i <= onEnergyCallBacks.size() - 1) { onEnergyCallBacks.get(i).setWaveData(fft, energy); } } } }; @Override public void onFFTReady(int sampleRateHz, int channelCount, float[] fft) { float energy = 0f; int size = Math.min(fft.length, AppConstant.SAMPLE_SIZE); float[] newData = new float[size]; for (int i = 0; i < size; i++) { //TODO 注意:这里取正数,如果绘制波形图,则不需要取正,后期如果加入波形类频谱则需要对此处改造 float value = Math.max(0, fft[i]) * AppConstant.LAGER_OFFSET; energy += value; newData[i] = value; } this.fft = newData; this.energy = energy; mainHandler.post(runnable); } }; public FFTListener getFftListener() { return fftListener; } public void addCallBack(OnVisualizerEnergyCallBack onEnergyCallBack) { onEnergyCallBacks.add(onEnergyCallBack); } public void removeCallBack(OnVisualizerEnergyCallBack onEnergyCallBack) { onEnergyCallBacks.remove(onEnergyCallBack); } public interface OnVisualizerEnergyCallBack { void setWaveData(float[] data, float totalEnergy); } }
0
0.889227
1
0.889227
game-dev
MEDIA
0.493252
game-dev
0.99245
1
0.99245
RhenaudTheLukark/CreateYourFrisk
6,138
Assets/Tiled2Unity/Scripts/Editor/ImportTiled2Unity.cs
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using System.Xml; using UnityEditor; using UnityEngine; namespace Tiled2Unity { partial class ImportTiled2Unity : IDisposable { private string fullPathToFile = ""; private string pathToTiled2UnityRoot = ""; private string assetPathToTiled2UnityRoot = ""; public ImportTiled2Unity(string file) { this.fullPathToFile = System.IO.Path.GetFullPath(file); // Discover the root of the Tiled2Unity scripts and assets this.pathToTiled2UnityRoot = System.IO.Path.GetDirectoryName(this.fullPathToFile); int index = this.pathToTiled2UnityRoot.LastIndexOf("Tiled2Unity", StringComparison.InvariantCultureIgnoreCase); if (index == -1) { Debug.LogError(String.Format("There is an error with your Tiled2Unity install. Could not find Tiled2Unity folder in {0}", file)); } else { this.pathToTiled2UnityRoot = this.pathToTiled2UnityRoot.Remove(index + "Tiled2Unity".Length); } this.fullPathToFile = this.fullPathToFile.Replace(System.IO.Path.DirectorySeparatorChar, '/'); this.pathToTiled2UnityRoot = this.pathToTiled2UnityRoot.Replace(System.IO.Path.DirectorySeparatorChar, '/'); // Figure out the path from "Assets" to "Tiled2Unity" root folder this.assetPathToTiled2UnityRoot = this.pathToTiled2UnityRoot.Remove(0, Application.dataPath.Count()); this.assetPathToTiled2UnityRoot = "Assets" + this.assetPathToTiled2UnityRoot; } public bool IsTiled2UnityFile() { return this.fullPathToFile.EndsWith(".tiled2unity.xml"); } public bool IsTiled2UnityTexture() { bool startsWith = this.fullPathToFile.Contains("/Tiled2Unity/Textures/"); bool endsWithTxt = this.fullPathToFile.EndsWith(".txt"); return startsWith && !endsWithTxt; } public bool IsTiled2UnityMaterial() { bool startsWith = this.fullPathToFile.Contains("/Tiled2Unity/Materials/"); bool endsWith = this.fullPathToFile.EndsWith(".mat"); return startsWith && endsWith; } public bool IsTiled2UnityWavefrontObj() { bool contains = this.fullPathToFile.Contains("/Tiled2Unity/Meshes/"); bool endsWith = this.fullPathToFile.EndsWith(".obj"); return contains && endsWith; } public bool IsTiled2UnityPrefab() { bool startsWith = this.fullPathToFile.Contains("/Tiled2Unity/Prefabs/"); bool endsWith = this.fullPathToFile.EndsWith(".prefab"); return startsWith && endsWith; } public string GetMeshAssetPath(string mapName, string meshName) { string meshAsset = String.Format("{0}/Meshes/{1}/{2}.obj", this.assetPathToTiled2UnityRoot, mapName, meshName); return meshAsset; } public string MakeMaterialAssetPath(string file, bool isResource) { string name = System.IO.Path.GetFileNameWithoutExtension(file); if (isResource) { return String.Format("{0}/Materials/Resources/{1}.mat", this.assetPathToTiled2UnityRoot, name); } // If we're here then the material is not a resource to be loaded at runtime return String.Format("{0}/Materials/{1}.mat", this.assetPathToTiled2UnityRoot, name); } public string GetExistingMaterialAssetPath(string file) { // The named material may be in a Ressources folder or not so we use the asset database to search string name = System.IO.Path.GetFileNameWithoutExtension(file); string filter = String.Format("t:material {0}", name); string folder = this.assetPathToTiled2UnityRoot + "/Materials"; string[] files = AssetDatabase.FindAssets(filter, new string[] { folder }); foreach (var f in files) { string assetPath = AssetDatabase.GUIDToAssetPath(f); if (String.Compare(Path.GetFileNameWithoutExtension(assetPath), name, true) == 0) { return assetPath; } } return ""; } public TextAsset GetTiled2UnityTextAsset() { string file = this.assetPathToTiled2UnityRoot + "/Tiled2Unity.export.txt"; return AssetDatabase.LoadAssetAtPath(file, typeof(TextAsset)) as TextAsset; } public string GetTextureAssetPath(string filename) { // Keep the extention given (png, tga, etc.) filename = System.IO.Path.GetFileName(filename); string textureAsset = String.Format("{0}/Textures/{1}", this.assetPathToTiled2UnityRoot, filename); return textureAsset; } public string GetPrefabAssetPath(string name, bool isResource, string extraPath) { string prefabAsset = ""; if (isResource) { if (String.IsNullOrEmpty(extraPath)) { // Put the prefab into a "Resources" folder so it can be instantiated through script prefabAsset = String.Format("{0}/Prefabs/Resources/{1}.prefab", this.assetPathToTiled2UnityRoot, name); } else { // Put the prefab into a "Resources/extraPath" folder so it can be instantiated through script prefabAsset = String.Format("{0}/Prefabs/Resources/{1}/{2}.prefab", this.assetPathToTiled2UnityRoot, extraPath, name); } } else { prefabAsset = String.Format("{0}/Prefabs/{1}.prefab", this.assetPathToTiled2UnityRoot, name); } return prefabAsset; } public void Dispose() { } } }
0
0.680217
1
0.680217
game-dev
MEDIA
0.836673
game-dev
0.868949
1
0.868949
magefree/mage
2,007
Mage.Sets/src/mage/cards/e/ErstwhileTrooper.java
package mage.cards.e; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.LimitedTimesPerTurnActivatedAbility; import mage.abilities.costs.common.DiscardTargetCost; import mage.abilities.effects.common.continuous.BoostSourceEffect; import mage.abilities.effects.common.continuous.GainAbilitySourceEffect; import mage.abilities.keyword.TrampleAbility; import mage.constants.SubType; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Zone; import mage.filter.StaticFilters; import mage.target.common.TargetCardInHand; /** * * @author TheElk801 */ public final class ErstwhileTrooper extends CardImpl { public ErstwhileTrooper(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{B}{G}"); this.subtype.add(SubType.ZOMBIE); this.subtype.add(SubType.SOLDIER); this.power = new MageInt(2); this.toughness = new MageInt(2); // Discard a creature card: Erstwhile Trooper gets +2/+2 and gains trample until end of turn. Activate this ability only once each turn. Ability ability = new LimitedTimesPerTurnActivatedAbility( Zone.BATTLEFIELD, new BoostSourceEffect( 2, 2, Duration.EndOfTurn ).setText("{this} gets +2/+2"), new DiscardTargetCost(new TargetCardInHand( StaticFilters.FILTER_CARD_CREATURE_A )) ); ability.addEffect(new GainAbilitySourceEffect( TrampleAbility.getInstance(), Duration.EndOfTurn ).setText("and gains trample until end of turn")); this.addAbility(ability); } private ErstwhileTrooper(final ErstwhileTrooper card) { super(card); } @Override public ErstwhileTrooper copy() { return new ErstwhileTrooper(this); } }
0
0.950494
1
0.950494
game-dev
MEDIA
0.985227
game-dev
0.998146
1
0.998146
FabricMC/fabric
2,381
fabric-events-interaction-v0/src/main/java/net/fabricmc/fabric/api/event/player/AttackBlockCallback.java
/* * Copyright (c) 2016, 2017, 2018, 2019 FabricMC * * 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 net.fabricmc.fabric.api.event.player; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.world.World; import net.fabricmc.fabric.api.event.Event; import net.fabricmc.fabric.api.event.EventFactory; /** * Callback for left-clicking ("attacking") a block. * Is hooked in before the spectator check, so make sure to check for the player's game mode as well! * * <p>On the logical client, the return values have the following meaning: * <ul> * <li>SUCCESS cancels further processing, causes a hand swing, and sends a packet to the server.</li> * <li>CONSUME cancels further processing, and sends a packet to the server. It does NOT cause a hand swing.</li> * <li>PASS falls back to further processing.</li> * <li>FAIL cancels further processing and does not send a packet to the server.</li> * </ul> * * <p>On the logical server, the return values have the following meaning: * <ul> * <li>PASS falls back to further processing.</li> * <li>Any other value cancels further processing.</li> * </ul> */ public interface AttackBlockCallback { Event<AttackBlockCallback> EVENT = EventFactory.createArrayBacked(AttackBlockCallback.class, (listeners) -> (player, world, hand, pos, direction) -> { for (AttackBlockCallback event : listeners) { ActionResult result = event.interact(player, world, hand, pos, direction); if (result != ActionResult.PASS) { return result; } } return ActionResult.PASS; } ); ActionResult interact(PlayerEntity player, World world, Hand hand, BlockPos pos, Direction direction); }
0
0.710098
1
0.710098
game-dev
MEDIA
0.988743
game-dev
0.506188
1
0.506188
Fundynamic/RealBot
56,345
dependencies/hlsdk-old/multiplayer/dmc/dlls/plats.cpp
/*** * * Copyright (c) 1996-2002, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ /* ===== plats.cpp ======================================================== spawn, think, and touch functions for trains, etc */ #include "extdll.h" #include "util.h" #include "cbase.h" #include "trains.h" #include "saverestore.h" static void PlatSpawnInsideTrigger(entvars_t* pevPlatform); #define SF_PLAT_TOGGLE 0x0001 class CBasePlatTrain : public CBaseToggle { public: virtual int ObjectCaps( void ) { return CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } void KeyValue( KeyValueData* pkvd); void Precache( void ); // This is done to fix spawn flag collisions between this class and a derived class virtual BOOL IsTogglePlat( void ) { return (pev->spawnflags & SF_PLAT_TOGGLE) ? TRUE : FALSE; } virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; BYTE m_bMoveSnd; // sound a plat makes while moving BYTE m_bStopSnd; // sound a plat makes when it stops float m_volume; // Sound volume }; TYPEDESCRIPTION CBasePlatTrain::m_SaveData[] = { DEFINE_FIELD( CBasePlatTrain, m_bMoveSnd, FIELD_CHARACTER ), DEFINE_FIELD( CBasePlatTrain, m_bStopSnd, FIELD_CHARACTER ), DEFINE_FIELD( CBasePlatTrain, m_volume, FIELD_FLOAT ), }; IMPLEMENT_SAVERESTORE( CBasePlatTrain, CBaseToggle ); void CBasePlatTrain :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "lip")) { m_flLip = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "wait")) { m_flWait = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "height")) { m_flHeight = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "rotation")) { m_vecFinalAngle.x = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "movesnd")) { m_bMoveSnd = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "stopsnd")) { m_bStopSnd = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "volume")) { m_volume = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else CBaseToggle::KeyValue( pkvd ); } #define noiseMoving noise #define noiseArrived noise1 void CBasePlatTrain::Precache( void ) { // set the plat's "in-motion" sound switch (m_bMoveSnd) { case 0: pev->noiseMoving = MAKE_STRING("common/null.wav"); break; case 1: PRECACHE_SOUND ("plats/bigmove1.wav"); pev->noiseMoving = MAKE_STRING("plats/bigmove1.wav"); break; case 2: PRECACHE_SOUND ("plats/bigmove2.wav"); pev->noiseMoving = MAKE_STRING("plats/bigmove2.wav"); break; case 3: PRECACHE_SOUND ("plats/elevmove1.wav"); pev->noiseMoving = MAKE_STRING("plats/elevmove1.wav"); break; case 4: PRECACHE_SOUND ("plats/elevmove2.wav"); pev->noiseMoving = MAKE_STRING("plats/elevmove2.wav"); break; case 5: PRECACHE_SOUND ("plats/elevmove3.wav"); pev->noiseMoving = MAKE_STRING("plats/elevmove3.wav"); break; case 6: PRECACHE_SOUND ("plats/freightmove1.wav"); pev->noiseMoving = MAKE_STRING("plats/freightmove1.wav"); break; case 7: PRECACHE_SOUND ("plats/freightmove2.wav"); pev->noiseMoving = MAKE_STRING("plats/freightmove2.wav"); break; case 8: PRECACHE_SOUND ("plats/heavymove1.wav"); pev->noiseMoving = MAKE_STRING("plats/heavymove1.wav"); break; case 9: PRECACHE_SOUND ("plats/rackmove1.wav"); pev->noiseMoving = MAKE_STRING("plats/rackmove1.wav"); break; case 10: PRECACHE_SOUND ("plats/railmove1.wav"); pev->noiseMoving = MAKE_STRING("plats/railmove1.wav"); break; case 11: PRECACHE_SOUND ("plats/squeekmove1.wav"); pev->noiseMoving = MAKE_STRING("plats/squeekmove1.wav"); break; case 12: PRECACHE_SOUND ("plats/talkmove1.wav"); pev->noiseMoving = MAKE_STRING("plats/talkmove1.wav"); break; case 13: PRECACHE_SOUND ("plats/talkmove2.wav"); pev->noiseMoving = MAKE_STRING("plats/talkmove2.wav"); break; default: pev->noiseMoving = MAKE_STRING("common/null.wav"); break; } // set the plat's 'reached destination' stop sound switch (m_bStopSnd) { case 0: pev->noiseArrived = MAKE_STRING("common/null.wav"); break; case 1: PRECACHE_SOUND ("plats/bigstop1.wav"); pev->noiseArrived = MAKE_STRING("plats/bigstop1.wav"); break; case 2: PRECACHE_SOUND ("plats/bigstop2.wav"); pev->noiseArrived = MAKE_STRING("plats/bigstop2.wav"); break; case 3: PRECACHE_SOUND ("plats/freightstop1.wav"); pev->noiseArrived = MAKE_STRING("plats/freightstop1.wav"); break; case 4: PRECACHE_SOUND ("plats/heavystop2.wav"); pev->noiseArrived = MAKE_STRING("plats/heavystop2.wav"); break; case 5: PRECACHE_SOUND ("plats/rackstop1.wav"); pev->noiseArrived = MAKE_STRING("plats/rackstop1.wav"); break; case 6: PRECACHE_SOUND ("plats/railstop1.wav"); pev->noiseArrived = MAKE_STRING("plats/railstop1.wav"); break; case 7: PRECACHE_SOUND ("plats/squeekstop1.wav"); pev->noiseArrived = MAKE_STRING("plats/squeekstop1.wav"); break; case 8: PRECACHE_SOUND ("plats/talkstop1.wav"); pev->noiseArrived = MAKE_STRING("plats/talkstop1.wav"); break; default: pev->noiseArrived = MAKE_STRING("common/null.wav"); break; } } // //====================== PLAT code ==================================================== // #define noiseMovement noise #define noiseStopMoving noise1 class CFuncPlat : public CBasePlatTrain { public: void Spawn( void ); void Precache( void ); void Setup( void ); virtual void Blocked( CBaseEntity *pOther ); void EXPORT PlatUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void EXPORT CallGoDown( void ) { GoDown(); } void EXPORT CallHitTop( void ) { HitTop(); } void EXPORT CallHitBottom( void ) { HitBottom(); } virtual void GoUp( void ); virtual void GoDown( void ); virtual void HitTop( void ); virtual void HitBottom( void ); }; LINK_ENTITY_TO_CLASS( func_plat, CFuncPlat ); // UNDONE: Need to save this!!! It needs class & linkage class CPlatTrigger : public CBaseEntity { public: virtual int ObjectCaps( void ) { return (CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION) | FCAP_DONT_SAVE; } void SpawnInsideTrigger( CFuncPlat *pPlatform ); void Touch( CBaseEntity *pOther ); CFuncPlat *m_pPlatform; }; /*QUAKED func_plat (0 .5 .8) ? PLAT_LOW_TRIGGER speed default 150 Plats are always drawn in the extended position, so they will light correctly. If the plat is the target of another trigger or button, it will start out disabled in the extended position until it is trigger, when it will lower and become a normal plat. If the "height" key is set, that will determine the amount the plat moves, instead of being implicitly determined by the model's height. Set "sounds" to one of the following: 1) base fast 2) chain slow */ void CFuncPlat :: Setup( void ) { //pev->noiseMovement = MAKE_STRING("plats/platmove1.wav"); //pev->noiseStopMoving = MAKE_STRING("plats/platstop1.wav"); if (m_flTLength == 0) m_flTLength = 80; if (m_flTWidth == 0) m_flTWidth = 10; pev->angles = g_vecZero; pev->solid = SOLID_BSP; pev->movetype = MOVETYPE_PUSH; UTIL_SetOrigin(pev, pev->origin); // set size and link into world UTIL_SetSize(pev, pev->mins, pev->maxs); SET_MODEL(ENT(pev), STRING(pev->model) ); // vecPosition1 is the top position, vecPosition2 is the bottom m_vecPosition1 = pev->origin; m_vecPosition2 = pev->origin; if (m_flHeight != 0) m_vecPosition2.z = pev->origin.z - m_flHeight; else m_vecPosition2.z = pev->origin.z - pev->size.z + 8; if (pev->speed == 0) pev->speed = 150; if ( m_volume == 0 ) m_volume = 0.85; } void CFuncPlat :: Precache( ) { CBasePlatTrain::Precache(); //PRECACHE_SOUND("plats/platmove1.wav"); //PRECACHE_SOUND("plats/platstop1.wav"); if ( !IsTogglePlat() ) PlatSpawnInsideTrigger( pev ); // the "start moving" trigger } void CFuncPlat :: Spawn( ) { Setup(); Precache(); // If this platform is the target of some button, it starts at the TOP position, // and is brought down by that button. Otherwise, it starts at BOTTOM. if ( !FStringNull(pev->targetname) ) { UTIL_SetOrigin (pev, m_vecPosition1); m_toggle_state = TS_AT_TOP; SetUse( PlatUse ); } else { UTIL_SetOrigin (pev, m_vecPosition2); m_toggle_state = TS_AT_BOTTOM; } } static void PlatSpawnInsideTrigger(entvars_t* pevPlatform) { GetClassPtr( (CPlatTrigger *)NULL)->SpawnInsideTrigger( GetClassPtr( (CFuncPlat *)pevPlatform ) ); } // // Create a trigger entity for a platform. // void CPlatTrigger :: SpawnInsideTrigger( CFuncPlat *pPlatform ) { m_pPlatform = pPlatform; // Create trigger entity, "point" it at the owning platform, give it a touch method pev->solid = SOLID_TRIGGER; pev->movetype = MOVETYPE_NONE; pev->origin = pPlatform->pev->origin; // Establish the trigger field's size Vector vecTMin = m_pPlatform->pev->mins + Vector ( 25 , 25 , 0 ); Vector vecTMax = m_pPlatform->pev->maxs + Vector ( 25 , 25 , 8 ); vecTMin.z = vecTMax.z - ( m_pPlatform->m_vecPosition1.z - m_pPlatform->m_vecPosition2.z + 8 ); if (m_pPlatform->pev->size.x <= 50) { vecTMin.x = (m_pPlatform->pev->mins.x + m_pPlatform->pev->maxs.x) / 2; vecTMax.x = vecTMin.x + 1; } if (m_pPlatform->pev->size.y <= 50) { vecTMin.y = (m_pPlatform->pev->mins.y + m_pPlatform->pev->maxs.y) / 2; vecTMax.y = vecTMin.y + 1; } UTIL_SetSize ( pev, vecTMin, vecTMax ); } // // When the platform's trigger field is touched, the platform ??? // void CPlatTrigger :: Touch( CBaseEntity *pOther ) { // Ignore touches by non-players entvars_t* pevToucher = pOther->pev; if ( !FClassnameIs (pevToucher, "player") ) return; // Ignore touches by corpses if (!pOther->IsAlive()) return; // Make linked platform go up/down. if (m_pPlatform->m_toggle_state == TS_AT_BOTTOM) m_pPlatform->GoUp(); else if (m_pPlatform->m_toggle_state == TS_AT_TOP) m_pPlatform->pev->nextthink = m_pPlatform->pev->ltime + 1;// delay going down } // // Used by SUB_UseTargets, when a platform is the target of a button. // Start bringing platform down. // void CFuncPlat :: PlatUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( IsTogglePlat() ) { // Top is off, bottom is on BOOL on = (m_toggle_state == TS_AT_BOTTOM) ? TRUE : FALSE; if ( !ShouldToggle( useType, on ) ) return; if (m_toggle_state == TS_AT_TOP) GoDown(); else if ( m_toggle_state == TS_AT_BOTTOM ) GoUp(); } else { SetUse( NULL ); if (m_toggle_state == TS_AT_TOP) GoDown(); } } // // Platform is at top, now starts moving down. // void CFuncPlat :: GoDown( void ) { if(pev->noiseMovement) EMIT_SOUND(ENT(pev), CHAN_STATIC, (char*)STRING(pev->noiseMovement), m_volume, ATTN_NORM); ASSERT(m_toggle_state == TS_AT_TOP || m_toggle_state == TS_GOING_UP); m_toggle_state = TS_GOING_DOWN; SetMoveDone(CallHitBottom); LinearMove(m_vecPosition2, pev->speed); } // // Platform has hit bottom. Stops and waits forever. // void CFuncPlat :: HitBottom( void ) { if(pev->noiseMovement) STOP_SOUND(ENT(pev), CHAN_STATIC, (char*)STRING(pev->noiseMovement)); if (pev->noiseStopMoving) EMIT_SOUND(ENT(pev), CHAN_WEAPON, (char*)STRING(pev->noiseStopMoving), m_volume, ATTN_NORM); ASSERT(m_toggle_state == TS_GOING_DOWN); m_toggle_state = TS_AT_BOTTOM; } // // Platform is at bottom, now starts moving up // void CFuncPlat :: GoUp( void ) { if (pev->noiseMovement) EMIT_SOUND(ENT(pev), CHAN_STATIC, (char*)STRING(pev->noiseMovement), m_volume, ATTN_NORM); ASSERT(m_toggle_state == TS_AT_BOTTOM || m_toggle_state == TS_GOING_DOWN); m_toggle_state = TS_GOING_UP; SetMoveDone(CallHitTop); LinearMove(m_vecPosition1, pev->speed); } // // Platform has hit top. Pauses, then starts back down again. // void CFuncPlat :: HitTop( void ) { if(pev->noiseMovement) STOP_SOUND(ENT(pev), CHAN_STATIC, (char*)STRING(pev->noiseMovement)); if (pev->noiseStopMoving) EMIT_SOUND(ENT(pev), CHAN_WEAPON, (char*)STRING(pev->noiseStopMoving), m_volume, ATTN_NORM); ASSERT(m_toggle_state == TS_GOING_UP); m_toggle_state = TS_AT_TOP; if ( !IsTogglePlat() ) { // After a delay, the platform will automatically start going down again. SetThink( CallGoDown ); pev->nextthink = pev->ltime + 3; } } void CFuncPlat :: Blocked( CBaseEntity *pOther ) { ALERT( at_aiconsole, "%s Blocked by %s\n", STRING(pev->classname), STRING(pOther->pev->classname) ); // Hurt the blocker a little pOther->TakeDamage(pev, pev, 1, DMG_CRUSH); if(pev->noiseMovement) STOP_SOUND(ENT(pev), CHAN_STATIC, (char*)STRING(pev->noiseMovement)); // Send the platform back where it came from ASSERT(m_toggle_state == TS_GOING_UP || m_toggle_state == TS_GOING_DOWN); if (m_toggle_state == TS_GOING_UP) GoDown(); else if (m_toggle_state == TS_GOING_DOWN) GoUp (); } class CFuncPlatRot : public CFuncPlat { public: void Spawn( void ); void SetupRotation( void ); virtual void GoUp( void ); virtual void GoDown( void ); virtual void HitTop( void ); virtual void HitBottom( void ); void RotMove( Vector &destAngle, float time ); virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; Vector m_end, m_start; }; LINK_ENTITY_TO_CLASS( func_platrot, CFuncPlatRot ); TYPEDESCRIPTION CFuncPlatRot::m_SaveData[] = { DEFINE_FIELD( CFuncPlatRot, m_end, FIELD_VECTOR ), DEFINE_FIELD( CFuncPlatRot, m_start, FIELD_VECTOR ), }; IMPLEMENT_SAVERESTORE( CFuncPlatRot, CFuncPlat ); void CFuncPlatRot :: SetupRotation( void ) { if ( m_vecFinalAngle.x != 0 ) // This plat rotates too! { CBaseToggle :: AxisDir( pev ); m_start = pev->angles; m_end = pev->angles + pev->movedir * m_vecFinalAngle.x; } else { m_start = g_vecZero; m_end = g_vecZero; } if ( !FStringNull(pev->targetname) ) // Start at top { pev->angles = m_end; } } void CFuncPlatRot :: Spawn( void ) { CFuncPlat :: Spawn(); SetupRotation(); } void CFuncPlatRot :: GoDown( void ) { CFuncPlat :: GoDown(); RotMove( m_start, pev->nextthink - pev->ltime ); } // // Platform has hit bottom. Stops and waits forever. // void CFuncPlatRot :: HitBottom( void ) { CFuncPlat :: HitBottom(); pev->avelocity = g_vecZero; pev->angles = m_start; } // // Platform is at bottom, now starts moving up // void CFuncPlatRot :: GoUp( void ) { CFuncPlat :: GoUp(); RotMove( m_end, pev->nextthink - pev->ltime ); } // // Platform has hit top. Pauses, then starts back down again. // void CFuncPlatRot :: HitTop( void ) { CFuncPlat :: HitTop(); pev->avelocity = g_vecZero; pev->angles = m_end; } void CFuncPlatRot :: RotMove( Vector &destAngle, float time ) { // set destdelta to the vector needed to move Vector vecDestDelta = destAngle - pev->angles; // Travel time is so short, we're practically there already; so make it so. if ( time >= 0.1) pev->avelocity = vecDestDelta / time; else { pev->avelocity = vecDestDelta; pev->nextthink = pev->ltime + 1; } } // //====================== TRAIN code ================================================== // class CFuncTrain : public CBasePlatTrain { public: void Spawn( void ); void Precache( void ); void Activate( void ); void OverrideReset( void ); void Blocked( CBaseEntity *pOther ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void KeyValue( KeyValueData *pkvd ); void EXPORT Wait( void ); void EXPORT Next( void ); virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; entvars_t *m_pevCurrentTarget; int m_sounds; BOOL m_activated; }; LINK_ENTITY_TO_CLASS( func_train, CFuncTrain ); TYPEDESCRIPTION CFuncTrain::m_SaveData[] = { DEFINE_FIELD( CFuncTrain, m_sounds, FIELD_INTEGER ), DEFINE_FIELD( CFuncTrain, m_pevCurrentTarget, FIELD_EVARS ), DEFINE_FIELD( CFuncTrain, m_activated, FIELD_BOOLEAN ), }; IMPLEMENT_SAVERESTORE( CFuncTrain, CBasePlatTrain ); void CFuncTrain :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "sounds")) { m_sounds = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else CBasePlatTrain::KeyValue( pkvd ); } void CFuncTrain :: Blocked( CBaseEntity *pOther ) { if ( gpGlobals->time < m_flActivateFinished) return; m_flActivateFinished = gpGlobals->time + 0.5; pOther->TakeDamage(pev, pev, pev->dmg, DMG_CRUSH); } void CFuncTrain :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( pev->spawnflags & SF_TRAIN_WAIT_RETRIGGER ) { // Move toward my target pev->spawnflags &= ~SF_TRAIN_WAIT_RETRIGGER; Next(); } else { pev->spawnflags |= SF_TRAIN_WAIT_RETRIGGER; // Pop back to last target if it's available if ( pev->enemy ) pev->target = pev->enemy->v.targetname; pev->nextthink = 0; pev->velocity = g_vecZero; if ( pev->noiseStopMoving ) EMIT_SOUND (ENT(pev), CHAN_VOICE, (char*)STRING(pev->noiseStopMoving), m_volume, ATTN_NORM); } } void CFuncTrain :: Wait( void ) { // Fire the pass target if there is one if ( m_pevCurrentTarget->message ) { FireTargets( STRING(m_pevCurrentTarget->message), this, this, USE_TOGGLE, 0 ); if ( FBitSet( m_pevCurrentTarget->spawnflags, SF_CORNER_FIREONCE ) ) m_pevCurrentTarget->message = 0; } // need pointer to LAST target. if ( FBitSet (m_pevCurrentTarget->spawnflags , SF_TRAIN_WAIT_RETRIGGER ) || ( pev->spawnflags & SF_TRAIN_WAIT_RETRIGGER ) ) { pev->spawnflags |= SF_TRAIN_WAIT_RETRIGGER; // clear the sound channel. if ( pev->noiseMovement ) STOP_SOUND( edict(), CHAN_STATIC, (char*)STRING(pev->noiseMovement) ); if ( pev->noiseStopMoving ) EMIT_SOUND (ENT(pev), CHAN_VOICE, (char*)STRING(pev->noiseStopMoving), m_volume, ATTN_NORM); pev->nextthink = 0; return; } // ALERT ( at_console, "%f\n", m_flWait ); if (m_flWait != 0) {// -1 wait will wait forever! pev->nextthink = pev->ltime + m_flWait; if ( pev->noiseMovement ) STOP_SOUND( edict(), CHAN_STATIC, (char*)STRING(pev->noiseMovement) ); if ( pev->noiseStopMoving ) EMIT_SOUND (ENT(pev), CHAN_VOICE, (char*)STRING(pev->noiseStopMoving), m_volume, ATTN_NORM); SetThink( Next ); } else { Next();// do it RIGHT now! } } // // Train next - path corner needs to change to next target // void CFuncTrain :: Next( void ) { CBaseEntity *pTarg; // now find our next target pTarg = GetNextTarget(); if ( !pTarg ) { if ( pev->noiseMovement ) STOP_SOUND( edict(), CHAN_STATIC, (char*)STRING(pev->noiseMovement) ); // Play stop sound if ( pev->noiseStopMoving ) EMIT_SOUND (ENT(pev), CHAN_VOICE, (char*)STRING(pev->noiseStopMoving), m_volume, ATTN_NORM); return; } // Save last target in case we need to find it again pev->message = pev->target; pev->target = pTarg->pev->target; m_flWait = pTarg->GetDelay(); if ( m_pevCurrentTarget && m_pevCurrentTarget->speed != 0 ) {// don't copy speed from target if it is 0 (uninitialized) pev->speed = m_pevCurrentTarget->speed; ALERT( at_aiconsole, "Train %s speed to %4.2f\n", STRING(pev->targetname), pev->speed ); } m_pevCurrentTarget = pTarg->pev;// keep track of this since path corners change our target for us. pev->enemy = pTarg->edict();//hack if(FBitSet(m_pevCurrentTarget->spawnflags, SF_CORNER_TELEPORT)) { // Path corner has indicated a teleport to the next corner. SetBits(pev->effects, EF_NOINTERP); UTIL_SetOrigin(pev, pTarg->pev->origin - (pev->mins + pev->maxs)* 0.5); Wait(); // Get on with doing the next path corner. } else { // Normal linear move. // CHANGED this from CHAN_VOICE to CHAN_STATIC around OEM beta time because trains should // use CHAN_STATIC for their movement sounds to prevent sound field problems. // this is not a hack or temporary fix, this is how things should be. (sjb). if ( pev->noiseMovement ) STOP_SOUND( edict(), CHAN_STATIC, (char*)STRING(pev->noiseMovement) ); if ( pev->noiseMovement ) EMIT_SOUND (ENT(pev), CHAN_STATIC, (char*)STRING(pev->noiseMovement), m_volume, ATTN_NORM); ClearBits(pev->effects, EF_NOINTERP); SetMoveDone( Wait ); LinearMove (pTarg->pev->origin - (pev->mins + pev->maxs)* 0.5, pev->speed); } } void CFuncTrain :: Activate( void ) { // Not yet active, so teleport to first target if ( !m_activated ) { m_activated = TRUE; entvars_t *pevTarg = VARS( FIND_ENTITY_BY_TARGETNAME (NULL, STRING(pev->target) ) ); pev->target = pevTarg->target; m_pevCurrentTarget = pevTarg;// keep track of this since path corners change our target for us. UTIL_SetOrigin (pev, pevTarg->origin - (pev->mins + pev->maxs) * 0.5 ); if ( FStringNull(pev->targetname) ) { // not triggered, so start immediately pev->nextthink = pev->ltime + 0.1; SetThink( Next ); } else pev->spawnflags |= SF_TRAIN_WAIT_RETRIGGER; } } /*QUAKED func_train (0 .5 .8) ? Trains are moving platforms that players can ride. The targets origin specifies the min point of the train at each corner. The train spawns at the first target it is pointing at. If the train is the target of a button or trigger, it will not begin moving until activated. speed default 100 dmg default 2 sounds 1) ratchet metal */ void CFuncTrain :: Spawn( void ) { Precache(); if (pev->speed == 0) pev->speed = 100; if ( FStringNull(pev->target) ) ALERT(at_console, "FuncTrain with no target"); if (pev->dmg == 0) pev->dmg = 2; pev->movetype = MOVETYPE_PUSH; if ( FBitSet (pev->spawnflags, SF_TRACKTRAIN_PASSABLE) ) pev->solid = SOLID_NOT; else pev->solid = SOLID_BSP; SET_MODEL( ENT(pev), STRING(pev->model) ); UTIL_SetSize (pev, pev->mins, pev->maxs); UTIL_SetOrigin(pev, pev->origin); m_activated = FALSE; if ( m_volume == 0 ) m_volume = 0.85; } void CFuncTrain::Precache( void ) { CBasePlatTrain::Precache(); #if 0 // obsolete // otherwise use preset sound switch (m_sounds) { case 0: pev->noise = 0; pev->noise1 = 0; break; case 1: PRECACHE_SOUND ("plats/train2.wav"); PRECACHE_SOUND ("plats/train1.wav"); pev->noise = MAKE_STRING("plats/train2.wav"); pev->noise1 = MAKE_STRING("plats/train1.wav"); break; case 2: PRECACHE_SOUND ("plats/platmove1.wav"); PRECACHE_SOUND ("plats/platstop1.wav"); pev->noise = MAKE_STRING("plats/platstop1.wav"); pev->noise1 = MAKE_STRING("plats/platmove1.wav"); break; } #endif } void CFuncTrain::OverrideReset( void ) { CBaseEntity *pTarg; // Are we moving? if ( pev->velocity != g_vecZero && pev->nextthink != 0 ) { pev->target = pev->message; // now find our next target pTarg = GetNextTarget(); if ( !pTarg ) { pev->nextthink = 0; pev->velocity = g_vecZero; } else // Keep moving for 0.1 secs, then find path_corner again and restart { SetThink( Next ); pev->nextthink = pev->ltime + 0.1; } } } // --------------------------------------------------------------------- // // Track Train // // --------------------------------------------------------------------- TYPEDESCRIPTION CFuncTrackTrain::m_SaveData[] = { DEFINE_FIELD( CFuncTrackTrain, m_ppath, FIELD_CLASSPTR ), DEFINE_FIELD( CFuncTrackTrain, m_length, FIELD_FLOAT ), DEFINE_FIELD( CFuncTrackTrain, m_height, FIELD_FLOAT ), DEFINE_FIELD( CFuncTrackTrain, m_speed, FIELD_FLOAT ), DEFINE_FIELD( CFuncTrackTrain, m_dir, FIELD_FLOAT ), DEFINE_FIELD( CFuncTrackTrain, m_startSpeed, FIELD_FLOAT ), DEFINE_FIELD( CFuncTrackTrain, m_controlMins, FIELD_VECTOR ), DEFINE_FIELD( CFuncTrackTrain, m_controlMaxs, FIELD_VECTOR ), DEFINE_FIELD( CFuncTrackTrain, m_sounds, FIELD_INTEGER ), DEFINE_FIELD( CFuncTrackTrain, m_flVolume, FIELD_FLOAT ), DEFINE_FIELD( CFuncTrackTrain, m_flBank, FIELD_FLOAT ), DEFINE_FIELD( CFuncTrackTrain, m_oldSpeed, FIELD_FLOAT ), }; IMPLEMENT_SAVERESTORE( CFuncTrackTrain, CBaseEntity ); LINK_ENTITY_TO_CLASS( func_tracktrain, CFuncTrackTrain ); void CFuncTrackTrain :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "wheels")) { m_length = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "height")) { m_height = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "startspeed")) { m_startSpeed = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "sounds")) { m_sounds = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "volume")) { m_flVolume = (float) (atoi(pkvd->szValue)); m_flVolume *= 0.1; pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "bank")) { m_flBank = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else CBaseEntity::KeyValue( pkvd ); } void CFuncTrackTrain :: NextThink( float thinkTime, BOOL alwaysThink ) { if ( alwaysThink ) pev->flags |= FL_ALWAYSTHINK; else pev->flags &= ~FL_ALWAYSTHINK; pev->nextthink = thinkTime; } void CFuncTrackTrain :: Blocked( CBaseEntity *pOther ) { entvars_t *pevOther = pOther->pev; // Blocker is on-ground on the train if ( FBitSet( pevOther->flags, FL_ONGROUND ) && VARS(pevOther->groundentity) == pev ) { float deltaSpeed = fabs(pev->speed); if ( deltaSpeed > 50 ) deltaSpeed = 50; if ( !pevOther->velocity.z ) pevOther->velocity.z += deltaSpeed; return; } else pevOther->velocity = (pevOther->origin - pev->origin ).Normalize() * pev->dmg; ALERT( at_aiconsole, "TRAIN(%s): Blocked by %s (dmg:%.2f)\n", STRING(pev->targetname), STRING(pOther->pev->classname), pev->dmg ); if ( pev->dmg <= 0 ) return; // we can't hurt this thing, so we're not concerned with it pOther->TakeDamage(pev, pev, pev->dmg, DMG_CRUSH); } void CFuncTrackTrain :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( useType != USE_SET ) { if ( !ShouldToggle( useType, (pev->speed != 0) ) ) return; if ( pev->speed == 0 ) { pev->speed = m_speed * m_dir; Next(); } else { pev->speed = 0; pev->velocity = g_vecZero; pev->avelocity = g_vecZero; StopSound(); SetThink( NULL ); } } else { float delta = value; delta = ((int)(pev->speed * 4) / (int)m_speed)*0.25 + 0.25 * delta; if ( delta > 1 ) delta = 1; else if ( delta < -1 ) delta = -1; if ( pev->spawnflags & SF_TRACKTRAIN_FORWARDONLY ) { if ( delta < 0 ) delta = 0; } pev->speed = m_speed * delta; Next(); ALERT( at_aiconsole, "TRAIN(%s), speed to %.2f\n", STRING(pev->targetname), pev->speed ); } } static float Fix( float angle ) { while ( angle < 0 ) angle += 360; while ( angle > 360 ) angle -= 360; return angle; } static void FixupAngles( Vector &v ) { v.x = Fix( v.x ); v.y = Fix( v.y ); v.z = Fix( v.z ); } #define TRAIN_STARTPITCH 60 #define TRAIN_MAXPITCH 200 #define TRAIN_MAXSPEED 1000 // approx max speed for sound pitch calculation void CFuncTrackTrain :: StopSound( void ) { // if sound playing, stop it if (m_soundPlaying && pev->noise) { unsigned short us_encode; unsigned short us_sound = ( ( unsigned short )( m_sounds ) & 0x0007 ) << 12; us_encode = us_sound; PLAYBACK_EVENT_FULL( FEV_RELIABLE | FEV_UPDATE, edict(), m_usAdjustPitch, 0.0, (float *)&g_vecZero, (float *)&g_vecZero, 0.0, 0.0, us_encode, 0, 1, 0 ); /* STOP_SOUND(ENT(pev), CHAN_STATIC, (char*)STRING(pev->noise)); */ EMIT_SOUND_DYN(ENT(pev), CHAN_ITEM, "plats/ttrain_brake1.wav", m_flVolume, ATTN_NORM, 0, 100); } m_soundPlaying = 0; } // update pitch based on speed, start sound if not playing // NOTE: when train goes through transition, m_soundPlaying should go to 0, // which will cause the looped sound to restart. void CFuncTrackTrain :: UpdateSound( void ) { float flpitch; if (!pev->noise) return; flpitch = TRAIN_STARTPITCH + (abs(pev->speed) * (TRAIN_MAXPITCH - TRAIN_STARTPITCH) / TRAIN_MAXSPEED); if (!m_soundPlaying) { // play startup sound for train EMIT_SOUND_DYN(ENT(pev), CHAN_ITEM, "plats/ttrain_start1.wav", m_flVolume, ATTN_NORM, 0, 100); EMIT_SOUND_DYN(ENT(pev), CHAN_STATIC, (char*)STRING(pev->noise), m_flVolume, ATTN_NORM, 0, (int) flpitch); m_soundPlaying = 1; } else { /* // update pitch EMIT_SOUND_DYN(ENT(pev), CHAN_STATIC, (char*)STRING(pev->noise), m_flVolume, ATTN_NORM, SND_CHANGE_PITCH, (int) flpitch); */ // volume 0.0 - 1.0 - 6 bits // m_sounds 3 bits // flpitch = 6 bits // 15 bits total unsigned short us_encode; unsigned short us_sound = ( ( unsigned short )( m_sounds ) & 0x0007 ) << 12; unsigned short us_pitch = ( ( unsigned short )( flpitch / 10.0 ) & 0x003f ) << 6; unsigned short us_volume = ( ( unsigned short )( m_flVolume * 40.0 ) & 0x003f ); us_encode = us_sound | us_pitch | us_volume; PLAYBACK_EVENT_FULL( FEV_RELIABLE | FEV_UPDATE, edict(), m_usAdjustPitch, 0.0, (float *)&g_vecZero, (float *)&g_vecZero, 0.0, 0.0, us_encode, 0, 0, 0 ); } } void CFuncTrackTrain :: Next( void ) { float time = 0.5; if ( !pev->speed ) { ALERT( at_aiconsole, "TRAIN(%s): Speed is 0\n", STRING(pev->targetname) ); StopSound(); return; } // if ( !m_ppath ) // m_ppath = CPathTrack::Instance(FIND_ENTITY_BY_TARGETNAME( NULL, STRING(pev->target) )); if ( !m_ppath ) { ALERT( at_aiconsole, "TRAIN(%s): Lost path\n", STRING(pev->targetname) ); StopSound(); return; } UpdateSound(); Vector nextPos = pev->origin; nextPos.z -= m_height; CPathTrack *pnext = m_ppath->LookAhead( &nextPos, pev->speed * 0.1, 1 ); nextPos.z += m_height; pev->velocity = (nextPos - pev->origin) * 10; Vector nextFront = pev->origin; nextFront.z -= m_height; if ( m_length > 0 ) m_ppath->LookAhead( &nextFront, m_length, 0 ); else m_ppath->LookAhead( &nextFront, 100, 0 ); nextFront.z += m_height; Vector delta = nextFront - pev->origin; Vector angles = UTIL_VecToAngles( delta ); // The train actually points west angles.y += 180; // !!! All of this crap has to be done to make the angles not wrap around, revisit this. FixupAngles( angles ); FixupAngles( pev->angles ); if ( !pnext || (delta.x == 0 && delta.y == 0) ) angles = pev->angles; float vy, vx; if ( !(pev->spawnflags & SF_TRACKTRAIN_NOPITCH) ) vx = UTIL_AngleDistance( angles.x, pev->angles.x ); else vx = 0; vy = UTIL_AngleDistance( angles.y, pev->angles.y ); pev->avelocity.y = vy * 10; pev->avelocity.x = vx * 10; if ( m_flBank != 0 ) { if ( pev->avelocity.y < -5 ) pev->avelocity.z = UTIL_AngleDistance( UTIL_ApproachAngle( -m_flBank, pev->angles.z, m_flBank*2 ), pev->angles.z); else if ( pev->avelocity.y > 5 ) pev->avelocity.z = UTIL_AngleDistance( UTIL_ApproachAngle( m_flBank, pev->angles.z, m_flBank*2 ), pev->angles.z); else pev->avelocity.z = UTIL_AngleDistance( UTIL_ApproachAngle( 0, pev->angles.z, m_flBank*4 ), pev->angles.z) * 4; } if ( pnext ) { if ( pnext != m_ppath ) { CPathTrack *pFire; if ( pev->speed >= 0 ) pFire = pnext; else pFire = m_ppath; m_ppath = pnext; // Fire the pass target if there is one if ( pFire->pev->message ) { FireTargets( STRING(pFire->pev->message), this, this, USE_TOGGLE, 0 ); if ( FBitSet( pFire->pev->spawnflags, SF_PATH_FIREONCE ) ) pFire->pev->message = 0; } if ( pFire->pev->spawnflags & SF_PATH_DISABLE_TRAIN ) pev->spawnflags |= SF_TRACKTRAIN_NOCONTROL; // Don't override speed if under user control if ( pev->spawnflags & SF_TRACKTRAIN_NOCONTROL ) { if ( pFire->pev->speed != 0 ) {// don't copy speed from target if it is 0 (uninitialized) pev->speed = pFire->pev->speed; ALERT( at_aiconsole, "TrackTrain %s speed to %4.2f\n", STRING(pev->targetname), pev->speed ); } } } SetThink( Next ); NextThink( pev->ltime + time, TRUE ); } else // end of path, stop { StopSound(); pev->velocity = (nextPos - pev->origin); pev->avelocity = g_vecZero; float distance = pev->velocity.Length(); m_oldSpeed = pev->speed; pev->speed = 0; // Move to the dead end // Are we there yet? if ( distance > 0 ) { // no, how long to get there? time = distance / m_oldSpeed; pev->velocity = pev->velocity * (m_oldSpeed / distance); SetThink( DeadEnd ); NextThink( pev->ltime + time, FALSE ); } else { DeadEnd(); } } } void CFuncTrackTrain::DeadEnd( void ) { // Fire the dead-end target if there is one CPathTrack *pTrack, *pNext; pTrack = m_ppath; ALERT( at_aiconsole, "TRAIN(%s): Dead end ", STRING(pev->targetname) ); // Find the dead end path node // HACKHACK -- This is bugly, but the train can actually stop moving at a different node depending on it's speed // so we have to traverse the list to it's end. if ( pTrack ) { if ( m_oldSpeed < 0 ) { do { pNext = pTrack->ValidPath( pTrack->GetPrevious(), TRUE ); if ( pNext ) pTrack = pNext; } while ( pNext ); } else { do { pNext = pTrack->ValidPath( pTrack->GetNext(), TRUE ); if ( pNext ) pTrack = pNext; } while ( pNext ); } } pev->velocity = g_vecZero; pev->avelocity = g_vecZero; if ( pTrack ) { ALERT( at_aiconsole, "at %s\n", STRING(pTrack->pev->targetname) ); if ( pTrack->pev->netname ) FireTargets( STRING(pTrack->pev->netname), this, this, USE_TOGGLE, 0 ); } else ALERT( at_aiconsole, "\n" ); } void CFuncTrackTrain :: SetControls( entvars_t *pevControls ) { Vector offset = pevControls->origin - pev->oldorigin; m_controlMins = pevControls->mins + offset; m_controlMaxs = pevControls->maxs + offset; } BOOL CFuncTrackTrain :: OnControls( entvars_t *pevTest ) { Vector offset = pevTest->origin - pev->origin; if ( pev->spawnflags & SF_TRACKTRAIN_NOCONTROL ) return FALSE; // Transform offset into local coordinates UTIL_MakeVectors( pev->angles ); Vector local; local.x = DotProduct( offset, gpGlobals->v_forward ); local.y = -DotProduct( offset, gpGlobals->v_right ); local.z = DotProduct( offset, gpGlobals->v_up ); if ( local.x >= m_controlMins.x && local.y >= m_controlMins.y && local.z >= m_controlMins.z && local.x <= m_controlMaxs.x && local.y <= m_controlMaxs.y && local.z <= m_controlMaxs.z ) return TRUE; return FALSE; } void CFuncTrackTrain :: Find( void ) { m_ppath = CPathTrack::Instance(FIND_ENTITY_BY_TARGETNAME( NULL, STRING(pev->target) )); if ( !m_ppath ) return; entvars_t *pevTarget = m_ppath->pev; if ( !FClassnameIs( pevTarget, "path_track" ) ) { ALERT( at_error, "func_track_train must be on a path of path_track\n" ); m_ppath = NULL; return; } Vector nextPos = pevTarget->origin; nextPos.z += m_height; Vector look = nextPos; look.z -= m_height; m_ppath->LookAhead( &look, m_length, 0 ); look.z += m_height; pev->angles = UTIL_VecToAngles( look - nextPos ); // The train actually points west pev->angles.y += 180; if ( pev->spawnflags & SF_TRACKTRAIN_NOPITCH ) pev->angles.x = 0; UTIL_SetOrigin( pev, nextPos ); NextThink( pev->ltime + 0.1, FALSE ); SetThink( Next ); pev->speed = m_startSpeed; UpdateSound(); } void CFuncTrackTrain :: NearestPath( void ) { CBaseEntity *pTrack = NULL; CBaseEntity *pNearest = NULL; float dist, closest; closest = 1024; while ((pTrack = UTIL_FindEntityInSphere( pTrack, pev->origin, 1024 )) != NULL) { // filter out non-tracks if ( !(pTrack->pev->flags & (FL_CLIENT|FL_MONSTER)) && FClassnameIs( pTrack->pev, "path_track" ) ) { dist = (pev->origin - pTrack->pev->origin).Length(); if ( dist < closest ) { closest = dist; pNearest = pTrack; } } } if ( !pNearest ) { ALERT( at_console, "Can't find a nearby track !!!\n" ); SetThink(NULL); return; } ALERT( at_aiconsole, "TRAIN: %s, Nearest track is %s\n", STRING(pev->targetname), STRING(pNearest->pev->targetname) ); // If I'm closer to the next path_track on this path, then it's my real path pTrack = ((CPathTrack *)pNearest)->GetNext(); if ( pTrack ) { if ( (pev->origin - pTrack->pev->origin).Length() < (pev->origin - pNearest->pev->origin).Length() ) pNearest = pTrack; } m_ppath = (CPathTrack *)pNearest; if ( pev->speed != 0 ) { NextThink( pev->ltime + 0.1, FALSE ); SetThink( Next ); } } void CFuncTrackTrain::OverrideReset( void ) { NextThink( pev->ltime + 0.1, FALSE ); SetThink( NearestPath ); } CFuncTrackTrain *CFuncTrackTrain::Instance( edict_t *pent ) { if ( FClassnameIs( pent, "func_tracktrain" ) ) return (CFuncTrackTrain *)GET_PRIVATE(pent); return NULL; } /*QUAKED func_train (0 .5 .8) ? Trains are moving platforms that players can ride. The targets origin specifies the min point of the train at each corner. The train spawns at the first target it is pointing at. If the train is the target of a button or trigger, it will not begin moving until activated. speed default 100 dmg default 2 sounds 1) ratchet metal */ void CFuncTrackTrain :: Spawn( void ) { if ( pev->speed == 0 ) m_speed = 100; else m_speed = pev->speed; pev->speed = 0; pev->velocity = g_vecZero; pev->avelocity = g_vecZero; pev->impulse = m_speed; m_dir = 1; if ( FStringNull(pev->target) ) ALERT( at_console, "FuncTrain with no target" ); if ( pev->spawnflags & SF_TRACKTRAIN_PASSABLE ) pev->solid = SOLID_NOT; else pev->solid = SOLID_BSP; pev->movetype = MOVETYPE_PUSH; SET_MODEL( ENT(pev), STRING(pev->model) ); UTIL_SetSize( pev, pev->mins, pev->maxs ); UTIL_SetOrigin( pev, pev->origin ); // Cache off placed origin for train controls pev->oldorigin = pev->origin; m_controlMins = pev->mins; m_controlMaxs = pev->maxs; m_controlMaxs.z += 72; // start trains on the next frame, to make sure their targets have had // a chance to spawn/activate NextThink( pev->ltime + 0.1, FALSE ); SetThink( Find ); Precache(); } void CFuncTrackTrain :: Precache( void ) { if (m_flVolume == 0.0) m_flVolume = 1.0; switch (m_sounds) { default: // no sound pev->noise = 0; break; case 1: PRECACHE_SOUND("plats/ttrain1.wav"); pev->noise = MAKE_STRING("plats/ttrain1.wav");break; case 2: PRECACHE_SOUND("plats/ttrain2.wav"); pev->noise = MAKE_STRING("plats/ttrain2.wav");break; case 3: PRECACHE_SOUND("plats/ttrain3.wav"); pev->noise = MAKE_STRING("plats/ttrain3.wav");break; case 4: PRECACHE_SOUND("plats/ttrain4.wav"); pev->noise = MAKE_STRING("plats/ttrain4.wav");break; case 5: PRECACHE_SOUND("plats/ttrain6.wav"); pev->noise = MAKE_STRING("plats/ttrain6.wav");break; case 6: PRECACHE_SOUND("plats/ttrain7.wav"); pev->noise = MAKE_STRING("plats/ttrain7.wav");break; } PRECACHE_SOUND("plats/ttrain_brake1.wav"); PRECACHE_SOUND("plats/ttrain_start1.wav"); m_usAdjustPitch = PRECACHE_EVENT( 1, "events/train.sc" ); } // This class defines the volume of space that the player must stand in to control the train class CFuncTrainControls : public CBaseEntity { public: virtual int ObjectCaps( void ) { return CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } void Spawn( void ); void EXPORT Find( void ); }; LINK_ENTITY_TO_CLASS( func_traincontrols, CFuncTrainControls ); void CFuncTrainControls :: Find( void ) { edict_t *pTarget = NULL; do { pTarget = FIND_ENTITY_BY_TARGETNAME( pTarget, STRING(pev->target) ); } while ( !FNullEnt(pTarget) && !FClassnameIs(pTarget, "func_tracktrain") ); if ( FNullEnt( pTarget ) ) { ALERT( at_console, "No train %s\n", STRING(pev->target) ); return; } CFuncTrackTrain *ptrain = CFuncTrackTrain::Instance(pTarget); ptrain->SetControls( pev ); UTIL_Remove( this ); } void CFuncTrainControls :: Spawn( void ) { pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NONE; SET_MODEL( ENT(pev), STRING(pev->model) ); UTIL_SetSize( pev, pev->mins, pev->maxs ); UTIL_SetOrigin( pev, pev->origin ); SetThink( Find ); pev->nextthink = gpGlobals->time; } // ---------------------------------------------------------------------------- // // Track changer / Train elevator // // ---------------------------------------------------------------------------- #define SF_TRACK_ACTIVATETRAIN 0x00000001 #define SF_TRACK_RELINK 0x00000002 #define SF_TRACK_ROTMOVE 0x00000004 #define SF_TRACK_STARTBOTTOM 0x00000008 #define SF_TRACK_DONT_MOVE 0x00000010 // // This entity is a rotating/moving platform that will carry a train to a new track. // It must be larger in X-Y planar area than the train, since it must contain the // train within these dimensions in order to operate when the train is near it. // typedef enum { TRAIN_SAFE, TRAIN_BLOCKING, TRAIN_FOLLOWING } TRAIN_CODE; class CFuncTrackChange : public CFuncPlatRot { public: void Spawn( void ); void Precache( void ); // virtual void Blocked( void ); virtual void EXPORT GoUp( void ); virtual void EXPORT GoDown( void ); void KeyValue( KeyValueData* pkvd ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void EXPORT Find( void ); TRAIN_CODE EvaluateTrain( CPathTrack *pcurrent ); void UpdateTrain( Vector &dest ); virtual void HitBottom( void ); virtual void HitTop( void ); void Touch( CBaseEntity *pOther ); virtual void UpdateAutoTargets( int toggleState ); virtual BOOL IsTogglePlat( void ) { return TRUE; } void DisableUse( void ) { m_use = 0; } void EnableUse( void ) { m_use = 1; } int UseEnabled( void ) { return m_use; } virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; virtual void OverrideReset( void ); CPathTrack *m_trackTop; CPathTrack *m_trackBottom; CFuncTrackTrain *m_train; int m_trackTopName; int m_trackBottomName; int m_trainName; TRAIN_CODE m_code; int m_targetState; int m_use; }; LINK_ENTITY_TO_CLASS( func_trackchange, CFuncTrackChange ); TYPEDESCRIPTION CFuncTrackChange::m_SaveData[] = { DEFINE_GLOBAL_FIELD( CFuncTrackChange, m_trackTop, FIELD_CLASSPTR ), DEFINE_GLOBAL_FIELD( CFuncTrackChange, m_trackBottom, FIELD_CLASSPTR ), DEFINE_GLOBAL_FIELD( CFuncTrackChange, m_train, FIELD_CLASSPTR ), DEFINE_GLOBAL_FIELD( CFuncTrackChange, m_trackTopName, FIELD_STRING ), DEFINE_GLOBAL_FIELD( CFuncTrackChange, m_trackBottomName, FIELD_STRING ), DEFINE_GLOBAL_FIELD( CFuncTrackChange, m_trainName, FIELD_STRING ), DEFINE_FIELD( CFuncTrackChange, m_code, FIELD_INTEGER ), DEFINE_FIELD( CFuncTrackChange, m_targetState, FIELD_INTEGER ), DEFINE_FIELD( CFuncTrackChange, m_use, FIELD_INTEGER ), }; IMPLEMENT_SAVERESTORE( CFuncTrackChange, CFuncPlatRot ); void CFuncTrackChange :: Spawn( void ) { Setup(); if ( FBitSet( pev->spawnflags, SF_TRACK_DONT_MOVE ) ) m_vecPosition2.z = pev->origin.z; SetupRotation(); if ( FBitSet( pev->spawnflags, SF_TRACK_STARTBOTTOM ) ) { UTIL_SetOrigin (pev, m_vecPosition2); m_toggle_state = TS_AT_BOTTOM; pev->angles = m_start; m_targetState = TS_AT_TOP; } else { UTIL_SetOrigin (pev, m_vecPosition1); m_toggle_state = TS_AT_TOP; pev->angles = m_end; m_targetState = TS_AT_BOTTOM; } EnableUse(); pev->nextthink = pev->ltime + 2.0; SetThink( Find ); Precache(); } void CFuncTrackChange :: Precache( void ) { // Can't trigger sound PRECACHE_SOUND( "buttons/button11.wav" ); CFuncPlatRot::Precache(); } // UNDONE: Filter touches before re-evaluating the train. void CFuncTrackChange :: Touch( CBaseEntity *pOther ) { #if 0 TRAIN_CODE code; entvars_t *pevToucher = pOther->pev; #endif } void CFuncTrackChange :: KeyValue( KeyValueData *pkvd ) { if ( FStrEq(pkvd->szKeyName, "train") ) { m_trainName = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else if ( FStrEq(pkvd->szKeyName, "toptrack") ) { m_trackTopName = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else if ( FStrEq(pkvd->szKeyName, "bottomtrack") ) { m_trackBottomName = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else { CFuncPlatRot::KeyValue( pkvd ); // Pass up to base class } } void CFuncTrackChange::OverrideReset( void ) { pev->nextthink = pev->ltime + 1.0; SetThink( Find ); } void CFuncTrackChange :: Find( void ) { // Find track entities edict_t *target; target = FIND_ENTITY_BY_TARGETNAME( NULL, STRING(m_trackTopName) ); if ( !FNullEnt(target) ) { m_trackTop = CPathTrack::Instance( target ); target = FIND_ENTITY_BY_TARGETNAME( NULL, STRING(m_trackBottomName) ); if ( !FNullEnt(target) ) { m_trackBottom = CPathTrack::Instance( target ); target = FIND_ENTITY_BY_TARGETNAME( NULL, STRING(m_trainName) ); if ( !FNullEnt(target) ) { m_train = CFuncTrackTrain::Instance( FIND_ENTITY_BY_TARGETNAME( NULL, STRING(m_trainName) ) ); if ( !m_train ) { ALERT( at_error, "Can't find train for track change! %s\n", STRING(m_trainName) ); return; } Vector center = (pev->absmin + pev->absmax) * 0.5; m_trackBottom = m_trackBottom->Nearest( center ); m_trackTop = m_trackTop->Nearest( center ); UpdateAutoTargets( m_toggle_state ); SetThink( NULL ); return; } else { ALERT( at_error, "Can't find train for track change! %s\n", STRING(m_trainName) ); target = FIND_ENTITY_BY_TARGETNAME( NULL, STRING(m_trainName) ); } } else ALERT( at_error, "Can't find bottom track for track change! %s\n", STRING(m_trackBottomName) ); } else ALERT( at_error, "Can't find top track for track change! %s\n", STRING(m_trackTopName) ); } TRAIN_CODE CFuncTrackChange :: EvaluateTrain( CPathTrack *pcurrent ) { // Go ahead and work, we don't have anything to switch, so just be an elevator if ( !pcurrent || !m_train ) return TRAIN_SAFE; if ( m_train->m_ppath == pcurrent || (pcurrent->m_pprevious && m_train->m_ppath == pcurrent->m_pprevious) || (pcurrent->m_pnext && m_train->m_ppath == pcurrent->m_pnext) ) { if ( m_train->pev->speed != 0 ) return TRAIN_BLOCKING; Vector dist = pev->origin - m_train->pev->origin; float length = dist.Length2D(); if ( length < m_train->m_length ) // Empirically determined close distance return TRAIN_FOLLOWING; else if ( length > (150 + m_train->m_length) ) return TRAIN_SAFE; return TRAIN_BLOCKING; } return TRAIN_SAFE; } void CFuncTrackChange :: UpdateTrain( Vector &dest ) { float time = (pev->nextthink - pev->ltime); m_train->pev->velocity = pev->velocity; m_train->pev->avelocity = pev->avelocity; m_train->NextThink( m_train->pev->ltime + time, FALSE ); // Attempt at getting the train to rotate properly around the origin of the trackchange if ( time <= 0 ) return; Vector offset = m_train->pev->origin - pev->origin; Vector delta = dest - pev->angles; // Transform offset into local coordinates UTIL_MakeInvVectors( delta, gpGlobals ); Vector local; local.x = DotProduct( offset, gpGlobals->v_forward ); local.y = DotProduct( offset, gpGlobals->v_right ); local.z = DotProduct( offset, gpGlobals->v_up ); local = local - offset; m_train->pev->velocity = pev->velocity + (local * (1.0/time)); } void CFuncTrackChange :: GoDown( void ) { if ( m_code == TRAIN_BLOCKING ) return; // HitBottom may get called during CFuncPlat::GoDown(), so set up for that // before you call GoDown() UpdateAutoTargets( TS_GOING_DOWN ); // If ROTMOVE, move & rotate if ( FBitSet( pev->spawnflags, SF_TRACK_DONT_MOVE ) ) { SetMoveDone( CallHitBottom ); m_toggle_state = TS_GOING_DOWN; AngularMove( m_start, pev->speed ); } else { CFuncPlat :: GoDown(); SetMoveDone( CallHitBottom ); RotMove( m_start, pev->nextthink - pev->ltime ); } // Otherwise, rotate first, move second // If the train is moving with the platform, update it if ( m_code == TRAIN_FOLLOWING ) { UpdateTrain( m_start ); m_train->m_ppath = NULL; } } // // Platform is at bottom, now starts moving up // void CFuncTrackChange :: GoUp( void ) { if ( m_code == TRAIN_BLOCKING ) return; // HitTop may get called during CFuncPlat::GoUp(), so set up for that // before you call GoUp(); UpdateAutoTargets( TS_GOING_UP ); if ( FBitSet( pev->spawnflags, SF_TRACK_DONT_MOVE ) ) { m_toggle_state = TS_GOING_UP; SetMoveDone( CallHitTop ); AngularMove( m_end, pev->speed ); } else { // If ROTMOVE, move & rotate CFuncPlat :: GoUp(); SetMoveDone( CallHitTop ); RotMove( m_end, pev->nextthink - pev->ltime ); } // Otherwise, move first, rotate second // If the train is moving with the platform, update it if ( m_code == TRAIN_FOLLOWING ) { UpdateTrain( m_end ); m_train->m_ppath = NULL; } } // Normal track change void CFuncTrackChange :: UpdateAutoTargets( int toggleState ) { if ( !m_trackTop || !m_trackBottom ) return; if ( toggleState == TS_AT_TOP ) ClearBits( m_trackTop->pev->spawnflags, SF_PATH_DISABLED ); else SetBits( m_trackTop->pev->spawnflags, SF_PATH_DISABLED ); if ( toggleState == TS_AT_BOTTOM ) ClearBits( m_trackBottom->pev->spawnflags, SF_PATH_DISABLED ); else SetBits( m_trackBottom->pev->spawnflags, SF_PATH_DISABLED ); } void CFuncTrackChange :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( m_toggle_state != TS_AT_TOP && m_toggle_state != TS_AT_BOTTOM ) return; // If train is in "safe" area, but not on the elevator, play alarm sound if ( m_toggle_state == TS_AT_TOP ) m_code = EvaluateTrain( m_trackTop ); else if ( m_toggle_state == TS_AT_BOTTOM ) m_code = EvaluateTrain( m_trackBottom ); else m_code = TRAIN_BLOCKING; if ( m_code == TRAIN_BLOCKING ) { // Play alarm and return EMIT_SOUND(ENT(pev), CHAN_VOICE, "buttons/button11.wav", 1, ATTN_NORM); return; } // Otherwise, it's safe to move // If at top, go down // at bottom, go up DisableUse(); if (m_toggle_state == TS_AT_TOP) GoDown(); else GoUp(); } // // Platform has hit bottom. Stops and waits forever. // void CFuncTrackChange :: HitBottom( void ) { CFuncPlatRot :: HitBottom(); if ( m_code == TRAIN_FOLLOWING ) { // UpdateTrain(); m_train->SetTrack( m_trackBottom ); } SetThink( NULL ); pev->nextthink = -1; UpdateAutoTargets( m_toggle_state ); EnableUse(); } // // Platform has hit bottom. Stops and waits forever. // void CFuncTrackChange :: HitTop( void ) { CFuncPlatRot :: HitTop(); if ( m_code == TRAIN_FOLLOWING ) { // UpdateTrain(); m_train->SetTrack( m_trackTop ); } // Don't let the plat go back down SetThink( NULL ); pev->nextthink = -1; UpdateAutoTargets( m_toggle_state ); EnableUse(); } class CFuncTrackAuto : public CFuncTrackChange { public: void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); virtual void UpdateAutoTargets( int toggleState ); }; LINK_ENTITY_TO_CLASS( func_trackautochange, CFuncTrackAuto ); // Auto track change void CFuncTrackAuto :: UpdateAutoTargets( int toggleState ) { CPathTrack *pTarget, *pNextTarget; if ( !m_trackTop || !m_trackBottom ) return; if ( m_targetState == TS_AT_TOP ) { pTarget = m_trackTop->GetNext(); pNextTarget = m_trackBottom->GetNext(); } else { pTarget = m_trackBottom->GetNext(); pNextTarget = m_trackTop->GetNext(); } if ( pTarget ) { ClearBits( pTarget->pev->spawnflags, SF_PATH_DISABLED ); if ( m_code == TRAIN_FOLLOWING && m_train && m_train->pev->speed == 0 ) m_train->Use( this, this, USE_ON, 0 ); } if ( pNextTarget ) SetBits( pNextTarget->pev->spawnflags, SF_PATH_DISABLED ); } void CFuncTrackAuto :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { CPathTrack *pTarget; if ( !UseEnabled() ) return; if ( m_toggle_state == TS_AT_TOP ) pTarget = m_trackTop; else if ( m_toggle_state == TS_AT_BOTTOM ) pTarget = m_trackBottom; else pTarget = NULL; if ( FClassnameIs( pActivator->pev, "func_tracktrain" ) ) { m_code = EvaluateTrain( pTarget ); // Safe to fire? if ( m_code == TRAIN_FOLLOWING && m_toggle_state != m_targetState ) { DisableUse(); if (m_toggle_state == TS_AT_TOP) GoDown(); else GoUp(); } } else { if ( pTarget ) pTarget = pTarget->GetNext(); if ( pTarget && m_train->m_ppath != pTarget && ShouldToggle( useType, m_targetState ) ) { if ( m_targetState == TS_AT_TOP ) m_targetState = TS_AT_BOTTOM; else m_targetState = TS_AT_TOP; } UpdateAutoTargets( m_targetState ); } } // ---------------------------------------------------------- // // // pev->speed is the travel speed // pev->health is current health // pev->max_health is the amount to reset to each time it starts #define FGUNTARGET_START_ON 0x0001 class CGunTarget : public CBaseMonster { public: void Spawn( void ); void Activate( void ); void EXPORT Next( void ); void EXPORT Start( void ); void EXPORT Wait( void ); void Stop( void ); int BloodColor( void ) { return DONT_BLEED; } int Classify( void ) { return CLASS_MACHINE; } int TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); Vector BodyTarget( const Vector &posSrc ) { return pev->origin; } virtual int ObjectCaps( void ) { return CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; private: BOOL m_on; }; LINK_ENTITY_TO_CLASS( func_guntarget, CGunTarget ); TYPEDESCRIPTION CGunTarget::m_SaveData[] = { DEFINE_FIELD( CGunTarget, m_on, FIELD_BOOLEAN ), }; IMPLEMENT_SAVERESTORE( CGunTarget, CBaseMonster ); void CGunTarget::Spawn( void ) { pev->solid = SOLID_BSP; pev->movetype = MOVETYPE_PUSH; UTIL_SetOrigin(pev, pev->origin); SET_MODEL(ENT(pev), STRING(pev->model) ); if ( pev->speed == 0 ) pev->speed = 100; // Don't take damage until "on" pev->takedamage = DAMAGE_NO; pev->flags |= FL_MONSTER; m_on = FALSE; pev->max_health = pev->health; if ( pev->spawnflags & FGUNTARGET_START_ON ) { SetThink( Start ); pev->nextthink = pev->ltime + 0.3; } } void CGunTarget::Activate( void ) { CBaseEntity *pTarg; // now find our next target pTarg = GetNextTarget(); if ( pTarg ) { m_hTargetEnt = pTarg; UTIL_SetOrigin( pev, pTarg->pev->origin - (pev->mins + pev->maxs) * 0.5 ); } } void CGunTarget::Start( void ) { Use( this, this, USE_ON, 0 ); } void CGunTarget::Next( void ) { SetThink( NULL ); m_hTargetEnt = GetNextTarget(); CBaseEntity *pTarget = m_hTargetEnt; if ( !pTarget ) { Stop(); return; } SetMoveDone( Wait ); LinearMove( pTarget->pev->origin - (pev->mins + pev->maxs) * 0.5, pev->speed ); } void CGunTarget::Wait( void ) { CBaseEntity *pTarget = m_hTargetEnt; if ( !pTarget ) { Stop(); return; } // Fire the pass target if there is one if ( pTarget->pev->message ) { FireTargets( STRING(pTarget->pev->message), this, this, USE_TOGGLE, 0 ); if ( FBitSet( pTarget->pev->spawnflags, SF_CORNER_FIREONCE ) ) pTarget->pev->message = 0; } m_flWait = pTarget->GetDelay(); pev->target = pTarget->pev->target; SetThink( Next ); if (m_flWait != 0) {// -1 wait will wait forever! pev->nextthink = pev->ltime + m_flWait; } else { Next();// do it RIGHT now! } } void CGunTarget::Stop( void ) { pev->velocity = g_vecZero; pev->nextthink = 0; pev->takedamage = DAMAGE_NO; } int CGunTarget::TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType ) { if ( pev->health > 0 ) { pev->health -= flDamage; if ( pev->health <= 0 ) { pev->health = 0; Stop(); if ( pev->message ) FireTargets( STRING(pev->message), this, this, USE_TOGGLE, 0 ); } } return 0; } void CGunTarget::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( !ShouldToggle( useType, m_on ) ) return; if ( m_on ) { Stop(); } else { pev->takedamage = DAMAGE_AIM; m_hTargetEnt = GetNextTarget(); if ( m_hTargetEnt == NULL ) return; pev->health = pev->max_health; Next(); } }
0
0.889099
1
0.889099
game-dev
MEDIA
0.786079
game-dev,audio-video-media
0.914006
1
0.914006
runuo/runuo
6,127
Scripts/Mobiles/Monsters/ML/Special/Meraktus.cs
using System; using System.Collections; using System.Collections.Generic; using Server.Items; using Server.Targeting; using Server.Misc; using Server.Engines.CannedEvil; namespace Server.Mobiles { [CorpseName( "the remains of Meraktus" )] public class Meraktus : BaseChampion { public override ChampionSkullType SkullType{ get{ return ChampionSkullType.Pain; } } public override Type[] UniqueList{ get{ return new Type[] { typeof( Subdue ) }; } } public override Type[] SharedList{ get{ return new Type[] { }; } } public override Type[] DecorativeList{ get{ return new Type[] { typeof( ArtifactLargeVase ), typeof( ArtifactVase ), typeof( MinotaurStatueDeed ) }; } } public override MonsterStatuetteType[] StatueTypes{ get{ return new MonsterStatuetteType[] { MonsterStatuetteType.Minotaur }; } } public override WeaponAbility GetWeaponAbility() { return WeaponAbility.Dismount; } [Constructable] public Meraktus() : base(AIType.AI_Melee) { Name = "Meraktus"; Title = "the Tormented"; Body = 263; BaseSoundID = 680; Hue = 0x835; SetStr( 1419, 1438 ); SetDex( 309, 413 ); SetInt( 129, 131 ); SetHits( 4100, 4200 ); SetDamage( 16, 30 ); SetDamageType( ResistanceType.Physical, 100 ); SetResistance( ResistanceType.Physical, 65, 90 ); SetResistance( ResistanceType.Fire, 65, 70 ); SetResistance( ResistanceType.Cold, 50, 60 ); SetResistance( ResistanceType.Poison, 40, 60 ); SetResistance( ResistanceType.Energy, 50, 55 ); //SetSkill( SkillName.Meditation, Unknown ); //SetSkill( SkillName.EvalInt, Unknown ); //SetSkill( SkillName.Magery, Unknown ); //SetSkill( SkillName.Poisoning, Unknown ); SetSkill( SkillName.Anatomy, 0); SetSkill( SkillName.MagicResist, 107.0, 111.3 ); SetSkill( SkillName.Tactics, 107.0, 117.0 ); SetSkill( SkillName.Wrestling, 100.0, 105.0 ); Fame = 70000; Karma = -70000; VirtualArmor = 28; // Don't know what it should be if ( Core.ML ) { PackResources(8); PackTalismans(5); } Timer.DelayCall(TimeSpan.FromSeconds(1), new TimerCallback(SpawnTormented)); } public virtual void PackResources(int amount) { for (int i = 0; i < amount; i++) switch (Utility.Random(6)) { case 0: PackItem(new Blight()); break; case 1: PackItem(new Scourge()); break; case 2: PackItem(new Taint()); break; case 3: PackItem(new Putrefication()); break; case 4: PackItem(new Corruption()); break; case 5: PackItem(new Muculent()); break; } } public virtual void PackTalismans(int amount) { int count = Utility.Random(amount); for (int i = 0; i < count; i++) PackItem(new RandomTalisman()); } public override void OnDeath( Container c ) { base.OnDeath( c ); if ( Core.ML ) { c.DropItem( new MalletAndChisel() ); switch ( Utility.Random( 3 ) ) { case 0: c.DropItem( new MinotaurHedge() ); break; case 1: c.DropItem( new BonePile() ); break; case 2: c.DropItem( new LightYarn() ); break; } if ( Utility.RandomBool() ) c.DropItem( new TormentedChains() ); if ( Utility.RandomDouble() < 0.025 ) c.DropItem(new CrimsonCincture()); } } public override void GenerateLoot() { if ( Core.ML ) { AddLoot( LootPack.AosSuperBoss, 5 ); // Need to verify } } public override int GetAngerSound() { return 0x597; } public override int GetIdleSound() { return 0x596; } public override int GetAttackSound() { return 0x599; } public override int GetHurtSound() { return 0x59a; } public override int GetDeathSound() { return 0x59c; } public override int Meat { get { return 2; } } public override int Hides { get { return 10; } } public override HideType HideType { get { return HideType.Regular; } } public override Poison PoisonImmune{ get{ return Poison.Regular; } } public override int TreasureMapLevel{ get{ return 3; } } public override bool BardImmune{ get{ return true; } } public override bool Unprovokable{ get{ return true; } } public override bool Uncalmable { get { return true; } } public override void OnGaveMeleeAttack(Mobile defender) { base.OnGaveMeleeAttack(defender); if (0.2 >= Utility.RandomDouble()) Earthquake(); } public void Earthquake() { Map map = this.Map; if (map == null) return; ArrayList targets = new ArrayList(); foreach (Mobile m in this.GetMobilesInRange(8)) { if (m == this || !CanBeHarmful(m)) continue; if (m is BaseCreature && (((BaseCreature)m).Controlled || ((BaseCreature)m).Summoned || ((BaseCreature)m).Team != this.Team)) targets.Add(m); else if (m.Player) targets.Add(m); } PlaySound(0x2F3); for (int i = 0; i < targets.Count; ++i) { Mobile m = (Mobile)targets[i]; if( m != null && !m.Deleted && m is PlayerMobile ) { PlayerMobile pm = m as PlayerMobile; if(pm != null && pm.Mounted) { pm.Mount.Rider=null; } } double damage = m.Hits * 0.6;//was .6 if (damage < 10.0) damage = 10.0; else if (damage > 75.0) damage = 75.0; DoHarmful(m); AOS.Damage(m, this, (int)damage, 100, 0, 0, 0, 0); if (m.Alive && m.Body.IsHuman && !m.Mounted) m.Animate(20, 7, 1, true, false, 0); // take hit } } public Meraktus( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } #region SpawnHelpers public void SpawnTormented() { BaseCreature spawna = new TormentedMinotaur(); spawna.MoveToWorld(Location, Map); BaseCreature spawnb = new TormentedMinotaur(); spawnb.MoveToWorld(Location, Map); BaseCreature spawnc = new TormentedMinotaur(); spawnc.MoveToWorld(Location, Map); BaseCreature spawnd = new TormentedMinotaur(); spawnd.MoveToWorld(Location, Map); } #endregion } }
0
0.994274
1
0.994274
game-dev
MEDIA
0.989867
game-dev
0.995872
1
0.995872
TeamLumi/opendpr
3,014
Assets/Scripts/Dpr/Battle/View/Task.cs
using DG.Tweening; using System; namespace Dpr.Battle.View { public class Task : IDisposable { public int _priority; public Task _iPtrPrev; public Task _iPtrNext; public bool _isSelfDelete; protected float _raito; protected int _frame; protected int _lifeTime; protected Ease _easingType; protected bool _isStart; protected Action _onStart; protected Action _onFinished; protected AdvanceMode _advanceMode; protected float _startTime; protected float _endTime; protected float _duration; protected float _elapsedTime; protected virtual bool IsFinishCondition { get; } public bool IsEffectEnable { get; set; } public TaskManager Parent { get; set; } public bool IsFinished { get => _isSelfDelete; } public float Duration { get => _endTime - _startTime; } public Task() { _priority = 0; _iPtrPrev = null; _iPtrNext = null; _isSelfDelete = false; _frame = 0; _lifeTime = 0; _isStart = false; _onStart = null; Parent = null; _endTime = 0.0f; _advanceMode = AdvanceMode.Step; _startTime = 0.0f; _elapsedTime = 0.0f; } public void Dispose() { OnDispose(); Clear(); } protected virtual void OnDispose() { // Empty } public void Clear(Task iPtrDummyTask) { Clear(); _iPtrPrev = iPtrDummyTask; _iPtrNext = iPtrDummyTask; _priority = 0; } public void Delete() { _iPtrPrev._iPtrNext = _iPtrNext; _iPtrNext._iPtrPrev = _iPtrPrev; Dispose(); } protected virtual void Clear() { _priority = 0; _iPtrPrev = null; _iPtrNext = null; _isSelfDelete = false; _frame = 0; _lifeTime = 0; _isStart = false; _onFinished = null; _onStart = null; Parent = null; _startTime = 0.0f; _endTime = 0.0f; _elapsedTime = 0.0f; } // TODO public virtual void Update(float deltaTime, float currentSequenceTime, int step) { } protected virtual void FinishTask() { OnFinishTask(); _isSelfDelete = true; _onFinished?.Invoke(); } public Task SetOnStart(Action onStart) { _onStart = onStart; return this; } public Task SetOnFinished(Action onFinished) { _onFinished = onFinished; return this; } public Task SetStartTime(float startTime) { _startTime = startTime; return this; } public Task SetEndTime(float endTime) { _endTime = endTime; _duration = endTime - _startTime; return this; } public Task SetDuration(float duration) { _duration = duration; return this; } public Task SetAdvanceMode(AdvanceMode mode) { _advanceMode = mode; return this; } protected virtual void OnUpdate(int frame, float raito) { // Empty } protected virtual void OnFinishTask() { // Empty } public enum AdvanceMode : int { Step = 0, Time = 1, } } }
0
0.747922
1
0.747922
game-dev
MEDIA
0.821962
game-dev
0.973395
1
0.973395
MACURD/Hearthbuddy8.7.6
1,035
Routines/DefaultRoutine/Silverfish/cards/1158-奥丹姆奇兵/Sim_ULD_240.cs
using System; using System.Collections.Generic; using System.Text; namespace HREngine.Bots { class Sim_ULD_240 : SimTemplate //* 对空奥术法师 Arcane Flakmage { //After you play a <b>Secret</b>, deal 2 damage to all enemy minions. //在你使用一张<b>奥秘</b>牌后,对所有敌方随从造成2点伤害。 public override void onCardIsGoingToBePlayed(Playfield p, Handmanager.Handcard hc, bool ownplay, Minion m) { int dmg = (ownplay) ? p.getSpellDamageDamage(2) : p.getEnemySpellDamageDamage(2); if (m.own == ownplay && hc.card.Secret) p.allMinionOfASideGetDamage(!ownplay, dmg, true); } // public override void onTurnStartTrigger(Playfield p, Minion triggerEffectMinion, bool turnStartOfOwner) // { // if (!turnStartOfOwner && triggerEffectMinion.own == turnStartOfOwner) // { // int dmg = p.getEnemySpellDamageDamage(2); // p.allMinionOfASideGetDamage(!turnStartOfOwner, dmg); // } // } } }
0
0.947313
1
0.947313
game-dev
MEDIA
0.989489
game-dev
0.970701
1
0.970701
pathea-games/planetexplorers
1,137
Assets/Resources/Particle/Script/ExplosionObject.js
var Force:Vector3; var Objcet:GameObject; var Num:int; var Scale:int = 20; var ScaleMin:int = 10; var Sounds:AudioClip[]; var LifeTimeObject:float = 2; var postitionoffset:float = 2; var random:boolean; function Start () { Physics.IgnoreLayerCollision(2,2); if(Sounds.length>0){ AudioSource.PlayClipAtPoint(Sounds[Random.Range(0,Sounds.length)],transform.position); } if(Objcet){ if(random){ Num = Random.Range(1,Num); } for(var i=0;i<Num;i++){ var pos = new Vector3(Random.Range(-postitionoffset,postitionoffset),Random.Range(-postitionoffset,postitionoffset),Random.Range(-postitionoffset,postitionoffset)) / 10f; var obj:GameObject = Instantiate(Objcet, this.transform.position + pos, Random.rotation); var scale = Random.Range(ScaleMin,Scale); //obj.transform.parent = transform; Destroy(obj,LifeTimeObject); if(Scale>0) obj.transform.localScale = new Vector3(scale,scale,scale); if(obj.GetComponent.<Rigidbody>() ){ obj.GetComponent.<Rigidbody>().AddForce(new Vector3(Random.Range(-Force.x,Force.x),Random.Range(-Force.y,Force.y),Random.Range(-Force.z,Force.z))); } } } }
0
0.629152
1
0.629152
game-dev
MEDIA
0.924752
game-dev
0.782847
1
0.782847
LangYa466/MCPLite-all-source
4,140
src/main/java/net/minecraft/world/WorldType.java
package net.minecraft.world; public class WorldType { /** List of world types. */ public static final WorldType[] worldTypes = new WorldType[16]; /** Default world type. */ public static final WorldType DEFAULT = (new WorldType(0, "default", 1)).setVersioned(); /** Flat world type. */ public static final WorldType FLAT = new WorldType(1, "flat"); /** Large Biome world Type. */ public static final WorldType LARGE_BIOMES = new WorldType(2, "largeBiomes"); /** amplified world type */ public static final WorldType AMPLIFIED = (new WorldType(3, "amplified")).setNotificationData(); public static final WorldType CUSTOMIZED = new WorldType(4, "customized"); public static final WorldType DEBUG_WORLD = new WorldType(5, "debug_all_block_states"); /** Default (1.1) world type. */ public static final WorldType DEFAULT_1_1 = (new WorldType(8, "default_1_1", 0)).setCanBeCreated(false); /** ID for this world type. */ private final int worldTypeId; private final String worldType; /** The int version of the ChunkProvider that generated this world. */ private final int generatorVersion; /** * Whether this world type can be generated. Normally true; set to false for out-of-date generator versions. */ private boolean canBeCreated; /** Whether this WorldType has a version or not. */ private boolean isWorldTypeVersioned; private boolean hasNotificationData; private WorldType(int id, String name) { this(id, name, 0); } private WorldType(int id, String name, int version) { this.worldType = name; this.generatorVersion = version; this.canBeCreated = true; this.worldTypeId = id; worldTypes[id] = this; } public String getWorldTypeName() { return this.worldType; } /** * Gets the translation key for the name of this world type. */ public String getTranslateName() { return "generator." + this.worldType; } /** * Gets the translation key for the info text for this world type. */ public String getTranslatedInfo() { return this.getTranslateName() + ".info"; } /** * Returns generatorVersion. */ public int getGeneratorVersion() { return this.generatorVersion; } public WorldType getWorldTypeForGeneratorVersion(int version) { return this == DEFAULT && version == 0 ? DEFAULT_1_1 : this; } /** * Sets canBeCreated to the provided value, and returns this. */ private WorldType setCanBeCreated(boolean enable) { this.canBeCreated = enable; return this; } /** * Gets whether this WorldType can be used to generate a new world. */ public boolean getCanBeCreated() { return this.canBeCreated; } /** * Flags this world type as having an associated version. */ private WorldType setVersioned() { this.isWorldTypeVersioned = true; return this; } /** * Returns true if this world Type has a version associated with it. */ public boolean isVersioned() { return this.isWorldTypeVersioned; } public static WorldType parseWorldType(String type) { for (int i = 0; i < worldTypes.length; ++i) { if (worldTypes[i] != null && worldTypes[i].worldType.equalsIgnoreCase(type)) { return worldTypes[i]; } } return null; } public int getWorldTypeID() { return this.worldTypeId; } /** * returns true if selecting this worldtype from the customize menu should display the generator.[worldtype].info * message */ public boolean showWorldInfoNotice() { return this.hasNotificationData; } /** * enables the display of generator.[worldtype].info message on the customize world menu */ private WorldType setNotificationData() { this.hasNotificationData = true; return this; } }
0
0.618988
1
0.618988
game-dev
MEDIA
0.409767
game-dev
0.542122
1
0.542122
Citadel-Station-13/Citadel-Station-13
21,799
code/modules/antagonists/changeling/changeling.dm
#define LING_FAKEDEATH_TIME 400 //40 seconds #define LING_DEAD_GENETICDAMAGE_HEAL_CAP 50 //The lowest value of geneticdamage handle_changeling() can take it to while dead. #define LING_ABSORB_RECENT_SPEECH 8 //The amount of recent spoken lines to gain on absorbing a mob /// Helper to format the text that gets thrown onto the chem hud element. #define FORMAT_CHEM_CHARGES_TEXT(charges) MAPTEXT("<div align='center' valign='middle' style='position:relative; top:0px; left:6px'><font color='#dd66dd'>[round(charges)]</font></div>") /datum/antagonist/changeling name = "Changeling" roundend_category = "changelings" antagpanel_category = "Changeling" job_rank = ROLE_CHANGELING antag_moodlet = /datum/mood_event/focused threat = 10 var/you_are_greet = TRUE var/give_objectives = TRUE var/team_mode = FALSE //Should assign team objectives ? //Changeling Stuff var/list/stored_profiles = list() //list of datum/changelingprofile var/datum/changelingprofile/first_prof = null var/absorbedcount = 0 /// did we get succed by another changeling var/hostile_absorbed = FALSE var/trueabsorbs = 0//dna gained using absorb, not dna sting var/chem_charges = 20 var/chem_storage = 75 var/chem_recharge_rate = 1 var/chem_recharge_slowdown = 0 var/sting_range = 2 var/changelingID = "Changeling" var/geneticdamage = 0 var/isabsorbing = 0 var/islinking = 0 var/geneticpoints = 10 var/maxgeneticpoints = 10 var/purchasedpowers = list() var/mimicing = "" var/can_respec = FALSE//set to TRUE in absorb.dm var/changeling_speak = 0 var/loudfactor = 0 //Used for blood tests. This is is the average loudness of the ling's abilities calculated with the below two vars var/loudtotal = 0 //Used to keep track of the sum of the ling's loudness var/totalpurchases = 0 //Used to keep track of how many purchases the ling's made after free abilities have been added var/datum/dna/chosen_dna var/datum/action/changeling/sting/chosen_sting var/datum/cellular_emporium/cellular_emporium var/datum/action/innate/cellular_emporium/emporium_action var/static/list/all_powers = typecacheof(/datum/action/changeling,TRUE) /datum/antagonist/changeling/Destroy() QDEL_NULL(cellular_emporium) QDEL_NULL(emporium_action) . = ..() /datum/antagonist/changeling/proc/generate_name() var/honorific if(owner.current.gender == FEMALE) honorific = "Ms." else if(owner.current.gender == MALE) honorific = "Mr." else honorific = "Mx." if(GLOB.possible_changeling_IDs.len) changelingID = pick(GLOB.possible_changeling_IDs) GLOB.possible_changeling_IDs -= changelingID changelingID = "[honorific] [changelingID]" else changelingID = "[honorific] [rand(1,999)]" /datum/antagonist/changeling/proc/create_actions() cellular_emporium = new(src) emporium_action = new(cellular_emporium) emporium_action.Grant(owner.current) /datum/antagonist/changeling/on_gain() generate_name() create_actions() reset_powers() create_initial_profile() if(give_objectives) forge_objectives() owner.current.get_language_holder().omnitongue = TRUE remove_clownmut() . = ..() /datum/antagonist/changeling/on_removal() //We'll be using this from now on var/mob/living/carbon/C = owner.current if(istype(C)) var/obj/item/organ/brain/B = C.getorganslot(ORGAN_SLOT_BRAIN) if(B && (B.decoy_override != initial(B.decoy_override))) B.organ_flags |= ORGAN_VITAL B.decoy_override = FALSE remove_changeling_powers() owner.special_role = null owner.current.hud_used?.lingchemdisplay?.invisibility = INVISIBILITY_ABSTRACT . = ..() /datum/antagonist/changeling/proc/remove_clownmut() if (owner) var/mob/living/carbon/human/H = owner.current if(istype(H) && owner.assigned_role == "Clown") to_chat(H, "You have evolved beyond your clownish nature, allowing you to wield weapons without harming yourself.") H.dna.remove_mutation(CLOWNMUT) /datum/antagonist/changeling/proc/reset_properties(hardReset = FALSE) changeling_speak = 0 chosen_sting = null geneticpoints = maxgeneticpoints sting_range = initial(sting_range) chem_recharge_slowdown = initial(chem_recharge_slowdown) mimicing = "" if (hardReset) chem_storage = initial(chem_storage) chem_recharge_rate = initial(chem_recharge_rate) geneticpoints = initial(geneticpoints) maxgeneticpoints = initial(maxgeneticpoints) chem_charges = min(chem_charges, chem_storage) /datum/antagonist/changeling/proc/remove_changeling_powers() if(ishuman(owner.current) || ismonkey(owner.current)) reset_properties() QDEL_NULL(cellular_emporium) QDEL_NULL(emporium_action) for(var/datum/action/changeling/p in purchasedpowers) purchasedpowers -= p p.Remove(owner.current) //MOVE THIS if(owner.current.hud_used) owner.current.hud_used.lingstingdisplay.icon_state = null owner.current.hud_used.lingstingdisplay.invisibility = INVISIBILITY_ABSTRACT /datum/antagonist/changeling/proc/reset_powers() if(purchasedpowers) remove_changeling_powers() create_actions() //Repurchase free powers. for(var/path in all_powers) var/datum/action/changeling/S = new path() if(!S.dna_cost) if(!has_sting(S)) purchasedpowers += S S.on_purchase(owner.current,TRUE) loudfactor = 0 loudtotal = 0 totalpurchases = 0 /datum/antagonist/changeling/proc/regain_powers()//for when action buttons are lost and need to be regained, such as when the mind enters a new mob emporium_action.Grant(owner.current) for(var/power in purchasedpowers) var/datum/action/changeling/S = power if(istype(S) && S.needs_button) S.Grant(owner.current) /datum/antagonist/changeling/proc/has_sting(datum/action/changeling/power) for(var/P in purchasedpowers) var/datum/action/changeling/otherpower = P if(initial(power.name) == otherpower.name) return TRUE return FALSE /datum/antagonist/changeling/proc/purchase_power(sting_name) var/datum/action/changeling/thepower for(var/path in all_powers) var/datum/action/changeling/S = path if(initial(S.name) == sting_name) thepower = new path break if(!thepower) to_chat(owner.current, "This is awkward. Changeling power purchase failed, please report this bug to a coder!") return if(absorbedcount < thepower.req_dna) to_chat(owner.current, "We lack the energy to evolve this ability!") return if(has_sting(thepower)) to_chat(owner.current, "We have already evolved this ability!") return if(thepower.dna_cost < 0) to_chat(owner.current, "We cannot evolve this ability.") return if(geneticpoints < thepower.dna_cost) to_chat(owner.current, "We have reached our capacity for abilities.") return if(HAS_TRAIT(owner.current, TRAIT_DEATHCOMA))//To avoid potential exploits by buying new powers while in stasis, which clears your verblist. to_chat(owner.current, "We lack the energy to evolve new abilities right now.") return geneticpoints -= thepower.dna_cost purchasedpowers += thepower thepower.on_purchase(owner.current)//Grant() is ran in this proc, see changeling_powers.dm loudtotal += thepower.loudness totalpurchases++ var/oldloudness = loudfactor loudfactor = loudtotal/max(totalpurchases,1) if(loudfactor >= LINGBLOOD_DETECTION_THRESHOLD && oldloudness < LINGBLOOD_DETECTION_THRESHOLD) to_chat(owner.current, "<span class='warning'>Our blood has grown flammable. Our blood will now react violently to heat.</span>") else if(loudfactor < LINGBLOOD_DETECTION_THRESHOLD && oldloudness >= LINGBLOOD_DETECTION_THRESHOLD) to_chat(owner.current, "<span class='notice'>Our blood has stabilized, and will no longer react violently to heat.</span>") if(loudfactor > LINGBLOOD_EXPLOSION_THRESHOLD && oldloudness <= LINGBLOOD_EXPLOSION_THRESHOLD) to_chat(owner.current, "<span class='warning'>Our blood has grown extremely flammable. Our blood will now react explosively to heat.</span>") else if(loudfactor <= LINGBLOOD_EXPLOSION_THRESHOLD && oldloudness > LINGBLOOD_EXPLOSION_THRESHOLD) to_chat(owner.current, "<span class='notice'>Our blood has slightly stabilized, and will no longer explode when exposed to heat.</span>") /datum/antagonist/changeling/proc/readapt() if(!ishuman(owner.current)) to_chat(owner.current, "<span class='danger'>We can't remove our evolutions in this form!</span>") return if(can_respec) to_chat(owner.current, "<span class='notice'>We have removed our evolutions from this form, and are now ready to readapt.</span>") reset_powers() playsound(get_turf(owner.current), 'sound/effects/lingreadapt.ogg', 75, TRUE, 5) can_respec = 0 SSblackbox.record_feedback("tally", "changeling_power_purchase", 1, "Readapt") return TRUE else to_chat(owner.current, "<span class='danger'>You lack the power to readapt your evolutions!</span>") return FALSE //Called in life() /datum/antagonist/changeling/proc/regenerate()//grants the HuD in life.dm var/mob/living/carbon/the_ling = owner.current if(istype(the_ling)) if(the_ling.stat == DEAD) chem_charges = min(max(0, chem_charges + chem_recharge_rate - chem_recharge_slowdown), (chem_storage*0.5)) geneticdamage = max(LING_DEAD_GENETICDAMAGE_HEAL_CAP,geneticdamage-1) else //not dead? no chem/geneticdamage caps. chem_charges = min(max(0, chem_charges + chem_recharge_rate - chem_recharge_slowdown), chem_storage) geneticdamage = max(0, geneticdamage-1) owner.current.hud_used?.lingchemdisplay?.invisibility = 0 owner.current.hud_used?.lingchemdisplay?.maptext = FORMAT_CHEM_CHARGES_TEXT(chem_charges) /datum/antagonist/changeling/proc/get_dna(dna_owner) for(var/datum/changelingprofile/prof in stored_profiles) if(dna_owner == prof.name) return prof /datum/antagonist/changeling/proc/has_dna(datum/dna/tDNA) for(var/datum/changelingprofile/prof in stored_profiles) if(tDNA.is_same_as(prof.dna)) return TRUE return FALSE /datum/antagonist/changeling/proc/can_absorb_dna(mob/living/carbon/human/target, var/verbose=1) var/mob/living/carbon/user = owner.current if(!istype(user)) return if(!target) return if(NO_DNA_COPY in target.dna.species.species_traits) if(verbose) to_chat(user, "<span class='warning'>[target] is not compatible with our biology.</span>") return if((HAS_TRAIT(target, TRAIT_NOCLONE)) || (HAS_TRAIT(target, TRAIT_NOCLONE))) if(verbose) to_chat(user, "<span class='warning'>DNA of [target] is ruined beyond usability!</span>") return if(!ishuman(target))//Absorbing monkeys is entirely possible, but it can cause issues with transforming. That's what lesser form is for anyway! if(verbose) to_chat(user, "<span class='warning'>We could gain no benefit from absorbing a lesser creature.</span>") return if(has_dna(target.dna)) if(verbose) to_chat(user, "<span class='warning'>We already have this DNA in storage!</span>") return if(!target.has_dna()) if(verbose) to_chat(user, "<span class='warning'>[target] is not compatible with our biology.</span>") return return TRUE /datum/antagonist/changeling/proc/create_profile(mob/living/carbon/human/H, protect = 0) var/datum/changelingprofile/prof = new H.dna.real_name = H.real_name //Set this again, just to be sure that it's properly set. var/datum/dna/new_dna = new H.dna.type H.dna.copy_dna(new_dna) prof.dna = new_dna prof.name = H.real_name prof.protected = protect prof.underwear = H.underwear prof.undie_color = H.undie_color prof.undershirt = H.undershirt prof.shirt_color = H.shirt_color prof.socks = H.socks prof.socks_color = H.socks_color var/datum/icon_snapshot/entry = new entry.name = H.name entry.icon = H.icon entry.icon_state = H.icon_state entry.overlays = H.get_overlays_copy(list(HANDS_LAYER, HANDCUFF_LAYER, LEGCUFF_LAYER)) prof.profile_snapshot = entry for(var/slot in GLOB.slots) if(slot in H.vars) var/obj/item/I = H.vars[slot] if(!I) continue prof.name_list[slot] = I.name prof.appearance_list[slot] = I.appearance prof.flags_cover_list[slot] = I.flags_cover prof.item_state_list[slot] = I.item_state prof.exists_list[slot] = 1 else continue return prof /datum/antagonist/changeling/proc/add_profile(datum/changelingprofile/prof) if(!first_prof) first_prof = prof stored_profiles += prof absorbedcount++ /datum/antagonist/changeling/proc/add_new_profile(mob/living/carbon/human/H, protect = 0) var/datum/changelingprofile/prof = create_profile(H, protect) add_profile(prof) return prof /datum/antagonist/changeling/proc/remove_profile(mob/living/carbon/human/H, force = 0) for(var/datum/changelingprofile/prof in stored_profiles) if(H.real_name == prof.name) if(prof.protected && !force) continue stored_profiles -= prof qdel(prof) /datum/antagonist/changeling/proc/create_initial_profile() var/mob/living/carbon/C = owner.current //only carbons have dna now, so we have to typecaste if(ishuman(C)) add_new_profile(C) /datum/antagonist/changeling/apply_innate_effects() //Brains optional. var/mob/living/carbon/C = owner.current if(istype(C)) var/obj/item/organ/brain/B = C.getorganslot(ORGAN_SLOT_BRAIN) if(B) B.organ_flags &= ~ORGAN_VITAL B.decoy_override = TRUE update_changeling_icons_added() RegisterSignal(owner.current,COMSIG_LIVING_BIOLOGICAL_LIFE, PROC_REF(regenerate)) return /datum/antagonist/changeling/remove_innate_effects() update_changeling_icons_removed() UnregisterSignal(owner.current,COMSIG_LIVING_BIOLOGICAL_LIFE) return /datum/antagonist/changeling/greet() if (you_are_greet) to_chat(owner.current, "<span class='boldannounce'>You are [changelingID], a changeling! You have absorbed and taken the form of a human.</span>") to_chat(owner.current, "<span class='boldannounce'>Use say \"[MODE_TOKEN_CHANGELING] message\" to communicate with your fellow changelings.</span>") to_chat(owner.current, "<b>You must complete the following tasks:</b>") owner.current.playsound_local(get_turf(owner.current), 'sound/ambience/antag/ling_aler.ogg', 100, FALSE, pressure_affected = FALSE) owner.announce_objectives() /datum/antagonist/changeling/farewell() to_chat(owner.current, "<span class='userdanger'>You grow weak and lose your powers! You are no longer a changeling and are stuck in your current form!</span>") /datum/antagonist/changeling/proc/forge_team_objectives() if(GLOB.changeling_team_objective_type) var/datum/objective/changeling_team_objective/team_objective = new GLOB.changeling_team_objective_type team_objective.owner = owner if(team_objective.prepare())//Setting up succeeded objectives += team_objective else qdel(team_objective) return /datum/antagonist/changeling/proc/forge_objectives() //OBJECTIVES - random traitor objectives. Unique objectives "steal brain" and "identity theft". //No escape alone because changelings aren't suited for it and it'd probably just lead to rampant robusting //If it seems like they'd be able to do it in play, add a 10% chance to have to escape alone var/escape_objective_possible = TRUE //if there's a team objective, check if it's compatible with escape objectives for(var/datum/objective/changeling_team_objective/CTO in objectives) if(!CTO.escape_objective_compatible) escape_objective_possible = FALSE break var/changeling_objective = rand(1,3) var/generic_absorb_objective = FALSE var/multiple_lings = length(get_antag_minds(/datum/antagonist/changeling,TRUE)) > 1 switch(changeling_objective) if(1) generic_absorb_objective = TRUE if(2) if(multiple_lings) var/datum/objective/absorb_changeling/ac = new ac.owner = owner objectives += ac else generic_absorb_objective = TRUE if(3) if(multiple_lings) var/datum/objective/absorb_most/ac = new ac.owner = owner objectives += ac else generic_absorb_objective = TRUE if(generic_absorb_objective) var/datum/objective/absorb/absorb_objective = new absorb_objective.owner = owner absorb_objective.gen_amount_goal(6, 8) objectives += absorb_objective if(prob(60)) if(prob(85)) var/datum/objective/steal/steal_objective = new steal_objective.owner = owner steal_objective.find_target() objectives += steal_objective else var/datum/objective/download/download_objective = new download_objective.owner = owner download_objective.gen_amount_goal() objectives += download_objective var/list/active_ais = active_ais() if(active_ais.len && prob(100/GLOB.joined_player_list.len)) var/datum/objective/destroy/destroy_objective = new destroy_objective.owner = owner destroy_objective.find_target() objectives += destroy_objective else var/datum/objective/assassinate/once/kill_objective = new kill_objective.owner = owner if(team_mode) //No backstabbing while in a team kill_objective.find_target_by_role(role = ROLE_CHANGELING, role_type = 1, invert = 1) else kill_objective.find_target() objectives += kill_objective if(!(locate(/datum/objective/escape) in objectives) && escape_objective_possible && prob(50)) var/datum/objective/escape/escape_with_identity/identity_theft = new identity_theft.owner = owner identity_theft.target = kill_objective.target identity_theft.update_explanation_text() objectives += identity_theft escape_objective_possible = FALSE if (!(locate(/datum/objective/escape) in objectives) && escape_objective_possible) if(prob(50)) var/datum/objective/escape/escape_objective = new escape_objective.owner = owner objectives += escape_objective else var/datum/objective/escape/escape_with_identity/identity_theft = new identity_theft.owner = owner if(team_mode) identity_theft.find_target_by_role(role = ROLE_CHANGELING, role_type = 1, invert = 1) else identity_theft.find_target() objectives += identity_theft escape_objective_possible = FALSE /datum/antagonist/changeling/proc/update_changeling_icons_added() var/datum/atom_hud/antag/hud = GLOB.huds[ANTAG_HUD_CHANGELING] hud.join_hud(owner.current) set_antag_hud(owner.current, "changeling") /datum/antagonist/changeling/proc/update_changeling_icons_removed() var/datum/atom_hud/antag/hud = GLOB.huds[ANTAG_HUD_CHANGELING] hud.leave_hud(owner.current) set_antag_hud(owner.current, null) /datum/antagonist/changeling/admin_add(datum/mind/new_owner,mob/admin) . = ..() to_chat(new_owner.current, "<span class='boldannounce'>Our powers have awoken. A flash of memory returns to us...we are [changelingID], a changeling!</span>") /datum/antagonist/changeling/get_admin_commands() . = ..() if(stored_profiles.len && (owner.current.real_name != first_prof.name)) .["Transform to initial appearance."] = CALLBACK(src,PROC_REF(admin_restore_appearance)) /datum/antagonist/changeling/proc/admin_restore_appearance(mob/admin) if(!stored_profiles.len || !iscarbon(owner.current)) to_chat(admin, "<span class='danger'>Resetting DNA failed!</span>") else var/mob/living/carbon/C = owner.current first_prof.dna.transfer_identity(C, transfer_SE=1) C.real_name = first_prof.name C.updateappearance(mutcolor_update=1) C.domutcheck() // Profile /datum/changelingprofile var/name = "a bug" var/protected = 0 var/datum/dna/dna = null var/list/name_list = list() //associative list of slotname = itemname var/list/appearance_list = list() var/list/flags_cover_list = list() var/list/exists_list = list() var/list/item_state_list = list() var/underwear var/undie_color var/undershirt var/shirt_color var/socks var/socks_color /// Icon snapshot of the profile var/datum/icon_snapshot/profile_snapshot /datum/changelingprofile/Destroy() qdel(dna) . = ..() /datum/changelingprofile/proc/copy_profile(datum/changelingprofile/newprofile) newprofile.name = name newprofile.protected = protected newprofile.dna = new dna.type dna.copy_dna(newprofile.dna) newprofile.name_list = name_list.Copy() newprofile.appearance_list = appearance_list.Copy() newprofile.flags_cover_list = flags_cover_list.Copy() newprofile.exists_list = exists_list.Copy() newprofile.item_state_list = item_state_list.Copy() newprofile.underwear = underwear newprofile.undershirt = undershirt newprofile.socks = socks newprofile.profile_snapshot = profile_snapshot /datum/antagonist/changeling/xenobio name = "Xenobio Changeling" give_objectives = FALSE show_in_roundend = FALSE //These are here for admin tracking purposes only you_are_greet = FALSE antag_moodlet = FALSE /datum/antagonist/changeling/roundend_report() var/list/parts = list() var/changelingwin = 1 if(!owner.current) changelingwin = 0 parts += printplayer(owner) //Removed sanity if(changeling) because we -want- a runtime to inform us that the changelings list is incorrect and needs to be fixed. parts += "<b>Changeling ID:</b> [changelingID]." parts += "<b>Genomes Extracted:</b> [absorbedcount]" parts += " " if(objectives.len) var/count = 1 for(var/datum/objective/objective in objectives) if(objective.completable) var/completion = objective.check_completion() if(completion >= 1) parts += "<B>Objective #[count]</B>: [objective.explanation_text] <span class='greentext'><B>Success!</B></span>" else if(completion <= 0) parts += "<B>Objective #[count]</B>: [objective.explanation_text] <span class='redtext'>Fail.</span>" changelingwin = FALSE else parts += "<B>Objective #[count]</B>: [objective.explanation_text] <span class='yellowtext'>[completion*100]%</span>" else parts += "<B>Objective #[count]</B>: [objective.explanation_text]" count++ if(changelingwin) parts += "<span class='greentext'>The changeling was successful!</span>" else parts += "<span class='redtext'>The changeling has failed.</span>" return parts.Join("<br>") /datum/antagonist/changeling/antag_listing_name() return ..() + "([changelingID])" /datum/antagonist/changeling/xenobio/antag_listing_name() return ..() + "(Xenobio)"
0
0.929612
1
0.929612
game-dev
MEDIA
0.972004
game-dev
0.975831
1
0.975831
SpongePowered/Sponge
4,024
src/mixins/java/org/spongepowered/common/mixin/inventory/impl/world/inventory/AbstractContainerMenuMixin_Fabric_Inventory.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.inventory.impl.world.inventory; import com.google.common.collect.ImmutableSet; import net.minecraft.core.NonNullList; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.bridge.world.inventory.InventoryBridge; import org.spongepowered.common.inventory.fabric.Fabric; import java.util.Collection; import java.util.Set; @Mixin(AbstractContainerMenu.class) public abstract class AbstractContainerMenuMixin_Fabric_Inventory implements Fabric, InventoryBridge { @Shadow @Final public NonNullList<Slot> slots; @Shadow public abstract Slot shadow$getSlot(int slotId); @Shadow public abstract void shadow$broadcastChanges(); @Nullable private Set<InventoryBridge> all; @Override public Collection<InventoryBridge> fabric$allInventories() { if (this.all == null) { final ImmutableSet.Builder<InventoryBridge> builder = ImmutableSet.builder(); for (final Slot slot : this.slots) { if (slot.container != null) { builder.add((InventoryBridge) slot.container); } } this.all = builder.build(); } return this.all; } @Override public InventoryBridge fabric$get(final int index) { if (this.slots.isEmpty()) { return null; // Somehow we got an empty container } return (InventoryBridge) this.shadow$getSlot(index).container; } @Override public ItemStack fabric$getStack(final int index) { return this.shadow$getSlot(index).getItem(); } @Override public void fabric$setStack(final int index, final ItemStack stack) { this.shadow$getSlot(index).set(stack); } @Override public int fabric$getMaxStackSize() { return this.fabric$allInventories().stream().map(b -> b.bridge$getAdapter().inventoryAdapter$getFabric()) .mapToInt(Fabric::fabric$getMaxStackSize).max().orElse(0); } @Override public int fabric$getSize() { return this.slots.size(); } @Override public void fabric$clear() { for (final Slot slot : this.slots) { slot.set(ItemStack.EMPTY); } } @Override public void fabric$markDirty() { this.shadow$broadcastChanges(); } @Override public Set<AbstractContainerMenu> fabric$containerMenus() { return Set.of((AbstractContainerMenu) (Object) this); } }
0
0.848371
1
0.848371
game-dev
MEDIA
0.997718
game-dev
0.969373
1
0.969373
CallOfCreator/NewMod
2,532
NewMod/Options/Roles/InjectorOptions.cs
using MiraAPI.GameOptions; using MiraAPI.GameOptions.Attributes; using MiraAPI.GameOptions.OptionTypes; using MiraAPI.Utilities; using NewMod.Roles.NeutralRoles; using UnityEngine; namespace NewMod.Options.Roles.InjectorOptions; public class InjectorOptions : AbstractOptionGroup<InjectorRole> { public override string GroupName => "Injector Settings"; [ModdedNumberOption("Serum Cooldown", min: 5, max: 60, suffixType: MiraNumberSuffixes.Seconds)] public float SerumCooldown { get; set; } = 20f; [ModdedNumberOption("Max Serum Uses", min: 1, max: 10)] public float MaxSerumUses { get; set; } = 3f; [ModdedNumberOption("Injections Required to Win", min: 1, max: 10)] public float RequiredInjectCount { get; set; } = 3f; [ModdedNumberOption("Adrenaline Effect (+% Speed)", min: 10, max: 200, increment: 5, suffixType: MiraNumberSuffixes.Percent)] public float AdrenalineSpeedBoost { get; set; } = 10f; [ModdedNumberOption("Immobilize Duration", min: 1, max: 10, suffixType: MiraNumberSuffixes.Seconds)] public float ParalysisDuration { get; set; } = 4f; [ModdedNumberOption("Bounce Force (Horizontal)", min: 1f, max: 2f, increment: 0.1f)] public float BounceForceHorizontal { get; set; } = 2f; [ModdedToggleOption("Enable Random Bounce Effects")] public bool EnableBounceVariants { get; set; } = true; [ModdedNumberOption("Bounce Duration", min: 1, max: 10, suffixType: MiraNumberSuffixes.Seconds)] public float BounceDuration { get; set; } = 10f; public ModdedNumberOption BounceRotateEffect { get; } = new("Bounce Rotate Effect", 180f, min: 0f, max: 180f, increment: 10f, suffixType: MiraNumberSuffixes.None) { Visible = () => OptionGroupSingleton<InjectorOptions>.Instance.EnableBounceVariants }; public ModdedNumberOption BounceStretchScale { get; } = new("Bounce Stretch Scale", 1.5f, min: 1f, max: 1.5f, increment: 0.01f, suffixType: MiraNumberSuffixes.Multiplier) { Visible = () => OptionGroupSingleton<InjectorOptions>.Instance.EnableBounceVariants }; [ModdedNumberOption("Repel Duration", min: 1, max: 10, suffixType: MiraNumberSuffixes.Seconds)] public float RepelDuration { get; set; } = 10f; [ModdedNumberOption("Repel Range", min: 0.5f, max: 4f, increment: 0.1f)] public float RepelRange { get; set; } = 2f; [ModdedNumberOption("Repel Force", min: 0.1f, max: 2f, increment: 0.1f, suffixType: MiraNumberSuffixes.Multiplier)] public float RepelForce { get; set; } = 0.3f; }
0
0.809234
1
0.809234
game-dev
MEDIA
0.919566
game-dev
0.635638
1
0.635638
HelixNGC7293/Virus-Spread-Simulator
9,694
VirusSimulator/Library/PackageCache/com.unity.timeline@1.2.6/Editor/Manipulators/Move/MoveItemHandler.cs
using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Timeline; namespace UnityEditor.Timeline { class MoveItemHandler : IAttractable, IAttractionHandler { bool m_Grabbing; MovingItems m_LeftMostMovingItems; MovingItems m_RightMostMovingItems; HashSet<TimelineItemGUI> m_ItemGUIs; ItemsGroup m_ItemsGroup; public TrackAsset targetTrack { get; private set; } public bool allowTrackSwitch { get; private set; } int m_GrabbedModalUndoGroup = -1; readonly WindowState m_State; public MovingItems[] movingItems { get; private set; } public MoveItemHandler(WindowState state) { m_State = state; } public void Grab(IEnumerable<ITimelineItem> items, TrackAsset referenceTrack) { Grab(items, referenceTrack, Vector2.zero); } public void Grab(IEnumerable<ITimelineItem> items, TrackAsset referenceTrack, Vector2 mousePosition) { if (items == null) return; items = items.ToArray(); // Cache enumeration result if (!items.Any()) return; m_GrabbedModalUndoGroup = Undo.GetCurrentGroup(); var trackItems = items.GroupBy(c => c.parentTrack).ToArray(); var trackItemsCount = trackItems.Length; var tracks = items.Select(c => c.parentTrack).Where(x => x != null).Distinct(); movingItems = new MovingItems[trackItemsCount]; allowTrackSwitch = trackItemsCount == 1 && !trackItems.SelectMany(x => x).Any(x => x is MarkerItem); // For now, track switch is only supported when all items are on the same track and there are no items foreach (var sourceTrack in tracks) { // one push per track handles all the clips on the track TimelineUndo.PushUndo(sourceTrack, "Move Items"); // push all markers on the track because of ripple foreach (var marker in sourceTrack.GetMarkers().OfType<ScriptableObject>()) TimelineUndo.PushUndo(marker, "Move Items"); } for (var i = 0; i < trackItemsCount; ++i) { var track = trackItems[i].Key; var grabbedItems = new MovingItems(m_State, track, trackItems[i].ToArray(), referenceTrack, mousePosition, allowTrackSwitch); movingItems[i] = grabbedItems; } m_LeftMostMovingItems = null; m_RightMostMovingItems = null; foreach (var grabbedTrackItems in movingItems) { if (m_LeftMostMovingItems == null || m_LeftMostMovingItems.start > grabbedTrackItems.start) m_LeftMostMovingItems = grabbedTrackItems; if (m_RightMostMovingItems == null || m_RightMostMovingItems.end < grabbedTrackItems.end) m_RightMostMovingItems = grabbedTrackItems; } m_ItemGUIs = new HashSet<TimelineItemGUI>(); m_ItemsGroup = new ItemsGroup(items); foreach (var item in items) m_ItemGUIs.Add(item.gui); targetTrack = referenceTrack; EditMode.BeginMove(this); m_Grabbing = true; } public void Drop() { if (IsValidDrop()) { foreach (var grabbedItems in movingItems) { var track = grabbedItems.targetTrack; TimelineUndo.PushUndo(track, "Move Items"); if (EditModeUtils.IsInfiniteTrack(track) && grabbedItems.clips.Any()) ((AnimationTrack)track).ConvertToClipMode(); } EditMode.FinishMove(); Done(); } else { Cancel(); } EditMode.ClearEditMode(); } bool IsValidDrop() { return movingItems.All(g => g.canDrop); } void Cancel() { if (!m_Grabbing) return; // TODO fix undo reselection persistency // identify the clips by their playable asset, since that reference will survive the undo // This is a workaround, until a more persistent fix for selection of clips across Undo can be found var assets = movingItems.SelectMany(x => x.clips).Select(x => x.asset); Undo.RevertAllDownToGroup(m_GrabbedModalUndoGroup); // reselect the clips from the original clip var clipsToSelect = movingItems.Select(x => x.originalTrack).SelectMany(x => x.GetClips()).Where(x => assets.Contains(x.asset)).ToArray(); SelectionManager.RemoveTimelineSelection(); foreach (var c in clipsToSelect) SelectionManager.Add(c); Done(); } void Done() { foreach (var movingItem in movingItems) { foreach (var item in movingItem.items) { if (item.gui != null) item.gui.isInvalid = false; } } movingItems = null; m_LeftMostMovingItems = null; m_RightMostMovingItems = null; m_Grabbing = false; m_State.Refresh(); } public double start { get { return m_ItemsGroup.start; } } public double end { get { return m_ItemsGroup.end; } } public bool ShouldSnapTo(ISnappable snappable) { var itemGUI = snappable as TimelineItemGUI; return itemGUI != null && !m_ItemGUIs.Contains(itemGUI); } public void UpdateTrackTarget(TrackAsset track) { if (!EditMode.AllowTrackSwitch()) return; targetTrack = track; var targetTracksChanged = false; foreach (var grabbedItem in movingItems) { var prevTrackGUI = grabbedItem.targetTrack; grabbedItem.SetReferenceTrack(track); targetTracksChanged = grabbedItem.targetTrack != prevTrackGUI; } if (targetTracksChanged) EditMode.HandleTrackSwitch(movingItems); RefreshPreviewItems(); m_State.rebuildGraph |= targetTracksChanged; } public void OnGUI(Event evt) { if (!m_Grabbing) return; if (evt.type != EventType.Repaint) return; var isValid = IsValidDrop(); using (new GUIViewportScope(m_State.GetWindow().sequenceContentRect)) { foreach (var grabbedClip in movingItems) { grabbedClip.RefreshBounds(m_State, evt.mousePosition); if (!grabbedClip.HasAnyDetachedParents()) continue; grabbedClip.Draw(isValid); } if (isValid) { EditMode.DrawMoveGUI(m_State, movingItems); } else { TimelineCursors.ClearCursor(); } } } public void OnAttractedEdge(IAttractable attractable, ManipulateEdges manipulateEdges, AttractedEdge edge, double time) { double offset; if (edge == AttractedEdge.Right) { var duration = end - start; var startTime = time - duration; startTime = EditMode.AdjustStartTime(m_State, m_RightMostMovingItems, startTime); offset = startTime + duration - end; } else { if (edge == AttractedEdge.Left) time = EditMode.AdjustStartTime(m_State, m_LeftMostMovingItems, time); offset = time - start; } if (start + offset < 0.0) offset = -start; if (!offset.Equals(0.0)) { foreach (var grabbedClips in movingItems) grabbedClips.start += offset; EditMode.UpdateMove(); RefreshPreviewItems(); } } public void RefreshPreviewItems() { foreach (var movingItemsGroup in movingItems) { // Check validity var valid = ValidateItemDrag(movingItemsGroup); foreach (var item in movingItemsGroup.items) { if (item.gui != null) item.gui.isInvalid = !valid; } movingItemsGroup.canDrop = valid; } } static bool ValidateItemDrag(ItemsPerTrack itemsGroup) { //TODO-marker: this is to prevent the drag operation from being canceled when moving only markers if (itemsGroup.clips.Any()) { if (itemsGroup.targetTrack == null) return false; if (itemsGroup.targetTrack.lockedInHierarchy) return false; if (itemsGroup.items.Any(i => !i.IsCompatibleWithTrack(itemsGroup.targetTrack))) return false; return EditMode.ValidateDrag(itemsGroup); } return true; } public void OnTrackDetach() { EditMode.OnTrackDetach(movingItems); } } }
0
0.977762
1
0.977762
game-dev
MEDIA
0.832212
game-dev
0.998041
1
0.998041
Decane/SRP
8,393
gamedata/configs/scripts/red_forest/red_bridge_csky_commander_logic.ltx
;-------------------------------------------------------------------------------------------------- ; ; Lebedev ; ; Vandals Immortality Fix v1.1 ; By Vandal aka SpeedCanHurt ; 09.11.2008 ; ; Not to be modified and redistributed without the permission of the creator ; For permission, email speedcanhurt@fastmail.fm ; ;-------------------------------------------------------------------------------------------------- [logic] active = smartcover@commander_wait relation = friend post_combat_time = 0,0 [smartcover@commander_wait] invulnerable = true meet = no_meet combat_ignore_cond = {!is_enemy_actor} cover_name = red_bridge_east_smartcover_com loophole_name = lh_4 on_actor_dist_le = 5 | smartcover@actor_come %+mil_freedom_com_talked% on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_down_done} smartcover@commander_wait3 on_info3 = {+red_bridge_actor_in_position} smartcover@commander_wait2 [smartcover@actor_come] invulnerable = true combat_ignore_cond = {!is_enemy_actor} cover_name = red_bridge_east_smartcover_com cover_state = idle_target on_game_timer = 10 | smartcover@actor_come2 %=play_sound(red_bridge_actor_come:csky:mar_csky_commander_name)% on_actor_dist_ge_nvis = 7 | smartcover@commander_wait2 %+red_bridge_actor_talk_with_cs_commander% on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_actor_talk_with_cs_commander} smartcover@commander_wait2 meet = no_meet [smartcover@actor_come2] invulnerable = true combat_ignore_cond = {!is_enemy_actor} cover_name = red_bridge_east_smartcover_com cover_state = idle_target on_signal = sound_end | smartcover@commander_wait2 %+red_bridge_actor_talk_with_cs_commander% on_actor_dist_ge_nvis = 7 | smartcover@commander_wait2 %+red_bridge_actor_talk_with_cs_commander% on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_actor_talk_with_cs_commander} smartcover@commander_wait2 meet = no_meet [smartcover@commander_wait2] invulnerable = true meet = no_meet combat_ignore_cond = {!is_enemy_actor} cover_name = red_bridge_east_smartcover_com loophole_name = lh_4 on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_down_done} smartcover@commander_wait3 [smartcover@commander_wait3] invulnerable = true use_in_combat = true meet = no_meet combat_ignore_cond = {!is_enemy_actor} cover_name = red_bridge_east_smartcover_com loophole_name = lh_4 on_game_timer = 150 | walker@bridge_walk_work_6 %+red_bridge_cs_commander_wait_1% on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_cs_commander_wait_1} walker@bridge_walk_work_6 [walker@bridge_walk_work_6] invulnerable = true combat_ignore_cond = {!is_enemy_actor} path_walk = red_bridge_csky_smart_bridge_walk def_state_moving1 = assault def_state_moving2 = assault def_state_moving3 = assault on_signal = action | camper@assault_work_6 %+red_bridge_cs_commander_wait_2% on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_cs_commander_wait_2} camper@assault_work_6 meet = no_meet [camper@assault_work_6] invulnerable = true out_restr = red_bridge_attack_restr path_walk = red_bridge_csky_smart_soldier_2_assault_walk path_look = red_bridge_csky_smart_soldier_2_assault_look radius = 20 no_retreat = true def_state_moving = assault def_state_campering = threat def_state_campering_fire = threat_fire on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_bandit_out} camper@wait_talk_work_6 meet = no_meet [camper@wait_talk_work_6] invulnerable = true out_restr = red_bridge_bandit_restr path_walk = red_bridge_csky_smart_comander_talk_walk path_look = red_bridge_csky_smart_comander_talk_1_look meet = no_meet on_game_timer = 600 | camper@talk_work_6 %+red_bridge_cs_commander_wait_3% on_actor_dist_le_nvis = 10 | camper@talk_work_6 %+red_bridge_cs_commander_wait_3% on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_cs_commander_wait_3} camper@talk_work_6 [camper@talk_work_6] invulnerable = true out_restr = red_bridge_bandit_restr path_walk = red_bridge_csky_smart_comander_talk_walk path_look = red_bridge_csky_smart_comander_talk_1_look on_signal = action | {+red_bridge_leshiy_redy} camper@talk_leshiy_work_6 %+red_bridge_thanks_leshiy =play_sound(red_bridge_thanks_leshiy)% on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_thanks_leshiy} camper@talk_leshiy_work_6 meet = no_meet [camper@talk_leshiy_work_6] invulnerable = true out_restr = red_bridge_bandit_restr path_walk = red_bridge_csky_smart_comander_talk_walk path_look = red_bridge_csky_smart_comander_talk_1_look on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_thanks_leshiy_reply} camper@reply2_work_6 meet = no_meet [camper@reply2_work_6] invulnerable = true out_restr = red_bridge_bandit_restr path_walk = red_bridge_csky_smart_comander_talk_walk path_look = red_bridge_csky_smart_comander_talk_1_look on_game_timer = 50 | camper@reply3_work_6 %+red_bridge_thanks_leshiy_reply2 =play_sound(red_bridge_thanks_leshiy_reply2)% on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_thanks_leshiy_reply2} camper@reply3_work_6 meet = no_meet [camper@reply3_work_6] invulnerable = true out_restr = red_bridge_bandit_restr path_walk = red_bridge_csky_smart_comander_talk_walk path_look = red_bridge_csky_smart_comander_talk_1_look on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_thanks_leshiy_reply3} camper@reply4_work_6 meet = no_meet [camper@reply4_work_6] invulnerable = true out_restr = red_bridge_bandit_restr path_walk = red_bridge_csky_smart_comander_talk_walk path_look = red_bridge_csky_smart_comander_talk_1_look on_game_timer = 30 | camper@wait_talk2_work_6 %+red_bridge_thanks_leshiy_reply4 =play_sound(red_bridge_thanks_leshiy_reply4)% on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_thanks_leshiy_reply4} camper@wait_talk2_work_6 meet = no_meet [camper@wait_talk2_work_6] invulnerable = true meet = no_meet out_restr = red_bridge_bandit_restr path_walk = red_bridge_csky_smart_comander_talk_2_walk path_look = red_bridge_csky_smart_comander_talk_2_look on_signal = action2 | {+red_bridge_cs1 +red_bridge_cs2 +red_bridge_cs3 +red_bridge_cs4 +red_bridge_cs5} camper@talk2_work_6 %+red_bridge_cs_commander_wait_4% on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_cs_commander_wait_4} camper@talk2_work_6 [camper@talk2_work_6] invulnerable = true out_restr = red_bridge_bandit_restr path_walk = red_bridge_csky_smart_comander_talk_2_walk path_look = red_bridge_csky_smart_comander_talk_2_look on_game_timer = 20 | camper@talk3_work_6 %+red_bridge_finished =play_sound(red_bridge_finished:csky:mar_csky_commander_name)% on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_finished} camper@talk3_work_6 meet = no_meet [camper@talk3_work_6] invulnerable = true out_restr = red_bridge_bandit_restr path_walk = red_bridge_csky_smart_comander_talk_2_walk path_look = red_bridge_csky_smart_comander_talk_2_look on_signal = sound_end | walker@bridge_guard_work_6 %+red_bridge_csky_go_limansk% on_info = {+stc_final_movie} %=destroy_object% on_info2 = {+red_bridge_csky_go_limansk} walker@bridge_guard_work_6 meet = no_meet [walker@bridge_guard_work_6] invulnerable = true meet = meet out_restr = red_bridge_bandit_restr path_walk = red_bridge_csky_smart_soldier_4_guard_walk path_look = red_bridge_csky_smart_soldier_4_guard_look on_info = {+stc_final_movie} %=destroy_object% on_info2 = {=dist_to_actor_ge(150) !actor_see_npc} %=destroy_object% [patrol@go_limansk_work_6] invulnerable = true path_walk = red_bridge_csky_smart_go_limansk_walk path_look = red_bridge_csky_smart_go_limansk_look commander = true on_signal = action | nil %=destroy_object% meet = no_meet on_info = {+stc_final_movie} %=destroy_object% [meet] invulnerable = true meet_state = 5 | ward@nil meet_state_wpn = 5 | ward@nil victim = 5 | actor victim_wpn = 5 | actor sound_start = mar_csky_leader_meet sound_stop = mar_csky_leader_meet_bye quest_npc = true use = true use_wpn = true
0
0.955964
1
0.955964
game-dev
MEDIA
0.985776
game-dev
0.957815
1
0.957815
nasa/fpp
1,637
compiler/tools/fpp-to-cpp/test/component/impl/ActiveExternalStateMachines.template.ref.hpp
// ====================================================================== // \title ActiveExternalStateMachines.hpp // \author [user name] // \brief hpp file for ActiveExternalStateMachines component implementation class // ====================================================================== #ifndef ExternalSm_ActiveExternalStateMachines_HPP #define ExternalSm_ActiveExternalStateMachines_HPP #include "ActiveExternalStateMachinesComponentAc.hpp" namespace ExternalSm { class ActiveExternalStateMachines final : public ActiveExternalStateMachinesComponentBase { public: // ---------------------------------------------------------------------- // Component construction and destruction // ---------------------------------------------------------------------- //! Construct ActiveExternalStateMachines object ActiveExternalStateMachines( const char* const compName //!< The component name ); //! Destroy ActiveExternalStateMachines object ~ActiveExternalStateMachines(); private: // ---------------------------------------------------------------------- // Overflow hook implementations for external state machines // ---------------------------------------------------------------------- //! Overflow hook implementation for sm5 void sm5_stateMachineOverflowHook( const ExternalSm::ActiveExternalStateMachines_S2_Interface::ActiveExternalStateMachines_S2_Signals signal, //!< The state machine signal const Fw::SmSignalBuffer& data //!< The state machine data ) override; }; } #endif
0
0.859752
1
0.859752
game-dev
MEDIA
0.472387
game-dev
0.52712
1
0.52712
iTXTech/Genisys
1,163
src/pocketmine/inventory/TemporaryInventory.php
<?php /** * * _____ _____ __ _ _ _____ __ __ _____ * / ___| | ____| | \ | | | | / ___/ \ \ / / / ___/ * | | | |__ | \| | | | | |___ \ \/ / | |___ * | | _ | __| | |\ | | | \___ \ \ / \___ \ * | |_| | | |___ | | \ | | | ___| | / / ___| | * \_____/ |_____| |_| \_| |_| /_____/ /_/ /_____/ * * 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. * * @author iTX Technologies * @link https://itxtech.org * */ namespace pocketmine\inventory; use pocketmine\Player; abstract class TemporaryInventory extends ContainerInventory{ //TODO abstract public function getResultSlotIndex(); public function onClose(Player $who){ foreach($this->getContents() as $slot => $item){ if($slot === $this->getResultSlotIndex()){ //Do not drop the item in the result slot - it is a virtual item and does not actually exist. continue; } $who->dropItem($item); } $this->clearAll(); } }
0
0.786971
1
0.786971
game-dev
MEDIA
0.543398
game-dev
0.842468
1
0.842468
Dreamtowards/Ethertia
1,654
lib/jolt-3.0.1/Samples/Tests/General/SimpleTest.cpp
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics) // SPDX-FileCopyrightText: 2021 Jorrit Rouwe // SPDX-License-Identifier: MIT #include <TestFramework.h> #include <Tests/General/SimpleTest.h> #include <Jolt/Physics/Collision/Shape/BoxShape.h> #include <Jolt/Physics/Collision/Shape/SphereShape.h> #include <Jolt/Physics/Body/BodyCreationSettings.h> #include <Jolt/Physics/Body/BodyActivationListener.h> #include <Layers.h> JPH_IMPLEMENT_RTTI_VIRTUAL(SimpleTest) { JPH_ADD_BASE_CLASS(SimpleTest, Test) } SimpleTest::~SimpleTest() { // Unregister activation listener mPhysicsSystem->SetBodyActivationListener(nullptr); } void SimpleTest::Initialize() { // Register activation listener mPhysicsSystem->SetBodyActivationListener(&mBodyActivationListener); // Floor CreateFloor(); RefConst<Shape> box_shape = new BoxShape(Vec3(0.5f, 1.0f, 2.0f)); // Dynamic body 1 Body &body1 = *mBodyInterface->CreateBody(BodyCreationSettings(box_shape, RVec3(0, 10, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING)); mBodyInterface->AddBody(body1.GetID(), EActivation::Activate); // Dynamic body 2 Body &body2 = *mBodyInterface->CreateBody(BodyCreationSettings(box_shape, RVec3(5, 10, 0), Quat::sRotation(Vec3::sAxisX(), 0.25f * JPH_PI), EMotionType::Dynamic, Layers::MOVING)); mBodyInterface->AddBody(body2.GetID(), EActivation::Activate); // Dynamic body 3 Body &body3 = *mBodyInterface->CreateBody(BodyCreationSettings(new SphereShape(2.0f), RVec3(10, 10, 0), Quat::sRotation(Vec3::sAxisX(), 0.25f * JPH_PI), EMotionType::Dynamic, Layers::MOVING)); mBodyInterface->AddBody(body3.GetID(), EActivation::Activate); }
0
0.851634
1
0.851634
game-dev
MEDIA
0.817749
game-dev
0.53525
1
0.53525
SkelletonX/DDTank4.1
11,370
Source Server/Game.Server.Scripts/AI/NPC/FiveNormalThirdBoss.cs
using System; using System.Collections.Generic; using System.Text; using Game.Logic.AI; using Game.Logic.Phy.Object; using Game.Logic; using System.Drawing; using Game.Logic.Actions; using Bussiness; using Game.Logic.Effects; namespace GameServerScript.AI.NPC { public class FiveNormalThirdBoss : ABrain { private int m_attackTurn = 0; protected Player m_targer; private List<PhysicalObj> m_objects = new List<PhysicalObj>(); private PhysicalObj m_effectTop; private SimpleNpc m_npc1; private SimpleNpc m_npc2; private SimpleNpc m_npc3; private int m_npcId1 = 5122; private int m_npcId2 = 5123; private int m_npcId3 = 5124; private int m_npcEnemyId = 5104; private int m_countForzenCanKill = 2; private int isSay = 0; private List<Point> m_pointCreateNpc2 = new List<Point> { new Point(1518, 699), new Point(500, 699) }; private string[] PersonAttackSay = { LanguageMgr.GetTranslation("GameServerScript.AI.NPC.FiveNormalBossThird.msg2"), LanguageMgr.GetTranslation("GameServerScript.AI.NPC.FiveNormalBossThird.msg3") }; private string[] CallNpc3Say = { "Quero torturar sem piedade <span class='red'>{0}</span>, sem piedade!", // GameServerScript.AI.NPC.FiveNormalBossThird.msg4 "<span class='red'>{0}</span>, já chegou a sua vez!", // GameServerScript.AI.NPC.FiveNormalBossThird.msg5 "Feche, quero fechar <span class='red'>{0}</span>!", // GameServerScript.AI.NPC.FiveNormalBossThird.msg6 "<span class='red'>{0}</span>, Veja isso", // GameServerScript.AI.NPC.FiveNormalBossThird.msg7 "Todo o mundo olhê, <span class='red'>{0}</span> já será executado." // GameServerScript.AI.NPC.FiveNormalBossThird.msg8 }; private string[] GlobalAttackSay = { LanguageMgr.GetTranslation("GameServerScript.AI.NPC.FiveNormalBossThird.msg9"), LanguageMgr.GetTranslation("GameServerScript.AI.NPC.FiveNormalBossThird.msg10") }; private string[] CallNpc1Say = { LanguageMgr.GetTranslation("GameServerScript.AI.NPC.FiveNormalBossThird.msg11"), LanguageMgr.GetTranslation("GameServerScript.AI.NPC.FiveNormalBossThird.msg12") }; private string[] OnShootedChat = { LanguageMgr.GetTranslation("GameServerScript.AI.NPC.FiveNormalBossThird.msg13"), LanguageMgr.GetTranslation("GameServerScript.AI.NPC.FiveNormalBossThird.msg14"), LanguageMgr.GetTranslation("GameServerScript.AI.NPC.FiveNormalBossThird.msg15") }; private string[] KillPlayerChat = { LanguageMgr.GetTranslation("GameServerScript.AI.NPC.FiveNormalBossThird.msg16"), LanguageMgr.GetTranslation("GameServerScript.AI.NPC.FiveNormalBossThird.msg17"), LanguageMgr.GetTranslation("GameServerScript.AI.NPC.FiveNormalBossThird.msg18") }; public override void OnBeginSelfTurn() { base.OnBeginSelfTurn(); } public override void OnBeginNewTurn() { base.OnBeginNewTurn(); m_body.CurrentDamagePlus = 1; m_body.CurrentShootMinus = 1; isSay = 0; foreach (PhysicalObj obj in m_objects) { Game.RemovePhysicalObj(obj, true); } m_objects = new List<PhysicalObj>(); } public override void OnCreated() { base.OnCreated(); Body.MaxBeatDis = 200; } public override void OnStartAttacking() { base.OnStartAttacking(); m_attackTurn++; switch(m_attackTurn) { case 1: PersonAttack(); break; case 2: if (m_npc2 != null && m_npc2.IsLiving) PersonAttack(); else CallNpc2Attack(); break; case 3: CallGlobalAttack(); break; case 4: if (m_npc3 != null && m_npc3.IsLiving) PersonAttack(); else CallNpc3Attack(); break; case 5: if(m_npc1 != null && m_npc1.IsLiving) CallGlobalAttack(); else CallNpc1Attack(); m_attackTurn = 0; break; } } private void CallGlobalAttack() { Body.ChangeDirection(-1, 500); Body.MoveTo(1000, 641, "fly", 1000, new LivingCallBack(RunGlobalAttack), 10); } private void RunGlobalAttack() { Body.CurrentDamagePlus = 2f; ((SimpleBoss)Body).RandomSay(GlobalAttackSay, 0, 1000, 0); Body.PlayMovie("beatA", 1200, 0); Body.CallFuction(new LivingCallBack(CreateGlobalAttackEffect), 2500); Body.RangeAttacking(Body.X - 10000, Body.X + 10000, "cry", 4500, true); Body.PlayMovie("beatC", 4000, 2000); } private void CreateGlobalAttackEffect() { m_effectTop = ((PVEGame)Game).CreateLayerTop(500, 300, "", "asset.game.4.heip", "", 1, 1); Body.CallFuction(new LivingCallBack(RemoveGlobalAttackEffect), 2400); } private void RemoveGlobalAttackEffect() { if (m_effectTop != null) Game.RemovePhysicalObj(m_effectTop, true); } private void PersonAttack() { m_targer = Game.FindRandomPlayer(); if(m_targer != null) { ((SimpleBoss)Body).RandomSay(PersonAttackSay, 0, 1000, 0); Body.MoveTo(m_targer.X, m_targer.Y - 100, "fly", 2000, new LivingCallBack(BeatE), 10); } } private void CallNpc1Attack() { ((SimpleBoss)Body).RandomSay(CallNpc1Say, 0, 1000, 0); Body.PlayMovie("beatD", 1200, 0); Body.CallFuction(new LivingCallBack(CreateNpc1), 3800); } private void CreateNpc1() { int randX = Game.Random.Next(440, 1570); LivingConfig config = ((PVEGame)Game).BaseLivingConfig(); config.DamageForzen = true; config.CanTakeDamage = false; config.IsFly = true; m_npc1 = ((SimpleBoss)Body).CreateChild(m_npcId1, randX, 580, 0, 1, false, config); m_npc1.Properties2 = m_countForzenCanKill; } private void CallNpc3Attack() { m_targer = Game.FindRandomPlayer(); if (m_targer != null) { Body.ChangeDirection(m_targer, 500); int randSay = Game.Random.Next(CallNpc3Say.Length); Body.Say(string.Format(CallNpc3Say[randSay], m_targer.PlayerDetail.PlayerCharacter.NickName), 0, 1000); Body.PlayMovie("beatD", 3000, 0); Body.CallFuction(new LivingCallBack(CreateNpc3), 5000); } } private void CreateNpc3() { LivingConfig config = ((PVEGame)Game).BaseLivingConfig(); config.IsFly = true; m_npc3 = ((SimpleBoss)Body).CreateChild(m_npcId3, 114, 453, 0, 1, false, config); m_npc3.Properties1 = m_targer.Id; m_npc3.Properties2 = new Point(m_targer.X, m_targer.Y); int maxDelay = Game.GetHighDelayTurn(); ((PVEGame)Game).SendObjectFocus(m_targer, 1, 1500, 0); Body.CallFuction(new LivingCallBack(CreateEffectMovePlayer), 2500); Body.CallFuction(new LivingCallBack(BlockAndHidePlayer), 3500); m_targer.BoltMove(m_npc3.X, m_npc3.Y, 3900); ((PVEGame)Game).SendObjectFocus(m_npc3, 1, 4000, 0); m_npc3.PlayMovie("in", 5000, 4000); ((PVEGame)Game).PveGameDelay = maxDelay + 1; } private void CallNpc2Attack() { m_targer = Game.FindRandomPlayer(); if(m_targer != null) { Body.ChangeDirection(m_targer, 500); int randSay = Game.Random.Next(CallNpc3Say.Length); Body.Say(string.Format(CallNpc3Say[randSay], m_targer.PlayerDetail.PlayerCharacter.NickName), 0, 1000); Body.PlayMovie("beatD", 3000, 0); Body.CallFuction(new LivingCallBack(CreateNpc2), 5000); } } private void CreateNpc2() { int createPoint = Game.Random.Next(m_pointCreateNpc2.Count); m_npc2 = ((SimpleBoss)Body).CreateChild(m_npcId2, m_pointCreateNpc2[createPoint].X, m_pointCreateNpc2[createPoint].Y, 0, -1, true); m_npc2.Properties1 = m_targer.Id; int maxDelay = Game.GetHighDelayTurn(); ((PVEGame)Game).SendObjectFocus(m_targer, 1, 4000, 0); Body.CallFuction(new LivingCallBack(CreateEffectMovePlayer), 5000); Body.CallFuction(new LivingCallBack(BlockAndHidePlayer), 6000); m_targer.BoltMove(m_npc2.X, m_npc2.Y, 6100); ((PVEGame)Game).SendObjectFocus(m_npc2, 1, 6800, 0); m_npc2.PlayMovie("AtoB", 7500, 0); m_npc2.PlayMovie("beatA", 10000, 2000); Body.BeatDirect(m_targer, "", 11000, 1, 1); ((PVEGame)Game).PveGameDelay = maxDelay + 1; } private void CreateEffectMovePlayer() { m_objects.Add(((PVEGame)Game).Createlayer(m_targer.X, m_targer.Y, "", "asset.game.4.lanhuo", "", 1, 1)); } private void BlockAndHidePlayer() { m_targer.SetVisible(false); m_targer.BlockTurn = true; } private void BeatE() { Body.Beat(m_targer, "beatE", 100, 1, 500, 1, 1); Body.CallFuction(new LivingCallBack(BackToDefaultPoint), 3500); } private void BackToDefaultPoint() { int randX = Game.Random.Next(376, 1643); int randY = Game.Random.Next(112, 593); Body.MoveTo(randX, randY, "fly", 500, 10); } public override void OnDie() { base.OnDie(); } public override void OnStopAttacking() { base.OnStopAttacking(); } public override void OnAfterTakedBomb() { if(Body.IsLiving == false) { //Body.MoveTo(1000, 299, "fly", 1000, CreateEffectEndGame, 10); } } public override void OnShootedSay(int delay) { base.OnShootedSay(delay); int index = Game.Random.Next(0, OnShootedChat.Length); if (isSay == 0 && Body.IsLiving == true) { Body.Say(OnShootedChat[index], 0, 1000 + delay, 0); isSay = 1; } } public override void OnKillPlayerSay() { base.OnKillPlayerSay(); ((SimpleBoss)Body).RandomSay(KillPlayerChat, 0, 0, 2000); } } }
0
0.798175
1
0.798175
game-dev
MEDIA
0.973711
game-dev
0.832553
1
0.832553
SoWeBegin/MicrovoltsEmulator
4,706
MainServer/include/Handlers/Item/ItemUpgradeHandler.h
#ifndef ITEM_ENERGY_INSERTION_HANDLER #define ITEM_ENERGY_INSERTION_HANDLER #include "../../../include/Network/MainSession.h" #include "../../../include/Network/MainSessionManager.h" #include "Network/Packet.h" #include "../../Structures/PlayerLists/Friend.h" #include "DeleteItemHandler.h" #include "../../Structures/Item/SpawnedItem.h" #include <Utils/Utils.h> namespace Main { namespace Handlers { enum SpecialItems { SUPER_GLUE = 4305004, ENERGY_REFUND_100 = 4305016, ENERGY_REFUND_30 = 4305014, ENERGY_REFUND_50 = 4305015, }; inline void handleItemUpgrade(const Common::Network::Packet& request, std::shared_ptr<Main::Network::Session> session) { START_BENCHMARK if (session->getPlayer().getPlayerState() != Common::Enums::STATE_INVENTORY) { session->sendMessage("Error: An item can be upgraded only while your state is STATE_INVENTORY!"); return; } const auto receivedExtra = request.getExtra(); if (receivedExtra == 0) { // Client ACK: user adds energy to a weapon const Main::ClientData::ItemAddEnergy itemAddEnergy = Main::Details::parseData<Main::ClientData::ItemAddEnergy>(request); if (itemAddEnergy.usedEnergy > session->getAccountInfo().battery) return; session->addEnergyToItem(itemAddEnergy, request.getOption(), request.getMission()); } else if (receivedExtra == 37 && request.getMission() < Enums::UPGRADE_TYPE_MAX) { // upgrade std::vector<Main::Structures::ItemSerialInfo> itemSerialInfos; if (request.getDataSize() % 8 != 0) return; const std::uint32_t maxLoops = request.getDataSize() / 8; for (std::uint32_t i = 0; i < maxLoops; ++i) { itemSerialInfos.push_back(Main::Details::parseData<Main::Structures::ItemSerialInfo>(request, i * 8)); } if (itemSerialInfos.empty()) { session->sendMessage("[handleItemUpgrade] error: no items in the upgrade request."); return; } const auto& firstItemSerialInfo = itemSerialInfos.front(); const auto firstItemIdOpt = session->getPlayer().findItemIdBySerialInfo(firstItemSerialInfo); // itemID of new weapon after upgrade if (!firstItemIdOpt) { session->sendMessage("[handleItemUpgrade] error: itemIdOpt was nullopt for first item: " + std::to_string(firstItemSerialInfo.itemNumber)); return; } const auto upgradeInfo = Common::ConstantDatabase::CdbSingleton<Common::ConstantDatabase::CdbUpgradeInfo>::getInstance().getEntry(*firstItemIdOpt); if (!upgradeInfo) { session->sendMessage("[handleItemUpgrade] error: upgradeInfo not found for itemID " + std::to_string(firstItemSerialInfo.itemNumber)); return; } bool useEnergyRefund = false; bool useGlue = false; for (const auto& itemSerialInfo : itemSerialInfos) { const auto itemIdOpt = session->getPlayer().findItemIdBySerialInfo(itemSerialInfo); if (!itemIdOpt) { session->sendMessage("[handleItemUpgrade] error: itemIdOpt was nullopt for item: " + std::to_string(itemSerialInfo.itemNumber)); return; } if (!useEnergyRefund) useEnergyRefund = *itemIdOpt == SpecialItems::ENERGY_REFUND_100 || *itemIdOpt == SpecialItems::ENERGY_REFUND_30 || *itemIdOpt == SpecialItems::ENERGY_REFUND_50; if (!useGlue) useGlue = *itemIdOpt == SpecialItems::SUPER_GLUE; } if (session->upgradeWeapon(*firstItemIdOpt, firstItemSerialInfo, upgradeInfo->ui_parentid, request.getMission(), request.getOption(), useEnergyRefund, useGlue)) { for (std::size_t i = 1; i < itemSerialInfos.size(); ++i) { session->deleteItem(itemSerialInfos[i], "Item deleted after it was used while upgrading a weapon (Example: Super Glue item"); } } } else if (receivedExtra == 53) { // upgrade reset session->resetUpgrade(Main::Details::parseData<Main::ClientData::UpgradeReset>(request)); } END_BENCHMARK(handleItemUpgrade, session) } } } #endif
0
0.979299
1
0.979299
game-dev
MEDIA
0.878618
game-dev
0.974518
1
0.974518
amethyst/rustrogueliketutorial
17,524
chapter-20-magicmapping/src/main.rs
extern crate serde; use rltk::{GameState, Rltk, Point}; use specs::prelude::*; use specs::saveload::{SimpleMarker, SimpleMarkerAllocator}; mod components; pub use components::*; mod map; pub use map::*; mod player; use player::*; mod rect; pub use rect::Rect; mod visibility_system; use visibility_system::VisibilitySystem; mod monster_ai_system; use monster_ai_system::MonsterAI; mod map_indexing_system; use map_indexing_system::MapIndexingSystem; mod melee_combat_system; use melee_combat_system::MeleeCombatSystem; mod damage_system; use damage_system::DamageSystem; mod gui; mod gamelog; mod spawner; mod inventory_system; use inventory_system::{ ItemCollectionSystem, ItemUseSystem, ItemDropSystem, ItemRemoveSystem }; pub mod saveload_system; pub mod random_table; pub mod particle_system; pub mod hunger_system; #[derive(PartialEq, Copy, Clone)] pub enum RunState { AwaitingInput, PreRun, PlayerTurn, MonsterTurn, ShowInventory, ShowDropItem, ShowTargeting { range : i32, item : Entity}, MainMenu { menu_selection : gui::MainMenuSelection }, SaveGame, NextLevel, ShowRemoveItem, GameOver, MagicMapReveal { row : i32 } } pub struct State { pub ecs: World } impl State { fn run_systems(&mut self) { let mut vis = VisibilitySystem{}; vis.run_now(&self.ecs); let mut mob = MonsterAI{}; mob.run_now(&self.ecs); let mut mapindex = MapIndexingSystem{}; mapindex.run_now(&self.ecs); let mut melee = MeleeCombatSystem{}; melee.run_now(&self.ecs); let mut damage = DamageSystem{}; damage.run_now(&self.ecs); let mut pickup = ItemCollectionSystem{}; pickup.run_now(&self.ecs); let mut itemuse = ItemUseSystem{}; itemuse.run_now(&self.ecs); let mut drop_items = ItemDropSystem{}; drop_items.run_now(&self.ecs); let mut item_remove = ItemRemoveSystem{}; item_remove.run_now(&self.ecs); let mut hunger = hunger_system::HungerSystem{}; hunger.run_now(&self.ecs); let mut particles = particle_system::ParticleSpawnSystem{}; particles.run_now(&self.ecs); self.ecs.maintain(); } } impl GameState for State { fn tick(&mut self, ctx : &mut Rltk) { let mut newrunstate; { let runstate = self.ecs.fetch::<RunState>(); newrunstate = *runstate; } ctx.cls(); particle_system::cull_dead_particles(&mut self.ecs, ctx); match newrunstate { RunState::MainMenu{..} => {} RunState::GameOver{..} => {} _ => { draw_map(&self.ecs, ctx); let positions = self.ecs.read_storage::<Position>(); let renderables = self.ecs.read_storage::<Renderable>(); let map = self.ecs.fetch::<Map>(); let mut data = (&positions, &renderables).join().collect::<Vec<_>>(); data.sort_by(|&a, &b| b.1.render_order.cmp(&a.1.render_order) ); for (pos, render) in data.iter() { let idx = map.xy_idx(pos.x, pos.y); if map.visible_tiles[idx] { ctx.set(pos.x, pos.y, render.fg, render.bg, render.glyph) } } gui::draw_ui(&self.ecs, ctx); } } match newrunstate { RunState::PreRun => { self.run_systems(); self.ecs.maintain(); newrunstate = RunState::AwaitingInput; } RunState::AwaitingInput => { newrunstate = player_input(self, ctx); } RunState::PlayerTurn => { self.run_systems(); self.ecs.maintain(); match *self.ecs.fetch::<RunState>() { RunState::MagicMapReveal{ .. } => newrunstate = RunState::MagicMapReveal{ row: 0 }, _ => newrunstate = RunState::MonsterTurn } } RunState::MonsterTurn => { self.run_systems(); self.ecs.maintain(); newrunstate = RunState::AwaitingInput; } RunState::ShowInventory => { let result = gui::show_inventory(self, ctx); match result.0 { gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput, gui::ItemMenuResult::NoResponse => {} gui::ItemMenuResult::Selected => { let item_entity = result.1.unwrap(); let is_ranged = self.ecs.read_storage::<Ranged>(); let is_item_ranged = is_ranged.get(item_entity); if let Some(is_item_ranged) = is_item_ranged { newrunstate = RunState::ShowTargeting{ range: is_item_ranged.range, item: item_entity }; } else { let mut intent = self.ecs.write_storage::<WantsToUseItem>(); intent.insert(*self.ecs.fetch::<Entity>(), WantsToUseItem{ item: item_entity, target: None }).expect("Unable to insert intent"); newrunstate = RunState::PlayerTurn; } } } } RunState::ShowDropItem => { let result = gui::drop_item_menu(self, ctx); match result.0 { gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput, gui::ItemMenuResult::NoResponse => {} gui::ItemMenuResult::Selected => { let item_entity = result.1.unwrap(); let mut intent = self.ecs.write_storage::<WantsToDropItem>(); intent.insert(*self.ecs.fetch::<Entity>(), WantsToDropItem{ item: item_entity }).expect("Unable to insert intent"); newrunstate = RunState::PlayerTurn; } } } RunState::ShowRemoveItem => { let result = gui::remove_item_menu(self, ctx); match result.0 { gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput, gui::ItemMenuResult::NoResponse => {} gui::ItemMenuResult::Selected => { let item_entity = result.1.unwrap(); let mut intent = self.ecs.write_storage::<WantsToRemoveItem>(); intent.insert(*self.ecs.fetch::<Entity>(), WantsToRemoveItem{ item: item_entity }).expect("Unable to insert intent"); newrunstate = RunState::PlayerTurn; } } } RunState::ShowTargeting{range, item} => { let result = gui::ranged_target(self, ctx, range); match result.0 { gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput, gui::ItemMenuResult::NoResponse => {} gui::ItemMenuResult::Selected => { let mut intent = self.ecs.write_storage::<WantsToUseItem>(); intent.insert(*self.ecs.fetch::<Entity>(), WantsToUseItem{ item, target: result.1 }).expect("Unable to insert intent"); newrunstate = RunState::PlayerTurn; } } } RunState::MainMenu{ .. } => { let result = gui::main_menu(self, ctx); match result { gui::MainMenuResult::NoSelection{ selected } => newrunstate = RunState::MainMenu{ menu_selection: selected }, gui::MainMenuResult::Selected{ selected } => { match selected { gui::MainMenuSelection::NewGame => newrunstate = RunState::PreRun, gui::MainMenuSelection::LoadGame => { saveload_system::load_game(&mut self.ecs); newrunstate = RunState::AwaitingInput; saveload_system::delete_save(); } gui::MainMenuSelection::Quit => { ::std::process::exit(0); } } } } } RunState::GameOver => { let result = gui::game_over(ctx); match result { gui::GameOverResult::NoSelection => {} gui::GameOverResult::QuitToMenu => { self.game_over_cleanup(); newrunstate = RunState::MainMenu{ menu_selection: gui::MainMenuSelection::NewGame }; } } } RunState::SaveGame => { saveload_system::save_game(&mut self.ecs); newrunstate = RunState::MainMenu{ menu_selection : gui::MainMenuSelection::LoadGame }; } RunState::NextLevel => { self.goto_next_level(); newrunstate = RunState::PreRun; } RunState::MagicMapReveal{row} => { let mut map = self.ecs.fetch_mut::<Map>(); for x in 0..MAPWIDTH { let idx = map.xy_idx(x as i32,row); map.revealed_tiles[idx] = true; } if row as usize == MAPHEIGHT-1 { newrunstate = RunState::MonsterTurn; } else { newrunstate = RunState::MagicMapReveal{ row: row+1 }; } } } { let mut runwriter = self.ecs.write_resource::<RunState>(); *runwriter = newrunstate; } damage_system::delete_the_dead(&mut self.ecs); } } impl State { fn entities_to_remove_on_level_change(&mut self) -> Vec<Entity> { let entities = self.ecs.entities(); let player = self.ecs.read_storage::<Player>(); let backpack = self.ecs.read_storage::<InBackpack>(); let player_entity = self.ecs.fetch::<Entity>(); let equipped = self.ecs.read_storage::<Equipped>(); let mut to_delete : Vec<Entity> = Vec::new(); for entity in entities.join() { let mut should_delete = true; // Don't delete the player let p = player.get(entity); if let Some(_p) = p { should_delete = false; } // Don't delete the player's equipment let bp = backpack.get(entity); if let Some(bp) = bp { if bp.owner == *player_entity { should_delete = false; } } let eq = equipped.get(entity); if let Some(eq) = eq { if eq.owner == *player_entity { should_delete = false; } } if should_delete { to_delete.push(entity); } } to_delete } fn goto_next_level(&mut self) { // Delete entities that aren't the player or his/her equipment let to_delete = self.entities_to_remove_on_level_change(); for target in to_delete { self.ecs.delete_entity(target).expect("Unable to delete entity"); } // Build a new map and place the player let worldmap; let current_depth; { let mut worldmap_resource = self.ecs.write_resource::<Map>(); current_depth = worldmap_resource.depth; *worldmap_resource = Map::new_map_rooms_and_corridors(current_depth + 1); worldmap = worldmap_resource.clone(); } // Spawn bad guys for room in worldmap.rooms.iter().skip(1) { spawner::spawn_room(&mut self.ecs, room, current_depth+1); } // Place the player and update resources let (player_x, player_y) = worldmap.rooms[0].center(); let mut player_position = self.ecs.write_resource::<Point>(); *player_position = Point::new(player_x, player_y); let mut position_components = self.ecs.write_storage::<Position>(); let player_entity = self.ecs.fetch::<Entity>(); let player_pos_comp = position_components.get_mut(*player_entity); if let Some(player_pos_comp) = player_pos_comp { player_pos_comp.x = player_x; player_pos_comp.y = player_y; } // Mark the player's visibility as dirty let mut viewshed_components = self.ecs.write_storage::<Viewshed>(); let vs = viewshed_components.get_mut(*player_entity); if let Some(vs) = vs { vs.dirty = true; } // Notify the player and give them some health let mut gamelog = self.ecs.fetch_mut::<gamelog::GameLog>(); gamelog.entries.push("You descend to the next level, and take a moment to heal.".to_string()); let mut player_health_store = self.ecs.write_storage::<CombatStats>(); let player_health = player_health_store.get_mut(*player_entity); if let Some(player_health) = player_health { player_health.hp = i32::max(player_health.hp, player_health.max_hp / 2); } } fn game_over_cleanup(&mut self) { // Delete everything let mut to_delete = Vec::new(); for e in self.ecs.entities().join() { to_delete.push(e); } for del in to_delete.iter() { self.ecs.delete_entity(*del).expect("Deletion failed"); } // Build a new map and place the player let worldmap; { let mut worldmap_resource = self.ecs.write_resource::<Map>(); *worldmap_resource = Map::new_map_rooms_and_corridors(1); worldmap = worldmap_resource.clone(); } // Spawn bad guys for room in worldmap.rooms.iter().skip(1) { spawner::spawn_room(&mut self.ecs, room, 1); } // Place the player and update resources let (player_x, player_y) = worldmap.rooms[0].center(); let player_entity = spawner::player(&mut self.ecs, player_x, player_y); let mut player_position = self.ecs.write_resource::<Point>(); *player_position = Point::new(player_x, player_y); let mut position_components = self.ecs.write_storage::<Position>(); let mut player_entity_writer = self.ecs.write_resource::<Entity>(); *player_entity_writer = player_entity; let player_pos_comp = position_components.get_mut(player_entity); if let Some(player_pos_comp) = player_pos_comp { player_pos_comp.x = player_x; player_pos_comp.y = player_y; } // Mark the player's visibility as dirty let mut viewshed_components = self.ecs.write_storage::<Viewshed>(); let vs = viewshed_components.get_mut(player_entity); if let Some(vs) = vs { vs.dirty = true; } } } fn main() -> rltk::BError { use rltk::RltkBuilder; let mut context = RltkBuilder::simple80x50() .with_title("Roguelike Tutorial") .build()?; context.with_post_scanlines(true); let mut gs = State { ecs: World::new() }; gs.ecs.register::<Position>(); gs.ecs.register::<Renderable>(); gs.ecs.register::<Player>(); gs.ecs.register::<Viewshed>(); gs.ecs.register::<Monster>(); gs.ecs.register::<Name>(); gs.ecs.register::<BlocksTile>(); gs.ecs.register::<CombatStats>(); gs.ecs.register::<WantsToMelee>(); gs.ecs.register::<SufferDamage>(); gs.ecs.register::<Item>(); gs.ecs.register::<ProvidesHealing>(); gs.ecs.register::<InflictsDamage>(); gs.ecs.register::<AreaOfEffect>(); gs.ecs.register::<Consumable>(); gs.ecs.register::<Ranged>(); gs.ecs.register::<InBackpack>(); gs.ecs.register::<WantsToPickupItem>(); gs.ecs.register::<WantsToUseItem>(); gs.ecs.register::<WantsToDropItem>(); gs.ecs.register::<Confusion>(); gs.ecs.register::<SimpleMarker<SerializeMe>>(); gs.ecs.register::<SerializationHelper>(); gs.ecs.register::<Equippable>(); gs.ecs.register::<Equipped>(); gs.ecs.register::<MeleePowerBonus>(); gs.ecs.register::<DefenseBonus>(); gs.ecs.register::<WantsToRemoveItem>(); gs.ecs.register::<ParticleLifetime>(); gs.ecs.register::<HungerClock>(); gs.ecs.register::<ProvidesFood>(); gs.ecs.register::<MagicMapper>(); gs.ecs.insert(SimpleMarkerAllocator::<SerializeMe>::new()); let map : Map = Map::new_map_rooms_and_corridors(1); let (player_x, player_y) = map.rooms[0].center(); let player_entity = spawner::player(&mut gs.ecs, player_x, player_y); gs.ecs.insert(rltk::RandomNumberGenerator::new()); for room in map.rooms.iter().skip(1) { spawner::spawn_room(&mut gs.ecs, room, 1); } gs.ecs.insert(map); gs.ecs.insert(Point::new(player_x, player_y)); gs.ecs.insert(player_entity); gs.ecs.insert(RunState::MainMenu{ menu_selection: gui::MainMenuSelection::NewGame }); gs.ecs.insert(gamelog::GameLog{ entries : vec!["Welcome to Rusty Roguelike".to_string()] }); gs.ecs.insert(particle_system::ParticleBuilder::new()); rltk::main_loop(context, gs) }
0
0.97411
1
0.97411
game-dev
MEDIA
0.615545
game-dev
0.978565
1
0.978565
Neo-Desktop/3d-pinball-space-cadet
2,871
Classes/TComponentGroup/TComponentGroup.cpp
#include "TComponentGroup.h" //----- (010159DC) -------------------------------------------------------- void TComponentGroup::NotifyTimerExpired(int a1, struct TPinballComponent* a2) { *(DWORD*)((char*)a2 + 50) = 0; control_handler(61, a2); } //----- (010159F9) -------------------------------------------------------- int __thiscall TComponentGroup::Message(TComponentGroup* this, int a2, float a3) { TComponentGroup* v3; // esi int v4; // eax int v5; // edi int v6; // ebx v3 = this; if (a2 == 48) { if (*(DWORD*)((char*)this + 50)) { timer_kill(*(DWORD*)((char*)this + 50)); *(DWORD*)((char*)v3 + 50) = 0; } if (a3 > 0.0) * (DWORD*)((char*)v3 + 50) = timer_set(a3, (int)v3, (int)TComponentGroup::NotifyTimerExpired); } else if (a2 <= 1007 || a2 > 1011 && a2 != 1020 && a2 != 1022) { v4 = *(DWORD*)(*(DWORD*)((char*)this + 46) + 4) - 1; if (v4 >= 0) { v5 = 4 * v4 + 8; v6 = *(DWORD*)(*(DWORD*)((char*)this + 46) + 4); do { (***(void (****)(int, DWORD))(v5 + *(DWORD*)((char*)v3 + 46)))(a2, LODWORD(a3)); v5 -= 4; --v6; } while (v6); } } return 0; } //----- (0101AA81) -------------------------------------------------------- TComponentGroup* __thiscall TComponentGroup::destroy(TComponentGroup* this, char a2) { TComponentGroup* v2; // esi v2 = this; TComponentGroup::~TComponentGroup(this); if (a2 & 1) component_delete((void*)v2); return v2; } //----- (01018FFD) -------------------------------------------------------- TComponentGroup* __thiscall TComponentGroup::TComponentGroup(TComponentGroup* this, struct TPinballTable* a2, int a3) { TComponentGroup* v3; // esi int v4; // eax signed int* i; // edi struct TPinballComponent* v6; // eax int v8; // [esp+Ch] [ebp-4h] int v9; // [esp+1Ch] [ebp+Ch] v3 = this; TPinballComponent::TPinballComponent(this, a2, a3, 0); *(DWORD*)v3 = &TComponentGroup::vftable; objlist_class::objlist_class((TComponentGroup*)((char*)v3 + 42), 4, 4); *(DWORD*)((char*)v3 + 50) = 0; if (a3 > 0) { v4 = loader_query_iattribute(a3, 1027, &v8); v9 = 0; for (i = (signed int*)v4; v9 < v8; ++i) { v6 = TPinballTable::find_component(a2, *i); if (v6) objlist_class::Add((TComponentGroup*)((char*)v3 + 42), (void*)v6); ++v9; } } return v3; } // 10024D8: using guessed type void *TComponentGroup::vftable; //----- (01019082) -------------------------------------------------------- TZmapList* __thiscall TComponentGroup::~TComponentGroup(TComponentGroup* this) { TComponentGroup* v1; // esi int v2; // eax v1 = this; v2 = *(DWORD*)((char*)this + 50); *(DWORD*)this = &TComponentGroup::vftable; if (v2) { timer_kill(v2); *(DWORD*)((char*)v1 + 50) = 0; } objlist_destroy(*(DWORD*)((char*)v1 + 46)); return TPinballComponent::~TPinballComponent(v1); } // 10024D8: using guessed type void *TComponentGroup::vftable;
0
0.891673
1
0.891673
game-dev
MEDIA
0.288813
game-dev
0.863593
1
0.863593
Kneesnap/FrogLord
2,057
src/net/highwayfrogs/editor/system/mm3d/blocks/MMTriangleGroupsBlock.java
package net.highwayfrogs.editor.system.mm3d.blocks; import lombok.Getter; import lombok.Setter; import net.highwayfrogs.editor.Constants; import net.highwayfrogs.editor.utils.data.reader.DataReader; import net.highwayfrogs.editor.utils.data.writer.DataWriter; import net.highwayfrogs.editor.system.mm3d.MMDataBlockBody; import net.highwayfrogs.editor.system.mm3d.MisfitModel3DObject; import net.highwayfrogs.editor.system.mm3d.OffsetType; import java.util.ArrayList; import java.util.List; /** * A group of triangles. Used to determine material. * Created by Kneesnap on 2/28/2019. */ @Getter @Setter public class MMTriangleGroupsBlock extends MMDataBlockBody { private short flags; private String name = ""; private final List<Integer> triangleIndices = new ArrayList<>(); private short smoothness = 0xFF; private int material = -1; // Index into material list. public static final int EMPTY_MATERIAL = -1; public static final short FLAG_HIDDEN = Constants.BIT_FLAG_0; // Set if hidden, clear if visible public static final short FLAG_SELECTED = Constants.BIT_FLAG_1; // Set if selected, clear if unselected public MMTriangleGroupsBlock(MisfitModel3DObject parent) { super(OffsetType.GROUPS, parent); } @Override public void load(DataReader reader) { this.flags = reader.readShort(); this.name = reader.readNullTerminatedString(); int triangleCount = reader.readInt(); for (int i = 0; i < triangleCount; i++) triangleIndices.add(reader.readInt()); this.smoothness = reader.readUnsignedByteAsShort(); this.material = reader.readInt(); } @Override public void save(DataWriter writer) { writer.writeShort(this.flags); writer.writeNullTerminatedString(this.name); writer.writeInt(this.triangleIndices.size()); for (int toWrite : this.triangleIndices) writer.writeInt(toWrite); writer.writeUnsignedByte(this.smoothness); writer.writeInt(this.material); } }
0
0.835231
1
0.835231
game-dev
MEDIA
0.319991
game-dev
0.84123
1
0.84123
qnpiiz/rich-2.0
2,176
src/main/java/net/minecraft/command/arguments/EnchantmentArgument.java
package net.minecraft.command.arguments; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.CompletableFuture; import net.minecraft.command.CommandSource; import net.minecraft.command.ISuggestionProvider; import net.minecraft.enchantment.Enchantment; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.Registry; import net.minecraft.util.text.TranslationTextComponent; public class EnchantmentArgument implements ArgumentType<Enchantment> { private static final Collection<String> EXAMPLES = Arrays.asList("unbreaking", "silk_touch"); public static final DynamicCommandExceptionType ENCHANTMENT_UNKNOWN = new DynamicCommandExceptionType((enchantment) -> { return new TranslationTextComponent("enchantment.unknown", enchantment); }); public static EnchantmentArgument enchantment() { return new EnchantmentArgument(); } public static Enchantment getEnchantment(CommandContext<CommandSource> context, String name) { return context.getArgument(name, Enchantment.class); } public Enchantment parse(StringReader p_parse_1_) throws CommandSyntaxException { ResourceLocation resourcelocation = ResourceLocation.read(p_parse_1_); return Registry.ENCHANTMENT.getOptional(resourcelocation).orElseThrow(() -> { return ENCHANTMENT_UNKNOWN.create(resourcelocation); }); } public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_listSuggestions_1_, SuggestionsBuilder p_listSuggestions_2_) { return ISuggestionProvider.suggestIterable(Registry.ENCHANTMENT.keySet(), p_listSuggestions_2_); } public Collection<String> getExamples() { return EXAMPLES; } }
0
0.710779
1
0.710779
game-dev
MEDIA
0.981028
game-dev
0.813879
1
0.813879
refinedmods/refinedstorage2
1,940
refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/autocrafter/AutocrafterConnectionStrategy.java
package com.refinedmods.refinedstorage.common.autocrafting.autocrafter; import com.refinedmods.refinedstorage.common.api.support.network.ConnectionSink; import com.refinedmods.refinedstorage.common.support.network.ColoredConnectionStrategy; import java.util.function.Supplier; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.block.state.BlockState; import static com.refinedmods.refinedstorage.common.support.AbstractDirectionalBlock.tryExtractDirection; class AutocrafterConnectionStrategy extends ColoredConnectionStrategy { AutocrafterConnectionStrategy(final Supplier<BlockState> blockStateProvider, final BlockPos origin) { super(blockStateProvider, origin); } @Override public void addOutgoingConnections(final ConnectionSink sink) { final Direction myDirection = tryExtractDirection(blockStateProvider.get()); if (myDirection == null) { super.addOutgoingConnections(sink); return; } for (final Direction direction : Direction.values()) { if (direction == myDirection) { sink.tryConnectInSameDimension(origin.relative(direction), direction.getOpposite(), AutocrafterBlock.class); } else { sink.tryConnectInSameDimension(origin.relative(direction), direction.getOpposite()); } } } @Override public boolean canAcceptIncomingConnection(final Direction incomingDirection, final BlockState connectingState) { if (!colorsAllowConnecting(connectingState)) { return false; } final Direction myDirection = tryExtractDirection(blockStateProvider.get()); if (myDirection != null) { return myDirection != incomingDirection || connectingState.getBlock() instanceof AutocrafterBlock; } return true; } }
0
0.964677
1
0.964677
game-dev
MEDIA
0.841658
game-dev
0.975345
1
0.975345
Ciberusps/unreal-helper-library
4,142
Source/UHLGAS/Public/UHLAbilitySystemConfig.h
// Pavel Penkov 2025 All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "AttributeSet.h" #include "GameplayTagContainer.h" #include "Engine/DataAsset.h" #include "UHLAbilitySystemConfig.generated.h" class UGameplayAbility; class UUHLAbilitySet; class UUHLInputConfig; class UAttributeSet; USTRUCT(BlueprintType) struct FUHLAbilitySystemSettings { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="AbilitySystemSettings", meta=(InlineEditConditionToggle)) bool bInitializeGameplayAttributes = true; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="AbilitySystemSettings", meta=(ForceInlineRow, EditCondition="bInitializeGameplayAttributes")) TMap<FGameplayAttribute, float> InitialAttributes = {}; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="AbilitySystemSettings", meta=(InlineEditConditionToggle)) bool bGiveAbilitiesOnStart = true; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="AbilitySystemSettings", meta=(EditCondition="bGiveAbilitiesOnStart")) TArray<TSubclassOf<UGameplayAbility>> Abilities = {}; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="AbilitySystemSettings", meta=(InlineEditConditionToggle)) bool bGiveAttributesSetsOnStart = true; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="AbilitySystemSettings", meta=(EditCondition="bGiveAttributesSetsOnStart")) TArray<TSubclassOf<UAttributeSet>> AttributeSets = {}; // TODO replace by "EUHLAbilityActivationPolicy::OnSpawn" UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="AbilitySystemSettings", meta=(InlineEditConditionToggle)) bool bActivateAbilitiesOnStart = true; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="AbilitySystemSettings", meta=(EditCondition="bActivateAbilitiesOnStart")) TArray<FGameplayTagContainer> ActiveAbilitiesOnStart = {}; // TODO initial GameplayEffects? UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="AbilitySystemSettings", meta=(InlineEditConditionToggle)) bool bGiveInitialGameplayTags = true; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="AbilitySystemSettings", meta=(EditCondition="bGiveInitialGameplayTags")) FGameplayTagContainer InitialGameplayTags; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="AbilitySystemSettings", AdvancedDisplay, meta=(InlineEditConditionToggle)) bool bGiveAbilitySetsOnStart = true; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="AbilitySystemSettings", AdvancedDisplay, meta=(EditCondition="bGiveAbilitySetsOnStart")) TArray<UUHLAbilitySet*> AbilitySets = {}; UPROPERTY(EditAnywhere, Transient, BlueprintReadWrite, Category="AbilitySystemSettings", AdvancedDisplay, meta=(InlineEditConditionToggle)) bool bPreviewAllAbilities = true; UPROPERTY(VisibleDefaultsOnly, Transient, Category="AbilitySystemSettings", AdvancedDisplay, meta=(EditCondition="bPreviewAllAbilities", MultiLine=true)) TMap<FString, FString> DebugPreviewAbilitiesFromAbilitySets = {}; // binding inputs to tags check Readme.MD on how to setup it UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="InputConfig") bool bUseInputConfig = false; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="InputConfig", meta=(EditCondition="bUseInputConfig")) UUHLInputConfig* InputConfig = nullptr; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="InputConfig", meta=(EditCondition="bUseInputConfig")) bool bUseAbilityInputCache = false; // if enabled - caching works only in predefined user windows - ANS_AbilityInputCache_CacheWindow // if disabled - works always UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="InputConfig", meta=(EditCondition="bUseInputConfig && bUseAbilityInputCache")) bool bUseInputCacheWindows = true; }; /** * if you want to set default values like "AttributeSets" or something just nest from this */ UCLASS(Blueprintable, BlueprintType) class UHLGAS_API UUHLAbilitySystemConfig : public UPrimaryDataAsset { GENERATED_BODY() public: UUHLAbilitySystemConfig(); UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="AbilitySystemConfig", meta=(ShowOnlyInnerProperties)) FUHLAbilitySystemSettings Settings; };
0
0.630557
1
0.630557
game-dev
MEDIA
0.897689
game-dev
0.517794
1
0.517794
BAndysc/WoWDatabaseEditor
6,275
Rendering/TheEngine/Coroutines/CoroutineManager.cs
using System; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; namespace TheEngine.Coroutines { public class WaitForTask { public readonly Task Task; public WaitForTask(Task task) { Task = task; } } public class CoroutineManager { public IReadOnlyList<CoroutineState> DebugList => coroutines; private List<CoroutineState> coroutines = new(); public class CoroutineState { public IEnumerator Coroutine; public bool Active; public CoroutineState? Parent; public Exception? NestedException; public bool IgnoreNestedExceptions; public Task? WaitingForTask; } public int PendingCoroutines => coroutines.Count; public void Start(IEnumerator coroutine) { var state = new CoroutineState() { Coroutine = coroutine, Active = true, Parent = null }; if (CoroutineStep(state)) coroutines.Add(state); } private bool StartNested(IEnumerator coroutine, CoroutineState parent) { var state = new CoroutineState() { Coroutine = coroutine, Active = true, Parent = parent }; if (CoroutineStep(state)) { coroutines.Add(state); return true; } return false; } private bool CoroutineStep(CoroutineState state) { bool hasContinuation = false; while (true) { try { hasContinuation = state.Coroutine.MoveNext(); } catch (Exception e) { if (state.Parent != null && !state.Parent.IgnoreNestedExceptions) { state.Parent.NestedException = e; state.Parent = null; // <-- so that it doesn't get activated } Console.WriteLine("Exception while running a continuation: "); Console.WriteLine(e); } if (hasContinuation) { var cur = state.Coroutine.Current; if (cur == null) { return true; } else if (cur is ContinueOnExceptionEnumerator continueOnException) { state.Active = false; state.IgnoreNestedExceptions = true; if (!StartNested(continueOnException.Enumerator, state) && state.NestedException == null) { state.Active = true; continue; // return CoroutineStep(state); } } else if (cur is IEnumerator nested) { state.Active = false; if (!StartNested(nested, state) && state.NestedException == null) { state.Active = true; continue; // return CoroutineStep(state); } } else if (cur is WaitForTask || cur is Task) { state.Active = false; Task task = cur is WaitForTask w ? w.Task : (Task)cur; state.WaitingForTask = task; if (task.IsCompleted) { if (task.Exception != null) Console.WriteLine(task.Exception); state.Active = true; state.WaitingForTask = null; } else { task.ContinueWith(t => { if (t.Exception != null) Console.WriteLine(t.Exception); state.Active = true; state.WaitingForTask = null; }); } if (state.Active) continue; //return CoroutineStep(state); } else throw new Exception("You can only yield null (For the next frame) or WaitForTask or another IEnumerator"); return true; } else { if (state.Parent != null) state.Parent.Active = true; return false; } } } public void Step() { var active = 0; var inactive = 0; for (int i = coroutines.Count - 1; i >= 0; --i) { try { if (coroutines[i].Active) { active++; if (!CoroutineStep(coroutines[i])) coroutines.RemoveAt(i); } else if (coroutines[i].NestedException != null) { if (coroutines[i].Parent != null && !coroutines[i].Parent.IgnoreNestedExceptions) coroutines[i].Parent.NestedException = coroutines[i].NestedException; // propagate coroutines.RemoveAt(i); } else inactive++; } catch (Exception e) { Console.WriteLine("Exception in a coroutine. The corotuine will be removed!"); Console.WriteLine(e); coroutines.RemoveAt(i); } } } } }
0
0.762502
1
0.762502
game-dev
MEDIA
0.71774
game-dev
0.934832
1
0.934832