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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ax-grymyr/l2dn-server | 1,768 | L2Dn/L2Dn.GameServer.Scripts/Handlers/EffectHandlers/StatBonusSpeed.cs | using L2Dn.GameServer.Model;
using L2Dn.GameServer.Model.Actor;
using L2Dn.GameServer.Model.Conditions;
using L2Dn.GameServer.Model.Effects;
using L2Dn.GameServer.Model.Items.Types;
using L2Dn.GameServer.Model.Skills;
using L2Dn.Model.Enums;
using L2Dn.Utilities;
namespace L2Dn.GameServer.Scripts.Handlers.EffectHandlers;
public sealed class StatBonusSpeed: AbstractEffect
{
private readonly double _stat;
private readonly Condition? _armorTypeCondition;
public StatBonusSpeed(StatSet @params)
{
_stat = (int)@params.getEnum("stat", BaseStat.DEX);
ItemTypeMask armorTypesMask = ItemTypeMask.Zero;
List<string>? armorTypes = @params.getList<string>("armorType");
if (armorTypes != null)
{
foreach (string armorType in armorTypes)
{
try
{
armorTypesMask |= Enum.Parse<ArmorType>(armorType);
}
catch (ArgumentException e)
{
throw new ArgumentException("armorTypes should contain ArmorType enum value but found " + armorType,
e);
}
}
}
_armorTypeCondition = armorTypesMask != ItemTypeMask.Zero ? new ConditionUsingItemType(armorTypesMask) : null;
}
public override void pump(Creature effected, Skill skill)
{
if (_armorTypeCondition == null || _armorTypeCondition.test(effected, effected, skill))
effected.getStat().mergeAdd(Stat.STAT_BONUS_SPEED, _stat);
}
public override int GetHashCode() => HashCode.Combine(_stat, _armorTypeCondition);
public override bool Equals(object? obj) => this.EqualsTo(obj, static x => (x._stat, x._armorTypeCondition));
} | 0 | 0.761814 | 1 | 0.761814 | game-dev | MEDIA | 0.957961 | game-dev | 0.808034 | 1 | 0.808034 |
LordOfDragons/dragengine | 9,292 | src/modules/physics/bullet/src/collider/debpColliderRig.h | /*
* MIT License
*
* Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef _DEBPCOLLIDERRIGGED_H_
#define _DEBPCOLLIDERRIGGED_H_
#include "debpCollider.h"
#include "../shape/debpShapeList.h"
class deColliderConstraint;
class deColliderRig;
class deRigBone;
class debpColliderBones;
class debpColliderBone;
class debpPhysicsBody;
class debpRig;
/**
* @brief Bullet Collider Rigged.
*/
class debpColliderRig : public debpCollider{
public:
/** Test mode enumerations. */
enum eTestModes{
/** Test against rig shape. */
etmRigShape,
/** Test against bone shape. */
etmBoneShape,
etmNone
};
private:
deColliderRig &pColliderRig;
decDVector pPosition;
decQuaternion pOrientation;
decVector pScale;
decVector pLinVelo;
decVector pAngVelo;
decVector pGravity;
decVector pPredictDisp;
decVector pPredictVelo;
bool pHasGravity;
bool pHasLinVelo;
bool pHasAngVelo;
bool pDirtyBones;
bool pDirtyAttachments;
bool pDirtyShapes;
bool pPreventUpdate;
bool pPreventAttNotify;
eTestModes pTestMode;
debpPhysicsBody *pSimplePhyBody;
debpColliderBones *pBones;
debpRig *pRig;
debpShapeList pRigShapes;
public:
/** @name Constructors and Destructors */
/*@{*/
/** Creates a new rigged collider. */
debpColliderRig( dePhysicsBullet *bullet, deColliderRig &collider );
/** Cleans up the rigged collider. */
~debpColliderRig() override;
/*@}*/
/** @name Management */
/*@{*/
/** Retrieves the rigged collider. */
inline deColliderRig &GetColliderRig() const{ return pColliderRig; }
/** Retrieves the test mode. */
inline eTestModes GetTestMode() const{ return pTestMode; }
/** \brief Mark bones dirty. */
void DirtyBones();
/** \brief Mark attachments dirty. */
void DirtyAttachments();
/** \brief Parent world changed. */
void SetParentWorld( debpWorld *parentWorld ) override;
/** Create physics body if not existing already. */
void CreateBody() override;
/** Destroy physics body if existing. */
void DestroyBody() override;
/** Update collider state from physics body state. */
void UpdateFromBody() override;
/** Update extends if required. */
void UpdateExtends() override;
/** Prepare for a simulation step. */
void PrepareForStep() override;
/** Prepares the collision detection. */
void PrepareDetection( float elapsed ) override;
/** Finished the collision detection updating the collider and send notifications. */
void FinishDetection() override;
/** \brief Calculate auto collision detection re-register value. */
bool CalcAutoColDetPrepare() override;
/** \brief Calculate auto collision detection re-register value. */
bool CalcAutoColDetFinish() override;
/**
* \brief Prepare constraints for next detection step.
* \details Required to deal with advanced features like joint frictions.
*/
void PrepareRigConstraintsForStep();
/** \brief Check if rig constraints broke and notify the scripting module if required. */
void CheckRigConstraintsBroke();
/** \brief Updates the collision object aabbs if dirty. */
void UpdateCollisionObjectAABBs() override;
/** Retrieves the rig or NULL if not set. */
inline debpRig *GetRig() const{ return pRig; }
/** Retrieves the list of rig shapes. */
inline debpShapeList &GetRigShapes(){ return pRigShapes; }
inline const debpShapeList &GetRigShapes() const{ return pRigShapes; }
/** Updates shapes with the current matrix. */
void UpdateShapes() override;
/** Updates shapes using a transformation matrix. */
void UpdateShapesWithMatrix( const decDMatrix &transformation ) override;
/** Determines if the shape is simple. */
bool IsSimpleShape() const;
/** \brief Simple physics body or \em NULL. */
inline debpPhysicsBody *GetSimplePhysicsBody() const{ return pSimplePhyBody; }
/** \brief Bones or NULL. */
inline debpColliderBones *GetBones() const{ return pBones; }
/** Prepare for static collsion test. Returns true if ready or false if not usable. */
bool PrepareStaticCollisionTest() override;
/*@}*/
/** \name Debugging */
/*@{*/
/** \brief Update debug drawer if developer mode is enabled. */
void UpdateDebugDrawer() override;
/**
* \brief Update debug drawer shape shape.
* \details Called after creating debug drawer or if the collider subclass requires an update.
*/
void UpdateDDSShape() override;
/*@}*/
/** \name Actions */
/*@{*/
/** \brief Enable or disable a component or rigged collider bone constraint. */
void EnableBoneConstraint( int bone, int constraint, bool enable ) override;
/**
* \brief Replace a component or rigged collider bone constraint.
* \details The provided rig constraint only serves as source to copy the
* new parameters. It has to be freed by the called afterwards.
*/
void ReplaceBoneConstraint( int bone, int constraint, const deRigConstraint &replacement ) override;
/*@}*/
/** @name Forces */
/*@{*/
/** Applies a force at the center mass point. */
void ApplyForce( const decVector &force ) override;
/** Applies a force relative to the collider position. */
void ApplyForceAt( const decVector &force, const decVector &point ) override;
/** Applies a torque force at the center mass point. */
void ApplyTorque( const decVector &torque ) override;
/** Applies a force at the center mass point of the given bone. */
void ApplyBoneForce( int bone, const decVector &force ) override;
/** Applies a force relative to the bone position. */
void ApplyBoneForceAt( int bone, const decVector &force, const decVector &point ) override;
/** Applies a torque force at the center mass point of the given bone. */
void ApplyBoneTorque( int bone, const decVector &torque ) override;
/*@}*/
/** @name Notifications */
/*@{*/
/** \brief Position changed. */
void PositionChanged() override;
/** \brief Orientation changed. */
void OrientationChanged() override;
/** \brief Position or orientation changed. */
void GeometryChanged() override;
/** \brief Scale changed. */
void ScaleChanged() override;
/** \brief Linear velocity changed. */
void LinearVelocityChanged() override;
/** \brief Angular velocity changed. */
void AngularVelocityChanged() override;
/** \brief Enabled changed. */
void EnabledChanged() override;
/** \brief Gravity changed. */
void GravityChanged() override;
/** \brief Properties like mass changed. */
void PropertiesChanged() override;
/** \brief Response type changed. */
void ResponseTypeChanged() override;
/** \brief Collision filter changed. */
void CollisionFilterChanged() override;
/** \brief Ignore colliders changed. */
void IgnoreCollidersChanged() override;
/** \brief Rig changed. */
void RigChanged() override;
/** \brief Attachment added. */
void AttachmentAdded( int index, deColliderAttachment *attachment ) override;
/** \brief Attachment changed. */
void AttachmentChanged( int index, deColliderAttachment *attachment ) override;
/** \brief Attachment removed. */
void AttachmentRemoved( int index, deColliderAttachment *attachment ) override;
/** \brief All attachments removed. */
void AllAttachmentsRemoved() override;
/** \brief Force update of all attachments. */
void AttachmentsForceUpdate() override;
/** \brief Bone position changed. */
void BonePositionChanged( int index ) override;
/** \brief Bone orientation changed. */
void BoneOrientationChanged( int index ) override;
/** \brief Bone linear velocity changed. */
void BoneLinearVelocityChanged( int index ) override;
/** \brief Bone angular velocity changed. */
void BoneAngularVelocityChanged( int index ) override;
/** \brief Bone properties changed. */
void BonePropertiesChanged( int index ) override;
/** \brief Bone dynamic changed. */
void BoneDynamicChanged( int index ) override;
/** \brief Constraint added. */
void ConstraintAdded( int index, deColliderConstraint *constraint ) override;
/** \brief Constraint changed. */
void ConstraintChanged( int index, deColliderConstraint *constraint ) override;
/*@}*/
private:
void pUpdateShapeExtends();
void pCleanUp();
void pUpdateBones();
void pUpdateAttachments( bool force );
void pUpdateIsMoving();
};
#endif
| 0 | 0.931229 | 1 | 0.931229 | game-dev | MEDIA | 0.847068 | game-dev | 0.701782 | 1 | 0.701782 |
Mercury-Language/mercury | 8,480 | extras/graphics/mercury_allegro/samples/speed/speed.m | %-----------------------------------------------------------------------------%
%
% SPEED: Simultaneous Projections Employing an Ensemble of Displays.
%
% Or alternatively: Stupid Pointless Effort at Establishing a Dumb Acronym.
%
% By Shawn Hargreaves, November 1999.
%
% Partial port to Mercury by Peter Wang.
% Please see http://www.talula.demon.co.uk/speed/index.html
% for the original version. In particular it has synthesised music
% which is not yet in this port.
%
%-----------------------------------------------------------------------------%
:- module speed.
:- interface.
:- import_module io.
:- import_module badguys.
:- import_module bullet.
:- import_module explode.
:- import_module message.
:- import_module player.
:- import_module sound.
%-----------------------------------------------------------------------------%
:- type game
---> game(
player :: player,
badguys :: badguys,
bullets :: bullets,
explosions :: explosions,
sounds :: sounds,
messages :: messages
).
:- pred main(io::di, io::uo) is det.
%-----------------------------------------------------------------------------%
%-----------------------------------------------------------------------------%
:- implementation.
:- import_module lcg.
:- import_module lcg.io.
:- import_module title.
:- import_module view.
:- import_module allegro.
:- import_module allegro.bitmap.
:- import_module allegro.color_format.
:- import_module allegro.graphics.
:- import_module allegro.init.
:- import_module allegro.keyboard.
:- import_module allegro.palette.
:- import_module allegro.sound.
:- import_module allegro.timer.
:- import_module allegro.transparency.
:- import_module bool.
:- import_module int.
:- import_module maybe.
:- import_module require.
:- import_module time.
%-----------------------------------------------------------------------------%
:- func width = int.
:- func height = int.
:- func bpp = int.
width = 640.
height = 480.
bpp = 8.
main(!IO) :-
allegro_init(Ok, !IO),
(
Ok = yes,
set_color_depth(bpp, !IO),
set_gfx_mode(gfx_autodetect_windowed, width, height, 0, 0, GfxOk, !IO),
(
GfxOk = yes,
install_timer(_TimerOk, !IO),
install_keyboard(_KeyboardOk, !IO),
install_sound(digi_autodetect, midi_none, _SoundOk, !IO),
sound.generate_samples(!IO),
(if
bpp = 8
then
generate_332_palette(Pal),
set_palette_entry(Pal, 0, 0,0,0, !IO),
set_palette(Pal, !IO),
create_rgb_table(RgbMap, Pal, !IO),
set_rgb_map(RgbMap, !IO),
% create_color_table(ColorMap, Pal, add_blender8, !IO),
set_add_blender(0, 0, 0, 255, !IO),
create_blender_table(ColorMap, Pal, !IO),
set_color_map(ColorMap, !IO)
else
error("only 8-bit colour supported at the moment")
% set_blender_mode(add_blender15, add_blender16, add_blender14, 0, 0, 0, 0, !IO),
),
title_loop(!IO),
sound.destroy_samples(!IO)
;
GfxOk = no
)
;
Ok = no
).
:- pred title_loop(io::di, io::uo) is det.
title_loop(!IO) :-
title_screen(WhatToDo, !IO),
(
WhatToDo = play_game,
play_game(0, !IO),
title_loop(!IO)
;
WhatToDo = quit
).
:- pred play_game(cycle_num::in, io::di, io::uo) is det.
:- type cycle_num == int.
play_game(CycleNum, !IO) :-
det_screen(_, ScreenW, ScreenH, !IO),
create_bitmap(ScreenW, ScreenH, MaybeBitmap, !IO),
(
MaybeBitmap = yes(Bitmap),
TimerSpeed = bps_to_timer(30*(CycleNum+2)),
install_int_ex(TimerSpeed, MaybeCounter, !IO),
(
MaybeCounter = yes(Counter),
game_loop(Bitmap, Counter, !IO),
remove_int(Counter, !IO)
;
MaybeCounter = no
),
destroy_bitmap(Bitmap, !IO)
;
MaybeBitmap = no
).
:- pred game_loop(bitmap::in, ticker::in, io::di, io::uo) is det.
game_loop(Bitmap, Counter, !IO) :-
time.clock(Time, !IO),
init_badguys(0, Badguys, lcg.init(Time), _RS),
Sounds0 = init_sounds,
sfx_ping(2, Sounds0, Sounds1),
play_queued_sfx(Sounds1, Sounds, !IO),
Game0 = game(init_player, Badguys, init_bullets, init_explosions,
Sounds, init_messages),
game_loop_2(Bitmap, Counter, Game0, Game, init_view, _View, !IO),
stop_sounds(Game ^ sounds, !IO).
:- pred game_loop_2(bitmap::in, ticker::in, game::in, game::out,
view::in, view::out, io::di, io::uo) is det.
game_loop_2(Bitmap, Counter, !Game, !View, !IO) :-
do_updates(Counter, !Game, !View, Quit, 0, N, !IO),
(
Quit = yes
;
Quit = no,
draw_view(Bitmap, !.Game, !.View, !IO),
(if N = 0 then
rest(0, !IO)
else
true
),
game_loop_2(Bitmap, Counter, !Game, !View, !IO)
).
:- pred do_updates(ticker::in, game::in, game::out, view::in, view::out,
quit::out, int::in, int::out, io::di, io::uo) is det.
:- type quit == bool.
do_updates(Counter, !Game, !View, Quit, !N, !IO) :-
get_ticker(Counter, Count, !IO),
(if
Count > 0
then
get_input(Input, !IO),
% debugging
key(key_v, V, !IO),
key(key_b, B, !IO),
( V = yes ->
advance_view(!View, _Cycled),
wait_key_released(key_v, !IO)
;
true
),
( B = yes ->
BG0 = !.Game ^ badguys,
kill_all_badguys(BG0, BG),
!:Game = !.Game ^ badguys := BG,
wait_key_released(key_b, !IO)
;
true
),
% end debugging
(
Input ^ escape = yes,
Quit = yes
;
Input ^ escape = no,
update_view(!View),
% XXX icky
some [!Player, !Badguys, !Bullets, !Explosions, !Sounds, !Messages]
(
!.Game = game(!:Player, !:Badguys, !:Bullets, !:Explosions,
!:Sounds, !:Messages),
update_bullets(!Bullets),
update_explosions(!Explosions),
update_messages(!Messages, !IO),
lcg.io.get_supply(RS0, !IO),
update_badguys(!Badguys, !Player, !Bullets, !Explosions,
!Sounds, !Messages, RS0, RS1, WaveComplete),
(
WaveComplete = yes,
advance_view(!View, Cycled),
(
Cycled = yes
% cyclenum++;
% install_int_ex(inc_counter, TIMER_SPEED);
;
Cycled = no
),
lay_attack_wave(Cycled, !Badguys, RS1, RS),
advance_player(!Player, Cycled, !Sounds, !Messages)
;
WaveComplete = no,
RS = RS1
),
lcg.io.set_supply(RS, !IO),
update_player(Input, !Player, Result, !Bullets, !Sounds,
!Messages),
play_queued_sfx(!Sounds, !IO),
!:Game = game(!.Player, !.Badguys, !.Bullets, !.Explosions,
!.Sounds, !.Messages)
),
(
Result = dead,
Quit = yes
;
Result = continue,
get_ticker(Counter, C, !IO),
set_ticker(Counter, C-1, !IO),
do_updates(Counter, !Game, !View, Quit, !.N+1, !:N, !IO)
)
)
else
Quit = no
).
:- pred get_input(input::out, io::di, io::uo) is det.
get_input(input(Esc, Left, Right, Space), !IO) :-
key(key_esc, Esc, !IO),
key(key_left, Left, !IO),
key(key_right, Right, !IO),
key(key_space, Space, !IO).
:- pred wait_key_released(int::in, io::di, io::uo) is det.
wait_key_released(Key, !IO) :-
key(Key, Pressed, !IO),
(
Pressed = yes,
wait_key_released(Key, !IO)
;
Pressed = no
).
%-----------------------------------------------------------------------------%
% vi:ft=mercury:ts=8:sts=4:sw=4:et
| 0 | 0.748608 | 1 | 0.748608 | game-dev | MEDIA | 0.813788 | game-dev | 0.713291 | 1 | 0.713291 |
roflmuffin/CounterStrikeSharp | 1,834 | managed/CounterStrikeSharp.API/Core/Schema/Classes/CFuncElectrifiedVolume.g.cs | // <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CFuncElectrifiedVolume : CFuncBrush
{
public CFuncElectrifiedVolume (IntPtr pointer) : base(pointer) {}
// m_EffectName
[SchemaMember("CFuncElectrifiedVolume", "m_EffectName")]
public string EffectName
{
get { return Schema.GetUtf8String(this.Handle, "CFuncElectrifiedVolume", "m_EffectName"); }
set { Schema.SetString(this.Handle, "CFuncElectrifiedVolume", "m_EffectName", value); }
}
// m_EffectInterpenetrateName
[SchemaMember("CFuncElectrifiedVolume", "m_EffectInterpenetrateName")]
public string EffectInterpenetrateName
{
get { return Schema.GetUtf8String(this.Handle, "CFuncElectrifiedVolume", "m_EffectInterpenetrateName"); }
set { Schema.SetString(this.Handle, "CFuncElectrifiedVolume", "m_EffectInterpenetrateName", value); }
}
// m_EffectZapName
[SchemaMember("CFuncElectrifiedVolume", "m_EffectZapName")]
public string EffectZapName
{
get { return Schema.GetUtf8String(this.Handle, "CFuncElectrifiedVolume", "m_EffectZapName"); }
set { Schema.SetString(this.Handle, "CFuncElectrifiedVolume", "m_EffectZapName", value); }
}
// m_iszEffectSource
[SchemaMember("CFuncElectrifiedVolume", "m_iszEffectSource")]
public string EffectSource
{
get { return Schema.GetUtf8String(this.Handle, "CFuncElectrifiedVolume", "m_iszEffectSource"); }
set { Schema.SetString(this.Handle, "CFuncElectrifiedVolume", "m_iszEffectSource", value); }
}
}
| 0 | 0.734001 | 1 | 0.734001 | game-dev | MEDIA | 0.856649 | game-dev | 0.597126 | 1 | 0.597126 |
msx80/DoorsOfDoomOmicron | 4,309 | doorsofdoom/src/main/java/com/github/msx80/doorsofdoom/model/Run.java | package com.github.msx80.doorsofdoom.model;
import com.github.msx80.doorsofdoom.DoorsOfDoom;
import com.google.gson.Gson;
public class Run {
public Pg pg;
public int level;
public int kills;
public Monster monster;
public int gold;
public int lootQty;
public Item lootItem;
public int shake = 0;
public int shakePg = 0;
public boolean exited = false;
public Run() {
pg = new Pg();
init();
}
public void damage(Entity e, int dmg) {
e.hp -= dmg;
if (e.hp < 0) e.hp = 0;
if (e.hp > e.maxHp) e.hp = e.maxHp;
}
public void init() {
exited = false;
level = 0;
kills = 0;
monster = null;
gold = 0;
lootQty = 0;
lootItem = null;
pg.maxHp = 20;
pg.hp = 20;
pg.effects.clear();
pg.equip.clear();
pg.blockedRemainder = 0;
pg.inventory.clear();
pg.ricalcola();
pg.inventoryAdd(Item.SmallPotion, 3);
pg.inventoryAdd(Item.Key, 50);
/*
pg.inventoryAdd(Item.Map, 1);
pg.inventoryAdd(Item.Rock, 1000);
pg.inventoryAdd(Item.Slingshot, 1);
pg.inventoryAdd(Item.MediumPotion, 3);
pg.inventoryAdd(Item.BigPotion, 3);
pg.inventoryAdd(Item.Sword, 3);
pg.inventoryAdd(Item.Shield, 1);
pg.inventoryAdd(Item.Greaves, 1);
pg.inventoryAdd(Item.Armour, 1);
pg.inventoryAdd(Item.Helm, 1);
pg.inventoryAdd(Item.EyePatch, 1);
pg.inventoryAdd(Item.Tricorn, 1);
pg.inventoryAdd(Item.Fang, 2);
pg.inventoryAdd(Item.Sprite, 12);
pg.inventoryAdd(Item.Venom, 22);
pg.inventoryAdd(Item.Wisdom, 1);
pg.inventoryAdd(Item.Ectoplasm, 22);
pg.inventoryAdd(Item.Slime, 22);
pg.inventoryAdd(Item.Hamburger, 2);
pg.inventoryAdd(Item.Phlogiston, 20);
pg.inventoryAdd(Item.Fur, 20);
pg.inventoryAdd(Item.Slime, 20);
pg.inventoryAdd(Item.Ectoplasm, 20);
pg.inventoryAdd(Item.BagOfGold, 2);
pg.inventoryAdd(Item.FlamingSword, 1);
pg.inventoryAdd(Item.CowardToken, 2);
pg.inventoryAdd(Item.BagOfGold, 2);
pg.inventoryAdd(Item.Knife, 2);
pg.inventoryAdd(Item.DuraniumArmour, 2);
pg.inventoryAdd(Item.DuraniumShield, 2);
pg.inventoryAdd(Item.DuraniumChausses, 2);
pg.inventoryAdd(Item.DuraniumHelm, 2);
pg.inventoryAdd(Item.Blood, 4);
pg.inventoryAdd(Item.Cheese, 15);
pg.inventoryAdd(Item.Jacket, 15);
pg.inventoryAdd(Item.Throusers, 15);
pg.inventoryAdd(Item.Leather, 15);
pg.inventoryAdd(Item.Bread, 15);
pg.inventoryAdd(Item.Stick, 15);
pg.inventoryAdd(Item.Rock, 15);
pg.inventoryAdd(Item.Armour, 15);
pg.inventoryAdd(Item.Venom, 15);
pg.inventoryAdd(Item.EctoDrink, 15);
pg.inventoryAdd(Item.Slingshot, 15);
pg.inventoryAdd(Item.Magnet, 15);
pg.inventoryAdd(Item.Pants, 15);
pg.inventoryAdd(Item.Gelatin, 15);
pg.inventoryAdd(Item.Stockade, 15);
pg.inventoryAdd(Item.Mint, 15);
pg.inventoryAdd(Item.Ectoplasm, 15);
pg.inventoryAdd(Item.Tomato, 15);
pg.inventoryAdd(Item.Fork, 15);
pg.inventoryAdd(Item.Phlogiston, 15);
pg.inventoryAdd(Item.Diamond, 15);
pg.inventoryAdd(Item.Crown, 15);
pg.inventoryAdd(Item.Gold, 1005);
pg.inventoryAdd(Item.Scroll, 15);
pg.inventoryAdd(Item.SmallPotion, 1);
pg.inventoryAdd(Item.Spinach, 1);
pg.inventoryAdd(Item.Elixir, 10);
pg.inventoryAdd(Item.Clover, 1);
pg.inventoryAdd(Item.Tomato, 1);
pg.inventoryAdd(Item.Shield, 15);
pg.inventoryAdd(Item.Shirt, 15);
pg.inventoryAdd(Item.Helm, 15);
pg.inventoryAdd(Item.Bone, 15);
pg.inventoryAdd(Item.FlamingSword, 1);
pg.inventoryAdd(Item.Sword, 1);
pg.inventoryAdd(Item.Claw, 1);
*/
/*
pg.equip(Item.FlamingSword);
pg.equip(Item.Armour);
pg.equip(Item.Helm);
pg.equip(Item.Greaves);
pg.equip(Item.Shield);
*/
// run.monster = new Monster(MonsterDef.SNAKE);
//pg.addEffect(Effect.GHOSTLY);
//pg.addEffect(Effect.BARRIER);
}
public long score() {
return level * 10
+ (pg.getInvCount(Item.Diamond) * 100)
+ (pg.getInvCount(Item.Crown) * DoorsOfDoom.CROWN_POINT)
+ (pg.getInvCount(Item.CowardToken) * -15)
+ (exited ? DoorsOfDoom.EXIT_BONUS : 0);
}
public String dump()
{
Gson g = new Gson();
String s = g.toJson(this);
System.out.println(s);
return s;
}
public static Run load(String s)
{
Gson g = new Gson();
Run r = g.fromJson(s, Run.class);
return r;
}
}
| 0 | 0.618088 | 1 | 0.618088 | game-dev | MEDIA | 0.947482 | game-dev | 0.754378 | 1 | 0.754378 |
aurora-sim/Aurora-Sim | 1,119 | AuroraDocs/OSSLFunctions/osFormatString.lsl | // ----------------------------------------------------------------
// Example / Sample Script to show function use.
//
// Script Title: osFormatString.lsl
// Script Author:
// Threat Level: Low
// Script Source: Reference http://opensimulator.org/wiki/osFormatString
//
// Notes: See Script Source reference for more detailed information
// This sample is full opensource and available to use as you see fit and desire.
// Threat Levels only apply to OSSL & AA Functions
// See http://opensimulator.org/wiki/Threat_level
//================================================================
// Inworld Script Line: osFormatString(string to_format, list strings);
//
// Example osFormatString
//
default
{
state_entry()
{
llSay(0,"Touch to see osFormatString chat formatted text");
}
touch_end(integer num)
{
string to_format = "My name is {0} and I am located in {1} Region. The avatar who just touched me is {2}.";
list format = [llGetObjectName(),llGetRegionName(),llKey2Name(llDetectedKey(0))];
llOwnerSay(osFormatString(to_format, format));
}
}
| 0 | 0.706574 | 1 | 0.706574 | game-dev | MEDIA | 0.356299 | game-dev | 0.50482 | 1 | 0.50482 |
871041532/zstring | 2,836 | zstringTest/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_SubMesh_Editor.cs | using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TMP_SubMesh)), CanEditMultipleObjects]
public class TMP_SubMesh_Editor : Editor
{
private struct m_foldout
{ // Track Inspector foldout panel states, globally.
//public static bool textInput = true;
public static bool fontSettings = true;
//public static bool extraSettings = false;
//public static bool shadowSetting = false;
//public static bool materialEditor = true;
}
private SerializedProperty fontAsset_prop;
private SerializedProperty spriteAsset_prop;
private TMP_SubMesh m_SubMeshComponent;
private Renderer m_Renderer;
public void OnEnable()
{
fontAsset_prop = serializedObject.FindProperty("m_fontAsset");
spriteAsset_prop = serializedObject.FindProperty("m_spriteAsset");
m_SubMeshComponent = target as TMP_SubMesh;
m_Renderer = m_SubMeshComponent.renderer;
}
public override void OnInspectorGUI()
{
EditorGUI.indentLevel = 0;
GUI.enabled = false;
EditorGUILayout.PropertyField(fontAsset_prop);
EditorGUILayout.PropertyField(spriteAsset_prop);
GUI.enabled = true;
EditorGUI.BeginChangeCheck();
// SORTING LAYERS
var sortingLayerNames = SortingLayerHelper.sortingLayerNames;
// Look up the layer name using the current layer ID
string oldName = SortingLayerHelper.GetSortingLayerNameFromID(m_Renderer.sortingLayerID);
// Use the name to look up our array index into the names list
int oldLayerIndex = System.Array.IndexOf(sortingLayerNames, oldName);
// Show the pop-up for the names
int newLayerIndex = EditorGUILayout.Popup("Sorting Layer", oldLayerIndex, sortingLayerNames);
// If the index changes, look up the ID for the new index to store as the new ID
if (newLayerIndex != oldLayerIndex)
{
//Undo.RecordObject(renderer, "Edit Sorting Layer");
m_Renderer.sortingLayerID = SortingLayerHelper.GetSortingLayerIDForIndex(newLayerIndex);
//EditorUtility.SetDirty(renderer);
}
// Expose the manual sorting order
int newSortingLayerOrder = EditorGUILayout.IntField("Order in Layer", m_Renderer.sortingOrder);
if (newSortingLayerOrder != m_Renderer.sortingOrder)
{
//Undo.RecordObject(renderer, "Edit Sorting Order");
m_Renderer.sortingOrder = newSortingLayerOrder;
}
}
}
}
| 0 | 0.749385 | 1 | 0.749385 | game-dev | MEDIA | 0.839557 | game-dev | 0.895515 | 1 | 0.895515 |
ServUO/ServUO | 1,928 | Scripts/Items/Artifacts/Equipment/Jewelry/DragonJadeEarrings.cs | using System;
namespace Server.Items
{
public class DragonJadeEarrings : GargishEarrings
{
public override bool IsArtifact { get { return true; } }
public override int LabelNumber { get { return 1113720; } } // Dragon Jade Earrings
public override int BasePhysicalResistance { get { return 9; } }
public override int BaseFireResistance { get { return 16; } }
public override int BaseColdResistance { get { return 5; } }
public override int BasePoisonResistance { get { return 13; } }
public override int BaseEnergyResistance { get { return 3; } }
[Constructable]
public DragonJadeEarrings()
{
Hue = 2129;
Attributes.BonusDex = 5;
Attributes.BonusStr = 5;
Attributes.RegenHits = 2;
Attributes.RegenStam = 3;
Attributes.LowerManaCost = 5;
AbsorptionAttributes.EaterFire = 10;
}
public DragonJadeEarrings(Serial serial)
: base(serial)
{
}
public override int InitMinHits
{
get
{
return 255;
}
}
public override int InitMaxHits
{
get
{
return 255;
}
}
public override bool CanBeWornByGargoyles
{
get
{
return true;
}
}
public override Race RequiredRace
{
get
{
return Race.Gargoyle;
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
| 0 | 0.643621 | 1 | 0.643621 | game-dev | MEDIA | 0.90719 | game-dev | 0.816769 | 1 | 0.816769 |
qnpiiz/rich-2.0 | 4,047 | src/main/java/net/minecraft/util/datafix/versions/V1451_3.java | package net.minecraft.util.datafix.versions;
import com.mojang.datafixers.DSL;
import com.mojang.datafixers.schemas.Schema;
import com.mojang.datafixers.types.templates.TypeTemplate;
import java.util.Map;
import java.util.function.Supplier;
import net.minecraft.util.datafix.NamespacedSchema;
import net.minecraft.util.datafix.TypeReferences;
public class V1451_3 extends NamespacedSchema
{
public V1451_3(int versionKey, Schema parent)
{
super(versionKey, parent);
}
public Map<String, Supplier<TypeTemplate>> registerEntities(Schema p_registerEntities_1_)
{
Map<String, Supplier<TypeTemplate>> map = super.registerEntities(p_registerEntities_1_);
p_registerEntities_1_.registerSimple(map, "minecraft:egg");
p_registerEntities_1_.registerSimple(map, "minecraft:ender_pearl");
p_registerEntities_1_.registerSimple(map, "minecraft:fireball");
p_registerEntities_1_.register(map, "minecraft:potion", (p_206498_1_) ->
{
return DSL.optionalFields("Potion", TypeReferences.ITEM_STACK.in(p_registerEntities_1_));
});
p_registerEntities_1_.registerSimple(map, "minecraft:small_fireball");
p_registerEntities_1_.registerSimple(map, "minecraft:snowball");
p_registerEntities_1_.registerSimple(map, "minecraft:wither_skull");
p_registerEntities_1_.registerSimple(map, "minecraft:xp_bottle");
p_registerEntities_1_.register(map, "minecraft:arrow", () ->
{
return DSL.optionalFields("inBlockState", TypeReferences.BLOCK_STATE.in(p_registerEntities_1_));
});
p_registerEntities_1_.register(map, "minecraft:enderman", () ->
{
return DSL.optionalFields("carriedBlockState", TypeReferences.BLOCK_STATE.in(p_registerEntities_1_), V0100.equipment(p_registerEntities_1_));
});
p_registerEntities_1_.register(map, "minecraft:falling_block", () ->
{
return DSL.optionalFields("BlockState", TypeReferences.BLOCK_STATE.in(p_registerEntities_1_), "TileEntityData", TypeReferences.BLOCK_ENTITY.in(p_registerEntities_1_));
});
p_registerEntities_1_.register(map, "minecraft:spectral_arrow", () ->
{
return DSL.optionalFields("inBlockState", TypeReferences.BLOCK_STATE.in(p_registerEntities_1_));
});
p_registerEntities_1_.register(map, "minecraft:chest_minecart", () ->
{
return DSL.optionalFields("DisplayState", TypeReferences.BLOCK_STATE.in(p_registerEntities_1_), "Items", DSL.list(TypeReferences.ITEM_STACK.in(p_registerEntities_1_)));
});
p_registerEntities_1_.register(map, "minecraft:commandblock_minecart", () ->
{
return DSL.optionalFields("DisplayState", TypeReferences.BLOCK_STATE.in(p_registerEntities_1_));
});
p_registerEntities_1_.register(map, "minecraft:furnace_minecart", () ->
{
return DSL.optionalFields("DisplayState", TypeReferences.BLOCK_STATE.in(p_registerEntities_1_));
});
p_registerEntities_1_.register(map, "minecraft:hopper_minecart", () ->
{
return DSL.optionalFields("DisplayState", TypeReferences.BLOCK_STATE.in(p_registerEntities_1_), "Items", DSL.list(TypeReferences.ITEM_STACK.in(p_registerEntities_1_)));
});
p_registerEntities_1_.register(map, "minecraft:minecart", () ->
{
return DSL.optionalFields("DisplayState", TypeReferences.BLOCK_STATE.in(p_registerEntities_1_));
});
p_registerEntities_1_.register(map, "minecraft:spawner_minecart", () ->
{
return DSL.optionalFields("DisplayState", TypeReferences.BLOCK_STATE.in(p_registerEntities_1_), TypeReferences.UNTAGGED_SPAWNER.in(p_registerEntities_1_));
});
p_registerEntities_1_.register(map, "minecraft:tnt_minecart", () ->
{
return DSL.optionalFields("DisplayState", TypeReferences.BLOCK_STATE.in(p_registerEntities_1_));
});
return map;
}
}
| 0 | 0.581864 | 1 | 0.581864 | game-dev | MEDIA | 0.952502 | game-dev | 0.73137 | 1 | 0.73137 |
X2CommunityCore/X2WOTCCommunityHighlander | 4,420 | X2WOTCCommunityHighlander/Src/XComGame/Classes/XGCharacterGenerator_Skirmisher.uc | class XGCharacterGenerator_Skirmisher extends XGCharacterGenerator
dependson(X2StrategyGameRulesetDataStructures);
var config array<int> PrimaryArmorColors;
var config array<int> SecondaryArmorColors;
var config array<name> MaleHelmets;
var config array<name> FemaleHelmets;
function bool IsSoldier(name CharacterTemplateName)
{
return true;
}
function X2CharacterTemplate SetCharacterTemplate(name CharacterTemplateName, name ArmorName)
{
MatchArmorTemplateForTorso = (ArmorName == '') ? 'SkirmisherArmor' : ArmorName;
MatchCharacterTemplateForTorso = 'NoCharacterTemplateName'; //Force the selector to use the armor type to filter torsos
return class'X2CharacterTemplateManager'.static.GetCharacterTemplateManager().FindCharacterTemplate('SkirmisherSoldier');
}
function TSoldier CreateTSoldier(optional name CharacterTemplateName, optional EGender eForceGender, optional name nmCountry = '', optional int iRace = -1, optional name ArmorName)
{
local X2SoldierClassTemplateManager ClassMgr;
local X2SoldierClassTemplate ClassTemplate;
kSoldier = super.CreateTSoldier('SkirmisherSoldier', eForceGender, nmCountry, iRace, ArmorName);
SetCountry('Country_Skirmisher');
GenerateName(kSoldier.kAppearance.iGender, kSoldier.nmCountry, kSoldier.strFirstName, kSoldier.strLastName, kSoldier.kAppearance.iRace);
ClassMgr = class'X2SoldierClassTemplateManager'.static.GetSoldierClassTemplateManager();
ClassTemplate = ClassMgr.FindSoldierClassTemplate('Skirmisher');
kSoldier.strNickName = GenerateNickname(ClassTemplate, kSoldier.kAppearance.iGender);
// Start issue #783
ModifyGeneratedUnitAppearance(CharacterTemplateName, eForceGender, nmCountry, iRace, ArmorName);
// End issue #783
return kSoldier;
}
function SetAccessories(X2SimpleBodyPartFilter BodyPartFilter, name CharacterTemplateName)
{
local X2BodyPartTemplateManager PartTemplateManager;
PartTemplateManager = class'X2BodyPartTemplateManager'.static.GetBodyPartTemplateManager();
//Turn off most customization options for Skirmishers
SetBodyPartToFirstInArray(PartTemplateManager, kSoldier.kAppearance.nmPatterns, "Patterns", BodyPartFilter.FilterAny);
SetBodyPartToFirstInArray(PartTemplateManager, kSoldier.kAppearance.nmWeaponPattern, "Patterns", BodyPartFilter.FilterAny);
SetBodyPartToFirstInArray(PartTemplateManager, kSoldier.kAppearance.nmTattoo_LeftArm, "Tattoos", BodyPartFilter.FilterAny);
SetBodyPartToFirstInArray(PartTemplateManager, kSoldier.kAppearance.nmTattoo_RightArm, "Tattoos", BodyPartFilter.FilterAny);
SetBodyPartToFirstInArray(PartTemplateManager, kSoldier.kAppearance.nmHaircut, "Hair", BodyPartFilter.FilterAny);
SetBodyPartToFirstInArray(PartTemplateManager, kSoldier.kAppearance.nmBeard, "Beards", BodyPartFilter.FilterAny);
SetBodyPartToFirstInArray(PartTemplateManager, kSoldier.kAppearance.nmHelmet, "Helmets", BodyPartFilter.FilterAny);
SetBodyPartToFirstInArray(PartTemplateManager, kSoldier.kAppearance.nmFacePropLower, "FacePropsLower", BodyPartFilter.FilterAny);
SetBodyPartToFirstInArray(PartTemplateManager, kSoldier.kAppearance.nmFacePropUpper, "FacePropsUpper", BodyPartFilter.FilterAny);
// Randomly choose a Skirmisher scar
RandomizeSetBodyPart(PartTemplateManager, kSoldier.kAppearance.nmScars, "Scars", BodyPartFilter.FilterByCharacter);
if (kSoldier.kAppearance.iGender == eGender_Male)
{
kSoldier.kAppearance.nmHelmet = default.MaleHelmets[`SYNC_RAND(default.MaleHelmets.Length)];
}
else
{
kSoldier.kAppearance.nmHelmet = default.FemaleHelmets[`SYNC_RAND(default.FemaleHelmets.Length)];
}
}
function SetArmorTints(X2CharacterTemplate CharacterTemplate)
{
super.SetArmorTints(CharacterTemplate);
kSoldier.kAppearance.iArmorTint = default.PrimaryArmorColors[`SYNC_RAND(default.PrimaryArmorColors.Length)];
kSoldier.kAppearance.iArmorTintSecondary = default.SecondaryArmorColors[`SYNC_RAND(default.SecondaryArmorColors.Length)];
}
function SetVoice(name CharacterTemplateName, name CountryName)
{
if (IsSoldier(CharacterTemplateName))
{
kSoldier.kAppearance.nmVoice = GetVoiceFromCountryAndGenderAndCharacter(CountryName, kSoldier.kAppearance.iGender, CharacterTemplateName);
if (kSoldier.kAppearance.nmVoice == '')
{
if (kSoldier.kAppearance.iGender == eGender_Male)
{
kSoldier.kAppearance.nmVoice = 'SkirmisherMaleVoice1_Localized';
}
else
{
kSoldier.kAppearance.nmVoice = 'SkirmisherFemaleVoice1_Localized';
}
}
}
} | 0 | 0.759465 | 1 | 0.759465 | game-dev | MEDIA | 0.739373 | game-dev | 0.905625 | 1 | 0.905625 |
GameFoundry/bsf | 8,499 | Source/Foundation/bsfEngine/GUI/BsGUISlider.cpp | //************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#include "GUI/BsGUISlider.h"
#include "GUI/BsGUISliderHandle.h"
#include "GUI/BsGUITexture.h"
#include "GUI/BsGUIDimensions.h"
#include "GUI/BsGUICommandEvent.h"
#include "GUI/BsGUIElementStyle.h"
using namespace std::placeholders;
namespace bs
{
GUISlider::GUISlider(bool horizontal, const String& styleName, const GUIDimensions& dimensions)
:GUIElementContainer(dimensions, styleName, GUIElementOption::AcceptsKeyFocus), mHorizontal(horizontal)
{
GUISliderHandleFlags flags = horizontal ? GUISliderHandleFlag::Horizontal : GUISliderHandleFlag::Vertical;
flags |= GUISliderHandleFlag::JumpOnClick;
mSliderHandle = GUISliderHandle::create(flags, getSubStyleName(getHandleStyleType()));
mBackground = GUITexture::create(getSubStyleName(getBackgroundStyleType()));
mFillBackground = GUITexture::create(getSubStyleName(getFillStyleType()));
mBackground->_setElementDepth(mSliderHandle->_getRenderElementDepthRange() + mFillBackground->_getRenderElementDepthRange());
mFillBackground->_setElementDepth(mSliderHandle->_getRenderElementDepthRange());
_registerChildElement(mSliderHandle);
_registerChildElement(mBackground);
_registerChildElement(mFillBackground);
mHandleMovedConn = mSliderHandle->onHandleMovedOrResized.connect(std::bind(&GUISlider::onHandleMoved, this, _1, _2));
}
GUISlider::~GUISlider()
{
mHandleMovedConn.disconnect();
}
const String& GUISlider::getHandleStyleType()
{
static String HANDLE_STYLE_TYPE = "SliderHandle";
return HANDLE_STYLE_TYPE;
}
const String& GUISlider::getBackgroundStyleType()
{
static String BACKGROUND_STYLE_TYPE = "SliderBackground";
return BACKGROUND_STYLE_TYPE;
}
const String& GUISlider::getFillStyleType()
{
static String FILL_STYLE_TYPE = "SliderFill";
return FILL_STYLE_TYPE;
}
Vector2I GUISlider::_getOptimalSize() const
{
Vector2I optimalSize = mSliderHandle->_getOptimalSize();
Vector2I backgroundSize = mBackground->_getOptimalSize();
optimalSize.x = std::max(optimalSize.x, backgroundSize.x);
optimalSize.y = std::max(optimalSize.y, backgroundSize.y);
return optimalSize;
}
void GUISlider::_updateLayoutInternal(const GUILayoutData& data)
{
GUILayoutData childData = data;
if (mHorizontal)
{
Vector2I optimalSize = mBackground->_getOptimalSize();
childData.area.height = optimalSize.y;
childData.area.y = data.area.y + (INT32)((data.area.height - childData.area.height) * 0.5f);
childData.clipRect = data.area;
childData.clipRect.clip(data.clipRect);
mBackground->_setLayoutData(childData);
optimalSize = mSliderHandle->_getOptimalSize();
childData.area.height = optimalSize.y;
childData.area.y = data.area.y + (INT32)((data.area.height - childData.area.height) * 0.5f);
childData.clipRect = data.area;
childData.clipRect.clip(data.clipRect);
mSliderHandle->_setLayoutData(childData);
UINT32 handleWidth = optimalSize.x;
optimalSize = mFillBackground->_getOptimalSize();
childData.area.height = optimalSize.y;
childData.area.y = data.area.y + (INT32)((data.area.height - childData.area.height) * 0.5f);
childData.area.width = mSliderHandle->getHandlePosPx() + handleWidth / 2;
childData.clipRect = data.area;
childData.clipRect.clip(data.clipRect);
mFillBackground->_setLayoutData(childData);
}
else
{
Vector2I optimalSize = mBackground->_getOptimalSize();
childData.area.width = optimalSize.x;
childData.area.x = data.area.x + (INT32)((data.area.width - childData.area.width) * 0.5f);
childData.clipRect = data.area;
childData.clipRect.clip(data.clipRect);
mBackground->_setLayoutData(childData);
optimalSize = mSliderHandle->_getOptimalSize();
childData.area.width = optimalSize.x;
childData.area.x = data.area.x + (INT32)((data.area.width - childData.area.width) * 0.5f);
childData.clipRect = data.area;
childData.clipRect.clip(data.clipRect);
mSliderHandle->_setLayoutData(childData);
UINT32 handleHeight = optimalSize.y;
optimalSize = mFillBackground->_getOptimalSize();
childData.area.width = optimalSize.x;
childData.area.x = data.area.x + (INT32)((data.area.width - childData.area.width) * 0.5f);
childData.area.height = mSliderHandle->getHandlePosPx() + handleHeight / 2;
childData.clipRect = data.area;
childData.clipRect.clip(data.clipRect);
mFillBackground->_setLayoutData(childData);
}
}
void GUISlider::styleUpdated()
{
mBackground->setStyle(getSubStyleName(getBackgroundStyleType()));
mFillBackground->setStyle(getSubStyleName(getFillStyleType()));
mSliderHandle->setStyle(getSubStyleName(getHandleStyleType()));
const GUIElementStyle* bgStyle = mBackground->_getStyle();
if(mHasFocus)
mBackground->setTexture(bgStyle->focused.texture);
else
mBackground->setTexture(bgStyle->normal.texture);
}
void GUISlider::setPercent(float pct)
{
float oldHandlePos = mSliderHandle->getHandlePos();
mSliderHandle->_setHandlePos(pct);
if (oldHandlePos != mSliderHandle->getHandlePos())
mSliderHandle->_markLayoutAsDirty();
}
float GUISlider::getPercent() const
{
return mSliderHandle->getHandlePos();
}
float GUISlider::getValue() const
{
float diff = mMaxRange - mMinRange;
return mMinRange + diff * mSliderHandle->getHandlePos();
}
void GUISlider::setValue(float value)
{
float diff = mMaxRange - mMinRange;
float pct = (value - mMinRange) / diff;
setPercent(pct);
}
void GUISlider::setRange(float min, float max)
{
mMinRange = min;
mMaxRange = max;
}
float GUISlider::getRangeMaximum() const
{
return mMaxRange;
}
float GUISlider::getRangeMinimum() const
{
return mMinRange;
}
void GUISlider::setStep(float step)
{
float range = mMaxRange - mMinRange;
if(range > 0.0f)
step = step / range;
else
step = 0.0f;
mSliderHandle->setStep(step);
}
float GUISlider::getStep() const
{
return mSliderHandle->getStep();
}
void GUISlider::setTint(const Color& color)
{
mBackground->setTint(color);
mSliderHandle->setTint(color);
}
void GUISlider::onHandleMoved(float newPosition, float newSize)
{
onChanged(getValue());
}
bool GUISlider::_commandEvent(const GUICommandEvent& ev)
{
const bool baseReturnValue = GUIElement::_commandEvent(ev);
const GUIElementStyle* bgStyle = mBackground->_getStyle();
if(ev.getType() == GUICommandEventType::FocusGained)
{
mHasFocus = true;
if(!_isDisabled())
mBackground->setTexture(bgStyle->focused.texture);
return true;
}
else if(ev.getType() == GUICommandEventType::FocusLost)
{
mHasFocus = false;
mBackground->setTexture(bgStyle->normal.texture);
return true;
}
else if(ev.getType() == GUICommandEventType::MoveLeft)
{
mSliderHandle->moveOneStep(false);
return true;
}
else if(ev.getType() == GUICommandEventType::MoveRight)
{
mSliderHandle->moveOneStep(true);
return true;
}
return baseReturnValue;
}
GUISliderHorz::GUISliderHorz(const String& styleName, const GUIDimensions& dimensions)
:GUISlider(true, styleName, dimensions)
{
}
GUISliderHorz* GUISliderHorz::create(const String& styleName)
{
return new (bs_alloc<GUISliderHorz>()) GUISliderHorz(getStyleName<GUISliderHorz>(styleName), GUIDimensions::create());
}
GUISliderHorz* GUISliderHorz::create(const GUIOptions& options, const String& styleName)
{
return new (bs_alloc<GUISliderHorz>()) GUISliderHorz(getStyleName<GUISliderHorz>(styleName), GUIDimensions::create(options));
}
const String& GUISliderHorz::getGUITypeName()
{
static String typeName = "SliderHorz";
return typeName;
}
GUISliderVert::GUISliderVert(const String& styleName, const GUIDimensions& dimensions)
:GUISlider(false, styleName, dimensions)
{
}
GUISliderVert* GUISliderVert::create(const String& styleName)
{
return new (bs_alloc<GUISliderVert>()) GUISliderVert(getStyleName<GUISliderVert>(styleName), GUIDimensions::create());
}
GUISliderVert* GUISliderVert::create(const GUIOptions& options, const String& styleName)
{
return new (bs_alloc<GUISliderVert>()) GUISliderVert(getStyleName<GUISliderVert>(styleName), GUIDimensions::create(options));
}
const String& GUISliderVert::getGUITypeName()
{
static String typeName = "SliderVert";
return typeName;
}
}
| 0 | 0.931849 | 1 | 0.931849 | game-dev | MEDIA | 0.688209 | game-dev | 0.973654 | 1 | 0.973654 |
naver/tamgu | 17,591 | bnf/optimise.tmg | file f(_current+'tamgun.cxx','r');
file sauve(_current+'codeparse.cxx','w');
string lg="tf!";
mapss keywords={"foldl":"folding",
"foldr":"folding",
"scanl":"folding",
"scanr":"folding",
"foldl1":"folding1",
"foldr1":"folding1",
"scanl1":"folding1",
"scanr1":"folding1",
"takeWhile":"filtering",
"flip":"flipping",
"filter":"filtering",
"dropWhile":"filtering",
"take":"taking",
"drop":"taking",
"map":"mapping",
"zipWith":"zipping",
"zip":"pairing",
"repeat":"cycling",
"cycle":"cycling",
"replicate":"repeating",
"any" : "taskellalltrue",
"all" : "taskellalltrue",
"and":"taskellboolchecking",
"or":"taskellboolchecking",
"xor":"taskellboolchecking"
};
string cr="\n";
map indexes={"atreg":34,"astreg":39,"apreg":34,"aspreg":39,"fstring":34,"festring":39,"astringdouble":34,"afullstring":34,"astringsimple":39,"anumber":'0123456789-',"valtail":"|","maptail":"|","valmaptail":"{","valvectortail":"[",
"jvector":"[","jmap":"{","telque":"<","intentionvect":"[","pintentionvect":"[","valmap":"{","parenthetic":"(","optional":"(","taskellvector":"[","taskellmap":"{","taskellmaptail":"|",
"valvector":"[","valmap":"{","term":"?","tuple":"(","predicatevariable":"?","valpredicatevector":"[","valmappredicate":"{","valtuple":"(",
"taskellcase":"c!","abool":lg,"localif":"i!", "tlquote":39, "tlist":"(","tlkeys":"{","tamgulisp":'\'
};
svector methodes=["m_expression","m_jexpression","m_pexpression","m_jdico",
"m_taskellexpression","m_taskellkeymap","m_forin","m_finaltoken","m_taskell","m_testswitch","m_hexpression",
"m_operator","m_hoper","m_operatoraffectation","m_comparator", "m_tlist","m_tlatom", "m_tlkeys","m_tlquote","m_tlkey"
];
map ikey;
map keyidx;
int i=0;
map kidx;
for (string sx in keywords) {
string val=keywords[sx];
if (ikey.test(val))
ikey[val].push(sx);
else {
ikey[val]=[sx];
kidx[val]=i;
i++;
}
keyidx[sx]=kidx[val];
}
map lestabs;
string nouvelle=@"
if (currentpos>=fx->stack.size())
return 0;
unsigned char xu = fx->stack[currentpos][intoken];
bool found = false;
switch (xu) {
"@;
string avecchaine = @"
if (currentpos>=fx->stack.size())
return 0;
string x=fx->stack[currentpos];
if (keys.find(x)==keys.end())
return 0;
int i=keys[x];
bool found = false;
switch (i) {
"@;
string s,sx,sxx,regle;
svector v,vx,ve;
bool premier=true;
map regles,leschars;
treemapss varstrings;
for (s in f) {
if ('#include "tamgun.h"' in s) {
s=s.replace('#include "tamgun.h"','#include "codeparse.h"');
sauve.write(regle);
}
if ("static const char* varstring" in s)
varstrings[s["varstring":"="][:-1]]=s['"':'"'][1:-1];
if ("bnf_tamgu::" in s) {
if (premier)
sauve.write(regle);
else {
sx=regle["::":"("][2:-1];
if ("BODYSYMBOL" in regle or "BODYCONTEXTUAL" in regle) {
regle["x_node* subtree=NULL;"]="//x_node* subtree=NULL;";
regle["int addsubtree=0;"]="//int addsubtree=0;";
}
if ("BODYOPTIONAL" in regle or "BODYWHILE" in regle) {
if ("setfail(" not in regle) {
regle["long pos=currentpos;"]="//long pos=currentpos;";
regle["int itok=intoken;"]="//int itok=intoken;";
regle["bool exitonfail=false;"]="//bool exitonfail=false;";
}
}
string lenomcomplet=sx;
if ("_" in sx[3:])
sx=sx["m_":"_"][:-1];
if (sx=="m_intentionvect" || sx=="m_pintentionvect") {
v=< <trim x> | x <- regle.trim().split(cr) >;
int ipos="//BODYOR" in v;
string reg;
reg="bool fnd=false;\n";
reg+="bool nbcomma=false;\n";
reg+="unsigned char c;\n";
reg+="for (long ix=currentpos+1;ix<fx->stack.size();ix++) {\n";
reg+="c=fx->stack[ix][0];\n";
reg+="if (c=='[' || c==']')\nreturn 0;\n";
reg+="if (c==',') {\n";
reg+="if (nbcomma)\nreturn 0;\nnbcomma=true;\n}\n";
reg+='if (fx->stack[ix] == "..")'+" {\nfnd=true;\nbreak;\n}\n}\n";
reg+="if (!fnd)\nreturn 0;\n";
v.insert(ipos,reg);
reg=v.join("\n");
reg+="\n";
sauve.writeln(reg);
regle=s;
continue;
}
if ("::m_operator_" in regle or "::m_operatoraffectation_" in regle or "::m_comparator_" in regle or "::m_hoper_" in regle) {
sx=regle["::":"("][4:-1];
string k=regle["if (!":")"]["'":"'"][1:-1];
if (k!="") {
if (k=='!')
indexes[sx]=33;
else
indexes[sx]=k;
}
}
if ( "::m_notreserved" in regle) {
v=< <trim x> | x <- regle.trim().split(cr) >;
vx=<x | x <- v," || " in x>;
sxx=vx[0]['(':'))'][1:-1];
vx=sxx.split(" || ");
string reg = @" static std::set<string> keywords;
static bool init = true;
if (init) {
init = false;
"@;
for (sxx in vx) {
string k = sxx["var":")"][:-1];
reg += " keywords.insert("+k+");\n";
}
reg += @" }
"@;
svector vres;
vres.push(v[0]);
vres.push(reg);
reg = @" if (keywords.find(fx->stack[currentpos]) != keywords.end()) {
lret+=fx->stack[currentpos];
incrementpos();"@;
int io;
for (io in <1,v,1>) {
sxx = v[io];
if ("||" in sxx)
break;
vres.push(sxx);
}
vres.push(reg);
io++;
vres.push(v[io]);
vres.push("}");
io++;
vres &&&= v[io:];
reg = vres.join("\n");
reg+="\n\n";
sauve.write(reg);
regle=s;
continue;
}
if ( "::m_wrong" in regle || "::m_notafunction" in regle || "::m_notapredicate" in regle || "::m_functionsort" in regle || "::m_filterkeyword" in regle) {
v=< <trim x> | x <- regle.trim().split(cr) >;
vx=<x | x <- v," || " in x>;
sxx=vx[0]['(':'))'][1:-1];
vx=sxx.split(" || ");
treemap vo;
for (sxx in vx) {
string k=sxx['varstring':')'][:-1];
k=varstrings[k];
if (vo.test(k[0]))
vo[k[0]].push(sxx);
else
vo[k[0]]=[sxx];
}
string reg=@"
bool found=false;
unsigned char xs = fx->stack[currentpos][intoken];
switch (xs) {
"@;
vector vdefault;
string e;
for (e in vo) {
if (e.sizeb()>1) {
vdefault.push(e);
}
else {
reg+="case '"+e+"' :\n";
if (vo[e].size()==1)
reg+="if ("+vo[e][0]+")\nfound=true;\nbreak;\n";
else {
reg+="if ("+vo[e].join(" || ")+")\nfound=true;\nbreak;\n";
}
}
}
if (vdefault.size()) {
reg+="default:\n";
svector vdef;
for (e in vdefault)
vdef&&&=vo[e];
reg+="if ("+vdef.join(" || ")+")\nfound=true;\n";
}
reg+="}\n";
reg+="if (found)";
vx=<if (" || " in x) reg else x | x <- v>;
reg=vx.join("\n");
reg+="\n\n";
sauve.write(reg);
regle=s;
continue;
}
if ("::m_hmetafunctions" in regle or "::m_hcompose" in regle) {
v=< <trim x> | x <- regle.trim().split(cr) >;
vx=<x | x <- v," || " in x>;
if (vx.size()) {
string reg="static map<string,int> keys;\nstatic bool init=false;\nif (!init) {\n";
svector u=<'keys["'+x+'"]='+keyidx[x]+";" | x <- keyidx.keys()>;
reg+=u.join("\n");
reg+="\ninit=true;\n}";
v.insert(2,reg);
vx=vx[0][4:-1].split(" || ");
reg=avecchaine;
for (sx in vx) {
string idx=sx["_":"("][1:-1];
idx="case "+kidx[idx]+":\nif ("+sx+") \nfound=true;\nbreak;\n";
reg+=idx;
}
reg+="}\nif (found)";
vx=<if (" || " in x) reg else x | x <- v>;
reg=vx.join("\n");
reg+="\n\n";
sauve.write(reg);
regle=s;
continue;
}
}
//Methodes
if (sx in methodes) {
v=< <trim x> | x <- regle.trim().split(cr) >;
vx=<x | x <- v," || " in x>;
if (vx.size()) {
vx=vx[0][4:-1].split(" || ");
primemap ors;
string idx;
for (sx in vx) {
sxx=sx[2:"("][:-1];
if (indexes.test(sxx)) {
idx=indexes[sxx];
if (idx[-1]=='!')
ors[indexes[sxx]]=[sx];
else {
idx=indexes[sxx][0];
if (sxx=="predicatevariable")
ors["#"]=[sx];
if (ors.test(idx))
ors[idx].push(sx);
else
ors[idx]=[sx];
if (string(indexes[sxx])!=idx) {
ors[indexes[sxx]]=[sx];
}
}
}
else {
if ("!" in sx) {
if ("x_test_char" in sx) {
idx=sx["'":"'"][1:-1];
if (ors.test(idx))
ors[idx].push(sx);
else
ors[idx]=[sx];
}
break;
}
if ("x_test_in" in sx) {
string k=sx[r"tab%d+"];
for (idx in lestabs[k]) {
if (ors.test(idx))
ors[idx].push(sx);
else
ors[idx]=[sx];
}
}
elif ("x_test_char" in sx) {
idx=sx["'":"'"][1:-1];
if (ors.test(idx))
ors[idx].push(sx);
else
ors[idx]=[sx];
}
else {
if (ors.test("default"))
ors["default"].push(sx);
else
ors["default"]=[sx];
}
}
}
if (ors.size()==1) {
sauve.write(regle);
}
else {
string reg=nouvelle;
bool def=false;
int lettre=0;
for (sx in ors) {
if (sx[0]!="0") {
if (sx=="default") {
def=true;
continue;
}
if (sx[-1]=='!')
lettre++;
else {
if (sx.isdigit() and sx!="0")
reg+="case "+sx+":\nif (";
else {
if (sx == '\')
reg+="case '\\\\':\nif (";
else
reg+="case '"+sx+"':\nif (";
}
bool p=true;
for (string e in ors[sx]) {
if (not p)
reg+=" || ";
p=false;
reg+=e;
}
reg+=") \nfound=true;\nbreak;\n";
}
}
}
for (sx in ors) {
if (sx[0]=='0') {
if (sx.size()==1) {
reg+="case '"+sx+"':\nif (";
bool p=true;
for (string e in ors[sx]) {
if (not p)
reg+=" || ";
p=false;
reg+=e;
}
}
else {
ve=sx[1:].split("");
ve=<("case '"+x+"':") | x <- ve>;
reg+=ve.join("\n");
reg+="\n";
reg+="if ("+ors[sx][0];
}
reg+=") \nfound=true;\nbreak;\n";
}
}
string defaut;
if (def) {
for (string e in ors["default"])
defaut+=" || "+e;
}
if (lettre) {
for (sx in ors) {
if (sx[-1]=='!') {
sxx=sx[:-1];
ve=<("case '"+x+"':") | x <- sxx>;
reg+=ve.join("\n");
if (lettre>1)
reg+="\nif ("+ors[sx][0]+defaut+") \nfound=true;\nbreak;\n";
else
reg+="\nif ("+ors[sx][0]+") {\nfound=true;\nbreak;\n}\n";
}
}
}
if (def) {
reg+="default:\nif (";
bool p=true;
for (string e in ors["default"]) {
if (not p)
reg+=" || ";
p=false;
reg+=e;
}
reg+=") \nfound=true;\n";
}
reg+="}\nif (found)";
vx=<if (" || " in x) reg else x | x <- v>;
reg=vx.join("\n");
reg+="\n\n";
sauve.write(reg);
}
}
else
sauve.write(regle);
}
else
sauve.write(regle);
}
premier=false;
regle=s;
}
else {
if ("static char tab" in s) {
sx=s["tab":"["][:-1];
svector sub=s["{":"}"][1:-1].split(",")[:-1];
lestabs[sx]=< x[1:-1] | x <- sub>;
}
regle+=s;
}
}
sauve.write(regle);
sauve.close();
f.close();
file relire(_current+'codeparse.cxx');
string txt=relire.read();
relire.close();
txt=txt.indent(4, false);
file sa(_current+'codeparse.cxx','w');
sa.write(txt);
sa.close();
relire.openread(_current+'tamgun.h');
txt=relire.read();
relire.close();
txt=txt.indent(4, false);
sa.openwrite(_current+'tamgun.h');
sa.write(txt);
sa.close();
| 0 | 0.94217 | 1 | 0.94217 | game-dev | MEDIA | 0.538752 | game-dev | 0.97171 | 1 | 0.97171 |
tx00100xt/SeriousSamClassic-VK | 6,164 | SamTFE/Sources/Engine/World/WorldCollision.h | /* Copyright (c) 2002-2012 Croteam Ltd.
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#ifndef SE_INCL_WORLDCOLLISION_H
#define SE_INCL_WORLDCOLLISION_H
#ifdef PRAGMA_ONCE
#pragma once
#endif
#include <Engine/Base/Lists.h>
#include <Engine/Templates/StaticArray.h>
#include <Engine/Math/Vector.h>
#include <Engine/Math/Matrix.h>
#include <Engine/Math/Placement.h>
#include <Engine/Entities/EntityCollision.h>
/*
* A class used for clipping a movement.
*/
class CClipMove {
public:
BOOL cm_bMovingBrush; // set if moving a brush (some things are reversed then)
CMovableEntity *cm_penMoving; // entity that is moving
CEntity *cm_penA; // entity A - can be only model
CEntity *cm_penB; // entity B - can be either model or brush
// masks for collision flags of other entities
ULONG cm_ulTestMask1;
ULONG cm_ulTestMask2;
ULONG cm_ulPassMaskA; // pass - send event to A
ULONG cm_ulPassMaskB; // pass - send event to B
// test if should test with some entity
inline BOOL MustTest(CEntity *pen) {
return
(pen->en_ulCollisionFlags&cm_ulTestMask1)&&
(pen->en_ulCollisionFlags&cm_ulTestMask2);
};
// send pass if needed
inline BOOL SendPassEvent(CEntity *pen);
CListHead cm_lhActiveSectors; // brush sectors that are queued for testing
// placement of entity A
FLOAT3D cm_vA0; FLOATmatrix3D cm_mA0; // at the start of movement
FLOAT3D cm_vA1; FLOATmatrix3D cm_mA1; // at the end of movement
// placement of entity B
FLOAT3D cm_vB0; FLOATmatrix3D cm_mB0; // at the start of movement
FLOAT3D cm_vB1; FLOATmatrix3D cm_mB1; // at the end of movement
CStaticArray<CMovingSphere> *cm_pamsA; // bounding spheres used by entity A
CStaticArray<CMovingSphere> *cm_pamsB; // bounding spheres used by entity B (if not brush)
// helper variables
FLOATaabbox3D cm_boxMovementPath; // aabbox around entire movement path
CEntity *cm_penTested; // entity to be remembered if hit (A or B)
CBrushPolygon *cm_pbpoTested; // brush polygon to be remembered if hit
class CWorld *cm_pwoWorld; // world that movement is taking place in
// projections for converting from space of entity A to space of entity B
FLOAT3D cm_vAToB0; FLOATmatrix3D cm_mAToB0; // at the start of movement
FLOAT3D cm_vAToB1; FLOATmatrix3D cm_mAToB1; // at the end of movement
// for converting from space of entity B to absolute space
FLOAT3D cm_vBToAbsolute; FLOATmatrix3D cm_mBToAbsolute;
FLOATaabbox3D cm_boxMovementPathAbsoluteA; // movement box in absolute space for A entity
// get start and end positions of an entity in this tick
inline void GetPositionsOfEntity(
CEntity *pen, FLOAT3D &v0, FLOATmatrix3D &m0, FLOAT3D &v1, FLOATmatrix3D &m1);
/* Project spheres of entity A to space of entity B. */
void ProjectASpheresToB(void);
/* Find movement box in absolute space for A entity. */
void FindAbsoluteMovementBoxForA(void);
/* Clip a moving point to a sphere, update collision data. */
inline void ClipMovingPointToSphere(const FLOAT3D &vStart, const FLOAT3D &vEnd,
const FLOAT3D &vSphereCenter, const FLOAT fSphereRadius);
/* Clip a moving point to a cylinder, update collision data. */
inline void ClipMovingPointToCylinder(const FLOAT3D &vStart, const FLOAT3D &vEnd,
const FLOAT3D &vCylinderBottomCenter, const FLOAT3D &vCylinderTopCenter,
const FLOAT fCylinderRadius);
/* Clip a moving sphere to a standing sphere, update collision data. */
void ClipMovingSphereToSphere(const CMovingSphere &msMoving,
const CMovingSphere &msStanding);
/* Clip a moving sphere to a brush polygon, update collision data. */
void ClipMovingSphereToBrushPolygon(
const CMovingSphere &msMoving, CBrushPolygon *pbpoPolygon);
/* Clip a moving sphere to a terrain polygon, update collision data. */
void ClipMovingSphereToTerrainPolygon(
const CMovingSphere &msMoving, const FLOAT3D &v0, const FLOAT3D &v1, const FLOAT3D &v2);
/* Clip movement to a brush polygon. */
void ClipMoveToBrushPolygon(CBrushPolygon *pbpoPolygon);
/* Clip movement to a terrain polygon. */
void ClipMoveToTerrainPolygon(const FLOAT3D &v0, const FLOAT3D &v1, const FLOAT3D &v2);
/* Prepare projections and spheres for movement clipping. */
void PrepareProjectionsAndSpheres(void);
/* Clip movement if B is a model. */
void ClipModelMoveToModel(void);
/* Clip movement if B is a brush. */
void ClipBrushMoveToModel(void);
/* Clip movement to a model entity. */
void ClipMoveToModel(CEntity *penModel);
void ClipToNonZoningSector(CBrushSector *pbsc);
void ClipToZoningSector(CBrushSector *pbsc);
void ClipToTerrain(CEntity *pen);
/* Cache near polygons of movable entity. */
void CacheNearPolygons(void);
/* Clip movement to brush sectors near the entity. */
void ClipMoveToBrushes(void);
/* Clip movement to models near the entity. */
void ClipMoveToModels(void);
/* Clip movement to the world. */
void ClipMoveToWorld(class CWorld *pwoWorld);
public:
// these are filled by clipping algorithm:
CEntity *cm_penHit; // entity hit when moving. NULL if nothing was hit
CBrushPolygon *cm_pbpoHit; // brush polygon that was hit (NULL if did not hit a brush)
FLOAT cm_fMovementFraction; // fraction of movement done before hitting
FLOATplane3D cm_plClippedPlane; // the plane that was hit (in absolute space)
FLOAT3D cm_vClippedLine; // vector describing part of test line that was clipped
/* Constructor. */
CClipMove(CMovableEntity *penEntity);
};
#endif /* include-once check. */
| 0 | 0.839509 | 1 | 0.839509 | game-dev | MEDIA | 0.979139 | game-dev | 0.63149 | 1 | 0.63149 |
RealZST/TD3-based_UAV_Collision_Avoidance | 2,726 | Library/PackageCache/com.unity.timeline@1.2.10/Editor/Window/TimelineWindow_ActiveTimeline.cs | using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;
namespace UnityEditor.Timeline
{
partial class TimelineWindow
{
private TimelineAsset m_PreviousMasterSequence;
public void ClearCurrentTimeline()
{
SetCurrentTimeline(null, null, null, true);
}
public void SetCurrentTimeline(TimelineAsset seq)
{
SetCurrentTimeline(seq, null, null);
}
public void SetCurrentTimeline(PlayableDirector director, TimelineClip hostClip = null)
{
var asset = director != null ? director.playableAsset as TimelineAsset : null;
SetCurrentTimeline(asset, director, hostClip);
}
void SetCurrentTimeline(TimelineAsset seq, PlayableDirector instanceOfDirector, TimelineClip hostClip, bool force = false)
{
if (state == null)
return;
if (!force &&
state.editSequence.hostClip == hostClip &&
state.editSequence.director == instanceOfDirector &&
state.editSequence.asset == seq)
return;
state.SetCurrentSequence(seq, instanceOfDirector, hostClip);
}
void OnBeforeSequenceChange()
{
treeView = null;
m_MarkerHeaderGUI = null;
m_TimeAreaDirty = true;
state.Reset();
m_PlayableLookup.ClearPlayableLookup();
// clear old editors to caches, like audio previews, get flushed
CustomTimelineEditorCache.ClearCache<ClipEditor>();
CustomTimelineEditorCache.ClearCache<MarkerEditor>();
CustomTimelineEditorCache.ClearCache<TrackEditor>();
m_PreviousMasterSequence = state.masterSequence.asset;
}
void OnAfterSequenceChange()
{
Repaint();
m_SequencePath = state.GetCurrentSequencePath();
m_LastFrameHadSequence = state.editSequence.asset != null;
TimelineWindowViewPrefs.SaveAll();
// this prevent clearing the animation window when going in/out of playmode, but
// clears it when we switch master timelines
// the cast to a object will handle the case where the sequence has been deleted.
object previousMasterSequence = m_PreviousMasterSequence;
bool isDeleted = previousMasterSequence != null && m_PreviousMasterSequence == null;
bool hasChanged = m_PreviousMasterSequence != null && m_PreviousMasterSequence != state.masterSequence.asset;
if (isDeleted || hasChanged)
TimelineAnimationUtilities.UnlinkAnimationWindow();
}
}
}
| 0 | 0.820312 | 1 | 0.820312 | game-dev | MEDIA | 0.874254 | game-dev | 0.93887 | 1 | 0.93887 |
TeamLumi/opendpr | 1,687 | Assets/Scripts/Dpr/Battle/Logic/Handler/DefaultPowerUp.cs | namespace Dpr.Battle.Logic.Handler
{
public static class DefaultPowerUp
{
private static readonly GET_FUNC_TABLE_ELEM[] GET_FUNC_TABLE = new GET_FUNC_TABLE_ELEM[]
{
new GET_FUNC_TABLE_ELEM(DefaultPowerUpReason.DEFAULT_POWERUP_REASON_NUSI, ADD_Nusi),
new GET_FUNC_TABLE_ELEM(DefaultPowerUpReason.DEFAULT_POWERUP_REASON_ULTRA_BEAST, ADD_Nusi),
new GET_FUNC_TABLE_ELEM(DefaultPowerUpReason.DEFAULT_POWERUP_REASON_BOSS, ADD_Nusi),
};
private static readonly EventFactor.EventHandlerTable[] HandlerTable_Nusi = new EventFactor.EventHandlerTable[]
{
new EventFactor.EventHandlerTable(EventID.MEMBER_IN_DEFAULT_POWERUP, handler_Nusi_MemberIn),
};
// TODO
public static HandlerGetFunc getHandlerGetFunc(DefaultPowerUpReason powerUpReason) { return default; }
// TODO
public static void removeFactorForce(EventSystem pEventSystem, byte pokeId, DefaultPowerUpReason powerUpReason) { }
// TODO
public static bool Add(EventSystem pEventSystem, BTL_POKEPARAM poke) { return default; }
// TODO
public static void Remove(EventSystem pEventSystem, BTL_POKEPARAM poke) { }
// TODO
public static EventFactor.EventHandlerTable[] ADD_Nusi() { return default; }
// TODO
public static void handler_Nusi_MemberIn(in EventFactor.EventHandlerArgs args, byte pokeID) { }
public delegate EventFactor.EventHandlerTable[] HandlerGetFunc();
private struct GET_FUNC_TABLE_ELEM
{
public DefaultPowerUpReason powerUpReason;
public HandlerGetFunc func;
public GET_FUNC_TABLE_ELEM(DefaultPowerUpReason powerUpReason, HandlerGetFunc func)
{
this.powerUpReason = powerUpReason;
this.func = func;
}
}
}
} | 0 | 0.68179 | 1 | 0.68179 | game-dev | MEDIA | 0.947802 | game-dev | 0.598319 | 1 | 0.598319 |
UWPX/UWPX-Client | 2,351 | UWPX_UI_Context/Classes/ValueConverter/LogLevelStringValueConverter.cs | using System;
using Logging;
using Windows.UI.Xaml.Data;
namespace UWPX_UI_Context.Classes.ValueConverter
{
public sealed class LogLevelStringValueConverter: IValueConverter
{
//--------------------------------------------------------Attributes:-----------------------------------------------------------------\\
#region --Attributes--
#endregion
//--------------------------------------------------------Constructor:----------------------------------------------------------------\\
#region --Constructors--
#endregion
//--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
#region --Set-, Get- Methods--
#endregion
//--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\
#region --Misc Methods (Public)--
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value is LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.NONE:
return "None";
case LogLevel.ERROR:
return "Error";
case LogLevel.WARNING:
return "Warning";
case LogLevel.INFO:
return "Info";
case LogLevel.DEBUG:
return "Debug";
case LogLevel.TRACE:
return "Trace";
default:
return logLevel.ToString();
}
}
return "";
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
#endregion
#region --Misc Methods (Private)--
#endregion
#region --Misc Methods (Protected)--
#endregion
//--------------------------------------------------------Events:---------------------------------------------------------------------\\
#region --Events--
#endregion
}
}
| 0 | 0.503903 | 1 | 0.503903 | game-dev | MEDIA | 0.388287 | game-dev | 0.821386 | 1 | 0.821386 |
DruidMech/UE4-CPP-Shooter-Series | 2,597 | Source Code Per Lesson/Section 10 - Outline and Glow Effects/186 Create Icon Animation/Weapon.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Item.h"
#include "AmmoType.h"
#include "Weapon.generated.h"
UENUM(BlueprintType)
enum class EWeaponType : uint8
{
EWT_SubmachineGun UMETA(DisplayName = "SubmachineGun"),
EWT_AssaultRifle UMETA(DisplayName = "AssaultRifle"),
EWT_MAX UMETA(DisplayName = "DefaultMAX")
};
/**
*
*/
UCLASS()
class SHOOTER_API AWeapon : public AItem
{
GENERATED_BODY()
public:
AWeapon();
virtual void Tick(float DeltaTime) override;
protected:
void StopFalling();
private:
FTimerHandle ThrowWeaponTimer;
float ThrowWeaponTime;
bool bFalling;
/** Ammo count for this Weapon */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Weapon Properties", meta = (AllowPrivateAccess = "true"))
int32 Ammo;
/** Maximum ammo that our weapon can hold */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Weapon Properties", meta = (AllowPrivateAccess = "true"))
int32 MagazineCapacity;
/** The type of weapon */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Weapon Properties", meta = (AllowPrivateAccess = "true"))
EWeaponType WeaponType;
/** The type of ammo for this weapon */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Weapon Properties", meta = (AllowPrivateAccess = "true"))
EAmmoType AmmoType;
/** FName for the Reload Montage Section */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Weapon Properties", meta = (AllowPrivateAccess = "true"))
FName ReloadMontageSection;
/** True when moving the clip while reloading */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Weapon Properties", meta = (AllowPrivateAccess = "true"))
bool bMovingClip;
/** Name for the clip bone */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Weapon Properties", meta = (AllowPrivateAccess = "true"))
FName ClipBoneName;
public:
/** Adds an impulse to the Weapon */
void ThrowWeapon();
FORCEINLINE int32 GetAmmo() const { return Ammo; }
FORCEINLINE int32 GetMagazineCapacity() const { return MagazineCapacity; }
/** Called from Character class when firing Weapon */
void DecrementAmmo();
FORCEINLINE EWeaponType GetWeaponType() const { return WeaponType; }
FORCEINLINE EAmmoType GetAmmoType() const { return AmmoType; }
FORCEINLINE FName GetReloadMontageSection() const { return ReloadMontageSection; }
FORCEINLINE FName GetClipBoneName() const { return ClipBoneName; }
void ReloadAmmo(int32 Amount);
FORCEINLINE void SetMovingClip(bool Move) { bMovingClip = Move; }
bool ClipIsFull();
};
| 0 | 0.840527 | 1 | 0.840527 | game-dev | MEDIA | 0.977619 | game-dev | 0.562503 | 1 | 0.562503 |
Aussiemon/Darktide-Source-Code | 32,733 | scripts/extension_systems/behavior/nodes/actions/bot/bt_bot_melee_action.lua | -- chunkname: @scripts/extension_systems/behavior/nodes/actions/bot/bt_bot_melee_action.lua
require("scripts/extension_systems/behavior/nodes/bt_node")
local Armor = require("scripts/utilities/attack/armor")
local ArmorSettings = require("scripts/settings/damage/armor_settings")
local Blackboard = require("scripts/extension_systems/blackboard/utilities/blackboard")
local Breed = require("scripts/utilities/breed")
local FixedFrame = require("scripts/utilities/fixed_frame")
local NavQueries = require("scripts/utilities/nav_queries")
local PlayerUnitVisualLoadout = require("scripts/extension_systems/visual_loadout/utilities/player_unit_visual_loadout")
local Stamina = require("scripts/utilities/attack/stamina")
local BtBotMeleeAction = class("BtBotMeleeAction", "BtNode")
BtBotMeleeAction.enter = function (self, unit, breed, blackboard, scratchpad, action_data, t)
scratchpad.engaging = false
scratchpad.engage_change_time = 0
scratchpad.engage_update_time = 0
scratchpad.last_evaluate_t = t
local unit_data_extension = ScriptUnit.extension(unit, "unit_data_system")
local inventory_component = unit_data_extension:read_component("inventory")
local visual_loadout_extension = ScriptUnit.extension(unit, "visual_loadout_system")
local weapon_template = PlayerUnitVisualLoadout.wielded_weapon_template(visual_loadout_extension, inventory_component)
scratchpad.weapon_template = weapon_template
local input_extension = ScriptUnit.extension(unit, "input_system")
local bot_unit_input = input_extension:bot_unit_input()
local soft_aiming = true
bot_unit_input:set_aiming(true, soft_aiming)
local group_extension = ScriptUnit.extension(unit, "group_system")
local bot_group = group_extension:bot_group()
local bot_group_data = group_extension:bot_group_data()
local navigation_extension = ScriptUnit.extension(unit, "navigation_system")
scratchpad.behavior_extension = ScriptUnit.extension(unit, "behavior_system")
scratchpad.bot_group = bot_group
scratchpad.bot_group_data = bot_group_data
scratchpad.bot_unit_input = bot_unit_input
scratchpad.darkness_system = Managers.state.extension:system("darkness_system")
scratchpad.first_person_component = unit_data_extension:read_component("first_person")
scratchpad.follow_component = blackboard.follow
scratchpad.locomotion_component = unit_data_extension:read_component("locomotion")
scratchpad.melee_component = Blackboard.write_component(blackboard, "melee")
scratchpad.nav_world = navigation_extension:nav_world()
scratchpad.perception_component = blackboard.perception
scratchpad.perception_extension = ScriptUnit.extension(unit, "perception_system")
scratchpad.stamina_component = unit_data_extension:read_component("stamina")
scratchpad.traverse_logic = navigation_extension:traverse_logic()
scratchpad.weapon_action_component = unit_data_extension:read_component("weapon_action")
scratchpad.weapon_extension = ScriptUnit.extension(unit, "weapon_system")
scratchpad.action_input_extension = ScriptUnit.extension(unit, "action_input_system")
scratchpad.slot_extension = ScriptUnit.extension(unit, "slot_system")
scratchpad.random_dodge_check_t = 0
local archetype = unit_data_extension:archetype()
scratchpad.archetype_stamina_template = archetype.stamina
local attack_intensity_extension = ScriptUnit.extension(unit, "attack_intensity_system")
scratchpad.attack_intensity_extension = attack_intensity_extension
end
BtBotMeleeAction.init_values = function (self, blackboard)
local melee_component = Blackboard.write_component(blackboard, "melee")
melee_component.engage_position:store(0, 0, 0)
melee_component.engage_position_set = false
melee_component.stop_at_current_position = false
end
BtBotMeleeAction.leave = function (self, unit, breed, blackboard, scratchpad, action_data, t, reason, destroy)
local bot_unit_input = scratchpad.bot_unit_input
bot_unit_input:set_aiming(false)
if scratchpad.engaging then
self:_disengage(scratchpad, t)
end
self:_clear_pending_attack(scratchpad)
end
BtBotMeleeAction.run = function (self, unit, breed, blackboard, scratchpad, action_data, dt, t)
local done, evaluate = self:_update_melee(unit, scratchpad, action_data, t)
if done then
return "done"
else
return "running", evaluate
end
end
local ENGAGE_TIME_WINDOW_MELEE = 5
local ENGAGE_TIME_WINDOW_DEFAULT = 0
local EVAL_TIMER_MELEE = 2
local EVAL_TIMER_ENGAGE = 1
local EVAL_TIMER_DEFAULT = 3
local DEFAULT_DEFENSE_META_DATA = {
push = "heavy",
push_action_input = "push",
start_action_input = "block",
stop_action_input = "block_release",
}
BtBotMeleeAction._update_melee = function (self, unit, scratchpad, action_data, t)
local perception_component = scratchpad.perception_component
local target_unit = perception_component.target_enemy
if not HEALTH_ALIVE[target_unit] then
return true
end
local perception_extension = scratchpad.perception_extension
local _, num_enemies_in_proximity = perception_extension:enemies_in_proximity()
scratchpad.num_enemies_in_proximity = num_enemies_in_proximity
local target_unit_data_extension = ScriptUnit.has_extension(target_unit, "unit_data_system")
local target_breed = target_unit_data_extension and target_unit_data_extension:breed()
local aim_position = self:_aim_position(target_unit, target_breed)
local bot_unit_input = scratchpad.bot_unit_input
bot_unit_input:set_aim_position(aim_position)
local first_person_component = scratchpad.first_person_component
local current_position = first_person_component.position
local follow_component = scratchpad.follow_component
local follow_position = follow_component.destination:unbox()
local attack_performed, wants_engage, eval_timer = false
local already_engaged, engage_change_time = scratchpad.engaging, scratchpad.engage_change_time
local locomotion_component = scratchpad.locomotion_component
local current_velocity = locomotion_component.velocity_current
local target_velocity = self:_target_velocity(target_unit, target_breed)
local self_position = POSITION_LOOKUP[unit]
local nav_world, traverse_logic = scratchpad.nav_world, scratchpad.traverse_logic
local target_position = self:_target_unit_position(self_position, target_unit, action_data, nav_world, traverse_logic)
local attack_meta_data = self:_choose_attack(target_unit, target_breed, scratchpad)
local melee_range = self:_calculate_melee_range(target_breed, attack_meta_data)
local is_in_melee_range = self:_is_in_melee_range(current_position, aim_position, melee_range, current_velocity, target_velocity, scratchpad, t)
local should_defend = self:_should_defend(unit, target_unit, scratchpad)
local is_defending = scratchpad.is_defending
local weapon_template = scratchpad.weapon_template
local defense_meta_data = weapon_template.defense_meta_data or DEFAULT_DEFENSE_META_DATA
if should_defend and not is_defending then
self:_update_start_defend(scratchpad, defense_meta_data)
eval_timer = EVAL_TIMER_MELEE
elseif is_defending then
local latest_fixed_t = FixedFrame.get_latest_fixed_time()
self:_update_defend(unit, should_defend, defense_meta_data, scratchpad, is_in_melee_range, target_unit, target_breed, latest_fixed_t, t)
scratchpad.start_defend_request_id = nil
eval_timer = EVAL_TIMER_MELEE
elseif scratchpad.is_attacking then
self:_update_attack(scratchpad, t)
eval_timer = math.huge
elseif is_in_melee_range then
local weapon_extension = scratchpad.weapon_extension
if self:_can_start_attack(attack_meta_data, weapon_extension) then
self:_start_attack(attack_meta_data, scratchpad, t)
attack_performed = true
end
wants_engage = perception_component.aggressive_mode or already_engaged and t - engage_change_time < ENGAGE_TIME_WINDOW_MELEE
eval_timer = EVAL_TIMER_MELEE
elseif self:_is_in_engage_range(self_position, target_position, action_data, follow_position) then
wants_engage = true
eval_timer = EVAL_TIMER_ENGAGE
else
wants_engage = already_engaged and t - engage_change_time <= ENGAGE_TIME_WINDOW_DEFAULT
eval_timer = EVAL_TIMER_DEFAULT
end
local engage = wants_engage and self:_allow_engage(unit, target_unit, target_position, target_breed, scratchpad, action_data, already_engaged, aim_position, follow_position)
if engage and not already_engaged then
self:_engage(scratchpad, t)
already_engaged = true
elseif not engage and already_engaged then
self:_disengage(scratchpad, t)
already_engaged = false
end
if already_engaged and not action_data.do_not_update_engage_position and t > scratchpad.engage_update_time then
self:_update_engage_position(unit, self_position, target_unit, target_position, target_velocity, target_breed, scratchpad, t, melee_range, nav_world, traverse_logic)
end
self:_update_dodge(unit, scratchpad, target_unit, t)
return false, self:_evaluation_timer(scratchpad, t, eval_timer)
end
BtBotMeleeAction._can_start_attack = function (self, attack_meta_data, weapon_extension)
local action_input = attack_meta_data.action_inputs[1].action_input
local raw_input
local fixed_t = FixedFrame.get_latest_fixed_time()
return weapon_extension:action_input_is_currently_valid("weapon_action", action_input, raw_input, fixed_t)
end
BtBotMeleeAction._update_attack = function (self, scratchpad, t)
local action_input_extension = scratchpad.action_input_extension
local attack_action_input_request_id = scratchpad.attack_action_input_request_id
if attack_action_input_request_id then
if not action_input_extension:bot_queue_request_is_consumed("weapon_action", attack_action_input_request_id) then
return
else
scratchpad.attack_action_input_request_id = nil
end
end
if t >= scratchpad.next_attack_action_input_t then
local attack_meta_data = scratchpad.executing_attack_meta_data
local action_input_i = scratchpad.next_action_input_i
local action_inputs = attack_meta_data.action_inputs
local action_input_config = action_inputs[action_input_i]
local action_input = action_input_config.action_input
local raw_input
local request_id = action_input_extension:bot_queue_action_input("weapon_action", action_input, raw_input)
scratchpad.attack_action_input_request_id = request_id
local next_action_input_i = action_input_i + 1
local next_action_input_config = action_inputs[next_action_input_i]
if next_action_input_config then
scratchpad.next_attack_action_input_t = t + next_action_input_config.timing
scratchpad.next_action_input_i = next_action_input_i
else
scratchpad.is_attacking = false
end
end
end
BtBotMeleeAction._aim_position = function (self, target_unit, target_breed)
local aim_node_name
if target_breed then
aim_node_name = target_breed.bot_melee_aim_node or "j_spine"
end
local aim_position
if Unit.has_node(target_unit, aim_node_name) then
local aim_node = Unit.node(target_unit, aim_node_name)
aim_position = Unit.world_position(target_unit, aim_node)
else
aim_position = POSITION_LOOKUP[target_unit]
end
return aim_position
end
local DEFAULT_MAXIMAL_MELEE_RANGE = 2.5
local DEFAULT_ATTACK_META_DATA = {
light_attack = {
arc = 0,
penetrating = false,
max_range = DEFAULT_MAXIMAL_MELEE_RANGE,
action_inputs = {
{
action_input = "start_attack",
timing = 0,
},
{
action_input = "light_attack",
timing = 0,
},
},
},
}
local ARMORED = ArmorSettings.types.armored
BtBotMeleeAction._choose_attack = function (self, target_unit, target_breed, scratchpad)
local num_enemies = scratchpad.num_enemies_in_proximity
local outnumbered = num_enemies > 1
local massively_outnumbered = num_enemies > 3
local target_armor = Armor.armor_type(target_unit, target_breed)
local weapon_template = scratchpad.weapon_template
local weapon_meta_data = weapon_template.attack_meta_data or DEFAULT_ATTACK_META_DATA
local best_attack_meta_data, best_utility = nil, -math.huge
for attack_input, attack_meta_data in pairs(weapon_meta_data) do
local utility = 0
if outnumbered and attack_meta_data.arc == 1 then
utility = utility + 1
elseif attack_meta_data.no_damage and massively_outnumbered and attack_meta_data.arc > 1 then
utility = utility + 2
elseif not attack_meta_data.no_damage and (outnumbered and attack_meta_data.arc > 1 or not outnumbered and attack_meta_data.arc == 0) then
utility = utility + 4
end
if target_armor ~= ARMORED or attack_meta_data.penetrating then
utility = utility + 8
end
if best_utility < utility then
best_attack_meta_data, best_utility = attack_meta_data, utility
end
end
return best_attack_meta_data
end
local DEFAULT_ENEMY_HITBOX_RADIUS_APPROXIMATION = 0.5
BtBotMeleeAction._calculate_melee_range = function (self, target_breed, attack_meta_data)
local target_hitbox_radius_approximation
if target_breed then
target_hitbox_radius_approximation = target_breed.bot_hitbox_radius_approximation or DEFAULT_ENEMY_HITBOX_RADIUS_APPROXIMATION
else
target_hitbox_radius_approximation = 0
end
local attack_range = attack_meta_data.max_range
local melee_range = attack_range + target_hitbox_radius_approximation
return melee_range
end
BtBotMeleeAction._target_velocity = function (self, target_unit, target_breed)
local target_velocity
if Breed.is_player(target_breed) then
local target_unit_data_extension = ScriptUnit.extension(target_unit, "unit_data_system")
local locomotion_component = target_unit_data_extension:read_component("locomotion")
target_velocity = locomotion_component.velocity_current
elseif target_breed then
local target_locomotion_extension = ScriptUnit.extension(target_unit, "locomotion_system")
target_velocity = target_locomotion_extension:current_velocity()
else
target_velocity = Vector3.zero()
end
return target_velocity
end
BtBotMeleeAction._is_in_melee_range = function (self, self_position, aim_position, melee_range, self_velocitiy, target_velocity, scratchpad, t)
local time_to_next_attack = self:_time_to_next_attack(scratchpad, t)
local relative_velocity = self_velocitiy - target_velocity
local check_position = self_position + relative_velocity * time_to_next_attack
local melee_range_sq = melee_range^2
return melee_range_sq > Vector3.distance_squared(aim_position, check_position)
end
BtBotMeleeAction._time_to_next_attack = function (self, scratchpad, t)
if scratchpad.is_attacking then
local attack_meta_data = scratchpad.executing_attack_meta_data
local action_inputs = attack_meta_data.action_inputs
local next_action_input_i = scratchpad.next_action_input_i
local remaining_action_input_time = 0
local num_action_inputs = #action_inputs
for i = next_action_input_i + 1, num_action_inputs do
local config = action_inputs[i]
remaining_action_input_time = remaining_action_input_time + config.timing
end
local current_action_input_time = scratchpad.next_attack_action_input_t - t
return current_action_input_time + remaining_action_input_time
else
return 0
end
end
BtBotMeleeAction._should_defend = function (self, unit, target_unit, scratchpad)
local attack_intensity_extension = scratchpad.attack_intensity_extension
if attack_intensity_extension:num_melee_attackers() > 0 then
return true
else
return false
end
end
BtBotMeleeAction._update_start_defend = function (self, scratchpad, defense_meta_data)
local start_defend_request_id = scratchpad.start_defend_request_id
if not start_defend_request_id then
local start_action_input = defense_meta_data.start_action_input
local raw_input
local fixed_t = FixedFrame.get_latest_fixed_time()
local weapon_extension = scratchpad.weapon_extension
if weapon_extension:action_input_is_currently_valid("weapon_action", start_action_input, raw_input, fixed_t) then
self:_start_defend(start_action_input, scratchpad)
end
else
local action_input_extension = scratchpad.action_input_extension
if action_input_extension:bot_queue_request_is_consumed("weapon_action", start_defend_request_id) then
scratchpad.is_defending = true
scratchpad.defend_request_id = nil
end
end
end
BtBotMeleeAction._start_defend = function (self, action_input, scratchpad)
local action_input_extension = scratchpad.action_input_extension
local raw_input
scratchpad.start_defend_request_id = action_input_extension:bot_queue_action_input("weapon_action", action_input, raw_input)
end
BtBotMeleeAction._stop_defend = function (self, scratchpad, defense_meta_data)
local action_input_extension = scratchpad.action_input_extension
local stop_action_input = defense_meta_data.stop_action_input
local raw_input
action_input_extension:bot_queue_action_input("weapon_action", stop_action_input, raw_input)
end
BtBotMeleeAction._update_defend = function (self, unit, should_defend, defense_meta_data, scratchpad, in_melee_range, target_unit, target_breed, fixed_t, t)
local action_input_extension = scratchpad.action_input_extension
local push_request_id = scratchpad.push_request_id
if push_request_id then
if action_input_extension:bot_queue_request_is_consumed("weapon_action", push_request_id) then
scratchpad.push_request_id = nil
scratchpad.is_defending = false
end
return
end
if should_defend then
local should_push, push_action_input, cant_push = self:_should_push(defense_meta_data, scratchpad, in_melee_range, target_unit, target_breed, fixed_t)
if should_push then
local raw_input
scratchpad.push_request_id = action_input_extension:bot_queue_action_input("weapon_action", push_action_input, raw_input)
end
scratchpad.cant_push = cant_push
else
self:_stop_defend(scratchpad, defense_meta_data)
scratchpad.is_defending = false
end
end
BtBotMeleeAction._should_push = function (self, defense_meta_data, scratchpad, in_melee_range, target_unit, target_breed, fixed_t)
local num_enemies = scratchpad.num_enemies_in_proximity
local stamina_component = scratchpad.stamina_component
local base_stamina_template = scratchpad.archetype_stamina_template
local current_stamina, _ = Stamina.current_and_max_value(target_unit, stamina_component, base_stamina_template)
local push_type = defense_meta_data.push
local low_stamina = current_stamina <= 1
local armor_type = Armor.armor_type(target_unit, target_breed)
local breed_is_pushable = true
if not target_breed then
breed_is_pushable = false
elseif target_breed.tags.monster then
breed_is_pushable = false
elseif armor_type == ARMORED and push_type ~= "heavy" then
breed_is_pushable = false
end
local outnumbered = num_enemies > 1
local push_action_input = defense_meta_data.push_action_input
local weapon_extension = scratchpad.weapon_extension
local raw_input
local push_action_is_available = weapon_extension:action_input_is_currently_valid("weapon_action", push_action_input, raw_input, fixed_t)
local cant_push = low_stamina or not push_action_is_available or not breed_is_pushable
if in_melee_range and push_action_is_available and breed_is_pushable and outnumbered and not low_stamina then
return true, push_action_input
else
return false, nil, cant_push
end
end
local DODGE_CHECK_RANDOM_RANGE = {
0.5,
2,
}
local CANT_PUSH_DODGE_CHECK_RANDOM_RANGE = {
0.1,
0.2,
}
local DODGE_RANGE_TEST_DISTANCE = 2.25
local DODGE_CHECK_FAIL_COOLDOWN = 0.1
BtBotMeleeAction._update_dodge = function (self, unit, scratchpad, target_unit, t)
local perception_component = scratchpad.perception_component
local target_ally, target_ally_needs_aid = perception_component.target_ally, perception_component.target_ally_needs_aid
local bot_group = scratchpad.bot_group
if target_ally_needs_aid and bot_group:is_prioritized_ally(unit, target_ally) then
return
end
local cant_push = scratchpad.cant_push
local bot_group_data = scratchpad.bot_group_data
local threat_data = bot_group_data.aoe_threat
if t < threat_data.expires then
return
end
if t < scratchpad.random_dodge_check_t then
return
end
local num_enemies = scratchpad.num_enemies_in_proximity
if num_enemies == 0 then
return
end
local attack_intensity_extension = scratchpad.attack_intensity_extension
if attack_intensity_extension:num_melee_attackers() == 0 then
return
end
local bot_position = POSITION_LOOKUP[unit]
local target_position = POSITION_LOOKUP[target_unit]
local dodge_away_from_target = math.random() > 0.5
local escape_dir
if dodge_away_from_target then
escape_dir = Vector3.normalize(bot_position - target_position)
else
local rotation = Unit.local_rotation(unit, 1)
local right = Quaternion.right(rotation)
local dodge_left = math.random() > 0.5
if dodge_left then
escape_dir = -right
else
escape_dir = right
end
end
if escape_dir then
local nav_world, traverse_logic = scratchpad.nav_world, scratchpad.traverse_logic
local to = bot_position + escape_dir * DODGE_RANGE_TEST_DISTANCE
local success = NavQueries.ray_can_go(nav_world, bot_position, to, traverse_logic, 1, 1)
if success then
local random_time = t + math.random() * 0.5
threat_data.expires = random_time
threat_data.escape_direction:store(escape_dir)
threat_data.dodge_t = math.min(t + math.random() * 0.5, random_time)
local dodge_check_range = cant_push and CANT_PUSH_DODGE_CHECK_RANDOM_RANGE or DODGE_CHECK_RANDOM_RANGE
scratchpad.random_dodge_check_t = t + math.random_range(dodge_check_range[1], dodge_check_range[2])
else
scratchpad.random_dodge_check_t = t + DODGE_CHECK_FAIL_COOLDOWN
end
end
end
BtBotMeleeAction._is_attacking_me = function (self, self_unit, enemy_unit)
local target_blackboard = BLACKBOARDS[enemy_unit]
if target_blackboard == nil then
return false
end
local target_perception_component = target_blackboard.perception
local behavior_component = target_blackboard.behavior
local move_state = behavior_component.move_state
local is_attacking_me = target_perception_component.target_unit == self_unit and move_state == "attacking"
return is_attacking_me
end
local STOP_ACTION_INTERRUPT_DATA = {}
BtBotMeleeAction._clear_pending_attack = function (self, scratchpad)
local action_input_extension = scratchpad.action_input_extension
action_input_extension:bot_queue_clear_requests("weapon_action")
action_input_extension:clear_input_queue_and_sequences("weapon_action")
local weapon_extension = scratchpad.weapon_extension
local fixed_t = FixedFrame.get_latest_fixed_time()
weapon_extension:stop_action("bot_left_node", STOP_ACTION_INTERRUPT_DATA, fixed_t)
end
BtBotMeleeAction._start_attack = function (self, attack_meta_data, scratchpad, t)
scratchpad.is_attacking = true
scratchpad.executing_attack_meta_data = attack_meta_data
scratchpad.next_action_input_i = 1
scratchpad.next_attack_action_input_t = t
end
local NEAR_FOLLOW_POSITION_RANGE_SQ = 25
BtBotMeleeAction._is_in_engage_range = function (self, self_position, target_position, action_data, follow_position)
local engage_range_sq
if Vector3.distance_squared(self_position, follow_position) < NEAR_FOLLOW_POSITION_RANGE_SQ then
engage_range_sq = action_data.engage_range_near_follow_position^2
else
engage_range_sq = action_data.engage_range^2
end
return engage_range_sq > Vector3.distance_squared(self_position, target_position)
end
local TARGET_NAV_MESH_ABOVE = 0.5
local TARGET_NAV_MESH_BELOW = 2
BtBotMeleeAction._target_unit_position = function (self, self_position, target_unit, action_data, nav_world, traverse_logic)
local target_unit_position
if action_data.destroy_object then
local smart_objects
local nav_graph_extension = ScriptUnit.has_extension(target_unit, "nav_graph_system")
if nav_graph_extension then
smart_objects = nav_graph_extension:smart_objects()
end
if smart_objects then
local smart_object = smart_objects[1]
local entrance_position, exit_position = smart_object:get_entrance_exit_positions()
target_unit_position = math.closest_position(self_position, entrance_position, exit_position)
else
local node_name = "rp_center"
local node = Unit.has_node(target_unit, node_name) and Unit.node(target_unit, node_name) or 1
local node_position = Unit.world_position(target_unit, node)
target_unit_position = NavQueries.position_on_mesh(nav_world, node_position, TARGET_NAV_MESH_ABOVE, TARGET_NAV_MESH_BELOW, traverse_logic) or node_position
end
else
target_unit_position = POSITION_LOOKUP[target_unit]
end
return target_unit_position
end
local START_CHALLENGE_VALUE = 10
local MAX_CHALLENGE_VALUE = 30
local ALREADY_ENGAGED_STICKINESS = 3
local IN_PROXIMITY_DISTANCE_SQ = 25
BtBotMeleeAction._allow_engage = function (self, self_unit, target_unit, target_position, target_breed, scratchpad, action_data, already_engaged, aim_position, follow_position)
local challenge_rating = 0
local override_range_default = action_data.override_engage_range_to_follow_position
local challenge_override_range = action_data.override_engage_range_to_follow_position_challenge
local lerp_t = (challenge_rating - START_CHALLENGE_VALUE) / (MAX_CHALLENGE_VALUE - START_CHALLENGE_VALUE)
local override_range
if lerp_t <= 0 then
override_range = override_range_default
elseif lerp_t >= 1 then
override_range = challenge_override_range
else
override_range = math.lerp(override_range_default, challenge_override_range, lerp_t * lerp_t)
end
local distance_to_follow_position = Vector3.distance(aim_position, follow_position)
local stickiness = already_engaged and ALREADY_ENGAGED_STICKINESS or 0
if override_range < distance_to_follow_position - stickiness then
return false
end
local main_path_manager = Managers.state.main_path
local perception_component, bot_group_data = scratchpad.perception_component, scratchpad.bot_group_data
local target_ally, target_ally_needs_aid = perception_component.target_ally, perception_component.target_ally_needs_aid
local follow_unit = target_ally_needs_aid and target_ally or bot_group_data.follow_unit
if follow_unit and main_path_manager:is_main_path_ready() then
local self_segment = main_path_manager:segment_index_by_unit(self_unit)
local target_segment = main_path_manager:segment_index_by_unit(follow_unit)
if self_segment < target_segment then
return false
end
end
local bot_group = scratchpad.bot_group
if target_ally_needs_aid and bot_group:is_prioritized_ally(self_unit, target_ally) then
return false
end
local priority_target = perception_component.priority_target_enemy
if priority_target and target_unit ~= priority_target then
return false
end
local behavior_extension = scratchpad.behavior_extension
local stay_near_player, max_allowed_distance = behavior_extension:should_stay_near_player()
if stay_near_player and max_allowed_distance < distance_to_follow_position then
return false
end
local darkness_system = scratchpad.darkness_system
local in_total_darkness = darkness_system:is_in_darkness(target_position, darkness_system.TOTAL_DARKNESS_THRESHOLD)
if in_total_darkness and not target_ally_needs_aid and not perception_component.aggressive_mode and target_unit ~= perception_component.urgent_target_enemy and target_unit ~= perception_component.opportunity_target_enemy then
return false
end
return true
end
BtBotMeleeAction._is_targeting_me = function (self, self_unit, enemy_unit)
local target_blackboard = BLACKBOARDS[enemy_unit]
if not target_blackboard then
return false
end
local target_perception_component = target_blackboard.perception
local is_targeting_me = target_perception_component.target_unit == self_unit
return is_targeting_me
end
BtBotMeleeAction._engage = function (self, scratchpad, t)
scratchpad.engaging = true
scratchpad.engage_change_time = t
end
BtBotMeleeAction._disengage = function (self, scratchpad, t)
scratchpad.engaging = false
scratchpad.engage_change_time = t
local melee_component = scratchpad.melee_component
melee_component.engage_position_set = false
end
local ENGAGE_NAV_MESH_ABOVE, ENGAGE_NAV_MESH_BELOW = 0.5, 0.5
local function _check_angle(nav_world, traverse_logic, target_position, start_direction, angle, distance)
local direction = Quaternion.rotate(Quaternion(Vector3.up(), angle), start_direction)
local check_position = target_position - direction * distance
local position = NavQueries.position_on_mesh(nav_world, check_position, ENGAGE_NAV_MESH_ABOVE, ENGAGE_NAV_MESH_BELOW, traverse_logic)
return position
end
local SUBDIVISIONS_PER_SIDE = 3
local ANGLE_INCREMENT = math.pi / (SUBDIVISIONS_PER_SIDE + 1)
local function _calculate_engage_position(nav_world, traverse_logic, target_position, engage_from, melee_distance)
local start_direction = Vector3.normalize(Vector3.flat(engage_from))
local position = _check_angle(nav_world, traverse_logic, target_position, start_direction, 0, melee_distance)
if position then
return position
end
for i = 1, SUBDIVISIONS_PER_SIDE do
local angle = ANGLE_INCREMENT * i
position = _check_angle(nav_world, traverse_logic, target_position, start_direction, angle, melee_distance)
if position then
return position
end
position = _check_angle(nav_world, traverse_logic, target_position, start_direction, -angle, melee_distance)
if position then
return position
end
end
position = _check_angle(nav_world, traverse_logic, target_position, start_direction, math.pi, melee_distance)
return position
end
local TARGET_MOVING_SPEED_THRESHOLD_SQ = 4
local FACING_DOT = -0.25
local ENGAGE_OFFSET_ANGLE = math.pi / 8
local ENGAGE_POSITION_MIN_DISTANCE_SQ = 0.010000000000000002
local ENGAGE_UPDATE_MIN_DISTANCE, ENGAGE_UPDATE_MAX_DISTANCE = 3, 7
local ENGAGE_UPDATE_MIN_INTERVAL, ENGAGE_UPDATE_MAX_INTERVAL = 0.2, 2
BtBotMeleeAction._update_engage_position = function (self, unit, self_position, target_unit, target_unit_position, target_velocity, target_breed, scratchpad, t, melee_range, nav_world, traverse_logic)
local melee_distance
local target_speed_sq = Vector3.length_squared(target_velocity)
melee_distance = target_speed_sq > TARGET_MOVING_SPEED_THRESHOLD_SQ and 0 or melee_range - 0.5
local melee_distance_sq = melee_distance^2
local targeting_me = self:_is_targeting_me(unit, target_unit)
local enemy_offset = target_unit_position - self_position
local should_stop = false
local engage_position
if target_breed and target_breed.bots_should_flank and (not targeting_me or target_breed.bots_flank_while_targeted) then
local enemy_rotation = Unit.local_rotation(target_unit, 1)
local enemy_direction = Quaternion.forward(enemy_rotation)
local engage_from
if Vector3.dot(enemy_direction, enemy_offset) > FACING_DOT then
engage_from = enemy_offset
else
local normalized_enemy_offset = Vector3.normalize(Vector3.flat(enemy_offset))
local normalized_enemy_direction = Vector3.normalize(Vector3.flat(enemy_direction))
local offset_angle = Vector3.flat_angle(-normalized_enemy_offset, normalized_enemy_direction)
local new_angle
if offset_angle > 0 then
new_angle = offset_angle + ENGAGE_OFFSET_ANGLE
else
new_angle = offset_angle - ENGAGE_OFFSET_ANGLE
end
local new_rotation = Quaternion.multiply(Quaternion(Vector3.up(), -new_angle), enemy_rotation)
engage_from = -Quaternion.forward(new_rotation)
end
engage_position = _calculate_engage_position(nav_world, traverse_logic, target_unit_position, engage_from, melee_distance)
elseif melee_distance_sq >= Vector3.distance_squared(self_position, target_unit_position) then
engage_position, should_stop = self_position, true
else
engage_position = _calculate_engage_position(nav_world, traverse_logic, target_unit_position, enemy_offset, melee_distance)
end
if engage_position then
local melee_component = scratchpad.melee_component
local previous_engage_position = melee_component.engage_position:unbox()
local engage_position_set = melee_component.engage_position_set
if not engage_position_set or Vector3.distance_squared(engage_position, previous_engage_position) > ENGAGE_POSITION_MIN_DISTANCE_SQ then
melee_component.engage_position:store(engage_position)
melee_component.engage_position_set = true
melee_component.stop_at_current_position = should_stop
end
local distance = Vector3.distance(self_position, engage_position)
local lerp_t = math.clamp(distance, ENGAGE_UPDATE_MIN_DISTANCE, ENGAGE_UPDATE_MAX_DISTANCE)
local interval = math.auto_lerp(ENGAGE_UPDATE_MIN_DISTANCE, ENGAGE_UPDATE_MAX_DISTANCE, ENGAGE_UPDATE_MIN_INTERVAL, ENGAGE_UPDATE_MAX_INTERVAL, lerp_t)
scratchpad.engage_update_time = t + interval
end
end
BtBotMeleeAction._evaluation_timer = function (self, scratchpad, t, timer_value)
local last_evaluate_t = scratchpad.last_evaluate_t
local evaluate = timer_value < t - last_evaluate_t
if evaluate then
scratchpad.last_evaluate_t = t
return true
else
return false
end
end
return BtBotMeleeAction
| 0 | 0.967359 | 1 | 0.967359 | game-dev | MEDIA | 0.974224 | game-dev | 0.95017 | 1 | 0.95017 |
glKarin/com.n0n3m4.diii4a | 10,196 | Q3E/src/main/jni/source/utils/dmxedit/luamain.cpp | //=============================================================================
//
//========= Copyright Valve Corporation, All rights reserved. ============//
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// $Header: $
// $NoKeywords: $
//
//=============================================================================
// Standard includes
#include <ctype.h>
#include <io.h>
// Valve includes
#include "appframework/AppFramework.h"
#include "datamodel/idatamodel.h"
#include "filesystem.h"
#include "icommandline.h"
#include "materialsystem/imaterialsystem.h"
#include "mathlib/mathlib.h"
#include "tier1/tier1.h"
#include "tier2/tier2.h"
#include "tier2/tier2dm.h"
#include "tier3/tier3.h"
#include "tier1/UtlStringMap.h"
#include "vstdlib/vstdlib.h"
#include "vstdlib/iprocessutils.h"
#include "tier2/p4helpers.h"
#include "p4lib/ip4.h"
// Lua includes
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
// Local includes
#include "dmxedit.h"
//-----------------------------------------------------------------------------
// The application object
//-----------------------------------------------------------------------------
class CDmxEditApp : public CDefaultAppSystemGroup< CSteamAppSystemGroup >
{
public:
// Methods of IApplication
virtual bool Create();
virtual bool PreInit( );
virtual int Main();
virtual void PostShutdown();
void PrintHelp( bool bWiki = false );
};
DEFINE_CONSOLE_STEAM_APPLICATION_OBJECT( CDmxEditApp );
//-----------------------------------------------------------------------------
// The application object
//-----------------------------------------------------------------------------
bool CDmxEditApp::Create()
{
AppSystemInfo_t appSystems[] =
{
{ "vstdlib.dll", PROCESS_UTILS_INTERFACE_VERSION },
{ "materialsystem.dll", MATERIAL_SYSTEM_INTERFACE_VERSION },
{ "p4lib.dll", P4_INTERFACE_VERSION },
{ "", "" } // Required to terminate the list
};
AddSystems( appSystems );
IMaterialSystem *pMaterialSystem = reinterpret_cast< IMaterialSystem * >( FindSystem( MATERIAL_SYSTEM_INTERFACE_VERSION ) );
if ( !pMaterialSystem )
{
Error( "// ERROR: Unable to connect to material system interface!\n" );
return false;
}
pMaterialSystem->SetShaderAPI( "shaderapiempty.dll" );
return true;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool CDmxEditApp::PreInit( )
{
CreateInterfaceFn factory = GetFactory();
MathLib_Init( 2.2f, 2.2f, 0.0f, 2.0f, false, false, false, false );
ConnectTier1Libraries( &factory, 1 );
ConnectTier2Libraries( &factory, 1 );
ConnectTier3Libraries( &factory, 1 );
if ( !ConnectDataModel( factory ) )
return false;
if ( InitDataModel( ) != INIT_OK )
return false;
if ( !g_pFullFileSystem || !g_pDataModel )
{
Error( "// ERROR: dmxedit is missing a required interface!\n" );
return false;
}
return true;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmxEditApp::PostShutdown()
{
ShutdownDataModel();
DisconnectDataModel();
DisconnectTier3Libraries();
DisconnectTier2Libraries();
DisconnectTier1Libraries();
}
//-----------------------------------------------------------------------------
// The application object
//-----------------------------------------------------------------------------
int CDmxEditApp::Main()
{
// This bit of hackery allows us to access files on the harddrive
g_pFullFileSystem->AddSearchPath( "", "LOCAL", PATH_ADD_TO_HEAD );
if ( CommandLine()->CheckParm( "-h" ) || CommandLine()->CheckParm( "-help" ) )
{
PrintHelp();
return 0;
}
if ( CommandLine()->CheckParm( "-wiki" ) )
{
PrintHelp( true );
return 0;
}
CUtlStringMap< CUtlString > setVars;
CUtlString sGame;
const int nParamCount = CommandLine()->ParmCount();
for ( int i = 0; i < nParamCount - 1; ++i )
{
const char *pCmd = CommandLine()->GetParm( i );
const char *pArg = CommandLine()->GetParm( i + 1 );
if ( StringHasPrefix( pCmd, "-s" ) )
{
const char *const pEquals = strchr( pArg, '=' );
if ( !pEquals )
{
Warning( "Warning: Invalid command line args, no ='s in -set argument: %s %s\n", pCmd, pArg );
}
char buf[ BUFSIZ ];
Q_strncpy( buf, pArg, pEquals - pArg + 1 );
const CUtlString sKey( buf );
CUtlString sVal( pEquals + 1 );
if ( !V_isdigit( *sVal.Get() ) && *sVal.Get() != '-' && *sVal.Get() != '"' )
{
CUtlString sqVal( "\"" );
sqVal += sVal;
sqVal += "\"";
sVal = sqVal;
}
setVars[ sKey ] = sVal;
if ( !Q_stricmp( sKey.Get(), "game" ) && sGame.IsEmpty() )
{
sGame = sKey;
}
++i;
}
else if ( StringHasPrefix( pCmd, "-g" ) )
{
if ( *pArg == '"' )
{
sGame = pArg;
}
else
{
sGame = ( "\"" );
sGame += pArg;
sGame += "\"";
}
}
else if ( StringHasPrefix( pCmd, "-nop4" ) )
{
// Don't issue warning on -nop4
}
else if ( StringHasPrefix( pCmd, "-coe" ) || StringHasPrefix( pCmd, "-ContinueOnError" ) )
{
// Don't issue warning on -nop4
}
else if ( StringHasPrefix( pCmd, "-" ) )
{
Warning( "Warning: Unknown command line argument: %s\n", pCmd );
}
}
// Do Perforce Stuff
if ( CommandLine()->FindParm( "-nop4" ) )
g_p4factory->SetDummyMode( true );
g_p4factory->SetOpenFileChangeList( "dmxedit" );
for ( int i = CommandLine()->ParmCount() - 1; i >= 1; --i )
{
const char *pParam = CommandLine()->GetParm( i );
if ( _access( pParam, 04 ) == 0 )
{
CDmxEditLua dmxEditLua;
for ( int i = 0; i < setVars.GetNumStrings(); ++i )
{
dmxEditLua.SetVar( setVars.String( i ), setVars[ i ] );
}
if ( !sGame.IsEmpty() )
{
dmxEditLua.SetGame( sGame );
}
return dmxEditLua.DoIt( pParam );
}
}
Error( "Cannot find any file to execute from passed command line arguments\n\n" );
PrintHelp();
return -1;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CUtlString Wikize( lua_State *pLuaState, const char *pWikiString )
{
CUtlString retVal( pWikiString );
lua_pushstring( pLuaState, "string");
lua_gettable( pLuaState, LUA_GLOBALSINDEX );
lua_pushstring( pLuaState, "gsub");
lua_gettable( pLuaState, -2);
lua_pushstring( pLuaState, pWikiString );
lua_pushstring( pLuaState, "([$#]%w+)" );
lua_pushstring( pLuaState, "'''%0'''" );
if ( lua_pcall( pLuaState, 3, 1, 0 ) == 0 )
{
if ( lua_isstring( pLuaState, -1 ) )
{
retVal = lua_tostring( pLuaState, -1 );
}
lua_pop( pLuaState, 1 );
}
return retVal;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
template < class T_t >
int Sort_LuaFunc_s( const T_t *pA, const T_t *pB )
{
return Q_stricmp( (*pA)->m_pFuncName, (*pB)->m_pFuncName );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmxEditApp::PrintHelp( bool bWiki /* = false */ )
{
CUtlVector< LuaFunc_s * > luaFuncs;
for ( LuaFunc_s *pFunc = LuaFunc_s::s_pFirstFunc; pFunc; pFunc = pFunc->m_pNextFunc )
{
luaFuncs.AddToTail( pFunc );
}
luaFuncs.Sort( Sort_LuaFunc_s );
if ( bWiki && LuaFunc_s::s_pFirstFunc )
{
lua_State *pLuaState = lua_open();
if ( pLuaState )
{
luaL_openlibs( pLuaState );
CUtlString wikiString;
for ( int i = 0; i < luaFuncs.Count(); ++i )
{
const LuaFunc_s *pFunc = luaFuncs[ i ];
if ( pFunc != LuaFunc_s::s_pFirstFunc )
{
Msg( "\n" );
}
Msg( ";%s( %s );\n", pFunc->m_pFuncName, pFunc->m_pFuncPrototype );
Msg( ":%s\n", Wikize( pLuaState, pFunc->m_pFuncDesc ).Get() );
}
return;
}
}
Msg( "\n" );
Msg( "NAME\n" );
Msg( " dmxedit - Edit dmx files\n" );
Msg( "\n" );
Msg( "SYNOPSIS\n" );
Msg( " dmxedit [ -h | -help ] [ -game <$game> ] [ -set $var=val ] [ script.lua ]\n" );
Msg( "\n" );
Msg( " -h | -help : Prints this information\n" );
Msg( " -g | -game <$game> : Sets the VPROJECT environment variable to the specified game.\n" );
Msg( " -s | -set <$var=val> : Sets the lua variable var to the specified val before the script is run.\n" );
Msg( "\n" );
Msg( "DESCRIPTION\n" );
Msg( " Edits dmx files by executing a lua script of dmx editing functions\n" );
Msg( "\n" );
if ( !LuaFunc_s::s_pFirstFunc )
return;
Msg( "FUNCTIONS\n" );
const char *pWhitespace = " \t";
for ( int i = 0; i < luaFuncs.Count(); ++i )
{
const LuaFunc_s *pFunc = luaFuncs[ i ];
Msg( " %s( %s );\n", pFunc->m_pFuncName, pFunc->m_pFuncPrototype );
Msg( " * " );
CUtlString tmpStr;
const char *pWordBegin = pFunc->m_pFuncDesc + strspn( pFunc->m_pFuncDesc, pWhitespace );
const char *pWhiteSpaceBegin = pWordBegin;
const char *pWordEnd = pWordBegin + strcspn( pWordBegin, pWhitespace );
bool bNewline = false;
while ( *pWordBegin )
{
if ( pWordEnd - pWhiteSpaceBegin + tmpStr.Length() > 70 )
{
if ( bNewline )
{
Msg( " " );
}
else
{
bNewline = true;
}
Msg( "%s\n", tmpStr.Get() );
tmpStr.Set( "" );
}
if ( tmpStr.Length() )
{
tmpStr += CUtlString( pWhiteSpaceBegin, pWordEnd - pWhiteSpaceBegin + 1);
}
else
{
tmpStr += CUtlString( pWordBegin, pWordEnd - pWordBegin + 1 );
}
pWhiteSpaceBegin = pWordEnd;
pWordBegin = pWhiteSpaceBegin + strspn( pWhiteSpaceBegin, pWhitespace );
pWordEnd = pWordBegin + strcspn( pWordBegin, pWhitespace );
}
if ( tmpStr.Length() )
{
if ( bNewline )
{
Msg( " " );
}
Msg( "%s\n", tmpStr.Get() );
}
Msg( "\n" );
}
Msg( "CREDITS\n" );
Msg( " Lua Copyright 1994-2006 Lua.org, PUC-Rio.\n ");
Msg( "\n" );
} | 0 | 0.898128 | 1 | 0.898128 | game-dev | MEDIA | 0.361337 | game-dev,cli-devtools | 0.956816 | 1 | 0.956816 |
LinHuangnan/RiscV_GameConsole_FPGA | 4,109 | code/HBirdv2_Prj/InfoNES097JRC1_SDL/mapper/InfoNES_Mapper_046.cpp | /*===================================================================*/
/* */
/* Mapper 46 (Color Dreams) */
/* */
/*===================================================================*/
#include "InfoNES.h"
#include "InfoNES_System.h"
#include "InfoNES_Mapper.h"
#include "InfoNES_pAPU.h"
#include "K6502.h"
BYTE Map46_Regs[ 4 ];
/*-------------------------------------------------------------------*/
/* Initialize Mapper 46 */
/*-------------------------------------------------------------------*/
void Map46_Init()
{
/* Initialize Mapper */
MapperInit = Map46_Init;
/* Write to Mapper */
MapperWrite = Map46_Write;
/* Write to SRAM */
MapperSram = Map46_Sram;
/* Write to APU */
MapperApu = Map0_Apu;
/* Read from APU */
MapperReadApu = Map0_ReadApu;
/* Callback at VSync */
MapperVSync = Map0_VSync;
/* Callback at HSync */
MapperHSync = Map0_HSync;
/* Callback at PPU */
MapperPPU = Map0_PPU;
/* Callback at Rendering Screen ( 1:BG, 0:Sprite ) */
MapperRenderScreen = Map0_RenderScreen;
/* Set SRAM Banks */
SRAMBANK = SRAM;
/* Set ROM Banks */
Map46_Regs[ 0 ] = Map46_Regs[ 1 ] = Map46_Regs[ 2 ] = Map46_Regs[ 3 ] = 0;
Map46_Set_ROM_Banks();
/* Name Table Mirroring */
InfoNES_Mirroring( 1 );
/* Set up wiring of the interrupt pin */
K6502_Set_Int_Wiring( 1, 1 );
}
/*-------------------------------------------------------------------*/
/* Mapper 46 Write to SRAM Function */
/*-------------------------------------------------------------------*/
void Map46_Sram( WORD wAddr, BYTE byData )
{
/* Set ROM Banks */
Map46_Regs[ 0 ] = byData & 0x0f;
Map46_Regs[ 1 ] = ( byData & 0xf0 ) >> 4;
Map46_Set_ROM_Banks();
}
/*-------------------------------------------------------------------*/
/* Mapper 46 Write Function */
/*-------------------------------------------------------------------*/
void Map46_Write( WORD wAddr, BYTE byData )
{
/* Set ROM Banks */
Map46_Regs[ 2 ] = byData & 0x01;
Map46_Regs[ 3 ] = ( byData & 0x70 ) >> 4;
Map46_Set_ROM_Banks();
}
/*-------------------------------------------------------------------*/
/* Mapper 46 Setup ROM Banks Function */
/*-------------------------------------------------------------------*/
void Map46_Set_ROM_Banks()
{
/* Set ROM Banks */
ROMBANK0 = ROMPAGE( ( ( Map46_Regs[ 0 ] << 3 ) + ( Map46_Regs[ 2 ] << 2 ) + 0 ) % ( NesHeader.byRomSize << 1 ) );
ROMBANK1 = ROMPAGE( ( ( Map46_Regs[ 0 ] << 3 ) + ( Map46_Regs[ 2 ] << 2 ) + 1 ) % ( NesHeader.byRomSize << 1 ) );
ROMBANK2 = ROMPAGE( ( ( Map46_Regs[ 0 ] << 3 ) + ( Map46_Regs[ 2 ] << 2 ) + 2 ) % ( NesHeader.byRomSize << 1 ) );
ROMBANK3 = ROMPAGE( ( ( Map46_Regs[ 0 ] << 3 ) + ( Map46_Regs[ 2 ] << 2 ) + 3 ) % ( NesHeader.byRomSize << 1 ) );
/* Set PPU Banks */
PPUBANK[ 0 ] = VROMPAGE( ( ( Map46_Regs[ 1 ] << 6 ) + ( Map46_Regs[ 3 ] << 3 ) + 0 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 1 ] = VROMPAGE( ( ( Map46_Regs[ 1 ] << 6 ) + ( Map46_Regs[ 3 ] << 3 ) + 1 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 2 ] = VROMPAGE( ( ( Map46_Regs[ 1 ] << 6 ) + ( Map46_Regs[ 3 ] << 3 ) + 2 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 3 ] = VROMPAGE( ( ( Map46_Regs[ 1 ] << 6 ) + ( Map46_Regs[ 3 ] << 3 ) + 3 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 4 ] = VROMPAGE( ( ( Map46_Regs[ 1 ] << 6 ) + ( Map46_Regs[ 3 ] << 3 ) + 4 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 5 ] = VROMPAGE( ( ( Map46_Regs[ 1 ] << 6 ) + ( Map46_Regs[ 3 ] << 3 ) + 5 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 6 ] = VROMPAGE( ( ( Map46_Regs[ 1 ] << 6 ) + ( Map46_Regs[ 3 ] << 3 ) + 6 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 7 ] = VROMPAGE( ( ( Map46_Regs[ 1 ] << 6 ) + ( Map46_Regs[ 3 ] << 3 ) + 7 ) % ( NesHeader.byVRomSize << 3 ) );
InfoNES_SetupChr();
}
| 0 | 0.756908 | 1 | 0.756908 | game-dev | MEDIA | 0.580921 | game-dev,drivers | 0.698052 | 1 | 0.698052 |
kbinani/je2be-core | 1,633 | test/loot-table.test.hpp | #pragma once
TEST_CASE("loot-table") {
SUBCASE("j2b2j") {
auto java = u8"minecraft:chests/village/village_plains_house";
auto bedrock = u8"loot_tables/chests/village/village_plains_house.json";
CHECK(LootTable::BedrockTableNameFromJava(java) == bedrock);
CHECK(LootTable::JavaTableNameFromBedrock(bedrock) == java);
}
#if 0
SUBCASE("bedrock") {
using namespace std;
using namespace leveldb;
using namespace mcfile;
using namespace mcfile::stream;
using namespace mcfile::be;
using namespace mcfile::nbt;
unique_ptr<DB> db(Open("fgdwYwGrHgI=")); //"vXxvY4enAAA="));
REQUIRE(db);
unique_ptr<Iterator> itr(db->NewIterator({}));
REQUIRE(itr);
set<string> lootTables;
for (itr->SeekToFirst(); itr->Valid(); itr->Next()) {
string key = itr->key().ToString();
auto parsed = mcfile::be::DbKey::Parse(key);
if (!parsed) {
continue;
}
if (!parsed->fIsTagged) {
continue;
}
switch (static_cast<DbKey::Tag>(parsed->fTagged.fTag)) {
case DbKey::Tag::BlockEntity:
CompoundTag::ReadUntilEos(itr->value().ToString(), Endian::Little, [&lootTables](shared_ptr<CompoundTag> const &tag) {
auto lootTable = tag->string(u8"LootTable");
if (!lootTable) {
return;
}
if (lootTables.find(*lootTable) == lootTables.end()) {
lootTables.insert(*lootTable);
cout << "--" << endl;
for (string const &t : lootTables) {
cout << t << endl;
}
}
});
break;
}
}
}
#endif
}
| 0 | 0.824816 | 1 | 0.824816 | game-dev | MEDIA | 0.475895 | game-dev | 0.897754 | 1 | 0.897754 |
OpenMods/OpenBlocks | 3,092 | src/main/java/openblocks/common/item/ItemCursor.java | package openblocks.common.item;
import javax.annotation.Nonnull;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import openblocks.Config;
import openmods.infobook.BookDocumentation;
import openmods.utils.EnchantmentUtils;
import openmods.utils.ItemUtils;
import openmods.utils.NbtUtils;
@BookDocumentation(hasVideo = true)
public class ItemCursor extends Item {
// TODO maybe allow off-hand item use?
public ItemCursor() {
setMaxStackSize(1);
}
@Override
public int getMaxItemUseDuration(@Nonnull ItemStack par1ItemStack) {
return 50;
}
@Override
public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
final ItemStack stack = player.getHeldItem(hand);
NBTTagCompound tag = ItemUtils.getItemTag(stack);
tag.setInteger("dimension", world.provider.getDimension());
NbtUtils.store(tag, pos);
tag.setInteger("side", facing.ordinal());
return EnumActionResult.SUCCESS;
}
@Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) {
final ItemStack heldStack = player.getHeldItem(hand);
if (hand != EnumHand.MAIN_HAND) return ActionResult.newResult(EnumActionResult.PASS, heldStack);
if (!world.isRemote) {
NBTTagCompound tag = heldStack.getTagCompound();
if (tag != null && NbtUtils.hasCoordinates(tag) && tag.hasKey("dimension")) {
final int dimension = tag.getInteger("dimension");
final BlockPos pos = NbtUtils.readBlockPos(tag);
if (world.provider.getDimension() == dimension && world.isBlockLoaded(pos)) {
final EnumFacing side = NbtUtils.readEnum(tag, "side", EnumFacing.UP);
clickBlock(world, player, hand, pos, side);
}
}
}
return ActionResult.newResult(EnumActionResult.SUCCESS, heldStack);
}
private static void clickBlock(World world, EntityPlayer player, EnumHand hand, BlockPos pos, EnumFacing side) {
if (!world.isAirBlock(pos)) {
final IBlockState state = world.getBlockState(pos);
final double distanceToLinkedBlock = player.getDistanceSq(pos);
if (distanceToLinkedBlock < Config.cursorDistanceLimit) {
final Block block = state.getBlock();
if (player.capabilities.isCreativeMode) {
block.onBlockActivated(world, pos, state, player, hand, side, 0, 0, 0);
} else {
final int cost = (int)Math.max(0, distanceToLinkedBlock - 10);
final int playerExperience = EnchantmentUtils.getPlayerXP(player);
if (cost <= playerExperience) {
block.onBlockActivated(world, pos, state, player, hand, side, 0, 0, 0);
EnchantmentUtils.addPlayerXP(player, -cost);
}
}
}
}
}
}
| 0 | 0.92569 | 1 | 0.92569 | game-dev | MEDIA | 0.998531 | game-dev | 0.990674 | 1 | 0.990674 |
SlimeKnights/Mantle | 4,990 | src/main/java/slimeknights/mantle/data/loadable/common/FluidStackLoadable.java | package slimeknights.mantle.data.loadable.common;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.Fluids;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidType;
import slimeknights.mantle.data.loadable.ErrorFactory;
import slimeknights.mantle.data.loadable.Loadable;
import slimeknights.mantle.data.loadable.Loadables;
import slimeknights.mantle.data.loadable.field.LoadableField;
import slimeknights.mantle.data.loadable.primitive.IntLoadable;
import slimeknights.mantle.data.loadable.record.RecordLoadable;
import javax.annotation.Nullable;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
/** Loadable for a fluid stack */
@SuppressWarnings("unused") // API
public class FluidStackLoadable {
private FluidStackLoadable() {}
/* reused lambdas */
/** Getter for an item from a stack */
private static final Function<FluidStack,Fluid> FLUID_GETTER = FluidStack::getFluid;
/** Checks if a stack can be serialized to a primitive, ignoring count */
private static final Predicate<FluidStack> COMPACT_NBT = stack -> !stack.hasTag();
/** Maps a fluid stack that may be empty to a strictly not empty one */
private static final BiFunction<FluidStack,ErrorFactory,FluidStack> NOT_EMPTY = (stack, error) -> {
if (stack.isEmpty()) {
throw error.create("FluidStack cannot be empty");
}
return stack;
};
/* fields */
/** Field for an optional fluid */
private static final LoadableField<Fluid,FluidStack> FLUID = Loadables.FLUID.defaultField("fluid", Fluids.EMPTY, false, FLUID_GETTER);
/** Field for fluid stack count that allows empty */
private static final LoadableField<Integer,FluidStack> AMOUNT = IntLoadable.FROM_ZERO.requiredField("amount", FluidStack::getAmount);
/** Field for fluid stack count */
private static final LoadableField<CompoundTag,FluidStack> NBT = NBTLoadable.ALLOW_STRING.nullableField("nbt", FluidStack::getTag);
/* Optional */
/** Single item which may be empty with an amount of 1000 */
public static final Loadable<FluidStack> OPTIONAL_BUCKET = fixedSize(FluidType.BUCKET_VOLUME);
/** Loadable for a stack that may be empty with variable count */
public static final RecordLoadable<FluidStack> OPTIONAL_STACK = RecordLoadable.create(FLUID, AMOUNT, (fluid, count) -> makeStack(fluid, count, null));
/** Loadable for a stack that may be empty with NBT and an amount of 1000 */
public static final RecordLoadable<FluidStack> OPTIONAL_BUCKET_NBT = fixedSizeNBT(FluidType.BUCKET_VOLUME);
/** Loadable for a stack that may be empty with variable count and NBT */
public static final RecordLoadable<FluidStack> OPTIONAL_STACK_NBT = RecordLoadable.create(FLUID, AMOUNT, NBT, FluidStackLoadable::makeStack);
/* Required */
/** Single item which may not be empty with an amount of 1000 */
public static final Loadable<FluidStack> REQUIRED_BUCKET = notEmpty(OPTIONAL_BUCKET);
/** Loadable for a stack that may not be empty with variable count */
public static final RecordLoadable<FluidStack> REQUIRED_STACK = notEmpty(OPTIONAL_STACK);
/** Loadable for a stack that may not be empty with NBT and an amount of 1000 */
public static final RecordLoadable<FluidStack> REQUIRED_BUCKET_NBT = notEmpty(OPTIONAL_BUCKET_NBT);
/** Loadable for a stack that may not be empty with variable count and NBT */
public static final RecordLoadable<FluidStack> REQUIRED_STACK_NBT = notEmpty(OPTIONAL_STACK_NBT);
/* Helpers */
/** Makes an item stack from the given parameters */
private static FluidStack makeStack(Fluid fluid, int amount, @Nullable CompoundTag nbt) {
if (fluid == Fluids.EMPTY || amount <= 0) {
return FluidStack.EMPTY;
}
return new FluidStack(fluid, amount, nbt);
}
/** Creates a loadable for a stack with a single item */
public static Loadable<FluidStack> fixedSize(int amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Count must be positive, received " + amount);
}
return Loadables.FLUID.flatXmap(fluid -> makeStack(fluid, amount, null), FLUID_GETTER);
}
/** Creates a loadable for a stack with a single item */
public static RecordLoadable<FluidStack> fixedSizeNBT(int amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Amount must be positive, received " + amount);
}
return RecordLoadable.create(FLUID, NBT, (fluid, tag) -> makeStack(fluid, amount, tag))
.compact(OPTIONAL_BUCKET, COMPACT_NBT);
}
/** Creates a non-empty variant of the loadable */
public static Loadable<FluidStack> notEmpty(Loadable<FluidStack> loadable) {
return loadable.validate(NOT_EMPTY);
}
/** Creates a non-empty variant of the loadable */
public static RecordLoadable<FluidStack> notEmpty(RecordLoadable<FluidStack> loadable) {
return loadable.validate(NOT_EMPTY);
}
}
| 0 | 0.799002 | 1 | 0.799002 | game-dev | MEDIA | 0.435324 | game-dev | 0.956493 | 1 | 0.956493 |
mastercomfig/tf2-patches-old | 18,253 | src/hammer/mapsprite.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Supports sprite preview and sprite icons for entities.
//
//===========================================================================//
#include "stdafx.h"
#include "hammer_mathlib.h"
#include "Box3D.h"
#include "BSPFile.h"
#include "const.h"
#include "MapDefs.h" // dvs: For COORD_NOTINIT
#include "MapDoc.h"
#include "MapEntity.h"
#include "MapSprite.h"
#include "Render2D.h"
#include "Render3D.h"
#include "hammer.h"
#include "Texture.h"
#include "TextureSystem.h"
#include "materialsystem/imesh.h"
#include "Material.h"
#include "Options.h"
#include "camera.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
IMPLEMENT_MAPCLASS(CMapSprite)
//-----------------------------------------------------------------------------
// Purpose: Factory function. Used for creating a CMapSprite from a set
// of string parameters from the FGD file.
// Input : *pInfo - Pointer to helper info class which gives us information
// about how to create the class.
// Output : Returns a pointer to the class, NULL if an error occurs.
//-----------------------------------------------------------------------------
CMapClass *CMapSprite::CreateMapSprite(CHelperInfo *pHelperInfo, CMapEntity *pParent)
{
const char *pszSprite = pHelperInfo->GetParameter(0);
//
// If we weren't passed a sprite name as an argument, get it from our parent
// entity's "model" key.
//
if (pszSprite == NULL)
{
pszSprite = pParent->GetKeyValue("model");
}
// HACK?
// When loading sprites, it can be the case that 'materials' is prepended
// This is because we have to look in the materials directory for sprites
// Remove the materials prefix...
if (pszSprite)
{
if (!strnicmp(pszSprite, "materials", 9) && ((pszSprite[9] == '/') || (pszSprite[9] == '\\')) )
{
pszSprite += 10;
}
}
//
// If we have a sprite name, create a sprite object.
//
CMapSprite *pSprite = NULL;
if (pszSprite != NULL)
{
pSprite = CreateMapSprite(pszSprite);
if (pSprite != NULL)
{
//
// Icons are alpha tested.
//
if (!stricmp(pHelperInfo->GetName(), "iconsprite"))
{
pSprite->SetRenderMode( kRenderTransAlpha );
pSprite->m_bIsIcon = true;
}
else
{
// FIXME: Gotta do this a little better
// This initializes the render mode in the sprite
pSprite->SetRenderMode( pSprite->m_eRenderMode );
}
}
}
return(pSprite);
}
//-----------------------------------------------------------------------------
// Purpose: Factory. Use this to construct CMapSprite objects, since the
// constructor is protected.
//-----------------------------------------------------------------------------
CMapSprite *CMapSprite::CreateMapSprite(const char *pszSpritePath)
{
CMapSprite *pSprite = new CMapSprite;
if (pSprite != NULL)
{
char szPath[MAX_PATH];
pSprite->Initialize();
// HACK: Remove the extension, this is for backward compatability
// It's trying to load a .spr, but we're giving it a .vmt.
strcpy( szPath, pszSpritePath );
char* pDot = strrchr( szPath, '.' );
if (pDot)
*pDot = 0;
pSprite->m_pSpriteInfo = CSpriteCache::CreateSprite(szPath);
if (pSprite->m_pSpriteInfo)
{
pSprite->CalcBounds();
}
}
return(pSprite);
}
//-----------------------------------------------------------------------------
// Purpose: Constructor.
//-----------------------------------------------------------------------------
CMapSprite::CMapSprite(void)
{
Initialize();
}
//-----------------------------------------------------------------------------
// Purpose: Destructor.
//-----------------------------------------------------------------------------
CMapSprite::~CMapSprite(void)
{
CSpriteCache::Release(m_pSpriteInfo);
}
//-----------------------------------------------------------------------------
// Sets the render mode
//-----------------------------------------------------------------------------
void CMapSprite::SetRenderMode( int eRenderMode )
{
m_eRenderMode = eRenderMode;
if (m_pSpriteInfo)
m_pSpriteInfo->SetRenderMode( m_eRenderMode );
}
//-----------------------------------------------------------------------------
// Purpose: Calculates our bounding box based on the sprite dimensions.
// Input : bFullUpdate - Whether we should recalculate our childrens' bounds.
//-----------------------------------------------------------------------------
void CMapSprite::CalcBounds(BOOL bFullUpdate)
{
CMapClass::CalcBounds(bFullUpdate);
float fRadius = 8;
if (m_pSpriteInfo)
{
fRadius = max(m_pSpriteInfo->GetWidth(), m_pSpriteInfo->GetHeight()) * m_fScale / 2.0;
if (fRadius == 0)
{
fRadius = 8;
}
}
//
// Build our bounds for frustum culling in the 3D view.
//
Vector Mins = m_Origin - Vector(fRadius, fRadius, fRadius);
Vector Maxs = m_Origin + Vector(fRadius, fRadius, fRadius);
m_CullBox.UpdateBounds(Mins, Maxs);
m_BoundingBox = m_CullBox;
//
// Build our bounds for 2D rendering. We keep sprites small in the 2D views no
// matter how large they are scaled.
//
if (!m_bIsIcon)
{
fRadius = 2;
}
Mins = m_Origin - Vector(fRadius, fRadius, fRadius);
Maxs = m_Origin + Vector(fRadius, fRadius, fRadius);
m_Render2DBox.UpdateBounds(Mins, Maxs);
}
//-----------------------------------------------------------------------------
// Purpose: Returns a copy of this object.
// Output : Pointer to the new object.
//-----------------------------------------------------------------------------
CMapClass *CMapSprite::Copy(bool bUpdateDependencies)
{
CMapSprite *pCopy = new CMapSprite;
if (pCopy != NULL)
{
pCopy->CopyFrom(this, bUpdateDependencies);
}
return(pCopy);
}
//-----------------------------------------------------------------------------
// Purpose: Turns this into a duplicate of the given object.
// Input : pObject - Pointer to the object to copy from.
// Output : Returns a pointer to this object.
//-----------------------------------------------------------------------------
CMapClass *CMapSprite::CopyFrom(CMapClass *pObject, bool bUpdateDependencies)
{
CMapSprite *pFrom = dynamic_cast<CMapSprite *>(pObject);
Assert(pObject != NULL);
if (pObject != NULL)
{
CMapClass::CopyFrom(pObject, bUpdateDependencies);
m_Angles = pFrom->m_Angles;
m_pSpriteInfo = pFrom->m_pSpriteInfo;
CSpriteCache::AddRef(pFrom->m_pSpriteInfo);
m_nCurrentFrame = pFrom->m_nCurrentFrame;
m_fSecondsPerFrame = pFrom->m_fSecondsPerFrame;
m_fElapsedTimeThisFrame = pFrom->m_fElapsedTimeThisFrame;
m_fScale = pFrom->m_fScale;
SetRenderMode( pFrom->m_eRenderMode );
m_RenderColor = pFrom->m_RenderColor;
m_bIsIcon = pFrom->m_bIsIcon;
}
return(this);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : bEnable -
//-----------------------------------------------------------------------------
void CMapSprite::EnableAnimation(BOOL bEnable)
{
//m_bAnimateModels = bEnable;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : Angles -
//-----------------------------------------------------------------------------
void CMapSprite::GetAngles(QAngle &Angles)
{
Angles = m_Angles;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMapSprite::Initialize(void)
{
m_Angles.Init();
m_eRenderMode = kRenderNormal;
m_RenderColor.r = 255;
m_RenderColor.g = 255;
m_RenderColor.b = 255;
m_fSecondsPerFrame = 1;
m_fElapsedTimeThisFrame = 0;
m_nCurrentFrame = 0;
m_fScale = 0.25;
m_bIsIcon = false;
}
//-----------------------------------------------------------------------------
// Updates time and returns the next frame
//-----------------------------------------------------------------------------
int CMapSprite::GetNextSpriteFrame( CRender3D* pRender )
{
//
// Determine whether we need to advance to the next frame based on our
// sprite framerate and the elapsed time.
//
int nNumFrames = m_pSpriteInfo->GetFrameCount();
if (nNumFrames > 1)
{
float fElapsedTime = pRender->GetElapsedTime();
m_fElapsedTimeThisFrame += fElapsedTime;
while (m_fElapsedTimeThisFrame > m_fSecondsPerFrame)
{
m_nCurrentFrame++;
m_fElapsedTimeThisFrame -= m_fSecondsPerFrame;
}
m_nCurrentFrame %= nNumFrames;
}
return m_nCurrentFrame;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pRender -
//-----------------------------------------------------------------------------
void CMapSprite::Render3D(CRender3D *pRender)
{
int nPasses;
if ((GetSelectionState() != SELECT_NONE) && (!m_bIsIcon))
{
if (pRender->NeedsOverlay())
nPasses = 3;
else
nPasses = 2;
}
else
{
nPasses = 1;
}
//
// If we have a sprite, render it.
//
if (m_pSpriteInfo)
{
//
// Only sprite icons can be clicked on, sprite preview objects cannot.
//
if (m_bIsIcon)
{
pRender->BeginRenderHitTarget(this);
}
m_pSpriteInfo->SetOrigin(m_Origin);
m_pSpriteInfo->SetAngles(m_Angles);
m_pSpriteInfo->Bind(pRender, GetNextSpriteFrame(pRender));
for (int nPass = 0; nPass < nPasses; nPass++)
{
if (nPass == 0)
{
// First pass uses the default rendering mode.
// unless that mode is texture
if (pRender->GetCurrentRenderMode() == RENDER_MODE_LIGHTMAP_GRID)
pRender->PushRenderMode( RENDER_MODE_TEXTURED);
else
pRender->PushRenderMode( RENDER_MODE_CURRENT );
}
else
{
if (nPass == nPasses - 1)
{
// last pass uses wireframe rendering mode.
pRender->PushRenderMode( RENDER_MODE_WIREFRAME);
}
else
{
pRender->PushRenderMode( RENDER_MODE_SELECTION_OVERLAY );
}
}
m_pSpriteInfo->SetScale(m_fScale > 0 ? m_fScale : 1.0 );
float fBlend;
// dvs: lots of things contribute to blend factor. See r_blend in engine.
//if (m_eRenderMode == kRenderNormal)
{
fBlend = 1.0;
}
unsigned char color[4];
SpriteColor( color, m_eRenderMode, m_RenderColor, fBlend * 255);
//
// If selected, render a yellow wireframe box.
//
if (GetSelectionState() != SELECT_NONE)
{
if (m_bIsIcon)
{
pRender->RenderWireframeBox(m_Render2DBox.bmins, m_Render2DBox.bmaxs, 255, 255, 0);
}
else
{
color[0] = 255;
color[1] = color[2] = 0;
}
//
// If selected, render the sprite with a yellow wireframe around it.
//
if ( nPass > 0 )
{
color[0] = color[1] = 255;
color[2] = 0;
}
}
MaterialPrimitiveType_t type = (nPass > 0) ? MATERIAL_LINE_LOOP : MATERIAL_POLYGON;
m_pSpriteInfo->SetMaterialPrimitiveType( type );
m_pSpriteInfo->DrawSprite3D( pRender, color );
pRender->PopRenderMode();
}
//
// Only sprite icons can be clicked on, sprite preview objects cannot.
//
if (m_bIsIcon)
{
pRender->EndRenderHitTarget();
}
}
//
// Else no sprite, render as a bounding box.
//
else if (m_bIsIcon)
{
pRender->BeginRenderHitTarget(this);
pRender->RenderBox(m_Render2DBox.bmins, m_Render2DBox.bmaxs, r, g, b, GetSelectionState());
pRender->EndRenderHitTarget();
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &File -
// bRMF -
// Output : int
//-----------------------------------------------------------------------------
int CMapSprite::SerializeRMF(std::fstream &File, BOOL bRMF)
{
return(0);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &File -
// bRMF -
// Output : int
//-----------------------------------------------------------------------------
int CMapSprite::SerializeMAP(std::fstream &File, BOOL bRMF)
{
return(0);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pTransBox -
//-----------------------------------------------------------------------------
void CMapSprite::DoTransform(const VMatrix &matrix)
{
BaseClass::DoTransform(matrix);
matrix3x4_t fCurrentMatrix,fMatrixNew;
AngleMatrix(m_Angles, fCurrentMatrix);
ConcatTransforms(matrix.As3x4(), fCurrentMatrix, fMatrixNew);
MatrixAngles(fMatrixNew, m_Angles);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pColor -
// pEntity -
// alpha -
//-----------------------------------------------------------------------------
void CMapSprite::SpriteColor(unsigned char *pColor, int eRenderMode, colorVec RenderColor, int alpha)
{
int a;
if ((eRenderMode == kRenderTransAdd) || (eRenderMode == kRenderGlow) || (eRenderMode == kRenderWorldGlow))
{
a = alpha;
}
else
{
a = 256;
}
if ((RenderColor.r == 0) && (RenderColor.g == 0) && (RenderColor.b == 0))
{
pColor[0] = pColor[1] = pColor[2] = (255 * a) >> 8;
}
else
{
pColor[0] = ((int)RenderColor.r * a)>>8;
pColor[1] = ((int)RenderColor.g * a)>>8;
pColor[2] = ((int)RenderColor.b * a)>>8;
}
}
//-----------------------------------------------------------------------------
// Purpose: Notifies that this object's parent entity has had a key value change.
// Input : szKey - The key that changed.
// szValue - The new value of the key.
//-----------------------------------------------------------------------------
void CMapSprite::OnParentKeyChanged(const char* szKey, const char* szValue)
{
if (!stricmp(szKey, "framerate"))
{
float fFramesPerSecond = atof(szValue);
if (fabs(fFramesPerSecond) > 0.001)
{
m_fSecondsPerFrame = 1 / fFramesPerSecond;
}
}
else if (!stricmp(szKey, "scale"))
{
m_fScale = atof(szValue);
if (m_fScale == 0)
{
m_fScale = 1;
}
m_pSpriteInfo->SetScale(m_fScale);
PostUpdate(Notify_Changed);
}
else if (!stricmp(szKey, "rendermode"))
{
switch (atoi(szValue))
{
case 0: // "Normal"
{
SetRenderMode( kRenderNormal );
break;
}
case 1: // "Color"
{
SetRenderMode( kRenderTransColor );
break;
}
case 2: // "Texture"
{
SetRenderMode( kRenderNormal );
break;
}
case 3: // "Glow"
{
SetRenderMode( kRenderGlow );
break;
}
case 4: // "Solid"
{
SetRenderMode( kRenderNormal );
break;
}
case 5: // "Additive"
{
SetRenderMode( kRenderTransAdd );
break;
}
case 7: // "Additive Fractional Frame"
{
SetRenderMode( kRenderTransAddFrameBlend );
break;
}
case 9: // "World Space Glow"
{
SetRenderMode( kRenderWorldGlow );
break;
}
}
}
//
// If we are the child of a light entity and its color is changing, change our render color.
//
else if (!stricmp(szKey, "_light"))
{
sscanf(szValue, "%d %d %d", &m_RenderColor.r, &m_RenderColor.g, &m_RenderColor.b);
}
else if (!stricmp(szKey, "angles"))
{
sscanf(szValue, "%f %f %f", &m_Angles[PITCH], &m_Angles[YAW], &m_Angles[ROLL]);
PostUpdate(Notify_Changed);
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CMapSprite::ShouldRenderLast(void)
{
return(true);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMapSprite::Render2D(CRender2D *pRender)
{
Vector vecMins;
Vector vecMaxs;
GetRender2DBox(vecMins, vecMaxs);
Vector2D pt,pt2;
pRender->TransformPoint(pt, vecMins);
pRender->TransformPoint(pt2, vecMaxs);
if ( !IsSelected() )
{
pRender->SetDrawColor( r, g, b );
pRender->SetHandleColor( r, g, b );
}
else
{
pRender->SetDrawColor( GetRValue(Options.colors.clrSelection), GetGValue(Options.colors.clrSelection), GetBValue(Options.colors.clrSelection) );
pRender->SetHandleColor( GetRValue(Options.colors.clrSelection), GetGValue(Options.colors.clrSelection), GetBValue(Options.colors.clrSelection) );
}
// Draw the bounding box.
pRender->DrawBox( vecMins, vecMaxs );
//
// Draw center handle.
//
if ( pRender->IsActiveView() )
{
int sizex = abs(pt.x - pt2.x)+1;
int sizey = abs(pt.y - pt2.y)+1;
// dont draw handle if object is too small
if ( sizex > 6 && sizey > 6 )
{
pRender->SetHandleStyle( HANDLE_RADIUS, CRender::HANDLE_CROSS );
pRender->DrawHandle( (vecMins+vecMaxs)/2 );
}
}
}
//-----------------------------------------------------------------------------
// Called by entity code to render sprites
//-----------------------------------------------------------------------------
void CMapSprite::RenderLogicalAt(CRender2D *pRender, const Vector2D &vecMins, const Vector2D &vecMaxs )
{
// If we have a sprite, render it.
if (!m_pSpriteInfo)
return;
m_pSpriteInfo->Bind( pRender, 0 );
pRender->PushRenderMode( RENDER_MODE_TEXTURED);
unsigned char color[4] = { 255, 255, 255, 255 };
SpriteColor( color, m_eRenderMode, m_RenderColor, 255);
// If selected, render a yellow wireframe box.
if ( GetSelectionState() != SELECT_NONE )
{
color[0] = 255;
color[1] = color[2] = 0;
}
CMatRenderContextPtr pRenderContext( MaterialSystemInterface() );
IMesh* pMesh = pRenderContext->GetDynamicMesh();
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_POLYGON, 4 );
meshBuilder.Position3f( vecMins.x, vecMins.y, 0.0f );
meshBuilder.TexCoord2f(0, 0, 1);
meshBuilder.Color3ub( color[0], color[1], color[2] );
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( vecMins.x, vecMaxs.y, 0.0f );
meshBuilder.TexCoord2f(0, 0, 0);
meshBuilder.Color3ub( color[0], color[1], color[2] );
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( vecMaxs.x, vecMaxs.y, 0.0f );
meshBuilder.TexCoord2f(0, 1, 0);
meshBuilder.Color3ub( color[0], color[1], color[2] );
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( vecMaxs.x, vecMins.y, 0.0f );
meshBuilder.TexCoord2f(0, 1, 1);
meshBuilder.Color3ub( color[0], color[1], color[2] );
meshBuilder.AdvanceVertex();
meshBuilder.End();
pMesh->Draw();
pRender->PopRenderMode();
} | 0 | 0.970058 | 1 | 0.970058 | game-dev | MEDIA | 0.676018 | game-dev,graphics-rendering | 0.986371 | 1 | 0.986371 |
AvantTeam/ProjectUnityPublic | 4,106 | main/src/unity/ai/HealingDefenderAI.java | package unity.ai;
import arc.math.*;
import arc.math.geom.*;
import mindustry.ai.types.*;
import mindustry.entities.*;
import mindustry.entities.units.*;
import mindustry.gen.*;
import mindustry.type.*;
import mindustry.world.meta.*;
/** @author EyeOfDarkness */
public class HealingDefenderAI extends DefenderAI{
@Override
public void updateTargeting(){
if(unit.hasWeapons()){
updateWeapons();
}else{
super.updateTargeting();
}
}
@Override
public void updateWeapons(){
float rotation = unit.rotation - 90;
boolean ret = retarget();
if(ret){
target = findTarget(unit.x, unit.y, unit.range(), true, true);
if(invalid(target)) target = null;
}
unit.isShooting = false;
for(WeaponMount mount : unit.mounts){
Weapon weapon = mount.weapon;
if(!weapon.controllable || weapon.bullet.healPercent <= 0f) continue;
float mountX = unit.x + Angles.trnsx(rotation, weapon.x, weapon.y),
mountY = unit.y + Angles.trnsy(rotation, weapon.x, weapon.y);
if(unit.type.singleTarget){
mount.target = target;
}else{
if(ret) mount.target = findTargetAlt(mountX, mountY, weapon.bullet.range, weapon.bullet.collidesAir, weapon.bullet.collidesGround);
}
if(checkTarget(mount.target, mountX, mountY, weapon.bullet.range)) mount.target = null;
boolean shoot = false;
if(mount.target != null){
shoot = mount.target.within(mountX, mountY, weapon.bullet.range + (mount.target instanceof Sized s ? s.hitSize()/2f : 0f)) && shouldShoot();
Vec2 to = Predict.intercept(unit, mount.target, weapon.bullet.speed);
mount.aimX = to.x;
mount.aimY = to.y;
}
unit.isShooting |= (mount.shoot = mount.rotate = shoot);
if(shoot){
unit.aimX = mount.aimX;
unit.aimY = mount.aimY;
}
}
}
@Override
public boolean checkTarget(Teamc target, float x, float y, float range){
return target == null || target.team() != unit.team || (target instanceof Healthc h && (h.health() >= h.maxHealth() || h.dead())) || (range != Float.MAX_VALUE && !target.within(x, y, range + (target instanceof Sized hb ? hb.hitSize()/2f : 0f)));
}
@Override
public boolean invalid(Teamc target){
return target == null || target.team() != unit.team || (target instanceof Healthc h && h.dead());
}
Teamc findTargetAlt(float x, float y, float range, boolean air, boolean ground){
Teamc trueResult;
Building blockResult = ground ? Units.findDamagedTile(unit.team, unit.x, unit.y) : null;
Unit unitResult = Units.closest(unit.team, x, y, Math.max(range, 400f), u -> !u.dead() && u.damaged() && u.checkTarget(air, ground) && u.type != unit.type, (u, tx, ty) -> -u.maxHealth + Mathf.dst2(u.x, u.y, tx, ty) / 6400f);
if(unitResult == null || (blockResult != null && (unitResult.dst2(unit) / 6400f) + unitResult.health > (blockResult.dst2(unit) / 6400f) + blockResult.health)){
trueResult = blockResult;
}else{
trueResult = unitResult;
}
return trueResult;
}
@Override
public Teamc findTarget(float x, float y, float range, boolean air, boolean ground){
Teamc trueResult;
Building blockResult = Units.findDamagedTile(unit.team, unit.x, unit.y);
Unit result = Units.closest(unit.team, x, y, Math.max(range, 400f), u -> !u.dead() && u.type != unit.type, (u, tx, ty) -> -u.maxHealth + Mathf.dst2(u.x, u.y, tx, ty) / 6400f);
if(result == null || (blockResult != null && (result.dst2(unit) / 6400f) + result.health > (blockResult.dst2(unit) / 6400f) + blockResult.health)){
trueResult = blockResult;
}else{
trueResult = result;
}
if(trueResult != null) return trueResult;
return unit.closestCore();
}
}
| 0 | 0.943969 | 1 | 0.943969 | game-dev | MEDIA | 0.98743 | game-dev | 0.977256 | 1 | 0.977256 |
GameFoundry/bsf | 1,854 | Source/Scripting/bsfScript/Extensions/BsAnimationEx.cpp | //********************************* bs::framework - Copyright 2018-2019 Marko Pintera ************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#include "Extensions/BsAnimationEx.h"
using namespace std::placeholders;
namespace bs
{
Vector<TNamedAnimationCurve<Vector3>> AnimationCurvesEx::getPositionCurves(const SPtr<AnimationCurves>& thisPtr)
{
return thisPtr->position;
}
void AnimationCurvesEx::setPositionCurves(const SPtr<AnimationCurves>& thisPtr, const Vector<TNamedAnimationCurve<Vector3>>& value)
{
thisPtr->position = value;
}
Vector<TNamedAnimationCurve<Quaternion>> AnimationCurvesEx::getRotationCurves(const SPtr<AnimationCurves>& thisPtr)
{
return thisPtr->rotation;
}
void AnimationCurvesEx::setRotationCurves(const SPtr<AnimationCurves>& thisPtr, const Vector<TNamedAnimationCurve<Quaternion>>& value)
{
thisPtr->rotation = value;
}
Vector<TNamedAnimationCurve<Vector3>> AnimationCurvesEx::getScaleCurves(const SPtr<AnimationCurves>& thisPtr)
{
return thisPtr->scale;
}
void AnimationCurvesEx::setScaleCurves(const SPtr<AnimationCurves>& thisPtr, const Vector<TNamedAnimationCurve<Vector3>>& value)
{
thisPtr->scale = value;
}
Vector<TNamedAnimationCurve<float>> AnimationCurvesEx::getGenericCurves(const SPtr<AnimationCurves>& thisPtr)
{
return thisPtr->generic;
}
void AnimationCurvesEx::setGenericCurves(const SPtr<AnimationCurves>& thisPtr, const Vector<TNamedAnimationCurve<float>>& value)
{
thisPtr->generic = value;
}
TAnimationCurve<Vector3> RootMotionEx::getPositionCurves(const SPtr<RootMotion>& thisPtr)
{
return thisPtr->position;
}
TAnimationCurve<Quaternion> RootMotionEx::getRotationCurves(const SPtr<RootMotion>& thisPtr)
{
return thisPtr->rotation;
}
}
| 0 | 0.740546 | 1 | 0.740546 | game-dev | MEDIA | 0.882874 | game-dev | 0.592123 | 1 | 0.592123 |
DarkflameUniverse/DarkflameServer | 7,114 | dGame/dInventory/Item.h | #pragma once
#include "dCommonVars.h"
#include "Inventory.h"
#include "LDFFormat.h"
#include "CDClientManager.h"
#include "Logger.h"
#include "Preconditions.h"
#include "eInventoryType.h"
#include "eLootSourceType.h"
namespace tinyxml2 {
class XMLElement;
};
/**
* An item that can be stored in an inventory and optionally consumed or equipped
* TODO: ideally this should be a component
*/
class Item final
{
public:
/**
* Creates an item, should be used if the item is not picked up but already exists
* @param id the object ID of the item to create
* @param lot the LOT of the item
* @param inventory the inventory to add this item to
* @param slot the slot in the inventory to add this item to
* @param count the amount of items to add to the inventory
* @param bound if the item should be bound
* @param config config data for this item, e.g. for rockets
* @param parent optional parent of this item, e.g. for proxy items
* @param subKey optional subkey for this item, e.g. for pets
*/
explicit Item(
LWOOBJID id,
LOT lot,
Inventory* inventory,
uint32_t slot,
uint32_t count,
bool bound,
const std::vector<LDFBaseData*>& config,
LWOOBJID parent,
LWOOBJID subKey,
eLootSourceType lootSourceType = eLootSourceType::NONE
);
/**
* Creates an item, should be used if the item is picked up / added to the inventory after load
* @param lot the LOT of the item
* @param inventory the inventory to add this item to
* @param slot the slot in the inventory to add this item to
* @param count the amount of items to add to the inventory
* @param config config data for this item, e.g. for rockets
* @param parent optional parent of this item, e.g. for proxy items
* @param showFlyingLoot show UI animation of the item being added
* @param isModMoveAndEquip equips the item
* @param subKey optional subkey for this item, e.g. for pets
* @param bound if the item should be bound
*/
explicit Item(
LOT lot,
Inventory* inventory,
uint32_t slot = 0,
uint32_t count = 1,
const std::vector<LDFBaseData*>& config = {},
LWOOBJID parent = LWOOBJID_EMPTY,
bool showFlyingLoot = true,
bool isModMoveAndEquip = false,
LWOOBJID subKey = LWOOBJID_EMPTY,
bool bound = false,
eLootSourceType lootSourceType = eLootSourceType::NONE
);
~Item();
/**
* Returns the object ID of this item
* @return the object ID of this item
*/
LWOOBJID GetId() const;
/**
* Returns the lot of this item
* @return the lot of this item
*/
LOT GetLot() const;
/**
* Sets the number of items this item represents
* @param value the number to update by
* @param silent if true, the client will not be notified of the change with GMs
* @param disassemble if items were removed, this returns all the sub parts of the item individually if it had assembly part lots
* @param showFlyingLoot shows flying loot to the client, if not silent
*/
void SetCount(uint32_t value, bool silent = false, bool disassemble = true, bool showFlyingLoot = true, eLootSourceType lootSourceType = eLootSourceType::NONE);
/**
* Returns the number of items this item represents (e.g. for stacks)
* @return the number of items this item represents
*/
uint32_t GetCount() const;
/**
* Sets the slot this item is stored in
* @param value the slot this item is stored in
*/
void SetSlot(uint32_t value);
/**
* Returns the slot this item is in
* @return the slot this item is in
*/
uint32_t GetSlot() const;
/**
* Returns current config info for this item, e.g. for rockets
* @return current config info for this item
*/
std::vector<LDFBaseData*>& GetConfig();
/**
* Returns current config info for this item, e.g. for rockets
* @return current config info for this item
*/
std::vector<LDFBaseData*> GetConfig() const;
/**
* Returns the database info for this item
* @return the database info for this item
*/
const CDItemComponent& GetInfo() const;
/**
* Sets if the item is bound
* @param value if the item is bound
*/
void SetBound(bool value);
/**
* Returns if the item is bound
* @return if the item is bound
*/
bool GetBound() const;
/**
* Sets the inventory this item belongs to
* @param value the inventory this item belongs to
*/
void SetInventory(Inventory* value);
/**
* Returns the inventory this item belongs to
* @return the inventory this item belongs to
*/
Inventory* GetInventory() const;
/**
* Returns the parent of this item, e.g. for proxy items
* @return the parent of this item
*/
LWOOBJID GetParent() const;
/**
* Sets the subkey for this item, e.g. for pets
* @param value the subkey for this item
*/
void SetSubKey(LWOOBJID value);
/**
* Returns the sub key this item has, e.g. for pets
* @return the sub key this item has
*/
LWOOBJID GetSubKey() const;
/**
* Returns the preconditions that must be met before this item may be used
* @return the preconditions that must be met before this item may be used
*/
PreconditionExpression* GetPreconditionExpression() const;
/**
* Equips this item into the linked inventory
* @param skipChecks skips equip checks for special items like rockets and cars
*/
void Equip(bool skipChecks = false);
/**
* Unequps the item from the linked inventory
*/
void UnEquip();
/**
* Returns if the item is equipped in the linked inventory
* @return if the item is equipped
*/
bool IsEquipped() const;
/**
* Attempts to consume one of this item, applying its skills
* @return whether the consumption was successful, e.g. the skill was cast
*/
bool Consume();
/**
* Uses this item if its non equip, essentially an interface for the linked GM
*/
void UseNonEquip(Item* item);
/**
* Disassembles the part LOTs of this item back into the inventory, if it has any
* @param inventoryType the inventory to dissassemble into
*/
void Disassemble(eInventoryType inventoryType = INVALID);
/**
* Disassembles this item into bricks
*/
void DisassembleModel(uint32_t numToDismantle);
/**
* Removes the item from the linked inventory
*/
void RemoveFromInventory();
void SaveConfigXml(tinyxml2::XMLElement& i) const;
void LoadConfigXml(const tinyxml2::XMLElement& i);
LWOOBJID GenerateID();
private:
/**
* The object ID of this item
*/
LWOOBJID id;
/**
* The LOT of this item
*/
LOT lot;
/**
* The number of items this represents
*/
uint32_t count;
/**
* The slot this item is stored in
*/
uint32_t slot;
/**
* If this item is bound
*/
bool bound;
/**
* A potential parent of this item, if this item is a subitem
*/
LWOOBJID parent;
/**
* A potential subkey of this item, e.g. for pets
*/
LWOOBJID subKey;
/**
* Config data for this item, e.g. for rocket parts and car parts
*/
std::vector<LDFBaseData*> config;
/**
* The inventory this item belongs to
*/
Inventory* inventory;
/**
* The database information of this item
*/
const CDItemComponent* info;
/**
* A precondition to using this item
*/
PreconditionExpression* preconditions = nullptr;
};
| 0 | 0.9303 | 1 | 0.9303 | game-dev | MEDIA | 0.409638 | game-dev | 0.74459 | 1 | 0.74459 |
Rackover/xvy | 9,937 | Assets/Scripts/Level.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class Level : MonoBehaviour
{
public const byte PLAYERS = 2;
public event Action OnScoreChanged;
[SerializeField]
private Material skybox;
[SerializeField]
private bool fogEnabled = false;
[SerializeField]
private Color fogColor;
[SerializeField]
private float fogStart;
[SerializeField]
private float fogEnd;
[SerializeField]
private Player playerPrefab;
[SerializeField]
private Transform[] spawns = new Transform[PLAYERS];
[SerializeField]
private IdleCamera[] idleCameras = new IdleCamera[PLAYERS];
[SerializeField]
private Bounds boundaries;
[SerializeField]
private float maxOobTime = 3f;
[SerializeField]
private float speedMultiplier = 1f;
public int Winner { get { return scores[0] > scores[1] ? 0 : 1; } }
public float SpeedMultiplier { get { return speedMultiplier; } }
public IList<int> Scores { get { return scores; } }
public bool GameOver { get { return gameOver; } }
private bool gameOver = false;
private readonly Player[] players = new Player[PLAYERS];
private readonly Transform[] trackingTargets = new Transform[PLAYERS];
private readonly int[] scores = new int[PLAYERS];
private readonly float[] oobTime = new float[PLAYERS];
private void Awake()
{
if (Game.i)
{
Game.i.RegisterLevel(this);
}
}
public Transform[] GetTrackingTargets()
{
return trackingTargets;
}
public void Exit()
{
for (int i = 0; i < PLAYERS; i++)
{
if (players[i])
{
Destroy(players[i].gameObject);
}
}
}
public void Enter()
{
RenderSettings.fog = fogEnabled;
RenderSettings.fogStartDistance = fogStart;
RenderSettings.fogEndDistance = fogEnd;
RenderSettings.fogDensity = fogColor.a;
RenderSettings.fogColor = fogColor;
RenderSettings.fogMode = FogMode.Linear;
playerPrefab.gameObject.SetActive(false);
gameOver = false;
RenderSettings.skybox = skybox;
#if UNITY_XENON && !UNITY_EDITOR
if (X360Core.GetTotalSignedInUsers() < 2)
{
X360Core.RequestSignIn(PLAYERS, PLAYERS, false);
}
#endif
for (int i = 0; i < PLAYERS; i++)
{
players[i] = Instantiate(playerPrefab);
players[i].gameObject.SetActive(true);
players[i].Initialize(i);
scores[i] = 0;
oobTime[i] = 0f;
int index = i;
players[i].OnKilled += () => OnPlayerKilled(index);
Debug.Log("created player " + i);
}
UpdateTrackingTargets();
}
public void FillEmptySeats()
{
for (int i = 0; i < players.Length; i++)
{
if (!players[i].GamepadConnected())
{
players[i].MakeMock();
}
}
}
private void OnPlayerKilled(int player)
{
if (GameOver)
{
players[player].Birth(spawns[player]);
}
else
{
scores[1 - player]++;
if (OnScoreChanged != null)
{
OnScoreChanged.Invoke();
}
for (int i = 0; i < Scores.Count; i++)
{
if (Scores[i] >= Game.i.ScoreToWin)
{
gameOver = true;
break;
}
}
}
}
public bool IsOOB(int player, out float lifeRemaining01)
{
if (players[player])
{
lifeRemaining01 = 1f - oobTime[player] / maxOobTime;
if (boundaries.Contains(players[player].Transform.position))
{
return false;
}
else
{
return true;
}
}
lifeRemaining01 = 0f;
return false;
}
public bool HasAlmostWon(int? player = null)
{
if (player.HasValue)
{
return scores[player.Value] == Game.i.ScoreToWin - 1;
}
for (int i = 0; i < PLAYERS; i++)
{
if (scores[i] == Game.i.ScoreToWin - 1)
{
return true;
}
}
return false;
}
public bool WantsCredits()
{
for (int i = 0; i < PLAYERS; i++)
{
if (players[i] != null && players[i].WantsCredits())
{
return true;
}
}
return false;
}
public bool AnyKey()
{
for (int i = 0; i < PLAYERS; i++)
{
if (players[i] != null && players[i].AnyKey())
{
return true;
}
}
return false;
}
public bool IsPlayerConnected(int index)
{
return players[index] != null && players[index].GamepadConnected();
}
public bool IsPlayerBeingHomedTo(int index)
{
return players[index] != null && players[index].IsBeingHomedTo;
}
public PlayerWeapon GetPlayerWeapon(int index)
{
return players[index].Weapon;
}
public bool IsPlayerBoosting(int index)
{
return players[index] != null && players[index].IsBoosting;
}
public Transform GetPlayerTransform(int index)
{
return players[index].Transform;
}
public void PlaySoundOnPlayer(int index, AudioClip clip)
{
if (players[index] != null)
{
players[index].LocalSource.PlayOneShot(clip);
}
}
public float GetPlayerGees(int index)
{
return players[index].Gees01;
}
public float GetPlayerSpeed(int index)
{
return players[index].Speed;
}
public Vector3 GetPlayerPosition(int index)
{
return players[index].Transform.position;
}
public void KillPlayerFromMissile(int index)
{
if (players[index])
{
players[index].NotifyKilled();
}
}
public string GetPlayerDebugStateDump(int index)
{
return players[index] == null ? string.Empty : players[index].DebugDump;
}
public Camera GetPlayerCamera(int index)
{
return players[index].Camera;
}
public bool IsPlayerReady(int index)
{
return players[index] != null && players[index].IsReady;
}
public bool HasPlayerSpawned(int index)
{
return players[index] != null && players[index].IsSpawned;
}
public bool IsPlayerAlive(int index)
{
return players[index] != null && players[index].IsAlive;
}
public void RebirthPlayers()
{
for (int i = 0; i < PLAYERS; i++)
{
if (!players[i].IsSpawned || !players[i].IsAlive)
{
players[i].Birth(PickBestSpawn(i));
}
}
}
private Transform PickBestSpawn(int player)
{
int otherPlayer = 1 - player;
if (!players[otherPlayer].IsAlive)
{
return spawns[player];
}
float bestSpawnDistance = float.NegativeInfinity;
Transform bestSpawn = spawns[0];
for (int i = 0; i < spawns.Length; i++)
{
float dist = Vector3.SqrMagnitude(spawns[i].position - players[otherPlayer].Transform.position);
if (dist > bestSpawnDistance)
{
bestSpawn = spawns[i];
bestSpawnDistance = dist;
}
}
return bestSpawn;
}
void Update()
{
if (!Game.i || players == null)
{
return;
}
for (int i = 0; i < PLAYERS; i++)
{
if (players[i] == null)
{
return;
}
}
bool needsSpawn = true;
for (int i = 0; i < PLAYERS; i++)
{
idleCameras[i].gameObject.SetActive(!players[i].IsSpawned);
if (!IsPlayerReady(i))
{
needsSpawn = false;
}
}
if (needsSpawn)
{
for (int i = 0; i < PLAYERS; i++)
{
if (!players[i].IsSpawned)
{
players[i].Birth(spawns[i]);
}
}
}
UpdateOOB();
UpdateTrackingTargets();
}
void UpdateOOB()
{
for (int i = 0; i < PLAYERS; i++)
{
if (players[i].IsAlive && players[i].IsReady)
{
bool oob = !boundaries.Contains(players[i].Transform.position);
if (oob)
{
oobTime[i] += Time.deltaTime;
if (oobTime[i] > maxOobTime)
{
players[i].NotifyOobDeath();
oobTime[i] = 0f;
}
}
else if (oobTime[i] > 0f)
{
oobTime[i] -= Time.deltaTime;
}
else
{
oobTime[i] = 0f;
}
}
else
{
oobTime[i] = 0f;
}
}
}
private void UpdateTrackingTargets()
{
// Update tracking targets
for (int i = 0; i < PLAYERS; i++)
{
if (players[i].IsSpawned)
{
trackingTargets[i] = players[i].Transform;
}
else
{
trackingTargets[i] = spawns[i];
}
}
}
#if UNITY_EDITOR
void OnDrawGizmos()
{
Gizmos.color = Color.magenta;
Gizmos.DrawWireCube(boundaries.center, boundaries.size);
}
#endif
}
| 0 | 0.821307 | 1 | 0.821307 | game-dev | MEDIA | 0.830006 | game-dev | 0.861062 | 1 | 0.861062 |
shxp3/CrossSine | 20,789 | src/main/java/net/ccbluex/liquidbounce/features/module/modules/other/Teleport.java |
package net.ccbluex.liquidbounce.features.module.modules.other;
import net.ccbluex.liquidbounce.event.*;
import net.ccbluex.liquidbounce.features.module.Module;
import net.ccbluex.liquidbounce.features.module.ModuleCategory;
import net.ccbluex.liquidbounce.features.module.ModuleInfo;
import net.ccbluex.liquidbounce.features.value.BoolValue;
import net.ccbluex.liquidbounce.features.value.ListValue;
import net.ccbluex.liquidbounce.utils.MovementUtils;
import net.ccbluex.liquidbounce.utils.PathUtils;
import net.ccbluex.liquidbounce.utils.block.BlockUtils;
import net.ccbluex.liquidbounce.utils.render.RenderUtils;
import net.ccbluex.liquidbounce.utils.timer.tickTimer;
import net.minecraft.block.BlockAir;
import net.minecraft.block.BlockFence;
import net.minecraft.block.BlockSnow;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.C03PacketPlayer;
import net.minecraft.network.play.client.C0BPacketEntityAction;
import net.minecraft.network.play.client.C0BPacketEntityAction.Action;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import org.lwjgl.input.Mouse;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import static org.lwjgl.opengl.GL11.*;
@ModuleInfo(name = "Teleport",category = ModuleCategory.OTHER)
public class Teleport extends Module {
private final BoolValue ignoreNoCollision = new BoolValue("IgnoreNoCollision", true);
private final ListValue modeValue = new ListValue("Mode", new String[] {"Tp", "Blink", "Flag", "Rewinside", "OldRewinside", "Spoof", "Minesucht", "AAC3.5.0","BWRel","Karhu"}, "Tp");
private final ListValue buttonValue = new ListValue("Button", new String[] {"Left", "Right", "Middle"}, "Middle");
private final BoolValue needSneak = new BoolValue("NeedSneak", true);
private final tickTimer flyTimer = new tickTimer();
private boolean hadGround;
private double fixedY;
private final List<Packet<?>> packets = new ArrayList<>();
private boolean disableLogger = false;
private boolean zitter = false;
private boolean doTeleport = false;
private boolean freeze = false;
private final tickTimer freezeTimer = new tickTimer();
private final tickTimer respawnTimer = new tickTimer();
private int delay;
private BlockPos endPos;
private MovingObjectPosition objectPosition;
private double endX = 0.0D;
private double endY = 0.0D;
private double endZ = 0.0D;
@Override
public void onEnable() {
int matrixStage = -1;
if(modeValue.equals("AAC3.5.0")) {
alert("§c>>> §a§lTeleport §fAAC 3.5.0 §c<<<");
alert("§cHow to teleport: §aPress " + buttonValue.get() + " mouse button.");
alert("§cHow to cancel teleport: §aDisable teleport module.");
}
}
@Override
public void onDisable() {
fixedY = 0D;
delay = 0;
mc.timer.timerSpeed = 1F;
endPos = null;
hadGround = false;
freeze = false;
disableLogger = false;
flyTimer.reset();
packets.clear();
}
@EventTarget
public void onUpdate(final UpdateEvent event) {
final int buttonIndex = Arrays.asList(buttonValue.getValues()).indexOf(buttonValue.get());
if(modeValue.equals("AAC3.5.0")) {
freezeTimer.update();
if(freeze && freezeTimer.hasTimePassed(40)) {
freezeTimer.reset();
freeze = false;
setState(false);
}
if(!flyTimer.hasTimePassed(60)) {
flyTimer.update();
if(mc.thePlayer.onGround) {
MovementUtils.INSTANCE.jump(true, false, 0.42);
}else{
MovementUtils.INSTANCE.forward(zitter ? -0.21D : 0.21D);
zitter = !zitter;
}
hadGround = false;
return;
}
if(mc.thePlayer.onGround)
hadGround = true;
if(!hadGround)
return;
if(mc.thePlayer.onGround)
mc.thePlayer.setPositionAndUpdate(mc.thePlayer.posX, mc.thePlayer.posY + 0.2D, mc.thePlayer.posZ);
final float vanillaSpeed = 2F;
mc.thePlayer.capabilities.isFlying = false;
mc.thePlayer.motionY = 0;
mc.thePlayer.motionX = 0;
mc.thePlayer.motionZ = 0;
if(mc.gameSettings.keyBindJump.isKeyDown())
mc.thePlayer.motionY += vanillaSpeed;
if(mc.gameSettings.keyBindSneak.isKeyDown())
mc.thePlayer.motionY -= vanillaSpeed;
MovementUtils.INSTANCE.strafe(vanillaSpeed);
if(Mouse.isButtonDown(buttonIndex) && !doTeleport) {
mc.thePlayer.setPositionAndUpdate(mc.thePlayer.posX, mc.thePlayer.posY - 11, mc.thePlayer.posZ);
disableLogger = true;
packets.forEach(packet -> mc.getNetHandler().addToSendQueue(packet));
freezeTimer.reset();
freeze = true;
}
doTeleport = Mouse.isButtonDown(buttonIndex);
return;
}
if(mc.currentScreen == null && Mouse.isButtonDown(buttonIndex) && delay <= 0) {
endPos = objectPosition.getBlockPos();
if(Objects.requireNonNull(BlockUtils.getBlock(endPos)).getMaterial() == Material.air) {
endPos = null;
return;
}
alert("§7[§8§lTeleport§7] §3Position was set to §8" + endPos.getX() + "§3, §8" + ((Objects.requireNonNull(BlockUtils.getBlock(objectPosition.getBlockPos())).getCollisionBoundingBox(mc.theWorld, objectPosition.getBlockPos(), Objects.requireNonNull(BlockUtils.getBlock(objectPosition.getBlockPos())).getDefaultState()) == null ? endPos.getY() + Objects.requireNonNull(BlockUtils.getBlock(endPos)).getBlockBoundsMaxY() : Objects.requireNonNull(BlockUtils.getBlock(objectPosition.getBlockPos())).getCollisionBoundingBox(mc.theWorld, objectPosition.getBlockPos(), Objects.requireNonNull(BlockUtils.getBlock(objectPosition.getBlockPos())).getDefaultState()).maxY) + fixedY) + "§3, §8" + endPos.getZ());
delay = 6;
endX = (double) endPos.getX() + 0.5D;
endY = (double) endPos.getY() + 1.0D;
endZ = (double) endPos.getZ() + 0.5D;
}
if(delay > 0)
--delay;
if(endPos != null) {
switch(modeValue.get().toLowerCase()) {
case "blink":
if(mc.thePlayer.isSneaking() || !needSneak.get()) {
// Sneak
mc.getNetHandler().addToSendQueue(new C0BPacketEntityAction(mc.thePlayer, Action.STOP_SNEAKING));
// Teleport
PathUtils.findBlinkPath(endX, endY, endZ).forEach(vector3d -> {
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(vector3d.xCoord, vector3d.yCoord, vector3d.zCoord, true));
mc.thePlayer.setPosition(endX, endY, endZ);
});
// Sneak
mc.getNetHandler().addToSendQueue(new C0BPacketEntityAction(mc.thePlayer, Action.START_SNEAKING));
// Notify
alert("§7[§8§lTeleport§7] §3You were teleported to §8" + endX + "§3, §8" + endY + "§3, §8" + endZ);
endPos=null;
}
break;
case "flag":
if(mc.thePlayer.isSneaking() || !needSneak.get()) {
// Sneak
mc.getNetHandler().addToSendQueue(new C0BPacketEntityAction(mc.thePlayer, Action.STOP_SNEAKING));
// Teleport
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(endX, endY, endZ, true));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY + 5D, mc.thePlayer.posZ, true));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(endX, endY, endZ, true));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX + 0.5D, mc.thePlayer.posY, mc.thePlayer.posZ + 0.5D, true));
MovementUtils.INSTANCE.forward(0.04D);
// Sneak
mc.getNetHandler().addToSendQueue(new C0BPacketEntityAction(mc.thePlayer, Action.START_SNEAKING));
// Notify
alert("§7[§8§lTeleport§7] §3You were teleported to §8" + endX + "§3, §8" + endY + "§3, §8" + endZ);
endPos = null;
}
break;
case "bwrel":
if(mc.thePlayer.isSneaking() || !needSneak.get()) {
mc.thePlayer.setPosition(mc.thePlayer.posX, mc.thePlayer.posY + 9.2507838107252498276, mc.thePlayer.posZ);
mc.thePlayer.motionY = 1.042026214225532854;
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(endX, endY, endZ, true));
}
break;
case "rewinside":
mc.thePlayer.motionY = 0.1;
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(endX, endY, endZ, true));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY + 0.6D, mc.thePlayer.posZ, true));
if((int) mc.thePlayer.posX == endX && (int) mc.thePlayer.posY == endY && (int) mc.thePlayer.posZ == endZ) {
alert("§7[§8§lTeleport§7] §3You were teleported to §8" + endX + "§3, §8" + endY + "§3, §8" + endZ);
endPos = null;
}else
alert("§7[§8§lTeleport§7] §3Teleport try...");
break;
case "oldrewinside":
mc.thePlayer.motionY = 0.1;
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(endX, endY, endZ, true));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(endX, endY, endZ, true));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
if((int) mc.thePlayer.posX == endX && (int) mc.thePlayer.posY == endY && (int) mc.thePlayer.posZ == endZ) {
alert("§7[§8§lTeleport§7] §3You were teleported to §8" + endX + "§3, §8" + endY + "§3, §8" + endZ);
endPos = null;
}else
alert("§7[§8§lTeleport§7] §3Teleport try...");
MovementUtils.INSTANCE.forward(0.04D);
break;
case "minesucht":
if(!mc.thePlayer.isSneaking() && needSneak.get())
break;
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(endX, endY, endZ, true));
alert("§7[§8§lTeleport§7] §3You were teleported to §8" + endX + "§3, §8" + endY + "§3, §8" + endZ);
endPos=null;
break;
case "tp":
if(!mc.thePlayer.isSneaking() && needSneak.get())
break;
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(endX, endY, endZ, true));
mc.thePlayer.setPosition(endX, endY, endZ);
alert("§7[§8§lTeleport§7] §3You were teleported to §8" + endX + "§3, §8" + endY + "§3, §8" + endZ);
endPos=null;
break;
case "karhu":
if(!mc.thePlayer.isSneaking() && needSneak.get())
break;
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(endX, endY, endZ, false));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, false));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(endX, endY, endZ, false));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, false));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(endX, endY, endZ, false));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, false));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(endX, endY, endZ, false));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, false));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(endX, endY, endZ, false));
mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, false));
mc.thePlayer.setPosition(endX, endY, endZ);
alert("§7[§8§lTeleport§7] §3You were teleported to §8" + endX + "§3, §8" + endY + "§3, §8" + endZ);
endPos=null;
break;
}
}
}
@EventTarget
public void onRender3D(final Render3DEvent event) {
if(modeValue.equals("AAC3.5.0"))
return;
final Vec3 lookVec = new Vec3(mc.thePlayer.getLookVec().xCoord * 300, mc.thePlayer.getLookVec().yCoord * 300, mc.thePlayer.getLookVec().zCoord * 300);
final Vec3 posVec = new Vec3(mc.thePlayer.posX, mc.thePlayer.posY + 1.62, mc.thePlayer.posZ);
objectPosition = mc.thePlayer.worldObj.rayTraceBlocks(posVec, posVec.add(lookVec), false, ignoreNoCollision.get(), false);
if (objectPosition == null || objectPosition.getBlockPos() == null)
return;
final BlockPos belowBlockPos = new BlockPos(objectPosition.getBlockPos().getX(), objectPosition.getBlockPos().getY() - 1, objectPosition.getBlockPos().getZ());
fixedY = BlockUtils.getBlock(objectPosition.getBlockPos()) instanceof BlockFence ? (mc.theWorld.getCollidingBoundingBoxes(mc.thePlayer, mc.thePlayer.getEntityBoundingBox().offset(objectPosition.getBlockPos().getX() + 0.5D - mc.thePlayer.posX, objectPosition.getBlockPos().getY() + 1.5D - mc.thePlayer.posY, objectPosition.getBlockPos().getZ() + 0.5D - mc.thePlayer.posZ)).isEmpty() ? 0.5D : 0D) : BlockUtils.getBlock(belowBlockPos) instanceof BlockFence ? (!mc.theWorld.getCollidingBoundingBoxes(mc.thePlayer, mc.thePlayer.getEntityBoundingBox().offset(objectPosition.getBlockPos().getX() + 0.5D - mc.thePlayer.posX, objectPosition.getBlockPos().getY() + 0.5D - mc.thePlayer.posY, objectPosition.getBlockPos().getZ() + 0.5D - mc.thePlayer.posZ)).isEmpty() || Objects.requireNonNull(BlockUtils.getBlock(objectPosition.getBlockPos())).getCollisionBoundingBox(mc.theWorld, objectPosition.getBlockPos(), Objects.requireNonNull(BlockUtils.getBlock(objectPosition.getBlockPos())).getDefaultState()) == null ? 0D : 0.5D - Objects.requireNonNull(BlockUtils.getBlock(objectPosition.getBlockPos())).getBlockBoundsMaxY()) : BlockUtils.getBlock(objectPosition.getBlockPos()) instanceof BlockSnow ? Objects.requireNonNull(BlockUtils.getBlock(objectPosition.getBlockPos())).getBlockBoundsMaxY() - 0.125D : 0D;
final int x = objectPosition.getBlockPos().getX();
final double y = (Objects.requireNonNull(BlockUtils.getBlock(objectPosition.getBlockPos())).getCollisionBoundingBox(mc.theWorld, objectPosition.getBlockPos(), Objects.requireNonNull(BlockUtils.getBlock(objectPosition.getBlockPos())).getDefaultState()) == null ? objectPosition.getBlockPos().getY() + Objects.requireNonNull(BlockUtils.getBlock(objectPosition.getBlockPos())).getBlockBoundsMaxY() : Objects.requireNonNull(BlockUtils.getBlock(objectPosition.getBlockPos())).getCollisionBoundingBox(mc.theWorld, objectPosition.getBlockPos(), Objects.requireNonNull(BlockUtils.getBlock(objectPosition.getBlockPos())).getDefaultState()).maxY) - 1D + fixedY;
final int z = objectPosition.getBlockPos().getZ();
if(!(BlockUtils.getBlock(objectPosition.getBlockPos()) instanceof BlockAir)) {
final RenderManager renderManager = mc.getRenderManager();
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glLineWidth(2F);
glDisable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
glDepthMask(false);
RenderUtils.glColor(modeValue.equals("minesucht") && mc.thePlayer.getPosition().getY() != y + 1 ? new Color(255, 0, 0, 90) : !mc.theWorld.getCollidingBoundingBoxes(mc.thePlayer, mc.thePlayer.getEntityBoundingBox().offset(x + 0.5D - mc.thePlayer.posX, y + 1D - mc.thePlayer.posY, z + 0.5D - mc.thePlayer.posZ)).isEmpty() ? new Color(255, 0, 0, 90) : new Color(0, 255, 0, 90));
RenderUtils.drawFilledBox(new AxisAlignedBB(x - renderManager.renderPosX, (y + 1) - renderManager.renderPosY, z - renderManager.renderPosZ, x - renderManager.renderPosX + 1.0D, y + 1.2D - renderManager.renderPosY, z - renderManager.renderPosZ + 1.0D));
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glDepthMask(true);
glDisable(GL_BLEND);
RenderUtils.renderNameTag(Math.round(mc.thePlayer.getDistance(x + 0.5D, y + 1D, z + 0.5D)) + "m", x + 0.5, y + 1.7, z + 0.5);
GlStateManager.resetColor();
}
}
@EventTarget
public void onMove(final MoveEvent event) {
if (modeValue.equals("aac3.5.0") && freeze) {
event.zeroXZ();
}
}
@EventTarget
public void onPacket(final PacketEvent event) {
final Packet<?> packet = event.getPacket();
if(disableLogger)
return;
if(packet instanceof C03PacketPlayer) {
final C03PacketPlayer packetPlayer = (C03PacketPlayer) packet;
switch(modeValue.get().toLowerCase()) {
case "spoof":
if(endPos == null)
break;
packetPlayer.x = endPos.getX() + 0.5D;
packetPlayer.y = endPos.getY() + 1;
packetPlayer.z = endPos.getZ() + 0.5D;
mc.thePlayer.setPosition(endPos.getX() + 0.5D, endPos.getY() + 1, endPos.getZ() + 0.5D);
break;
case "aac3.5.0":
if(!flyTimer.hasTimePassed(60))
return;
event.cancelEvent();
if(!(packet instanceof C03PacketPlayer.C04PacketPlayerPosition) && !(packet instanceof C03PacketPlayer.C06PacketPlayerPosLook))
return;
packets.add(packet);
break;
}
}
}
@Override
public String getTag() {
return modeValue.get();
}
}
| 0 | 0.93145 | 1 | 0.93145 | game-dev | MEDIA | 0.884485 | game-dev | 0.984561 | 1 | 0.984561 |
GauntletGames-2086/D6-Jokers | 1,167 | Objects/D6 Sides/d6_side LuaList/Generation/Demolish.lua | local d6_side_info = SMODS.D6_Side({
key = "demolish_side",
loc_txt = {},
config = {consumable_slots_removed = 0},
pos = {x=7, y=0},
add_to_deck = function(self, card, from_debuff, other, d6_side)
G.E_MANAGER:add_event(Event({
func = function()
d6_side.extra.consumable_slots_removed = G.consumeables.config.card_limit
for i, v in ipairs(G.consumeables.cards) do
v:start_dissolve(nil, i ~= 1, 1.6)
if v.edition and v.edition.card_limit then
d6_side.extra.consumable_slots_removed = d6_side.extra.consumable_slots_removed - 1
end
end
G.consumeables:change_size(-d6_side.extra.consumable_slots_removed or 0)
return true end
}))
end,
remove_from_deck = function(self, card, from_debuff, other, d6_side)
G.E_MANAGER:add_event(Event({
func = function()
G.consumeables:change_size(d6_side.extra.consumable_slots_removed or 0)
return true end
}))
end,
register = function(self, order)
if order and order == self.order then
SMODS.GameObject.register(self)
end
end,
order = 5,
})
D6_JokerDisplay.D6_Side_Definitions[d6_side_info.key] = {
text = {},
}
return d6_side_info | 0 | 0.917023 | 1 | 0.917023 | game-dev | MEDIA | 0.870634 | game-dev | 0.966434 | 1 | 0.966434 |
ericraio/vanilla-wow-addons | 15,370 | c/CT_BuffMod/CT_BuffFrame.lua | CT_AddMovable("CT_BuffMod_Drag", CT_BUFFMOD_MOVABLE_BUFFBAR, "BOTTOMLEFT", "BOTTOMLEFT", "MinimapCluster", 10, -20, function(status)
if ( status ) then
CT_BuffMod_Drag:Show()
else
CT_BuffMod_Drag:Hide();
end
end, BuffModResetFunction);
CT_ExpireBuffs = { };
CT_BuffNames = { };
CT_LastExpiredBuffs = { };
CT_PlaySound = 0;
local CT_UsingTooltip = 0;
CT_BuffMod_BuffSides = "RIGHT";
CT_ShowDuration = 1;
CT_ShowExpire = 1;
CT_ShowRed = 0;
-- Buffs not to recast
CT_BuffMod_NoRecastBuffs = {
["Mind Control"] = 1
};
function CT_BuffFrame_OnLoad()
MinBuffDurationExpireMessage = 51; -- Never display an expire message if the buff duration is less than this.
ExpireMessageTime = 15; -- How long before the buff expires to display the expire message.
ExpireMessageColors = { };
ExpireMessageColors["r"] = 1.0;
ExpireMessageColors["g"] = 0.0;
ExpireMessageColors["b"] = 0.0;
ExpireMessageFrame = DEFAULT_CHAT_FRAME; -- The frame in which to display the expire message.
BuffStartFlashTime = 16; -- How long before the buff expires to start flashing.
BuffFlashOn = 0.50; -- How long to flash.
BuffFlashOff = 0.50; -- How long between each flash.
BuffMinOpacity = 0.30; -- Minimum level of opacity.
BuffFlashState = 0;
BuffFlashTime = 0;
BuffFlashUpdateTime = 0;
BuffFrame:Hide();
CT_BuffFrame:Show();
end
function CT_BuffFrame_OnUpdate(elapsed)
if ( BuffFlashUpdateTime > 0 ) then
BuffFlashUpdateTime = BuffFlashUpdateTime - elapsed;
else
BuffFlashUpdateTime = BuffFlashUpdateTime + TOOLTIP_UPDATE_TIME;
end
BuffFlashTime = BuffFlashTime - elapsed;
if ( BuffFlashTime < 0 ) then
local overtime = -BuffFlashTime;
if ( BuffFlashState == 1 ) then
BuffFlashState = 0;
BuffFlashTime = BuffFlashOff;
else
BuffFlashState = 1;
BuffFlashTime = BuffFlashOn;
end
if ( overtime < BuffFlashTime ) then
BuffFlashTime = BuffFlashTime - overtime;
end
end
end
function CT_BuffIsDebuff(id)
for z=0, 23, 1 do
local dbIndex, dbTemp = GetPlayerBuff(z, "HARMFUL");
if ( dbIndex == -1 ) then return 0; end
if ( dbIndex == id ) then
return 1;
end
end
return 0;
end
function CT_GetBuffName(unit, i, filt)
CT_UsingTooltip = 1;
local filter;
if ( not filt ) then
filter = "HELPFUL|HARMFUL";
else
filter = filt;
end
local buffIndex, untilCancelled = GetPlayerBuff(i, filter);
local buff;
if ( buffIndex < 24 ) then
buff = buffIndex;
if (buff == -1) then
buff = nil;
end
end
if (buff) then
local tooltip = BTooltip;
if (unit == "player" and tooltip ) then
tooltip:SetPlayerBuff(buffIndex);
end
local tooltiptext = getglobal("BTooltipTextLeft1");
if ( tooltiptext ) then
local name = tooltiptext:GetText();
if ( name ~= nil ) then
CT_UsingTooltip = 0;
return name;
end
end
end
CT_UsingTooltip = 0;
return nil;
end
function CT_BuffButton_Update()
local buffIndex, untilCancelled = GetPlayerBuff(this:GetID(), "HELPFUL|HARMFUL");
this.buffIndex = buffIndex;
this.untilCancelled = untilCancelled;
if ( buffIndex < 0 ) then
this:Hide();
return;
else
this:SetAlpha(1.0);
this:Show();
end
local icon = getglobal(this:GetName().."Icon");
icon:SetTexture(GetPlayerBuffTexture(buffIndex, "HELPFUL|HARMFUL"));
if ( GameTooltip:IsOwned(this) ) then
GameTooltip:SetPlayerBuff(buffIndex, "HELPFUL|HARMFUL");
end
local name = CT_GetBuffName("player", this:GetID(), "HELPFUL|HARMFUL");
if ( name ) then
getglobal(this:GetName() .. "DescribeText"):SetText( name );
end
CT_BuffNames[this:GetID()] = nil;
end
function CT_BuffButton_OnLoad()
getglobal(this:GetName() .. "DurationText"):SetTextColor(1, 1, 0);
local bIndex, untilCancelled = GetPlayerBuff(this:GetID(), "HELPFUL|HARMFUL");
if ( CT_BuffIsDebuff( temp ) == 1 ) then
if ( CT_ShowRed == 1 ) then
getglobal(this:GetName() .. "DescribeText"):SetTextColor(1, 0, 0);
else
getglobal(this:GetName() .. "DescribeText"):SetTextColor(1, 1, 0);
end
getglobal(this:GetName() .. "Debuff"):Show();
else
getglobal(this:GetName() .. "DescribeText"):SetTextColor(1, 1, 0);
getglobal(this:GetName() .. "Debuff"):Hide();
end
if ( untilCancelled == 1 or CT_ShowDuration == 0 ) then
getglobal(this:GetName() .. "DurationText"):SetText("");
end
CT_BuffButton_Update();
this:RegisterForClicks("RightButtonUp");
this:RegisterEvent("PLAYER_AURAS_CHANGED");
local descript = getglobal(this:GetName() .. "DescribeText");
if ( descript ) then descript:Show(); end
end
function CT_BuffButton_OnEvent(event)
CT_BuffButton_Update();
end
function CT_GetStringTime(seconds)
local str = "";
if ( seconds >= 60 ) then
local minutes = ceil(seconds / 60);
str = minutes .. " " .. CT_BUFFMOD_MINUTE;
if ( minutes > 1 ) then
str = minutes .. " " .. CT_BUFFMOD_MINUTES;
else
str = minutes .. " " .. CT_BUFFMOD_MINUTE;
end
else
if ( seconds > 1 ) then
str = floor(seconds) .. " " .. CT_BUFFMOD_SECONDS;
else
str = floor(seconds) .. " " .. CT_BUFFMOD_SECOND;
end
end
return str;
end
function CT_BuffButton_OnUpdate(elapsed)
local buffname;
local bIndex, untilCancelled = GetPlayerBuff( this:GetID(), "HELPFUL|HARMFUL" );
local isDebuff = CT_BuffIsDebuff(bIndex);
local buffnum = GetPlayerBuffApplications(bIndex)
if ( buffnum > 1 ) then
getglobal(this:GetName() .. "Count"):SetText(buffnum);
else
getglobal(this:GetName() .. "Count"):SetText("");
end
if ( isDebuff == 1 ) then
if ( CT_ShowRed == 1 ) then
getglobal(this:GetName() .. "DescribeText"):SetTextColor(1, 0, 0);
else
getglobal(this:GetName() .. "DescribeText"):SetTextColor(1, 1, 0);
end
getglobal(this:GetName() .. "Debuff"):Show();
else
getglobal(this:GetName() .. "DescribeText"):SetTextColor(1, 1, 0);
getglobal(this:GetName() .. "Debuff"):Hide();
end
if ( untilCancelled == 1 ) then
getglobal(this:GetName() .. "DurationText"):SetText("");
return;
end
if ( not CT_BuffNames[this:GetID()] ) then
buffname = CT_GetBuffName( "player", this:GetID() );
CT_BuffNames[this:GetID()] = buffname;
else
buffname = CT_BuffNames[this:GetID()];
end
local timeLeft = GetPlayerBuffTimeLeft(bIndex);
local buffAlphaValue;
if ( timeLeft >= 1 and CT_ShowDuration == 1 ) then
getglobal(this:GetName() .. "DurationText"):SetText(CT_GetStringTime(timeLeft));
else
getglobal(this:GetName() .. "DurationText"):SetText("");
end
if ( floor(timeLeft) == MinBuffDurationExpireMessage and not CT_ExpireBuffs[buffname] ) then
CT_ExpireBuffs[buffname] = 1;
end
if ( ceil(timeLeft) == ExpireMessageTime and CT_ExpireBuffs[buffname] and CT_BuffIsDebuff(bIndex) == 0 ) then
if ( CT_ShowExpire == 1 and not CT_BuffMod_NoRecastBuffs[buffname]) then
if ( CT_PlaySound == 1 ) then
PlaySound("TellMessage");
end
CT_BuffMod_AddToQueue(buffname);
local message;
if ( CT_PlayerSpells[buffname] and GetBindingKey("CT_RECASTBUFF") ) then
message = format(ExpireMessageRecastString, buffname, GetBindingText(GetBindingKey("CT_RECASTBUFF"), "KEY_"));
else
message = format(ExpireMessageString, buffname);
end
ExpireMessageFrame:AddMessage(message, ExpireMessageColors["r"], ExpireMessageColors["g"], ExpireMessageColors["b"]);
end
CT_ExpireBuffs[buffname] = nil;
CT_BuffNames[this:GetID()] = nil;
end
if ( timeLeft < BuffStartFlashTime ) then
if ( BuffFlashState == 1 ) then
buffAlphaValue = (BuffFlashOn - BuffFlashTime) / BuffFlashOn;
buffAlphaValue = buffAlphaValue * (1 - BuffMinOpacity) + BuffMinOpacity;
else
buffAlphaValue = BuffFlashTime / BuffFlashOn;
buffAlphaValue = (buffAlphaValue * (1 - BuffMinOpacity)) + BuffMinOpacity;
this:SetAlpha(BuffFlashTime / BuffFlashOn);
end
this:SetAlpha(buffAlphaValue);
else
this:SetAlpha(1.0);
end
if ( BuffFlashUpdateTime > 0 ) then
return;
end
if ( GameTooltip:IsOwned(this) ) then
GameTooltip:SetPlayerBuff(bIndex);
end
end
function CT_BuffButton_OnClick()
CancelPlayerBuff(this.buffIndex);
end
function CT_Buffs_SwapSides(onLoad)
local i;
for i = 0, 23, 1 do
getglobal("CT_BuffButton" .. i .. "DescribeText"):ClearAllPoints();
getglobal("CT_BuffButton" .. i .. "DurationText"):ClearAllPoints();
if ( CT_BuffMod_BuffSides == "RIGHT" or onLoad ) then
getglobal("CT_BuffButton" .. i .. "DescribeText"):SetPoint("RIGHT", "CT_BuffButton" .. i, "LEFT", -8, 7);
getglobal("CT_BuffButton" .. i .. "DurationText"):SetPoint("RIGHT", "CT_BuffButton" .. i, "LEFT", -8, -7);
elseif ( CT_BuffMod_BuffSides == "LEFT" ) then
getglobal("CT_BuffButton" .. i .. "DescribeText"):SetPoint("LEFT", "CT_BuffButton" .. i, "LEFT", 40, 7);
getglobal("CT_BuffButton" .. i .. "DurationText"):SetPoint("LEFT", "CT_BuffButton" .. i, "LEFT", 40, -7);
end
end
if ( onLoad ) then return; end
if ( CT_BuffMod_BuffSides == "LEFT" ) then
CT_BuffMod_BuffSides = "RIGHT";
else
CT_BuffMod_BuffSides = "LEFT";
end
end
expirefunction = function(modId, count)
local val = CT_Mods[modId]["modValue"];
if ( val == "1min" ) then
CT_Mods[modId]["modValue"] = "Off";
if ( count ) then count:SetText("Off"); end
CT_ShowExpire = 0;
CT_Print(CT_BUFFMOD_ON_EXPIRE, 1.0, 1.0, 0.0);
else
CT_ShowExpire = 1;
if ( val == "15sec" ) then
CT_Mods[modId]["modValue"] = "1min";
if ( count ) then count:SetText("1min"); end
CT_Print(CT_BUFFMOD_MIN_EXPIRE, 1.0, 1.0, 0.0);
ExpireMessageTime = 60;
MinBuffDurationExpireMessage = 120;
elseif ( val == "Off" ) then
CT_Mods[modId]["modValue"] = "15sec";
if ( count ) then count:SetText("15sec"); end
CT_Print(CT_BUFFMOD_SEC_EXPIRE, 1.0, 1.0, 0.0);
ExpireMessageTime = 15;
MinBuffDuratioonExpireMessage = 51;
end
end
end
durationfunction = function(modId)
if ( CT_ShowDuration == 1 ) then
CT_ShowDuration = 0;
CT_SetModStatus(modId, "off");
CT_Print(CT_BUFFMOD_OFF_DURATION, 1.0, 1.0, 0.0);
else
CT_ShowDuration = 1;
CT_SetModStatus(modId, "on");
CT_Print(CT_BUFFMOD_ON_DURATION, 1.0, 1.0, 0.0);
end
end
expireinitfunction = function(modId)
local val = CT_Mods[modId]["modValue"];
if ( val == "Off" ) then
CT_ShowExpire = 0;
else
CT_ShowExpire = 1;
if ( val == "1min" ) then
ExpireMessageTime = 60;
MinBuffDurationExpireMessage = 120;
elseif ( val == "15sec" ) then
ExpireMessageTime = 15;
MinBuffDurationExpireMessage = 51;
end
end
end
durationinitfunction = function(modId)
local val = CT_Mods[modId]["modStatus"];
if ( val == "on" ) then
CT_ShowDuration = 1;
else
CT_ShowDuration = 0;
end
end
debuffnamesfunction = function(modId)
local val = CT_Mods[modId]["modStatus"];
if ( val == "on" ) then
CT_ShowRed = 1;
CT_Print(CT_BUFFMOD_ON_DEBUFF, 1.0, 1.0, 0.0);
else
CT_ShowRed = 0;
CT_Print(CT_BUFFMOD_OFF_DEBUFF, 1.0, 1.0, 0.0);
end
end
debuffnamesinitfunction = function(modId)
local val = CT_Mods[modId]["modStatus"];
if ( val == "on" ) then
CT_ShowRed = 1;
else
CT_ShowRed = 0;
end
end
lockframefunction = function(modId)
local val = CT_Mods[modId]["modStatus"];
if ( val == "off" ) then
CT_Print(CT_BUFFMOD_OFF_LOCK, 1, 1, 0);
CT_BuffMod_Drag:Hide();
else
CT_Print(CT_BUFFMOD_ON_LOCK, 1, 1, 0);
CT_BuffMod_Drag:Show();
end
end
lockframeinitfunction = function(modId)
local val = CT_Mods[modId]["modStatus"];
if ( val == "off" ) then
CT_BuffMod_Drag:Hide();
else
CT_BuffMod_Drag:Show();
end
end
buffmodfunction = function(modId)
local val = CT_Mods[modId]["modStatus"];
if ( val == "off" ) then
CT_Print(CT_BUFFMOD_OFF_TOGGLE, 1, 1, 0);
CT_BuffFrame:Hide();
BuffFrame:Show();
if ( TemporaryEnchantFrame ) then
TemporaryEnchantFrame:Show();
end
else
CT_Print(CT_BUFFMOD_ON_TOGGLE, 1, 1, 0);
CT_BuffFrame:Show();
BuffFrame:Hide();
if ( TemporaryEnchantFrame and CT_ItemBuffFrame ) then
TemporaryEnchantFrame:Hide();
elseif ( TemporaryEnchantFrame ) then
TemporaryEnchantFrame:Show();
end
end
end
buffmodinitfunction = function(modId)
local val = CT_Mods[modId]["modStatus"];
if ( val == "off" ) then
CT_BuffFrame:Hide();
BuffFrame:Show();
if ( TemporaryEnchantFrame ) then
TemporaryEnchantFrame:Show();
end
else
CT_BuffFrame:Show();
BuffFrame:Hide();
if ( TemporaryEnchantFrame and CT_ItemBuffFrame ) then
TemporaryEnchantFrame:Hide();
elseif ( TemporaryEnchantFrame ) then
TemporaryEnchantFrame:Show();
end
end
end
CT_RegisterMod(CT_BUFFMOD_MODNAME_TOGGLE, CT_BUFFMOD_MODNAME_SUB_TOGGLE, 4, "Interface\\Icons\\Spell_Holy_Renew", CT_BUFFMOD_MODNAME_TOOLTIP_TOGGLE, "on", nil, buffmodfunction, buffmodinitfunction);
CT_RegisterMod(CT_BUFFMOD_MODNAME_EXPIRE, CT_BUFFMOD_MODNAME_SUB_EXPIRE, 4, "Interface\\Icons\\INV_Misc_Note_03", CT_BUFFMOD_MODNAME_TOOLTIP_EXPIRE, "switch", "15sec", expirefunction, expireinitfunction);
CT_RegisterMod(CT_BUFFMOD_MODNAME_DURATION, CT_BUFFMOD_MODNAME_SUB_DURATION, 4, "Interface\\Icons\\INV_Misc_PocketWatch_01", CT_BUFFMOD_MODNAME_TOOLTIP_DURATION, "on", nil, durationfunction, durationinitfunction);
CT_RegisterMod(CT_BUFFMOD_MODNAME_DEBUFF, CT_BUFFMOD_MODNAME_SUB_DEBUFF, 4, "Interface\\Icons\\Spell_Holy_SealOfSacrifice", CT_BUFFMOD_MODNAME_TOOLTIP_DEBUFF, "off", nil, debuffnamesfunction, debuffnamesinitfunction);
function CT_BuffMod_RecastLastBuff()
local buff = CT_BuffMod_GetExpiredBuff();
if ( buff and CT_PlayerSpells[buff] ) then
if ( CT_PlayerSpells[buff] ) then
CT_BuffMod_LastCastSpell = buff;
CT_BuffMod_LastCast = GetTime();
if ( UnitExists("target") and UnitIsFriend("player", "target") ) then
TargetUnit("player");
end
CastSpell(CT_PlayerSpells[buff]["spell"], CT_PlayerSpells[buff]["tab"]+1);
if ( SpellIsTargeting() and SpellCanTargetUnit("player") ) then
SpellTargetUnit("player");
end
end
end
end
function CT_BuffButton_OnEnter()
if ( this:GetCenter() < UIParent:GetCenter() ) then
GameTooltip:SetOwner(this, "ANCHOR_RIGHT");
else
GameTooltip:SetOwner(this, "ANCHOR_LEFT");
end
GameTooltip:SetPlayerBuff(this.buffIndex);
end
function CT_BuffMod_AddToQueue(name)
local hKey = 0;
local hVal = 0;
for key, val in CT_LastExpiredBuffs do
if ( val > hVal ) then
hKey = key; hVal = val;
end
end
if ( hKey == name ) then return; end
CT_LastExpiredBuffs[name] = hVal+1;
end
function CT_BuffMod_GetExpiredBuff()
local hKey = 0;
local hVal = 0;
for key, val in CT_LastExpiredBuffs do
if ( val > hVal ) then
hKey = key; hVal = val;
end
end
if ( hKey ~= 0 and hVal ~= 0 ) then
CT_LastExpiredBuffs[hKey] = nil;
return hKey;
else
return nil;
end
end
function CT_BuffMod_OnEvent(event)
if ( CT_BuffMod_LastCast and (GetTime()-CT_BuffMod_LastCast) <= 0.1 ) then
CT_BuffMod_AddToQueue(CT_BuffMod_LastCastSpell);
CT_BuffMod_LastCast = nil;
CT_BuffMod_LastCastSpell = nil;
end
end
function BuffModResetFunction()
if ( CT_BuffMod_BuffSides == "LEFT" ) then
CT_Buffs_SwapSides();
end
end
ChirpFunction = function(modId)
local val = CT_Mods[modId]["modStatus"];
if ( val == "off" ) then
CT_Print(CT_BUFFMOD_OFF_CHIRP, 1, 1, 0);
CT_PlaySound = 0;
else
CT_Print(CT_BUFFMOD_ON_CHIRP, 1, 1, 0);
CT_PlaySound = 1;
end
end
ChirpInitFunction = function(modId)
local val = CT_Mods[modId]["modStatus"];
if ( val == "off" ) then
CT_PlaySound = 0;
else
CT_PlaySound = 1;
end
end
CT_RegisterMod(CT_BUFFMOD_MODNAME_SOUND, CT_BUFFMOD_SUB_SOUND, 4, "Interface\\Icons\\INV_Misc_Bell_01", CT_BUFFMOD_TOOLTIP_SOUND, "off", nil, ChirpFunction, ChirpInitFunction); | 0 | 0.804831 | 1 | 0.804831 | game-dev | MEDIA | 0.894234 | game-dev | 0.885237 | 1 | 0.885237 |
Aizistral-Studios/Enigmatic-Legacy | 5,087 | src/main/java/com/aizistral/enigmaticlegacy/items/WormholePotion.java | package com.aizistral.enigmaticlegacy.items;
import java.util.List;
import javax.annotation.Nullable;
import com.aizistral.enigmaticlegacy.EnigmaticLegacy;
import com.aizistral.enigmaticlegacy.crafting.BindToPlayerRecipe.IBound;
import com.aizistral.enigmaticlegacy.helpers.ItemLoreHelper;
import com.aizistral.enigmaticlegacy.helpers.ItemNBTHelper;
import com.aizistral.enigmaticlegacy.items.generic.ItemBase;
import com.aizistral.enigmaticlegacy.packets.clients.PacketPortalParticles;
import com.aizistral.enigmaticlegacy.packets.clients.PacketRecallParticles;
import net.minecraft.ChatFormatting;
import net.minecraft.advancements.CriteriaTriggers;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.Rarity;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.UseAnim;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.PacketDistributor;
public class WormholePotion extends ItemBase implements IBound {
public WormholePotion() {
super(ItemBase.getDefaultProperties().stacksTo(1).rarity(Rarity.RARE));
}
@Override
@OnlyIn(Dist.CLIENT)
public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> list, TooltipFlag flagIn) {
if (Screen.hasShiftDown()) {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.wormholePotion1");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.wormholePotion2");
} else {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.holdShift");
}
if (ItemNBTHelper.verifyExistance(stack, "BoundPlayer")) {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.boundToPlayer", ChatFormatting.DARK_RED, ItemNBTHelper.getString(stack, "BoundPlayer", "Herobrine"));
}
}
@Override
public ItemStack finishUsingItem(ItemStack stack, Level worldIn, LivingEntity entityLiving) {
if (!(entityLiving instanceof Player))
return stack;
Player player = (Player) entityLiving;
if (player instanceof ServerPlayer) {
CriteriaTriggers.CONSUME_ITEM.trigger((ServerPlayer) player, stack);
}
Player receiver = this.getBoundPlayer(worldIn, stack);
if (!worldIn.isClientSide && receiver != null) {
Vec3 vec = receiver.position();
while (vec.distanceTo(receiver.position()) < 1.0D) {
vec = receiver.position().add((random.nextDouble() - 0.5D) * 4D, 0, (random.nextDouble() - 0.5D) * 4D);
}
worldIn.playSound(null, player.blockPosition(), SoundEvents.ENDERMAN_TELEPORT, SoundSource.PLAYERS, 1.0F, (float) (0.8F + (Math.random() * 0.2)));
EnigmaticLegacy.packetInstance.send(PacketDistributor.NEAR.with(() -> new PacketDistributor.TargetPoint(player.getX(), player.getY(), player.getZ(), 128, player.level().dimension())), new PacketPortalParticles(player.getX(), player.getY() + (player.getBbHeight() / 2), player.getZ(), 100, 1.25F, false));
player.teleportTo(vec.x, vec.y + 0.25, vec.z);
worldIn.playSound(null, player.blockPosition(), SoundEvents.ENDERMAN_TELEPORT, SoundSource.PLAYERS, 1.0F, (float) (0.8F + (Math.random() * 0.2)));
EnigmaticLegacy.packetInstance.send(PacketDistributor.NEAR.with(() -> new PacketDistributor.TargetPoint(player.getX(), player.getY(), player.getZ(), 128, player.level().dimension())), new PacketRecallParticles(player.getX(), player.getY() + (player.getBbHeight() / 2), player.getZ(), 48, false));
}
if (!player.getAbilities().instabuild) {
stack.shrink(1);
if (stack.isEmpty())
return new ItemStack(Items.GLASS_BOTTLE);
player.getInventory().add(new ItemStack(Items.GLASS_BOTTLE));
}
return stack;
}
@Override
public int getUseDuration(ItemStack stack) {
return 32;
}
@Override
public UseAnim getUseAnimation(ItemStack stack) {
return UseAnim.DRINK;
}
@Override
public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand hand) {
ItemStack stack = player.getItemInHand(hand);
Player receiver = this.getBoundPlayer(world, stack);
if (receiver != null/* && receiver != player */) {
player.startUsingItem(hand);
return new InteractionResultHolder<>(InteractionResult.SUCCESS, stack);
}
return new InteractionResultHolder<>(InteractionResult.FAIL, stack);
}
@Override
@OnlyIn(Dist.CLIENT)
public boolean isFoil(ItemStack stack) {
return true;
}
}
| 0 | 0.912842 | 1 | 0.912842 | game-dev | MEDIA | 0.988763 | game-dev | 0.97443 | 1 | 0.97443 |
Eniripsa96/SkillAPI | 4,754 | src/com/sucy/skill/api/particle/SpigotParticles.java | package com.sucy.skill.api.particle;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Particle;
import java.util.Map;
/**
* SkillAPI © 2018
* com.sucy.skill.api.particle.SpigotParticles
*/
public class SpigotParticles {
private static boolean error = true;
public static void play(final Location loc, final String particle, final float dx, final float dy, final float dz, final int count, final float speed, final double distance) {
play(loc, particle, dx, dy, dz, count, speed, distance, null);
}
public static void playItem(final Location loc, final String particle, final float dx, final float dy, final float dz, final int count, final float speed, final double distance, final Material material) {
play(loc, particle, dx, dy, dz, count, speed, distance, material);
}
public static void playBlock(final Location loc, final String particle, final float dx, final float dy, final float dz, final int count, final float speed, final double distance, final Material material) {
play(loc, particle, dx, dy, dz, count, speed, distance, material);
}
private static void play(final Location loc, final String particle, final float dx, final float dy, final float dz, final int count, final float speed, final double distance, final Material material) {
final String key = particle.toLowerCase().replace('_', ' ');
final Particle effect = CONVERSION.get(key);
if (effect == null) return;
try {
final Object packet = com.sucy.skill.api.particle.Particle.make(
effect.name(), loc.getX(), loc.getY(), loc.getZ(), dx, dy, dz, speed, count, material, 0);
com.sucy.skill.api.particle.Particle.send(loc, ImmutableList.of(packet), distance);
} catch (final Exception ex) {
if (error) {
ex.printStackTrace();
error = false;
}
}
}
private static final Map<String, Particle> CONVERSION = ImmutableMap.<String, Particle>builder()
.put("angry villager", Particle.VILLAGER_ANGRY)
.put("barrier", Particle.BARRIER)
.put("block crack", Particle.BLOCK_CRACK)
.put("bubble", Particle.WATER_BUBBLE)
.put("cloud", Particle.CLOUD)
.put("crit", Particle.CRIT)
.put("damage indicator", Particle.DAMAGE_INDICATOR)
.put("death", Particle.SUSPENDED)
.put("death suspend", Particle.SUSPENDED_DEPTH)
.put("dragon breath", Particle.DRAGON_BREATH)
.put("drip lava", Particle.DRIP_LAVA)
.put("drip water", Particle.DRIP_WATER)
.put("enchantment table", Particle.ENCHANTMENT_TABLE)
.put("end rod", Particle.END_ROD)
.put("ender signal", Particle.PORTAL)
.put("explode", Particle.EXPLOSION_NORMAL)
.put("firework spark", Particle.FIREWORKS_SPARK)
.put("flame", Particle.FLAME)
.put("footstep", Particle.CLOUD)
.put("happy villager", Particle.VILLAGER_HAPPY)
.put("heart", Particle.HEART)
.put("huge explosion", Particle.EXPLOSION_HUGE)
.put("hurt", Particle.DAMAGE_INDICATOR)
.put("icon crack", Particle.ITEM_CRACK)
.put("instant spell", Particle.SPELL_INSTANT)
.put("large explode", Particle.EXPLOSION_LARGE)
.put("large smoke", Particle.SMOKE_LARGE)
.put("lava", Particle.LAVA)
.put("magic crit", Particle.CRIT_MAGIC)
.put("mob spell", Particle.SPELL_MOB)
.put("mob spell ambient", Particle.SPELL_MOB_AMBIENT)
.put("mobspawner flames", Particle.FLAME)
.put("note", Particle.NOTE)
.put("portal", Particle.PORTAL)
.put("potion break", Particle.SPELL)
.put("red dust", Particle.REDSTONE)
.put("sheep eat", Particle.MOB_APPEARANCE)
.put("slime", Particle.SLIME)
.put("smoke", Particle.SMOKE_NORMAL)
.put("snowball poof", Particle.SNOWBALL)
.put("snow shovel", Particle.SNOW_SHOVEL)
.put("spell", Particle.SPELL)
.put("splash", Particle.WATER_SPLASH)
.put("sweep attack", Particle.SWEEP_ATTACK)
.put("suspend", Particle.SUSPENDED)
.put("town aura", Particle.TOWN_AURA)
.put("water drop", Particle.WATER_DROP)
.put("water wake", Particle.WATER_WAKE)
.put("witch magic", Particle.SPELL_WITCH)
.put("wolf hearts", Particle.HEART)
.build();
}
| 0 | 0.787806 | 1 | 0.787806 | game-dev | MEDIA | 0.975242 | game-dev | 0.948836 | 1 | 0.948836 |
lumien231/Random-Things | 1,412 | src/main/java/lumien/randomthings/worldgen/BloodRoseFeature.java | package lumien.randomthings.worldgen;
import java.util.Random;
import java.util.function.Function;
import com.mojang.datafixers.Dynamic;
import lumien.randomthings.block.ModBlocks;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IWorld;
import net.minecraft.world.gen.ChunkGenerator;
import net.minecraft.world.gen.GenerationSettings;
import net.minecraft.world.gen.feature.FlowersFeature;
import net.minecraft.world.gen.feature.NoFeatureConfig;
public class BloodRoseFeature extends FlowersFeature
{
public BloodRoseFeature(Function<Dynamic<?>, ? extends NoFeatureConfig> p_i49876_1_)
{
super(p_i49876_1_);
}
@Override
public BlockState getRandomFlower(Random random, BlockPos pos)
{
return ModBlocks.BLOOD_ROSE.getDefaultState();
}
public boolean place(IWorld worldIn, ChunkGenerator<? extends GenerationSettings> generator, Random rand, BlockPos pos, NoFeatureConfig config)
{
BlockState blockstate = this.getRandomFlower(rand, pos);
int i = 0;
for (int j = 0; j < 8; ++j)
{
BlockPos blockpos = pos.add(rand.nextInt(8) - rand.nextInt(8), rand.nextInt(4) - rand.nextInt(4), rand.nextInt(8) - rand.nextInt(8));
if (worldIn.isAirBlock(blockpos) && blockpos.getY() < 255 && blockstate.isValidPosition(worldIn, blockpos))
{
worldIn.setBlockState(blockpos, blockstate, 2);
++i;
}
}
return i > 0;
}
}
| 0 | 0.66445 | 1 | 0.66445 | game-dev | MEDIA | 0.999183 | game-dev | 0.890919 | 1 | 0.890919 |
JDKDigital/productivemetalworks | 15,466 | src/main/java/cy/jdkdigital/productivemetalworks/client/screen/FoundryControllerScreen.java | package cy.jdkdigital.productivemetalworks.client.screen;
import com.mojang.datafixers.util.Pair;
import cy.jdkdigital.productivelib.util.FluidContainerUtil;
import cy.jdkdigital.productivemetalworks.ProductiveMetalworks;
import cy.jdkdigital.productivemetalworks.common.block.entity.FoundryControllerBlockEntity;
import cy.jdkdigital.productivemetalworks.common.datamap.FuelMap;
import cy.jdkdigital.productivemetalworks.common.menu.FoundryControllerContainer;
import cy.jdkdigital.productivemetalworks.network.MoveFoundryFluidData;
import cy.jdkdigital.productivemetalworks.recipe.ItemMeltingRecipe;
import cy.jdkdigital.productivemetalworks.registry.ModTags;
import cy.jdkdigital.productivemetalworks.util.*;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.FormattedCharSequence;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.RecipeHolder;
import net.neoforged.neoforge.fluids.FluidStack;
import net.neoforged.neoforge.network.PacketDistributor;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FoundryControllerScreen extends AbstractContainerScreen<FoundryControllerContainer>
{
private static final ResourceLocation GUI = ResourceLocation.fromNamespaceAndPath(ProductiveMetalworks.MODID, "textures/gui/container/foundry_controller.png");
private static final ResourceLocation SCROLLER_SPRITE = ResourceLocation.withDefaultNamespace("container/creative_inventory/scroller");
private boolean isScrolling;
private float scrollOffs;
private int fuelTanks = 0;
// Save fluids positions for tooltip and interaction
// tank index, <offset, height>
Map<Integer, Pair<Integer, Integer>> fluidPositions = new HashMap<>();
public FoundryControllerScreen(FoundryControllerContainer container, Inventory inv, Component titleIn) {
super(container, inv, titleIn);
this.imageWidth = 202;
}
@Override
protected void init() {
super.init();
if (this.menu.blockEntity.getMultiblockData() != null) {
this.menu.scrollTo(this.scrollOffs);
this.fuelTanks = (int) this.menu.blockEntity.getMultiblockData().peripherals().stream().filter(blockPos -> this.menu.blockEntity.getLevel().getBlockState(blockPos).is(ModTags.Blocks.FOUNDRY_TANKS)).count();
}
}
@Override
public void render(@Nonnull GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) {
super.render(guiGraphics, mouseX, mouseY, partialTicks);
this.renderTooltip(guiGraphics, mouseX, mouseY);
}
@Override
protected void renderBg(@Nonnull GuiGraphics guiGraphics, float partialTicks, int mouseX, int mouseY) {
// Draw main screen
guiGraphics.blit(GUI, this.getGuiLeft(), this.getGuiTop(), 0, 0, this.getXSize(), this.getYSize());
// Draw slots
if (this.menu.blockEntity.getItemHandler() instanceof TickingSlotInventoryHandler itemHandler) {
int rowIndex = this.menu.getRowIndexForScroll(this.scrollOffs);
int slotsAfterScroll = itemHandler.getSlots() - (rowIndex * FoundryControllerContainer.COLUMNS);
// calculate number of rows under the scroll fold
int rows = this.menu.calculateRowCount(rowIndex);
for (int row = 0; row < Math.min(3, rows); row++) {
for (int i = 0; i < FoundryControllerContainer.COLUMNS; i++) {
int slot = (row * FoundryControllerContainer.COLUMNS) + (rowIndex * FoundryControllerContainer.COLUMNS) + i;
if (row * FoundryControllerContainer.COLUMNS + i < slotsAfterScroll && slot < itemHandler.getSlots() && this.menu.slots.get(slot).isActive()) {
int slotX = this.getGuiLeft() + 79 + (i * 18);
int slotY = this.getGuiTop() + 16 + (row * 18);
guiGraphics.blit(GUI, slotX, slotY, 202, 0, 18, 18);
var stack = itemHandler.getStackInSlot(slot);
if (!stack.isEmpty()) {
var ticker = itemHandler.getTicker(slot);
if (ticker.getSecond() != 0 && !ticker.getFirst().equals(ticker.getSecond())) {
int progress = (int) (18f - ((float) ticker.getFirst() / (float) ticker.getSecond()) * 18f);
guiGraphics.blit(GUI, slotX, slotY + (18 - progress), 202, 36 - progress, 18, progress);
} else {
guiGraphics.blit(GUI, slotX, slotY, 202, 36, 18, 18);
}
}
}
}
}
}
// Draw scrollbar
guiGraphics.blitSprite(SCROLLER_SPRITE, this.getGuiLeft() + 156, this.getGuiTop() + 17 + (int) (37f * this.scrollOffs), 12, 15);
switch (this.menu.blockEntity.getCoilType()) {
case UNKNOWN, FLUID -> {
// Draw fuel tank
if (!this.menu.blockEntity.fuel.isEmpty()) {
FluidContainerUtil.renderFluidTank(guiGraphics, this, this.menu.blockEntity.fuel, this.fuelTanks * 4000, 57, 17, 16, 52);
}
break;
}
case ENERGY -> {
// Draw energy tank
if (this.menu.blockEntity.getPowerMax() == 0) {
break;
}
// battery
guiGraphics.blit(GUI, getGuiLeft() + 56, getGuiTop() + 14, 238, 0, 18, 56);
// energy
float powerRatio = ((float) this.menu.blockEntity.getPower() / (float) this.menu.blockEntity.getPowerMax());
int energyLevel = (int) ((52f * powerRatio) + 0.5f);
guiGraphics.blit(GUI, getGuiLeft() + 57, getGuiTop() + 17 + 52 - energyLevel, 239, 59, 16, energyLevel);
}
}
// Draw fluid tank
int tankCapacity = this.menu.blockEntity.fluidHandler.getCapacity();
if (fluidPositions.size() != this.menu.blockEntity.fluidHandler.getTanks()) {
fluidPositions.clear();
}
int fluidCount = 0;
for (int tank = 0; tank < this.menu.blockEntity.fluidHandler.getTanks(); tank++) {
if (!this.menu.blockEntity.fluidHandler.getFluidInTank(tank).isEmpty()) {
fluidCount++;
}
}
int tankHeight = 52;
int fluidMinHeight = 4;
int fluidMinAmount = tankCapacity / tankHeight * fluidMinHeight;
int fluidMaxAmount = tankCapacity - (fluidCount * fluidMinAmount - fluidMinAmount);
int nextFluidOffset = 0;
for (int tank = 0; tank < this.menu.blockEntity.fluidHandler.getTanks(); tank++) {
FluidStack fluidStack = this.menu.blockEntity.fluidHandler.getFluidInTank(tank);
if (!fluidStack.isEmpty()) {
int adjustedAmount = Math.max(Math.min(fluidMaxAmount, fluidStack.getAmount()), fluidMinAmount);
double fluidHeight = Math.round(tankHeight * ((double) adjustedAmount / (double) tankCapacity));
fluidPositions.put(tank, Pair.of(nextFluidOffset, (int) fluidHeight));
FluidContainerUtil.renderTiledFluid(guiGraphics, this, fluidStack, 8, 17 + 52 - (int) fluidHeight - nextFluidOffset, 42, (int) fluidHeight, 0);
nextFluidOffset += (int) fluidHeight;
}
}
}
@Override
protected @NotNull List<Component> getTooltipFromContainerItem(ItemStack stack) {
List<Component> tooltips = super.getTooltipFromContainerItem(stack);
if (!stack.isEmpty()) {
FoundryControllerBlockEntity.IMelterProcessor melter = switch (this.menu.blockEntity.getCoilType()) {
case UNKNOWN -> null;
case CoilType.FLUID -> new FoundryControllerBlockEntity.LiquidMelter();
case CoilType.ENERGY -> new FoundryControllerBlockEntity.EnergyMelter();
};
if (melter != null) {
FuelMap fuelData = melter.getFoundryFuel(this.menu.blockEntity.getLevel(), this.menu.blockEntity).getFuelData();
if (fuelData != null) {
RecipeHolder<ItemMeltingRecipe> recipe = RecipeHelper.getItemMeltingRecipe(Minecraft.getInstance().level, stack, fuelData);
if (recipe != null) {
int speedModifier = this.menu.blockEntity.getSpeedModifier();
// Sum total fluid amount that would be melted
int totalProducedFluid = recipe.value().result.stream().map(FluidStack::getAmount).reduce(Integer::sum).orElse(0);
// Look at the fuel required for this recipe melt
int requiredFuel = (int) (totalProducedFluid * fuelData.consumption() * speedModifier);
boolean hasEnough = requiredFuel <= (this.menu.blockEntity.getCoilType().equals(CoilType.ENERGY) ? this.menu.blockEntity.getPower() : this.menu.blockEntity.getFuel().getAmount());
tooltips.add(tooltips.size() - 1, Component.translatable("gui.productivemetalworks.required_fuel", requiredFuel + (this.menu.blockEntity.getCoilType().equals(CoilType.ENERGY) ? " FE" : " mb")).withStyle(hasEnough ? ChatFormatting.GREEN : ChatFormatting.RED));
}
}
}
}
return tooltips;
}
@Override
protected void renderLabels(GuiGraphics guiGraphics, int mouseX, int mouseY) {
super.renderLabels(guiGraphics, mouseX, mouseY);
List<FormattedCharSequence> tooltipList = new ArrayList<>();
if (insideFuelTank(mouseX, mouseY)) {
FoundryControllerBlockEntity.IMelterProcessor melter = switch (this.menu.blockEntity.getCoilType()) {
case UNKNOWN -> null;
case CoilType.FLUID -> new FoundryControllerBlockEntity.LiquidMelter();
case CoilType.ENERGY -> new FoundryControllerBlockEntity.EnergyMelter();
};
switch (this.menu.blockEntity.getCoilType()) {
case FLUID -> {
if (!this.menu.blockEntity.fuel.isEmpty()) {
tooltipList.add(Component.literal(this.menu.blockEntity.fuel.getAmount() + "mb " + Component.translatable(this.menu.blockEntity.fuel.getFluid().getFluidType().getDescriptionId()).getString()).getVisualOrderText());
if (melter != null) {
var fuelData = melter.getFoundryFuel(this.menu.blockEntity.getLevel(), this.menu.blockEntity).getFuelData();
if (fuelData != null) {
tooltipList.add(Component.translatable("gui.productivemetalworks.temperature", fuelData.temperature()).getVisualOrderText());
}
}
}
}
case ENERGY -> {
tooltipList.add(Component.literal(this.menu.blockEntity.getPower() + " FE").getVisualOrderText());
if (melter != null) {
var fuelData = melter.getFoundryFuel(this.menu.blockEntity.getLevel(), this.menu.blockEntity).getFuelData();
if (fuelData != null) {
tooltipList.add(Component.translatable("gui.productivemetalworks.temperature", fuelData.temperature()).getVisualOrderText());
}
}
}
}
}
if (insideTank(mouseX, mouseY)) {
int tank = getHoveredTank(mouseX, mouseY);
if (tank >= 0) {
FluidStack fluidStack = this.menu.blockEntity.fluidHandler.getFluidInTank(tank);
tooltipList.add(Component.literal(fluidStack.getAmount() + "mb " + Component.translatable(fluidStack.getFluid().getFluidType().getDescriptionId()).getString()).getVisualOrderText());
tooltipList.addAll(FluidHelper.formatTooltip(fluidStack).stream().map(Component::getVisualOrderText).toList());
}
}
if (!tooltipList.isEmpty()) {
guiGraphics.renderTooltip(font, tooltipList, mouseX - getGuiLeft(), mouseY - getGuiTop());
}
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (insideTank(mouseX, mouseY)) {
int tank = getHoveredTank(mouseX, mouseY);
PacketDistributor.sendToServer(new MoveFoundryFluidData(this.menu.blockEntity.getBlockPos(), tank));
return true;
}
if (this.insideScrollbar(mouseX, mouseY)) {
this.isScrolling = true;
return true;
}
return super.mouseClicked(mouseX, mouseY, button);
}
@Override
public boolean mouseReleased(double mouseX, double mouseY, int button) {
if (button == 0) {
this.isScrolling = false;
}
return super.mouseReleased(mouseX, mouseY, button);
}
@Override
public boolean mouseDragged(double mouseX, double mouseY, int button, double dragX, double dragY) {
if (this.isScrolling) {
this.scrollOffs = ((float) mouseY - (float) this.getGuiTop() - 24.5f) / 37f;
this.scrollOffs = Mth.clamp(this.scrollOffs, 0.0F, 1.0F);
this.menu.scrollTo(this.scrollOffs);
return true;
}
return super.mouseDragged(mouseX, mouseY, button, dragX, dragY);
}
@Override
public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) {
if (insideScrollbar(mouseX, mouseY) || insideContainer(mouseX, mouseY)) {
this.scrollOffs = this.menu.subtractInputFromScroll(this.scrollOffs, scrollY);
this.menu.scrollTo(this.scrollOffs);
return true;
}
return super.mouseScrolled(mouseX, mouseY, scrollX, scrollY);
}
private int getHoveredTank(double mouseX, double mouseY) {
if (insideTank(mouseX, mouseY)) {
for (Map.Entry<Integer, Pair<Integer, Integer>> entry : fluidPositions.entrySet()) {
Pair<Integer, Integer> o = entry.getValue();
if (isHovering(8, 69 - o.getFirst() - o.getSecond(), 42, o.getSecond(), mouseX, mouseY)) {
return entry.getKey();
}
}
}
return -1;
}
private boolean insideContainer(double mouseX, double mouseY) {
return isHovering(80, 17, 88, 52, mouseX, mouseY);
}
private boolean insideFuelTank(double mouseX, double mouseY) {
return isHovering(57, 17, 16, 52, mouseX, mouseY);
}
private boolean insideTank(double mouseX, double mouseY) {
return isHovering(8, 17, 42, 52, mouseX, mouseY);
}
protected boolean insideScrollbar(double mouseX, double mouseY) {
return isHovering(156, 17, 12, 52, mouseX, mouseY);
}
}
| 0 | 0.859925 | 1 | 0.859925 | game-dev | MEDIA | 0.945291 | game-dev | 0.965079 | 1 | 0.965079 |
Swofty-Developments/HypixelSkyBlock | 2,918 | type.hub/src/main/java/net/swofty/type/hub/gui/elizabeth/subguis/GUIBitsConfirmBuy.java | package net.swofty.type.hub.gui.elizabeth.subguis;
import net.minestom.server.event.inventory.InventoryCloseEvent;
import net.minestom.server.event.inventory.InventoryPreClickEvent;
import net.minestom.server.inventory.Inventory;
import net.minestom.server.inventory.InventoryType;
import net.minestom.server.item.ItemStack;
import net.minestom.server.item.Material;
import net.swofty.commons.StringUtility;
import net.swofty.type.hub.gui.elizabeth.GUIBitsShop;
import net.swofty.type.generic.gui.inventory.ItemStackCreator;
import net.swofty.type.generic.gui.inventory.HypixelInventoryGUI;
import net.swofty.type.generic.gui.inventory.item.GUIClickableItem;
import net.swofty.type.skyblockgeneric.item.SkyBlockItem;
import net.swofty.type.skyblockgeneric.user.SkyBlockPlayer;
import net.swofty.type.generic.user.HypixelPlayer;
public class GUIBitsConfirmBuy extends HypixelInventoryGUI {
SkyBlockItem item;
Integer price;
public GUIBitsConfirmBuy(SkyBlockItem item, Integer price) {
super("Confirm", InventoryType.CHEST_3_ROW);
this.item = item;
this.price = price;
}
public void onOpen(InventoryGUIOpenEvent e) {
fill(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE));
set(new GUIClickableItem(11) {
@Override
public void run(InventoryPreClickEvent e, HypixelPlayer p) {
SkyBlockPlayer player = (SkyBlockPlayer) p;
player.addAndUpdateItem(item);
player.removeBits(price);
new GUIBitsShop().open(player);
}
@Override
public ItemStack.Builder getItem(HypixelPlayer p) {
SkyBlockPlayer player = (SkyBlockPlayer) p;
return ItemStackCreator.getStack("§aConfirm", Material.LIME_TERRACOTTA, 1,
"§7Buying: " + item.getDisplayName(),
"§7Cost: §b" + StringUtility.commaify(price));
}
});
set(new GUIClickableItem(15) {
@Override
public void run(InventoryPreClickEvent e, HypixelPlayer p) {
SkyBlockPlayer player = (SkyBlockPlayer) p;
player.closeInventory();
}
@Override
public ItemStack.Builder getItem(HypixelPlayer p) {
SkyBlockPlayer player = (SkyBlockPlayer) p;
return ItemStackCreator.getStack("§cCancel", Material.RED_TERRACOTTA, 1);
}
});
updateItemStacks(getInventory(), getPlayer());
}
@Override
public boolean allowHotkeying() {
return false;
}
@Override
public void onClose(InventoryCloseEvent e, CloseReason reason) {
}
@Override
public void suddenlyQuit(Inventory inventory, HypixelPlayer player) {
}
@Override
public void onBottomClick(InventoryPreClickEvent e) {
}
}
| 0 | 0.893103 | 1 | 0.893103 | game-dev | MEDIA | 0.954213 | game-dev | 0.864196 | 1 | 0.864196 |
ustwo/ReplayKitUnityBridge | 3,041 | DemoUnityAndReplayKit/Assets/RecordController.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
public class RecordController : MonoBehaviour {
public VideoPlayer videoPlayer;
private bool isRecording = false;
public GameObject cube;
public GameObject videoTexture;
public float TimeToRecord;
private static string MailSubjectLine = "Test Hello";
void Start () {
// Set the time you are allowing the user to record gameplay
ReplayKitUnity.AllowedTimeToRecord = TimeToRecord;
// Tells ReplayKit to use a default interface that is excluded in playback
ReplayKitUnity.ShowDefaultButtonUI();
// Subscribe to the ReplayKit callbacks
if (ReplayKitUnity.IsScreenRecorderAvailable) {
ReplayKitUnity.Instance.onStopScreenCaptureWithFile += OnStopCallback;
ReplayKitUnity.Instance.onStartScreenCapture += OnStartRecording;
}
}
// Call back that is triggered from iOS native
public void OnStartRecording() {
if (!isRecording) {
isRecording = true;
cube.SetActive(true);
}
}
// You will recieve the file path to the recorded gameplay session here
public void OnStopCallback(string file) {
isRecording = false;
cube.SetActive(false);
videoTexture.SetActive(true);
// Play the recorded video
StartCoroutine(playVideo(file));
}
IEnumerator playVideo(string file) {
videoPlayer.enabled = true;
if (videoPlayer == null) {
Debug.Log("video player is null");
yield return null;
}
//Disable Play on Awake for both Video and Audio
videoPlayer.playOnAwake = false;
//We want to play from video clip not from url
videoPlayer.source = VideoSource.Url;
videoPlayer.url = file;
//Set Audio Output to AudioSource
videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;
//Assign the Audio from Video to AudioSource to be played
videoPlayer.EnableAudioTrack(0, true);
//videoPlayer.SetTargetAudioSource(0, audioSource);
//Set video To Play then prepare Audio to prevent Buffering
videoPlayer.Prepare();
//Wait until video is prepared
while (!videoPlayer.isPrepared) {
Debug.Log("Preparing Video");
yield return null;
}
Debug.Log("Done Preparing Video");
// Play Video
videoPlayer.Play();
Debug.Log("Playing Video");
while (videoPlayer.isPlaying) {
// Debug.LogWarning("Video Time: " + Mathf.FloorToInt((float)videoPlayer.time));
yield return null;
}
Debug.Log("Done Playing Video");
}
public void ShowSendVideoButton() {
}
public void DidTapSend() {
// Set the subject line for the email message
ReplayKitUnity.MailSubjectText = MailSubjectLine;
// Show the email/iOS share sheet
ReplayKitUnity.ShowEmailShareSheet();
}
}
| 0 | 0.502014 | 1 | 0.502014 | game-dev | MEDIA | 0.485992 | game-dev | 0.900027 | 1 | 0.900027 |
ProwlEngine/Prowl.Echo | 3,585 | Echo/ReflectionUtils.cs | // This file is part of the Prowl Game Engine
// Licensed under the MIT License. See the LICENSE file in the project root for details.
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace Prowl.Echo;
[RequiresUnreferencedCode("These methods use reflection and can't be statically analyzed.")]
public static class ReflectionUtils
{
// Cache for type lookups
private static readonly ConcurrentDictionary<string, Type?> TypeCache = new();
// Cache for serializable fields
private static readonly ConcurrentDictionary<RuntimeTypeHandle, FieldInfo[]> SerializableFieldsCache = new();
internal static void ClearCache()
{
TypeCache.Clear();
SerializableFieldsCache.Clear();
}
internal static Type? FindTypeByName(string qualifiedTypeName)
{
return TypeCache.GetOrAdd(qualifiedTypeName, typeName => {
// First try direct type lookup
Type? t = Type.GetType(typeName);
if (t != null)
return t;
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly asm in assemblies)
{
// Try full name lookup
t = asm.GetType(typeName);
if (t != null)
return t;
// Try name-only lookup (case insensitive) while ignoring load failures
Type[] types;
try
{
types = asm.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
types = ex.Types.Where(type => type != null).Cast<Type>().ToArray();
}
t = types.FirstOrDefault(type => type.Name.Equals(typeName, StringComparison.OrdinalIgnoreCase));
if (t != null)
return t;
}
return null;
});
}
internal static FieldInfo[] GetSerializableFields(this object target)
{
Type targetType = target.GetType();
return SerializableFieldsCache.GetOrAdd(targetType.TypeHandle, _ => {
const BindingFlags flags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly;
// Start with the current type
List<FieldInfo> fields = new List<FieldInfo>();
Type? currentType = targetType;
// Walk up the inheritance hierarchy to collect fields from all base types
while (currentType != null && currentType != typeof(object))
{
fields.AddRange(currentType.GetFields(flags)
.Where(field => IsFieldSerializable(field)));
currentType = currentType.BaseType;
}
return fields.ToArray();
});
}
private static bool IsFieldSerializable(FieldInfo field)
{
// Check if field should be serialized
bool shouldSerialize = field.IsPublic || field.GetCustomAttribute<SerializeFieldAttribute>() != null;
if (!shouldSerialize)
return false;
// Check if field should be ignored
bool shouldIgnore = field.GetCustomAttribute<SerializeIgnoreAttribute>() != null ||
field.GetCustomAttribute<NonSerializedAttribute>() != null;
if (shouldIgnore)
return false;
return true;
}
}
| 0 | 0.882573 | 1 | 0.882573 | game-dev | MEDIA | 0.673061 | game-dev | 0.98959 | 1 | 0.98959 |
AntonioND/ucity-advance | 19,620 | source/room_game/draw_common.c | // SPDX-License-Identifier: GPL-3.0-only
//
// Copyright (c) 2017-2019, 2021, Antonio Niño Díaz
#include <stdint.h>
#include <ugba/ugba.h>
#include "map_utils.h"
#include "money.h"
#include "sfx.h"
#include "room_game/building_info.h"
#include "room_game/draw_common.h"
#include "room_game/draw_road.h"
#include "room_game/draw_power_lines.h"
#include "room_game/draw_train.h"
#include "room_game/room_game.h"
#include "room_game/tileset_info.h"
// ----------------------------------------------------------------------------
// The functions below can be used to guess the type of the rows and columns
// right outside the map (but out of it). They expand the type of the tile in
// the border (water or field). For example, if the last tile at row 63 is a
// forest, row 64 would have a field. If it was water, the result would be water
// too.
uint16_t CityMapGetTypeNoBoundCheck(int x, int y)
{
void *map = (void *)CITY_MAP_BASE;
uint16_t tile = MAP_REGULAR_TILE(read_tile_sbb(map, x, y));
const city_tile_info *tile_info = City_Tileset_Entry_Info(tile);
return tile_info->element_type;
}
uint16_t CityMapGetType(int x, int y)
{
int fix = 0;
if (x < 0)
{
x = 0;
fix = 1;
}
else if (x >= CITY_MAP_WIDTH)
{
x = CITY_MAP_WIDTH - 1;
fix = 1;
}
if (y < 0)
{
y = 0;
fix = 1;
}
else if (y >= CITY_MAP_HEIGHT)
{
y = CITY_MAP_HEIGHT - 1;
fix = 1;
}
if (fix)
{
if ((CityMapGetTypeNoBoundCheck(x, y) & TYPE_MASK) == TYPE_WATER)
return TYPE_WATER;
return TYPE_FIELD;
}
void *map = (void *)CITY_MAP_BASE;
uint16_t tile = MAP_REGULAR_TILE(read_tile_sbb(map, x, y));
const city_tile_info *tile_info = City_Tileset_Entry_Info(tile);
return tile_info->element_type;
}
uint16_t CityMapGetTile(int x, int y)
{
void *map = (void *)CITY_MAP_BASE;
return MAP_REGULAR_TILE(read_tile_sbb(map, x, y));
}
uint16_t CityMapGetTileClamped(int x, int y)
{
if (x < 0)
x = 0;
else if (x > (CITY_MAP_WIDTH - 1))
x = CITY_MAP_WIDTH - 1;
if (y < 0)
y = 0;
else if (y > (CITY_MAP_HEIGHT - 1))
y = CITY_MAP_HEIGHT - 1;
void *map = (void *)CITY_MAP_BASE;
return MAP_REGULAR_TILE(read_tile_sbb(map, x, y));
}
void CityMapGetTypeAndTileUnsafe(int x, int y, uint16_t *tile, uint16_t *type)
{
void *map = (void *)CITY_MAP_BASE;
*tile = MAP_REGULAR_TILE(read_tile_sbb(map, x, y));
const city_tile_info *tile_info = City_Tileset_Entry_Info(*tile);
*type = tile_info->element_type;
}
void CityMapGetTypeAndTile(int x, int y, uint16_t *tile, uint16_t *type)
{
int fix = 0;
if (x < 0)
{
x = 0;
fix = 1;
}
else if (x >= CITY_MAP_WIDTH)
{
x = CITY_MAP_WIDTH - 1;
fix = 1;
}
if (y < 0)
{
y = 0;
fix = 1;
}
else if (y >= CITY_MAP_HEIGHT)
{
y = CITY_MAP_HEIGHT - 1;
fix = 1;
}
if (fix)
{
if ((CityMapGetTypeNoBoundCheck(x, y) & TYPE_MASK) == TYPE_WATER)
{
*tile = T_WATER;
*type = TYPE_WATER;
}
else
{
*tile = T_GRASS;
*type = TYPE_FIELD;
}
}
else
{
CityMapGetTypeAndTileUnsafe(x, y, tile, type);
}
}
// ----------------------------------------------------------------------------
void CityMapDrawTile(uint16_t tile, int x, int y)
{
void *map = (void *)CITY_MAP_BASE;
uint16_t vram_info = City_Tileset_VRAM_Info(tile);
write_tile_sbb(vram_info, map, x, y);
}
void CityMapDrawTilePreserveFlip(uint16_t tile, int x, int y)
{
void *map = (void *)CITY_MAP_BASE;
uint16_t *ptr = get_pointer_sbb(map, x, y);
uint16_t vram_info = City_Tileset_VRAM_Info(tile);
uint16_t mask = MAP_REGULAR_HFLIP | MAP_REGULAR_VFLIP;
*ptr = (*ptr & mask) | vram_info;
}
void CityMapToggleHFlip(int x, int y)
{
void *map = (void *)CITY_MAP_BASE;
toggle_hflip_tile_sbb(map, x, y);
}
void CityMapToggleVFlip(int x, int y)
{
void *map = (void *)CITY_MAP_BASE;
toggle_vflip_tile_sbb(map, x, y);
}
// Checks if a bridge of a certain type can be built. For that to be possible,
// the coordinates must point at a water tile next to the ground, but with only
// one tile of ground surounding it (or 2 at two opposite sides). It cannot
// leave the map, it must end inside of it.
//
// Returns the length and direction of a possible bridge.
void CityMapCheckBuildBridge(int force, int x, int y, uint16_t type,
int *length, int *direction)
{
*length = 0;
// Check if this point is actually water with nothing else built on it
if (CityMapGetType(x, y) != TYPE_WATER)
return;
// Check if there's an item nearby like the one specified
// ------------------------------------------------------
//
// Only the border of a river or the sea could have one, so that would
// mean that this is actually the border of the water.
//
// Fail if:
// - 0 neighbours (don't know how to start)
// - 2, 3 or 4 neighbours
int neighbours = 0;
if (CityMapGetType(x, y - 1) == (type | TYPE_FIELD))
{
neighbours++;
*direction = KEY_DOWN;
}
if (CityMapGetType(x - 1, y) == (type | TYPE_FIELD))
{
neighbours++;
*direction = KEY_RIGHT;
}
if (CityMapGetType(x + 1, y) == (type | TYPE_FIELD))
{
neighbours++;
*direction = KEY_LEFT;
}
if (CityMapGetType(x, y + 1) == (type | TYPE_FIELD))
{
neighbours++;
*direction = KEY_UP;
}
// It's only possible to guess direction if there is only one neighbour
if (neighbours != 1)
return;
// Start checking the build direction
int curx = x;
int cury = y;
while (1)
{
*length = *length + 1;
if (*direction == KEY_UP)
cury--;
else if (*direction == KEY_DOWN)
cury++;
else if (*direction == KEY_LEFT)
curx--;
else if (*direction == KEY_RIGHT)
curx++;
if ((curx < 0) || (curx >= CITY_MAP_WIDTH) ||
(cury < 0) || (cury >= CITY_MAP_HEIGHT))
{
*length = 0;
return;
}
// Check if there is an obstacle
uint16_t type_ = CityMapGetType(curx, cury);
if (type_ != TYPE_WATER)
{
type_ &= TYPE_MASK;
// If bridge or dock, fail
if ((type_ == TYPE_WATER) || (type_ == TYPE_DOCK))
{
*length = 0;
return;
}
break;
}
}
// Check if there is enough money
int building_type;
if (type == TYPE_HAS_ROAD)
{
building_type = B_Road;
}
else if (type == TYPE_HAS_TRAIN)
{
building_type = B_Train;
}
else if (type == TYPE_HAS_POWER)
{
building_type = B_PowerLines;
}
else
{
UGBA_Assert(0);
return;
}
if (force == 0)
{
const building_info *bi = Get_Building_Info(building_type);
if (MoneyIsThereEnough(bi->price * (*length)) == 0)
{
// Exit and play "not enough money" sound
SFX_BuildError();
return;
}
// Success
SFX_Build();
}
return;
}
// Builds a bridge until it finds a non TYPE_WATER (exactly) tile.
// Returns the other end of the bridge in x and y.
void CityMapBuildBridge(int force, int *x, int *y, uint16_t type,
int length, int direction)
{
// First, check which tile to draw
int deltax = 0;
int deltay = 0;
uint16_t tile;
if (type == TYPE_HAS_ROAD)
{
if (direction == KEY_UP)
{
deltay = -1;
tile = T_ROAD_TB_BRIDGE;
}
else if (direction == KEY_DOWN)
{
deltay = +1;
tile = T_ROAD_TB_BRIDGE;
}
else if (direction == KEY_LEFT)
{
deltax = -1;
tile = T_ROAD_LR_BRIDGE;
}
else if (direction == KEY_RIGHT)
{
deltax = +1;
tile = T_ROAD_LR_BRIDGE;
}
else
{
UGBA_Assert(0);
return;
}
}
else if (type == TYPE_HAS_TRAIN)
{
if (direction == KEY_UP)
{
deltay = -1;
tile = T_TRAIN_TB_BRIDGE;
}
else if (direction == KEY_DOWN)
{
deltay = +1;
tile = T_TRAIN_TB_BRIDGE;
}
else if (direction == KEY_LEFT)
{
deltax = -1;
tile = T_TRAIN_LR_BRIDGE;
}
else if (direction == KEY_RIGHT)
{
deltax = +1;
tile = T_TRAIN_LR_BRIDGE;
}
else
{
UGBA_Assert(0);
return;
}
}
else if (type == TYPE_HAS_POWER)
{
if (direction == KEY_UP)
{
deltay = -1;
tile = T_POWER_LINES_TB_BRIDGE;
}
else if (direction == KEY_DOWN)
{
deltay = +1;
tile = T_POWER_LINES_TB_BRIDGE;
}
else if (direction == KEY_LEFT)
{
deltax = -1;
tile = T_POWER_LINES_LR_BRIDGE;
}
else if (direction == KEY_RIGHT)
{
deltax = +1;
tile = T_POWER_LINES_LR_BRIDGE;
}
else
{
UGBA_Assert(0);
return;
}
}
else
{
UGBA_Assert(0);
return;
}
// Draw bridge
int built_length = 0;
while (built_length < length)
{
uint16_t type_ = CityMapGetType(*x, *y);
if (type_ != TYPE_WATER)
break;
CityMapDrawTile(tile, *x, *y);
*x = *x + deltax;
*y = *y + deltay;
built_length--;
}
// Get money
int building_type;
if (type == TYPE_HAS_ROAD)
{
building_type = B_Road;
}
else if (type == TYPE_HAS_TRAIN)
{
building_type = B_Train;
}
else if (type == TYPE_HAS_POWER)
{
building_type = B_PowerLines;
}
else
{
UGBA_Assert(0);
return;
}
if (force == 0)
{
const building_info *bi = Get_Building_Info(building_type);
MoneyReduce(bi->price * length);
}
// Done
}
typedef struct {
uint8_t mask;
uint8_t expected_result;
uint16_t resulting_tile;
} water_mask;
static const water_mask water_mask_table[] = {
// From more restrictive to less restrictive
// 8 neighbours of this tile.
//
// 0 1 2
// 3 . 4 <- Bit order
// 5 6 7
{ 0b01011010, 0b01010000, T_WATER__GRASS_TL },
{ 0b01011010, 0b01011000, T_WATER__GRASS_TC },
{ 0b01011010, 0b01001000, T_WATER__GRASS_TR },
{ 0b01011010, 0b01010010, T_WATER__GRASS_CL },
{ 0b01011010, 0b01001010, T_WATER__GRASS_CR },
{ 0b01011010, 0b00010010, T_WATER__GRASS_BL },
{ 0b01011010, 0b00011010, T_WATER__GRASS_BC },
{ 0b01011010, 0b00001010, T_WATER__GRASS_BR },
{ 0b01011011, 0b01011010, T_WATER__GRASS_CORNER_TL },
{ 0b01011110, 0b01011010, T_WATER__GRASS_CORNER_TR },
{ 0b01111010, 0b01011010, T_WATER__GRASS_CORNER_BL },
{ 0b11011010, 0b01011010, T_WATER__GRASS_CORNER_BR },
{ 0b00000000, 0b00000000, T_WATER }, // Default -> Always valid
};
void MapUpdateWater(int x, int y)
{
if ((x < 0) || (x >= CITY_MAP_WIDTH))
return;
if ((y < 0) || (y >= CITY_MAP_HEIGHT))
return;
// Assume that this is water, and that a bridge here (if any) is supposed to
// be deleted by this function. If this is a dock, delete it too.
// Calculate the needed tile
// -------------------------
// Create a byte containing the state of the 8 neighbours of this pixel.
//
// 1 = has water, 0 = doesn't have water.
//
// 0 1 2
// 3 . 4 <- Bit order
// 5 6 7
uint8_t flags = 0;
uint16_t tile, type;
CityMapGetTypeAndTile(x - 1, y - 1, &tile, &type);
type &= TYPE_MASK;
if ((type == TYPE_WATER) || (type == TYPE_DOCK) || (tile == T_RADIATION_WATER))
flags |= 1 << 0;
CityMapGetTypeAndTile(x, y - 1, &tile, &type);
type &= TYPE_MASK;
if ((type == TYPE_WATER) || (type == TYPE_DOCK) || (tile == T_RADIATION_WATER))
flags |= 1 << 1;
CityMapGetTypeAndTile(x + 1, y - 1, &tile, &type);
type &= TYPE_MASK;
if ((type == TYPE_WATER) || (type == TYPE_DOCK) || (tile == T_RADIATION_WATER))
flags |= 1 << 2;
CityMapGetTypeAndTile(x - 1, y, &tile, &type);
type &= TYPE_MASK;
if ((type == TYPE_WATER) || (type == TYPE_DOCK) || (tile == T_RADIATION_WATER))
flags |= 1 << 3;
CityMapGetTypeAndTile(x + 1, y, &tile, &type);
type &= TYPE_MASK;
if ((type == TYPE_WATER) || (type == TYPE_DOCK) || (tile == T_RADIATION_WATER))
flags |= 1 << 4;
CityMapGetTypeAndTile(x - 1, y + 1, &tile, &type);
type &= TYPE_MASK;
if ((type == TYPE_WATER) || (type == TYPE_DOCK) || (tile == T_RADIATION_WATER))
flags |= 1 << 5;
CityMapGetTypeAndTile(x, y + 1, &tile, &type);
type &= TYPE_MASK;
if ((type == TYPE_WATER) || (type == TYPE_DOCK) || (tile == T_RADIATION_WATER))
flags |= 1 << 6;
CityMapGetTypeAndTile(x + 1, y + 1, &tile, &type);
type &= TYPE_MASK;
if ((type == TYPE_WATER) || (type == TYPE_DOCK) || (tile == T_RADIATION_WATER))
flags |= 1 << 7;
// Compare with table
const water_mask *wm = &water_mask_table[0];
while (1)
{
// This loop will always end because the last element of the table will
// always pass this check.
if ((wm->mask & flags) == wm->expected_result)
{
// Draw resulting tile
CityMapDrawTile(wm->resulting_tile, x, y);
return;
}
wm++;
}
}
// It deletes one tile of road, train or power lines, but it doesn't update
// neighbours, that has to be done by the caller. It doesn't work to demolish
// bridges. Returns 0 on success.
int MapDeleteRoadTrainPowerlines(int force, int x, int y)
{
// Check if there is enough money
if (force == 0)
{
const building_info *bi = Get_Building_Info(B_Delete);
if (MoneyIsThereEnough(bi->price) == 0)
{
// Exit and play "not enough money" sound
SFX_BuildError();
return 1;
}
}
// Delete
CityMapDrawTile(T_DEMOLISHED, x, y);
// Decrease money
if (force == 0)
{
const building_info *bi = Get_Building_Info(B_Delete);
MoneyReduce(bi->price);
SFX_Demolish();
}
return 0;
}
// Roads, train tracks and power lines require special handling because it is
// needed to handle bridges in a different way.
void BuildingRemoveRoadTrainPowerLines(int force, int x, int y)
{
// Check if this is a bridge
uint16_t tile, type;
CityMapGetTypeAndTile(x, y, &tile, &type);
if ((type & TYPE_MASK) == TYPE_WATER)
{
DrawCityDeleteBridge(force, x, y);
return;
}
// Delete tile
if (MapDeleteRoadTrainPowerlines(force, x, y) != 0)
return; // Exit if it failed
// Update suroundings according to the elements that it had
if (type & TYPE_HAS_ROAD)
MapUpdateNeighboursRoad(x, y);
if (type & TYPE_HAS_TRAIN)
MapUpdateNeighboursTrain(x, y);
if (type & TYPE_HAS_POWER)
MapUpdateNeighboursPowerLines(x, y);
}
typedef struct {
uint16_t tile;
uint16_t type;
int is_vertical;
} bridge_info;
static const bridge_info bridge_tile_info[] = {
{ T_ROAD_TB_BRIDGE, TYPE_HAS_ROAD, 1 },
{ T_ROAD_LR_BRIDGE, TYPE_HAS_ROAD, 0 },
{ T_TRAIN_TB_BRIDGE, TYPE_HAS_TRAIN, 1 },
{ T_TRAIN_LR_BRIDGE, TYPE_HAS_TRAIN, 0 },
{ T_POWER_LINES_TB_BRIDGE, TYPE_HAS_POWER, 1 },
{ T_POWER_LINES_LR_BRIDGE, TYPE_HAS_POWER, 0 },
{ 0, 0, 0 }, // End
};
// Checks length of the bridge to see if there is money to delete. If so, it
// calls DrawCityDeleteBridgeForce and reduces the money. The money check
// can be disabled. If plays SFX.
void DrawCityDeleteBridge(int force, int x, int y)
{
// Check tile to see which direction to go (up or left)
uint16_t tile = CityMapGetTile(x, y);
int is_vertical;
int type;
const bridge_info *bti = &bridge_tile_info[0];
while (1)
{
if (bti->tile == tile)
{
is_vertical = bti->is_vertical;
type = bti->type;
break;
}
bti++;
if (bti->type == 0)
return;
}
// Go to the top of the bridge or the left depending on orientation
int ox = x;
int oy = y;
while (1)
{
if ((ox < 0) || (oy < 0))
return;
if (is_vertical)
oy--;
else
ox--;
uint16_t type_ = CityMapGetType(ox, oy) & TYPE_MASK;
if (type_ != TYPE_WATER)
{
if (is_vertical)
oy++;
else
ox++;
break;
}
}
// Calculate how many tiles long is this bridge
int ex = ox;
int ey = oy;
int length = 1;
while (1)
{
if ((ex >= CITY_MAP_WIDTH) || (ey >= CITY_MAP_HEIGHT))
return;
if (is_vertical)
ey++;
else
ex++;
uint16_t type_ = CityMapGetType(ex, ey) & TYPE_MASK;
if (type_ != TYPE_WATER)
{
if (is_vertical)
ey--;
else
ex--;
break;
}
length++;
}
// Check if there is enough money
int32_t total_price = 0;
if (force == 0)
{
// The size is needed to calculate the money to be spent.
const building_info *delete_info = Get_Building_Info(B_Delete);
int32_t base_price = delete_info->price;
total_price = base_price * length;
if (MoneyIsThereEnough(total_price) == 0)
{
// Exit and play "not enough money" sound
SFX_BuildError();
return;
}
}
// Delete bridge
x = ox;
y = oy;
for (int l = 0; l < length; l++)
{
MapUpdateWater(x, y);
if (is_vertical)
{
y++;
if (y > ey)
break;
}
else
{
x++;
if (x > ex)
break;
}
}
// Update both ends of the bridge
// Because of how mixing road, trains and power line works, it's NOT
// impossible for them to be together at one of the ends of the bridge,
// but in that case there is no point in doing a refresh because it can't
// change the tile.
if (is_vertical)
{
oy--;
ey++;
}
else
{
ox--;
ex++;
}
if (type == TYPE_HAS_ROAD)
{
MapUpdateNeighboursRoad(ox, oy);
MapUpdateNeighboursRoad(ex, ey);
}
else if (type == TYPE_HAS_TRAIN)
{
MapUpdateNeighboursTrain(ox, oy);
MapUpdateNeighboursTrain(ex, ey);
}
else if (type == TYPE_HAS_POWER)
{
MapUpdateNeighboursPowerLines(ox, oy);
MapUpdateNeighboursPowerLines(ex, ey);
}
// Decrease money
if (force == 0)
{
MoneyReduce(total_price);
SFX_Demolish();
}
// Done
}
| 0 | 0.977275 | 1 | 0.977275 | game-dev | MEDIA | 0.898944 | game-dev | 0.933323 | 1 | 0.933323 |
Olezen/UnitySourceMovement | 18,943 | Modified fragsurf/Movement/SurfPhysics.cs | using UnityEngine;
using Fragsurf.TraceUtil;
namespace Fragsurf.Movement {
public class SurfPhysics {
///// Fields /////
/// <summary>
/// Change this if your ground is on a different layer
/// </summary>
public static int groundLayerMask = LayerMask.GetMask (new string[] { "Default", "Ground", "Player clip" }); //(1 << 0);
private static Collider[] _colliders = new Collider [maxCollisions];
private static Vector3[] _planes = new Vector3 [maxClipPlanes];
public const float HU2M = 52.4934383202f;
private const int maxCollisions = 128;
private const int maxClipPlanes = 5;
private const int numBumps = 1;
public const float SurfSlope = 0.7f;
///// Methods /////
/// <summary>
///
/// </summary>
/// <param name="collider"></param>
/// <param name="origin"></param>
/// <param name="velocity"></param>
/// http://www.00jknight.com/blog/unity-character-controller
public static void ResolveCollisions (Collider collider, ref Vector3 origin, ref Vector3 velocity, float rigidbodyPushForce, float velocityMultiplier = 1f, float stepOffset = 0f, ISurfControllable surfer = null) {
// manual collision resolving
int numOverlaps = 0;
if (collider is CapsuleCollider) {
var capc = collider as CapsuleCollider;
Vector3 point1, point2;
GetCapsulePoints (capc, origin, out point1, out point2);
numOverlaps = Physics.OverlapCapsuleNonAlloc (point1, point2, capc.radius,
_colliders, groundLayerMask, QueryTriggerInteraction.Ignore);
} else if (collider is BoxCollider) {
numOverlaps = Physics.OverlapBoxNonAlloc (origin, collider.bounds.extents, _colliders,
Quaternion.identity, groundLayerMask, QueryTriggerInteraction.Ignore);
}
Vector3 forwardVelocity = Vector3.Scale (velocity, new Vector3 (1f, 0f, 1f));
for (int i = 0; i < numOverlaps; i++) {
Vector3 direction;
float distance;
if (Physics.ComputePenetration (collider, origin,
Quaternion.identity, _colliders [i], _colliders [i].transform.position,
_colliders [i].transform.rotation, out direction, out distance)) {
// Step offset
if (stepOffset > 0f && surfer != null && surfer.moveData.useStepOffset)
if (StepOffset (collider, _colliders [i], ref origin, ref velocity, rigidbodyPushForce, velocityMultiplier, stepOffset, direction, distance, forwardVelocity, surfer))
return;
// Handle collision
direction.Normalize ();
Vector3 penetrationVector = direction * distance;
Vector3 velocityProjected = Vector3.Project (velocity, -direction);
velocityProjected.y = 0; // don't touch y velocity, we need it to calculate fall damage elsewhere
origin += penetrationVector;
velocity -= velocityProjected * velocityMultiplier;
Rigidbody rb = _colliders [i].GetComponentInParent<Rigidbody> ();
if (rb != null && !rb.isKinematic)
rb.AddForceAtPosition (velocityProjected * velocityMultiplier * rigidbodyPushForce, origin, ForceMode.Impulse);
}
}
}
public static bool StepOffset (Collider collider, Collider otherCollider, ref Vector3 origin, ref Vector3 velocity, float rigidbodyPushForce, float velocityMultiplier, float stepOffset, Vector3 direction, float distance, Vector3 forwardVelocity, ISurfControllable surfer) {
// Return if step offset is 0
if (stepOffset <= 0f)
return false;
// Get forward direction (return if we aren't moving/are only moving vertically)
Vector3 forwardDirection = forwardVelocity.normalized;
if (forwardDirection.sqrMagnitude == 0f)
return false;
// Trace ground
Trace groundTrace = Tracer.TraceCollider (collider, origin, origin + Vector3.down * 0.1f, groundLayerMask);
if (groundTrace.hitCollider == null || Vector3.Angle (Vector3.up, groundTrace.planeNormal) > surfer.moveData.slopeLimit)
return false;
// Trace wall
Trace wallTrace = Tracer.TraceCollider (collider, origin, origin + velocity, groundLayerMask, 0.9f);
if (wallTrace.hitCollider == null || Vector3.Angle (Vector3.up, wallTrace.planeNormal) <= surfer.moveData.slopeLimit)
return false;
// Trace upwards (check for roof etc)
float upDistance = stepOffset;
Trace upTrace = Tracer.TraceCollider (collider, origin, origin + Vector3.up * stepOffset, groundLayerMask);
if (upTrace.hitCollider != null)
upDistance = upTrace.distance;
// Don't bother doing the rest if we can't move up at all anyway
if (upDistance <= 0f)
return false;
Vector3 upOrigin = origin + Vector3.up * upDistance;
// Trace forwards (check for walls etc)
float forwardMagnitude = stepOffset;
float forwardDistance = forwardMagnitude;
Trace forwardTrace = Tracer.TraceCollider (collider, upOrigin, upOrigin + forwardDirection * Mathf.Max (0.2f, forwardMagnitude), groundLayerMask);
if (forwardTrace.hitCollider != null)
forwardDistance = forwardTrace.distance;
// Don't bother doing the rest if we can't move forward anyway
if (forwardDistance <= 0f)
return false;
Vector3 upForwardOrigin = upOrigin + forwardDirection * forwardDistance;
// Trace down (find ground)
float downDistance = upDistance;
Trace downTrace = Tracer.TraceCollider (collider, upForwardOrigin, upForwardOrigin + Vector3.down * upDistance, groundLayerMask);
if (downTrace.hitCollider != null)
downDistance = downTrace.distance;
// Check step size/angle
float verticalStep = Mathf.Clamp (upDistance - downDistance, 0f, stepOffset);
float horizontalStep = forwardDistance;
float stepAngle = Vector3.Angle (Vector3.forward, new Vector3 (0f, verticalStep, horizontalStep));
if (stepAngle > surfer.moveData.slopeLimit)
return false;
// Get new position
Vector3 endOrigin = origin + Vector3.up * verticalStep;
// Actually move
if (origin != endOrigin && forwardDistance > 0f) {
Debug.Log ("Moved up step!");
origin = endOrigin + forwardDirection * forwardDistance * Time.deltaTime;
return true;
} else
return false;
}
/// <summary>
///
/// </summary>
public static void Friction (ref Vector3 velocity, float stopSpeed, float friction, float deltaTime) {
var speed = velocity.magnitude;
if (speed < 0.0001905f)
return;
var drop = 0f;
// apply ground friction
var control = (speed < stopSpeed) ? stopSpeed : speed;
drop += control * friction * deltaTime;
// scale the velocity
var newspeed = speed - drop;
if (newspeed < 0)
newspeed = 0;
if (newspeed != speed) {
newspeed /= speed;
velocity *= newspeed;
}
}
/// <summary>
///
/// </summary>
/// <param name="velocity"></param>
/// <param name="wishdir"></param>
/// <param name="wishspeed"></param>
/// <param name="accel"></param>
/// <param name="airCap"></param>
/// <param name="deltaTime"></param>
/// <returns></returns>
public static Vector3 AirAccelerate (Vector3 velocity, Vector3 wishdir, float wishspeed, float accel, float airCap, float deltaTime) {
var wishspd = wishspeed;
// Cap speed
wishspd = Mathf.Min (wishspd, airCap);
// Determine veer amount
var currentspeed = Vector3.Dot (velocity, wishdir);
// See how much to add
var addspeed = wishspd - currentspeed;
// If not adding any, done.
if (addspeed <= 0)
return Vector3.zero;
// Determine acceleration speed after acceleration
var accelspeed = accel * wishspeed * deltaTime;
// Cap it
accelspeed = Mathf.Min (accelspeed, addspeed);
var result = Vector3.zero;
// Adjust pmove vel.
for (int i = 0; i < 3; i++)
result [i] += accelspeed * wishdir [i];
return result;
}
/// <summary>
///
/// </summary>
/// <param name="wishdir"></param>
/// <param name="wishspeed"></param>
/// <param name="accel"></param>
/// <returns></returns>
public static Vector3 Accelerate (Vector3 currentVelocity, Vector3 wishdir, float wishspeed, float accel, float deltaTime, float surfaceFriction) {
// See if we are changing direction a bit
var currentspeed = Vector3.Dot (currentVelocity, wishdir);
// Reduce wishspeed by the amount of veer.
var addspeed = wishspeed - currentspeed;
// If not going to add any speed, done.
if (addspeed <= 0)
return Vector3.zero;
// Determine amount of accleration.
var accelspeed = accel * deltaTime * wishspeed * surfaceFriction;
// Cap at addspeed
if (accelspeed > addspeed)
accelspeed = addspeed;
var result = Vector3.zero;
// Adjust velocity.
for (int i = 0; i < 3; i++)
result [i] += accelspeed * wishdir [i];
return result;
}
/// <summary>
///
/// </summary>
/// <param name="velocity"></param>
/// <param name="origin"></param>
/// <param name="firstDestination"></param>
/// <param name="firstTrace"></param>
/// <returns></returns>
public static int Reflect (ref Vector3 velocity, Collider collider, Vector3 origin, float deltaTime) {
float d;
var newVelocity = Vector3.zero;
var blocked = 0; // Assume not blocked
var numplanes = 0; // and not sliding along any planes
var originalVelocity = velocity; // Store original velocity
var primalVelocity = velocity;
var allFraction = 0f;
var timeLeft = deltaTime; // Total time for this movement operation.
for (int bumpcount = 0; bumpcount < numBumps; bumpcount++) {
if (velocity.magnitude == 0f)
break;
// Assume we can move all the way from the current origin to the
// end point.
var end = VectorExtensions.VectorMa (origin, timeLeft, velocity);
var trace = Tracer.TraceCollider (collider, origin, end, groundLayerMask);
allFraction += trace.fraction;
if (trace.fraction > 0) {
// actually covered some distance
originalVelocity = velocity;
numplanes = 0;
}
// If we covered the entire distance, we are done
// and can return.
if (trace.fraction == 1)
break; // moved the entire distance
// If the plane we hit has a high z component in the normal, then
// it's probably a floor
if (trace.planeNormal.y > SurfSlope)
blocked |= 1; // floor
// If the plane has a zero z component in the normal, then it's a
// step or wall
if (trace.planeNormal.y == 0)
blocked |= 2; // step / wall
// Reduce amount of m_flFrameTime left by total time left * fraction
// that we covered.
timeLeft -= timeLeft * trace.fraction;
// Did we run out of planes to clip against?
if (numplanes >= maxClipPlanes) {
// this shouldn't really happen
// Stop our movement if so.
velocity = Vector3.zero;
//Con_DPrintf("Too many planes 4\n");
break;
}
// Set up next clipping plane
_planes [numplanes] = trace.planeNormal;
numplanes++;
// modify original_velocity so it parallels all of the clip planes
//
// reflect player velocity
// Only give this a try for first impact plane because you can get yourself stuck in an acute corner by jumping in place
// and pressing forward and nobody was really using this bounce/reflection feature anyway...
if (numplanes == 1) {
for (int i = 0; i < numplanes; i++) {
if (_planes [i] [1] > SurfSlope) {
// floor or slope
return blocked;
//ClipVelocity(originalVelocity, _planes[i], ref newVelocity, 1f);
//originalVelocity = newVelocity;
} else
ClipVelocity (originalVelocity, _planes [i], ref newVelocity, 1f);
}
velocity = newVelocity;
originalVelocity = newVelocity;
} else {
int i = 0;
for (i = 0; i < numplanes; i++) {
ClipVelocity (originalVelocity, _planes [i], ref velocity, 1);
int j = 0;
for (j = 0; j < numplanes; j++) {
if (j != i) {
// Are we now moving against this plane?
if (Vector3.Dot (velocity, _planes [j]) < 0)
break;
}
}
if (j == numplanes) // Didn't have to clip, so we're ok
break;
}
// Did we go all the way through plane set
if (i != numplanes) { // go along this plane
// pmove.velocity is set in clipping call, no need to set again.
;
} else { // go along the crease
if (numplanes != 2) {
velocity = Vector3.zero;
break;
}
var dir = Vector3.Cross (_planes [0], _planes [1]).normalized;
d = Vector3.Dot (dir, velocity);
velocity = dir * d;
}
//
// if original velocity is against the original velocity, stop dead
// to avoid tiny occilations in sloping corners
//
d = Vector3.Dot (velocity, primalVelocity);
if (d <= 0f) {
//Con_DPrintf("Back\n");
velocity = Vector3.zero;
break;
}
}
}
if (allFraction == 0f)
velocity = Vector3.zero;
// Check if they slammed into a wall
//float fSlamVol = 0.0f;
//var primal2dLen = new Vector2(primal_velocity.x, primal_velocity.z).magnitude;
//var vel2dLen = new Vector2(_moveData.Velocity.x, _moveData.Velocity.z).magnitude;
//float fLateralStoppingAmount = primal2dLen - vel2dLen;
//if (fLateralStoppingAmount > PLAYER_MAX_SAFE_FALL_SPEED * 2.0f)
//{
// fSlamVol = 1.0f;
//}
//else if (fLateralStoppingAmount > PLAYER_MAX_SAFE_FALL_SPEED)
//{
// fSlamVol = 0.85f;
//}
//PlayerRoughLandingEffects(fSlamVol);
return blocked;
}
/// <summary>
///
/// </summary>
/// <param name="input"></param>
/// <param name="normal"></param>
/// <param name="output"></param>
/// <param name="overbounce"></param>
/// <returns></returns>
public static int ClipVelocity (Vector3 input, Vector3 normal, ref Vector3 output, float overbounce) {
var angle = normal [1];
var blocked = 0x00; // Assume unblocked.
if (angle > 0) // If the plane that is blocking us has a positive z component, then assume it's a floor.
blocked |= 0x01; //
if (angle == 0) // If the plane has no Z, it is vertical (wall/step)
blocked |= 0x02; //
// Determine how far along plane to slide based on incoming direction.
var backoff = Vector3.Dot (input, normal) * overbounce;
for (int i = 0; i < 3; i++) {
var change = normal [i] * backoff;
output [i] = input [i] - change;
}
// iterate once to make sure we aren't still moving through the plane
float adjust = Vector3.Dot (output, normal);
if (adjust < 0.0f) {
output -= (normal * adjust);
// Msg( "Adjustment = %lf\n", adjust );
}
// Return blocking flags.
return blocked;
}
/// <summary>
///
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
public static void GetCapsulePoints (CapsuleCollider capc, Vector3 origin, out Vector3 p1, out Vector3 p2) {
var distanceToPoints = capc.height / 2f - capc.radius;
p1 = origin + capc.center + Vector3.up * distanceToPoints;
p2 = origin + capc.center - Vector3.up * distanceToPoints;
}
}
}
| 0 | 0.902853 | 1 | 0.902853 | game-dev | MEDIA | 0.990847 | game-dev | 0.995834 | 1 | 0.995834 |
The-Final-Nights/The-Final-Nights | 7,878 | code/game/machinery/iv_drip.dm | #define IV_TAKING 0
#define IV_INJECTING 1
/obj/machinery/iv_drip
name = "\improper IV drip"
desc = "An IV drip with an advanced infusion pump that can both drain blood into and inject liquids from attached containers. Blood packs are processed at an accelerated rate. Alt-Click to change the transfer rate."
icon = 'icons/obj/iv_drip.dmi'
icon_state = "iv_drip"
anchored = FALSE
mouse_drag_pointer = MOUSE_ACTIVE_POINTER
var/mob/living/carbon/attached
var/mode = IV_INJECTING
var/dripfeed = FALSE
var/obj/item/reagent_containers/beaker
var/static/list/drip_containers = typecacheof(list(/obj/item/reagent_containers/blood,
/obj/item/reagent_containers/food,
/obj/item/reagent_containers/glass,
/obj/item/reagent_containers/chem_pack))
/obj/machinery/iv_drip/Initialize(mapload)
. = ..()
update_icon()
/obj/machinery/iv_drip/Destroy()
attached = null
QDEL_NULL(beaker)
return ..()
/obj/machinery/iv_drip/update_icon_state()
. = ..()
if(attached)
if(mode)
icon_state = "injecting"
else
icon_state = "donating"
else
if(mode)
icon_state = "injectidle"
else
icon_state = "donateidle"
/obj/machinery/iv_drip/update_overlays()
. = ..()
if(beaker)
if(attached)
. += "beakeractive"
else
. += "beakeridle"
if(beaker.reagents.total_volume)
var/mutable_appearance/filling_overlay = mutable_appearance('icons/obj/iv_drip.dmi', "reagent")
var/percent = round((beaker.reagents.total_volume / beaker.volume) * 100)
switch(percent)
if(0 to 9)
filling_overlay.icon_state = "reagent0"
if(10 to 24)
filling_overlay.icon_state = "reagent10"
if(25 to 49)
filling_overlay.icon_state = "reagent25"
if(50 to 74)
filling_overlay.icon_state = "reagent50"
if(75 to 79)
filling_overlay.icon_state = "reagent75"
if(80 to 90)
filling_overlay.icon_state = "reagent80"
if(91 to INFINITY)
filling_overlay.icon_state = "reagent100"
filling_overlay.color = mix_color_from_reagents(beaker.reagents.reagent_list)
. += filling_overlay
/obj/machinery/iv_drip/MouseDrop(mob/living/target)
. = ..()
if(!ishuman(usr) || !usr.canUseTopic(src, BE_CLOSE) || !isliving(target))
return
if(attached)
visible_message("<span class='warning'>[attached] is detached from [src].</span>")
attached = null
update_icon()
return
if(!target.has_dna())
to_chat(usr, "<span class='danger'>The drip beeps: Warning, incompatible creature!</span>")
return
if(Adjacent(target) && usr.Adjacent(target))
if(beaker)
usr.visible_message("<span class='warning'>[usr] attaches [src] to [target].</span>", "<span class='notice'>You attach [src] to [target].</span>")
log_combat(usr, target, "attached", src, "containing: [beaker.name] - ([beaker.reagents.log_list()])")
add_fingerprint(usr)
attached = target
START_PROCESSING(SSmachines, src)
update_icon()
else
to_chat(usr, "<span class='warning'>There's nothing attached to the IV drip!</span>")
/obj/machinery/iv_drip/attackby(obj/item/W, mob/user, params)
if(is_type_in_typecache(W, drip_containers) || IS_EDIBLE(W))
if(beaker)
to_chat(user, "<span class='warning'>[beaker] is already loaded on [src]!</span>")
return
if(!user.transferItemToLoc(W, src))
return
beaker = W
to_chat(user, "<span class='notice'>You attach [W] to [src].</span>")
user.log_message("attached a [W] to [src] at [AREACOORD(src)] containing ([beaker.reagents.log_list()])", LOG_ATTACK)
add_fingerprint(user)
update_icon()
return
else
return ..()
/obj/machinery/iv_drip/deconstruct(disassembled = TRUE)
if(!(flags_1 & NODECONSTRUCT_1))
new /obj/item/stack/sheet/metal(loc)
qdel(src)
/obj/machinery/iv_drip/process(delta_time)
if(!attached)
return PROCESS_KILL
if(!(get_dist(src, attached) <= 1 && isturf(attached.loc)))
to_chat(attached, "<span class='userdanger'>The IV drip needle is ripped out of you!</span>")
attached.apply_damage(3, BRUTE, pick(BODY_ZONE_R_ARM, BODY_ZONE_L_ARM))
attached = null
update_icon()
return PROCESS_KILL
if(beaker)
// Give blood
if(mode)
if(beaker.reagents.total_volume)
var/transfer_amount = 5
if (dripfeed)
transfer_amount = 1
if(istype(beaker, /obj/item/reagent_containers/blood))
// speed up transfer on blood packs
transfer_amount *= 2
beaker.reagents.trans_to(attached, transfer_amount * delta_time * 0.5, methods = INJECT, show_message = FALSE) //make reagents reacts, but don't spam messages
update_icon()
// Take blood
else
var/amount = beaker.reagents.maximum_volume - beaker.reagents.total_volume
amount = min(amount, 4) * delta_time * 0.5
// If the beaker is full, ping
if(!amount)
if(prob(5))
visible_message("<span class='hear'>[src] pings.</span>")
return
// If the human is losing too much blood, beep.
if(attached.blood_volume < BLOOD_VOLUME_SAFE && prob(5))
visible_message("<span class='hear'>[src] beeps loudly.</span>")
playsound(loc, 'sound/machines/twobeep_high.ogg', 50, TRUE)
attached.transfer_blood_to(beaker, amount)
update_icon()
/obj/machinery/iv_drip/attack_hand(mob/user, list/modifiers)
. = ..()
if(.)
return
if(!ishuman(user))
return
if(attached)
visible_message("<span class='notice'>[attached] is detached from [src].</span>")
attached = null
update_icon()
return
else if(beaker)
eject_beaker(user)
else
toggle_mode()
/obj/machinery/iv_drip/attack_hand_secondary(mob/user, modifiers)
. = ..()
if(. == SECONDARY_ATTACK_CANCEL_ATTACK_CHAIN)
return
if(dripfeed)
dripfeed = FALSE
to_chat(usr, "<span class='notice'>You loosen the valve to speed up the [src].</span>")
else
dripfeed = TRUE
to_chat(usr, "<span class='notice'>You tighten the valve to slowly drip-feed the contents of [src].</span>")
/obj/machinery/iv_drip/verb/eject_beaker()
set category = "Object"
set name = "Remove IV Container"
set src in view(1)
if(!isliving(usr))
to_chat(usr, "<span class='warning'>You can't do that!</span>")
return
if (!usr.canUseTopic())
return
if(usr.incapacitated())
return
if(beaker)
beaker.forceMove(drop_location())
beaker.dropped() //TFN ADDITION
beaker = null
update_icon()
/obj/machinery/iv_drip/verb/toggle_mode()
set category = "Object"
set name = "Toggle Mode"
set src in view(1)
if(!isliving(usr))
to_chat(usr, "<span class='warning'>You can't do that!</span>")
return
if (!usr.canUseTopic())
return
if(usr.incapacitated())
return
mode = !mode
to_chat(usr, "<span class='notice'>The IV drip is now [mode ? "injecting" : "taking blood"].</span>")
update_icon()
/obj/machinery/iv_drip/examine(mob/user)
. = ..()
if(get_dist(user, src) > 2)
return
. += "[src] is [mode ? "injecting" : "taking blood"]."
if(beaker)
if(beaker.reagents && beaker.reagents.reagent_list.len)
. += "<span class='notice'>Attached is \a [beaker] with [beaker.reagents.total_volume] units of liquid.</span>"
else
. += "<span class='notice'>Attached is an empty [beaker.name].</span>"
else
. += "<span class='notice'>No chemicals are attached.</span>"
. += "<span class='notice'>[attached ? attached : "No one"] is attached.</span>"
/obj/machinery/iv_drip/saline
name = "saline drip"
desc = "An all-you-can-drip saline canister designed to supply a hospital without running out, with a scary looking pump rigged to inject saline into containers, but filling people directly might be a bad idea."
icon_state = "saline"
density = TRUE
/obj/machinery/iv_drip/saline/Initialize(mapload)
. = ..()
beaker = new /obj/item/reagent_containers/glass/saline(src)
/obj/machinery/iv_drip/saline/ComponentInitialize()
. = ..()
AddElement(/datum/element/update_icon_blocker)
/obj/machinery/iv_drip/saline/eject_beaker()
return
/obj/machinery/iv_drip/saline/toggle_mode()
return
#undef IV_TAKING
#undef IV_INJECTING
| 0 | 0.93697 | 1 | 0.93697 | game-dev | MEDIA | 0.715023 | game-dev | 0.91468 | 1 | 0.91468 |
bibendovsky/ltjs | 1,260 | game/clientshelldll/tron/screenload.h | // ----------------------------------------------------------------------- //
//
// MODULE : ScreenLoad.h
//
// PURPOSE : Interface screen for loading saved games
//
// (c) 1999-2001 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#if !defined(_SCREEN_LOAD_H_)
#define _SCREEN_LOAD_H_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "basescreen.h"
struct SaveGameData
{
SaveGameData() {szWorldName[0] = LTNULL;szUserName[0] = LTNULL;szTime[0] = LTNULL;}
char szWorldName[128];
char szUserName[128];
char szTime[128];
};
class CScreenLoad : public CBaseScreen
{
public:
CScreenLoad();
virtual ~CScreenLoad();
LTBOOL Build();
void OnFocus(LTBOOL bFocus);
LTBOOL HandleKeyDown(int key, int rep);
protected:
uint32 OnCommand(uint32 dwCommand, uint32 dwParam1, uint32 dwParam2);
void BuildSavedLevelLists();
void ClearSavedLevelLists();
void ParseSaveString(char const* pszWorldName, char const* pszTitle, time_t const& saveTime, SaveGameData *pSG, bool bUserName);
bool BuildSaveControls( char const* pszIniKey, uint32 nCommandId, uint32 nControlHelpStringId,
bool bUserName );
};
#endif // !defined(_SCREEN_LOAD_H_) | 0 | 0.716759 | 1 | 0.716759 | game-dev | MEDIA | 0.964529 | game-dev | 0.733195 | 1 | 0.733195 |
lllyasviel/YGOProUnity_V2 | 2,092 | Assets/NGUI/Scripts/Tweening/TweenRotation.cs | //----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2015 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the object's rotation.
/// </summary>
[AddComponentMenu("NGUI/Tween/Tween Rotation")]
public class TweenRotation : UITweener
{
public Vector3 from;
public Vector3 to;
public bool quaternionLerp = false;
Transform mTrans;
public Transform cachedTransform { get { if (mTrans == null) mTrans = transform; return mTrans; } }
[System.Obsolete("Use 'value' instead")]
public Quaternion rotation { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public Quaternion value { get { return cachedTransform.localRotation; } set { cachedTransform.localRotation = value; } }
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished)
{
value = quaternionLerp ? Quaternion.Slerp(Quaternion.Euler(from), Quaternion.Euler(to), factor) :
Quaternion.Euler(new Vector3(
Mathf.Lerp(from.x, to.x, factor),
Mathf.Lerp(from.y, to.y, factor),
Mathf.Lerp(from.z, to.z, factor)));
}
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenRotation Begin (GameObject go, float duration, Quaternion rot)
{
TweenRotation comp = UITweener.Begin<TweenRotation>(go, duration);
comp.from = comp.value.eulerAngles;
comp.to = rot.eulerAngles;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value.eulerAngles; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value.eulerAngles; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = Quaternion.Euler(from); }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = Quaternion.Euler(to); }
}
| 0 | 0.955763 | 1 | 0.955763 | game-dev | MEDIA | 0.881136 | game-dev | 0.889397 | 1 | 0.889397 |
rj00a/evenio | 9,705 | src/event/targeted.rs | use alloc::borrow::Cow;
use core::alloc::Layout;
use core::any::TypeId;
use core::ops::Index;
pub use evenio_macros::TargetedEvent;
use super::global::GlobalEvent;
use super::{Event, EventDescriptor, EventKind, EventPtr, Mutability};
use crate::archetype::Archetype;
use crate::drop::DropFn;
use crate::entity::EntityLocation;
use crate::handler::{HandlerConfig, HandlerInfo, HandlerParam, InitError};
use crate::map::{Entry, TypeIdMap};
use crate::slot_map::{Key, SlotMap};
use crate::sparse::SparseIndex;
use crate::world::{UnsafeWorldCell, World};
/// An event which is directed at a particular entity.
///
/// This trait is automatically implemented for all types which implement
/// `Event<EventIdx = TargetedEventIdx>`. Use the derive macro to create the
/// appropriate implementation of [`Event`].
///
/// This trait is intended to be mutually exclusive with [`GlobalEvent`].
///
/// # Deriving
///
/// ```
/// use evenio::prelude::*;
///
/// #[derive(TargetedEvent)]
/// struct MyEvent {
/// example_data: i32,
/// }
/// ```
///
/// Due to language limitations, types with generic type params will
/// have a `T: 'static` bound in the generated impl.
///
/// ```
/// use evenio::prelude::*;
///
/// // `T: 'static` is required for this to impl `Event`.
/// #[derive(TargetedEvent)]
/// struct TypeWithGeneric<T>(T);
/// ```
pub trait TargetedEvent: Event<EventIdx = TargetedEventIdx> {}
impl<E: Event<EventIdx = TargetedEventIdx>> TargetedEvent for E {}
/// Stores metadata for all [`Event`]s in the world.
///
/// This can be obtained in a handler by using the `&Events` handler
/// parameter.
///
/// ```
/// # use evenio::prelude::*;
/// # use evenio::event::TargetedEvents;
/// #
/// # #[derive(GlobalEvent)] struct E;
/// #
/// # let mut world = World::new();
/// world.add_handler(|_: Receiver<E>, events: &TargetedEvents| {});
#[derive(Debug)]
pub struct TargetedEvents {
infos: SlotMap<TargetedEventInfo>,
by_type_id: TypeIdMap<TargetedEventId>,
}
impl TargetedEvents {
pub(crate) fn new() -> Self {
Self {
infos: SlotMap::new(),
by_type_id: TypeIdMap::default(),
}
}
pub(crate) fn add(&mut self, desc: EventDescriptor) -> (TargetedEventId, bool) {
let mut info = TargetedEventInfo {
id: TargetedEventId::NULL,
name: desc.name,
kind: desc.kind,
type_id: desc.type_id,
layout: desc.layout,
drop: desc.drop,
mutability: desc.mutability,
};
let insert = || {
TargetedEventId(
self.infos
.insert_with(|id| {
info.id = TargetedEventId(id);
info
})
.expect("too many targeted events"),
)
};
if let Some(type_id) = desc.type_id {
match self.by_type_id.entry(type_id) {
Entry::Vacant(v) => (*v.insert(insert()), true),
Entry::Occupied(o) => (*o.get(), false),
}
} else {
(insert(), true)
}
}
/// Gets the [`TargetedEventInfo`] of the given event. Returns `None` if the
/// ID is invalid.
pub fn get(&self, id: TargetedEventId) -> Option<&TargetedEventInfo> {
self.infos.get(id.0)
}
/// Gets the [`TargetedEventInfo`] for an event using its
/// [`TargetedEventIdx`]. Returns `None` if the index is invalid.
#[inline]
pub fn get_by_index(&self, idx: TargetedEventIdx) -> Option<&TargetedEventInfo> {
Some(self.infos.get_by_index(idx.0)?.1)
}
/// Gets the [`TargetedEventInfo`] for an event using its [`TypeId`].
/// Returns `None` if the `TypeId` does not map to an event.
pub fn get_by_type_id(&self, type_id: TypeId) -> Option<&TargetedEventInfo> {
let idx = *self.by_type_id.get(&type_id)?;
Some(unsafe { self.get(idx).unwrap_unchecked() })
}
/// Does the given event exist in the world?
pub fn contains(&self, id: TargetedEventId) -> bool {
self.get(id).is_some()
}
pub(crate) fn remove(&mut self, id: TargetedEventId) -> Option<TargetedEventInfo> {
let info = self.infos.remove(id.0)?;
if let Some(type_id) = info.type_id {
self.by_type_id.remove(&type_id);
}
Some(info)
}
/// Returns an iterator over all event infos.
pub fn iter(&self) -> impl Iterator<Item = &TargetedEventInfo> {
self.infos.iter().map(|(_, v)| v)
}
}
impl Index<TargetedEventId> for TargetedEvents {
type Output = TargetedEventInfo;
fn index(&self, index: TargetedEventId) -> &Self::Output {
if let Some(info) = self.get(index) {
info
} else {
panic!("no such targeted event with ID of {index:?} exists")
}
}
}
impl Index<TargetedEventIdx> for TargetedEvents {
type Output = TargetedEventInfo;
fn index(&self, index: TargetedEventIdx) -> &Self::Output {
if let Some(info) = self.get_by_index(index) {
info
} else {
panic!("no such targeted event with index of {index:?} exists")
}
}
}
impl Index<TypeId> for TargetedEvents {
type Output = TargetedEventInfo;
fn index(&self, index: TypeId) -> &Self::Output {
if let Some(info) = self.get_by_type_id(index) {
info
} else {
panic!("no such targeted event with type ID of {index:?} exists")
}
}
}
unsafe impl HandlerParam for &'_ TargetedEvents {
type State = ();
type This<'a> = &'a TargetedEvents;
fn init(_world: &mut World, _config: &mut HandlerConfig) -> Result<Self::State, InitError> {
Ok(())
}
unsafe fn get<'a>(
_state: &'a mut Self::State,
_info: &'a HandlerInfo,
_event_ptr: EventPtr<'a>,
_target_location: EntityLocation,
world: UnsafeWorldCell<'a>,
) -> Self::This<'a> {
world.targeted_events()
}
fn refresh_archetype(_state: &mut Self::State, _arch: &Archetype) {}
fn remove_archetype(_state: &mut Self::State, _arch: &Archetype) {}
}
/// Contains all the metadata for an added [`TargetedEvent`].
#[derive(Debug)]
pub struct TargetedEventInfo {
name: Cow<'static, str>,
id: TargetedEventId,
kind: EventKind,
type_id: Option<TypeId>,
layout: Layout,
drop: DropFn,
mutability: Mutability,
}
impl TargetedEventInfo {
/// Gets the name of the event.
///
/// This name is intended for debugging purposes and should not be relied
/// upon for correctness.
pub fn name(&self) -> &str {
&self.name
}
/// Gets the ID of the event.
pub fn id(&self) -> TargetedEventId {
self.id
}
/// Gets the [`EventKind`] of the event.
pub fn kind(&self) -> EventKind {
self.kind
}
/// Gets the [`TypeId`] of the event, if any.
pub fn type_id(&self) -> Option<TypeId> {
self.type_id
}
/// Gets the [`Layout`] of the event.
pub fn layout(&self) -> Layout {
self.layout
}
/// Gets the [`DropFn`] of the event.
pub fn drop(&self) -> DropFn {
self.drop
}
/// Gets the [mutability] of the event
///
/// [mutability]: Event::Mutability
pub fn mutability(&self) -> Mutability {
self.mutability
}
}
/// Lightweight identifier for a targeted event type.
///
/// Event identifiers are implemented using an [index] and a generation count.
/// The generation count ensures that IDs from despawned events are not reused
/// by new events.
///
/// An event identifier is only meaningful in the [`World`] it was created
/// from. Attempting to use an event ID in a different world will have
/// unexpected results.
///
/// [index]: TargetedEventIdx
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash, Debug)]
pub struct TargetedEventId(Key);
impl TargetedEventId {
/// The global event ID which never identifies a live entity. This is the
/// default value for `EntityId`.
pub const NULL: Self = Self(Key::NULL);
/// Creates a new entity ID from an index and generation count. Returns
/// `None` if a valid ID is not formed.
pub const fn new(index: u32, generation: u32) -> Option<Self> {
match Key::new(index, generation) {
Some(k) => Some(Self(k)),
None => None,
}
}
/// Returns the index of this ID.
pub const fn index(self) -> TargetedEventIdx {
TargetedEventIdx(self.0.index())
}
/// Returns the generation count of this ID.
pub const fn generation(self) -> u32 {
self.0.generation().get()
}
}
/// A [`TargetedEventId`] with the generation count stripped out.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct TargetedEventIdx(pub u32);
unsafe impl SparseIndex for TargetedEventIdx {
const MAX: Self = Self(u32::MAX);
fn index(self) -> usize {
self.0.index()
}
fn from_index(idx: usize) -> Self {
Self(u32::from_index(idx))
}
}
/// An [`Event`] sent immediately after a new targeted event is added to the
/// world.
///
/// Contains the [`TargetedEventId`] of the added event.
#[derive(GlobalEvent, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct AddTargetedEvent(pub TargetedEventId);
/// An [`Event`] sent immediately before a targeted event is removed from the
/// world.
///
/// Contains the [`TargetedEventId`] of the event to be removed.
#[derive(GlobalEvent, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct RemoveTargetedEvent(pub TargetedEventId);
| 0 | 0.878018 | 1 | 0.878018 | game-dev | MEDIA | 0.718443 | game-dev | 0.945939 | 1 | 0.945939 |
gridengine/gridengine | 3,632 | source/libs/sgeobj/sge_manop.c | /*___INFO__MARK_BEGIN__*/
/*************************************************************************
*
* The Contents of this file are made available subject to the terms of
* the Sun Industry Standards Source License Version 1.2
*
* Sun Microsystems Inc., March, 2001
*
*
* Sun Industry Standards Source License Version 1.2
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.2 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://gridengine.sunsource.net/Gridengine_SISSL_license.html
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2001 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
************************************************************************/
/*___INFO__MARK_END__*/
#include "uti/sge_rmon.h"
#include "cull/cull.h"
#include "sgeobj/sge_manop.h"
#include "sgeobj/sge_object.h"
/****** sgeobj/manop/manop_is_manager() ***************************************
* NAME
* manop_is_manager() -- is a certain user manager?
*
* SYNOPSIS
* bool manop_is_manager(const char *user_name)
*
* FUNCTION
* Checks if the user given by user name is a manager.
*
* INPUTS
* const char *user_name - user name
*
* RESULT
* bool - true or false
*
* NOTES
* Operator/Manager should be a property of a user.
* Then the function would be user_is_manager - much more plausible
*
* SEE ALSO
* gdi/manop/manop_is_operator()
******************************************************************************/
bool manop_is_manager(const char *user_name)
{
bool ret = false;
DENTER(TOP_LAYER, "manop_is_manager");
if (user_name == NULL) {
ret = false;
} else if (lGetElemStr(*object_type_get_master_list(SGE_TYPE_MANAGER),
UM_name, user_name) != NULL) {
ret = true;
}
DEXIT;
return ret;
}
/****** sgeobj/manop/manop_is_operator() **************************************
* NAME
* manop_is_operator() -- is a certain user operator?
*
* SYNOPSIS
* bool manop_is_operator(const char *user_name)
*
* FUNCTION
* Checks if the user given by user name is a operator.
* A manager is implicitly also an operator.
*
* INPUTS
* const char *user_name - user name
*
* RESULT
* bool - true or false
*
* NOTES
* Operator/Manager should be a property of a user.
* Then the function would be user_is_operator - much more plausible
*
* SEE ALSO
* gdi/manop/manop_is_manager()
******************************************************************************/
bool manop_is_operator(const char *user_name)
{
bool ret = false;
DENTER(TOP_LAYER, "manop_is_operator");
if (user_name == NULL) {
ret = false;
} else if(lGetElemStr(*object_type_get_master_list(SGE_TYPE_OPERATOR),
UO_name, user_name) != NULL) {
ret = true;
} else if (lGetElemStr(*object_type_get_master_list(SGE_TYPE_MANAGER),
UM_name, user_name) != NULL) {
ret = true;
}
DRETURN(ret);
}
| 0 | 0.776063 | 1 | 0.776063 | game-dev | MEDIA | 0.469219 | game-dev | 0.592793 | 1 | 0.592793 |
daleao/sdv | 1,184 | Professions/Framework/Patchers/Fishing/PondQueryMenuCtorPatcher.cs | namespace DaLion.Professions.Framework.Patchers.Fishing;
#region using directives
using DaLion.Shared.Harmony;
using HarmonyLib;
using StardewValley.Buildings;
using StardewValley.Menus;
#endregion using directives
[UsedImplicitly]
internal sealed class PondQueryMenuCtorPatcher : HarmonyPatcher
{
/// <summary>Initializes a new instance of the <see cref="PondQueryMenuCtorPatcher"/> class.</summary>
/// <param name="harmonizer">The <see cref="Harmonizer"/> instance that manages this patcher.</param>
/// <param name="logger">A <see cref="Logger"/> instance.</param>
internal PondQueryMenuCtorPatcher(Harmonizer harmonizer, Logger logger)
: base(harmonizer, logger)
{
this.Target = this.RequireConstructor<PondQueryMenu>(typeof(FishPond));
}
#region harmony patches
/// <summary>Patch to adjust fish pond query menu for Aquarist increased max capacity.</summary>
[HarmonyPostfix]
[UsedImplicitly]
private static void PondQueryMenuDrawPostfix(FishPond fish_pond)
{
if (fish_pond.maxOccupants.Value > 10)
{
PondQueryMenu.height += 32;
}
}
#endregion harmony patches
}
| 0 | 0.653759 | 1 | 0.653759 | game-dev | MEDIA | 0.85312 | game-dev | 0.729766 | 1 | 0.729766 |
GaijinEntertainment/DagorEngine | 4,052 | prog/3rdPartyLibs/phys/bullet-3/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/// This file was created by Alex Silverman
#ifndef BT_BVH_TRIANGLE_MATERIAL_MESH_SHAPE_H
#define BT_BVH_TRIANGLE_MATERIAL_MESH_SHAPE_H
#include "btBvhTriangleMeshShape.h"
#include "btMaterial.h"
///The BvhTriangleMaterialMeshShape extends the btBvhTriangleMeshShape. Its main contribution is the interface into a material array, which allows per-triangle friction and restitution.
ATTRIBUTE_ALIGNED16(class)
btMultimaterialTriangleMeshShape : public btBvhTriangleMeshShape
{
btAlignedObjectArray<btMaterial *> m_materialList;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btMultimaterialTriangleMeshShape(btStridingMeshInterface * meshInterface, bool useQuantizedAabbCompression, bool buildBvh = true) : btBvhTriangleMeshShape(meshInterface, useQuantizedAabbCompression, buildBvh)
{
m_shapeType = MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE;
const unsigned char *vertexbase;
int numverts;
PHY_ScalarType type;
int stride;
const unsigned char *indexbase;
int indexstride;
int numfaces;
PHY_ScalarType indicestype;
//m_materialLookup = (int**)(btAlignedAlloc(sizeof(int*) * meshInterface->getNumSubParts(), 16));
for (int i = 0; i < meshInterface->getNumSubParts(); i++)
{
m_meshInterface->getLockedReadOnlyVertexIndexBase(
&vertexbase,
numverts,
type,
stride,
&indexbase,
indexstride,
numfaces,
indicestype,
i);
//m_materialLookup[i] = (int*)(btAlignedAlloc(sizeof(int) * numfaces, 16));
}
}
///optionally pass in a larger bvh aabb, used for quantization. This allows for deformations within this aabb
btMultimaterialTriangleMeshShape(btStridingMeshInterface * meshInterface, bool useQuantizedAabbCompression, const btVector3 &bvhAabbMin, const btVector3 &bvhAabbMax, bool buildBvh = true) : btBvhTriangleMeshShape(meshInterface, useQuantizedAabbCompression, bvhAabbMin, bvhAabbMax, buildBvh)
{
m_shapeType = MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE;
const unsigned char *vertexbase;
int numverts;
PHY_ScalarType type;
int stride;
const unsigned char *indexbase;
int indexstride;
int numfaces;
PHY_ScalarType indicestype;
//m_materialLookup = (int**)(btAlignedAlloc(sizeof(int*) * meshInterface->getNumSubParts(), 16));
for (int i = 0; i < meshInterface->getNumSubParts(); i++)
{
m_meshInterface->getLockedReadOnlyVertexIndexBase(
&vertexbase,
numverts,
type,
stride,
&indexbase,
indexstride,
numfaces,
indicestype,
i);
//m_materialLookup[i] = (int*)(btAlignedAlloc(sizeof(int) * numfaces * 2, 16));
}
}
virtual ~btMultimaterialTriangleMeshShape()
{
/*
for(int i = 0; i < m_meshInterface->getNumSubParts(); i++)
{
btAlignedFree(m_materialValues[i]);
m_materialLookup[i] = NULL;
}
btAlignedFree(m_materialValues);
m_materialLookup = NULL;
*/
}
//debugging
virtual const char *getName() const { return "MULTIMATERIALTRIANGLEMESH"; }
///Obtains the material for a specific triangle
const btMaterial *getMaterialProperties(int partID, int triIndex);
};
#endif //BT_BVH_TRIANGLE_MATERIAL_MESH_SHAPE_H
| 0 | 0.965916 | 1 | 0.965916 | game-dev | MEDIA | 0.904259 | game-dev | 0.976884 | 1 | 0.976884 |
lavbubl/CompleteCook | 1,158 | extensions/gameframe_native/autogen.gml | #define gameframe_mouse_in_window
/// gameframe_mouse_in_window()->bool
var _buf = gameframe_prepare_buffer(1);
return gameframe_mouse_in_window_raw(buffer_get_address(_buf), 1);
#define gameframe_init_raw
/// gameframe_init_raw()
var _buf = gameframe_prepare_buffer(8);
buffer_write(_buf, buffer_u64, int64(window_handle()));
gameframe_init_raw_raw(buffer_get_address(_buf), 8);
#define gameframe_syscommand
/// gameframe_syscommand(_sc:number)
var _buf = gameframe_prepare_buffer(8);
buffer_write(_buf, buffer_f64, argument0);
gameframe_syscommand_raw(buffer_get_address(_buf), 8);
#define gameframe_get_monitors_1
/// gameframe_get_monitors_1()->int
var _buf = gameframe_prepare_buffer(1);
return gameframe_get_monitors_1_raw(buffer_get_address(_buf), 1);
#define gameframe_get_double_click_time
/// gameframe_get_double_click_time()->int
var _buf = gameframe_prepare_buffer(1);
return gameframe_get_double_click_time_raw(buffer_get_address(_buf), 1);
#define gameframe_is_natively_minimized
/// gameframe_is_natively_minimized()->bool
var _buf = gameframe_prepare_buffer(1);
return gameframe_is_natively_minimized_raw(buffer_get_address(_buf), 1);
| 0 | 0.639868 | 1 | 0.639868 | game-dev | MEDIA | 0.430922 | game-dev | 0.663238 | 1 | 0.663238 |
Hoyotoon/HoyoToon | 10,468 | Scripts/Editor/Manager/UI/Core/HoyoToonUIComponentManager.cs | using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace HoyoToon.UI.Core
{
/// <summary>
/// Manager for HoyoToon UI components, handling component lifecycle and communication
/// </summary>
public class HoyoToonUIComponentManager
{
#region Singleton
private static HoyoToonUIComponentManager _instance;
public static HoyoToonUIComponentManager Instance
{
get
{
if (_instance == null)
_instance = new HoyoToonUIComponentManager();
return _instance;
}
}
#endregion
#region Fields
private Dictionary<string, HoyoToonUIComponent> registeredComponents = new Dictionary<string, HoyoToonUIComponent>();
private Dictionary<string, HoyoToonUITabComponent> registeredTabs = new Dictionary<string, HoyoToonUITabComponent>();
private string activeTabId = null;
#endregion
#region Events
/// <summary>
/// Event fired when a component is registered
/// </summary>
public event Action<string, HoyoToonUIComponent> ComponentRegistered;
/// <summary>
/// Event fired when a component is unregistered
/// </summary>
public event Action<string> ComponentUnregistered;
/// <summary>
/// Event fired when the active tab changes
/// </summary>
public event Action<string, string> ActiveTabChanged; // oldTabId, newTabId
/// <summary>
/// Event fired when a component triggers an event
/// </summary>
public event Action<ComponentEventArgs> ComponentEvent;
#endregion
#region Component Management
/// <summary>
/// Register a UI component
/// </summary>
public void RegisterComponent(HoyoToonUIComponent component)
{
if (component == null)
throw new ArgumentNullException(nameof(component));
var id = component.ComponentId;
if (registeredComponents.ContainsKey(id))
{
Debug.LogWarning($"Component with ID '{id}' is already registered. Replacing existing component.");
UnregisterComponent(id);
}
registeredComponents[id] = component;
// If it's a tab component, also register it in the tabs collection
if (component is HoyoToonUITabComponent tabComponent)
{
registeredTabs[id] = tabComponent;
}
ComponentRegistered?.Invoke(id, component);
}
/// <summary>
/// Unregister a UI component
/// </summary>
public void UnregisterComponent(string componentId)
{
if (registeredComponents.TryGetValue(componentId, out var component))
{
component.Cleanup();
registeredComponents.Remove(componentId);
registeredTabs.Remove(componentId);
ComponentUnregistered?.Invoke(componentId);
// If this was the active tab, clear it
if (activeTabId == componentId)
{
activeTabId = null;
}
}
}
/// <summary>
/// Get a registered component by ID
/// </summary>
public T GetComponent<T>(string componentId) where T : HoyoToonUIComponent
{
if (registeredComponents.TryGetValue(componentId, out var component) && component is T)
{
return (T)component;
}
return null;
}
/// <summary>
/// Get all registered components of a specific type
/// </summary>
public List<T> GetComponents<T>() where T : HoyoToonUIComponent
{
return registeredComponents.Values.OfType<T>().ToList();
}
/// <summary>
/// Check if a component is registered
/// </summary>
public bool IsComponentRegistered(string componentId)
{
return registeredComponents.ContainsKey(componentId);
}
/// <summary>
/// Initialize all registered components
/// </summary>
public void InitializeAllComponents()
{
foreach (var component in registeredComponents.Values)
{
if (!component.IsInitialized)
{
component.Initialize();
}
}
}
/// <summary>
/// Update all registered components with new data
/// </summary>
public void UpdateAllComponents(Dictionary<string, object> globalData = null)
{
foreach (var component in registeredComponents.Values)
{
component.UpdateComponent(globalData);
}
}
/// <summary>
/// Cleanup all registered components
/// </summary>
public void CleanupAllComponents()
{
foreach (var component in registeredComponents.Values.ToList())
{
component.Cleanup();
}
registeredComponents.Clear();
registeredTabs.Clear();
activeTabId = null;
}
#endregion
#region Tab Management
/// <summary>
/// Get all registered tab components
/// </summary>
public List<HoyoToonUITabComponent> GetAllTabs()
{
return registeredTabs.Values.ToList();
}
/// <summary>
/// Get tab component by ID
/// </summary>
public HoyoToonUITabComponent GetTab(string tabId)
{
registeredTabs.TryGetValue(tabId, out var tab);
return tab;
}
/// <summary>
/// Set the active tab
/// </summary>
public void SetActiveTab(string tabId)
{
if (activeTabId == tabId)
return; // Already active
var oldTabId = activeTabId;
// Deactivate current tab
if (!string.IsNullOrEmpty(activeTabId) && registeredTabs.TryGetValue(activeTabId, out var currentTab))
{
currentTab.OnTabDeactivated();
}
// Activate new tab
if (!string.IsNullOrEmpty(tabId) && registeredTabs.TryGetValue(tabId, out var newTab))
{
if (!newTab.IsInitialized)
{
newTab.Initialize();
}
newTab.OnTabActivated();
activeTabId = tabId;
}
else
{
activeTabId = null;
}
ActiveTabChanged?.Invoke(oldTabId, activeTabId);
}
/// <summary>
/// Get the currently active tab
/// </summary>
public HoyoToonUITabComponent GetActiveTab()
{
if (!string.IsNullOrEmpty(activeTabId) && registeredTabs.TryGetValue(activeTabId, out var tab))
{
return tab;
}
return null;
}
/// <summary>
/// Get quick actions from the active tab
/// </summary>
public List<QuickAction> GetActiveTabQuickActions()
{
var activeTab = GetActiveTab();
return activeTab?.GetQuickActions() ?? new List<QuickAction>();
}
#endregion
#region Event System
/// <summary>
/// Fire a component event
/// </summary>
public void FireComponentEvent(string componentId, string eventType, Dictionary<string, object> eventData = null)
{
var args = new ComponentEventArgs(componentId, eventType, eventData);
ComponentEvent?.Invoke(args);
}
/// <summary>
/// Subscribe to component events of a specific type
/// </summary>
public void SubscribeToComponentEvents(string eventType, Action<ComponentEventArgs> handler)
{
ComponentEvent += (args) =>
{
if (args.EventType == eventType)
{
handler(args);
}
};
}
#endregion
#region Utility Methods
/// <summary>
/// Get component statistics for debugging
/// </summary>
public ComponentManagerStats GetStats()
{
return new ComponentManagerStats
{
TotalComponents = registeredComponents.Count,
TotalTabs = registeredTabs.Count,
InitializedComponents = registeredComponents.Values.Count(c => c.IsInitialized),
ActiveTabId = activeTabId
};
}
/// <summary>
/// Validate component integrity
/// </summary>
public List<string> ValidateComponents()
{
var issues = new List<string>();
foreach (var kvp in registeredComponents)
{
var id = kvp.Key;
var component = kvp.Value;
if (component == null)
{
issues.Add($"Component '{id}' is null");
continue;
}
if (component.ComponentId != id)
{
issues.Add($"Component ID mismatch: registered as '{id}' but reports '{component.ComponentId}'");
}
if (component.RootElement == null && component.IsInitialized)
{
issues.Add($"Component '{id}' is marked as initialized but has no root element");
}
}
return issues;
}
#endregion
}
/// <summary>
/// Statistics about the component manager state
/// </summary>
public class ComponentManagerStats
{
public int TotalComponents { get; set; }
public int TotalTabs { get; set; }
public int InitializedComponents { get; set; }
public string ActiveTabId { get; set; }
public override string ToString()
{
return $"Components: {TotalComponents} ({InitializedComponents} initialized), Tabs: {TotalTabs}, Active Tab: {ActiveTabId ?? "None"}";
}
}
} | 0 | 0.622589 | 1 | 0.622589 | game-dev | MEDIA | 0.495973 | game-dev | 0.917657 | 1 | 0.917657 |
Espere-1119-Song/VideoNSA | 24,974 | ms-swift/fla/ops/attn/parallel.py | # -*- coding: utf-8 -*-
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
import warnings
from typing import Optional
import torch
import triton
import triton.language as tl
from einops import reduce
from fla.ops.utils import prepare_chunk_indices
from fla.ops.utils.cumsum import chunk_global_cumsum
from fla.ops.utils.op import exp2, log2
from fla.utils import autocast_custom_bwd, autocast_custom_fwd, check_shared_mem, contiguous
@triton.heuristics({
'USE_G': lambda args: args['g_cumsum'] is not None,
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.autotune(
configs=[
triton.Config({}, num_warps=num_warps, num_stages=num_stages)
for num_warps in [2, 4] + ([8] if check_shared_mem('hopper') else [])
for num_stages in [2, 3, 4, 5]
],
key=['B', 'H', 'HQ', 'G', 'K', 'V', 'BK', 'BV', 'USE_G', 'IS_VARLEN'],
)
@triton.jit
def parallel_attn_fwd_kernel(
q,
k,
v,
o,
g_cumsum,
lse,
scale,
cu_seqlens,
chunk_indices,
T,
B: tl.constexpr,
H: tl.constexpr,
HQ: tl.constexpr,
G: tl.constexpr,
K: tl.constexpr,
V: tl.constexpr,
BT: tl.constexpr,
BS: tl.constexpr,
BK: tl.constexpr,
BV: tl.constexpr,
USE_G: tl.constexpr,
IS_VARLEN: tl.constexpr,
):
i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_b, i_hq = i_bh // HQ, i_bh % HQ
i_h = i_hq // G
if IS_VARLEN:
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
T = eos - bos
else:
i_n = i_b
bos, eos = i_n * T, i_n * T + T
RCP_LN2: tl.constexpr = 1.4426950216
p_q = tl.make_block_ptr(q + (bos * HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_t * BT, 0), (BT, BK), (1, 0))
p_o = tl.make_block_ptr(o + (bos * HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
p_lse = tl.make_block_ptr(lse + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
# the Q block is kept in the shared memory throughout the whole kernel
# [BT, BK]
b_q = tl.load(p_q, boundary_check=(0, 1))
# [BT, BV]
b_o = tl.zeros([BT, BV], dtype=tl.float32)
b_m = tl.full([BT], float('-inf'), dtype=tl.float32)
b_acc = tl.zeros([BT], dtype=tl.float32)
if USE_G:
p_g = tl.make_block_ptr(g_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
b_gq = tl.load(p_g, boundary_check=(0,)).to(tl.float32)
else:
b_gq = None
for i_s in range(0, i_t * BT, BS):
p_k = tl.make_block_ptr(k + (bos * H + i_h) * K, (K, T), (1, H*K), (0, i_s), (BK, BS), (0, 1))
p_v = tl.make_block_ptr(v + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
# [BK, BS]
b_k = tl.load(p_k, boundary_check=(0, 1))
# [BS, BV]
b_v = tl.load(p_v, boundary_check=(0, 1))
# [BT, BS]
b_s = tl.dot(b_q, b_k) * scale * RCP_LN2
if USE_G:
o_k = i_s + tl.arange(0, BS)
m_k = o_k < T
b_gk = tl.load(g_cumsum + (bos + o_k) * HQ + i_hq, mask=m_k, other=0).to(tl.float32)
b_s += b_gq[:, None] - b_gk[None, :]
# [BT, BS]
b_m, b_mp = tl.maximum(b_m, tl.max(b_s, 1)), b_m
b_r = exp2(b_mp - b_m)
# [BT, BS]
b_p = exp2(b_s - b_m[:, None])
# [BT]
b_acc = b_acc * b_r + tl.sum(b_p, 1)
# [BT, BV]
b_o = b_o * b_r[:, None] + tl.dot(b_p.to(b_q.dtype), b_v)
b_mp = b_m
# [BT]
o_q = i_t * BT + tl.arange(0, BT)
for i_s in range(i_t * BT, min((i_t + 1) * BT, T), BS):
p_k = tl.make_block_ptr(k + (bos * H + i_h) * K, (K, T), (1, H*K), (0, i_s), (BK, BS), (0, 1))
p_v = tl.make_block_ptr(v + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
# [BS]
o_k = i_s + tl.arange(0, BS)
m_k = o_k < T
# [BK, BS]
b_k = tl.load(p_k, boundary_check=(0, 1))
# [BS, BV]
b_v = tl.load(p_v, boundary_check=(0, 1))
# [BT, BS]
b_s = tl.dot(b_q, b_k) * scale * RCP_LN2
if USE_G:
b_gk = tl.load(g_cumsum + (bos + o_k) * HQ + i_hq, mask=m_k, other=0).to(tl.float32)
b_s += b_gq[:, None] - b_gk[None, :]
b_s = tl.where((o_q[:, None] >= o_k[None, :]) & m_k[None, :], b_s, float('-inf'))
# [BT]
b_m, b_mp = tl.maximum(b_m, tl.max(b_s, 1)), b_m
b_r = exp2(b_mp - b_m)
# [BT, BS]
b_p = exp2(b_s - b_m[:, None])
# [BT]
b_acc = b_acc * b_r + tl.sum(b_p, 1)
# [BT, BV]
b_o = b_o * b_r[:, None] + tl.dot(b_p.to(b_q.dtype), b_v)
b_mp = b_m
b_o = b_o / b_acc[:, None]
b_m += log2(b_acc)
tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_lse, b_m.to(p_lse.dtype.element_ty), boundary_check=(0,))
@triton.jit
def parallel_attn_bwd_kernel_preprocess(
o,
do,
delta,
B: tl.constexpr,
V: tl.constexpr
):
i_n = tl.program_id(0)
o_d = tl.arange(0, B)
m_d = o_d < V
b_o = tl.load(o + i_n * V + o_d, mask=m_d, other=0)
b_do = tl.load(do + i_n * V + o_d, mask=m_d, other=0).to(tl.float32)
b_delta = tl.sum(b_o * b_do)
tl.store(delta + i_n, b_delta.to(delta.dtype.element_ty))
@triton.heuristics({
'USE_G': lambda args: args['g_cumsum'] is not None,
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.autotune(
configs=[
triton.Config({}, num_warps=num_warps, num_stages=num_stages)
for num_warps in [2, 4] + ([8] if check_shared_mem('hopper') else [])
for num_stages in [2, 3, 4, 5]
],
key=['B', 'H', 'HQ', 'G', 'K', 'V', 'BK', 'BV', 'USE_G', 'IS_VARLEN'],
)
@triton.jit(do_not_specialize=['T'])
def parallel_attn_bwd_kernel_dq(
q,
k,
v,
lse,
delta,
do,
dq,
dg_cumsum,
g_cumsum,
scale,
cu_seqlens,
chunk_indices,
T,
B: tl.constexpr,
H: tl.constexpr,
HQ: tl.constexpr,
G: tl.constexpr,
K: tl.constexpr,
V: tl.constexpr,
BT: tl.constexpr,
BS: tl.constexpr,
BK: tl.constexpr,
BV: tl.constexpr,
IS_VARLEN: tl.constexpr,
USE_G: tl.constexpr
):
i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_b, i_hq = i_bh // HQ, i_bh % HQ
i_h = i_hq // G
if IS_VARLEN:
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
T = eos - bos
else:
i_n = i_b
bos, eos = i_n * T, i_n * T + T
# NOTE: we must multiply RCP_LN2 after tl.dot for high precision
RCP_LN2: tl.constexpr = 1.4426950216
p_q = tl.make_block_ptr(q + (bos * HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_t * BT, 0), (BT, BK), (1, 0))
p_dq = tl.make_block_ptr(dq + (bos * HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_t * BT, 0), (BT, BK), (1, 0))
p_do = tl.make_block_ptr(do + (bos * HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
p_lse = tl.make_block_ptr(lse + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
p_delta = tl.make_block_ptr(delta + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
# [BT, BK]
b_q = tl.load(p_q, boundary_check=(0, 1))
# [BT, BV]
b_do = tl.load(p_do, boundary_check=(0, 1))
# [BT]
b_lse = tl.load(p_lse, boundary_check=(0,))
b_delta = tl.load(p_delta, boundary_check=(0,))
# [BT, BK]
b_dq = tl.zeros([BT, BK], dtype=tl.float32)
if USE_G:
b_dg = tl.zeros([BT, ], dtype=tl.float32)
p_gq = tl.make_block_ptr(g_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
b_gq = tl.load(p_gq, boundary_check=(0,)).to(tl.float32)
else:
b_gq = None
b_dg = None
o_q = i_t * BT + tl.arange(0, BT)
for i_s in range(0, i_t * BT, BS):
p_k = tl.make_block_ptr(k + (bos * H + i_h) * K, (K, T), (1, H*K), (0, i_s), (BK, BS), (0, 1))
p_v = tl.make_block_ptr(v + (bos * H + i_h) * V, (V, T), (1, H*V), (i_v * BV, i_s), (BV, BS), (0, 1))
o_k = i_s + tl.arange(0, BS)
m_k = o_k < T
# [BK, BS]
b_k = tl.load(p_k, boundary_check=(0, 1))
# [BV, BS]
b_v = tl.load(p_v, boundary_check=(0, 1))
# [BT, BS]
b_s = tl.dot(b_q, b_k) * scale * RCP_LN2
if USE_G:
b_gk = tl.load(g_cumsum + (bos + o_k) * HQ + i_hq, mask=m_k, other=0).to(tl.float32)
b_s += b_gq[:, None] - b_gk[None, :]
b_s = tl.where((o_q[:, None] >= o_k[None, :]) & m_k[None, :], b_s, float('-inf'))
b_p = exp2(b_s - b_lse[:, None])
# [BT, BV] @ [BV, BS] -> [BT, BS]
b_dp = tl.dot(b_do, b_v)
b_ds = b_p * (b_dp.to(tl.float32) - b_delta[:, None])
# [BT, BS] @ [BS, BK] -> [BT, BK]
b_dq += tl.dot(b_ds.to(b_k.dtype), tl.trans(b_k))
if USE_G:
b_dg += tl.sum(b_ds, 1)
# [BT]
o_q = i_t * BT + tl.arange(0, BT)
for i_s in range(i_t * BT, min((i_t + 1) * BT, T), BS):
p_k = tl.make_block_ptr(k + (bos * H + i_h) * K, (K, T), (1, H*K), (0, i_s), (BK, BS), (0, 1))
p_v = tl.make_block_ptr(v + (bos * H + i_h) * V, (V, T), (1, H*V), (i_v * BV, i_s), (BV, BS), (0, 1))
# [BS]
o_k = i_s + tl.arange(0, BS)
m_k = o_k < T
# [BK, BS]
b_k = tl.load(p_k, boundary_check=(0, 1))
# [BV, BS]
b_v = tl.load(p_v, boundary_check=(0, 1))
# [BT, BS]
b_s = tl.dot(b_q, b_k) * scale * RCP_LN2
if USE_G:
p_gk = tl.make_block_ptr(g_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
b_gk = tl.load(p_gk, boundary_check=(0,)).to(tl.float32)
b_s += b_gq[:, None] - b_gk[None, :]
b_p = tl.where((o_q[:, None] >= o_k[None, :]) & m_k[None, :], exp2(b_s - b_lse[:, None]), 0)
# [BT, BV] @ [BV, BS] -> [BT, BS]
b_dp = tl.dot(b_do, b_v)
b_ds = b_p * (b_dp.to(tl.float32) - b_delta[:, None])
# [BT, BS] @ [BS, BK] -> [BT, BK]
b_dq += tl.dot(b_ds.to(b_k.dtype), tl.trans(b_k))
if USE_G:
b_dg += tl.sum(b_ds, 1)
b_dq *= scale
tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
if USE_G:
p_dg = tl.make_block_ptr(dg_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
tl.store(p_dg, b_dg.to(p_dg.dtype.element_ty), boundary_check=(0,))
@triton.heuristics({
'USE_G': lambda args: args['g_cumsum'] is not None,
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.autotune(
configs=[
triton.Config({}, num_warps=num_warps, num_stages=num_stages)
for num_warps in [2, 4] + ([8] if check_shared_mem('hopper') else [])
for num_stages in [2, 3, 4, 5]
],
key=['B', 'H', 'HQ', 'G', 'K', 'V', 'BK', 'BV', 'USE_G', 'IS_VARLEN'],
)
@triton.jit(do_not_specialize=['T'])
def parallel_attn_bwd_kernel_dkv(
q,
k,
v,
g_cumsum,
lse,
delta,
do,
dk,
dv,
dg_cumsum,
cu_seqlens,
chunk_indices,
scale,
T,
B: tl.constexpr,
H: tl.constexpr,
HQ: tl.constexpr,
G: tl.constexpr,
K: tl.constexpr,
V: tl.constexpr,
BT: tl.constexpr,
BS: tl.constexpr,
BK: tl.constexpr,
BV: tl.constexpr,
USE_G: tl.constexpr,
IS_VARLEN: tl.constexpr
):
i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_b, i_hq = i_bh // HQ, i_bh % HQ
i_h = i_hq // G
if IS_VARLEN:
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
T = eos - bos
else:
i_n = i_b
bos, eos = i_n * T, i_n * T + T
RCP_LN2: tl.constexpr = 1.4426950216
p_k = tl.make_block_ptr(k + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, 0), (BT, BK), (1, 0))
p_v = tl.make_block_ptr(v + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
p_dk = tl.make_block_ptr(dk + (bos * HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_t * BT, 0), (BT, BK), (1, 0))
p_dv = tl.make_block_ptr(dv + (bos * HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
# [BT, BK]
b_k = tl.load(p_k, boundary_check=(0, 1))
b_dk = tl.zeros([BT, BK], dtype=tl.float32)
# [BT, BV]
b_v = tl.load(p_v, boundary_check=(0, 1))
b_dv = tl.zeros([BT, BV], dtype=tl.float32)
o_k = i_t * BT + tl.arange(0, BT)
if USE_G:
p_gk = tl.make_block_ptr(g_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
b_gk = tl.load(p_gk, boundary_check=(0,)).to(tl.float32)
b_dg = tl.zeros([BT,], dtype=tl.float32)
else:
b_gk = None
b_dg = None
for i_s in range(i_t * BT, min((i_t + 1) * BT, T), BS):
p_q = tl.make_block_ptr(q + (bos * HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_s, 0), (BS, BK), (1, 0))
p_do = tl.make_block_ptr(do + (bos * HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
p_lse = tl.make_block_ptr(lse + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
p_delta = tl.make_block_ptr(delta + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
# [BS]
o_q = i_s + tl.arange(0, BS)
m_q = o_q < T
# [BS, BK]
b_q = tl.load(p_q, boundary_check=(0, 1))
# [BS, BV]
b_do = tl.load(p_do, boundary_check=(0, 1))
# [BS]
b_lse = tl.load(p_lse, boundary_check=(0,))
b_delta = tl.load(p_delta, boundary_check=(0,))
# [BT, BS]
b_s = tl.dot(b_k, tl.trans(b_q)) * scale * RCP_LN2
if USE_G:
p_gq = tl.make_block_ptr(g_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
b_gq = tl.load(p_gq, boundary_check=(0,)).to(tl.float32)
b_s += b_gq[None, :] - b_gk[:, None]
b_p = tl.where((o_k[:, None] <= o_q[None, :]) & m_q[None, :], exp2(b_s - b_lse[None, :]), 0)
# [BT, BS] @ [BS, BV] -> [BT, BV]
b_dv += tl.dot(b_p.to(b_do.dtype), b_do)
# [BT, BV] @ [BV, BS] -> [BT, BS]
b_dp = tl.dot(b_v, tl.trans(b_do))
# [BT, BS]
b_ds = b_p * (b_dp - b_delta[None, :])
# [BT, BS] @ [BS, BK] -> [BT, BK]
b_dk += tl.dot(b_ds.to(b_q.dtype), b_q)
if USE_G:
b_dg -= tl.sum(b_ds, 1)
for i_s in range((i_t + 1) * BT, tl.cdiv(T, BS) * BS, BS):
p_q = tl.make_block_ptr(q + (bos * HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_s, 0), (BS, BK), (1, 0))
p_do = tl.make_block_ptr(do + (bos * HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
p_lse = tl.make_block_ptr(lse + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
p_delta = tl.make_block_ptr(delta + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
# [BS]
o_q = i_s + tl.arange(0, BS)
m_q = o_q < T
# [BS, BK]
b_q = tl.load(p_q, boundary_check=(0, 1))
# [BS, BV]
b_do = tl.load(p_do, boundary_check=(0, 1))
# [BS]
b_lse = tl.load(p_lse, boundary_check=(0,))
b_delta = tl.load(p_delta, boundary_check=(0,))
# [BT, BS]
b_s = tl.dot(b_k, tl.trans(b_q)) * scale * RCP_LN2
if USE_G:
p_gq = tl.make_block_ptr(g_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
b_gq = tl.load(p_gq, boundary_check=(0,)).to(tl.float32)
b_s += b_gq[None, :] - b_gk[:, None]
b_p = tl.where(m_q[None, :], exp2(b_s - b_lse[None, :]), 0)
# [BT, BS] @ [BS, BV] -> [BT, BV]
b_dv += tl.dot(b_p.to(b_do.dtype), b_do)
# [BT, BV] @ [BV, BS] -> [BT, BS]
b_dp = tl.dot(b_v, tl.trans(b_do))
# [BT, BS]
b_ds = b_p * (b_dp - b_delta[None, :])
# [BT, BS] @ [BS, BK] -> [BT, BK]
b_dk += tl.dot(b_ds.to(b_q.dtype), b_q)
if USE_G:
b_dg -= tl.sum(b_ds, 1)
b_dk = b_dk * scale
tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
if USE_G:
p_dg = tl.make_block_ptr(dg_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
tl.store(p_dg, b_dg.to(p_dg.dtype.element_ty), boundary_check=(0,))
def parallel_attn_fwd(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
g_cumsum: torch.Tensor,
scale: float,
chunk_size: int = 128,
cu_seqlens: Optional[torch.LongTensor] = None,
):
B, T, H, K, V = *k.shape, v.shape[-1]
HQ = q.shape[2]
G = HQ // H
BT = chunk_size
if check_shared_mem('hopper', q.device.index):
BS = min(64, max(16, triton.next_power_of_2(T)))
BK = min(256, max(16, triton.next_power_of_2(K)))
BV = min(256, max(16, triton.next_power_of_2(V)))
elif check_shared_mem('ampere', q.device.index):
BS = min(32, max(16, triton.next_power_of_2(T)))
BK = min(256, max(16, triton.next_power_of_2(K)))
BV = min(128, max(16, triton.next_power_of_2(V)))
else:
BS = min(32, max(16, triton.next_power_of_2(T)))
BK = min(256, max(16, triton.next_power_of_2(K)))
BV = min(64, max(16, triton.next_power_of_2(V)))
NK = triton.cdiv(K, BK)
NV = triton.cdiv(V, BV)
chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
assert NK == 1, "The key dimension can not be larger than 256"
o = torch.empty(B, T, HQ, V, dtype=v.dtype, device=q.device)
lse = torch.empty(B, T, HQ, dtype=torch.float, device=q.device)
grid = (NV, NT, B * HQ)
parallel_attn_fwd_kernel[grid](
q=q,
k=k,
v=v,
o=o,
g_cumsum=g_cumsum,
lse=lse,
scale=scale,
cu_seqlens=cu_seqlens,
chunk_indices=chunk_indices,
B=B,
T=T,
H=H,
HQ=HQ,
G=G,
K=K,
V=V,
BT=BT,
BS=BS,
BK=BK,
BV=BV,
)
return o, lse
def parallel_attn_bwd_preprocess(
o: torch.Tensor,
do: torch.Tensor
):
V = o.shape[-1]
delta = torch.empty_like(o[..., 0], dtype=torch.float)
parallel_attn_bwd_kernel_preprocess[(delta.numel(),)](
o=o,
do=do,
delta=delta,
B=triton.next_power_of_2(V),
V=V,
)
return delta
def parallel_attn_bwd(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
o: torch.Tensor,
g_cumsum: torch.Tensor,
lse: torch.Tensor,
do: torch.Tensor,
scale: float = None,
chunk_size: int = 128,
cu_seqlens: Optional[torch.LongTensor] = None,
):
B, T, H, K, V = *k.shape, v.shape[-1]
HQ = q.shape[2]
G = HQ // H
BT = chunk_size
BS = max(16, triton.next_power_of_2(T))
BS = min(32, BS) if check_shared_mem('ampere') else min(16, BS) # SY:H100 should at least use BS=64 to use WGMMA
BK = max(16, triton.next_power_of_2(K))
BV = max(16, triton.next_power_of_2(V))
chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
NV = triton.cdiv(V, BV)
delta = parallel_attn_bwd_preprocess(o, do)
dq = torch.empty(B, T, HQ, K, dtype=k.dtype if H == HQ else torch.float, device=q.device)
dk = torch.empty(B, T, HQ, K, dtype=k.dtype if H == HQ else torch.float, device=q.device)
dv = torch.empty(B, T, HQ, V, dtype=v.dtype if H == HQ else torch.float, device=q.device)
grid = (NV, NT, B * HQ)
dg_cumsum, dg_cumsum_k = None, None
if g_cumsum is not None:
dg_cumsum = torch.empty(B, T, HQ, dtype=torch.float, device=q.device)
dg_cumsum_k = torch.empty(B, T, HQ, dtype=torch.float, device=q.device)
parallel_attn_bwd_kernel_dq[grid](
q=q,
k=k,
v=v,
g_cumsum=g_cumsum,
lse=lse,
delta=delta,
do=do,
dq=dq,
dg_cumsum=dg_cumsum,
cu_seqlens=cu_seqlens,
chunk_indices=chunk_indices,
scale=scale,
T=T,
B=B,
H=H,
HQ=HQ,
G=G,
K=K,
V=V,
BT=BT,
BS=BS,
BK=BK,
BV=BV
)
parallel_attn_bwd_kernel_dkv[grid](
q=q,
k=k,
v=v,
g_cumsum=g_cumsum,
lse=lse,
delta=delta,
do=do,
dk=dk,
dv=dv,
dg_cumsum=dg_cumsum_k,
cu_seqlens=cu_seqlens,
chunk_indices=chunk_indices,
scale=scale,
T=T,
B=B,
H=H,
HQ=HQ,
G=G,
K=K,
V=V,
BT=BT,
BS=BS,
BK=BK,
BV=BV
)
dk = reduce(dk, 'b t (h g) k -> b t h k', g=G, reduction='sum')
dv = reduce(dv, 'b t (h g) v -> b t h v', g=G, reduction='sum')
if g_cumsum is not None:
dg_cumsum.add_(dg_cumsum_k)
return dq, dk, dv, dg_cumsum
@torch.compile
class ParallelAttentionFunction(torch.autograd.Function):
@staticmethod
@contiguous
@autocast_custom_fwd
def forward(ctx, q, k, v, g, scale, cu_seqlens):
ctx.dtype = q.dtype
RCP_LN2: float = 1.4426950216
chunk_size = min(128, max(16, triton.next_power_of_2(q.shape[1])))
g_cumsum = chunk_global_cumsum(g, cu_seqlens=cu_seqlens, scale=RCP_LN2) if g is not None else None
o, lse = parallel_attn_fwd(
q=q,
k=k,
v=v,
g_cumsum=g_cumsum,
scale=scale,
chunk_size=chunk_size,
cu_seqlens=cu_seqlens,
)
ctx.save_for_backward(q, k, v, o, g_cumsum, lse)
ctx.chunk_size = chunk_size
ctx.cu_seqlens = cu_seqlens
ctx.scale = scale
return o.to(q.dtype)
@staticmethod
@contiguous
@autocast_custom_bwd
def backward(ctx, do):
q, k, v, o, g_cumsum, lse = ctx.saved_tensors
dq, dk, dv, dg = parallel_attn_bwd(
q=q,
k=k,
v=v,
o=o,
g_cumsum=g_cumsum,
lse=lse,
do=do,
scale=ctx.scale,
chunk_size=ctx.chunk_size,
cu_seqlens=ctx.cu_seqlens,
)
if dg is not None:
dg = chunk_global_cumsum(dg, cu_seqlens=ctx.cu_seqlens, reverse=True)
return dq.to(q), dk.to(k), dv.to(v), dg, None, None
def parallel_attn(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
g: Optional[torch.Tensor] = None,
scale: Optional[float] = None,
cu_seqlens: Optional[torch.LongTensor] = None,
head_first: bool = False
) -> torch.Tensor:
r"""
Args:
q (torch.Tensor):
queries of shape `[B, T, HQ, K]`.
k (torch.Tensor):
keys of shape `[B, T, H, K]`.
GQA will be applied if HQ is divisible by H.
v (torch.Tensor):
values of shape `[B, T, H, V]`.
g (Optional[torch.Tensor]):
log decay factors of shape `[B, T, H]`.
scale (Optional[float]):
Scale factor for attention scores.
If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
cu_seqlens (torch.LongTensor):
Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
consistent with the FlashAttention API.
head_first (Optional[bool]):
Whether the inputs are in the head-first format. Default: `False`.
This argument has been deprecated.
Returns:
o (torch.Tensor):
Outputs of shape `[B, T, HQ, V]`.
"""
if head_first:
raise DeprecationWarning(
"head_first is deprecated and will be removed in a future version. "
"Please use head_first=False for now instead."
)
if not head_first and q.shape[1] < q.shape[2]:
warnings.warn(
f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
"This may indicate the inputs were passed in head-first format [B, H, T, ...] "
"when head_first=False was specified. "
"Please verify your input tensor format matches the expected shape [B, T, H, ...]."
)
if scale is None:
scale = k.shape[-1] ** -0.5
if cu_seqlens is not None:
assert q.shape[0] == 1, "batch size must be 1 when cu_seqlens are provided"
o = ParallelAttentionFunction.apply(q, k, v, g, scale, cu_seqlens)
return o
| 0 | 0.652929 | 1 | 0.652929 | game-dev | MEDIA | 0.217835 | game-dev | 0.863395 | 1 | 0.863395 |
Maxlego08/zMenu | 1,435 | Hooks/Jobs/src/main/java/fr/maxlego08/menu/hooks/jobs/ZJobPermissible.java | package fr.maxlego08.menu.hooks.jobs;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.container.Job;
import fr.maxlego08.menu.api.MenuPlugin;
import fr.maxlego08.menu.api.button.Button;
import fr.maxlego08.menu.api.engine.InventoryEngine;
import fr.maxlego08.menu.api.requirement.Action;
import fr.maxlego08.menu.api.requirement.permissible.JobPermissible;
import fr.maxlego08.menu.api.utils.Placeholders;
import org.bukkit.entity.Player;
import java.util.List;
public class ZJobPermissible extends JobPermissible {
private final String jobName;
public ZJobPermissible(List<Action> denyActions, List<Action> successActions, String jobName) {
super(denyActions, successActions);
this.jobName = jobName;
}
@Override
public boolean hasPermission(Player player, Button button, InventoryEngine inventory, Placeholders placeholders) {
MenuPlugin plugin = inventory.getPlugin();
Job job = Jobs.getJob(plugin.parse(player, placeholders.parse(this.jobName)));
if (job == null) {
plugin.getLogger().severe("Job " + this.jobName + " was not found !");
return true;
}
return Jobs.getPlayerManager().getJobsPlayer(player.getUniqueId()).isInJob(job);
}
@Override
public boolean isValid() {
return this.jobName != null;
}
@Override
public String getJobName() {
return this.jobName;
}
}
| 0 | 0.817419 | 1 | 0.817419 | game-dev | MEDIA | 0.718053 | game-dev | 0.778538 | 1 | 0.778538 |
Fluorohydride/ygopro-scripts | 3,202 | c87609391.lua | --ラプターズ・アルティメット・メイス
function c87609391.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_CONTINUOUS_TARGET)
e1:SetTarget(c87609391.target)
e1:SetOperation(c87609391.operation)
c:RegisterEffect(e1)
--atk up
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(1000)
c:RegisterEffect(e2)
--equip limit
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_EQUIP_LIMIT)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetValue(c87609391.eqlimit)
c:RegisterEffect(e3)
--search
local e4=Effect.CreateEffect(c)
e4:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e4:SetRange(LOCATION_SZONE)
e4:SetCode(EVENT_BE_BATTLE_TARGET)
e4:SetCondition(c87609391.thcon)
e4:SetTarget(c87609391.thtg)
e4:SetOperation(c87609391.thop)
c:RegisterEffect(e4)
end
function c87609391.eqlimit(e,c)
return c:IsSetCard(0xba)
end
function c87609391.filter(c)
return c:IsFaceup() and c:IsSetCard(0xba)
end
function c87609391.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c87609391.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c87609391.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c87609391.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c87609391.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if e:GetHandler():IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,e:GetHandler(),tc)
end
end
function c87609391.thcon(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
local ec=e:GetHandler():GetEquipTarget()
local at=Duel.GetAttacker()
return tc==ec and at and at:GetAttack()>ec:GetAttack()
end
function c87609391.thfilter(c)
return c:IsSetCard(0x95) and c:IsType(TYPE_SPELL) and c:IsAbleToHand()
end
function c87609391.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c87609391.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c87609391.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c87609391.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
local c=e:GetHandler()
local tc=Duel.GetAttacker()
if tc:IsRelateToBattle() and tc:IsFaceup() and tc:IsAttackable() then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_AVOID_BATTLE_DAMAGE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
e1:SetValue(1)
e1:SetCondition(c87609391.damcon)
e1:SetReset(RESET_PHASE+PHASE_DAMAGE_CAL)
e1:SetLabelObject(tc)
Duel.RegisterEffect(e1,tp)
end
end
end
function c87609391.damcon(e)
return e:GetLabelObject()==Duel.GetAttacker()
end
| 0 | 0.878528 | 1 | 0.878528 | game-dev | MEDIA | 0.988025 | game-dev | 0.934267 | 1 | 0.934267 |
EXOK/Celeste64 | 1,257 | Source/Actors/FloatyBlock.cs |
namespace Celeste64;
public sealed class FloatyBlock : Solid
{
private Vec3 origin;
private Vec3 offset;
private float friction = 300;
private float frictionThreshold = 50;
private float frequency = 1.2f;
private float halflife = 3.0f;
private bool hasPlayerRider;
public override void Added()
{
base.Added();
origin = Position;
offset = Vec3.Zero;
}
public override void Update()
{
base.Update();
if (!hasPlayerRider && HasPlayerRider())
{
hasPlayerRider = true;
Velocity += World.Get<Player>()!.PreviousVelocity * .8f;
}
else if (hasPlayerRider && !HasPlayerRider())
{
if (World.Get<Player>() is Player player)
Velocity -= player.Velocity * .8f;
hasPlayerRider = false;
}
// friction
friction = 200;
frictionThreshold = 1;
if (friction > 0 && Velocity.LengthSquared() > Calc.Squared(frictionThreshold))
Velocity = Utils.Approach(Velocity, Velocity.Normalized() * frictionThreshold, friction * Time.Delta);
// spring!
Vec3 diff = Position - (origin + offset);
Vec3 normal = diff.Normalized();
float vel = Vec3.Dot(Velocity, normal);
float old_vel = vel;
vel = SpringPhysics.Calculate(diff.Length(), vel, 0, 0, frequency, halflife);
Velocity += normal * (vel - old_vel);
}
}
| 0 | 0.83575 | 1 | 0.83575 | game-dev | MEDIA | 0.949958 | game-dev | 0.944346 | 1 | 0.944346 |
keithhearne/VSTPlugins | 10,728 | MoorerReverbStereo/JuceLibraryCode/modules/juce_gui_basics/layout/juce_ComponentAnimator.cpp | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found 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.juce.com for more information.
==============================================================================
*/
class ComponentAnimator::AnimationTask
{
public:
AnimationTask (Component* const comp)
: component (comp)
{
}
void reset (const Rectangle<int>& finalBounds,
float finalAlpha,
int millisecondsToSpendMoving,
bool useProxyComponent,
double startSpeed_, double endSpeed_)
{
msElapsed = 0;
msTotal = jmax (1, millisecondsToSpendMoving);
lastProgress = 0;
destination = finalBounds;
destAlpha = finalAlpha;
isMoving = (finalBounds != component->getBounds());
isChangingAlpha = (finalAlpha != component->getAlpha());
left = component->getX();
top = component->getY();
right = component->getRight();
bottom = component->getBottom();
alpha = component->getAlpha();
const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
midSpeed = invTotalDistance;
endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
if (useProxyComponent)
proxy = new ProxyComponent (*component);
else
proxy = nullptr;
component->setVisible (! useProxyComponent);
}
bool useTimeslice (const int elapsed)
{
if (Component* const c = proxy != nullptr ? static_cast <Component*> (proxy)
: static_cast <Component*> (component))
{
msElapsed += elapsed;
double newProgress = msElapsed / (double) msTotal;
if (newProgress >= 0 && newProgress < 1.0)
{
newProgress = timeToDistance (newProgress);
const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
jassert (newProgress >= lastProgress);
lastProgress = newProgress;
if (delta < 1.0)
{
bool stillBusy = false;
if (isMoving)
{
left += (destination.getX() - left) * delta;
top += (destination.getY() - top) * delta;
right += (destination.getRight() - right) * delta;
bottom += (destination.getBottom() - bottom) * delta;
const Rectangle<int> newBounds (roundToInt (left),
roundToInt (top),
roundToInt (right - left),
roundToInt (bottom - top));
if (newBounds != destination)
{
c->setBounds (newBounds);
stillBusy = true;
}
}
if (isChangingAlpha)
{
alpha += (destAlpha - alpha) * delta;
c->setAlpha ((float) alpha);
stillBusy = true;
}
if (stillBusy)
return true;
}
}
}
moveToFinalDestination();
return false;
}
void moveToFinalDestination()
{
if (component != nullptr)
{
component->setAlpha ((float) destAlpha);
component->setBounds (destination);
if (proxy != nullptr)
component->setVisible (destAlpha > 0);
}
}
//==============================================================================
class ProxyComponent : public Component
{
public:
ProxyComponent (Component& c)
{
setWantsKeyboardFocus (false);
setBounds (c.getBounds());
setTransform (c.getTransform());
setAlpha (c.getAlpha());
setInterceptsMouseClicks (false, false);
if (Component* const parent = c.getParentComponent())
parent->addAndMakeVisible (this);
else if (c.isOnDesktop() && c.getPeer() != nullptr)
addToDesktop (c.getPeer()->getStyleFlags() | ComponentPeer::windowIgnoresKeyPresses);
else
jassertfalse; // seem to be trying to animate a component that's not visible..
image = c.createComponentSnapshot (c.getLocalBounds(), false, getDesktopScaleFactor());
setVisible (true);
toBehind (&c);
}
void paint (Graphics& g) override
{
g.setOpacity (1.0f);
g.drawImageTransformed (image, AffineTransform::scale (getWidth() / (float) image.getWidth(),
getHeight() / (float) image.getHeight()), false);
}
private:
Image image;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent)
};
WeakReference<Component> component;
ScopedPointer<Component> proxy;
Rectangle<int> destination;
double destAlpha;
int msElapsed, msTotal;
double startSpeed, midSpeed, endSpeed, lastProgress;
double left, top, right, bottom, alpha;
bool isMoving, isChangingAlpha;
private:
double timeToDistance (const double time) const noexcept
{
return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
: 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
+ (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
}
};
//==============================================================================
ComponentAnimator::ComponentAnimator()
: lastTime (0)
{
}
ComponentAnimator::~ComponentAnimator()
{
}
//==============================================================================
ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const noexcept
{
for (int i = tasks.size(); --i >= 0;)
if (component == tasks.getUnchecked(i)->component.get())
return tasks.getUnchecked(i);
return nullptr;
}
void ComponentAnimator::animateComponent (Component* const component,
const Rectangle<int>& finalBounds,
const float finalAlpha,
const int millisecondsToSpendMoving,
const bool useProxyComponent,
const double startSpeed,
const double endSpeed)
{
// the speeds must be 0 or greater!
jassert (startSpeed >= 0 && endSpeed >= 0)
if (component != nullptr)
{
AnimationTask* at = findTaskFor (component);
if (at == nullptr)
{
at = new AnimationTask (component);
tasks.add (at);
sendChangeMessage();
}
at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
useProxyComponent, startSpeed, endSpeed);
if (! isTimerRunning())
{
lastTime = Time::getMillisecondCounter();
startTimer (1000 / 50);
}
}
}
void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
{
if (component != nullptr)
{
if (component->isShowing() && millisecondsToTake > 0)
animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
component->setVisible (false);
}
}
void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
{
if (component != nullptr && ! (component->isVisible() && component->getAlpha() == 1.0f))
{
component->setAlpha (0.0f);
component->setVisible (true);
animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
}
}
void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
{
if (tasks.size() > 0)
{
if (moveComponentsToTheirFinalPositions)
for (int i = tasks.size(); --i >= 0;)
tasks.getUnchecked(i)->moveToFinalDestination();
tasks.clear();
sendChangeMessage();
}
}
void ComponentAnimator::cancelAnimation (Component* const component,
const bool moveComponentToItsFinalPosition)
{
if (AnimationTask* const at = findTaskFor (component))
{
if (moveComponentToItsFinalPosition)
at->moveToFinalDestination();
tasks.removeObject (at);
sendChangeMessage();
}
}
Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
{
jassert (component != nullptr);
if (AnimationTask* const at = findTaskFor (component))
return at->destination;
return component->getBounds();
}
bool ComponentAnimator::isAnimating (Component* component) const noexcept
{
return findTaskFor (component) != nullptr;
}
bool ComponentAnimator::isAnimating() const noexcept
{
return tasks.size() != 0;
}
void ComponentAnimator::timerCallback()
{
const uint32 timeNow = Time::getMillisecondCounter();
if (lastTime == 0 || lastTime == timeNow)
lastTime = timeNow;
const int elapsed = (int) (timeNow - lastTime);
for (int i = tasks.size(); --i >= 0;)
{
if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
{
tasks.remove (i);
sendChangeMessage();
}
}
lastTime = timeNow;
if (tasks.size() == 0)
stopTimer();
}
| 0 | 0.954803 | 1 | 0.954803 | game-dev | MEDIA | 0.647635 | game-dev,graphics-rendering | 0.996667 | 1 | 0.996667 |
opentibiabr/canary | 1,092 | data/scripts/spells/attack/strong_flame_strike.lua | local combat = Combat()
combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_FIREDAMAGE)
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_FIREATTACK)
combat:setParameter(COMBAT_PARAM_DISTANCEEFFECT, CONST_ANI_FIRE)
function onGetFormulaValues(player, level, maglevel)
local min = (level / 5) + (maglevel * 2.8) + 16
local max = (level / 5) + (maglevel * 4.4) + 28
return -min, -max
end
combat:setCallback(CALLBACK_PARAM_LEVELMAGICVALUE, "onGetFormulaValues")
local spell = Spell("instant")
function spell.onCastSpell(creature, var)
return combat:execute(creature, var)
end
spell:group("attack", "special")
spell:id(150)
spell:name("Strong Flame Strike")
spell:words("exori gran flam")
spell:castSound(SOUND_EFFECT_TYPE_SPELL_OR_RUNE)
spell:impactSound(SOUND_EFFECT_TYPE_SPELL_STRONG_FLAME_STRIKE)
spell:level(70)
spell:mana(60)
spell:isPremium(true)
spell:range(3)
spell:needCasterTargetOrDirection(true)
spell:blockWalls(true)
spell:cooldown(8 * 1000)
spell:groupCooldown(2 * 1000, 8 * 1000)
spell:needLearn(false)
spell:vocation("sorcerer;true", "master sorcerer;true")
spell:register()
| 0 | 0.748114 | 1 | 0.748114 | game-dev | MEDIA | 0.985944 | game-dev | 0.737953 | 1 | 0.737953 |
magefree/mage | 1,434 | Mage.Sets/src/mage/cards/w/WavesOfAggression.java |
package mage.cards.w;
import java.util.UUID;
import mage.abilities.effects.common.AddCombatAndMainPhaseEffect;
import mage.abilities.effects.common.UntapAllEffect;
import mage.abilities.keyword.RetraceAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.permanent.AttackedThisTurnPredicate;
/**
*
* @author anonymous
*/
public final class WavesOfAggression extends CardImpl {
private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("creatures that attacked this turn");
static {
filter.add(AttackedThisTurnPredicate.instance);
}
public WavesOfAggression(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{3}{R/W}{R/W}");
// Untap all creatures that attacked this turn. After this main phase, there is an additional combat phase followed by an additional main phase.
this.getSpellAbility().addEffect(new UntapAllEffect(filter));
this.getSpellAbility().addEffect(new AddCombatAndMainPhaseEffect());
// Retrace
this.addAbility(new RetraceAbility(this));
}
private WavesOfAggression(final WavesOfAggression card) {
super(card);
}
@Override
public WavesOfAggression copy() {
return new WavesOfAggression(this);
}
}
| 0 | 0.967061 | 1 | 0.967061 | game-dev | MEDIA | 0.919864 | game-dev | 0.980938 | 1 | 0.980938 |
LostCityRS/Content | 3,281 | scripts/minigames/game_ranging/scripts/target.rs2 | // accuracy pulled from https://oldschool.runescape.wiki/w/Module:Chart_data/ranging_guild_target_region_chance
[aploc1,loc_2513]
if (%targetcount = 0) {
if(npc_find(coord, ranging_guild_competition_judge, 5, 0) = true) { // 5 tiles checked on osrs
~chatnpc("<p,neutral>Sorry, you may only use the targets for the competition, not for practicing.");
return;
}
mes("Maybe you should ask before using those.");
} else if (%targetcount >= 1 & %targetcount < 11) {
if(inv_totalcat(worn, weapon_bow) = 0) {
if(npc_find(coord, ranging_guild_competition_judge, 5, 0) = true) { // 5 tiles checked on osrs
~chatnpc("<p,neutral>You need a bow to take part in the competition.");
return;
}
mes("A bow might help here...");
}
if(inv_total(worn, bronze_arrow) = 0) {
if(npc_find(coord, ranging_guild_competition_judge, 5, 0) = true) { // 5 tiles checked on osrs
~chatnpc("<p,neutral>I suggest you use the 10 bronze arrows I gave you.");
return;
}
mes("You'll be needing those bronze arrows...");
}
if(distance(coord, loc_coord) < 5) {
mes("You should probably be behind the <lowercase(lc_name(haystack2))>.");
return;
}
mes("You carefully aim at the target...");
anim(human_bow, 0);
sound_synth(arrowlaunch2, 0, 0);
spotanim_pl(oc_param(bronze_arrow, proj_launch), 96, 0);
inv_del(worn, bronze_arrow, 1);
~coord_projectile(coord, loc_coord, bronze_arrow_travel, 40, 36, 41, 15, 5, 11, 5);
p_delay(2);
%targetcount = calc(%targetcount + 1);
// roll target
def_int $target = ~roll_rangeguild_target;
%targethit = $target;
// calc pts
def_int $points = ~get_targetpts;
%targetscore = calc(%targetscore + $points);
stat_advance(ranged, calc(($points / 2) * 10));
if_settext(target:com_120, ~get_targetstr);
if_openmain(target);
} else if(%targetcount = 11) {
if(npc_find(coord, ranging_guild_competition_judge, 5, 0) = true) {
@ranging_guild_competition_judge_reward_pts;
}
mes("You've fired all your arrows, maybe you should talk to the Judge.");
}
[proc,get_targetstr]()(string)
switch_int(%targethit) {
case 11 : return ("Missed!");
case 9,10 : return ("Hit Black!");
case 5,6,7,8 : return ("Hit Blue!");
case 2,3,4 : return ("Hit Red!");
case 1 : return ("Hit Yellow!");
case 0 : return ("Bulls-Eye!");
}
[proc,get_targetpts]()(int)
switch_int(%targethit) {
case 11 : return (0);
case 9,10 : return (10);
case 5,6,7,8 : return (20);
case 2,3,4 : return (30);
case 1 : return (50);
case 0 : return (100);
}
// def rolls source: https://discord.com/channels/177206626514632704/269673599554551808/1070094764797595729 (wiki)
[proc,roll_rangeguild_target]()(int)
def_int $value = 11;
def_int $att_roll = random(%com_rangeattack);
if(randominc($att_roll) > randominc(1000)) $value = (calc(random(1) + 9));
if(randominc($att_roll) > randominc(2000)) $value = (calc(random(4) + 5));
if(randominc($att_roll) > randominc(3000)) $value = (calc(random(3) + 2));
if(randominc($att_roll) > randominc(4000)) $value = (1);
if(randominc($att_roll) > randominc(7000)) $value = (0);
return ($value);
| 0 | 0.796737 | 1 | 0.796737 | game-dev | MEDIA | 0.949903 | game-dev | 0.822939 | 1 | 0.822939 |
erogenousbeef-zz/BigReactors | 5,628 | src/main/java/erogenousbeef/bigreactors/common/tileentity/TileEntityCyaniteReprocessor.java | package erogenousbeef.bigreactors.common.tileentity;
import java.util.ArrayList;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import cofh.core.util.oredict.OreDictionaryArbiter;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import erogenousbeef.bigreactors.api.registry.Reactants;
import erogenousbeef.bigreactors.client.ClientProxy;
import erogenousbeef.bigreactors.client.gui.GuiCyaniteReprocessor;
import erogenousbeef.bigreactors.common.tileentity.base.TileEntityPoweredInventoryFluid;
import erogenousbeef.bigreactors.gui.container.ContainerCyaniteReprocessor;
import erogenousbeef.bigreactors.utils.StaticUtils;
public class TileEntityCyaniteReprocessor extends TileEntityPoweredInventoryFluid {
public static final int SLOT_INLET = 0;
public static final int SLOT_OUTLET = 1;
public static final int NUM_SLOTS = 2;
public static final int FLUIDTANK_WATER = 0;
public static final int NUM_TANKS = 1;
protected static final int FLUID_CONSUMED = FluidContainerRegistry.BUCKET_VOLUME * 1;
protected static final int INGOTS_CONSUMED = 2;
public TileEntityCyaniteReprocessor() {
super();
// Do not transmit energy from the internal buffer.
m_ProvidesEnergy = false;
}
@Override
public int getSizeInventory() {
return NUM_SLOTS;
}
@Override
public String getInventoryName() {
return "Cyanite Reprocessor";
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack itemstack) {
if(itemstack == null) { return true; }
if(slot == SLOT_OUTLET) {
return Reactants.isFuel(itemstack);
}
else if(slot == SLOT_INLET) {
return Reactants.isWaste(itemstack);
}
return false;
}
@Override
public int getMaxEnergyStored() {
return 10000;
}
@Override
public int getCycleEnergyCost() {
return 2000;
}
@Override
public int getCycleLength() {
return 200; // 10 seconds / 20tps
}
@Override
public boolean canBeginCycle() {
FluidStack fluid = drain(0, FLUID_CONSUMED, false);
if(fluid == null || fluid.amount < FLUID_CONSUMED) {
return false;
}
if(_inventories[SLOT_INLET] != null && _inventories[SLOT_INLET].stackSize >= INGOTS_CONSUMED) {
if(_inventories[SLOT_OUTLET] != null && _inventories[SLOT_OUTLET].stackSize >= getInventoryStackLimit()) {
return false;
}
return true;
}
return false;
}
@Override
public void onPoweredCycleBegin() {
}
@Override
public void onPoweredCycleEnd() {
if(_inventories[SLOT_OUTLET] != null) {
if(consumeInputs()) {
_inventories[SLOT_OUTLET].stackSize += 1;
}
}
else {
// TODO: Make this query the input for the right type of output to create.
ArrayList<ItemStack> candidates = OreDictionaryArbiter.getOres("ingotBlutonium");
if(candidates == null || candidates.isEmpty()) {
// WTF?
return;
}
if(consumeInputs()) {
_inventories[SLOT_OUTLET] = candidates.get(0).copy();
_inventories[SLOT_OUTLET].stackSize = 1;
}
}
distributeItemsFromSlot(SLOT_OUTLET);
markChunkDirty();
}
private boolean consumeInputs() {
_inventories[SLOT_INLET] = StaticUtils.Inventory.consumeItem(_inventories[SLOT_INLET], INGOTS_CONSUMED);
drain(0, FLUID_CONSUMED, true);
return true;
}
@Override
public int getNumTanks() {
return NUM_TANKS;
}
@Override
public int getTankSize(int tankIndex) {
return FluidContainerRegistry.BUCKET_VOLUME * 5;
}
@Override
protected boolean isFluidValidForTank(int tankIdx, FluidStack type) {
if(type == null) { return false; }
return type.getFluid().getID() == FluidRegistry.getFluid("water").getID();
}
/// BeefGUI
@SideOnly(Side.CLIENT)
@Override
public GuiScreen getGUI(EntityPlayer player) {
return new GuiCyaniteReprocessor(getContainer(player), this);
}
@Override
public Container getContainer(EntityPlayer player) {
return new ContainerCyaniteReprocessor(this, player);
}
@Override
protected int getDefaultTankForFluid(Fluid fluid) {
if(fluid.getName() == "water")
return 0;
else
return FLUIDTANK_NONE;
}
// IReconfigurableSides & IBeefReconfigurableSides
@SideOnly(Side.CLIENT)
public IIcon getIconForSide(int side) {
if(side == facing) {
// This should never happen
return getBlockType().getIcon(side, getBlockMetadata());
}
int exposure = getExposure(side);
switch(exposure) {
case 0:
return ClientProxy.CommonBlockIcons.getIcon(ClientProxy.CommonBlockIcons.ITEM_RED);
case 1:
return ClientProxy.CommonBlockIcons.getIcon(ClientProxy.CommonBlockIcons.ITEM_GREEN);
case 2:
return ClientProxy.CommonBlockIcons.getIcon(ClientProxy.CommonBlockIcons.FLUID_BLUE);
default:
return ClientProxy.CommonBlockIcons.getIcon(ClientProxy.CommonBlockIcons.DEFAULT);
}
}
@Override
public int getNumConfig(int side) {
if(facing == side) {
return 0;
}
else {
return 3;
}
}
@Override
public int getExposedTankFromSide(int side) {
int exposure = getExposure(side);
if(exposure == 2) { return FLUIDTANK_WATER; }
return FLUIDTANK_NONE;
}
@Override
protected int getExposedInventorySlotFromSide(int side) {
int exposure = getExposure(side);
if(exposure == 0) { return SLOT_INLET; }
if(exposure == 1) { return SLOT_OUTLET; }
return SLOT_NONE;
}
}
| 0 | 0.915745 | 1 | 0.915745 | game-dev | MEDIA | 0.97499 | game-dev | 0.955285 | 1 | 0.955285 |
meishadevs/GoldMiner | 5,651 | frameworks/runtime-src/proj.win32/Debug.win32/src/SceneMenu.js | /**
* 菜单场景(关卡选择场景)
*/
var MenuLayer = cc.Layer.extend(
{
rootNode:null,
//用于设置游戏场景的名称
spriteTitle:null,
//用于设置游戏场景所在的图片
spriteImage:null,
ctor:function ()
{
this._super();
if (bgVolume)
{
//播放背景音乐
cc.audioEngine.playMusic(res.sound001_mp3, true);
}
else
{
//停止播放背景音乐
cc.audioEngine.stopMusic(res.sound001_mp3);
}
this.initCocosStudio();
this.getButton();
this.initMenuPage();
return true;
},
initCocosStudio:function()
{
//设置菜单
rootNode = ccs.load(res.SceneMenu_json);
this.addChild(rootNode.node);
},
getButton:function()
{
//获得返回按钮
var buttonReturn = ccui.helper.seekWidgetByName(rootNode.node, "buttonReturn");
buttonReturn.addTouchEventListener(this.intoSceneStart);
//获得进入游戏场景按钮
var buttonGame = ccui.helper.seekWidgetByName(rootNode.node, "intoGame");
buttonGame.addTouchEventListener(this.intoSceneGame);
//获得向左翻页按钮
var buttonPageLeft = ccui.helper.seekWidgetByName(rootNode.node, "buttonPageLeft");
buttonPageLeft.addTouchEventListener(this.pageLeft.bind(this));
//获得向右翻页按钮
var buttonPageRight = ccui.helper.seekWidgetByName(rootNode.node, "buttonPageRight");
buttonPageRight.addTouchEventListener(this.pageRight.bind(this));
spriteTitle = rootNode.node.getChildByName("spriteTitle");
spriteImage = rootNode.node.getChildByName("spriteImage");
},
//进入开始场景
intoSceneStart: function (sender, type)
{
switch (type)
{
case ccui.Widget.TOUCH_BEGAN:
{
if (effVolume)
{
//播放按钮音效
cc.audioEngine.playEffect(res.sound010_mp3);
}
//停止播放背景音乐
cc.audioEngine.stopMusic(res.sound001_mp3);
cc.director.runScene(new SceneStart());
}
break;
default :
break;
}
},
//进入游戏场景
intoSceneGame: function (sender, type)
{
switch (type)
{
case ccui.Widget.TOUCH_BEGAN:
{
if (effVolume)
{
//播放按钮音效
cc.audioEngine.playEffect(res.sound010_mp3);
}
//停止播放背景音乐
cc.audioEngine.stopMusic(res.sound001_mp3);
//进入宝象国
if (indexSceneGame == 1)
{
cc.director.runScene(new SceneBaoXiangGuo());
}
//进入通天河
else if (indexSceneGame == 2)
{
cc.director.runScene(new SceneTongTianHe());
}
//进入女儿国
else if (indexSceneGame == 3)
{
cc.director.runScene(new SceneNvErGuo());
}
//进入火焰山
else if (indexSceneGame == 4)
{
cc.director.runScene(new SceneHuoYanShan());
}
//进入灵山
else if (indexSceneGame == 5)
{
cc.director.runScene(new SceneLingShan());
}
}
break;
default :
break;
}
},
//初始化菜单页面
initMenuPage:function()
{
//刷新页面
this.updatePageData();
},
//刷新页面
updatePageData: function ()
{
//设置游戏场景的标题
spriteTitle.setTexture(arrayTitle[indexSceneGame]);
//设置游戏场景的图片
var index = indexSceneGame - 1;
spriteImage.setTexture("res/SceneMenu/tu" + index + ".png");
for (var i = 0; i <= 4; i++)
{
sprite = seekFromRootByName(rootNode.node, "dian" + i);
if (i == indexSceneGame - 1)
{
sprite.setTexture(res.yellowPoint_png);
}
else
{
sprite.setTexture(res.blackPoint_png);
}
}
},
//向左翻页
pageLeft: function (sender, type)
{
switch (type)
{
case ccui.Widget.TOUCH_BEGAN:
{
if (effVolume)
{
//播放按钮音效
cc.audioEngine.playEffect(res.sound010_mp3);
}
//向左翻一页
indexSceneGame--;
if (indexSceneGame == 0)
{
indexSceneGame = 5;
}
//刷新页面
this.updatePageData();
}
break;
default :
break;
}
},
//向右翻页
pageRight : function (sender, type)
{
switch (type)
{
case ccui.Widget.TOUCH_BEGAN:
{
if (effVolume)
{
//播放按钮音效
cc.audioEngine.playEffect(res.sound010_mp3);
}
//向右翻一页
indexSceneGame++;
if (indexSceneGame == 6)
{
indexSceneGame = 1;
}
//刷新页面
this.updatePageData();
}
break;
default :
break;
}
},
});
var SceneMenu = cc.Scene.extend(
{
onEnter:function ()
{
this._super();
var layer = new MenuLayer();
this.addChild(layer);
}
});
| 0 | 0.853635 | 1 | 0.853635 | game-dev | MEDIA | 0.943018 | game-dev | 0.97826 | 1 | 0.97826 |
TeamTwilight/twilightforest-fabric | 2,970 | src/main/java/twilightforest/util/Codecs.java | package twilightforest.util;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Codec;
import com.mojang.serialization.DataResult;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import it.unimi.dsi.fastutil.floats.Float2ObjectAVLTreeMap;
import it.unimi.dsi.fastutil.floats.Float2ObjectSortedMap;
import net.minecraft.Util;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Holder;
import net.minecraft.core.Vec3i;
import net.minecraft.util.ExtraCodecs;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Climate;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public final class Codecs {
public static final Codec<BlockPos> STRING_POS = Codec.STRING.comapFlatMap(Codecs::parseString2BlockPos, Vec3i::toShortString);
public static final Codec<Direction> ONLY_HORIZONTAL = Direction.CODEC.comapFlatMap(direction -> direction.getAxis() != Direction.Axis.Y ? DataResult.success(direction) : DataResult.error(() -> "Horizontal direction only!", direction), Function.identity());
public static final Codec<Float> FLOAT_STRING = Codec.STRING.comapFlatMap(Codecs::parseString2Float, f -> Float.toString(f));
public static final Codec<Climate.ParameterList<Holder<Biome>>> CLIMATE_SYSTEM = ExtraCodecs.nonEmptyList(RecordCodecBuilder.<Pair<Climate.ParameterPoint, Holder<Biome>>>create((instance) -> instance.group(Climate.ParameterPoint.CODEC.fieldOf("parameters").forGetter(Pair::getFirst), Biome.CODEC.fieldOf("biome").forGetter(Pair::getSecond)).apply(instance, Pair::of)).listOf()).xmap(Climate.ParameterList::new, Climate.ParameterList::values);
public static <T> Codec<Float2ObjectSortedMap<T>> floatTreeCodec(Codec<T> elementCodec) {
return Codec
.compoundList(Codecs.FLOAT_STRING, elementCodec)
.xmap(floatEList -> floatEList.stream().collect(Float2ObjectAVLTreeMap::new, (map, pair) -> map.put(pair.getFirst(), pair.getSecond()), Float2ObjectAVLTreeMap::putAll), map -> map.entrySet().stream().map(entry -> new Pair<>(entry.getKey(), entry.getValue())).toList());
}
private static DataResult<BlockPos> parseString2BlockPos(String string) {
try {
return Util.fixedSize(Arrays.stream(string.split(" *, *")).mapToInt(Integer::parseInt), 3).map(arr -> new BlockPos(arr[0], arr[1], arr[2]));
} catch (Throwable e) {
return DataResult.error(e::getMessage);
}
}
private static DataResult<Float> parseString2Float(String string) {
try {
return DataResult.success(Float.valueOf(string));
} catch (Throwable e) {
return DataResult.error(e::getMessage);
}
}
public static <E> DataResult<Pair<E, E>> arrayToPair(List<E> list) {
return Util.fixedSize(list, 2).map(l -> Pair.of(l.get(0), l.get(1)));
}
private Codecs() {}
}
| 0 | 0.812433 | 1 | 0.812433 | game-dev | MEDIA | 0.878322 | game-dev | 0.915525 | 1 | 0.915525 |
Xeeynamo/sotn-decomp | 1,143 | src/st/top/top.h | // SPDX-License-Identifier: AGPL-3.0-or-later
#ifndef TOP_H
#define TOP_H
#define STAGE_IS_TOP
#include <stage.h>
#define OVL_EXPORT(x) TOP_##x
typedef enum EntityIDs {
/* 0x00 */ E_NONE,
/* 0x01 */ E_BREAKABLE,
/* 0x02 */ E_EXPLOSION,
/* 0x03 */ E_PRIZE_DROP,
/* 0x04 */ E_NUMERIC_DAMAGE,
/* 0x05 */ E_RED_DOOR,
/* 0x06 */ E_INTENSE_EXPLOSION,
/* 0x07 */ E_SOUL_STEAL_ORB,
/* 0x08 */ E_ROOM_FOREGROUND,
/* 0x09 */ E_STAGE_NAME_POPUP,
/* 0x0A */ E_EQUIP_ITEM_DROP,
/* 0x0B */ E_RELIC_ORB,
/* 0x0C */ E_HEART_DROP,
/* 0x0D */ E_ENEMY_BLOOD,
/* 0x0E */ E_MESSAGE_BOX,
/* 0x0F */ E_DUMMY_0F,
/* 0x10 */ E_DUMMY_10,
/* 0x11 */ E_ID_11 = 0x11,
/* 0x13 */ E_UNK_ID_13 = 0x13,
/* 0x14 */ E_EXPLOSION_VARIANTS,
/* 0x15 */ E_GREY_PUFF,
/* 0x17 */ E_STAIR_SWITCH = 0x17,
/* 0x18 */ E_SECRET_STAIRS,
/* 0x21 */ E_FLEA_RIDER = 0x21,
/* 0x23 */ E_CUTSCENE = 0x23,
/* 0x27 */ E_BREAKABLE_2 = 0x27,
/* 0x28 */ E_AXE_KNIGHT_BLUE,
/* 0x29 */ E_AXE_KNIGHT_AXE,
/* 0x2A */ E_AXE_KNIGHT_AXE_2,
/* 0x2B */ E_UNK_ENTITY,
};
#endif // TOP_H
| 0 | 0.569241 | 1 | 0.569241 | game-dev | MEDIA | 0.588401 | game-dev | 0.629955 | 1 | 0.629955 |
ryzom/ryzomcore | 34,103 | ryzom/client/src/interface_v3/dbctrl_sheet.h | // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010-2021 Winch Gate Property Limited
//
// This source file has been modified by the following contributors:
// Copyright (C) 2011-2020 Jan BOON (Kaetemi) <jan.boon@kaetemi.be>
// Copyright (C) 2012 Matt RAYKOWSKI (sfb) <matt.raykowski@gmail.com>
// Copyright (C) 2013 Laszlo KIS-ADAM (dfighter) <dfighter1985@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef RZ_DBCTRL_SHEET_H
#define RZ_DBCTRL_SHEET_H
// nel
#include "nel/misc/types_nl.h"
#include "nel/misc/smart_ptr.h"
// client
#include "nel/gui/reflect.h"
#include "nel/gui/ctrl_draggable.h"
#include "nel/gui/interface_expr.h"
#include "nel/gui/action_handler.h"
#include "sphrase_manager.h"
// game share
#include "game_share/brick_types.h"
#include "game_share/trade_slot_type.h"
#include "game_share/skills.h"
#include "game_share/slot_types.h"
#include "game_share/rm_family.h"
#include "game_share/item_family.h"
//
#include "../time_client.h"
#include "item_info_waiter.h"
class CItemSheet;
class CPactSheet;
class CDBCtrlSheet;
class CMacroCmd;
class IListSheetBase;
class CSBrickSheet;
class CSPhraseSheet;
class COutpostBuildingSheet;
namespace NLGUI
{
class CViewRenderer;
class CViewText;
}
class CDBCtrlSheet;
#ifdef RYZOM_FORGE
// ***************************************************************************
// Item info request from server
class CControlSheetInfoWaiter : public IItemInfoWaiter
{
public:
CDBCtrlSheet* CtrlSheet;
string LuaMethodName;
bool Requesting;
CControlSheetInfoWaiter()
: IItemInfoWaiter(), Requesting(false)
{ }
public:
std::string infoValidated() const;
void sendRequest();
virtual void infoReceived();
};
#endif
// ***************************************************************************
/** Common info for CDBCtrlSheet and CDBGroupListSheet
*/
class CCtrlSheetInfo
{
public:
enum TSheetType
{
// Items. sheetId points to a CItemSheet via SheetMngr
SheetType_Item,
// A pact
SheetType_Pact,
// A skill
SheetType_Skill,
// Special : the type of the sheet is automatically deduced from its sheet, it drawn like an item
SheetType_Auto,
// A macro (ie:'open window inventory + dock bag1')
SheetType_Macro,
// Flag of a guild
SheetType_GuildFlag,
// A mission
SheetType_Mission,
// New Sabrina Brick
SheetType_SBrick,
// New Sabrina Phrase. Index in the PhraseBook
SheetType_SPhraseId,
// New Sabrina Phrase. Complete phrase used for bot chat sentence (sheet id represent a CSPhraseSheet)
SheetType_SPhrase,
// A teleport location (just the slot bitmap)
SheetType_Teleport_Location,
// A guild teleport type
SheetType_ElevatorDestination,
// An outpost building
SheetType_OutpostBuilding,
};
CCtrlSheetInfo();
enum TBrickSheetSize
{
BrickSheetWidth= 24,
BrickSheetHeight= 24,
};
public:
TSheetType _Type;
// If it is a brick or a spell, give all the brick type this slot accepts.
// Each bit is for the associated BRICK_TYPE::EBrickType enum (unnknown bit 0 etc...)
// Default is ALL (ie 0xFFFFFFFF)
uint32 _BrickTypeBitField;
// display.
sint32 _DispNoSheetBmpId; // Texture to display when no sheet (==0)
sint32 _SheetSelectionGroup; // group for sheet selection, or -1 if none
// Events
IActionHandler *_AHOnLeftClick;
CStringShared _AHLeftClickParams;
IActionHandler *_AHOnRightClick;
CStringShared _AHRightClickParams;
//
IActionHandler *_AHOnCanDrag;
CStringShared _AHCanDragParams;
IActionHandler *_AHOnDrag;
CStringShared _AHDragParams;
IActionHandler *_AHOnCanDrop;
CStringShared _AHCanDropParams;
IActionHandler *_AHOnDrop;
CStringShared _AHDropParams;
IActionHandler *_AHOnCannotDrop;
CStringShared _AHCannotDropParams;
CStringShared _ListMenuLeft;
CStringShared _ListMenuRight;
CStringShared _ListMenuRightEmptySlot;
//
bool _InterfaceColor : 1; // Color given by the interface ?
bool _UseQuantity : 1; // is the quantity read and displayed ?
bool _ReadQuantityFromSheet : 1; // Read quantity from sheet rather than from database
bool _UseQuality : 1; // is the quality read and displayed ?
bool _DisplayItemQuality : 1; // Do we have to display the quality for the item (false for Cosmetics and Teleport and if _UseQuality==fasle)?
bool _DuplicateOnDrag : 1; // when dragged, the item is shown twice : one version at the mouse position.
// and another in the source slot. Useful for items to buy that are in infinite quantity.
bool _AutoGrayed : 1; // if true then gray the ctrlSheeet if: 1/ Items: Is the Item Locked. 2/ Bricks: is the brick Latent.
bool _HasTradeSlotType : 1; // true is the SLOT_TYPE DB field should be taken in account
bool _BrickOverable : 1; // if Type is Brick, display like a button (because LeftClickable).
bool _DragCopy : 1; // true if support copy drag
bool _ForceItemBackGroundGeneric : 1;
// For an Item only, this tells what item type this slot accept. Undefined means ALL
SLOTTYPE::TSlotType _ItemSlot;
public:
bool parseCtrlInfo(xmlNodePtr cur, CInterfaceGroup * parentGroup);
// Context menu accessor/ One for each button
void setListMenuLeft (const std::string &cm) { _ListMenuLeft = cm; }
void setListMenuRight (const std::string &cm) { _ListMenuRight = cm; }
void setListMenuBoth (const std::string &cm) { _ListMenuLeft= _ListMenuRight= cm; }
const std::string &getListMenuLeft () { return _ListMenuLeft; }
const std::string &getListMenuRight () { return _ListMenuRight; }
const std::string &getListMenuRightEmptySlot () {return _ListMenuRightEmptySlot;}
};
// ***************************************************************************
/**
* Class representing base for items that are described in Georges forms
* \author Matthieu 'TrapII' Besson
* \author Nevrax France
* \date 2002
*/
class CDBCtrlSheet : public CCtrlDraggable, protected CCtrlSheetInfo
{
public:
DECLARE_UI_CLASS(CDBCtrlSheet)
// Release fucking statics
static void release ();
enum TSheetCategory { Item = 0, Pact, Skill, GuildFlag, Mission, Phrase, DontKnow };
public:
CDBCtrlSheet(const TCtorParam ¶m);
~CDBCtrlSheet();
virtual bool parse(xmlNodePtr cur, CInterfaceGroup * parentGroup);
virtual void updateCoords();
virtual void draw();
void drawSheet (sint32 scrX, sint32 scrY, bool draging, bool showSelectionBorder = true);
virtual bool handleEvent (const NLGUI::CEventDescriptor &event);
void setActionOnLeftClick (const std::string &ActionHandlerName) { _AHOnLeftClick = CAHManager::getInstance()->getAH(ActionHandlerName, _AHLeftClickParams); }
void setActionOnRightClick (const std::string &ActionHandlerName) { _AHOnRightClick = CAHManager::getInstance()->getAH(ActionHandlerName, _AHRightClickParams); }
void setActionOnDrop (const std::string &ActionHandlerName) { _AHOnDrop = CAHManager::getInstance()->getAH(ActionHandlerName, _AHDropParams); }
void setActionOnCanDrop (const std::string &ActionHandlerName) { _AHOnCanDrop = CAHManager::getInstance()->getAH(ActionHandlerName, _AHCanDropParams); }
void setParamsOnLeftClick (const std::string &ParamsHandlerName) { _AHLeftClickParams = ParamsHandlerName; }
void setParamsOnRightClick (const std::string &ParamsHandlerName) { _AHRightClickParams = ParamsHandlerName; }
void setParamsOnDrop (const std::string &ParamsHandlerName) { _AHDropParams = ParamsHandlerName; }
void setParamsOnCanDrop (const std::string &ParamsHandlerName) { _AHCanDropParams = ParamsHandlerName; }
const std::string &getActionOnLeftClick () const { return CAHManager::getInstance()->getAHName(_AHOnLeftClick); }
const std::string &getActionOnRightClick () const { return CAHManager::getInstance()->getAHName(_AHOnRightClick); }
const std::string &getActionOnDrop () const { return CAHManager::getInstance()->getAHName(_AHOnDrop); }
const std::string &getActionOnCanDrop () const { return CAHManager::getInstance()->getAHName(_AHOnCanDrop); }
const std::string &getParamsOnLeftClick () const { return _AHLeftClickParams; }
const std::string &getParamsOnRightClick () const { return _AHRightClickParams; }
const std::string &getParamsOnDrop () const { return _AHDropParams; }
const std::string &getParamsOnCanDrop () const { return _AHCanDropParams; }
void setListMenuLeft (const std::string &cm) { CCtrlSheetInfo::setListMenuLeft(cm); }
void setListMenuRight (const std::string &cm) { CCtrlSheetInfo::setListMenuRight(cm); }
void setListMenuBoth (const std::string &cm) { CCtrlSheetInfo::setListMenuBoth(cm); }
const std::string &getListMenuLeft () { return CCtrlSheetInfo::getListMenuLeft(); }
const std::string &getListMenuRight () { return CCtrlSheetInfo::getListMenuRight(); }
const std::string &getListMenuRightEmptySlot () {return CCtrlSheetInfo::getListMenuRightEmptySlot();}
void setCanDrop (bool cd) { _CanDrop = cd; }
bool getCanDrop () const { return _CanDrop; }
sint32 getDeltaDragX() {return _DeltaDragX;}
sint32 getDeltaDragY() {return _DeltaDragY;}
// For "oncandrag" action handlers only, which would want to avoid the drag
void setTempCanDrag(bool cd) {_TempCanDrag= cd;}
// called when a setCapturePointerLeft(NULL) is made for instance
CCtrlSheetInfo::TSheetType getType () const;
void setType (CCtrlSheetInfo::TSheetType type);
// Swap the content with another ctrl_sheet (debug): SheetId, Quantity and Quality
void swapSheet(CDBCtrlSheet *other);
void setSheetId(sint32 val) {_SheetId.setSInt32(val);}
void setQuality(sint32 val) {_Quality.setSInt32(val);}
void setQuantity(sint32 val) {_Quantity.setSInt32(val);}
void setItemNameId(uint32 val) {_NameId.setSInt32(val);}
void setEnchant(sint32 val) {_Enchant.setSInt32(val);}
// get sheet info.
sint32 getSheetId() const { return (sint32)_SheetId.getSInt32(); }
sint32 getQuality() const { return _UseQuality ? (sint32)_Quality.getSInt32() : 0; }
sint32 getEnchant() const { return _Enchant.getSInt32(); }
sint32 getQuantity() const { return (sint32)_Quantity.getSInt32(); }
uint32 getItemNameId() const { return (uint32)_NameId.getSInt32();}
// New Stack Size
sint32 getStackable() const { return (_Stackable>1) ? 999 : 1; }
// get non locked quantity (can be zero)
sint32 getNonLockedQuantity() const;
const CItemSheet *asItemSheet() const;
const CPactSheet *asPactSheet() const;
const CSBrickSheet *asSBrickSheet() const;
const CSPhraseSheet *asSPhraseSheet() const;
const COutpostBuildingSheet *asOutpostBuildingSheet() const;
// Operation on the link between the sheet and database. the string is the branch root of SHEET....
std::string getSheet() const;
void setSheet (const std::string &dbBranchId);
void setSheetFast( const std::string &dbParentBranchId, int sheetNum, int slotNum );
REFLECT_EXPORT_START(CDBCtrlSheet, CCtrlDraggable)
REFLECT_STRING("sheet", getSheet, setSheet);
REFLECT_RGBA("color", getSheetColor, setSheetColor);
REFLECT_RGBA("color1", getGuildColor1, setGuildColor1);
REFLECT_RGBA("color2", getGuildColor2, setGuildColor2);
REFLECT_SINT32("back", getGuildBack, setGuildBack);
REFLECT_SINT32("symbol", getGuildSymbol, setGuildSymbol);
REFLECT_BOOL("invert_symbol", getInvertGuildSymbol, setInvertGuildSymbol);
REFLECT_BOOL("can_drop", getCanDrop, setCanDrop);
REFLECT_STRING_REF ("left_click", getActionOnLeftClick, setActionOnLeftClick);
REFLECT_STRING_REF ("right_click", getActionOnRightClick, setActionOnRightClick);
REFLECT_STRING_REF ("left_click_params", getParamsOnLeftClick, setParamsOnLeftClick);
REFLECT_STRING_REF ("right_click_params", getParamsOnRightClick, setParamsOnRightClick);
REFLECT_STRING_REF ("on_drop", getActionOnDrop, setActionOnDrop);
REFLECT_STRING_REF ("on_drop_params", getParamsOnDrop, setParamsOnDrop);
REFLECT_STRING_REF ("on_can_drop", getActionOnCanDrop, setActionOnCanDrop);
REFLECT_STRING_REF ("on_can_drop_params", getParamsOnCanDrop, setParamsOnCanDrop);
REFLECT_LUA_METHOD("getDraggedSheet", luaGetDraggedSheet);
#ifdef RYZOM_FORGE
REFLECT_LUA_METHOD("getItemInfo", luaGetItemInfo);
#endif
REFLECT_LUA_METHOD("getName", luaGetName);
REFLECT_LUA_METHOD("getCreatorName", luaGetCreatorName);
REFLECT_LUA_METHOD("waitInfo", luaWaitInfo);
REFLECT_LUA_METHOD("buildCrystallizedSpellListBrick", luaBuildCrystallizedSpellListBrick);
REFLECT_EXPORT_END
int luaGetDraggedSheet(CLuaState &ls);
#ifdef RYZOM_FORGE
int luaGetItemInfo(CLuaState &ls);
#endif
int luaGetName(CLuaState &ls);
int luaGetCreatorName(CLuaState &ls);
int luaWaitInfo(CLuaState &ls);
int luaBuildCrystallizedSpellListBrick(CLuaState &ls);
// hardcode creation. User must setup other CtrlBase value (parent etc...)
void initSheet(const std::string &dbValue, const CCtrlSheetInfo &ctrlInfo);
void initSheetFast( const std::string &dbParentBranchId, int sheetNum, int slotNum,
const CCtrlSheetInfo &ctrlInfo );
// get the selection group for this ctrl sheet, or -1 if none
sint getSelectionGroup() const { return _SheetSelectionGroup; }
// get the selection group for this ctrl sheet as a string, or "" if none
const std::string &getSelectionGroupAsString() const;
// get the currently selected sheet (only one at a time)
static CDBCtrlSheet *getCurrSelection() { return _CurrSelection; }
// set the currently selected sheet.
static void setCurrSelection(CDBCtrlSheet *selected);
// get the root branch containing the properties for that sheet
NLMISC::CCDBNodeBranch *getRootBranch() const;
/** If the branch in setSheet(branch) is of the form ...:# (where # is a number), return this number.
* The value is hence modified by setSheet(). return 0 if not of this form.
*/
uint32 getIndexInDB() const {return _IndexInDB;}
/** If the branch in setSheet(branch) is of the form ...:#:# (where # are numbers), return this number.
* The value is hence modified by setSheet(). return 0 if not of this form.
*/
uint32 getSecondIndexInDB() const {return _SecondIndexInDB;}
// synonym for getSecondIndexInDB().
uint32 getInventoryIndex() const {return getSecondIndexInDB();}
// determine the inventory slot from the database branch id
static uint getInventorySlot( const std::string &dbBranchId );
// Get the last dropped sheet. The pointer is only valid during the call of the event handler
//static CDBCtrlSheet *getDraggedSheet() { return _LastDraggedSheet; }
/* Get the last selected sheet that have been draged or right clicked (should be use by menu to get their caller)
* It is used by the item actions like destroy, move etc..
*/
static CDBCtrlSheet *getCurrSelSheet() { return _CurrMenuSheet; }
static void setCurrSelSheet(CDBCtrlSheet *sheet) { _CurrMenuSheet = sheet; }
/// \name SBrick / SPhrase
// @{
// true if the ctrl_sheet is a Sabrina brick
bool isSBrick() const {return getType() ==SheetType_SBrick;}
// true if magic sentence is a Sabrina phrase
bool isSPhraseId() const {return getType()==SheetType_SPhraseId;}
// true if magic sentence is a Sabrina phrase
bool isSPhrase() const {return getType()==SheetType_SPhrase;}
// true if brick or magic sentence
bool isSBrickOrSPhraseId() const
{
CCtrlSheetInfo::TSheetType type= getType();
return type==SheetType_SBrick || type==SheetType_SPhraseId;
}
bool isSPhraseIdMemory() const;
// special for macro and Memories
bool isMacroMemory() const;
// return the phrase slot from database.
sint32 getSPhraseId() const;
/// true if it is a shortcut
bool isShortCut() const {return _ShortCut;}
// @}
/// Setup the alpha of the sheet drawn
void setSheetColor(NLMISC::CRGBA color) {_SheetColor= color;}
NLMISC::CRGBA getSheetColor() const {return _SheetColor;}
/// Special ContextHelp for ctrl sheet.
virtual void getContextHelp(std::string &help) const;
virtual void getContextHelpToolTip(std::string &help) const;
/** true if an item of another ctrlSheet can be dropped on this slot.
* also return true if src is 0, or if _ItemSlot==UNDEFINED
*/
bool canDropItem(CDBCtrlSheet *src) const;
/// Force the item/brick to be grayed. NB: no effect if "auto_grayed" is true
void setGrayed(bool state) { _Grayed= state;}
bool getGrayed() const
{
// If The Item sheet or phrase is 0, assume never grayed
if(_SheetId.getNodePtr() && getSheetId() == 0)
return false;
// NB: if a macro, getNodePtr()==NULL
else
return _Grayed;
}
// Additional gray for items. The item is finally grayed if one of this
void setItemWeared(bool state) {_ItemWeared= state;}
bool getItemWeared() const { return _ItemWeared;}
void setItemBeastGrayed(bool state) {_ItemBeastGrayed= state;}
bool getItemBeastGrayed() const { return _ItemBeastGrayed;}
void setUseQuality(bool use) { if(use!=_UseQuality) { _UseQuality= use; _NeedSetup= true;} }
void setUseQuantity(bool use) { if(use!=_UseQuantity) { _UseQuantity= use; _NeedSetup= true;} }
bool getUseQuality() const { return _UseQuality; }
bool getUseQuantity() const { return _UseQuantity; }
//
void setReadQuantityFromSheetFlag(bool on) { _ReadQuantityFromSheet = on; }
bool getReadQuantityFromSheetFlag() const { return _ReadQuantityFromSheet; }
// test if the sheet is a skill sheet
bool isSkill() const { return _HasTradeSlotType ? _TradeSlotType.getSInt32() == TRADE_SLOT_TYPE::Skill : false; }
// test if the sheet is a mission sheet
bool isMission() const;
// If the sheet is a skill, just get it
SKILLS::ESkills getSkill() const { return isSkill() ? (SKILLS::ESkills) getSheetId() : SKILLS::unknown; }
// set special behaviour
void setBehaviour(TRADE_SLOT_TYPE::TTradeSlotType type);
TRADE_SLOT_TYPE::TTradeSlotType getBehaviour() const { return _HasTradeSlotType ? (TRADE_SLOT_TYPE::TTradeSlotType) _TradeSlotType.getSInt32() : TRADE_SLOT_TYPE::StandardBehaviour; }
SLOTTYPE::TSlotType getItemSlot() { return _ItemSlot; }
void setItemSlot(SLOTTYPE::TSlotType slot) { _ItemSlot = slot; }
void setTextureNoItem(sint32 nTxID) { _DispNoSheetBmpId = nTxID; }
sint32 getTextureNoItem() { return _DispNoSheetBmpId; }
// copy the aspect of this sheet (not the handlers)
void copyAspect(CDBCtrlSheet *dest);
// true if same aspects.
bool sameAspect(CDBCtrlSheet *dest) const;
// get the sheet category
TSheetCategory getSheetCategory() const;
// get the ListSheet parent. NB: different code from CDBGroupListSheet and CDBGroupListSheetTrade. NULL if not found
IListSheetBase *getListSheetParent() const;
// get the index of this sheet in its parent list, or -1 if there's no such list
sint getIndexInParent() const;
// get the 'LOCKED' field in the db
NLMISC::CCDBNodeLeaf *getLockValuePtr() { return _GrayedLink; }
/// \name Macro
// @{
void readFromMacro(const CMacroCmd &mc); // Macro To ControlSheet
void writeToMacro(CMacroCmd &mc); // ControlSheet To Macro
void setMacroBack(uint8 nb);
void setMacroIcon(uint8 nb);
void setMacroOver(uint8 nb);
void setMacroText(const std::string &mcText);
sint32 getMacroId() const {return _MacroID;}
bool isMacro() const {return getType()==SheetType_Macro;}
// @}
/** According to ActualType, return true if the sheet is valid. eg: getSheetId()!=0 and brick exist
* for sheet type brucks. Always for Macros and skills.
*/
bool isSheetValid() const;
/// \name Guild Flag
// @{
NLMISC::CRGBA getGuildColor1() const;
NLMISC::CRGBA getGuildColor2() const;
sint32 getGuildBack() const;
sint32 getGuildSymbol() const;
bool getInvertGuildSymbol() const;
void setGuildColor1(NLMISC::CRGBA col);
void setGuildColor2(NLMISC::CRGBA col);
void setGuildBack(sint32 n);
void setGuildSymbol(sint32 n);
void setInvertGuildSymbol(bool b);
// @}
/// \name For teleport location
// @{
void setSlot(const std::string &textureName);
void initSheetSize();
// @}
NLMISC::CCDBNodeLeaf *getSlotType() const { return _TradeSlotType.getNodePtr(); }
// get item weight
uint16 getItemWeight() const;
NLMISC::CCDBNodeLeaf *getItemWeightPtr() const;
// set item weight
void setItemWeight(uint16 weight);
// get item info version
uint8 getItemInfoVersion() const;
NLMISC::CCDBNodeLeaf *getItemInfoVersionPtr() const;
// set item info version
void setItemInfoVersion(uint8 infoVersion);
// get item Locked state
uint16 getItemLocked() const;
NLMISC::CCDBNodeLeaf *getItemLockedPtr() const;
// set item locked state
void setItemLocked(uint16 lock);
// get item PRICE. 0 if no DB
sint32 getItemPrice() const;
NLMISC::CCDBNodeLeaf *getItemPricePtr() const;
// set item PRICE
void setItemPrice(sint32 price);
// get item RESALE_FLAG. 0 if no DB
sint32 getItemResaleFlag() const;
NLMISC::CCDBNodeLeaf *getItemResaleFlagPtr() const;
// set item RESALE_FLAG
void setItemResaleFlag(sint32 rf);
#ifdef RYZOM_FORGE
//get item CREATE_TIME. 0 if no DB
sint32 getItemCreateTime() const;
NLMISC::CCDBNodeLeaf *getItemCreateTimePtr() const;
// set item CREATE_TIME
void setItemCreateTime(sint32 ct);
//get item SERIAL. 0 if no DB
sint32 getItemSerial() const;
NLMISC::CCDBNodeLeaf *getItemSerialPtr() const;
// set item CREATE_TIME
void setItemSerial(sint32 serial);
#endif
// get item locked by owner
bool getLockedByOwner() const;
// true if the inventory supports owner locking
bool canOwnerLock() const;
// get item SELLER_TYPE. 0 if no DB
sint32 getItemSellerType() const;
NLMISC::CCDBNodeLeaf *getItemSellerTypePtr() const;
// set item SELLER_TYPE
void setItemSellerType(sint32 rf);
// get item FABER_QUALITY. 0 if no DB
RM_CLASS_TYPE::TRMClassType getItemRMClassType() const;
NLMISC::CCDBNodeLeaf *getItemRMClassTypePtr() const {return _ItemRMClassType;}
// set item FABER_QUALITY
void setItemRMClassType(sint32 fq);
// get item FABER_STAT_TYPE. 0 if no DB
RM_FABER_STAT_TYPE::TRMStatType getItemRMFaberStatType() const;
NLMISC::CCDBNodeLeaf *getItemRMFaberStatTypePtr() const {return _ItemRMFaberStatType;}
// set item FABER_STAT_TYPE
void setItemRMFaberStatType(sint32 fss);
// get item PREREQUISIT_VALID. true if no DB
bool getItemPrerequisitValid() const;
NLMISC::CCDBNodeLeaf *getItemPrerequisitValidPtr() const;
// set item PREREQUISIT_VALID
void setItemPrerequisitValid(bool prv);
// get color index of item (return -1 if no color available)
sint32 getItemColor() const {if(_UserColor) return _UserColor->getValue32(); else return -1;}
// set item color (if possible)
void setItemColor(sint32 val) {if(_UserColor) _UserColor->setValue32(val);}
// get item CHARAC_BUFFS. 0 if no DB
uint8 getItemCharacBuffs() const;
NLMISC::CCDBNodeLeaf *getItemCharacBuffsPtr() const;
// set item CHARAC_BUFFS
void setItemCharacBuffs(uint8 val);
// get item ACCESS. 0 if no DB
uint8 getItemAccess() const; // TODO: Guild grade & proper default
NLMISC::CCDBNodeLeaf *getItemAccessPtr() const;
// set item CHARAC_BUFFS
void setItemAccess(uint8 val);
// Get the Actual item name. Localized version of SheetId, or given by server through NAMEID.
std::string getItemActualName() const;
/// true if support drag copy (with CTRL). action handler has to check control.
bool canDragCopy() const {return _DragCopy;}
// special for items, call it at initInGame()
static void initArmourColors();
// true if an item that respect Carac requirement. NB: still return true if not an item
bool checkItemRequirement();
virtual void serial(NLMISC::IStream &f);
// From CCtrlBase, for phrases, we use a special, enhanced tooltip window
virtual std::string getContextHelpWindowName() const;
// For auras, powers, etc. set the range of ticks during which regen occurs
void setRegenTickRange(const CTickRange &tickRange);
const CTickRange &getRegenTickRange() const { return _RegenTickRange; }
// Default regen text is displayed on bottom of icon.
void setRegenText(bool b) { _RegenTextEnabled = b; }
// Allow to override default formatter.
// First parameter will be replaced with current timer value (always >= 0)
// If its a lua function, then parameters are
// 1: current timer value; can be negative
// 2: DB path for ctrl root (ie UI:VARIABLES:BONUSES:0), or nil
//
// ie: "secondsToTimeStringShort" -> CInterfaceExpr::evalAsString("secondsToTimeStringShort(123)", ret)
// ie: "lua:secondsToTimeStringShort" -> CInterfaceExpr::evalAsString("lua:secondsToTimeStringShort(123, 'UI:VARIABLES:BONUSES:0')", ret)
void setRegenTextFct(const std::string &s);
void setRegenTextY(sint32 y) { _RegenTextY = y; }
void setRegenTextShadow(bool b) { _RegenTextShadow = b; }
void setRegenTextShadowColor(NLMISC::CRGBA c) { _RegenTextShadowColor = c; }
void setRegenTextOutline(bool b) { _RegenTextOutline = b; }
void setRegenTextOutlineColor(NLMISC::CRGBA c) { _RegenTextOutlineColor = c; }
void setRegenTextFontSize(uint32 s) { _RegenTextFontSize = s; }
void setRegenTextColor(NLMISC::CRGBA c) { _RegenTextColor = c; }
// start notify anim (at the end of regen usually)
void startNotifyAnim();
void updateCharacBuffs();
#ifdef RYZOM_FORGE
// callback from info waiter
void infoReceived();
#endif
// set enchant/buff marker visiblility
#ifdef RYZOM_FORGE
static void setShowIconBuffs(bool b) { _ShowIconBuffs = b; }
#endif
protected:
#ifdef RYZOM_FORGE
inline bool useItemInfoForFamily(ITEMFAMILY::EItemFamily family) const;
#endif
void setupItem();
void setupPact();
void setupMacro();
void setupGuildFlag();
void setupMission();
void setupSBrick();
void setupSPhrase();
void setupSPhraseId();
void setupOutpostBuilding();
// optSheet is for special faber
void setupDisplayAsSBrick(sint32 sheet, sint32 optSheet= 0);
// setup icon from phrases
void setupDisplayAsPhrase(const std::vector<NLMISC::CSheetId> &bricks, const std::string &phraseName);
// draw a number and returns the width of the drawn number
sint32 drawNumber(sint32 x, sint32 y, sint32 wSheet, sint32 hSheet, NLMISC::CRGBA color, sint32 value, bool rightAlign=true);
protected:
// Root branch of the DB
std::string _DbBranchName;
// items db entries
CInterfaceProperty _SheetId;
CInterfaceProperty _NameId;
CInterfaceProperty _Quantity;
CInterfaceProperty _Quality;
CInterfaceProperty _TradeSlotType;
CInterfaceProperty _Enchant;
CInterfaceProperty _PrerequisitValid;
CInterfaceProperty _Worned; // if true means that item is worned (red cross, no longer usable unless it's a tool)
// As node leaf for backward compatibilities
NLMISC::CCDBNodeLeaf *_ItemRMClassType;
NLMISC::CCDBNodeLeaf *_ItemRMFaberStatType;
mutable sint32 _LastSheetId;
#ifdef RYZOM_FORGE
bool _ItemInfoChanged;
#endif
/// Display
sint32 _DispSlotBmpId; // Display slot bitmap id
sint32 _DispSelSlotId;
sint32 _DispBackBmpId; // Back Icon
sint32 _DispSheetBmpId; // Main Icon
sint32 _DispOverBmpId; // Over Icon
sint32 _DispOver2BmpId; // Over Icon N0 2 for bricks / items. Useful for items when _DispOverBmpId is used to paint user color on the item.
#ifdef RYZOM_FORGE
std::string _HpBuffIcon;
std::string _SapBuffIcon;
std::string _StaBuffIcon;
std::string _FocusBuffIcon;
#endif
// texture ids to show
struct SBuffIcon
{
SBuffIcon(sint32 txid, NLMISC::CRGBA col=NLMISC::CRGBA::White)
:TextureId(txid), Color(col), IconW(0), IconH(0)
{ }
sint32 TextureId;
NLMISC::CRGBA Color;
sint32 IconW;
sint32 IconH;
};
std::vector<SBuffIcon> _BuffIcons;
std::vector<SBuffIcon> _EnchantIcons;
// Level Brick or Quality
union
{
sint32 _DispQuality;
sint32 _DispLevel;
};
// Quantity for items
sint32 _DispQuantity;
sint32 _Stackable;
sint32 _TextureIdOver;
uint32 _IndexInDB;
uint32 _SecondIndexInDB;
// For SBrick only. Display level?
bool _MustDisplayLevel : 1;
/// Events
bool _CanDrop : 1;
bool _Over : 1;
/// Is a TaskBar shortcut
bool _ShortCut : 1;
/// Draw the slot ?
bool _DrawSlot : 1;
/// Is the Item/Brick as to be grayed?
bool _ItemBeastGrayed : 1; // This is an item in a pack animal / beast, that is unavailable
bool _ItemWeared : 1; // Item weared (for bags item)
bool _Grayed : 1;
bool _Useable : 1; // if false, means more than grayed: "red-ed" we cannot get or use it. SBrick, SPhrase and SItem
/// Init after parse()
bool _SetupInit : 1;
/// true if need a full setup in setupItem() ...
mutable bool _NeedSetup : 1;
// Temp for oncandrag AH
bool _TempCanDrag : 1;
// For ArmourColorFromDB
bool _ArmourColorFromDB : 1;
// True if the Armour Color Bitmaps have been setuped
bool _ArmourColorBmpOk : 1;
// Bkup of Armour Color index. -1 or 0..7
sint8 _ArmourColorIndex;
CTickRange _RegenTickRange;
NLGUI::CViewText *_RegenText;
sint32 _RegenTextValue;
//
std::string _RegenTextFct;
bool _RegenTextFctLua;
bool _RegenTextEnabled;
bool _RegenTextShadow;
bool _RegenTextOutline;
sint32 _RegenTextY;
uint32 _RegenTextFontSize;
NLMISC::CRGBA _RegenTextShadowColor;
NLMISC::CRGBA _RegenTextOutlineColor;
NLMISC::CRGBA _RegenTextColor;
/// D'n'd
sint32 _DragX, _DragY;
sint32 _DeltaDragX, _DeltaDragY;
sint32 _IconW, _IconH;
// Global color of the control.
NLMISC::CRGBA _SheetColor;
// Special colors (item/bricks)
NLMISC::CRGBA _IconBackColor;
NLMISC::CRGBA _IconColor;
NLMISC::CRGBA _IconOverColor;
NLMISC::CRGBA _IconOver2Color;
// Item only: Special armour color. black(0) if is not an armour
uint32 _PackedArmourColor;
// For an Item only. Useful for LeftHand Filtering: must have a pointer to the right hand
CDBCtrlSheet *_OtherHandItemFilter;
// This String is optional and usage dependent for Item, Macro, or Sentence
std::string _OptString;
NLMISC::CCDBNodeLeaf *_GrayedLink;
// Macro or sentence String compiled as texture Ids and positions, from the _OptString.
struct CCharBitmap
{
sint32 X,Y;
sint32 Id;
};
std::vector<CCharBitmap> _CharBitmaps;
// Macro Id
sint32 _MacroID;
// Guild Flag
NL3D::UTextureFile *_GuildBack;
NL3D::UTextureFile *_GuildSymb;
static NL3D::UMaterial _GuildMat;
bool _UseGuildIcon;
NLMISC::CSheetId _GuildIcon;
// SPhrase version
sint32 _LastPhraseVersion;
// special for items : colour of armour
static NLMISC::CRGBA _ArmourColor[8];
// special for items. Carac Requirement
CHARACTERISTICS::TCharacteristics _ItemCaracReqType;
sint32 _ItemCaracReqValue;
// Special for Armour
NLMISC::CCDBNodeLeaf *_UserColor;
// keep pointer on item sheet
const CItemSheet *_ItemSheet;
// unique persistent phrase exposed to lua script
static NLMISC::CSmartPtr<CSPhraseComAdpater> _PhraseAdapter;
sint64 _NotifyAnimEndTime;
#ifdef RYZOM_FORGE
mutable CControlSheetInfoWaiter _ItemInfoWaiter;
#endif
private:
mutable TSheetType _ActualType;
static CDBCtrlSheet *_CurrSelection;
static CDBCtrlSheet *_CurrMenuSheet;
#ifdef RYZOM_FORGE
static bool _ShowIconBuffs;
#endif
private:
void updateActualType() const;
void updateIconSize();
void resetAllTexIDs();
void setupInit();
#ifdef RYZOM_FORGE
// remove enchant and buff markers from item icon
void clearIconBuffs();
#endif
void setupCharBitmaps(sint32 maxW, sint32 maxLine, sint32 maxWChar= 1000, bool topDown= false);
void resetCharBitmaps();
void displayCharBitmaps(sint32 rdrLayer, sint32 x, sint32 y, NLMISC::CRGBA color);
// special for items
void updateItemCharacRequirement(sint32 sheetId);
#ifdef RYZOM_FORGE
// Send ITEM_INFO:GET request to server to fetch Buffs, Enchant info
void setupItemInfoWaiter();
#endif
// update armour color, and cache
void updateArmourColor(sint8 col);
// setup sheet DB. _DbBranchName must be ok, and _SecondIndexInDb and _IndexInDb as well
void setupSheetDbLinks ();
// 'regen' rendering
// convert from uv coordinates in the [0, 1] x [0, 1] range to screen coords
inline void uvToScreen(float x, float y, NLMISC::CVector &screenPos, uint texSize) const;
// from an angle in the [0, 1] range, return both uv & screen coords for that angle
// (angle is projected on the side of rectangle of the 'regen' texture)
void buildPieCorner(float angle, NLMISC::CUV &uv, NLMISC::CVector &pos, uint texSize) const;
// from a start and end angle in the [0, 1] range, build the set of uv mapped triangles necessary
// to display that 'pie'
// NB : output are indeed quads, at the time ofthis writing, uv mappedtri randering not available ...
// so we turn them into quad for conveniency ...
uint buildPie(NLMISC::CQuadUV *quv, float startAngle, float endAngle, uint texSize);
// gelper to draw the notify animation
void drawRotatedQuad(CViewRenderer &vr, float angle, float scale, uint renderLayer, uint32 textureId, sint32 texWidth, sint32 texHeight);
// create and draw regen text over icon
void drawRegenText();
};
/** User type (used with expression system of the interface, see interface_expr.h, that contains a pointer to a CDBCtrlSheet
*/
struct CDBCtrlSheetPtrUserType : public CInterfaceExprUserType
{
CDBCtrlSheet *Sheet; // pointer to a sheet
// ctor
CDBCtrlSheetPtrUserType(CDBCtrlSheet *sheet = NULL) : Sheet(sheet) {}
// from CInterfaceExprUserType
virtual CInterfaceExprUserType *clone() const { return new CDBCtrlSheetPtrUserType(*this); }
};
#endif // RZ_DBCTRL_SHEET_H
/* End of dbctrl_sheet.h */
| 0 | 0.957328 | 1 | 0.957328 | game-dev | MEDIA | 0.54602 | game-dev,desktop-app | 0.747127 | 1 | 0.747127 |
3dfxdev/EDGE | 6,944 | deps/physfs/extras/physfsrwops.c | /*
* This code provides a glue layer between PhysicsFS and Simple Directmedia
* Layer's (SDL) RWops i/o abstraction.
*
* License: this code is public domain. I make no warranty that it is useful,
* correct, harmless, or environmentally safe.
*
* This particular file may be used however you like, including copying it
* verbatim into a closed-source project, exploiting it commercially, and
* removing any trace of my name from the source (although I hope you won't
* do that). I welcome enhancements and corrections to this file, but I do
* not require you to send me patches if you make changes. This code has
* NO WARRANTY.
*
* Unless otherwise stated, the rest of PhysicsFS falls under the zlib license.
* Please see LICENSE.txt in the root of the source tree.
*
* SDL 1.2 falls under the LGPL license. SDL 1.3+ is zlib, like PhysicsFS.
* You can get SDL at https://www.libsdl.org/
*
* This file was written by Ryan C. Gordon. (icculus@icculus.org).
*/
#include <stdio.h> /* used for SEEK_SET, SEEK_CUR, SEEK_END ... */
#include "physfsrwops.h"
/* SDL's RWOPS interface changed a little in SDL 2.0... */
#if defined(SDL_VERSION_ATLEAST)
#if SDL_VERSION_ATLEAST(2, 0, 0)
#define TARGET_SDL2 1
#endif
#endif
#if !TARGET_SDL2
#ifndef RW_SEEK_SET
#define RW_SEEK_SET SEEK_SET
#endif
#ifndef RW_SEEK_CUR
#define RW_SEEK_CUR SEEK_CUR
#endif
#ifndef RW_SEEK_END
#define RW_SEEK_END SEEK_END
#endif
#endif
#if TARGET_SDL2
static Sint64 SDLCALL physfsrwops_size(struct SDL_RWops *rw)
{
PHYSFS_File *handle = (PHYSFS_File *) rw->hidden.unknown.data1;
return (Sint64) PHYSFS_fileLength(handle);
} /* physfsrwops_size */
#endif
#if TARGET_SDL2
static Sint64 SDLCALL physfsrwops_seek(struct SDL_RWops *rw, Sint64 offset, int whence)
#else
static int physfsrwops_seek(SDL_RWops *rw, int offset, int whence)
#endif
{
PHYSFS_File *handle = (PHYSFS_File *) rw->hidden.unknown.data1;
PHYSFS_sint64 pos = 0;
if (whence == RW_SEEK_SET)
pos = (PHYSFS_sint64) offset;
else if (whence == RW_SEEK_CUR)
{
const PHYSFS_sint64 current = PHYSFS_tell(handle);
if (current == -1)
{
SDL_SetError("Can't find position in file: %s",
PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
return -1;
} /* if */
if (offset == 0) /* this is a "tell" call. We're done. */
{
#if TARGET_SDL2
return (Sint64) current;
#else
return (int) current;
#endif
} /* if */
pos = current + ((PHYSFS_sint64) offset);
} /* else if */
else if (whence == RW_SEEK_END)
{
const PHYSFS_sint64 len = PHYSFS_fileLength(handle);
if (len == -1)
{
SDL_SetError("Can't find end of file: %s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
return -1;
} /* if */
pos = len + ((PHYSFS_sint64) offset);
} /* else if */
else
{
SDL_SetError("Invalid 'whence' parameter.");
return -1;
} /* else */
if ( pos < 0 )
{
SDL_SetError("Attempt to seek past start of file.");
return -1;
} /* if */
if (!PHYSFS_seek(handle, (PHYSFS_uint64) pos))
{
SDL_SetError("PhysicsFS error: %s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
return -1;
} /* if */
#if TARGET_SDL2
return (Sint64) pos;
#else
return (int) pos;
#endif
} /* physfsrwops_seek */
#if TARGET_SDL2
static size_t SDLCALL physfsrwops_read(struct SDL_RWops *rw, void *ptr,
size_t size, size_t maxnum)
#else
static int physfsrwops_read(SDL_RWops *rw, void *ptr, int size, int maxnum)
#endif
{
PHYSFS_File *handle = (PHYSFS_File *) rw->hidden.unknown.data1;
const PHYSFS_uint64 readlen = (PHYSFS_uint64) (maxnum * size);
const PHYSFS_sint64 rc = PHYSFS_readBytes(handle, ptr, readlen);
if (rc != ((PHYSFS_sint64) readlen))
{
if (!PHYSFS_eof(handle)) /* not EOF? Must be an error. */
{
SDL_SetError("PhysicsFS error: %s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
#if TARGET_SDL2
return 0;
#else
return -1;
#endif
} /* if */
} /* if */
#if TARGET_SDL2
return (size_t) rc / size;
#else
return (int) rc / size;
#endif
} /* physfsrwops_read */
#if TARGET_SDL2
static size_t SDLCALL physfsrwops_write(struct SDL_RWops *rw, const void *ptr,
size_t size, size_t num)
#else
static int physfsrwops_write(SDL_RWops *rw, const void *ptr, int size, int num)
#endif
{
PHYSFS_File *handle = (PHYSFS_File *) rw->hidden.unknown.data1;
const PHYSFS_uint64 writelen = (PHYSFS_uint64) (num * size);
const PHYSFS_sint64 rc = PHYSFS_writeBytes(handle, ptr, writelen);
if (rc != ((PHYSFS_sint64) writelen))
SDL_SetError("PhysicsFS error: %s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
#if TARGET_SDL2
return (size_t) rc;
#else
return (int) rc;
#endif
} /* physfsrwops_write */
static int physfsrwops_close(SDL_RWops *rw)
{
PHYSFS_File *handle = (PHYSFS_File *) rw->hidden.unknown.data1;
if (!PHYSFS_close(handle))
{
SDL_SetError("PhysicsFS error: %s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
return -1;
} /* if */
SDL_FreeRW(rw);
return 0;
} /* physfsrwops_close */
static SDL_RWops *create_rwops(PHYSFS_File *handle)
{
SDL_RWops *retval = NULL;
if (handle == NULL)
SDL_SetError("PhysicsFS error: %s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
else
{
retval = SDL_AllocRW();
if (retval != NULL)
{
#if TARGET_SDL2
retval->size = physfsrwops_size;
#endif
retval->seek = physfsrwops_seek;
retval->read = physfsrwops_read;
retval->write = physfsrwops_write;
retval->close = physfsrwops_close;
retval->hidden.unknown.data1 = handle;
} /* if */
} /* else */
return retval;
} /* create_rwops */
SDL_RWops *PHYSFSRWOPS_makeRWops(PHYSFS_File *handle)
{
SDL_RWops *retval = NULL;
if (handle == NULL)
SDL_SetError("NULL pointer passed to PHYSFSRWOPS_makeRWops().");
else
retval = create_rwops(handle);
return retval;
} /* PHYSFSRWOPS_makeRWops */
SDL_RWops *PHYSFSRWOPS_openRead(const char *fname)
{
return create_rwops(PHYSFS_openRead(fname));
} /* PHYSFSRWOPS_openRead */
SDL_RWops *PHYSFSRWOPS_openWrite(const char *fname)
{
return create_rwops(PHYSFS_openWrite(fname));
} /* PHYSFSRWOPS_openWrite */
SDL_RWops *PHYSFSRWOPS_openAppend(const char *fname)
{
return create_rwops(PHYSFS_openAppend(fname));
} /* PHYSFSRWOPS_openAppend */
/* end of physfsrwops.c ... */
| 0 | 0.931821 | 1 | 0.931821 | game-dev | MEDIA | 0.74743 | game-dev | 0.907257 | 1 | 0.907257 |
Kaggle/learntools | 3,799 | learntools/python/blackjack.py | import random
"""
Example display:
Player is dealt K and 3 (total = 13)
Dealer is dealt 8
Player hits and receives 5. (total = 18)
Player stays.
Dealer hits and receives 4 (total = 12)
Dealer hits and receives Q (total = 22)
Dealer busts! Player wins!
"""
class BlackJack:
def __init__(self, player_agent, verbose=False, legacy=False):
self.phit = player_agent
# Backwards compatibility with old call signature of should_hit
self.legacy = legacy
self.verbose = verbose
self.player_cards = []
self.dealer_cards = []
@staticmethod
def deal():
return random.choice(list(range(2, 11)) + ['A', 'J', 'Q', 'K'])
def log(self, msg):
if self.verbose:
print(msg)
@property
def player_total(self):
return self.card_total(self.player_cards)
@property
def dealer_total(self):
return self.card_total(self.dealer_cards)
@staticmethod
def card_total(cards, ace_counts=False):
tot = 0
aces = 0
for c in cards:
if c == 'A':
aces += 1
elif c in list('JQK'):
tot += 10
else:
tot += c
# tot is now the total of non-ace cards
tot = tot + aces
# tot is now the smallest possible total
# Looping here isn't strictly necessary because we'll never count more
# than one ace as high. But hey, we're future-proofed in case we ever
# want to implement 31.
high_aces = 0
for _ in range(aces):
if (tot + 10) <= 21:
tot += 10
high_aces += 1
if ace_counts:
return tot, (aces-high_aces), high_aces
return tot
def player_hits(self):
if self.legacy:
args = [self.player_total, self.dealer_total, self.player_cards.count('A')]
else:
player_total, low_aces, high_aces = self.card_total(self.player_cards, ace_counts=1)
args = [self.dealer_total, player_total, low_aces, high_aces]
return self.phit(*args)
def play(self):
p1, p2 = self.deal(), self.deal()
self.player_cards = [p1, p2]
self.log('Player starts with {} and {} (total = {})'.format(
p1, p2, self.player_total,
))
d1 = self.deal()
self.log('Dealer starts with {}'.format(d1))
self.dealer_cards = [d1]
self.log('\n__Player\'s turn__')
while self.player_hits():
c = self.deal()
self.player_cards.append(c)
self.log('Player hits and receives {}. (total = {})'.format(
c, self.player_total))
if self.player_total > 21:
self.log('Player busts! Dealer wins.')
return -1
self.log('Player stays')
self.log('\n__Dealer\'s turn__')
while True:
c = self.deal()
self.dealer_cards.append(c)
self.log('Dealer hits and receives {}. (total = {})'.format(
c, self.dealer_total))
if self.dealer_total > 21:
self.log('Dealer busts! Player wins.')
return 1
# Stand on 17
elif self.dealer_total >= 17:
self.log('Dealer stands.')
if self.dealer_total >= self.player_total:
self.log('Dealer wins. {} >= {}'.format(
self.dealer_total, self.player_total,
))
return -1
else:
self.log('Player wins. {} > {}'.format(
self.player_total, self.dealer_total,
))
return 1
| 0 | 0.678301 | 1 | 0.678301 | game-dev | MEDIA | 0.849509 | game-dev | 0.847038 | 1 | 0.847038 |
salutesh/DayZ-Expansion-Scripts | 1,303 | DayZExpansion/Quests/Scripts/4_World/DayZExpansion_Quests/Systems/Quests/ExpansionQuestItemConfig.c | /**
* ExpansionQuestItemConfig.c
*
* DayZ Expansion Mod
* www.dayzexpansion.com
* © 2022 DayZ Expansion Mod Team
*
* This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.
*
*/
class ExpansionQuestItemConfig
{
protected string ClassName = string.Empty;
protected int Amount = -1;
bool IsVehicle()
{
return ExpansionStatic.IsVehicle(ClassName);
}
void SetClassName(string name)
{
ClassName = name;
}
string GetClassName()
{
return ClassName;
}
void SetAmount(int amount)
{
Amount = amount;
}
int GetAmount()
{
return Amount;
}
void OnSend(ParamsWriteContext ctx)
{
ctx.Write(ClassName);
ctx.Write(Amount);
}
bool OnRecieve(ParamsReadContext ctx)
{
if (!ctx.Read(ClassName))
return false;
if (!ctx.Read(Amount))
return false;
return true;
}
void QuestDebug()
{
#ifdef EXPANSIONMODQUESTSINSTANCEDEBUG
Print("------------------------------------------------------------");
Print(ToString() + "::QuestDebug - ClassName: " + ClassName);
Print(ToString() + "::QuestDebug - Amount: " + Amount);
Print("------------------------------------------------------------");
#endif
}
}; | 0 | 0.908575 | 1 | 0.908575 | game-dev | MEDIA | 0.931121 | game-dev | 0.741409 | 1 | 0.741409 |
ServUO/ServUO | 2,860 | Scripts/Items/Equipment/Weapons/NoDachi.cs | using System;
using Server.Engines.Craft;
namespace Server.Items
{
[Alterable(typeof(DefBlacksmithy), typeof(GargishTalwar))]
[FlipableAttribute(0x27A2, 0x27ED)]
public class NoDachi : BaseSword
{
[Constructable]
public NoDachi()
: base(0x27A2)
{
this.Weight = 10.0;
this.Layer = Layer.TwoHanded;
}
public NoDachi(Serial serial)
: base(serial)
{
}
public override WeaponAbility PrimaryAbility
{
get
{
return WeaponAbility.CrushingBlow;
}
}
public override WeaponAbility SecondaryAbility
{
get
{
return WeaponAbility.RidingSwipe;
}
}
public override int AosStrengthReq
{
get
{
return 40;
}
}
public override int AosMinDamage
{
get
{
return 16;
}
}
public override int AosMaxDamage
{
get
{
return 19;
}
}
public override int AosSpeed
{
get
{
return 35;
}
}
public override float MlSpeed
{
get
{
return 3.50f;
}
}
public override int OldStrengthReq
{
get
{
return 40;
}
}
public override int OldMinDamage
{
get
{
return 16;
}
}
public override int OldMaxDamage
{
get
{
return 18;
}
}
public override int OldSpeed
{
get
{
return 35;
}
}
public override int DefHitSound
{
get
{
return 0x23B;
}
}
public override int DefMissSound
{
get
{
return 0x23A;
}
}
public override int InitMinHits
{
get
{
return 31;
}
}
public override int InitMaxHits
{
get
{
return 90;
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | 0 | 0.834149 | 1 | 0.834149 | game-dev | MEDIA | 0.808791 | game-dev | 0.928171 | 1 | 0.928171 |
b-crawl/bcrawl | 2,458 | crawl-ref/source/l-mapgrd.cc | #include "AppHdr.h"
#include "l-libs.h"
#include "cluautil.h"
#include "mapdef.h"
// mapgrd and mapgrd_col handling (i.e. map_lines in a metatable)
struct mapcolumn
{
map_def* map;
int col;
};
static int mapgrd_get(lua_State *ls)
{
// Return a metatable for this column in the map grid.
map_def *map = *(map_def **) luaL_checkudata(ls, 1, MAPGRD_METATABLE);
if (!map)
return 0;
int column = luaL_safe_checkint(ls, 2);
mapcolumn *mapref = clua_new_userdata<mapcolumn>(ls, MAPGRD_COL_METATABLE);
mapref->map = map;
mapref->col = column;
return 1;
}
static int mapgrd_set(lua_State *ls)
{
return luaL_error(ls, "%s", "Cannot assign to read-only table.");
}
static char* mapgrd_glyph(lua_State *ls, int &col, int &row)
{
mapcolumn *mapc = (mapcolumn *)luaL_checkudata(ls, 1, MAPGRD_COL_METATABLE);
if (!mapc)
return nullptr;
row = luaL_safe_checkint(ls, 2);
col = mapc->col;
map_lines &lines = mapc->map->map;
if (row < 0 || col < 0 || col >= lines.width() || row >= lines.height())
return nullptr;
coord_def mc(col, row);
return &lines(mc);
}
static int mapgrd_col_get(lua_State *ls)
{
int col, row;
char *gly = mapgrd_glyph(ls, col, row);
if (!gly)
return luaL_error(ls, "Invalid coords: %d, %d", col, row);
char buf[2];
buf[0] = *gly;
buf[1] = '\0';
lua_pushstring(ls, buf);
return 1;
}
static int mapgrd_col_set(lua_State *ls)
{
int col, row;
char *gly = mapgrd_glyph(ls, col, row);
if (!gly)
return luaL_error(ls, "Invalid coords: %d, %d", col, row);
const char *str = luaL_checkstring(ls, 3);
if (!str[0] || str[1])
return luaL_error(ls, "%s", "mapgrd must be set to a single char.");
(*gly) = str[0];
return 0;
}
void dluaopen_mapgrd(lua_State *ls)
{
// mapgrd table
luaL_newmetatable(ls, MAPGRD_METATABLE);
lua_pushstring(ls, "__index");
lua_pushcfunction(ls, mapgrd_get);
lua_settable(ls, -3);
lua_pushstring(ls, "__newindex");
lua_pushcfunction(ls, mapgrd_set);
lua_settable(ls, -3);
lua_pop(ls, 1);
// mapgrd col table
luaL_newmetatable(ls, MAPGRD_COL_METATABLE);
lua_pushstring(ls, "__index");
lua_pushcfunction(ls, mapgrd_col_get);
lua_settable(ls, -3);
lua_pushstring(ls, "__newindex");
lua_pushcfunction(ls, mapgrd_col_set);
lua_settable(ls, -3);
lua_pop(ls, 1);
}
| 0 | 0.921464 | 1 | 0.921464 | game-dev | MEDIA | 0.221088 | game-dev | 0.819739 | 1 | 0.819739 |
QuestionableM/SM-ProximityVoiceChat | 4,667 | Dependencies/bullet3/BulletDynamics/Dynamics/btSimulationIslandManagerMt.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_SIMULATION_ISLAND_MANAGER_MT_H
#define BT_SIMULATION_ISLAND_MANAGER_MT_H
#include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h"
class btTypedConstraint;
class btConstraintSolver;
struct btContactSolverInfo;
class btIDebugDraw;
///
/// SimulationIslandManagerMt -- Multithread capable version of SimulationIslandManager
/// Splits the world up into islands which can be solved in parallel.
/// In order to solve islands in parallel, an IslandDispatch function
/// must be provided which will dispatch calls to multiple threads.
/// The amount of parallelism that can be achieved depends on the number
/// of islands. If only a single island exists, then no parallelism is
/// possible.
///
class btSimulationIslandManagerMt : public btSimulationIslandManager
{
public:
struct Island
{
// a simulation island consisting of bodies, manifolds and constraints,
// to be passed into a constraint solver.
btAlignedObjectArray<btCollisionObject*> bodyArray;
btAlignedObjectArray<btPersistentManifold*> manifoldArray;
btAlignedObjectArray<btTypedConstraint*> constraintArray;
int id; // island id
bool isSleeping;
void append(const Island& other); // add bodies, manifolds, constraints to my own
};
struct SolverParams
{
btConstraintSolver* m_solverPool;
btConstraintSolver* m_solverMt;
btContactSolverInfo* m_solverInfo;
btIDebugDraw* m_debugDrawer;
btDispatcher* m_dispatcher;
};
static void solveIsland(btConstraintSolver* solver, Island& island, const SolverParams& solverParams);
typedef void (*IslandDispatchFunc)(btAlignedObjectArray<Island*>* islands, const SolverParams& solverParams);
static void serialIslandDispatch(btAlignedObjectArray<Island*>* islandsPtr, const SolverParams& solverParams);
static void parallelIslandDispatch(btAlignedObjectArray<Island*>* islandsPtr, const SolverParams& solverParams);
protected:
btAlignedObjectArray<Island*> m_allocatedIslands; // owner of all Islands
btAlignedObjectArray<Island*> m_activeIslands; // islands actively in use
btAlignedObjectArray<Island*> m_freeIslands; // islands ready to be reused
btAlignedObjectArray<Island*> m_lookupIslandFromId; // big lookup table to map islandId to Island pointer
Island* m_batchIsland;
int m_minimumSolverBatchSize;
int m_batchIslandMinBodyCount;
IslandDispatchFunc m_islandDispatch;
Island* getIsland(int id);
virtual Island* allocateIsland(int id, int numBodies);
virtual void initIslandPools();
virtual void addBodiesToIslands(btCollisionWorld* collisionWorld);
virtual void addManifoldsToIslands(btDispatcher* dispatcher);
virtual void addConstraintsToIslands(btAlignedObjectArray<btTypedConstraint*>& constraints);
virtual void mergeIslands();
public:
btSimulationIslandManagerMt();
virtual ~btSimulationIslandManagerMt();
virtual void buildAndProcessIslands(btDispatcher* dispatcher,
btCollisionWorld* collisionWorld,
btAlignedObjectArray<btTypedConstraint*>& constraints,
const SolverParams& solverParams);
virtual void buildIslands(btDispatcher* dispatcher, btCollisionWorld* colWorld);
int getMinimumSolverBatchSize() const
{
return m_minimumSolverBatchSize;
}
void setMinimumSolverBatchSize(int sz)
{
m_minimumSolverBatchSize = sz;
}
IslandDispatchFunc getIslandDispatchFunction() const
{
return m_islandDispatch;
}
// allow users to set their own dispatch function for multithreaded dispatch
void setIslandDispatchFunction(IslandDispatchFunc func)
{
m_islandDispatch = func;
}
};
#endif //BT_SIMULATION_ISLAND_MANAGER_H
| 0 | 0.801145 | 1 | 0.801145 | game-dev | MEDIA | 0.821591 | game-dev | 0.66284 | 1 | 0.66284 |
LofizKittyCat/GradleMCPBase | 1,487 | src/main/java/net/minecraft/client/renderer/entity/RenderSquid.java | package net.minecraft.client.renderer.entity;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.passive.EntitySquid;
import net.minecraft.util.ResourceLocation;
public class RenderSquid extends RenderLiving<EntitySquid>
{
private static final ResourceLocation squidTextures = new ResourceLocation("textures/entity/squid.png");
public RenderSquid(RenderManager renderManagerIn, ModelBase modelBaseIn, float shadowSizeIn)
{
super(renderManagerIn, modelBaseIn, shadowSizeIn);
}
protected ResourceLocation getEntityTexture(EntitySquid entity)
{
return squidTextures;
}
protected void rotateCorpse(EntitySquid bat, float p_77043_2_, float p_77043_3_, float partialTicks)
{
float f = bat.prevSquidPitch + (bat.squidPitch - bat.prevSquidPitch) * partialTicks;
float f1 = bat.prevSquidYaw + (bat.squidYaw - bat.prevSquidYaw) * partialTicks;
GlStateManager.translate(0.0F, 0.5F, 0.0F);
GlStateManager.rotate(180.0F - p_77043_3_, 0.0F, 1.0F, 0.0F);
GlStateManager.rotate(f, 1.0F, 0.0F, 0.0F);
GlStateManager.rotate(f1, 0.0F, 1.0F, 0.0F);
GlStateManager.translate(0.0F, -1.2F, 0.0F);
}
protected float handleRotationFloat(EntitySquid livingBase, float partialTicks)
{
return livingBase.lastTentacleAngle + (livingBase.tentacleAngle - livingBase.lastTentacleAngle) * partialTicks;
}
}
| 0 | 0.611869 | 1 | 0.611869 | game-dev | MEDIA | 0.878078 | game-dev,graphics-rendering | 0.763851 | 1 | 0.763851 |
Gethe/wow-ui-source | 1,311 | Interface/AddOns/Blizzard_GlueXML/Mainline/GlueTooltip.xml | <Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
..\..\Blizzard_SharedXML\UI.xsd">
<GameTooltip name="GlueTooltipTemplate" inherits="SharedTooltipTemplate" virtual="true">
<KeyValues>
<KeyValue key="textLeft1Font" value="GlueFontNormal" type="string"/>
<KeyValue key="textRight1Font" value="GlueFontNormal" type="string"/>
<KeyValue key="textLeft2Font" value="GlueFontNormalSmall" type="string"/>
<KeyValue key="textRight2Font" value="GlueFontNormalSmall" type="string"/>
</KeyValues>
<Scripts>
<OnTooltipCleared>
GameTooltip_ClearMoney(self);
SharedTooltip_ClearInsertedFrames(self);
</OnTooltipCleared>
</Scripts>
</GameTooltip>
<GameTooltip name="GlueTooltip" inherits="GlueTooltipTemplate" parent="GlueParent" />
<GameTooltip name="GlueNoHeaderTooltip" inherits="GlueTooltipTemplate" parent="GlueParent">
<KeyValues>
<KeyValue key="textLeft1Font" value="GlueFontNormalSmall" type="string"/>
<KeyValue key="textRight1Font" value="GlueFontNormalSmall" type="string"/>
<KeyValue key="textLeft2Font" value="GlueFontNormalSmall" type="string"/>
<KeyValue key="textRight2Font" value="GlueFontNormalSmall" type="string"/>
</KeyValues>
</GameTooltip>
</Ui>
| 0 | 0.622625 | 1 | 0.622625 | game-dev | MEDIA | 0.660668 | game-dev | 0.569369 | 1 | 0.569369 |
RS485/LogisticsPipes | 1,851 | common/logisticspipes/logisticspipes/IRoutedItem.java | /**
* Copyright (c) Krapht, 2011
* "LogisticsPipes" is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package logisticspipes.logisticspipes;
import java.util.List;
import java.util.UUID;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import logisticspipes.interfaces.routing.IAdditionalTargetInformation;
import logisticspipes.routing.IRouter;
import logisticspipes.routing.ItemRoutingInformation;
import logisticspipes.routing.order.IDistanceTracker;
import logisticspipes.utils.item.ItemIdentifierStack;
/**
* This interface describes the actions that must be available on an item that
* is considered routed
*/
public interface IRoutedItem {
enum TransportMode {
Unknown,
Default,
Passive,
Active
}
int getDestination();
UUID getDestinationUUID();
void setDestination(int destination);
void clearDestination();
void setTransportMode(TransportMode transportMode);
TransportMode getTransportMode();
void setAdditionalTargetInformation(IAdditionalTargetInformation info);
IAdditionalTargetInformation getAdditionalTargetInformation();
void setDoNotBuffer(boolean doNotBuffer);
boolean getDoNotBuffer();
int getBufferCounter();
void setBufferCounter(int counter);
void setArrived(boolean flag);
boolean getArrived();
void addToJamList(IRouter router);
List<Integer> getJamList();
void checkIDFromUUID();
ItemIdentifierStack getItemIdentifierStack();
void readFromNBT(NBTTagCompound data);
void writeToNBT(NBTTagCompound tagEntityItem);
void setDistanceTracker(IDistanceTracker tracker);
IDistanceTracker getDistanceTracker();
ItemRoutingInformation getInfo();
void split(int itemsToTake, EnumFacing orientation);
}
| 0 | 0.874775 | 1 | 0.874775 | game-dev | MEDIA | 0.873123 | game-dev | 0.958414 | 1 | 0.958414 |
danmaq/touhou-ctc-danmakufu | 4,499 | th_dnh/script/thC/INCLUDE/BOSS/Lily.dnh | //////////////////////////////////////////////////////////////////////
//====================================================================
//
// I ` Concealed the Conclusion
// {XŗLCu@[EzCg
//
// {XXNvgCN[hĂB
// ȊO̓CN[hȂłB
// ʂ̃{XŗLCuɃCN[hȂłB
//
//====================================================================
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// oϐ
//////////////////////////////////////////////////////////////////////
/** 摜yьʉt@C */
let m_szImageBoss = dotBossLily;
let m_szImageCutIn = cutLily;
let m_szImageShadow = IMAGE_CL_CIRCLE_6S;
let m_szImageShadowChar = dotShadow;
let m_aszImageList = IMAGE_LIST_LILY;
let m_aszImageBGList = LOADBGLIST_LILY;
/** I{̂̋NłȂꍇɃ[h摜yьʉ̃Xg */
let m_aszImageFileListNotStage = [ m_szImageShadow, m_szImageShadowChar ] ~ m_aszImageList ~ m_aszImageBGList;
let m_aszSeFileListNotStage = seListEnemy ~ seListShadow;
/** [h摜yьʉ̃Xg */
let m_aszImageFileList = [];
let m_aszSeFileList = [];
/** [vXe[^X 0:ʏ 1:Œ 2: 3:o */
let m_nWarpStatus = 0;
/** ŁEoJñJEg */
let m_nWarpCount = 0;
/** ŁEoJn犮܂ł̃JEg */
let m_nMaxWarpCount = 14;
//////////////////////////////////////////////////////////////////////
//--------------------------------------------------------------------
// wi`
//--------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////
/**
* wi`悵܂B
*/
function DrawSpellBG{
/** yʔŔwiȂ */
//if( m_bDrawSpellBGLight ){
// DrawSpellBG_Light();
// return;
//}
SetGraphicRect( 0, 0, 1024, 1024 );
DrawRotateCenter( imgSpellBamboo, 0.3 );
}
//////////////////////////////////////////////////////////////////////
//--------------------------------------------------------------------
// `֘A
//--------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////
/**
* `f[^ݒ肵܂B
* {X`OɌĂяoĂB
*/
function SetDrawDataLily{
let nScaleX = 1;
let nScaleY = 1;
let nHalfWarpCount = m_nMaxWarpCount / 2;
alternative( m_nWarpStatus )
/** Œ */
case( 1 ){
if( m_nWarpCount < nHalfWarpCount ){
nScaleX = 1 + 0.5 * m_nWarpCount / nHalfWarpCount;
nScaleY = 1 - 0.9 * m_nWarpCount / nHalfWarpCount;
}
else{
nScaleX = 1.5 - 1.5 * ( m_nWarpCount - nHalfWarpCount ) / nHalfWarpCount;
nScaleY = 0.1 + 2.4 * ( m_nWarpCount - nHalfWarpCount ) / nHalfWarpCount;
}
SetGraphicScale( nScaleX, nScaleY );
m_nEnemyAlpha = 255;
}
/** */
case( 2 ){
SetGraphicScale( 1, 1 );
m_nEnemyAlpha = 0;
}
/** o */
case( 3 ){
if( m_nWarpCount < nHalfWarpCount ){
nScaleX = 1.5 * m_nWarpCount / nHalfWarpCount;
nScaleY = 2.5 - 2.4 * m_nWarpCount / nHalfWarpCount;
}
else{
nScaleX = 1.5 - 0.5 * ( m_nWarpCount - nHalfWarpCount ) / nHalfWarpCount;
nScaleY = 0.1 + 0.9 * ( m_nWarpCount - nHalfWarpCount ) / nHalfWarpCount;
}
SetGraphicScale( nScaleX, nScaleY );
m_nEnemyAlpha = 255;
}
/** ʏ */
others{
SetGraphicScale( 1, 1 );
m_nEnemyAlpha = 255;
}
}
//////////////////////////////////////////////////////////////////////
//--------------------------------------------------------------------
//
//--------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////
/**
* [vړ܂B
* nFramem_nMaxWarpCount*2ȏłKv܂B
* @param nFrame [vt[
* @param nArea oGA 0:Ԓe 1:Ԓe 2:ԒeE 3:Ώ̒e 4:Xy 5:ʊO
*/
task Warp( let nFrame, let nArea ){
/** Œ */
m_nWarpStatus = 1;
m_nWarpCount = 0;
loop( m_nMaxWarpCount ){
yield;
m_nWarpCount ++;
}
/** */
SetEnemyMarker( false );
m_nWarpStatus = 2;
SetX( CL_CEN_X );
SetY( CL_MIN_Y - 1000 );
__Wait( nFrame - m_nMaxWarpCount * 2 );
/** o */
SetEnemyMarker( true );
alternative( nArea )
/** Ԓe */
case( 0 ){
SetX( CL_CEN_X );
SetY( CL_MIN_Y + 100 );
}
/** Ԓe */
case( 1 ){
SetX( rand( CL_MIN_X + 90, CL_CEN_X - 60 ) );
SetY( CL_MIN_Y + 100 + RandBlur( 20 ) );
}
/** ԒeE */
case( 2 ){
SetX( rand( CL_CEN_X + 60, CL_MAX_X - 90 ) );
SetY( CL_MIN_Y + 100 + RandBlur( 20 ) );
}
/** Ώ̒e */
case( 3 ){
SetX( CL_CEN_X );
SetY( CL_CEN_Y - 60 );
}
/** Xy */
case( 4 ){
SetX( CL_CEN_X );
SetY( CL_MIN_Y + 120 );
}
/** ʊO */
others{
SetX( CL_CEN_X );
SetY( CL_MIN_Y - 1000 );
}
m_nWarpStatus = 3;
m_nWarpCount = 0;
loop( m_nMaxWarpCount ){
yield;
m_nWarpCount ++;
}
m_nWarpStatus = 0;
}
| 0 | 0.702256 | 1 | 0.702256 | game-dev | MEDIA | 0.764258 | game-dev | 0.786117 | 1 | 0.786117 |
FashionFreedom/Seamly2D | 15,150 | src/libs/xerces-c/macx/include/xercesc/util/ValueHashTableOf.c | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Include
// ---------------------------------------------------------------------------
#if defined(XERCES_TMPLSINC)
#include <xercesc/util/ValueHashTableOf.hpp>
#endif
#include <xercesc/util/NullPointerException.hpp>
#include <xercesc/util/Janitor.hpp>
#include <assert.h>
#include <new>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// ValueHashTableOf: Constructors and Destructor
// ---------------------------------------------------------------------------
template <class TVal, class THasher>
ValueHashTableOf<TVal, THasher>::ValueHashTableOf( const XMLSize_t modulus
, const THasher& hasher
, MemoryManager* const manager)
: fMemoryManager(manager)
, fBucketList(0)
, fHashModulus(modulus)
, fInitialModulus(modulus)
, fCount(0)
, fHasher(hasher)
{
initialize(modulus);
}
template <class TVal, class THasher>
ValueHashTableOf<TVal, THasher>::ValueHashTableOf( const XMLSize_t modulus
, MemoryManager* const manager)
: fMemoryManager(manager)
, fBucketList(0)
, fHashModulus(modulus)
, fInitialModulus(modulus)
, fCount(0)
, fHasher()
{
initialize(modulus);
}
template <class TVal, class THasher>
void ValueHashTableOf<TVal, THasher>::initialize(const XMLSize_t modulus)
{
if (modulus == 0)
ThrowXMLwithMemMgr(IllegalArgumentException, XMLExcepts::HshTbl_ZeroModulus, fMemoryManager);
// Allocate the bucket list and zero them
fBucketList = (ValueHashTableBucketElem<TVal>**) fMemoryManager->allocate
(
fHashModulus * sizeof(ValueHashTableBucketElem<TVal>*)
); //new ValueHashTableBucketElem<TVal>*[fHashModulus];
memset(fBucketList, 0, sizeof(fBucketList[0]) * fHashModulus);
}
template <class TVal, class THasher>
ValueHashTableOf<TVal, THasher>::~ValueHashTableOf()
{
removeAll();
// Then delete the bucket list & hasher
fMemoryManager->deallocate(fBucketList); //delete [] fBucketList;
}
// ---------------------------------------------------------------------------
// ValueHashTableOf: Element management
// ---------------------------------------------------------------------------
template <class TVal, class THasher>
bool ValueHashTableOf<TVal, THasher>::isEmpty() const
{
return fCount==0;
}
template <class TVal, class THasher>
bool ValueHashTableOf<TVal, THasher>::
containsKey(const void* const key) const
{
XMLSize_t hashVal;
const ValueHashTableBucketElem<TVal>* findIt = findBucketElem(key, hashVal);
return (findIt != 0);
}
template <class TVal, class THasher>
void ValueHashTableOf<TVal, THasher>::
removeKey(const void* const key)
{
XMLSize_t hashVal;
removeBucketElem(key, hashVal);
}
template <class TVal, class THasher>
void ValueHashTableOf<TVal, THasher>::removeAll()
{
if(isEmpty())
return;
// Clean up the buckets first
for (XMLSize_t buckInd = 0; buckInd < fHashModulus; buckInd++)
{
// Get the bucket list head for this entry
ValueHashTableBucketElem<TVal>* curElem = fBucketList[buckInd];
ValueHashTableBucketElem<TVal>* nextElem;
while (curElem)
{
// Save the next element before we hose this one
nextElem = curElem->fNext;
// delete the current element and move forward
// destructor is empty...
// curElem->~ValueHashTableBucketElem();
fMemoryManager->deallocate(curElem);
curElem = nextElem;
}
// Clean out this entry
fBucketList[buckInd] = 0;
}
fCount = 0;
}
// ---------------------------------------------------------------------------
// ValueHashTableOf: Getters
// ---------------------------------------------------------------------------
template <class TVal, class THasher>
TVal& ValueHashTableOf<TVal, THasher>::get(const void* const key, MemoryManager* const manager)
{
XMLSize_t hashVal;
ValueHashTableBucketElem<TVal>* findIt = findBucketElem(key, hashVal);
if (!findIt)
ThrowXMLwithMemMgr(NoSuchElementException, XMLExcepts::HshTbl_NoSuchKeyExists, manager);
return findIt->fData;
}
template <class TVal, class THasher>
const TVal& ValueHashTableOf<TVal, THasher>::
get(const void* const key) const
{
XMLSize_t hashVal;
const ValueHashTableBucketElem<TVal>* findIt = findBucketElem(key, hashVal);
if (!findIt)
ThrowXMLwithMemMgr(NoSuchElementException, XMLExcepts::HshTbl_NoSuchKeyExists, fMemoryManager);
return findIt->fData;
}
// ---------------------------------------------------------------------------
// ValueHashTableOf: Putters
// ---------------------------------------------------------------------------
template <class TVal, class THasher>
void ValueHashTableOf<TVal, THasher>::put(void* key, const TVal& valueToAdopt)
{
// Apply 0.75 load factor to find threshold.
XMLSize_t threshold = fHashModulus * 3 / 4;
// If we've grown too big, expand the table and rehash.
if (fCount >= threshold)
rehash();
// First see if the key exists already
XMLSize_t hashVal;
ValueHashTableBucketElem<TVal>* newBucket = findBucketElem(key, hashVal);
//
// If so,then update its value. If not, then we need to add it to
// the right bucket
//
if (newBucket)
{
newBucket->fData = valueToAdopt;
newBucket->fKey = key;
}
else
{
newBucket =
new (fMemoryManager->allocate(sizeof(ValueHashTableBucketElem<TVal>)))
ValueHashTableBucketElem<TVal>(key, valueToAdopt, fBucketList[hashVal]);
fBucketList[hashVal] = newBucket;
fCount++;
}
}
// ---------------------------------------------------------------------------
// ValueHashTableOf: Private methods
// ---------------------------------------------------------------------------
template <class TVal, class THasher>
void ValueHashTableOf<TVal, THasher>::rehash()
{
const XMLSize_t newMod = (fHashModulus * 2) + 1;
ValueHashTableBucketElem<TVal>** newBucketList =
(ValueHashTableBucketElem<TVal>**) fMemoryManager->allocate
(
newMod * sizeof(ValueHashTableBucketElem<TVal>*)
);//new RefHashTableBucketElem<TVal>*[newMod];
// Make sure the new bucket list is destroyed if an
// exception is thrown.
ArrayJanitor<ValueHashTableBucketElem<TVal>*> guard(newBucketList, fMemoryManager);
memset(newBucketList, 0, newMod * sizeof(newBucketList[0]));
// Rehash all existing entries.
for (XMLSize_t index = 0; index < fHashModulus; index++)
{
// Get the bucket list head for this entry
ValueHashTableBucketElem<TVal>* curElem = fBucketList[index];
while (curElem)
{
// Save the next element before we detach this one
ValueHashTableBucketElem<TVal>* const nextElem = curElem->fNext;
const XMLSize_t hashVal = fHasher.getHashVal(curElem->fKey, newMod);
assert(hashVal < newMod);
ValueHashTableBucketElem<TVal>* const newHeadElem = newBucketList[hashVal];
// Insert at the start of this bucket's list.
curElem->fNext = newHeadElem;
newBucketList[hashVal] = curElem;
curElem = nextElem;
}
}
ValueHashTableBucketElem<TVal>** const oldBucketList = fBucketList;
// Everything is OK at this point, so update the
// member variables.
fBucketList = guard.release();
fHashModulus = newMod;
// Delete the old bucket list.
fMemoryManager->deallocate(oldBucketList);//delete[] oldBucketList;
}
template <class TVal, class THasher>
inline ValueHashTableBucketElem<TVal>* ValueHashTableOf<TVal, THasher>::
findBucketElem(const void* const key, XMLSize_t& hashVal)
{
// Hash the key
hashVal = fHasher.getHashVal(key, fHashModulus);
assert(hashVal < fHashModulus);
// Search that bucket for the key
ValueHashTableBucketElem<TVal>* curElem = fBucketList[hashVal];
while (curElem)
{
if (fHasher.equals(key, curElem->fKey))
return curElem;
curElem = curElem->fNext;
}
return 0;
}
template <class TVal, class THasher>
inline const ValueHashTableBucketElem<TVal>* ValueHashTableOf<TVal, THasher>::
findBucketElem(const void* const key, XMLSize_t& hashVal) const
{
// Hash the key
hashVal = fHasher.getHashVal(key, fHashModulus);
assert(hashVal < fHashModulus);
// Search that bucket for the key
const ValueHashTableBucketElem<TVal>* curElem = fBucketList[hashVal];
while (curElem)
{
if (fHasher.equals(key, curElem->fKey))
return curElem;
curElem = curElem->fNext;
}
return 0;
}
template <class TVal, class THasher>
void ValueHashTableOf<TVal, THasher>::
removeBucketElem(const void* const key, XMLSize_t& hashVal)
{
// Hash the key
hashVal = fHasher.getHashVal(key, fHashModulus);
assert(hashVal < fHashModulus);
//
// Search the given bucket for this key. Keep up with the previous
// element so we can patch around it.
//
ValueHashTableBucketElem<TVal>* curElem = fBucketList[hashVal];
ValueHashTableBucketElem<TVal>* lastElem = 0;
while (curElem)
{
if (fHasher.equals(key, curElem->fKey))
{
if (!lastElem)
{
// It was the first in the bucket
fBucketList[hashVal] = curElem->fNext;
}
else
{
// Patch around the current element
lastElem->fNext = curElem->fNext;
}
// Delete the current element
// delete curElem;
// destructor is empty...
// curElem->~ValueHashTableBucketElem();
fMemoryManager->deallocate(curElem);
fCount--;
return;
}
// Move both pointers upwards
lastElem = curElem;
curElem = curElem->fNext;
}
// We never found that key
ThrowXMLwithMemMgr(NoSuchElementException, XMLExcepts::HshTbl_NoSuchKeyExists, fMemoryManager);
}
// ---------------------------------------------------------------------------
// ValueHashTableOfEnumerator: Constructors and Destructor
// ---------------------------------------------------------------------------
template <class TVal, class THasher>
ValueHashTableOfEnumerator<TVal, THasher>::
ValueHashTableOfEnumerator(ValueHashTableOf<TVal, THasher>* const toEnum
, const bool adopt
, MemoryManager* const manager)
: fAdopted(adopt), fCurElem(0), fCurHash((XMLSize_t)-1), fToEnum(toEnum), fMemoryManager(manager)
{
if (!toEnum)
ThrowXMLwithMemMgr(NullPointerException, XMLExcepts::CPtr_PointerIsZero, manager);
//
// Find the next available bucket element in the hash table. If it
// comes back zero, that just means the table is empty.
//
// Note that the -1 in the current hash tells it to start from the
// beginning.
//
findNext();
}
template <class TVal, class THasher>
ValueHashTableOfEnumerator<TVal, THasher>::~ValueHashTableOfEnumerator()
{
if (fAdopted)
delete fToEnum;
}
// ---------------------------------------------------------------------------
// ValueHashTableOfEnumerator: Enum interface
// ---------------------------------------------------------------------------
template <class TVal, class THasher>
bool ValueHashTableOfEnumerator<TVal, THasher>::hasMoreElements() const
{
//
// If our current has is at the max and there are no more elements
// in the current bucket, then no more elements.
//
if (!fCurElem && (fCurHash == fToEnum->fHashModulus))
return false;
return true;
}
template <class TVal, class THasher>
TVal& ValueHashTableOfEnumerator<TVal, THasher>::nextElement()
{
// Make sure we have an element to return
if (!hasMoreElements())
ThrowXMLwithMemMgr(NoSuchElementException, XMLExcepts::Enum_NoMoreElements, fMemoryManager);
//
// Save the current element, then move up to the next one for the
// next time around.
//
ValueHashTableBucketElem<TVal>* saveElem = fCurElem;
findNext();
return saveElem->fData;
}
template <class TVal, class THasher>
void* ValueHashTableOfEnumerator<TVal, THasher>::nextElementKey()
{
// Make sure we have an element to return
if (!hasMoreElements())
ThrowXMLwithMemMgr(NoSuchElementException, XMLExcepts::Enum_NoMoreElements, fMemoryManager);
//
// Save the current element, then move up to the next one for the
// next time around.
//
ValueHashTableBucketElem<TVal>* saveElem = fCurElem;
findNext();
return saveElem->fKey;
}
template <class TVal, class THasher>
void ValueHashTableOfEnumerator<TVal, THasher>::Reset()
{
fCurHash = (XMLSize_t)-1;
fCurElem = 0;
findNext();
}
// ---------------------------------------------------------------------------
// ValueHashTableOfEnumerator: Private helper methods
// ---------------------------------------------------------------------------
template <class TVal, class THasher>
void ValueHashTableOfEnumerator<TVal, THasher>::findNext()
{
//
// If there is a current element, move to its next element. If this
// hits the end of the bucket, the next block will handle the rest.
//
if (fCurElem)
fCurElem = fCurElem->fNext;
//
// If the current element is null, then we have to move up to the
// next hash value. If that is the hash modulus, then we cannot
// go further.
//
if (!fCurElem)
{
if (++fCurHash == fToEnum->fHashModulus)
return;
// Else find the next non-empty bucket
while (fToEnum->fBucketList[fCurHash]==0)
{
// Bump to the next hash value. If we max out return
if (++fCurHash == fToEnum->fHashModulus)
return;
}
fCurElem = fToEnum->fBucketList[fCurHash];
}
}
XERCES_CPP_NAMESPACE_END
| 0 | 0.899115 | 1 | 0.899115 | game-dev | MEDIA | 0.79484 | game-dev | 0.951279 | 1 | 0.951279 |
Swofty-Developments/HypixelSkyBlock | 2,873 | type.skyblockgeneric/src/main/java/net/swofty/type/skyblockgeneric/server/eventcaller/CustomEventCaller.java | package net.swofty.type.skyblockgeneric.server.eventcaller;
import net.minestom.server.MinecraftServer;
import net.minestom.server.timer.Scheduler;
import net.minestom.server.timer.TaskSchedule;
import net.swofty.type.skyblockgeneric.SkyBlockGenericLoader;
import net.swofty.type.skyblockgeneric.user.SkyBlockPlayer;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CustomEventCaller {
private static final Map<SkyBlockPlayer, PlayerValues> playerValuesCache = new HashMap<>();
private static ServerValues serverValuesCache = null;
public static void start() {
Scheduler scheduler = MinecraftServer.getSchedulerManager();
// Per Player Caller
scheduler.submitTask(() -> {
for (SkyBlockPlayer player : SkyBlockGenericLoader.getLoadedPlayers()) {
if (!playerValuesCache.containsKey(player)) {
playerValuesCache.put(player, new PlayerValues(player, PlayerValues.Value.getValues()));
return TaskSchedule.seconds(1);
}
PlayerValues newValues = new PlayerValues(player, PlayerValues.Value.getValues());
List<PlayerValues.Value> differentValues = playerValuesCache.get(player).getDifferentValues(newValues);
differentValues.forEach(playerValue -> {
playerValue.getConsumer().accept(player, safeEntry(
playerValuesCache.get(player).getValue(playerValue),
newValues.getValue(playerValue)
));
});
playerValuesCache.put(player, newValues);
}
return TaskSchedule.seconds(1);
});
// Server Caller
scheduler.submitTask(() -> {
if (serverValuesCache == null) {
serverValuesCache = new ServerValues(ServerValues.Value.getValues());
return TaskSchedule.seconds(1);
}
ServerValues newValues = new ServerValues(ServerValues.Value.getValues());
List<ServerValues.Value> differentValues = serverValuesCache.getDifferentValues(newValues);
differentValues.forEach(serverValue -> {
if (serverValue.getShouldCall().apply(serverValuesCache.getValue(serverValue), newValues.getValue(serverValue))) {
serverValue.getConsumer().accept(newValues.getValue(serverValue));
}
});
serverValuesCache = newValues;
return TaskSchedule.seconds(1);
});
}
public static void clearCache(SkyBlockPlayer player) {
playerValuesCache.remove(player);
}
public static <K, V> Map.Entry<K, V> safeEntry(K key, V value) {
return new AbstractMap.SimpleEntry<>(key, value);
}
}
| 0 | 0.818003 | 1 | 0.818003 | game-dev | MEDIA | 0.729724 | game-dev,networking | 0.944766 | 1 | 0.944766 |
Fluorohydride/ygopro-scripts | 2,392 | c17589298.lua | --サクリファイス・ソード
function c17589298.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_CONTINUOUS_TARGET)
e1:SetTarget(c17589298.target)
e1:SetOperation(c17589298.operation)
c:RegisterEffect(e1)
--
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(400)
c:RegisterEffect(e2)
--Equip limit
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_EQUIP_LIMIT)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetValue(c17589298.eqlimit)
c:RegisterEffect(e3)
--tohand
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e4:SetCategory(CATEGORY_TOHAND)
e4:SetDescription(aux.Stringid(17589298,0))
e4:SetCode(EVENT_TO_GRAVE)
e4:SetCondition(c17589298.retcon)
e4:SetTarget(c17589298.rettg)
e4:SetOperation(c17589298.retop)
c:RegisterEffect(e4)
end
function c17589298.eqlimit(e,c)
return c:IsAttribute(ATTRIBUTE_DARK)
end
function c17589298.filter(c)
return c:IsFaceup() and c:IsAttribute(ATTRIBUTE_DARK)
end
function c17589298.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c17589298.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c17589298.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c17589298.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c17589298.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,c,tc)
end
end
function c17589298.retcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local ec=c:GetPreviousEquipTarget()
return c:IsReason(REASON_LOST_TARGET) and ec:IsReason(REASON_RELEASE)
end
function c17589298.rettg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToHand() end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,e:GetHandler(),1,0,0)
end
function c17589298.retop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SendtoHand(c,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,c)
end
end
| 0 | 0.820454 | 1 | 0.820454 | game-dev | MEDIA | 0.974813 | game-dev | 0.833686 | 1 | 0.833686 |
SpaceMadness/lunar-unity-plugin | 9,290 | Project/Assets/LunarPlugin/Scripts/Console/CRuntimeResolver.cs | //
// CRuntimeResolver.cs
//
// Lunar Plugin for Unity: a command line solution for your game.
// https://github.com/SpaceMadness/lunar-unity-plugin
//
// Copyright 2016 Alex Lementuev, SpaceMadness.
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using UnityEngine;
using LunarPlugin;
namespace LunarPluginInternal
{
using Option = CCommand.Option;
public class CRuntimeResolverException : Exception
{
public CRuntimeResolverException(string message, Exception innerException)
: base(message, innerException)
{
}
}
internal static class CRuntimeResolver // TODO: remove this class
{
public static Result Resolve()
{
Result result = new Result();
try
{
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Type type in assembly.GetTypes())
{
CCommand cmd;
if ((cmd = ResolveCommand(type)) != null)
{
result.AddCommand(cmd);
}
else if (IsCVarContainer(type))
{
result.AddContainer(type);
}
}
}
}
catch (ReflectionTypeLoadException e)
{
StringBuilder message = new StringBuilder("Unable to resolve Lunar commands:");
foreach (Exception ex in e.LoaderExceptions)
{
message.AppendFormat("\n\t{0}", ex.Message);
}
throw new CRuntimeResolverException(message.ToString(), e);
}
catch (Exception e)
{
throw new CRuntimeResolverException("Unable to resolve Lunar commands", e);
}
return result;
}
private static CCommand ResolveCommand(Type type)
{
CCommandAttribute cmdAttr = GetCustomAttribute<CCommandAttribute>(type);
if (cmdAttr != null)
{
string commandName = cmdAttr.Name;
if (!IsCorrectPlatform(cmdAttr.Flags))
{
Debug.LogWarning("Skipping command: " + commandName);
return null;
}
CCommand command = CClassUtils.CreateInstance<CCommand>(type);
if (command != null)
{
command.Name = commandName;
command.Description = cmdAttr.Description;
if (cmdAttr.Values != null)
{
command.Values = cmdAttr.Values.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
}
command.Flags |= cmdAttr.Flags;
ResolveOptions(command);
return command;
}
else
{
CLog.e("Unable to register command: name={0} type={1}", commandName, type);
}
}
return null;
}
private static bool IsCVarContainer(Type type)
{
return GetCustomAttribute<CVarContainerAttribute>(type) != null;
}
private static T GetCustomAttribute<T>(Type type) where T : Attribute
{
object[] attributes = type.GetCustomAttributes(typeof(T), false);
return attributes != null && attributes.Length == 1 ? attributes[0] as T : null;
}
public static void ResolveOptions(CCommand command)
{
ResolveOptions(command, command.GetType());
}
public static void ResolveOptions(CCommand command, Type commandType)
{
FieldInfo[] fields = commandType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
for (int i = 0; i < fields.Length; ++i)
{
FieldInfo info = fields[i];
object[] attributes = info.GetCustomAttributes(typeof(CCommandOptionAttribute), true);
if (attributes.Length == 1)
{
CCommandOptionAttribute attr = (CCommandOptionAttribute)attributes[0];
string name = attr.Name != null ? attr.Name : info.Name;
Option option = new Option(info, name, attr.Description);
if (attr.Values != null)
{
option.Values = ParseValues(attr.Values, info.FieldType);
}
option.ShortName = attr.ShortName;
option.IsRequired = attr.Required;
option.DefaultValue = GetDefaultValue(command, info);
command.AddOption(option);
}
}
}
private static string[] ParseValues(string str, Type type)
{
string[] tokens = str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < tokens.Length; ++i)
{
string token = tokens[i].Trim();
if (Option.IsValidValue(type, token))
{
tokens[i] = token;
}
else
{
throw new CCommandParseException("Invalid value '{0}' for type '{1}'", token, type);
}
}
Array.Sort(tokens);
return tokens;
}
private static bool IsCorrectPlatform(CCommandFlags flags)
{
/*
if ((flags & CCommandFlags.IOS) != 0 && !Runtime.IsIOS)
{
return false;
}
if ((flags & CCommandFlags.Android) != 0 && !Runtime.IsAndroid)
{
return false;
}
if ((flags & CCommandFlags.Mobile) != 0 && !Runtime.IsMobile)
{
return false;
}
if ((flags & CCommandFlags.Standalone) != 0 && !Runtime.IsStandAlone)
{
return false;
}
if ((flags & CCommandFlags.OSX) != 0 && !Runtime.IsOSX)
{
Debug.Log(4);
return false;
}
if ((flags & CCommandFlags.Windows) != 0 && !Runtime.IsWindows)
{
Debug.Log(5);
return false;
}
if ((flags & CCommandFlags.Linux) != 0 && !Runtime.IsLinux)
{
Debug.Log(6);
return false;
}
if ((flags & CCommandFlags.Editor) != 0)
{
if ((flags & CCommandFlags.OSXEditor) != 0 && !Runtime.IsOSXEditor)
{
return false;
}
if ((flags & CCommandFlags.WindowsEditor) != 0 && !Runtime.IsWindowsEditor)
{
return false;
}
return true;
}
*/
return true;
}
private static object GetDefaultValue(CCommand command, FieldInfo info)
{
object value = info.GetValue(command);
if (info.FieldType.IsValueType)
{
return value;
}
return value is ICloneable ? ((ICloneable)value).Clone() : value;
}
public class Result
{
private IList<CCommand> commands;
private IList<Type> cvarContainersTypes;
public Result()
{
commands = new List<CCommand>();
}
public void AddCommand(CCommand cmd)
{
commands.Add(cmd);
}
public void AddContainer(Type type)
{
if (cvarContainersTypes == null)
cvarContainersTypes = new List<Type>();
cvarContainersTypes.Add(type);
}
public IList<CCommand> Commands
{
get { return commands; }
}
public IList<Type> CvarContainersTypes
{
get { return cvarContainersTypes; }
}
}
}
}
| 0 | 0.967368 | 1 | 0.967368 | game-dev | MEDIA | 0.832087 | game-dev | 0.973514 | 1 | 0.973514 |
PuneetKohli/Step-Inside-2D-Floorplan-to-3D-Walkthrough | 1,765 | Assets/NGUI/Scripts/Tweening/TweenOrthoSize.cs | //----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2016 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the camera's orthographic size.
/// </summary>
[RequireComponent(typeof(Camera))]
[AddComponentMenu("NGUI/Tween/Tween Orthographic Size")]
public class TweenOrthoSize : UITweener
{
public float from = 1f;
public float to = 1f;
Camera mCam;
/// <summary>
/// Camera that's being tweened.
/// </summary>
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
public Camera cachedCamera { get { if (mCam == null) mCam = camera; return mCam; } }
#else
public Camera cachedCamera { get { if (mCam == null) mCam = GetComponent<Camera>(); return mCam; } }
#endif
[System.Obsolete("Use 'value' instead")]
public float orthoSize { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public float value
{
get { return cachedCamera.orthographicSize; }
set { cachedCamera.orthographicSize = value; }
}
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished) { value = from * (1f - factor) + to * factor; }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenOrthoSize Begin (GameObject go, float duration, float to)
{
TweenOrthoSize comp = UITweener.Begin<TweenOrthoSize>(go, duration);
comp.from = comp.value;
comp.to = to;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
public override void SetStartToCurrentValue () { from = value; }
public override void SetEndToCurrentValue () { to = value; }
}
| 0 | 0.819677 | 1 | 0.819677 | game-dev | MEDIA | 0.868516 | game-dev | 0.934604 | 1 | 0.934604 |
gideros/gideros | 16,849 | plugins/liquidfun/source/liquidfun/Box2D/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Joints/b2PrismaticJoint.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2TimeStep.h>
// Linear constraint (point-to-line)
// d = p2 - p1 = x2 + r2 - x1 - r1
// C = dot(perp, d)
// Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1))
// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2)
// J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)]
//
// Angular constraint
// C = a2 - a1 + a_initial
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
//
// K = J * invM * JT
//
// J = [-a -s1 a s2]
// [0 -1 0 1]
// a = perp
// s1 = cross(d + r1, a) = cross(p2 - x1, a)
// s2 = cross(r2, a) = cross(p2 - x2, a)
// Motor/Limit linear constraint
// C = dot(ax1, d)
// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2)
// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)]
// Block Solver
// We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even
// when the mass has poor distribution (leading to large torques about the joint anchor points).
//
// The Jacobian has 3 rows:
// J = [-uT -s1 uT s2] // linear
// [0 -1 0 1] // angular
// [-vT -a1 vT a2] // limit
//
// u = perp
// v = axis
// s1 = cross(d + r1, u), s2 = cross(r2, u)
// a1 = cross(d + r1, v), a2 = cross(r2, v)
// M * (v2 - v1) = JT * df
// J * v2 = bias
//
// v2 = v1 + invM * JT * df
// J * (v1 + invM * JT * df) = bias
// K * df = bias - J * v1 = -Cdot
// K = J * invM * JT
// Cdot = J * v1 - bias
//
// Now solve for f2.
// df = f2 - f1
// K * (f2 - f1) = -Cdot
// f2 = invK * (-Cdot) + f1
//
// Clamp accumulated limit impulse.
// lower: f2(3) = max(f2(3), 0)
// upper: f2(3) = min(f2(3), 0)
//
// Solve for correct f2(1:2)
// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1
// = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3)
// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2)
// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2)
//
// Now compute impulse to be applied:
// df = f2 - f1
void b2PrismaticJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis)
{
bodyA = bA;
bodyB = bB;
localAnchorA = bodyA->GetLocalPoint(anchor);
localAnchorB = bodyB->GetLocalPoint(anchor);
localAxisA = bodyA->GetLocalVector(axis);
referenceAngle = bodyB->GetAngle() - bodyA->GetAngle();
}
b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def)
: b2Joint(def)
{
m_localAnchorA = def->localAnchorA;
m_localAnchorB = def->localAnchorB;
m_localXAxisA = def->localAxisA;
m_localXAxisA.Normalize();
m_localYAxisA = b2Cross(1.0f, m_localXAxisA);
m_referenceAngle = def->referenceAngle;
m_impulse.SetZero();
m_motorMass = 0.0f;
m_motorImpulse = 0.0f;
m_lowerTranslation = def->lowerTranslation;
m_upperTranslation = def->upperTranslation;
m_maxMotorForce = def->maxMotorForce;
m_motorSpeed = def->motorSpeed;
m_enableLimit = def->enableLimit;
m_enableMotor = def->enableMotor;
m_limitState = e_inactiveLimit;
m_axis.SetZero();
m_perp.SetZero();
}
void b2PrismaticJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_localCenterA = m_bodyA->m_sweep.localCenter;
m_localCenterB = m_bodyB->m_sweep.localCenter;
m_invMassA = m_bodyA->m_invMass;
m_invMassB = m_bodyB->m_invMass;
m_invIA = m_bodyA->m_invI;
m_invIB = m_bodyB->m_invI;
b2Vec2 cA = data.positions[m_indexA].c;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 cB = data.positions[m_indexB].c;
float32 aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Rot qA(aA), qB(aB);
// Compute the effective masses.
b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
b2Vec2 d = (cB - cA) + rB - rA;
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
// Compute motor Jacobian and effective mass.
{
m_axis = b2Mul(qA, m_localXAxisA);
m_a1 = b2Cross(d + rA, m_axis);
m_a2 = b2Cross(rB, m_axis);
m_motorMass = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2;
if (m_motorMass > 0.0f)
{
m_motorMass = 1.0f / m_motorMass;
}
}
// Prismatic constraint.
{
m_perp = b2Mul(qA, m_localYAxisA);
m_s1 = b2Cross(d + rA, m_perp);
m_s2 = b2Cross(rB, m_perp);
float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2;
float32 k12 = iA * m_s1 + iB * m_s2;
float32 k13 = iA * m_s1 * m_a1 + iB * m_s2 * m_a2;
float32 k22 = iA + iB;
if (k22 == 0.0f)
{
// For bodies with fixed rotation.
k22 = 1.0f;
}
float32 k23 = iA * m_a1 + iB * m_a2;
float32 k33 = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2;
m_K.ex.Set(k11, k12, k13);
m_K.ey.Set(k12, k22, k23);
m_K.ez.Set(k13, k23, k33);
}
// Compute motor and limit terms.
if (m_enableLimit)
{
float32 jointTranslation = b2Dot(m_axis, d);
if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop)
{
m_limitState = e_equalLimits;
}
else if (jointTranslation <= m_lowerTranslation)
{
if (m_limitState != e_atLowerLimit)
{
m_limitState = e_atLowerLimit;
m_impulse.z = 0.0f;
}
}
else if (jointTranslation >= m_upperTranslation)
{
if (m_limitState != e_atUpperLimit)
{
m_limitState = e_atUpperLimit;
m_impulse.z = 0.0f;
}
}
else
{
m_limitState = e_inactiveLimit;
m_impulse.z = 0.0f;
}
}
else
{
m_limitState = e_inactiveLimit;
m_impulse.z = 0.0f;
}
if (m_enableMotor == false)
{
m_motorImpulse = 0.0f;
}
if (data.step.warmStarting)
{
// Account for variable time step.
m_impulse *= data.step.dtRatio;
m_motorImpulse *= data.step.dtRatio;
b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis;
float32 LA = m_impulse.x * m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a1;
float32 LB = m_impulse.x * m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a2;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
else
{
m_impulse.SetZero();
m_motorImpulse = 0.0f;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
void b2PrismaticJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
// Solve linear motor constraint.
if (m_enableMotor && m_limitState != e_equalLimits)
{
float32 Cdot = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA;
float32 impulse = m_motorMass * (m_motorSpeed - Cdot);
float32 oldImpulse = m_motorImpulse;
float32 maxImpulse = data.step.dt * m_maxMotorForce;
m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_motorImpulse - oldImpulse;
b2Vec2 P = impulse * m_axis;
float32 LA = impulse * m_a1;
float32 LB = impulse * m_a2;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
b2Vec2 Cdot1;
Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA;
Cdot1.y = wB - wA;
if (m_enableLimit && m_limitState != e_inactiveLimit)
{
// Solve prismatic and limit constraint in block form.
float32 Cdot2;
Cdot2 = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA;
b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2);
b2Vec3 f1 = m_impulse;
b2Vec3 df = m_K.Solve33(-Cdot);
m_impulse += df;
if (m_limitState == e_atLowerLimit)
{
m_impulse.z = b2Max(m_impulse.z, 0.0f);
}
else if (m_limitState == e_atUpperLimit)
{
m_impulse.z = b2Min(m_impulse.z, 0.0f);
}
// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2)
b2Vec2 b = -Cdot1 - (m_impulse.z - f1.z) * b2Vec2(m_K.ez.x, m_K.ez.y);
b2Vec2 f2r = m_K.Solve22(b) + b2Vec2(f1.x, f1.y);
m_impulse.x = f2r.x;
m_impulse.y = f2r.y;
df = m_impulse - f1;
b2Vec2 P = df.x * m_perp + df.z * m_axis;
float32 LA = df.x * m_s1 + df.y + df.z * m_a1;
float32 LB = df.x * m_s2 + df.y + df.z * m_a2;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
else
{
// Limit is inactive, just solve the prismatic constraint in block form.
b2Vec2 df = m_K.Solve22(-Cdot1);
m_impulse.x += df.x;
m_impulse.y += df.y;
b2Vec2 P = df.x * m_perp;
float32 LA = df.x * m_s1 + df.y;
float32 LB = df.x * m_s2 + df.y;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
bool b2PrismaticJoint::SolvePositionConstraints(const b2SolverData& data)
{
b2Vec2 cA = data.positions[m_indexA].c;
float32 aA = data.positions[m_indexA].a;
b2Vec2 cB = data.positions[m_indexB].c;
float32 aB = data.positions[m_indexB].a;
b2Rot qA(aA), qB(aB);
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
// Compute fresh Jacobians
b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
b2Vec2 d = cB + rB - cA - rA;
b2Vec2 axis = b2Mul(qA, m_localXAxisA);
float32 a1 = b2Cross(d + rA, axis);
float32 a2 = b2Cross(rB, axis);
b2Vec2 perp = b2Mul(qA, m_localYAxisA);
float32 s1 = b2Cross(d + rA, perp);
float32 s2 = b2Cross(rB, perp);
b2Vec3 impulse;
b2Vec2 C1;
C1.x = b2Dot(perp, d);
C1.y = aB - aA - m_referenceAngle;
float32 linearError = b2Abs(C1.x);
float32 angularError = b2Abs(C1.y);
bool active = false;
float32 C2 = 0.0f;
if (m_enableLimit)
{
float32 translation = b2Dot(axis, d);
if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop)
{
// Prevent large angular corrections
C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection);
linearError = b2Max(linearError, b2Abs(translation));
active = true;
}
else if (translation <= m_lowerTranslation)
{
// Prevent large linear corrections and allow some slop.
C2 = b2Clamp(translation - m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f);
linearError = b2Max(linearError, m_lowerTranslation - translation);
active = true;
}
else if (translation >= m_upperTranslation)
{
// Prevent large linear corrections and allow some slop.
C2 = b2Clamp(translation - m_upperTranslation - b2_linearSlop, 0.0f, b2_maxLinearCorrection);
linearError = b2Max(linearError, translation - m_upperTranslation);
active = true;
}
}
if (active)
{
float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
float32 k12 = iA * s1 + iB * s2;
float32 k13 = iA * s1 * a1 + iB * s2 * a2;
float32 k22 = iA + iB;
if (k22 == 0.0f)
{
// For fixed rotation
k22 = 1.0f;
}
float32 k23 = iA * a1 + iB * a2;
float32 k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2;
b2Mat33 K;
K.ex.Set(k11, k12, k13);
K.ey.Set(k12, k22, k23);
K.ez.Set(k13, k23, k33);
b2Vec3 C;
C.x = C1.x;
C.y = C1.y;
C.z = C2;
impulse = K.Solve33(-C);
}
else
{
float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
float32 k12 = iA * s1 + iB * s2;
float32 k22 = iA + iB;
if (k22 == 0.0f)
{
k22 = 1.0f;
}
b2Mat22 K;
K.ex.Set(k11, k12);
K.ey.Set(k12, k22);
b2Vec2 impulse1 = K.Solve(-C1);
impulse.x = impulse1.x;
impulse.y = impulse1.y;
impulse.z = 0.0f;
}
b2Vec2 P = impulse.x * perp + impulse.z * axis;
float32 LA = impulse.x * s1 + impulse.y + impulse.z * a1;
float32 LB = impulse.x * s2 + impulse.y + impulse.z * a2;
cA -= mA * P;
aA -= iA * LA;
cB += mB * P;
aB += iB * LB;
data.positions[m_indexA].c = cA;
data.positions[m_indexA].a = aA;
data.positions[m_indexB].c = cB;
data.positions[m_indexB].a = aB;
return linearError <= b2_linearSlop && angularError <= b2_angularSlop;
}
b2Vec2 b2PrismaticJoint::GetAnchorA() const
{
return m_bodyA->GetWorldPoint(m_localAnchorA);
}
b2Vec2 b2PrismaticJoint::GetAnchorB() const
{
return m_bodyB->GetWorldPoint(m_localAnchorB);
}
b2Vec2 b2PrismaticJoint::GetReactionForce(float32 inv_dt) const
{
return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis);
}
float32 b2PrismaticJoint::GetReactionTorque(float32 inv_dt) const
{
return inv_dt * m_impulse.y;
}
float32 b2PrismaticJoint::GetJointTranslation() const
{
b2Vec2 pA = m_bodyA->GetWorldPoint(m_localAnchorA);
b2Vec2 pB = m_bodyB->GetWorldPoint(m_localAnchorB);
b2Vec2 d = pB - pA;
b2Vec2 axis = m_bodyA->GetWorldVector(m_localXAxisA);
float32 translation = b2Dot(d, axis);
return translation;
}
float32 b2PrismaticJoint::GetJointSpeed() const
{
b2Body* bA = m_bodyA;
b2Body* bB = m_bodyB;
b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter);
b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter);
b2Vec2 p1 = bA->m_sweep.c + rA;
b2Vec2 p2 = bB->m_sweep.c + rB;
b2Vec2 d = p2 - p1;
b2Vec2 axis = b2Mul(bA->m_xf.q, m_localXAxisA);
b2Vec2 vA = bA->m_linearVelocity;
b2Vec2 vB = bB->m_linearVelocity;
float32 wA = bA->m_angularVelocity;
float32 wB = bB->m_angularVelocity;
float32 speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA));
return speed;
}
bool b2PrismaticJoint::IsLimitEnabled() const
{
return m_enableLimit;
}
void b2PrismaticJoint::EnableLimit(bool flag)
{
if (flag != m_enableLimit)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_enableLimit = flag;
m_impulse.z = 0.0f;
}
}
float32 b2PrismaticJoint::GetLowerLimit() const
{
return m_lowerTranslation;
}
float32 b2PrismaticJoint::GetUpperLimit() const
{
return m_upperTranslation;
}
void b2PrismaticJoint::SetLimits(float32 lower, float32 upper)
{
b2Assert(lower <= upper);
if (lower != m_lowerTranslation || upper != m_upperTranslation)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_lowerTranslation = lower;
m_upperTranslation = upper;
m_impulse.z = 0.0f;
}
}
bool b2PrismaticJoint::IsMotorEnabled() const
{
return m_enableMotor;
}
void b2PrismaticJoint::EnableMotor(bool flag)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_enableMotor = flag;
}
void b2PrismaticJoint::SetMotorSpeed(float32 speed)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_motorSpeed = speed;
}
void b2PrismaticJoint::SetMaxMotorForce(float32 force)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_maxMotorForce = force;
}
float32 b2PrismaticJoint::GetMotorForce(float32 inv_dt) const
{
return inv_dt * m_motorImpulse;
}
void b2PrismaticJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b2Log(" b2PrismaticJointDef jd;\n");
b2Log(" jd.bodyA = bodies[%d];\n", indexA);
b2Log(" jd.bodyB = bodies[%d];\n", indexB);
b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y);
b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y);
b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y);
b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle);
b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit);
b2Log(" jd.lowerTranslation = %.15lef;\n", m_lowerTranslation);
b2Log(" jd.upperTranslation = %.15lef;\n", m_upperTranslation);
b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor);
b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed);
b2Log(" jd.maxMotorForce = %.15lef;\n", m_maxMotorForce);
b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
| 0 | 0.96802 | 1 | 0.96802 | game-dev | MEDIA | 0.842651 | game-dev | 0.977686 | 1 | 0.977686 |
Liweimin0512/godot_gameplay_ability_system | 4,774 | source/ability_action/effects/base_damage_effect.gd | extends EffectAction
class_name BaseDamageEffect
## 基础暴击倍数
const BASE_CRIT_MULTIPLIER : float = 1.5
@export var attribute_component_name : StringName = "ability_attribute_component"
@export var ability_resource_component_name : StringName = "ability_resource_component"
@export var apply_damage_resource : StringName = "health" ## 伤害资源
@export var damage_type : StringName = "physical" ## 伤害类型
@export var is_indirect : bool = false ## 是否为间接伤害
@export var base_damage_attribute : StringName = "attack" ## 基础伤害属性
@export var defense_attribute : StringName = "defense" ## 防御力属性
@export var hit_rate_attribute : StringName = "hit_rate" ## 命中率属性
@export var dodge_rate_attribute : StringName = "dodge_rate" ## 闪避率属性
@export var min_hit_rate : float = 0.0 ## 最小命中率
@export var crit_rate_attribute : StringName = "crit_rate" ## 暴击率属性
@export var crit_multiplier : float = BASE_CRIT_MULTIPLIER ## 暴击倍数
var _is_critical : bool = false
var _is_hit : bool = false
func _perform_action(context: AbilityEffectContext) -> STATUS:
var caster : Node = context.caster
var targets : Array[Node] = context.get_all_targets()
if not _validate_entities(caster, targets):
return STATUS.FAILURE
for target in targets:
_is_hit = _roll_hit(caster, target, context)
_calculate_damage(caster, target, context)
# 发送伤害计算前事件
AbilitySystem.push_ability_event("damage_calculating", context.duplicate())
_apply_damage(target, context)
AbilitySystem.push_ability_event("damage_completed", context.duplicate())
return STATUS.SUCCESS
## 伤害计算
func _calculate_damage(attacker: Node, defender: Node, context: AbilityEffectContext) -> void:
if _is_hit == false:
context.damage_data.damage = 0
return
var base_damage = _get_base_damage(attacker, context)
var defense = _get_defense(defender)
var critical_multiplier = _get_crit_multiplier(attacker, context)
# 基础伤害计算
var final_damage = max(base_damage - defense, base_damage * 0.1 ) * critical_multiplier
context.damage_data.damage = final_damage
context.damage_data.damage_type = damage_type
context.damage_data.caster = context.caster
context.damage_data.target = context.target
context.damage_data.ability = context.ability
return
## 应用伤害
func _apply_damage(defender: Node, context: AbilityEffectContext) -> void:
var damage = context.damage_data.damage
var ability_resource_component: AbilityResourceComponent = defender.ability_resource_component
var health_resource : AbilityResource = ability_resource_component.get_resource("health")
if not health_resource:
GASLogger.error("can not found health resource")
return
health_resource.consume(damage)
## 获取基础伤害
func _get_base_damage(attacker: Node, context: AbilityEffectContext) -> float:
# 基类提供基础实现,子类可以重写
return _get_attribute_value(attacker, base_damage_attribute) * _get_damage_multiplier(context)
## 获取防御力
func _get_defense(defender: Node) -> float:
return _get_attribute_value(defender, defense_attribute)
## 获取技能伤害倍数
func _get_damage_multiplier(context: AbilityEffectContext) -> float:
var multiplier = context.damage_data.damage_multiplier
return multiplier
## 获取暴击伤害倍数
func _get_crit_multiplier(attacker: Node, context: AbilityEffectContext) -> float:
var multiplier = 1.0
# 检查暴击
_is_critical = _roll_critical(attacker, context)
if _is_critical:
multiplier *= crit_multiplier
return multiplier
## 判定是否命中
func _roll_hit(attacker: Node, defender: Node, context: AbilityEffectContext) -> bool:
var force_hit = context.damage_data.force_hit
var dodge_rate = _get_attribute_value(defender, dodge_rate_attribute)
var hit_rate = max(min_hit_rate, _get_attribute_value(attacker, hit_rate_attribute) - dodge_rate)
return randf() < hit_rate
## 判定是否暴击
func _roll_critical(attacker: Node, context: AbilityEffectContext) -> bool:
var force_critical = context.damage_data.force_critical
if force_critical:
# 强制暴击
return true
var crit_chance = _get_attribute_value(attacker, crit_rate_attribute)
return randf() < crit_chance
## 获取属性值
func _get_attribute_value(node: Node, attribute: StringName) -> float:
var ability_attribute_component : AbilityAttributeComponent = node.get(attribute_component_name)
if not ability_attribute_component:
GASLogger.error("找不到属性组件, 无法获取属性值!")
return 0.0
return ability_attribute_component.get_attribute_value(attribute)
## 检查实体有效性
func _validate_entities(attacker: Node, targets: Array[Node]) -> bool:
if not attacker or targets.is_empty():
GASLogger.error("DealDamageEffectNode attacker or targets is empty!")
return false
return true
| 0 | 0.804137 | 1 | 0.804137 | game-dev | MEDIA | 0.967335 | game-dev | 0.753019 | 1 | 0.753019 |
lukasmonk/lucaschess | 4,605 | Engines/Windows/glaurung/src/move.cpp | /*
Glaurung, a UCI chess playing engine.
Copyright (C) 2004-2008 Tord Romstad
Glaurung 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.
Glaurung 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/>.
*/
////
//// Includes
////
#include <cassert>
#include "move.h"
#include "piece.h"
#include "position.h"
#include "ucioption.h"
////
//// Functions
////
/// move_from_string() takes a position and a string as input, and attempts to
/// convert the string to a move, using simple coordinate notation (g1f3,
/// a7a8q, etc.). In order to correctly parse en passant captures and castling
/// moves, we need the position. This function is not robust, and expects that
/// the input move is legal and correctly formatted.
Move move_from_string(const Position &pos, const std::string &str) {
Square from, to;
Piece piece;
Color us = pos.side_to_move();
if(str.length() < 4) return MOVE_NONE;
// Read the from and to squares:
from = square_from_string(str.substr(0, 2));
to = square_from_string(str.substr(2, 4));
// Find the moving piece:
piece = pos.piece_on(from);
// If the string has more than 4 characters, try to interpret the 5th
// character as a promotion:
if(type_of_piece(piece) == PAWN && str.length() >= 5) {
switch(str[4]) {
case 'n': case 'N':
return make_promotion_move(from, to, KNIGHT);
case 'b': case 'B':
return make_promotion_move(from, to, BISHOP);
case 'r': case 'R':
return make_promotion_move(from, to, ROOK);
case 'q': case 'Q':
return make_promotion_move(from, to, QUEEN);
}
}
if(piece == king_of_color(us)) {
// Is this a castling move? A king move is assumed to be a castling
// move if the destination square is occupied by a friendly rook, or
// if the distance between the source and destination squares is more
// than 1.
if(pos.piece_on(to) == rook_of_color(us))
return make_castle_move(from, to);
else if(square_distance(from, to) > 1) {
// This is a castling move, but we have to translate it to the
// internal "king captures rook" representation.
SquareDelta delta = (to > from)? DELTA_E : DELTA_W;
Square s;
for(s = from + delta;
pawn_rank(us, s) == RANK_1 && pos.piece_on(s) != rook_of_color(us);
s += delta);
if(pawn_rank(us, s) == RANK_1 && pos.piece_on(s) == rook_of_color(us))
return make_castle_move(from, s);
}
}
else if(piece == pawn_of_color(us)) {
// En passant move? We assume that a pawn move is an en passant move
// without further testing if the destination square is epSquare.
if(to == pos.ep_square())
return make_ep_move(from, to);
}
return make_move(from, to);
}
/// move_to_string() converts a move to a string in coordinate notation
/// (g1f3, a7a8q, etc.). The only special case is castling moves, where we
/// print in the e1g1 notation in normal chess mode, and in e1h1 notation in
/// Chess960 mode.
const std::string move_to_string(Move move) {
std::string str;
if(move == MOVE_NONE)
str = "(none)";
else if(move == MOVE_NULL)
str = "0000";
else {
if(!Chess960) {
if(move_from(move) == SQ_E1 && move_is_short_castle(move)) {
str = "e1g1"; return str;
}
else if(move_from(move) == SQ_E1 && move_is_long_castle(move)) {
str = "e1c1"; return str;
}
if(move_from(move) == SQ_E8 && move_is_short_castle(move)) {
str = "e8g8"; return str;
}
else if(move_from(move) == SQ_E8 && move_is_long_castle(move)) {
str = "e8c8"; return str;
}
}
str = square_to_string(move_from(move)) + square_to_string(move_to(move));
if(move_promotion(move))
str += piece_type_to_char(move_promotion(move), false);
}
return str;
}
/// Overload the << operator, to make it easier to print moves.
std::ostream &operator << (std::ostream &os, Move m) {
return os << move_to_string(m);
}
/// move_is_ok(), for debugging.
bool move_is_ok(Move m) {
return square_is_ok(move_from(m)) && square_is_ok(move_to(m));
}
| 0 | 0.852898 | 1 | 0.852898 | game-dev | MEDIA | 0.870262 | game-dev | 0.981398 | 1 | 0.981398 |
BLACKujira/SekaiTools | 3,317 | SekaiTools/Assets/Live2D/Cubism/Framework/ObjectExtensionMethods.cs | /**
* Copyright(c) Live2D Inc. All rights reserved.
*
* Use of this source code is governed by the Live2D Open Software license
* that can be found at https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html.
*/
using UnityEngine;
namespace Live2D.Cubism.Framework
{
/// <summary>
/// Extensions for <see cref="Object"/>s.
/// </summary>
internal static class ObjectExtensionMethods
{
/// <summary>
/// Extracts an interface from an <see cref="Object"/>.
/// </summary>
/// <typeparam name="T">Interface type to extract.</typeparam>
/// <param name="self"><see langword="this"/>.</param>
/// <returns>Valid reference on success; <see langword="null"/> otherwise.</returns>
public static T GetInterface<T>(this Object self) where T : class
{
var result = self as T;
if (result != null)
{
return result;
}
// Deal with GameObjects.
var gameObject = self as GameObject;
if (gameObject != null)
{
result = gameObject.GetComponent<T>();
}
// Warn on error.
if (self != null && result == null)
{
Debug.LogWarning(self + " doesn't expose requested interface of type \"" + typeof(T) + "\".");
}
return result;
}
/// <summary>
/// Nulls reference in case an <see cref="Object"/> doesn't expose an interface requested.
/// </summary>
/// <typeparam name="T">Type of interface to check for.</typeparam>
/// <param name="self"><see langword="this"/>.</param>
/// <returns><paramref name="self"/> if object exposes interface; <see langword="null"/> otherwise.</returns>
public static Object ToNullUnlessImplementsInterface<T>(this Object self) where T : class
{
var exposesInterface = self.ImplementsInterface<T>();
// Warn on error.
if (self != null && !exposesInterface)
{
Debug.LogWarning(self + " doesn't expose requested interface of type \"" + typeof(T) + "\".");
}
return (exposesInterface)
? self
: null;
}
/// <summary>
/// Checks whether a <see cref="Object"/> implements an interface.
/// </summary>
/// <typeparam name="T">Interface type to check against.</typeparam>
/// <param name="self"><see langword="this"/>.</param>
/// <returns><see langword="true"/> if interface is exposed; <see langword="false"/> otherwise.</returns>
public static bool ImplementsInterface<T>(this Object self)
{
// Return early in case argument matches type.
if (self is T)
{
return true;
}
// Search in components in case object is a GameObject.
var gameObject = self as GameObject;
if (gameObject != null)
{
var components = gameObject.GetComponents<T>();
return components.Length > 0;
}
// Return on fail.
return false;
}
}
}
| 0 | 0.840643 | 1 | 0.840643 | game-dev | MEDIA | 0.795141 | game-dev | 0.854708 | 1 | 0.854708 |
JiepengTan/LockstepEngine_ARPGDemo | 3,146 | Unity/Assets/LockstepEngine/BehaviourTree/Src/Composite/BTActionSequence.cs | using System;
using System.Collections.Generic;
namespace Lockstep.BehaviourTree {
[BuildInNode(typeof(BTActionSequence), EBTBuildInTypeIdx.BTActionSequence)]
public unsafe partial class BTActionSequence : BTComposite {
public override object[] GetRuntimeData(BTWorkingData wData){
return new object[] {
*(BTCActionSequence*) wData.GetContext(_uniqueKey),
};
}
protected override int MemSize => sizeof(BTCActionSequence);
public override Type DataType => typeof(BTCActionSequence);
//-------------------------------------------------------
private bool _continueIfErrorOccors;
//-------------------------------------------------------
public BTActionSequence(){
_continueIfErrorOccors = false;
}
public BTActionSequence SetContinueIfErrorOccors(bool v){
_continueIfErrorOccors = v;
return this;
}
//------------------------------------------------------
protected override bool OnEvaluate( /*in*/ BTWorkingData wData){
var thisContext = (BTCActionSequence*) wData.GetContext(_uniqueKey);
int checkedNodeIndex = -1;
if (IsIndexValid(thisContext->currentSelectedIndex)) {
checkedNodeIndex = thisContext->currentSelectedIndex;
}
else {
checkedNodeIndex = 0;
}
if (IsIndexValid(checkedNodeIndex)) {
BTAction node = GetChild<BTAction>(checkedNodeIndex);
if (node.Evaluate(wData)) {
thisContext->currentSelectedIndex = checkedNodeIndex;
return true;
}
}
return false;
}
protected override int OnUpdate(BTWorkingData wData){
var thisContext = (BTCActionSequence*) wData.GetContext(_uniqueKey);
int runningStatus = BTRunningStatus.FINISHED;
BTAction node = GetChild<BTAction>(thisContext->currentSelectedIndex);
runningStatus = node.Update(wData);
if (_continueIfErrorOccors == false && BTRunningStatus.IsError(runningStatus)) {
thisContext->currentSelectedIndex = -1;
return runningStatus;
}
if (BTRunningStatus.IsFinished(runningStatus)) {
thisContext->currentSelectedIndex++;
if (IsIndexValid(thisContext->currentSelectedIndex)) {
runningStatus = BTRunningStatus.EXECUTING;
}
else {
thisContext->currentSelectedIndex = -1;
}
}
return runningStatus;
}
protected override void OnTransition(BTWorkingData wData){
var thisContext = (BTCActionSequence*) wData.GetContext(_uniqueKey);
BTAction node = GetChild<BTAction>(thisContext->currentSelectedIndex);
if (node != null) {
node.Transition(wData);
}
thisContext->currentSelectedIndex = -1;
}
}
} | 0 | 0.891214 | 1 | 0.891214 | game-dev | MEDIA | 0.647244 | game-dev | 0.940644 | 1 | 0.940644 |
sideeffects/HoudiniEngineForUnreal-v2 | 12,046 | Source/HoudiniEngineRuntime/Private/HoudiniAssetBlueprintComponent.h | /*
* Copyright (c) <2021> Side Effects Software Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. The name of Side Effects Software may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "CoreMinimal.h"
#include "Delegates/IDelegateInstance.h"
#include "Engine/Blueprint.h"
#include "HoudiniAssetComponent.h"
#if WITH_EDITOR
#include "Subsystems/AssetEditorSubsystem.h"
#endif
#include "HoudiniAssetBlueprintComponent.generated.h"
class USCS_Node;
UCLASS(NotBlueprintType, Experimental, meta=(BlueprintSpawnableComponent, DisplayName="Houdini Asset"))
class HOUDINIENGINERUNTIME_API UHoudiniAssetBlueprintComponent : public UHoudiniAssetComponent
{
GENERATED_BODY()
public:
UHoudiniAssetBlueprintComponent(const FObjectInitializer & ObjectInitializer);
#if WITH_EDITOR
// Sync certain variables of this HoudiniAssetComponent to the blueprint generated class.
// This is typically used when the Blueprint definition is being edited and the HAC cook
// took place in a transient HoudiniAssetComponent. Certain properties needs to be copied
// from the transient component back to the Blueprint generated class in order to be retained
// as part of the Client MeetingBlueprint definition.
void CopyStateToTemplateComponent();
void CopyStateFromTemplateComponent(UHoudiniAssetBlueprintComponent* FromComponent, const bool bClearFromInputs, const bool bClearToInputs, const bool bCopyInputObjectComponentProperties);
void CopyDetailsFromComponent(
UHoudiniAssetBlueprintComponent* FromComponent,
const bool bCreateSCSNodes,
const bool bClearChangedToInputs,
const bool bClearChangedFromInputs,
const bool bInCanDeleteHoudiniNodes,
const bool bCopyInputObjectComponentProperties,
bool &bOutBlueprintStructureChanged,
EObjectFlags SetFlags=RF_NoFlags,
EObjectFlags ClearFlags=RF_NoFlags);
// Update references on ToInput by looking up component references on FromInput in the SCS graph, on locating the correct component for ToInput.
void UpdateInputObjectComponentReferences(
USimpleConstructionScript* SCS,
UHoudiniInput* FromInput,
UHoudiniInput* ToInput,
const bool bCopyInputObjectProperties,
const bool bCreateMissingSCSNodes=false,
USCS_Node* ParentSCSNode=nullptr,
bool* bOutSCSNodeCreated=nullptr);
virtual bool HasOpenEditor() const override;
IAssetEditorInstance* FindEditorInstance() const;
AActor* GetPreviewActor() const;
#endif
virtual UHoudiniAssetComponent* GetCachedTemplate() const override;
//------------------------------------------------------------------------------------------------
// Supported Features
//------------------------------------------------------------------------------------------------
// Some features may be unavaible depending on the context in which the Houdini Asset Component
// has been instantiated.
virtual bool CanDeleteHoudiniNodes() const override;
void SetCanDeleteHoudiniNodes(bool bInCanDeleteNodes);
virtual bool IsValidComponent() const override;
virtual bool IsInputTypeSupported(EHoudiniInputType InType) const override;
virtual bool IsOutputTypeSupported(EHoudiniOutputType InType) const override;
virtual bool IsProxyStaticMeshEnabled() const override;
//------------------------------------------------------------------------------------------------
// Notifications
//------------------------------------------------------------------------------------------------
//virtual void BroadcastPreAssetCook() override;
virtual void OnPrePreCook() override;
virtual void OnPostPreCook() override;
virtual void OnPreOutputProcessing() override;
virtual void OnPostOutputProcessing() override;
virtual void OnPrePreInstantiation() override;
virtual void NotifyHoudiniRegisterCompleted() override;
virtual void NotifyHoudiniPreUnregister() override;
virtual void NotifyHoudiniPostUnregister() override;
//------------------------------------------------------------------------------------------------
// UActorComponent overrides
//------------------------------------------------------------------------------------------------
#if WITH_EDITOR
virtual void OnComponentCreated() override;
#endif
virtual void OnRegister() override;
virtual void BeginDestroy() override;
virtual void DestroyComponent(bool bPromoteChildren = false) override;
virtual void OnComponentDestroyed(bool bDestroyingHierarchy) override;
// Refer USplineComponent for a decent reference on how to use component instance data.
virtual TStructOnScope<FActorComponentInstanceData> GetComponentInstanceData() const override;
void ApplyComponentInstanceData(struct FHoudiniAssetBlueprintInstanceData* ComponentInstanceData, const bool bPostUCS);
//------------------------------------------------------------------------------------------------
// UHoudiniAssetComponent overrides
//------------------------------------------------------------------------------------------------
FHoudiniAssetComponentEvent OnParametersChangedEvent;
FHoudiniAssetComponentEvent OnHoudiniAssetChangedEvent;
virtual void HoudiniEngineTick() override;
virtual void OnFullyLoaded() override;
virtual void OnTemplateParametersChanged() override;
virtual void OnHoudiniAssetChanged() override;
virtual void RegisterHoudiniComponent(UHoudiniAssetComponent* InComponent) override;
virtual void OnBlueprintStructureModified() override;
virtual void OnBlueprintModified() override;
//------------------------------------------------------------------------------------------------
// Blueprint functions
//------------------------------------------------------------------------------------------------
UFUNCTION(BlueprintCallable, Category="Houdini Asset Component")
bool HasParameter(FString Name);
UFUNCTION(BlueprintCallable, Category="Houdini Asset Component")
void SetFloatParameter(FString Name, float Value, int Index=0);
UFUNCTION(BlueprintCallable, Category="Houdini Asset Component")
void SetToggleValueAt(FString Name, bool Value, int Index=0);
void AddInputObjectMapping(const FGuid& InputGuid, const FGuid& SCSVariableGuid) { CachedInputNodes.Add(InputGuid, SCSVariableGuid); }
bool GetInputObjectSCSVariableGuid(const FGuid& InputGuid, FGuid& OutSCSGuid);
void RemoveInputObjectSCSVariableGuid(const FGuid& InputGuid) { CachedInputNodes.Remove(InputGuid); };
USCS_Node* FindSCSNodeForTemplateComponent(USimpleConstructionScript* SCS, const UActorComponent* InComponent) const;
USCS_Node* FindSCSNodeForTemplateComponentInClassHierarchy(const UActorComponent* InComponent) const;
#if WITH_EDITOR
USCS_Node* FindSCSNodeForInstanceComponent(USimpleConstructionScript* SCS, const UActorComponent* InComponent) const;
#endif // WITH_EDITOR
UActorComponent* FindComponentInstanceInActor(const AActor* InActor, USCS_Node* SCSNode) const;
protected:
template<typename ParamT, typename ValueT>
void SetTypedValueAt(const FString& Name, ValueT& Value, int Index=0);
void OnTemplateParametersChangedHandler(UHoudiniAssetComponent* ComponentTemplate);
void InvalidateData();
USceneComponent* FindOwnerComponentByName(FName ComponentName) const;
USceneComponent* FindActorComponentByName(AActor * InActor, FName ComponentName) const;
void CachePreviewState();
void CacheBlueprintData();
USimpleConstructionScript* GetSCS() const;
//// The output translation has finished.
//void OnOutputProcessingCompletedHandler(UHoudiniAssetComponent * InComponent);
#if WITH_EDITOR
//void ReceivedAssetEditorRequestCloseEvent(UObject* Asset, EAssetEditorCloseReason CloseReason);
TWeakObjectPtr<UAssetEditorSubsystem> CachedAssetEditorSubsystem;
#endif
TWeakObjectPtr<UBlueprint> CachedBlueprint;
TWeakObjectPtr<AActor> CachedActorCDO;
TWeakObjectPtr<UHoudiniAssetBlueprintComponent> CachedTemplateComponent;
/*UPROPERTY(DuplicateTransient)
bool bOutputsRequireUpdate;*/
UPROPERTY()
bool FauxBPProperty;
UPROPERTY()
bool bHoudiniAssetChanged;
UPROPERTY(Transient, DuplicateTransient)
bool bUpdatedFromTemplate;
UPROPERTY()
bool bIsInBlueprintEditor;
UPROPERTY(Transient, DuplicateTransient)
bool bCanDeleteHoudiniNodes;
UPROPERTY(Transient, DuplicateTransient)
bool bHasRegisteredComponentTemplate;
FDelegateHandle TemplatePropertiesChangedHandle;
// This is used to keep track of which SCS variable names correspond to which
// output objects.
// This seems like it will cause issues in the map.
UPROPERTY()
TMap<FHoudiniOutputObjectIdentifier, FGuid> CachedOutputNodes;
// This is used to keep track of which (SCS) variable guids correspond to which
// input objects.
UPROPERTY()
TMap<FGuid, FGuid> CachedInputNodes;
};
///** Used to keep track of output data and mappings during reconstruction */
USTRUCT()
struct FHoudiniAssetBlueprintOutput
{
GENERATED_BODY()
UPROPERTY()
int32 OutputIndex;
UPROPERTY()
FHoudiniOutputObject OutputObject;
FHoudiniAssetBlueprintOutput()
: OutputIndex(INDEX_NONE)
{
}
};
/** Used to store HoudiniAssetComponent data during BP reconstruction */
USTRUCT()
struct FHoudiniAssetBlueprintInstanceData : public FActorComponentInstanceData
{
GENERATED_BODY()
public:
FHoudiniAssetBlueprintInstanceData();
FHoudiniAssetBlueprintInstanceData(const UHoudiniAssetBlueprintComponent* SourceComponent);
virtual ~FHoudiniAssetBlueprintInstanceData() = default;
/*virtual bool ContainsData() const override
{
return (HAC != nullptr) || Super::ContainsData();
}*/
virtual void ApplyToComponent(UActorComponent* Component, const ECacheApplyPhase CacheApplyPhase) override
{
Super::ApplyToComponent(Component, CacheApplyPhase);
CastChecked<UHoudiniAssetBlueprintComponent>(Component)->ApplyComponentInstanceData(this, (CacheApplyPhase == ECacheApplyPhase::PostUserConstructionScript));
}
virtual void AddReferencedObjects(FReferenceCollector& Collector) override;
// Persist all the required properties for being able to recook the HoudiniAsset from its existing state.
UPROPERTY()
UHoudiniAsset* HoudiniAsset;
UPROPERTY()
int32 AssetId;
UPROPERTY()
EHoudiniAssetState AssetState;
// Subasset index
UPROPERTY()
uint32 SubAssetIndex;
UPROPERTY()
uint32 AssetCookCount;
UPROPERTY()
bool bHasBeenLoaded;
UPROPERTY()
bool bHasBeenDuplicated;
UPROPERTY()
bool bPendingDelete;
UPROPERTY()
bool bRecookRequested;
UPROPERTY()
bool bRebuildRequested;
UPROPERTY()
bool bEnableCooking;
UPROPERTY()
bool bForceNeedUpdate;
UPROPERTY()
bool bLastCookSuccess;
/*UPROPERTY(DuplicateTransient)
TSet<UHoudiniAssetComponent*> DownstreamHoudiniAssets;*/
UPROPERTY()
FGuid ComponentGUID;
UPROPERTY()
FGuid HapiGUID;
UPROPERTY()
bool bRegisteredComponentTemplate;
// Name of the component from which this
// data was copied. Used for debugging purposes.
UPROPERTY()
FString SourceName;
UPROPERTY()
TMap<FHoudiniOutputObjectIdentifier, FHoudiniAssetBlueprintOutput> Outputs;
UPROPERTY()
TArray<UHoudiniInput*> Inputs;
};
| 0 | 0.977449 | 1 | 0.977449 | game-dev | MEDIA | 0.660928 | game-dev | 0.763794 | 1 | 0.763794 |
shiptest-ss13/Shiptest | 1,216 | code/modules/mapping/preloader.dm | // global datum that will preload variables on atoms instanciation
GLOBAL_VAR_INIT(use_preloader, FALSE)
GLOBAL_LIST_INIT(_preloader_attributes, null)
GLOBAL_LIST_INIT(_preloader_path, null)
/// Preloader datum
/datum/map_preloader
parent_type = /datum
var/list/attributes
var/target_path
/world/proc/preloader_setup(list/the_attributes, path)
if(the_attributes.len)
GLOB.use_preloader = TRUE
GLOB._preloader_attributes = the_attributes
GLOB._preloader_path = path
/world/proc/preloader_load(atom/what)
GLOB.use_preloader = FALSE
var/list/attributes = GLOB._preloader_attributes
for(var/attribute in attributes)
var/value = attributes[attribute]
if(islist(value))
value = deepCopyList(value)
#ifdef TESTING
if(what.vars[attribute] == value)
var/message = "<font color=green>[what.type]</font> at [AREACOORD(what)] - <b>VAR:</b> <font color=red>[attribute] = [isnull(value) ? "null" : (isnum(value) ? value : "\"[value]\"")]</font>"
log_mapping("DIRTY VAR: [message]")
GLOB.dirty_vars += message
#endif
what.vars[attribute] = value
/area/template_noop
name = "Area Passthrough"
/turf/template_noop
name = "Turf Passthrough"
icon_state = "noop"
bullet_bounce_sound = null
| 0 | 0.925685 | 1 | 0.925685 | game-dev | MEDIA | 0.659324 | game-dev | 0.775284 | 1 | 0.775284 |
chris81605/DOL-BJXExtende_for_ML_Project | 1,694 | DATA/原版 0.4.5.3/DoLModExportData_20240117_021134/passage/Street Bully Stalk Finish.twee | :: Street Bully Stalk Finish []
<<set $outside to 1>><<effects>>
<<if $stalk_end is "confront">>
<<if $feetaction is "confront">>
惠特尼瞪着你,双臂交叉。
<<else>>
<<if !$stalk_assess>>一双手<<else>>惠特尼<</if>>从你身后抓住了你。
<</if>>
<<if $whitneyromance is 1>>
“你到这儿来就是想找麻烦,是不是?”<<if !$stalk_assess>>是惠特尼。<</if>><<His>>的朋友们从<<his>>肩后窥视。<<He>>笑了。“那正好,你走运了。”
<<else>>
“擅闯要罚款的,荡妇。”<<if !$stalk_assess>>是惠特尼。<</if>><<His>>的朋友们将你团团围住。“你很走运,这次算你便宜。”
<</if>>
<br><br>
<<silently>><<endcombat>><</silently>>
<<npc Whitney>><<person1>>
<<if $NPCName[$NPCNameList.indexOf("Whitney")].dom gte 15>>
<<He>>打了个响指,然后指了指<<his>>下面。
<<else>>
<<He>>把一只手放在你的头上,往下推去。
<</if>>
<<if Time.dayState isnot "night">>
<span class="lewd">你可以清楚地看到相邻的街道。</span>
<</if>>
<br><br>
<<if $promiscuity gte 55>>
<<link [[帮惠特尼口交|Street Bully Sex]]>><<set $phase to 0>><<set $sexstart to 1>><<npcincr Whitney love 1>><<npcincr Whitney dom 1>><</link>><<promiscuous4>><<glove>><<gdom>>
<br>
<</if>>
<<if $whitneyromance is 1>>
<<link [[要求去一个隐蔽的地方|Street Bully Private]]>><<npcincr Whitney dom -1>><</link>><<promiscuous1>><<ldom>>
<br>
<</if>>
<<link [[顺其自然|Street Bully Sex]]>><<set $phase to 0>><<set $molestationstart to 1>><<trauma 6>><<stress 6>><<npcincr Whitney dom 1>><</link>><<gtrauma>><<gstress>><<gdom>>
<br>
<<link [[战斗|Street Bully Fight]]>><<npcincr Whitney dom -1>><<set $fightstart to 1>><</link>>
<br>
<<elseif $stalk_end is "hide">>
你从藏身之处出来。<<if $stalk_assess>>惠特尼<<else>>跟踪你的人<</if>>无处可寻。<<tearful>>你继续你的路。
<br><br>
<<clotheson>>
<<endcombat>>
<<destinationeventend>>
<<else>>
你放慢脚步,<<tearful>>随后你继续前进。
<br><br>
<<clotheson>>
<<endcombat>>
<<destinationeventend>>
<</if>> | 0 | 0.905633 | 1 | 0.905633 | game-dev | MEDIA | 0.822187 | game-dev | 0.638572 | 1 | 0.638572 |
AdaCompNUS/summit | 11,305 | PythonAPI/docs/commands.yml | ---
- module_name: command
doc: >
classes:
- class_name: Response
# - DESCRIPTION ------------------------
doc: >
States the result of executing a command as either the ID of the actor to whom the command was applied to (when succeeded) or an error string (when failed).
actor ID, depending on whether or not the command succeeded. The method **<font color="#7fb800">apply_batch_sync()</font>** in carla.Client returns a list of these to summarize the execution of a batch.
# - PROPERTIES -------------------------
instance_variables:
- var_name: actor_id
type: int
doc: >
Actor to whom the command was applied to. States that the command was successful.
- var_name: error
type: str
doc: >
A string stating the command has failed.
# - METHODS ----------------------------
methods:
- def_name: has_error
return: bool
params:
doc: >
Returns <b>True</b> if the command represents a successful execution and <b>False</b> if not.
# --------------------------------------
- class_name: SpawnActor
# - DESCRIPTION ------------------------
doc: >
Command adaptation of **<font color="#7fb800">spawn_actor()</font>** in carla.World. Spawns an actor into the world based on the blueprint provided and the transform. If a parent is provided, the actor is attached to it.
# - PROPERTIES -------------------------
instance_variables:
- var_name: transform
type: carla.Transform
doc: >
Transform to be applied.
- var_name: parent_id
type: int
doc: >
Identificator of the parent actor.
# - METHODS ----------------------------
methods:
- def_name: __init__
# --------------------------------------
- def_name: __init__
params:
- param_name: blueprint
type: carla.ActorBlueprint
- param_name: transform
type: carla.Transform
# --------------------------------------
- def_name: __init__
params:
- param_name: blueprint
type: carla.ActorBlueprint
- param_name: transform
type: carla.Transform
- param_name: parent
type: carla.Actor or int
# --------------------------------------
- def_name: then
params:
- param_name: command
type: carla.Command
doc: >
CommandType.
doc: >
Links another command to be executed right after. It allows to ease very common flows such as spawning a set of vehicles by command and then using this method to set them to autopilot automatically.
# --------------------------------------
- class_name: DestroyActor
# - DESCRIPTION ------------------------
doc: >
Command adaptation of **<font color="#7fb800">destroy()</font>** in carla.Actor that tells the simulator to destroy this actor. It has no effect if the actor was already destroyed. When executed with **<font color="#7fb800">apply_batch_synch()</font>** in carla.Client there will be a <b>command.Response</b> that will return a boolean stating whether the actor was successfully destroyed.
# - PROPERTIES -------------------------
instance_variables:
- var_name: actor_id
type: int
doc: >
Actor affected by the command
# - METHODS ----------------------------
methods:
- def_name: __init__
params:
- param_name: actor
type: carla.Actor or int
doc: >
Actor or its ID to whom the command will be applied to.
# --------------------------------------
- class_name: ApplyVehicleControl
# - DESCRIPTION ------------------------
doc: >
Command adaptation of **<font color="#7fb800">apply_control()</font>** in carla.Vehicle. Applies a certain control to a vehicle.
# - PROPERTIES -------------------------
instance_variables:
- var_name: actor_id
type: int
doc: >
Vehicle actor affected by the command.
- var_name: control
type: carla.VehicleControl
doc: >
Vehicle control to be applied.
# - METHODS ----------------------------
methods:
- def_name: __init__
params:
- param_name: actor
type: carla.Actor or int
doc: >
Actor or its ID to whom the command will be applied to.
- param_name: control
type: carla.VehicleControl
# --------------------------------------
- class_name: ApplyWalkerControl
# - DESCRIPTION ------------------------
doc: >
Command adaptation of **<font color="#7fb800">apply_control()</font>** in carla.Walker. Applies a control to a walker.
# - PROPERTIES -------------------------
instance_variables:
- var_name: actor_id
type: int
doc: >
Walker actor affected by the command.
- var_name: control
type: carla.WalkerControl
doc: >
Walker control to be applied.
# - METHODS ----------------------------
methods:
- def_name: __init__
params:
- param_name: actor
type: carla.Actor or int
doc: >
Actor or its ID to whom the command will be applied to.
- param_name: control
type: carla.WalkerControl
# --------------------------------------
- class_name: ApplyTransform
# - DESCRIPTION ------------------------
doc: >
Command adaptation of **<font color="#7fb800">set_transform()</font>** in carla.Actor. Sets a new transform to an actor.
# - PROPERTIES -------------------------
instance_variables:
- var_name: actor_id
type: int
doc: >
Actor affected by the command.
- var_name: transform
type: carla.Transform
doc: >
Transformation to be applied.
# - METHODS ----------------------------
methods:
- def_name: __init__
params:
- param_name: actor
type: carla.Actor or int
doc: >
Actor or its ID to whom the command will be applied to.
- param_name: transform
type: carla.Transform
# --------------------------------------
- class_name: ApplyWalkerState
# - DESCRIPTION ------------------------
doc: >
Apply a state to the walker actor. Specially useful to initialize an actor them with a specific location, orientation and speed.
# - PROPERTIES -------------------------
instance_variables:
- var_name: actor_id
type: int
doc: >
Walker actor affected by the command.
- var_name: transform
type: carla.Transform
doc: >
Transform to be applied.
- var_name: speed
type: float
doc: >
Speed to be applied.
# - METHODS ----------------------------
methods:
- def_name: __init__
params:
- param_name: actor
type: carla.Actor or int
doc: >
Actor or its ID to whom the command will be applied to.
- param_name: transform
type: carla.Transform
- param_name: speed
type: float
# --------------------------------------
- class_name: ApplyVelocity
# - DESCRIPTION ------------------------
doc: >
Command adaptation of **<font color="#7fb800">set_velocity()</font>** in carla.Actor. Sets an actor's velocity.
# - PROPERTIES -------------------------
instance_variables:
- var_name: actor_id
type: int
doc: >
Actor affected by the command.
- var_name: velocity
type: carla.Vector3D
doc: >
The 3D velocity applied to the actor.
# - METHODS ----------------------------
methods:
- def_name: __init__
params:
- param_name: actor
type: carla.Actor or int
doc: >
Actor or its ID to whom the command will be applied to.
- param_name: velocity
type: carla.Vector3D
# --------------------------------------
- class_name: ApplyAngularVelocity
# - DESCRIPTION ------------------------
doc: >
Command adaptation of **<font color="#7fb800">set_angular_velocity()</font>** in carla.Actor. Sets an actor's angular velocity.
# - PROPERTIES -------------------------
instance_variables:
- var_name: actor_id
type: int
doc: >
Actor affected by the command.
- var_name: angular_velocity
type: carla.Vector3D
doc: >
The 3D angular velocity that will be applied to the actor.
# - METHODS ----------------------------
methods:
- def_name: __init__
params:
- param_name: actor
type: carla.Actor or int
doc: >
Actor or its ID to whom the command will be applied to.
- param_name: angular_velocity
type: carla.Vector3D
# --------------------------------------
- class_name: ApplyImpulse
# - DESCRIPTION ------------------------
doc: >
Command adaptation of **<font color="#7fb800">add_impulse()</font>** in carla.Actor. Adds impulse to an actor.
# - PROPERTIES -------------------------
instance_variables:
- var_name: actor_id
type: int
doc: >
Actor affected by the command.
- var_name: impulse
type: carla.Vector3D
doc: >
Impulse applied to the actor.
# - METHODS ----------------------------
methods:
- def_name: __init__
params:
- param_name: actor
type: carla.Actor or int
doc: >
Actor or its ID to whom the command will be applied to.
- param_name: impulse
type: carla.Vector3D
# --------------------------------------
- class_name: SetSimulatePhysics
# - DESCRIPTION ------------------------
doc: >
Command adaptation of **<font color="#7fb800">set_simulate_physics()</font>** in carla.Actor. Determines whether an actor will be affected by physics or not.
# - PROPERTIES -------------------------
instance_variables:
- var_name: actor_id
type: int
doc: >
Actor affected by the command.
- var_name: enabled
type: bool
doc: >
If physics should be activated or not.
# - METHODS ----------------------------
methods:
- def_name: __init__
params:
- param_name: actor
type: carla.Actor or int
doc: >
Actor or its ID to whom the command will be applied to.
- param_name: enabled
type: bool
# --------------------------------------
- class_name: SetAutopilot
# - DESCRIPTION ------------------------
doc: >
Command adaptation of **<font color="#7fb800">set_autopilot()</font>** in carla.Vehicle. Turns on/off the vehicle's server-side autopilot.
# - PROPERTIES -------------------------
instance_variables:
- var_name: actor_id
type: int
doc: >
Actor that is affected by the command.
- var_name: enabled
type: bool
doc: >
If autopilot should be activated or not.
# - METHODS ----------------------------
methods:
- def_name: __init__
params:
- param_name: actor
type: carla.Actor or int
doc: >
Actor or its ID to whom the command will be applied to.
- param_name: enabled
type: bool
# --------------------------------------
...
| 0 | 0.749362 | 1 | 0.749362 | game-dev | MEDIA | 0.602552 | game-dev | 0.538991 | 1 | 0.538991 |
LingASDJ/Magic_Ling_Pixel_Dungeon | 6,504 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/rooms/special/NxhyShopRoomList.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2021 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.levels.rooms.special;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.Mob;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs.Nxhy;
import com.shatteredpixel.shatteredpixeldungeon.items.Generator;
import com.shatteredpixel.shatteredpixeldungeon.items.Heap;
import com.shatteredpixel.shatteredpixeldungeon.items.Item;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfLevitation;
import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.MeleeWeapon;
import com.shatteredpixel.shatteredpixeldungeon.levels.Level;
import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain;
import com.shatteredpixel.shatteredpixeldungeon.levels.painters.Painter;
import com.watabou.utils.Point;
import java.util.ArrayList;
public class NxhyShopRoomList extends SpecialRoom {
private ArrayList<Item> itemsToSpawn;
@Override
public int minWidth() {
return Math.max(10, (int)(Math.sqrt(itemCount())+6));
}
@Override
public int minHeight() {
return Math.max(10, (int)(Math.sqrt(itemCount())+6));
}
public int itemCount(){
if (itemsToSpawn == null) itemsToSpawn = generateItems();
return itemsToSpawn.size();
}
public void paint( Level level ) {
Painter.fill( level, this, Terrain.WALL );
Painter.fill( level, this, 1, Terrain.EMPTY_SP );
placeShopkeeper( level );
placeItems( level );
for (Door door : connected.values()) {
door.set( Door.Type.REGULAR );
}
}
protected void placeShopkeeper( Level level ) {
int pos = level.pointToCell(center());
Mob Nxhy = new Nxhy();
Nxhy.pos = pos;
level.mobs.add( Nxhy );
}
protected void placeItems( Level level ){
if (itemsToSpawn == null){
itemsToSpawn = generateItems();
}
Point itemPlacement = new Point(entrance());
if (itemPlacement.y == top){
itemPlacement.y++;
} else if (itemPlacement.y == bottom) {
itemPlacement.y--;
} else if (itemPlacement.x == left){
itemPlacement.x++;
} else {
itemPlacement.x--;
}
for (Item item : itemsToSpawn) {
if (itemPlacement.x == left+1 && itemPlacement.y != top+1){
itemPlacement.y--;
} else if (itemPlacement.y == top+1 && itemPlacement.x != right-1){
itemPlacement.x++;
} else if (itemPlacement.x == right-1 && itemPlacement.y != bottom-1){
itemPlacement.y++;
} else {
itemPlacement.x--;
}
int cell = level.pointToCell(itemPlacement);
if (level.heaps.get( cell ) != null) {
do {
cell = level.pointToCell(random());
} while (level.heaps.get( cell ) != null || level.findMob( cell ) != null);
}
level.drop( item, cell ).type = Heap.Type.FOR_SALE;
}
}
protected static ArrayList<Item> generateItems() {
ArrayList<Item> itemsToSpawn = new ArrayList<>();
MeleeWeapon w;
switch (Dungeon.depth) {
default:
w = (MeleeWeapon) Generator.random(Generator.wepTiers[1]);
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
itemsToSpawn.add( Generator.randomUsingDefaults( Generator.Category.STONE ) );
break;
}
w.enchant(null);
w.cursed = false;
w.level(0);
w.identify();
itemsToSpawn.add(w);
itemsToSpawn.add( new PotionOfLevitation() );
itemsToSpawn.add( new PotionOfLevitation() );
itemsToSpawn.add( new PotionOfLevitation() );
itemsToSpawn.add( new PotionOfLevitation() );
itemsToSpawn.add( new PotionOfLevitation() );
itemsToSpawn.add( new PotionOfLevitation() );
itemsToSpawn.add( new PotionOfLevitation() );
itemsToSpawn.add( new PotionOfLevitation() );
itemsToSpawn.add( new PotionOfLevitation() );
itemsToSpawn.add( new PotionOfLevitation() );
itemsToSpawn.add( new PotionOfLevitation() );
return itemsToSpawn;
}
}
| 0 | 0.722653 | 1 | 0.722653 | game-dev | MEDIA | 0.997424 | game-dev | 0.952557 | 1 | 0.952557 |
pablushaa/AllahClientRecode | 4,268 | net/minecraft/world/gen/structure/MapGenEndCity.java | package net.minecraft.world.gen.structure;
import java.util.Random;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.ChunkPrimer;
import net.minecraft.world.gen.ChunkGeneratorEnd;
public class MapGenEndCity extends MapGenStructure
{
private final int citySpacing = 20;
private final int minCitySeparation = 11;
private final ChunkGeneratorEnd endProvider;
public MapGenEndCity(ChunkGeneratorEnd p_i46665_1_)
{
this.endProvider = p_i46665_1_;
}
public String getStructureName()
{
return "EndCity";
}
protected boolean canSpawnStructureAtCoords(int chunkX, int chunkZ)
{
int i = chunkX;
int j = chunkZ;
if (chunkX < 0)
{
chunkX -= 19;
}
if (chunkZ < 0)
{
chunkZ -= 19;
}
int k = chunkX / 20;
int l = chunkZ / 20;
Random random = this.worldObj.setRandomSeed(k, l, 10387313);
k = k * 20;
l = l * 20;
k = k + (random.nextInt(9) + random.nextInt(9)) / 2;
l = l + (random.nextInt(9) + random.nextInt(9)) / 2;
if (i == k && j == l && this.endProvider.isIslandChunk(i, j))
{
int i1 = func_191070_b(i, j, this.endProvider);
return i1 >= 60;
}
else
{
return false;
}
}
protected StructureStart getStructureStart(int chunkX, int chunkZ)
{
return new MapGenEndCity.Start(this.worldObj, this.endProvider, this.rand, chunkX, chunkZ);
}
public BlockPos getClosestStrongholdPos(World worldIn, BlockPos pos, boolean p_180706_3_)
{
this.worldObj = worldIn;
return func_191069_a(worldIn, this, pos, 20, 11, 10387313, true, 100, p_180706_3_);
}
private static int func_191070_b(int p_191070_0_, int p_191070_1_, ChunkGeneratorEnd p_191070_2_)
{
Random random = new Random((long)(p_191070_0_ + p_191070_1_ * 10387313));
Rotation rotation = Rotation.values()[random.nextInt(Rotation.values().length)];
ChunkPrimer chunkprimer = new ChunkPrimer();
p_191070_2_.setBlocksInChunk(p_191070_0_, p_191070_1_, chunkprimer);
int i = 5;
int j = 5;
if (rotation == Rotation.CLOCKWISE_90)
{
i = -5;
}
else if (rotation == Rotation.CLOCKWISE_180)
{
i = -5;
j = -5;
}
else if (rotation == Rotation.COUNTERCLOCKWISE_90)
{
j = -5;
}
int k = chunkprimer.findGroundBlockIdx(7, 7);
int l = chunkprimer.findGroundBlockIdx(7, 7 + j);
int i1 = chunkprimer.findGroundBlockIdx(7 + i, 7);
int j1 = chunkprimer.findGroundBlockIdx(7 + i, 7 + j);
int k1 = Math.min(Math.min(k, l), Math.min(i1, j1));
return k1;
}
public static class Start extends StructureStart
{
private boolean isSizeable;
public Start()
{
}
public Start(World worldIn, ChunkGeneratorEnd chunkProvider, Random random, int chunkX, int chunkZ)
{
super(chunkX, chunkZ);
this.create(worldIn, chunkProvider, random, chunkX, chunkZ);
}
private void create(World worldIn, ChunkGeneratorEnd chunkProvider, Random rnd, int chunkX, int chunkZ)
{
Random random = new Random((long)(chunkX + chunkZ * 10387313));
Rotation rotation = Rotation.values()[random.nextInt(Rotation.values().length)];
int i = MapGenEndCity.func_191070_b(chunkX, chunkZ, chunkProvider);
if (i < 60)
{
this.isSizeable = false;
}
else
{
BlockPos blockpos = new BlockPos(chunkX * 16 + 8, i, chunkZ * 16 + 8);
StructureEndCityPieces.func_191087_a(worldIn.getSaveHandler().getStructureTemplateManager(), blockpos, rotation, this.components, rnd);
this.updateBoundingBox();
this.isSizeable = true;
}
}
public boolean isSizeableStructure()
{
return this.isSizeable;
}
}
}
| 0 | 0.865329 | 1 | 0.865329 | game-dev | MEDIA | 0.937704 | game-dev | 0.937256 | 1 | 0.937256 |
prolog/shadow-of-the-wyrm | 2,635 | engine/creatures/source/SlownessStatusEffect.cpp | #include "Conversion.hpp"
#include "CreatureProperties.hpp"
#include "Game.hpp"
#include "SlownessCalculator.hpp"
#include "SlownessStatusEffect.hpp"
#include "StatusAilmentTextKeys.hpp"
#include "StatusEffectFactory.hpp"
#include "StatusTypes.hpp"
using namespace std;
SlownessStatusEffect::SlownessStatusEffect()
{
status_calc = std::make_shared<SlownessCalculator>();
}
void SlownessStatusEffect::notify_deities(CreaturePtr initiating, CreaturePtr /*affected_creature*/) const
{
if (initiating != nullptr)
{
Game& game = Game::instance();
MapPtr current_map = game.get_current_map();
game.get_deity_action_manager_ref().notify_action(initiating, current_map, CreatureActionKeys::ACTION_FREEZE, true);
}
}
bool SlownessStatusEffect::after_apply(CreaturePtr creature) const
{
bool effect_applied = true;
if (creature)
{
// If the creature is hasted, then remove the slow property we've
// just added, and remove the creature's haste.
if (creature->has_status(StatusIdentifiers::STATUS_ID_HASTE))
{
creature->remove_status(StatusIdentifiers::STATUS_ID_SLOWNESS);
// Undo the haste status, adding a message if necessary:
StatusEffectPtr haste = StatusEffectFactory::create_status_effect(initiating_creature, StatusIdentifiers::STATUS_ID_HASTE, source_id);
haste->undo_change(creature);
effect_applied = false;
}
}
return effect_applied;
}
Modifier SlownessStatusEffect::get_base_modifier(CreaturePtr creature, const int /*danger_level*/) const
{
Modifier m;
if (creature != nullptr)
{
int speed_penalty = (creature->get_speed().get_base() / 2 * -1);
m.set_speed_modifier(speed_penalty);
}
return m;
}
string SlownessStatusEffect::get_player_application_message() const
{
string message = StringTable::get(StatusAilmentTextKeys::STATUS_MESSAGE_PLAYER_SLOWED);
return message;
}
string SlownessStatusEffect::get_npc_application_message(CreaturePtr creature) const
{
string message = StatusAilmentTextKeys::get_npc_slowed_message(creature);
return message;
}
string SlownessStatusEffect::get_player_undo_message() const
{
string message = StringTable::get(StatusAilmentTextKeys::STATUS_MESSAGE_PLAYER_SLOWNESS_CURED);
return message;
}
string SlownessStatusEffect::get_npc_undo_message(CreaturePtr creature) const
{
string message = StatusAilmentTextKeys::get_npc_undo_slowness_message(creature);
return message;
}
string SlownessStatusEffect::get_status_identifier() const
{
return StatusIdentifiers::STATUS_ID_SLOWNESS;
}
#ifdef UNIT_TESTS
#include "unit_tests/SlownessStatusEffect_test.cpp"
#endif | 0 | 0.855081 | 1 | 0.855081 | game-dev | MEDIA | 0.623449 | game-dev | 0.981499 | 1 | 0.981499 |
sashaportnova/EMG-IMU-collection-and-analysis-toolkit | 1,933 | Assets/XCharts/Runtime/Component/Axis/AxisAnimation.cs | using UnityEngine;
namespace XCharts.Runtime
{
/// <summary>
/// animation style of axis.
/// ||坐标轴动画配置。
/// </summary>
[System.Serializable]
[Since("v3.9.0")]
public class AxisAnimation : ChildComponent
{
[SerializeField] private bool m_Show = true;
[SerializeField] private float m_Duration;
[SerializeField] private bool m_UnscaledTime;
/// <summary>
/// whether to enable animation.
/// ||是否开启动画。
/// </summary>
public bool show
{
get { return m_Show; }
set { if (PropertyUtil.SetStruct(ref m_Show, value)) SetComponentDirty(); }
}
/// <summary>
/// the duration of animation (ms). When it is set to 0, the animation duration will be automatically calculated according to the serie.
/// ||动画时长(ms)。 默认设置为0时,会自动获取serie的动画时长。
/// </summary>
public float duration
{
get { return m_Duration; }
set { if (PropertyUtil.SetStruct(ref m_Duration, value)) SetComponentDirty(); }
}
/// <summary>
/// Animation updates independently of Time.timeScale.
/// ||动画是否受TimeScaled的影响。默认为 false 受TimeScaled的影响。
/// </summary>
public bool unscaledTime
{
get { return m_UnscaledTime; }
set { if (PropertyUtil.SetStruct(ref m_UnscaledTime, value)) SetComponentDirty(); }
}
public AxisAnimation Clone()
{
var animation = new AxisAnimation
{
show = show,
duration = duration,
unscaledTime = unscaledTime
};
return animation;
}
public void Copy(AxisAnimation animation)
{
show = animation.show;
duration = animation.duration;
unscaledTime = animation.unscaledTime;
}
}
} | 0 | 0.789234 | 1 | 0.789234 | game-dev | MEDIA | 0.708207 | game-dev | 0.938144 | 1 | 0.938144 |
Fluorohydride/ygopro-scripts | 1,253 | c69982329.lua | --ペンデュラム・ターン
function c69982329.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c69982329.target)
e1:SetOperation(c69982329.activate)
c:RegisterEffect(e1)
end
function c69982329.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_PZONE) end
if chk==0 then return Duel.IsExistingTarget(nil,tp,LOCATION_PZONE,LOCATION_PZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
local g=Duel.SelectTarget(tp,nil,tp,LOCATION_PZONE,LOCATION_PZONE,1,1,nil)
local tc=g:GetFirst()
local t={}
local p=1
for i=1,10 do
if i~=tc:GetLeftScale() then
t[p]=i
p=p+1
end
end
local ac=Duel.AnnounceNumber(tp,table.unpack(t))
e:SetLabel(ac)
end
function c69982329.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LSCALE)
e1:SetValue(e:GetLabel())
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_CHANGE_RSCALE)
tc:RegisterEffect(e2)
end
end
| 0 | 0.887355 | 1 | 0.887355 | game-dev | MEDIA | 0.978105 | game-dev | 0.930506 | 1 | 0.930506 |
UnioGame/leoecs.lite.features | 2,304 | Ability/Systems/EvaluateAbilitySystem.cs | namespace Game.Ecs.Ability.Common.Systems
{
using System;
using Characteristics.Cooldown.Components;
using Characteristics.Duration.Components;
using Components;
using Leopotam.EcsLite;
using UniGame.LeoEcs.Timer.Components;
using UniGame.LeoEcs.Bootstrap.Runtime.Attributes;
using UniGame.LeoEcs.Shared.Extensions;
using UnityEngine;
#if ENABLE_IL2CPP
using Unity.IL2CPP.CompilerServices;
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
#endif
[Serializable]
[ECSDI]
public sealed class EvaluateAbilitySystem : IEcsRunSystem,IEcsInitSystem
{
private EcsFilter _filter;
private EcsWorld _world;
private EcsPool<DurationComponent> _durationPool;
private EcsPool<CooldownComponent> _cooldownPool;
private EcsPool<AbilityEvaluationComponent> _evaluationPool;
private EcsPool<CompleteAbilitySelfRequest> _completeAbilityPool;
public void Init(IEcsSystems systems)
{
_world = systems.GetWorld();
_filter = _world
.Filter<AbilityUsingComponent>()
.Inc<DurationComponent>()
.Inc<CooldownComponent>()
.Exc<AbilityPauseComponent>()
.End();
}
public void Run(IEcsSystems systems)
{
foreach (var entity in _filter)
{
ref var durationComponent = ref _durationPool.Get(entity);
ref var cooldownComponent = ref _cooldownPool.Get(entity);
ref var evaluationComponent = ref _evaluationPool.GetOrAddComponent(entity);
var currentTime = evaluationComponent.EvaluateTime;
var delta = durationComponent.Value - currentTime;
if (delta > 0.0f && !Mathf.Approximately(delta, 0.0f))
{
evaluationComponent.EvaluateTime += Time.deltaTime * Mathf.Max(1.0f, durationComponent.Value / cooldownComponent.Value);
continue;
}
_completeAbilityPool.Add(entity);
}
}
}
} | 0 | 0.792261 | 1 | 0.792261 | game-dev | MEDIA | 0.986601 | game-dev | 0.868709 | 1 | 0.868709 |
mrthinger/wow-voiceover | 3,139 | AI_VoiceOver/3.3.5/Libs/LibDataBroker-1.1/LibDataBroker-1.1.lua |
assert(LibStub, "LibDataBroker-1.1 requires LibStub")
assert(LibStub:GetLibrary("CallbackHandler-1.0", true), "LibDataBroker-1.1 requires CallbackHandler-1.0")
local lib, oldminor = LibStub:NewLibrary("LibDataBroker-1.1", 4)
if not lib then return end
oldminor = oldminor or 0
lib.callbacks = lib.callbacks or LibStub:GetLibrary("CallbackHandler-1.0"):New(lib)
lib.attributestorage, lib.namestorage, lib.proxystorage = lib.attributestorage or {}, lib.namestorage or {}, lib.proxystorage or {}
local attributestorage, namestorage, callbacks = lib.attributestorage, lib.namestorage, lib.callbacks
if oldminor < 2 then
lib.domt = {
__metatable = "access denied",
__index = function(self, key) return attributestorage[self] and attributestorage[self][key] end,
}
end
if oldminor < 3 then
lib.domt.__newindex = function(self, key, value)
if not attributestorage[self] then attributestorage[self] = {} end
if attributestorage[self][key] == value then return end
attributestorage[self][key] = value
local name = namestorage[self]
if not name then return end
callbacks:Fire("LibDataBroker_AttributeChanged", name, key, value, self)
callbacks:Fire("LibDataBroker_AttributeChanged_"..name, name, key, value, self)
callbacks:Fire("LibDataBroker_AttributeChanged_"..name.."_"..key, name, key, value, self)
callbacks:Fire("LibDataBroker_AttributeChanged__"..key, name, key, value, self)
end
end
if oldminor < 2 then
function lib:NewDataObject(name, dataobj)
if self.proxystorage[name] then return end
if dataobj then
assert(type(dataobj) == "table", "Invalid dataobj, must be nil or a table")
self.attributestorage[dataobj] = {}
for i,v in pairs(dataobj) do
self.attributestorage[dataobj][i] = v
dataobj[i] = nil
end
end
dataobj = setmetatable(dataobj or {}, self.domt)
self.proxystorage[name], self.namestorage[dataobj] = dataobj, name
self.callbacks:Fire("LibDataBroker_DataObjectCreated", name, dataobj)
return dataobj
end
end
if oldminor < 1 then
function lib:DataObjectIterator()
return pairs(self.proxystorage)
end
function lib:GetDataObjectByName(dataobjectname)
return self.proxystorage[dataobjectname]
end
function lib:GetNameByDataObject(dataobject)
return self.namestorage[dataobject]
end
end
if oldminor < 4 then
local next = pairs(attributestorage)
function lib:pairs(dataobject_or_name)
local t = type(dataobject_or_name)
assert(t == "string" or t == "table", "Usage: ldb:pairs('dataobjectname') or ldb:pairs(dataobject)")
local dataobj = self.proxystorage[dataobject_or_name] or dataobject_or_name
assert(attributestorage[dataobj], "Data object not found")
return next, attributestorage[dataobj], nil
end
local ipairs_iter = ipairs(attributestorage)
function lib:ipairs(dataobject_or_name)
local t = type(dataobject_or_name)
assert(t == "string" or t == "table", "Usage: ldb:ipairs('dataobjectname') or ldb:ipairs(dataobject)")
local dataobj = self.proxystorage[dataobject_or_name] or dataobject_or_name
assert(attributestorage[dataobj], "Data object not found")
return ipairs_iter, attributestorage[dataobj], 0
end
end
| 0 | 0.848343 | 1 | 0.848343 | game-dev | MEDIA | 0.387658 | game-dev | 0.824973 | 1 | 0.824973 |
magefree/mage | 1,299 | Mage.Sets/src/mage/cards/b/BoonSatyr.java |
package mage.cards.b;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.common.continuous.BoostEnchantedEffect;
import mage.abilities.keyword.BestowAbility;
import mage.abilities.keyword.FlashAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.SubType;
import mage.constants.Zone;
/**
*
* @author LevelX2
*/
public final class BoonSatyr extends CardImpl {
public BoonSatyr(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT,CardType.CREATURE},"{1}{G}{G}");
this.subtype.add(SubType.SATYR);
this.power = new MageInt(4);
this.toughness = new MageInt(2);
// Flash
this.addAbility(FlashAbility.getInstance());
// Bestow {3}{G}{G}
this.addAbility(new BestowAbility(this, "{3}{G}{G}"));
// Enchanted creature gets +4/+2.
this.addAbility(new SimpleStaticAbility(new BoostEnchantedEffect(4,2, Duration.WhileOnBattlefield)));
}
private BoonSatyr(final BoonSatyr card) {
super(card);
}
@Override
public BoonSatyr copy() {
return new BoonSatyr(this);
}
}
| 0 | 0.905057 | 1 | 0.905057 | game-dev | MEDIA | 0.987184 | game-dev | 0.987123 | 1 | 0.987123 |
Cytoid/Cytoid | 1,517 | Assets/Scripts/Navigation/Elements/ChibiDisplay.cs | using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
public class ChibiDisplay : MonoBehaviour
{
public Image image;
public Animator animator;
private readonly List<Sequence> tweenSequences = new List<Sequence>();
public void SetSprite(Sprite sprite)
{
if (sprite == null)
{
image.sprite = null;
return;
}
SetAnimation(null);
image.sprite = sprite;
PopTween();
}
public void SetAnimation(RuntimeAnimatorController controller, string animationName = "Default")
{
if (controller == null)
{
animator.runtimeAnimatorController = null;
return;
}
SetSprite(null);
animator.runtimeAnimatorController = controller;
animator.Play(animationName);
PopTween();
}
private void PopTween()
{
tweenSequences.ForEach(it => it.Kill());
tweenSequences.Clear();
image.rectTransform.DOKill();
tweenSequences.Add(DOTween.Sequence()
.Append(image.rectTransform.DOScaleY(1.03f, 0.3f))
.Append(image.rectTransform.DOScaleY(1f, 0.3f))
.OnComplete(BreatheTween));
}
private void BreatheTween()
{
tweenSequences.Add(DOTween.Sequence()
.Append(image.rectTransform.DOScaleY(1.01f, 1.6f))
.Append(image.rectTransform.DOScaleY(1f, 1.6f))
.OnComplete(BreatheTween));
}
} | 0 | 0.596454 | 1 | 0.596454 | game-dev | MEDIA | 0.843727 | game-dev | 0.945194 | 1 | 0.945194 |
generik0/Smooth.IoC.Dapper.Repository.UnitOfWork | 1,862 | src/Smooth.IoC.Dapper.Repository.UnitOfWork/RepositorySaveOrUpdate.cs | using System;
using System.Threading.Tasks;
using Smooth.IoC.Repository.UnitOfWork.Extensions;
using Smooth.IoC.UnitOfWork.Interfaces;
namespace Smooth.IoC.Repository.UnitOfWork
{
public abstract partial class Repository< TEntity, TPk>
where TEntity : class
where TPk : IComparable
{
public virtual TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow)
{
if (TryAllKeysDefault(entity))
{
uow.Insert(entity);
}
else
{
uow.Update(entity);
}
var primaryKeyValue = GetPrimaryKeyValue(entity);
return primaryKeyValue != null ? primaryKeyValue : default(TPk);
}
public virtual TPk SaveOrUpdate<TSession>(TEntity entity) where TSession : class, ISession
{
using (var uow = Factory.Create<IUnitOfWork, TSession>())
{
return SaveOrUpdate(entity, uow);
}
}
public virtual async Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow)
{
return await Task.Run(() =>
{
if (TryAllKeysDefault(entity))
{
uow.InsertAsync(entity);
}
else
{
uow.UpdateAsync(entity);
}
var primaryKeyValue = GetPrimaryKeyValue(entity);
return primaryKeyValue != null ? primaryKeyValue : default(TPk);
});
}
public virtual async Task<TPk> SaveOrUpdateAsync<TSession>(TEntity entity) where TSession : class, ISession
{
using (var uow = Factory.Create<IUnitOfWork, TSession>())
{
return await SaveOrUpdateAsync(entity, uow);
}
}
}
}
| 0 | 0.830863 | 1 | 0.830863 | game-dev | MEDIA | 0.938449 | game-dev | 0.803046 | 1 | 0.803046 |
MohistMC/Youer | 1,280 | src/main/java/ca/spottedleaf/dataconverter/minecraft/versions/V3201.java | package ca.spottedleaf.dataconverter.minecraft.versions;
import ca.spottedleaf.dataconverter.converters.DataConverter;
import ca.spottedleaf.dataconverter.minecraft.MCVersions;
import ca.spottedleaf.dataconverter.minecraft.datatypes.MCTypeRegistry;
import ca.spottedleaf.dataconverter.types.MapType;
public final class V3201 {
private static final int VERSION = MCVersions.V1_19_2 + 81;
public static void register() {
MCTypeRegistry.OPTIONS.addStructureConverter(new DataConverter<>(VERSION) {
private static void fixList(final MapType<String> data, final String target) {
if (data == null) {
return;
}
final String curr = data.getString(target);
if (curr == null) {
return;
}
data.setString(target, curr.replace("\"programer_art\"", "\"programmer_art\""));
}
@Override
public MapType<String> convert(final MapType<String> data, final long sourceVersion, final long toVersion) {
fixList(data, "resourcePacks");
fixList(data, "incompatibleResourcePacks");
return null;
}
});
}
private V3201() {}
}
| 0 | 0.654834 | 1 | 0.654834 | game-dev | MEDIA | 0.610582 | game-dev | 0.564941 | 1 | 0.564941 |
AzureeDev/payday-2-luajit | 34,071 | pd2-lua/lib/managers/menu/renderers/menunodecustomizeweaponcolorgui.lua | core:import("CoreMenuItemOption")
require("lib/managers/menu/MenuInitiatorBase")
require("lib/managers/menu/renderers/MenuNodeBaseGui")
local massive_font = tweak_data.menu.pd2_massive_font
local large_font = tweak_data.menu.pd2_large_font
local medium_font = tweak_data.menu.pd2_medium_font
local small_font = tweak_data.menu.pd2_small_font
local tiny_font = tweak_data.menu.pd2_tiny_font
local massive_font_size = tweak_data.menu.pd2_massive_font_size
local large_font_size = tweak_data.menu.pd2_large_font_size
local medium_font_size = tweak_data.menu.pd2_medium_font_size
local small_font_size = tweak_data.menu.pd2_small_font_size
local tiny_font_size = tweak_data.menu.pd2_tiny_font_size
MenuCustomizeWeaponColorInitiator = MenuCustomizeWeaponColorInitiator or class(MenuInitiatorBase)
function MenuCustomizeWeaponColorInitiator:modify_node(original_node, node_data)
local node = original_node
return self:setup_node(node, node_data)
end
function MenuCustomizeWeaponColorInitiator:setup_node(node, node_data)
node:clean_items()
node.topic_id = node_data.topic_id
node.topic_params = node_data.topic_params
local weapon_color_data = {}
node.weapon_color_data = weapon_color_data
local crafted = managers.blackmarket:get_crafted_category_slot(node_data.category, node_data.slot)
if not crafted or not crafted.cosmetics then
return node
end
local weapon_color_id = crafted.cosmetics.id or node_data.name
local weapon_color_quality = crafted.cosmetics.quality or node_data.cosmetic_quality
local weapon_color_index = crafted.cosmetics.color_index or node_data.cosmetic_index
local weapon_pattern_scale = crafted.cosmetics.pattern_scale or node_data.pattern_scale or tweak_data.blackmarket.weapon_color_pattern_scale_default
weapon_color_data.category = node_data.category
weapon_color_data.slot = node_data.slot
weapon_color_data.cosmetic_data = clone(crafted.cosmetics)
local weapon_color_tweak_data = tweak_data.blackmarket.weapon_skins[weapon_color_id]
local weapon_color_variation_template = tweak_data.blackmarket.weapon_color_templates.color_variation
local color_group_data = {}
node.color_group_data = color_group_data
color_group_data.options = {}
color_group_data.selected = 1
color_group_data.highlighted = nil
table.insert(color_group_data.options, {
value = "all",
text_id = "menu_weapon_color_group_all"
})
local global_value_data = nil
for index, id in ipairs(tweak_data.blackmarket.weapon_color_groups) do
global_value_data = tweak_data.lootdrop.global_value_category[id] or tweak_data.lootdrop.global_values[id] or tweak_data.lootdrop.global_value_category.normal
if global_value_data then
table.insert(color_group_data.options, {
value = id,
text_id = global_value_data.name_id
})
end
end
if not node:item("divider_end") then
local guis_catalog, bundle_folder, color_tweak, unlocked, have_color, dlc, global_value = nil
local colors_data = {}
for index, id in ipairs(tweak_data.blackmarket.weapon_colors) do
color_tweak = tweak_data.blackmarket.weapon_skins[id]
guis_catalog = "guis/"
bundle_folder = color_tweak.texture_bundle_folder
if bundle_folder then
guis_catalog = guis_catalog .. "dlcs/" .. tostring(bundle_folder) .. "/"
end
dlc = color_tweak.dlc or managers.dlc:global_value_to_dlc(color_tweak.global_value)
global_value = color_tweak.global_value or managers.dlc:dlc_to_global_value(dlc)
unlocked = not dlc or managers.dlc:is_dlc_unlocked(dlc)
have_color = managers.blackmarket:has_item(global_value, "weapon_skins", id)
table.insert(colors_data, {
visible_callback = "is_weapon_color_option_visible",
_meta = "option",
disabled_icon_callback = "get_weapon_color_disabled_icon",
enabled_callback = "is_weapon_color_option_unlocked",
value = id,
color = color_tweak.color,
text_id = "bm_wskn_" .. id,
unlocked = unlocked,
have_color = have_color,
texture = guis_catalog .. "textures/pd2/blackmarket/icons/weapon_color/" .. id
})
end
local color_item = self:create_grid(node, colors_data, {
callback = "refresh_node",
name = "cosmetic_color",
height_aspect = 0.85,
text_id = "menu_weapon_color_title",
align_line_proportions = 0,
rows = 2.5,
sort_callback = "sort_weapon_colors",
columns = 20
})
color_item:set_value(weapon_color_id)
self:create_divider(node, "padding", nil, 10)
local variations_data = {}
for index = 1, #weapon_color_variation_template do
table.insert(variations_data, {
_meta = "option",
value = index,
text_id = tweak_data.blackmarket:get_weapon_color_index_string(index)
})
end
local variation_item = self:create_multichoice(node, variations_data, {
callback = "refresh_node",
name = "cosmetic_variation",
text_id = "menu_weapon_color_index_title"
})
variation_item:set_value(weapon_color_index)
local qualities = {}
for id, data in pairs(tweak_data.economy.qualities) do
table.insert(qualities, {
localize = true,
_meta = "option",
value = id,
text_id = data.name_id,
index = data.index
})
end
table.sort(qualities, function (x, y)
return y.index < x.index
end)
local quality_item = self:create_multichoice(node, qualities, {
callback = "refresh_node",
name = "quality",
text_id = "menu_weapon_color_quality"
})
quality_item:set_value(weapon_color_quality)
self:create_divider(node, "no_pattern_scale", nil, 21, nil, "should_show_pattern_divider")
local pattern_scales = {}
for index, data in ipairs(tweak_data.blackmarket.weapon_color_pattern_scales) do
table.insert(pattern_scales, {
_meta = "option",
value = index,
text_id = data.name_id,
index = index
})
end
local pattern_scale_item = self:create_multichoice(node, pattern_scales, {
visible_callback = "should_show_pattern_scale",
name = "pattern_scale",
callback = "refresh_node",
text_id = "menu_weapon_color_pattern_scale"
})
pattern_scale_item:set_value(weapon_pattern_scale)
end
self:create_divider(node, "end", nil, 8)
local new_item = nil
local apply_params = {
visible_callback = "should_show_weapon_color_apply",
name = "apply",
callback = "apply_weapon_color",
text_id = "dialog_apply",
align = "right"
}
new_item = node:create_item({}, apply_params)
new_item:set_enabled(false)
node:add_item(new_item)
local buy_dlc_params = {
visible_callback = "should_show_weapon_color_buy",
name = "buy_dlc",
callback = "buy_weapon_color_dlc",
text_id = "menu_dlc_buy_weapon_color",
align = "right"
}
new_item = node:create_item({}, buy_dlc_params)
node:add_item(new_item)
if managers.menu:is_pc_controller() then
local back_params = {
last_item = "true",
name = "back",
text_id = "menu_back",
align = "right",
previous_node = "true"
}
new_item = node:create_item({}, back_params)
node:add_item(new_item)
end
node:set_default_item_name("cosmetic_color")
managers.blackmarket:view_weapon_with_cosmetics(weapon_color_data.category, weapon_color_data.slot, weapon_color_data.cosmetic_data, nil, nil, BlackMarketGui.get_crafting_custom_data())
node.randomseed = os.time()
math.randomseed(node.randomseed)
return node
end
function MenuCustomizeWeaponColorInitiator:refresh_node(node)
local cosmetic_color_item = node:item("cosmetic_color")
cosmetic_color_item:visible()
local weapon_color_data = node.weapon_color_data
local cosmetic_data = weapon_color_data.cosmetic_data
local cosmetic_color_item = node:item("cosmetic_color")
local cosmetic_variation_item = node:item("cosmetic_variation")
local quality_item = node:item("quality")
local apply_item = node:item("apply")
local color_id = cosmetic_color_item:value()
local color_index = cosmetic_variation_item:value()
local color_quality = quality_item:value()
local color_tweak_data = tweak_data.blackmarket.weapon_skins[color_id]
cosmetic_data.id = color_id
cosmetic_data.instance_id = color_id
cosmetic_data.color_index = color_index
cosmetic_data.quality = color_quality
local pattern_scale = color_tweak_data.pattern_scale
if pattern_scale then
cosmetic_data.pattern_scale = tonumber(pattern_scale) > 0 and pattern_scale or nil
elseif MenuCallbackHandler:should_show_pattern_scale() then
local cosmetic_pattern_scale_item = node:item("pattern_scale")
local color_pattern_scale = cosmetic_pattern_scale_item:value()
cosmetic_data.pattern_scale = color_tweak_data.color_skin_data and color_tweak_data.color_skin_data.pattern_default and color_pattern_scale or nil
else
cosmetic_data.pattern_scale = nil
end
local weapon_unit_data = managers.menu_scene and managers.menu_scene:get_item_unit_data()
local weapon_unit = weapon_unit_data and weapon_unit_data.unit
if alive(weapon_unit) then
weapon_unit:base():change_cosmetics(cosmetic_data)
end
local second_unit = weapon_unit_data and weapon_unit_data.second_unit
if alive(second_unit) then
second_unit:base():change_cosmetics(cosmetic_data)
end
node.color_group_data.highlighted = nil
local can_apply = MenuCallbackHandler:can_apply_weapon_color(node)
apply_item:set_enabled(can_apply)
math.randomseed(node.randomseed)
return node
end
MenuNodeCustomizeWeaponColorGui = MenuNodeCustomizeWeaponColorGui or class(MenuNodeBaseGui)
MenuNodeCustomizeWeaponColorGui.CUSTOM_MOUSE_INPUT = true
function MenuNodeCustomizeWeaponColorGui:init(node, layer, parameters)
parameters.font = tweak_data.menu.pd2_small_font
parameters.font_size = tweak_data.menu.pd2_small_font_size
parameters.align = "left"
parameters.row_item_blend_mode = "add"
parameters.row_item_color = tweak_data.screen_colors.button_stage_3
parameters.row_item_hightlight_color = tweak_data.screen_colors.button_stage_2
parameters.marker_alpha = 1
parameters.to_upper = true
MenuNodeCustomizeWeaponColorGui.super.init(self, node, layer, parameters)
end
function MenuNodeCustomizeWeaponColorGui:_setup_item_panel_parent(safe_rect, shape)
shape = shape or {}
shape.x = shape.x or safe_rect.x
shape.y = shape.y or safe_rect.y + 0
shape.w = shape.w or safe_rect.width
shape.h = shape.h or safe_rect.height - 0
MenuNodeCustomizeWeaponColorGui.super._setup_item_panel_parent(self, safe_rect, shape)
end
function MenuNodeCustomizeWeaponColorGui:setup(node)
MenuNodeCustomizeWeaponColorGui.super.setup(self, node)
self:update_color_info()
end
function MenuNodeCustomizeWeaponColorGui:_setup_item_panel(safe_rect, res)
MenuNodeCustomizeWeaponColorGui.super._setup_item_panel(self, safe_rect, res)
local align_padding = self._align_line_padding or 10
local color_grid_row_item = self:row_item_by_name("cosmetic_color")
local item_width = safe_rect.width * (1 - self._align_line_proportions)
local color_grid_width = color_grid_row_item.gui_panel:width()
self.item_panel:set_w(color_grid_width)
self.item_panel:set_center_x(safe_rect.width / 2 + 4)
self.item_panel:set_bottom(safe_rect.height - align_padding * 2 - (alive(self._legends_panel) and self._legends_panel:h() + align_padding or 0))
local title_string = managers.localization:to_upper_text(self.node.topic_id, self.node.topic_params)
self._text_panel = self._item_panel_parent:panel({
name = "title_panel",
layer = self.layers.background
})
self._text_panel:text({
name = "title_text",
layer = 1,
text = title_string,
font_size = tweak_data.menu.pd2_large_font_size,
font = tweak_data.menu.pd2_large_font,
color = tweak_data.screen_colors.text
})
self._text_panel:text({
rotation = 360,
name = "title_bg_text",
alpha = 0.4,
y = -13,
x = -13,
text = title_string,
font_size = tweak_data.menu.pd2_massive_font_size,
font = tweak_data.menu.pd2_massive_font,
color = tweak_data.screen_colors.button_stage_3
})
self._tab_panel = self._item_panel_parent:panel({
name = "tab_panel",
layer = self.layers.items
})
self._tabs = {}
self._tab_scroll_parent_panel = self._tab_panel:panel({
x = self.item_panel:left(),
width = self.item_panel:right() - self.item_panel:left()
})
self._tab_scroll_panel = self._tab_scroll_parent_panel:panel({
x = self.node.tab_panel_position or 0
})
local _, tw, th, tab_panel, tab_text, tab_select_rect = nil
local color_group_data = self.node.color_group_data
local tab_scroll_h = 0
local tab_padding = 15
for index, option in ipairs(color_group_data.options) do
tab_panel = self._tab_scroll_panel:panel()
tab_select_rect = tab_panel:bitmap({
texture = "guis/textures/pd2/shared_tab_box",
halign = "grow",
valign = "grow",
w = tab_panel:w(),
h = tab_panel:h()
})
tab_text = tab_panel:text({
vertical = "center",
halign = "grow",
align = "center",
layer = 1,
valign = "grow",
text = managers.localization:to_upper_text(option.text_id),
font = medium_font,
font_size = medium_font_size
})
_, _, tw, th = tab_text:text_rect()
tab_panel:set_size(tw + tab_padding, th + 10)
tab_panel:set_left(#self._tabs > 0 and self._tabs[#self._tabs].panel:right() or 0)
tab_scroll_h = math.max(tab_scroll_h, th + 10)
table.insert(self._tabs, {
panel = tab_panel,
text = tab_text,
select_rect = tab_select_rect
})
self:_update_tab(index)
end
self._tab_scroll_parent_panel:set_height(tab_scroll_h)
self._tab_scroll_parent_panel:set_bottom(self.item_panel:top() + 2 - align_padding)
self._tab_scroll_panel:set_size(self._tabs[#self._tabs].panel:right(), tab_scroll_h)
if self._tab_scroll_parent_panel:width() < self._tab_scroll_panel:width() then
local is_pc_controller = managers.menu:is_pc_controller()
local is_steam_controller = is_pc_controller and managers.menu:is_steam_controller() or false
local prev_string = nil
if is_pc_controller then
prev_string = is_steam_controller and managers.localization:steam_btn("bumper_l") or "<"
else
prev_string = managers.localization:get_default_macro("BTN_BOTTOM_L")
end
local prev_color = self._prev_page_highlighted and tweak_data.screen_colors.button_stage_2 or tweak_data.screen_colors.button_stage_3
local prev_page = self._tab_panel:text({
name = "prev_page",
layer = 1,
font_size = medium_font_size,
font = medium_font,
color = prev_color,
text = prev_string
})
_, _, tw, th = prev_page:text_rect()
prev_page:set_size(tw, tab_scroll_h)
prev_page:set_position(align_padding, self._tab_scroll_parent_panel:top())
local next_string = nil
if is_pc_controller then
next_string = is_steam_controller and managers.localization:steam_btn("bumper_r") or ">"
else
next_string = managers.localization:get_default_macro("BTN_BOTTOM_R")
end
local next_color = self._next_page_highlighted and tweak_data.screen_colors.button_stage_2 or tweak_data.screen_colors.button_stage_3
local next_page = self._tab_panel:text({
name = "next_page",
layer = 1,
font_size = medium_font_size,
font = medium_font,
color = next_color,
text = next_string
})
_, _, tw, th = next_page:text_rect()
next_page:set_size(tw, tab_scroll_h)
next_page:set_righttop(self._tab_panel:width() - align_padding - 4, self._tab_scroll_parent_panel:top())
self._tab_scroll_parent_panel:set_width(next_page:left() - prev_page:right() - 2 * align_padding)
self._tab_scroll_parent_panel:set_x(prev_page:right() + align_padding)
if is_steam_controller or not is_pc_controller then
prev_page:set_color(tweak_data.screen_colors.text)
next_page:set_color(tweak_data.screen_colors.text)
prev_page:move(0, 4)
next_page:move(0, 4)
end
end
self:update_tab_panel_position()
self:update_color_info()
if alive(self.box_panel) then
self._item_panel_parent:remove(self.box_panel)
self.box_panel = nil
end
self.box_panel = self._item_panel_parent:panel({
name = "box_panel",
layer = self.layers.background
})
self.box_panel:set_shape(self.item_panel:shape())
self.box_panel:grow(align_padding * 1, align_padding * 2)
self.box_panel:move(-align_padding, -align_padding)
self.boxgui = BoxGuiObject:new(self.box_panel, {
layer = 1,
sides = {
1,
1,
2,
1
}
})
self.boxgui:set_clipping(false)
self.box_panel:rect({
alpha = 0.6,
rotation = 360,
layer = 0,
color = Color.black
})
self.blur = self.box_panel:bitmap({
texture = "guis/textures/test_blur_df",
render_template = "VertexColorTexturedBlur3D",
w = self.box_panel:w(),
h = self.box_panel:h()
})
local start_blur = self.start_blur or 0
local function func(o)
local blur = start_blur
over(0.6, function (p)
o:set_alpha(math.lerp(blur, 1, p))
end)
end
self.blur:animate(func)
self._align_data.panel:set_left(self.box_panel:left())
self:_set_topic_position()
end
function MenuNodeCustomizeWeaponColorGui:_update_tab(index)
local color_group_data = self.node.color_group_data
local tab = self._tabs[index]
if color_group_data.selected == index then
tab.text:set_color(tweak_data.screen_colors.button_stage_1)
tab.text:set_blend_mode("normal")
tab.select_rect:show()
elseif color_group_data.highlighted == index then
tab.text:set_color(tweak_data.screen_colors.button_stage_2)
tab.text:set_blend_mode("add")
tab.select_rect:hide()
else
tab.text:set_color(tweak_data.screen_colors.button_stage_3)
tab.text:set_blend_mode("add")
tab.select_rect:hide()
end
end
function MenuNodeCustomizeWeaponColorGui:update_tab_panel_position()
local color_group_data = self.node.color_group_data
local selected = color_group_data.selected
local tab = self._tabs[selected]
local tab_panel = tab.panel
if tab_panel:left() + self._tab_scroll_panel:x() < 0 then
self._tab_scroll_panel:set_left(-tab_panel:left())
elseif self._tab_scroll_parent_panel:width() < tab_panel:right() + self._tab_scroll_panel:x() then
self._tab_scroll_panel:set_right(self._tab_scroll_parent_panel:width() - (tab_panel:right() - self._tab_scroll_panel:width()))
end
self.node.tab_panel_position = self._tab_scroll_panel:left()
local prev_page = self._tab_panel:child("prev_page")
if alive(prev_page) then
prev_page:set_visible(self._tab_scroll_panel:left() < 0)
end
local next_page = self._tab_panel:child("next_page")
if alive(next_page) then
next_page:set_visible(self._tab_scroll_parent_panel:width() < self._tab_scroll_panel:right())
end
end
function MenuNodeCustomizeWeaponColorGui:_set_color_group_index(index)
local color_group_data = self.node.color_group_data
local new_index = math.clamp(index, 1, #color_group_data.options)
if new_index ~= color_group_data.selected then
color_group_data.selected = new_index
managers.menu:active_menu().logic:refresh_node()
end
end
function MenuNodeCustomizeWeaponColorGui:input_focus()
if self._mouse_over_row_item then
local current_item = managers.menu:active_menu().logic:selected_item()
local mouse_over_item = self._mouse_over_row_item.item
if current_item == mouse_over_item and mouse_over_item.TYPE == "grid" then
return 1
end
end
if self._mouse_over_tab_panel or self._prev_page_highlighted or self._next_page_highlighted then
return 1
end
end
function MenuNodeCustomizeWeaponColorGui:mouse_moved(o, x, y)
local used = false
local icon = "arrow"
if managers.menu_scene:input_focus() then
self._mouse_over_row_item = nil
self._mouse_over_tab_panel = nil
return used, icon
end
local current_item = managers.menu:active_menu().logic:selected_item()
local current_row_item = current_item and self:row_item(current_item)
local selected_row_item = nil
if current_row_item and current_row_item.gui_panel and current_row_item.gui_panel:inside(x, y) then
selected_row_item = current_row_item
else
local inside_item_panel_parent = self:item_panel_parent():inside(x, y)
local item, is_inside = nil
for _, row_item in pairs(self.row_items) do
item = row_item.item
is_inside = false
if item and not item.no_mouse_select then
is_inside = item.TYPE == "grid" and item:scroll_bar_grabbed(row_item) and true or inside_item_panel_parent and row_item.gui_panel:inside(x, y)
end
if is_inside then
selected_row_item = row_item
break
end
end
end
if selected_row_item then
local selected_name = selected_row_item.name
used = true
icon = "link"
if not current_item or selected_name ~= current_item:name() then
managers.menu:active_menu().logic:mouse_over_select_item(selected_name, false)
current_row_item = selected_row_item
current_item = selected_row_item.item
end
if current_item then
self._mouse_over_row_item = current_row_item
if current_item.TYPE == "grid" then
icon = current_item:mouse_moved(x, y, current_row_item)
elseif current_item.TYPE == "multi_choice" then
local inside_arrow_left = current_row_item.arrow_left:visible() and current_row_item.arrow_left:inside(x, y)
local inside_arrow_right = current_row_item.arrow_right:visible() and current_row_item.arrow_right:inside(x, y)
local inside_gui_text = current_row_item.arrow_left:visible() and current_row_item.arrow_right:visible() and current_row_item.gui_text:inside(x, y)
local inside_choice_panel = current_row_item.choice_panel:visible() and current_row_item.choice_panel:inside(x, y)
if inside_arrow_left or inside_arrow_right or inside_gui_text or inside_choice_panel then
icon = "link"
else
icon = "arrow"
end
end
end
else
self._mouse_over_row_item = nil
end
self._mouse_over_tab_panel = self._tab_scroll_parent_panel:inside(x, y)
local prev_page = self._tab_panel:child("prev_page")
if alive(prev_page) then
local is_inside = prev_page:inside(x, y) and prev_page:visible()
if is_inside then
used = true
icon = "link"
end
if is_inside then
if not self._prev_page_highlighted then
self._prev_page_highlighted = true
managers.menu_component:post_event("highlight")
prev_page:set_color(tweak_data.screen_colors.button_stage_2)
end
return used, icon
elseif self._prev_page_highlighted then
self._prev_page_highlighted = nil
prev_page:set_color(tweak_data.screen_colors.button_stage_3)
end
end
local next_page = self._tab_panel:child("next_page")
if alive(next_page) then
local is_inside = next_page:inside(x, y) and next_page:visible()
if is_inside then
used = true
icon = "link"
end
if is_inside then
if not self._next_page_highlighted then
self._next_page_highlighted = true
managers.menu_component:post_event("highlight")
next_page:set_color(tweak_data.screen_colors.button_stage_2)
end
return used, icon
elseif self._next_page_highlighted then
self._next_page_highlighted = nil
next_page:set_color(tweak_data.screen_colors.button_stage_3)
end
end
local color_group_data = self.node.color_group_data
if color_group_data.highlighted then
local highlighted_tab = self._tabs[color_group_data.highlighted]
if highlighted_tab.panel:inside(x, y) then
return true, color_group_data.highlighted == color_group_data.selected and "arrow" or "link"
end
local prev_highlighted = color_group_data.highlighted
color_group_data.highlighted = nil
self:_update_tab(prev_highlighted)
end
if self._mouse_over_tab_panel then
for index, tab in ipairs(self._tabs) do
if tab.panel:inside(x, y) then
color_group_data.highlighted = index
self:_update_tab(index)
used = true
icon = "link"
if color_group_data.selected ~= index then
icon = "arrow"
managers.menu_component:post_event("highlight")
end
break
end
end
end
return used, icon
end
function MenuNodeCustomizeWeaponColorGui:mouse_pressed(button, x, y)
local active_menu = managers.menu:active_menu()
if not managers.menu:active_menu() then
return
end
local logic = active_menu.logic
local input = active_menu.input
if self._mouse_over_row_item then
local mouse_over_item = self._mouse_over_row_item.item
if button == Idstring("mouse wheel down") then
if mouse_over_item.TYPE == "grid" then
return mouse_over_item:wheel_scroll_start(-1, self._mouse_over_row_item)
end
elseif button == Idstring("mouse wheel up") and mouse_over_item.TYPE == "grid" then
return mouse_over_item:wheel_scroll_start(1, self._mouse_over_row_item)
end
if button == Idstring("0") then
if mouse_over_item.TYPE == "grid" then
mouse_over_item:mouse_pressed(button, x, y, self._mouse_over_row_item)
elseif mouse_over_item.TYPE == "multi_choice" then
if self._mouse_over_row_item.arrow_right:inside(x, y) then
if mouse_over_item:next() then
input:post_event("selection_next")
logic:trigger_item(true, mouse_over_item)
end
elseif self._mouse_over_row_item.arrow_left:inside(x, y) then
if mouse_over_item:previous() then
input:post_event("selection_previous")
logic:trigger_item(true, mouse_over_item)
end
elseif self._mouse_over_row_item.gui_text:inside(x, y) then
if self._mouse_over_row_item.align == "left" then
if mouse_over_item:previous() then
input:post_event("selection_previous")
logic:trigger_item(true, mouse_over_item)
end
elseif mouse_over_item:next() then
input:post_event("selection_next")
logic:trigger_item(true, mouse_over_item)
end
elseif self._mouse_over_row_item.choice_panel:inside(x, y) and mouse_over_item:enabled() then
mouse_over_item:popup_choice(self._mouse_over_row_item)
input:post_event("selection_next")
logic:trigger_item(true, mouse_over_item)
end
elseif mouse_over_item.TYPE == "divider" then
-- Nothing
else
local item = logic:selected_item()
if item then
input._item_input_action_map[item.TYPE](item, input._controller, true)
end
end
return true
end
elseif self._mouse_over_tab_panel then
if button == Idstring("mouse wheel down") then
self:next_page()
return true
elseif button == Idstring("mouse wheel up") then
self:previous_page()
return true
end
elseif self._prev_page_highlighted then
self:previous_page()
return true
elseif self._next_page_highlighted then
self:next_page()
return true
end
if button == Idstring("0") then
local color_group_data = self.node.color_group_data
local highlighted_tab = self._tabs[color_group_data.highlighted]
if highlighted_tab and highlighted_tab.panel:inside(x, y) then
self:_set_color_group_index(color_group_data.highlighted)
return true
end
end
end
function MenuNodeCustomizeWeaponColorGui:mouse_released(button, x, y)
local item = nil
for _, row_item in pairs(self.row_items) do
item = row_item.item
if item.TYPE == "grid" then
row_item.item:mouse_released(button, x, y, row_item)
end
end
end
function MenuNodeCustomizeWeaponColorGui:previous_page()
local color_group_data = self.node.color_group_data
self:_set_color_group_index(color_group_data.selected - 1)
end
function MenuNodeCustomizeWeaponColorGui:next_page()
local color_group_data = self.node.color_group_data
self:_set_color_group_index(color_group_data.selected + 1)
end
function MenuNodeCustomizeWeaponColorGui:_set_info_shape()
local top_align_row_item = self:row_item_by_name("cosmetic_variation")
local left = self.item_panel:world_left()
local top = top_align_row_item.gui_panel:world_top()
local width = self.item_panel:width() - top_align_row_item.gui_panel:width() - self._align_line_padding * 2
local height = self.item_panel:height() - top_align_row_item.gui_panel:top() + self._align_line_padding * 0
self._info_bg_rect:set_world_position(left, top)
self._info_bg_rect:set_size(width, height)
local mini_info = self._mini_info_text:parent()
local mini_text = self._mini_info_text
mini_info:set_shape(self._info_bg_rect:shape())
mini_text:set_shape(self._align_line_padding, self._align_line_padding, mini_info:w() - self._align_line_padding * 2, mini_info:h() - self._align_line_padding * 2)
if self.info_box_gui then
self.info_box_gui:close()
self.info_box_gui = nil
end
self.info_box_gui = BoxGuiObject:new(mini_info, {
sides = {
1,
1,
1,
1
},
layer = self.layers.background + 1
})
if self.item_box_gui then
self.item_box_gui:close()
self.item_box_gui = nil
end
if self.item_box_panel then
self.item_box_panel:parent():remove(self.item_box_panel)
end
self.item_box_panel = self.safe_rect_panel:panel({
x = mini_info:right() + self._align_line_padding,
y = mini_info:top(),
w = top_align_row_item.gui_panel:width() + self._align_line_padding * 2,
h = mini_info:h()
})
self.item_box_gui = BoxGuiObject:new(self.item_box_panel, {
sides = {
0,
0,
0,
0
},
layer = self.layers.background + 1
})
MenuNodeBaseGui.rec_round_object(mini_text)
end
function MenuNodeCustomizeWeaponColorGui:_set_item_positions()
MenuNodeCustomizeWeaponColorGui.super._set_item_positions(self)
self:_set_info_shape()
end
function MenuNodeCustomizeWeaponColorGui:resolution_changed()
MenuNodeCustomizeWeaponColorGui.super.resolution_changed(self)
self:_set_info_shape()
end
function MenuNodeCustomizeWeaponColorGui:update_color_info(node)
node = node or self.node
if not node then
return
end
local data = node.weapon_color_data
if not data or not data.cosmetic_data then
return
end
local info_string = ""
local color_range = {}
local function _add_string(new_string, color, separator)
separator = separator or ""
local s = utf8.len(info_string) + 1
info_string = info_string .. separator .. new_string
if color then
local e = utf8.len(info_string)
table.insert(color_range, {
s,
e,
color
})
end
end
local color_id = data.cosmetic_data.id
local color_tweak = tweak_data.blackmarket.weapon_skins[color_id]
local name_id = color_tweak.name_id
local desc_id = color_tweak.desc_id
local unlock_id = nil
local unlock_macros = {}
local dlc = color_tweak.dlc or managers.dlc:global_value_to_dlc(color_tweak.global_value)
local global_value = color_tweak.global_value or managers.dlc:dlc_to_global_value(dlc)
local gvalue_tweak = tweak_data.lootdrop.global_values[global_value]
local cosmetic_color_item = node:item("cosmetic_color")
local color_item_option = cosmetic_color_item:get_option(color_id)
local unlocked = color_item_option:get_parameter("unlocked")
local have_color = color_item_option:get_parameter("have_color")
if not unlocked then
unlock_id = gvalue_tweak and gvalue_tweak.unlock_id or "bm_menu_dlc_locked"
elseif not have_color then
local achievement_locked_content = managers.dlc:weapon_color_achievement_locked_content(color_id)
local milestone_locked_content = managers.dlc:weapon_color_achievement_milestone_locked_content(color_id)
local dlc_tweak = tweak_data.dlc[achievement_locked_content]
local achievement = dlc_tweak and dlc_tweak.achievement_id
local achievement = dlc_tweak and dlc_tweak.achievement_id
if achievement and managers.achievment:get_info(achievement) then
local achievement_visual = tweak_data.achievement.visual[achievement]
unlock_id = achievement_visual and achievement_visual.desc_id or "achievement_" .. tostring(achievement) .. "_desc" or "bm_menu_dlc_locked"
elseif milestone_locked_content then
for _, data in ipairs(tweak_data.achievement.milestones) do
if data.id == milestone_locked_content then
unlock_id = "bm_menu_milestone_reward_unlock"
unlock_macros.NUM = tostring(data.at)
break
end
end
elseif managers.dlc:is_content_skirmish_locked("weapon_skins", color_id) then
unlock_id = "bm_menu_skirmish_content_reward"
elseif managers.dlc:is_content_crimespree_locked("weapon_skins", color_id) then
unlock_id = "bm_menu_crimespree_content_reward"
elseif managers.dlc:is_content_infamy_locked("weapon_skins", color_id) then
unlock_id = "menu_infamy_lock_info"
else
unlock_id = "bm_menu_dlc_locked"
end
end
if name_id then
_add_string(managers.localization:to_upper_text(name_id), nil, "")
end
if gvalue_tweak and gvalue_tweak.desc_id then
_add_string(managers.localization:to_upper_text(gvalue_tweak.desc_id), gvalue_tweak.color, "\n")
end
if unlock_id then
_add_string(managers.localization:to_upper_text(unlock_id, unlock_macros), tweak_data.screen_colors.important_1, "\n")
end
self:set_mini_info_with_color_range(info_string, color_range)
end
function MenuNodeGui:set_mini_info_with_color_range(text, color_range)
self._mini_info_text:set_text(text)
self._mini_info_text:clear_range_color(0, utf8.len(self._mini_info_text:text()))
for _, data in ipairs(color_range) do
self._mini_info_text:set_range_color(unpack(data))
end
end
function MenuNodeCustomizeWeaponColorGui:_clear_gui()
if alive(self.blur) then
self.start_blur = self.blur:alpha()
end
MenuNodeCustomizeWeaponColorGui.super._clear_gui(self)
self._mouse_over_row_item = nil
if self._text_panel then
self._item_panel_parent:remove(self._text_panel)
self._text_panel = nil
end
if self._tab_panel then
self._item_panel_parent:remove(self._tab_panel)
self._tab_panel = nil
end
end
function MenuNodeCustomizeWeaponColorGui:_setup_item_rows(node)
MenuNodeCustomizeWeaponColorGui.super._setup_item_rows(self, node)
end
function MenuNodeCustomizeWeaponColorGui:reload_item(item)
MenuNodeCustomizeWeaponColorGui.super.reload_item(self, item)
local row_item = self:row_item(item)
if row_item and alive(row_item.gui_panel) and (not item.align_panel or not item:align_panel(row_item, self.item_panel)) then
row_item.gui_panel:set_halign("right")
row_item.gui_panel:set_right(self.item_panel:w() - self._align_line_padding)
end
end
function MenuNodeCustomizeWeaponColorGui:_align_marker(row_item)
MenuNodeCustomizeWeaponColorGui.super._align_marker(self, row_item)
self._marker_data.marker:set_world_right(self.item_panel:world_right() - self._align_line_padding)
end
function MenuNodeCustomizeWeaponColorGui:close()
for _, row_item in ipairs(self.row_items) do
if row_item.item and type(row_item.item.close) == "function" then
row_item.item:close(row_item)
end
end
math.randomseed(os.time())
MenuNodeCustomizeWeaponColorGui.super.close(self)
end
| 0 | 0.96907 | 1 | 0.96907 | game-dev | MEDIA | 0.960921 | game-dev | 0.953701 | 1 | 0.953701 |
Roll20/roll20-api-scripts | 161,397 | Condefinition/Condefinition.js | var API_Meta = API_Meta ||
{}; //eslint-disable-line no-var
API_Meta.Condefinition = {
offset: Number.MAX_SAFE_INTEGER,
lineCount: -1
};
{
try
{
throw new Error('');
}
catch (e)
{
API_Meta.Condefinition.offset = (parseInt(e.stack.split(/\n/)[1].replace(/^.*:(\d+):.*$/, '$1'), 10) - (7));
}
}
/* globals libTokenMarkers, TokenMod, SmartAoE */
on('ready', () =>
{
// Make sure libTokenMarkers exists, has the functions that are expected, and has a constant for testing
if('undefined' === typeof libTokenMarkers ||
(['getStatus', 'getStatuses', 'getOrderedList'].find(k =>
!libTokenMarkers.hasOwnProperty(k) || 'function' !== typeof libTokenMarkers[k]
))
)
{
// notify of the missing library
sendChat('', `/w gm <div style="color:red;font-weight:bold;border:2px solid red;background-color:black;border-radius:1em;padding:1em;">Missing dependency: libTokenMarkers.<br>You can install this on your Mod Page with One-Click install.</div>`);
return;
}
// Checks for the existence of a given marker. Used for determining whether to create marketplace buttons
const markerExists = (marker) =>
{
if(!marker || !marker.length) return false;
const match = /(@\d+$|:)/.exec(marker);
const endIndex = match ? match.index : marker.length;
const key = marker.slice(0, endIndex);
const status = libTokenMarkers.getStatus(key);
return status.getName() === marker;
};
let definitions2014 = [
["concentrating", "Some Spells require you to maintain Concentration in order to keep their magic active. If you lose concentration, such a spell ends.<BR>If a spell must be maintained with Concentration, that fact appears in its Duration entry, and the spell specifies how long you can concentrate on it. You can end Concentration at any time (no Action required).<BR>Normal activity, such as moving and Attacking, doesn’t interfere with Concentration. The following factors can break concentration:<BR>• Casting another spell that requires Concentration. You lose concentration on a spell if you cast another spell that requires concentration. You can’t concentrate on two Spells at once.<BR>• Taking Damage. Whenever you take damage while you are concentrating on a spell, you must make a Constitution saving throw to maintain your Concentration. The DC equals 10 or half the damage you take, whichever number is higher. If you take damage from multiple sources, such as an arrow and a dragon’s breath, you make a separate saving throw for each source of damage.<BR>• Being Incapacitated or killed. You lose Concentration on a spell if you are incapacitated or if you die.<BR>• The DM might also decide that certain environmental phenomena, such as a wave Crashing over you while you’re on a storm-tossed ship, require you to succeed on a DC 10 Constitution saving throw to maintain Concentration on a spell."],
["blinded", "• A blinded creature can’t see and automatically fails any ability check that requires sight.<BR>• Attack rolls against the creature have advantage, and the creature’s attack rolls have disadvantage."],
["charmed", "A charmed creature can’t attack the charmer or target the charmer with harmful bilities or magical Effects.<BR>The charmer has advantage on any ability check to interact socially with the creature."],
["deafened", "A deafened creature can’t hear and automatically fails any ability check that requires hearing."],
["exhaustion", "Some special ablities and environmental hazards, such as starvation and the long-term effects of freezing or scorching temperatures, can lead to a spcial condition called exhaustion. Exhaustion is measured in six levels. An Effect can give a creature one or more levels of exhaustion, as specified in the effect’s description.<BR><BR><table><thead><tr><th>Lvl </th><th>Effect</th></tr></thead><tbody><tr><td>1</td><td>Disadvantage on Ability Checks</td></tr><tr><td>2</td><td>Speed halved</td></tr><tr><td>3</td><td>Disadvantage on attack rolls and Saving Throws<br></td></tr><tr><td>4</td><td>Hit point maximum halved</td></tr><tr><td>5</td><td>Speed reduced to 0</td></tr><tr><td>6</td><td>Death</td></tr></tbody></table><BR>If an already exhausted creature suffers another effect that causes exhaustion, its current level of exhaustion increases by the amount specified in the effect’s description.<BR><BR>A creature suffers the effect of its current level of exhaustion as well as all lower levels. For example, a creature suffering level 2 exhaustion has its speed halved and has disadvantage on Ability Checks.<BR><BR>An Effect that removes exhaustion reduces its level as specified in the effect’s description, with all exhaustion Effects Ending if a creature’s exhaustion level is reduced below 1.<BR><BR>Finishing a Long Rest reduces a creature’s exhaustion level by 1, provided that the creature has also ingested some food and drink. Also, being raised from the dead reduces a creature's exhaustion level by 1."],
["frightened", "A frightened creature has disadvantage on Ability Checks and attack rolls while the source of its fear is within Line of Sight.<BR>The creature can’t willingly move closer to the source of its fear."],
["grappled", "A grappled creature’s speed becomes 0, and it can’t benefit from any bonus to its speed.<BR>The condition ends if the grappler is <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>incapacitated</a>.<BR>The condition also ends if an Effect removes the grappled creature from the reach of the Grappler or Grappling Effect, such as when a creature is hurled away by the thunderwave spell."],
["incapacitated", "An incapacitated creature can’t take actions or reactions."],
["invisible", "An invisible creature is impossible to see without the aid of magic or a spcial sense. For the purpose of hiding, the creature is heavily obscured. The creature’s location can be detected by any noise it makes or any tracks it leaves.<BR>Attack rolls against the creature have disadvantage, and the creature’s Attack rolls have advantage."],
["paralyzed", "A paralyzed creature is <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>incapacitated</a> and can’t move or speak.<BR>The creature automatically fails Strength and Dexterity Saving Throws.<BR>Attack rolls against the creature have advantage.<BR>Any Attack that hits the creature is a critical hit if the attacker is within 5 feet of the creature."],
["petrified", "A petrified creature is transformed, along with any nonmagical object it is wearing or carrying, into a solid inanimate substance (usually stone). Its weight increases by a factor of ten, and it ceases aging.<BR>The creature is <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>incapacitated</a>, can’t move or speak, and is unaware of its surroundings.<BR>Attack rolls against the creature have advantage.<BR>The creature automatically fails Strength and Dexterity Saving Throws.<BR>The creature has Resistance to all damage.<BR>The creature is immune to poison and disease, although a poison or disease already in its system is suspended, not neutralized."],
["poisoned", "A poisoned creature has disadvantage on attack rolls and Ability Checks."],
["prone", "A prone creature’s only Movement option is to crawl, unless it stands up and thereby ends the condition.<BR>The creature has disadvantage on attack rolls. <BR>An attack roll against the creature has advantage<BR>if the attacker is within 5 feet of the creature.Otherwise, the attack roll has disadvantage."],
["restrained", "A restrained creature’s speed becomes 0, and it can’t benefit from any bonus to its speed.<BR>Attack rolls against the creature have advantage, and the creature’s Attack rolls have disadvantage.<BR>The creature has disadvantage on Dexterity Saving Throws."],
["stunned", "A stunned creature is <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>incapacitated</a>, can’t move, and can speak only falteringly.<BR>The creature automatically fails Strength and Dexterity Saving Throws.<BR>Attack rolls against the creature have advantage."],
["unconscious", "An unconscious creature is <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>incapacitated</a>, can’t move or speak, and is unaware of its surroundings<BR>The creature drops whatever it’s holding and falls prone.<BR>The creature automatically fails Strength and Dexterity Saving Throws.<BR>Attack rolls against the creature have advantage.<BR>Any Attack that hits the creature is a critical hit if the attacker is within 5 feet of the creature."],
["dead", "A dead creature is an object.<BR>Most GMs have a monster die the instant it drops to 0 Hit Points, rather than having it fall Unconscious and make death Saving Throws.<BR>Mighty Villains and Special nonplayer Characters are Common exceptions; the GM might have them fall Unconscious and follow the same rules as player Characters."],
["bardic-inspiration", "Once within the next 10 minutes, the creature can roll the die and add the number rolled to one ability check, Attack roll, or saving throw it makes. The creature can wait until after it rolls The D20 before deciding to use the Bardic Inspiration die, but must decide before the DM says whether the roll succeeds or fails."],
["bloodied", "Bloodied is not an official term, but usually determines the effectiveness of a Swarm. It is the point at which a creature reaches half their full hit points. The DM may reveal this to the players as an indicator of how strong the monster currently is."],
["confused", "Not a true condition, but can represent the effect of the confusion spell.<BR>An affected target can’t take reactions and must roll a d10 at the start of each of its turns to determine its behavior for that turn.<BR>d10 Behavior<BR>1 The creature uses all its Movement to move in a random direction. To determine the direction, roll a d8 and assign a direction to each die face. The creature doesn't take an Action this turn.<BR>2-6 The creature doesn't move or take ACTIONS this turn.<BR>7-8 The creature uses its Action to make a melee Attack against a randomly determined creature within its reach. If there is no creature within its reach, the creature does nothing this turn.<BR>9-10 The creature can act and move normally."],
["full-cover", "A target with total cover can’t be targeted directly by an Attack or a spell, although some Spells can reach such a target by including it in an area of Effect. A target has total cover if it is completely concealed by an obstacle.<BR><BR>Walls, trees, Creatures, and other Obstacles can provide cover during Combat, making a target more difficult to harm. A target can benefit from cover only when an Attack or other Effect originates on the opposite side of the cover.<BR>There are three degrees of cover. If a target is behind multiple sources of cover, only the most protective degree of cover applies; the degrees aren’t added together. For example, if a target is behind a creature that gives half cover and a tree trunk that gives three-quarters cover, the target has three-quarters cover."],
["three-quarter-cover", "A target with three-quarters cover has a +5 bonus to AC and Dexterity Saving Throws. A target has three-quarters cover if about three-quarters of it is covered by an obstacle. The obstacle might be a portcullis, an arrow slit, or a thick tree trunk.<BR><BR>Walls, trees, Creatures, and other Obstacles can provide cover during Combat, making a target more difficult to harm. A target can benefit from cover only when an Attack or other Effect originates on the opposite side of the cover.<BR>There are three degrees of cover. If a target is behind multiple sources of cover, only the most protective degree of cover applies; the degrees aren’t added together. For example, if a target is behind a creature that gives half cover and a tree trunk that gives three-quarters cover, the target has three-quarters cover."],
["half-cover", "A target with half cover has a +2 bonus to AC and Dexterity Saving Throws. A target has half cover if an obstacle blocks at least half of its body. The obstacle might be a low wall, a large piece of furniture, a narrow tree trunk, or a creature, whether that creature is an enemy or a friend.<BR><BR>Walls, trees, Creatures, and other Obstacles can provide cover during Combat, making a target more difficult to harm. A target can benefit from cover only when an Attack or other Effect originates on the opposite side of the cover.<BR>There are three degrees of cover. If a target is behind multiple sources of cover, only the most protective degree of cover applies; the degrees aren’t added together. For example, if a target is behind a creature that gives half cover and a tree trunk that gives three-quarters cover, the target has three-quarters cover."],
["diseased", "See the entry on <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='https://app.roll20.net/compendium/dnd5e/Rules%3ADiseases?sharedCompendium=4665985#toc_1'>Diseases</a> in the Compendium"],
["ethereal", "Border Ethereal<BR>From the Border Ethereal, a Traveler can see into whatever plane it overlaps, but that plane appears muted and indistinct, its colors blurring into each other and its edges turning fuzzy. Ethereal denizens watch the plane as though peering through distorted and frosted glass, and can’t see anything beyond 30 feet into the other plane. Conversely, the Ethereal Plane is usually Invisible to those on the overlapped planes, except with the aid of magic.<BR>Normally, Creatures in the Border Ethereal can’t Attack Creatures on the overlapped plane, and vice versa. A Traveler on the Ethereal Plane is Invisible and utterly silent to someone on the overlapped plane, and solid Objects on the overlapped plane don’t hamper the Movement of a creature in the Border Ethereal. The exceptions are certain Magical Effects (including anything made of Magical force) and living beings. This makes the Ethereal Plane ideal for reconnaissance, spying on opponents, and moving around without being detected. The Ethereal Plane also disobeys the laws of gravity; a creature there can move up and down as easily as walking."],
["flying", "Flying Creatures enjoy many benefits of mobility, but they must also deal with the danger of Falling. If a flying creature is knocked prone, has its speed reduced to 0, or is otherwise deprived of the ability to move, the creature falls, unless it has the ability to hover or it is being held aloft by magic, such as by the fly spell."],
["haste", "The target’s speed is doubled, it gains a +2 bonus to AC, it has advantage on Dexterity Saving Throws, and it gains an additional Action on each of its turns. That Action can be used only to take the Attack (one weapon attack only), Dash, Disengage, Hide, or Use an Object Action.<BR>When the spell ends, the target can’t move or take actions until after its next turn, as a wave of lethargy sweeps over it."],
["hexed", "Until the spell ends, you deal an extra 1d6 necrotic damage to the target whenever you hit it with an Attack. Also, choose one ability when you cast the spell. The target has disadvantage on Ability Checks made with the chosen ability.<BR>If the target drops to 0 Hit Points before this spell ends, you can use a bonus Action on a subsequent turn of yours to curse a new creature.<BR>A Remove Curse cast on the target ends this spell early."],
["hexblade-curse", "As a Bonus Action, choose one creature you can see within 30 feet of you. The target is Cursed for 1 minute. The curse ends early if the target dies, you die, or you are Incapacitated. Until the curse ends, you gain the following benefits:<BR>You gain a bonus to Damage Rolls against the Cursed target. The bonus equals your Proficiency Bonus.<BR>Any Attack roll you make against the Cursed target is a critical hit on a roll of 19 or 20 on The D20.<BR>If the Cursed target dies, you regain Hit Points equal to your Warlock level + your Charisma modifier (minimum of 1 hit point).<BR>You can’t use this feature again until you finish a short or Long Rest."],
["hidden", "Combatants often try to Escape their foes’ notice by Hiding, casting the Invisibility spell, or lurking in darkness.<BR>When you Attack a target that you can’t see, you have disadvantage on the attack roll. This is true whether you’re guessing the target’s Location or you’re targeting a creature you can hear but not see. If the target isn’t in the Location you targeted, you automatically miss, but the DM typically just says that the attack missed, not whether you guessed the target’s Location correctl<BR>When a creature can’t see you, you have advantage on Attack rolls against it. If you are hidden—both unseen and unheard—when you make an attack, you give away your Location when the attack hits or misses."],
["TempHP", "Temporary Hit Points aren’t actual hit points; they are a buffer against damage, a pool of Hit Points that protect you from injury.<BR>When you have temporary Hit Points and take damage, the temporary Hit Points are lost first, and any leftover damage carries over to your normal Hit Points. For example, if you have 5 temporary Hit Points and take 7 damage, you lose the temporary Hit Points and then take 2 damage.<BR>Because temporary Hit Points are separate from your actual Hit Points, they can exceed your hit point maximum. A character can, therefore, be at full Hit Points and receive temporary Hit Points.<BR>Healing can’t restore temporary Hit Points, and they can’t be added together. If you have temporary Hit Points and receive more of them, you decide whether to keep the ones you have or to gain the new ones. For example, if a spell grants you 12 temporary Hit Points when you already have 10, you can have 12 or 10, not 22.<BR>If you have 0 Hit Points, receiving temporary Hit Points doesn’t restore you to consciousness or stabilize you. They can still absorb damage directed at you while you’re in that state, but only true Healing can save you.<BR>Unless a feature that grants you temporary Hit Points has a Duration, they last until they’re depleted or you finish a Long Rest."],
["favored", "Concentration.<BR>The first time on each of your turns that you hit the Favored enemy and deal damage to it, including when you mark it, you can increase that damage by 1d4.<BR>You can use this feature to mark a Favored enemy a number of times equal to your Proficiency bonus, and you regain all expended uses when you finish a Long Rest.<BR>This feature's extra damage increases when you reach certain levels in this class: to 1d6 at 6th Level and to 1d8 at 14th level."],
["marked", "You deal an extra 1d6 damage to the target whenever you hit it with a weapon Attack, and you have advantage on any Wisdom (Perception) or Wisdom (Survival) check you make to find it. If the target drops to 0 Hit Points before this spell ends, you can use a bonus Action on a subsequent turn of yours to mark a new creature<BR><b>At Higher Levels.</b> When you cast this spell using a spell slot of 3rd or 4th Level, you can maintain your Concentration on the spell for up to 8 hours. When you use a spell slot of 5th Level or higher, you can maintain your concentration on the spell for up to 24 hours."],
["raging", "While raging, you gain the following benefits if you aren’t wearing heavy armor:<BR>• You have advantage on Strength checks and Strength Saving Throws.<BR>• When you make a melee weapon Attack using Strength, you gain a bonus to the damage roll that increases as you gain levels as a Barbarian, as shown in the Rage Damage column of the Barbarian table.<BR• You have Resistance to bludgeoning, piercing, and slashing damage.<BR>If you are able to cast Spells, you can’t cast them or concentrate on them while raging.<BR>Your rage lasts for 1 minute. It ends early if you are knocked Unconscious or if Your Turn ends and you haven’t attacked a Hostile creature since your last turn or taken damage since then. You can also end your rage on Your Turn as a bonus Action.<BR>Once you have raged the number of times shown for your Barbarian level in the Rages column of the Barbarian table, you must finish a Long Rest before you can rage again."],
["slowed", "An affected target’s speed is halved, it takes a −2 penalty to AC and Dexterity Saving Throws, and it can’t use reactions. On its turn, it can use either an Action or a bonus Action, not both. Regardless of the creature’s Abilities or magic items, it can’t make more than one melee or ranged Attack during its turn.<BR>If the creature attempts to Cast a Spell with a Casting Time of 1 Action, roll a d20. On an 11 or higher, the spell doesn’t take Effect until the creature’s next turn, and the creature must use its Action on that turn to complete the spell. If it can’t, the spell is wasted.<BR>A creature affected by this spell makes another Wisdom saving throw at the end of each of its turns. On a successful save, the Effect ends for it."],
["Torch", "A torch burns for 1 hour, providing bright light in a 20-foot radius and dim light for an additional 20 feet. If you make a melee Attack with a burning torch and hit, it deals 1 fire damage."],
["dying", "<b>Falling Unconscious</b><BR>If damage reduces you to 0 Hit Points and fails to kill you, you fall Unconscious (see Conditions ). This unconsciousness ends if you regain any Hit Points.<BR><b>Death Saving Throws</b><BR>Whenever you start Your Turn with 0 Hit Points, you must make a Special saving throw, called a death saving throw, to determine whether you creep closer to death or hang onto life. Unlike other Saving Throws, this one isn’t tied to any ability score. You are in the hands of fate now, aided only by Spells and Features that improve your chances of succeeding on a saving throw.<BR>Roll a d20: If the roll is 10 or higher, you succeed. Otherwise, you fail. A success or failure has no Effect by itself. On your third success, you become stable (see below). On your third failure, you die. The successes and failures don’t need to be consecutive; keep track of both until you collect three of a kind. The number of both is reset to zero when you regain any Hit Points or become stable.<BR>Rolling 1 or 20: When you make a death saving throw and roll a 1 on The D20, it counts as two failures. If you roll a 20 on The D20, you regain 1 hit point.<BR>Damage at 0 Hit Points: If you take any damage while you have 0 Hit Points, you suffer a death saving throw failure. If the damage is from a critical hit, you suffer two failures instead. If the damage equals or exceeds your hit point maximum, you suffer Instant Death."],
["burrowing", "A monster that has a burrowing speed can use that speed to move through sand, earth, mud, or ice. A monster can’t burrow through solid rock unless it has a Special trait that allows it to do so."],
["dodging", "Until the start of your next turn, any Attack roll made against you has disadvantage if you can see the attacker, and you make Dexterity Saving Throws with advantage. You lose this benefit if you are Incapacitated or if your speed drops to 0."],
["inspiration", "If you have Inspiration, you can expend it when you make an Attack roll, saving throw, or ability check. Spending your Inspiration gives you advantage on that roll.<BR>Additionally, if you have Inspiration, you can reward another player for good Roleplaying, clever thinking, or simply doing something exciting in the game. When another player character does something that really contributes to the story in a fun and interesting way, you can give up your Inspiration to give that character Inspiration."],
["TemporaryHP", "Temporary Hit Points aren’t actual hit points; they are a buffer against damage, a pool of Hit Points that protect you from injury.<BR>When you have temporary Hit Points and take damage, the temporary Hit Points are lost first, and any leftover damage carries over to your normal Hit Points. For example, if you have 5 temporary Hit Points and take 7 damage, you lose the temporary Hit Points and then take 2 damage.<BR>Because temporary Hit Points are separate from your actual Hit Points, they can exceed your hit point maximum. A character can, therefore, be at full Hit Points and receive temporary Hit Points.<BR>Healing can’t restore temporary Hit Points, and they can’t be added together. If you have temporary Hit Points and receive more of them, you decide whether to keep the ones you have or to gain the new ones. For example, if a spell grants you 12 temporary Hit Points when you already have 10, you can have 12 or 10, not 22.<BR>If you have 0 Hit Points, receiving temporary Hit Points doesn’t restore you to consciousness or stabilize you. They can still absorb damage directed at you while you’re in that state, but only true Healing can save you.<BR>Unless a feature that grants you temporary Hit Points has a Duration, they last until they’re depleted or you finish a Long Rest."]
];
let definitions2024 = [
["concentrating", "Some spells and other effects require Concentration to remain active, as specified in their descriptions. If the effect’s creator loses Concentration, the effect ends. If the effect has a maximum duration, the effect’s description specifies how long the creator can concentrate on it: up to 1 minute, 1 hour, or some other duration. The creator can end Concentration at any time (no action required). The following factors break Concentration.<br>Another Concentration Effect. You lose Concentration on an effect the moment you start casting a spell that requires Concentration or activate another effect that requires Concentration.<br>Damage. If you take damage, you must succeed on a Constitution saving throw to maintain Concentration. The DC equals 10 or half the damage taken (round down), whichever number is higher, up to a maximum DC of 30.<br>Incapacitated or Dead. Your Concentration ends if you have the Incapacitated condition or you die."],
["blinded", "While you have the Blinded condition, you experience the following effects.<BR><b>Can’t See.</b> You can’t see and automatically fail any ability check that requires sight.<BR><b>Attacks Affected.</b> Attack rolls against you have Advantage, and your attack rolls have Disadvantage."],
["charmed", "While you have the Charmed condition, you experience the following effects.<BR><BR><b>Can’t Harm the Charmer.</b> You can’t attack the charmer or target the charmer with damaging abilities or magical effects.<BR><BR><b>Social Advantage.</b> The charmer has Advantage on any ability check to interact with you socially."],
["deafened", "While you have the Deafened condition, you experience the following effect.<BR><BR><b>Can’t Hear.</b> You can’t hear and automatically fail any ability check that requires hearing."],
["exhaustion", "While you have the Exhaustion condition, you experience the following effects.<BR><BR><b>Exhaustion Levels.</b> This condition is cumulative. Each time you receive it, you gain 1 Exhaustion level. You die if your Exhaustion level is 6.<BR><BR><b>D20 Tests Affected.</b> When you make a D20 Test, the roll is reduced by 2 times your Exhaustion level.<BR><BR><b>Speed Reduced.</b> Your Speed is reduced by a number of feet equal to 5 times your Exhaustion level.<BR><BR><b>Removing Exhaustion Levels.</b> Finishing a Long Rest removes 1 of your Exhaustion levels. When your Exhaustion level reaches 0, the condition ends."],
["frightened", "While you have the Frightened condition, you experience the following effects.<BR><BR><b>Ability Checks and Attacks Affected.</b> You have Disadvantage on ability checks and attack rolls while the source of fear is within line of sight.<BR><BR><b>Can’t Approach.</b> You can’t willingly move closer to the source of fear."],
["grappled", "While you have the Grappled condition, you experience the following effects.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Attacks Affected.</b> You have Disadvantage on attack rolls against any target other than the grappler.<BR><BR><b>Movable.</b> The grappler can drag or carry you when it moves, but every foot of movement costs it 1 extra foot unless you are Tiny or two or more sizes smaller than it."],
["incapacitated", "While you have the Incapacitated condition, you experience the following effects.<BR><BR><b>Inactive.</b> You can’t take any action, Bonus Action, or Reaction.<BR><BR><b>No Concentration.</b> Your Concentration is broken.<BR><BR><b>Speechless.</b> You can’t speak.<BR><BR><b>Surprised.</b> If you’re Incapacitated when you roll Initiative, you have Disadvantage on the roll."],
["invisible", "While you have the Invisible condition, you experience the following effects.<BR><BR><b>Surprise.</b> If you’re Invisible when you roll Initiative, you have Advantage on the roll.<BR><BR><b>Concealed.</b> You aren’t affected by any effect that requires its target to be seen unless the effect’s creator can somehow see you. Any equipment you are wearing or carrying is also concealed.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Disadvantage, and your attack rolls have Advantage. If a creature can somehow see you, you don’t gain this benefit against that creature."],
["paralyzed", "While you have the Paralyzed condition, you experience the following effects.<BR><BR><b>Incapacitated.</b> You have the <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>Incapacitated</a> condition.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Saving Throws Affected.</b> You automatically fail Strength and Dexterity saving throws.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage.<BR><BR><b>Automatic Critical Hits.</b> Any attack roll that hits you is a Critical Hit if the attacker is within 5 feet of you."],
["petrified", "While you have the Petrified condition, you experience the following effects.<BR><BR><b>Turned to Inanimate Substance.</b> You are transformed, along with any nonmagical objects you are wearing and carrying, into a solid inanimate substance (usually stone). Your weight increases by a factor of ten, and you cease aging.<BR><BR><b>Incapacitated.</b> You have the <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>Incapacitated</a> condition.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage.<BR><BR><b>Saving Throws Affected.</b> You automatically fail Strength and Dexterity saving throws.<BR><BR><b>Resist Damage.</b> You have Resistance to all damage.<BR><BR><b>Poison Immunity.</b> You have Immunity to the Poisoned condition."],
["poisoned", "While you have the Poisoned condition, you experience the following effect.<BR><BR><b>Ability Checks and Attacks Affected.</b> You have Disadvantage on attack rolls and ability checks."],
["prone", "While you have the Prone condition, you experience the following effects.<BR><BR><b>Restricted Movement.</b> Your only movement options are to crawl or to spend an amount of movement equal to half your Speed (round down) to right yourself and thereby end the condition. If your Speed is 0, you can’t right yourself.<BR><BR><b>Attacks Affected.</b> You have Disadvantage on attack rolls. An attack roll against you has Advantage if the attacker is within 5 feet of you. Otherwise, that attack roll has Disadvantage."],
["restrained", "While you have the Restrained condition, you experience the following effects.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage, and your attack rolls have Disadvantage.<BR><BR><b>Saving Throws Affected.</b> You have Disadvantage on Dexterity saving throws."],
["stunned", "While you have the Stunned condition, you experience the following effects.<BR><BR><b>Incapacitated.</b> You have the <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>Incapacitated</a> condition.<BR><BR><b>Saving Throws Affected.</b> You automatically fail Strength and Dexterity saving throws.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage."],
["unconscious", "While you have the Unconscious condition, you experience the following effects.<BR><BR><b>Inert.</b> You have the <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>Incapacitated</a> and <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef prone'>Prone</a> conditions, and you drop whatever you’re holding. When this condition ends, you remain Prone.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage.<BR><BR><b>Saving Throws Affected.</b> You automatically fail Strength and Dexterity saving throws.<BR><BR><b>Automatic Critical Hits.</b> Any attack roll that hits you is a Critical Hit if the attacker is within 5 feet of you.<BR><BR><b>Unaware.</b> You’re unaware of your surroundings."],
["dead", "A dead creature has no Hit Points and can’t regain them unless it is first revived by magic such as the Raise Dead or Revivify spell. When such a spell is cast, the spirit knows who is casting it and can refuse. The spirit of a dead creature has left the body and departed for the Outer Planes, and reviving the creature requires calling the spirit back.<BR>If the creature returns to life, the revival effect determines the creature’s current Hit Points. Unless otherwise stated, the creature returns to life with any conditions, magical contagions, or curses that were affecting it at death if the durations of those effects are still ongoing. If the creature died with any Exhaustion levels, it returns with 1 fewer level. If the creature had Attunement to one or more magic items, it is no longer attuned to them."],
["bardic-inspiration", "Once within the next 10 minutes, the creature can roll the die and add the number rolled to one ability check, Attack roll, or saving throw it makes. The creature can wait until after it rolls The D20 before deciding to use the Bardic Inspiration die, but must decide before the DM says whether the roll succeeds or fails."],
["bloodied", "A creature is Bloodied while it has half its Hit Points or fewer remaining. Usually determines the effectiveness of a Swarm. It is the point at which a creature reaches half their full hit points. The DM may reveal this to the players as an indicator of how strong the monster currently is."],
["confused", "Not a true condition, but can represent the effect of the confusion spell.<BR>An affected target can’t take reactions and must roll 1d10 at the start of each of its turns to determine its behavior for that turn, consulting the table below.<BR>1d10 - Behavior for the Turn<BR>1 - The target doesn't take an action, and it uses all its movement to move. Roll 1d4 for the direction: 1, north; 2, east; 3, south; or 4, west. <BR>2-6 - The target doesn't move or take actions. <BR>7-8 - The target doesn't move, and it takes the Attack action to make one melee attack against a random creature within reach. If none are within reach, the target takes no action.<BR>9-10 - The target chooses its behavior. At the end of each of its turns, an affected target repeats the save, ending the spell on itself on a success."],
["full-cover", "Cover provides a degree of protection to a target behind it. There are three degrees of cover, each of which provides a different benefit to a target: Half Cover (+2 bonus to AC and Dexterity saving throws), Three-Quarters Cover (+5 bonus to AC and Dexterity saving throws), and Total Cover (can’t be targeted directly). If behind more than one degree of cover, a target benefits only from the most protective degree."],
["three-quarter-cover", "Cover provides a degree of protection to a target behind it. There are three degrees of cover, each of which provides a different benefit to a target: Half Cover (+2 bonus to AC and Dexterity saving throws), Three-Quarters Cover (+5 bonus to AC and Dexterity saving throws), and Total Cover (can’t be targeted directly). If behind more than one degree of cover, a target benefits only from the most protective degree."],
["half-cover", "Cover provides a degree of protection to a target behind it. There are three degrees of cover, each of which provides a different benefit to a target: Half Cover (+2 bonus to AC and Dexterity saving throws), Three-Quarters Cover (+5 bonus to AC and Dexterity saving throws), and Total Cover (can’t be targeted directly). If behind more than one degree of cover, a target benefits only from the most protective degree."],
["diseased", "See the entry on <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='https://app.roll20.net/compendium/dnd5e/Rules%3ADiseases?sharedCompendium=4665985#toc_1'>Diseases</a> in the Compendium"],
["ethereal", "Border Ethereal<BR>From the Border Ethereal, a traveler can see into whatever plane it overlaps, but that plane appears grayish and indistinct, its colors blurring into each other and its edges turning fuzzy, limiting visibility to 30 feet into the other plane. Conversely, the Ethereal Plane is usually imperceptible to those on the overlapped planes, except with the aid of magic.<BR>Normally, creatures in the Border Ethereal can’t attack creatures on the overlapped plane, and vice versa. A traveler on the Ethereal Plane is imperceptible to someone on the overlapped plane, and solid objects on the overlapped plane don’t hamper the movement of a creature in the Border Ethereal. The exceptions are certain magical effects (including anything made of magical force) and living beings. This makes the Ethereal Plane ideal for scouting, spying on opponents, and moving around without being detected. The Ethereal Plane also disobeys the laws of gravity; a creature there can freely move in any direction.<BR>Deep Ethereal<BR>To reach the Deep Ethereal, one typically needs a Plane Shift spell, a Gate spell, or a magical portal. Visitors to the Deep Ethereal are engulfed by roiling mist. Scattered throughout the plane are curtains of vaporous color, and passing through a curtain leads a traveler to a region of the Border Ethereal connected to a specific Inner Plane, the Material Plane, the Feywild, or the Shadowfell. The color of the curtain indicates the plane whose Border Ethereal the curtain conceals; see the Ethereal Curtains table. The curtains are also distinguishable by texture and temperature, each one reflecting something of the nature of the plane beyond."],
["flying", "A variety of effects allow a creature to fly. While flying, you fall if you have the Incapacitated or Prone condition or your Fly Speed is reduced to 0. You can stay aloft in those circumstances if you can hover."],
["haste", "The target’s speed is doubled, it gains a +2 bonus to AC, it has advantage on Dexterity Saving Throws, and it gains an additional Action on each of its turns. That Action can be used only to take the Attack (one weapon attack only), Dash, Disengage, Hide, or Use an Object Action.<BR>When the spell ends, the target can’t move or take actions until after its next turn, as a wave of lethargy sweeps over it."],
["hexed", "You place a curse on a creature that you can see within range. Until the spell ends, you deal an extra 1d6 Necrotic damage to the target whenever you hit it with an attack roll. Also, choose one ability when you cast the spell. The target has Disadvantage on ability checks made with the chosen ability.<BR>If the target drops to 0 Hit Points before this spell ends, you can take a Bonus Action on a later turn to curse a new creature."],
["hexblade-curse", "As a Bonus Action, choose one creature you can see within 30 feet of you. The target is Cursed for 1 minute. The curse ends early if the target dies, you die, or you are Incapacitated. Until the curse ends, you gain the following benefits:<BR>You gain a bonus to Damage Rolls against the Cursed target. The bonus equals your Proficiency Bonus.<BR>Any Attack roll you make against the Cursed target is a critical hit on a roll of 19 or 20 on The D20.<BR>If the Cursed target dies, you regain Hit Points equal to your Warlock level + your Charisma modifier (minimum of 1 hit point).<BR>You can’t use this feature again until you finish a short or Long Rest."],
["hidden", "With the Hide action, you try to conceal yourself. To do so, you must succeed on a DC 15 Dexterity (Stealth) check while you’re Heavily Obscured or behind Three-Quarters Cover or Total Cover, and you must be out of any enemy’s line of sight; if you can see a creature, you can discern whether it can see you.<BR>On a successful check, you have the Invisible condition. Make note of your check’s total, which is the DC for a creature to find you with a Wisdom (Perception) check.<BR>The condition ends on you immediately after any of the following occurs: you make a sound louder than a whisper, an enemy finds you, you make an attack roll, or you cast a spell with a Verbal component."],
["TempHP", "Temporary Hit Points aren’t actual hit points; they are a buffer against damage, a pool of Hit Points that protect you from injury.<BR>When you have temporary Hit Points and take damage, the temporary Hit Points are lost first, and any leftover damage carries over to your normal Hit Points. For example, if you have 5 temporary Hit Points and take 7 damage, you lose the temporary Hit Points and then take 2 damage.<BR>Because temporary Hit Points are separate from your actual Hit Points, they can exceed your hit point maximum. A character can, therefore, be at full Hit Points and receive temporary Hit Points.<BR>Healing can’t restore temporary Hit Points, and they can’t be added together. If you have temporary Hit Points and receive more of them, you decide whether to keep the ones you have or to gain the new ones. For example, if a spell grants you 12 temporary Hit Points when you already have 10, you can have 12 or 10, not 22.<BR>If you have 0 Hit Points, receiving temporary Hit Points doesn’t restore you to consciousness or stabilize you. They can still absorb damage directed at you while you’re in that state, but only true Healing can save you.<BR>Unless a feature that grants you temporary Hit Points has a Duration, they last until they’re depleted or you finish a Long Rest."],
["favored", "Concentration.<BR>The first time on each of your turns that you hit the Favored enemy and deal damage to it, including when you mark it, you can increase that damage by 1d4.<BR>You can use this feature to mark a Favored enemy a number of times equal to your Proficiency bonus, and you regain all expended uses when you finish a Long Rest.<BR>This feature's extra damage increases when you reach certain levels in this class: to 1d6 at 6th Level and to 1d8 at 14th level."],
["marked", "You magically mark one creature you can see within range as your quarry. Until the spell ends, you deal an extra 1d6 Force damage to the target whenever you hit it with an attack roll. You also have Advantage on any Wisdom (Perception or Survival) check you make to find it.<BR>If the target drops to 0 Hit Points before this spell ends, you can take a Bonus Action to move the mark to a new creature you can see within range.<BR>Using a Higher-Level Spell Slot. Your Concentration can last longer with a spell slot of level 3–4 (up to 8 hours) or 5+ (up to 24 hours)."],
["raging", "While active, your Rage follows the rules below.<BR>Damage Resistance. You have Resistance to Bludgeoning, Piercing, and Slashing damage.<BR>Rage Damage. When you make an attack using Strength—with either a weapon or an Unarmed Strike—and deal damage to the target, you gain a bonus to the damage that increases as you gain levels as a Barbarian, as shown in the Rage Damage column of the Barbarian Features table.<BR>Strength Advantage. You have Advantage on Strength checks and Strength saving throws.<BR>No Concentration or Spells. You can’t maintain Concentration, and you can’t cast spells.<BR>Duration. The Rage lasts until the end of your next turn, and it ends early if you don Heavy armor or have the Incapacitated condition. If your Rage is still active on your next turn, you can extend the Rage for another round by doing one of the following:<BR>Make an attack roll against an enemy.<BR>Force an enemy to make a saving throw.<BR>Take a Bonus Action to extend your Rage."],
["slowed", "Each target must succeed on a Wisdom saving throw or be affected by this spell for the duration.<BR>An affected target’s Speed is halved, it takes a −2 penalty to AC and Dexterity saving throws, and it can’t take Reactions. On its turns, it can take either an action or a Bonus Action, not both, and it can make only one attack if it takes the Attack action. If it casts a spell with a Somatic component, there is a 25 percent chance the spell fails as a result of the target making the spell’s gestures too slowly.<BR>An affected target repeats the save at the end of each of its turns, ending the spell on itself on a success."],
["Torch", "A Torch burns for 1 hour, casting Bright Light in a 20-foot radius and Dim Light for an additional 20 feet. When you take the Attack action, you can attack with the Torch, using it as a Simple Melee weapon. On a hit, the target takes 1 Fire damage."],
["dying", "When a creature drops to 0 Hit Points, it either dies outright or falls unconscious, as explained below.<BR>Instant Death<BR>Here are the main ways a creature can die instantly.<BR>Monster Death.<BR>A monster dies the instant it drops to 0 Hit Points, although a Dungeon Master can ignore this rule for an individual monster and treat it like a character.<BR>Hit Point Maximum of 0.<BR>A creature dies if its Hit Point maximum reaches 0. Certain effects drain life energy, reducing a creature’s Hit Point maximum.<BR>Massive Damage.<BR>When damage reduces a character to 0 Hit Points and damage remains, the character dies if the remainder equals or exceeds their Hit Point maximum. For example, if your character has a Hit Point maximum of 12, currently has 6 Hit Points, and takes 18 damage, the character drops to 0 Hit Points, but 12 damage remains. The character then dies, since 12 equals their Hit Point maximum.<BR>Character Demise<BR>If your character dies, others might find a magical way to revive your character, such as with the Raise Dead spell. Or talk with the DM about making a new character to join the group.<BR>Falling<BR>Unconscious<BR>If you reach 0 Hit Points and don’t die instantly, you have the Unconscious condition until you regain any Hit Points, and you now face making Death Saving Throws (see below).<BR>Knocking Out a Creature<BR>When you would reduce a creature to 0 Hit Points with a melee attack, you can instead reduce the creature to 1 Hit Point and give it the Unconscious condition. It then starts a Short Rest, at the end of which that condition ends on it. The condition ends early if the creature regains any Hit Points or if someone takes an action to administer first aid to it, making a successful DC 10 Wisdom (Medicine) check.<BR>Death Saving Throws<BR>Whenever you start your turn with 0 Hit Points, you must make a Death Saving Throw to determine whether you creep closer to death or hang on to life. Unlike other saving throws, this one isn’t tied to an ability score. You’re in the hands of fate now.<BR>Three Successes/Failures.<BR>Roll 1d20. If the roll is 10 or higher, you succeed. Otherwise, you fail. A success or failure has no effect by itself. On your third success, you become Stable. On your third failure, you die.<BR>The successes and failures don’t need to be consecutive; keep track of both until you collect three of a kind. The number of both is reset to zero when you regain any Hit Points or become Stable.<BR>Rolling a 1 or 20.<BR>When you roll a 1 on the d20 for a Death Saving Throw, you suffer two failures. If you roll a 20 on the d20, you regain 1 Hit Point.<BR>Damage at 0 Hit Points.<BR>If you take any damage while you have 0 Hit Points, you suffer a Death Saving Throw failure. If the damage is from a Critical Hit, you suffer two failures instead. If the damage equals or exceeds your Hit Point maximum, you die.<BR>Stabilizing a Character<BR>You can take the Help action to try to stabilize a creature with 0 Hit Points, which requires a successful DC 10 Wisdom (Medicine) check.<BR>A Stable creature doesn’t make Death Saving Throws even though it has 0 Hit Points, but it still has the Unconscious condition. If the creature takes damage, it stops being Stable and starts making Death Saving Throws again. A Stable creature that isn’t healed regains 1 Hit Point after 1d4 hours."],
["burrowing", "A creature that has a Burrow Speed can use that speed to move through sand, earth, mud, or ice. The creature can’t burrow through solid rock unless the creature has a trait that allows it to do so. See also “Speed."],
["dodging", "If you take the Dodge action, you gain the following benefits: until the start of your next turn, any attack roll made against you has Disadvantage if you can see the attacker, and you make Dexterity saving throws with Advantage.<BR>You lose these benefits if you have the Incapacitated condition or if your Speed is 0."],
["inspiration", "If you (a player character) have Heroic Inspiration, you can expend it to reroll any die immediately after rolling it, and you must use the new roll.<BR>If you gain Heroic Inspiration but already have it, it’s lost unless you give it to a player character who lacks it."],
["TemporaryHP", "Temporary Hit Points aren’t actual hit points; they are a buffer against damage, a pool of Hit Points that protect you from injury.<BR>When you have temporary Hit Points and take damage, the temporary Hit Points are lost first, and any leftover damage carries over to your normal Hit Points. For example, if you have 5 temporary Hit Points and take 7 damage, you lose the temporary Hit Points and then take 2 damage.<BR>Because temporary Hit Points are separate from your actual Hit Points, they can exceed your hit point maximum. A character can, therefore, be at full Hit Points and receive temporary Hit Points.<BR>Healing can’t restore temporary Hit Points, and they can’t be added together. If you have temporary Hit Points and receive more of them, you decide whether to keep the ones you have or to gain the new ones. For example, if a spell grants you 12 temporary Hit Points when you already have 10, you can have 12 or 10, not 22.<BR>If you have 0 Hit Points, receiving temporary Hit Points doesn’t restore you to consciousness or stabilize you. They can still absorb damage directed at you while you’re in that state, but only true Healing can save you.<BR>Unless a feature that grants you temporary Hit Points has a Duration, they last until they’re depleted or you finish a Long Rest."]
];
let defaultConditionsArray = [
["concentrating",
/concentration check|concentration=1/i,
"Some spells and other effects require Concentration to remain active, as specified in their descriptions. If the effect’s creator loses Concentration, the effect ends. If the effect has a maximum duration, the effect’s description specifies how long the creator can concentrate on it: up to 1 minute, 1 hour, or some other duration. The creator can end Concentration at any time (no action required). The following factors break Concentration.<br>Another Concentration Effect. You lose Concentration on an effect the moment you start casting a spell that requires Concentration or activate another effect that requires Concentration.<br>Damage. If you take damage, you must succeed on a Constitution saving throw to maintain Concentration. The DC equals 10 or half the damage taken (round down), whichever number is higher, up to a maximum DC of 30.<br>Incapacitated or Dead. Your Concentration ends if you have the Incapacitated condition or you die.",
`death-zone`
],
["blinded",
/(be|and|is|magically|become|becomes|is either|has the) blinded|blinded condition/i,
"While you have the Blinded condition, you experience the following effects.<BR><b>Can’t See.</b> You can’t see and automatically fail any ability check that requires sight.<BR><b>Attacks Affected.</b> Attack rolls against you have Advantage, and your attack rolls have Disadvantage.",
`bleeding-eye`
],
[
"charmed",
/(be|and|is|magically|become|becomes) charmed|charmed condition/i,
"While you have the Charmed condition, you experience the following effects.<BR><BR><b>Can’t Harm the Charmer.</b> You can’t attack the charmer or target the charmer with damaging abilities or magical effects.<BR><BR><b>Social Advantage.</b> The charmer has Advantage on any ability check to interact with you socially.",
`chained-heart`
],
[
"deafened",
/(be|and|is|magically|become|becomes) deafened|deafened condition/i,
"While you have the Deafened condition, you experience the following effect.<BR><BR><b>Can’t Hear.</b> You can’t hear and automatically fail any ability check that requires hearing.",
`overdrive`
],
[
"exhaustion",
/(be|and|is|magically|become|becomes) exhausted|(of|magical) exhaustion|exhausted condition/i,
"While you have the Exhaustion condition, you experience the following effects.<BR><BR><b>Exhaustion Levels.</b> This condition is cumulative. Each time you receive it, you gain 1 Exhaustion level. You die if your Exhaustion level is 6.<BR><BR><b>D20 Tests Affected.</b> When you make a D20 Test, the roll is reduced by 2 times your Exhaustion level.<BR><BR><b>Speed Reduced.</b> Your Speed is reduced by a number of feet equal to 5 times your Exhaustion level.<BR><BR><b>Removing Exhaustion Levels.</b> Finishing a Long Rest removes 1 of your Exhaustion levels. When your Exhaustion level reaches 0, the condition ends.",
`half-haze`
],
[
"frightened",
/(be|and|is|magically|become|becomes) frightened|frightened condition/i,
"While you have the Frightened condition, you experience the following effects.<BR><BR><b>Ability Checks and Attacks Affected.</b> You have Disadvantage on ability checks and attack rolls while the source of fear is within line of sight.<BR><BR><b>Can’t Approach.</b> You can’t willingly move closer to the source of fear.",
`screaming`
],
[
"grappled",
/(be|and|is|magically|becomes|considered) grappled|grappled condition/i,
"While you have the Grappled condition, you experience the following effects.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Attacks Affected.</b> You have Disadvantage on attack rolls against any target other than the grappler.<BR><BR><b>Movable.</b> The grappler can drag or carry you when it moves, but every foot of movement costs it 1 extra foot unless you are Tiny or two or more sizes smaller than it.",
`grab`
],
[
"incapacitated",
/(be|and|is|magically|become|becomes) incapacitated|incapacitated condition/i,
"While you have the Incapacitated condition, you experience the following effects.<BR><BR><b>Inactive.</b> You can’t take any action, Bonus Action, or Reaction.<BR><BR><b>No Concentration.</b> Your Concentration is broken.<BR><BR><b>Speechless.</b> You can’t speak.<BR><BR><b>Surprised.</b> If you’re Incapacitated when you roll Initiative, you have Disadvantage on the roll.",
`interdiction`
],
[
"invisible",
/(be|and|is|magically|become|becomes) invisible|invisible condition/i,
"While you have the Invisible condition, you experience the following effects.<BR><BR><b>Surprise.</b> If you’re Invisible when you roll Initiative, you have Advantage on the roll.<BR><BR><b>Concealed.</b> You aren’t affected by any effect that requires its target to be seen unless the effect’s creator can somehow see you. Any equipment you are wearing or carrying is also concealed.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Disadvantage, and your attack rolls have Advantage. If a creature can somehow see you, you don’t gain this benefit against that creature.",
`ninja-mask`
],
[
"paralyzed",
/(be|and|is|magically|become|becomes) paralyzed|paralyzed condition/i,
"While you have the Paralyzed condition, you experience the following effects.<BR><BR><b>Incapacitated.</b> You have the <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>Incapacitated</a> condition.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Saving Throws Affected.</b> You automatically fail Strength and Dexterity saving throws.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage.<BR><BR><b>Automatic Critical Hits.</b> Any attack roll that hits you is a Critical Hit if the attacker is within 5 feet of you.",
`aura`
],
[
"petrified",
/(be|and|is|magically|become|becomes|becoming) petrified|(turns to|turning to) stone|petrified condition/i,
"While you have the Petrified condition, you experience the following effects.<BR><BR><b>Turned to Inanimate Substance.</b> You are transformed, along with any nonmagical objects you are wearing and carrying, into a solid inanimate substance (usually stone). Your weight increases by a factor of ten, and you cease aging.<BR><BR><b>Incapacitated.</b> You have the <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>Incapacitated</a> condition.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage.<BR><BR><b>Saving Throws Affected.</b> You automatically fail Strength and Dexterity saving throws.<BR><BR><b>Resist Damage.</b> You have Resistance to all damage.<BR><BR><b>Poison Immunity.</b> You have Immunity to the Poisoned condition.",
`chemical-bolt`
],
[
"poisoned",
/(be|and|is|magically|become|becomes) poisoned|poisoned condition/i,
"While you have the Poisoned condition, you experience the following effect.<BR><BR><b>Ability Checks and Attacks Affected.</b> You have Disadvantage on attack rolls and ability checks.",
'skull'
],
[
"prone",
/(be|and|is|magically|become|becomes|knocked|fall|falls) prone|prone condition/i,
"While you have the Prone condition, you experience the following effects.<BR><BR><b>Restricted Movement.</b> Your only movement options are to crawl or to spend an amount of movement equal to half your Speed (round down) to right yourself and thereby end the condition. If your Speed is 0, you can’t right yourself.<BR><BR><b>Attacks Affected.</b> You have Disadvantage on attack rolls. An attack roll against you has Advantage if the attacker is within 5 feet of you. Otherwise, that attack roll has Disadvantage.",
`back-pain`
],
[
"restrained",
/(be|and|is|magically|become|becomes) restrained|restrained condition/i,
"While you have the Restrained condition, you experience the following effects.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage, and your attack rolls have Disadvantage.<BR><BR><b>Saving Throws Affected.</b> You have Disadvantage on Dexterity saving throws.",
`cobweb`
],
[
"stunned",
/(be|and|is|magically|become|becomes) stunned|stunned condition/i,
"While you have the Stunned condition, you experience the following effects.<BR><BR><b>Incapacitated.</b> You have the <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>Incapacitated</a> condition.<BR><BR><b>Saving Throws Affected.</b> You automatically fail Strength and Dexterity saving throws.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage.",
`broken-skull`
],
[
"unconscious",
/(be|and|is|magically|become|becomes) unconscious|unconscious condition/i,
"While you have the Unconscious condition, you experience the following effects.<BR><BR><b>Inert.</b> You have the <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>Incapacitated</a> and <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef prone'>Prone</a> conditions, and you drop whatever you’re holding. When this condition ends, you remain Prone.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage.<BR><BR><b>Saving Throws Affected.</b> You automatically fail Strength and Dexterity saving throws.<BR><BR><b>Automatic Critical Hits.</b> Any attack roll that hits you is a Critical Hit if the attacker is within 5 feet of you.<BR><BR><b>Unaware.</b> You’re unaware of your surroundings.",
`sleepy`
],
[
"dead",
/nonmatching string to prevent accidental triggering/i,
"A dead creature has no Hit Points and can’t regain them unless it is first revived by magic such as the Raise Dead or Revivify spell. When such a spell is cast, the spirit knows who is casting it and can refuse. The spirit of a dead creature has left the body and departed for the Outer Planes, and reviving the creature requires calling the spirit back.<BR>If the creature returns to life, the revival effect determines the creature’s current Hit Points. Unless otherwise stated, the creature returns to life with any conditions, magical contagions, or curses that were affecting it at death if the durations of those effects are still ongoing. If the creature died with any Exhaustion levels, it returns with 1 fewer level. If the creature had Attunement to one or more magic items, it is no longer attuned to them.",
`dead`
],
[
"bardic-inspiration",
/You can inspire others through stirring words or music/i,
"Once within the next 10 minutes, the creature can roll the die and add the number rolled to one ability check, Attack roll, or saving throw it makes. The creature can wait until after it rolls The D20 before deciding to use the Bardic Inspiration die, but must decide before the DM says whether the roll succeeds or fails.",
`black-flag`
],
[
"bloodied",
/nonmatching string to prevent accidental triggering/i,
"A creature is Bloodied while it has half its Hit Points or fewer remaining. Usually determines the effectiveness of a Swarm. It is the point at which a creature reaches half their full hit points. The DM may reveal this to the players as an indicator of how strong the monster currently is.",
`pummeled`
],
[
"confused",
/spawning delusions and provoking uncontrolled action/i,
"Not a true condition, but can represent the effect of the confusion spell.<BR>An affected target can’t take reactions and must roll 1d10 at the start of each of its turns to determine its behavior for that turn, consulting the table below.<BR>1d10 - Behavior for the Turn<BR>1 - The target doesn't take an action, and it uses all its movement to move. Roll 1d4 for the direction: 1, north; 2, east; 3, south; or 4, west. <BR>2-6 - The target doesn't move or take actions. <BR>7-8 - The target doesn't move, and it takes the Attack action to make one melee attack against a random creature within reach. If none are within reach, the target takes no action.<BR>9-10 - The target chooses its behavior. At the end of each of its turns, an affected target repeats the save, ending the spell on itself on a success.",
`rolling-bomb`
],
[
"full-cover",
/nonmatching string to prevent accidental triggering/i,
"Cover provides a degree of protection to a target behind it. There are three degrees of cover, each of which provides a different benefit to a target: Half Cover (+2 bonus to AC and Dexterity saving throws), Three-Quarters Cover (+5 bonus to AC and Dexterity saving throws), and Total Cover (can’t be targeted directly). If behind more than one degree of cover, a target benefits only from the most protective degree.",
`bolt-shield`
],
[
"three-quarter-cover",
/nonmatching string to prevent accidental triggering/i,
"Cover provides a degree of protection to a target behind it. There are three degrees of cover, each of which provides a different benefit to a target: Half Cover (+2 bonus to AC and Dexterity saving throws), Three-Quarters Cover (+5 bonus to AC and Dexterity saving throws), and Total Cover (can’t be targeted directly). If behind more than one degree of cover, a target benefits only from the most protective degree.",
`broken-shield`
],
[
"half-cover",
/nonmatching string to prevent accidental triggering/i,
"Cover provides a degree of protection to a target behind it. There are three degrees of cover, each of which provides a different benefit to a target: Half Cover (+2 bonus to AC and Dexterity saving throws), Three-Quarters Cover (+5 bonus to AC and Dexterity saving throws), and Total Cover (can’t be targeted directly). If behind more than one degree of cover, a target benefits only from the most protective degree.",
`broken-shield`
],
[
"diseased",
/nonmatching string to prevent accidental triggering/i,
"See the entry on <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='https://app.roll20.net/compendium/dnd5e/Rules%3ADiseases?sharedCompendium=4665985#toc_1'>Diseases</a> in the Compendium",
`radioactive`
],
[
"ethereal",
/ethereal/i,
"Border Ethereal<BR>From the Border Ethereal, a traveler can see into whatever plane it overlaps, but that plane appears grayish and indistinct, its colors blurring into each other and its edges turning fuzzy, limiting visibility to 30 feet into the other plane. Conversely, the Ethereal Plane is usually imperceptible to those on the overlapped planes, except with the aid of magic.<BR>Normally, creatures in the Border Ethereal can’t attack creatures on the overlapped plane, and vice versa. A traveler on the Ethereal Plane is imperceptible to someone on the overlapped plane, and solid objects on the overlapped plane don’t hamper the movement of a creature in the Border Ethereal. The exceptions are certain magical effects (including anything made of magical force) and living beings. This makes the Ethereal Plane ideal for scouting, spying on opponents, and moving around without being detected. The Ethereal Plane also disobeys the laws of gravity; a creature there can freely move in any direction.<BR>Deep Ethereal<BR>To reach the Deep Ethereal, one typically needs a Plane Shift spell, a Gate spell, or a magical portal. Visitors to the Deep Ethereal are engulfed by roiling mist. Scattered throughout the plane are curtains of vaporous color, and passing through a curtain leads a traveler to a region of the Border Ethereal connected to a specific Inner Plane, the Material Plane, the Feywild, or the Shadowfell. The color of the curtain indicates the plane whose Border Ethereal the curtain conceals; see the Ethereal Curtains table. The curtains are also distinguishable by texture and temperature, each one reflecting something of the nature of the plane beyond.",
`angel-outfit`
],
[
"flying",
/nonmatching string to prevent accidental triggering/i,
"A variety of effects allow a creature to fly. While flying, you fall if you have the Incapacitated or Prone condition or your Fly Speed is reduced to 0. You can stay aloft in those circumstances if you can hover.",
`fluffy-wing`
],
[
"haste",
/as a wave of lethargy sweeps over it/i,
"The target’s speed is doubled, it gains a +2 bonus to AC, it has advantage on Dexterity Saving Throws, and it gains an additional Action on each of its turns. That Action can be used only to take the Attack (one weapon attack only), Dash, Disengage, Hide, or Use an Object Action.<BR>When the spell ends, the target can’t move or take actions until after its next turn, as a wave of lethargy sweeps over it.",
`stopwatch`
],
[
"hexed",
/You place a curse on a creature that you can see within range/i,
"You place a curse on a creature that you can see within range. Until the spell ends, you deal an extra 1d6 Necrotic damage to the target whenever you hit it with an attack roll. Also, choose one ability when you cast the spell. The target has Disadvantage on ability checks made with the chosen ability.<BR>If the target drops to 0 Hit Points before this spell ends, you can take a Bonus Action on a later turn to curse a new creature.",
`lightning-helix`
],
[
"hexblade-curse",
/Starting at 1st Level, you gain the ability to place a baleful curse on someone/i,
"As a Bonus Action, choose one creature you can see within 30 feet of you. The target is Cursed for 1 minute. The curse ends early if the target dies, you die, or you are Incapacitated. Until the curse ends, you gain the following benefits:<BR>You gain a bonus to Damage Rolls against the Cursed target. The bonus equals your Proficiency Bonus.<BR>Any Attack roll you make against the Cursed target is a critical hit on a roll of 19 or 20 on The D20.<BR>If the Cursed target dies, you regain Hit Points equal to your Warlock level + your Charisma modifier (minimum of 1 hit point).<BR>You can’t use this feature again until you finish a short or Long Rest.",
`all-for-one`
],
[
"hidden",
/nonmatching string to prevent accidental triggering/i,
"With the Hide action, you try to conceal yourself. To do so, you must succeed on a DC 15 Dexterity (Stealth) check while you’re Heavily Obscured or behind Three-Quarters Cover or Total Cover, and you must be out of any enemy’s line of sight; if you can see a creature, you can discern whether it can see you.<BR>On a successful check, you have the Invisible condition. Make note of your check’s total, which is the DC for a creature to find you with a Wisdom (Perception) check.<BR>The condition ends on you immediately after any of the following occurs: you make a sound louder than a whisper, an enemy finds you, you make an attack roll, or you cast a spell with a Verbal component.",
`ninja-mask`
],
[
"TempHP",
/nonmatching string to prevent accidental triggering/i,
"Temporary Hit Points aren’t actual hit points; they are a buffer against damage, a pool of Hit Points that protect you from injury.<BR>When you have temporary Hit Points and take damage, the temporary Hit Points are lost first, and any leftover damage carries over to your normal Hit Points. For example, if you have 5 temporary Hit Points and take 7 damage, you lose the temporary Hit Points and then take 2 damage.<BR>Because temporary Hit Points are separate from your actual Hit Points, they can exceed your hit point maximum. A character can, therefore, be at full Hit Points and receive temporary Hit Points.<BR>Healing can’t restore temporary Hit Points, and they can’t be added together. If you have temporary Hit Points and receive more of them, you decide whether to keep the ones you have or to gain the new ones. For example, if a spell grants you 12 temporary Hit Points when you already have 10, you can have 12 or 10, not 22.<BR>If you have 0 Hit Points, receiving temporary Hit Points doesn’t restore you to consciousness or stabilize you. They can still absorb damage directed at you while you’re in that state, but only true Healing can save you.<BR>Unless a feature that grants you temporary Hit Points has a Duration, they last until they’re depleted or you finish a Long Rest.",
`broken-heart`
],
[
"favored",
/mystical bond with Nature to mark the target as your Favored enemy/i,
"Concentration.<BR>The first time on each of your turns that you hit the Favored enemy and deal damage to it, including when you mark it, you can increase that damage by 1d4.<BR>You can use this feature to mark a Favored enemy a number of times equal to your Proficiency bonus, and you regain all expended uses when you finish a Long Rest.<BR>This feature's extra damage increases when you reach certain levels in this class: to 1d6 at 6th Level and to 1d8 at 14th level.",
`archery-target`
],
[
"marked",
/(mystically mark it as your quarry|You magically mark one creature you can see within range as your quarry)/i,
"You magically mark one creature you can see within range as your quarry. Until the spell ends, you deal an extra 1d6 Force damage to the target whenever you hit it with an attack roll. You also have Advantage on any Wisdom (Perception or Survival) check you make to find it.<BR>If the target drops to 0 Hit Points before this spell ends, you can take a Bonus Action to move the mark to a new creature you can see within range.<BR>Using a Higher-Level Spell Slot. Your Concentration can last longer with a spell slot of level 3–4 (up to 8 hours) or 5+ (up to 24 hours).",
`archery-target`
],
[
"raging",
/On your turn, you can enter a rage as a Bonus Action/i,
"While active, your Rage follows the rules below.<BR>Damage Resistance. You have Resistance to Bludgeoning, Piercing, and Slashing damage.<BR>Rage Damage. When you make an attack using Strength—with either a weapon or an Unarmed Strike—and deal damage to the target, you gain a bonus to the damage that increases as you gain levels as a Barbarian, as shown in the Rage Damage column of the Barbarian Features table.<BR>Strength Advantage. You have Advantage on Strength checks and Strength saving throws.<BR>No Concentration or Spells. You can’t maintain Concentration, and you can’t cast spells.<BR>Duration. The Rage lasts until the end of your next turn, and it ends early if you don Heavy armor or have the Incapacitated condition. If your Rage is still active on your next turn, you can extend the Rage for another round by doing one of the following:<BR>Make an attack roll against an enemy.<BR>Force an enemy to make a saving throw.<BR>Take a Bonus Action to extend your Rage.",
`strong`
],
[
"slowed",
/You alter time around up to six creatures of your choice/i,
"Each target must succeed on a Wisdom saving throw or be affected by this spell for the duration.<BR>An affected target’s Speed is halved, it takes a −2 penalty to AC and Dexterity saving throws, and it can’t take Reactions. On its turns, it can take either an action or a Bonus Action, not both, and it can make only one attack if it takes the Attack action. If it casts a spell with a Somatic component, there is a 25 percent chance the spell fails as a result of the target making the spell’s gestures too slowly.<BR>An affected target repeats the save at the end of each of its turns, ending the spell on itself on a success.",
`snail`
],
[
"Torch",
/nonmatching string to prevent accidental triggering/i,
"A Torch burns for 1 hour, casting Bright Light in a 20-foot radius and Dim Light for an additional 20 feet. When you take the Attack action, you can attack with the Torch, using it as a Simple Melee weapon. On a hit, the target takes 1 Fire damage.",
`frozen-orb`
],
[
"dying",
/nonmatching string to prevent accidental triggering/i,
"When a creature drops to 0 Hit Points, it either dies outright or falls unconscious, as explained below.<BR>Instant Death<BR>Here are the main ways a creature can die instantly.<BR>Monster Death.<BR>A monster dies the instant it drops to 0 Hit Points, although a Dungeon Master can ignore this rule for an individual monster and treat it like a character.<BR>Hit Point Maximum of 0.<BR>A creature dies if its Hit Point maximum reaches 0. Certain effects drain life energy, reducing a creature’s Hit Point maximum.<BR>Massive Damage.<BR>When damage reduces a character to 0 Hit Points and damage remains, the character dies if the remainder equals or exceeds their Hit Point maximum. For example, if your character has a Hit Point maximum of 12, currently has 6 Hit Points, and takes 18 damage, the character drops to 0 Hit Points, but 12 damage remains. The character then dies, since 12 equals their Hit Point maximum.<BR>Character Demise<BR>If your character dies, others might find a magical way to revive your character, such as with the Raise Dead spell. Or talk with the DM about making a new character to join the group.<BR>Falling<BR>Unconscious<BR>If you reach 0 Hit Points and don’t die instantly, you have the Unconscious condition until you regain any Hit Points, and you now face making Death Saving Throws (see below).<BR>Knocking Out a Creature<BR>When you would reduce a creature to 0 Hit Points with a melee attack, you can instead reduce the creature to 1 Hit Point and give it the Unconscious condition. It then starts a Short Rest, at the end of which that condition ends on it. The condition ends early if the creature regains any Hit Points or if someone takes an action to administer first aid to it, making a successful DC 10 Wisdom (Medicine) check.<BR>Death Saving Throws<BR>Whenever you start your turn with 0 Hit Points, you must make a Death Saving Throw to determine whether you creep closer to death or hang on to life. Unlike other saving throws, this one isn’t tied to an ability score. You’re in the hands of fate now.<BR>Three Successes/Failures.<BR>Roll 1d20. If the roll is 10 or higher, you succeed. Otherwise, you fail. A success or failure has no effect by itself. On your third success, you become Stable. On your third failure, you die.<BR>The successes and failures don’t need to be consecutive; keep track of both until you collect three of a kind. The number of both is reset to zero when you regain any Hit Points or become Stable.<BR>Rolling a 1 or 20.<BR>When you roll a 1 on the d20 for a Death Saving Throw, you suffer two failures. If you roll a 20 on the d20, you regain 1 Hit Point.<BR>Damage at 0 Hit Points.<BR>If you take any damage while you have 0 Hit Points, you suffer a Death Saving Throw failure. If the damage is from a Critical Hit, you suffer two failures instead. If the damage equals or exceeds your Hit Point maximum, you die.<BR>Stabilizing a Character<BR>You can take the Help action to try to stabilize a creature with 0 Hit Points, which requires a successful DC 10 Wisdom (Medicine) check.<BR>A Stable creature doesn’t make Death Saving Throws even though it has 0 Hit Points, but it still has the Unconscious condition. If the creature takes damage, it stops being Stable and starts making Death Saving Throws again. A Stable creature that isn’t healed regains 1 Hit Point after 1d4 hours.",
`death-zone`
],
[
"burrowing",
/nonmatching string to prevent accidental triggering/i,
"A creature that has a Burrow Speed can use that speed to move through sand, earth, mud, or ice. The creature can’t burrow through solid rock unless the creature has a trait that allows it to do so. See also “Speed.",
`edge-crack`
],
[
"dodging",
/nonmatching string to prevent accidental triggering/i,
"If you take the Dodge action, you gain the following benefits: until the start of your next turn, any attack roll made against you has Disadvantage if you can see the attacker, and you make Dexterity saving throws with Advantage.<BR>You lose these benefits if you have the Incapacitated condition or if your Speed is 0.",
`tread`
],
[
"inspiration",
/nonmatching string to prevent accidental triggering/i,
"If you (a player character) have Heroic Inspiration, you can expend it to reroll any die immediately after rolling it, and you must use the new roll.<BR>If you gain Heroic Inspiration but already have it, it’s lost unless you give it to a player character who lacks it.",
`flying-flag`
],
[
"TemporaryHP",
/nonmatching string to prevent accidental triggering/i,
"Temporary Hit Points aren’t actual hit points; they are a buffer against damage, a pool of Hit Points that protect you from injury.<BR>When you have temporary Hit Points and take damage, the temporary Hit Points are lost first, and any leftover damage carries over to your normal Hit Points. For example, if you have 5 temporary Hit Points and take 7 damage, you lose the temporary Hit Points and then take 2 damage.<BR>Because temporary Hit Points are separate from your actual Hit Points, they can exceed your hit point maximum. A character can, therefore, be at full Hit Points and receive temporary Hit Points.<BR>Healing can’t restore temporary Hit Points, and they can’t be added together. If you have temporary Hit Points and receive more of them, you decide whether to keep the ones you have or to gain the new ones. For example, if a spell grants you 12 temporary Hit Points when you already have 10, you can have 12 or 10, not 22.<BR>If you have 0 Hit Points, receiving temporary Hit Points doesn’t restore you to consciousness or stabilize you. They can still absorb damage directed at you while you’re in that state, but only true Healing can save you.<BR>Unless a feature that grants you temporary Hit Points has a Duration, they last until they’re depleted or you finish a Long Rest.",
`broken-heart`
]
]
// END SET STATUS CONDITIONS OR TOKEN MARKERS
let defaultConditionsArray_EasyToRead = [
["concentrating",
/concentration check|concentration=1/i,
"Some spells and other effects require Concentration to remain active, as specified in their descriptions. If the effect’s creator loses Concentration, the effect ends. If the effect has a maximum duration, the effect’s description specifies how long the creator can concentrate on it: up to 1 minute, 1 hour, or some other duration. The creator can end Concentration at any time (no action required). The following factors break Concentration.<BR>Another Concentration Effect. You lose Concentration on an effect the moment you start casting a spell that requires Concentration or activate another effect that requires Concentration.<BR>Damage. If you take damage, you must succeed on a Constitution saving throw to maintain Concentration. The DC equals 10 or half the damage taken (round down), whichever number is higher, up to a maximum DC of 30.<BR>Incapacitated or Dead. Your Concentration ends if you have the Incapacitated condition or you die.",
`Concentrating`
],
["blinded",
/(be|and|is|magically|become|becomes|is either|has the) blinded|blinded condition/i,
"While you have the Blinded condition, you experience the following effects.<BR><b>Can’t See.</b> You can’t see and automatically fail any ability check that requires sight.<BR><b>Attacks Affected.</b> Attack rolls against you have Advantage, and your attack rolls have Disadvantage.",
`Blinded`
],
[
"charmed",
/(be|and|is|magically|become|becomes) charmed|charmed condition/i,
"While you have the Charmed condition, you experience the following effects.<BR><BR><b>Can’t Harm the Charmer.</b> You can’t attack the charmer or target the charmer with damaging abilities or magical effects.<BR><BR><b>Social Advantage.</b> The charmer has Advantage on any ability check to interact with you socially.",
`Charmed`
],
[
"deafened",
/(be|and|is|magically|become|becomes) deafened|deafened condition/i,
"While you have the Deafened condition, you experience the following effect.<BR><BR><b>Can’t Hear.</b> You can’t hear and automatically fail any ability check that requires hearing.",
`Deafened`
],
[
"exhausted",
/(be|and|is|magically|become|becomes) exhausted|(of|magical) exhaustion|exhausted condition/i,
"While you have the Exhaustion condition, you experience the following effects.<BR><BR><b>Exhaustion Levels.</b> This condition is cumulative. Each time you receive it, you gain 1 Exhaustion level. You die if your Exhaustion level is 6.<BR><BR><b>D20 Tests Affected.</b> When you make a D20 Test, the roll is reduced by 2 times your Exhaustion level.<BR><BR><b>Speed Reduced.</b> Your Speed is reduced by a number of feet equal to 5 times your Exhaustion level.<BR><BR><b>Removing Exhaustion Levels.</b> Finishing a Long Rest removes 1 of your Exhaustion levels. When your Exhaustion level reaches 0, the condition ends.",
`Exhausted`
],
[
"frightened",
/(be|and|is|magically|become|becomes) frightened|frightened condition/i,
"While you have the Frightened condition, you experience the following effects.<BR><BR><b>Ability Checks and Attacks Affected.</b> You have Disadvantage on ability checks and attack rolls while the source of fear is within line of sight.<BR><BR><b>Can’t Approach.</b> You can’t willingly move closer to the source of fear.",
`Frightened`
],
[
"grappled",
/(be|and|is|magically|becomes|considered) grappled|grappled condition/i,
"While you have the Grappled condition, you experience the following effects.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Attacks Affected.</b> You have Disadvantage on attack rolls against any target other than the grappler.<BR><BR><b>Movable.</b> The grappler can drag or carry you when it moves, but every foot of movement costs it 1 extra foot unless you are Tiny or two or more sizes smaller than it.",
`Grappled`
],
[
"incapacitated",
/(be|and|is|magically|become|becomes) incapacitated|incapacitated condition/i,
"While you have the Incapacitated condition, you experience the following effects.<BR><BR><b>Inactive.</b> You can’t take any action, Bonus Action, or Reaction.<BR><BR><b>No Concentration.</b> Your Concentration is broken.<BR><BR><b>Speechless.</b> You can’t speak.<BR><BR><b>Surprised.</b> If you’re Incapacitated when you roll Initiative, you have Disadvantage on the roll.",
`Incapacitated`
],
[
"invisible",
/(be|and|is|magically|become|becomes) invisible|invisible condition/i,
"While you have the Invisible condition, you experience the following effects.<BR><BR><b>Surprise.</b> If you’re Invisible when you roll Initiative, you have Advantage on the roll.<BR><BR><b>Concealed.</b> You aren’t affected by any effect that requires its target to be seen unless the effect’s creator can somehow see you. Any equipment you are wearing or carrying is also concealed.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Disadvantage, and your attack rolls have Advantage. If a creature can somehow see you, you don’t gain this benefit against that creature.",
`Invisible`
],
[
"paralyzed",
/(be|and|is|magically|become|becomes) paralyzed|paralyzed condition/i,
"While you have the Paralyzed condition, you experience the following effects.<BR><BR><b>Incapacitated.</b> You have the <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>Incapacitated</a> condition.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Saving Throws Affected.</b> You automatically fail Strength and Dexterity saving throws.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage.<BR><BR><b>Automatic Critical Hits.</b> Any attack roll that hits you is a Critical Hit if the attacker is within 5 feet of you.",
`Paralyzed`
],
[
"petrified",
/(be|and|is|magically|become|becomes|becoming) petrified|(turns to|turning to) stone|petrified condition/i,
"While you have the Petrified condition, you experience the following effects.<BR><BR><b>Turned to Inanimate Substance.</b> You are transformed, along with any nonmagical objects you are wearing and carrying, into a solid inanimate substance (usually stone). Your weight increases by a factor of ten, and you cease aging.<BR><BR><b>Incapacitated.</b> You have the <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>Incapacitated</a> condition.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage.<BR><BR><b>Saving Throws Affected.</b> You automatically fail Strength and Dexterity saving throws.<BR><BR><b>Resist Damage.</b> You have Resistance to all damage.<BR><BR><b>Poison Immunity.</b> You have Immunity to the Poisoned condition.",
`Petrified`
],
[
"poisoned",
/(be|and|is|magically|become|becomes) poisoned|poisoned condition/i,
"While you have the Poisoned condition, you experience the following effect.<BR><BR><b>Ability Checks and Attacks Affected.</b> You have Disadvantage on attack rolls and ability checks.",
'Poisoned'
],
[
"prone",
/(be|and|is|magically|become|becomes|knocked|fall|falls) prone|prone condition/i,
"While you have the Prone condition, you experience the following effects.<BR><BR><b>Restricted Movement.</b> Your only movement options are to crawl or to spend an amount of movement equal to half your Speed (round down) to right yourself and thereby end the condition. If your Speed is 0, you can’t right yourself.<BR><BR><b>Attacks Affected.</b> You have Disadvantage on attack rolls. An attack roll against you has Advantage if the attacker is within 5 feet of you. Otherwise, that attack roll has Disadvantage.",
`Prone`
],
[
"restrained",
/(be|and|is|magically|become|becomes) restrained|restrained condition/i,
"While you have the Restrained condition, you experience the following effects.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage, and your attack rolls have Disadvantage.<BR><BR><b>Saving Throws Affected.</b> You have Disadvantage on Dexterity saving throws.",
`Restrained`
],
[
"stunned",
/(be|and|is|magically|become|becomes) stunned|stunned condition/i,
"While you have the Stunned condition, you experience the following effects.<BR><BR><b>Incapacitated.</b> You have the <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>Incapacitated</a> condition.<BR><BR><b>Saving Throws Affected.</b> You automatically fail Strength and Dexterity saving throws.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage.",
`Stunned`
],
[
"unconscious",
/(be|and|is|magically|become|becomes) unconscious|unconscious condition/i,
"While you have the Unconscious condition, you experience the following effects.<BR><BR><b>Inert.</b> You have the <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>Incapacitated</a> and <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef prone'>Prone</a> conditions, and you drop whatever you’re holding. When this condition ends, you remain Prone.<BR><BR><b>Speed 0.</b> Your Speed is 0 and can’t increase.<BR><BR><b>Attacks Affected.</b> Attack rolls against you have Advantage.<BR><BR><b>Saving Throws Affected.</b> You automatically fail Strength and Dexterity saving throws.<BR><BR><b>Automatic Critical Hits.</b> Any attack roll that hits you is a Critical Hit if the attacker is within 5 feet of you.<BR><BR><b>Unaware.</b> You’re unaware of your surroundings.",
`Unconscious9`
],
[
"dead",
/nonmatching string to prevent accidental triggering/i,
"A dead creature has no Hit Points and can’t regain them unless it is first revived by magic such as the Raise Dead or Revivify spell. When such a spell is cast, the spirit knows who is casting it and can refuse. The spirit of a dead creature has left the body and departed for the Outer Planes, and reviving the creature requires calling the spirit back.<BR>If the creature returns to life, the revival effect determines the creature’s current Hit Points. Unless otherwise stated, the creature returns to life with any conditions, magical contagions, or curses that were affecting it at death if the durations of those effects are still ongoing. If the creature died with any Exhaustion levels, it returns with 1 fewer level. If the creature had Attunement to one or more magic items, it is no longer attuned to them.",
`dead`
],
[
"bardic-inspiration",
/You can inspire others through stirring words or music/i,
"Once within the next 10 minutes, the creature can roll the die and add the number rolled to one ability check, Attack roll, or saving throw it makes. The creature can wait until after it rolls The D20 before deciding to use the Bardic Inspiration die, but must decide before the DM says whether the roll succeeds or fails.",
`Bardic`
],
[
"bloodied",
/nonmatching string to prevent accidental triggering/i,
"A creature is Bloodied while it has half its Hit Points or fewer remaining. Usually determines the effectiveness of a Swarm. It is the point at which a creature reaches half their full hit points. The DM may reveal this to the players as an indicator of how strong the monster currently is.",
`Bloodied`
],
[
"confused",
/spawning delusions and provoking uncontrolled action/i,
"Not a true condition, but can represent the effect of the confusion spell.<BR>An affected target can’t take reactions and must roll 1d10 at the start of each of its turns to determine its behavior for that turn, consulting the table below.<BR>1d10 - Behavior for the Turn<BR>1 - The target doesn't take an action, and it uses all its movement to move. Roll 1d4 for the direction: 1, north; 2, east; 3, south; or 4, west. <BR>2-6 - The target doesn't move or take actions. <BR>7-8 - The target doesn't move, and it takes the Attack action to make one melee attack against a random creature within reach. If none are within reach, the target takes no action.<BR>9-10 - The target chooses its behavior. At the end of each of its turns, an affected target repeats the save, ending the spell on itself on a success.",
`Confused`
],
[
"full-cover",
/nonmatching string to prevent accidental triggering/i,
"Cover provides a degree of protection to a target behind it. There are three degrees of cover, each of which provides a different benefit to a target: Half Cover (+2 bonus to AC and Dexterity saving throws), Three-Quarters Cover (+5 bonus to AC and Dexterity saving throws), and Total Cover (can’t be targeted directly). If behind more than one degree of cover, a target benefits only from the most protective degree.",
// `death-zone`
`Cover`
],
[
"three-quarter-cover",
/nonmatching string to prevent accidental triggering/i,
"Cover provides a degree of protection to a target behind it. There are three degrees of cover, each of which provides a different benefit to a target: Half Cover (+2 bonus to AC and Dexterity saving throws), Three-Quarters Cover (+5 bonus to AC and Dexterity saving throws), and Total Cover (can’t be targeted directly). If behind more than one degree of cover, a target benefits only from the most protective degree.",
`ThreeQuarterCover`
],
[
"half-cover",
/nonmatching string to prevent accidental triggering/i,
"Cover provides a degree of protection to a target behind it. There are three degrees of cover, each of which provides a different benefit to a target: Half Cover (+2 bonus to AC and Dexterity saving throws), Three-Quarters Cover (+5 bonus to AC and Dexterity saving throws), and Total Cover (can’t be targeted directly). If behind more than one degree of cover, a target benefits only from the most protective degree.",
`HalfCover`
],
[
"diseased",
/nonmatching string to prevent accidental triggering/i,
"See the entry on <a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='https://app.roll20.net/compendium/dnd5e/Rules%3ADiseases?sharedCompendium=4665985#toc_1'>Diseases</a> in the Compendium",
`Dieseased`
],
[
"ethereal",
/ethereal/i,
"Border Ethereal<BR>From the Border Ethereal, a traveler can see into whatever plane it overlaps, but that plane appears grayish and indistinct, its colors blurring into each other and its edges turning fuzzy, limiting visibility to 30 feet into the other plane. Conversely, the Ethereal Plane is usually imperceptible to those on the overlapped planes, except with the aid of magic.<BR>Normally, creatures in the Border Ethereal can’t attack creatures on the overlapped plane, and vice versa. A traveler on the Ethereal Plane is imperceptible to someone on the overlapped plane, and solid objects on the overlapped plane don’t hamper the movement of a creature in the Border Ethereal. The exceptions are certain magical effects (including anything made of magical force) and living beings. This makes the Ethereal Plane ideal for scouting, spying on opponents, and moving around without being detected. The Ethereal Plane also disobeys the laws of gravity; a creature there can freely move in any direction.<BR>Deep Ethereal<BR>To reach the Deep Ethereal, one typically needs a Plane Shift spell, a Gate spell, or a magical portal. Visitors to the Deep Ethereal are engulfed by roiling mist. Scattered throughout the plane are curtains of vaporous color, and passing through a curtain leads a traveler to a region of the Border Ethereal connected to a specific Inner Plane, the Material Plane, the Feywild, or the Shadowfell. The color of the curtain indicates the plane whose Border Ethereal the curtain conceals; see the Ethereal Curtains table. The curtains are also distinguishable by texture and temperature, each one reflecting something of the nature of the plane beyond.",
`Ethereal`
],
[
"flying",
/nonmatching string to prevent accidental triggering/i,
"A variety of effects allow a creature to fly. While flying, you fall if you have the Incapacitated or Prone condition or your Fly Speed is reduced to 0. You can stay aloft in those circumstances if you can hover.",
`Flying`
],
[
"haste",
/as a wave of lethargy sweeps over it/i,
"The target’s speed is doubled, it gains a +2 bonus to AC, it has advantage on Dexterity Saving Throws, and it gains an additional Action on each of its turns. That Action can be used only to take the Attack (one weapon attack only), Dash, Disengage, Hide, or Use an Object Action.<BR>When the spell ends, the target can’t move or take actions until after its next turn, as a wave of lethargy sweeps over it.",
`Haste`
],
[
"hexed",
/You place a curse on a creature that you can see within range/i,
"You place a curse on a creature that you can see within range. Until the spell ends, you deal an extra 1d6 Necrotic damage to the target whenever you hit it with an attack roll. Also, choose one ability when you cast the spell. The target has Disadvantage on ability checks made with the chosen ability.<BR>If the target drops to 0 Hit Points before this spell ends, you can take a Bonus Action on a later turn to curse a new creature.",
`Hexed`
],
[
"hexblade-curse",
/Starting at 1st Level, you gain the ability to place a baleful curse on someone/i,
"As a Bonus Action, choose one creature you can see within 30 feet of you. The target is Cursed for 1 minute. The curse ends early if the target dies, you die, or you are Incapacitated. Until the curse ends, you gain the following benefits:<BR>You gain a bonus to Damage Rolls against the Cursed target. The bonus equals your Proficiency Bonus.<BR>Any Attack roll you make against the Cursed target is a critical hit on a roll of 19 or 20 on The D20.<BR>If the Cursed target dies, you regain Hit Points equal to your Warlock level + your Charisma modifier (minimum of 1 hit point).<BR>You can’t use this feature again until you finish a short or Long Rest.",
`Hexed2`
],
[
"hidden",
/nonmatching string to prevent accidental triggering/i,
"With the Hide action, you try to conceal yourself. To do so, you must succeed on a DC 15 Dexterity (Stealth) check while you’re Heavily Obscured or behind Three-Quarters Cover or Total Cover, and you must be out of any enemy’s line of sight; if you can see a creature, you can discern whether it can see you.<BR>On a successful check, you have the Invisible condition. Make note of your check’s total, which is the DC for a creature to find you with a Wisdom (Perception) check.<BR>The condition ends on you immediately after any of the following occurs: you make a sound louder than a whisper, an enemy finds you, you make an attack roll, or you cast a spell with a Verbal component.",
`Hidden`
],
[
"TempHP",
/nonmatching string to prevent accidental triggering/i,
"Temporary Hit Points aren’t actual hit points; they are a buffer against damage, a pool of Hit Points that protect you from injury.<BR>When you have temporary Hit Points and take damage, the temporary Hit Points are lost first, and any leftover damage carries over to your normal Hit Points. For example, if you have 5 temporary Hit Points and take 7 damage, you lose the temporary Hit Points and then take 2 damage.<BR>Because temporary Hit Points are separate from your actual Hit Points, they can exceed your hit point maximum. A character can, therefore, be at full Hit Points and receive temporary Hit Points.<BR>Healing can’t restore temporary Hit Points, and they can’t be added together. If you have temporary Hit Points and receive more of them, you decide whether to keep the ones you have or to gain the new ones. For example, if a spell grants you 12 temporary Hit Points when you already have 10, you can have 12 or 10, not 22.<BR>If you have 0 Hit Points, receiving temporary Hit Points doesn’t restore you to consciousness or stabilize you. They can still absorb damage directed at you while you’re in that state, but only true Healing can save you.<BR>Unless a feature that grants you temporary Hit Points has a Duration, they last until they’re depleted or you finish a Long Rest.",
`TempHP`
],
[
"favored",
/mystical bond with Nature to mark the target as your Favored enemy/i,
"Concentration.<BR>The first time on each of your turns that you hit the Favored enemy and deal damage to it, including when you mark it, you can increase that damage by 1d4.<BR>You can use this feature to mark a Favored enemy a number of times equal to your Proficiency bonus, and you regain all expended uses when you finish a Long Rest.<BR>This feature's extra damage increases when you reach certain levels in this class: to 1d6 at 6th Level and to 1d8 at 14th level.",
`Marked`
],
[
"marked",
/(mystically mark it as your quarry|You magically mark one creature you can see within range as your quarry)/i,
"You magically mark one creature you can see within range as your quarry. Until the spell ends, you deal an extra 1d6 Force damage to the target whenever you hit it with an attack roll. You also have Advantage on any Wisdom (Perception or Survival) check you make to find it.<BR>If the target drops to 0 Hit Points before this spell ends, you can take a Bonus Action to move the mark to a new creature you can see within range.<BR>Using a Higher-Level Spell Slot. Your Concentration can last longer with a spell slot of level 3–4 (up to 8 hours) or 5+ (up to 24 hours).",
`Marked2`
],
[
"raging",
/On your turn, you can enter a rage as a Bonus Action/i,
"While active, your Rage follows the rules below.<BR>Damage Resistance. You have Resistance to Bludgeoning, Piercing, and Slashing damage.<BR>Rage Damage. When you make an attack using Strength—with either a weapon or an Unarmed Strike—and deal damage to the target, you gain a bonus to the damage that increases as you gain levels as a Barbarian, as shown in the Rage Damage column of the Barbarian Features table.<BR>Strength Advantage. You have Advantage on Strength checks and Strength saving throws.<BR>No Concentration or Spells. You can’t maintain Concentration, and you can’t cast spells.<BR>Duration. The Rage lasts until the end of your next turn, and it ends early if you don Heavy armor or have the Incapacitated condition. If your Rage is still active on your next turn, you can extend the Rage for another round by doing one of the following:<BR>Make an attack roll against an enemy.<BR>Force an enemy to make a saving throw.<BR>Take a Bonus Action to extend your Rage.",
`Raging`
],
[
"slowed",
/You alter time around up to six creatures of your choice/i,
"Each target must succeed on a Wisdom saving throw or be affected by this spell for the duration.<BR>An affected target’s Speed is halved, it takes a −2 penalty to AC and Dexterity saving throws, and it can’t take Reactions. On its turns, it can take either an action or a Bonus Action, not both, and it can make only one attack if it takes the Attack action. If it casts a spell with a Somatic component, there is a 25 percent chance the spell fails as a result of the target making the spell’s gestures too slowly.<BR>An affected target repeats the save at the end of each of its turns, ending the spell on itself on a success.",
`Slow`
],
[
"Torch",
/nonmatching string to prevent accidental triggering/i,
"A Torch burns for 1 hour, casting Bright Light in a 20-foot radius and Dim Light for an additional 20 feet. When you take the Attack action, you can attack with the Torch, using it as a Simple Melee weapon. On a hit, the target takes 1 Fire damage.",
`Torch`
],
[
"dying",
/nonmatching string to prevent accidental triggering/i,
"When a creature drops to 0 Hit Points, it either dies outright or falls unconscious, as explained below.<BR>Instant Death<BR>Here are the main ways a creature can die instantly.<BR>Monster Death.<BR>A monster dies the instant it drops to 0 Hit Points, although a Dungeon Master can ignore this rule for an individual monster and treat it like a character.<BR>Hit Point Maximum of 0.<BR>A creature dies if its Hit Point maximum reaches 0. Certain effects drain life energy, reducing a creature’s Hit Point maximum.<BR>Massive Damage.<BR>When damage reduces a character to 0 Hit Points and damage remains, the character dies if the remainder equals or exceeds their Hit Point maximum. For example, if your character has a Hit Point maximum of 12, currently has 6 Hit Points, and takes 18 damage, the character drops to 0 Hit Points, but 12 damage remains. The character then dies, since 12 equals their Hit Point maximum.<BR>Character Demise<BR>If your character dies, others might find a magical way to revive your character, such as with the Raise Dead spell. Or talk with the DM about making a new character to join the group.<BR>Falling<BR>Unconscious<BR>If you reach 0 Hit Points and don’t die instantly, you have the Unconscious condition until you regain any Hit Points, and you now face making Death Saving Throws (see below).<BR>Knocking Out a Creature<BR>When you would reduce a creature to 0 Hit Points with a melee attack, you can instead reduce the creature to 1 Hit Point and give it the Unconscious condition. It then starts a Short Rest, at the end of which that condition ends on it. The condition ends early if the creature regains any Hit Points or if someone takes an action to administer first aid to it, making a successful DC 10 Wisdom (Medicine) check.<BR>Death Saving Throws<BR>Whenever you start your turn with 0 Hit Points, you must make a Death Saving Throw to determine whether you creep closer to death or hang on to life. Unlike other saving throws, this one isn’t tied to an ability score. You’re in the hands of fate now.<BR>Three Successes/Failures.<BR>Roll 1d20. If the roll is 10 or higher, you succeed. Otherwise, you fail. A success or failure has no effect by itself. On your third success, you become Stable. On your third failure, you die.<BR>The successes and failures don’t need to be consecutive; keep track of both until you collect three of a kind. The number of both is reset to zero when you regain any Hit Points or become Stable.<BR>Rolling a 1 or 20.<BR>When you roll a 1 on the d20 for a Death Saving Throw, you suffer two failures. If you roll a 20 on the d20, you regain 1 Hit Point.<BR>Damage at 0 Hit Points.<BR>If you take any damage while you have 0 Hit Points, you suffer a Death Saving Throw failure. If the damage is from a Critical Hit, you suffer two failures instead. If the damage equals or exceeds your Hit Point maximum, you die.<BR>Stabilizing a Character<BR>You can take the Help action to try to stabilize a creature with 0 Hit Points, which requires a successful DC 10 Wisdom (Medicine) check.<BR>A Stable creature doesn’t make Death Saving Throws even though it has 0 Hit Points, but it still has the Unconscious condition. If the creature takes damage, it stops being Stable and starts making Death Saving Throws again. A Stable creature that isn’t healed regains 1 Hit Point after 1d4 hours.",
`Dying`
],
[
"burrowing",
/nonmatching string to prevent accidental triggering/i,
"A creature that has a Burrow Speed can use that speed to move through sand, earth, mud, or ice. The creature can’t burrow through solid rock unless the creature has a trait that allows it to do so. See also “Speed.",
`Burrowing`
],
[
"dodging",
/nonmatching string to prevent accidental triggering/i,
"If you take the Dodge action, you gain the following benefits: until the start of your next turn, any attack roll made against you has Disadvantage if you can see the attacker, and you make Dexterity saving throws with Advantage.<BR>You lose these benefits if you have the Incapacitated condition or if your Speed is 0.",
`Dodging`
],
[
"inspiration",
/nonmatching string to prevent accidental triggering/i,
"If you (a player character) have Heroic Inspiration, you can expend it to reroll any die immediately after rolling it, and you must use the new roll.<BR>If you gain Heroic Inspiration but already have it, it’s lost unless you give it to a player character who lacks it.",
`Inspiration`
],
[
"TemporaryHP",
/nonmatching string to prevent accidental triggering/i,
"Temporary Hit Points aren’t actual hit points; they are a buffer against damage, a pool of Hit Points that protect you from injury.<BR>When you have temporary Hit Points and take damage, the temporary Hit Points are lost first, and any leftover damage carries over to your normal Hit Points. For example, if you have 5 temporary Hit Points and take 7 damage, you lose the temporary Hit Points and then take 2 damage.<BR>Because temporary Hit Points are separate from your actual Hit Points, they can exceed your hit point maximum. A character can, therefore, be at full Hit Points and receive temporary Hit Points.<BR>Healing can’t restore temporary Hit Points, and they can’t be added together. If you have temporary Hit Points and receive more of them, you decide whether to keep the ones you have or to gain the new ones. For example, if a spell grants you 12 temporary Hit Points when you already have 10, you can have 12 or 10, not 22.<BR>If you have 0 Hit Points, receiving temporary Hit Points doesn’t restore you to consciousness or stabilize you. They can still absorb damage directed at you while you’re in that state, but only true Healing can save you.<BR>Unless a feature that grants you temporary Hit Points has a Duration, they last until they’re depleted or you finish a Long Rest.",
`TempHP2`
]
]
// END SET STATUS CONDITIONS OR TOKEN MARKERS
//Creates Handouts
function createHandoutIfMissing(name, html, gmnotes, avatar)
{
if(!name) return;
if(!html && !gmnotes && !avatar) return; // nothing to set
const existing = findObjs(
{
_type: "handout",
name
})[0];
if(existing) return;
const handout = createObj("handout",
{
name,
inplayerjournals: "all",
archived: false
});
const props = {};
if(html) props.notes = html;
if(gmnotes) props.gmnotes = gmnotes;
if(avatar) props.avatar = avatar;
handout.set(props);
}
const buttonstyle = `"background-color:#702c91; border-style:none;border-radius:0px 0px 0px 0px; margin:3px 2px 3px 0px; text-decoration:none;display:inline-block;color:#e6e6e6; font-family:Arial; font-size:13px; padding:0px 7px"`;
const publicButtonStyle = `"background-color:#702c91; border-style:none;border-radius:10px 0px 0px 10px; margin:3px 2px 3px 3px; text-decoration:none;display:inline-block;color:#e6e6e6; font-family:Arial; font-size:13px; padding:0px 3px"`;
const markerButtonStyle = `"background-color:#702c91; border-style:none;border-radius:0px 10px 10px 0px; margin:3px 3px 3px 0px; text-decoration:none;display:inline-block;color:#e6e6e6; font-family:Arial; font-size:13px; padding:0px 3px"`;
const saveButtonstyle = `"background-color:#ce0f69; border-width:0px;border-radius:13px; margin:3px; text-transform:capitalize;text-decoration:none;display:inline-block;color:#fff; font-family:Arial; font-size:13px; padding:0px 7px"`;
const groupSaveButtonstyle = `"background-color:#ce0f69; border-width:0px;border-radius:13px 0px 0px 13px; margin:3px 1px 3px 3px; text-transform:capitalize;text-decoration:none;display:inline-block;color:#fff; font-family:Arial; font-size:13px; padding:0px 7px"`;
const applyDamageButtonstyle = `"background-color:#ce0f69; border-width:0px;border-radius:0px 13px 13px 0px; margin:3px 3px 3px 1px; text-transform:capitalize;text-decoration:none;display:inline-block;color:#fff; font-family:Arial; font-size:13px; padding:0px 7px"`;
const simpleButtonstyle = `"background-color:#702c91; border-style:none;border-radius:2px; margin:3px 2px 3px 0px; text-decoration:none;display:inline-block;color:#e6e6e6; font-family:Arial; font-size:13px; padding:0px 7px"`;
const conditionnamestyle = `"background-color:#702c91; border-style:none;border-radius:6px 6px 0px 0px; margin:-8px -8px 3px -8px; font-weight:bold;text-transform:capitalize;text-decoration:none;display:block;text-align:center;color:#e6e6e6; font-family:Arial; font-size:13px; padding:0px 7px"`;
const reportstyle = `"display: block; background-color:#aaa; border-radius:6px; text-decoration:none;color:#111; font-family:Arial; font-size:13px; padding: 8px;"`;
const preportstyle = `"display: block; background-color:#aaa; border-radius:6px; text-decoration:none;color:#111; font-family:Arial; font-size:13px; padding: 8px;"`;
const regexForTitles = /<a style='background-color: transparent;padding: 0px;color: #702c91;display: inline-block;border: none;' href='!condef incapacitated'>incapacitated<\/a>/;
const buttonbox = `<div style='position:relative;left: -5px; top: -30px; margin-bottom: -34px; min-height:30px; border: solid 1px #444; border-radius:4px; background-color:#000; color:#ddd; display:block'>`;
const buttonboxUnshifted = `<div style='position:relative;left: -5px; top: min-height:30px; border: solid 1px #444; border-radius:4px; background-color:#000;display:block'>`;
const buttonMenuStyle = `"display:block; border:1px solid #555; padding:3px; border-radius:4px; background-color:#bbb;"`;
const printChar = '<span style="font-family: pictos">w</a>';
const helpHTML = `<h2>Condefinition</h2><h3>What it does</h3><p>Condefinition reads incoming roll templates and looks for imposed conditions and saving throws. It display a button(s) in chat that allow you to quickly apply a corresponding token marker, define the condition, track concentration, roll saving throws and/or apply damage from spells or effects that are triggered by saving throws.</p><ul><li>If the roll template contains a saving throw, it gives a button for the saving throw. Press the button and click on a target to have it roll the appropriate save. If you have <b>GroupCheck</b> installed, it will run a groupcheck save. If you have <b><a href=\"https://app.roll20.net/forum/post/3631602/script-groupcheck-roll-checks-saves-et-cetera-for-many-tokens-at-once/?pageforid=4359153#post-4359153\">Apply Damage</a></b> installed, it will run through the steps to do a save and apply damage.</li><li>If the roll template contains an imposed condition, it will create a button to define the condition. If there is a cross reference in the definition of the condition, it will create an inline link. You can also hover over the button for the text. You can use this button to whisper the text to yourself, or broadcast to the players.</li><li>You can also toggle that condition on any selected tokens. Assigning token markers requires installing <b>TokenMod</b>, and for greater facility, <b>LibTokenMarkers</b>. It comes with the default Status Markers assigned, but the script creates a configuration handout that can be edited to use custom token markers. Instructions are included later in this handout.</li><li>If you installed this Mod using Roll20 One-Click, it should automatically install <b>GroupCheck</b>, <b>TokenMod</b>, and <b>LibTokenMarkers</b> if they are not already present. <b><a href=\"https://app.roll20.net/forum/post/3631602/script-groupcheck-roll-checks-saves-et-cetera-for-many-tokens-at-once/?pageforid=4359153#post-4359153\">Apply Damage</a></b> needs to be installed manually if you want its functionality.</li><li>Besides the official conditions, this also tracks mentions in chat for many common features that benefit from markers, such as raging, using Hunter's Mark, Hexblade's Curse and more. Each of these has buttons to toggle or define the effect.</li><li>The marker for the Concentrating condition also tracks concentration, and prompts for a Constitution Saving Throw when the token takes damage. See below for details. </li><li>This script has been written to work on Classic or Jumpgate, and with the 2014 and/or 2024 sheets for 5e D&D. Instructions for using this with <b>Condition Sync </b>(2024 sheet only) are included below in the configuration section. A dedicated user could probably adapt this for other sheets, but you would need to install the code manually. Contact me for guidance if you need it, but you will need a decent understanding of JavaScript.</li></ul><h3>What it can't do</h3><p>Currently, there are some limitations:</p><ul><li>This is built for GMs to facilitate running NPCs. Although most of the functions will work with PCs as well, and buttons should display for any player whose actions generate them, not every bit of it is player-accessible</li><li>The conditions are matched to tokens and their markers, not character sheets. This is the intended behavior as each instance of a goblin (for example) can have its own imposed conditions. The only exception is if you are using <b>Condition Sync</b> on the 2024 sheet. In this case, Roll20 will sync PC sheet conditions with the appropriate token markers and vice versa)</li><li>I have tried to catch every variation of condition wording, but I have probably missed a few incidences, particularly in products which do not adhere well to the WotC style.</li><li>In this iteration, all buttons and definitions are whispered to the controller of the NPC, typically the GM. If there is interest, I may change this to obey the whisper settings of the NPC, but I did not want to spam the chat. </li></ul><h3>Helper Scripts</h3><ul><li>Required: <b>Token-mod</b>, <b>libTokenMarkers</b></li><li>Improved by: <b>GroupCheck</b>, <b><a href=\"https://app.roll20.net/forum/post/3631602/script-groupcheck-roll-checks-saves-et-cetera-for-many-tokens-at-once/?pageforid=4359153#post-4359153\">Apply Damage</a></b></li></ul><h2>Operation</h2><h3><b>Buttons</b></h3><p>Every time a condition is implied by something in a chat roll template, or if the report function is used on a selected token, the script produces a button. Each button has three parts.</p><p>The middle, largest part of the button will send a message tot he GM in chat, that defines the condition. Sometimes, this will have links to other conditions that the condition imposes. Such as an <i>Unconscious</i> character is also <i>Incapacitated</i>.</p><p>The left side of the button has a word balloon graphic. This also send the definition to chat, but in this case, it is visible to all players.</p><p>The right hand side of the button shows the marker associated with that condition. It will toggle the marker for any and all selected tokens.</p><p><img src=\"https://files.d20.io/images/442935594/yOS7eoRAux8WyT5rvSFaLg/original.png?1748567284\"></p><p><br></p><h3><b>List All Common Condition Definitions</b></h3><p>Condefinition can produce a reference palette of all official condition buttons.<span style=\"background-color: rgba( 0 , 0 , 0 , 0 )\"> Type <code>!condef-all</code> to display the report. Note that the script tracks more markers than this, such as \"Raging\", or \"Marked\". These are just the official <i>conditions</i> defined by the rules.</span></p><p><img src=\"https://files.d20.io/images/442933995/z7UHtU9JRZgfR0p0vx_H4g/original.png?1748566537\"></p><p><br></p><h3>Concentration</h3><p>Condefintion will monitor if the token taking damage has a defined concentration marker on it. If you reduce the hit point bar of a concentrating token, the script will prompt you to make the appropriate Constitution save.</p><p>Example. \"Morrigan\" just took 30 hp of damage while concentrating on a spell. The Script notes that the concentration marker was active, calculates the saving throw and produces a button that will cause the selected token to roll a saving throw. Note: In order to make this script work with both the 2014 and 2024 sheets, the <b>Group Check</b> mod is required and configured for your sheet(s). If you installed Condefinition via Roll20 One Click, it should have installed all helper scripts automatically. See the first section of this handout for more details. </p><p><img src=\"https://files.d20.io/images/442936255/oTJKREx0B8Dwp5TQ6VGxyg/original.png?1748567553\"></p><p><br></p><h3>Report</h3><p>Condefintion also allows you to select any number of tokens and run <code>!condef-report</code>. The script produces a set of report buttons for each selected token that has a defined condition marker on it. In this case, the sub-buttons that toggle token markers will only affect the respective token, and that token does not need to be selected.</p><p><img src=\"https://files.d20.io/images/442937172/myYkaSLzPA8hqYG9xKlu_g/original.png?1748568068\"></p><p><br></p><h3>Automation of Abilities that Force Saving Throws</h3><p>This feature requires both <b>Group Check</b>, and the manually installed script<span style=\"font-family: "proxima nova" , , , "system-ui" , "segoe ui" , "roboto" , , "ubuntu" , "cantarell" , "helvetica neue" , sans-serif\"> </span><b style=\"font-family: "proxima nova" , , , "system-ui" , "segoe ui" , "roboto" , , "ubuntu" , "cantarell" , "helvetica neue" , sans-serif\"><a href=\"https://app.roll20.net/forum/post/3631602/script-groupcheck-roll-checks-saves-et-cetera-for-many-tokens-at-once/?pageforid=4359153#post-4359153\">Apply Damage</a></b> in order to function. It also requires that the spell or feature of a creature is sent to chat with the Description turned on. In some cases this requires rolling damage or clicking the roll template button that shows the spell description. There are too many sheet variables to account for here, but in short, the keywords needed in order to trigger the script must have been sent to chat. </p><p><img src=\"https://files.d20.io/images/442940114/kWl_PCGDYV8f_9cs_jw_Yw/original.png?1748569736\"></p><p>The button produced is very similar to the concentration check button. In this case, the left half will roll a saving throw for all selected tokens. If you have Apply Damage installed, it will also walk you through the steps necessary to resolve the roll and apply damage accordingly. Note that this function will work on a combination of selected 2014 and 2024 tokens.</p><p><img src=\"https://files.d20.io/images/442941123/VzdgD5qvSLHRqwKBX2rXNw/original.png?1748570402\"></p><p><br></p><h2>Configuration</h2><p>Out of the box, this script will support conditions defined by both the 2014 and 2024 rule sets. It also can switch between the default token markers or my own Easy to Read token markers. This latter is entirely for my own convenience, and they are not required in any way for the script to function.</p><h4>The Condefinitions Handout</h4><p>Type <code>!condef help</code> or <code>!condef config</code> in chat to call up the configuration controls. </p><p>Condefinition uses a lot of Regular Expressions (search code) to find and apply token markers and definitions. It reads these from a handout called Condefinitions. You can edit this handout manually. It has all of the code needed to define the conditions wrapped in a code block. You can edit the names, the definitions, the search code and the name of the corresponding token marker. The edited text must be clean plain text wrapped in code tags using the Code style button in the editor. Most users will only need to change the name of the token marker to match their chosen set.</p><p><b>Configuring for Condition Sync ( D&D by Roll20 (2024) sheet only)</b></p><p>Condition Sync is a feature that keeps character sheet conditions and token markers in sync. For example, if a player applies the \"Blinded\" condition on their character sheet, the corresponding token marker will be automatically applied to their token. Likewise, if the \"Blinded\" token marker is applied to the token, the character sheet will update to reflect the condition.</p><p>This functionality works by renaming 15 specific token markers to match the naming format recognized by the 2024 character sheet (e.g., sheet-blinded). (There are actually 16 syncing conditions, but the \"Custom\" condition is a catchall that is outside of the purview of this script).</p><p><b>To enable Condition Sync in this script:</b></p><ol><li><b>Choose a 2024 rule set using the appropriate button.</b></li><li><b>Click the \"Use Condition-Sync Marker Names\" button.</b></li><li><b>Finally, click \"Apply Configuration\" to save the changes.</b></li></ol><p><br></p><p>If you don't feel comfortable editing the other code, or do so and make a mistake which breaks the handout, you can reset to the default using the buttons in the configuration panel. The script contains defaults for the 2014 and 2024 rule sets, using the default token markers provided by Roll20. <i>I original wrote this script using my own Marketplace set, so if you have installed my \"Easy to Read Token Markers\" set, then there are also buttons that set defaults for those. This Marketplace set is honestly for my own convenience, and the script does not require this set in any way.</i></p><p>Each Condefintion definition is four lines long, and separated by an empty line.</p><ul><li><b>Line 1</b> is the name of the condition</li><li><b>Line 2</b> is the Regular Expression (REGEX) used to trigger the operation of the script. It's a list of search terms that match condition and effect names. If you are not familiar with REGEX, just leave that line alone and you should be fine.</li><li><b>Line 3</b> is the definition of the condition or effect.. This must all be on one line, and can accept simple html styling.</li><li><b>Line 4</b> is the name of the associated token marker.</li></ul><p>After editing and saving the configuration document, you must press the \"Update Conditions\" button in the chat configuration controls. This will apply the conditions immediately.</p><p><b>It is strongly advised that if you do make home brew changes, you duplicate the Condefinitions Handout to use as a backup.</b> the controls can \"reset to factory specs\", but they cannot undo breaking changes.</p><p>If you create a configuration that uses a marketplace set of Token Markers that you prefer, feel free to share with others. It can be copied and pasted between games, so long as you are careful to paste clean text only (hold down the shift key while pasting, or copy from a plain text editor), and wrap the whole thing in the \"Code\" style.</p><p><img src=\"https://files.d20.io/images/442943259/dwGOgHA6nb3a8fRJIat8Dw/original.png?1748571846\"></p><p><br></p><p><br></p>`;
//createHandoutIfMissing("Help: Condefinition", helpHTML);
createHandoutIfMissing("Help: Condefinition", helpHTML, "", "https://s3.amazonaws.com/files.d20.io/images/442783616/hDkduTWDpcVEKomHnbb6AQ/med.png");
//Only include these buttons if the user has the Easy To Read markers from the Marketplace
const marketButtons = markerExists("Hexed3")
? `<b>Easy to Read Markers (Marketplace)</b><br>` +
makeGenericButton("2014", "!condef-easy2014") + ` ` +
makeGenericButton("2024", "!condef-easy2024") + `<br>`
: "";
const getConfigMessage = () => `<br>` +
`Condefinition uses a lot of Regular Expressions (search code) to find and apply token markers and definitions. It reads these from a handout called Condefinitions. This handout has all of the code needed to define the conditions in a code block. You can edit the names, the definitions, the search code and the name of the corresponding token marker. The edited text must be clean plain text wrapped in code tags using the Code style button in the editor. Most users will only need to change the name of the token marker to match their chosen set.<BR><BR>If you don't feel comfortable editing the other code, or do so and make a mistake which breaks the handout, you can reset to the default using the buttons in the configuration panel. The script contains defaults for the 2014 and 2024 rule sets, using the default token markers provided by Roll20. I original wrote this script using my own Marketplace set, so if you have installed my "Easy to Read Token Markers" set, then there are also buttons that set defaults for those. This Marketplace set is honestly for my own convenience, and the script does not require this set in any way.` + `<BR><BR>` +
`<div style=${buttonMenuStyle}>` +
(marketButtons ?
`<B>Choose your Rule and Marker Sets:</B>` + `<br><br>` +
`<B>Generic Token Markers</B>`
:`<B>Choose Your Rule Set</B>`) + `<br>` +
makeGenericButton("2014", "!condef-generic2014") + ` ` +
makeGenericButton("2024", "!condef-generic2024") + `<br>` +
marketButtons +
`<br>` +
/* `<B>Modify for Condition Sync?</B>` + `<br>` +
makeGenericButton("Use Condition-Sync Marker Names", "!condef-sheetmarkers") + `<br><br>` +
*/
`<B>Edit Manually from Handout</B>` + `<br>` +
makeGenericButton("Open Handout", getHandoutURL("Condefinitions")) +
`<br><br>` +
`<B>Critical Last Step:</B>` + `<br>` +
makeGenericButton("Apply Configuration", "!condef-loadconditions") + `<br>` +
`</div>` +
`<br>` +
`<div style="text-align:center` + makeGenericButton(" Help ", getHandoutURL("Help: Condefinition")) + `</div>`
;
let conditionsArray = [];
loadConditionsFromHandout();
let ConcentrationMarker = (conditionsArray.find(([k]) => k.toLowerCase() === "concentrating") || [, , , "death-zone"])[3];
let condefConcentrationMarker = "status_" + ConcentrationMarker;
let applyDamageIsInstalled = false;
//check for dependencies
if(typeof ApplyDamage !== "undefined")
{
applyDamageIsInstalled = true;
}
let groupCheckIsInstalled = false;
if(typeof GroupCheck !== "undefined")
{
groupCheckIsInstalled = true;
}
const version = '1.0.3';
log('Condefinitions v' + version + ' is ready! --offset ' + API_Meta.Condefinition.offset + ' for the D&D 5th Edition by Roll20 Sheet. Command is !condef-help');
loadConditionsFromHandout();
function getHandoutURL(handoutName)
{
const handout = findObjs(
{
_type: "handout",
name: handoutName
})[0];
if(!handout)
{
sendMessage("No Condefintions Handout could be found. Press one of the default settings buttons to create a new handout.")
return `"No Handout was found"`;
}
else
{
const id = handout.get("_id");
return `https://journal.roll20.net/handout/${id}`;
}
}
function getConditionIcon(conditionName)
{
const iconMap = {
blinded: "bleeding-eye",
charmed: "chained-heart",
// Extend as needed
};
return iconMap[conditionName] || "question-mark";
}
function decodeHTMLEntities(str)
{
return str
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/&/g, "&");
}
function deserializeConditionsMultiline(text)
{
return text
.replace(/^<pre>|<\/pre>$/g, "") // Strip <pre> tags if present
.split(/\r?\n\r?\n/) // Split on double line breaks
.map(block =>
{
const [key, regexStr, description, label] = block.trim()
.split(/\r?\n/);
const regexMatch = regexStr?.match(/^\/(.+)\/([gimuy]*)$/);
const regex = regexMatch ? new RegExp(regexMatch[1], regexMatch[2]) : /.^/;
return [key, regex, description, label];
})
.filter(entry => entry.length === 4); // Prevents malformed rows
}
function loadConditionsFromHandout()
{
const handout = findObjs(
{
_type: "handout",
name: "Condefinitions"
})[0];
if(!handout)
{
log("⚠️ Handout 'Condefinitions' not found. Creating new Config handout.");
writeConditionsToHandoutMultilinePlainText(defaultConditionsArray);
loadConditionsFromHandout();
createHandoutIfMissing("Condefinitions", helpHTML);
sendMessage(getConfigMessage(), "Condefinition Configuration");
return;
}
handout.get("notes", function(notes)
{
const parsed = deserializeConditionsMultiline(notes);
if(parsed.length)
{
conditionsArray = parsed;
}
else
{
log("⚠️ No valid conditions found in 'Condefinitions' handout.");
}
});
}
function serializeConditionsArrayMultiline(array)
{
return array.map(([key, regex, description, label]) =>
`${key}\n${regex.toString()}\n${description}\n${label}`
)
.join("\n\n");
}
function writeConditionsToHandoutMultilinePlainText(conditionsArray)
{
const content = conditionsArray.map(([key, regex, description, label]) =>
{
const regexString = regex.toString(); // /.../flags
// const icon = getConditionIcon(key); // optional helper for icon name
return `${key}\n${regex.toString()}\n${description}\n${label}`;
})
.join("\n\n");
const escaped = content
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
const wrapped = `<pre>${escaped}</pre>`;
let handout = findObjs(
{
_type: "handout",
name: "Condefinitions"
})[0];
if(!handout)
{
handout = createObj("handout",
{
name: "Condefinitions",
inplayerjournals: "all",
archived: false
});
}
handout.set(
{
notes: wrapped
});
}
function readAndParseConditions()
{
const handout = findObjs(
{
_type: "handout",
name: "Condefinitions"
})[0];
if(!handout)
{
log("⚠️ Handout not found.");
return;
}
handout.get("notes", function(notes)
{
const stripped = notes.replace(/^<pre>/i, "")
.replace(/<\/pre>$/i, "");
const decoded = stripped
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/&/g, "&");
const parsed = deserializeConditionsMultiline(notes);
return parsed
});
}
function mergeDescriptionsWithClassicDefinitions(originalArray, newConditions)
{
return originalArray.map(entry =>
{
const [key, regex, , marker] = entry;
const match = newConditions.find(def => def[0] === key);
const newDescription = match ? match[1] : entry[2]; // fallback to original description if no match
return [key, regex, newDescription, marker];
});
}
function sendMessage(message, title)
{
let theTitle = (title ? `<div style=${conditionnamestyle}>${title} </div>` : "");
let theMessage = (message ? ` <div style=${reportstyle}>${theTitle}${message}</div>` : "");
sendChat("Condefinition", `/w gm ${theMessage}`, null,
{
noarchive: true
});
}
// writeConditionsToHandoutMultilinePlainText(conditionsArray);
const input = `<pre>blinded
/(be|and|is|magically|become|becomes|is either) blinded|blinded condition/i
Example description here
bleeding-eye
Blinded</pre>`;
const result = deserializeConditionsMultiline(input);
let buttons = "";
let reportText = "";
function makeButton(conditionName, descriptionText, tokenMarker, tokenID)
{
let tmLabel = `<span style="font-family: pictos">L</span>`;
//let markerName = tokenMarker;
let markerName = ((tokenMarker.includes(";;")) ? tokenMarker.split(";;")[0] : tokenMarker);
if('undefined' !== typeof libTokenMarkers && undefined !== libTokenMarkers.getStatus(markerName)
.url)
{
let tmImage = libTokenMarkers.getStatus(markerName)
.url;
if(undefined !== tmImage && tmImage.length > 0)
{
tmLabel = `<img src="${tmImage}"style="margin-top:-1px; height:12px;">`;
}
}
buttons = buttons + `<div style="display:inline-block"><a href="!pcondef ${conditionName}" title="${descriptionText.replace(/<BR>/g, " ").replace(regexForTitles, "incapacitated")}" style=${publicButtonStyle}>${printChar}</a><a href="!condef ${conditionName}" title="${descriptionText.replace(/<BR>/g, " ").replace(regexForTitles, "incapacitated")}" style=${buttonstyle}>${conditionName}</a><a href="!condef-toggle ${tokenMarker} ${((undefined !== tokenID) ? " --ignore-selected --ids " + tokenID : "")}" style=${markerButtonStyle}>${tmLabel}</a></div>`;
}
function makeGenericButton(name, link)
{
return `<div style="display:inline-block"><a href="${link}" style=${simpleButtonstyle}>${name}</a></div>`;
}
//Concentration Observer
function concentrationCheck(obj, prev)
{
if(obj.get("statusmarkers")
.includes(condefConcentrationMarker) || obj.get("statusmarkers")
.includes(ConcentrationMarker) || obj.get(condefConcentrationMarker))
{
// if (obj.get(condefConcentrationMarker)) {
if(prev["bar1_value"] > obj.get("bar1_value"))
{
let final_conc_DC = 10;
let calc_conc_DC = (prev["bar1_value"] - obj.get("bar1_value")) / 2;
if(calc_conc_DC > final_conc_DC)
{
final_conc_DC = Math.floor(calc_conc_DC);
}
// let tokenName = obj.get("name");
let theMessage = `! &{template:spell} {{name=Concentration}}{{savedc=${final_conc_DC}}} {{description=Make a DC ${final_conc_DC} Constitution saving throw}}{{Concentration=1}}`;
// let theMessage = `this should print`;
sendChat("gm", theMessage);
}
}
}
//Event Handlers
on("change:graphic:bar1_value", concentrationCheck);
if(typeof(TokenMod) === 'object') TokenMod.ObserveTokenChange(concentrationCheck);
if('undefined' !== typeof SmartAoE && SmartAoE.ObserveTokenChange)
{
SmartAoE.ObserveTokenChange(function(obj, prev)
{
concentrationCheck(obj, prev);
});
}
//Condition report creator. Use !condef for GM only, pcondef for player report. Follow by condition names separated by spaces. !condef-all returns buttons for all conditions, for reference
on('chat:message', function(msg)
{
if(msg.type === "api" && msg.content === "!condef-generic2014")
{
writeConditionsToHandoutMultilinePlainText(mergeDescriptionsWithClassicDefinitions(defaultConditionsArray, definitions2014));
loadConditionsFromHandout();
sendMessage("Condefinitions handout has been reset to Default token markers using the 2014 condition definitions");
return;
}
if(msg.type === "api" && msg.content === "!condef-generic2024")
{
writeConditionsToHandoutMultilinePlainText(mergeDescriptionsWithClassicDefinitions(defaultConditionsArray, definitions2024));
loadConditionsFromHandout();
sendMessage("Condefinitions handout has been reset to Default token markers using the 2024 condition definitions");
return;
}
if(msg.type === "api" && msg.content === "!condef-easy2014")
{
writeConditionsToHandoutMultilinePlainText(mergeDescriptionsWithClassicDefinitions(defaultConditionsArray_EasyToRead, definitions2014));
loadConditionsFromHandout();
sendMessage("Condefinitions handout has been reset to the Easy to Read token markers using the 2014 condition definitions");
return;
}
if(msg.type === "api" && msg.content === "!condef-easy2024")
{
writeConditionsToHandoutMultilinePlainText(mergeDescriptionsWithClassicDefinitions(defaultConditionsArray_EasyToRead, definitions2024));
loadConditionsFromHandout();
sendMessage("Condefinitions handout has been reset to the Easy to Read token markers using the 2024 condition definitions");
return;
}
if (msg.type === 'api' && msg.content === '!condef-sheetmarkers' && playerIsGM(msg.playerid)) {
const handout = findObjs({ _type: "handout", name: "Condefinitions" })[0];
if (!handout) {
sendMessage("⚠️ Handout 'Condefinitions' not found.", "Condefinition");
return;
}
handout.get("notes", function (notes) {
const stripped = notes.replace(/^<pre>/i, "").replace(/<\/pre>$/i, "");
const decoded = stripped
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/&/g, "&");
const targetConditions = new Set([
"blinded", "charmed", "custom", "deafened", "exhausted",
"frightened", "grappled", "incapacitated", "invisible",
"paralyzed", "petrified", "poisoned", "prone",
"restrained", "stunned", "unconscious"
]);
const blocks = decoded.split(/\n\s*\n/);
const updatedBlocks = blocks.map(block => {
const lines = block.trim().split('\n');
if (lines.length !== 4) return block;
const [name, regex, description, marker] = lines;
const key = name.trim().toLowerCase();
if (targetConditions.has(key)) {
return [name, regex, description, `sheet-${key}`].join('\n');
}
return block;
});
const updated = updatedBlocks.join('\n\n');
const escaped = updated
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
const wrapped = `<pre>${escaped}</pre>`;
handout.set({ notes: wrapped });
sendMessage("✅ 16 condition token markers updated to sheet-compatible names.", "Condefinition");
});
}
if(msg.type === "api" && msg.content === "!condef-loadconditions")
{
loadConditionsFromHandout();
ConcentrationMarker = (conditionsArray.find(([k]) => k.toLowerCase() === "concentrating") || [, , , "death-zone"])[3];
condefConcentrationMarker = "status_" + ConcentrationMarker;
sendMessage("Condition definitions reloaded from handout.");
return;
}
if(msg.type === "api" && (msg.content === "!condef-config" || msg.content === "!condef-help"))
{
createHandoutIfMissing("Help: Condefinition", helpHTML, "", "https://s3.amazonaws.com/files.d20.io/images/442783616/hDkduTWDpcVEKomHnbb6AQ/med.png");
sendMessage(getConfigMessage(), "Condefinition Configuration");
return;
}
if('api' === msg.type && msg.content.match(/^!(condef|pcondef|condef-all|condef-report|condef-toggle)/))
{
let args = msg.content.split(" ");
let sender = msg.who;
if(msg.content === '!condef-all')
{
let message = `! &{template:noecho} {{description= blinded condition charmed condition deafened condition exhausted condition frightened condition grappled condition incapacitated condition invisible condition paralyzed condition petrified condition poisoned condition prone condition restrained condition stunned condition unconscious condition concentration check}}`;
sendChat("gm", message, null,
{
noarchive: true
});
message = "";
return;
}
let messagePrefix = ((msg.content.includes('pcondef')) ? '' : '/w ' + sender + ' ');
let theCommand = ((msg.content.includes("pcondef")) ? "!pcondef" : "!condef");
//selected vs target handler
if(msg.content.includes('condef-toggle ') && msg.content.length > 15)
{
let tokenMarker = msg.content.split('condef-toggle ')[1];
let message = '';
if(msg.selected)
{
//message = `!token-mod --set statusmarkers|!${tokenMarker}`;
let ids = msg.selected.reduce((m, o) => [...m, o._id], []);
message = `!token-mod --api-as ${msg.playerid} --set statusmarkers|!${tokenMarker} --ids ${ids.join(' ')}`;
//message = `!token-mod --api-as ${msg.playerid} --set statusmarkers|!${tokenMarker}`;
}
else
{
message = messagePrefix + buttonboxUnshifted + '<a style = ' + buttonstyle + ' href ="!token-mod --set statusmarkers|!' + tokenMarker + ' --ids @{target|token_id}">No token is selected.<BR>Click here to pick a target.</a></div>';
}
sendChat("", message, null,
{
noarchive: true
});
return;
}
if(msg.content === '!condef-report')
{
buttons = "";
let selected = (msg.selected);
if(selected)
{
_.each(selected, function(token)
{
let tok = getObj("graphic", token._id);
let tokName = tok.get("name") || "unnamed token";
let tokID = tok.get("_id");
let markers = tok.get("statusmarkers")
.replace(/::/g, ";;");
if(markers)
{
for(let i = 0; i < conditionsArray.length; i++)
{
let name = conditionsArray[i][0];
let descriptionText = conditionsArray[i][2];
let tokenMarker = conditionsArray[i][3];
if(markers.includes(tokenMarker))
{
makeButton(name, descriptionText, tokenMarker, tokID);
}
}
let message = buttonbox + "<span style= 'font-weight:bold; margin: 0px 2px 0px 3px; color:#ddd'>" + tokName + "</span>" + buttons + "</div>";
sendChat("", messagePrefix + message, null,
{
noarchive: true
});
buttons = "";
}
});
}
else
{
sendMessage("Select one or more tokens with conditions on them");
}
return;
}
for(let i = 0; i < conditionsArray.length; i++)
{
let reportName = conditionsArray[i][0];
let reportDescription = conditionsArray[i][2];
if(undefined !== args[1] && args[1] === reportName)
{
reportDescription = reportDescription.replace("!condef", theCommand);
reportText = `<div style=${((messagePrefix === "") ? preportstyle : reportstyle)}><div style=${conditionnamestyle}>${reportName} </div>${reportDescription.replace(/</g, "<").replace(/>/g, ">")}</div>`;
}
}
if(undefined !== reportText && reportText.length > 0)
{
sendChat("", messagePrefix + reportText, null,
{
noarchive: true
});
}
}
//Roll Template Interception
if((undefined !== msg.rolltemplate && msg.rolltemplate.match(/npcfullatk|npcdmg|npcaction|traits|atkdmg|spell|condefinitions|spelloutput|noecho/g)) || (msg.content.match(/dnd-2024/g)))
{
//log (msg.content);
let sender = msg.who;
let messagePrefix = '/w ' + sender + ' ';
let saveAbility = "";
let saveMatches = "";
let theAbility = "";
let saveDC = "";
let conCheck = "";
let concentrationButton = "";
saveMatches = msg.content.match(/DC\s(\d\d)\s(Strength|Dexterity|Constitution|Intelligence|Wisdom|Charisma)\ssaving throw/i);
if(msg.rolltemplate !== "spell" && msg.rolltemplate !== "atkdmg" && null !== saveMatches && saveMatches.length === 3)
{
saveDC = saveMatches[1];
saveAbility = saveMatches[2];
}
//msg echo to console is disabled
if(msg.rolltemplate === "spell" || msg.rolltemplate === "atkdmg" || msg.rolltemplate === "spelloutput" || (msg.content.match(/dnd-2024 dnd-2024--/g)))
{
/*log(msg.content);*/
saveAbility = msg.content.match(/(Strength|Dexterity|Constitution|Intelligence|Wisdom|Charisma)\ssav(e|ing throw)/i) || "";
if(saveAbility.length > 0)
{
saveAbility = saveAbility[1] || "";
}
saveDC = ((msg.rolltemplate === "spell" || msg.rolltemplate === "spelloutput") ? msg.content.match(/{{savedc=(\d+)}}/) : msg.content.match(/{{mod=DC(\d+)}}/)) || msg.content.match(/DC\s(\d+)/) || "";
conCheck = ((msg.rolltemplate === "spell" && msg.content.match(/{{name=Concentration/)) ? "Concentration Check" : "");
// if (conCheck!==""){
// makeButton("Concentrating", "makes a con check", "concentrating");
// }
// concentrationButton = ((conCheck==="") ? "" : "<BR>" + buttons);
//log("concentrationButton = " + concentrationButton);
if(saveDC.length > 0)
{
saveDC = saveDC[1] || "";
}
}
if(undefined !== saveAbility && null !== saveAbility)
{
theAbility = saveAbility.replace(/Strength/i, "str")
.replace(/Dexterity/i, "dex")
.replace(/Constitution/i, "con")
.replace(/Intelligence/i, "int")
.replace(/Wisdom/i, "wis")
.replace(/Charisma/i, "cha");
}
let saveButton = "";
if(theAbility.match(/(str|dex|con|int|wis|cha)/))
{
//for regular saves
saveButton = `<a href="! %{target|npc_${theAbility}}" style=${saveButtonstyle}>DC${saveDC} ${theAbility}</a> <span style = "color:#fff">${conCheck}${concentrationButton}</span>`;
//for groupcheck
if(groupCheckIsInstalled)
{
saveAbility = saveAbility.charAt(0)
.toUpperCase() + saveAbility.slice(1);
saveButton = `<a href="!group-check --${saveAbility} Save" style=${groupSaveButtonstyle}>DC${saveDC} ${theAbility}</a> <span style = "color:#fff">${conCheck}${concentrationButton}</span>`;
if(applyDamageIsInstalled && conCheck !== "Concentration Check")
{
saveButton = saveButton + `<a href="!group-check --hideformula --public --${saveAbility} Save --process --subheader vs DC ${saveDC} --button ApplyDamage !apply-damage ~dmg ?{Damage} ~type ?{Damage on Save|Half,half|None,none} ~DC ${saveDC} ~saves RESULTS(,) ~ids IDS(,)" style=${applyDamageButtonstyle}>Dmg</a>`;
}
}
}
for(let i = 0; i < conditionsArray.length; i++)
{
let name = conditionsArray[i][0];
let descriptionText = conditionsArray[i][2];
let tokenMarker = conditionsArray[i][3];
if(undefined !== name)
{
if(msg.content.match(conditionsArray[i][1]))
{
makeButton(name, descriptionText, tokenMarker);
}
}
}
let GMSaveButton = saveButton;
if(!playerIsGM(msg.playerid) && msg.playerid !== "API")
{
saveButton = "";
}
if(buttons.length > 0 || saveButton.length > 0)
{
let message = buttonbox + saveButton + buttons + "</div>";
sendChat("", messagePrefix + message, null,
{
noarchive: true
});
if(!messagePrefix.includes(' (GM)') && msg.rolltemplate !== "noecho")
{
message = buttonbox + GMSaveButton + buttons + "</div>";
if(conCheck !== "Concentration Check")
{
sendChat("", '/w gm ' + message, null,
{
noarchive: true
});
}
}
buttons = "";
}
}
});
});
{
try
{
throw new Error('');
}
catch (e)
{
API_Meta.Condefinition.lineCount = (parseInt(e.stack.split(/\n/)[1].replace(/^.*:(\d+):.*$/, '$1'), 10) - API_Meta.Condefinition.offset);
}
}
| 0 | 0.884595 | 1 | 0.884595 | game-dev | MEDIA | 0.928076 | game-dev | 0.691036 | 1 | 0.691036 |
Lothrazar/Cyclic | 6,412 | src/main/java/com/lothrazar/cyclic/registry/MaterialRegistry.java | package com.lothrazar.cyclic.registry;
import java.util.List;
import com.lothrazar.cyclic.ModCyclic;
import com.lothrazar.cyclic.material.EmeraldArmorMaterial;
import com.lothrazar.cyclic.material.GemArmorMaterial;
import com.lothrazar.cyclic.material.GlowingArmorMaterial;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.BlockTags;
import net.minecraft.world.item.ArmorMaterial;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.Tier;
import net.minecraft.world.item.Tiers;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraftforge.common.ForgeConfigSpec.DoubleValue;
import net.minecraftforge.common.ForgeConfigSpec.IntValue;
import net.minecraftforge.common.ForgeTier;
import net.minecraftforge.common.TierSortingRegistry;
import net.minecraftforge.fml.common.Mod;
@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)
public class MaterialRegistry {
//
// public static final CreativeModeTab BLOCK_GROUP = new CreativeModeTab(ModCyclic.MODID) {
//
// @Override
// public ItemStack makeIcon() {
// return new ItemStack(BlockRegistry.TRASH.get());
// }
// };
// public static final CreativeModeTab ITEM_GROUP = new CreativeModeTab(ModCyclic.MODID + "items") {
//
// @Override
// public ItemStack makeIcon() {
// return new ItemStack(ItemRegistry.GEM_AMBER.get());
// }
// };
public static IntValue EMERALD_BOOTS;
public static IntValue EMERALD_LEG;
public static IntValue EMERALD_CHEST;
public static IntValue EMERALD_HELM;
public static IntValue OBS_BOOTS;
public static IntValue OBS_LEG;
public static IntValue OBS_CHEST;
public static IntValue OBS_HELM;
public static DoubleValue EMERALD_TOUGH;
public static DoubleValue EMERALD_DMG;
public static DoubleValue OBS_TOUGH;
public static DoubleValue OBS_DMG;
public static class ArmorMats {
public static final ArmorMaterial EMERALD = new EmeraldArmorMaterial();
public static final ArmorMaterial GEMOBSIDIAN = new GemArmorMaterial();
public static final ArmorMaterial GLOWING = new GlowingArmorMaterial();
}
public static class ToolMats {
//NB is outside
public static final Tier NETHERBRICK = TierSortingRegistry.registerTier(
//harvestLevel, uses, toolSpeed, damage, enchantability
new ForgeTier(Tiers.IRON.getLevel(),
(Tiers.IRON.getUses() + Tiers.GOLD.getUses()) / 2,
(Tiers.IRON.getSpeed() + Tiers.GOLD.getSpeed()) / 2,
(Tiers.IRON.getAttackDamageBonus() + Tiers.GOLD.getAttackDamageBonus()) / 2,
Tiers.GOLD.getEnchantmentValue() + 2,
BlockTags.create(new ResourceLocation(ModCyclic.MODID, "needs_nether_bricks_tool")),
() -> Ingredient.of(Items.NETHER_BRICKS)),
new ResourceLocation(ModCyclic.MODID, "nether_bricks"),
List.of(Tiers.GOLD), List.of(Tiers.DIAMOND));
//
//WOOD
//then stuff between wood and stone
public static final Tier SANDSTONE = TierSortingRegistry.registerTier(
//harvestLevel, uses, toolSpeed, damage, enchantability
new ForgeTier(Tiers.STONE.getLevel(),
Tiers.STONE.getUses() + 20, Tiers.STONE.getSpeed(),
(Tiers.WOOD.getAttackDamageBonus() + Tiers.STONE.getAttackDamageBonus()) / 2,
Tiers.IRON.getEnchantmentValue() + 2,
BlockTags.create(new ResourceLocation(ModCyclic.MODID, "needs_sandstone_tool")),
() -> Ingredient.of(Items.SANDSTONE)),
new ResourceLocation(ModCyclic.MODID, "sandstone"),
List.of(Tiers.WOOD), List.of(Tiers.STONE));
//after stone then COPPER
public static final Tier COPPER = TierSortingRegistry.registerTier(
//harvestLevel, uses, toolSpeed, damage, enchantability
new ForgeTier(Tiers.IRON.getLevel(),
(Tiers.STONE.getUses() + Tiers.IRON.getUses()) / 2, (Tiers.STONE.getSpeed() + Tiers.IRON.getSpeed()) / 2, // uses aka durability
(Tiers.STONE.getAttackDamageBonus() + Tiers.IRON.getAttackDamageBonus()) / 2,
Tiers.DIAMOND.getEnchantmentValue() + 2,
BlockTags.create(new ResourceLocation(ModCyclic.MODID, "needs_copper_tool")),
() -> Ingredient.of(Items.COPPER_INGOT)),
new ResourceLocation(ModCyclic.MODID, "copper"),
List.of(Tiers.STONE), List.of(Tiers.IRON));
//then RON
//after iron is AMYTH
public static final Tier AMETHYST = TierSortingRegistry.registerTier(
//harvestLevel, uses, toolSpeed, damage, enchantability
new ForgeTier(Tiers.IRON.getLevel(),
Tiers.IRON.getUses() + 5, Tiers.IRON.getSpeed() + 0.2F, // uses aka durability
Tiers.IRON.getAttackDamageBonus() + 0.1F, Tiers.GOLD.getEnchantmentValue() * 2,
BlockTags.create(new ResourceLocation(ModCyclic.MODID, "needs_amethyst_tool")),
() -> Ingredient.of(Items.AMETHYST_SHARD)),
new ResourceLocation(ModCyclic.MODID, "amethyst"),
List.of(Tiers.IRON), List.of(Tiers.DIAMOND));
//then diamond
//after diamond is
public static final Tier EMERALD = TierSortingRegistry.registerTier(
//harvestLevel, uses, toolSpeed, damage, enchantability
new ForgeTier(Tiers.DIAMOND.getLevel(),
Tiers.DIAMOND.getUses() + Tiers.GOLD.getUses(), Tiers.DIAMOND.getSpeed() * 2, // uses aka durability
EMERALD_DMG.get().floatValue(), Tiers.GOLD.getEnchantmentValue() + 1,
BlockTags.create(new ResourceLocation(ModCyclic.MODID, "needs_emerald_tool")),
() -> Ingredient.of(Items.EMERALD)),
new ResourceLocation(ModCyclic.MODID, "emerald"),
List.of(Tiers.DIAMOND), List.of(Tiers.NETHERITE));
//then netherite then
//after netherite
public static final Tier GEMOBSIDIAN = TierSortingRegistry.registerTier(
//harvestLevel, uses, toolSpeed, damage, enchantability
new ForgeTier(Tiers.NETHERITE.getLevel(),
Tiers.DIAMOND.getUses() * 4, Tiers.DIAMOND.getSpeed() * 4, // uses aka durability
OBS_DMG.get().floatValue(), Tiers.GOLD.getEnchantmentValue() + 1,
BlockTags.create(new ResourceLocation(ModCyclic.MODID, "needs_obsidian_tool")),
() -> Ingredient.of(ItemRegistry.GEM_OBSIDIAN.get())),
new ResourceLocation(ModCyclic.MODID, "gem_obsidian"),
List.of(Tiers.NETHERITE), List.of());
}
}
| 0 | 0.927818 | 1 | 0.927818 | game-dev | MEDIA | 0.993548 | game-dev | 0.910332 | 1 | 0.910332 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.