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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2amigos/yii2-grid-view-library | 2,712 | src/GridView.php | <?php
/*
* This file is part of the 2amigos/yii2-grid-view-library project.
* (c) 2amigOS! <http://2amigos.us/>
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace dosamigos\grid;
use dosamigos\grid\contracts\RegistersClientScriptInterface;
use dosamigos\grid\contracts\RunnableBehaviorInterface;
use yii\base\Behavior;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
class GridView extends \yii\grid\GridView
{
/**
* @var Behavior[]|array the attached behaviors (behavior name => behavior).
*/
private $gBehaviors = [];
/**
* @inheritdoc
*/
public function init()
{
Html::addCssClass($this->options, 'da-grid-view');
Html::addCssClass($this->tableOptions, 'da-grid-view-table');
parent::init();
}
/**
* @inheritdoc
*/
public function behaviors()
{
return ArrayHelper::merge($this->gBehaviors, parent::behaviors());
}
/**
* Provide the option to be able to set behaviors on GridView configuration.
*
* @param array $behaviors
*/
public function setBehaviors(array $behaviors = [])
{
$this->gBehaviors = $behaviors;
}
/**
* Enhanced version of the render section to be able to work with behaviors that work directly with the
* template.
*
* @param string $name
*
* @return bool|mixed|string
*/
public function renderSection($name)
{
$method = 'render' . ucfirst(str_replace(['{', '}'], '', $name)); // methods are prefixed with 'render'!
$behaviors = $this->getBehaviors();
if (is_array($behaviors)) {
foreach ($behaviors as $behavior) {
/** @var Object $behavior */
if ($behavior->hasMethod($method)) {
return call_user_func([$behavior, $method]);
}
}
}
return parent::renderSection($name);
}
/**
* @inheritdoc
*/
public function run()
{
parent::run();
$this->runBehaviors();
}
/**
* Runs behaviors, registering their scripts if necessary
*/
protected function runBehaviors()
{
$behaviors = $this->getBehaviors();
if (is_array($behaviors)) {
foreach ($behaviors as $behavior) {
if ($behavior instanceof RegistersClientScriptInterface) {
$behavior->registerClientScript();
}
if($behavior instanceof RunnableBehaviorInterface) {
$behavior->run();
}
}
}
}
}
| 412 | 0.846559 | 1 | 0.846559 | game-dev | MEDIA | 0.464648 | game-dev | 0.895238 | 1 | 0.895238 |
mattheww/sgfmill | 2,202 | doc/examples.rst | Examples
========
Reading from a file
-------------------
::
from sgfmill import sgf
with open("foo.sgf", "rb") as f:
game = sgf.Sgf_game.from_bytes(f.read())
winner = game.get_winner()
board_size = game.get_size()
root_node = game.get_root()
b_player = root_node.get("PB")
w_player = root_node.get("PW")
for node in game.get_main_sequence():
print(node.get_move())
Recording a game
----------------
::
from sgfmill import sgf
game = sgf.Sgf_game(size=13)
for move_info in ...:
node = game.extend_main_sequence()
node.set_move(move_info.colour, move_info.move)
if move_info.comment is not None:
node.set("C", move_info.comment)
with open(pathname, "wb") as f:
f.write(game.serialise())
Modifying a game
----------------
::
>>> from sgfmill import sgf
>>> game = sgf.Sgf_game.from_string("(;FF[4]GM[1]SZ[9];B[ee];W[ge])")
>>> root_node = game.get_root()
>>> root_node.set("RE", "B+R")
>>> new_node = game.extend_main_sequence()
>>> new_node.set_move("b", (2, 3))
>>> [node.get_move() for node in game.get_main_sequence()]
[(None, None), ('b', (4, 4)), ('w', (4, 6)), ('b', (2, 3))]
>>> game.serialise()
b'(;FF[4]CA[UTF-8]GM[1]RE[B+R]SZ[9];B[ee];W[ge];B[dg])\n'
See also the :script:`show_sgf.py` and :script:`split_sgf_collection.py`
example scripts.
The example scripts
-------------------
The following example scripts are available in the :file:`examples/` directory
of the Sgfmill source distribution.
They may be independently useful, as well as illustrating the library API.
See the top of each script for further information.
See :ref:`running the example scripts <running the example scripts>` for notes
on making the :mod:`!sgfmill` package available for use with the example
scripts.
.. script:: show_sgf.py
Prints an ASCII diagram of the position from an |sgf| file.
This demonstrates the :mod:`~sgfmill.sgf`, :mod:`~sgfmill.sgf_moves`, and
:mod:`~sgfmill.ascii_boards` modules.
.. script:: split_sgf_collection.py
Splits a file containing an |sgf| game collection into multiple files.
This demonstrates the parsing functions from the :mod:`!sgf_grammar` module.
| 412 | 0.606145 | 1 | 0.606145 | game-dev | MEDIA | 0.324423 | game-dev | 0.686244 | 1 | 0.686244 |
mangosArchives/serverZero_Rel19 | 4,729 | src/scripts/scripts/eastern_kingdoms/blackrock_mountain/blackrock_spire/boss_overlord_wyrmthalak.cpp | /**
* ScriptDev2 is an extension for mangos providing enhanced features for
* area triggers, creatures, game objects, instances, items, and spells beyond
* the default database scripting in mangos.
*
* Copyright (C) 2006-2013 ScriptDev2 <http://www.scriptdev2.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
/**
* ScriptData
* SDName: Boss_Overlord_Wyrmthalak
* SD%Complete: 100
* SDComment: None
* SDCategory: Blackrock Spire
* EndScriptData
*/
#include "precompiled.h"
enum
{
SPELL_BLASTWAVE = 11130,
SPELL_SHOUT = 23511,
SPELL_CLEAVE = 20691,
SPELL_KNOCKAWAY = 20686,
NPC_SPIRESTONE_WARLORD = 9216,
NPC_SMOLDERTHORN_BERSERKER = 9268
};
const float afLocations[2][4] =
{
{ -39.355381f, -513.456482f, 88.472046f, 4.679872f},
{ -49.875881f, -511.896942f, 88.195160f, 4.613114f}
};
struct MANGOS_DLL_DECL boss_overlordwyrmthalakAI : public ScriptedAI
{
boss_overlordwyrmthalakAI(Creature* pCreature) : ScriptedAI(pCreature) {Reset();}
uint32 m_uiBlastWaveTimer;
uint32 m_uiShoutTimer;
uint32 m_uiCleaveTimer;
uint32 m_uiKnockawayTimer;
bool m_bSummoned;
void Reset() override
{
m_uiBlastWaveTimer = 20000;
m_uiShoutTimer = 2000;
m_uiCleaveTimer = 6000;
m_uiKnockawayTimer = 12000;
m_bSummoned = false;
}
void JustSummoned(Creature* pSummoned) override
{
if (pSummoned->GetEntry() != NPC_SPIRESTONE_WARLORD && pSummoned->GetEntry() != NPC_SMOLDERTHORN_BERSERKER)
{
return;
}
if (m_creature->getVictim())
{
Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0);
pSummoned->AI()->AttackStart(pTarget ? pTarget : m_creature->getVictim());
}
}
void UpdateAI(const uint32 uiDiff) override
{
// Return since we have no target
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
{
return;
}
// BlastWave
if (m_uiBlastWaveTimer < uiDiff)
{
DoCastSpellIfCan(m_creature, SPELL_BLASTWAVE);
m_uiBlastWaveTimer = 20000;
}
else
{ m_uiBlastWaveTimer -= uiDiff; }
// Shout
if (m_uiShoutTimer < uiDiff)
{
DoCastSpellIfCan(m_creature, SPELL_SHOUT);
m_uiShoutTimer = 10000;
}
else
{ m_uiShoutTimer -= uiDiff; }
// Cleave
if (m_uiCleaveTimer < uiDiff)
{
DoCastSpellIfCan(m_creature->getVictim(), SPELL_CLEAVE);
m_uiCleaveTimer = 7000;
}
else
{ m_uiCleaveTimer -= uiDiff; }
// Knockaway
if (m_uiKnockawayTimer < uiDiff)
{
DoCastSpellIfCan(m_creature, SPELL_KNOCKAWAY);
m_uiKnockawayTimer = 14000;
}
else
{ m_uiKnockawayTimer -= uiDiff; }
// Summon two Beserks
if (!m_bSummoned && m_creature->GetHealthPercent() < 51.0f)
{
m_creature->SummonCreature(NPC_SPIRESTONE_WARLORD, afLocations[0][0], afLocations[0][1], afLocations[0][2], afLocations[0][3], TEMPSUMMON_TIMED_DESPAWN, 300000);
m_creature->SummonCreature(NPC_SMOLDERTHORN_BERSERKER, afLocations[1][0], afLocations[1][1], afLocations[1][2], afLocations[1][3], TEMPSUMMON_TIMED_DESPAWN, 300000);
m_bSummoned = true;
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_boss_overlordwyrmthalak(Creature* pCreature)
{
return new boss_overlordwyrmthalakAI(pCreature);
}
void AddSC_boss_overlordwyrmthalak()
{
Script* pNewScript;
pNewScript = new Script;
pNewScript->Name = "boss_overlord_wyrmthalak";
pNewScript->GetAI = &GetAI_boss_overlordwyrmthalak;
pNewScript->RegisterSelf();
}
| 412 | 0.92978 | 1 | 0.92978 | game-dev | MEDIA | 0.995084 | game-dev | 0.940838 | 1 | 0.940838 |
ErikKalkoken/evebuddy | 2,274 | internal/app/storage/characterattributes.go | package storage
import (
"context"
"fmt"
"time"
"github.com/ErikKalkoken/evebuddy/internal/app"
"github.com/ErikKalkoken/evebuddy/internal/app/storage/queries"
)
func (st *Storage) GetCharacterAttributes(ctx context.Context, characterID int32) (*app.CharacterAttributes, error) {
wrapErr := func(err error) error {
return fmt.Errorf("UpdateOrCreGetCharacterAttributesateCharacterAttributes character ID %d: %w", characterID, err)
}
if characterID == 0 {
return nil, wrapErr(app.ErrInvalid)
}
o, err := st.qRO.GetCharacterAttributes(ctx, int64(characterID))
if err != nil {
return nil, wrapErr(convertGetError(err))
}
return characterAttributeFromDBModel(o), nil
}
type UpdateOrCreateCharacterAttributesParams struct {
ID int64
BonusRemaps int
CharacterID int32
Charisma int
Intelligence int
LastRemapDate time.Time
Memory int
Perception int
Willpower int
}
func (st *Storage) UpdateOrCreateCharacterAttributes(ctx context.Context, arg UpdateOrCreateCharacterAttributesParams) error {
wrapErr := func(err error) error {
return fmt.Errorf("UpdateOrCreateCharacterAttributes %+v: %w", arg, err)
}
if arg.CharacterID == 0 {
return wrapErr(app.ErrInvalid)
}
arg2 := queries.UpdateOrCreateCharacterAttributesParams{
CharacterID: int64(arg.CharacterID),
BonusRemaps: int64(arg.BonusRemaps),
Charisma: int64(arg.Charisma),
Intelligence: int64(arg.Intelligence),
Memory: int64(arg.Memory),
Perception: int64(arg.Perception),
Willpower: int64(arg.Willpower),
}
if !arg.LastRemapDate.IsZero() {
arg2.LastRemapDate.Time = arg.LastRemapDate
arg2.LastRemapDate.Valid = true
}
err := st.qRW.UpdateOrCreateCharacterAttributes(ctx, arg2)
if err != nil {
return wrapErr(err)
}
return nil
}
func characterAttributeFromDBModel(o queries.CharacterAttribute) *app.CharacterAttributes {
o2 := &app.CharacterAttributes{
ID: o.ID,
BonusRemaps: int(o.BonusRemaps),
CharacterID: int32(o.CharacterID),
Charisma: int(o.Charisma),
Intelligence: int(o.Intelligence),
Memory: int(o.Memory),
Perception: int(o.Perception),
Willpower: int(o.Willpower),
}
if o.LastRemapDate.Valid {
o2.LastRemapDate = o.LastRemapDate.Time
}
return o2
}
| 412 | 0.825254 | 1 | 0.825254 | game-dev | MEDIA | 0.233597 | game-dev | 0.87981 | 1 | 0.87981 |
Lcbx/GdScript2All | 2,669 | results/example_controller.hpp |
#ifndef EXAMPLE_CONTROLLER_H
#define EXAMPLE_CONTROLLER_H
#include <godot_cpp/godot.hpp>
#include <godot_cpp/variant/array.hpp>
#include <godot_cpp/variant/dictionary.hpp>
#include <godot_cpp/classes/character_body3d.hpp>
#include <godot_cpp/classes/kinematic_collision3d.hpp>
using namespace godot;
class Character : public CharacterBody3D {
GDCLASS(Character, CharacterBody3D);
public:
/* 3D character controller
usable for both players and AI
for players, input is handled an overlay script which sets local_dir and view_dir
speed and acceleration is based on movementState which is a Ressource (see MovementState.gd)
*/
// TODO:
// * add ways to get over obstacles
// * implement fall damage
// * hold crouch key to increase gravity ?
// * hold jump key to lower gravity strength ?
// * change gravity into a non-linear acceleration ?
/* movement physics */
protected:
const double MIN_JUMP_VELOCITY = 3.5;
const double MAX_Y_SPEED = 10.0;
const Vector3 XZ = Vector3(1.0, 0.0, 1.0);
const Vector3 YZ = Vector3(0.0, 1.0, 1.0);
const Vector3 XY = Vector3(1.0, 1.0, 0.0);
static double gravity;
Variant coyoteTime = Utils.createTimer(this, 0.15);
Variant jumpCoolDown = Utils.createTimer(this, 0.15);
/* movement state / animations */
public:
void _process(double delta) override;
/* signal changedState(Ref<MovementEnum> state) */
/* signal collision(Ref<KinematicCollision3D> collision) */
/* signal movement(Vector3 dir, double speed) */
/* signal jump(double speed) */
enum MovementEnum {crouch, walk, run, fall};
protected:
Array movements;
Character::MovementEnum movementState = MovementEnum::walk;
public:
void set_movementState(Character::MovementEnum value);
Character::MovementEnum get_movementState();
protected:
Character::MovementEnum wantedMovement = MovementEnum::walk;
/* steering variables */
Vector3 _global_mov_dir = Vector3();
Vector3 global_mov_dir = Vector3();
public:
Vector3 get_global_mov_dir();
// NOTE: local_dir is normalized on the xz plane by Overlay
void set_global_mov_dir(Vector3 value);
protected:
Vector3 _local_dir;
Vector3 local_dir;
public:
Vector3 get_local_dir();
void set_local_dir(Vector3 value);
/* view */
double calculate_ground_speed();
/* signal viewDirChanged(Vector3 euler) */
protected:
Vector3 view_dir = Vector3();
public:
void set_view_dir(Vector3 value);
Vector3 get_view_dir();
void set_movements(Array value);
Array get_movements();
void set_wantedMovement(Character::MovementEnum value);
Character::MovementEnum get_wantedMovement();
static void _bind_methods();
};
VARIANT_ENUM_CAST(Character::MovementEnum)
#endif // EXAMPLE_CONTROLLER_H
| 412 | 0.744748 | 1 | 0.744748 | game-dev | MEDIA | 0.982268 | game-dev | 0.746642 | 1 | 0.746642 |
hiddenswitch/Spellsource | 5,480 | spellsource-game/src/main/java/com/hiddenswitch/spellsource/draft/DraftContext.java | package com.hiddenswitch.spellsource.draft;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import net.demilich.metastone.game.cards.CardCatalogue;
import net.demilich.metastone.game.cards.catalogues.ClasspathCardCatalogue;
import java.util.function.Consumer;
/**
* Stores data and logic relating to drafting cards.
* <p>
* This context does not itself start a game. Use a {@link net.demilich.metastone.game.GameContext} for that.
* <p>
* Create a draft context using {@link #DraftContext()}, then set its behaviour using {@link
* #setBehaviour(DraftBehaviour)}. The default behaviour <b>never</b> replies to any choices.
* <p>
* To start the draft, call {@link #accept(Handler)} with a handler when the draft is done.
* <p>
* Retrieve the current state of the draft using {@link #getPublicState()}.
*
* @see DraftLogic for the specific rules regarding which cards are chosen to show to a player during a draft.
*/
public class DraftContext implements Consumer<Handler<AsyncResult<DraftContext>>> {
private DraftLogic logic = new DraftLogic(this);
private PublicDraftState publicState = new PublicDraftState();
private PrivateDraftState privateState = new PrivateDraftState();
private DraftBehaviour behaviour = new NullDraftBehaviour();
private CardCatalogue cardCatalogue = ClasspathCardCatalogue.INSTANCE;
private Handler<AsyncResult<DraftContext>> handleDone;
/**
* Creates a new draft context with a {@link NullDraftBehaviour} as the default.
*/
public DraftContext() {
}
/**
* Starts a draft.
*
* @param done Called when all the draft choices have been made and the deck the player has been constructing is ready
* to play.
*/
public void accept(Handler<AsyncResult<DraftContext>> done) {
if (handleDone != null) {
throw new RuntimeException("Stale draft context.");
}
handleDone = done;
// Resume from the correct spot
switch (getPublicState().getStatus()) {
case NOT_STARTED:
getLogic().initializeDraft();
selectHero();
break;
case SELECT_HERO:
selectHero();
break;
case IN_PROGRESS:
selectCard();
break;
case COMPLETE:
done.handle(Future.succeededFuture(this));
break;
}
}
public CardCatalogue getCardCatalogue() {
return cardCatalogue;
}
protected void selectHero() {
getBehaviour().chooseHeroAsync(getPublicState().getHeroClassChoices(), this::onHeroSelected);
}
/**
* This handler should be called with the player's champion selection.
*
* @param choice The champion selected by the player.
*/
public void onHeroSelected(AsyncResult<String> choice) {
if (choice.failed()) {
// TODO: Retry
return;
}
getLogic().startDraft(choice.result());
selectCard();
}
protected void selectCard() {
getBehaviour().chooseCardAsync(getLogic().getCardChoices(), this::onCardSelected);
}
/**
* This handler should be called whenever the player makes a card choice.
*
* @param selectedCardResult The index of the card chosen in {@link PublicDraftState#getCurrentCardChoices()}.
*/
public void onCardSelected(AsyncResult<Integer> selectedCardResult) {
getLogic().selectCard(selectedCardResult.result());
if (getLogic().isDraftOver()) {
// TODO: What do we do when we're done? We should create a deck and populate it
if (handleDone != null) {
handleDone.handle(Future.succeededFuture(this));
}
} else {
selectCard();
}
}
/**
* Gets the draft logic.
*
* @return
*/
public DraftLogic getLogic() {
return logic;
}
public void setLogic(DraftLogic logic) {
this.logic = logic;
}
/**
* Gets the public draft state. This state is safe to share with the end user and does not leak any information that
* would advantage the player unfairly in the drafting process.
*
* @return
*/
public PublicDraftState getPublicState() {
return publicState;
}
public void setPublicState(PublicDraftState publicState) {
this.publicState = publicState;
}
/**
* Gets the private draft state. In practice, this is the pre-generated list of cards the player will see, according
* to the current rules in {@link DraftLogic}. This should never be shared with an end-user, since it can be used to
* cheat.
*
* @return
*/
public PrivateDraftState getPrivateState() {
return privateState;
}
public void setPrivateState(PrivateDraftState privateState) {
this.privateState = privateState;
}
/**
* Gets the behaviour to which draft requests are delegated.
*
* @return
*/
public DraftBehaviour getBehaviour() {
return behaviour;
}
/**
* Sets the behaviour. Beware of the {@link NullDraftBehaviour}--it does not ever call its callbacks, so the {@link
* DraftContext} is never completed by it.
*
* @param behaviour
*/
public void setBehaviour(DraftBehaviour behaviour) {
this.behaviour = behaviour;
}
public DraftContext withLogic(final DraftLogic logic) {
this.setLogic(logic);
return this;
}
public DraftContext withPublicState(final PublicDraftState publicState) {
this.setPublicState(publicState);
return this;
}
public DraftContext withPrivateState(final PrivateDraftState privateState) {
this.setPrivateState(privateState);
return this;
}
public DraftContext withBehaviour(final DraftBehaviour behaviour) {
this.setBehaviour(behaviour);
return this;
}
protected void notifyPublicStateChanged() {
getBehaviour().notifyDraftState(getPublicState());
}
}
| 412 | 0.966097 | 1 | 0.966097 | game-dev | MEDIA | 0.26385 | game-dev | 0.936731 | 1 | 0.936731 |
ggnkua/Atari_ST_Sources | 12,293 | ASM/Mystic Bytes (MSB)/sv2011 invitro/falcon/3rd_party/WinSDL/include/SDL_scancode.h | /*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2009 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
/**
* \file SDL_scancode.h
*/
#ifndef _SDL_scancode_h
#define _SDL_scancode_h
#include "SDL_stdinc.h"
/**
* \enum SDL_scancode
*
* \brief The SDL keyboard scancode representation.
*
* Values of this type are used to represent keyboard keys, among other places
* in the \link SDL_keysym::scancode key.keysym.scancode \endlink field of the
* SDL_Event structure.
*
* The values in this enumeration are based on the USB usage page standard:
* http://www.usb.org/developers/devclass_docs/Hut1_12.pdf
*/
typedef enum
{
SDL_SCANCODE_UNKNOWN = 0,
/* These values are from usage page 0x07 (USB keyboard page) */
SDL_SCANCODE_A = 4,
SDL_SCANCODE_B = 5,
SDL_SCANCODE_C = 6,
SDL_SCANCODE_D = 7,
SDL_SCANCODE_E = 8,
SDL_SCANCODE_F = 9,
SDL_SCANCODE_G = 10,
SDL_SCANCODE_H = 11,
SDL_SCANCODE_I = 12,
SDL_SCANCODE_J = 13,
SDL_SCANCODE_K = 14,
SDL_SCANCODE_L = 15,
SDL_SCANCODE_M = 16,
SDL_SCANCODE_N = 17,
SDL_SCANCODE_O = 18,
SDL_SCANCODE_P = 19,
SDL_SCANCODE_Q = 20,
SDL_SCANCODE_R = 21,
SDL_SCANCODE_S = 22,
SDL_SCANCODE_T = 23,
SDL_SCANCODE_U = 24,
SDL_SCANCODE_V = 25,
SDL_SCANCODE_W = 26,
SDL_SCANCODE_X = 27,
SDL_SCANCODE_Y = 28,
SDL_SCANCODE_Z = 29,
SDL_SCANCODE_1 = 30,
SDL_SCANCODE_2 = 31,
SDL_SCANCODE_3 = 32,
SDL_SCANCODE_4 = 33,
SDL_SCANCODE_5 = 34,
SDL_SCANCODE_6 = 35,
SDL_SCANCODE_7 = 36,
SDL_SCANCODE_8 = 37,
SDL_SCANCODE_9 = 38,
SDL_SCANCODE_0 = 39,
SDL_SCANCODE_RETURN = 40,
SDL_SCANCODE_ESCAPE = 41,
SDL_SCANCODE_BACKSPACE = 42,
SDL_SCANCODE_TAB = 43,
SDL_SCANCODE_SPACE = 44,
SDL_SCANCODE_MINUS = 45,
SDL_SCANCODE_EQUALS = 46,
SDL_SCANCODE_LEFTBRACKET = 47,
SDL_SCANCODE_RIGHTBRACKET = 48,
SDL_SCANCODE_BACKSLASH = 49, /**< Located at the lower left of the return key on ISO keyboards and at the right end of the QWERTY row on ANSI keyboards. Produces REVERSE SOLIDUS (backslash) and VERTICAL LINE in a US layout, REVERSE SOLIDUS and VERTICAL LINE in a UK Mac layout, NUMBER SIGN and TILDE in a UK Windows layout, DOLLAR SIGN and POUND SIGN in a Swiss German layout, NUMBER SIGN and APOSTROPHE in a German layout, GRAVE ACCENT and POUND SIGN in a French Mac layout, and ASTERISK and MICRO SIGN in a French Windows layout. */
SDL_SCANCODE_NONUSHASH = 50, /**< ISO USB keyboards actually use this code instead of 49 for the same key, but all OSes I've seen treat the two codes identically. So, as an implementor, unless your keyboard generates both of those codes and your OS treats them differently, you should generate SDL_SCANCODE_BACKSLASH instead of this code. As a user, you should not rely on this code because SDL will never generate it with most (all?) keyboards. */
SDL_SCANCODE_SEMICOLON = 51,
SDL_SCANCODE_APOSTROPHE = 52,
SDL_SCANCODE_GRAVE = 53, /**< Located in the top left corner (on both ANSI and ISO keyboards). Produces GRAVE ACCENT and TILDE in a US Windows layout and in US and UK Mac layouts on ANSI keyboards, GRAVE ACCENT and NOT SIGN in a UK Windows layout, SECTION SIGN and PLUS-MINUS SIGN in US and UK Mac layouts on ISO keyboards, SECTION SIGN and DEGREE SIGN in a Swiss German layout (Mac: only on ISO keyboards), CIRCUMFLEX ACCENT and DEGREE SIGN in a German layout (Mac: only on ISO keyboards), SUPERSCRIPT TWO and TILDE in a French Windows layout, COMMERCIAL AT and NUMBER SIGN in a French Mac layout on ISO keyboards, and LESS-THAN SIGN and GREATER-THAN SIGN in a Swiss German, German, or French Mac layout on ANSI keyboards. */
SDL_SCANCODE_COMMA = 54,
SDL_SCANCODE_PERIOD = 55,
SDL_SCANCODE_SLASH = 56,
SDL_SCANCODE_CAPSLOCK = 57,
SDL_SCANCODE_F1 = 58,
SDL_SCANCODE_F2 = 59,
SDL_SCANCODE_F3 = 60,
SDL_SCANCODE_F4 = 61,
SDL_SCANCODE_F5 = 62,
SDL_SCANCODE_F6 = 63,
SDL_SCANCODE_F7 = 64,
SDL_SCANCODE_F8 = 65,
SDL_SCANCODE_F9 = 66,
SDL_SCANCODE_F10 = 67,
SDL_SCANCODE_F11 = 68,
SDL_SCANCODE_F12 = 69,
SDL_SCANCODE_PRINTSCREEN = 70,
SDL_SCANCODE_SCROLLLOCK = 71,
SDL_SCANCODE_PAUSE = 72,
SDL_SCANCODE_INSERT = 73, /**< insert on PC, help on some Mac keyboards (but does send code 73, not 117) */
SDL_SCANCODE_HOME = 74,
SDL_SCANCODE_PAGEUP = 75,
SDL_SCANCODE_DELETE = 76,
SDL_SCANCODE_END = 77,
SDL_SCANCODE_PAGEDOWN = 78,
SDL_SCANCODE_RIGHT = 79,
SDL_SCANCODE_LEFT = 80,
SDL_SCANCODE_DOWN = 81,
SDL_SCANCODE_UP = 82,
SDL_SCANCODE_NUMLOCKCLEAR = 83, /**< num lock on PC, clear on Mac keyboards */
SDL_SCANCODE_KP_DIVIDE = 84,
SDL_SCANCODE_KP_MULTIPLY = 85,
SDL_SCANCODE_KP_MINUS = 86,
SDL_SCANCODE_KP_PLUS = 87,
SDL_SCANCODE_KP_ENTER = 88,
SDL_SCANCODE_KP_1 = 89,
SDL_SCANCODE_KP_2 = 90,
SDL_SCANCODE_KP_3 = 91,
SDL_SCANCODE_KP_4 = 92,
SDL_SCANCODE_KP_5 = 93,
SDL_SCANCODE_KP_6 = 94,
SDL_SCANCODE_KP_7 = 95,
SDL_SCANCODE_KP_8 = 96,
SDL_SCANCODE_KP_9 = 97,
SDL_SCANCODE_KP_0 = 98,
SDL_SCANCODE_KP_PERIOD = 99,
SDL_SCANCODE_NONUSBACKSLASH = 100, /**< This is the additional key that ISO keyboards have over ANSI ones, located between left shift and Y. Produces GRAVE ACCENT and TILDE in a US or UK Mac layout, REVERSE SOLIDUS (backslash) and VERTICAL LINE in a US or UK Windows layout, and LESS-THAN SIGN and GREATER-THAN SIGN in a Swiss German, German, or French layout. */
SDL_SCANCODE_APPLICATION = 101, /**< windows contextual menu, compose */
SDL_SCANCODE_POWER = 102, /**< The USB document says this is a status flag, not a physical key - but some Mac keyboards do have a power key. */
SDL_SCANCODE_KP_EQUALS = 103,
SDL_SCANCODE_F13 = 104,
SDL_SCANCODE_F14 = 105,
SDL_SCANCODE_F15 = 106,
SDL_SCANCODE_F16 = 107,
SDL_SCANCODE_F17 = 108,
SDL_SCANCODE_F18 = 109,
SDL_SCANCODE_F19 = 110,
SDL_SCANCODE_F20 = 111,
SDL_SCANCODE_F21 = 112,
SDL_SCANCODE_F22 = 113,
SDL_SCANCODE_F23 = 114,
SDL_SCANCODE_F24 = 115,
SDL_SCANCODE_EXECUTE = 116,
SDL_SCANCODE_HELP = 117,
SDL_SCANCODE_MENU = 118,
SDL_SCANCODE_SELECT = 119,
SDL_SCANCODE_STOP = 120,
SDL_SCANCODE_AGAIN = 121, /*!< redo */
SDL_SCANCODE_UNDO = 122,
SDL_SCANCODE_CUT = 123,
SDL_SCANCODE_COPY = 124,
SDL_SCANCODE_PASTE = 125,
SDL_SCANCODE_FIND = 126,
SDL_SCANCODE_MUTE = 127,
SDL_SCANCODE_VOLUMEUP = 128,
SDL_SCANCODE_VOLUMEDOWN = 129,
/* not sure whether there's a reason to enable these */
/* SDL_SCANCODE_LOCKINGCAPSLOCK = 130, */
/* SDL_SCANCODE_LOCKINGNUMLOCK = 131, */
/* SDL_SCANCODE_LOCKINGSCROLLLOCK = 132, */
SDL_SCANCODE_KP_COMMA = 133,
SDL_SCANCODE_KP_EQUALSAS400 = 134,
SDL_SCANCODE_INTERNATIONAL1 = 135, /**< used on Asian keyboards, see footnotes in USB doc */
SDL_SCANCODE_INTERNATIONAL2 = 136,
SDL_SCANCODE_INTERNATIONAL3 = 137, /**< Yen */
SDL_SCANCODE_INTERNATIONAL4 = 138,
SDL_SCANCODE_INTERNATIONAL5 = 139,
SDL_SCANCODE_INTERNATIONAL6 = 140,
SDL_SCANCODE_INTERNATIONAL7 = 141,
SDL_SCANCODE_INTERNATIONAL8 = 142,
SDL_SCANCODE_INTERNATIONAL9 = 143,
SDL_SCANCODE_LANG1 = 144, /**< Hangul/English toggle */
SDL_SCANCODE_LANG2 = 145, /**< Hanja conversion */
SDL_SCANCODE_LANG3 = 146, /**< Katakana */
SDL_SCANCODE_LANG4 = 147, /**< Hiragana */
SDL_SCANCODE_LANG5 = 148, /**< Zenkaku/Hankaku */
SDL_SCANCODE_LANG6 = 149, /**< reserved */
SDL_SCANCODE_LANG7 = 150, /**< reserved */
SDL_SCANCODE_LANG8 = 151, /**< reserved */
SDL_SCANCODE_LANG9 = 152, /**< reserved */
SDL_SCANCODE_ALTERASE = 153, /**< Erase-Eaze */
SDL_SCANCODE_SYSREQ = 154,
SDL_SCANCODE_CANCEL = 155,
SDL_SCANCODE_CLEAR = 156,
SDL_SCANCODE_PRIOR = 157,
SDL_SCANCODE_RETURN2 = 158,
SDL_SCANCODE_SEPARATOR = 159,
SDL_SCANCODE_OUT = 160,
SDL_SCANCODE_OPER = 161,
SDL_SCANCODE_CLEARAGAIN = 162,
SDL_SCANCODE_CRSEL = 163,
SDL_SCANCODE_EXSEL = 164,
SDL_SCANCODE_KP_00 = 176,
SDL_SCANCODE_KP_000 = 177,
SDL_SCANCODE_THOUSANDSSEPARATOR = 178,
SDL_SCANCODE_DECIMALSEPARATOR = 179,
SDL_SCANCODE_CURRENCYUNIT = 180,
SDL_SCANCODE_CURRENCYSUBUNIT = 181,
SDL_SCANCODE_KP_LEFTPAREN = 182,
SDL_SCANCODE_KP_RIGHTPAREN = 183,
SDL_SCANCODE_KP_LEFTBRACE = 184,
SDL_SCANCODE_KP_RIGHTBRACE = 185,
SDL_SCANCODE_KP_TAB = 186,
SDL_SCANCODE_KP_BACKSPACE = 187,
SDL_SCANCODE_KP_A = 188,
SDL_SCANCODE_KP_B = 189,
SDL_SCANCODE_KP_C = 190,
SDL_SCANCODE_KP_D = 191,
SDL_SCANCODE_KP_E = 192,
SDL_SCANCODE_KP_F = 193,
SDL_SCANCODE_KP_XOR = 194,
SDL_SCANCODE_KP_POWER = 195,
SDL_SCANCODE_KP_PERCENT = 196,
SDL_SCANCODE_KP_LESS = 197,
SDL_SCANCODE_KP_GREATER = 198,
SDL_SCANCODE_KP_AMPERSAND = 199,
SDL_SCANCODE_KP_DBLAMPERSAND = 200,
SDL_SCANCODE_KP_VERTICALBAR = 201,
SDL_SCANCODE_KP_DBLVERTICALBAR = 202,
SDL_SCANCODE_KP_COLON = 203,
SDL_SCANCODE_KP_HASH = 204,
SDL_SCANCODE_KP_SPACE = 205,
SDL_SCANCODE_KP_AT = 206,
SDL_SCANCODE_KP_EXCLAM = 207,
SDL_SCANCODE_KP_MEMSTORE = 208,
SDL_SCANCODE_KP_MEMRECALL = 209,
SDL_SCANCODE_KP_MEMCLEAR = 210,
SDL_SCANCODE_KP_MEMADD = 211,
SDL_SCANCODE_KP_MEMSUBTRACT = 212,
SDL_SCANCODE_KP_MEMMULTIPLY = 213,
SDL_SCANCODE_KP_MEMDIVIDE = 214,
SDL_SCANCODE_KP_PLUSMINUS = 215,
SDL_SCANCODE_KP_CLEAR = 216,
SDL_SCANCODE_KP_CLEARENTRY = 217,
SDL_SCANCODE_KP_BINARY = 218,
SDL_SCANCODE_KP_OCTAL = 219,
SDL_SCANCODE_KP_DECIMAL = 220,
SDL_SCANCODE_KP_HEXADECIMAL = 221,
SDL_SCANCODE_LCTRL = 224,
SDL_SCANCODE_LSHIFT = 225,
SDL_SCANCODE_LALT = 226, /**< alt, option */
SDL_SCANCODE_LGUI = 227, /**< windows, command (apple), meta */
SDL_SCANCODE_RCTRL = 228,
SDL_SCANCODE_RSHIFT = 229,
SDL_SCANCODE_RALT = 230, /**< alt gr, option */
SDL_SCANCODE_RGUI = 231, /**< windows, command (apple), meta */
SDL_SCANCODE_MODE = 257, /* I'm not sure if this is really not covered by any of the above, but since there's a special KMOD_MODE for it I'm adding it here */
/* These values are mapped from usage page 0x0C (USB consumer page) */
SDL_SCANCODE_AUDIONEXT = 258,
SDL_SCANCODE_AUDIOPREV = 259,
SDL_SCANCODE_AUDIOSTOP = 260,
SDL_SCANCODE_AUDIOPLAY = 261,
SDL_SCANCODE_AUDIOMUTE = 262,
SDL_SCANCODE_MEDIASELECT = 263,
SDL_SCANCODE_WWW = 264,
SDL_SCANCODE_MAIL = 265,
SDL_SCANCODE_CALCULATOR = 266,
SDL_SCANCODE_COMPUTER = 267,
SDL_SCANCODE_AC_SEARCH = 268,
SDL_SCANCODE_AC_HOME = 269,
SDL_SCANCODE_AC_BACK = 270,
SDL_SCANCODE_AC_FORWARD = 271,
SDL_SCANCODE_AC_STOP = 272,
SDL_SCANCODE_AC_REFRESH = 273,
SDL_SCANCODE_AC_BOOKMARKS = 274,
/* These are values that Christian Walther added (for mac keyboard?) */
SDL_SCANCODE_BRIGHTNESSDOWN = 275,
SDL_SCANCODE_BRIGHTNESSUP = 276,
SDL_SCANCODE_DISPLAYSWITCH = 277, /**< display mirroring/dual display switch, video mode switch */
SDL_SCANCODE_KBDILLUMTOGGLE = 278,
SDL_SCANCODE_KBDILLUMDOWN = 279,
SDL_SCANCODE_KBDILLUMUP = 280,
SDL_SCANCODE_EJECT = 281,
SDL_SCANCODE_SLEEP = 282,
/* Add any other keys here */
SDL_NUM_SCANCODES = 512 /**< (not a key, just marks the number of scancodes for array bounds) */
} SDL_scancode;
#endif /* _SDL_scancode_h */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.736599 | 1 | 0.736599 | game-dev | MEDIA | 0.439704 | game-dev | 0.567598 | 1 | 0.567598 |
Ludovicus-Maior/WoW-Pro-Guides | 4,632 | WoWPro_Dailies/WoWPro_Dailies.lua | -- luacheck: globals WoWPro_DailiesDB Grail
-- luacheck: globals tonumber pairs
------------------------------
-- WoWPro_Dailies --
------------------------------
WoWPro.Dailies = WoWPro:NewModule("Dailies")
WoWPro:Embed(WoWPro.Dailies)
WoWPro.Dailies.Version = WoWPro.GetAddOnMetadata("WoWPro_Dailies", "Version")
-- Called before all addons have loaded, but after saved variables have loaded. --
function WoWPro.Dailies:OnInitialize()
-- Nothing for now
end
-- Called when the module is enabled, and on log-in and /reload, after all addons have loaded. --
function WoWPro.Dailies:OnEnable()
WoWPro:dbp("|cff33ff33Enabled|r: Dailies Module")
--Loading Frames--
if not WoWPro.Dailies.FramesLoaded then --First time the addon has been enabled since UI Load
WoWPro.Dailies.FramesLoaded = true
end
-- Creating empty user settings if none exist --
WoWPro_DailiesDB = WoWPro_DailiesDB or {}
WoWProCharDB.Guide = WoWProCharDB.Guide or {}
WoWProCharDB.completedQIDs = WoWProCharDB.completedQIDs or {}
WoWPro.Dailies.RecordQIDs = true
if WoWProDB.char.lastdailiesguide and not WoWProDB.char.currentguide then
WoWPro:LoadGuide(WoWProDB.char.lastdailiesguide)
end
WoWPro.FirstMapCall = true
end
-- Called when the module is disabled --
function WoWPro.Dailies:OnDisable()
--[[ If the current guide is a dailies guide, removes the map point, stores the guide's ID to be resumed later,
sets the current guide to nil, and loads the nil guide. ]]
if WoWPro.Guides[WoWProDB.char.currentguide] and WoWPro.Guides[WoWProDB.char.currentguide].guidetype == "Dailies" then
WoWPro:RemoveMapPoint()
WoWProDB.char.lastdailiesguide = WoWProDB.char.currentguide
end
end
function WoWPro.Dailies:RegisterGuide(guide)
WoWPro:NoCache(guide)
end
function WoWPro.Dailies:GuideFaction(guide,faction, hfaction)
if not hfaction then
guide.faction = tonumber(faction)
else
if WoWPro.Faction == 'Alliance' then
guide.faction = tonumber(faction)
else
guide.faction = tonumber(hfaction)
end
end
local factionInfo = WoWPro.C_Reputation_GetFactionDataByID(guide.faction)
if factionInfo then
guide.name = factionInfo.name
end
guide.category = "Dailies"
end
function WoWPro.Dailies:GuideNameAndCategory(guide,name,cat)
if name then
guide.name = name
end
if cat then
guide.category = cat
else
guide.category = guide.zone
end
end
-- Use Grail to go a crude guide for a zone. Pass in the mapID and it will find all the quests that start/end in that zone.
function WoWPro.Dailies:DumpInfo()
local zoneID = 951
WoWPro.Dailies.eBox = WoWPro.Dailies.eBox or _G.CreateFrame("EditBox", nil, _G.UIParent, "ChatFrameEditBoxTemplate")
local eBox = WoWPro.Dailies.eBox
eBox:SetWidth(512)
eBox:SetHeight(256)
eBox:SetMultiLine(true)
eBox:SetAutoFocus(true)
eBox:SetFontObject(_G.GameFontHighlight)
local text=""
Grail:CreateIndexedQuestList()
-- Ask for the list of quests in the zone
for _,quid in pairs(Grail:QuestsInMap(zoneID,true)) do
local pre = WoWPro:GrailQuestPrereq(quid)
local turnin_npc = Grail:QuestNPCTurnins(quid)
local accept_npc = Grail:QuestNPCAccepts(quid)
local name = Grail:QuestName(quid)
local accept_m = (accept_npc and accept_npc[1] and Grail:NPCLocations(accept_npc[1],true,true))
local turnin_m = (turnin_npc and turnin_npc[1] and Grail:NPCLocations(turnin_npc[1],true,true))
local line
if pre then
pre = "PRE|"..pre.."||"
else
pre = ""
end
if accept_m then
accept_m = ("%s, %s"):format(accept_m[1].x, accept_m[1].y)
else
accept_m = "unknown"
end
if turnin_m then
turnin_m = ("%s, %s"):format(turnin_m[1].x, turnin_m[1].y)
else
turnin_m = "unknown"
end
accept_npc = (accept_npc and accept_npc[1] and Grail:NPCName(accept_npc[1])) or "???"
turnin_npc = (turnin_npc and turnin_npc[1] and Grail:NPCName(turnin_npc[1])) or "???"
line = ("A %s|QID|%d|M|%s||%sN|From %s.|"):format(name, quid, accept_m, pre, accept_npc)
text = text .. line .. "\n"
line = ("T %s|QID|%d|M|%s||N|To %s.|"):format(name, quid, turnin_m, turnin_npc)
text = text .. line .. "\n"
end
eBox:SetText(text)
eBox:SetPoint("CENTER")
eBox:Show()
eBox:SetScript("OnEscapePressed", function (this) this:Hide() end)
end
| 412 | 0.847089 | 1 | 0.847089 | game-dev | MEDIA | 0.935519 | game-dev | 0.912655 | 1 | 0.912655 |
SyndiShanX/Synergy-IW-GSC-Menu | 45,247 | IW7-GSC/scripts/cp/maps/cp_final/cp_final_final_boss.gsc | /************************************************************
* Decompiled by Bog
* Edited by SyndiShanX
* Script: scripts\cp\maps\cp_final\cp_final_final_boss.gsc
************************************************************/
init() {
scripts\engine\utility::flag_init("meph_fight");
level.fbd = spawnstruct();
var_00 = level.fbd;
var_00.soulprojectilemonitorfunc = ::soulprojectilemonitor;
var_00.soulprojectiledeathfunc = ::soulprojectiledeathmonitor;
initfx();
var_00.circles = scripts\engine\utility::getstructarray("capture_points", "targetname");
var_00.activatedcircles = [];
foreach(var_03, var_02 in var_00.circles) {
var_02.var_3CB7 = 0;
var_02.buffer = 0;
var_02.state = "DORMANT";
var_02.model = spawn("script_model", var_02.origin + (0, 0, 3));
var_02.model setmodel("tag_origin_ritual_circle_0" + var_03 + 1);
var_02.previouscharge = 0;
var_02.var_D8B2 = "DORMANT";
var_02.index = var_03;
var_02.blinkable = 1;
}
var_00.activecircle = undefined;
var_00.numplayerschargingcircle = 0;
registeractionstocircles();
var_00.souls = [];
var_00.numsoulsalive = 0;
var_00.numsoulsactive = 0;
var_00.var_10B41 = 0;
var_00.victory = 0;
var_00.bossstate = "MAIN";
var_00.fightstarted = 0;
var_00.sectioncomplete = 0;
var_00.playerschargingcircle = [];
level.debugdlc4boss = ::start_boss_fight;
level.debugdlc4bossstart = ::start;
var_04 = getent("rockwall_clip", "targetname");
var_05 = getent("rockwall_trig", "targetname");
var_05 enablelinkto();
var_05 linkto(var_04);
}
bossfight_loadout() {
foreach(var_01 in level.players) {
var_01 scripts\cp\utility::allow_player_teleport(0);
}
foreach(var_01 in level.players) {
var_01 thread scripts\cp\maps\cp_final\cp_final::delay_set_audio_zone(var_01);
}
level.magic_weapons["venomx"] = "iw7_venomx_zm_pap2";
foreach(var_06 in level.var_B163) {
var_06.var_13C25 = scripts\cp\zombies\interaction_magicwheel::func_7ABF();
}
level.consumable_active_override = ::meph_consumable_check;
level.meph_fight_started = 1;
level.unlimited_fnf = 1;
level.magic_wheel_upgraded_pap2 = 1;
level.fnf_cost = 0;
enable_bossfight_fnf();
enable_bossfight_magicwheel();
thread spawn_perk_pickup();
var_08 = 300;
level thread auto_start_boss_fight(var_08);
var_09 = scripts\engine\utility::getstructarray("afterlife_selfrevive_door", "script_noteworthy");
foreach(var_0B in var_09) {
scripts\cp\cp_interaction::remove_from_current_interaction_list(var_0B);
}
scripts\cp\cp_interaction::remove_from_current_interaction_list(scripts\engine\utility::getstruct("afterlife_spectate_door", "script_noteworthy"));
var_0D = getent("bossfight_ala_clip", "targetname");
var_0D solid();
var_0E = scripts\engine\utility::getstructarray("afterlife_arcade", "targetname");
var_0E = scripts\engine\utility::array_randomize(var_0E);
foreach(var_10, var_01 in level.players) {
var_01.ability_invulnerable = 1;
var_01 setorigin(var_0E[var_10].origin);
var_01 setplayerangles(var_0E[var_10].angles);
}
scripts\cp\cp_interaction::add_to_current_interaction_list(scripts\engine\utility::getstruct("meph_perks", "script_noteworthy"));
scripts\cp\cp_interaction::add_to_current_interaction_list(scripts\engine\utility::getstruct("start_meph_battle", "script_noteworthy"));
}
auto_start_boss_fight(param_00) {
level endon("fight_started");
setomnvar("zm_ui_timer", gettime() + param_00 * 1000);
wait(param_00 - 5);
var_01 = spawn("script_origin", (2000, -4814, 446));
var_01 playloopsound("quest_rewind_clock_tick_long");
wait(5);
var_01 delete();
playsoundatpos((2000, -4814, 446), "mpq_fail_buzzer");
arcade_game_cleanup();
wait(2);
scripts\cp\cp_vo::set_vo_system_busy(1);
foreach(var_03 in level.players) {
scripts\cp\maps\cp_final\cp_final_vo::clear_up_all_vo(var_03);
var_03 _meth_82C0("bink_fadeout_amb", 0.66);
}
scripts\cp\utility::play_bink_video("sysload_o2", 86, 0);
wait(86.5);
foreach(var_03 in level.players) {
var_03 clearclienttriggeraudiozone(0.3);
}
spawn_meph();
start(level.dlc4_boss);
level.dlc4_boss playsound("cp_final_meph_intro_ground");
}
arcade_game_cleanup() {
foreach(var_01 in level.players) {
var_01 notify("arcade_special_interrupt");
var_01 disableusability();
}
wait(0.1);
level notify("force_exit_arcade");
foreach(var_01 in level.players) {
var_01 unlink();
if(isdefined(var_01.anchor)) {
var_01.anchor delete();
}
if(!var_01 scripts\cp\utility::areinteractionsenabled()) {
var_01 scripts\cp\utility::allow_player_interactions(1);
}
}
}
spawn_perk_pickup() {
var_00 = scripts\engine\utility::getstruct("meph_perks", "script_noteworthy");
var_01 = scripts\engine\utility::getstruct(var_00.target, "targetname");
level.perk_pickup = spawnfx(level._effect["vfx_mep_perk_buy"], var_01.origin);
wait(0.1);
triggerfx(level.perk_pickup);
}
try_to_leave_bossfight(param_00, param_01) {
if(!all_players_near_exit(param_00)) {
iprintlnbold("All players must be near the exit");
return;
}
scripts\cp\cp_interaction::remove_from_current_interaction_list(param_00);
level notify("fight_started");
scripts\cp\cp_vo::set_vo_system_busy(1);
foreach(param_01 in level.players) {
scripts\cp\maps\cp_final\cp_final_vo::clear_up_all_vo(param_01);
param_01 _meth_82C0("bink_fadeout_amb", 0.66);
}
scripts\cp\utility::play_bink_video("sysload_o2", 86, 0);
wait(86.5);
foreach(param_01 in level.players) {
param_01 clearclienttriggeraudiozone(0.3);
}
spawn_meph();
start(level.dlc4_boss);
level.dlc4_boss playsound("cp_final_meph_intro_ground");
}
all_players_near_exit(param_00) {
var_01 = 128;
foreach(var_03 in level.players) {
if(!var_03 scripts\cp\utility::is_valid_player()) {
return 0;
}
if(distance2d(var_03.origin, param_00.origin) > var_01) {
return 0;
}
}
return 1;
}
pre_bossfight_init() {
init_bossfight_fnf();
init_bossfight_magicwheel();
disable_bossfight_fnf();
disable_bossfight_magicwheel();
var_00 = getent("bossfight_ala_clip", "targetname");
var_00 notsolid();
scripts\cp\cp_interaction::remove_from_current_interaction_list(scripts\engine\utility::getstruct("meph_perks", "script_noteworthy"));
scripts\cp\cp_interaction::remove_from_current_interaction_list(scripts\engine\utility::getstruct("start_meph_battle", "script_noteworthy"));
}
disable_bossfight_fnf() {
level.boss_fnf_interaction.jaw hide();
level.boss_fnf_interaction.machine setscriptablepartstate("machine", "default");
level.boss_fnf_interaction.machine setscriptablepartstate("mouth", "off");
level.boss_fnf_interaction.machine setscriptablepartstate("teller", "off_nomodel");
level.boss_fnf_interaction.machine_top setscriptablepartstate("machine", "off_nomodel");
level.boss_fnf_interaction.machine.hidden = 1;
foreach(var_01 in level.boss_fnf_interaction.lights) {
var_01 setlightintensity(0);
}
}
enable_bossfight_fnf() {
level.boss_fnf_interaction.jaw show();
level.boss_fnf_interaction.machine setscriptablepartstate("teller", "safe_on");
level.boss_fnf_interaction.machine setscriptablepartstate("machine", "default_on");
wait(0.1);
level.boss_fnf_interaction.machine_top setscriptablepartstate("machine", "on");
level.boss_fnf_interaction.machine.hidden = undefined;
foreach(var_01 in level.boss_fnf_interaction.lights) {
var_01 setlightintensity(0.65);
}
scripts\cp\cp_interaction::add_to_current_interaction_list(level.boss_fnf_interaction);
level thread scripts\cp\cp_music_and_dialog::add_to_ambient_sound_queue("jaroslav_anc_attract", level.boss_fnf_interaction.jaw.origin, 120, 120, 250000, 100);
}
init_bossfight_fnf() {
var_00 = scripts\engine\utility::getstruct("jaroslav_machine_meph", "script_noteworthy");
var_01 = getentarray(var_00.target, "targetname");
foreach(var_03 in var_01) {
if(var_03.script_noteworthy == "fnf_machine") {
var_00.machine = var_03;
continue;
}
if(var_03.script_noteworthy == "fnf_machine_top") {
var_00.machine_top = var_03;
continue;
}
if(var_03.script_noteworthy == "fnf_jaw") {
var_00.jaw = var_03;
continue;
}
if(var_03.script_noteworthy == "fnf_light") {
if(!isdefined(var_00.lights)) {
var_00.lights = [];
}
var_00.lights[var_00.lights.size] = var_03;
}
}
level.boss_fnf_interaction = var_00;
scripts\cp\cp_interaction::remove_from_current_interaction_list(level.boss_fnf_interaction);
}
init_bossfight_magicwheel() {
while (!isdefined(level.var_B163)) {
wait(0.05);
}
wait(1);
level.bossfight_magicwheel = scripts\engine\utility::getclosest((1679.3, -4209, 331), level.var_B163);
}
disable_bossfight_magicwheel() {
level.bossfight_magicwheel setscriptablepartstate("base", "off_nomodel");
level.bossfight_magicwheel setscriptablepartstate("fx", "off");
level.bossfight_magicwheel setscriptablepartstate("spin_light", "off");
var_00 = getentarray("out_of_order", "script_noteworthy");
var_01 = scripts\engine\utility::getclosest(level.bossfight_magicwheel.origin, var_00);
var_01 hide();
level.bossfight_magicwheel.var_10A03 hide();
level.bossfight_magicwheel makeunusable();
}
enable_bossfight_magicwheel() {
level.bossfight_magicwheel setscriptablepartstate("base", "on");
level.bossfight_magicwheel setscriptablepartstate("fx", scripts\cp\zombies\interaction_magicwheel::get_default_fx_state());
level.bossfight_magicwheel setscriptablepartstate("spin_light", "on");
level.bossfight_magicwheel.var_10A03 show();
level.bossfight_magicwheel.var_10A03 setscriptablepartstate("spinner", "idle");
level.bossfight_magicwheel makeusable();
level.bossfight_magicwheel _meth_84A7("tag_use");
level.bossfight_magicwheel setusefov(60);
level.bossfight_magicwheel setuserange(72);
level.current_active_wheel = level.bossfight_magicwheel;
level.bossfight_magicwheel sethintstring( & "CP_FINAL_SPIN_WHEEL_FREE");
}
start_boss_fight() {
scripts\cp\maps\cp_final\cp_final::disablepas();
level.meph_fight_started = 1;
if(isdefined(level.pap_room_portal)) {
level.pap_room_portal delete();
}
if(getdvarint("skip_bossfight_loadout") == 1 || scripts\engine\utility::istrue(level.debug_boss_fight_skip_loadout)) {
spawn_meph();
start(level.dlc4_boss);
return;
}
bossfight_loadout();
}
boss_fight_intro_clear_audio_zone() {
wait(10);
self clearclienttriggeraudiozone(10);
}
play_meph_song(param_00, param_01) {
if(soundexists(param_01)) {
wait(2.5);
var_02 = spawn("script_origin", param_00);
var_02 playloopsound(param_01);
level scripts\engine\utility::waittill_any_3("game_ended", "FINAL_BOSS_VICTORY");
var_02 stoploopsound();
wait(0.1);
var_02 delete();
}
}
disable_laststand_weapon(param_00) {
return 0;
}
spawn_meph() {
if(isdefined(level.dlc4_boss)) {
return;
}
level.current_vision_set = "cp_final_meph";
scripts\cp\maps\cp_final\cp_final::disablepas();
scripts\cp\maps\cp_final\cp_final::enablepa("pa_meph");
level notify("add_hidden_song_to_playlist");
scripts\cp\cp_vo::set_vo_system_busy(1);
level.can_use_pistol_during_laststand_func = ::disable_laststand_weapon;
foreach(var_01 in level.players) {
var_01 _meth_82C0("final_boss_battle_space_intro", 0.02);
var_01 thread boss_fight_intro_clear_audio_zone();
}
level thread play_meph_song((1785, -2077, 211), "mus_zombies_boss_battle");
level.meph_fight_started = 1;
level.no_laststand_music = 1;
level.var_4C58 = ::meph_intermission_func;
level.force_respawn_location = ::respawn_in_meph_fight;
level.getspawnpoint = ::respawn_in_meph_fight;
scripts\cp\zombies\zombies_spawning::activate_volume_by_name("meph_arena");
scripts\engine\utility::flag_set("meph_fight");
level.zombies_paused = 1;
if(isdefined(level.dlc4_boss) && isalive(level.dlc4_boss)) {
level.dlc4_boss suicide();
level.dlc4_boss = undefined;
var_03 = undefined;
} else {
var_04 = "axis";
var_05 = vectortoangles((688, -11, 0));
var_03 = scripts\cp\zombies\zombies_spawning::func_13F53("dlc4_boss", (-13314, -337, -109), var_05, var_04);
level.dlc4_boss = var_03;
level.dlc4_boss thread clearvaluesondeath();
foreach(var_08, var_01 in level.players) {
var_07 = (0, 0, 0);
switch (var_08) {
case 0:
var_07 = (-12819, -327, -106);
break;
case 1:
var_07 = (-12822, -397, -106);
break;
case 2:
var_07 = (-12769, -287, -106);
break;
case 3:
var_07 = (-12776, -361, -106);
break;
}
var_01.ability_invulnerable = undefined;
var_01 setorigin(var_07);
var_01 enableusability();
var_01 setplayerangles(vectortoangles((-13314, -337, -48) - var_01.origin));
}
level.dlc4_boss thread persistent_flame_damage();
}
scripts\engine\utility::exploder(124);
setomnvar("zm_meph_battle", 1);
return var_03;
}
respawn_in_meph_fight(param_00) {
var_01 = scripts\engine\utility::getstructarray("boss_player_starts", "targetname");
if(isdefined(param_00) && isplayer(param_00)) {
foreach(var_03 in var_01) {
if(positionwouldtelefrag(var_03.origin, param_00)) {
continue;
}
return var_03;
}
}
return var_01[0];
}
clearvaluesondeath() {
self waittill("death");
level.loot_time_out = undefined;
level.disable_loot_fly_to_player = undefined;
level.movemodefunc["generic_zombie"] = level.originalmovemodefunc;
}
persistent_flame_damage() {
level endon("game_ended");
var_00 = getbosstunedata();
var_01 = spawn("trigger_radius", self.origin, 0, 128, 128);
var_01 enablelinkto();
var_01 linkto(self, "tag_origin");
for (;;) {
var_01 waittill("trigger", var_02);
if(!var_02 scripts\cp\utility::is_valid_player()) {
continue;
}
if(!isdefined(var_02.padding_damage)) {
playfxontagforclients(level._effect["vfx_dlc4_player_burn_flames"], var_02, "tag_eye", var_02);
var_02.padding_damage = 1;
var_02 dodamage(getbosstunedata().persistent_fire_damage, var_01.origin, var_01, var_01, "MOD_UNKNOWN", "iw7_electrictrap_zm");
var_02 thread remove_padding_damage();
continue;
}
}
}
remove_padding_damage() {
self endon("disconnect");
wait(getbosstunedata().persistent_fire_rate);
self.padding_damage = undefined;
}
initfx() {
level._effect["weak_spot_hit"] = loadfx("vfx\iw7\levels\cp_final\boss_demon\vfx_weakspot_hit.vfx");
level._effect["sb_quest_item_pickup"] = loadfx("vfx\iw7\core\zombie\vfx_zom_souvenir_pickup.vfx");
level._effect["flying_soul_death"] = loadfx("vfx\iw7\levels\cp_final\boss_demon\vfx_flying_soul_death.vfx");
level._effect["flying_soul_birth"] = loadfx("vfx\iw7\levels\cp_final\boss_demon\vfx_flying_soul_birth.vfx");
level._effect["flying_soul_hit_fail"] = loadfx("vfx\iw7\levels\cp_final\boss_demon\vfx_flying_soul_hit_fail.vfx");
level._effect["boss_shield_hit"] = loadfx("vfx\iw7\levels\cp_final\boss_demon\vfx_boss_shield_hit.vfx");
level._effect["boss_teleport_start"] = loadfx("vfx\iw7\levels\cp_final\boss\vfx_dlc4_boss_telep_out.vfx");
level._effect["boss_teleport_start_left"] = loadfx("vfx\iw7\levels\cp_final\boss\vfx_dlc4_boss_telep_out_left.vfx");
level._effect["boss_teleport_end"] = loadfx("vfx\iw7\levels\cp_final\boss\vfx_dlc4_boss_telep_in.vfx");
level._effect["boss_teleport_end_left"] = loadfx("vfx\iw7\levels\cp_final\boss\vfx_dlc4_boss_telep_in_left.vfx");
level._effect["talisman_flash"] = loadfx("vfx\iw7\levels\cp_final\boss\vfx_talisman_flash.vfx");
}
initinteraction(param_00) {
var_01 = spawnstruct();
var_01.name = "capture_points";
var_01.script_noteworthy = "capture_points";
var_01.var_336 = "interaction";
var_01.origin = param_00.origin;
var_01.custom_search_dist = 130;
var_01.cost = 0;
var_01.powered_on = 1;
var_01.spend_type = undefined;
var_01.script_parameters = "";
var_01.requires_power = 0;
var_01.hint_func = ::ritualcirclehintfunc;
var_01.activation_func = ::activatecircle;
var_01.enabled = 1;
var_01.circle = param_00;
level.interactions["capture_points"] = var_01;
param_00.interaction = var_01;
}
ritualcirclehintfunc(param_00, param_01) {
var_02 = param_00.circle;
if(var_02.state == "ACTIVE") {
if(level.fbd.bossstate == "FRENZIED") {
return & "CP_FINAL_ACTIVATE_TALISMAN";
}
return & "CP_FINAL_TALISMANS_NOTREADY";
}
return & "CP_FINAL_PLACE_TALISMAN";
}
registeractionstocircles() {
var_00 = level.fbd;
var_00.circles[0].actionname = "clap";
var_00.circles[1].actionname = "throw";
var_00.circles[2].actionname = "tornado";
var_00.circles[3].actionname = "air_pound";
var_00.circles[4].actionname = "fly_over";
}
start(param_00) {
var_01 = level.fbd;
var_01.boss = param_00;
var_02 = getbosstunedata();
level.no_loot_drop = 1;
scripts\engine\utility::flag_clear("zombie_drop_powerups");
scripts\cp\cp_vo::func_C9CB(level.players);
level.vo_system_busy = 1;
registerweakspots();
foreach(var_05, var_04 in var_01.circles) {
initinteraction(var_04);
scripts\cp\cp_interaction::add_to_current_interaction_list(var_04.interaction);
var_04.weakspot = var_01.weakspots[var_05];
}
level.zombie_ghost_model = var_02.stolen_ghost_model;
var_01.soultobossmindistsqr = pow(var_02.boss_mid_height + var_02.soul_mid_height, 2);
level.get_fake_ghost_model_func = ::returnfakesoulmodel;
foreach(var_07 in level.players) {
var_07 freezecontrols(1);
}
thread pre_fight_cleanup();
thread waittillintrofinished();
thread perframeupdate();
level.loot_time_out = 99999;
level.disable_loot_fly_to_player = 1;
level.originalmovemodefunc = level.movemodefunc["generic_zombie"];
level.movemodefunc["generic_zombie"] = ::makezombiessprint;
level thread max_ammo_manager();
var_01.fightstarted = 1;
var_01.boss.health = 9999999;
}
pre_fight_cleanup() {
var_00 = scripts\engine\utility::getstructarray("fast_travel_portal", "targetname");
foreach(var_02 in var_00) {
if(isdefined(var_02.trigger)) {
var_02.trigger delete();
}
if(isdefined(var_02.portal_scriptable)) {
var_02.portal_scriptable delete();
}
wait(0.05);
}
}
makezombiessprint(param_00) {
return "sprint";
}
max_ammo_manager() {
wait(3);
level.drop_max_ammo_func = ::scripts\cp\loot::drop_loot;
level thread unlimited_max_ammo();
level thread max_ammo_pick_up_listener();
}
unlimited_max_ammo() {
level endon("game_ended");
level endon("restart_ammo_timer");
scripts\engine\utility::flag_init("max_ammo_active");
var_00 = 180;
var_01 = 60;
for (;;) {
try_drop_max_ammo();
var_02 = isdefined(level.fbd.bossstate) && level.fbd.bossstate == "FRENZIED";
if(!var_02) {
wait(var_00);
continue;
}
wait(var_01);
}
}
try_drop_max_ammo() {
var_00 = level.dlc4_boss.arenacenter;
if(!scripts\engine\utility::flag("max_ammo_active")) {
scripts\engine\utility::flag_set("max_ammo_active");
level thread[[level.drop_max_ammo_func]](var_00, undefined, "ammo_max", undefined, undefined, 1);
}
}
max_ammo_pick_up_listener() {
level endon("game_ended");
for (;;) {
level waittill("pick_up_max_ammo");
scripts\engine\utility::flag_clear("max_ammo_active");
}
}
returnfakesoulmodel(param_00) {
return getbosstunedata().fake_ghost_model;
}
waittillintrofinished() {
level endon("game_ended");
wait(12);
foreach(var_01 in level.players) {
var_01 playlocalsound(var_01.vo_prefix + "meph_encounter");
}
while (!isdefined(level.fbd.boss.introfinished) || !level.fbd.boss.introfinished) {
wait(0.2);
}
foreach(var_01 in level.players) {
var_01 freezecontrols(0);
}
if(getdvarint("skip_bossfight_loadout") == 1 || scripts\engine\utility::istrue(level.debug_boss_fight_loadouts)) {
setupdebugplayerloadouts();
}
foreach(var_01 in level.players) {
giveentangler(var_01);
}
if(scripts\cp\utility::isplayingsolo() || level.only_one_player) {
foreach(var_01 in level.players) {
if(var_01 scripts\cp\utility::has_zombie_perk("perk_machine_revive")) {
scripts\cp\cp_laststand::enable_self_revive(var_01);
}
}
}
}
setupdebugplayerloadouts() {
var_00 = ["iw7_mauler_zm"];
var_01 = ["iw7_fhr_zm"];
foreach(var_03 in level.players) {
var_04 = randomint(var_01.size);
var_05 = randomint(var_00.size);
var_03 takeweapon(var_03 scripts\cp\utility::getvalidtakeweapon());
var_06 = scripts\cp\utility::getrawbaseweaponname(var_01[var_04]);
if(isdefined(var_03.weapon_build_models[var_06])) {
scripts\cp\zombies\coop_wall_buys::givevalidweapon(var_03, var_03.weapon_build_models[var_06]);
} else {
scripts\cp\zombies\coop_wall_buys::givevalidweapon(var_03, var_01[var_04]);
}
var_07 = scripts\cp\utility::getrawbaseweaponname(var_00[var_05]);
if(isdefined(var_03.weapon_build_models[var_07])) {
scripts\cp\zombies\coop_wall_buys::givevalidweapon(var_03, var_03.weapon_build_models[var_07]);
} else {
scripts\cp\zombies\coop_wall_buys::givevalidweapon(var_03, var_01[var_04]);
}
var_03.total_currency_earned = min(10000, var_03 scripts\cp\cp_persistence::get_player_max_currency());
var_03 scripts\cp\cp_persistence::set_player_currency(10000);
var_03.have_permanent_perks = 1;
level thread scripts\cp\gametypes\zombie::give_permanent_perks(var_03);
scripts\cp\cp_laststand::enable_self_revive(var_03);
}
if(isdefined(level.pap_max) && level.pap_max < 3) {
level.pap_max++;
}
level[[level.upgrade_weapons_func]]();
level thread[[level.upgrade_weapons_func]]();
}
perframeupdate() {
var_00 = level.fbd;
var_01 = getbosstunedata();
var_00.boss endon("death");
for (;;) {
var_00.numplayerschargingcircle = 0;
var_00.playerschargingcircle = [];
if(isdefined(var_00.activecircle)) {
var_02 = var_00.activecircle;
if(var_02.state == "CHARGING") {
foreach(var_04 in level.players) {
if(canchargecircle(var_04, var_02)) {
var_00.numplayerschargingcircle = var_00.numplayerschargingcircle + 1;
var_00.playerschargingcircle[var_00.playerschargingcircle.size] = var_04;
var_05 = var_01.var_3CCC * level.players.size * pow(0.9, level.players.size);
var_06 = 1 / var_05;
var_07 = var_06 * 50;
var_02.var_3CB7 = min(var_02.var_3CB7 + var_07, 1);
if(level.players.size > 2) {
var_02.buffer = var_01.buffer_time_coop;
} else {
var_02.buffer = var_01.buffer_time_solo;
}
var_02.state = "CHARGING";
}
}
var_02.buffer = max(var_02.buffer - 50, 0);
if(var_02.buffer == 0) {
var_09 = var_01.decharge_rate * 50;
var_02.var_3CB7 = max(var_02.var_3CB7 - var_09, 0);
if(var_02.var_3CB7 == 0) {
if(isdefined(var_02.talisman)) {
var_02.talisman delete();
var_02.talisman = undefined;
}
foreach(var_0B in var_00.circles) {
if(var_0B.state != "ACTIVE") {
var_0B.state = "DORMANT";
scripts\cp\cp_interaction::add_to_current_interaction_list(var_0B.interaction);
}
}
foreach(var_04 in level.players) {
var_04 scripts\cp\cp_interaction::refresh_interaction();
}
}
}
}
if(var_02.state == "CHARGING" && var_02.var_D8B2 != "CHARGING") {
var_02.model setscriptablepartstate("symbol", "on");
} else if(var_02.state == "DORMANT" && var_02.var_D8B2 != "DORMANT") {
var_02.model setscriptablepartstate("symbol", "off");
} else if(var_02.state == "ACTIVE" && var_02.var_D8B2 != "ACTIVE") {
var_02.model setscriptablepartstate("symbol", "active");
}
if(var_02.state == "CHARGING") {
var_0F = int(floor(var_02.var_3CB7 * 10));
} else {
var_0F = int(ceil(var_0F.var_3CB7 * 10));
}
if(var_02.state == "CHARGING") {
var_10 = int(floor(var_02.previouscharge * 10));
} else {
var_10 = int(ceil(var_0F.previouscharge * 10));
}
if(var_0F != var_10) {
var_02.model setscriptablepartstate("meter", "" + var_0F);
if(var_0F > var_10) {
playsoundatpos(var_02.model.origin + (0, 0, 20), "cp_final_talisman_count_up");
} else {
playsoundatpos(var_02.model.origin + (0, 0, 20), "cp_final_talisman_count_down");
}
}
if(var_02.state == "CHARGING") {
if(var_02.var_3CB7 == 1) {
var_02.var_3CB7 = 1;
var_02.state = "ACTIVE";
releasesouls(var_02);
thread manageactivecircle();
var_02.talisman setscriptablepartstate("effects", "charge_complete");
}
}
var_02.var_D8B2 = var_02.state;
var_02.previouscharge = var_02.var_3CB7;
}
wait(0.05);
}
}
manageactivecircle() {
var_00 = level.fbd;
var_01 = getbosstunedata();
var_00.boss endon(var_01.section_complete_notify);
var_02 = gettime();
var_03 = gettime();
var_04 = var_00.activecircle.origin;
var_05 = (0, 0, 0);
for (;;) {
var_06 = gettime();
var_00.activecircle.var_3CB7 = 1 - var_06 - var_02 / var_01.active_time;
if(var_06 > var_02 + var_01.active_time) {
var_00.summonsouls = 0;
thread attempttofailstage();
break;
}
if(var_00.summonsouls && var_06 > var_03 + var_01.soul_respawn_time) {
if(var_00.numsoulsalive < var_01.num_souls_released) {
thread spawnsoul(var_00.activecircle);
}
var_03 = var_06;
}
if(!var_00.summonsouls && var_00.numsoulsalive == 0) {
break;
}
scripts\engine\utility::waitframe();
}
}
attempttofailstage() {
var_00 = level.fbd;
var_00.boss endon(getbosstunedata().section_complete_notify);
clearsouls();
wait(2);
if(!var_00.boss.vulnerable) {
deactivatecircle();
var_00.boss.soulhealth = 999;
wait(2);
var_00.boss scripts\aitypes\dlc4_boss\behaviors::resetsoulhealth();
return;
}
level waittill("FINAL_BOSS_STAGE_FAILED");
deactivatecircle();
var_00.boss.soulhealth = 999;
wait(2);
var_00.boss scripts\aitypes\dlc4_boss\behaviors::resetsoulhealth();
}
invulresetsoulhealth() {}
activatecircle(param_00, param_01) {
var_02 = level.fbd;
if(!isdefined(level.fbd.circlesactivated)) {
level.fbd.circlesactivated = 0;
}
if(var_02.bossstate == "FRENZIED" && param_00.circle.state == "ACTIVE") {
level.fbd.circlesactivated = level.fbd.circlesactivated + 1;
scripts\cp\cp_interaction::remove_from_current_interaction_list(param_00);
var_03 = param_00.circle;
var_03.model setscriptablepartstate("symbol", "complete");
var_02.boss setscriptablepartstate("circle_" + var_03.index, "completed");
var_03.talisman setscriptablepartstate("effects", "circle_complete");
playsoundatpos(var_03.talisman.origin + (0, 0, 30), "cp_final_frenzy_activate_talisman");
} else if(var_02.bossstate == "MAIN" && param_00.circle.state == "DORMANT") {
foreach(var_03 in var_02.circles) {
if(var_03.state != "ACTIVE") {
var_03.var_3CB7 = 0;
var_03.state = "LOCKED";
playsoundatpos(var_03.interaction.origin + (0, 0, 20), "cp_final_talisman_place_on_sign");
scripts\cp\cp_interaction::remove_from_current_interaction_list(var_03.interaction);
}
}
param_00.circle.state = "CHARGING";
param_00.circle.talisman = spawn("script_model", param_00.origin + (0, 0, 4));
param_00.circle.talisman.angles = (-90, 0, 0);
param_00.circle.talisman setmodel("cp_final_talisman_ritual");
var_02.activecircle = param_00.circle;
}
foreach(param_01 in level.players) {
param_01 scripts\cp\cp_interaction::refresh_interaction();
}
}
deactivatecircle() {
var_00 = level.fbd;
var_00.activecircle.var_3CB7 = 0;
var_00.activecircle.state = "DORMANT";
var_00.activecircle.model setscriptablepartstate("symbol", "off");
var_00.activecircle.model setscriptablepartstate("meter", "0");
if(isdefined(var_00.activecircle.talisman)) {
var_00.activecircle.talisman delete();
var_00.activecircle.talisman = undefined;
}
if(!isdefined(var_00.boss.doinggroundvul) || !var_00.boss.doinggroundvul) {
var_00.boss setscriptablepartstate("circle_" + var_00.activecircle.index, "off");
}
foreach(var_02 in var_00.circles) {
if(var_02.state != "ACTIVE") {
scripts\cp\cp_interaction::add_to_current_interaction_list(var_02.interaction);
var_02.state = "DORMANT";
}
}
var_00.activecircle.weakspot.health = var_00.activecircle.weakspot.maxhealth;
foreach(var_05 in level.players) {
var_05 scripts\cp\cp_interaction::refresh_interaction();
}
}
canchargecircle(param_00, param_01) {
if(param_01.state != "CHARGING") {
return 0;
}
if(!param_00 scripts\cp\utility::is_valid_player()) {
return 0;
}
var_02 = distance2dsquared(param_00.origin, param_01.origin);
if(var_02 > param_01.fgetarg * param_01.fgetarg) {
return 0;
}
return 1;
}
spawnsoul(param_00) {
var_01 = param_00.origin;
var_02 = (0, 0, 0);
var_03 = level.fbd;
var_04 = getbosstunedata();
var_03.numsoulsalive = var_03.numsoulsalive + 1;
var_03.numsoulsactive = var_03.numsoulsactive + 1;
var_05 = scripts\cp\maps\cp_zmb\cp_zmb_ghost_wave::spawn_zombie_ghost(var_01, var_02);
var_03.souls[var_03.souls.size] = var_05;
param_00.model playsound("cp_final_talisman_soul_release");
playfx(level._effect["flying_soul_birth"], param_00.origin, (1, 0, 0), (0, 0, 1));
thread souldeathmonitor(var_05);
}
releasesouls(param_00) {
var_01 = level.fbd;
var_02 = getbosstunedata();
var_01.summonsouls = 0;
var_01.souls = [];
var_03 = param_00.origin;
var_04 = (0, 0, 0);
wait(0.75);
for (var_05 = 0; var_05 < var_02.num_souls_released; var_05++) {
spawnsoul(var_01.activecircle);
wait(0.25);
}
var_01.summonsouls = 1;
}
soulprojectilemonitor(param_00, param_01) {
var_02 = level.fbd;
var_03 = getbosstunedata();
var_02.boss endon("death");
param_00 endon("death");
var_04 = gettime();
for (;;) {
var_05 = param_00 gettagorigin("j_spine4");
if(gettime() - var_04 > var_03.soul_lifetime) {
var_06 = param_00 gettagorigin("j_spine4");
playfx(level._effect["flying_soul_hit_fail"], var_06, anglestoforward(param_00.angles), anglestoup(param_00.angles));
scripts\aitypes\zombie_ghost\behaviors::fake_ghost_explode(param_00, param_01, var_03.soul_explosion_radius);
}
var_07 = var_02.boss gettagorigin("j_mainroot");
var_08 = distancesquared(var_05, var_07);
if(var_08 < var_02.soultobossmindistsqr) {
if(!isdefined(level.soul_vo_played)) {
level.soul_vo_played = 1;
level thread play_meph_vo(param_01, "meph_damage_souls", 1);
}
param_01 thread scripts\cp\cp_damage::updatehitmarker("high_damage_cp");
var_02.boss scripts\asm\dlc4_boss\dlc4_boss_asm::smallpain();
var_06 = param_00 gettagorigin("j_spine4");
playfx(level._effect["flying_soul_death"], var_06, anglestoforward(param_00.angles), anglestoup(param_00.angles));
playsoundatpos(param_00.origin, "weap_soul_projectile_impact_lg");
scripts\aitypes\zombie_ghost\behaviors::fake_ghost_explode(param_00, param_01, var_03.soul_explosion_radius);
break;
}
scripts\engine\utility::waitframe();
}
}
play_meph_vo(param_00, param_01, param_02) {
wait(param_02);
foreach(var_04 in level.players) {
if(var_04 == param_00) {
param_00 playlocalsound(param_00.vo_prefix + "plr_" + param_01);
continue;
}
var_04 playlocalsound(param_00.vo_prefix + param_01);
}
}
souldeathmonitor(param_00) {
level.fbd.boss endon("death");
param_00 waittill("death");
level.fbd.numsoulsalive = level.fbd.numsoulsalive - 1;
}
soulprojectiledeathmonitor(param_00) {
var_01 = level.fbd;
var_01.boss endon("death");
param_00 waittill("death");
var_01.numsoulsactive = var_01.numsoulsactive - 1;
}
clearsouls() {
var_00 = level.fbd;
foreach(var_02 in var_00.souls) {
if(isalive(var_02)) {
if(scripts\engine\utility::istrue(var_02.is_entangled) && isdefined(var_02.player_entangled_by)) {
var_02.player_entangled_by.ghost_in_entanglement = undefined;
}
var_02.nocorpse = 1;
var_02 suicide();
level.fbd.numsoulsactive = level.fbd.numsoulsactive - 1;
}
}
level notify("CLEAR_SOULS");
}
setupfornextwave() {
var_00 = level.fbd;
var_01 = getbosstunedata();
foreach(var_03 in var_00.circles) {
if(var_03.state != "ACTIVE") {
var_03.state = "DORMANT";
var_03.var_3CB7 = 0;
scripts\cp\cp_interaction::add_to_current_interaction_list(var_03.interaction);
}
}
foreach(var_06 in level.players) {
var_06 scripts\cp\cp_interaction::refresh_interaction();
}
scripts\aitypes\dlc4_boss\behaviors::updateweights();
}
giveentangler(param_00) {
var_01 = getbosstunedata();
param_00 thread entanglerhitmonitor(param_00);
param_00 thread entanglerrechargemonitor(param_00);
param_00 thread scripts\cp\crafted_entangler::watch_dpad();
param_00 setclientomnvar("zom_crafted_weapon", 19);
scripts\cp\utility::set_crafted_inventory_item("crafted_entangler", ::scripts\cp\crafted_entangler::give_crafted_entangler, param_00);
}
entanglerhitmonitor(param_00) {
var_01 = getbosstunedata();
level endon("game_ended");
param_00 endon("disconnect");
param_00 endon(var_01.entangler_stop_notify);
for (;;) {
var_02 = 0;
for (;;) {
var_03 = param_00 scripts\engine\utility::waittill_any_timeout_no_endon_death_2(var_01.entangler_track_update_frequency, var_01.entangler_hit_same_target_notify);
if(var_03 == var_01.entangler_hit_same_target_notify) {
var_02 = var_02 + var_01.entangler_track_update_frequency;
var_04 = min(var_02 / var_01.entangler_track_time, 1);
if(var_04 == 1 && isalive(param_00.current_entangler_target) && !scripts\aitypes\zombie_ghost\behaviors::isentangled(param_00.current_entangler_target) && !isdefined(param_00.ghost_in_entanglement)) {
param_00.current_entangler_target scripts\aitypes\zombie_ghost\behaviors::entangleghost(param_00.current_entangler_target, param_00);
}
continue;
}
break;
}
}
}
entanglerrechargemonitor(param_00) {
var_01 = getbosstunedata();
level endon("game_ended");
param_00 endon("disconnect");
param_00 endon(var_01.entangler_stop_notify);
for (;;) {
wait(var_01.entangler_recharge_rate);
param_00 setweaponammoclip(var_01.entangler_weapon_name, weaponclipsize(var_01.entangler_weapon_name));
}
}
registerweakspots() {
var_00 = level.fbd;
var_00.weakspots = [];
registerweakspot("j_shoulder_ri", (0, 0, -12), (0, 0, -10), (-10, 180, 180), var_00.circles[0]);
registerweakspot("j_chest", (34, -15, -19), (34, -15, -19), (120, 0, 53), var_00.circles[1]);
registerweakspot("j_shoulder_le", (3, 0, 14), (3, 0, 14), (0, 0, 180), var_00.circles[2]);
registerweakspot("j_chest", (42, -16, 0), (42, -16, 0), (90, -30, 15), var_00.circles[3]);
registerweakspot("j_chest", (34, -17, 19), (34, -17, 19), (80, 0, 53), var_00.circles[4]);
}
registerweakspot(param_00, param_01, param_02, param_03, param_04) {
var_05 = level.fbd;
var_06 = spawnstruct();
var_06.var_332 = param_00;
var_06.modeloffset = param_01;
var_06.vfxoffset = param_02;
var_06.angleoffset = param_03;
var_06.circle = param_04;
var_06.maxhealth = int(getbosstunedata().weak_spot_health * level.players.size * pow(0.9, level.players.size - 1));
var_06.health = var_06.maxhealth;
var_05.weakspots[var_05.weakspots.size] = var_06;
}
setupweakspot(param_00) {
if(!isdefined(param_00)) {
return;
}
var_01 = level.fbd;
var_02 = getbosstunedata();
var_03 = param_00.weakspot;
var_04 = var_01.boss gettagorigin(var_03.var_332);
var_01.boss setscriptablepartstate("circle_" + param_00.index, "on");
var_05 = spawn("script_model", var_04);
var_05 setmodel(var_02.weak_spot_model);
var_05 linkto(var_01.boss, var_03.var_332, var_03.modeloffset, var_03.angleoffset);
var_05 getrandomweaponfromcategory();
var_05.health = var_03.health;
var_03.model = var_05;
thread weakspotmonitor(param_00);
level thread play_meph_vo(level.dlc4_boss scripts\cp\utility::get_closest_living_player(), "meph_damage_weak", 5);
}
cleanupweakspot(param_00) {
var_01 = level.fbd;
if(!isdefined(param_00)) {
return;
}
var_02 = getbosstunedata().min_health_percent * param_00.weakspot.maxhealth;
param_00.weakspot.health = int(max(param_00.weakspot.model.health, var_02));
if(isdefined(param_00.weakspot.model)) {
param_00.weakspot.model delete();
}
if(isdefined(param_00.weakspot.vfxent)) {
var_03 = param_00.weakspot.vfxent;
param_00.weakspot.vfxent delete();
}
}
weakspotmonitor(param_00) {
var_01 = level.fbd;
var_02 = getbosstunedata();
var_03 = param_00.weakspot;
var_03 endon("death");
var_03.model setcandamage(1);
for (;;) {
var_03.model waittill("damage", var_04, var_05, var_06, var_07);
if(!isdefined(var_05) || var_05 == var_01.boss || !isplayer(var_05)) {
continue;
}
var_08 = var_06 * -1;
playfx(level._effect["weak_spot_hit"], var_07, var_08);
if(var_03.model.health <= 0 && !var_01.sectioncomplete) {
clearsouls();
param_00.var_3CB7 = 1;
param_00.model setscriptablepartstate("symbol", "complete");
param_00.model setscriptablepartstate("meter", "10");
var_01.activatedcircles[var_01.activatedcircles.size] = param_00;
var_01.boss.var_1198.desirednode = 0;
self.automaticspawn = 0;
var_09 = var_01.boss.unlockedactions.size;
if(var_09 == 4) {
var_01.bossstate = "FRENZIED";
var_01.boss.showblood = 1;
level notify("restart_ammo_timer");
level thread unlimited_max_ammo();
var_01.boss thread blinkweakspots();
} else {
var_01.boss.unlockedactions[var_09] = var_01.boss.specialactionnames[var_09];
}
var_01.boss notify(var_02.section_complete_notify);
var_01.sectioncomplete = 1;
cleanupweakspot(var_01.activecircle);
var_01.boss setscriptablepartstate("circle_" + param_00.index, "destroyed");
playsoundatpos(var_07, "cp_final_meph_destroy_sign_explo");
break;
}
}
}
blinkweakspots() {
self endon("last_stand");
self endon("death");
var_00 = getbosstunedata();
var_01 = level.fbd;
var_02 = ["completed", "off", "on", "active"];
var_03 = [0, 0, 0, 0, 0];
wait(1);
for (;;) {
foreach(var_05 in var_01.circles) {
if(var_05.blinkable && randomfloat(1) < var_00.frenzied_blink_chance) {
var_06 = var_03[var_05.index] + randomint(var_02.size - 1) + 1 % var_02.size;
var_01.boss setscriptablepartstate("circle_" + var_05.index, var_02[var_06]);
if(var_02[var_06] != "completed") {
var_05.model setscriptablepartstate("symbol", var_02[var_06]);
} else {
var_05.model setscriptablepartstate("symbol", "complete");
}
var_05.model setscriptablepartstate("meter", randomint(11));
var_03[var_05.index] = var_06;
}
}
scripts\engine\utility::waitframe();
}
}
gointolaststand() {
var_00 = level.fbd;
var_01 = getbosstunedata();
self.cantakedamage = 0;
var_00.bossstate = "LAST_STAND";
var_00.boss.laststandhealth = var_01.last_stand_health;
var_00.boss scripts\aitypes\dlc4_boss\behaviors::setnextaction("ground_vul");
self notify("stop_blackhole");
self.blackholetimer = undefined;
self notify("pain");
self notify("last_stand");
self.var_1198.painnotifytime = 100;
}
frenzyprogressmonitor() {
var_00 = level.fbd;
var_00.boss endon("death");
var_01 = getbosstunedata();
var_02 = var_01.frenzied_health;
for (var_03 = 0; var_03 < 5; var_03++) {
var_04 = int(1 * 4 - var_03 / 5 * var_02);
while (var_00.boss.frenziedhealth > var_04) {
wait(0.2);
}
var_05 = var_00.activatedcircles[var_03];
var_05.blinkable = 0;
var_05.model setscriptablepartstate("symbol", "off");
var_05.model setscriptablepartstate("meter", "0");
var_00.boss setscriptablepartstate("circle_" + var_05.index, "active");
var_05.talisman setscriptablepartstate("effects", "charge_complete_raised");
var_06 = vectortoangles(var_00.boss.arenacenter - var_05.talisman.origin);
var_05.talisman movez(60, 1, 0.25, 0.25);
var_05.talisman rotateto((0, 0, 0) + var_06, 0.8);
thread talismanmovementmonitor(var_05.talisman);
}
wait(2);
foreach(var_05 in var_00.circles) {
var_05.talisman setscriptablepartstate("effects", "charge_complete_pulsing");
var_05.model setscriptablepartstate("symbol", "on");
var_05.model setscriptablepartstate("meter", "10");
var_00.boss setscriptablepartstate("circle_" + var_05.index, "on");
scripts\cp\cp_interaction::add_to_current_interaction_list(var_05.interaction);
}
var_00.circlesactivated = 0;
while (var_00.circlesactivated < 5) {
wait(0.1);
}
var_09 = spawn("script_origin", var_00.boss.arenacenter + (0, 0, 300));
wait(0.5);
foreach(var_05 in var_00.circles) {
playfx(level._effect["talisman_flash"], var_05.talisman.origin);
}
level notify("STOP_FRENZY_SPAWN");
level notify("STOP_FRENZY_ARMAGEDDON");
foreach(var_0D in level.agentarray) {
if(var_0D == level.dlc4_boss) {
continue;
}
if(isalive(var_0D) && isdefined(var_0D.isactive) && var_0D.isactive) {
var_0D.nodamagescale = 1;
var_0D dodamage(var_0D.health + 1000, var_00.boss.arenacenter);
}
}
var_09 playsound("cp_final_frenzy_laser_build_up");
wait(3);
foreach(var_05 in var_00.circles) {
var_10 = self.origin + (0, 0, 250) - var_05.talisman.origin;
var_05.talisman rotateto(vectortoangles(var_10), 0.25, 0.08, 0.08);
}
wait(0.3);
level notify("KILL_TALISMAN_MOVEMENT");
playsoundatpos(var_00.boss.arenacenter + (0, 0, 300), "cp_final_frenzy_laser_beam_fire_npc_start");
var_09 playloopsound("cp_final_frenzy_laser_beam_fire_npc_loop");
foreach(var_05 in var_00.circles) {
var_05.talisman thread activatetalismanbeam();
}
gointolaststand();
wait(2.5);
playsoundatpos(var_09.origin, "cp_final_frenzy_laser_beam_fire_npc_end");
var_09 delete();
foreach(var_05 in var_00.circles) {
playfx(level._effect["flying_soul_death"], var_05.talisman.origin);
var_00.boss setscriptablepartstate("circle_" + var_05.index, "destroyed");
var_05.talisman delete();
var_05.model setscriptablepartstate("symbol", "off");
var_05.model setscriptablepartstate("meter", "0");
}
}
talismanmovementmonitor(param_00) {
level.fbd.boss endon("death");
level endon("KILL_TALISMAN_MOVEMENT");
var_01 = 1.5;
var_02 = 4;
var_03 = 3;
wait(1);
for (;;) {
param_00 movez(var_02, var_01, var_01 / var_03, var_01 / var_03);
wait(var_01);
param_00 movez(0 - var_02, var_01, var_01 / var_03, var_01 / var_03);
wait(var_01);
}
}
activatetalismanbeam() {
playfxontagsbetweenclients(level._effect["vfx_talisman_beam"], self, "tag_origin", level.fbd.boss, "j_spine4");
wait(0.5);
playfxontagsbetweenclients(level._effect["vfx_talisman_beam"], self, "tag_origin", level.fbd.boss, "j_spine4");
}
victory() {
var_00 = level.fbd;
level.dlc4_boss stoploopsound();
thread killbomb();
level.fbd.victory = 1;
level.no_loot_drop = undefined;
level notify("FINAL_BOSS_VICTORY");
}
killbomb() {
if(isdefined(level.laststandfx)) {
level.laststandfx delete();
}
wait(0.1);
playsoundatpos(level.fbd.boss.arenacenter + (0, 0, 450), "cp_final_meph_final_soul_bomb_diffuse");
playfx(level._effect["soul_bomb_die"], level.fbd.boss.arenacenter + (0, 0, 450));
var_00 = scripts\mp\mp_agent::getaliveagentsofteam("axis");
foreach(var_02 in var_00) {
if(var_02 == level.dlc4_boss) {
continue;
}
var_02 dodamage(var_02.health + 1000, var_02.origin);
}
level.meph_battle_over = 1;
}
getbosstunedata() {
return level.agenttunedata["dlc4_boss"];
}
meph_consumable_check(param_00) {
if(param_00 == "secret_service" || param_00 == "anywhere_but_here") {
return 0;
}
if(isdefined(self.consumables) && isdefined(self.consumables[param_00]) && isdefined(self.consumables[param_00].on) && self.consumables[param_00].on == 1) {
return 1;
}
return 0;
}
meph_intermission_func(param_00) {
self.forcespawnorigin = level.dlc4_boss.arenacenter + (-250, 0, 500);
self.forcespawnangles = (60, 0, 0);
var_01 = self.forcespawnangles;
scripts\cp\cp_globallogic::spawnplayer();
self setclientdvar("cg_everyoneHearsEveryone", 1);
self setdepthoffield(0, 128, 512, 4000, 6, 1.8);
if(level.console) {
self setclientdvar("cg_fov", "90");
}
scripts\cp\utility::updatesessionstate("intermission");
} | 412 | 0.795249 | 1 | 0.795249 | game-dev | MEDIA | 0.964171 | game-dev | 0.770824 | 1 | 0.770824 |
fusioncharts/react-native-fusioncharts | 8,125 | examples/bare-react-native-app/chart/ios/Pods/boost/boost/msm/front/row2.hpp | // Copyright 2008 Christophe Henry
// henry UNDERSCORE christophe AT hotmail DOT com
// This is an extended version of the state machine available in the boost::mpl library
// Distributed under the same license as the original.
// Copyright for the original version:
// Copyright 2005 David Abrahams and Aleksey Gurtovoy. Distributed
// under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_MSM_ROW2_HPP
#define BOOST_MSM_ROW2_HPP
#include <boost/type_traits/is_base_of.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/fusion/include/at_key.hpp>
#include <boost/msm/back/common_types.hpp>
#include <boost/msm/row_tags.hpp>
#include <boost/msm/front/detail/row2_helper.hpp>
namespace boost { namespace msm { namespace front
{
template<
typename T1
, class Event
, typename T2
>
struct _row2
{
typedef _row_tag row_type_tag;
typedef T1 Source;
typedef T2 Target;
typedef Event Evt;
};
template<
typename T1
, class Event
, typename T2
, typename CalledForAction
, void (CalledForAction::*action)(Event const&)
>
struct a_row2
{
typedef a_row_tag row_type_tag;
typedef T1 Source;
typedef T2 Target;
typedef Event Evt;
template <class FSM,class SourceState,class TargetState,class AllStates>
static ::boost::msm::back::HandledEnum action_call(FSM& fsm,Event const& evt,SourceState& src,TargetState& tgt,
AllStates& all_states)
{
// in this front-end, we don't need to know source and target states
::boost::msm::front::detail::row2_action_helper<CalledForAction,Event,action>::template call_helper
(fsm,evt,src,tgt,all_states,
::boost::mpl::bool_< ::boost::is_base_of<CalledForAction,FSM>::type::value>());
return ::boost::msm::back::HANDLED_TRUE;
}
};
template<
typename T1
, class Event
, typename T2
, typename CalledForAction
, void (CalledForAction::*action)(Event const&)
, typename CalledForGuard
, bool (CalledForGuard::*guard)(Event const&)
>
struct row2
{
typedef row_tag row_type_tag;
typedef T1 Source;
typedef T2 Target;
typedef Event Evt;
template <class FSM,class SourceState,class TargetState, class AllStates>
static ::boost::msm::back::HandledEnum action_call(FSM& fsm,Event const& evt,SourceState& src,TargetState& tgt,
AllStates& all_states)
{
// in this front-end, we don't need to know source and target states
::boost::msm::front::detail::row2_action_helper<CalledForAction,Event,action>::call_helper
(fsm,evt,src,tgt,all_states,
::boost::mpl::bool_< ::boost::is_base_of<CalledForAction,FSM>::type::value>());
return ::boost::msm::back::HANDLED_TRUE;
}
template <class FSM,class SourceState,class TargetState,class AllStates>
static bool guard_call(FSM& fsm,Event const& evt,SourceState& src,TargetState& tgt,
AllStates& all_states)
{
// in this front-end, we don't need to know source and target states
return ::boost::msm::front::detail::row2_guard_helper<CalledForGuard,Event,guard>::call_helper
(fsm,evt,src,tgt,all_states,
::boost::mpl::bool_< ::boost::is_base_of<CalledForGuard,FSM>::type::value>());
}
};
template<
typename T1
, class Event
, typename T2
, typename CalledForGuard
, bool (CalledForGuard::*guard)(Event const&)
>
struct g_row2
{
typedef g_row_tag row_type_tag;
typedef T1 Source;
typedef T2 Target;
typedef Event Evt;
template <class FSM,class SourceState,class TargetState,class AllStates>
static bool guard_call(FSM& fsm,Event const& evt,SourceState& src,TargetState& tgt,
AllStates& all_states)
{
// in this front-end, we don't need to know source and target states
return ::boost::msm::front::detail::row2_guard_helper<CalledForGuard,Event,guard>::call_helper
(fsm,evt,src,tgt,all_states,
::boost::mpl::bool_< ::boost::is_base_of<CalledForGuard,FSM>::type::value>());
}
};
// internal transitions
template<
typename T1
, class Event
, typename CalledForAction
, void (CalledForAction::*action)(Event const&)
>
struct a_irow2
{
typedef a_irow_tag row_type_tag;
typedef T1 Source;
typedef T1 Target;
typedef Event Evt;
template <class FSM,class SourceState,class TargetState,class AllStates>
static ::boost::msm::back::HandledEnum action_call(FSM& fsm,Event const& evt,SourceState& src,TargetState& tgt,
AllStates& all_states)
{
// in this front-end, we don't need to know source and target states
::boost::msm::front::detail::row2_action_helper<CalledForAction,Event,action>::call_helper
(fsm,evt,src,tgt,all_states,
::boost::mpl::bool_< ::boost::is_base_of<CalledForAction,FSM>::type::value>());
return ::boost::msm::back::HANDLED_TRUE;
}
};
template<
typename T1
, class Event
, typename CalledForAction
, void (CalledForAction::*action)(Event const&)
, typename CalledForGuard
, bool (CalledForGuard::*guard)(Event const&)
>
struct irow2
{
typedef irow_tag row_type_tag;
typedef T1 Source;
typedef T1 Target;
typedef Event Evt;
template <class FSM,class SourceState,class TargetState,class AllStates>
static ::boost::msm::back::HandledEnum action_call(FSM& fsm,Event const& evt,SourceState& src,TargetState& tgt,
AllStates& all_states)
{
// in this front-end, we don't need to know source and target states
::boost::msm::front::detail::row2_action_helper<CalledForAction,Event,action>::call_helper
(fsm,evt,src,tgt,all_states,
::boost::mpl::bool_< ::boost::is_base_of<CalledForAction,FSM>::type::value>());
return ::boost::msm::back::HANDLED_TRUE;
}
template <class FSM,class SourceState,class TargetState,class AllStates>
static bool guard_call(FSM& fsm,Event const& evt,SourceState& src,TargetState& tgt,
AllStates& all_states)
{
// in this front-end, we don't need to know source and target states
return ::boost::msm::front::detail::row2_guard_helper<CalledForGuard,Event,guard>::call_helper
(fsm,evt,src,tgt,all_states,
::boost::mpl::bool_< ::boost::is_base_of<CalledForGuard,FSM>::type::value>());
}
};
template<
typename T1
, class Event
, typename CalledForGuard
, bool (CalledForGuard::*guard)(Event const&)
>
struct g_irow2
{
typedef g_irow_tag row_type_tag;
typedef T1 Source;
typedef T1 Target;
typedef Event Evt;
template <class FSM,class SourceState,class TargetState,class AllStates>
static bool guard_call(FSM& fsm,Event const& evt,SourceState& src,TargetState& tgt,
AllStates& all_states)
{
// in this front-end, we don't need to know source and target states
return ::boost::msm::front::detail::row2_guard_helper<CalledForGuard,Event,guard>::call_helper
(fsm,evt,src,tgt,all_states,
::boost::mpl::bool_< ::boost::is_base_of<CalledForGuard,FSM>::type::value>());
}
};
}}}
#endif //BOOST_MSM_ROW2_HPP
| 412 | 0.850566 | 1 | 0.850566 | game-dev | MEDIA | 0.070146 | game-dev | 0.924323 | 1 | 0.924323 |
Planimeter/hl2sb-src | 12,807 | src/game/server/hl2/npc_antlion.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef NPC_ANTLION_H
#define NPC_ANTLION_H
#ifdef _WIN32
#pragma once
#endif
#include "ai_blended_movement.h"
#include "soundent.h"
#include "ai_behavior_follow.h"
#include "ai_behavior_assault.h"
class CAntlionTemplateMaker;
#define ANTLION_FOLLOW_DISTANCE 350
#define ANTLION_FOLLOW_DISTANCE_SQR (ANTLION_FOLLOW_DISTANCE*ANTLION_FOLLOW_DISTANCE)
#define ANTLION_SKIN_COUNT 4
class CNPC_Antlion;
// Antlion follow behavior
class CAI_AntlionFollowBehavior : public CAI_FollowBehavior
{
typedef CAI_FollowBehavior BaseClass;
public:
CAI_AntlionFollowBehavior()
: BaseClass( AIF_ANTLION )
{
}
bool FarFromFollowTarget( void )
{
return ( GetFollowTarget() && (GetAbsOrigin() - GetFollowTarget()->GetAbsOrigin()).LengthSqr() > ANTLION_FOLLOW_DISTANCE_SQR );
}
bool ShouldFollow( void )
{
if ( GetFollowTarget() == NULL )
return false;
if ( GetEnemy() != NULL )
return false;
return true;
}
};
//
// Antlion class
//
enum AntlionMoveState_e
{
ANTLION_MOVE_FREE,
ANTLION_MOVE_FOLLOW,
ANTLION_MOVE_FIGHT_TO_GOAL,
};
#define SF_ANTLION_BURROW_ON_ELUDED ( 1 << 16 )
#define SF_ANTLION_USE_GROUNDCHECKS ( 1 << 17 )
#define SF_ANTLION_WORKER ( 1 << 18 ) // Use the "worker" model
typedef CAI_BlendingHost< CAI_BehaviorHost<CAI_BlendedNPC> > CAI_BaseAntlionBase;
class CNPC_Antlion : public CAI_BaseAntlionBase
{
public:
DECLARE_CLASS( CNPC_Antlion, CAI_BaseAntlionBase );
CNPC_Antlion( void );
virtual float InnateRange1MinRange( void ) { return 50*12; }
virtual float InnateRange1MaxRange( void ) { return 250*12; }
bool IsWorker( void ) const { return HasSpawnFlags( SF_ANTLION_WORKER ); } // NOTE: IsAntlionWorker function must agree!
float GetIdealAccel( void ) const;
float MaxYawSpeed( void );
bool FInViewCone( CBaseEntity *pEntity );
bool FInViewCone( const Vector &vecSpot );
void Activate( void );
void HandleAnimEvent( animevent_t *pEvent );
void StartTask( const Task_t *pTask );
void RunTask( const Task_t *pTask );
void IdleSound( void );
void PainSound( const CTakeDamageInfo &info );
void Precache( void );
void Spawn( void );
int OnTakeDamage_Alive( const CTakeDamageInfo &info );
void TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator );
void BuildScheduleTestBits( void );
void GatherConditions( void );
void PrescheduleThink( void );
void ZapThink( void );
void BurrowUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
bool CreateVPhysics();
bool IsJumpLegal( const Vector &startPos, const Vector &apex, const Vector &endPos ) const;
bool HandleInteraction( int interactionType, void *data, CBaseCombatCharacter *sender = NULL );
bool QuerySeeEntity( CBaseEntity *pEntity, bool bOnlyHateOrFearIfNPC = false );
bool ShouldPlayIdleSound( void );
bool OverrideMoveFacing( const AILocalMoveGoal_t &move, float flInterval );
bool IsValidEnemy(CBaseEntity *pEnemy);
bool QueryHearSound( CSound *pSound );
bool IsLightDamage( const CTakeDamageInfo &info );
bool CreateBehaviors( void );
bool ShouldHearBugbait( void ) { return ( m_bIgnoreBugbait == false ); }
int SelectSchedule( void );
void Touch( CBaseEntity *pOther );
virtual int RangeAttack1Conditions( float flDot, float flDist );
virtual int MeleeAttack1Conditions( float flDot, float flDist );
virtual int MeleeAttack2Conditions( float flDot, float flDist );
virtual int GetSoundInterests( void ) { return (BaseClass::GetSoundInterests())|(SOUND_DANGER|SOUND_PHYSICS_DANGER|SOUND_THUMPER|SOUND_BUGBAIT); }
virtual bool IsHeavyDamage( const CTakeDamageInfo &info );
Class_T Classify( void ) { return CLASS_ANTLION; }
void Event_Killed( const CTakeDamageInfo &info );
bool FValidateHintType ( CAI_Hint *pHint );
void GatherEnemyConditions( CBaseEntity *pEnemy );
bool IsAllied( void );
bool ShouldGib( const CTakeDamageInfo &info );
bool CorpseGib( const CTakeDamageInfo &info );
float GetMaxJumpSpeed() const { return 1024.0f; }
void SetFightTarget( CBaseEntity *pTarget );
void InputFightToPosition( inputdata_t &inputdata );
void InputStopFightToPosition( inputdata_t &inputdata );
void InputJumpAtTarget( inputdata_t &inputdata );
void SetFollowTarget( CBaseEntity *pTarget );
int TranslateSchedule( int scheduleType );
virtual Activity NPC_TranslateActivity( Activity baseAct );
bool ShouldResumeFollow( void );
bool ShouldAbandonFollow( void );
void SetMoveState( AntlionMoveState_e state );
int ChooseMoveSchedule( void );
DECLARE_DATADESC();
bool m_bStartBurrowed;
float m_flNextJumpPushTime;
void SetParentSpawnerName( const char *szName ) { m_strParentSpawner = MAKE_STRING( szName ); }
const char *GetParentSpawnerName( void ) { return STRING( m_strParentSpawner ); }
virtual void StopLoopingSounds( void );
bool AllowedToBePushed( void );
virtual Vector BodyTarget( const Vector &posSrc, bool bNoisy = true );
virtual float GetAutoAimRadius() { return 36.0f; }
void ClearBurrowPoint( const Vector &origin );
void Flip( bool bZapped = false );
bool CanBecomeRagdoll();
virtual void NotifyDeadFriend( CBaseEntity *pFriend );
private:
inline CBaseEntity *EntityToWatch( void );
void UpdateHead( void );
bool FindChasePosition( const Vector &targetPos, Vector &result );
bool GetGroundPosition( const Vector &testPos, Vector &result );
bool GetPathToSoundFleePoint( int soundType );
inline bool IsFlipped( void );
void Burrow( void );
void Unburrow( void );
void InputUnburrow( inputdata_t &inputdata );
void InputBurrow( inputdata_t &inputdata );
void InputBurrowAway( inputdata_t &inputdata );
void InputDisableJump( inputdata_t &inputdata );
void InputEnableJump( inputdata_t &inputdata );
void InputIgnoreBugbait( inputdata_t &inputdata );
void InputHearBugbait( inputdata_t &inputdata );
bool FindBurrow( const Vector &origin, float distance, int type, bool excludeNear = true );
void CreateDust( bool placeDecal = true );
bool ValidBurrowPoint( const Vector &point );
bool CheckLanding( void );
bool Alone( void );
bool CheckAlertRadius( void );
bool ShouldJump( void );
void MeleeAttack( float distance, float damage, QAngle& viewPunch, Vector& shove );
void SetWings( bool state );
void StartJump( void );
void LockJumpNode( void );
bool IsUnusableNode(int iNodeID, CAI_Hint *pHint);
bool OnObstructionPreSteer( AILocalMoveGoal_t *pMoveGoal, float distClear, AIMoveResult_t *pResult );
void ManageFleeCapabilities( bool bEnable );
int SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode );
bool IsFirmlyOnGround( void );
void CascadePush( const Vector &vecForce );
virtual bool CanRunAScriptedNPCInteraction( bool bForced = false );
virtual void Ignite ( float flFlameLifetime, bool bNPCOnly, float flSize, bool bCalledByLevelDesigner );
virtual bool GetSpitVector( const Vector &vecStartPos, const Vector &vecTarget, Vector *vecOut );
virtual bool InnateWeaponLOSCondition( const Vector &ownerPos, const Vector &targetPos, bool bSetConditions );
virtual bool FCanCheckAttacks( void );
bool SeenEnemyWithinTime( float flTime );
void DelaySquadAttack( float flDuration );
#if HL2_EPISODIC
void DoPoisonBurst();
#endif
float m_flIdleDelay;
float m_flBurrowTime;
float m_flJumpTime;
float m_flAlertRadius;
float m_flPounceTime;
int m_iUnBurrowAttempts;
int m_iContext; //for FValidateHintType context
Vector m_vecSaveSpitVelocity; // Saved when we start to attack and used if we failed to get a clear shot once we release
CAI_AntlionFollowBehavior m_FollowBehavior;
CAI_AssaultBehavior m_AssaultBehavior;
AntlionMoveState_e m_MoveState;
COutputEvent m_OnReachFightGoal; //Reached our scripted destination to fight to
COutputEvent m_OnUnBurrowed; //Unburrowed
Vector m_vecSavedJump;
Vector m_vecLastJumpAttempt;
float m_flIgnoreSoundTime; // Sound time to ignore if earlier than
float m_flNextAcknowledgeTime; // Next time an antlion can make an acknowledgement noise
float m_flSuppressFollowTime; // Amount of time to suppress our follow time
float m_flObeyFollowTime; // A range of time the antlions must be obedient
Vector m_vecHeardSound;
bool m_bHasHeardSound;
bool m_bAgitatedSound; //Playing agitated sound?
bool m_bWingsOpen; //Are the wings open?
bool m_bIgnoreBugbait; //If the antlion should ignore bugbait sounds
string_t m_strParentSpawner; //Name of our spawner
EHANDLE m_hFollowTarget;
EHANDLE m_hFightGoalTarget;
float m_flEludeDistance; //Distance until the antlion will consider himself "eluded" if so flagged
bool m_bLeapAttack;
bool m_bDisableJump;
float m_flTimeDrown;
float m_flTimeDrownSplash;
bool m_bDontExplode; // Suppresses worker poison burst when drowning, failing to unburrow, etc.
bool m_bLoopingStarted;
bool m_bSuppressUnburrowEffects; // Don't kick up dust when spawning
#if HL2_EPISODIC
bool m_bHasDoneAirAttack; ///< only allowed to apply this damage once per glide
#endif
bool m_bForcedStuckJump;
int m_nBodyBone;
// Used to trigger a heavy damage interrupt if sustained damage is taken
int m_nSustainedDamage;
float m_flLastDamageTime;
float m_flZapDuration;
protected:
int m_poseHead_Yaw, m_poseHead_Pitch;
virtual void PopulatePoseParameters( void );
private:
HSOUNDSCRIPTHANDLE m_hFootstep;
DEFINE_CUSTOM_AI;
//==================================================
// AntlionConditions
//==================================================
enum
{
COND_ANTLION_FLIPPED = LAST_SHARED_CONDITION,
COND_ANTLION_ON_NPC,
COND_ANTLION_CAN_JUMP,
COND_ANTLION_FOLLOW_TARGET_TOO_FAR,
COND_ANTLION_RECEIVED_ORDERS,
COND_ANTLION_IN_WATER,
COND_ANTLION_CAN_JUMP_AT_TARGET,
COND_ANTLION_SQUADMATE_KILLED
};
//==================================================
// AntlionSchedules
//==================================================
enum
{
SCHED_ANTLION_CHASE_ENEMY_BURROW = LAST_SHARED_SCHEDULE,
SCHED_ANTLION_JUMP,
SCHED_ANTLION_RUN_TO_BURROW_IN,
SCHED_ANTLION_BURROW_IN,
SCHED_ANTLION_BURROW_WAIT,
SCHED_ANTLION_BURROW_OUT,
SCHED_ANTLION_WAIT_FOR_UNBORROW_TRIGGER,
SCHED_ANTLION_WAIT_FOR_CLEAR_UNBORROW,
SCHED_ANTLION_WAIT_UNBORROW,
SCHED_ANTLION_FLEE_THUMPER,
SCHED_ANTLION_CHASE_BUGBAIT,
SCHED_ANTLION_FLIP,
SCHED_ANTLION_DISMOUNT_NPC,
SCHED_ANTLION_RUN_TO_FIGHT_GOAL,
SCHED_ANTLION_RUN_TO_FOLLOW_GOAL,
SCHED_ANTLION_BUGBAIT_IDLE_STAND,
SCHED_ANTLION_BURROW_AWAY,
SCHED_ANTLION_FLEE_PHYSICS_DANGER,
SCHED_ANTLION_POUNCE,
SCHED_ANTLION_POUNCE_MOVING,
SCHED_ANTLION_DROWN,
SCHED_ANTLION_WORKER_RANGE_ATTACK1,
SCHED_ANTLION_WORKER_RUN_RANDOM,
SCHED_ANTLION_TAKE_COVER_FROM_ENEMY,
SCHED_ANTLION_ZAP_FLIP,
SCHED_ANTLION_WORKER_FLANK_RANDOM,
SCHED_ANTLION_TAKE_COVER_FROM_SAVEPOSITION
};
//==================================================
// AntlionTasks
//==================================================
enum
{
TASK_ANTLION_SET_CHARGE_GOAL = LAST_SHARED_TASK,
TASK_ANTLION_FIND_BURROW_IN_POINT,
TASK_ANTLION_FIND_BURROW_OUT_POINT,
TASK_ANTLION_BURROW,
TASK_ANTLION_UNBURROW,
TASK_ANTLION_VANISH,
TASK_ANTLION_BURROW_WAIT,
TASK_ANTLION_CHECK_FOR_UNBORROW,
TASK_ANTLION_JUMP,
TASK_ANTLION_WAIT_FOR_TRIGGER,
TASK_ANTLION_GET_THUMPER_ESCAPE_PATH,
TASK_ANTLION_GET_PATH_TO_BUGBAIT,
TASK_ANTLION_FACE_BUGBAIT,
TASK_ANTLION_DISMOUNT_NPC,
TASK_ANTLION_REACH_FIGHT_GOAL,
TASK_ANTLION_GET_PHYSICS_DANGER_ESCAPE_PATH,
TASK_ANTLION_FACE_JUMP,
TASK_ANTLION_DROWN,
TASK_ANTLION_GET_PATH_TO_RANDOM_NODE,
TASK_ANTLION_FIND_COVER_FROM_SAVEPOSITION,
};
};
//-----------------------------------------------------------------------------
// Purpose: Shield
//-----------------------------------------------------------------------------
class CAntlionRepellant : public CPointEntity
{
DECLARE_DATADESC();
public:
DECLARE_CLASS( CAntlionRepellant, CPointEntity );
~CAntlionRepellant();
public:
void Spawn( void );
void InputEnable( inputdata_t &inputdata );
void InputDisable( inputdata_t &inputdata );
float GetRadius( void );
void SetRadius( float flRadius ) { m_flRepelRadius = flRadius; }
static bool IsPositionRepellantFree( Vector vDesiredPos );
void OnRestore( void );
private:
float m_flRepelRadius;
bool m_bEnabled;
};
extern bool IsAntlion( CBaseEntity *pEntity );
extern bool IsAntlionWorker( CBaseEntity *pEntity );
#ifdef HL2_EPISODIC
extern float AntlionWorkerBurstRadius( void );
#endif // HL2_EPISODIC
#endif // NPC_ANTLION_H
| 412 | 0.90046 | 1 | 0.90046 | game-dev | MEDIA | 0.984434 | game-dev | 0.598586 | 1 | 0.598586 |
LiteLDev/LeviLamina | 1,260 | src-server/mc/world/actor/VehicleUtils.h | #pragma once
#include "mc/_HeaderOutputPredefine.h"
// auto generated forward declare list
// clang-format off
class Actor;
class Block;
class BlockPos;
class IConstBlockSource;
class Vec3;
struct ActorUniqueID;
namespace VehicleUtils { struct VehicleDirections; }
// clang-format on
namespace VehicleUtils {
// functions
// NOLINTBEGIN
MCAPI ::std::optional<float> calculateBlockFloorHeight(::IConstBlockSource const& region, ::BlockPos const& blockPos);
MCAPI bool ignoredExitCollisionBlock(::Block const& block);
MCAPI bool isPassengerOfActor(::Actor const& maybePassenger, ::ActorUniqueID const& actorID);
MCAPI ::std::optional<::Vec3> testPosFollowingEjectPattern(
::VehicleUtils::VehicleDirections const& vehicleDirections,
::std::function<bool(::Vec3 const&, ::Vec3 const&)> callback
);
MCAPI ::std::optional<::Vec3> testPosFollowingLegacyActivatorRailPattern(
::VehicleUtils::VehicleDirections const& vehicleDirections,
::std::function<bool(::Vec3 const&, ::Vec3 const&)> callback
);
MCAPI ::std::optional<::Vec3> testPosFollowingLegacyActorPattern(
::VehicleUtils::VehicleDirections const&,
::std::function<bool(::Vec3 const&, ::Vec3 const&)> callback
);
// NOLINTEND
} // namespace VehicleUtils
| 412 | 0.740833 | 1 | 0.740833 | game-dev | MEDIA | 0.490226 | game-dev,graphics-rendering | 0.668517 | 1 | 0.668517 |
AzureeDev/payday-2-luajit | 87,560 | pd2-lua/lib/tweak_data/preplanningtweakdata.lua | PrePlanningTweakData = PrePlanningTweakData or class()
function PrePlanningTweakData:get_custom_texture_rect(num)
if not num then
return
end
local x = math.floor(num / 10) - 1
local y = num % 10 - 1
return {
x * 48,
y * 48,
48,
48
}
end
function PrePlanningTweakData:get_category_texture_rect(num)
if not num then
return
end
local x = math.floor(num / 10) - 1
local y = num % 10 - 1
return {
x * 64,
y * 64,
64,
64
}
end
function PrePlanningTweakData:get_type_texture_rect(num)
if not num then
return
end
local x = math.floor(num / 10) - 1
local y = num % 10 - 1
return {
x * 48,
y * 48,
48,
48
}
end
function PrePlanningTweakData:init(tweak_data)
self:_create_locations(tweak_data)
self.plans = {
escape_plan = {}
}
self.plans.escape_plan.category = "escape_plan"
self.plans.vault_plan = {
category = "vault_plan"
}
self.plans.plan_of_action = {
category = "plan_of_action"
}
self.plans.entry_plan = {
category = "entry_plan"
}
self.plans.entry_plan_generic = {
category = "entry_plan_generic"
}
self.gui = {
custom_icons_path = "guis/dlcs/big_bank/textures/pd2/pre_planning/preplan_icon_types",
type_icons_path = "guis/dlcs/big_bank/textures/pd2/pre_planning/preplan_icon_types",
category_icons_path = "guis/dlcs/big_bank/textures/pd2/pre_planning/preplan_icon_frames",
category_icons_bg = 42,
MAX_DRAW_POINTS = 1000
}
self.categories = {
default = {}
}
self.categories.default.name_id = "menu_pp_cat_default"
self.categories.default.desc_id = "menu_pp_cat_default_desc"
self.categories.default.icon = 32
self.categories.default.prio = 0
self.categories.dead_drop = {
name_id = "menu_pp_cat_dead_drop",
desc_id = "menu_pp_cat_dead_drop_desc",
icon = 22,
prio = 5
}
self.categories.mission_equipment = {
name_id = "menu_pp_cat_mission_equipment",
desc_id = "menu_pp_cat_mission_equipment_desc",
icon = 11,
prio = 0
}
self.categories.insider_help = {
name_id = "menu_pp_cat_insider_help",
desc_id = "menu_pp_cat_insider_help_desc",
upgrade_lock = {
upgrade = "additional_assets",
category = "player"
},
icon = 21,
prio = 2
}
self.categories.data_hacking = {
name_id = "menu_pp_cat_data_hacking",
desc_id = "menu_pp_cat_data_hacking_desc",
icon = 31,
prio = 3
}
self.categories.hired_help = {
name_id = "menu_pp_cat_hired_help",
desc_id = "menu_pp_cat_hired_help_desc",
icon = 41,
prio = 1
}
self.categories.surveillance = {
name_id = "menu_pp_cat_surveillance",
desc_id = "menu_pp_cat_surveillance_desc",
icon = 41,
prio = 4
}
self.categories.vault_plan = {
name_id = "menu_pp_cat_vault_plan",
desc_id = "menu_pp_cat_vault_plan_desc",
plan = "vault_plan",
icon = 11,
prio = 2
}
self.categories.escape_plan = {
name_id = "menu_pp_cat_escape_plan",
desc_id = "menu_pp_cat_escape_plan_desc",
plan = "escape_plan",
icon = 12,
total = 1,
prio = 1
}
self.categories.plan_of_action = {
name_id = "menu_pp_cat_plan_of_action",
desc_id = "menu_pp_cat_plan_of_action_desc",
plan = "plan_of_action",
icon = 12,
total = 1,
prio = 1
}
self.categories.entry_plan_generic = {
name_id = "menu_pp_cat_entry_plan_generic",
desc_id = "menu_pp_cat_entry_plan_generic_desc",
plan = "entry_plan_generic",
icon = 12,
total = 1,
prio = 1
}
self.categories.entry_plan = {
name_id = "menu_pp_cat_entry_plan",
desc_id = "menu_pp_cat_entry_plan_desc",
plan = "entry_plan",
icon = 12,
total = 1,
prio = 1
}
self.categories.BFD_upgrades = {
name_id = "menu_pp_cat_BFD_upgrades",
desc_id = "menu_pp_cat_BFD_upgrades_desc",
icon = 12,
prio = 1
}
self.categories.BFD_attachments = {
name_id = "menu_pp_cat_BFD_attachments",
desc_id = "menu_pp_cat_BFD_attachments_desc",
icon = 12,
prio = 1
}
self.types = {
ammo_bag = {}
}
self.types.ammo_bag.name_id = "menu_pp_asset_ammo"
self.types.ammo_bag.desc_id = "menu_pp_asset_ammo_desc"
self.types.ammo_bag.deployable_id = "ammo_bag"
self.types.ammo_bag.icon = 52
self.types.ammo_bag.category = "dead_drop"
self.types.ammo_bag.total = 2
self.types.ammo_bag.cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_deaddropbag")
self.types.ammo_bag.budget_cost = 2
self.types.ammo_bag.post_event = "preplan_05"
self.types.ammo_bag.prio = 5
self.types.health_bag = {
name_id = "menu_pp_asset_health",
desc_id = "menu_pp_asset_health_desc",
deployable_id = "doctor_bag",
icon = 31,
category = "dead_drop",
total = 2,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_deaddropbag"),
budget_cost = 2,
post_event = "preplan_06",
prio = 6
}
self.types.bodybags_bag = {
name_id = "menu_pp_asset_bodybags_bag",
desc_id = "menu_pp_asset_bodybags_bag_desc",
deployable_id = "bodybags_bag",
icon = 13,
category = "dead_drop",
upgrade_lock = {
upgrade = "buy_bodybags_asset",
category = "player"
},
total = 2,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_deaddropbag"),
budget_cost = 2,
post_event = "preplan_15",
prio = 3
}
self.types.grenade_crate = {
name_id = "menu_pp_asset_grenade_crate",
desc_id = "menu_pp_asset_grenade_crate_desc",
deployable_id = "grenade_crate",
icon = 21,
category = "dead_drop",
dlc_lock = "gage_pack",
total = 2,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_deaddropbag"),
budget_cost = 2,
post_event = "preplan_15",
prio = 4,
progress_stat = "gage_10_stats"
}
self.types.car = {
name_id = "menu_asset_car",
total = 1
}
self.types.drill_parts = {
name_id = "menu_pp_asset_drill_parts",
desc_id = "menu_pp_asset_drill_parts_desc",
category = "dead_drop",
icon = 12,
total = 1,
post_event = "preplan_16",
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_drillparts"),
budget_cost = 3,
prio = 2
}
self.types.zipline = {
name_id = "menu_pp_asset_zipline",
desc_id = "menu_pp_asset_zipline_desc",
category = "mission_equipment",
icon = 23,
total = 1,
post_event = "preplan_07",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_zipline"),
budget_cost = 2
}
self.types.zipline_generic = deep_clone(self.types.zipline)
self.types.zipline_generic.desc_id = "menu_pp_asset_zipline_generic_desc"
self.types.unlocked_door = {
name_id = "menu_pp_asset_unlocked_door",
desc_id = "menu_pp_asset_unlocked_door_desc",
category = "mission_equipment",
icon = 41,
total = 1,
post_event = "preplan_07",
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_unlocked_door"),
budget_cost = 1,
prio = 2
}
self.types.unlocked_window = {
name_id = "menu_pp_asset_unlocked_window",
desc_id = "menu_pp_asset_unlocked_window_desc",
category = "mission_equipment",
icon = 41,
total = 5,
post_event = "preplan_07",
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_unlocked_window"),
budget_cost = 1,
prio = 2
}
self.types.highlight_keybox = {
name_id = "menu_pp_asset_highlight_keybox",
desc_id = "menu_pp_asset_highlight_keybox_desc",
category = "mission_equipment",
icon = 43,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_highlight_keybox"),
budget_cost = 2,
post_event = "preplan_16",
prio = 2
}
self.types.ladder = {
name_id = "menu_pp_asset_ladder",
category = "mission_equipment",
total = 1,
post_event = "preplan_07",
prio = 2
}
self.types.disable_camera = {
name_id = "menu_pp_asset_disable_camera",
category = "surveillance",
total = 1,
post_event = "preplan_08",
prio = 2
}
self.types.disable_metal_detector = {
name_id = "menu_pp_asset_disable_metal_detector",
category = "insider_help",
upgrade_lock = {
upgrade = "additional_assets",
category = "player"
},
total = 1,
post_event = "preplan_10",
prio = 3
}
self.types.disable_guards_cake = {
name_id = "menu_pp_asset_disable_guards_cake",
desc_id = "menu_pp_asset_disable_guards_cake_desc",
category = "insider_help",
upgrade_lock = {
upgrade = "additional_assets",
category = "player"
},
icon = 25,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_cake"),
budget_cost = 3,
post_event = "preplan_09",
prio = 1
}
self.types.extra_cameras = {
name_id = "menu_pp_asset_extra_cameras",
desc_id = "menu_pp_asset_extra_cameras_desc",
category = "surveillance",
look_angle = {
length = 0.3,
angle = 80,
color = Color(192, 255, 170, 0) / 255
},
icon = 11,
total = 9,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_extracameras"),
budget_cost = 1,
post_event = "preplan_16",
prio = 2
}
self.types.keycard = {
name_id = "menu_pp_asset_keycard",
desc_id = "menu_pp_asset_keycard_desc",
category = "insider_help",
upgrade_lock = {
upgrade = "additional_assets",
category = "player"
},
icon = 53,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_keycard"),
budget_cost = 2,
post_event = "preplan_16",
prio = 2
}
self.types.camera_access = {
name_id = "menu_pp_camera_access",
desc_id = "menu_pp_camera_access_desc",
category = "surveillance",
icon = 24,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_accesscameras"),
budget_cost = 2,
post_event = "preplan_16",
prio = 8
}
self.types.delay_police_10 = {
name_id = "menu_pp_asset_delay_police_10",
desc_id = "menu_pp_asset_delay_police_10_desc",
delay_weapons_hot_t = 10,
icon = 42,
category = "data_hacking",
total = 1,
post_event = "preplan_04",
prio = 7
}
self.types.delay_police_10_no_pos = deep_clone(self.types.delay_police_10)
self.types.delay_police_10_no_pos.budget_cost = 1
self.types.delay_police_10_no_pos.cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_delay10")
self.types.delay_police_10_no_pos.pos_not_important = true
self.types.delay_police_20 = {
name_id = "menu_pp_asset_delay_police_20",
desc_id = "menu_pp_asset_delay_police_20_desc",
delay_weapons_hot_t = 20,
icon = 42,
category = "data_hacking",
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_delay20"),
budget_cost = 1,
post_event = "preplan_04",
prio = 6
}
self.types.delay_police_30 = {
name_id = "menu_pp_asset_delay_police_30",
desc_id = "menu_pp_asset_delay_police_30_desc",
delay_weapons_hot_t = 30,
icon = 42,
category = "data_hacking",
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_delay30"),
budget_cost = 2,
post_event = "preplan_10",
prio = 5
}
self.types.delay_police_30_no_pos = deep_clone(self.types.delay_police_30)
self.types.delay_police_30_no_pos.pos_not_important = true
self.types.delay_police_60 = {
name_id = "menu_pp_asset_delay_police_60",
desc_id = "menu_pp_asset_delay_police_60_desc",
delay_weapons_hot_t = 60,
icon = 42,
category = "data_hacking",
total = 1,
budget_cost = 4,
post_event = "preplan_04",
prio = 4
}
self.types.reduce_timelock_60 = {
name_id = "menu_pp_asset_reduce_timelock_60",
desc_id = "menu_pp_asset_reduce_timelock_60_desc",
reduce_timelock_t = 60,
icon = 15,
category = "data_hacking",
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_timelock60"),
budget_cost = 2,
post_event = "preplan_10",
prio = 3
}
self.types.reduce_timelock_120 = {
name_id = "menu_pp_asset_reduce_timelock_120",
desc_id = "menu_pp_asset_reduce_timelock_120_desc",
reduce_timelock_t = 120,
icon = 15,
category = "data_hacking",
total = 1,
budget_cost = 4,
post_event = "preplan_10",
prio = 2
}
self.types.reduce_timelock_240 = {
name_id = "menu_pp_asset_reduce_timelock_240",
desc_id = "menu_pp_asset_reduce_timelock_240_desc",
reduce_timelock_t = 240,
icon = 15,
category = "data_hacking",
total = 1,
budget_cost = 6,
post_event = "preplan_10",
prio = 1
}
self.types.spycam = {
name_id = "menu_asset_spycam",
desc_id = "menu_asset_spycam_desc",
category = "surveillance",
upgrade_lock = {
upgrade = "buy_spotter_asset",
category = "player"
},
look_angle = {
length = 0.5,
angle = 80,
color = Color(192, 255, 51, 51) / 255
},
icon = 35,
total = 3,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_spycam"),
budget_cost = 2,
post_event = "preplan_14",
prio = 3
}
self.types.spotter = {
name_id = "menu_asset_spotter",
category = "hired_help",
upgrade_lock = {
upgrade = "buy_spotter_asset",
category = "player"
},
look_angle = {
length = 0.5,
angle = 80,
color = Color(192, 255, 51, 51) / 255
},
icon = 33,
total = 1,
budget_cost = 2,
post_event = "preplan_13",
prio = 4
}
self.types.spotter_des = deep_clone(self.types.spotter)
self.types.spotter_des.budget_cost = 3
self.types.spotter_des.cost = tweak_data:get_value("money_manager", "preplaning_thebomb_cost_spotter")
self.types.spotter_des.desc_id = "menu_pp_asset_spotter_desc"
self.types.sniper = {
name_id = "menu_pp_asset_sniper",
desc_id = "menu_pp_asset_sniper_desc",
category = "hired_help",
icon = 55,
total = 1,
post_event = "preplan_13",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_mia_cost_sniper"),
budget_cost = 1
}
self.types.delayed_police = {
name_id = "menu_pp_asset_delayed_police",
desc_id = "menu_pp_asset_delayed_police_desc",
category = "hired_help",
icon = 15,
total = 1,
post_event = "preplan_13",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_mia_cost_delayed_police"),
budget_cost = 1
}
self.types.reduce_mobsters = {
name_id = "menu_pp_asset_reduce_mobsters",
desc_id = "menu_pp_asset_reduce_mobsters_desc",
category = "hired_help",
icon = 61,
total = 1,
post_event = "preplan_13",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_mia_cost_reduce_mobsters"),
budget_cost = 1
}
self.types.escape_van_loud = {
name_id = "menu_pp_escape_van_loud",
desc_id = "menu_pp_escape_van_loud_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
total = 1,
cost = 0,
budget_cost = 0,
post_event = "preplan_17",
prio = 6
}
self.types.escape_bus_loud = {
name_id = "menu_pp_escape_bus_loud",
desc_id = "menu_pp_escape_bus_loud_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_escapebig"),
budget_cost = 6,
post_event = "preplan_17",
prio = 1
}
self.types.escape_c4_loud = {
name_id = "menu_pp_escape_c4_loud",
desc_id = "menu_pp_escape_c4_loud_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_escapebig"),
budget_cost = 3,
post_event = "preplan_17",
prio = 2
}
self.types.escape_elevator_loud = {
name_id = "menu_pp_escape_elevator_loud",
desc_id = "menu_pp_escape_elevator_loud_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_escapebig"),
budget_cost = 3,
post_event = "preplan_17",
prio = 3
}
self.types.escape_zipline_loud = {
name_id = "menu_pp_escape_zipline_loud",
desc_id = "menu_pp_escape_zipline_loud_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_zipline"),
budget_cost = 3,
post_event = "preplan_17",
prio = 2
}
self.types.escape_helicopter_loud = {
name_id = "menu_pp_escape_helicopter_loud",
desc_id = "menu_pp_escape_helicopter_loud_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = 0,
budget_cost = 0,
post_event = "preplan_17",
prio = 3
}
self.types.escape_aliens_loud = {
name_id = "menu_pp_escape_aliens_loud",
desc_id = "menu_pp_escape_aliens_loud_desc",
plan = "escape_plan",
pos_not_important = false,
deployable_id = "ammo_bag",
category = "escape_plan",
total = 1,
cost = tweak_data:get_value("money_manager", "mission_asset_cost_large", 10),
budget_cost = 10,
post_event = "preplan_17",
prio = 99
}
self.types.vault_drill = {
name_id = "menu_pp_vault_drill",
plan = "vault_plan",
pos_not_important = false,
category = "vault_plan",
total = 1,
cost = 0,
budget_cost = 0,
post_event = "preplan_17",
prio = 2,
prio = 5
}
self.types.vault_c4 = {
name_id = "menu_pp_vault_c4",
plan = "vault_plan",
pos_not_important = false,
category = "vault_plan",
total = 1,
cost = tweak_data:get_value("money_manager", "mission_asset_cost_large", 1),
budget_cost = 4,
post_event = "preplan_17",
prio = 2
}
self.types.vault_lance = {
name_id = "menu_pp_vault_lance",
plan = "vault_plan",
pos_not_important = false,
category = "vault_plan",
icon = 12,
total = 1,
cost = 0,
budget_cost = 0,
post_event = "preplan_17",
prio = 5
}
self.types.vault_big_drill = {
name_id = "menu_pp_vault_big_drill",
desc_id = "menu_pp_vault_big_drill_desc",
plan = "vault_plan",
pos_not_important = false,
category = "vault_plan",
icon = 12,
total = 1,
cost = 0,
budget_cost = 0,
post_event = "preplan_17",
prio = 5
}
self.types.vault_thermite = {
name_id = "menu_pp_vault_thermite",
desc_id = "menu_pp_vault_thermite_desc",
plan = "vault_plan",
pos_not_important = false,
category = "vault_plan",
icon = 51,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_thermite"),
budget_cost = 5,
post_event = "preplan_02",
prio = 1
}
self.types.vault_singularity = {
name_id = "menu_pp_vault_singularity",
plan = "vault_plan",
pos_not_important = false,
category = "vault_plan",
total = 1,
cost = tweak_data:get_value("money_manager", "mission_asset_cost_large", 10),
budget_cost = 10,
post_event = "preplan_17",
prio = 99
}
self.types.disable_alarm_button = {
name_id = "menu_pp_asset_disable_alarm_button",
desc_id = "menu_pp_asset_disable_alarm_button_desc",
category = "data_hacking",
icon = 42,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_disable_alarm_button"),
budget_cost = 3,
post_event = "preplan_16",
prio = 1
}
self.types.safe_escape = {
name_id = "menu_pp_asset_safe_escape",
desc_id = "menu_pp_asset_safe_escape_desc",
category = "insider_help",
upgrade_lock = {
upgrade = "additional_assets",
category = "player"
},
icon = 54,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_safe_escape"),
budget_cost = 3,
post_event = "preplan_16",
prio = 1
}
self.types.sniper_spot = {
name_id = "menu_pp_asset_sniper_spot",
desc_id = "menu_pp_asset_sniper_spot_desc",
category = "hired_help",
icon = 55,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_sniper_spot"),
budget_cost = 3,
post_event = "preplan_16",
prio = 1
}
self.types.bag_shortcut = {
name_id = "menu_pp_asset_bag_shortcut",
desc_id = "menu_pp_asset_bag_shortcut_desc",
category = "mission_equipment",
icon = 34,
total = 1,
post_event = "preplan_16",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_bag_shortcut"),
budget_cost = 2
}
self.types.bag_zipline = {
name_id = "menu_pp_asset_bag_zipline",
desc_id = "menu_pp_asset_bag_zipline_desc",
category = "mission_equipment",
icon = 34,
total = 1,
post_event = "preplan_16",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_bag_zipline"),
budget_cost = 2
}
self.types.bag_zipline_stealth_only = {
name_id = "menu_pp_asset_bag_zipline_stealth_only",
desc_id = "menu_pp_asset_bag_zipline_stealth_only_desc",
category = "mission_equipment",
icon = 34,
total = 1,
post_event = "preplan_16",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_bag_zipline"),
budget_cost = 2
}
self.types.loot_drop_off = {
name_id = "menu_pp_asset_loot_drop_off",
desc_id = "menu_pp_asset_loot_drop_off_desc",
category = "hired_help",
icon = 34,
total = 1,
post_event = "preplan_16",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_loot_drop_off"),
budget_cost = 2
}
self.types.loot_drop_off_stealth_only = {
name_id = "menu_pp_asset_loot_drop_off_stealth_only",
desc_id = "menu_pp_asset_loot_drop_off_stealth_only_desc",
category = "hired_help",
icon = 34,
total = 1,
post_event = "preplan_16",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_loot_drop_off"),
budget_cost = 2
}
self.types.loot_drop_off_generic = deep_clone(self.types.loot_drop_off)
self.types.loot_drop_off_generic.desc_id = "menu_pp_asset_loot_drop_off_generic_desc"
self.types.thermal_paste = {
name_id = "menu_pp_asset_thermal_paste",
desc_id = "menu_pp_asset_thermal_paste_desc",
category = "dead_drop",
icon = 51,
total = 1,
post_event = "preplan_16",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_thermal_paste"),
budget_cost = 3,
spawn_unit = "units/payday2/equipment/gen_equipment_thermal_paste_crate/gen_equipment_thermal_paste_crate"
}
self.types.framing_frame_1_truck = {
name_id = "menu_pp_asset_framing_frame_1_truck",
desc_id = "menu_pp_asset_framing_frame_1_truck_desc",
category = "mission_equipment",
icon = 63,
total = 1,
post_event = "preplan_07",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_framing_frame_1_truck"),
budget_cost = 2
}
self.types.framing_frame_1_entry_point = {
name_id = "menu_pp_asset_framing_frame_1_entry_point",
desc_id = "menu_pp_asset_framing_frame_1_entry_point_desc",
category = "mission_equipment",
icon = 41,
total = 1,
post_event = "preplan_07",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_framing_frame_1_entry_point"),
budget_cost = 2
}
self.types.branchbank_lance = {
name_id = "menu_pp_branchbank_lance",
desc_id = "menu_pp_branchbank_lance_desc",
plan = "vault_plan",
pos_not_important = false,
category = "vault_plan",
icon = 12,
total = 1,
cost = 0,
budget_cost = 0,
post_event = "preplan_17",
prio = 5
}
self.types.branchbank_vault_key = {
name_id = "menu_pp_asset_branchbank_vault_key",
desc_id = "menu_pp_asset_branchbank_vault_key_desc",
category = "mission_equipment",
icon = 43,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_branchbank_vault_key"),
budget_cost = 3,
post_event = "preplan_16",
prio = 2
}
self.types.crojob_stealth = {
name_id = "menu_pp_crojob_stealth",
desc_id = "menu_pp_crojob_stealth_desc",
plan = "plan_of_action",
pos_not_important = true,
category = "plan_of_action",
icon = 54,
total = 0,
cost = 0,
budget_cost = 0,
post_event = "",
prio = 3
}
self.types.crojob_loud = {
name_id = "menu_pp_crojob_loud",
desc_id = "menu_pp_crojob_loud_desc",
plan = "plan_of_action",
pos_not_important = true,
category = "plan_of_action",
icon = 54,
total = 0,
cost = 0,
budget_cost = 0,
post_event = "",
prio = 3
}
self.types.crojob2_escape_van = {
name_id = "menu_pp_crojob2_escape_van",
desc_id = "menu_pp_crojob2_escape_van_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = 0,
budget_cost = 0,
post_event = "preplan_12",
prio = 3
}
self.types.crojob2_escape_helicopter = {
name_id = "menu_pp_crojob2_escape_helicopter",
desc_id = "menu_pp_crojob2_escape_helicopter_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_thebomb_cost_escape_mid"),
budget_cost = 4,
post_event = "preplan_17",
prio = 3
}
self.types.crojob2_escape_boat = {
name_id = "menu_pp_crojob2_escape_boat",
desc_id = "menu_pp_crojob2_escape_boat_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_thebomb_cost_escape_close"),
budget_cost = 8,
post_event = "preplan_13",
prio = 3
}
self.types.crojob2_better_hacker = {
name_id = "menu_pp_asset_crojob2_better_hacker",
desc_id = "menu_pp_asset_crojob2_better_hacker_desc",
icon = 15,
pos_not_important = true,
category = "hired_help",
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_thebomb_cost_hacker"),
budget_cost = 3,
post_event = "preplan_10",
prio = 3
}
self.types.crojob2_better_pilot = {
name_id = "menu_pp_asset_crojob2_better_pilot",
desc_id = "menu_pp_asset_crojob2_better_pilot_desc",
icon = 73,
pos_not_important = true,
category = "hired_help",
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_thebomb_cost_pilot"),
budget_cost = 3,
post_event = "preplan_17",
prio = 3
}
self.types.crojob2_manifest = {
name_id = "menu_pp_asset_crojob2_manifest",
desc_id = "menu_pp_asset_crojob2_manifest_desc",
icon = 71,
pos_not_important = true,
category = "mission_equipment",
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_thebomb_cost_manifest"),
budget_cost = 2,
post_event = "preplan_14",
prio = 3
}
self.types.crojob3_escape_boat = {
name_id = "menu_pp_crojob3_escape_boat",
desc_id = "menu_pp_crojob3_escape_boat_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = 0,
budget_cost = 0,
post_event = "preplan_16",
prio = 3
}
self.types.crojob3_escape_plane = {
name_id = "menu_pp_crojob3_escape_plane",
desc_id = "menu_pp_crojob3_escape_plane_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_thebomb_cost_escape_mid"),
budget_cost = 4,
post_event = "preplan_13",
prio = 3
}
self.types.crojob3_escape_helicopter = {
name_id = "menu_pp_crojob3_escape_helicopter",
desc_id = "menu_pp_crojob3_escape_helicopter_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_thebomb_cost_escape_close"),
budget_cost = 8,
post_event = "preplan_14",
prio = 3
}
self.types.crojob3_demolition_expert = {
name_id = "menu_pp_asset_crojob3_demolition_expert",
desc_id = "menu_pp_asset_crojob3_demolition_expert_desc",
pos_not_important = false,
icon = 65,
category = "hired_help",
total = 3,
cost = tweak_data:get_value("money_manager", "preplaning_thebomb_cost_demolition"),
budget_cost = 1,
post_event = "preplan_14",
prio = 3
}
self.types.crojob3_better_pilot = {
name_id = "menu_pp_asset_crojob3_better_pilot",
desc_id = "menu_pp_asset_crojob3_better_pilot_desc",
pos_not_important = true,
icon = 73,
category = "hired_help",
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_thebomb_cost_pilot"),
budget_cost = 4,
post_event = "preplan_17",
prio = 3
}
self.types.crojob3_sniper = {
name_id = "menu_pp_asset_sniper",
desc_id = "menu_pp_asset_sniper_desc",
pos_not_important = false,
icon = 55,
category = "hired_help",
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_mia_cost_sniper"),
budget_cost = 4,
post_event = "preplan_13",
prio = 3
}
self.types.crojob3_ladder = {
name_id = "menu_pp_asset_crojob3_ladder",
desc_id = "menu_pp_asset_crojob3_ladder_desc",
pos_not_important = false,
icon = 63,
category = "mission_equipment",
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_thebomb_cost_ladder"),
budget_cost = 1,
post_event = "preplan_15",
prio = 5
}
self.types.crojob3_crowbar = {
name_id = "menu_pp_asset_crojob3_crowbar",
desc_id = "menu_pp_asset_crojob3_crowbar_desc",
pos_not_important = false,
icon = 72,
category = "mission_equipment",
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_thebomb_cost_crowbar"),
budget_cost = 1,
post_event = "preplan_15",
prio = 5
}
self.types.glass_cutter = {
name_id = "menu_pp_asset_glass_cutter",
desc_id = "menu_pp_asset_glass_cutter_desc",
category = "mission_equipment",
icon = 64,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_glass_cutter"),
budget_cost = 1,
post_event = "preplan_16",
prio = 2
}
self.types.kenaz_silent_entry = {
name_id = "menu_pp_asset_kenaz_silent_entry",
desc_id = "menu_pp_asset_kenaz_silent_entry_desc",
plan = "entry_plan",
pos_not_important = false,
category = "entry_plan",
icon = 94,
cost = 0,
budget_cost = 0,
post_event = "",
prio = 3
}
self.types.kenaz_loud_entry = {
name_id = "menu_pp_asset_kenaz_loud_entry",
desc_id = "menu_pp_asset_kenaz_loud_entry_desc",
plan = "entry_plan",
pos_not_important = false,
category = "entry_plan",
icon = 95,
cost = 0,
budget_cost = 0,
post_event = "",
prio = 3
}
self.types.kenaz_loud_entry_with_c4 = {
name_id = "menu_pp_asset_kenaz_loud_entry_with_c4",
desc_id = "menu_pp_asset_kenaz_loud_entry_with_c4_desc",
plan = "entry_plan",
pos_not_important = false,
category = "entry_plan",
icon = 95,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_loud_entry_with_c4"),
budget_cost = 6,
post_event = "",
prio = 3
}
self.types.kenaz_limo_escape = {
name_id = "menu_pp_asset_kenaz_limo_escape",
desc_id = "menu_pp_asset_kenaz_limo_escape_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = 0,
budget_cost = 0,
post_event = "preplan_12",
prio = 3
}
self.types.kenaz_zeppelin_escape = {
name_id = "menu_pp_asset_kenaz_zeppelin_escape",
desc_id = "menu_pp_asset_kenaz_zeppelin_escape_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_zeppelin_escape"),
budget_cost = 4,
post_event = "preplan_12",
prio = 3
}
self.types.kenaz_van_escape = {
name_id = "menu_pp_asset_kenaz_van_escape",
desc_id = "menu_pp_asset_kenaz_van_escape_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_van_escape"),
budget_cost = 8,
post_event = "preplan_12",
prio = 3
}
self.types.kenaz_wrecking_ball_escape = {
name_id = "menu_pp_asset_kenaz_wrecking_ball_escape",
desc_id = "menu_pp_asset_kenaz_wrecking_ball_escape_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_wrecking_ball_escape"),
budget_cost = 10,
post_event = "preplan_12",
prio = 3
}
self.types.sentry_gun = {
name_id = "menu_pp_asset_sentry_gun",
desc_id = "menu_pp_asset_sentry_gun_desc",
icon = 75,
category = "dead_drop",
total = 2,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_deaddropbag"),
budget_cost = 1,
post_event = "",
prio = 5
}
self.types.kenaz_drill_better_plasma_cutter = {
name_id = "menu_pp_asset_kenaz_drill_better_plasma_cutter",
desc_id = "menu_pp_asset_kenaz_drill_better_plasma_cutter_desc",
pos_not_important = false,
category = "BFD_upgrades",
icon = 64,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_drill_better_plasma_cutter"),
budget_cost = 2,
post_event = "",
prio = 3
}
self.types.kenaz_drill_improved_cooling_system = {
name_id = "menu_pp_asset_kenaz_drill_improved_cooling_system",
desc_id = "menu_pp_asset_kenaz_drill_improved_cooling_system_desc",
pos_not_important = false,
category = "BFD_upgrades",
icon = 92,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_drill_improved_cooling_system"),
budget_cost = 3,
post_event = "",
prio = 3
}
self.types.kenaz_drill_engine_optimization = {
name_id = "menu_pp_asset_kenaz_drill_engine_optimization",
desc_id = "menu_pp_asset_kenaz_drill_engine_optimization_desc",
pos_not_important = false,
category = "BFD_upgrades",
icon = 15,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_drill_engine_optimization"),
budget_cost = 2,
post_event = "",
prio = 3
}
self.types.kenaz_drill_engine_additional_power = {
name_id = "menu_pp_asset_kenaz_drill_engine_additional_power",
desc_id = "menu_pp_asset_kenaz_drill_engine_additional_power_desc",
pos_not_important = false,
category = "BFD_upgrades",
icon = 44,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_drill_engine_additional_power"),
budget_cost = 3,
post_event = "",
prio = 3
}
self.types.kenaz_drill_sentry = {
name_id = "menu_pp_asset_kenaz_drill_sentry",
desc_id = "menu_pp_asset_kenaz_drill_sentry_desc",
pos_not_important = false,
category = "BFD_attachments",
icon = 75,
total = 2,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_deaddropbag"),
budget_cost = 1,
post_event = "",
prio = 3
}
self.types.kenaz_drill_extra_battery = {
name_id = "menu_pp_asset_kenaz_drill_extra_battery",
desc_id = "menu_pp_asset_kenaz_drill_extra_battery_desc",
pos_not_important = false,
category = "BFD_attachments",
icon = 44,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_drill_extra_battery"),
budget_cost = 3,
post_event = "",
prio = 3
}
self.types.kenaz_drill_water_level_indicator = {
name_id = "menu_pp_asset_kenaz_drill_water_level_indicator",
desc_id = "menu_pp_asset_kenaz_drill_water_level_indicator_desc",
pos_not_important = false,
category = "BFD_attachments",
icon = 92,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_drill_water_level_indicator"),
budget_cost = 1,
post_event = "",
prio = 3
}
self.types.kenaz_drill_timer_addon = {
name_id = "menu_pp_asset_kenaz_drill_timer_addon",
desc_id = "menu_pp_asset_kenaz_drill_timer_addon_desc",
pos_not_important = false,
category = "BFD_attachments",
icon = 15,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_drill_timer_addon"),
budget_cost = 1,
post_event = "",
prio = 3
}
self.types.kenaz_drill_toolbox = {
name_id = "menu_pp_asset_kenaz_drill_toolbox",
desc_id = "menu_pp_asset_kenaz_drill_toolbox_desc",
pos_not_important = false,
category = "BFD_attachments",
icon = 93,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_drill_toolbox"),
budget_cost = 1,
post_event = "",
prio = 3
}
self.types.kenaz_drill_medkit = {
name_id = "menu_pp_asset_kenaz_drill_medkit",
desc_id = "menu_pp_asset_kenaz_drill_medkit_desc",
pos_not_important = false,
category = "BFD_attachments",
icon = 31,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_drill_medkit"),
budget_cost = 2,
post_event = "",
prio = 3
}
self.types.kenaz_drill_ammobox = {
name_id = "menu_pp_asset_kenaz_drill_ammobox",
desc_id = "menu_pp_asset_kenaz_drill_ammobox_desc",
pos_not_important = false,
category = "BFD_attachments",
icon = 52,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_drill_ammobox"),
budget_cost = 2,
post_event = "",
prio = 3
}
self.types.kenaz_ace_pilot = {
name_id = "menu_pp_asset_kenaz_ace_pilot",
desc_id = "menu_pp_asset_kenaz_ace_pilot_desc",
pos_not_important = true,
category = "hired_help",
icon = 73,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_ace_pilot"),
budget_cost = 1,
post_event = "",
prio = 3
}
self.types.kenaz_faster_blimp = {
name_id = "menu_pp_asset_kenaz_faster_blimp",
desc_id = "menu_pp_asset_kenaz_faster_blimp_desc",
pos_not_important = true,
category = "hired_help",
icon = 74,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_faster_blimp"),
budget_cost = 2,
post_event = "",
prio = 3
}
self.types.kenaz_rig_slotmachine = {
name_id = "menu_pp_asset_kenaz_rig_slotmachine",
desc_id = "menu_pp_asset_kenaz_rig_slotmachine_desc",
pos_not_important = true,
category = "data_hacking",
icon = 45,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_rig_slotmachine"),
budget_cost = 4,
post_event = "",
prio = 3
}
self.types.kenaz_sabotage_skylight_barrier = {
name_id = "menu_pp_asset_kenaz_sabotage_skylight_barrier",
desc_id = "menu_pp_asset_kenaz_sabotage_skylight_barrier_desc",
pos_not_important = false,
category = "data_hacking",
icon = 42,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_sabotage_skylight_barrier"),
budget_cost = 3,
post_event = "",
prio = 3
}
self.types.kenaz_customer_data_USB = {
name_id = "menu_pp_asset_kenaz_customer_data_USB",
desc_id = "menu_pp_asset_kenaz_customer_data_USB_desc",
pos_not_important = true,
category = "mission_equipment",
icon = 85,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_customer_data_USB"),
budget_cost = 3,
post_event = "",
prio = 3
}
self.types.kenaz_unlocked_cages = {
name_id = "menu_pp_asset_kenaz_unlocked_cages",
desc_id = "menu_pp_asset_kenaz_unlocked_cages_desc",
pos_not_important = false,
category = "insider_help",
upgrade_lock = {
upgrade = "additional_assets",
category = "player"
},
icon = 41,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_unlocked_cages"),
budget_cost = 3,
post_event = "",
prio = 3
}
self.types.kenaz_unlocked_doors = {
name_id = "menu_pp_asset_kenaz_unlocked_doors",
desc_id = "menu_pp_asset_kenaz_unlocked_doors_desc",
pos_not_important = false,
category = "insider_help",
upgrade_lock = {
upgrade = "additional_assets",
category = "player"
},
icon = 41,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_unlocked_doors"),
budget_cost = 2,
post_event = "",
prio = 3
}
self.types.kenaz_guitar_case_position = {
name_id = "menu_pp_asset_kenaz_guitar_case_position",
desc_id = "menu_pp_asset_kenaz_guitar_case_position_desc",
pos_not_important = false,
category = "insider_help",
upgrade_lock = {
upgrade = "additional_assets",
category = "player"
},
icon = 83,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_guitar_case_position"),
budget_cost = 1,
post_event = "",
prio = 3
}
self.types.kenaz_disable_metal_detectors = {
name_id = "menu_pp_asset_kenaz_disable_metal_detectors",
desc_id = "menu_pp_asset_kenaz_disable_metal_detectors_desc",
pos_not_important = true,
category = "insider_help",
upgrade_lock = {
upgrade = "additional_assets",
category = "player"
},
icon = 42,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_disable_metal_detectors"),
budget_cost = 1,
post_event = "",
prio = 3
}
self.types.kenaz_celebrity_visit = {
name_id = "menu_pp_asset_kenaz_celebrity_visit",
desc_id = "menu_pp_asset_kenaz_celebrity_visit_desc",
pos_not_important = false,
category = "hired_help",
icon = 91,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_celebrity_visit"),
budget_cost = 2,
post_event = "",
prio = 3
}
self.types.kenaz_vault_gate_key = {
name_id = "menu_pp_asset_kenaz_vault_gate_key",
desc_id = "menu_pp_asset_kenaz_vault_gate_key_desc",
pos_not_important = true,
category = "mission_equipment",
icon = 43,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_kenaz_vault_gate_key"),
budget_cost = 2,
post_event = "",
prio = 3
}
self.types.mex_keys = {
name_id = "menu_pp_asset_mex_keys",
desc_id = "menu_pp_asset_mex_keys_desc",
category = "mission_equipment",
icon = 43,
total = 1,
post_event = "preplan_16",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_mex_keys"),
budget_cost = 3
}
self.types.roof_access = {
name_id = "menu_pp_asset_roof_access",
desc_id = "menu_pp_asset_roof_access_desc",
category = "mission_equipment",
icon = 63,
total = 2,
post_event = "preplan_16",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_roof_access"),
budget_cost = 3
}
self.types.upper_floor_access = {
name_id = "menu_pp_asset_upper_floor_access",
desc_id = "menu_pp_asset_upper_floor_access_desc",
category = "mission_equipment",
icon = 63,
total = 1,
post_event = "preplan_16",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_upper_floor_access"),
budget_cost = 2
}
self.types.crowbar_single = {
name_id = "menu_pp_asset_crowbar_single",
desc_id = "menu_pp_asset_crowbar_single_desc",
category = "mission_equipment",
icon = 72,
total = 1,
post_event = "preplan_16",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_crowbar_single"),
budget_cost = 1
}
self.types.bex_car_pull = {
name_id = "menu_pp_asset_bex_car_pull",
desc_id = "menu_pp_asset_bex_car_pull_desc",
category = "hired_help",
icon = 103,
total = 1,
post_event = "preplan_16",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_bex_car_pull"),
budget_cost = 6
}
self.types.bex_drunk_mariachi = {
name_id = "menu_pp_asset_bex_drunk_mariachi",
desc_id = "menu_pp_asset_bex_drunk_mariachi_desc",
category = "hired_help",
icon = 101,
total = 1,
post_event = "preplan_16",
prio = 3,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_bex_drunk_mariachi"),
budget_cost = 3
}
self.types.bex_garbage_truck = {
name_id = "menu_pp_asset_bex_garbage_truck",
desc_id = "menu_pp_asset_bex_garbage_truck_desc",
category = "hired_help",
icon = 102,
total = 1,
post_event = "preplan_16",
prio = 3,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_bex_garbage_truck"),
budget_cost = 3
}
self.types.bex_zipline = {
name_id = "menu_pp_asset_bex_zipline",
desc_id = "menu_pp_asset_bex_zipline_desc",
category = "hired_help",
icon = 95,
total = 1,
post_event = "preplan_16",
prio = 3,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_bex_zipline"),
budget_cost = 3
}
self.types.pex_parked_car = {
name_id = "menu_pp_asset_pex_parked_car",
desc_id = "menu_pp_asset_pex_parked_car_desc",
category = "hired_help",
icon = 104,
total = 1,
post_event = "preplan_16",
prio = 3,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_pex_parked_car"),
budget_cost = 3
}
self.types.pex_spiked_churro = {
name_id = "menu_pp_asset_pex_spiked_churro",
desc_id = "menu_pp_asset_pex_spiked_churro_desc",
category = "hired_help",
icon = 105,
total = 1,
post_event = "preplan_16",
prio = 3,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_pex_spiked_churro"),
budget_cost = 3
}
self.types.pex_camera_access = {
name_id = "menu_pp_asset_pex_camera_access",
desc_id = "menu_pp_asset_pex_camera_access_desc",
category = "hired_help",
icon = 24,
total = 1,
post_event = "preplan_16",
prio = 3,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_pex_camera_access"),
budget_cost = 3
}
self.types.pex_open_window = {
name_id = "menu_pp_asset_pex_open_window",
desc_id = "menu_pp_asset_pex_open_window_desc",
category = "hired_help",
icon = 111,
total = 1,
post_event = "preplan_16",
prio = 3,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_pex_open_window"),
budget_cost = 3
}
self.types.fex_stealth_entry_with_thermite = {
name_id = "menu_pp_asset_fex_stealth_entry_with_thermite",
desc_id = "menu_pp_asset_fex_stealth_entry_with_thermite_desc",
plan = "entry_plan_generic",
pos_not_important = false,
category = "entry_plan_generic",
icon = 95,
total = 1,
cost = 0,
budget_cost = 0,
post_event = "preplan_07",
prio = 3
}
self.types.fex_stealth_entry_with_boat = {
name_id = "menu_pp_asset_fex_stealth_entry_with_boat",
desc_id = "menu_pp_asset_fex_stealth_entry_with_boat_desc",
plan = "entry_plan_generic",
pos_not_important = false,
category = "entry_plan_generic",
icon = 95,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_fex_stealth_entry_with_boat"),
budget_cost = 6,
post_event = "preplan_07",
prio = 3
}
self.types.fex_loud_escape_with_car = {
name_id = "menu_pp_asset_fex_loud_escape_with_car",
desc_id = "menu_pp_asset_fex_loud_escape_with_car_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = 0,
budget_cost = 0,
post_event = "preplan_16",
prio = 3
}
self.types.fex_loud_escape_with_heli = {
name_id = "menu_pp_asset_fex_loud_escape_with_heli",
desc_id = "menu_pp_asset_fex_loud_escape_with_heli_desc",
plan = "escape_plan",
pos_not_important = false,
category = "escape_plan",
icon = 54,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_fex_loud_escape_with_heli"),
budget_cost = 6,
post_event = "preplan_16",
prio = 3
}
self.types.fex_stealth_semi_open_garage_door = {
name_id = "menu_pp_asset_fex_stealth_semi_open_garage_door",
desc_id = "menu_pp_asset_fex_stealth_semi_open_garage_door_desc",
plan = "insider_help",
upgrade_lock = {
upgrade = "additional_assets",
category = "player"
},
pos_not_important = false,
category = "insider_help",
icon = 111,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_fex_stealth_semi_open_garage_door"),
budget_cost = 2,
post_event = "preplan_16",
prio = 1
}
self.types.chas_tram = {
name_id = "menu_pp_chas_tram",
desc_id = "menu_pp_chas_tram_desc",
category = "hired_help",
icon = 103,
total = 1,
post_event = "preplan_16",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_chas_tram"),
budget_cost = 6
}
self.types.chas_garbage_truck = {
name_id = "menu_pp_asset_chas_garbage_truck",
desc_id = "menu_pp_asset_chas_garbage_truck_desc",
category = "hired_help",
icon = 102,
total = 1,
post_event = "preplan_16",
prio = 3,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_bex_garbage_truck"),
budget_cost = 3
}
self.types.chas_open_window = {
name_id = "menu_pp_asset_chas_open_window",
desc_id = "menu_pp_asset_chas_open_window_desc",
category = "hired_help",
icon = 111,
total = 1,
post_event = "preplan_16",
prio = 3,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_pex_open_window"),
budget_cost = 2
}
self.types.sand_broken_wall = {
name_id = "menu_pp_asset_sand_broken_wall",
desc_id = "menu_pp_asset_sand_broken_wall_desc",
category = "hired_help",
icon = 112,
total = 1,
post_event = "preplan_16",
prio = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_chas_tram"),
budget_cost = 1
}
self.types.sand_less_camera_drones = {
name_id = "menu_pp_asset_sand_less_camera_drones",
desc_id = "menu_pp_asset_sand_less_camera_drones_desc",
category = "hired_help",
icon = 114,
total = 1,
post_event = "preplan_16",
prio = 3,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_bex_garbage_truck"),
budget_cost = 3
}
self.types.sand_ladder_bridge = {
name_id = "menu_pp_asset_sand_ladder_bridge",
desc_id = "menu_pp_asset_sand_ladder_bridge_desc",
category = "hired_help",
icon = 63,
total = 1,
post_event = "preplan_16",
prio = 3,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_bex_garbage_truck"),
budget_cost = 2
}
self.types.sand_extra_dumpsters = {
name_id = "menu_pp_asset_sand_extra_dumpsters",
desc_id = "menu_pp_asset_sand_extra_dumpsters_desc",
category = "hired_help",
icon = 113,
total = 1,
post_event = "preplan_16",
prio = 3,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_pex_open_window"),
budget_cost = 2
}
self.types.chca_entry_as_guest = {
name_id = "menu_pp_asset_chca_entry_as_guest",
desc_id = "menu_pp_asset_chca_entry_as_guest_desc",
plan = "entry_plan_generic",
pos_not_important = false,
category = "entry_plan_generic",
icon = 95,
total = 1,
cost = 0,
budget_cost = 0,
post_event = "preplan_07",
prio = 3
}
self.types.chca_entry_as_crew = {
name_id = "menu_pp_asset_chca_entry_as_crew",
desc_id = "menu_pp_asset_chca_entry_as_crew_desc",
plan = "entry_plan_generic",
pos_not_important = false,
category = "entry_plan_generic",
icon = 95,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_fex_stealth_entry_with_boat"),
budget_cost = 4,
post_event = "preplan_07",
prio = 3
}
self.types.chca_entry_helicopter = {
name_id = "menu_pp_asset_chca_entry_helicopter",
desc_id = "menu_pp_asset_chca_entry_helicopter_desc",
plan = "entry_plan_generic",
pos_not_important = false,
category = "entry_plan_generic",
icon = 95,
total = 1,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_fex_stealth_entry_with_boat"),
budget_cost = 4,
post_event = "preplan_07",
prio = 3
}
self.types.chca_unlocked_doors = {
name_id = "menu_pp_asset_chca_unlocked_doors",
desc_id = "menu_pp_asset_chca_unlocked_doors_desc",
upgrade_lock = {
upgrade = "additional_assets",
category = "player"
},
pos_not_important = false,
category = "insider_help",
icon = 41,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_unlocked_door"),
budget_cost = 2,
post_event = "",
prio = 3
}
self.types.chca_spiked_drink = {
name_id = "menu_pp_asset_chca_spiked_drink",
desc_id = "menu_pp_asset_chca_spiked_drink_desc",
upgrade_lock = {
upgrade = "additional_assets",
category = "player"
},
category = "insider_help",
icon = 82,
total = 1,
post_event = "preplan_16",
prio = 3,
cost = tweak_data:get_value("money_manager", "preplanning_asset_cost_pex_spiked_churro"),
budget_cost = 2
}
self.types.chca_keycard = {
name_id = "menu_pp_asset_chca_keycard",
desc_id = "menu_pp_asset_chca_keycard_desc",
upgrade_lock = {
upgrade = "additional_assets",
category = "player"
},
pos_not_important = false,
category = "insider_help",
icon = 53,
total = 1,
cost = tweak_data:get_value("money_manager", "preplaning_asset_cost_unlocked_door"),
budget_cost = 2,
post_event = "",
prio = 3
}
end
function PrePlanningTweakData:_create_locations(tweak_data)
self.upgrade_locks = {
"none",
"additional_assets"
}
self.dlc_locks = {
"none",
"big_bank"
}
self.location_groups = {
"a",
"b",
"c",
"d",
"e",
"f"
}
self.locations = {
big = {
{
texture = "guis/dlcs/big_bank/textures/pd2/pre_planning/big_lobby",
x2 = 5750,
rotation = 90,
map_size = 1,
map_x = -1.1,
x1 = -250,
name_id = "menu_pp_big_loc_a",
y2 = 3000,
y1 = -3000,
map_y = -0 + 0.5,
custom_points = {
{
text_id = "menu_pp_info_frontdoor",
rotation = -90,
y = 1025,
to_upper = true,
icon = 45,
x = 1500,
post_event = "pln_pp_bb1_a"
},
{
text_id = "menu_pp_info_backoffices",
rotation = -90,
y = 480,
to_upper = true,
icon = 45,
x = 800,
post_event = "pln_pp_bb1_c"
},
{
text_id = "menu_pp_info_garage",
rotation = -90,
y = 1690,
to_upper = true,
icon = 45,
x = 1300,
post_event = "pln_pp_bb1_l"
},
{
text_id = "menu_pp_info_mainhall",
rotation = -90,
y = 1025,
to_upper = true,
icon = 45,
x = 1000,
post_event = "pln_pp_bb1_n"
},
{
text_id = "menu_pp_info_entrypoint",
rotation = -90,
y = 350,
to_upper = true,
icon = 45,
x = 1950,
post_event = "pln_pp_bb1_o"
},
{
text_id = "menu_pp_info_timelock",
rotation = -90,
y = 1024,
to_upper = true,
icon = 45,
x = 90,
post_event = "pln_pp_bb1_d"
},
{
text_id = "menu_pp_info_securityroom",
rotation = -90,
y = 590,
to_upper = true,
icon = 45,
x = 348,
post_event = "pln_pp_bb1_i"
},
{
text_id = "menu_pp_info_securityroom",
rotation = -90,
y = 1742,
to_upper = true,
icon = 45,
x = 574,
post_event = "pln_pp_bb1_i"
}
}
},
{
texture = "guis/dlcs/big_bank/textures/pd2/pre_planning/big_level_2",
x2 = 5750,
rotation = 90,
map_size = 1,
map_x = 0,
x1 = -250,
map_y = 0.5,
name_id = "menu_pp_big_loc_b",
y2 = 3000,
y1 = -3000,
custom_points = {
{
text_id = "menu_pp_info_mgroffices",
rotation = -90,
y = 1700,
to_upper = true,
icon = 45,
x = 190,
post_event = "pln_pp_bb1_k"
},
{
text_id = "menu_pp_info_backoffices",
rotation = -90,
y = 480,
to_upper = true,
icon = 45,
x = 800,
post_event = "pln_pp_bb1_c"
},
{
text_id = "menu_pp_info_timelock",
rotation = -90,
y = 1024,
to_upper = true,
icon = 45,
x = 90,
post_event = "pln_pp_bb1_d"
},
{
text_id = "menu_pp_info_ladder",
rotation = -90,
y = 1625,
to_upper = true,
icon = 45,
x = 870,
post_event = "pln_pp_bb1_b"
},
{
text_id = "menu_pp_info_securityroom",
rotation = -90,
y = 1437,
to_upper = true,
icon = 45,
x = 164,
post_event = "pln_pp_bb1_i"
}
}
},
{
texture = "guis/dlcs/big_bank/textures/pd2/pre_planning/big_roof",
x2 = 5750,
rotation = 90,
map_size = 1,
map_x = 1.1,
x1 = -250,
name_id = "menu_pp_big_loc_c",
y2 = 3000,
y1 = -3000,
map_y = -0 + 0.5,
custom_points = {
{
text_id = "menu_pp_info_ladder",
rotation = -90,
y = 1629,
to_upper = true,
icon = 45,
x = 869,
post_event = "pln_pp_bb1_b"
},
{
text_id = "menu_pp_info_zipline",
rotation = -90,
y = 1164,
to_upper = true,
icon = 45,
x = 1356,
post_event = "pln_pp_bb1_m"
},
{
text_id = "menu_pp_info_roof",
rotation = -90,
y = 1458,
to_upper = true,
icon = 45,
x = 782,
post_event = "pln_pp_bb1_h"
}
}
},
{
texture = "guis/dlcs/big_bank/textures/pd2/pre_planning/big_level_vault_2",
x2 = 229,
rotation = 90,
map_size = 1,
x1 = -5771,
map_y = -0.6000000000000001,
name_id = "menu_pp_big_loc_d",
y2 = 3000,
y1 = -3000,
map_x = -0,
custom_points = {
{
text_id = "menu_pp_info_vaultsecurity1",
rotation = -90,
y = 1298,
to_upper = true,
icon = 45,
x = 1152,
post_event = "pln_pp_bb1_g"
},
{
text_id = "menu_pp_info_vaultsecurity2",
rotation = -90,
y = 746,
to_upper = true,
icon = 45,
x = 1152,
post_event = "pln_pp_bb1_g"
},
{
text_id = "menu_pp_info_vault",
rotation = -90,
y = 1365,
to_upper = true,
icon = 45,
x = 465,
post_event = "pln_pp_bb1_f"
}
}
},
{
texture = "guis/dlcs/big_bank/textures/pd2/pre_planning/big_level_vault",
x2 = 229,
rotation = 90,
map_size = 1,
map_x = -1.1,
x1 = -5771,
map_y = -0.6000000000000001,
name_id = "menu_pp_big_loc_e",
y2 = 3000,
y1 = -3000,
custom_points = {
{
text_id = "menu_pp_info_moneycounting",
rotation = -90,
y = 1015,
to_upper = true,
icon = 45,
x = 1154,
post_event = "pln_pp_bb1_e"
},
{
text_id = "menu_pp_info_vault",
rotation = -90,
y = 1365,
to_upper = true,
icon = 45,
x = 465,
post_event = "pln_pp_bb1_f"
}
}
},
mission_briefing_texture = "guis/textures/pd2/pre_planning/mission_briefing_big",
total_budget = 10,
default_plans = {
escape_plan = "escape_helicopter_loud",
vault_plan = "vault_big_drill"
},
start_location = {
group = "a",
zoom = 1.5,
x = 1500,
y = 1025
}
},
mia_1 = {
{
texture = "guis/textures/pd2/pre_planning/hlm_01",
x2 = 7476,
rotation = 0,
map_width = 2,
map_x = -0.55,
x1 = -5524,
map_height = 1,
map_y = 0,
name_id = "menu_pp_mia_1_loc_a",
y2 = 1142,
y1 = -5358,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/hlm_02",
x2 = 7782,
rotation = 0,
map_width = 1,
map_x = 1.05,
x1 = -1018,
map_height = 0.5,
map_y = -0.25,
name_id = "menu_pp_mia_1_loc_b",
y2 = -272,
y1 = -4672,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/hlm_03",
x2 = 7782,
rotation = 0,
map_width = 1,
map_x = 1.05,
x1 = -1018,
map_height = 0.5,
map_y = 0.25,
name_id = "menu_pp_mia_1_loc_c",
y2 = -272,
y1 = -4672,
custom_points = {}
},
grid_width_mul = 0.5,
mission_briefing_texture = "guis/textures/pd2/pre_planning/mission_briefing_hlm1",
grid_height_mul = 1.4,
total_budget = 6,
default_plans = {},
start_location = {
group = "a",
zoom = 1,
x = 1024,
y = 512
}
},
mia_2 = {
{
texture = "guis/textures/pd2/pre_planning/hlm2_01",
x2 = 3850,
rotation = 0,
map_width = 1,
map_x = 0,
x1 = -3050,
map_height = 1,
map_y = 1,
name_id = "menu_pp_mia_2_loc_a",
y2 = 3625,
y1 = -3275,
custom_points = {
{
text_id = "menu_pp_info_the_box",
rotation = 0,
y = 840,
to_upper = true,
icon = 45,
x = 290,
post_event = "Play_pln_pp_hm2_01"
},
{
text_id = "menu_pp_info_bombstrapped",
rotation = 0,
y = 507,
to_upper = true,
icon = 45,
x = 423,
post_event = "Play_pln_pp_hm2_04"
}
}
},
{
texture = "guis/textures/pd2/pre_planning/hlm2_02",
x2 = 3850,
rotation = 0,
map_width = 1,
map_x = -1,
x1 = -3050,
map_height = 1,
map_y = 0,
name_id = "menu_pp_mia_2_loc_b",
y2 = 3625,
y1 = -3275,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/hlm2_03",
x2 = 3850,
rotation = 0,
map_width = 1,
map_x = 0,
x1 = -3050,
map_height = 1,
map_y = 0,
name_id = "menu_pp_mia_2_loc_c",
y2 = 3625,
y1 = -3275,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/hlm2_04",
x2 = 3850,
rotation = 0,
map_width = 1,
map_x = 1,
x1 = -3050,
map_height = 1,
map_y = 0,
name_id = "menu_pp_mia_2_loc_d",
y2 = 3625,
y1 = -3275,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/hlm2_05",
x2 = 3850,
rotation = 0,
map_width = 1,
map_x = 0,
x1 = -3050,
map_height = 1,
map_y = -1,
name_id = "menu_pp_mia_2_loc_e",
y2 = 3625,
y1 = -3275,
custom_points = {
{
text_id = "menu_pp_info_vault_comm",
rotation = 0,
y = 143,
to_upper = true,
icon = 45,
x = 300,
post_event = "Play_pln_pp_hm2_02"
},
{
text_id = "menu_pp_info_cocaine_mountain",
rotation = 0,
y = 143,
to_upper = true,
icon = 45,
x = 546,
post_event = "Play_pln_pp_hm2_03"
}
}
},
mission_briefing_texture = "guis/textures/pd2/pre_planning/mission_briefing_hlm2",
grid_width_mul = 0.5,
grid_height_mul = 0.5,
total_budget = 6,
default_plans = {},
start_location = {
group = "a",
zoom = 1.25,
x = 290,
y = 835
}
},
framing_frame_1 = {
{
texture = "guis/textures/pd2/pre_planning/framing_frame_1_1",
x2 = 2750,
rotation = 90,
map_size = 1,
map_x = -0.6,
x1 = -2750,
map_y = 0,
name_id = "menu_pp_framing_frame_1_loc_a",
y2 = 2750,
y1 = -2750,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/framing_frame_1_2",
x2 = 6300,
rotation = 90,
map_size = 1,
map_x = 0.6,
x1 = -2700,
map_y = 0,
name_id = "menu_pp_framing_frame_1_loc_b",
y2 = 3700,
y1 = -5300,
custom_points = {}
},
mission_briefing_texture = "guis/textures/pd2/pre_planning/mission_briefing_framingframe1",
total_budget = 8,
default_plans = {},
start_location = {
group = "a",
zoom = 1,
x = 512,
y = 512
}
}
}
self.locations.gallery = deep_clone(self.locations.framing_frame_1)
self.locations.branchbank = {
{
texture = "guis/textures/pd2/pre_planning/branchbank_1",
x2 = 500,
rotation = 0,
map_size = 1,
map_x = -0.6,
x1 = -3500,
map_y = 0,
name_id = "menu_pp_branchbank_loc_a",
y2 = 3700,
y1 = -300,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/branchbank_2",
x2 = 2500,
rotation = 0,
map_size = 1,
map_x = 0.6,
x1 = -5500,
map_y = 0,
name_id = "menu_pp_branchbank_loc_b",
y2 = 4800,
y1 = -3200,
custom_points = {}
},
mission_briefing_texture = "guis/textures/pd2/pre_planning/mission_briefing_big",
total_budget = 8,
default_plans = {
vault_plan = "branchbank_lance"
},
start_location = {
group = "a",
zoom = 1,
x = 512,
y = 512
}
}
self.locations.firestarter_3 = {
{
texture = "guis/textures/pd2/pre_planning/branchbank_1",
x2 = 500,
rotation = 0,
map_size = 1,
map_x = -0.6,
x1 = -3500,
map_y = 0,
name_id = "menu_pp_branchbank_loc_a",
y2 = 3700,
y1 = -300,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/branchbank_2",
x2 = 2500,
rotation = 0,
map_size = 1,
map_x = 0.6,
x1 = -5500,
map_y = 0,
name_id = "menu_pp_branchbank_loc_b",
y2 = 4800,
y1 = -3200,
custom_points = {}
},
mission_briefing_texture = "guis/textures/pd2/pre_planning/mission_briefing_big",
total_budget = 8,
default_plans = {
vault_plan = "branchbank_lance"
},
start_location = {
group = "a",
zoom = 1,
x = 512,
y = 512
}
}
self.locations.framing_frame_3 = {
{
texture = "guis/textures/pd2/pre_planning/framing_frame_3_1",
x2 = -1400,
rotation = 0,
map_size = 1,
map_x = -1.1,
x1 = -6600,
map_y = 0,
name_id = "menu_pp_framing_frame_3_loc_b",
y2 = 5800,
y1 = 600,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/framing_frame_3_2",
x2 = -1400,
rotation = 0,
map_size = 1,
map_x = 0,
x1 = -6600,
map_y = 0,
name_id = "menu_pp_framing_frame_3_loc_a",
y2 = 5900,
y1 = 700,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/framing_frame_3_3",
x2 = -1325,
rotation = 0,
map_size = 1,
map_x = 1.1,
x1 = -7325,
map_y = 0,
name_id = "menu_pp_framing_frame_3_loc_c",
y2 = 6625,
y1 = 625,
custom_points = {}
},
grid_width_mul = 2.2,
mission_briefing_texture = "guis/textures/pd2/pre_planning/mission_briefing_framingframe3",
grid_height_mul = 1.5,
min_zoom = 0.7,
total_budget = 8,
default_plans = {},
start_location = {
group = "a",
zoom = 1,
x = 512,
y = 512
}
}
self.locations.kosugi = {
{
texture = "guis/textures/pd2/pre_planning/shadow_raid_1",
x2 = 6850,
rotation = 0,
map_size = 2,
map_x = -0.5999999999999999,
x1 = -5650,
map_y = -0.5999999999999999,
name_id = "menu_pp_shadow_raid_loc_a",
y2 = 4650,
y1 = -7850,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/shadow_raid_2",
x2 = 1550,
rotation = 0,
map_size = 1,
map_x = 1.1,
x1 = -3950,
map_y = -1.1,
name_id = "menu_pp_shadow_raid_loc_b",
y2 = -650,
y1 = -6150,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/shadow_raid_3",
x2 = 1550,
rotation = 0,
map_size = 1,
map_x = 1.1,
x1 = -3950,
map_y = 0,
name_id = "menu_pp_shadow_raid_loc_c",
y2 = -650,
y1 = -6150,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/shadow_raid_4",
x2 = 1550,
rotation = 0,
map_size = 1,
map_x = 1.1,
x1 = -3950,
map_y = 1.1,
name_id = "menu_pp_shadow_raid_loc_d",
y2 = -650,
y1 = -6150,
custom_points = {}
},
mission_briefing_texture = "guis/textures/pd2/pre_planning/mission_briefing_shadowraid",
min_zoom = 0.4,
total_budget = 8,
default_plans = {},
start_location = {
group = "a",
zoom = 0.8,
x = 2048,
y = 1024
}
}
self.locations.mus = {
{
texture = "guis/textures/pd2/pre_planning/mus_1",
x2 = 10000,
rotation = -90,
map_width = 1,
map_x = -1.05,
x1 = -10000,
map_height = 2,
map_y = 0,
name_id = "menu_pp_mus_loc_a",
y2 = 5000,
y1 = -5000,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/mus_2",
x2 = 10000,
rotation = -90,
map_width = 1,
map_x = 0,
x1 = -10000,
map_height = 2,
map_y = 0,
name_id = "menu_pp_mus_loc_b",
y2 = 5000,
y1 = -5000,
custom_points = {}
},
{
texture = "guis/textures/pd2/pre_planning/mus_3",
x2 = 10000,
rotation = -90,
map_width = 1,
map_x = 1.05,
x1 = -10000,
map_height = 2,
map_y = 0,
name_id = "menu_pp_mus_loc_c",
y2 = 5000,
y1 = -5000,
custom_points = {}
},
mission_briefing_texture = "guis/textures/pd2/pre_planning/mission_briefing_museum",
total_budget = 10,
default_plans = {},
start_location = {
group = "a",
zoom = 1.5,
x = 1024,
y = 521
}
}
self.locations.crojob2 = {
{
texture = "guis/dlcs/the_bomb/textures/pd2/pre_planning/crojob_stage_2_a",
x2 = 10500,
rotation = 0,
map_size = 1,
map_x = 0,
x1 = -9500,
map_y = 0,
name_id = "menu_pp_crojob_stage_2_loc_a",
y2 = 11500,
y1 = -8500,
custom_points = {
{
text_id = "menu_pp_info_crojob2_ship",
rotation = 0,
y = 1134,
to_upper = true,
icon = 45,
x = 964,
post_event = "Play_pln_cr2_14"
},
{
text_id = "menu_pp_info_crojob2_loading_dock_3B",
rotation = 0,
y = 538,
to_upper = true,
icon = 45,
x = 454,
post_event = "Play_pln_cr2_105"
},
{
text_id = "menu_pp_info_crojob2_dock_gate",
rotation = 0,
y = 770,
to_upper = true,
icon = 45,
x = 964,
post_event = "Play_pln_cr2_106"
},
{
text_id = "menu_pp_info_crojob2_control_room_right",
rotation = 0,
y = 768,
to_upper = true,
icon = 45,
x = 1134,
post_event = "Play_pln_cr2_107"
},
{
text_id = "menu_pp_info_crojob2_control_room_left",
rotation = 0,
y = 768,
to_upper = true,
icon = 45,
x = 798,
post_event = "Play_pln_cr2_108"
},
{
text_id = "menu_pp_info_crojob2_fence_gate",
rotation = 0,
y = 702,
to_upper = true,
icon = 45,
x = 82,
post_event = "Play_pln_cr2_109"
},
{
text_id = "menu_pp_info_crojob2_locker_room",
rotation = 0,
y = 1508,
to_upper = true,
icon = 45,
x = 1524,
post_event = "Play_pln_cr2_110"
},
{
text_id = "menu_pp_info_crojob2_office",
rotation = 0,
y = 1336,
to_upper = true,
icon = 45,
x = 1526,
post_event = "Play_pln_cr2_111"
},
{
text_id = "menu_pp_info_crojob2_storage_room",
rotation = 0,
y = 1122,
to_upper = true,
icon = 45,
x = 348,
post_event = "Play_pln_cr2_112"
},
{
text_id = "menu_pp_info_crojob2_ship_control_room_left",
rotation = 0,
y = 1420,
to_upper = true,
icon = 45,
x = 350,
post_event = "Play_pln_cr2_113"
},
{
text_id = "menu_pp_info_crojob2_ship_control_room_right",
rotation = 0,
y = 1118,
to_upper = true,
icon = 45,
x = 1424,
post_event = "Play_pln_cr2_114"
}
}
},
mission_briefing_texture = "guis/textures/pd2/pre_planning/mission_briefing_crojob_stealth",
total_budget = 10,
default_plans = {
escape_plan = "crojob2_escape_van"
},
start_location = {
group = "a",
zoom = 1.5,
x = 1024,
y = 1024
}
}
self.locations.crojob3 = {
{
texture = "guis/dlcs/the_bomb/textures/pd2/pre_planning/crojob_stage_3_a",
x2 = 14950,
rotation = 0,
map_size = 1,
map_x = 0,
x1 = -50,
map_y = -0.5,
name_id = "menu_pp_crojob_stage_3_loc_a",
y2 = 10775,
y1 = -4225,
custom_points = {
{
text_id = "menu_pp_info_crojob3_vault",
rotation = 0,
y = 550,
to_upper = true,
icon = 45,
x = 512,
post_event = "Play_pln_cr3_48"
},
{
text_id = "menu_pp_info_crojob3_water_pump",
rotation = 0,
y = 584,
to_upper = true,
icon = 45,
x = 846,
post_event = "Play_pln_cr3_50"
}
}
},
{
texture = "guis/dlcs/the_bomb/textures/pd2/pre_planning/crojob_stage_3_b",
x2 = 13250,
rotation = 0,
map_size = 1,
map_x = 0,
x1 = -50,
map_y = 0.5,
name_id = "menu_pp_crojob_stage_3_loc_b",
y2 = -4225,
y1 = -19225,
custom_points = {
{
text_id = "menu_pp_info_crojob3_thermite",
rotation = 0,
y = 566,
to_upper = true,
icon = 45,
x = 533,
post_event = "Play_pln_cr3_49"
}
}
},
mission_briefing_texture = "guis/textures/pd2/pre_planning/mission_briefing_crojob_loud",
total_budget = 10,
default_plans = {
escape_plan = "crojob3_escape_boat"
},
start_location = {
group = "a",
zoom = 1,
x = 512,
y = 512
}
}
self.locations.crojob3_night = {
{
texture = "guis/dlcs/the_bomb/textures/pd2/pre_planning/crojob_stage_3_a",
x2 = 14950,
rotation = 0,
map_size = 1,
map_x = 0,
x1 = -50,
map_y = -0.5,
name_id = "menu_pp_crojob_stage_3_loc_a",
y2 = 10775,
y1 = -4225,
custom_points = {
{
text_id = "menu_pp_info_crojob3_vault",
rotation = 0,
y = 550,
to_upper = true,
icon = 45,
x = 512,
post_event = "Play_pln_cr3_48"
},
{
text_id = "menu_pp_info_crojob3_water_pump",
rotation = 0,
y = 584,
to_upper = true,
icon = 45,
x = 846,
post_event = "Play_pln_cr3_50"
}
}
},
{
texture = "guis/dlcs/the_bomb/textures/pd2/pre_planning/crojob_stage_3_b",
x2 = 13250,
rotation = 0,
map_size = 1,
map_x = 0,
x1 = -50,
map_y = 0.5,
name_id = "menu_pp_crojob_stage_3_loc_b",
y2 = -4225,
y1 = -19225,
custom_points = {
{
text_id = "menu_pp_info_crojob3_thermite",
rotation = 0,
y = 566,
to_upper = true,
icon = 45,
x = 533,
post_event = "Play_pln_cr3_49"
}
}
},
mission_briefing_texture = "guis/textures/pd2/pre_planning/mission_briefing_crojob_loud",
total_budget = 10,
default_plans = {
escape_plan = "crojob3_escape_boat"
},
start_location = {
group = "a",
zoom = 1,
x = 512,
y = 512
}
}
self.locations.kenaz = {
{
texture = "guis/dlcs/kenaz/textures/pd2/pre_planning/kenaz_loc_a_df",
map_width = 1,
x2 = 4975,
rotation = 0,
map_x = -1.1,
x1 = -6175,
map_height = 2,
map_y = 0,
name_id = "menu_pp_kenaz_loc_a",
y2 = 7850,
y1 = -14450
},
{
texture = "guis/dlcs/kenaz/textures/pd2/pre_planning/kenaz_loc_b_df",
x2 = 5475,
rotation = 0,
map_width = 1,
map_x = 0,
x1 = -6175,
map_height = 2,
map_y = 0,
name_id = "menu_pp_kenaz_loc_b",
y2 = 8350,
y1 = -14450,
custom_points = {
{
text_id = "menu_pp_info_kenaz_reception",
rotation = -90,
y = 1181,
to_upper = true,
icon = 45,
x = 544,
post_event = "Play_pln_ca1_140"
},
{
text_id = "menu_pp_info_kenaz_lobby",
rotation = -90,
y = 1223,
to_upper = true,
icon = 45,
x = 546,
post_event = "Play_pln_ca1_141"
},
{
text_id = "menu_pp_info_kenaz_pool_area",
rotation = -90,
y = 1020,
to_upper = true,
icon = 45,
x = 229,
post_event = "Play_pln_ca1_142"
},
{
text_id = "menu_pp_info_kenaz_outside_lounge",
rotation = -90,
y = 971,
to_upper = true,
icon = 45,
x = 812,
post_event = "Play_pln_ca1_143"
},
{
text_id = "menu_pp_info_kenaz_gambling_hall",
rotation = -90,
y = 924,
to_upper = true,
icon = 45,
x = 551,
post_event = "Play_pln_ca1_144"
},
{
text_id = "menu_pp_info_kenaz_employees_only",
rotation = -90,
y = 566,
to_upper = true,
icon = 45,
x = 550,
post_event = "Play_pln_ca1_146"
},
{
text_id = "menu_pp_info_kenaz_security_center",
rotation = -90,
y = 625,
to_upper = true,
icon = 45,
x = 546,
post_event = "Play_pln_ca1_147"
}
}
},
{
texture = "guis/dlcs/kenaz/textures/pd2/pre_planning/kenaz_loc_c_df",
map_width = 0.5,
x2 = 200,
rotation = 0,
map_x = 0.85,
x1 = -200,
map_height = 1,
map_y = -0.5,
name_id = "menu_pp_kenaz_loc_c",
y2 = 400,
y1 = -400
},
mission_briefing_texture = "guis/textures/pd2/pre_planning/mission_briefing_casino",
total_budget = 15,
default_plans = {
entry_plan = "kenaz_silent_entry",
escape_plan = "kenaz_limo_escape"
},
start_location = {
group = "a",
zoom = 1,
x = 1024,
y = 1024
},
start_location = {
group = "b",
zoom = 1,
x = 512,
y = 512
},
start_location = {
group = "c",
zoom = 1,
x = 512,
y = 512
}
}
self.locations.pbr = {
{
texture = "guis/dlcs/berry/textures/pd2/pre_planning/base_01",
x2 = -5000,
rotation = 90,
map_size = 1,
map_x = -0.55,
x1 = -15000,
map_y = 0,
name_id = "menu_pp_berry_bpr_loc_a",
y2 = 2400,
y1 = -7600,
custom_points = {}
},
{
texture = "guis/dlcs/berry/textures/pd2/pre_planning/base_02",
x2 = -5100,
rotation = 0,
map_size = 1,
map_x = 0.55,
x1 = -15100,
map_y = 0,
name_id = "menu_pp_berry_bpr_loc_b",
y2 = 2000,
y1 = -8000,
custom_points = {}
},
mission_briefing_texture = "guis/dlcs/berry/textures/pd2/pre_planning/mission_briefing_pbr",
post_event_prefix = "loc",
total_budget = 6,
default_plans = {},
start_location = {
group = "a",
zoom = 1,
x = 1024,
y = 1024
}
}
self.locations.mex = {
{
texture = "guis/dlcs/mex/textures/pd2/pre_planning/mex_01",
map_width = 1,
x2 = 6750,
map_x = -0.6,
x1 = -2450,
map_size = 1,
map_height = 1,
map_y = 1.1,
name_id = "menu_pp_mex_loc_a",
y2 = 6450,
y1 = -2750,
rotation = -0,
custom_points = {
{
text_id = "menu_pp_info_mex_entry",
rotation = 0,
y = 1024,
to_upper = true,
icon = 45,
x = 150
},
{
text_id = "menu_pp_info_mex_shack_north",
rotation = 0,
y = 450,
to_upper = true,
icon = 45,
x = 875
},
{
text_id = "menu_pp_info_mex_shack_south",
rotation = 0,
y = 1700,
to_upper = true,
icon = 45,
x = 975
},
{
text_id = "menu_pp_info_mex_tunnel_entrance_north",
rotation = 0,
y = 370,
to_upper = true,
icon = 45,
x = 1212
},
{
text_id = "menu_pp_info_mex_tunnel_entrance_east",
rotation = 0,
y = 970,
to_upper = true,
icon = 45,
x = 1700
},
{
text_id = "menu_pp_info_mex_tunnel_entrance_south",
rotation = 0,
y = 1650,
to_upper = true,
icon = 45,
x = 1750
}
}
},
{
texture = "guis/dlcs/mex/textures/pd2/pre_planning/mex_02",
map_width = 1,
x2 = 6750,
map_x = -0.6,
x1 = -2450,
map_size = 1,
map_height = 1,
map_y = 0,
name_id = "menu_pp_mex_loc_b",
y2 = 6450,
y1 = -2750,
rotation = -0,
custom_points = {
{
text_id = "menu_pp_info_mex_briefing_room",
rotation = 0,
y = 990,
to_upper = true,
icon = 45,
x = 1018
},
{
text_id = "menu_pp_info_mex_secruity_room_a",
rotation = 0,
y = 915,
to_upper = true,
icon = 45,
x = 860
},
{
text_id = "menu_pp_info_mex_secruity_room_b",
rotation = 0,
y = 930,
to_upper = true,
icon = 45,
x = 1290
}
}
},
{
texture = "guis/dlcs/mex/textures/pd2/pre_planning/mex_03",
map_width = 1,
x2 = 8172,
map_x = 0.6,
x1 = -3822,
map_size = 1,
map_height = 1,
map_y = 1.1,
name_id = "menu_pp_mex_loc_c",
y2 = -3603,
y1 = -15597,
rotation = -0,
custom_points = {
{
text_id = "menu_pp_info_mex_tunnel_exit_north",
rotation = 0,
y = 240,
to_upper = true,
icon = 45,
x = 1420
},
{
text_id = "menu_pp_info_mex_tunnel_exit_west",
rotation = 0,
y = 1270,
to_upper = true,
icon = 45,
x = 260
},
{
text_id = "menu_pp_info_mex_tunnel_exit_south",
rotation = 0,
y = 1630,
to_upper = true,
icon = 45,
x = 1820
},
{
text_id = "menu_pp_info_mex_hangar_a",
rotation = 0,
y = 830,
to_upper = true,
icon = 45,
x = 1630
},
{
text_id = "menu_pp_info_mex_hangar_b",
rotation = 0,
y = 1200,
to_upper = true,
icon = 45,
x = 1720
},
{
text_id = "menu_pp_info_mex_storage_06",
rotation = 0,
y = 980,
to_upper = true,
icon = 45,
x = 610
},
{
text_id = "menu_pp_info_mex_storage_05",
rotation = 0,
y = 805,
to_upper = true,
icon = 45,
x = 610
},
{
text_id = "menu_pp_info_mex_storage_04",
rotation = 0,
y = 730,
to_upper = true,
icon = 45,
x = 610
},
{
text_id = "menu_pp_info_mex_storage_01",
rotation = 0,
y = 300,
to_upper = true,
icon = 45,
x = 710
},
{
text_id = "menu_pp_info_mex_storage_02",
rotation = 0,
y = 300,
to_upper = true,
icon = 45,
x = 800
},
{
text_id = "menu_pp_info_mex_storage_03",
rotation = 0,
y = 300,
to_upper = true,
icon = 45,
x = 880
},
{
text_id = "menu_pp_info_mex_storage_07",
rotation = 0,
y = 1720,
to_upper = true,
icon = 45,
x = 590
},
{
text_id = "menu_pp_info_mex_storage_08",
rotation = 0,
y = 1480,
to_upper = true,
icon = 45,
x = 1210
},
{
text_id = "menu_pp_info_mex_storage_09",
rotation = 0,
y = 1845,
to_upper = true,
icon = 45,
x = 930
}
}
},
{
texture = "guis/dlcs/mex/textures/pd2/pre_planning/mex_04",
map_width = 1,
x2 = 8172,
map_x = 0.6,
x1 = -3822,
map_size = 1,
map_height = 1,
map_y = 0,
name_id = "menu_pp_mex_loc_d",
y2 = -3603,
y1 = -15597,
rotation = -0,
custom_points = {
{
text_id = "menu_pp_info_mex_controlroom",
rotation = 0,
y = 700,
to_upper = true,
icon = 45,
x = 580
},
{
text_id = "menu_pp_info_mex_secruity_room_c",
rotation = 0,
y = 575,
to_upper = true,
icon = 45,
x = 975
},
{
text_id = "menu_pp_info_mex_secruity_room_d",
rotation = 0,
y = 840,
to_upper = true,
icon = 45,
x = 550
},
{
text_id = "menu_pp_info_mex_secruity_room_e",
rotation = 0,
y = 575,
to_upper = true,
icon = 45,
x = 1070
}
}
},
{
texture = "guis/dlcs/mex/textures/pd2/pre_planning/mex_05",
map_width = 1,
x2 = 8172,
map_x = 0.6,
x1 = -3822,
map_size = 1,
map_height = 1,
map_y = -1.1,
name_id = "menu_pp_mex_loc_e",
y2 = -3603,
y1 = -15597,
rotation = -0,
custom_points = {
{
text_id = "menu_pp_info_mex_roof_entrance_a",
rotation = 0,
y = 530,
to_upper = true,
icon = 45,
x = 950
},
{
text_id = "menu_pp_info_mex_roof_entrance_b",
rotation = 0,
y = 900,
to_upper = true,
icon = 45,
x = 800
}
}
},
{
texture = "guis/dlcs/mex/textures/pd2/pre_planning/mex_boarder_01",
map_size = 1,
skip_for_grid = true,
map_y = -0.3,
x2 = 10000,
map_x = 0,
x1 = -10000,
map_height = 4,
map_width = 0.12,
name_id = "menu_pp_mex_loc_boarder",
y2 = 5000,
y1 = -5000,
rotation = -0
},
grid_width_mul = 1,
post_event_prefix = "loc",
mission_briefing_texture = "guis/dlcs/mex/textures/pd2/pre_planning/mex_01",
total_budget = 10,
default_plans = {},
start_location = {
group = "a",
zoom = 1.5,
x = 1024,
y = 1024
},
active_location_groups = {
"a",
"b"
}
}
self.locations.bex = {
{
texture = "guis/dlcs/bex/textures/pd2/pre_planning/bex_01",
x2 = 6000,
rotation = 180,
map_size = 1,
map_x = -0.55,
map_y = 0,
name_id = "menu_pp_bex_bpr_loc_a",
y2 = 5000,
y1 = -7000,
x1 = -0 - 6000,
custom_points = {}
},
{
texture = "guis/dlcs/bex/textures/pd2/pre_planning/bex_02",
x2 = 6000,
rotation = 180,
map_size = 1,
map_x = 0.25,
map_y = 0,
name_id = "menu_pp_bex_bpr_loc_b",
y2 = 5000,
y1 = -7000,
x1 = -0 - 6000,
custom_points = {}
},
{
texture = "guis/dlcs/bex/textures/pd2/pre_planning/bex_03",
x2 = 6000,
rotation = 180,
map_size = 1,
map_x = 1.05,
map_y = 0,
name_id = "menu_pp_bex_bpr_loc_c",
y2 = 5000,
y1 = -7000,
x1 = -0 - 6000,
custom_points = {}
},
mission_briefing_texture = "guis/dlcs/bex/textures/pd2/pre_planning/bex_preview",
post_event_prefix = "loc",
total_budget = 10,
default_plans = {},
start_location = {
group = "a",
zoom = 1,
x = 512,
y = 512
}
}
self.locations.pex = {
{
texture = "guis/dlcs/pex/textures/pd2/pre_planning/pex_01",
x2 = 5500,
rotation = 0,
map_size = 1,
map_x = -1.5,
map_y = 0,
name_id = "menu_pp_pex_bpr_loc_a",
x1 = -0 - 5500,
y1 = -0 - 5500,
y2 = -0 + 5500,
custom_points = {}
},
{
texture = "guis/dlcs/pex/textures/pd2/pre_planning/pex_02",
x2 = 5500,
rotation = 0,
map_size = 1,
map_x = -0.4,
map_y = 0,
name_id = "menu_pp_pex_bpr_loc_b",
x1 = -0 - 5500,
y1 = -0 - 5500,
y2 = -0 + 5500,
custom_points = {}
},
mission_briefing_texture = "guis/dlcs/pex/textures/pd2/pre_planning/pex_preview",
post_event_prefix = "loc",
total_budget = 10,
default_plans = {},
start_location = {
group = "a",
zoom = 1,
x = 512,
y = 512
}
}
self.locations.fex = {
{
texture = "guis/dlcs/fex/textures/pd2/pre_planning/fex_01",
x2 = 6000,
rotation = 0,
map_size = 1,
map_x = -0.55,
map_y = 0,
name_id = "menu_pp_fex_bpr_loc_a",
x1 = -0 - 6000,
y1 = -0 - 6000,
y2 = -0 + 6000,
custom_points = {}
},
{
texture = "guis/dlcs/fex/textures/pd2/pre_planning/fex_02",
x2 = 6000,
rotation = 0,
map_size = 1,
map_x = 0.55,
map_y = 0,
name_id = "menu_pp_fex_bpr_loc_b",
x1 = -0 - 6000,
y1 = -0 - 6000,
y2 = -0 + 6000,
custom_points = {}
},
mission_briefing_texture = "guis/dlcs/fex/textures/pd2/pre_planning/fex_preview",
post_event_prefix = "loc",
total_budget = 10,
default_plans = {
escape_plan = "fex_loud_escape_with_car",
entry_plan_generic = "fex_stealth_entry_with_thermite"
},
start_location = {
group = "a",
zoom = 1,
x = 512,
y = 512
}
}
self.locations.chas = {
{
texture = "guis/dlcs/chas/textures/pd2/pre_planning/chas_01",
x2 = 3500,
rotation = 0,
map_size = 1,
map_x = -0.55,
x1 = -9500,
map_y = 0,
name_id = "menu_pp_chas_bpr_loc_a",
y2 = 8500,
y1 = -4500,
custom_points = {}
},
{
texture = "guis/dlcs/chas/textures/pd2/pre_planning/chas_02",
x2 = 3500,
rotation = 0,
map_size = 1,
map_x = 0.55,
x1 = -9500,
map_y = 0,
name_id = "menu_pp_chas_bpr_loc_b",
y2 = 8500,
y1 = -4500,
custom_points = {}
},
mission_briefing_texture = "guis/dlcs/chas/textures/pd2/pre_planning/chas_preview",
post_event_prefix = "loc",
total_budget = 10,
default_plans = {},
start_location = {
group = "a",
zoom = 1,
x = 512,
y = 512
}
}
self.locations.sand = {
{
texture = "guis/dlcs/sand/textures/pd2/pre_planning/sand_01",
x2 = 20700,
rotation = 0,
map_size = 1,
map_x = -0.55,
x1 = -9300,
map_y = 0,
name_id = "menu_pp_sand_bpr_loc_a",
y2 = 13700,
y1 = -16300,
custom_points = {}
},
{
texture = "guis/dlcs/sand/textures/pd2/pre_planning/sand_02",
x2 = 20700,
rotation = 0,
map_size = 1,
map_x = -0.55,
x1 = -9300,
map_y = 0.75,
name_id = "menu_pp_sand_bpr_loc_b",
y2 = 13700,
y1 = -16300,
custom_points = {}
},
mission_briefing_texture = "guis/dlcs/sand/textures/pd2/pre_planning/sand_preview",
post_event_prefix = "loc",
total_budget = 10,
default_plans = {},
start_location = {
group = "a",
zoom = 1,
x = 512,
y = 512
}
}
self.locations.chca = {
{
texture = "guis/dlcs/chca/textures/pd2/pre_planning/chca_01",
x2 = 5000,
rotation = 0,
map_size = 1,
map_x = -0.55,
x1 = -25000,
map_y = 0,
name_id = "menu_pp_chca_bpr_loc_a",
y2 = 21000,
y1 = -9000,
custom_points = {}
},
{
texture = "guis/dlcs/chca/textures/pd2/pre_planning/chca_02",
x2 = 5000,
rotation = 0,
map_size = 1,
map_x = 0,
x1 = -25000,
map_y = 0,
name_id = "menu_pp_chca_bpr_loc_b",
y2 = 21000,
y1 = -9000,
custom_points = {}
},
{
texture = "guis/dlcs/chca/textures/pd2/pre_planning/chca_03",
x2 = 5000,
rotation = 0,
map_size = 1,
map_x = 0.55,
x1 = -25000,
map_y = 0,
name_id = "menu_pp_chca_bpr_loc_c",
y2 = 21000,
y1 = -9000,
custom_points = {}
},
mission_briefing_texture = "guis/dlcs/chca/textures/pd2/pre_planning/chca_preview",
post_event_prefix = "loc",
total_budget = 10,
default_plans = {
entry_plan_generic = "chca_entry_as_guest"
},
start_location = {
group = "a",
zoom = 1,
x = 512,
y = 512
}
}
end
function PrePlanningTweakData:get_level_data(level_id)
return self.locations[level_id] or {}
end
| 412 | 0.746553 | 1 | 0.746553 | game-dev | MEDIA | 0.567686 | game-dev | 0.937631 | 1 | 0.937631 |
ErichStyger/McuLib | 9,645 | src/McuEvents.c | /* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : McuEvents.h
** Project : FRDM-K64F_Generator
** Processor : MK64FN1M0VLL12
** Component : SimpleEvents
** Version : Component 01.059, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2020-08-14, 06:24, # CodeGen: 679
** Abstract :
**
** Settings :
** Component name : McuEvents
** SDK : McuLib
** Critical Section : McuCriticalSection
** Initialize on Init : yes
** Event Name List : (string list)
** Contents :
** SetEvent - void McuEvents_SetEvent(uint8_t event);
** ClearEvent - void McuEvents_ClearEvent(uint8_t event);
** EventsPending - bool McuEvents_EventsPending(void);
** GetEvent - bool McuEvents_GetEvent(uint8_t event);
** GetClearEvent - bool McuEvents_GetClearEvent(uint8_t event);
** HandleEvent - void McuEvents_HandleEvent(void);
**
** * Copyright (c) 2011-2020, Erich Styger
** * Web: https://mcuoneclipse.com
** * SourceForge: https://sourceforge.net/projects/mcuoneclipse
** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx
** * All rights reserved.
** *
** * Redistribution and use in source and binary forms, with or without modification,
** * are permitted provided that the following conditions are met:
** *
** * - Redistributions of source code must retain the above copyright notice, this list
** * of conditions and the following disclaimer.
** *
** * - Redistributions in binary form must reproduce the above copyright notice, this
** * list of conditions and the following disclaimer in the documentation and/or
** * other materials provided with the distribution.
** *
** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** ###################################################################*/
/*!
** @file McuEvents.h
** @version 01.00
** @brief
**
*/
/*!
** @addtogroup McuEvents_module McuEvents module documentation
** @{
*/
/* MODULE McuEvents. */
#include "McuEvents.h"
#include "McuCriticalSection.h"
static uint8_t McuEvents_Events[((McuEvents_CONFIG_NOF_EVENTS-1)/8)+1]; /*!< Bit set of events */
/*
** ===================================================================
** Method : SetEvent (component SimpleEvents)
**
** Description :
** Sets an event (number) be processed by the next HandleEvent()
** call
** Parameters :
** NAME - DESCRIPTION
** event - The event (number) to be set so it
** will be called by the HandleEvent() routine
** later on. Note that there cannot be
** multiple instances of an event, and the
** lower the event number, the higher the
** priority.
** Returns : Nothing
** ===================================================================
*/
void McuEvents_SetEvent(uint8_t event)
{
McuCriticalSection_CriticalVariable();
/* event is in the range of 0..255: find bit position in array */
McuCriticalSection_EnterCritical();
McuEvents_Events[event/8] |= 0x80>>(event%8);
McuCriticalSection_ExitCritical();
}
/*
** ===================================================================
** Method : ClearEvent (component SimpleEvents)
**
** Description :
** Clears one event (number). If the event is not set, then the
** function has no effect.
** Parameters :
** NAME - DESCRIPTION
** event - The event number to be cleared.
** Returns : Nothing
** ===================================================================
*/
void McuEvents_ClearEvent(uint8_t event)
{
McuCriticalSection_CriticalVariable();
/* event is in the range of 0..255: find bit position in array */
McuCriticalSection_EnterCritical();
McuEvents_Events[event/8] &= ~(0x80>>(event%8));
McuCriticalSection_ExitCritical();
}
/*
** ===================================================================
** Method : GetEvent (component SimpleEvents)
**
** Description :
** Allows to check if an event is set or not.
** Parameters :
** NAME - DESCRIPTION
** event - The event number to check. If the
** event is set, the function returns TRUE.
** Returns :
** --- - none
** ===================================================================
*/
bool McuEvents_GetEvent(uint8_t event)
{
/* event is in the range of 0..255: find bit position in array */
return (bool)((McuEvents_Events[event/8]&(0x80>>(event%8)))!=0);
}
/*
** ===================================================================
** Method : GetClearEvent (component SimpleEvents)
**
** Description :
** Allows to check if an event is set or not. If set, it will
** be automatically cleared.
** Parameters :
** NAME - DESCRIPTION
** event - The event number to check. If the
** event is set, the function returns TRUE.
** Returns :
** --- - none
** ===================================================================
*/
bool McuEvents_GetClearEvent(uint8_t event)
{
bool isSet = FALSE;
McuCriticalSection_CriticalVariable();
McuCriticalSection_EnterCritical();
if (McuEvents_GetEvent(event)) { /* event present */
McuEvents_Events[event/8] &= ~(0x80>>(event%8)); /* clear event */
isSet = TRUE;
}
McuCriticalSection_ExitCritical();
return isSet;
}
/*
** ===================================================================
** Method : EventsPending (component SimpleEvents)
**
** Description :
** Returns true if any events are pending, false otherwise
** Parameters : None
** Returns :
** --- - True in case any events are pending, false
** otherwise.
** ===================================================================
*/
bool McuEvents_EventsPending(void)
{
#if McuEvents_CONFIG_NOF_EVENTS<=8
return (bool)(McuEvents_Events[0]!=0);
#elif McuEvents_CONFIG_NOF_EVENTS<=16
return (bool)(McuEvents_Events[0]!=0 || McuEvents_Events[1]!=0);
#elif McuEvents_CONFIG_NOF_EVENTS<=24
return (McuEvents_Events[0]!=0 || McuEvents_Events[1]!=0 || McuEvents_Events[2]!=0);
#elif McuEvents_CONFIG_NOF_EVENTS<=32
return (bool)(McuEvents_Events[0]!=0 || McuEvents_Events[1]!=0 || McuEvents_Events[2]!=0 || McuEvents_Events[3]!=0);
#else /* iterate through the array */
char i; /* local counter */
for(i=0; i<(McuEvents_CONFIG_NOF_EVENTS/8)+1; i++) {
if (McuEvents_Events[i] != 0) { /* there are events pending */
return TRUE;
}
}
return FALSE;
#endif
}
/*
** ===================================================================
** Method : HandleEvent (component SimpleEvents)
**
** Description :
** Event handler, to be called periodically.
** Parameters : None
** Returns : Nothing
** ===================================================================
*/
void McuEvents_HandleEvent(void)
{
/* Handle the one with the highest priority. */
uint8_t event;
McuCriticalSection_CriticalVariable();
McuCriticalSection_EnterCritical();
for (event=0; event<McuEvents_CONFIG_NOF_EVENTS; event++) { /* does a test on every event */
if (McuEvents_GetEvent(event)) { /* event present */
McuEvents_Events[event/8] &= ~(0x80>>(event%8)); /* clear event */
break; /* get out of loop */
}
}
McuCriticalSection_ExitCritical();
#if McuEvents_CONFIG_USE_EVENT_HANDLER
/*lint -save -e522 function lacks side effect */
if (event != McuEvents_CONFIG_NOF_EVENTS) {
McuEvents_CONFIG_EVENT_HANDLER_NAME(event);
}
/*lint -restore */
#endif
}
/*
** ===================================================================
** Method : McuEvents_Init (component SimpleEvents)
**
** Description :
** This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
void McuEvents_Init(void)
{
#if McuEvents_CONFIG_NOF_EVENTS<=8
McuEvents_Events[0] = 0; /* initialize data structure */
#else
uint8_t i;
for(i=0;i<sizeof(McuEvents_Events); i++) {
McuEvents_Events[i] = 0; /* initialize data structure */
}
#endif
}
/* END McuEvents. */
/*!
** @}
*/
| 412 | 0.785605 | 1 | 0.785605 | game-dev | MEDIA | 0.289558 | game-dev | 0.797463 | 1 | 0.797463 |
PolarisSS13/Polaris | 1,958 | code/modules/xenoarcheaology/effects/hurt.dm | /datum/artifact_effect/uncommon/hurt
name = "hurt"
effect_type = EFFECT_ORGANIC
effect_color = "#6d1212"
/datum/artifact_effect/uncommon/hurt/DoEffectTouch(mob/living/user)
if (user)
var/weakness = GetAnomalySusceptibility(user)
if (iscarbon(user) && prob(weakness * 100))
var/mob/living/carbon/C = user
to_chat(C, "<span class='danger'>A painful discharge of energy strikes you!</span>")
C.adjustOxyLoss(rand(5,25) * weakness)
C.adjustToxLoss(rand(5,25) * weakness)
C.adjustBruteLoss(rand(5,25) * weakness)
C.adjustFireLoss(rand(5,25) * weakness)
C.adjustBrainLoss(rand(1,5) * weakness)
C.apply_effect(25 * weakness, IRRADIATE)
C.adjust_nutrition(-50 * weakness)
C.nutrition -= min(50 * weakness, C.nutrition)
C.make_dizzy(6 * weakness)
C.weakened += 6 * weakness
/datum/artifact_effect/uncommon/hurt/DoEffectAura()
var/atom/holder = get_master_holder()
if (holder)
var/turf/T = get_turf(holder)
for (var/mob/living/carbon/C in range(src.effectrange,T))
var/weakness = GetAnomalySusceptibility(C)
if (prob(weakness * 100))
if (prob(10))
to_chat(C, "<span class='danger'>You feel a painful force radiating from something nearby.</span>")
C.adjustBruteLoss(1 * weakness)
C.adjustFireLoss(1 * weakness)
C.adjustToxLoss(1 * weakness)
C.adjustOxyLoss(1 * weakness)
C.adjustBrainLoss(0.1 * weakness)
C.updatehealth()
/datum/artifact_effect/uncommon/hurt/DoEffectPulse()
var/atom/holder = get_master_holder()
if (holder)
var/turf/T = get_turf(holder)
for (var/mob/living/carbon/C in range(effectrange, T))
var/weakness = GetAnomalySusceptibility(C)
if (prob(weakness * 100))
to_chat(C, "<span class='danger'>A wave of painful energy strikes you!</span>")
C.adjustBruteLoss(3 * weakness)
C.adjustFireLoss(3 * weakness)
C.adjustToxLoss(3 * weakness)
C.adjustOxyLoss(3 * weakness)
C.adjustBrainLoss(0.1 * weakness)
C.updatehealth()
| 412 | 0.723391 | 1 | 0.723391 | game-dev | MEDIA | 0.96793 | game-dev | 0.947 | 1 | 0.947 |
jarjin/uLua | 1,231 | Assets/uLua/Core/LuaObjectMap.cs | using UnityEngine;
using System.Collections.Generic;
//忘了原来的设计了,还是用系统的吧
public class LuaObjectMap
{
private List<object> list;
private Queue<int> pool;
public LuaObjectMap()
{
list = new List<object>(1024);
pool = new Queue<int>(1024);
}
public object this[int i]
{
get { return list[i]; }
}
public int Add(object obj)
{
int index = -1;
if (pool.Count > 0)
{
index = pool.Dequeue();
list[index] = obj;
}
else
{
list.Add(obj);
index = list.Count - 1;
}
return index;
}
public bool TryGetValue(int index, out object obj)
{
if (index >= 0 && index < list.Count)
{
obj = list[index];
return obj != null;
}
obj = null;
return false;
}
public object Remove(int index)
{
if (index >= 0 && index < list.Count)
{
object o = list[index];
if (o != null)
{
pool.Enqueue(index);
}
list[index] = null;
return o;
}
return null;
}
}
| 412 | 0.700851 | 1 | 0.700851 | game-dev | MEDIA | 0.58112 | game-dev | 0.840182 | 1 | 0.840182 |
qnpiiz/rich-2.0 | 2,821 | src/main/java/net/minecraft/world/gen/feature/structure/OceanRuinStructure.java | package net.minecraft.world.gen.feature.structure;
import com.mojang.serialization.Codec;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MutableBoundingBox;
import net.minecraft.util.registry.DynamicRegistries;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.ChunkGenerator;
import net.minecraft.world.gen.feature.template.TemplateManager;
public class OceanRuinStructure extends Structure<OceanRuinConfig>
{
public OceanRuinStructure(Codec<OceanRuinConfig> p_i232109_1_)
{
super(p_i232109_1_);
}
public Structure.IStartFactory<OceanRuinConfig> getStartFactory()
{
return OceanRuinStructure.Start::new;
}
public static class Start extends StructureStart<OceanRuinConfig>
{
public Start(Structure<OceanRuinConfig> p_i225875_1_, int p_i225875_2_, int p_i225875_3_, MutableBoundingBox p_i225875_4_, int p_i225875_5_, long p_i225875_6_)
{
super(p_i225875_1_, p_i225875_2_, p_i225875_3_, p_i225875_4_, p_i225875_5_, p_i225875_6_);
}
public void func_230364_a_(DynamicRegistries p_230364_1_, ChunkGenerator p_230364_2_, TemplateManager p_230364_3_, int p_230364_4_, int p_230364_5_, Biome p_230364_6_, OceanRuinConfig p_230364_7_)
{
int i = p_230364_4_ * 16;
int j = p_230364_5_ * 16;
BlockPos blockpos = new BlockPos(i, 90, j);
Rotation rotation = Rotation.randomRotation(this.rand);
OceanRuinPieces.func_204041_a(p_230364_3_, blockpos, rotation, this.components, this.rand, p_230364_7_);
this.recalculateStructureSize();
}
}
public static enum Type implements IStringSerializable
{
WARM("warm"),
COLD("cold");
public static final Codec<OceanRuinStructure.Type> field_236998_c_ = IStringSerializable.createEnumCodec(OceanRuinStructure.Type::values, OceanRuinStructure.Type::getType);
private static final Map<String, OceanRuinStructure.Type> BY_NAME = Arrays.stream(values()).collect(Collectors.toMap(OceanRuinStructure.Type::getName, (p_215134_0_) -> {
return p_215134_0_;
}));
private final String name;
private Type(String nameIn)
{
this.name = nameIn;
}
public String getName()
{
return this.name;
}
@Nullable
public static OceanRuinStructure.Type getType(String nameIn)
{
return BY_NAME.get(nameIn);
}
public String getString()
{
return this.name;
}
}
}
| 412 | 0.503754 | 1 | 0.503754 | game-dev | MEDIA | 0.770078 | game-dev | 0.746428 | 1 | 0.746428 |
HUHNcode/Lucid-addon | 9,610 | src/main/java/huhncode/lucid/lucidaddon/modules/.experimental/FakeLag.java | package huhncode.lucid.lucidaddon.modules;
import huhncode.lucid.lucidaddon.LucidAddon;
import meteordevelopment.meteorclient.events.packets.PacketEvent;
import meteordevelopment.meteorclient.events.world.TickEvent;
import meteordevelopment.meteorclient.settings.*;
import meteordevelopment.meteorclient.systems.friends.Friends;
import meteordevelopment.meteorclient.systems.modules.Module;
import meteordevelopment.orbit.EventHandler;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.BowItem;
import net.minecraft.item.CrossbowItem;
import net.minecraft.item.PotionItem;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.c2s.common.KeepAliveC2SPacket;
import net.minecraft.network.packet.c2s.play.*;
import net.minecraft.network.packet.s2c.play.EntityVelocityUpdateS2CPacket;
import net.minecraft.network.packet.s2c.play.ExplosionS2CPacket;
import net.minecraft.network.packet.s2c.play.HealthUpdateS2CPacket;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Vec3d;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ThreadLocalRandom;
public class FakeLag extends Module {
public enum Mode {
CONSTANT,
DYNAMIC
}
private final SettingGroup sgGeneral = settings.getDefaultGroup();
private final SettingGroup sgFlush = settings.createGroup("Flush Conditions");
private final Setting<Mode> mode = sgGeneral.add(new EnumSetting.Builder<Mode>()
.name("mode")
.description("When to lag.")
.defaultValue(Mode.DYNAMIC)
.build()
);
private final Setting<Double> range = sgGeneral.add(new DoubleSetting.Builder()
.name("range")
.description("The range to check for enemies in dynamic mode.")
.defaultValue(4.5)
.min(0)
.sliderMax(10)
.visible(() -> mode.get() == Mode.DYNAMIC)
.build()
);
private final Setting<Integer> minDelay = sgGeneral.add(new IntSetting.Builder()
.name("min-delay")
.description("The minimum delay in milliseconds to hold packets.")
.defaultValue(300)
.min(0)
.sliderMax(1000)
.build()
);
private final Setting<Integer> maxDelay = sgGeneral.add(new IntSetting.Builder()
.name("max-delay")
.description("The maximum delay in milliseconds to hold packets.")
.defaultValue(600)
.min(0)
.sliderMax(1000)
.build()
);
private final Setting<Integer> recoilTime = sgGeneral.add(new IntSetting.Builder()
.name("recoil-time")
.description("How long to wait in milliseconds after flushing before lagging again.")
.defaultValue(250)
.min(0)
.sliderMax(1000)
.build()
);
private final Setting<Boolean> flushOnEntityInteract = sgFlush.add(new BoolSetting.Builder()
.name("flush-on-entity-interact")
.description("Flushes packets when you attack or interact with an entity.")
.defaultValue(true)
.build()
);
private final Setting<Boolean> flushOnBlockInteract = sgFlush.add(new BoolSetting.Builder()
.name("flush-on-block-interact")
.description("Flushes packets when you interact with a block.")
.defaultValue(true)
.build()
);
private final Setting<Boolean> flushOnAction = sgFlush.add(new BoolSetting.Builder()
.name("flush-on-action")
.description("Flushes packets on player actions like starting to sprint or sneak.")
.defaultValue(true)
.build()
);
private final Queue<Packet<?>> packetQueue = new ConcurrentLinkedQueue<>();
private Vec3d serverSidePos;
private long recoilUntil = 0;
private long lagStartedTime = 0;
private int currentDelay = 0;
private boolean isEnemyNearby = false;
public FakeLag() {
super(LucidAddon.CATEGORY, "fake-lag", "Holds back packets to make you harder to hit.");
}
@Override
public void onActivate() {
reset();
}
@Override
public void onDeactivate() {
flush();
}
private void reset() {
packetQueue.clear();
recoilUntil = 0;
lagStartedTime = 0;
currentDelay = 0;
if (mc.player != null) {
serverSidePos = mc.player.getPos();
} else {
serverSidePos = Vec3d.ZERO;
}
}
private void flush() {
if (mc.getNetworkHandler() == null) {
packetQueue.clear();
return;
}
synchronized (packetQueue) {
while (!packetQueue.isEmpty()) {
mc.getNetworkHandler().sendPacket(packetQueue.poll());
}
}
if (mc.player != null) {
serverSidePos = mc.player.getPos();
}
recoilUntil = System.currentTimeMillis() + recoilTime.get();
lagStartedTime = 0;
}
@EventHandler
private void onTick(TickEvent.Pre event) {
if (mode.get() == Mode.DYNAMIC) {
isEnemyNearby = findEnemy();
}
if (lagStartedTime > 0 && System.currentTimeMillis() - lagStartedTime > currentDelay) {
flush();
}
}
@EventHandler
private void onPacketReceive(PacketEvent.Receive event) {
if (mc.player == null) return;
if (event.packet instanceof HealthUpdateS2CPacket packet && packet.getHealth() < mc.player.getHealth()) {
flush();
return;
}
if (event.packet instanceof EntityVelocityUpdateS2CPacket packet && packet.getId() == mc.player.getId()) {
if (packet.getVelocity().lengthSquared() > 0.01) {
flush();
return;
}
}
if (event.packet instanceof ExplosionS2CPacket) {
flush();
}
}
@EventHandler
private void onPacketSend(PacketEvent.Send event) {
if (mc.player == null || mc.player.isDead() || mc.player.isTouchingWater() || mc.currentScreen != null) {
if (!packetQueue.isEmpty()) flush();
return;
}
if (System.currentTimeMillis() < recoilUntil) return;
if (mc.player.isUsingItem()) {
var item = mc.player.getActiveItem().getItem();
if (item.isFood() || item instanceof PotionItem || item instanceof BowItem || item instanceof CrossbowItem) {
if (!packetQueue.isEmpty()) flush();
return;
}
}
if (flushOnEntityInteract.get() && (event.packet instanceof PlayerInteractEntityC2SPacket || event.packet instanceof HandSwingC2SPacket)) {
if (!packetQueue.isEmpty()) flush();
return;
}
if (flushOnBlockInteract.get() && (event.packet instanceof PlayerInteractBlockC2SPacket || event.packet instanceof UpdateSignC2SPacket)) {
if (!packetQueue.isEmpty()) flush();
return;
}
if (flushOnAction.get() && event.packet instanceof PlayerActionC2SPacket) {
if (!packetQueue.isEmpty()) flush();
return;
}
if (!(event.packet instanceof PlayerMoveC2SPacket) && !(event.packet instanceof KeepAliveC2SPacket)) {
return;
}
if (mode.get() == Mode.DYNAMIC) {
if (!isEnemyNearby) {
if (!packetQueue.isEmpty()) flush();
return;
}
Box playerBoxAtServerPos = mc.player.getBoundingBox().offset(serverSidePos.subtract(mc.player.getPos()));
boolean shouldNotLag = false;
double closestClientDistSq = Double.MAX_VALUE;
double closestServerDistSq = Double.MAX_VALUE;
for (PlayerEntity p : mc.world.getPlayers()) {
if (!shouldAttack(p)) continue;
if (p.getBoundingBox().intersects(playerBoxAtServerPos)) {
shouldNotLag = true;
break;
}
double clientDistSq = mc.player.getPos().squaredDistanceTo(p.getPos());
double serverDistSq = serverSidePos.squaredDistanceTo(p.getPos());
if (clientDistSq < closestClientDistSq) closestClientDistSq = clientDistSq;
if (serverDistSq < closestServerDistSq) closestServerDistSq = serverDistSq;
}
if (shouldNotLag || closestServerDistSq < closestClientDistSq) {
if (!packetQueue.isEmpty()) flush();
return;
}
}
queuePacket(event.packet);
event.cancel();
}
private void queuePacket(Packet<?> packet) {
synchronized (packetQueue) {
packetQueue.add(packet);
}
if (packet instanceof PlayerMoveC2SPacket p) {
serverSidePos = new Vec3d(p.getX(serverSidePos.x), p.getY(serverSidePos.y), p.getZ(serverSidePos.z));
}
if (lagStartedTime == 0) {
lagStartedTime = System.currentTimeMillis();
currentDelay = ThreadLocalRandom.current().nextInt(minDelay.get(), maxDelay.get() + 1);
}
}
private boolean findEnemy() {
if (mc.world == null || mc.player == null) return false;
for (PlayerEntity player : mc.world.getPlayers()) {
if (shouldAttack(player)) return true;
}
return false;
}
private boolean shouldAttack(PlayerEntity p) {
if (p == mc.player || p.isDead() || !Friends.get().shouldAttack(p) || p.isCreative()) return false;
return mc.player.distanceTo(p) <= range.get();
}
} | 412 | 0.945895 | 1 | 0.945895 | game-dev | MEDIA | 0.743442 | game-dev,networking | 0.965212 | 1 | 0.965212 |
Straw1997/UnityURPCloud | 2,142 | Clouds/Library/PackageCache/com.unity.shadergraph@10.2.2/Editor/Util/UIUtilities.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Graphing.Util
{
static class UIUtilities
{
public static bool ItemsReferenceEquals<T>(this IList<T> first, IList<T> second)
{
if (first.Count != second.Count)
{
return false;
}
for (int i = 0; i < first.Count; i++)
{
if (!ReferenceEquals(first[i], second[i]))
{
return false;
}
}
return true;
}
public static int GetHashCode(params object[] objects)
{
return GetHashCode(objects.AsEnumerable());
}
public static int GetHashCode<T>(IEnumerable<T> objects)
{
var hashCode = 17;
foreach (var @object in objects)
{
hashCode = hashCode * 31 + (@object == null ? 79 : @object.GetHashCode());
}
return hashCode;
}
public static IEnumerable<T> ToEnumerable<T>(this T item)
{
yield return item;
}
public static void Add<T>(this VisualElement visualElement, T elementToAdd, Action<T> action)
where T : VisualElement
{
visualElement.Add(elementToAdd);
action(elementToAdd);
}
public static IEnumerable<Type> GetTypesOrNothing(this Assembly assembly)
{
try
{
return assembly.GetTypes();
}
catch
{
return Enumerable.Empty<Type>();
}
}
public static Vector2 CalculateCentroid(IEnumerable<Vector2> nodePositions)
{
Vector2 centroid = Vector2.zero;
int count = 1;
foreach (var position in nodePositions)
{
centroid = centroid + (position - centroid) / count;
++count;
}
return centroid;
}
}
}
| 412 | 0.91271 | 1 | 0.91271 | game-dev | MEDIA | 0.433152 | game-dev | 0.977879 | 1 | 0.977879 |
lip6/coriolis | 6,595 | hurricane/src/configuration/hurricane/configuration/PyParameter.h | // -*- C++ -*-
//
// This file is part of the Coriolis Software.
// Copyright (c) UPMC 2020-2020, All Rights Reserved
//
// +-----------------------------------------------------------------+
// | C O R I O L I S |
// | C o n f i g u r a t i o n D a t a - B a s e |
// | |
// | Author : Jean-Paul CHAPUT |
// | E-mail : Jean-Paul.Chaput@lip6.fr |
// | =============================================================== |
// | C++ Header : "./hurricane/configuration/PyParameter.h" |
// +-----------------------------------------------------------------+
#pragma once
#include "hurricane/configuration/PyTypeManager.h"
#include "hurricane/configuration/Parameter.h"
#include "hurricane/configuration/ParameterWidget.h"
namespace Cfg {
extern "C" {
extern PyMethodDef PyParameter_Methods[];
extern PyMethodDef PyParameterPriority_Methods[];
extern PyMethodDef PyParameterType_Methods[];
extern PyMethodDef PyParameterFlags_Methods[];
extern PyGetSetDef PyParameter_Getsets[];
} // extern "C".
} // Cfg namespace.
inline bool pyToC ( PyObject* pyArg, Cfg::Parameter::Type* arg )
{
if (not PyLong_Check(pyArg)) return false;
long type = PyLong_AsLong( pyArg );
switch ( type ) {
case Cfg::Parameter::Unknown:
case Cfg::Parameter::String:
case Cfg::Parameter::Bool:
case Cfg::Parameter::Int:
case Cfg::Parameter::Enumerate:
case Cfg::Parameter::Double:
case Cfg::Parameter::Percentage:
*arg = (Cfg::Parameter::Type)type;
break;
default:
return false;
}
return true;
}
inline bool pyToC ( PyObject* pyArg, Cfg::Parameter::Priority* arg )
{
if (not PyLong_Check(pyArg)) return false;
long priority = PyLong_AsLong( pyArg );
switch ( priority ) {
case Cfg::Parameter::UseDefault:
case Cfg::Parameter::ApplicationBuiltin:
case Cfg::Parameter::ConfigurationFile:
case Cfg::Parameter::UserFile:
case Cfg::Parameter::CommandLine:
case Cfg::Parameter::Interactive:
*arg = (Cfg::Parameter::Priority)priority;
break;
default:
return false;
}
return true;
}
template<>
inline PyObject* cToPy<Cfg::Parameter::Type>( Cfg::Parameter::Type type )
{ return Py_BuildValue( "i", type ); }
template<>
inline PyObject* cToPy<Cfg::Parameter::Priority>( Cfg::Parameter::Priority pri )
{ return Py_BuildValue( "i", pri ); }
template<>
inline PyObject* cToPy<Cfg::Parameter::Flags>( Cfg::Parameter::Flags flags )
{ return Py_BuildValue( "i", flags ); }
namespace Isobar3 {
template<>
inline void pyTypePostInit<Cfg::Parameter> ( PyTypeObject* typeObject )
{
// std::cerr << "pyTypePostInit<Cfg::Parameter>()" << std::endl;
PyTypeManagerNonDBo<Cfg::Parameter::Priority>::create( (PyObject*)typeObject
, Cfg::PyParameterPriority_Methods
, NULL
, PyTypeManager::NoCppDelete
, "Priority"
);
PyTypeManagerNonDBo<Cfg::Parameter::Type >::create( (PyObject*)typeObject
, Cfg::PyParameterType_Methods
, NULL
, PyTypeManager::NoCppDelete
, "Type"
);
PyTypeManagerNonDBo<Cfg::Parameter::Flags >::create( (PyObject*)typeObject
, Cfg::PyParameterFlags_Methods
, NULL
, PyTypeManager::NoCppDelete
, "Flags"
);
}
template<>
inline void pyTypePostInit<Cfg::Parameter::Priority> ( PyTypeObject* typeObject )
{
// Parameter::Priority enum.
addConstant( typeObject, "UseDefault" , Cfg::Parameter::UseDefault );
addConstant( typeObject, "ApplicationBuiltin", Cfg::Parameter::ApplicationBuiltin );
addConstant( typeObject, "ConfigurationFile" , Cfg::Parameter::ConfigurationFile );
addConstant( typeObject, "UserFile" , Cfg::Parameter::UserFile );
addConstant( typeObject, "CommandLine" , Cfg::Parameter::CommandLine );
addConstant( typeObject, "Interactive" , Cfg::Parameter::Interactive );
}
template<>
inline void pyTypePostInit<Cfg::Parameter::Type> ( PyTypeObject* typeObject )
{
// Parameter::Type enum.
addConstant( typeObject, "Unknown" , Cfg::Parameter::Unknown );
addConstant( typeObject, "String" , Cfg::Parameter::String );
addConstant( typeObject, "Bool" , Cfg::Parameter::Bool );
addConstant( typeObject, "Int" , Cfg::Parameter::Int );
addConstant( typeObject, "Enumerate" , Cfg::Parameter::Enumerate );
addConstant( typeObject, "Double" , Cfg::Parameter::Double );
addConstant( typeObject, "Percentage", Cfg::Parameter::Percentage );
}
template<>
inline void pyTypePostInit<Cfg::Parameter::Flags> ( PyTypeObject* typeObject )
{
// Parameter::Flags enum.
addConstant( typeObject, "HasMin" , Cfg::Parameter::HasMin );
addConstant( typeObject, "HasMax" , Cfg::Parameter::HasMax );
addConstant( typeObject, "IsFile" , Cfg::Parameter::IsFile );
addConstant( typeObject, "IsPath" , Cfg::Parameter::IsPath );
addConstant( typeObject, "NeedRestart" , Cfg::Parameter::NeedRestart );
addConstant( typeObject, "MustExist" , Cfg::Parameter::MustExist );
addConstant( typeObject, "TypeCheck" , Cfg::Parameter::TypeCheck );
addConstant( typeObject, "FromString" , Cfg::Parameter::FromString );
addConstant( typeObject, "AllRequirements", Cfg::Parameter::AllRequirements );
addConstant( typeObject, "UseSpinBox" , Cfg::ParameterWidget::UseSpinBox );
addConstant( typeObject, "IsFileName" , Cfg::ParameterWidget::IsFileName );
addConstant( typeObject, "IsPathName" , Cfg::ParameterWidget::IsPathName );
}
} // Isobar3 namespace.
| 412 | 0.821536 | 1 | 0.821536 | game-dev | MEDIA | 0.284399 | game-dev | 0.824272 | 1 | 0.824272 |
11011010/BFA-Frankenstein-Core | 66,735 | src/server/scripts/Pandaria/HeartOfFear/boss_zorlok.cpp | /*
* Copyright (C) 2020 BfaCore
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "GameObjectAI.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "heart_of_fear.h"
#include "Creature.h"
#include "CreatureAI.h"
#include "Spell.h"
enum eZorlokSpells
{
SPELL_MANTID_WINGS = 126316,
SPELL_ATTENUATION = 122440,
SPELL_CONVERT = 122740,
SPELL_INHALE = 122852,
SPELL_EXHALE = 122761,
SPELL_EXHALE_DMG = 122760,
SPELL_PHEROMONES_OF_ZEAL = 123812, // Aura inflicting damages to players
SPELL_PHEROMONES_CLOUD = 123811, // Creating Cloud of pheromones
SPELL_FORCE_AND_VERVE = 122713,
SPELL_NOISE_CANCELLING = 122706,
SPELL_MISSILE_NOISE_CANC = 122707,
SPELL_SONG_OF_THE_EMPRESS = 123791,
SPELL_SONIC_RING_VISUAL = 122334,
SPELL_SONIC_RING_AURA = 122336,
SPELL_SONIC_PULSE_VISUAL = 124668,
SPELL_SONIC_PULSE_AURA = 124673,
SPELL_INHALE_PHEROMONES = 124018,
SPELL_REINFORCE = 123833,
SPELL_ZORLOK_BERSERK = 120207,
SPELL_MAGNETIC_PULSE = 147379, // Pull the players on the boss
SPELL_ECHO_OF_ZORLOK = 127496,
SPELL_VIZIER_ZORLOK_BONUS = 132194
};
enum eZorlokEvent
{
EVENT_INHALE = 1,
EVENT_EXHALE = 2,
EVENT_BERSERK = 3,
EVENT_ATTENUATION = 4,
EVENT_SUMMON_RINGS = 5,
EVENT_SUMMON_RINGS1 = 6,
EVENT_SUMMON_RINGS2 = 7,
EVENT_PHEROMONES_CLOUD = 8,
EVENT_FORCE_AND_VERVE = 9,
EVENT_CAST_FANDV = 10,
EVENT_CONVERT = 11,
EVENT_PULL_RAID = 12,
EVENT_SONIC_PULSE = 13,
EVENT_SUMMON_LAST_ECHO = 14,
EVENT_SONIC_MOVE = 15
};
enum eZorlokActions
{
ACTION_SONIC_RING = 2,
ACTION_INHALE_PHEROMONES = 3,
ACTION_WIPE = 4,
ACTION_SONIC_PULSE = 5
};
enum eZorlokTypes
{
TYPE_EXHALE_TARGET = 1,
TYPE_PHASE_ZORLOK = 2
};
enum eZorlokAdds
{
NPC_SONIC_RING = 62689,
NPC_SONIC_PULSE = 63837,
NPC_ECHO_OF_ATTENUATION = 65173,
NPC_ECHO_OF_FORCE_AND_VERVE = 65174
};
enum eZorlokPhase
{
PHASE_ZORLOK1 = 1,
PHASE_ZORLOK2 = 4 // value '4' needed, DON'T CHANGE IT !!!
};
enum ePlatforms
{
PLATFORM_ZORLOK_SW = 1, // Platform South-west (Force and verve)
PLATFORM_ZORLOK_NE = 2, // Platform North-east (Attenuation)
PLATFORM_ZORLOK_SE = 3 // Platform South-east (Convert)
};
enum eTalk
{
TALK_AGGRO = 1,
TALK_DEATH = 2,
TALK_EVENT_IDLE_1A = 3, // 1st phase of trash mobs
TALK_EVENT_IDLE_1B = 4,
TALK_EVENT_IDLE_1C = 5,
TALK_EVENT_IDLE_2 = 6, // 2nd phase of trash mobs
TALK_EVENT_IDLE_3 = 7, // 3rd phase of trash mobs
TALK_EVENT_IDLE_4 = 8, // 4th phase of trash mobs
TALK_EVENT_PHASE_1 = 9,
TALK_EVENT_PHASE_2 = 10,
TALK_EVENT_PHASE_3 = 11,
TALK_EVENT_TRASH_A_COMBAT = 12,
TALK_EVENT_TRASH_A_DIES = 13,
TALK_EVENT_TRASH_B_COMBAT = 14,
TALK_EVENT_TRASH_B_DIES = 15,
TALK_EVENT_TRASH_C_COMBAT = 16,
TALK_EVENT_TRASH_C_DIES = 17,
TALK_SLAY_01 = 18, // Killing a player
TALK_SLAY_02 = 19,
TALK_EXHALE = 20,
TALK_INHALE = 21,
TALK_CONVERT = 22,
TALK_PITCH = 23 // Echoes of power
};
Position zorlokPlatforms[3] =
{
{-2317.21f, 300.67f, 409.90f, 0.0f}, // SW Platform
{-2234.36f, 216.88f, 409.90f, 0.0f}, // NE Platform
{-2315.77f, 218.20f, 409.90f, 0.0f} // SE Platform
};
Position zorlokReachPoints[3] =
{
{-2317.21f, 300.67f, 420.0f, 0.0f}, // NE Platform
{-2234.36f, 216.88f, 420.0f, 0.0f}, // SW Platform
{-2315.77f, 218.20f, 420.0f, 0.0f} // SE Platform
};
Position oratiumCenter[2] =
{
{-2274.80f, 259.19f, 420.0f, 0.318021f},
{-2274.80f, 259.19f, 406.5f, 0.318021f}
};
// 212943 - Final Phase Door
Position finalPhaseWalls1[3] =
{
{-2299.195f, 282.5938f, 408.5445f, 2.383867f},
{-2250.401f, 234.0122f, 408.5445f, 2.333440f},
{-2299.63f, 233.3889f, 408.5445f, 0.7598741f}
};
// 212916 - Arena Walls
Position finalPhaseWalls2[3] =
{
{-2255.168f, 308.7326f, 406.0f, 0.7853968f},
{-2240.0f, 294.0f, 406.0f, 0.7853968f},
{-2225.753f, 280.1424f, 406.381f, 0.7853968f}
};
float tabCenter[3] = {-2274.8f, 259.187f, 406.5f};
float rangeAttenuation1[2][2] =
{
{-2256.0f, -2208.0f},
{190.0f, 240.0f}
};
float rangeAttenuation2[2][2] =
{
// Coords to redone
{-2297.0f, -2250.0f},
{237.0f, 280.0f}
};
// Zorlok - 62980
// Echo of Attenuation - 65173
// Echo of Force and Verve - 65174
class boss_zorlok : public CreatureScript
{
public:
boss_zorlok() : CreatureScript("boss_zorlok") { }
struct boss_zorlokAI : public BossAI
{
boss_zorlokAI(Creature* creature) : BossAI(creature, DATA_ZORLOK)
{
pInstance = creature->GetInstanceScript();
}
// Global
InstanceScript* pInstance;
EventMap events;
bool isActive;
bool isFlying;
std::list<uint8> platforms;
uint8 numPlat;
uint8 phase;
uint8 hasTalk;
uint32 platformToUse;
uint32 actualPlatform;
// Inhale - Exhale
uint32 exhaleTarget;
bool inhaleDone;
// Attenuation
uint8 sonicRingCount;
uint8 sonicPulseCount;
float ringOrientation;
float xr, yr, zr, orientation; // Starting coords for sonic ring wave
float pulseOrientation;
float xp, yp, zp, op; // Starting coords for sonic pulse wave (Heroic mode)
bool clocksideRings;
// Echo
bool isEcho;
bool isAttEcho;
bool isFaVEcho;
bool hasSummonedLastEcho;
void Reset() override
{
events.Reset();
summons.DespawnAll();
me->SetVirtualItem(0, EQUIP_ZORLOK);
// Make sure we can target zorlok
me->RemoveUnitFlag(UNIT_FLAG_IMMUNE_TO_PC);
// Set Echo
isAttEcho = me->GetEntry() == NPC_ECHO_OF_ATTENUATION;
isFaVEcho = me->GetEntry() == NPC_ECHO_OF_FORCE_AND_VERVE;
isEcho = (isAttEcho || isFaVEcho);
// Set fying
if (!isEcho)
{
DoCast(me, SPELL_MANTID_WINGS);
me->SetCanFly(true);
me->SetSpeed(MOVE_FLIGHT, 4.5f);
me->SetHover(true);
me->SetDisableGravity(true);
me->SetReactState(REACT_PASSIVE);
me->RemoveAllAreaTriggers();
}
else
me->AddAura(SPELL_ECHO_OF_ZORLOK, me);
// Zor'lok isn't immediately active, but echoes are.
isActive = isEcho;
if (pInstance && !isEcho)
{
EncounterState bossState = pInstance->GetBossState(DATA_ZORLOK);
if (bossState != DONE && bossState != NOT_STARTED)
pInstance->SetBossState(DATA_ZORLOK, NOT_STARTED);
}
numPlat = 0;
phase = isEcho ? GetZorlok()->AI()->GetData(TYPE_PHASE_ZORLOK) : 0;
platformToUse = 0;
hasTalk = 0;
actualPlatform = 0;
sonicRingCount = 0;
sonicPulseCount = 0;
xr = 0, yr = 0, zr = 0, orientation = 0;
xp = 0, yp = 0, zp = 0, op = 0;
clocksideRings = true;
inhaleDone = false;
exhaleTarget = 0;
pulseOrientation = 0.0f;
ringOrientation = 0.0f;
hasSummonedLastEcho = false;
// Echo in phase 2 should not move
if (isEcho && phase == 2)
me->AddUnitFlag(UNIT_FLAG_REMOVE_CLIENT_CONTROL);
platforms.clear();
if (!isEcho)
RemoveWalls();
// In heroic mode, the platforms are ordered, so we just need to increase numPlat and having it matching to ePlatforms values, which
// are heroic ordered, to get the right platform.
//
// In normal mode, platforms are picked in random order, so we need to put them in a list, to remove them when they're used (in order
// to avoid Zorlok to use them again).
if (!IsHeroic() && !isEcho)
{
platforms.push_back(PLATFORM_ZORLOK_SW);
platforms.push_back(PLATFORM_ZORLOK_NE);
platforms.push_back(PLATFORM_ZORLOK_SE);
}
}
// --- Specific Functions ---
void RemoveWalls()
{
std::list<GameObject*> arenaList;
std::list<GameObject*> wallsList;
GetGameObjectListWithEntryInGrid(arenaList, me, GOB_ARENA_WALLS, 200.0f);
GetGameObjectListWithEntryInGrid(wallsList, me, GOB_FINAL_PHASE_WALLS, 200.0f);
for (auto wall : arenaList)
me->RemoveGameObject(wall, true);
for (auto wall : wallsList)
me->RemoveGameObject(wall, true);
}
void SetFlying()
{
isFlying = true;
me->AttackStop();
me->DeleteThreatList();
me->getThreatManager().clearReferences();
me->SetCanFly(true);
me->SetReactState(REACT_PASSIVE);
me->HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF);
me->SetDisableGravity(true);
me->SetHover(true);
me->AddUnitMovementFlag(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_FLYING);
me->AddUnitFlag(UNIT_FLAG_IMMUNE_TO_PC);
if (isActive)
{
if (phase == PHASE_ZORLOK1 && hasTalk < numPlat)
{
me->GetMotionMaster()->MovePoint(platformToUse, zorlokReachPoints[platformToUse - 1]);
me->TextEmote("Imperial Vizier Zor'lok is flying to one of hist platforms!", 0, true);
hasTalk = numPlat;
}
else
me->GetMotionMaster()->MovePoint(phase, oratiumCenter[0]);
}
else
me->GetMotionMaster()->MoveTargetedHome();
}
void SetLanding(uint8 dest)
{
me->SetCanFly(false);
me->SetDisableGravity(false);
me->RemoveUnitMovementFlag(MOVEMENTFLAG_FLYING);
me->SetHover(false);
me->RemoveUnitFlag(UNIT_FLAG_IMMUNE_TO_PC);
events.ScheduleEvent(EVENT_INHALE, 15000);
if (platformToUse != actualPlatform)
actualPlatform = platformToUse;
if (dest)
{
switch (dest)
{
// Force & Verve platform
case PLATFORM_ZORLOK_SW:
{
events.ScheduleEvent(EVENT_FORCE_AND_VERVE, urand(10000, 20000));
break;
}
// Attenuation Platform
case PLATFORM_ZORLOK_NE:
{
events.ScheduleEvent(EVENT_ATTENUATION, urand(10000, 20000));
break;
}
// Convert Platform
case PLATFORM_ZORLOK_SE:
{
events.ScheduleEvent(EVENT_CONVERT, urand (10000, 20000));
break;
}
// Phase 2 - Center of the room
case PHASE_ZORLOK2:
{
Talk(TALK_EVENT_PHASE_2);
events.ScheduleEvent(ChooseAction(), urand(25000, 35000));
events.ScheduleEvent(EVENT_PULL_RAID, 2000);
break;
}
default:
break;
}
}
}
// Specific for echo
Creature* GetZorlok()
{
if (Creature* Zorlok = pInstance->GetCreature(NPC_ZORLOK))
return Zorlok;
return 0;
}
// Return an angle between 0.0f and 6.28f from a non corrected value
float CorrectAngle(float angle)
{
if (angle > 2 * float(M_PI))
angle -= 2 * float(M_PI);
else if (angle < 0.0f)
angle += 2 * float(M_PI);
// angle = (angle > (2 * M_PI)) ? (angle - (2 * M_PI)) : ((angle < 0.0f) ? (angle + (2 * M_PI)) : angle);
return angle;
}
void JustDied(Unit* /*who*/) override
{
events.Reset();
summons.DespawnAll();
me->RemoveAllAreaTriggers();
if (isEcho || !pInstance)
return;
if (pInstance->GetBossState(DATA_ZORLOK) == DONE)
return;
me->SetCanFly(false);
me->SetDisableGravity(true);
RemoveWalls();
Talk(TALK_DEATH);
pInstance->SetBossState(DATA_ZORLOK, DONE);
pInstance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me);
pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_CONVERT);
pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_FORCE_AND_VERVE);
pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_PHEROMONES_OF_ZEAL);
/*if (me->GetMap()->IsLFR())
{
me->ResetLootRecipients();
Player* l_Player = me->GetMap()->GetPlayers().begin()->GetSource();
if (l_Player && l_Player->GetGroup())
sLFGMgr->AutomaticLootAssignation(me, l_Player->GetGroup());
}*/
_JustDied();
Map::PlayerList const& l_PlrList = me->GetMap()->GetPlayers();
for (Map::PlayerList::const_iterator l_Itr = l_PlrList.begin(); l_Itr != l_PlrList.end(); ++l_Itr)
{
if (Player* l_Player = l_Itr->GetSource())
me->CastSpell(l_Player, SPELL_VIZIER_ZORLOK_BONUS, true);
}
}
void JustReachedHome() override
{
if (isEcho || !isActive)
return;
_JustReachedHome();
isActive = false;
events.Reset();
if (me->HasAura(SPELL_SONG_OF_THE_EMPRESS))
me->RemoveAura(SPELL_SONG_OF_THE_EMPRESS);
if (pInstance)
pInstance->SetBossState(DATA_ZORLOK, FAIL);
me->RemoveUnitFlag(UNIT_FLAG_IMMUNE_TO_PC);
me->RemoveUnitFlag(UNIT_FLAG_IN_COMBAT);
}
void EnterCombat(Unit* /*p_Attacker*/) override
{
if (pInstance)
{
pInstance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me);
if (pInstance->GetBossState(DATA_ZORLOK) != IN_PROGRESS)
pInstance->SetBossState(DATA_ZORLOK, IN_PROGRESS);
}
// Creating walls
for (uint8 i = 0; i < 3; ++i)
// Arena walls
me->SummonGameObject(GOB_ARENA_WALLS, finalPhaseWalls2[i].GetPositionX(), finalPhaseWalls2[i].GetPositionY(), finalPhaseWalls2[i].GetPositionZ(), finalPhaseWalls2[i].GetOrientation(), QuaternionData(), 7200);
// 10 minutes enrage timer
if (!isEcho)
events.ScheduleEvent(EVENT_BERSERK, 600000);
if (isAttEcho)
events.ScheduleEvent(EVENT_ATTENUATION, 15000);
if (isFaVEcho)
events.ScheduleEvent(EVENT_FORCE_AND_VERVE, 15000);
}
void MoveInLineOfSight(Unit* attacker) override
{
// Do nothing if not in attack phase (ie. flying), or if the unit beside isn't a player
if (!isEcho && (!me->HasReactState(REACT_DEFENSIVE) || attacker->GetTypeId() != TYPEID_PLAYER))
return;
// If is using Song of Empress, stop it
if (me->HasAura(SPELL_SONG_OF_THE_EMPRESS))
me->RemoveAura(SPELL_SONG_OF_THE_EMPRESS);
// Start attacking player
me->AddThreat(attacker, 0.0f);
}
void KilledUnit(Unit* victim) override
{
if (isEcho)
return;
if (victim->IsPlayer())
Talk(TALK_SLAY_01 + urand(0, 1));
}
uint32 ChoosePlatform()
{
// In Heroic mode, the platforms order is fixed
if (IsHeroic())
return platformToUse = ++numPlat;
// Using a while loop considering it's possible none of the platforms could be selected due to the rand condition : if so, we need to redo
// another loop(s) until a platform is picked.
while (true)
{
// count is used to set the same chance to be chosen for all platforms
uint32 count = 0;
for (auto platform : platforms)
{
// can only trigger if urand returns 0
if (!urand(0, uint32(platforms.size() - (1 + count))))
{
platforms.remove(platform);
++numPlat;
return platformToUse = platform;
}
++count;
}
}
}
void DamageTaken(Unit* attacker, uint32 &damage) override
{
// Check if trashes are done
if (pInstance && !isEcho)
{
EncounterState bossState = pInstance->GetBossState(DATA_ZORLOK);
if (bossState == NOT_STARTED || bossState == TO_BE_DECIDED)
{
Creature* ShieldMaster = GetClosestCreatureWithEntry(me, NPC_SRATHIK_SHIELD_MASTER, 200.0f, true);
Creature* Zealok = GetClosestCreatureWithEntry(me, NPC_ZARTHIK_ZEALOT, 200.0f, true);
Creature* Fanatic = GetClosestCreatureWithEntry(me, NPC_SETTHIK_FANATIC, 200.0f, true);
Creature* BoneSmasher = GetClosestCreatureWithEntry(me, NPC_ENSLAVED_BONESMASHER, 200.0f, true);
Creature* Supplicant = GetClosestCreatureWithEntry(me, NPC_ZARTHIK_SUPPLICANT, 200.0f, true);
Creature* Supplicant2 = GetClosestCreatureWithEntry(me, NPC_ZARTHIK_SUPPLICANT_2, 200.0f, true);
Creature* Supplicant3 = GetClosestCreatureWithEntry(me, NPC_ZARTHIK_SUPPLICANT_3, 200.0f, true);
if (ShieldMaster || Zealok || Fanatic || BoneSmasher || Supplicant || Supplicant2 || Supplicant3)
{
EnterEvadeMode(EVADE_REASON_OTHER);
pInstance->SetBossState(DATA_ZORLOK, NOT_STARTED);
return;
}
}
}
if (isEcho || (isFlying && isActive) || (attacker->GetTypeId() != TYPEID_PLAYER))
return;
if (!isActive)
{
isActive = true;
if (!isEcho)
{
Talk(TALK_AGGRO);
me->CastSpell(tabCenter[0], tabCenter[1], tabCenter[2], SPELL_PHEROMONES_CLOUD, false);
phase = PHASE_ZORLOK1;
if (pInstance)
pInstance->SetBossState(DATA_ZORLOK, IN_PROGRESS);
}
}
// Removing song of the empress
if (me->GetDistance(attacker) < 5.0f)
{
uint32 spell = me->GetCurrentSpell(CURRENT_CHANNELED_SPELL) ? me->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_spellInfo->Id : 0;
if (me->HasAura(SPELL_SONG_OF_THE_EMPRESS) || spell == SPELL_SONG_OF_THE_EMPRESS)
{
me->RemoveAurasDueToSpell(SPELL_SONG_OF_THE_EMPRESS);
me->InterruptNonMeleeSpells(true, SPELL_SONG_OF_THE_EMPRESS);
me->CastStop(SPELL_SONG_OF_THE_EMPRESS);
AttackStart(attacker);
me->SetInCombatWith(attacker);
}
}
if (isEcho || phase == PHASE_ZORLOK2)
return;
// Phase 1
if (me->HealthBelowPctDamaged(100 - 20 * numPlat, damage) && phase == PHASE_ZORLOK1)
{
events.Reset();
// Switching platforms at 100%, 80% and 60% remaining life
if (numPlat < 3)
{
if (IsHeroic())
{
// Leaving Force and Verve Echo
if (numPlat == 1)
me->SummonCreature(NPC_ECHO_OF_FORCE_AND_VERVE, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation());
if (numPlat == 2)
me->SummonCreature(NPC_ECHO_OF_ATTENUATION, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation());
}
uint32 platformToUse = ChoosePlatform();
me->GetMotionMaster()->MoveTakeoff(platformToUse, zorlokReachPoints[platformToUse - 1]);
me->TextEmote("Imperial Vizier Zor'lok is flying to one of his platforms!", 0, true);
}
// At 40% remaining phase, switch on phase 2
else
{
phase = PHASE_ZORLOK2;
me->GetMotionMaster()->MoveTakeoff(phase, oratiumCenter[0]);
}
// Set Flying
SetFlying();
}
}
void DoAction (int32 const action) override
{
switch (action)
{
case ACTION_SONIC_RING:
{
if (!sonicRingCount)
{
clocksideRings = (urand(0, 1) ? true : false);
xr = me->GetPositionX();
yr = me->GetPositionY();
zr = me->GetPositionZ();
orientation = me->GetOrientation();
}
float variation = float(M_PI)/2;
float frontAngle = CorrectAngle(orientation + ringOrientation);
float leftAngle = CorrectAngle(frontAngle + variation);
float rightAngle = CorrectAngle(frontAngle - variation);
float backAngle = CorrectAngle(frontAngle + 2 * variation);
me->SummonCreature(NPC_SONIC_RING, xr, yr, zr, frontAngle);
me->SummonCreature(NPC_SONIC_RING, xr, yr, zr, leftAngle);
me->SummonCreature(NPC_SONIC_RING, xr, yr, zr, rightAngle);
me->SummonCreature(NPC_SONIC_RING, xr, yr, zr, backAngle);
if (sonicRingCount >= 10)
{
sonicRingCount = 0;
ringOrientation = 0.0f;
// Resetting coords
xr = 0.0f;
yr = 0.0f;
zr = 0.0f;
orientation = 0.0f;
// Reset Zor'lok in combat
me->SetReactState(REACT_DEFENSIVE);
me->RemoveUnitFlag(UnitFlags(UNIT_FLAG_PACIFIED|UNIT_FLAG_REMOVE_CLIENT_CONTROL|UNIT_FLAG_IMMUNE_TO_PC|UNIT_FLAG_STUNNED));
me->RemoveUnitFlag2(UNIT_FLAG2_DISABLE_TURN);
me->AddUnitFlag2(UNIT_FLAG2_ALLOW_ENEMY_INTERACT);
}
else
{
++sonicRingCount;
ringOrientation = CorrectAngle(ringOrientation + (clocksideRings ? -M_PI / 6 : M_PI / 6));
events.ScheduleEvent(EVENT_SUMMON_RINGS, 1000);
}
break;
}
case ACTION_SONIC_PULSE:
{
// To have a proper spawn, we save the position on first pulse, and progressively increase/decrease (according to clocksideRings)
// the angle the pulse will have and so, the path they'll follow
if (!sonicPulseCount)
{
xp = me->GetPositionX();
yp = me->GetPositionY();
zp = me->GetPositionZ();
op = me->GetOrientation();
}
float variation = 2.f * float(M_PI) / 3.f;
// Summons in Y (3 branches)
float mainAngle = CorrectAngle(op + pulseOrientation);
float angLeft = CorrectAngle(mainAngle + variation);
float angRight = CorrectAngle(mainAngle - variation);
me->SummonCreature(NPC_SONIC_PULSE, xp, yp, zp, mainAngle);
me->SummonCreature(NPC_SONIC_PULSE, xp, yp, zp, angLeft);
me->SummonCreature(NPC_SONIC_PULSE, xp, yp, zp, angRight);
if (sonicPulseCount >= 8)
{
sonicPulseCount = 0;
pulseOrientation = 0.0f;
// Resetting coords;
xp = 0.0f;
yp = 0.0f;
zp = 0.0f;
op = 0.0f;
}
else
{
++sonicPulseCount;
pulseOrientation = CorrectAngle(pulseOrientation + (clocksideRings ? -M_PI / 6 : M_PI / 6));
events.ScheduleEvent(EVENT_SONIC_PULSE, 1500);
}
break;
}
case ACTION_WIPE:
{
events.Reset();
summons.DespawnAll();
me->RemoveAllAreaTriggers();
me->RemoveAllAuras();
me->SetFullHealth();
me->SetReactState(REACT_PASSIVE);
isActive = false;
platforms.clear();
if (!IsHeroic())
{
platforms.push_back(PLATFORM_ZORLOK_SW);
platforms.push_back(PLATFORM_ZORLOK_NE);
platforms.push_back(PLATFORM_ZORLOK_SE);
}
numPlat = 0;
phase = 0;
hasTalk = 0;
platformToUse = 0;
actualPlatform = 0;
exhaleTarget = 0;
sonicRingCount = 0;
sonicPulseCount = 0;
ringOrientation = 0.0f;
pulseOrientation = 0.0f;
xr = 0.0f, yr = 0.0f, zr = 0.0f, orientation = 0.0f;
xp = 0.0f, yp = 0.0f, zp = 0.0f, op = 0.0f;
clocksideRings = true;
inhaleDone = false;
hasSummonedLastEcho = false;
RemoveWalls();
if (pInstance)
{
pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_PHEROMONES_CLOUD);
pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_CONVERT);
pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_NOISE_CANCELLING);
pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_FORCE_AND_VERVE);
pInstance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me);
}
SetFlying();
break;
}
default:
break;
}
}
uint32 ChooseAction()
{
uint32 choice = urand(1, 3);
switch (choice)
{
case 1:
return EVENT_ATTENUATION;
case 2:
return EVENT_CONVERT;
case 3:
return EVENT_FORCE_AND_VERVE;
default:
break;
}
return 0;
}
void MovementInform(uint32 type, uint32 id) override
{
if (isEcho || id == 0 || type != POINT_MOTION_TYPE)
return;
// General rule :
// * if id < 4, Zor'lok is going on a platform
// * if id = 4, Zor'lok is going on the center of the room to absorb pheromones
// Phase 1 : going onto landing points on platforms
if (id < 4)
{
if (numPlat == 1)
Talk(TALK_EVENT_PHASE_1);
me->GetMotionMaster()->MoveLand(id + 10, zorlokPlatforms[id - 1]);
SetLanding(id);
}
// Switching from phase 1 to phase 2
if (id == 4)
{
me->CastSpell(me, SPELL_INHALE_PHEROMONES, true);
me->TextEmote("Imperial Vizier Zor'lok inhales Pheromones of Zeal!", 0, true);
pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_PHEROMONES_CLOUD);
events.ScheduleEvent(EVENT_PULL_RAID, 7000);
}
}
uint32 GetData(uint32 type) const override
{
if (type == TYPE_EXHALE_TARGET)
return exhaleTarget;
if (type == TYPE_PHASE_ZORLOK)
return phase;
return 0;
}
void SetData(uint32 type, uint32 value) override
{
if (type == TYPE_EXHALE_TARGET)
exhaleTarget = value;
}
void UpdateAI(const uint32 diff) override
{
if (!isActive)
return;
// On Wipe
if (pInstance && !isEcho)
{
if (pInstance->IsWipe())
{
DoAction(ACTION_WIPE);
// We stop here to avoid Zor'lok to cast Song of the empress
return;
}
}
// Remove/Set auras on players
if (!isEcho)
{
Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers();
if (!PlayerList.isEmpty())
{
for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
{
if (Player* playr = i->GetSource())
{
// Remove convert aura for players who have less than 50% remaining health
if (playr->HasAura(SPELL_CONVERT) && playr->HealthBelowPct(51))
playr->RemoveAurasDueToSpell(SPELL_CONVERT);
// Pheromones of zeal - on phase 1 only
if (phase == PHASE_ZORLOK1)
{
// Remove pheromones of zeal aura from players who aren't on the bottom floor
if (playr->HasAura(SPELL_PHEROMONES_OF_ZEAL) && playr->GetPositionZ() >= 408.5f)
playr->RemoveAura(SPELL_PHEROMONES_OF_ZEAL);
// Set pheromones of zeal aura on players who are on the bottom floor
else if (!playr->HasAura(SPELL_PHEROMONES_OF_ZEAL) && playr->GetPositionZ() < 408.5f)
playr->AddAura(SPELL_PHEROMONES_OF_ZEAL, playr);
}
}
}
}
}
UpdateVictim();
events.Update(diff);
if (isFlying && platformToUse == actualPlatform && !isEcho && actualPlatform > 0 &&
((me->GetPositionZ() < 410.5f && phase == PHASE_ZORLOK1) ||
(me->GetPositionZ() < 407.0f && phase == PHASE_ZORLOK2)))
{
isFlying = false;
me->HandleEmoteCommand(EMOTE_ONESHOT_LAND);
me->SetReactState(REACT_DEFENSIVE);
}
// Song of empress
Unit* target = me->GetVictim();
if (!isFlying && (!target || me->GetDistance(target) > 5.0f) && !me->HasUnitState(UNIT_STATE_CASTING))
me->CastSpell(me, SPELL_SONG_OF_THE_EMPRESS, true);
switch (events.ExecuteEvent())
{
// All-time events
case EVENT_INHALE:
{
// Can't inhale if already casting
if (me->HasUnitState(UNIT_STATE_CASTING))
events.RescheduleEvent(EVENT_INHALE, 5000);
else
{
// Inhale (Exhale is triggered when Zor'lok has 3-4 stacks of inhale)
Aura* inhale = me->GetAura(SPELL_INHALE);
if (!inhale || inhale->GetStackAmount() < 3 || !urand((inhale->GetStackAmount() < 4 ? 0 : 1), 1))
{
Talk(TALK_INHALE);
me->TextEmote("Imperial Vizier Zor'lok |cFFFF0000|Hspell:122852|h[Inhale]|h|r a big air breath!", 0, true);
me->CastSpell(me, SPELL_INHALE, false);
}
// Exhale
else
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 60.0f, true))
{
exhaleTarget = target->GetGUID().GetCounter();
Talk(TALK_EXHALE);
DoCast(target, SPELL_EXHALE, true);
}
}
events.ScheduleEvent(EVENT_INHALE, urand(25000, 50000));
}
break;
}
// Attenuation platform
case EVENT_ATTENUATION:
{
if (!isEcho && me->HasUnitState(UNIT_STATE_CASTING))
{
events.RescheduleEvent(EVENT_ATTENUATION, 10000);
return;
}
me->CastSpell(me, SPELL_ATTENUATION, true);
me->SetReactState(REACT_PASSIVE);
me->AddUnitFlag(UnitFlags(UNIT_FLAG_PACIFIED|UNIT_FLAG_REMOVE_CLIENT_CONTROL|UNIT_FLAG_IMMUNE_TO_PC|UNIT_FLAG_STUNNED));
me->AddUnitFlag2(UNIT_FLAG2_DISABLE_TURN);
me->RemoveUnitFlag2(UNIT_FLAG2_ALLOW_ENEMY_INTERACT);
uint32 action = ((phase == PHASE_ZORLOK1 || isEcho) ? EVENT_ATTENUATION : ChooseAction());
events.ScheduleEvent(action, 40000);
break;
}
case EVENT_SUMMON_RINGS:
{
DoAction(ACTION_SONIC_RING);
break;
}
case EVENT_SONIC_PULSE:
{
DoAction(ACTION_SONIC_PULSE);
break;
}
// Convert platform
case EVENT_CONVERT:
{
if (me->HasUnitState(UNIT_STATE_CASTING))
{
events.RescheduleEvent(EVENT_CONVERT, 10000);
return;
}
me->TextEmote("Imperial Vizier Zor'lok is using is voice to |cFFFF0000|Hspell:122740|h[Convert]|h|r members of the raid and to call them by his side !", 0, true);
// Creating target list
Talk(TALK_CONVERT);
DoCast(SPELL_CONVERT);
uint32 action = ((phase == PHASE_ZORLOK1 || isEcho) ? EVENT_CONVERT : ChooseAction());
events.ScheduleEvent(action, 40000);
break;
}
// Force and Verve platform
case EVENT_FORCE_AND_VERVE:
{
if (me->HasUnitState(UNIT_STATE_CASTING))
{
events.RescheduleEvent(EVENT_FORCE_AND_VERVE, 10000);
return;
}
// Creating Zor'lok's Noise Cancelling zones : 3 in normal mode, 4 in heroic
if (!isEcho)
{
for (int i = 0; i < (IsHeroic() ? 4 : 3); ++i)
{
float x = me->GetPositionX() + frand(-20.0f, 20.0f);
float y = me->GetPositionY() + frand(-20.0f, 20.0f);
me->CastSpell(x, y, me->GetPositionZ(), SPELL_MISSILE_NOISE_CANC, false);
}
}
// Creating Echo of Attenuation's Noise Cancelling zones : 2 on Echo (me), 2 on Zor'lok
else
{
Creature* caster;
for (int i = 0; i < 2; ++i)
{
caster = (i == 0 ? me : GetZorlok());
for (int j = 0; j < 2; ++j)
{
float x = caster->GetPositionX() + frand(-20.0f, 20.0f);
float y = caster->GetPositionY() + frand(-20.0f, 20.0f);
caster->CastSpell(x, y, caster->GetPositionZ(), SPELL_MISSILE_NOISE_CANC, false);
}
}
}
me->AddUnitState(UNIT_STATE_CASTING);
events.ScheduleEvent(EVENT_CAST_FANDV, 2000);
break;
}
case EVENT_CAST_FANDV:
{
me->SetReactState(REACT_PASSIVE);
std::ostringstream text;
text << (me->GetName()) << " shouts with |cFFFF0000|Hspell:122713|h[Force et brio]|h|r!";
me->TextEmote(text.str().c_str(), 0, true);
me->CastSpell(me, SPELL_FORCE_AND_VERVE, true);
uint32 action = ((phase == PHASE_ZORLOK1 || isEcho) ? EVENT_FORCE_AND_VERVE : ChooseAction());
// On first Force and Verve during phase 2 in Heroic mode, Zor'lok summons the last echo at the end of spell (10 secs)
if (!hasSummonedLastEcho && phase == PHASE_ZORLOK2)
{
hasSummonedLastEcho = true;
events.ScheduleEvent(EVENT_SUMMON_LAST_ECHO, 10000);
}
events.ScheduleEvent(action, 40000);
break;
}
case EVENT_SUMMON_LAST_ECHO:
{
me->SummonCreature(NPC_ECHO_OF_ATTENUATION, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation());
break;
}
case EVENT_BERSERK:
{
me->CastSpell(me, SPELL_ZORLOK_BERSERK, false);
break;
}
case EVENT_PULL_RAID:
{
if (inhaleDone)
break;
// Removing pheromones cloud
me->RemoveAreaTrigger(SPELL_PHEROMONES_CLOUD);
pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_PHEROMONES_OF_ZEAL);
// Landing
me->GetMotionMaster()->MoveLand(PHASE_ZORLOK2 + 10, oratiumCenter[1]);
SetLanding(PHASE_ZORLOK2);
// Pulling far players
std::list<Player*> playerList;
GetPlayerListInGrid(playerList, me, 300.0f);
for (std::list<Player*>::iterator itr = playerList.begin(); itr != playerList.end(); ++itr)
{
// The point is that if they're on a platform, they'll be blocked by walls, so they have to be pulled
if ((*itr)->GetPositionZ() > 408.5f)
(*itr)->CastSpell(me, SPELL_MAGNETIC_PULSE, false);
}
// Creating Walls for final phase
for (uint8 i = 0; i < 3; ++i)
me->SummonGameObject(GOB_FINAL_PHASE_WALLS, finalPhaseWalls1[i].GetPositionX(), finalPhaseWalls1[i].GetPositionY(), finalPhaseWalls1[i].GetPositionZ(), finalPhaseWalls1[i].GetOrientation(), QuaternionData(), 7200);
inhaleDone = true;
break;
}
default:
break;
}
if (!me->HasUnitState(UNIT_STATE_CASTING))
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_zorlokAI(creature);
}
};
// Sonic Ring - 62689
class mob_sonic_ring : public CreatureScript
{
public:
mob_sonic_ring() : CreatureScript("mob_sonic_ring") { }
struct mob_sonic_ringAI : public ScriptedAI
{
mob_sonic_ringAI(Creature* creature) : ScriptedAI(creature)
{
pInstance = creature->GetInstanceScript();
}
InstanceScript* pInstance;
EventMap m_Events;
Position m_TargetPos;
void Reset() override
{
me->AddAura(SPELL_SONIC_RING_VISUAL, me);
me->SetReactState(REACT_PASSIVE);
me->AddUnitFlag(UnitFlags(UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE));
// Low speed
me->SetSpeed(MOVE_WALK, 0.5f);
me->SetSpeed(MOVE_RUN, 0.5f);
float l_PosX = me->GetPositionX() + 50.0f * cos(me->GetOrientation());
float l_PosY = me->GetPositionY() + 50.0f * sin(me->GetOrientation());
m_TargetPos = { l_PosX, l_PosY, me->GetPositionZ(), me->GetOrientation() };
m_Events.ScheduleEvent(EVENT_SONIC_MOVE, 500);
// In case the mob is unable to reach the target point
me->DespawnOrUnsummon(10000);
}
void MovementInform(uint32 type, uint32 id) override
{
if (type != POINT_MOTION_TYPE)
return;
if (id == 1)
me->DespawnOrUnsummon();
}
void UpdateAI(uint32 const p_Diff) override
{
m_Events.Update(p_Diff);
if (m_Events.ExecuteEvent() == EVENT_SONIC_MOVE)
me->GetMotionMaster()->MovePoint(1, m_TargetPos);
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new mob_sonic_ringAI(creature);
}
};
// Sonic Pulse (Heroic Mode) - 63837
class mob_sonic_pulse : public CreatureScript
{
public:
mob_sonic_pulse() : CreatureScript("mob_sonic_pulse") { }
struct mob_sonic_pulseAI : public ScriptedAI
{
mob_sonic_pulseAI(Creature* creature) : ScriptedAI(creature)
{
pInstance = creature->GetInstanceScript();
}
EventMap m_Events;
InstanceScript* pInstance;
Position m_TargetPos;
void Reset() override
{
me->AddAura(SPELL_SONIC_PULSE_VISUAL, me);
me->SetReactState(REACT_PASSIVE);
me->AddUnitFlag(UnitFlags(UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE));
// Low speed
me->SetSpeed(MOVE_WALK, 0.3f);
me->SetSpeed(MOVE_RUN, 0.3f);
float l_PosX = me->GetPositionX() + 50.0f * cos(me->GetOrientation());
float l_PosY = me->GetPositionY() + 50.0f * sin(me->GetOrientation());
m_TargetPos = { l_PosX, l_PosY, me->GetPositionZ(), me->GetOrientation() };
m_Events.ScheduleEvent(EVENT_SONIC_MOVE, 500);
// In case the mob is unable to reach the target point
me->DespawnOrUnsummon(10000);
}
void MovementInform(uint32 point, uint32 type) override
{
if (type != POINT_MOTION_TYPE)
return;
if (point)
me->DespawnOrUnsummon();
}
void UpdateAI(uint32 const p_Diff) override
{
m_Events.Update(p_Diff);
if (m_Events.ExecuteEvent() == EVENT_SONIC_MOVE)
me->GetMotionMaster()->MovePoint(1, m_TargetPos);
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new mob_sonic_pulseAI(creature);
}
};
// Inhale - 122852
class spell_inhale_zorlok : public SpellScriptLoader
{
public:
spell_inhale_zorlok() : SpellScriptLoader("spell_inhale_zorlok") { }
class spell_inhale_SpellScript : public SpellScript
{
PrepareSpellScript(spell_inhale_SpellScript);
void HandleScriptEffect(SpellEffIndex effIndex)
{
if (Unit* caster = GetCaster())
caster->CastSpell(caster, GetSpellInfo()->GetEffect(effIndex)->BasePoints, false);
}
void Register() override
{
OnEffectLaunch += SpellEffectFn(spell_inhale_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_APPLY_AURA);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_inhale_SpellScript();
}
};
// Attenuation - 122440
class spell_attenuation : public SpellScriptLoader
{
public:
spell_attenuation() : SpellScriptLoader("spell_attenuation") { }
class spell_attenuation_SpellScript : public SpellScript
{
PrepareSpellScript(spell_attenuation_SpellScript);
void Apply()
{
if (Creature* zorlok = GetCaster()->ToCreature())
{
// Summoning Sonic Rings
zorlok->AI()->DoAction(ACTION_SONIC_RING);
// Summoning additional Sonic Pulses in Heroic mode
if (zorlok->GetInstanceScript()->instance->IsHeroic())
zorlok->AI()->DoAction(ACTION_SONIC_PULSE);
}
}
void Register() override
{
AfterCast += SpellCastFn(spell_attenuation_SpellScript::Apply);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_attenuation_SpellScript();
}
};
// Force and Verve (Aura) - 122718
class spell_force_verve : public SpellScriptLoader
{
public:
spell_force_verve() : SpellScriptLoader("spell_force_verve") { }
class spell_force_verve_SpellScript : public SpellScript
{
PrepareSpellScript(spell_force_verve_SpellScript);
void ApplyEffect()
{
if (Player* target = GetHitPlayer())
{
if (target->HasAura(SPELL_NOISE_CANCELLING))
SetHitDamage(GetHitDamage() * 0.25);
}
}
void SetReact()
{
if (Creature* caster = GetCaster()->ToCreature())
caster->SetReactState(REACT_DEFENSIVE);
}
void Register() override
{
OnHit += SpellHitFn(spell_force_verve_SpellScript::ApplyEffect);
AfterCast += SpellCastFn(spell_force_verve_SpellScript::SetReact);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_force_verve_SpellScript();
}
};
// Sonic Ring (Aura) - 122336
class spell_sonic_ring : public SpellScriptLoader
{
public:
spell_sonic_ring() : SpellScriptLoader("spell_sonic_ring") { }
class spell_sonic_ring_SpellScript : public SpellScript
{
PrepareSpellScript(spell_sonic_ring_SpellScript);
void Effect()
{
if (Player* target = GetHitPlayer())
{
if (target->HasAura(SPELL_NOISE_CANCELLING))
SetHitDamage(GetHitDamage() * 0.4);
}
}
void Register() override
{
OnHit += SpellHitFn(spell_sonic_ring_SpellScript::Effect);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_sonic_ring_SpellScript();
}
};
// Sonic Pulse (Aura) - 124673
class spell_sonic_pulse : public SpellScriptLoader
{
public:
spell_sonic_pulse() : SpellScriptLoader("spell_sonic_pulse") { }
class spell_sonic_pulse_AuraScript : public AuraScript
{
PrepareAuraScript(spell_sonic_pulse_AuraScript);
void ApplyAura(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
if (Unit* caster = GetCaster())
caster->AddAura(SPELL_SONIC_RING_AURA, caster);
}
void Register() override
{
OnEffectApply += AuraEffectApplyFn(spell_sonic_pulse_AuraScript::ApplyAura, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);
OnEffectApply += AuraEffectApplyFn(spell_sonic_pulse_AuraScript::ApplyAura, EFFECT_1, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);
}
};
class spell_sonic_pulse_SpellScript : public SpellScript
{
PrepareSpellScript(spell_sonic_pulse_SpellScript);
void Effect()
{
if (Unit* caster = GetCaster())
caster->AddAura(SPELL_SONIC_RING_AURA, caster);
if (Player* target = GetHitPlayer())
{
if (target->HasAura(SPELL_NOISE_CANCELLING))
SetHitDamage(GetHitDamage() * 0.4);
}
}
void Register() override
{
OnHit += SpellHitFn(spell_sonic_pulse_SpellScript::Effect);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_sonic_pulse_SpellScript();
}
AuraScript* GetAuraScript() const override
{
return new spell_sonic_pulse_AuraScript();
}
};
class ExhaleTargetFilter
{
public:
explicit ExhaleTargetFilter(Unit* caster) : _caster(caster) { }
bool operator()(WorldObject* object) const
{
uint32 exhaleLowId = CAST_AI(boss_zorlok::boss_zorlokAI, _caster->GetAI())->GetData(TYPE_EXHALE_TARGET);
Player* exhaleTarget = ObjectAccessor::FindPlayer(ObjectGuid::Create<HighGuid::Player>(exhaleLowId));
if (!exhaleTarget)
return false;
// Remove all the other players (stun only Exhale target).
return (object == exhaleTarget) ? false : true;
}
private:
Unit* _caster;
};
// Exhale: 122761
class spell_zorlok_exhale : public SpellScriptLoader
{
public:
spell_zorlok_exhale() : SpellScriptLoader("spell_zorlok_exhale") { }
class spell_zorlok_exhale_SpellScript : public SpellScript
{
PrepareSpellScript(spell_zorlok_exhale_SpellScript);
void FilterTargets(std::list<WorldObject*>& targets)
{
targets.clear();
Unit* caster = GetCaster();
if (!caster)
return;
//Player* target = ObjectAccessor::FindPlayer(MAKE_NEW_GUID(TYPEID_PLAYER, 0, caster->GetAI()->GetData(TYPE_EXHALE_TARGET)));
Player* target = ObjectAccessor::FindPlayer(ObjectGuid::Create<HighGuid::Player>(caster->GetAI()->GetData(TYPE_EXHALE_TARGET)));
// No target? Then we pick a random one
if (!target || !target->IsAlive())
{
std::list<Player*> playerList;
GetPlayerListInGrid(playerList, caster, 60.0f);
if (playerList.empty())
return;
bool searching = true;
std::list<Player*>::iterator itr = playerList.begin();
while (searching)
{
if (urand(0, 1))
{
target = *itr;
searching = false;
}
++itr;
if (itr == playerList.end())
itr = playerList.begin();
}
}
if (target)
targets.push_back(target);
}
void RemoveStack()
{
if (Unit* caster = GetCaster())
caster->RemoveAurasDueToSpell(SPELL_INHALE);
}
void HandleScriptEffect(SpellEffIndex /*effIndex*/)
{
if (Unit* caster = GetCaster())
{
if (Player* target = GetHitPlayer())
caster->CastSpell(target, SPELL_EXHALE_DMG, true);
}
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_zorlok_exhale_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_zorlok_exhale_SpellScript::FilterTargets, EFFECT_2, TARGET_UNIT_SRC_AREA_ENEMY);
AfterCast += SpellCastFn(spell_zorlok_exhale_SpellScript::RemoveStack);
OnEffectHitTarget += SpellEffectFn(spell_zorlok_exhale_SpellScript::HandleScriptEffect, EFFECT_1, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_zorlok_exhale_SpellScript();
}
};
// Exhale (damage): 122760
class spell_zorlok_exhale_damage : public SpellScriptLoader
{
public:
spell_zorlok_exhale_damage() : SpellScriptLoader("spell_zorlok_exhale_damage") { }
class spell_zorlok_exhale_damage_SpellScript : public SpellScript
{
PrepareSpellScript(spell_zorlok_exhale_damage_SpellScript);
void FilterTargets(std::list<WorldObject*>& targets)
{
Unit* caster = GetCaster();
if (!caster || !caster->GetAI())
return;
//Unit* currentTarget = ObjectAccessor::FindPlayer(MAKE_NEW_GUID(TYPEID_PLAYER, 0, caster->GetAI()->GetData(TYPE_EXHALE_TARGET)));
Unit* currentTarget = ObjectAccessor::FindPlayer(ObjectGuid::Create<HighGuid::Player>(caster->GetAI()->GetData(TYPE_EXHALE_TARGET)));
if (targets.empty() || !currentTarget)
return;
targets.remove_if([caster, currentTarget](WorldObject* p_Object) -> bool
{
if (p_Object == currentTarget)
return false;
if (p_Object->GetTypeId() != TYPEID_PLAYER || !p_Object->IsInBetween(caster, currentTarget, 3.0f))
return true;
return false;
});
// Two or more targets, means there's someone between Zor'lok and his target.
if (targets.size() > 1)
{
// Select first target between Zor'lok and the Exhale target.
WorldObject* nearestTarget = nullptr;
float distance = 1000.0f;
for (WorldObject* l_Object : targets)
{
if (caster->GetDistance2d(l_Object) < distance)
{
nearestTarget = l_Object;
distance = caster->GetDistance2d(l_Object);
}
}
if (nearestTarget != nullptr && nearestTarget != currentTarget)
{
// Set Zor'lok's current Exhale target to that nearest player.
uint32 targetLowGuid = nearestTarget->GetGUID().GetCounter();
caster->GetAI()->SetData(TYPE_EXHALE_TARGET, targetLowGuid);
}
}
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_zorlok_exhale_damage_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_CONE_ENTRY_129);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_zorlok_exhale_damage_SpellScript();
}
};
// 122740 - Convert
class spell_convert : public SpellScriptLoader
{
public :
spell_convert() : SpellScriptLoader("spell_convert") { }
class spell_convertSpellScript : public SpellScript
{
PrepareSpellScript(spell_convertSpellScript);
void SelectTargets(std::list<WorldObject*>& targets)
{
targets.clear();
if (Unit* caster = GetCaster())
{
std::list<Player*> playerList;
GetPlayerListInGrid(playerList, caster, 60.0f);
// Removing dead or already converted players
std::list<Player*>::iterator itr, next;
for (itr = playerList.begin(); itr != playerList.end(); itr = next)
{
next = itr;
++next;
if (!(*itr)->IsAlive() || (*itr)->HasAura(SPELL_CONVERT))
playerList.remove(*itr);
}
uint8 maxVictims = caster->GetInstanceScript()->instance->Is25ManRaid() ? 5 : 2;
// If it remains less players than the number of victims of the spell, the whole raid will be targeted
if (playerList.size() <= maxVictims)
for (auto player : playerList)
targets.push_back(player);
// Else, we randomly choose victims until we have enough targets
else
{
std::list<Player*>::iterator itr, next;
itr = playerList.begin();
while (targets.size() < maxVictims)
{
next = itr;
if (urand(0, 1))
{
targets.push_back(*itr);
playerList.remove(*itr);
}
itr = ++next;
if (itr == playerList.end())
itr = playerList.begin();
}
}
}
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_convertSpellScript::SelectTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_convertSpellScript();
}
};
/// Created by spell 122731
class at_cancelling_noise : public AreaTriggerAI
{
public:
at_cancelling_noise(AreaTrigger* areaTrigger) : AreaTriggerAI(areaTrigger) { }
void OnUpdate(uint32 /*p_Time*/) override
{
std::list<Unit*> l_TargetList;
float l_Radius = 10.0f;
Unit* l_Caster = at->GetCaster();
if (!l_Caster)
return;
l_Caster->GetAttackableUnitListInRange(l_TargetList, l_Radius);
if (!l_TargetList.empty())
{
for (Unit* l_Target : l_TargetList)
{
// Periodic absorption for Imperial Vizier Zor'lok's Force and Verve and Sonic Rings
if (l_Target->GetDistance(at) > 2.0f && l_Target->HasAura(SPELL_NOISE_CANCELLING))
l_Target->RemoveAura(SPELL_NOISE_CANCELLING);
else if (l_Target->GetDistance(at) <= 2.0f && !l_Target->HasAura(SPELL_NOISE_CANCELLING))
l_Caster->AddAura(SPELL_NOISE_CANCELLING, l_Target);
}
}
}
};
void AddSC_boss_zorlok()
{
new boss_zorlok(); ///< 62980 - Imperial Vizier Zor'lok
new mob_sonic_ring(); ///< 62689 - Sonic Ring
new mob_sonic_pulse(); ///< 63837 - Sonic Pulse
new spell_inhale_zorlok(); ///< 122852 - Inhale
new spell_attenuation(); ///< 122440 - Attenuation
new spell_force_verve(); ///< 122718 - Force and verve
new spell_sonic_ring(); ///< 122336 - Sonic Ring
new spell_sonic_pulse(); ///< 124673 - Sonic Pulse
new spell_zorlok_exhale(); ///< 122761 - Exhale
new spell_zorlok_exhale_damage(); ///< 122760 - Exhale (damage aura)
new spell_convert(); ///< 122740 - Convert
RegisterAreaTriggerAI(at_cancelling_noise); ///< 122731 - Cancelling Noise AreaTrigger
}
| 412 | 0.96628 | 1 | 0.96628 | game-dev | MEDIA | 0.996365 | game-dev | 0.883243 | 1 | 0.883243 |
Space-Stories/space-station-14 | 9,894 | Content.Shared/UserInterface/ActivatableUISystem.cs | using Content.Shared.ActionBlocker;
using Content.Shared.Administration.Managers;
using Content.Shared.Ghost;
using Content.Shared.Hands;
using Content.Shared.Hands.Components;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Interaction;
using Content.Shared.Interaction.Events;
using Content.Shared.Popups;
using Content.Shared.Verbs;
using Content.Shared.Whitelist;
using Robust.Shared.Utility;
namespace Content.Shared.UserInterface;
public sealed partial class ActivatableUISystem : EntitySystem
{
[Dependency] private readonly ISharedAdminManager _adminManager = default!;
[Dependency] private readonly ActionBlockerSystem _blockerSystem = default!;
[Dependency] private readonly SharedUserInterfaceSystem _uiSystem = default!;
[Dependency] private readonly SharedPopupSystem _popupSystem = default!;
[Dependency] private readonly SharedHandsSystem _hands = default!;
[Dependency] private readonly EntityWhitelistSystem _whitelistSystem = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<ActivatableUIComponent, ComponentStartup>(OnStartup);
SubscribeLocalEvent<ActivatableUIComponent, UseInHandEvent>(OnUseInHand);
SubscribeLocalEvent<ActivatableUIComponent, ActivateInWorldEvent>(OnActivate);
SubscribeLocalEvent<ActivatableUIComponent, InteractUsingEvent>(OnInteractUsing);
SubscribeLocalEvent<ActivatableUIComponent, HandDeselectedEvent>(OnHandDeselected);
SubscribeLocalEvent<ActivatableUIComponent, GotUnequippedHandEvent>(OnHandUnequipped);
SubscribeLocalEvent<ActivatableUIComponent, BoundUIClosedEvent>(OnUIClose);
SubscribeLocalEvent<ActivatableUIComponent, GetVerbsEvent<ActivationVerb>>(GetActivationVerb);
SubscribeLocalEvent<ActivatableUIComponent, GetVerbsEvent<Verb>>(GetVerb);
SubscribeLocalEvent<UserInterfaceComponent, OpenUiActionEvent>(OnActionPerform);
InitializePower();
}
private void OnStartup(Entity<ActivatableUIComponent> ent, ref ComponentStartup args)
{
if (ent.Comp.Key == null)
{
Log.Error($"Missing UI Key for entity: {ToPrettyString(ent)}");
return;
}
// TODO BUI
// set interaction range to zero to avoid constant range checks.
//
// if (ent.Comp.InHandsOnly && _uiSystem.TryGetInterfaceData(ent.Owner, ent.Comp.Key, out var data))
// data.InteractionRange = 0;
}
private void OnActionPerform(EntityUid uid, UserInterfaceComponent component, OpenUiActionEvent args)
{
if (args.Handled || args.Key == null)
return;
args.Handled = _uiSystem.TryToggleUi(uid, args.Key, args.Performer);
}
private void GetActivationVerb(EntityUid uid, ActivatableUIComponent component, GetVerbsEvent<ActivationVerb> args)
{
if (component.VerbOnly || !ShouldAddVerb(uid, component, args))
return;
args.Verbs.Add(new ActivationVerb
{
Act = () => InteractUI(args.User, uid, component),
Text = Loc.GetString(component.VerbText),
// TODO VERB ICON find a better icon
Icon = new SpriteSpecifier.Texture(new ResPath("/Textures/Interface/VerbIcons/settings.svg.192dpi.png")),
});
}
private void GetVerb(EntityUid uid, ActivatableUIComponent component, GetVerbsEvent<Verb> args)
{
if (!component.VerbOnly || !ShouldAddVerb(uid, component, args))
return;
args.Verbs.Add(new Verb
{
Act = () => InteractUI(args.User, uid, component),
Text = Loc.GetString(component.VerbText),
// TODO VERB ICON find a better icon
Icon = new SpriteSpecifier.Texture(new ResPath("/Textures/Interface/VerbIcons/settings.svg.192dpi.png")),
});
}
private bool ShouldAddVerb<T>(EntityUid uid, ActivatableUIComponent component, GetVerbsEvent<T> args) where T : Verb
{
if (!args.CanAccess)
return false;
if (_whitelistSystem.IsWhitelistFail(component.RequiredItems, args.Using ?? default))
return false;
if (component.RequiresComplex)
{
if (args.Hands == null)
return false;
if (component.InHandsOnly)
{
if (!_hands.IsHolding(args.User, uid, out var hand, args.Hands))
return false;
if (component.RequireActiveHand && args.Hands.ActiveHand != hand)
return false;
}
}
return args.CanInteract || HasComp<GhostComponent>(args.User) && !component.BlockSpectators;
}
private void OnUseInHand(EntityUid uid, ActivatableUIComponent component, UseInHandEvent args)
{
if (args.Handled)
return;
if (component.VerbOnly)
return;
if (component.RequiredItems != null)
return;
args.Handled = InteractUI(args.User, uid, component);
}
private void OnActivate(EntityUid uid, ActivatableUIComponent component, ActivateInWorldEvent args)
{
if (args.Handled || !args.Complex)
return;
if (component.VerbOnly)
return;
if (component.RequiredItems != null)
return;
args.Handled = InteractUI(args.User, uid, component);
}
private void OnInteractUsing(EntityUid uid, ActivatableUIComponent component, InteractUsingEvent args)
{
if (args.Handled)
return;
if (component.VerbOnly)
return;
if (component.RequiredItems == null)
return;
if (_whitelistSystem.IsWhitelistFail(component.RequiredItems, args.Used))
return;
args.Handled = InteractUI(args.User, uid, component);
}
private void OnUIClose(EntityUid uid, ActivatableUIComponent component, BoundUIClosedEvent args)
{
var user = args.Actor;
if (user != component.CurrentSingleUser)
return;
if (!Equals(args.UiKey, component.Key))
return;
SetCurrentSingleUser(uid, null, component);
}
private bool InteractUI(EntityUid user, EntityUid uiEntity, ActivatableUIComponent aui)
{
if (aui.Key == null || !_uiSystem.HasUi(uiEntity, aui.Key))
return false;
if (_uiSystem.IsUiOpen(uiEntity, aui.Key, user))
{
_uiSystem.CloseUi(uiEntity, aui.Key, user);
return true;
}
if (!_blockerSystem.CanInteract(user, uiEntity) && (!HasComp<GhostComponent>(user) || aui.BlockSpectators))
return false;
if (aui.RequiresComplex)
{
if (!_blockerSystem.CanComplexInteract(user))
return false;
}
if (aui.InHandsOnly)
{
if (!TryComp(user, out HandsComponent? hands))
return false;
if (!_hands.IsHolding(user, uiEntity, out var hand, hands))
return false;
if (aui.RequireActiveHand && hands.ActiveHand != hand)
return false;
}
if (aui.AdminOnly && !_adminManager.IsAdmin(user))
return false;
if (aui.SingleUser && aui.CurrentSingleUser != null && user != aui.CurrentSingleUser)
{
var message = Loc.GetString("machine-already-in-use", ("machine", uiEntity));
_popupSystem.PopupClient(message, uiEntity, user);
if (_uiSystem.IsUiOpen(uiEntity, aui.Key))
return true;
Log.Error($"Activatable UI has user without being opened? Entity: {ToPrettyString(uiEntity)}. User: {aui.CurrentSingleUser}, Key: {aui.Key}");
}
// If we've gotten this far, fire a cancellable event that indicates someone is about to activate this.
// This is so that stuff can require further conditions (like power).
var oae = new ActivatableUIOpenAttemptEvent(user);
var uae = new UserOpenActivatableUIAttemptEvent(user, uiEntity);
RaiseLocalEvent(user, uae);
RaiseLocalEvent(uiEntity, oae);
if (oae.Cancelled || uae.Cancelled)
return false;
// Give the UI an opportunity to prepare itself if it needs to do anything
// before opening
var bae = new BeforeActivatableUIOpenEvent(user);
RaiseLocalEvent(uiEntity, bae);
SetCurrentSingleUser(uiEntity, user, aui);
_uiSystem.OpenUi(uiEntity, aui.Key, user);
//Let the component know a user opened it so it can do whatever it needs to do
var aae = new AfterActivatableUIOpenEvent(user, user);
RaiseLocalEvent(uiEntity, aae);
return true;
}
public void SetCurrentSingleUser(EntityUid uid, EntityUid? user, ActivatableUIComponent? aui = null)
{
if (!Resolve(uid, ref aui))
return;
if (!aui.SingleUser)
return;
aui.CurrentSingleUser = user;
Dirty(uid, aui);
RaiseLocalEvent(uid, new ActivatableUIPlayerChangedEvent());
}
public void CloseAll(EntityUid uid, ActivatableUIComponent? aui = null)
{
if (!Resolve(uid, ref aui, false))
return;
if (aui.Key == null)
{
Log.Error($"Encountered null key in activatable ui on entity {ToPrettyString(uid)}");
return;
}
_uiSystem.CloseUi(uid, aui.Key);
}
private void OnHandDeselected(Entity<ActivatableUIComponent> ent, ref HandDeselectedEvent args)
{
if (ent.Comp.InHandsOnly && ent.Comp.RequireActiveHand)
CloseAll(ent, ent);
}
private void OnHandUnequipped(Entity<ActivatableUIComponent> ent, ref GotUnequippedHandEvent args)
{
if (ent.Comp.InHandsOnly)
CloseAll(ent, ent);
}
}
| 412 | 0.910135 | 1 | 0.910135 | game-dev | MEDIA | 0.871616 | game-dev | 0.977015 | 1 | 0.977015 |
ProjectIgnis/CardScripts | 1,578 | unofficial/c511000889.lua | --Pheromone Wasp
local s,id=GetID()
function s.initial_effect(c)
--sp summon
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_DAMAGE_STEP_END)
e2:SetCondition(s.condition)
e2:SetOperation(s.operation)
c:RegisterEffect(e2)
end
function s.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetAttackTarget()==nil and Duel.GetAttacker()==e:GetHandler()
end
function s.operation(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_PHASE+PHASE_BATTLE)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetTarget(s.sptg)
e1:SetOperation(s.spop)
e1:SetReset(RESET_PHASE+PHASE_BATTLE)
e:GetHandler():RegisterEffect(e1)
end
function s.filter(c,e,tp)
return c:IsLevelBelow(4) and c:IsRace(RACE_INSECT) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,s.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if #g>0 then
if Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
else
Duel.Destroy(g,REASON_EFFECT)
end
else
local cg=Duel.GetFieldGroup(tp,LOCATION_DECK,0)
Duel.ConfirmCards(1-tp,cg)
Duel.ShuffleDeck(tp)
end
end | 412 | 0.907167 | 1 | 0.907167 | game-dev | MEDIA | 0.984998 | game-dev | 0.954983 | 1 | 0.954983 |
ImLegiitXD/Dream-Advanced | 12,647 | dll/back/1.8.9/net/minecraft/client/gui/stream/GuiStreamUnavailable.java | package net.minecraft.client.gui.stream;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.stream.IStream;
import net.minecraft.client.stream.NullStream;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.Session;
import net.minecraft.util.Util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GLContext;
import tv.twitch.ErrorCode;
public class GuiStreamUnavailable extends GuiScreen
{
private static final Logger field_152322_a = LogManager.getLogger();
private final IChatComponent field_152324_f;
private final GuiScreen parentScreen;
private final GuiStreamUnavailable.Reason field_152326_h;
private final List<ChatComponentTranslation> field_152327_i;
private final List<String> field_152323_r;
public GuiStreamUnavailable(GuiScreen p_i1070_1_, GuiStreamUnavailable.Reason p_i1070_2_)
{
this(p_i1070_1_, p_i1070_2_, (List<ChatComponentTranslation>)null);
}
public GuiStreamUnavailable(GuiScreen parentScreenIn, GuiStreamUnavailable.Reason p_i46311_2_, List<ChatComponentTranslation> p_i46311_3_)
{
this.field_152324_f = new ChatComponentTranslation("stream.unavailable.title", new Object[0]);
this.field_152323_r = Lists.<String>newArrayList();
this.parentScreen = parentScreenIn;
this.field_152326_h = p_i46311_2_;
this.field_152327_i = p_i46311_3_;
}
/**
* Adds the buttons (and other controls) to the screen in question. Called when the GUI is displayed and when the
* window resizes, the buttonList is cleared beforehand.
*/
public void initGui()
{
if (this.field_152323_r.isEmpty())
{
this.field_152323_r.addAll(this.fontRendererObj.listFormattedStringToWidth(this.field_152326_h.func_152561_a().getFormattedText(), (int)((float)this.width * 0.75F)));
if (this.field_152327_i != null)
{
this.field_152323_r.add("");
for (ChatComponentTranslation chatcomponenttranslation : this.field_152327_i)
{
this.field_152323_r.add(chatcomponenttranslation.getUnformattedTextForChat());
}
}
}
if (this.field_152326_h.func_152559_b() != null)
{
this.buttonList.add(new GuiButton(0, this.width / 2 - 155, this.height - 50, 150, 20, I18n.format("gui.cancel", new Object[0])));
this.buttonList.add(new GuiButton(1, this.width / 2 - 155 + 160, this.height - 50, 150, 20, I18n.format(this.field_152326_h.func_152559_b().getFormattedText(), new Object[0])));
}
else
{
this.buttonList.add(new GuiButton(0, this.width / 2 - 75, this.height - 50, 150, 20, I18n.format("gui.cancel", new Object[0])));
}
}
/**
* Called when the screen is unloaded. Used to disable keyboard repeat events
*/
public void onGuiClosed()
{
}
/**
* Draws the screen and all the components in it. Args : mouseX, mouseY, renderPartialTicks
*/
public void drawScreen(int mouseX, int mouseY, float partialTicks)
{
this.drawDefaultBackground();
int i = Math.max((int)((double)this.height * 0.85D / 2.0D - (double)((float)(this.field_152323_r.size() * this.fontRendererObj.FONT_HEIGHT) / 2.0F)), 50);
this.drawCenteredString(this.fontRendererObj, this.field_152324_f.getFormattedText(), this.width / 2, i - this.fontRendererObj.FONT_HEIGHT * 2, 16777215);
for (String s : this.field_152323_r)
{
this.drawCenteredString(this.fontRendererObj, s, this.width / 2, i, 10526880);
i += this.fontRendererObj.FONT_HEIGHT;
}
super.drawScreen(mouseX, mouseY, partialTicks);
}
@SuppressWarnings("incomplete-switch")
/**
* Called by the controls from the buttonList when activated. (Mouse pressed for buttons)
*/
protected void actionPerformed(GuiButton button) throws IOException
{
if (button.enabled)
{
if (button.id == 1)
{
switch (this.field_152326_h)
{
case ACCOUNT_NOT_BOUND:
case FAILED_TWITCH_AUTH:
this.func_152320_a("https://account.mojang.com/me/settings");
break;
case ACCOUNT_NOT_MIGRATED:
this.func_152320_a("https://account.mojang.com/migrate");
break;
case UNSUPPORTED_OS_MAC:
this.func_152320_a("http://www.apple.com/osx/");
break;
case UNKNOWN:
case LIBRARY_FAILURE:
case INITIALIZATION_FAILURE:
this.func_152320_a("http://bugs.mojang.com/browse/MC");
}
}
this.mc.displayGuiScreen(this.parentScreen);
}
}
private void func_152320_a(String p_152320_1_)
{
try
{
Class<?> oclass = Class.forName("java.awt.Desktop");
Object object = oclass.getMethod("getDesktop", new Class[0]).invoke((Object)null, new Object[0]);
oclass.getMethod("browse", new Class[] {URI.class}).invoke(object, new Object[] {new URI(p_152320_1_)});
}
catch (Throwable throwable)
{
field_152322_a.error("Couldn\'t open link", throwable);
}
}
public static void func_152321_a(GuiScreen p_152321_0_)
{
Minecraft minecraft = Minecraft.getMinecraft();
IStream istream = minecraft.getTwitchStream();
if (!OpenGlHelper.framebufferSupported)
{
List<ChatComponentTranslation> list = Lists.<ChatComponentTranslation>newArrayList();
list.add(new ChatComponentTranslation("stream.unavailable.no_fbo.version", new Object[] {GL11.glGetString(GL11.GL_VERSION)}));
list.add(new ChatComponentTranslation("stream.unavailable.no_fbo.blend", new Object[] {Boolean.valueOf(GLContext.getCapabilities().GL_EXT_blend_func_separate)}));
list.add(new ChatComponentTranslation("stream.unavailable.no_fbo.arb", new Object[] {Boolean.valueOf(GLContext.getCapabilities().GL_ARB_framebuffer_object)}));
list.add(new ChatComponentTranslation("stream.unavailable.no_fbo.ext", new Object[] {Boolean.valueOf(GLContext.getCapabilities().GL_EXT_framebuffer_object)}));
minecraft.displayGuiScreen(new GuiStreamUnavailable(p_152321_0_, GuiStreamUnavailable.Reason.NO_FBO, list));
}
else if (istream instanceof NullStream)
{
if (((NullStream)istream).func_152937_a().getMessage().contains("Can\'t load AMD 64-bit .dll on a IA 32-bit platform"))
{
minecraft.displayGuiScreen(new GuiStreamUnavailable(p_152321_0_, GuiStreamUnavailable.Reason.LIBRARY_ARCH_MISMATCH));
}
else
{
minecraft.displayGuiScreen(new GuiStreamUnavailable(p_152321_0_, GuiStreamUnavailable.Reason.LIBRARY_FAILURE));
}
}
else if (!istream.func_152928_D() && istream.func_152912_E() == ErrorCode.TTV_EC_OS_TOO_OLD)
{
switch (Util.getOSType())
{
case WINDOWS:
minecraft.displayGuiScreen(new GuiStreamUnavailable(p_152321_0_, GuiStreamUnavailable.Reason.UNSUPPORTED_OS_WINDOWS));
break;
case OSX:
minecraft.displayGuiScreen(new GuiStreamUnavailable(p_152321_0_, GuiStreamUnavailable.Reason.UNSUPPORTED_OS_MAC));
break;
default:
minecraft.displayGuiScreen(new GuiStreamUnavailable(p_152321_0_, GuiStreamUnavailable.Reason.UNSUPPORTED_OS_OTHER));
}
}
else if (!minecraft.getTwitchDetails().containsKey("twitch_access_token"))
{
if (minecraft.getSession().getSessionType() == Session.Type.LEGACY)
{
minecraft.displayGuiScreen(new GuiStreamUnavailable(p_152321_0_, GuiStreamUnavailable.Reason.ACCOUNT_NOT_MIGRATED));
}
else
{
minecraft.displayGuiScreen(new GuiStreamUnavailable(p_152321_0_, GuiStreamUnavailable.Reason.ACCOUNT_NOT_BOUND));
}
}
else if (!istream.func_152913_F())
{
switch (istream.func_152918_H())
{
case INVALID_TOKEN:
minecraft.displayGuiScreen(new GuiStreamUnavailable(p_152321_0_, GuiStreamUnavailable.Reason.FAILED_TWITCH_AUTH));
break;
case ERROR:
default:
minecraft.displayGuiScreen(new GuiStreamUnavailable(p_152321_0_, GuiStreamUnavailable.Reason.FAILED_TWITCH_AUTH_ERROR));
}
}
else if (istream.func_152912_E() != null)
{
List<ChatComponentTranslation> list1 = Arrays.<ChatComponentTranslation>asList(new ChatComponentTranslation[] {new ChatComponentTranslation("stream.unavailable.initialization_failure.extra", new Object[]{ErrorCode.getString(istream.func_152912_E())})});
minecraft.displayGuiScreen(new GuiStreamUnavailable(p_152321_0_, GuiStreamUnavailable.Reason.INITIALIZATION_FAILURE, list1));
}
else
{
minecraft.displayGuiScreen(new GuiStreamUnavailable(p_152321_0_, GuiStreamUnavailable.Reason.UNKNOWN));
}
}
public static enum Reason
{
NO_FBO(new ChatComponentTranslation("stream.unavailable.no_fbo", new Object[0])),
LIBRARY_ARCH_MISMATCH(new ChatComponentTranslation("stream.unavailable.library_arch_mismatch", new Object[0])),
LIBRARY_FAILURE(new ChatComponentTranslation("stream.unavailable.library_failure", new Object[0]), new ChatComponentTranslation("stream.unavailable.report_to_mojang", new Object[0])),
UNSUPPORTED_OS_WINDOWS(new ChatComponentTranslation("stream.unavailable.not_supported.windows", new Object[0])),
UNSUPPORTED_OS_MAC(new ChatComponentTranslation("stream.unavailable.not_supported.mac", new Object[0]), new ChatComponentTranslation("stream.unavailable.not_supported.mac.okay", new Object[0])),
UNSUPPORTED_OS_OTHER(new ChatComponentTranslation("stream.unavailable.not_supported.other", new Object[0])),
ACCOUNT_NOT_MIGRATED(new ChatComponentTranslation("stream.unavailable.account_not_migrated", new Object[0]), new ChatComponentTranslation("stream.unavailable.account_not_migrated.okay", new Object[0])),
ACCOUNT_NOT_BOUND(new ChatComponentTranslation("stream.unavailable.account_not_bound", new Object[0]), new ChatComponentTranslation("stream.unavailable.account_not_bound.okay", new Object[0])),
FAILED_TWITCH_AUTH(new ChatComponentTranslation("stream.unavailable.failed_auth", new Object[0]), new ChatComponentTranslation("stream.unavailable.failed_auth.okay", new Object[0])),
FAILED_TWITCH_AUTH_ERROR(new ChatComponentTranslation("stream.unavailable.failed_auth_error", new Object[0])),
INITIALIZATION_FAILURE(new ChatComponentTranslation("stream.unavailable.initialization_failure", new Object[0]), new ChatComponentTranslation("stream.unavailable.report_to_mojang", new Object[0])),
UNKNOWN(new ChatComponentTranslation("stream.unavailable.unknown", new Object[0]), new ChatComponentTranslation("stream.unavailable.report_to_mojang", new Object[0]));
private final IChatComponent field_152574_m;
private final IChatComponent field_152575_n;
private Reason(IChatComponent p_i1066_3_)
{
this(p_i1066_3_, (IChatComponent)null);
}
private Reason(IChatComponent p_i1067_3_, IChatComponent p_i1067_4_)
{
this.field_152574_m = p_i1067_3_;
this.field_152575_n = p_i1067_4_;
}
public IChatComponent func_152561_a()
{
return this.field_152574_m;
}
public IChatComponent func_152559_b()
{
return this.field_152575_n;
}
}
}
| 412 | 0.847335 | 1 | 0.847335 | game-dev | MEDIA | 0.798654 | game-dev | 0.898564 | 1 | 0.898564 |
Oscheibe/ARIndoorNav | 1,273 | ARIndoorNav Project/Assets/Scripts/View/MarkerDetectionUI.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MarkerDetectionUI : MonoBehaviour
{
public SystemStatePresenter _SystemStatePresenter;
public TextDetection _TextDetection;
public MarkerDetection _MarkerDetection;
public GameObject _loadingAnimationGO;
public float _loadingTime = 1.0f;
public string DestinationRoomString { get; private set; }
public void ShowLoadingAnimation()
{
_loadingAnimationGO.SetActive(true);
Invoke("HideLoadingAnimation", _loadingTime);
}
private void HideLoadingAnimation()
{
_loadingAnimationGO.SetActive(false);
}
/**
* Called by a button
* Method to start the marker detection process
*/
public void StartMarkerDetection()
{
Debug.Log($"Pressed Marker detection button: {DestinationRoomString}");
if (!string.IsNullOrEmpty(DestinationRoomString))
{
_MarkerDetection.SaveUserPosition();
_TextDetection.ReceiveTextList(new List<string> { DestinationRoomString });
}
//_SystemStatePresenter.ConfirmMarkerTracking();
}
public void SetDestinationRoomString(string input)
{
DestinationRoomString = input;
}
} | 412 | 0.7181 | 1 | 0.7181 | game-dev | MEDIA | 0.730051 | game-dev,desktop-app | 0.572507 | 1 | 0.572507 |
electronicarts/CnC_Remastered_Collection | 4,363 | REDALERT/SMUDGE.H | //
// Copyright 2020 Electronic Arts Inc.
//
// TiberianDawn.DLL and RedAlert.dll and corresponding source code is free
// software: you can redistribute it and/or modify it under the terms of
// the GNU General Public License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
// TiberianDawn.DLL and RedAlert.dll and corresponding source code is distributed
// in the hope that it will be useful, but with permitted additional restrictions
// under Section 7 of the GPL. See the GNU General Public License in LICENSE.TXT
// distributed with this program. You should have received a copy of the
// GNU General Public License along with permitted additional restrictions
// with this program. If not, see https://github.com/electronicarts/CnC_Remastered_Collection
/* $Header: /CounterStrike/SMUDGE.H 1 3/03/97 10:25a Joe_bostic $ */
/***********************************************************************************************
*** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***
***********************************************************************************************
* *
* Project Name : Command & Conquer *
* *
* File Name : SMUDGE.H *
* *
* Programmer : Joe L. Bostic *
* *
* Start Date : August 9, 1994 *
* *
* Last Update : August 9, 1994 [JLB] *
* *
*---------------------------------------------------------------------------------------------*
* Functions: *
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#ifndef SMUDGE_H
#define SMUDGE_H
#include "object.h"
#include "type.h"
/******************************************************************************
** This is the transitory form for smudges. They exist as independent objects
** only in the transition stage from creation to placement upon the map. Once
** they are placed on the map, they merely become 'smudges' in the cell data. This
** object is then destroyed.
*/
class SmudgeClass : public ObjectClass
{
public:
/*
** This is a pointer to the template object's class.
*/
CCPtr<SmudgeTypeClass> Class;
/*-------------------------------------------------------------------
** Constructors and destructors.
*/
static void * operator new(size_t size);
static void * operator new(size_t , void * ptr) {return(ptr);};
static void operator delete(void *ptr);
SmudgeClass(SmudgeType type, COORDINATE pos=0xFFFFFFFFUL, HousesType house = HOUSE_NONE);
SmudgeClass(NoInitClass const & x) : ObjectClass(x), Class(x) {};
operator SmudgeType(void) const {return Class->Type;};
virtual ~SmudgeClass(void) {if (GameActive) SmudgeClass::Limbo();Class=0;};
static void Init(void);
/*
** File I/O.
*/
static void Read_INI(CCINIClass & ini);
static void Write_INI(CCINIClass & ini);
static char *INI_Name(void) {return "SMUDGE";};
bool Load(Straw & file);
bool Save(Pipe & file) const;
virtual ObjectTypeClass const & Class_Of(void) const {return *Class;};
virtual bool Mark(MarkType);
virtual void Draw_It(int , int , WindowNumberType ) const {};
void Disown(CELL cell);
private:
static HousesType ToOwn;
/*
** Some additional padding in case we need to add data to the class and maintain backwards compatibility for save/load
*/
unsigned char SaveLoadPadding[8];
};
#endif | 412 | 0.823577 | 1 | 0.823577 | game-dev | MEDIA | 0.792473 | game-dev | 0.50143 | 1 | 0.50143 |
magefree/mage | 2,441 | Mage.Sets/src/mage/cards/m/Manabond.java |
package mage.cards.m;
import mage.MageObject;
import mage.abilities.Ability;
import mage.abilities.triggers.BeginningOfEndStepTriggeredAbility;
import mage.abilities.effects.OneShotEffect;
import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.Zone;
import mage.game.Game;
import mage.players.Player;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.UUID;
/**
*
* @author Plopman
*/
public final class Manabond extends CardImpl {
public Manabond(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{G}");
// At the beginning of your end step, reveal your hand and put all land cards from it onto the battlefield. If you do, discard your hand.
this.addAbility(new BeginningOfEndStepTriggeredAbility(new ManabondEffect(), true));
}
private Manabond(final Manabond card) {
super(card);
}
@Override
public Manabond copy() {
return new Manabond(this);
}
}
class ManabondEffect extends OneShotEffect {
ManabondEffect() {
super(Outcome.PutCardInPlay);
staticText = "reveal your hand and put all land cards from it onto the battlefield. If you do, discard your hand";
}
private ManabondEffect(final ManabondEffect effect) {
super(effect);
}
@Override
public boolean apply(Game game, Ability source) {
Player controller = game.getPlayer(source.getControllerId());
MageObject sourceObject = source.getSourceObject(game);
if (controller != null && sourceObject != null) {
controller.revealCards(sourceObject.getIdName(), controller.getHand(), game);
Set<Card> toBattlefield = new LinkedHashSet<>();
for (UUID uuid : controller.getHand()) {
Card card = game.getCard(uuid);
if (card != null && card.isLand(game)) {
toBattlefield.add(card);
}
}
controller.moveCards(toBattlefield, Zone.BATTLEFIELD, source, game, false, false, true, null);
controller.discard(controller.getHand().size(), false, false, source, game);
return true;
}
return false;
}
@Override
public ManabondEffect copy() {
return new ManabondEffect(this);
}
}
| 412 | 0.993471 | 1 | 0.993471 | game-dev | MEDIA | 0.987458 | game-dev | 0.997529 | 1 | 0.997529 |
Joshua-F/osrs-dumps | 8,045 | script/[clientscript,duel_initworn].cs2 | // 205
[clientscript,duel_initworn]
def_int $int0 = 0;
def_obj $obj1 = null;
cc_deleteall(pvp_arena_legacyduel_options:worn_lay);
cc_deleteall(pvp_arena_legacyduel_options:no_signs);
def_int $int2 = 0;
while ($int2 < 11) {
cc_create(pvp_arena_legacyduel_options:worn_lay, ^iftype_graphic, $int2);
cc_setsize(36, 32, ^setsize_abs, ^setsize_abs);
if ($int2 = 0) {
cc_setposition(if_getx(pvp_arena_legacyduel_options:duel_wornicon0), if_gety(pvp_arena_legacyduel_options:duel_wornicon0), ^setpos_abs_left, ^setpos_abs_top);
$int0 = 0;
}
if ($int2 = 1) {
cc_setposition(if_getx(pvp_arena_legacyduel_options:duel_wornicon1), if_gety(pvp_arena_legacyduel_options:duel_wornicon1), ^setpos_abs_left, ^setpos_abs_top);
$int0 = 1;
}
if ($int2 = 2) {
cc_setposition(if_getx(pvp_arena_legacyduel_options:duel_wornicon2), if_gety(pvp_arena_legacyduel_options:duel_wornicon2), ^setpos_abs_left, ^setpos_abs_top);
$int0 = 2;
}
if ($int2 = 3) {
cc_setposition(if_getx(pvp_arena_legacyduel_options:duel_wornicon13), if_gety(pvp_arena_legacyduel_options:duel_wornicon13), ^setpos_abs_left, ^setpos_abs_top);
$int0 = 13;
}
if ($int2 = 4) {
cc_setposition(if_getx(pvp_arena_legacyduel_options:duel_wornicon3), if_gety(pvp_arena_legacyduel_options:duel_wornicon3), ^setpos_abs_left, ^setpos_abs_top);
$int0 = 3;
}
if ($int2 = 5) {
cc_setposition(if_getx(pvp_arena_legacyduel_options:duel_wornicon4), if_gety(pvp_arena_legacyduel_options:duel_wornicon4), ^setpos_abs_left, ^setpos_abs_top);
$int0 = 4;
}
if ($int2 = 6) {
cc_setposition(if_getx(pvp_arena_legacyduel_options:duel_wornicon5), if_gety(pvp_arena_legacyduel_options:duel_wornicon5), ^setpos_abs_left, ^setpos_abs_top);
$int0 = 5;
}
if ($int2 = 7) {
cc_setposition(if_getx(pvp_arena_legacyduel_options:duel_wornicon7), if_gety(pvp_arena_legacyduel_options:duel_wornicon7), ^setpos_abs_left, ^setpos_abs_top);
$int0 = 7;
}
if ($int2 = 8) {
cc_setposition(if_getx(pvp_arena_legacyduel_options:duel_wornicon9), if_gety(pvp_arena_legacyduel_options:duel_wornicon9), ^setpos_abs_left, ^setpos_abs_top);
$int0 = 9;
}
if ($int2 = 9) {
cc_setposition(if_getx(pvp_arena_legacyduel_options:duel_wornicon10), if_gety(pvp_arena_legacyduel_options:duel_wornicon10), ^setpos_abs_left, ^setpos_abs_top);
$int0 = 10;
}
if ($int2 = 10) {
cc_setposition(if_getx(pvp_arena_legacyduel_options:duel_wornicon12), if_gety(pvp_arena_legacyduel_options:duel_wornicon12), ^setpos_abs_left, ^setpos_abs_top);
$int0 = 12;
}
$obj1 = inv_getobj(worn, $int0);
if ($obj1 ! null) {
cc_setobject($obj1, inv_getnum(worn, $int0));
cc_setopbase("<col=ff9040><oc_name($obj1)></col>");
cc_setgraphicshadow(0x333333);
cc_setoutline(1);
if ($int0 = 0) {
if_setgraphic(null, pvp_arena_legacyduel_options:duel_wornicon0);
}
if ($int0 = 1) {
if_setgraphic(null, pvp_arena_legacyduel_options:duel_wornicon1);
}
if ($int0 = 2) {
if_setgraphic(null, pvp_arena_legacyduel_options:duel_wornicon2);
}
if ($int0 = 13) {
if_setgraphic(null, pvp_arena_legacyduel_options:duel_wornicon13);
}
if ($int0 = 3) {
if_setgraphic(null, pvp_arena_legacyduel_options:duel_wornicon3);
}
if ($int0 = 4) {
if_setgraphic(null, pvp_arena_legacyduel_options:duel_wornicon4);
}
if ($int0 = 5) {
if_setgraphic(null, pvp_arena_legacyduel_options:duel_wornicon5);
}
if ($int0 = 7) {
if_setgraphic(null, pvp_arena_legacyduel_options:duel_wornicon7);
}
if ($int0 = 9) {
if_setgraphic(null, pvp_arena_legacyduel_options:duel_wornicon9);
}
if ($int0 = 10) {
if_setgraphic(null, pvp_arena_legacyduel_options:duel_wornicon10);
}
if ($int0 = 12) {
if_setgraphic(null, pvp_arena_legacyduel_options:duel_wornicon12);
}
} else {
if ($int0 = 0) {
if_setgraphic("wornicons,0", pvp_arena_legacyduel_options:duel_wornicon0);
}
if ($int0 = 1) {
if_setgraphic("wornicons,1", pvp_arena_legacyduel_options:duel_wornicon1);
}
if ($int0 = 2) {
if_setgraphic("wornicons,2", pvp_arena_legacyduel_options:duel_wornicon2);
}
if ($int0 = 13) {
if_setgraphic("wornicons,10", pvp_arena_legacyduel_options:duel_wornicon13);
}
if ($int0 = 3) {
if_setgraphic("wornicons,3", pvp_arena_legacyduel_options:duel_wornicon3);
}
if ($int0 = 4) {
if_setgraphic("wornicons,5", pvp_arena_legacyduel_options:duel_wornicon4);
}
if ($int0 = 5) {
if_setgraphic("wornicons,6", pvp_arena_legacyduel_options:duel_wornicon5);
}
if ($int0 = 7) {
if_setgraphic("wornicons,7", pvp_arena_legacyduel_options:duel_wornicon7);
}
if ($int0 = 9) {
if_setgraphic("wornicons,8", pvp_arena_legacyduel_options:duel_wornicon9);
}
if ($int0 = 10) {
if_setgraphic("wornicons,9", pvp_arena_legacyduel_options:duel_wornicon10);
}
if ($int0 = 12) {
if_setgraphic("wornicons,4", pvp_arena_legacyduel_options:duel_wornicon12);
}
}
cc_create(pvp_arena_legacyduel_options:no_signs, ^iftype_graphic, $int2);
cc_setsize(10, 32, ^setsize_abs, ^setsize_abs);
cc_setgraphic(exclamation_mark);
cc_sethide(true);
if ($int2 = 0) {
cc_setposition(calc(10 + if_getx(pvp_arena_legacyduel_options:duel_wornicon0)), if_gety(pvp_arena_legacyduel_options:duel_wornicon0), ^setpos_abs_left, ^setpos_abs_top);
}
if ($int2 = 1) {
cc_setposition(calc(10 + if_getx(pvp_arena_legacyduel_options:duel_wornicon1)), if_gety(pvp_arena_legacyduel_options:duel_wornicon1), ^setpos_abs_left, ^setpos_abs_top);
}
if ($int2 = 2) {
cc_setposition(calc(10 + if_getx(pvp_arena_legacyduel_options:duel_wornicon2)), if_gety(pvp_arena_legacyduel_options:duel_wornicon2), ^setpos_abs_left, ^setpos_abs_top);
}
if ($int2 = 3) {
cc_setposition(calc(10 + if_getx(pvp_arena_legacyduel_options:duel_wornicon13)), if_gety(pvp_arena_legacyduel_options:duel_wornicon13), ^setpos_abs_left, ^setpos_abs_top);
}
if ($int2 = 4) {
cc_setposition(calc(10 + if_getx(pvp_arena_legacyduel_options:duel_wornicon3)), if_gety(pvp_arena_legacyduel_options:duel_wornicon3), ^setpos_abs_left, ^setpos_abs_top);
}
if ($int2 = 5) {
cc_setposition(calc(10 + if_getx(pvp_arena_legacyduel_options:duel_wornicon4)), if_gety(pvp_arena_legacyduel_options:duel_wornicon4), ^setpos_abs_left, ^setpos_abs_top);
}
if ($int2 = 6) {
cc_setposition(calc(10 + if_getx(pvp_arena_legacyduel_options:duel_wornicon5)), if_gety(pvp_arena_legacyduel_options:duel_wornicon5), ^setpos_abs_left, ^setpos_abs_top);
}
if ($int2 = 7) {
cc_setposition(calc(10 + if_getx(pvp_arena_legacyduel_options:duel_wornicon7)), if_gety(pvp_arena_legacyduel_options:duel_wornicon7), ^setpos_abs_left, ^setpos_abs_top);
}
if ($int2 = 8) {
cc_setposition(calc(10 + if_getx(pvp_arena_legacyduel_options:duel_wornicon9)), if_gety(pvp_arena_legacyduel_options:duel_wornicon9), ^setpos_abs_left, ^setpos_abs_top);
}
if ($int2 = 9) {
cc_setposition(calc(10 + if_getx(pvp_arena_legacyduel_options:duel_wornicon10)), if_gety(pvp_arena_legacyduel_options:duel_wornicon10), ^setpos_abs_left, ^setpos_abs_top);
}
if ($int2 = 10) {
cc_setposition(calc(10 + if_getx(pvp_arena_legacyduel_options:duel_wornicon12)), if_gety(pvp_arena_legacyduel_options:duel_wornicon12), ^setpos_abs_left, ^setpos_abs_top);
}
$int2 = calc($int2 + 1);
}
| 412 | 0.982018 | 1 | 0.982018 | game-dev | MEDIA | 0.962421 | game-dev | 0.796635 | 1 | 0.796635 |
pyfa-org/eos | 6,539 | tests/integration/sim/rah/criteria/test_criteria.py | # ==============================================================================
# Copyright (C) 2011 Diego Duclos
# Copyright (C) 2011-2018 Anton Vorobyov
#
# This file is part of Eos.
#
# Eos is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Eos is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Eos. If not, see <http://www.gnu.org/licenses/>.
# ==============================================================================
from eos import EffectMode
from eos import ModuleLow
from eos import Ship
from eos import State
from eos.const.eve import EffectId
from tests.integration.sim.rah.testcase import RahSimTestCase
class TestRahSimCriteria(RahSimTestCase):
def test_active_added(self):
# Setup
ship = Ship(self.make_ship_type((0.5, 0.65, 0.75, 0.9)).id)
self.fit.ship = ship
rah = ModuleLow(
self.make_rah_type((0.85, 0.85, 0.85, 0.85), 6, 1000).id,
state=State.active)
# Action
self.fit.modules.low.equip(rah)
# Verification
self.assertAlmostEqual(rah.attrs[self.armor_em.id], 1)
self.assertAlmostEqual(rah.attrs[self.armor_therm.id], 0.925)
self.assertAlmostEqual(rah.attrs[self.armor_kin.id], 0.82)
self.assertAlmostEqual(rah.attrs[self.armor_expl.id], 0.655)
self.assertAlmostEqual(ship.attrs[self.armor_em.id], 0.5)
self.assertAlmostEqual(ship.attrs[self.armor_therm.id], 0.60125)
self.assertAlmostEqual(ship.attrs[self.armor_kin.id], 0.615)
self.assertAlmostEqual(ship.attrs[self.armor_expl.id], 0.5895)
# Cleanup
self.assert_solsys_buffers_empty(self.fit.solar_system)
self.assert_log_entries(0)
def test_active_switched(self):
# Setup
ship = Ship(self.make_ship_type((0.5, 0.65, 0.75, 0.9)).id)
self.fit.ship = ship
rah = ModuleLow(
self.make_rah_type((0.85, 0.85, 0.85, 0.85), 6, 1000).id,
state=State.online)
self.fit.modules.low.equip(rah)
# Action
rah.state = State.active
# Verification
self.assertAlmostEqual(rah.attrs[self.armor_em.id], 1)
self.assertAlmostEqual(rah.attrs[self.armor_therm.id], 0.925)
self.assertAlmostEqual(rah.attrs[self.armor_kin.id], 0.82)
self.assertAlmostEqual(rah.attrs[self.armor_expl.id], 0.655)
self.assertAlmostEqual(ship.attrs[self.armor_em.id], 0.5)
self.assertAlmostEqual(ship.attrs[self.armor_therm.id], 0.60125)
self.assertAlmostEqual(ship.attrs[self.armor_kin.id], 0.615)
self.assertAlmostEqual(ship.attrs[self.armor_expl.id], 0.5895)
# Cleanup
self.assert_solsys_buffers_empty(self.fit.solar_system)
self.assert_log_entries(0)
def test_inactive_added(self):
# Setup
ship = Ship(self.make_ship_type((0.5, 0.65, 0.75, 0.9)).id)
self.fit.ship = ship
rah = ModuleLow(
self.make_rah_type((0.85, 0.85, 0.85, 0.85), 6, 1000).id,
state=State.online)
# Action
self.fit.modules.low.equip(rah)
# Verification
self.assertAlmostEqual(rah.attrs[self.armor_em.id], 0.85)
self.assertAlmostEqual(rah.attrs[self.armor_therm.id], 0.85)
self.assertAlmostEqual(rah.attrs[self.armor_kin.id], 0.85)
self.assertAlmostEqual(rah.attrs[self.armor_expl.id], 0.85)
self.assertAlmostEqual(ship.attrs[self.armor_em.id], 0.5)
self.assertAlmostEqual(ship.attrs[self.armor_therm.id], 0.65)
self.assertAlmostEqual(ship.attrs[self.armor_kin.id], 0.75)
self.assertAlmostEqual(ship.attrs[self.armor_expl.id], 0.9)
# Cleanup
self.assert_solsys_buffers_empty(self.fit.solar_system)
self.assert_log_entries(0)
def test_inactive_switched(self):
# Setup
ship = Ship(self.make_ship_type((0.5, 0.65, 0.75, 0.9)).id)
self.fit.ship = ship
rah = ModuleLow(
self.make_rah_type((0.85, 0.85, 0.85, 0.85), 6, 1000).id,
state=State.active)
self.fit.modules.low.equip(rah)
# Action
rah.state = State.online
# Verification
self.assertAlmostEqual(rah.attrs[self.armor_em.id], 0.85)
self.assertAlmostEqual(rah.attrs[self.armor_therm.id], 0.85)
self.assertAlmostEqual(rah.attrs[self.armor_kin.id], 0.85)
self.assertAlmostEqual(rah.attrs[self.armor_expl.id], 0.85)
self.assertAlmostEqual(ship.attrs[self.armor_em.id], 0.5)
self.assertAlmostEqual(ship.attrs[self.armor_therm.id], 0.65)
self.assertAlmostEqual(ship.attrs[self.armor_kin.id], 0.75)
self.assertAlmostEqual(ship.attrs[self.armor_expl.id], 0.9)
# Cleanup
self.assert_solsys_buffers_empty(self.fit.solar_system)
self.assert_log_entries(0)
def test_not_rah(self):
# Setup
ship = Ship(self.make_ship_type((0.5, 0.65, 0.75, 0.9)).id)
self.fit.ship = ship
rah = ModuleLow(
self.make_rah_type((0.85, 0.85, 0.85, 0.85), 6, 1000).id,
state=State.active)
# RAH is detected using effect, thus if item doesn't have RAH effect,
# it's not RAH
rah.set_effect_mode(
EffectId.adaptive_armor_hardener, EffectMode.force_stop)
# Action
self.fit.modules.low.equip(rah)
# Verification
self.assertAlmostEqual(rah.attrs[self.armor_em.id], 0.85)
self.assertAlmostEqual(rah.attrs[self.armor_therm.id], 0.85)
self.assertAlmostEqual(rah.attrs[self.armor_kin.id], 0.85)
self.assertAlmostEqual(rah.attrs[self.armor_expl.id], 0.85)
# Effect is not seen - modifiers do not work too
self.assertAlmostEqual(ship.attrs[self.armor_em.id], 0.5)
self.assertAlmostEqual(ship.attrs[self.armor_therm.id], 0.65)
self.assertAlmostEqual(ship.attrs[self.armor_kin.id], 0.75)
self.assertAlmostEqual(ship.attrs[self.armor_expl.id], 0.9)
# Cleanup
self.assert_solsys_buffers_empty(self.fit.solar_system)
self.assert_log_entries(0)
| 412 | 0.850711 | 1 | 0.850711 | game-dev | MEDIA | 0.862092 | game-dev,testing-qa | 0.690448 | 1 | 0.690448 |
Squalr/Squally | 7,212 | Source/Scenes/Platformer/Level/Combat/Attacks/Debuffs/Manifest/Manifest.cpp | #include "Manifest.h"
#include "cocos/2d/CCActionInstant.h"
#include "cocos/2d/CCActionInterval.h"
#include "cocos/2d/CCSprite.h"
#include "Engine/Animations/SmartAnimationSequenceNode.h"
#include "Engine/Events/ObjectEvents.h"
#include "Engine/Hackables/HackableCode.h"
#include "Engine/Hackables/HackableObject.h"
#include "Engine/Hackables/Menus/HackablePreview.h"
#include "Engine/Localization/ConcatString.h"
#include "Engine/Localization/ConstantString.h"
#include "Engine/Optimization/LazyNode.h"
#include "Engine/Particles/SmartParticles.h"
#include "Engine/Localization/ConstantString.h"
#include "Engine/Sound/WorldSound.h"
#include "Engine/Utils/GameUtils.h"
#include "Engine/Utils/MathUtils.h"
#include "Entities/Platformer/PlatformerEntity.h"
#include "Events/CombatEvents.h"
#include "Events/PlatformerEvents.h"
#include "Scenes/Platformer/Hackables/HackFlags.h"
#include "Scenes/Platformer/Level/Combat/Attacks/Debuffs/Manifest/ManifestGenericPreview.h"
#include "Scenes/Platformer/Level/Combat/CombatMap.h"
#include "Scenes/Platformer/Level/Combat/TimelineEvent.h"
#include "Scenes/Platformer/Level/Combat/TimelineEventGroup.h"
#include "Resources/FXResources.h"
#include "Resources/ObjectResources.h"
#include "Resources/ParticleResources.h"
#include "Resources/SoundResources.h"
#include "Resources/UIResources.h"
#include "Strings/Strings.h"
using namespace cocos2d;
#define LOCAL_FUNC_ID_MANIFEST 1
const std::string Manifest::ManifestIdentifier = "manifest";
const int Manifest::MinMultiplier = -1;
const int Manifest::MaxMultiplier = 2;
const int Manifest::DamageIncrease = 3; // Keep in sync with asm
const float Manifest::Duration = 12.0f;
Manifest* Manifest::create(PlatformerEntity* caster, PlatformerEntity* target)
{
Manifest* instance = new Manifest(caster, target);
instance->autorelease();
return instance;
}
Manifest::Manifest(PlatformerEntity* caster, PlatformerEntity* target)
: super(caster, target, UIResources::Menus_Icons_Spirit, AbilityType::Shadow, BuffData(Manifest::Duration, Manifest::ManifestIdentifier))
{
this->spellEffect = SmartParticles::create(ParticleResources::Platformer_Combat_Abilities_Curse);
this->spellAura = Sprite::create(FXResources::Auras_ChantAura2);
this->spellAura->setColor(Color3B::MAGENTA);
this->spellAura->setOpacity(0);
this->addChild(this->spellEffect);
this->addChild(this->spellAura);
}
Manifest::~Manifest()
{
}
void Manifest::onEnter()
{
super::onEnter();
this->spellEffect->setPositionY(this->owner->getEntityBottomPointRelative().y);
this->spellEffect->start();
this->spellAura->runAction(Sequence::create(
FadeTo::create(0.25f, 255),
DelayTime::create(0.5f),
FadeTo::create(0.25f, 0),
nullptr
));
CombatEvents::TriggerHackableCombatCue();
}
void Manifest::initializePositions()
{
super::initializePositions();
}
void Manifest::registerHackables()
{
super::registerHackables();
if (this->owner == nullptr)
{
return;
}
HackableCode::CodeInfoMap codeInfoMap =
{
{
LOCAL_FUNC_ID_MANIFEST,
HackableCode::HackableCodeInfo(
Manifest::ManifestIdentifier,
Strings::Menus_Hacking_Abilities_Debuffs_Manifest_Manifest::create(),
HackableBase::HackBarColor::Purple,
UIResources::Menus_Icons_Spirit,
LazyNode<HackablePreview>::create([=](){ return ManifestGenericPreview::create(); }),
{
{
HackableCode::Register::zax, Strings::Menus_Hacking_Abilities_Debuffs_Manifest_RegisterEax::create(), HackableDataType::Int32, true
},
},
int(HackFlags::None),
this->getRemainingDuration(),
0.0f,
{
HackableCode::ReadOnlyScript(
Strings::Menus_Hacking_CodeEditor_OriginalCode::create(),
// x86
ConcatString::create({
COMMENT(Strings::Menus_Hacking_Abilities_Debuffs_Manifest_CommentCompareDamage::create()),
ConstantString::create("cmp dword ptr [eax], 0\n"),
COMMENT(Strings::Menus_Hacking_Abilities_Debuffs_Manifest_CommentJumpReduce::create()),
ConstantString::create("jne reduceDamage\n"),
COMMENT(Strings::Menus_Hacking_Abilities_Debuffs_Manifest_CommentElseSkip::create()),
ConstantString::create("jmp skipCode\n\n"),
ConstantString::create("reduceDamage:\n"),
ConstantString::create("mov dword ptr [eax], 0\n\n"),
ConstantString::create("skipCode:\n\n"),
COMMENT(Strings::Menus_Hacking_Abilities_Generic_Conditional_CommentJmp::create()),
COMMENT(Strings::Menus_Hacking_Abilities_Generic_Conditional_CommentJne::create()),
COMMENT(Strings::Menus_Hacking_Abilities_Generic_Conditional_CommentJ::create()),
COMMENT(Strings::Menus_Hacking_Abilities_Generic_Conditional_CommentNe::create())
})
, // x64
ConcatString::create({
COMMENT(Strings::Menus_Hacking_Abilities_Debuffs_Manifest_CommentCompareDamage::create()),
ConstantString::create("cmp dword ptr [rax], 0\n"),
COMMENT(Strings::Menus_Hacking_Abilities_Debuffs_Manifest_CommentJumpReduce::create()),
ConstantString::create("jne reduceDamage\n"),
COMMENT(Strings::Menus_Hacking_Abilities_Debuffs_Manifest_CommentElseSkip::create()),
ConstantString::create("jmp skipCode\n"),
ConstantString::create("reduceDamage:\n"),
ConstantString::create("mov dword ptr [rax], 0\n\n"),
ConstantString::create("skipCode:\n\n"),
COMMENT(Strings::Menus_Hacking_Abilities_Generic_Conditional_CommentJmp::create()),
COMMENT(Strings::Menus_Hacking_Abilities_Generic_Conditional_CommentJne::create()),
COMMENT(Strings::Menus_Hacking_Abilities_Generic_Conditional_CommentJ::create()),
COMMENT(Strings::Menus_Hacking_Abilities_Generic_Conditional_CommentNe::create())
})
)
},
true
)
},
};
this->hackables = CREATE_HACKABLES(Manifest::applyManifest, codeInfoMap);
for (HackableCode* next : this->hackables)
{
this->owner->registerCode(next);
}
}
void Manifest::onBeforeDamageDealt(CombatEvents::ModifiableDamageOrHealingArgs* damageOrHealing)
{
super::onBeforeDamageDealt(damageOrHealing);
Buff::HackStateStorage[Buff::StateKeyDamageDealt] = Value(damageOrHealing->damageOrHealingValue);
this->applyManifest();
(*damageOrHealing->damageOrHealingMin) = -std::abs(damageOrHealing->damageOrHealingValue * Manifest::MinMultiplier);
(*damageOrHealing->damageOrHealingMax) = std::abs(damageOrHealing->damageOrHealingValue * Manifest::MaxMultiplier);
(*damageOrHealing->damageOrHealing) = Buff::HackStateStorage[Buff::StateKeyDamageDealt].asInt();
}
NO_OPTIMIZE void Manifest::applyManifest()
{
static volatile int currentDamageDealt;
static volatile int* currentDamagePtr;
currentDamageDealt = 0;
currentDamagePtr = ¤tDamageDealt;
ASM_PUSH_EFLAGS();
ASM(push ZAX);
ASM_MOV_REG_PTR(ZAX, currentDamagePtr);
HACKABLE_CODE_BEGIN(LOCAL_FUNC_ID_MANIFEST);
ASM(cmp dword ptr [ZAX], 0);
ASM(jne manifestReduceDamage);
ASM(jmp skipManifestCode);
ASM(manifestReduceDamage:);
ASM(mov dword ptr [ZAX], 0);
ASM(skipManifestCode:);
ASM_NOP12();
HACKABLE_CODE_END();
ASM(pop ZAX);
ASM_POP_EFLAGS();
HACKABLES_STOP_SEARCH();
Buff::HackStateStorage[Buff::StateKeyDamageDealt] = Value(currentDamageDealt);
}
END_NO_OPTIMIZE
| 412 | 0.809443 | 1 | 0.809443 | game-dev | MEDIA | 0.939656 | game-dev | 0.759553 | 1 | 0.759553 |
fulpstation/fulpstation | 6,169 | code/modules/mob/living/navigation.dm | #define MAX_NAVIGATE_RANGE 125
/mob/living
/// Cooldown of the navigate() verb.
COOLDOWN_DECLARE(navigate_cooldown)
/client
/// Images of the path created by navigate().
var/list/navigation_images = list()
/mob/living/verb/navigate()
set name = "Navigate"
set category = "IC"
if(incapacitated)
return
if(length(client.navigation_images))
addtimer(CALLBACK(src, PROC_REF(cut_navigation)), world.tick_lag)
balloon_alert(src, "navigation path removed")
return
if(!COOLDOWN_FINISHED(src, navigate_cooldown))
balloon_alert(src, "navigation on cooldown!")
return
addtimer(CALLBACK(src, PROC_REF(create_navigation)), world.tick_lag)
/mob/living/proc/create_navigation()
var/can_go_down = SSmapping.level_trait(z, ZTRAIT_DOWN)
var/can_go_up = SSmapping.level_trait(z, ZTRAIT_UP)
var/list/destination_list = list()
for(var/atom/destination as anything in GLOB.navigate_destinations)
if(get_dist(destination, src) > MAX_NAVIGATE_RANGE)
continue
var/destination_name = GLOB.navigate_destinations[destination]
if(destination.z != z && (can_go_down || can_go_up)) // up or down is just a good indicator "we're on the station", we don't need to check specifics
destination_name += ((get_dir_multiz(src, destination) & UP) ? " (Above)" : " (Below)")
destination_list[destination_name] = destination
if(can_go_down)
destination_list["Nearest Way Down"] = DOWN
if(can_go_up)
destination_list["Nearest Way Up"] = UP
if(!length(destination_list))
balloon_alert(src, "no navigation signals!")
return
var/platform_code = tgui_input_list(src, "Select a location", "Navigate", sort_list(destination_list))
var/atom/navigate_target = destination_list[platform_code]
if(isnull(navigate_target) || incapacitated)
return
var/finding_zchange = FALSE
COOLDOWN_START(src, navigate_cooldown, 15 SECONDS)
if(navigate_target == UP || navigate_target == DOWN || (isatom(navigate_target) && navigate_target.z != z))
// lowering the cooldown to 5 seconds if we're navigating to a ladder or staircase instead of a proper destination
// (so we can decide to move to another destination right off the bat, rather than needing to wait)
COOLDOWN_START(src, navigate_cooldown, 5 SECONDS)
var/direction_name = isatom(navigate_target) ? "there" : (navigate_target == UP ? "up" : "down")
var/nav_dir = isatom(navigate_target) ? (get_dir_multiz(src, navigate_target) & (UP|DOWN)) : navigate_target
var/atom/new_target = find_nearest_stair_or_ladder(nav_dir)
if(!new_target)
balloon_alert(src, "can't find ladder or staircase going [direction_name]!")
return
navigate_target = new_target
finding_zchange = TRUE
if(!isatom(navigate_target))
stack_trace("Navigate target ([navigate_target]) is not an atom, somehow.")
return
var/list/path = get_path_to(src, navigate_target, MAX_NAVIGATE_RANGE, mintargetdist = 1, access = get_access(), skip_first = FALSE)
if(!length(path))
balloon_alert(src, "no valid path with current access!")
return
path |= get_turf(navigate_target)
for(var/i in 1 to length(path))
var/turf/current_turf = path[i]
var/image/path_image = image(icon = 'icons/effects/navigation.dmi', layer = HIGH_PIPE_LAYER, loc = current_turf)
SET_PLANE(path_image, GAME_PLANE, current_turf)
path_image.color = COLOR_CYAN
path_image.alpha = 0
var/dir_1 = 0
var/dir_2 = 0
if(i == 1)
dir_2 = REVERSE_DIR(angle2dir(get_angle(path[i+1], current_turf)))
else if(i == length(path))
dir_2 = REVERSE_DIR(angle2dir(get_angle(path[i-1], current_turf)))
else
dir_1 = REVERSE_DIR(angle2dir(get_angle(path[i+1], current_turf)))
dir_2 = REVERSE_DIR(angle2dir(get_angle(path[i-1], current_turf)))
if(dir_1 > dir_2)
dir_1 = dir_2
dir_2 = REVERSE_DIR(angle2dir(get_angle(path[i+1], current_turf)))
path_image.icon_state = "[dir_1]-[dir_2]"
client.images += path_image
client.navigation_images += path_image
animate(path_image, 0.5 SECONDS, alpha = 150)
addtimer(CALLBACK(src, PROC_REF(shine_navigation)), 0.5 SECONDS)
RegisterSignal(src, COMSIG_LIVING_DEATH, PROC_REF(cut_navigation))
if(finding_zchange)
RegisterSignal(src, COMSIG_MOVABLE_Z_CHANGED, PROC_REF(cut_navigation))
balloon_alert(src, "navigation path created")
/mob/living/proc/shine_navigation()
for(var/i in 1 to length(client.navigation_images))
if(!length(client.navigation_images))
return
animate(client.navigation_images[i], time = 1 SECONDS, loop = -1, alpha = 200, color = "#bbffff", easing = BACK_EASING | EASE_OUT)
animate(time = 2 SECONDS, loop = -1, alpha = 150, color = "#00ffff", easing = CUBIC_EASING | EASE_OUT)
stoplag(0.1 SECONDS)
/mob/living/proc/cut_navigation()
SIGNAL_HANDLER
for(var/image/navigation_path in client.navigation_images)
client.images -= navigation_path
client.navigation_images.Cut()
UnregisterSignal(src, list(COMSIG_LIVING_DEATH, COMSIG_MOVABLE_Z_CHANGED))
/**
* Finds nearest ladder or staircase either up or down.
*
* Arguments:
* * direction - UP or DOWN.
*/
/mob/living/proc/find_nearest_stair_or_ladder(direction)
if(!direction)
return
if(direction != UP && direction != DOWN)
return
var/target
for(var/obj/structure/ladder/lad in GLOB.ladders)
if(lad.z != z)
continue
if(direction == UP && !lad.up)
continue
if(direction == DOWN && !lad.down)
continue
if(!target)
target = lad
continue
if(get_dist_euclidean(lad, src) > get_dist_euclidean(target, src))
continue
target = lad
for(var/obj/structure/stairs/stairs_bro in GLOB.stairs)
if(direction == UP && stairs_bro.z != z) //if we're going up, we need to find stairs on our z level
continue
if(direction == DOWN && stairs_bro.z != z - 1) //if we're going down, we need to find stairs on the z level beneath us
continue
if(!target)
target = stairs_bro.z == z ? stairs_bro : get_step_multiz(stairs_bro, UP) //if the stairs aren't on our z level, get the turf above them (on our zlevel) to path to instead
continue
if(get_dist_euclidean(stairs_bro, src) > get_dist_euclidean(target, src))
continue
target = stairs_bro.z == z ? stairs_bro : get_step_multiz(stairs_bro, UP)
return target
#undef MAX_NAVIGATE_RANGE
| 412 | 0.940226 | 1 | 0.940226 | game-dev | MEDIA | 0.925542 | game-dev | 0.991142 | 1 | 0.991142 |
sillsdev/FieldWorks | 5,550 | Src/views/lib/ActionHandler.h | /*-----------------------------------------------------------------------*//*:Ignore in Surveyor
Copyright (c) 1999-2013 SIL International
This software is licensed under the LGPL, version 2.1 or later
(http://www.gnu.org/licenses/lgpl-2.1.html)
File: ActionHandler.h
Responsibility: John Thomson
Last reviewed: never
Description:
This file contains class declarations for the ActionHandler class.
-------------------------------------------------------------------------------*//*:End Ignore*/
#pragma once
#ifndef ActionHandler_INCLUDED
#define ActionHandler_INCLUDED
class ActionHandler;
/*----------------------------------------------------------------------------------------------
Cross-Reference: ${IActionHandler}
@h3{Hungarian: acth}
----------------------------------------------------------------------------------------------*/
class ActionHandler : public IActionHandler
{
public:
ActionHandler();
~ActionHandler();
STDMETHOD_(UCOMINT32, AddRef)(void);
static void CreateCom(IUnknown * punkCtl, REFIID riid, void ** ppv);
STDMETHOD(QueryInterface)(REFIID iid, void ** ppv);
STDMETHOD_(UCOMINT32, Release)(void);
STDMETHOD(BeginUndoTask)(BSTR bstrUndo, BSTR bstrRedo);
STDMETHOD(EndUndoTask)();
STDMETHOD(ContinueUndoTask)();
STDMETHOD(EndOuterUndoTask)();
STDMETHOD(BreakUndoTask)(BSTR bstrUndo, BSTR bstrRedo);
STDMETHOD(BeginNonUndoableTask)();
STDMETHOD(EndNonUndoableTask)();
STDMETHOD(StartSeq)(BSTR bstrUndo, BSTR bstrRedo, IUndoAction * puact);
STDMETHOD(GetUndoText)(BSTR * pbstrUndo);
STDMETHOD(GetUndoTextN)(int iAct, BSTR * pbstrUndo);
STDMETHOD(GetRedoText)(BSTR * pbstrRedo);
STDMETHOD(GetRedoTextN)(int iAct, BSTR * pbstrRedo);
STDMETHOD(AddAction)(IUndoAction * puact);
STDMETHOD(CanUndo)(ComBool * pfCanUndo);
STDMETHOD(CanRedo)(ComBool * pfCanRedo);
STDMETHOD(Undo)(UndoResult * pures);
STDMETHOD(Redo)(UndoResult * pures);
STDMETHOD(CreateMarkIfNeeded)(ComBool fCreateMark);
STDMETHOD(Rollback)(int nDepth);
STDMETHOD(get_CurrentDepth)(int * pnDepth);
STDMETHOD(Commit)();
STDMETHOD(Close)();
STDMETHOD(Mark)(int * phMark);
STDMETHOD(CollapseToMark)(int hMark, BSTR bstrUndo, BSTR bstrRedo, ComBool * pf);
STDMETHOD(DiscardToMark)(int hMark);
STDMETHOD(get_TopMarkHandle)(int * phMark);
STDMETHOD(get_TasksSinceMark)(ComBool fUndo, ComBool * pf);
STDMETHOD(get_UndoableActionCount)(int * pcAct);
STDMETHOD(get_UndoableSequenceCount)(int * pcAct);
STDMETHOD(get_RedoableSequenceCount)(int * pcAct);
STDMETHOD(get_IsUndoOrRedoInProgress)(ComBool * pfInProgress);
STDMETHOD(get_SuppressSelections)(ComBool * pfSupressSel);
protected:
int m_cref;
// Depth of nesting of the tasks.
int m_nDepth;
// Labels for next task.
StrUni m_stuNextUndo;
StrUni m_stuNextRedo;
// True if we have done at least one BeginUndoTask but have not yet put any undo-actions
// on the stack.
// JT: This flag is set in BeginUndoTask. It's real purpose is so we can postpone
// recording the start of a new action sequence (done in CleanupRedoActions, believe
// it or not) until there is at least one action to put in the sequence. Otherwise,
// we might unnecessarily clean out the Redo stack for a 'task' that turns out to
// have no substance.
bool m_fStartedNext;
// True to create a mark when you add an action, if there isn't one
// False otherwise
bool m_fCreateMarkIfNeeded;
// True if it currently makes sense to Continue the current task. Calling Undo or Redo
// definitely means this is not sensible, so a ContinueUndoTask following one of these
// gets converted into an independent task.
bool m_fCanContinueTask;
// True if an action was added to the current task that changed the data.
bool m_fDataChangeAction;
// Index to the current action in the action vector m_vquact, ie, the most recent action
// added and/or the next action to undo.
int m_iuactCurr;
// Vector of actions.
Vector<IUndoActionPtr> m_vquact;
// Index to the current action sequence given in the vector m_viSeqStart.
// JT: This is the sequence that will be Undone if the user currently selects Undo.
// It is initialized to -1, a state that indicates there is currently nothing that
// can be undone.
// It is also the sequence that will be added to by new actions.
int m_iCurrSeq;
// Vector of action sequences.
// JT: I gather each item is an index into m_vquact, of the first action in a given
// sequence (where a sequence is defined as the stuff from one outer BeginUndoTask
// to the corresponding EndUndoTask, that is, typically what seems to the user like
// a single indivisible undoable action). Some of these sequences may be currently
// in the 'undone' state.
Vector<int> m_viSeqStart;
// Undo text that goes with the action sequence.
Vector<StrUni> m_vstuUndo;
// Redo text that goes with the action sequence.
Vector<StrUni> m_vstuRedo;
// For marking the stack with a range of temporary undo-tasks that are private to a
// data-entry field editor (AfDeFieldEditor).
Vector<int> m_viMarks;
// True for the duration of an Undo/Redo operation. Used to suppress
// recording any new actions.
bool m_fUndoOrRedoInProgress;
// private methods:
void AddActionAux(IUndoAction * puact);
void CleanUpRedoActions(bool fForce);
void CleanUpEmptyTasks();
void EmptyStack();
void CleanUpMarks();
HRESULT CallUndo(UndoResult * pures, bool & fRedoable, bool fForDataChange);
HRESULT CallRedo(UndoResult * pures, bool fForDataChange, int iSeqToRedo, int iLastRedoAct);
};
DEFINE_COM_PTR(ActionHandler);
#endif // ActionHandler_INCLUDED
| 412 | 0.949628 | 1 | 0.949628 | game-dev | MEDIA | 0.456328 | game-dev | 0.955187 | 1 | 0.955187 |
JDKDigital/productive-bees | 2,572 | src/main/java/cy/jdkdigital/productivebees/common/block/CryoStasis.java | package cy.jdkdigital.productivebees.common.block;
import com.mojang.serialization.MapCodec;
import cy.jdkdigital.productivebees.common.block.entity.CryoStasisBlockEntity;
import cy.jdkdigital.productivebees.init.ModBlockEntityTypes;
import cy.jdkdigital.productivelib.common.block.CapabilityContainerBlock;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BaseEntityBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.HorizontalDirectionalBlock;
import net.minecraft.world.level.block.RenderShape;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class CryoStasis extends CapabilityContainerBlock
{
public static final MapCodec<CryoStasis> CODEC = simpleCodec(CryoStasis::new);
public CryoStasis(Properties properties) {
super(properties);
this.registerDefaultState(this.defaultBlockState().setValue(HorizontalDirectionalBlock.FACING, Direction.NORTH));
}
@Override
protected MapCodec<? extends BaseEntityBlock> codec() {
return CODEC;
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(HorizontalDirectionalBlock.FACING);
}
@Override
public BlockState getStateForPlacement(BlockPlaceContext context) {
return this.defaultBlockState().setValue(HorizontalDirectionalBlock.FACING, context.getHorizontalDirection().getOpposite());
}
@Nullable
@Override
public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState state, BlockEntityType<T> blockEntityType) {
return level.isClientSide ? null : createTickerHelper(blockEntityType, ModBlockEntityTypes.CRYO_STASIS.get(), CryoStasisBlockEntity::tick);
}
@SuppressWarnings("deprecation")
@Nonnull
@Override
public RenderShape getRenderShape(BlockState state) {
return RenderShape.MODEL;
}
@Nullable
@Override
public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
return new CryoStasisBlockEntity(pos, state);
}
} | 412 | 0.574 | 1 | 0.574 | game-dev | MEDIA | 0.996498 | game-dev | 0.7658 | 1 | 0.7658 |
jaamsim/jaamsim | 7,771 | src/main/java/com/jaamsim/JSON/JSONParser.java | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2022 JaamSim Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jaamsim.JSON;
import java.util.ArrayList;
import java.util.HashMap;
public class JSONParser {
public static boolean isSymTok(JSONTokenizer.Token tok, String sym) {
return tok.type == JSONTokenizer.SYM_TYPE && tok.value.equals(sym);
}
public static boolean isStringTok(JSONTokenizer.Token tok) {
return tok.type == JSONTokenizer.STRING_TYPE;
}
private static int parseMap(ArrayList<JSONTokenizer.Token> toks, int startPos, JSONValue outVal) throws JSONError {
// Consume the opening token
int pos = startPos;
JSONTokenizer.Token tok = toks.get(pos);
HashMap<String, JSONValue> vals = new HashMap<>();
// special case: empty list
if (isSymTok(tok, "}")) {
// This map has terminated
outVal.mapVal = vals;
return pos+1;
}
while(pos < toks.size()) {
if (!isStringTok(tok)) {
throw new JSONError(null, tok.pos, "Map keys must be strings");
}
String key = tok.value;
pos++;
tok = toks.get(pos);
if (!isSymTok(tok, ":")) {
throw new JSONError(null, tok.pos, "Expected \":\"");
}
pos++;
JSONValue val = new JSONValue();
pos = parseElement(toks, pos, val);
vals.put(key, val);
tok = toks.get(pos);
if (isSymTok(tok, "}")) {
// Terminated
outVal.mapVal = vals;
return pos+1;
}
if (isSymTok(tok, ",")) {
pos++;
tok = toks.get(pos);
continue;
}
throw new JSONError(null, tok.pos, "Unexpected symbol in map");
}
tok = toks.get(startPos);
throw new JSONError(null, tok.pos, "Unterminated list");
}
private static int parseList(ArrayList<JSONTokenizer.Token> toks, int startPos, JSONValue outVal) throws JSONError {
// Consume the opening token
int pos = startPos;
JSONTokenizer.Token tok = toks.get(pos);
ArrayList<JSONValue> vals = new ArrayList<>();
// special case: empty list
if (isSymTok(tok, "]")) {
// This list has terminated
outVal.listVal = vals;
return pos+1;
}
while(pos < toks.size()) {
JSONValue val = new JSONValue();
pos = parseElement(toks, pos, val);
vals.add(val);
tok = toks.get(pos);
if (isSymTok(tok, "]")) {
// Terminated
outVal.listVal = vals;
return pos+1;
}
if (isSymTok(tok, ",")) {
tok = toks.get(pos++);
continue;
}
throw new JSONError(null, tok.pos, "Unexpected symbol in list");
}
tok = toks.get(startPos);
throw new JSONError(null, tok.pos, "Unterminated list");
}
private static int parseElement(ArrayList<JSONTokenizer.Token> toks, int startPos, JSONValue outVal) throws JSONError {
int pos = startPos;
JSONTokenizer.Token startTok = toks.get(pos++);
switch(startTok.type) {
case JSONTokenizer.NUM_TYPE:
try {
outVal.numVal = Double.parseDouble(startTok.value);
return pos;
} catch(NumberFormatException ex) {
throw new JSONError(null, startTok.pos, "Number format error");
}
case JSONTokenizer.STRING_TYPE:
outVal.stringVal = startTok.value;
return pos;
case JSONTokenizer.SYM_TYPE:
switch(startTok.value) {
case "[":
return parseList(toks, pos, outVal);
case "{":
return parseMap(toks, pos, outVal);
default:
throw new JSONError(null, startTok.pos, "Unexpected token to start element");
}
case JSONTokenizer.KEYWORD_TYPE:
outVal.isKey = true;
if (startTok.value.equals("true")) {
outVal.numVal = JSONValue.TRUE_VAL;
}
if (startTok.value.equals("false")) {
outVal.numVal = JSONValue.FALSE_VAL;
}
if (startTok.value.equals("null")) {
outVal.numVal = JSONValue.NULL_VAL;
}
return pos;
default:
throw new JSONError(null, startTok.pos, "Internal error: Unknown token type");
}
}
public static JSONValue parse(ArrayList<JSONTokenizer.Token> toks) throws JSONError {
JSONValue ret = new JSONValue();
parseElement(toks, 0, ret);
return ret;
}
public static JSONValue parse(String json) throws JSONError {
ArrayList<JSONTokenizer.Token> toks = JSONTokenizer.tokenize(json);
return parse(toks);
}
ArrayList<String> pieces;
private boolean scannerInString = false;
private boolean scannerEscaping = false;
private int scannerPiece = 0;
//int scannerPos = 0;
private boolean firstElemFound = false;
private boolean topElemIsObj = false;
private boolean scannerError = false;
private int objDepth = 0;
private int arrayDepth = 0;
private boolean topElemIsComplete = false;
public JSONParser() {
pieces = new ArrayList<>();
}
public void addPiece(String piece) {
pieces.add(piece);
}
public boolean scanningError() {
return scannerError;
}
public boolean isObject() {
return topElemIsObj;
}
// Scan all the existing pieces and see if the current element is possibly complete
// The simple parser does not support partial elements. Attempting to parse incomplete data
// will return a parse error
public boolean isElementComplete() {
if (scannerError) return false;
if (topElemIsComplete) return true;
int piecePos = 0;
while(true) {
if (scannerPiece >= pieces.size()) {
break;
}
String curPiece = pieces.get(scannerPiece);
if (piecePos >= curPiece.length()) {
piecePos = 0;
scannerPiece++;
continue;
}
char scannedChar = curPiece.charAt(piecePos);
piecePos++;
if (scannerEscaping) {
// TODO: be more selecting of the escape logic
// All we currently care about is escaped quotes
scannerEscaping = false;
continue;
}
if (scannerInString) {
if (scannedChar == '\\') {
scannerEscaping = true;
continue;
}
if (scannedChar == '"') {
scannerInString = false;
continue;
}
continue;
}
// Not in a string
if (scannedChar == '"') {
scannerInString = true;
continue;
}
if (scannedChar == '{') {
if (!firstElemFound) {
firstElemFound = true;
topElemIsObj = true;
}
objDepth++;
continue;
}
if (scannedChar == '}') {
if (objDepth <= 0) {
scannerError = true;
return false;
}
objDepth--;
continue;
}
if (scannedChar == '[') {
if (!firstElemFound) {
firstElemFound = true;
topElemIsObj = false;
}
arrayDepth++;
continue;
}
if (scannedChar == ']') {
if (arrayDepth <= 0) {
scannerError = true;
return false;
}
arrayDepth--;
continue;
}
}
if (objDepth == 0 && arrayDepth == 0 && firstElemFound) {
topElemIsComplete = true;
return true;
}
return false;
}
public JSONValue parse() throws JSONError {
// Build up a single string (this is not super efficient...)
StringBuilder sb = new StringBuilder();
for (String s: pieces) {
sb.append(s);
}
String source = sb.toString();
// Scan the listed pieces
boolean isComp = isElementComplete();
if (scannerError) {
// The preliminary scanner detected a parse error
throw new JSONError(source, -1, "Mismatched brackets detected");
}
if (!isComp) {
// This element is not yet complete
throw new JSONError(source, source.length(), "Incomplete JSON element");
}
ArrayList<JSONTokenizer.Token> toks = JSONTokenizer.tokenize(source);
return JSONParser.parse(toks);
}
}
| 412 | 0.839423 | 1 | 0.839423 | game-dev | MEDIA | 0.133635 | game-dev | 0.912599 | 1 | 0.912599 |
strk/gnash | 18,685 | plugin/aos4/plugin.cpp | // plugin.cpp: Windows "win32" flash player Mozilla plugin, for Gnash.
//
// Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
// Free Software Foundation, Inc
//
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
#ifdef HAVE_CONFIG_H
#include "gnashconfig.h"
#endif
#include <proto/intuition.h>
#include <proto/Picasso96API.h>
#include <proto/exec.h>
#include <cstdlib>
#define FLASH_MAJOR_VERSION "9"
#define FLASH_MINOR_VERSION "0"
#define FLASH_REV_NUMBER "82"
#define MIME_TYPES_HANDLED "application/x-shockwave-flash"
// The name must be this value to get flash movies that check the
// plugin version to load.
#define PLUGIN_NAME "Shockwave Flash"
#define MIME_TYPES_DESCRIPTION MIME_TYPES_HANDLED":swf:"PLUGIN_NAME
// Some javascript plugin detectors use the description
// to decide the flash version to display. They expect the
// form (major version).(minor version) r(revision).
// e.g. "8.0 r99."
#ifndef FLASH_MAJOR_VERSION
#define FLASH_MAJOR_VERSION DEFAULT_FLASH_MAJOR_VERSION
#endif
#ifndef FLASH_MINOR_VERSION
#define FLASH_MINOR_VERSION DEFAULT_FLASH_MINOR_VERSION
#endif
#ifndef FLASH_REV_NUMBER
#define FLASH_REV_NUMBER DEFAULT_FLASH_REV_NUMBER
#endif
#define FLASH_VERSION FLASH_MAJOR_VERSION"."\
FLASH_MINOR_VERSION" r"FLASH_REV_NUMBER"."
#define PLUGIN_DESCRIPTION \
"Shockwave Flash "FLASH_VERSION" Gnash "VERSION", the GNU SWF Player. \
Copyright © 2006, 2007, 2008 \
<a href=\"http://www.fsf.org\">Free Software Foundation</a>, Inc.<br> \
Gnash comes with NO WARRANTY, to the extent permitted by law. \
You may redistribute copies of Gnash under the terms of the \
<a href=\"http://www.gnu.org/licenses/gpl.html\">GNU General Public \
License</a>. For more information about Gnash, see <a \
href=\"http://www.gnu.org/software/gnash/\"> \
http://www.gnu.org/software/gnash</a>. \
Compatible Shockwave Flash "FLASH_VERSION
#include <cstdarg>
#include <cstdint>
#include <fstream>
#include "plugin.h"
static int module_initialized = FALSE;
static PRLock* playerLock = NULL;
static int instances = 0;
#ifdef NPAPI_CONST
const
#endif
char* NPP_GetMIMEDescription(void);
static void playerThread(void *arg);
//static LRESULT CALLBACK PluginWinProc(HWND, UINT, WPARAM, LPARAM);
#define DBG(x, ...) __DBG(x, ## __VA_ARGS__)
inline void
__DBG(const char *fmt, ...)
{
char buf[1024];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
va_end(ap);
printf(buf);
}
// general initialization and shutdown
NPError
NS_PluginInitialize(void)
{
DBG("NS_PluginInitialize\n");
if (!playerLock) {
playerLock = PR_NewLock();
}
module_initialized = TRUE;
return NPERR_NO_ERROR;
}
void
NS_PluginShutdown(void)
{
DBG("NS_PluginShutdown\n");
if (!module_initialized) return;
if (playerLock) {
PR_DestroyLock(playerLock);
playerLock = NULL;
}
}
/// \brief Return the MIME Type description for this plugin.
#ifdef NPAPI_CONST
const
#endif
char*
NPP_GetMIMEDescription(void)
{
if (!module_initialized) return NULL;
return MIME_TYPES_HANDLED;
}
#if 0
/// \brief Retrieve values from the plugin for the Browser
///
/// This C++ function is called by the browser to get certain
/// information is needs from the plugin. This information is the
/// plugin name, a description, etc...
///
/// This is actually not used on Win32 (XP_WIN), only on Unix (XP_UNIX).
NPError
NS_PluginGetValue(NPPVariable aVariable, void *aValue)
{
NPError err = NPERR_NO_ERROR;
if (!module_initialized) return NPERR_NO_ERROR;
DBG("aVariable = %d\n", aVariable);
switch (aVariable) {
case NPPVpluginNameString:
*static_cast<char **> (aValue) = PLUGIN_NAME;
break;
// This becomes the description field you see below the opening
// text when you type about:plugins and in
// navigator.plugins["Shockwave Flash"].description, used in
// many flash version detection scripts.
case NPPVpluginDescriptionString:
*static_cast<const char **>(aValue) = PLUGIN_DESCRIPTION;
break;
case NPPVpluginNeedsXEmbed:
#ifdef HAVE_GTK2
*static_cast<PRBool *>(aValue) = PR_TRUE;
#else
*static_cast<PRBool *>(aValue) = PR_FALSE;
#endif
break;
case NPPVpluginTimerInterval:
case NPPVpluginKeepLibraryInMemory:
default:
err = NPERR_INVALID_PARAM;
break;
}
return err;
}
#endif
// construction and destruction of our plugin instance object
nsPluginInstanceBase*
NS_NewPluginInstance(nsPluginCreateData* aCreateDataStruct)
{
DBG("NS_NewPluginInstance\n");
if (!module_initialized) return NULL;
if (instances > 0) {
return NULL;
}
instances++; // N.B. This is a threading race condition. FIXME.
if (!playerLock) {
playerLock = PR_NewLock();
}
if (!aCreateDataStruct) {
return NULL;
}
return new nsPluginInstance(aCreateDataStruct);
}
void
NS_DestroyPluginInstance(nsPluginInstanceBase* aPlugin)
{
DBG("NS_DestroyPluginInstance\n");
if (!module_initialized) return;
if (aPlugin) {
delete (nsPluginInstance *) aPlugin;
}
if (playerLock) {
PR_DestroyLock(playerLock);
playerLock = NULL;
}
instances--;
}
// nsPluginInstance class implementation
/// \brief Constructor
nsPluginInstance::nsPluginInstance(nsPluginCreateData* data) :
nsPluginInstanceBase(),
_instance(data->instance),
_window(NULL),
_initialized(FALSE),
_shutdown(FALSE),
_stream(NULL),
_url(""),
_thread(NULL),
_width(0),
_height(0),
_rowstride(0),
_hMemDC(NULL),
_bmp(NULL),
_memaddr(NULL),
mouse_x(0),
mouse_y(0),
mouse_buttons(0),
_oldWndProc(NULL)
{
DBG("nsPluginInstance::nsPluginInstance\n");
}
/// \brief Destructor
nsPluginInstance::~nsPluginInstance()
{
DBG("nsPluginInstance::~nsPluginInstance\n");
if (_memaddr) {
// Deleting _bmp should free this memory.
_memaddr = NULL;
}
if (_hMemDC) {
//DeleteObject(_hMemDC);
IExec->FreeVec(_hMemDC);
_hMemDC = NULL;
}
if (_bmp) {
//DeleteObject(_bmp);
IP96->p96FreeBitMap(_bmp);
_bmp = NULL;
}
}
NPBool
nsPluginInstance::init(NPWindow* aWindow)
{
DBG("nsPluginInstance::init\n");
if (!aWindow) {
DBG("aWindow == NULL\n");
return FALSE;
}
_x = aWindow->x;
_y = aWindow->y;
_width = aWindow->width;
_height = aWindow->height;
_window = (struct Window *) aWindow->window;
// Windows DIB row stride is always a multiple of 4 bytes.
_rowstride = /* 24 bits */ 3 * _width;
_rowstride += _rowstride % 4;
/*
memset(&_bmpInfo, 0, sizeof(BITMAPINFOHEADER));
_bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
_bmpInfo.bmiHeader.biWidth = _width;
// Negative height means first row comes first in memory.
_bmpInfo.bmiHeader.biHeight = -1 * _height;
_bmpInfo.bmiHeader.biPlanes = 1;
_bmpInfo.bmiHeader.biBitCount = 24;
_bmpInfo.bmiHeader.biCompression = BI_RGB;
_bmpInfo.bmiHeader.biSizeImage = 0;
_bmpInfo.bmiHeader.biXPelsPerMeter = 0;
_bmpInfo.bmiHeader.biYPelsPerMeter = 0;
_bmpInfo.bmiHeader.biClrUsed = 0;
_bmpInfo.bmiHeader.biClrImportant = 0;
HDC hDC = GetDC(_window);
_hMemDC = CreateCompatibleDC(hDC);
_bmp = CreateDIBSection(_hMemDC, &_bmpInfo,
DIB_RGB_COLORS, (void **) &_memaddr, 0, 0);
SelectObject(_hMemDC, _bmp);
*/
_bmp = IP96->p96AllocBitMap(_width, _height, 24, BMF_MINPLANES | BMF_DISPLAYABLE,((struct Window *)aWindow)->RPort->BitMap, (RGBFTYPE)0);
DBG("aWindow->type: %s (%u)\n",
(aWindow->type == NPWindowTypeWindow) ? "NPWindowTypeWindow" :
(aWindow->type == NPWindowTypeDrawable) ? "NPWindowTypeDrawable" :
"unknown",
aWindow->type);
// subclass window so we can intercept window messages and
// do our drawing to it
//_oldWndProc = SubclassWindow(_window, (WNDPROC) PluginWinProc);
// associate window with our nsPluginInstance object so we can access
// it in the window procedure
//SetWindowLong(_window, GWL_USERDATA, (LONG) this);
_initialized = TRUE;
return TRUE;
}
void
nsPluginInstance::shut(void)
{
DBG("nsPluginInstance::shut\n");
DBG("Acquiring playerLock mutex for shutdown.\n");
PR_Lock(playerLock);
_shutdown = TRUE;
DBG("Releasing playerLock mutex for shutdown.\n");
PR_Unlock(playerLock);
if (_thread) {
DBG("Waiting for thread to terminate.\n");
PR_JoinThread(_thread);
_thread = NULL;
}
// subclass it back
//SubclassWindow(_window, _oldWndProc);
_initialized = FALSE;
}
NPError
nsPluginInstance::NewStream(NPMIMEType type, NPStream *stream,
NPBool seekable, std::uint16_t *stype)
{
DBG("nsPluginInstance::NewStream\n");
DBG("stream->url: %s\n", stream->url);
if (!_stream) {
_stream = stream;
_url = stream->url;
#if 0
if (seekable) {
*stype = NP_SEEK;
}
#endif
}
return NPERR_NO_ERROR;
}
NPError
nsPluginInstance::DestroyStream(NPStream *stream, NPError reason)
{
DBG("nsPluginInstance::DestroyStream\n");
DBG("stream->url: %s\n", stream->url);
// N.B. We can only support one Gnash VM/thread right now.
if (!_thread) {
_thread = PR_CreateThread(PR_USER_THREAD, playerThread, this,
PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0);
}
return NPERR_NO_ERROR;
}
int32
nsPluginInstance::Write(NPStream *stream, int32 offset, int32 len,
void *buffer)
{
DBG("nsPluginInstance::Write\n");
DBG("stream->url: %s, offset: %ld, len: %ld\n",
stream->url, offset, len);
}
static void
playerThread(void *arg)
{
nsPluginInstance *plugin = (nsPluginInstance *) arg;
plugin->threadMain();
}
void
nsPluginInstance::threadMain(void)
{
DBG("nsPluginInstance::threadMain started\n");
DBG("URL: %s\n", _url.c_str());
PR_Lock(playerLock);
// Initialize Gnash core library.
DBG("Gnash core initialized.\n");
// Init logfile.
gnash::RcInitFile& rcinit = gnash::RcInitFile::getDefaultInstance();
std::string logfilename = std::string("T:npgnash.log");
rcinit.setDebugLog(logfilename);
gnash::LogFile& dbglogfile = gnash::LogFile::getDefaultInstance();
dbglogfile.setWriteDisk(true);
dbglogfile.setVerbosity(GNASH_DEBUG_LEVEL);
DBG("Gnash logging initialized: %s\n", logfilename.c_str());
// Init sound.
//_sound_handler.reset(gnash::sound::create_sound_handler_sdl());
//gnash::set_sound_handler(_sound_handler.get());
DBG("Gnash sound initialized.\n");
// Init GUI.
int old_mouse_x = 0, old_mouse_y = 0, old_mouse_buttons = 0;
_render_handler =
(gnash::render_handler *) gnash::create_render_handler_agg("BGR24");
// _memaddr = (unsigned char *) malloc(getMemSize());
static_cast<gnash::render_handler_agg_base *>(_render_handler)->init_buffer(
getMemAddr(), getMemSize(), _width, _height, _rowstride);
gnash::set_render_handler(_render_handler);
DBG("Gnash GUI initialized: %ux%u\n", _width, _height);
gnash::URL url(_url);
VariableMap vars;
gnash::URL::parse_querystring(url.querystring(), vars);
for (VariableMap::iterator i = vars.begin(), ie = vars.end(); i != ie; ++i) {
_flashVars[i->first] = i->second;
}
gnash::set_base_url(url);
gnash::movie_definition* md = NULL;
try {
md = gnash::createMovie(url, _url.c_str(), false);
} catch (const gnash::GnashException& err) {
md = NULL;
}
if (!md) {
/*
* N.B. Can't use the goto here, as C++ complains about "jump to
* label 'done' from here crosses initialization of ..." a bunch
* of things. Sigh. So, instead, I duplicate the cleanup code
* here. TODO: Remove this duplication.
*/
// goto done;
PR_Unlock(playerLock);
DBG("Clean up Gnash.\n");
//gnash::clear();
DBG("nsPluginInstance::threadMain exiting\n");
return;
}
DBG("Movie created: %s\n", _url.c_str());
int movie_width = static_cast<int>(md->get_width_pixels());
int movie_height = static_cast<int>(md->get_height_pixels());
float movie_fps = md->get_frame_rate();
DBG("Movie dimensions: %ux%u (%.2f fps)\n",
movie_width, movie_height, movie_fps);
gnash::SystemClock clock; // use system clock here...
gnash::movie_root& root = gnash::VM::init(*md, clock).getRoot();
DBG("Gnash VM initialized.\n");
// Register this plugin as listener for FsCommands from the core
// (movie_root)
#if 0
/* Commenting out for now as registerFSCommandCallback() has changed. */
root.registerFSCommandCallback(FSCommand_callback);
#endif
// Register a static function to handle ActionScript events such
// as Mouse.hide, Stage.align etc.
// root.registerEventCallback(&staticEventHandlingFunction);
md->completeLoad();
DBG("Movie loaded.\n");
std::unique_ptr<gnash::Movie> mr(md->createMovie());
mr->setVariables(_flashVars);
root.setRootMovie(mr.release());
//root.set_display_viewport(0, 0, _width, _height);
root.set_background_alpha(1.0f);
gnash::Movie* mi = root.getRootMovie();
DBG("Movie instance created.\n");
//ShowWindow(_window, SW_SHOW);
IIntuition->ShowWindow(_window,NULL);
for (;;) {
// DBG("Inside main thread loop.\n");
if (_shutdown) {
DBG("Main thread shutting down.\n");
break;
}
size_t cur_frame = mi->get_current_frame();
// DBG("Got current frame number: %d.\n", cur_frame);
size_t tot_frames = mi->get_frame_count();
// DBG("Got total frame count: %d.\n", tot_frames);
// DBG("Advancing one frame.\n");
root.advance();
// DBG("Going to next frame.\n");
root.goto_frame(cur_frame + 1);
// DBG("Ensuring frame is loaded.\n");
//root.get_movie_definition()->ensure_frame_loaded(tot_frames);
// DBG("Setting play state to PLAY.\n");
root.set_play_state(gnash::MovieClip::PLAYSTATE_PLAY);
if (old_mouse_x != mouse_x || old_mouse_y != mouse_y) {
old_mouse_x = mouse_x;
old_mouse_y = mouse_y;
//root.notify_mouse_moved(mouse_x, mouse_y);
}
if (old_mouse_buttons != mouse_buttons) {
old_mouse_buttons = mouse_buttons;
int mask = 1;
//root.notify_mouse_clicked(mouse_buttons > 0, mask);
}
root.display();
#if 0
RECT rt;
GetClientRect(_window, &rt);
InvalidateRect(_window, &rt, FALSE);
InvalidatedRanges ranges;
ranges.setSnapFactor(1.3f);
ranges.setSingleMode(false);
root.add_invalidated_bounds(ranges, false);
ranges.growBy(40.0f);
ranges.combine_ranges();
if (!ranges.isNull()) {
InvalidateRect(_window, &rt, FALSE);
}
root.display();
#endif
// DBG("Unlocking playerLock mutex.\n");
PR_Unlock(playerLock);
// DBG("Sleeping.\n");
PR_Sleep(PR_INTERVAL_MIN);
// DBG("Acquiring playerLock mutex.\n");
PR_Lock(playerLock);
}
done:
PR_Unlock(playerLock);
DBG("Clean up Gnash.\n");
/*
* N.B. As per server/impl.cpp:clear(), all of Gnash's threads aren't
* guaranteed to be terminated by this, yet. Therefore, when Firefox
* unloads npgnash.dll after calling NS_PluginShutdown(), and there are
* still Gnash threads running, they will try and access memory that was
* freed as part of the unloading of npgnash.dll, resulting in a process
* abend.
*/
//gnash::clear();
DBG("nsPluginInstance::threadMain exiting\n");
}
const char*
nsPluginInstance::getVersion()
{
return NPN_UserAgent(_instance);
}
void
nsPluginInstance::FSCommand_callback(gnash::MovieClip* movie, const std::string& command, const std::string& args)
// For handling notification callbacks from ActionScript.
{
gnash::log_debug(_("FSCommand_callback(%p): %s %s"), (void*) movie, command, args);
}
/*
static LRESULT CALLBACK
PluginWinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// get our plugin instance object
nsPluginInstance *plugin =
(nsPluginInstance *) GetWindowLong(hWnd, GWL_USERDATA);
if (plugin) {
switch (msg) {
case WM_PAINT:
{
if (plugin->getMemAddr() == NULL) {
break;
}
PAINTSTRUCT ps;
HDC hDC = BeginPaint(hWnd, &ps);
RECT rt;
GetClientRect(hWnd, &rt);
int w = rt.right - rt.left;
int h = rt.bottom - rt.top;
BitBlt(hDC, rt.left, rt.top, w, h,
plugin->getMemDC(), 0, 0, SRCCOPY);
EndPaint(hWnd, &ps);
return 0L;
}
case WM_MOUSEMOVE:
{
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
plugin->notify_mouse_state(x, y, -1);
break;
}
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
{
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
int buttons = (msg == WM_LBUTTONDOWN) ? 1 : 0;
plugin->notify_mouse_state(x, y, buttons);
break;
}
default:
// dbglogfile << "msg " << msg << endl;
break;
}
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
*/
| 412 | 0.962997 | 1 | 0.962997 | game-dev | MEDIA | 0.195995 | game-dev | 0.93914 | 1 | 0.93914 |
pranavbalu1/AbyssUnity | 2,540 | Assets/Scripts/Item/InventoryManager.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InventoryManager : MonoBehaviour
{
[SerializeField] private GameObject slotHolder;
[SerializeField] private GameObject slotSelector;
[SerializeField] private int selectedSlotIndex = 0;
public ItemClass selectedItem;
public List<ItemClass> inventory = new(4);
private GameObject[] slots;
public void Start()
{
slots = new GameObject[slotHolder.transform.childCount];
for (int i = 0; i < slotHolder.transform.childCount; i++)
{
slots[i] = slotHolder.transform.GetChild(i).gameObject;
}
RefreshUI();
}
public void Update()
{
//scroll wheel to select slot
if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
selectedSlotIndex--;
if (selectedSlotIndex < 0)
{
selectedSlotIndex = slots.Length - 1;
}
}
else if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
selectedSlotIndex++;
if (selectedSlotIndex >= slots.Length)
{
selectedSlotIndex = 0;
}
}
//1 through 4 to select slot
if (Input.GetKeyDown(KeyCode.Alpha1))
{
selectedSlotIndex = 0;
}
else if (Input.GetKeyDown(KeyCode.Alpha2))
{
selectedSlotIndex = 1;
}
else if (Input.GetKeyDown(KeyCode.Alpha3))
{
selectedSlotIndex = 2;
}
else if (Input.GetKeyDown(KeyCode.Alpha4))
{
selectedSlotIndex = 3;
}
slotSelector.transform.position = slots[selectedSlotIndex].transform.position;
}
public void RefreshUI()
{
for (int i = 0; i < slots.Length; i++)
{
try
{
slots[i].transform.GetChild(0).GetComponent<Image>().sprite = inventory[i].item_icon;
}
catch
{
slots[i].transform.GetChild(0).GetComponent<Image>().sprite = null;
slots[i].transform.GetChild(0).GetComponent<Image>().enabled = false;
}
}
}
public void AddItem(ItemClass item)
{
inventory.Add(item);
RefreshUI();
}
public void RemoveItem(ItemClass item)
{
inventory.Remove(item);
RefreshUI();
}
public ItemClass GetSelectedItem => inventory[selectedSlotIndex];
}
| 412 | 0.84957 | 1 | 0.84957 | game-dev | MEDIA | 0.957288 | game-dev | 0.944335 | 1 | 0.944335 |
Auxilor/EcoEnchants | 12,752 | eco-core/core-plugin/src/main/kotlin/com/willfp/ecoenchants/mechanics/AnvilSupport.kt | package com.willfp.ecoenchants.mechanics
import com.willfp.eco.core.EcoPlugin
import com.willfp.eco.core.fast.fast
import com.willfp.eco.core.proxy.ProxyConstants
import com.willfp.eco.util.StringUtils
import com.willfp.ecoenchants.enchant.EcoEnchants
import com.willfp.ecoenchants.enchant.wrap
import org.bukkit.Material
import org.bukkit.Tag
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.inventory.PrepareAnvilEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.Damageable
import org.bukkit.inventory.meta.EnchantmentStorageMeta
import java.util.UUID
import kotlin.math.abs
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
import kotlin.math.roundToInt
data class AnvilResult(
val result: ItemStack?,
val xp: Int?
)
fun Int.infiniteIfNegative() = if (this < 1) Int.MAX_VALUE else this
private val FAIL = AnvilResult(null, null)
interface OpenInventoryProxy {
fun getOpenInventory(player: Player): Any
}
class AnvilSupport(
private val plugin: EcoPlugin
) : Listener {
/**
* Map to prevent incrementing cost several times as inventory events are fired 3 times.
*/
private val antiRepeat = mutableSetOf<UUID>()
/**
* Class for AnvilGUI wrappers to ignore them.
*/
private val anvilGuiClass = "net.wesjd.anvilgui.version.Wrapper" +
ProxyConstants.NMS_VERSION.substring(1) +
"\$AnvilContainer"
@EventHandler(priority = EventPriority.HIGHEST)
fun onAnvilPrepare(event: PrepareAnvilEvent) {
val player = event.viewers.getOrNull(0) as? Player ?: return
val permanenceCurse = EcoEnchants.getByID("permanence_curse")
val leftItem = event.inventory.getItem(0)
val rightItem = event.inventory.getItem(1)
if (permanenceCurse != null) {
if ((leftItem != null && leftItem.fast().getEnchants(true).containsKey(permanenceCurse.enchantment)) ||
(rightItem != null && rightItem.fast().getEnchants(true).containsKey(permanenceCurse.enchantment))
) {
event.result = null
event.inventory.setItem(2, null)
return
}
}
if (this.plugin.getProxy(OpenInventoryProxy::class.java)
.getOpenInventory(player)::class.java.toString() == anvilGuiClass
) {
return
}
if (antiRepeat.contains(player.uniqueId)) {
return
}
antiRepeat.add(player.uniqueId)
this.plugin.scheduler.run {
antiRepeat.remove(player.uniqueId)
val left = event.inventory.getItem(0)?.clone()
val old = left?.clone()
val right = event.inventory.getItem(1)?.clone()
event.result = null
event.inventory.setItem(2, null)
val result = doMerge(
left,
right,
@Suppress("REMOVAL", "DEPRECATION")
event.inventory.renameText ?: "",
player
)
val price = result.xp ?: 0
val outItem = result.result ?: ItemStack(Material.AIR)
@Suppress("REMOVAL", "DEPRECATION")
val oldCost = event.inventory.repairCost
val oldLeft = event.inventory.getItem(0)
if (result == FAIL) {
return@run
}
if (oldLeft == null || oldLeft.type != outItem.type) {
return@run
}
if (left == old) {
return@run
}
var cost = oldCost + price
// Unbelievably specific edge case
if (oldCost == -price) {
cost = price
}
// Cost could be less than zero at times, so I include that here.
if (cost <= 0) {
return@run
}
/*
Transplanted anti-dupe bodge from pre-recode.
*/
val leftEnchants = left?.fast()?.getEnchants(true) ?: emptyMap()
val outEnchants = outItem.fast().getEnchants(true)
if (event.inventory.getItem(1) == null && leftEnchants != outEnchants) {
return@run
}
if (plugin.configYml.getBool("anvil.use-rework-penalty")) {
val repairCost = outItem.fast().repairCost
outItem.fast().repairCost = (repairCost + 1) * 2 - 1
}
@Suppress("REMOVAL", "DEPRECATION")
event.inventory.maximumRepairCost = plugin.configYml.getInt("anvil.max-repair-cost").infiniteIfNegative()
@Suppress("REMOVAL", "DEPRECATION")
event.inventory.repairCost = cost
event.result = outItem
event.inventory.setItem(2, outItem)
}
}
private fun doMerge(
left: ItemStack?,
right: ItemStack?,
itemName: String,
player: Player
): AnvilResult {
if (left == null || left.type == Material.AIR) {
return FAIL
}
val formattedItemName = if (player.hasPermission("ecoenchants.anvil.color")) {
StringUtils.format(itemName)
} else {
@Suppress("DEPRECATION")
org.bukkit.ChatColor.stripColor(itemName)
}.let { if (it.isNullOrEmpty()) left.fast().displayName else it }
if (right == null || right.type == Material.AIR) {
if (left.fast().displayName == formattedItemName) {
return FAIL
}
left.fast().displayName =
formattedItemName.let { "§o$it" } // Not a great way to make it italic, but it works
return AnvilResult(left, 0)
}
val leftMeta = left.itemMeta
val rightMeta = right.itemMeta
var unitRepairCost = 0
// Unit repair
if (left.type != right.type) {
if (right.type.canUnitRepair(left.type) && leftMeta is Damageable) {
val perUnit = ceil(left.type.maxDurability / 4.0).toInt()
val max = ceil(leftMeta.damage.toDouble() / perUnit).toInt()
val toDeduct = min(max, right.amount)
unitRepairCost = toDeduct
if (toDeduct <= 0) {
return FAIL
} else {
val newDamage = leftMeta.damage - toDeduct * perUnit
leftMeta.damage = newDamage.coerceAtLeast(0) // Prevent negative damage
right.amount -= toDeduct
}
} else {
if (right.type != Material.ENCHANTED_BOOK) {
return FAIL
}
}
}
left.fast().displayName = formattedItemName.let { "§o$it" } // Same again, it works though
val leftEnchants = left.fast().getEnchants(true)
val rightEnchants = right.fast().getEnchants(true)
val outEnchants = leftEnchants.toMutableMap()
for ((enchant, level) in rightEnchants) {
if (outEnchants.containsKey(enchant)) {
val currentLevel = outEnchants[enchant]!!
outEnchants[enchant] = if (level == currentLevel) {
min(enchant.maxLevel, level + 1)
} else {
max(level, currentLevel)
}
} else {
// Running .wrap() to use EcoEnchantLike canEnchantItem logic
if (enchant.wrap().canEnchantItem(left)) {
if (outEnchants.size < plugin.configYml.getInt("anvil.enchant-limit").infiniteIfNegative()) {
outEnchants[enchant] = level
}
}
}
}
// Item repair - extra check for unit repair cost to prevent weird damage
// Enchanted books seem to be damageable? Not quite sure why. Anyway, there's an extra check.
if (leftMeta is Damageable && rightMeta is Damageable && unitRepairCost == 0 && rightMeta !is EnchantmentStorageMeta) {
val maxDamage = left.type.maxDurability.toInt()
val leftDurability = maxDamage - leftMeta.damage
val rightDurability = maxDamage - rightMeta.damage
val damage = maxDamage - max(maxDamage, leftDurability + rightDurability)
leftMeta.damage = damage.coerceAtLeast(0) // Prevent negative damage
}
if (leftMeta is EnchantmentStorageMeta) {
for (storedEnchant in leftMeta.storedEnchants.keys.toSet()) {
leftMeta.removeStoredEnchant(storedEnchant)
}
for ((enchant, level) in outEnchants) {
leftMeta.addStoredEnchant(enchant, level, true)
}
} else {
for (storedEnchant in leftMeta.enchants.keys.toSet()) {
leftMeta.removeEnchant(storedEnchant)
}
for ((enchant, level) in outEnchants) {
leftMeta.addEnchant(enchant, level, true)
}
}
left.itemMeta = leftMeta
val enchantLevelDiff = abs(leftEnchants.values.sum() - outEnchants.values.sum())
val xpCost =
enchantLevelDiff.toDouble().pow(plugin.configYml.getDouble("anvil.cost-exponent")) + unitRepairCost
return AnvilResult(left, xpCost.roundToInt())
}
}
private val repair = mapOf<Collection<Material>, Collection<Material>>(
Pair(
Tag.PLANKS.values,
listOf(
Material.WOODEN_SWORD,
Material.WOODEN_PICKAXE,
Material.WOODEN_AXE,
Material.WOODEN_SHOVEL,
Material.WOODEN_HOE,
Material.SHIELD
)
),
Pair(
listOf(Material.LEATHER),
listOf(
Material.LEATHER_HELMET,
Material.LEATHER_CHESTPLATE,
Material.LEATHER_LEGGINGS,
Material.LEATHER_BOOTS
)
),
Pair(
listOf(
Material.COBBLESTONE,
Material.COBBLED_DEEPSLATE,
Material.BLACKSTONE
),
listOf(
Material.STONE_SWORD,
Material.STONE_PICKAXE,
Material.STONE_AXE,
Material.STONE_SHOVEL,
Material.STONE_HOE
)
),
Pair(
listOf(
Material.IRON_INGOT
),
listOf(
Material.IRON_HELMET,
Material.IRON_CHESTPLATE,
Material.IRON_LEGGINGS,
Material.IRON_BOOTS,
Material.CHAINMAIL_HELMET,
Material.CHAINMAIL_CHESTPLATE,
Material.CHAINMAIL_LEGGINGS,
Material.CHAINMAIL_BOOTS,
Material.IRON_SWORD,
Material.IRON_PICKAXE,
Material.IRON_AXE,
Material.IRON_SHOVEL,
Material.IRON_HOE
)
),
Pair(
listOf(
Material.GOLD_INGOT
),
listOf(
Material.GOLDEN_HELMET,
Material.GOLDEN_CHESTPLATE,
Material.GOLDEN_LEGGINGS,
Material.GOLDEN_BOOTS,
Material.GOLDEN_SWORD,
Material.GOLDEN_PICKAXE,
Material.GOLDEN_AXE,
Material.GOLDEN_SHOVEL,
Material.GOLDEN_HOE
)
),
Pair(
listOf(
Material.DIAMOND
),
listOf(
Material.DIAMOND_HELMET,
Material.DIAMOND_CHESTPLATE,
Material.DIAMOND_LEGGINGS,
Material.DIAMOND_BOOTS,
Material.DIAMOND_SWORD,
Material.DIAMOND_PICKAXE,
Material.DIAMOND_AXE,
Material.DIAMOND_SHOVEL,
Material.DIAMOND_HOE
)
),
Pair(
listOf(
Material.NETHERITE_INGOT
),
listOf(
Material.NETHERITE_HELMET,
Material.NETHERITE_CHESTPLATE,
Material.NETHERITE_LEGGINGS,
Material.NETHERITE_BOOTS,
Material.NETHERITE_SWORD,
Material.NETHERITE_PICKAXE,
Material.NETHERITE_AXE,
Material.NETHERITE_SHOVEL,
Material.NETHERITE_HOE
)
),
Pair(
listOf(
Material.TURTLE_SCUTE
),
listOf(
Material.TURTLE_HELMET
)
),
Pair(
listOf(
Material.PHANTOM_MEMBRANE
),
listOf(
Material.ELYTRA
)
)
)
fun Material.canUnitRepair(other: Material): Boolean {
for ((units, repairable) in repair) {
if (this in units) {
return other in repairable
}
}
return false
}
| 412 | 0.894721 | 1 | 0.894721 | game-dev | MEDIA | 0.990853 | game-dev | 0.97693 | 1 | 0.97693 |
stipple-effect/stipple-effect | 1,893 | src/com/jordanbunke/stipple_effect/utility/EnumUtils.java | package com.jordanbunke.stipple_effect.utility;
import com.jordanbunke.delta_time.error.GameError;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
public class EnumUtils {
public static <T extends Enum<T>> T next(final T previous) {
final Class<T> enumClass = previous.getDeclaringClass();
final T[] values = enumClass.getEnumConstants();
if (values == null || values.length == 0) {
GameError.send("The generic attempt to fetch the next enum element failed");
return previous;
}
final List<T> vList = Arrays.stream(values).toList();
final int index = vList.indexOf(previous),
nextIndex = (index + 1) % values.length;
return values[nextIndex];
}
public static <T extends Enum<T>> String formattedName(final T enumConst) {
final String name = enumConst.name();
return Arrays.stream(name.split("_"))
.map(EnumUtils::capitalizeFirstLetter)
.reduce((a, b) -> a + " " + b).orElse(name);
}
private static String capitalizeFirstLetter(final String word) {
return word.charAt(0) + word.substring(1).toLowerCase();
}
public static <T extends Enum<T>> Stream<T> stream(final Class<T> enumClass) {
return Arrays.stream(enumClass.getEnumConstants());
}
public static <T extends Enum<T>> boolean matches(
final String name, final Class<T> enumClass,
final Function<T, String> f
) {
return stream(enumClass)
.map(e -> f.apply(e).equals(name))
.reduce(false, Boolean::logicalOr);
}
public static <T extends Enum<T>> boolean matches(
final String name, final Class<T> enumClass
) {
return matches(name, enumClass, T::name);
}
}
| 412 | 0.85536 | 1 | 0.85536 | game-dev | MEDIA | 0.508477 | game-dev | 0.976513 | 1 | 0.976513 |
2004Scape/Server | 2,187 | data/src/scripts/levelrequire/scripts/tier20.rs2 | // Melee
[opheld2,mithril_dagger] @levelrequire_attack(20, last_slot);
[opheld2,mithril_dagger_p] @levelrequire_attack(20, last_slot);
[opheld2,mithril_axe] @levelrequire_attack(20, last_slot);
[opheld2,mithril_pickaxe] @levelrequire_attack(20, last_slot);
[opheld2,mithril_mace] @levelrequire_attack(20, last_slot);
[opheld2,mithril_sword] @levelrequire_attack(20, last_slot);
[opheld2,mithril_scimitar] @levelrequire_attack(20, last_slot);
[opheld2,mithril_longsword] @levelrequire_attack(20, last_slot);
[opheld2,mithril_warhammer] @levelrequire_attack(20, last_slot);
[opheld2,mithril_battleaxe] @levelrequire_attack(20, last_slot);
[opheld2,mithril_spear] @levelrequire_attack(20, last_slot);
[opheld2,mithril_spear_p] @levelrequire_attack(20, last_slot);
[opheld2,mithril_2h_sword] @levelrequire_attack(20, last_slot);
[opheld2,excalibur] @levelrequire_attack(20, last_slot);
[opheld2,mithril_med_helm] @levelrequire_defence(20, last_slot);
[opheld2,mithril_full_helm] @levelrequire_defence(20, last_slot);
[opheld2,mithril_sq_shield] @levelrequire_defence(20, last_slot);
[opheld2,mithril_kiteshield] @levelrequire_defence(20, last_slot);
[opheld2,mithril_platelegs] @levelrequire_defence(20, last_slot);
[opheld2,mithril_plateskirt] @levelrequire_defence(20, last_slot);
[opheld2,mithril_chainbody] @levelrequire_defence(20, last_slot);
[opheld2,mithril_platebody] @levelrequire_defence(20, last_slot);
// Ranged
[opheld2,willow_longbow] @levelrequire_ranged(20, last_slot);
[opheld2,willow_shortbow] @levelrequire_ranged(20, last_slot);
[opheld2,coif] @levelrequire_ranged(20, last_slot);
[opheld2,studded_body] @levelrequire_ranged_and_defence(20, 20, last_slot);
[opheld2,studded_chaps] @levelrequire_ranged(20, last_slot);
[opheld2,mithril_dart] @levelrequire_ranged(20, last_slot);
[opheld2,mithril_dart_p] @levelrequire_ranged(20, last_slot);
[opheld2,mithril_knife] @levelrequire_ranged(20, last_slot);
[opheld2,mithril_knife_p] @levelrequire_ranged(20, last_slot);
[opheld2,mithril_thrownaxe] @levelrequire_ranged(20, last_slot);
[opheld2,mithril_javelin] @levelrequire_ranged(20, last_slot);
[opheld2,mithril_javelin_p] @levelrequire_ranged(20, last_slot);
// Magic
| 412 | 0.825064 | 1 | 0.825064 | game-dev | MEDIA | 0.990904 | game-dev | 0.683435 | 1 | 0.683435 |
amethyst/rustrogueliketutorial | 2,297 | chapter-38-rooms/src/map_builders/room_draw.rs | use super::{MetaMapBuilder, BuilderMap, TileType, Rect};
use rltk::RandomNumberGenerator;
pub struct RoomDrawer {}
impl MetaMapBuilder for RoomDrawer {
fn build_map(&mut self, rng: &mut rltk::RandomNumberGenerator, build_data : &mut BuilderMap) {
self.build(rng, build_data);
}
}
impl RoomDrawer {
#[allow(dead_code)]
pub fn new() -> Box<RoomDrawer> {
Box::new(RoomDrawer{})
}
#[allow(dead_code)]
fn rectangle(&mut self, build_data : &mut BuilderMap, room : &Rect) {
for y in room.y1 +1 ..= room.y2 {
for x in room.x1 + 1 ..= room.x2 {
let idx = build_data.map.xy_idx(x, y);
if idx > 0 && idx < ((build_data.map.width * build_data.map.height)-1) as usize {
build_data.map.tiles[idx] = TileType::Floor;
}
}
}
}
#[allow(dead_code)]
fn circle(&mut self, build_data : &mut BuilderMap, room : &Rect) {
let radius = i32::min(room.x2 - room.x1, room.y2 - room.y1) as f32 / 2.0;
let center = room.center();
let center_pt = rltk::Point::new(center.0, center.1);
for y in room.y1 ..= room.y2 {
for x in room.x1 ..= room.x2 {
let idx = build_data.map.xy_idx(x, y);
let distance = rltk::DistanceAlg::Pythagoras.distance2d(center_pt, rltk::Point::new(x, y));
if idx > 0
&& idx < ((build_data.map.width * build_data.map.height)-1) as usize
&& distance <= radius
{
build_data.map.tiles[idx] = TileType::Floor;
}
}
}
}
fn build(&mut self, rng : &mut RandomNumberGenerator, build_data : &mut BuilderMap) {
let rooms : Vec<Rect>;
if let Some(rooms_builder) = &build_data.rooms {
rooms = rooms_builder.clone();
} else {
panic!("Room Drawing require a builder with room structures");
}
for room in rooms.iter() {
let room_type = rng.roll_dice(1,4);
match room_type {
1 => self.circle(build_data, room),
_ => self.rectangle(build_data, room)
}
build_data.take_snapshot();
}
}
}
| 412 | 0.753704 | 1 | 0.753704 | game-dev | MEDIA | 0.66771 | game-dev | 0.914183 | 1 | 0.914183 |
Cataclysm-TLG/Cataclysm-TLG | 125,837 | src/creature.cpp | #include "creature.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdlib>
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include "anatomy.h"
#include "body_part_set.h"
#include "cached_options.h"
#include "calendar.h"
#include "cata_assert.h"
#include "cata_utility.h"
#include "cata_variant.h"
#include "character.h"
#include "character_attire.h"
#include "character_id.h"
#include "color.h"
#include "creature_tracker.h"
#include "cursesdef.h"
#include "damage.h"
#include "debug.h"
#include "effect.h"
#include "enum_traits.h"
#include "enums.h"
#include "event.h"
#include "event_bus.h"
#include "explosion.h"
#include "field.h"
#include "flat_set.h"
#include "flexbuffer_json-inl.h"
#include "flexbuffer_json.h"
#include "game.h"
#include "game_constants.h"
#include "item.h"
#include "item_location.h"
#include "json_error.h"
#include "level_cache.h"
#include "lightmap.h"
#include "line.h"
#include "localized_comparator.h"
#include "magic_enchantment.h"
#include "map.h"
#include "map_iterator.h"
#include "mapdata.h"
#include "mattack_common.h"
#include "mdarray.h"
#include "messages.h"
#include "monster.h"
#include "morale_types.h"
#include "mtype.h"
#include "npc.h"
#include "options.h"
#include "output.h"
#include "point.h"
#include "projectile.h"
#include "rng.h"
#include "sounds.h"
#include "talker.h"
#include "talker_avatar.h"
#include "talker_character.h"
#include "talker_monster.h"
#include "talker_npc.h"
#include "translation.h"
#include "translations.h"
#include "units.h"
#include "value_ptr.h"
#include "vehicle.h"
#include "veh_type.h"
#include "vpart_position.h"
struct mutation_branch;
static const ammo_effect_str_id ammo_effect_APPLY_SAP( "APPLY_SAP" );
static const ammo_effect_str_id ammo_effect_BEANBAG( "BEANBAG" );
static const ammo_effect_str_id ammo_effect_BLINDS_EYES( "BLINDS_EYES" );
static const ammo_effect_str_id ammo_effect_FOAMCRETE( "FOAMCRETE" );
static const ammo_effect_str_id ammo_effect_IGNITE( "IGNITE" );
static const ammo_effect_str_id ammo_effect_INCENDIARY( "INCENDIARY" );
static const ammo_effect_str_id ammo_effect_LARGE_BEANBAG( "LARGE_BEANBAG" );
static const ammo_effect_str_id ammo_effect_MAGIC( "MAGIC" );
static const ammo_effect_str_id ammo_effect_NOGIB( "NOGIB" );
static const ammo_effect_str_id ammo_effect_NO_DAMAGE_SCALING( "NO_DAMAGE_SCALING" );
static const ammo_effect_str_id ammo_effect_PARALYZEPOISON( "PARALYZEPOISON" );
static const ammo_effect_str_id ammo_effect_ROBOT_DAZZLE( "ROBOT_DAZZLE" );
static const ammo_effect_str_id ammo_effect_TANGLE( "TANGLE" );
static const anatomy_id anatomy_human_anatomy( "human_anatomy" );
static const damage_type_id damage_acid( "acid" );
static const damage_type_id damage_bash( "bash" );
static const damage_type_id damage_electric( "electric" );
static const damage_type_id damage_heat( "heat" );
static const efftype_id effect_all_fours( "all_fours" );
static const efftype_id effect_blind( "blind" );
static const efftype_id effect_downed( "downed" );
static const efftype_id effect_foamcrete_slow( "foamcrete_slow" );
static const efftype_id effect_invisibility( "invisibility" );
static const efftype_id effect_knockdown( "knockdown" );
static const efftype_id effect_lying_down( "lying_down" );
static const efftype_id effect_monster_dodged( "monster_dodged" );
static const efftype_id effect_no_sight( "no_sight" );
static const efftype_id effect_npc_suspend( "npc_suspend" );
static const efftype_id effect_onfire( "onfire" );
static const efftype_id effect_paralyzepoison( "paralyzepoison" );
static const efftype_id effect_quadruped_full( "quadruped_full" );
static const efftype_id effect_quadruped_half( "quadruped_half" );
static const efftype_id effect_ridden( "ridden" );
static const efftype_id effect_riding( "riding" );
static const efftype_id effect_sap( "sap" );
static const efftype_id effect_sensor_stun( "sensor_stun" );
static const efftype_id effect_sleep( "sleep" );
static const efftype_id effect_stumbled_into_invisible( "stumbled_into_invisible" );
static const efftype_id effect_stunned( "stunned" );
static const efftype_id effect_telepathic_ignorance( "telepathic_ignorance" );
static const efftype_id effect_telepathic_ignorance_self( "telepathic_ignorance_self" );
static const efftype_id effect_tied( "tied" );
static const efftype_id effect_zapped( "zapped" );
static const field_type_str_id field_fd_last_known( "fd_last_known" );
static const flag_id json_flag_GRAB_FILTER( "GRAB_FILTER" );
static const json_character_flag json_flag_BIONIC_LIMB( "BIONIC_LIMB" );
static const json_character_flag json_flag_CANNOT_MOVE( "CANNOT_MOVE" );
static const json_character_flag json_flag_CANNOT_TAKE_DAMAGE( "CANNOT_TAKE_DAMAGE" );
static const json_character_flag json_flag_FREEZE_EFFECTS( "FREEZE_EFFECTS" );
static const json_character_flag json_flag_IGNORE_TEMP( "IGNORE_TEMP" );
static const json_character_flag json_flag_LIMB_LOWER( "LIMB_LOWER" );
static const json_character_flag json_flag_LIMB_UPPER( "LIMB_UPPER" );
static const material_id material_cotton( "cotton" );
static const material_id material_flesh( "flesh" );
static const material_id material_hflesh( "hflesh" );
static const material_id material_iflesh( "iflesh" );
static const material_id material_kevlar( "kevlar" );
static const material_id material_paper( "paper" );
static const material_id material_powder( "powder" );
static const material_id material_steel( "steel" );
static const material_id material_stone( "stone" );
static const material_id material_vegetable( "vegetable" );
static const material_id material_wood( "wood" );
static const material_id material_wool( "wool" );
static const morale_type morale_pyromania_nofire( "morale_pyromania_nofire" );
static const morale_type morale_pyromania_startfire( "morale_pyromania_startfire" );
static const species_id species_ROBOT( "ROBOT" );
static const trait_id trait_DEBUG_CLOAK( "DEBUG_CLOAK" );
static const trait_id trait_PYROMANIA( "PYROMANIA" );
const std::map<std::string, creature_size> Creature::size_map = {
{"TINY", creature_size::tiny},
{"SMALL", creature_size::small},
{"MEDIUM", creature_size::medium},
{"LARGE", creature_size::large},
{"HUGE", creature_size::huge}
};
const std::set<material_id> Creature::cmat_flesh{
material_flesh, material_iflesh, material_hflesh,
};
const std::set<material_id> Creature::cmat_fleshnveg{
material_flesh, material_iflesh, material_hflesh, material_vegetable
};
const std::set<material_id> Creature::cmat_flammable{
material_paper, material_powder,
material_cotton, material_wool
};
const std::set<material_id> Creature::cmat_flameres{
material_stone, material_kevlar, material_steel
};
Creature::Creature()
{
moves = 0;
pain = 0;
killer = nullptr;
speed_base = 100;
underwater = false;
location = tripoint_abs_ms( 20, 10, -500 ); // Some arbitrary position that will cause debugmsgs
Creature::reset_bonuses();
fake = false;
}
Creature::Creature( const Creature & ) = default;
Creature::Creature( Creature && ) noexcept( map_is_noexcept &&list_is_noexcept ) = default;
Creature &Creature::operator=( const Creature & ) = default;
Creature &Creature::operator=( Creature && ) noexcept = default;
Creature::~Creature() = default;
tripoint_bub_ms Creature::pos_bub() const
{
return get_map().get_bub( location );
}
tripoint_bub_ms Creature::pos_bub( const map &here ) const
{
return here.get_bub( location );
}
void Creature::setpos( map &here, const tripoint_bub_ms &p, bool check_gravity/* = true*/ )
{
const tripoint_abs_ms old_loc = pos_abs();
set_pos_abs_only( here.get_abs( p ) );
on_move( old_loc );
if( check_gravity ) {
gravity_check( &here );
if( !is_monster() ) {
as_character()->water_immersion();
}
}
}
void Creature::setpos( const tripoint_abs_ms &p, bool check_gravity/* = true*/ )
{
const tripoint_abs_ms old_loc = pos_abs();
set_pos_abs_only( p );
on_move( old_loc );
if( check_gravity ) {
gravity_check();
if( !is_monster() ) {
as_character()->water_immersion();
}
}
}
static units::volume size_to_volume( creature_size size_class )
{
// TODO: size_to_volume and volume_to_size should be made into a single consistent function.
// TODO: Volume averages should be 8500, 23000, 75000, 136000, 244000
// TODO: This would necessitate increasing vpart capacity and resizing
// almost every monster in the game.
if( size_class == creature_size::tiny ) {
return 15625_ml;
} else if( size_class == creature_size::small ) {
return 31250_ml;
} else if( size_class == creature_size::medium ) {
return 62500_ml;
} else if( size_class == creature_size::large ) {
return 125000_ml;
}
return 250000_ml;
}
int Creature::enum_size() const
{
static const int size_map[] = { 0, 1, 2, 3, 4, 5 }; // Mapping from enum value to size
if( get_size() < creature_size::num_sizes ) {
return size_map[static_cast<int>( get_size() )];
}
debugmsg( "ERROR: enum_size() returned invalid creature size class." );
return 3;
}
bool Creature::can_move_to_vehicle_tile( const tripoint_abs_ms &loc, bool &cramped ) const
{
map &here = get_map();
const optional_vpart_position vp_there = here.veh_at( loc );
if( !vp_there ) {
cramped = false;
return true;
}
const monster *mon = as_monster();
vehicle &veh = vp_there->vehicle();
std::vector<vehicle_part *> cargo_parts;
cargo_parts = veh.get_parts_at( loc, "CARGO", part_status_flag::any );
units::volume capacity = 0_ml;
units::volume free_cargo = 0_ml;
for( vehicle_part *part : cargo_parts ) {
vehicle_stack contents = veh.get_items( *part );
if( !vp_there.part_with_feature( "CARGO_PASSABLE", false ) &&
!vp_there.part_with_feature( "APPLIANCE", false ) &&
!vp_there.part_with_feature( "OBSTACLE", false ) ) {
capacity += contents.max_volume();
free_cargo += contents.free_volume();
// Open-topped vehicle parts have more room to step over cargo.
if( !vp_there.part_with_feature( "ROOF", true ) ) {
free_cargo *= 1.2;
}
}
}
if( capacity > 0_ml ) {
// First, we'll try to squeeze in. Open-topped vehicle parts have more room to step over cargo.
if( !veh.enclosed_at( loc ) ) {
free_cargo *= 1.2;
}
const creature_size size = get_size();
units::volume critter_volume;
if( mon ) {
critter_volume = mon->get_volume();
} else {
critter_volume = size_to_volume( size );
}
if( critter_volume > free_cargo * 1.33 ) {
return false;
}
if( critter_volume >= size_to_volume( creature_size::huge ) &&
!vp_there.part_with_feature( "HUGE_OK", false ) ) {
return false;
}
if( critter_volume > free_cargo ) {
if( !mon || !( mon->type->bodytype == "snake" || mon->type->bodytype == "blob" ||
mon->type->bodytype == "fish" ||
has_flag( mon_flag_PLASTIC ) ) ) {
cramped = true;
return true;
}
}
if( size == creature_size::huge && !vp_there.part_with_feature( "AISLE", false ) &&
// TODO: Can we get rid of huge_ok? Cargo space alone should handle it, right?
!vp_there.part_with_feature( "HUGE_OK", false ) ) {
cramped = true;
return true;
}
}
cramped = false;
return true;
}
bool Creature::can_move_to_vehicle_tile( const tripoint_abs_ms &loc ) const
{
bool dummy = false;
return can_move_to_vehicle_tile( loc, dummy );
}
int Creature::climbing_cost( const tripoint_bub_ms &, const tripoint_bub_ms & ) const
{
debugmsg( "ERROR: creature ran empty overload climbing_cost()." );
return 0;
}
void Creature::move_to( const tripoint_abs_ms &loc )
{
const tripoint_abs_ms old_loc = pos_abs();
set_pos_abs_only( loc );
on_move( old_loc );
}
void Creature::set_pos_bub_only( const map &here, const tripoint_bub_ms &p )
{
location = here.get_abs( p );
}
void Creature::set_pos_abs_only( const tripoint_abs_ms &loc )
{
location = loc;
}
void Creature::on_move( const tripoint_abs_ms & ) {}
std::vector<std::string> Creature::get_grammatical_genders() const
{
// Returning empty list means we use the language-specified default
return {};
}
void Creature::gravity_check()
{
}
void Creature::gravity_check( map * )
{
}
void Creature::normalize()
{
}
void Creature::reset()
{
reset_bonuses();
reset_stats();
}
void Creature::bleed( map &here ) const
{
here.add_splatter( bloodType(), pos_bub( here ) );
}
void Creature::reset_bonuses()
{
num_blocks = 1;
num_dodges = 1;
num_blocks_bonus = 0;
num_dodges_bonus = 0;
armor_bonus.clear();
speed_bonus = 0;
dodge_bonus = 0;
block_bonus = 0;
hit_bonus = 0;
bash_bonus = 0;
cut_bonus = 0;
size_bonus = 0;
bash_mult = 1.0f;
cut_mult = 1.0f;
melee_quiet = false;
throw_resist = 0;
}
void Creature::process_turn()
{
decrement_summon_timer();
if( is_dead_state() ) {
return;
}
reset_bonuses();
process_effects();
process_damage_over_time();
// Call this in case any effects have changed our stats
reset_stats();
// add an appropriate number of moves
if( !has_effect( effect_ridden ) ) {
moves += get_speed();
}
}
bool Creature::cant_do_underwater( bool msg ) const
{
if( is_underwater() ) {
if( msg ) {
add_msg_player_or_npc( m_info, _( "You can't do that while underwater." ),
_( "<npcname> can't do that while underwater." ) );
}
return true;
}
return false;
}
bool Creature::is_underwater() const
{
return underwater;
}
bool Creature::is_likely_underwater( const map &here ) const
{
return is_underwater() ||
( has_flag( mon_flag_AQUATIC ) &&
here.has_flag( ter_furn_flag::TFLAG_SWIMMABLE, pos_bub( here ) ) );
}
// Detects whether a target is sapient or not (or barely sapient, since ferals count)
bool Creature::has_mind() const
{
return false;
}
bool Creature::is_ranged_attacker() const
{
if( has_flag( mon_flag_RANGED_ATTACKER ) ) {
return true;
}
const monster *mon = as_monster();
if( mon ) {
for( const std::pair<const std::string, mtype_special_attack> &attack :
mon->type->special_attacks ) {
if( attack.second->id == "gun" ) {
return true;
}
}
}
//TODO Potentially add check for this as npc wielding ranged weapon
return false;
}
bool Creature::digging() const
{
return false;
}
bool Creature::is_dangerous_fields( const field &fld ) const
{
// Else check each field to see if it's dangerous to us
for( const auto &dfield : fld ) {
if( is_dangerous_field( dfield.second ) && !is_immune_field( dfield.first ) ) {
return true;
}
}
// No fields were found to be dangerous, so the field set isn't dangerous
return false;
}
bool Creature::is_dangerous_field( const field_entry &entry ) const
{
// If it's dangerous and we're not immune return true, else return false
return entry.is_dangerous() && !is_immune_field( entry.get_field_type() );
}
bool Creature::is_immune_fields( const std::vector<field_type_id> &fields ) const
{
for( const field_type_id fi : fields ) {
if( !is_immune_field( fi ) ) {
return false;
}
}
return true;
}
static bool majority_rule( const bool a_vote, const bool b_vote, const bool c_vote )
{
// Helper function suggested on discord by jbtw
return ( a_vote + b_vote + c_vote ) > 1;
}
bool Creature::sees( const map &here, const Creature &critter ) const
{
const Character *ch = critter.as_character();
const tripoint_bub_ms pos = pos_bub( here );
const tripoint_bub_ms critter_pos = critter.pos_bub( here );
// Creatures always see themselves (simplifies drawing).
if( &critter == this ) {
return true;
}
if( std::abs( posz() - critter.posz() ) > fov_3d_z_range ) {
return false;
}
const int target_range = rl_dist( pos_abs( ), critter.pos_abs( ) );
if( target_range > MAX_VIEW_DISTANCE ) {
return false;
}
if( critter.has_flag( mon_flag_ALWAYS_VISIBLE ) || ( has_flag( mon_flag_ALWAYS_SEES_YOU ) &&
critter.is_avatar() ) ) {
return true;
}
if( this->has_flag( mon_flag_ALL_SEEING ) ) {
const monster *m = this->as_monster();
return target_range <= std::max( m->type->vision_day, m->type->vision_night );
}
if( critter.is_hallucination() && !is_avatar() ) {
// Hallucinations are imaginations of the player character, npcs or monsters don't hallucinate.
return false;
}
// Creature has stumbled into an invisible player and is now aware of them.
// REVIEW: Why is this only done for the player?
if( has_effect( effect_stumbled_into_invisible ) &&
here.has_field_at( critter_pos, field_fd_last_known ) && critter.is_avatar() ) {
return true;
}
// This check is ridiculously expensive so defer it to after everything else.
// REVIEW: Is this really expensive, or an old comment?
auto visible = []( const Character * ch ) {
return ch == nullptr || !ch->is_invisible();
};
// Can always see adjacent monsters on the same level.
// We also bypass lighting for vertically adjacent monsters, but still check for floors.
if( target_range <= 1 ) {
return ( posz() == critter.posz() || here.sees( pos, critter_pos, 1 ) ) &&
visible( ch );
}
// If we cannot see without any of the penalties below, bail now.
if( !sees( here, critter_pos, critter.is_avatar() ) ) {
return false;
}
// Used with the Mind over Matter power Obscurity, to telepathically erase yourself from a target's perceptions
if( has_effect( effect_telepathic_ignorance ) &&
critter.has_effect( effect_telepathic_ignorance_self ) ) {
return false;
}
bool different_levels = false;
if( posz() != critter.posz() ) {
different_levels = true;
}
bool has_camouflage = false;
bool has_water_camouflage = false;
bool has_night_invisibility = false;
if( critter.is_monster() ) {
has_camouflage = critter.has_flag( mon_flag_CAMOUFLAGE );
has_water_camouflage = critter.has_flag( mon_flag_WATER_CAMOUFLAGE ) ||
( critter.get_size() < creature_size::large && critter.has_flag( mon_flag_NO_BREATHE ) );
has_night_invisibility = critter.has_flag( mon_flag_NIGHT_INVISIBILITY );
}
bool is_underwater = critter.is_likely_underwater( here );
bool is_invisible = critter.has_effect( effect_invisibility );
// Check if creature is digging and the tile is diggable
if( target_range > 2 && critter.digging() &&
here.has_flag( ter_furn_flag::TFLAG_DIGGABLE, critter.pos_bub( here ) ) ) {
return false;
}
// Camouflage or Water Camouflage checks
if( has_camouflage && target_range > this->get_eff_per() ) {
return false;
}
if( has_water_camouflage && target_range > this->get_eff_per() ) {
if( is_underwater ||
here.has_flag( ter_furn_flag::TFLAG_DEEP_WATER, critter.pos_bub( here ) ) ||
( here.has_flag( ter_furn_flag::TFLAG_SHALLOW_WATER, critter.pos_bub( here ) ) &&
critter.get_size() < creature_size::medium ) ) {
return false;
}
}
// Night Invisibility check
if( has_night_invisibility && here.light_at( critter.pos_bub( here ) ) <= lit_level::LOW ) {
return false;
}
// Invisible effect
if( is_invisible ) {
return false;
}
// Underwater visibility check with majority rule
if( !is_likely_underwater( here ) && is_underwater &&
majority_rule( critter.has_flag( mon_flag_WATER_CAMOUFLAGE ),
here.has_flag( ter_furn_flag::TFLAG_DEEP_WATER, critter.pos_bub( here ) ),
different_levels ) ) {
return false;
}
if( ( here.has_flag_ter_or_furn( ter_furn_flag::TFLAG_HIDE_PLACE, critter.pos_bub( here ) ) ) &&
critter.get_size() < creature_size::large ) {
return false;
}
if( here.has_flag_ter_or_furn( ter_furn_flag::TFLAG_SMALL_HIDE, critter.pos_bub( here ) ) &&
critter.has_flag( mon_flag_SMALL_HIDER ) ) {
return false;
}
int ledge_concealment = 0;
if( different_levels ) {
ledge_concealment = ( here.ledge_concealment( pos_bub( here ), critter.pos_bub( here ) ) );
}
const int concealment = std::max( here.obstacle_concealment( pos_bub( here ),
critter.pos_bub( here ) ),
ledge_concealment );
if( ch != nullptr ) {
if( concealment > eye_level() ) {
return false;
}
return visible( ch );
} else {
if( concealment > eye_level() ) {
return false;
}
}
return true;
}
int Creature::eye_level() const
{
if( this->is_monster() ) {
return this->as_monster()->eye_level();
} else {
return this->as_character()->eye_level();
}
}
bool Creature::sees( const map &here, const tripoint_bub_ms &t, bool is_avatar,
int range_mod ) const
{
if( std::abs( posz() - t.z() ) > fov_3d_z_range ) {
return false;
}
const tripoint_bub_ms pos = pos_bub( here );
const int range_cur = sight_range( here.ambient_light_at( t ) );
const int range_day = sight_range( default_daylight_level() );
const int range_night = sight_range( 0 );
const int range_max = std::max( range_day, range_night );
const int range_min = std::min( range_cur, range_max );
const int wanted_range = rl_dist( pos, t );
if( wanted_range <= range_min ||
( wanted_range <= range_max &&
here.ambient_light_at( t ) > here.get_cache_ref( t.z() ).natural_light_level_cache ) ) {
int range = 0;
if( here.ambient_light_at( t ) > here.get_cache_ref( t.z() ).natural_light_level_cache ) {
range = MAX_VIEW_DISTANCE;
} else {
range = range_min;
}
if( has_effect( effect_no_sight ) ) {
range = 1;
}
if( range_mod > 0 ) {
range = std::min( range, range_mod );
}
if( is_avatar ) {
// Special case monster -> player visibility, forcing it to be symmetric with player vision.
const float player_visibility_factor = get_player_character().visibility() / 100.0f;
int adj_range = std::floor( range * player_visibility_factor );
return adj_range >= wanted_range &&
here.get_cache_ref( posz() ).seen_cache[pos.x()][pos.y()] > LIGHT_TRANSPARENCY_SOLID;
} else {
return here.sees( pos, t, range );
}
} else {
return false;
}
}
// Helper function to check if potential area of effect of a weapon overlaps vehicle
// Maybe TODO: If this is too slow, precalculate a bounding box and clip the tested area to it
static bool overlaps_vehicle( const std::set<tripoint_abs_ms> &veh_area, const tripoint_abs_ms &pos,
const int area )
{
for( const tripoint_abs_ms &tmp : tripoint_range<tripoint_abs_ms>( pos - tripoint( area, area, 0 ),
pos + tripoint( area - 1, area - 1, 0 ) ) ) {
if( veh_area.count( tmp ) > 0 ) {
return true;
}
}
return false;
}
Creature *Creature::auto_find_hostile_target( int range, int &boo_hoo, int area )
{
map &here = get_map();
Creature *target = nullptr;
Character &player_character = get_player_character();
tripoint_bub_ms player_pos = player_character.pos_bub();
constexpr int hostile_adj = 2; // Priority bonus for hostile targets
const int iff_dist = ( range + area ) * 3 / 2 + 6; // iff check triggers at this distance
// iff safety margin (degrees). less accuracy, more paranoia
units::angle iff_hangle = units::from_degrees( 15 + area );
float best_target_rating = -1.0f; // bigger is better
units::angle u_angle = {}; // player angle relative to turret
boo_hoo = 0; // how many targets were passed due to IFF. Tragically.
bool self_area_iff = false; // Need to check if the target is near the vehicle we're a part of
bool area_iff = false; // Need to check distance from target to player
bool angle_iff = sees( here, player_character ); // Need to check if player is in cone to target
int pldist = rl_dist( pos_bub( here ), player_pos );
vehicle *in_veh = is_fake() ? veh_pointer_or_null( here.veh_at( pos_bub( here ) ) ) : nullptr;
if( pldist < iff_dist && angle_iff ) {
area_iff = area > 0;
// Player inside vehicle won't be hit by shots from the roof,
// so we can fire "through" them just fine.
const optional_vpart_position vp = here.veh_at( player_pos );
if( in_veh && veh_pointer_or_null( vp ) == in_veh && vp->is_inside() ) {
angle_iff = false; // No angle IFF, but possibly area IFF
} else if( pldist < 3 ) {
// granularity increases with proximity
iff_hangle = ( pldist == 2 ? 30_degrees : 60_degrees );
}
u_angle = coord_to_angle( pos_bub( here ), player_pos );
}
if( area > 0 && in_veh != nullptr ) {
self_area_iff = true;
}
std::vector<Creature *> targets = g->get_creatures_if( [&]( const Creature & critter ) {
if( critter.is_monster() ) {
// friendly to the player, not a target for us
return static_cast<const monster *>( &critter )->attitude( &player_character ) == MATT_ATTACK;
}
if( critter.is_npc() ) {
// friendly to the player, not a target for us
return static_cast<const npc *>( &critter )->get_attitude() == NPCATT_KILL;
}
// TODO: what about g->u?
return false;
} );
for( Creature *&m : targets ) {
if( !sees( here, *m ) ) {
// can't see nor sense it
if( is_fake() && in_veh ) {
// If turret in the vehicle then
// Hack: trying yo avoid turret LOS blocking by frames bug by trying to see target from vehicle boundary
// Or turret wallhack for turret's car
// TODO: to visibility checking another way, probably using 3D FOV
std::vector<tripoint_bub_ms> path_to_target = line_to( pos_bub( here ), m->pos_bub( here ) );
path_to_target.insert( path_to_target.begin(), pos_bub( here ) );
// Getting point on vehicle boundaries and on line between target and turret
bool continueFlag = true;
do {
const optional_vpart_position vp = here.veh_at( path_to_target.back() );
vehicle *const veh = vp ? &vp->vehicle() : nullptr;
if( in_veh == veh ) {
continueFlag = false;
} else {
path_to_target.pop_back();
}
} while( continueFlag );
tripoint_bub_ms oldPos = pos_bub( here );
setpos( here,
path_to_target.back() ); // Temporary moving targeting npc on vehicle boundary position
bool seesFromVehBound = sees( here, *m ); // And look from there
setpos( here, oldPos );
if( !seesFromVehBound ) {
continue;
}
} else {
continue;
}
}
int dist = rl_dist( pos_abs(), m->pos_abs() ) + 1; // rl_dist can be 0
if( dist > range + 1 || dist < area ) {
// Too near or too far
continue;
}
// Prioritize big, armed and hostile stuff
float mon_rating = m->power_rating();
float target_rating = mon_rating / dist;
if( mon_rating + hostile_adj <= 0 ) {
// We wouldn't attack it even if it was hostile
continue;
}
if( in_veh != nullptr && veh_pointer_or_null( here.veh_at( m->pos_bub( here ) ) ) == in_veh ) {
// No shooting stuff on vehicle we're a part of
continue;
}
if( area_iff && rl_dist( player_pos, m->pos_bub( here ) ) <= area ) {
// Player in AoE
boo_hoo++;
continue;
}
// Hostility check can be expensive, but we need to inform the player of boo_hoo
// only when the target is actually "hostile enough"
bool maybe_boo = false;
if( angle_iff ) {
units::angle tangle = coord_to_angle( pos_abs(), m->pos_abs() );
units::angle diff = units::fabs( u_angle - tangle );
// Player is in the angle and not too far behind the target
if( ( diff + iff_hangle > 360_degrees || diff < iff_hangle ) &&
( dist * 3 / 2 + 6 > pldist ) ) {
maybe_boo = true;
}
}
if( !maybe_boo && ( ( mon_rating + hostile_adj ) / dist <= best_target_rating ) ) {
// "Would we skip the target even if it was hostile?"
// Helps avoid (possibly expensive) attitude calculation
continue;
}
if( m->attitude_to( player_character ) == Attitude::HOSTILE ) {
target_rating = ( mon_rating + hostile_adj ) / dist;
if( maybe_boo ) {
boo_hoo++;
continue;
}
}
if( target_rating <= best_target_rating || target_rating <= 0 ) {
continue; // Handle this late so that boo_hoo++ can happen
}
// Expensive check for proximity to vehicle
if( self_area_iff && overlaps_vehicle( in_veh->get_points(), m->pos_abs(), area ) ) {
continue;
}
target = m;
best_target_rating = target_rating;
}
return target;
}
/*
* Damage-related functions
*/
int Creature::size_melee_penalty() const
{
switch( get_size() ) {
case creature_size::tiny:
return rng( 10, 30 );
case creature_size::small:
return rng( 5, 15 );
case creature_size::medium:
return 0;
case creature_size::large:
return rng( -5, -15 );
case creature_size::huge:
return rng( -10, -30 );
case creature_size::num_sizes:
debugmsg( "ERROR: Creature has invalid size class." );
return 0;
}
debugmsg( "Invalid target size %d", get_size() );
return 0;
}
bool Creature::is_adjacent( const Creature *target, const bool allow_z_levels ) const
{
if( target == nullptr ) {
return false;
}
if( rl_dist( pos_bub(), target->pos_bub() ) != 1 ) {
return false;
}
// Diagonally offset targets are not adjacent.
if( posz() != target->posz() && pos_bub().xy() != target->pos_bub().xy() ) {
return false;
}
// Explicitly check for Z difference > 1
if( std::abs( posz() - target->posz() ) > 1 ) {
return false;
}
map &here = get_map();
if( posz() == target->posz() ) {
return
/* either target or attacker are underwater and separated by vehicle tiles */
!( underwater != target->underwater &&
here.veh_at( pos_bub() ) && here.veh_at( target->pos_bub() ) );
}
if( !allow_z_levels ) {
return false;
}
// The square above must have no floor.
// The square below must have no ceiling (i.e. no floor on the tile above it).
const bool target_above = target->posz() > posz();
const tripoint_bub_ms up = target_above ? target->pos_bub() : pos_bub();
const tripoint_bub_ms down = target_above ? pos_bub() : target->pos_bub();
const tripoint_bub_ms above{ down.xy(), up.z()};
return ( !here.has_floor( up ) || here.ter( up )->has_flag( ter_furn_flag::TFLAG_GOES_DOWN ) ) &&
( !here.has_floor( above ) || here.ter( above )->has_flag( ter_furn_flag::TFLAG_GOES_DOWN ) );
}
int Creature::deal_melee_attack( Creature *source, int hitroll )
{
const float dodge = dodge_roll();
on_try_dodge();
int hit_spread = hitroll - dodge - size_melee_penalty();
add_msg_debug( debugmode::DF_CREATURE, "Base hitroll %d",
hitroll );
add_msg_debug( debugmode::DF_CREATURE, "Dodge roll %.1f",
dodge );
if( has_flag( mon_flag_IMMOBILE ) || has_effect_with_flag( json_flag_CANNOT_MOVE ) ) {
// Under normal circumstances, even a clumsy person would
// not miss a turret. It should, however, be possible to
// miss a smaller target, especially when wielding a
// clumsy weapon or when severely encumbered.
hit_spread += 40;
}
// If attacker missed call targets on_dodge event
if( dodge > 0.0 && hit_spread <= 0 && source != nullptr && !source->is_hallucination() ) {
on_dodge( source, source->get_melee() );
} else if( !is_monster() && dodge > 0.0 && source != nullptr && !source->is_hallucination() &&
one_in( 4 ) ) {
on_fail_dodge( source, source->get_melee() - 2 );
}
add_msg_debug( debugmode::DF_CREATURE, "Final hitspread %d",
hit_spread );
return hit_spread;
}
void Creature::deal_melee_hit( Creature *source, int hit_spread, bool critical_hit,
damage_instance dam, dealt_damage_instance &dealt_dam,
const weakpoint_attack &attack, const bodypart_id *bp )
{
map &here = get_map();
if( source == nullptr || source->is_hallucination() ) {
dealt_dam.bp_hit = anatomy_human_anatomy->random_body_part();
return;
}
dam = source->modify_damage_dealt_with_enchantments( dam );
// If carrying a rider, there is a chance the hits may hit rider instead.
// melee attack will start off as targeted at mount
if( has_effect( effect_ridden ) ) {
monster *mons = dynamic_cast<monster *>( this );
if( mons && mons->mounted_player ) {
if( !mons->has_flag( mon_flag_MECH_DEFENSIVE ) &&
one_in( std::max( 2, mons->get_size() - mons->mounted_player->get_size() ) ) ) {
mons->mounted_player->deal_melee_hit( source, hit_spread, critical_hit, dam, dealt_dam, attack );
return;
}
}
}
damage_instance d = dam; // copy, since we will mutate in block_hit
bodypart_id bp_hit = bp == nullptr ? select_body_part( this, -1, -1, source->can_attack_high(),
hit_spread ) : *bp;
block_hit( source, bp_hit, d );
weakpoint_attack attack_copy = attack;
attack_copy.is_crit = critical_hit;
attack_copy.type = weakpoint_attack::type_of_melee_attack( d );
on_hit( &here, source, bp_hit ); // trigger on-gethit events
dam.onhit_effects( source, this ); // on-hit effects for inflicted damage types
dealt_dam = deal_damage( source, bp_hit, d, attack_copy );
dealt_dam.bp_hit = bp_hit;
}
double Creature::accuracy_projectile_attack( const int &speed, const double &missed_by ) const
{
const int avoid_roll = dodge_roll();
// Do dice(10, speed) instead of dice(speed, 10) because speed could potentially be > 10000
const int diff_roll = dice( 10, speed );
// Partial dodge, capped at [0.0, 1.0], added to missed_by
const double dodge_rescaled = avoid_roll / static_cast<double>( diff_roll );
return missed_by + std::max( 0.0, std::min( 1.0, dodge_rescaled ) );
}
void projectile::apply_effects_damage( Creature &target, Creature *source,
const dealt_damage_instance &dealt_dam, bool critical ) const
{
const map &here = get_map();
int dam = dealt_dam.total_damage();
// Apply ammo effects to target.
if( proj_effects.count( ammo_effect_TANGLE ) ) {
// if its a tameable animal, its a good way to catch them if they are running away, like them ranchers do!
// we assume immediate success, then certain monster types immediately break free in monster.cpp move_effects()
if( target.is_monster() ) {
const item &drop_item = get_drop();
if( !drop_item.is_null() ) {
target.add_effect( effect_source( source ), effect_tied, 1_turns, true );
target.as_monster()->tied_item = cata::make_value<item>( drop_item );
} else {
add_msg_debug( debugmode::DF_CREATURE,
"projectile with TANGLE effect, but no drop item specified" );
}
} else if( ( target.is_npc() || target.is_avatar() ) &&
!target.is_immune_effect( effect_downed ) ) {
// no tied up effect for people yet, just down them and stun them, its close enough to the desired effect.
// we can assume a person knows how to untangle their legs eventually and not panic like an animal.
target.add_effect( effect_source( source ), effect_downed, 1_turns );
// stunned to simulate staggering around and stumbling trying to get the entangled thing off of them.
target.add_effect( effect_source( source ), effect_stunned, rng( 3_turns, 8_turns ) );
}
}
Character &player_character = get_player_character();
int amount = dam > 2 ? dam / 2 : one_in( 2 );
if( proj_effects.count( ammo_effect_INCENDIARY ) ) {
if( x_in_y( amount, 50 ) ) { // 1% chance for 1 damamge
if( target.made_of( material_vegetable ) || target.made_of_any( Creature::cmat_flammable ) ) {
target.add_effect( effect_source( source ), effect_onfire, rng( 2_turns, 6_turns ) * amount,
dealt_dam.bp_hit );
} else if( target.made_of_any( Creature::cmat_flesh ) && one_in( 4 ) ) {
target.add_effect( effect_source( source ), effect_onfire, rng( 1_turns, 2_turns ) * amount,
dealt_dam.bp_hit );
}
if( player_character.has_trait( trait_PYROMANIA ) &&
!player_character.has_morale( morale_pyromania_startfire ) &&
player_character.sees( here, target ) ) {
player_character.add_msg_if_player( m_good,
_( "You feel a surge of euphoria as flame engulfs %s!" ), target.get_name() );
player_character.add_morale( morale_pyromania_startfire, 15, 15, 8_hours, 6_hours );
player_character.rem_morale( morale_pyromania_nofire );
}
}
} else if( proj_effects.count( ammo_effect_IGNITE ) ) {
if( x_in_y( 1, 2 ) ) { // 50% chance
if( target.made_of( material_vegetable ) || target.made_of_any( Creature::cmat_flammable ) ) {
target.add_effect( effect_source( source ), effect_onfire, 10_turns * amount, dealt_dam.bp_hit );
} else if( target.made_of_any( Creature::cmat_flesh ) ) {
target.add_effect( effect_source( source ), effect_onfire, 6_turns * amount, dealt_dam.bp_hit );
}
if( player_character.has_trait( trait_PYROMANIA ) &&
!player_character.has_morale( morale_pyromania_startfire ) &&
player_character.sees( here, target ) ) {
player_character.add_msg_if_player( m_good,
_( "You feel a surge of euphoria as flame engulfs %s!" ), target.get_name() );
player_character.add_morale( morale_pyromania_startfire, 15, 15, 8_hours, 6_hours );
player_character.rem_morale( morale_pyromania_nofire );
}
}
}
if( proj_effects.count( ammo_effect_ROBOT_DAZZLE ) ) {
if( critical && target.in_species( species_ROBOT ) ) {
time_duration duration = rng( 6_turns, 8_turns );
target.add_effect( effect_source( source ), effect_stunned, duration );
target.add_effect( effect_source( source ), effect_sensor_stun, duration );
add_msg( source->is_avatar() ?
_( "You land a clean shot on the %1$s sensors, stunning it." ) :
_( "The %1$s is stunned!" ),
target.disp_name( true ) );
}
}
if( dealt_dam.bp_hit->has_type( body_part_type::type::head ) &&
proj_effects.count( ammo_effect_BLINDS_EYES ) ) {
// TODO: Change this to require bp_eyes
target.add_env_effect( effect_blind,
target.get_random_body_part_of_type( body_part_type::type::sensor ), 5, rng( 3_turns, 10_turns ) );
}
if( proj_effects.count( ammo_effect_APPLY_SAP ) ) {
target.add_effect( effect_source( source ), effect_sap, 1_turns * dam );
}
if( proj_effects.count( ammo_effect_PARALYZEPOISON ) && dam > 0 &&
!dealt_dam.bp_hit->has_flag( json_flag_BIONIC_LIMB ) ) {
target.add_msg_if_player( m_bad, _( "You feel poison coursing through your body!" ) );
target.add_effect( effect_source( source ), effect_paralyzepoison, 5_minutes );
}
if( proj_effects.count( ammo_effect_FOAMCRETE ) && effect_foamcrete_slow.is_valid() ) {
target.add_msg_if_player( m_bad, _( "The foamcrete stiffens around you!" ) );
target.add_effect( effect_source( source ), effect_foamcrete_slow, 5_minutes );
}
int stun_strength = 0;
if( proj_effects.count( ammo_effect_BEANBAG ) ) {
stun_strength = 4;
}
if( proj_effects.count( ammo_effect_LARGE_BEANBAG ) ) {
stun_strength = 16;
}
if( stun_strength > 0 ) {
switch( target.get_size() ) {
case creature_size::tiny:
stun_strength *= 4;
break;
case creature_size::small:
stun_strength *= 2;
break;
case creature_size::medium:
default:
break;
case creature_size::large:
stun_strength /= 2;
break;
case creature_size::huge:
stun_strength /= 4;
break;
}
target.add_effect( effect_source( source ), effect_stunned,
1_turns * rng( stun_strength / 2, stun_strength ) );
}
}
struct projectile_attack_results {
int max_damage;
std::string message;
game_message_type gmtSCTcolor = m_neutral;
double damage_mult = 1.0;
bodypart_id bp_hit;
std::string wp_hit;
bool is_crit = false;
bool is_headshot = false;
const weakpoint *wp;
explicit projectile_attack_results( const projectile &proj ) {
max_damage = proj.impact.total_damage();
}
};
projectile_attack_results Creature::select_body_part_projectile_attack(
const projectile &proj, const double goodhit, const bool magic,
const double missed_by, const weakpoint_attack &attack ) const
{
projectile_attack_results ret( proj );
const float crit_multiplier = proj.critical_multiplier;
const float std_hit_mult = std::sqrt( 2.0 * crit_multiplier );
bool fatal_hit = false;
double hit_roll = rng_float( goodhit, 1.0 );
// 40% true when goodhit = 0, 20% true when goodhit = 0.2
bool crit_roll = hit_roll * 0.5 < accuracy_critical;
const monster *mon = as_monster();
if( mon ) {
fatal_hit = ret.max_damage * crit_multiplier > get_hp_max();
ret.wp = mon->type->weakpoints.select_weakpoint( attack );
crit_roll &= ret.wp->is_good && !ret.wp->id.empty();
ret.is_headshot = !has_flag( mon_flag_NOHEAD ) && ret.wp->is_head;
} else {
double hit_value = missed_by + rng_float( -0.5, 0.5 );
if( magic ) {
// We want spells to hit all bodyparts randomly, not only torso
// It still gonna be torso mainly
hit_value = rng_float( -0.5, 1.5 );
}
// Range is -0.5 to 1.5 -> missed_by will be [1, 0], so the rng addition to it
// will push it to at most 1.5 and at least -0.5
ret.bp_hit = get_anatomy()->select_body_part_projectile_attack( -0.5, 1.5, hit_value );
fatal_hit = ret.max_damage * crit_multiplier > get_hp_max( ret.bp_hit );
ret.is_headshot = ret.bp_hit.id() == body_part_head;
}
if( magic ) {
// do nothing special, no damage mults, nothing
} else if( goodhit < accuracy_headshot && ( ret.is_headshot || fatal_hit ) ) {
ret.message = _( "Critical!!" );
ret.gmtSCTcolor = m_headshot;
// ( 0.95, 1.05 ) when goodhit = 0, ( 0.95, 1.04 ) when nears 0.1
ret.damage_mult *= 0.6 + 0.45 - 0.1 * hit_roll;
ret.damage_mult *= std_hit_mult + ( crit_multiplier - std_hit_mult );
ret.is_crit = true;
} else if( goodhit < accuracy_critical && ( crit_roll || fatal_hit ) ) {
ret.message = _( "Critical!" );
ret.gmtSCTcolor = m_critical;
// ( 0.75, 1.0 ) when goodhit = 0, ( 0.75, 0.95 ) when nears 0.2
ret.damage_mult *= 0.75 + 0.25 - 0.25 * hit_roll;
ret.damage_mult *= std_hit_mult + ( crit_multiplier - std_hit_mult );
ret.is_crit = true;
} else if( goodhit < accuracy_goodhit ) {
ret.message = _( "Good hit!" );
ret.gmtSCTcolor = m_good;
// ( 0.5, 1.0 ) when goodhit = 0, ( 0.5, 0.75 ) when nears 0.5
ret.damage_mult *= 1.0 - 0.5 * hit_roll;
ret.damage_mult *= std_hit_mult;
} else if( goodhit < accuracy_standard ) {
// ( 0.5, 1.0 ) when goodhit = 0.5, ( 0.5, 0.7 ) when nears 0.8
ret.damage_mult *= 1.5 - hit_roll;
} else if( goodhit < accuracy_grazing ) {
ret.message = _( "Grazing hit." );
ret.gmtSCTcolor = m_grazing;
// ( 0.05, 0.25 ) when goodhit = 0.8, 0.05 when nears 1.0
ret.damage_mult *= 1.05 - hit_roll;
}
add_msg_debug( debugmode::DF_CREATURE, "crit_damage_mult: %f", ret.damage_mult );
return ret;
}
void Creature::messaging_projectile_attack( const Creature *source,
const projectile_attack_results &hit_selection, const int total_damage ) const
{
const map &here = get_map();
const tripoint_bub_ms pos = pos_bub( here );
const tripoint_bub_ms source_pos = source->pos_bub( here );
const viewer &player_view = get_player_view();
const bool u_see_this = player_view.sees( here, *this );
if( u_see_this ) {
if( hit_selection.damage_mult == 0 ) {
if( source != nullptr ) {
add_msg( m_bad, source->is_avatar() ? _( "You miss!" ) : _( "The shot misses!" ) );
}
} else if( total_damage == 0 ) {
if( hit_selection.wp_hit.empty() ) {
//~ 1$ - monster name, 2$ - character's bodypart or monster's skin/armor
add_msg( m_bad, _( "The shot reflects off %1$s %2$s!" ), disp_name( true ),
is_monster() ?
skin_name() :
body_part_name_accusative( hit_selection.bp_hit ) );
} else {
//~ %1$s: creature name, %2$s: weakpoint hit
add_msg( m_bad, _( "The shot hits %1$s in %2$s but deals no damage." ),
disp_name(), hit_selection.wp_hit );
}
} else if( is_avatar() ) {
//monster hits player ranged
//~ Hit message. 1$s is bodypart name in accusative. 2$d is damage value.
add_msg_if_player( m_bad, _( "You were hit in the %1$s for %2$d damage." ),
body_part_name_accusative( hit_selection.bp_hit ),
total_damage );
} else if( source != nullptr ) {
if( source->is_avatar() ) {
//player hits monster ranged
SCT.add( pos.xy().raw(),
direction_from( point::zero, point( pos.x() - source_pos.x(), pos.y() - source_pos.y() ) ),
get_hp_bar( total_damage, get_hp_max(), true ).first,
m_good, hit_selection.message, hit_selection.gmtSCTcolor );
if( get_hp() > 0 ) {
SCT.add( pos.xy().raw(),
direction_from( point::zero, point( pos.x() - source_pos.x(), pos.y() - source_pos.y() ) ),
get_hp_bar( get_hp(), get_hp_max(), true ).first, m_good,
//~ "hit points", used in scrolling combat text
_( "HP" ), m_neutral, "hp" );
} else {
SCT.removeCreatureHP();
}
// Move it here to show crit msg only when you actually hurt the target
add_msg( m_good, hit_selection.message );
if( hit_selection.wp_hit.empty() ) {
//~ %1$s: creature name, %2$d: damage value
add_msg( m_good, _( "You hit %1$s for %2$d damage." ),
disp_name(), total_damage );
} else {
//~ %1$s: creature name, %2$s: weakpoint hit, %3$d: damage value
add_msg( m_good, _( "You hit %1$s in %2$s for %3$d damage." ),
disp_name(), hit_selection.wp_hit, total_damage );
}
} else if( source != this ) {
if( hit_selection.wp_hit.empty() ) {
//~ 1$ - shooter, 2$ - target
add_msg( _( "%1$s shoots %2$s." ),
source->disp_name(), disp_name() );
} else {
//~ 1$ - shooter, 2$ - target, 3$ - weakpoint
add_msg( _( "%1$s shoots %2$s in %3$s." ),
source->disp_name(), disp_name(), hit_selection.wp_hit );
}
}
}
}
}
void Creature::print_proj_avoid_msg( Creature *source, viewer &player_view ) const
{
const map &here = get_map();
// "Avoid" rather than "dodge", because it includes removing self from the line of fire
// rather than just Matrix-style bullet dodging
if( source != nullptr && player_view.sees( here, *source ) ) {
add_msg_player_or_npc(
m_warning,
_( "You avoid %s projectile!" ),
get_option<bool>( "LOG_MONSTER_ATTACK_MONSTER" ) ? _( "<npcname> avoids %s projectile." ) : "",
source->disp_name( true ) );
} else {
add_msg_player_or_npc(
m_warning,
_( "You avoid an incoming projectile!" ),
get_option<bool>( "LOG_MONSTER_ATTACK_MONSTER" ) ? _( "<npcname> avoids an incoming projectile." ) :
"" );
}
}
/**
* Attempts to harm a creature with a projectile.
*
* @param source Pointer to the creature who shot the projectile.
* @param attack A structure describing the attack and its results.
* @param print_messages enables message printing by default.
*/
void Creature::deal_projectile_attack( map *here, Creature *source, dealt_projectile_attack &attack,
const double &missed_by, bool print_messages,
const weakpoint_attack &wp_attack )
{
const bool magic = attack.proj.proj_effects.count( ammo_effect_MAGIC ) > 0;
if( missed_by >= 1.0 && !magic ) {
// Total miss
return;
}
// If carrying a rider, there is a chance the hits may hit rider instead.
if( has_effect( effect_ridden ) ) {
monster *mons = as_monster();
if( mons && mons->mounted_player ) {
if( !mons->has_flag( mon_flag_MECH_DEFENSIVE ) &&
one_in( std::max( 2, mons->get_size() - mons->mounted_player->get_size() ) ) ) {
mons->mounted_player->deal_projectile_attack( here, source, attack, missed_by, print_messages,
wp_attack );
return;
}
}
}
const projectile &proj = attack.proj;
dealt_damage_instance &dealt_dam = attack.dealt_dam;
const auto &proj_effects = proj.proj_effects;
viewer &player_view = get_player_view();
Character *guy = as_character();
if( guy ) {
double range_dodge_chance = guy->enchantment_cache->modify_value( enchant_vals::mod::RANGE_DODGE,
1.0f ) - 1.0f;
if( x_in_y( range_dodge_chance, 1.0f ) ) {
on_try_dodge();
print_proj_avoid_msg( source, player_view );
return;
}
}
const bool can_dodge = !magic && attack.proj.speed < 20 &&
( !guy || guy->can_try_dodge().success() );
double goodhit = can_dodge ?
accuracy_projectile_attack( attack.proj.speed, missed_by ) :
missed_by;
// We only trigger a dodge attempt if it's a relatively slow projectile.
if( can_dodge ) {
on_try_dodge(); // There's a dodge roll in accuracy_projectile_attack()
}
if( goodhit >= 1.0 ) {
if( !print_messages ) {
return;
}
print_proj_avoid_msg( source, player_view );
return;
}
// Create a copy that records whether the attack is a crit.
weakpoint_attack wp_attack_copy = wp_attack;
wp_attack_copy.type = weakpoint_attack::attack_type::PROJECTILE;
wp_attack_copy.source = attack.shrapnel ? nullptr : source;
wp_attack_copy.target = this;
wp_attack_copy.accuracy = goodhit;
wp_attack_copy.compute_wp_skill();
projectile_attack_results hit_selection = select_body_part_projectile_attack( proj, goodhit,
magic, missed_by, wp_attack_copy );
wp_attack_copy.is_crit = hit_selection.is_crit;
// copy it, since we're mutating.
// use shot_impact after point-blank
damage_instance impact = proj.multishot ? proj.shot_impact : proj.impact;
if( hit_selection.damage_mult > 0.0f && proj_effects.count( ammo_effect_NO_DAMAGE_SCALING ) ) {
hit_selection.damage_mult = 1.0f;
}
impact.mult_damage( hit_selection.damage_mult );
if( proj_effects.count( ammo_effect_NOGIB ) > 0 ) {
float dmg_ratio = static_cast<float>( impact.total_damage() ) / get_hp_max( hit_selection.bp_hit );
if( dmg_ratio > 1.25f ) {
impact.mult_damage( 1.0f / dmg_ratio );
}
}
dealt_dam = deal_damage( source, hit_selection.bp_hit, impact, wp_attack_copy, *hit_selection.wp );
// Force damage instance to match the selected body point
dealt_dam.bp_hit = hit_selection.bp_hit;
// Retrieve the selected weakpoint from the damage instance.
hit_selection.wp_hit = dealt_dam.wp_hit;
proj.apply_effects_damage( *this, source, dealt_dam, goodhit < accuracy_critical );
int total_dam = dealt_dam.total_damage();
if( print_messages ) {
messaging_projectile_attack( source, hit_selection, total_dam );
}
check_dead_state( here );
attack.last_hit_critter = this;
attack.missed_by = goodhit;
attack.headshot = hit_selection.is_headshot;
attack.targets_hit[this].first++;
if( total_dam > 0 ) {
attack.targets_hit[this].second += total_dam;
}
}
dealt_damage_instance Creature::deal_damage( Creature *source, bodypart_id bp,
const damage_instance &dam, const weakpoint_attack &attack, const weakpoint &wp )
{
if( is_dead_state() || has_effect_with_flag( json_flag_CANNOT_TAKE_DAMAGE ) ) {
return dealt_damage_instance();
}
int total_damage = 0;
int total_base_damage = 0;
int total_pain = 0;
damage_instance d = dam; // copy, since we will mutate in absorb_hit
dealt_damage_instance dealt_dams;
weakpoint_attack attack_copy = attack;
if( attack.accuracy == -1.0 ) {
attack_copy.source = source;
attack_copy.target = this;
attack_copy.compute_wp_skill();
}
const weakpoint *wkpt = absorb_hit( attack_copy, bp, d, wp );
dealt_dams.wp_hit = wkpt == nullptr ? "" : wkpt->get_name();
// Add up all the damage units dealt
for( const damage_unit &it : d.damage_units ) {
int cur_damage = 0;
deal_damage_handle_type( effect_source( source ), it, bp, cur_damage, total_pain );
total_base_damage += std::max( 0.0f, it.amount * it.unconditional_damage_mult );
if( cur_damage > 0 ) {
dealt_dams.dealt_dams[it.type] += cur_damage;
total_damage += cur_damage;
}
}
// get eocs for all damage effects
d.ondamage_effects( source, this, dam, bp.id() );
if( total_base_damage < total_damage ) {
// Only deal more HP than remains if damage not including crit multipliers is higher.
total_damage = clamp( get_hp( bp ), total_base_damage, total_damage );
}
if( !bp->has_flag( json_flag_BIONIC_LIMB ) ) {
mod_pain( total_pain );
}
apply_damage( source, bp, total_damage );
if( wkpt != nullptr ) {
wkpt->apply_effects( *this, total_damage, attack );
}
return dealt_dams;
}
void Creature::deal_damage_handle_type( const effect_source &source, const damage_unit &du,
bodypart_id bp, int &damage, int &pain )
{
const map &here = get_map();
// Handles ACIDPROOF, electric immunity etc.
if( is_immune_damage( du.type ) ) {
return;
}
// Apply damage multiplier from skill, critical hits or grazes after all other modifications.
const int adjusted_damage = du.amount * du.damage_multiplier * du.unconditional_damage_mult;
if( adjusted_damage <= 0 ) {
return;
}
float div = 4.0f;
// FIXME: Hardcoded damage types
if( du.type == damage_bash ) {
// Bashing damage is less painful
div = 5.0f;
} else if( du.type == damage_heat ) {
// heat damage sets us on fire sometimes
if( rng( 0, 100 ) < adjusted_damage ) {
add_effect( source, effect_onfire, rng( 1_turns, 3_turns ), bp );
Character &player_character = get_player_character();
if( player_character.has_trait( trait_PYROMANIA ) &&
!player_character.has_morale( morale_pyromania_startfire ) &&
player_character.sees( here, *this ) ) {
player_character.add_msg_if_player( m_good,
_( "You feel a surge of euphoria as flame engulfs %s!" ), this->get_name() );
player_character.add_morale( morale_pyromania_startfire, 15, 15, 8_hours, 6_hours );
player_character.rem_morale( morale_pyromania_nofire );
}
}
} else if( du.type == damage_electric ) {
// Electrical damage adds a major speed/dex debuff
double multiplier = 1.0;
if( monster *mon = as_monster() ) {
multiplier = mon->type->status_chance_multiplier;
}
const int chance = std::log10( ( adjusted_damage + 2 ) * 0.5 ) * 100 * multiplier;
if( x_in_y( chance, 100 ) ) {
const int duration = std::max( adjusted_damage / 10.0 * multiplier, 2.0 );
add_effect( source, effect_zapped, 1_turns * duration );
}
if( Character *ch = as_character() ) {
const double pain_mult = ch->calculate_by_enchantment( 1.0, enchant_vals::mod::EXTRA_ELEC_PAIN );
div /= pain_mult;
if( pain_mult > 1.0 ) {
ch->add_msg_player_or_npc( m_bad, _( "You're painfully electrocuted!" ),
_( "<npcname> is shocked!" ) );
}
}
} else if( du.type == damage_acid ) {
// Acid damage and acid burns are more painful
div = 3.0f;
}
on_damage_of_type( source, adjusted_damage, du.type, bp );
damage += adjusted_damage;
pain += roll_remainder( adjusted_damage / div );
}
void Creature::heal_bp( bodypart_id /* bp */, int /* dam */ )
{
}
void Creature::longpull( const std::string &name, const tripoint_bub_ms &p )
{
const map &here = get_map();
if( pos_bub( here ) == p ) {
add_msg_if_player( _( "You try to pull yourself together." ) );
return;
}
std::vector<tripoint_bub_ms> path = line_to( pos_bub( here ), p, 0, 0 );
Creature *c = nullptr;
for( const tripoint_bub_ms &path_p : path ) {
c = get_creature_tracker().creature_at( path_p );
if( c == nullptr && here.impassable( path_p ) ) {
add_msg_if_player( m_warning, _( "There's an obstacle in the way!" ) );
return;
}
if( c != nullptr ) {
break;
}
}
if( c == nullptr || !sees( here, *c ) ) {
// TODO: Latch onto objects?
add_msg_if_player( m_warning, _( "There's nothing here to latch onto with your %s!" ),
name );
return;
}
// Pull creature
const Character *ch = as_character();
const monster *mon = as_monster();
const int str = ch != nullptr ? ch->get_str() : mon != nullptr ? mon->get_grab_strength() : 10;
const int odds = units::to_kilogram( c->get_weight() ) / ( str * 3 );
if( one_in( clamp<int>( odds * odds, 1, 1000 ) ) ) {
add_msg_if_player( m_good, _( "You pull %1$s towards you with your %2$s!" ), c->disp_name(),
name );
if( c->is_avatar() ) {
add_msg( m_warning, _( "%1$s pulls you in with their %2$s!" ), disp_name( false, true ), name );
}
c->move_to( tripoint_abs_ms( line_to( pos_abs().raw(), c->pos_abs().raw(), 0,
0 ).front() ) );
c->add_effect( effect_stunned, 1_seconds );
sounds::sound( c->pos_bub( here ), 5, sounds::sound_t::combat, _( "Shhhk!" ) );
} else {
add_msg_if_player( m_bad, _( "%s weight makes it difficult to pull towards you." ),
c->disp_name( true, true ) );
if( c->is_avatar() ) {
add_msg( m_info, _( "%1s tries to pull you in, but you resist!" ), disp_name( false, true ) );
}
}
}
bool Creature::grapple_drag( Creature *c )
{
const Character *ch = as_character();
const monster *mon = as_monster();
const int str = ch != nullptr ? ch->get_str() : mon != nullptr ? mon->get_grab_strength() : 10;
// Medium is 3.
int your_size = static_cast<std::underlying_type_t<creature_size>>( get_size() );
const int odds = units::to_kilogram( c->get_weight() ) / ( str * your_size );
if( one_in( clamp<int>( odds * odds, 1, 1000 ) ) ) {
return true;
} else {
add_msg_if_player( m_bad, _( "You strain to drag %s." ),
c->disp_name() );
if( c->is_avatar() ) {
add_msg( m_info, _( "%1s fails to drag you." ), disp_name( false, true ) );
}
return false;
}
return false;
}
bool Creature::stumble_invis( const Creature &player, const bool stumblemsg )
{
map &here = get_map();
// DEBUG insivibility can't be seen through
if( player.has_trait( trait_DEBUG_CLOAK ) ) {
return false;
}
if( this == &player || !is_adjacent( &player, true ) ) {
return false;
}
if( stumblemsg ) {
const bool player_sees = player.sees( here, *this );
add_msg( m_bad, _( "%s stumbles into you!" ), player_sees ? this->disp_name( false,
true ) : _( "Something" ) );
}
add_effect( effect_stumbled_into_invisible, 6_seconds );
// Mark last known location, or extend duration if exists
if( here.has_field_at( player.pos_bub( here ), field_fd_last_known ) ) {
here.set_field_age( player.pos_bub( here ), field_fd_last_known, 0_seconds );
} else {
here.add_field( player.pos_bub( here ), field_fd_last_known );
}
moves = 0;
return true;
}
bool Creature::attack_air( const tripoint_bub_ms &p )
{
// Calculate move cost differently for monsters and npcs
int move_cost = 100;
if( is_monster() ) {
move_cost = as_monster()->type->attack_cost;
} else if( is_npc() ) {
// Simplified moves calculation from Character::melee_attack_abstract
item_location cur_weapon = as_character()->used_weapon();
item cur_weap = cur_weapon ? *cur_weapon : null_item_reference();
move_cost = as_character()->attack_speed( cur_weap ) * ( 1 /
as_character()->exertion_adjusted_move_multiplier( EXPLOSIVE_EXERCISE ) );
as_character()->set_activity_level( EXPLOSIVE_EXERCISE );
}
mod_moves( -move_cost );
// Attack animation
if( get_option<bool>( "ANIMATIONS" ) ) {
std::map<tripoint_bub_ms, nc_color> area_color;
area_color[ p ] = c_black;
explosion_handler::draw_custom_explosion( area_color, "animation_hit" );
}
// Chance to remove last known location
if( one_in( 2 ) ) {
get_map().set_field_intensity( p, field_fd_last_known, 0 );
}
add_msg_if_player_sees( *this, _( "%s attacks, but there is nothing there!" ),
disp_name( false, true ) );
return true;
}
bool Creature::dodge_check( float hit_roll, bool force_try, float )
{
// If successfully uncanny dodged, no need to calculate dodge chance
if( uncanny_dodge() ) {
return true;
}
const float dodge_ability = dodge_roll();
// center is 5 - 0 / 2
// stddev is 5 - 0 / 4
const float dodge_chance = 1 - normal_roll_chance( 2.5f, 1.25f, dodge_ability - hit_roll );
if( dodge_chance >= 0.8f || force_try ) {
on_try_dodge();
float attack_roll = hit_roll + rng_normal( 0, 5 );
return dodge_ability > attack_roll;
}
return false;
}
bool Creature::dodge_check( monster *z, float training_level )
{
return dodge_check( z->get_hit(), training_level );
}
bool Creature::dodge_check( monster *z, bodypart_id bp, const damage_instance &dam_inst,
float training_level )
{
if( is_monster() ) {
return dodge_check( z );
}
Character *guy_target = as_character();
float potential_damage = 0.0f;
for( const damage_unit &dmg : dam_inst.damage_units ) {
potential_damage += dmg.amount - guy_target->worn.damage_resist( dmg.type, bp );
}
int part_hp = guy_target->get_part_hp_cur( bp );
float dmg_ratio = 0.0f; // if the part is already destroyed it can't take more damage
if( part_hp > 0 ) {
dmg_ratio = potential_damage / part_hp;
}
//If attack might remove more than half of the part's hp, dodge no matter the odds
if( dmg_ratio >= 0.5f ) {
return dodge_check( z->get_hit(), true, training_level );
} else if( dmg_ratio > 0.0f ) { // else apply usual rules
return dodge_check( z->get_hit(), training_level );
}
return false;
}
/*
* State check functions
*/
bool Creature::is_warm() const
{
return true;
}
bool Creature::in_species( const species_id & ) const
{
return false;
}
bool Creature::is_fake() const
{
return fake;
}
void Creature::set_fake( const bool fake_value )
{
fake = fake_value;
}
void Creature::add_effect( const effect_source &source, const effect &eff, bool force,
bool deferred )
{
add_effect( source, eff.get_id(), eff.get_duration(), eff.get_bp(), eff.is_permanent(),
eff.get_intensity(), force, deferred );
}
void Creature::add_effect( const effect_source &source, const efftype_id &eff_id,
const time_duration &dur, bodypart_id bp, bool permanent, int intensity, bool force, bool deferred )
{
// Check our innate immunity
if( !force && is_immune_effect( eff_id ) ) {
return;
}
if( eff_id == effect_knockdown && ( has_effect( effect_ridden ) ||
has_effect( effect_riding ) ) ) {
monster *mons = dynamic_cast<monster *>( this );
if( mons && mons->mounted_player ) {
mons->mounted_player->forced_dismount();
}
}
if( !eff_id.is_valid() ) {
debugmsg( "Invalid effect, ID: %s", eff_id.c_str() );
return;
}
const effect_type &type = eff_id.obj();
// Mutate to a main (HP'd) body_part if necessary.
if( type.get_main_parts() ) {
bp = bp->main_part;
}
// Filter out bodypart immunity
for( json_character_flag flag : eff_id->immune_bp_flags ) {
if( bp->has_flag( flag ) ) {
return;
}
}
// Then check if the effect is blocked by another
for( auto &elem : *effects ) {
for( auto &_effect_it : elem.second ) {
for( const auto &blocked_effect : _effect_it.second.get_blocks_effects() ) {
if( blocked_effect == eff_id ) {
// The effect is blocked by another, return
return;
}
}
}
}
bool found = false;
// Check if we already have it
auto matching_map = effects->find( eff_id );
if( matching_map != effects->end() ) {
auto &bodyparts = matching_map->second;
auto found_effect = bodyparts.find( bp );
if( found_effect != bodyparts.end() ) {
found = true;
effect &e = found_effect->second;
const int prev_int = e.get_intensity();
// If we do, mod the duration, factoring in the mod value
e.mod_duration( dur * e.get_dur_add_perc() / 100 );
// Limit to max duration
if( e.get_duration() > e.get_max_duration() ) {
e.set_duration( e.get_max_duration() );
}
// Adding a permanent effect makes it permanent
if( e.is_permanent() ) {
e.pause_effect();
}
// int_dur_factor overrides all other intensity settings
// ...but it's handled in set_duration, so explicitly do nothing here
if( e.get_int_dur_factor() > 0_turns ) {
// Set intensity if value is given
} else if( intensity > 0 ) {
e.set_intensity( intensity, is_avatar() );
// Else intensity uses the type'd step size if it already exists
} else if( e.get_int_add_val() != 0 ) {
e.mod_intensity( e.get_int_add_val(), is_avatar() );
}
// Bound intensity by [1, max intensity]
if( e.get_intensity() < 1 ) {
add_msg_debug( debugmode::DF_CREATURE, "Bad intensity, ID: %s", e.get_id().c_str() );
e.set_intensity( 1 );
} else if( e.get_intensity() > e.get_max_intensity() ) {
e.set_intensity( e.get_max_intensity() );
}
if( e.get_intensity() != prev_int ) {
on_effect_int_change( eff_id, e.get_intensity(), bp );
}
}
}
if( !found ) {
// If we don't already have it then add a new one
// Now we can make the new effect for application
effect e( effect_source( source ), &type, dur, bp.id(), permanent, intensity, calendar::turn );
// Bound to max duration
if( e.get_duration() > e.get_max_duration() ) {
e.set_duration( e.get_max_duration() );
}
// Force intensity if it is duration based
if( e.get_int_dur_factor() != 0_turns ) {
const int intensity = std::ceil( e.get_duration() / e.get_int_dur_factor() );
e.set_intensity( std::max( 1, intensity ) );
}
// Bound new effect intensity by [1, max intensity]
if( e.get_intensity() < 1 ) {
add_msg_debug( debugmode::DF_CREATURE, "Bad intensity, ID: %s", e.get_id().c_str() );
e.set_intensity( 1 );
} else if( e.get_intensity() > e.get_max_intensity() ) {
e.set_intensity( e.get_max_intensity() );
}
( *effects )[eff_id][bp] = e;
if( Character *ch = as_character() ) {
get_event_bus().send<event_type::character_gains_effect>( ch->getID(), bp.id(), eff_id );
if( is_avatar() ) {
eff_id->add_apply_msg( e.get_intensity() );
}
}
on_effect_int_change( eff_id, e.get_intensity(), bp );
// Perform any effect addition effects.
// only when not deferred
if( !deferred ) {
process_one_effect( e, true );
}
}
}
void Creature::add_effect( const effect_source &source, const efftype_id &eff_id,
const time_duration &dur, bool permanent, int intensity, bool force, bool deferred )
{
add_effect( source, eff_id, dur, bodypart_str_id::NULL_ID(), permanent, intensity, force,
deferred );
}
void Creature::schedule_effect( const effect &eff, bool force, bool deferred )
{
scheduled_effects.push( scheduled_effect{eff.get_id(), eff.get_duration(), eff.get_bp(),
eff.is_permanent(), eff.get_intensity(), force,
deferred} );
}
void Creature::schedule_effect( const efftype_id &eff_id, const time_duration &dur, bodypart_id bp,
bool permanent, int intensity, bool force, bool deferred )
{
scheduled_effects.push( scheduled_effect{eff_id, dur, bp,
permanent, intensity, force,
deferred} );
}
void Creature::schedule_effect( const efftype_id &eff_id,
const time_duration &dur, bool permanent, int intensity, bool force,
bool deferred )
{
scheduled_effects.push( scheduled_effect{eff_id, dur, bodypart_str_id::NULL_ID(),
permanent, intensity, force, deferred} );
}
bool Creature::add_env_effect( const efftype_id &eff_id, const bodypart_id &vector, int strength,
const time_duration &dur, const bodypart_id &bp, bool permanent, int intensity, bool force )
{
if( !force && is_immune_effect( eff_id ) ) {
return false;
}
if( dice( strength, 3 ) > dice( get_env_resist( vector ), 3 ) ) {
// Only add the effect if we fail the resist roll
// Don't check immunity (force == true), because we did check above
add_effect( effect_source::empty(), eff_id, dur, bp, permanent, intensity, true );
return true;
} else {
return false;
}
}
bool Creature::add_env_effect( const efftype_id &eff_id, const bodypart_id &vector, int strength,
const time_duration &dur, bool permanent, int intensity, bool force )
{
return add_env_effect( eff_id, vector, strength, dur, bodypart_str_id::NULL_ID(), permanent,
intensity, force );
}
bool Creature::add_liquid_effect( const efftype_id &eff_id, const bodypart_id &vector, int strength,
const time_duration &dur, const bodypart_id &bp, bool permanent, int intensity, bool force )
{
if( !force && is_immune_effect( eff_id ) ) {
return false;
}
if( is_monster() ) {
if( dice( strength, 3 ) > dice( get_env_resist( vector ), 3 ) ) {
//Monsters don't have clothing wetness multipliers, so we still use enviro for them.
add_effect( effect_source::empty(), eff_id, dur, bodypart_str_id::NULL_ID(), permanent, intensity,
true );
return true;
} else {
return false;
}
}
const Character *c = as_character();
//d100 minus strength should never be less than 1 so we don't have liquids phasing through sealed power armor.
if( std::max( dice( 1, 100 ) - strength,
1 ) < ( c->worn.clothing_wetness_mult( vector ) * 100 ) ) {
// Don't check immunity (force == true), because we did check above
add_effect( effect_source::empty(), eff_id, dur, bp, permanent, intensity, true );
return true;
} else {
return false;
}
}
bool Creature::add_liquid_effect( const efftype_id &eff_id, const bodypart_id &vector, int strength,
const time_duration &dur, bool permanent, int intensity, bool force )
{
return add_liquid_effect( eff_id, vector, strength, dur, bodypart_str_id::NULL_ID(), permanent,
intensity, force );
}
void Creature::clear_effects()
{
for( auto &elem : *effects ) {
for( auto &_effect_it : elem.second ) {
const effect &e = _effect_it.second;
on_effect_int_change( e.get_id(), 0, e.get_bp() );
}
}
effects->clear();
}
bool Creature::remove_effect( const efftype_id &eff_id, const bodypart_id &bp )
{
if( !has_effect( eff_id, bp.id() ) ) {
//Effect doesn't exist, so do nothing
return false;
}
const effect_type &type = eff_id.obj();
if( Character *ch = as_character() ) {
if( is_avatar() ) {
if( !type.get_remove_message().empty() ) {
add_msg( type.lose_game_message_type( get_effect( eff_id, bp.id() ).get_intensity() ),
type.get_remove_message() );
}
}
get_event_bus().send<event_type::character_loses_effect>( ch->getID(), bp.id(), eff_id );
}
// bp_null means remove all of a given effect id
if( bp == bodypart_str_id::NULL_ID() ) {
for( auto &it : ( *effects )[eff_id] ) {
on_effect_int_change( eff_id, 0, it.first );
}
effects->erase( eff_id );
} else {
( *effects )[eff_id].erase( bp.id() );
on_effect_int_change( eff_id, 0, bp );
// If there are no more effects of a given type remove the type map
if( ( *effects )[eff_id].empty() ) {
effects->erase( eff_id );
}
}
return true;
}
bool Creature::remove_effect( const efftype_id &eff_id )
{
return remove_effect( eff_id, bodypart_str_id::NULL_ID() );
}
void Creature::schedule_effect_removal( const efftype_id &eff_id, const bodypart_id &bp )
{
terminating_effects.push( terminating_effect{eff_id, bp} );
}
void Creature::schedule_effect_removal( const efftype_id &eff_id )
{
return schedule_effect_removal( eff_id, bodypart_str_id::NULL_ID() );
}
bool Creature::has_effect( const efftype_id &eff_id, const bodypart_id &bp ) const
{
// bp_null means anything targeted or not
if( bp.id() == bodypart_str_id::NULL_ID() ) {
return effects->count( eff_id );
} else {
auto got_outer = effects->find( eff_id );
if( got_outer != effects->end() ) {
auto got_inner = got_outer->second.find( bp.id() );
if( got_inner != got_outer->second.end() ) {
return true;
}
}
return false;
}
}
bool Creature::has_effect( const efftype_id &eff_id ) const
{
return has_effect( eff_id, bodypart_str_id::NULL_ID() );
}
bool Creature::has_effect_with_flag( const flag_id &flag, const bodypart_id &bp ) const
{
return std::any_of( effects->begin(), effects->end(), [&]( const auto & elem ) {
// effect::has_flag currently delegates to effect_type::has_flag
return elem.first->has_flag( flag ) && elem.second.count( bp );
} );
}
bool Creature::has_effect_with_flag( const flag_id &flag ) const
{
return std::any_of( effects->begin(), effects->end(), [&]( const auto & elem ) {
// effect::has_flag currently delegates to effect_type::has_flag
return elem.first->has_flag( flag );
} );
}
std::vector<std::reference_wrapper<const effect>> Creature::get_effects_with_flag(
const flag_id &flag ) const
{
std::vector<std::reference_wrapper<const effect>> effs;
for( auto &elem : *effects ) {
if( !elem.first->has_flag( flag ) ) {
continue;
}
for( const std::pair<const bodypart_id, effect> &_it : elem.second ) {
effs.emplace_back( _it.second );
}
}
return effs;
}
std::vector<std::reference_wrapper<const effect>> Creature::get_effects() const
{
std::vector<std::reference_wrapper<const effect>> effs;
for( auto &elem : *effects ) {
for( const std::pair<const bodypart_id, effect> &_it : elem.second ) {
effs.emplace_back( _it.second );
}
}
return effs;
}
std::vector<std::reference_wrapper<const effect>> Creature::get_effects_from_bp(
const bodypart_id &bp ) const
{
std::vector<std::reference_wrapper<const effect>> effs;
for( auto &elem : *effects ) {
const auto iter = elem.second.find( bp );
if( iter != elem.second.end() ) {
effs.emplace_back( iter->second );
}
}
return effs;
}
effect &Creature::get_effect( const efftype_id &eff_id, const bodypart_id &bp )
{
return const_cast<effect &>( const_cast<const Creature *>( this )->get_effect( eff_id, bp ) );
}
const effect &Creature::get_effect( const efftype_id &eff_id, const bodypart_id &bp ) const
{
auto got_outer = effects->find( eff_id );
if( got_outer != effects->end() ) {
auto got_inner = got_outer->second.find( bp );
if( got_inner != got_outer->second.end() ) {
return got_inner->second;
}
}
return effect::null_effect;
}
time_duration Creature::get_effect_dur( const efftype_id &eff_id, const bodypart_id &bp ) const
{
const effect &eff = get_effect( eff_id, bp );
if( !eff.is_null() ) {
return eff.get_duration();
}
return 0_turns;
}
int Creature::get_effect_int( const efftype_id &eff_id, const bodypart_id &bp ) const
{
const effect &eff = get_effect( eff_id, bp );
if( !eff.is_null() ) {
return eff.get_intensity();
}
return 0;
}
void Creature::process_effects()
{
map &here = get_map();
// id's and body_part's of all effects to be removed. If we ever get player or
// monster specific removals these will need to be moved down to that level and then
// passed in to this function.
std::vector<efftype_id> rem_ids;
std::vector<bodypart_id> rem_bps;
// Decay/removal of effects
for( auto &elem : *effects ) {
for( auto &_it : elem.second ) {
// Do not freeze the effect with the FREEZE_EFFECTS flag.
if( has_effect_with_flag( json_flag_FREEZE_EFFECTS ) &&
!_it.second.has_flag( json_flag_FREEZE_EFFECTS ) ) {
continue;
}
// Add any effects that others remove to the removal list
for( const auto &removed_effect : _it.second.get_removes_effects() ) {
rem_ids.push_back( removed_effect );
rem_bps.emplace_back( bodypart_str_id::NULL_ID() );
}
effect &e = _it.second;
const int prev_int = e.get_intensity();
// Run decay effects, marking effects for removal as necessary.
e.decay( rem_ids, rem_bps, calendar::turn, is_avatar(), *effects );
if( e.get_intensity() != prev_int && e.get_duration() > 0_turns ) {
on_effect_int_change( e.get_id(), e.get_intensity(), e.get_bp() );
}
const bool reduced = resists_effect( e );
if( e.kill_roll( reduced ) ) {
add_msg_if_player( m_bad, e.get_death_message() );
if( is_avatar() ) {
std::map<std::string, cata_variant> event_data;
std::pair<std::string, cata_variant> data_obj( "character",
cata_variant::make<cata_variant_type::character_id>( as_character()->getID() ) );
event_data.insert( data_obj );
cata::event sent( e.death_event(), calendar::turn, std::move( event_data ) );
get_event_bus().send( sent );
}
die( &here, e.get_source().resolve_creature() );
}
}
}
// Actually remove effects. This should be the last thing done in process_effects().
for( size_t i = 0; i < rem_ids.size(); ++i ) {
remove_effect( rem_ids[i], rem_bps[i] );
}
}
bool Creature::resists_effect( const effect &e ) const
{
for( const efftype_id &i : e.get_resist_effects() ) {
if( has_effect( i ) ) {
return true;
}
}
for( const string_id<mutation_branch> &i : e.get_resist_traits() ) {
if( has_trait( i ) ) {
return true;
}
}
return false;
}
bool Creature::has_trait( const trait_id &/*flag*/ ) const
{
return false;
}
// Methods for setting/getting misc key/value pairs.
void Creature::set_value( const std::string &key, diag_value value )
{
values[ key ] = std::move( value );
}
void Creature::remove_value( const std::string &key )
{
values.erase( key );
}
diag_value const &Creature::get_value( const std::string &key ) const
{
return global_variables::_common_get_value( key, values );
}
diag_value const *Creature::maybe_get_value( const std::string &key ) const
{
return global_variables::_common_maybe_get_value( key, values );
}
void Creature::clear_values()
{
values.clear();
}
int Creature::mod_pain( int npain )
{
mod_pain_noresist( npain );
return npain;
}
void Creature::mod_pain_noresist( int npain )
{
set_pain( pain + npain );
}
void Creature::set_pain( int npain )
{
npain = std::max( npain, 0 );
if( pain != npain ) {
pain = npain;
on_stat_change( "pain", pain );
}
}
int Creature::get_pain() const
{
return pain;
}
int Creature::get_perceived_pain() const
{
return get_pain();
}
int Creature::get_moves() const
{
return moves;
}
void Creature::mod_moves( int nmoves )
{
moves += nmoves;
}
void Creature::set_moves( int nmoves )
{
moves = nmoves;
}
bool Creature::in_sleep_state() const
{
return has_effect( effect_sleep ) || has_effect( effect_lying_down ) ||
has_effect( effect_npc_suspend );
}
/*
* Killer-related things
*/
Creature *Creature::get_killer() const
{
return killer;
}
void Creature::set_killer( Creature *const killer )
{
// Only the first killer will be stored, calling set_killer again with a different
// killer would mean it's called on a dead creature and therefore ignored.
if( killer != nullptr && !killer->is_fake() && this->killer == nullptr ) {
this->killer = killer;
}
}
void Creature::clear_killer()
{
killer = nullptr;
}
void Creature::set_summon_time( const time_duration &length )
{
lifespan_end = calendar::turn + length;
}
time_point Creature::get_summon_time()
{
if( !lifespan_end.has_value() ) {
return calendar::turn_zero;
}
return lifespan_end.value();
}
void Creature::decrement_summon_timer()
{
if( !lifespan_end ) {
return;
}
if( lifespan_end.value() <= calendar::turn ) {
die( &get_map(), nullptr );
}
}
Creature *Creature::get_summoner() const
{
if( !summoner ) {
return nullptr;
} else if( summoner.value() == get_player_character().getID() ) {
return &get_player_character();
} else {
return g->find_npc( summoner.value() );
}
}
void Creature::set_summoner( Creature *const summoner )
{
if( summoner->as_character() != nullptr ) {
this->summoner = summoner->as_character()->getID();
}
}
void Creature::set_summoner( character_id summoner )
{
this->summoner = summoner;
}
int Creature::get_num_blocks() const
{
return num_blocks + num_blocks_bonus;
}
int Creature::get_num_dodges() const
{
return num_dodges + num_dodges_bonus;
}
int Creature::get_num_blocks_bonus() const
{
return num_blocks_bonus;
}
int Creature::get_num_dodges_bonus() const
{
return num_dodges_bonus;
}
int Creature::get_num_blocks_base() const
{
return num_blocks;
}
int Creature::get_num_dodges_base() const
{
return num_dodges;
}
// currently this is expected to be overridden to actually have use
int Creature::get_env_resist( bodypart_id ) const
{
return 0;
}
int Creature::get_armor_res( const damage_type_id &dt, bodypart_id ) const
{
return get_armor_res_bonus( dt );
}
int Creature::get_armor_res_base( const damage_type_id &dt, bodypart_id ) const
{
return get_armor_res_bonus( dt );
}
int Creature::get_armor_res_bonus( const damage_type_id &dt ) const
{
auto iter = armor_bonus.find( dt );
return iter == armor_bonus.end() ? 0 : std::round( iter->second );
}
int Creature::get_spell_resist() const
{
// TODO: add spell resistance to monsters, then make this pure virtual
return 0;
}
int Creature::get_speed() const
{
return get_speed_base() + get_speed_bonus();
}
int Creature::get_eff_per() const
{
return 0;
}
float Creature::get_dodge( bool critfail ) const
{
if( critfail && rng( 0, 99 ) == 0 ) {
return 0.0f;
}
return get_dodge_base() + get_dodge_bonus();
}
float Creature::get_hit() const
{
return get_hit_base() + get_hit_bonus();
}
anatomy_id Creature::get_anatomy() const
{
return creature_anatomy;
}
void Creature::set_anatomy( const anatomy_id &anat )
{
creature_anatomy = anat;
}
const std::map<bodypart_str_id, bodypart> &Creature::get_body() const
{
return body;
}
void Creature::set_body()
{
body.clear();
for( const bodypart_id &bp : get_anatomy()->get_bodyparts() ) {
body.emplace( bp.id(), bodypart( bp.id() ) );
}
}
bool Creature::has_part( const bodypart_id &id, body_part_filter filter ) const
{
return get_part_id( id, filter, true ) != bodypart_str_id::NULL_ID();
}
bodypart *Creature::get_part( const bodypart_id &id )
{
auto found = body.find( get_part_id( id ).id() );
if( found == body.end() ) {
debugmsg( "Could not find bodypart %s in %s's body", id.id().c_str(), get_name() );
return nullptr;
}
return &found->second;
}
const bodypart *Creature::get_part( const bodypart_id &id ) const
{
auto found = body.find( get_part_id( id ).id() );
if( found == body.end() ) {
debugmsg( "Could not find bodypart %s in %s's body", id.id().c_str(), get_name() );
return nullptr;
}
return &found->second;
}
template<typename T>
static T get_part_helper( const Creature &c, const bodypart_id &id,
T( bodypart::* get )() const )
{
const bodypart *const part = c.get_part( id );
if( part ) {
return ( part->*get )();
} else {
// If the bodypart doesn't exist, return the appropriate accessor on the null bodypart.
// Static null bodypart variable, otherwise the compiler notes the possible return of local variable address (#42798).
static const bodypart bp_null;
return ( bp_null.*get )();
}
}
namespace
{
template<typename T>
class type_identity
{
public:
using type = T;
};
} // namespace
template<typename T>
static void set_part_helper( Creature &c, const bodypart_id &id,
void( bodypart::* set )( T ), typename type_identity<T>::type val )
{
bodypart *const part = c.get_part( id );
if( part ) {
( part->*set )( val );
}
}
bodypart_id Creature::get_part_id( const bodypart_id &id,
body_part_filter filter, bool suppress_debugmsg ) const
{
auto found = body.find( id.id() );
if( found != body.end() ) {
return found->first;
}
// try to find an equivalent part in the body map
if( filter >= body_part_filter::equivalent ) {
for( const std::pair<const bodypart_str_id, bodypart> &bp : body ) {
if( id->part_side == bp.first->part_side &&
id->primary_limb_type() == bp.first->primary_limb_type() ) {
return bp.first;
}
}
}
// try to find the next best thing
std::pair<bodypart_id, float> best = { bodypart_str_id::NULL_ID().id(), 0.0f };
if( filter >= body_part_filter::next_best ) {
for( const std::pair<const bodypart_str_id, bodypart> &bp : body ) {
for( const std::pair<const body_part_type::type, float> &mp : bp.first->limbtypes ) {
// if the secondary limb type matches and is better than the current
if( mp.first == id->primary_limb_type() && mp.second > best.second ) {
// give an inflated bonus if the part sides match
float bonus = id->part_side == bp.first->part_side ? 1.0f : 0.0f;
best = { bp.first, mp.second + bonus };
}
}
}
}
if( best.first == bodypart_str_id::NULL_ID() && !suppress_debugmsg ) {
debugmsg( "Could not find equivalent bodypart id %s in %s's body", id.id().c_str(), get_name() );
}
return best.first;
}
int Creature::get_part_hp_cur( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::get_hp_cur );
}
int Creature::get_part_hp_max( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::get_hp_max );
}
int Creature::get_part_healed_total( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::get_healed_total );
}
int Creature::get_part_damage_disinfected( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::get_damage_disinfected );
}
int Creature::get_part_damage_bandaged( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::get_damage_bandaged );
}
const encumbrance_data &Creature::get_part_encumbrance_data( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::get_encumbrance_data );
}
int Creature::get_part_drench_capacity( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::get_drench_capacity );
}
int Creature::get_part_wetness( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::get_wetness );
}
units::temperature Creature::get_part_temp_cur( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::get_temp_cur );
}
units::temperature Creature::get_part_temp_conv( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::get_temp_conv );
}
int Creature::get_part_frostbite_timer( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::get_frostbite_timer );
}
std::array<int, NUM_WATER_TOLERANCE> Creature::get_part_mut_drench( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::get_mut_drench );
}
float Creature::get_part_wetness_percentage( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::get_wetness_percentage );
}
void Creature::set_part_hp_cur( const bodypart_id &id, int set )
{
bool was_broken = is_avatar() && as_character()->is_limb_broken( id );
set_part_helper( *this, id, &bodypart::set_hp_cur, set );
if( !was_broken && is_avatar() && as_character()->is_limb_broken( id ) ) {
get_event_bus().send<event_type::broken_bone>( as_character()->getID(), id );
}
}
void Creature::set_part_hp_max( const bodypart_id &id, int set )
{
set_part_helper( *this, id, &bodypart::set_hp_max, set );
}
void Creature::set_part_healed_total( const bodypart_id &id, int set )
{
set_part_helper( *this, id, &bodypart::set_healed_total, set );
}
void Creature::set_part_damage_disinfected( const bodypart_id &id, int set )
{
set_part_helper( *this, id, &bodypart::set_damage_disinfected, set );
}
void Creature::set_part_damage_bandaged( const bodypart_id &id, int set )
{
set_part_helper( *this, id, &bodypart::set_damage_bandaged, set );
}
void Creature::set_part_encumbrance_data( const bodypart_id &id, const encumbrance_data &set )
{
set_part_helper( *this, id, &bodypart::set_encumbrance_data, set );
}
void Creature::set_part_wetness( const bodypart_id &id, int set )
{
set_part_helper( *this, id, &bodypart::set_wetness, set );
}
void Creature::set_part_temp_cur( const bodypart_id &id, units::temperature set )
{
set_part_helper( *this, id, &bodypart::set_temp_cur, set );
}
void Creature::set_part_temp_conv( const bodypart_id &id, units::temperature set )
{
set_part_helper( *this, id, &bodypart::set_temp_conv, set );
}
void Creature::set_part_frostbite_timer( const bodypart_id &id, int set )
{
set_part_helper( *this, id, &bodypart::set_frostbite_timer, set );
}
void Creature::set_part_mut_drench( const bodypart_id &id, std::pair<water_tolerance, int> set )
{
set_part_helper( *this, id, &bodypart::set_mut_drench, set );
}
void Creature::mod_part_hp_cur( const bodypart_id &id, int mod )
{
bool was_broken = is_avatar() && as_character()->is_limb_broken( id );
set_part_helper( *this, id, &bodypart::mod_hp_cur, mod );
if( !was_broken && is_avatar() && as_character()->is_limb_broken( id ) ) {
get_event_bus().send<event_type::broken_bone>( as_character()->getID(), id );
}
}
void Creature::mod_part_hp_max( const bodypart_id &id, int mod )
{
set_part_helper( *this, id, &bodypart::mod_hp_max, mod );
}
void Creature::mod_part_healed_total( const bodypart_id &id, int mod )
{
set_part_helper( *this, id, &bodypart::mod_healed_total, mod );
}
void Creature::mod_part_damage_disinfected( const bodypart_id &id, int mod )
{
set_part_helper( *this, id, &bodypart::mod_damage_disinfected, mod );
}
void Creature::mod_part_damage_bandaged( const bodypart_id &id, int mod )
{
set_part_helper( *this, id, &bodypart::mod_damage_bandaged, mod );
}
void Creature::mod_part_wetness( const bodypart_id &id, int mod )
{
set_part_helper( *this, id, &bodypart::mod_wetness, mod );
}
void Creature::mod_part_temp_cur( const bodypart_id &id, units::temperature_delta mod )
{
set_part_helper( *this, id, &bodypart::mod_temp_cur, mod );
}
void Creature::mod_part_temp_conv( const bodypart_id &id, units::temperature_delta mod )
{
set_part_helper( *this, id, &bodypart::mod_temp_conv, mod );
}
void Creature::mod_part_frostbite_timer( const bodypart_id &id, int mod )
{
set_part_helper( *this, id, &bodypart::mod_frostbite_timer, mod );
}
void Creature::set_all_parts_temp_cur( units::temperature set )
{
for( std::pair<const bodypart_str_id, bodypart> &elem : body ) {
if( elem.first->has_flag( json_flag_IGNORE_TEMP ) ) {
continue;
}
elem.second.set_temp_cur( set );
}
}
void Creature::set_all_parts_temp_conv( units::temperature set )
{
for( std::pair<const bodypart_str_id, bodypart> &elem : body ) {
if( elem.first->has_flag( json_flag_IGNORE_TEMP ) ) {
continue;
}
elem.second.set_temp_conv( set );
}
}
void Creature::set_all_parts_wetness( int set )
{
for( std::pair<const bodypart_str_id, bodypart> &elem : body ) {
elem.second.set_wetness( set );
}
}
void Creature::set_all_parts_hp_cur( const int set )
{
for( std::pair<const bodypart_str_id, bodypart> &elem : body ) {
elem.second.set_hp_cur( set );
}
}
void Creature::set_all_parts_hp_to_max()
{
for( std::pair<const bodypart_str_id, bodypart> &elem : body ) {
elem.second.set_hp_to_max();
}
}
bool Creature::has_atleast_one_wet_part() const
{
for( const std::pair<const bodypart_str_id, bodypart> &elem : body ) {
if( elem.second.get_wetness() > 0 ) {
return true;
}
}
return false;
}
bool Creature::is_part_at_max_hp( const bodypart_id &id ) const
{
return get_part_helper( *this, id, &bodypart::is_at_max_hp );
}
bodypart_id Creature::get_random_body_part( bool main ) const
{
// TODO: Refuse broken limbs, adjust for mutations
const bodypart_id &part = get_anatomy()->random_body_part();
return main ? part->main_part.id() : part;
}
static void sort_body_parts( std::vector<bodypart_id> &bps, const Creature *c )
{
// We want to dynamically sort the parts based on their connections as
// defined in json.
// The goal is to performa a pre-order depth-first traversal starting
// with the root part (the head) and prioritising children with fewest
// descendants.
// First build a map with the reverse connections
std::unordered_map<bodypart_id, cata::flat_set<bodypart_id>> parts_connected_to;
bodypart_id root_part;
for( const bodypart_id &bp : bps ) {
bodypart_id conn = c->get_part_id( bp->connected_to );
if( conn == bp ) {
root_part = bp;
} else {
parts_connected_to[conn].insert( bp );
}
}
if( root_part == bodypart_id() ) {
debugmsg( "No root part in body" );
return;
}
// Topo-sort the parts from the extremities towards the head
std::unordered_map<bodypart_id, cata::flat_set<bodypart_id>> unaccounted_parts =
parts_connected_to;
cata::flat_set<bodypart_id> parts_with_no_connections;
for( const bodypart_id &bp : bps ) {
if( unaccounted_parts[bp].empty() ) {
parts_with_no_connections.insert( bp );
}
}
std::vector<bodypart_id> topo_sorted_parts;
while( !parts_with_no_connections.empty() ) {
auto last = parts_with_no_connections.end();
--last;
bodypart_id bp = *last;
parts_with_no_connections.erase( last );
unaccounted_parts.erase( bp );
topo_sorted_parts.push_back( bp );
bodypart_id conn = c->get_part_id( bp->connected_to );
if( conn == bp ) {
break;
}
auto conn_it = unaccounted_parts.find( conn );
cata_assert( conn_it != unaccounted_parts.end() );
conn_it->second.erase( bp );
if( conn_it->second.empty() ) {
parts_with_no_connections.insert( conn );
}
}
if( !unaccounted_parts.empty() || !parts_with_no_connections.empty() ) {
debugmsg( "Error in topo-sorting bodyparts: unaccounted_parts.size() == %d; "
"parts_with_no_connections.size() == %d", unaccounted_parts.size(),
parts_with_no_connections.size() );
return;
}
// Using the topo-sorted parts, we can count the descendants of each
// part
std::unordered_map<bodypart_id, int> num_descendants;
for( const bodypart_id &bp : topo_sorted_parts ) {
int this_num_descendants = 1;
for( const bodypart_id &child : parts_connected_to[bp] ) {
this_num_descendants += num_descendants[child];
}
num_descendants[bp] = this_num_descendants;
}
// Finally, we can do the depth-first traversal:
std::vector<bodypart_id> result;
std::stack<bodypart_id> pending;
pending.push( root_part );
const auto compare_children = [&]( const bodypart_id & l, const bodypart_id & r ) {
std::string l_name = l->name.translated();
std::string r_name = r->name.translated();
bodypart_id l_opp = l->opposite_part;
bodypart_id r_opp = r->opposite_part;
// Sorting first on the min of the name and opposite's name ensures
// that we put pairs together in the list.
std::string l_min_name = std::min( l_name, l_opp->name.translated(), localized_compare );
std::string r_min_name = std::min( r_name, r_opp->name.translated(), localized_compare );
// We delibarately reverse the comparison because the elements get
// reversed below when they are transferred from the vector to the
// stack.
return localized_compare(
std::make_tuple( num_descendants[r], r_min_name, r_name ),
std::make_tuple( num_descendants[l], l_min_name, l_name ) );
};
while( !pending.empty() ) {
bodypart_id next = pending.top();
pending.pop();
result.push_back( next );
const cata::flat_set<bodypart_id> children_set = parts_connected_to.at( next );
std::vector<bodypart_id> children( children_set.begin(), children_set.end() );
std::sort( children.begin(), children.end(), compare_children );
for( const bodypart_id &child : children ) {
pending.push( child );
}
}
cata_assert( bps.size() == result.size() );
bps = result;
}
std::vector<bodypart_id> Creature::get_all_body_parts( get_body_part_flags flags ) const
{
bool only_main( flags & get_body_part_flags::only_main );
bool only_minor( flags & get_body_part_flags::only_minor );
std::vector<bodypart_id> all_bps;
all_bps.reserve( body.size() );
for( const std::pair<const bodypart_str_id, bodypart> &elem : body ) {
if( has_part( elem.first ) ) {
if( ( only_main && elem.first->main_part != elem.first ) || ( only_minor &&
elem.first->main_part == elem.first ) ) {
continue;
}
all_bps.emplace_back( elem.first );
}
}
if( flags & get_body_part_flags::sorted ) {
sort_body_parts( all_bps, this );
}
return all_bps;
}
std::vector<bodypart_id> Creature::get_random_body_parts( const std::vector<bodypart_id> &bp_list,
size_t amount )
{
std::vector<bodypart_id> random_parts;
amount = std::max<size_t>( 0, std::min( amount, ( bp_list.size() - 1 ) ) );
// Use a set to avoid duplicates
std::set<int> selected_indices;
while( selected_indices.size() < amount ) {
int index = rng( 0, bp_list.size() - 1 );
selected_indices.insert( index );
}
// Collect the random bodypart_ids
for( int index : selected_indices ) {
random_parts.push_back( bp_list[index] );
}
return random_parts;
}
bodypart_id Creature::get_root_body_part() const
{
for( const bodypart_id &part : get_all_body_parts() ) {
if( part->connected_to == part->id ) {
return part;
}
}
debugmsg( "ERROR: character has no root part" );
return body_part_head;
}
std::vector<bodypart_id> Creature::get_all_body_parts_of_type(
body_part_type::type part_type, get_body_part_flags flags ) const
{
const bool only_main( flags & get_body_part_flags::only_main );
const bool primary( flags & get_body_part_flags::primary_type );
std::vector<bodypart_id> bodyparts;
for( const std::pair<const bodypart_str_id, bodypart> &elem : body ) {
if( only_main && elem.first->main_part != elem.first ) {
continue;
}
if( primary ) {
if( elem.first->primary_limb_type() == part_type ) {
bodyparts.emplace_back( elem.first );
}
} else if( elem.first->has_type( part_type ) ) {
bodyparts.emplace_back( elem.first );
}
}
if( flags & get_body_part_flags::sorted ) {
sort_body_parts( bodyparts, this );
}
return bodyparts;
}
bodypart_id Creature::get_random_body_part_of_type( body_part_type::type part_type ) const
{
return random_entry( get_all_body_parts_of_type( part_type ) );
}
std::vector<bodypart_id> Creature::get_all_body_parts_with_flag( const json_character_flag &flag )
const
{
std::vector<bodypart_id> bodyparts;
for( const std::pair<const bodypart_str_id, bodypart> &elem : body ) {
if( elem.first->has_flag( flag ) ) {
bodyparts.emplace_back( elem.first );
}
}
return bodyparts;
}
body_part_set Creature::get_drenching_body_parts( bool upper, bool mid, bool lower ) const
{
body_part_set ret;
// Need to exclude stuff - start full and reduce?
ret.fill( get_all_body_parts() );
// Diving
if( upper && mid && lower ) {
return ret;
}
body_part_set upper_limbs;
body_part_set lower_limbs;
upper_limbs.fill( get_all_body_parts_with_flag( json_flag_LIMB_UPPER ) );
lower_limbs.fill( get_all_body_parts_with_flag( json_flag_LIMB_LOWER ) );
// Rain?
if( upper && mid ) {
ret.substract_set( lower_limbs );
}
// Swimming with your head out
if( !upper ) {
ret.substract_set( upper_limbs );
}
// Wading in water
if( !upper && !mid && lower ) {
ret = lower_limbs;
}
return ret;
}
std::vector<bodypart_id> Creature::get_ground_contact_bodyparts( bool arms_legs ) const
{
std::vector<bodypart_id> arms = get_all_body_parts_of_type( body_part_type::type::arm );
std::vector<bodypart_id> legs = get_all_body_parts_of_type( body_part_type::type::leg );
std::vector<bodypart_id> hands = get_all_body_parts_of_type( body_part_type::type::hand );
std::vector<bodypart_id> feet = get_all_body_parts_of_type( body_part_type::type::foot );
if( has_effect( effect_quadruped_full ) || has_effect( effect_quadruped_half ) ) {
if( arms_legs == true ) {
std::vector<bodypart_id> bodyparts( arms.size() + legs.size() );
std::merge( arms.begin(), arms.end(), legs.begin(), legs.end(), bodyparts.begin() );
return bodyparts;
} else {
std::vector<bodypart_id> bodyparts( hands.size() + feet.size() );
std::merge( hands.begin(), hands.end(), feet.begin(), feet.end(), bodyparts.begin() );
return bodyparts;
}
} else {
std::vector<bodypart_id> bodyparts;
if( arms_legs == true ) {
bodyparts = get_all_body_parts_of_type( body_part_type::type::leg );
} else {
bodyparts = get_all_body_parts_of_type( body_part_type::type::foot );
}
return bodyparts;
}
}
std::string Creature::string_for_ground_contact_bodyparts( const std::vector<bodypart_id> &bps )
const
{
//Taken of "body_part_names" function in armor_layers.cpp
std::vector<std::string> names;
names.reserve( bps.size() );
for( bodypart_id part : bps ) {
bool can_be_consolidated = false;
std::string current_part = body_part_name_accusative( part );
std::string opposite_part = body_part_name_accusative( part->opposite_part );
std::string part_group = body_part_name_accusative( part, 2 );
for( const std::string &already_listed : names ) {
if( already_listed == opposite_part ) {
can_be_consolidated = true;
break;
}
}
if( can_be_consolidated ) {
std::replace( names.begin(), names.end(), opposite_part, part_group );
} else {
names.push_back( current_part );
}
}
return enumerate_as_string( names );
}
int Creature::get_num_body_parts_of_type( body_part_type::type part_type ) const
{
return static_cast<int>( get_all_body_parts_of_type( part_type ).size() );
}
int Creature::get_num_broken_body_parts_of_type( body_part_type::type part_type ) const
{
int ret = 0;
for( const bodypart_id &bp : get_all_body_parts_of_type( part_type ) ) {
if( get_part_hp_cur( bp ) == 0 ) {
ret++;
}
}
return ret;
}
int Creature::get_hp( const bodypart_id &bp ) const
{
if( bp != bodypart_str_id::NULL_ID() ) {
return get_part_hp_cur( bp );
}
int hp_total = 0;
for( const std::pair<const bodypart_str_id, bodypart> &elem : get_body() ) {
hp_total += elem.second.get_hp_cur();
}
return hp_total;
}
int Creature::get_hp() const
{
return get_hp( bodypart_str_id::NULL_ID() );
}
int Creature::get_hp_max( const bodypart_id &bp ) const
{
if( bp != bodypart_str_id::NULL_ID() ) {
return get_part_hp_max( bp );
}
int hp_total = 0;
for( const std::pair<const bodypart_str_id, bodypart> &elem : get_body() ) {
hp_total += elem.second.get_hp_max();
}
return hp_total;
}
int Creature::get_hp_max() const
{
return get_hp_max( bodypart_str_id::NULL_ID() );
}
int Creature::get_speed_base() const
{
return speed_base;
}
int Creature::get_speed_bonus() const
{
return speed_bonus;
}
float Creature::get_dodge_bonus() const
{
return dodge_bonus;
}
int Creature::get_block_bonus() const
{
return block_bonus; //base is 0
}
float Creature::get_hit_bonus() const
{
return hit_bonus; //base is 0
}
int Creature::get_bash_bonus() const
{
return bash_bonus;
}
int Creature::get_cut_bonus() const
{
return cut_bonus;
}
float Creature::get_bash_mult() const
{
return bash_mult;
}
float Creature::get_cut_mult() const
{
return cut_mult;
}
bool Creature::get_melee_quiet() const
{
return melee_quiet;
}
int Creature::get_throw_resist() const
{
return throw_resist;
}
void Creature::mod_stat( const std::string &stat, float modifier )
{
if( stat == "speed" ) {
mod_speed_bonus( modifier );
} else if( stat == "dodge" ) {
mod_dodge_bonus( modifier );
} else if( stat == "block" ) {
mod_block_bonus( modifier );
} else if( stat == "hit" ) {
mod_hit_bonus( modifier );
} else if( stat == "bash" ) {
mod_bash_bonus( modifier );
} else if( stat == "cut" ) {
mod_cut_bonus( modifier );
} else if( stat == "pain" ) {
mod_pain( modifier );
} else if( stat == "moves" ) {
mod_moves( modifier );
} else {
debugmsg( "Tried to modify a nonexistent stat %s.", stat.c_str() );
}
}
void Creature::set_num_blocks_bonus( int nblocks )
{
num_blocks_bonus = nblocks;
}
void Creature::mod_num_blocks_bonus( int nblocks )
{
num_blocks_bonus += nblocks;
}
void Creature::mod_num_dodges_bonus( int ndodges )
{
num_dodges_bonus += ndodges;
}
void Creature::set_armor_res_bonus( int narm, const damage_type_id &dt )
{
armor_bonus[dt] = narm;
}
void Creature::set_speed_base( int nspeed )
{
speed_base = nspeed;
}
void Creature::set_speed_bonus( int nspeed )
{
speed_bonus = nspeed;
}
void Creature::set_dodge_bonus( float ndodge )
{
dodge_bonus = ndodge;
}
void Creature::set_block_bonus( int nblock )
{
block_bonus = nblock;
}
void Creature::set_hit_bonus( float nhit )
{
hit_bonus = nhit;
}
void Creature::set_bash_bonus( int nbash )
{
bash_bonus = nbash;
}
void Creature::set_cut_bonus( int ncut )
{
cut_bonus = ncut;
}
void Creature::mod_speed_bonus( int nspeed )
{
speed_bonus += nspeed;
}
void Creature::mod_dodge_bonus( float ndodge )
{
dodge_bonus += ndodge;
}
void Creature::mod_block_bonus( int nblock )
{
block_bonus += nblock;
}
void Creature::mod_hit_bonus( float nhit )
{
hit_bonus += nhit;
}
void Creature::mod_bash_bonus( int nbash )
{
bash_bonus += nbash;
}
void Creature::mod_cut_bonus( int ncut )
{
cut_bonus += ncut;
}
void Creature::mod_size_bonus( int nsize )
{
nsize = clamp( nsize, creature_size::tiny - get_size(), creature_size::huge - get_size() );
size_bonus += nsize;
}
void Creature::set_bash_mult( float nbashmult )
{
bash_mult = nbashmult;
}
void Creature::set_cut_mult( float ncutmult )
{
cut_mult = ncutmult;
}
void Creature::set_melee_quiet( bool nquiet )
{
melee_quiet = nquiet;
}
void Creature::set_throw_resist( int nthrowres )
{
throw_resist = nthrowres;
}
units::mass Creature::weight_capacity() const
{
units::mass base_carry = 13_kilogram;
switch( get_size() ) {
case creature_size::tiny:
base_carry /= 4;
break;
case creature_size::small:
base_carry /= 2;
break;
case creature_size::medium:
default:
break;
case creature_size::large:
base_carry *= 2;
break;
case creature_size::huge:
base_carry *= 4;
break;
}
return base_carry;
}
/*
* Drawing-related functions
*/
void Creature::draw( const catacurses::window &w, const point_bub_ms &origin, bool inverted ) const
{
draw( w, tripoint_bub_ms( origin, posz() ), inverted );
}
void Creature::draw( const catacurses::window &w, const tripoint_bub_ms &origin,
bool inverted ) const
{
map &here = get_map();
const tripoint_bub_ms pos = pos_bub( here );
if( is_draw_tiles_mode() ) {
return;
}
point draw( point( getmaxx( w ) / 2 + pos.x(), getmaxy( w ) / 2 + pos.y() ) - origin.xy().raw() );
if( inverted ) {
mvwputch_inv( w, draw, basic_symbol_color(), symbol() );
} else if( is_symbol_highlighted() ) {
mvwputch_hi( w, draw, basic_symbol_color(), symbol() );
} else {
mvwputch( w, draw, symbol_color(), symbol() );
}
}
bool Creature::is_symbol_highlighted() const
{
return false;
}
global_variables::impl_t &Creature::get_values()
{
return values;
}
bodypart_id Creature::get_max_hitsize_bodypart() const
{
return anatomy( get_all_body_parts() ).get_max_hitsize_bodypart();
}
bodypart_id Creature::select_body_part( const Creature *you, int min_hit, int max_hit,
bool can_attack_high,
int hit_roll ) const
{
add_msg_debug( debugmode::DF_CREATURE, "hit roll = %d", hit_roll );
if( !is_monster() && !can_attack_high ) {
can_attack_high = as_character()->is_on_ground();
}
return anatomy( get_all_body_parts() ).select_body_part( you, min_hit, max_hit, can_attack_high,
hit_roll );
}
bodypart_id Creature::select_blocking_part( bool arm, bool leg, bool nonstandard ) const
{
return anatomy( get_all_body_parts() ).select_blocking_part( this, arm, leg, nonstandard );
}
bodypart_id Creature::random_body_part( bool main_parts_only ) const
{
const bodypart_id &bp = get_anatomy()->random_body_part();
return main_parts_only ? bp->main_part : bp ;
}
std::vector<bodypart_id> Creature::get_all_eligable_parts( int min_hit, int max_hit,
bool can_attack_high ) const
{
return anatomy( get_all_body_parts() ).get_all_eligable_parts( min_hit, max_hit, can_attack_high );
}
void Creature::add_damage_over_time( const damage_over_time_data &DoT )
{
damage_over_time_map.emplace_back( DoT );
}
void Creature::process_damage_over_time()
{
for( auto DoT = damage_over_time_map.begin(); DoT != damage_over_time_map.end(); ) {
if( DoT->duration > 0_turns ) {
for( const bodypart_id &bp : DoT->bps ) {
const double dmg_amount = DoT->amount;
if( dmg_amount < 0.0 ) {
heal_bp( bp.id(), roll_remainder( -dmg_amount ) );
} else if( dmg_amount > 0.0 ) {
deal_damage( nullptr, bp.id(), damage_instance( DoT->type, roll_remainder( dmg_amount ) ) );
}
}
DoT->duration -= 1_turns;
++DoT;
} else {
DoT = damage_over_time_map.erase( DoT );
}
}
}
void Creature::check_dead_state( map *here )
{
if( is_dead_state() ) {
die( here, killer );
}
}
std::string Creature::attitude_raw_string( Attitude att )
{
switch( att ) {
case Attitude::HOSTILE:
return "hostile";
case Attitude::NEUTRAL:
return "neutral";
case Attitude::FRIENDLY:
return "friendly";
default:
return "other";
}
}
const std::pair<translation, nc_color> &Creature::get_attitude_ui_data( Attitude att )
{
using pair_t = std::pair<translation, nc_color>;
static const std::array<pair_t, 5> strings {
{
pair_t {to_translation( "Hostile" ), c_red},
pair_t {to_translation( "Neutral" ), h_white},
pair_t {to_translation( "Friendly" ), c_green},
pair_t {to_translation( "Any" ), c_yellow},
pair_t {to_translation( "BUG: Behavior unnamed. (Creature::get_attitude_ui_data)" ), h_red}
}
};
if( static_cast<int>( att ) < 0 || static_cast<int>( att ) >= static_cast<int>( strings.size() ) ) {
return strings.back();
}
return strings[static_cast<int>( att )];
}
std::string Creature::replace_with_npc_name( std::string input ) const
{
replace_substring( input, "<npcname>", disp_name(), true );
return input;
}
void Creature::knock_back_from( const tripoint_bub_ms &p )
{
map &here = get_map();
const tripoint_bub_ms pos = pos_bub( here );
if( p == pos ) {
return; // No effect
}
if( is_hallucination() ) {
die( &here, nullptr );
return;
}
tripoint_bub_ms to = pos;
if( p.x() < pos.x() ) {
to.x()++;
}
if( p.x() > pos.x() ) {
to.x()--;
}
if( p.y() < pos.y() ) {
to.y()++;
}
if( p.y() > pos.y() ) {
to.y()--;
}
knock_back_to( to );
}
double Creature::calculate_by_enchantment( double modify, enchant_vals::mod value,
bool round_output ) const
{
modify += enchantment_cache->get_value_add( value );
modify *= 1.0 + enchantment_cache->get_value_multiply( value );
if( round_output ) {
modify = std::round( modify );
}
return modify;
}
void Creature::adjust_taken_damage_by_enchantments( damage_unit &du ) const
{
//If we're not dealing any damage of the given type, don't even bother.
if( du.amount < 0.1f ) {
return;
}
double total = enchantment_cache->modify_damage_units_by_armor_protection( du.type, du.amount );
if( !du.type->no_resist ) {
total = calculate_by_enchantment( total, enchant_vals::mod::ARMOR_ALL );
}
du.amount = std::max( 0.0, total );
}
void Creature::adjust_taken_damage_by_enchantments_post_absorbed( damage_unit &du ) const
{
du.amount = std::max( 0.0, enchantment_cache->modify_damage_units_by_extra_damage( du.type,
du.amount ) );
}
void Creature::add_msg_if_player( const translation &msg ) const
{
return add_msg_if_player( msg.translated() );
}
void Creature::add_msg_if_player( const game_message_params ¶ms, const translation &msg ) const
{
return add_msg_if_player( params, msg.translated() );
}
void Creature::add_msg_if_npc( const translation &msg ) const
{
return add_msg_if_npc( msg.translated() );
}
void Creature::add_msg_if_npc( const game_message_params ¶ms, const translation &msg ) const
{
return add_msg_if_npc( params, msg.translated() );
}
void Creature::add_msg_player_or_npc( const translation &pc, const translation &npc ) const
{
return add_msg_player_or_npc( pc.translated(), npc.translated() );
}
void Creature::add_msg_player_or_npc( const game_message_params ¶ms, const translation &pc,
const translation &npc ) const
{
return add_msg_player_or_npc( params, pc.translated(), npc.translated() );
}
void Creature::add_msg_player_or_say( const translation &pc, const translation &npc ) const
{
return add_msg_player_or_say( pc.translated(), npc.translated() );
}
void Creature::add_msg_player_or_say( const game_message_params ¶ms, const translation &pc,
const translation &npc ) const
{
return add_msg_player_or_say( params, pc.translated(), npc.translated() );
}
std::vector <int> Creature::dispersion_for_even_chance_of_good_hit = { {
1731, 859, 573, 421, 341, 286, 245, 214, 191, 175,
151, 143, 129, 118, 114, 107, 101, 94, 90, 78,
78, 78, 74, 71, 68, 66, 62, 61, 59, 57,
46, 46, 46, 46, 46, 46, 45, 45, 44, 42,
41, 41, 39, 39, 38, 37, 36, 35, 34, 34,
33, 33, 32, 30, 30, 30, 30, 29, 28
}
};
void Creature::load_hit_range( const JsonObject &jo )
{
if( jo.has_array( "even_good" ) ) {
jo.read( "even_good", dispersion_for_even_chance_of_good_hit );
}
}
tripoint_abs_ms Creature::pos_abs() const
{
return location;
}
tripoint_abs_sm Creature::pos_abs_sm() const
{
return project_to<coords::sm>( location );
}
tripoint_abs_omt Creature::pos_abs_omt() const
{
return project_to<coords::omt>( location );
}
std::unique_ptr<talker> get_talker_for( Creature &me )
{
if( me.is_monster() ) {
return std::make_unique<talker_monster>( me.as_monster() );
} else if( me.is_npc() ) {
return std::make_unique<talker_npc>( me.as_npc() );
} else if( me.is_avatar() ) {
return std::make_unique<talker_avatar>( me.as_avatar() );
}
debugmsg( "Invalid creature type %s.", me.get_name() );
return std::make_unique<talker>();
}
std::unique_ptr<const_talker> get_const_talker_for( const Creature &me )
{
if( me.is_monster() ) {
return std::make_unique<talker_monster_const>( me.as_monster() );
} else if( me.is_npc() ) {
return std::make_unique<talker_npc_const>( me.as_npc() );
} else if( me.is_avatar() ) {
return std::make_unique<talker_avatar_const>( me.as_avatar() );
}
debugmsg( "Invalid creature type %s.", me.get_name() );
return std::make_unique<talker>();
}
std::unique_ptr<talker> get_talker_for( Creature *me )
{
if( !me ) {
debugmsg( "Null creature type." );
return std::make_unique<talker>();
}
return get_talker_for( *me );
}
| 412 | 0.988636 | 1 | 0.988636 | game-dev | MEDIA | 0.94872 | game-dev | 0.779868 | 1 | 0.779868 |
Dirkster99/AvalonDock | 5,918 | source/Components/AvalonDock/Commands/WeakAction.cs | using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
namespace AvalonDock.Commands
{
/// <summary>
/// Class WeakAction.
/// </summary>
internal class WeakAction
{
#region Private Fields
/// <summary>
/// The static action
/// </summary>
private Action _staticAction;
#endregion Private Fields
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WeakAction" /> class.
/// </summary>
/// <param name="action">The action that will be associated to this instance.</param>
public WeakAction(Action action)
: this(action?.Target, action)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WeakAction" /> class.
/// </summary>
/// <param name="target">The action's owner.</param>
/// <param name="action">The action that will be associated to this instance.</param>
[SuppressMessage(
"Microsoft.Design",
"CA1062:Validate arguments of public methods",
MessageId = "1",
Justification = "Method should fail with an exception if action is null.")]
public WeakAction(object target, Action action)
{
if (action.Method.IsStatic)
{
_staticAction = action;
if (target != null)
{
// Keep a reference to the target to control the
// WeakAction's lifetime.
Reference = new WeakReference(target);
}
return;
}
Method = action.Method;
ActionReference = new WeakReference(action.Target);
Reference = new WeakReference(target);
}
#endregion Public Constructors
#region Protected Constructors
/// <summary>
/// Initializes an empty instance of the <see cref="WeakAction" /> class.
/// </summary>
protected WeakAction()
{
}
#endregion Protected Constructors
#region Public Properties
/// <summary>
/// Gets a value indicating whether the Action's owner is still alive, or if it was collected
/// by the Garbage Collector already.
/// </summary>
/// <value><c>true</c> 如果 this instance is alive; 否则, <c>false</c>.</value>
public virtual bool IsAlive
{
get
{
if (_staticAction == null
&& Reference == null)
{
return false;
}
if (_staticAction != null)
{
if (Reference != null)
{
return Reference.IsAlive;
}
return true;
}
return Reference.IsAlive;
}
}
/// <summary>
/// Gets a value indicating whether the WeakAction is static or not.
/// </summary>
/// <value><c>true</c> 如果 this instance is static; 否则, <c>false</c>.</value>
public bool IsStatic
{
get
{
#if SILVERLIGHT
return (_action != null && _action.Target == null)
|| _staticAction != null;
#else
return _staticAction != null;
#endif
}
}
/// <summary>
/// Gets the name of the method that this WeakAction represents.
/// </summary>
/// <value>The name of the method.</value>
public virtual string MethodName
{
get
{
if (_staticAction != null)
{
return _staticAction.Method.Name;
}
return Method.Name;
}
}
/// <summary>
/// Gets the Action's owner. This object is stored as a
/// <see cref="WeakReference" />.
/// </summary>
/// <value>The target.</value>
public object Target
{
get
{
if (Reference == null)
{
return null;
}
return Reference.Target;
}
}
#endregion Public Properties
#region Protected Properties
/// <summary>
/// Gets or sets a WeakReference to this WeakAction's action's target.
/// This is not necessarily the same as
/// <see cref="Reference" />, for example if the
/// method is anonymous.
/// </summary>
/// <value>The action reference.</value>
protected WeakReference ActionReference
{
get;
set;
}
/// <summary>
/// The target of the weak reference.
/// </summary>
/// <value>The action target.</value>
protected object ActionTarget
{
get
{
if (ActionReference == null)
{
return null;
}
return ActionReference.Target;
}
}
/// <summary>
/// Gets or sets the <see cref="MethodInfo" /> corresponding to this WeakAction's
/// method passed in the constructor.
/// </summary>
/// <value>The method.</value>
protected MethodInfo Method
{
get;
set;
}
/// <summary>
/// Gets or sets a WeakReference to the target passed when constructing
/// the WeakAction. This is not necessarily the same as
/// <see cref="ActionReference" />, for example if the
/// method is anonymous.
/// </summary>
/// <value>The reference.</value>
protected WeakReference Reference
{
get;
set;
}
#endregion Protected Properties
#region Public Methods
/// <summary>
/// Executes the action. This only happens if the action's owner
/// is still alive.
/// </summary>
public void Execute(object param = null)
{
if (_staticAction != null)
{
_staticAction();
return;
}
var actionTarget = ActionTarget;
if (IsAlive)
{
if (Method != null
&& ActionReference != null
&& actionTarget != null)
{
var paras = Method.GetParameters().Count();
try
{
if (paras > 0)
{
Method.Invoke(actionTarget, new object[] { param });
}
else
{
Method.Invoke(actionTarget, null);
}
}
catch { }
// ReSharper disable RedundantJumpStatement
return;
// ReSharper restore RedundantJumpStatement
}
#if SILVERLIGHT
if (_action != null)
{
_action();
}
#endif
}
}
/// <summary>
/// Sets the reference that this instance stores to null.
/// </summary>
public void MarkForDeletion()
{
Reference = null;
ActionReference = null;
Method = null;
_staticAction = null;
#if SILVERLIGHT
_action = null;
#endif
}
#endregion Public Methods
}
} | 412 | 0.856765 | 1 | 0.856765 | game-dev | MEDIA | 0.643818 | game-dev | 0.938164 | 1 | 0.938164 |
ServUO/ServUO | 2,563 | Scripts/Mobiles/Normal/BoneDemon.cs | using System;
namespace Server.Mobiles
{
[CorpseName("a bone demon corpse")]
public class BoneDemon : BaseCreature
{
[Constructable]
public BoneDemon()
: base(AIType.AI_Mage, FightMode.Closest, 10, 1, 0.2, 0.4)
{
Name = "a bone demon";
Body = 308;
BaseSoundID = 0x48D;
SetStr(1000);
SetDex(151, 175);
SetInt(171, 220);
SetHits(3600);
SetDamage(34, 36);
SetDamageType(ResistanceType.Physical, 50);
SetDamageType(ResistanceType.Cold, 50);
SetResistance(ResistanceType.Physical, 75);
SetResistance(ResistanceType.Fire, 60);
SetResistance(ResistanceType.Cold, 90);
SetResistance(ResistanceType.Poison, 100);
SetResistance(ResistanceType.Energy, 60);
SetSkill(SkillName.Wrestling, 100.0);
SetSkill(SkillName.Tactics, 100.0);
SetSkill(SkillName.MagicResist, 50.1, 75.0);
SetSkill(SkillName.DetectHidden, 100.0);
SetSkill(SkillName.Magery, 77.6, 87.5);
SetSkill(SkillName.EvalInt, 77.6, 87.5);
SetSkill(SkillName.Meditation, 100.0);
Fame = 20000;
Karma = -20000;
VirtualArmor = 44;
}
public BoneDemon(Serial serial)
: base(serial)
{
}
public override bool BardImmune
{
get
{
return !Core.SE;
}
}
public override bool Unprovokable
{
get
{
return Core.SE;
}
}
public override bool AreaPeaceImmune
{
get
{
return Core.SE;
}
}
public override Poison PoisonImmune
{
get
{
return Poison.Lethal;
}
}
public override int TreasureMapLevel
{
get
{
return 1;
}
}
public override void GenerateLoot()
{
AddLoot(LootPack.FilthyRich, 8);
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
| 412 | 0.839914 | 1 | 0.839914 | game-dev | MEDIA | 0.975923 | game-dev | 0.767026 | 1 | 0.767026 |
AuroraZiling/Hollow | 1,910 | Hollow/Helpers/Registry/Screen.cs | using System;
using System.Runtime.Versioning;
using Hollow.Abstractions.Enums;
namespace Hollow.Helpers.Registry;
[SupportedOSPlatform("Windows")]
public class Screen
{
private const string ChinaKeyRoot = "HKEY_CURRENT_USER\\Software\\miHoYo\\绝区零";
private const string GlobalKeyRoot = "HKEY_CURRENT_USER\\Software\\miHoYo\\ZenlessZoneZero";
private const string ResolutionHeightKey = "Screenmanager Resolution Height_h2627697771";
private const string ResolutionWidthKey = "Screenmanager Resolution Width_h182942802";
private const string IsFullScreenKey = "Screenmanager Fullscreen mode_h3630240806";
public int ResolutionHeight { get; set; }
public int ResolutionWidth { get; set; }
public bool IsFullScreen { get; set; }
public Screen(GameServer gameServer)
{
var keyRoot = gameServer switch
{
GameServer.China => ChinaKeyRoot,
GameServer.Global => GlobalKeyRoot,
_ => throw new ArgumentOutOfRangeException(nameof(gameServer), gameServer, null)
};
ResolutionHeight = Common.GetRegDword(keyRoot, ResolutionHeightKey) ?? 0;
ResolutionWidth = Common.GetRegDword(keyRoot, ResolutionWidthKey) ?? 0;
IsFullScreen = Common.GetRegDword(keyRoot, IsFullScreenKey) == 1;
}
public static void SaveScreenSettings(GameServer gameServer, int width, int height, bool isFullScreen)
{
var keyRoot = gameServer switch
{
GameServer.China => ChinaKeyRoot,
GameServer.Global => GlobalKeyRoot,
_ => throw new ArgumentOutOfRangeException(nameof(gameServer), gameServer, null)
};
Common.SetRegDword(keyRoot, ResolutionHeightKey, height);
Common.SetRegDword(keyRoot, ResolutionWidthKey, width);
Common.SetRegDword(keyRoot, IsFullScreenKey, isFullScreen ? 1 : 3);
}
} | 412 | 0.5487 | 1 | 0.5487 | game-dev | MEDIA | 0.925776 | game-dev | 0.751862 | 1 | 0.751862 |
lytico/db4o | 2,288 | db4o.net/Db4objects.Db4o.Tests/Db4objects.Db4o.Tests/Common/Reflect/Custom/CustomClassRepository.cs | /* Copyright (C) 2004 - 2011 Versant Inc. http://www.db4o.com */
using System;
using System.Collections;
using Db4objects.Db4o.Foundation;
using Db4objects.Db4o.Reflect;
using Db4objects.Db4o.Tests.Common.Reflect.Custom;
namespace Db4objects.Db4o.Tests.Common.Reflect.Custom
{
public class CustomClassRepository
{
public Hashtable4 _classes;
[System.NonSerialized]
public CustomReflector _reflector;
public CustomClassRepository()
{
// fields must be public so test works on less capable runtimes
_classes = new Hashtable4();
}
public virtual CustomClass ForName(string className)
{
return (CustomClass)_classes.Get(className);
}
public virtual CustomClass DefineClass(string className, string[] fieldNames, string
[] fieldTypes)
{
AssertNotDefined(className);
CustomClass klass = CreateClass(className, fieldNames, fieldTypes);
return DefineClass(klass);
}
private CustomClass CreateClass(string className, string[] fieldNames, string[] fieldTypes
)
{
return new CustomClass(this, className, fieldNames, ResolveTypes(fieldTypes));
}
private Type[] ResolveTypes(string[] typeNames)
{
Type[] types = new Type[typeNames.Length];
for (int i = 0; i < types.Length; ++i)
{
types[i] = ResolveType(typeNames[i]);
}
return types;
}
private Type ResolveType(string typeName)
{
if (typeName.Equals("string"))
{
return typeof(string);
}
if (typeName.Equals("int"))
{
return typeof(int);
}
throw new ArgumentException("Invalid type '" + typeName + "'");
}
private CustomClass DefineClass(CustomClass klass)
{
_classes.Put(klass.GetName(), klass);
return klass;
}
private void AssertNotDefined(string className)
{
if (_classes.ContainsKey(className))
{
throw new ArgumentException("Class '" + className + "' already defined.");
}
}
public virtual void Initialize(CustomReflector reflector)
{
_reflector = reflector;
}
public virtual IReflectClass ForFieldType(Type type)
{
return _reflector.ForFieldType(type);
}
public override string ToString()
{
return "CustomClassRepository(classes: " + _classes.Size() + ")";
}
public virtual IEnumerator Iterator()
{
return _classes.ValuesIterator();
}
}
}
| 412 | 0.767504 | 1 | 0.767504 | game-dev | MEDIA | 0.283238 | game-dev | 0.909601 | 1 | 0.909601 |
Mandarancio/OpenGOO | 8,197 | src/extlibs/box2d/Box2D/Dynamics/b2Fixture.cpp | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "b2Fixture.h"
#include "Contacts/b2Contact.h"
#include "b2World.h"
#include "../Collision/Shapes/b2CircleShape.h"
#include "../Collision/Shapes/b2EdgeShape.h"
#include "../Collision/Shapes/b2PolygonShape.h"
#include "../Collision/Shapes/b2ChainShape.h"
#include "../Collision/b2BroadPhase.h"
#include "../Collision/b2Collision.h"
#include "../Common/b2BlockAllocator.h"
b2Fixture::b2Fixture()
{
m_userData = NULL;
m_body = NULL;
m_next = NULL;
m_proxies = NULL;
m_proxyCount = 0;
m_shape = NULL;
m_density = 0.0f;
}
void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def)
{
m_userData = def->userData;
m_friction = def->friction;
m_restitution = def->restitution;
m_body = body;
m_next = NULL;
m_filter = def->filter;
m_isSensor = def->isSensor;
m_shape = def->shape->Clone(allocator);
// Reserve proxy space
int32 childCount = m_shape->GetChildCount();
m_proxies = (b2FixtureProxy*)allocator->Allocate(childCount * sizeof(b2FixtureProxy));
for (int32 i = 0; i < childCount; ++i)
{
m_proxies[i].fixture = NULL;
m_proxies[i].proxyId = b2BroadPhase::e_nullProxy;
}
m_proxyCount = 0;
m_density = def->density;
}
void b2Fixture::Destroy(b2BlockAllocator* allocator)
{
// The proxies must be destroyed before calling this.
b2Assert(m_proxyCount == 0);
// Free the proxy array.
int32 childCount = m_shape->GetChildCount();
allocator->Free(m_proxies, childCount * sizeof(b2FixtureProxy));
m_proxies = NULL;
// Free the child shape.
switch (m_shape->m_type)
{
case b2Shape::e_circle:
{
b2CircleShape* s = (b2CircleShape*)m_shape;
s->~b2CircleShape();
allocator->Free(s, sizeof(b2CircleShape));
}
break;
case b2Shape::e_edge:
{
b2EdgeShape* s = (b2EdgeShape*)m_shape;
s->~b2EdgeShape();
allocator->Free(s, sizeof(b2EdgeShape));
}
break;
case b2Shape::e_polygon:
{
b2PolygonShape* s = (b2PolygonShape*)m_shape;
s->~b2PolygonShape();
allocator->Free(s, sizeof(b2PolygonShape));
}
break;
case b2Shape::e_chain:
{
b2ChainShape* s = (b2ChainShape*)m_shape;
s->~b2ChainShape();
allocator->Free(s, sizeof(b2ChainShape));
}
break;
default:
b2Assert(false);
break;
}
m_shape = NULL;
}
void b2Fixture::CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf)
{
b2Assert(m_proxyCount == 0);
// Create proxies in the broad-phase.
m_proxyCount = m_shape->GetChildCount();
for (int32 i = 0; i < m_proxyCount; ++i)
{
b2FixtureProxy* proxy = m_proxies + i;
m_shape->ComputeAABB(&proxy->aabb, xf, i);
proxy->proxyId = broadPhase->CreateProxy(proxy->aabb, proxy);
proxy->fixture = this;
proxy->childIndex = i;
}
}
void b2Fixture::DestroyProxies(b2BroadPhase* broadPhase)
{
// Destroy proxies in the broad-phase.
for (int32 i = 0; i < m_proxyCount; ++i)
{
b2FixtureProxy* proxy = m_proxies + i;
broadPhase->DestroyProxy(proxy->proxyId);
proxy->proxyId = b2BroadPhase::e_nullProxy;
}
m_proxyCount = 0;
}
void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2)
{
if (m_proxyCount == 0)
{
return;
}
for (int32 i = 0; i < m_proxyCount; ++i)
{
b2FixtureProxy* proxy = m_proxies + i;
// Compute an AABB that covers the swept shape (may miss some rotation effect).
b2AABB aabb1, aabb2;
m_shape->ComputeAABB(&aabb1, transform1, proxy->childIndex);
m_shape->ComputeAABB(&aabb2, transform2, proxy->childIndex);
proxy->aabb.Combine(aabb1, aabb2);
b2Vec2 displacement = transform2.p - transform1.p;
broadPhase->MoveProxy(proxy->proxyId, proxy->aabb, displacement);
}
}
void b2Fixture::SetFilterData(const b2Filter& filter)
{
m_filter = filter;
Refilter();
}
void b2Fixture::Refilter()
{
if (m_body == NULL)
{
return;
}
// Flag associated contacts for filtering.
b2ContactEdge* edge = m_body->GetContactList();
while (edge)
{
b2Contact* contact = edge->contact;
b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureB = contact->GetFixtureB();
if (fixtureA == this || fixtureB == this)
{
contact->FlagForFiltering();
}
edge = edge->next;
}
b2World* world = m_body->GetWorld();
if (world == NULL)
{
return;
}
// Touch each proxy so that new pairs may be created
b2BroadPhase* broadPhase = &world->m_contactManager.m_broadPhase;
for (int32 i = 0; i < m_proxyCount; ++i)
{
broadPhase->TouchProxy(m_proxies[i].proxyId);
}
}
void b2Fixture::SetSensor(bool sensor)
{
if (sensor != m_isSensor)
{
m_body->SetAwake(true);
m_isSensor = sensor;
}
}
void b2Fixture::Dump(int32 bodyIndex)
{
b2Log(" b2FixtureDef fd;\n");
b2Log(" fd.friction = %.15lef;\n", m_friction);
b2Log(" fd.restitution = %.15lef;\n", m_restitution);
b2Log(" fd.density = %.15lef;\n", m_density);
b2Log(" fd.isSensor = bool(%d);\n", m_isSensor);
b2Log(" fd.filter.categoryBits = uint16(%d);\n", m_filter.categoryBits);
b2Log(" fd.filter.maskBits = uint16(%d);\n", m_filter.maskBits);
b2Log(" fd.filter.groupIndex = int16(%d);\n", m_filter.groupIndex);
switch (m_shape->m_type)
{
case b2Shape::e_circle:
{
b2CircleShape* s = (b2CircleShape*)m_shape;
b2Log(" b2CircleShape shape;\n");
b2Log(" shape.m_radius = %.15lef;\n", s->m_radius);
b2Log(" shape.m_p.Set(%.15lef, %.15lef);\n", s->m_p.x, s->m_p.y);
}
break;
case b2Shape::e_edge:
{
b2EdgeShape* s = (b2EdgeShape*)m_shape;
b2Log(" b2EdgeShape shape;\n");
b2Log(" shape.m_radius = %.15lef;\n", s->m_radius);
b2Log(" shape.m_vertex0.Set(%.15lef, %.15lef);\n", s->m_vertex0.x, s->m_vertex0.y);
b2Log(" shape.m_vertex1.Set(%.15lef, %.15lef);\n", s->m_vertex1.x, s->m_vertex1.y);
b2Log(" shape.m_vertex2.Set(%.15lef, %.15lef);\n", s->m_vertex2.x, s->m_vertex2.y);
b2Log(" shape.m_vertex3.Set(%.15lef, %.15lef);\n", s->m_vertex3.x, s->m_vertex3.y);
b2Log(" shape.m_hasVertex0 = bool(%d);\n", s->m_hasVertex0);
b2Log(" shape.m_hasVertex3 = bool(%d);\n", s->m_hasVertex3);
}
break;
case b2Shape::e_polygon:
{
b2PolygonShape* s = (b2PolygonShape*)m_shape;
b2Log(" b2PolygonShape shape;\n");
b2Log(" b2Vec2 vs[%d];\n", b2_maxPolygonVertices);
for (int32 i = 0; i < s->m_vertexCount; ++i)
{
b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y);
}
b2Log(" shape.Set(vs, %d);\n", s->m_vertexCount);
}
break;
case b2Shape::e_chain:
{
b2ChainShape* s = (b2ChainShape*)m_shape;
b2Log(" b2ChainShape shape;\n");
b2Log(" b2Vec2 vs[%d];\n", s->m_count);
for (int32 i = 0; i < s->m_count; ++i)
{
b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y);
}
b2Log(" shape.CreateChain(vs, %d);\n", s->m_count);
b2Log(" shape.m_prevVertex.Set(%.15lef, %.15lef);\n", s->m_prevVertex.x, s->m_prevVertex.y);
b2Log(" shape.m_nextVertex.Set(%.15lef, %.15lef);\n", s->m_nextVertex.x, s->m_nextVertex.y);
b2Log(" shape.m_hasPrevVertex = bool(%d);\n", s->m_hasPrevVertex);
b2Log(" shape.m_hasNextVertex = bool(%d);\n", s->m_hasNextVertex);
}
break;
default:
return;
}
b2Log("\n");
b2Log(" fd.shape = &shape;\n");
b2Log("\n");
b2Log(" bodies[%d]->CreateFixture(&fd);\n", bodyIndex);
}
| 412 | 0.967205 | 1 | 0.967205 | game-dev | MEDIA | 0.832591 | game-dev | 0.989501 | 1 | 0.989501 |
rdelezuch/Slime-King-in-Space-Game | 1,091 | Slime King in Space/Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/SetPropertyUtility.cs | using System;
using System.Collections.Generic;
using UnityEngine.Events;
namespace UnityEngine.UI
{
internal static class SetPropertyUtility
{
public static bool SetColor(ref Color currentValue, Color newValue)
{
if (currentValue.r == newValue.r && currentValue.g == newValue.g && currentValue.b == newValue.b && currentValue.a == newValue.a)
return false;
currentValue = newValue;
return true;
}
public static bool SetStruct<T>(ref T currentValue, T newValue) where T : struct
{
if (EqualityComparer<T>.Default.Equals(currentValue, newValue))
return false;
currentValue = newValue;
return true;
}
public static bool SetClass<T>(ref T currentValue, T newValue) where T : class
{
if ((currentValue == null && newValue == null) || (currentValue != null && currentValue.Equals(newValue)))
return false;
currentValue = newValue;
return true;
}
}
}
| 412 | 0.629921 | 1 | 0.629921 | game-dev | MEDIA | 0.704257 | game-dev | 0.596233 | 1 | 0.596233 |
MichaelAquilina/synapse-project | 6,658 | src/ui/tile-view/tile-view.vala | /*
* Copyright (C) 2010 Michal Hruby <michal.mhr@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Authored by Michal Hruby <michal.mhr@gmail.com>
*
*/
namespace UI.Widgets
{
public class TileView : Gtk.EventBox
{
private List<Tile> tiles = new List<Tile> ();
private Gtk.Box box = new Gtk.Box (Gtk.Orientation.VERTICAL, 0);
public int icon_size { get; construct set; default = 48; }
protected int selected_index = -1;
public TileView ()
{
GLib.Object (can_focus: true, visible_window: false);
this.button_press_event.connect (this.on_button_press);
this.key_press_event.connect (this.on_key_press);
box.homogeneous = false;
box.show ();
this.add (box);
style_updated ();
}
public virtual void append_tile (AbstractTileObject tile_obj)
{
Tile tile = new Tile (tile_obj, this.icon_size);
tile.owner = this;
tile.active_changed.connect (this.on_tile_active_changed);
tile.size_allocate.connect (this.on_tile_size_allocated);
tile.show ();
tiles.append (tile);
box.pack_start (tile, false, false, 0);
}
public virtual void remove_tile (AbstractTileObject tile_obj)
{
unowned Tile tile = null;
foreach (unowned Tile t in tiles)
{
if (t.owned_object == tile_obj)
{
tile = t;
break;
}
}
if (tile == null)
{
warning ("Container does not own this AbstractTileObject!");
return;
}
if (selected_index == tiles.index (tile))
{
clear_selection ();
}
tile.hide ();
tile.active_changed.disconnect (this.on_tile_active_changed);
tile.size_allocate.disconnect (this.on_tile_size_allocated);
tile.owner = null;
box.remove (tile);
tiles.remove (tile);
}
public List<unowned AbstractTileObject> get_tiles ()
{
var result = new List<unowned AbstractTileObject> ();
foreach (unowned Tile t in tiles)
{
result.prepend (t.owned_object);
}
result.reverse ();
return result;
}
public void clear ()
{
var tiles_copy = this.get_tiles ();
foreach (unowned AbstractTileObject to in tiles_copy)
{
this.remove_tile (to);
}
}
public virtual void clear_selection ()
{
if (0 <= selected_index < tiles.length ())
{
tiles.nth_data (selected_index).set_selected (false);
}
selected_index = -1;
}
public virtual AbstractTileObject? get_current_tile ()
{
if (0 <= selected_index < tiles.length ())
{
return tiles.nth_data (selected_index).owned_object;
}
return null;
}
protected override void style_updated ()
{
/*if (changing_style) return;
changing_style = true;
base.style_updated ();
unowned Widget p = this.get_parent ();
p.modify_bg (StateType.NORMAL, style.@base[StateType.NORMAL]);
changing_style = false;*/
}
public virtual void on_tile_active_changed (Tile tile)
{
tile.owned_object.active_changed ();
foreach (unowned Tile t in tiles)
{
t.update_state ();
}
}
public virtual void on_tile_size_allocated (Gtk.Widget w, Gtk.Allocation alloc)
{
Tile tile = w as Tile;
Gtk.ScrolledWindow? scroll = null;
scroll = this.get_parent () == null ?
null : this.get_parent ().get_parent () as Gtk.ScrolledWindow;
if (scroll == null)
{
return;
}
if (tiles.index (tile) != selected_index)
{
return;
}
unowned Gtk.Adjustment scroll_vadj = scroll.get_vadjustment ();
Gdk.Rectangle va = {0, (int) scroll_vadj.get_value (),
alloc.width, this.get_parent ().get_allocated_height ()};
var va_region = new Cairo.Region.rectangle (va);
if (va_region.contains_rectangle ((Cairo.RectangleInt)alloc) != Cairo.RegionOverlap.IN)
{
double delta = 0.0;
if (alloc.y + alloc.height > va.y + va.height)
{
delta = alloc.y + alloc.height - (va.y + va.height);
delta += this.style.ythickness * 2;
}
else if (alloc.y < va.y)
{
delta = alloc.y - va.y;
}
scroll_vadj.set_value (va.y + delta);
this.queue_draw ();
}
}
protected bool on_button_press (Gdk.EventButton event)
{
this.has_focus = true;
clear_selection ();
for (int i=0; i<tiles.length (); i++)
{
unowned Tile t = tiles.nth_data (i);
Gtk.Allocation alloc;
t.get_allocation (out alloc);
var region = new Cairo.Region.rectangle ((Cairo.RectangleInt)alloc);
if (region.contains_point ((int)event.x, (int)event.y))
{
this.select (i);
break;
}
}
this.queue_draw ();
return false;
}
protected bool on_key_press (Gdk.EventKey event)
{
int index = selected_index;
switch (event.keyval)
{
case Gdk.Key.Up:
case Gdk.Key.KP_Up:
case Gdk.Key.uparrow:
index--;
break;
case Gdk.Key.Down:
case Gdk.Key.KP_Down:
case Gdk.Key.downarrow:
index++;
break;
}
index = index.clamp (0, (int) tiles.length () - 1);
if (index != selected_index)
{
clear_selection ();
this.select (index);
return true;
}
return false;
}
public void select (int index)
{
if (0 <= index < tiles.length ())
{
selected_index = index;
tiles.nth_data (index).set_selected (true);
}
else
{
clear_selection ();
}
if (this.get_parent () != null && this.get_parent ().get_realized ())
{
this.get_parent ().queue_draw ();
}
this.queue_resize ();
}
}
}
| 412 | 0.931588 | 1 | 0.931588 | game-dev | MEDIA | 0.873293 | game-dev | 0.978084 | 1 | 0.978084 |
supersol-ai/SuperSol-Core | 5,857 | perf/benches/sigverify.rs | #![feature(test)]
extern crate test;
use {
log::*,
rand::{thread_rng, Rng},
solana_perf::{
packet::{to_packet_batches, Packet, PacketBatch},
recycler::Recycler,
sigverify,
test_tx::{test_multisig_tx, test_tx},
},
test::Bencher,
};
const NUM: usize = 256;
const LARGE_BATCH_PACKET_COUNT: usize = 128;
#[bench]
fn bench_sigverify_simple(bencher: &mut Bencher) {
let tx = test_tx();
let num_packets = NUM;
// generate packet vector
let mut batches = to_packet_batches(
&std::iter::repeat(tx).take(num_packets).collect::<Vec<_>>(),
128,
);
let recycler = Recycler::default();
let recycler_out = Recycler::default();
// verify packets
bencher.iter(|| {
sigverify::ed25519_verify(&mut batches, &recycler, &recycler_out, false, num_packets);
})
}
fn gen_batches(
use_same_tx: bool,
packets_per_batch: usize,
total_packets: usize,
) -> Vec<PacketBatch> {
if use_same_tx {
let tx = test_tx();
to_packet_batches(&vec![tx; total_packets], packets_per_batch)
} else {
let txs: Vec<_> = std::iter::repeat_with(test_tx)
.take(total_packets)
.collect();
to_packet_batches(&txs, packets_per_batch)
}
}
#[bench]
#[ignore]
fn bench_sigverify_low_packets_small_batch(bencher: &mut Bencher) {
let num_packets = sigverify::VERIFY_PACKET_CHUNK_SIZE - 1;
let mut batches = gen_batches(false, 1, num_packets);
let recycler = Recycler::default();
let recycler_out = Recycler::default();
bencher.iter(|| {
sigverify::ed25519_verify(&mut batches, &recycler, &recycler_out, false, num_packets);
})
}
#[bench]
#[ignore]
fn bench_sigverify_low_packets_large_batch(bencher: &mut Bencher) {
let num_packets = sigverify::VERIFY_PACKET_CHUNK_SIZE - 1;
let mut batches = gen_batches(false, LARGE_BATCH_PACKET_COUNT, num_packets);
let recycler = Recycler::default();
let recycler_out = Recycler::default();
bencher.iter(|| {
sigverify::ed25519_verify(&mut batches, &recycler, &recycler_out, false, num_packets);
})
}
#[bench]
#[ignore]
fn bench_sigverify_medium_packets_small_batch(bencher: &mut Bencher) {
let num_packets = sigverify::VERIFY_PACKET_CHUNK_SIZE * 8;
let mut batches = gen_batches(false, 1, num_packets);
let recycler = Recycler::default();
let recycler_out = Recycler::default();
bencher.iter(|| {
sigverify::ed25519_verify(&mut batches, &recycler, &recycler_out, false, num_packets);
})
}
#[bench]
#[ignore]
fn bench_sigverify_medium_packets_large_batch(bencher: &mut Bencher) {
let num_packets = sigverify::VERIFY_PACKET_CHUNK_SIZE * 8;
let mut batches = gen_batches(false, LARGE_BATCH_PACKET_COUNT, num_packets);
let recycler = Recycler::default();
let recycler_out = Recycler::default();
bencher.iter(|| {
sigverify::ed25519_verify(&mut batches, &recycler, &recycler_out, false, num_packets);
})
}
#[bench]
#[ignore]
fn bench_sigverify_high_packets_small_batch(bencher: &mut Bencher) {
let num_packets = sigverify::VERIFY_PACKET_CHUNK_SIZE * 32;
let mut batches = gen_batches(false, 1, num_packets);
let recycler = Recycler::default();
let recycler_out = Recycler::default();
bencher.iter(|| {
sigverify::ed25519_verify(&mut batches, &recycler, &recycler_out, false, num_packets);
})
}
#[bench]
#[ignore]
fn bench_sigverify_high_packets_large_batch(bencher: &mut Bencher) {
let num_packets = sigverify::VERIFY_PACKET_CHUNK_SIZE * 32;
let mut batches = gen_batches(false, LARGE_BATCH_PACKET_COUNT, num_packets);
let recycler = Recycler::default();
let recycler_out = Recycler::default();
// verify packets
bencher.iter(|| {
sigverify::ed25519_verify(&mut batches, &recycler, &recycler_out, false, num_packets);
})
}
#[bench]
#[ignore]
fn bench_sigverify_uneven(bencher: &mut Bencher) {
solana_logger::setup();
let simple_tx = test_tx();
let multi_tx = test_multisig_tx();
let mut tx;
let num_packets = NUM * 50;
let mut num_valid = 0;
let mut current_packets = 0;
// generate packet vector
let mut batches = vec![];
while current_packets < num_packets {
let mut len: usize = thread_rng().gen_range(1..128);
current_packets += len;
if current_packets > num_packets {
len -= current_packets - num_packets;
current_packets = num_packets;
}
let mut batch = PacketBatch::with_capacity(len);
batch.resize(len, Packet::default());
for packet in batch.iter_mut() {
if thread_rng().gen_ratio(1, 2) {
tx = simple_tx.clone();
} else {
tx = multi_tx.clone();
};
Packet::populate_packet(packet, None, &tx).expect("serialize request");
if thread_rng().gen_ratio((num_packets - NUM) as u32, num_packets as u32) {
packet.meta_mut().set_discard(true);
} else {
num_valid += 1;
}
}
batches.push(batch);
}
info!("num_packets: {} valid: {}", num_packets, num_valid);
let recycler = Recycler::default();
let recycler_out = Recycler::default();
// verify packets
bencher.iter(|| {
sigverify::ed25519_verify(&mut batches, &recycler, &recycler_out, false, num_packets);
})
}
#[bench]
fn bench_get_offsets(bencher: &mut Bencher) {
let tx = test_tx();
// generate packet vector
let mut batches =
to_packet_batches(&std::iter::repeat(tx).take(1024).collect::<Vec<_>>(), 1024);
let recycler = Recycler::default();
// verify packets
bencher.iter(|| {
let _ans = sigverify::generate_offsets(&mut batches, &recycler, false);
})
}
| 412 | 0.882958 | 1 | 0.882958 | game-dev | MEDIA | 0.465427 | game-dev | 0.80837 | 1 | 0.80837 |
MATTYOneInc/AionEncomBase_Java8 | 3,822 | AL-Game/data/scripts/system/handlers/quest/theobomos/_3048Owner_Of_The_Angled_Blade_Dagger.java | /*
* =====================================================================================*
* This file is part of Aion-Unique (Aion-Unique Home Software Development) *
* Aion-Unique Development is a closed Aion Project that use Old Aion Project Base *
* Like Aion-Lightning, Aion-Engine, Aion-Core, Aion-Extreme, Aion-NextGen, ArchSoft, *
* Aion-Ger, U3J, Encom And other Aion project, All Credit Content *
* That they make is belong to them/Copyright is belong to them. And All new Content *
* that Aion-Unique make the copyright is belong to Aion-Unique *
* You may have agreement with Aion-Unique Development, before use this Engine/Source *
* You have agree with all of Term of Services agreement with Aion-Unique Development *
* =====================================================================================*
*/
package quest.theobomos;
import com.aionemu.gameserver.model.gameobjects.Item;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.questEngine.handlers.HandlerResult;
import com.aionemu.gameserver.questEngine.handlers.QuestHandler;
import com.aionemu.gameserver.questEngine.model.QuestDialog;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
/****/
/** Author Ghostfur & Unknown (Aion-Unique)
/****/
public class _3048Owner_Of_The_Angled_Blade_Dagger extends QuestHandler {
private final static int questId = 3048;
public _3048Owner_Of_The_Angled_Blade_Dagger() {
super(questId);
}
@Override
public void register() {
qe.registerQuestNpc(798208).addOnTalkEvent(questId);
qe.registerQuestNpc(798206).addOnTalkEvent(questId);
qe.registerQuestItem(182208033, questId); //Angled Blade Dagger.
}
@Override
public HandlerResult onItemUseEvent(QuestEnv env, Item item) {
final Player player = env.getPlayer();
final QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs == null || qs.getStatus() == QuestStatus.NONE) {
return HandlerResult.fromBoolean(sendQuestDialog(env, 4));
}
return HandlerResult.FAILED;
}
@Override
public boolean onDialogEvent(QuestEnv env) {
int targetId = 0;
final Player player = env.getPlayer();
final QuestState qs = player.getQuestStateList().getQuestState(questId);
if (env.getVisibleObject() instanceof Npc) {
targetId = ((Npc) env.getVisibleObject()).getNpcId();
} if (targetId == 0) {
if (env.getDialogId() == 1002) {
return sendQuestStartDialog(env);
}
if (env.getDialogId() == 1003) {
return closeDialogWindow(env);
}
} else if (targetId == 798208) {
if (qs != null && qs.getStatus() == QuestStatus.START && qs.getQuestVarById(0) == 0) {
if (env.getDialog() == QuestDialog.START_DIALOG) {
return sendQuestDialog(env, 1352);
} else if (env.getDialog() == QuestDialog.STEP_TO_1) {
qs.setQuestVarById(0, qs.getQuestVarById(0) + 1);
updateQuestStatus(env);
return closeDialogWindow(env);
}
}
} else if (targetId == 798206) {
if (qs != null && qs.getStatus() == QuestStatus.START && qs.getQuestVarById(0) == 1) {
if (env.getDialog() == QuestDialog.START_DIALOG) {
return sendQuestDialog(env, 2375);
} else if (env.getDialogId() == 1009) {
removeQuestItem(env, 182208033, 1); //Angled Blade Dagger.
qs.setQuestVar(1);
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
return sendQuestEndDialog(env);
}
}
else if (qs != null && qs.getStatus() == QuestStatus.REWARD) {
return sendQuestEndDialog(env);
}
}
return false;
}
} | 412 | 0.947819 | 1 | 0.947819 | game-dev | MEDIA | 0.959141 | game-dev | 0.970138 | 1 | 0.970138 |
00-Evan/shattered-pixel-dungeon-gdx | 3,572 | core/src/com/shatteredpixel/shatteredpixeldungeon/items/potions/elixirs/ElixirOfMight.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2019 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.items.potions.elixirs;
import com.shatteredpixel.shatteredpixeldungeon.Badges;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.AlchemicalCatalyst;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfStrength;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.sprites.CharSprite;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
import com.shatteredpixel.shatteredpixeldungeon.ui.BuffIndicator;
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog;
import com.watabou.utils.Bundle;
public class ElixirOfMight extends Elixir {
{
image = ItemSpriteSheet.ELIXIR_MIGHT;
}
@Override
public void apply( Hero hero ) {
setKnown();
hero.STR++;
Buff.affect(hero, HTBoost.class).reset();
HTBoost boost = Buff.affect(hero, HTBoost.class);
boost.reset();
hero.updateHT( true );
hero.sprite.showStatus( CharSprite.POSITIVE, Messages.get(this, "msg_1", boost.boost() ));
GLog.p( Messages.get(this, "msg_2") );
Badges.validateStrengthAttained();
}
public String desc() {
return Messages.get(this, "desc", HTBoost.boost(Dungeon.hero.HT));
}
@Override
public int price() {
//prices of ingredients
return quantity * (50 + 40);
}
public static class Recipe extends com.shatteredpixel.shatteredpixeldungeon.items.Recipe.SimpleRecipe {
{
inputs = new Class[]{PotionOfStrength.class, AlchemicalCatalyst.class};
inQuantity = new int[]{1, 1};
cost = 5;
output = ElixirOfMight.class;
outQuantity = 1;
}
}
public static class HTBoost extends Buff {
{
type = buffType.POSITIVE;
}
private int left;
public void reset(){
left = 5;
}
public int boost(){
return Math.round(left*boost(target.HT)/5f);
}
public static int boost(int HT){
return Math.round(4 + HT/20f);
}
public void onLevelUp(){
left --;
if (left <= 0){
detach();
}
}
@Override
public int icon() {
return BuffIndicator.HEALING;
}
@Override
public String toString() {
return Messages.get(this, "name");
}
@Override
public String desc() {
return Messages.get(this, "desc", boost(), left);
}
private static String LEFT = "left";
@Override
public void storeInBundle(Bundle bundle) {
super.storeInBundle(bundle);
bundle.put( LEFT, left );
}
@Override
public void restoreFromBundle(Bundle bundle) {
super.restoreFromBundle(bundle);
left = bundle.getInt(LEFT);
}
}
}
| 412 | 0.678101 | 1 | 0.678101 | game-dev | MEDIA | 0.982816 | game-dev | 0.952126 | 1 | 0.952126 |
Bunny67/Details-WotLK | 61,260 | Details/core/control.lua |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
local _detalhes = _G._detalhes
local Loc = LibStub("AceLocale-3.0"):GetLocale( "Details" )
local SharedMedia = LibStub:GetLibrary("LibSharedMedia-3.0")
local _tempo = time()
local _
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> local pointers
local _math_floor = math.floor --lua local
local _math_max = math.max --lua local
local _ipairs = ipairs --lua local
local _pairs = pairs --lua local
local _table_wipe = table.wipe --lua local
local _bit_band = bit.band --lua local
local _GetInstanceInfo = GetInstanceInfo --wow api local
local _GetCurrentMapAreaID = GetCurrentMapAreaID --wow api local
local _GetRealZoneText = GetRealZoneText --wow api local
local _GetInstanceDifficulty = GetInstanceDifficulty --wow api local
local _UnitExists = UnitExists --wow api local
local _UnitGUID = UnitGUID --wow api local
local _UnitName = UnitName --wow api local
local _GetTime = GetTime
local _IsAltKeyDown = IsAltKeyDown
local _IsShiftKeyDown = IsShiftKeyDown
local _IsControlKeyDown = IsControlKeyDown
local atributo_damage = _detalhes.atributo_damage --details local
local atributo_heal = _detalhes.atributo_heal --details local
local atributo_energy = _detalhes.atributo_energy --details local
local atributo_misc = _detalhes.atributo_misc --details local
local atributo_custom = _detalhes.atributo_custom --details local
local info = _detalhes.janela_info --details local
local UnitGroupRolesAssigned = DetailsFramework.UnitGroupRolesAssigned
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> constants
local modo_GROUP = _detalhes.modos.group
local modo_ALL = _detalhes.modos.all
local class_type_dano = _detalhes.atributos.dano
local OBJECT_TYPE_PETS = 0x00003000
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> details api functions
--> try to find the opponent of last fight, can be called during a fight as well
function _detalhes:FindEnemy()
local ZoneName, InstanceType = _GetInstanceInfo()
local ZoneMapID = _GetCurrentMapAreaID()
local in_instance = IsInInstance() --> garrison returns party as instance type.
if (InstanceType == "party" or InstanceType == "raid") and in_instance then
if InstanceType == "party" then
if _detalhes:GetBossNames(_detalhes.zone_id) then
return Loc["STRING_SEGMENT_TRASH"]
end
else
return Loc["STRING_SEGMENT_TRASH"]
end
end
for _, actor in _ipairs(_detalhes.tabela_vigente[class_type_dano]._ActorTable) do
if not actor.grupo and not actor.owner and not actor.nome:find("[*]") and _bit_band(actor.flag_original, 0x00000060) ~= 0 then --> 0x20+0x40 neutral + enemy reaction
for name, _ in _pairs(actor.targets) do
if name == _detalhes.playername then
return actor.nome
else
local _target_actor = _detalhes.tabela_vigente(class_type_dano, name)
if _target_actor and _target_actor.grupo then
return actor.nome
end
end
end
end
end
for _, actor in _ipairs(_detalhes.tabela_vigente[class_type_dano]._ActorTable) do
if actor.grupo and not actor.owner then
for target_name, _ in _pairs(actor.targets) do
return target_name
end
end
end
return Loc["STRING_UNKNOW"]
end
local boss_found = function(index, name, zone, mapid, diff, encounterid)
local mapID = GetCurrentMapAreaID()
if not mapID then
--print("Details! exeption handled: zone has no map")
return
end
local boss_table = {
index = index,
name = name,
encounter = name,
zone = zone,
mapid = mapid,
diff = diff,
diff_string = select(4, GetInstanceInfo()),
id = encounterid,
}
if not _detalhes:IsRaidRegistered(mapid) and _detalhes.zone_type == "raid" then
local boss_list = _detalhes:GetCurrentDungeonBossListFromEJ()
if boss_list then
local ActorsContainer = _detalhes.tabela_vigente[class_type_dano]._ActorTable
if ActorsContainer then
for index, Actor in _ipairs(ActorsContainer) do
if not Actor.grupo then
if boss_list[Actor.nome] then
Actor.boss = true
boss_table.bossimage = boss_list[Actor.nome][4]
break
end
end
end
end
end
end
_detalhes.tabela_vigente.is_boss = boss_table
if _detalhes.in_combat and not _detalhes.leaving_combat then
--> catch boss function if any
local bossFunction, bossFunctionType = _detalhes:GetBossFunction(mapID, index)
if bossFunction then
if _bit_band(bossFunctionType, 0x1) ~= 0 then --realtime
_detalhes.bossFunction = bossFunction
_detalhes.tabela_vigente.bossFunction = _detalhes:ScheduleTimer("bossFunction", 1)
end
end
if _detalhes.zone_type ~= "raid" then
local endType, endData = _detalhes:GetEncounterEnd(mapID, index)
if endType and endData then
if _detalhes.debug then
_detalhes:Msg("(debug) setting boss end type to:", endType)
end
_detalhes.encounter_end_table.type = endType
_detalhes.encounter_end_table.killed = {}
_detalhes.encounter_end_table.data = {}
if type(endData) == "table" then
if _detalhes.debug then
_detalhes:Msg("(debug) boss type is table:", endType)
end
if endType == 1 or endType == 2 then
for _, npcID in ipairs(endData) do
_detalhes.encounter_end_table.data[npcID] = false
end
end
else
if endType == 1 or endType == 2 then
_detalhes.encounter_end_table.data[endData] = false
end
end
end
end
end
--> we the boss was found during the combat table creation, we must postpone the event trigger
if not _detalhes.tabela_vigente.IsBeingCreated then
_detalhes:SendEvent("COMBAT_BOSS_FOUND", nil, index, name)
_detalhes:CheckFor_SuppressedWindowsOnEncounterFound()
end
return boss_table
end
function _detalhes:ReadBossFrames()
if _detalhes.tabela_vigente.is_boss then
return --no need to check
end
if _detalhes.encounter_table.name then
local encounter_table = _detalhes.encounter_table
return boss_found(encounter_table.index, encounter_table.name, encounter_table.zone, encounter_table.mapid, encounter_table.diff, encounter_table.id)
end
for index = 1, 4, 1 do
if _UnitExists("boss"..index) then
local guid = _UnitGUID("boss"..index)
if guid then
local serial = _detalhes:GetNpcIdFromGuid(guid)
if serial then
local ZoneName = _GetInstanceInfo()
local DifficultyID = _GetInstanceDifficulty()
local ZoneMapID = _GetCurrentMapAreaID()
local BossIds = _detalhes:GetBossIds(ZoneMapID)
if BossIds then
local BossIndex = BossIds[serial]
if BossIndex then
if _detalhes.debug then
_detalhes:Msg("(debug) boss found:",_detalhes:GetBossName(ZoneMapID, BossIndex))
end
return boss_found(BossIndex, _detalhes:GetBossName(ZoneMapID, BossIndex), ZoneName, ZoneMapID, DifficultyID)
end
end
end
end
end
end
end
--try to get the encounter name after the encounter(can be called during the combat as well)
function _detalhes:FindBoss()
if _detalhes.encounter_table.name then
local encounter_table = _detalhes.encounter_table
return boss_found(encounter_table.index, encounter_table.name, encounter_table.zone, encounter_table.mapid, encounter_table.diff, encounter_table.id)
end
local ZoneName, InstanceType = _GetInstanceInfo()
local ZoneMapID = _GetCurrentMapAreaID()
local DifficultyID = _GetInstanceDifficulty()
local BossIds = _detalhes:GetBossIds(ZoneMapID)
if not BossIds then
for id, data in _pairs(_detalhes.EncounterInformation) do
if data.name == ZoneName then
BossIds = _detalhes:GetBossIds(id)
ZoneMapID = id
break
end
end
end
if BossIds then
local BossIndex = nil
local ActorsContainer = _detalhes.tabela_vigente[class_type_dano]._ActorTable
if ActorsContainer then
for index, Actor in _ipairs(ActorsContainer) do
if not Actor.grupo then
local serial = _detalhes:GetNpcIdFromGuid(Actor.serial)
if serial then
BossIndex = BossIds[serial]
if BossIndex then
Actor.boss = true
return boss_found(BossIndex, _detalhes:GetBossName(ZoneMapID, BossIndex), ZoneName, ZoneMapID, DifficultyID)
end
end
end
end
end
end
return false
end
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> internal functions
-- _detalhes.statistics = {container_calls = 0, container_pet_calls = 0, container_unknow_pet = 0, damage_calls = 0, heal_calls = 0, absorbs_calls = 0, energy_calls = 0, pets_summons = 0}
function _detalhes:StartCombat(...)
return _detalhes:EntrarEmCombate(...)
end
-- ~start ~inicio ~novo �ovo
function _detalhes:EntrarEmCombate(...)
if _detalhes.debug then
_detalhes:Msg("(debug) |cFFFFFF00started a new combat|r|cFFFF7700", _detalhes.encounter_table and _detalhes.encounter_table.name or "")
-- local from = debugstack(2, 1, 0)
-- print(from)
end
if not _detalhes.tabela_historico.tabelas[1] then
_detalhes.tabela_overall = _detalhes.combate:NovaTabela()
_detalhes:InstanciaCallFunction(_detalhes.ResetaGump, nil, -1) --> reseta scrollbar, iterators, rodap�, etc
_detalhes:InstanciaCallFunction(_detalhes.InstanciaFadeBarras, -1) --> esconde todas as barras
_detalhes:InstanciaCallFunction(_detalhes.AtualizaSegmentos) --> atualiza o showing
end
--> re-lock nos tempos da tabela passada -- lock again last table times
_detalhes.tabela_vigente:TravarTempos()
local n_combate = _detalhes:NumeroCombate(1) --aumenta o contador de combates -- combat number up
--> cria a nova tabela de combates -- create new table
local ultimo_combate = _detalhes.tabela_vigente
_detalhes.tabela_vigente = _detalhes.combate:NovaTabela(true, _detalhes.tabela_overall, n_combate, ...) --cria uma nova tabela de combate
--> flag this combat as being created
_detalhes.tabela_vigente.IsBeingCreated = true
_detalhes.tabela_vigente.previous_combat = ultimo_combate
_detalhes.tabela_vigente:seta_data(_detalhes._detalhes_props.DATA_TYPE_START) --seta na tabela do combate a data do inicio do combate -- setup time data
_detalhes.in_combat = true --sinaliza ao addon que h� um combate em andamento -- in combat flag up
_detalhes.tabela_vigente.combat_id = n_combate --> grava o n�mero deste combate na tabela atual -- setup combat id on new table
_detalhes.last_combat_pre_pot_used = nil
_detalhes:FlagCurrentCombat()
--> � o timer que ve se o jogador ta em combate ou n�o -- check if any party or raid members are in combat
_detalhes.tabela_vigente.verifica_combate = _detalhes:ScheduleRepeatingTimer("EstaEmCombate", 1)
_detalhes:ClearCCPetsBlackList()
_table_wipe(_detalhes.encounter_end_table)
_table_wipe(_detalhes.pets_ignored)
_table_wipe(_detalhes.pets_no_owner)
_detalhes.container_pets:BuscarPets()
_table_wipe(_detalhes.cache_dead_npc)
_table_wipe(_detalhes.cache_damage_group)
_table_wipe(_detalhes.cache_healing_group)
_detalhes:UpdateParserGears()
--> get all buff already applied before the combat start
_detalhes:CatchRaidBuffUptime("BUFF_UPTIME_IN")
_detalhes:CatchRaidDebuffUptime("DEBUFF_UPTIME_IN")
_detalhes:UptadeRaidMembersCache()
--> we already have boss information? build .is_boss table
if _detalhes.encounter_table.id and _detalhes.encounter_table["start"] and not _detalhes.encounter_table["end"] then
local encounter_table = _detalhes.encounter_table
--> boss_found will trigger "COMBAT_BOSS_FOUND" event, but at this point of the combat creation is safe to send it
boss_found(encounter_table.index, encounter_table.name, encounter_table.zone, encounter_table.mapid, encounter_table.diff, encounter_table.id)
else
--> if we don't have this infor right now, lets check in few seconds dop
if _detalhes:IsInInstance() then
_detalhes:ScheduleTimer("ReadBossFrames", 1)
_detalhes:ScheduleTimer("ReadBossFrames", 30)
end
end
--> if the window is showing current segment, switch it for the new combat
--> also if the window has auto current, jump to current segment
_detalhes:InstanciaCallFunction(_detalhes.TrocaSegmentoAtual, _detalhes.tabela_vigente.is_boss and true)
--> clear hosts and make the cloud capture stuff
_detalhes.host_of = nil
_detalhes.host_by = nil
if _detalhes.in_group and _detalhes.cloud_capture then
if _detalhes:IsInInstance() or _detalhes.debug then
if not _detalhes:CaptureIsAllEnabled() then
_detalhes:ScheduleSendCloudRequest()
-- if _detalhes.debug then
-- _detalhes:Msg("(debug) requesting a cloud server.")
-- end
end
else
-- if _detalhes.debug then
-- _detalhes:Msg("(debug) isn't inside a registred instance", _detalhes:IsInInstance())
-- end
end
else
-- if _detalhes.debug then
-- _detalhes:Msg("(debug) isn't in group or cloud is turned off", _detalhes.in_group, _detalhes.cloud_capture)
-- end
end
--> hide / alpha / switch in combat
for index, instancia in ipairs(_detalhes.tabela_instancias) do
if instancia.ativa then
--instancia:SetCombatAlpha(nil, nil, true) --passado para o regen disable
instancia:CheckSwitchOnCombatStart(true)
end
end
_detalhes:InstanceCall(_detalhes.CheckPsUpdate)
--> combat creation is completed, remove the flag
_detalhes.tabela_vigente.IsBeingCreated = nil
_detalhes:SendEvent("COMBAT_PLAYER_ENTER", nil, _detalhes.tabela_vigente, _detalhes.encounter_table and _detalhes.encounter_table.id)
if _detalhes.tabela_vigente.is_boss then
--> the encounter was found through encounter_start event
_detalhes:SendEvent("COMBAT_BOSS_FOUND", nil, _detalhes.tabela_vigente.is_boss.index, _detalhes.tabela_vigente.is_boss.name)
end
_detalhes:CheckSwitchToCurrent()
_detalhes:CheckForTextTimeCounter(true)
--> stop bar testing if any
_detalhes:StopTestBarUpdate()
end
function _detalhes:DelayedSyncAlert()
local lower_instance = _detalhes:GetLowerInstanceNumber()
if lower_instance then
lower_instance = _detalhes:GetInstance(lower_instance)
if lower_instance then
if not lower_instance:HaveInstanceAlert() then
lower_instance:InstanceAlert(Loc["STRING_EQUILIZING"], {[[Interface\COMMON\StreamCircle]], 22, 22, true}, 5, {function() end})
end
end
end
end
function _detalhes:ScheduleSyncPlayerActorData()
if (IsInGroup() or IsInRaid()) and (_detalhes.zone_type == "party" or _detalhes.zone_type == "raid") then
--> do not sync if in battleground or arena
_detalhes:SendCharacterData()
end
end
function _detalhes:EndCombat()
if _detalhes.in_combat then
_detalhes:SairDoCombate()
end
end
-- ~end ~leave
function _detalhes:SairDoCombate(bossKilled, from_encounter_end)
if _detalhes.debug then
_detalhes:Msg("(debug) |cFFFFFF00ended a combat|r|cFFFF7700", _detalhes.encounter_table and _detalhes.encounter_table.name or "")
end
--> in case of something somehow someway call to close the same combat a second time.
if _detalhes.tabela_vigente == _detalhes.last_closed_combat then
return
end
_detalhes.last_closed_combat = _detalhes.tabela_vigente
-- if _detalhes.statistics then
-- for k, v in pairs(_detalhes.statistics) do
-- print(k, v)
-- end
-- end
_detalhes.leaving_combat = true
_detalhes.last_combat_time = _tempo
--deprecated(combat are now added immediatelly since there's no script run too long)
-- if _detalhes.schedule_remove_overall and not from_encounter_end and not InCombatLockdown() then
-- if _detalhes.debug then
-- _detalhes:Msg("(debug) found schedule overall data deletion.")
-- end
--
-- _detalhes.schedule_remove_overall = false
-- _detalhes.tabela_historico:resetar_overall()
-- end
_detalhes:CatchRaidBuffUptime("BUFF_UPTIME_OUT")
_detalhes:CatchRaidDebuffUptime("DEBUFF_UPTIME_OUT")
_detalhes:CloseEnemyDebuffsUptime()
--> check if this isn't a boss and try to find a boss in the segment
if not _detalhes.tabela_vigente.is_boss then
_detalhes:FindBoss()
--> still didn't find the boss
if not _detalhes.tabela_vigente.is_boss then
local ZoneName = _GetInstanceInfo()
local ZoneMapID = _GetCurrentMapAreaID()
local DifficultyID = _GetInstanceDifficulty()
local findboss = _detalhes:GetRaidBossFindFunction(ZoneMapID)
if findboss then
local BossIndex = findboss()
if BossIndex then
boss_found(BossIndex, _detalhes:GetBossName(ZoneMapID, BossIndex), ZoneName, ZoneMapID, DifficultyID)
end
end
end
end
if _detalhes.tabela_vigente.bossFunction then
_detalhes:CancelTimer(_detalhes.tabela_vigente.bossFunction)
_detalhes.tabela_vigente.bossFunction = nil
end
--> finaliza a checagem se esta ou n�o no combate -- finish combat check
if _detalhes.tabela_vigente.verifica_combate then
_detalhes:CancelTimer(_detalhes.tabela_vigente.verifica_combate)
_detalhes.tabela_vigente.verifica_combate = nil
end
--> lock timers
_detalhes.tabela_vigente:TravarTempos()
--> get waste shields
-- if _detalhes.close_shields then
-- _detalhes:CloseShields(_detalhes.tabela_vigente)
-- end
--> salva hora, minuto, segundo do fim da luta
_detalhes.tabela_vigente:seta_data(_detalhes._detalhes_props.DATA_TYPE_END)
_detalhes.tabela_vigente:seta_tempo_decorrido()
--> drop last events table to garbage collector
_detalhes.tabela_vigente.player_last_events = {}
--> flag instance type
local _, InstanceType = _GetInstanceInfo()
_detalhes.tabela_vigente.instance_type = InstanceType
if not _detalhes.tabela_vigente.is_boss and from_encounter_end and type(from_encounter_end) == "table" then
local encounterID, encounterName, difficultyID, raidSize, endStatus = unpack(from_encounter_end)
if encounterID then
local ZoneName, InstanceType, _, DifficultyName = GetInstanceInfo()
local DifficultyID = _GetInstanceDifficulty()
local ZoneMapID = _GetCurrentMapAreaID()
local _, boss_index = _detalhes:GetBossEncounterDetailsFromEncounterId(ZoneMapID, encounterID)
_detalhes.tabela_vigente.is_boss = {
index = boss_index or 0,
name = encounterName,
encounter = encounterName,
zone = ZoneName,
mapid = ZoneMapID,
diff = DifficultyID,
diff_string = DifficultyName,
id = encounterID,
}
end
end
--> send item level after a combat if is in raid or party group
_detalhes:ScheduleTimer("ScheduleSyncPlayerActorData", 1)
--if this segment isn't a boss fight
if not _detalhes.tabela_vigente.is_boss then
if _detalhes.tabela_vigente.is_pvp or _detalhes.tabela_vigente.is_arena then
_detalhes:FlagActorsOnPvPCombat()
end
if _detalhes.tabela_vigente.is_arena then
_detalhes.tabela_vigente.enemy = "["..ARENA.."] ".._detalhes.tabela_vigente.is_arena.name
end
local in_instance = IsInInstance() --> garrison returns party as instance type.
if (InstanceType == "party" or InstanceType == "raid") and in_instance then
if InstanceType == "party" then
--> tag the combat as trash clean up
_detalhes.tabela_vigente.is_trash = true
else
_detalhes.tabela_vigente.is_trash = true
end
else
if not in_instance then
if _detalhes.world_combat_is_trash then
_detalhes.tabela_vigente.is_temporary = true
end
end
end
if not _detalhes.tabela_vigente.enemy then
local enemy = _detalhes:FindEnemy()
if enemy and _detalhes.debug then
_detalhes:Msg("(debug) enemy found", enemy)
end
_detalhes.tabela_vigente.enemy = enemy
end
if _detalhes.debug then
-- _detalhes:Msg("(debug) forcing equalize actors behavior.")
-- _detalhes:EqualizeActorsSchedule(_detalhes.host_of)
end
--> verifica memoria
_detalhes:FlagActorsOnCommonFight() --fight_component
-- _detalhes:CheckMemoryAfterCombat() -- 7.2.5 is doing some weird errors even out of combat
else
--this segment is a boss fight
if not InCombatLockdown() and not UnitAffectingCombat("player") then
else
-- _detalhes.schedule_flag_boss_components = true
end
--calling here without checking for combat since the does not ran too long for scripts
_detalhes:FlagActorsOnBossFight()
local boss_id = _detalhes.encounter_table.id
if bossKilled then
_detalhes.tabela_vigente.is_boss.killed = true
--> add to storage
if not InCombatLockdown() and not UnitAffectingCombat("player") and not _detalhes.logoff_saving_data then
-- _detalhes.StoreEncounter()
local successful, errortext = pcall(_detalhes.StoreEncounter)
if not successful then
_detalhes:Msg("error occurred on StoreEncounter():", errortext)
end
else
_detalhes.schedule_store_boss_encounter = true
end
_detalhes:SendEvent("COMBAT_BOSS_DEFEATED", nil, _detalhes.tabela_vigente)
_detalhes:CheckFor_TrashSuppressionOnEncounterEnd()
else
_detalhes:SendEvent("COMBAT_BOSS_WIPE", nil, _detalhes.tabela_vigente)
end
-- if _detalhes:GetBossDetails(_detalhes.tabela_vigente.is_boss.mapid, _detalhes.tabela_vigente.is_boss.index) or then
_detalhes.tabela_vigente.is_boss.index = _detalhes.tabela_vigente.is_boss.index or 1
_detalhes.tabela_vigente.enemy = _detalhes.tabela_vigente.is_boss.encounter
if _detalhes.tabela_vigente.instance_type == "raid" then
_detalhes.last_encounter2 = _detalhes.last_encounter
_detalhes.last_encounter = _detalhes.tabela_vigente.is_boss.name
if _detalhes.pre_pot_used then
_detalhes.last_combat_pre_pot_used = table_deepcopy(_detalhes.pre_pot_used)
end
if _detalhes.pre_pot_used and _detalhes.announce_prepots.enabled then
_detalhes:Msg(_detalhes.pre_pot_used or "")
_detalhes.pre_pot_used = nil
end
end
if from_encounter_end then
if _detalhes.encounter_table.start then
_detalhes.tabela_vigente:SetStartTime(_detalhes.encounter_table.start)
end
_detalhes.tabela_vigente:SetEndTime(_detalhes.encounter_table["end"] or GetTime())
end
--> encounter boss function
local bossFunction, bossFunctionType = _detalhes:GetBossFunction(_detalhes.tabela_vigente.is_boss.mapid or 0, _detalhes.tabela_vigente.is_boss.index or 0)
if bossFunction then
if _bit_band(bossFunctionType, 0x2) ~= 0 then --end of combat
if not _detalhes.logoff_saving_data then
local successful, errortext = pcall(bossFunction, _detalhes.tabela_vigente)
if not successful then
_detalhes:Msg("error occurred on Encounter Boss Function:", errortext)
end
end
end
end
if _detalhes.tabela_vigente.instance_type == "raid" then
--> schedule captures off
_detalhes:CaptureSet(false, "damage", false, 15)
_detalhes:CaptureSet(false, "energy", false, 15)
_detalhes:CaptureSet(false, "aura", false, 15)
_detalhes:CaptureSet(false, "energy", false, 15)
_detalhes:CaptureSet(false, "spellcast", false, 15)
if _detalhes.debug then
_detalhes:Msg("(debug) freezing parser for 15 seconds.")
end
end
--> schedule sync
_detalhes:EqualizeActorsSchedule(_detalhes.host_of)
if _detalhes:GetEncounterEqualize(_detalhes.tabela_vigente.is_boss.mapid, _detalhes.tabela_vigente.is_boss.index) then
_detalhes:ScheduleTimer("DelayedSyncAlert", 3)
end
-- else
-- if _detalhes.debug then
-- _detalhes:EqualizeActorsSchedule(_detalhes.host_of)
-- end
-- end
end
if _detalhes.solo then
--> debuffs need a checkup, not well functional right now
_detalhes.CloseSoloDebuffs()
end
local tempo_do_combate = _detalhes.tabela_vigente:GetCombatTime()
local invalid_combat
-- TEMP
local zoneName, zoneType = GetInstanceInfo()
if not _detalhes.tabela_vigente.discard_segment and(zoneType == "none" or tempo_do_combate >= _detalhes.minimum_combat_time or not _detalhes.tabela_historico.tabelas[1]) then
_detalhes.tabela_historico:adicionar(_detalhes.tabela_vigente) --move a tabela atual para dentro do hist�rico
--8.0.1 miss data isn't required at the moment, spells like akari's soul has been removed from the game
--_detalhes:CanSendMissData()
if _detalhes.tabela_vigente.is_boss then
if IsInRaid() then
local cleuID = _detalhes.tabela_vigente.is_boss.id
local diff = _detalhes.tabela_vigente.is_boss.diff
if cleuID and (diff == 1 or diff == 2 or diff == 3 or diff == 4) then
local raidData = _detalhes.raid_data
--get or build diff raid data table
local diffRaidData = raidData[diff]
if(not diffRaidData) then
diffRaidData = {}
raidData[diff] = diffRaidData
end
--get or build a table for this cleuID
diffRaidData[cleuID] = diffRaidData[cleuID] or {wipes = 0, kills = 0, best_try = 1, longest = 0, try_history = {}}
local cleuIDData = diffRaidData[cleuID]
--store encounter data for plugins and weakauras
if _detalhes.tabela_vigente:GetCombatTime() > cleuIDData.longest then
cleuIDData.longest = _detalhes.tabela_vigente:GetCombatTime()
end
if _detalhes.tabela_vigente.is_boss.killed then
cleuIDData.kills = cleuIDData.kills + 1
cleuIDData.best_try = 0
tinsert(cleuIDData.try_history, {0, _detalhes.tabela_vigente:GetCombatTime()})
-- print("KILL", "best try", cleuIDData.best_try, "amt kills", cleuIDData.kills, "wipes", cleuIDData.wipes, "longest", cleuIDData.longest)
else
cleuIDData.wipes = cleuIDData.wipes + 1
if _detalhes.boss1_health_percent and _detalhes.boss1_health_percent < cleuIDData.best_try then
cleuIDData.best_try = _detalhes.boss1_health_percent
tinsert(cleuIDData.try_history, {_detalhes.boss1_health_percent, _detalhes.tabela_vigente:GetCombatTime()})
end
-- print("WIPE", "best try", cleuIDData.best_try, "amt kills", cleuIDData.kills, "wipes", cleuIDData.wipes, "longest", cleuIDData.longest)
end
end
end
--
end
--the combat is valid, see if the user is sharing data with somebody
if _detalhes.shareData then
local zipData = Details:CompressData(_detalhes.tabela_vigente, "comm")
if zipData then
print("has zip data")
end
end
else
invalid_combat = _detalhes.tabela_vigente
--> tutorial about the combat time < then 'minimum_combat_time'
local hasSeenTutorial = _detalhes:GetTutorialCVar("MIN_COMBAT_TIME")
if not hasSeenTutorial then
local lower_instance = _detalhes:GetLowerInstanceNumber()
if lower_instance then
lower_instance = _detalhes:GetInstance(lower_instance)
if lower_instance then
lower_instance:InstanceAlert("combat ignored: less than 5 seconds.", {[[Interface\BUTTONS\UI-GROUPLOOT-PASS-DOWN]], 18, 18, false, 0, 1, 0, 1}, 20, {function() Details:Msg("combat ignored: elapsed time less than 5 seconds."); Details:Msg("add '|cFFFFFF00Details.minimum_combat_time = 2;|r' on Auto Run Code to change the minimum time.") end})
_detalhes:SetTutorialCVar("MIN_COMBAT_TIME", true)
end
end
end
--in case of a forced discard segment, just check a second time if we have a previous combat.
if not _detalhes.tabela_historico.tabelas[1] then
_detalhes.tabela_vigente = _detalhes.tabela_vigente
else
_detalhes.tabela_vigente = _detalhes.tabela_historico.tabelas[1] --> pega a tabela do ultimo combate
end
if _detalhes.tabela_vigente:GetStartTime() == 0 then
--_detalhes.tabela_vigente.start_time = _detalhes._tempo
_detalhes.tabela_vigente:SetStartTime(_GetTime())
--_detalhes.tabela_vigente.end_time = _detalhes._tempo
_detalhes.tabela_vigente:SetEndTime(_GetTime())
end
_detalhes.tabela_vigente.resincked = true
--> tabela foi descartada, precisa atualizar os baseframes // precisa atualizer todos ou apenas o overall?
_detalhes:InstanciaCallFunction(_detalhes.AtualizarJanela)
if _detalhes.solo then
local esta_instancia = _detalhes.tabela_instancias[_detalhes.solo]
if _detalhes.SoloTables.CombatID == _detalhes:NumeroCombate() then --> significa que o solo mode validou o combate, como matar um bixo muito low level com uma s� porrada
if _detalhes.SoloTables.CombatIDLast and _detalhes.SoloTables.CombatIDLast ~= 0 then --> volta os dados da luta anterior
_detalhes.SoloTables.CombatID = _detalhes.SoloTables.CombatIDLast
else
if _detalhes.RefreshSolo then
_detalhes:RefreshSolo()
end
_detalhes.SoloTables.CombatID = nil
end
end
end
_detalhes:NumeroCombate(-1)
end
_detalhes.host_of = nil
_detalhes.host_by = nil
if _detalhes.cloud_process then
_detalhes:CancelTimer(_detalhes.cloud_process)
end
_detalhes.in_combat = false
_detalhes.leaving_combat = false
_detalhes:OnCombatPhaseChanged()
_table_wipe(_detalhes.tabela_vigente.PhaseData.damage_section)
_table_wipe(_detalhes.tabela_vigente.PhaseData.heal_section)
_table_wipe(_detalhes.cache_damage_group)
_table_wipe(_detalhes.cache_healing_group)
_detalhes:UpdateParserGears()
--> hide / alpha in combat
for index, instancia in ipairs(_detalhes.tabela_instancias) do
if instancia.ativa then
--instancia:SetCombatAlpha(nil, nil, true) --passado para o regen enabled
if instancia.auto_switch_to_old then
instancia:CheckSwitchOnCombatEnd()
end
end
end
_detalhes.pre_pot_used = nil
-- TODO
-- if _detalhes.encounter_table and _detalhes.encounter_table.id ~= 36597 then
_table_wipe(_detalhes.encounter_table)
-- else
-- if _detalhes.debug then
-- _detalhes:Msg("(debug) in the lich king encounter, cannot wipe the encounter table.")
-- end
-- end
_detalhes:InstanceCall(_detalhes.CheckPsUpdate)
if invalid_combat then
_detalhes:SendEvent("COMBAT_INVALID")
_detalhes:SendEvent("COMBAT_PLAYER_LEAVE", nil, invalid_combat)
else
_detalhes:SendEvent("COMBAT_PLAYER_LEAVE", nil, _detalhes.tabela_vigente)
end
_detalhes:CheckForTextTimeCounter()
_detalhes.StoreSpells()
_detalhes:RunScheduledEventsAfterCombat()
end
-- TEMP
function _detalhes:GetPlayersInArena()
local aliados = GetNumGroupMembers() -- LE_PARTY_CATEGORY_HOME
for i = 1, aliados-1 do
local role = UnitGroupRolesAssigned("party"..i)
if role ~= "NONE" then
local name = GetUnitName("party"..i, true)
_detalhes.arena_table[name] = {role = role}
end
end
local role = UnitGroupRolesAssigned("player")
if role ~= "NONE" then
local name = GetUnitName("player", true)
_detalhes.arena_table[name] = {role = role}
end
if _detalhes.debug then
_detalhes:Msg("(debug) Found", oponentes, "enemies and", aliados, "allies")
end
end
local string_arena_enemyteam_damage = [[
local combat = _detalhes:GetCombat("current")
local total = 0
for _, actor in combat[1]:ListActors() do
if actor.arena_enemy then
total = total + actor.total
end
end
return total
]]
local string_arena_myteam_damage = [[
local combat = _detalhes:GetCombat("current")
local total = 0
for _, actor in combat[1]:ListActors() do
if actor.arena_ally then
total = total + actor.total
end
end
return total
]]
local string_arena_enemyteam_heal = [[
local combat = _detalhes:GetCombat("current")
local total = 0
for _, actor in combat[2]:ListActors() do
if actor.arena_enemy then
total = total + actor.total
end
end
return total
]]
local string_arena_myteam_heal = [[
local combat = _detalhes:GetCombat("current")
local total = 0
for _, actor in combat[2]:ListActors() do
if actor.arena_ally then
total = total + actor.total
end
end
return total
]]
function _detalhes:CreateArenaSegment()
_detalhes:GetPlayersInArena()
_detalhes.arena_begun = true
_detalhes.start_arena = nil
if _detalhes.in_combat then
_detalhes:SairDoCombate()
end
--> registra os gr�ficos
_detalhes:TimeDataRegister("Your Team Damage", string_arena_myteam_damage, nil, "Details!", "v1.0",[[Interface\ICONS\Ability_DualWield]], true, true)
_detalhes:TimeDataRegister("Enemy Team Damage", string_arena_enemyteam_damage, nil, "Details!", "v1.0",[[Interface\ICONS\Ability_DualWield]], true, true)
_detalhes:TimeDataRegister("Your Team Healing", string_arena_myteam_heal, nil, "Details!", "v1.0",[[Interface\ICONS\Ability_DualWield]], true, true)
_detalhes:TimeDataRegister("Enemy Team Healing", string_arena_enemyteam_heal, nil, "Details!", "v1.0",[[Interface\ICONS\Ability_DualWield]], true, true)
--> inicia um novo combate
_detalhes:EntrarEmCombate()
--> sinaliza que esse combate � arena
_detalhes.tabela_vigente.arena = true
_detalhes.tabela_vigente.is_arena = {name = _detalhes.zone_name, zone = _detalhes.zone_name, mapid = _detalhes.zone_id}
_detalhes:SendEvent("COMBAT_ARENA_START")
end
function _detalhes:StartArenaSegment(...)
if _detalhes.debug then
_detalhes:Msg("(debug) starting a new arena segment.")
end
local timerType, timeSeconds, totalTime = ...
if _detalhes.start_arena then
_detalhes:CancelTimer(_detalhes.start_arena, true)
end
_detalhes.start_arena = _detalhes:ScheduleTimer("CreateArenaSegment", timeSeconds)
_detalhes:GetPlayersInArena()
end
function _detalhes:EnteredInArena()
if _detalhes.debug then
_detalhes:Msg("(debug) the player EnteredInArena().")
end
_detalhes.arena_begun = false
_detalhes:GetPlayersInArena()
end
function _detalhes:LeftArena()
if _detalhes.debug then
_detalhes:Msg("(debug) player LeftArena().")
end
_detalhes.is_in_arena = false
_detalhes.arena_begun = false
if _detalhes.start_arena then
_detalhes:CancelTimer(_detalhes.start_arena, true)
end
_detalhes:TimeDataUnregister("Your Team Damage")
_detalhes:TimeDataUnregister("Enemy Team Damage")
_detalhes:TimeDataUnregister("Your Team Healing")
_detalhes:TimeDataUnregister("Enemy Team Healing")
_detalhes:SendEvent("COMBAT_ARENA_END")
end
-- TEMP
local validSpells = {
[220893] = {class = "ROGUE", spec = 261, maxPercent = 0.075, container = 1, commID = "MISSDATA_ROGUE_SOULRIP"},
--[11366] = {class = "MAGE", spec = 63, maxPercent = 0.9, container = 1, commID = "MISSDATA_ROGUE_SOULRIP"},
}
function _detalhes:CanSendMissData()
if(not IsInRaid() and not IsInGroup()) then
return
end
local _, playerClass = UnitClass("player")
local specIndex = DetailsFramework.GetSpecialization()
local playerSpecID
if(specIndex) then
playerSpecID = DetailsFramework.GetSpecializationInfo(specIndex)
end
if(playerSpecID and playerClass) then
for spellID, t in pairs(validSpells) do
if(playerClass == t.class and playerSpecID == t.spec) then
_detalhes:SendMissData(spellID, t.container, _detalhes.network.ids[t.commID])
end
end
end
return false
end
function _detalhes:SendMissData(spellID, containerType, commID)
local combat = _detalhes.tabela_vigente
if combat then
local damageActor = combat(containerType, _detalhes.playername)
if damageActor then
local spell = damageActor.spells:GetSpell(spellID)
if spell then
local data = {
[1] = containerType,
[2] = spellID,
[3] = spell.total,
[4] = spell.counter
}
if _detalhes.debug then
_detalhes:Msg("(debug) sending miss data packet:", spellID, containerType, commID)
end
_detalhes:SendRaidOrPartyData(commID, data)
end
end
end
end
function _detalhes.HandleMissData(playerName, data)
local combat = _detalhes.tabela_vigente
if _detalhes.debug then
_detalhes:Msg("(debug) miss data received from:", playerName, "spellID:", data[2], data[3], data[4])
end
if combat then
local containerType = data[1]
if type(containerType) ~= "number" or containerType < 1 or containerType > 4 then
return
end
local damageActor = combat(containerType, playerName)
if damageActor then
local spellID = data[2] --a spellID has been passed?
if not spellID or type(spellID) ~= "number" then
return
end
local validateSpell = validSpells[spellID]
if not validateSpell then --is a valid spell?
return
end
--does the target player fit in the spell requirement on OUR end?
local class, spec, maxPercent = validateSpell.class, validateSpell.spec, validateSpell.maxPercent
if class ~= damageActor.classe or spec ~= damageActor.spec then
return
end
local total, counter = data[3], data[4]
if type(total) ~= "number" or type(counter) ~= "number" then
return
end
if total > (damageActor.total * maxPercent) then
return
end
local spellObject = damageActor.spells:PegaHabilidade(spellID, true)
if spellObject then
if spellObject.total < total and total > 0 and damageActor.nome ~= _detalhes.playername then
local difference = total - spellObject.total
if difference > 0 then
spellObject.total = total
spellObject.counter = counter
damageActor.total = damageActor.total + difference
combat[containerType].need_refresh = true
if _detalhes.debug then
_detalhes:Msg("(debug) miss data successful added from:", playerName, data[2], "difference:", difference)
end
end
end
end
end
end
end
function _detalhes:MakeEqualizeOnActor(player, realm, receivedActor)
if true then --> disabled for testing
return
end
local combat = _detalhes:GetCombat("current")
local damage, heal, energy, misc = _detalhes:GetAllActors("current", player)
if not damage and not heal and not energy and not misc then
--> try adding server name
damage, heal, energy, misc = _detalhes:GetAllActors("current", player.."-"..realm)
if not damage and not heal and not energy and not misc then
--> not found any actor object, so we need to create
local actorName
if realm ~= GetRealmName() then
actorName = player.."-"..realm
else
actorName = player
end
local guid = _detalhes:FindGUIDFromName(player)
-- 0x512 normal party
-- 0x514 normal raid
if guid then
damage = combat[1]:PegarCombatente(guid, actorName, 0x514, true)
heal = combat[2]:PegarCombatente(guid, actorName, 0x514, true)
energy = combat[3]:PegarCombatente(guid, actorName, 0x514, true)
misc = combat[4]:PegarCombatente(guid, actorName, 0x514, true)
if _detalhes.debug then
_detalhes:Msg("(debug) equalize received actor:", actorName, damage, heal)
end
else
if _detalhes.debug then
_detalhes:Msg("(debug) equalize couldn't get guid for player ",player)
end
end
end
end
combat[1].need_refresh = true
combat[2].need_refresh = true
combat[3].need_refresh = true
combat[4].need_refresh = true
if damage then
if damage.total < receivedActor[1][1] then
if _detalhes.debug then
_detalhes:Msg(player.." damage before: "..damage.total.." damage received: "..receivedActor[1][1])
end
damage.total = receivedActor[1][1]
end
if damage.damage_taken < receivedActor[1][2] then
damage.damage_taken = receivedActor[1][2]
end
if damage.friendlyfire_total < receivedActor[1][3] then
damage.friendlyfire_total = receivedActor[1][3]
end
end
if heal then
if heal.total < receivedActor[2][1] then
heal.total = receivedActor[2][1]
end
if heal.totalover < receivedActor[2][2] then
heal.totalover = receivedActor[2][2]
end
if heal.healing_taken < receivedActor[2][3] then
heal.healing_taken = receivedActor[2][3]
end
end
if energy then
if energy.mana and(receivedActor[3][1] > 0 and energy.mana < receivedActor[3][1]) then
energy.mana = receivedActor[3][1]
end
if energy.e_rage and(receivedActor[3][2] > 0 and energy.e_rage < receivedActor[3][2]) then
energy.e_rage = receivedActor[3][2]
end
if energy.e_energy and(receivedActor[3][3] > 0 and energy.e_energy < receivedActor[3][3]) then
energy.e_energy = receivedActor[3][3]
end
if energy.runepower and(receivedActor[3][4] > 0 and energy.runepower < receivedActor[3][4]) then
energy.runepower = receivedActor[3][4]
end
end
if misc then
if misc.interrupt and(receivedActor[4][1] > 0 and misc.interrupt < receivedActor[4][1]) then
misc.interrupt = receivedActor[4][1]
end
if misc.dispell and(receivedActor[4][2] > 0 and misc.dispell < receivedActor[4][2]) then
misc.dispell = receivedActor[4][2]
end
end
end
function _detalhes:EqualizePets()
--> check for pets without owner
for _, actor in _ipairs(_detalhes.tabela_vigente[1]._ActorTable) do
--> have flag and the flag tell us he is a pet
if actor.flag_original and bit.band(actor.flag_original, OBJECT_TYPE_PETS) ~= 0 then
--> do not have owner and he isn't on owner container
if not actor.owner and not _detalhes.tabela_pets.pets[actor.serial] then
_detalhes:SendPetOwnerRequest(actor.serial, actor.nome)
end
end
end
end
function _detalhes:EqualizeActorsSchedule(host_of)
--> store pets sent through 'needpetowner'
_detalhes.sent_pets = _detalhes.sent_pets or {n = time()}
if _detalhes.sent_pets.n + 20 < time() then
_table_wipe(_detalhes.sent_pets)
_detalhes.sent_pets.n = time()
end
--> pet equilize disabled on details 1.4.0
-- _detalhes:ScheduleTimer("EqualizePets", 1 + math.random())
--> do not equilize if there is any disabled capture
-- if _detalhes:CaptureIsAllEnabled() then
_detalhes:ScheduleTimer("EqualizeActors", 2 + math.random() + math.random() , host_of)
-- end
end
function _detalhes:EqualizeActors(host_of)
--> Disabling the sync. Since WoD combatlog are sent between player on phased zones during encounters.
if not host_of or true then --> full disabled for testing
return
end
if _detalhes.debug then
_detalhes:Msg("(debug) sending equilize actor data")
end
local damage, heal, energy, misc
if host_of then
damage, heal, energy, misc = _detalhes:GetAllActors("current", host_of)
else
damage, heal, energy, misc = _detalhes:GetAllActors("current", _detalhes.playername)
end
if damage then
damage = {damage.total or 0, damage.damage_taken or 0, damage.friendlyfire_total or 0}
else
damage = {0, 0, 0}
end
if heal then
heal = {heal.total or 0, heal.totalover or 0, heal.healing_taken or 0}
else
heal = {0, 0, 0}
end
if energy then
energy = {energy.mana or 0, energy.e_rage or 0, energy.e_energy or 0, energy.runepower or 0}
else
energy = {0, 0, 0, 0}
end
if misc then
misc = {misc.interrupt or 0, misc.dispell or 0}
else
misc = {0, 0}
end
local data = {damage, heal, energy, misc}
--> envia os dados do proprio host pra ele antes
if host_of then
_detalhes:SendRaidDataAs(_detalhes.network.ids.CLOUD_EQUALIZE, host_of, nil, data)
_detalhes:EqualizeActors()
else
_detalhes:SendRaidData(_detalhes.network.ids.CLOUD_EQUALIZE, data)
end
end
function _detalhes:FlagActorsOnPvPCombat()
for class_type, container in _ipairs(_detalhes.tabela_vigente) do
for _, actor in _ipairs(container._ActorTable) do
actor.pvp_component = true
end
end
end
function _detalhes:FlagActorsOnBossFight()
for class_type, container in _ipairs(_detalhes.tabela_vigente) do
for _, actor in _ipairs(container._ActorTable) do
actor.boss_fight_component = true
end
end
end
local fight_component = function(energy_container, misc_container, name)
local on_energy = energy_container._ActorTable[energy_container._NameIndexTable[name]]
if on_energy then
on_energy.fight_component = true
end
local on_misc = misc_container._ActorTable[misc_container._NameIndexTable[name]]
if on_misc then
on_misc.fight_component = true
end
end
function _detalhes:FlagActorsOnCommonFight()
local damage_container = _detalhes.tabela_vigente[1]
local healing_container = _detalhes.tabela_vigente[2]
local energy_container = _detalhes.tabela_vigente[3]
local misc_container = _detalhes.tabela_vigente[4]
local mythicDungeonRun = _detalhes.tabela_vigente.is_mythic_dungeon_segment
for class_type, container in _ipairs({damage_container, healing_container}) do
for _, actor in _ipairs(container._ActorTable) do
if mythicDungeonRun then
actor.fight_component = true
end
if actor.grupo then
if class_type == 1 or class_type == 2 then
for target_name, amount in _pairs(actor.targets) do
local target_object = container._ActorTable[container._NameIndexTable[target_name]]
if target_object then
target_object.fight_component = true
fight_component(energy_container, misc_container, target_name)
end
end
if class_type == 1 then
for damager_actor, _ in _pairs(actor.damage_from) do
local target_object = container._ActorTable[container._NameIndexTable[damager_actor]]
if target_object then
target_object.fight_component = true
fight_component(energy_container, misc_container, damager_actor)
end
end
elseif class_type == 2 then
for healer_actor, _ in _pairs(actor.healing_from) do
local target_object = container._ActorTable[container._NameIndexTable[healer_actor]]
if target_object then
target_object.fight_component = true
fight_component(energy_container, misc_container, healer_actor)
end
end
end
end
end
end
end
end
function _detalhes:AtualizarJanela(instancia, _segmento)
if _segmento then --> apenas atualizar janelas que estejam mostrando o segmento solicitado
if _segmento == instancia.segmento then
instancia:TrocaTabela(instancia, instancia.segmento, instancia.atributo, instancia.sub_atributo, true)
end
else
if instancia.modo == modo_GROUP or instancia.modo == modo_ALL then
instancia:TrocaTabela(instancia, instancia.segmento, instancia.atributo, instancia.sub_atributo, true)
end
end
end
function _detalhes:PostponeInstanceToCurrent(instance)
if not instance.last_interaction or (instance.ativa and (instance.last_interaction + 3 < _tempo) and (not DetailsReportWindow or not DetailsReportWindow:IsShown()) and (not _detalhes.janela_info:IsShown())) then
instance._postponing_current = nil
if instance.segmento == 0 then
return _detalhes:TrocaSegmentoAtual(instance)
else
return
end
end
if instance.is_interacting and instance.last_interaction < _tempo then
instance.last_interaction = _tempo
end
instance._postponing_current = _detalhes:ScheduleTimer("PostponeInstanceToCurrent", 1, instance)
end
function _detalhes:TrocaSegmentoAtual(instancia, is_encounter)
if instancia.segmento == 0 and instancia.baseframe and instancia.ativa then
if not is_encounter then
if instancia.is_interacting then
if not instancia.last_interaction or instancia.last_interaction < _tempo then
instancia.last_interaction = _tempo or time()
end
end
if (instancia.last_interaction and (instancia.last_interaction + 3 > _detalhes._tempo)) or (DetailsReportWindow and DetailsReportWindow:IsShown()) or (_detalhes.janela_info:IsShown()) then
--> postpone
instancia._postponing_current = _detalhes:ScheduleTimer("PostponeInstanceToCurrent", 1, instancia)
return
end
end
--print("==> Changing the Segment now! - control.lua 1220")
instancia.last_interaction = _tempo - 4 --pode setar, completou o ciclo
instancia._postponing_current = nil
instancia.showing = _detalhes.tabela_vigente
instancia:ResetaGump()
_detalhes.gump:Fade(instancia, "in", nil, "barras")
end
end
function _detalhes:SetTrashSuppression(n)
assert(type(n) == "number", "SetTrashSuppression expects a number on index 1.")
if n < 0 then
n = 0
end
_detalhes.instances_suppress_trash = n
end
function _detalhes:CheckFor_SuppressedWindowsOnEncounterFound()
for _, instance in _detalhes:ListInstances() do
if instance.ativa and instance.baseframe and (not instance.last_interaction or instance.last_interaction > _tempo) and instance.segmento == 0 then
_detalhes:TrocaSegmentoAtual(instance, true)
end
end
end
function _detalhes:CheckFor_EnabledTrashSuppression()
if _detalhes.HasTrashSuppression and _detalhes.HasTrashSuppression > _tempo then
self.last_interaction = _detalhes.HasTrashSuppression
end
end
function _detalhes:SetTrashSuppressionAfterEncounter()
_detalhes:InstanceCall("CheckFor_EnabledTrashSuppression")
end
function _detalhes:CheckFor_TrashSuppressionOnEncounterEnd()
if _detalhes.instances_suppress_trash > 0 then
_detalhes.HasTrashSuppression = _tempo + _detalhes.instances_suppress_trash
--> delaying in 3 seconds for other stuff like auto open windows after combat.
_detalhes:ScheduleTimer("SetTrashSuppressionAfterEncounter", 3)
end
end
--> internal GetCombatId() version
function _detalhes:NumeroCombate(flag)
if flag == 0 then
_detalhes.combat_id = 0
elseif flag then
_detalhes.combat_id = _detalhes.combat_id + flag
end
return _detalhes.combat_id
end
--> tooltip fork / search key: ~tooltip
local avatarPoint = {"bottomleft", "topleft", -3, -4}
local backgroundPoint = {{"bottomleft", "topleft", 0, -3}, {"bottomright", "topright", 0, -3}}
local textPoint = {"left", "right", -11, -5}
local avatarTexCoord = {0, 1, 0, 1}
local backgroundColor = {0, 0, 0, 0.6}
local avatarTextColor = {1, 1, 1, 1}
function _detalhes:AddTooltipReportLineText()
GameCooltip:AddLine(Loc["STRING_CLICK_REPORT_LINE1"], Loc["STRING_CLICK_REPORT_LINE2"])
GameCooltip:AddStatusBar(100, 1, 0, 0, 0, 0.8)
end
function _detalhes:AddTooltipBackgroundStatusbar(side, value, useSpark)
_detalhes.tooltip.background[4] = 0.8
_detalhes.tooltip.icon_size.W = _detalhes.tooltip.line_height
_detalhes.tooltip.icon_size.H = _detalhes.tooltip.line_height
value = value or 100
if(not side) then
local r, g, b, a = unpack(_detalhes.tooltip.background)
GameCooltip:AddStatusBar(value, 1, r, g, b, a, useSpark, {value = 100, color = {.21, .21, .21, 0.8}, texture =[[Interface\AddOns\Details\images\bar_serenity]]})
else
GameCooltip:AddStatusBar(value, 2, unpack(_detalhes.tooltip.background))
end
end
function _detalhes:AddTooltipHeaderStatusbar(r, g, b, a)
local r, g, b, a, statusbarGlow, backgroundBar = unpack(_detalhes.tooltip.header_statusbar)
GameCooltip:AddStatusBar(100, 1, r, g, b, a, statusbarGlow, backgroundBar, "Skyline")
end
-- /run local a,b=_detalhes.tooltip.header_statusbar,0.3;a[1]=b;a[2]=b;a[3]=b;a[4]=0.8;
function _detalhes:AddTooltipSpellHeaderText(headerText, headerColor, amount, iconTexture, L, R, T, B)
if _detalhes.tooltip.show_amount then
GameCooltip:AddLine(headerText, "x" .. amount .. "", nil, headerColor, 1, 1, 1, .4, _detalhes.tooltip.fontsize_title)
else
GameCooltip:AddLine(headerText, nil, nil, headerColor, nil, _detalhes.tooltip.fontsize_title)
end
if iconTexture then
GameCooltip:AddIcon(iconTexture, 1, 1, 14, 14, L or 0, R or 1, T or 0, B or 1)
end
end
local bgColor, borderColor = {0, 0, 0, 0.8}, {0, 0, 0, 0} --{0.37, 0.37, 0.37, .75}, {.30, .30, .30, .3}
function _detalhes:BuildInstanceBarTooltip(frame)
local GameCooltip = GameCooltip
GameCooltip:Reset()
GameCooltip:SetType("tooltip")
GameCooltip:SetOption("MinWidth", _math_max(230, self.baseframe:GetWidth()*0.98))
GameCooltip:SetOption("StatusBarTexture",[[Interface\AddOns\Details\images\bar_background]])
GameCooltip:SetOption("TextSize", _detalhes.tooltip.fontsize)
GameCooltip:SetOption("TextFont", _detalhes.tooltip.fontface)
GameCooltip:SetOption("TextColor", _detalhes.tooltip.fontcolor)
GameCooltip:SetOption("TextColorRight", _detalhes.tooltip.fontcolor_right)
GameCooltip:SetOption("TextShadow", _detalhes.tooltip.fontshadow and "OUTLINE")
GameCooltip:SetOption("LeftBorderSize", -4)
GameCooltip:SetOption("RightBorderSize", 4)
GameCooltip:SetOption("RightTextMargin", 0)
GameCooltip:SetOption("VerticalOffset", 8)
GameCooltip:SetOption("AlignAsBlizzTooltip", true)
GameCooltip:SetOption("AlignAsBlizzTooltipFrameHeightOffset", -8)
GameCooltip:SetOption("LineHeightSizeOffset", 4)
GameCooltip:SetOption("VerticalPadding", -4)
GameCooltip:SetBackdrop(1, _detalhes.cooltip_preset2_backdrop, bgColor, borderColor)
local myPoint = _detalhes.tooltip.anchor_point
local anchorPoint = _detalhes.tooltip.anchor_relative
local x_Offset = _detalhes.tooltip.anchor_offset[1]
local y_Offset = _detalhes.tooltip.anchor_offset[2]
if _detalhes.tooltip.anchored_to == 1 then
GameCooltip:SetHost(frame, myPoint, anchorPoint, x_Offset, y_Offset)
else
GameCooltip:SetHost(DetailsTooltipAnchor, myPoint, anchorPoint, x_Offset, y_Offset)
end
end
function _detalhes:MontaTooltip(frame, qual_barra, keydown)
self:BuildInstanceBarTooltip(frame)
local GameCooltip = GameCooltip
local esta_barra = self.barras[qual_barra] --> barra que o mouse passou em cima e ir� mostrar o tooltip
local objeto = esta_barra.minha_tabela --> pega a referencia da tabela --> retorna a classe_damage ou classe_heal
if not objeto then --> a barra n�o possui um objeto
return false
end
--verifica por tooltips especiais:
if objeto.dead then --> � uma barra de dead
return _detalhes:ToolTipDead(self, objeto, esta_barra, keydown) --> inst�ncia,[morte], barra
elseif objeto.byspell then
return _detalhes:ToolTipBySpell(self, objeto, esta_barra, keydown)
elseif objeto.frags then
return _detalhes:ToolTipFrags(self, objeto, esta_barra, keydown)
elseif objeto.boss_debuff then
return _detalhes:ToolTipVoidZones(self, objeto, esta_barra, keydown)
end
local t = objeto:ToolTip(self, qual_barra, esta_barra, keydown) --> inst�ncia, n� barra, objeto barra, keydown
if t then
if objeto.serial and objeto.serial ~= "" then
local avatar = NickTag:GetNicknameTable(objeto.serial, true)
if avatar and not _detalhes.ignore_nicktag then
if avatar[2] and avatar[4] and avatar[1] then
GameCooltip:SetBannerImage(1, avatar[2], 80, 40, avatarPoint, avatarTexCoord, nil) --> overlay[2] avatar path
GameCooltip:SetBannerImage(2, avatar[4], 200, 55, backgroundPoint, avatar[5], avatar[6]) --> background
GameCooltip:SetBannerText(1, (not _detalhes.ignore_nicktag and avatar[1]) or objeto.nome, textPoint, avatarTextColor, 14, SharedMedia:Fetch("font", _detalhes.tooltip.fontface)) --> text[1] nickname
end
else
-- if _detalhes.remove_realm_from_name and objeto.displayName:find("%*") then
-- GameCooltip:SetBannerImage(1,[[Interface\AddOns\Details\images\background]], 20, 30, avatarPoint, avatarTexCoord, {0, 0, 0, 0}) --> overlay[2] avatar path
-- GameCooltip:SetBannerImage(2,[[Interface\PetBattles\Weather-BurntEarth]], 160, 30, {{"bottomleft", "topleft", 0, -5}, {"bottomright", "topright", 0, -5}}, {0.12, 0.88, 1, 0}, {0, 0, 0, 0.1}) --> overlay[2] avatar path {0, 0, 0, 0}
-- GameCooltip:SetBannerText(1, objeto.nome, {"left", "left", 11, -8}, {1, 1, 1, 0.7}, 10, SharedMedia:Fetch("font", _detalhes.tooltip.fontface)) --> text[1] nickname
-- end
end
end
GameCooltip:ShowCooltip()
end
end
function _detalhes.gump:UpdateTooltip(qual_barra, esta_barra, instancia)
if _IsShiftKeyDown() then
return instancia:MontaTooltip(esta_barra, qual_barra, "shift")
elseif _IsControlKeyDown() then
return instancia:MontaTooltip(esta_barra, qual_barra, "ctrl")
elseif _IsAltKeyDown() then
return instancia:MontaTooltip(esta_barra, qual_barra, "alt")
else
return instancia:MontaTooltip(esta_barra, qual_barra)
end
end
function _detalhes:EndRefresh(instancia, total, tabela_do_combate, showing)
_detalhes:EsconderBarrasNaoUsadas(instancia, showing)
end
function _detalhes:EsconderBarrasNaoUsadas(instancia, showing)
--> primeira atualiza��o ap�s uma mudan�a de segmento --> verifica se h� mais barras sendo mostradas do que o necess�rio
--------------------
if instancia.v_barras then
--print("mostrando", instancia.rows_showing, instancia.rows_created)
for barra_numero = instancia.rows_showing+1, instancia.rows_created do
_detalhes.gump:Fade(instancia.barras[barra_numero], "in")
end
instancia.v_barras = false
if instancia.rows_showing == 0 and instancia:GetSegment() == -1 then -- -1 overall data
if not instancia:IsShowingOverallDataWarning() then
local tutorial = _detalhes:GetTutorialCVar("OVERALLDATA_WARNING1") or 0
if (type(tutorial) == "number") and(tutorial < 60) then
_detalhes:SetTutorialCVar("OVERALLDATA_WARNING1", tutorial + 1)
instancia:ShowOverallDataWarning(true)
end
end
else
if instancia:IsShowingOverallDataWarning() then
instancia:ShowOverallDataWarning(false)
end
end
end
return showing
end
--> call update functions
function _detalhes:AtualizarALL(forcar)
local tabela_do_combate = self.showing
--> confere se a inst�ncia possui uma tabela v�lida
if not tabela_do_combate then
if not self.freezed then
return self:Freeze()
end
return
end
local need_refresh = tabela_do_combate[self.atributo].need_refresh
if not need_refresh and not forcar then
return --> n�o precisa de refresh
-- else
-- tabela_do_combate[self.atributo].need_refresh = false
end
if self.atributo == 1 then --> damage
return atributo_damage:RefreshWindow(self, tabela_do_combate, forcar, nil, need_refresh)
elseif self.atributo == 2 then --> heal
return atributo_heal:RefreshWindow(self, tabela_do_combate, forcar, nil, need_refresh)
elseif self.atributo == 3 then --> energy
return atributo_energy:RefreshWindow(self, tabela_do_combate, forcar, nil, need_refresh)
elseif self.atributo == 4 then --> outros
return atributo_misc:RefreshWindow(self, tabela_do_combate, forcar, nil, need_refresh)
elseif self.atributo == 5 then --> ocustom
return atributo_custom:RefreshWindow(self, tabela_do_combate, forcar, nil, need_refresh)
end
end
function _detalhes:ForceRefresh()
self:AtualizaGumpPrincipal(true)
end
function _detalhes:AtualizaGumpPrincipal(instancia, forcar)
if not instancia or type(instancia) == "boolean" then --> o primeiro par�metro n�o foi uma inst�ncia ou ALL
forcar = instancia
instancia = self
end
if not forcar then
_detalhes.LastUpdateTick = _detalhes._tempo
end
if instancia == -1 then
--> update
for index, esta_instancia in _ipairs(_detalhes.tabela_instancias) do
if esta_instancia.ativa then
if esta_instancia.modo == modo_GROUP or esta_instancia.modo == modo_ALL then
esta_instancia:AtualizarALL(forcar)
end
end
end
--> marcar que n�o precisa ser atualizada
for index, esta_instancia in _ipairs(_detalhes.tabela_instancias) do
if esta_instancia.ativa and esta_instancia.showing then
if esta_instancia.modo == modo_GROUP or esta_instancia.modo == modo_ALL then
if esta_instancia.atributo <= 4 then
esta_instancia.showing[esta_instancia.atributo].need_refresh = false
end
end
end
end
if not forcar then --atualizar o gump de detalhes tamb�m se ele estiver aberto
if info.ativo then
return info.jogador:MontaInfo()
end
end
return
else
if not instancia.ativa then
return
end
end
if instancia.modo == modo_ALL or instancia.modo == modo_GROUP then
return instancia:AtualizarALL(forcar)
end
end
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> core
function _detalhes:AutoEraseConfirm()
local panel = DetailsEraseDataConfirmation
if not panel then
panel = CreateFrame("Frame", "DetailsEraseDataConfirmation", UIParent)
panel:SetSize(400, 85)
panel:SetBackdrop({
bgFile =[[Interface\AddOns\Details\images\background]], tile = true, tileSize = 16,
edgeFile =[[Interface\AddOns\Details\images\border_2]], edgeSize = 12
})
panel:SetPoint("CENTER", UIParent)
panel:SetBackdropColor(0, 0, 0, 0.4)
panel:SetScript("OnMouseDown", function(self, button)
if button == "RightButton" then
panel:Hide()
end
end)
--local icon = _detalhes.gump:CreateImage(panel,[[Interface\AddOns\Details\images\logotipo]], 512*0.4, 256*0.4)
--icon:SetPoint("BOTTOMLEFT", panel, "TOPLEFT", -10, -11)
local text = _detalhes.gump:CreateLabel(panel, Loc["STRING_OPTIONS_CONFIRM_ERASE"], nil, nil, "GameFontNormal")
text:SetPoint("CENTER", panel, "CENTER")
text:SetPoint("TOP", panel, "TOP", 0, -10)
local no = _detalhes.gump:CreateButton(panel, function() panel:Hide() end, 90, 20, Loc["STRING_NO"])
no:SetPoint("BOTTOMLEFT", panel, "BOTTOMLEFT", 30, 10)
no:InstallCustomTexture(nil, nil, nil, nil, true)
local yes = _detalhes.gump:CreateButton(panel, function() panel:Hide(); _detalhes.tabela_historico:resetar() end, 90, 20, Loc["STRING_YES"])
yes:SetPoint("BOTTOMRIGHT", panel, "BOTTOMRIGHT", -30, 10)
yes:InstallCustomTexture(nil, nil, nil, nil, true)
end
panel:Show()
end
function _detalhes:CheckForAutoErase(mapid)
if _detalhes.last_instance_id ~= mapid then
_detalhes.tabela_historico:resetar_overall()
if _detalhes.segments_auto_erase == 2 then
--ask
_detalhes:ScheduleTimer("AutoEraseConfirm", 1)
elseif _detalhes.segments_auto_erase == 3 then
--erase
_detalhes.tabela_historico:resetar()
end
else
if _tempo > _detalhes.last_instance_time + 21600 then --6 hours
if _detalhes.segments_auto_erase == 2 then
--ask
_detalhes:ScheduleTimer("AutoEraseConfirm", 1)
elseif _detalhes.segments_auto_erase == 3 then
--erase
_detalhes.tabela_historico:resetar()
end
end
end
_detalhes.last_instance_id = mapid
_detalhes.last_instance_time = _tempo
--_detalhes.last_instance_time = 0 --debug
end
function _detalhes:UpdateControl()
_tempo = _detalhes._tempo
end | 412 | 0.94994 | 1 | 0.94994 | game-dev | MEDIA | 0.976685 | game-dev | 0.918241 | 1 | 0.918241 |
pzstorm/storm | 5,823 | core/src/test/java/io/pzstorm/storm/event/LuaEventFactoryTest.java | package io.pzstorm.storm.event;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableMap;
import io.pzstorm.storm.UnitTest;
import io.pzstorm.storm.event.lua.*;
import se.krka.kahlua.vm.KahluaTable;
import zombie.characters.IsoGameCharacter;
import zombie.characters.IsoPlayer;
import zombie.characters.IsoZombie;
import zombie.characters.SurvivorDesc;
import zombie.inventory.types.HandWeapon;
import zombie.iso.BuildingDef;
import zombie.iso.IsoMovingObject;
import zombie.iso.IsoObject;
class LuaEventFactoryTest implements UnitTest {
private static final ImmutableMap<Class<? extends LuaEvent>, Class<?>[]> EVENT_CLASS_CONSTRUCTOR_DATA =
ImmutableMap.<Class<? extends LuaEvent>, Class<?>[]>builder()
.put(OnChallengeQueryEvent.class, new Class<?>[] {})
.put(OnCharacterCollideEvent.class, new Class<?>[] {
IsoMovingObject.class, IsoObject.class
})
.put(OnCreateLivingCharacterEvent.class, new Class<?>[] {
IsoPlayer.class, SurvivorDesc.class
})
.put(OnFETickEvent.class, new Class<?>[] {
Integer.class
})
.put(OnFillInventoryObjectContextMenuEvent.class, new Class<?>[] {
Double.class, KahluaTable.class, KahluaTable.class
})
.put(OnFillWorldObjectContextMenuEvent.class, new Class<?>[] {
Double.class, KahluaTable.class, KahluaTable.class, Boolean.class
})
.put(OnGameBootEvent.class, new Class<?>[] {})
.put(OnGameStartEvent.class, new Class<?>[] {})
.put(OnJoypadActivateEvent.class, new Class<?>[] {
Integer.class
})
.put(OnKeyPressedEvent.class, new Class<?>[] {
Integer.class
})
.put(OnKeyStartPressedEvent.class, new Class<?>[] {
Integer.class
})
.put(OnLoadMapZonesEvent.class, new Class<?>[] {})
.put(OnMultiTriggerNPCEvent.class, new Class<?>[] {
String.class, KahluaTable.class, BuildingDef.class
})
.put(OnObjectCollideEvent.class, new Class<?>[] {
IsoMovingObject.class, IsoObject.class
})
.put(OnPlayerUpdateEvent.class, new Class<?>[] {
IsoPlayer.class
})
.put(OnPostUIDrawEvent.class, new Class<?>[] {})
.put(OnPreFillInventoryObjectContextMenuEvent.class, new Class<?>[] {
Double.class, KahluaTable.class, KahluaTable.class
})
.put(OnPreUIDrawEvent.class, new Class<?>[] {})
.put(OnRefreshInventoryWindowContainersEvent.class, new Class<?>[] {
KahluaTable.class, String.class
})
.put(OnTickEvenPausedEvent.class, new Class<?>[] {
Double.class
})
.put(OnTickEvent.class, new Class<?>[] {
Double.class
})
.put(OnTriggerNPCEvent.class, new Class<?>[] {
String.class, KahluaTable.class, BuildingDef.class
})
.put(OnWeaponHitCharacterEvent.class, new Class<?>[] {
IsoGameCharacter.class, IsoGameCharacter.class, HandWeapon.class, Float.class
})
.put(OnWeaponSwingEvent.class, new Class<?>[] {
IsoGameCharacter.class, HandWeapon.class
})
.put(OnZombieUpdateEvent.class, new Class<?>[] {
IsoZombie.class
})
.build();
@Test
void shouldConstructLuaEventFromClassInstance() {
for (Map.Entry<Class<? extends LuaEvent>, Class<?>[]> entry : EVENT_CLASS_CONSTRUCTOR_DATA.entrySet())
{
Class<? extends LuaEvent> eventClass = entry.getKey();
List<Object> constructorArgs = getDummyConstructorArgList(entry.getValue());
LuaEvent event = LuaEventFactory.constructLuaEvent(eventClass, constructorArgs.toArray());
Assertions.assertTrue(eventClass.isAssignableFrom(event.getClass()));
}
}
@Test
void shouldConstructLuaEventFromClassName() {
for (Map.Entry<Class<? extends LuaEvent>, Class<?>[]> entry : EVENT_CLASS_CONSTRUCTOR_DATA.entrySet())
{
Class<? extends LuaEvent> eventClass = entry.getKey();
List<Object> constructorArgs = getDummyConstructorArgList(entry.getValue());
String eventName = LuaEventFactory.getEventName(eventClass);
LuaEvent event = LuaEventFactory.constructLuaEvent(eventName, constructorArgs.toArray());
Assertions.assertTrue(eventClass.isAssignableFrom(Objects.requireNonNull(event).getClass()));
}
}
@Test
void shouldGetNullLuaEventWithNonExistingClassName() {
String eventName = "nonExistingEvent";
Assertions.assertNull(LuaEventFactory.constructLuaEvent(eventName, new ArrayList<>().toArray()));
}
@Test
void shouldConstructLuaEventWithMultipleConstructors() {
LuaEvent event = LuaEventFactory.constructLuaEvent(OnConnectFailedEvent.class, "");
Assertions.assertTrue(OnConnectFailedEvent.class.isAssignableFrom(event.getClass()));
event = LuaEventFactory.constructLuaEvent(OnConnectFailedEvent.class);
Assertions.assertTrue(OnConnectFailedEvent.class.isAssignableFrom(event.getClass()));
}
private List<Object> getDummyConstructorArgList(Class<?>[] constructorArgTypes) {
List<Object> result = new ArrayList<>();
for (Class<?> argType : constructorArgTypes)
{
Object object;
if (argType.isPrimitive())
{
if (argType == int.class) {
object = 0;
}
else if (argType == double.class) {
object = 0.0D;
}
else if (argType == float.class) {
object = 0.0f;
}
else if (argType == short.class) {
object = (short) 0;
}
else if (argType == long.class) {
object = (long) 0;
}
else if (argType == byte.class) {
object = (byte) 0;
}
else if (argType == char.class) {
object = 'a';
}
else if (argType == boolean.class) {
object = false;
}
else throw new UnsupportedOperationException();
}
else object = argType.cast(null);
result.add(object);
}
return result;
}
}
| 412 | 0.767393 | 1 | 0.767393 | game-dev | MEDIA | 0.712752 | game-dev | 0.604391 | 1 | 0.604391 |
gamekit-developers/gamekit | 21,330 | Ogre-1.9a/OgreMain/include/OgreResource.h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 _Resource_H__
#define _Resource_H__
#include "OgrePrerequisites.h"
#include "OgreString.h"
#include "OgreSharedPtr.h"
#include "OgreStringInterface.h"
#include "OgreAtomicScalar.h"
#include "Threading/OgreThreadHeaders.h"
#include "OgreHeaderPrefix.h"
namespace Ogre {
typedef unsigned long long int ResourceHandle;
// Forward declaration
class ManualResourceLoader;
/** \addtogroup Core
* @{
*/
/** \addtogroup Resources
* @{
*/
/** Abstract class representing a loadable resource (e.g. textures, sounds etc)
@remarks
Resources are data objects that must be loaded and managed throughout
an application. A resource might be a mesh, a texture, or any other
piece of data - the key thing is that they must be identified by
a name which is unique, must be loaded only once,
must be managed efficiently in terms of retrieval, and they may
also be unloadable to free memory up when they have not been used for
a while and the memory budget is under stress.
@par
All Resource instances must be a member of a resource group; see
ResourceGroupManager for full details.
@par
Subclasses must implement:
<ol>
<li>A constructor, overriding the same parameters as the constructor
defined by this class. Subclasses are not allowed to define
constructors with other parameters; other settings must be
settable through accessor methods before loading.</li>
<li>The loadImpl() and unloadImpl() methods - mSize must be set
after loadImpl()</li>
<li>StringInterface ParamCommand and ParamDictionary setups
in order to allow setting of core parameters (prior to load)
through a generic interface.</li>
</ol>
*/
class _OgreExport Resource : public StringInterface, public ResourceAlloc
{
public:
OGRE_AUTO_MUTEX; // public to allow external locking
class Listener
{
public:
Listener() {}
virtual ~Listener() {}
/** Callback to indicate that background loading has completed.
@deprecated
Use loadingComplete instead.
*/
OGRE_DEPRECATED virtual void backgroundLoadingComplete(Resource*) {}
/** Callback to indicate that background preparing has completed.
@deprecated
Use preparingComplete instead.
*/
OGRE_DEPRECATED virtual void backgroundPreparingComplete(Resource*) {}
/** Called whenever the resource finishes loading.
@remarks
If a Resource has been marked as background loaded (@see Resource::setBackgroundLoaded),
the call does not itself occur in the thread which is doing the loading;
when loading is complete a response indicator is placed with the
ResourceGroupManager, which will then be sent back to the
listener as part of the application's primary frame loop thread.
*/
virtual void loadingComplete(Resource*) {}
/** Called whenever the resource finishes preparing (paging into memory).
@remarks
If a Resource has been marked as background loaded (@see Resource::setBackgroundLoaded)
the call does not itself occur in the thread which is doing the preparing;
when preparing is complete a response indicator is placed with the
ResourceGroupManager, which will then be sent back to the
listener as part of the application's primary frame loop thread.
*/
virtual void preparingComplete(Resource*) {}
/** Called whenever the resource has been unloaded. */
virtual void unloadingComplete(Resource*) {}
};
/// Enum identifying the loading state of the resource
enum LoadingState
{
/// Not loaded
LOADSTATE_UNLOADED,
/// Loading is in progress
LOADSTATE_LOADING,
/// Fully loaded
LOADSTATE_LOADED,
/// Currently unloading
LOADSTATE_UNLOADING,
/// Fully prepared
LOADSTATE_PREPARED,
/// Preparing is in progress
LOADSTATE_PREPARING
};
protected:
/// Creator
ResourceManager* mCreator;
/// Unique name of the resource
String mName;
/// The name of the resource group
String mGroup;
/// Numeric handle for more efficient look up than name
ResourceHandle mHandle;
/// Is the resource currently loaded?
AtomicScalar<LoadingState> mLoadingState;
/// Is this resource going to be background loaded? Only applicable for multithreaded
volatile bool mIsBackgroundLoaded;
/// The size of the resource in bytes
size_t mSize;
/// Is this file manually loaded?
bool mIsManual;
/// Origin of this resource (e.g. script name) - optional
String mOrigin;
/// Optional manual loader; if provided, data is loaded from here instead of a file
ManualResourceLoader* mLoader;
/// State count, the number of times this resource has changed state
size_t mStateCount;
typedef set<Listener*>::type ListenerList;
ListenerList mListenerList;
OGRE_MUTEX(mListenerListMutex);
/** Protected unnamed constructor to prevent default construction.
*/
Resource()
: mCreator(0), mHandle(0), mLoadingState(LOADSTATE_UNLOADED),
mIsBackgroundLoaded(false), mSize(0), mIsManual(0), mLoader(0)
{
}
/** Internal hook to perform actions before the load process, but
after the resource has been marked as 'loading'.
@note Mutex will have already been acquired by the loading thread.
Also, this call will occur even when using a ManualResourceLoader
(when loadImpl is not actually called)
*/
virtual void preLoadImpl(void) {}
/** Internal hook to perform actions after the load process, but
before the resource has been marked as fully loaded.
@note Mutex will have already been acquired by the loading thread.
Also, this call will occur even when using a ManualResourceLoader
(when loadImpl is not actually called)
*/
virtual void postLoadImpl(void) {}
/** Internal hook to perform actions before the unload process.
@note Mutex will have already been acquired by the unloading thread.
*/
virtual void preUnloadImpl(void) {}
/** Internal hook to perform actions after the unload process, but
before the resource has been marked as fully unloaded.
@note Mutex will have already been acquired by the unloading thread.
*/
virtual void postUnloadImpl(void) {}
/** Internal implementation of the meat of the 'prepare' action.
*/
virtual void prepareImpl(void) {}
/** Internal function for undoing the 'prepare' action. Called when
the load is completed, and when resources are unloaded when they
are prepared but not yet loaded.
*/
virtual void unprepareImpl(void) {}
/** Internal implementation of the meat of the 'load' action, only called if this
resource is not being loaded from a ManualResourceLoader.
*/
virtual void loadImpl(void) = 0;
/** Internal implementation of the 'unload' action; called regardless of
whether this resource is being loaded from a ManualResourceLoader.
*/
virtual void unloadImpl(void) = 0;
public:
/** Standard constructor.
@param creator Pointer to the ResourceManager that is creating this resource
@param name The unique name of the resource
@param group The name of the resource group to which this resource belongs
@param isManual Is this resource manually loaded? If so, you should really
populate the loader parameter in order that the load process
can call the loader back when loading is required.
@param loader Pointer to a ManualResourceLoader implementation which will be called
when the Resource wishes to load (should be supplied if you set
isManual to true). You can in fact leave this parameter null
if you wish, but the Resource will never be able to reload if
anything ever causes it to unload. Therefore provision of a proper
ManualResourceLoader instance is strongly recommended.
*/
Resource(ResourceManager* creator, const String& name, ResourceHandle handle,
const String& group, bool isManual = false, ManualResourceLoader* loader = 0);
/** Virtual destructor. Shouldn't need to be overloaded, as the resource
deallocation code should reside in unload()
@see
Resource::unload()
*/
virtual ~Resource();
/** Prepares the resource for load, if it is not already. One can call prepare()
before load(), but this is not required as load() will call prepare()
itself, if needed. When OGRE_THREAD_SUPPORT==1 both load() and prepare()
are thread-safe. When OGRE_THREAD_SUPPORT==2 however, only prepare()
is thread-safe. The reason for this function is to allow a background
thread to do some of the loading work, without requiring the whole render
system to be thread-safe. The background thread would call
prepare() while the main render loop would later call load(). So long as
prepare() remains thread-safe, subclasses can arbitrarily split the work of
loading a resource between load() and prepare(). It is best to try and
do as much work in prepare(), however, since this will leave less work for
the main render thread to do and thus increase FPS.
@param backgroundThread Whether this is occurring in a background thread
*/
virtual void prepare(bool backgroundThread = false);
/** Loads the resource, if it is not already.
@remarks
If the resource is loaded from a file, loading is automatic. If not,
if for example this resource gained it's data from procedural calls
rather than loading from a file, then this resource will not reload
on it's own.
@param backgroundThread Indicates whether the caller of this method is
the background resource loading thread.
*/
virtual void load(bool backgroundThread = false);
/** Reloads the resource, if it is already loaded.
@remarks
Calls unload() and then load() again, if the resource is already
loaded. If it is not loaded already, then nothing happens.
*/
virtual void reload(void);
/** Returns true if the Resource is reloadable, false otherwise.
*/
virtual bool isReloadable(void) const
{
return !mIsManual || mLoader;
}
/** Is this resource manually loaded?
*/
virtual bool isManuallyLoaded(void) const
{
return mIsManual;
}
/** Unloads the resource; this is not permanent, the resource can be
reloaded later if required.
*/
virtual void unload(void);
/** Retrieves info about the size of the resource.
*/
virtual size_t getSize(void) const
{
return mSize;
}
/** 'Touches' the resource to indicate it has been used.
*/
virtual void touch(void);
/** Gets resource name.
*/
virtual const String& getName(void) const
{
return mName;
}
virtual ResourceHandle getHandle(void) const
{
return mHandle;
}
/** Returns true if the Resource has been prepared, false otherwise.
*/
virtual bool isPrepared(void) const
{
// No lock required to read this state since no modify
return (mLoadingState.get() == LOADSTATE_PREPARED);
}
/** Returns true if the Resource has been loaded, false otherwise.
*/
virtual bool isLoaded(void) const
{
// No lock required to read this state since no modify
return (mLoadingState.get() == LOADSTATE_LOADED);
}
/** Returns whether the resource is currently in the process of
background loading.
*/
virtual bool isLoading() const
{
return (mLoadingState.get() == LOADSTATE_LOADING);
}
/** Returns the current loading state.
*/
virtual LoadingState getLoadingState() const
{
return mLoadingState.get();
}
/** Returns whether this Resource has been earmarked for background loading.
@remarks
This option only makes sense when you have built Ogre with
thread support (OGRE_THREAD_SUPPORT). If a resource has been marked
for background loading, then it won't load on demand like normal
when load() is called. Instead, it will ignore request to load()
except if the caller indicates it is the background loader. Any
other users of this resource should check isLoaded(), and if that
returns false, don't use the resource and come back later.
*/
virtual bool isBackgroundLoaded(void) const { return mIsBackgroundLoaded; }
/** Tells the resource whether it is background loaded or not.
@see Resource::isBackgroundLoaded. Note that calling this only
defers the normal on-demand loading behaviour of a resource, it
does not actually set up a thread to make sure the resource gets
loaded in the background. You should use ResourceBackgroundLoadingQueue
to manage the actual loading (which will call this method itself).
*/
virtual void setBackgroundLoaded(bool bl) { mIsBackgroundLoaded = bl; }
/** Escalates the loading of a background loaded resource.
@remarks
If a resource is set to load in the background, but something needs
it before it's been loaded, there could be a problem. If the user
of this resource really can't wait, they can escalate the loading
which basically pulls the loading into the current thread immediately.
If the resource is already being loaded but just hasn't quite finished
then this method will simply wait until the background load is complete.
*/
virtual void escalateLoading();
/** Register a listener on this resource.
@see Resource::Listener
*/
virtual void addListener(Listener* lis);
/** Remove a listener on this resource.
@see Resource::Listener
*/
virtual void removeListener(Listener* lis);
/// Gets the group which this resource is a member of
virtual const String& getGroup(void) const { return mGroup; }
/** Change the resource group ownership of a Resource.
@remarks
This method is generally reserved for internal use, although
if you really know what you're doing you can use it to move
this resource from one group to another.
@param newGroup Name of the new group
*/
virtual void changeGroupOwnership(const String& newGroup);
/// Gets the manager which created this resource
virtual ResourceManager* getCreator(void) { return mCreator; }
/** Get the origin of this resource, e.g. a script file name.
@remarks
This property will only contain something if the creator of
this resource chose to populate it. Script loaders are advised
to populate it.
*/
virtual const String& getOrigin(void) const { return mOrigin; }
/// Notify this resource of it's origin
virtual void _notifyOrigin(const String& origin) { mOrigin = origin; }
/** Returns the number of times this resource has changed state, which
generally means the number of times it has been loaded. Objects that
build derived data based on the resource can check this value against
a copy they kept last time they built this derived data, in order to
know whether it needs rebuilding. This is a nice way of monitoring
changes without having a tightly-bound callback.
*/
virtual size_t getStateCount() const { return mStateCount; }
/** Manually mark the state of this resource as having been changed.
@remarks
You only need to call this from outside if you explicitly want derived
objects to think this object has changed. @see getStateCount.
*/
virtual void _dirtyState();
/** Firing of loading complete event
@remarks
You should call this from the thread that runs the main frame loop
to avoid having to make the receivers of this event thread-safe.
If you use Ogre's built in frame loop you don't need to call this
yourself.
@param wasBackgroundLoaded Whether this was a background loaded event
*/
virtual void _fireLoadingComplete(bool wasBackgroundLoaded);
/** Firing of preparing complete event
@remarks
You should call this from the thread that runs the main frame loop
to avoid having to make the receivers of this event thread-safe.
If you use Ogre's built in frame loop you don't need to call this
yourself.
@param wasBackgroundLoaded Whether this was a background loaded event
*/
virtual void _firePreparingComplete(bool wasBackgroundLoaded);
/** Firing of unloading complete event
@remarks
You should call this from the thread that runs the main frame loop
to avoid having to make the receivers of this event thread-safe.
If you use Ogre's built in frame loop you don't need to call this
yourself.
*/
virtual void _fireUnloadingComplete(void);
/** Calculate the size of a resource; this will only be called after 'load' */
virtual size_t calculateSize(void) const;
};
/** Shared pointer to a Resource.
@remarks
This shared pointer allows many references to a resource to be held, and
when the final reference is removed, the resource will be destroyed.
Note that the ResourceManager which created this Resource will be holding
at least one reference, so this resource will not get destroyed until
someone removes the resource from the manager - this at least gives you
strong control over when resources are freed. But the nature of the
shared pointer means that if anyone refers to the removed resource in the
meantime, the resource will remain valid.
@par
You may well see references to ResourcePtr (i.e. ResourcePtr&) being passed
around internally within Ogre. These are 'weak references' ie they do
not increment the reference count on the Resource. This is done for
efficiency in temporary operations that shouldn't need to incur the
overhead of maintaining the reference count; however we don't recommend
you do it yourself since these references are not guaranteed to remain valid.
*/
typedef SharedPtr<Resource> ResourcePtr;
/** Interface describing a manual resource loader.
@remarks
Resources are usually loaded from files; however in some cases you
want to be able to set the data up manually instead. This provides
some problems, such as how to reload a Resource if it becomes
unloaded for some reason, either because of memory constraints, or
because a device fails and some or all of the data is lost.
@par
This interface should be implemented by all classes which wish to
provide manual data to a resource. They provide a pointer to themselves
when defining the resource (via the appropriate ResourceManager),
and will be called when the Resource tries to load.
They should implement the loadResource method such that the Resource
is in the end set up exactly as if it had loaded from a file,
although the implementations will likely differ between subclasses
of Resource, which is why no generic algorithm can be stated here.
@note
The loader must remain valid for the entire life of the resource,
so that if need be it can be called upon to re-load the resource
at any time.
*/
class _OgreExport ManualResourceLoader
{
public:
ManualResourceLoader() {}
virtual ~ManualResourceLoader() {}
/** Called when a resource wishes to load. Note that this could get
* called in a background thread even in just a semithreaded ogre
* (OGRE_THREAD_SUPPORT==2). Thus, you must not access the rendersystem from
* this callback. Do that stuff in loadResource.
@param resource The resource which wishes to load
*/
virtual void prepareResource(Resource* resource)
{ (void)resource; }
/** Called when a resource wishes to prepare.
@param resource The resource which wishes to prepare
*/
virtual void loadResource(Resource* resource) = 0;
};
/** @} */
/** @} */
}
#include "OgreHeaderSuffix.h"
#endif
| 412 | 0.979723 | 1 | 0.979723 | game-dev | MEDIA | 0.832813 | game-dev | 0.71082 | 1 | 0.71082 |
MinecraftForge/MinecraftForge | 1,631 | src/main/java/net/minecraftforge/client/model/pipeline/VertexConsumerWrapper.java | /*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.pipeline;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.blaze3d.vertex.VertexFormatElement;
/**
* Wrapper for {@link VertexConsumer} which delegates all operations to its parent.
* <p>
* Useful for defining custom pipeline elements that only process certain data.
*/
public abstract class VertexConsumerWrapper implements VertexConsumer
{
protected final VertexConsumer parent;
public VertexConsumerWrapper(VertexConsumer parent)
{
this.parent = parent;
}
@Override
public VertexConsumer addVertex(float x, float y, float z)
{
parent.addVertex(x, y, z);
return this;
}
@Override
public VertexConsumer setColor(int r, int g, int b, int a)
{
parent.setColor(r, g, b, a);
return this;
}
@Override
public VertexConsumer setUv(float u, float v)
{
parent.setUv(u, v);
return this;
}
@Override
public VertexConsumer setUv1(int u, int v)
{
parent.setUv1(u, v);
return this;
}
@Override
public VertexConsumer setUv2(int u, int v)
{
parent.setUv2(u, v);
return this;
}
@Override
public VertexConsumer setNormal(float x, float y, float z)
{
parent.setNormal(x, y, z);
return this;
}
@Override
public VertexConsumer misc(VertexFormatElement element, int... values)
{
parent.misc(element, values);
return this;
}
}
| 412 | 0.848527 | 1 | 0.848527 | game-dev | MEDIA | 0.941904 | game-dev | 0.834347 | 1 | 0.834347 |
tukui-org/ElvUI | 3,388 | ElvUI/Mainline/Modules/Skins/GuildControl.lua | local E, L, V, P, G = unpack(ElvUI)
local S = E:GetModule('Skins')
local _G = _G
local unpack = unpack
local hooksecurefunc = hooksecurefunc
local GuildControlGetNumRanks = GuildControlGetNumRanks
local GetNumGuildBankTabs = GetNumGuildBankTabs
local function SkinGuildRanks()
for i=1, GuildControlGetNumRanks() do
local rankFrame = _G['GuildControlUIRankOrderFrameRank'..i]
if rankFrame then
if not rankFrame.nameBox.backdrop then
S:HandleEditBox(rankFrame.nameBox)
S:HandleButton(rankFrame.downButton)
S:HandleButton(rankFrame.upButton)
S:HandleButton(rankFrame.deleteButton)
end
rankFrame.nameBox.backdrop:ClearAllPoints()
rankFrame.nameBox.backdrop:Point('TOPLEFT', -2, -4)
rankFrame.nameBox.backdrop:Point('BOTTOMRIGHT', -4, 4)
end
end
end
local function SkinBankTabs()
local numTabs = GetNumGuildBankTabs()
if numTabs < _G.MAX_BUY_GUILDBANK_TABS then
numTabs = numTabs + 1
end
for i=1, numTabs do
local tab = _G['GuildControlBankTab'..i]
if not tab then break end
local buy = tab.buy
if buy and buy.button and not buy.button.IsSkinned then
S:HandleButton(buy.button)
end
local owned = tab.owned
if owned then
owned.tabIcon:SetTexCoord(unpack(E.TexCoords))
if owned.editBox and not owned.editBox.backdrop then
S:HandleEditBox(owned.editBox)
end
if owned.viewCB and not owned.viewCB.IsSkinned then
S:HandleCheckBox(owned.viewCB)
end
if owned.depositCB and not owned.depositCB.IsSkinned then
S:HandleCheckBox(owned.depositCB)
end
end
end
end
function S:Blizzard_GuildControlUI()
if not (E.private.skins.blizzard.enable and E.private.skins.blizzard.guildcontrol) then return end
_G.GuildControlUI:StripTextures()
_G.GuildControlUI:SetTemplate('Transparent')
local RankSettingsFrameGoldBox = _G.GuildControlUIRankSettingsFrameGoldBox
S:HandleEditBox(RankSettingsFrameGoldBox)
RankSettingsFrameGoldBox.backdrop:Point('TOPLEFT', -2, -4)
RankSettingsFrameGoldBox.backdrop:Point('BOTTOMRIGHT', 2, 4)
RankSettingsFrameGoldBox:StripTextures()
S:HandleButton(_G.GuildControlUIRankOrderFrameNewButton)
S:HandleCloseButton(_G.GuildControlUICloseButton)
S:HandleDropDownBox(_G.GuildControlUIRankBankFrameRankDropdown, 180)
S:HandleTrimScrollBar(_G.GuildControlUIRankBankFrameInsetScrollFrame.ScrollBar)
S:HandleDropDownBox(_G.GuildControlUINavigationDropdown)
S:HandleDropDownBox(_G.GuildControlUIRankSettingsFrameRankDropdown, 180)
--[[ FIX ME 11.0
_G.GuildControlUINavigationDropDownButton:Width(20)
_G.GuildControlUIRankSettingsFrameRankDropDownButton:Width(20)
_G.GuildControlUIRankBankFrameRankDropDownButton:Width(20)
]]
_G.GuildControlUIRankBankFrame:StripTextures()
_G.GuildControlUIRankBankFrameInset:StripTextures()
_G.GuildControlUIRankBankFrameInsetScrollFrame:StripTextures()
_G.GuildControlUIHbar:StripTextures()
_G.GuildControlUIRankOrderFrameNewButton:HookScript('OnClick', function()
E:Delay(1, SkinGuildRanks)
end)
S:HandleCheckBox(_G.GuildControlUIRankSettingsFrameOfficerCheckbox)
for i=1, _G.NUM_RANK_FLAGS do
local checkbox = _G['GuildControlUIRankSettingsFrameCheckbox'..i]
if checkbox then S:HandleCheckBox(checkbox) end
end
hooksecurefunc('GuildControlUI_BankTabPermissions_Update', SkinBankTabs)
hooksecurefunc('GuildControlUI_RankOrder_Update', SkinGuildRanks)
end
S:AddCallbackForAddon('Blizzard_GuildControlUI')
| 412 | 0.599036 | 1 | 0.599036 | game-dev | MEDIA | 0.77411 | game-dev | 0.782879 | 1 | 0.782879 |
peeweek/net.peeweek.gameplay-ingredients | 2,563 | Runtime/LevelScripting/Logic/SaveDataSwitchOnIntLogic.cs | using UnityEngine;
namespace GameplayIngredients.Logic
{
[AddComponentMenu(ComponentMenu.logicPath + "Save Data Switch On Int Logic")]
[Callable("Data", "Logic/ic-generic-logic.png")]
public class SaveDataSwitchOnIntLogic : LogicBase
{
public GameSaveManager.Location SaveLocation = GameSaveManager.Location.System;
public string Key = "SomeKey";
[NonNullCheck]
public Callable[] DefaultCaseToCall;
[NonNullCheck]
public Callable[] CasesToCall;
public override void Execute(GameObject instigator = null)
{
var gsm = Manager.Get<GameSaveManager>();
if (gsm.HasInt(Key, SaveLocation))
{
int value = gsm.GetInt(Key, SaveLocation);
if(value > 0 && value < CasesToCall.Length)
{
if (CasesToCall[value] != null)
Callable.Call(CasesToCall[value], instigator);
else
{
Debug.LogWarning($"[SaveDataSwitchOnIntLogic] {gameObject.name} : Callable at index #{Key} was null, using default case.");
CallDefault(instigator);
}
}
else
{
Debug.LogWarning($"[SaveDataSwitchOnIntLogic] {gameObject.name} : Callable at index #{Key} was out of range, using default case.");
CallDefault(instigator);
}
}
else
{
Debug.LogWarning($"[SaveDataSwitchOnIntLogic] {gameObject.name} : Could not Find {Key} in {SaveLocation} Save, using default case.");
CallDefault(instigator);
}
}
void CallDefault(GameObject instigator)
{
if(DefaultCaseToCall != null)
{
Callable.Call(DefaultCaseToCall, instigator);
}
else
{
Debug.LogWarning($"[SaveDataSwitchOnIntLogic] {gameObject.name} : Did not set a default callable, aborting.");
}
}
public override string GetDefaultName()
{
return $"Switch on Integer {SaveLocation} Save Data '{Key}'";
}
void WarnNotExist(string name, GameSaveManager.ValueType type, GameSaveManager.Location location)
{
Debug.LogWarning(string.Format("Save Data Logic: Trying to get {0} value to non existent {1} data in {2} save.", type, name, location));
}
}
}
| 412 | 0.830924 | 1 | 0.830924 | game-dev | MEDIA | 0.741563 | game-dev | 0.776455 | 1 | 0.776455 |
esphome/esphome | 1,051 | esphome/components/datetime/datetime_base.h | #pragma once
#include "esphome/core/automation.h"
#include "esphome/core/component.h"
#include "esphome/core/entity_base.h"
#include "esphome/core/time.h"
#ifdef USE_TIME
#include "esphome/components/time/real_time_clock.h"
#endif
namespace esphome {
namespace datetime {
class DateTimeBase : public EntityBase {
public:
virtual ESPTime state_as_esptime() const = 0;
void add_on_state_callback(std::function<void()> &&callback) { this->state_callback_.add(std::move(callback)); }
#ifdef USE_TIME
void set_rtc(time::RealTimeClock *rtc) { this->rtc_ = rtc; }
time::RealTimeClock *get_rtc() const { return this->rtc_; }
#endif
protected:
CallbackManager<void()> state_callback_;
#ifdef USE_TIME
time::RealTimeClock *rtc_;
#endif
};
#ifdef USE_TIME
class DateTimeStateTrigger : public Trigger<ESPTime> {
public:
explicit DateTimeStateTrigger(DateTimeBase *parent) {
parent->add_on_state_callback([this, parent]() { this->trigger(parent->state_as_esptime()); });
}
};
#endif
} // namespace datetime
} // namespace esphome
| 412 | 0.973315 | 1 | 0.973315 | game-dev | MEDIA | 0.20686 | game-dev | 0.793186 | 1 | 0.793186 |
jonnyzzz/TeamCity.Node | 2,169 | server/src/main/java/com/jonnyzzz/teamcity/plugins/node/server/GulpRunType.kt | /*
* Copyright 2013-2015 Eugene Petrenko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jonnyzzz.teamcity.plugins.node.server
import jetbrains.buildServer.requirements.Requirement
import jetbrains.buildServer.requirements.RequirementType
import jetbrains.buildServer.serverSide.PropertiesProcessor
import com.jonnyzzz.teamcity.plugins.node.common.*
class GulpRunType : RunTypeBase() {
private val bean = GulpBean()
override fun getType(): String = bean.runTypeName
override fun getDisplayName(): String = "Gulp"
override fun getDescription(): String = "Executes Gulp tasks"
override fun getEditJsp(): String = "gulp.edit.jsp"
override fun getViewJsp(): String = "gulp.view.jsp"
override fun getRunnerPropertiesProcessor(): PropertiesProcessor = PropertiesProcessor { arrayListOf() }
override fun describeParameters(parameters: Map<String, String>): String
= "Run targets: ${bean.parseCommands(parameters[bean.targets]).joinToString(", ")}"
override fun getDefaultRunnerProperties(): MutableMap<String, String>
= hashMapOf(bean.gulpMode to bean.gulpModeDefault.value)
override fun getRunnerSpecificRequirements(runParameters: Map<String, String>): MutableList<Requirement> {
val result = arrayListOf<Requirement>()
result.addAll(super.getRunnerSpecificRequirements(runParameters))
result.add(Requirement(NodeBean().nodeJSConfigurationParameter, null, RequirementType.EXISTS))
if (bean.parseMode(runParameters[bean.gulpMode]) == GulpExecutionMode.GLOBAL) {
result.add(Requirement(bean.gulpConfigurationParameter, null, RequirementType.EXISTS))
}
return result
}
}
| 412 | 0.817388 | 1 | 0.817388 | game-dev | MEDIA | 0.212996 | game-dev | 0.825418 | 1 | 0.825418 |
PGMDev/PGM | 1,827 | core/src/main/java/tc/oc/pgm/score/ScoreDefinition.java | package tc.oc.pgm.score;
import static net.kyori.adventure.text.Component.empty;
import static net.kyori.adventure.text.Component.space;
import static net.kyori.adventure.text.Component.text;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import tc.oc.pgm.api.filter.Filter;
import tc.oc.pgm.api.party.Competitor;
import tc.oc.pgm.util.named.NameStyle;
public record ScoreDefinition(
int scoreLimit,
int deathScore,
int killScore,
int mercyLimit,
int mercyLimitMin,
Display display,
Filter scoreboardFilter) {
public enum Display {
NUMERICAL(null, Integer.MAX_VALUE) {
@Override
public Component format(Competitor competitor, int score, int limit) {
return text()
.append(text(score, NamedTextColor.WHITE))
.append(limit > 0 ? text("/", NamedTextColor.DARK_GRAY) : empty())
.append(limit > 0 ? text(limit, NamedTextColor.GRAY) : empty())
.append(space())
.append(competitor.getName(NameStyle.SIMPLE_COLOR))
.build();
}
},
CIRCLE("\u2B24", 16), // ⬤
SQUARE("\u2b1b", 16), // ⬛
PIPE("|", 24);
public final String symbol;
public final int max;
Display(String symbol, int max) {
this.symbol = symbol;
this.max = max;
}
public Component format(Competitor competitor, int score, int limit) {
if (score < 0 || score > max || limit > max)
return NUMERICAL.format(competitor, score, limit);
return text()
.append(text("\u2794 ", competitor.getTextColor())) // ➔
.append(text(symbol.repeat(score), competitor.getTextColor()))
.append(limit > score ? text(symbol.repeat(limit - score), NamedTextColor.GRAY) : empty())
.build();
}
}
}
| 412 | 0.779904 | 1 | 0.779904 | game-dev | MEDIA | 0.372699 | game-dev | 0.890395 | 1 | 0.890395 |
JukeboxMC/JukeboxMC | 1,455 | JukeboxMC-Server/src/main/kotlin/org/jukeboxmc/server/block/behavior/BlockGlowLichen.kt | package org.jukeboxmc.server.block.behavior
import org.cloudburstmc.nbt.NbtMap
import org.jukeboxmc.api.Identifier
import org.jukeboxmc.api.block.GlowLichen
import org.jukeboxmc.api.block.data.BlockFace
import org.jukeboxmc.api.math.Vector
import org.jukeboxmc.server.block.JukeboxBlock
import org.jukeboxmc.server.item.JukeboxItem
import org.jukeboxmc.server.player.JukeboxPlayer
import org.jukeboxmc.server.world.JukeboxWorld
class BlockGlowLichen(identifier: Identifier, blockStates: NbtMap?) : JukeboxBlock(identifier, blockStates),
GlowLichen {
override fun placeBlock(
player: JukeboxPlayer,
world: JukeboxWorld,
blockPosition: Vector,
placePosition: Vector,
clickedPosition: Vector,
itemInHand: JukeboxItem,
blockFace: BlockFace
): Boolean {
val block = world.getBlock(placePosition)
if (block is BlockWater && block.getLiquidDepth() == 0) {
world.setBlock(placePosition, block, 1, false)
}
return super.placeBlock(player, world, blockPosition, placePosition, clickedPosition, itemInHand, blockFace)
}
override fun getMultiFaceDirections(): Int {
return this.getIntState("multi_face_direction_bits")
}
override fun setMultiFaceDirections(value: Int): GlowLichen {
return this.setState("multi_face_direction_bits", value)
}
override fun getWaterLoggingLevel(): Int {
return 1
}
} | 412 | 0.737542 | 1 | 0.737542 | game-dev | MEDIA | 0.909479 | game-dev | 0.620243 | 1 | 0.620243 |
phaserjs/phaser-ce-examples | 2,356 | examples/virtualjoystick/buttons.js | /**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2015 Photon Storm Ltd.
* @license {@link http://choosealicense.com/licenses/no-license/|No License}
*
* @description This example requires the Phaser Virtual Joystick Plugin to run.
* For more details please see http://phaser.io/shop/plugins/virtualjoystick
*/
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example');
var PhaserGame = function () {
this.fx;
this.pad;
this.buttonA;
this.buttonB;
this.buttonC;
};
PhaserGame.prototype = {
preload: function () {
this.load.atlas('generic', 'assets/virtualjoystick/skins/generic-joystick.png', 'assets/virtualjoystick/skins/generic-joystick.json');
this.load.image('bg', 'assets/virtualjoystick/barbarian_loading.png');
this.load.audio('sfx', [ 'assets/virtualjoystick/magical_horror_audiosprite.mp3', 'assets/virtualjoystick/magical_horror_audiosprite.ogg' ]);
},
create: function () {
var bg = this.add.image(this.world.centerX, 32, 'bg');
bg.anchor.x = 0.5;
this.fx = game.add.audio('sfx');
this.fx.allowMultiple = true;
this.fx.addMarker('charm', 0, 2.7);
this.fx.addMarker('curse', 4, 2.9);
this.fx.addMarker('fireball', 8, 5.2);
this.fx.addMarker('spell', 14, 4.7);
this.fx.addMarker('soundscape', 20, 18.8);
this.pad = this.game.plugins.add(Phaser.VirtualJoystick);
this.buttonA = this.pad.addButton(200, 520, 'generic', 'button1-up', 'button1-down');
this.buttonA.onDown.add(this.pressButtonA, this);
this.buttonA.addKey(Phaser.Keyboard.A);
this.buttonB = this.pad.addButton(400, 500, 'generic', 'button2-up', 'button2-down');
this.buttonB.onDown.add(this.pressButtonB, this);
this.buttonB.addKey(Phaser.Keyboard.B);
this.buttonC = this.pad.addButton(600, 520, 'generic', 'button3-up', 'button3-down');
this.buttonC.onDown.add(this.pressButtonC, this);
this.buttonC.addKey(Phaser.Keyboard.C);
},
pressButtonA: function () {
this.fx.play('charm');
},
pressButtonB: function () {
this.fx.play('spell');
},
pressButtonC: function () {
this.fx.play('fireball');
}
};
game.state.add('Game', PhaserGame, true);
| 412 | 0.75308 | 1 | 0.75308 | game-dev | MEDIA | 0.711298 | game-dev | 0.91603 | 1 | 0.91603 |
mastercomfig/tf2-patches-old | 31,113 | src/vgui2/vgui_controls/consoledialog.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#include "vgui_controls/consoledialog.h"
#include "vgui/IInput.h"
#include "vgui/IScheme.h"
#include "vgui/IVGui.h"
#include "vgui/ISurface.h"
#include "vgui/ILocalize.h"
#include "KeyValues.h"
#include "vgui_controls/Button.h"
#include "vgui/KeyCode.h"
#include "vgui_controls/Menu.h"
#include "vgui_controls/TextEntry.h"
#include "vgui_controls/RichText.h"
#include "tier1/convar.h"
#include "tier1/convar_serverbounded.h"
#include "icvar.h"
#include "filesystem.h"
#include <stdlib.h>
#if defined( _X360 )
#include "xbox/xbox_win32stubs.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Used by the autocompletion system
//-----------------------------------------------------------------------------
class CNonFocusableMenu : public Menu
{
DECLARE_CLASS_SIMPLE( CNonFocusableMenu, Menu );
public:
CNonFocusableMenu( Panel *parent, const char *panelName )
: BaseClass( parent, panelName ),
m_pFocus( 0 )
{
}
void SetFocusPanel( Panel *panel )
{
m_pFocus = panel;
}
VPANEL GetCurrentKeyFocus()
{
if ( !m_pFocus )
return GetVPanel();
return m_pFocus->GetVPanel();
}
private:
Panel *m_pFocus;
};
//-----------------------------------------------------------------------------
// Purpose: forwards tab key presses up from the text entry so we can do autocomplete
//-----------------------------------------------------------------------------
class TabCatchingTextEntry : public TextEntry
{
public:
TabCatchingTextEntry(Panel *parent, const char *name, VPANEL comp) : TextEntry(parent, name), m_pCompletionList( comp )
{
SetAllowNonAsciiCharacters( true );
SetDragEnabled( true );
}
virtual void OnKeyCodeTyped(KeyCode code)
{
if (code == KEY_TAB)
{
GetParent()->OnKeyCodeTyped(code);
}
else if ( code == KEY_ENTER )
{
// submit is the default button whose click event will have been called already
}
else
{
TextEntry::OnKeyCodeTyped(code);
}
}
virtual void OnKillFocus()
{
if ( input()->GetFocus() != m_pCompletionList ) // if its not the completion window trying to steal our focus
{
PostMessage(GetParent(), new KeyValues("CloseCompletionList"));
}
}
private:
VPANEL m_pCompletionList;
};
// Things the user typed in and hit submit/return with
CHistoryItem::CHistoryItem( void )
{
m_text = NULL;
m_extraText = NULL;
m_bHasExtra = false;
}
CHistoryItem::CHistoryItem( const char *text, const char *extra )
{
Assert( text );
m_text = NULL;
m_extraText = NULL;
m_bHasExtra = false;
SetText( text , extra );
}
CHistoryItem::CHistoryItem( const CHistoryItem& src )
{
m_text = NULL;
m_extraText = NULL;
m_bHasExtra = false;
SetText( src.GetText(), src.GetExtra() );
}
CHistoryItem::~CHistoryItem( void )
{
delete[] m_text;
delete[] m_extraText;
m_text = NULL;
}
const char *CHistoryItem::GetText() const
{
if ( m_text )
{
return m_text;
}
else
{
return "";
}
}
const char *CHistoryItem::GetExtra() const
{
if ( m_extraText )
{
return m_extraText;
}
else
{
return NULL;
}
}
void CHistoryItem::SetText( const char *text, const char *extra )
{
delete[] m_text;
int len = strlen( text ) + 1;
m_text = new char[ len ];
Q_memset( m_text, 0x0, len );
Q_strncpy( m_text, text, len );
if ( extra )
{
m_bHasExtra = true;
delete[] m_extraText;
int elen = strlen( extra ) + 1;
m_extraText = new char[ elen ];
Q_memset( m_extraText, 0x0, elen);
Q_strncpy( m_extraText, extra, elen );
}
else
{
m_bHasExtra = false;
}
}
//-----------------------------------------------------------------------------
//
// Console page completion item starts here
//
//-----------------------------------------------------------------------------
CConsolePanel::CompletionItem::CompletionItem( void )
{
m_bIsCommand = true;
m_pCommand = NULL;
m_pText = NULL;
}
CConsolePanel::CompletionItem::CompletionItem( const CompletionItem& src )
{
m_bIsCommand = src.m_bIsCommand;
m_pCommand = src.m_pCommand;
if ( src.m_pText )
{
m_pText = new CHistoryItem( (const CHistoryItem& )src.m_pText );
}
else
{
m_pText = NULL;
}
}
CConsolePanel::CompletionItem& CConsolePanel::CompletionItem::operator =( const CompletionItem& src )
{
if ( this == &src )
return *this;
m_bIsCommand = src.m_bIsCommand;
m_pCommand = src.m_pCommand;
if ( src.m_pText )
{
m_pText = new CHistoryItem( (const CHistoryItem& )*src.m_pText );
}
else
{
m_pText = NULL;
}
return *this;
}
CConsolePanel::CompletionItem::~CompletionItem( void )
{
if ( m_pText )
{
delete m_pText;
m_pText = NULL;
}
}
const char *CConsolePanel::CompletionItem::GetName() const
{
if ( m_bIsCommand )
return m_pCommand->GetName();
return m_pCommand ? m_pCommand->GetName() : GetCommand();
}
const char *CConsolePanel::CompletionItem::GetItemText( void )
{
static char text[256];
text[0] = 0;
if ( m_pText )
{
if ( m_pText->HasExtra() )
{
Q_snprintf( text, sizeof( text ), "%s %s", m_pText->GetText(), m_pText->GetExtra() );
}
else
{
Q_strncpy( text, m_pText->GetText(), sizeof( text ) );
}
}
return text;
}
const char *CConsolePanel::CompletionItem::GetCommand( void ) const
{
static char text[256];
text[0] = 0;
if ( m_pText )
{
Q_strncpy( text, m_pText->GetText(), sizeof( text ) );
}
return text;
}
//-----------------------------------------------------------------------------
//
// Console page starts here
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Purpose: Constructor, destuctor
//-----------------------------------------------------------------------------
CConsolePanel::CConsolePanel( vgui::Panel *pParent, const char *pName, bool bStatusVersion ) :
BaseClass( pParent, pName ), m_bStatusVersion( bStatusVersion )
{
SetKeyBoardInputEnabled( true );
if ( !m_bStatusVersion )
{
SetMinimumSize(100,100);
}
// create controls
m_pHistory = new RichText(this, "ConsoleHistory");
m_pHistory->SetAllowKeyBindingChainToParent( false );
SETUP_PANEL( m_pHistory );
m_pHistory->SetVerticalScrollbar( !m_bStatusVersion );
if ( m_bStatusVersion )
{
m_pHistory->SetDrawOffsets( 3, 3 );
}
m_pHistory->GotoTextEnd();
m_pSubmit = new Button(this, "ConsoleSubmit", "#Console_Submit");
m_pSubmit->SetCommand("submit");
m_pSubmit->SetVisible( !m_bStatusVersion );
CNonFocusableMenu *pCompletionList = new CNonFocusableMenu( this, "CompletionList" );
m_pCompletionList = pCompletionList;
m_pCompletionList->SetVisible(false);
m_pEntry = new TabCatchingTextEntry(this, "ConsoleEntry", m_pCompletionList->GetVPanel() );
m_pEntry->AddActionSignalTarget(this);
m_pEntry->SendNewLine(true);
pCompletionList->SetFocusPanel( m_pEntry );
// need to set up default colors, since ApplySchemeSettings won't be called until later
m_PrintColor = Color(216, 222, 211, 255);
m_DPrintColor = Color(196, 181, 80, 255);
m_pEntry->SetTabPosition(1);
m_bAutoCompleteMode = false;
m_szPartialText[0] = 0;
m_szPreviousPartialText[0]=0;
// Add to global console list
g_pCVar->InstallConsoleDisplayFunc( this );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CConsolePanel::~CConsolePanel()
{
ClearCompletionList();
m_CommandHistory.Purge();
g_pCVar->RemoveConsoleDisplayFunc( this );
}
//-----------------------------------------------------------------------------
// Updates the completion list
//-----------------------------------------------------------------------------
void CConsolePanel::OnThink()
{
BaseClass::OnThink();
if ( !IsVisible() )
return;
if ( !m_pCompletionList->IsVisible() )
return;
UpdateCompletionListPosition();
}
//-----------------------------------------------------------------------------
// Purpose: Clears the console
//-----------------------------------------------------------------------------
void CConsolePanel::Clear()
{
m_pHistory->SetText("");
m_pHistory->GotoTextEnd();
}
//-----------------------------------------------------------------------------
// Purpose: color text print
//-----------------------------------------------------------------------------
void CConsolePanel::ColorPrint( const Color& clr, const char *msg )
{
if ( m_bStatusVersion )
{
Clear();
}
m_pHistory->InsertColorChange( clr );
m_pHistory->InsertString( msg );
}
//-----------------------------------------------------------------------------
// Purpose: normal text print
//-----------------------------------------------------------------------------
void CConsolePanel::Print(const char *msg)
{
ColorPrint( m_PrintColor, msg );
}
//-----------------------------------------------------------------------------
// Purpose: debug text print
//-----------------------------------------------------------------------------
void CConsolePanel::DPrint( const char *msg )
{
ColorPrint( m_DPrintColor, msg );
}
void CConsolePanel::ClearCompletionList()
{
int c = m_CompletionList.Count();
int i;
for ( i = c - 1; i >= 0; i-- )
{
delete m_CompletionList[ i ];
}
m_CompletionList.Purge();
}
static ConCommand *FindAutoCompleteCommmandFromPartial( const char *partial )
{
char command[ 256 ];
Q_strncpy( command, partial, sizeof( command ) );
char *space = Q_strstr( command, " " );
if ( space )
{
*space = 0;
}
ConCommand *cmd = g_pCVar->FindCommand( command );
if ( !cmd )
return NULL;
if ( !cmd->CanAutoComplete() )
return NULL;
return cmd;
}
//-----------------------------------------------------------------------------
// Purpose: rebuilds the list of possible completions from the current entered text
//-----------------------------------------------------------------------------
void CConsolePanel::RebuildCompletionList(const char *text)
{
ClearCompletionList();
// we need the length of the text for the partial string compares
int len = Q_strlen(text);
if ( len < 1 )
{
// Fill the completion list with history instead
for ( int i = 0 ; i < m_CommandHistory.Count(); i++ )
{
CHistoryItem *item = &m_CommandHistory[ i ];
CompletionItem *comp = new CompletionItem();
m_CompletionList.AddToTail( comp );
comp->m_bIsCommand = false;
comp->m_pCommand = NULL;
comp->m_pText = new CHistoryItem( *item );
}
return;
}
bool bNormalBuild = true;
// if there is a space in the text, and the command isn't of the type to know how to autocomplet, then command completion is over
const char *space = strstr( text, " " );
if ( space )
{
ConCommand *pCommand = FindAutoCompleteCommmandFromPartial( text );
if ( !pCommand )
return;
bNormalBuild = false;
CUtlVector< CUtlString > commands;
int count = pCommand->AutoCompleteSuggest( text, commands );
Assert( count <= COMMAND_COMPLETION_MAXITEMS );
int i;
for ( i = 0; i < count; i++ )
{
// match found, add to list
CompletionItem *item = new CompletionItem();
m_CompletionList.AddToTail( item );
item->m_bIsCommand = false;
item->m_pCommand = NULL;
item->m_pText = new CHistoryItem( commands[ i ].String() );
}
}
if ( bNormalBuild )
{
// look through the command list for all matches
ConCommandBase const *cmd = (ConCommandBase const *)cvar->GetCommands();
while (cmd)
{
if ( cmd->IsFlagSet( FCVAR_DEVELOPMENTONLY ) || cmd->IsFlagSet( FCVAR_HIDDEN ) )
{
cmd = cmd->GetNext();
continue;
}
if ( !strnicmp(text, cmd->GetName(), len))
{
// match found, add to list
CompletionItem *item = new CompletionItem();
m_CompletionList.AddToTail( item );
item->m_pCommand = (ConCommandBase *)cmd;
const char *tst = cmd->GetName();
if ( !cmd->IsCommand() )
{
item->m_bIsCommand = false;
ConVar *var = ( ConVar * )cmd;
ConVar_ServerBounded *pBounded = dynamic_cast<ConVar_ServerBounded*>( var );
if ( pBounded || var->IsFlagSet( FCVAR_NEVER_AS_STRING ) )
{
char strValue[512];
int intVal = pBounded ? pBounded->GetInt() : var->GetInt();
float floatVal = pBounded ? pBounded->GetFloat() : var->GetFloat();
if ( floatVal == intVal )
Q_snprintf( strValue, sizeof( strValue ), "%d", intVal );
else
Q_snprintf( strValue, sizeof( strValue ), "%f", floatVal );
item->m_pText = new CHistoryItem( var->GetName(), strValue );
}
else
{
item->m_pText = new CHistoryItem( var->GetName(), var->GetString() );
}
}
else
{
item->m_bIsCommand = true;
item->m_pText = new CHistoryItem( tst );
}
}
cmd = cmd->GetNext();
}
// Now sort the list by command name
if ( m_CompletionList.Count() >= 2 )
{
for ( int i = 0 ; i < m_CompletionList.Count(); i++ )
{
for ( int j = i + 1; j < m_CompletionList.Count(); j++ )
{
const CompletionItem *i1, *i2;
i1 = m_CompletionList[ i ];
i2 = m_CompletionList[ j ];
if ( Q_stricmp( i1->GetName(), i2->GetName() ) > 0 )
{
CompletionItem *temp = m_CompletionList[ i ];
m_CompletionList[ i ] = m_CompletionList[ j ];
m_CompletionList[ j ] = temp;
}
}
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: auto completes current text
//-----------------------------------------------------------------------------
void CConsolePanel::OnAutoComplete(bool reverse)
{
if (!m_bAutoCompleteMode)
{
// we're not in auto-complete mode, Start
m_iNextCompletion = 0;
m_bAutoCompleteMode = true;
}
// if we're in reverse, move back to before the current
if (reverse)
{
m_iNextCompletion -= 2;
if (m_iNextCompletion < 0)
{
// loop around in reverse
m_iNextCompletion = m_CompletionList.Size() - 1;
}
}
// get the next completion
if (!m_CompletionList.IsValidIndex(m_iNextCompletion))
{
// loop completion list
m_iNextCompletion = 0;
}
// make sure everything is still valid
if (!m_CompletionList.IsValidIndex(m_iNextCompletion))
return;
// match found, set text
char completedText[256];
CompletionItem *item = m_CompletionList[m_iNextCompletion];
Assert( item );
if ( !item->m_bIsCommand && item->m_pCommand )
{
Q_strncpy(completedText, item->GetCommand(), sizeof(completedText) - 2 );
}
else
{
Q_strncpy(completedText, item->GetItemText(), sizeof(completedText) - 2 );
}
if ( !Q_strstr( completedText, " " ) )
{
Q_strncat(completedText, " ", sizeof(completedText), COPY_ALL_CHARACTERS );
}
m_pEntry->SetText(completedText);
m_pEntry->GotoTextEnd();
m_pEntry->SelectNone();
m_iNextCompletion++;
}
//-----------------------------------------------------------------------------
// Purpose: Called whenever the user types text
//-----------------------------------------------------------------------------
void CConsolePanel::OnTextChanged(Panel *panel)
{
if (panel != m_pEntry)
return;
Q_strncpy( m_szPreviousPartialText, m_szPartialText, sizeof( m_szPreviousPartialText ) );
// get the partial text the user type
m_pEntry->GetText(m_szPartialText, sizeof(m_szPartialText));
// see if they've hit the tilde key (which opens & closes the console)
int len = Q_strlen(m_szPartialText);
bool hitTilde = ( m_szPartialText[len - 1] == '~' || m_szPartialText[len - 1] == '`' ) ? true : false;
bool altKeyDown = ( vgui::input()->IsKeyDown( KEY_LALT ) || vgui::input()->IsKeyDown( KEY_RALT ) ) ? true : false;
bool ctrlKeyDown = ( vgui::input()->IsKeyDown( KEY_LCONTROL ) || vgui::input()->IsKeyDown( KEY_RCONTROL ) ) ? true : false;
// Alt-Tilde toggles Japanese IME on/off!!!
if ( ( len > 0 ) && hitTilde )
{
// Strip the last character (tilde)
m_szPartialText[ len - 1 ] = L'\0';
if( !altKeyDown && !ctrlKeyDown )
{
m_pEntry->SetText( "" );
// close the console
PostMessage( this, new KeyValues( "Close" ) );
PostActionSignal( new KeyValues( "ClosedByHittingTilde" ) );
}
else
{
m_pEntry->SetText( m_szPartialText );
}
return;
}
// clear auto-complete state since the user has typed
m_bAutoCompleteMode = false;
RebuildCompletionList(m_szPartialText);
// build the menu
if ( m_CompletionList.Count() < 1 )
{
m_pCompletionList->SetVisible(false);
}
else
{
m_pCompletionList->SetVisible(true);
m_pCompletionList->DeleteAllItems();
const int MAX_MENU_ITEMS = 10;
// add the first ten items to the list
for (int i = 0; i < m_CompletionList.Count() && i < MAX_MENU_ITEMS; i++)
{
char text[256];
text[0] = 0;
if (i == MAX_MENU_ITEMS - 1)
{
Q_strncpy(text, "...", sizeof( text ) );
}
else
{
Assert( m_CompletionList[i] );
Q_strncpy(text, m_CompletionList[i]->GetItemText(), sizeof( text ) );
}
KeyValues *kv = new KeyValues("CompletionCommand");
kv->SetString("command",text);
m_pCompletionList->AddMenuItem(text, kv, this);
}
UpdateCompletionListPosition();
}
RequestFocus();
m_pEntry->RequestFocus();
}
//-----------------------------------------------------------------------------
// Purpose: generic vgui command handler
//-----------------------------------------------------------------------------
void CConsolePanel::OnCommand(const char *command)
{
if ( !Q_stricmp( command, "Submit" ) )
{
// submit the entry as a console commmand
char szCommand[256];
m_pEntry->GetText(szCommand, sizeof(szCommand));
PostActionSignal( new KeyValues( "CommandSubmitted", "command", szCommand ) );
// add to the history
Print("] ");
Print(szCommand);
Print("\n");
// clear the field
m_pEntry->SetText("");
// clear the completion state
OnTextChanged(m_pEntry);
// always go the end of the buffer when the user has typed something
m_pHistory->GotoTextEnd();
// Add the command to the history
char *extra = strchr(szCommand, ' ');
if ( extra )
{
*extra = '\0';
extra++;
}
if ( Q_strlen( szCommand ) > 0 )
{
AddToHistory( szCommand, extra );
}
m_pCompletionList->SetVisible(false);
}
else
{
BaseClass::OnCommand(command);
}
}
//-----------------------------------------------------------------------------
// Focus related methods
//-----------------------------------------------------------------------------
bool CConsolePanel::TextEntryHasFocus() const
{
return ( input()->GetFocus() == m_pEntry->GetVPanel() );
}
void CConsolePanel::TextEntryRequestFocus()
{
m_pEntry->RequestFocus();
}
//-----------------------------------------------------------------------------
// Purpose: swallows tab key pressed
//-----------------------------------------------------------------------------
void CConsolePanel::OnKeyCodeTyped(KeyCode code)
{
BaseClass::OnKeyCodeTyped(code);
// check for processing
if ( TextEntryHasFocus() )
{
if (code == KEY_TAB)
{
bool reverse = false;
if (input()->IsKeyDown(KEY_LSHIFT) || input()->IsKeyDown(KEY_RSHIFT))
{
reverse = true;
}
// attempt auto-completion
OnAutoComplete(reverse);
m_pEntry->RequestFocus();
}
else if (code == KEY_DOWN)
{
OnAutoComplete(false);
// UpdateCompletionListPosition();
// m_pCompletionList->SetVisible(true);
m_pEntry->RequestFocus();
}
else if (code == KEY_UP)
{
OnAutoComplete(true);
m_pEntry->RequestFocus();
}
}
}
//-----------------------------------------------------------------------------
// Purpose: lays out controls
//-----------------------------------------------------------------------------
void CConsolePanel::PerformLayout()
{
BaseClass::PerformLayout();
// setup tab ordering
GetFocusNavGroup().SetDefaultButton(m_pSubmit);
IScheme *pScheme = scheme()->GetIScheme( GetScheme() );
m_pEntry->SetBorder(pScheme->GetBorder("DepressedButtonBorder"));
m_pHistory->SetBorder(pScheme->GetBorder("DepressedButtonBorder"));
// layout controls
int wide, tall;
GetSize(wide, tall);
if ( !m_bStatusVersion )
{
const int inset = 8;
const int entryHeight = 24;
const int topHeight = 4;
const int entryInset = 4;
const int submitWide = 64;
const int submitInset = 7; // x inset to pull the submit button away from the frame grab
m_pHistory->SetPos(inset, inset + topHeight);
m_pHistory->SetSize(wide - (inset * 2), tall - (entryInset * 2 + inset * 2 + topHeight + entryHeight));
m_pHistory->InvalidateLayout();
int nSubmitXPos = wide - ( inset + submitWide + submitInset );
m_pSubmit->SetPos( nSubmitXPos, tall - (entryInset * 2 + entryHeight));
m_pSubmit->SetSize( submitWide, entryHeight);
m_pEntry->SetPos( inset, tall - (entryInset * 2 + entryHeight) );
m_pEntry->SetSize( nSubmitXPos - entryInset - 2 * inset, entryHeight);
}
else
{
const int inset = 2;
int entryWidth = wide / 2;
if ( wide > 400 )
{
entryWidth = 200;
}
m_pEntry->SetBounds( inset, inset, entryWidth, tall - 2 * inset );
m_pHistory->SetBounds( inset + entryWidth + inset, inset, ( wide - entryWidth ) - inset, tall - 2 * inset );
}
UpdateCompletionListPosition();
}
//-----------------------------------------------------------------------------
// Purpose: Sets the position of the completion list popup
//-----------------------------------------------------------------------------
void CConsolePanel::UpdateCompletionListPosition()
{
int ex, ey;
m_pEntry->GetPos(ex, ey);
if ( !m_bStatusVersion )
{
// Position below text entry
ey += m_pEntry->GetTall();
}
else
{
// Position above text entry
int menuwide, menutall;
m_pCompletionList->GetSize( menuwide, menutall );
ey -= ( menutall + 4 );
}
LocalToScreen( ex, ey );
m_pCompletionList->SetPos( ex, ey );
if ( m_pCompletionList->IsVisible() )
{
m_pEntry->RequestFocus();
MoveToFront();
m_pCompletionList->MoveToFront();
}
}
//-----------------------------------------------------------------------------
// Purpose: Closes the completion list
//-----------------------------------------------------------------------------
void CConsolePanel::CloseCompletionList()
{
m_pCompletionList->SetVisible(false);
}
//-----------------------------------------------------------------------------
// Purpose: sets up colors
//-----------------------------------------------------------------------------
void CConsolePanel::ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
m_PrintColor = GetSchemeColor("Console.TextColor", pScheme);
m_DPrintColor = GetSchemeColor("Console.DevTextColor", pScheme);
m_pHistory->SetFont( pScheme->GetFont( "ConsoleText", IsProportional() ) );
m_pCompletionList->SetFont( pScheme->GetFont( "DefaultSmall", IsProportional() ) );
InvalidateLayout();
}
//-----------------------------------------------------------------------------
// Purpose: Handles autocompletion menu input
//-----------------------------------------------------------------------------
void CConsolePanel::OnMenuItemSelected(const char *command)
{
if ( strstr( command, "..." ) ) // stop the menu going away if you click on ...
{
m_pCompletionList->SetVisible( true );
}
else
{
m_pEntry->SetText(command);
m_pEntry->GotoTextEnd();
m_pEntry->InsertChar(' ');
m_pEntry->GotoTextEnd();
}
}
void CConsolePanel::Hide()
{
OnClose();
m_iNextCompletion = 0;
RebuildCompletionList("");
}
void CConsolePanel::AddToHistory( const char *commandText, const char *extraText )
{
// Newest at end, oldest at head
while ( m_CommandHistory.Count() >= MAX_HISTORY_ITEMS )
{
// Remove from head until size is reasonable
m_CommandHistory.Remove( 0 );
}
// strip the space off the end of the command before adding it to the history
// If this code gets cleaned up then we should remove the redundant calls to strlen,
// the check for whether _alloca succeeded, and should use V_strncpy instead of the
// error prone memset/strncpy sequence.
char *command = static_cast<char *>( _alloca( (strlen( commandText ) + 1 ) * sizeof( char ) ));
if ( command )
{
memset( command, 0x0, strlen( commandText ) + 1 );
strncpy( command, commandText, strlen( commandText ));
// There is no actual bug here, just some sloppy/odd code.
// src\vgui2\vgui_controls\consoledialog.cpp(974): warning C6053: The prior call to 'strncpy' might not zero-terminate string 'command'
ANALYZE_SUPPRESS( 6053 )
if ( command[ strlen( command ) -1 ] == ' ' )
{
command[ strlen( command ) -1 ] = '\0';
}
}
// strip the quotes off the extra text
char *extra = NULL;
if ( extraText )
{
extra = static_cast<char *>( malloc( (strlen( extraText ) + 1 ) * sizeof( char ) ));
if ( extra )
{
memset( extra, 0x0, strlen( extraText ) + 1 );
strncpy( extra, extraText, strlen( extraText )); // +1 to dodge the starting quote
// Strip trailing spaces
int i = strlen( extra ) - 1;
while ( i >= 0 && // Check I before referencing i == -1 into the extra array!
extra[ i ] == ' ' )
{
extra[ i ] = '\0';
i--;
}
}
}
// If it's already there, then remove since we'll add it to the end instead
CHistoryItem *item = NULL;
for ( int i = m_CommandHistory.Count() - 1; i >= 0; i-- )
{
item = &m_CommandHistory[ i ];
if ( !item )
continue;
if ( stricmp( item->GetText(), command ) )
continue;
if ( extra || item->GetExtra() )
{
if ( !extra || !item->GetExtra() )
continue;
// stricmp so two commands with the same starting text get added
if ( stricmp( item->GetExtra(), extra ) )
continue;
}
m_CommandHistory.Remove( i );
}
item = &m_CommandHistory[ m_CommandHistory.AddToTail() ];
Assert( item );
item->SetText( command, extra );
m_iNextCompletion = 0;
RebuildCompletionList( m_szPartialText );
free( extra );
}
void CConsolePanel::GetConsoleText( char *pchText, size_t bufSize ) const
{
wchar_t *temp = new wchar_t[ bufSize ];
m_pHistory->GetText( 0, temp, bufSize * sizeof( wchar_t ) );
g_pVGuiLocalize->ConvertUnicodeToANSI( temp, pchText, bufSize );
delete[] temp;
}
//-----------------------------------------------------------------------------
// Purpose: writes out console to disk
//-----------------------------------------------------------------------------
void CConsolePanel::DumpConsoleTextToFile()
{
const int CONDUMP_FILES_MAX_NUM = 1000;
FileHandle_t handle;
bool found = false;
char szfile[ 512 ];
// we don't want to overwrite other condump.txt files
for ( int i = 0 ; i < CONDUMP_FILES_MAX_NUM ; ++i )
{
_snprintf( szfile, sizeof(szfile), "condump%03d.txt", i );
if ( !g_pFullFileSystem->FileExists(szfile) )
{
found = true;
break;
}
}
if ( !found )
{
Print( "Can't condump! Too many existing condump output files in the gamedir!\n" );
return;
}
handle = g_pFullFileSystem->Open( szfile, "wb" );
if ( handle != FILESYSTEM_INVALID_HANDLE )
{
int pos = 0;
while (1)
{
wchar_t buf[512];
m_pHistory->GetText(pos, buf, sizeof(buf));
pos += sizeof(buf) / sizeof(wchar_t);
// don't continue if none left
if (buf[0] == 0)
break;
// convert to ansi
char ansi[512];
g_pVGuiLocalize->ConvertUnicodeToANSI(buf, ansi, sizeof(ansi));
// write to disk
int len = strlen(ansi);
for (int i = 0; i < len; i++)
{
// preceed newlines with a return
if (ansi[i] == '\n')
{
char ret = '\r';
g_pFullFileSystem->Write( &ret, 1, handle );
}
g_pFullFileSystem->Write( ansi + i, 1, handle );
}
}
g_pFullFileSystem->Close( handle );
Print( "console dumped to " );
Print( szfile );
Print( "\n" );
}
else
{
Print( "Unable to condump to " );
Print( szfile );
Print( "\n" );
}
}
//-----------------------------------------------------------------------------
//
// Console dialog starts here
//
//-----------------------------------------------------------------------------
CConsoleDialog::CConsoleDialog( vgui::Panel *pParent, const char *pName, bool bStatusVersion ) :
BaseClass( pParent, pName )
{
// initialize dialog
SetVisible( false );
SetTitle( "#Console_Title", true );
m_pConsolePanel = new CConsolePanel( this, "ConsolePage", bStatusVersion );
m_pConsolePanel->AddActionSignalTarget( this );
}
void CConsoleDialog::OnScreenSizeChanged( int iOldWide, int iOldTall )
{
BaseClass::OnScreenSizeChanged( iOldWide, iOldTall );
int sx, sy;
surface()->GetScreenSize( sx, sy );
int w, h;
GetSize( w, h );
if ( w > sx || h > sy )
{
if ( w > sx )
{
w = sx;
}
if ( h > sy )
{
h = sy;
}
// Try and lower the size to match the screen bounds
SetSize( w, h );
}
}
//-----------------------------------------------------------------------------
// Purpose: brings dialog to the fore
//-----------------------------------------------------------------------------
void CConsoleDialog::PerformLayout()
{
BaseClass::PerformLayout();
int x, y, w, h;
GetClientArea( x, y, w, h );
m_pConsolePanel->SetBounds( x, y, w, h );
}
//-----------------------------------------------------------------------------
// Purpose: brings dialog to the fore
//-----------------------------------------------------------------------------
void CConsoleDialog::Activate()
{
BaseClass::Activate();
m_pConsolePanel->m_pEntry->RequestFocus();
}
//-----------------------------------------------------------------------------
// Hides the dialog
//-----------------------------------------------------------------------------
void CConsoleDialog::Hide()
{
OnClose();
m_pConsolePanel->Hide();
}
//-----------------------------------------------------------------------------
// Close just hides the dialog
//-----------------------------------------------------------------------------
void CConsoleDialog::Close()
{
Hide();
}
//-----------------------------------------------------------------------------
// Submits commands
//-----------------------------------------------------------------------------
void CConsoleDialog::OnCommandSubmitted( const char *pCommand )
{
PostActionSignal( new KeyValues( "CommandSubmitted", "command", pCommand ) );
}
//-----------------------------------------------------------------------------
// Chain to the page
//-----------------------------------------------------------------------------
void CConsoleDialog::Print( const char *pMessage )
{
m_pConsolePanel->Print( pMessage );
}
void CConsoleDialog::DPrint( const char *pMessage )
{
m_pConsolePanel->DPrint( pMessage );
}
void CConsoleDialog::ColorPrint( const Color& clr, const char *msg )
{
m_pConsolePanel->ColorPrint( clr, msg );
}
void CConsoleDialog::Clear()
{
m_pConsolePanel->Clear( );
}
void CConsoleDialog::DumpConsoleTextToFile()
{
m_pConsolePanel->DumpConsoleTextToFile( );
}
void CConsoleDialog::OnKeyCodePressed( vgui::KeyCode code )
{
if ( code == KEY_XBUTTON_B )
{
Hide();
}
else
{
BaseClass::OnKeyCodePressed(code);
}
} | 412 | 0.981722 | 1 | 0.981722 | game-dev | MEDIA | 0.659847 | game-dev | 0.934306 | 1 | 0.934306 |
magemonkeystudio/fabled | 2,669 | src/main/java/studio/magemonkey/fabled/dynamic/mechanic/value/ValueAddMechanic.java | /**
* Fabled
* studio.magemonkey.fabled.dynamic.mechanic.value.ValueAddMechanic
* <p>
* The MIT License (MIT)
* <p>
* Copyright (c) 2024 MageMonkeyStudio
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package studio.magemonkey.fabled.dynamic.mechanic.value;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.LivingEntity;
import studio.magemonkey.fabled.Fabled;
import studio.magemonkey.fabled.api.CastData;
import studio.magemonkey.fabled.dynamic.DynamicSkill;
import studio.magemonkey.fabled.dynamic.mechanic.MechanicComponent;
import java.util.List;
/**
* Adds to a cast data value
*/
@Deprecated
public class ValueAddMechanic extends MechanicComponent {
private static final String KEY = "key";
private static final String AMOUNT = "amount";
private static final String SAVE = "save";
@Override
public String getKey() {
return "value add";
}
@Override
public boolean execute(LivingEntity caster, int level, List<LivingEntity> targets, boolean force) {
if (targets.isEmpty() || !settings.has(KEY)) {
return false;
}
String key = settings.getString(KEY);
double amount = parseValues(caster, AMOUNT, level, 1) * targets.size();
CastData data = DynamicSkill.getCastData(caster);
if (!data.contains(key)) {
data.put(key, amount);
} else {
data.put(key, amount + data.getDouble(key));
}
if (settings.getBool(SAVE, false))
Fabled.getData((OfflinePlayer) caster).setPersistentData(key, data.getRaw(key));
return true;
}
}
| 412 | 0.840031 | 1 | 0.840031 | game-dev | MEDIA | 0.702529 | game-dev | 0.676938 | 1 | 0.676938 |
Wonder-Technology/Wonder-Editor | 1,645 | lib/es6_global/src/core/composable_component/mainEditor/composable_component/inspector/composable_component/sceneTree_Inspector/composable_component/light/composable_component/point_light/ui/eventHandler/PointLightCloseColorPickEventHandler.js |
import * as Color$WonderEditor from "../../../../../../../../../../../../external/Color.js";
import * as EventHandler$WonderEditor from "../../../../../../../../../../../../ui/eventHandler/EventHandler.js";
import * as EmptyEventHandler$WonderEditor from "../../../../../../../../../../../../ui/eventHandler/EmptyEventHandler.js";
import * as StateEngineService$WonderEditor from "../../../../../../../../../../../../../service/state/engine/state/StateEngineService.js";
import * as PointLightEngineService$WonderEditor from "../../../../../../../../../../../../../service/state/engine/PointLightEngineService.js";
var handleSelfLogic = EmptyEventHandler$WonderEditor.EmptyEventHandler[0];
var setUndoValueToCopiedEngineStateForPromise = EmptyEventHandler$WonderEditor.EmptyEventHandler[2];
function setUndoValueToCopiedEngineState(param, lightComponent, value) {
return PointLightEngineService$WonderEditor.setPointLightColor(Color$WonderEditor.convert16HexToRGBArr(value), lightComponent, StateEngineService$WonderEditor.deepCopyForRestore(StateEngineService$WonderEditor.unsafeGetState(/* () */0)));
}
var CustomEventHandler = /* module */[
/* handleSelfLogic */handleSelfLogic,
/* setUndoValueToCopiedEngineStateForPromise */setUndoValueToCopiedEngineStateForPromise,
/* setUndoValueToCopiedEngineState */setUndoValueToCopiedEngineState
];
var MakeEventHandler = EventHandler$WonderEditor.MakeEventHandler([
handleSelfLogic,
setUndoValueToCopiedEngineState,
setUndoValueToCopiedEngineStateForPromise
]);
export {
CustomEventHandler ,
MakeEventHandler ,
}
/* MakeEventHandler Not a pure module */
| 412 | 0.574003 | 1 | 0.574003 | game-dev | MEDIA | 0.765296 | game-dev | 0.695893 | 1 | 0.695893 |
shaovie/gserver | 29,223 | world/src/fight/use_skill.cpp | #include "char_obj.h"
#include "sys_log.h"
#include "skill_info.h"
#include "skill_config.h"
#include "error.h"
#include "fighter_mgr.h"
#include "buff_module.h"
#include "monster_mgr.h"
#include "spawn_monster.h"
#include "scene_config.h"
#include "scene_mgr.h"
#include "mblock_pool.h"
#include "monster_obj.h"
#include "effect_obj.h"
#include "effect_obj_mgr.h"
// Lib header
#include "macros.h"
static ilog_obj *s_log = sys_log::instance()->get_ilog("fight");
static ilog_obj *e_log = err_log::instance()->get_ilog("fight");
DIR_STEP(s_dir_step);
int char_obj::can_use_skill(const skill_detail *sd,
const skill_info *si,
const int block_radius,
const time_value &now,
const coord_t &target_pos)
{
if (this->has_buff(BF_SK_DING_SHEN))
{
if (this->career() == CAREER_LI_LIANG)
{
if (si->cid_ != LI_LIANG_COMMON_SKILL_1
&& si->cid_ != LI_LIANG_COMMON_SKILL_2
&& si->cid_ != LI_LIANG_COMMON_SKILL_3)
return ERR_CAN_NOT_USE_SKILL;
}else if (this->career() == CAREER_MIN_JIE)
{
if (si->cid_ != MIN_JIE_COMMON_SKILL_1
&& si->cid_ != MIN_JIE_COMMON_SKILL_2
&& si->cid_ != MIN_JIE_COMMON_SKILL_3
&& si->cid_ != MIN_JIE_BIAN_SHEN_COMMON_SKILL)
return ERR_CAN_NOT_USE_SKILL;
}else if (this->career() == CAREER_ZHONG_LI)
{
if (si->cid_ != ZHI_LI_COMMON_SKILL_1
&& si->cid_ != ZHI_LI_COMMON_SKILL_2
&& si->cid_ != ZHI_LI_COMMON_SKILL_3)
return ERR_CAN_NOT_USE_SKILL;
}
}
if (this->has_buff(BF_SK_XUAN_YUN)
|| this->has_buff(BF_SK_XUAN_FENG)
|| this->has_buff(BF_SK_SHANDIAN_FENGBAO))
return ERR_CAN_NOT_USE_SKILL;
if (sd->distance_ > 0
&& target_pos.x_ != 0
&& target_pos.y_ != 0
&& util::is_out_of_distance(this->coord_x_,
this->coord_y_,
target_pos.x_,
target_pos.y_,
sd->distance_ + this->block_radius_ + block_radius))
return ERR_SKILL_OUT_OF_DISTANCE;
if (sd->cd_ > 0)
{
if ((now - time_value(si->use_time_, si->use_usec_)).msec() < (long)sd->cd_)
return ERR_SKILL_CD_LIMIT;
}
return 0;
}
int char_obj::do_use_skill(const int target_id,
const time_value &now,
const short target_x,
const short target_y,
const int skill_cid,
const int skill_hurt_delay,
const skill_detail *sd)
{
int ret = this->dispatch_skill(target_id,
now,
target_x,
target_y,
skill_cid,
skill_hurt_delay,
sd);
if (ret == 0)
this->last_use_skill_time_ = now;
return ret;
}
int char_obj::dispatch_skill(const int target_id,
const time_value &now,
const short target_x,
const short target_y,
const int skill_cid,
const int skill_hurt_delay,
const skill_detail *sd)
{
int ret = 0;
switch (skill_cid)
{
case 32000001: // 怪物 普通攻击
case 32000002: // 怪物 普通攻击
case 32000003: // 怪物 普通攻击
case 32000004: // 怪物 普通攻击
case 32000005: // 怪物 普通攻击
case 32000006: // 怪物 普通攻击
case 32000007: // 怪物 普通攻击
case 32000008: // 怪物 普通攻击
case 32000009: // 怪物 普通攻击
case 32000010: // 怪物 普通攻击
case 32000011: // 怪物 怪物攻击
case 32000012: // 怪物 怪物攻击
case 32000013: // 怪物 普通攻击
case 32000014: // 怪物 普通攻击
// 造成百分比伤害,附加固定额外伤害值,并附加BUF
ret = this->sk_percent_hurt_and_add_fixed_hurt(target_id,
now,
skill_cid,
skill_hurt_delay,
sd,
target_x,
target_y);
break;
case 31110001: // 力量型 普通攻击1
case 31110002: // 力量型 普通攻击2
case 31110003: // 力量型 普通攻击3
case 31210001: // 敏捷型 普通攻击1
case 31210002: // 敏捷型 普通攻击2
case 31210003: // 敏捷型 普通攻击3
case 31310001: // 智力型 普通攻击1
case 31310002: // 智力型 普通攻击2
case 31310003: // 智力型 普通技能3
// 对一定范围半径内的所有目标造成百分比伤害,附加固定额外伤害值, 并附加BUF
ret = this->sk_area_percent_hurt_and_add_fixed_hurt(now,
skill_cid,
skill_hurt_delay,
sd,
target_id,
target_x,
target_y,
true);
break;
case 31110011: // 力量型 战斗怒吼
case 32100005: // 怪物 死亡脉冲
case 32100009: // 怪物 冰霜震击
// 对一定范围半径内的所有目标造成百分比伤害,附加固定额外伤害值, 并附加BUF
ret = this->sk_area_percent_hurt_and_add_fixed_hurt(now,
skill_cid,
skill_hurt_delay,
sd,
0,
this->coord_x_,
this->coord_y_,
false);
break;
case 31210004: // 敏捷型 变身普通攻击
// 对一定范围半径内的所有目标造成百分比伤害,附加固定额外伤害值, 并附加BUF
ret = this->sk_area_percent_hurt_and_add_fixed_hurt(now,
skill_cid,
skill_hurt_delay,
sd,
target_id,
target_x,
target_y,
false);
break;
case 31110013: // 力量型 剑刃风暴
case 31210013: // 敏捷型 烈焰火环
case 31310021: // 智力型 寒冰护体
case 32100004: // 怪物 蝗虫群
case 32100011: // 怪物 狂暴
case 32100012: // 怪物 铁甲
case 32100013: // 怪物 回春
case 32100014: // 怪物 反弹
ret = this->sk_insert_buff_to_self(now, skill_cid, sd);
break;
case 32100001: // 怪物 击晕
case 32100002: // 怪物 减速
ret = this->sk_insert_buff_to_target(now, skill_cid, sd, target_id);
break;
case 31310012: // 智力型 冰锥术
case 31210011: // 敏捷型 破空之刃
ret = this->sk_1_4_view_area_percent_hurt_and_add_fixed_hurt(now,
skill_cid,
skill_hurt_delay,
sd);
break;
case 31110012: // 力量型 战神冲锋
case 31210012: // 敏捷型 疾风猎刃
case 31310011: // 智力型 龙破斩
case 32100017: // 怪物 混沌陨石
case 32100003: // 怪物 地刺
case 32100006: // 怪物 腐蚀蜂群
case 32100008: // 怪物 超声冲击波
// 对直线范围内的所有目标造成百分比伤害,附加固定额外伤害值
ret = this->sk_line_area_percent_hurt_and_add_fixed_hurt(now,
skill_cid,
skill_hurt_delay,
sd);
break;
case 31110021: // 力量型 镜像分身
ret = this->sk_jing_xiang_fen_shen(skill_cid, skill_hurt_delay, sd);
break;
case 31210021: // 敏捷型 恶魔变身
ret = this->sk_area_percent_hurt_and_add_fixed_hurt_and_insert_buff_to_self(now,
skill_cid,
skill_hurt_delay,
sd,
this->coord_x_,
this->coord_y_);
break;
case 31310013: // 智力型 暴风雪
case 32100007: // 怪物 闪电风暴
ret = this->sk_place_a_last_hurt_effect_and_insert_buf_to_self(now, skill_cid, sd);
break;
case 32100019: // 怪物 爆发
ret = this->sk_area_total_hp_percent_hurt(now,
skill_cid,
skill_hurt_delay,
sd,
this->coord_x_,
this->coord_y_);
break;
default:
e_log->wning("unknwon skill %d in %s", skill_cid, __func__);
break;
}
return ret;
}
int char_obj::sk_percent_hurt_and_add_fixed_hurt(const int target_id,
const time_value &now,
const int skill_cid,
const int skill_hurt_delay,
const skill_detail *sd,
const short target_x,
const short target_y)
{
if (target_id == 0) // 没有目标也可以释放
{
this->broadcast_use_skill(skill_cid, sd->cur_lvl_, target_id, target_x, target_y);
return 0;
}
if (this->id_ == target_id) return ERR_SKILL_TARGET_ILLEGAL;
char_obj *target = fighter_mgr::instance()->find(target_id);
if (target == NULL) return ERR_SKILL_TARGET_NOT_EXIST;
int ret = this->is_proper_attack_target(target);
if (ret != 0) return ret;
int real_hurt = 0;
if (target->can_be_hurt(this) == 0)
{
int tip = 0;
real_hurt = this->do_calc_hurt(tip, target);
if (tip != SK_TIP_SHAN_BI && tip != SK_TIP_HU_DUN)
{
if (sd->hurt_percent_ > 0)
real_hurt = real_hurt * sd->hurt_percent_ / 100;
real_hurt += sd->add_fixed_hurt_;
target->do_be_hurt(this, now, real_hurt, sd->hate_coe_, skill_cid, skill_hurt_delay);
this->sk_do_insert_buff(target,
skill_cid,
real_hurt,
now,
sd->buff_info_,
SK_BUFF_TARGET_SINGLE,
0);
}
target->broadcast_be_hurt_effect(skill_cid, real_hurt, tip, this->id_);
}
target->do_ji_tui(this, now, sd->back_dis_, skill_cid);
this->broadcast_use_skill(skill_cid, sd->cur_lvl_, target_id, target->coord_x(), target->coord_y());
target->on_be_attacked(this);
this->on_attack_somebody(target_id, target->unit_type(), now, skill_cid, real_hurt);
return 0;
}
int char_obj::sk_area_percent_hurt_and_add_fixed_hurt(const time_value &now,
const int skill_cid,
const int skill_hurt_delay,
const skill_detail *sd,
const int target_id,
const short target_x,
const short target_y,
const bool with_tian_fu)
{
if (target_x <= 0 && target_y <= 0)
return ERR_SKILL_TARGET_ILLEGAL;
int target_set[64] = {0}; // should be OPTIMIZED
int ret = scene_mgr::instance()->get_scene_unit_list(this->scene_id_,
sizeof(target_set)/sizeof(target_set[0]),
this->attack_target(),
OBJ_DEAD,
target_x,
target_y,
sd->param_1_,
target_set);
int sum_hurt = 0;
int attacked_target_id = target_id;
this->sk_do_area_percent_hurt_and_add_fixed_hurt(now,
ret,
target_set,
skill_cid,
skill_hurt_delay,
sd,
with_tian_fu,
attacked_target_id,
sum_hurt);
this->broadcast_use_skill(skill_cid, sd->cur_lvl_, 0, target_x, target_y);
this->on_attack_somebody(attacked_target_id, 0, now, skill_cid, sum_hurt);
return 0;
}
void char_obj::sk_do_area_percent_hurt_and_add_fixed_hurt(const time_value &now,
const int target_cnt,
const int *target_set,
const int skill_cid,
const int skill_hurt_delay,
const skill_detail *sd,
const bool with_tian_fu,
int &attacked_target_id,
int &sum_hurt)
{
for (int i = 0; i < target_cnt; ++i)
{
if (this->id_ == target_set[i]) continue;
char_obj *target = fighter_mgr::instance()->find(target_set[i]);
if (target == NULL
|| this->is_proper_attack_target(target) != 0)
continue;
if (target->can_be_hurt(this) == 0)
{
int tip = 0;
int real_hurt = this->do_calc_hurt(tip, target);
if (tip != SK_TIP_SHAN_BI && tip != SK_TIP_HU_DUN)
{
if (sd->hurt_percent_ > 0)
real_hurt = real_hurt * sd->hurt_percent_ / 100;
real_hurt += sd->add_fixed_hurt_;
sum_hurt += real_hurt;
target->do_be_hurt(this, now, real_hurt, sd->hate_coe_, skill_cid, skill_hurt_delay);
this->sk_do_insert_buff(target,
skill_cid,
real_hurt,
now,
sd->buff_info_,
SK_BUFF_TARGET_AREA,
0);
if (with_tian_fu)
this->do_tianfu_effect(target, now);
}
if (attacked_target_id == 0)
attacked_target_id = target_set[i];
target->broadcast_be_hurt_effect(skill_cid, real_hurt, tip, this->id_);
}
target->do_ji_tui(this, now, sd->back_dis_, skill_cid);
target->on_be_attacked(this);
}
}
int char_obj::sk_insert_buff_to_self(const time_value &now,
const int skill_cid,
const skill_detail *sd)
{
this->sk_do_insert_buff(this,
skill_cid,
0,
now,
sd->buff_info_,
SK_BUFF_TARGET_SELF,
0);
this->broadcast_use_skill(skill_cid, sd->cur_lvl_, 0, 0, 0);
return 0;
}
int char_obj::sk_insert_buff_to_target(const time_value &now,
const int skill_cid,
const skill_detail *sd,
const int target_id)
{
if (this->id_ == target_id) return ERR_SKILL_TARGET_ILLEGAL;
char_obj *target = fighter_mgr::instance()->find(target_id);
if (target == NULL) return ERR_SKILL_TARGET_NOT_EXIST;
int ret = this->is_proper_attack_target(target);
if (ret != 0) return ret;
this->sk_do_insert_buff(target,
skill_cid,
0,
now,
sd->buff_info_,
SK_BUFF_TARGET_SINGLE,
0);
this->broadcast_use_skill(skill_cid, sd->cur_lvl_, 0, 0, 0);
target->on_be_attacked(this);
this->on_attack_somebody(target_id, target->unit_type(), now, skill_cid, 0);
return 0;
}
int char_obj::sk_jing_xiang_fen_shen(const int skill_cid,
const int skill_hurt_delay,
const skill_detail *sd)
{
if (sd->param_1_ > 3) return ERR_CONFIG_NOT_EXIST;
coord_t pos_list[3];
const int dist = 3;
if (sd->param_1_ == 1)
{
pos_list[0].x_ = this->coord_x_ - dist;
pos_list[0].y_ = this->coord_y_;
}else if (sd->param_1_ == 2)
{
pos_list[0].x_ = this->coord_x_ - dist;
pos_list[0].y_ = this->coord_y_;
pos_list[1].x_ = this->coord_x_ + dist;
pos_list[1].y_ = this->coord_y_;
}else if (sd->param_1_ == 3)
{
pos_list[0].x_ = this->coord_x_ - dist;
pos_list[0].y_ = this->coord_y_;
pos_list[1].x_ = this->coord_x_ + dist;
pos_list[1].y_ = this->coord_y_;
pos_list[2].x_ = this->coord_x_;
pos_list[2].y_ = this->coord_y_ + dist;
}
for (int i = 0; i < sd->param_1_; ++i)
{
if (!scene_config::instance()->can_move(this->scene_cid_,
pos_list[i].x_,
pos_list[i].y_))
{
pos_list[i] = scene_config::instance()->get_random_pos(this->scene_cid_,
this->coord_x_,
this->coord_y_,
dist + 1);
}
int mst_id = spawn_monster::spawn_one(sd->param_3_,
skill_hurt_delay,
this->scene_id_,
this->scene_cid_,
this->dir_,
pos_list[i].x_,
pos_list[i].y_);
if (mst_id != -1)
{
monster_obj *mo = monster_mgr::instance()->find(mst_id);
if (mo != NULL)
{
mblock *mb = mblock_pool::instance()->alloc(sizeof(int)*12);
*mb << this->id()
<< this->pk_mode()
<< this->team_id()
<< this->guild_id()
<< this->lvl()
<< this->total_hp()
<< this->obj_attr_.gong_ji() * sd->param_2_ / 100
<< this->obj_attr_.fang_yu()
<< this->obj_attr_.ming_zhong()
<< this->obj_attr_.shan_bi()
<< this->obj_attr_.bao_ji()
<< this->obj_attr_.kang_bao()
<< this->obj_attr_.shang_mian();
mo->post_aev(AEV_ZHUZAI_FEN_SHEN_INFO, mb);
mblock *mb2 = mblock_pool::instance()->alloc(sizeof(int));
*mb2 << mst_id;
this->post_aev(AEV_ZHUZAI_FEN_SHEN_INFO, mb2);
}
}
}
this->broadcast_use_skill(skill_cid, sd->cur_lvl_, 0, 0, 0);
return 0;
}
int char_obj::sk_line_area_percent_hurt_and_add_fixed_hurt(const time_value &now,
const int skill_cid,
const int skill_hurt_delay,
const skill_detail *sd)
{
short target_x = this->coord_x_;
short target_y = this->coord_y_;
for (int i = 0; i < sd->param_1_; ++i)
{
target_x += s_dir_step[(int)this->dir_][0];
target_y += s_dir_step[(int)this->dir_][1];
if (!scene_config::instance()->can_move(this->scene_cid_,
target_x,
target_y))
break;
}
int target_set[64] = {0}; // should be OPTIMIZED
int ret = scene_mgr::instance()->get_line_area_obj_set(this->scene_id_,
sizeof(target_set)/sizeof(target_set[0]),
this->attack_target(),
OBJ_DEAD,
this->coord_x_,
this->coord_y_,
this->dir_,
target_x,
target_y,
sd->param_2_,
target_set);
int sum_hurt = 0;
int attacked_target_id = 0;
this->sk_do_area_percent_hurt_and_add_fixed_hurt(now,
ret,
target_set,
skill_cid,
skill_hurt_delay,
sd,
false,
attacked_target_id,
sum_hurt);
this->broadcast_use_skill(skill_cid, sd->cur_lvl_, 0, target_x, target_y);
this->on_attack_somebody(attacked_target_id, 0, now, skill_cid, sum_hurt);
return 0;
}
int char_obj::sk_1_4_view_area_percent_hurt_and_add_fixed_hurt(const time_value &now,
const int skill_cid,
const int skill_hurt_delay,
const skill_detail *sd)
{
int target_set[64] = {0}; // should be OPTIMIZED
int ret = scene_mgr::instance()->get_1_4_view_obj_set(this->scene_id_,
sizeof(target_set)/sizeof(target_set[0]),
this->attack_target(),
OBJ_DEAD,
this->coord_x_,
this->coord_y_,
this->dir_,
sd->param_1_,
target_set);
int sum_hurt = 0;
int attacked_target_id = 0;
this->sk_do_area_percent_hurt_and_add_fixed_hurt(now,
ret,
target_set,
skill_cid,
skill_hurt_delay,
sd,
false,
attacked_target_id,
sum_hurt);
this->broadcast_use_skill(skill_cid, sd->cur_lvl_, 0, 0, 0);
this->on_attack_somebody(attacked_target_id, 0, now, skill_cid, sum_hurt);
return 0;
}
int char_obj::sk_area_percent_hurt_and_add_fixed_hurt_and_insert_buff_to_self(const time_value &now,
const int skill_cid,
const int skill_hurt_delay,
const skill_detail *sd,
const short target_x,
const short target_y)
{
int target_set[64] = {0}; // should be OPTIMIZED
int ret = scene_mgr::instance()->get_scene_unit_list(this->scene_id_,
sizeof(target_set)/sizeof(target_set[0]),
this->attack_target(),
OBJ_DEAD,
target_x,
target_y,
sd->param_1_,
target_set);
int sum_hurt = 0;
int attacked_target_id = 0;
this->sk_do_area_percent_hurt_and_add_fixed_hurt(now,
ret,
target_set,
skill_cid,
skill_hurt_delay,
sd,
false,
attacked_target_id,
sum_hurt);
this->sk_do_insert_buff(this,
skill_cid,
0,
now,
sd->buff_info_,
SK_BUFF_TARGET_SELF,
0);
if (skill_cid == 31210021) // 恶魔变身
buff_module::do_remove_all_debuff(this);
this->broadcast_use_skill(skill_cid, sd->cur_lvl_, 0, target_x, target_y);
this->on_attack_somebody(attacked_target_id, 0, now, skill_cid, sum_hurt);
return 0;
}
int char_obj::sk_place_a_last_hurt_effect_and_insert_buf_to_self(const time_value &now,
const int skill_cid,
const skill_detail *sd)
{
sk_last_hurt_effect_obj *seo = sk_last_hurt_effect_obj_alloctor::instance()->alloc();
seo->set(now,
this->id(),
skill_cid,
sd->cur_lvl_,
this->scene_cid_,
this->scene_id_,
this->coord_x_,
this->coord_y_,
sd->param_3_);
if (seo->do_enter_scene() != 0)
{
seo->release();
return 0;
}
effect_obj_mgr::instance()->insert(seo);
this->sk_do_insert_buff(this,
skill_cid,
0,
now,
sd->buff_info_,
SK_BUFF_TARGET_SELF,
0);
this->broadcast_use_skill(skill_cid, sd->cur_lvl_, 0, this->coord_x_, this->coord_y_);
return 0;
}
int char_obj::sk_area_total_hp_percent_hurt(const time_value &now,
const int skill_cid,
const int skill_hurt_delay,
const skill_detail *sd,
const short target_x,
const short target_y)
{
int target_set[64] = {0}; // should be OPTIMIZED
int ret = scene_mgr::instance()->get_scene_unit_list(this->scene_id_,
sizeof(target_set)/sizeof(target_set[0]),
this->attack_target(),
OBJ_DEAD,
target_x,
target_y,
sd->param_1_,
target_set);
int sum_hurt = 0;
int attacked_target_id = 0;
for (int i = 0; i < ret; ++i)
{
if (this->id_ == target_set[i]) continue;
char_obj *target = fighter_mgr::instance()->find(target_set[i]);
if (target == NULL
|| this->is_proper_attack_target(target) != 0)
continue;
if (target->can_be_hurt(this) == 0)
{
int tip = 0;
int real_hurt = target->total_hp() * sd->param_2_ / 100;
target->do_be_hurt(this, now, real_hurt, sd->hate_coe_, skill_cid, skill_hurt_delay);
if (attacked_target_id == 0)
attacked_target_id = target_set[i];
target->broadcast_be_hurt_effect(skill_cid, real_hurt, tip, this->id_);
}
target->do_ji_tui(this, now, sd->back_dis_, skill_cid);
target->on_be_attacked(this);
}
this->broadcast_use_skill(skill_cid, sd->cur_lvl_, 0, target_x, target_y);
this->on_attack_somebody(attacked_target_id, 0, now, skill_cid, sum_hurt);
return 0;
}
| 412 | 0.916281 | 1 | 0.916281 | game-dev | MEDIA | 0.340081 | game-dev | 0.911707 | 1 | 0.911707 |
gree/pure2d | 8,552 | pure2D/src/main/java/com/funzio/pure2D/effects/trails/MotionTrailShape.java | /*******************************************************************************
* Copyright (C) 2012-2014 GREE, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
/**
*
*/
package com.funzio.pure2D.effects.trails;
import android.graphics.PointF;
import com.funzio.pure2D.Manipulatable;
import com.funzio.pure2D.Scene;
import com.funzio.pure2D.shapes.Polyline;
import java.util.Arrays;
/**
* @author long
*/
public class MotionTrailShape extends Polyline implements MotionTrail {
public static final int DEFAULT_NUM_POINTS = 10;
public static final float DEFAULT_MOTION_EASING = 0.5f;
protected int mNumPoints = DEFAULT_NUM_POINTS;
protected float mMotionEasingX = DEFAULT_MOTION_EASING;
protected float mMotionEasingY = DEFAULT_MOTION_EASING;
protected float mMinLength = 1;
protected float mSegmentLength = 0;
protected Manipulatable mTarget;
protected PointF mTargetOffset = new PointF(0, 0);
protected Object mData;
private boolean mFollowingHead = false;
public MotionTrailShape() {
this(null);
}
public MotionTrailShape(final Manipulatable target) {
super();
// set default num points
setNumPoints(mNumPoints);
if (target != null) {
setTarget(target);
}
}
@Override
public void reset(final Object... params) {
mMotionEasingX = mMotionEasingY = DEFAULT_MOTION_EASING;
setPointsAt(0, 0);
}
@Override
public Object getData() {
return mData;
}
@Override
public void setData(final Object data) {
mData = data;
}
@Override
public void setPosition(final float x, final float y) {
if (mNumPoints > 0) {
if (!mPoints[0].equals(x, y)) {
mPoints[0].set(x, y);
// flag
mFollowingHead = true;
}
}
}
/**
* Need to also override this since we override setPosition()
* @return
*/
@Override
public PointF getPosition() {
return mNumPoints > 0 ? mPoints[0] : null;
}
@Override
public void move(final float dx, final float dy) {
if (mNumPoints > 0) {
mPoints[0].offset(dx, dy);
// flag
mFollowingHead = true;
}
}
@Override
public boolean update(final int deltaTime) {
if (mNumPoints > 0) {
if (!mFollowingHead && mTarget != null) {
final PointF p1 = mTarget.getPosition();
final float dx = p1.x - (mPoints[0].x - mTargetOffset.x);
final float dy = p1.y - (mPoints[0].y - mTargetOffset.y);
if (Math.abs(dx) >= 1 || Math.abs(dy) >= 1) {
// flag
mFollowingHead = true;
}
}
if (mFollowingHead) {
// calculate time loop for consistency with different framerate
final int loop = deltaTime / Scene.DEFAULT_MSPF;
PointF p1, p2;
float dx, dy;
for (int n = 0; n < loop; n++) {
for (int i = mNumPoints - 1; i > 0; i--) {
p1 = mPoints[i];
p2 = mPoints[i - 1];
dx = p2.x - p1.x;
dy = p2.y - p1.y;
if (mMinLength <= 1 || (dx * dx + dy * dy) > (mSegmentLength * mSegmentLength)) {
// move toward the leading point
p1.x += dx * mMotionEasingX;
p1.y += dy * mMotionEasingY;
// show vertex
setColorMultipliersAt(i, 1);
} else {
// hide vertex
setColorMultipliersAt(i, 0);
}
}
}
// follow the target
if (mTarget != null) {
// set the head
final PointF pos = mTarget.getPosition();
mPoints[0].set(pos.x + mTargetOffset.x, pos.y + mTargetOffset.y);
}
// apply
setPoints(mPoints);
}
}
return super.update(deltaTime);
}
@Override
protected void validateVertices() {
super.validateVertices();
if (mTotalLength <= mMinLength) {
// flag done
mFollowingHead = false;
// hide all vertices
Arrays.fill(mColorMultipliers, 0);
}
}
public int getNumPoints() {
return mNumPoints;
}
public void setNumPoints(final int numPoints) {
mNumPointsUsed = mNumPoints = numPoints;
if (numPoints < 2) {
mPoints = null;
return;
}
if (mPoints == null || mPoints.length != numPoints) {
mPoints = new PointF[numPoints];
final PointF pos = (mTarget != null) ? mTarget.getPosition() : null;
for (int i = 0; i < numPoints; i++) {
mPoints[i] = new PointF();
if (pos != null) {
mPoints[i].set(pos.x + mTargetOffset.x, pos.y + mTargetOffset.y);
}
}
// find the length
mSegmentLength = mMinLength / (mNumPoints < 2 ? 1 : mNumPoints - 1);
// optimize
mTotalLength = 0;
mFollowingHead = false;
}
// re-count, each point has 2 vertices
allocateVertices(numPoints * 2, VERTEX_POINTER_SIZE);
}
public Manipulatable getTarget() {
return mTarget;
}
public void setTarget(final Manipulatable target) {
mTarget = target;
if (mTarget != null) {
final PointF pos = mTarget.getPosition();
for (int i = 0; i < mNumPoints; i++) {
mPoints[i].set(pos.x + mTargetOffset.x, pos.y + mTargetOffset.y);
}
// apply
setPoints(mPoints);
}
}
public void setPointsAt(final float x, final float y) {
for (int i = 0; i < mNumPoints; i++) {
mPoints[i].set(x, y);
}
// apply
setPoints(mPoints);
}
public void setPointsAt(final PointF p) {
for (int i = 0; i < mNumPoints; i++) {
mPoints[i].set(p.x, p.y);
}
// apply
setPoints(mPoints);
}
public float getMinLength() {
return mMinLength;
}
public void setMinLength(final float totalLength) {
mMinLength = totalLength;
mSegmentLength = mMinLength / (mNumPoints < 2 ? 1 : mNumPoints - 1);
}
public float getMotionEasingX() {
return mMotionEasingX;
}
public float getMotionEasingY() {
return mMotionEasingY;
}
/**
* @param easing, must be from 0 to 1
*/
public void setMotionEasing(final float easing) {
mMotionEasingX = mMotionEasingY = easing;
}
public void setMotionEasing(final float easingX, final float easingY) {
mMotionEasingX = easingX;
mMotionEasingY = easingY;
}
public PointF getTargetOffset() {
return mTargetOffset;
}
public void setTargetOffset(final float offsetX, final float offsetY) {
mTargetOffset.set(offsetX, offsetY);
}
}
| 412 | 0.915546 | 1 | 0.915546 | game-dev | MEDIA | 0.58039 | game-dev,graphics-rendering | 0.972857 | 1 | 0.972857 |
airwindows/airwindows | 11,073 | plugins/WinVST/Infrasonic/InfrasonicProc.cpp | /* ========================================
* Infrasonic - Infrasonic.h
* Copyright (c) 2016 airwindows, Airwindows uses the MIT license
* ======================================== */
#ifndef __Infrasonic_H
#include "Infrasonic.h"
#endif
void Infrasonic::processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames)
{
float* in1 = inputs[0];
float* in2 = inputs[1];
float* out1 = outputs[0];
float* out2 = outputs[1];
biquadE[0] = biquadD[0] = biquadC[0] = biquadB[0] = biquadA[0] = 20.0 / getSampleRate();
biquadA[1] = 0.50623256;
biquadB[1] = 0.56116312;
biquadC[1] = 0.70710678;
biquadD[1] = 1.10134463;
biquadE[1] = 3.19622661; //tenth order Butterworth out of five biquads
double K = tan(M_PI * biquadA[0]); //lowpass
double norm = 1.0 / (1.0 + K / biquadA[1] + K * K);
biquadA[2] = norm;
biquadA[3] = -2.0 * biquadA[2];
biquadA[4] = biquadA[2];
biquadA[5] = 2.0 * (K * K - 1.0) * norm;
biquadA[6] = (1.0 - K / biquadA[1] + K * K) * norm;
K = tan(M_PI * biquadA[0]);
norm = 1.0 / (1.0 + K / biquadB[1] + K * K);
biquadB[2] = norm;
biquadB[3] = -2.0 * biquadB[2];
biquadB[4] = biquadB[2];
biquadB[5] = 2.0 * (K * K - 1.0) * norm;
biquadB[6] = (1.0 - K / biquadB[1] + K * K) * norm;
K = tan(M_PI * biquadC[0]);
norm = 1.0 / (1.0 + K / biquadC[1] + K * K);
biquadC[2] = norm;
biquadC[3] = -2.0 * biquadC[2];
biquadC[4] = biquadC[2];
biquadC[5] = 2.0 * (K * K - 1.0) * norm;
biquadC[6] = (1.0 - K / biquadC[1] + K * K) * norm;
K = tan(M_PI * biquadD[0]);
norm = 1.0 / (1.0 + K / biquadD[1] + K * K);
biquadD[2] = norm;
biquadD[3] = -2.0 * biquadD[2];
biquadD[4] = biquadD[2];
biquadD[5] = 2.0 * (K * K - 1.0) * norm;
biquadD[6] = (1.0 - K / biquadD[1] + K * K) * norm;
K = tan(M_PI * biquadE[0]);
norm = 1.0 / (1.0 + K / biquadE[1] + K * K);
biquadE[2] = norm;
biquadE[3] = -2.0 * biquadE[2];
biquadE[4] = biquadE[2];
biquadE[5] = 2.0 * (K * K - 1.0) * norm;
biquadE[6] = (1.0 - K / biquadE[1] + K * K) * norm;
while (--sampleFrames >= 0)
{
double inputSampleL = *in1;
double inputSampleR = *in2;
if (fabs(inputSampleL)<1.18e-23) inputSampleL = fpdL * 1.18e-17;
if (fabs(inputSampleR)<1.18e-23) inputSampleR = fpdR * 1.18e-17;
double outSampleL = biquadA[2]*inputSampleL+biquadA[3]*biquadA[7]+biquadA[4]*biquadA[8]-biquadA[5]*biquadA[9]-biquadA[6]*biquadA[10];
biquadA[8] = biquadA[7]; biquadA[7] = inputSampleL; inputSampleL = outSampleL; biquadA[10] = biquadA[9]; biquadA[9] = inputSampleL; //DF1 left
outSampleL = biquadB[2]*inputSampleL+biquadB[3]*biquadB[7]+biquadB[4]*biquadB[8]-biquadB[5]*biquadB[9]-biquadB[6]*biquadB[10];
biquadB[8] = biquadB[7]; biquadB[7] = inputSampleL; inputSampleL = outSampleL; biquadB[10] = biquadB[9]; biquadB[9] = inputSampleL; //DF1 left
outSampleL = biquadC[2]*inputSampleL+biquadC[3]*biquadC[7]+biquadC[4]*biquadC[8]-biquadC[5]*biquadC[9]-biquadC[6]*biquadC[10];
biquadC[8] = biquadC[7]; biquadC[7] = inputSampleL; inputSampleL = outSampleL; biquadC[10] = biquadC[9]; biquadC[9] = inputSampleL; //DF1 left
outSampleL = biquadD[2]*inputSampleL+biquadD[3]*biquadD[7]+biquadD[4]*biquadD[8]-biquadD[5]*biquadD[9]-biquadD[6]*biquadD[10];
biquadD[8] = biquadD[7]; biquadD[7] = inputSampleL; inputSampleL = outSampleL; biquadD[10] = biquadD[9]; biquadD[9] = inputSampleL; //DF1 left
outSampleL = biquadE[2]*inputSampleL+biquadE[3]*biquadE[7]+biquadE[4]*biquadE[8]-biquadE[5]*biquadE[9]-biquadE[6]*biquadE[10];
biquadE[8] = biquadE[7]; biquadE[7] = inputSampleL; inputSampleL = outSampleL; biquadE[10] = biquadE[9]; biquadE[9] = inputSampleL; //DF1 left
double outSampleR = biquadA[2]*inputSampleR+biquadA[3]*biquadA[11]+biquadA[4]*biquadA[12]-biquadA[5]*biquadA[13]-biquadA[6]*biquadA[14];
biquadA[12] = biquadA[11]; biquadA[11] = inputSampleR; inputSampleR = outSampleR; biquadA[14] = biquadA[13]; biquadA[13] = inputSampleR; //DF1 right
outSampleR = biquadB[2]*inputSampleR+biquadB[3]*biquadB[11]+biquadB[4]*biquadB[12]-biquadB[5]*biquadB[13]-biquadB[6]*biquadB[14];
biquadB[12] = biquadB[11]; biquadB[11] = inputSampleR; inputSampleR = outSampleR; biquadB[14] = biquadB[13]; biquadB[13] = inputSampleR; //DF1 right
outSampleR = biquadC[2]*inputSampleR+biquadC[3]*biquadC[11]+biquadC[4]*biquadC[12]-biquadC[5]*biquadC[13]-biquadC[6]*biquadC[14];
biquadC[12] = biquadC[11]; biquadC[11] = inputSampleR; inputSampleR = outSampleR; biquadC[14] = biquadC[13]; biquadC[13] = inputSampleR; //DF1 right
outSampleR = biquadD[2]*inputSampleR+biquadD[3]*biquadD[11]+biquadD[4]*biquadD[12]-biquadD[5]*biquadD[13]-biquadD[6]*biquadD[14];
biquadD[12] = biquadD[11]; biquadD[11] = inputSampleR; inputSampleR = outSampleR; biquadD[14] = biquadD[13]; biquadD[13] = inputSampleR; //DF1 right
outSampleR = biquadE[2]*inputSampleR+biquadE[3]*biquadE[11]+biquadE[4]*biquadE[12]-biquadE[5]*biquadE[13]-biquadE[6]*biquadE[14];
biquadE[12] = biquadE[11]; biquadE[11] = inputSampleR; inputSampleR = outSampleR; biquadE[14] = biquadE[13]; biquadE[13] = inputSampleR; //DF1 right
//begin 32 bit stereo floating point dither
int expon; frexpf((float)inputSampleL, &expon);
fpdL ^= fpdL << 13; fpdL ^= fpdL >> 17; fpdL ^= fpdL << 5;
inputSampleL += ((double(fpdL)-uint32_t(0x7fffffff)) * 5.5e-36l * pow(2,expon+62));
frexpf((float)inputSampleR, &expon);
fpdR ^= fpdR << 13; fpdR ^= fpdR >> 17; fpdR ^= fpdR << 5;
inputSampleR += ((double(fpdR)-uint32_t(0x7fffffff)) * 5.5e-36l * pow(2,expon+62));
//end 32 bit stereo floating point dither
*out1 = inputSampleL;
*out2 = inputSampleR;
*in1++;
*in2++;
*out1++;
*out2++;
}
}
void Infrasonic::processDoubleReplacing(double **inputs, double **outputs, VstInt32 sampleFrames)
{
double* in1 = inputs[0];
double* in2 = inputs[1];
double* out1 = outputs[0];
double* out2 = outputs[1];
biquadE[0] = biquadD[0] = biquadC[0] = biquadB[0] = biquadA[0] = 20.0 / getSampleRate();
biquadA[1] = 0.50623256;
biquadB[1] = 0.56116312;
biquadC[1] = 0.70710678;
biquadD[1] = 1.10134463;
biquadE[1] = 3.19622661; //tenth order Butterworth out of five biquads
double K = tan(M_PI * biquadA[0]); //lowpass
double norm = 1.0 / (1.0 + K / biquadA[1] + K * K);
biquadA[2] = norm;
biquadA[3] = -2.0 * biquadA[2];
biquadA[4] = biquadA[2];
biquadA[5] = 2.0 * (K * K - 1.0) * norm;
biquadA[6] = (1.0 - K / biquadA[1] + K * K) * norm;
K = tan(M_PI * biquadA[0]);
norm = 1.0 / (1.0 + K / biquadB[1] + K * K);
biquadB[2] = norm;
biquadB[3] = -2.0 * biquadB[2];
biquadB[4] = biquadB[2];
biquadB[5] = 2.0 * (K * K - 1.0) * norm;
biquadB[6] = (1.0 - K / biquadB[1] + K * K) * norm;
K = tan(M_PI * biquadC[0]);
norm = 1.0 / (1.0 + K / biquadC[1] + K * K);
biquadC[2] = norm;
biquadC[3] = -2.0 * biquadC[2];
biquadC[4] = biquadC[2];
biquadC[5] = 2.0 * (K * K - 1.0) * norm;
biquadC[6] = (1.0 - K / biquadC[1] + K * K) * norm;
K = tan(M_PI * biquadD[0]);
norm = 1.0 / (1.0 + K / biquadD[1] + K * K);
biquadD[2] = norm;
biquadD[3] = -2.0 * biquadD[2];
biquadD[4] = biquadD[2];
biquadD[5] = 2.0 * (K * K - 1.0) * norm;
biquadD[6] = (1.0 - K / biquadD[1] + K * K) * norm;
K = tan(M_PI * biquadE[0]);
norm = 1.0 / (1.0 + K / biquadE[1] + K * K);
biquadE[2] = norm;
biquadE[3] = -2.0 * biquadE[2];
biquadE[4] = biquadE[2];
biquadE[5] = 2.0 * (K * K - 1.0) * norm;
biquadE[6] = (1.0 - K / biquadE[1] + K * K) * norm;
while (--sampleFrames >= 0)
{
double inputSampleL = *in1;
double inputSampleR = *in2;
if (fabs(inputSampleL)<1.18e-23) inputSampleL = fpdL * 1.18e-17;
if (fabs(inputSampleR)<1.18e-23) inputSampleR = fpdR * 1.18e-17;
double outSampleL = biquadA[2]*inputSampleL+biquadA[3]*biquadA[7]+biquadA[4]*biquadA[8]-biquadA[5]*biquadA[9]-biquadA[6]*biquadA[10];
biquadA[8] = biquadA[7]; biquadA[7] = inputSampleL; inputSampleL = outSampleL; biquadA[10] = biquadA[9]; biquadA[9] = inputSampleL; //DF1 left
outSampleL = biquadB[2]*inputSampleL+biquadB[3]*biquadB[7]+biquadB[4]*biquadB[8]-biquadB[5]*biquadB[9]-biquadB[6]*biquadB[10];
biquadB[8] = biquadB[7]; biquadB[7] = inputSampleL; inputSampleL = outSampleL; biquadB[10] = biquadB[9]; biquadB[9] = inputSampleL; //DF1 left
outSampleL = biquadC[2]*inputSampleL+biquadC[3]*biquadC[7]+biquadC[4]*biquadC[8]-biquadC[5]*biquadC[9]-biquadC[6]*biquadC[10];
biquadC[8] = biquadC[7]; biquadC[7] = inputSampleL; inputSampleL = outSampleL; biquadC[10] = biquadC[9]; biquadC[9] = inputSampleL; //DF1 left
outSampleL = biquadD[2]*inputSampleL+biquadD[3]*biquadD[7]+biquadD[4]*biquadD[8]-biquadD[5]*biquadD[9]-biquadD[6]*biquadD[10];
biquadD[8] = biquadD[7]; biquadD[7] = inputSampleL; inputSampleL = outSampleL; biquadD[10] = biquadD[9]; biquadD[9] = inputSampleL; //DF1 left
outSampleL = biquadE[2]*inputSampleL+biquadE[3]*biquadE[7]+biquadE[4]*biquadE[8]-biquadE[5]*biquadE[9]-biquadE[6]*biquadE[10];
biquadE[8] = biquadE[7]; biquadE[7] = inputSampleL; inputSampleL = outSampleL; biquadE[10] = biquadE[9]; biquadE[9] = inputSampleL; //DF1 left
double outSampleR = biquadA[2]*inputSampleR+biquadA[3]*biquadA[11]+biquadA[4]*biquadA[12]-biquadA[5]*biquadA[13]-biquadA[6]*biquadA[14];
biquadA[12] = biquadA[11]; biquadA[11] = inputSampleR; inputSampleR = outSampleR; biquadA[14] = biquadA[13]; biquadA[13] = inputSampleR; //DF1 right
outSampleR = biquadB[2]*inputSampleR+biquadB[3]*biquadB[11]+biquadB[4]*biquadB[12]-biquadB[5]*biquadB[13]-biquadB[6]*biquadB[14];
biquadB[12] = biquadB[11]; biquadB[11] = inputSampleR; inputSampleR = outSampleR; biquadB[14] = biquadB[13]; biquadB[13] = inputSampleR; //DF1 right
outSampleR = biquadC[2]*inputSampleR+biquadC[3]*biquadC[11]+biquadC[4]*biquadC[12]-biquadC[5]*biquadC[13]-biquadC[6]*biquadC[14];
biquadC[12] = biquadC[11]; biquadC[11] = inputSampleR; inputSampleR = outSampleR; biquadC[14] = biquadC[13]; biquadC[13] = inputSampleR; //DF1 right
outSampleR = biquadD[2]*inputSampleR+biquadD[3]*biquadD[11]+biquadD[4]*biquadD[12]-biquadD[5]*biquadD[13]-biquadD[6]*biquadD[14];
biquadD[12] = biquadD[11]; biquadD[11] = inputSampleR; inputSampleR = outSampleR; biquadD[14] = biquadD[13]; biquadD[13] = inputSampleR; //DF1 right
outSampleR = biquadE[2]*inputSampleR+biquadE[3]*biquadE[11]+biquadE[4]*biquadE[12]-biquadE[5]*biquadE[13]-biquadE[6]*biquadE[14];
biquadE[12] = biquadE[11]; biquadE[11] = inputSampleR; inputSampleR = outSampleR; biquadE[14] = biquadE[13]; biquadE[13] = inputSampleR; //DF1 right
//begin 64 bit stereo floating point dither
//int expon; frexp((double)inputSampleL, &expon);
fpdL ^= fpdL << 13; fpdL ^= fpdL >> 17; fpdL ^= fpdL << 5;
//inputSampleL += ((double(fpdL)-uint32_t(0x7fffffff)) * 1.1e-44l * pow(2,expon+62));
//frexp((double)inputSampleR, &expon);
fpdR ^= fpdR << 13; fpdR ^= fpdR >> 17; fpdR ^= fpdR << 5;
//inputSampleR += ((double(fpdR)-uint32_t(0x7fffffff)) * 1.1e-44l * pow(2,expon+62));
//end 64 bit stereo floating point dither
*out1 = inputSampleL;
*out2 = inputSampleR;
*in1++;
*in2++;
*out1++;
*out2++;
}
}
| 412 | 0.543947 | 1 | 0.543947 | game-dev | MEDIA | 0.247903 | game-dev | 0.575282 | 1 | 0.575282 |
dtprj/dongting | 4,341 | server/src/main/java/com/github/dtprj/dongting/raft/rpc/AdminConfigChangeProcessor.java | /*
* Copyright The Dongting Project
*
* The Dongting Project 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:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.dtprj.dongting.raft.rpc;
import com.github.dtprj.dongting.codec.DecodeContext;
import com.github.dtprj.dongting.codec.DecoderCallback;
import com.github.dtprj.dongting.log.DtLog;
import com.github.dtprj.dongting.log.DtLogs;
import com.github.dtprj.dongting.net.Commands;
import com.github.dtprj.dongting.net.PbLongWritePacket;
import com.github.dtprj.dongting.net.ReadPacket;
import com.github.dtprj.dongting.net.WritePacket;
import com.github.dtprj.dongting.raft.server.NotLeaderException;
import com.github.dtprj.dongting.raft.server.RaftGroup;
import com.github.dtprj.dongting.raft.server.RaftProcessor;
import com.github.dtprj.dongting.raft.server.RaftServer;
import com.github.dtprj.dongting.raft.server.ReqInfo;
import java.util.concurrent.CompletableFuture;
/**
* @author huangli
*/
public class AdminConfigChangeProcessor extends RaftProcessor<Object> {
private static final DtLog log = DtLogs.getLogger(AdminConfigChangeProcessor.class);
public AdminConfigChangeProcessor(RaftServer raftServer) {
super(raftServer);
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
protected int getGroupId(ReadPacket frame) {
if (frame.command == Commands.RAFT_ADMIN_PREPARE_CHANGE) {
ReadPacket<AdminPrepareConfigChangeReq> f = (ReadPacket<AdminPrepareConfigChangeReq>) frame;
AdminPrepareConfigChangeReq req = f.getBody();
return req.groupId;
} else {
ReadPacket<AdminCommitOrAbortReq> f = (ReadPacket<AdminCommitOrAbortReq>) frame;
AdminCommitOrAbortReq req = f.getBody();
return req.groupId;
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public DecoderCallback createDecoderCallback(int command, DecodeContext context) {
if (command == Commands.RAFT_ADMIN_PREPARE_CHANGE) {
return context.toDecoderCallback(new AdminPrepareConfigChangeReq.Callback());
} else {
return context.toDecoderCallback(new AdminCommitOrAbortReq());
}
}
@SuppressWarnings({"rawtypes"})
@Override
protected WritePacket doProcess(ReqInfo reqInfo) {
ReadPacket reqFrame = reqInfo.reqFrame;
RaftGroup rg = reqInfo.raftGroup;
String type;
CompletableFuture<Long> f;
if (reqFrame.command == Commands.RAFT_ADMIN_PREPARE_CHANGE) {
type = "prepare";
AdminPrepareConfigChangeReq req = (AdminPrepareConfigChangeReq) reqFrame.getBody();
f = rg.leaderPrepareJointConsensus(req.members, req.observers, req.preparedMembers, req.preparedObservers);
} else if (reqFrame.command == Commands.RAFT_ADMIN_COMMIT_CHANGE) {
type = "commit";
AdminCommitOrAbortReq req = (AdminCommitOrAbortReq) reqFrame.getBody();
f = rg.leaderCommitJointConsensus(req.prepareIndex);
} else {
type = "abort";
f = rg.leaderAbortJointConsensus();
}
f.whenComplete((index, ex) -> {
if (ex != null) {
if (ex instanceof NotLeaderException) {
log.warn("Admin {} config change failed, groupId={}, not leader", type, rg.getGroupId());
} else {
log.error("Admin {} config change failed, groupId={}", type, rg.getGroupId(), ex);
}
writeErrorResp(reqInfo, ex);
} else {
log.info("Admin {} config change success, groupId={}, resultIndex={}", type, rg.getGroupId(), index);
reqInfo.reqContext.writeRespInBizThreads(new PbLongWritePacket(index));
}
});
return null;
}
}
| 412 | 0.891125 | 1 | 0.891125 | game-dev | MEDIA | 0.302652 | game-dev | 0.890079 | 1 | 0.890079 |
ChaoticBuilder/Ultrabell | 19,395 | actors/luigi/geo_header.h | extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt1_switch_face_opt1[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt1_switch_face_opt2[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt1_switch_face_opt3[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt1_switch_face_opt4[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt1_switch_face_opt5[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt1_switch_face_opt6[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt1_switch_face_opt7[];
extern const GeoLayout luigi_armature_002_switch_option_002[];
extern const GeoLayout luigi_right_hand_open_armature[];
extern const GeoLayout luigi_left_hand_open_armature[];
extern const GeoLayout luigi_left_hand_peace_armature[];
extern const GeoLayout luigi_left_hand_cap_armature[];
extern const GeoLayout luigi_left_hand_wing_cap_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt1_switch_face_opt1[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt1_switch_face_opt2[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt1_switch_face_opt3[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt1_switch_face_opt4[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt1_switch_face_opt5[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt1_switch_face_opt6[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt1_switch_face_opt7[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_jump_luigi_armature_002_switch_option_002[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_jump_luigi_right_hand_open_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_jump_luigi_left_hand_open_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_jump_luigi_left_hand_peace_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_jump_luigi_left_hand_cap_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_jump_luigi_left_hand_wing_cap_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt0_000_switch_001_opt1[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt0_000_switch_001_opt2[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt0_000_switch_001_opt3[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt0_000_switch_001_opt4[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt0_000_switch_001_opt5[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt0_000_switch_001_opt6[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1_000_switch_opt0_000_switch_001_opt7[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt1[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt2_jump_luigi_armature_002_switch_option_002[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt2_jump_luigi_right_hand_open_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt2_jump_luigi_left_hand_open_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt2_jump_luigi_left_hand_peace_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt2_jump_luigi_left_hand_cap_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt2_jump_luigi_left_hand_wing_cap_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt2[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt3_jump_luigi_armature_002_switch_option_002[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt3_jump_luigi_right_hand_open_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt3_jump_luigi_left_hand_open_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt3_jump_luigi_left_hand_peace_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt3_jump_luigi_left_hand_cap_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt3_jump_luigi_left_hand_wing_cap_armature[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt3[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt0_000_switch_001_opt1[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt0_000_switch_001_opt2[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt0_000_switch_001_opt3[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt0_000_switch_001_opt4[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt0_000_switch_001_opt5[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt0_000_switch_001_opt6[];
extern const GeoLayout luigi_002_switch_opt0_001_switch_opt0_000_switch_opt0_000_switch_001_opt7[];
extern const GeoLayout luigi_geo[];
extern u8 luigi_mario_metal_rgba16_rgba16[];
extern u8 luigi_mario_eyes_center_rgba16_rgba16[];
extern u8 luigi_luigi_logo_rgba16_ci8[];
extern u8 luigi_luigi_logo_rgba16_pal_rgba16[];
extern u8 luigi_mario_eyes_half_closed_rgba16_rgba16[];
extern u8 luigi_mario_eyes_closed_rgba16_rgba16[];
extern u8 luigi_mario_eyes_right_unused_rgba16_rgba16[];
extern u8 luigi_mario_eyes_left_unused_rgba16_rgba16[];
extern u8 luigi_mario_eyes_up_unused_rgba16_rgba16[];
extern u8 luigi_mario_eyes_down_unused_rgba16_rgba16[];
extern u8 luigi_mario_eyes_dead_rgba16_rgba16[];
extern u8 luigi_mario_wing_tip_rgba16_ia8[];
extern u8 luigi_mario_wing_rgba16_ia8[];
extern Vtx luigi_000_offset_mesh_layer_1_vtx_0[53];
extern Gfx luigi_000_offset_mesh_layer_1_tri_0[];
extern Vtx luigi_000_offset_001_mesh_layer_1_vtx_0[84];
extern Gfx luigi_000_offset_001_mesh_layer_1_tri_0[];
extern Vtx luigi_000_offset_001_mesh_layer_1_vtx_1[27];
extern Gfx luigi_000_offset_001_mesh_layer_1_tri_1[];
extern Vtx luigi_000_offset_001_mesh_layer_1_vtx_2[14];
extern Gfx luigi_000_offset_001_mesh_layer_1_tri_2[];
extern Vtx luigi_000_displaylist_mesh_layer_1_vtx_0[12];
extern Gfx luigi_000_displaylist_mesh_layer_1_tri_0[];
extern Vtx luigi_000_displaylist_mesh_layer_1_vtx_1[95];
extern Gfx luigi_000_displaylist_mesh_layer_1_tri_1[];
extern Vtx luigi_000_displaylist_mesh_layer_1_vtx_2[14];
extern Gfx luigi_000_displaylist_mesh_layer_1_tri_2[];
extern Vtx luigi_000_displaylist_mesh_layer_1_vtx_3[28];
extern Gfx luigi_000_displaylist_mesh_layer_1_tri_3[];
extern Vtx luigi_000_displaylist_mesh_layer_1_vtx_4[53];
extern Gfx luigi_000_displaylist_mesh_layer_1_tri_4[];
extern Vtx luigi_000_displaylist_mesh_layer_1_vtx_5[7];
extern Gfx luigi_000_displaylist_mesh_layer_1_tri_5[];
extern Vtx luigi_000_displaylist_mesh_layer_1_vtx_6[6];
extern Gfx luigi_000_displaylist_mesh_layer_1_tri_6[];
extern Vtx luigi_000_displaylist_mesh_layer_1_vtx_7[12];
extern Gfx luigi_000_displaylist_mesh_layer_1_tri_7[];
extern Vtx luigi_000_displaylist_mesh_layer_4_vtx_0[3];
extern Gfx luigi_000_displaylist_mesh_layer_4_tri_0[];
extern Vtx luigi_002_switch_option_head__no_cap__mesh_layer_1_vtx_0[50];
extern Gfx luigi_002_switch_option_head__no_cap__mesh_layer_1_tri_0[];
extern Vtx luigi_002_switch_option_head__no_cap__mesh_layer_1_vtx_1[79];
extern Gfx luigi_002_switch_option_head__no_cap__mesh_layer_1_tri_1[];
extern Vtx luigi_002_switch_option_head__no_cap__mesh_layer_1_vtx_2[14];
extern Gfx luigi_002_switch_option_head__no_cap__mesh_layer_1_tri_2[];
extern Vtx luigi_002_switch_option_head__no_cap__mesh_layer_1_vtx_3[69];
extern Gfx luigi_002_switch_option_head__no_cap__mesh_layer_1_tri_3[];
extern Vtx luigi_000_displaylist_001_mesh_layer_4_vtx_0[5];
extern Gfx luigi_000_displaylist_001_mesh_layer_4_tri_0[];
extern Vtx luigi_000_displaylist_001_mesh_layer_4_vtx_1[4];
extern Gfx luigi_000_displaylist_001_mesh_layer_4_tri_1[];
extern Vtx luigi_000_displaylist_002_mesh_layer_4_vtx_0[4];
extern Gfx luigi_000_displaylist_002_mesh_layer_4_tri_0[];
extern Vtx luigi_000_displaylist_002_mesh_layer_4_vtx_1[4];
extern Gfx luigi_000_displaylist_002_mesh_layer_4_tri_1[];
extern Vtx luigi_000_offset_003_mesh_layer_1_vtx_0[20];
extern Gfx luigi_000_offset_003_mesh_layer_1_tri_0[];
extern Vtx luigi_000_offset_004_mesh_layer_1_vtx_0[16];
extern Gfx luigi_000_offset_004_mesh_layer_1_tri_0[];
extern Vtx luigi_000_displaylist_003_mesh_layer_1_vtx_0[38];
extern Gfx luigi_000_displaylist_003_mesh_layer_1_tri_0[];
extern Vtx luigi_002_switch_option_right_hand_open_mesh_layer_1_vtx_0[42];
extern Gfx luigi_002_switch_option_right_hand_open_mesh_layer_1_tri_0[];
extern Vtx luigi_000_offset_006_mesh_layer_1_vtx_0[20];
extern Gfx luigi_000_offset_006_mesh_layer_1_tri_0[];
extern Vtx luigi_000_offset_007_mesh_layer_1_vtx_0[16];
extern Gfx luigi_000_offset_007_mesh_layer_1_tri_0[];
extern Vtx luigi_000_displaylist_004_mesh_layer_1_vtx_0[38];
extern Gfx luigi_000_displaylist_004_mesh_layer_1_tri_0[];
extern Vtx luigi_002_switch_option_left_hand_open_mesh_layer_1_vtx_0[42];
extern Gfx luigi_002_switch_option_left_hand_open_mesh_layer_1_tri_0[];
extern Vtx luigi_004_switch_option_left_hand_peace_mesh_layer_1_vtx_0[69];
extern Gfx luigi_004_switch_option_left_hand_peace_mesh_layer_1_tri_0[];
extern Vtx luigi_005_switch_option_left_hand_cap_mesh_layer_4_vtx_0[11];
extern Gfx luigi_005_switch_option_left_hand_cap_mesh_layer_4_tri_0[];
extern Vtx luigi_005_switch_option_left_hand_cap_mesh_layer_1_vtx_0[28];
extern Gfx luigi_005_switch_option_left_hand_cap_mesh_layer_1_tri_0[];
extern Vtx luigi_005_switch_option_left_hand_cap_mesh_layer_1_vtx_1[10];
extern Gfx luigi_005_switch_option_left_hand_cap_mesh_layer_1_tri_1[];
extern Vtx luigi_005_switch_option_left_hand_cap_mesh_layer_1_vtx_2[25];
extern Gfx luigi_005_switch_option_left_hand_cap_mesh_layer_1_tri_2[];
extern Vtx luigi_006_switch_option_left_hand_wing_cap_mesh_layer_4_vtx_0[11];
extern Gfx luigi_006_switch_option_left_hand_wing_cap_mesh_layer_4_tri_0[];
extern Vtx luigi_006_switch_option_left_hand_wing_cap_mesh_layer_1_vtx_0[28];
extern Gfx luigi_006_switch_option_left_hand_wing_cap_mesh_layer_1_tri_0[];
extern Vtx luigi_006_switch_option_left_hand_wing_cap_mesh_layer_1_vtx_1[10];
extern Gfx luigi_006_switch_option_left_hand_wing_cap_mesh_layer_1_tri_1[];
extern Vtx luigi_006_switch_option_left_hand_wing_cap_mesh_layer_1_vtx_2[25];
extern Gfx luigi_006_switch_option_left_hand_wing_cap_mesh_layer_1_tri_2[];
extern Vtx luigi_006_switch_option_left_hand_wing_cap_wings_mesh_layer_4_vtx_0[8];
extern Gfx luigi_006_switch_option_left_hand_wing_cap_wings_mesh_layer_4_tri_0[];
extern Vtx luigi_006_switch_option_left_hand_wing_cap_wings_mesh_layer_4_vtx_1[8];
extern Gfx luigi_006_switch_option_left_hand_wing_cap_wings_mesh_layer_4_tri_1[];
extern Vtx luigi_000_offset_009_mesh_layer_1_vtx_0[16];
extern Gfx luigi_000_offset_009_mesh_layer_1_tri_0[];
extern Vtx luigi_000_offset_010_mesh_layer_1_vtx_0[12];
extern Gfx luigi_000_offset_010_mesh_layer_1_tri_0[];
extern Vtx luigi_000_offset_011_mesh_layer_1_vtx_0[15];
extern Gfx luigi_000_offset_011_mesh_layer_1_tri_0[];
extern Vtx luigi_000_offset_011_mesh_layer_1_vtx_1[8];
extern Gfx luigi_000_offset_011_mesh_layer_1_tri_1[];
extern Vtx luigi_000_offset_012_mesh_layer_1_vtx_0[16];
extern Gfx luigi_000_offset_012_mesh_layer_1_tri_0[];
extern Vtx luigi_000_offset_013_mesh_layer_1_vtx_0[12];
extern Gfx luigi_000_offset_013_mesh_layer_1_tri_0[];
extern Vtx luigi_000_displaylist_005_mesh_layer_1_vtx_0[15];
extern Gfx luigi_000_displaylist_005_mesh_layer_1_tri_0[];
extern Vtx luigi_000_displaylist_005_mesh_layer_1_vtx_1[8];
extern Gfx luigi_000_displaylist_005_mesh_layer_1_tri_1[];
extern Gfx mat_luigi_blue[];
extern Gfx mat_revert_luigi_blue[];
extern Gfx mat_luigi_metal_v3_001[];
extern Gfx mat_revert_luigi_metal_v3_001[];
extern Gfx mat_luigi_red[];
extern Gfx mat_revert_luigi_red[];
extern Gfx mat_luigi_button[];
extern Gfx mat_revert_luigi_button[];
extern Gfx mat_luigi_face_0___eye_open_v3_001[];
extern Gfx mat_revert_luigi_face_0___eye_open_v3_001[];
extern Gfx mat_luigi_skin[];
extern Gfx mat_revert_luigi_skin[];
extern Gfx mat_luigi_mustache_v3_001[];
extern Gfx mat_revert_luigi_mustache_v3_001[];
extern Gfx mat_luigi_hair_v3_001[];
extern Gfx mat_revert_luigi_hair_v3_001[];
extern Gfx mat_luigi_cap_inside[];
extern Gfx mat_revert_luigi_cap_inside[];
extern Gfx mat_luigi_cat_pink[];
extern Gfx mat_revert_luigi_cat_pink[];
extern Gfx mat_luigi_cat[];
extern Gfx mat_revert_luigi_cat[];
extern Gfx mat_luigi_logo[];
extern Gfx mat_revert_luigi_logo[];
extern Gfx mat_luigi_face_1___eye_half_v3_001[];
extern Gfx mat_revert_luigi_face_1___eye_half_v3_001[];
extern Gfx mat_luigi_face_2___eye_closed_v3_001[];
extern Gfx mat_revert_luigi_face_2___eye_closed_v3_001[];
extern Gfx mat_luigi_face_3_v3_001[];
extern Gfx mat_revert_luigi_face_3_v3_001[];
extern Gfx mat_luigi_face_4_v3_001[];
extern Gfx mat_revert_luigi_face_4_v3_001[];
extern Gfx mat_luigi_face_5_v3_001[];
extern Gfx mat_revert_luigi_face_5_v3_001[];
extern Gfx mat_luigi_face_6_v3_001[];
extern Gfx mat_revert_luigi_face_6_v3_001[];
extern Gfx mat_luigi_face_7___eye_X_v3_001[];
extern Gfx mat_revert_luigi_face_7___eye_X_v3_001[];
extern Gfx mat_luigi_wing_2_v3_001_layer4[];
extern Gfx mat_revert_luigi_wing_2_v3_001_layer4[];
extern Gfx mat_luigi_wing_1_v3_001[];
extern Gfx mat_revert_luigi_wing_1_v3_001[];
extern Gfx mat_luigi_gloves_v3_001[];
extern Gfx mat_revert_luigi_gloves_v3_001[];
extern Gfx mat_luigi_shoes_v3_001[];
extern Gfx mat_revert_luigi_shoes_v3_001[];
extern Gfx mat_luigi_shoes2_v3_002[];
extern Gfx mat_revert_luigi_shoes2_v3_002[];
extern Gfx luigi_000_offset_mesh_layer_1[];
extern Gfx luigi_000_offset_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_offset_001_mesh_layer_1[];
extern Gfx luigi_000_offset_001_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_displaylist_mesh_layer_1[];
extern Gfx luigi_000_displaylist_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_displaylist_mesh_layer_1_mat_override_face_1___eye_half_v3_001_1[];
extern Gfx luigi_000_displaylist_mesh_layer_1_mat_override_face_2___eye_closed_v3_001_2[];
extern Gfx luigi_000_displaylist_mesh_layer_1_mat_override_face_3_v3_001_3[];
extern Gfx luigi_000_displaylist_mesh_layer_1_mat_override_face_4_v3_001_4[];
extern Gfx luigi_000_displaylist_mesh_layer_1_mat_override_face_5_v3_001_5[];
extern Gfx luigi_000_displaylist_mesh_layer_1_mat_override_face_6_v3_001_6[];
extern Gfx luigi_000_displaylist_mesh_layer_1_mat_override_face_7___eye_X_v3_001_7[];
extern Gfx luigi_000_displaylist_mesh_layer_4[];
extern Gfx luigi_000_displaylist_mesh_layer_4_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_displaylist_mesh_layer_4_mat_override_face_1___eye_half_v3_001_1[];
extern Gfx luigi_000_displaylist_mesh_layer_4_mat_override_face_2___eye_closed_v3_001_2[];
extern Gfx luigi_000_displaylist_mesh_layer_4_mat_override_face_3_v3_001_3[];
extern Gfx luigi_000_displaylist_mesh_layer_4_mat_override_face_4_v3_001_4[];
extern Gfx luigi_000_displaylist_mesh_layer_4_mat_override_face_5_v3_001_5[];
extern Gfx luigi_000_displaylist_mesh_layer_4_mat_override_face_6_v3_001_6[];
extern Gfx luigi_000_displaylist_mesh_layer_4_mat_override_face_7___eye_X_v3_001_7[];
extern Gfx luigi_002_switch_option_head__no_cap__mesh_layer_1[];
extern Gfx luigi_002_switch_option_head__no_cap__mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_002_switch_option_head__no_cap__mesh_layer_1_mat_override_face_1___eye_half_v3_001_1[];
extern Gfx luigi_002_switch_option_head__no_cap__mesh_layer_1_mat_override_face_2___eye_closed_v3_001_2[];
extern Gfx luigi_002_switch_option_head__no_cap__mesh_layer_1_mat_override_face_3_v3_001_3[];
extern Gfx luigi_002_switch_option_head__no_cap__mesh_layer_1_mat_override_face_4_v3_001_4[];
extern Gfx luigi_002_switch_option_head__no_cap__mesh_layer_1_mat_override_face_5_v3_001_5[];
extern Gfx luigi_002_switch_option_head__no_cap__mesh_layer_1_mat_override_face_6_v3_001_6[];
extern Gfx luigi_002_switch_option_head__no_cap__mesh_layer_1_mat_override_face_7___eye_X_v3_001_7[];
extern Gfx luigi_000_displaylist_001_mesh_layer_4[];
extern Gfx luigi_000_displaylist_001_mesh_layer_4_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_displaylist_002_mesh_layer_4[];
extern Gfx luigi_000_displaylist_002_mesh_layer_4_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_offset_003_mesh_layer_1[];
extern Gfx luigi_000_offset_003_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_offset_004_mesh_layer_1[];
extern Gfx luigi_000_offset_004_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_displaylist_003_mesh_layer_1[];
extern Gfx luigi_000_displaylist_003_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_002_switch_option_right_hand_open_mesh_layer_1[];
extern Gfx luigi_002_switch_option_right_hand_open_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_offset_006_mesh_layer_1[];
extern Gfx luigi_000_offset_006_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_offset_007_mesh_layer_1[];
extern Gfx luigi_000_offset_007_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_displaylist_004_mesh_layer_1[];
extern Gfx luigi_000_displaylist_004_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_002_switch_option_left_hand_open_mesh_layer_1[];
extern Gfx luigi_002_switch_option_left_hand_open_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_004_switch_option_left_hand_peace_mesh_layer_1[];
extern Gfx luigi_004_switch_option_left_hand_peace_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_005_switch_option_left_hand_cap_mesh_layer_4[];
extern Gfx luigi_005_switch_option_left_hand_cap_mesh_layer_4_mat_override_metal_v3_001_0[];
extern Gfx luigi_005_switch_option_left_hand_cap_mesh_layer_1[];
extern Gfx luigi_005_switch_option_left_hand_cap_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_006_switch_option_left_hand_wing_cap_mesh_layer_4[];
extern Gfx luigi_006_switch_option_left_hand_wing_cap_mesh_layer_4_mat_override_metal_v3_001_0[];
extern Gfx luigi_006_switch_option_left_hand_wing_cap_mesh_layer_1[];
extern Gfx luigi_006_switch_option_left_hand_wing_cap_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_006_switch_option_left_hand_wing_cap_wings_mesh_layer_4[];
extern Gfx luigi_006_switch_option_left_hand_wing_cap_wings_mesh_layer_4_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_offset_009_mesh_layer_1[];
extern Gfx luigi_000_offset_009_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_offset_010_mesh_layer_1[];
extern Gfx luigi_000_offset_010_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_offset_011_mesh_layer_1[];
extern Gfx luigi_000_offset_011_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_offset_012_mesh_layer_1[];
extern Gfx luigi_000_offset_012_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_offset_013_mesh_layer_1[];
extern Gfx luigi_000_offset_013_mesh_layer_1_mat_override_metal_v3_001_0[];
extern Gfx luigi_000_displaylist_005_mesh_layer_1[];
extern Gfx luigi_000_displaylist_005_mesh_layer_1_mat_override_metal_v3_001_0[];
| 412 | 0.591986 | 1 | 0.591986 | game-dev | MEDIA | 0.270133 | game-dev | 0.538169 | 1 | 0.538169 |
bates64/papermario-dx | 20,961 | src/world/area_jan/jan_02/npc.c | #include "jan_02.h"
#include "sprite/player.h"
#include "world/common/npc/Yoshi.inc.c"
#include "world/common/npc/Yoshi_Patrol.inc.c"
#include "world/common/complete/KeyItemChoice.inc.c"
#define CHUCK_QUIZMO_NPC_ID NPC_ChuckQuizmo
#include "world/common/complete/Quizmo.inc.c"
#include "world/common/todo/SwitchToPartner.inc.c"
EvtScript N(EVS_GetRescuedYoshiCount) = {
Set(LVar0, 0)
Add(LVar0, GF_JAN05_SavedYoshi)
Add(LVar0, GF_JAN07_SavedYoshi)
Add(LVar0, GF_JAN08_SavedYoshi)
Add(LVar0, GF_JAN10_SavedYoshi)
Add(LVar0, GF_JAN11_SavedYoshi)
Return
End
};
EvtScript N(EVS_Scene_GetJadeRaven) = {
Call(SetNpcFlagBits, NPC_PARTNER, NPC_FLAG_IGNORE_WORLD_COLLISION, TRUE)
IfEq(GF_JAN02_Met_VillageLeader, TRUE)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_Talk, ANIM_VillageLeader_Idle, 0, MSG_CH5_0023)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_Talk, ANIM_VillageLeader_Idle, 0, MSG_CH5_0024)
EndIf
Wait(5 * DT)
Call(SetNpcFlagBits, NPC_SELF, NPC_FLAG_IGNORE_PLAYER_COLLISION, TRUE)
Call(SetNpcAnimation, NPC_SELF, ANIM_VillageLeader_Walk)
Call(NpcMoveTo, NPC_SELF, 8, -140, 25)
Call(SetNpcFlagBits, NPC_SELF, NPC_FLAG_IGNORE_PLAYER_COLLISION, FALSE)
Call(SetNpcAnimation, NPC_SELF, ANIM_VillageLeader_Idle)
Wait(5 * DT)
Call(UseSettingsFrom, CAM_DEFAULT, 25, 15, -150)
Call(SetPanTarget, CAM_DEFAULT, 25, 15, -150)
Call(SetCamDistance, CAM_DEFAULT, Float(300.0))
Call(SetCamPitch, CAM_DEFAULT, Float(16.0), Float(-8.0))
Call(SetCamSpeed, CAM_DEFAULT, Float(4.0 / DT))
Call(PanToTarget, CAM_DEFAULT, 0, TRUE)
Wait(5 * DT)
Call(PlayerMoveTo, 58, -140, 25)
Call(PlayerFaceNpc, NPC_SELF, FALSE)
Call(func_802D2C14, 1)
Call(SetNpcFlagBits, NPC_PARTNER, NPC_FLAG_IGNORE_PLAYER_COLLISION, TRUE)
Wait(30 * DT)
Call(SetNpcAnimation, NPC_SELF, ANIM_VillageLeader_Rummage)
Wait(30 * DT)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_Rummage, ANIM_VillageLeader_Rummage, 5, MSG_CH5_0025)
Wait(60 * DT)
Call(SetNpcAnimation, NPC_SELF, ANIM_VillageLeader_Idle)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_Talk, ANIM_VillageLeader_Idle, 0, MSG_CH5_0026)
EVT_GIVE_REWARD(ITEM_JADE_RAVEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_Talk, ANIM_VillageLeader_Idle, 0, MSG_CH5_0027)
Set(GB_StoryProgress, STORY_CH5_GOT_JADE_RAVEN)
Wait(15 * DT)
Call(GetPlayerPos, LVar3, LVar4, LVar5)
Add(LVar3, 25)
Call(SetPanTarget, CAM_DEFAULT, LVar3, LVar4, LVar5)
Call(SetCamSpeed, CAM_DEFAULT, Float(2.5 / DT))
Call(PanToTarget, CAM_DEFAULT, 0, TRUE)
Call(WaitForCam, CAM_DEFAULT, Float(1.0))
Call(SetNpcFlagBits, NPC_PARTNER, NPC_FLAG_IGNORE_WORLD_COLLISION, FALSE)
Call(func_802D2C14, 0)
Call(GetCurrentPartnerID, LVar0)
IfEq(LVar0, PARTNER_SUSHIE)
Thread
Wait(15 * DT)
Call(PlayerFaceNpc, NPC_PARTNER, FALSE)
EndThread
Call(DisablePartnerAI, 0)
Call(SpeakToPlayer, NPC_PARTNER, ANIM_WorldSushie_Talk, ANIM_WorldSushie_Idle, 2, MSG_CH5_0028)
Else
Call(N(SwitchToPartner), PARTNER_SUSHIE)
Call(SpeakToPlayer, NPC_PARTNER, -1, -1, 5, MSG_CH5_0029)
Call(SetNpcFlagBits, NPC_PARTNER, NPC_FLAG_IGNORE_PLAYER_COLLISION, TRUE)
Wait(15 * DT)
Call(GetNpcPos, NPC_PARTNER, LVar2, LVar3, LVar4)
Call(MakeLerp, LVar2, 85, 10 * DT, EASING_LINEAR)
Loop(0)
Call(UpdateLerp)
Call(SetNpcPos, NPC_PARTNER, LVar0, LVar3, LVar4)
Wait(1)
IfEq(LVar1, 0)
BreakLoop
EndIf
EndLoop
Call(InterpNpcYaw, NPC_PARTNER, 270, 0)
Wait(10 * DT)
Thread
Wait(10 * DT)
Call(PlayerFaceNpc, NPC_PARTNER, FALSE)
EndThread
Call(DisablePartnerAI, 0)
Call(ContinueSpeech, NPC_PARTNER, ANIM_WorldSushie_Talk, ANIM_WorldSushie_Idle, 5, MSG_CH5_002A)
Wait(10 * DT)
EndIf
Call(ContinueSpeech, NPC_PARTNER, ANIM_WorldSushie_Talk, ANIM_WorldSushie_Idle, 5, MSG_CH5_002B)
Call(SetPlayerAnimation, ANIM_MarioW2_SpeakUp)
Wait(30 * DT)
Call(SpeakToPlayer, NPC_PARTNER, ANIM_WorldSushie_Talk, ANIM_WorldSushie_Idle, 5, MSG_CH5_002C)
Wait(10 * DT)
Call(EnablePartnerAI)
Call(ResetCam, CAM_DEFAULT, Float(2.0 / DT))
Return
End
};
EvtScript N(EVS_NpcInteract_VillageLeader) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
IfEq(GF_JAN02_Met_VillageLeader, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_TalkSit, ANIM_VillageLeader_IdleSit, 0, MSG_CH5_0021)
Set(GF_JAN02_Met_VillageLeader, TRUE)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_TalkSit, ANIM_VillageLeader_IdleSit, 0, MSG_CH5_0022)
EndIf
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
CaseLt(STORY_CH5_GOT_JADE_RAVEN)
ExecWait(N(EVS_Scene_GetJadeRaven))
CaseLt(STORY_CH5_RAPHAEL_LEFT_NEST)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_Talk, ANIM_VillageLeader_Idle, 0, MSG_CH5_002D)
CaseLt(STORY_CH5_ZIP_LINE_READY)
IfEq(AF_JAN02_RaphaelComment, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_TalkSit, ANIM_VillageLeader_IdleSit, 0, MSG_CH5_002E)
Set(AF_JAN02_RaphaelComment, TRUE)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_TalkSit, ANIM_VillageLeader_IdleSit, 0, MSG_CH5_002F)
EndIf
CaseLt(STORY_CH5_ENTERED_MT_LAVA_LAVA)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_TalkSit, ANIM_VillageLeader_IdleSit, 0, MSG_CH5_0030)
CaseLt(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_TalkSit, ANIM_VillageLeader_IdleSit, 0, MSG_CH5_0031)
CaseLt(STORY_CH6_FLOWER_GATE_OPEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_TalkSit, ANIM_VillageLeader_IdleSit, 0, MSG_CH5_0032)
CaseDefault
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_TalkSit, ANIM_VillageLeader_IdleSit, 0, MSG_CH5_0033)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcInit_VillageLeader) = {
Call(BindNpcIdle, NPC_SELF, 0)
Call(SetNpcAnimation, NPC_SELF, ANIM_VillageLeader_IdleSit)
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_VillageLeader)))
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SetNpcPos, NPC_SELF, NPC_DISPOSE_LOCATION)
CaseLt(STORY_CH5_GOT_JADE_RAVEN)
Call(SetNpcAnimation, NPC_SELF, ANIM_VillageLeader_Idle)
Call(InterpNpcYaw, NPC_SELF, 90, 1)
Call(SetNpcPos, NPC_SELF, 0, 15, -50)
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_VillageLeader)))
CaseLt(STORY_CH5_RAPHAEL_LEFT_NEST)
Call(SetNpcAnimation, NPC_SELF, ANIM_VillageLeader_Idle)
Call(InterpNpcYaw, NPC_SELF, 90, 1)
Call(SetNpcPos, NPC_SELF, 30, 15, -30)
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_VillageLeader)))
CaseDefault
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_VillageLeader)))
EndSwitch
Return
End
};
EvtScript N(EVS_NpcInteract_Councillor) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
IfEq(AF_JAN02_MetCouncillor, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_LeadersFriend_TalkSit, ANIM_LeadersFriend_IdleSit, 0, MSG_CH5_0034)
Call(EndSpeech, NPC_SELF, ANIM_LeadersFriend_TalkSit, ANIM_LeadersFriend_IdleSit, 0)
Set(AF_JAN02_MetCouncillor, TRUE)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_LeadersFriend_TalkSit, ANIM_LeadersFriend_IdleSit, 0, MSG_CH5_0035)
EndIf
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
IfEq(GF_JAN03_AgreedToRescueChildren, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_LeadersFriend_TalkSitSad, ANIM_LeadersFriend_BowSit, 0, MSG_CH5_0036)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_LeadersFriend_TalkSitSad, ANIM_LeadersFriend_BowSit, 0, MSG_CH5_0037)
EndIf
CaseLt(STORY_CH5_GOT_JADE_RAVEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_LeadersFriend_TalkSit, ANIM_LeadersFriend_IdleSit, 0, MSG_CH5_0038)
CaseLt(STORY_CH5_ENTERED_MT_LAVA_LAVA)
Call(SpeakToPlayer, NPC_SELF, ANIM_LeadersFriend_TalkSit, ANIM_LeadersFriend_IdleSit, 0, MSG_CH5_0039)
CaseLt(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SpeakToPlayer, NPC_SELF, ANIM_LeadersFriend_TalkSit, ANIM_LeadersFriend_IdleSit, 0, MSG_CH5_003A)
CaseLt(STORY_CH6_FLOWER_GATE_OPEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_LeadersFriend_TalkSit, ANIM_LeadersFriend_IdleSit, 0, MSG_CH5_003B)
CaseDefault
Call(SpeakToPlayer, NPC_SELF, ANIM_LeadersFriend_TalkSit, ANIM_LeadersFriend_IdleSit, 0, MSG_CH5_003C)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcInit_Councillor) = {
Call(SetNpcAnimation, NPC_SELF, ANIM_LeadersFriend_IdleSit)
Call(SetNpcCollisionSize, NPC_SELF, 40, 32)
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SetNpcAnimation, NPC_SELF, ANIM_LeadersFriend_BowSit)
EndIf
EndSwitch
Call(BindNpcIdle, NPC_SELF, 0)
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_Councillor)))
Return
End
};
EvtScript N(EVS_NpcInteract_Yoshi_01) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Red_Talk, ANIM_Yoshi_Red_Idle, 0, MSG_CH5_003D)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
ExecWait(N(EVS_GetRescuedYoshiCount))
IfEq(LVar0, 0)
IfEq(GF_JAN03_AgreedToRescueChildren, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Red_CryTalk, ANIM_Yoshi_Red_Cry, 0, MSG_CH5_003E)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Red_CryTalk, ANIM_Yoshi_Red_Cry, 0, MSG_CH5_003F)
EndIf
Else
IfEq(GF_JAN08_SavedYoshi, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Red_CryTalk, ANIM_Yoshi_Red_Cry, 0, MSG_CH5_0040)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Red_Talk, ANIM_Yoshi_Red_Idle, 0, MSG_CH5_0041)
EndIf
EndIf
CaseLe(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Red_Talk, ANIM_Yoshi_Red_Idle, 0, MSG_CH5_0042)
CaseLt(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Red_Talk, ANIM_Yoshi_Red_Idle, 0, MSG_CH5_0043)
CaseLt(STORY_CH6_FLOWER_GATE_OPEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Red_Talk, ANIM_Yoshi_Red_Idle, 0, MSG_CH5_0044)
CaseDefault
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Red_Talk, ANIM_Yoshi_Red_Idle, 0, MSG_CH5_0045)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcIdle_Yoshi_01) = {
Loop(0)
Call(NpcMoveTo, NPC_SELF, -520, -270, 50)
Call(NpcMoveTo, NPC_SELF, -420, -270, 50)
EndLoop
Return
End
};
EvtScript N(EVS_NpcInit_Yoshi_01) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
IfEq(GF_JAN08_SavedYoshi, FALSE)
Call(SetNpcAnimation, NPC_SELF, ANIM_Yoshi_Red_Panic)
Call(BindNpcIdle, NPC_SELF, Ref(N(EVS_NpcIdle_Yoshi_01)))
EndIf
EndSwitch
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_Yoshi_01)))
Return
End
};
EvtScript N(EVS_NpcInteract_Yoshi_02) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Blue_Talk, ANIM_Yoshi_Blue_Idle, 0, MSG_CH5_0046)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
ExecWait(N(EVS_GetRescuedYoshiCount))
IfEq(LVar0, 0)
IfEq(GF_JAN03_AgreedToRescueChildren, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Blue_CryTalk, ANIM_Yoshi_Blue_Cry, 0, MSG_CH5_0047)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Blue_CryTalk, ANIM_Yoshi_Blue_Cry, 0, MSG_CH5_0048)
EndIf
Else
IfEq(GF_JAN10_SavedYoshi, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Blue_CryTalk, ANIM_Yoshi_Blue_Cry, 0, MSG_CH5_0049)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Blue_Talk, ANIM_Yoshi_Blue_Idle, 0, MSG_CH5_004A)
EndIf
EndIf
CaseLe(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Blue_Talk, ANIM_Yoshi_Blue_Idle, 0, MSG_CH5_004B)
CaseLt(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Blue_Talk, ANIM_Yoshi_Blue_Idle, 0, MSG_CH5_004C)
CaseLt(STORY_CH6_FLOWER_GATE_OPEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Blue_Talk, ANIM_Yoshi_Blue_Idle, 0, MSG_CH5_004D)
CaseDefault
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Blue_Talk, ANIM_Yoshi_Blue_Idle, 0, MSG_CH5_004E)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcIdle_Yoshi_02) = {
Loop(0)
Call(NpcMoveTo, NPC_SELF, 180, -520, 50)
Call(NpcMoveTo, NPC_SELF, 80, -520, 50)
EndLoop
Return
End
};
EvtScript N(EVS_NpcInit_Yoshi_02) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
IfEq(GF_JAN10_SavedYoshi, FALSE)
Call(SetNpcAnimation, NPC_SELF, ANIM_Yoshi_Blue_Panic)
Call(BindNpcIdle, NPC_SELF, Ref(N(EVS_NpcIdle_Yoshi_02)))
EndIf
EndSwitch
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_Yoshi_02)))
Return
End
};
EvtScript N(EVS_NpcInteract_Yoshi_03) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Purple_Talk, ANIM_Yoshi_Purple_Idle, 0, MSG_CH5_004F)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
ExecWait(N(EVS_GetRescuedYoshiCount))
IfEq(LVar0, 0)
IfEq(GF_JAN03_AgreedToRescueChildren, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Purple_CryTalk, ANIM_Yoshi_Purple_Cry, 0, MSG_CH5_0050)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Purple_CryTalk, ANIM_Yoshi_Purple_Cry, 0, MSG_CH5_0051)
EndIf
Else
IfEq(GF_JAN05_SavedYoshi, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Purple_CryTalk, ANIM_Yoshi_Purple_Cry, 0, MSG_CH5_0052)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Purple_Talk, ANIM_Yoshi_Purple_Idle, 0, MSG_CH5_0053)
EndIf
EndIf
CaseLe(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Purple_Talk, ANIM_Yoshi_Purple_Idle, 0, MSG_CH5_0054)
CaseLt(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Purple_Talk, ANIM_Yoshi_Purple_Idle, 0, MSG_CH5_0055)
CaseLt(STORY_CH6_FLOWER_GATE_OPEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Purple_Talk, ANIM_Yoshi_Purple_Idle, 0, MSG_CH5_0056)
CaseDefault
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Purple_Talk, ANIM_Yoshi_Purple_Idle, 0, MSG_CH5_0057)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcIdle_Yoshi_03) = {
Loop(0)
Call(NpcMoveTo, NPC_SELF, 600, -150, 50)
Call(NpcMoveTo, NPC_SELF, 500, -150, 50)
EndLoop
Return
End
};
EvtScript N(EVS_NpcInit_Yoshi_03) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
IfEq(GF_JAN05_SavedYoshi, FALSE)
Call(SetNpcAnimation, NPC_SELF, ANIM_Yoshi_Purple_Panic)
Call(BindNpcIdle, NPC_SELF, Ref(N(EVS_NpcIdle_Yoshi_03)))
EndIf
EndSwitch
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_Yoshi_03)))
Return
End
};
AnimID N(ExtraAnims_Councillor)[] = {
ANIM_LeadersFriend_TalkSit,
ANIM_LeadersFriend_TalkSitSad,
ANIM_LeadersFriend_IdleSit,
ANIM_LeadersFriend_BowSit,
ANIM_LIST_END
};
NpcData N(NpcData_Townsfolk)[] = {
{
.id = NPC_YoshiLeader,
.pos = { 323.0f, 30.0f, 412.0f },
.yaw = 270,
.init = &N(EVS_NpcInit_VillageLeader),
.settings = &N(NpcSettings_Yoshi),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST | ENEMY_FLAG_DO_NOT_AUTO_FACE_PLAYER,
.drops = NO_DROPS,
.animations = YOSHI_LEADER_ANIMS,
.tattle = MSG_NpcTattle_VillageLeader,
},
{
.id = NPC_YoshiCouncillor,
.pos = { 172.0f, 30.0f, 418.0f },
.yaw = 90,
.init = &N(EVS_NpcInit_Councillor),
.settings = &N(NpcSettings_Yoshi),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST | ENEMY_FLAG_DO_NOT_AUTO_FACE_PLAYER,
.drops = NO_DROPS,
.animations = YOSHI_COUNCILLOR_ANIMS,
.extraAnimations = N(ExtraAnims_Councillor),
.tattle = MSG_NpcTattle_LeadersFriend,
},
{
.id = NPC_Yoshi_01,
.pos = { -520.0f, 0.0f, -270.0f },
.yaw = 90,
.territory = {
.patrol = {
.isFlying = TRUE,
.moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED,
.numPoints = 2,
.points = {
{ -520, 0, -270 },
{ -420, 0, -270 },
},
.detectShape = SHAPE_CYLINDER,
.detectPos = { -520, 0, -270 },
.detectSize = { 100 },
}
},
.init = &N(EVS_NpcInit_Yoshi_01),
.settings = &N(NpcSettings_Yoshi_Patrol),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = YOSHI_RED_ANIMS,
.tattle = MSG_NpcTattle_EntranceYoshi,
},
{
.id = NPC_Yoshi_02,
.pos = { 180.0f, 0.0f, -520.0f },
.yaw = 270,
.territory = {
.patrol = {
.isFlying = TRUE,
.moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED,
.numPoints = 3,
.points = {
{ 180, 0, -520 },
{ 10, 0, -520 },
{ 100, 0, -600 },
},
.detectShape = SHAPE_CYLINDER,
.detectPos = { 5, 0, -554 },
.detectSize = { 100 },
}
},
.init = &N(EVS_NpcInit_Yoshi_02),
.settings = &N(NpcSettings_Yoshi_Patrol),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = YOSHI_BLUE_ANIMS,
.tattle = MSG_NpcTattle_BlueYoshi,
},
{
.id = NPC_Yoshi_03,
.pos = { 600.0f, 0.0f, -150.0f },
.yaw = 270,
.territory = {
.patrol = {
.isFlying = TRUE,
.moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED,
.numPoints = 2,
.points = {
{ 600, 0, -150 },
{ 485, 0, -220 },
},
.detectShape = SHAPE_CYLINDER,
.detectPos = { 600, 0, -150 },
.detectSize = { 100 },
}
},
.init = &N(EVS_NpcInit_Yoshi_03),
.settings = &N(NpcSettings_Yoshi_Patrol),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = YOSHI_PURPLE_ANIMS,
.tattle = MSG_NpcTattle_LikeableYoshi,
},
};
NpcData N(NpcData_ChuckQuizmo) = {
.id = NPC_ChuckQuizmo,
.pos = { -150.0f, 15.0f, 300.0f },
.yaw = 90,
.initVarCount = 1,
.initVar = { .bytes = { 0, QUIZ_AREA_JAN, QUIZ_COUNT_JAN, QUIZ_MAP_JAN_02 }},
.settings = &N(NpcSettings_ChuckQuizmo),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = QUIZMO_ANIMS,
.tattle = MSG_NpcTattle_ChuckQuizmo,
};
NpcGroupList N(DefaultNPCs) = {
NPC_GROUP(N(NpcData_Townsfolk)),
NPC_GROUP(N(NpcData_ChuckQuizmo)),
{}
};
| 412 | 0.862722 | 1 | 0.862722 | game-dev | MEDIA | 0.990626 | game-dev | 0.687585 | 1 | 0.687585 |
Kampfkarren/zombie-strike | 991 | src/shared/ReplicatedStorage/Core/Raycast.lua | local CollectionService = game:GetService("CollectionService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Workspace = game:GetService("Workspace")
local GetCharacter = require(ReplicatedStorage.Core.GetCharacter)
local function Raycast(position, direction, ignore)
local ray = Ray.new(position, direction)
local success
local h, p, n, humanoid
table.insert(ignore, Workspace.Effects)
repeat
h, p, n = Workspace:FindPartOnRayWithIgnoreList(ray, ignore)
if h then
local character = GetCharacter(h)
humanoid = character and character.Humanoid
if humanoid and humanoid.Health <= 0 then
humanoid = nil
end
if humanoid then
success = true
else
if (h.CanCollide and h.Transparency < 1)
or CollectionService:HasTag(h, "Hitbox")
then
success = true
else
table.insert(ignore, h)
success = false
end
end
else
success = true
end
until success
return h, p, n, humanoid
end
return Raycast
| 412 | 0.752852 | 1 | 0.752852 | game-dev | MEDIA | 0.898002 | game-dev,testing-qa | 0.851721 | 1 | 0.851721 |
Vrekt/LunarGdx | 15,670 | legacy/LunarWorld.java | package gdx.lunar.world;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Disposable;
import gdx.lunar.entity.LunarEntity;
import gdx.lunar.entity.drawing.Rotation;
import gdx.lunar.entity.network.NetworkEntity;
import gdx.lunar.entity.player.LunarEntityPlayer;
import gdx.lunar.entity.player.LunarNetworkEntityPlayer;
import gdx.lunar.network.AbstractConnection;
import gdx.lunar.protocol.packet.client.CPacketApplyEntityBodyForce;
import gdx.lunar.protocol.packet.client.CPacketRequestSpawnEntity;
import gdx.lunar.world.map.LunarNetworkedTile;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ThreadLocalRandom;
/**
* Represents a networked game world.
* <p>
* P = any local entity player instance type you wish.
* N = any local network entity instance type you wish
* E = any local entity instance type you wish
*/
public abstract class LunarWorld<P extends LunarEntityPlayer, N extends LunarNetworkEntityPlayer, E extends LunarEntity> implements Disposable {
protected ConcurrentMap<Integer, N> players = new ConcurrentHashMap<>();
protected ConcurrentMap<Integer, E> entities = new ConcurrentHashMap<>();
protected final P player;
protected final World world;
protected float worldScale;
protected boolean handlePhysics, updatePlayer, updateNetworkPlayers;
protected boolean updateEntities;
protected float stepTime = 1.0f / 60.0f;
protected float maxFrameTime = 0.25f;
protected float accumulator;
protected int velocityIterations = 8, positionIterations = 3;
// if this world is being used as a lobby.
protected int lobbyId;
protected final Vector2 worldSpawn = new Vector2(0, 0);
/**
* Initialize a new game world.
*
* @param player the player
* @param world the box2d world
* @param worldScale the scaling of the world.
* @param handlePhysics if true, this world will manage updating the Box2d world.
* @param updatePlayer if the local player should be updated.
* @param updateNetworkPlayers if network players should be updated.
* @param updateEntities if entities should be updated.
*/
public LunarWorld(LunarEntityPlayer player, World world, float worldScale,
boolean handlePhysics, boolean updatePlayer, boolean updateNetworkPlayers,
boolean updateEntities) {
this.player = player;
this.world = world;
this.worldScale = worldScale;
this.handlePhysics = handlePhysics;
this.updatePlayer = updatePlayer;
this.updateNetworkPlayers = updateNetworkPlayers;
this.updateEntities = updateEntities;
}
/**
* An empty default constructor. You should use the setters to define configuration next.
*
* @param player the player
* @param world the world
*/
public LunarWorld(LunarEntityPlayer player, World world) {
this.player = player;
this.world = world;
this.handlePhysics = true;
this.updatePlayer = true;
this.updateNetworkPlayers = true;
this.updateEntities = true;
}
public void setStepTime(float stepTime) {
this.stepTime = stepTime;
}
public float getStepTime() {
return stepTime;
}
public void setMaxFrameTime(float maxFrameTime) {
this.maxFrameTime = maxFrameTime;
}
public void setVelocityIterations(int velocityIterations) {
this.velocityIterations = velocityIterations;
}
public void setPositionIterations(int positionIterations) {
this.positionIterations = positionIterations;
}
public void setHandlePhysics(boolean handlePhysics) {
this.handlePhysics = handlePhysics;
}
public void setUpdatePlayer(boolean updatePlayer) {
this.updatePlayer = updatePlayer;
}
public void setUpdateNetworkPlayers(boolean updateNetworkPlayers) {
this.updateNetworkPlayers = updateNetworkPlayers;
}
public void setUpdateEntities(boolean updateEntities) {
this.updateEntities = updateEntities;
}
/**
* Allows you to use internal collections in your project.
* Should override {@code setPlayerInWorld}
*
* @param players c
*/
@SuppressWarnings("unchecked")
public <T extends LunarNetworkEntityPlayer> void setPlayersCollection(ConcurrentMap<Integer, T> players) {
this.players = (ConcurrentMap<Integer, LunarNetworkEntityPlayer>) players;
}
/**
* Allows you to use internal collections in your project.
* Should override {@code setPlayerInWorld}
*
* @param entities c
*/
@SuppressWarnings("unchecked")
public <T extends LunarEntity> void setEntitiesCollection(ConcurrentMap<Integer, T> entities) {
this.entities = (ConcurrentMap<Integer, LunarEntity>) entities;
}
public void setLobbyId(int lobbyId) {
this.lobbyId = lobbyId;
}
public int getLobbyId() {
return lobbyId;
}
/**
* @return the Box2d world.
*/
public World getPhysicsWorld() {
return world;
}
/**
* @return players in this world.
*/
public ConcurrentMap<Integer, LunarNetworkEntityPlayer> getPlayers() {
return players;
}
public Vector2 getWorldSpawn() {
return worldSpawn;
}
public void setWorldSpawn(Vector2 where) {
this.worldSpawn.set(where);
}
public void setWorldSpawn(float x, float y) {
this.worldSpawn.set(x, y);
}
/**
* Send the tiled map over the network.
*/
public void syncTiledMapOverNetwork() {
}
/**
* Tell other players about a networked tile
*
* @param tile the tile
*/
public void sendNetworkedTile(AbstractConnection connection, LunarNetworkedTile tile) {
}
/**
* Set player in this world
*
* @param player the player
*/
public void setPlayerInWorld(LunarNetworkEntityPlayer player) {
this.players.put(player.getEntityId(), player);
}
/**
* Set an entity in this world
*
* @param entity the entity
*/
public void setEntityInWorld(LunarEntity entity) {
this.entities.put(entity.getEntityId(), entity);
}
/**
* Set an entity in this world and broadcast to others.
*
* @param entity the entity
*/
public void setEntityInWorldNetwork(AbstractConnection connection, LunarEntity entity) {
// ensure we have a temporary entity ID before continuing.
if (entity.getEntityId() == 0) {
entity.setEntityId(ThreadLocalRandom.current().nextInt());
}
setEntityInWorld(entity);
connection.send(new CPacketRequestSpawnEntity(connection.alloc(), entity.getName(), entity.getX(), entity.getY(), entity.getEntityId()));
}
/**
* Check if a temporary entity exists by ID
*
* @param temporaryEntityId the temporary ID
* @param entityId the new entity ID
* @return {@code true} if so
*/
public boolean resetTemporaryEntityIfExists(int temporaryEntityId, int entityId) {
if (this.entities.containsKey(temporaryEntityId)) {
this.entities.get(temporaryEntityId).setEntityId(entityId);
return true;
}
return false;
}
/**
* The request was denied from the server, so remove it.
*
* @param temporaryEntityId the entity ID.
*/
public void removeTemporaryEntity(int temporaryEntityId) {
this.entities.remove(temporaryEntityId);
}
/**
* Set a networked entity in this world.
*
* @param entity the entity
*/
public void setEntityInWorld(NetworkEntity entity) {
this.entities.put(entity.getEntityId(), entity);
}
/**
* Remove a player from this world
*
* @param player the player
*/
public void removePlayerFromWorld(LunarNetworkEntityPlayer player) {
this.players.remove(player.getEntityId(), player);
}
/**
* Remove a player from this world
*
* @param player the player ID.
*/
public void removePlayerFromWorld(int player) {
this.players.remove(player);
}
/**
* Remove an entity from this world
*
* @param entity the entity
*/
public void removeEntityFromWorld(LunarEntity entity) {
this.entities.remove(entity.getEntityId(), entity);
}
/**
* Remove an entity from this world
*
* @param entity the entity ID
*/
public void removeEntityFromWorld(int entity) {
this.entities.remove(entity);
}
/**
* Get the position of a player
*
* @param player entity ID
* @return the position or {@code null} if no player matching the ID was found.
*/
public Vector2 getPositionOfPlayer(int player) {
final LunarNetworkEntityPlayer p = this.players.get(player);
if (p == null) return null;
return p.getPosition();
}
/**
* @param player the player
* @return the player or {@code null} if no player matching the ID was found.
*/
public LunarNetworkEntityPlayer getPlayer(int player) {
return this.players.get(player);
}
/**
* Apply force to the local players body and send over the network.
*
* @param connection the connection
* @param fx force X
* @param fy force Y
* @param px point X
* @param py point Y
* @param wake wake
*/
public void applyForceToPlayerNetwork(AbstractConnection connection, float fx, float fy, float px, float py, boolean wake) {
connection.send(new CPacketApplyEntityBodyForce(connection.alloc(), player.getEntityId(), fx, fy, px, py));
this.player.getBody().applyForce(fx, fy, px, py, wake);
}
/**
* Apply a force to another players body and send that over the network to others.
*
* @param player the player
* @param connection the connection
* @param fx force X
* @param fy force Y
* @param px point X
* @param py point Y
* @param wake wake
*/
public void applyForceToOtherPlayerNetwork(int player, AbstractConnection connection, float fx, float fy, float px, float py, boolean wake) {
applyForceToOtherPlayerNetwork(this.players.get(player), connection, fx, fy, px, py, wake);
}
/**
* Apply a force to another players body and send that over the network to others.
*
* @param player the player
* @param connection the connection to use
* @param fx force X
* @param fy force Y
* @param px point X
* @param py point Y
* @param wake wake
*/
public void applyForceToOtherPlayerNetwork(LunarNetworkEntityPlayer player, AbstractConnection connection, float fx, float fy, float px, float py, boolean wake) {
if (player == null) return;
connection.send(new CPacketApplyEntityBodyForce(connection.alloc(), player.getEntityId(), fx, fy, px, py));
player.getBody().applyForce(fx, fy, px, py, wake);
}
/**
* Apply a force to another entities body and send that over the network to others.
*
* @param entityId the entities ID
* @param connection the connection to use
* @param fx force X
* @param fy force Y
* @param px point X
* @param py point Y
* @param wake wake
*/
public void applyForceToEntityNetwork(int entityId, AbstractConnection connection, float fx, float fy, float px, float py, boolean wake) {
applyForceToEntityNetwork(this.entities.get(entityId), connection, fx, fy, px, py, wake);
}
/**
* Apply a force to another entities body and send that over the network to others.
*
* @param entity the entity
* @param connection the connection to use
* @param fx force X
* @param fy force Y
* @param px point X
* @param py point Y
* @param wake wake
*/
public void applyForceToEntityNetwork(LunarEntity entity, AbstractConnection connection, float fx, float fy, float px, float py, boolean wake) {
if (entity == null) return;
connection.send(new CPacketApplyEntityBodyForce(connection.alloc(), player.getEntityId(), fx, fy, px, py));
player.getBody().applyForce(fx, fy, px, py, wake);
}
/**
* Update a players position
*
* @param entityId the entity ID
* @param x x
* @param y y
* @param rotation rotation
*/
public void updatePlayerPosition(int entityId, float x, float y, int rotation) {
final LunarNetworkEntityPlayer player = players.get(entityId);
if (player != null) {
player.updatePositionFromNetwork(x, y, Rotation.values()[rotation]);
}
}
/**
* Update a players velocity
*
* @param entityId entity ID
* @param velocityX velocity X
* @param velocityY velocity Y
* @param rotation the rotation
*/
public void updatePlayerVelocity(int entityId, float velocityX, float velocityY, int rotation) {
final LunarNetworkEntityPlayer player = players.get(entityId);
if (player != null) {
player.updateVelocityFromNetwork(velocityX, velocityY, Rotation.values()[rotation]);
}
}
/**
* Update this world
*
* @param d delta time.
*/
public void update(float d) {
final float delta = Math.min(d, maxFrameTime);
if (handlePhysics) {
accumulator += delta;
while (accumulator >= stepTime) {
if (updateNetworkPlayers) {
for (LunarNetworkEntityPlayer value : players.values()) {
value.preUpdate();
}
}
player.preUpdate();
world.step(stepTime, velocityIterations, positionIterations);
accumulator -= stepTime;
}
}
if (updateEntities) for (LunarEntity value : entities.values()) value.update(delta);
if (updatePlayer) {
player.update(delta);
player.interpolate(0.5f);
}
if (updateNetworkPlayers) {
for (LunarNetworkEntityPlayer value : players.values()) {
value.update(delta);
value.interpolate(0.5f);
}
}
}
/**
* Step the internal physics world
*
* @param delta delta time
*/
public void stepPhysicsWorld(float delta) {
accumulator += delta;
while (accumulator >= stepTime) {
if (updateNetworkPlayers) {
for (LunarNetworkEntityPlayer value : players.values()) {
value.preUpdate();
}
}
player.preUpdate();
world.step(stepTime, velocityIterations, positionIterations);
accumulator -= stepTime;
}
}
/**
* Render this world
*
* @param batch the batch
* @param delta the delta
*/
public abstract void renderWorld(SpriteBatch batch, float delta);
@Override
public void dispose() {
this.players.clear();
this.world.dispose();
}
}
| 412 | 0.906964 | 1 | 0.906964 | game-dev | MEDIA | 0.870586 | game-dev | 0.866944 | 1 | 0.866944 |
SmartToolFactory/Animation-Tutorials | 5,809 | Tutorial3-1Transitions/src/main/java/com/smarttoolfactory/tutorial3_1transitions/transition/AlphaForcedTransition.kt | package com.smarttoolfactory.tutorial3_1transitions.transition
import android.animation.Animator
import android.animation.PropertyValuesHolder
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import androidx.transition.Transition
import androidx.transition.TransitionValues
import com.smarttoolfactory.tutorial3_1transitions.R
/**
*
* Transition that forces view state(property) to be set for starting and ending scenes.
*
* ``` transitionValues.values[PROPERTY_NAME] = property``` directly
* sets property on **View** after capturing start values which causes
* [captureEndValues] to be invoked with different set of values.
*
* * If starting scene and ending scene is equal in alpha this transition will not start because
* [captureEndValues] will not capture anything other than start values.
*
*/
class AlphaForcedTransition : Transition {
private var startAlpha: Float = 0f
private var endAlpha: Float = 1f
/**
* Forces start end values to be set on view such as setting a view's visibility as View.VISIBLE
* at start and View.INVISIBLE for the end scene which forces scenes to have different values
* and transition to start.
*
* * Has public visibility to debug scenes with [debugMode], with and without forced values.
*/
var forceValues: Boolean = true
/**
* Logs lifecycle and parameters to console when set to true
*/
var debugMode = false
constructor(startAlpha: Float, endAlpha: Float, forceValues: Boolean = true) {
this.startAlpha = startAlpha
this.endAlpha = endAlpha
this.forceValues = forceValues
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
val a = context.obtainStyledAttributes(attrs, R.styleable.CustomAlphaTransition)
startAlpha = a.getFloat(R.styleable.CustomAlphaTransition_startAlpha, startAlpha)
endAlpha = a.getFloat(R.styleable.CustomAlphaTransition_endAlpha, endAlpha)
a.recycle()
}
override fun captureStartValues(transitionValues: TransitionValues) {
if (forceValues) {
transitionValues.view?.alpha = startAlpha
}
captureValues(transitionValues)
if (debugMode) {
println("⚠️ ${this::class.java.simpleName} captureStartValues() view: ${transitionValues.view} ")
transitionValues.values.forEach { (key, value) ->
println("Key: $key, value: $value")
}
}
if (forceValues) {
transitionValues.view?.alpha = endAlpha
}
}
// Capture the value of property for a target in the ending Scene.
override fun captureEndValues(transitionValues: TransitionValues) {
captureValues(transitionValues)
if (debugMode) {
println("🔥 ${this::class.java.simpleName} captureEndValues() view: ${transitionValues.view} ")
transitionValues.values.forEach { (key, value) ->
println("Key: $key, value: $value")
}
}
}
private fun captureValues(transitionValues: TransitionValues) {
transitionValues.values[PROP_NAME_ALPHA] = transitionValues.view.alpha
}
private fun createForcedAnimator(
sceneRoot: ViewGroup,
startValues: TransitionValues?,
endValues: TransitionValues?
): Animator? {
if (startAlpha == endAlpha) return null // no alpha to run
val view = when {
startValues?.view != null -> {
startValues.view
}
endValues?.view != null -> {
endValues.view
}
else -> {
return null
}
}
val propAlpha =
PropertyValuesHolder.ofFloat(PROP_NAME_ALPHA, startAlpha, endAlpha)
val valAnim = ValueAnimator.ofPropertyValuesHolder(propAlpha)
valAnim.addUpdateListener { valueAnimator ->
view.alpha = valueAnimator.getAnimatedValue(PROP_NAME_ALPHA) as Float
}
return valAnim
}
private fun createTransitionAnimator(
sceneRoot: ViewGroup,
startValues: TransitionValues?,
endValues: TransitionValues?
): Animator? {
if (endValues == null || startValues == null) return null // no values
val startAlpha = startValues.values[PROP_NAME_ALPHA] as Float
val endAlpha = endValues.values[PROP_NAME_ALPHA] as Float
if (startAlpha == endAlpha) return null // no alpha to run
val view = startValues.view
val propAlpha =
PropertyValuesHolder.ofFloat(PROP_NAME_ALPHA, startAlpha, endAlpha)
val valAnim = ValueAnimator.ofPropertyValuesHolder(propAlpha)
valAnim.addUpdateListener { valueAnimator ->
view.alpha = valueAnimator.getAnimatedValue(PROP_NAME_ALPHA) as Float
}
return valAnim
}
override fun createAnimator(
sceneRoot: ViewGroup,
startValues: TransitionValues?,
endValues: TransitionValues?
): Animator? {
if (debugMode) {
println(
"🎃 ${this::class.java.simpleName} createAnimator() " +
"forceValues: $forceValues" +
"\nSCENE ROOT: $sceneRoot" +
"\nSTART VALUES: $startValues" +
"\nEND VALUES: $endValues "
)
}
return if (forceValues) {
createForcedAnimator(sceneRoot, startValues, endValues)
} else {
createTransitionAnimator(sceneRoot, startValues, endValues)
}
}
companion object {
private const val PROP_NAME_ALPHA = "android:custom:alpha"
}
} | 412 | 0.804769 | 1 | 0.804769 | game-dev | MEDIA | 0.28521 | game-dev | 0.929495 | 1 | 0.929495 |
CurativeTree/BuildCraft | 5,816 | src/main/java/ct/buildcraft/lib/expression/node/func/gen/NodeFuncLongLongLongToObject.java | /*
* Copyright (c) 2017 SpaceToad and the BuildCraft team
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/
*/
package ct.buildcraft.lib.expression.node.func.gen;
import java.util.Objects;
import ct.buildcraft.lib.expression.NodeInliningHelper;
import ct.buildcraft.lib.expression.api.IDependantNode;
import ct.buildcraft.lib.expression.api.IDependancyVisitor;
import ct.buildcraft.lib.expression.api.IExpressionNode.INodeBoolean;
import ct.buildcraft.lib.expression.api.IExpressionNode.INodeDouble;
import ct.buildcraft.lib.expression.api.IExpressionNode.INodeLong;
import ct.buildcraft.lib.expression.api.IExpressionNode.INodeObject;
import ct.buildcraft.lib.expression.api.INodeFunc.INodeFuncObject;
import ct.buildcraft.lib.expression.api.INodeStack;
import ct.buildcraft.lib.expression.api.InvalidExpressionException;
import ct.buildcraft.lib.expression.api.NodeTypes;
import ct.buildcraft.lib.expression.node.func.StringFunctionQuad;
import ct.buildcraft.lib.expression.node.func.NodeFuncBase;
import ct.buildcraft.lib.expression.node.func.NodeFuncBase.IFunctionNode;
import ct.buildcraft.lib.expression.node.value.NodeConstantObject;
// AUTO_GENERATED FILE, DO NOT EDIT MANUALLY!
public class NodeFuncLongLongLongToObject<R> extends NodeFuncBase implements INodeFuncObject<R> {
public final IFuncLongLongLongToObject<R> function;
private final StringFunctionQuad stringFunction;
private final Class<R> returnType;
public NodeFuncLongLongLongToObject(String name, Class<R> returnType, IFuncLongLongLongToObject<R> function) {
this(returnType, function, (a, b, c) -> "[ long, long, long -> " + NodeTypes.getName(returnType) + " ] " + name + "(" + a + ", " + b + ", " + c + ")");
}
public NodeFuncLongLongLongToObject(Class<R> returnType, IFuncLongLongLongToObject<R> function, StringFunctionQuad stringFunction) {
this.returnType = returnType;
this.function = function;
this.stringFunction = stringFunction;
}
@Override
public Class<R> getType() {
return returnType;
}
@Override
public String toString() {
return stringFunction.apply("{A}", "{B}", "{C}");
}
@Override
public NodeFuncLongLongLongToObject<R> setNeverInline() {
super.setNeverInline();
return this;
}
@Override
public INodeObject<R> getNode(INodeStack stack) throws InvalidExpressionException {
INodeLong c = stack.popLong();
INodeLong b = stack.popLong();
INodeLong a = stack.popLong();
return create(a, b, c);
}
/** Shortcut to create a new {@link FuncLongLongLongToObject} without needing to create
* and populate an {@link INodeStack} to pass to {@link #getNode(INodeStack)}. */
public FuncLongLongLongToObject create(INodeLong argA, INodeLong argB, INodeLong argC) {
return new FuncLongLongLongToObject(argA, argB, argC);
}
public class FuncLongLongLongToObject implements INodeObject<R>, IDependantNode, IFunctionNode {
public final INodeLong argA;
public final INodeLong argB;
public final INodeLong argC;
public FuncLongLongLongToObject(INodeLong argA, INodeLong argB, INodeLong argC) {
this.argA = argA;
this.argB = argB;
this.argC = argC;
}
@Override
public Class<R> getType() {
return returnType;
}
@Override
public R evaluate() {
return function.apply(argA.evaluate(), argB.evaluate(), argC.evaluate());
}
@Override
public INodeObject<R> inline() {
if (!canInline) {
// Note that we can still inline the arguments, just not *this* function
return NodeInliningHelper.tryInline(this, argA, argB, argC,
(a, b, c) -> new FuncLongLongLongToObject(a, b, c),
(a, b, c) -> new FuncLongLongLongToObject(a, b, c)
);
}
return NodeInliningHelper.tryInline(this, argA, argB, argC,
(a, b, c) -> new FuncLongLongLongToObject(a, b, c),
(a, b, c) -> new NodeConstantObject<>(returnType, function.apply(a.evaluate(), b.evaluate(), c.evaluate()))
);
}
@Override
public void visitDependants(IDependancyVisitor visitor) {
if (!canInline) {
if (function instanceof IDependantNode) {
visitor.dependOn((IDependantNode) function);
} else {
visitor.dependOnExplictly(this);
}
}
visitor.dependOn(argA, argB, argC);
}
@Override
public String toString() {
return stringFunction.apply(argA.toString(), argB.toString(), argC.toString());
}
@Override
public NodeFuncBase getFunction() {
return NodeFuncLongLongLongToObject.this;
}
@Override
public int hashCode() {
return Objects.hash(argA, argB, argC);
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || getClass() != obj.getClass()) {
return false;
}
FuncLongLongLongToObject other = (FuncLongLongLongToObject) obj;
return Objects.equals(argA, other.argA) //
&&Objects.equals(argB, other.argB) //
&&Objects.equals(argC, other.argC);
}
}
@FunctionalInterface
public interface IFuncLongLongLongToObject<R> {
R apply(long a, long b, long c);
}
}
| 412 | 0.83208 | 1 | 0.83208 | game-dev | MEDIA | 0.773865 | game-dev | 0.824227 | 1 | 0.824227 |
datvm/TimberbornMods | 3,451 | EarthquakeWeather/Weathers/Earthquake.cs | namespace EarthquakeWeather.Weathers;
public class Earthquake(
EarthquakeWeatherSettings settings,
ModdableWeatherSpecService moddableWeatherSpecService,
ISingletonLoader loader,
IDayNightCycle dayNightCycle,
EarthquakeNotificationService earthquakeNotif
) : DefaultModdedWeather<EarthquakeWeatherSettings>(settings, moddableWeatherSpecService),
IModdedHazardousWeather, ISaveableSingleton, ITickableSingleton
{
static readonly SingletonKey SaveKey = new("EarthquakeWeather");
static readonly PropertyKey<Vector2Int> DamageStrengthKey = new("DamageStrength");
static readonly PropertyKey<float> NextHitKey = new("NextHit");
public const string WeatherId = "Earthquake";
public override string Id { get; } = WeatherId;
public Vector2Int DamageStrength { get; private set; }
public float SurgeStrength { get; private set; }
public float NextHit { get; private set; }
public event Action? OnEarthquakeHit;
public override int GetDurationAtCycle(int cycle, ModdableWeatherHistoryProvider history)
{
var parameters = Settings.Parameters;
var handicap = ModdableWeatherUtils.CalculateHandicap(
history.GetWeatherCycleCount(Id),
parameters.HandicapCycles,
() => parameters.HandicapPerc);
DamageStrength = new(
Mathf.FloorToInt(Settings.MinStrength.Value * handicap),
Mathf.FloorToInt(Settings.MaxStrength.Value * handicap)
);
CalculateSurgeStrength();
ModdableWeatherUtils.Log(() => $"Earthquake Weather at cycle {cycle} has: Damage = {DamageStrength} (handicap: {handicap:#%}).");
return base.GetDurationAtCycle(cycle, history);
}
public override void Load()
{
base.Load();
CalculateSurgeStrength();
LoadSavedData();
if (DamageStrength == default)
{
// Only happen while testing/editting in editor
DamageStrength = new(Settings.MinStrength.Value, Settings.MaxStrength.Value);
}
}
void LoadSavedData()
{
if (!loader.TryGetSingleton(SaveKey, out var s)) { return; }
if (s.Has(DamageStrengthKey))
{
DamageStrength = s.Get(DamageStrengthKey);
}
if (s.Has(NextHitKey))
{
NextHit = s.Get(NextHitKey);
}
}
public void Save(ISingletonSaver singletonSaver)
{
var s = singletonSaver.GetSingleton(SaveKey);
s.Set(DamageStrengthKey, DamageStrength);
s.Set(NextHitKey, NextHit);
}
float CalculateSurgeStrength() => SurgeStrength = Settings.SurgeStr.Value / 100f;
public override void Start(bool onLoad)
{
if (!onLoad)
{
ScheduleNextHit();
}
base.Start(onLoad);
}
public void Tick()
{
if (!Active || NextHit > dayNightCycle.PartialDayNumber) { return; }
Hit();
}
public void Hit()
{
earthquakeNotif.Clear();
OnEarthquakeHit?.Invoke();
ScheduleNextHit();
earthquakeNotif.ShowNotification();
}
void ScheduleNextHit()
{
var delay = UnityEngine.Random.Range(Settings.MinFrequency.Value, Settings.MaxFrequency.Value);
NextHit = dayNightCycle.PartialDayNumber + delay;
ModdableWeatherUtils.Log(() => $"Next earthquake hit scheduled at day {NextHit:0.00} (in {delay:0.00} days)");
}
}
| 412 | 0.920178 | 1 | 0.920178 | game-dev | MEDIA | 0.754723 | game-dev | 0.94855 | 1 | 0.94855 |
azerothcore/Keira3 | 1,345 | libs/features/gameobject/src/gameobject-loot-template/gameobject-loot-template.service.ts | import { Injectable, inject } from '@angular/core';
import { LootEditorIdService } from '@keira/shared/base-abstract-classes';
import {
GAMEOBJECT_LOOT_TEMPLATE_TABLE,
GAMEOBJECT_TEMPLATE_ID,
GAMEOBJECT_TEMPLATE_LOOT_ID,
GAMEOBJECT_TEMPLATE_TABLE,
GAMEOBJECT_TEMPLATE_TYPE,
GameobjectLootTemplate,
} from '@keira/shared/acore-world-model';
import { Observable } from 'rxjs';
import { GameobjectHandlerService } from '../gameobject-handler.service';
@Injectable({
providedIn: 'root',
})
export class GameobjectLootTemplateService extends LootEditorIdService<GameobjectLootTemplate> {
protected override readonly handlerService = inject(GameobjectHandlerService);
protected override _entityClass = GameobjectLootTemplate;
protected override _entityTable = GAMEOBJECT_LOOT_TEMPLATE_TABLE;
protected override _entityTemplateTable = GAMEOBJECT_TEMPLATE_TABLE;
protected override _entityTemplateIdField = GAMEOBJECT_TEMPLATE_ID;
protected override _entityTemplateLootField = GAMEOBJECT_TEMPLATE_LOOT_ID;
constructor() {
super();
this.init();
}
getType(): Observable<{ type: number }[]> {
return this.queryService.query(
`SELECT ${GAMEOBJECT_TEMPLATE_TYPE} ` +
`FROM ${GAMEOBJECT_TEMPLATE_TABLE} ` +
`WHERE ${GAMEOBJECT_TEMPLATE_ID} = ${this.handlerService.selected}`,
);
}
}
| 412 | 0.88659 | 1 | 0.88659 | game-dev | MEDIA | 0.889691 | game-dev | 0.819285 | 1 | 0.819285 |
MistakesMultiplied/cathook | 1,596 | external/source-sdk-2013-headers/mp/src/game/client/fx_fleck.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================//
#if !defined( FXFLECKS_H )
#define FXFLECKS_H
#ifdef _WIN32
#pragma once
#endif
#include "particles_simple.h"
#include "particlemgr.h"
#include "particle_collision.h"
// FleckParticle
class FleckParticle : public Particle
{
public:
Vector m_vecVelocity;
float m_flRoll;
float m_flRollDelta;
float m_flDieTime; // How long it lives for.
float m_flLifetime; // How long it has been alive for so far.
byte m_uchColor[3];
byte m_uchSize;
};
//
// CFleckParticles
//
class CFleckParticles : public CSimpleEmitter
{
public:
CFleckParticles( const char *pDebugName );
~CFleckParticles();
static CSmartPtr<CFleckParticles> Create( const char *pDebugName, const Vector &vCenter, const Vector &extents );
virtual void RenderParticles( CParticleRenderIterator *pIterator );
virtual void SimulateParticles( CParticleSimulateIterator *pIterator );
//Setup for point emission
virtual void Setup( const Vector &origin, const Vector *direction, float angularSpread, float minSpeed, float maxSpeed, float gravity, float dampen, int flags = 0 );
CParticleCollision m_ParticleCollision;
CFleckParticles *m_pNextParticleSystem;
private:
CFleckParticles( const CFleckParticles & ); // not defined, not accessible
};
#endif //FXFLECKS_H | 412 | 0.880695 | 1 | 0.880695 | game-dev | MEDIA | 0.738273 | game-dev,graphics-rendering | 0.538205 | 1 | 0.538205 |
corporateshark/Mastering-Android-NDK | 2,247 | Chapter7/1_SDL2UI/jni/SDL/src/loadso/dlopen/SDL_sysloadso.c | /*
Simple DirectMedia Layer
Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
#ifdef SDL_LOADSO_DLOPEN
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* System dependent library loading routines */
#include <stdio.h>
#include <dlfcn.h>
#include "SDL_loadso.h"
void *
SDL_LoadObject(const char *sofile)
{
void *handle = dlopen(sofile, RTLD_NOW|RTLD_LOCAL);
const char *loaderror = (char *) dlerror();
if (handle == NULL) {
SDL_SetError("Failed loading %s: %s", sofile, loaderror);
}
return (handle);
}
void *
SDL_LoadFunction(void *handle, const char *name)
{
void *symbol = dlsym(handle, name);
if (symbol == NULL) {
/* append an underscore for platforms that need that. */
size_t len = 1 + SDL_strlen(name) + 1;
char *_name = SDL_stack_alloc(char, len);
_name[0] = '_';
SDL_strlcpy(&_name[1], name, len);
symbol = dlsym(handle, _name);
SDL_stack_free(_name);
if (symbol == NULL) {
SDL_SetError("Failed loading %s: %s", name,
(const char *) dlerror());
}
}
return (symbol);
}
void
SDL_UnloadObject(void *handle)
{
if (handle != NULL) {
dlclose(handle);
}
}
#endif /* SDL_LOADSO_DLOPEN */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.744164 | 1 | 0.744164 | game-dev | MEDIA | 0.306486 | game-dev | 0.500977 | 1 | 0.500977 |
copperwater/xNetHack | 33,142 | src/bones.c | /* NetHack 3.7 bones.c $NHDT-Date: 1701500709 2023/12/02 07:05:09 $ $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.129 $ */
/* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985,1993. */
/*-Copyright (c) Robert Patrick Rankin, 2012. */
/* NetHack may be freely redistributed. See license for details. */
#include "hack.h"
staticfn boolean no_bones_level(d_level *);
staticfn void goodfruit(int);
staticfn void resetobjs(struct obj *, boolean);
staticfn void give_to_nearby_mon(struct obj *, coordxy, coordxy) NONNULLARG1;
staticfn boolean fixuporacle(struct monst *) NONNULLARG1;
staticfn void remove_mon_from_bones(struct monst *) NONNULLARG1;
staticfn void set_ghostly_objlist(struct obj *objchain);
staticfn boolean
no_bones_level(d_level *lev)
{
s_level *sptr;
if (ledger_no(&gs.save_dlevel))
assign_level(lev, &gs.save_dlevel);
return (boolean) (((sptr = Is_special(lev)) != 0 && !sptr->boneid)
|| !svd.dungeons[lev->dnum].boneid
/* no bones on the last or multiway branch levels
in any dungeon (level 1 isn't multiway) */
|| Is_botlevel(lev)
|| (Is_branchlev(lev) && lev->dlevel > 1)
/* no bones in the invocation level */
|| Invocation_lev(lev));
}
/* Call this function for each fruit object saved in the bones level: it marks
* that particular type of fruit as existing (the marker is that that type's
* ID is positive instead of negative). This way, when we later save the
* chain of fruit types, we know to only save the types that exist.
*/
staticfn void
goodfruit(int id)
{
struct fruit *f = fruit_from_indx(-id);
if (f)
f->fid = id;
}
staticfn void
resetobjs(struct obj *ochain, boolean restore)
{
struct obj *otmp, *nobj;
for (otmp = ochain; otmp; otmp = nobj) {
nobj = otmp->nobj;
if (otmp->cobj)
resetobjs(otmp->cobj, restore);
if (otmp->in_use) {
obj_extract_self(otmp);
dealloc_obj(otmp);
continue;
}
if (restore) {
/* artifact bookkeeping needs to be done during
restore; other fixups are done while saving */
if (otmp->oartifact) {
if (exist_artifact(otmp->otyp, safe_oname(otmp))
|| is_quest_artifact(otmp)) {
/* prevent duplicate--revert to ordinary obj */
otmp->oartifact = 0;
if (has_oname(otmp))
free_oname(otmp);
} else {
artifact_exists(otmp, safe_oname(otmp), TRUE,
ONAME_BONES);
}
} else if (has_oname(otmp)) {
sanitize_name(ONAME(otmp));
}
/* prevent materials from differing on things like rings */
if (!valid_obj_material(otmp, otmp->material)) {
set_material(otmp, objects[otmp->otyp].oc_material);
}
/* 3.6.3: set no_charge for partly eaten food in shop;
all other items become goods for sale if in a shop */
if (otmp->oclass == FOOD_CLASS && otmp->oeaten) {
struct obj *top;
char *p;
coordxy ox, oy;
for (top = otmp; top->where == OBJ_CONTAINED;
top = top->ocontainer)
continue;
otmp->no_charge = (top->where == OBJ_FLOOR
&& get_obj_location(top, &ox, &oy, 0)
/* can't use costly_spot() since its
result depends upon hero's location */
&& inside_shop(ox, oy)
&& *(p = in_rooms(ox, oy, SHOPBASE))
&& tended_shop(&svr.rooms[*p - ROOMOFFSET]));
}
if (otmp->otyp == THIEFSTONE && thiefstone_ledger_valid(otmp)) {
/* x and y should already be set to an appropriate location on
* this level by the save code; all we need to do is set the
* ledger; no handling necessary for cancelled stones */
otmp->keyed_ledger = ledger_no(&u.uz);
}
} else { /* saving */
/* do not zero out o_ids for ghost levels anymore */
if (objects[otmp->otyp].oc_uses_known)
otmp->known = 0;
otmp->dknown = otmp->bknown = 0;
otmp->rknown = 0;
otmp->lknown = 0;
otmp->cknown = 0;
otmp->tknown = 0;
otmp->invlet = 0;
otmp->no_charge = 0;
otmp->how_lost = LOST_NONE;
/* strip user-supplied names */
/* Statue and some corpse names are left intact,
presumably in case they came from score file.
[TODO: this ought to be done differently--names
which came from such a source or came from any
stoned or killed monster should be flagged in
some manner; then we could just check the flag
here and keep "real" names (dead pets, &c) while
discarding player notes attached to statues.] */
if (has_oname(otmp)
&& !(otmp->oartifact || otmp->otyp == STATUE
|| otmp->otyp == SPE_NOVEL
|| (otmp->otyp == CORPSE
&& otmp->corpsenm >= SPECIAL_PM))) {
free_oname(otmp);
}
if (otmp->otyp == SLIME_MOLD) {
goodfruit(otmp->spe);
#ifdef MAIL_STRUCTURES
} else if (otmp->otyp == SCR_MAIL) {
/* 0: delivered in-game via external event;
1: from bones or wishing; 2: written with marker */
if (otmp->spe == 0)
otmp->spe = 1;
#endif
} else if (otmp->otyp == EGG) {
otmp->spe = 0; /* not "laid by you" in next game */
} else if (otmp->otyp == TIN) {
/* make tins of unique monster's meat be empty */
if (ismnum(otmp->corpsenm)
&& unique_corpstat(&mons[otmp->corpsenm]))
otmp->corpsenm = NON_PM;
} else if (otmp->otyp == CORPSE || otmp->otyp == STATUE) {
int mnum = otmp->corpsenm;
/* Discard incarnation details of unique monsters
(by passing null instead of otmp for object),
shopkeepers (by passing false for revival flag),
temple priests, and vault guards in order to
prevent corpse revival or statue reanimation. */
if (has_omonst(otmp)
&& cant_revive(&mnum, FALSE, (struct obj *) 0)) {
free_omonst(otmp);
/* mnum is now either human_zombie or doppelganger;
for corpses of uniques, we need to force the
transformation now rather than wait until a
revival attempt, otherwise eating this corpse
would behave as if it remains unique */
if (mnum == PM_DOPPELGANGER && otmp->otyp == CORPSE)
set_corpsenm(otmp, mnum);
}
} else if (is_mines_prize(otmp) || is_soko_prize(otmp)) {
/* achievement tracking; in case prize was moved off its
original level (which is always a no-bones level) */
otmp->nomerge = 0;
} else if (otmp->otyp == AMULET_OF_YENDOR) {
/* no longer the real Amulet */
otmp->otyp = FAKE_AMULET_OF_YENDOR;
set_material(otmp, PLASTIC);
curse(otmp);
} else if (otmp->otyp == CANDELABRUM_OF_INVOCATION) {
if (otmp->lamplit)
end_burn(otmp, TRUE);
otmp->otyp = WAX_CANDLE;
set_material(otmp, WAX);
otmp->age = 50L; /* assume used */
if (otmp->spe > 0)
otmp->quan = (long) otmp->spe;
otmp->spe = 0;
otmp->owt = weight(otmp);
curse(otmp);
} else if (otmp->otyp == BELL_OF_OPENING) {
otmp->otyp = BELL;
set_material(otmp, SILVER);
curse(otmp);
} else if (otmp->otyp == SPE_BOOK_OF_THE_DEAD) {
otmp->otyp = SPE_BLANK_PAPER;
curse(otmp);
} else if (otmp->otyp == THIEFSTONE) {
if (thiefstone_ledger_valid(otmp)) {
if (otmp->keyed_ledger != ledger_no(&u.uz)) {
/* keyed to some other level -- its x and y are
* meaningless since that other level doesn't come along
* with the bones file; instead re-key the stone to
* somewhere on this level. */
coord cc;
choose_thiefstone_loc(&cc); /* find suitable new location */
set_keyed_loc(otmp, cc.x, cc.y);
}
/* the ledger from the old game is meaningless in the new
* game; set to something that should always be valid so the
* restore code can just test for validity */
otmp->keyed_ledger = 1;
}
else {
/* it ought to be this already but just to be sure... */
otmp->keyed_ledger = THIEFSTONE_LEDGER_CANCELLED;
}
}
}
}
}
/* while loading bones, strip out text possibly supplied by old player
that might accidentally or maliciously disrupt new player's display */
void
sanitize_name(char *namebuf)
{
int c;
boolean strip_8th_bit = (WINDOWPORT(tty)
&& !iflags.wc_eight_bit_input);
/* it's tempting to skip this for single-user platforms, since
only the current player could have left these bones--except
things like "hearse" and other bones exchange schemes make
that assumption false */
while (*namebuf) {
c = *namebuf & 0177;
if (c < ' ' || c == '\177') {
/* non-printable or undesirable */
*namebuf = '.';
} else if (c != *namebuf) {
/* expected to be printable if user wants such things */
if (strip_8th_bit)
*namebuf = '_';
}
++namebuf;
}
}
/* The hero has just died and is dropping their possessions.
* Nearby monsters may take some of them.
* Currently, this is only for directly adjacent monsters to avoid silliness
* like monsters on the other side of a wall getting some of the items.
* If there is no nearby monster, just drop the item. */
/* Give object to a random object-liking monster on or adjacent to x,y
but skipping hero's location.
If no such monster, place object on floor at x,y. */
staticfn void
give_to_nearby_mon(struct obj *otmp, coordxy x, coordxy y)
{
struct monst *mtmp;
struct monst *selected = (struct monst *) 0;
int nmon = 0, xx, yy;
for (xx = x - 1; xx <= x + 1; ++xx) {
for (yy = y - 1; yy <= y + 1; ++yy) {
if (!isok(xx, yy))
continue;
if (u_at(xx, yy))
continue;
if (!(mtmp = m_at(xx, yy)))
continue;
/* This doesn't do any checks on otmp to see that it matches the
* likes_* property, intentionally. Assume that the monster is
* rifling through and taking things that look interesting. */
if (!(likes_gold(mtmp->data) || likes_gems(mtmp->data)
|| likes_objs(mtmp->data) || likes_magic(mtmp->data)))
continue;
nmon++;
if (!rn2(nmon))
selected = mtmp;
}
}
if (selected && can_carry(selected, otmp))
add_to_minv(selected, otmp);
else
place_object(otmp, x, y);
}
/* called by savebones(); also by finish_paybill(shk.c) */
void
drop_upon_death(
struct monst *mtmp, /* monster if hero rises as one (non ghost) */
struct obj *cont, /* container if hero is turned into a statue */
coordxy x, coordxy y)
{
struct obj *otmp;
/* when dual-wielding, the second weapon gets dropped rather than
welded if it becomes cursed; ensure that that won't happen here
by ending dual-wield */
u.twoweap = FALSE; /* bypass set_twoweap() */
/* all inventory is dropped (for the normal case), even non-droppable
things like worn armor and accessories, welded weapon, or cursed
loadstones */
while ((otmp = gi.invent) != 0) {
obj_extract_self(otmp);
/* when turning into green slime, all gear remains held;
other types "arise from the dead" do aren't holding
equipment during their brief interval as a corpse */
if (!mtmp || is_undead(mtmp->data))
obj_no_longer_held(otmp);
/* lamps don't go out when dropped */
if ((cont || artifact_light(otmp)) && obj_is_burning(otmp))
end_burn(otmp, TRUE); /* smother in statue */
otmp->owornmask = 0L;
/* undo any armor weight reduction if it was worn */
otmp->owt = weight(otmp);
if (otmp->otyp == SLIME_MOLD)
goodfruit(otmp->spe);
if (rn2(5))
curse(otmp);
if (mtmp)
(void) add_to_minv(mtmp, otmp);
else if (cont)
(void) add_to_container(cont, otmp);
else if (!rn2(8))
give_to_nearby_mon(otmp, x, y);
else
place_object(otmp, x, y);
}
if (cont)
cont->owt = weight(cont);
}
/* possibly restore oracle's room and/or put her back inside it; returns
False if she's on the wrong level and should be removed, True otherwise */
staticfn boolean
fixuporacle(struct monst *oracle)
{
coord cc;
int ridx, o_ridx;
/* oracle doesn't move, but knight's joust or monk's staggering blow
could push her onto a hole in the floor; at present, traps don't
activate in such situation hence she won't fall to another level;
however, that could change so be prepared to cope with such things */
if (!Is_oracle_level(&u.uz))
return FALSE;
oracle->mpeaceful = 1; /* for behavior toward next character */
o_ridx = levl[oracle->mx][oracle->my].roomno - ROOMOFFSET;
if (o_ridx >= 0 && svr.rooms[o_ridx].rtype == DELPHI)
return TRUE; /* no fixup needed */
/*
* The Oracle isn't in DELPHI room. Either hero entered her chamber
* and got the one-time welcome message, converting it into an
* ordinary room, or she got teleported out, or both. Try to put
* her back inside her room, if necessary, and restore its type.
*/
/* find original delphi chamber; should always succeed */
for (ridx = 0; ridx < SIZE(svr.rooms); ++ridx)
if (svr.rooms[ridx].orig_rtype == DELPHI)
break;
if (o_ridx != ridx && ridx < SIZE(svr.rooms)) {
/* room found and she's not in it, so try to move her there */
cc.x = (svr.rooms[ridx].lx + svr.rooms[ridx].hx) / 2;
cc.y = (svr.rooms[ridx].ly + svr.rooms[ridx].hy) / 2;
if (enexto(&cc, cc.x, cc.y, oracle->data)) {
rloc_to(oracle, cc.x, cc.y);
o_ridx = levl[oracle->mx][oracle->my].roomno - ROOMOFFSET;
}
/* [if her room is already full, she might end up outside;
that's ok, next hero just won't get any welcome message,
same as used to happen before this fixup was introduced] */
}
if (ridx == o_ridx) /* if she's in her room, mark it as such */
svr.rooms[ridx].rtype = DELPHI;
return TRUE; /* keep oracle in new bones file */
}
/* check whether bones are feasible on this level; not whether bones *will* be
* made from this level, but whether bones *could* be made from this level */
boolean
can_make_bones(void)
{
struct trap *ttmp;
if (!flags.bones || Polyinit_mode)
return FALSE;
if (ledger_no(&u.uz) <= 0 || ledger_no(&u.uz) > maxledgerno())
return FALSE;
if (no_bones_level(&u.uz))
return FALSE; /* no bones for specific levels */
if (u.uswallow) {
return FALSE; /* no bones when swallowed */
}
if (is_open_air(u.ux, u.uy))
return FALSE; /* possessions would all fall to another level; rest of
this level probably isn't very interesting as bones */
if (svl.level.flags.visited_after_event)
return FALSE; /* the level has probably been transformed in some way
that someone else shouldn't get when seeing it for the
first time */
if (!Is_branchlev(&u.uz)) {
/* no bones on non-branches with portals */
for (ttmp = gf.ftrap; ttmp; ttmp = ttmp->ntrap)
if (ttmp->ttyp == MAGIC_PORTAL)
return FALSE;
}
/* don't let multiple restarts generate multiple copies of objects
in bones files */
if (discover)
return FALSE;
return TRUE;
}
/* monster might need to be removed before saving a bones file,
in case these characters are not in their home bases */
staticfn void
remove_mon_from_bones(struct monst *mtmp)
{
struct permonst *mptr = mtmp->data;
if (mtmp->iswiz || mptr == &mons[PM_MEDUSA]
|| mptr->msound == MS_NEMESIS || mptr->msound == MS_LEADER
|| is_Vlad(mtmp) /* mptr == &mons[VLAD_THE_IMPALER] || cham == VLAD */
|| (mptr == &mons[PM_ORACLE] && !fixuporacle(mtmp)))
mongone(mtmp);
}
/* save bones and possessions of a deceased adventurer */
void
savebones(int how, time_t when, struct obj *corpse)
{
coordxy x, y;
struct trap *ttmp;
struct monst *mtmp;
struct fruit *f;
struct cemetery *newbones;
char c, *bonesid;
char whynot[BUFSZ];
NHFILE *nhfp;
/* caller has already checked `can_make_bones()' */
clear_bypasses();
nhfp = open_bonesfile(&u.uz, &bonesid);
if (nhfp) {
close_nhfile(nhfp);
if (wizard) {
if (y_n("Bones file already exists. Replace it?") == 'y') {
if (delete_bonesfile(&u.uz))
goto make_bones;
else
pline("Cannot unlink old bones.");
}
}
/* compression can change the file's name, so must
wait until after any attempt to delete this file */
compress_bonesfile();
return;
}
make_bones:
unleash_all();
/* new ghost or other undead isn't punished even if hero was;
end-of-game disclosure has already had a chance to report the
Punished status so we don't need to preserve it any further */
if (Punished)
unpunish(); /* unwear uball, destroy uchain */
/* in case dismounting kills steed [is that even possible?], do so
before cleaning up dead monsters */
if (u.usteed)
dismount_steed(DISMOUNT_BONES);
iter_mons(remove_mon_from_bones); /* send various unique monsters away, */
dmonsfree(); /* then discard dead or gone monsters */
forget_engravings(); /* next hero won't have read any engravings yet */
/* mark all named fruits as nonexistent; if/when we come to instances
of any of them we'll mark those as existing (using goodfruit()) */
for (f = gf.ffruit; f; f = f->nextf)
f->fid = -f->fid;
set_ghostly_objlist(gi.invent);
/* dispose of your possessions, usually cursed */
if (ismnum(u.ugrave_arise)) {
/* give your possessions to the monster you become */
gi.in_mklev = TRUE; /* use <u.ux,u.uy> as-is */
mtmp = makemon(&mons[u.ugrave_arise], u.ux, u.uy, NO_MINVENT);
gi.in_mklev = FALSE;
if (!mtmp) { /* arise-type might have been genocided */
drop_upon_death((struct monst *) 0, (struct obj *) 0, u.ux, u.uy);
u.ugrave_arise = NON_PM; /* in case caller cares */
return;
}
give_u_to_m_resistances(mtmp);
mtmp = christen_monst(mtmp, svp.plname);
newsym(u.ux, u.uy);
/* ["Your body rises from the dead as an <mname>..." used
to be given here, but it has been moved to done() so that
it gets delivered even when savebones() isn't called] */
drop_upon_death(mtmp, (struct obj *) 0, u.ux, u.uy);
/* 'mtmp' now has hero's inventory; if 'mtmp' is a mummy, give it
a wrapping unless already carrying one */
if (mtmp->data->mlet == S_MUMMY && !m_carrying(mtmp, MUMMY_WRAPPING))
(void) mongets(mtmp, MUMMY_WRAPPING);
m_dowear(mtmp, TRUE);
} else if (u.ugrave_arise == LEAVESTATUE) {
struct obj *otmp;
/* embed your possessions in your statue */
otmp = mk_named_object(STATUE, &mons[u.umonnum], u.ux, u.uy,
svp.plname);
drop_upon_death((struct monst *) 0, otmp, u.ux, u.uy);
if (!otmp)
return; /* couldn't make statue */
mtmp = (struct monst *) 0;
} else { /* u.ugrave_arise < LEAVESTATUE */
/* drop everything */
drop_upon_death((struct monst *) 0, (struct obj *) 0, u.ux, u.uy);
/* trick makemon() into allowing monster creation
* on your location
*/
gi.in_mklev = TRUE;
mtmp = makemon(&mons[PM_GHOST], u.ux, u.uy, MM_NONAME);
gi.in_mklev = FALSE;
if (!mtmp)
return;
mtmp = christen_monst(mtmp, svp.plname);
if (corpse)
(void) obj_attach_mid(corpse, mtmp->m_id);
}
if (mtmp) {
int i;
mtmp->m_lev = (u.ulevel ? u.ulevel : 1);
mtmp->mhp = mtmp->mhpmax = u.uhpmax;
mtmp->female = flags.female;
mtmp->msleeping = 1;
if (!has_ebones(mtmp))
newebones(mtmp);
if (has_ebones(mtmp)) {
for (i = 0; i <= NUM_ROLES; ++i) {
if (!strcmp(gu.urole.name.m, roles[i].name.m)) {
EBONES(mtmp)->role = i;
break;
}
/* impossible("savebones: bad gu.urole.name.m \"%s\"",
gu.urole.name.m); */
}
for (i = 0; i <= NUM_RACES; ++i) {
if (!strcmp(gu.urace.noun, races[i].noun)) {
EBONES(mtmp)->race = i;
break;
}
/* impossible("savebones: bad gu.urace.noun \"%s\"",
gu.urace.noun); */
}
EBONES(mtmp)->oldalign = u.ualign;
EBONES(mtmp)->deathlevel = u.ulevel;
/* moreluck not included in luck computation */
EBONES(mtmp)->luck = Doomed ? LUCKMIN : u.uluck;
EBONES(mtmp)->mnum = Role_switch;
EBONES(mtmp)->female = flags.female;
EBONES(mtmp)->demigod = u.uevent.udemigod;
EBONES(mtmp)->crowned = u.uevent.uhand_of_elbereth;
}
}
for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
set_ghostly_objlist(mtmp->minvent);
resetobjs(mtmp->minvent, FALSE);
/* do not zero out m_ids for bones levels any more */
mtmp->mlstmv = 0L;
if (mtmp->mtame)
mtmp->mtame = mtmp->mpeaceful = 0;
/* observations about the current hero won't apply to future game */
mtmp->seen_resistance = M_SEEN_NOTHING;
}
for (ttmp = gf.ftrap; ttmp; ttmp = ttmp->ntrap) {
ttmp->madeby_u = 0;
ttmp->tseen = unhideable_trap(ttmp->ttyp);
}
set_ghostly_objlist(fobj);
resetobjs(fobj, FALSE);
set_ghostly_objlist(svl.level.buriedobjlist);
resetobjs(svl.level.buriedobjlist, FALSE);
/* Hero is no longer on the map. */
u.ux0 = u.ux, u.uy0 = u.uy;
u.ux = u.uy = 0;
/* Clear all memory from the level. */
for (x = 1; x < COLNO; x++)
for (y = 0; y < ROWNO; y++) {
levl[x][y].seenv = 0;
levl[x][y].waslit = 0;
levl[x][y].glyph = GLYPH_UNEXPLORED;
svl.lastseentyp[x][y] = 0;
}
/* Attach bones info to the current level before saving. */
newbones = (struct cemetery *) alloc(sizeof *newbones);
/* entries are '\0' terminated but have fixed length allocations,
so pre-fill with spaces to initialize any excess room */
(void) memset((genericptr_t) newbones, ' ', sizeof *newbones);
/* format name+role,&c, death reason, and date+time;
gender and alignment reflect final values rather than what the
character started out as, same as topten and logfile entries */
Sprintf(newbones->who, "%s-%.3s-%.3s-%.3s-%.3s",
svp.plname, gu.urole.filecode,
gu.urace.filecode, genders[flags.female].filecode,
aligns[1 - u.ualign.type].filecode);
formatkiller(newbones->how, sizeof newbones->how, how, TRUE);
Strcpy(newbones->when, yyyymmddhhmmss(when));
/* final resting place, used to decide when bones are discovered */
newbones->frpx = u.ux0, newbones->frpy = u.uy0;
newbones->bonesknown = FALSE;
/* if current character died on a bones level, the cemetery list
will have multiple entries, most recent (this dead hero) first */
newbones->next = svl.level.bonesinfo;
svl.level.bonesinfo = newbones;
/* flag these bones if they are being created in wizard mode;
they might already be flagged as such, even when we're playing
in normal mode, if this level came from a previous bones file */
if (wizard)
svl.level.flags.wizard_bones = 1;
nhfp = create_bonesfile(&u.uz, &bonesid, whynot);
if (!nhfp) {
if (wizard)
pline1(whynot);
/* bones file creation problems are silent to the player.
* Keep it that way, but place a clue into the paniclog.
*/
paniclog("savebones", whynot);
return;
}
c = (char) (strlen(bonesid) + 1);
nhfp->mode = WRITING;
store_version(nhfp);
store_savefileinfo(nhfp);
if (nhfp->structlevel) {
/* if a bones pool digit is in use, it precedes the bonesid
string and isn't recorded in the file */
bwrite(nhfp->fd, (genericptr_t) &c, sizeof c);
bwrite(nhfp->fd, (genericptr_t) bonesid, (unsigned) c); /* DD.nn */
savefruitchn(nhfp);
}
update_mlstmv(); /* update monsters for eventual restoration */
savelev(nhfp, ledger_no(&u.uz));
close_nhfile(nhfp);
commit_bonesfile(&u.uz);
compress_bonesfile();
}
int
getbones(void)
{
int ok;
NHFILE *nhfp = (NHFILE *) 0;
char c = 0, *bonesid,
oldbonesid[40] = { 0 }; /* was [10]; more should be safer */
if (discover) /* save bones files for real games */
return 0;
if (!flags.bones)
return 0;
/* wizard check added by GAN 02/05/87 */
if (rn2(3) /* only once in three times do we find bones */
&& !wizard)
return 0;
if (no_bones_level(&u.uz))
return 0;
nhfp = open_bonesfile(&u.uz, &bonesid);
if (!nhfp)
return 0;
if (nhfp && nhfp->structlevel && nhfp->fd < 0)
return 0;
if (nhfp && nhfp->fieldlevel) {
if (nhfp->style.deflt && !nhfp->fpdef)
return 0;
}
if (validate(nhfp, gb.bones, FALSE) != 0) {
if (!wizard)
pline("Discarding unusable bones; no need to panic...");
ok = FALSE;
} else {
ok = TRUE;
if (wizard) {
if (y_n("Get bones?") == 'n') {
close_nhfile(nhfp);
compress_bonesfile();
return 0;
}
}
if (nhfp->structlevel) {
/* if a bones pool digit is in use, it precedes the bonesid
string and wasn't recorded in the file */
mread(nhfp->fd, (genericptr_t) &c,
sizeof c); /* length including terminating '\0' */
if ((unsigned) c <= sizeof oldbonesid) {
mread(nhfp->fd, (genericptr_t) oldbonesid,
(unsigned) c); /* DD.nn or Qrrr.n for role rrr */
} else {
if (wizard)
debugpline2("Abandoning bones , %u > %u.",
(unsigned) c, (unsigned) sizeof oldbonesid);
close_nhfile(nhfp);
compress_bonesfile();
/* ToDo: maybe unlink these problematic bones? */
return 0;
}
}
if (strcmp(bonesid, oldbonesid) != 0) {
char errbuf[BUFSZ];
Sprintf(errbuf, "This is bones level '%s', not '%s'!",
oldbonesid, bonesid);
if (wizard) {
pline1(errbuf);
ok = FALSE; /* won't die of trickery */
}
trickery(errbuf);
} else {
struct monst *mtmp;
getlev(nhfp, 0, 0);
/* Note that getlev() now keeps tabs on unique
* monsters such as demon lords, and tracks the
* birth counts of all species just as makemon()
* does. If a bones monster is extinct or has been
* subject to genocide, their mhpmax will be
* set to the magic DEFUNCT_MONSTER cookie value.
*/
for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
if (has_mgivenname(mtmp))
sanitize_name(MGIVENNAME(mtmp));
if (mtmp->mhpmax == DEFUNCT_MONSTER) {
if (wizard) {
debugpline1("Removing defunct monster %s from bones.",
mtmp->data->pmnames[NEUTRAL]);
}
mongone(mtmp);
} else
/* to correctly reset named artifacts on the level */
resetobjs(mtmp->minvent, TRUE);
}
resetobjs(fobj, TRUE);
resetobjs(svl.level.buriedobjlist, TRUE);
fix_shop_damage();
}
}
close_nhfile(nhfp);
sanitize_engravings();
u.uroleplay.numbones++;
if (wizard) {
if (y_n("Unlink bones?") == 'n') {
compress_bonesfile();
return ok;
}
}
if (!delete_bonesfile(&u.uz)) {
/* When N games try to simultaneously restore the same
* bones file, N-1 of them will fail to delete it
* (the first N-1 under AmigaDOS, the last N-1 under UNIX).
* So no point in a mysterious message for a normal event
* -- just generate a new level for those N-1 games.
*/
/* pline("Cannot unlink bones."); */
return 0;
}
return ok;
}
/* check whether current level contains bones from a particular player */
boolean
bones_include_name(const char *name)
{
struct cemetery *bp;
size_t len;
char buf[BUFSZ];
/* prepare buffer by appending terminal hyphen to name, to avoid partial
* matches producing false positives */
Strcpy(buf, name);
Strcat(buf, "-");
len = strlen(buf);
for (bp = svl.level.bonesinfo; bp; bp = bp->next) {
if (!strncmp(bp->who, buf, len))
return TRUE;
}
return FALSE;
}
/* set the ghostly bit in a list of objects */
staticfn void
set_ghostly_objlist(struct obj *objchain)
{
while (objchain) {
objchain->ghostly = 1;
objchain = objchain->nobj;
}
}
/* This is called when a marked object from a bones file is picked-up.
Some could result in a message, and the obj->ghostly flag is always
cleared. obj->ghostly has no other usage at this time. */
void
fix_ghostly_obj(struct obj *obj)
{
if (!obj->ghostly)
return;
switch(obj->otyp) {
/* asymmetrical weapons */
case BOW:
case ELVEN_BOW:
case ORCISH_BOW:
case YUMI:
case BOOMERANG:
You("make adjustments to %s to suit your %s hand.",
the(xname(obj)),
URIGHTY ? "right" : "left");
break;
default:
break;
}
obj->ghostly = 0;
}
void
newebones(struct monst *mtmp)
{
if (!mtmp->mextra)
mtmp->mextra = newmextra();
if (!EBONES(mtmp)) {
EBONES(mtmp) = (struct ebones *) alloc(
sizeof (struct ebones));
(void) memset((genericptr_t) EBONES(mtmp), 0,
sizeof (struct ebones));
EBONES(mtmp)->parentmid = mtmp->m_id;
}
}
/* this is not currently used */
void
free_ebones(struct monst *mtmp)
{
if (mtmp->mextra && EBONES(mtmp)) {
free((genericptr_t) EBONES(mtmp));
EBONES(mtmp) = (struct ebones *) 0;
}
}
/*bones.c*/
| 412 | 0.994776 | 1 | 0.994776 | game-dev | MEDIA | 0.914015 | game-dev | 0.99397 | 1 | 0.99397 |
proletariatgames/unreal.hx | 4,100 | Haxe/Externs/UE4.22/unreal/functionaltesting/UAutomationPerformaceHelper.hx | /**
*
* WARNING! This file was autogenerated by:
* _ _ _ _ __ __
* | | | | | | |\ \ / /
* | | | | |_| | \ V /
* | | | | _ | / \
* | |_| | | | |/ /^\ \
* \___/\_| |_/\/ \/
*
* This file was autogenerated by UnrealHxGenerator using UHT definitions.
* It only includes UPROPERTYs and UFUNCTIONs. Do not modify it!
* In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix
**/
package unreal.functionaltesting;
/**
Class for use with functional tests which provides various performance measuring features.
Recording of basic, unintrusive performance stats.
Automatic captures using external CPU and GPU profilers.
Triggering and ending of writing full stats to a file.
**/
@:umodule("FunctionalTesting")
@:glueCppIncludes("FunctionalTest.h")
@:uextern @:uclass extern class UAutomationPerformaceHelper extends unreal.UObject {
/**
Begin basic stat recording
**/
@:ufunction(BlueprintCallable) @:final public function Tick(DeltaSeconds : unreal.Float32) : Void;
/**
Adds a sample to the stats counters for the current performance stats record.
**/
@:ufunction(BlueprintCallable) @:final public function Sample(DeltaSeconds : unreal.Float32) : Void;
/**
Begins recording a new named performance stats record. We start by recording the baseline
**/
@:ufunction(BlueprintCallable) @:final public function BeginRecordingBaseline(RecordName : unreal.FString) : Void;
/**
Stops recording the baseline and moves to the main record.
**/
@:ufunction(BlueprintCallable) @:final public function EndRecordingBaseline() : Void;
/**
Begins recording a new named performance stats record. We start by recording the baseline.
**/
@:ufunction(BlueprintCallable) @:final public function BeginRecording(RecordName : unreal.FString, InGPUBudget : unreal.Float32, InRenderThreadBudget : unreal.Float32, InGameThreadBudget : unreal.Float32) : Void;
/**
Stops recording performance stats.
**/
@:ufunction(BlueprintCallable) @:final public function EndRecording() : Void;
/**
Writes the current set of performance stats records to a csv file in the profiling directory. An additional directory and an extension override can also be used.
**/
@:ufunction(BlueprintCallable) @:final public function WriteLogFile(CaptureDir : unreal.FString, CaptureExtension : unreal.FString) : Void;
/**
Returns true if this stats tracker is currently recording performance stats.
**/
@:ufunction(BlueprintCallable) @:thisConst @:final public function IsRecording() : Bool;
/**
Does any init work across all tests..
**/
@:ufunction(BlueprintCallable) @:final public function OnBeginTests() : Void;
/**
Does any final work needed as all tests are complete.
**/
@:ufunction(BlueprintCallable) @:final public function OnAllTestsComplete() : Void;
@:ufunction(BlueprintCallable) @:thisConst @:final public function IsCurrentRecordWithinGPUBudget() : Bool;
@:ufunction(BlueprintCallable) @:thisConst @:final public function IsCurrentRecordWithinGameThreadBudget() : Bool;
@:ufunction(BlueprintCallable) @:thisConst @:final public function IsCurrentRecordWithinRenderThreadBudget() : Bool;
/**
Communicates with external profiler to being a CPU capture.
**/
@:ufunction(BlueprintCallable) @:final public function StartCPUProfiling() : Void;
/**
Communicates with external profiler to end a CPU capture.
**/
@:ufunction(BlueprintCallable) @:final public function StopCPUProfiling() : Void;
/**
Will trigger a GPU trace next time the current test falls below GPU budget.
**/
@:ufunction(BlueprintCallable) @:final public function TriggerGPUTraceIfRecordFallsBelowBudget() : Void;
/**
Begins recording stats to a file.
**/
@:ufunction(BlueprintCallable) @:final public function BeginStatsFile(RecordName : unreal.FString) : Void;
/**
Ends recording stats to a file.
**/
@:ufunction(BlueprintCallable) @:final public function EndStatsFile() : Void;
}
| 412 | 0.874863 | 1 | 0.874863 | game-dev | MEDIA | 0.227345 | game-dev | 0.567119 | 1 | 0.567119 |
pixel-quest/pixel-games | 24,246 | games/pirates_v1/pirates_v1.lua | --[[
Название: Пираты (карибского моря)
Автор: Avondale, дискорд - avonda
Описание механики:
Игроки управляют кораблями в море, стреляют в корабли друг друга из пушек и уклоняются от выстрелов
Побеждает тот кто остаётся последним выжившим
Идеи по доработке:
]]
math.randomseed(os.time())
require("avonlib")
local CLog = require("log")
local CInspect = require("inspect")
local CHelp = require("help")
local CJson = require("json")
local CTime = require("time")
local CAudio = require("audio")
local CColors = require("colors")
local tGame = {
Cols = 24,
Rows = 15,
Buttons = {},
}
local tConfig = {}
-- стейты или этапы игры
local GAMESTATE_SETUP = 1
local GAMESTATE_GAME = 2
local GAMESTATE_POSTGAME = 3
local GAMESTATE_FINISH = 4
local bGamePaused = false
local iGameState = GAMESTATE_SETUP
local iPrevTickTime = 0
local bAnyButtonClick = false
local tPlayerInGame = {}
local tGameStats = {
StageLeftDuration = 0,
StageTotalDuration = 0,
CurrentStars = 0,
TotalStars = 0,
CurrentLives = 0,
TotalLives = 0,
Players = { -- максимум 6 игроков
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
},
TargetScore = 0,
StageNum = 0,
TotalStages = 0,
TargetColor = CColors.NONE,
ScoreboardVariant = 6,
}
local tGameResults = {
Won = false,
AfterDelay = false,
PlayersCount = 0,
Score = 0,
Color = CColors.NONE,
}
local tFloor = {}
local tButtons = {}
local tFloorStruct = {
iColor = CColors.NONE,
iBright = CColors.BRIGHT0,
bClick = false,
bDefect = false,
iWeight = 0,
iPlayerID = 0,
}
local tButtonStruct = {
bClick = false,
bDefect = false,
}
local tTeamColors = {}
tTeamColors[1] = CColors.GREEN
tTeamColors[2] = CColors.MAGENTA
tTeamColors[3] = CColors.WHITE
tTeamColors[4] = CColors.YELLOW
tTeamColors[5] = CColors.CYAN
function StartGame(gameJson, gameConfigJson)
tGame = CJson.decode(gameJson)
tConfig = CJson.decode(gameConfigJson)
for iX = 1, tGame.Cols do
tFloor[iX] = {}
for iY = 1, tGame.Rows do
tFloor[iX][iY] = CHelp.ShallowCopy(tFloorStruct)
end
end
for _, iId in pairs(tGame.Buttons) do
tButtons[iId] = CHelp.ShallowCopy(tButtonStruct)
end
iPrevTickTime = CTime.unix()
if AL.RoomHasNFZ(tGame) then
AL.LoadNFZInfo()
end
if tGame.StartPositions == nil then
tGame.StartPositions = {}
local iMinX = 1
local iMinY = 1
local iMaxX = tGame.Cols-1
local iMaxY = tGame.Rows
if AL.NFZ.bLoaded then
iMinX = AL.NFZ.iMinX
iMinY = AL.NFZ.iMinY
iMaxX = AL.NFZ.iMaxX
iMaxY = AL.NFZ.iMaxY
end
tGame.StartPositionSizeX = math.floor((iMaxX-iMinX)/tConfig.PlayerCount)
if tGame.StartPositionSizeX < 4 then tGame.StartPositionSizeX = 4; end
if tGame.StartPositionSizeX > 10 then tGame.StartPositionSizeX = 10; end
tGame.StartPositionSizeY = iMaxY - iMinY + 1
local iX = iMinX
local iY = iMinY
for iPlayerID = 1, tConfig.PlayerCount do
tGame.StartPositions[iPlayerID] = {}
tGame.StartPositions[iPlayerID].X = iX
tGame.StartPositions[iPlayerID].Y = iY
tGame.StartPositions[iPlayerID].Color = tTeamColors[iPlayerID]
iX = iX + tGame.StartPositionSizeX + 1
if iX + tGame.StartPositionSizeX-1 > iMaxX+1 then
break;
end
end
else
for iPlayerID = 1, #tGame.StartPositions do
tGame.StartPositions[iPlayerID].Color = tonumber(tGame.StartPositions[iPlayerID].Color)
end
end
tGameStats.TargetScore = tConfig.ShipHealth
CShips.Init()
CGameMode.Announcer()
end
function NextTick()
if iGameState == GAMESTATE_SETUP then
GameSetupTick()
end
if iGameState == GAMESTATE_GAME then
GameTick()
end
if iGameState == GAMESTATE_POSTGAME then
PostGameTick()
if not tGameResults.AfterDelay then
tGameResults.AfterDelay = true
return tGameResults
end
end
if iGameState == GAMESTATE_FINISH then
tGameResults.AfterDelay = false
return tGameResults
end
AL.CountTimers((CTime.unix() - iPrevTickTime) * 1000)
iPrevTickTime = CTime.unix()
end
function GameSetupTick()
SetGlobalColorBright(CColors.BLUE, tConfig.Bright-2) -- красим всё поле в один цвет
SetAllButtonColorBright(CColors.BLUE, tConfig.Bright, true)
local iPlayersReady = 0
for iPos, tPos in ipairs(tGame.StartPositions) do
if iPos <= #tGame.StartPositions then
local iBright = CColors.BRIGHT15
if CheckPositionClick(tPos, tGame.StartPositionSizeX, tGame.StartPositionSizeY) then
tGameStats.Players[iPos].Color = tPos.Color
iBright = CColors.BRIGHT30
iPlayersReady = iPlayersReady + 1
tPlayerInGame[iPos] = true
else
tGameStats.Players[iPos].Color = CColors.NONE
tPlayerInGame[iPos] = false
end
CPaint.PlayerZone(iPos, iBright)
end
end
if (iPlayersReady > 1 and bAnyButtonClick) or (iPlayersReady == #tGame.StartPositions and CGameMode.bCanAutoStart) then
bAnyButtonClick = false
CGameMode.iAlivePlayerCount = iPlayersReady
iGameState = GAMESTATE_GAME
CShips.Spawn()
CGameMode.Thinkers()
CGameMode.StartCountDown(5)
end
end
function GameTick()
SetGlobalColorBright(CColors.BLUE, tConfig.Bright-1) -- красим всё поле в один цвет
SetAllButtonColorBright(CColors.NONE, 0, false)
CPaint.Ships()
CPaint.Projectiles()
end
function PostGameTick()
end
function RangeFloor(setPixel, setButton)
for iX = 1, tGame.Cols do
for iY = 1, tGame.Rows do
setPixel(iX , iY, tFloor[iX][iY].iColor, tFloor[iX][iY].iBright)
end
end
for i, tButton in pairs(tButtons) do
setButton(i, tButton.iColor, tButton.iBright)
end
end
function SwitchStage()
end
--GAMEMODE
CGameMode = {}
CGameMode.iCountdown = 0
CGameMode.bCanAutoStart = false
CGameMode.bGameStarted = false
CGameMode.iAlivePlayerCount = 0
CGameMode.iWinnerID = 0
CGameMode.Announcer = function()
CAudio.PlayVoicesSync("pirates/pirates_guide.mp3")
CAudio.PlayVoicesSync("choose-color.mp3")
--CAudio.PlayVoicesSync("press-button-for-start.mp3")
AL.NewTimer(CAudio.GetVoicesDuration("pirates/pirates_guide.mp3")*1000 + 3000, function()
CGameMode.bCanAutoStart = true
end)
end
CGameMode.StartCountDown = function(iCountDownTime)
CGameMode.iCountdown = iCountDownTime
AL.NewTimer(1000, function()
CAudio.ResetSync()
tGameStats.StageLeftDuration = CGameMode.iCountdown
if CGameMode.iCountdown <= 0 then
CGameMode.StartGame()
return nil
else
CAudio.PlayLeftAudio(CGameMode.iCountdown)
CGameMode.iCountdown = CGameMode.iCountdown - 1
return 1000
end
end)
end
CGameMode.Thinkers = function()
AL.NewTimer(200, function()
if iGameState ~= GAMESTATE_GAME then return nil; end
CShips.ShipThinker()
return 200
end)
AL.NewTimer(100, function()
if iGameState ~= GAMESTATE_GAME then return nil; end
CProjectiles.ProjectileThink()
return 100
end)
end
CGameMode.StartGame = function()
CAudio.PlayVoicesSync(CAudio.START_GAME)
CAudio.PlayRandomBackground()
CGameMode.bGameStarted = true
end
CGameMode.EndGame = function()
for iShipId = 1, #CShips.tShips do
if CShips.tShips[iShipId].bAlive then
CGameMode.iWinnerID = CShips.tShips[iShipId].iPlayerID
break;
end
end
iGameState = GAMESTATE_POSTGAME
CAudio.PlaySyncColorSound(tGame.StartPositions[CGameMode.iWinnerID].Color)
CAudio.PlayVoicesSync(CAudio.VICTORY)
SetGlobalColorBright(tGameStats.Players[CGameMode.iWinnerID].Color, tConfig.Bright)
tGameResults.Color = tGame.StartPositions[CGameMode.iWinnerID].Color
AL.NewTimer(10000, function()
iGameState = GAMESTATE_FINISH
end)
end
--//
--SHIPS
CShips = {}
CShips.tShips = {}
CShips.tPlayerIDToShipId = {}
CShips.Init = function()
CShips.SHIP_SIZE_X = 3
CShips.SHIP_SIZE_Y = math.floor(tGame.StartPositionSizeY/2)
CShips.SHIP_HEALTH = tConfig.ShipHealth
CShips.PLAYER_CONTROL_Y_OFFSET = -math.floor(CShips.SHIP_SIZE_Y/2)
end
CShips.Spawn = function()
for iPlayerID = 1, #tGame.StartPositions do
if tPlayerInGame[iPlayerID] then
CShips.NewShip(iPlayerID)
end
end
end
CShips.NewShip = function(iPlayerID)
local iShipId = #CShips.tShips+1
CShips.tShips[iShipId] = {}
CShips.tShips[iShipId].iPlayerID = iPlayerID
CShips.tShips[iShipId].iX = tGame.StartPositions[iPlayerID].X + math.floor(tGame.StartPositionSizeX/2) - 1
CShips.tShips[iShipId].iY = 1
CShips.tShips[iShipId].iTargetY = 1
CShips.tShips[iShipId].iLastControlX = 0
CShips.tShips[iShipId].iLastControlY = 0
CShips.tShips[iShipId].iHealth = CShips.SHIP_HEALTH
CShips.tShips[iShipId].bAlive = true
CShips.tShips[iShipId].bLeftCanShoot = true
CShips.tShips[iShipId].bRightCanShoot = true
CShips.tShips[iShipId].bOnFire = false
if iPlayerID == 1 then CShips.tShips[iShipId].iX = tGame.StartPositions[iPlayerID].X + 1 end
if iPlayerID == #tGame.StartPositions then CShips.tShips[iShipId].iX = tGame.StartPositions[iPlayerID].X + tGame.StartPositionSizeX-3 end
CShips.tPlayerIDToShipId[iPlayerID] = iShipId
tGameStats.Players[CShips.tShips[iShipId].iPlayerID].Score = CShips.tShips[iShipId].iHealth
end
CShips.ShipThinker = function()
for iShipId = 1, #CShips.tShips do
if CShips.tShips[iShipId] and CShips.tShips[iShipId].bAlive then
if CShips.tShips[iShipId].iTargetY ~= CShips.tShips[iShipId].iY then
if CShips.tShips[iShipId].iY > CShips.tShips[iShipId].iTargetY then
CShips.tShips[iShipId].iY = CShips.tShips[iShipId].iY - 1
else
CShips.tShips[iShipId].iY = CShips.tShips[iShipId].iY + 1
end
end
end
end
end
CShips.PlayerControl = function(iPlayerID, iX, iY)
local iShipId = CShips.tPlayerIDToShipId[iPlayerID]
if CShips.tShips[iShipId].iLastControlX == 0 or (tFloor[CShips.tShips[iShipId].iLastControlX][CShips.tShips[iShipId].iLastControlY].iWeight <= tFloor[iX][iY].iWeight) or tFloor[CShips.tShips[iShipId].iLastControlX][CShips.tShips[iShipId].iLastControlY].bDefect then
CShips.tShips[iShipId].iLastControlX = iX
CShips.tShips[iShipId].iLastControlY = iY
local iNewTargetY = iY+CShips.PLAYER_CONTROL_Y_OFFSET
if iNewTargetY ~= CShips.tShips[iShipId].iTargetY and iNewTargetY+1 ~= CShips.tShips[iShipId].iTargetY and iNewTargetY-1 ~= CShips.tShips[iShipId].iTargetY then
CShips.tShips[iShipId].iTargetY = iNewTargetY
if CShips.tShips[iShipId].iTargetY < 1 then CShips.tShips[iShipId].iTargetY = 1 end
if CShips.tShips[iShipId].iTargetY > tGame.StartPositionSizeY-CShips.SHIP_SIZE_Y+1 then CShips.tShips[iShipId].iTargetY = tGame.StartPositionSizeY-CShips.SHIP_SIZE_Y+1 end
end
end
end
CShips.ShipShoot = function(iShipId, iX, iY, bLeftSide)
if bLeftSide then
if CShips.tShips[iShipId].bLeftCanShoot then
CShips.tShips[iShipId].bLeftCanShoot = false
AL.NewTimer(2000, function()
CShips.tShips[iShipId].bLeftCanShoot = true
end)
else
return false
end
else
if CShips.tShips[iShipId].bRightCanShoot then
CShips.tShips[iShipId].bRightCanShoot = false
AL.NewTimer(2000, function()
CShips.tShips[iShipId].bRightCanShoot = true
end)
else
return false
end
end
local iVelX = -1
if iX > CShips.tShips[iShipId].iX then
iVelX = 1
end
CProjectiles.NewProjectile(iX, iY, iVelX, 0)
CAudio.PlaySystemAsync("pirates/cannon.mp3")
return true
end
CShips.DamageShip = function(iShipId)
CShips.tShips[iShipId].iHealth = CShips.tShips[iShipId].iHealth - 1
tGameStats.Players[CShips.tShips[iShipId].iPlayerID].Score = CShips.tShips[iShipId].iHealth
if CShips.tShips[iShipId].iHealth == 0 then
CAudio.PlaySystemAsync("pirates/ship_dead.mp3")
CShips.tShips[iShipId].bAlive = false
CGameMode.iAlivePlayerCount = CGameMode.iAlivePlayerCount - 1
if CGameMode.iAlivePlayerCount == 1 then
CGameMode.EndGame()
end
else
CAudio.PlaySystemAsync("pirates/ship_hit.mp3")
CShips.tShips[iShipId].bOnFire = true
AL.NewTimer(250, function()
CShips.tShips[iShipId].bOnFire = false
end)
end
end
--//
--Projectiles
CProjectiles = {}
CProjectiles.tProjectiles = {}
CProjectiles.NewProjectile = function(iX, iY, iVelX, iVelY)
local iProjectileId = #CProjectiles.tProjectiles+1
CProjectiles.tProjectiles[iProjectileId] = {}
CProjectiles.tProjectiles[iProjectileId].iX = iX
CProjectiles.tProjectiles[iProjectileId].iY = iY
CProjectiles.tProjectiles[iProjectileId].iVelX = iVelX
CProjectiles.tProjectiles[iProjectileId].iVelY = iVelY
end
CProjectiles.ProjectileThink = function()
for iProjectileId = 1, #CProjectiles.tProjectiles do
if CProjectiles.tProjectiles[iProjectileId] then
CProjectiles.tProjectiles[iProjectileId].iX = CProjectiles.tProjectiles[iProjectileId].iX + CProjectiles.tProjectiles[iProjectileId].iVelX
CProjectiles.tProjectiles[iProjectileId].iY = CProjectiles.tProjectiles[iProjectileId].iY + CProjectiles.tProjectiles[iProjectileId].iVelY
if CProjectiles.tProjectiles[iProjectileId].iX < 1 or CProjectiles.tProjectiles[iProjectileId].iX > tGame.Cols or
CProjectiles.tProjectiles[iProjectileId].iY < 1 or CProjectiles.tProjectiles[iProjectileId].iY > tGame.Rows then
CProjectiles.tProjectiles[iProjectileId] = nil
else
CProjectiles.ProjectileCollision(iProjectileId)
end
end
end
end
CProjectiles.ProjectileCollision = function(iProjectileId)
for iShipId = 1, #CShips.tShips do
if CShips.tShips[iShipId] and CShips.tShips[iShipId].bAlive then
if CProjectiles.tProjectiles[iProjectileId].iX == CShips.tShips[iShipId].iX + math.floor(CShips.SHIP_SIZE_X/2) then
if CProjectiles.tProjectiles[iProjectileId].iY >= CShips.tShips[iShipId].iY and CProjectiles.tProjectiles[iProjectileId].iY <= CShips.tShips[iShipId].iY + CShips.SHIP_SIZE_Y-1 then
CShips.DamageShip(iShipId)
CProjectiles.tProjectiles[iProjectileId] = nil
return;
end
end
end
end
for iProjectileId2 = 1, #CProjectiles.tProjectiles do
if iProjectileId ~= iProjectileId2 and CProjectiles.tProjectiles[iProjectileId2] then
if CProjectiles.tProjectiles[iProjectileId].iX == CProjectiles.tProjectiles[iProjectileId2].iX and CProjectiles.tProjectiles[iProjectileId].iY == CProjectiles.tProjectiles[iProjectileId2].iY then
CProjectiles.tProjectiles[iProjectileId2] = nil
CProjectiles.tProjectiles[iProjectileId].iVelX = 0
CProjectiles.tProjectiles[iProjectileId].iVelY = 0
--sound projectiles hit
AL.NewTimer(250, function()
CProjectiles.tProjectiles[iProjectileId] = nil
end)
return;
end
end
end
end
--//
--PAINT
CPaint = {}
CPaint.PlayerZone = function(iPlayerID, iBright)
for i = tGame.StartPositions[iPlayerID].X, tGame.StartPositions[iPlayerID].X + tGame.StartPositionSizeX-1 do
for j = tGame.StartPositions[iPlayerID].Y, tGame.StartPositions[iPlayerID].Y + tGame.StartPositionSizeY-1 do
if not (i < 1 or i > tGame.Cols or j < 1 or j > tGame.Rows) then
tFloor[i][j].iColor = tGame.StartPositions[iPlayerID].Color
tFloor[i][j].iBright = iBright
tFloor[i][j].iPlayerID = iPlayerID
end
end
end
end
CPaint.Ships = function()
for iShipId = 1, #CShips.tShips do
for iX = CShips.tShips[iShipId].iX, CShips.tShips[iShipId].iX + CShips.SHIP_SIZE_X-1 do
for iY = CShips.tShips[iShipId].iY, CShips.tShips[iShipId].iY + CShips.SHIP_SIZE_Y-1 do
if tFloor[iX] and tFloor[iX][iY] then
local iColor = tGame.StartPositions[CShips.tShips[iShipId].iPlayerID].Color
local iBright = tConfig.Bright
if CShips.tShips[iShipId].bAlive then
if iY ~= CShips.tShips[iShipId].iY and iY ~= CShips.tShips[iShipId].iY + CShips.SHIP_SIZE_Y-1 then
if iX == CShips.tShips[iShipId].iX + math.floor(CShips.SHIP_SIZE_X/2) then
iBright = iBright-2
if CShips.tShips[iShipId].bOnFire then
iColor = CColors.RED
end
end
else
if iX == CShips.tShips[iShipId].iX or iX == CShips.tShips[iShipId].iX+CShips.SHIP_SIZE_X-1 then
iColor = CColors.BLUE
iBright = iBright-1
end
end
if iGameState == GAMESTATE_GAME and CGameMode.bGameStarted then
if (iX == CShips.tShips[iShipId].iX and iShipId ~= 1 and CShips.tShips[iShipId].bLeftCanShoot) or (iX == CShips.tShips[iShipId].iX+CShips.SHIP_SIZE_X-1 and iShipId ~= #CShips.tShips and CShips.tShips[iShipId].bRightCanShoot) then
if iY == CShips.tShips[iShipId].iY + math.floor(CShips.SHIP_SIZE_Y/2)-1 or iY == CShips.tShips[iShipId].iY + math.floor(CShips.SHIP_SIZE_Y/2)+1 then
iColor = CColors.RED
local bLeftSide = true
if iX > CShips.tShips[iShipId].iX then bLeftSide = false; end
if not tFloor[iX][iY].bDefect and tFloor[iX][iY].bClick and tFloor[iX][iY].iWeight > 5 then
CShips.ShipShoot(iShipId, iX, iY, bLeftSide)
end
end
end
end
else
iColor = CColors.RED
iBright = 1
end
tFloor[iX][iY].iColor = iColor
tFloor[iX][iY].iBright = iBright
end
end
end
end
end
CPaint.Projectiles = function()
for iProjectileId = 1, #CProjectiles.tProjectiles do
if CProjectiles.tProjectiles[iProjectileId] then
tFloor[CProjectiles.tProjectiles[iProjectileId].iX][CProjectiles.tProjectiles[iProjectileId].iY].iColor = CColors.RED
tFloor[CProjectiles.tProjectiles[iProjectileId].iX][CProjectiles.tProjectiles[iProjectileId].iY].iBright = tConfig.Bright+1
end
end
end
--//
--UTIL прочие утилиты
function CheckPositionClick(tStart, iSizeX, iSizeY)
for iX = tStart.X, tStart.X + iSizeX - 1 do
for iY = tStart.Y, tStart.Y + iSizeY - 1 do
if tFloor[iX] and tFloor[iX][iY] then
if tFloor[iX][iY].bClick then
return true
end
end
end
end
return false
end
function SetPositionColorBright(tStart, iSize, iColor, iBright)
for i = 0, iSize * iSize - 1 do
local iX = tStart.X + i % iSize
local iY = tStart.Y + math.floor(i / iSize)
if not (iX < 1 or iX > tGame.Cols or iY < 1 or iY > tGame.Rows) then
tFloor[iX][iY].iColor = iColor
tFloor[iX][iY].iBright = iBright
end
end
end
function SetRectColorBright(iX, iY, iSizeX, iSizeY, iColor, iBright)
for i = iX, iX + iSizeX do
for j = iY, iY + iSizeY do
if not (i < 1 or i > tGame.Cols or j < 1 or j > tGame.Rows) and not tFloor[i][j].bAnimated then
tFloor[i][j].iColor = iColor
tFloor[i][j].iBright = iBright
end
end
end
end
function SetGlobalColorBright(iColor, iBright)
for iX = 1, tGame.Cols do
for iY = 1, tGame.Rows do
tFloor[iX][iY].iColor = iColor
tFloor[iX][iY].iBright = iBright
end
end
for i, tButton in pairs(tButtons) do
tButtons[i].iColor = iColor
tButtons[i].iBright = iBright
end
end
function SetAllButtonColorBright(iColor, iBright, bCheckDefect)
for i, tButton in pairs(tButtons) do
if not bCheckDefect or not tButtons[i].bDefect then
tButtons[i].iColor = iColor
tButtons[i].iBright = iBright
end
end
end
--//
--//
function GetStats()
return tGameStats
end
function PauseGame()
bGamePaused = true
end
function ResumeGame()
bGamePaused = false
iPrevTickTime = CTime.unix()
end
function PixelClick(click)
if tFloor[click.X] and tFloor[click.X][click.Y] then
if bGamePaused then
tFloor[click.X][click.Y].bClick = false
return;
end
if iGameState == GAMESTATE_SETUP then
if click.Click then
tFloor[click.X][click.Y].bClick = true
tFloor[click.X][click.Y].bHold = false
elseif not tFloor[click.X][click.Y].bHold then
AL.NewTimer(500, function()
if not tFloor[click.X][click.Y].bHold then
tFloor[click.X][click.Y].bHold = true
AL.NewTimer(750, function()
if tFloor[click.X][click.Y].bHold then
tFloor[click.X][click.Y].bClick = false
end
end)
end
end)
end
tFloor[click.X][click.Y].iWeight = click.Weight
return
end
if iGameState == GAMESTATE_GAME and click.Click and not tFloor[click.X][click.Y].bDefect and tFloor[click.X][click.Y].iPlayerID > 0 and tPlayerInGame[tFloor[click.X][click.Y].iPlayerID] then
CShips.PlayerControl(tFloor[click.X][click.Y].iPlayerID, click.X, click.Y)
end
tFloor[click.X][click.Y].bClick = click.Click
tFloor[click.X][click.Y].iWeight = click.Weight
end
end
function DefectPixel(defect)
if tFloor[defect.X] and tFloor[defect.X][defect.Y] then
tFloor[defect.X][defect.Y].bDefect = defect.Defect
end
end
function ButtonClick(click)
if tButtons[click.Button] == nil or bGamePaused or tButtons[click.Button].bDefect then return end
tButtons[click.Button].bClick = click.Click
if click.Click and not tButtons[click.Button].bDefect then
bAnyButtonClick = true
end
end
function DefectButton(defect)
if tButtons[defect.Button] == nil then return end
tButtons[defect.Button].bDefect = defect.Defect
if defect.Defect then
tButtons[defect.Button].iColor = CColors.NONE
tButtons[defect.Button].iBright = CColors.BRIGHT0
end
end | 412 | 0.812254 | 1 | 0.812254 | game-dev | MEDIA | 0.725658 | game-dev | 0.887725 | 1 | 0.887725 |
tcmxx/UnityTensorflowKeras | 8,567 | Assets/UnityTensorflow/Examples/Maze/Scripts/MazeAgent.cs | using MLAgents;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MazeViewer))]
public class MazeAgent : Agent
{
public Vector2Int mazeDimension;
public bool regenerateMapOnReset = false;
public bool randomWallChance = false;
public bool noVectorObservation = true;
public float wallChanceOnNonPath = 0.3f;
public int maxStepAllowed = 20;
public float failureReward = -100;
public float maxWinReward = 100;
public float goToWallReward;
public float goUpReward = 1;
public float goCloserReward = 1;
public float stepCostReward = -0.1f;
private Vector2Int startPosition;
private Vector2Int goalPosition;
private Vector2Int currentPlayerPosition;
public bool Win { get; private set; }
public float[,] map;
private Dictionary<int, GameState> savedState;
private MazeViewer viewer;
[Header("Info")]
[ReadOnly]
[SerializeField]
protected int steps = 0;
public readonly int WallInt = 0;
public readonly int PlayerInt = 2;
public readonly int PathInt = 1;
public readonly int GoalInt = 3;
private struct GameState
{
public float[,] map;
public Vector2Int startPosition;
public Vector2Int goalPosition;
public Vector2Int currentPlayerPosition;
public bool win;
}
private void Awake()
{
viewer = GetComponent<MazeViewer>();
}
// Use this for initialization
public override void InitializeAgent()
{
savedState = new Dictionary<int, GameState>();
viewer.InitializeGraphic(this);
AgentReset();
}
public override void CollectObservations()
{
if (noVectorObservation)
return;
float[] result = new float[mazeDimension.x * mazeDimension.y];
for (int x = 0; x < mazeDimension.x; ++x)
{
for (int y = 0; y < mazeDimension.y; ++y)
{
result[y + x * mazeDimension.y] = (map[x, y] - 1.5f) / 1.5f;
}
}
AddVectorObs(result);
}
public override void AgentReset()
{
steps = 0;
if (regenerateMapOnReset)
{
RegenerateMap();
SaveState(-1);
}
else
{
LoadState(-1);
}
}
/// <summary>
/// take a action and return the reward
/// </summary>
/// <param name="action">0 left 1 right 2 down 3 up</param>
/// <returns>reward of this action</returns>
public override void AgentAction(float[] vectorAction, string textAction)
{
int action = Mathf.RoundToInt(vectorAction[0]);
float returnReward = 0;
//calculate the distance to goal before the action
int distanceBefore = Mathf.Abs((currentPlayerPosition - goalPosition).x) + Mathf.Abs((currentPlayerPosition - goalPosition).y);
Vector2Int toPosition = currentPlayerPosition;
//do the action
switch (action)
{
case 0:
toPosition.x -= 1;
break;
case 1:
toPosition.x += 1;
break;
case 2:
toPosition.y -= 1;
break;
case 3:
toPosition.y += 1;
break;
default:
Debug.LogError("invalid action number");
break;
}
bool reachGoal;
float stepChangedReward;
StepFromTo(currentPlayerPosition, toPosition, out stepChangedReward, out reachGoal);
returnReward += stepChangedReward;
//reward for move closer to the destination
int distanceAfter = Mathf.Abs((currentPlayerPosition - goalPosition).x) + Mathf.Abs((currentPlayerPosition - goalPosition).y);
if (distanceAfter < distanceBefore)
{
returnReward += goCloserReward;
}
//reward for going up
if (action == 3)
{
returnReward += goUpReward;
}
if (reachGoal)
{
Done();
Win = true;
}
if (steps >= maxStepAllowed)
{
Done();
Win = false;
returnReward += failureReward;
}
steps++;
AddReward(returnReward);
viewer.UpdateGraphics(this);
}
public void SaveState(int key)
{
float[,] copiedMap = new float[mazeDimension.x, mazeDimension.y];
System.Buffer.BlockCopy(map, 0, copiedMap, 0, map.Length * sizeof(float));
GameState state = new GameState();
state.map = copiedMap;
state.currentPlayerPosition = currentPlayerPosition;
state.goalPosition = goalPosition;
state.startPosition = startPosition;
state.win = Win;
savedState[key] = state;
}
public bool LoadState(int key)
{
MazeAgent fromEnv = this;
if (fromEnv.savedState.ContainsKey(key))
{
GameState state = fromEnv.savedState[key];
System.Buffer.BlockCopy(state.map, 0, map, 0, map.Length * sizeof(float));
currentPlayerPosition = state.currentPlayerPosition;
goalPosition = state.goalPosition;
startPosition = state.startPosition;
Win = state.win;
viewer.UpdateGraphics(this);
return true;
}
else
{
return false;
}
}
private void RegenerateMap()
{
map = new float[mazeDimension.x, mazeDimension.y];
GeneratePossiblePath();
GenerateExtraPath();
viewer.UpdateGraphics(this);
}
//mark a path with true. The generator will guarantee that this path is walkable
private void GeneratePossiblePath()
{
int place = Random.Range(0, mazeDimension.x);
int prevPlace = place;
map[place, mazeDimension.y - 1] = GoalInt;
goalPosition = new Vector2Int(place, mazeDimension.y - 1);
bool toggle = true;
for (int i = mazeDimension.y - 2; i >= 0; --i)
{
if (toggle)
{
toggle = false;
map[prevPlace, i] = PathInt;
}
else
{
toggle = true;
place = Random.Range(0, mazeDimension.x);
for (int j = Mathf.Min(place, prevPlace); j <= Mathf.Max(place, prevPlace); ++j)
{
map[j, i] = PathInt;
}
}
prevPlace = place;
}
startPosition = new Vector2Int(place, 0);
map[place, 0] = PlayerInt;
currentPlayerPosition = startPosition;
}
private void GenerateExtraPath()
{
float wallChance = wallChanceOnNonPath;
if (randomWallChance)
{
wallChance = Random.Range(0.0f, 1.0f);
}
for (int i = 0; i < mazeDimension.x; ++i)
{
for (int j = 0; j < mazeDimension.y; ++j)
{
if (map[i, j] == WallInt && Random.Range(0.0f, 1.0f) > wallChance)
{
map[i, j] = PathInt;
}
}
}
}
private void StepFromTo(Vector2Int from, Vector2Int to, out float stepChangedReward, out bool reachedGoal)
{
Debug.Assert(map[from.x, from.y] == PlayerInt && currentPlayerPosition.Equals(from));
stepChangedReward = 0;
stepChangedReward += stepCostReward;
if (to.x < 0 || to.y < 0 || to.x >= mazeDimension.x || to.y >= mazeDimension.y)
{
//run to the edge
stepChangedReward += goToWallReward;
reachedGoal = false;
}
else
{
if (map[to.x, to.y] == WallInt)
{
//run into a wall
//run to the edge
stepChangedReward += goToWallReward;
reachedGoal = false;
}
else if (map[to.x, to.y] == GoalInt)
{
//reach the goal
stepChangedReward += maxWinReward;
reachedGoal = true;
}
else
{
//move successfully
map[currentPlayerPosition.x, currentPlayerPosition.y] = PathInt;
currentPlayerPosition = to;
map[currentPlayerPosition.x, currentPlayerPosition.y] = PlayerInt;
reachedGoal = false;
}
}
}
}
| 412 | 0.919053 | 1 | 0.919053 | game-dev | MEDIA | 0.951627 | game-dev | 0.98195 | 1 | 0.98195 |
nasa/TrickHLA | 15,586 | source/SpaceFOM/PhysicalEntity.cpp | /*!
@file SpaceFOM/PhysicalEntity.cpp
@ingroup SpaceFOM
@brief This class provides data packing for the SpaceFOM PhysicalEntities.
@copyright Copyright 2023 United States Government as represented by the
Administrator of the National Aeronautics and Space Administration.
No copyright is claimed in the United States under Title 17, U.S. Code.
All Other Rights Reserved.
\par<b>Responsible Organization</b>
Simulation and Graphics Branch, Mail Code ER7\n
Software, Robotics & Simulation Division\n
NASA, Johnson Space Center\n
2101 NASA Parkway, Houston, TX 77058
@tldh
@trick_link_dependency{../TrickHLA/Attribute.cpp}
@trick_link_dependency{../TrickHLA/DebugHandler.cpp}
@trick_link_dependency{../TrickHLA/Object.cpp}
@trick_link_dependency{../TrickHLA/Packing.cpp}
@trick_link_dependency{../TrickHLA/Types.cpp}
@trick_link_dependency{PhysicalEntity.cpp}
@revs_title
@revs_begin
@rev_entry{Edwin Z. Crues, NASA ER7, TrickHLA, July 2023, --, Initial version.}
@rev_entry{Edwin Z. Crues, NASA ER7, TrickHLA, July 2023, --, Cleaned up and filled out.}
@rev_entry{Edwin Z. Crues, NASA ER7, TrickHLA, November 2023, --, Refactored.}
@revs_end
*/
// System include files.
#include <cstdlib>
#include <iostream>
#include <limits>
#include <math.h>
#include <sstream>
#include <string>
// Trick include files.
#include "trick/MemoryManager.hh"
#include "trick/exec_proto.hh"
#include "trick/matrix_macros.h"
#include "trick/message_proto.h"
#include "trick/vector_macros.h"
// TrickHLA include files.
#include "TrickHLA/Attribute.hh"
#include "TrickHLA/CompileConfig.hh"
#include "TrickHLA/DebugHandler.hh"
#include "TrickHLA/Object.hh"
#include "TrickHLA/Packing.hh"
#include "TrickHLA/Types.hh"
// SpaceFOM include files.
#include "SpaceFOM/PhysicalEntity.hh"
using namespace std;
using namespace TrickHLA;
using namespace SpaceFOM;
/*!
* @job_class{initialization}
*/
PhysicalEntity::PhysicalEntity() // RETURN: -- None.
: physical_data( NULL )
{
return;
}
/*!
* @job_class{initialization}
*/
PhysicalEntity::PhysicalEntity( PhysicalEntityData &physical_data_ref ) // RETURN: -- None.
: physical_data( &physical_data_ref )
{
return;
}
/*!
* @job_class{shutdown}
*/
PhysicalEntity::~PhysicalEntity() // RETURN: -- None.
{
physical_data = NULL;
}
/*!
* @job_class{initialization}
*/
void PhysicalEntity::configure( PhysicalEntityData *physical_data_ptr )
{
// First call the base class pre_initialize function.
PhysicalEntityBase::configure();
// Set the reference to the PhysicalEntity data.
if ( physical_data_ptr == NULL ) {
ostringstream errmsg;
errmsg << "SpaceFOM::PhysicalEntity::initialize():" << __LINE__
<< " ERROR: Unexpected NULL PhysicalEntityData: "
<< pe_packing_data.name << '\n';
// Print message and terminate.
TrickHLA::DebugHandler::terminate_with_message( errmsg.str() );
}
this->physical_data = physical_data_ptr;
// Return to calling routine.
return;
}
/*!
* @job_class{initialization}
*/
void PhysicalEntity::initialize()
{
// Check to make sure the PhysicalEntity data is set.
if ( physical_data == NULL ) {
ostringstream errmsg;
errmsg << "SpaceFOM::PhysicalEntity::initialize():" << __LINE__
<< " ERROR: Unexpected NULL PhysicalEntityData: "
<< pe_packing_data.name << '\n';
// Print message and terminate.
TrickHLA::DebugHandler::terminate_with_message( errmsg.str() );
}
// Mark this as initialized.
PhysicalEntityBase::initialize();
// Return to calling routine.
return;
}
/*!
* @job_class{scheduled}
*/
void PhysicalEntity::pack_from_working_data()
{
int iinc;
// NOTE: Because TrickHLA handles the bundling of locally owned attributes
// we do not need to check the ownership status of them here like we do
// in the unpack() function, since we don't run the risk of corrupting our
// state.
// Check for name change.
if ( physical_data->name != NULL ) {
if ( pe_packing_data.name != NULL ) {
// Compare names.
if ( strcmp( physical_data->name, pe_packing_data.name ) ) {
if ( trick_MM->delete_var( static_cast< void * >( pe_packing_data.name ) ) ) {
message_publish( MSG_WARNING, "PhysicalEntity::pack_from_working_data():%d WARNING failed to delete Trick Memory for 'pe_packing_data.name'\n",
__LINE__ );
}
pe_packing_data.name = trick_MM->mm_strdup( physical_data->name );
}
} else {
// No name to compare so copy name.
pe_packing_data.name = trick_MM->mm_strdup( physical_data->name );
}
} else {
// This is bad scoobies so just punt.
ostringstream errmsg;
errmsg << "SpaceFOM::PhysicalEntity::copy_working_data():" << __LINE__
<< " ERROR: Unexpected NULL name for PhysicalEntity!\n";
// Print message and terminate.
TrickHLA::DebugHandler::terminate_with_message( errmsg.str() );
}
// Check for type change.
if ( physical_data->type != NULL ) {
if ( pe_packing_data.type != NULL ) {
if ( strcmp( physical_data->type, pe_packing_data.type ) ) {
if ( trick_MM->delete_var( static_cast< void * >( pe_packing_data.type ) ) ) {
message_publish( MSG_WARNING, "PhysicalEntity::copy_working_data():%d WARNING failed to delete Trick Memory for 'pe_packing_data.type'\n",
__LINE__ );
}
pe_packing_data.type = trick_MM->mm_strdup( physical_data->type );
}
} else {
pe_packing_data.type = trick_MM->mm_strdup( physical_data->type );
}
} else {
if ( pe_packing_data.type != NULL ) {
if ( trick_MM->delete_var( static_cast< void * >( pe_packing_data.type ) ) ) {
message_publish( MSG_WARNING, "PhysicalEntity::copy_working_data():%d WARNING failed to delete Trick Memory for 'pe_packing_data.type'\n",
__LINE__ );
}
pe_packing_data.type = NULL;
}
}
// Check for status change.
if ( physical_data->status != NULL ) {
if ( pe_packing_data.status != NULL ) {
if ( strcmp( physical_data->status, pe_packing_data.status ) ) {
if ( trick_MM->delete_var( static_cast< void * >( pe_packing_data.status ) ) ) {
message_publish( MSG_WARNING, "PhysicalEntity::copy_working_data():%d WARNING failed to delete Trick Memory for 'pe_packing_data.status'\n",
__LINE__ );
}
pe_packing_data.status = trick_MM->mm_strdup( physical_data->status );
}
} else {
pe_packing_data.status = trick_MM->mm_strdup( physical_data->status );
}
} else {
if ( pe_packing_data.status != NULL ) {
if ( trick_MM->delete_var( static_cast< void * >( pe_packing_data.status ) ) ) {
message_publish( MSG_WARNING, "PhysicalEntity::copy_working_data():%d WARNING failed to delete Trick Memory for 'pe_packing_data.status'\n",
__LINE__ );
}
pe_packing_data.status = NULL;
}
}
// Check for parent frame change.
if ( physical_data->parent_frame != NULL ) {
if ( pe_packing_data.parent_frame != NULL ) {
// We have a parent frame; so, check to see if frame names are different.
if ( strcmp( physical_data->parent_frame, pe_packing_data.parent_frame ) ) {
// Frames are different, so reassign the new frame string.
if ( trick_MM->delete_var( static_cast< void * >( pe_packing_data.parent_frame ) ) ) {
message_publish( MSG_WARNING, "PhysicalEntity::copy_working_data():%d WARNING failed to delete Trick Memory for 'pe_packing_data.parent_frame'\n",
__LINE__ );
}
pe_packing_data.parent_frame = trick_MM->mm_strdup( physical_data->parent_frame );
}
} else {
// No parent frame name to compare so copy name.
pe_packing_data.parent_frame = trick_MM->mm_strdup( physical_data->parent_frame );
}
} else {
// This is bad scoobies so just punt.
ostringstream errmsg;
errmsg << "SpaceFOM::PhysicalEntity::copy_working_data():" << __LINE__
<< " ERROR: Unexpected NULL parent frame for PhysicalEntity: "
<< physical_data->name << '\n';
// Print message and terminate.
TrickHLA::DebugHandler::terminate_with_message( errmsg.str() );
}
// Pack the state time coordinate data.
// Position and velocity vectors.
for ( iinc = 0; iinc < 3; ++iinc ) {
pe_packing_data.state.pos[iinc] = physical_data->state.pos[iinc];
pe_packing_data.state.vel[iinc] = physical_data->state.vel[iinc];
}
// Attitude quaternion.
pe_packing_data.state.att.scalar = physical_data->state.att.scalar;
for ( iinc = 0; iinc < 3; ++iinc ) {
pe_packing_data.state.att.vector[iinc] = physical_data->state.att.vector[iinc];
pe_packing_data.state.ang_vel[iinc] = physical_data->state.ang_vel[iinc];
}
// Time tag for this state data.
pe_packing_data.state.time = get_scenario_time();
// Set the acceleration data.
for ( iinc = 0; iinc < 3; ++iinc ) {
pe_packing_data.accel[iinc] = physical_data->accel[iinc];
}
// Set the rotational acceleration data.
for ( iinc = 0; iinc < 3; ++iinc ) {
pe_packing_data.ang_accel[iinc] = physical_data->ang_accel[iinc];
}
// Set the center of mass location.
for ( iinc = 0; iinc < 3; ++iinc ) {
pe_packing_data.cm[iinc] = physical_data->cm[iinc];
}
// Pack the body to structural reference frame attitude quaternion.
pe_packing_data.body_wrt_struct.scalar = physical_data->body_wrt_struct.scalar;
for ( iinc = 0; iinc < 3; ++iinc ) {
pe_packing_data.body_wrt_struct.vector[iinc] = physical_data->body_wrt_struct.vector[iinc];
}
// Return to the calling routine.
return;
}
/*!
* @job_class{scheduled}
*/
void PhysicalEntity::unpack_into_working_data()
{
// If the HLA attribute has changed and is remotely owned (i.e. is
// coming from another federate) then override our simulation state with the
// incoming value. If we locally own the attribute then we do not want to
// override it's value. If we did not do this check then we would be
// overriding state of something we own and publish with whatever value
// happen to be in the local variable, which would cause data corruption of
// the state. We always need to do this check because ownership transfers
// could happen at any time or the data could be at a different rate.
// Set the entity name, type, status, and parent frame name.
if ( name_attr->is_received() ) {
if ( physical_data->name != NULL ) {
if ( !strcmp( physical_data->name, pe_packing_data.name ) ) {
if ( trick_MM->delete_var( static_cast< void * >( physical_data->name ) ) ) {
message_publish( MSG_WARNING, "PhysicalEntity::unpack_into_working_data():%d WARNING failed to delete Trick Memory for 'physical_data->name'\n",
__LINE__ );
}
physical_data->name = trick_MM->mm_strdup( pe_packing_data.name );
}
} else {
physical_data->name = trick_MM->mm_strdup( pe_packing_data.name );
}
}
if ( type_attr->is_received() ) {
if ( physical_data->type != NULL ) {
if ( !strcmp( physical_data->type, pe_packing_data.type ) ) {
if ( trick_MM->delete_var( static_cast< void * >( physical_data->type ) ) ) {
message_publish( MSG_WARNING, "PhysicalEntity::unpack_into_working_data():%d WARNING failed to delete Trick Memory for 'physical_data->type'\n",
__LINE__ );
}
physical_data->type = trick_MM->mm_strdup( pe_packing_data.type );
}
} else {
physical_data->type = trick_MM->mm_strdup( pe_packing_data.type );
}
}
if ( status_attr->is_received() ) {
if ( physical_data->status != NULL ) {
if ( !strcmp( physical_data->status, pe_packing_data.status ) ) {
if ( trick_MM->delete_var( static_cast< void * >( physical_data->status ) ) ) {
message_publish( MSG_WARNING, "PhysicalEntity::unpack_into_working_data():%d WARNING failed to delete Trick Memory for 'physical_data->status'\n",
__LINE__ );
}
physical_data->status = trick_MM->mm_strdup( pe_packing_data.status );
}
} else {
physical_data->status = trick_MM->mm_strdup( pe_packing_data.status );
}
}
if ( parent_frame_attr->is_received() ) {
if ( physical_data->parent_frame != NULL ) {
if ( !strcmp( physical_data->parent_frame, pe_packing_data.parent_frame ) ) {
if ( trick_MM->delete_var( static_cast< void * >( physical_data->parent_frame ) ) ) {
message_publish( MSG_WARNING, "PhysicalEntity::unpack_into_working_data():%d WARNING failed to delete Trick Memory for 'physical_data->parent_frame'\n",
__LINE__ );
}
if ( pe_packing_data.parent_frame[0] != '\0' ) {
physical_data->parent_frame = trick_MM->mm_strdup( pe_packing_data.parent_frame );
} else {
physical_data->parent_frame = NULL;
}
}
} else {
if ( pe_packing_data.parent_frame[0] != '\0' ) {
physical_data->parent_frame = trick_MM->mm_strdup( pe_packing_data.parent_frame );
}
}
}
// Unpack the space-time coordinate state data.
if ( state_attr->is_received() ) {
// Unpack the data.
// Position and velocity vectors.
for ( int iinc = 0; iinc < 3; ++iinc ) {
physical_data->state.pos[iinc] = pe_packing_data.state.pos[iinc];
physical_data->state.vel[iinc] = pe_packing_data.state.vel[iinc];
}
// Attitude quaternion.
physical_data->state.att.scalar = pe_packing_data.state.att.scalar;
for ( int iinc = 0; iinc < 3; ++iinc ) {
physical_data->state.att.vector[iinc] = pe_packing_data.state.att.vector[iinc];
physical_data->state.ang_vel[iinc] = pe_packing_data.state.ang_vel[iinc];
}
// Time tag for this state data.
physical_data->state.time = pe_packing_data.state.time;
}
// Unpack the translational acceleration data.
if ( accel_attr->is_received() ) {
for ( int iinc = 0; iinc < 3; ++iinc ) {
physical_data->accel[iinc] = pe_packing_data.accel[iinc];
}
}
// Unpack the rotational acceleration data.
if ( ang_accel_attr->is_received() ) {
for ( int iinc = 0; iinc < 3; ++iinc ) {
physical_data->ang_accel[iinc] = pe_packing_data.ang_accel[iinc];
}
}
// Unpack the center of mass data.
if ( cm_attr->is_received() ) {
for ( int iinc = 0; iinc < 3; ++iinc ) {
physical_data->cm[iinc] = pe_packing_data.cm[iinc];
}
}
// Unpack the body to structural attitude data.
if ( body_frame_attr->is_received() ) {
// Body to structure frame orientation.
physical_data->body_wrt_struct.scalar = pe_packing_data.body_wrt_struct.scalar;
for ( int iinc = 0; iinc < 3; ++iinc ) {
physical_data->body_wrt_struct.vector[iinc] = pe_packing_data.body_wrt_struct.vector[iinc];
}
}
return;
}
| 412 | 0.976028 | 1 | 0.976028 | game-dev | MEDIA | 0.742149 | game-dev | 0.949726 | 1 | 0.949726 |
Sgt-Imalas/Sgt_Imalas-Oni-Mods | 2,378 | SkillsInfoScreen/ModIntegration_CleanHud.cs | using Epic.OnlineServices.Platform;
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UtilLibs;
namespace SkillsInfoScreen
{
internal class ModIntegration_CleanHud
{
/// <summary>
/// wrapper that allows fetching a config state value of type T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="propertyName"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool TryGetConfigValue<T>(string propertyName, out T value)
{
value = default(T);
InitTypes();
if (ConfigInstance == null)
return false;
Traverse property = Traverse.Create(ConfigInstance).Property(propertyName);
if (!property.PropertyExists())
{
Debug.LogWarning("Mod Config State did not have a property with the name: " + propertyName);
return false;
}
object propertyValue = property.GetValue();
var foundType = propertyValue.GetType();
var T_Type = typeof(T);
if (foundType != T_Type)
{
Debug.LogWarning("Mod Config State had a property with the name: " + propertyName + ", but it was typeOf " + foundType.Name + ", instead of the expected " + T_Type.Name);
return false;
}
value = (T)propertyValue;
return true;
}
/// <summary>
/// Integration with CleanHud small buttons
/// </summary>
static object ConfigInstance = null;
static void InitTypes()
{
if (ConfigInstance != null)
return;
var CleanHUD_Options = Type.GetType("CleanHUD.Options, CleanHUD");
if (CleanHUD_Options == null)
{
SgtLogger.l("CleanHUD.Options type not found.");
//UtilMethods.ListAllTypesWithAssemblies();
return;
}
ConfigInstance = null;
var m_GetConfigInstance = CleanHUD_Options.GetProperty("Opts", BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public );
if (m_GetConfigInstance == null)
{
SgtLogger.error("CleanHUD_Options.Opts property not found.");
return;
}
try
{
ConfigInstance = m_GetConfigInstance.GetValue(null);
}
catch (Exception e)
{
SgtLogger.error("Failure to get Config Instance from CleanHUD_Options:\n" + e.Message);
}
SgtLogger.l("CleanHUD_Options integration: " + (ConfigInstance != null ? "Success" : "Failed"));
}
}
}
| 412 | 0.959188 | 1 | 0.959188 | game-dev | MEDIA | 0.159238 | game-dev | 0.954635 | 1 | 0.954635 |
smartties/Blip-Blop-for-Android | 1,958 | jni/src/ennemi_com_heros.cpp | /******************************************************************
*
*
* ----------------------
* EnnemiComHeros.cpp
* ----------------------
*
*
*
* Mephisto / LOADED - V 0.1 - 14 Janvier 2001
*
*
*
******************************************************************/
#include "ennemi_com_heros.h"
EnnemiComHeros::EnnemiComHeros(): dorkeball(2)
{
pv = 1000;
dy = -8;
dx = -2;
}
void EnnemiComHeros::update()
{
if (dorkeball == 2) {
x += dx;
tombe();
int yp;
if ((dy > 0) && (yp = plat(x, y + dy)) != 0) {
etat = ETAT_NORMAL;
dy = 0;
y = yp;
etape = 0;
ss_etape = 0;
dorkeball = 1;
return;
} else {
ss_etape ++;
ss_etape %= 5;
if (ss_etape == 0) {
etape ++;
etape %= 4;
}
pic = pbk_ennemis[272 + etape];
}
} else if (dorkeball == 1) {
ss_etape ++;
ss_etape %= 8;
if (ss_etape == 0) {
etape ++;
if (etape > 3) {
dorkeball = 0;
etape = 0;
ss_etape = 0;
} else {
pic = pbk_ennemis[388 + etape];
}
}
} else {
if (blood > 0)
blood -= 1;
switch (etat) {
case ETAT_NORMAL:
case ETAT_AVANCE:
onAvance();
break;
case ETAT_MEURE:
case ETAT_CARBONISE:
onMeure();
break;
}
updateADetruire();
}
}
void EnnemiComHeros::onAvance()
{
tombe();
ss_etape += 1;
ss_etape %= 8;
if (ss_etape == 0) {
etape += 1;
etape %= 2;
}
// Marche
//
if (x - 1 < xmin || mur_opaque(x - 1, y))
dir = SENS_DROITE;
else if (x + 1 > offset + 640 || mur_opaque(x + 1, y))
dir = SENS_GAUCHE;
if (dir == SENS_DROITE) {
marche(2);
} else {
marche(-2);
}
pic = pbk_ennemis[304 + etape];
colFromPic();
}
void EnnemiComHeros::onMeure()
{
tombe();
ss_etape += 1;
ss_etape %= 4;
if (ss_etape == 0 && etape < 22)
etape += 1;
if (etape >= 22) {
game_flag[1] --;
a_detruire = true;
} else {
pic = pbk_ennemis[358 + etape];
}
}
void EnnemiComHeros::estTouche(Tir * tir)
{
Ennemi::estTouche(tir);
} | 412 | 0.823045 | 1 | 0.823045 | game-dev | MEDIA | 0.709952 | game-dev | 0.918077 | 1 | 0.918077 |
HunterPie/HunterPie | 9,456 | HunterPie.UI/Overlay/Widgets/Monster/MonsterContextHandler.cs | using HunterPie.Core.Client.Configuration.Overlay;
using HunterPie.Core.Game.Entity.Enemy;
using HunterPie.Core.Game.Entity.Game;
using HunterPie.Core.Game.Enums;
using HunterPie.Core.Game.Events;
using HunterPie.Core.Game.Services.Monster.Events;
using HunterPie.Integrations.Datasources.MonsterHunterRise.Entity.Enemy;
using HunterPie.Integrations.Datasources.MonsterHunterWilds.Entity.Enemy;
using HunterPie.Integrations.Datasources.MonsterHunterWorld.Entity.Enemy;
using HunterPie.UI.Overlay.Widgets.Monster.Adapters;
using HunterPie.UI.Overlay.Widgets.Monster.ViewModels;
using System;
using System.ComponentModel;
using System.Linq;
namespace HunterPie.UI.Overlay.Widgets.Monster;
public class MonsterContextHandler : BossMonsterViewModel, IContextHandler, IDisposable
{
private readonly IGame _game;
public readonly IMonster Context;
public MonsterContextHandler(
IGame game,
IMonster context,
MonsterWidgetConfig config
) : base(config)
{
_game = game;
Context = context;
HookEvents();
AddEnrage();
UpdateData();
}
public void HookEvents()
{
_game.TargetDetectionService.OnTargetChanged += OnTargetDetectionChanged;
Config.TargetMode.PropertyChanged += OnTargetModeChange;
Context.OnHealthChange += OnHealthUpdate;
Context.OnStaminaChange += OnStaminaUpdate;
Context.OnCaptureThresholdChange += OnCaptureThresholdChange;
Context.OnEnrageStateChange += OnEnrageStateChange;
Context.OnSpawn += OnSpawn;
Context.OnDeath += OnDespawn;
Context.OnDespawn += OnDespawn;
Context.OnTargetChange += OnTargetChange;
Context.OnNewPartFound += OnNewPartFound;
Context.OnNewAilmentFound += OnNewAilmentFound;
Context.OnCrownChange += OnCrownChange;
Context.OnWeaknessesChange += OnWeaknessesChange;
}
public void UnhookEvents()
{
_game.TargetDetectionService.OnTargetChanged -= OnTargetDetectionChanged;
Config.TargetMode.PropertyChanged -= OnTargetModeChange;
Context.OnHealthChange -= OnHealthUpdate;
Context.OnStaminaChange -= OnStaminaUpdate;
Context.OnCaptureThresholdChange -= OnCaptureThresholdChange;
Context.OnEnrageStateChange -= OnEnrageStateChange;
Context.OnSpawn -= OnSpawn;
Context.OnDeath -= OnDespawn;
Context.OnDespawn -= OnDespawn;
Context.OnTargetChange -= OnTargetChange;
Context.OnNewPartFound -= OnNewPartFound;
Context.OnNewAilmentFound -= OnNewAilmentFound;
Context.OnCrownChange -= OnCrownChange;
Context.OnWeaknessesChange -= OnWeaknessesChange;
}
private void OnTargetDetectionChanged(object sender, InferTargetChangedEventArgs e) =>
HandleTargetUpdate(
lockOnTarget: Context.Target,
manualTarget: Context.ManualTarget,
inferredTarget: _game.TargetDetectionService.Infer(Context)
);
private void OnTargetModeChange(object sender, PropertyChangedEventArgs _) =>
HandleTargetUpdate(
lockOnTarget: Context.Target,
manualTarget: Context.ManualTarget,
inferredTarget: _game.TargetDetectionService.Infer(Context)
);
private void OnSpawn(object sender, EventArgs e)
{
IsQurio = Context is MHRMonster { MonsterType: MonsterType.Qurio };
Name = Context.Name;
Em = BuildMonsterEmByContext();
IsAlive = true;
FetchMonsterIcon();
UIThread.BeginInvoke(() =>
{
if (Types.Count > 0)
return;
foreach (string typeId in Context.Types)
Types.Add(typeId);
});
}
private void OnDespawn(object sender, EventArgs e)
{
IsAlive = false;
}
private void OnCaptureThresholdChange(object sender, IMonster e)
{
CaptureThreshold = e.CaptureThreshold;
IsCapturable = CaptureThreshold >= (Health / MaxHealth);
CanBeCaptured = e.CaptureThreshold > 0;
}
private void OnWeaknessesChange(object sender, Element[] e)
{
UIThread.BeginInvoke(() =>
{
lock (Weaknesses)
{
Weaknesses.Clear();
foreach (Element weakness in e)
Weaknesses.Add(weakness);
}
});
}
private void OnStaminaUpdate(object sender, EventArgs e)
{
MaxStamina = Context.MaxStamina;
Stamina = Context.Stamina;
}
private void OnEnrageStateChange(object sender, EventArgs e) => IsEnraged = Context.IsEnraged;
private void OnCrownChange(object sender, EventArgs e) => Crown = Context.Crown;
private void OnNewAilmentFound(object sender, IMonsterAilment e)
{
UIThread.BeginInvoke(() =>
{
bool contains = Ailments.ToArray()
.Cast<MonsterAilmentContextHandler>()
.Any(p => p.Context == e);
if (contains)
return;
Ailments.Add(new MonsterAilmentContextHandler(Context, e, Config));
});
}
private void OnNewPartFound(object sender, IMonsterPart e)
{
UIThread.Invoke(() =>
{
bool contains = Parts.ToArray()
.Cast<MonsterPartContextHandler>()
.Any(p => p.Context == e);
if (contains)
return;
Parts.Add(new MonsterPartContextHandler(Context, e, Config));
});
}
private void OnTargetChange(object sender, MonsterTargetEventArgs e) =>
HandleTargetUpdate(
lockOnTarget: e.LockOnTarget,
manualTarget: e.ManualTarget,
inferredTarget: _game.TargetDetectionService.Infer(Context)
);
private void OnHealthUpdate(object sender, EventArgs e)
{
MaxHealth = Context.MaxHealth;
Health = Context.Health;
IsCapturable = CaptureThreshold >= (Health / MaxHealth);
}
private void UpdateData()
{
IsQurio = Context is MHRMonster { MonsterType: MonsterType.Qurio };
Variant = Context.Variant;
if (Context.Id > -1)
{
Name = Context.Name;
Em = BuildMonsterEmByContext();
FetchMonsterIcon();
}
MaxHealth = Context.MaxHealth;
Health = Context.Health;
HandleTargetUpdate(
lockOnTarget: Context.Target,
manualTarget: Context.ManualTarget,
inferredTarget: _game.TargetDetectionService.Infer(Context)
);
MaxStamina = Context.MaxStamina;
Stamina = Context.Stamina;
TargetType = Context.Target;
Crown = Context.Crown;
IsEnraged = Context.IsEnraged;
IsAlive = Context.Health > 0;
CaptureThreshold = Context.CaptureThreshold;
CanBeCaptured = Context.CaptureThreshold > 0;
IsCapturable = CaptureThreshold >= (Health / MaxHealth);
UIThread.BeginInvoke(() =>
{
foreach (string typeId in Context.Types)
Types.Add(typeId);
foreach (Element weakness in Context.Weaknesses)
Weaknesses.Add(weakness);
if (Parts.Count != Context.Parts.Count || Ailments.Count != Context.Ailments.Count)
{
foreach (IMonsterPart part in Context.Parts)
{
bool contains = Parts
.ToArray()
.Cast<MonsterPartContextHandler>()
.Any(p => p.Context == part);
if (contains)
continue;
Parts.Add(new MonsterPartContextHandler(Context, part, Config));
}
foreach (IMonsterAilment ailment in Context.Ailments)
{
bool contains = Ailments
.ToArray()
.Cast<MonsterAilmentContextHandler>()
.Any(p => p.Context == ailment);
if (contains)
continue;
Ailments.Add(new MonsterAilmentContextHandler(Context, ailment, Config));
}
}
});
}
private void AddEnrage() => UIThread.BeginInvoke(() => Ailments.Add(new MonsterAilmentContextHandler(Context, Context.Enrage, Config)));
private string BuildMonsterEmByContext()
{
return Context switch
{
MHRMonster ctx => $"Rise_{ctx.Id:00}",
MHWMonster ctx => $"World_{ctx.Id:00}",
MHWildsMonster ctx => $"Wilds_{ctx.Id:00}",
_ => throw new NotImplementedException("unreachable")
};
}
private void HandleTargetUpdate(
Target lockOnTarget,
Target manualTarget,
Target inferredTarget
)
{
TargetType = MonsterTargetAdapter.Adapt(Config, lockOnTarget, manualTarget, inferredTarget);
IsTarget = TargetType == Target.Self || (TargetType == Target.None && !Config.ShowOnlyTarget);
}
public void Dispose()
{
UnhookEvents();
foreach (MonsterPartViewModel part in Parts)
part.Dispose();
foreach (MonsterAilmentViewModel ailment in Ailments)
ailment.Dispose();
Parts.Clear();
Ailments.Clear();
}
} | 412 | 0.927175 | 1 | 0.927175 | game-dev | MEDIA | 0.727409 | game-dev | 0.940258 | 1 | 0.940258 |
Adam4lexander/Spoke | 2,723 | Spoke.Unity/SpokeBehaviour.cs | using UnityEngine;
namespace Spoke {
/// <summary>
/// The easiest way to use Spoke is to extend SpokeBehaviour instead of MonoBehaviour.
/// It sets up a SpokeTree, and exposes lifecycle signals you can use to manage state.
///
/// A single method: Init(), is called during Awake to set up your effects.
/// Override this method instead of Awake, OnEnable, Start, etc.
///
/// Works fine with [ExecuteAlways] behaviours
/// </summary>
public abstract class SpokeBehaviour : MonoBehaviour {
State<bool> isAwake = State.Create(false);
State<bool> isEnabled = State.Create(false);
State<bool> isStarted = State.Create(false);
/// <summary>True after Awake, False after Destroyed</summary>
public ISignal<bool> IsAwake => isAwake;
/// <summary>True while the behaviour is enabled</summary>
public ISignal<bool> IsEnabled => isEnabled;
/// <summary>True after Start has run</summary>
public ISignal<bool> IsStarted => isStarted;
SpokeHandle sceneTeardown, appTeardown;
SpokeTree root;
/// <summary>
/// Override Init to set up your Spoke effects.
/// It's an EffectBlock that will be hosted by the root Effect in the tree.
/// </summary>
protected abstract void Init(EffectBuilder s);
protected virtual void Awake() {
DoInit();
}
protected virtual void OnDestroy() {
DoTeardown();
}
protected virtual void OnEnable() {
if (root == null) DoInit(); // Domain reload may not run Awake
isEnabled.Set(true);
}
protected virtual void OnDisable() {
isEnabled.Set(false);
}
protected virtual void Start() {
isStarted.Set(true);
}
void DoInit() {
root = SpokeTree.Spawn($"{GetType().Name}:SpokeTree", new Effect("Init", Init), new UnitySpokeLogger(this));
sceneTeardown = SpokeTeardown.Scene.Subscribe(scene => {
if (scene == gameObject.scene) DoTeardown();
});
appTeardown = SpokeTeardown.App.Subscribe(() => DoTeardown());
isAwake.Set(true);
}
void DoTeardown() {
sceneTeardown.Dispose();
appTeardown.Dispose();
// Avoid setting enabled=false for ExecuteAlways behaviours on domain reload. Because
// it will be serialized as disabled on each reload.
if (Application.isPlaying) enabled = false;
isEnabled.Set(false);
root?.Dispose();
root = default;
isAwake.Set(false);
}
}
} | 412 | 0.890911 | 1 | 0.890911 | game-dev | MEDIA | 0.953522 | game-dev | 0.949013 | 1 | 0.949013 |
JosePaumard/streams-utils | 3,148 | src/main/java/org/paumard/spliterators/FilteringAllMaxSpliterator.java | /*
* Copyright (C) 2015 José Paumard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.paumard.spliterators;
import org.paumard.streams.StreamsUtils;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* See the documentation and patterns to be used in this class in the {@link StreamsUtils} factory class.
*
* @author José
*/
public class FilteringAllMaxSpliterator<E> implements Spliterator<E> {
private final Spliterator<E> spliterator;
private final Comparator<? super E> comparator;
private Stream.Builder<E> builder = Stream.builder();
private E currentMax;
private boolean hasMore = true;
private boolean maxesBuilt = false;
private Iterator<E> maxes;
public static <E> FilteringAllMaxSpliterator<E> of(
Spliterator<E> spliterator,
Comparator<? super E> comparator) {
Objects.requireNonNull(spliterator);
Objects.requireNonNull(comparator);
return new FilteringAllMaxSpliterator<>(spliterator, comparator);
}
private FilteringAllMaxSpliterator(
Spliterator<E> spliterator,
Comparator<? super E> comparator) {
this.spliterator = spliterator;
this.comparator = comparator;
}
@Override
public boolean tryAdvance(Consumer<? super E> action) {
while (hasMore) {
hasMore = spliterator.tryAdvance(e -> {
if (currentMax == null) {
currentMax = e;
builder.add(e);
} else if (comparator.compare(currentMax, e) == 0) {
builder.add(e);
} else if (comparator.compare(currentMax, e) < 0) {
currentMax = e;
builder = Stream.builder();
builder.add(e);
}
});
}
if (!maxesBuilt) {
maxes = builder.build().collect(Collectors.toList()).iterator();
maxesBuilt = true;
}
if (maxesBuilt && maxes.hasNext()) {
action.accept(maxes.next());
return true;
}
return false;
}
@Override
public Spliterator<E> trySplit() {
return null;
}
@Override
public long estimateSize() {
return 0L;
}
@Override
public int characteristics() {
return spliterator.characteristics() & ~Spliterator.SIZED & ~Spliterator.SUBSIZED;
}
@Override
public Comparator<? super E> getComparator() {
return this.spliterator.getComparator();
}
} | 412 | 0.823922 | 1 | 0.823922 | game-dev | MEDIA | 0.435571 | game-dev | 0.956408 | 1 | 0.956408 |
MobileGL-Dev/MobileGL | 4,937 | MobileGL/MG_State/GLState/ProgramState/ProgramObject.h | #pragma once
#include <Includes.h>
#include "ShaderObject.h"
#include "MG_Util/Metrics/BufferMetrics.h"
#include "MG_Util/ShaderTranspiler/SpvcSession.h"
namespace MobileGL {
namespace MG_State {
namespace GLState {
class ProgramObject {
public:
ProgramObject(const Uint id) : m_id(id) {}
bool ShaderIsAttached(SharedPtr<ShaderObject> shader);
bool AttachShader(SharedPtr<ShaderObject> shader);
SizeT DetachShader(SharedPtr<ShaderObject> shader);
void Link();
void MarkAsDeleted();
void SetExplicitAttribLocation(Uint index, const char* name);
Vector<SharedPtr<ShaderObject>>& GetAttachedShaders();
const String& GetInfoLog() const { return m_infoLog; }
Int GetUniformMaxLength() const { return m_uniformNameMaxLength; }
Uint GetUniformCount() { return m_activeUniformCount; }
Uint GetMaxUniformLocation() const { return m_maxUniformLocation; }
Int GetUniformLocation(const String& name) {
const auto it = m_uniformLocations.find(name);
return (it == m_uniformLocations.end()) ? -1 : (Int)it->second;
}
GLenum GetUniformType(Uint index) const { return m_uniformTypes[index]; }
Bool IsUniformOpaqueAtLocation(Uint location) const { return m_uniformIsOpaqueType[location]; }
const String& GetUniformName(Uint index) const { return m_uniformNames[index]; }
Uint GetUniformOffset(Uint location) const { return m_uniformOffsets[location]; }
Uint GetUniformSizesInBytes(Uint location) const {
return MG_Util::GetGLTypeSize(m_uniformTypes[location]);
}
Int GetAttributeLocation(const String& name) {
const auto it = std::find(m_attribs.begin(), m_attribs.end(), name);
return (it == m_attribs.end()) ? -1 : std::distance(m_attribs.begin(), it);
}
GLenum GetAttribType(Uint index) const { return m_attribTypes[index]; }
const String& GetAttribName(Uint index) const { return m_attribs[index]; }
void* MapUBO() { return m_uboScratch.data(); }
Bool GetDeleteStatus() const { return m_deleteStatus; }
Bool GetLinkStatus() const { return m_linkStatus; }
Bool GetValidateStatus() const { return m_validateStatus; }
Int GetActiveAtomicCounterCount() const { return m_program->getNumAtomicCounters(); }
Int GetActiveAttributesCount() const { return m_program->getNumPipeInputs(); }
Int GetActiveUniformBlocksCount() const { return m_program->getNumUniformBlocks(); }
Int GetActiveAttributesMaxLength() const { return m_attribInNameMaxLength; }
Int GetActiveUniformBlocksMaxNameLength() const { return m_uniformBlockNameMaxLength; }
private:
void DoReflection();
void GenerateBinary();
void WaitUntilGenerationCompleted();
// void PreLink();
// void PostLink();
const Uint m_id = 0;
Vector<SharedPtr<ShaderObject>> m_shaders;
SharedPtr<glslang::TProgram> m_program;
Vector<Vector<unsigned>> m_generatedSpirv;
// Attributes
UnorderedMap<String, Uint> m_explicitAttribLocations;
Vector<String> m_attribs;
Vector<GLenum> m_attribTypes;
// Uniforms
// MG_Util::ShaderTranspiler::SpvcMetadata m_metadata;
UnorderedMap<String, Uint> m_uniformLocations;
// Ordered by location,
// aka. m_uniformNames[loc] == "name at location `loc`"
Vector<String> m_uniformNames;
// ditto.
Vector<GLenum> m_uniformTypes;
Vector<Bool> m_uniformIsOpaqueType;
Vector<Int> m_uniformArraySizes;
// Need to be reflected after linking of SPIR-V binary
Vector<Uint> m_uniformOffsets;
Vector<Uint> m_uniformSizesInBytes;
Vector<Uint8> m_uboScratch;
Uint m_activeUniformCount = 0;
Uint m_maxUniformLocation = 0;
Int m_uniformNameMaxLength = 0;
Int m_attribInNameMaxLength = 0;
Int m_uniformBlockNameMaxLength = 0;
String m_infoLog;
Bool m_deleteStatus = false;
Bool m_linkStatus = false;
Bool m_validateStatus = true;
};
} // namespace GLState
} // namespace MG_State
} // namespace MobileGL
| 412 | 0.77041 | 1 | 0.77041 | game-dev | MEDIA | 0.341762 | game-dev | 0.629627 | 1 | 0.629627 |
f15gdsy/BT-Framework | 1,183 | Core/BTPrioritySelector.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace BT {
/// <summary>
/// BTPrioritySelector selects the first sussessfully evaluated child as the active child.
/// </summary>
public class BTPrioritySelector : BTNode {
private BTNode _activeChild;
public BTPrioritySelector (BTPrecondition precondition = null) : base (precondition) {}
// selects the active child
protected override bool DoEvaluate () {
foreach (BTNode child in children) {
if (child.Evaluate()) {
if (_activeChild != null && _activeChild != child) {
_activeChild.Clear();
}
_activeChild = child;
return true;
}
}
if (_activeChild != null) {
_activeChild.Clear();
_activeChild = null;
}
return false;
}
public override void Clear () {
if (_activeChild != null) {
_activeChild.Clear();
_activeChild = null;
}
}
public override BTResult Tick () {
if (_activeChild == null) {
return BTResult.Ended;
}
BTResult result = _activeChild.Tick();
if (result != BTResult.Running) {
_activeChild.Clear();
_activeChild = null;
}
return result;
}
}
} | 412 | 0.955131 | 1 | 0.955131 | game-dev | MEDIA | 0.726669 | game-dev | 0.969877 | 1 | 0.969877 |
lua9520/source-engine-2018-cstrike15_src | 7,400 | public/p4lib/ip4.h | //====== Copyright 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#ifndef IP4_H
#define IP4_H
#ifdef _WIN32
#pragma once
#endif
#include "tier1/utlsymbol.h"
#include "tier1/utlvector.h"
#include "tier1/utlstring.h"
#include "appframework/iappsystem.h"
//-----------------------------------------------------------------------------
// Current perforce file state
//-----------------------------------------------------------------------------
enum P4FileState_t
{
P4FILE_UNOPENED = 0,
P4FILE_OPENED_FOR_ADD,
P4FILE_OPENED_FOR_EDIT,
P4FILE_OPENED_FOR_DELETE,
P4FILE_OPENED_FOR_INTEGRATE,
};
//-----------------------------------------------------------------------------
// Purpose: definition of a file
//-----------------------------------------------------------------------------
struct P4File_t
{
CUtlSymbol m_sName; // file name
CUtlSymbol m_sPath; // residing folder
CUtlSymbol m_sDepotFile; // the name in the depot
CUtlSymbol m_sClientFile; // the name on the client in Perforce syntax
CUtlSymbol m_sLocalFile; // the name on the client in local syntax
int m_iHeadRevision; // head revision number
int m_iHaveRevision; // the revision the clientspec has synced locally
bool m_bOpenedByOther; // opened by another user
bool m_bDir; // directory
bool m_bDeleted; // deleted
P4FileState_t m_eOpenState; // current change state
int m_iChangelist; // changelist current opened in
};
//-----------------------------------------------------------------------------
// Purpose: a single revision of a file
//-----------------------------------------------------------------------------
struct P4Revision_t
{
int m_iChange; // changelist number
int m_nYear, m_nMonth, m_nDay;
int m_nHour, m_nMinute, m_nSecond;
CUtlSymbol m_sUser; // submitting user
CUtlSymbol m_sClient; // submitting client
CUtlString m_Description;
};
//-----------------------------------------------------------------------------
// Purpose: a single clientspec
//-----------------------------------------------------------------------------
struct P4Client_t
{
CUtlSymbol m_sName;
CUtlSymbol m_sUser;
CUtlSymbol m_sHost; // machine name this client is on
CUtlSymbol m_sLocalRoot; // local path
};
//-----------------------------------------------------------------------------
// Purpose: Interface to accessing P4 commands
//-----------------------------------------------------------------------------
#define P4_MAX_INPUT_BUFFER_SIZE 16384 // descriptions should be limited to this size!
abstract_class IP4 : public IAppSystem
{
public:
// name of the current clientspec
virtual P4Client_t &GetActiveClient() = 0;
// changes the current client
virtual void SetActiveClient(const char *clientname) = 0;
// Refreshes the current client from p4 settings
virtual void RefreshActiveClient() = 0;
// translate filespecs into the desired syntax
virtual void GetDepotFilePath(char *depotFilePath, const char *filespec, int size) = 0;
virtual void GetClientFilePath(char *clientFilePath, const char *filespec, int size) = 0;
virtual void GetLocalFilePath(char *localFilePath, const char *filespec, int size) = 0;
// retreives the list of files in a path
virtual CUtlVector<P4File_t> &GetFileList( const char *path ) = 0;
// returns the list of files opened for edit/integrate/delete
virtual void GetOpenedFileList( CUtlVector<P4File_t> &fileList, bool bDefaultChangeOnly ) = 0;
virtual void GetOpenedFileList( const char *pRootDirectory, CUtlVector<P4File_t> &fileList ) = 0;
virtual void GetOpenedFileListInPath( const char *pPathID, CUtlVector<P4File_t> &fileList ) = 0;
// retrieves revision history for a file or directory
virtual CUtlVector<P4Revision_t> &GetRevisionList( const char *path, bool bIsDir ) = 0;
// returns a list of clientspecs
virtual CUtlVector<P4Client_t> &GetClientList() = 0;
// changes the clientspec to remove the specified path (cloaking)
virtual void RemovePathFromActiveClientspec( const char *path ) = 0;
// file manipulation
virtual bool OpenFileForAdd( const char *pFullPath ) = 0;
virtual bool OpenFileForEdit( const char *pFullPath ) = 0;
virtual bool OpenFileForDelete( const char *pFullPath ) = 0;
virtual bool SyncFile( const char *pFullPath, int nRevision = -1 ) = 0; // default revision is to sync to the head revision
// submit/revert
virtual bool SubmitFile( const char *pFullPath, const char *pDescription ) = 0;
virtual bool RevertFile( const char *pFullPath ) = 0;
// file checkin/checkout for multiple files
virtual bool OpenFilesForAdd( int nCount, const char **ppFullPathList ) = 0;
virtual bool OpenFilesForEdit( int nCount, const char **ppFullPathList ) = 0;
virtual bool OpenFilesForDelete( int nCount, const char **ppFullPathList ) = 0;
// submit/revert for multiple files
virtual bool SubmitFiles( int nCount, const char **ppFullPathList, const char *pDescription ) = 0;
virtual bool RevertFiles( int nCount, const char **ppFullPathList ) = 0;
// Is this file in perforce?
virtual bool IsFileInPerforce( const char *pFullPath ) = 0;
// Get the perforce file state
virtual P4FileState_t GetFileState( const char *pFullPath ) = 0;
// depot root
virtual const char *GetDepotRoot() = 0;
virtual int GetDepotRootLength() = 0;
// local root
virtual const char *GetLocalRoot() = 0;
virtual int GetLocalRootLength() = 0;
// Gets a string for a symbol
virtual const char *String( CUtlSymbol s ) const = 0;
// Returns which clientspec a file lies under. This will
// search for p4config files in root directories of the file
// It returns false if it didn't find a p4config file.
virtual bool GetClientSpecForFile( const char *pFullPath, char *pClientSpec, int nMaxLen ) = 0;
virtual bool GetClientSpecForDirectory( const char *pFullPathDir, char *pClientSpec, int nMaxLen ) = 0;
// Returns which clientspec a filesystem path ID lies under. This will
// search for p4config files in all root directories of the all paths in
// the search path. NOTE: All directories in a path need to use the same clientspec
// or this function will return false.
// It returns false if it didn't find a p4config file.
virtual bool GetClientSpecForPath( const char *pPathId, char *pClientSpec, int nMaxLen ) = 0;
// Opens a file in p4 win
virtual void OpenFileInP4Win( const char *pFullPath ) = 0;
// have we connected? if not, nothing works
virtual bool IsConnectedToServer( bool bRetry = true ) = 0;
// Returns file information for a single file
virtual bool GetFileInfo( const char *pFullPath, P4File_t *pFileInfo ) = 0;
// retrieves the list of files in a path, using a known client spec
virtual CUtlVector<P4File_t> &GetFileListUsingClientSpec( const char *pPath, const char *pClientSpec ) = 0;
// retrieves the last error from the last op (which is likely to span multiple lines)
// this is only valid after OpenFile[s]For{Add,Edit,Delete} or {Submit,Revert}File[s]
virtual const char *GetLastError() = 0;
// sets the name of the changelist to open files under, NULL for "Default" changelist
virtual void SetOpenFileChangeList( const char *pChangeListName ) = 0;
virtual void GetFileListInChangelist( unsigned int changeListNumber, CUtlVector<P4File_t> &fileList ) = 0;
};
DECLARE_TIER2_INTERFACE( IP4, p4 );
#endif // IP4_H
| 412 | 0.877302 | 1 | 0.877302 | game-dev | MEDIA | 0.492276 | game-dev,networking | 0.655026 | 1 | 0.655026 |
LordOfDragons/dragengine | 3,103 | src/deigde/editors/speechAnimation/src/sanimation/phoneme/saePhonemeList.cpp | /*
* 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.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "saePhoneme.h"
#include "saePhonemeList.h"
#include <dragengine/deEngine.h>
#include <dragengine/common/exceptions.h>
// Class saePhoneme
/////////////////////
// Constructor, destructor
////////////////////////////
saePhonemeList::saePhonemeList(){
}
saePhonemeList::~saePhonemeList(){
}
// Management
///////////////
int saePhonemeList::GetCount() const{
return pPhonemes.GetCount();
}
saePhoneme *saePhonemeList::GetAt( int index ) const{
return ( saePhoneme* )pPhonemes.GetAt( index );
}
saePhoneme *saePhonemeList::GetIPA( int ipa ) const{
const int count = pPhonemes.GetCount();
saePhoneme *phoneme;
int p;
for( p=0; p<count; p++ ){
phoneme = ( saePhoneme* )pPhonemes.GetAt( p );
if( phoneme->GetIPA() == ipa ){
return phoneme;
}
}
return NULL;
}
int saePhonemeList::IndexOf( saePhoneme *phoneme ) const{
return pPhonemes.IndexOf( phoneme );
}
int saePhonemeList::IndexOfIPA( int ipa ) const{
const int count = pPhonemes.GetCount();
int p;
for( p=0; p<count; p++ ){
if( ( ( saePhoneme* )pPhonemes.GetAt( p ) )->GetIPA() == ipa ){
return p;
}
}
return -1;
}
bool saePhonemeList::Has( saePhoneme *phoneme ) const{
return pPhonemes.Has( phoneme );
}
bool saePhonemeList::HasIPA( int ipa ) const{
const int count = pPhonemes.GetCount();
int p;
for( p=0; p<count; p++ ){
if( ( ( saePhoneme* )pPhonemes.GetAt( p ) )->GetIPA() == ipa ){
return true;
}
}
return false;
}
void saePhonemeList::Add( saePhoneme *phoneme ){
if( ! phoneme || HasIPA( phoneme->GetIPA() ) ) DETHROW( deeInvalidParam );
pPhonemes.Add( phoneme );
}
void saePhonemeList::Remove( saePhoneme *phoneme ){
pPhonemes.Remove( phoneme );
}
void saePhonemeList::RemoveAll(){
pPhonemes.RemoveAll();
}
saePhonemeList &saePhonemeList::operator=( const saePhonemeList &list ){
pPhonemes = list.pPhonemes;
return *this;
}
| 412 | 0.828846 | 1 | 0.828846 | game-dev | MEDIA | 0.340676 | game-dev | 0.652243 | 1 | 0.652243 |
experiment-games/gmod-experiment-redux | 6,906 | plugins/customizable_weaponry/entities/weapons/exp_tacrp_ex_hk45c.lua | local PLUGIN = PLUGIN
SWEP.Base = "exp_tacrp_base"
SWEP.Spawnable = true
AddCSLuaFile()
-- names and stuff
SWEP.PrintName = "HK HK45 Compact"
SWEP.AbbrevName = "HK45C"
SWEP.Category = "Tactical RP"
SWEP.SubCatTier = "1Elite"
SWEP.SubCatType = "1Sidearm"
SWEP.Description = "Modern pistol with great firepower in a handy package."
SWEP.Trivia_Caliber = ".45 ACP"
SWEP.Trivia_Manufacturer = "Heckler & Koch"
SWEP.Trivia_Year = "2006"
SWEP.Faction = PLUGIN.FACTION_COALITION
SWEP.Credits = [[
Model: B0t, Red Crayon
Textures: IppE, Grall19
Sounds: DMG, xLongWayHome, Leeroy Newman
Animations: Tactical Intervention]]
SWEP.ViewModel = "models/weapons/tacint_extras/v_hk45c.mdl"
SWEP.WorldModel = "models/weapons/tacint_extras/w_hk45c.mdl"
SWEP.Slot = 1
SWEP.BalanceStats = {
[PLUGIN.BALANCE_SBOX] = {
Range_Max = 1200,
RPM = 360,
ClipSize = 8,
},
[PLUGIN.BALANCE_TTT] = {
-- TODO
},
}
-- "ballistics"
SWEP.Damage_Max = 36
SWEP.Damage_Min = 10
SWEP.Range_Min = 600 -- distance for which to maintain maximum damage
SWEP.Range_Max = 1500 -- distance at which we drop to minimum damage
SWEP.Penetration = 3 -- units of metal this weapon can penetrate
SWEP.ArmorPenetration = 0.7
SWEP.ArmorBonus = 0.25
SWEP.MuzzleVelocity = 9800
SWEP.BodyDamageMultipliers = {
[HITGROUP_HEAD] = 4,
[HITGROUP_CHEST] = 1,
[HITGROUP_STOMACH] = 1,
[HITGROUP_LEFTARM] = 1,
[HITGROUP_RIGHTARM] = 1,
[HITGROUP_LEFTLEG] = 0.75,
[HITGROUP_RIGHTLEG] = 0.75,
[HITGROUP_GEAR] = 0.9
}
-- misc. shooting
SWEP.Firemode = 1
SWEP.RPM = 450
SWEP.RPMMultSemi = 0.75
SWEP.Spread = 0.005
SWEP.ShootTimeMult = 0.5
SWEP.RecoilResetInstant = false
SWEP.RecoilPerShot = 1
SWEP.RecoilMaximum = 3.5
SWEP.RecoilResetTime = 0.02
SWEP.RecoilDissipationRate = 12
SWEP.RecoilFirstShotMult = 1
SWEP.RecoilVisualKick = 1.5
SWEP.RecoilKick = 6
SWEP.RecoilStability = 0.5
SWEP.RecoilSpreadPenalty = 0.007
SWEP.CanBlindFire = true
-- handling
SWEP.MoveSpeedMult = 0.975
SWEP.ShootingSpeedMult = 0.9
SWEP.SightedSpeedMult = 0.8
SWEP.ReloadSpeedMult = 0.75
SWEP.AimDownSightsTime = 0.25
SWEP.SprintToFireTime = 0.25
SWEP.Sway = 1
SWEP.ScopedSway = 0.5
SWEP.FreeAimMaxAngle = 3
-- hold types
SWEP.HoldType = "revolver"
SWEP.HoldTypeSprint = "normal"
SWEP.HoldTypeBlindFire = "pistol"
SWEP.GestureShoot = ACT_HL2MP_GESTURE_RANGE_ATTACK_PISTOL
SWEP.GestureReload = ACT_HL2MP_GESTURE_RELOAD_PISTOL
SWEP.PassiveAng = Angle(0, 0, 0)
SWEP.PassivePos = Vector(0, -2, -5)
SWEP.BlindFireAng = Angle(0, 5, 0)
SWEP.BlindFirePos = Vector(0, -2, -5)
SWEP.BlindFireSuicideAng = Angle(-130, 0, 45)
SWEP.BlindFireSuicidePos = Vector(25, 15, -6)
SWEP.SprintAng = Angle(0, 30, 0)
SWEP.SprintPos = Vector(2, 0, -12)
SWEP.SightAng = Angle(0, -0.1, 0)
SWEP.SightPos = Vector(-3.45, 0, -3.4)
SWEP.HolsterVisible = true
SWEP.HolsterSlot = PLUGIN.HOLSTER_SLOT_PISTOL
SWEP.HolsterPos = Vector(0, 3, -4)
SWEP.HolsterAng = Angle(90, 0, 0)
-- reload
SWEP.ClipSize = 10
SWEP.Ammo = "pistol"
SWEP.ReloadTimeMult = 1.15
SWEP.DropMagazineModel = "models/weapons/tacint_extras/magazines/hk45c.mdl"
SWEP.DropMagazineImpact = "pistol"
SWEP.ReloadUpInTime = 0.9
SWEP.DropMagazineTime = 0.2
-- sounds
local path = "TacRP/weapons/p250/p250_"
local path1 = "tacrp_extras/hk45c/"
SWEP.Sound_Shoot = "^" .. path1 .. "hk45-1.wav"
SWEP.Sound_Shoot_Silenced = path .. "fire_silenced-1.wav"
SWEP.Vol_Shoot = 110
SWEP.ShootPitchVariance = 2.5 -- amount to vary pitch by each shot
-- effects
-- the .qc attachment for the muzzle
SWEP.QCA_Muzzle = 4
SWEP.MuzzleEffect = "muzzleflash_pistol"
-- anims
SWEP.AnimationTranslationTable = {
["deploy"] = "draw",
["fire"] = { "shoot1", "shoot2", "shoot3" },
["blind_fire"] = { "blind_shoot1", "blind_shoot2", "blind_shoot3" },
["melee"] = { "melee1", "melee2" }
}
SWEP.ProceduralIronFire = {
vm_pos = Vector(0, -0.5, -0.6),
vm_ang = Angle(0, 2, 0),
t = 0.2,
tmax = 0.2,
bones = {
{
bone = "ValveBiped.slide",
pos = Vector(0, 0, -3),
t0 = 0,
t1 = 0.1,
},
{
bone = "ValveBiped.hammer",
ang = Angle(-15, 0, 0),
t0 = 0,
t1 = 0.15,
},
{
bone = "ValveBiped.Bip01_R_Finger1",
ang = Angle(0, -15, 0),
t0 = 0,
t1 = 0.2,
},
{
bone = "ValveBiped.Bip01_R_Finger11",
ang = Angle(-35, 0, 0),
t0 = 0,
t1 = 0.15,
},
},
}
SWEP.LastShot = true
-- attachments
SWEP.Attachments = {
[1] = {
PrintName = "Optic",
Category = "optic_pistol",
Bone = "ValveBiped.slide",
WMBone = "Box01",
AttachSound = "TacRP/weapons/optic_on.wav",
DetachSound = "TacRP/weapons/optic_off.wav",
VMScale = 1,
WMScale = 1,
Pos_VM = Vector(0.01, 0, -0.1),
Ang_VM = Angle(0, 90, 180),
Pos_WM = Vector(0.15, -1.5, -1),
Ang_WM = Angle(0, -90, 0),
},
[2] = {
PrintName = "Muzzle",
Category = "silencer",
Bone = "ValveBiped.barrel_assembly",
WMBone = "Box01",
AttachSound = "TacRP/weapons/silencer_on.wav",
DetachSound = "TacRP/weapons/silencer_off.wav",
VMScale = 0.5,
WMScale = 0.5,
Pos_VM = Vector(-0.65, 0.4, 6),
Ang_VM = Angle(90, 0, 0),
Pos_WM = Vector(0.1, 7.5, -1.5),
Ang_WM = Angle(0, -90, 0),
},
[3] = {
PrintName = "Tactical",
Category = "tactical",
Bone = "ValveBiped.p250_rootbone",
WMBone = "Box01",
AttachSound = "TacRP/weapons/flashlight_on.wav",
DetachSound = "TacRP/weapons/flashlight_off.wav",
VMScale = 1,
WMScale = 1.1,
Pos_VM = Vector(-2, 0, 5.5),
Ang_VM = Angle(90, 0, 180),
Pos_WM = Vector(0, 4.5, -2.75),
Ang_WM = Angle(0, -90, 180),
},
[4] = {
PrintName = "Accessory",
Category = { "acc", "acc_extmag_pistol", "acc_holster", "acc_brace" },
AttachSound = "TacRP/weapons/flashlight_on.wav",
DetachSound = "TacRP/weapons/flashlight_off.wav",
},
[5] = {
PrintName = "Bolt",
Category = { "bolt_automatic" },
AttachSound = "TacRP/weapons/flashlight_on.wav",
DetachSound = "TacRP/weapons/flashlight_off.wav",
},
[6] = {
PrintName = "Trigger",
Category = { "trigger_semi" },
AttachSound = "TacRP/weapons/flashlight_on.wav",
DetachSound = "TacRP/weapons/flashlight_off.wav",
},
[7] = {
PrintName = "Ammo",
Category = { "ammo_pistol" },
AttachSound = "TacRP/weapons/flashlight_on.wav",
DetachSound = "TacRP/weapons/flashlight_off.wav",
},
[8] = {
PrintName = "Perk",
Category = { "perk", "perk_melee", "perk_shooting", "perk_reload" },
AttachSound = "tacrp/weapons/flashlight_on.wav",
DetachSound = "tacrp/weapons/flashlight_off.wav",
},
}
local function addsound(name, spath)
sound.Add({
name = name,
channel = 16,
volume = 1.0,
sound = spath
})
end
addsound("tacint_hk45c.clip_in", path1 .. "magin.wav")
addsound("tacint_hk45c.clip_in-mid", path .. "clip_in-mid.wav")
addsound("tacint_hk45c.clip_out", path1 .. "magout.wav")
addsound("tacint_hk45c.slide_action", path1 .. "slidepull.wav")
addsound("tacint_hk45c.slide_shut", path1 .. "sliderelease.wav")
addsound("tacint_hk45c.cock_hammer", path .. "cockhammer.wav")
| 412 | 0.864327 | 1 | 0.864327 | game-dev | MEDIA | 0.951365 | game-dev | 0.816214 | 1 | 0.816214 |
space-wizards/space-station-14 | 4,794 | Content.Server/StationEvents/Events/StationEventSystem.cs | using Content.Server.Administration.Logs;
using Content.Server.Chat.Systems;
using Content.Server.GameTicking;
using Content.Server.GameTicking.Rules;
using Content.Server.Station.Systems;
using Content.Server.StationEvents.Components;
using Content.Shared.Database;
using Content.Shared.GameTicking.Components;
using Robust.Shared.Audio.Systems;
using Robust.Shared.Player;
using Robust.Shared.Prototypes;
namespace Content.Server.StationEvents.Events;
/// <summary>
/// An abstract entity system inherited by all station events for their behavior.
/// </summary>
public abstract class StationEventSystem<T> : GameRuleSystem<T> where T : IComponent
{
[Dependency] protected readonly IAdminLogManager AdminLogManager = default!;
[Dependency] protected readonly IPrototypeManager PrototypeManager = default!;
[Dependency] protected readonly ChatSystem ChatSystem = default!;
[Dependency] protected readonly SharedAudioSystem Audio = default!;
[Dependency] protected readonly StationSystem StationSystem = default!;
protected ISawmill Sawmill = default!;
public override void Initialize()
{
base.Initialize();
Sawmill = Logger.GetSawmill("stationevents");
}
/// <inheritdoc/>
protected override void Added(EntityUid uid, T component, GameRuleComponent gameRule, GameRuleAddedEvent args)
{
base.Added(uid, component, gameRule, args);
if (!TryComp<StationEventComponent>(uid, out var stationEvent))
return;
AdminLogManager.Add(LogType.EventAnnounced, $"Event added / announced: {ToPrettyString(uid)}");
// we don't want to send to players who aren't in game (i.e. in the lobby)
Filter allPlayersInGame = Filter.Empty().AddWhere(GameTicker.UserHasJoinedGame);
if (stationEvent.StartAnnouncement != null)
ChatSystem.DispatchFilteredAnnouncement(allPlayersInGame, Loc.GetString(stationEvent.StartAnnouncement), playSound: false, colorOverride: stationEvent.StartAnnouncementColor);
Audio.PlayGlobal(stationEvent.StartAudio, allPlayersInGame, true);
}
/// <inheritdoc/>
protected override void Started(EntityUid uid, T component, GameRuleComponent gameRule, GameRuleStartedEvent args)
{
base.Started(uid, component, gameRule, args);
if (!TryComp<StationEventComponent>(uid, out var stationEvent))
return;
AdminLogManager.Add(LogType.EventStarted, LogImpact.High, $"Event started: {ToPrettyString(uid)}");
if (stationEvent.Duration != null)
{
var duration = stationEvent.MaxDuration == null
? stationEvent.Duration
: TimeSpan.FromSeconds(RobustRandom.NextDouble(stationEvent.Duration.Value.TotalSeconds,
stationEvent.MaxDuration.Value.TotalSeconds));
stationEvent.EndTime = Timing.CurTime + duration;
}
}
/// <inheritdoc/>
protected override void Ended(EntityUid uid, T component, GameRuleComponent gameRule, GameRuleEndedEvent args)
{
base.Ended(uid, component, gameRule, args);
if (!TryComp<StationEventComponent>(uid, out var stationEvent))
return;
AdminLogManager.Add(LogType.EventStopped, $"Event ended: {ToPrettyString(uid)}");
// we don't want to send to players who aren't in game (i.e. in the lobby)
Filter allPlayersInGame = Filter.Empty().AddWhere(GameTicker.UserHasJoinedGame);
if (stationEvent.EndAnnouncement != null)
ChatSystem.DispatchFilteredAnnouncement(allPlayersInGame, Loc.GetString(stationEvent.EndAnnouncement), playSound: false, colorOverride: stationEvent.EndAnnouncementColor);
Audio.PlayGlobal(stationEvent.EndAudio, allPlayersInGame, true);
}
/// <summary>
/// Called every tick when this event is running.
/// Events are responsible for their own lifetime, so this handles starting and ending after time.
/// </summary>
/// <inheritdoc/>
public override void Update(float frameTime)
{
base.Update(frameTime);
var query = EntityQueryEnumerator<StationEventComponent, GameRuleComponent>();
while (query.MoveNext(out var uid, out var stationEvent, out var ruleData))
{
if (!GameTicker.IsGameRuleAdded(uid, ruleData))
continue;
if (!GameTicker.IsGameRuleActive(uid, ruleData) && !HasComp<DelayedStartRuleComponent>(uid))
{
GameTicker.StartGameRule(uid, ruleData);
}
else if (stationEvent.EndTime != null && Timing.CurTime >= stationEvent.EndTime && GameTicker.IsGameRuleActive(uid, ruleData))
{
GameTicker.EndGameRule(uid, ruleData);
}
}
}
}
| 412 | 0.930461 | 1 | 0.930461 | game-dev | MEDIA | 0.854256 | game-dev | 0.88725 | 1 | 0.88725 |
dhewm/dhewm3 | 36,131 | neo/d3xp/BrittleFracture.cpp | /*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
Doom 3 Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "sys/platform.h"
#include "framework/DeclEntityDef.h"
#include "renderer/ModelManager.h"
#include "Fx.h"
#include "BrittleFracture.h"
CLASS_DECLARATION( idEntity, idBrittleFracture )
EVENT( EV_Activate, idBrittleFracture::Event_Activate )
EVENT( EV_Touch, idBrittleFracture::Event_Touch )
END_CLASS
const int SHARD_ALIVE_TIME = 5000;
const int SHARD_FADE_START = 2000;
static const char *brittleFracture_SnapshotName = "_BrittleFracture_Snapshot_";
/*
================
idBrittleFracture::idBrittleFracture
================
*/
idBrittleFracture::idBrittleFracture( void ) {
material = NULL;
decalMaterial = NULL;
decalSize = 0.0f;
maxShardArea = 0.0f;
maxShatterRadius = 0.0f;
minShatterRadius = 0.0f;
linearVelocityScale = 0.0f;
angularVelocityScale = 0.0f;
shardMass = 0.0f;
density = 0.0f;
friction = 0.0f;
bouncyness = 0.0f;
fxFracture.Clear();
bounds.Clear();
disableFracture = false;
lastRenderEntityUpdate = -1;
changed = false;
fl.networkSync = true;
#ifdef _D3XP
isXraySurface = false;
#endif
}
/*
================
idBrittleFracture::~idBrittleFracture
================
*/
idBrittleFracture::~idBrittleFracture( void ) {
int i;
for ( i = 0; i < shards.Num(); i++ ) {
shards[i]->decals.DeleteContents( true );
delete shards[i];
}
// make sure the render entity is freed before the model is freed
FreeModelDef();
renderModelManager->FreeModel( renderEntity.hModel );
}
/*
================
idBrittleFracture::Save
================
*/
void idBrittleFracture::Save( idSaveGame *savefile ) const {
int i, j;
savefile->WriteInt( health );
entityFlags_s flags = fl;
LittleBitField( &flags, sizeof( flags ) );
savefile->Write( &flags, sizeof( flags ) );
// setttings
savefile->WriteMaterial( material );
savefile->WriteMaterial( decalMaterial );
savefile->WriteFloat( decalSize );
savefile->WriteFloat( maxShardArea );
savefile->WriteFloat( maxShatterRadius );
savefile->WriteFloat( minShatterRadius );
savefile->WriteFloat( linearVelocityScale );
savefile->WriteFloat( angularVelocityScale );
savefile->WriteFloat( shardMass );
savefile->WriteFloat( density );
savefile->WriteFloat( friction );
savefile->WriteFloat( bouncyness );
savefile->WriteString( fxFracture );
// state
savefile->WriteBounds( bounds );
savefile->WriteBool( disableFracture );
savefile->WriteInt( lastRenderEntityUpdate );
savefile->WriteBool( changed );
savefile->WriteStaticObject( physicsObj );
savefile->WriteInt( shards.Num() );
for ( i = 0; i < shards.Num(); i++ ) {
savefile->WriteWinding( shards[i]->winding );
savefile->WriteInt( shards[i]->decals.Num() );
for ( j = 0; j < shards[i]->decals.Num(); j++ ) {
savefile->WriteWinding( *shards[i]->decals[j] );
}
savefile->WriteInt( shards[i]->neighbours.Num() );
for ( j = 0; j < shards[i]->neighbours.Num(); j++ ) {
int index = shards.FindIndex(shards[i]->neighbours[j]);
assert(index != -1);
savefile->WriteInt( index );
}
savefile->WriteInt( shards[i]->edgeHasNeighbour.Num() );
for ( j = 0; j < shards[i]->edgeHasNeighbour.Num(); j++ ) {
savefile->WriteBool( shards[i]->edgeHasNeighbour[j] );
}
savefile->WriteInt( shards[i]->droppedTime );
savefile->WriteInt( shards[i]->islandNum );
savefile->WriteBool( shards[i]->atEdge );
savefile->WriteStaticObject( shards[i]->physicsObj );
}
#ifdef _D3XP
savefile->WriteBool( isXraySurface );
#endif
}
/*
================
idBrittleFracture::Restore
================
*/
void idBrittleFracture::Restore( idRestoreGame *savefile ) {
int i, j , num;
renderEntity.hModel = renderModelManager->AllocModel();
renderEntity.hModel->InitEmpty( brittleFracture_SnapshotName );
renderEntity.callback = idBrittleFracture::ModelCallback;
renderEntity.noShadow = true;
renderEntity.noSelfShadow = true;
renderEntity.noDynamicInteractions = false;
savefile->ReadInt( health );
savefile->Read( &fl, sizeof( fl ) );
LittleBitField( &fl, sizeof( fl ) );
// setttings
savefile->ReadMaterial( material );
savefile->ReadMaterial( decalMaterial );
savefile->ReadFloat( decalSize );
savefile->ReadFloat( maxShardArea );
savefile->ReadFloat( maxShatterRadius );
savefile->ReadFloat( minShatterRadius );
savefile->ReadFloat( linearVelocityScale );
savefile->ReadFloat( angularVelocityScale );
savefile->ReadFloat( shardMass );
savefile->ReadFloat( density );
savefile->ReadFloat( friction );
savefile->ReadFloat( bouncyness );
savefile->ReadString( fxFracture );
// state
savefile->ReadBounds(bounds);
savefile->ReadBool( disableFracture );
savefile->ReadInt( lastRenderEntityUpdate );
savefile->ReadBool( changed );
savefile->ReadStaticObject( physicsObj );
RestorePhysics( &physicsObj );
savefile->ReadInt( num );
shards.SetNum( num );
for ( i = 0; i < num; i++ ) {
shards[i] = new shard_t;
}
for ( i = 0; i < num; i++ ) {
savefile->ReadWinding( shards[i]->winding );
savefile->ReadInt( j );
shards[i]->decals.SetNum( j );
for ( j = 0; j < shards[i]->decals.Num(); j++ ) {
shards[i]->decals[j] = new idFixedWinding;
savefile->ReadWinding( *shards[i]->decals[j] );
}
savefile->ReadInt( j );
shards[i]->neighbours.SetNum( j );
for ( j = 0; j < shards[i]->neighbours.Num(); j++ ) {
int index;
savefile->ReadInt( index );
assert(index != -1);
shards[i]->neighbours[j] = shards[index];
}
savefile->ReadInt( j );
shards[i]->edgeHasNeighbour.SetNum( j );
for ( j = 0; j < shards[i]->edgeHasNeighbour.Num(); j++ ) {
savefile->ReadBool( shards[i]->edgeHasNeighbour[j] );
}
savefile->ReadInt( shards[i]->droppedTime );
savefile->ReadInt( shards[i]->islandNum );
savefile->ReadBool( shards[i]->atEdge );
savefile->ReadStaticObject( shards[i]->physicsObj );
if ( shards[i]->droppedTime < 0 ) {
shards[i]->clipModel = physicsObj.GetClipModel( i );
} else {
shards[i]->clipModel = shards[i]->physicsObj.GetClipModel();
}
}
#ifdef _D3XP
savefile->ReadBool( isXraySurface );
#endif
}
/*
================
idBrittleFracture::Spawn
================
*/
void idBrittleFracture::Spawn( void ) {
// get shard properties
decalMaterial = declManager->FindMaterial( spawnArgs.GetString( "mtr_decal" ) );
decalSize = spawnArgs.GetFloat( "decalSize", "40" );
maxShardArea = spawnArgs.GetFloat( "maxShardArea", "200" );
maxShardArea = idMath::ClampFloat( 100, 10000, maxShardArea );
maxShatterRadius = spawnArgs.GetFloat( "maxShatterRadius", "40" );
minShatterRadius = spawnArgs.GetFloat( "minShatterRadius", "10" );
linearVelocityScale = spawnArgs.GetFloat( "linearVelocityScale", "0.1" );
angularVelocityScale = spawnArgs.GetFloat( "angularVelocityScale", "40" );
fxFracture = spawnArgs.GetString( "fx" );
// get rigid body properties
shardMass = spawnArgs.GetFloat( "shardMass", "20" );
shardMass = idMath::ClampFloat( 0.001f, 1000.0f, shardMass );
spawnArgs.GetFloat( "density", "0.1", density );
density = idMath::ClampFloat( 0.001f, 1000.0f, density );
spawnArgs.GetFloat( "friction", "0.4", friction );
friction = idMath::ClampFloat( 0.0f, 1.0f, friction );
spawnArgs.GetFloat( "bouncyness", "0.01", bouncyness );
bouncyness = idMath::ClampFloat( 0.0f, 1.0f, bouncyness );
disableFracture = spawnArgs.GetBool( "disableFracture", "0" );
health = spawnArgs.GetInt( "health", "40" );
fl.takedamage = true;
// FIXME: set "bleed" so idProjectile calls AddDamageEffect
spawnArgs.SetBool( "bleed", 1 );
#ifdef _D3XP
// check for xray surface
if ( 1 ) {
const idRenderModel *model = renderEntity.hModel;
isXraySurface = false;
for ( int i = 0; i < model->NumSurfaces(); i++ ) {
const modelSurface_t *surf = model->Surface( i );
if ( idStr( surf->shader->GetName() ) == "textures/smf/window_scratch" ) {
isXraySurface = true;
break;
}
}
}
#endif
CreateFractures( renderEntity.hModel );
FindNeighbours();
renderEntity.hModel = renderModelManager->AllocModel();
renderEntity.hModel->InitEmpty( brittleFracture_SnapshotName );
renderEntity.callback = idBrittleFracture::ModelCallback;
renderEntity.noShadow = true;
renderEntity.noSelfShadow = true;
renderEntity.noDynamicInteractions = false;
}
/*
================
idBrittleFracture::AddShard
================
*/
void idBrittleFracture::AddShard( idClipModel *clipModel, idFixedWinding &w ) {
shard_t *shard = new shard_t;
shard->clipModel = clipModel;
shard->droppedTime = -1;
shard->winding = w;
shard->decals.Clear();
shard->edgeHasNeighbour.AssureSize( w.GetNumPoints(), false );
shard->neighbours.Clear();
shard->atEdge = false;
shards.Append( shard );
}
/*
================
idBrittleFracture::RemoveShard
================
*/
void idBrittleFracture::RemoveShard( int index ) {
int i;
delete shards[index];
shards.RemoveIndex( index );
physicsObj.RemoveIndex( index );
for ( i = index; i < shards.Num(); i++ ) {
shards[i]->clipModel->SetId( i );
}
}
/*
================
idBrittleFracture::UpdateRenderEntity
================
*/
bool idBrittleFracture::UpdateRenderEntity( renderEntity_s *renderEntity, const renderView_t *renderView ) const {
int i, j, k, n, msec, numTris, numDecalTris;
float fade;
dword packedColor;
srfTriangles_t *tris, *decalTris;
modelSurface_t surface;
idDrawVert *v;
idPlane plane;
idMat3 tangents;
// this may be triggered by a model trace or other non-view related source,
// to which we should look like an empty model
if ( !renderView ) {
return false;
}
// don't regenerate it if it is current
if ( lastRenderEntityUpdate == gameLocal.time || !changed ) {
return false;
}
lastRenderEntityUpdate = gameLocal.time;
changed = false;
numTris = 0;
numDecalTris = 0;
for ( i = 0; i < shards.Num(); i++ ) {
n = shards[i]->winding.GetNumPoints();
if ( n > 2 ) {
numTris += n - 2;
}
for ( k = 0; k < shards[i]->decals.Num(); k++ ) {
n = shards[i]->decals[k]->GetNumPoints();
if ( n > 2 ) {
numDecalTris += n - 2;
}
}
}
// FIXME: re-use model surfaces
renderEntity->hModel->InitEmpty( brittleFracture_SnapshotName );
// allocate triangle surfaces for the fractures and decals
tris = renderEntity->hModel->AllocSurfaceTriangles( numTris * 3, material->ShouldCreateBackSides() ? numTris * 6 : numTris * 3 );
decalTris = renderEntity->hModel->AllocSurfaceTriangles( numDecalTris * 3, decalMaterial->ShouldCreateBackSides() ? numDecalTris * 6 : numDecalTris * 3 );
for ( i = 0; i < shards.Num(); i++ ) {
const idVec3 &origin = shards[i]->clipModel->GetOrigin();
const idMat3 &axis = shards[i]->clipModel->GetAxis();
fade = 1.0f;
if ( shards[i]->droppedTime >= 0 ) {
msec = gameLocal.time - shards[i]->droppedTime - SHARD_FADE_START;
if ( msec > 0 ) {
fade = 1.0f - (float) msec / ( SHARD_ALIVE_TIME - SHARD_FADE_START );
}
}
packedColor = PackColor( idVec4( renderEntity->shaderParms[ SHADERPARM_RED ] * fade,
renderEntity->shaderParms[ SHADERPARM_GREEN ] * fade,
renderEntity->shaderParms[ SHADERPARM_BLUE ] * fade,
fade ) );
const idWinding &winding = shards[i]->winding;
winding.GetPlane( plane );
tangents = ( plane.Normal() * axis ).ToMat3();
for ( j = 2; j < winding.GetNumPoints(); j++ ) {
v = &tris->verts[tris->numVerts++];
v->Clear();
v->xyz = origin + winding[0].ToVec3() * axis;
v->st[0] = winding[0].s;
v->st[1] = winding[0].t;
v->normal = tangents[0];
v->tangents[0] = tangents[1];
v->tangents[1] = tangents[2];
v->SetColor( packedColor );
v = &tris->verts[tris->numVerts++];
v->Clear();
v->xyz = origin + winding[j-1].ToVec3() * axis;
v->st[0] = winding[j-1].s;
v->st[1] = winding[j-1].t;
v->normal = tangents[0];
v->tangents[0] = tangents[1];
v->tangents[1] = tangents[2];
v->SetColor( packedColor );
v = &tris->verts[tris->numVerts++];
v->Clear();
v->xyz = origin + winding[j].ToVec3() * axis;
v->st[0] = winding[j].s;
v->st[1] = winding[j].t;
v->normal = tangents[0];
v->tangents[0] = tangents[1];
v->tangents[1] = tangents[2];
v->SetColor( packedColor );
tris->indexes[tris->numIndexes++] = tris->numVerts - 3;
tris->indexes[tris->numIndexes++] = tris->numVerts - 2;
tris->indexes[tris->numIndexes++] = tris->numVerts - 1;
if ( material->ShouldCreateBackSides() ) {
tris->indexes[tris->numIndexes++] = tris->numVerts - 2;
tris->indexes[tris->numIndexes++] = tris->numVerts - 3;
tris->indexes[tris->numIndexes++] = tris->numVerts - 1;
}
}
for ( k = 0; k < shards[i]->decals.Num(); k++ ) {
const idWinding &decalWinding = *shards[i]->decals[k];
for ( j = 2; j < decalWinding.GetNumPoints(); j++ ) {
v = &decalTris->verts[decalTris->numVerts++];
v->Clear();
v->xyz = origin + decalWinding[0].ToVec3() * axis;
v->st[0] = decalWinding[0].s;
v->st[1] = decalWinding[0].t;
v->normal = tangents[0];
v->tangents[0] = tangents[1];
v->tangents[1] = tangents[2];
v->SetColor( packedColor );
v = &decalTris->verts[decalTris->numVerts++];
v->Clear();
v->xyz = origin + decalWinding[j-1].ToVec3() * axis;
v->st[0] = decalWinding[j-1].s;
v->st[1] = decalWinding[j-1].t;
v->normal = tangents[0];
v->tangents[0] = tangents[1];
v->tangents[1] = tangents[2];
v->SetColor( packedColor );
v = &decalTris->verts[decalTris->numVerts++];
v->Clear();
v->xyz = origin + decalWinding[j].ToVec3() * axis;
v->st[0] = decalWinding[j].s;
v->st[1] = decalWinding[j].t;
v->normal = tangents[0];
v->tangents[0] = tangents[1];
v->tangents[1] = tangents[2];
v->SetColor( packedColor );
decalTris->indexes[decalTris->numIndexes++] = decalTris->numVerts - 3;
decalTris->indexes[decalTris->numIndexes++] = decalTris->numVerts - 2;
decalTris->indexes[decalTris->numIndexes++] = decalTris->numVerts - 1;
if ( decalMaterial->ShouldCreateBackSides() ) {
decalTris->indexes[decalTris->numIndexes++] = decalTris->numVerts - 2;
decalTris->indexes[decalTris->numIndexes++] = decalTris->numVerts - 3;
decalTris->indexes[decalTris->numIndexes++] = decalTris->numVerts - 1;
}
}
}
}
tris->tangentsCalculated = true;
decalTris->tangentsCalculated = true;
SIMDProcessor->MinMax( tris->bounds[0], tris->bounds[1], tris->verts, tris->numVerts );
SIMDProcessor->MinMax( decalTris->bounds[0], decalTris->bounds[1], decalTris->verts, decalTris->numVerts );
memset( &surface, 0, sizeof( surface ) );
surface.shader = material;
surface.id = 0;
surface.geometry = tris;
renderEntity->hModel->AddSurface( surface );
memset( &surface, 0, sizeof( surface ) );
surface.shader = decalMaterial;
surface.id = 1;
surface.geometry = decalTris;
renderEntity->hModel->AddSurface( surface );
return true;
}
/*
================
idBrittleFracture::ModelCallback
================
*/
bool idBrittleFracture::ModelCallback( renderEntity_s *renderEntity, const renderView_t *renderView ) {
const idBrittleFracture *ent;
ent = static_cast<idBrittleFracture *>(gameLocal.entities[ renderEntity->entityNum ]);
if ( !ent ) {
gameLocal.Error( "idBrittleFracture::ModelCallback: callback with NULL game entity" );
}
return ent->UpdateRenderEntity( renderEntity, renderView );
}
/*
================
idBrittleFracture::Present
================
*/
void idBrittleFracture::Present() {
// don't present to the renderer if the entity hasn't changed
if ( !( thinkFlags & TH_UPDATEVISUALS ) ) {
return;
}
BecomeInactive( TH_UPDATEVISUALS );
renderEntity.bounds = bounds;
renderEntity.origin.Zero();
renderEntity.axis.Identity();
// force an update because the bounds/origin/axis may stay the same while the model changes
renderEntity.forceUpdate = true;
// add to refresh list
if ( modelDefHandle == -1 ) {
modelDefHandle = gameRenderWorld->AddEntityDef( &renderEntity );
} else {
gameRenderWorld->UpdateEntityDef( modelDefHandle, &renderEntity );
}
changed = true;
}
/*
================
idBrittleFracture::Think
================
*/
void idBrittleFracture::Think( void ) {
int i, startTime, endTime, droppedTime;
shard_t *shard;
bool atRest = true, fading = false;
// remove overdue shards
for ( i = 0; i < shards.Num(); i++ ) {
droppedTime = shards[i]->droppedTime;
if ( droppedTime != -1 ) {
if ( gameLocal.time - droppedTime > SHARD_ALIVE_TIME ) {
RemoveShard( i );
i--;
}
fading = true;
}
}
// remove the entity when nothing is visible
if ( !shards.Num() ) {
PostEventMS( &EV_Remove, 0 );
return;
}
if ( thinkFlags & TH_PHYSICS ) {
startTime = gameLocal.previousTime;
endTime = gameLocal.time;
// run physics on shards
for ( i = 0; i < shards.Num(); i++ ) {
shard = shards[i];
if ( shard->droppedTime == -1 ) {
continue;
}
shard->physicsObj.Evaluate( endTime - startTime, endTime );
if ( !shard->physicsObj.IsAtRest() ) {
atRest = false;
}
}
if ( atRest ) {
BecomeInactive( TH_PHYSICS );
} else {
BecomeActive( TH_PHYSICS );
}
}
if ( !atRest || bounds.IsCleared() ) {
bounds.Clear();
for ( i = 0; i < shards.Num(); i++ ) {
bounds.AddBounds( shards[i]->clipModel->GetAbsBounds() );
}
}
if ( fading ) {
BecomeActive( TH_UPDATEVISUALS | TH_THINK );
} else {
BecomeInactive( TH_THINK );
}
RunPhysics();
Present();
}
/*
================
idBrittleFracture::ApplyImpulse
================
*/
void idBrittleFracture::ApplyImpulse( idEntity *ent, int id, const idVec3 &point, const idVec3 &impulse ) {
if ( id < 0 || id >= shards.Num() ) {
return;
}
if ( shards[id]->droppedTime != -1 ) {
shards[id]->physicsObj.ApplyImpulse( 0, point, impulse );
} else if ( health <= 0 && !disableFracture ) {
Shatter( point, impulse, gameLocal.time );
}
}
/*
================
idBrittleFracture::AddForce
================
*/
void idBrittleFracture::AddForce( idEntity *ent, int id, const idVec3 &point, const idVec3 &force ) {
if ( id < 0 || id >= shards.Num() ) {
return;
}
if ( shards[id]->droppedTime != -1 ) {
shards[id]->physicsObj.AddForce( 0, point, force );
} else if ( health <= 0 && !disableFracture ) {
Shatter( point, force, gameLocal.time );
}
}
/*
================
idBrittleFracture::ProjectDecal
================
*/
void idBrittleFracture::ProjectDecal( const idVec3 &point, const idVec3 &dir, const int time, const char *damageDefName ) {
int i, j, bits, clipBits;
float a, c, s;
idVec2 st[MAX_POINTS_ON_WINDING];
idVec3 origin;
idMat3 axis, axistemp;
idPlane textureAxis[2];
if ( gameLocal.isServer ) {
idBitMsg msg;
byte msgBuf[MAX_EVENT_PARAM_SIZE];
msg.Init( msgBuf, sizeof( msgBuf ) );
msg.BeginWriting();
msg.WriteFloat( point[0] );
msg.WriteFloat( point[1] );
msg.WriteFloat( point[2] );
msg.WriteFloat( dir[0] );
msg.WriteFloat( dir[1] );
msg.WriteFloat( dir[2] );
ServerSendEvent( EVENT_PROJECT_DECAL, &msg, true, -1 );
}
if ( time >= gameLocal.time ) {
// try to get the sound from the damage def
const idDeclEntityDef *damageDef = NULL;
const idSoundShader *sndShader = NULL;
if ( damageDefName ) {
damageDef = gameLocal.FindEntityDef( damageDefName, false );
if ( damageDef ) {
sndShader = declManager->FindSound( damageDef->dict.GetString( "snd_shatter", "" ) );
}
}
if ( sndShader ) {
StartSoundShader( sndShader, SND_CHANNEL_ANY, 0, false, NULL );
} else {
StartSound( "snd_bullethole", SND_CHANNEL_ANY, 0, false, NULL );
}
}
a = gameLocal.random.RandomFloat() * idMath::TWO_PI;
c = cos( a );
s = -sin( a );
axis[2] = -dir;
axis[2].Normalize();
axis[2].NormalVectors( axistemp[0], axistemp[1] );
axis[0] = axistemp[ 0 ] * c + axistemp[ 1 ] * s;
axis[1] = axistemp[ 0 ] * s + axistemp[ 1 ] * -c;
textureAxis[0] = axis[0] * ( 1.0f / decalSize );
textureAxis[0][3] = -( point * textureAxis[0].Normal() ) + 0.5f;
textureAxis[1] = axis[1] * ( 1.0f / decalSize );
textureAxis[1][3] = -( point * textureAxis[1].Normal() ) + 0.5f;
for ( i = 0; i < shards.Num(); i++ ) {
idFixedWinding &winding = shards[i]->winding;
origin = shards[i]->clipModel->GetOrigin();
axis = shards[i]->clipModel->GetAxis();
float d0, d1;
clipBits = -1;
for ( j = 0; j < winding.GetNumPoints(); j++ ) {
idVec3 p = origin + winding[j].ToVec3() * axis;
st[j].x = d0 = textureAxis[0].Distance( p );
st[j].y = d1 = textureAxis[1].Distance( p );
bits = FLOATSIGNBITSET( d0 );
d0 = 1.0f - d0;
bits |= FLOATSIGNBITSET( d1 ) << 2;
d1 = 1.0f - d1;
bits |= FLOATSIGNBITSET( d0 ) << 1;
bits |= FLOATSIGNBITSET( d1 ) << 3;
clipBits &= bits;
}
if ( clipBits ) {
continue;
}
idFixedWinding *decal = new idFixedWinding;
shards[i]->decals.Append( decal );
decal->SetNumPoints( winding.GetNumPoints() );
for ( j = 0; j < winding.GetNumPoints(); j++ ) {
(*decal)[j].ToVec3() = winding[j].ToVec3();
(*decal)[j].s = st[j].x;
(*decal)[j].t = st[j].y;
}
}
BecomeActive( TH_UPDATEVISUALS );
}
/*
================
idBrittleFracture::DropShard
================
*/
void idBrittleFracture::DropShard( shard_t *shard, const idVec3 &point, const idVec3 &dir, const float impulse, const int time ) {
int i, j, clipModelId;
float dist, f;
idVec3 dir2, origin;
idMat3 axis;
shard_t *neighbour;
// don't display decals on dropped shards
shard->decals.DeleteContents( true );
// remove neighbour pointers of neighbours pointing to this shard
for ( i = 0; i < shard->neighbours.Num(); i++ ) {
neighbour = shard->neighbours[i];
for ( j = 0; j < neighbour->neighbours.Num(); j++ ) {
if ( neighbour->neighbours[j] == shard ) {
neighbour->neighbours.RemoveIndex( j );
break;
}
}
}
// remove neighbour pointers
shard->neighbours.Clear();
// remove the clip model from the static physics object
clipModelId = shard->clipModel->GetId();
physicsObj.SetClipModel( NULL, 1.0f, clipModelId, false );
origin = shard->clipModel->GetOrigin();
axis = shard->clipModel->GetAxis();
// set the dropped time for fading
shard->droppedTime = time;
dir2 = origin - point;
dist = dir2.Normalize();
f = dist > maxShatterRadius ? 1.0f : idMath::Sqrt( dist - minShatterRadius ) * ( 1.0f / idMath::Sqrt( maxShatterRadius - minShatterRadius ) );
// setup the physics
shard->physicsObj.SetSelf( this );
shard->physicsObj.SetClipModel( shard->clipModel, density );
shard->physicsObj.SetMass( shardMass );
shard->physicsObj.SetOrigin( origin );
shard->physicsObj.SetAxis( axis );
shard->physicsObj.SetBouncyness( bouncyness );
shard->physicsObj.SetFriction( 0.6f, 0.6f, friction );
shard->physicsObj.SetGravity( gameLocal.GetGravity() );
shard->physicsObj.SetContents( CONTENTS_RENDERMODEL );
shard->physicsObj.SetClipMask( MASK_SOLID | CONTENTS_MOVEABLECLIP );
shard->physicsObj.ApplyImpulse( 0, origin, impulse * linearVelocityScale * dir );
shard->physicsObj.SetAngularVelocity( dir.Cross( dir2 ) * ( f * angularVelocityScale ) );
shard->clipModel->SetId( clipModelId );
BecomeActive( TH_PHYSICS );
}
/*
================
idBrittleFracture::Shatter
================
*/
void idBrittleFracture::Shatter( const idVec3 &point, const idVec3 &impulse, const int time ) {
int i;
idVec3 dir;
shard_t *shard;
float m;
if ( gameLocal.isServer ) {
idBitMsg msg;
byte msgBuf[MAX_EVENT_PARAM_SIZE];
msg.Init( msgBuf, sizeof( msgBuf ) );
msg.BeginWriting();
msg.WriteFloat( point[0] );
msg.WriteFloat( point[1] );
msg.WriteFloat( point[2] );
msg.WriteFloat( impulse[0] );
msg.WriteFloat( impulse[1] );
msg.WriteFloat( impulse[2] );
ServerSendEvent( EVENT_SHATTER, &msg, true, -1 );
}
if ( time > ( gameLocal.time - SHARD_ALIVE_TIME ) ) {
StartSound( "snd_shatter", SND_CHANNEL_ANY, 0, false, NULL );
}
if ( !IsBroken() ) {
Break();
}
if ( fxFracture.Length() ) {
idEntityFx::StartFx( fxFracture, &point, &GetPhysics()->GetAxis(), this, true );
}
dir = impulse;
m = dir.Normalize();
for ( i = 0; i < shards.Num(); i++ ) {
shard = shards[i];
if ( shard->droppedTime != -1 ) {
continue;
}
if ( ( shard->clipModel->GetOrigin() - point ).LengthSqr() > Square( maxShatterRadius ) ) {
continue;
}
DropShard( shard, point, dir, m, time );
}
DropFloatingIslands( point, impulse, time );
}
/*
================
idBrittleFracture::DropFloatingIslands
================
*/
void idBrittleFracture::DropFloatingIslands( const idVec3 &point, const idVec3 &impulse, const int time ) {
int i, j, numIslands;
int queueStart, queueEnd;
shard_t *curShard, *nextShard, **queue;
bool touchesEdge;
idVec3 dir;
dir = impulse;
dir.Normalize();
numIslands = 0;
queue = (shard_t **) _alloca16( shards.Num() * sizeof(shard_t **) );
for ( i = 0; i < shards.Num(); i++ ) {
shards[i]->islandNum = 0;
}
for ( i = 0; i < shards.Num(); i++ ) {
if ( shards[i]->droppedTime != -1 ) {
continue;
}
if ( shards[i]->islandNum ) {
continue;
}
queueStart = 0;
queueEnd = 1;
queue[0] = shards[i];
shards[i]->islandNum = numIslands+1;
touchesEdge = false;
if ( shards[i]->atEdge ) {
touchesEdge = true;
}
for ( curShard = queue[queueStart]; queueStart < queueEnd; curShard = queue[++queueStart] ) {
for ( j = 0; j < curShard->neighbours.Num(); j++ ) {
nextShard = curShard->neighbours[j];
if ( nextShard->droppedTime != -1 ) {
continue;
}
if ( nextShard->islandNum ) {
continue;
}
queue[queueEnd++] = nextShard;
nextShard->islandNum = numIslands+1;
if ( nextShard->atEdge ) {
touchesEdge = true;
}
}
}
numIslands++;
// if the island is not connected to the world at any edges
if ( !touchesEdge ) {
for ( j = 0; j < queueEnd; j++ ) {
DropShard( queue[j], point, dir, 0.0f, time );
}
}
}
}
/*
================
idBrittleFracture::Break
================
*/
void idBrittleFracture::Break( void ) {
fl.takedamage = false;
physicsObj.SetContents( CONTENTS_RENDERMODEL | CONTENTS_TRIGGER );
}
/*
================
idBrittleFracture::IsBroken
================
*/
bool idBrittleFracture::IsBroken( void ) const {
return ( fl.takedamage == false );
}
/*
================
idBrittleFracture::Killed
================
*/
void idBrittleFracture::Killed( idEntity *inflictor, idEntity *attacker, int damage, const idVec3 &dir, int location ) {
if ( !disableFracture ) {
ActivateTargets( this );
Break();
}
}
/*
================
idBrittleFracture::AddDamageEffect
================
*/
void idBrittleFracture::AddDamageEffect( const trace_t &collision, const idVec3 &velocity, const char *damageDefName ) {
if ( !disableFracture ) {
ProjectDecal( collision.c.point, collision.c.normal, gameLocal.time, damageDefName );
}
}
/*
================
idBrittleFracture::Fracture_r
================
*/
void idBrittleFracture::Fracture_r( idFixedWinding &w ) {
int i, j, bestPlane;
float a, c, s, dist, bestDist;
idVec3 origin;
idPlane windingPlane, splitPlanes[2];
idMat3 axis, axistemp;
idFixedWinding back;
idTraceModel trm;
idClipModel *clipModel;
while( 1 ) {
origin = w.GetCenter();
w.GetPlane( windingPlane );
if ( w.GetArea() < maxShardArea ) {
break;
}
// randomly create a split plane
axis[2] = windingPlane.Normal();
#ifdef _D3XP
if ( isXraySurface ) {
a = idMath::TWO_PI / 2.f;
}
else {
a = gameLocal.random.RandomFloat() * idMath::TWO_PI;
}
#else
a = gameLocal.random.RandomFloat() * idMath::TWO_PI;
#endif
c = cos( a );
s = -sin( a );
axis[2].NormalVectors( axistemp[0], axistemp[1] );
axis[0] = axistemp[ 0 ] * c + axistemp[ 1 ] * s;
axis[1] = axistemp[ 0 ] * s + axistemp[ 1 ] * -c;
// get the best split plane
bestDist = 0.0f;
bestPlane = 0;
for ( i = 0; i < 2; i++ ) {
splitPlanes[i].SetNormal( axis[i] );
splitPlanes[i].FitThroughPoint( origin );
for ( j = 0; j < w.GetNumPoints(); j++ ) {
dist = splitPlanes[i].Distance( w[j].ToVec3() );
if ( dist > bestDist ) {
bestDist = dist;
bestPlane = i;
}
}
}
// split the winding
if ( !w.Split( &back, splitPlanes[bestPlane] ) ) {
break;
}
// recursively create shards for the back winding
Fracture_r( back );
}
// translate the winding to it's center
origin = w.GetCenter();
for ( j = 0; j < w.GetNumPoints(); j++ ) {
w[j].ToVec3() -= origin;
}
w.RemoveEqualPoints();
trm.SetupPolygon( w );
trm.Shrink( CM_CLIP_EPSILON );
clipModel = new idClipModel( trm );
physicsObj.SetClipModel( clipModel, 1.0f, shards.Num() );
physicsObj.SetOrigin( GetPhysics()->GetOrigin() + origin, shards.Num() );
physicsObj.SetAxis( GetPhysics()->GetAxis(), shards.Num() );
AddShard( clipModel, w );
}
/*
================
idBrittleFracture::CreateFractures
================
*/
void idBrittleFracture::CreateFractures( const idRenderModel *renderModel ) {
int i, j, k;
const modelSurface_t *surf;
const idDrawVert *v;
idFixedWinding w;
if ( !renderModel ) {
return;
}
physicsObj.SetSelf( this );
physicsObj.SetOrigin( GetPhysics()->GetOrigin(), 0 );
physicsObj.SetAxis( GetPhysics()->GetAxis(), 0 );
#ifdef _D3XP
if ( isXraySurface ) {
for ( i = 0; i < 1 /*renderModel->NumSurfaces()*/; i++ ) {
surf = renderModel->Surface( i );
material = surf->shader;
w.Clear();
int k = 0;
v = &surf->geometry->verts[k];
w.AddPoint( v->xyz );
w[k].s = v->st[0];
w[k].t = v->st[1];
k = 1;
v = &surf->geometry->verts[k];
w.AddPoint( v->xyz );
w[k].s = v->st[0];
w[k].t = v->st[1];
k = 3;
v = &surf->geometry->verts[k];
w.AddPoint( v->xyz );
w[k].s = v->st[0];
w[k].t = v->st[1];
k = 2;
v = &surf->geometry->verts[k];
w.AddPoint( v->xyz );
w[k].s = v->st[0];
w[k].t = v->st[1];
Fracture_r( w );
}
}
else {
for ( i = 0; i < 1 /*renderModel->NumSurfaces()*/; i++ ) {
surf = renderModel->Surface( i );
material = surf->shader;
for ( j = 0; j < surf->geometry->numIndexes; j += 3 ) {
w.Clear();
for ( k = 0; k < 3; k++ ) {
v = &surf->geometry->verts[ surf->geometry->indexes[ j + 2 - k ] ];
w.AddPoint( v->xyz );
w[k].s = v->st[0];
w[k].t = v->st[1];
}
Fracture_r( w );
}
}
}
#else
for ( i = 0; i < 1 /*renderModel->NumSurfaces()*/; i++ ) {
surf = renderModel->Surface( i );
material = surf->shader;
for ( j = 0; j < surf->geometry->numIndexes; j += 3 ) {
w.Clear();
for ( k = 0; k < 3; k++ ) {
v = &surf->geometry->verts[ surf->geometry->indexes[ j + 2 - k ] ];
w.AddPoint( v->xyz );
w[k].s = v->st[0];
w[k].t = v->st[1];
}
Fracture_r( w );
}
}
#endif
physicsObj.SetContents( material->GetContentFlags() );
SetPhysics( &physicsObj );
}
/*
================
idBrittleFracture::FindNeighbours
================
*/
void idBrittleFracture::FindNeighbours( void ) {
int i, j, k, l;
idVec3 p1, p2, dir;
idMat3 axis;
idPlane plane[4];
for ( i = 0; i < shards.Num(); i++ ) {
shard_t *shard1 = shards[i];
const idWinding &w1 = shard1->winding;
const idVec3 &origin1 = shard1->clipModel->GetOrigin();
const idMat3 &axis1 = shard1->clipModel->GetAxis();
for ( k = 0; k < w1.GetNumPoints(); k++ ) {
p1 = origin1 + w1[k].ToVec3() * axis1;
p2 = origin1 + w1[(k+1)%w1.GetNumPoints()].ToVec3() * axis1;
dir = p2 - p1;
dir.Normalize();
axis = dir.ToMat3();
plane[0].SetNormal( dir );
plane[0].FitThroughPoint( p1 );
plane[1].SetNormal( -dir );
plane[1].FitThroughPoint( p2 );
plane[2].SetNormal( axis[1] );
plane[2].FitThroughPoint( p1 );
plane[3].SetNormal( axis[2] );
plane[3].FitThroughPoint( p1 );
for ( j = 0; j < shards.Num(); j++ ) {
if ( i == j ) {
continue;
}
shard_t *shard2 = shards[j];
for ( l = 0; l < shard1->neighbours.Num(); l++ ) {
if ( shard1->neighbours[l] == shard2 ) {
break;
}
}
if ( l < shard1->neighbours.Num() ) {
continue;
}
const idWinding &w2 = shard2->winding;
const idVec3 &origin2 = shard2->clipModel->GetOrigin();
const idMat3 &axis2 = shard2->clipModel->GetAxis();
for ( l = w2.GetNumPoints()-1; l >= 0; l-- ) {
p1 = origin2 + w2[l].ToVec3() * axis2;
p2 = origin2 + w2[(l-1+w2.GetNumPoints())%w2.GetNumPoints()].ToVec3() * axis2;
if ( plane[0].Side( p2, 0.1f ) == SIDE_FRONT && plane[1].Side( p1, 0.1f ) == SIDE_FRONT ) {
if ( plane[2].Side( p1, 0.1f ) == SIDE_ON && plane[3].Side( p1, 0.1f ) == SIDE_ON ) {
if ( plane[2].Side( p2, 0.1f ) == SIDE_ON && plane[3].Side( p2, 0.1f ) == SIDE_ON ) {
shard1->neighbours.Append( shard2 );
shard1->edgeHasNeighbour[k] = true;
shard2->neighbours.Append( shard1 );
shard2->edgeHasNeighbour[(l-1+w2.GetNumPoints())%w2.GetNumPoints()] = true;
break;
}
}
}
}
}
}
for ( k = 0; k < w1.GetNumPoints(); k++ ) {
if ( !shard1->edgeHasNeighbour[k] ) {
break;
}
}
if ( k < w1.GetNumPoints() ) {
shard1->atEdge = true;
} else {
shard1->atEdge = false;
}
}
}
/*
================
idBrittleFracture::Event_Activate
================
*/
void idBrittleFracture::Event_Activate( idEntity *activator ) {
disableFracture = false;
if ( health <= 0 ) {
Break();
}
}
/*
================
idBrittleFracture::Event_Touch
================
*/
void idBrittleFracture::Event_Touch( idEntity *other, trace_t *trace ) {
idVec3 point, impulse;
if ( !IsBroken() ) {
return;
}
if ( trace->c.id < 0 || trace->c.id >= shards.Num() ) {
return;
}
point = shards[trace->c.id]->clipModel->GetOrigin();
impulse = other->GetPhysics()->GetLinearVelocity() * other->GetPhysics()->GetMass();
Shatter( point, impulse, gameLocal.time );
}
/*
================
idBrittleFracture::ClientPredictionThink
================
*/
void idBrittleFracture::ClientPredictionThink( void ) {
// only think forward because the state is not synced through snapshots
if ( !gameLocal.isNewFrame ) {
return;
}
Think();
}
/*
================
idBrittleFracture::ClientReceiveEvent
================
*/
bool idBrittleFracture::ClientReceiveEvent( int event, int time, const idBitMsg &msg ) {
idVec3 point, dir;
switch( event ) {
case EVENT_PROJECT_DECAL: {
point[0] = msg.ReadFloat();
point[1] = msg.ReadFloat();
point[2] = msg.ReadFloat();
dir[0] = msg.ReadFloat();
dir[1] = msg.ReadFloat();
dir[2] = msg.ReadFloat();
ProjectDecal( point, dir, time, NULL );
return true;
}
case EVENT_SHATTER: {
point[0] = msg.ReadFloat();
point[1] = msg.ReadFloat();
point[2] = msg.ReadFloat();
dir[0] = msg.ReadFloat();
dir[1] = msg.ReadFloat();
dir[2] = msg.ReadFloat();
Shatter( point, dir, time );
return true;
}
default:
break;
}
return idEntity::ClientReceiveEvent( event, time, msg );
}
| 412 | 0.95009 | 1 | 0.95009 | game-dev | MEDIA | 0.691043 | game-dev,graphics-rendering | 0.979699 | 1 | 0.979699 |
GTNewHorizons/GTNH-Translations | 15,497 | pl_PL/config/txloader/forceload/Binnie Core(+4)[genetics]/lang/pl_PL.lang | fluid.binnie.dna.raw=Płynne DNA
fluid.binnie.bacteria=Bakteria
fluid.binnie.growthMedium=Podłoże Hodowlane
fluid.binnie.bacteriaPoly=Bakterie Polimeryzujące
fluid.binnie.bacteriaVector=Bakterie Wektorowe
genetics.item.fieldKit.name=Zestaw Terenowy
genetics.item.fieldKit.tooltip.noPaper=Brak Papieru
genetics.item.fieldKit.tooltip.sheetsOfPaper=%d arkuszy papieru
genetics.item.fieldKit.tooltip.sheetOfPaper=%d arkuszu papieru
item.misc.name=Resource
genetics.item.casingIron.name=Wzmocniona Obudowa
genetics.item.dnaDye.name=Barwnik DNA
genetics.item.dyeFluor.name=Barwnik Fluorescencyjny
genetics.item.enzyme.name=Enzym
genetics.item.growthMedium.name=Podłoże Hodowlane
genetics.item.sequencerEmpty.name=Pusta Sekwencja
item.serum.name=Empty Serum Vial
genetics.item.serumEmpty.name=Pusta Fiolka Serum
item.serumArray.name=Empty Serum Array
genetics.item.genomeEmpty.name=Pusty Szyk Serum
genetics.item.cylinderEmpty.name=Glass Cylinder
genetics.item.integratedCircuit.name=Integrated Circuit Board
genetics.item.integratedCPU.name=Integrated CPU
genetics.item.casingCircuit.name=Integrated Casing
item.analyst.name=Analyst
genetics.item.analyst.name=Analyst
item.database.name=Gene Database
genetics.item.database.0.name=Gene Database
genetics.item.database.1.name=Master Gene Database
item.registry.name=Registry
genetics.item.registry.0.name=Registry
item.masterRegistry.name=Registry
genetics.item.registry.1.name=Master Registry
genetics.item.serum.name=%s Serum
genetics.item.serumArray.name=%s Serum Array
genetics.item.sequence=DNA Sequence
genetics.item.sequence.0=Very Faint
genetics.item.sequence.1=Faint
genetics.item.sequence.2=Weak
genetics.item.sequence.3=Average
genetics.item.sequence.4=Strong
genetics.item.sequence.5=Very Strong
genetics.gene.charge.empty=Empty
genetics.gene.charge.one=1 Charge
genetics.gene.charge.many=%d Charges
genetics.gene.more=%d more genes. Hold shift to display
item.sequence.name=DNA Sequence
genetics.sequence.corrupted=Corrupted Sequence
genetics.sequence.descriptor=%s DNA Sequence
genetics.sequence.unknown=<Unknown>
genetics.sequence.unsequenced=Unsequenced
genetics.sequence.fully=Fully Sequenced
genetics.sequence.partially=Partially Sequenced (%d%%)
tile.machine.name=Isolator
genetics.machine.machine.isolator=Isolator
genetics.machine.machine.isolator.info=The Isolator takes a random allele from a bee, tree or other individual and copies it into an empty sequence vial. This requires the use of ethanol as a solvent and an enzyme to cut up the DNA. The unsequenced serums can then be amplified in a Polymeriser and sequenced in a Sequencer. This process has a small chance to destroy the individual.
genetics.machine.isolator.error.noIndividual=No individual to isolate
genetics.machine.isolator.error.noRoom=No room for DNA sequences
genetics.machine.isolator.error.noVials=No empty sequencer vials
genetics.machine.isolator.error.noLiquid=Insufficient ethanol
genetics.machine.isolator.error.noEnzyme=No enzyme
genetics.machine.machine.sequencer=Sequencer
genetics.machine.machine.sequencer.info=The Sequencer takes unsequenced serums and determines which allele is present in them. This process is slow and requires the use of fluorescent dye.
genetics.machine.sequencer.unsequencedDNA=Unsequenced DNA
genetics.machine.sequencer.error.noSequence=No DNA sequence
genetics.machine.sequencer.error.noOwner.title=No Owner
genetics.machine.sequencer.error.noOwner=Replace this block to claim this machine
genetics.machine.sequencer.error.noSpace=No space for empty sequences
genetics.machine.sequencer.error.noDye=Insufficient Dye
genetics.machine.sequencer.gui.sequensedBy=Genes will be sequenced by %s
genetics.machine.sequencer.gui.willNotSave=Userless. Will not save sequences
genetics.machine.machine.polymeriser=Polymeriser
genetics.machine.machine.polymeriser.info=The Polymeriser fills empty serums with Raw DNA and replicating bacteria. This process can be accelerated using gold nuggets.
genetics.machine.polymeriser.error.noItem=No item to replicate
genetics.machine.polymeriser.error.itemFilled=Item Filled
genetics.machine.polymeriser.error.noLiquid=Insufficient Bacteria
genetics.machine.polymeriser.error.noDNA=Insufficient DNA
genetics.machine.polymeriser.replicatingWithGene=Replicating with 1 gene
genetics.machine.polymeriser.replicatingWithGenes=Replicating with %d genes
genetics.machine.polymeriser.unfilledSerum=Unfilled Serum
genetics.machine.machine.inoculator=Inoculator
genetics.machine.machine.inoculator.info=The Inoculator uses serums to add genes to breedable individuals. This process is very slow and requires a Bacteria Vector, but is always successful.
genetics.machine.inoculator.error.noIndividual=No Individual to Inoculate
genetics.machine.inoculator.error.noSerum=No Serum
genetics.machine.inoculator.error.noLiquid=Not enough liquid
genetics.machine.inoculator.error.emptySerum.title=Empty Serum
genetics.machine.inoculator.error.emptySerum=Serum is empty
genetics.machine.inoculator.error.invalidSerum.title=Invalid Serum
genetics.machine.inoculator.error.invalidSerum.0=Serum does not hold any genes
genetics.machine.inoculator.error.invalidSerum.1=Mismatch of Serum Type and Target
genetics.machine.inoculator.error.defunctSerum.title=Defunct Serum
genetics.machine.inoculator.error.defunctSerum=Individual already possesses this allele
genetics.machine.inoculator.inoculatingWithGene=Inoculating with 1 gene
genetics.machine.inoculator.inoculatingWithGenes=Inoculating with %d genes
genetics.machine.inoculator.inoculableIndividual=Inoculable Individual
genetics.machine.inoculator.serums=Serum Vials & Arrays
genetics.machine.labMachine.genepool=Genepool
genetics.machine.labMachine.genepool.info=The Genepool uses enzymes and ethanol to break down living things into DNA. During this process, all genetic information is lost and the source of the DNA is destroyed.
genetics.machine.genepool.error.noIndividual=No Individual
genetics.machine.genepool.error.noRoom=Not enough room in Tank
genetics.machine.genepool.error.noEthanol=Not enough Ethanol
genetics.machine.genepool.error.insufficientEnzyme=Insufficient Enzyme
tile.labMachine.name=Lab Stand
genetics.machine.labMachine.labMachine=Lab Stand
genetics.machine.labMachine.analyser=Analyzer
genetics.machine.labMachine.analyser.info=The Analyzer takes breedable individuals and DNA sequencers and analyzes them to determine the genes present. This requires DNA Dye, created from purple dye and glowstone
genetics.machine.analyser.dnaDye=DNA Dye
genetics.machine.analyser.unanalysedItem=Unanalyzed Item
genetics.machine.analyser.error.alreadyAnalysed.title=Already Analyzed
genetics.machine.analyser.error.alreadyAnalysed=Item has already been analyzed
genetics.machine.analyser.error.insufficientDye.title=Insufficient Dye
genetics.machine.analyser.error.insufficientDye=Not enough DNA dye to analyze
genetics.machine.analyser.error.noItem=No item to analyze
genetics.machine.labMachine.incubator=Incubator
genetics.machine.labMachine.incubator.info=The Incubator combines liquids and items and allows them to sit at an ideal temperature to encourage bacterial growth.
genetics.machine.incubator.error.noRecipe.title=No Recipe
genetics.machine.incubator.error.noRecipe=There is no valid recipe
genetics.machine.incubator.error.noLiquid=Not enough incubation liquid
genetics.machine.incubator.error.noRoom=No room for output
genetics.machine.labMachine.acclimatiser=Acclimatiser
genetics.machine.labMachine.acclimatiser.info=The Acclimatiser uses acclimatizing items to adjust the temperature and humidity tolerance of individuals. This process has only a small chance to succeed.
genetics.machine.acclimatiser.acclimatizingItems=Acclimatizing Items
genetics.machine.acclimatiser.error.noIndividual=No Individual to Acclimatise
genetics.machine.acclimatiser.error.noAcclimatizingItems=No Acclimatising Items
genetics.machine.acclimatiser.error.invalidAcclimatizingItems=Cannot Acclimatise this individual with these items
tile.advMachine.name=Splicer
genetics.machine.advMachine.splicer=Splicer
genetics.machine.advMachine.splicer.info=The Splicer is an incredibly powerful machine that is used to insert genes into individuals. This process is fast, but requires monumental amounts of power.
genetics.machine.splicer.error.noIndividual=No Individual to Splice
genetics.machine.splicer.error.noSerum=No Serum
genetics.machine.splicer.error.emptySerum.title=Empty Serum
genetics.machine.splicer.error.emptySerum=Serum is empty
genetics.machine.splicer.error.invalidSerum.title=Invalid Serum
genetics.machine.splicer.error.invalidSerum.0=Serum does not hold any genes
genetics.machine.splicer.error.invalidSerum.1=Mismatch of Serum Type and Target
genetics.machine.splicer.error.defunctSerum.title=Defunct Serum
genetics.machine.splicer.error.defunctSerum=Individual already possesses this allele
genetics.machine.splicer.splicableIndividual=Splicable Individual
genetics.machine.splicer.serums=Serum Vials & Arrays
genetics.machine.splicer.splicingIn.0=Splicing in %d/%d genes
genetics.machine.splicer.splicingIn.1=Splicing in %d/%d gene
genetics.machine.splicer.splicingIn.2=Splicing in %d genes
genetics.machine.splicer.splicingIn.3=Splicing in %d gene
genetics.gui.geneBank=Gene Bank
genetics.gui.geneBank.info=Info
genetics.gui.geneBank.stats=Stats
genetics.gui.geneBank.ranking=Ranking
genetics.gui.geneBank.project=Full Genome Project
genetics.gui.geneBank.sequencedGenes=Sequenced %d/%d Genes
genetics.gui.geneBank.sequencedGenes.short=%d/%d Genes
genetics.gui.analyst.info=Add a bee, tree, flower or butterfly to the top left slot. DNA Dye is required if it has not been analysed yet. This dye can also convert vanilla items to breedable individuals.
genetics.gui.analyst.registry=Registry
genetics.gui.analyst.page.hours=%s hours.
genetics.gui.analyst.page.minutes=%s min.
genetics.gui.analyst.page.seconds=%s sec.
genetics.gui.analyst.chromosome.active=Active: %s
genetics.gui.analyst.chromosome.inactive=Inactive: %s
genetics.gui.analyst.karyogram=Karyogram
genetics.gui.analyst.specimen=Specimen
genetics.gui.analyst.appearance=Appearance
genetics.gui.analyst.appearance.primaryColor=Primary Petal Color
genetics.gui.analyst.appearance.secondColor=Secondary Petal Color
genetics.gui.analyst.appearance.stemColor=Stem Color
genetics.gui.analyst.behaviour=Behaviour
genetics.gui.analyst.behaviour.effect=Effect: %s
genetics.gui.analyst.behaviour.pollinatesNearby=Pollinates nearby
genetics.gui.analyst.behaviour.withinBlocks=Within %d blocks
genetics.gui.analyst.behaviour.everyTime=Every %s
genetics.gui.analyst.behaviour.territory=Territory: %dx%dx%d
genetics.gui.analyst.behaviour.metabolism=Metabolism: %s
genetics.gui.analyst.biology=Biology
genetics.gui.analyst.biology.allDay=Active all day and night
genetics.gui.analyst.biology.night=Active at night
genetics.gui.analyst.biology.day=Active during the day
genetics.gui.analyst.biology.notRain=Cannot work during rain
genetics.gui.analyst.biology.rain=Can work during rain
genetics.gui.analyst.biology.underground=Can work underground
genetics.gui.analyst.biology.notUnderground=Cannot work underground
genetics.gui.analyst.biology.flammable=Flammable
genetics.gui.analyst.biology.nonflammable=Nonflammable
genetics.gui.analyst.biology.sappiness=Sappiness: %s
genetics.gui.analyst.biology.fertility.drones=%d drones per hive
genetics.gui.analyst.biology.fertility.drone=1 drone per hive
genetics.gui.analyst.biology.fertility.moths=Lays %d caterpillars before dying
genetics.gui.analyst.biology.fertility.moth=Lays 1 caterpillar before dying
genetics.gui.analyst.biology.fertility.leaves=1 Sapling per %d leaves
genetics.gui.analyst.biology.fertility.leaf=1 Sapling per 1 leaf
genetics.gui.analyst.biology.caterpillarGestation=Caterpillar Gestation
genetics.gui.analyst.biology.flightSpeed=Flight Speed
genetics.gui.analyst.biology.blocksPerSec=%d blocks per second
genetics.gui.analyst.biology.mothSpawn.perLeaf=Butterflies spawn every\n%s per leaf
genetics.gui.analyst.biology.mothSpawn=Butterflies spawn every\n%s
genetics.gui.analyst.biology.plantTypes=Plant Types
genetics.gui.analyst.biology.averageLifespan=Average Lifespan
genetics.gui.analyst.biology.pollination=Pollination
genetics.gui.analyst.biology.seedDispersal=Seed Dispersal
genetics.gui.analyst.biology.perLifetime=%d per lifetime
genetics.gui.analyst.biology.mcDays=%s MC days
genetics.gui.analyst.climate=Climate
genetics.gui.analyst.climate.biomes=Biomes
genetics.gui.analyst.climate.humidity=Humidity Tolerance
genetics.gui.analyst.climate.temperature=Temp. Tolerance
genetics.gui.analyst.soil=Soil
genetics.gui.analyst.soil.moistureTolerance=Moisture Tolerance
genetics.gui.analyst.soil.pHTolerance=pH Tolerance
genetics.gui.analyst.soil.recommendedSoil=Recommended Soil
genetics.gui.analyst.soil.otherSoils=Other Soils
genetics.gui.analyst.genome.active=Active Genome
genetics.gui.analyst.genome.inactive=Inactive Genome
genetics.gui.analyst.growth=Growth
genetics.gui.analyst.growth.mature=Saplings mature in
genetics.gui.analyst.growth.height=Height: %s
genetics.gui.analyst.growth.girth=Girth: %s
genetics.gui.analyst.growth.conditions=Growth Conditions
genetics.gui.analyst.mutations=Mutations
genetics.gui.analyst.mutations.habitat=Natural Habitat
genetics.gui.analyst.mutations.habitat.any=Found in any Hive
genetics.gui.analyst.mutations.habitat.villagers=Bought from Villagers
genetics.gui.analyst.mutations.habitat.chest=Dungeon Chests
genetics.gui.analyst.mutations.resultantMutations=Resultant Mutations
genetics.gui.analyst.mutations.furtherMutations=Further Mutations
genetics.gui.analyst.mutations.chance=%d%% Chance
genetics.gui.analyst.mutations.chance.current=(%d%% currently)
genetics.gui.analyst.mutations.unknownMutation=Unknown Mutation
genetics.gui.analyst.mutations.unknown=UNKNOWN
genetics.gui.analyst.description=Description
genetics.gui.analyst.description.unknown=<Unknown>
genetics.gui.analyst.description.discoveredBy=Discovered by %s
genetics.gui.analyst.description.complexity=Genetic Complexity: %s
genetics.gui.analyst.produce=Produce
genetics.gui.analyst.produce.rate=Rate: %s
genetics.gui.analyst.produce.natural=Natural Products
genetics.gui.analyst.produce.speciality=Specialty Products
genetics.gui.analyst.produce.refined=Refined Products
genetics.gui.analyst.produce.centrifuge=Centrifuges to give:
genetics.gui.analyst.produce.squeezes=Squeezes to give:
genetics.gui.analyst.produce.everyTime=Every %s
genetics.gui.analyst.fruit=Fruit
genetics.gui.analyst.fruit.yield=Yield: %s
genetics.gui.analyst.fruit.natural=Natural Fruit
genetics.gui.analyst.fruit.speciality=Speciality Fruit
genetics.gui.analyst.fruit.refined=Refined Products
genetics.gui.analyst.fruit.possible=Possible Fruits
genetics.gui.analyst.fruit.none=This tree has no\nfruits or nuts
genetics.gui.analyst.wood=Wood
genetics.gui.analyst.wood.fireproof=Fireproof
genetics.gui.analyst.wood.flammable=Flammable
genetics.gui.analyst.wood.logs=Logs
genetics.gui.analyst.wood.products=Refined Products
genetics.gui.analyst.wood.noFruits=This tree has no\nfruits or nuts
genetics.nei.tip.loss=Loss:
genetics.nei.tip.noConsume=Not Be Consumed
genetics.nei.tip.effect=Effect: %s
genetics.nei.tip.temperature=Temperature
genetics.nei.tip.humidity=Humidity
genetics.nei.tip.processSpeed=%dx Processing Speed
genetics.nei.tip.rf=%dx Processing Speed
genetics.nei.tip.databaseDesc=Open the database and pick up an empty serum. Click the serum on Sequenced gene to apply. | 412 | 0.646808 | 1 | 0.646808 | game-dev | MEDIA | 0.436982 | game-dev | 0.557371 | 1 | 0.557371 |
FWGS/hlsdk-portable | 9,436 | dlls/zombie.cpp | /***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* This source code contains proprietary and confidential information of
* Valve LLC and its suppliers. Access to this code is restricted to
* persons who have executed a written SDK license with Valve. Any access,
* use or distribution of this code by or to any unlicensed person is illegal.
*
****/
//=========================================================
// Zombie
//=========================================================
// UNDONE: Don't flinch every time you get hit
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "monsters.h"
#include "schedule.h"
//=========================================================
// Monster's Anim Events Go Here
//=========================================================
#define ZOMBIE_AE_ATTACK_RIGHT 0x01
#define ZOMBIE_AE_ATTACK_LEFT 0x02
#define ZOMBIE_AE_ATTACK_BOTH 0x03
#define ZOMBIE_FLINCH_DELAY 2 // at most one flinch every n secs
class CZombie : public CBaseMonster
{
public:
void Spawn( void );
void Precache( void );
void SetYawSpeed( void );
int Classify( void );
void HandleAnimEvent( MonsterEvent_t *pEvent );
int IgnoreConditions( void );
float m_flNextFlinch;
void PainSound( void );
void AlertSound( void );
void IdleSound( void );
void AttackSound( void );
static const char *pAttackSounds[];
static const char *pIdleSounds[];
static const char *pAlertSounds[];
static const char *pPainSounds[];
static const char *pAttackHitSounds[];
static const char *pAttackMissSounds[];
// No range attacks
BOOL CheckRangeAttack1( float flDot, float flDist ) { return FALSE; }
BOOL CheckRangeAttack2( float flDot, float flDist ) { return FALSE; }
int TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType );
};
LINK_ENTITY_TO_CLASS( monster_zombie, CZombie )
const char *CZombie::pAttackHitSounds[] =
{
"zombie/claw_strike1.wav",
"zombie/claw_strike2.wav",
"zombie/claw_strike3.wav",
};
const char *CZombie::pAttackMissSounds[] =
{
"zombie/claw_miss1.wav",
"zombie/claw_miss2.wav",
};
const char *CZombie::pAttackSounds[] =
{
"zombie/zo_attack1.wav",
"zombie/zo_attack2.wav",
};
const char *CZombie::pIdleSounds[] =
{
"zombie/zo_idle1.wav",
"zombie/zo_idle2.wav",
"zombie/zo_idle3.wav",
"zombie/zo_idle4.wav",
};
const char *CZombie::pAlertSounds[] =
{
"zombie/zo_alert10.wav",
"zombie/zo_alert20.wav",
"zombie/zo_alert30.wav",
};
const char *CZombie::pPainSounds[] =
{
"zombie/zo_pain1.wav",
"zombie/zo_pain2.wav",
};
//=========================================================
// Classify - indicates this monster's place in the
// relationship table.
//=========================================================
int CZombie::Classify( void )
{
return CLASS_ALIEN_MONSTER;
}
//=========================================================
// SetYawSpeed - allows each sequence to have a different
// turn rate associated with it.
//=========================================================
void CZombie::SetYawSpeed( void )
{
int ys;
ys = 120;
#if 0
switch ( m_Activity )
{
}
#endif
pev->yaw_speed = ys;
}
int CZombie::TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType )
{
// Take 30% damage from bullets
if( bitsDamageType == DMG_BULLET )
{
Vector vecDir = pev->origin - ( pevInflictor->absmin + pevInflictor->absmax ) * 0.5f;
vecDir = vecDir.Normalize();
float flForce = DamageForce( flDamage );
pev->velocity = pev->velocity + vecDir * flForce;
flDamage *= 0.3f;
}
// HACK HACK -- until we fix this.
if( IsAlive() )
PainSound();
return CBaseMonster::TakeDamage( pevInflictor, pevAttacker, flDamage, bitsDamageType );
}
void CZombie::PainSound( void )
{
int pitch = 95 + RANDOM_LONG( 0, 9 );
if( RANDOM_LONG( 0, 5 ) < 2 )
EMIT_SOUND_DYN( ENT( pev ), CHAN_VOICE, RANDOM_SOUND_ARRAY( pPainSounds ), 1.0, ATTN_NORM, 0, pitch );
}
void CZombie::AlertSound( void )
{
int pitch = 95 + RANDOM_LONG( 0, 9 );
EMIT_SOUND_DYN( ENT( pev ), CHAN_VOICE, RANDOM_SOUND_ARRAY( pAlertSounds ), 1.0, ATTN_NORM, 0, pitch );
}
void CZombie::IdleSound( void )
{
int pitch = 95 + RANDOM_LONG( 0, 9 );
// Play a random idle sound
EMIT_SOUND_DYN( ENT( pev ), CHAN_VOICE, RANDOM_SOUND_ARRAY( pIdleSounds ), 1.0, ATTN_NORM, 0, pitch );
}
void CZombie::AttackSound( void )
{
int pitch = 95 + RANDOM_LONG( 0, 9 );
// Play a random attack sound
EMIT_SOUND_DYN( ENT( pev ), CHAN_VOICE, RANDOM_SOUND_ARRAY( pAttackSounds ), 1.0, ATTN_NORM, 0, pitch );
}
//=========================================================
// HandleAnimEvent - catches the monster-specific messages
// that occur when tagged animation frames are played.
//=========================================================
void CZombie::HandleAnimEvent( MonsterEvent_t *pEvent )
{
switch( pEvent->event )
{
case ZOMBIE_AE_ATTACK_RIGHT:
{
// do stuff for this event.
//ALERT( at_console, "Slash right!\n" );
CBaseEntity *pHurt = CheckTraceHullAttack( 70, gSkillData.zombieDmgOneSlash, DMG_SLASH );
if( pHurt )
{
if( pHurt->pev->flags & ( FL_MONSTER | FL_CLIENT ) )
{
pHurt->pev->punchangle.z = -18;
pHurt->pev->punchangle.x = 5;
pHurt->pev->velocity = pHurt->pev->velocity - gpGlobals->v_right * 100;
}
// Play a random attack hit sound
EMIT_SOUND_DYN( ENT( pev ), CHAN_WEAPON, RANDOM_SOUND_ARRAY( pAttackHitSounds ), 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG( -5 , 5 ) );
}
else // Play a random attack miss sound
EMIT_SOUND_DYN( ENT( pev ), CHAN_WEAPON, RANDOM_SOUND_ARRAY( pAttackMissSounds ), 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG( -5, 5 ) );
if( RANDOM_LONG( 0, 1 ) )
AttackSound();
}
break;
case ZOMBIE_AE_ATTACK_LEFT:
{
// do stuff for this event.
//ALERT( at_console, "Slash left!\n" );
CBaseEntity *pHurt = CheckTraceHullAttack( 70, gSkillData.zombieDmgOneSlash, DMG_SLASH );
if( pHurt )
{
if( pHurt->pev->flags & ( FL_MONSTER | FL_CLIENT ) )
{
pHurt->pev->punchangle.z = 18;
pHurt->pev->punchangle.x = 5;
pHurt->pev->velocity = pHurt->pev->velocity + gpGlobals->v_right * 100;
}
EMIT_SOUND_DYN( ENT( pev ), CHAN_WEAPON, RANDOM_SOUND_ARRAY( pAttackHitSounds ), 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG( -5, 5 ) );
}
else
EMIT_SOUND_DYN( ENT( pev ), CHAN_WEAPON, RANDOM_SOUND_ARRAY( pAttackMissSounds ), 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG( -5, 5 ) );
if( RANDOM_LONG( 0, 1 ) )
AttackSound();
}
break;
case ZOMBIE_AE_ATTACK_BOTH:
{
// do stuff for this event.
CBaseEntity *pHurt = CheckTraceHullAttack( 70, gSkillData.zombieDmgBothSlash, DMG_SLASH );
if( pHurt )
{
if( pHurt->pev->flags & ( FL_MONSTER | FL_CLIENT ) )
{
pHurt->pev->punchangle.x = 5;
pHurt->pev->velocity = pHurt->pev->velocity + gpGlobals->v_forward * -100;
}
EMIT_SOUND_DYN( ENT( pev ), CHAN_WEAPON, RANDOM_SOUND_ARRAY( pAttackHitSounds ), 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG( -5, 5 ) );
}
else
EMIT_SOUND_DYN( ENT( pev ), CHAN_WEAPON, RANDOM_SOUND_ARRAY( pAttackMissSounds ), 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG( -5, 5 ) );
if( RANDOM_LONG( 0, 1 ) )
AttackSound();
}
break;
default:
CBaseMonster::HandleAnimEvent( pEvent );
break;
}
}
//=========================================================
// Spawn
//=========================================================
void CZombie::Spawn()
{
Precache();
SET_MODEL( ENT( pev ), "models/zombie.mdl" );
UTIL_SetSize( pev, VEC_HUMAN_HULL_MIN, VEC_HUMAN_HULL_MAX );
pev->solid = SOLID_SLIDEBOX;
pev->movetype = MOVETYPE_STEP;
m_bloodColor = BLOOD_COLOR_GREEN;
pev->health = gSkillData.zombieHealth;
pev->view_ofs = VEC_VIEW;// position of the eyes relative to monster's origin.
m_flFieldOfView = 0.5;// indicates the width of this monster's forward view cone ( as a dotproduct result )
m_MonsterState = MONSTERSTATE_NONE;
m_afCapability = bits_CAP_DOORS_GROUP;
MonsterInit();
}
//=========================================================
// Precache - precaches all resources this monster needs
//=========================================================
void CZombie::Precache()
{
PRECACHE_MODEL( "models/zombie.mdl" );
PRECACHE_SOUND_ARRAY( pAttackHitSounds );
PRECACHE_SOUND_ARRAY( pAttackMissSounds );
PRECACHE_SOUND_ARRAY( pAttackSounds );
PRECACHE_SOUND_ARRAY( pIdleSounds );
PRECACHE_SOUND_ARRAY( pAlertSounds );
PRECACHE_SOUND_ARRAY( pPainSounds );
}
//=========================================================
// AI Schedules Specific to this monster
//=========================================================
int CZombie::IgnoreConditions( void )
{
int iIgnore = CBaseMonster::IgnoreConditions();
if( ( m_Activity == ACT_MELEE_ATTACK1 ) || ( m_Activity == ACT_MELEE_ATTACK1 ) )
{
#if 0
if( pev->health < 20 )
iIgnore |= ( bits_COND_LIGHT_DAMAGE| bits_COND_HEAVY_DAMAGE );
else
#endif
if( m_flNextFlinch >= gpGlobals->time )
iIgnore |= ( bits_COND_LIGHT_DAMAGE | bits_COND_HEAVY_DAMAGE );
}
if( ( m_Activity == ACT_SMALL_FLINCH ) || ( m_Activity == ACT_BIG_FLINCH ) )
{
if( m_flNextFlinch < gpGlobals->time )
m_flNextFlinch = gpGlobals->time + ZOMBIE_FLINCH_DELAY;
}
return iIgnore;
}
| 412 | 0.95626 | 1 | 0.95626 | game-dev | MEDIA | 0.980034 | game-dev | 0.976969 | 1 | 0.976969 |
steward-fu/nds | 4,467 | sdl2/src/video/vita/SDL_vitamessagebox.c | /*
Simple DirectMedia Layer
Copyright (C) 1997-2022 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
#if SDL_VIDEO_DRIVER_VITA
#include "SDL_vitavideo.h"
#include "SDL_vitamessagebox.h"
#include <psp2/message_dialog.h>
#if SDL_VIDEO_RENDER_VITA_GXM
#include "../../render/vitagxm/SDL_render_vita_gxm_tools.h"
#endif /* SDL_VIDEO_RENDER_VITA_GXM */
int VITA_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
{
#if SDL_VIDEO_RENDER_VITA_GXM
SceMsgDialogParam param;
SceMsgDialogUserMessageParam msgParam;
SceMsgDialogButtonsParam buttonParam;
SceDisplayFrameBuf dispparam;
char message[512];
SceMsgDialogResult dialog_result;
SceCommonDialogErrorCode init_result;
SDL_bool setup_minimal_gxm = SDL_FALSE;
if(messageboxdata->numbuttons > 3) {
return -1;
}
SDL_zero(param);
sceMsgDialogParamInit(¶m);
param.mode = SCE_MSG_DIALOG_MODE_USER_MSG;
SDL_zero(msgParam);
SDL_snprintf(message, sizeof(message), "%s\r\n\r\n%s", messageboxdata->title, messageboxdata->message);
msgParam.msg = (const SceChar8 *)message;
SDL_zero(buttonParam);
if(messageboxdata->numbuttons == 3) {
msgParam.buttonType = SCE_MSG_DIALOG_BUTTON_TYPE_3BUTTONS;
msgParam.buttonParam = &buttonParam;
buttonParam.msg1 = messageboxdata->buttons[0].text;
buttonParam.msg2 = messageboxdata->buttons[1].text;
buttonParam.msg3 = messageboxdata->buttons[2].text;
}
else if(messageboxdata->numbuttons == 2) {
msgParam.buttonType = SCE_MSG_DIALOG_BUTTON_TYPE_YESNO;
}
else if(messageboxdata->numbuttons == 1) {
msgParam.buttonType = SCE_MSG_DIALOG_BUTTON_TYPE_OK;
}
param.userMsgParam = &msgParam;
dispparam.size = sizeof(dispparam);
init_result = sceMsgDialogInit(¶m);
// Setup display if it hasn't been initialized before
if(init_result == SCE_COMMON_DIALOG_ERROR_GXM_IS_UNINITIALIZED) {
gxm_minimal_init_for_common_dialog();
init_result = sceMsgDialogInit(¶m);
setup_minimal_gxm = SDL_TRUE;
}
gxm_init_for_common_dialog();
if(init_result >= 0) {
while(sceMsgDialogGetStatus() == SCE_COMMON_DIALOG_STATUS_RUNNING) {
gxm_swap_for_common_dialog();
}
SDL_zero(dialog_result);
sceMsgDialogGetResult(&dialog_result);
if(dialog_result.buttonId == SCE_MSG_DIALOG_BUTTON_ID_BUTTON1) {
*buttonid = messageboxdata->buttons[0].buttonid;
}
else if(dialog_result.buttonId == SCE_MSG_DIALOG_BUTTON_ID_BUTTON2) {
*buttonid = messageboxdata->buttons[1].buttonid;
}
else if(dialog_result.buttonId == SCE_MSG_DIALOG_BUTTON_ID_BUTTON3) {
*buttonid = messageboxdata->buttons[2].buttonid;
}
else if(dialog_result.buttonId == SCE_MSG_DIALOG_BUTTON_ID_YES) {
*buttonid = messageboxdata->buttons[0].buttonid;
}
else if(dialog_result.buttonId == SCE_MSG_DIALOG_BUTTON_ID_NO) {
*buttonid = messageboxdata->buttons[1].buttonid;
}
else if(dialog_result.buttonId == SCE_MSG_DIALOG_BUTTON_ID_OK) {
*buttonid = messageboxdata->buttons[0].buttonid;
}
sceMsgDialogTerm();
}
else {
return -1;
}
gxm_term_for_common_dialog();
if(setup_minimal_gxm) {
gxm_minimal_term_for_common_dialog();
}
return 0;
#else
(void)messageboxdata;
(void)buttonid;
return -1;
#endif
}
#endif /* SDL_VIDEO_DRIVER_VITA */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.894145 | 1 | 0.894145 | game-dev | MEDIA | 0.350866 | game-dev | 0.923393 | 1 | 0.923393 |
dotnet/wpf | 3,279 | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/hwdestinationtexturepool.h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//+-----------------------------------------------------------------------------
//
//
// $TAG ENGR
// $Module: win_mil_graphics_resourcemgmt
// $Keywords:
//
// $Description:
// Contains the CHwDestinationTexturePool class
//
// $ENDTAG
//
//------------------------------------------------------------------------------
MtExtern(CHwDestinationTexturePool);
//+-----------------------------------------------------------------------------
//
// Class:
// CHwDestinationTexturePool
//
// Synopsis:
// Controls realized instances of CHwDestinationTexture objects.
//
// This class will take creation parameters for a CHwDestinationTexture and
// either return an unused/cached texture or create a new one.
//
// This pool is intended to live in a CD3DDeviceLevel1 as a member.
//
//------------------------------------------------------------------------------
class CHwDestinationTexturePool : public IMILPoolManager
{
public:
static __checkReturn HRESULT Create(
__in_ecount(1) CD3DDeviceLevel1 *pDevice,
__deref_out_ecount(1) CHwDestinationTexturePool **ppDestinationTexturePool
);
HRESULT GetHwDestinationTexture(
__deref_out_ecount(1) CHwDestinationTexture **ppHwDestinationTexture
);
// Used to notify the manager that there are no outstanding uses and
// the manager has full control.
void UnusedNotification(
__inout_ecount(1) CMILPoolResource *pUnused
);
// Used to notify the manager that the resource is no longer usable
// and should be removed from the pool.
void UnusableNotification(
__inout_ecount(1) CMILPoolResource *pUnusable
);
void Release();
private:
DECLARE_METERHEAP_ALLOC(ProcessHeap, Mt(CHwDestinationTexturePool));
CHwDestinationTexturePool(
__in_ecount(1) CD3DDeviceLevel1 *pDevice
);
~CHwDestinationTexturePool();
private:
void AddToUnused(
__in_ecount(1) CHwDestinationTexture *pHwDestTexture
);
void RemoveFromUnused(
__deref_out_ecount(1) CHwDestinationTexture **ppHwDestTexture
);
// This method reduces the count of textures that will call this
// manager at some time. When there are no outstanding textures
// and the pool, which created this pool manager, Release's it,
// the count will reach -1 and the object will be deleted.
MIL_FORCEINLINE void DecOutstanding()
{
m_cOutstandingTextures--;
if (m_cOutstandingTextures == -1)
{
delete this;
}
}
private:
CD3DDeviceLevel1 * const m_pDevice;
// List of brushes that have recently become unused
LIST_ENTRY m_oUnusedListHead;
UINT m_cUnusedTextures;
// Count of all textures currently in use. When the manager
// has been released by the referencing pool object this
// value is decremented by 1 thus enabling it to reach -1.
// When the count is -1 this manager should be deleted.
LONG m_cOutstandingTextures;
};
| 412 | 0.914057 | 1 | 0.914057 | game-dev | MEDIA | 0.740522 | game-dev | 0.747518 | 1 | 0.747518 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.