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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
MATTYOneInc/AionEncomBase_Java8 | 3,377 | AL-Game/data/scripts/system/handlers/quest/master_server/_11364.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.master_server;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.SM_DIALOG_WINDOW;
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;
import com.aionemu.gameserver.services.QuestService;
import com.aionemu.gameserver.utils.PacketSendUtility;
/****/
/** Author Ghostfur & Unknown (Aion-Unique)
/****/
public class _11364 extends QuestHandler
{
private final static int questId = 11364;
public _11364() {
super(questId);
}
@Override
public void register() {
qe.registerOnKillInWorld(210130000, questId);
qe.registerQuestNpc(835654).addOnTalkEvent(questId);
qe.registerQuestNpc(835654).addOnAtDistanceEvent(questId);
}
@Override
public boolean onKillInWorldEvent(QuestEnv env) {
final Player player = env.getPlayer();
if (env.getVisibleObject() instanceof Player && player != null) {
if ((env.getPlayer().getLevel() >= (((Player)env.getVisibleObject()).getLevel() - 5)) &&
(env.getPlayer().getLevel() <= (((Player)env.getVisibleObject()).getLevel() + 9))) {
return defaultOnKillRankedEvent(env, 0, 3, true);
}
}
return false;
}
@Override
public boolean onDialogEvent(QuestEnv env) {
final Player player = env.getPlayer();
int targetId = env.getTargetId();
final QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs.getStatus() == QuestStatus.REWARD) {
if (targetId == 835654) {
if (env.getDialog() == QuestDialog.START_DIALOG) {
return sendQuestDialog(env, 10002);
} else if (env.getDialog() == QuestDialog.SELECT_REWARD) {
return sendQuestDialog(env, 5);
} else {
return sendQuestEndDialog(env);
}
}
}
return false;
}
@Override
public boolean onAtDistanceEvent(QuestEnv env) {
final Player player = env.getPlayer();
final QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs == null || qs.getStatus() == QuestStatus.NONE || qs.canRepeat()) {
QuestService.startQuest(env);
PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(0, 0));
return true;
}
return false;
}
} | 412 | 0.911154 | 1 | 0.911154 | game-dev | MEDIA | 0.950668 | game-dev | 0.9365 | 1 | 0.9365 |
mixandjam/ThePathless-Gameplay | 2,585 | Assets/Scripts/ProceduralSystem.cs | using UnityEngine;
using UnityEngine.Animations.Rigging;
using DG.Tweening;
public class ProceduralSystem : MonoBehaviour
{
ArrowSystem arrowSystem;
TargetSystem targetSystem;
bool rigEnabled;
[Header("Animation Rigging Connections")]
[SerializeField] Rig aimRig;
[SerializeField] Rig ikRig;
[SerializeField] Rig pullRig;
[SerializeField] Transform aimRigTarget;
[Header("Bow Connections")]
[SerializeField] Transform bowTransform;
[SerializeField] Transform bowDefaultReference;
[SerializeField] Transform bowActionReference;
[SerializeField] LineRenderer bowLineRenderer;
[SerializeField] Transform bowLineCenter;
[SerializeField] Transform bowLineHandReference;
[SerializeField] GameObject arrowInLineGO;
[Header("Settings")]
[SerializeField] float transitionSpeed = .1f;
[SerializeReference] float stringPullAmount = 0.2f;
private void Start()
{
arrowSystem = GetComponent<ArrowSystem>();
targetSystem = GetComponent<TargetSystem>();
arrowSystem.OnInputStart.AddListener(EnableRig);
arrowSystem.OnInputRelease.AddListener(DisableRig);
arrowSystem.OnTargetLost.AddListener(DisableRig);
arrowInLineGO.SetActive(false);
}
void Update()
{
if (arrowSystem.isCharging && targetSystem.storedTarget != null)
aimRigTarget.position = targetSystem.storedTarget.transform.position;
bowLineRenderer.SetPosition(1, bowLineCenter.localPosition);
}
void EnableRig()
{
rigEnabled = true;
arrowInLineGO.SetActive(true);
DOTween.Complete(5);
DOTween.Complete(7);
DOVirtual.Float(aimRig.weight, 1, transitionSpeed/2, SetAimRigWeight).SetId(5);
SetPullWeight(0);
DOVirtual.Float(pullRig.weight, 1, transitionSpeed, SetPullWeight).SetId(6);
bowLineCenter.DOLocalMoveZ(-stringPullAmount, transitionSpeed, false);
}
void DisableRig()
{
rigEnabled = false;
arrowInLineGO.SetActive(false);
bowLineCenter.DOLocalMoveZ(0, .4f, false).SetEase(Ease.OutElastic);
bowLineCenter.DOLocalMoveX(0, .4f, false).SetEase(Ease.OutElastic);
DOTween.Complete(5);
DOTween.Kill(6);
DOVirtual.Float(aimRig.weight, 0, transitionSpeed, SetAimRigWeight).SetDelay(.4f).SetId(7);
}
public void SetAimRigWeight(float weight)
{
aimRig.weight = weight;
ikRig.weight = weight;
}
void SetPullWeight(float weight)
{
pullRig.weight = weight;
}
}
| 412 | 0.760732 | 1 | 0.760732 | game-dev | MEDIA | 0.935205 | game-dev | 0.952433 | 1 | 0.952433 |
genshinsim/gcsim | 2,498 | internal/characters/traveler/common/hydro/charge.go | package hydro
import (
"fmt"
"github.com/genshinsim/gcsim/internal/frames"
"github.com/genshinsim/gcsim/pkg/core/action"
"github.com/genshinsim/gcsim/pkg/core/attacks"
"github.com/genshinsim/gcsim/pkg/core/attributes"
"github.com/genshinsim/gcsim/pkg/core/combat"
"github.com/genshinsim/gcsim/pkg/core/info"
)
var (
chargeFrames [][]int
chargeHitmarks = [][]int{{9, 20}, {14, 25}}
)
func init() {
chargeFrames = make([][]int, 2)
// Male
chargeFrames[0] = frames.InitAbilSlice(55) // CA -> N1
chargeFrames[0][action.ActionSkill] = 37 // CA -> E
chargeFrames[0][action.ActionBurst] = 36 // CA -> Q
chargeFrames[0][action.ActionDash] = chargeHitmarks[0][len(chargeHitmarks[0])-1] // CA -> D
chargeFrames[0][action.ActionJump] = chargeHitmarks[0][len(chargeHitmarks[0])-1] // CA -> J
chargeFrames[0][action.ActionSwap] = 44 // CA -> Swap
// Female
chargeFrames[1] = frames.InitAbilSlice(58) // CA -> N1
chargeFrames[1][action.ActionSkill] = 34 // CA -> E
chargeFrames[1][action.ActionBurst] = 35 // CA -> Q
chargeFrames[1][action.ActionDash] = chargeHitmarks[1][len(chargeHitmarks[1])-1] // CA -> D
chargeFrames[1][action.ActionJump] = chargeHitmarks[1][len(chargeHitmarks[1])-1] // CA -> J
chargeFrames[1][action.ActionSwap] = chargeHitmarks[1][len(chargeHitmarks[1])-1] // CA -> Swap
}
func (c *Traveler) ChargeAttack(p map[string]int) (action.Info, error) {
ai := info.AttackInfo{
ActorIndex: c.Index(),
AttackTag: attacks.AttackTagExtra,
ICDTag: attacks.ICDTagNormalAttack,
ICDGroup: attacks.ICDGroupDefault,
StrikeType: attacks.StrikeTypeSlash,
Element: attributes.Physical,
Durability: 25,
}
for i, mult := range charge[c.gender] {
ai.Mult = mult[c.TalentLvlAttack()]
ai.Abil = fmt.Sprintf("Charge %v", i)
c.Core.QueueAttack(
ai,
combat.NewCircleHitOnTarget(c.Core.Combat.Player(), nil, 2.2),
chargeHitmarks[c.gender][i],
chargeHitmarks[c.gender][i],
)
}
return action.Info{
Frames: frames.NewAbilFunc(chargeFrames[c.gender]),
AnimationLength: chargeFrames[c.gender][action.InvalidAction],
CanQueueAfter: chargeHitmarks[c.gender][len(chargeHitmarks[c.gender])-1],
State: action.ChargeAttackState,
}, nil
}
| 412 | 0.901897 | 1 | 0.901897 | game-dev | MEDIA | 0.807913 | game-dev | 0.839909 | 1 | 0.839909 |
magefree/mage | 1,396 | Mage.Sets/src/mage/cards/j/JelennSphinx.java |
package mage.cards.j;
import mage.MageInt;
import mage.abilities.common.AttacksTriggeredAbility;
import mage.abilities.effects.common.continuous.BoostAllEffect;
import mage.abilities.keyword.FlyingAbility;
import mage.abilities.keyword.VigilanceAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.SubType;
import mage.filter.StaticFilters;
import java.util.UUID;
/**
* @author LevelX2
*/
public final class JelennSphinx extends CardImpl {
public JelennSphinx(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{W}{U}");
this.subtype.add(SubType.SPHINX);
this.power = new MageInt(1);
this.toughness = new MageInt(5);
// Flying
this.addAbility(FlyingAbility.getInstance());
// Vigilance
this.addAbility(VigilanceAbility.getInstance());
// Whenever Jelenn Sphinx attacks, other attacking creatures get +1/+1 until end of turn.
this.addAbility(new AttacksTriggeredAbility(new BoostAllEffect(1, 1, Duration.EndOfTurn, StaticFilters.FILTER_ATTACKING_CREATURES, true), false));
}
private JelennSphinx(final JelennSphinx card) {
super(card);
}
@Override
public JelennSphinx copy() {
return new JelennSphinx(this);
}
}
| 412 | 0.952396 | 1 | 0.952396 | game-dev | MEDIA | 0.96666 | game-dev | 0.997243 | 1 | 0.997243 |
qcad/qcad | 68,668 | src/scripting/ecmaapi/generated/REcmaLinetype.cpp | // ***** AUTOGENERATED CODE, DO NOT EDIT *****
// ***** This class is not copyable.
#include "REcmaLinetype.h"
#include "RMetaTypes.h"
#include "../REcmaHelper.h"
// forwards declarations mapped to includes
#include "RDocument.h"
#include "RTransaction.h"
// includes for base ecma wrapper classes
#include "REcmaObject.h"
void REcmaLinetype::initEcma(QScriptEngine& engine, QScriptValue* proto
)
{
bool protoCreated = false;
if(proto == NULL){
proto = new QScriptValue(engine.newVariant(qVariantFromValue(
(RLinetype*) 0)));
protoCreated = true;
}
// primary base class RObject:
QScriptValue dpt = engine.defaultPrototype(
qMetaTypeId<RObject*>());
if (dpt.isValid()) {
proto->setPrototype(dpt);
}
/*
*/
QScriptValue fun;
// toString:
REcmaHelper::registerFunction(&engine, proto, toString, "toString");
// destroy:
REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
// conversion for base class RObject
REcmaHelper::registerFunction(&engine, proto, getRObject, "getRObject");
// get class name
REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
// conversion to all base classes (multiple inheritance):
REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
// properties:
// methods:
REcmaHelper::registerFunction(&engine, proto, getType, "getType");
REcmaHelper::registerFunction(&engine, proto, clone, "clone");
REcmaHelper::registerFunction(&engine, proto, cloneToLinetype, "cloneToLinetype");
REcmaHelper::registerFunction(&engine, proto, getName, "getName");
REcmaHelper::registerFunction(&engine, proto, setName, "setName");
REcmaHelper::registerFunction(&engine, proto, isMetric, "isMetric");
REcmaHelper::registerFunction(&engine, proto, setMetric, "setMetric");
REcmaHelper::registerFunction(&engine, proto, getDescription, "getDescription");
REcmaHelper::registerFunction(&engine, proto, setDescription, "setDescription");
REcmaHelper::registerFunction(&engine, proto, getLabel, "getLabel");
REcmaHelper::registerFunction(&engine, proto, getPatternString, "getPatternString");
REcmaHelper::registerFunction(&engine, proto, setPatternString, "setPatternString");
REcmaHelper::registerFunction(&engine, proto, isValid, "isValid");
REcmaHelper::registerFunction(&engine, proto, getProperty, "getProperty");
REcmaHelper::registerFunction(&engine, proto, setProperty, "setProperty");
REcmaHelper::registerFunction(&engine, proto, getPattern, "getPattern");
REcmaHelper::registerFunction(&engine, proto, setPattern, "setPattern");
REcmaHelper::registerFunction(&engine, proto, equals, "equals");
REcmaHelper::registerFunction(&engine, proto, operator_not_assign, "operator_not_assign");
REcmaHelper::registerFunction(&engine, proto, operator_less, "operator_less");
REcmaHelper::registerFunction(&engine, proto, print, "print");
engine.setDefaultPrototype(
qMetaTypeId<RLinetype*>(), *proto);
QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
// static methods:
REcmaHelper::registerFunction(&engine, &ctor, init, "init");
REcmaHelper::registerFunction(&engine, &ctor, getRtti, "getRtti");
// static properties:
ctor.setProperty("PropertyType",
qScriptValueFromValue(&engine, RLinetype::PropertyType),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyName",
qScriptValueFromValue(&engine, RLinetype::PropertyName),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyDescription",
qScriptValueFromValue(&engine, RLinetype::PropertyDescription),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyMetric",
qScriptValueFromValue(&engine, RLinetype::PropertyMetric),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyPatternString",
qScriptValueFromValue(&engine, RLinetype::PropertyPatternString),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
// enum values:
// enum conversions:
// init class:
engine.globalObject().setProperty("RLinetype",
ctor, QScriptValue::SkipInEnumeration);
if( protoCreated ){
delete proto;
}
}
QScriptValue REcmaLinetype::createEcma(QScriptContext* context, QScriptEngine* engine)
{
if (context->thisObject().strictlyEquals(
engine->globalObject())) {
return REcmaHelper::throwError(
QString::fromLatin1("RLinetype(): Did you forget to construct with 'new'?"),
context);
}
QScriptValue result;
// generate constructor variants:
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ constructor:
// non-copyable class:
RLinetype
* cppResult =
new
RLinetype
();
// TODO: triggers: Warning: QScriptEngine::newVariant(): changing class of non-QScriptObject not supported:
result = engine->newVariant(context->thisObject(), qVariantFromValue(cppResult));
} else
if( context->argumentCount() ==
1
&& (
context->argument(
0
).isVariant()
||
context->argument(
0
).isQObject()
||
context->argument(
0
).isNull()
) /* type: RDocument * */
){
// prepare arguments:
// argument is pointer
RDocument * a0 = NULL;
a0 =
REcmaHelper::scriptValueTo<RDocument >(
context->argument(0)
);
if (a0==NULL &&
!context->argument(0).isNull()) {
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type RDocument *RDocument *.", context);
}
// end of arguments
// call C++ constructor:
// non-copyable class:
RLinetype
* cppResult =
new
RLinetype
(
a0
);
// TODO: triggers: Warning: QScriptEngine::newVariant(): changing class of non-QScriptObject not supported:
result = engine->newVariant(context->thisObject(), qVariantFromValue(cppResult));
} else
if( context->argumentCount() ==
2
&& (
context->argument(
0
).isVariant()
||
context->argument(
0
).isQObject()
||
context->argument(
0
).isNull()
) /* type: RDocument * */
&& (
context->argument(
1
).isVariant()
||
context->argument(
1
).isQObject()
||
context->argument(
1
).isNull()
) /* type: RLinetypePattern */
){
// prepare arguments:
// argument is pointer
RDocument * a0 = NULL;
a0 =
REcmaHelper::scriptValueTo<RDocument >(
context->argument(0)
);
if (a0==NULL &&
!context->argument(0).isNull()) {
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type RDocument *RDocument *.", context);
}
// argument isCopyable and has default constructor and isSimpleClass
RLinetypePattern*
ap1 =
qscriptvalue_cast<
RLinetypePattern*
>(
context->argument(
1
)
);
if (ap1 == NULL) {
return REcmaHelper::throwError("RLinetype: Argument 1 is not of type RLinetypePattern.",
context);
}
RLinetypePattern
a1 =
*ap1;
// end of arguments
// call C++ constructor:
// non-copyable class:
RLinetype
* cppResult =
new
RLinetype
(
a0
,
a1
);
// TODO: triggers: Warning: QScriptEngine::newVariant(): changing class of non-QScriptObject not supported:
result = engine->newVariant(context->thisObject(), qVariantFromValue(cppResult));
} else
if( context->argumentCount() ==
1
&& (
context->argument(
0
).isVariant()
||
context->argument(
0
).isQObject()
||
context->argument(
0
).isNull()
) /* type: RLinetype */
){
// prepare arguments:
// argument is reference
RLinetype*
ap0 =
qscriptvalue_cast<
RLinetype*
>(
context->argument(
0
)
);
if( ap0 == NULL ){
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type RLinetype* or QSharedPointer<RLinetype>.",
context);
}
RLinetype& a0 = *ap0;
// end of arguments
// call C++ constructor:
// non-copyable class:
RLinetype
* cppResult =
new
RLinetype
(
a0
);
// TODO: triggers: Warning: QScriptEngine::newVariant(): changing class of non-QScriptObject not supported:
result = engine->newVariant(context->thisObject(), qVariantFromValue(cppResult));
} else
{
return REcmaHelper::throwError(
QString::fromLatin1("RLinetype(): no matching constructor found."),
context);
}
return result;
}
// conversion functions for base classes:
QScriptValue REcmaLinetype::getRObject(QScriptContext *context,
QScriptEngine *engine)
{
RObject* cppResult =
qscriptvalue_cast<RLinetype*> (context->thisObject());
QScriptValue result = qScriptValueFromValue(engine, cppResult);
return result;
}
// returns class name:
QScriptValue REcmaLinetype::getClassName(QScriptContext *context, QScriptEngine *engine)
{
return qScriptValueFromValue(engine, QString("RLinetype"));
}
// returns all base classes (in case of multiple inheritance):
QScriptValue REcmaLinetype::getBaseClasses(QScriptContext *context, QScriptEngine *engine)
{
QStringList list;
list.append("RObject");
return qScriptValueFromSequence(engine, list);
}
// properties:
// public methods:
QScriptValue
REcmaLinetype::init
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::init", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::init";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'void'
RLinetype::
init();
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.init().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::init", context, engine);
return result;
}
QScriptValue
REcmaLinetype::getRtti
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::getRtti", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::getRtti";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'RS::EntityType'
RS::EntityType cppResult =
RLinetype::
getRtti();
// return type: RS::EntityType
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.getRtti().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::getRtti", context, engine);
return result;
}
QScriptValue
REcmaLinetype::getType
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::getType", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::getType";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("getType", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'RS::EntityType'
RS::EntityType cppResult =
self->getType();
// return type: RS::EntityType
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.getType().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::getType", context, engine);
return result;
}
QScriptValue
REcmaLinetype::clone
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::clone", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::clone";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("clone", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'QSharedPointer < RObject >'
QSharedPointer < RObject > cppResult =
self->clone();
// return type: QSharedPointer < RObject >
// Shared pointer to object, cast to best match:
result = REcmaHelper::toScriptValue(engine, cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.clone().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::clone", context, engine);
return result;
}
QScriptValue
REcmaLinetype::cloneToLinetype
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::cloneToLinetype", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::cloneToLinetype";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("cloneToLinetype", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'QSharedPointer < RLinetype >'
QSharedPointer < RLinetype > cppResult =
self->cloneToLinetype();
// return type: QSharedPointer < RLinetype >
// not standard type nor reference
result = qScriptValueFromValue(engine, cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.cloneToLinetype().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::cloneToLinetype", context, engine);
return result;
}
QScriptValue
REcmaLinetype::getName
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::getName", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::getName";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("getName", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'QString'
QString cppResult =
self->getName();
// return type: QString
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.getName().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::getName", context, engine);
return result;
}
QScriptValue
REcmaLinetype::setName
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::setName", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::setName";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("setName", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isString()
) /* type: QString */
){
// prepare arguments:
// argument isStandardType
QString
a0 =
(QString)
context->argument( 0 ).
toString();
// end of arguments
// call C++ function:
// return type 'void'
self->setName(a0);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.setName().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::setName", context, engine);
return result;
}
QScriptValue
REcmaLinetype::isMetric
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::isMetric", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::isMetric";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("isMetric", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->isMetric();
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.isMetric().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::isMetric", context, engine);
return result;
}
QScriptValue
REcmaLinetype::setMetric
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::setMetric", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::setMetric";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("setMetric", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isBool()
) /* type: bool */
){
// prepare arguments:
// argument isStandardType
bool
a0 =
(bool)
context->argument( 0 ).
toBool();
// end of arguments
// call C++ function:
// return type 'void'
self->setMetric(a0);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.setMetric().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::setMetric", context, engine);
return result;
}
QScriptValue
REcmaLinetype::getDescription
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::getDescription", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::getDescription";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("getDescription", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'QString'
QString cppResult =
self->getDescription();
// return type: QString
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.getDescription().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::getDescription", context, engine);
return result;
}
QScriptValue
REcmaLinetype::setDescription
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::setDescription", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::setDescription";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("setDescription", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isString()
) /* type: QString */
){
// prepare arguments:
// argument isStandardType
QString
a0 =
(QString)
context->argument( 0 ).
toString();
// end of arguments
// call C++ function:
// return type 'void'
self->setDescription(a0);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.setDescription().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::setDescription", context, engine);
return result;
}
QScriptValue
REcmaLinetype::getLabel
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::getLabel", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::getLabel";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("getLabel", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'QString'
QString cppResult =
self->getLabel();
// return type: QString
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.getLabel().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::getLabel", context, engine);
return result;
}
QScriptValue
REcmaLinetype::getPatternString
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::getPatternString", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::getPatternString";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("getPatternString", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'QString'
QString cppResult =
self->getPatternString();
// return type: QString
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.getPatternString().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::getPatternString", context, engine);
return result;
}
QScriptValue
REcmaLinetype::setPatternString
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::setPatternString", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::setPatternString";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("setPatternString", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isString()
) /* type: QString */
){
// prepare arguments:
// argument isStandardType
QString
a0 =
(QString)
context->argument( 0 ).
toString();
// end of arguments
// call C++ function:
// return type 'void'
self->setPatternString(a0);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.setPatternString().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::setPatternString", context, engine);
return result;
}
QScriptValue
REcmaLinetype::isValid
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::isValid", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::isValid";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("isValid", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->isValid();
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.isValid().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::isValid", context, engine);
return result;
}
QScriptValue
REcmaLinetype::getProperty
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::getProperty", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::getProperty";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("getProperty", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RPropertyTypeId */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RPropertyTypeId*
ap0 =
qscriptvalue_cast<
RPropertyTypeId*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type RPropertyTypeId.",
context);
}
RPropertyTypeId
a0 =
*ap0;
// end of arguments
// call C++ function:
// return type 'QPair < QVariant , RPropertyAttributes >'
QPair < QVariant , RPropertyAttributes > cppResult =
self->getProperty(a0);
// return type: QPair < QVariant , RPropertyAttributes >
// Pair of ...:
//result = REcmaHelper::pairToScriptValue(engine, cppResult);
QVariantList vl;
QVariant v;
// first type of pair is variant:
if (QString(cppResult.first.typeName())=="RLineweight::Lineweight") {
v.setValue((int)cppResult.first.value<RLineweight::Lineweight>());
}
else {
v.setValue(cppResult.first);
}
vl.append(v);
v.setValue(cppResult.second);
vl.append(v);
result = qScriptValueFromValue(engine, vl);
} else
if( context->argumentCount() ==
2 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RPropertyTypeId */
&& (
context->argument(1).isBool()
) /* type: bool */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RPropertyTypeId*
ap0 =
qscriptvalue_cast<
RPropertyTypeId*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type RPropertyTypeId.",
context);
}
RPropertyTypeId
a0 =
*ap0;
// argument isStandardType
bool
a1 =
(bool)
context->argument( 1 ).
toBool();
// end of arguments
// call C++ function:
// return type 'QPair < QVariant , RPropertyAttributes >'
QPair < QVariant , RPropertyAttributes > cppResult =
self->getProperty(a0
,
a1);
// return type: QPair < QVariant , RPropertyAttributes >
// Pair of ...:
//result = REcmaHelper::pairToScriptValue(engine, cppResult);
QVariantList vl;
QVariant v;
// first type of pair is variant:
if (QString(cppResult.first.typeName())=="RLineweight::Lineweight") {
v.setValue((int)cppResult.first.value<RLineweight::Lineweight>());
}
else {
v.setValue(cppResult.first);
}
vl.append(v);
v.setValue(cppResult.second);
vl.append(v);
result = qScriptValueFromValue(engine, vl);
} else
if( context->argumentCount() ==
3 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RPropertyTypeId */
&& (
context->argument(1).isBool()
) /* type: bool */
&& (
context->argument(2).isBool()
) /* type: bool */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RPropertyTypeId*
ap0 =
qscriptvalue_cast<
RPropertyTypeId*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type RPropertyTypeId.",
context);
}
RPropertyTypeId
a0 =
*ap0;
// argument isStandardType
bool
a1 =
(bool)
context->argument( 1 ).
toBool();
// argument isStandardType
bool
a2 =
(bool)
context->argument( 2 ).
toBool();
// end of arguments
// call C++ function:
// return type 'QPair < QVariant , RPropertyAttributes >'
QPair < QVariant , RPropertyAttributes > cppResult =
self->getProperty(a0
,
a1
,
a2);
// return type: QPair < QVariant , RPropertyAttributes >
// Pair of ...:
//result = REcmaHelper::pairToScriptValue(engine, cppResult);
QVariantList vl;
QVariant v;
// first type of pair is variant:
if (QString(cppResult.first.typeName())=="RLineweight::Lineweight") {
v.setValue((int)cppResult.first.value<RLineweight::Lineweight>());
}
else {
v.setValue(cppResult.first);
}
vl.append(v);
v.setValue(cppResult.second);
vl.append(v);
result = qScriptValueFromValue(engine, vl);
} else
if( context->argumentCount() ==
4 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RPropertyTypeId */
&& (
context->argument(1).isBool()
) /* type: bool */
&& (
context->argument(2).isBool()
) /* type: bool */
&& (
context->argument(3).isBool()
) /* type: bool */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RPropertyTypeId*
ap0 =
qscriptvalue_cast<
RPropertyTypeId*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type RPropertyTypeId.",
context);
}
RPropertyTypeId
a0 =
*ap0;
// argument isStandardType
bool
a1 =
(bool)
context->argument( 1 ).
toBool();
// argument isStandardType
bool
a2 =
(bool)
context->argument( 2 ).
toBool();
// argument isStandardType
bool
a3 =
(bool)
context->argument( 3 ).
toBool();
// end of arguments
// call C++ function:
// return type 'QPair < QVariant , RPropertyAttributes >'
QPair < QVariant , RPropertyAttributes > cppResult =
self->getProperty(a0
,
a1
,
a2
,
a3);
// return type: QPair < QVariant , RPropertyAttributes >
// Pair of ...:
//result = REcmaHelper::pairToScriptValue(engine, cppResult);
QVariantList vl;
QVariant v;
// first type of pair is variant:
if (QString(cppResult.first.typeName())=="RLineweight::Lineweight") {
v.setValue((int)cppResult.first.value<RLineweight::Lineweight>());
}
else {
v.setValue(cppResult.first);
}
vl.append(v);
v.setValue(cppResult.second);
vl.append(v);
result = qScriptValueFromValue(engine, vl);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.getProperty().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::getProperty", context, engine);
return result;
}
QScriptValue
REcmaLinetype::setProperty
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::setProperty", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::setProperty";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("setProperty", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
2 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RPropertyTypeId */
&& (
context->argument(1).isVariant() ||
context->argument(1).isQObject() ||
context->argument(1).isNumber() ||
context->argument(1).isString() ||
context->argument(1).isBool() ||
context->argument(1).isArray() ||
context->argument(1).isNull() ||
context->argument(1).isUndefined()
) /* type: QVariant */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RPropertyTypeId*
ap0 =
qscriptvalue_cast<
RPropertyTypeId*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type RPropertyTypeId.",
context);
}
RPropertyTypeId
a0 =
*ap0;
// argument isCopyable or pointer
QVariant
a1 =
qscriptvalue_cast<
QVariant
>(
context->argument(
1
)
);
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->setProperty(a0
,
a1);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
if( context->argumentCount() ==
3 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RPropertyTypeId */
&& (
context->argument(1).isVariant() ||
context->argument(1).isQObject() ||
context->argument(1).isNumber() ||
context->argument(1).isString() ||
context->argument(1).isBool() ||
context->argument(1).isArray() ||
context->argument(1).isNull() ||
context->argument(1).isUndefined()
) /* type: QVariant */
&& (
context->argument(2).isVariant() ||
context->argument(2).isQObject() ||
context->argument(2).isNull()
) /* type: RTransaction * */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RPropertyTypeId*
ap0 =
qscriptvalue_cast<
RPropertyTypeId*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type RPropertyTypeId.",
context);
}
RPropertyTypeId
a0 =
*ap0;
// argument isCopyable or pointer
QVariant
a1 =
qscriptvalue_cast<
QVariant
>(
context->argument(
1
)
);
// argument is pointer
RTransaction * a2 = NULL;
a2 =
REcmaHelper::scriptValueTo<RTransaction >(
context->argument(2)
);
if (a2==NULL &&
!context->argument(2).isNull()) {
return REcmaHelper::throwError("RLinetype: Argument 2 is not of type RTransaction *RTransaction *.", context);
}
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->setProperty(a0
,
a1
,
a2);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.setProperty().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::setProperty", context, engine);
return result;
}
QScriptValue
REcmaLinetype::getPattern
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::getPattern", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::getPattern";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("getPattern", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'RLinetypePattern'
RLinetypePattern cppResult =
self->getPattern();
// return type: RLinetypePattern
// not standard type nor reference
result = qScriptValueFromValue(engine, cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.getPattern().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::getPattern", context, engine);
return result;
}
QScriptValue
REcmaLinetype::setPattern
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::setPattern", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::setPattern";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("setPattern", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RLinetypePattern */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RLinetypePattern*
ap0 =
qscriptvalue_cast<
RLinetypePattern*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type RLinetypePattern.",
context);
}
RLinetypePattern
a0 =
*ap0;
// end of arguments
// call C++ function:
// return type 'void'
self->setPattern(a0);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.setPattern().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::setPattern", context, engine);
return result;
}
QScriptValue
REcmaLinetype::equals
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::operator==", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::operator==";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("operator==", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RLinetype */
){
// prepare arguments:
// argument is reference
RLinetype*
ap0 =
qscriptvalue_cast<
RLinetype*
>(
context->argument(
0
)
);
if( ap0 == NULL ){
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type RLinetype* or QSharedPointer<RLinetype>.",
context);
}
RLinetype& a0 = *ap0;
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->operator==(a0);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.equals().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::operator==", context, engine);
return result;
}
QScriptValue
REcmaLinetype::operator_not_assign
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::operator!=", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::operator!=";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("operator!=", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RLinetype */
){
// prepare arguments:
// argument is reference
RLinetype*
ap0 =
qscriptvalue_cast<
RLinetype*
>(
context->argument(
0
)
);
if( ap0 == NULL ){
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type RLinetype* or QSharedPointer<RLinetype>.",
context);
}
RLinetype& a0 = *ap0;
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->operator!=(a0);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.operator_not_assign().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::operator!=", context, engine);
return result;
}
QScriptValue
REcmaLinetype::operator_less
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::operator<", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::operator<";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("operator<", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RLinetype */
){
// prepare arguments:
// argument is reference
RLinetype*
ap0 =
qscriptvalue_cast<
RLinetype*
>(
context->argument(
0
)
);
if( ap0 == NULL ){
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type RLinetype* or QSharedPointer<RLinetype>.",
context);
}
RLinetype& a0 = *ap0;
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->operator<(a0);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.operator_less().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::operator<", context, engine);
return result;
}
QScriptValue
REcmaLinetype::print
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaLinetype::print", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaLinetype::print";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RLinetype* self =
getSelf("print", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: QDebug */
){
// prepare arguments:
// argument is reference
QDebug*
ap0 =
qscriptvalue_cast<
QDebug*
>(
context->argument(
0
)
);
if( ap0 == NULL ){
return REcmaHelper::throwError("RLinetype: Argument 0 is not of type QDebug* or QSharedPointer<QDebug>.",
context);
}
QDebug& a0 = *ap0;
// end of arguments
// call C++ function:
// return type 'void'
self->print(a0);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RLinetype.print().",
context);
}
//REcmaHelper::functionEnd("REcmaLinetype::print", context, engine);
return result;
}
QScriptValue REcmaLinetype::toString
(QScriptContext *context, QScriptEngine *engine)
{
RLinetype* self = getSelf("toString", context);
QString result;
result = QString("RLinetype(0x%1)").arg((unsigned long int)self, 0, 16);
return QScriptValue(result);
}
QScriptValue REcmaLinetype::destroy(QScriptContext *context, QScriptEngine *engine)
{
RLinetype* self = getSelf("RLinetype", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
delete self;
context->thisObject().setData(engine->nullValue());
context->thisObject().prototype().setData(engine->nullValue());
context->thisObject().setPrototype(engine->nullValue());
context->thisObject().setScriptClass(NULL);
return engine->undefinedValue();
}
RLinetype* REcmaLinetype::getSelf(const QString& fName, QScriptContext* context)
{
RLinetype* self = NULL;
// self could be a normal object (e.g. from an UI file) or
// an ECMA shell object (made from an ECMA script):
//self = getSelfShell(fName, context);
//if (self==NULL) {
self = REcmaHelper::scriptValueTo<RLinetype >(context->thisObject())
;
//}
if (self == NULL){
// avoid recursion (toString is used by the backtrace):
if (fName!="toString") {
REcmaHelper::throwError(QString("RLinetype.%1(): "
"This object is not a RLinetype").arg(fName),
context);
}
return NULL;
}
return self;
}
RLinetype* REcmaLinetype::getSelfShell(const QString& fName, QScriptContext* context)
{
RLinetype* selfBase = getSelf(fName, context);
RLinetype* self = dynamic_cast<RLinetype*>(selfBase);
//return REcmaHelper::scriptValueTo<RLinetype >(context->thisObject());
if(self == NULL){
REcmaHelper::throwError(QString("RLinetype.%1(): "
"This object is not a RLinetype").arg(fName),
context);
}
return self;
}
| 412 | 0.93771 | 1 | 0.93771 | game-dev | MEDIA | 0.736641 | game-dev | 0.858853 | 1 | 0.858853 |
EphemeralSpace/ephemeral-space | 2,639 | Content.Shared/Revenant/EntitySystems/SharedCorporealSystem.cs | using Content.Shared.Physics;
using Robust.Shared.Physics;
using System.Linq;
using Content.Shared.Movement.Systems;
using Content.Shared.Revenant.Components;
using Robust.Shared.Physics.Systems;
namespace Content.Shared.Revenant.EntitySystems;
/// <summary>
/// Makes the revenant solid when the component is applied.
/// Additionally applies a few visual effects.
/// Used for status effect.
/// </summary>
public abstract class SharedCorporealSystem : EntitySystem
{
[Dependency] private readonly SharedAppearanceSystem _appearance = default!;
[Dependency] private readonly MovementSpeedModifierSystem _movement = default!;
[Dependency] private readonly SharedPhysicsSystem _physics = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<CorporealComponent, ComponentStartup>(OnStartup);
SubscribeLocalEvent<CorporealComponent, ComponentShutdown>(OnShutdown);
SubscribeLocalEvent<CorporealComponent, RefreshMovementSpeedModifiersEvent>(OnRefresh);
}
private void OnRefresh(EntityUid uid, CorporealComponent component, RefreshMovementSpeedModifiersEvent args)
{
args.ModifySpeed(component.MovementSpeedDebuff, component.MovementSpeedDebuff);
}
public virtual void OnStartup(EntityUid uid, CorporealComponent component, ComponentStartup args)
{
_appearance.SetData(uid, RevenantVisuals.Corporeal, true);
if (TryComp<FixturesComponent>(uid, out var fixtures) && fixtures.FixtureCount >= 1)
{
var fixture = fixtures.Fixtures.First();
_physics.SetCollisionMask(uid, fixture.Key, fixture.Value, (int) (CollisionGroup.SmallMobMask | CollisionGroup.GhostImpassable), fixtures);
_physics.SetCollisionLayer(uid, fixture.Key, fixture.Value, (int) CollisionGroup.SmallMobLayer, fixtures);
}
_movement.RefreshMovementSpeedModifiers(uid);
}
public virtual void OnShutdown(EntityUid uid, CorporealComponent component, ComponentShutdown args)
{
_appearance.SetData(uid, RevenantVisuals.Corporeal, false);
if (TryComp<FixturesComponent>(uid, out var fixtures) && fixtures.FixtureCount >= 1)
{
var fixture = fixtures.Fixtures.First();
_physics.SetCollisionMask(uid, fixture.Key, fixture.Value, (int) CollisionGroup.GhostImpassable, fixtures);
_physics.SetCollisionLayer(uid, fixture.Key, fixture.Value, 0, fixtures);
}
component.MovementSpeedDebuff = 1; //just so we can avoid annoying code elsewhere
_movement.RefreshMovementSpeedModifiers(uid);
}
}
| 412 | 0.898507 | 1 | 0.898507 | game-dev | MEDIA | 0.784466 | game-dev,graphics-rendering | 0.923145 | 1 | 0.923145 |
mrchantey/beet | 1,573 | crates/beet_spatial/src/steer_actions/separate.rs | use crate::prelude::*;
use beet_core::prelude::*;
use beet_flow::prelude::*;
use std::marker::PhantomData;
/// Ensures that boids avoid crowding neighbors by maintaining a minimum distance from each other.
/// This is done by updating the [`Velocity`] component.
/// ## Tags
/// - [LongRunning](ActionTag::LongRunning)
/// - [MutateOrigin](ActionTag::MutateOrigin)
#[derive(Debug, Clone, PartialEq, Component, Reflect)]
#[reflect(Default, Component)]
#[require(ContinueRun)]
pub struct Separate<M> {
/// The scalar to apply to the impulse
pub scalar: f32,
/// The radius within which to avoid other boids
pub radius: f32,
#[reflect(ignore)]
phantom: PhantomData<M>,
}
impl<M> Default for Separate<M> {
fn default() -> Self {
Self {
scalar: 1.,
radius: 0.25,
phantom: PhantomData,
}
}
}
impl<M> Separate<M> {
/// Set impulse strength with default radius
pub fn new(scalar: f32) -> Self {
Self {
scalar,
..default()
}
}
/// Scale all radius and distances by this value
pub fn scaled_dist(mut self, dist: f32) -> Self {
self.radius *= dist;
self
}
}
pub(crate) fn separate<M: Component>(
boids: Query<(Entity, &Transform), With<M>>,
mut agents: AgentQuery<(Entity, &Transform, &mut Impulse, &MaxSpeed)>,
query: Query<(Entity, &Separate<M>), With<Running>>,
) -> Result {
for (action, separate) in query.iter() {
let (entity, transform, mut impulse, max_speed) =
agents.get_mut(action)?;
**impulse += *separate_impulse(
entity,
transform.translation,
*max_speed,
separate,
boids.iter(),
);
}
Ok(())
}
| 412 | 0.865949 | 1 | 0.865949 | game-dev | MEDIA | 0.642499 | game-dev | 0.958863 | 1 | 0.958863 |
pinterf/mvtools | 5,727 | Sources/conc/ObjPool.hpp | /*****************************************************************************
ObjPool.hpp
Author: Laurent de Soras, 2012
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#if ! defined (conc_ObjPool_CODEHEADER_INCLUDED)
#define conc_ObjPool_CODEHEADER_INCLUDED
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include <cassert>
#include <stdexcept>
namespace conc
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*
==============================================================================
Name: ctor
Description:
Create the pool, empty of any object.
Throws: Most likely memory allocation exceptions.
==============================================================================
*/
template <class T>
ObjPool <T>::ObjPool ()
: _factory_ptr (0)
, _stack_free ()
, _stack_all ()
, _obj_cell_pool_ptr ()
{
_obj_cell_pool_ptr->expand_to (1024);
}
/*
==============================================================================
Name: dtor
Throws: Nothing (I hope so).
==============================================================================
*/
template <class T>
ObjPool <T>::~ObjPool ()
{
cleanup ();
}
/*
==============================================================================
Name: set_factory
Description:
Link the pool to the object factory. This function must be called at least
once before any call to take_obj().
Input parameters:
- fact: Reference on the factory.
Throws: Nothing
==============================================================================
*/
template <class T>
void ObjPool <T>::set_factory (Factory &fact)
{
_factory_ptr = &fact;
}
template <class T>
typename ObjPool <T>::Factory & ObjPool <T>::use_factory () const
{
assert (_factory_ptr != 0);
return (*_factory_ptr);
}
/*
==============================================================================
Name: take_obj
Description:
Borrow an object from the pool, or try to construct a new one if none are
available. Objects must be returned to the pool with return_obj(), under
the penalty of resource leaks.
Returns:
A pointer on the object, or 0 if no object is available and cannot be
created for any reason.
Throws: Nothing
==============================================================================
*/
template <class T>
T * ObjPool <T>::take_obj ()
{
assert (_factory_ptr != 0);
ObjType * obj_ptr = 0;
PtrCell * cell_ptr = _stack_free.pop ();
if (cell_ptr == 0)
{
obj_ptr = _factory_ptr->create ();
if (obj_ptr != 0)
{
bool ok_flag = false;
try
{
cell_ptr = _obj_cell_pool_ptr->take_cell (true);
if (cell_ptr != 0)
{
cell_ptr->_val = obj_ptr;
_stack_all.push (*cell_ptr);
ok_flag = true;
}
}
catch (...)
{
// Nothing
}
if (! ok_flag)
{
delete obj_ptr;
obj_ptr = 0;
}
}
}
else
{
obj_ptr = cell_ptr->_val;
_obj_cell_pool_ptr->return_cell (*cell_ptr);
}
return (obj_ptr);
}
/*
==============================================================================
Name: return_obj
Description:
Return to the pool an object previously borrowed with take_obj().
These details are not checked but are very important:
- Do not return twice the same object
- Do not return an object you didn't get from take_obj()
Input parameters:
- obj: Reference on the returned object.
Throws: Nothing
==============================================================================
*/
template <class T>
void ObjPool <T>::return_obj (T &obj)
{
PtrCell * cell_ptr = 0;
try
{
cell_ptr = _obj_cell_pool_ptr->take_cell (true);
}
catch (...)
{
// Nothing
}
if (cell_ptr == 0)
{
throw std::runtime_error ("return_obj(): cannot allocate a new cell.");
}
else
{
cell_ptr->_val = &obj;
_stack_free.push (*cell_ptr);
}
}
/*
==============================================================================
Name: cleanup
Description:
Preliminary deletion of the pool content, also used during the pool
destruction.
Do not call it if some objects are still out of the pool!
Use with care.
Throws: Nothing
==============================================================================
*/
template <class T>
void ObjPool <T>::cleanup ()
{
#if ! defined (NDEBUG)
const int count_free =
#endif
delete_obj_stack (_stack_free, false);
#if ! defined (NDEBUG)
const int count_all =
#endif
delete_obj_stack (_stack_all, true);
// False would mean that some cells are still out, in use.
assert (count_free == count_all);
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
template <class T>
int ObjPool <T>::delete_obj_stack (PtrStack &ptr_stack, bool destroy_flag)
{
typename PtrStack::CellType * cell_ptr = 0;
int count = 0;
do
{
cell_ptr = ptr_stack.pop ();
if (cell_ptr != 0)
{
if (destroy_flag)
{
ObjType * & obj_ptr = cell_ptr->_val;
delete obj_ptr;
obj_ptr = 0;
}
_obj_cell_pool_ptr->return_cell (*cell_ptr);
++ count;
}
}
while (cell_ptr != 0);
return (count);
}
} // namespace conc
#endif // conc_ObjPool_CODEHEADER_INCLUDED
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 412 | 0.792151 | 1 | 0.792151 | game-dev | MEDIA | 0.692518 | game-dev | 0.586016 | 1 | 0.586016 |
bebeli555/CookieClient | 2,471 | src/main/java/me/bebeli555/cookieclient/mods/render/EntityESP.java | package me.bebeli555.cookieclient.mods.render;
import me.bebeli555.cookieclient.Mod;
import me.bebeli555.cookieclient.gui.Group;
import me.bebeli555.cookieclient.gui.Mode;
import me.bebeli555.cookieclient.gui.Setting;
import me.bebeli555.cookieclient.rendering.RenderUtil;
import me.bebeli555.cookieclient.utils.EntityUtil;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
public class EntityESP extends Mod {
public static Setting players = new Setting(Mode.BOOLEAN, "Players", true);
public static Setting monsters = new Setting(Mode.BOOLEAN, "Monsters", true);
public static Setting neutrals = new Setting(Mode.BOOLEAN, "Neutrals", true);
public static Setting passive = new Setting(Mode.BOOLEAN, "Passive", true);
public static Setting items = new Setting(Mode.BOOLEAN, "Items", true);
public static Setting everything = new Setting(Mode.BOOLEAN, "Everything", false, "Highlight every entity");
public static Setting red = new Setting(Mode.INTEGER, "Red", 66, "RBG");
public static Setting green = new Setting(Mode.INTEGER, "Green", 245, "RBG");
public static Setting blue = new Setting(Mode.INTEGER, "Blue", 185, "RBG");
public static Setting alpha = new Setting(Mode.INTEGER, "Alpha", 255, "RBG");
public static Setting width = new Setting(Mode.DOUBLE, "Width", 1, "The width of the rendered lines");
public EntityESP() {
super(Group.RENDER, "EntityESP", "Highlight entities hitboxes");
}
@Override
public void onRenderWorld(float partialTicks) {
for (Entity entity : mc.world.loadedEntityList) {
if (isValid(entity)) {
RenderUtil.renderHitBox(entity, red.intValue() / 255.0f, green.intValue() / 255.0f, blue.intValue() / 255.0f, alpha.intValue() / 255.0f, (float)width.doubleValue(), partialTicks);
}
}
}
public static boolean isValid(Entity entity) {
if (entity.equals(mc.renderViewEntity)) {
return false;
}
if (everything.booleanValue()) {
return true;
}
if (players.booleanValue() && entity instanceof EntityPlayer) {
return true;
} else if (monsters.booleanValue() && EntityUtil.isHostileMob(entity)) {
return true;
} else if (neutrals.booleanValue() && EntityUtil.isNeutralMob(entity)) {
return true;
} else if (passive.booleanValue() && EntityUtil.isPassive(entity)) {
return true;
} else if (items.booleanValue() && entity instanceof EntityItem) {
return true;
}
return false;
}
}
| 412 | 0.538895 | 1 | 0.538895 | game-dev | MEDIA | 0.929738 | game-dev | 0.910008 | 1 | 0.910008 |
dream-young-soul/h5_mir | 2,703 | src/Logic/Entity/PropertySet.ts | /*
* 实体属性集合
* @author 后天
*/
module Entity
{
export class PropertySet
{
private m_ArrProp = [];
constructor()
{
}
public Clear():void
{
this.m_ArrProp = [];
}
public SetProperty(propType:Entity.enPropEntity,value):void
{
this.m_ArrProp[propType] = value;
}
public GetIntProperty(propType:Entity.enPropEntity):number
{
if(this.m_ArrProp[propType] == null)
{
return 0;
}
return parseInt(this.m_ArrProp[propType].toString() );
}
public GetProperty(propType:Entity.enPropEntity):any
{
if(this.m_ArrProp[propType] == null)
{
return 0;
}
return this.m_ArrProp[propType];
}
public GetPropertyToArray():any
{
let ret = [];
for(let i in this.m_ArrProp)
{
ret.push({id:i,value:this.m_ArrProp[i]});
}
return ret;
}
public ReadMultiProperty(nCount:number, pack:Net.Packet):void
{
for(let i:number = 0;i < nCount;i++)
{
let propId:number = pack.ReadUByte();
this.ReadProperty(propId, pack);
}
}
public ReadProperty(propId:number,pack:Net.Packet):void
{
let type:PropertyDataType = ActorProperties.GetDataType(propId);
switch(type)
{
case PropertyDataType.DOUBLE:
{
this.m_ArrProp[propId] = pack.ReadDouble();
break;
}
case PropertyDataType.FLOAT:
{
this.m_ArrProp[propId] = pack.ReadFloat();
break;
}
case PropertyDataType.INT:
{
this.m_ArrProp[propId] = pack.ReadInt32();
break;
}
case PropertyDataType.STRING:
{
this.m_ArrProp[propId] = pack.ReadCustomString();
break;
}
case PropertyDataType.UINT:
{
this.m_ArrProp[propId] = pack.ReadUInt32();
break;
}
default:
{
throw new Error("ReadProperty error normal type" + type.toString());
}
}
}
}
} | 412 | 0.823526 | 1 | 0.823526 | game-dev | MEDIA | 0.41543 | game-dev | 0.914727 | 1 | 0.914727 |
OGSR/OGSR-Engine | 5,585 | ogsr_engine/xrGame/alife_monster_patrol_path_manager.cpp | ////////////////////////////////////////////////////////////////////////////
// Module : alife_monster_patrol_path_manager.cpp
// Created : 01.11.2005
// Modified : 22.11.2005
// Author : Dmitriy Iassenev
// Description : ALife monster patrol path manager class
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "alife_monster_patrol_path_manager.h"
#include "xrServer_Objects_ALife_Monsters.h"
#include "ai_space.h"
#include "patrol_path_storage.h"
#include "patrol_path.h"
#include "patrol_point.h"
#include "patrol_path_manager_space.h"
#include "game_graph.h"
CALifeMonsterPatrolPathManager::CALifeMonsterPatrolPathManager(object_type* object)
{
VERIFY(object);
m_object = object;
m_path = 0;
m_actual = true;
m_completed = true;
m_current_vertex_index = u32(-1);
m_previous_vertex_index = u32(-1);
m_start_vertex_index = u32(-1);
start_type(PatrolPathManager::ePatrolStartTypeNearest);
route_type(PatrolPathManager::ePatrolRouteTypeContinue);
use_randomness(true);
}
void CALifeMonsterPatrolPathManager::path(const shared_str& path_name) { path(ai().patrol_paths().safe_path(path_name)); }
const CALifeMonsterPatrolPathManager::_GRAPH_ID& CALifeMonsterPatrolPathManager::target_game_vertex_id() const
{
return (path().vertex(m_current_vertex_index)->data().game_vertex_id());
}
const u32& CALifeMonsterPatrolPathManager::target_level_vertex_id() const { return (path().vertex(m_current_vertex_index)->data().level_vertex_id()); }
const Fvector& CALifeMonsterPatrolPathManager::target_position() const { return (path().vertex(m_current_vertex_index)->data().position()); }
void CALifeMonsterPatrolPathManager::select_nearest()
{
m_current_vertex_index = u32(-1);
Fvector global_position = ai().game_graph().vertex(object().m_tGraphID)->game_point();
float best_distance = flt_max;
CPatrolPath::const_vertex_iterator I = path().vertices().begin();
CPatrolPath::const_vertex_iterator E = path().vertices().end();
for (; I != E; ++I)
{
if ((*I).second->data().game_vertex_id() == object().m_tGraphID)
{
m_current_vertex_index = (*I).second->vertex_id();
break;
}
float distance = global_position.distance_to(ai().game_graph().vertex((*I).second->data().game_vertex_id())->game_point());
if (distance >= best_distance)
continue;
best_distance = distance;
m_current_vertex_index = (*I).second->vertex_id();
}
VERIFY(m_current_vertex_index < path().vertices().size());
}
void CALifeMonsterPatrolPathManager::actualize()
{
m_current_vertex_index = u32(-1);
m_previous_vertex_index = u32(-1);
m_actual = true;
m_completed = false;
switch (start_type())
{
case PatrolPathManager::ePatrolStartTypeFirst: {
m_current_vertex_index = 0;
break;
}
case PatrolPathManager::ePatrolStartTypeLast: {
m_current_vertex_index = path().vertices().size() - 1;
break;
}
case PatrolPathManager::ePatrolStartTypeNearest: {
select_nearest();
break;
}
case PatrolPathManager::ePatrolStartTypePoint: {
m_current_vertex_index = m_start_vertex_index;
break;
}
case PatrolPathManager::ePatrolStartTypeNext:
// we advisedly do not process this case since it is far-fetched
default: NODEFAULT;
};
VERIFY(path().vertices().size() > m_current_vertex_index);
}
bool CALifeMonsterPatrolPathManager::location_reached() const
{
if (object().m_tGraphID != target_game_vertex_id())
return (false);
if (object().m_tNodeID != target_level_vertex_id())
return (false);
return (true);
}
void CALifeMonsterPatrolPathManager::navigate()
{
const CPatrolPath::CVertex& vertex = *path().vertex(m_current_vertex_index);
typedef CPatrolPath::CVertex::EDGES EDGES;
EDGES::const_iterator I = vertex.edges().begin(), B = I;
EDGES::const_iterator E = vertex.edges().end();
u32 branching_factor = 0;
for (; I != E; ++I)
{
if (*I == m_previous_vertex_index)
continue;
++branching_factor;
}
if (!branching_factor)
{
switch (route_type())
{
case PatrolPathManager::ePatrolRouteTypeStop: {
VERIFY(!m_completed);
m_completed = true;
break;
};
case PatrolPathManager::ePatrolRouteTypeContinue: {
if (vertex.edges().empty())
{
VERIFY(!m_completed);
m_completed = true;
break;
}
VERIFY(vertex.edges().size() == 1);
VERIFY(vertex.edges().front().vertex_id() == m_previous_vertex_index);
std::swap(m_current_vertex_index, m_previous_vertex_index);
break;
};
default: NODEFAULT;
};
}
const u32 chosen = use_randomness() ? ::Random.randI(branching_factor) : 0;
u32 branch = 0;
for (I = B; I != E; ++I)
{
if (*I == m_previous_vertex_index)
continue;
if (chosen == branch)
break;
++branch;
}
VERIFY(I != E);
m_previous_vertex_index = m_current_vertex_index;
m_current_vertex_index = (*I).vertex_id();
}
void CALifeMonsterPatrolPathManager::update()
{
if (!m_path)
return;
if (completed())
return;
if (!actual())
actualize();
if (!location_reached())
return;
navigate();
}
| 412 | 0.967432 | 1 | 0.967432 | game-dev | MEDIA | 0.95068 | game-dev | 0.979925 | 1 | 0.979925 |
magefree/mage | 1,749 | Mage.Sets/src/mage/cards/w/Waterknot.java |
package mage.cards.w;
import java.util.UUID;
import mage.abilities.common.EntersBattlefieldTriggeredAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.common.AttachEffect;
import mage.abilities.effects.common.DontUntapInControllersUntapStepEnchantedEffect;
import mage.abilities.effects.common.TapEnchantedEffect;
import mage.abilities.keyword.EnchantAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Outcome;
import mage.constants.Zone;
import mage.target.TargetPermanent;
import mage.target.common.TargetCreaturePermanent;
/**
* @author Loki & L_J
*/
public final class Waterknot extends CardImpl {
public Waterknot(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{1}{U}{U}");
this.subtype.add(SubType.AURA);
// Enchant creature
TargetPermanent auraTarget = new TargetCreaturePermanent();
this.getSpellAbility().addTarget(auraTarget);
this.getSpellAbility().addEffect(new AttachEffect(Outcome.Detriment));
this.addAbility(new EnchantAbility(auraTarget));
// When Waterknot enters the battlefield, tap enchanted creature.
this.addAbility(new EntersBattlefieldTriggeredAbility(new TapEnchantedEffect()));
// Enchanted creature doesn't untap during its controller's untap step.
this.addAbility(new SimpleStaticAbility(new DontUntapInControllersUntapStepEnchantedEffect()));
}
private Waterknot(final Waterknot card) {
super(card);
}
@Override
public Waterknot copy() {
return new Waterknot(this);
}
}
| 412 | 0.943945 | 1 | 0.943945 | game-dev | MEDIA | 0.949886 | game-dev | 0.985248 | 1 | 0.985248 |
Secrets-of-Sosaria/World | 2,345 | Data/Scripts/Items/Houses/Decorations/DecoIngotDeed.cs | using System;
using Server;
using Server.Mobiles;
using Server.Network;
using Server.Multis;
using Server.Items;
namespace Server.Items
{
public class DecoStatueDeed : Item
{
public override string DefaultName
{
get { return "decoration ingot deed"; }
}
[Constructable]
public DecoStatueDeed() : base( 0x14F0 )
{
Weight = 1.0;
}
public DecoStatueDeed( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int)0 ); //version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
public override void OnDoubleClick( Mobile from )
{
int tempNumber = -1;
if ( !IsChildOf( from.Backpack ) )
{
from.SendLocalizedMessage( 1042001 ); // That must be in your pack for you to use it.
}
else
{
tempNumber = Utility.RandomMinMax(0,110);
switch ( Utility.RandomMinMax( 0, 19 ) )
{
case 0: from.AddToBackpack(new DecoSilverIngots() ); break;
case 1: from.AddToBackpack(new DecoSilverIngots2() ); break;
case 2: from.AddToBackpack(new DecoSilverIngots3() ); break;
case 3: from.AddToBackpack(new DecoSilverIngots4() ); break;
case 4: from.AddToBackpack(new DecoSilverIngot2() ); break;
case 5: from.AddToBackpack(new DecoSilverIngot() ); break;
case 6: from.AddToBackpack(new DecoGoldIngot() ); break;
case 7: from.AddToBackpack(new DecoGoldIngot2() ); break;
case 8: from.AddToBackpack(new DecoGoldIngots() ); break;
case 9: from.AddToBackpack(new DecoGoldIngots2() ); break;
case 10: from.AddToBackpack(new DecoGoldIngots3() ); break;
case 11: from.AddToBackpack(new DecoGoldIngots4() ); break;
case 12: from.AddToBackpack(new DecoIronIngot() ); break;
case 13: from.AddToBackpack(new DecoIronIngots2() ); break;
case 14: from.AddToBackpack(new DecoIronIngots() ); break;
case 15: from.AddToBackpack(new DecoIronIngots2() ); break;
case 16: from.AddToBackpack(new DecoIronIngots3() ); break;
case 17: from.AddToBackpack(new DecoIronIngots4() ); break;
case 18: from.AddToBackpack(new DecoIronIngots5() ); break;
case 19: from.AddToBackpack(new DecoIronIngots6() ); break;
}
this.Delete();
}
}
}
} | 412 | 0.885764 | 1 | 0.885764 | game-dev | MEDIA | 0.830248 | game-dev | 0.899166 | 1 | 0.899166 |
panaverse/learn-generative-ai | 1,092 | 02_python_crash_course/python_crash_course_book_code_with_typing/solution_files/chapter_13/ex_13_5_sideways_shooter_2/bullet.py | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""A class to manage bullets fired from the ship."""
def __init__(self, ss_game):
"""Create a bullet object at the ship's current position."""
super().__init__()
self.screen = ss_game.screen
self.settings = ss_game.settings
self.color = self.settings.bullet_color
# Create a bullet rect at (0, 0) and then set correct position.
self.rect = pygame.Rect(0, 0, self.settings.bullet_width,
self.settings.bullet_height)
self.rect.midright = ss_game.ship.rect.midright
# Store the bullet's position as a decimal value.
self.x = float(self.rect.x)
def update(self):
"""Move the bullet across the screen."""
# Update the decimal position of the bullet.
self.x += self.settings.bullet_speed
# Update the rect position.
self.rect.x = self.x
def draw_bullet(self):
"""Draw the bullet to the screen."""
pygame.draw.rect(self.screen, self.color, self.rect)
| 412 | 0.796451 | 1 | 0.796451 | game-dev | MEDIA | 0.77794 | game-dev | 0.789628 | 1 | 0.789628 |
Mikescher/AlephNote | 4,547 | Source/Plugins/EvernotePlugin/EDAM/NoteStore/RelatedQuery.cs | /**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
*/
using System;
using System.Text;
using AlephNote.Plugins.Evernote.Thrift.Protocol;
namespace AlephNote.Plugins.Evernote.EDAM.NoteStore
{
#if !SILVERLIGHT && !NETFX_CORE
[Serializable]
#endif
public partial class RelatedQuery : TBase
{
private string _noteGuid;
private string _plainText;
private NoteFilter _filter;
private string _referenceUri;
public string NoteGuid
{
get
{
return _noteGuid;
}
set
{
__isset.noteGuid = true;
this._noteGuid = value;
}
}
public string PlainText
{
get
{
return _plainText;
}
set
{
__isset.plainText = true;
this._plainText = value;
}
}
public NoteFilter Filter
{
get
{
return _filter;
}
set
{
__isset.filter = true;
this._filter = value;
}
}
public string ReferenceUri
{
get
{
return _referenceUri;
}
set
{
__isset.referenceUri = true;
this._referenceUri = value;
}
}
public Isset __isset;
#if !SILVERLIGHT && !NETFX_CORE
[Serializable]
#endif
public struct Isset {
public bool noteGuid;
public bool plainText;
public bool filter;
public bool referenceUri;
}
public RelatedQuery() {
}
public void Read (TProtocol iprot)
{
TField field;
iprot.ReadStructBegin();
while (true)
{
field = iprot.ReadFieldBegin();
if (field.Type == TType.Stop) {
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.String) {
NoteGuid = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 2:
if (field.Type == TType.String) {
PlainText = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 3:
if (field.Type == TType.Struct) {
Filter = new NoteFilter();
Filter.Read(iprot);
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 4:
if (field.Type == TType.String) {
ReferenceUri = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
default:
TProtocolUtil.Skip(iprot, field.Type);
break;
}
iprot.ReadFieldEnd();
}
iprot.ReadStructEnd();
}
public void Write(TProtocol oprot) {
TStruct struc = new TStruct("RelatedQuery");
oprot.WriteStructBegin(struc);
TField field = new TField();
if (NoteGuid != null && __isset.noteGuid) {
field.Name = "noteGuid";
field.Type = TType.String;
field.ID = 1;
oprot.WriteFieldBegin(field);
oprot.WriteString(NoteGuid);
oprot.WriteFieldEnd();
}
if (PlainText != null && __isset.plainText) {
field.Name = "plainText";
field.Type = TType.String;
field.ID = 2;
oprot.WriteFieldBegin(field);
oprot.WriteString(PlainText);
oprot.WriteFieldEnd();
}
if (Filter != null && __isset.filter) {
field.Name = "filter";
field.Type = TType.Struct;
field.ID = 3;
oprot.WriteFieldBegin(field);
Filter.Write(oprot);
oprot.WriteFieldEnd();
}
if (ReferenceUri != null && __isset.referenceUri) {
field.Name = "referenceUri";
field.Type = TType.String;
field.ID = 4;
oprot.WriteFieldBegin(field);
oprot.WriteString(ReferenceUri);
oprot.WriteFieldEnd();
}
oprot.WriteFieldStop();
oprot.WriteStructEnd();
}
public override string ToString() {
StringBuilder sb = new StringBuilder("RelatedQuery(");
sb.Append("NoteGuid: ");
sb.Append(NoteGuid);
sb.Append(",PlainText: ");
sb.Append(PlainText);
sb.Append(",Filter: ");
sb.Append(Filter== null ? "<null>" : Filter.ToString());
sb.Append(",ReferenceUri: ");
sb.Append(ReferenceUri);
sb.Append(")");
return sb.ToString();
}
}
}
| 412 | 0.748378 | 1 | 0.748378 | game-dev | MEDIA | 0.285206 | game-dev | 0.826067 | 1 | 0.826067 |
OpenRCT2/OpenRCT2 | 6,790 | src/openrct2/paint/track/gentle/MerryGoRound.cpp | /*****************************************************************************
* Copyright (c) 2014-2025 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#include "../../../GameState.h"
#include "../../../entity/EntityRegistry.h"
#include "../../../interface/Viewport.h"
#include "../../../ride/Ride.h"
#include "../../../ride/RideEntry.h"
#include "../../../ride/Track.h"
#include "../../../ride/TrackPaint.h"
#include "../../../ride/Vehicle.h"
#include "../../Paint.h"
#include "../../support/WoodenSupports.h"
#include "../../tile_element/Segment.h"
#include "../../track/Segment.h"
using namespace OpenRCT2;
static constexpr uint32_t kMerryGoRoundRiderOffsets[] = {
0, 32, 64, 96, 16, 48, 80, 112,
};
static constexpr uint16_t kMerryGoRoundBreakdownVibration[] = {
0, 1, 2, 3, 4, 3, 2, 1, 0, 0,
};
static void PaintRiders(
PaintSession& session, const Ride& ride, const RideObjectEntry& rideEntry, const Vehicle& vehicle, int32_t rotationOffset,
const CoordsXYZ& offset, const BoundBoxXYZ& bb)
{
if (session.DPI.zoom_level > ZoomLevel{ 0 })
return;
if (!(ride.lifecycleFlags & RIDE_LIFECYCLE_ON_TRACK))
return;
for (int32_t peep = 0; peep <= 14; peep += 2)
{
if (vehicle.num_peeps <= peep)
break;
auto imageOffset = (kMerryGoRoundRiderOffsets[peep / 2] + rotationOffset) % 128;
imageOffset -= 13;
if (imageOffset >= 68)
continue;
auto imageIndex = rideEntry.Cars[0].base_image_id + 32 + imageOffset;
auto imageId = ImageId(imageIndex, vehicle.peep_tshirt_colours[peep], vehicle.peep_tshirt_colours[peep + 1]);
PaintAddImageAsChild(session, imageId, offset, bb);
}
}
static void PaintCarousel(
PaintSession& session, const Ride& ride, uint8_t direction, int8_t xOffset, int8_t yOffset, uint16_t height,
ImageId stationColour)
{
height += 7;
auto rideEntry = ride.getRideEntry();
if (rideEntry == nullptr)
return;
auto vehicle = getGameState().entities.GetEntity<Vehicle>(ride.vehicles[0]);
if (ride.lifecycleFlags & RIDE_LIFECYCLE_ON_TRACK && vehicle != nullptr)
{
session.InteractionType = ViewportInteractionItem::entity;
session.CurrentlyDrawnEntity = vehicle;
if (ride.lifecycleFlags & (RIDE_LIFECYCLE_BREAKDOWN_PENDING | RIDE_LIFECYCLE_BROKEN_DOWN)
&& ride.breakdownReasonPending == BREAKDOWN_CONTROL_FAILURE && ride.breakdownSoundModifier >= 128)
{
height += kMerryGoRoundBreakdownVibration[(vehicle->current_time >> 1) & 7];
}
}
auto rotationOffset = 0;
if (vehicle != nullptr)
{
auto rotation = ((vehicle->Orientation >> 3) + session.CurrentRotation) << 5;
rotationOffset = (vehicle->flatRideAnimationFrame + rotation) % 128;
}
CoordsXYZ offset(xOffset, yOffset, height);
BoundBoxXYZ bb = { { xOffset + 16, yOffset + 16, height }, { 24, 24, 48 } };
auto imageTemplate = ImageId(0, ride.vehicleColours[0].Body, ride.vehicleColours[0].Trim);
if (stationColour != TrackStationColour)
{
imageTemplate = stationColour;
}
auto imageOffset = rotationOffset & 0x1F;
auto imageId = imageTemplate.WithIndex(rideEntry->Cars[0].base_image_id + imageOffset);
PaintAddImageAsParent(session, imageId, offset, bb);
if (vehicle != nullptr && vehicle->num_peeps > 0)
{
PaintRiders(session, ride, *rideEntry, *vehicle, rotationOffset, offset, bb);
}
session.CurrentlyDrawnEntity = nullptr;
session.InteractionType = ViewportInteractionItem::ride;
}
static void PaintMerryGoRound(
PaintSession& session, const Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height,
const TrackElement& trackElement, SupportType supportType)
{
trackSequence = kTrackMap3x3[direction][trackSequence];
int32_t edges = kEdges3x3[trackSequence];
WoodenASupportsPaintSetupRotated(
session, WoodenSupportType::truss, WoodenSupportSubType::neSw, direction, height,
GetStationColourScheme(session, trackElement));
const StationObject* stationObject = ride.getStationObject();
TrackPaintUtilPaintFloor(session, edges, session.TrackColours, height, kFloorSpritesCork, stationObject);
TrackPaintUtilPaintFences(
session, edges, session.MapPosition, trackElement, ride, GetStationColourScheme(session, trackElement), height,
kFenceSpritesRope, session.CurrentRotation);
auto stationColour = GetStationColourScheme(session, trackElement);
switch (trackSequence)
{
case 1:
PaintCarousel(session, ride, direction, 32, 32, height, stationColour);
break;
case 3:
PaintCarousel(session, ride, direction, 32, -32, height, stationColour);
break;
case 5:
PaintCarousel(session, ride, direction, 0, -32, height, stationColour);
break;
case 6:
PaintCarousel(session, ride, direction, -32, 32, height, stationColour);
break;
case 7:
PaintCarousel(session, ride, direction, -32, -32, height, stationColour);
break;
case 8:
PaintCarousel(session, ride, direction, -32, 0, height, stationColour);
break;
}
int32_t cornerSegments = 0;
switch (trackSequence)
{
case 1:
// top
cornerSegments = EnumsToFlags(PaintSegment::top, PaintSegment::topLeft, PaintSegment::topRight);
break;
case 3:
// right
cornerSegments = EnumsToFlags(PaintSegment::topRight, PaintSegment::right, PaintSegment::bottomRight);
break;
case 6:
// left
cornerSegments = EnumsToFlags(PaintSegment::topLeft, PaintSegment::left, PaintSegment::bottomLeft);
break;
case 7:
// bottom
cornerSegments = EnumsToFlags(PaintSegment::bottomLeft, PaintSegment::bottom, PaintSegment::bottomRight);
break;
}
PaintUtilSetSegmentSupportHeight(session, cornerSegments, height + 2, 0x20);
PaintUtilSetSegmentSupportHeight(session, kSegmentsAll & ~cornerSegments, 0xFFFF, 0);
PaintUtilSetGeneralSupportHeight(session, height + 64);
}
TrackPaintFunction GetTrackPaintFunctionMerryGoRound(OpenRCT2::TrackElemType trackType)
{
if (trackType != TrackElemType::FlatTrack3x3)
{
return TrackPaintFunctionDummy;
}
return PaintMerryGoRound;
}
| 412 | 0.882604 | 1 | 0.882604 | game-dev | MEDIA | 0.753782 | game-dev | 0.961883 | 1 | 0.961883 |
ProjectIgnis/CardScripts | 1,254 | unofficial/c100100060.lua | --Sp-サルベージ
local s,id=GetID()
function s.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(s.con)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
end
function s.con(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFieldCard(tp,LOCATION_FZONE,0)
return tc and tc:GetCounter(0x91)>1
end
function s.filter(c)
local atk=c:GetAttack()
return atk>=0 and atk<=1500 and c:IsAttribute(ATTRIBUTE_WATER) and c:IsAbleToHand()
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:GetControler()==tp and chkc:GetLocation()==LOCATION_GRAVE and s.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(s.filter,tp,LOCATION_GRAVE,0,2,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,s.filter,tp,LOCATION_GRAVE,0,2,2,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,2,0,0)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local sg=g:Filter(Card.IsRelateToEffect,nil,e)
if #sg>0 then
Duel.SendtoHand(sg,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,sg)
end
end | 412 | 0.93526 | 1 | 0.93526 | game-dev | MEDIA | 0.98371 | game-dev | 0.960021 | 1 | 0.960021 |
yigao/NFShmXFrame | 3,447 | game/MMO/NFLogicComm/DescStore/FestivalMuban_rptaskDesc.cpp | #include "FestivalMuban_rptaskDesc.h"
#include "NFComm/NFPluginModule/NFCheck.h"
FestivalMuban_rptaskDesc::FestivalMuban_rptaskDesc()
{
if (EN_OBJ_MODE_INIT == NFShmMgr::Instance()->GetCreateMode()) {
CreateInit();
}
else {
ResumeInit();
}
}
FestivalMuban_rptaskDesc::~FestivalMuban_rptaskDesc()
{
}
int FestivalMuban_rptaskDesc::CreateInit()
{
return 0;
}
int FestivalMuban_rptaskDesc::ResumeInit()
{
return 0;
}
int FestivalMuban_rptaskDesc::Load(NFResDB *pDB)
{
NFLogTrace(NF_LOG_SYSTEMLOG, 0, "--begin--");
CHECK_EXPR(pDB != NULL, -1, "pDB == NULL");
NFLogTrace(NF_LOG_SYSTEMLOG, 0, "FestivalMuban_rptaskDesc::Load() strFileName = {}", GetFileName());
proto_ff::Sheet_FestivalMuban_rptask table;
NFResTable* pResTable = pDB->GetTable(GetFileName());
CHECK_EXPR(pResTable != NULL, -1, "pTable == NULL, GetTable:{} Error", GetFileName());
int iRet = 0;
iRet = pResTable->FindAllRecord(GetDBName(), &table);
CHECK_EXPR(iRet == 0, -1, "FindAllRecord Error:{}", GetFileName());
//NFLogTrace(NF_LOG_SYSTEMLOG, 0, "{}", table.Utf8DebugString());
if ((table.e_festivalmuban_rptask_list_size() < 0) || (table.e_festivalmuban_rptask_list_size() > (int)(m_astDescMap.max_size())))
{
NFLogError(NF_LOG_SYSTEMLOG, 0, "Invalid TotalNum:{}", table.e_festivalmuban_rptask_list_size());
return -2;
}
m_minId = INVALID_ID;
for (int i = 0; i < (int)table.e_festivalmuban_rptask_list_size(); i++)
{
const proto_ff::E_FestivalMuban_rptask& desc = table.e_festivalmuban_rptask_list(i);
if (desc.has_m_id() == false && desc.ByteSize() == 0)
{
NFLogError(NF_LOG_SYSTEMLOG, 0, "the desc no value, {}", desc.Utf8DebugString());
continue;
}
if (m_minId == INVALID_ID)
{
m_minId = desc.m_id();
}
else
{
if (desc.m_id() < m_minId)
{
m_minId = desc.m_id();
}
}
//NFLogTrace(NF_LOG_SYSTEMLOG, 0, "{}", desc.Utf8DebugString());
if (m_astDescMap.find(desc.m_id()) != m_astDescMap.end())
{
if (IsReloading())
{
auto pDesc = GetDesc(desc.m_id());
NF_ASSERT_MSG(pDesc, "the desc:{} Reload, GetDesc Failed!, id:{}", GetClassName(), desc.m_id());
pDesc->read_from_pbmsg(desc);
}
else
{
NFLogError(NF_LOG_SYSTEMLOG, 0, "the desc:{} id:{} exist", GetClassName(), desc.m_id());
}
continue;
}
CHECK_EXPR_ASSERT(m_astDescMap.size() < m_astDescMap.max_size(), -1, "m_astDescMap Space Not Enough");
auto pDesc = &m_astDescMap[desc.m_id()];
CHECK_EXPR_ASSERT(pDesc, -1, "m_astDescMap Insert Failed desc.id:{}", desc.m_id());
pDesc->read_from_pbmsg(desc);
CHECK_EXPR_ASSERT(GetDesc(desc.m_id()) == pDesc, -1, "GetDesc != pDesc, id:{}", desc.m_id());
}
for(int i = 0; i < (int)m_astDescIndex.size(); i++)
{
m_astDescIndex[i] = INVALID_ID;
}
for(auto iter = m_astDescMap.begin(); iter != m_astDescMap.end(); iter++)
{
int64_t index = (int64_t)iter->first - (int64_t)m_minId;
if (index >= 0 && index < (int64_t)m_astDescIndex.size())
{
m_astDescIndex[index] = iter.m_curNode->m_self;
CHECK_EXPR_ASSERT(iter == m_astDescMap.get_iterator(m_astDescIndex[index]), -1, "index error");
CHECK_EXPR_ASSERT(GetDesc(iter->first) == &iter->second, -1, "GetDesc != iter->second, id:{}", iter->first);
}
}
NFLogTrace(NF_LOG_SYSTEMLOG, 0, "load {}, num={}", iRet, table.e_festivalmuban_rptask_list_size());
NFLogTrace(NF_LOG_SYSTEMLOG, 0, "--end--");
return 0;
}
int FestivalMuban_rptaskDesc::CheckWhenAllDataLoaded()
{
return 0;
}
| 412 | 0.966923 | 1 | 0.966923 | game-dev | MEDIA | 0.667675 | game-dev | 0.987815 | 1 | 0.987815 |
madhur/dotfiles | 12,220 | home/madhur/.config/awesome/bling/module/scratchpad.lua | local awful = require("awful")
local gears = require("gears")
local naughty = require("naughty")
local helpers = require(tostring(...):match(".*bling") .. ".helpers")
local capi = { awesome = awesome, client = client }
local ruled = capi.awesome.version ~= "v4.3" and require("ruled") or nil
local pairs = pairs
local Scratchpad = { mt = {} }
--- Called when the turn off animation has ended
local function on_animate_turn_off_end(self, tag)
-- When toggling off a scratchpad that's present on multiple tags
-- depsite still being unminizmied on the other tags it will become invisible
-- as it's position could be outside the screen from the animation
self.client:geometry({
x = self.geometry.x + self.client.screen.geometry.x,
y = self.geometry.y + self.client.screen.geometry.y,
width = self.geometry.width,
height = self.geometry.height,
})
helpers.client.turn_off(self.client, tag)
self.turning_off = false
self:emit_signal("turn_off", self.client)
end
--- The turn off animation
local function animate_turn_off(self, anim, axis)
self.screen_on_toggled_scratchpad = self.client.screen
self.tag_on_toggled_scratchpad = self.screen_on_toggled_scratchpad.selected_tag
if self.client.floating == false then
-- Save the client geometry before floating it
local non_floating_x = self.client.x
local non_floating_y = self.client.y
local non_floating_width = self.client.width
local non_floating_height = self.client.height
-- Can't animate non floating clients
self.client.floating = true
-- Set the client geometry back to what it was before floating it
self.client:geometry({
x = non_floating_x,
y = non_floating_y,
width = non_floating_width,
height = non_floating_height,
})
end
if axis == "x" then
anim.pos = self.client.x
else
anim.pos = self.client.y
end
anim:set(anim:initial())
end
-- Handles changing tag mid animation
local function abort_if_tag_was_switched(self)
-- Check for the following scenerio:
-- Toggle on scratchpad at tag 1
-- Toggle on scratchpad at tag 2
-- Toggle off scratchpad at tag 1
-- Switch to tag 2
-- Outcome: The client will remain on tag 1 and will instead be removed from tag 2
if (self.turning_off) and (self.screen_on_toggled_scratchpad and
self.screen_on_toggled_scratchpad.selected_tag) ~= self.tag_on_toggled_scratchpad
then
if self.rubato.x then
self.rubato.x:abort()
end
if self.rubato.y then
self.rubato.y:abort()
end
on_animate_turn_off_end(self, self.tag_on_toggled_scratchpad)
self.screen_on_toggled_scratchpad.selected_tag = nil
self.tag_on_toggled_scratchpad = nil
end
end
--- The turn on animation
local function animate_turn_on(self, anim, axis)
-- Check for the following scenerio:
-- Toggle on scratchpad at tag 1
-- Toggle on scratchpad at tag 2
-- The animation will instantly end
-- as the timer pos is already at the on position
-- from toggling on the scratchpad at tag 1
if axis == "x" and anim.pos == self.geometry.x then
anim.pos = anim:initial()
else
if anim.pos == self.geometry.y then
anim.pos = anim:initial()
end
end
if axis == "x" then
anim:set(self.geometry.x)
else
anim:set(self.geometry.y)
end
end
--- Creates a new scratchpad object based on the argument
--
-- @param args A table of possible arguments
-- @return The new scratchpad object
function Scratchpad:new(args)
args = args or {}
if args.awestore then
naughty.notify({
title = "Bling Error",
text = "Awestore is no longer supported! Please take a look at the scratchpad documentation and use rubato for animations instead.",
})
end
args.rubato = args.rubato or {}
local ret = gears.object{}
gears.table.crush(ret, Scratchpad)
gears.table.crush(ret, args)
if ret.rubato.x then
ret.rubato.x:subscribe(function(pos)
if ret.client and ret.client.valid then
ret.client.x = pos
end
abort_if_tag_was_switched(ret)
end)
ret.rubato.x.ended:subscribe(function()
if ((ret.rubato.y and ret.rubato.y.state == false) or (ret.rubato.y == nil)) and ret.turning_off == true then
on_animate_turn_off_end(ret)
end
end)
end
if ret.rubato.y then
ret.rubato.y:subscribe(function(pos)
if ret.client and ret.client.valid then
ret.client.y = pos
end
abort_if_tag_was_switched(ret)
end)
ret.rubato.y.ended:subscribe(function()
if ((ret.rubato.x and ret.rubato.x.state == false) or (ret.rubato.x == nil)) and ret.turning_off == true then
on_animate_turn_off_end(ret)
end
end)
end
return ret
end
--- Find all clients that satisfy the the rule
--
-- @return A list of all clients that satisfy the rule
function Scratchpad:find()
return helpers.client.find(self.rule)
end
--- Applies the objects scratchpad properties to a given client
--
-- @param c A client to which to apply the properties
function Scratchpad:apply(c)
if not c or not c.valid then
return
end
c.floating = self.floating
c.sticky = self.sticky
c.fullscreen = false
c.maximized = false
c:geometry({
x = self.geometry.x + awful.screen.focused().geometry.x,
y = self.geometry.y + awful.screen.focused().geometry.y,
width = self.geometry.width,
height = self.geometry.height,
})
if self.autoclose then
c:connect_signal("unfocus", function(c1)
c1.sticky = false -- client won't turn off if sticky
helpers.client.turn_off(c1)
end)
end
end
--- Turns the scratchpad on
function Scratchpad:turn_on()
self.client = self:find()[1]
local anim_x = self.rubato.x
local anim_y = self.rubato.y
local in_anim = false
if (anim_x and anim_x.state == true) or (anim_y and anim_y.state == true) then
in_anim = true
end
if self.client and not in_anim and self.client.first_tag and self.client.first_tag.selected then
self.client:raise()
capi.client.focus = self.client
return
end
if self.client and not in_anim then
-- if a client was found, turn it on
if self.reapply then
self:apply(self.client)
end
-- c.sticky was set to false in turn_off so it has to be reapplied anyway
self.client.sticky = self.sticky
if anim_x then
animate_turn_on(self, anim_x, "x")
end
if anim_y then
animate_turn_on(self, anim_y, "y")
end
helpers.client.turn_on(self.client)
self:emit_signal("turn_on", self.client)
return
end
if not self.client then
-- if no client was found, spawn one, find the corresponding window,
-- apply the properties only once (until the next closing)
local pid = awful.spawn.with_shell(self.command)
if capi.awesome.version ~= "v4.3" then
ruled.client.append_rule({
id = "scratchpad",
rule = self.rule,
properties = {
-- If a scratchpad is opened it should spawn at the current tag
-- the same way it will behave if the client was already open
tag = awful.screen.focused().selected_tag,
switch_to_tags = false,
-- Hide the client until the gemoetry rules are applied
hidden = true,
minimized = true,
},
callback = function(c)
-- For a reason I can't quite get the gemotery rules will fail to apply unless we use this timer
gears.timer({
timeout = 0.15,
autostart = true,
single_shot = true,
callback = function()
self.client = c
self:apply(c)
c.hidden = false
c.minimized = false
-- Some clients fail to gain focus
c:activate({})
if anim_x then
animate_turn_on(self, anim_x, "x")
end
if anim_y then
animate_turn_on(self, anim_y, "y")
end
self:emit_signal("inital_apply", c)
-- Discord spawns 2 windows, so keep the rule until the 2nd window shows
if c.name ~= "Discord Updater" then
ruled.client.remove_rule("scratchpad")
end
-- In a case Discord is killed before the second window spawns
c:connect_signal("request::unmanage", function()
ruled.client.remove_rule("scratchpad")
end)
end,
})
end,
})
else
local function inital_apply(c1)
if helpers.client.is_child_of(c1, pid) then
self.client = c1
self:apply(c1)
if anim_x then
animate_turn_on(self, anim_x, "x")
end
if anim_y then
animate_turn_on(self, anim_y, "y")
end
self:emit_signal("inital_apply", c1)
client.disconnect_signal("manage", inital_apply)
end
end
client.connect_signal("manage", inital_apply)
end
end
end
--- Turns the scratchpad off
function Scratchpad:turn_off()
self.client = self:find()[1]
-- Get the tweens
local anim_x = self.rubato.x
local anim_y = self.rubato.y
local in_anim = false
if (anim_x and anim_x.state == true) or (anim_y and anim_y.state == true) then
in_anim = true
end
if self.client and not in_anim then
if anim_x then
self.turning_off = true
animate_turn_off(self, anim_x, "x")
end
if anim_y then
self.turning_off = true
animate_turn_off(self, anim_y, "y")
end
if not anim_x and not anim_y then
helpers.client.turn_off(self.client)
self:emit_signal("turn_off", self.client)
end
end
end
--- Turns the scratchpad off if it is focused otherwise it raises the scratchpad
function Scratchpad:toggle()
local is_turn_off = false
local c = self:find()[1]
if self.dont_focus_before_close then
if c then
if c.sticky and #c:tags() > 0 then
is_turn_off = true
else
local current_tag = c.screen.selected_tag
for k, tag in pairs(c:tags()) do
if tag == current_tag then
is_turn_off = true
break
else
is_turn_off = false
end
end
end
end
else
is_turn_off = capi.client.focus
and awful.rules.match(capi.client.focus, self.rule)
end
if is_turn_off then
self:turn_off()
else
self:turn_on()
end
end
--- Make the module callable without putting a `:new` at the end of it
--
-- @param args A table of possible arguments
-- @return The new scratchpad object
function Scratchpad.mt:__call(...)
return Scratchpad:new(...)
end
return setmetatable(Scratchpad, Scratchpad.mt)
| 412 | 0.927908 | 1 | 0.927908 | game-dev | MEDIA | 0.655689 | game-dev,graphics-rendering | 0.96568 | 1 | 0.96568 |
raven2cz/dotfiles | 45,488 | .config/awesome/machina/methods.lua |
--------------------------------------------------------- dependencies -- ;
local naughty = require('naughty')
local gears = require("gears")
local awful = require("awful")
local beautiful = require('beautiful')
local grect = gears.geometry.rectangle
local tabs = require("machina.tabs")
local geoms = require("machina.geoms")
local helpers = require("machina.helpers")
local get_client_ix = helpers.get_client_ix
local getlowest = helpers.getlowest
local compare = helpers.compare
local tablelength = helpers.tablelength
local set_contains = helpers.set_contains
local clear_tabbar = helpers.clear_tabbar
---------------------------------------------------------------- locals -- ;
local global_client_table = {}
local global_widget_table = {}
function double_click_event_handler(double_click_event)
if double_click_timer then
double_click_timer:stop()
double_click_timer = nil
double_click_event()
return
end
beautiful.layout_machi = machi.get_icon()
double_click_timer = gears.timer.start_new(0.20, function()
double_click_timer = nil
return false
end)
end
function get_global_clients()
return global_client_table
end
function update_global_clients(c)
global_client_table[c.window] = c
end
----------------------------------------------------- reset_client_meta -- ;
local function reset_client_meta(c)
c.maximized = false
c.maximized_horizontal = false
c.maximized_vertical = false
c.direction = nil
return c
end
--------------------------------------------------- reset_all_clients() -- ;
local function reset_all_clients(s)
local s = s or awful.screen.focused()
for i,c in pairs(s.clients) do
reset_client_meta(c)
end
end
---------------------------------------------------------- set_region() -- ;
local function set_region(region, c)
local c = c or client.focus or nil
if c then
c.region = region end
end
------------------------------------------ get_visible_floating_clients -- ;
local function get_all_floating_clients(s)
local s = s or awful.screen.focused(s)
local les_visibles = {}
for i,p in pairs(s.all_clients) do
if p.floating then
les_visibles[#les_visibles+1] = p
end
end
return les_visibles
end
local function get_visible_floating_clients(s)
local s = s or awful.screen.focused(s)
local les_visibles = {}
for i,p in pairs(s.all_clients) do
if p.floating and (p.always_on or p.bypass) and p:isvisible() then
les_visibles[#les_visibles+1] = p
end
end
return les_visibles
end
---------------------------------------------------- get_space_around() -- ;
local function get_space_around(c)
if not c then return nil end
local c = c or nil
local s = awful.screen.focused()
local space_around = {
left=c.x,
right=s.workarea.width - (c.x + c.width),
top=s.workarea.height - (c.y),
bottom=s.workarea.height - (c.y + c.height),
}
return space_around
end
-------------------------------------------------------- align_floats() -- ;
local function align_floats(direction)
return function (c)
local s = s or awful.screen.focused()
local c = client.focus or nil
local direction = direction or "right"
local space_around = get_space_around(c)
local cs = get_all_floating_clients(s)
if not c then return end
--|flow control
if space_around.right < 300
and space_around.left < 300 then
return
end --|flow control
for i,p in pairs(cs) do
if p.window == c.window then goto next end
--|if c itself if it is actually floating
if space_around.right < 300 and direction == "right" then
direction = "left"
end
if space_around.left < 300 and direction == "left" then
direction = "right"
end --|flow control, nothing to do
if direction == "right" then
if (p.width) > space_around.right then
p.width = space_around.right
end
--|resize if necessary
p:geometry({x=c.x+c.width, y=c.y})
--|place x on the right
end
if direction == "left" then
if p.width > space_around.left then
p.width = space_around.left
end
--|resize if necessary
p:geometry({x=space_around.left - p.width, y=c.y})
--|place x on the left
end
if direction == "left" then direction = "right" end
if direction == "right" then direction = "left" end
p.hidden = false
p:raise()
-- p:emit_signal("request::activate")
--|bring float up
awful.placement.no_offscreen(p)
--|ensure everything is visible
::next::
end
client.focus = c
--|keep focus at the originating client
end
end
--|this will spread out floating clients to the left or
--|right of the focused client, can refactor most of this later.
--|perhaps it is better to limit this to visible floats only.
--|perhaps it would be better to keep the position and geometry
--|of the floats prior to aligning them, so that they can appear
--|where they used to be later.
------------------------------------------------------------- go_edge() -- ;
local function go_edge(direction, regions, current_box)
test_box = true
edge_pos = nil
while test_box do
test_box = grect.get_in_direction(direction, regions, current_box)
if test_box then
current_box = regions[test_box]
edge_pos = test_box
end
end
return edge_pos
end --|
--|figures out the beginning of each row on the layout.
----------------------------------------------------------- always_on() -- ;
local function toggle_always_on()
always_on = nil or client.focus.always_on
client.focus.always_on = not always_on
end
--------------------------------------------------------- screen_info() -- ;
local function screen_info(s)
local s = s or awful.screen.focused()
local focused_screen = s or nil
local workarea = s.workarea or nil
local selected_tag = s.selected_tag or nil
local layout = awful.layout.get(s) or nil
local focused_client = client.focus or nil
return focused_screen,
workarea,
selected_tag,
layout,
focused_client
end
---------------------------------------------------------- get_region() -- ;
local function get_region(region_ix, s)
local s = s or awful.screen.focused()
local focused_screen,
workarea,
selected_tag,
layout,
focused_client = screen_info(s)
local machi_fn = nil
local machi_data = nil
local machi_regions = nil
if layout.machi_get_regions then
machi_fn = layout.machi_get_regions
machi_data = machi_fn(workarea, selected_tag)
machi_regions = machi_data
end --|version 1
if layout.machi_get_instance_data then
machi_fn = layout.machi_get_instance_data
machi_geom = layout.machi_set_geometry
machi_data = {machi_fn(screen[focused_screen], selected_tag)}
machi_regions = machi_data[3]
for i=#machi_regions,1,-1 do
if machi_regions[i].habitable == false then
table.remove(machi_regions, i)
end
end --|remove unhabitable regions
table.sort(
machi_regions,
function (a1, a2)
return a1.id > a2.id
end
) --|v2 returns unordered region list and needs sorting.
end --|version 2/NG
return machi_regions[region_ix]
end
--------------------------------------------------------- get_regions() -- ;
local function get_regions(s)
local s = s or awful.screen.focused()
local focused_screen,
workarea,
selected_tag,
layout,
focused_client = screen_info(s)
local machi_fn = nil
local machi_data = nil
local machi_regions = nil
if layout.machi_get_regions then
machi_fn = layout.machi_get_regions
machi_data = machi_fn(workarea, selected_tag)
machi_regions = machi_data
end --|version 1
if layout.machi_get_instance_data then
machi_fn = layout.machi_get_instance_data
machi_geom = layout.machi_set_geometry
machi_data = {machi_fn(screen[focused_screen], selected_tag)}
machi_regions = machi_data[3]
for i=#machi_regions,1,-1 do
if machi_regions[i].habitable == false then
table.remove(machi_regions, i)
end
end --|remove unhabitable regions
table.sort(
machi_regions,
function (a1, a2)
return a1.id > a2.id
end
) --|v2 returns unordered region list and needs sorting.
end --|version 2/NG
return machi_regions, machi_fn
end
------------------------------------------------------- get_client_info -- ;
local function get_client_info(c)
local c = c or client.focus or nil
local s = s or c.screen or nil
local source_client = c
local active_region = nil
local outofboundary = nil
local proximity = {}
if not source_client then return {} end
--|flow control
if source_client.x < 0 or source_client.y < 0
then outofboundary = true
end --| negative coordinates always mean out of boundary
local regions = get_regions(s)
--|get regions on the screen
if not regions then return {} end
--|flow control
for i, a in ipairs(regions) do
local px = a.x - source_client.x
local py = a.y - source_client.y
if px == 0 then px = 1 end
if py == 0 then py = 1 end
proximity[i] = {
index = i,
v = math.abs(px * py)
} --│keep track of proximity in case nothing matches in
--│this block.
end --│figures out focused client's region under normal
--│circumstances.
if not active_region then
table.sort(proximity, compare) --| sort to get the smallest area
active_region = proximity[1].index --| first item should be the right choice
if source_client.floating then
if regions[active_region].width - source_client.width ~= 0
or regions[active_region].height - source_client.height ~= 0
then
outofboundary = true
end
end --|when client is not the same size as the located
--|region, we should still consider this as out of
--|boundary
end --|user is probably executing get_active_regions on a
--|floating window.
if not active_region then
active_region = 1
end --|at this point, we are out of options, set the index
--|to one and hope for the best.
-- refactor
if active_region and source_client.width > regions[active_region].width then
outofboundary = true
end --|machi sometimes could auto expand the client, consider
--|that as out of boundary.
if active_region and source_client.height > regions[active_region].height then
outofboundary = true
end --|machi sometimes could auto expand the client, consider
--|that as out of boundary.
-- refactor
active_region_geom = {
width=regions[active_region].width-regions[active_region].width/2,
height=regions[active_region].height-regions[active_region].height/2
}
return {
active_region = active_region,
active_region_geom = active_region_geom,
regions = regions,
outofboundary = outofboundary,
tags = c:tags()
}
end
------------------------------------------------------------- move_to() -- ;
local function move_to(location)
return function()
local c = client.focus or nil
if not c then return end
--▨ flow control
local c = reset_client_meta(client.focus)
local ci = get_client_info(c)
local useless_gap = nil
local regions = get_regions()
local edges = {x={},y={}}
local is = {
region=ci.active_region,
region_geom=ci.active_region_geom
}
for i,region in ipairs(regions) do
edges.x[region.x] = region.x + region.width
edges.y[region.y] = region.y + region.height
end
useless_gap = getlowest(edges.x)
if client.focus.floating then
client.focus:geometry(geoms[location](useless_gap))
end
if not client.focus.floating then
-- todo: set actual destination region geometry
-- this is not okay and buggy
-- or at least set it up to use directional shifting
-- to match left, right, center
local tobe_geom = geoms[location](useless_gap)
tobe_geom.width = 300
tobe_geom.height = 600
local tobe = {
region=get_client_info(client.focus).active_region,
}
client.focus:geometry(tobe_geom)
resize_region_to_index(is.region, is.region_geom, true)
draw_tabbar(is.region)
gears.timer.delayed_call(function ()
client.focus.region = tobe.region
draw_tabbar(tobe.region)
end)
end --| redraw tabs and update meta
return
end
end
----------------------------------------- focus_by_direction(direction) -- ;
local function focus_by_direction(direction)
return function()
if not client.focus then return false end
awful.client.focus.global_bydirection(direction, nil,true)
client.focus:raise()
end
end
----------------------------------------------- get_clients_in_region() -- ;
local function get_punched_clients(region_ix, s)
local s = s or awful.screen.focused()
local active_region = region_ix or nil
local region = get_region(region_ix, s)
local region_clients = {}
if #region_clients == 0 then
for i, w in ipairs(s.clients) do
if not w.floating then
if w.region == region_ix then
region_clients[#region_clients + 1] = w
end
end
end --|try to get clients based on simple coordinates
end
return region_clients
end --|try to get clients in a region using three different
--|algorithms.
local function get_clients_in_region(region_ix, c, s)
local c = c or client.focus or nil
local s = s or c.screen or awful.screen.focused()
local source_client = c or client.focus or nil
local source_screen = s or (source_client and source_client.screen)
local active_region = region_ix or nil
local regions = get_regions(s)
local region_clients = {}
if not active_region then
for i, a in ipairs(regions) do
if a.x <= source_client.x and source_client.x < a.x + a.width and
a.y <= source_client.y and source_client.y < a.y + a.height
then
active_region = i
end
end
end --|if no region index was provided, find the
--|region of the focused_client.
if not active_region then
return
end
if #region_clients == 0 then
for i, w in ipairs(s.clients) do
if not (w.floating) then
if (
math.abs(regions[active_region].x - w.x) <= 5 and
math.abs(regions[active_region].y - w.y) <= 5
)
-- or
-- (
-- regions[active_region].x ~= w.x and
-- w.region == region_ix
-- ) --|handle resizing left expanded regions
then
region_clients[#region_clients + 1] = w
w.region = region_ix
--|this basically will fix any inconsistency
--|along the way.
end
end
end --|try to get clients based on simple coordinates
end
-- if #region_clients == 0 then
-- for i, cc in pairs(s.clients) do
-- if cc.region == active_region
-- and regions[active_region].x == cc.x
-- and regions[active_region].y == cc.y
-- then
-- region_clients[#region_clients + 1] = cc
-- end
-- end
-- end --| this logic compares c.region to global client index.
-- --| if we somehow fail to update c.region somewhere
-- --| shuffle shortcuts won't work with this one.
-- if #region_clients == 0 then
-- for _, cc in ipairs(s.clients) do
-- if not (cc.floating) then
-- if regions[active_region].x <= cc.x + cc.width + cc.border_width * 2
-- and cc.x <= (regions[active_region].x + regions[active_region].width)
-- and regions[active_region].y <= (cc.y + cc.height + cc.border_width * 2)
-- and cc.y <= (regions[active_region].y + regions[active_region].height)
-- then
-- region_clients[#region_clients + 1] = cc
-- end
-- end
-- end
-- end --|this logic works with coordinates more throughly but
-- --|it also causes issues with overflowing
-- --|(expanded) clients.
return region_clients
end --|try to get clients in a region using three different
--|algorithms.
----------------------------------------------------- expand_horizontal -- ;
local function expand_horizontal(direction)
return function ()
local c = client.focus
local geom = nil
if c.maximized_horizontal then
c.maximized_horizontal = false
end --|reset toggle maximized state
if c.direction == direction then
c.direction = nil
c.maximized_horizontal = false
c.maximized_vertical = false
if not c.floating then
resize_region_to_index(c.region, true, true)
draw_tabbar(c.region)
gears.timer.weak_start_new(0.1,function ()
client_under_mouse = mouse.current_client
if client_under_mouse then
client.focus = mouse.current_client
end
end) --|when toggling leave the focus
--|to the client under the pointer
end
return
end --|reset toggle when sending the same
--|shortcut consequitively.
local stuff = get_client_info()
local target = grect.get_in_direction(direction, stuff.regions, client.focus:geometry())
if not target and direction ~= "center" then return end -- flow control
--▨▨▨
if direction == "right" then
tobe = {
x=c.x,
width=math.abs(stuff.regions[target].x + stuff.regions[target].width - c.x - 4),
height=c.height,
y=c.y
}
c.direction = direction
c.maximized_horizontal = true
c.maximixed_vertical = false
gears.timer.delayed_call(function (c)
c:geometry(tobe)
resize_region_to_client(c, {horizontal=true,vertical=false,direction=direction})
end,c)
return
end
--▨▨▨
if direction == "left" then
tobe = {
x=stuff.regions[target].x,
width=c.x + c.width - stuff.regions[target].x,
height=c.height,
y=c.y
}
c.direction = direction
c.maximized_horizontal = true
c.maximixed_vertical = false
gears.timer.delayed_call(function (c)
c:geometry(tobe)
resize_region_to_client(c, {horizontal=true,vertical=false,direction=direction})
end,c)
return
end
--▨▨▨
if direction == "center" then
c.maximized = false
c.maximixed_vertical = false
fixedchoice = geoms.clients[c.class] or nil
if c.floating then
c.maximized_horizontal = false
geom = geoms.crt43()
end
if not c.floating then
c.direction = "center"
c.maximized_horizontal = true
geom = geoms.p1080()
end
if fixedchoice and not c.floating then
c.direction = "center"
c.maximized_horizontal = true
geom = fixedchoice()
end
c:geometry(geom)
awful.placement.centered(c)
client.focus = nil
--|allow micky to move the mouse
gears.timer.delayed_call(function (c)
client.focus = c
--|allow micky to move the mouse
c:raise()
client.emit_signal("tabbar_draw", c.region)
clear_tabbar(c)
end,c) --|give it time in case maximize_horizontal is
--|adjusted before centering
return
end
end
end
--|c.direction is used to create a fake toggling effect.
--|tiled clients require an internal maximized property to
--|be set, otherwise they won't budge.
----------------------------------------------------- expand_vertical() -- ;
local function expand_vertical()
local c = client.focus
local going = "down"
if c.maximized_vertical then
if not c.floating then
-- draw_tabbar(c.region)
resize_region_to_index(c.region, true, true)
end
return
end --|reset toggle when sending same shortcut
--|consequitively
local stuff = get_client_info()
local target = grect.get_in_direction("down", stuff.regions, client.focus:geometry())
if target and stuff.regions[target].x ~= c.x then
return
end --|flow control
--|ensure we are operating in the same X axis,
--|vertical directions jump around
if not target then
going = "up"
target = grect.get_in_direction("up", stuff.regions, client.focus:geometry())
end --|flow control
--|try reverse direction
if not target then return end
--|flow control
if going == "down" then
tobe = {
y=c.y,
x=c.x,
width=c.width,
height=stuff.regions[target].y + stuff.regions[target].height - c.y
}
end
if going == "up" then
tobe = {
x=c.x,
width=c.width,
y=stuff.regions[target].y,
height= c.height + c.y - stuff.regions[target].y
}
end
c.maximized_vertical = true
gears.timer.delayed_call(function ()
client.focus:raise()
client.focus:geometry(tobe)
resize_region_to_client(c, {horizontal=false,vertical=true,direction=direction})
end)
return
end
------------------------------------------------------------- shuffle() -- ;
local function shuffle(direction)
return function()
if not client.focus then return end
--▨ flow control
local tablist = get_piled_clients(client.focus.region)
--|this is the ordered list
if not #tablist then return end
--▨ flow control
focused_client_ix = get_client_ix(client.focus.window, tablist)
--|find the index position of the focused client
if not focused_client_ix then return end
--▨ flow control
prev_ix = focused_client_ix - 1
next_ix = focused_client_ix + 1
--|calculate target indexes
if next_ix > #tablist then next_ix = 1 end
if prev_ix < 1 then prev_ix = #tablist end
--|check for validity of the index
if direction == "backward" then
tablist[prev_ix]:emit_signal("request::activate", "mouse_enter",{raise = true})
return
end
if direction == "forward" then
tablist[next_ix]:emit_signal("request::activate", "mouse_enter",{raise = true})
return
end
end
end
---------------------------------------------------------- get_swapee() -- ;
local function get_swapee(target_region_ix)
local regions = get_regions()
--| all regions
local cltbl = awful.client.visible(client.focus.screen, true)
--| all visible clients on all regions
--| but we don't know which regions they are at
local swap_map = {}
for a,region in ipairs(regions) do
for i,c in ipairs(cltbl) do
if c.x == region.x and c.y == region.y then
swap_map[a] = i
break --|avoid stacked regions
end
end
end --|iterate over regions, and match the client objects in
--|each region.
local swapee = cltbl[swap_map[target_region_ix]]
return swapee
end
--[[
returns the client object at a specific region. we can
also use signals to keep track of this but we are trying
to avoid exessive use of signals.
--]]
---------------------------------------------------------- my_shifter() -- ;
local function focus_by_number(region_ix,s)
return function()
local s = s or awful.screen.focused()
local regions = get_regions(s)
local target_region_ix
local target_region
local swapee = get_swapee(region_ix)
--|visible client at the target region
swapee:emit_signal("request::activate", "mouse_enter",{raise = true})
end
end
local function focus_by_index(direction)
return function()
if direction == "left" then direction = "backward" end
if direction == "right" then direction = "forward" end
local c = client.focus
local stuff = get_client_info()
local client_region_ix = stuff.active_region
local source_region
local target_region_ix
local target_region
c = reset_client_meta(c)
--|clean artifacts in case client was expanded.
if direction == "backward" then
if (client_region_ix + 1) > #stuff.regions then
target_region_ix = 1
else
target_region_ix = client_region_ix+1
end
end --|go next region by index,
--|if not reset to first
if direction == "forward" then
if (client_region_ix - 1) < 1 then
target_region_ix = #stuff.regions
else
target_region_ix = client_region_ix - 1
end
end --|go previous region by index,
--|if not reset to last
local swapee = get_swapee(target_region_ix)
--|visible client at the target region
swapee:emit_signal("request::activate", "mouse_enter",{raise = true})
end
end
local function my_shifter(direction, swap)
return function()
if direction == "left" then direction = "backward" end
if direction == "right" then direction = "forward" end
local c = client.focus
local stuff = get_client_info()
local client_region_ix = stuff.active_region
local source_region
local target_region_ix
local target_region
c = reset_client_meta(c)
--|clean artifacts in case client was expanded.
if direction == "backward" then
if (client_region_ix + 1) > #stuff.regions then
target_region_ix = 1
else
target_region_ix = client_region_ix+1
end
end --|go next region by index,
--|if not reset to first
if direction == "forward" then
if (client_region_ix - 1) < 1 then
target_region_ix = #stuff.regions
else
target_region_ix = client_region_ix - 1
end
end --|go previous region by index,
--|if not reset to last
if stuff.outofboundary then
target_region_ix = client_region_ix
end --|ignore previous when out of boundary
--|probably floating or expanded client
--|push inside the boundary instead
source_region = stuff.regions[client_region_ix]
target_region = stuff.regions[target_region_ix]
--|target regions geometry
local swapee = get_swapee(target_region_ix)
--|visible client at the target region
c:geometry(target_region)
--|relocate client
c.region = target_region_ix
--|update client property
if not swap then c:raise() end
--|raise
if swap and swapee then
swapee:geometry(source_region)
swapee:emit_signal("request::activate", "mouse_enter",{raise = true})
end --|perform swap
draw_tabbar(target_region_ix)
resize_region_to_index(target_region_ix, target_region, true)
--|update tabs in target region
draw_tabbar(client_region_ix)
resize_region_to_index(client_region_ix, source_region, true)
--|update tabs in source region
end
end
---------------------------------------------------- shift_by_direction -- ;
local function shift_by_direction(direction, swap)
return function ()
local c = client.focus
local stuff = get_client_info()
local target_region_ix = nil
local client_region_ix = stuff.active_region
if stuff.outofboundary == true then
return my_shifter(direction)()
end --|my_shifter handles this situation better.
local candidate = {
up = grect.get_in_direction("up", stuff.regions, client.focus:geometry()),
down = grect.get_in_direction("down", stuff.regions, client.focus:geometry()),
left = grect.get_in_direction("left", stuff.regions, client.focus:geometry()),
right = grect.get_in_direction("right", stuff.regions, client.focus:geometry())
}
target_region_ix = candidate[direction]
--|try to get a candidate region if possible
if not target_region_ix then
if direction == "right" then try = "left" end
if direction == "left" then try = "right" end
if direction == "down" then try = "up" end
if direction == "up" then try = "down" end
target_region_ix = go_edge(try, stuff.regions, client.focus:geometry())
end --|go the beginning or the end if there is no
--|candidate
source_region = stuff.regions[client_region_ix]
target_region = stuff.regions[target_region_ix]
local swapee = get_swapee(target_region_ix)
--|visible client at the target region
c:geometry(target_region)
--|relocate client
c.region = target_region_ix
--|update client property
if not swap then c:raise() end
--|raise
if swap and swapee then
swapee:geometry(source_region)
swapee:emit_signal("request::activate", "mouse_enter",{raise = true})
swapee.region = client_region_ix
end --|perform swap, update meta
draw_tabbar(target_region_ix)
resize_region_to_index(target_region_ix, target_region, true)
--|update tabs in target region
draw_tabbar(client_region_ix)
resize_region_to_index(client_region_ix, source_region, true)
--|update tabs in source region
end
end
----------------------------------------------------- get_tiled_clients -- ;
function get_piled_clients(region_ix, s)
local s = s or client.focus.screen or awful.screen.focused()
local tablist = get_punched_clients(region_ix, s)
local all_clients = get_global_clients()
local tiled_clients = {}
local myorder = {}
local window_ix = {}
for i,t in ipairs(tablist) do
window_ix[t.window] = true
end
local po = 1
for i,c in pairs(all_clients) do
if not c.floating and window_ix[c.window] then
tiled_clients[po] = c
po = po + 1
end
end
return tiled_clients
end --[23]
function get_tiled_clients(region_ix, s)
local s = s or client.focus.screen or awful.screen.focused()
local tablist = get_clients_in_region(region_ix, c, s)
local all_clients = get_global_clients()
local tiled_clients = {}
local myorder = {}
local window_ix = {}
for i,t in ipairs(tablist) do
window_ix[t.window] = true
end
local po = 1
for i,c in pairs(all_clients) do
if not c.floating and window_ix[c.window] then
tiled_clients[po] = c
po = po + 1
end
end
return tiled_clients
end --[23]
-------------------------------------------------------- draw_tabbar() -- ;
function draw_tabbar(region_ix, s)
local s = s or awful.screen.focused()
local flexlist = tabs.layout()
local tablist = get_tiled_clients(region_ix, s)
if tablelength(tablist) == 0 then
return
end --|this should only fire on an empty region
if tablelength(tablist) == 1 then
clear_tabbar(tablist[1])
return
end --|reset tabbar titlebar when only
--|one client is in the region.
for cl_ix, cl in ipairs(tablist) do
local flexlist = tabs.layout()
global_widget_table[cl.window] = {}
for cc_ix, cc in ipairs(tablist) do
local buttons = gears.table.join(
awful.button({}, 1, function(_)
double_click_event_handler(function()
cc.floating = not cc.floating
end)
gears.timer.delayed_call(function(p)
client.emit_signal("riseup", p)
end, cc)
end),
awful.button({}, 3, function(_)
cc:kill()
end))
global_widget_table[cl.window][cc_ix] = tabs.create(cc, (cc == cl), buttons, cl_ix)
flexlist:add(global_widget_table[cl.window][cc_ix])
flexlist.max_widget_size = 120
end
local titlebar = awful.titlebar(cl, {
bg = tabs.bg_normal,
size = tabs.size,
position = tabs.position,
})
titlebar:setup{layout = wibox.layout.flex.horizontal, flexlist}
awful.titlebar(cl, {size=8, position = "top"})
awful.titlebar(cl, {size=0, position = "left"})
awful.titlebar(cl, {size=0, position = "right"})
end
end
------------------------------------------------------ resize_region_to -- ;
-- todo: can merge these later, this will have side effects
-- when using multipler monitors.
function resize_region_to_client(c, reset)
local c = c or client.focus or nil
if c.floating then return end
--|we don't wan't interference
local tablist = get_tiled_clients(c.region)
for i, w in ipairs(tablist) do
if reset == true then
reset_client_meta(w)
else
w.maximized_horizontal = reset.horizontal
w.maximized_vertical = reset.vertical
w.direction = reset.direction
end
w:geometry(c:geometry())
end
end
function resize_region_to_index(region_ix, geom, reset)
local tablist = get_punched_clients(region_ix)
local region_info = get_region(region_ix)
for c_ix, c in ipairs(tablist) do
if reset == true then
reset_client_meta(c)
else
c.maximized_horizontal = reset.horizontal
c.maximized_vertical = reset.vertical
c.direction = reset.direction
end
c:geometry(region_info)
end
end
----------------------------------------------------- teleport_client() -- ;
local function teleport_client(c,s)
local c = c or client.focus
local s = s or c.screen or awful.screen.focused()
if not c then return true end
--|flow control
local is = {
region=c.region or get_client_info(c).active_region,
geom=c:geometry(),
screen=c.screen
} --|parameters before teleport
if not c.floating then
c:geometry({width=300, height=300})
end --|to avoid machi's auto expansion (lu,rd) of tiled
--|clients, resize them temporarily. they will be auto
--|expanded to the region anyway.
c:move_to_screen()
--|teleport
gears.timer.delayed_call(function (c)
local tobe = {
region=get_client_info(c).active_region,
}
c.region = tobe.region
draw_tabbar(c.region, c.screen)
draw_tabbar(is.region, is.screen)
c:emit_signal("request::activate", "mouse_enter",{raise = true})
end,c)
end
------------------------------------------------------ signal helpers -- ;
local function manage_signal(c)
-- reset_all_clients(s)
--|reset hack, we shouldn't need this in the second write
--|up.
if c.data.awful_client_properties then
local ci = get_client_info(c)
--|client info
global_client_table[c.window] = c
--|add window.id to client index
if ci.active_region and not c.floating then
gears.timer.delayed_call(function(cinfo, p)
if p.data.awful_client_properties then --[20]
p.region = cinfo.region
draw_tabbar(cinfo.active_region, p.screen)
p:geometry(cinfo.active_region_geom)
end
end, ci, c)
end --|in case new client appears tiled
--|we must update the regions tabbars.
if c.transient_for then
c:move_to_screen(c.transient_for.screen)
c:move_to_tag(awful.screen.focused().selected_tag)
client.focus = c
end --|when clients have a preset screen index with the rules,
--|transient windows always open in that screen even if we
--|moved it to the other one. this takes care of that.
end
end --[6]
----------------------------------------------------;
local function unmanage_signal(c)
if c then
global_client_table[c.window] = nil
--|remove window.id from client index
global_widget_table[c.window] = nil
--|remove window.id from widget index
if not c.floating then
local ci = get_client_info(c)
if ci.active_region then
draw_tabbar(ci.active_region, c.screen)
end
end
end
end --[7]
----------------------------------------------------;
local function selected_tag_signal(t)
gears.timer.delayed_call(function(t)
local regions = get_regions(t.screen)
if regions and #regions then
for i, region in ipairs(regions) do
draw_tabbar(i, t.screen)
end
end
end,t)
end --[8]
----------------------------------------------------;
local function floating_signal(c)
if not global_client_table[c.window] then return end
--|possibly to optimize config reload
--|floating signal kicks in before manage
--|this should bypass weird things happening during reload if any.
if c.floating then
if c.region then
gears.timer.delayed_call(function(active_region,c)
clear_tabbar(c)
draw_tabbar(c.region)
c.region = nil
end, active_region,c)
end
end --|window became floating
if not c.floating then
local ci = get_client_info(c)
if ci.active_region then
c.region = ci.active_region
gears.timer.delayed_call(function(active_region)
draw_tabbar(active_region)
end, ci.active_region)
end
end --|window became tiled
end --[9]
----------------------------------------------------;
local function focus_signal(c)
if global_widget_table[c.window] then
for i, p in pairs(global_widget_table[c.window]) do
if p.focused then
local widget = global_widget_table[c.window][i]:get_children_by_id(c.window)[1]
widget.bg = "#43417a"
end
end
end
end
----------------------------------------------------;
local function unfocus_signal(c)
if global_widget_table[c.window] then
for i, p in pairs(global_widget_table[c.window]) do
if p.focused then
p.bg = "#292929"
break
end
end
end
end
----------------------------------------------------;
local function minimized_signal(c)
if c.minimized then unmanage_signal(c) end
if not c.minimized then manage_signal(c) end
end --[[ manage minimized and not minimized ]]
----------------------------------------------------;
local function name_signal(c)
if widget_ix[c.window] then
for i, p in pairs(widget_ix[c.window]) do
if p.focused then
widget = widget_ix[c.window][i]:get_children_by_id(c.window)[1]
widget.widget.markup = c.name
end
end
end
end -- todo: need to update the other clients in the region here as well
-- this may not even be worth it as the client names kind of pollute the
-- tabs a lot making it harder to distinguish what is what.
-- client.connect_signal("property::name", name_signal)
----------------------------------------------------;
local function riseup_signal(c)
client.focus = c; c:raise()
-- c:emit_signal("request::activate", "mouse_enter",{raise = true})
end
----------------------------------------------------;
-- awful.titlebar.widget.connect_signal("mouse::enter", function()
-- log('here')
-- end)
--------------------------------------------------------------- signals -- ;
client.connect_signal("riseup", riseup_signal)
client.connect_signal("focus", focus_signal)
client.connect_signal("unfocus", unfocus_signal)
client.connect_signal("property::minimized", minimized_signal)
client.connect_signal("property::floating", floating_signal)
client.connect_signal("tabbar_draw", draw_tabbar)
client.connect_signal("unmanage", unmanage_signal)
client.connect_signal("manage", manage_signal)
tag.connect_signal("property::selected", selected_tag_signal)
-- client.connect_signal("mouse::enter", function ()
-- log(mouse.current_widget)
-- end)
--------------------------------------------------------------- exports -- ;
module = {
focus_by_direction = focus_by_direction,
get_active_regions = get_client_info,
shift_by_direction = shift_by_direction,
expand_horizontal = expand_horizontal,
shuffle = shuffle,
old_shuffle = old_shuffle,
my_shifter = my_shifter,
expand_vertical = expand_vertical,
move_to = move_to,
get_regions = get_regions,
toggle_always_on = toggle_always_on,
draw_tabbar = draw_tabbar,
get_global_clients = get_global_clients,
update_global_clients = update_global_clients,
get_client_info = get_client_info,
teleport_client = teleport_client,
focus_by_index = focus_by_index,
focus_by_number = focus_by_number,
set_region = set_region,
align_floats = align_floats,
}
return module
--[[ ------------------------------------------------- NOTES ]
[99] order of signals, manage_signal executes the last,
not the first.
[0] todo: rewrite the whole thing, but plan ahead this
time.
- get regions from machi, this will give us indexes
- manage signal will mark the global index and punch
the region_id to the client.
- it will then draw tabs to the region
region_expansions:
- regions can be expanded using the maximixed trick.
- it will change the geometry of all the clients in
that region.
- redrawing the tabbar is not necessary.
- when toggling, region geometry will also change.
functions needed:
- get_region(region_id, screen)
- get_regions(screen)
- get_clients_in_region(region_id, screen): this would
need to return the ordered list of all the clients
in the region from the global client list.
there are multiple strategies that can be used:
c.region_id:
this wil flap during reload
geometric comparison: we can compare all client
geometry to regions geometry. but it will fail for
expanded/overflowing clients.
- draw_tabbar(region, screen): it will draw tabbars
for all the clients in the region.
- expand_region(direction, region, screen): it will
expand all the clients in the region. same shortcut
will reset the expansions. expansions will happen
in multiple directions, and "center".
MPV: it appears client flashing could also be an issue.
MPV for instance starts large briefly and causes an
update in the wrong region. We need a region.id lookup
only it seems. We should also consider reading awm rules
for a region id for placement.
[4] machi's own region expansion has issues on
awesome-reload. if we were to expand a region, and then
do reload, machi-layout would insist to keep the expanded
layout in its own accord.
[5] to avoid this, we temporarily set the non floating
clients region geometry.
[4] when the clients become float, we restore this
geometry. Do note, there is something awkward here, it
appears no matter what all clients start as float then
get tiled, so there is a flaw in this logic.
[9] when windows switch between float and tiled we must
perform necessary maintenance on the destination and
source regions. a delayed call was necessary when clients
become tiled to give awm enough time to draw the widgets
properly. (*)this floating signal acts weird during
configuration reloads.
[8] property::selected gets called the last, by the time
we are here, we already have the global_client_list to
draw tabbars. This may appear redundant here, but it's
good to have this fire up in case the user switches
tags.
[7] when removing a tiled client we must update the
tabbars of others. floating clients do not require any
cleanup.
[6] global_client_table is the milestone the tabbars rely
on. whenever a new client appears we must add to it, and
when a client is killed we must make sure it is
removed.
[23] global_client_index stores the ordered list of all
clients available and it is used as a blueprint to keep
the order of our tablist intact, without this, tabbars
would go out of order when user focuses via shortcuts
(run_or_raise).
[20] cudatext had an awkward issue, I suppose it's the way
it's rendering its window causing it to register multiple
times and it would make client.lua throw an invalid
object error at line 1195. So, it's handled now.
--]]
| 412 | 0.945778 | 1 | 0.945778 | game-dev | MEDIA | 0.52335 | game-dev | 0.926741 | 1 | 0.926741 |
chenyong2github/QuadTreeSceneManager | 6,555 | Assets/Standard Assets/Utility/WaypointProgressTracker.cs | using System;
using UnityEngine;
namespace UnityStandardAssets.Utility
{
public class WaypointProgressTracker : MonoBehaviour
{
// This script can be used with any object that is supposed to follow a
// route marked out by waypoints.
// This script manages the amount to look ahead along the route,
// and keeps track of progress and laps.
[SerializeField] private WaypointCircuit circuit; // A reference to the waypoint-based route we should follow
[SerializeField] private float lookAheadForTargetOffset = 5;
// The offset ahead along the route that the we will aim for
[SerializeField] private float lookAheadForTargetFactor = .1f;
// A multiplier adding distance ahead along the route to aim for, based on current speed
[SerializeField] private float lookAheadForSpeedOffset = 10;
// The offset ahead only the route for speed adjustments (applied as the rotation of the waypoint target transform)
[SerializeField] private float lookAheadForSpeedFactor = .2f;
// A multiplier adding distance ahead along the route for speed adjustments
[SerializeField] private ProgressStyle progressStyle = ProgressStyle.SmoothAlongRoute;
// whether to update the position smoothly along the route (good for curved paths) or just when we reach each waypoint.
[SerializeField] private float pointToPointThreshold = 4;
// proximity to waypoint which must be reached to switch target to next waypoint : only used in PointToPoint mode.
public enum ProgressStyle
{
SmoothAlongRoute,
PointToPoint,
}
// these are public, readable by other objects - i.e. for an AI to know where to head!
public WaypointCircuit.RoutePoint targetPoint { get; private set; }
public WaypointCircuit.RoutePoint speedPoint { get; private set; }
public WaypointCircuit.RoutePoint progressPoint { get; private set; }
public Transform target;
private float progressDistance; // The progress round the route, used in smooth mode.
private int progressNum; // the current waypoint number, used in point-to-point mode.
private Vector3 lastPosition; // Used to calculate current speed (since we may not have a rigidbody component)
private float speed; // current speed of this object (calculated from delta since last frame)
// setup script properties
private void Start()
{
// we use a transform to represent the point to aim for, and the point which
// is considered for upcoming changes-of-speed. This allows this component
// to communicate this information to the AI without requiring further dependencies.
// You can manually create a transform and assign it to this component *and* the AI,
// then this component will update it, and the AI can read it.
if (target == null)
{
target = new GameObject(name + " Waypoint Target").transform;
}
Reset();
}
// reset the object to sensible values
public void Reset()
{
progressDistance = 0;
progressNum = 0;
if (progressStyle == ProgressStyle.PointToPoint)
{
target.position = circuit.Waypoints[progressNum].position;
target.rotation = circuit.Waypoints[progressNum].rotation;
}
}
private void Update()
{
if (progressStyle == ProgressStyle.SmoothAlongRoute)
{
// determine the position we should currently be aiming for
// (this is different to the current progress position, it is a a certain amount ahead along the route)
// we use lerp as a simple way of smoothing out the speed over time.
if (Time.deltaTime > 0)
{
speed = Mathf.Lerp(speed, (lastPosition - transform.position).magnitude/Time.deltaTime,
Time.deltaTime);
}
target.position =
circuit.GetRoutePoint(progressDistance + lookAheadForTargetOffset + lookAheadForTargetFactor*speed)
.position;
target.rotation =
Quaternion.LookRotation(
circuit.GetRoutePoint(progressDistance + lookAheadForSpeedOffset + lookAheadForSpeedFactor*speed)
.direction);
// get our current progress along the route
progressPoint = circuit.GetRoutePoint(progressDistance);
Vector3 progressDelta = progressPoint.position - transform.position;
if (Vector3.Dot(progressDelta, progressPoint.direction) < 0)
{
progressDistance += progressDelta.magnitude*0.5f;
}
lastPosition = transform.position;
}
else
{
// point to point mode. Just increase the waypoint if we're close enough:
Vector3 targetDelta = target.position - transform.position;
if (targetDelta.magnitude < pointToPointThreshold)
{
progressNum = (progressNum + 1)%circuit.Waypoints.Length;
}
target.position = circuit.Waypoints[progressNum].position;
target.rotation = circuit.Waypoints[progressNum].rotation;
// get our current progress along the route
progressPoint = circuit.GetRoutePoint(progressDistance);
Vector3 progressDelta = progressPoint.position - transform.position;
if (Vector3.Dot(progressDelta, progressPoint.direction) < 0)
{
progressDistance += progressDelta.magnitude;
}
lastPosition = transform.position;
}
}
private void OnDrawGizmos()
{
if (Application.isPlaying)
{
Gizmos.color = Color.green;
Gizmos.DrawLine(transform.position, target.position);
Gizmos.DrawWireSphere(circuit.GetRoutePosition(progressDistance), 1);
Gizmos.color = Color.yellow;
Gizmos.DrawLine(target.position, target.position + target.forward);
}
}
}
}
| 412 | 0.933665 | 1 | 0.933665 | game-dev | MEDIA | 0.54494 | game-dev,graphics-rendering | 0.87842 | 1 | 0.87842 |
Aizistral-Studios/Enigmatic-Legacy | 1,891 | src/main/java/com/aizistral/enigmaticlegacy/objects/EnabledCondition.java | package com.aizistral.enigmaticlegacy.objects;
import com.aizistral.enigmaticlegacy.EnigmaticLegacy;
import com.aizistral.enigmaticlegacy.config.OmniconfigHandler;
import com.google.gson.JsonObject;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.item.Item;
import net.minecraftforge.common.crafting.conditions.ICondition;
import net.minecraftforge.common.crafting.conditions.IConditionSerializer;
import net.minecraftforge.registries.ForgeRegistries;
/**
* Condition that checks whether item is instance of IPerhaps, and if it is,
* whether or not it is enabled. Used to disable recipes for items disabled
* in config.
* @author Integral
*/
public class EnabledCondition implements ICondition {
private static final ResourceLocation ID = new ResourceLocation(EnigmaticLegacy.MODID, "is_enabled");
private final ResourceLocation item;
public EnabledCondition(ResourceLocation item) {
this.item = item;
}
@Override
public ResourceLocation getID() {
return ID;
}
@Override
public boolean test(IContext context) {
Item item = ForgeRegistries.ITEMS.getValue(this.item);
if (this.item.toString().equals(EnigmaticLegacy.MODID + ":bonuswoolrecipes"))
return OmniconfigHandler.bonusWoolRecipesEnabled.getValue();
else
return OmniconfigHandler.isItemEnabled(item);
}
public static class Serializer implements IConditionSerializer<EnabledCondition> {
public static final Serializer INSTANCE = new Serializer();
@Override
public void write(JsonObject json, EnabledCondition value) {
json.addProperty("item", value.item.toString());
}
@Override
public EnabledCondition read(JsonObject json) {
return new EnabledCondition(new ResourceLocation(GsonHelper.getAsString(json, "item")));
}
@Override
public ResourceLocation getID() {
return EnabledCondition.ID;
}
}
}
| 412 | 0.725952 | 1 | 0.725952 | game-dev | MEDIA | 0.991699 | game-dev | 0.921035 | 1 | 0.921035 |
KgDW/NullPoint-Fabric | 1,811 | src/main/java/me/nullpoint/asm/mixins/MixinBoatEntity.java | package me.nullpoint.asm.mixins;
import me.nullpoint.Nullpoint;
import me.nullpoint.api.events.impl.BoatMoveEvent;
import me.nullpoint.mod.modules.impl.movement.EntityControl;
import net.minecraft.entity.vehicle.BoatEntity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(BoatEntity.class)
public class MixinBoatEntity {
@Shadow private boolean pressingLeft;
@Shadow private boolean pressingRight;
@Inject(method = "tick", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/vehicle/BoatEntity;move(Lnet/minecraft/entity/MovementType;Lnet/minecraft/util/math/Vec3d;)V"), cancellable = true)
private void onTickInvokeMove(CallbackInfo info) {
BoatMoveEvent event = new BoatMoveEvent((BoatEntity) (Object) this);
Nullpoint.EVENT_BUS.post(event);
if (event.isCancelled()) {
info.cancel();
}
}
@Redirect(method = "updatePaddles", at = @At(value = "FIELD", target = "Lnet/minecraft/entity/vehicle/BoatEntity;pressingLeft:Z"))
private boolean onUpdatePaddlesPressingLeft(BoatEntity boat) {
if (EntityControl.INSTANCE.isOn() && EntityControl.INSTANCE.fly.getValue()) return false;
return pressingLeft;
}
@Redirect(method = "updatePaddles", at = @At(value = "FIELD", target = "Lnet/minecraft/entity/vehicle/BoatEntity;pressingRight:Z"))
private boolean onUpdatePaddlesPressingRight(BoatEntity boat) {
if (EntityControl.INSTANCE.isOn() && EntityControl.INSTANCE.fly.getValue()) return false;
return pressingRight;
}
}
| 412 | 0.921131 | 1 | 0.921131 | game-dev | MEDIA | 0.89539 | game-dev | 0.937656 | 1 | 0.937656 |
ejoy/vaststars | 1,045 | startup/pkg/vaststars.gamerender/service/memtexture.lua | local ltask = require "ltask"
local ServiceWindow = ltask.queryservice "ant.window|window"
local S = {}
local function init()
local textmgr = ltask.queryservice "ant.resource_manager|resource"
ltask.call(textmgr, "register", "mem", ltask.self())
end
function S.load(name, path, config)
local type, size, rot, dis = ltask.call(ServiceWindow, "parse_prefab_config", config)
local c = {
info = {
width = size.width,
height = size.height,
format = "RGBA8",
mipmap = false,
depth = 1,
numLayers = 1,
cubeMap = false,
storageSize = 4,
numMips = 1,
bitsPerPixel = 32,
},
flag = "+l-lvcucrt",
handle = nil,
}
c.handle = ltask.call(ServiceWindow, "get_portrait_handle", name, size.width, size.height)
ltask.call(ServiceWindow, "set_portrait_prefab", name, path, rot, dis, type)
return c, true
end
function S.unload(handle)
ltask.call(ServiceWindow, "destroy_portrait_handle", handle)
end
init()
return S
| 412 | 0.732015 | 1 | 0.732015 | game-dev | MEDIA | 0.544122 | game-dev | 0.596723 | 1 | 0.596723 |
rorchard/FuzzyCLIPS | 36,250 | source/msgcom.c | static char rcsid[] = "$Header: /dist/CVS/fzclips/src/msgcom.c,v 1.3 2001/08/11 21:06:56 dave Exp $" ;
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.05 04/09/97 */
/* */
/* OBJECT MESSAGE COMMANDS */
/*******************************************************/
/*************************************************************/
/* Purpose: */
/* */
/* Principal Programmer(s): */
/* Brian L. Donnell */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* */
/*************************************************************/
/* =========================================
*****************************************
EXTERNAL DEFINITIONS
=========================================
***************************************** */
#include "setup.h"
#if OBJECT_SYSTEM
#include <string.h>
#include "argacces.h"
#include "classcom.h"
#include "classfun.h"
#include "classinf.h"
#include "insfun.h"
#include "insmoddp.h"
#include "msgfun.h"
#include "prccode.h"
#include "router.h"
#if BLOAD || BLOAD_AND_BSAVE
#include "bload.h"
#endif
#if ! RUN_TIME
#include "extnfunc.h"
#endif
#if (! BLOAD_ONLY) && (! RUN_TIME)
#include "constrct.h"
#include "msgpsr.h"
#endif
#if DEBUGGING_FUNCTIONS
#include "watch.h"
#endif
#define _MSGCOM_SOURCE_
#include "msgcom.h"
/* =========================================
*****************************************
CONSTANTS
=========================================
***************************************** */
/* =========================================
*****************************************
MACROS AND TYPES
=========================================
***************************************** */
/* =========================================
*****************************************
INTERNALLY VISIBLE FUNCTION HEADERS
=========================================
***************************************** */
#if ! RUN_TIME
static void CreateSystemHandlers(void);
#endif
#if (! BLOAD_ONLY) && (! RUN_TIME)
static int WildDeleteHandler(DEFCLASS *,SYMBOL_HN *,char *);
#endif
#if DEBUGGING_FUNCTIONS
static BOOLEAN DefmessageHandlerWatchAccess(int,int,EXPRESSION *);
static BOOLEAN DefmessageHandlerWatchPrint(char *,int,EXPRESSION *);
static BOOLEAN DefmessageHandlerWatchSupport(char *,char *,int,
void (*)(char *,void *,unsigned),
void (*)(int,void *,unsigned),EXPRESSION *);
static BOOLEAN WatchClassHandlers(void *,char *,int,char *,int,int,
void (*)(char *,void *,unsigned),
void (*)(int,void *,unsigned));
static void PrintHandlerWatchFlag(char *,void *,unsigned);
#endif
/* =========================================
*****************************************
EXTERNALLY VISIBLE GLOBAL VARIABLES
=========================================
***************************************** */
/* =========================================
*****************************************
INTERNALLY VISIBLE GLOBAL VARIABLES
=========================================
***************************************** */
static ENTITY_RECORD HandlerGetInfo = { "HANDLER_GET", HANDLER_GET,0,1,1,
PrintHandlerSlotGetFunction,
PrintHandlerSlotGetFunction,NULL,
HandlerSlotGetFunction,
NULL,NULL,NULL,NULL,NULL,NULL },
HandlerPutInfo = { "HANDLER_PUT", HANDLER_PUT,0,1,1,
PrintHandlerSlotPutFunction,
PrintHandlerSlotPutFunction,NULL,
HandlerSlotPutFunction,
NULL,NULL,NULL,NULL,NULL,NULL };
/* =========================================
*****************************************
EXTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
/***************************************************
NAME : SetupMessageHandlers
DESCRIPTION : Sets up internal symbols and
fucntion definitions pertaining to
message-handlers. Also creates
system handlers
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : Functions and data structures
initialized
NOTES : Should be called before
SetupInstanceModDupCommands() in
INSMODDP.C
***************************************************/
globle void SetupMessageHandlers()
{
InstallPrimitive(&HandlerGetInfo,HANDLER_GET);
InstallPrimitive(&HandlerPutInfo,HANDLER_PUT);
#if ! RUN_TIME
INIT_SYMBOL = (SYMBOL_HN *) AddSymbol(INIT_STRING);
IncrementSymbolCount(INIT_SYMBOL);
DELETE_SYMBOL = (SYMBOL_HN *) AddSymbol(DELETE_STRING);
IncrementSymbolCount(DELETE_SYMBOL);
AddClearFunction("defclass",CreateSystemHandlers,-100);
#if ! BLOAD_ONLY
SELF_SYMBOL = (SYMBOL_HN *) AddSymbol(SELF_STRING);
IncrementSymbolCount(SELF_SYMBOL);
AddConstruct("defmessage-handler","defmessage-handlers",
ParseDefmessageHandler,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
DefineFunction2("undefmessage-handler",'v',PTIF UndefmessageHandlerCommand,
"UndefmessageHandlerCommand","23w");
#endif
DefineFunction2("send",'u',PTIF SendCommand,"SendCommand","2*uuw");
#if DEBUGGING_FUNCTIONS
DefineFunction2("preview-send",'v',PTIF PreviewSendCommand,"PreviewSendCommand","22w");
DefineFunction2("ppdefmessage-handler",'v',PTIF PPDefmessageHandlerCommand,
"PPDefmessageHandlerCommand","23w");
DefineFunction2("list-defmessage-handlers",'v',PTIF ListDefmessageHandlersCommand,
"ListDefmessageHandlersCommand","02w");
#endif
#if IMPERATIVE_MESSAGE_HANDLERS
DefineFunction2("next-handlerp",'b',PTIF NextHandlerAvailable,"NextHandlerAvailable","00");
FuncSeqOvlFlags("next-handlerp",TRUE,FALSE);
DefineFunction2("call-next-handler",'u',
PTIF CallNextHandler,"CallNextHandler","00");
FuncSeqOvlFlags("call-next-handler",TRUE,FALSE);
DefineFunction2("override-next-handler",'u',
PTIF CallNextHandler,"CallNextHandler",NULL);
FuncSeqOvlFlags("override-next-handler",TRUE,FALSE);
#endif
DefineFunction2("dynamic-get",'u',PTIF DynamicHandlerGetSlot,"DynamicHandlerGetSlot","11w");
DefineFunction2("dynamic-put",'u',PTIF DynamicHandlerPutSlot,"DynamicHandlerPutSlot","1**w");
DefineFunction2("get",'u',PTIF DynamicHandlerGetSlot,"DynamicHandlerGetSlot","11w");
DefineFunction2("put",'u',PTIF DynamicHandlerPutSlot,"DynamicHandlerPutSlot","1**w");
#endif
#if DEBUGGING_FUNCTIONS
AddWatchItem("messages",0,&WatchMessages,36,NULL,NULL);
AddWatchItem("message-handlers",0,&WatchHandlers,35,
DefmessageHandlerWatchAccess,DefmessageHandlerWatchPrint);
#endif
}
/*****************************************************
NAME : GetDefmessageHandlerName
DESCRIPTION : Gets the name of a message-handler
INPUTS : 1) Pointer to a class
2) Array index of handler in class's
message-handler array (+1)
RETURNS : Name-string of message-handler
SIDE EFFECTS : None
NOTES : None
*****************************************************/
char *GetDefmessageHandlerName(
void *ptr,
unsigned index)
{
return(ValueToString(((DEFCLASS *) ptr)->handlers[index-1].name));
}
/*****************************************************
NAME : GetDefmessageHandlerType
DESCRIPTION : Gets the type of a message-handler
INPUTS : 1) Pointer to a class
2) Array index of handler in class's
message-handler array (+1)
RETURNS : Type-string of message-handler
SIDE EFFECTS : None
NOTES : None
*****************************************************/
globle char *GetDefmessageHandlerType(
void *ptr,
unsigned index)
{
return(hndquals[((DEFCLASS *) ptr)->handlers[index-1].type]);
}
/**************************************************************
NAME : GetNextDefmessageHandler
DESCRIPTION : Finds first or next handler for a class
INPUTS : 1) The address of the handler's class
2) The array index of the current handler (+1)
RETURNS : The array index (+1) of the next handler, or 0
if there is none
SIDE EFFECTS : None
NOTES : If index == 0, the first handler array index
(i.e. 1) returned
**************************************************************/
globle unsigned GetNextDefmessageHandler(
void *ptr,
unsigned index)
{
DEFCLASS *cls;
cls = (DEFCLASS *) ptr;
if (index == 0)
return((cls->handlers != NULL) ? 1 : 0);
if (index == cls->handlerCount)
return(0);
return(index+1);
}
/*****************************************************
NAME : GetDefmessageHandlerPointer
DESCRIPTION : Returns a pointer to a handler
INPUTS : 1) Pointer to a class
2) Array index of handler in class's
message-handler array (+1)
RETURNS : Pointer to the handler.
SIDE EFFECTS : None
NOTES : None
*****************************************************/
globle HANDLER *GetDefmessageHandlerPointer(
void *ptr,
unsigned index)
{
return(&((DEFCLASS *) ptr)->handlers[index-1]);
}
#if DEBUGGING_FUNCTIONS
/*********************************************************
NAME : GetDefmessageHandlerWatch
DESCRIPTION : Determines if trace messages for calls
to this handler will be generated or not
INPUTS : 1) A pointer to the class
2) The index of the handler
RETURNS : TRUE if a trace is active,
FALSE otherwise
SIDE EFFECTS : None
NOTES : None
*********************************************************/
globle BOOLEAN GetDefmessageHandlerWatch(
void *theClass,
unsigned theIndex)
{
return(((DEFCLASS *) theClass)->handlers[theIndex-1].trace);
}
/*********************************************************
NAME : SetDefmessageHandlerWatch
DESCRIPTION : Sets the trace to ON/OFF for the
calling of the handler
INPUTS : 1) TRUE to set the trace on,
FALSE to set it off
2) A pointer to the class
3) The index of the handler
RETURNS : Nothing useful
SIDE EFFECTS : Watch flag for the handler set
NOTES : None
*********************************************************/
globle void SetDefmessageHandlerWatch(
int newState,
void *theClass,
unsigned theIndex)
{
((DEFCLASS *) theClass)->handlers[theIndex-1].trace = newState;
}
#endif
/***************************************************
NAME : FindDefmessageHandler
DESCRIPTION : Determines the index of a specfied
message-handler
INPUTS : 1) A pointer to the class
2) Name-string of the handler
3) Handler-type: "around","before",
"primary", or "after"
RETURNS : The index of the handler
(0 if not found)
SIDE EFFECTS : None
NOTES : None
***************************************************/
globle unsigned FindDefmessageHandler(
void *ptr,
char *hname,
char *htypestr)
{
int htype;
SYMBOL_HN *hsym;
DEFCLASS *cls;
int index;
htype = HandlerType("handler-lookup",htypestr);
if (htype == MERROR)
return(0);
hsym = FindSymbol(hname);
if (hsym == NULL)
return(0);
cls = (DEFCLASS *) ptr;
index = FindHandlerByIndex(cls,hsym,(unsigned) htype);
return((unsigned) (index+1));
}
/***************************************************
NAME : IsDefmessageHandlerDeletable
DESCRIPTION : Determines if a message-handler
can be deleted
INPUTS : 1) Address of the handler's class
2) Index of the handler
RETURNS : TRUE if deletable, FALSE otherwise
SIDE EFFECTS : None
NOTES : None
***************************************************/
globle int IsDefmessageHandlerDeletable(
void *ptr,
unsigned index)
{
#if (MAC_MPW || MAC_MCW) && (RUN_TIME || BLOAD_ONLY)
#pragma unused(ptr)
#pragma unused(index)
#endif
#if BLOAD_ONLY || RUN_TIME
return(FALSE);
#else
DEFCLASS *cls;
#if BLOAD || BLOAD_AND_BSAVE
if (Bloaded())
return(FALSE);
#endif
cls = (DEFCLASS *) ptr;
if (cls->handlers[index-1].system == 1)
return(FALSE);
return((HandlersExecuting(cls) == FALSE) ? TRUE : FALSE);
#endif
}
/******************************************************************************
NAME : UndefmessageHandlerCommand
DESCRIPTION : Deletes a handler from a class
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : Handler deleted if possible
NOTES : H/L Syntax: (undefmessage-handler <class> <handler> [<type>])
******************************************************************************/
globle void UndefmessageHandlerCommand()
{
#if RUN_TIME || BLOAD_ONLY
PrintErrorID("MSGCOM",3,FALSE);
PrintRouter(WERROR,"Unable to delete message-handlers.\n");
#else
SYMBOL_HN *mname;
char *tname;
DATA_OBJECT tmp;
DEFCLASS *cls;
#if BLOAD || BLOAD_AND_BSAVE
if (Bloaded())
{
PrintErrorID("MSGCOM",3,FALSE);
PrintRouter(WERROR,"Unable to delete message-handlers.\n");
return;
}
#endif
if (ArgTypeCheck("undefmessage-handler",1,SYMBOL,&tmp) == FALSE)
return;
cls = LookupDefclassByMdlOrScope(DOToString(tmp));
if ((cls == NULL) ? (strcmp(DOToString(tmp),"*") != 0) : FALSE)
{
ClassExistError("undefmessage-handler",DOToString(tmp));
return;
}
if (ArgTypeCheck("undefmessage-handler",2,SYMBOL,&tmp) == FALSE)
return;
mname = (SYMBOL_HN *) tmp.value;
if (RtnArgCount() == 3)
{
if (ArgTypeCheck("undefmessage-handler",3,SYMBOL,&tmp) == FALSE)
return;
tname = DOToString(tmp);
if (strcmp(tname,"*") == 0)
tname = NULL;
}
else
tname = hndquals[MPRIMARY];
WildDeleteHandler(cls,mname,tname);
#endif
}
/***********************************************************
NAME : UndefmessageHandler
DESCRIPTION : Deletes a handler from a class
INPUTS : 1) Class address (Can be NULL)
2) Handler index (can be 0)
RETURNS : 1 if successful, 0 otherwise
SIDE EFFECTS : Handler deleted if possible
NOTES : None
***********************************************************/
globle int UndefmessageHandler(
void *vptr,
unsigned mhi)
{
#if (MAC_MPW || MAC_MCW) && (RUN_TIME || BLOAD_ONLY)
#pragma unused(vptr)
#pragma unused(mhi)
#endif
#if RUN_TIME || BLOAD_ONLY
PrintErrorID("MSGCOM",3,FALSE);
PrintRouter(WERROR,"Unable to delete message-handlers.\n");
return(0);
#else
DEFCLASS *cls;
#if BLOAD || BLOAD_AND_BSAVE
if (Bloaded())
{
PrintErrorID("MSGCOM",3,FALSE);
PrintRouter(WERROR,"Unable to delete message-handlers.\n");
return(0);
}
#endif
if (vptr == NULL)
{
if (mhi != 0)
{
PrintErrorID("MSGCOM",1,FALSE);
PrintRouter(WERROR,"Incomplete message-handler specification for deletion.\n");
return(0);
}
return(WildDeleteHandler(NULL,NULL,NULL));
}
if (mhi == 0)
return(WildDeleteHandler((DEFCLASS *) vptr,NULL,NULL));
cls = (DEFCLASS *) vptr;
if (HandlersExecuting(cls))
{
HandlerDeleteError(GetDefclassName((void *) cls));
return(0);
}
cls->handlers[mhi-1].mark = 1;
DeallocateMarkedHandlers(cls);
return(1);
#endif
}
#if DEBUGGING_FUNCTIONS
/*******************************************************************************
NAME : PPDefmessageHandlerCommand
DESCRIPTION : Displays the pretty-print form (if any) for a handler
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : H/L Syntax: (ppdefmessage-handler <class> <message> [<type>])
*******************************************************************************/
globle void PPDefmessageHandlerCommand()
{
DATA_OBJECT temp;
SYMBOL_HN *csym,*msym;
char *tname;
DEFCLASS *cls = NULL;
int mtype;
HANDLER *hnd;
if (ArgTypeCheck("ppdefmessage-handler",1,SYMBOL,&temp) == FALSE)
return;
csym = FindSymbol(DOToString(temp));
if (ArgTypeCheck("ppdefmessage-handler",2,SYMBOL,&temp) == FALSE)
return;
msym = FindSymbol(DOToString(temp));
if (RtnArgCount() == 3)
{
if (ArgTypeCheck("ppdefmessage-handler",3,SYMBOL,&temp) == FALSE)
return;
tname = DOToString(temp);
}
else
tname = hndquals[MPRIMARY];
mtype = HandlerType("ppdefmessage-handler",tname);
if (mtype == MERROR)
{
SetEvaluationError(TRUE);
return;
}
if (csym != NULL)
cls = LookupDefclassByMdlOrScope(ValueToString(csym));
if (((cls == NULL) || (msym == NULL)) ? TRUE :
((hnd = FindHandlerByAddress(cls,msym,(unsigned) mtype)) == NULL))
{
PrintErrorID("MSGCOM",2,FALSE);
PrintRouter(WERROR,"Unable to find message-handler ");
PrintRouter(WERROR,ValueToString(msym));
PrintRouter(WERROR," ");
PrintRouter(WERROR,tname);
PrintRouter(WERROR," for class ");
PrintRouter(WERROR,ValueToString(csym));
PrintRouter(WERROR," in function ppdefmessage-handler.\n");
SetEvaluationError(TRUE);
return;
}
if (hnd->ppForm != NULL)
PrintInChunks(WDISPLAY,hnd->ppForm);
}
/*****************************************************************************
NAME : ListDefmessageHandlersCommand
DESCRIPTION : Depending on arguments, does lists handlers which
match restrictions
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : H/L Syntax: (list-defmessage-handlers [<class> [inherit]]))
*****************************************************************************/
globle void ListDefmessageHandlersCommand()
{
int inhp;
void *clsptr;
if (RtnArgCount() == 0)
ListDefmessageHandlers(WDISPLAY,NULL,0);
else
{
clsptr = ClassInfoFnxArgs("list-defmessage-handlers",&inhp);
if (clsptr == NULL)
return;
ListDefmessageHandlers(WDISPLAY,clsptr,inhp);
}
}
/********************************************************************
NAME : PreviewSendCommand
DESCRIPTION : Displays a list of the core for a message describing
shadows,etc.
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : Temporary core created and destroyed
NOTES : H/L Syntax: (preview-send <class> <msg>)
********************************************************************/
globle void PreviewSendCommand()
{
DEFCLASS *cls;
DATA_OBJECT temp;
/* =============================
Get the class for the message
============================= */
if (ArgTypeCheck("preview-send",1,SYMBOL,&temp) == FALSE)
return;
cls = LookupDefclassByMdlOrScope(DOToString(temp));
if (cls == NULL)
{
ClassExistError("preview-send",ValueToString(temp.value));
return;
}
if (ArgTypeCheck("preview-send",2,SYMBOL,&temp) == FALSE)
return;
PreviewSend(WDISPLAY,(void *) cls,DOToString(temp));
}
/********************************************************
NAME : GetDefmessageHandlerPPForm
DESCRIPTION : Gets a message-handler pretty print form
INPUTS : 1) Address of the handler's class
2) Index of the handler
RETURNS : TRUE if printable, FALSE otherwise
SIDE EFFECTS : None
NOTES : None
********************************************************/
globle char *GetDefmessageHandlerPPForm(
void *ptr,
unsigned index)
{
return(((DEFCLASS *) ptr)->handlers[index-1].ppForm);
}
/*******************************************************************
NAME : ListDefmessageHandlers
DESCRIPTION : Lists message-handlers for a class
INPUTS : 1) The logical name of the output
2) Class name (NULL to display all handlers)
3) A flag indicating whether to list inherited
handlers or not
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : None
*******************************************************************/
globle void ListDefmessageHandlers(
char *log,
void *vptr,
int inhp)
{
DEFCLASS *cls;
long cnt;
PACKED_CLASS_LINKS plinks;
if (vptr != NULL)
{
cls = (DEFCLASS *) vptr;
if (inhp)
cnt = DisplayHandlersInLinks(log,&cls->allSuperclasses,0);
else
{
plinks.classCount = 1;
plinks.classArray = &cls;
cnt = DisplayHandlersInLinks(log,&plinks,0);
}
}
else
{
plinks.classCount = 1;
cnt = 0L;
for (cls = (DEFCLASS *) GetNextDefclass(NULL) ;
cls != NULL ;
cls = (DEFCLASS *) GetNextDefclass((void *) cls))
{
plinks.classArray = &cls;
cnt += DisplayHandlersInLinks(log,&plinks,0);
}
}
PrintTally(log,cnt,"message-handler","message-handlers");
}
/********************************************************************
NAME : PreviewSend
DESCRIPTION : Displays a list of the core for a message describing
shadows,etc.
INPUTS : 1) Logical name of output
2) Class pointer
3) Message name-string
RETURNS : Nothing useful
SIDE EFFECTS : Temporary core created and destroyed
NOTES : None
********************************************************************/
globle void PreviewSend(
char *logicalName,
void *clsptr,
char *msgname)
{
HANDLER_LINK *core;
SYMBOL_HN *msym;
msym = FindSymbol(msgname);
if (msym == NULL)
return;
core = FindPreviewApplicableHandlers((DEFCLASS *) clsptr,msym);
if (core != NULL)
{
DisplayCore(logicalName,core,0);
DestroyHandlerLinks(core);
}
}
/****************************************************
NAME : DisplayHandlersInLinks
DESCRIPTION : Recursively displays all handlers
for an array of classes
INPUTS : 1) The logical name of the output
2) The packed class links
3) The index to print from the links
RETURNS : The number of handlers printed
SIDE EFFECTS : None
NOTES : Used by DescribeClass()
****************************************************/
globle long DisplayHandlersInLinks(
char *log,
PACKED_CLASS_LINKS *plinks,
unsigned index)
{
register unsigned i;
long cnt;
cnt = (long) plinks->classArray[index]->handlerCount;
if (index < (plinks->classCount - 1))
cnt += DisplayHandlersInLinks(log,plinks,index + 1);
for (i = 0 ; i < plinks->classArray[index]->handlerCount ; i++)
PrintHandler(log,&plinks->classArray[index]->handlers[i],TRUE);
return(cnt);
}
#endif
/* =========================================
*****************************************
INTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
#if ! RUN_TIME
/**********************************************************
NAME : CreateSystemHandlers
DESCRIPTION : Attachess the system message-handlers
after a (clear)
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : System handlers created
NOTES : Must be called after CreateSystemClasses()
**********************************************************/
static void CreateSystemHandlers()
{
NewSystemHandler(USER_TYPE_NAME,INIT_STRING,"init-slots",0);
NewSystemHandler(USER_TYPE_NAME,DELETE_STRING,"delete-instance",0);
#if DEBUGGING_FUNCTIONS
NewSystemHandler(USER_TYPE_NAME,PRINT_STRING,"ppinstance",0);
#endif
NewSystemHandler(USER_TYPE_NAME,DIRECT_MODIFY_STRING,"(direct-modify)",1);
NewSystemHandler(USER_TYPE_NAME,MSG_MODIFY_STRING,"(message-modify)",1);
NewSystemHandler(USER_TYPE_NAME,DIRECT_DUPLICATE_STRING,"(direct-duplicate)",2);
NewSystemHandler(USER_TYPE_NAME,MSG_DUPLICATE_STRING,"(message-duplicate)",2);
}
#endif
#if (! BLOAD_ONLY) && (! RUN_TIME)
/************************************************************
NAME : WildDeleteHandler
DESCRIPTION : Deletes a handler from a class
INPUTS : 1) Class address (Can be NULL)
2) Message Handler Name (Can be NULL)
3) Type name ("primary", etc.)
RETURNS : 1 if successful, 0 otherwise
SIDE EFFECTS : Handler deleted if possible
NOTES : None
************************************************************/
static int WildDeleteHandler(
DEFCLASS *cls,
SYMBOL_HN *msym,
char *tname)
{
int mtype;
if (msym == NULL)
msym = (SYMBOL_HN *) AddSymbol("*");
if (tname != NULL)
{
mtype = HandlerType("undefmessage-handler",tname);
if (mtype == MERROR)
return(0);
}
else
mtype = -1;
if (cls == NULL)
{
int success = 1;
for (cls = (DEFCLASS *) GetNextDefclass(NULL) ;
cls != NULL ;
cls = (DEFCLASS *) GetNextDefclass((void *) cls))
if (DeleteHandler(cls,msym,mtype,FALSE) == 0)
success = 0;
return(success);
}
return(DeleteHandler(cls,msym,mtype,TRUE));
}
#endif
#if DEBUGGING_FUNCTIONS
/******************************************************************
NAME : DefmessageHandlerWatchAccess
DESCRIPTION : Parses a list of class names passed by
AddWatchItem() and sets the traces accordingly
INPUTS : 1) A code indicating which trace flag is to be set
0 - Watch instance creation/deletion
1 - Watch slot changes to instances
2) The value to which to set the trace flags
3) A list of expressions containing the names
of the classes for which to set traces
RETURNS : TRUE if all OK, FALSE otherwise
SIDE EFFECTS : Watch flags set in specified classes
NOTES : Accessory function for AddWatchItem()
******************************************************************/
#if IBM_TBC
#pragma argsused
#endif
static BOOLEAN DefmessageHandlerWatchAccess(
int code,
int newState,
EXPRESSION *argExprs)
{
#if MAC_MPW || MAC_MCW || IBM_MCW
#pragma unused(code)
#endif
if (newState)
return(DefmessageHandlerWatchSupport("watch",NULL,newState,
NULL,SetDefmessageHandlerWatch,argExprs));
else
return(DefmessageHandlerWatchSupport("unwatch",NULL,newState,
NULL,SetDefmessageHandlerWatch,argExprs));
}
/***********************************************************************
NAME : DefclassWatchPrint
DESCRIPTION : Parses a list of class names passed by
AddWatchItem() and displays the traces accordingly
INPUTS : 1) The logical name of the output
2) A code indicating which trace flag is to be examined
0 - Watch instance creation/deletion
1 - Watch slot changes to instances
3) A list of expressions containing the names
of the classes for which to examine traces
RETURNS : TRUE if all OK, FALSE otherwise
SIDE EFFECTS : Watch flags displayed for specified classes
NOTES : Accessory function for AddWatchItem()
***********************************************************************/
#if IBM_TBC
#pragma argsused
#endif
static BOOLEAN DefmessageHandlerWatchPrint(
char *log,
int code,
EXPRESSION *argExprs)
{
#if MAC_MPW || MAC_MCW || IBM_MCW
#pragma unused(code)
#endif
return(DefmessageHandlerWatchSupport("list-watch-items",log,-1,
PrintHandlerWatchFlag,NULL,argExprs));
}
/*******************************************************
NAME : DefmessageHandlerWatchSupport
DESCRIPTION : Sets or displays handlers specified
INPUTS : 1) The calling function name
2) The logical output name for displays
(can be NULL)
4) The new set state (can be -1)
5) The print function (can be NULL)
6) The trace function (can be NULL)
7) The handlers expression list
RETURNS : TRUE if all OK,
FALSE otherwise
SIDE EFFECTS : Handler trace flags set or displayed
NOTES : None
*******************************************************/
static BOOLEAN DefmessageHandlerWatchSupport(
char *funcName,
char *log,
int newState,
void (*printFunc)(char *,void *,unsigned),
void (*traceFunc)(int,void *,unsigned),
EXPRESSION *argExprs)
{
struct defmodule *theModule;
void *theClass;
char *theHandlerStr;
int theType;
int argIndex = 2;
DATA_OBJECT tmpData;
/* ===============================
If no handlers are specified,
show the trace for all handlers
in all handlers
=============================== */
if (argExprs == NULL)
{
SaveCurrentModule();
theModule = (struct defmodule *) GetNextDefmodule(NULL);
while (theModule != NULL)
{
SetCurrentModule((void *) theModule);
if (traceFunc == NULL)
{
PrintRouter(log,GetDefmoduleName((void *) theModule));
PrintRouter(log,":\n");
}
theClass = GetNextDefclass(NULL);
while (theClass != NULL)
{
if (WatchClassHandlers(theClass,NULL,-1,log,newState,
TRUE,printFunc,traceFunc) == FALSE)
return(FALSE);
theClass = GetNextDefclass(theClass);
}
theModule = (struct defmodule *) GetNextDefmodule((void *) theModule);
}
RestoreCurrentModule();
return(TRUE);
}
/* ================================================
Set or show the traces for the specified handler
================================================ */
while (argExprs != NULL)
{
if (EvaluateExpression(argExprs,&tmpData))
return(FALSE);
if (tmpData.type != SYMBOL)
{
ExpectedTypeError1(funcName,argIndex,"class name");
return(FALSE);
}
theClass = (void *) LookupDefclassByMdlOrScope(DOToString(tmpData));
if (theClass == NULL)
{
ExpectedTypeError1(funcName,argIndex,"class name");
return(FALSE);
}
if (GetNextArgument(argExprs) != NULL)
{
argExprs = GetNextArgument(argExprs);
argIndex++;
if (EvaluateExpression(argExprs,&tmpData))
return(FALSE);
if (tmpData.type != SYMBOL)
{
ExpectedTypeError1(funcName,argIndex,"handler name");
return(FALSE);
}
theHandlerStr = DOToString(tmpData);
if (GetNextArgument(argExprs) != NULL)
{
argExprs = GetNextArgument(argExprs);
argIndex++;
if (EvaluateExpression(argExprs,&tmpData))
return(FALSE);
if (tmpData.type != SYMBOL)
{
ExpectedTypeError1(funcName,argIndex,"handler type");
return(FALSE);
}
if ((theType = HandlerType(funcName,DOToString(tmpData))) == MERROR)
return(FALSE);
}
else
theType = -1;
}
else
{
theHandlerStr = NULL;
theType = -1;
}
if (WatchClassHandlers(theClass,theHandlerStr,theType,log,
newState,FALSE,printFunc,traceFunc) == FALSE)
{
ExpectedTypeError1(funcName,argIndex,"handler");
return(FALSE);
}
argIndex++;
argExprs = GetNextArgument(argExprs);
}
return(TRUE);
}
/*******************************************************
NAME : WatchClassHandlers
DESCRIPTION : Sets or displays handlers specified
INPUTS : 1) The class
2) The handler name (or NULL wildcard)
3) The handler type (or -1 wildcard)
4) The logical output name for displays
(can be NULL)
5) The new set state (can be -1)
6) The print function (can be NULL)
7) The trace function (can be NULL)
RETURNS : TRUE if all OK,
FALSE otherwise
SIDE EFFECTS : Handler trace flags set or displayed
NOTES : None
*******************************************************/
static BOOLEAN WatchClassHandlers(
void *theClass,
char *theHandlerStr,
int theType,
char *log,
int newState,
int indentp,
void (*printFunc)(char *,void *,unsigned),
void (*traceFunc)(int,void *,unsigned))
{
unsigned theHandler;
int found = FALSE;
theHandler = GetNextDefmessageHandler(theClass,0);
while (theHandler != 0)
{
if ((theType == -1) ? TRUE :
(theType == ((DEFCLASS *) theClass)->handlers[theHandler-1].type))
{
if ((theHandlerStr == NULL) ? TRUE :
(strcmp(theHandlerStr,GetDefmessageHandlerName(theClass,theHandler)) == 0))
{
if (traceFunc != NULL)
(*traceFunc)(newState,theClass,theHandler);
else
{
if (indentp)
PrintRouter(log," ");
(*printFunc)(log,theClass,theHandler);
}
found = TRUE;
}
}
theHandler = GetNextDefmessageHandler(theClass,theHandler);
}
if ((theHandlerStr != NULL) && (theType != -1) && (found == FALSE))
return(FALSE);
return(TRUE);
}
/***************************************************
NAME : PrintHandlerWatchFlag
DESCRIPTION : Displays trace value for handler
INPUTS : 1) The logical name of the output
2) The class
3) The handler index
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : None
***************************************************/
static void PrintHandlerWatchFlag(
char *log,
void *theClass,
unsigned theHandler)
{
PrintRouter(log,GetDefclassName(theClass));
PrintRouter(log," ");
PrintRouter(log,GetDefmessageHandlerName(theClass,theHandler));
PrintRouter(log," ");
PrintRouter(log,GetDefmessageHandlerType(theClass,theHandler));
if (GetDefmessageHandlerWatch(theClass,theHandler))
PrintRouter(log," = on\n");
else
PrintRouter(log," = off\n");
}
#endif /* DEBUGGING_FUNCTIONS */
#endif
/***************************************************
NAME :
DESCRIPTION :
INPUTS :
RETURNS :
SIDE EFFECTS :
NOTES :
***************************************************/
| 412 | 0.983825 | 1 | 0.983825 | game-dev | MEDIA | 0.419853 | game-dev | 0.657055 | 1 | 0.657055 |
varabyte/kobweb | 7,813 | frontend/silk-icons-fa/build.gradle.kts | plugins {
alias(libs.plugins.kotlin.multiplatform)
id("kobweb-compose")
id("com.varabyte.kobweb.internal.publish")
}
group = "com.varabyte.kobwebx"
version = libs.versions.kobweb.get()
private val GENERATED_SRC_ROOT = "build/generated/icons/src/jsMain/kotlin"
enum class IconCategory {
SOLID,
REGULAR,
BRAND,
}
val generateIconsTask = tasks.register("generateIcons") {
val srcFile = layout.projectDirectory.file("fa-icon-list.txt")
val dstFile =
layout.projectDirectory.file("$GENERATED_SRC_ROOT/com/varabyte/kobweb/silk/components/icons/fa/FaIcons.kt")
inputs.files(srcFile)
outputs.dir(GENERATED_SRC_ROOT)
doLast {
// {SOLID=[ad, address-book, address-card, ...], REGULAR=[address-book, address-card, angry, ...], ... }
val iconRawNames = srcFile.asFile
.readLines().asSequence()
.filter { line -> !line.startsWith("#") }
.map { line ->
// Convert icon name to function name, e.g.
// align-left -> FaAlignLeft
line.split("=", limit = 2).let { parts ->
val category = when (parts[0]) {
"fas" -> IconCategory.SOLID
"far" -> IconCategory.REGULAR
"fab" -> IconCategory.BRAND
else -> throw GradleException("Unexpected category string: ${parts[0]}")
}
val names = parts[1]
category to names.split(",")
}
}
.toMap()
// For each icon name, figure out what categories they are in. This will affect the function signature we generate.
// {ad=[SOLID], address-book=[SOLID, REGULAR], address-card=[SOLID, REGULAR], ...
val iconCategories = mutableMapOf<String, MutableSet<IconCategory>>()
iconRawNames.forEach { entry ->
val category = entry.key
entry.value.forEach { rawName ->
iconCategories.computeIfAbsent(rawName, { mutableSetOf() }).add(category)
}
}
// Sanity check results
iconCategories
.filterNot { entry ->
val categories = entry.value
categories.size == 1 ||
(categories.size == 2 && categories.contains(IconCategory.SOLID) && categories.contains(IconCategory.REGULAR))
}
.let { invalidGroupings ->
if (invalidGroupings.isNotEmpty()) {
throw GradleException("Found unexpected groupings. An icon should only be in its own category OR it can have solid and regular versions: $invalidGroupings")
}
}
// Generate four types of functions: solid only, regular only, solid or regular, and brand
val iconMethodEntries = iconCategories
.map { entry ->
val rawName = entry.key
// Convert e.g. "align-items" to "FaAlignItems"
@Suppress("DEPRECATION") // capitalize is way more readable than a direct replacement
val methodName = "Fa${rawName.split("-").joinToString("") { it.capitalize() }}"
val categories = entry.value
when {
categories.size == 2 -> {
"@Composable fun $methodName(modifier: Modifier = Modifier, style: IconStyle = IconStyle.OUTLINE, size: IconSize? = null) = FaIcon(\"$rawName\", modifier, style.category, size)"
}
categories.contains(IconCategory.SOLID) -> {
"@Composable fun $methodName(modifier: Modifier = Modifier, size: IconSize? = null) = FaIcon(\"$rawName\", modifier, IconCategory.SOLID, size)"
}
categories.contains(IconCategory.REGULAR) -> {
"@Composable fun $methodName(modifier: Modifier = Modifier, size: IconSize? = null) = FaIcon(\"$rawName\", modifier, IconCategory.REGULAR, size)"
}
categories.contains(IconCategory.BRAND) -> {
"@Composable fun $methodName(modifier: Modifier = Modifier, size: IconSize? = null) = FaIcon(\"$rawName\", modifier, IconCategory.BRAND, size)"
}
else -> GradleException("Unhandled icon entry: $entry")
}
}
val iconsCode =
"""
|//@formatter:off
|@file:Suppress("unused", "SpellCheckingInspection")
|
|// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|// THIS FILE IS AUTOGENERATED.
|//
|// Do not edit this file by hand. Instead, update `fa-icon-list.txt` in the module root and run the Gradle
|// task "generateIcons"
|// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
|package com.varabyte.kobweb.silk.components.icons.fa
|
|import androidx.compose.runtime.*
|import com.varabyte.kobweb.compose.ui.Modifier
|import com.varabyte.kobweb.compose.ui.toAttrs
|import org.jetbrains.compose.web.dom.Span
|
|enum class IconCategory(internal val className: String) {
| REGULAR("far"),
| SOLID("fas"),
| BRAND("fab");
|}
|
|enum class IconStyle(internal val category: IconCategory) {
| FILLED(IconCategory.SOLID),
| OUTLINE(IconCategory.REGULAR);
|}
|
|// See: https://fontawesome.com/docs/web/style/size
|enum class IconSize(internal val className: String) {
| // Relative sizes
| XXS("fa-2xs"),
| XS("fa-xs"),
| SM("fa-sm"),
| LG("fa-lg"),
| XL("fa-xl"),
| XXL("fa-2xl"),
|
| // Literal sizes
| X1("fa-1x"),
| X2("fa-2x"),
| X3("fa-3x"),
| X4("fa-4x"),
| X5("fa-5x"),
| X6("fa-6x"),
| X7("fa-7x"),
| X8("fa-8x"),
| X9("fa-9x"),
| X10("fa-10x");
|}
|
|@Composable
|fun FaIcon(
| name: String,
| modifier: Modifier,
| style: IconCategory = IconCategory.REGULAR,
| size: IconSize? = null,
|) {
| Span(
| attrs = modifier.toAttrs {
| classes(style.className, "fa-${'$'}name")
| if (size != null) {
| classes(size.className)
| }
| }
| )
|}
|
|${iconMethodEntries.joinToString("\n")}
""".trimMargin()
dstFile.asFile.apply {
parentFile.mkdirs()
writeText(iconsCode)
}
}
}
kotlin {
js {
browser()
}
sourceSets {
jsMain {
kotlin.srcDir(generateIconsTask)
dependencies {
implementation(libs.compose.runtime)
implementation(libs.compose.html.core)
api(projects.frontend.kobwebCompose)
}
}
}
}
kobwebPublication {
artifactName.set("Kobweb Silk Icons (Font Awesome)")
artifactId.set("silk-icons-fa")
description.set("A collection of composables that directly wrap Font Awesome icons.")
}
| 412 | 0.78657 | 1 | 0.78657 | game-dev | MEDIA | 0.452711 | game-dev | 0.961 | 1 | 0.961 |
Realizedd/Duels | 2,344 | duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/InfoCommand.java | package me.realized.duels.command.commands.duels.subcommands;
import java.util.List;
import java.util.stream.Collectors;
import me.realized.duels.DuelsPlugin;
import me.realized.duels.arena.ArenaImpl;
import me.realized.duels.command.BaseCommand;
import me.realized.duels.kit.KitImpl;
import me.realized.duels.util.StringUtil;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class InfoCommand extends BaseCommand {
public InfoCommand(final DuelsPlugin plugin) {
super(plugin, "info", "info [name]", "Displays information about the selected arena.", 2, false);
}
@Override
protected void execute(final CommandSender sender, final String label, final String[] args) {
final String name = StringUtil.join(args, " ", 1, args.length).replace("-", " ");
final ArenaImpl arena = arenaManager.get(name);
if (arena == null) {
lang.sendMessage(sender, "ERROR.arena.not-found", "name", name);
return;
}
final String inUse = arena.isUsed() ? lang.getMessage("GENERAL.true") : lang.getMessage("GENERAL.false");
final String disabled = arena.isDisabled() ? lang.getMessage("GENERAL.true") : lang.getMessage("GENERAL.false");
final String kits = StringUtil.join(arena.getKits().stream().map(KitImpl::getName).collect(Collectors.toList()), ", ");
final String positions = StringUtil.join(arena.getPositions().values().stream().map(StringUtil::parse).collect(Collectors.toList()), ", ");
final String players = StringUtil.join(arena.getPlayers().stream().map(Player::getName).collect(Collectors.toList()), ", ");
lang.sendMessage(sender, "COMMAND.duels.info", "name", name, "in_use", inUse, "disabled", disabled, "kits",
!kits.isEmpty() ? kits : lang.getMessage("GENERAL.none"), "positions", !positions.isEmpty() ? positions : lang.getMessage("GENERAL.none"), "players",
!players.isEmpty() ? players : lang.getMessage("GENERAL.none"));
}
@Override
public List<String> onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) {
if (args.length == 2) {
return handleTabCompletion(args[1], arenaManager.getNames());
}
return null;
}
}
| 412 | 0.842229 | 1 | 0.842229 | game-dev | MEDIA | 0.929593 | game-dev | 0.874684 | 1 | 0.874684 |
jjant/runty8 | 6,017 | src/runty8-editor/src/controller.rs | use std::fmt::Debug;
use crate::ui::DispatchEvent;
use crate::util::vec2::Vec2i;
use crate::{
app::{AppCompat, ElmApp},
editor::{self, key_combo::KeyCombos, Editor},
ui::Element,
Resources,
};
use runty8_core::{DrawData, Event, InputEvent, Key, KeyboardEvent, MouseEvent, Pico8};
#[derive(Debug, Clone, Copy)]
pub(crate) enum Msg<AppMsg> {
Editor(editor::Msg),
App(AppMsg),
KeyboardEvent(KeyboardEvent),
MouseEvent(MouseEvent),
Tick,
}
#[derive(Copy, Clone, Debug)]
enum KeyComboAction {
RestartGame,
SwitchScene,
}
#[derive(Debug)]
pub(crate) struct Controller<Game> {
scene: Scene,
editor: Editor,
app: Game,
key_combos: KeyCombos<KeyComboAction>,
pico8: Pico8,
mouse_position: Vec2i,
/// The editor and the game can modify the "draw state" (`draw_data`): camera, palette, etc.
/// In order for these settings not to spill from the game to the editor, and viceversa,
/// we keep an alternate [`DrawData`] that we swap, when the scene changes.
alternate_draw_data: DrawData,
}
impl<T> Controller<T> {
pub(crate) fn screen_buffer(&self) -> &[u8] {
self.pico8.draw_data.buffer()
}
pub(crate) fn take_new_title(&mut self) -> Option<String> {
self.pico8.take_new_title()
}
}
impl<Game: AppCompat> Controller<Game> {
pub fn init(scene: Scene, resources: Resources) -> Self {
let mut pico8 = Pico8::new(resources);
Self {
scene,
editor: <Editor as ElmApp>::init(),
app: Game::init(&mut pico8),
key_combos: KeyCombos::new()
.push(KeyComboAction::RestartGame, Key::R, &[Key::Control])
.push(KeyComboAction::SwitchScene, Key::Escape, &[]),
pico8,
mouse_position: Vec2i::new(64, 64),
alternate_draw_data: DrawData::new(),
}
}
fn update(&mut self, msg: &Msg<Game::Msg>) {
match msg {
Msg::Editor(editor_msg) => {
<Editor as ElmApp>::update(&mut self.editor, editor_msg, &mut self.pico8.resources);
}
Msg::App(msg) => {
self.app.update(msg, &mut self.pico8);
}
&Msg::KeyboardEvent(event) => {
self.handle_key_combos(event);
}
// Currently the mouse position is tracked by two things independently:
// - Updated by this subscription here in the controller, stored in `self.mouse_position`
// - Updated by the Game, stored in the controller as well, in `self.pico8.state.mouse_{x,y}`
//
// I haven't found yet a nice way to unify them that plays nicely with both,
// and can be run in the editor or in the runtime by itself.
&Msg::MouseEvent(MouseEvent::Move { x, y }) => {
self.mouse_position = Vec2i::new(x, y);
}
&Msg::MouseEvent(MouseEvent::Button { .. }) => {}
&Msg::Tick => {}
}
}
fn subscriptions(&self, event: &Event) -> Vec<Msg<Game::Msg>> {
let sub_msgs: Vec<Msg<Game::Msg>> = match self.scene {
Scene::Editor => <Editor as ElmApp>::subscriptions(&self.editor, event)
.into_iter()
.map(Msg::Editor)
.collect(),
Scene::App => <Game as AppCompat>::subscriptions(&self.app, event)
.into_iter()
.map(Msg::App)
.collect(),
};
let own_msgs = match event {
Event::Input(InputEvent::Mouse(mouse_event)) => Some(Msg::MouseEvent(*mouse_event)),
Event::Input(InputEvent::Keyboard(keyboard_event)) => {
Some(Msg::KeyboardEvent(*keyboard_event))
}
Event::Tick { .. } => Some(Msg::Tick),
Event::WindowClosed => todo!("WindowClosed event not yet handled"),
}
.into_iter();
sub_msgs.into_iter().chain(own_msgs).collect()
}
}
fn view<'a, Game: AppCompat>(
scene: &'a Scene,
editor: &'a mut Editor,
app: &'a mut Game,
resources: &mut Resources,
) -> Element<'a, Msg<Game::Msg>> {
match scene {
Scene::Editor => <Editor as ElmApp>::view(editor, resources).map(Msg::Editor),
Scene::App => app.view(resources).map(Msg::App),
}
}
impl<Game: AppCompat> Controller<Game> {
// TODO: Why doesn't this function simply return a [`Msg`]?
fn handle_key_combos(&mut self, key_event: KeyboardEvent) {
self.key_combos.on_event(key_event, |action| match action {
KeyComboAction::RestartGame => {
self.app = Game::init(&mut self.pico8);
self.scene = Scene::App;
}
KeyComboAction::SwitchScene => {
std::mem::swap(&mut self.pico8.draw_data, &mut self.alternate_draw_data);
self.scene.flip()
}
});
}
/// Thing that actually calls update/orchestrates stuff
pub(crate) fn step(&mut self, event: Event) {
let mut view = view(
&self.scene,
&mut self.editor,
&mut self.app,
&mut self.pico8.resources,
);
let mut msg_queue = vec![];
let dispatch_event = &mut DispatchEvent::new(&mut msg_queue);
let mouse_position = (self.mouse_position.x, self.mouse_position.y);
view.as_widget_mut()
.on_event(event, mouse_position, dispatch_event);
view.as_widget_mut().draw(&mut self.pico8);
drop(view);
for subscription_msg in self.subscriptions(&event) {
msg_queue.push(subscription_msg);
}
for msg in msg_queue.into_iter() {
self.update(&msg);
}
}
}
#[derive(Debug)]
pub enum Scene {
Editor,
App,
}
impl Scene {
pub fn flip(&mut self) {
*self = match self {
Scene::Editor => Scene::App,
Scene::App => Scene::Editor,
}
}
}
| 412 | 0.803153 | 1 | 0.803153 | game-dev | MEDIA | 0.590773 | game-dev,desktop-app | 0.900483 | 1 | 0.900483 |
focus-creative-games/luban_examples | 1,868 | Projects/Csharp_Unity_json/Assets/Gen/ai.BlackboardKey.cs |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using Luban;
using SimpleJSON;
namespace cfg.ai
{
public sealed partial class BlackboardKey : Luban.BeanBase
{
public BlackboardKey(JSONNode _buf)
{
{ if(!_buf["name"].IsString) { throw new SerializationException(); } Name = _buf["name"]; }
{ if(!_buf["desc"].IsString) { throw new SerializationException(); } Desc = _buf["desc"]; }
{ if(!_buf["is_static"].IsBoolean) { throw new SerializationException(); } IsStatic = _buf["is_static"]; }
{ if(!_buf["type"].IsNumber) { throw new SerializationException(); } Type = (ai.EKeyType)_buf["type"].AsInt; }
{ if(!_buf["type_class_name"].IsString) { throw new SerializationException(); } TypeClassName = _buf["type_class_name"]; }
}
public static BlackboardKey DeserializeBlackboardKey(JSONNode _buf)
{
return new ai.BlackboardKey(_buf);
}
public readonly string Name;
public readonly string Desc;
public readonly bool IsStatic;
public readonly ai.EKeyType Type;
public readonly string TypeClassName;
public const int __ID__ = -511559886;
public override int GetTypeId() => __ID__;
public void ResolveRef(Tables tables)
{
}
public override string ToString()
{
return "{ "
+ "name:" + Name + ","
+ "desc:" + Desc + ","
+ "isStatic:" + IsStatic + ","
+ "type:" + Type + ","
+ "typeClassName:" + TypeClassName + ","
+ "}";
}
}
}
| 412 | 0.814468 | 1 | 0.814468 | game-dev | MEDIA | 0.862202 | game-dev | 0.765424 | 1 | 0.765424 |
Moulberry/Flashback | 1,693 | src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerLoginPacketListenerImpl.java | package com.moulberry.flashback.mixin.replay_server;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.network.protocol.login.ServerboundHelloPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerLoginPacketListenerImpl;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
@Mixin(ServerLoginPacketListenerImpl.class)
public abstract class MixinServerLoginPacketListenerImpl {
@Shadow
@Final
MinecraftServer server;
@Shadow
abstract void startClientVerification(GameProfile gameProfile);
@Shadow
@Nullable
String requestedUsername;
@Inject(method = "handleHello", at = @At("HEAD"), cancellable = true)
public void handleHello(ServerboundHelloPacket serverboundHelloPacket, CallbackInfo ci) {
if (this.server instanceof ReplayServer) {
this.requestedUsername = ReplayServer.REPLAY_VIEWER_NAME;
UUID replayViewerUUID = UUID.nameUUIDFromBytes(serverboundHelloPacket.name().getBytes(StandardCharsets.UTF_8));
GameProfile gameProfile = new GameProfile(replayViewerUUID, ReplayServer.REPLAY_VIEWER_NAME);
this.startClientVerification(gameProfile);
ci.cancel();
}
}
}
| 412 | 0.885534 | 1 | 0.885534 | game-dev | MEDIA | 0.861897 | game-dev | 0.925966 | 1 | 0.925966 |
Szuszi/CityGenerator-Unity | 10,830 | CityGenerator2D/Assets/Procedural City Generator/Scripts/RoadGeneration/MajorGenerator.cs | using System;
using System.Collections.Generic;
using GraphModel;
using UnityEngine;
namespace RoadGeneration
{
/**
* This class will implement the extended L-system
*/
class MajorGenerator
{
private readonly List<RoadSegment> globalGoalsRoads;
private readonly List<RoadSegment> queue;
private readonly List<RoadSegment> segments;
private readonly System.Random rand;
private readonly int border;
private readonly int maxSegment;
private readonly int maxLean;
private readonly float branchProbability;
private readonly Graph graph;
private const int RoadLength = 10;
public MajorGenerator(
System.Random seededRandom,
int mapSize,
int maxRoad,
int maxDegree,
float branchingChance,
Graph graphToBuild)
{
globalGoalsRoads = new List<RoadSegment>();
queue = new List<RoadSegment>();
segments = new List<RoadSegment>();
rand = seededRandom;
border = mapSize;
maxSegment = maxRoad;
maxLean = maxDegree;
branchProbability = branchingChance;
graph = graphToBuild;
}
public void Run()
{
GenerateStartSegments();
while (queue.Count != 0 && segments.Count < maxSegment)
{
RoadSegment current = queue[0];
queue.RemoveAt(0);
if (!CheckLocalConstraints(current)) continue;
segments.Add(current);
AddToGraph(current);
GlobalGoals(current);
}
if (segments.Count == maxSegment) Debug.Log("Major Roads reached maximal amount");
}
private bool CheckLocalConstraints(RoadSegment segment)
{
foreach (RoadSegment road in segments)
{
//If the new segment end is close to another segments Node, Fix it's end to it
if (IsClose(segment.NodeTo, road.NodeTo))
{
segment.NodeTo = road.NodeTo;
segment.EndSegment = true;
}
if (segment.IsCrossing(road)) return false; //Check if segment is crossing an other road
}
//Check if segment is out of border
if (segment.NodeFrom.X > border || segment.NodeFrom.X < -border
|| segment.NodeFrom.Y > border || segment.NodeFrom.Y < -border) return false;
//Check if segment would come into itself
if (segment.NodeFrom.X == segment.NodeTo.X && segment.NodeFrom.Y == segment.NodeTo.Y) return false;
//nodeTo or nodeFrom has more than 4 edges
if (segment.NodeTo.Edges.Count >= 4 || segment.NodeFrom.Edges.Count >= 4) return false;
foreach (Edge edge in segment.NodeTo.Edges)
{
//NodeTo already connected to NodeFrom
if(edge.NodeA == segment.NodeFrom || edge.NodeB == segment.NodeFrom) return false;
}
return true;
}
private void GlobalGoals(RoadSegment segment)
{
if (segment.EndSegment) return;
globalGoalsRoads.Clear();
var dirVector = segment.GetDirVector();
//BRANCHING
int maxInt = (int) Math.Round(3 / branchProbability);
if (branchProbability > 0.3) //Maximum branch probability is 3 out of 10 (0.3)
{
maxInt = 6;
}
else if (branchProbability < 0.03) //Minimum branch probability is 3 out of 100 (0.03)
{
maxInt = 100;
}
int branchRandom = rand.Next(0, maxInt);
if (branchRandom == 1) //the road branches out to the RIGHT
{
var normalVector = new Vector2(dirVector.y, -dirVector.x);
RoadSegment branchedSegment = CalcNewRoadSegment(segment.NodeTo, normalVector, 0);
globalGoalsRoads.Add(branchedSegment);
}
else if (branchRandom == 2) //The road branches out to the LEFT
{
var normalVector = new Vector2(-dirVector.y, dirVector.x);
RoadSegment branchedSegment = CalcNewRoadSegment(segment.NodeTo, normalVector, 0);
globalGoalsRoads.Add(branchedSegment);
}
else if (branchRandom == 3) //The road branches out to BOTH DIRECTIONS
{
var normalVector1 = new Vector2(dirVector.y, -dirVector.x);
var normalVector2 = new Vector2(-dirVector.y, dirVector.x);
RoadSegment branchedSegment1 = CalcNewRoadSegment(segment.NodeTo, normalVector1, 0);
RoadSegment branchedSegment2 = CalcNewRoadSegment(segment.NodeTo, normalVector2, 0);
globalGoalsRoads.Add(branchedSegment1);
globalGoalsRoads.Add(branchedSegment2);
}
//ROAD CONTINUE
globalGoalsRoads.Add(GetContinuingRoadSegment(segment));
foreach (RoadSegment newSegment in globalGoalsRoads)
{
queue.Add(newSegment);
}
}
private RoadSegment GetContinuingRoadSegment(RoadSegment segment)
{
var dirVector = segment.GetDirVector();
if (maxLean < 1) return CalcNewRoadSegment(segment.NodeTo, dirVector, 0);
if (segment.LeanIteration == 3) //Check if we need a new lean. If yes, calculate the next RoadSegment
{
var randomNumber = rand.Next(0, 3);
if (randomNumber == 1)
{
dirVector = RotateVector(dirVector, GetRandomAngle(2, maxLean * 2));
RoadSegment newSegment = CalcNewRoadSegment(segment.NodeTo, dirVector, 0);
newSegment.LeanLeft = true;
return newSegment;
}
else if (randomNumber == 2)
{
dirVector = RotateVector(dirVector, GetRandomAngle(-2, -maxLean * 2));
RoadSegment newSegment = CalcNewRoadSegment(segment.NodeTo, dirVector, 0);
newSegment.LeanRight = true;
return newSegment;
}
else
{
return CalcNewRoadSegment(segment.NodeTo, dirVector, 0);
}
}
else //if not, grow the new segment following the lean
{
if (segment.LeanLeft)
{
dirVector = RotateVector(dirVector, GetRandomAngle(2, maxLean));
RoadSegment segment1 = CalcNewRoadSegment(segment.NodeTo, dirVector, segment.LeanIteration + 1);
segment1.LeanLeft = true;
return segment1;
}
else if (segment.LeanRight)
{
dirVector = RotateVector(dirVector, GetRandomAngle(-2, -maxLean));
RoadSegment segment1 = CalcNewRoadSegment(segment.NodeTo, dirVector, segment.LeanIteration + 1);
segment1.LeanRight = true;
return segment1;
}
else
{
return CalcNewRoadSegment(segment.NodeTo, dirVector, segment.LeanIteration + 1);
}
}
}
private void GenerateStartSegments()
{
//First Generate a number nearby the middle quarter of the map
int sampleX = rand.Next(0, (border * 100));
int sampleY = rand.Next(0, (border * 100));
float starterX = (sampleX / 100.0f) - (float)border/2;
float starterY = (sampleY / 100.0f) - (float)border/2;
var startNode = new Node(starterX, starterY);
//Secondly Generate a vector which determines the two starting directions
int randomDirX = rand.Next(-100, 100);
int randomDirY = rand.Next(-100, 100);
var startDir = new Vector2(randomDirX, randomDirY);
var starterNodeTo1 = new Node(startNode.X + startDir.normalized.x * RoadLength, starterY + startDir.normalized.y * RoadLength);
var starterNodeTo2 = new Node(startNode.X - startDir.normalized.x * RoadLength, starterY - startDir.normalized.y * RoadLength);
//Thirdly We make two starting RoadSegment from these
var starterSegment1 = new RoadSegment(startNode, starterNodeTo1, 0);
var starterSegment2 = new RoadSegment(startNode, starterNodeTo2, 0);
queue.Add(starterSegment1);
queue.Add(starterSegment2);
}
private void AddToGraph(RoadSegment road)
{
if (!graph.MajorNodes.Contains(road.NodeFrom)) graph.MajorNodes.Add(road.NodeFrom);
if (!graph.MajorNodes.Contains(road.NodeTo)) graph.MajorNodes.Add(road.NodeTo);
graph.MajorEdges.Add(new Edge(road.NodeFrom, road.NodeTo));
}
private float GetRandomAngle(int a, int b) //Calculates an Angle between a and b, returns it in radian
{
//First we make 'a' smaller, and generate a random number in the range
if(b < a)
{
(b, a) = (a, b);
}
int range = Math.Abs(b - a);
int rotation = rand.Next(0, range) + a;
//then we make it to radian, and return it
float rotationAngle = (float)(Math.PI / 180) * rotation;
return rotationAngle;
}
private Vector2 RotateVector(Vector2 dirVector, float rotationAngle)
{
//This works like a rotation matrix
dirVector.x = ((float)Math.Cos(rotationAngle) * dirVector.x) - ((float)Math.Sin(rotationAngle) * dirVector.y);
dirVector.y = ((float)Math.Sin(rotationAngle) * dirVector.x) + ((float)Math.Cos(rotationAngle) * dirVector.y);
return dirVector;
}
private bool IsClose(Node a, Node b)
{
float idealRadius = RoadLength * 0.8f;
if (a.getDistance(b) < idealRadius) return true;
return false;
}
private RoadSegment CalcNewRoadSegment(Node nodeFrom, Vector2 dirVector, int leanIteration)
{
var newNodeTo = new Node(nodeFrom.X + dirVector.normalized.x * RoadLength, nodeFrom.Y + dirVector.normalized.y * RoadLength);
return new RoadSegment(nodeFrom, newNodeTo, leanIteration);
}
public List<RoadSegment> GetRoadSegments()
{
return segments;
}
}
}
| 412 | 0.901792 | 1 | 0.901792 | game-dev | MEDIA | 0.421868 | game-dev | 0.986353 | 1 | 0.986353 |
pixelcmtd/CXClient | 4,900 | src/minecraft/net/minecraft/world/gen/layer/GenLayerBiome.java | package net.minecraft.world.gen.layer;
import net.minecraft.world.WorldType;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.gen.ChunkProviderSettings;
public class GenLayerBiome extends GenLayer
{
private BiomeGenBase[] field_151623_c = new BiomeGenBase[] {BiomeGenBase.desert, BiomeGenBase.desert, BiomeGenBase.desert, BiomeGenBase.savanna, BiomeGenBase.savanna, BiomeGenBase.plains};
private BiomeGenBase[] field_151621_d = new BiomeGenBase[] {BiomeGenBase.forest, BiomeGenBase.roofedForest, BiomeGenBase.extremeHills, BiomeGenBase.plains, BiomeGenBase.birchForest, BiomeGenBase.swampland};
private BiomeGenBase[] field_151622_e = new BiomeGenBase[] {BiomeGenBase.forest, BiomeGenBase.extremeHills, BiomeGenBase.taiga, BiomeGenBase.plains};
private BiomeGenBase[] field_151620_f = new BiomeGenBase[] {BiomeGenBase.icePlains, BiomeGenBase.icePlains, BiomeGenBase.icePlains, BiomeGenBase.coldTaiga};
private final ChunkProviderSettings field_175973_g;
public GenLayerBiome(long p_i45560_1_, GenLayer p_i45560_3_, WorldType p_i45560_4_, String p_i45560_5_)
{
super(p_i45560_1_);
this.parent = p_i45560_3_;
if (p_i45560_4_ == WorldType.DEFAULT_1_1)
{
this.field_151623_c = new BiomeGenBase[] {BiomeGenBase.desert, BiomeGenBase.forest, BiomeGenBase.extremeHills, BiomeGenBase.swampland, BiomeGenBase.plains, BiomeGenBase.taiga};
this.field_175973_g = null;
}
else if (p_i45560_4_ == WorldType.CUSTOMIZED)
{
this.field_175973_g = ChunkProviderSettings.Factory.jsonToFactory(p_i45560_5_).func_177864_b();
}
else
{
this.field_175973_g = null;
}
}
/**
* Returns a list of integer values generated by this layer. These may be interpreted as temperatures, rainfall
* amounts, or biomeList[] indices based on the particular GenLayer subclass.
*/
public int[] getInts(int areaX, int areaY, int areaWidth, int areaHeight)
{
int[] aint = this.parent.getInts(areaX, areaY, areaWidth, areaHeight);
int[] aint1 = IntCache.getIntCache(areaWidth * areaHeight);
for (int i = 0; i < areaHeight; ++i)
{
for (int j = 0; j < areaWidth; ++j)
{
this.initChunkSeed((long)(j + areaX), (long)(i + areaY));
int k = aint[j + i * areaWidth];
int l = (k & 3840) >> 8;
k = k & -3841;
if (this.field_175973_g != null && this.field_175973_g.fixedBiome >= 0)
{
aint1[j + i * areaWidth] = this.field_175973_g.fixedBiome;
}
else if (isBiomeOceanic(k))
{
aint1[j + i * areaWidth] = k;
}
else if (k == BiomeGenBase.mushroomIsland.biomeID)
{
aint1[j + i * areaWidth] = k;
}
else if (k == 1)
{
if (l > 0)
{
if (this.nextInt(3) == 0)
{
aint1[j + i * areaWidth] = BiomeGenBase.mesaPlateau.biomeID;
}
else
{
aint1[j + i * areaWidth] = BiomeGenBase.mesaPlateau_F.biomeID;
}
}
else
{
aint1[j + i * areaWidth] = this.field_151623_c[this.nextInt(this.field_151623_c.length)].biomeID;
}
}
else if (k == 2)
{
if (l > 0)
{
aint1[j + i * areaWidth] = BiomeGenBase.jungle.biomeID;
}
else
{
aint1[j + i * areaWidth] = this.field_151621_d[this.nextInt(this.field_151621_d.length)].biomeID;
}
}
else if (k == 3)
{
if (l > 0)
{
aint1[j + i * areaWidth] = BiomeGenBase.megaTaiga.biomeID;
}
else
{
aint1[j + i * areaWidth] = this.field_151622_e[this.nextInt(this.field_151622_e.length)].biomeID;
}
}
else if (k == 4)
{
aint1[j + i * areaWidth] = this.field_151620_f[this.nextInt(this.field_151620_f.length)].biomeID;
}
else
{
aint1[j + i * areaWidth] = BiomeGenBase.mushroomIsland.biomeID;
}
}
}
return aint1;
}
}
| 412 | 0.612637 | 1 | 0.612637 | game-dev | MEDIA | 0.932888 | game-dev | 0.655684 | 1 | 0.655684 |
RetroAchievements/RAEmus | 23,571 | RAPCE/PadConfig.cpp | /******************************************************************************
Ootake
EPCEpbh1`5ɃL[{[h̃L[܂߂ĎRɊ蓖Ăł悤ɂB
EWindowsp16{^pbhƃnbgXCb`iAiOΉpbhł悭gĂ
jɂΉB
Ev0.54BWCpbh͂̔蕔Q[{ԓlDirectInputōs悤ɂ
Bi0.53ȑÔQ{ȏWCpbhȂłƂ̕sj
EAːp{^̐ݒljBQ{^CR{^pbhɁA{^T,Ů
ė̈gpBiU{^pbhɂ͐ݒłȂdlj
Ep{^̐ݒljB
EXe[gZ[up{^̐ݒljB
EXN[Vbgp{^̐ݒljB
Copyright(C)2006-2010 Kitao Nakamura.
ŁEpłJȂƂ͕K\[XR[hYtĂB
̍ۂɎł܂܂̂ŁAЂƂƂm点ƍKłB
Iȗp͋ւ܂B
Ƃ́uGNU General Public License(ʌOp_)vɏ܂B
*******************************************************************************
[PadConfig.c]
Implements a pad configuration window.
Copyright (C) 2005 Ki
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.
******************************************************************************/
#define _CRT_SECURE_NO_DEPRECATE
#define DIRECTINPUT_VERSION 0x0800 //KitaoljBɂ邩ȂADirectInput5yB7ƂxBXy[XnA[킩₷B
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "PadConfig.h"
#include "resource.h"
#include "WinMain.h"
#include "Input.h"
#include "JoyPad.h" //Kitaolj
#define PADCONFIG_CAPTION "Pad Configuration"
#define LINE_LEN 70 //KitaoXV
#define N_LINES 20
#define N_MAXJOYSTICK 5
//KitaoXVBnbgXCb`16{^pbhɂΉB
static const Sint32 button[INPUT_NUM_BUTTON] =
{
INPUT_JOYSTICK_UP, INPUT_JOYSTICK_RIGHT, INPUT_JOYSTICK_DOWN, INPUT_JOYSTICK_LEFT,
INPUT_JOYSTICK_POVUP, INPUT_JOYSTICK_POVRIGHT, INPUT_JOYSTICK_POVDOWN, INPUT_JOYSTICK_POVLEFT,
INPUT_JOYSTICK_BUTTON1, INPUT_JOYSTICK_BUTTON2, INPUT_JOYSTICK_BUTTON3, INPUT_JOYSTICK_BUTTON4,
INPUT_JOYSTICK_BUTTON5, INPUT_JOYSTICK_BUTTON6, INPUT_JOYSTICK_BUTTON7, INPUT_JOYSTICK_BUTTON8,
INPUT_JOYSTICK_BUTTON9, INPUT_JOYSTICK_BUTTON10, INPUT_JOYSTICK_BUTTON11, INPUT_JOYSTICK_BUTTON12,
INPUT_JOYSTICK_BUTTON13, INPUT_JOYSTICK_BUTTON14, INPUT_JOYSTICK_BUTTON15, INPUT_JOYSTICK_BUTTON16
};
typedef struct
{
DIJOYSTATE2 joyState;
Uint32 buttonState; //KitaoXVB16{^ɑΉBnbgXCb`Ԃꂽ̂Uint32ɁB
} JOYSTICK;
//KitaoljBDirectInputgpB
static LPDIRECTINPUT _pDI = NULL; // DirectInput C^[tF[X|C^
static LPDIRECTINPUTDEVICE _pDIDKey = NULL; // DirectInput Keyboard device
static LPDIRECTINPUTDEVICE2 _pDIDJoy[N_MAXJOYSTICK]; // DirectInput Joystick device
static Uint32 _FontWidth;
static Uint32 _FontHeight;
static const char* _pCaption = PADCONFIG_CAPTION;
static HINSTANCE _hInstance = NULL;
static HWND _hWnd;
static BOOL _bWindowCreated; //Kitaolj
static char* _pText[N_LINES];
static char _Text[N_LINES][LINE_LEN];
static Uint32 _Line = 0;
static Sint32 _nJoySticks;
static JOYSTICK _Joystick[N_MAXJOYSTICK];
static Sint32 _Mode; //KitaoljB0cʏ̐ݒB1cAːp{^̐ݒB2cp{^̐ݒB3cXe[gZ[up{^̐ݒB4cXe[g[hp{^̐ݒB
// 5cXN[Vbgp{^̐ݒB6ct@NVp{^̐ݒB7ct@NV{^̃Xe[gZ[u[hp{^̐ݒB
// 8c|[Yp{^̐ݒB
static Sint32 _PadID; //Kitaolj
static PCEPAD* _pPad; //Kitaolj
static Sint32 _SetOk = -1; //KitaoljB߂lBݒ芮Ȃ1BLZȂ-1Bݒ蒆0B
static Sint32* _pSetOk = 0; //Kitaolj
static char _DIKeys[256]; //KitaoljBL[{[h̏ԗp
/* tHg̍擾 */
static Uint32
get_font_height(
HWND hWnd)
{
HDC hDC;
HFONT hFont;
HFONT hFontOld;
TEXTMETRIC tm;
hDC = GetDC(hWnd);
hFont = (HFONT)GetStockObject(OEM_FIXED_FONT); /* Œsb`tHg */
hFontOld = (HFONT)SelectObject(hDC, hFont);
GetTextMetrics(hDC, &tm);
SelectObject(hDC, hFontOld);
DeleteObject(hFont);
ReleaseDC(hWnd, hDC);
return (Uint32)(tm.tmHeight);
}
/* tHg̉擾 */
static Uint32
get_font_width(
HWND hWnd)
{
HDC hDC;
HFONT hFont;
HFONT hFontOld;
TEXTMETRIC tm;
hDC = GetDC(hWnd);
hFont = (HFONT)GetStockObject(OEM_FIXED_FONT); /* Œsb`tHg */
hFontOld = (HFONT)SelectObject(hDC, hFont);
GetTextMetrics(hDC, &tm);
SelectObject(hDC, hFontOld);
DeleteObject(hFont);
ReleaseDC(hWnd, hDC);
return (Uint32)tm.tmAveCharWidth;
}
//KitaoXV
static void
set_window_size(
HWND hWnd)
{
RECT rc;
Uint32 wndW = _FontWidth * LINE_LEN;
Uint32 wndH = _FontHeight * N_LINES;
int y;
SetRect(&rc, 0, 0, wndW, wndH);
AdjustWindowRectEx(&rc, GetWindowLong(hWnd, GWL_STYLE),
GetMenu(hWnd) != NULL, GetWindowLong(hWnd, GWL_EXSTYLE));
wndW = rc.right - rc.left;
wndH = rc.bottom - rc.top;
GetWindowRect(WINMAIN_GetHwnd(), &rc);
y = rc.top;
if (y + (int)wndH > GetSystemMetrics(SM_CYSCREEN))
{
y = GetSystemMetrics(SM_CYSCREEN) - wndH ;
if (y<0) y=0;
}
MoveWindow(hWnd, rc.left, y, wndW, wndH, TRUE);
}
static void
update_window(
HWND hWnd)
{
HDC hDC;
HFONT hFont;
HFONT hFontOld;
PAINTSTRUCT ps;
Uint32 i;
/* `揀 */
hDC = BeginPaint(hWnd, &ps);
hFont = (HFONT)GetStockObject(OEM_FIXED_FONT);
hFontOld = (HFONT)SelectObject(hDC, hFont);
SetBkColor(hDC, RGB(0,0,0));
SetTextColor(hDC, RGB(224, 224, 224));
/* ̔wihԂ */
SetBkMode(hDC, OPAQUE);
for (i=0; i<_Line; i++)
{
TextOut(hDC, 0, i*_FontHeight, _pText[i], strlen(_pText[i]));
}
/* I */
EndPaint(hWnd, &ps);
SelectObject(hDC, hFontOld);
DeleteObject(hFont);
ReleaseDC(hWnd, hDC);
}
static void
add_text(
const char* pText, ...)
{
Uint32 i;
va_list ap;
char* p;
va_start(ap, pText);
vsprintf(_pText[_Line++], pText, ap);
va_end(ap);
// scroll a line
if (_Line == N_LINES)
{
p = _pText[0];
for (i = 1; i < N_LINES; ++i)
{
_pText[i-1] = _pText[i];
}
_pText[N_LINES-1] = p;
*p = '\0';
--_Line;
}
InvalidateRect(_hWnd, NULL, FALSE); //KitaoXV
UpdateWindow(_hWnd);
}
/*-----------------------------------------------------------------------------
[joypad_update_state]
͏XV܂B
-----------------------------------------------------------------------------*/
static void
joypad_update_state()
{
int i;
HRESULT hResult;
for (i = 0; i < _nJoySticks; i++)
{
// |[OsȂ
hResult = _pDIDJoy[i]->Poll();
if (hResult != DI_OK) //sƂ̓ANZX蒼Ă蒼
{
_pDIDJoy[i]->Acquire();
_pDIDJoy[i]->Poll();
}
// WCXeBbN̏Ԃǂ
_pDIDJoy[i]->GetDeviceState(sizeof(DIJOYSTATE2), &_Joystick[i].joyState);
// {^̏ԂXV (Ƃ肠 12 ̃{^ɑΉ) KitaoXVB16̃{^ɑΉ
_Joystick[i].buttonState = 0;
if (_Joystick[i].joyState.rgbButtons[0] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON1;
if (_Joystick[i].joyState.rgbButtons[1] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON2;
if (_Joystick[i].joyState.rgbButtons[2] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON3;
if (_Joystick[i].joyState.rgbButtons[3] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON4;
if (_Joystick[i].joyState.rgbButtons[4] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON5;
if (_Joystick[i].joyState.rgbButtons[5] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON6;
if (_Joystick[i].joyState.rgbButtons[6] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON7;
if (_Joystick[i].joyState.rgbButtons[7] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON8;
if (_Joystick[i].joyState.rgbButtons[8] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON9;
if (_Joystick[i].joyState.rgbButtons[9] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON10;
if (_Joystick[i].joyState.rgbButtons[10] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON11;
if (_Joystick[i].joyState.rgbButtons[11] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON12;
if (_Joystick[i].joyState.rgbButtons[12] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON13;
if (_Joystick[i].joyState.rgbButtons[13] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON14;
if (_Joystick[i].joyState.rgbButtons[14] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON15;
if (_Joystick[i].joyState.rgbButtons[15] & 0x80) _Joystick[i].buttonState |= INPUT_JOYSTICK_BUTTON16;
if (_Joystick[i].joyState.lY < -250) _Joystick[i].buttonState |= INPUT_JOYSTICK_UP;
if (_Joystick[i].joyState.lX > +250) _Joystick[i].buttonState |= INPUT_JOYSTICK_RIGHT;
if (_Joystick[i].joyState.lY > +250) _Joystick[i].buttonState |= INPUT_JOYSTICK_DOWN;
if (_Joystick[i].joyState.lX < -250) _Joystick[i].buttonState |= INPUT_JOYSTICK_LEFT;
//KitaoXVBnbgXCb`iAiOΉRg[̏\{^ł悭gjɂΉB
if (_Joystick[i].joyState.rgdwPOV[0] == 0) _Joystick[i].buttonState |= INPUT_JOYSTICK_POVUP;
if (_Joystick[i].joyState.rgdwPOV[0] == 45*DI_DEGREES)
{
_Joystick[i].buttonState |= INPUT_JOYSTICK_POVUP;
_Joystick[i].buttonState |= INPUT_JOYSTICK_POVRIGHT;
}
if (_Joystick[i].joyState.rgdwPOV[0] == 90*DI_DEGREES) _Joystick[i].buttonState |= INPUT_JOYSTICK_POVRIGHT;
if (_Joystick[i].joyState.rgdwPOV[0] == 135*DI_DEGREES)
{
_Joystick[i].buttonState |= INPUT_JOYSTICK_POVRIGHT;
_Joystick[i].buttonState |= INPUT_JOYSTICK_POVDOWN;
}
if (_Joystick[i].joyState.rgdwPOV[0] == 180*DI_DEGREES) _Joystick[i].buttonState |= INPUT_JOYSTICK_POVDOWN;
if (_Joystick[i].joyState.rgdwPOV[0] == 225*DI_DEGREES)
{
_Joystick[i].buttonState |= INPUT_JOYSTICK_POVDOWN;
_Joystick[i].buttonState |= INPUT_JOYSTICK_POVLEFT;
}
if (_Joystick[i].joyState.rgdwPOV[0] == 270*DI_DEGREES) _Joystick[i].buttonState |= INPUT_JOYSTICK_POVLEFT;
if (_Joystick[i].joyState.rgdwPOV[0] == 315*DI_DEGREES)
{
_Joystick[i].buttonState |= INPUT_JOYSTICK_POVLEFT;
_Joystick[i].buttonState |= INPUT_JOYSTICK_POVUP;
}
}
}
//KitaoljBL[{[h̏ԂǂݎčXVB
static void
keyborad_update_state()
{
HRESULT hResult;
// L[{[h̏Ԃǂ
hResult =_pDIDKey->GetDeviceState(256, &_DIKeys);
// ǂݎɎs̏
if (hResult != DI_OK) //sƂ̓ANZX蒼Ă蒼
{
_pDIDKey->Acquire();
_pDIDKey->GetDeviceState(256, &_DIKeys);
}
}
static BOOL
pump_message()
{
MSG msg;
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (_hInstance == NULL)
return FALSE;
return TRUE;
}
static BOOL
get_button(
Sint16* pButton)
{
Sint16 q,i; //Kitaolj
Sint16 theJoystick = -1; //Kitaolj
Sint16 theButton = -1;
while (theButton < 0)
{
Sleep(1);
if (!pump_message())
return FALSE;
//WCXeBbN
joypad_update_state(); //WCXeBbN̏Ԃǂ
for (q=0; q<=_nJoySticks-1; q++) //KitaoljBȂĂSẴWCXeBbÑ{^t悤ɂB
for (i=0; i<=INPUT_NUM_BUTTON-1; i++)
if (_Joystick[q].buttonState & button[i]) //{^Ă
{
//ꂽ{^܂ő҂
while (_Joystick[q].buttonState & button[i])
{
Sleep(1);
if (!pump_message())
return FALSE;
joypad_update_state();
}
theJoystick = q+1; //KitaoljBǂ̃WCXeBbÑ{^
theButton = i;
if (theButton <=7) //\L[ornbgXCb`
*pButton = (200 + theJoystick*100) + theButton;
else //{^
*pButton = (200 + theJoystick*100 +50) + (theButton -8);
return TRUE;
}
//KitaoljBL[{[h
keyborad_update_state(); //L[{[h̏Ԃǂ
for (i=0; i<=255; i++)
if ((_DIKeys[i] & 0x80)&&(i != DIK_ESCAPE)&&(i != DIK_CAPITAL)&&(i != DIK_KANJI)&& //L[ĂiEscCAPS(p/Sp)L[ȊOjBv0.83XV(KiC肪Ƃ܂)
(i != DIK_CAPITAL)&&(i != DIK_KANA)) //uCapsLockL[vƁuȃL[vɁB(Ă܂ƃL[tȂȂ)Bv1.33lj
{
//ꂽ{^܂ő҂
while (_DIKeys[i] & 0x80)
{
Sleep(1);
if (!pump_message())
return FALSE;
keyborad_update_state();
}
if (i == DIK_F1) //F1L[ȂݒNA
i = -1;
*pButton = i;
return TRUE;
}
}
return FALSE;
}
//KitaoXV
static BOOL
configure(
Sint32 mode, //KitaoljB0cʏ̐ݒB1cAːp{^̐ݒB2`c{^̐ݒ
Sint32 padID, //KitaoXVBjoyIDpadID(1`5)ցBPCGW̃pbhio[ŊǗ悤ɂB
PCEPAD* pPad)
{
Sint16 up = -1;
Sint16 right = -1;
Sint16 down = -1;
Sint16 left = -1;
Sint16 select = -1;
Sint16 run = -1;
Sint16 buttonI = -1;
Sint16 buttonII = -1;
Sint16 buttonIII = -1;
Sint16 buttonIV = -1;
Sint16 buttonV = -1;
Sint16 buttonVI = -1;
add_text("\n");
switch (mode)
{
case 0:
case 1: //ʏ̐ݒorAːp{^̐ݒ
if (JOYPAD_GetConnectSixButton()) //Kitaolj
add_text("Setting of Player#%ld for \"6 Button Pad\": (\"Esc\"=Abort \"F1\"=Clear)", padID);
else if (JOYPAD_GetConnectThreeButton()) //Kitaolj
add_text("Setting of Player#%ld for \"3 Button Pad\": (\"Esc\"=Abort \"F1\"=Clear)", padID);
else
add_text("Setting of Player#%ld for \"2 Button Pad\": (\"Esc\"=Abort \"F1\"=Clear)", padID);
if (mode == 1)
{ //A˃{^̐ݒ莞B{^T,UɘAːp{^ݒB
up = pPad->buttonU;
right = pPad->buttonR;
down = pPad->buttonD;
left = pPad->buttonL;
select = pPad->buttonSel;
run = pPad->buttonRun;
buttonI = pPad->button1;
buttonII= pPad->button2;
buttonIII=pPad->button3;
buttonIV= pPad->button4;
add_text("Press a button for \"turbo button I\"..."); if (!get_button(&buttonV)) return FALSE;
add_text("Press a button for \"turbo button II\"..."); if (!get_button(&buttonVI)) return FALSE;
}
else
{ //ʏ펞
add_text("Press a button for \"UP\"..."); if (!get_button(&up)) return FALSE;
add_text("Press a button for \"RIGHT\"..."); if (!get_button(&right)) return FALSE;
add_text("Press a button for \"DOWN\"..."); if (!get_button(&down)) return FALSE;
add_text("Press a button for \"LEFT\"..."); if (!get_button(&left)) return FALSE;
add_text("Press a button for \"SELECT\"..."); if (!get_button(&select)) return FALSE;
add_text("Press a button for \"RUN\"..."); if (!get_button(&run)) return FALSE;
add_text("Press a button for \"button I\"..."); if (!get_button(&buttonI)) return FALSE;
add_text("Press a button for \"button II\"..."); if (!get_button(&buttonII)) return FALSE;
if (JOYPAD_GetConnectSixButton()) //Kitaolj
{
add_text("Press a button for \"button III\"..."); if (!get_button(&buttonIII)) return FALSE;
add_text("Press a button for \"button IV\"..."); if (!get_button(&buttonIV)) return FALSE;
add_text("Press a button for \"button V\"..."); if (!get_button(&buttonV)) return FALSE;
add_text("Press a button for \"button VI\"..."); if (!get_button(&buttonVI)) return FALSE;
}
else if (JOYPAD_GetConnectThreeButton()) //Kitaolj
{
add_text("Press a button for \"button III[=RUN]\"..."); if (!get_button(&buttonIII)) return FALSE;
add_text("Press a button for \"button IV[=SELECT]\"..."); if (!get_button(&buttonIV)) return FALSE;
}
}
break;
case 2: //p{^̐ݒ
add_text("Setting of \"Video Speed Up Button\": (\"Esc\"=Abort \"F1\"=Clear)");
add_text("Press a button for \"Video Speed Up Button\"..."); if (!get_button(&buttonI)) return FALSE;
break;
case 3: //Xe[gZ[up{^̐ݒ
add_text("Setting of \"Save State Button\": (\"Esc\"=Abort \"F1\"=Default[S])");
add_text("Press a button for \"Save State Button\"..."); if (!get_button(&buttonI)) return FALSE;
break;
case 4: //Xe[g[hp{^̐ݒ
add_text("Setting of \"Load State Button\": (\"Esc\"=Abort \"F1\"=Default[L])");
add_text("Press a button for \"Load State Button\"..."); if (!get_button(&buttonI)) return FALSE;
break;
case 5: //XN[Vbgp{^̐ݒ
add_text("Setting of \"Screenshot Button\": (\"Esc\"=Abort \"F1\"=Default[PrintScr])");
add_text("Press a button for \"Screenshot Button\"..."); if (!get_button(&buttonI)) return FALSE;
break;
case 6: //t@NVp{^̐ݒ
add_text("Setting of \"Function Button\": (\"Esc\"=Abort \"F1\"=Clear)");
add_text("Press a button for \"Function Button\"..."); if (!get_button(&buttonI)) return FALSE;
break;
case 7: //t@NV{^̃Z[u[hp{^̐ݒ
add_text("Setting of \"Function SaveState Button\": (\"Esc\"=Abort \"F1\"=Clear)");
add_text("Press a button for \"Function SaveState Button\"..."); if (!get_button(&buttonI)) return FALSE;
add_text("Setting of \"Function LoadState Button\": (\"Esc\"=Abort \"F1\"=Clear)");
add_text("Press a button for \"Function LoadState Button\"..."); if (!get_button(&buttonII)) return FALSE;
break;
case 8: //|[Yp{^̐ݒ
add_text("Setting of \"Pause Button\": (\"Esc\"=Abort \"F1\"=Clear)");
add_text("Press a button for \"Pause Button\"..."); if (!get_button(&buttonI)) return FALSE;
break;
}
//KitaoXV
pPad->buttonU = up; //L[̐ݒBAXL[R[h(0`255)BWCpbhP(300`399B100{^܂őΉ)BWCpbhQ(400`499)BȉWCpbhT{܂œlB
pPad->buttonR = right; //EL[̐ݒ
pPad->buttonD = down; //L[̐ݒ
pPad->buttonL = left; //L[̐ݒ
pPad->buttonSel = select; //Select{^̐ݒ
pPad->buttonRun = run; //Run{^̐ݒ
pPad->button1 = buttonI; //I{^̐ݒ
pPad->button2 = buttonII; //II{^̐ݒ
pPad->button3 = buttonIII;//III{^̐ݒ
pPad->button4 = buttonIV; //IV{^̐ݒ
pPad->button5 = buttonV; //V{^̐ݒ
pPad->button6 = buttonVI; //VI{^̐ݒ
return TRUE;
}
static LRESULT CALLBACK
padconfig_wnd_proc(
HWND hWnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
int i;
switch(uMsg)
{
case WM_CREATE:
EnableWindow(WINMAIN_GetHwnd(), FALSE);//KitaoljBCEChEă[_ɁB
_FontWidth = get_font_width(hWnd);
_FontHeight = get_font_height(hWnd);
set_window_size(hWnd);
break;
case WM_PAINT:
update_window(hWnd);
_bWindowCreated = TRUE; //v0.74lj
break;
case WM_ACTIVATE: //Kitaolj
if (wParam != 0) //ANeBuɂȂƂ
{
//DirectInput̃ANZX
//L[{[h
if (_pDIDKey != NULL)
_pDIDKey->Acquire();
//WCXeBbN
for (i = 0; i < _nJoySticks; ++i)
if (_pDIDJoy[i] != NULL)
_pDIDJoy[i]->Acquire();
}
break;
case WM_KEYDOWN:
if (wParam == VK_ESCAPE)
PostMessage(hWnd, WM_CLOSE, 0, 0);
break;
case WM_CLOSE:
PADCONFIG_Deinit();
break;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
//KitaoljBJoyStickfoCX̎擾R[obN
static BOOL
CALLBACK
DIEnumAxisCallback(
LPCDIDEVICEOBJECTINSTANCE lpddi,
LPVOID pvRef)
{
DIPROPRANGE diDR;
DIPROPDWORD diDD;
//̐ݒB
ZeroMemory(&diDR, sizeof(diDR));
diDR.diph.dwSize = sizeof(diDR);
diDR.diph.dwHeaderSize = sizeof(diDR.diph);
diDR.diph.dwHow = DIPH_BYID;
diDR.diph.dwObj = lpddi->dwType;
diDR.lMin = -1000;
diDR.lMax = +1000;
_pDIDJoy[_nJoySticks]->SetProperty(DIPROP_RANGE, &diDR.diph);
//ΎɐݒB
ZeroMemory(&diDD, sizeof(diDD));
diDD.diph.dwSize = sizeof(diDD);
diDD.diph.dwHeaderSize = sizeof(diDD.diph);
diDD.diph.dwHow = DIPH_DEVICE;
diDD.dwData = DIPROPAXISMODE_ABS;
_pDIDJoy[_nJoySticks]->SetProperty(DIPROP_AXISMODE, &diDD.diph);
//fbh][0ɐݒBfW^pbhłLBDirectX7ȍ~łłԔǂȂBKitaolj
ZeroMemory(&diDD, sizeof(diDD));
diDD.diph.dwSize = sizeof(diDD);
diDD.diph.dwHeaderSize = sizeof(diDD.diph);
diDD.diph.dwHow = DIPH_DEVICE;
diDD.dwData = 0;
_pDIDJoy[_nJoySticks]->SetProperty(DIPROP_DEADZONE, &diDD.diph);
//Oa][őɁBKitaolj
ZeroMemory(&diDD, sizeof(diDD));
diDD.diph.dwSize = sizeof(diDD);
diDD.diph.dwHeaderSize = sizeof(diDD.diph);
diDD.diph.dwHow = DIPH_DEVICE;
diDD.dwData = 10000;
_pDIDJoy[_nJoySticks]->SetProperty(DIPROP_SATURATION, &diDD.diph);
return DIENUM_CONTINUE; //̎T
}
static BOOL
CALLBACK
DIEnumDevicesCallback(
LPCDIDEVICEINSTANCE lpddi,
LPVOID pvRef)
{
HRESULT hResult;
LPDIRECTINPUTDEVICE pDIDJoy; //Kitaolj
DIPROPDWORD diDD;
//WCXeBbNfoCX쐬
hResult = _pDI->CreateDevice(lpddi->guidInstance, &pDIDJoy, NULL);
if(hResult != DI_OK)
return DIENUM_CONTINUE; //s璆~ĎT
//KitaoljBDirectInputDevice2ɊgĂ悤ɂijB
pDIDJoy->QueryInterface(IID_IDirectInputDevice8, (LPVOID*)&_pDIDJoy[_nJoySticks]);
pDIDJoy->Release();
//f[^tH[}bgݒ肷
_pDIDJoy[_nJoySticks]->SetDataFormat(&c_dfDIJoystick2);
//obt@ŏɁBǂȂBKitaolj
ZeroMemory(&diDD, sizeof(diDD));
diDD.diph.dwSize = sizeof(diDD);
diDD.diph.dwHeaderSize = sizeof(diDD.diph);
diDD.diph.dwHow = DIPH_DEVICE;
diDD.dwData = 1;
_pDIDJoy[_nJoySticks]->SetProperty(DIPROP_BUFFERSIZE, &diDD.diph);
//xw肷 KitaoXVBݒDISCL_NONEXCLUSIVEɁobNOEhł\ɂB
_pDIDJoy[_nJoySticks]->SetCooperativeLevel(_hWnd, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND);
//JoyStickfoCX̎BKitaolj
_pDIDJoy[_nJoySticks]->EnumObjects(DIEnumAxisCallback, NULL, DIDFT_AXIS);
_nJoySticks++;
//Rg[5oꂽI
if(_nJoySticks==N_MAXJOYSTICK)
return DIENUM_STOP; //I
else
return DIENUM_CONTINUE; //̃foCXT
}
//KitaoXVBL[{[hɂΉBWCXeBbNDȃWCXeBbNDȔԍŎg悤ɂB
static BOOL
padconfig_main()
{
WNDCLASS wc;
HWND hWnd;
BOOL bOk;
HRESULT hResult;
int i;
RECT rc;
ZeroMemory(&wc, sizeof(wc));
wc.style = 0;
wc.lpfnWndProc = padconfig_wnd_proc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = _hInstance;
wc.hIcon = LoadIcon(_hInstance, MAKEINTRESOURCE(OOTAKEICON)); //ACRǂݍ݁Bv2.00XV
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.lpszMenuName = "";
wc.lpszClassName = _pCaption;
if (RegisterClass(&wc) == 0)
return FALSE;
_bWindowCreated = FALSE; //Kitaolj
hWnd = CreateWindow(
_pCaption,
_pCaption,
WS_MINIMIZEBOX | WS_SYSMENU | WS_CAPTION,
CW_USEDEFAULT,
CW_USEDEFAULT,
0,
0,
NULL,
NULL,
_hInstance,
NULL
);
if (hWnd == NULL)
return FALSE;
_hWnd = hWnd;
CloseWindow(WINMAIN_GetHwnd());//CEBhEŏ
ShowWindow(hWnd, SW_SHOWNORMAL);
UpdateWindow(hWnd);
GetWindowRect(hWnd, &rc);
SetWindowPos(hWnd, HWND_TOP, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, SWP_FRAMECHANGED); //̃EBhEuɎOɕ\v
while (_bWindowCreated == FALSE) //EBhE̐܂ő҂Bv0.74
Sleep(1);
ImmAssociateContext(hWnd, 0); //KitaoljBIMEɂBv0.79
//ȉKitaoljB
//WindowsWCXeBbNp̕ϐ
_nJoySticks = 0;
ZeroMemory(_Joystick, sizeof(_Joystick));
// DirectInputC^[tF[X擾
if (DirectInput8Create(WINMAIN_GetHInstance(), DIRECTINPUT_VERSION, IID_IDirectInput8A, (void**)&_pDI, NULL) != DI_OK)
return FALSE;
//L[{[hfoCX擾
if (_pDI->CreateDevice(GUID_SysKeyboard, &_pDIDKey, NULL) != DI_OK)
return FALSE;
//f[^tH[}bgݒ肷
if (_pDIDKey->SetDataFormat(&c_dfDIKeyboard) != DI_OK)
return FALSE;
//xw肷
hResult=_pDIDKey->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND);
//L[{[h̃ANZXĂB
_pDIDKey->Acquire();
//JoyStickfoCX
_pDI->EnumDevices(DI8DEVCLASS_GAMECTRL, DIEnumDevicesCallback, NULL, DIEDFL_ATTACHEDONLY);
if (_nJoySticks == 0)
add_text("PADCONFIG: No supported joystick found.");
else
add_text("PADCONFIG: %ld joystick(s) found.", _nJoySticks);
//ŏɃANZXĂB
for (i = 0; i < _nJoySticks; i++)
_pDIDJoy[i]->Acquire();
//͐ݒ
bOk = configure(_Mode, _PadID, _pPad);
if (bOk)
_SetOk = 1; //ݒ芮̈
PostMessage(hWnd, WM_CLOSE, 0, 0);
return bOk;
}
//KitaoXVBlvĈƂL[{[h̃{^g悤ɂB
BOOL
PADCONFIG_Init(
HINSTANCE hInstance,
Sint32 mode, //KitaoljB0cʏ̐ݒB1cAːp{^̐ݒB2cp{^̐ݒB3cXe[gZ[up{^̐ݒB4cXe[g[hp{^̐ݒB5cXN[Vbgp{^̐ݒB
// 6ct@NVp{^̐ݒB7ct@NV{^̃Xe[gZ[u[hp{^̐ݒB8c|[Yp{^̐ݒB
Sint32 padID,
PCEPAD* pPad,
Sint32* setOk)
{
int i;
_hInstance = hInstance;
_Line = 0;
_Mode = mode;
_PadID = padID;
_pPad = pPad;
_pSetOk = setOk;
_SetOk = -1; //LZ
for (i=0; i<N_LINES; i++)
_pText[i] = _Text[i];
return padconfig_main();
}
void
PADCONFIG_Deinit()
{
int i;
if (_hInstance != NULL)
{
if (_pDIDKey != NULL)
{
_pDIDKey->Unacquire();
_pDIDKey->Release();
_pDIDKey = NULL;
}
for (i = 0; i < N_MAXJOYSTICK; ++i)
{
if (_pDIDJoy[i] != NULL)
{
_pDIDJoy[i]->Unacquire();
_pDIDJoy[i]->Release();
_pDIDJoy[i] = NULL;
}
}
if (_pDI != NULL)
{
_pDI->Release();
_pDI = NULL;
}
DestroyWindow(_hWnd);
_hWnd = NULL;
UnregisterClass(_pCaption, _hInstance);
_hInstance = NULL;
//CEBhEɃtH[JX߂̑傫ɁB
EnableWindow(WINMAIN_GetHwnd(), TRUE);
OpenIcon(WINMAIN_GetHwnd());
*_pSetOk = _SetOk; //߂lݒB̏uԂɃCEBhE͓oB
}
}
| 412 | 0.874183 | 1 | 0.874183 | game-dev | MEDIA | 0.734706 | game-dev,drivers | 0.510654 | 1 | 0.510654 |
KhronosGroup/glTF-CSharp-Loader | 6,597 | glTFLoader/Schema/BufferView.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace glTFLoader.Schema {
using System.Linq;
using System.Runtime.Serialization;
public class BufferView {
/// <summary>
/// Backing field for Buffer.
/// </summary>
private int m_buffer;
/// <summary>
/// Backing field for ByteOffset.
/// </summary>
private int m_byteOffset = 0;
/// <summary>
/// Backing field for ByteLength.
/// </summary>
private int m_byteLength;
/// <summary>
/// Backing field for ByteStride.
/// </summary>
private System.Nullable<int> m_byteStride;
/// <summary>
/// Backing field for Target.
/// </summary>
private System.Nullable<TargetEnum> m_target;
/// <summary>
/// Backing field for Name.
/// </summary>
private string m_name;
/// <summary>
/// Backing field for Extensions.
/// </summary>
private System.Collections.Generic.Dictionary<string, object> m_extensions;
/// <summary>
/// Backing field for Extras.
/// </summary>
private Extras m_extras;
/// <summary>
/// The index of the buffer.
/// </summary>
[Newtonsoft.Json.JsonRequiredAttribute()]
[Newtonsoft.Json.JsonPropertyAttribute("buffer")]
public int Buffer {
get {
return this.m_buffer;
}
set {
if ((value < 0)) {
throw new System.ArgumentOutOfRangeException("Buffer", value, "Expected value to be greater than or equal to 0");
}
this.m_buffer = value;
}
}
/// <summary>
/// The offset into the buffer in bytes.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("byteOffset")]
public int ByteOffset {
get {
return this.m_byteOffset;
}
set {
if ((value < 0)) {
throw new System.ArgumentOutOfRangeException("ByteOffset", value, "Expected value to be greater than or equal to 0");
}
this.m_byteOffset = value;
}
}
/// <summary>
/// The length of the bufferView in bytes.
/// </summary>
[Newtonsoft.Json.JsonRequiredAttribute()]
[Newtonsoft.Json.JsonPropertyAttribute("byteLength")]
public int ByteLength {
get {
return this.m_byteLength;
}
set {
if ((value < 1)) {
throw new System.ArgumentOutOfRangeException("ByteLength", value, "Expected value to be greater than or equal to 1");
}
this.m_byteLength = value;
}
}
/// <summary>
/// The stride, in bytes.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("byteStride")]
public System.Nullable<int> ByteStride {
get {
return this.m_byteStride;
}
set {
if ((value < 4)) {
throw new System.ArgumentOutOfRangeException("ByteStride", value, "Expected value to be greater than or equal to 4");
}
if ((value > 252)) {
throw new System.ArgumentOutOfRangeException("ByteStride", value, "Expected value to be less than or equal to 252");
}
this.m_byteStride = value;
}
}
/// <summary>
/// The hint representing the intended GPU buffer type to use with this buffer view.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("target")]
public System.Nullable<TargetEnum> Target {
get {
return this.m_target;
}
set {
this.m_target = value;
}
}
/// <summary>
/// The user-defined name of this object.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public string Name {
get {
return this.m_name;
}
set {
this.m_name = value;
}
}
/// <summary>
/// JSON object with extension-specific objects.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("extensions")]
public System.Collections.Generic.Dictionary<string, object> Extensions {
get {
return this.m_extensions;
}
set {
this.m_extensions = value;
}
}
/// <summary>
/// Application-specific data.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("extras")]
public Extras Extras {
get {
return this.m_extras;
}
set {
this.m_extras = value;
}
}
public bool ShouldSerializeByteOffset() {
return ((m_byteOffset == 0)
== false);
}
public bool ShouldSerializeByteStride() {
return ((m_byteStride == null)
== false);
}
public bool ShouldSerializeTarget() {
return ((m_target == null)
== false);
}
public bool ShouldSerializeName() {
return ((m_name == null)
== false);
}
public bool ShouldSerializeExtensions() {
return ((m_extensions == null)
== false);
}
public bool ShouldSerializeExtras() {
return ((m_extras == null)
== false);
}
public enum TargetEnum {
ARRAY_BUFFER = 34962,
ELEMENT_ARRAY_BUFFER = 34963,
}
}
}
| 412 | 0.882334 | 1 | 0.882334 | game-dev | MEDIA | 0.40677 | game-dev | 0.890821 | 1 | 0.890821 |
JasonCian/Millenaire-rewrite | 39,526 | reference/OldSource/java/org/millenaire/common/village/BuildingResManager.java | package org.millenaire.common.village;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import net.minecraft.block.Block;
import net.minecraft.block.BlockCocoa;
import net.minecraft.block.BlockOldLog;
import net.minecraft.block.BlockPlanks;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.ResourceLocation;
import org.millenaire.common.block.BlockSilkWorm;
import org.millenaire.common.block.BlockSnailSoil;
import org.millenaire.common.block.MillBlocks;
import org.millenaire.common.config.MillConfigValues;
import org.millenaire.common.entity.TileEntityLockedChest;
import org.millenaire.common.forge.Mill;
import org.millenaire.common.item.InvItem;
import org.millenaire.common.network.StreamReadWrite;
import org.millenaire.common.utilities.BlockItemUtilities;
import org.millenaire.common.utilities.MillCommonUtilities;
import org.millenaire.common.utilities.MillLog;
import org.millenaire.common.utilities.Point;
import org.millenaire.common.utilities.WorldUtilities;
public class BuildingResManager {
public CopyOnWriteArrayList<Point> brickspot = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> chests = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> fishingspots = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> sugarcanesoils = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> healingspots = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> furnaces = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> firepits = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> brewingStands = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> signs = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> banners = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> cultureBanners = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<CopyOnWriteArrayList<Point>> sources = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<IBlockState> sourceTypes = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<CopyOnWriteArrayList<Point>> spawns = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<ResourceLocation> spawnTypes = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<CopyOnWriteArrayList<Point>> mobSpawners = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<ResourceLocation> mobSpawnerTypes = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<CopyOnWriteArrayList<Point>> soils = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<ResourceLocation> soilTypes = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> stalls = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> woodspawn = new CopyOnWriteArrayList<>();
public ConcurrentHashMap<Point, String> woodspawnTypes = new ConcurrentHashMap<>();
public CopyOnWriteArrayList<Point> netherwartsoils = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> silkwormblock = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> snailsoilblock = new CopyOnWriteArrayList<>();
public CopyOnWriteArrayList<Point> dispenderUnknownPowder = new CopyOnWriteArrayList<>();
private Point sleepingPos = null;
private Point sellingPos = null;
private Point craftingPos = null;
private Point defendingPos = null;
private Point shelterPos = null;
private Point pathStartPos = null;
private Point leasurePos = null;
private final Building building;
public BuildingResManager(Building b) {
this.building = b;
}
public void addMobSpawnerPoint(ResourceLocation type, Point p) {
if (!this.mobSpawnerTypes.contains(type)) {
CopyOnWriteArrayList<Point> spawnsPoint = new CopyOnWriteArrayList<>();
spawnsPoint.add(p);
this.mobSpawners.add(spawnsPoint);
this.mobSpawnerTypes.add(type);
} else {
for (int i = 0; i < this.mobSpawnerTypes.size(); i++) {
if (((ResourceLocation)this.mobSpawnerTypes.get(i)).equals(type) &&
!((CopyOnWriteArrayList)this.mobSpawners.get(i)).contains(p))
((CopyOnWriteArrayList<Point>)this.mobSpawners.get(i)).add(p);
}
}
}
public void addSoilPoint(ResourceLocation type, Point p) {
if (!this.soilTypes.contains(type)) {
CopyOnWriteArrayList<Point> spawnsPoint = new CopyOnWriteArrayList<>();
spawnsPoint.add(p);
this.soils.add(spawnsPoint);
this.soilTypes.add(type);
} else {
for (int i = 0; i < this.soilTypes.size(); i++) {
if (((ResourceLocation)this.soilTypes.get(i)).equals(type) &&
!((CopyOnWriteArrayList)this.soils.get(i)).contains(p))
((CopyOnWriteArrayList<Point>)this.soils.get(i)).add(p);
}
}
}
public void addSourcePoint(IBlockState blockState, Point p) {
if (!this.sourceTypes.contains(blockState)) {
CopyOnWriteArrayList<Point> spawnsPoint = new CopyOnWriteArrayList<>();
spawnsPoint.add(p);
this.sources.add(spawnsPoint);
this.sourceTypes.add(blockState);
} else {
for (int i = 0; i < this.sourceTypes.size(); i++) {
if (((IBlockState)this.sourceTypes.get(i)).equals(blockState) &&
!((CopyOnWriteArrayList)this.sources.get(i)).contains(p))
((CopyOnWriteArrayList<Point>)this.sources.get(i)).add(p);
}
}
}
public void addSpawnPoint(ResourceLocation type, Point p) {
if (!this.spawnTypes.contains(type)) {
CopyOnWriteArrayList<Point> spawnsPoint = new CopyOnWriteArrayList<>();
spawnsPoint.add(p);
this.spawns.add(spawnsPoint);
this.spawnTypes.add(type);
} else {
for (int i = 0; i < this.spawnTypes.size(); i++) {
if (((ResourceLocation)this.spawnTypes.get(i)).equals(type) &&
!((CopyOnWriteArrayList)this.spawns.get(i)).contains(p))
((CopyOnWriteArrayList<Point>)this.spawns.get(i)).add(p);
}
}
}
public HashMap<InvItem, Integer> getChestsContent() {
HashMap<InvItem, Integer> contents = new HashMap<>();
for (Point p : this.chests) {
TileEntityLockedChest chest = p.getMillChest(this.building.world);
if (chest != null)
for (int i = 0; i < chest.getSizeInventory(); i++) {
ItemStack stack = chest.getStackInSlot(i);
if (stack != null && stack.getItem() != Items.AIR) {
InvItem key = InvItem.createInvItem(stack);
if (stack != null)
if (contents.containsKey(key)) {
contents.put(key, Integer.valueOf(stack.getCount() + ((Integer)contents.get(key)).intValue()));
} else {
contents.put(key, Integer.valueOf(stack.getCount()));
}
}
}
}
return contents;
}
public Point getCocoaHarvestLocation() {
for (int i = 0; i < this.soilTypes.size(); i++) {
if (((ResourceLocation)this.soilTypes.get(i)).equals(Mill.CROP_CACAO))
for (Point p : this.soils.get(i)) {
IBlockState state = p.getBlockActualState(this.building.world);
if (state.getBlock() == Blocks.COCOA && (
(Integer)state.getValue((IProperty)BlockCocoa.AGE)).intValue() >= 2)
return p;
}
}
return null;
}
public Point getCocoaPlantingLocation() {
for (int i = 0; i < this.soilTypes.size(); i++) {
if (((ResourceLocation)this.soilTypes.get(i)).equals(Mill.CROP_CACAO))
for (Point p : this.soils.get(i)) {
if (p.getBlock(this.building.world) == Blocks.AIR) {
if (p.getNorth().getBlock(this.building.world) == Blocks.LOG &&
isBlockJungleWood(p.getNorth().getBlockActualState(this.building.world)))
return p;
if (p.getEast().getBlock(this.building.world) == Blocks.LOG &&
isBlockJungleWood(p.getEast().getBlockActualState(this.building.world)))
return p;
if (p.getSouth().getBlock(this.building.world) == Blocks.LOG &&
isBlockJungleWood(p.getSouth().getBlockActualState(this.building.world)))
return p;
if (p.getWest().getBlock(this.building.world) == Blocks.LOG &&
isBlockJungleWood(p.getWest().getBlockActualState(this.building.world)))
return p;
}
}
}
return null;
}
public Point getCraftingPos() {
if (this.craftingPos != null)
return this.craftingPos;
if (this.sellingPos != null)
return this.sellingPos;
return this.sleepingPos;
}
public Point getDefendingPos() {
if (this.defendingPos != null)
return this.defendingPos;
if (this.sellingPos != null)
return this.sellingPos;
return this.sleepingPos;
}
public Point getEmptyBrickLocation() {
if (this.brickspot.size() == 0)
return null;
for (int i = 0; i < this.brickspot.size(); i++) {
Point p = this.brickspot.get(i);
if (WorldUtilities.getBlock(this.building.world, p) == Blocks.AIR)
return p;
}
return null;
}
public Point getFullBrickLocation() {
if (this.brickspot.size() == 0)
return null;
for (int i = 0; i < this.brickspot.size(); i++) {
Point p = this.brickspot.get(i);
if (WorldUtilities.getBlockState(this.building.world, p) == MillBlocks.BS_MUD_BRICK)
return p;
}
return null;
}
public Point getLeasurePos() {
if (this.leasurePos != null)
return this.leasurePos;
return getSellingPos();
}
public int getNbEmptyBrickLocation() {
if (this.brickspot.size() == 0)
return 0;
int nb = 0;
for (int i = 0; i < this.brickspot.size(); i++) {
Point p = this.brickspot.get(i);
if (WorldUtilities.getBlock(this.building.world, p) == Blocks.AIR)
nb++;
}
return nb;
}
public int getNbFullBrickLocation() {
if (this.brickspot.size() == 0)
return 0;
int nb = 0;
for (int i = 0; i < this.brickspot.size(); i++) {
Point p = this.brickspot.get(i);
if (WorldUtilities.getBlockState(this.building.world, p) == MillBlocks.BS_MUD_BRICK)
nb++;
}
return nb;
}
public int getNbNetherWartHarvestLocation() {
if (this.netherwartsoils.size() == 0)
return 0;
int nb = 0;
for (int i = 0; i < this.netherwartsoils.size(); i++) {
Point p = this.netherwartsoils.get(i);
if (WorldUtilities.getBlock(this.building.world, p.getAbove()) == Blocks.NETHER_WART &&
WorldUtilities.getBlockMeta(this.building.world, p.getAbove()) >= 3)
nb++;
}
return nb;
}
public int getNbNetherWartPlantingLocation() {
if (this.netherwartsoils.size() == 0)
return 0;
int nb = 0;
for (int i = 0; i < this.netherwartsoils.size(); i++) {
Point p = this.netherwartsoils.get(i);
if (WorldUtilities.getBlock(this.building.world, p.getAbove()) == Blocks.AIR)
nb++;
}
return nb;
}
public int getNbSilkWormHarvestLocation() {
if (this.silkwormblock.size() == 0)
return 0;
int nb = 0;
for (int i = 0; i < this.silkwormblock.size(); i++) {
Point p = this.silkwormblock.get(i);
if (WorldUtilities.getBlockState(this.building.world, p) == MillBlocks.SILK_WORM.getDefaultState()
.withProperty((IProperty)BlockSilkWorm.PROGRESS, (Comparable)BlockSilkWorm.EnumType.SILKWORMFULL))
nb++;
}
return nb;
}
public int getNbSnailSoilHarvestLocation() {
if (this.snailsoilblock.size() == 0)
return 0;
int nb = 0;
for (int i = 0; i < this.snailsoilblock.size(); i++) {
Point p = this.snailsoilblock.get(i);
if (WorldUtilities.getBlockState(this.building.world, p) == MillBlocks.SNAIL_SOIL.getDefaultState().withProperty((IProperty)BlockSnailSoil.PROGRESS, (Comparable)BlockSnailSoil.EnumType.SNAIL_SOIL_FULL))
nb++;
}
return nb;
}
public int getNbSugarCaneHarvestLocation() {
if (this.sugarcanesoils.size() == 0)
return 0;
int nb = 0;
for (int i = 0; i < this.sugarcanesoils.size(); i++) {
Point p = this.sugarcanesoils.get(i);
if (WorldUtilities.getBlock(this.building.world, p.getRelative(0.0D, 2.0D, 0.0D)) == Blocks.REEDS)
nb++;
}
return nb;
}
public int getNbSugarCanePlantingLocation() {
if (this.sugarcanesoils.size() == 0)
return 0;
int nb = 0;
for (int i = 0; i < this.sugarcanesoils.size(); i++) {
Point p = this.sugarcanesoils.get(i);
if (WorldUtilities.getBlock(this.building.world, p.getAbove()) == Blocks.AIR)
nb++;
}
return nb;
}
public Point getNetherWartsHarvestLocation() {
if (this.netherwartsoils.size() == 0)
return null;
int start = MillCommonUtilities.randomInt(this.netherwartsoils.size());
int i;
for (i = start; i < this.netherwartsoils.size(); i++) {
Point p = this.netherwartsoils.get(i);
if (WorldUtilities.getBlock(this.building.world, p.getAbove()) == Blocks.NETHER_WART &&
WorldUtilities.getBlockMeta(this.building.world, p.getAbove()) == 3)
return p;
}
for (i = 0; i < start; i++) {
Point p = this.netherwartsoils.get(i);
if (WorldUtilities.getBlock(this.building.world, p.getAbove()) == Blocks.NETHER_WART &&
WorldUtilities.getBlockMeta(this.building.world, p.getAbove()) == 3)
return p;
}
return null;
}
public Point getNetherWartsPlantingLocation() {
if (this.netherwartsoils.size() == 0)
return null;
int start = MillCommonUtilities.randomInt(this.netherwartsoils.size());
int i;
for (i = start; i < this.netherwartsoils.size(); i++) {
Point p = this.netherwartsoils.get(i);
if (WorldUtilities.getBlock(this.building.world, p.getAbove()) == Blocks.AIR &&
WorldUtilities.getBlock(this.building.world, p) == Blocks.SOUL_SAND)
return p;
}
for (i = 0; i < start; i++) {
Point p = this.netherwartsoils.get(i);
if (WorldUtilities.getBlock(this.building.world, p.getAbove()) == Blocks.AIR &&
WorldUtilities.getBlock(this.building.world, p) == Blocks.SOUL_SAND)
return p;
}
return null;
}
public Point getPathStartPos() {
if (this.pathStartPos != null)
return this.pathStartPos;
return getSellingPos();
}
public Point getPlantingLocation() {
for (Point p : this.woodspawn) {
Block block = WorldUtilities.getBlock(this.building.world, p);
if (block == Blocks.AIR || block == Blocks.SNOW_LAYER || (
BlockItemUtilities.isBlockDecorativePlant(block) && !(block instanceof net.minecraft.block.BlockSapling) && !(block instanceof org.millenaire.common.block.BlockMillSapling)))
return p;
}
return null;
}
public String getPlantingLocationType(Point target) {
return this.woodspawnTypes.get(target);
}
public Point getSellingPos() {
if (this.sellingPos != null)
return this.sellingPos;
return this.sleepingPos;
}
public Point getShelterPos() {
if (this.shelterPos != null)
return this.shelterPos;
return this.sleepingPos;
}
public Point getSilkwormHarvestLocation() {
if (this.silkwormblock.size() == 0)
return null;
int start = MillCommonUtilities.randomInt(this.silkwormblock.size());
int i;
for (i = start; i < this.silkwormblock.size(); i++) {
Point p = this.silkwormblock.get(i);
if (WorldUtilities.getBlockState(this.building.world, p) == MillBlocks.SILK_WORM.getDefaultState()
.withProperty((IProperty)BlockSilkWorm.PROGRESS, (Comparable)BlockSilkWorm.EnumType.SILKWORMFULL))
return p;
}
for (i = 0; i < start; i++) {
Point p = this.silkwormblock.get(i);
if (WorldUtilities.getBlockState(this.building.world, p) == MillBlocks.SILK_WORM.getDefaultState()
.withProperty((IProperty)BlockSilkWorm.PROGRESS, (Comparable)BlockSilkWorm.EnumType.SILKWORMFULL))
return p;
}
return null;
}
public Point getSleepingPos() {
return this.sleepingPos;
}
public Point getSnailSoilHarvestLocation() {
if (this.snailsoilblock.size() == 0)
return null;
int start = MillCommonUtilities.randomInt(this.snailsoilblock.size());
int i;
for (i = start; i < this.snailsoilblock.size(); i++) {
Point p = this.snailsoilblock.get(i);
if (WorldUtilities.getBlockState(this.building.world, p) == MillBlocks.SNAIL_SOIL.getDefaultState().withProperty((IProperty)BlockSnailSoil.PROGRESS, (Comparable)BlockSnailSoil.EnumType.SNAIL_SOIL_FULL))
return p;
}
for (i = 0; i < start; i++) {
Point p = this.snailsoilblock.get(i);
if (WorldUtilities.getBlockState(this.building.world, p) == MillBlocks.SNAIL_SOIL.getDefaultState().withProperty((IProperty)BlockSnailSoil.PROGRESS, (Comparable)BlockSnailSoil.EnumType.SNAIL_SOIL_FULL))
return p;
}
return null;
}
public List<Point> getSoilPoints(ResourceLocation type) {
for (int i = 0; i < this.soilTypes.size(); i++) {
if (((ResourceLocation)this.soilTypes.get(i)).equals(type))
return this.soils.get(i);
}
return null;
}
public Point getSugarCaneHarvestLocation() {
if (this.sugarcanesoils.size() == 0)
return null;
int start = MillCommonUtilities.randomInt(this.sugarcanesoils.size());
int i;
for (i = start; i < this.sugarcanesoils.size(); i++) {
Point p = this.sugarcanesoils.get(i);
if (WorldUtilities.getBlock(this.building.world, p.getRelative(0.0D, 2.0D, 0.0D)) == Blocks.REEDS)
return p;
}
for (i = 0; i < start; i++) {
Point p = this.sugarcanesoils.get(i);
if (WorldUtilities.getBlock(this.building.world, p.getRelative(0.0D, 2.0D, 0.0D)) == Blocks.REEDS)
return p;
}
return null;
}
public Point getSugarCanePlantingLocation() {
if (this.sugarcanesoils.size() == 0)
return null;
int start = MillCommonUtilities.randomInt(this.sugarcanesoils.size());
int i;
for (i = start; i < this.sugarcanesoils.size(); i++) {
Point p = this.sugarcanesoils.get(i);
if (WorldUtilities.getBlock(this.building.world, p.getAbove()) == Blocks.AIR)
return p;
}
for (i = 0; i < start; i++) {
Point p = this.sugarcanesoils.get(i);
if (WorldUtilities.getBlock(this.building.world, p.getAbove()) == Blocks.AIR)
return p;
}
return null;
}
private boolean isBlockJungleWood(IBlockState state) {
return (state.getValue((IProperty)BlockOldLog.VARIANT) == BlockPlanks.EnumType.JUNGLE);
}
public void readDataStream(PacketBuffer ds) throws IOException {
this.chests = StreamReadWrite.readPointList(ds);
this.furnaces = StreamReadWrite.readPointList(ds);
this.firepits = StreamReadWrite.readPointList(ds);
this.signs = StreamReadWrite.readPointList(ds);
this.stalls = StreamReadWrite.readPointList(ds);
this.banners = StreamReadWrite.readPointList(ds);
this.cultureBanners = StreamReadWrite.readPointList(ds);
for (Point p : this.chests) {
TileEntityLockedChest chest = p.getMillChest(this.building.mw.world);
if (chest != null)
chest.buildingPos = this.building.getPos();
}
}
public void readFromNBT(NBTTagCompound nbttagcompound) {
this.sleepingPos = Point.read(nbttagcompound, "spawnPos");
this.sellingPos = Point.read(nbttagcompound, "sellingPos");
this.craftingPos = Point.read(nbttagcompound, "craftingPos");
this.defendingPos = Point.read(nbttagcompound, "defendingPos");
this.shelterPos = Point.read(nbttagcompound, "shelterPos");
this.pathStartPos = Point.read(nbttagcompound, "pathStartPos");
this.leasurePos = Point.read(nbttagcompound, "leasurePos");
if (this.sleepingPos == null)
this.sleepingPos = this.building.getPos().getAbove();
NBTTagList nbttaglist = nbttagcompound.getTagList("chests", 10);
int i;
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null &&
!this.chests.contains(p))
this.chests.add(p);
}
if (!this.chests.contains(this.building.getPos()))
this.chests.add(0, this.building.getPos());
nbttaglist = nbttagcompound.getTagList("furnaces", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null)
this.furnaces.add(p);
}
nbttaglist = nbttagcompound.getTagList("firepits", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null)
this.firepits.add(p);
}
nbttaglist = nbttagcompound.getTagList("brewingStands", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null)
this.brewingStands.add(p);
}
nbttaglist = nbttagcompound.getTagList("banners", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null)
this.banners.add(p);
}
nbttaglist = nbttagcompound.getTagList("culturebanners", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null)
this.cultureBanners.add(p);
}
nbttaglist = nbttagcompound.getTagList("signs", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
this.signs.add(p);
}
nbttaglist = nbttagcompound.getTagList("netherwartsoils", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null)
this.netherwartsoils.add(p);
}
nbttaglist = nbttagcompound.getTagList("silkwormblock", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null)
this.silkwormblock.add(p);
}
nbttaglist = nbttagcompound.getTagList("snailsoilblock", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null)
this.snailsoilblock.add(p);
}
nbttaglist = nbttagcompound.getTagList("sugarcanesoils", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null)
this.sugarcanesoils.add(p);
}
nbttaglist = nbttagcompound.getTagList("fishingspots", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null)
this.fishingspots.add(p);
}
nbttaglist = nbttagcompound.getTagList("healingspots", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null)
this.healingspots.add(p);
}
nbttaglist = nbttagcompound.getTagList("stalls", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null)
this.stalls.add(p);
}
nbttaglist = nbttagcompound.getTagList("woodspawn", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null) {
this.woodspawn.add(p);
String type = nbttagcompound1.getString("type");
if (type != null)
this.woodspawnTypes.put(p, type);
}
}
nbttaglist = nbttagcompound.getTagList("brickspot", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
Point p = Point.read(nbttagcompound1, "pos");
if (p != null)
this.brickspot.add(p);
}
nbttaglist = nbttagcompound.getTagList("spawns", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
ResourceLocation spawnType = new ResourceLocation(nbttagcompound1.getString("type"));
this.spawnTypes.add(spawnType);
CopyOnWriteArrayList<Point> v = new CopyOnWriteArrayList<>();
NBTTagList nbttaglist2 = nbttagcompound1.getTagList("points", 10);
for (int j = 0; j < nbttaglist2.tagCount(); j++) {
NBTTagCompound nbttagcompound2 = nbttaglist2.getCompoundTagAt(j);
Point p = Point.read(nbttagcompound2, "pos");
if (p != null) {
v.add(p);
if (MillConfigValues.LogHybernation >= 2)
MillLog.minor(this, "Loaded spawn point: " + p);
}
}
this.spawns.add(v);
if (MillConfigValues.LogHybernation >= 2)
MillLog.minor(this, "Loaded " + v.size() + " spawn points for " + this.spawnTypes.get(i));
}
nbttaglist = nbttagcompound.getTagList("mobspawns", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
this.mobSpawnerTypes.add(new ResourceLocation(nbttagcompound1.getString("type")));
CopyOnWriteArrayList<Point> v = new CopyOnWriteArrayList<>();
NBTTagList nbttaglist2 = nbttagcompound1.getTagList("points", 10);
for (int j = 0; j < nbttaglist2.tagCount(); j++) {
NBTTagCompound nbttagcompound2 = nbttaglist2.getCompoundTagAt(j);
Point p = Point.read(nbttagcompound2, "pos");
if (p != null) {
v.add(p);
if (MillConfigValues.LogHybernation >= 2)
MillLog.minor(this, "Loaded spawn point: " + p);
}
}
this.mobSpawners.add(v);
if (MillConfigValues.LogHybernation >= 2)
MillLog.minor(this, "Loaded " + v.size() + " mob spawn points for " + this.spawnTypes.get(i));
}
nbttaglist = nbttagcompound.getTagList("sources", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
if (nbttagcompound1.hasKey("block_rl")) {
Block block = Block.getBlockFromName(nbttagcompound1.getString("block_rl"));
int meta = nbttagcompound1.getInteger("block_meta");
IBlockState blockState = block.getStateFromMeta(meta);
this.sourceTypes.add(blockState);
} else {
int blockId = nbttagcompound1.getInteger("type");
this.sourceTypes.add(Block.getBlockById(blockId).getDefaultState());
}
CopyOnWriteArrayList<Point> v = new CopyOnWriteArrayList<>();
NBTTagList nbttaglist2 = nbttagcompound1.getTagList("points", 10);
for (int j = 0; j < nbttaglist2.tagCount(); j++) {
NBTTagCompound nbttagcompound2 = nbttaglist2.getCompoundTagAt(j);
Point p = Point.read(nbttagcompound2, "pos");
if (p != null) {
v.add(p);
if (MillConfigValues.LogHybernation >= 3)
MillLog.debug(this, "Loaded source point: " + p);
}
}
this.sources.add(v);
if (MillConfigValues.LogHybernation >= 1)
MillLog.debug(this, "Loaded " + v.size() + " sources points for " + ((IBlockState)this.sourceTypes.get(i)).toString());
}
nbttaglist = nbttagcompound.getTagList("genericsoils", 10);
for (i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
ResourceLocation type = new ResourceLocation(nbttagcompound1.getString("type"));
NBTTagList nbttaglist2 = nbttagcompound1.getTagList("points", 10);
for (int j = 0; j < nbttaglist2.tagCount(); j++) {
NBTTagCompound nbttagcompound2 = nbttaglist2.getCompoundTagAt(j);
Point p = Point.read(nbttagcompound2, "pos");
if (p != null)
addSoilPoint(type, p);
}
}
for (Point p : this.chests) {
if (this.building.world.isChunkGeneratedAt(p.getiX() / 16, p.getiZ() / 16) && p
.getMillChest(this.building.world) != null)
(p.getMillChest(this.building.world)).buildingPos = this.building.getPos();
}
}
public void sendBuildingPacket(PacketBuffer data) throws IOException {
StreamReadWrite.writePointList(this.chests, data);
StreamReadWrite.writePointList(this.furnaces, data);
StreamReadWrite.writePointList(this.firepits, data);
StreamReadWrite.writePointList(this.signs, data);
StreamReadWrite.writePointList(this.stalls, data);
StreamReadWrite.writePointList(this.banners, data);
StreamReadWrite.writePointList(this.cultureBanners, data);
}
public void setCraftingPos(Point p) {
this.craftingPos = p;
}
public void setDefendingPos(Point p) {
this.defendingPos = p;
}
public void setLeasurePos(Point p) {
this.leasurePos = p;
}
public void setPathStartPos(Point p) {
this.pathStartPos = p;
}
public void setSellingPos(Point p) {
this.sellingPos = p;
}
public void setShelterPos(Point p) {
this.shelterPos = p;
}
public void setSleepingPos(Point p) {
this.sleepingPos = p;
}
public void writeToNBT(NBTTagCompound nbttagcompound) {
if (this.sleepingPos != null)
this.sleepingPos.write(nbttagcompound, "spawnPos");
if (this.sellingPos != null)
this.sellingPos.write(nbttagcompound, "sellingPos");
if (this.craftingPos != null)
this.craftingPos.write(nbttagcompound, "craftingPos");
if (this.defendingPos != null)
this.defendingPos.write(nbttagcompound, "defendingPos");
if (this.shelterPos != null)
this.shelterPos.write(nbttagcompound, "shelterPos");
if (this.pathStartPos != null)
this.pathStartPos.write(nbttagcompound, "pathStartPos");
if (this.leasurePos != null)
this.leasurePos.write(nbttagcompound, "leasurePos");
NBTTagList nbttaglist = new NBTTagList();
for (Point p : this.signs) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
if (p != null) {
p.write(nbttagcompound1, "pos");
} else {
nbttagcompound1.setDouble("pos_xCoord", 0.0D);
nbttagcompound1.setDouble("pos_yCoord", 0.0D);
nbttagcompound1.setDouble("pos_zCoord", 0.0D);
}
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("signs", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.netherwartsoils) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("netherwartsoils", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.silkwormblock) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("silkwormblock", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.snailsoilblock) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("snailsoilblock", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.sugarcanesoils) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("sugarcanesoils", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.fishingspots) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("fishingspots", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.healingspots) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("healingspots", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.stalls) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("stalls", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.woodspawn) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
if (this.woodspawnTypes.containsKey(p))
nbttagcompound1.setString("type", this.woodspawnTypes.get(p));
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("woodspawn", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.brickspot) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("brickspot", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
int i;
for (i = 0; i < this.spawns.size(); i++) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setString("type", ((ResourceLocation)this.spawnTypes.get(i)).toString());
NBTTagList nbttaglist2 = new NBTTagList();
for (Point p : this.spawns.get(i)) {
NBTTagCompound nbttagcompound2 = new NBTTagCompound();
p.write(nbttagcompound2, "pos");
nbttaglist2.appendTag((NBTBase)nbttagcompound2);
}
nbttagcompound1.setTag("points", (NBTBase)nbttaglist2);
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("spawns", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (i = 0; i < this.soilTypes.size(); i++) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setString("type", ((ResourceLocation)this.soilTypes.get(i)).toString());
NBTTagList nbttaglist2 = new NBTTagList();
for (Point p : this.soils.get(i)) {
NBTTagCompound nbttagcompound2 = new NBTTagCompound();
p.write(nbttagcompound2, "pos");
nbttaglist2.appendTag((NBTBase)nbttagcompound2);
}
nbttagcompound1.setTag("points", (NBTBase)nbttaglist2);
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("genericsoils", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (i = 0; i < this.mobSpawners.size(); i++) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setString("type", ((ResourceLocation)this.mobSpawnerTypes.get(i)).toString());
NBTTagList nbttaglist2 = new NBTTagList();
for (Point p : this.mobSpawners.get(i)) {
NBTTagCompound nbttagcompound2 = new NBTTagCompound();
p.write(nbttagcompound2, "pos");
nbttaglist2.appendTag((NBTBase)nbttagcompound2);
}
nbttagcompound1.setTag("points", (NBTBase)nbttaglist2);
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("mobspawns", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (i = 0; i < this.sources.size(); i++) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setString("block_rl", ((IBlockState)this.sourceTypes.get(i)).getBlock().getRegistryName().toString());
nbttagcompound1.setInteger("block_meta", ((IBlockState)this.sourceTypes
.get(i)).getBlock().getMetaFromState(this.sourceTypes.get(i)));
NBTTagList nbttaglist2 = new NBTTagList();
for (Point p : this.sources.get(i)) {
NBTTagCompound nbttagcompound2 = new NBTTagCompound();
p.write(nbttagcompound2, "pos");
nbttaglist2.appendTag((NBTBase)nbttagcompound2);
}
nbttagcompound1.setTag("points", (NBTBase)nbttaglist2);
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("sources", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.chests) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("chests", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.furnaces) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("furnaces", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.firepits) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("firepits", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.brewingStands) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("brewingStands", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.banners) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("banners", (NBTBase)nbttaglist);
nbttaglist = new NBTTagList();
for (Point p : this.cultureBanners) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
p.write(nbttagcompound1, "pos");
nbttaglist.appendTag((NBTBase)nbttagcompound1);
}
nbttagcompound.setTag("culturebanners", (NBTBase)nbttaglist);
}
}
| 412 | 0.860431 | 1 | 0.860431 | game-dev | MEDIA | 0.829662 | game-dev | 0.711021 | 1 | 0.711021 |
ftsrg/theta | 3,555 | subprojects/common/analysis/src/main/java/hu/bme/mit/theta/analysis/prod2/prod2explpred/Prod2ExplPredAnalysis.java | /*
* Copyright 2025 Budapest University of Technology and Economics
*
* 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 hu.bme.mit.theta.analysis.prod2.prod2explpred;
import static com.google.common.base.Preconditions.checkNotNull;
import hu.bme.mit.theta.analysis.Analysis;
import hu.bme.mit.theta.analysis.InitFunc;
import hu.bme.mit.theta.analysis.PartialOrd;
import hu.bme.mit.theta.analysis.TransFunc;
import hu.bme.mit.theta.analysis.expl.ExplPrec;
import hu.bme.mit.theta.analysis.expl.ExplState;
import hu.bme.mit.theta.analysis.expr.ExprAction;
import hu.bme.mit.theta.analysis.pred.PredPrec;
import hu.bme.mit.theta.analysis.pred.PredState;
import hu.bme.mit.theta.analysis.prod2.*;
import hu.bme.mit.theta.analysis.prod2.prod2explpred.Prod2ExplPredAbstractors.Prod2ExplPredAbstractor;
public final class Prod2ExplPredAnalysis<A extends ExprAction>
implements Analysis<Prod2State<ExplState, PredState>, A, Prod2Prec<ExplPrec, PredPrec>> {
private final PartialOrd<Prod2State<ExplState, PredState>> partialOrd;
private final InitFunc<Prod2State<ExplState, PredState>, Prod2Prec<ExplPrec, PredPrec>>
initFunc;
private final TransFunc<Prod2State<ExplState, PredState>, A, Prod2Prec<ExplPrec, PredPrec>>
transFunc;
private Prod2ExplPredAnalysis(
final Analysis<ExplState, ? super A, ExplPrec> analysis1,
final Analysis<PredState, ? super A, PredPrec> analysis2,
final StrengtheningOperator<ExplState, PredState, ExplPrec, PredPrec>
strenghteningOperator,
final Prod2ExplPredAbstractor prod2ExplPredAbstractor) {
checkNotNull(analysis1);
checkNotNull(analysis2);
partialOrd = Prod2Ord.create(analysis1.getPartialOrd(), analysis2.getPartialOrd());
initFunc =
Prod2InitFunc.create(
analysis1.getInitFunc(), analysis2.getInitFunc(), strenghteningOperator);
transFunc = Prod2ExplPredDedicatedTransFunc.create(prod2ExplPredAbstractor);
}
public static <A extends ExprAction> Prod2ExplPredAnalysis<A> create(
final Analysis<ExplState, ? super A, ExplPrec> analysis1,
final Analysis<PredState, ? super A, PredPrec> analysis2,
final StrengtheningOperator<ExplState, PredState, ExplPrec, PredPrec>
strenghteningOperator,
final Prod2ExplPredAbstractor prod2ExplPredAbstractor) {
return new Prod2ExplPredAnalysis<A>(
analysis1, analysis2, strenghteningOperator, prod2ExplPredAbstractor);
}
@Override
public PartialOrd<Prod2State<ExplState, PredState>> getPartialOrd() {
return partialOrd;
}
@Override
public InitFunc<Prod2State<ExplState, PredState>, Prod2Prec<ExplPrec, PredPrec>> getInitFunc() {
return initFunc;
}
@Override
public TransFunc<Prod2State<ExplState, PredState>, A, Prod2Prec<ExplPrec, PredPrec>>
getTransFunc() {
return transFunc;
}
}
| 412 | 0.694998 | 1 | 0.694998 | game-dev | MEDIA | 0.518183 | game-dev,scientific-computing | 0.618571 | 1 | 0.618571 |
Sgt-Imalas/Sgt_Imalas-Oni-Mods | 1,310 | OniRetroEdition/ModPatches/DeepFryerConfigPatch.cs | using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OniRetroEdition.ModPatches
{
internal class DeepFryerConfigPatch
{
[HarmonyPatch(typeof(DeepfryerConfig), nameof(DeepfryerConfig.ConfigureRecipes))]
public class DeepfryerConfig_ConfigureRecipes_Patch
{
public static void Postfix(DeepfryerConfig __instance)
{
ComplexRecipe.RecipeElement[] ingredients = [
new ComplexRecipe.RecipeElement((Tag) "Meat", 1f),
new ComplexRecipe.RecipeElement((Tag) "Tallow", 2f) ];
ComplexRecipe.RecipeElement[] products = [new ComplexRecipe.RecipeElement((Tag) "DeepFriedMeat", 1f, ComplexRecipe.RecipeElement.TemperatureOperation.Heated)];
DeepFriedMeatConfig.recipe = new ComplexRecipe(ComplexRecipeManager.MakeRecipeID("Deepfryer", (IList<ComplexRecipe.RecipeElement>)ingredients, (IList<ComplexRecipe.RecipeElement>)products), ingredients, products, [DlcManager.DLC2_ID])
{
time = TUNING.FOOD.RECIPES.STANDARD_COOK_TIME,
description = global::STRINGS.ITEMS.FOOD.DEEPFRIEDMEAT.RECIPEDESC,
nameDisplay = ComplexRecipe.RecipeNameDisplay.Result,
fabricators = new List<Tag>() { (Tag)"Deepfryer"},
sortOrder = 300
};
}
}
}
}
| 412 | 0.748179 | 1 | 0.748179 | game-dev | MEDIA | 0.946434 | game-dev | 0.654349 | 1 | 0.654349 |
MadeBaruna/paimon-moe-api | 1,407 | src/migrations/1659407527059-UpdateBanner.ts | import { MigrationInterface, QueryRunner } from 'typeorm';
import { Banner } from '../entities/banner';
const banners = {
characters: {
name: 'Tapestry of Golden Flames',
start: '2022-08-02 18:00:00',
end: '2022-08-23 14:59:59',
id: 300033,
},
weapons: {
name: 'Epitome Invocation',
start: '2022-08-02 18:00:00',
end: '2022-08-23 14:59:59',
id: 400032,
},
};
export class UpdateBanner1659407527059 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
const newCharacterBanner = banners.characters;
const characterBanner = new Banner();
characterBanner.id = newCharacterBanner.id;
characterBanner.type = 'characters';
characterBanner.name = newCharacterBanner.name;
characterBanner.start = `${newCharacterBanner.start}+8`;
characterBanner.end = `${newCharacterBanner.end}+8`;
const newWeaponBanner = banners.weapons;
const weaponBanner = new Banner();
weaponBanner.id = newWeaponBanner.id;
weaponBanner.type = 'weapons';
weaponBanner.name = newWeaponBanner.name;
weaponBanner.start = `${newWeaponBanner.start}+8`;
weaponBanner.end = `${newWeaponBanner.end}+8`;
await queryRunner.manager.save([characterBanner, weaponBanner]);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.manager.delete(Banner, [300033, 400032]);
}
}
| 412 | 0.852727 | 1 | 0.852727 | game-dev | MEDIA | 0.867836 | game-dev | 0.753236 | 1 | 0.753236 |
CaravelGames/drod | 2,979 | DRODLibTests/src/tests/Scripting/Imperative_Vulnerable_Invulnerable.cpp | #include "../../test-include.hpp"
#include "../../CAssert.h"
namespace {
void AddStabbingCharacter(UINT wX, UINT wY) {
CCharacter* pCharacter = RoomBuilder::AddVisibleCharacter(wX, wY, N, M_MIMIC);
RoomBuilder::AddCommand(pCharacter, CCharacterCommand::CC_Wait, 0);
RoomBuilder::AddCommand(pCharacter, CCharacterCommand::CC_MoveRel, 0, -1);
}
}
TEST_CASE("Scripting: Imperative - Vulnerable & Invulnerable", "[game]") {
RoomBuilder::ClearRoom();
CCharacter* pCharacter = RoomBuilder::AddCharacter(1, 1, NO_ORIENTATION);
RoomBuilder::AddCommand(pCharacter, CCharacterCommand::CC_SetPlayerStealth, StealthType::Stealth_Off);
SECTION("Wubba") {
SECTION("Wubba starts sword invulnerable by default") {
RoomBuilder::AddVisibleCharacter(10, 10, NO_ORIENTATION, M_WUBBA);
AddStabbingCharacter(10, 12);
Runner::StartGame(30, 30);
Runner::ExecuteCommand(CMD_WAIT);
AssertMonster(10, 10);
}
SECTION("Wubba set to imperative Vulnerable should be sword vulnerable") {
pCharacter = RoomBuilder::AddVisibleCharacter(10, 10, NO_ORIENTATION, M_WUBBA);
RoomBuilder::AddCommand(pCharacter, CCharacterCommand::CC_Imperative, ScriptFlag::Vulnerable);
AddStabbingCharacter(10, 12);
Runner::StartGame(30, 30);
Runner::ExecuteCommand(CMD_WAIT);
AssertNoMonster(10, 10);
}
SECTION("Wubba set to imperative Vulnerable then Invulnerable should be sword invulnerable") {
pCharacter = RoomBuilder::AddVisibleCharacter(10, 10, NO_ORIENTATION, M_WUBBA);
RoomBuilder::AddCommand(pCharacter, CCharacterCommand::CC_Imperative, ScriptFlag::Vulnerable);
RoomBuilder::AddCommand(pCharacter, CCharacterCommand::CC_Imperative, ScriptFlag::Invulnerable);
AddStabbingCharacter(10, 12);
Runner::StartGame(30, 30);
Runner::ExecuteCommand(CMD_WAIT);
AssertMonster(10, 10);
}
}
SECTION("Roach") {
SECTION("Roach starts sword vulnerable by default") {
RoomBuilder::AddVisibleCharacter(10, 10, N, M_ROACH);
AddStabbingCharacter(10, 12);
Runner::StartGame(30, 30);
Runner::ExecuteCommand(CMD_WAIT);
AssertNoMonster(10, 10);
}
SECTION("Roach set to imperative Invulnerable should be sword invulnerable") {
pCharacter = RoomBuilder::AddVisibleCharacter(10, 10, N, M_ROACH);
RoomBuilder::AddCommand(pCharacter, CCharacterCommand::CC_Imperative, ScriptFlag::Invulnerable);
AddStabbingCharacter(10, 12);
Runner::StartGame(30, 30);
Runner::ExecuteCommand(CMD_WAIT);
AssertMonster(10, 10);
}
SECTION("Roach set to imperative Invulnerable then Vulnerable should be sword vulnerable") {
pCharacter = RoomBuilder::AddVisibleCharacter(10, 10, N, M_ROACH);
RoomBuilder::AddCommand(pCharacter, CCharacterCommand::CC_Imperative, ScriptFlag::Invulnerable);
RoomBuilder::AddCommand(pCharacter, CCharacterCommand::CC_Imperative, ScriptFlag::Vulnerable);
AddStabbingCharacter(10, 12);
Runner::StartGame(30, 30);
Runner::ExecuteCommand(CMD_WAIT);
AssertNoMonster(10, 10);
}
}
}
| 412 | 0.979436 | 1 | 0.979436 | game-dev | MEDIA | 0.693914 | game-dev | 0.76471 | 1 | 0.76471 |
unattended-backpack/monorepo | 4,428 | sigil/optimism/op-challenger/game/fault/types/position.go | package types
import (
"errors"
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/common"
)
var (
ErrPositionDepthTooSmall = errors.New("position depth is too small")
RootPosition = NewPositionFromGIndex(big.NewInt(1))
)
// Depth is the depth of a position in a game tree where the root level has
// depth 0, the root's children have depth 1, their children have depth 2, and
// so on.
type Depth uint64
// Position is a golang wrapper around the dispute game Position type.
type Position struct {
depth Depth
indexAtDepth *big.Int
}
func NewPosition(depth Depth, indexAtDepth *big.Int) Position {
return Position{
depth: depth,
indexAtDepth: indexAtDepth,
}
}
// NewPositionFromGIndex creates a new Position given a generalized index.
func NewPositionFromGIndex(x *big.Int) Position {
depth := bigMSB(x)
withoutMSB := new(big.Int).Not(new(big.Int).Lsh(big.NewInt(1), uint(depth)))
indexAtDepth := new(big.Int).And(x, withoutMSB)
return NewPosition(depth, indexAtDepth)
}
func (p Position) String() string {
return fmt.Sprintf("Position(depth: %v, indexAtDepth: %v)", p.depth, p.IndexAtDepth())
}
func (p Position) MoveRight() Position {
return Position{
depth: p.depth,
indexAtDepth: new(big.Int).Add(p.IndexAtDepth(), big.NewInt(1)),
}
}
// RelativeToAncestorAtDepth returns a new position for a subtree.
// [ancestor] is the depth of the subtree root node.
func (p Position) RelativeToAncestorAtDepth(ancestor Depth) (Position, error) {
if ancestor > p.depth {
return Position{}, ErrPositionDepthTooSmall
}
newPosDepth := p.depth - ancestor
nodesAtDepth := 1 << newPosDepth
newIndexAtDepth := new(big.Int).Mod(p.IndexAtDepth(), big.NewInt(int64(nodesAtDepth)))
return NewPosition(newPosDepth, newIndexAtDepth), nil
}
func (p Position) Depth() Depth {
return p.depth
}
func (p Position) IndexAtDepth() *big.Int {
if p.indexAtDepth == nil {
return common.Big0
}
return p.indexAtDepth
}
func (p Position) IsRootPosition() bool {
return p.depth == 0 && common.Big0.Cmp(p.IndexAtDepth()) == 0
}
func (p Position) lshIndex(amount Depth) *big.Int {
return new(big.Int).Lsh(p.IndexAtDepth(), uint(amount))
}
// TraceIndex calculates the what the index of the claim value would be inside the trace.
// It is equivalent to going right until the final depth has been reached.
// Note: this method will panic if maxDepth < p.depth
func (p Position) TraceIndex(maxDepth Depth) *big.Int {
// When we go right, we do a shift left and set the bottom bit to be 1.
// To do this in a single step, do all the shifts at once & or in all 1s for the bottom bits.
if maxDepth < p.depth {
panic(fmt.Sprintf("maxDepth(%d) < p.depth(%d)", maxDepth, p.depth))
}
rd := maxDepth - p.depth
rhs := new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), uint(rd)), big.NewInt(1))
ti := new(big.Int).Or(p.lshIndex(rd), rhs)
return ti
}
// move returns a new position at the left or right child.
func (p Position) move(right bool) Position {
return Position{
depth: p.depth + 1,
indexAtDepth: new(big.Int).Or(p.lshIndex(1), big.NewInt(int64(boolToInt(right)))),
}
}
func boolToInt(b bool) int {
if b {
return 1
} else {
return 0
}
}
func (p Position) parentIndexAtDepth() *big.Int {
return new(big.Int).Div(p.IndexAtDepth(), big.NewInt(2))
}
func (p Position) RightOf(parent Position) bool {
return p.parentIndexAtDepth().Cmp(parent.IndexAtDepth()) != 0
}
// parent return a new position that is the parent of this Position.
func (p Position) parent() Position {
return Position{
depth: p.depth - 1,
indexAtDepth: p.parentIndexAtDepth(),
}
}
// Attack creates a new position which is the attack position of this one.
func (p Position) Attack() Position {
return p.move(false)
}
// Defend creates a new position which is the defend position of this one.
func (p Position) Defend() Position {
return p.parent().move(true).move(false)
}
func (p Position) Print(maxDepth Depth) {
fmt.Printf("GIN: %4b\tTrace Position is %4b\tTrace Depth is: %d\tTrace Index is: %d\n", p.ToGIndex(), p.IndexAtDepth(), p.depth, p.TraceIndex(maxDepth))
}
func (p Position) ToGIndex() *big.Int {
return new(big.Int).Or(new(big.Int).Lsh(big.NewInt(1), uint(p.depth)), p.IndexAtDepth())
}
// bigMSB returns the index of the most significant bit
func bigMSB(x *big.Int) Depth {
if x.Cmp(big.NewInt(0)) == 0 {
return 0
}
return Depth(x.BitLen() - 1)
}
| 412 | 0.84979 | 1 | 0.84979 | game-dev | MEDIA | 0.292174 | game-dev | 0.877866 | 1 | 0.877866 |
acmeism/RosettaCodeData | 2,698 | Task/Minesweeper-game/BASIC256/minesweeper-game.basic | N = 6 : M = 5 : H = 25 : P = 0.2
fastgraphics
graphsize N*H,(M+1)*H
font "Arial",H/2+1,75
dim f(N,M) # 1 open, 2 mine, 4 expected mine
dim s(N,M) # count of mines in a neighborhood
trian1 = {1,1,H-1,1,H-1,H-1} : trian2 = {1,1,1,H-1,H-1,H-1}
mine = {2,2, H/2,H/2-2, H-2,2, H/2+2,H/2, H-2,H-2, H/2,H/2+2, 2,H-2, H/2-2,H/2}
flag = {H/2-1,3, H/2+1,3, H-4,H/5, H/2+1,H*2/5, H/2+1,H*0.9-2, H*0.8,H-2, H*0.2,H-2, H/2-1,H*0.9-2}
mines = int(N*M*P) : k = mines : act = 0
while k>0
i = int(rand*N) : j = int(rand*M)
if not f[i,j] then
f[i,j] = 2 : k = k - 1 # set mine
s[i,j] = s[i,j] + 1 : gosub adj # count it
end if
end while
togo = M*N-mines : over = 0 : act = 1
gosub redraw
while not over
clickclear
while not clickb
pause 0.01
end while
i = int(clickx/H) : j = int(clicky/H)
if i<N and j<M then
if clickb=1 then
if not (f[i,j]&4) then ai = i : aj = j : gosub opencell
if not s[i,j] then gosub adj
else
if not (f[i,j]&1) then
if f[i,j]&4 then mines = mines+1
if not (f[i,j]&4) then mines = mines-1
f[i,j] = (f[i,j]&~4)|(~f[i,j]&4)
end if
end if
if not (togo or mines) then over = 1
gosub redraw
end if
end while
imgsave "Minesweeper_game_BASIC-256.png", "PNG"
end
redraw:
for i = 0 to N-1
for j = 0 to M-1
if over=-1 and f[i,j]&2 then f[i,j] = f[i,j]|1
gosub drawcell
next j
next i
# Counter
color (32,32,32) : rect 0,M*H,N*H,H
color white : x = 5 : y = M*H+H*0.05
if not over then text x,y,"Mines: " + mines
if over=1 then text x,y,"You won!"
if over=-1 then text x,y,"You lost"
refresh
return
drawcell:
color darkgrey
rect i*H,j*H,H,H
if f[i,j]&1=0 then # closed
color black : stamp i*H,j*H,trian1
color white : stamp i*H,j*H,trian2
color grey : rect i*H+2,j*H+2,H-4,H-4
if f[i,j]&4 then color blue : stamp i*H,j*H,flag
else
color 192,192,192 : rect i*H+1,j*H+1,H-2,H-2
# Draw
if f[i,j]&2 then # mine
if not (f[i,j]&4) then color red
if f[i,j]&4 then color darkgreen
circle i*H+H/2,j*H+H/2,H/5 : stamp i*H,j*H,mine
else
if s[i,j] then color (32,32,32) : text i*H+H/3,j*H+1,s[i,j]
end if
end if
return
adj:
aj = j-1
if j and i then ai = i-1 : gosub adjact
if j then ai = i : gosub adjact
if j and i<N-1 then ai = i+1 : gosub adjact
aj = j
if i then ai = i-1 : gosub adjact
if i<N-1 then ai = i+1 : gosub adjact
aj = j+1
if j<M-1 and i then ai = i-1 : gosub adjact
if j<M-1 then ai = i : gosub adjact
if j<M-1 and i<N-1 then ai = i+1 : gosub adjact
return
adjact:
if not act then s[ai,aj] = s[ai,aj]+1 : return
if act then gosub opencell : return
opencell:
if not (f[ai,aj]&1) then
f[ai,aj] = f[ai,aj]|1
togo = togo-1
end if
if f[ai,aj]&2 then over = -1
return
| 412 | 0.766928 | 1 | 0.766928 | game-dev | MEDIA | 0.555728 | game-dev | 0.913026 | 1 | 0.913026 |
akhuting/gms083 | 9,513 | src/main/java/server/maps/MapleReactorFactory.java | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package server.maps;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import provider.MapleData;
import provider.MapleDataProvider;
import provider.MapleDataProviderFactory;
import provider.MapleDataTool;
import server.maps.MapleReactorStats.StateData;
import tools.Pair;
import tools.StringUtil;
public class MapleReactorFactory {
private static MapleDataProvider data = MapleDataProviderFactory.getDataProvider(new File(System.getProperty("wzpath") + "/Reactor.wz"));
private static Map<Integer, MapleReactorStats> reactorStats = new HashMap<Integer, MapleReactorStats>();
public static final MapleReactorStats getReactorS(int rid) {
MapleReactorStats stats = reactorStats.get(Integer.valueOf(rid));
if (stats == null) {
int infoId = rid;
MapleData reactorData = data.getData(StringUtil.getLeftPaddedStr(Integer.toString(infoId) + ".img", '0', 11));
MapleData link = reactorData.getChildByPath("info/link");
if (link != null) {
infoId = MapleDataTool.getIntConvert("info/link", reactorData);
stats = reactorStats.get(Integer.valueOf(infoId));
}
if (stats == null) {
stats = new MapleReactorStats();
reactorData = data.getData(StringUtil.getLeftPaddedStr(Integer.toString(infoId) + ".img", '0', 11));
if (reactorData == null) {
return stats;
}
boolean canTouch = MapleDataTool.getInt("info/activateByTouch", reactorData, 0) > 0;
boolean areaSet = false;
boolean foundState = false;
for (byte i = 0; true; i++) {
MapleData reactorD = reactorData.getChildByPath(String.valueOf(i));
if (reactorD == null) {
break;
}
MapleData reactorInfoData_ = reactorD.getChildByPath("event");
if (reactorInfoData_ != null && reactorInfoData_.getChildByPath("0") != null) {
MapleData reactorInfoData = reactorInfoData_.getChildByPath("0");
Pair<Integer, Integer> reactItem = null;
int type = MapleDataTool.getIntConvert("type", reactorInfoData);
if (type == 100) { //reactor waits for item
reactItem = new Pair<Integer, Integer>(MapleDataTool.getIntConvert("0", reactorInfoData), MapleDataTool.getIntConvert("1", reactorInfoData, 1));
if (!areaSet) { //only set area of effect for item-triggered reactors once
stats.setTL(MapleDataTool.getPoint("lt", reactorInfoData));
stats.setBR(MapleDataTool.getPoint("rb", reactorInfoData));
areaSet = true;
}
}
foundState = true;
stats.addState(i, type, reactItem, (byte) MapleDataTool.getIntConvert("state", reactorInfoData), MapleDataTool.getIntConvert("timeOut", reactorInfoData_, -1), (byte) (canTouch ? 2 : (MapleDataTool.getIntConvert("2", reactorInfoData, 0) > 0 || reactorInfoData.getChildByPath("clickArea") != null || type == 9 ? 1 : 0)));
} else {
stats.addState(i, 999, null, (byte) (foundState ? -1 : (i + 1)), 0, (byte) 0);
}
}
reactorStats.put(Integer.valueOf(infoId), stats);
if (rid != infoId) {
reactorStats.put(Integer.valueOf(rid), stats);
}
} else { // stats exist at infoId but not rid; add to map
reactorStats.put(Integer.valueOf(rid), stats);
}
}
return stats;
}
public static MapleReactorStats getReactor(int rid) {
MapleReactorStats stats = reactorStats.get(Integer.valueOf(rid));
if (stats == null) {
int infoId = rid;
MapleData reactorData = data.getData(StringUtil.getLeftPaddedStr(Integer.toString(infoId) + ".img", '0', 11));
MapleData link = reactorData.getChildByPath("info/link");
if (link != null) {
infoId = MapleDataTool.getIntConvert("info/link", reactorData);
stats = reactorStats.get(Integer.valueOf(infoId));
}
MapleData activateOnTouch = reactorData.getChildByPath("info/activateByTouch");
boolean loadArea = false;
if (activateOnTouch != null) {
loadArea = MapleDataTool.getInt("info/activateByTouch", reactorData, 0) != 0;
}
if (stats == null) {
reactorData = data.getData(StringUtil.getLeftPaddedStr(Integer.toString(infoId) + ".img", '0', 11));
MapleData reactorInfoData = reactorData.getChildByPath("0");
stats = new MapleReactorStats();
List<StateData> statedatas = new ArrayList<>();
if (reactorInfoData != null) {
boolean areaSet = false;
byte i = 0;
while (reactorInfoData != null) {
MapleData eventData = reactorInfoData.getChildByPath("event");
if (eventData != null) {
int timeOut = -1;
for (MapleData fknexon : eventData.getChildren()) {
if (fknexon.getName().equalsIgnoreCase("timeOut")) {
timeOut = MapleDataTool.getInt(fknexon);
} else {
Pair<Integer, Integer> reactItem = null;
int type = MapleDataTool.getIntConvert("type", fknexon);
if (type == 100) { //reactor waits for item
reactItem = new Pair<Integer, Integer>(MapleDataTool.getIntConvert("0", fknexon), MapleDataTool.getIntConvert("1", fknexon));
if (!areaSet || loadArea) { //only set area of effect for item-triggered reactors once
stats.setTL(MapleDataTool.getPoint("lt", fknexon));
stats.setBR(MapleDataTool.getPoint("rb", fknexon));
areaSet = true;
}
}
MapleData activeSkillID = fknexon.getChildByPath("activeSkillID");
List<Integer> skillids = null;
if (activeSkillID != null) {
skillids = new ArrayList<Integer>();
for (MapleData skill : activeSkillID.getChildren()) {
skillids.add(MapleDataTool.getInt(skill));
}
}
byte nextState = (byte) MapleDataTool.getIntConvert("state", fknexon);
statedatas.add(new StateData(type, reactItem, skillids, nextState));
}
}
stats.addState(i, statedatas, timeOut);
}
i++;
reactorInfoData = reactorData.getChildByPath(Byte.toString(i));
statedatas = new ArrayList<>();
}
} else //sit there and look pretty; likely a reactor such as Zakum/Papulatus doors that shows if player can enter
{
statedatas.add(new StateData(999, null, null, (byte) 0));
stats.addState((byte) 0, statedatas, -1);
}
reactorStats.put(Integer.valueOf(infoId), stats);
if (rid != infoId) {
reactorStats.put(Integer.valueOf(rid), stats);
}
} else // stats exist at infoId but not rid; add to map
{
reactorStats.put(Integer.valueOf(rid), stats);
}
}
return stats;
}
}
| 412 | 0.757003 | 1 | 0.757003 | game-dev | MEDIA | 0.655543 | game-dev | 0.833772 | 1 | 0.833772 |
liballeg/allegro4 | 4,273 | tools/plugins/datworms.c | /* ______ ___ ___
* /\ _ \ /\_ \ /\_ \
* \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___
* \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\
* \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \
* \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/
* \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/
* /\____/
* \_/__/
*
* A really silly little Worms grabber plugin.
*
* By Shawn Hargreaves.
*
* See readme.txt for copyright information.
*/
#include <stdio.h>
#include "allegro.h"
#include "../datedit.h"
/* what a pointless way to spend my Sunday afternoon :-) */
static int worms(void)
{
#define MAX_SIZE 65536
int *xpos = malloc(sizeof(int)*MAX_SIZE);
int *ypos = malloc(sizeof(int)*MAX_SIZE);
int head, tail, dir, dead, quit, score, counter;
int tx, ty, x, y, i, c1, c2, c3;
again:
head = 0;
tail = 0;
dir = 0;
dead = FALSE;
quit = FALSE;
score = 0;
counter = 0;
tx = -100;
ty = -100;
show_mouse(NULL);
if (bitmap_color_depth(screen) <= 8) {
PALETTE pal;
get_palette(pal);
pal[0].r = 0;
pal[0].g = 0;
pal[0].b = 0;
pal[1].r = 31;
pal[1].g = 31;
pal[1].b = 31;
pal[254].r = 31;
pal[254].g = 31;
pal[254].b = 31;
pal[255].r = 63;
pal[255].g = 63;
pal[255].b = 63;
set_palette(pal);
c1 = 0;
c2 = 1;
c3 = 255;
}
else {
c1 = gui_fg_color;
c2 = gui_mg_color;
c3 = gui_bg_color;
}
clear_to_color(screen, c1);
xor_mode(TRUE);
xpos[0] = SCREEN_W/2;
ypos[0] = SCREEN_H/2;
putpixel(screen, xpos[0], ypos[0], c3);
while ((!dead) && (!quit)) {
x = xpos[head];
y = ypos[head];
switch (dir) {
case 0: x++; break;
case 1: y++; break;
case 2: x--; break;
case 3: y--; break;
}
if (x >= SCREEN_W)
x -= SCREEN_W;
else if (x < 0)
x += SCREEN_W;
if (y >= SCREEN_H)
y -= SCREEN_H;
else if (y < 0)
y += SCREEN_H;
head++;
if (head >= MAX_SIZE)
head = 0;
xpos[head] = x;
ypos[head] = y;
counter++;
if (counter & 15) {
putpixel(screen, xpos[tail], ypos[tail], c3);
tail++;
if (tail >= MAX_SIZE)
tail = 0;
}
i = tail;
while (i != head) {
if ((x == xpos[i]) && (y == ypos[i])) {
dead = TRUE;
break;
}
i++;
if (i >= MAX_SIZE)
i = 0;
}
if (!(counter % (1+(score+2)/3)))
vsync();
putpixel(screen, x, y, c3);
if ((tx < 0) || (ty < 0)) {
do {
tx = 16+AL_RAND()%(SCREEN_W-32);
ty = 16+AL_RAND()%(SCREEN_H-32);
} while ((ABS(x-tx)+ABS(y-ty)) < 64);
circle(screen, tx, ty, 8, c2);
circle(screen, tx, ty, 5, c2);
circle(screen, tx, ty, 2, c2);
}
if ((ABS(x-tx)+ABS(y-ty)) < 9) {
circle(screen, tx, ty, 8, c2);
circle(screen, tx, ty, 5, c2);
circle(screen, tx, ty, 2, c2);
tx = -100;
ty = -100;
score++;
}
textprintf_ex(screen, font, 0, 0, c2, c1, "Score: %d", score);
if (keypressed()) {
switch (readkey()>>8) {
case KEY_RIGHT:
dir = 0;
break;
case KEY_DOWN:
dir = 1;
break;
case KEY_LEFT:
dir = 2;
break;
case KEY_UP:
dir = 3;
break;
case KEY_ESC:
quit = TRUE;
break;
}
}
}
xor_mode(FALSE);
clear_to_color(screen, gui_fg_color);
set_palette(datedit_current_palette);
do {
poll_keyboard();
} while ((key[KEY_ESC]) || (key[KEY_RIGHT]) || (key[KEY_LEFT]) || (key[KEY_UP]) || (key[KEY_DOWN]));
clear_keybuf();
show_mouse(screen);
if (dead) {
char buf[64];
sprintf(buf, "Score: %d", score);
if (alert(buf, NULL, NULL, "Play", "Quit", 'p', 'q') == 1)
goto again;
}
free(xpos);
free(ypos);
return D_REDRAW;
}
/* hook ourselves into the grabber menu system */
static MENU worms_menu =
{
"Worms",
worms,
NULL,
0,
NULL
};
DATEDIT_MENU_INFO datworms_menu =
{
&worms_menu,
NULL,
DATEDIT_MENU_HELP,
0,
NULL
};
| 412 | 0.742786 | 1 | 0.742786 | game-dev | MEDIA | 0.453914 | game-dev | 0.918311 | 1 | 0.918311 |
jediminer543/JMT-MCMT | 1,625 | src/main/java/org/jmt/mcmt/commands/PerfCommand.java | package org.jmt.mcmt.commands;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.jmt.mcmt.asmdest.ASMHookTerminator;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import net.minecraft.util.text.StringTextComponent;
public class PerfCommand {
public static LiteralArgumentBuilder<CommandSource> registerPerf(LiteralArgumentBuilder<CommandSource> root) {
return root.then(Commands.literal("mspt").executes(cmdCtx -> {
try {
double mspt = Arrays.stream(ASMHookTerminator.lastTickTime)
.boxed().collect(Collectors.toList()).subList(0, ASMHookTerminator.lastTickTimeFill)
.stream().mapToDouble(i->i/1000000.0).average().orElse(0);
double last = ASMHookTerminator.lastTickTime[(ASMHookTerminator.lastTickTimePos-1)%ASMHookTerminator.lastTickTime.length]/1000000.0;
StringTextComponent message = new StringTextComponent(
"Average MSPT was " + mspt + "ms (Last: " + last + "ms)");
cmdCtx.getSource().sendFeedback(message, true);
} catch (Exception e) {
e.printStackTrace();
}
return 1;
})).then(Commands.literal("tps").executes(cmdCtx -> {
double mspt = Arrays.stream(ASMHookTerminator.lastTickTime)
.boxed().collect(Collectors.toList()).subList(0, ASMHookTerminator.lastTickTimeFill)
.stream().mapToDouble(i->i/1000000.0).average().orElse(0);
StringTextComponent message = new StringTextComponent(
"Theoretical peak average TPS is " + 1000/mspt + "tps");
cmdCtx.getSource().sendFeedback(message, true);
return 1;
}));
}
}
| 412 | 0.786467 | 1 | 0.786467 | game-dev | MEDIA | 0.695147 | game-dev,networking | 0.935956 | 1 | 0.935956 |
GabrielOlvH/Industrial-Revolution | 1,222 | src/main/kotlin/me/steven/indrev/recipes/machines/ElectrolysisRecipe.kt | package me.steven.indrev.recipes.machines
import me.steven.indrev.recipes.machines.entries.InputEntry
import me.steven.indrev.recipes.machines.entries.OutputEntry
import me.steven.indrev.utils.IRFluidAmount
import me.steven.indrev.utils.identifier
import net.minecraft.recipe.RecipeSerializer
import net.minecraft.util.Identifier
class ElectrolysisRecipe(
override val identifier: Identifier,
override val input: Array<InputEntry>,
override val outputs: Array<OutputEntry>,
override val fluidInput: Array<IRFluidAmount>,
override val fluidOutput: Array<IRFluidAmount>,
override val ticks: Int
) : IRFluidRecipe() {
override fun getType(): IRRecipeType<*> = TYPE
override fun fits(width: Int, height: Int): Boolean = true
override fun getSerializer(): RecipeSerializer<*> = SERIALIZER
companion object {
val IDENTIFIER = identifier("electrolysis")
val TYPE = IRRecipeType<ElectrolysisRecipe>(IDENTIFIER)
val SERIALIZER = Serializer()
class Serializer : IRFluidRecipeSerializer<ElectrolysisRecipe>({ id, ingredients, output, fluidInput, fluidOutput, ticks -> ElectrolysisRecipe(id, ingredients, output, fluidInput, fluidOutput, ticks) })
}
} | 412 | 0.87996 | 1 | 0.87996 | game-dev | MEDIA | 0.181069 | game-dev | 0.803471 | 1 | 0.803471 |
RimWorldCCLTeam/CommunityCoreLibrary | 1,037 | _Mod/User Release/Community Core Library/Languages/French/DefInjected/MiniMapDef/MiniMaps.xml | <?xml version="1.0" encoding="utf-8" ?>
<LanguageData>
<MiniMap_ViewPort.label>vue actuelle</MiniMap_ViewPort.label>
<MiniMap_ViewPort.description>Montre la vue actuelle.</MiniMap_ViewPort.description>
<MiniMap_Fog.label>brouillard</MiniMap_Fog.label>
<MiniMap_Fog.description>Montre le brouillard.</MiniMap_Fog.description>
<MiniMap_Pawns.label>personnages</MiniMap_Pawns.label>
<MiniMap_Pawns.description>Montre les personnages.</MiniMap_Pawns.description>
<MiniMap_Utilities.label>constructions</MiniMap_Utilities.label>
<MiniMap_Utilities.description>Montre les constructions.</MiniMap_Utilities.description>
<MiniMap_Areas.label>zones</MiniMap_Areas.label>
<MiniMap_Areas.description>Montre les différentes zones.</MiniMap_Areas.description>
<MiniMap_Terrain.label>terrain</MiniMap_Terrain.label>
<MiniMap_Terrain.description>Montre les détails du terrain.</MiniMap_Terrain.description>
</LanguageData> | 412 | 0.722184 | 1 | 0.722184 | game-dev | MEDIA | 0.791958 | game-dev | 0.803574 | 1 | 0.803574 |
ohosvscode/ohos_electron_hap | 3,401 | web_engine/src/main/ets/common/InjectModule.ets | /*
* Copyright (c) 2023-2025 Haitai FangYuan Co., Ltd.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
import common from '@ohos.app.ability.common';
import { Container, interfaces, ContainerModule } from 'inversify';
import { MODULE_TYPE } from "./ModuleType";
import { Dependency, DependencyProvider } from '../interface/Dependency';
export default class InjectModule {
private static container = new Container({ defaultScope: "Singleton" });
private static dependency: Dependency;
private static isInject: boolean = false;
static inject(provider: DependencyProvider) {
if (InjectModule.isInject) {
return;
}
try {
InjectModule.dependency = provider.createDependency();
InjectModule.container.bind<common.Context>(MODULE_TYPE.Context).toDynamicValue(
() => {
return InjectModule.dependency.getContext();
});
InjectModule.container.load(InjectModule.dependency.getCommonModule(),
InjectModule.dependency.getAdapterModule());
InjectModule.isInject = true;
} catch(err) {
throw new Error('inject Module failed: ' + JSON.stringify(err));
}
}
static get<T>(serviceIdentifier: interfaces.ServiceIdentifier<T>): T {
return InjectModule.container.get<T>(serviceIdentifier);
}
static getOrCreate<T>(serviceIdentifier: interfaces.ServiceIdentifier<T>): T {
try {
const module = InjectModule.container.get<T>(serviceIdentifier);
if (module) {
return module;
}
} catch (err) {
const loadMode = new ContainerModule((bind:interfaces.Bind) => {
bind(serviceIdentifier).toSelf()
});
InjectModule.container.load(loadMode);
return InjectModule.container.get<T>(serviceIdentifier);
} finally {
return InjectModule.container.get<T>(serviceIdentifier);
}
}
static destroy() {
InjectModule.container.unbindAll();
}
}
| 412 | 0.842995 | 1 | 0.842995 | game-dev | MEDIA | 0.684351 | game-dev | 0.636167 | 1 | 0.636167 |
GeyserMC/Geyser | 2,902 | core/src/main/java/org/geysermc/geyser/translator/protocol/java/JavaBossEventTranslator.java | /*
* Copyright (c) 2019-2022 GeyserMC. http://geysermc.org
*
* 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.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.geyser.translator.protocol.java;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.ClientboundBossEventPacket;
import org.geysermc.geyser.session.GeyserSession;
import org.geysermc.geyser.session.cache.BossBar;
import org.geysermc.geyser.translator.protocol.PacketTranslator;
import org.geysermc.geyser.translator.protocol.Translator;
@Translator(packet = ClientboundBossEventPacket.class)
public class JavaBossEventTranslator extends PacketTranslator<ClientboundBossEventPacket> {
@Override
public void translate(GeyserSession session, ClientboundBossEventPacket packet) {
BossBar bossBar = session.getEntityCache().getBossBar(packet.getUuid());
switch (packet.getAction()) {
case ADD:
long entityId = session.getEntityCache().getNextEntityId().incrementAndGet();
bossBar = new BossBar(session, entityId, packet.getTitle(), packet.getHealth(), packet.getColor().ordinal(), 1, 0);
session.getEntityCache().addBossBar(packet.getUuid(), bossBar);
break;
case UPDATE_TITLE:
if (bossBar != null) bossBar.updateTitle(packet.getTitle());
break;
case UPDATE_HEALTH:
if (bossBar != null) bossBar.updateHealth(packet.getHealth());
break;
case REMOVE:
session.getEntityCache().removeBossBar(packet.getUuid());
break;
case UPDATE_STYLE:
if (bossBar != null) bossBar.updateColor(packet.getColor().ordinal());
break;
case UPDATE_FLAGS:
//todo
}
}
}
| 412 | 0.80741 | 1 | 0.80741 | game-dev | MEDIA | 0.47913 | game-dev,networking | 0.798972 | 1 | 0.798972 |
DanceManiac/Advanced-X-Ray-Public | 1,118 | SourcesAXR/editor/property_integer_limited_reference.cpp | ////////////////////////////////////////////////////////////////////////////
// Module : property_integer_limited_reference.cpp
// Created : 17.12.2007
// Modified : 17.12.2007
// Author : Dmitriy Iassenev
// Description : limited integer property reference implementation class
////////////////////////////////////////////////////////////////////////////
#include "pch.hpp"
#include "property_integer_limited_reference.hpp"
property_integer_limited_reference::property_integer_limited_reference (
int& value,
int const %min,
int const %max
) :
inherited (value),
m_min (min),
m_max (max)
{
}
System::Object ^property_integer_limited_reference::get_value ()
{
int value = safe_cast<int>(inherited::get_value());
if (value < m_min)
value = m_min;
if (value > m_max)
value = m_max;
return (value);
}
void property_integer_limited_reference::set_value (System::Object ^object)
{
int new_value = safe_cast<int>(object);
if (new_value < m_min)
new_value = m_min;
if (new_value > m_max)
new_value = m_max;
inherited::set_value (new_value);
} | 412 | 0.89958 | 1 | 0.89958 | game-dev | MEDIA | 0.245284 | game-dev | 0.950812 | 1 | 0.950812 |
LmeSzinc/AzurLaneAutoScript | 29,713 | module/map/map_base.py | import copy
from module.base.utils import location2node, node2location
from module.logger import logger
from module.map.map_grids import SelectedGrids
from module.map.utils import *
from module.map_detection.grid_info import GridInfo
class CampaignMap:
def __init__(self, name=None):
self.name = name
self.grid_class = GridInfo
self.grids = {}
self._shape = (0, 0)
self._map_data = ''
self._map_data_loop = ''
self._weight_data = ''
self._wall_data = ''
self._portal_data = []
self._land_based_data = []
self._maze_data = []
self.maze_round = 9
self._fortress_data = [(), ()]
self._bouncing_enemy_data = []
self._spawn_data = []
self._spawn_data_stack = []
self._spawn_data_loop = []
self._spawn_data_use_loop = False
self._camera_data = []
self._camera_data_spawn_point = []
self._map_covered = SelectedGrids([])
self._ignore_prediction = []
self.in_map_swipe_preset_data = None
self.poor_map_data = False
self.camera_sight = (-3, -1, 3, 2)
self.grid_connection = {}
def __iter__(self):
return iter(self.grids.values())
def __getitem__(self, item):
"""
Args:
item:
Returns:
GridInfo:
"""
return self.grids[tuple(item)]
def __contains__(self, item):
return tuple(item) in self.grids
@staticmethod
def _parse_text(text):
text = text.strip()
for y, row in enumerate(text.split('\n')):
row = row.strip()
for x, data in enumerate(row.split(' ')):
yield (x, y), data
@property
def shape(self):
return self._shape
@shape.setter
def shape(self, scale):
self._shape = node2location(scale.upper())
for y in range(self._shape[1] + 1):
for x in range(self._shape[0] + 1):
grid = self.grid_class()
grid.location = (x, y)
self.grids[(x, y)] = grid
# camera_data can be generate automatically, but it's better to set it manually.
self.camera_data = [location2node(loca) for loca in camera_2d((0, 0, *self._shape), sight=self.camera_sight)]
self.camera_data_spawn_point = []
# weight_data set to 10.
for grid in self:
grid.weight = 10.
@property
def map_data(self):
return self._map_data
@map_data.setter
def map_data(self, text):
self._map_data = text
self._load_map_data(text)
@property
def map_data_loop(self):
return self._map_data_loop
@map_data_loop.setter
def map_data_loop(self, text):
self._map_data_loop = text
def load_map_data(self, use_loop=False):
"""
Args:
use_loop (bool): If at clearing mode.
clearing mode (Correct name) == fast forward (in old Alas) == loop (in lua files)
"""
has_loop = bool(len(self.map_data_loop))
logger.info(f'Load map_data, has_loop={has_loop}, use_loop={use_loop}')
if has_loop and use_loop:
self._load_map_data(self.map_data_loop)
else:
self._load_map_data(self.map_data)
def _load_map_data(self, text):
if not len(self.grids.keys()):
grids = np.array([loca for loca, _ in self._parse_text(text)])
self.shape = location2node(tuple(np.max(grids, axis=0)))
for loca, data in self._parse_text(text):
self.grids[loca].decode(data)
@property
def wall_data(self):
return self._wall_data
@wall_data.setter
def wall_data(self, text):
self._wall_data = text
@property
def portal_data(self):
return self._portal_data
@portal_data.setter
def portal_data(self, portal_list):
"""
Args:
portal_list (list[tuple]): [(start, end),]
"""
for nodes in portal_list:
node1, node2 = location_ensure(nodes[0]), location_ensure(nodes[1])
self._portal_data.append((node1, node2))
self[node1].is_portal = True
@property
def land_based_data(self):
return self._land_based_data
@land_based_data.setter
def land_based_data(self, data):
self._land_based_data = data
def _load_land_base_data(self, data):
"""
land_based_data need to be set after map_data.
Args:
data (list[list[str]]): Such as [['H7', 'up'], ['D5', 'left'], ['G3', 'down'], ['C2', 'right']]
"""
rotation_dict = {
'up': [(0, -1), (0, -2), (0, -3)],
'down': [(0, 1), (0, 2), (0, 3)],
'left': [(-1, 0), (-2, 0), (-3, 0)],
'right': [(1, 0), (2, 0), (3, 0)],
}
self._land_based_data = data
for land_based in data:
grid, rotation = land_based
grid = self.grids[location_ensure(grid)]
trigger = self.grid_covered(grid=grid, location=[(0, -1), (0, 1), (-1, 0), (1, 0)]).select(is_land=False)
block = self.grid_covered(grid=grid, location=rotation_dict[rotation]).select(is_land=False)
trigger.set(is_mechanism_trigger=True, mechanism_trigger=trigger, mechanism_block=block)
block.set(is_mechanism_block=True)
@property
def maze_data(self):
return self._maze_data
@maze_data.setter
def maze_data(self, data):
self._maze_data = data
def _load_maze_data(self, data):
"""
Args:
data (list): Such as [('D5', 'I4', 'J6'), ('C4', 'E4', 'D8'), ('C2', 'G2', 'G6')]
"""
self._maze_data = data
self.maze_round = len(data) * 3
for index, maze in enumerate(data):
maze = self.to_selected(maze)
maze.set(is_maze=True, maze_round=tuple(list(range(index * 3, index * 3 + 3))))
for grid in maze:
self.find_path_initial(grid, has_ambush=False)
grid.maze_nearby = self.select(cost=1).add(self.select(cost=2)).select(is_land=False)
@property
def fortress_data(self):
return self._fortress_data
@fortress_data.setter
def fortress_data(self, data):
enemy, block = data
if not isinstance(enemy, SelectedGrids):
enemy = self.to_selected((enemy,) if not isinstance(enemy, (tuple, list)) else enemy)
if not isinstance(block, SelectedGrids):
block = self.to_selected((block,) if not isinstance(block, (tuple, list)) else block)
self._fortress_data = [enemy, block]
def _load_fortress_data(self, data):
"""
Args:
data (list): [fortress_enemy, fortress_block], they can should be str or a tuple/list of str.
Such as [('B5', 'E2', 'H5', 'E8'), 'G3'] or ['F5', 'G1']
"""
self._fortress_data = data
enemy, block = data
enemy.set(is_fortress=True)
block.set(is_mechanism_block=True)
@property
def bouncing_enemy_data(self):
return self._bouncing_enemy_data
@bouncing_enemy_data.setter
def bouncing_enemy_data(self, data):
self._bouncing_enemy_data = [self.to_selected(route) for route in data]
def _load_bouncing_enemy_data(self, data):
"""
Args:
data (list[SelectedGrids]): Grids that enemy is bouncing in.
[enemy_route, enemy_route, ...], Such as [(C2, C3, C4), ]
"""
for route in data:
route.set(may_bouncing_enemy=True)
def load_mechanism(self, land_based=False, maze=False, fortress=False, bouncing_enemy=False):
logger.info(f'Load mechanism, land_base={land_based}, maze={maze}, fortress={fortress}, '
f'bouncing_enemy={bouncing_enemy}')
if land_based:
self._load_land_base_data(self.land_based_data)
if maze:
self._load_maze_data(self.maze_data)
if fortress:
self._load_fortress_data(self._fortress_data)
if bouncing_enemy:
self._load_bouncing_enemy_data(self._bouncing_enemy_data)
def grid_connection_initial(self, wall=False, portal=False):
"""
Args:
wall (bool): If use wall_data
portal (bool): If use portal_data
Returns:
bool: If used wall data.
"""
logger.info(f'grid_connection: wall={wall}, portal={portal}')
# Generate grid connection.
total = set([grid for grid in self.grids.keys()])
for grid in self:
connection = set()
for arr in np.array([(0, -1), (0, 1), (-1, 0), (1, 0)]):
arr = tuple(arr + grid.location)
if arr in total:
connection.add(arr)
self.grid_connection[grid.location] = connection
# Use wall_data to delete connection.
if wall and self._wall_data:
wall = []
for y, line in enumerate([l for l in self._wall_data.split('\n') if l]):
for x, letter in enumerate(line[4:-2]):
if letter != ' ':
wall.append((x, y))
wall = np.array(wall)
vert = wall[np.all([wall[:, 0] % 4 == 2, wall[:, 1] % 2 == 0], axis=0)]
hori = wall[np.all([wall[:, 0] % 4 == 0, wall[:, 1] % 2 == 1], axis=0)]
disconnect = []
for loca in (vert - (2, 0)) // (4, 2):
disconnect.append([loca, loca + (1, 0)])
for loca in (hori - (0, 1)) // (4, 2):
disconnect.append([loca, loca + (0, 1)])
for g1, g2 in disconnect:
g1 = tuple(g1.tolist())
g2 = tuple(g2.tolist())
self.grid_connection[g1].remove(g2)
self.grid_connection[g2].remove(g1)
# Create portal link
for start, end in self._portal_data:
if portal:
self.grid_connection[start].add(end)
self[start].is_portal = True
self[start].portal_link = end
else:
if end in self.grid_connection[start]:
self.grid_connection[start].remove(end)
self[start].is_portal = False
self[start].portal_link = None
return True
def fixup_submarine_fleet(self):
# fixup submarine spawn point
# If a grid is_submarine, the lower grid may detected as is_fleet, because they have the same ammo icon
for grid in self.select(is_fleet=True):
if grid.is_spawn_point:
continue
for upper in self.grid_covered(grid, location=[(0, -1)]):
if upper.is_submarine_spawn_point:
logger.info(f'Fixup submarine spawn point, fleet={grid} -> submarine={upper}')
grid.is_fleet = False
grid.is_current_fleet = False
upper.is_submarine = True
# and we don't allow a grid to be both is_enemy and is_fleet at init
# which might be an submarine above
for grid in self.select(is_enemy=True, is_fleet=True):
grid.is_fleet = False
grid.is_current_fleet = False
def show(self):
# logger.info('Showing grids:')
logger.info(' ' + ' '.join([' ' + chr(x + 64 + 1) for x in range(self.shape[0] + 1)]))
for y in range(self.shape[1] + 1):
text = str(y + 1).rjust(2) + ' ' + ' '.join(
[self[(x, y)].str if (x, y) in self else ' ' for x in range(self.shape[0] + 1)])
logger.info(text)
def update(self, grids, camera, mode='normal'):
"""
Args:
grids:
camera (tuple):
mode (str): Scan mode, such as 'init', 'normal', 'carrier', 'movable'
"""
offset = np.array(camera) - np.array(grids.center_loca)
# grids.show()
failed_count = 0
for grid in grids.grids.values():
loca = tuple(offset + grid.location)
if loca in self.grids:
if self.ignore_prediction_match(globe=loca, local=grid):
continue
if not copy.copy(self.grids[loca]).merge(grid, mode=mode):
logger.warning(f"Wrong Prediction. {self.grids[loca]} = '{grid.str}'")
failed_count += 1
if failed_count < 2:
for grid in grids.grids.values():
loca = tuple(offset + grid.location)
if loca in self.grids:
if self.ignore_prediction_match(globe=loca, local=grid):
continue
self.grids[loca].merge(grid, mode=mode)
if mode == 'init':
self.fixup_submarine_fleet()
return True
else:
logger.warning('Too many wrong prediction')
return False
def reset(self):
for grid in self:
grid.reset()
def reset_fleet(self):
for grid in self:
grid.is_current_fleet = False
@property
def camera_data(self):
"""
Returns:
SelectedGrids:
"""
return self._camera_data
@camera_data.setter
def camera_data(self, nodes):
"""
Args:
nodes (list): Contains str.
"""
self._camera_data = SelectedGrids([self[node2location(node)] for node in nodes])
@property
def camera_data_spawn_point(self):
"""Additional camera_data to detect fleets at spawn point.
Returns:
SelectedGrids:
"""
return self._camera_data_spawn_point
@camera_data_spawn_point.setter
def camera_data_spawn_point(self, nodes):
"""
Args:
nodes (list): Contains str.
"""
self._camera_data_spawn_point = SelectedGrids([self[node2location(node)] for node in nodes])
@property
def spawn_data(self):
"""
Returns:
[list[dict]]:
"""
if self._spawn_data_use_loop:
return self._spawn_data_loop
else:
return self._spawn_data
@spawn_data.setter
def spawn_data(self, data_list):
self._spawn_data = data_list
@property
def spawn_data_loop(self):
return self._spawn_data_loop
@spawn_data_loop.setter
def spawn_data_loop(self, data_list):
self._spawn_data_loop = data_list
@property
def spawn_data_stack(self):
return self._spawn_data_stack
def load_spawn_data(self, use_loop=False):
has_loop = bool(len(self._spawn_data_loop))
logger.info(f'Load spawn_data, has_loop={has_loop}, use_loop={use_loop}')
if has_loop and use_loop:
self._spawn_data_use_loop = True
self._load_spawn_data(self._spawn_data_loop)
else:
self._spawn_data_use_loop = False
self._load_spawn_data(self._spawn_data)
def _load_spawn_data(self, data_list):
spawn = {'battle': 0, 'enemy': 0, 'mystery': 0, 'siren': 0, 'boss': 0}
for data in data_list:
spawn['battle'] = data['battle']
spawn['enemy'] += data.get('enemy', 0)
spawn['mystery'] += data.get('mystery', 0)
spawn['siren'] += data.get('siren', 0)
spawn['boss'] += data.get('boss', 0)
self._spawn_data_stack.append(spawn.copy())
@property
def weight_data(self):
return self._weight_data
@weight_data.setter
def weight_data(self, text):
self._weight_data = text
for loca, data in self._parse_text(text):
self[loca].weight = float(data)
@property
def map_covered(self):
"""
Returns:
SelectedGrids:
"""
covered = []
for grid in self:
covered += self.grid_covered(grid).grids
return SelectedGrids(covered).add(self._map_covered)
@map_covered.setter
def map_covered(self, nodes):
"""
Args:
nodes (list): Contains str.
"""
self._map_covered = SelectedGrids([self[node2location(node)] for node in nodes])
def ignore_prediction(self, globe, **local):
"""
Args:
globe (GridInfo, tuple, str): Grid in globe map.
**local: Any properties in local grid.
Examples:
MAP.ignore_prediction(D5, enemy_scale=1, enemy_genre='Enemy')
will ignore `1E` enemy on D5.
"""
globe = location_ensure(globe)
self._ignore_prediction.append((globe, local))
def ignore_prediction_match(self, globe, local):
"""
Args:
globe (tuple):
local (GridInfo):
Returns:
bool: If matched a wrong prediction.
"""
for wrong_globe, wrong_local in self._ignore_prediction:
if wrong_globe == globe:
if all([local.__getattribute__(k) == v for k, v in wrong_local.items()]):
return True
return False
@property
def is_map_data_poor(self):
if not self.select(may_enemy=True) or not self.select(may_boss=True) or not self.select(is_spawn_point=True):
return False
if not len(self.spawn_data):
return False
return True
def show_cost(self):
logger.info(' ' + ' '.join([' ' + chr(x + 64 + 1) for x in range(self.shape[0] + 1)]))
for y in range(self.shape[1] + 1):
text = str(y + 1).rjust(2) + ' ' + ' '.join(
[str(self[(x, y)].cost).rjust(4) if (x, y) in self else ' ' for x in range(self.shape[0] + 1)])
logger.info(text)
def show_connection(self):
logger.info(' ' + ' '.join([' ' + chr(x + 64 + 1) for x in range(self.shape[0] + 1)]))
for y in range(self.shape[1] + 1):
text = str(y + 1).rjust(2) + ' ' + ' '.join(
[location2node(self[(x, y)].connection) if (x, y) in self and self[(x, y)].connection else ' ' for x in
range(self.shape[0] + 1)])
logger.info(text)
def find_path_initial(self, location, has_ambush=True, has_enemy=True):
"""
Args:
location (tuple(int)): Grid location
has_ambush (bool): MAP_HAS_AMBUSH
has_enemy (bool): False if only sea and land are considered
"""
location = location_ensure(location)
ambush_cost = 10 if has_ambush else 1
for grid in self:
grid.cost = 9999
grid.connection = None
start = self[location]
start.cost = 0
visited = [start]
visited = set(visited)
while 1:
new = visited.copy()
for grid in visited:
for arr in self.grid_connection[grid.location]:
arr = self[arr]
if arr.is_land or arr.is_mechanism_block:
continue
cost = ambush_cost if arr.may_ambush else 1
cost += grid.cost
if cost < arr.cost:
arr.cost = cost
arr.connection = grid.location
elif cost == arr.cost:
if abs(arr.location[0] - grid.location[0]) == 1:
arr.connection = grid.location
if arr.is_sea or not has_enemy:
new.add(arr)
if len(new) == len(visited):
break
visited = new
# self.show_cost()
# self.show_connection()
def find_path_initial_multi_fleet(self, location_dict, current, has_ambush):
"""
Args:
location_dict (dict): Key: int, fleet index. Value: tuple(int), grid location.
current (tuple): Current location.
has_ambush (bool): MAP_HAS_AMBUSH
"""
location_dict = sorted(location_dict.items(), key=lambda kv: (int(kv[1] == current),))
for fleet, location in location_dict:
if location == ():
continue
self.find_path_initial(location, has_ambush=has_ambush)
attr = f'cost_{fleet}'
for grid in self:
grid.__setattr__(attr, grid.cost)
def _find_path(self, location):
"""
Args:
location (tuple):
Returns:
list[tuple]: walking route.
Examples:
MAP_7_2._find_path(node2location('H2'))
[(2, 2), (3, 2), (4, 2), (5, 2), (6, 2), (6, 1), (7, 1)] # ['C3', 'D3', 'E3', 'F3', 'G3', 'G2', 'H2']
"""
if self[location].cost == 0:
return [location]
if self[location].connection is None:
return None
res = [location]
while 1:
location = self[location].connection
if len(res) > 30:
logger.warning('Route too long')
logger.warning(res)
# exit(1)
if location is not None:
res.append(location)
else:
break
res.reverse()
if len(res) == 0:
logger.warning('No path found. Destination: %s' % str(location))
return [location, location]
return res
def _find_route_node(self, route, step=0, turning_optimize=False):
"""
Args:
route (list[tuple]): list of grids.
step (int): Fleet step in event map. Default to 0.
turning_optimize: (bool): True to optimize route to reduce ambushes
Returns:
list[tuple]: list of walking node.
Examples:
MAP_7_2._find_route_node([(2, 2), (3, 2), (4, 2), (5, 2), (6, 2), (6, 1), (7, 1)])
[(6, 2), (7, 1)]
"""
if turning_optimize:
res = []
diff = np.abs(np.diff(route, axis=0))
turning = np.diff(diff, axis=0)[:, 0]
indexes = np.where(turning == -1)[0] + 1
for index in indexes:
if not self[route[index]].is_fleet:
res.append(index)
else:
logger.info(f'Path_node_avoid: {self[route[index]]}')
if (index > 1) and (index - 1 not in indexes):
res.append(index - 1)
if (index < len(route) - 2) and (index + 1 not in indexes):
res.append(index + 1)
res.append(len(route) - 1)
# res = [4, 6]
if step == 0:
return [route[index] for index in res]
else:
if step == 0:
return [route[-1]]
# Index of the last node
# res = [6]
res = [max(len(route) - 1, 0)]
res.insert(0, 0)
inserted = []
for left, right in zip(res[:-1], res[1:]):
for index in list(range(left, right, step))[1:]:
way_node = self[route[index]]
if way_node.is_fleet or way_node.is_portal or way_node.is_flare:
logger.info(f'Path_node_avoid: {way_node}')
if (index > 1) and (index - 1 not in res):
inserted.append(index - 1)
if (index < len(route) - 2) and (index + 1 not in res):
inserted.append(index + 1)
else:
inserted.append(index)
inserted.append(right)
res = inserted
# res = [3, 6, 8]
return [route[index] for index in res]
def find_path(self, location, step=0, turning_optimize=False):
location = location_ensure(location)
path = self._find_path(location)
if path is None or not len(path):
logger.warning('No path found. Return destination.')
return [location]
logger.info('Full path: %s' % '[' + ', ' .join([location2node(grid) for grid in path]) + ']')
portal_path = []
index = [0]
for i, loca in enumerate(zip(path[:-1], path[1:])):
grid = self[loca[0]]
if grid.is_portal and grid.portal_link == loca[1]:
index += [i, i + 1]
if grid.is_maze and i != 0:
index += [i]
if len(path) not in index:
index.append(len(path))
for start, end in zip(index[:-1], index[1:]):
if end - start == 1 and self[path[start]].is_portal and self[path[start]].portal_link == path[end]:
continue
local_path = path[start:end + 1]
local_path = self._find_route_node(local_path, step=step, turning_optimize=turning_optimize)
portal_path += local_path
logger.info('Path: %s' % '[' + ', ' .join([location2node(grid) for grid in local_path]) + ']')
path = portal_path
return path
def grid_covered(self, grid, location=None):
"""
Args:
grid (GridInfo)
location (list[tuple[int]]): Relative coordinate of the covered grid.
Returns:
SelectedGrids:
"""
if location is None:
covered = [tuple(np.array(grid.location) + upper) for upper in grid.covered_grid()]
else:
covered = [tuple(np.array(grid.location) + upper) for upper in location]
covered = [self[upper] for upper in covered if upper in self]
return SelectedGrids(covered)
def missing_get(self, battle_count, mystery_count=0, siren_count=0, carrier_count=0, mode='normal'):
try:
missing = self.spawn_data_stack[battle_count].copy()
except IndexError:
missing = self.spawn_data_stack[-1].copy()
may = {'enemy': 0, 'mystery': 0, 'siren': 0, 'boss': 0, 'carrier': 0}
missing['enemy'] -= battle_count - siren_count
missing['mystery'] -= mystery_count
missing['siren'] -= siren_count
missing['carrier'] = carrier_count - self.select(is_enemy=True, may_enemy=False).count \
if mode == 'carrier' else 0
for grid in self:
for attr in ['enemy', 'mystery', 'siren', 'boss']:
if grid.__getattribute__('is_' + attr):
missing[attr] -= 1
missing['enemy'] += len(self.fortress_data[0]) - self.select(is_fortress=True).count
for route in self.bouncing_enemy_data:
if not route.select(may_bouncing_enemy=True):
# bouncing enemy cleared, re-add one enemy
missing['enemy'] += 1
for upper in self.map_covered:
if (upper.may_enemy or mode == 'movable') and not upper.is_enemy:
may['enemy'] += 1
if upper.may_mystery and not upper.is_mystery:
may['mystery'] += 1
if (upper.may_siren or mode == 'movable') and not upper.is_siren:
may['siren'] += 1
if upper.may_boss and not upper.is_boss:
may['boss'] += 1
if upper.may_carrier:
may['carrier'] += 1
logger.attr('enemy_missing',
', '.join([f'{k[:2].upper()}:{str(v).rjust(2)}' for k, v in missing.items() if k != 'battle']))
logger.attr('enemy_may____',
', '.join([f'{k[:2].upper()}:{str(v).rjust(2)}' for k, v in may.items()]))
return may, missing
def missing_is_none(self, battle_count, mystery_count=0, siren_count=0, carrier_count=0, mode='normal'):
if self.poor_map_data:
return False
may, missing = self.missing_get(battle_count, mystery_count, siren_count, carrier_count, mode)
for key in may.keys():
if missing[key] != 0:
return False
return True
def missing_predict(self, battle_count, mystery_count=0, siren_count=0, carrier_count=0, mode='normal'):
if self.poor_map_data:
return False
may, missing = self.missing_get(battle_count, mystery_count, siren_count, carrier_count, mode)
# predict
for upper in self.map_covered:
for attr in ['enemy', 'mystery', 'siren', 'boss']:
if upper.__getattribute__('may_' + attr) and missing[attr] > 0 and missing[attr] == may[attr]:
logger.info('Predict %s to be %s' % (location2node(upper.location), attr))
upper.__setattr__('is_' + attr, True)
if carrier_count:
if upper.may_carrier and missing['carrier'] > 0 and missing['carrier'] == may['carrier']:
logger.info('Predict %s to be enemy' % location2node(upper.location))
upper.__setattr__('is_enemy', True)
def select(self, **kwargs):
"""
Args:
**kwargs: Attributes of Grid.
Returns:
SelectedGrids:
"""
result = []
for grid in self:
flag = True
for k, v in kwargs.items():
if grid.__getattribute__(k) != v:
flag = False
if flag:
result.append(grid)
return SelectedGrids(result)
def to_selected(self, grids):
"""
Args:
grids (list):
Returns:
SelectedGrids:
"""
return SelectedGrids([self[location_ensure(loca)] for loca in grids])
def flatten(self):
"""
Returns:
list[GridInfo]:
"""
return self.grids.values()
| 412 | 0.857752 | 1 | 0.857752 | game-dev | MEDIA | 0.468514 | game-dev | 0.979098 | 1 | 0.979098 |
fallahn/crogine | 2,963 | android/BulletDroid/src/BulletDynamics/MLCPSolvers/btDantzigSolver.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///original version written by Erwin Coumans, October 2013
#ifndef BT_DANTZIG_SOLVER_H
#define BT_DANTZIG_SOLVER_H
#include "btMLCPSolverInterface.h"
#include "btDantzigLCP.h"
class btDantzigSolver : public btMLCPSolverInterface
{
protected:
btScalar m_acceptableUpperLimitSolution;
btAlignedObjectArray<char> m_tempBuffer;
btAlignedObjectArray<btScalar> m_A;
btAlignedObjectArray<btScalar> m_b;
btAlignedObjectArray<btScalar> m_x;
btAlignedObjectArray<btScalar> m_lo;
btAlignedObjectArray<btScalar> m_hi;
btAlignedObjectArray<int> m_dependencies;
btDantzigScratchMemory m_scratchMemory;
public:
btDantzigSolver()
:m_acceptableUpperLimitSolution(btScalar(1000))
{
}
virtual bool solveMLCP(const btMatrixXu & A, const btVectorXu & b, btVectorXu& x, const btVectorXu & lo,const btVectorXu & hi,const btAlignedObjectArray<int>& limitDependency, int numIterations, bool useSparsity = true)
{
bool result = true;
int n = b.rows();
if (n)
{
int nub = 0;
btAlignedObjectArray<btScalar> ww;
ww.resize(n);
const btScalar* Aptr = A.getBufferPointer();
m_A.resize(n*n);
for (int i=0;i<n*n;i++)
{
m_A[i] = Aptr[i];
}
m_b.resize(n);
m_x.resize(n);
m_lo.resize(n);
m_hi.resize(n);
m_dependencies.resize(n);
for (int i=0;i<n;i++)
{
m_lo[i] = lo[i];
m_hi[i] = hi[i];
m_b[i] = b[i];
m_x[i] = x[i];
m_dependencies[i] = limitDependency[i];
}
result = btSolveDantzigLCP (n,&m_A[0],&m_x[0],&m_b[0],&ww[0],nub,&m_lo[0],&m_hi[0],&m_dependencies[0],m_scratchMemory);
if (!result)
return result;
// printf("numAllocas = %d\n",numAllocas);
for (int i=0;i<n;i++)
{
volatile btScalar xx = m_x[i];
if (xx != m_x[i])
return false;
if (x[i] >= m_acceptableUpperLimitSolution)
{
return false;
}
if (x[i] <= -m_acceptableUpperLimitSolution)
{
return false;
}
}
for (int i=0;i<n;i++)
{
x[i] = m_x[i];
}
}
return result;
}
};
#endif //BT_DANTZIG_SOLVER_H
| 412 | 0.882454 | 1 | 0.882454 | game-dev | MEDIA | 0.883488 | game-dev | 0.962659 | 1 | 0.962659 |
dotCMS/core | 3,139 | dotCMS/src/main/webapp/html/js/dojo/custom-build/dojox/dgauges/components/DefaultPropertiesMixin.js | define("dojox/dgauges/components/DefaultPropertiesMixin", ["dojo/_base/declare", "dojo/_base/Color"], function(declare, Color){
return declare("dojox.dgauges.components.DefaultPropertiesMixin", null, {
// summary:
// This class defines default properties of predefined gauges.
// minimum: Number
// The minimum value of the scaler. Default is 0.
minimum: 0,
// maximum: Number
// The maximum value of the scaler. Default is 100.
maximum: 100,
// snapInterval:
// Specifies the increment value to be used as snap values on this scale
// during user interaction.
// Default is 1.
snapInterval: 1,
// majorTickInterval: Number
// The interval between two major ticks.
majorTickInterval: NaN,
// minorTickInterval: Number
// The interval between two minor ticks.
minorTickInterval: NaN,
// minorTicksEnabled: Boolean
// If false, minor ticks are not generated. Default is true.
minorTicksEnabled: true,
// summary:
// The value of the indicator. Default is 0.
value: 0,
// interactionArea: String
// How to interact with the indicator using mouse or touch interactions.
// Can be "indicator", "gauge" or "none". The default value is "gauge".
// If set to "indicator", the indicator shape reacts to mouse and touch events.
// If set to "gauge", the whole gauge reacts to mouse and touch events.
// If "none", interactions are disabled.
interactionArea: "gauge",
// interactionMode: String
// Can be "mouse" or "touch".
interactionMode: "mouse",
// animationDuration: Number
// The duration of the value change animation in milliseconds. Default is 0.
// The animation occurs on both user interactions and programmatic value changes.
// Set this property to 0 to disable animation.
animationDuration: 0,
_setMinimumAttr: function(v){
this.getElement("scale").scaler.set("minimum", v);
},
_setMaximumAttr: function(v){
this.getElement("scale").scaler.set("maximum", v);
},
_setSnapIntervalAttr: function(v){
this.getElement("scale").scaler.set("snapInterval", v);
},
_setMajorTickIntervalAttr: function(v){
this.getElement("scale").scaler.set("majorTickInterval", v);
},
_setMinorTickIntervalAttr: function(v){
this.getElement("scale").scaler.set("minorTickInterval", v);
},
_setMinorTicksEnabledAttr: function(v){
this.getElement("scale").scaler.set("minorTicksEnabled", v);
},
_setInteractionAreaAttr: function(v){
this.getElement("scale").getIndicator("indicator").set("interactionArea", v);
},
_setInteractionModeAttr: function(v){
this.getElement("scale").getIndicator("indicator").set("interactionMode", v);
},
_setAnimationDurationAttr: function(v){
this.getElement("scale").getIndicator("indicator").set("animationDuration", v);
},
_setBorderColorAttr: function(v){
this.borderColor = new Color(v);
this.invalidateRendering();
},
_setFillColorAttr: function(v){
this.fillColor = new Color(v);
this.invalidateRendering();
},
_setIndicatorColorAttr: function(v){
this.indicatorColor = new Color(v);
this.invalidateRendering();
}
});
});
| 412 | 0.916121 | 1 | 0.916121 | game-dev | MEDIA | 0.840857 | game-dev | 0.62107 | 1 | 0.62107 |
RabbitStewDio/EnTTSharp | 1,240 | src/EnTTSharp.Annotations/EntityComponentRegistration.cs | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace EnTTSharp.Annotations
{
public class EntityComponentRegistration
{
readonly Dictionary<Type, object> data;
public EntityComponentRegistration(TypeInfo typeInfo)
{
this.TypeInfo = typeInfo;
this.data = new Dictionary<Type, object>();
}
public bool IsEmpty => data.Count == 0;
public TypeInfo TypeInfo { get; }
public void Store<TData>(TData value)
{
object? o = value;
if (o != null)
{
data[typeof(TData)] = o;
}
}
public bool TryGet<TData>([MaybeNullWhen(false)] out TData result)
{
if (this.data.TryGetValue(typeof(TData), out var raw) &&
raw is TData typed)
{
result = typed;
return true;
}
result = default!;
return false;
}
public override string ToString()
{
return $"EntityComponentRegistration({nameof(TypeInfo)}: {TypeInfo}, {nameof(IsEmpty)}: {IsEmpty})";
}
}
} | 412 | 0.783169 | 1 | 0.783169 | game-dev | MEDIA | 0.308386 | game-dev | 0.942966 | 1 | 0.942966 |
grayj/Jedi-Academy | 11,055 | base/ui/jamp/multiplayer.menu | //----------------------------------------------------------------------------------------------
//
// MULTIPLAYER MENU
//
// Allows player to start a game or join one in progress
//
//----------------------------------------------------------------------------------------------
{
menuDef
{
name "multiplayermenu"
fullScreen 1
rect 0 0 640 480 // Size and position of the menu
visible 1 // Visible on open
focusColor 1 1 1 1 // Focus color for text and items
descX 320
descY 426
descScale 1
descColor 1 .682 0 .8
descAlignment ITEM_ALIGN_CENTER
onESC
{
play "sound/interface/esc.wav" ;
close all;
open mainMenu
}
onOpen
{
setfocus quickserver_button
}
//----------------------------------------------------------------------------------------------
// MENU BACKGROUND
//----------------------------------------------------------------------------------------------
itemDef
{
name really_background
group none
style WINDOW_STYLE_SHADER
rect 156 154 320 240
background "gfx/menus/main_centerblue"
forecolor 1 1 1 1
visible 1
decoration
}
itemDef
{
name background_text
group none
style WINDOW_STYLE_SHADER
rect 0 0 160 480
background "gfx/menus/menu_side_text"
forecolor 1 1 1 1
visible 1
decoration
}
itemDef
{
name background_text_b
group none
style WINDOW_STYLE_SHADER
rect 480 0 160 480
background "gfx/menus/menu_side_text_right"
forecolor 1 1 1 1
visible 1
decoration
}
itemDef
{
name background
group none
style WINDOW_STYLE_SHADER
rect 0 0 640 480
background "gfx/menus/main_background"
forecolor 1 1 1 1
visible 1
decoration
}
itemDef
{
name starwars
group none
style WINDOW_STYLE_SHADER
rect 107 8 428 112
background "gfx/menus/jediacademy"
forecolor 1 1 1 1
visible 1
decoration
}
itemDef
{
name left_frame
group lf_fr
style WINDOW_STYLE_SHADER
rect 0 50 320 160
background "gfx/menus/menu_boxes_left"
forecolor 1 1 1 1
visible 1
decoration
}
itemDef
{
name right_frame
group rt_fr
style WINDOW_STYLE_SHADER
rect 320 50 320 160
background "gfx/menus/menu_boxes_right"
forecolor 1 1 1 1
visible 1
decoration
}
//----------------------------------------------------------------------------------------------
// TOP MENU BUTTONS
//----------------------------------------------------------------------------------------------
itemDef
{
name button_glow
group none
style WINDOW_STYLE_SHADER
rect 0 0 0 0
background "gfx/menus/menu_buttonback"
forecolor 1 1 1 1
visible 0
decoration
}
// Big button "PLAY"
itemDef
{
name playbutton
group toprow
style WINDOW_STYLE_EMPTY
type ITEM_TYPE_BUTTON
rect 7 126 130 24
text @MENUS_PLAY
descText @MENUS_START_PLAYING_NOW
font 3
textscale 1.1
textaligny 0
textalign ITEM_ALIGN_CENTER
textstyle 0
textalignx 65
forecolor 1 1 1 1
visible 1
action
{
}
}
// Big button "PLAYER PROFILE"
itemDef
{
name profilebutton
group toprow
text @MENUS_PROFILE
descText @MENUS_PROFILE_DESC
style WINDOW_STYLE_EMPTY
type ITEM_TYPE_BUTTON
rect 170 126 130 24
textaligny 0
font 3
textscale 1.1
textalign ITEM_ALIGN_CENTER
textstyle 0
textalignx 65
forecolor 1 .682 0 1
visible 1
mouseEnter
{
show button_glow
setitemrect button_glow 120 124 230 30
}
mouseExit
{
hide button_glow
}
action
{
play "sound/interface/button1.wav" ;
close all ;
open playerMenu
}
}
// Big button "CONTROLS"
itemDef
{
name controlsbutton
group toprow
text @MENUS_CONTROLS2
descText @MENUS_CONFIGURE_GAME_CONTROLS
type ITEM_TYPE_BUTTON
style WINDOW_STYLE_EMPTY
rect 340 126 130 24
font 3
textscale 1.1
textaligny 0
textalign ITEM_ALIGN_CENTER
textstyle 0
textalignx 65
backcolor 0 0 0 0
forecolor 1 .682 0 1
visible 1
mouseEnter
{
show button_glow
setitemrect button_glow 290 124 230 30
}
mouseExit
{
hide button_glow
}
action
{
play "sound/interface/button1.wav" ;
close all ;
open controlsMenu ;
}
}
// Big button "SETUP"
itemDef
{
name setupbutton
group toprow
text @MENUS_SETUP
descText @MENUS_CONFIGURE_GAME_SETTINGS
type ITEM_TYPE_BUTTON
style WINDOW_STYLE_EMPTY
rect 502 126 130 24
font 3
textscale 1.1
textaligny 0
textalign ITEM_ALIGN_CENTER
textstyle 0
textalignx 65
backcolor 0 0 0 0
forecolor 1 .682 0 1
visible 1
mouseEnter
{
show button_glow
setitemrect button_glow 452 124 230 30
}
mouseExit
{
hide button_glow
}
action
{
play "sound/interface/button1.wav" ;
close all ;
open setup_menu
}
}
//----------------------------------------------------------------------------------------------
// MULTIPLAYER MENU SPECIFIC
//----------------------------------------------------------------------------------------------
itemDef
{
name title_glow
group none
style WINDOW_STYLE_SHADER
rect 150 162 340 20
background "gfx/menus/menu_buttonback"
forecolor 1 1 1 1
visible 1
decoration
}
itemDef
{
name title
group none
text @MENUS_START_PLAYING
style WINDOW_STYLE_EMPTY
rect 225 164 190 16
font 3
textscale .7
textalign ITEM_ALIGN_CENTER
textalignx 95
textaligny -1
forecolor .549 .854 1 1
visible 1
decoration
}
// QUICK START
itemDef
{
name quickserver_button
group none
text @MENUS_SOLO_GAME
descText @MENUS_QUICKSTART_DESC
type ITEM_TYPE_BUTTON
style WINDOW_STYLE_EMPTY
rect 225 191 190 36
font 3
textscale 1
textalign ITEM_ALIGN_CENTER
textstyle 0
textalignx 95
textaligny 8
forecolor 1 .682 0 1
visible 1
mouseEnter
{
show button_glow
setitemrect button_glow 175 197 300 30
}
mouseExit
{
hide button_glow
}
action
{
play "sound/interface/button1.wav" ;
close multiplayermenu ;
open quickgame
}
}
// JOIN SERVER
itemDef
{
name joinserver_button
group none
text @MENUS_JOIN_SERVER_CAPS
descText @MENUS_SEARCH_FOR_SERVERS_TO
type ITEM_TYPE_BUTTON
style WINDOW_STYLE_EMPTY
rect 225 226 190 36
font 3
textscale 1
textalign ITEM_ALIGN_CENTER
textstyle 0
textalignx 95
textaligny 8
forecolor 1 .682 0 1
visible 1
mouseEnter
{
show button_glow
setitemrect button_glow 175 232 300 30
}
mouseExit
{
hide button_glow
}
action
{
play "sound/interface/button1.wav" ;
close multiplayermenu ;
open joinserver
}
}
// CREATE SERVER
itemDef
{
name startserver_button
group none
text @MENUS_CREATE_SERVER_CAPS
descText @MENUS_CREATE_YOUR_OWN_SERVER
type ITEM_TYPE_BUTTON
style WINDOW_STYLE_EMPTY
rect 225 261 190 36
font 3
textscale 1
textalign ITEM_ALIGN_CENTER
textstyle 0
textalignx 95
textaligny 8
forecolor 1 .682 0 1
visible 1
mouseEnter
{
show button_glow
setitemrect button_glow 175 267 300 30
}
mouseExit
{
hide button_glow
}
action
{
play "sound/interface/button1.wav" ;
close multiplayermenu ;
open createserver
}
}
// PLAY DEMO FILE
itemDef
{
name playdemo_button
group none
text @MENUS_PLAY_DEMO_CAPS
descText @MENUS_PLAY_BACK_A_RECORDED
type ITEM_TYPE_BUTTON
style WINDOW_STYLE_EMPTY
rect 225 296 190 36
font 3
textscale 1
textalign ITEM_ALIGN_CENTER
textstyle 0
textalignx 95
textaligny 8
forecolor 1 .682 0 1
visible 1
mouseEnter
{
show button_glow
setitemrect button_glow 175 302 300 30
}
mouseExit
{
hide button_glow
}
action
{
play "sound/interface/button1.wav" ;
close multiplayermenu ;
open demo
}
}
// GAME RULES
itemDef
{
name rules_button
group none
text @MENUS_RULES
descText @MENUS_RULES_DESC
type ITEM_TYPE_BUTTON
style WINDOW_STYLE_EMPTY
rect 225 331 190 36
font 3
textscale 1
textalign ITEM_ALIGN_CENTER
textstyle 0
textalignx 95
textaligny 8
forecolor 1 .682 0 1
visible 1
mouseEnter
{
show button_glow
setitemrect button_glow 175 337 300 30
}
mouseExit
{
hide button_glow
}
action
{
play "sound/interface/button1.wav" ;
close multiplayermenu ;
open rulesMenu
}
}
//----------------------------------------------------------------------------------------------
// BOTTOM BUTTONS
//----------------------------------------------------------------------------------------------
// BACK button
itemDef
{
name backbutton
group fade_buttons
text @MENUS_BACK
descText @MENUS_BACKTOMAIN
type ITEM_TYPE_BUTTON
style WINDOW_STYLE_EMPTY
rect 59 444 130 24
font 3
textscale 1.1
textalign ITEM_ALIGN_CENTER
textstyle 3
textalignx 65
textaligny -1
forecolor 1 .682 0 1
visible 1
mouseEnter
{
show button_glow
setitemrect button_glow 30 441 190 30
}
mouseExit
{
hide button_glow
}
action
{
play "sound/interface/esc.wav" ;
close all ;
open mainMenu
}
}
// EXIT button
itemDef
{
name exitgamebutton
group othermain
text @MENUS_EXIT
descText @MENUS_LEAVE_JEDI_KNIGHT_II
type ITEM_TYPE_BUTTON
style WINDOW_STYLE_EMPTY
rect 255 444 130 24
font 3
textscale 1.1
textalign ITEM_ALIGN_CENTER
textstyle 0
textalignx 65
textaligny -1
forecolor 1 .682 0 1
visible 1
mouseEnter
{
show button_glow
setitemrect button_glow 225 441 190 30
}
mouseExit
{
hide button_glow
}
action
{
play "sound/weapons/saber/saberoff.mp3";
close all ;
open quitMenu
}
}
}
}
| 412 | 0.934869 | 1 | 0.934869 | game-dev | MEDIA | 0.968425 | game-dev | 0.879317 | 1 | 0.879317 |
libriscv/godot-sandbox | 1,772 | program/rust/docker/src/godot/dictionary.rs | #![allow(dead_code)]
use core::arch::asm;
use crate::Variant;
use crate::VariantType;
#[repr(C)]
pub struct GodotDictionary {
pub reference: i32
}
impl GodotDictionary {
pub fn new() -> GodotDictionary {
let mut var = Variant::new_nil();
unsafe {
asm!("ecall",
in("a0") &mut var,
in("a1") VariantType::Dictionary as i32,
in("a2") 0, // method
in("a7") 517, // ECALL_VCREATE
);
}
GodotDictionary {
reference: unsafe { var.u.i } as i32
}
}
pub fn from_ref(var_ref: i32) -> GodotDictionary {
GodotDictionary {
reference: var_ref
}
}
pub fn to_variant(&self) -> Variant {
let mut v = Variant::new_nil();
v.t = VariantType::Array;
v.u.i = self.reference as i64;
v
}
/* Godot Dictionary API */
pub fn size(&self) -> i64 {
return self.call("size", &[]).to_integer();
}
pub fn empty(&self) -> bool {
return self.size() == 0;
}
pub fn clear(&self) {
self.call("clear", &[]);
}
pub fn get(&self, key: &Variant) -> Variant {
const ECALL_DICTIONARY_OPS: i32 = 524;
let mut var = Variant::new_nil();
unsafe {
asm!("ecall",
in("a0") 0, // OP_GET
in("a1") self.reference,
in("a2") key,
in("a3") &mut var,
in("a7") ECALL_DICTIONARY_OPS,
);
}
var
}
pub fn set(&self, key: &Variant, value: &Variant) {
const ECALL_DICTIONARY_OPS: i32 = 524;
unsafe {
asm!("ecall",
in("a0") 1, // OP_SET
in("a1") self.reference,
in("a2") key,
in("a3") value,
in("a7") ECALL_DICTIONARY_OPS,
);
}
}
/* Make a method call on the string (as Variant) */
pub fn call(&self, method: &str, args: &[Variant]) -> Variant {
// Call the method using Variant::callp
let var = Variant::from_ref(VariantType::Array, self.reference);
var.call(method, &args)
}
}
| 412 | 0.610566 | 1 | 0.610566 | game-dev | MEDIA | 0.300178 | game-dev | 0.72022 | 1 | 0.72022 |
MATTYOneInc/AionEncomBase_Java8 | 9,796 | AL-Game/data/scripts/system/handlers/instance/HamateIsleStoreroomInstance.java | /*
* This file is part of Encom.
*
* Encom is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Encom 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with Encom. If not, see <http://www.gnu.org/licenses/>.
*/
package instance;
import com.aionemu.commons.utils.Rnd;
import com.aionemu.gameserver.instance.handlers.GeneralInstanceHandler;
import com.aionemu.gameserver.instance.handlers.InstanceID;
import com.aionemu.gameserver.model.drop.DropItem;
import com.aionemu.gameserver.model.flyring.FlyRing;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.items.storage.Storage;
import com.aionemu.gameserver.model.templates.flyring.FlyRingTemplate;
import com.aionemu.gameserver.model.utils3d.Point3D;
import com.aionemu.gameserver.network.aion.serverpackets.*;
import com.aionemu.gameserver.services.drop.DropRegistrationService;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.ThreadPoolManager;
import com.aionemu.gameserver.world.WorldMapInstance;
import com.aionemu.gameserver.world.knownlist.Visitor;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Future;
/****/
/** Author (Encom)
Chamber of Roah or Hamate Isle Storeroom is a fortress group instance for players of level 40 and above.
Its entrance is located in Hamate Isle in Sullenscale Rive on Mondays, Wednesdays, Fridays and Sundays.
Like other fortress instances, monsters inside it will aggro regardless of the level of the party.
As of 4.9, the entrance was moved from Roah Fortress in Upper Reshanta to Lower Reshanta due to the fortress becoming inactive.
Backstory:
When Balaur held the fortress, they built an inner cave in the deepest parts of the floating island. Within these chambers, they stored their treasures.
Due to not being directly connected to the outside, they created a teleport statue, acting as a portal to the hoard.
However, as Balaur lost the fortress to Daevas, this secret strongbox was discovered.
Daevas accessed this area, but were surprised by the presence of the Balaur guards.
They now must venture in, making their way through the remnants, to acquire those amazing riches.
As Ereshkigal's relics found in Drakenspire Depths released strong energy waves, Reshanta was suffered a shift in its temperature.
Allowing the rising of the Dragon Lord's armies, it caused the outer fortresses to be neutralised, sealing the original entrance.
With the sudden appearance of the central archipelago of Lower Reshanta, strange portals leading to this chambers were discovered
re-enabling access to the affected treasure rooms.
Walkthrough:
The instance is composed of the drop point, which is connected to the main hall, which branches into three bridges leading to their respective wings.
When players step out of the drop point, a 15-minutes countdown will begin, which when ends will force treasure chests to despawn.
Each chamber holds one treasure box, which can be opened with the key dropped from the chamber's head guard.
A bigger chest may spawn sometimes spawn in the main hall, in front of the bridge leading to the northern chamber.
If players attack the unique mob of the room, all guards which have not been cleared already will attack them,
making it imperative to clear the whole room before engaging the fight.
Each room has a different difficulty, varying from easy (western room), to medium (eastern room) to hard (northern room).
The western room is guarded by a random Naga/Nagarant guard, holding the <Golden Ruins of Roah Key>,
which can be used to open the treasure chest behind it,
In the eastern room players will find a Drakan guard, holding the <Jeweled Ruins of Roah Key>, also used to open the chest behind the unique mob.
Laslty, players may reach the northern chamber, guarded by <Protector Kael>, holding the <Magic Ruins of Roah Key>.
This boss will constantly cast shield, reducing physical damage inflicted on him, as well as slowing his enemies' attack and movement speed.
/****/
@InstanceID(300070000)
public class HamateIsleStoreroomInstance extends GeneralInstanceHandler
{
private Future<?> hamateIsleStoreroomTask;
private boolean isStartTimer = false;
private List<Npc> HamateIsleStoreroomTreasureBoxSuscess = new ArrayList<Npc>();
@Override
public void onInstanceCreate(WorldMapInstance instance) {
super.onInstanceCreate(instance);
spawnHamateIsleStoreroomRings();
switch (Rnd.get(1, 2)) {
case 1:
spawn(214780, 381.35986f, 510.61307f, 102.618126f, (byte) 111); //Dakaer Diabolist.
break;
case 2:
spawn(214781, 381.35986f, 510.61307f, 102.618126f, (byte) 111); //Dakaer Bloodmender.
break;
} switch (Rnd.get(1, 2)) {
case 1:
spawn(214782, 625.4933f, 455.0907f, 102.63267f, (byte) 47); //Dakaer Adjutant.
break;
case 2:
spawn(214784, 625.4933f, 455.0907f, 102.63267f, (byte) 47); //Dakaer Physician.
break;
} switch (Rnd.get(1, 2)) {
case 1:
spawn(215449, 503.947f, 623.82227f, 103.695724f, (byte) 90); //Relic Protector Kael.
break;
case 2:
spawn(215450, 503.947f, 623.82227f, 103.695724f, (byte) 90); //Ebonlord Vasana.
break;
}
}
public void onDropRegistered(Npc npc) {
Set<DropItem> dropItems = DropRegistrationService.getInstance().getCurrentDropMap().get(npc.getObjectId());
int npcId = npc.getNpcId();
int index = dropItems.size() + 1;
switch (npcId) {
case 214780: //Dakaer Diabolist.
case 214781: //Dakaer Bloodmender.
for (Player player: instance.getPlayersInside()) {
if (player.isOnline()) {
dropItems.add(DropRegistrationService.getInstance().regDropItem(index++, player.getObjectId(), npcId, 185000036, 1)); //Golden Ruins Of Roah Key.
}
}
break;
case 214782: //Dakaer Adjutant.
case 214784: //Dakaer Physician.
for (Player player: instance.getPlayersInside()) {
if (player.isOnline()) {
dropItems.add(DropRegistrationService.getInstance().regDropItem(index++, player.getObjectId(), npcId, 185000037, 1)); //Jeweled Ruins Of Roah Key.
}
}
break;
case 215449: //Relic Protector Kael.
case 215450: //Ebonlord Vasana.
for (Player player: instance.getPlayersInside()) {
if (player.isOnline()) {
dropItems.add(DropRegistrationService.getInstance().regDropItem(index++, player.getObjectId(), npcId, 185000038, 1)); //Magic Ruins Of Roah Key.
}
}
break;
}
}
private void spawnHamateIsleStoreroomRings() {
FlyRing f1 = new FlyRing(new FlyRingTemplate("HAMATE_ISLE_STOREROOM", mapId,
new Point3D(501.77, 409.53, 94.12),
new Point3D(503.93, 409.65, 98.9),
new Point3D(506.26, 409.7, 94.15), 10), instanceId);
f1.spawn();
}
@Override
public boolean onPassFlyingRing(Player player, String flyingRing) {
if (flyingRing.equals("HAMATE_ISLE_STOREROOM")) {
if (!isStartTimer) {
isStartTimer = true;
System.currentTimeMillis();
instance.doOnAllPlayers(new Visitor<Player>() {
@Override
public void visit(Player player) {
if (player.isOnline()) {
startHamateIsleStoreroomTimer();
PacketSendUtility.sendPacket(player, new SM_QUEST_ACTION(0, 900));
//The Balaur protective magic ward has been activated.
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_INSTANCE_START_IDABRE);
}
}
});
}
}
return false;
}
@Override
public void onEnterInstance(final Player player) {
super.onInstanceCreate(instance);
HamateIsleStoreroomTreasureBoxSuscess.add((Npc) spawn(700472, 377.06046f, 512.4419f, 102.618126f, (byte) 114));
HamateIsleStoreroomTreasureBoxSuscess.add((Npc) spawn(700473, 628.6996f, 451.98642f, 102.63267f, (byte) 48));
HamateIsleStoreroomTreasureBoxSuscess.add((Npc) spawn(700474, 503.7779f, 630.8419f, 104.54881f, (byte) 90));
}
private void startHamateIsleStoreroomTimer() {
hamateIsleStoreroomTask = ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
//All Balaur treasure chests have disappeared.
sendMsg(1400244);
HamateIsleStoreroomTreasureBoxSuscess.get(0).getController().onDelete();
HamateIsleStoreroomTreasureBoxSuscess.get(1).getController().onDelete();
HamateIsleStoreroomTreasureBoxSuscess.get(2).getController().onDelete();
}
}, 900000); //15 Minutes.
}
private void sendMsg(final String str) {
instance.doOnAllPlayers(new Visitor<Player>() {
@Override
public void visit(Player player) {
PacketSendUtility.sendWhiteMessageOnCenter(player, str);
}
});
}
@Override
public void onLeaveInstance(Player player) {
removeItems(player);
}
@Override
public void onPlayerLogOut(Player player) {
removeItems(player);
}
private void removeItems(Player player) {
Storage storage = player.getInventory();
storage.decreaseByItemId(185000036, storage.getItemCountByItemId(185000036)); //Golden Ruins Of Roah Key.
storage.decreaseByItemId(185000037, storage.getItemCountByItemId(185000037)); //Jeweled Ruins Of Roah Key.
storage.decreaseByItemId(185000038, storage.getItemCountByItemId(185000038)); //Magic Ruins Of Roah Key.
}
} | 412 | 0.99121 | 1 | 0.99121 | game-dev | MEDIA | 0.957385 | game-dev | 0.997551 | 1 | 0.997551 |
simulationcraft/simc | 23,807 | profiles/TWW3/TWW3_Demon_Hunter_Vengeance.simc | demonhunter="TWW3_Demon_Hunter_Vengeance"
source=default
spec=vengeance
level=80
race=night_elf
timeofday=night
role=tank
position=front
talents=CUkAVVFIvriGAPx6R1rEiLo2cCAGjZmZMmZkZmxYYMbzMYsNjZMjZGmZWmZsMzMMDGAAAAmlZWmlZmZW2mtppZwMzgN
# Default consumables
potion=tempered_potion_3
flask=flask_of_alchemical_chaos_3
food=feast_of_the_divine_day
augmentation=crystallized
temporary_enchant=main_hand:ironclaw_whetstone_3/off_hand:ironclaw_whetstone_3
# This default action priority list is automatically created based on your character.
# It is a attempt to provide you with a action list that is both simple and practicable,
# while resulting in a meaningful and good simulation. It may not result in the absolutely highest possible dps.
# Feel free to edit, adapt and improve it to your own needs.
# SimulationCraft is always looking for updates and improvements to the default action lists.
# Executed before combat begins. Accepts non-harmful actions only.
actions.precombat=snapshot_stats
actions.precombat+=/variable,name=single_target,value=spell_targets.spirit_bomb=1
actions.precombat+=/variable,name=small_aoe,value=spell_targets.spirit_bomb>=2&spell_targets.spirit_bomb<=5
actions.precombat+=/variable,name=big_aoe,value=spell_targets.spirit_bomb>=6
actions.precombat+=/variable,name=trinket_1_buffs,value=trinket.1.has_use_buff|(trinket.1.has_buff.agility|trinket.1.has_buff.mastery|trinket.1.has_buff.versatility|trinket.1.has_buff.haste|trinket.1.has_buff.crit)
actions.precombat+=/variable,name=trinket_2_buffs,value=trinket.2.has_use_buff|(trinket.2.has_buff.agility|trinket.2.has_buff.mastery|trinket.2.has_buff.versatility|trinket.2.has_buff.haste|trinket.2.has_buff.crit)
actions.precombat+=/arcane_torrent
actions.precombat+=/sigil_of_flame,if=hero_tree.aldrachi_reaver|(hero_tree.felscarred&talent.student_of_suffering)
actions.precombat+=/immolation_aura
# Executed every time the actor is available.
actions=variable,name=num_spawnable_souls,op=reset,default=0
actions+=/variable,name=num_spawnable_souls,op=max,value=1,if=talent.soul_sigils&cooldown.sigil_of_flame.up
actions+=/variable,name=num_spawnable_souls,op=max,value=2,if=talent.fracture&cooldown.fracture.charges_fractional>=1&!buff.metamorphosis.up
actions+=/variable,name=num_spawnable_souls,op=max,value=3,if=talent.fracture&cooldown.fracture.charges_fractional>=1&buff.metamorphosis.up
actions+=/variable,name=num_spawnable_souls,op=add,value=1,if=talent.soul_carver&(cooldown.soul_carver.remains>(cooldown.soul_carver.duration-3))
actions+=/auto_attack
actions+=/disrupt,if=target.debuff.casting.react
actions+=/infernal_strike,use_off_gcd=1
actions+=/demon_spikes,use_off_gcd=1,if=!buff.demon_spikes.up&!cooldown.pause_action.remains
actions+=/run_action_list,name=ar,if=hero_tree.aldrachi_reaver
actions+=/run_action_list,name=fs,if=hero_tree.felscarred
actions.ar=use_item,slot=trinket1,if=!trinket.1.is.tome_of_lights_devotion&(!variable.trinket_1_buffs|(variable.trinket_1_buffs&((buff.metamorphosis.up)|(buff.metamorphosis.up&cooldown.metamorphosis.remains<10)|(cooldown.metamorphosis.remains>trinket.1.cooldown.duration)|(variable.trinket_2_buffs&trinket.2.cooldown.remains<cooldown.metamorphosis.remains))))
actions.ar+=/use_item,slot=trinket2,if=!trinket.2.is.tome_of_lights_devotion&(!variable.trinket_2_buffs|(variable.trinket_2_buffs&((buff.metamorphosis.up)|(buff.metamorphosis.up&cooldown.metamorphosis.remains<10)|(cooldown.metamorphosis.remains>trinket.2.cooldown.duration)|(variable.trinket_1_buffs&trinket.1.cooldown.remains<cooldown.metamorphosis.remains))))
actions.ar+=/use_item,name=tome_of_lights_devotion,if=buff.inner_resilience.up
actions.ar+=/potion,use_off_gcd=1,if=(buff.rending_strike.up&buff.glaive_flurry.up)|prev_gcd.1.reavers_glaive
actions.ar+=/call_action_list,name=externals,if=(buff.rending_strike.up&buff.glaive_flurry.up)|prev_gcd.1.reavers_glaive
actions.ar+=/metamorphosis,use_off_gcd=1,if=!buff.metamorphosis.up
actions.ar+=/fel_devastation,use_off_gcd=1,if=!buff.rending_strike.up&!buff.glaive_flurry.up
# Always Soul Cleave if Rending Strike isn't up and Glaive Flurry is
actions.ar+=/soul_cleave,if=!buff.rending_strike.up&buff.glaive_flurry.up
# Spend Rending Strike or generate Fury for empowered Soul Cleave
actions.ar+=/shear,if=talent.fracture&buff.glaive_flurry.up
# Spend Rending Strike or generate Fury for empowered Soul Cleave
actions.ar+=/shear,if=!talent.fracture&buff.glaive_flurry.up
actions.ar+=/reavers_glaive,if=!buff.rending_strike.up&!buff.glaive_flurry.up
actions.ar+=/the_hunt,if=!buff.reavers_glaive.up&(buff.art_of_the_glaive.stack+soul_fragments.total)<20
actions.ar+=/fiery_brand,if=talent.fiery_demise&!dot.fiery_brand.ticking
actions.ar+=/soul_carver,if=!talent.fiery_demise|(talent.fiery_demise&dot.fiery_brand.ticking)
actions.ar+=/sigil_of_spite
# Immolation Aura is one of our best generators if Fallout is talented
actions.ar+=/immolation_aura,if=talent.fallout
actions.ar+=/bulk_extraction,if=spell_targets>=3
actions.ar+=/shear,if=talent.fracture&buff.metamorphosis.up
actions.ar+=/sigil_of_flame
actions.ar+=/shear,if=talent.fracture
actions.ar+=/spirit_bomb,if=spell_targets>=12&soul_fragments>=4
actions.ar+=/soul_cleave
actions.ar+=/immolation_aura
actions.ar+=/felblade
actions.ar+=/vengeful_retreat,if=talent.unhindered_assault
actions.ar+=/throw_glaive
actions.ar+=/shear,if=!talent.fracture
actions.externals=invoke_external_buff,name=symbol_of_hope
actions.externals+=/invoke_external_buff,name=power_infusion
actions.fel_dev=spirit_bomb,if=buff.demonsurge_spirit_burst.up&(variable.can_spburst|soul_fragments>=4|(buff.metamorphosis.remains<(gcd.max*2)))
actions.fel_dev+=/soul_cleave,if=buff.demonsurge_soul_sunder.up&(!buff.demonsurge_spirit_burst.up|(buff.metamorphosis.remains<(gcd.max*2)))
actions.fel_dev+=/sigil_of_spite,if=(!talent.cycle_of_binding|(cooldown.sigil_of_spite.duration<(cooldown.metamorphosis.remains+18)))&(soul_fragments.total<=2&buff.demonsurge_spirit_burst.up)
actions.fel_dev+=/soul_carver,if=soul_fragments.total<=2&!prev_gcd.1.sigil_of_spite&buff.demonsurge_spirit_burst.up
actions.fel_dev+=/shear,if=talent.fracture&soul_fragments.total<=2&buff.demonsurge_spirit_burst.up
actions.fel_dev+=/felblade,if=buff.demonsurge_spirit_burst.up|buff.demonsurge_soul_sunder.up
actions.fel_dev+=/shear,if=talent.fracture&buff.demonsurge_spirit_burst.up|buff.demonsurge_soul_sunder.up
actions.fel_dev_prep=potion,use_off_gcd=1,if=prev_gcd.1.fiery_brand
actions.fel_dev_prep+=/sigil_of_flame,if=!variable.hold_sof_for_precombat&!variable.hold_sof_for_student&!variable.hold_sof_for_dot
actions.fel_dev_prep+=/fiery_brand,if=talent.fiery_demise&((fury+variable.fel_dev_passive_fury_gen)>=120)&(variable.can_spburst|variable.can_spburst_soon|soul_fragments.total>=4)&active_dot.fiery_brand=0&((cooldown.metamorphosis.remains<(execute_time+action.fel_devastation.execute_time+(gcd.max*2)))|variable.fiery_brand_back_before_meta)
actions.fel_dev_prep+=/fel_devastation,if=((fury+variable.fel_dev_passive_fury_gen)>=120)&(variable.can_spburst|variable.can_spburst_soon|soul_fragments.total>=4)
actions.fel_dev_prep+=/sigil_of_spite,if=(!talent.cycle_of_binding|(cooldown.sigil_of_spite.duration<(cooldown.metamorphosis.remains+18)))&(soul_fragments.total<=1|(!(variable.can_spburst|variable.can_spburst_soon|soul_fragments.total>=4)&(!talent.fracture|action.shear.charges_fractional<1)))
actions.fel_dev_prep+=/soul_carver,if=(!talent.cycle_of_binding|cooldown.metamorphosis.remains>20)&(soul_fragments.total<=1|(!(variable.can_spburst|variable.can_spburst_soon|soul_fragments.total>=4)&(!talent.fracture|action.shear.charges_fractional<1)))&!prev_gcd.1.sigil_of_spite&!prev_gcd.2.sigil_of_spite
actions.fel_dev_prep+=/felblade,if=!((fury+variable.fel_dev_passive_fury_gen)>=120)&(variable.can_spburst|variable.can_spburst_soon|soul_fragments.total>=4)
actions.fel_dev_prep+=/shear,if=talent.fracture&!(variable.can_spburst|variable.can_spburst_soon|soul_fragments.total>=4)|!((fury+variable.fel_dev_passive_fury_gen)>=120)
actions.fel_dev_prep+=/felblade
actions.fel_dev_prep+=/shear,if=talent.fracture
actions.fel_dev_prep+=/wait,sec=0.1,if=(!(variable.can_spburst|variable.can_spburst_soon|soul_fragments.total>=4)|!((fury+variable.fel_dev_passive_fury_gen)>=120))&(!talent.fracture|action.shear.charges_fractional>=0.7)
actions.fel_dev_prep+=/fel_devastation
actions.fel_dev_prep+=/soul_cleave,if=((fury+variable.fel_dev_passive_fury_gen)>=150)
actions.fel_dev_prep+=/throw_glaive
actions.fs=variable,name=crit_pct,op=set,value=(dot.sigil_of_flame.crit_pct+(talent.aura_of_pain*6))%100,if=active_dot.sigil_of_flame>0&talent.volatile_flameblood
actions.fs+=/variable,name=fel_dev_sequence_time,op=set,value=2+(2*gcd.max)
actions.fs+=/variable,name=fel_dev_sequence_time,op=add,value=gcd.max,if=talent.fiery_demise&cooldown.fiery_brand.up
actions.fs+=/variable,name=fel_dev_sequence_time,op=add,value=gcd.max,if=cooldown.sigil_of_flame.up|cooldown.sigil_of_flame.remains<variable.fel_dev_sequence_time
actions.fs+=/variable,name=fel_dev_sequence_time,op=add,value=gcd.max,if=cooldown.immolation_aura.up|cooldown.immolation_aura.remains<variable.fel_dev_sequence_time
actions.fs+=/variable,name=fel_dev_passive_fury_gen,op=set,value=0
actions.fs+=/variable,name=fel_dev_passive_fury_gen,op=add,value=2.5*floor((buff.student_of_suffering.remains>?variable.fel_dev_sequence_time)),if=talent.student_of_suffering.enabled&(buff.student_of_suffering.remains>1|prev_gcd.1.sigil_of_flame)
actions.fs+=/variable,name=fel_dev_passive_fury_gen,op=add,value=30+(2*talent.flames_of_fury*spell_targets.sigil_of_flame),if=(cooldown.sigil_of_flame.remains<variable.fel_dev_sequence_time)
actions.fs+=/variable,name=fel_dev_passive_fury_gen,op=add,value=8,if=cooldown.immolation_aura.remains<variable.fel_dev_sequence_time
actions.fs+=/variable,name=fel_dev_passive_fury_gen,op=add,value=2*floor((buff.immolation_aura.remains>?variable.fel_dev_sequence_time)),if=buff.immolation_aura.remains>1
actions.fs+=/variable,name=fel_dev_passive_fury_gen,op=add,value=7.5*variable.crit_pct*floor((buff.immolation_aura.remains>?variable.fel_dev_sequence_time)),if=talent.volatile_flameblood&buff.immolation_aura.remains>1
actions.fs+=/variable,name=fel_dev_passive_fury_gen,op=add,value=22,if=talent.darkglare_boon.enabled
actions.fs+=/variable,name=spbomb_threshold,op=setif,condition=talent.fiery_demise&dot.fiery_brand.ticking,value=(variable.single_target*5)+(variable.small_aoe*5)+(variable.big_aoe*4),value_else=(variable.single_target*5)+(variable.small_aoe*5)+(variable.big_aoe*4)
actions.fs+=/variable,name=can_spbomb,op=setif,condition=talent.spirit_bomb,value=soul_fragments>=variable.spbomb_threshold,value_else=0
actions.fs+=/variable,name=can_spbomb_soon,op=setif,condition=talent.spirit_bomb,value=soul_fragments.total>=variable.spbomb_threshold,value_else=0
actions.fs+=/variable,name=can_spbomb_one_gcd,op=setif,condition=talent.spirit_bomb,value=(soul_fragments.total+variable.num_spawnable_souls)>=variable.spbomb_threshold,value_else=0
actions.fs+=/variable,name=spburst_threshold,op=setif,condition=talent.fiery_demise&dot.fiery_brand.ticking,value=(variable.single_target*5)+(variable.small_aoe*5)+(variable.big_aoe*4),value_else=(variable.single_target*5)+(variable.small_aoe*5)+(variable.big_aoe*4)
actions.fs+=/variable,name=can_spburst,op=setif,condition=talent.spirit_bomb,value=soul_fragments>=variable.spburst_threshold,value_else=0
actions.fs+=/variable,name=can_spburst_soon,op=setif,condition=talent.spirit_bomb,value=soul_fragments.total>=variable.spburst_threshold,value_else=0
actions.fs+=/variable,name=can_spburst_one_gcd,op=setif,condition=talent.spirit_bomb,value=(soul_fragments.total+variable.num_spawnable_souls)>=variable.spburst_threshold,value_else=0
actions.fs+=/variable,name=meta_prep_time,op=set,value=0
actions.fs+=/variable,name=meta_prep_time,op=add,value=action.fiery_brand.execute_time,if=talent.fiery_demise&cooldown.fiery_brand.up
actions.fs+=/variable,name=meta_prep_time,op=add,value=action.sigil_of_flame.execute_time*action.sigil_of_flame.charges
actions.fs+=/variable,name=dont_soul_cleave,op=setif,condition=buff.metamorphosis.up&buff.demonsurge_hardcast.up,value=buff.demonsurge_spirit_burst.up|(buff.metamorphosis.remains<(gcd.max*2)&(!((fury+variable.fel_dev_passive_fury_gen)>=120)|!(variable.can_spburst|variable.can_spburst_soon|soul_fragments.total>=4))),value_else=(cooldown.fel_devastation.remains<(gcd.max*3)&(!((fury+variable.fel_dev_passive_fury_gen)>=120)|!(variable.can_spburst|variable.can_spburst_soon|soul_fragments.total>=4)))
actions.fs+=/variable,name=fiery_brand_back_before_meta,op=setif,condition=talent.down_in_flames,value=charges>=max_charges|(charges_fractional>=1&cooldown.fiery_brand.full_recharge_time<=gcd.remains+execute_time)|(charges_fractional>=1&((1-(charges_fractional-1))*cooldown.fiery_brand.duration)<=cooldown.metamorphosis.remains),value_else=(cooldown.fiery_brand.duration<=cooldown.metamorphosis.remains)
actions.fs+=/variable,name=hold_sof_for_meta,op=setif,condition=talent.illuminated_sigils,value=(charges_fractional>=1&((1-(charges_fractional-1))*cooldown.sigil_of_flame.duration)>cooldown.metamorphosis.remains),value_else=cooldown.sigil_of_flame.duration>cooldown.metamorphosis.remains
actions.fs+=/variable,name=hold_sof_for_fel_dev,op=setif,condition=talent.illuminated_sigils,value=(charges_fractional>=1&((1-(charges_fractional-1))*cooldown.sigil_of_flame.duration)>cooldown.fel_devastation.remains),value_else=cooldown.sigil_of_flame.duration>cooldown.fel_devastation.remains
actions.fs+=/variable,name=hold_sof_for_student,op=setif,condition=talent.student_of_suffering,value=prev_gcd.1.sigil_of_flame|(buff.student_of_suffering.remains>(4-talent.quickened_sigils)),value_else=0
actions.fs+=/variable,name=hold_sof_for_dot,op=setif,condition=talent.ascending_flame,value=0,value_else=prev_gcd.1.sigil_of_flame|(dot.sigil_of_flame.remains>(4-talent.quickened_sigils))
actions.fs+=/variable,name=hold_sof_for_precombat,value=(talent.illuminated_sigils&time<(2-talent.quickened_sigils))
actions.fs+=/use_item,slot=trinket1,if=!trinket.1.is.tome_of_lights_devotion&(!variable.trinket_1_buffs|(variable.trinket_1_buffs&((buff.metamorphosis.up&buff.demonsurge_hardcast.up)|(buff.metamorphosis.up&!buff.demonsurge_hardcast.up&cooldown.metamorphosis.remains<10)|(cooldown.metamorphosis.remains>trinket.1.cooldown.duration)|(variable.trinket_2_buffs&trinket.2.cooldown.remains<cooldown.metamorphosis.remains))))
actions.fs+=/use_item,slot=trinket2,if=!trinket.2.is.tome_of_lights_devotion&(!variable.trinket_2_buffs|(variable.trinket_2_buffs&((buff.metamorphosis.up&buff.demonsurge_hardcast.up)|(buff.metamorphosis.up&!buff.demonsurge_hardcast.up&cooldown.metamorphosis.remains<10)|(cooldown.metamorphosis.remains>trinket.2.cooldown.duration)|(variable.trinket_1_buffs&trinket.1.cooldown.remains<cooldown.metamorphosis.remains))))
actions.fs+=/use_item,name=tome_of_lights_devotion,if=buff.inner_resilience.up
actions.fs+=/immolation_aura,if=time<4
actions.fs+=/immolation_aura,if=!(cooldown.metamorphosis.up&prev_gcd.1.sigil_of_flame)&!(talent.fallout&talent.spirit_bomb&spell_targets.spirit_bomb>=3&((buff.metamorphosis.up&(variable.can_spburst|variable.can_spburst_soon))|(!buff.metamorphosis.up&(variable.can_spbomb|variable.can_spbomb_soon))))&!(buff.metamorphosis.up&buff.demonsurge_hardcast.up)
actions.fs+=/sigil_of_flame,if=!talent.student_of_suffering&!variable.hold_sof_for_dot&!variable.hold_sof_for_precombat
actions.fs+=/sigil_of_flame,if=!variable.hold_sof_for_precombat&(charges=max_charges|(!variable.hold_sof_for_student&!variable.hold_sof_for_dot&!variable.hold_sof_for_meta&!variable.hold_sof_for_fel_dev))
actions.fs+=/fiery_brand,if=active_dot.fiery_brand=0&(!talent.fiery_demise|((talent.down_in_flames&charges>=max_charges)|variable.fiery_brand_back_before_meta))
actions.fs+=/call_action_list,name=fs_execute,if=fight_remains<20
actions.fs+=/run_action_list,name=fel_dev,if=buff.metamorphosis.up&!buff.demonsurge_hardcast.up&(buff.demonsurge_soul_sunder.up|buff.demonsurge_spirit_burst.up)
actions.fs+=/run_action_list,name=metamorphosis,if=buff.metamorphosis.up&buff.demonsurge_hardcast.up
actions.fs+=/run_action_list,name=fel_dev_prep,if=!buff.demonsurge_hardcast.up&(cooldown.fel_devastation.up|(cooldown.fel_devastation.remains<=(gcd.max*3)))
actions.fs+=/run_action_list,name=meta_prep,if=(cooldown.metamorphosis.remains<=variable.meta_prep_time)&!cooldown.fel_devastation.up&!cooldown.fel_devastation.remains<10&!buff.demonsurge_soul_sunder.up&!buff.demonsurge_spirit_burst.up
actions.fs+=/the_hunt
actions.fs+=/felblade,if=((cooldown.sigil_of_spite.remains<execute_time|cooldown.soul_carver.remains<execute_time)&cooldown.fel_devastation.remains<(execute_time+gcd.max)&fury<50)
actions.fs+=/soul_carver,if=(!talent.fiery_demise|talent.fiery_demise&dot.fiery_brand.ticking)&((!talent.spirit_bomb|variable.single_target)|(talent.spirit_bomb&!prev_gcd.1.sigil_of_spite&((soul_fragments.total+3<=5&fury>=40)|(soul_fragments.total=0&fury>=15))))
actions.fs+=/sigil_of_spite,if=(!talent.cycle_of_binding|(cooldown.sigil_of_spite.duration<(cooldown.metamorphosis.remains+18)))&(!talent.spirit_bomb|(fury>=80&(variable.can_spbomb|variable.can_spbomb_soon))|(soul_fragments.total<=(2-talent.soul_sigils.rank)))
actions.fs+=/spirit_bomb,if=variable.can_spburst&talent.fiery_demise&dot.fiery_brand.ticking&!(cooldown.fel_devastation.remains<(gcd.max*3))
actions.fs+=/spirit_bomb,if=variable.can_spbomb&talent.fiery_demise&dot.fiery_brand.ticking&!(cooldown.fel_devastation.remains<(gcd.max*3))
actions.fs+=/soul_cleave,if=variable.single_target&!variable.dont_soul_cleave
actions.fs+=/spirit_bomb,if=variable.can_spburst&!(cooldown.fel_devastation.remains<(gcd.max*3))
actions.fs+=/spirit_bomb,if=variable.can_spbomb&!(cooldown.fel_devastation.remains<(gcd.max*3))
actions.fs+=/felblade,if=((fury<40&((buff.metamorphosis.up&(variable.can_spburst|variable.can_spburst_soon))|(!buff.metamorphosis.up&(variable.can_spbomb|variable.can_spbomb_soon)))))
actions.fs+=/shear,if=talent.fracture&((fury<40&((buff.metamorphosis.up&(variable.can_spburst|variable.can_spburst_soon))|(!buff.metamorphosis.up&(variable.can_spbomb|variable.can_spbomb_soon))))|(buff.metamorphosis.up&variable.can_spburst_one_gcd)|(!buff.metamorphosis.up&variable.can_spbomb_one_gcd))
actions.fs+=/felblade,if=fury.deficit>=40
actions.fs+=/soul_cleave,if=!variable.dont_soul_cleave
actions.fs+=/shear,if=talent.fracture
actions.fs+=/throw_glaive
actions.fs_execute=metamorphosis,use_off_gcd=1
actions.fs_execute+=/the_hunt
actions.fs_execute+=/sigil_of_flame
actions.fs_execute+=/fiery_brand
actions.fs_execute+=/sigil_of_spite
actions.fs_execute+=/soul_carver
actions.fs_execute+=/fel_devastation
actions.meta_prep=metamorphosis,use_off_gcd=1,if=cooldown.sigil_of_flame.charges<1
actions.meta_prep+=/fiery_brand,if=talent.fiery_demise&((talent.down_in_flames&charges>=max_charges)|active_dot.fiery_brand=0)
actions.meta_prep+=/potion,use_off_gcd=1
actions.meta_prep+=/sigil_of_flame
actions.metamorphosis=call_action_list,name=externals
actions.metamorphosis+=/fel_devastation,if=buff.metamorphosis.remains<(gcd.max*3)
actions.metamorphosis+=/felblade,if=fury<50&(buff.metamorphosis.remains<(gcd.max*3))&cooldown.fel_devastation.up
actions.metamorphosis+=/shear,if=talent.fracture&fury<50&!cooldown.felblade.up&(buff.metamorphosis.remains<(gcd.max*3))&cooldown.fel_devastation.up
actions.metamorphosis+=/sigil_of_flame,if=talent.illuminated_sigils&talent.cycle_of_binding&charges=max_charges
actions.metamorphosis+=/immolation_aura
actions.metamorphosis+=/sigil_of_flame,if=!talent.student_of_suffering&(talent.ascending_flame|(!talent.ascending_flame&!prev_gcd.1.sigil_of_flame&(dot.sigil_of_doom.remains<(4-talent.quickened_sigils))))
actions.metamorphosis+=/sigil_of_flame,if=talent.student_of_suffering&!prev_gcd.1.sigil_of_flame&!prev_gcd.1.sigil_of_flame&(buff.student_of_suffering.remains<(4-talent.quickened_sigils))
actions.metamorphosis+=/sigil_of_flame,if=buff.metamorphosis.remains<((2-talent.quickened_sigils)+(charges*gcd.max))
actions.metamorphosis+=/fel_devastation,if=soul_fragments<=3&(soul_fragments.inactive>=2|prev_gcd.1.sigil_of_spite)
actions.metamorphosis+=/felblade,if=((cooldown.sigil_of_spite.remains<execute_time|cooldown.soul_carver.remains<execute_time)&cooldown.fel_devastation.remains<(execute_time+gcd.max)&fury<50)
actions.metamorphosis+=/soul_carver,if=(!talent.spirit_bomb|(variable.single_target&!buff.demonsurge_spirit_burst.up))|(((soul_fragments.total+3)<=6)&fury>=40&!prev_gcd.1.sigil_of_spite)
actions.metamorphosis+=/sigil_of_spite,if=!talent.spirit_bomb|(fury>=80&(variable.can_spburst|variable.can_spburst_soon))|(soul_fragments.total<=(2-talent.soul_sigils.rank))
actions.metamorphosis+=/spirit_bomb,if=variable.can_spburst&buff.demonsurge_spirit_burst.up
actions.metamorphosis+=/fel_devastation
actions.metamorphosis+=/the_hunt
actions.metamorphosis+=/soul_cleave,if=buff.demonsurge_soul_sunder.up&!buff.demonsurge_spirit_burst.up&!variable.can_spburst_one_gcd
actions.metamorphosis+=/spirit_bomb,if=variable.can_spburst&(talent.fiery_demise&dot.fiery_brand.ticking|variable.big_aoe)&buff.metamorphosis.remains>(gcd.max*2)
actions.metamorphosis+=/felblade,if=fury<40&(variable.can_spburst|variable.can_spburst_soon)&(buff.demonsurge_spirit_burst.up|talent.fiery_demise&dot.fiery_brand.ticking|variable.big_aoe)
actions.metamorphosis+=/shear,if=talent.fracture&fury<40&(variable.can_spburst|variable.can_spburst_soon|variable.can_spburst_one_gcd)&(buff.demonsurge_spirit_burst.up|talent.fiery_demise&dot.fiery_brand.ticking|variable.big_aoe)
actions.metamorphosis+=/shear,if=talent.fracture&variable.can_spburst_one_gcd&(buff.demonsurge_spirit_burst.up|variable.big_aoe)&!prev_gcd.1.shear
actions.metamorphosis+=/soul_cleave,if=variable.single_target&!variable.dont_soul_cleave
actions.metamorphosis+=/spirit_bomb,if=variable.can_spburst&buff.metamorphosis.remains>(gcd.max*2)
actions.metamorphosis+=/felblade,if=fury.deficit>=40
actions.metamorphosis+=/soul_cleave,if=!variable.dont_soul_cleave&!(variable.big_aoe&(variable.can_spburst|variable.can_spburst_soon))
actions.metamorphosis+=/felblade
actions.metamorphosis+=/shear,if=talent.fracture&!prev_gcd.1.shear
head=irradiated_impurity_filter,id=237525,ilevel=723,gem_id=213470
neck=ornately_engraved_amplifier,id=185842,ilevel=723,gem_id=213485/213743
shoulders=charhounds_vicious_hornguards,id=237689,ilevel=723
back=reshii_wraps,id=235499,ilevel=730,gem_id=238045,enchant_id=7409
chest=charhounds_vicious_bindings,id=237694,ilevel=723,enchant_id=7364
wrists=runebranded_armbands,id=219334,bonus_id=11109/8790,ilevel=720,gem_id=213485,enchant_id=7391
hands=charhounds_vicious_felclaws,id=237692,ilevel=723
waist=venzas_powderbelt,id=185809,ilevel=723,gem_id=213485
legs=charhounds_vicious_hidecoat,id=237690,ilevel=723,enchant_id=7601
feet=interlopers_reinforced_sandals,id=243306,ilevel=723
finger1=band_of_the_shattered_soul,id=242405,ilevel=723,gem_id=213485/213485,enchant_id=7340
finger2=ring_of_the_panoply,id=246281,ilevel=723,gem_id=213485/213485,enchant_id=7352
trinket1=arazs_ritual_forge,id=242402,ilevel=723
trinket2=tome_of_lights_devotion,id=219309,ilevel=723
main_hand=sonic_kaboomerang,id=234491,ilevel=723,enchant_id=7460
off_hand=everforged_longsword,id=222440,bonus_id=11300/8790,ilevel=720,enchant_id=7439
# Gear Summary
# gear_ilvl=723.06
# gear_agility=69364
# gear_stamina=664039
# gear_attack_power=938
# gear_crit_rating=21335
# gear_haste_rating=29076
# gear_mastery_rating=2929
# gear_versatility_rating=2861
# gear_leech_rating=3060
# gear_armor=43860
# set_bonus=name=thewarwithin_season_3,pc=2,hero_tree=felscarred,enable=1
# set_bonus=name=thewarwithin_season_3,pc=4,hero_tree=felscarred,enable=1
| 412 | 0.688935 | 1 | 0.688935 | game-dev | MEDIA | 0.962064 | game-dev | 0.790441 | 1 | 0.790441 |
Enigma-Game/Enigma | 1,670 | src/items/Landmine.cc | /*
* Copyright (C) 2002,2003,2004 Daniel Heck
* Copyright (C) 2009 Ronald Lamprecht
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "items/Landmine.hh"
//#include "errors.hh"
//#include "main.hh"
//#include "player.hh"
#include "world.hh"
namespace enigma {
Landmine::Landmine() {
}
bool Landmine::actor_hit (Actor *a) {
const double ITEM_RADIUS = 0.3;
if (!a->is_flying()) {
double dist = length(a->get_pos() - get_pos().center());
if (dist < ITEM_RADIUS)
explode();
}
return false;
}
void Landmine::on_stonehit(Stone *st) {
explode();
}
void Landmine::explode() {
sound_event ("landmine");
replace("it_explosion_hollow");
}
DEF_ITEMTRAITSF(Landmine, "it_landmine", it_landmine, itf_static);
BOOT_REGISTER_START
BootRegister(new Landmine(), "it_landmine");
BOOT_REGISTER_END
} // namespace enigma
| 412 | 0.815258 | 1 | 0.815258 | game-dev | MEDIA | 0.991561 | game-dev | 0.581505 | 1 | 0.581505 |
Fluorohydride/ygopro-scripts | 1,850 | c47810543.lua | --魔弾-ブラッディ・クラウン
function c47810543.initial_effect(c)
c:SetUniqueOnField(1,0,47810543)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(47810543,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetRange(LOCATION_SZONE)
e2:SetCountLimit(1,47810543)
e2:SetCondition(c47810543.condition)
e2:SetTarget(c47810543.target)
e2:SetOperation(c47810543.operation)
c:RegisterEffect(e2)
end
function c47810543.condition(e,tp,eg,ep,ev,re,r,rp)
local ph=Duel.GetCurrentPhase()
return ph==PHASE_MAIN1 or ph==PHASE_MAIN2
end
function c47810543.filter(c,e,tp)
return c:IsSetCard(0x108) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c47810543.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c47810543.filter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c47810543.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c47810543.filter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 and Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)>0 then
local seq=4-g:GetFirst():GetSequence()
if Duel.CheckLocation(1-tp,LOCATION_MZONE,seq) then
local val=aux.SequenceToGlobal(1-tp,LOCATION_MZONE,seq)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_DISABLE_FIELD)
e1:SetValue(val)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
end
end
| 412 | 0.841307 | 1 | 0.841307 | game-dev | MEDIA | 0.989928 | game-dev | 0.930818 | 1 | 0.930818 |
REECE-LI/20-StepControl | 13,837 | 2_Firmware/STM32F303_fw/Users/Xdrive/Motor/motion_planner.cpp | #include "motion_planner.h"
#include <cmath>
void MotionPlanner::CurrentTracker::Init()
{
SetCurrentAcc(context->config->ratedCurrentAcc);
}
void MotionPlanner::CurrentTracker::NewTask(int32_t _realCurrent)
{
currentIntegral = 0;
trackCurrent = _realCurrent;
}
void MotionPlanner::CurrentTracker::CalcSoftGoal(int32_t _goalCurrent)
{
int32_t deltaCurrent = _goalCurrent - trackCurrent;
if (deltaCurrent == 0)
{
trackCurrent = _goalCurrent;
} else if (deltaCurrent > 0)
{
if (trackCurrent >= 0)
{
CalcCurrentIntegral(currentAcc);
if (trackCurrent >= _goalCurrent)
{
currentIntegral = 0;
trackCurrent = _goalCurrent;
}
} else
{
CalcCurrentIntegral(currentAcc);
if ((int32_t) trackCurrent >= 0)
{
currentIntegral = 0;
trackCurrent = 0;
}
}
} else if (deltaCurrent < 0)
{
if (trackCurrent <= 0)
{
CalcCurrentIntegral(-currentAcc);
if ((int32_t) trackCurrent <= (int32_t) _goalCurrent)
{
currentIntegral = 0;
trackCurrent = _goalCurrent;
}
} else
{
CalcCurrentIntegral(-currentAcc);
if ((int32_t) trackCurrent <= 0)
{
currentIntegral = 0;
trackCurrent = 0;
}
}
}
goCurrent = (int32_t) trackCurrent;
}
void MotionPlanner::CurrentTracker::CalcCurrentIntegral(int32_t _current)
{
currentIntegral += _current;
trackCurrent += currentIntegral / context->CONTROL_FREQUENCY;
currentIntegral = currentIntegral % context->CONTROL_FREQUENCY;
}
void MotionPlanner::CurrentTracker::SetCurrentAcc(int32_t _currentAcc)
{
currentAcc = _currentAcc;
}
void MotionPlanner::VelocityTracker::Init()
{
SetVelocityAcc(context->config->ratedVelocityAcc);
}
void MotionPlanner::VelocityTracker::SetVelocityAcc(int32_t _velocityAcc)
{
velocityAcc = _velocityAcc;
}
void MotionPlanner::VelocityTracker::NewTask(int32_t _realVelocity)
{
velocityIntegral = 0;
trackVelocity = _realVelocity;
}
void MotionPlanner::VelocityTracker::CalcSoftGoal(int32_t _goalVelocity)
{
int32_t deltaVelocity = _goalVelocity - trackVelocity;
if (deltaVelocity == 0)
{
trackVelocity = _goalVelocity;
} else if (deltaVelocity > 0)
{
if (trackVelocity >= 0)
{
CalcVelocityIntegral(velocityAcc);
if (trackVelocity >= _goalVelocity)
{
velocityIntegral = 0;
trackVelocity = _goalVelocity;
}
} else
{
CalcVelocityIntegral(velocityAcc);
if (trackVelocity >= 0)
{
velocityIntegral = 0;
trackVelocity = 0;
}
}
} else if (deltaVelocity < 0)
{
if (trackVelocity <= 0)
{
CalcVelocityIntegral(-velocityAcc);
if (trackVelocity <= _goalVelocity)
{
velocityIntegral = 0;
trackVelocity = _goalVelocity;
}
} else
{
CalcVelocityIntegral(-velocityAcc);
if (trackVelocity <= 0)
{
velocityIntegral = 0;
trackVelocity = 0;
}
}
}
goVelocity = (int32_t) trackVelocity;
}
void MotionPlanner::VelocityTracker::CalcVelocityIntegral(int32_t _velocity)
{
velocityIntegral += _velocity;
trackVelocity += velocityIntegral / context->CONTROL_FREQUENCY;
velocityIntegral = velocityIntegral % context->CONTROL_FREQUENCY;
}
void MotionPlanner::PositionTracker::Init()
{
SetVelocityAcc(context->config->ratedVelocityAcc);
/*
* Allow to locking-brake when velocity is lower than (speedLockingBrake).
* The best value should be (ratedMoveAcc/1000)
*/
speedLockingBrake = context->config->ratedVelocityAcc / 1000;
}
void MotionPlanner::PositionTracker::SetVelocityAcc(int32_t value)
{
velocityUpAcc = value;
velocityDownAcc = value;
quickVelocityDownAcc = 0.5f / (float) velocityDownAcc;
}
void MotionPlanner::PositionTracker::NewTask(int32_t real_location, int32_t real_speed)
{
velocityIntegral = 0;
trackVelocity = real_speed;
positionIntegral = 0;
trackPosition = real_location;
}
void MotionPlanner::PositionTracker::CalcSoftGoal(int32_t _goalPosition)
{
int32_t deltaPosition = _goalPosition - trackPosition;
if (deltaPosition == 0)
{
if ((trackVelocity >= -speedLockingBrake) && (trackVelocity <= speedLockingBrake))
{
velocityIntegral = 0;
trackVelocity = 0;
positionIntegral = 0;
} else if (trackVelocity > 0)
{
CalcVelocityIntegral(-velocityDownAcc);
if (trackVelocity <= 0)
{
velocityIntegral = 0;
trackVelocity = 0;
}
} else if (trackVelocity < 0)
{
CalcVelocityIntegral(velocityDownAcc);
if (trackVelocity >= 0)
{
velocityIntegral = 0;
trackVelocity = 0;
}
}
} else
{
if (trackVelocity == 0)
{
if (deltaPosition > 0)
{
CalcVelocityIntegral(velocityUpAcc);
} else
{
CalcVelocityIntegral(-velocityUpAcc);
}
} else if ((deltaPosition > 0) && (trackVelocity > 0))
{
if (trackVelocity <= context->config->ratedVelocity)
{
auto need_down_location = (int32_t) ((float) trackVelocity *
(float) trackVelocity *
(float) quickVelocityDownAcc);
if (abs(deltaPosition) > need_down_location)
{
if (trackVelocity < context->config->ratedVelocity)
{
CalcVelocityIntegral(velocityUpAcc);
if (trackVelocity >= context->config->ratedVelocity)
{
velocityIntegral = 0;
trackVelocity = context->config->ratedVelocity;
}
} else if (trackVelocity > context->config->ratedVelocity)
{
CalcVelocityIntegral(-velocityDownAcc);
}
} else
{
CalcVelocityIntegral(-velocityDownAcc);
if (trackVelocity <= 0)
{
velocityIntegral = 0;
trackVelocity = 0;
}
}
} else
{
CalcVelocityIntegral(-velocityDownAcc);
if (trackVelocity <= 0)
{
velocityIntegral = 0;
trackVelocity = 0;
}
}
} else if ((deltaPosition < 0) && (trackVelocity < 0))
{
if (trackVelocity >= -context->config->ratedVelocity)
{
auto need_down_location = (int32_t) ((float) trackVelocity *
(float) trackVelocity *
(float) quickVelocityDownAcc);
if (abs(deltaPosition) > need_down_location)
{
if (trackVelocity > -context->config->ratedVelocity)
{
CalcVelocityIntegral(-velocityUpAcc);
if (trackVelocity <= -context->config->ratedVelocity)
{
velocityIntegral = 0;
trackVelocity = -context->config->ratedVelocity;
}
} else if (trackVelocity < -context->config->ratedVelocity)
{
CalcVelocityIntegral(velocityDownAcc);
}
} else
{
CalcVelocityIntegral(velocityDownAcc);
if (trackVelocity >= 0)
{
velocityIntegral = 0;
trackVelocity = 0;
}
}
} else
{
CalcVelocityIntegral(velocityDownAcc);
if (trackVelocity >= 0)
{
velocityIntegral = 0;
trackVelocity = 0;
}
}
} else if ((deltaPosition < 0) && (trackVelocity > 0))
{
CalcVelocityIntegral(-velocityDownAcc);
if (trackVelocity <= 0)
{
velocityIntegral = 0;
trackVelocity = 0;
}
} else if (((deltaPosition > 0) && (trackVelocity < 0)))
{
CalcVelocityIntegral(velocityDownAcc);
if (trackVelocity >= 0)
{
velocityIntegral = 0;
trackVelocity = 0;
}
}
}
CalcPositionIntegral(trackVelocity);
go_location = (int32_t) trackPosition;
go_velocity = (int32_t) trackVelocity;
}
void MotionPlanner::PositionTracker::CalcPositionIntegral(int32_t value)
{
positionIntegral += value;
trackPosition += positionIntegral / context->CONTROL_FREQUENCY;
positionIntegral = positionIntegral % context->CONTROL_FREQUENCY;
}
void MotionPlanner::PositionTracker::CalcVelocityIntegral(int32_t value)
{
velocityIntegral += value;
trackVelocity += velocityIntegral / context->CONTROL_FREQUENCY;
velocityIntegral = velocityIntegral % context->CONTROL_FREQUENCY;
}
void MotionPlanner::PositionInterpolator::Init()
{
}
void MotionPlanner::PositionInterpolator::NewTask(int32_t _realPosition, int32_t _realVelocity)
{
recordPosition = _realPosition;
recordPositionLast = _realPosition;
estPosition = _realPosition;
estVelocity = _realVelocity;
}
void MotionPlanner::PositionInterpolator::CalcSoftGoal(int32_t _goalPosition)
{
recordPositionLast = recordPosition;
recordPosition = _goalPosition;
estPositionIntegral += (((recordPosition - recordPositionLast) * context->CONTROL_FREQUENCY)
+ ((estVelocity << 6) - estVelocity));
estVelocity = estPositionIntegral >> 6;
estPositionIntegral -= (estVelocity << 6);
estPosition = recordPosition;
goPosition = estPosition;
goVelocity = estVelocity;
}
void MotionPlanner::TrajectoryTracker::SetSlowDownVelocityAcc(int32_t value)
{
velocityDownAcc = value;
}
void MotionPlanner::TrajectoryTracker::NewTask(int32_t real_location, int32_t real_speed)
{
updateTime = 0;
overtimeFlag = false;
dynamicVelocityAccRemainder = 0;
velocityNow = real_speed;
velovityNowRemainder = 0;
positionNow = real_location;
}
void MotionPlanner::TrajectoryTracker::CalcSoftGoal(int32_t _goalPosition, int32_t _goalVelocity)
{
if (_goalVelocity != recordVelocity || _goalPosition != recordPosition)
{
updateTime = 0;
recordVelocity = _goalVelocity;
recordPosition = _goalPosition;
dynamicVelocityAcc = (int32_t) ((float) (_goalVelocity + velocityNow) *
(float) (_goalVelocity - velocityNow) /
(float) (2 * (_goalPosition - positionNow)));
overtimeFlag = false;
} else
{
if (updateTime >= (updateTimeout * 1000))
overtimeFlag = true;
else
updateTime += context->CONTROL_PERIOD;
}
if (overtimeFlag)
{
if (velocityNow == 0)
{
dynamicVelocityAccRemainder = 0;
} else if (velocityNow > 0)
{
CalcVelocityIntegral(-velocityDownAcc);
if (velocityNow <= 0)
{
dynamicVelocityAccRemainder = 0;
velocityNow = 0;
}
} else
{
CalcVelocityIntegral(velocityDownAcc);
if (velocityNow >= 0)
{
dynamicVelocityAccRemainder = 0;
velocityNow = 0;
}
}
} else
{
CalcVelocityIntegral(dynamicVelocityAcc);
}
CalcPositionIntegral(velocityNow);
goPosition = positionNow;
goVelocity = velocityNow;
}
void MotionPlanner::TrajectoryTracker::CalcVelocityIntegral(int32_t value)
{
dynamicVelocityAccRemainder += value; // sum up last remainder
velocityNow += dynamicVelocityAccRemainder / context->CONTROL_FREQUENCY;
dynamicVelocityAccRemainder = dynamicVelocityAccRemainder % context->CONTROL_FREQUENCY; // calc remainder
}
void MotionPlanner::TrajectoryTracker::CalcPositionIntegral(int32_t value)
{
velovityNowRemainder += value;
positionNow += velovityNowRemainder / context->CONTROL_FREQUENCY;
velovityNowRemainder = velovityNowRemainder % context->CONTROL_FREQUENCY;
}
void MotionPlanner::TrajectoryTracker::Init(int32_t _updateTimeout)
{
//SetSlowDownVelocityAcc(context->config->ratedVelocityAcc / 10);
SetSlowDownVelocityAcc(context->config->ratedVelocityAcc);
updateTimeout = _updateTimeout;
}
void MotionPlanner::AttachConfig(MotionPlanner::Config_t* _config)
{
config = _config;
currentTracker.Init();
velocityTracker.Init();
positionTracker.Init();
positionInterpolator.Init();
trajectoryTracker.Init(200);
}
| 412 | 0.88601 | 1 | 0.88601 | game-dev | MEDIA | 0.24898 | game-dev | 0.864624 | 1 | 0.864624 |
DLindustries/System | 3,102 | src/main/java/dlindustries/vigillant/system/gui/components/settings/CheckBox.java | package dlindustries.vigillant.system.gui.components.settings;
import dlindustries.vigillant.system.gui.components.ModuleButton;
import dlindustries.vigillant.system.module.setting.BooleanSetting;
import dlindustries.vigillant.system.module.setting.Setting;
import dlindustries.vigillant.system.utils.ColorUtils;
import dlindustries.vigillant.system.utils.TextRenderer;
import dlindustries.vigillant.system.utils.Utils;
import net.minecraft.client.gui.DrawContext;
import org.lwjgl.glfw.GLFW;
import java.awt.*;
public final class CheckBox extends RenderableSetting {
private final BooleanSetting setting;
private Color currentAlpha;
public CheckBox(ModuleButton parent, Setting<?> setting, int offset) {
super(parent, setting, offset);
this.setting = (BooleanSetting) setting;
}
@Override
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
super.render(context, mouseX, mouseY, delta);
int nameOffset = parentX() + 31;
CharSequence chars = setting.getName();
TextRenderer.drawString(chars, context, nameOffset, (parentY() + parentOffset() + offset) + 9, new Color(245, 245, 245, 255).getRGB());
// Draw checkbox border (16x16)
context.fill((parentX() + 7), (parentY() + parentOffset() + offset) + parentHeight() / 2 - 8, (parentX() + 23), (parentY() + parentOffset() + offset) + parentHeight() / 2 + 8, new Color(100, 100, 100, 255).getRGB());
// Draw checkbox fill (14x14)
context.fill((parentX() + 8), (parentY() + parentOffset() + offset) + parentHeight() / 2 - 7, (parentX() + 22), (parentY() + parentOffset() + offset) + parentHeight() / 2 + 7, setting.getValue() ? Utils.getMainColor(255, parent.settings.indexOf(this)).getRGB() : new Color(50, 50, 50, 255).getRGB());
// Draw checkmark if checked (8x8 square)
if (setting.getValue()) {
context.fill((parentX() + 11), (parentY() + parentOffset() + offset) + parentHeight() / 2 - 4, (parentX() + 19), (parentY() + parentOffset() + offset) + parentHeight() / 2 + 4, new Color(245, 245, 245, 255).getRGB());
}
if (!parent.parent.dragging) {
int toHoverAlpha = isHovered(mouseX, mouseY) ? 15 : 0;
if (currentAlpha == null)
currentAlpha = new Color(255, 255, 255, toHoverAlpha);
else currentAlpha = new Color(255, 255, 255, currentAlpha.getAlpha());
if (currentAlpha.getAlpha() != toHoverAlpha)
currentAlpha = ColorUtils.smoothAlphaTransition(0.05F, toHoverAlpha, currentAlpha);
context.fill(parentX(), parentY() + parentOffset() + offset, parentX() + parentWidth(), parentY() + parentOffset() + offset + parentHeight(), currentAlpha.getRGB());
}
}
@Override
public void keyPressed(int keyCode, int scanCode, int modifiers) {
if(mouseOver && parent.extended) {
if(keyCode == GLFW.GLFW_KEY_BACKSPACE)
setting.setValue(setting.getOriginalValue());
}
super.keyPressed(keyCode, scanCode, modifiers);
}
@Override
public void mouseClicked(double mouseX, double mouseY, int button) {
if (isHovered(mouseX, mouseY) && button == GLFW.GLFW_MOUSE_BUTTON_LEFT)
setting.toggle();
super.mouseClicked(mouseX, mouseY, button);
}
}
| 412 | 0.743791 | 1 | 0.743791 | game-dev | MEDIA | 0.377845 | game-dev,desktop-app | 0.930179 | 1 | 0.930179 |
gta-reversed/gta-reversed | 1,931 | source/game_sa/Tasks/TaskTypes/TaskComplexWalkRoundFire.h | #pragma once
#include "TaskComplex.h"
#include "Base.h"
#include "Ped.h"
#include "Vector.h"
class CPed;
class CTaskComplexWalkRoundFire;
class NOTSA_EXPORT_VTABLE CTaskComplexWalkRoundFire : public CTaskComplex {
public:
eMoveState m_moveState{}; ///< How the ped should move when going around the fire
CSphere m_fireBoundSphere{}; ///< Bounding sphere of the fire
CVector m_targetPos{}; ///< The current position the ped is "going to" (using the GoToPoint task)
CVector m_initialPedPos{}; ///< Ped's initial position (when the task was created)
public:
static void InjectHooks();
static constexpr auto Type = eTaskType::TASK_COMPLEX_WALK_ROUND_FIRE;
CTaskComplexWalkRoundFire(eMoveState moveState, CVector const& firePos, float fireRadius, CVector const& targetPos);
CTaskComplexWalkRoundFire(const CTaskComplexWalkRoundFire&);
~CTaskComplexWalkRoundFire() = default;
bool ComputeDetourTarget(const CPed& ped, CVector& outTarget) const;
CVector GetDetourTarget(const CPed& ped) const;
CTask* Clone() const override { return new CTaskComplexWalkRoundFire{ *this }; }
eTaskType GetTaskType() const override { return Type; }
CTask* CreateNextSubTask(CPed* ped) override { return nullptr; }
CTask* CreateFirstSubTask(CPed* ped) override;
CTask* ControlSubTask(CPed* ped) override;
private: // Wrappers for hooks
// 0x655720
CTaskComplexWalkRoundFire* Constructor(eMoveState moveState, CVector const& firePos, float fireRadius, CVector const& targetPos) {
this->CTaskComplexWalkRoundFire::CTaskComplexWalkRoundFire(moveState, firePos, fireRadius, targetPos);
return this;
}
// 0x655780
CTaskComplexWalkRoundFire* Destructor() {
this->CTaskComplexWalkRoundFire::~CTaskComplexWalkRoundFire();
return this;
}
};
VALIDATE_SIZE(CTaskComplexWalkRoundFire, 0x38);
| 412 | 0.879331 | 1 | 0.879331 | game-dev | MEDIA | 0.955311 | game-dev | 0.518063 | 1 | 0.518063 |
Team-RTG/Realistic-Terrain-Generation | 6,033 | src/main/java/rtg/world/biome/realistic/realworld/RealisticBiomeRWBlueOakForest.java | package rtg.world.biome.realistic.realworld;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDirt.DirtType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.chunk.ChunkPrimer;
import rtg.api.config.BiomeConfig;
import rtg.api.util.BlockUtil;
import rtg.api.util.noise.SimplexNoise;
import rtg.api.world.RTGWorld;
import rtg.api.world.surface.SurfaceBase;
import rtg.api.world.terrain.TerrainBase;
import rtg.api.world.terrain.heighteffect.BumpyHillsEffect;
public class RealisticBiomeRWBlueOakForest extends RealisticBiomeRWBase {
public RealisticBiomeRWBlueOakForest(Biome biome) {
super(biome);
}
@Override
public void initConfig() {
}
@Override
public TerrainBase initTerrain() {
return new TerrainRWBlueOakForest();
}
@Override
public SurfaceBase initSurface() {
return new SurfaceRWBlueOakForest(getConfig(), this.baseBiome().topBlock, this.baseBiome().fillerBlock, 0f, 1.5f, 60f, 65f, 1.5f, BlockUtil.getStateDirt(DirtType.PODZOL), 0.15f);
}
public static class TerrainRWBlueOakForest extends TerrainBase {
private float baseHeight = 64f;
private float hillStrength = 50f;
private BumpyHillsEffect hillEffect;
private float hillWidth = 60f;
private float hillBumpyness = 10f;
private float hillBumpynessWidth = 20f;
public TerrainRWBlueOakForest() {
hillEffect = new BumpyHillsEffect();
hillEffect.hillHeight = hillStrength;
hillEffect.hillWavelength = hillWidth;
hillEffect.spikeHeight = hillBumpyness;
hillEffect.spikeWavelength = this.hillBumpynessWidth;
}
public TerrainRWBlueOakForest(float bh, float hs) {
this();
baseHeight = bh;
hillStrength = hs;
}
@Override
public float generateNoise(RTGWorld rtgWorld, int x, int y, float border, float river) {
groundNoise = groundNoise(x, y, groundNoiseAmplitudeHills, rtgWorld);
float m = hillEffect.added(rtgWorld, x, y);
return riverized(baseHeight, river) + (groundNoise + m) * river;
}
}
public static class SurfaceRWBlueOakForest extends SurfaceBase {
private float min;
private float sCliff = 1.5f;
private float sHeight = 60f;
private float sStrength = 65f;
private float cCliff = 1.5f;
private IBlockState mix;
private float mixHeight;
public SurfaceRWBlueOakForest(BiomeConfig config, IBlockState top, IBlockState fill, float minCliff, float stoneCliff,
float stoneHeight, float stoneStrength, float clayCliff, IBlockState mixBlock, float mixSize) {
super(config, top, fill);
min = minCliff;
sCliff = stoneCliff;
sHeight = stoneHeight;
sStrength = stoneStrength;
cCliff = clayCliff;
mix = mixBlock;
mixHeight = mixSize;
}
@Override
public void paintTerrain(ChunkPrimer primer, int i, int j, int x, int z, int depth, RTGWorld rtgWorld, float[] noise, float river, Biome[] base) {
Random rand = rtgWorld.rand();
SimplexNoise simplex = rtgWorld.simplexInstance(0);
float c = TerrainBase.calcCliff(x, z, noise, river);
int cliff = 0;
boolean m = false;
Block b;
for (int k = 255; k > -1; k--) {
b = primer.getBlockState(x, k, z).getBlock();
if (b == Blocks.AIR) {
depth = -1;
}
else if (b == Blocks.STONE) {
depth++;
if (depth == 0) {
float p = simplex.noise3f(i / 8f, j / 8f, k / 8f) * 0.5f;
if (c > min && c > sCliff - ((k - sHeight) / sStrength) + p) {
cliff = 1;
}
if (c > cCliff) {
cliff = 2;
}
if (cliff == 1) {
if (rand.nextInt(3) == 0) {
primer.setBlockState(x, k, z, hcCobble());
}
else {
primer.setBlockState(x, k, z, hcStone());
}
}
else if (cliff == 2) {
primer.setBlockState(x, k, z, getShadowStoneBlock());
}
else if (k < 63) {
if (k < 62) {
primer.setBlockState(x, k, z, fillerBlock);
}
else {
primer.setBlockState(x, k, z, topBlock);
}
}
else if (simplex.noise2f(i / 12f, j / 12f) > mixHeight) {
primer.setBlockState(x, k, z, mix);
m = true;
}
else {
primer.setBlockState(x, k, z, topBlock);
}
}
else if (depth < 6) {
if (cliff == 1) {
primer.setBlockState(x, k, z, hcStone());
}
else if (cliff == 2) {
primer.setBlockState(x, k, z, getShadowStoneBlock());
}
else {
primer.setBlockState(x, k, z, fillerBlock);
}
}
}
}
}
}
}
| 412 | 0.923057 | 1 | 0.923057 | game-dev | MEDIA | 0.77085 | game-dev | 0.995908 | 1 | 0.995908 |
seed-labs/seed-emulator | 35,301 | experiments/carla-seed/automatic_control/automatic_control.py | #!/usr/bin/env python
# Copyright (c) 2018 Intel Labs.
# authors: German Ros (german.ros@intel.com)
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""Example of automatic vehicle control from client side."""
from __future__ import print_function
import argparse
import collections
import datetime
import glob
import logging
import math
import os
import numpy.random as random
import re
import sys
import weakref
try:
import pygame
from pygame.locals import KMOD_CTRL
from pygame.locals import K_ESCAPE
from pygame.locals import K_q
except ImportError:
raise RuntimeError('cannot import pygame, make sure pygame package is installed')
try:
import numpy as np
except ImportError:
raise RuntimeError(
'cannot import numpy, make sure numpy package is installed')
# ==============================================================================
# -- Find CARLA module ---------------------------------------------------------
# ==============================================================================
try:
sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
# ==============================================================================
# -- Add PythonAPI for release mode --------------------------------------------
# ==============================================================================
try:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/carla')
except IndexError:
pass
import carla
from carla import ColorConverter as cc
from agents.navigation.behavior_agent import BehaviorAgent # pylint: disable=import-error
from agents.navigation.basic_agent import BasicAgent # pylint: disable=import-error
from agents.navigation.constant_velocity_agent import ConstantVelocityAgent # pylint: disable=import-error
# ==============================================================================
# -- Global functions ----------------------------------------------------------
# ==============================================================================
def find_weather_presets():
"""Method to find weather presets"""
rgx = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)')
def name(x): return ' '.join(m.group(0) for m in rgx.finditer(x))
presets = [x for x in dir(carla.WeatherParameters) if re.match('[A-Z].+', x)]
return [(getattr(carla.WeatherParameters, x), name(x)) for x in presets]
def get_actor_display_name(actor, truncate=250):
"""Method to get actor display name"""
name = ' '.join(actor.type_id.replace('_', '.').title().split('.')[1:])
return (name[:truncate - 1] + u'\u2026') if len(name) > truncate else name
def get_actor_blueprints(world, filter, generation):
bps = world.get_blueprint_library().filter(filter)
if generation.lower() == "all":
return bps
# If the filter returns only one bp, we assume that this one needed
# and therefore, we ignore the generation
if len(bps) == 1:
return bps
try:
int_generation = int(generation)
# Check if generation is in available generations
if int_generation in [1, 2, 3]:
bps = [x for x in bps if int(x.get_attribute('generation')) == int_generation]
return bps
else:
print(" Warning! Actor Generation is not valid. No actor will be spawned.")
return []
except:
print(" Warning! Actor Generation is not valid. No actor will be spawned.")
return []
# ==============================================================================
# -- World ---------------------------------------------------------------
# ==============================================================================
class World(object):
""" Class representing the surrounding environment """
def __init__(self, carla_world, hud, args):
"""Constructor method"""
self._args = args
self.world = carla_world
try:
self.map = self.world.get_map()
except RuntimeError as error:
print('RuntimeError: {}'.format(error))
print(' The server could not send the OpenDRIVE (.xodr) file:')
print(' Make sure it exists, has the same name of your town, and is correct.')
sys.exit(1)
self.hud = hud
self.player = None
self.collision_sensor = None
self.lane_invasion_sensor = None
self.gnss_sensor = None
self.camera_manager = None
self._weather_presets = find_weather_presets()
self._weather_index = 0
self._actor_filter = args.filter
self._actor_generation = args.generation
self.restart(args)
self.world.on_tick(hud.on_world_tick)
self.recording_enabled = False
self.recording_start = 0
def restart(self, args):
"""Restart the world"""
# Keep same camera config if the camera manager exists.
cam_index = self.camera_manager.index if self.camera_manager is not None else 0
cam_pos_id = self.camera_manager.transform_index if self.camera_manager is not None else 0
# Get a random blueprint.
blueprint_list = get_actor_blueprints(self.world, self._actor_filter, self._actor_generation)
if not blueprint_list:
raise ValueError("Couldn't find any blueprints with the specified filters")
blueprint = random.choice(blueprint_list)
blueprint.set_attribute('role_name', 'hero')
if blueprint.has_attribute('color'):
color = random.choice(blueprint.get_attribute('color').recommended_values)
blueprint.set_attribute('color', color)
# Spawn the player.
if self.player is not None:
spawn_point = self.player.get_transform()
spawn_point.location.z += 2.0
spawn_point.rotation.roll = 0.0
spawn_point.rotation.pitch = 0.0
self.destroy()
self.player = self.world.try_spawn_actor(blueprint, spawn_point)
self.modify_vehicle_physics(self.player)
while self.player is None:
if not self.map.get_spawn_points():
print('There are no spawn points available in your map/town.')
print('Please add some Vehicle Spawn Point to your UE4 scene.')
sys.exit(1)
spawn_points = self.map.get_spawn_points()
spawn_point = random.choice(spawn_points) if spawn_points else carla.Transform()
self.player = self.world.try_spawn_actor(blueprint, spawn_point)
self.modify_vehicle_physics(self.player)
if self._args.sync:
self.world.tick()
else:
self.world.wait_for_tick()
# Set up the sensors.
self.collision_sensor = CollisionSensor(self.player, self.hud)
self.lane_invasion_sensor = LaneInvasionSensor(self.player, self.hud)
self.gnss_sensor = GnssSensor(self.player)
self.camera_manager = CameraManager(self.player, self.hud)
self.camera_manager.transform_index = cam_pos_id
self.camera_manager.set_sensor(cam_index, notify=False)
actor_type = get_actor_display_name(self.player)
self.hud.notification(actor_type)
def next_weather(self, reverse=False):
"""Get next weather setting"""
self._weather_index += -1 if reverse else 1
self._weather_index %= len(self._weather_presets)
preset = self._weather_presets[self._weather_index]
self.hud.notification('Weather: %s' % preset[1])
self.player.get_world().set_weather(preset[0])
def modify_vehicle_physics(self, actor):
#If actor is not a vehicle, we cannot use the physics control
try:
physics_control = actor.get_physics_control()
physics_control.use_sweep_wheel_collision = True
actor.apply_physics_control(physics_control)
except Exception:
pass
def tick(self, clock):
"""Method for every tick"""
self.hud.tick(self, clock)
def render(self, display):
"""Render world"""
self.camera_manager.render(display)
self.hud.render(display)
def destroy_sensors(self):
"""Destroy sensors"""
self.camera_manager.sensor.destroy()
self.camera_manager.sensor = None
self.camera_manager.index = None
def destroy(self):
"""Destroys all actors"""
actors = [
self.camera_manager.sensor,
self.collision_sensor.sensor,
self.lane_invasion_sensor.sensor,
self.gnss_sensor.sensor,
self.player]
for actor in actors:
if actor is not None:
actor.destroy()
# ==============================================================================
# -- KeyboardControl -----------------------------------------------------------
# ==============================================================================
class KeyboardControl(object):
def __init__(self, world):
world.hud.notification("Press 'H' or '?' for help.", seconds=4.0)
def parse_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
return True
if event.type == pygame.KEYUP:
if self._is_quit_shortcut(event.key):
return True
@staticmethod
def _is_quit_shortcut(key):
"""Shortcut for quitting"""
return (key == K_ESCAPE) or (key == K_q and pygame.key.get_mods() & KMOD_CTRL)
# ==============================================================================
# -- HUD -----------------------------------------------------------------------
# ==============================================================================
class HUD(object):
"""Class for HUD text"""
def __init__(self, width, height):
"""Constructor method"""
self.dim = (width, height)
font = pygame.font.Font(pygame.font.get_default_font(), 20)
font_name = 'courier' if os.name == 'nt' else 'mono'
fonts = [x for x in pygame.font.get_fonts() if font_name in x]
default_font = 'ubuntumono'
mono = default_font if default_font in fonts else fonts[0]
mono = pygame.font.match_font(mono)
self._font_mono = pygame.font.Font(mono, 12 if os.name == 'nt' else 14)
self._notifications = FadingText(font, (width, 40), (0, height - 40))
self.help = HelpText(pygame.font.Font(mono, 24), width, height)
self.server_fps = 0
self.frame = 0
self.simulation_time = 0
self._show_info = True
self._info_text = []
self._server_clock = pygame.time.Clock()
def on_world_tick(self, timestamp):
"""Gets informations from the world at every tick"""
self._server_clock.tick()
self.server_fps = self._server_clock.get_fps()
self.frame = timestamp.frame_count
self.simulation_time = timestamp.elapsed_seconds
def tick(self, world, clock):
"""HUD method for every tick"""
self._notifications.tick(world, clock)
if not self._show_info:
return
transform = world.player.get_transform()
vel = world.player.get_velocity()
control = world.player.get_control()
heading = 'N' if abs(transform.rotation.yaw) < 89.5 else ''
heading += 'S' if abs(transform.rotation.yaw) > 90.5 else ''
heading += 'E' if 179.5 > transform.rotation.yaw > 0.5 else ''
heading += 'W' if -0.5 > transform.rotation.yaw > -179.5 else ''
colhist = world.collision_sensor.get_collision_history()
collision = [colhist[x + self.frame - 200] for x in range(0, 200)]
max_col = max(1.0, max(collision))
collision = [x / max_col for x in collision]
vehicles = world.world.get_actors().filter('vehicle.*')
self._info_text = [
'Server: % 16.0f FPS' % self.server_fps,
'Client: % 16.0f FPS' % clock.get_fps(),
'',
'Vehicle: % 20s' % get_actor_display_name(world.player, truncate=20),
'Map: % 20s' % world.map.name.split('/')[-1],
'Simulation time: % 12s' % datetime.timedelta(seconds=int(self.simulation_time)),
'',
'Speed: % 15.0f km/h' % (3.6 * math.sqrt(vel.x**2 + vel.y**2 + vel.z**2)),
u'Heading:% 16.0f\N{DEGREE SIGN} % 2s' % (transform.rotation.yaw, heading),
'Location:% 20s' % ('(% 5.1f, % 5.1f)' % (transform.location.x, transform.location.y)),
'GNSS:% 24s' % ('(% 2.6f, % 3.6f)' % (world.gnss_sensor.lat, world.gnss_sensor.lon)),
'Height: % 18.0f m' % transform.location.z,
'']
if isinstance(control, carla.VehicleControl):
self._info_text += [
('Throttle:', control.throttle, 0.0, 1.0),
('Steer:', control.steer, -1.0, 1.0),
('Brake:', control.brake, 0.0, 1.0),
('Reverse:', control.reverse),
('Hand brake:', control.hand_brake),
('Manual:', control.manual_gear_shift),
'Gear: %s' % {-1: 'R', 0: 'N'}.get(control.gear, control.gear)]
elif isinstance(control, carla.WalkerControl):
self._info_text += [
('Speed:', control.speed, 0.0, 5.556),
('Jump:', control.jump)]
self._info_text += [
'',
'Collision:',
collision,
'',
'Number of vehicles: % 8d' % len(vehicles)]
if len(vehicles) > 1:
self._info_text += ['Nearby vehicles:']
def dist(l):
return math.sqrt((l.x - transform.location.x)**2 + (l.y - transform.location.y)
** 2 + (l.z - transform.location.z)**2)
vehicles = [(dist(x.get_location()), x) for x in vehicles if x.id != world.player.id]
for dist, vehicle in sorted(vehicles):
if dist > 200.0:
break
vehicle_type = get_actor_display_name(vehicle, truncate=22)
self._info_text.append('% 4dm %s' % (dist, vehicle_type))
def toggle_info(self):
"""Toggle info on or off"""
self._show_info = not self._show_info
def notification(self, text, seconds=2.0):
"""Notification text"""
self._notifications.set_text(text, seconds=seconds)
def error(self, text):
"""Error text"""
self._notifications.set_text('Error: %s' % text, (255, 0, 0))
def render(self, display):
"""Render for HUD class"""
if self._show_info:
info_surface = pygame.Surface((220, self.dim[1]))
info_surface.set_alpha(100)
display.blit(info_surface, (0, 0))
v_offset = 4
bar_h_offset = 100
bar_width = 106
for item in self._info_text:
if v_offset + 18 > self.dim[1]:
break
if isinstance(item, list):
if len(item) > 1:
points = [(x + 8, v_offset + 8 + (1 - y) * 30) for x, y in enumerate(item)]
pygame.draw.lines(display, (255, 136, 0), False, points, 2)
item = None
v_offset += 18
elif isinstance(item, tuple):
if isinstance(item[1], bool):
rect = pygame.Rect((bar_h_offset, v_offset + 8), (6, 6))
pygame.draw.rect(display, (255, 255, 255), rect, 0 if item[1] else 1)
else:
rect_border = pygame.Rect((bar_h_offset, v_offset + 8), (bar_width, 6))
pygame.draw.rect(display, (255, 255, 255), rect_border, 1)
fig = (item[1] - item[2]) / (item[3] - item[2])
if item[2] < 0.0:
rect = pygame.Rect(
(bar_h_offset + fig * (bar_width - 6), v_offset + 8), (6, 6))
else:
rect = pygame.Rect((bar_h_offset, v_offset + 8), (fig * bar_width, 6))
pygame.draw.rect(display, (255, 255, 255), rect)
item = item[0]
if item: # At this point has to be a str.
surface = self._font_mono.render(item, True, (255, 255, 255))
display.blit(surface, (8, v_offset))
v_offset += 18
self._notifications.render(display)
self.help.render(display)
# ==============================================================================
# -- FadingText ----------------------------------------------------------------
# ==============================================================================
class FadingText(object):
""" Class for fading text """
def __init__(self, font, dim, pos):
"""Constructor method"""
self.font = font
self.dim = dim
self.pos = pos
self.seconds_left = 0
self.surface = pygame.Surface(self.dim)
def set_text(self, text, color=(255, 255, 255), seconds=2.0):
"""Set fading text"""
text_texture = self.font.render(text, True, color)
self.surface = pygame.Surface(self.dim)
self.seconds_left = seconds
self.surface.fill((0, 0, 0, 0))
self.surface.blit(text_texture, (10, 11))
def tick(self, _, clock):
"""Fading text method for every tick"""
delta_seconds = 1e-3 * clock.get_time()
self.seconds_left = max(0.0, self.seconds_left - delta_seconds)
self.surface.set_alpha(500.0 * self.seconds_left)
def render(self, display):
"""Render fading text method"""
display.blit(self.surface, self.pos)
# ==============================================================================
# -- HelpText ------------------------------------------------------------------
# ==============================================================================
class HelpText(object):
""" Helper class for text render"""
def __init__(self, font, width, height):
"""Constructor method"""
lines = __doc__.split('\n')
self.font = font
self.dim = (680, len(lines) * 22 + 12)
self.pos = (0.5 * width - 0.5 * self.dim[0], 0.5 * height - 0.5 * self.dim[1])
self.seconds_left = 0
self.surface = pygame.Surface(self.dim)
self.surface.fill((0, 0, 0, 0))
for i, line in enumerate(lines):
text_texture = self.font.render(line, True, (255, 255, 255))
self.surface.blit(text_texture, (22, i * 22))
self._render = False
self.surface.set_alpha(220)
def toggle(self):
"""Toggle on or off the render help"""
self._render = not self._render
def render(self, display):
"""Render help text method"""
if self._render:
display.blit(self.surface, self.pos)
# ==============================================================================
# -- CollisionSensor -----------------------------------------------------------
# ==============================================================================
class CollisionSensor(object):
""" Class for collision sensors"""
def __init__(self, parent_actor, hud):
"""Constructor method"""
self.sensor = None
self.history = []
self._parent = parent_actor
self.hud = hud
world = self._parent.get_world()
blueprint = world.get_blueprint_library().find('sensor.other.collision')
self.sensor = world.spawn_actor(blueprint, carla.Transform(), attach_to=self._parent)
# We need to pass the lambda a weak reference to
# self to avoid circular reference.
weak_self = weakref.ref(self)
self.sensor.listen(lambda event: CollisionSensor._on_collision(weak_self, event))
def get_collision_history(self):
"""Gets the history of collisions"""
history = collections.defaultdict(int)
for frame, intensity in self.history:
history[frame] += intensity
return history
@staticmethod
def _on_collision(weak_self, event):
"""On collision method"""
self = weak_self()
if not self:
return
actor_type = get_actor_display_name(event.other_actor)
self.hud.notification('Collision with %r' % actor_type)
impulse = event.normal_impulse
intensity = math.sqrt(impulse.x ** 2 + impulse.y ** 2 + impulse.z ** 2)
self.history.append((event.frame, intensity))
if len(self.history) > 4000:
self.history.pop(0)
# ==============================================================================
# -- LaneInvasionSensor --------------------------------------------------------
# ==============================================================================
class LaneInvasionSensor(object):
"""Class for lane invasion sensors"""
def __init__(self, parent_actor, hud):
"""Constructor method"""
self.sensor = None
self._parent = parent_actor
self.hud = hud
world = self._parent.get_world()
bp = world.get_blueprint_library().find('sensor.other.lane_invasion')
self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent)
# We need to pass the lambda a weak reference to self to avoid circular
# reference.
weak_self = weakref.ref(self)
self.sensor.listen(lambda event: LaneInvasionSensor._on_invasion(weak_self, event))
@staticmethod
def _on_invasion(weak_self, event):
"""On invasion method"""
self = weak_self()
if not self:
return
lane_types = set(x.type for x in event.crossed_lane_markings)
text = ['%r' % str(x).split()[-1] for x in lane_types]
self.hud.notification('Crossed line %s' % ' and '.join(text))
# ==============================================================================
# -- GnssSensor --------------------------------------------------------
# ==============================================================================
class GnssSensor(object):
""" Class for GNSS sensors"""
def __init__(self, parent_actor):
"""Constructor method"""
self.sensor = None
self._parent = parent_actor
self.lat = 0.0
self.lon = 0.0
world = self._parent.get_world()
blueprint = world.get_blueprint_library().find('sensor.other.gnss')
self.sensor = world.spawn_actor(blueprint, carla.Transform(carla.Location(x=1.0, z=2.8)),
attach_to=self._parent)
# We need to pass the lambda a weak reference to
# self to avoid circular reference.
weak_self = weakref.ref(self)
self.sensor.listen(lambda event: GnssSensor._on_gnss_event(weak_self, event))
@staticmethod
def _on_gnss_event(weak_self, event):
"""GNSS method"""
self = weak_self()
if not self:
return
self.lat = event.latitude
self.lon = event.longitude
# ==============================================================================
# -- CameraManager -------------------------------------------------------------
# ==============================================================================
class CameraManager(object):
""" Class for camera management"""
def __init__(self, parent_actor, hud):
"""Constructor method"""
self.sensor = None
self.surface = None
self._parent = parent_actor
self.hud = hud
self.recording = False
bound_x = 0.5 + self._parent.bounding_box.extent.x
bound_y = 0.5 + self._parent.bounding_box.extent.y
bound_z = 0.5 + self._parent.bounding_box.extent.z
attachment = carla.AttachmentType
self._camera_transforms = [
(carla.Transform(carla.Location(x=-2.0*bound_x, y=+0.0*bound_y, z=2.0*bound_z), carla.Rotation(pitch=8.0)), attachment.SpringArmGhost),
(carla.Transform(carla.Location(x=+0.8*bound_x, y=+0.0*bound_y, z=1.3*bound_z)), attachment.Rigid),
(carla.Transform(carla.Location(x=+1.9*bound_x, y=+1.0*bound_y, z=1.2*bound_z)), attachment.SpringArmGhost),
(carla.Transform(carla.Location(x=-2.8*bound_x, y=+0.0*bound_y, z=4.6*bound_z), carla.Rotation(pitch=6.0)), attachment.SpringArmGhost),
(carla.Transform(carla.Location(x=-1.0, y=-1.0*bound_y, z=0.4*bound_z)), attachment.Rigid)]
self.transform_index = 1
self.sensors = [
['sensor.camera.rgb', cc.Raw, 'Camera RGB'],
['sensor.camera.depth', cc.Raw, 'Camera Depth (Raw)'],
['sensor.camera.depth', cc.Depth, 'Camera Depth (Gray Scale)'],
['sensor.camera.depth', cc.LogarithmicDepth, 'Camera Depth (Logarithmic Gray Scale)'],
['sensor.camera.semantic_segmentation', cc.Raw, 'Camera Semantic Segmentation (Raw)'],
['sensor.camera.semantic_segmentation', cc.CityScapesPalette,
'Camera Semantic Segmentation (CityScapes Palette)'],
['sensor.lidar.ray_cast', None, 'Lidar (Ray-Cast)']]
world = self._parent.get_world()
bp_library = world.get_blueprint_library()
for item in self.sensors:
blp = bp_library.find(item[0])
if item[0].startswith('sensor.camera'):
blp.set_attribute('image_size_x', str(hud.dim[0]))
blp.set_attribute('image_size_y', str(hud.dim[1]))
elif item[0].startswith('sensor.lidar'):
blp.set_attribute('range', '50')
item.append(blp)
self.index = None
def toggle_camera(self):
"""Activate a camera"""
self.transform_index = (self.transform_index + 1) % len(self._camera_transforms)
self.set_sensor(self.index, notify=False, force_respawn=True)
def set_sensor(self, index, notify=True, force_respawn=False):
"""Set a sensor"""
index = index % len(self.sensors)
needs_respawn = True if self.index is None else (
force_respawn or (self.sensors[index][0] != self.sensors[self.index][0]))
if needs_respawn:
if self.sensor is not None:
self.sensor.destroy()
self.surface = None
self.sensor = self._parent.get_world().spawn_actor(
self.sensors[index][-1],
self._camera_transforms[self.transform_index][0],
attach_to=self._parent,
attachment_type=self._camera_transforms[self.transform_index][1])
# We need to pass the lambda a weak reference to
# self to avoid circular reference.
weak_self = weakref.ref(self)
self.sensor.listen(lambda image: CameraManager._parse_image(weak_self, image))
if notify:
self.hud.notification(self.sensors[index][2])
self.index = index
def next_sensor(self):
"""Get the next sensor"""
self.set_sensor(self.index + 1)
def toggle_recording(self):
"""Toggle recording on or off"""
self.recording = not self.recording
self.hud.notification('Recording %s' % ('On' if self.recording else 'Off'))
def render(self, display):
"""Render method"""
if self.surface is not None:
display.blit(self.surface, (0, 0))
@staticmethod
def _parse_image(weak_self, image):
self = weak_self()
if not self:
return
if self.sensors[self.index][0].startswith('sensor.lidar'):
points = np.frombuffer(image.raw_data, dtype=np.dtype('f4'))
points = np.reshape(points, (int(points.shape[0] / 4), 4))
lidar_data = np.array(points[:, :2])
lidar_data *= min(self.hud.dim) / 100.0
lidar_data += (0.5 * self.hud.dim[0], 0.5 * self.hud.dim[1])
lidar_data = np.fabs(lidar_data) # pylint: disable=assignment-from-no-return
lidar_data = lidar_data.astype(np.int32)
lidar_data = np.reshape(lidar_data, (-1, 2))
lidar_img_size = (self.hud.dim[0], self.hud.dim[1], 3)
lidar_img = np.zeros(lidar_img_size)
lidar_img[tuple(lidar_data.T)] = (255, 255, 255)
self.surface = pygame.surfarray.make_surface(lidar_img)
else:
image.convert(self.sensors[self.index][1])
array = np.frombuffer(image.raw_data, dtype=np.dtype("uint8"))
array = np.reshape(array, (image.height, image.width, 4))
array = array[:, :, :3]
array = array[:, :, ::-1]
self.surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))
if self.recording:
image.save_to_disk('_out/%08d' % image.frame)
# ==============================================================================
# -- Game Loop ---------------------------------------------------------
# ==============================================================================
def game_loop(args):
"""
Main loop of the simulation. It handles updating all the HUD information,
ticking the agent and, if needed, the world.
"""
pygame.init()
pygame.font.init()
world = None
try:
if args.seed:
random.seed(args.seed)
client = carla.Client(args.host, args.port)
client.set_timeout(60.0)
traffic_manager = client.get_trafficmanager()
sim_world = client.get_world()
if args.sync:
settings = sim_world.get_settings()
settings.synchronous_mode = True
settings.fixed_delta_seconds = 0.05
sim_world.apply_settings(settings)
traffic_manager.set_synchronous_mode(True)
display = pygame.display.set_mode(
(args.width, args.height),
pygame.HWSURFACE | pygame.DOUBLEBUF)
hud = HUD(args.width, args.height)
world = World(client.get_world(), hud, args)
controller = KeyboardControl(world)
if args.agent == "Basic":
agent = BasicAgent(world.player, 30)
agent.follow_speed_limits(True)
elif args.agent == "Constant":
agent = ConstantVelocityAgent(world.player, 30)
ground_loc = world.world.ground_projection(world.player.get_location(), 5)
if ground_loc:
world.player.set_location(ground_loc.location + carla.Location(z=0.01))
agent.follow_speed_limits(True)
elif args.agent == "Behavior":
agent = BehaviorAgent(world.player, behavior=args.behavior)
# Set the agent destination
spawn_points = world.map.get_spawn_points()
destination = random.choice(spawn_points).location
agent.set_destination(destination)
clock = pygame.time.Clock()
while True:
clock.tick()
if args.sync:
world.world.tick()
else:
world.world.wait_for_tick()
if controller.parse_events():
return
world.tick(clock)
world.render(display)
pygame.display.flip()
if agent.done():
if args.loop:
agent.set_destination(random.choice(spawn_points).location)
world.hud.notification("Target reached", seconds=4.0)
print("The target has been reached, searching for another target")
else:
print("The target has been reached, stopping the simulation")
break
control = agent.run_step()
control.manual_gear_shift = False
world.player.apply_control(control)
finally:
if world is not None:
settings = world.world.get_settings()
settings.synchronous_mode = False
settings.fixed_delta_seconds = None
world.world.apply_settings(settings)
traffic_manager.set_synchronous_mode(True)
world.destroy()
pygame.quit()
# ==============================================================================
# -- main() --------------------------------------------------------------
# ==============================================================================
def main():
"""Main method"""
argparser = argparse.ArgumentParser(
description='CARLA Automatic Control Client')
argparser.add_argument(
'-v', '--verbose',
action='store_true',
dest='debug',
help='Print debug information')
argparser.add_argument(
'--host',
metavar='H',
default='127.0.0.1',
help='IP of the host server (default: 127.0.0.1)')
argparser.add_argument(
'-p', '--port',
metavar='P',
default=2000,
type=int,
help='TCP port to listen to (default: 2000)')
argparser.add_argument(
'--res',
metavar='WIDTHxHEIGHT',
default='1280x720',
help='Window resolution (default: 1280x720)')
argparser.add_argument(
'--sync',
action='store_true',
help='Synchronous mode execution')
argparser.add_argument(
'--filter',
metavar='PATTERN',
default='vehicle.*',
help='Actor filter (default: "vehicle.*")')
argparser.add_argument(
'--generation',
metavar='G',
default='2',
help='restrict to certain actor generation (values: "1","2","All" - default: "2")')
argparser.add_argument(
'-l', '--loop',
action='store_true',
dest='loop',
help='Sets a new random destination upon reaching the previous one (default: False)')
argparser.add_argument(
"-a", "--agent", type=str,
choices=["Behavior", "Basic", "Constant"],
help="select which agent to run",
default="Behavior")
argparser.add_argument(
'-b', '--behavior', type=str,
choices=["cautious", "normal", "aggressive"],
help='Choose one of the possible agent behaviors (default: normal) ',
default='normal')
argparser.add_argument(
'-s', '--seed',
help='Set seed for repeating executions (default: None)',
default=None,
type=int)
args = argparser.parse_args()
args.width, args.height = [int(x) for x in args.res.split('x')]
log_level = logging.DEBUG if args.debug else logging.INFO
logging.basicConfig(format='%(levelname)s: %(message)s', level=log_level)
logging.info('listening to server %s:%s', args.host, args.port)
print(__doc__)
try:
game_loop(args)
except KeyboardInterrupt:
print('\nCancelled by user. Bye!')
if __name__ == '__main__':
main()
| 412 | 0.880338 | 1 | 0.880338 | game-dev | MEDIA | 0.794842 | game-dev | 0.960358 | 1 | 0.960358 |
microsoft/mixed-reality-robot-interaction-demo | 5,644 | MS_MR_Demo1/Assets/MRTK/Core/Utilities/Physics/GazeStabilizer.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Physics
{
/// <summary>
/// GazeStabilizer iterates over samples of Raycast data and
/// helps stabilize the user's gaze for precision targeting.
/// </summary>
[Serializable]
public class GazeStabilizer : BaseRayStabilizer
{
/// <summary>
///Number of samples that you want to iterate on.
/// </summary>
public int StoredStabilitySamples => storedStabilitySamples;
[SerializeField]
[Range(40, 120)]
[Tooltip("Number of samples that you want to iterate on.")]
private int storedStabilitySamples = 60;
/// <summary>
/// The stabilized position.
/// </summary>
public override Vector3 StablePosition => stablePosition;
private Vector3 stablePosition;
/// <summary>
/// The stabilized rotation.
/// </summary>
public override Quaternion StableRotation => stableRotation;
private Quaternion stableRotation;
/// <summary>
/// The stabilized position.
/// </summary>
public override Ray StableRay => stableRay;
private Ray stableRay;
/// <summary>
/// Calculates standard deviation and averages for the gaze position.
/// </summary>
private readonly VectorRollingStatistics positionRollingStats = new VectorRollingStatistics();
/// <summary>
/// Calculates standard deviation and averages for the gaze direction.
/// </summary>
private readonly VectorRollingStatistics directionRollingStats = new VectorRollingStatistics();
/// <summary>
/// Tunable parameter.
/// If the standard deviation for the position is above this value, we reset and stop stabilizing.
/// </summary>
private const float PositionStandardDeviationReset = 0.2f;
/// <summary>
/// Tunable parameter.
/// If the standard deviation for the direction is above this value, we reset and stop stabilizing.
/// </summary>
private const float DirectionStandardDeviationReset = 0.1f;
/// <summary>
/// We must have at least this many samples with a standard deviation below the above constants to stabilize
/// </summary>
private const int MinimumSamplesRequiredToStabilize = 30;
/// <summary>
/// When not stabilizing this is the 'lerp' applied to the position and direction of the gaze to smooth it over time.
/// </summary>
private const float UnstabilizedLerpFactor = 0.3f;
/// <summary>
/// When stabilizing we will use the standard deviation of the position and direction to create the lerp value.
/// By default this value will be low and the cursor will be too sluggish, so we 'boost' it by this value.
/// </summary>
private const float StabalizedLerpBoost = 10.0f;
public GazeStabilizer()
{
directionRollingStats.Init(storedStabilitySamples);
positionRollingStats.Init(storedStabilitySamples);
}
/// <summary>
/// Updates the StablePosition and StableRotation based on GazeSample values.
/// Call this method with RaycastHit parameters to get stable values.
/// </summary>
/// <param name="gazePosition">Position value from a RaycastHit point.</param>
/// <param name="gazeDirection">Direction value from a RaycastHit rotation.</param>
public override void UpdateStability(Vector3 gazePosition, Vector3 gazeDirection)
{
positionRollingStats.AddSample(gazePosition);
directionRollingStats.AddSample(gazeDirection);
float lerpPower = UnstabilizedLerpFactor;
if (positionRollingStats.ActualSampleCount > MinimumSamplesRequiredToStabilize && // we have enough samples and...
(positionRollingStats.CurrentStandardDeviation > PositionStandardDeviationReset || // the standard deviation of positions is high or...
directionRollingStats.CurrentStandardDeviation > DirectionStandardDeviationReset)) // the standard deviation of directions is high
{
// We've detected that the user's gaze is no longer fixed, so stop stabilizing so that gaze is responsive.
// Debug.Log($"Reset {positionRollingStats.CurrentStandardDeviation} {positionRollingStats.StandardDeviationsAwayOfLatestSample} {directionRollingStats.CurrentStandardDeviation} {directionRollingStats.StandardDeviationsAwayOfLatestSample}");
positionRollingStats.Reset();
directionRollingStats.Reset();
}
else if (positionRollingStats.ActualSampleCount > MinimumSamplesRequiredToStabilize)
{
// We've detected that the user's gaze is fairly fixed, so start stabilizing. The more fixed the gaze the less the cursor will move.
lerpPower = StabalizedLerpBoost * (positionRollingStats.CurrentStandardDeviation + directionRollingStats.CurrentStandardDeviation);
}
stablePosition = Vector3.Lerp(stablePosition, gazePosition, lerpPower);
stableRotation = Quaternion.LookRotation(Vector3.Lerp(stableRotation * Vector3.forward, gazeDirection, lerpPower));
stableRay = new Ray(stablePosition, stableRotation * Vector3.forward);
}
}
} | 412 | 0.927077 | 1 | 0.927077 | game-dev | MEDIA | 0.666559 | game-dev | 0.837339 | 1 | 0.837339 |
SourceEngine-CommunityEdition/source | 46,189 | game/server/hl2/npc_spotlight.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "ai_basenpc.h"
#include "AI_Default.h"
#include "AI_Senses.h"
#include "ai_node.h" // for hint defintions
#include "ai_network.h"
#include "AI_Hint.h"
#include "ai_squad.h"
#include "beam_shared.h"
#include "globalstate.h"
#include "soundent.h"
#include "ndebugoverlay.h"
#include "entitylist.h"
#include "npc_citizen17.h"
#include "scriptedtarget.h"
#include "ai_interactions.h"
#include "spotlightend.h"
#include "beam_flags.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define SPOTLIGHT_SWING_FORWARD 1
#define SPOTLIGHT_SWING_BACK -1
//------------------------------------
// Spawnflags
//------------------------------------
#define SF_SPOTLIGHT_START_TRACK_ON (1 << 16)
#define SF_SPOTLIGHT_START_LIGHT_ON (1 << 17)
#define SF_SPOTLIGHT_NO_DYNAMIC_LIGHT (1 << 18)
#define SF_SPOTLIGHT_NEVER_MOVE (1 << 19)
//-----------------------------------------------------------------------------
// Parameters for how the spotlight behaves
//-----------------------------------------------------------------------------
#define SPOTLIGHT_ENTITY_INSPECT_LENGTH 15 // How long does the inspection last
#define SPOTLIGHT_HINT_INSPECT_LENGTH 15 // How long does the inspection last
#define SPOTLIGHT_SOUND_INSPECT_LENGTH 1 // How long does the inspection last
#define SPOTLIGHT_HINT_INSPECT_DELAY 20 // Check for hint nodes this often
#define SPOTLIGHT_ENTITY_INSPECT_DELAY 1 // Check for citizens this often
#define SPOTLIGHT_HINT_SEARCH_DIST 1000 // How far from self do I look for hints?
#define SPOTLIGHT_ENTITY_SEARCH_DIST 100 // How far from spotlight do I look for entities?
#define SPOTLIGHT_ACTIVE_SEARCH_DIST 200 // How far from spotlight do I look when already have entity
#define SPOTLIGHT_BURN_TARGET_THRESH 60 // How close need to get to burn target
#define SPOTLIGHT_MAX_SPEED_SCALE 2
//#define SPOTLIGHT_DEBUG
// -----------------------------------
// Spotlight flags
// -----------------------------------
enum SpotlightFlags_t
{
BITS_SPOTLIGHT_LIGHT_ON = 0x00000001, // Light is on
BITS_SPOTLIGHT_TRACK_ON = 0x00000002, // Tracking targets / scanning
BITS_SPOTLIGHT_SMOOTH_RETURN = 0x00001000, // If out of range, don't pop back to position
};
class CBeam;
class CNPC_Spotlight : public CAI_BaseNPC
{
DECLARE_CLASS( CNPC_Spotlight, CAI_BaseNPC );
public:
CNPC_Spotlight();
Class_T Classify(void);
int UpdateTransmitState(void);
void Event_Killed( const CTakeDamageInfo &info );
int OnTakeDamage_Alive( const CTakeDamageInfo &info );
int GetSoundInterests( void );
bool FValidateHintType(CAI_Hint *pHint);
Disposition_t IRelationType(CBaseEntity *pTarget);
float HearingSensitivity( void ) { return 4.0; };
void NPCThink(void);
bool HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt);
void UpdateTargets(void);
void Precache(void);
void Spawn(void);
public:
int m_fSpotlightFlags;
// ------------------------------
// Scripted Spotlight Motion
// ------------------------------
CScriptedTarget* m_pScriptedTarget; // My current scripted target
void SetScriptedTarget( CScriptedTarget *pScriptedTarget );
// ------------------------------
// Inspecting
// ------------------------------
Vector m_vInspectPos;
float m_flInspectEndTime;
float m_flNextEntitySearchTime;
float m_flNextHintSearchTime; // Time to look for hints to inspect
void SetInspectTargetToEntity(CBaseEntity *pEntity, float fInspectDuration);
void SetInspectTargetToEnemy(CBaseEntity *pEntity);
void SetInspectTargetToPos(const Vector &vInspectPos, float fInspectDuration);
void SetInspectTargetToHint(CAI_Hint *pHint, float fInspectDuration);
void ClearInspectTarget(void);
bool HaveInspectTarget(void);
Vector InspectTargetPosition(void);
CBaseEntity* BestInspectTarget(void);
void RequestInspectSupport(void);
// -------------------------------
// Outputs
// -------------------------------
bool m_bHadEnemy; // Had an enemy
COutputEvent m_pOutputAlert; // Alerted by sound
COutputEHANDLE m_pOutputDetect; // Found enemy, output it's name
COutputEHANDLE m_pOutputLost; // Lost enemy
COutputEHANDLE m_pOutputSquadDetect; // Squad Found enemy
COutputEHANDLE m_pOutputSquadLost; // Squad Lost enemy
COutputVector m_pOutputPosition; // End position of spotlight beam
// ------------------------------
// Spotlight
// ------------------------------
float m_flYaw;
float m_flYawCenter;
float m_flYawRange; // +/- around center
float m_flYawSpeed;
float m_flYawDir;
float m_flPitch;
float m_flPitchCenter;
float m_flPitchMin;
float m_flPitchMax;
float m_flPitchSpeed;
float m_flPitchDir;
float m_flIdleSpeed; // Speed when no enemy
float m_flAlertSpeed; // Speed when found enemy
Vector m_vSpotlightTargetPos;
Vector m_vSpotlightCurrentPos;
CBeam* m_pSpotlight;
CSpotlightEnd* m_pSpotlightTarget;
Vector m_vSpotlightDir;
int m_nHaloSprite;
float m_flSpotlightMaxLength;
float m_flSpotlightCurLength;
float m_flSpotlightGoalWidth;
void SpotlightUpdate(void);
Vector SpotlightCurrentPos(void);
void SpotlightSetTargetYawAndPitch(void);
float SpotlightSpeed(void);
void SpotlightCreate(void);
void SpotlightDestroy(void);
bool SpotlightIsPositionLegal(const Vector &vTestPos);
// ------------------------------
// Inputs
// ------------------------------
void InputLightOn( inputdata_t &inputdata );
void InputLightOff( inputdata_t &inputdata );
void InputTrackOn( inputdata_t &inputdata );
void InputTrackOff( inputdata_t &inputdata );
protected:
DECLARE_DATADESC();
};
BEGIN_DATADESC( CNPC_Spotlight )
DEFINE_FIELD( m_vInspectPos, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_flYaw, FIELD_FLOAT ),
DEFINE_FIELD( m_flYawCenter, FIELD_FLOAT ),
DEFINE_FIELD( m_flYawSpeed, FIELD_FLOAT ),
DEFINE_FIELD( m_flYawDir, FIELD_FLOAT ),
DEFINE_FIELD( m_flPitch, FIELD_FLOAT ),
DEFINE_FIELD( m_flPitchCenter, FIELD_FLOAT ),
DEFINE_FIELD( m_flPitchSpeed, FIELD_FLOAT ),
DEFINE_FIELD( m_flPitchDir, FIELD_FLOAT ),
DEFINE_FIELD( m_flSpotlightCurLength, FIELD_FLOAT ),
DEFINE_FIELD( m_fSpotlightFlags, FIELD_INTEGER ),
DEFINE_FIELD( m_flInspectEndTime, FIELD_TIME ),
DEFINE_FIELD( m_flNextEntitySearchTime, FIELD_TIME ),
DEFINE_FIELD( m_flNextHintSearchTime, FIELD_TIME ),
DEFINE_FIELD( m_bHadEnemy, FIELD_BOOLEAN ),
DEFINE_FIELD( m_vSpotlightTargetPos, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_vSpotlightCurrentPos, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_pSpotlight, FIELD_CLASSPTR ),
DEFINE_FIELD( m_pSpotlightTarget, FIELD_CLASSPTR ),
DEFINE_FIELD( m_vSpotlightDir, FIELD_VECTOR ),
DEFINE_FIELD( m_nHaloSprite, FIELD_INTEGER ),
DEFINE_FIELD( m_pScriptedTarget, FIELD_CLASSPTR ),
DEFINE_KEYFIELD( m_flYawRange, FIELD_FLOAT, "YawRange"),
DEFINE_KEYFIELD( m_flPitchMin, FIELD_FLOAT, "PitchMin"),
DEFINE_KEYFIELD( m_flPitchMax, FIELD_FLOAT, "PitchMax"),
DEFINE_KEYFIELD( m_flIdleSpeed, FIELD_FLOAT, "IdleSpeed"),
DEFINE_KEYFIELD( m_flAlertSpeed, FIELD_FLOAT, "AlertSpeed"),
DEFINE_KEYFIELD( m_flSpotlightMaxLength,FIELD_FLOAT, "SpotlightLength"),
DEFINE_KEYFIELD( m_flSpotlightGoalWidth,FIELD_FLOAT, "SpotlightWidth"),
// DEBUG m_pScriptedTarget
// Inputs
DEFINE_INPUTFUNC( FIELD_VOID, "LightOn", InputLightOn ),
DEFINE_INPUTFUNC( FIELD_VOID, "LightOff", InputLightOff ),
DEFINE_INPUTFUNC( FIELD_VOID, "TrackOn", InputTrackOn ),
DEFINE_INPUTFUNC( FIELD_VOID, "TrackOff", InputTrackOff ),
// Outputs
DEFINE_OUTPUT(m_pOutputAlert, "OnAlert" ),
DEFINE_OUTPUT(m_pOutputDetect, "DetectedEnemy" ),
DEFINE_OUTPUT(m_pOutputLost, "LostEnemy" ),
DEFINE_OUTPUT(m_pOutputSquadDetect, "SquadDetectedEnemy" ),
DEFINE_OUTPUT(m_pOutputSquadLost, "SquadLostEnemy" ),
DEFINE_OUTPUT(m_pOutputPosition, "LightPosition" ),
END_DATADESC()
LINK_ENTITY_TO_CLASS(npc_spotlight, CNPC_Spotlight);
CNPC_Spotlight::CNPC_Spotlight()
{
#ifdef _DEBUG
m_vInspectPos.Init();
m_vSpotlightTargetPos.Init();
m_vSpotlightCurrentPos.Init();
m_vSpotlightDir.Init();
#endif
}
//-----------------------------------------------------------------------------
// Purpose: Indicates this NPC's place in the relationship table.
//-----------------------------------------------------------------------------
Class_T CNPC_Spotlight::Classify(void)
{
return(CLASS_MILITARY);
}
//-------------------------------------------------------------------------------------
// Purpose : Send even though we don't have a model so spotlight gets proper position
// Input :
// Output :
//-------------------------------------------------------------------------------------
int CNPC_Spotlight::UpdateTransmitState(void)
{
return SetTransmitState( FL_EDICT_PVSCHECK );
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
int CNPC_Spotlight::GetSoundInterests( void )
{
return (SOUND_COMBAT | SOUND_DANGER);
}
//------------------------------------------------------------------------------
// Purpose : Override to split in two when attacked
// Input :
// Output :
//------------------------------------------------------------------------------
int CNPC_Spotlight::OnTakeDamage_Alive( const CTakeDamageInfo &info )
{
// Deflect spotlight
Vector vCrossProduct;
CrossProduct(m_vSpotlightDir,g_vecAttackDir, vCrossProduct);
if (vCrossProduct.y > 0)
{
m_flYaw += random->RandomInt(10,20);
}
else
{
m_flYaw -= random->RandomInt(10,20);
}
return (BaseClass::OnTakeDamage_Alive( info ));
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pInflictor -
// pAttacker -
// flDamage -
// bitsDamageType -
//-----------------------------------------------------------------------------
void CNPC_Spotlight::Event_Killed( const CTakeDamageInfo &info )
{
// Interrupt whatever schedule I'm on
SetCondition(COND_SCHEDULE_DONE);
// Remove spotlight
SpotlightDestroy();
// Otherwise, turn into a physics object and fall to the ground
CBaseCombatCharacter::Event_Killed( info );
}
//-----------------------------------------------------------------------------
// Purpose: Tells use whether or not the NPC cares about a given type of hint node.
// Input : sHint -
// Output : TRUE if the NPC is interested in this hint type, FALSE if not.
//-----------------------------------------------------------------------------
bool CNPC_Spotlight::FValidateHintType(CAI_Hint *pHint)
{
if (pHint->HintType() == HINT_WORLD_WINDOW)
{
Vector vHintPos;
pHint->GetPosition(this,&vHintPos);
if (SpotlightIsPositionLegal(vHintPos))
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Plays the engine sound.
//-----------------------------------------------------------------------------
void CNPC_Spotlight::NPCThink(void)
{
SetNextThink( gpGlobals->curtime + 0.1f );// keep npc thinking.
if (CAI_BaseNPC::m_nDebugBits & bits_debugDisableAI)
{
if (m_pSpotlightTarget)
{
m_pSpotlightTarget->SetAbsVelocity( vec3_origin );
}
}
else if (IsAlive())
{
GetSenses()->Listen();
UpdateTargets();
SpotlightUpdate();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Spotlight::Precache(void)
{
//
// Model.
//
PrecacheModel("models/combot.mdl");
PrecacheModel("models/gibs/combot_gibs.mdl");
//
// Sprites.
//
PrecacheModel("sprites/spotlight.vmt");
m_nHaloSprite = PrecacheModel("sprites/blueflare1.vmt");
BaseClass::Precache();
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
CBaseEntity* CNPC_Spotlight::BestInspectTarget(void)
{
// Only look for inspect targets when spotlight it on
if (m_pSpotlightTarget == NULL)
{
return NULL;
}
float fBestDistance = MAX_COORD_RANGE;
int nBestPriority = -1000;
int nBestRelationship = D_NU;
// Get my best enemy first
CBaseEntity* pBestEntity = BestEnemy();
if (pBestEntity)
{
// If the enemy isn't visibile
if (!FVisible(pBestEntity))
{
// If he hasn't been seen in a while and hasn't already eluded
// the squad, make the enemy as eluded and fire a lost squad output
float flTimeLastSeen = GetEnemies()->LastTimeSeen(pBestEntity);
if (!GetEnemies()->HasEludedMe(pBestEntity) &&
flTimeLastSeen + 0.5 < gpGlobals->curtime)
{
GetEnemies()->MarkAsEluded(pBestEntity);
m_pOutputSquadLost.Set(*((EHANDLE *)pBestEntity),this,this);
}
pBestEntity = NULL;
}
// If he has eluded me or isn't in the legal range of my spotligth reject
else if (GetEnemies()->HasEludedMe(pBestEntity) ||
!SpotlightIsPositionLegal(GetEnemies()->LastKnownPosition(pBestEntity)) )
{
pBestEntity = NULL;
}
}
CBaseEntity *pEntity = NULL;
// Search from the spotlight position
Vector vSearchOrigin = m_pSpotlightTarget->GetAbsOrigin();
float flSearchDist;
if (HaveInspectTarget())
{
flSearchDist = SPOTLIGHT_ACTIVE_SEARCH_DIST;
}
else
{
flSearchDist = SPOTLIGHT_ENTITY_SEARCH_DIST;
}
for ( CEntitySphereQuery sphere( vSearchOrigin, SPOTLIGHT_ENTITY_SEARCH_DIST ); pEntity = sphere.GetCurrentEntity(); sphere.NextEntity() )
{
if (pEntity->GetFlags() & (FL_CLIENT|FL_NPC))
{
if (pEntity->GetFlags() & FL_NOTARGET)
{
continue;
}
if (!pEntity->IsAlive())
{
continue;
}
if ((pEntity->Classify() == CLASS_MILITARY)||
(pEntity->Classify() == CLASS_BULLSEYE))
{
continue;
}
if (m_pSquad && m_pSquad->SquadIsMember(pEntity))
{
continue;
}
// Disregard if the entity is out of the view cone, occluded,
if( !FVisible( pEntity ) )
{
continue;
}
// If it's a new enemy or one that had eluded me
if (!GetEnemies()->HasMemory(pEntity) ||
GetEnemies()->HasEludedMe(pEntity) )
{
m_pOutputSquadDetect.Set(*((EHANDLE *)pEntity),this,this);
}
UpdateEnemyMemory(pEntity,pEntity->GetAbsOrigin());
CBaseCombatCharacter* pBCC = (CBaseCombatCharacter*)pEntity;
float fTestDistance = (GetAbsOrigin() - pBCC->EyePosition()).Length();
int nTestRelationship = IRelationType(pBCC);
int nTestPriority = IRelationPriority ( pBCC );
// Only follow hated entities if I'm not in idle state
if (nTestRelationship != D_HT && m_NPCState != NPC_STATE_IDLE)
{
continue;
}
// -------------------------------------------
// Choose hated entites over everything else
// -------------------------------------------
if (nTestRelationship == D_HT && nBestRelationship != D_HT)
{
pBestEntity = pBCC;
fBestDistance = fTestDistance;
nBestPriority = nTestPriority;
nBestRelationship = nTestRelationship;
}
// -------------------------------------------
// If both are hated, or both are not
// -------------------------------------------
else if( (nTestRelationship != D_HT && nBestRelationship != D_HT) ||
(nTestRelationship == D_HT && nBestRelationship == D_HT) )
{
// --------------------------------------
// Pick one with the higher priority
// --------------------------------------
if (nTestPriority > nBestPriority)
{
pBestEntity = pBCC;
fBestDistance = fTestDistance;
nBestPriority = nTestPriority;
nBestRelationship = nTestRelationship;
}
// -----------------------------------------
// If priority the same pick best distance
// -----------------------------------------
else if (nTestPriority == nBestPriority)
{
if (fTestDistance < fBestDistance)
{
pBestEntity = pBCC;
fBestDistance = fTestDistance;
nBestPriority = nTestPriority;
nBestRelationship = nTestRelationship;
}
}
}
}
}
return pBestEntity;
}
//------------------------------------------------------------------------------
// Purpose : Clears any previous inspect target and set inspect target to
// the given entity and set the durection of the inspection
// Input :
// Output :
//------------------------------------------------------------------------------
void CNPC_Spotlight::SetInspectTargetToEntity(CBaseEntity *pEntity, float fInspectDuration)
{
ClearInspectTarget();
SetTarget(pEntity);
m_flInspectEndTime = gpGlobals->curtime + fInspectDuration;
}
//------------------------------------------------------------------------------
// Purpose : Clears any previous inspect target and set inspect target to
// the given entity and set the durection of the inspection
// Input :
// Output :
//------------------------------------------------------------------------------
void CNPC_Spotlight::SetInspectTargetToEnemy(CBaseEntity *pEntity)
{
ClearInspectTarget();
SetEnemy( pEntity );
m_bHadEnemy = true;
m_flInspectEndTime = 0;
SetState(NPC_STATE_COMBAT);
EHANDLE hEnemy;
hEnemy.Set( GetEnemy() );
m_pOutputDetect.Set(hEnemy, NULL, this);
}
//------------------------------------------------------------------------------
// Purpose : Clears any previous inspect target and set inspect target to
// the given hint node and set the durection of the inspection
// Input :
// Output :
//------------------------------------------------------------------------------
void CNPC_Spotlight::SetInspectTargetToHint(CAI_Hint *pHintNode, float fInspectDuration)
{
ClearInspectTarget();
// --------------------------------------------
// Figure out the location that the hint hits
// --------------------------------------------
float fHintYaw = DEG2RAD(pHintNode->Yaw());
Vector vHintDir = Vector(cos(fHintYaw),sin(fHintYaw),0);
Vector vHintOrigin;
pHintNode->GetPosition(this,&vHintOrigin);
Vector vHintEnd = vHintOrigin + (vHintDir * 500);
trace_t tr;
AI_TraceLine ( vHintOrigin, vHintEnd, MASK_OPAQUE, this, COLLISION_GROUP_NONE, &tr);
if (tr.fraction == 1.0)
{
DevMsg("ERROR: Scanner hint node not facing a surface!\n");
}
else
{
SetHintNode( pHintNode );
m_vInspectPos = tr.endpos;
pHintNode->Lock(this);
m_flInspectEndTime = gpGlobals->curtime + fInspectDuration;
}
}
//------------------------------------------------------------------------------
// Purpose : Clears any previous inspect target and set inspect target to
// the given position and set the durection of the inspection
// Input :
// Output :
//------------------------------------------------------------------------------
void CNPC_Spotlight::SetInspectTargetToPos(const Vector &vInspectPos, float fInspectDuration)
{
ClearInspectTarget();
m_vInspectPos = vInspectPos;
m_flInspectEndTime = gpGlobals->curtime + fInspectDuration;
}
//------------------------------------------------------------------------------
// Purpose : Clears out any previous inspection targets
// Input :
// Output :
//------------------------------------------------------------------------------
void CNPC_Spotlight::ClearInspectTarget(void)
{
// If I'm losing an enemy, fire a message
if (m_bHadEnemy)
{
m_bHadEnemy = false;
EHANDLE hEnemy;
hEnemy.Set( GetEnemy() );
m_pOutputLost.Set(hEnemy,this,this);
}
// If I'm in combat state, go to alert
if (m_NPCState == NPC_STATE_COMBAT)
{
SetState(NPC_STATE_ALERT);
}
SetTarget( NULL );
SetEnemy( NULL );
ClearHintNode( SPOTLIGHT_HINT_INSPECT_LENGTH );
m_vInspectPos = vec3_origin;
m_flYawDir = random->RandomInt(0,1) ? 1 : -1;
m_flPitchDir = random->RandomInt(0,1) ? 1 : -1;
}
//------------------------------------------------------------------------------
// Purpose : Returns true if there is a position to be inspected and sets
// vTargetPos to the inspection position
// Input :
// Output :
//------------------------------------------------------------------------------
bool CNPC_Spotlight::HaveInspectTarget(void)
{
if (GetEnemy() != NULL)
{
return true;
}
else if (GetTarget() != NULL)
{
return true;
}
if (m_vInspectPos != vec3_origin)
{
return true;
}
return false;
}
//------------------------------------------------------------------------------
// Purpose : Returns true if there is a position to be inspected and sets
// vTargetPos to the inspection position
// Input :
// Output :
//------------------------------------------------------------------------------
Vector CNPC_Spotlight::InspectTargetPosition(void)
{
if (GetEnemy() != NULL)
{
// If in spotlight mode, aim for ground below target unless is client
if (!(GetEnemy()->GetFlags() & FL_CLIENT))
{
Vector vInspectPos;
vInspectPos.x = GetEnemy()->GetAbsOrigin().x;
vInspectPos.y = GetEnemy()->GetAbsOrigin().y;
vInspectPos.z = GetFloorZ(GetEnemy()->GetAbsOrigin()+Vector(0,0,1));
return vInspectPos;
}
// Otherwise aim for eyes
else
{
return GetEnemy()->EyePosition();
}
}
else if (GetTarget() != NULL)
{
// If in spotlight mode, aim for ground below target unless is client
if (!(GetTarget()->GetFlags() & FL_CLIENT))
{
Vector vInspectPos;
vInspectPos.x = GetTarget()->GetAbsOrigin().x;
vInspectPos.y = GetTarget()->GetAbsOrigin().y;
vInspectPos.z = GetFloorZ(GetTarget()->GetAbsOrigin());
return vInspectPos;
}
// Otherwise aim for eyes
else
{
return GetTarget()->EyePosition();
}
}
else if (m_vInspectPos != vec3_origin)
{
return m_vInspectPos;
}
else
{
DevMsg("InspectTargetPosition called with no target!\n");
return m_vInspectPos;
}
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
void CNPC_Spotlight::UpdateTargets(void)
{
if (m_fSpotlightFlags & BITS_SPOTLIGHT_TRACK_ON)
{
// --------------------------------------------------------------------------
// Look for a nearby entity to inspect
// --------------------------------------------------------------------------
CBaseEntity *pBestEntity = BestInspectTarget();
// If I found one
if (pBestEntity)
{
// If it's an enemy
if (IRelationType(pBestEntity) == D_HT)
{
// If I'm not already inspecting an enemy take it
if (GetEnemy() == NULL)
{
SetInspectTargetToEnemy(pBestEntity);
if (m_pSquad)
{
AISquadIter_t iter;
for (CAI_BaseNPC *pSquadMember = m_pSquad->GetFirstMember( &iter ); pSquadMember; pSquadMember = m_pSquad->GetNextMember( &iter ) )
{
// reset members who aren't activly engaged in fighting
if (pSquadMember->GetEnemy() != pBestEntity && !pSquadMember->HasCondition( COND_SEE_ENEMY))
{
// give them a new enemy
pSquadMember->SetLastAttackTime( 0 );
pSquadMember->SetCondition ( COND_NEW_ENEMY );
}
}
}
}
// If I am inspecting an enemy, take it if priority is higher
else
{
if (IRelationPriority(pBestEntity) > IRelationPriority(GetEnemy()))
{
SetInspectTargetToEnemy(pBestEntity);
}
}
}
// If its not an enemy
else
{
// If I'm not already inspeting something take it
if (GetTarget() == NULL)
{
SetInspectTargetToEntity(pBestEntity,SPOTLIGHT_ENTITY_INSPECT_LENGTH);
}
// If I am inspecting somethin, take if priority is higher
else
{
if (IRelationPriority(pBestEntity) > IRelationPriority(GetTarget()))
{
SetInspectTargetToEntity(pBestEntity,SPOTLIGHT_ENTITY_INSPECT_LENGTH);
}
}
}
}
// ---------------------------------------
// If I'm not current inspecting an enemy
// ---------------------------------------
if (GetEnemy() == NULL)
{
// -----------------------------------------------------------
// If my inspection over clear my inspect target.
// -----------------------------------------------------------
if (HaveInspectTarget() &&
gpGlobals->curtime > m_flInspectEndTime )
{
m_flNextEntitySearchTime = gpGlobals->curtime + SPOTLIGHT_ENTITY_INSPECT_DELAY;
m_flNextHintSearchTime = gpGlobals->curtime + SPOTLIGHT_HINT_INSPECT_DELAY;
ClearInspectTarget();
}
// --------------------------------------------------------------
// If I heard a sound inspect it
// --------------------------------------------------------------
if (HasCondition(COND_HEAR_COMBAT) || HasCondition(COND_HEAR_DANGER) )
{
CSound *pSound = GetBestSound();
if (pSound)
{
Vector vSoundPos = pSound->GetSoundOrigin();
// Only alert to sound if in my swing range
if (SpotlightIsPositionLegal(vSoundPos))
{
SetInspectTargetToPos(vSoundPos,SPOTLIGHT_SOUND_INSPECT_LENGTH);
// Fire alert output
m_pOutputAlert.FireOutput(NULL,this);
SetState(NPC_STATE_ALERT);
}
}
}
// --------------------------------------
// Check for hints to inspect
// --------------------------------------
if (gpGlobals->curtime > m_flNextHintSearchTime &&
!HaveInspectTarget() )
{
SetHintNode(CAI_HintManager::FindHint(this, HINT_NONE, 0, SPOTLIGHT_HINT_SEARCH_DIST));
if (GetHintNode())
{
m_flNextHintSearchTime = gpGlobals->curtime + SPOTLIGHT_HINT_INSPECT_LENGTH;
SetInspectTargetToHint(GetHintNode(),SPOTLIGHT_HINT_INSPECT_LENGTH);
}
}
}
// -------------------------------------------------------
// Make sure inspect target is still in a legal position
// (Don't care about enemies)
// -------------------------------------------------------
if (GetTarget())
{
if (!SpotlightIsPositionLegal(GetEnemies()->LastKnownPosition(GetTarget())))
{
ClearInspectTarget();
}
else if (!FVisible(GetTarget()))
{
ClearInspectTarget();
}
}
if (GetEnemy())
{
if (!FVisible(GetEnemy()))
{
ClearInspectTarget();
}
// If enemy is dead inspect for a couple of seconds on move on
else if (!GetEnemy()->IsAlive())
{
SetInspectTargetToPos( GetEnemy()->GetAbsOrigin(), 1.0);
}
else
{
UpdateEnemyMemory(GetEnemy(),GetEnemy()->GetAbsOrigin());
}
}
// -----------------------------------------
// See if I'm at my burn target
// ------------------------------------------
if (!HaveInspectTarget() &&
m_pScriptedTarget &&
m_pSpotlightTarget != NULL )
{
float fTargetDist = (m_vSpotlightTargetPos - m_vSpotlightCurrentPos).Length();
if (fTargetDist < SPOTLIGHT_BURN_TARGET_THRESH )
{
// Update scripted target
SetScriptedTarget( m_pScriptedTarget->NextScriptedTarget());
}
else
{
Vector vTargetDir = m_vSpotlightTargetPos - m_vSpotlightCurrentPos;
VectorNormalize(vTargetDir);
float flDot = DotProduct(m_vSpotlightDir,vTargetDir);
if (flDot > 0.99 )
{
// Update scripted target
SetScriptedTarget( m_pScriptedTarget->NextScriptedTarget());
}
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Overridden because if the player is a criminal, we hate them.
// Input : pTarget - Entity with which to determine relationship.
// Output : Returns relationship value.
//-----------------------------------------------------------------------------
Disposition_t CNPC_Spotlight::IRelationType(CBaseEntity *pTarget)
{
//
// If it's the player and they are a criminal, we hate them.
//
if (pTarget->Classify() == CLASS_PLAYER)
{
if (GlobalEntity_GetState("gordon_precriminal") == GLOBAL_ON)
{
return(D_NU);
}
}
return(CBaseCombatCharacter::IRelationType(pTarget));
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
void CNPC_Spotlight::SpotlightDestroy(void)
{
if (m_pSpotlight)
{
UTIL_Remove(m_pSpotlight);
m_pSpotlight = NULL;
UTIL_Remove(m_pSpotlightTarget);
m_pSpotlightTarget = NULL;
}
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
void CNPC_Spotlight::SpotlightCreate(void)
{
// If I have an enemy, start spotlight on my enemy
if (GetEnemy() != NULL)
{
Vector vEnemyPos = GetEnemyLKP();
Vector vTargetPos = vEnemyPos;
vTargetPos.z = GetFloorZ(vEnemyPos);
m_vSpotlightDir = vTargetPos - GetAbsOrigin();
VectorNormalize(m_vSpotlightDir);
}
// If I have an target, start spotlight on my target
else if (GetTarget() != NULL)
{
Vector vTargetPos = GetTarget()->GetAbsOrigin();
vTargetPos.z = GetFloorZ(GetTarget()->GetAbsOrigin());
m_vSpotlightDir = vTargetPos - GetAbsOrigin();
VectorNormalize(m_vSpotlightDir);
}
else
{
AngleVectors( GetAbsAngles(), &m_vSpotlightDir );
}
trace_t tr;
AI_TraceLine ( GetAbsOrigin(), GetAbsOrigin() + m_vSpotlightDir * m_flSpotlightMaxLength,
MASK_OPAQUE, this, COLLISION_GROUP_NONE, &tr);
m_pSpotlightTarget = (CSpotlightEnd*)CreateEntityByName( "spotlight_end" );
m_pSpotlightTarget->Spawn();
m_pSpotlightTarget->SetLocalOrigin( tr.endpos );
m_pSpotlightTarget->SetOwnerEntity( this );
m_pSpotlightTarget->m_clrRender = m_clrRender;
m_pSpotlightTarget->m_Radius = m_flSpotlightMaxLength;
if ( FBitSet (m_spawnflags, SF_SPOTLIGHT_NO_DYNAMIC_LIGHT) )
{
m_pSpotlightTarget->m_flLightScale = 0.0;
}
m_pSpotlight = CBeam::BeamCreate( "sprites/spotlight.vmt", 2.0 );
m_pSpotlight->SetColor( m_clrRender->r, m_clrRender->g, m_clrRender->b );
m_pSpotlight->SetHaloTexture(m_nHaloSprite);
m_pSpotlight->SetHaloScale(40);
m_pSpotlight->SetEndWidth(m_flSpotlightGoalWidth);
m_pSpotlight->SetBeamFlags(FBEAM_SHADEOUT);
m_pSpotlight->SetBrightness( 80 );
m_pSpotlight->SetNoise( 0 );
m_pSpotlight->EntsInit( this, m_pSpotlightTarget );
}
//------------------------------------------------------------------------------
// Purpose : Returns true is spotlight can reach position
// Input :
// Output :
//------------------------------------------------------------------------------
bool CNPC_Spotlight::SpotlightIsPositionLegal(const Vector &vTestPos)
{
Vector vTargetDir = vTestPos - GetAbsOrigin();
VectorNormalize(vTargetDir);
QAngle vTargetAngles;
VectorAngles(vTargetDir,vTargetAngles);
// Make sure target is in a legal position
if (UTIL_AngleDistance( vTargetAngles[YAW], m_flYawCenter ) > m_flYawRange)
{
return false;
}
else if (UTIL_AngleDistance( vTargetAngles[YAW], m_flYawCenter ) < -m_flYawRange)
{
return false;
}
if (UTIL_AngleDistance( vTargetAngles[PITCH], m_flPitchCenter ) > m_flPitchMax)
{
return false;
}
else if (UTIL_AngleDistance( vTargetAngles[PITCH], m_flPitchCenter ) < m_flPitchMin)
{
return false;
}
return true;
}
//------------------------------------------------------------------------------
// Purpose : Converts spotlight target position into desired yaw and pitch
// directions to reach target
// Input :
// Output :
//------------------------------------------------------------------------------
void CNPC_Spotlight::SpotlightSetTargetYawAndPitch(void)
{
Vector vTargetDir = m_vSpotlightTargetPos - GetAbsOrigin();
VectorNormalize(vTargetDir);
QAngle vTargetAngles;
VectorAngles(vTargetDir,vTargetAngles);
float flYawDiff = UTIL_AngleDistance(vTargetAngles[YAW], m_flYaw);
if ( flYawDiff > 0)
{
m_flYawDir = SPOTLIGHT_SWING_FORWARD;
}
else
{
m_flYawDir = SPOTLIGHT_SWING_BACK;
}
//DevMsg("%f %f (%f)\n",vTargetAngles[YAW], m_flYaw,flYawDiff);
float flPitchDiff = UTIL_AngleDistance(vTargetAngles[PITCH], m_flPitch);
if (flPitchDiff > 0)
{
m_flPitchDir = SPOTLIGHT_SWING_FORWARD;
}
else
{
m_flPitchDir = SPOTLIGHT_SWING_BACK;
}
//DevMsg("%f %f (%f)\n",vTargetAngles[PITCH], m_flPitch,flPitchDiff);
if ( fabs(flYawDiff) < 2)
{
m_flYawDir *= 0.5;
}
if ( fabs(flPitchDiff) < 2)
{
m_flPitchDir *= 0.5;
}
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
float CNPC_Spotlight::SpotlightSpeed(void)
{
float fSpeedScale = 1.0;
float fInspectDist = (m_vSpotlightTargetPos - m_vSpotlightCurrentPos).Length();
if (fInspectDist < 100)
{
fSpeedScale = 0.25;
}
if (!HaveInspectTarget() && m_pScriptedTarget)
{
return (fSpeedScale * m_pScriptedTarget->MoveSpeed());
}
else if (m_NPCState == NPC_STATE_COMBAT ||
m_NPCState == NPC_STATE_ALERT )
{
return (fSpeedScale * m_flAlertSpeed);
}
else
{
return (fSpeedScale * m_flIdleSpeed);
}
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
Vector CNPC_Spotlight::SpotlightCurrentPos(void)
{
if (!m_pSpotlight)
{
DevMsg("Spotlight pos. called w/o spotlight!\n");
return vec3_origin;
}
if (HaveInspectTarget())
{
m_vSpotlightTargetPos = InspectTargetPosition();
SpotlightSetTargetYawAndPitch();
}
else if (m_pScriptedTarget)
{
m_vSpotlightTargetPos = m_pScriptedTarget->GetAbsOrigin();
SpotlightSetTargetYawAndPitch();
// I'm allowed to move outside my normal range when
// tracking burn targets. Return smoothly when I'm done
m_fSpotlightFlags |= BITS_SPOTLIGHT_SMOOTH_RETURN;
}
else
{
// Make random movement frame independent
if (random->RandomInt(0,10) == 0)
{
m_flYawDir *= -1;
}
if (random->RandomInt(0,10) == 0)
{
m_flPitchDir *= -1;
}
}
// Calculate new pitch and yaw velocity
float flSpeed = SpotlightSpeed();
float flNewYawSpeed = m_flYawDir * flSpeed;
float flNewPitchSpeed = m_flPitchDir * flSpeed;
// Adjust current velocity
float myYawDecay = 0.8;
float myPitchDecay = 0.7;
m_flYawSpeed = (myYawDecay * m_flYawSpeed + (1-myYawDecay) * flNewYawSpeed );
m_flPitchSpeed = (myPitchDecay * m_flPitchSpeed + (1-myPitchDecay) * flNewPitchSpeed);
// Keep speed with in bounds
float flMaxSpeed = SPOTLIGHT_MAX_SPEED_SCALE * SpotlightSpeed();
if (m_flYawSpeed > flMaxSpeed) m_flYawSpeed = flMaxSpeed;
else if (m_flYawSpeed < -flMaxSpeed) m_flYawSpeed = -flMaxSpeed;
if (m_flPitchSpeed > flMaxSpeed) m_flPitchSpeed = flMaxSpeed;
else if (m_flPitchSpeed < -flMaxSpeed) m_flPitchSpeed = -flMaxSpeed;
// Calculate new pitch and yaw positions
m_flYaw += m_flYawSpeed;
m_flPitch += m_flPitchSpeed;
// Keep yaw in 0/360 range
if (m_flYaw < 0 ) m_flYaw +=360;
if (m_flYaw > 360) m_flYaw -=360;
// ---------------------------------------------
// Check yaw and pitch boundaries unless I have
// a burn target, or an enemy
// ---------------------------------------------
if (( HaveInspectTarget() && GetEnemy() == NULL ) ||
(!HaveInspectTarget() && !m_pScriptedTarget ) )
{
bool bInRange = true;
if (UTIL_AngleDistance( m_flYaw, m_flYawCenter ) > m_flYawRange)
{
if (m_fSpotlightFlags & BITS_SPOTLIGHT_SMOOTH_RETURN)
{
bInRange = false;
}
else
{
m_flYaw = m_flYawCenter + m_flYawRange;
}
m_flYawDir = SPOTLIGHT_SWING_BACK;
}
else if (UTIL_AngleDistance( m_flYaw, m_flYawCenter ) < -m_flYawRange)
{
if (m_fSpotlightFlags & BITS_SPOTLIGHT_SMOOTH_RETURN)
{
bInRange = false;
}
else
{
m_flYaw = m_flYawCenter - m_flYawRange;
}
m_flYawDir = SPOTLIGHT_SWING_FORWARD;
}
if (UTIL_AngleDistance( m_flPitch, m_flPitchCenter ) > m_flPitchMax)
{
if (m_fSpotlightFlags & BITS_SPOTLIGHT_SMOOTH_RETURN)
{
bInRange = false;
}
else
{
m_flPitch = m_flPitchCenter + m_flPitchMax;
}
m_flPitchDir = SPOTLIGHT_SWING_BACK;
}
else if (UTIL_AngleDistance( m_flPitch, m_flPitchCenter ) < m_flPitchMin)
{
if (m_fSpotlightFlags & BITS_SPOTLIGHT_SMOOTH_RETURN)
{
bInRange = false;
}
else
{
m_flPitch = m_flPitchCenter + m_flPitchMin;
}
m_flPitchDir = SPOTLIGHT_SWING_FORWARD;
}
// If in range I'm done doing a smooth return
if (bInRange)
{
m_fSpotlightFlags &= ~BITS_SPOTLIGHT_SMOOTH_RETURN;
}
}
// Convert pitch and yaw to forward angle
QAngle vAngle = vec3_angle;
vAngle[YAW] = m_flYaw;
vAngle[PITCH] = m_flPitch;
AngleVectors( vAngle, &m_vSpotlightDir );
// ---------------------------------------------
// Get beam end point. Only collide with
// solid objects, not npcs
// ---------------------------------------------
trace_t tr;
AI_TraceLine ( GetAbsOrigin(), GetAbsOrigin() + (m_vSpotlightDir * 2 * m_flSpotlightMaxLength),
(CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_MONSTER|CONTENTS_DEBRIS),
this, COLLISION_GROUP_NONE, &tr);
return (tr.endpos);
}
//------------------------------------------------------------------------------
// Purpose : Update the direction and position of my spotlight
// Input :
// Output :
//------------------------------------------------------------------------------
void CNPC_Spotlight::SpotlightUpdate(void)
{
// ---------------------------------------------------
// Go back to idle state after a while
// ---------------------------------------------------
if (m_NPCState == NPC_STATE_ALERT &&
m_flLastStateChangeTime + 30 < gpGlobals->curtime )
{
SetState(NPC_STATE_IDLE);
}
// ---------------------------------------------------
// If I don't have a spotlight attempt to create one
// ---------------------------------------------------
if (!m_pSpotlight &&
m_fSpotlightFlags & BITS_SPOTLIGHT_LIGHT_ON )
{
SpotlightCreate();
}
if (!m_pSpotlight)
{
return;
}
// -----------------------------------------------------
// If spotlight flag is off destroy spotlight and exit
// -----------------------------------------------------
if (!(m_fSpotlightFlags & BITS_SPOTLIGHT_LIGHT_ON))
{
if (m_pSpotlight)
{
SpotlightDestroy();
return;
}
}
if (m_fSpotlightFlags & BITS_SPOTLIGHT_TRACK_ON)
{
// -------------------------------------------
// Calculate the new spotlight position
// --------------------------------------------
m_vSpotlightCurrentPos = SpotlightCurrentPos();
}
// --------------------------------------------------------------
// Update spotlight target velocity
// --------------------------------------------------------------
Vector vTargetDir = (m_vSpotlightCurrentPos - m_pSpotlightTarget->GetAbsOrigin());
float vTargetDist = vTargetDir.Length();
Vector vecNewVelocity = vTargetDir;
VectorNormalize(vecNewVelocity);
vecNewVelocity *= (10 * vTargetDist);
// If a large move is requested, just jump to final spot as we
// probably hit a discontinuity
if (vecNewVelocity.Length() > 200)
{
VectorNormalize(vecNewVelocity);
vecNewVelocity *= 200;
VectorNormalize(vTargetDir);
m_pSpotlightTarget->SetLocalOrigin( m_vSpotlightCurrentPos );
}
m_pSpotlightTarget->SetAbsVelocity( vecNewVelocity );
m_pSpotlightTarget->m_vSpotlightOrg = GetAbsOrigin();
// Avoid sudden change in where beam fades out when cross disconinuities
m_pSpotlightTarget->m_vSpotlightDir = m_pSpotlightTarget->GetLocalOrigin() - m_pSpotlightTarget->m_vSpotlightOrg;
float flBeamLength = VectorNormalize( m_pSpotlightTarget->m_vSpotlightDir );
m_flSpotlightCurLength = (0.60*m_flSpotlightCurLength) + (0.4*flBeamLength);
// Fade out spotlight end if past max length.
if (m_flSpotlightCurLength > 2*m_flSpotlightMaxLength)
{
m_pSpotlightTarget->SetRenderColorA( 0 );
m_pSpotlight->SetFadeLength(m_flSpotlightMaxLength);
}
else if (m_flSpotlightCurLength > m_flSpotlightMaxLength)
{
m_pSpotlightTarget->SetRenderColorA( (1-((m_flSpotlightCurLength-m_flSpotlightMaxLength)/m_flSpotlightMaxLength)) );
m_pSpotlight->SetFadeLength(m_flSpotlightMaxLength);
}
else
{
m_pSpotlightTarget->SetRenderColorA( 1.0 );
m_pSpotlight->SetFadeLength(m_flSpotlightCurLength);
}
// Adjust end width to keep beam width constant
float flNewWidth = m_flSpotlightGoalWidth*(flBeamLength/m_flSpotlightMaxLength);
m_pSpotlight->SetEndWidth(flNewWidth);
// Adjust width of light on the end.
if ( FBitSet (m_spawnflags, SF_SPOTLIGHT_NO_DYNAMIC_LIGHT) )
{
m_pSpotlightTarget->m_flLightScale = 0.0;
}
else
{
// <<TODO>> - magic number 1.8 depends on sprite size
m_pSpotlightTarget->m_flLightScale = 1.8*flNewWidth;
}
m_pOutputPosition.Set(m_pSpotlightTarget->GetLocalOrigin(),this,this);
#ifdef SPOTLIGHT_DEBUG
NDebugOverlay::Cross3D(m_vSpotlightCurrentPos,Vector(-5,-5,-5),Vector(5,5,5),0,255,0,true,0.1);
NDebugOverlay::Cross3D(m_vSpotlightTargetPos,Vector(-5,-5,-5),Vector(5,5,5),255,0,0,true,0.1);
#endif
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Spotlight::Spawn(void)
{
// Check for user error
if (m_flSpotlightMaxLength <= 0)
{
DevMsg("CNPC_Spotlight::Spawn: Invalid spotlight length <= 0, setting to 500\n");
m_flSpotlightMaxLength = 500;
}
if (m_flSpotlightGoalWidth <= 0)
{
DevMsg("CNPC_Spotlight::Spawn: Invalid spotlight width <= 0, setting to 10\n");
m_flSpotlightGoalWidth = 10;
}
if (m_flSpotlightGoalWidth > MAX_BEAM_WIDTH)
{
DevMsg("CNPC_Spotlight::Spawn: Invalid spotlight width %.1f (max %.1f)\n", m_flSpotlightGoalWidth, MAX_BEAM_WIDTH );
m_flSpotlightGoalWidth = MAX_BEAM_WIDTH;
}
Precache();
// This is a dummy model that is never used!
SetModel( "models/player.mdl" );
// No Hull for now
UTIL_SetSize(this,vec3_origin,vec3_origin);
SetSolid( SOLID_BBOX );
AddSolidFlags( FSOLID_NOT_STANDABLE );
m_bloodColor = DONT_BLEED;
SetViewOffset( Vector(0, 0, 10) ); // Position of the eyes relative to NPC's origin.
m_flFieldOfView = VIEW_FIELD_FULL;
m_NPCState = NPC_STATE_IDLE;
CapabilitiesAdd( bits_CAP_SQUAD);
// ------------------------------------
// Init all class vars
// ------------------------------------
m_vInspectPos = vec3_origin;
m_flInspectEndTime = 0;
m_flNextEntitySearchTime= gpGlobals->curtime + SPOTLIGHT_ENTITY_INSPECT_DELAY;
m_flNextHintSearchTime = gpGlobals->curtime + SPOTLIGHT_HINT_INSPECT_DELAY;
m_bHadEnemy = false;
m_vSpotlightTargetPos = vec3_origin;
m_vSpotlightCurrentPos = vec3_origin;
m_pSpotlight = NULL;
m_pSpotlightTarget = NULL;
m_vSpotlightDir = vec3_origin;
//m_nHaloSprite // Set in precache
m_flSpotlightCurLength = m_flSpotlightMaxLength;
m_flYaw = 0;
m_flYawSpeed = 0;
m_flYawCenter = GetLocalAngles().y;
m_flYawDir = random->RandomInt(0,1) ? 1 : -1;
//m_flYawRange = 90; // Keyfield in WC
m_flPitch = 0;
m_flPitchSpeed = 0;
m_flPitchCenter = GetLocalAngles().x;
m_flPitchDir = random->RandomInt(0,1) ? 1 : -1;
//m_flPitchMin = 35; // Keyfield in WC
//m_flPitchMax = 50; // Keyfield in WC
//m_flIdleSpeed = 2; // Keyfield in WC
//m_flAlertSpeed = 5; // Keyfield in WC
m_fSpotlightFlags = 0;
if (FBitSet ( m_spawnflags, SF_SPOTLIGHT_START_TRACK_ON ))
{
m_fSpotlightFlags |= BITS_SPOTLIGHT_TRACK_ON;
}
if (FBitSet ( m_spawnflags, SF_SPOTLIGHT_START_LIGHT_ON ))
{
m_fSpotlightFlags |= BITS_SPOTLIGHT_LIGHT_ON;
}
// If I'm never moving just turn on the spotlight and don't think again
if (FBitSet ( m_spawnflags, SF_SPOTLIGHT_NEVER_MOVE ))
{
SpotlightCreate();
}
else
{
NPCInit();
SetThink(CallNPCThink);
}
AddEffects( EF_NODRAW );
SetMoveType( MOVETYPE_NONE );
SetGravity( 0.0 );
}
//------------------------------------------------------------------------------
// Purpose: Inputs
//------------------------------------------------------------------------------
void CNPC_Spotlight::InputLightOn( inputdata_t &inputdata )
{
m_fSpotlightFlags |= BITS_SPOTLIGHT_LIGHT_ON;
}
void CNPC_Spotlight::InputLightOff( inputdata_t &inputdata )
{
m_fSpotlightFlags &= ~BITS_SPOTLIGHT_LIGHT_ON;
}
void CNPC_Spotlight::InputTrackOn( inputdata_t &inputdata )
{
m_fSpotlightFlags |= BITS_SPOTLIGHT_TRACK_ON;
}
void CNPC_Spotlight::InputTrackOff( inputdata_t &inputdata )
{
m_fSpotlightFlags &= ~BITS_SPOTLIGHT_TRACK_ON;
}
//------------------------------------------------------------------------------
// Purpose : Starts cremator doing scripted burn to a location
//------------------------------------------------------------------------------
void CNPC_Spotlight::SetScriptedTarget( CScriptedTarget *pScriptedTarget )
{
if (pScriptedTarget)
{
m_pScriptedTarget = pScriptedTarget;
m_vSpotlightTargetPos = m_pScriptedTarget->GetAbsOrigin();
}
else
{
m_pScriptedTarget = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose: This is a generic function (to be implemented by sub-classes) to
// handle specific interactions between different types of characters
// (For example the barnacle grabbing an NPC)
// Input : Constant for the type of interaction
// Output : true - if sub-class has a response for the interaction
// false - if sub-class has no response
//-----------------------------------------------------------------------------
bool CNPC_Spotlight::HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt)
{
if (interactionType == g_interactionScriptedTarget)
{
// If I already have a scripted target, reject the new one
if (m_pScriptedTarget && sourceEnt)
{
return false;
}
else
{
SetScriptedTarget((CScriptedTarget*)sourceEnt);
return true;
}
}
return false;
}
| 412 | 0.947908 | 1 | 0.947908 | game-dev | MEDIA | 0.951142 | game-dev | 0.703319 | 1 | 0.703319 |
scanse/sweep-3d-scanner-unity-viewer | 9,149 | Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/RigidbodyFirstPersonController.cs | using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (Rigidbody))]
[RequireComponent(typeof (CapsuleCollider))]
public class RigidbodyFirstPersonController : MonoBehaviour
{
[Serializable]
public class MovementSettings
{
public float ForwardSpeed = 8.0f; // Speed when walking forward
public float BackwardSpeed = 4.0f; // Speed when walking backwards
public float StrafeSpeed = 4.0f; // Speed when walking sideways
public float RunMultiplier = 2.0f; // Speed when sprinting
public KeyCode RunKey = KeyCode.LeftShift;
public float JumpForce = 30f;
public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f));
[HideInInspector] public float CurrentTargetSpeed = 8f;
#if !MOBILE_INPUT
private bool m_Running;
#endif
public void UpdateDesiredTargetSpeed(Vector2 input)
{
if (input == Vector2.zero) return;
if (input.x > 0 || input.x < 0)
{
//strafe
CurrentTargetSpeed = StrafeSpeed;
}
if (input.y < 0)
{
//backwards
CurrentTargetSpeed = BackwardSpeed;
}
if (input.y > 0)
{
//forwards
//handled last as if strafing and moving forward at the same time forwards speed should take precedence
CurrentTargetSpeed = ForwardSpeed;
}
#if !MOBILE_INPUT
if (Input.GetKey(RunKey))
{
CurrentTargetSpeed *= RunMultiplier;
m_Running = true;
}
else
{
m_Running = false;
}
#endif
}
#if !MOBILE_INPUT
public bool Running
{
get { return m_Running; }
}
#endif
}
[Serializable]
public class AdvancedSettings
{
public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this )
public float stickToGroundHelperDistance = 0.5f; // stops the character
public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input
public bool airControl; // can the user control the direction that is being moved in the air
[Tooltip("set it to 0.1 or more if you get stuck in wall")]
public float shellOffset; //reduce the radius by that ratio to avoid getting stuck in wall (a value of 0.1f is nice)
}
public Camera cam;
public MovementSettings movementSettings = new MovementSettings();
public MouseLook mouseLook = new MouseLook();
public AdvancedSettings advancedSettings = new AdvancedSettings();
private Rigidbody m_RigidBody;
private CapsuleCollider m_Capsule;
private float m_YRotation;
private Vector3 m_GroundContactNormal;
private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded;
public Vector3 Velocity
{
get { return m_RigidBody.velocity; }
}
public bool Grounded
{
get { return m_IsGrounded; }
}
public bool Jumping
{
get { return m_Jumping; }
}
public bool Running
{
get
{
#if !MOBILE_INPUT
return movementSettings.Running;
#else
return false;
#endif
}
}
private void Start()
{
m_RigidBody = GetComponent<Rigidbody>();
m_Capsule = GetComponent<CapsuleCollider>();
mouseLook.Init (transform, cam.transform);
}
private void Update()
{
RotateView();
if (CrossPlatformInputManager.GetButtonDown("Jump") && !m_Jump)
{
m_Jump = true;
}
}
private void FixedUpdate()
{
GroundCheck();
Vector2 input = GetInput();
if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded))
{
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = cam.transform.forward*input.y + cam.transform.right*input.x;
desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;
desiredMove.x = desiredMove.x*movementSettings.CurrentTargetSpeed;
desiredMove.z = desiredMove.z*movementSettings.CurrentTargetSpeed;
desiredMove.y = desiredMove.y*movementSettings.CurrentTargetSpeed;
if (m_RigidBody.velocity.sqrMagnitude <
(movementSettings.CurrentTargetSpeed*movementSettings.CurrentTargetSpeed))
{
m_RigidBody.AddForce(desiredMove*SlopeMultiplier(), ForceMode.Impulse);
}
}
if (m_IsGrounded)
{
m_RigidBody.drag = 5f;
if (m_Jump)
{
m_RigidBody.drag = 0f;
m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z);
m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse);
m_Jumping = true;
}
if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f)
{
m_RigidBody.Sleep();
}
}
else
{
m_RigidBody.drag = 0f;
if (m_PreviouslyGrounded && !m_Jumping)
{
StickToGroundHelper();
}
}
m_Jump = false;
}
private float SlopeMultiplier()
{
float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up);
return movementSettings.SlopeCurveModifier.Evaluate(angle);
}
private void StickToGroundHelper()
{
RaycastHit hitInfo;
if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
((m_Capsule.height/2f) - m_Capsule.radius) +
advancedSettings.stickToGroundHelperDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f)
{
m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal);
}
}
}
private Vector2 GetInput()
{
Vector2 input = new Vector2
{
x = CrossPlatformInputManager.GetAxis("Horizontal"),
y = CrossPlatformInputManager.GetAxis("Vertical")
};
movementSettings.UpdateDesiredTargetSpeed(input);
return input;
}
private void RotateView()
{
//avoids the mouse looking if the game is effectively paused
if (Mathf.Abs(Time.timeScale) < float.Epsilon) return;
// get the rotation before it's changed
float oldYRotation = transform.eulerAngles.y;
mouseLook.LookRotation (transform, cam.transform);
if (m_IsGrounded || advancedSettings.airControl)
{
// Rotate the rigidbody velocity to match the new direction that the character is looking
Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up);
m_RigidBody.velocity = velRotation*m_RigidBody.velocity;
}
}
/// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom
private void GroundCheck()
{
m_PreviouslyGrounded = m_IsGrounded;
RaycastHit hitInfo;
if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
m_IsGrounded = true;
m_GroundContactNormal = hitInfo.normal;
}
else
{
m_IsGrounded = false;
m_GroundContactNormal = Vector3.up;
}
if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping)
{
m_Jumping = false;
}
}
}
}
| 412 | 0.858803 | 1 | 0.858803 | game-dev | MEDIA | 0.99544 | game-dev | 0.990285 | 1 | 0.990285 |
nexusnode/crafting-dead | 4,114 | crafting-dead-core/src/main/java/com/craftingdead/core/world/item/combatslot/CombatSlot.java | /*
* Crafting Dead
* Copyright (C) 2022 NexusNode LTD
*
* This Non-Commercial Software License Agreement (the "Agreement") is made between
* you (the "Licensee") and NEXUSNODE (BRAD HUNTER). (the "Licensor").
* By installing or otherwise using Crafting Dead (the "Software"), you agree to be
* bound by the terms and conditions of this Agreement as may be revised from time
* to time at Licensor's sole discretion.
*
* If you do not agree to the terms and conditions of this Agreement do not download,
* copy, reproduce or otherwise use any of the source code available online at any time.
*
* https://github.com/nexusnode/crafting-dead/blob/1.18.x/LICENSE.txt
*
* https://craftingdead.net/terms.php
*/
package com.craftingdead.core.world.item.combatslot;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.mojang.serialization.Codec;
import net.minecraft.util.StringRepresentable;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.ItemStack;
public enum CombatSlot implements CombatSlotProvider, StringRepresentable {
PRIMARY("primary", true),
SECONDARY("secondary", true),
MELEE("melee", false),
GRENADE("grenade", false) {
@Override
protected int getAvailableSlot(Inventory playerInventory, boolean ignoreEmpty) {
int index = super.getAvailableSlot(playerInventory, false);
return index == -1 ? 3 : index;
}
},
EXTRA("extra", false);
public static final Codec<CombatSlot> CODEC =
StringRepresentable.fromEnum(CombatSlot::values, CombatSlot::byName);
private static final Map<String, CombatSlot> BY_NAME = Arrays.stream(values())
.collect(Collectors.toMap(CombatSlot::getSerializedName, Function.identity()));
private final String name;
private final boolean dropExistingItems;
private CombatSlot(String name, boolean dropExistingItems) {
this.name = name;
this.dropExistingItems = dropExistingItems;
}
@Override
public String getSerializedName() {
return this.name;
}
@Override
public CombatSlot getCombatSlot() {
return this;
}
protected int getAvailableSlot(Inventory playerInventory, boolean ignoreEmpty) {
for (int i = 0; i < 6; i++) {
if ((ignoreEmpty || playerInventory.getItem(i).isEmpty()) && getSlotType(i) == this) {
return i;
}
}
return -1;
}
public boolean addToInventory(ItemStack itemStack, Inventory playerInventory,
boolean ignoreEmpty) {
int index = this.getAvailableSlot(playerInventory, ignoreEmpty);
if (index == -1) {
return false;
}
if (this.dropExistingItems && !playerInventory.getItem(index).isEmpty()) {
ItemStack oldStack = playerInventory.removeItemNoUpdate(index);
playerInventory.player.drop(oldStack, true, true);
}
playerInventory.setItem(index, itemStack);
return true;
}
public static Optional<CombatSlot> getSlotType(ItemStack itemStack) {
return itemStack.getCapability(CAPABILITY).map(CombatSlotProvider::getCombatSlot);
}
public boolean isItemValid(ItemStack itemStack) {
return itemStack.isEmpty() || getSlotType(itemStack)
.map(this::equals)
.orElse(false);
}
public static boolean isInventoryValid(Inventory inventory) {
for (int i = 0; i < 7; i++) {
if (!CombatSlot
.isItemValidForSlot(inventory.getItem(i), i)) {
return false;
}
}
return true;
}
public static boolean isItemValidForSlot(ItemStack itemStack, int slot) {
return getSlotType(slot).isItemValid(itemStack);
}
public static CombatSlot getSlotType(int slot) {
switch (slot) {
case 0:
return PRIMARY;
case 1:
return SECONDARY;
case 2:
return MELEE;
case 3:
case 4:
case 5:
return GRENADE;
case 6:
return EXTRA;
default:
throw new IllegalArgumentException("Invalid slot");
}
}
public static CombatSlot byName(String name) {
return BY_NAME.get(name);
}
}
| 412 | 0.953113 | 1 | 0.953113 | game-dev | MEDIA | 0.987491 | game-dev | 0.986573 | 1 | 0.986573 |
neuecc/UniRx | 4,351 | Assets/Plugins/UniRx/Scripts/Operators/Where.cs | using System;
namespace UniRx.Operators
{
internal class WhereObservable<T> : OperatorObservableBase<T>
{
readonly IObservable<T> source;
readonly Func<T, bool> predicate;
readonly Func<T, int, bool> predicateWithIndex;
public WhereObservable(IObservable<T> source, Func<T, bool> predicate)
: base(source.IsRequiredSubscribeOnCurrentThread())
{
this.source = source;
this.predicate = predicate;
}
public WhereObservable(IObservable<T> source, Func<T, int, bool> predicateWithIndex)
: base(source.IsRequiredSubscribeOnCurrentThread())
{
this.source = source;
this.predicateWithIndex = predicateWithIndex;
}
// Optimize for .Where().Where()
public IObservable<T> CombinePredicate(Func<T, bool> combinePredicate)
{
if (this.predicate != null)
{
return new WhereObservable<T>(source, x => this.predicate(x) && combinePredicate(x));
}
else
{
return new WhereObservable<T>(this, combinePredicate);
}
}
// Optimize for .Where().Select()
public IObservable<TR> CombineSelector<TR>(Func<T, TR> selector)
{
if (this.predicate != null)
{
return new WhereSelectObservable<T, TR>(source, predicate, selector);
}
else
{
return new SelectObservable<T, TR>(this, selector); // can't combine
}
}
protected override IDisposable SubscribeCore(IObserver<T> observer, IDisposable cancel)
{
if (predicate != null)
{
return source.Subscribe(new Where(this, observer, cancel));
}
else
{
return source.Subscribe(new Where_(this, observer, cancel));
}
}
class Where : OperatorObserverBase<T, T>
{
readonly WhereObservable<T> parent;
public Where(WhereObservable<T> parent, IObserver<T> observer, IDisposable cancel)
: base(observer, cancel)
{
this.parent = parent;
}
public override void OnNext(T value)
{
var isPassed = false;
try
{
isPassed = parent.predicate(value);
}
catch (Exception ex)
{
try { observer.OnError(ex); } finally { Dispose(); }
return;
}
if (isPassed)
{
observer.OnNext(value);
}
}
public override void OnError(Exception error)
{
try { observer.OnError(error); } finally { Dispose(); }
}
public override void OnCompleted()
{
try { observer.OnCompleted(); } finally { Dispose(); }
}
}
class Where_ : OperatorObserverBase<T, T>
{
readonly WhereObservable<T> parent;
int index;
public Where_(WhereObservable<T> parent, IObserver<T> observer, IDisposable cancel)
: base(observer, cancel)
{
this.parent = parent;
this.index = 0;
}
public override void OnNext(T value)
{
var isPassed = false;
try
{
isPassed = parent.predicateWithIndex(value, index++);
}
catch (Exception ex)
{
try { observer.OnError(ex); } finally { Dispose(); }
return;
}
if (isPassed)
{
observer.OnNext(value);
}
}
public override void OnError(Exception error)
{
try { observer.OnError(error); } finally { Dispose(); }
}
public override void OnCompleted()
{
try { observer.OnCompleted(); } finally { Dispose(); }
}
}
}
} | 412 | 0.950471 | 1 | 0.950471 | game-dev | MEDIA | 0.244971 | game-dev | 0.971982 | 1 | 0.971982 |
alexkulya/pandaria_5.4.8 | 20,516 | src/server/scripts/Kalimdor/CavernsOfTime/WellofEternity/boss_queen_azshara.cpp | /*
* This file is part of the Pandaria 5.4.8 Project. See THANKS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptPCH.h"
#include "well_of_eternity.h"
enum ScriptedTexts
{
SAY_AGGRO = 0,
SAY_INTERRUPT = 1,
SAY_END_1 = 2,
SAY_END_2 = 3,
SAY_END_3 = 4,
SAY_WIPE = 5,
SAY_KILL = 6,
SAY_PUPPET = 7,
SAY_ALL = 8,
SAY_ADDS_1 = 9,
SAY_ADDS_2 = 10,
SAY_ADDS_3 = 11,
};
enum Spells
{
SPELL_SERVANT_OF_THE_QUEEN = 102334,
SPELL_TOTAL_OBEDIENCE = 103241,
SPELL_TOTAL_OBEDIENCE_1 = 110096, // ?
// Enchanted Magus
SPELL_ARCANE_SHOCK = 102463,
SPELL_HAMMER_OF_DIVINITY_1 = 102454,
SPELL_HAMMER_OF_DIVINITY_2 = 102454,
SPELL_HAMMER_OF_DIVINITY_DUMMY = 102460,
SPELL_ARCANE_BOMB = 102455,
SPELL_ARCANE_BOMB_DUMMY = 109122,
SPELL_FIREBALL = 102265,
SPELL_FIREBOMB = 102482,
SPELL_BLASTWAVE = 102483,
SPELL_BLADES_OF_ICE = 102467,
SPELL_BLADES_OF_ICE_DMG = 102468,
SPELL_ICE_FLING = 102478,
SPELL_COLDFLAME = 102465,
SPELL_COLDFLAME_DMG = 102466,
SPELL_PUPPET_CROSS = 102310,
SPELL_PUPPET_STRING_HOVER = 102312,
SPELL_PUPPET_STRING_DUMMY_1 = 102315,
SPELL_PUPPET_STRING_DUMMY_2 = 102318,
SPELL_PUPPET_STRING_DUMMY_3 = 102319,
SPELL_PUPPET_STRING_SCRIPT_1 = 102333,
SPELL_PUPPET_STRING_SCRIPT_2 = 102345,
};
enum Adds
{
NPC_HAND_OF_QUEEN = 54728,
NPC_ENCHANTED_MAGUS_ARCANE = 54884,
NPC_ENCHANTED_MAGUS_FIRE = 54882,
NPC_ENCHANTED_MAGUS_FROST = 54883,
NPC_HAMMER_OF_DIVINITY_1 = 54864,
NPC_HAMMER_OF_DIVINITY_2 = 54865,
};
enum Events
{
EVENT_ADDS_1 = 1,
EVENT_ADDS_2 = 2,
EVENT_ADDS_3 = 3,
EVENT_SERVANT_OF_THE_QUEEN = 4,
EVENT_TOTAL_OBEDIENCE = 5,
EVENT_END = 6,
EVENT_ARCANE_SHOCK = 7,
EVENT_ARCANE_BOMB = 8,
EVENT_FIREBALL = 9,
EVENT_FIREBOMB = 10,
EVENT_BLASTWAVE = 11,
EVENT_BLADES_OF_ICE = 12,
EVENT_COLDFLAME = 13,
EVENT_ICE_FLING = 14,
};
enum Actions
{
ACTION_ATTACK = 1,
};
const Position addsPos[6] =
{
{3453.030029f, -5282.740234f, 230.04f, 4.45f}, // fire 1
{3443.540039f, -5280.370117f, 230.04f, 4.66f}, // frost 1
{3461.139893f, -5283.169922f, 230.04f, 4.31f}, // arcane 1
{3435.590088f, -5278.350098f, 230.04f, 4.50f}, // fire 2
{3469.729980f, -5282.430176f, 230.04f, 4.53f}, // frost 2
{3428.43f, -5274.59f, 230.04f, 4.20f} // arcane 2
};
const uint32 addsEntry[6] =
{
NPC_ENCHANTED_MAGUS_FIRE,
NPC_ENCHANTED_MAGUS_FROST,
NPC_ENCHANTED_MAGUS_ARCANE,
NPC_ENCHANTED_MAGUS_FIRE,
NPC_ENCHANTED_MAGUS_FROST,
NPC_ENCHANTED_MAGUS_ARCANE
};
class boss_queen_azshara : public CreatureScript
{
public:
boss_queen_azshara() : CreatureScript("boss_queen_azshara") { }
struct boss_queen_azsharaAI : public BossAI
{
boss_queen_azsharaAI(Creature* creature) : BossAI(creature, DATA_AZSHARA)
{
me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_STUN, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_FEAR, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_ROOT, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_FREEZE, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_HORROR, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_SAPPED, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_CHARM, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, true);
me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_CONFUSE, true);
}
void Reset() override
{
_Reset();
memset(addsGUIDs, 0, sizeof(addsGUIDs));
for (uint8 i = 0; i < 6; ++i)
if (Creature* pAdd = me->SummonCreature(addsEntry[i], addsPos[i], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 5000))
addsGUIDs[i] = pAdd->GetGUID();
addsCount = 0;
}
void EnterCombat(Unit* /*who*/) override
{
Talk(SAY_AGGRO);
addsCount = 0;
events.RescheduleEvent(EVENT_ADDS_1, 11000);
DoZoneInCombat();
instance->SetBossState(DATA_AZSHARA, IN_PROGRESS);
}
void JustReachedHome() override
{
Talk(SAY_WIPE);
addsCount = 0;
}
void AttackStart(Unit* target) override
{
if (target)
me->Attack(target, false);
}
void KilledUnit(Unit* victim) override
{
if (victim && victim->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_KILL);
}
void SpellHit(Unit* /*caster*/, const SpellInfo* spellInfo) override
{
if (Spell* spell = me->GetCurrentSpell(CURRENT_GENERIC_SPELL))
if (spellInfo->HasEffect(SPELL_EFFECT_INTERRUPT_CAST))
{
me->InterruptSpell(CURRENT_GENERIC_SPELL);
Talk(SAY_INTERRUPT);
}
}
void DamageTaken(Unit* attacker, uint32& damage) override
{
damage = 0;
me->UpdateUInt32Value(UNIT_FIELD_HEALTH, me->GetMaxHealth());
}
void SummonedCreatureDies(Creature* summon, Unit* /*killer*/) override
{
if (!me->IsInCombat())
return;
if (summon->GetEntry() == NPC_ENCHANTED_MAGUS_FIRE ||
summon->GetEntry() == NPC_ENCHANTED_MAGUS_ARCANE ||
summon->GetEntry() == NPC_ENCHANTED_MAGUS_FROST)
addsCount++;
if ((addsCount == 2) || (addsCount == 4))
events.ScheduleEvent(EVENT_ADDS_1, 6000);
else if (addsCount == 6)
{
events.Reset();
me->InterruptNonMeleeSpells(false);
Talk(SAY_END_1);
events.ScheduleEvent(EVENT_END, 6000);
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
if (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_TOTAL_OBEDIENCE:
Talk(SAY_ALL);
DoCastAOE(SPELL_TOTAL_OBEDIENCE);
break;
case EVENT_ADDS_1:
Talk((addsCount / 2) + 9);
events.RescheduleEvent(EVENT_ADDS_2, 7000);
break;
case EVENT_ADDS_2:
if (Creature* pAdd = ObjectAccessor::GetCreature(*me, addsGUIDs[addsCount]))
pAdd->AI()->Talk(addsCount / 2);
events.RescheduleEvent(EVENT_ADDS_3, 6000);
break;
case EVENT_ADDS_3:
for (uint8 i = addsCount; i < (addsCount + 2); ++i)
{
if (Creature* pAdd = ObjectAccessor::GetCreature(*me, addsGUIDs[i]))
{
pAdd->SetReactState(REACT_AGGRESSIVE);
pAdd->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
DoZoneInCombat(pAdd);
pAdd->AI()->DoAction(ACTION_ATTACK);
}
}
events.ScheduleEvent(EVENT_TOTAL_OBEDIENCE, urand(10000, 20000));
break;
case EVENT_END:
{
instance->DoKilledMonsterKredit(QUEST_THE_VAINGLORIOUS, 54853, 0);
instance->SetBossState(DATA_AZSHARA, DONE);
instance->DoRespawnGameObject(instance->GetData64(DATA_ROYAL_CACHE), DAY);
instance->DoModifyPlayerCurrencies(CURRENCY_TYPE_JUSTICE_POINTS, 7000);
me->DespawnOrUnsummon();
break;
}
default:
break;
}
}
}
private:
EventMap events;
uint8 phase;
uint64 addsGUIDs[6];
uint8 addsCount;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_queen_azsharaAI>(creature);
}
};
class npc_queen_azshara_enchanted_magus : public CreatureScript
{
public:
npc_queen_azshara_enchanted_magus() : CreatureScript("npc_queen_azshara_enchanted_magus") { }
struct npc_queen_azshara_enchanted_magusAI : public ScriptedAI
{
npc_queen_azshara_enchanted_magusAI(Creature* creature) : ScriptedAI(creature) { }
void Reset() override
{
events.Reset();
me->SetReactState(REACT_PASSIVE);
}
void DoAction(int32 action) override
{
if (action == ACTION_ATTACK)
{
if (me->GetEntry() == NPC_ENCHANTED_MAGUS_FIRE)
{
events.ScheduleEvent(EVENT_FIREBALL, 1000);
events.ScheduleEvent(EVENT_FIREBOMB, urand(10000, 15000));
events.ScheduleEvent(EVENT_BLASTWAVE, urand(10000, 20000));
}
else if (me->GetEntry() == NPC_ENCHANTED_MAGUS_FROST)
{
events.ScheduleEvent(EVENT_BLADES_OF_ICE, urand(5000, 10000));
events.ScheduleEvent(EVENT_COLDFLAME, urand(12000, 20000));
events.ScheduleEvent(EVENT_ICE_FLING, urand(2000, 15000));
}
else if (me->GetEntry() == NPC_ENCHANTED_MAGUS_ARCANE)
{
events.ScheduleEvent(EVENT_ARCANE_SHOCK, urand(10000, 15000));
events.ScheduleEvent(EVENT_ARCANE_BOMB, urand(5000, 10000));
}
}
}
/*void MovementInform(uint32 type, uint32 pointId) override
{
if (me->GetEntry() == NPC_ENCHANTED_MAGUS_FROST && data == EVENT_CHARGE)
if (Player* player = me->SelectNearestPlayer(5.0f))
DoCast(player, SPELL_BLADES_OF_ICE_DMG, true);
}*/
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
if (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FIREBALL:
DoCastVictim(SPELL_FIREBALL);
events.ScheduleEvent(EVENT_FIREBALL, 3000);
break;
case EVENT_FIREBOMB:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true))
DoCast(target, SPELL_FIREBOMB);
events.ScheduleEvent(EVENT_FIREBOMB, urand(15000, 20000));
break;
case EVENT_BLASTWAVE:
DoCastAOE(SPELL_BLASTWAVE);
events.ScheduleEvent(EVENT_BLASTWAVE, urand(15000, 20000));
break;
case EVENT_ICE_FLING:
DoCastAOE(SPELL_ICE_FLING);
events.ScheduleEvent(EVENT_ICE_FLING, urand(10000, 20000));
break;
case EVENT_BLADES_OF_ICE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true))
DoCast(target, SPELL_BLADES_OF_ICE);
events.ScheduleEvent(EVENT_BLADES_OF_ICE, urand(12000, 20000));
break;
case EVENT_COLDFLAME:
//if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true))
//DoCast(target, SPELL_COLDFLAME);
events.ScheduleEvent(EVENT_COLDFLAME, urand(16000, 25000));
break;
case EVENT_ARCANE_SHOCK:
me->StopMoving();
DoCast(me, SPELL_ARCANE_SHOCK);
events.ScheduleEvent(EVENT_ARCANE_SHOCK, urand(12000, 20000));
break;
case EVENT_ARCANE_BOMB:
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true))
{
Creature* pStalker1 = me->SummonCreature(NPC_HAMMER_OF_DIVINITY_2, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation(), TEMPSUMMON_TIMED_DESPAWN, 20000);
Creature* pStalker2 = me->SummonCreature(NPC_HAMMER_OF_DIVINITY_1, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ() + 30.0f, target->GetOrientation(), TEMPSUMMON_TIMED_DESPAWN, 20000);
if (pStalker1 && pStalker2)
pStalker2->GetMotionMaster()->MovePoint(0, pStalker1->GetPositionX(), pStalker1->GetPositionY(), pStalker1->GetPositionZ());
}
events.ScheduleEvent(EVENT_ARCANE_BOMB, urand(18000, 25000));
break;
}
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
EventMap events;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_queen_azshara_enchanted_magusAI>(creature);
}
};
class npc_queen_azshara_hammer_of_divinity : public CreatureScript
{
public:
npc_queen_azshara_hammer_of_divinity() : CreatureScript("npc_queen_azshara_hammer_of_divinity") { }
struct npc_queen_azshara_hammer_of_divinityAI : public ScriptedAI
{
npc_queen_azshara_hammer_of_divinityAI(Creature* creature) : ScriptedAI(creature)
{
bDespawn = false;
me->SetSpeed(MOVE_RUN, 0.1f, true);
me->SetCanFly(true);
me->SetDisableGravity(true);
SetCombatMovement(false);
}
void UpdateAI(uint32 /*diff*/) override
{
if (bDespawn)
return;
if (Creature* pStalker = me->FindNearestCreature(NPC_HAMMER_OF_DIVINITY_2, 1.0f))
{
bDespawn = true;
DoCastAOE(SPELL_ARCANE_BOMB);
pStalker->DespawnOrUnsummon(500);
me->DespawnOrUnsummon(500);
}
}
private:
bool bDespawn;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_queen_azshara_hammer_of_divinityAI>(creature);
}
};
class spell_queen_azshara_coldflame : public SpellScriptLoader
{
public:
spell_queen_azshara_coldflame() : SpellScriptLoader("spell_queen_azshara_coldflame") { }
class spell_queen_azshara_coldflame_AuraScript : public AuraScript
{
PrepareAuraScript(spell_queen_azshara_coldflame_AuraScript);
bool Load() override
{
count = 0;
return true;
}
void PeriodicTick(AuraEffect const* /*aurEff*/)
{
if (!GetCaster())
return;
count++;
if (count > 11)
{
GetCaster()->RemoveAura(SPELL_COLDFLAME);
return;
}
Position pos;
GetCaster()->GetNearPosition(pos, 3.0f * (count / 2), 0.0f);
GetCaster()->CastSpell(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), SPELL_COLDFLAME_DMG, true);
}
void Register() override
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_queen_azshara_coldflame_AuraScript::PeriodicTick, EFFECT_1, SPELL_AURA_PERIODIC_DUMMY);
}
private:
uint8 count;
};
AuraScript* GetAuraScript() const override
{
return new spell_queen_azshara_coldflame_AuraScript();
}
};
class spell_queen_azshara_arcane_bomb : public SpellScriptLoader
{
public:
spell_queen_azshara_arcane_bomb() : SpellScriptLoader("spell_queen_azshara_arcane_bomb") { }
class spell_queen_azshara_arcane_bomb_SpellScript : public SpellScript
{
PrepareSpellScript(spell_queen_azshara_arcane_bomb_SpellScript);
void ChangeSummonPos(SpellEffIndex /*effIndex*/)
{
WorldLocation summonPos = *GetExplTargetDest();
Position offset = {0.0f, 0.0f, 15.0f, 0.0f};
summonPos.RelocateOffset(offset);
SetExplTargetDest(summonPos);
GetHitDest()->RelocateOffset(offset);
}
void Register() override
{
OnEffectHit += SpellEffectFn(spell_queen_azshara_arcane_bomb_SpellScript::ChangeSummonPos, EFFECT_0, SPELL_EFFECT_SUMMON);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_queen_azshara_arcane_bomb_SpellScript();
}
};
void AddSC_boss_queen_azshara()
{
new boss_queen_azshara();
new npc_queen_azshara_enchanted_magus();
new npc_queen_azshara_hammer_of_divinity();
new spell_queen_azshara_coldflame();
//new spell_queen_azshara_arcane_bomb();
}
| 412 | 0.940109 | 1 | 0.940109 | game-dev | MEDIA | 0.970518 | game-dev | 0.933542 | 1 | 0.933542 |
oculus-samples/Unity-Decommissioned | 6,847 | Assets/Samples/Meta Avatars SDK/35.2.0/Sample Scenes/Scripts/LODGallery/LODGallerySceneSpawner.cs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* Licensed under the Oculus SDK License Agreement (the "License");
* you may not use the Oculus SDK except in compliance with the License,
* which is provided at the time of installation or download, or which
* otherwise accompanies this software in either electronic or hard copy form.
*
* You may obtain a copy of the License at
*
* https://developer.oculus.com/licenses/oculussdk/
*
* Unless required by applicable law or agreed to in writing, the Oculus SDK
* 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.
*/
#nullable enable
using UnityEngine;
using Oculus.Avatar2;
using UnityEngine.Serialization;
using System.Collections;
using UnityEngine.XR;
[RequireComponent(typeof(LODGallerySceneOrganizer))]
public class LODGallerySceneSpawner : MonoBehaviour
{
private GameObject[][]? _containers;
private const string LOG_SCOPE = "LODGalleryScene";
private static LODGallerySceneSpawner? s_instance;
private const float DELAY_BETWEEN_SPAWNS = 0.5f;
[Header("Tracking Input")]
[SerializeField]
[FormerlySerializedAs("_bodyTracking")]
private OvrAvatarInputManagerBehavior? _inputManager;
[FormerlySerializedAs("_faceTrackingBehavior")]
[SerializeField]
private OvrAvatarFacePoseBehavior? _facePoseBehavior;
[FormerlySerializedAs("_eyeTrackingBehavior")]
[SerializeField]
private OvrAvatarEyePoseBehavior? _eyePoseBehavior;
[SerializeField]
private OvrAvatarLipSyncBehavior? _lipSync;
[SerializeField]
private bool _displayLODLabels = true;
[SerializeField]
private GameObject? labelPrefab;
[SerializeField]
private Vector3 lodLabelOffset = new Vector3(0.4f, 0, 0);
public static LODGallerySceneSpawner? Instance => s_instance;
private void Awake()
{
if (s_instance != null && s_instance != this)
{
Destroy(gameObject);
}
else
{
s_instance = this;
}
}
private void Start()
{
_containers = GetComponent<LODGallerySceneOrganizer>().GetArrangedGameObjects();
StartSpawning();
}
private void StartSpawning()
{
StartCoroutine(PopulateAvatarsOfType(0, LODGalleryUtils.LODGalleryAvatarType.Standard));
StartCoroutine(PopulateAvatarsOfType(1, LODGalleryUtils.LODGalleryAvatarType.Light));
StartCoroutine(PopulateAvatarsOfType(2, LODGalleryUtils.LODGalleryAvatarType.UltraLight));
}
private IEnumerator PopulateAvatarsOfType(int row, LODGalleryUtils.LODGalleryAvatarType avatarType)
{
if (_containers is not null)
{
for (int lodLevel = 0; lodLevel < 5; lodLevel++)
{
GameObject currentContainer = _containers[row][lodLevel];
OvrAvatarEntity? entity = null;
switch (avatarType)
{
case LODGalleryUtils.LODGalleryAvatarType.UltraLight:
// TODO: T192538677
// if (lodLevel == 2 || lodLevel == 4)
// {
// currentContainer = _containers[row][lodLevel == 2 ? 0 : 1];
// entity = currentContainer.AddComponent<LODGallerySceneFastLoadAvatarEntity>();
// currentContainer.name = $"UltraLight Avatar LOD {lodLevel}";
// }
break;
case LODGalleryUtils.LODGalleryAvatarType.Light:
entity = currentContainer.AddComponent<LODGallerySceneAvatarEntity>();
currentContainer.name = $"Light Avatar LOD {lodLevel}";
break;
case LODGalleryUtils.LODGalleryAvatarType.Standard:
entity = currentContainer.AddComponent<LODGallerySceneHQAvatarEntity>();
currentContainer.name = $"Standard Avatar LOD {lodLevel}";
break;
default:
OvrAvatarLog.LogWarning("Invalid Avatar type.");
yield break;
}
if (entity != null)
{
AddTrackingInputs(entity);
AlignAvatarEntityOrientation(entity);
SetAvatarLODLevel(entity, lodLevel);
if (_displayLODLabels)
{
AlignLODLabels(entity, lodLevel);
}
}
OvrAvatarLog.LogInfo("LODGallerySceneSpawner spawned " + currentContainer.name, LOG_SCOPE, this);
yield return new WaitForSeconds(DELAY_BETWEEN_SPAWNS);
}
}
else
{
OvrAvatarLog.LogError("No container found");
yield return new WaitForSeconds(DELAY_BETWEEN_SPAWNS);
}
}
private void AddTrackingInputs(OvrAvatarEntity entity)
{
entity.SetInputManager(_inputManager);
entity.SetFacePoseProvider(_facePoseBehavior);
entity.SetEyePoseProvider(_eyePoseBehavior);
entity.SetLipSync(_lipSync);
}
private void SetAvatarLODLevel(OvrAvatarEntity entity, int lodLevel)
{
entity.AvatarLOD.overrideLOD = true;
entity.AvatarLOD.overrideLevel = lodLevel;
}
private void AlignLODLabels(OvrAvatarEntity entity, int lodLevel)
{
// add label prefab
if (labelPrefab is null)
{
OvrAvatarLog.LogError("Failed to align LOD labels, no label prefab found");
return;
}
GameObject label = Instantiate(labelPrefab, entity.gameObject.transform);
label.transform.localPosition = Vector3.up + lodLabelOffset;
if (OvrAvatarUtility.IsHeadsetActive())
{
// fix label text rotation in headset
label.transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
}
else
{
label.transform.localRotation = Quaternion.identity;
}
TextMesh textMesh = label.GetComponent<TextMesh>();
if (textMesh)
{
textMesh.text = lodLevel.ToString();
}
}
// Rotate avatars 180 degrees if in editor (and not PC VR),
// so that avatars are facing the correct direction.
private void AlignAvatarEntityOrientation(OvrAvatarEntity entity)
{
#if UNITY_EDITOR
if (XRSettings.loadedDeviceName != "oculus display")
{
entity.transform.Rotate(Vector3.up, 180f);
}
#endif
}
}
| 412 | 0.871097 | 1 | 0.871097 | game-dev | MEDIA | 0.868658 | game-dev,graphics-rendering | 0.974179 | 1 | 0.974179 |
jorya/raw-os | 3,283 | extension/rf/active_memory.c | /*
raw os - Copyright (C) Lingjun Chen(jorya_txj).
This file is part of raw os.
raw os is free software; you can redistribute it 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.
raw os 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 Lesser General Public License
along with this program. if not, write email to jorya.txj@gmail.com
---
A special exception to the LGPL can be applied should you wish to distribute
a combined work that includes raw os, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/* 2012-9 Created by jorya_txj
* xxxxxx please added here
*/
#include <raw_api.h>
#include <rf/rf_config.h>
#include <rf/active_object.h>
#include <rf/active_time_event.h>
#include <rf/active_memory.h>
#include <rf/active_queue_broadcast.h>
/*
************************************************************************************************************************
* Allocate an event from pool
*
* Description: This function is called to allocate an event block from pool
*
* Arguments :pool is the address of memory block pool
* ---------
* sig is the event sig
*
* Returns
*
* Note(s)
*
*
************************************************************************************************************************
*/
void *active_event_memory_allocate(MEM_POOL *pool, RAW_U16 sig)
{
STATE_EVENT *event;
RAW_OS_ERROR ret;
ret = raw_block_allocate(pool, (void **)&event);
if (ret != RAW_SUCCESS) {
RAW_ASSERT(0);
}
event->sig = sig;
event->which_pool = pool;
event->ref_count = 0;
return (void *)event;
}
/*
************************************************************************************************************************
* Collect an event from pool
*
* Description: This function is Collect an event from pool
*
* Arguments :event is the event whichto be collected.
* ---------
*
*
* Returns
*
* Note(s) This is the internal function and should not be called by users.
*
*
************************************************************************************************************************
*/
void active_memory_collect(STATE_EVENT *event)
{
RAW_OS_ERROR ret;
RAW_SR_ALLOC();
if (event->which_pool) {
RAW_CPU_DISABLE();
if (event->ref_count > 1) {
event->ref_count--;
RAW_CPU_ENABLE();
}
else {
RAW_CPU_ENABLE();
RAW_ASSERT(event->ref_count == 1);
ret = raw_block_release(event->which_pool, event);
if (ret != RAW_SUCCESS) {
RAW_ASSERT(0);
}
}
}
}
| 412 | 0.803315 | 1 | 0.803315 | game-dev | MEDIA | 0.228571 | game-dev | 0.620814 | 1 | 0.620814 |
TwelveIterationMods/CookingForBlockheads | 12,556 | common/src/main/java/net/blay09/mods/cookingforblockheads/block/ModBlocks.java | package net.blay09.mods.cookingforblockheads.block;
import net.blay09.mods.balm.api.block.BalmBlocks;
import net.blay09.mods.cookingforblockheads.CookingForBlockheads;
import net.blay09.mods.cookingforblockheads.component.ModComponents;
import net.blay09.mods.cookingforblockheads.component.MultiblockKitchenComponent;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockBehaviour;
public class ModBlocks {
public static CookingTableBlock[] dyedCookingTables = new CookingTableBlock[DyeColor.values().length];
public static CounterBlock[] dyedCounters = new CounterBlock[DyeColor.values().length];
public static CabinetBlock[] dyedCabinets = new CabinetBlock[DyeColor.values().length];
public static OvenBlock[] ovens = new OvenBlock[DyeColor.values().length];
public static CookingTableBlock cookingTable;
public static Block toolRack;
public static Block toaster;
public static Block milkJar;
public static Block cowJar;
public static Block spiceRack;
public static Block fruitBasket;
public static Block cuttingBoard;
public static FridgeBlock[] fridges = new FridgeBlock[DyeColor.values().length];
public static SinkBlock sink;
public static SinkBlock[] dyedSinks = new SinkBlock[DyeColor.values().length];
public static CounterBlock counter;
public static CabinetBlock cabinet;
public static Block connector;
public static DyedConnectorBlock[] dyedConnectors = new DyedConnectorBlock[DyeColor.values().length];
public static Block[] kitchenFloors = new Block[DyeColor.values().length];
public static void initialize(BalmBlocks blocks) {
blocks.register((identifier) -> toolRack = new ToolRackBlock(blockProperties(identifier)), (block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.tool_rack.description")))), id("tool_rack"));
blocks.register((identifier) -> toaster = new ToasterBlock(blockProperties(identifier)), (block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.toaster.description")))), id("toaster"));
blocks.register((identifier) -> milkJar = new MilkJarBlock(blockProperties(identifier)), (block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.milk_jar.description")))), id("milk_jar"));
blocks.register((identifier) -> cowJar = new CowJarBlock(blockProperties(identifier)), (block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.cow_jar.description")))), id("cow_jar"));
blocks.register((identifier) -> spiceRack = new SpiceRackBlock(blockProperties(identifier)), (block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.spice_rack.description")))), id("spice_rack"));
blocks.register((identifier) -> fruitBasket = new FruitBasketBlock(blockProperties(identifier)), (block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.fruit_basket.description")))),
id("fruit_basket"));
blocks.register((identifier) -> cuttingBoard = new CuttingBoardBlock(blockProperties(identifier)), (block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.cutting_board.description")))), id("cutting_board"));
DyeColor[] colors = DyeColor.values();
kitchenFloors = new Block[colors.length];
ovens = new OvenBlock[colors.length];
dyedCookingTables = new CookingTableBlock[colors.length];
dyedConnectors = new DyedConnectorBlock[colors.length];
for (final var color : colors) {
final var colorPrefix = color.getSerializedName() + "_";
blocks.register((identifier) -> ovens[color.ordinal()] = new OvenBlock(color, blockProperties(identifier)),
(block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.oven.description")))),
id(colorPrefix + "oven"));
}
for (final var color : colors) {
final var colorPrefix = color.getSerializedName() + "_";
blocks.register((identifier) -> fridges[color.ordinal()] = new FridgeBlock(color, blockProperties(identifier)),
(block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.fridge.description")))),
id(colorPrefix + "fridge"));
}
blocks.register((identifier) -> connector = new ConnectorBlock(blockProperties(identifier)), (block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.connector.description")))), id("connector"));
for (final var color : colors) {
final var colorPrefix = color.getSerializedName() + "_";
blocks.register((identifier) -> dyedConnectors[color.ordinal()] = new DyedConnectorBlock(color, blockProperties(identifier)),
(block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.connector.description")))),
id(colorPrefix + "connector"));
}
for (final var color : colors) {
final var colorPrefix = color.getSerializedName() + "_";
blocks.register((identifier) -> kitchenFloors[color.ordinal()] = new KitchenFloorBlock(blockProperties(identifier)),
(block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.kitchen_floor.description")))),
id(colorPrefix + "kitchen_floor"));
}
blocks.register((identifier) -> cookingTable = new CookingTableBlock(null, blockProperties(identifier)), (block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.cooking_table.description")))), id("cooking_table"));
for (final var color : colors) {
final var colorPrefix = color.getSerializedName() + "_";
blocks.register((identifier) -> dyedCookingTables[color.ordinal()] = new CookingTableBlock(color, blockProperties(identifier)),
(block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.cooking_table.description")))),
id(colorPrefix + "cooking_table"));
}
blocks.register((identifier) -> counter = new CounterBlock(null, blockProperties(identifier)), (block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.counter.description")))),
id("counter"));
for (final var color : colors) {
final var colorPrefix = color.getSerializedName() + "_";
blocks.register((identifier) -> dyedCounters[color.ordinal()] = new CounterBlock(color, blockProperties(identifier)),
(block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.counter.description")))),
id(colorPrefix + "counter"));
}
blocks.register((identifier) -> cabinet = new CabinetBlock(null, blockProperties(identifier)), (block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.cabinet.description")))), id("cabinet"));
for (final var color : colors) {
final var colorPrefix = color.getSerializedName() + "_";
blocks.register((identifier) -> dyedCabinets[color.ordinal()] = new CabinetBlock(color, blockProperties(identifier)),
(block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.cabinet.description")))),
id(colorPrefix + "cabinet"));
}
blocks.register((identifier) -> sink = new SinkBlock(null, blockProperties(identifier)), (block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.sink.description")))), id("sink"));
for (final var color : colors) {
final var colorPrefix = color.getSerializedName() + "_";
blocks.register((identifier) -> dyedSinks[color.ordinal()] = new SinkBlock(color, blockProperties(identifier)),
(block, id) -> new BlockItem(block, itemProperties(id)
.component(ModComponents.multiblockKitchen.get(),
new MultiblockKitchenComponent(Component.translatable("tooltip.cookingforblockheads.sink.description")))),
id(colorPrefix + "sink"));
}
}
private static BlockBehaviour.Properties blockProperties(ResourceLocation identifier) {
return BlockBehaviour.Properties.of().setId(blockId(identifier));
}
private static Item.Properties itemProperties(ResourceLocation identifier) {
return new Item.Properties().setId(itemId(identifier));
}
private static ResourceKey<Block> blockId(ResourceLocation identifier) {
return ResourceKey.create(Registries.BLOCK, identifier);
}
private static ResourceKey<Item> itemId(ResourceLocation identifier) {
return ResourceKey.create(Registries.ITEM, identifier);
}
private static BlockItem itemBlock(Block block, ResourceLocation identifier) {
return new BlockItem(block, itemProperties(identifier));
}
private static ResourceLocation id(String name) {
return ResourceLocation.fromNamespaceAndPath(CookingForBlockheads.MOD_ID, name);
}
}
| 412 | 0.85245 | 1 | 0.85245 | game-dev | MEDIA | 0.975796 | game-dev | 0.786991 | 1 | 0.786991 |
Geant4/geant4 | 14,966 | source/processes/hadronic/models/inclxx/utils/src/G4INCLParticleSpecies.cc | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// INCL++ intra-nuclear cascade model
// Alain Boudard, CEA-Saclay, France
// Joseph Cugnon, University of Liege, Belgium
// Jean-Christophe David, CEA-Saclay, France
// Pekka Kaitaniemi, CEA-Saclay, France, and Helsinki Institute of Physics, Finland
// Sylvie Leray, CEA-Saclay, France
// Davide Mancusi, CEA-Saclay, France
//
#define INCLXX_IN_GEANT4_MODE 1
#include "globals.hh"
/*
* G4INCLParticleSpecies.cc
*
* \date Nov 25, 2011
* \author Davide Mancusi
*/
#include "G4INCLParticleSpecies.hh"
#include "G4INCLParticleTable.hh"
#include <algorithm>
#include <cctype>
#include <sstream>
#include <algorithm>
namespace G4INCL {
ParticleSpecies::ParticleSpecies(std::string const &pS) {
// Normalise the string to lower case
if(pS=="p" || pS=="proton") {
theA = 1;
theZ = 1;
theS = 0;
theType = G4INCL::Proton;
} else if(pS=="n" || pS=="neutron") {
theA = 1;
theZ = 0;
theS = 0;
theType = G4INCL::Neutron;
} else if(pS=="delta++" || pS=="deltaplusplus") {
theA = 1;
theZ = 2;
theS = 0;
theType = G4INCL::DeltaPlusPlus;
} else if(pS=="delta+" || pS=="deltaplus") {
theA = 1;
theZ = 1;
theS = 0;
theType = G4INCL::DeltaPlus;
} else if(pS=="delta0" || pS=="deltazero") {
theA = 1;
theZ = 0;
theS = 0;
theType = G4INCL::DeltaZero;
} else if(pS=="delta-" || pS=="deltaminus") {
theA = 1;
theZ = -1;
theS = 0;
theType = G4INCL::DeltaMinus;
} else if(pS=="pi+" || pS=="pion+" || pS=="piplus" || pS=="pionplus") {
theA = 0;
theZ = 1;
theS = 0;
theType = G4INCL::PiPlus;
} else if(pS=="pi0" || pS=="pion0" || pS=="pizero" || pS=="pionzero") {
theA = 0;
theZ = 0;
theS = 0;
theType = G4INCL::PiZero;
} else if(pS=="pi-" || pS=="pion-" || pS=="piminus" || pS=="pionminus") {
theA = 0;
theZ = -1;
theS = 0;
theType = G4INCL::PiMinus;
} else if(pS=="lambda" || pS=="l" || pS=="l0") {
theA = 1;
theZ = 0;
theS = -1;
theType = G4INCL::Lambda;
} else if(pS=="s+" || pS=="sigma+" || pS=="sigmaplus") {
theA = 1;
theZ = 1;
theS = -1;
theType = G4INCL::SigmaPlus;
} else if(pS=="s0" || pS=="sigma0" || pS=="sigmazero") {
theA = 1;
theZ = 0;
theS = -1;
theType = G4INCL::SigmaZero;
} else if(pS=="s-" || pS=="sigma-" || pS=="sigmaminus") { //Sm = Samarium
theA = 1;
theZ = -1;
theS = -1;
theType = G4INCL::SigmaMinus;
} else if(pS=="xi-" || pS=="x-") {
theA = 1;
theZ = -1;
theS = -2;
theType = G4INCL::XiMinus;
} else if(pS=="xi0" || pS=="x0") {
theA = 1;
theZ = 0;
theS = -2;
theType = G4INCL::XiZero;
} else if(pS=="pb" || pS=="antiproton") {
theA = -1;
theZ = -1;
theS = 0;
theType = G4INCL::antiProton;
} else if(pS=="nb" || pS=="antineutron") {
theA = -1;
theZ = 0;
theS = 0;
theType = G4INCL::antiNeutron;
} else if(pS=="s+b" || pS=="antisigma+" || pS=="antisigmaplus") {
theA = -1;
theZ = -1;
theS = 1;
theType = G4INCL::antiSigmaPlus;
} else if(pS=="s0b" || pS=="antisigma0" || pS=="antisigmazero") {
theA = -1;
theZ = 0;
theS = 1;
theType = G4INCL::antiSigmaZero;
} else if(pS=="s-b" || pS=="antisigma-" || pS=="antisigmaminus") { //Sm = Samarium; Whats wrong with the sign?
theA = -1;
theZ = 1;
theS = 1;
theType = G4INCL::antiSigmaMinus;
} else if(pS=="antilambda" || pS=="lb" || pS=="l0b") {
theA = -1;
theZ = 0;
theS = 1;
theType = G4INCL::antiLambda;
} else if(pS=="antixi-" || pS=="x-b") {
theA = -1;
theZ = 1;
theS = 2;
theType = G4INCL::antiXiMinus;
} else if(pS=="antixi0" || pS=="x0b") {
theA = -1;
theZ = 0;
theS = 2;
theType = G4INCL::antiXiZero;
} else if(pS=="k+" || pS=="kaon+" || pS=="kplus" || pS=="kaonplus") {
theA = 0;
theZ = 1;
theS = 1;
theType = G4INCL::KPlus;
} else if(pS=="k0" || pS=="kaon0" || pS=="kzero" || pS=="kaonzero") {
theA = 0;
theZ = 0;
theS = 1;
theType = G4INCL::KZero;
} else if(pS=="k0b" || pS=="kzb" || pS=="kaon0bar" || pS=="kzerobar" || pS=="kaonzerobar") {
theA = 0;
theZ = 0;
theS = -1;
theType = G4INCL::KZeroBar;
} else if(pS=="k-" || pS=="kaon-" || pS=="kminus" || pS=="kaonminus") {
theA = 0;
theZ = -1;
theS = -1;
theType = G4INCL::KMinus;
} else if(pS=="k0s" || pS=="kshort" || pS=="ks" || pS=="kaonshort") {
theA = 0;
theZ = 0;
// theS not defined
theType = G4INCL::KShort;
} else if(pS=="k0l" || pS=="klong" || pS=="kl" || pS=="kaonlong") {
theA = 0;
theZ = 0;
// theS not defined
theType = G4INCL::KLong;
} else if(pS=="d" || pS=="deuteron") {
theA = 2;
theZ = 1;
theS = 0;
theType = G4INCL::Composite;
} else if(pS=="t" || pS=="triton") {
theA = 3;
theZ = 1;
theS = 0;
theType = G4INCL::Composite;
} else if(pS=="a" || pS=="alpha") {
theA = 4;
theZ = 2;
theS = 0;
theType = G4INCL::Composite;
} else if(pS=="eta") {
theA = 0;
theZ = 0;
theS = 0;
theType = G4INCL::Eta;
} else if(pS=="omega") {
theA = 0;
theZ = 0;
theS = 0;
theType = G4INCL::Omega;
} else if(pS=="etaprime" || pS=="etap") {
theA = 0;
theZ = 0;
theS = 0;
theType = G4INCL::EtaPrime;
} else if(pS=="photon") {
theA = 0;
theZ = 0;
theS = 0;
theType = G4INCL::Photon;
} else
parseNuclide(pS);
}
ParticleSpecies::ParticleSpecies(ParticleType const t) :
theType(t),
theA(ParticleTable::getMassNumber(theType)),
theZ(ParticleTable::getChargeNumber(theType)),
theS(ParticleTable::getStrangenessNumber(theType))
{}
ParticleSpecies::ParticleSpecies(const G4int A, const G4int Z) :
theType(Composite),
theA(A),
theZ(Z),
theS(0)
{}
ParticleSpecies::ParticleSpecies(const G4int A, const G4int Z, const G4int S) :
theType(Composite),
theA(A),
theZ(Z),
theS(S)
{}
void ParticleSpecies::parseNuclide(std::string const &pS) {
theType = Composite;
theS = 0; // no hypernuclei projectile or target for now
// Allowed characters
const std::string separators("-_");
std::string allowed("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
allowed += separators;
// There must be at least one character
if(pS.find_first_not_of(allowed)!=std::string::npos) {
// Malformed input string
// Setting unknown particle species
(*this) = ParticleSpecies(UnknownParticle);
return;
}
if(pS.size()<1) {
// Malformed input string
// Setting unknown particle species
(*this) = ParticleSpecies(UnknownParticle);
return;
}
std::size_t firstSeparator = pS.find_first_of(separators);
std::size_t lastSeparator = pS.find_last_of(separators);
if(firstSeparator!=std::string::npos && firstSeparator!=lastSeparator) {
// Several separators in malformed input string
// Setting unknown particle species
(*this) = ParticleSpecies(UnknownParticle);
return;
}
// Identify the type of the first character
G4int (*predicate)(G4int);
G4bool startsWithAlpha = std::isalpha(pS.at(0));
if(startsWithAlpha) {
predicate=std::isdigit;
} else if(std::isdigit(pS.at(0))) {
predicate=std::isalpha;
} else {
// Non-alphanumeric character in string
// Setting unknown particle species
(*this) = ParticleSpecies(UnknownParticle);
return;
}
G4bool hasIsotope = true;
size_t endFirstSection, beginSecondSection;
if(firstSeparator==std::string::npos) {
// No separator, Fe56 or 56Fe style
// Identify the end of the first section
// Find the first character that is not of the same type as the first one
beginSecondSection = std::find_if(pS.begin()+1, pS.end(), predicate) - pS.begin();
if(beginSecondSection>=pS.size()) {
if(startsWithAlpha) {
// Only alphabetic characters are present -- must be an element name
hasIsotope = false;
} else {
// Only numeric characters in the string
// Setting unknown particle species
(*this) = ParticleSpecies(UnknownParticle);
return;
}
}
endFirstSection = beginSecondSection;
} else {
// One separator, Fe-56 or 56-Fe style or hypercluster style: Fe56-1 (iron 56 including 1 lambda)
endFirstSection = firstSeparator;
beginSecondSection = firstSeparator+1;
}
std::string firstSection(pS.substr(0,endFirstSection));
std::string secondSection(pS.substr(beginSecondSection,std::string::npos));
std::stringstream parsingStream;
if(std::isalpha(firstSection.at(0)) && std::isdigit(firstSection.at(endFirstSection-1))) { // Hypernucleus, must be Fe56-1 style
std::stringstream parseStrangeness;
parseStrangeness.str(secondSection);
parseStrangeness >> theS;
if(parsingStream.fail()) {
// Couldn't parse the strange charge section
// Setting unknown particle species
(*this) = ParticleSpecies(UnknownParticle);
return;
}
theS *= (-1);
beginSecondSection = std::find_if(pS.begin()+1, pS.end(), predicate) - pS.begin(); // predicate == std::isdigit(G4int) in this case
firstSection = pS.substr(0, beginSecondSection);
secondSection = pS.substr(beginSecondSection, endFirstSection);
}
// Parse the sections
G4bool success;
if(startsWithAlpha) {
parsingStream.str(secondSection);
success = parseElement(firstSection);
} else {
parsingStream.str(firstSection);
success = parseElement(secondSection);
}
if(!success) {
// Couldn't parse the element section
// Setting unknown particle species
(*this) = ParticleSpecies(UnknownParticle);
return;
}
if(hasIsotope) {
parsingStream >> theA;
if(parsingStream.fail()) {
// Couldn't parse the mass section
// Setting unknown particle species
(*this) = ParticleSpecies(UnknownParticle);
return;
}
} else
theA = 0;
// Check that Z<=A
if(theZ>theA && hasIsotope) {
// Setting unknown particle species
(*this) = ParticleSpecies(UnknownParticle);
return;
}
// Special particle type for protons
if(theZ==1 && theA==1)
theType = Proton;
}
G4bool ParticleSpecies::parseElement(std::string const &s) {
theZ = ParticleTable::parseElement(s);
if(theZ<0)
theZ = ParticleTable::parseIUPACElement(s);
if(theZ<0)
return false;
else
return true;
}
G4bool ParticleSpecies::parseIUPACElement(std::string const &s) {
theZ = ParticleTable::parseIUPACElement(s);
if(theZ==0)
return false;
else
return true;
}
G4int ParticleSpecies::getPDGCode() const {
switch (theType) {
case Proton:
return 2212;
break;
case Neutron:
return 2112;
break;
case DeltaPlusPlus:
return 2224;
break;
case DeltaPlus:
return 2214;
break;
case DeltaZero:
return 2114;
break;
case DeltaMinus:
return 1114;
break;
case PiPlus:
return 211;
break;
case PiZero:
return 111;
break;
case PiMinus:
return -211;
break;
case Eta:
return 221;
break;
case Omega:
return 223;
break;
case EtaPrime:
return 331;
break;
case Photon:
return 22;
break;
case Lambda:
return 3122;
break;
case SigmaPlus:
return 3222;
break;
case SigmaZero:
return 3212;
break;
case SigmaMinus:
return 3112;
break;
case antiProton:
return -2212;
break;
case XiMinus:
return 3312;
break;
case XiZero:
return 3322;
break;
case antiNeutron:
return -2112;
break;
case antiLambda:
return -3122;
break;
case antiSigmaPlus:
return -3222;
break;
case antiSigmaZero:
return -3212;
break;
case antiSigmaMinus:
return -3112;
break;
case antiXiMinus:
return -3312;
break;
case antiXiZero:
return -3322;
break;
case KPlus:
return 321;
break;
case KZero:
return 311;
break;
case KZeroBar:
return -311;
break;
case KShort:
return 310;
break;
case KLong:
return 130;
break;
case KMinus:
return -321;
break;
case Composite:
if(theA == 1 && theZ == 1 && theS == 0) return 2212;
else if(theA == 1 && theZ == 0 && theS == 0) return 2112;
else if(theA == 1 && theZ == 0 && theS == -1) return 3122;
else return theA+theZ*1000-theS*1e6; // Here -theS because hyper-nucleus -> theS < 0
break;
default:
INCL_ERROR("ParticleSpecies::getPDGCode: Unknown particle type." << '\n');
return 0;
break;
}
}
}
| 412 | 0.921865 | 1 | 0.921865 | game-dev | MEDIA | 0.933066 | game-dev | 0.981429 | 1 | 0.981429 |
Gadersd/stable-diffusion-burn | 3,803 | python/autoencoder.py | import pathlib
import save
from save import *
from tinygrad.nn import Conv2d
def save_resnet_block(resnet_block, path):
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
save_group_norm(resnet_block.norm1, pathlib.Path(path, 'norm1'))
save_conv2d(resnet_block.conv1, pathlib.Path(path, 'conv1'))
save_group_norm(resnet_block.norm2, pathlib.Path(path, 'norm2'))
save_conv2d(resnet_block.conv2, pathlib.Path(path, 'conv2'))
if isinstance(resnet_block.nin_shortcut, Conv2d):
save_conv2d(resnet_block.nin_shortcut, pathlib.Path(path, 'nin_shortcut'))
def save_attn_block(attn_block, path):
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
save_group_norm(attn_block.norm, pathlib.Path(path, 'norm'))
save_conv2d(attn_block.q, pathlib.Path(path, 'q'))
save_conv2d(attn_block.k, pathlib.Path(path, 'k'))
save_conv2d(attn_block.v, pathlib.Path(path, 'v'))
save_conv2d(attn_block.proj_out, pathlib.Path(path, 'proj_out'))
def save_mid(mid, path):
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
save_resnet_block(mid.block_1, pathlib.Path(path, 'block_1'))
save_attn_block(mid.attn_1, pathlib.Path(path, 'attn'))
save_resnet_block(mid.block_2, pathlib.Path(path, 'block_2'))
def save_decoder_block(decoder_block, path):
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
if 'block' in decoder_block:
save_resnet_block(decoder_block["block"][0], pathlib.Path(path, 'res1'))
save_resnet_block(decoder_block["block"][1], pathlib.Path(path, 'res2'))
save_resnet_block(decoder_block["block"][2], pathlib.Path(path, 'res3'))
if 'upsample' in decoder_block:
save_conv2d(decoder_block['upsample']['conv'], pathlib.Path(path, 'upsampler'))
def save_decoder(decoder, path):
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
save_conv2d(decoder.conv_in, pathlib.Path(path, 'conv_in'))
save_mid(decoder.mid, pathlib.Path(path, 'mid'))
for i, block in enumerate(decoder.up[::-1]):
print(i)
if isinstance(block['block'][0].nin_shortcut, Conv2d):
print(block['block'][0].nin_shortcut.weight.shape)
save_decoder_block(block, pathlib.Path(path, f'blocks/{i}'))
save_scalar(len(decoder.up), "n_block", path)
save_group_norm(decoder.norm_out, pathlib.Path(path, 'norm_out'))
save_conv2d(decoder.conv_out, pathlib.Path(path, 'conv_out'))
def save_encoder_block(encoder_block, path):
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
if 'block' in encoder_block:
save_resnet_block(encoder_block["block"][0], pathlib.Path(path, 'res1'))
save_resnet_block(encoder_block["block"][1], pathlib.Path(path, 'res2'))
if 'downsample' in encoder_block:
save_padded_conv2d(encoder_block['downsample']['conv'], pathlib.Path(path, 'downsampler'))
def save_encoder(encoder, path):
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
save_conv2d(encoder.conv_in, pathlib.Path(path, 'conv_in'))
save_mid(encoder.mid, pathlib.Path(path, 'mid'))
for i, block in enumerate(encoder.down):
save_encoder_block(block, pathlib.Path(path, f'blocks/{i}'))
save_scalar(len(encoder.down), "n_block", path)
save_group_norm(encoder.norm_out, pathlib.Path(path, 'norm_out'))
save_conv2d(encoder.conv_out, pathlib.Path(path, 'conv_out'))
def save_autoencoder(autoencoder, path):
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
save_encoder(autoencoder.encoder, pathlib.Path(path, 'encoder'))
save_decoder(autoencoder.decoder, pathlib.Path(path, 'decoder'))
save_conv2d(autoencoder.quant_conv, pathlib.Path(path, 'quant_conv'))
save_conv2d(autoencoder.post_quant_conv, pathlib.Path(path, 'post_quant_conv')) | 412 | 0.549846 | 1 | 0.549846 | game-dev | MEDIA | 0.179892 | game-dev | 0.670861 | 1 | 0.670861 |
00-Evan/shattered-pixel-dungeon | 3,380 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/Pushing.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2025 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.effects;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
import com.shatteredpixel.shatteredpixeldungeon.sprites.CharSprite;
import com.watabou.noosa.Camera;
import com.watabou.noosa.Game;
import com.watabou.noosa.Visual;
import com.watabou.utils.Callback;
import com.watabou.utils.PointF;
public class Pushing extends Actor {
private CharSprite sprite;
private int from;
private int to;
private Effect effect;
private Char ch;
private Callback callback;
{
actPriority = VFX_PRIO+10;
}
public Pushing( Char ch, int from, int to ) {
this.ch = ch;
sprite = ch.sprite;
this.from = from;
this.to = to;
this.callback = null;
if (ch == Dungeon.hero){
Camera.main.panFollow(ch.sprite, 20f);
}
}
public Pushing( Char ch, int from, int to, Callback callback ) {
this(ch, from, to);
this.callback = callback;
}
@Override
protected boolean act() {
Actor.remove( Pushing.this );
if (sprite != null && sprite.parent != null) {
if (Dungeon.level.heroFOV[from] || Dungeon.level.heroFOV[to]){
sprite.visible = true;
}
if (effect == null) {
new Effect();
}
} else {
return true;
}
//so that all pushing effects at the same time go simultaneously
for ( Actor actor : Actor.all() ){
if (actor instanceof Pushing && actor.cooldown() == 0)
return true;
}
return false;
}
public static boolean pushingExistsForChar(Char ch) {
for (Actor a : all()){
if (a instanceof Pushing && ((Pushing)a).ch == ch){
return true;
}
}
return false;
}
public class Effect extends Visual {
private static final float DELAY = 0.15f;
private PointF end;
private float delay;
public Effect() {
super( 0, 0, 0, 0 );
point( sprite.worldToCamera( from ) );
end = sprite.worldToCamera( to );
speed.set( 2 * (end.x - x) / DELAY, 2 * (end.y - y) / DELAY );
acc.set( -speed.x / DELAY, -speed.y / DELAY );
delay = 0;
if (sprite.parent != null)
sprite.parent.add( this );
}
@Override
public void update() {
super.update();
if ((delay += Game.elapsed) < DELAY) {
sprite.x = x;
sprite.y = y;
} else {
sprite.point(end);
killAndErase();
Actor.remove(Pushing.this);
if (callback != null) callback.call();
GameScene.sortMobSprites();
next();
}
}
}
}
| 412 | 0.866377 | 1 | 0.866377 | game-dev | MEDIA | 0.985703 | game-dev | 0.9549 | 1 | 0.9549 |
Innoxia/liliths-throne-public | 37,234 | src/com/lilithsthrone/game/dialogue/places/dominion/lilayashome/LilayasRoom.java | package com.lilithsthrone.game.dialogue.places.dominion.lilayashome;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.lilithsthrone.game.character.GameCharacter;
import com.lilithsthrone.game.character.attributes.CorruptionLevel;
import com.lilithsthrone.game.character.body.CoverableArea;
import com.lilithsthrone.game.character.body.types.VaginaType;
import com.lilithsthrone.game.character.fetishes.Fetish;
import com.lilithsthrone.game.character.npc.dominion.Lilaya;
import com.lilithsthrone.game.character.npc.dominion.Rose;
import com.lilithsthrone.game.dialogue.DialogueFlagValue;
import com.lilithsthrone.game.dialogue.DialogueNode;
import com.lilithsthrone.game.dialogue.responses.Response;
import com.lilithsthrone.game.dialogue.responses.ResponseEffectsOnly;
import com.lilithsthrone.game.dialogue.responses.ResponseSex;
import com.lilithsthrone.game.dialogue.utils.UtilText;
import com.lilithsthrone.game.inventory.InventorySlot;
import com.lilithsthrone.game.inventory.clothing.AbstractClothing;
import com.lilithsthrone.game.inventory.clothing.AbstractClothingType;
import com.lilithsthrone.game.inventory.clothing.ClothingType;
import com.lilithsthrone.game.sex.InitialSexActionInformation;
import com.lilithsthrone.game.sex.SexAreaInterface;
import com.lilithsthrone.game.sex.SexAreaOrifice;
import com.lilithsthrone.game.sex.SexAreaPenetration;
import com.lilithsthrone.game.sex.SexParticipantType;
import com.lilithsthrone.game.sex.SexType;
import com.lilithsthrone.game.sex.managers.universal.SMAllFours;
import com.lilithsthrone.game.sex.managers.universal.SMLyingDown;
import com.lilithsthrone.game.sex.managers.universal.SMMasturbation;
import com.lilithsthrone.game.sex.positions.slots.SexSlotAllFours;
import com.lilithsthrone.game.sex.positions.slots.SexSlotLyingDown;
import com.lilithsthrone.game.sex.positions.slots.SexSlotMasturbation;
import com.lilithsthrone.game.sex.sexActions.baseActions.PenisAnus;
import com.lilithsthrone.game.sex.sexActions.baseActions.PenisMouth;
import com.lilithsthrone.game.sex.sexActions.baseActions.PenisVagina;
import com.lilithsthrone.game.sex.sexActions.baseActions.TongueVagina;
import com.lilithsthrone.main.Main;
import com.lilithsthrone.utils.Util;
import com.lilithsthrone.utils.Util.Value;
import com.lilithsthrone.utils.colours.Colour;
import com.lilithsthrone.utils.colours.PresetColour;
import com.lilithsthrone.world.WorldType;
import com.lilithsthrone.world.places.PlaceType;
/**
* @since 0.2.5
* @version 0.4.4.1
* @author Innoxia
*/
public class LilayasRoom {
public static AbstractClothing lilayasPanties;
public static final DialogueNode ROOM_LILAYA = new DialogueNode("Lilaya's Room", ".", false) {
@Override
public int getSecondsPassed() {
return 10;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "EXTERIOR");
}
@Override
public String getResponseTabTitle(int index) {
return LilayaHomeGeneric.getLilayasHouseStandardResponseTabs(index);
}
@Override
public Response getResponse(int responseTab, int index) {
if(responseTab==1) {
return LilayaHomeGeneric.getLilayasHouseFastTravelResponses(index);
}
if (index == 1) {
if(!Main.game.isExtendedWorkTime()) {
return new Response("Lilaya's Room", "The door is firmly shut and locked at the moment...", null);
}
return new Response("Lilaya's Room", "Have a look around Lilaya's room.", ROOM_LILAYA_INSIDE);
} else {
return null;
}
}
};
public static final DialogueNode ROOM_LILAYA_INSIDE = new DialogueNode("Lilaya's Room", ".", true) {
@Override
public int getSecondsPassed() {
return 30;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "INTERIOR_ENTRY");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 0) {
return new Response("Leave", "Step back out into the corridor.", ROOM_LILAYA);
} else if (index == 1) {
return new Response("Panties", "Look through Lilaya's pile of panties.", PANTIES,
Util.newArrayListOfValues(Fetish.FETISH_INCEST), CorruptionLevel.TWO_HORNY,
null, null, null) {
@Override
public void effects() {
List<AbstractClothingType> panties = new ArrayList<>();
panties.add(ClothingType.getClothingTypeFromId("innoxia_groin_lacy_panties"));
panties.add(ClothingType.getClothingTypeFromId("innoxia_groin_panties"));
panties.add(ClothingType.getClothingTypeFromId("innoxia_groin_shimapan"));
panties.add(ClothingType.getClothingTypeFromId("innoxia_groin_crotchless_panties"));
lilayasPanties = Main.game.getItemGen().generateClothing(panties.get(Util.random.nextInt(panties.size())), false);
}
};
} else {
return null;
}
}
};
public static final DialogueNode PANTIES = new DialogueNode("Lilaya's Room", ".", true) {
@Override
public int getSecondsPassed() {
return 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "PANTIES");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 0) {
return new Response("Leave", "Step back out into the corridor.", ROOM_LILAYA) {
@Override
public void effects() {
Main.game.getTextStartStringBuilder().append(UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "PANTIES_EXIT"));
}
};
} else if (index == 1) {
return new ResponseSex("Panty Masturbation", "Use Lilaya's panties to help you masturbate.",
true, true,
new SMMasturbation(
Util.newHashMapOfValues(new Value<>(Main.game.getPlayer(), SexSlotMasturbation.KNEELING_PANTIES))) {
@Override
public String applyEndSexEffects() {
return Main.game.getPlayer().addClothing(LilayasRoom.lilayasPanties, 1, false, true);
}
},
null,
null, PANTIES_POST_MASTURBATION, UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "PANTIES_MASTURBATION"));
} else {
return null;
}
}
};
public static final DialogueNode PANTIES_POST_MASTURBATION = new DialogueNode("Finished", "As you stop masturbating, you wonder what you should do with Lilaya's panties next...", true) {
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "PANTIES_POST_MASTURBATION");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new Response("Hide", "Quickly hide underneath Lilaya's bed, taking the panties along with you.", HIDE);
} else if (index == 2) {
return new Response("Flee", "Quickly make your exit, taking the panties along with you.", FLEE);
} else if (index == 3) {
return new Response("Enjoy Panties", "Surely Rose isn't going to come in here... You think it'd be safe to just continue enjoying Lilaya's panties.", CAUGHT) {
@Override
public void effects() {
Main.game.getNpc(Rose.class).setLocation(WorldType.LILAYAS_HOUSE_FIRST_FLOOR, PlaceType.LILAYA_HOME_ROOM_LILAYA);
Main.game.getTextEndStringBuilder().append(Main.game.getNpc(Rose.class).incrementAffection(Main.game.getPlayer(), -25));
}
};
} else {
return null;
}
}
};
public static final DialogueNode HIDE = new DialogueNode("Lilaya's Room", ".", true) {
@Override
public int getSecondsPassed() {
return 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "HIDE");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new Response("Leave", "Now that Rose has left, you can safely step back out into the corridor.", ROOM_LILAYA);
} else {
return null;
}
}
};
public static final DialogueNode FLEE = new DialogueNode("Lilaya's Room", ".", true) {
@Override
public int getSecondsPassed() {
return 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "FLEE");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new ResponseEffectsOnly("Your room", "Continue on down the corridor to your room.") {
@Override
public void effects() {
Main.game.getPlayer().setLocation(WorldType.LILAYAS_HOUSE_FIRST_FLOOR, PlaceType.LILAYA_HOME_ROOM_PLAYER);
Main.game.setContent(new Response("", "", Main.game.getPlayerCell().getDialogue(false)));
}
};
} else {
return null;
}
}
};
public static final DialogueNode CAUGHT = new DialogueNode("Lilaya's Room", ".", true) {
@Override
public int getSecondsPassed() {
return 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "CAUGHT");
}
@Override
public Response getResponse(int responseTab, int index) {
if(index==1) {
return new Response("Apologise", "Say sorry to Rose.", APOLOGY) {
@Override
public void effects() {
Main.game.getTextEndStringBuilder().append(Main.game.getNpc(Rose.class).incrementAffection(Main.game.getPlayer(), 10));
}
};
} else if(index==2) {
return new Response("Threaten", "Threaten Rose and tell her that she'll be sorry if she tells Lilaya about this.", THREATEN) {
@Override
public void effects() {
Main.game.getTextEndStringBuilder().append(Main.game.getNpc(Rose.class).incrementAffection(Main.game.getPlayer(), -25));
}
};
} else if (index == 3) {
return new ResponseEffectsOnly("Leave", "Make some quick excuses and rush past Rose back to your room.") {
@Override
public void effects() {
Main.game.getDialogueFlags().setFlag(DialogueFlagValue.roseToldOnYou, true);
Main.game.getTextStartStringBuilder().append(UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "CAUGHT_FLEE"));
Main.game.getPlayer().setLocation(WorldType.LILAYAS_HOUSE_FIRST_FLOOR, PlaceType.LILAYA_HOME_ROOM_PLAYER);
Main.game.getNpc(Rose.class).setLocation(WorldType.LILAYAS_HOUSE_GROUND_FLOOR, PlaceType.LILAYA_HOME_LAB);
Main.game.setContent(new Response("", "", Main.game.getPlayerCell().getDialogue(false)));
}
};
} else {
return null;
}
}
};
public static final DialogueNode APOLOGY = new DialogueNode("Lilaya's Room", ".", true, true) {
@Override
public int getSecondsPassed() {
return 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "APOLOGY");
}
@Override
public Response getResponse(int responseTab, int index) {
if(index==1) {
return new Response("Beg", "Beg Rose not to tell Lilaya.", BEG) {
@Override
public void effects() {
Main.game.getTextEndStringBuilder().append(Main.game.getNpc(Rose.class).incrementAffection(Main.game.getPlayer(), 15));
}
};
} else if (index == 2) {
return new ResponseEffectsOnly("Leave", "Tell Rose not to let Lilaya know, and rush off back to your room.") {
@Override
public void effects() {
Main.game.getDialogueFlags().setFlag(DialogueFlagValue.roseToldOnYou, true);
Main.game.getTextStartStringBuilder().append(UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "APOLOGY_FLEE"));
Main.game.getPlayer().setLocation(WorldType.LILAYAS_HOUSE_FIRST_FLOOR, PlaceType.LILAYA_HOME_ROOM_PLAYER);
Main.game.getNpc(Rose.class).setLocation(WorldType.LILAYAS_HOUSE_GROUND_FLOOR, PlaceType.LILAYA_HOME_LAB);
Main.game.setContent(new Response("", "", Main.game.getPlayerCell().getDialogue(false)));
}
};
} else {
return null;
}
}
};
public static final DialogueNode BEG = new DialogueNode("Lilaya's Room", ".", true, true) {
@Override
public int getSecondsPassed() {
return 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "BEG");
}
@Override
public Response getResponse(int responseTab, int index) {
if(index==1) {
return new ResponseSex("Submit", "Let Rose push you back on to the bed and fuck you.",
Util.newArrayListOfValues(Fetish.FETISH_SUBMISSIVE),
null, CorruptionLevel.THREE_DIRTY, null, null, null,
true, false,
new SMLyingDown(
Util.newHashMapOfValues(new Value<>(Main.game.getNpc(Rose.class), SexSlotLyingDown.MISSIONARY)),
Util.newHashMapOfValues(new Value<>(Main.game.getPlayer(), SexSlotLyingDown.LYING_DOWN))) {
@Override
public boolean isPositionChangingAllowed(GameCharacter character) {
return false;
}
@Override
public boolean isAbleToRemoveSelfClothing(GameCharacter character) {
return !character.isPlayer();
}
@Override
public boolean isAbleToRemoveOthersClothing(GameCharacter character, AbstractClothing clothing) {
return !character.isPlayer();
}
@Override
public Map<GameCharacter, List<SexAreaInterface>> getAreasBannedMap() {
return Util.newHashMapOfValues(
new Value<>(
Main.game.getNpc(Rose.class),
Util.newArrayListOfValues(
SexAreaOrifice.VAGINA,
SexAreaOrifice.ANUS,
SexAreaOrifice.MOUTH)));
}
},
null,
null,
AFTER_ROSE_AS_DOM,
UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "ROSE_AS_DOM")){
@Override
public void effects() {
Main.game.getTextEndStringBuilder().append(Main.game.getNpc(Rose.class).incrementAffection(Main.game.getPlayer(), 15));
if(Main.game.getNpc(Rose.class).getClothingInSlot(InventorySlot.GROIN)!=null) {
Main.game.getNpc(Rose.class).unequipClothingIntoVoid(Main.game.getNpc(Rose.class).getClothingInSlot(InventorySlot.GROIN), true, Main.game.getNpc(Rose.class));
}
Main.game.getNpc(Rose.class).displaceClothingForAccess(CoverableArea.PENIS, null);
Main.game.getNpc(Rose.class).equipClothingFromNowhere(Main.game.getItemGen().generateClothing("innoxia_bdsm_penis_strapon", PresetColour.CLOTHING_PURPLE_DARK, false), true, Main.game.getNpc(Rose.class));
}
};
} else if (index == 2) {
return new ResponseEffectsOnly("Refuse", "Refuse Rose's offer and rush off back to your room.") {
@Override
public void effects() {
Main.game.getDialogueFlags().setFlag(DialogueFlagValue.roseToldOnYou, true);
Main.game.getTextStartStringBuilder().append(UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "BEG_FLEE"));
Main.game.getPlayer().setLocation(WorldType.LILAYAS_HOUSE_FIRST_FLOOR, PlaceType.LILAYA_HOME_ROOM_PLAYER);
Main.game.getNpc(Rose.class).setLocation(WorldType.LILAYAS_HOUSE_GROUND_FLOOR, PlaceType.LILAYA_HOME_LAB);
Main.game.setContent(new Response("", "", Main.game.getPlayerCell().getDialogue(false)));
}
};
} else {
return null;
}
}
};
public static final DialogueNode AFTER_ROSE_AS_DOM = new DialogueNode("Finished", "Feeling as though she's 'punished' you enough, Rose brings an end to the sex.", true) {
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "AFTER_ROSE_AS_DOM");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new ResponseEffectsOnly("Leave", "Hurry back to your room.") {
@Override
public void effects() {
Main.game.getPlayer().setLocation(WorldType.LILAYAS_HOUSE_FIRST_FLOOR, PlaceType.LILAYA_HOME_ROOM_PLAYER);
Main.game.getNpc(Rose.class).setLocation(WorldType.LILAYAS_HOUSE_GROUND_FLOOR, PlaceType.LILAYA_HOME_LAB);
Main.game.getNpc(Rose.class).equipClothing();
Main.game.setContent(new Response("", "", Main.game.getPlayerCell().getDialogue(false)));
}
};
} else {
return null;
}
}
};
public static final DialogueNode THREATEN = new DialogueNode("", "", true) {
@Override
public int getSecondsPassed() {
return 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "THREATEN");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new Response("Wait", "Do as Rose says and wait while Lilaya comes up to her room to confront you.", THREATEN_WAIT) {
@Override
public void effects() {
Main.game.getDialogueFlags().setFlag(DialogueFlagValue.roseToldOnYou, false);
Main.game.getNpc(Lilaya.class).setLocation(WorldType.LILAYAS_HOUSE_FIRST_FLOOR, PlaceType.LILAYA_HOME_ROOM_LILAYA);
Main.game.getTextEndStringBuilder().append(Main.game.getNpc(Lilaya.class).incrementAffection(Main.game.getPlayer(), -5));
}
};
} else if (index == 2) {
return new ResponseEffectsOnly("Flee", "Not wanting to be confronted by Lilaya, you rush off back to your room.") {
@Override
public void effects() {
Main.game.getDialogueFlags().setFlag(DialogueFlagValue.roseToldOnYou, true);
Main.game.getTextStartStringBuilder().append(UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "THREATEN_FLEE"));
Main.game.getPlayer().setLocation(WorldType.LILAYAS_HOUSE_FIRST_FLOOR, PlaceType.LILAYA_HOME_ROOM_PLAYER);
Main.game.getNpc(Rose.class).setLocation(WorldType.LILAYAS_HOUSE_GROUND_FLOOR, PlaceType.LILAYA_HOME_LAB);
Main.game.setContent(new Response("", "", Main.game.getPlayerCell().getDialogue(false)));
}
};
} else {
return null;
}
}
};
public static final DialogueNode THREATEN_WAIT = new DialogueNode("", "", true, true) {
@Override
public int getSecondsPassed() {
return 2*60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "THREATEN_WAIT");
}
@Override
public Response getResponse(int responseTab, int index) {
if(index==1) {
return new Response("Submit", "Doing as Lilaya says, you decide to submit and apologise to Rose, letting her decide how best to punish you...", THREATEN_SUBMIT) {
@Override
public Colour getHighlightColour() {
return PresetColour.GENERIC_SEX;
}
@Override
public void effects() {
Main.game.getDialogueFlags().setFlag(DialogueFlagValue.roseToldOnYou, false);
Main.game.getTextEndStringBuilder().append(Main.game.getNpc(Rose.class).incrementAffection(Main.game.getPlayer(), 25));
Main.game.getTextEndStringBuilder().append(Main.game.getNpc(Lilaya.class).incrementAffection(Main.game.getPlayer(), 5));
}
};
}
//TODO needs more options to allow player to fuck Rose?
// else if (index == 2) {
// return new Response("Dominate",
// "Without apologising, dominantly tell Lilaya and Rose that you did what you did because you were feeling particularly horny, and that now that they're here, they should help you to get some relief.",
// DOMINATE,
// Util.newArrayListOfValues(Fetish.FETISH_DOMINANT),
// null, null, null, null) {
// @Override
// public Colour getHighlightColour() {
// return PresetColour.GENERIC_SEX_AS_DOM;
// }
// };
//
// }
else if (index == 2) {
return new ResponseEffectsOnly("Apologise", "Not wanting to risk Lilaya's wrath, you quickly apologise and hurry back to your room.") {
@Override
public void effects() {
Main.game.getDialogueFlags().setFlag(DialogueFlagValue.roseToldOnYou, false);
Main.game.getTextEndStringBuilder().append(Main.game.getNpc(Rose.class).incrementAffection(Main.game.getPlayer(), 15));
Main.game.getTextEndStringBuilder().append(Main.game.getNpc(Lilaya.class).incrementAffection(Main.game.getPlayer(), 5));
Main.game.getTextStartStringBuilder().append(UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "THREATEN_APOLOGISE"));
Main.game.getPlayer().setLocation(WorldType.LILAYAS_HOUSE_FIRST_FLOOR, PlaceType.LILAYA_HOME_ROOM_PLAYER);
Main.game.getNpc(Rose.class).setLocation(WorldType.LILAYAS_HOUSE_GROUND_FLOOR, PlaceType.LILAYA_HOME_LAB);
Main.game.getNpc(Lilaya.class).setLocation(WorldType.LILAYAS_HOUSE_GROUND_FLOOR, PlaceType.LILAYA_HOME_LAB);
Main.game.setContent(new Response("", "", Main.game.getPlayerCell().getDialogue(false)));
}
};
}
return null;
}
};
public static final DialogueNode THREATEN_SUBMIT = new DialogueNode("", "", true, true) {
@Override
public int getSecondsPassed() {
return 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "THREATEN_SUBMIT");
}
@Override
public Response getResponse(int responseTab, int index) {
if(index==1) {
return new ResponseSex("Lilaya's pussy", "Tell Rose that you like the taste of Lilaya's pussy.",
true, false,
new SMAllFours(
Util.newHashMapOfValues(
new Value<>(Main.game.getNpc(Rose.class), SexSlotAllFours.BEHIND),
new Value<>(Main.game.getNpc(Lilaya.class), SexSlotAllFours.IN_FRONT)),
Util.newHashMapOfValues(
new Value<>(Main.game.getPlayer(), SexSlotAllFours.ALL_FOURS))) {
@Override
public boolean isPartnerWantingToStopSex(GameCharacter partner) {
return partner.equals(Main.game.getNpc(Rose.class)) && Main.sex.isSatisfiedFromOrgasms(Main.game.getNpc(Rose.class), true) && Main.sex.isSatisfiedFromOrgasms(Main.game.getNpc(Lilaya.class), true);
}
@Override
public SexType getForeplayPreference(GameCharacter character, GameCharacter targetedCharacter) {
if(targetedCharacter.isPlayer()) {
return getMainSexPreference(character, targetedCharacter);
}
return super.getForeplayPreference(character, targetedCharacter);
}
@Override
public SexType getMainSexPreference(GameCharacter character, GameCharacter targetedCharacter) {
if(character.equals(Main.game.getNpc(Rose.class)) && targetedCharacter.isPlayer()) {
if(Main.game.getPlayer().hasVagina() && Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.VAGINA, true)) {
return new SexType(SexParticipantType.NORMAL, SexAreaPenetration.PENIS, SexAreaOrifice.VAGINA);
} else if(Main.game.isAnalContentEnabled() && Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.ANUS, true)) {
return new SexType(SexParticipantType.NORMAL, SexAreaPenetration.PENIS, SexAreaOrifice.ANUS);
}
}
if(character.equals(Main.game.getNpc(Lilaya.class)) && targetedCharacter.isPlayer()) {
return new SexType(SexParticipantType.NORMAL, SexAreaOrifice.VAGINA, SexAreaPenetration.TONGUE);
}
return super.getMainSexPreference(character, targetedCharacter);
}
@Override
public boolean isPositionChangingAllowed(GameCharacter character) {
return false;
}
@Override
public boolean isAbleToRemoveSelfClothing(GameCharacter character) {
return !character.isPlayer();
}
@Override
public boolean isAbleToRemoveOthersClothing(GameCharacter character, AbstractClothing clothing) {
return !character.isPlayer();
}
@Override
public Map<GameCharacter, List<SexAreaInterface>> getAreasBannedMap() {
return Util.newHashMapOfValues(
new Value<>(
Main.game.getNpc(Rose.class),
Util.newArrayListOfValues(
SexAreaOrifice.VAGINA,
SexAreaOrifice.ANUS,
SexAreaOrifice.MOUTH)));
}
@Override
public boolean isCharacterStartNaked(GameCharacter character) {
return character.equals(Main.game.getNpc(Lilaya.class));
}
@Override
public Map<GameCharacter, List<CoverableArea>> exposeAtStartOfSexMap() {
Map<GameCharacter, List<CoverableArea>> exposeMap = new HashMap<>();
if(Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.MOUTH, true)) {
exposeMap.put(Main.game.getPlayer(), Util.newArrayListOfValues(CoverableArea.MOUTH));
}
if(Main.game.getPlayer().hasVagina() && Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.VAGINA, true)) {
exposeMap.putIfAbsent(Main.game.getPlayer(), new ArrayList<>());
exposeMap.get(Main.game.getPlayer()).add(CoverableArea.VAGINA);
} else if(Main.game.isAnalContentEnabled() && Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.ANUS, true)) {
exposeMap.putIfAbsent(Main.game.getPlayer(), new ArrayList<>());
exposeMap.get(Main.game.getPlayer()).add(CoverableArea.ANUS);
}
return exposeMap;
}
},
null,
null,
AFTER_LILAYA_AND_ROSE_AS_DOMS,
UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "LILAYA_AND_ROSE_AS_DOMS")) {
@Override
public List<InitialSexActionInformation> getInitialSexActions() {
return Util.newArrayListOfValues(
Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.MOUTH, true)
?new InitialSexActionInformation(Main.game.getPlayer(), Main.game.getNpc(Lilaya.class), TongueVagina.CUNNILINGUS_START, false, true)
:null,
Main.game.getPlayer().hasVagina() && Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.VAGINA, true)
?new InitialSexActionInformation(Main.game.getNpc(Rose.class), Main.game.getPlayer(), PenisVagina.PENIS_FUCKING_START, false, true)
:(Main.game.isAnalContentEnabled() && Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.ANUS, true)
?new InitialSexActionInformation(Main.game.getNpc(Rose.class), Main.game.getPlayer(), PenisAnus.PENIS_FUCKING_START, false, true)
:null));
}
@Override
public void effects() {
if(Main.game.getNpc(Rose.class).getClothingInSlot(InventorySlot.GROIN)!=null) {
Main.game.getNpc(Rose.class).unequipClothingIntoVoid(Main.game.getNpc(Rose.class).getClothingInSlot(InventorySlot.GROIN), true, Main.game.getNpc(Rose.class));
}
Main.game.getNpc(Rose.class).displaceClothingForAccess(CoverableArea.PENIS, null);
Main.game.getNpc(Rose.class).equipClothingFromNowhere(Main.game.getItemGen().generateClothing("innoxia_bdsm_penis_strapon", PresetColour.CLOTHING_PURPLE_DARK, false), true, Main.game.getNpc(Rose.class));
}
};
} else if(index==2) {
return new ResponseSex("Lilaya's cock", "Tell Rose that you want Lilaya to grow a cock for you to suck.",
true, false,
new SMAllFours(
Util.newHashMapOfValues(
new Value<>(Main.game.getNpc(Rose.class), SexSlotAllFours.BEHIND),
new Value<>(Main.game.getNpc(Lilaya.class), SexSlotAllFours.IN_FRONT)),
Util.newHashMapOfValues(
new Value<>(Main.game.getPlayer(), SexSlotAllFours.ALL_FOURS))) {
@Override
public boolean isPartnerWantingToStopSex(GameCharacter partner) {
return partner.equals(Main.game.getNpc(Rose.class)) && Main.sex.isSatisfiedFromOrgasms(Main.game.getNpc(Rose.class), true) && Main.sex.isSatisfiedFromOrgasms(Main.game.getNpc(Lilaya.class), true);
}
@Override
public SexType getForeplayPreference(GameCharacter character, GameCharacter targetedCharacter) {
if(targetedCharacter.isPlayer()) {
return getMainSexPreference(character, targetedCharacter);
}
return super.getForeplayPreference(character, targetedCharacter);
}
@Override
public SexType getMainSexPreference(GameCharacter character, GameCharacter targetedCharacter) {
if(character.equals(Main.game.getNpc(Rose.class)) && targetedCharacter.isPlayer()) {
if(Main.game.getPlayer().hasVagina() && Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.VAGINA, true)) {
return new SexType(SexParticipantType.NORMAL, SexAreaPenetration.PENIS, SexAreaOrifice.VAGINA);
} else if(Main.game.isAnalContentEnabled() && Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.ANUS, true)) {
return new SexType(SexParticipantType.NORMAL, SexAreaPenetration.PENIS, SexAreaOrifice.ANUS);
}
}
if(character.equals(Main.game.getNpc(Lilaya.class)) && targetedCharacter.isPlayer()) {
return new SexType(SexParticipantType.NORMAL, SexAreaPenetration.PENIS, SexAreaOrifice.MOUTH);
}
return super.getMainSexPreference(character, targetedCharacter);
}
@Override
public boolean isPositionChangingAllowed(GameCharacter character) {
return false;
}
@Override
public boolean isAbleToRemoveSelfClothing(GameCharacter character) {
return !character.isPlayer();
}
@Override
public boolean isAbleToRemoveOthersClothing(GameCharacter character, AbstractClothing clothing) {
return !character.isPlayer();
}
@Override
public Map<GameCharacter, List<SexAreaInterface>> getAreasBannedMap() {
return Util.newHashMapOfValues(
new Value<>(
Main.game.getNpc(Rose.class),
Util.newArrayListOfValues(
SexAreaOrifice.VAGINA,
SexAreaOrifice.ANUS,
SexAreaOrifice.MOUTH)));
}
@Override
public boolean isCharacterStartNaked(GameCharacter character) {
return character.equals(Main.game.getNpc(Lilaya.class));
}
@Override
public Map<GameCharacter, List<CoverableArea>> exposeAtStartOfSexMap() {
Map<GameCharacter, List<CoverableArea>> exposeMap = new HashMap<>();
if(Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.MOUTH, true)) {
exposeMap.put(Main.game.getPlayer(), Util.newArrayListOfValues(CoverableArea.MOUTH));
}
if(Main.game.getPlayer().hasVagina() && Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.VAGINA, true)) {
exposeMap.putIfAbsent(Main.game.getPlayer(), new ArrayList<>());
exposeMap.get(Main.game.getPlayer()).add(CoverableArea.VAGINA);
} else if(Main.game.isAnalContentEnabled() && Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.ANUS, true)) {
exposeMap.putIfAbsent(Main.game.getPlayer(), new ArrayList<>());
exposeMap.get(Main.game.getPlayer()).add(CoverableArea.ANUS);
}
return exposeMap;
}
},
null,
null,
AFTER_LILAYA_AND_ROSE_AS_DOMS,
UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "LILAYA_AND_ROSE_AS_DOMS_PENIS")) {
@Override
public List<InitialSexActionInformation> getInitialSexActions() {
return Util.newArrayListOfValues(
Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.MOUTH, true)
?new InitialSexActionInformation(Main.game.getPlayer(), Main.game.getNpc(Lilaya.class), PenisMouth.GIVING_BLOWJOB_START, false, true)
:null,
Main.game.getPlayer().hasVagina() && Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.VAGINA, true)
?new InitialSexActionInformation(Main.game.getNpc(Rose.class), Main.game.getPlayer(), PenisVagina.PENIS_FUCKING_START, false, true)
:(Main.game.isAnalContentEnabled() && Main.game.getPlayer().isAbleToAccessCoverableArea(CoverableArea.ANUS, true)
?new InitialSexActionInformation(Main.game.getNpc(Rose.class), Main.game.getPlayer(), PenisAnus.PENIS_FUCKING_START, false, true)
:null));
}
@Override
public void effects() {
Main.game.getNpc(Lilaya.class).setVaginaType(VaginaType.NONE);
((Lilaya)Main.game.getNpc(Lilaya.class)).growCock();
if(Main.game.getNpc(Rose.class).getClothingInSlot(InventorySlot.GROIN)!=null) {
Main.game.getNpc(Rose.class).unequipClothingIntoVoid(Main.game.getNpc(Rose.class).getClothingInSlot(InventorySlot.GROIN), true, Main.game.getNpc(Rose.class));
}
Main.game.getNpc(Rose.class).displaceClothingForAccess(CoverableArea.PENIS, null);
Main.game.getNpc(Rose.class).equipClothingFromNowhere(Main.game.getItemGen().generateClothing("innoxia_bdsm_penis_strapon", PresetColour.CLOTHING_PURPLE_DARK, false), true, Main.game.getNpc(Rose.class));
}
};
}
return null;
}
};
public static final DialogueNode AFTER_LILAYA_AND_ROSE_AS_DOMS = new DialogueNode("Finished", "Feeling as though she's 'punished' you enough, Rose brings an end to the sex.", true) {
@Override
public int getSecondsPassed() {
return 5*60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "AFTER_LILAYA_AND_ROSE_AS_DOMS");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new ResponseEffectsOnly("Leave", "Hurry back to your room.") {
@Override
public void effects() {
Main.game.getTextStartStringBuilder().append(UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "AFTER_LILAYA_AND_ROSE_AS_DOMS_LEAVE"));
Main.game.getPlayer().setLocation(WorldType.LILAYAS_HOUSE_FIRST_FLOOR, PlaceType.LILAYA_HOME_ROOM_PLAYER);
Main.game.getNpc(Lilaya.class).setLocation(WorldType.LILAYAS_HOUSE_GROUND_FLOOR, PlaceType.LILAYA_HOME_LAB);
Main.game.getNpc(Rose.class).setLocation(WorldType.LILAYAS_HOUSE_GROUND_FLOOR, PlaceType.LILAYA_HOME_LAB);
Main.game.setContent(new Response("", "", Main.game.getPlayerCell().getDialogue(false)));
}
};
} else {
return null;
}
}
};
public static final DialogueNode DOMINATE = new DialogueNode("", "", true) {
@Override
public int getSecondsPassed() {
return 60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "DOMINATE");
}
@Override
public Response getResponse(int responseTab, int index) {
if(index==1) {
return new ResponseSex("Fuck Lilaya", "Have dominant sex with Rose and Lilaya.",
true, false,
new SMAllFours(
Util.newHashMapOfValues(new Value<>(Main.game.getPlayer(), SexSlotAllFours.BEHIND)),
Util.newHashMapOfValues(new Value<>(Main.game.getNpc(Lilaya.class), SexSlotAllFours.ALL_FOURS))) {
@Override
public boolean isPositionChangingAllowed(GameCharacter character) {
return false;
}
},
Util.newArrayListOfValues(Main.game.getNpc(Rose.class)),
null,
AFTER_LILAYA_AS_SUB,
UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "LILAYA_AS_SUB_START"));
} else if (index == 2) {
return new ResponseEffectsOnly("Leave", "Turn down Rose's offer and head back to your room.") {
@Override
public void effects() {
Main.game.getTextStartStringBuilder().append(UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "DOMINATE_LEAVE"));
Main.game.getPlayer().setLocation(WorldType.LILAYAS_HOUSE_FIRST_FLOOR, PlaceType.LILAYA_HOME_ROOM_PLAYER);
Main.game.getNpc(Lilaya.class).setLocation(WorldType.LILAYAS_HOUSE_GROUND_FLOOR, PlaceType.LILAYA_HOME_LAB);
Main.game.getNpc(Rose.class).setLocation(WorldType.LILAYAS_HOUSE_GROUND_FLOOR, PlaceType.LILAYA_HOME_LAB);
Main.game.setContent(new Response("", "", Main.game.getPlayerCell().getDialogue(false)));
}
};
} else {
return null;
}
}
};
public static final DialogueNode AFTER_LILAYA_AS_SUB = new DialogueNode("Finished", "Having had your fun with Lilaya, you bring an end to the sex.", true) {
@Override
public int getSecondsPassed() {
return 5*60;
}
@Override
public String getContent() {
return UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "AFTER_ROSE_AND_LILAYA_AS_SUBS");
}
@Override
public Response getResponse(int responseTab, int index) {
if (index == 1) {
return new ResponseEffectsOnly("Leave", "Head back to your room.") {
@Override
public void effects() {
Main.game.getTextStartStringBuilder().append(UtilText.parseFromXMLFile("places/dominion/lilayasHome/lilayasRoom", "AFTER_ROSE_AND_LILAYA_AS_SUBS_LEAVE"));
Main.game.getPlayer().setLocation(WorldType.LILAYAS_HOUSE_FIRST_FLOOR, PlaceType.LILAYA_HOME_ROOM_PLAYER);
Main.game.getNpc(Lilaya.class).setLocation(WorldType.LILAYAS_HOUSE_GROUND_FLOOR, PlaceType.LILAYA_HOME_LAB);
Main.game.getNpc(Rose.class).setLocation(WorldType.LILAYAS_HOUSE_GROUND_FLOOR, PlaceType.LILAYA_HOME_LAB);
Main.game.setContent(new Response("", "", Main.game.getPlayerCell().getDialogue(false)));
}
};
}
return null;
}
};
}
| 412 | 0.735999 | 1 | 0.735999 | game-dev | MEDIA | 0.601929 | game-dev | 0.545046 | 1 | 0.545046 |
smourier/DirectNAot | 3,646 | DirectN.Extensions/Utilities/RunningObjectTable.cs | namespace DirectN.Extensions.Utilities;
public static partial class RunningObjectTable
{
public static HRESULT Register(CommandTarget commandTarget, out uint cookie, ROT_FLAGS flags = ROT_FLAGS.ROTFLAGS_REGISTRATIONKEEPSALIVE, bool throwOnError = true)
{
cookie = 0;
var hr = Functions.GetRunningObjectTable(0, out var tablePtr).ThrowOnError(throwOnError);
if (tablePtr == null)
return hr;
using var table = new ComObject<IRunningObjectTable>(tablePtr);
var moniker = commandTarget.Moniker + ":" + SystemUtilities.CurrentProcess.Id;
using var d = new Pwstr(CommandTarget.Delimiter);
using var m = new Pwstr(moniker);
hr = Functions.CreateItemMoniker(d, m, out var mkPtr).ThrowOnError(throwOnError);
if (mkPtr == null)
return hr;
using var mk = new ComObject<IMoniker>(mkPtr);
var unk = ComObject.GetOrCreateComInstance(commandTarget);
return table.Object.Register(flags, unk, mk.Object, out cookie).ThrowOnError(throwOnError);
}
public static HRESULT Revoke(uint cookie, bool throwOnError = true)
{
var hr = Functions.GetRunningObjectTable(0, out var tablePtr).ThrowOnError(throwOnError);
if (tablePtr == null)
return hr;
using var table = new ComObject<IRunningObjectTable>(tablePtr);
return table.Object.Revoke(cookie).ThrowOnError(false);
}
public static nint GetObject(string itemName, string? delimiter = null, bool throwOnError = true)
{
ArgumentNullException.ThrowIfNull(itemName);
delimiter = delimiter.Nullify() ?? "!";
using var d = new Pwstr(delimiter);
using var n = new Pwstr(itemName);
Functions.CreateItemMoniker(d, n, out var mkPtr).ThrowOnError(throwOnError);
if (mkPtr == null)
return 0;
using var mk = new ComObject<IMoniker>(mkPtr);
if (mk == null)
return 0;
Functions.GetRunningObjectTable(0, out var tablePtr).ThrowOnError(throwOnError);
if (tablePtr == null)
return 0;
using var table = new ComObject<IRunningObjectTable>(tablePtr);
table.Object.GetObject(mk.Object, out var unk).ThrowOnError(throwOnError);
return unk;
}
public static nint GetObject(IMoniker moniker, bool throwOnError = true)
{
ArgumentNullException.ThrowIfNull(moniker);
Functions.GetRunningObjectTable(0, out var tablePtr).ThrowOnError(throwOnError);
if (tablePtr == null)
return 0;
using var table = new ComObject<IRunningObjectTable>(tablePtr);
table.Object.GetObject(moniker, out var unk).ThrowOnError(throwOnError);
return unk;
}
public static IEnumerable<IComObject<IMoniker>> Enumerate(bool throwOnError = true)
{
Functions.GetRunningObjectTable(0, out var tablePtr).ThrowOnError(throwOnError);
if (tablePtr == null)
yield break;
using var table = new ComObject<IRunningObjectTable>(tablePtr);
table.Object.EnumRunning(out var enumeratorPtr).ThrowOnError(throwOnError);
if (enumeratorPtr == null)
yield break;
using var enumerator = new ComObject<IEnumMoniker>(enumeratorPtr);
var mks = new nint[1];
do
{
if (enumerator.Object.Next(1, mks, nint.Zero) != 0)
break;
var mk = mks[0];
var m = ComObject.FromPointer<IMoniker>(mk);
if (m != null)
yield return m; // caller will have to call dispose
}
while (true);
}
}
| 412 | 0.795449 | 1 | 0.795449 | game-dev | MEDIA | 0.382658 | game-dev | 0.9157 | 1 | 0.9157 |
Platonymous/Stardew-Valley-Mods | 2,831 | SeedBag/SeedBagMod.cs | using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewValley;
using StardewValley.Menus;
using System.Linq;
using SpaceShared.APIs;
using HarmonyLib;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using System;
namespace Portraiture2
{
public class SeedBagMod : Mod
{
internal static SeedBagMod _instance;
internal static IModHelper _helper => _instance.Helper;
internal static ITranslationHelper i18n => _helper.Translation;
internal static Config config;
internal static Harmony HarmonyInstance;
internal static bool DrawingTool = false;
public override void Entry(IModHelper helper)
{
_instance = this;
config = helper.ReadConfig<Config>();
helper.Events.GameLoop.GameLaunched += OnGameLaunched;
helper.Events.Display.MenuChanged += Display_MenuChanged;
HarmonyInstance = new Harmony("Platonymous.SeedBag");
HarmonyInstance.Patch(
AccessTools.Method(typeof(SpriteBatch), "Draw", new Type[] { typeof(Texture2D), typeof(Vector2), typeof(Rectangle?), typeof(Color), typeof(float), typeof(Vector2), typeof(float), typeof(SpriteEffects), typeof(float) })
,new HarmonyMethod(this.GetType(),nameof(Draw)));
HarmonyInstance.Patch(
AccessTools.Method(typeof(Game1), nameof(Game1.drawTool), new Type[] {typeof(Farmer), typeof(int)})
,new HarmonyMethod(this.GetType(), nameof(BeforeTool))
, new HarmonyMethod(this.GetType(), nameof(AfterTool)));
}
public static void BeforeTool(Farmer f)
{
if(f == Game1.player)
DrawingTool = true;
}
public static void AfterTool()
{
DrawingTool = false;
}
public static void Draw(ref Texture2D texture, ref Rectangle? sourceRectangle)
{
if (DrawingTool && Game1.player?.CurrentTool is SeedBagTool && texture == Game1.toolSpriteSheet)
{
texture = SeedBagTool.Texture;
sourceRectangle = new Rectangle(0, 0, 16, 16);
}
}
private void Display_MenuChanged(object sender, MenuChangedEventArgs e)
{
if (e.NewMenu is ShopMenu { ShopId: "SeedShop" } menu && new SeedBagTool() is SeedBagTool tool)
menu.AddForSale(tool , new ItemStockInformation(tool.salePrice(),1));
}
private void OnGameLaunched(object sender, GameLaunchedEventArgs e)
{
SeedBagTool.LoadTextures(Helper);
var spaceCore = this.Helper.ModRegistry.GetApi<ISpaceCoreApi>("spacechase0.SpaceCore");
spaceCore.RegisterSerializerType(typeof(SeedBagTool));
}
}
}
| 412 | 0.908229 | 1 | 0.908229 | game-dev | MEDIA | 0.822109 | game-dev | 0.814148 | 1 | 0.814148 |
11011010/BFA-Frankenstein-Core | 3,684 | src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_the_maker.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 "ScriptMgr.h"
#include "blood_furnace.h"
#include "ScriptedCreature.h"
enum Yells
{
SAY_AGGRO = 0,
SAY_KILL = 1,
SAY_DIE = 2
};
enum Spells
{
SPELL_ACID_SPRAY = 38153,
SPELL_EXPLODING_BREAKER = 30925,
SPELL_KNOCKDOWN = 20276,
SPELL_DOMINATION = 25772
};
enum Events
{
EVENT_ACID_SPRAY = 1,
EVENT_EXPLODING_BREAKER,
EVENT_DOMINATION,
EVENT_KNOCKDOWN
};
class boss_the_maker : public CreatureScript
{
public:
boss_the_maker() : CreatureScript("boss_the_maker") { }
struct boss_the_makerAI : public BossAI
{
boss_the_makerAI(Creature* creature) : BossAI(creature, DATA_THE_MAKER) { }
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
Talk(SAY_AGGRO);
events.ScheduleEvent(EVENT_ACID_SPRAY, 15000);
events.ScheduleEvent(EVENT_EXPLODING_BREAKER, 6000);
events.ScheduleEvent(EVENT_DOMINATION, 120000);
events.ScheduleEvent(EVENT_KNOCKDOWN, 10000);
}
void KilledUnit(Unit* who) override
{
if (who->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_KILL);
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
Talk(SAY_DIE);
}
void ExecuteEvent(uint32 eventId) override
{
switch (eventId)
{
case EVENT_ACID_SPRAY:
DoCastVictim(SPELL_ACID_SPRAY);
events.ScheduleEvent(EVENT_ACID_SPRAY, urand(15000, 23000));
break;
case EVENT_EXPLODING_BREAKER:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 30.0f, true))
DoCast(target, SPELL_EXPLODING_BREAKER);
events.ScheduleEvent(EVENT_EXPLODING_BREAKER, urand(4000, 12000));
break;
case EVENT_DOMINATION:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true))
DoCast(target, SPELL_DOMINATION);
events.ScheduleEvent(EVENT_DOMINATION, 120000);
break;
case EVENT_KNOCKDOWN:
DoCastVictim(SPELL_KNOCKDOWN);
events.ScheduleEvent(EVENT_KNOCKDOWN, urand(4000, 12000));
break;
default:
break;
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetBloodFurnaceAI<boss_the_makerAI>(creature);
}
};
void AddSC_boss_the_maker()
{
new boss_the_maker();
}
| 412 | 0.981786 | 1 | 0.981786 | game-dev | MEDIA | 0.987671 | game-dev | 0.833657 | 1 | 0.833657 |
ren8179/Qf.Core | 1,192 | framework/src/Qf.Core/Uow/IUnitOfWork.cs | using JetBrains.Annotations;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Qf.Core.Uow
{
public interface IUnitOfWork : IDatabaseApiContainer, ITransactionApiContainer, IDisposable
{
Guid Id { get; }
event EventHandler<UnitOfWorkFailedEventArgs> Failed;
event EventHandler<UnitOfWorkEventArgs> Disposed;
IUnitOfWorkOptions Options { get; }
IUnitOfWork Outer { get; }
bool IsReserved { get; }
bool IsDisposed { get; }
bool IsCompleted { get; }
string ReservationName { get; }
void SetOuter([CanBeNull] IUnitOfWork outer);
void Initialize([NotNull] UnitOfWorkOptions options);
void Reserve([NotNull] string reservationName);
void SaveChanges();
Task SaveChangesAsync(CancellationToken cancellationToken = default);
void Complete();
Task CompleteAsync(CancellationToken cancellationToken = default);
void Rollback();
Task RollbackAsync(CancellationToken cancellationToken = default);
void OnCompleted(Func<Task> handler);
}
}
| 412 | 0.71816 | 1 | 0.71816 | game-dev | MEDIA | 0.515647 | game-dev | 0.727429 | 1 | 0.727429 |
SR5-FoundryVTT/SR5-FoundryVTT | 2,257 | src/module/apps/chummer-import-form.ts | import { CharacterImporter } from "./importer/actorImport/characterImporter/CharacterImporter"
import { SpiritImporter } from "./importer/actorImport/spiritImporter/SpiritImporter"
export class ChummerImportForm extends foundry.appv1.api.FormApplication {
static override get defaultOptions() {
const options = super.defaultOptions;
options.id = 'chummer-import';
options.classes = ['shadowrun5e'];
options.title = 'Chummer/Hero Lab Import';
options.template = 'systems/shadowrun5e/dist/templates/apps/import.hbs';
options.width = 600;
options.height = 'auto';
return options;
}
override async _updateObject(event, formData) { }
override getData() {
return {};
}
override activateListeners(html) {
html.find('.submit-chummer-import').click(async (event) => {
event.preventDefault();
const chummerFile = JSON.parse($('.chummer-text').val() as string);
const importOptions = {
assignIcons: $('.assignIcons').is(':checked'),
armor: $('.armor').is(':checked'),
contacts: $('.contacts').is(':checked'),
cyberware: $('.cyberware').is(':checked'),
equipment: $('.gear').is(':checked'),
lifestyles: $('.lifestyles').is(':checked'),
powers: $('.powers').is(':checked'),
qualities: $('.qualities').is(':checked'),
spells: $('.spells').is(':checked'),
vehicles: $('.vehicles').is(':checked'),
weapons: $('.weapons').is(':checked'),
};
let importer;
switch((this.object as any).type) {
case 'character': importer = new CharacterImporter(); break;
case 'spirit': importer = new SpiritImporter(); break;
}
await importer.importChummerCharacter(this.object, chummerFile, importOptions);
ui.notifications?.info(
'Complete! Check everything. Notably: Ranged weapon mods and ammo; Strength based weapon damage; Specializations on all spells, powers, and weapons;'
);
void this.close();
});
}
}
| 412 | 0.861266 | 1 | 0.861266 | game-dev | MEDIA | 0.44931 | game-dev | 0.825035 | 1 | 0.825035 |
mangosArchives/serverZero_Rel19 | 19,446 | src/scripts/scripts/eastern_kingdoms/burning_steppes.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: Burning_Steppes
* SD%Complete: 100
* SDComment: Quest support: 4121, 4122, 4224, 4866.
* SDCategory: Burning Steppes
* EndScriptData
*/
/**
* ContentData
* npc_ragged_john
* npc_grark_lorkrub
* EndContentData
*/
#include "precompiled.h"
#include "escort_ai.h"
/*######
## npc_ragged_john
######*/
struct MANGOS_DLL_DECL npc_ragged_johnAI : public ScriptedAI
{
npc_ragged_johnAI(Creature* pCreature) : ScriptedAI(pCreature) { Reset(); }
void Reset() override {}
void MoveInLineOfSight(Unit* who) override
{
if (who->HasAura(16468, EFFECT_INDEX_0))
{
if (who->GetTypeId() == TYPEID_PLAYER && m_creature->IsWithinDistInMap(who, 15) && who->isInAccessablePlaceFor(m_creature))
{
DoCastSpellIfCan(who, 16472);
((Player*)who)->AreaExploredOrEventHappens(4866);
}
}
if (!m_creature->getVictim() && who->IsTargetableForAttack() && (m_creature->IsHostileTo(who)) && who->isInAccessablePlaceFor(m_creature))
{
if (!m_creature->CanFly() && m_creature->GetDistanceZ(who) > CREATURE_Z_ATTACK_RANGE)
{
return;
}
float attackRadius = m_creature->GetAttackDistance(who);
if (m_creature->IsWithinDistInMap(who, attackRadius) && m_creature->IsWithinLOSInMap(who))
{
who->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
AttackStart(who);
}
}
}
};
CreatureAI* GetAI_npc_ragged_john(Creature* pCreature)
{
return new npc_ragged_johnAI(pCreature);
}
bool GossipHello_npc_ragged_john(Player* pPlayer, Creature* pCreature)
{
if (pCreature->IsQuestGiver())
{
pPlayer->PrepareQuestMenu(pCreature->GetObjectGuid());
}
if (pPlayer->GetQuestStatus(4224) == QUEST_STATUS_INCOMPLETE)
{
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Official business, John. I need some information about Marshal Windsor. Tell me about he last time you saw him.", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF);
}
pPlayer->SEND_GOSSIP_MENU(2713, pCreature->GetObjectGuid());
return true;
}
bool GossipSelect_npc_ragged_john(Player* pPlayer, Creature* pCreature, uint32 /*uiSender*/, uint32 uiAction)
{
switch (uiAction)
{
case GOSSIP_ACTION_INFO_DEF:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "So what did you do?", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
pPlayer->SEND_GOSSIP_MENU(2714, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF+1:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Start making sense, dwarf. I don't want to have anything to do with your cracker, your pappy, or any sort of 'discreditin'.", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2);
pPlayer->SEND_GOSSIP_MENU(2715, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF+2:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Ironfoe?", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3);
pPlayer->SEND_GOSSIP_MENU(2716, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF+3:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Interesting... continue, John.", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4);
pPlayer->SEND_GOSSIP_MENU(2717, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF+4:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "So that's how Windsor died...", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 5);
pPlayer->SEND_GOSSIP_MENU(2718, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF+5:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "So how did he die?", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 6);
pPlayer->SEND_GOSSIP_MENU(2719, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF+6:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Ok, so where the hell is he? Wait a minute! Are you drunk?", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 7);
pPlayer->SEND_GOSSIP_MENU(2720, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF+7:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "WHY is he in Blackrock Depths?", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 8);
pPlayer->SEND_GOSSIP_MENU(2721, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF+8:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "300? So the Dark Irons killed him and dragged him into the Depths?", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 9);
pPlayer->SEND_GOSSIP_MENU(2722, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF+9:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Ahh... Ironfoe.", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 10);
pPlayer->SEND_GOSSIP_MENU(2723, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF+10:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Thanks, Ragged John. Your story was very uplifting and informative.", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 11);
pPlayer->SEND_GOSSIP_MENU(2725, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF+11:
pPlayer->CLOSE_GOSSIP_MENU();
pPlayer->AreaExploredOrEventHappens(4224);
break;
}
return true;
}
/*######
## npc_grark_lorkrub
######*/
enum
{
SAY_START = -1000873,
SAY_PAY = -1000874,
SAY_FIRST_AMBUSH_START = -1000875,
SAY_FIRST_AMBUSH_END = -1000876,
SAY_SEC_AMBUSH_START = -1000877,
SAY_SEC_AMBUSH_END = -1000878,
SAY_THIRD_AMBUSH_START = -1000879,
SAY_THIRD_AMBUSH_END = -1000880,
EMOTE_LAUGH = -1000881,
SAY_LAST_STAND = -1000882,
SAY_LEXLORT_1 = -1000883,
SAY_LEXLORT_2 = -1000884,
EMOTE_RAISE_AXE = -1000885,
EMOTE_LOWER_HAND = -1000886,
SAY_LEXLORT_3 = -1000887,
SAY_LEXLORT_4 = -1000888,
EMOTE_SUBMIT = -1000889,
SAY_AGGRO = -1000890,
SPELL_CAPTURE_GRARK = 14250,
NPC_BLACKROCK_AMBUSHER = 9522,
NPC_BLACKROCK_RAIDER = 9605,
NPC_FLAMESCALE_DRAGONSPAWN = 7042,
NPC_SEARSCALE_DRAKE = 7046,
NPC_GRARK_LORKRUB = 9520,
NPC_HIGH_EXECUTIONER_NUZARK = 9538,
NPC_SHADOW_OF_LEXLORT = 9539,
FACTION_FRIENDLY = 35,
QUEST_ID_PRECARIOUS_PREDICAMENT = 4121
};
static const DialogueEntry aOutroDialogue[] =
{
{SAY_LAST_STAND, NPC_GRARK_LORKRUB, 5000},
{SAY_LEXLORT_1, NPC_SHADOW_OF_LEXLORT, 3000},
{SAY_LEXLORT_2, NPC_SHADOW_OF_LEXLORT, 5000},
{EMOTE_RAISE_AXE, NPC_HIGH_EXECUTIONER_NUZARK, 4000},
{EMOTE_LOWER_HAND, NPC_SHADOW_OF_LEXLORT, 3000},
{SAY_LEXLORT_3, NPC_SHADOW_OF_LEXLORT, 3000},
{NPC_GRARK_LORKRUB, 0, 5000},
{SAY_LEXLORT_4, NPC_SHADOW_OF_LEXLORT, 0},
{0, 0, 0},
};
struct MANGOS_DLL_DECL npc_grark_lorkrubAI : public npc_escortAI, private DialogueHelper
{
npc_grark_lorkrubAI(Creature* pCreature) : npc_escortAI(pCreature),
DialogueHelper(aOutroDialogue)
{
Reset();
}
ObjectGuid m_nuzarkGuid;
ObjectGuid m_lexlortGuid;
GuidList m_lSearscaleGuidList;
uint8 m_uiKilledCreatures;
bool m_bIsFirstSearScale;
void Reset() override
{
if (!HasEscortState(STATE_ESCORT_ESCORTING))
{
m_uiKilledCreatures = 0;
m_bIsFirstSearScale = true;
m_lSearscaleGuidList.clear();
m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
}
void Aggro(Unit* /*pWho*/) override
{
if (!HasEscortState(STATE_ESCORT_ESCORTING))
{
DoScriptText(SAY_AGGRO, m_creature);
}
}
void MoveInLineOfSight(Unit* pWho) override
{
// No combat during escort
if (HasEscortState(STATE_ESCORT_ESCORTING))
{
return;
}
npc_escortAI::MoveInLineOfSight(pWho);
}
void WaypointReached(uint32 uiPointId) override
{
switch (uiPointId)
{
case 1:
DoScriptText(SAY_START, m_creature);
break;
case 7:
DoScriptText(SAY_PAY, m_creature);
break;
case 12:
DoScriptText(SAY_FIRST_AMBUSH_START, m_creature);
SetEscortPaused(true);
m_creature->SummonCreature(NPC_BLACKROCK_AMBUSHER, -7844.3f, -1521.6f, 139.2f, 0.0f, TEMPSUMMON_TIMED_OOC_DESPAWN, 20000);
m_creature->SummonCreature(NPC_BLACKROCK_AMBUSHER, -7860.4f, -1507.8f, 141.0f, 6.0f, TEMPSUMMON_TIMED_OOC_DESPAWN, 20000);
m_creature->SummonCreature(NPC_BLACKROCK_RAIDER, -7845.6f, -1508.1f, 138.8f, 6.1f, TEMPSUMMON_TIMED_OOC_DESPAWN, 20000);
m_creature->SummonCreature(NPC_BLACKROCK_RAIDER, -7859.8f, -1521.8f, 139.2f, 6.2f, TEMPSUMMON_TIMED_OOC_DESPAWN, 20000);
break;
case 24:
DoScriptText(SAY_SEC_AMBUSH_START, m_creature);
SetEscortPaused(true);
m_creature->SummonCreature(NPC_BLACKROCK_AMBUSHER, -8035.3f, -1222.2f, 135.5f, 5.1f, TEMPSUMMON_TIMED_OOC_DESPAWN, 20000);
m_creature->SummonCreature(NPC_FLAMESCALE_DRAGONSPAWN, -8037.5f, -1216.9f, 135.8f, 5.1f, TEMPSUMMON_TIMED_OOC_DESPAWN, 20000);
m_creature->SummonCreature(NPC_BLACKROCK_AMBUSHER, -8009.5f, -1222.1f, 139.2f, 3.9f, TEMPSUMMON_TIMED_OOC_DESPAWN, 20000);
m_creature->SummonCreature(NPC_FLAMESCALE_DRAGONSPAWN, -8007.1f, -1219.4f, 140.1f, 3.9f, TEMPSUMMON_TIMED_OOC_DESPAWN, 20000);
break;
case 28:
m_creature->SummonCreature(NPC_SEARSCALE_DRAKE, -7897.8f, -1123.1f, 233.4f, 3.0f, TEMPSUMMON_TIMED_OOC_DESPAWN, 60000);
m_creature->SummonCreature(NPC_SEARSCALE_DRAKE, -7898.8f, -1125.1f, 193.9f, 3.0f, TEMPSUMMON_TIMED_OOC_DESPAWN, 60000);
m_creature->SummonCreature(NPC_SEARSCALE_DRAKE, -7895.6f, -1119.5f, 194.5f, 3.1f, TEMPSUMMON_TIMED_OOC_DESPAWN, 60000);
break;
case 30:
{
SetEscortPaused(true);
DoScriptText(SAY_THIRD_AMBUSH_START, m_creature);
Player* pPlayer = GetPlayerForEscort();
if (!pPlayer)
{
return;
}
// Set all the dragons in combat
for (GuidList::const_iterator itr = m_lSearscaleGuidList.begin(); itr != m_lSearscaleGuidList.end(); ++itr)
{
if (Creature* pTemp = m_creature->GetMap()->GetCreature(*itr))
{
pTemp->AI()->AttackStart(pPlayer);
}
}
break;
}
case 36:
DoScriptText(EMOTE_LAUGH, m_creature);
break;
case 45:
StartNextDialogueText(SAY_LAST_STAND);
SetEscortPaused(true);
m_creature->SummonCreature(NPC_HIGH_EXECUTIONER_NUZARK, -7532.3f, -1029.4f, 258.0f, 2.7f, TEMPSUMMON_TIMED_DESPAWN, 40000);
m_creature->SummonCreature(NPC_SHADOW_OF_LEXLORT, -7532.8f, -1032.9f, 258.2f, 2.5f, TEMPSUMMON_TIMED_DESPAWN, 40000);
break;
}
}
void JustDidDialogueStep(int32 iEntry) override
{
switch (iEntry)
{
case SAY_LEXLORT_1:
m_creature->SetStandState(UNIT_STAND_STATE_KNEEL);
break;
case SAY_LEXLORT_3:
// Note: this part isn't very clear. Should he just simply attack him, or charge him?
if (Creature* pNuzark = m_creature->GetMap()->GetCreature(m_nuzarkGuid))
{
pNuzark->HandleEmote(EMOTE_ONESHOT_ATTACK2HTIGHT);
}
break;
case NPC_GRARK_LORKRUB:
// Fake death creature when the axe is lowered. This will allow us to finish the event
m_creature->InterruptNonMeleeSpells(true);
m_creature->SetHealth(1);
m_creature->StopMoving();
m_creature->ClearComboPointHolders();
m_creature->RemoveAllAurasOnDeath();
m_creature->ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
m_creature->ClearAllReactives();
m_creature->GetMotionMaster()->Clear();
m_creature->GetMotionMaster()->MoveIdle();
m_creature->SetStandState(UNIT_STAND_STATE_DEAD);
break;
case SAY_LEXLORT_4:
// Finish the quest
if (Player* pPlayer = GetPlayerForEscort())
{
pPlayer->GroupEventHappens(QUEST_ID_PRECARIOUS_PREDICAMENT, m_creature);
}
// Kill self
m_creature->DealDamage(m_creature, m_creature->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NONE, NULL, false);
break;
}
}
void JustSummoned(Creature* pSummoned) override
{
switch (pSummoned->GetEntry())
{
case NPC_HIGH_EXECUTIONER_NUZARK:
m_nuzarkGuid = pSummoned->GetObjectGuid();
break;
case NPC_SHADOW_OF_LEXLORT:
m_lexlortGuid = pSummoned->GetObjectGuid();
break;
case NPC_SEARSCALE_DRAKE:
// If it's the flying drake allow him to move in circles
if (m_bIsFirstSearScale)
{
m_bIsFirstSearScale = false;
pSummoned->SetLevitate(true);
// ToDo: this guy should fly in circles above the creature
}
m_lSearscaleGuidList.push_back(pSummoned->GetObjectGuid());
break;
default:
// The hostile mobs should attack the player only
if (Player* pPlayer = GetPlayerForEscort())
{
pSummoned->AI()->AttackStart(pPlayer);
}
break;
}
}
void SummonedCreatureJustDied(Creature* /*pSummoned*/) override
{
++m_uiKilledCreatures;
switch (m_uiKilledCreatures)
{
case 4:
DoScriptText(SAY_FIRST_AMBUSH_END, m_creature);
SetEscortPaused(false);
break;
case 8:
DoScriptText(SAY_SEC_AMBUSH_END, m_creature);
SetEscortPaused(false);
break;
case 11:
DoScriptText(SAY_THIRD_AMBUSH_END, m_creature);
SetEscortPaused(false);
break;
}
}
Creature* GetSpeakerByEntry(uint32 uiEntry) override
{
switch (uiEntry)
{
case NPC_GRARK_LORKRUB:
return m_creature;
case NPC_HIGH_EXECUTIONER_NUZARK:
return m_creature->GetMap()->GetCreature(m_nuzarkGuid);
case NPC_SHADOW_OF_LEXLORT:
return m_creature->GetMap()->GetCreature(m_lexlortGuid);
default:
return NULL;
}
}
void UpdateEscortAI(const uint32 uiDiff) override
{
DialogueUpdate(uiDiff);
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
{
return;
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_npc_grark_lorkrub(Creature* pCreature)
{
return new npc_grark_lorkrubAI(pCreature);
}
bool QuestAccept_npc_grark_lorkrub(Player* pPlayer, Creature* pCreature, const Quest* pQuest)
{
if (pQuest->GetQuestId() == QUEST_ID_PRECARIOUS_PREDICAMENT)
{
if (npc_grark_lorkrubAI* pEscortAI = dynamic_cast<npc_grark_lorkrubAI*>(pCreature->AI()))
{
pEscortAI->Start(false, pPlayer, pQuest);
}
return true;
}
return false;
}
bool EffectDummyCreature_spell_capture_grark(Unit* /*pCaster*/, uint32 uiSpellId, SpellEffectIndex uiEffIndex, Creature* pCreatureTarget, ObjectGuid /*originalCasterGuid*/)
{
// always check spellid and effectindex
if (uiSpellId == SPELL_CAPTURE_GRARK && uiEffIndex == EFFECT_INDEX_0)
{
// Note: this implementation needs additional research! There is a lot of guesswork involved in this!
if (pCreatureTarget->GetHealthPercent() > 25.0f)
{
return false;
}
// The faction is guesswork - needs more research
DoScriptText(EMOTE_SUBMIT, pCreatureTarget);
pCreatureTarget->SetFactionTemporary(FACTION_FRIENDLY, TEMPFACTION_RESTORE_RESPAWN);
pCreatureTarget->AI()->EnterEvadeMode();
// always return true when we are handling this spell and effect
return true;
}
return false;
}
void AddSC_burning_steppes()
{
Script* pNewScript;
pNewScript = new Script;
pNewScript->Name = "npc_ragged_john";
pNewScript->GetAI = &GetAI_npc_ragged_john;
pNewScript->pGossipHello = &GossipHello_npc_ragged_john;
pNewScript->pGossipSelect = &GossipSelect_npc_ragged_john;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "npc_grark_lorkrub";
pNewScript->GetAI = &GetAI_npc_grark_lorkrub;
pNewScript->pQuestAcceptNPC = &QuestAccept_npc_grark_lorkrub;
pNewScript->pEffectDummyNPC = &EffectDummyCreature_spell_capture_grark;
pNewScript->RegisterSelf();
}
| 412 | 0.958535 | 1 | 0.958535 | game-dev | MEDIA | 0.96499 | game-dev | 0.952565 | 1 | 0.952565 |
Cataclysm-TLG/Cataclysm-TLG | 64,023 | src/avatar.cpp | #include "avatar.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <functional>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <utility>
#include "action.h"
#include "activity_actor_definitions.h"
#include "avatar_action.h"
#include "bodypart.h"
#include "calendar.h"
#include "cata_assert.h"
#include "cata_utility.h"
#include "catacharset.h"
#include "character.h"
#include "character_id.h"
#include "character_martial_arts.h"
#include "color.h"
#include "creature.h"
#include "cursesdef.h"
#include "debug.h"
#include "diary.h"
#include "effect.h"
#include "enums.h"
#include "event.h"
#include "event_bus.h"
#include "faction.h"
#include "field_type.h"
#include "flag.h"
#include "flexbuffer_json-inl.h"
#include "flexbuffer_json.h"
#include "game.h"
#include "game_constants.h"
#include "game_inventory.h"
#include "help.h"
#include "inventory.h"
#include "item.h"
#include "item_location.h"
#include "itype.h"
#include "iuse.h"
#include "json.h"
#include "line.h"
#include "map.h"
#include "map_memory.h"
#include "mapdata.h"
#include "martialarts.h"
#include "messages.h"
#include "mission.h"
#include "move_mode.h"
#include "mutation.h"
#include "npc.h"
#include "output.h"
#include "overmap.h"
#include "overmapbuffer.h"
#include "pathfinding.h"
#include "pimpl.h"
#include "profession.h"
#include "ranged.h"
#include "recipe.h"
#include "ret_val.h"
#include "rng.h"
#include "scenario.h"
#include "skill.h"
#include "sleep.h"
#include "stomach.h"
#include "string_formatter.h"
#include "talker.h"
#include "talker_avatar.h"
#include "timed_event.h"
#include "translations.h"
#include "trap.h"
#include "type_id.h"
#include "ui.h"
#include "units.h"
#include "value_ptr.h"
#include "veh_type.h"
#include "vehicle.h"
#include "vpart_position.h"
static const bionic_id bio_cloak( "bio_cloak" );
static const bionic_id bio_sleep_shutdown( "bio_sleep_shutdown" );
static const efftype_id effect_alarm_clock( "alarm_clock" );
static const efftype_id effect_boomered( "boomered" );
static const efftype_id effect_depressants( "depressants" );
static const efftype_id effect_happy( "happy" );
static const efftype_id effect_irradiated( "irradiated" );
static const efftype_id effect_narcosis( "narcosis" );
static const efftype_id effect_onfire( "onfire" );
static const efftype_id effect_pkill( "pkill" );
static const efftype_id effect_psi_stunned( "psi_stunned" );
static const efftype_id effect_relax_gas( "relax_gas" );
static const efftype_id effect_sad( "sad" );
static const efftype_id effect_sleep( "sleep" );
static const efftype_id effect_sleep_deprived( "sleep_deprived" );
static const efftype_id effect_slept_through_alarm( "slept_through_alarm" );
static const efftype_id effect_stim( "stim" );
static const efftype_id effect_stim_overdose( "stim_overdose" );
static const efftype_id effect_stunned( "stunned" );
static const faction_id faction_your_followers( "your_followers" );
static const itype_id itype_guidebook( "guidebook" );
static const itype_id itype_mut_longpull( "mut_longpull" );
static const json_character_flag json_flag_ALARMCLOCK( "ALARMCLOCK" );
static const json_character_flag json_flag_PAIN_IMMUNE( "PAIN_IMMUNE" );
static const json_character_flag json_flag_WEBBED_HANDS( "WEBBED_HANDS" );
static const mfaction_str_id monfaction_player( "player" );
static const morale_type morale_food_good( "morale_food_good" );
static const morale_type morale_food_hot( "morale_food_hot" );
static const morale_type morale_honey( "morale_honey" );
static const morale_type morale_vomited( "morale_vomited" );
static const move_mode_id move_mode_crouch( "crouch" );
static const move_mode_id move_mode_prone( "prone" );
static const move_mode_id move_mode_run( "run" );
static const move_mode_id move_mode_walk( "walk" );
static const trait_id trait_ARACHNID_ARMS( "ARACHNID_ARMS" );
static const trait_id trait_ARACHNID_ARMS_OK( "ARACHNID_ARMS_OK" );
static const trait_id trait_CHITIN2( "CHITIN2" );
static const trait_id trait_CHITIN3( "CHITIN3" );
static const trait_id trait_CHITIN_FUR3( "CHITIN_FUR3" );
static const trait_id trait_COMPOUND_EYES( "COMPOUND_EYES" );
static const trait_id trait_DEBUG_CLOAK( "DEBUG_CLOAK" );
static const trait_id trait_INSECT_ARMS( "INSECT_ARMS" );
static const trait_id trait_INSECT_ARMS_OK( "INSECT_ARMS_OK" );
static const trait_id trait_PROF_DICEMASTER( "PROF_DICEMASTER" );
static const trait_id trait_SHELL2( "SHELL2" );
static const trait_id trait_SHELL3( "SHELL3" );
static const trait_id trait_STIMBOOST( "STIMBOOST" );
static const trait_id trait_THICK_SCALES( "THICK_SCALES" );
static const trait_id trait_WHISKERS( "WHISKERS" );
static const trait_id trait_WHISKERS_RAT( "WHISKERS_RAT" );
avatar::avatar()
{
player_map_memory = std::make_unique<map_memory>();
show_map_memory = true;
active_mission = nullptr;
grab_type = object_type::NONE;
calorie_diary.emplace_front( );
a_diary = nullptr;
}
avatar::~avatar() = default;
// NOLINTNEXTLINE(performance-noexcept-move-constructor)
avatar::avatar( avatar && ) = default;
// NOLINTNEXTLINE(performance-noexcept-move-constructor)
avatar &avatar::operator=( avatar && ) = default;
void avatar::control_npc( npc &np, const bool debug )
{
if( !np.is_player_ally() ) {
debugmsg( "control_npc() called on non-allied npc %s", np.name );
return;
}
// Switching to sleeping NPCs causes problems. We want to wake them up,
// but not if they're sedated.
if( np.has_effect( effect_narcosis ) ) {
debugmsg( "control_npc() called on sedated npc %s.", np.name );
return;
}
np.wake_up();
character_id new_character = np.getID();
const std::function<void( npc & )> update_npc = [new_character]( npc & guy ) {
guy.update_missions_target( get_avatar().getID(), new_character );
};
overmap_buffer.foreach_npc( update_npc );
mission().update_world_missions_character( get_avatar().getID(), new_character );
// move avatar character data into shadow npc
swap_character( get_shadow_npc() );
// swap target npc with shadow npc
std::swap( get_shadow_npc(), np );
// move shadow npc character data into avatar
swap_character( get_shadow_npc() );
// the avatar character is no longer a follower NPC
g->remove_npc_follower( getID() );
// the previous avatar character is now a follower
g->add_npc_follower( np.getID() );
np.set_fac( faction_your_followers );
// perception and mutations may have changed, so reset light level caches
g->reset_light_level();
// center the map on the new avatar character
const bool z_level_changed = g->vertical_shift( posz() );
g->update_map( *this, z_level_changed );
character_mood_face( true );
profession_id prof_id = prof ? prof->ident() : profession::generic()->ident();
get_event_bus().send<event_type::game_avatar_new>( /*is_new_game=*/false, debug,
getID(), name, male, prof_id, custom_profession );
}
void avatar::control_npc_menu( const bool debug )
{
std::vector<shared_ptr_fast<npc>> followers;
uilist charmenu;
int charnum = 0;
for( const character_id &elem : g->get_follower_list() ) {
shared_ptr_fast<npc> follower = overmap_buffer.find_npc( elem );
if( follower && !follower->has_effect( effect_narcosis ) ) {
followers.emplace_back( follower );
charmenu.addentry( charnum++, true, MENU_AUTOASSIGN, follower->get_name() );
}
if( follower && ( follower->has_effect( effect_narcosis ) || ( follower->in_sleep_state() &&
follower->has_bionic( bio_sleep_shutdown ) ) ) ) {
followers.emplace_back( follower );
std::string reason = _( " (unavailable)" );
charmenu.addentry( charnum++, false, MENU_AUTOASSIGN, follower->get_name() + reason );
}
}
if( followers.empty() ) {
popup( _( "There's no one to take control of!" ) );
return;
}
charmenu.w_y_setup = 0;
charmenu.query();
if( charmenu.ret < 0 || static_cast<size_t>( charmenu.ret ) >= followers.size() ) {
return;
}
get_avatar().control_npc( *followers[charmenu.ret], debug );
}
void avatar::longpull( const std::string &name )
{
item wtmp( itype_mut_longpull );
g->temp_exit_fullscreen();
target_handler::trajectory traj = target_handler::mode_throw( *this, wtmp, false );
g->reenter_fullscreen();
if( traj.empty() ) {
return; // cancel
}
Creature::longpull( name, traj.back() );
}
void avatar::toggle_map_memory()
{
show_map_memory = !show_map_memory;
}
bool avatar::is_map_memory_valid() const
{
return player_map_memory->is_valid();
}
bool avatar::should_show_map_memory() const
{
if( get_timed_events().get( timed_event_type::OVERRIDE_PLACE ) ) {
return false;
}
return show_map_memory;
}
bool avatar::save_map_memory()
{
return player_map_memory->save( pos_abs() );
}
void avatar::load_map_memory()
{
player_map_memory->load( pos_abs() );
}
void avatar::prepare_map_memory_region( const tripoint_abs_ms &p1, const tripoint_abs_ms &p2 )
{
player_map_memory->prepare_region( p1, p2 );
}
const memorized_tile &avatar::get_memorized_tile( const tripoint_abs_ms &p ) const
{
if( should_show_map_memory() ) {
return player_map_memory->get_tile( p );
}
return mm_submap::default_tile;
}
void avatar::memorize_terrain( const tripoint_abs_ms &p, const std::string_view id,
int subtile, int rotation )
{
player_map_memory->set_tile_terrain( p, id, subtile, rotation );
}
void avatar::memorize_decoration( const tripoint_abs_ms &p, const std::string_view id,
int subtile, int rotation )
{
player_map_memory->set_tile_decoration( p, id, subtile, rotation );
}
void avatar::memorize_symbol( const tripoint_abs_ms &p, char32_t symbol )
{
player_map_memory->set_tile_symbol( p, symbol );
}
void avatar::memorize_clear_decoration( const tripoint_abs_ms &p, std::string_view prefix )
{
player_map_memory->clear_tile_decoration( p, prefix );
}
std::vector<mission *> avatar::get_active_missions() const
{
return active_missions;
}
std::vector<mission *> avatar::get_completed_missions() const
{
return completed_missions;
}
std::vector<mission *> avatar::get_failed_missions() const
{
return failed_missions;
}
mission *avatar::get_active_mission() const
{
return active_mission;
}
void avatar::reset_all_missions()
{
active_mission = nullptr;
active_missions.clear();
completed_missions.clear();
failed_missions.clear();
}
tripoint_abs_omt avatar::get_active_mission_target() const
{
if( active_mission == nullptr ) {
return tripoint_abs_omt::invalid;
}
return active_mission->get_target();
}
void avatar::set_active_mission( mission &cur_mission )
{
const auto iter = std::find( active_missions.begin(), active_missions.end(), &cur_mission );
if( iter == active_missions.end() ) {
debugmsg( "new active mission %s is not in the active_missions list",
cur_mission.mission_id().c_str() );
} else {
active_mission = &cur_mission;
}
}
void avatar::on_mission_assignment( mission &new_mission )
{
active_missions.push_back( &new_mission );
set_active_mission( new_mission );
}
void avatar::on_mission_finished( mission &cur_mission )
{
if( cur_mission.has_failed() ) {
if( !cur_mission.get_type().invisible_on_complete ) {
failed_missions.push_back( &cur_mission );
}
add_msg_if_player( m_bad, _( "Mission \"%s\" is failed." ), cur_mission.name() );
} else {
if( !cur_mission.get_type().invisible_on_complete ) {
completed_missions.push_back( &cur_mission );
}
add_msg_if_player( m_good, _( "Mission \"%s\" is successfully completed." ),
cur_mission.name() );
}
const auto iter = std::find( active_missions.begin(), active_missions.end(), &cur_mission );
if( iter == active_missions.end() ) {
debugmsg( "completed mission %s was not in the active_missions list",
cur_mission.mission_id().c_str() );
} else {
active_missions.erase( iter );
}
if( &cur_mission == active_mission ) {
if( active_missions.empty() ) {
active_mission = nullptr;
} else {
active_mission = active_missions.front();
}
}
}
bool avatar::has_mission_id( const mission_type_id &miss_id )
{
for( mission *miss : active_missions ) {
if( miss->mission_id() == miss_id ) {
return true;
}
}
return false;
}
void avatar::remove_active_mission( mission &cur_mission )
{
cur_mission.remove_active_world_mission( cur_mission );
const auto iter = std::find( active_missions.begin(), active_missions.end(), &cur_mission );
if( iter == active_missions.end() ) {
debugmsg( "removed mission %s was not in the active_missions list",
cur_mission.mission_id().c_str() );
} else {
active_missions.erase( iter );
}
if( &cur_mission == active_mission ) {
if( active_missions.empty() ) {
active_mission = nullptr;
} else {
active_mission = active_missions.front();
}
}
}
diary *avatar::get_avatar_diary()
{
if( a_diary == nullptr ) {
a_diary = std::make_unique<diary>();
}
return a_diary.get();
}
bool avatar::read( item_location &book, item_location ereader )
{
if( !book ) {
add_msg( m_info, _( "Never mind." ) );
return false;
}
std::vector<std::string> fail_messages;
const Character *reader = get_book_reader( *book, fail_messages );
if( reader == nullptr ) {
// We can't read, and neither can our followers
for( const std::string &reason : fail_messages ) {
add_msg( m_bad, reason );
}
return false;
}
// spells are handled in a different place
// src/iuse_actor.cpp -> learn_spell_actor::use
if( book->get_use( "learn_spell" ) ) {
book->get_use( "learn_spell" )->call( this, *book, pos_bub() );
return true;
}
bool continuous = false;
const time_duration time_taken = time_to_read( *book, *reader );
add_msg_debug( debugmode::DF_ACT_READ, "avatar::read time_taken = %s",
to_string_writable( time_taken ) );
// If the player hasn't read this book before, skim it to get an idea of what's in it.
if( !has_identified( book->typeId() ) ) {
if( reader != this ) {
add_msg( m_info, fail_messages[0] );
add_msg( m_info, _( "%s reads aloud…" ), reader->disp_name() );
}
assign_activity( read_activity_actor( time_taken, book, ereader, false ) );
return true;
}
if( book->typeId() == itype_guidebook ) {
// special guidebook effect: print a misc. hint when read
if( reader != this ) {
add_msg( m_info, fail_messages[0] );
dynamic_cast<const npc &>( *reader ).say( get_hint() );
} else {
add_msg( m_info, get_hint() );
}
get_event_bus().send<event_type::reads_book>( getID(), book->typeId() );
mod_moves( -100 );
return false;
}
const cata::value_ptr<islot_book> &type = book->type->book;
const skill_id &skill = type->skill;
const std::string skill_name = skill ? skill.obj().name() : "";
// Find NPCs to join the study session:
std::map<Character *, std::string> learners;
//reading only for fun
std::map<Character *, std::string> fun_learners;
std::map<Character *, std::string> nonlearners;
for( Character *elem : get_crafting_helpers() ) {
const book_mastery mastery = elem->get_book_mastery( *book );
const bool morale_req = elem->fun_to_read( *book ) || elem->has_morale_to_read();
// Note that the reader cannot be a nonlearner
// since a reader should always have enough morale to read
// and at the very least be able to understand the book
if( elem->is_deaf() && elem != reader ) {
nonlearners.insert( { elem, _( " (deaf)" ) } );
} else if( mastery == book_mastery::MASTERED && elem->fun_to_read( *book ) ) {
fun_learners.insert( {elem, elem == reader ? _( " (reading aloud to you)" ) : "" } );
} else if( mastery == book_mastery::LEARNING && morale_req ) {
learners.insert( {elem, elem == reader ? _( " (reading aloud to you)" ) : ""} );
} else {
std::string reason = _( " (uninterested)" );
if( !morale_req ) {
reason = _( " (too sad)" );
} else if( mastery == book_mastery::CANT_UNDERSTAND ) {
reason = string_format( _( " (needs %d %s)" ), type->req, skill_name );
} else if( mastery == book_mastery::MASTERED ) {
reason = string_format( _( " (already has %d %s)" ), type->level, skill_name );
}
nonlearners.insert( { elem, reason } );
}
}
int learner_id = -1;
const bool is_martialarts = book->type->use_methods.count( "MA_MANUAL" );
//only show the menu if there's useful information or multiple options
if( ( skill || !nonlearners.empty() || !fun_learners.empty() ) && !is_martialarts ) {
uilist menu;
// Some helpers to reduce repetition:
auto length = []( const std::pair<Character *, std::string> &elem ) {
return utf8_width( elem.first->disp_name() ) + utf8_width( elem.second );
};
auto max_length = [&length]( const std::map<Character *, std::string> &m ) {
auto max_ele = std::max_element( m.begin(),
m.end(), [&length]( const std::pair<Character *, std::string> &left,
const std::pair<Character *, std::string> &right ) {
return length( left ) < length( right );
} );
return max_ele == m.end() ? 0 : length( *max_ele );
};
auto get_text = [&]( const std::map<Character *, std::string> &m,
const std::pair<Character *, std::string> &elem
) {
const int lvl = elem.first->get_knowledge_level( skill );
const std::string lvl_text = skill ? string_format( _( " | current level: %d" ), lvl ) : "";
const std::string name_text = elem.first->disp_name() + elem.second;
return string_format( "%s%s", left_justify( name_text, max_length( m ) ), lvl_text );
};
auto add_header = [&menu]( const std::string & str ) {
menu.addentry( -1, false, -1, "" );
uilist_entry header( -1, false, -1, str, c_yellow, c_yellow );
header.force_color = true;
menu.entries.push_back( header );
};
menu.title = !skill ? string_format( _( "Reading %s" ), book->type_name() ) :
//~ %1$s: book name, %2$s: skill name, %3$d and %4$d: skill levels
string_format( _( "Reading %1$s (can train %2$s from %3$d to %4$d)" ), book->type_name(),
skill_name, type->req, type->level );
menu.addentry( 0, true, '0', _( "Read once" ) );
const int lvl = get_knowledge_level( skill );
menu.addentry( 2 + getID().get_value(), lvl < type->level, '1',
string_format( _( "Read until you gain a level | current level: %d" ), lvl ) );
// select until player gets level by default
if( lvl < type->level ) {
menu.selected = 1;
}
if( !learners.empty() ) {
add_header( _( "Read until this character gains a level:" ) );
for( const std::pair<Character *const, std::string> &elem : learners ) {
menu.addentry( 2 + elem.first->getID().get_value(), true, -1,
get_text( learners, elem ) );
}
}
if( !fun_learners.empty() ) {
add_header( _( "Reading for fun:" ) );
for( const std::pair<Character *const, std::string> &elem : fun_learners ) {
menu.addentry( -1, false, -1, get_text( fun_learners, elem ) );
}
}
if( !nonlearners.empty() ) {
add_header( _( "Not participating:" ) );
for( const std::pair<Character *const, std::string> &elem : nonlearners ) {
menu.addentry( -1, false, -1, get_text( nonlearners, elem ) );
}
}
menu.query( true );
if( menu.ret == UILIST_CANCEL ) {
add_msg( m_info, _( "Never mind." ) );
return false;
} else if( menu.ret >= 2 ) {
continuous = true;
learner_id = menu.ret - 2;
}
}
if( is_martialarts ) {
if( martial_arts_data->has_martialart( martial_art_learned_from( *book->type ) ) ) {
add_msg_if_player( m_info, _( "You already know all this book has to teach." ) );
return false;
}
uilist menu;
menu.title = string_format( _( "Train %s from manual:" ),
martial_art_learned_from( *book->type )->name );
menu.addentry( 1, true, '1', _( "Train once" ) );
menu.addentry( 2, true, '0', _( "Train until tired or success" ) );
menu.query( true );
if( menu.ret == UILIST_CANCEL ) {
add_msg( m_info, _( "Never mind." ) );
return false;
} else if( menu.ret == 1 ) {
continuous = false;
} else { // menu.ret == 2
continuous = true;
}
}
add_msg( m_info, _( "Now reading %s, %s to stop early." ),
book->type_name(), press_x( ACTION_PAUSE ) );
// Print some informational messages
if( reader != this ) {
add_msg( m_info, fail_messages[0] );
add_msg( m_info, _( "%s reads aloud…" ), reader->disp_name() );
} else if( !learners.empty() || !fun_learners.empty() ) {
add_msg( m_info, _( "You read aloud…" ) );
}
if( learners.size() == 1 ) {
add_msg( m_info, _( "%s studies with you." ), learners.begin()->first->disp_name() );
} else if( !learners.empty() ) {
const std::string them = enumerate_as_string( learners.begin(),
learners.end(), [&]( const std::pair<Character *, std::string> &elem ) {
return elem.first->disp_name();
} );
add_msg( m_info, _( "%s study with you." ), them );
}
// Don't include the reader as it would be too redundant.
std::set<std::string> readers;
for( const std::pair<Character *const, std::string> &elem : fun_learners ) {
if( elem.first != reader ) {
readers.insert( elem.first->disp_name() );
}
}
if( readers.size() == 1 ) {
add_msg( m_info, _( "%s reads with you for fun." ), readers.begin()->c_str() );
} else if( !readers.empty() ) {
const std::string them = enumerate_as_string( readers );
add_msg( m_info, _( "%s read with you for fun." ), them );
}
if( !book->has_flag( flag_CAN_USE_IN_DARK ) &&
std::min( fine_detail_vision_mod(), reader->fine_detail_vision_mod() ) > 1.0 ) {
add_msg( m_warning,
_( "It's difficult for %s to see fine details right now. Reading will take longer than usual." ),
reader->disp_name() );
}
const int intelligence = get_int();
const bool complex_penalty = type->intel > std::min( intelligence, reader->get_int() ) &&
!reader->has_trait( trait_PROF_DICEMASTER );
const Character *complex_player = reader->get_int() < intelligence ? reader : this;
if( complex_penalty ) {
add_msg( m_warning,
_( "This book is too complex for %s to easily understand. It will take longer to read." ),
complex_player->disp_name() );
}
// push an identifier of martial art book to the action handling
if( is_martialarts &&
get_stamina() < get_stamina_max() / 10 ) {
add_msg( m_info, _( "You are too exhausted to train martial arts." ) );
return false;
}
assign_activity( read_activity_actor( time_taken, book, ereader, continuous, learner_id ) );
return true;
}
void avatar::grab( object_type grab_type_new, const tripoint_rel_ms &grab_point_new )
{
const auto update_memory =
[this]( const object_type gtype, const tripoint_rel_ms & gpoint, const bool erase ) {
map &m = get_map();
if( gtype == object_type::VEHICLE ) {
if( const optional_vpart_position ovp = m.veh_at( pos_bub() + gpoint ) ) {
for( const tripoint_abs_ms &target : ovp->vehicle().get_points() ) {
if( erase ) {
memorize_clear_decoration( target, /* prefix = */ "vp_" );
}
m.memory_cache_dec_set_dirty( m.get_bub( target ), true );
}
}
} else if( gtype != object_type::NONE ) {
if( erase ) {
memorize_clear_decoration( m.get_abs( pos_bub() + gpoint ) );
}
m.memory_cache_dec_set_dirty( pos_bub() + gpoint, true );
}
};
// Mark the area covered by the previous vehicle/furniture/etc for re-memorizing.
update_memory( grab_type, grab_point, /* erase = */ false );
grab_type = grab_type_new;
grab_point = grab_point_new;
// Clear the map memory for the area covered by the vehicle/furniture/etc to
// eliminate ghost vehicles/furnitures/etc.
update_memory( grab_type, grab_point, /* erase = */ true );
path_settings->avoid_rough_terrain = grab_type != object_type::NONE;
}
object_type avatar::get_grab_type() const
{
return grab_type;
}
bool avatar::has_identified( const itype_id &item_id ) const
{
return items_identified.count( item_id ) > 0;
}
void avatar::identify( const item &item )
{
if( has_identified( item.typeId() ) ) {
return;
}
if( !item.is_identifiable() ) {
debugmsg( "tried to identify non-book item" );
return;
}
const ::item &book = item; // alias
cata_assert( !has_identified( item.typeId() ) );
items_identified.insert( item.typeId() );
cata_assert( has_identified( item.typeId() ) );
const auto &reading = item.type->book;
const skill_id &skill = reading->skill;
add_msg( _( "You skim %s to find out what's in it." ), book.type_name() );
if( skill ) {
add_msg( m_info, _( "Can bring your %s knowledge to %d." ),
skill.obj().name(), reading->level );
if( reading->req != 0 ) {
add_msg( m_info, _( "Requires %1$s knowledge level %2$d to understand." ),
skill.obj().name(), reading->req );
}
}
if( reading->intel != 0 ) {
add_msg( m_info, _( "Requires intelligence of %d to easily read." ), reading->intel );
}
//It feels wrong to use a pointer to *this, but I can't find any other player pointers in this method.
if( book_fun_for( book, *this ) != 0 ) {
add_msg( m_info, _( "Reading this book affects your morale by %d." ), book_fun_for( book, *this ) );
}
if( book.type->use_methods.count( "MA_MANUAL" ) ) {
const matype_id style_to_learn = martial_art_learned_from( *book.type );
add_msg( m_info, _( "You can learn %s style from it." ), style_to_learn->name );
add_msg( m_info, _( "This fighting style is %s to learn." ),
martialart_difficulty( style_to_learn ) );
add_msg( m_info, _( "It would be easier to master if you'd have skill expertise in %s." ),
style_to_learn->primary_skill->name() );
add_msg( m_info, _( "A training session with this book takes %s." ),
to_string_clipped( reading->time ) );
} else {
add_msg( m_info, _( "A chapter of this book takes %s to read." ),
to_string_clipped( reading->time ) );
}
std::vector<std::string> crafting_recipes;
std::vector<std::string> practice_recipes;
for( const islot_book::recipe_with_description_t &elem : reading->recipes ) {
// If the player knows it, they recognize it even if it's not clearly stated.
if( elem.is_hidden() && !knows_recipe( elem.recipe ) ) {
continue;
}
if( elem.recipe->is_practice() ) {
practice_recipes.emplace_back( elem.recipe->result_name() );
} else {
crafting_recipes.emplace_back( elem.name() );
}
}
if( !crafting_recipes.empty() ) {
add_msg( m_info, string_format( _( "This book can help you craft: %s" ),
enumerate_as_string( crafting_recipes ) ) );
}
if( !practice_recipes.empty() ) {
add_msg( m_info, string_format( _( "This book can help you practice: %s" ),
enumerate_as_string( practice_recipes ) ) );
}
const std::size_t num_total_recipes = crafting_recipes.size() + practice_recipes.size();
if( num_total_recipes < reading->recipes.size() ) {
add_msg( m_info, _( "It might help you figuring out some more recipes." ) );
}
}
void avatar::clear_nutrition()
{
calorie_diary.clear();
calorie_diary.emplace_front();
consumption_history.clear();
}
void avatar::clear_identified()
{
items_identified.clear();
}
void avatar::wake_up()
{
if( has_effect( effect_sleep ) ) {
// alarm was set and player hasn't slept through the alarm.
if( has_effect( effect_alarm_clock ) && !has_effect( effect_slept_through_alarm ) ) {
add_msg( _( "It looks like you woke up before your alarm." ) );
// effects will be removed in Character::wake_up.
} else if( has_effect( effect_slept_through_alarm ) ) {
if( has_flag( json_flag_ALARMCLOCK ) ) {
add_msg( m_warning, _( "It looks like you've slept through your internal alarm…" ) );
} else {
add_msg( m_warning, _( "It looks like you've slept through the alarm…" ) );
}
}
}
Character::wake_up();
}
void avatar::add_snippet( snippet_id snippet )
{
if( has_seen_snippet( snippet ) ) {
return;
}
snippets_read.emplace( snippet );
}
bool avatar::has_seen_snippet( const snippet_id &snippet ) const
{
return snippets_read.count( snippet ) > 0;
}
const std::set<snippet_id> &avatar::get_snippets()
{
return snippets_read;
}
void avatar::vomit()
{
if( stomach.contains() != 0_ml ) {
// Remove all joy from previously eaten food and apply the penalty
rem_morale( morale_food_good );
rem_morale( morale_food_hot );
// bears must suffer too
rem_morale( morale_honey );
// 1.5 times longer
add_morale( morale_vomited, -2 * units::to_milliliter( stomach.contains() / 50 ), -40, 90_minutes,
45_minutes, false );
} else {
add_msg( m_warning, _( "You retched, but your stomach is empty." ) );
}
Character::vomit();
}
bool avatar::try_break_relax_gas( const std::string &msg_success, const std::string &msg_failure )
{
const effect &pacify = get_effect( effect_relax_gas, body_part_mouth );
if( pacify.is_null() ) {
return true;
} else if( one_in( pacify.get_intensity() ) ) {
add_msg( m_good, msg_success );
return true;
} else {
mod_moves( std::max( 0, pacify.get_intensity() * 10 + rng( -30, 30 ) ) );
add_msg( m_bad, msg_failure );
return false;
}
}
nc_color avatar::basic_symbol_color() const
{
bool in_shell = has_active_mutation( trait_SHELL2 ) ||
has_active_mutation( trait_SHELL3 );
if( has_effect( effect_onfire ) ) {
return c_red;
}
if( has_effect( effect_stunned ) ) {
return c_light_blue;
}
if( has_effect( effect_psi_stunned ) ) {
return c_light_blue;
}
if( has_effect( effect_boomered ) ) {
return c_pink;
}
if( in_shell ) {
return c_magenta;
}
if( underwater ) {
return c_blue;
}
if( has_active_bionic( bio_cloak ) ||
is_wearing_active_optcloak() || has_trait( trait_DEBUG_CLOAK ) ) {
return c_dark_gray;
}
return move_mode->symbol_color();
}
int avatar::print_info( const catacurses::window &w, int vStart, int, int column ) const
{
return vStart + fold_and_print( w, point( column, vStart ), getmaxx( w ) - column - 1, c_dark_gray,
_( "You (%s)" ),
get_name() ) - 1;
}
std::string avatar::display_name( bool possessive, bool capitalize_first ) const
{
if( !possessive ) {
return capitalize_first ? _( "You" ) : _( "you" );
} else {
return capitalize_first ? _( "Your" ) : _( "your" );
}
}
mfaction_id avatar::get_monster_faction() const
{
return monfaction_player.id();
}
void avatar::reset_stats()
{
const int current_stim = get_stim();
// Trait / mutation buffs
if( has_trait( trait_THICK_SCALES ) ) {
add_miss_reason( _( "Your thick scales get in the way." ), 2 );
}
if( has_trait( trait_CHITIN2 ) ) {
add_miss_reason( _( "Your chitin gets in the way." ), 1 );
}
if( has_trait( trait_COMPOUND_EYES ) && !wearing_something_on( bodypart_id( "eyes" ) ) ) {
mod_per_bonus( 2 );
}
if( has_trait( trait_INSECT_ARMS ) ) {
add_miss_reason( _( "Your insect limbs get in the way." ), 2 );
}
if( has_trait( trait_INSECT_ARMS_OK ) ) {
if( !wearing_fitting_on( bodypart_id( "torso" ) ) ) {
mod_dex_bonus( 1 );
} else {
add_miss_reason( _( "Your clothing restricts your insect arms." ), 1 );
}
}
if( has_flag( json_flag_WEBBED_HANDS ) ) {
add_miss_reason( _( "Your webbed hands get in the way." ), 1 );
}
if( has_trait( trait_ARACHNID_ARMS ) ) {
add_miss_reason( _( "Your arachnid limbs get in the way." ), 4 );
}
if( has_trait( trait_ARACHNID_ARMS_OK ) ) {
if( !wearing_fitting_on( bodypart_id( "torso" ) ) ) {
mod_dex_bonus( 2 );
} else {
add_miss_reason( _( "Your clothing constricts your arachnid limbs." ), 2 );
}
}
const auto set_fake_effect_dur = [this]( const efftype_id & type, const time_duration & dur ) {
effect &eff = get_effect( type );
if( eff.get_duration() == dur ) {
return;
}
if( eff.is_null() && dur > 0_turns ) {
add_effect( type, dur, true );
} else if( dur > 0_turns ) {
eff.set_duration( dur );
} else {
remove_effect( type );
}
};
// Painkiller
set_fake_effect_dur( effect_pkill, 1_turns * get_painkiller() );
// Pain
if( get_perceived_pain() > 0 ) {
const stat_mod ppen = get_pain_penalty();
ppen_str = ppen.strength;
ppen_dex = ppen.dexterity;
ppen_int = ppen.intelligence;
ppen_per = ppen.perception;
ppen_spd = ppen.speed;
mod_str_bonus( -ppen_str );
mod_dex_bonus( -ppen_dex );
mod_int_bonus( -ppen_int );
mod_per_bonus( -ppen_per );
if( ppen.dexterity > 0 ) {
add_miss_reason( _( "Your pain distracts you!" ), static_cast<unsigned>( ppen.dexterity ) );
}
}
// Radiation
set_fake_effect_dur( effect_irradiated, 1_turns * get_rad() );
// Morale
const int morale = get_morale_level();
set_fake_effect_dur( effect_happy, 1_turns * morale );
set_fake_effect_dur( effect_sad, 1_turns * -morale );
// Stimulants
set_fake_effect_dur( effect_stim, 1_turns * current_stim );
set_fake_effect_dur( effect_depressants, 1_turns * -current_stim );
if( has_trait( trait_STIMBOOST ) ) {
set_fake_effect_dur( effect_stim_overdose, 1_turns * ( current_stim - 60 ) );
} else {
set_fake_effect_dur( effect_stim_overdose, 1_turns * ( current_stim - 30 ) );
}
// Starvation
const float bmi = get_bmi_fat();
if( bmi < character_weight_category::normal ) {
const int str_penalty = std::floor( ( 1.0f - ( get_bmi_fat() /
character_weight_category::normal ) ) * str_max );
const int dexint_penalty = std::floor( ( character_weight_category::normal - bmi ) * 3.0f );
add_miss_reason( _( "You're weak from hunger." ),
static_cast<unsigned>( ( get_starvation() + 300 ) / 1000 ) );
mod_str_bonus( -1 * str_penalty );
mod_dex_bonus( -1 * dexint_penalty );
mod_int_bonus( -1 * dexint_penalty );
}
// Thirst
if( get_thirst() >= 200 ) {
// We die at 1200
const int dex_mod = -get_thirst() / 200;
add_miss_reason( _( "You're weak from thirst." ), static_cast<unsigned>( -dex_mod ) );
mod_str_bonus( -get_thirst() / 200 );
mod_dex_bonus( dex_mod );
mod_int_bonus( -get_thirst() / 200 );
mod_per_bonus( -get_thirst() / 200 );
}
if( get_sleep_deprivation() >= SLEEP_DEPRIVATION_HARMLESS ) {
set_fake_effect_dur( effect_sleep_deprived, 1_turns * get_sleep_deprivation() );
} else if( has_effect( effect_sleep_deprived ) ) {
remove_effect( effect_sleep_deprived );
}
// Dodge-related effects
mod_dodge_bonus( mabuff_dodge_bonus() );
// Whiskers don't work so well if they're covered
if( has_trait( trait_WHISKERS ) && !natural_attack_restricted_on( bodypart_id( "mouth" ) ) ) {
mod_dodge_bonus( 1 );
}
if( has_trait( trait_WHISKERS_RAT ) && !natural_attack_restricted_on( bodypart_id( "mouth" ) ) ) {
mod_dodge_bonus( 2 );
}
// depending on mounts size, attacks will hit the mount and use their dodge rating.
// if they hit the player, the player cannot dodge as effectively.
if( is_mounted() ) {
mod_dodge_bonus( -4 );
}
// Apply static martial arts buffs
martial_arts_data->ma_static_effects( *this );
// Effects
for( const auto &maps : *effects ) {
for( const auto &i : maps.second ) {
const effect &it = i.second;
bool reduced = resists_effect( it );
mod_str_bonus( it.get_mod( "STR", reduced ) );
mod_dex_bonus( it.get_mod( "DEX", reduced ) );
mod_per_bonus( it.get_mod( "PER", reduced ) );
mod_int_bonus( it.get_mod( "INT", reduced ) );
}
}
Character::reset_stats();
recalc_sight_limits();
}
// based on D&D 5e level progression
static const std::array<int, 20> xp_cutoffs = { {
300, 900, 2700, 6500, 14000,
23000, 34000, 48000, 64000, 85000,
100000, 120000, 140000, 165000, 195000,
225000, 265000, 305000, 355000, 405000
}
};
int avatar::free_upgrade_points() const
{
int lvl = 0;
for( const int &xp_lvl : xp_cutoffs ) {
if( kill_xp >= xp_lvl ) {
lvl++;
} else {
break;
}
}
return lvl - spent_upgrade_points;
}
void avatar::upgrade_stat_prompt( const character_stat &stat )
{
const int free_points = free_upgrade_points();
if( free_points <= 0 ) {
const std::size_t lvl = spent_upgrade_points + free_points;
if( lvl >= xp_cutoffs.size() ) {
popup( _( "You've already reached maximum level." ) );
} else {
popup( _( "Needs %d more experience to gain next level." ), xp_cutoffs[lvl] - kill_xp );
}
return;
}
std::string stat_string;
switch( stat ) {
case character_stat::STRENGTH:
stat_string = _( "strength" );
break;
case character_stat::DEXTERITY:
stat_string = _( "dexterity" );
break;
case character_stat::INTELLIGENCE:
stat_string = _( "intelligence" );
break;
case character_stat::PERCEPTION:
stat_string = _( "perception" );
break;
case character_stat::DUMMY_STAT:
stat_string = _( "invalid stat" );
debugmsg( "Tried to use invalid stat" );
break;
default:
return;
}
if( query_yn( _( "Are you sure you want to raise %s? %d points available." ), stat_string,
free_points ) ) {
switch( stat ) {
case character_stat::STRENGTH:
str_max++;
spent_upgrade_points++;
recalc_hp();
break;
case character_stat::DEXTERITY:
dex_max++;
spent_upgrade_points++;
break;
case character_stat::INTELLIGENCE:
int_max++;
spent_upgrade_points++;
break;
case character_stat::PERCEPTION:
per_max++;
spent_upgrade_points++;
break;
case character_stat::DUMMY_STAT:
debugmsg( "Tried to use invalid stat" );
break;
}
}
}
faction *avatar::get_faction() const
{
return g->faction_manager_ptr->get( faction_your_followers );
}
bool avatar::is_ally( const Character &p ) const
{
if( p.getID() == getID() ) {
return true;
}
const npc &guy = dynamic_cast<const npc &>( p );
return guy.is_ally( *this );
}
bool avatar::is_obeying( const Character &p ) const
{
if( p.getID() == getID() ) {
return true;
}
const npc &guy = dynamic_cast<const npc &>( p );
return guy.is_obeying( *this );
}
bool avatar::cant_see( const tripoint_bub_ms &p ) const
{
// calc based on recoil
if( !last_target_pos.has_value() ) {
return false;
}
if( aim_cache_dirty ) {
rebuild_aim_cache();
}
return aim_cache[p.x()][p.y()];
}
void avatar::rebuild_aim_cache() const
{
map &here = get_map();
aim_cache_dirty =
false; // Can trigger recursive death spiral if still set when calc_steadiness is called.
double pi = 2 * acos( 0.0 );
const tripoint_bub_ms local_last_target = here.get_bub(
last_target_pos.value() );
const tripoint_bub_ms pos = pos_bub( here );
float base_angle = atan2f( local_last_target.y() - pos.y(),
local_last_target.x() - pos.x() );
// move from -pi to pi, to 0 to 2pi for angles
if( base_angle < 0 ) {
base_angle = base_angle + 2 * pi;
}
// todo: this is not the correct weapon when aiming with fake items
item *weapon = get_wielded_item() ? &*get_wielded_item() : &null_item_reference();
// calc steadiness with player recoil (like they are taking a regular shot not careful etc.
float range = 3.0f - 2.8f * calc_steadiness( *this, *weapon, local_last_target, recoil );
// pin between pi and negative pi
float upper_bound = base_angle + range;
float lower_bound = base_angle - range;
// cap each within 0 - 2pi
if( upper_bound > 2 * pi ) {
upper_bound = upper_bound - 2 * pi;
}
if( lower_bound < 0 ) {
lower_bound = lower_bound + 2 * pi;
}
for( int smx = 0; smx < MAPSIZE_X; ++smx ) {
for( int smy = 0; smy < MAPSIZE_Y; ++smy ) {
float current_angle = atan2f( smy - pos.y(), smx - pos.x() );
// move from -pi to pi, to 0 to 2pi for angles
if( current_angle < 0 ) {
current_angle = current_angle + 2 * pi;
}
// some basic angle inclusion math, but also everything with 15 is still seen
if( rl_dist( tripoint_bub_ms( smx, smy, posz() ), pos ) < 15 ) {
aim_cache[smx][smy] = false;
} else if( lower_bound > upper_bound ) {
aim_cache[smx][smy] = !( current_angle >= lower_bound ||
current_angle <= upper_bound );
} else {
aim_cache[smx][smy] = !( current_angle >= lower_bound &&
current_angle <= upper_bound );
}
}
}
// set cache as no longer dirty
}
void avatar::set_movement_mode( const move_mode_id &new_mode )
{
map &here = get_map();
if( can_switch_to( new_mode ) ) {
bool instant = true;
if( is_hauling() && new_mode->stop_hauling() ) {
stop_hauling();
}
add_msg( new_mode->change_message( true, get_steed_type() ) );
if(
(
( ( move_mode == move_mode_run || move_mode == move_mode_walk ) &&
( new_mode == move_mode_crouch || new_mode == move_mode_prone ) ) ||
( ( move_mode == move_mode_prone || move_mode == move_mode_crouch ) &&
( new_mode == move_mode_walk || new_mode == move_mode_run ) )
) &&
( move_mode != new_mode )
) {
instant = false;
}
move_mode = new_mode;
// Enchantments based on move modes can stack inappropriately without a recalc here
recalculate_enchantment_cache();
// crouching affects visibility
//TODO: Replace with dirtying vision_transparency_cache
here.set_transparency_cache_dirty( pos_bub() );
here.set_seen_cache_dirty( posz() );
recoil = MAX_RECOIL;
// TODO: Variable costs from traits, mutations, whether we were prone or crouching, limb scores.
if( !instant ) {
mod_moves( -100 );
}
} else {
add_msg( new_mode->change_message( false, get_steed_type() ) );
}
}
void avatar::toggle_run_mode()
{
if( is_running() ) {
set_movement_mode( move_mode_walk );
} else {
set_movement_mode( move_mode_run );
}
}
void avatar::toggle_crouch_mode()
{
if( is_crouching() ) {
set_movement_mode( move_mode_walk );
} else {
set_movement_mode( move_mode_crouch );
}
}
void avatar::toggle_prone_mode()
{
if( is_prone() ) {
set_movement_mode( move_mode_walk );
} else {
set_movement_mode( move_mode_prone );
}
}
void avatar::activate_crouch_mode()
{
if( !is_crouching() ) {
set_movement_mode( move_mode_crouch );
}
}
void avatar::reset_move_mode()
{
if( !is_walking() ) {
set_movement_mode( move_mode_walk );
}
}
void avatar::cycle_move_mode()
{
const move_mode_id next = current_movement_mode()->cycle();
set_movement_mode( next );
// if a movemode is disabled then just cycle to the next one
if( !movement_mode_is( next ) ) {
set_movement_mode( next->cycle() );
}
}
void avatar::cycle_move_mode_reverse()
{
const move_mode_id prev = current_movement_mode()->cycle_reverse();
set_movement_mode( prev );
// if a movemode is disabled then just cycle to the previous one
if( !movement_mode_is( prev ) ) {
set_movement_mode( prev->cycle_reverse() );
}
}
bool avatar::wield( item &it )
{
if( !avatar_action::check_stealing( *this, it ) ) {
return false;
}
return Character::wield( it );
}
bool avatar::wield( item_location loc, bool remove_old )
{
if( !avatar_action::check_stealing( *this, *loc ) ) {
return false;
}
return Character::wield( loc, remove_old );
}
item::reload_option avatar::select_ammo( const item_location &base, bool prompt,
bool empty )
{
if( !base ) {
return item::reload_option();
}
return game_menus::inv::select_ammo( *this, base, prompt, empty );
}
bool avatar::invoke_item( item *used, const tripoint_bub_ms &pt, int pre_obtain_moves )
{
const std::map<std::string, use_function> &use_methods = used->type->use_methods;
const int num_methods = use_methods.size();
const bool has_relic = used->has_relic_activation();
if( use_methods.empty() && !has_relic ) {
return false;
} else if( num_methods == 1 && !has_relic ) {
return invoke_item( used, use_methods.begin()->first, pt, pre_obtain_moves );
} else if( num_methods == 0 && has_relic ) {
return used->use_relic( *this, pt );
}
uilist umenu;
umenu.text = string_format( _( "What to do with your %s?" ), used->tname() );
umenu.hilight_disabled = true;
for( const auto &e : use_methods ) {
const auto res = e.second.can_call( *this, *used, pt );
umenu.addentry_desc( MENU_AUTOASSIGN, res.success(), MENU_AUTOASSIGN, e.second.get_name(),
res.str() );
}
if( has_relic ) {
umenu.addentry_desc( MENU_AUTOASSIGN, true, MENU_AUTOASSIGN, _( "Use relic" ),
_( "Activate this relic." ) );
}
umenu.desc_enabled = std::any_of( umenu.entries.begin(),
umenu.entries.end(), []( const uilist_entry & elem ) {
return !elem.desc.empty();
} );
umenu.query();
int choice = umenu.ret;
// Use the relic
if( choice == num_methods ) {
return used->use_relic( *this, pt );
}
if( choice < 0 || choice >= num_methods ) {
return false;
}
const std::string &method = std::next( use_methods.begin(), choice )->first;
return invoke_item( used, method, pt, pre_obtain_moves );
}
bool avatar::invoke_item( item *used )
{
return Character::invoke_item( used );
}
bool avatar::invoke_item( item *used, const std::string &method, const tripoint_bub_ms &pt,
int pre_obtain_moves )
{
if( pre_obtain_moves == -1 ) {
pre_obtain_moves = get_moves();
}
return Character::invoke_item( used, method, pt, pre_obtain_moves );
}
bool avatar::invoke_item( item *used, const std::string &method )
{
return Character::invoke_item( used, method );
}
void avatar::update_cardio_acc()
{
// This function should be called once every 24 hours,
// before the front of the calorie diary is reset for the next day.
// Cardio goal is 1000 times the ratio of kcals spent versus bmr,
// giving a default of 1000 for no extra activity.
const int bmr = get_bmr();
if( bmr == 0 ) {
set_cardio_acc( clamp( get_cardio_acc(), get_cardio_acc_base(), get_cardio_acc_base() * 3 ) );
return;
}
const int last_24h_kcal = calorie_diary.front().spent;
const int cardio_goal = ( last_24h_kcal * get_cardio_acc_base() ) / bmr;
// If cardio accumulator is below cardio goal, gain some cardio.
// Or, if cardio accumulator is above cardio goal, lose some cardio.
const int cardio_accum = get_cardio_acc();
int adjustment = 0;
if( cardio_accum > cardio_goal ) {
adjustment = -std::sqrt( cardio_accum - cardio_goal );
} else if( cardio_goal > cardio_accum ) {
adjustment = std::sqrt( cardio_goal - cardio_accum );
}
// Set a large sane upper limit to cardio fitness. This could be done
// asymptotically instead of as a sharp cutoff, but the gradual growth
// rate of cardio_acc should accomplish that naturally.
set_cardio_acc( clamp( cardio_accum + adjustment, get_cardio_acc_base(),
get_cardio_acc_base() * 3 ) );
}
void avatar::advance_daily_calories()
{
calorie_diary.emplace_front( );
if( calorie_diary.size() > 30 ) {
calorie_diary.pop_back();
}
}
int avatar::get_daily_spent_kcal( bool yesterday ) const
{
if( yesterday ) {
if( calorie_diary.size() < 2 ) {
return 0;
}
std::list<avatar::daily_calories> copy = calorie_diary;
copy.pop_front();
return copy.front().spent;
}
return calorie_diary.front().spent;
}
int avatar::get_daily_ingested_kcal( bool yesterday ) const
{
if( yesterday ) {
if( calorie_diary.size() < 2 ) {
return 0;
}
std::list<avatar::daily_calories> copy = calorie_diary;
copy.pop_front();
return copy.front().ingested;
}
return calorie_diary.front().ingested;
}
void avatar::add_ingested_kcal( int kcal )
{
calorie_diary.front().ingested += kcal;
}
void avatar::add_spent_calories( int cal )
{
calorie_diary.front().spent += cal;
}
void avatar::add_gained_calories( int cal )
{
calorie_diary.front().gained += cal;
}
int avatar::get_daily_calories( unsigned days_ago, std::string const &type ) const
{
auto iterator = calorie_diary.begin();
if( days_ago > calorie_diary.size() ) {
debugmsg(
"trying to access calorie diary from %d days ago, but the diary only contains %d days",
days_ago, calorie_diary.size() );
return 0;
}
std::advance( iterator, days_ago );
int result{};
if( type == "spent" ) {
result = iterator->spent;
} else if( type == "gained" ) {
result = iterator->gained;
} else if( type == "ingested" ) {
result = iterator->ingested;
} else if( type == "total" ) {
result = iterator->total();
}
return result;
}
void avatar::log_activity_level( float level )
{
calorie_diary.front().activity_levels[level]++;
}
avatar::daily_calories::daily_calories()
{
activity_levels.emplace( NO_EXERCISE, 0 );
activity_levels.emplace( LIGHT_EXERCISE, 0 );
activity_levels.emplace( MODERATE_EXERCISE, 0 );
activity_levels.emplace( BRISK_EXERCISE, 0 );
activity_levels.emplace( ACTIVE_EXERCISE, 0 );
activity_levels.emplace( EXTRA_EXERCISE, 0 );
activity_levels.emplace( EXPLOSIVE_EXERCISE, 0 );
}
void avatar::daily_calories::serialize( JsonOut &json ) const
{
json.start_object();
json.member( "spent", spent );
json.member( "gained", gained );
json.member( "ingested", ingested );
save_activity( json );
json.end_object();
}
void avatar::daily_calories::deserialize( const JsonObject &data )
{
data.read( "spent", spent );
data.read( "gained", gained );
data.read( "ingested", ingested );
if( data.has_member( "activity" ) ) {
read_activity( data );
}
}
void avatar::daily_calories::save_activity( JsonOut &json ) const
{
json.member( "activity" );
json.start_array();
for( const std::pair<const float, int> &level : activity_levels ) {
if( level.second > 0 ) {
json.start_array();
json.write( level.first );
json.write( level.second );
json.end_array();
}
}
json.end_array();
}
void avatar::daily_calories::read_activity( const JsonObject &data )
{
if( data.has_array( "activity" ) ) {
double act_level;
for( JsonArray ja : data.get_array( "activity" ) ) {
act_level = ja.next_float();
activity_levels[ act_level ] = ja.next_int();
}
return;
}
// Fallback to legacy format for backward compatibility
JsonObject jo = data.get_object( "activity" );
for( const std::pair<const std::string, float> &member : activity_levels_map ) {
int times;
if( !jo.read( member.first, times ) ) {
continue;
}
activity_levels.at( member.second ) = times;
}
}
std::string avatar::total_daily_calories_string() const
{
const std::string header_string =
colorize( " Minutes at each exercise level Calories per day",
c_white ) + "\n" +
colorize( " Day Sleep - Light Moderate Brisk Active Extra Explosive Gained Spent Total",
c_yellow ) + "\n";
const std::string format_string =
" %4d %4d %4d %4d %4d %4d %4d %4d %6d %6d";
const float no_ex_thresh = ( SLEEP_EXERCISE + NO_EXERCISE ) / 2.0f;
const float light_ex_thresh = ( NO_EXERCISE + LIGHT_EXERCISE ) / 2.0f;
const float mod_ex_thresh = ( LIGHT_EXERCISE + MODERATE_EXERCISE ) / 2.0f;
const float brisk_ex_thresh = ( MODERATE_EXERCISE + BRISK_EXERCISE ) / 2.0f;
const float active_ex_thresh = ( BRISK_EXERCISE + ACTIVE_EXERCISE ) / 2.0f;
const float extra_ex_thresh = ( ACTIVE_EXERCISE + ( EXTRA_EXERCISE ) ) / 2.0f;
const float explosive_ex_thresh = ( EXTRA_EXERCISE + ( EXPLOSIVE_EXERCISE ) ) / 2.0f;
std::string ret = header_string;
// Start with today in the first row, day number from start of the Cataclysm
int today = day_of_season<int>( calendar::turn ) + 1;
int day_offset = 0;
for( const daily_calories &day : calorie_diary ) {
// Yes, this is clunky.
// Perhaps it should be done in log_activity_level? But that's called a lot more often.
int sleep_exercise = 0;
int no_exercise = 0;
int light_exercise = 0;
int moderate_exercise = 0;
int brisk_exercise = 0;
int active_exercise = 0;
int extra_exercise = 0;
int explosive_exercise = 0;
for( const std::pair<const float, int> &level : day.activity_levels ) {
if( level.second > 0 ) {
if( level.first < no_ex_thresh ) {
sleep_exercise += level.second;
} else if( level.first < light_ex_thresh ) {
no_exercise += level.second;
} else if( level.first < mod_ex_thresh ) {
light_exercise += level.second;
} else if( level.first < brisk_ex_thresh ) {
moderate_exercise += level.second;
} else if( level.first < active_ex_thresh ) {
brisk_exercise += level.second;
} else if( level.first < extra_ex_thresh ) {
active_exercise += level.second;
} else if( level.first < explosive_ex_thresh ) {
extra_exercise += level.second;
} else {
explosive_exercise += level.second;
}
}
}
std::string row_data = string_format( format_string, today + day_offset--,
5 * sleep_exercise,
5 * no_exercise,
5 * light_exercise,
5 * moderate_exercise,
5 * brisk_exercise,
5 * active_exercise,
5 * extra_exercise,
5 * explosive_exercise,
day.gained, day.spent );
// Alternate gray and white text for row data
if( day_offset % 2 == 0 ) {
ret += colorize( row_data, c_white );
} else {
ret += colorize( row_data, c_light_gray );
}
// Color-code each day's net calories
std::string total_kcals = string_format( " %6d", day.total() );
if( day.total() > 4000 ) {
ret += colorize( total_kcals, c_light_cyan );
} else if( day.total() > 2000 ) {
ret += colorize( total_kcals, c_cyan );
} else if( day.total() > 250 ) {
ret += colorize( total_kcals, c_light_blue );
} else if( day.total() < -4000 ) {
ret += colorize( total_kcals, c_pink );
} else if( day.total() < -2000 ) {
ret += colorize( total_kcals, c_red );
} else if( day.total() < -250 ) {
ret += colorize( total_kcals, c_light_red );
} else {
ret += colorize( total_kcals, c_light_gray );
}
ret += "\n";
}
return ret;
}
std::unique_ptr<talker> get_talker_for( avatar &me )
{
return std::make_unique<talker_avatar>( &me );
}
std::unique_ptr<talker> get_talker_for( avatar *me )
{
return std::make_unique<talker_avatar>( me );
}
void avatar::reassign_item( item &it, int invlet )
{
bool remove_old = true;
if( invlet ) {
item *prev = invlet_to_item( invlet );
if( prev != nullptr ) {
remove_old = it.typeId() != prev->typeId();
inv->reassign_item( *prev, it.invlet, remove_old );
}
}
if( !invlet || inv_chars.valid( invlet ) ) {
const auto iter = inv->assigned_invlet.find( it.invlet );
bool found = iter != inv->assigned_invlet.end();
if( found ) {
inv->assigned_invlet.erase( iter );
}
if( invlet && ( !found || it.invlet != invlet ) ) {
inv->assigned_invlet[invlet] = it.typeId();
}
inv->reassign_item( it, invlet, remove_old );
}
}
void avatar::add_pain_msg( int val, const bodypart_id &bp ) const
{
if( has_flag( json_flag_PAIN_IMMUNE ) ) {
return;
}
if( bp == bodypart_str_id::NULL_ID() ) {
if( val > 20 ) {
add_msg_if_player( _( "Your body is wracked with excruciating pain!" ) );
} else if( val > 10 ) {
add_msg_if_player( _( "Your body is wracked with terrible pain!" ) );
} else if( val > 5 ) {
add_msg_if_player( _( "Your body is wracked with pain!" ) );
} else if( val > 1 ) {
add_msg_if_player( _( "Your body pains you!" ) );
} else {
add_msg_if_player( _( "Your body aches." ) );
}
} else {
if( val > 20 ) {
add_msg_if_player( _( "Your %s is wracked with excruciating pain!" ),
body_part_name_accusative( bp ) );
} else if( val > 10 ) {
add_msg_if_player( _( "Your %s is wracked with terrible pain!" ),
body_part_name_accusative( bp ) );
} else if( val > 5 ) {
add_msg_if_player( _( "Your %s is wracked with pain!" ),
body_part_name_accusative( bp ) );
} else if( val > 1 ) {
add_msg_if_player( _( "Your %s pains you!" ),
body_part_name_accusative( bp ) );
} else {
add_msg_if_player( _( "Your %s aches." ),
body_part_name_accusative( bp ) );
}
}
}
void avatar::try_to_sleep( const time_duration &dur )
{
get_comfort_at( pos_bub() ).add_try_msgs( *this );
add_msg_if_player( _( "You start trying to fall asleep." ) );
if( has_active_bionic( bio_sleep_shutdown ) ) {
bio_sleep_shutdown_powered_at_last_sleep_check = has_power();
if( bio_sleep_shutdown_powered_at_last_sleep_check ) {
add_msg_if_player( m_good, _( "Your sleep mode CBM starts working its magic." ) );
} else {
add_msg_if_player( m_bad, _( "Your sleep mode CBM doesn't have enough power to operate." ) );
}
}
assign_activity( try_sleep_activity_actor( dur ) );
}
bool avatar::query_yn( const std::string &mes ) const
{
return ::query_yn( mes );
}
void avatar::set_pos_abs_only( const tripoint_abs_ms &loc )
{
Creature::set_pos_abs_only( loc );
}
npc &avatar::get_shadow_npc()
{
if( !shadow_npc ) {
shadow_npc = std::make_unique<npc>();
shadow_npc->op_of_u.trust = 10;
shadow_npc->op_of_u.value = 10;
shadow_npc->set_attitude( NPCATT_FOLLOW );
}
return *shadow_npc;
}
void avatar::export_as_npc( const cata_path &path )
{
swap_character( get_shadow_npc() );
get_shadow_npc().export_to( path );
swap_character( get_shadow_npc() );
}
void monster_visible_info::remove_npc( npc *n )
{
for( auto &t : unique_types ) {
auto it = std::find( t.begin(), t.end(), n );
if( it != t.end() ) {
t.erase( it );
}
}
}
| 412 | 0.985823 | 1 | 0.985823 | game-dev | MEDIA | 0.900539 | game-dev | 0.671187 | 1 | 0.671187 |
wahidrachmawan/uNode | 12,154 | Assets/uNode3/Core.Editor/Utility/GraphConverter.cs | using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace MaxyGames.UNode.Editors {
/// <summary>
/// This is base class for convert a graph into other graph type
/// </summary>
public abstract class GraphConverter {
public virtual int order => 0;
public abstract bool IsValid(IGraph graph);
public abstract string GetMenuName(IGraph graph);
public abstract void Convert(IGraph graph);
protected void ValidateGraph(
IGraph graph,
bool supportAttribute = true,
bool supportGeneric = true,
bool supportModifier = true,
bool supportConstructor = true) {
if(!supportAttribute) {
if(graph is IGraphWithAttributes AS && AS.Attributes?.Count > 0) {
Debug.LogWarning("The target graph contains 'Attributes' which is not supported, the converted graph will not include it.");
AS.Attributes.Clear();
}
}
if(!supportGeneric) {
if(graph is IGenericParameterSystem GPS && GPS.GenericParameters?.Count > 0) {
Debug.LogWarning("The target graph contains 'GenericParameter' which is not supported, the converted graph will not include it.");
GPS.GenericParameters = new GenericParameterData[0];
}
}
if(!supportModifier) {
if(graph is IClassModifier clsModifier) {
var modifier = clsModifier.GetModifier();
if(modifier.Static || modifier.Abstract || modifier.Partial || modifier.Sealed) {
Debug.LogWarning("The target graph contains unsupported class modifier, the converted graph will ignore it.");
modifier.Static = false;
modifier.Abstract = false;
modifier.Partial = false;
modifier.Sealed = false;
}
}
}
if(!supportModifier && graph is IGraphWithVariables variableSystem) {
var variables = variableSystem.GetVariables();
if(variables != null) {
foreach(var v in variables) {
if(!supportModifier) {
if(v.modifier.Static || v.modifier.ReadOnly || v.modifier.Const) {
Debug.LogWarning("The target graph contains unsupported variable modifier, the converted graph will ignore it.");
v.modifier.Static = false;
v.modifier.ReadOnly = false;
v.modifier.Const = false;
}
}
}
}
}
if((!supportAttribute || !supportGeneric || !supportModifier) && graph is IGraphWithFunctions functionSystem) {
var functions = functionSystem.GetFunctions();
if(functions != null) {
foreach(var f in functions) {
if(!supportAttribute) {
if(f.attributes?.Count > 0) {
Debug.LogWarning("The target graph contains function 'Attributes' which is not supported, the converted graph will not include it.");
f.attributes.Clear();
}
}
if(!supportGeneric) {
if(f.GenericParameters?.Count > 0) {
Debug.LogWarning("The target graph contains function generic parameter which is not supported, the converted graph will not include it.");
f.GenericParameters = new GenericParameterData[0];
}
}
if(!supportModifier) {
if(f.modifier.Abstract || f.modifier.Async || f.modifier.Extern || f.modifier.New || f.modifier.Override || f.modifier.Partial || f.modifier.Static || f.modifier.Unsafe || f.modifier.Virtual) {
Debug.LogWarning("The target graph contains unsupported function modifier, the converted graph will ignore it.");
f.modifier = new FunctionModifier() {
Public = f.modifier.isPublic,
Private = !f.modifier.isPublic
};
}
}
}
}
}
if((!supportAttribute || !supportModifier) && graph is IGraphWithProperties propertySystem) {
var properties = propertySystem.GetProperties();
if(properties != null) {
foreach(var f in properties) {
if(!supportAttribute) {
if(f.attributes?.Count > 0) {
Debug.LogWarning("The target graph contains property 'Attributes' which is not supported, the converted graph will not include it.");
f.attributes.Clear();
}
}
if(!supportModifier) {
if(f.modifier.Abstract || f.modifier.Static || f.modifier.Virtual) {
Debug.LogWarning("The target graph contains unsupported property modifier, the converted graph will ignore it.");
f.modifier = new PropertyModifier() {
Public = f.modifier.isPublic,
Private = !f.modifier.isPublic
};
}
}
}
}
}
if(!supportConstructor) {
if(graph is IGraphWithConstructors CS) {
var ctors = CS.GetConstructors().ToArray();
if(ctors?.Length > 0) {
Debug.LogWarning("The target graph contains constructor which is not supported, the converted graph will not include it.");
for(int i = 0; i < ctors.Length; i++) {
if(ctors[i] != null) {
ctors[i].Destroy();
}
}
}
}
}
}
}
}
namespace MaxyGames.UNode.Editors.Converter {
class ConverterToClassScript : GraphConverter {
public override void Convert(IGraph graph) {
if(graph is GraphComponent) {
var sourceGraph = graph as GraphComponent;
var scriptGraph = ScriptableObject.CreateInstance<ScriptGraph>();
scriptGraph.name = graph.GetGraphName();
var graphAsset = ScriptGraph.CreateInstance<ClassScript>();
graphAsset.inheritType = typeof(MonoBehaviour);
SerializedGraph.Copy(sourceGraph.serializedGraph, graphAsset.serializedGraph, sourceGraph, graphAsset);
scriptGraph.TypeList.AddType(graphAsset, scriptGraph);
var path = EditorUtility.SaveFilePanelInProject("Save graph", graph.GetGraphName(), "asset", "");
if(string.IsNullOrEmpty(path) == false) {
AssetDatabase.CreateAsset(scriptGraph, path);
AssetDatabase.AddObjectToAsset(graphAsset, scriptGraph);
ValidateGraph(graphAsset);
AssetDatabase.SaveAssets();
EditorGUIUtility.PingObject(scriptGraph);
}
}
else if(graph is ClassDefinition) {
var sourceGraph = graph as ClassDefinition;
var scriptGraph = ScriptableObject.CreateInstance<ScriptGraph>();
scriptGraph.name = graph.GetGraphName();
var graphAsset = ScriptGraph.CreateInstance<ClassScript>();
graphAsset.inheritType = sourceGraph.model.InheritType;
SerializedGraph.Copy(sourceGraph.serializedGraph, graphAsset.serializedGraph, sourceGraph, graphAsset);
scriptGraph.TypeList.AddType(graphAsset, scriptGraph);
var path = EditorUtility.SaveFilePanelInProject("Save graph", graph.GetGraphName(), "asset", "", System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(sourceGraph)));
if(string.IsNullOrEmpty(path) == false) {
AssetDatabase.CreateAsset(scriptGraph, path);
AssetDatabase.AddObjectToAsset(graphAsset, scriptGraph);
ValidateGraph(graphAsset);
AssetDatabase.SaveAssets();
EditorGUIUtility.PingObject(scriptGraph);
}
}
}
public override string GetMenuName(IGraph graph) {
return "Convert to C# Class";
}
public override bool IsValid(IGraph graph) {
if(graph is ClassDefinition definition) {
return ReflectionUtils.IsNativeType(definition.InheritType);
}
if(graph is GraphComponent) {
return true;
}
return false;
}
}
class ConverterToClassDefinition : GraphConverter {
public override void Convert(IGraph graph) {
if(graph is GraphComponent) {
var sourceGraph = graph as GraphComponent;
var graphAsset = ScriptGraph.CreateInstance<ClassDefinition>();
graphAsset.name = graph.GetGraphName();
graphAsset.model = new ClassComponentModel();
graphAsset.@namespace = sourceGraph.GetGraphNamespace();
graphAsset.usingNamespaces = new List<string>(sourceGraph.GetUsingNamespaces());
SerializedGraph.Copy(sourceGraph.serializedGraph, graphAsset.serializedGraph, sourceGraph, graphAsset);
var path = EditorUtility.SaveFilePanelInProject("Save graph", graph.GetGraphName(), "asset", "");
if(string.IsNullOrEmpty(path) == false) {
AssetDatabase.CreateAsset(graphAsset, path);
ValidateGraph(graphAsset, supportAttribute: false, supportGeneric: false, supportModifier: false, supportConstructor: false);
AssetDatabase.SaveAssets();
EditorGUIUtility.PingObject(graphAsset);
}
}
else if(graph is ClassScript) {
var sourceGraph = graph as ClassScript;
var graphAsset = ScriptGraph.CreateInstance<ClassDefinition>();
graphAsset.name = graph.GetGraphName();
if(sourceGraph.inheritType == typeof(MonoBehaviour)) {
graphAsset.model = new ClassComponentModel();
}
else if(sourceGraph.inheritType == typeof(ScriptableObject)) {
graphAsset.model = new ClassAssetModel();
}
else {
graphAsset.model = new ClassObjectModel();
}
graphAsset.@namespace = sourceGraph.GetGraphNamespace();
graphAsset.usingNamespaces = new List<string>(sourceGraph.GetUsingNamespaces());
SerializedGraph.Copy(sourceGraph.serializedGraph, graphAsset.serializedGraph, sourceGraph, graphAsset);
var path = EditorUtility.SaveFilePanelInProject("Save graph", graph.GetGraphName(), "asset", "", System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(sourceGraph)));
if(string.IsNullOrEmpty(path) == false) {
AssetDatabase.CreateAsset(graphAsset, path);
ValidateGraph(graphAsset, supportAttribute: false, supportGeneric: false, supportModifier: false, supportConstructor: false);
AssetDatabase.SaveAssets();
EditorGUIUtility.PingObject(graphAsset);
}
}
}
public override string GetMenuName(IGraph graph) {
return "Convert to Class Definition";
}
public override bool IsValid(IGraph graph) {
if(graph is ClassScript classScript) {
return classScript.inheritType == typeof(MonoBehaviour) || classScript.inheritType == typeof(ScriptableObject) || classScript.inheritType == typeof(object);
}
if(graph is GraphComponent) {
return true;
}
return false;
}
}
class ConverterToSingleton : GraphConverter {
public override void Convert(IGraph graph) {
if(graph is ClassDefinition) {
var sourceGraph = graph as ClassDefinition;
var graphAsset = ScriptGraph.CreateInstance<GraphSingleton>();
graphAsset.name = graph.GetGraphName();
graphAsset.@namespace = sourceGraph.GetGraphNamespace();
graphAsset.usingNamespaces = new List<string>(sourceGraph.GetUsingNamespaces());
SerializedGraph.Copy(sourceGraph.serializedGraph, graphAsset.serializedGraph, sourceGraph, graphAsset);
var path = EditorUtility.SaveFilePanelInProject("Save graph", graph.GetGraphName(), "asset", "");
if(string.IsNullOrEmpty(path) == false) {
AssetDatabase.CreateAsset(graphAsset, path);
ValidateGraph(graphAsset, supportAttribute: false, supportGeneric: false, supportModifier: false, supportConstructor: false);
AssetDatabase.SaveAssets();
EditorGUIUtility.PingObject(graphAsset);
}
}
else if(graph is ClassScript) {
var sourceGraph = graph as ClassScript;
var graphAsset = ScriptGraph.CreateInstance<GraphSingleton>();
graphAsset.name = graph.GetGraphName();
graphAsset.@namespace = sourceGraph.GetGraphNamespace();
graphAsset.usingNamespaces = new List<string>(sourceGraph.GetUsingNamespaces());
SerializedGraph.Copy(sourceGraph.serializedGraph, graphAsset.serializedGraph, sourceGraph, graphAsset);
var path = EditorUtility.SaveFilePanelInProject("Save graph", graph.GetGraphName(), "asset", "", System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(sourceGraph)));
if(string.IsNullOrEmpty(path) == false) {
AssetDatabase.CreateAsset(graphAsset, path);
ValidateGraph(graphAsset, supportAttribute: false, supportGeneric: false, supportModifier: false, supportConstructor: false);
AssetDatabase.SaveAssets();
EditorGUIUtility.PingObject(graphAsset);
}
}
}
public override string GetMenuName(IGraph graph) {
return "Convert to Singleton";
}
public override bool IsValid(IGraph graph) {
if(graph is ClassScript classScript) {
return classScript.inheritType == typeof(MonoBehaviour);
}
if(graph is ClassDefinition classDefinition && classDefinition.InheritType == typeof(MonoBehaviour)) {
return true;
}
return false;
}
}
} | 412 | 0.921689 | 1 | 0.921689 | game-dev | MEDIA | 0.245037 | game-dev | 0.950208 | 1 | 0.950208 |
Jire/Charlatano | 3,692 | src/main/kotlin/com/charlatano/scripts/BombTimer.kt | /*
* Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO
* Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.charlatano.scripts
import com.badlogic.gdx.graphics.Color
import com.charlatano.game.CSGO
import com.charlatano.game.entity.*
import com.charlatano.game.entityByType
import com.charlatano.game.offsets.EngineOffsets
import com.charlatano.overlay.CharlatanoOverlay
import com.charlatano.settings.ENABLE_BOMB_TIMER
import com.charlatano.utils.every
import org.jire.kna.float
private var bombState = BombState()
fun bombTimer() {
bombUpdater()
CharlatanoOverlay {
bombState.apply {
if (ENABLE_BOMB_TIMER && this.planted) {
batch.begin()
textRenderer.color = Color.ORANGE
textRenderer.draw(batch, bombState.toString(), 20F, 500F)
batch.end()
}
}
}
}
private fun currentGameTicks(): Float = CSGO.engineDLL.float(EngineOffsets.dwGlobalVars + 16)
fun bombUpdater() = every(8, true) {
if (!ENABLE_BOMB_TIMER) return@every
val time = currentGameTicks()
val bomb: Entity = entityByType(EntityType.CPlantedC4)?.entity ?: -1L
bombState.apply {
timeLeftToExplode = bomb.blowTime() - time
hasBomb = bomb > 0 && !bomb.dormant()
planted = hasBomb && !bomb.defused() && timeLeftToExplode > 0
if (planted) {
if (location.isEmpty()) location = bomb.plantLocation()
val defuser = bomb.defuser()
timeLeftToDefuse = bomb.defuseTime() - time
gettingDefused = defuser > 0 && timeLeftToDefuse > 0
canDefuse = gettingDefused && (timeLeftToExplode > timeLeftToDefuse)
} else {
location = ""
canDefuse = false
gettingDefused = false
}
}
}
private data class BombState(var hasBomb: Boolean = false,
var planted: Boolean = false,
var canDefuse: Boolean = false,
var gettingDefused: Boolean = false,
var timeLeftToExplode: Float = -1f,
var timeLeftToDefuse: Float = -1f,
var location: String = "") {
private val sb = StringBuilder()
override fun toString(): String {
sb.setLength(0)
sb.append("Bomb Planted!\n")
sb.append("TimeToExplode : ${formatFloat(timeLeftToExplode)} \n")
if (location.isNotBlank())
sb.append("Location : $location \n")
if (gettingDefused) {
// sb.append("GettingDefused : $gettingDefused \n")
sb.append("CanDefuse : $canDefuse \n")
// Redundant as the UI already shows this, but may have a use case I'm missing
sb.append("TimeToDefuse : ${formatFloat(timeLeftToDefuse)} ")
}
return sb.toString()
}
private fun formatFloat(f: Float): String {
return "%.3f".format(f)
}
}
| 412 | 0.748558 | 1 | 0.748558 | game-dev | MEDIA | 0.833829 | game-dev | 0.928618 | 1 | 0.928618 |
EsotericSoftware/spine-runtimes | 4,894 | spine-ts/spine-pixi-v8/example/physics2.html | <html>
<head>
<meta charset="UTF-8" />
<title>spine-pixi-v8</title>
<script src="https://cdn.jsdelivr.net/npm/pixi.js@8.4.1/dist/pixi.js"></script>
<script src="../dist/iife/spine-pixi-v8.js"></script>
<link rel="stylesheet" href="../../index.css">
</head>
<body>
<script>
(async function () {
var app = new PIXI.Application();
await app.init({
width: window.innerWidth,
height: window.innerHeight,
resolution: window.devicePixelRatio || 1,
autoDensity: true,
resizeTo: window,
backgroundColor: 0x2c3e50,
hello: true,
})
document.body.appendChild(app.canvas);
// Pre-load the skeleton data and atlas. You can also load .json skeleton data.
PIXI.Assets.add({alias: "girlData", src: "/assets/celestial-circus-pro.skel"});
PIXI.Assets.add({alias: "girlAtlas", src: "/assets/celestial-circus-pma.atlas"});
await PIXI.Assets.load(["girlData", "girlAtlas"]);
// Create the spine display object
const girl = spine.Spine.from({skeleton: "girlData", atlas: "girlAtlas",
scale: 0.2,
});
// Center the spine object on screen.
girl.x = window.innerWidth / 2;
girl.y = window.innerHeight / 2 + girl.getBounds().height / 4;
// Set animation "eyeblink-long" on track 0, looped.
girl.state.setAnimation(0, "eyeblink-long", true);
// Add the display object to the stage.
app.stage.addChild(girl);
// Make the stage interactive and register pointer events
app.stage.eventMode = "dynamic";
app.stage.hitArea = app.screen;
let isDragging = false;
let lastX = -1, lastY = -1;
app.stage.on("pointerdown", (e) => {
isDragging = true;
let mousePosition = new spine.Vector2(e.data.global.x, e.data.global.y);
lastX = mousePosition.x;
lastY = mousePosition.y;
});
app.stage.on("pointermove", (e) => {
if (isDragging) {
let mousePosition = new spine.Vector2(e.data.global.x, e.data.global.y);
girl.x += mousePosition.x - lastX;
girl.y += mousePosition.y - lastY;
girl.skeleton.physicsTranslate(mousePosition.x - lastX, mousePosition.y - lastY);
lastX = mousePosition.x;
lastY = mousePosition.y;
}
});
const endDrag = () => (isDragging = false);
app.stage.on("pointerup", endDrag);
app.stage.on("pointerupoutside", endDrag);
document.addEventListener('fullscreenchange', () => {
endDrag();
});
const buttonContainer = new PIXI.Container();
buttonContainer.position.set(0, 0);
const buttonBackground = new PIXI.Graphics()
.roundRect(0, 0, 140, 100, 5)
.fill({ color: 0x000000, alpha: .7 });
buttonContainer.addChild(buttonBackground);
const fontStyle = {
fill: 0xdddddd,
fontFamily: 'sans-serif',
fontSize: 16,
};
// Create the text label for the heading
const textHeading = new PIXI.Text({ text: "Drag anywhere", style: fontStyle }); // Button text and color
textHeading.position.set(15, 15); // Set the position of the text within the button
buttonContainer.addChild(textHeading);
// Create the text label for the FPS counter
const textFps = new PIXI.Text({ text: "0 fps", style: fontStyle });
textFps.position.set(15, 40);
buttonContainer.addChild(textFps);
// Create the text label for the button toggle fullscreen
const textButton = new PIXI.Text({ text: "Fullscreen", style: fontStyle }); // Button text and color
textButton.position.set(15, 65); // Set the position of the text within the button
buttonContainer.addChild(textButton);
// Add the button container to the stage
app.stage.addChild(buttonContainer);
buttonContainer.interactive = true;
buttonContainer.buttonMode = true;
let fsEnabled = false;
buttonContainer.on('pointerdown', () => {
if (fsEnabled) {
document.exitFullscreen();
textButton.text = "Fullscreen";
} else {
app.renderer.canvas.requestFullscreen();
textButton.text = "Windowed";
}
fsEnabled = !fsEnabled;
});
app.ticker.add(throttle(() => textFps.text = app.ticker.FPS.toFixed(2) + " fps", 250));
})();
const throttle = (func, delay) => {
let lastCall = 0;
return (...args) => {
const now = Date.now();
if (now - lastCall >= delay) {
func.apply(this, args);
lastCall = now;
}
};
}
</script>
</body>
</html> | 412 | 0.622996 | 1 | 0.622996 | game-dev | MEDIA | 0.424478 | game-dev,web-frontend | 0.968639 | 1 | 0.968639 |
glKarin/com.n0n3m4.diii4a | 80,535 | Q3E/src/main/jni/fteqw/engine/server/sv_phys.c | /*
Copyright (C) 1996-1997 Id Software, 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 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.
*/
// sv_phys.c
#include "quakedef.h"
#if !defined(CLIENTONLY) || defined(CSQC_DAT)
#include "pr_common.h"
/*
pushmove objects do not obey gravity, and do not interact with each other or trigger fields, but block normal movement and push normal objects when they move.
onground is set for toss objects when they come to a complete rest. it is set for steping or walking objects
doors, plats, etc are SOLID_BSP, and MOVETYPE_PUSH
bonus items are SOLID_TRIGGER touch, and MOVETYPE_TOSS
corpses are SOLID_NOT and MOVETYPE_TOSS
crates are SOLID_BBOX and MOVETYPE_TOSS
walking monsters are SOLID_SLIDEBOX and MOVETYPE_STEP
flying/floating monsters are SOLID_SLIDEBOX and MOVETYPE_FLY
solid_edge items only clip against bsp models.
*/
cvar_t sv_maxvelocity = CVAR("sv_maxvelocity","10000");
cvar_t sv_gravity = CVAR( "sv_gravity", "800");
cvar_t sv_stopspeed = CVAR( "sv_stopspeed", "100");
cvar_t sv_maxspeed = CVAR( "sv_maxspeed", "320");
cvar_t sv_spectatormaxspeed = CVAR( "sv_spectatormaxspeed", "500");
cvar_t sv_accelerate = CVAR( "sv_accelerate", "10");
cvar_t sv_airaccelerate = CVAR( "sv_airaccelerate", "0.7");
cvar_t sv_wateraccelerate = CVAR( "sv_wateraccelerate", "10");
cvar_t sv_friction = CVAR( "sv_friction", "4");
cvar_t sv_waterfriction = CVAR( "sv_waterfriction", "4");
cvar_t sv_wallfriction = CVARD( "sv_wallfriction", "1", "Additional friction when running into walls");
cvar_t sv_gameplayfix_noairborncorpse = CVAR( "sv_gameplayfix_noairborncorpse", "0");
cvar_t sv_gameplayfix_multiplethinks = CVARAD("sv_gameplayfix_multiplethinks", "1", /*dp*/"sv_gameplayfix_multiplethinksperframe", "Enables multiple thinks per entity per frame so small nextthink times are accurate. QuakeWorld mods expect a value of 1, while NQ expects 0.");
cvar_t sv_gameplayfix_stepdown = CVARD( "sv_gameplayfix_stepdown", "0", "Attempt to step down steps, instead of only up them. Affects non-predicted movetype_walk.");
cvar_t sv_gameplayfix_bouncedownslopes = CVARD( "sv_gameplayfix_grenadebouncedownslopes", "0", "MOVETYPE_BOUNCE speeds are calculated relative to the impacted surface, instead of the vertical, reducing the chance of grenades just sitting there on slopes.");
cvar_t sv_gameplayfix_trappedwithin = CVARD( "sv_gameplayfix_trappedwithin", "0", "Blocks further entity movement when an entity is already inside another entity. This ensures that bsp precision issues cannot allow the entity to completely pass through eg the world.");
//cvar_t sv_gameplayfix_radialmaxvelocity = CVARD( "sv_gameplayfix_radialmaxvelocity", "0", "Applies maxvelocity radially instead of axially.");
#if !defined(CLIENTONLY) && defined(NQPROT) && defined(HAVE_LEGACY)
cvar_t sv_gameplayfix_spawnbeforethinks = CVARD( "sv_gameplayfix_spawnbeforethinks", "0", "Fixes an issue where player thinks (including Pre+Post) can be called before PutClientInServer. Unfortunately at least one mod depends upon PreThink being called first in order to correctly determine spawn positions.");
#endif
cvar_t dpcompat_noretouchground = CVARD( "dpcompat_noretouchground", "0", "Prevents entities that are already standing on an entity from touching the same entity again.");
cvar_t sv_sound_watersplash = CVAR( "sv_sound_watersplash", "misc/h2ohit1.wav");
cvar_t sv_sound_land = CVAR( "sv_sound_land", "demon/dland2.wav");
cvar_t sv_stepheight = CVARAFD("pm_stepheight", "", /*dp*/"sv_stepheight", CVAR_SERVERINFO, "If empty, the value "STRINGIFY(PM_DEFAULTSTEPHEIGHT)" will be used instead. This is the size of the step you can step up or down.");
extern cvar_t sv_nqplayerphysics;
cvar_t pm_ktjump = CVARF("pm_ktjump", "", CVAR_SERVERINFO);
cvar_t pm_bunnyspeedcap = CVARFD("pm_bunnyspeedcap", "", CVAR_SERVERINFO, "0 or 1, ish. If the player is traveling faster than this speed while turning, their velocity will be gracefully reduced to match their current maxspeed. You can still rocket-jump to gain high velocity, but turning will reduce your speed back to the max. This can be used to disable bunny hopping.");
cvar_t pm_watersinkspeed = CVARFD("pm_watersinkspeed", "", CVAR_SERVERINFO, "This is the speed that players will sink at while inactive in water. Empty means 60.");
cvar_t pm_flyfriction = CVARFD("pm_flyfriction", "", CVAR_SERVERINFO, "Amount of friction that applies in fly or 6dof mode. Empty means 4.");
cvar_t pm_slidefix = CVARFD("pm_slidefix", "", CVAR_SERVERINFO, "Fixes an issue when walking down slopes (ie: so they act more like slopes and not a series of steps)");
cvar_t pm_slidyslopes = CVARFD("pm_slidyslopes", "", CVAR_SERVERINFO, "Replicates NQ behaviour, where players will slowly slide down ramps. Generally requires 'pm_noround 1' too, otherwise the effect rounds to nothing.");
cvar_t pm_bunnyfriction = CVARFD("pm_bunnyfriction", "", CVAR_SERVERINFO, "Replicates NQ behaviour, ensuring that there's at least a frame of friction while jumping - friction is proportional to tick rate.");
cvar_t pm_autobunny = CVARFD("pm_autobunny", "", CVAR_SERVERINFO, "Players will continue jumping without needing to release the jump button.");
cvar_t pm_airstep = CVARAFD("pm_airstep", "", /*dp*/"sv_jumpstep", CVAR_SERVERINFO, "Allows players to step up while jumping. This makes stairs more graceful but also increases potential jump heights.");
cvar_t pm_pground = CVARFD("pm_pground", "", CVAR_SERVERINFO, "Use persisten onground state instead of recalculating every frame."CON_WARNING"Do NOT use with nq mods, as most nq mods will interfere with onground state, resulting in glitches.");
cvar_t pm_stepdown = CVARFD("pm_stepdown", "", CVAR_SERVERINFO, "Causes physics to stick to the ground, instead of constantly losing traction while going down steps.");
cvar_t pm_walljump = CVARFD("pm_walljump", "", CVAR_SERVERINFO, "Allows the player to bounce off walls while arborne.");
cvar_t pm_edgefriction = CVARAFD("pm_edgefriction", "", /*nq*/"edgefriction", CVAR_SERVERINFO, "Increases friction when about to walk over a cliff, so you're less likely to plummet by mistake. When empty defaults to 2, but uses a tracebox instead of a traceline to detect the drop.");
#define cvargroup_serverphysics "server physics variables"
void WPhys_Init(void)
{
Cvar_Register (&sv_maxvelocity, cvargroup_serverphysics);
Cvar_Register (&sv_gravity, cvargroup_serverphysics);
Cvar_Register (&sv_stopspeed, cvargroup_serverphysics);
Cvar_Register (&sv_maxspeed, cvargroup_serverphysics);
Cvar_Register (&sv_spectatormaxspeed, cvargroup_serverphysics);
Cvar_Register (&sv_accelerate, cvargroup_serverphysics);
Cvar_Register (&sv_airaccelerate, cvargroup_serverphysics);
Cvar_Register (&sv_wateraccelerate, cvargroup_serverphysics);
Cvar_Register (&sv_friction, cvargroup_serverphysics);
Cvar_Register (&sv_waterfriction, cvargroup_serverphysics);
Cvar_Register (&sv_wallfriction, cvargroup_serverphysics);
Cvar_Register (&sv_sound_watersplash, cvargroup_serverphysics);
Cvar_Register (&sv_sound_land, cvargroup_serverphysics);
Cvar_Register (&sv_stepheight, cvargroup_serverphysics);
Cvar_Register (&sv_gameplayfix_noairborncorpse, cvargroup_serverphysics);
Cvar_Register (&sv_gameplayfix_multiplethinks, cvargroup_serverphysics);
Cvar_Register (&sv_gameplayfix_stepdown, cvargroup_serverphysics);
Cvar_Register (&sv_gameplayfix_bouncedownslopes, cvargroup_serverphysics);
Cvar_Register (&sv_gameplayfix_trappedwithin, cvargroup_serverphysics);
Cvar_Register (&dpcompat_noretouchground, cvargroup_serverphysics);
#if !defined(CLIENTONLY) && defined(NQPROT) && defined(HAVE_LEGACY)
Cvar_Register (&sv_gameplayfix_spawnbeforethinks, cvargroup_serverphysics);
#endif
}
#define MOVE_EPSILON 0.01
static void WPhys_Physics_Toss (world_t *w, wedict_t *ent);
/*
================
SV_CheckAllEnts
================
static void SV_CheckAllEnts (void)
{
int e;
edict_t *check;
// see if any solid entities are inside the final position
for (e=1 ; e<sv.world.num_edicts ; e++)
{
check = EDICT_NUM(svprogfuncs, e);
if (check->isfree)
continue;
if (check->v->movetype == MOVETYPE_PUSH
|| check->v->movetype == MOVETYPE_NONE
|| check->v->movetype == MOVETYPE_FOLLOW
|| check->v->movetype == MOVETYPE_NOCLIP
|| check->v->movetype == MOVETYPE_ANGLENOCLIP)
continue;
if (World_TestEntityPosition (&sv.world, (wedict_t*)check))
Con_Printf ("entity in invalid position\n");
}
}
*/
/*
================
SV_CheckVelocity
================
*/
void WPhys_CheckVelocity (world_t *w, wedict_t *ent)
{
int i;
#ifdef HAVE_SERVER
if (sv_nqplayerphysics.ival)
{ //bound axially (like vanilla)
for (i=0 ; i<3 ; i++)
{
if (IS_NAN(ent->v->velocity[i]))
{
Con_DPrintf ("Got a NaN velocity on entity %i (%s)\n", ent->entnum, PR_GetString(w->progs, ent->v->classname));
ent->v->velocity[i] = 0;
}
if (IS_NAN(ent->v->origin[i]))
{
Con_Printf ("Got a NaN origin on entity %i (%s)\n", ent->entnum, PR_GetString(w->progs, ent->v->classname));
ent->v->origin[i] = 0;
}
if (ent->v->velocity[i] > sv_maxvelocity.value)
ent->v->velocity[i] = sv_maxvelocity.value;
else if (ent->v->velocity[i] < -sv_maxvelocity.value)
ent->v->velocity[i] = -sv_maxvelocity.value;
}
}
else
#endif
{ //bound radially (for sanity)
for (i=0 ; i<3 ; i++)
{
if (IS_NAN(ent->v->velocity[i]))
{
Con_DPrintf ("Got a NaN velocity on entity %i (%s)\n", ent->entnum, PR_GetString(w->progs, ent->v->classname));
ent->v->velocity[i] = 0;
}
if (IS_NAN(ent->v->origin[i]))
{
Con_Printf ("Got a NaN origin on entity %i (%s)\n", ent->entnum, PR_GetString(w->progs, ent->v->classname));
ent->v->origin[i] = 0;
}
}
if (Length(ent->v->velocity) > sv_maxvelocity.value)
{
// Con_DPrintf("Slowing %s\n", PR_GetString(w->progs, ent->v->classname));
VectorScale (ent->v->velocity, sv_maxvelocity.value/Length(ent->v->velocity), ent->v->velocity);
}
}
}
/*
=============
SV_RunThink
Runs thinking code if time. There is some play in the exact time the think
function will be called, because it is called before any movement is done
in a frame. Not used for pushmove objects, because they must be exact.
Returns false if the entity removed itself.
=============
*/
qboolean WPhys_RunThink (world_t *w, wedict_t *ent)
{
float thinktime;
if (!sv_gameplayfix_multiplethinks.ival) //try and imitate nq as closeley as possible
{
thinktime = ent->v->nextthink;
if (thinktime <= 0 || thinktime > w->physicstime + host_frametime)
return true;
if (thinktime < w->physicstime)
thinktime = w->physicstime; // don't let things stay in the past.
// it is possible to start that way
// by a trigger with a local time.
ent->v->nextthink = 0;
*w->g.time = thinktime;
w->Event_Think(w, ent);
return !ED_ISFREE(ent);
}
do
{
thinktime = ent->v->nextthink;
if (thinktime <= 0)
return true;
if (thinktime > w->physicstime + host_frametime)
return true;
if (thinktime < w->physicstime)
thinktime = w->physicstime; // don't let things stay in the past.
// it is possible to start that way
// by a trigger with a local time.
ent->v->nextthink = 0;
*w->g.time = thinktime;
w->Event_Think(w, ent);
if (ED_ISFREE(ent))
return false;
if (ent->v->nextthink <= thinktime) //hmm... infinate loop was possible here.. Quite a few non-QW mods do this.
return true;
} while (1);
return true;
}
/*
==================
SV_Impact
Two entities have touched, so run their touch functions
==================
*/
static void WPhys_Impact (world_t *w, wedict_t *e1, trace_t *trace)
{
wedict_t *e2 = trace->ent;
*w->g.time = w->physicstime;
if (e1->v->touch && e1->v->solid != SOLID_NOT)
{
w->Event_Touch(w, e1, e2, trace);
}
if (e2->v->touch && e2->v->solid != SOLID_NOT)
{
w->Event_Touch(w, e2, e1, trace);
}
}
/*
==================
ClipVelocity
Slide off of the impacting object
==================
*/
#define STOP_EPSILON 0.1
//courtesy of darkplaces, it's just more efficient.
static void ClipVelocity (vec3_t in, vec3_t normal, vec3_t out, float overbounce)
{
int i;
float backoff;
backoff = -DotProduct (in, normal) * overbounce;
VectorMA(in, backoff, normal, out);
for (i = 0;i < 3;i++)
if (out[i] > -STOP_EPSILON && out[i] < STOP_EPSILON)
out[i] = 0;
}
static void WPhys_PortalTransform(world_t *w, wedict_t *ent, wedict_t *portal, vec3_t org, vec3_t move)
{
int oself = *w->g.self;
void *pr_globals = PR_globals(w->progs, PR_CURRENT);
*w->g.self = EDICT_TO_PROG(w->progs, portal);
//transform origin+velocity etc
VectorCopy(org, G_VECTOR(OFS_PARM0));
VectorCopy(ent->v->angles, G_VECTOR(OFS_PARM1));
VectorCopy(ent->v->velocity, w->g.v_forward);
VectorCopy(move, w->g.v_right);
VectorCopy(ent->xv->gravitydir, w->g.v_up);
if (!DotProduct(w->g.v_up, w->g.v_up))
w->g.v_up[2] = -1;
PR_ExecuteProgram (w->progs, portal->xv->camera_transform);
VectorCopy(G_VECTOR(OFS_RETURN), org);
VectorCopy(w->g.v_forward, ent->v->velocity);
VectorCopy(w->g.v_right, move);
// VectorCopy(w->g.v_up, ent->xv->gravitydir);
//monsters get their gravitydir set if it isn't already, to ensure that they still work (angle issues).
if ((int)ent->v->flags & FL_MONSTER)
if (!ent->xv->gravitydir[0] && !ent->xv->gravitydir[1] && !ent->xv->gravitydir[2])
ent->xv->gravitydir[2] = -1;
//transform the angles too
VectorCopy(org, G_VECTOR(OFS_PARM0));
#ifndef CLIENTONLY
if (w == &sv.world && ent->entnum <= svs.allocated_client_slots)
{
VectorCopy(ent->v->v_angle, ent->v->angles);
}
else
#endif
ent->v->angles[0] *= r_meshpitch.value;
VectorCopy(ent->v->angles, G_VECTOR(OFS_PARM1));
AngleVectors(ent->v->angles, w->g.v_forward, w->g.v_right, w->g.v_up);
PR_ExecuteProgram (w->progs, portal->xv->camera_transform);
VectorAngles(w->g.v_forward, w->g.v_up, ent->v->angles, true);
#ifndef CLIENTONLY
if (ent->entnum > 0 && ent->entnum <= svs.allocated_client_slots)
{
client_t *cl = &svs.clients[ent->entnum-1];
ent->v->angles[0] *= r_meshpitch.value;
VectorCopy(ent->v->angles, ent->v->v_angle);
ent->v->angles[0] *= r_meshpitch.value;
SV_SendFixAngle(cl, NULL, FIXANGLE_AUTO, true);
}
#endif
/*
avelocity is horribly dependant upon eular angles. trying to treat it as a matrix is folly.
if (DotProduct(ent->v->avelocity, ent->v->avelocity))
{
ent->v->avelocity[0] *= r_meshpitch.value;
AngleVectors(ent->v->avelocity, w->g.v_forward, w->g.v_right, w->g.v_up);
PR_ExecuteProgram (w->progs, portal->xv->camera_transform);
VectorAngles(w->g.v_forward, w->g.v_up, ent->v->avelocity);
ent->v->avelocity[0] *= r_meshpitch.value;
}
*/
*w->g.self = oself;
}
/*
============
SV_FlyMove
The basic solid body movement clip that slides along multiple planes
Returns the clipflags if the velocity was modified (hit something solid)
1 = floor
2 = wall / step
4 = dead stop
If steptrace is not NULL, the trace of any vertical wall hit will be stored
============
*/
#define MAX_CLIP_PLANES 5
static int WPhys_FlyMove (world_t *w, wedict_t *ent, const vec3_t gravitydir, float time, trace_t *steptrace)
{
int bumpcount, numbumps;
vec3_t dir;
float d;
int numplanes;
vec3_t planes[MAX_CLIP_PLANES];
vec3_t primal_velocity, original_velocity, new_velocity;
int i, j;
trace_t trace;
vec3_t end;
float time_left;
int blocked;
wedict_t *impact;
vec3_t diff;
numbumps = 4;
blocked = 0;
VectorCopy (ent->v->velocity, original_velocity);
VectorCopy (ent->v->velocity, primal_velocity);
numplanes = 0;
time_left = time;
for (bumpcount=0 ; bumpcount<numbumps ; bumpcount++)
{
for (i=0 ; i<3 ; i++)
end[i] = ent->v->origin[i] + time_left * ent->v->velocity[i];
trace = World_Move (w, ent->v->origin, ent->v->mins, ent->v->maxs, end, MOVE_NORMAL, (wedict_t*)ent);
impact = trace.ent;
if (impact && impact->v->solid == SOLID_PORTAL)
{
vec3_t move;
vec3_t from;
VectorCopy(trace.endpos, from); //just in case
VectorSubtract(end, trace.endpos, move);
WPhys_PortalTransform(w, ent, impact, from, move);
VectorAdd(from, move, end);
//if we follow the portal, then we basically need to restart from the other side.
time_left -= time_left * trace.fraction;
VectorCopy (ent->v->velocity, primal_velocity);
VectorCopy (ent->v->velocity, original_velocity);
numplanes = 0;
trace = World_Move (w, from, ent->v->mins, ent->v->maxs, end, MOVE_NORMAL, (wedict_t*)ent);
impact = trace.ent;
}
if (trace.allsolid)//should be (trace.startsolid), but that breaks compat. *sigh*
{ // entity is trapped in another solid
VectorClear (ent->v->velocity);
return 3;
}
if (trace.fraction > 0)
{ // actually covered some distance
VectorCopy (trace.endpos, ent->v->origin);
VectorCopy (ent->v->velocity, original_velocity);
numplanes = 0;
}
if (trace.fraction == 1)
break; // moved the entire distance
if (!trace.ent)
Host_Error ("SV_FlyMove: !trace.ent");
if (dpcompat_noretouchground.ival)
{ //note: also sets onground AFTER the touch event.
if (!((int)ent->v->flags&FL_ONGROUND) || ent->v->groundentity!=EDICT_TO_PROG(w->progs, trace.ent))
WPhys_Impact (w, ent, &trace);
}
if (-DotProduct(gravitydir, trace.plane.normal) > 0.7)
{
blocked |= 1; // floor
if (((wedict_t *)trace.ent)->v->solid == SOLID_BSP || dpcompat_noretouchground.ival)
{
ent->v->flags = (int)ent->v->flags | FL_ONGROUND;
ent->v->groundentity = EDICT_TO_PROG(w->progs, trace.ent);
}
}
if (!DotProduct(gravitydir, trace.plane.normal))
{
blocked |= 2; // step
if (steptrace)
*steptrace = trace; // save for player extrafriction
}
//
// run the impact function
//
if (!dpcompat_noretouchground.ival)
WPhys_Impact (w, ent, &trace);
if (ED_ISFREE(ent))
break; // removed by the impact function
time_left -= time_left * trace.fraction;
// cliped to another plane
if (numplanes >= MAX_CLIP_PLANES)
{ // this shouldn't really happen
VectorClear (ent->v->velocity);
if (steptrace)
*steptrace = trace; // save for player extrafriction
return 3;
}
if (0)
{
ClipVelocity(ent->v->velocity, trace.plane.normal, ent->v->velocity, 1);
break;
}
else
{
if (numplanes)
{
VectorSubtract(planes[0], trace.plane.normal, diff);
if (Length(diff) < 0.01)
continue; //hit this plane already
}
VectorCopy (trace.plane.normal, planes[numplanes]);
numplanes++;
//
// modify original_velocity so it parallels all of the clip planes
//
for (i=0 ; i<numplanes ; i++)
{
ClipVelocity (original_velocity, planes[i], new_velocity, 1);
for (j=0 ; j<numplanes ; j++)
if (j != i)
{
if (DotProduct (new_velocity, planes[j]) < 0)
break; // not ok
}
if (j == numplanes)
break;
}
if (i != numplanes)
{ // go along this plane
// Con_Printf ("%5.1f %5.1f %5.1f ",ent->v->velocity[0], ent->v->velocity[1], ent->v->velocity[2]);
VectorCopy (new_velocity, ent->v->velocity);
// Con_Printf ("%5.1f %5.1f %5.1f\n",ent->v->velocity[0], ent->v->velocity[1], ent->v->velocity[2]);
}
else
{ // go along the crease
if (numplanes != 2)
{
// Con_Printf ("clip velocity, numplanes == %i\n",numplanes);
// Con_Printf ("%5.1f %5.1f %5.1f ",ent->v->velocity[0], ent->v->velocity[1], ent->v->velocity[2]);
VectorClear (ent->v->velocity);
// Con_Printf ("%5.1f %5.1f %5.1f\n",ent->v->velocity[0], ent->v->velocity[1], ent->v->velocity[2]);
return 7;
}
// Con_Printf ("%5.1f %5.1f %5.1f ",ent->v->velocity[0], ent->v->velocity[1], ent->v->velocity[2]);
CrossProduct (planes[0], planes[1], dir);
VectorNormalize(dir); //fixes slow falling in corners
d = DotProduct (dir, ent->v->velocity);
VectorScale (dir, d, ent->v->velocity);
// Con_Printf ("%5.1f %5.1f %5.1f\n",ent->v->velocity[0], ent->v->velocity[1], ent->v->velocity[2]);
}
}
//
// if original velocity is against the original velocity, stop dead
// to avoid tiny occilations in sloping corners
//
if (DotProduct (ent->v->velocity, primal_velocity) <= 0)
{
VectorClear (ent->v->velocity);
return blocked;
}
}
return blocked;
}
/*
============
SV_AddGravity
============
*/
static void WPhys_AddGravity (world_t *w, wedict_t *ent, const float *gravitydir)
{
float scale = ent->xv->gravity;
if (!scale)
scale = (ent->v->movetype == MOVETYPE_BOUNCEMISSILE)?0.5:1.0;
VectorMA(ent->v->velocity, scale * movevars.gravity * host_frametime, gravitydir, ent->v->velocity);
}
/*
===============================================================================
PUSHMOVE
===============================================================================
*/
/*
============
SV_PushEntity
Does not change the entities velocity at all
============
*/
static trace_t WPhys_PushEntity (world_t *w, wedict_t *ent, vec3_t push, unsigned int traceflags)
{
trace_t trace;
vec3_t end;
wedict_t *impact;
VectorAdd (ent->v->origin, push, end);
if ((int)ent->v->flags&FLQW_LAGGEDMOVE)
traceflags |= MOVE_LAGGED;
if (ent->v->movetype == MOVETYPE_FLYMISSILE)
traceflags |= MOVE_MISSILE;
else if (ent->v->solid == SOLID_TRIGGER || ent->v->solid == SOLID_NOT)
// only clip against bmodels
traceflags |= MOVE_NOMONSTERS;
else
traceflags |= MOVE_NORMAL;
trace = World_Move (w, ent->v->origin, ent->v->mins, ent->v->maxs, end, traceflags, (wedict_t*)ent);
impact = trace.ent;
if (impact && impact->v->solid == SOLID_PORTAL)
{
vec3_t move;
vec3_t from;
float firstfrac = trace.fraction;
VectorCopy(trace.endpos, from); //just in case
VectorSubtract(end, trace.endpos, move);
WPhys_PortalTransform(w, ent, impact, from, move);
VectorAdd(from, move, end);
trace = World_Move (w, from, ent->v->mins, ent->v->maxs, end, traceflags, (wedict_t*)ent);
trace.fraction = firstfrac + (1-firstfrac)*trace.fraction;
}
/*hexen2's movetype_swim does not allow swimming entities to move out of water. this implementation is quite hacky, but matches hexen2 well enough*/
if (ent->v->movetype == MOVETYPE_H2SWIM)
{
if (!(w->worldmodel->funcs.PointContents(w->worldmodel, NULL, trace.endpos) & (FTECONTENTS_WATER|FTECONTENTS_SLIME|FTECONTENTS_LAVA)))
{
VectorCopy(ent->v->origin, trace.endpos);
trace.fraction = 0;
trace.ent = w->edicts;
}
}
#if defined(HAVE_SERVER) && defined(HEXEN2)
else if (ent->v->solid == SOLID_PHASEH2 && progstype == PROG_H2 && w == &sv.world && trace.fraction != 1 && trace.ent &&
(((int)((wedict_t*)trace.ent)->v->flags & FL_MONSTER) || (int)((wedict_t*)trace.ent)->v->movetype == MOVETYPE_WALK))
{ //hexen2's SOLID_PHASEH2 ents should pass through players+monsters, yet still trigger impacts. I would use MOVE_ENTCHAIN but that would corrupt .chain, perhaps that's okay though?
//continue the trace on to where we wold be if there had been no impact
trace_t trace2 = World_Move (w, trace.endpos, ent->v->mins, ent->v->maxs, end, traceflags|MOVE_NOMONSTERS|MOVE_MISSILE|MOVE_RESERVED/*Don't fuck up in the face of dp's MOVE_WORLDONLY*/, (wedict_t*)ent);
//do the first non-world impact
// if (trace.ent)
// VectorMA(trace.endpos, sv_impactpush.value, trace.plane.normal, ent->v->origin);
// else
VectorCopy (trace.endpos, ent->v->origin);
World_LinkEdict (w, ent, true);
if (trace.ent)
{
WPhys_Impact (w, ent, &trace);
if (ent->ereftype != ER_ENTITY)
return trace; //someone remove()d it. don't do weird stuff.
}
//and use our regular impact logic for the rest of it.
trace = trace2;
}
#endif
// if (trace.ent)
// VectorMA(trace.endpos, sv_impactpush.value, trace.plane.normal, ent->v->origin);
// else
VectorCopy (trace.endpos, ent->v->origin);
World_LinkEdict (w, ent, true);
if (trace.ent)
WPhys_Impact (w, ent, &trace);
return trace;
}
typedef struct
{
wedict_t *ent;
vec3_t origin;
vec3_t angles;
} pushed_t;
static pushed_t pushed[1024], *pushed_p;
/*
============
SV_Push
Objects need to be moved back on a failed push,
otherwise riders would continue to slide.
============
*/
static qboolean WPhys_PushAngles (world_t *w, wedict_t *pusher, vec3_t move, vec3_t amove)
{
int i, e;
wedict_t *check, *block;
vec3_t mins, maxs;
//float oldsolid;
pushed_t *p;
vec3_t org, org2, move2, forward, right, up;
#ifdef HAVE_SERVER
short yawchange = (amove[PITCH]||amove[ROLL])?0:ANGLE2SHORT(amove[YAW]);
#endif
pushed_p = pushed;
// find the bounding box
for (i=0 ; i<3 ; i++)
{
mins[i] = pusher->v->absmin[i] + move[i];
maxs[i] = pusher->v->absmax[i] + move[i];
}
// we need this for pushing things later
VectorNegate (amove, org);
AngleVectors (org, forward, right, up);
// save the pusher's original position
pushed_p->ent = pusher;
VectorCopy (pusher->v->origin, pushed_p->origin);
VectorCopy (pusher->v->angles, pushed_p->angles);
pushed_p++;
// move the pusher to it's final position
VectorAdd (pusher->v->origin, move, pusher->v->origin);
VectorAdd (pusher->v->angles, amove, pusher->v->angles);
World_LinkEdict (w, pusher, false);
// see if any solid entities are inside the final position
if (pusher->v->movetype != MOVETYPE_H2PUSHPULL)
for (e = 1; e < w->num_edicts; e++)
{
check = WEDICT_NUM_PB(w->progs, e);
if (ED_ISFREE(check))
continue;
if (check->v->movetype == MOVETYPE_PUSH
|| check->v->movetype == MOVETYPE_NONE
|| check->v->movetype == MOVETYPE_NOCLIP
|| check->v->movetype == MOVETYPE_ANGLENOCLIP)
continue;
/*
oldsolid = pusher->v->solid;
pusher->v->solid = SOLID_NOT;
block = World_TestEntityPosition (w, check);
pusher->v->solid = oldsolid;
if (block)
continue;
*/
// if the entity is standing on the pusher, it will definitely be moved
if ( ! ( ((int)check->v->flags & FL_ONGROUND)
&& PROG_TO_WEDICT(w->progs, check->v->groundentity) == pusher) )
{
// see if the ent needs to be tested
if ( check->v->absmin[0] >= maxs[0]
|| check->v->absmin[1] >= maxs[1]
|| check->v->absmin[2] >= maxs[2]
|| check->v->absmax[0] <= mins[0]
|| check->v->absmax[1] <= mins[1]
|| check->v->absmax[2] <= mins[2] )
continue;
// see if the ent's bbox is inside the pusher's final position
if (!World_TestEntityPosition (w, (wedict_t*)check))
continue;
}
if ((pusher->v->movetype == MOVETYPE_PUSH) || (PROG_TO_WEDICT(w->progs, check->v->groundentity) == pusher))
{
if (pushed_p == (pushed+(sizeof(pushed)/sizeof(pushed[0]))))
continue;
// move this entity
pushed_p->ent = check;
VectorCopy (check->v->origin, pushed_p->origin);
VectorCopy (check->v->angles, pushed_p->angles);
pushed_p++;
// try moving the contacted entity
VectorAdd (check->v->origin, move, check->v->origin);
VectorAdd (check->v->angles, amove, check->v->angles);
#ifdef HAVE_SERVER
if (w == &sv.world && check->entnum>0&&(check->entnum)<=sv.allocated_client_slots)
svs.clients[check->entnum-1].baseangles[YAW] += yawchange;
#endif
// figure movement due to the pusher's amove
VectorSubtract (check->v->origin, pusher->v->origin, org);
org2[0] = DotProduct (org, forward);
org2[1] = -DotProduct (org, right);
org2[2] = DotProduct (org, up);
VectorSubtract (org2, org, move2);
VectorAdd (check->v->origin, move2, check->v->origin);
if (check->v->movetype != MOVETYPE_WALK)
check->v->flags = (int)check->v->flags & ~FL_ONGROUND;
// may have pushed them off an edge
if (PROG_TO_WEDICT(w->progs, check->v->groundentity) != pusher)
check->v->groundentity = 0;
block = World_TestEntityPosition (w, check);
if (!block)
{ // pushed ok
World_LinkEdict (w, check, false);
// impact?
continue;
}
// if it is ok to leave in the old position, do it
// this is only relevent for riding entities, not pushed
// FIXME: this doesn't acount for rotation
VectorCopy (pushed_p[-1].origin, check->v->origin);
block = World_TestEntityPosition (w, check);
if (!block)
{
pushed_p--;
continue;
}
//okay, that didn't work, try pushing the against stuff
WPhys_PushEntity(w, check, move, 0);
block = World_TestEntityPosition (w, check);
if (!block)
continue;
VectorCopy(check->v->origin, move);
for (i = 0; i < 8 && block; i++)
{
//precision errors can strike when you least expect it. lets try and reduce them.
check->v->origin[0] = move[0] + ((i&1)?-1:1)/8.0;
check->v->origin[1] = move[1] + ((i&2)?-1:1)/8.0;
check->v->origin[2] = move[2] + ((i&4)?-1:1)/8.0;
block = World_TestEntityPosition (w, check);
}
if (!block)
{
World_LinkEdict (w, check, false);
continue;
}
}
// if it is sitting on top. Do not block.
if (check->v->mins[0] == check->v->maxs[0])
{
World_LinkEdict (w, check, false);
continue;
}
//some pushers are contents brushes, and are not solid. water cannot crush. the player just enters the water.
//but, the player will be moved along with the water if possible.
if (pusher->v->skin < 0)
continue;
if (check->v->solid == SOLID_NOT || check->v->solid == SOLID_TRIGGER)
{ // corpse
check->v->mins[0] = check->v->mins[1] = 0;
VectorCopy (check->v->mins, check->v->maxs);
World_LinkEdict (w, check, false);
continue;
}
// Con_Printf("Pusher hit %s\n", PR_GetString(w->progs, check->v->classname));
if (pusher->v->blocked)
{
*w->g.self = EDICT_TO_PROG(w->progs, pusher);
*w->g.other = EDICT_TO_PROG(w->progs, check);
#ifdef VM_Q1
if (w==&sv.world && svs.gametype == GT_Q1QVM)
Q1QVM_Blocked();
else
#endif
PR_ExecuteProgram (w->progs, pusher->v->blocked);
}
// move back any entities we already moved
// go backwards, so if the same entity was pushed
// twice, it goes back to the original position
for (p=pushed_p-1 ; p>=pushed ; p--)
{
VectorCopy (p->origin, p->ent->v->origin);
VectorCopy (p->angles, p->ent->v->angles);
World_LinkEdict (w, p->ent, false);
#ifdef HAVE_SERVER
if (w==&sv.world && p->ent->entnum>0&&(p->ent->entnum)<=sv.allocated_client_slots)
svs.clients[p->ent->entnum-1].baseangles[YAW] -= yawchange;
#endif
}
return false;
}
//FIXME: is there a better way to handle this?
// see if anything we moved has touched a trigger
for (p=pushed_p-1 ; p>=pushed ; p--)
World_TouchAllLinks (w, p->ent);
return true;
}
/*
============
SV_Push
============
*/
qboolean WPhys_Push (world_t *w, wedict_t *pusher, vec3_t move, vec3_t amove)
{
#define PUSHABLE_LIMIT 8192
int i, e;
wedict_t *check, *block;
vec3_t mins, maxs;
vec3_t pushorig;
int num_moved;
wedict_t *moved_edict[PUSHABLE_LIMIT];
vec3_t moved_from[PUSHABLE_LIMIT];
float oldsolid;
if ((amove[0] || amove[1] || amove[2]) && !w->remasterlogic)
{
return WPhys_PushAngles(w, pusher, move, amove);
}
for (i=0 ; i<3 ; i++)
{
mins[i] = pusher->v->absmin[i] + move[i]-(1/32.0);
maxs[i] = pusher->v->absmax[i] + move[i]+(1/32.0);
}
VectorCopy (pusher->v->origin, pushorig);
// move the pusher to it's final position
VectorAdd (pusher->v->origin, move, pusher->v->origin);
World_LinkEdict (w, pusher, false);
// see if any solid entities are inside the final position
num_moved = 0;
for (e=1 ; e<w->num_edicts ; e++)
{
check = WEDICT_NUM_PB(w->progs, e);
if (ED_ISFREE(check))
continue;
if (check->v->movetype == MOVETYPE_PUSH
|| check->v->movetype == MOVETYPE_NONE
|| check->v->movetype == MOVETYPE_FOLLOW
|| check->v->movetype == MOVETYPE_NOCLIP
|| check->v->movetype == MOVETYPE_ANGLENOCLIP)
continue;
// if the entity is standing on the pusher, it will definately be moved
if ( ! ( ((int)check->v->flags & FL_ONGROUND)
&&
PROG_TO_WEDICT(w->progs, check->v->groundentity) == pusher) )
{
if ( check->v->absmin[0] >= maxs[0]
|| check->v->absmin[1] >= maxs[1]
|| check->v->absmin[2] >= maxs[2]
|| check->v->absmax[0] <= mins[0]
|| check->v->absmax[1] <= mins[1]
|| check->v->absmax[2] <= mins[2] )
continue;
// see if the ent's bbox is inside the pusher's final position
if (!World_TestEntityPosition (w, check))
continue;
}
oldsolid = pusher->v->solid;
pusher->v->solid = SOLID_NOT;
block = World_TestEntityPosition (w, check);
pusher->v->solid = oldsolid;
if (block)
continue;
if (num_moved == PUSHABLE_LIMIT)
break;
VectorCopy (check->v->origin, moved_from[num_moved]);
moved_edict[num_moved] = check;
num_moved++;
if (check->v->groundentity != pusher->entnum)
check->v->flags = (int)check->v->flags & ~FL_ONGROUND;
// try moving the contacted entity
VectorAdd (check->v->origin, move, check->v->origin);
if (pusher->v->skin < 0)
{
pusher->v->solid = SOLID_NOT;
block = World_TestEntityPosition (w, check);
pusher->v->solid = oldsolid;
}
else
block = World_TestEntityPosition (w, check);
if (!block)
{ // pushed ok
World_LinkEdict (w, check, false);
continue;
}
if (block)
{
//try to nudge it forward by an epsilon to avoid precision issues
float movelen = VectorLength(move);
VectorMA(check->v->origin, (1/8.0)/movelen, move, check->v->origin);
block = World_TestEntityPosition (w, check);
if (!block)
{ //okay, that got it. we're all good.
World_LinkEdict (w, check, false);
continue;
}
}
// if it is ok to leave in the old position, do it
VectorCopy (moved_from[num_moved-1], check->v->origin);
block = World_TestEntityPosition (w, check);
if (!block)
{
//if leaving it where it was, allow it to drop to the floor again (useful for plats that move downward)
if (check->v->movetype != MOVETYPE_WALK)
check->v->flags = (int)check->v->flags & ~FL_ONGROUND;
num_moved--;
continue;
}
// its blocking us. this is probably a problem.
//corpses
if (check->v->mins[0] == check->v->maxs[0])
{
World_LinkEdict (w, check, false);
continue;
}
if (check->v->solid == SOLID_NOT || check->v->solid == SOLID_TRIGGER)
{ // corpse
check->v->mins[0] = check->v->mins[1] = 0;
VectorCopy (check->v->mins, check->v->maxs);
World_LinkEdict (w, check, false);
continue;
}
//these pushers are contents brushes, and are not solid. water cannot crush. the player just enters the water.
//but, the player will be moved along with the water.
if (pusher->v->skin < 0)
continue;
VectorCopy (pushorig, pusher->v->origin);
World_LinkEdict (w, pusher, false);
// if the pusher has a "blocked" function, call it
// otherwise, just stay in place until the obstacle is gone
if (pusher->v->blocked)
{
*w->g.self = EDICT_TO_PROG(w->progs, pusher);
*w->g.other = EDICT_TO_PROG(w->progs, check);
#ifdef VM_Q1
if (w==&sv.world && svs.gametype == GT_Q1QVM)
Q1QVM_Blocked();
else
#endif
PR_ExecuteProgram (w->progs, pusher->v->blocked);
} else {
*w->g.other = 0;
}
// move back any entities we already moved
for (i=0 ; i<num_moved ; i++)
{
VectorCopy (moved_from[i], moved_edict[i]->v->origin);
World_LinkEdict (w, moved_edict[i], false);
}
return false;
}
return true;
}
/*
============
SV_PushMove
============
*/
static void WPhys_PushMove (world_t *w, wedict_t *pusher, float movetime)
{
int i;
vec3_t move;
vec3_t amove;
if (!pusher->v->velocity[0] && !pusher->v->velocity[1] && !pusher->v->velocity[2]
&& !pusher->v->avelocity[0] && !pusher->v->avelocity[1] && !pusher->v->avelocity[2])
{
pusher->v->ltime += movetime;
return;
}
for (i=0 ; i<3 ; i++)
{
move[i] = pusher->v->velocity[i] * movetime;
amove[i] = pusher->v->avelocity[i] * movetime;
}
if (WPhys_Push (w, pusher, move, amove))
pusher->v->ltime += movetime;
}
/*
================
SV_Physics_Pusher
================
*/
static void WPhys_Physics_Pusher (world_t *w, wedict_t *ent)
{
float thinktime;
float oldltime;
float movetime;
vec3_t oldorg, move;
vec3_t oldang, amove;
float l;
oldltime = ent->v->ltime;
thinktime = ent->v->nextthink;
if (thinktime < ent->v->ltime + host_frametime)
{
movetime = thinktime - ent->v->ltime;
if (movetime < 0)
movetime = 0;
}
else
movetime = host_frametime;
if (movetime)
{
WPhys_PushMove (w, ent, movetime); // advances ent->v->ltime if not blocked
}
if (thinktime > oldltime && thinktime <= ent->v->ltime)
{
VectorCopy (ent->v->origin, oldorg);
VectorCopy (ent->v->angles, oldang);
ent->v->nextthink = 0;
#if 1
*w->g.time = w->physicstime;
w->Event_Think(w, ent);
#else
pr_global_struct->time = sv.world.physicstime;
pr_global_struct->self = EDICT_TO_PROG(w->progs, ent);
pr_global_struct->other = EDICT_TO_PROG(w->progs, w->edicts);
#ifdef VM_Q1
if (svs.gametype == GT_Q1QVM)
Q1QVM_Think();
else
#endif
PR_ExecuteProgram (svprogfuncs, ent->v->think);
#endif
if (ED_ISFREE(ent))
return;
VectorSubtract (ent->v->origin, oldorg, move);
VectorSubtract (ent->v->angles, oldang, amove);
l = Length(move)+Length(amove);
if (l > 1.0/64)
{
// Con_Printf ("**** snap: %f\n", Length (l));
VectorCopy (oldorg, ent->v->origin);
VectorCopy (oldang, ent->v->angles);
WPhys_Push (w, ent, move, amove);
}
}
}
/*
=============
SV_Physics_Follow
Entities that are "stuck" to another entity
=============
*/
static void WPhys_Physics_Follow (world_t *w, wedict_t *ent)
{
vec3_t vf, vr, vu, angles, v;
wedict_t *e;
// regular thinking
if (!WPhys_RunThink (w, ent))
return;
// LordHavoc: implemented rotation on MOVETYPE_FOLLOW objects
e = PROG_TO_WEDICT(w->progs, ent->v->aiment);
if (e->v->angles[0] == ent->xv->punchangle[0] && e->v->angles[1] == ent->xv->punchangle[1] && e->v->angles[2] == ent->xv->punchangle[2])
{
// quick case for no rotation
VectorAdd(e->v->origin, ent->v->view_ofs, ent->v->origin);
}
else
{
angles[0] = ent->xv->punchangle[0] * r_meshpitch.value;
angles[1] = ent->xv->punchangle[1];
angles[2] = ent->xv->punchangle[2] * r_meshroll.value;
AngleVectors (angles, vf, vr, vu);
v[0] = ent->v->view_ofs[0] * vf[0] + ent->v->view_ofs[1] * vr[0] + ent->v->view_ofs[2] * vu[0];
v[1] = ent->v->view_ofs[0] * vf[1] + ent->v->view_ofs[1] * vr[1] + ent->v->view_ofs[2] * vu[1];
v[2] = ent->v->view_ofs[0] * vf[2] + ent->v->view_ofs[1] * vr[2] + ent->v->view_ofs[2] * vu[2];
angles[0] = e->v->angles[0] * r_meshpitch.value;
angles[1] = e->v->angles[1];
angles[2] = e->v->angles[2] * r_meshroll.value;
AngleVectors (angles, vf, vr, vu);
ent->v->origin[0] = v[0] * vf[0] + v[1] * vf[1] + v[2] * vf[2] + e->v->origin[0];
ent->v->origin[1] = v[0] * vr[0] + v[1] * vr[1] + v[2] * vr[2] + e->v->origin[1];
ent->v->origin[2] = v[0] * vu[0] + v[1] * vu[1] + v[2] * vu[2] + e->v->origin[2];
}
VectorAdd (e->v->angles, ent->v->v_angle, ent->v->angles);
World_LinkEdict (w, ent, true);
}
/*
=============
SV_Physics_Noclip
A moving object that doesn't obey physics
=============
*/
static void WPhys_Physics_Noclip (world_t *w, wedict_t *ent)
{
vec3_t end;
#ifdef HAVE_SERVER
trace_t trace;
wedict_t *impact;
#endif
// regular thinking
if (!WPhys_RunThink (w, ent))
return;
VectorMA (ent->v->angles, host_frametime, ent->v->avelocity, ent->v->angles);
VectorMA (ent->v->origin, host_frametime, ent->v->velocity, end);
#ifdef HAVE_SERVER
//allow spectators to no-clip through portals without bogging down sock's mods.
if (ent->entnum > 0 && ent->entnum <= sv.allocated_client_slots && w == &sv.world)
{
trace = World_Move (w, ent->v->origin, ent->v->mins, ent->v->maxs, end, MOVE_NOMONSTERS, (wedict_t*)ent);
impact = trace.ent;
if (impact && impact->v->solid == SOLID_PORTAL)
{
vec3_t move;
vec3_t from;
VectorCopy(trace.endpos, from); //just in case
VectorSubtract(end, trace.endpos, move);
WPhys_PortalTransform(w, ent, impact, from, move);
VectorAdd(from, move, end);
}
}
#endif
VectorCopy(end, ent->v->origin);
World_LinkEdict (w, (wedict_t*)ent, false);
}
/*
==============================================================================
TOSS / BOUNCE
==============================================================================
*/
/*
=============
SV_CheckWaterTransition
=============
*/
static void WPhys_CheckWaterTransition (world_t *w, wedict_t *ent)
{
int cont;
cont = World_PointContentsWorldOnly (w, ent->v->origin);
//needs to be q1 progs compatible
if (cont & FTECONTENTS_LAVA)
cont = Q1CONTENTS_LAVA;
else if (cont & FTECONTENTS_SLIME)
cont = Q1CONTENTS_SLIME;
else if (cont & FTECONTENTS_WATER)
cont = Q1CONTENTS_WATER;
else
cont = Q1CONTENTS_EMPTY;
if (!ent->v->watertype)
{ // just spawned here
ent->v->watertype = cont;
ent->v->waterlevel = 1;
return;
}
if (ent->v->watertype != cont && w->Event_ContentsTransition(w, ent, ent->v->watertype, cont))
{
ent->v->watertype = cont;
ent->v->waterlevel = 1;
}
else if (cont <= Q1CONTENTS_WATER)
{
if (ent->v->watertype == Q1CONTENTS_EMPTY && *sv_sound_watersplash.string)
{ // just crossed into water
w->Event_Sound(NULL, ent, 0, sv_sound_watersplash.string, 255, 1, 0, 0, 0);
}
ent->v->watertype = cont;
ent->v->waterlevel = 1;
}
else
{
if (ent->v->watertype != Q1CONTENTS_EMPTY && *sv_sound_watersplash.string)
{ // just crossed into open
w->Event_Sound(NULL, ent, 0, sv_sound_watersplash.string, 255, 1, 0, 0, 0);
}
ent->v->watertype = Q1CONTENTS_EMPTY;
ent->v->waterlevel = cont;
}
}
/*
=============
SV_Physics_Toss
Toss, bounce, and fly movement. When onground, do nothing.
=============
*/
static void WPhys_Physics_Toss (world_t *w, wedict_t *ent)
{
trace_t trace;
vec3_t move;
float backoff;
int fl;
const float *gravitydir;
int movetype;
WPhys_CheckVelocity (w, ent);
// regular thinking
if (!WPhys_RunThink (w, ent))
return;
if (ent->xv->gravitydir[2] || ent->xv->gravitydir[1] || ent->xv->gravitydir[0])
gravitydir = ent->xv->gravitydir;
else
gravitydir = w->g.defaultgravitydir;
// if onground, return without moving
if ( ((int)ent->v->flags & FL_ONGROUND) )
{
if (-DotProduct(gravitydir, ent->v->velocity) >= (1.0f/32.0f))
ent->v->flags = (int)ent->v->flags & ~FL_ONGROUND;
else
{
if (sv_gameplayfix_noairborncorpse.value)
{
wedict_t *onent;
onent = PROG_TO_WEDICT(w->progs, ent->v->groundentity);
if (!ED_ISFREE(onent))
return; //don't drop if our fround is still valid
}
else
return; //don't drop, even if the item we were on was removed (certain dm maps do this for q3 style stuff).
}
}
// add gravity
movetype = ent->v->movetype;
if (movetype != MOVETYPE_FLY
&& movetype != MOVETYPE_FLY_WORLDONLY
&& movetype != MOVETYPE_FLYMISSILE
&& (movetype != MOVETYPE_BOUNCEMISSILE || w->remasterlogic/*gib*/)
&& movetype != MOVETYPE_H2SWIM)
WPhys_AddGravity (w, ent, gravitydir);
// move angles
VectorMA (ent->v->angles, host_frametime, ent->v->avelocity, ent->v->angles);
// move origin
VectorScale (ent->v->velocity, host_frametime, move);
if (!DotProduct(move, move))
{
//rogue buzzsaws are vile and jerkily move via setorigin, and need to be relinked so that they can touch path corners.
if (ent->v->solid && ent->v->nextthink)
World_LinkEdict (w, ent, true);
return;
}
fl = 0;
#ifndef CLIENTONLY
/*doesn't affect csqc, as it has no lagged ents registered anywhere*/
if (sv_antilag.ival==2)
fl |= MOVE_LAGGED;
#endif
trace = WPhys_PushEntity (w, ent, move, fl);
if (trace.allsolid && sv_gameplayfix_trappedwithin.ival && ent->v->solid != SOLID_NOT && ent->v->solid != SOLID_TRIGGER)
{
trace.fraction = 0; //traces that start in solid report a fraction of 0. this is to prevent things from dropping out of the world completely. at least this way they ought to still be shootable etc
#pragma warningmsg("The following line might help boost framerates a lot in rmq, not sure if they violate expected behaviour in other mods though - check that they're safe.")
VectorNegate(gravitydir, trace.plane.normal);
}
if (trace.fraction == 1 || !trace.ent)
return;
if (ED_ISFREE(ent))
return;
VectorCopy(trace.endpos, move);
movetype = ent->v->movetype;
if (movetype == MOVETYPE_BOUNCEMISSILE && w->remasterlogic)
movetype = MOVETYPE_BOUNCE; //'gib'...
if (movetype == MOVETYPE_BOUNCE)
{
if (ent->xv->bouncefactor)
backoff = 1 + ent->xv->bouncefactor;
else
backoff = 1.5;
}
else if (movetype == MOVETYPE_BOUNCEMISSILE)
{
if (ent->xv->bouncefactor)
backoff = 1 + ent->xv->bouncefactor;
// else if (progstype == PROG_H2 && ent->v->solid == SOLID_PHASEH2 && ((int)((wedict_t*)trace.ent)->v->flags & (FL_MONSTER|FL_CLIENT)))
// backoff = 0; //don't bounce/slide, just pass straight through.
else
backoff = w->remasterlogic?1.5/*gib...*/:2;
}
else
backoff = 1;
if (backoff)
ClipVelocity (ent->v->velocity, trace.plane.normal, ent->v->velocity, backoff);
// stop if on ground
if ((-DotProduct(gravitydir, trace.plane.normal) > 0.7) && (movetype != MOVETYPE_BOUNCEMISSILE))
{
float bouncespeed;
float bouncestop = ent->xv->bouncestop;
if (!bouncestop)
bouncestop = 60;
else
bouncestop *= movevars.gravity * (ent->xv->gravity?ent->xv->gravity:1);
if (sv_gameplayfix_bouncedownslopes.ival)
bouncespeed = DotProduct(trace.plane.normal, ent->v->velocity);
else
bouncespeed = -DotProduct(gravitydir, ent->v->velocity);
if (bouncespeed < bouncestop || movetype != MOVETYPE_BOUNCE )
{
ent->v->flags = (int)ent->v->flags | FL_ONGROUND;
ent->v->groundentity = EDICT_TO_PROG(w->progs, trace.ent);
VectorClear (ent->v->velocity);
VectorClear (ent->v->avelocity);
}
}
// check for in water
WPhys_CheckWaterTransition (w, ent);
}
/*
===============================================================================
STEPPING MOVEMENT
===============================================================================
*/
/*
=============
SV_Physics_Step
Monsters freefall when they don't have a ground entity, otherwise
all movement is done with discrete steps.
This is also used for objects that have become still on the ground, but
will fall if the floor is pulled out from under them.
FIXME: is this true?
=============
*/
static void WPhys_Physics_Step (world_t *w, wedict_t *ent)
{
qboolean hitsound;
qboolean freefall;
int fl = ent->v->flags;
const float *gravitydir;
vec3_t oldorg;
VectorCopy(ent->v->origin, oldorg);
if (ent->xv->gravitydir[2] || ent->xv->gravitydir[1] || ent->xv->gravitydir[0])
gravitydir = ent->xv->gravitydir;
else
gravitydir = w->g.defaultgravitydir;
if (-DotProduct(gravitydir, ent->v->velocity) >= (1.0 / 32.0) && (fl & FL_ONGROUND))
{
fl &= ~FL_ONGROUND;
ent->v->flags = fl;
}
// frefall if not onground
if (fl & (FL_ONGROUND | FL_FLY))
freefall = false;
else
freefall = true;
if (fl & FL_SWIM)
freefall = ent->v->waterlevel <= 0;
if (freefall)
{
hitsound = -DotProduct(gravitydir, ent->v->velocity) < movevars.gravity*-0.1;
WPhys_AddGravity (w, ent, gravitydir);
WPhys_CheckVelocity (w, ent);
WPhys_FlyMove (w, ent, gravitydir, host_frametime, NULL);
World_LinkEdict (w, ent, true);
if ( (int)ent->v->flags & FL_ONGROUND ) // just hit ground
{
#if defined(HEXEN2) && defined(HAVE_SERVER)
if (w==&sv.world && progstype == PROG_H2 && ((int)ent->v->flags & FL_MONSTER))
; //hexen2 monsters do not make landing sounds.
else
#endif
if (hitsound && *sv_sound_land.string)
{
w->Event_Sound(NULL, ent, 0, sv_sound_land.string, 255, 1, 0, 0, 0);
}
}
}
// regular thinking
WPhys_RunThink (w, ent);
if (!VectorEquals(ent->v->origin, oldorg))
WPhys_CheckWaterTransition (w, ent);
}
//============================================================================
#ifndef CLIENTONLY
void SV_ProgStartFrame (void)
{
// let the progs know that a new frame has started
pr_global_struct->self = EDICT_TO_PROG(svprogfuncs, sv.world.edicts);
pr_global_struct->other = EDICT_TO_PROG(svprogfuncs, sv.world.edicts);
pr_global_struct->time = sv.world.physicstime;
#ifdef VM_Q1
if (svs.gametype == GT_Q1QVM)
Q1QVM_StartFrame(false);
else
#endif
{
if (pr_global_ptrs->StartFrame)
PR_ExecuteProgram (svprogfuncs, *pr_global_ptrs->StartFrame);
}
}
#endif
/*
=============
SV_CheckStuck
This is a big hack to try and fix the rare case of getting stuck in the world
clipping hull.
=============
*/
static void WPhys_CheckStuck (world_t *w, wedict_t *ent)
{
int i, j;
int z;
vec3_t org;
//return;
if (!World_TestEntityPosition (w, ent))
{
VectorCopy (ent->v->origin, ent->v->oldorigin);
return;
}
VectorCopy (ent->v->origin, org);
VectorCopy (ent->v->oldorigin, ent->v->origin);
if (!World_TestEntityPosition (w, ent))
{
Con_DPrintf ("Unstuck.\n");
World_LinkEdict (w, ent, true);
return;
}
for (z=0 ; z < movevars.stepheight ; z++)
for (i=-1 ; i <= 1 ; i++)
for (j=-1 ; j <= 1 ; j++)
{
ent->v->origin[0] = org[0] + i;
ent->v->origin[1] = org[1] + j;
ent->v->origin[2] = org[2] + z;
if (!World_TestEntityPosition (w, ent))
{
Con_DPrintf ("Unstuck.\n");
World_LinkEdict (w, ent, true);
return;
}
}
VectorCopy (org, ent->v->origin);
Con_DPrintf ("player is stuck.\n");
}
/*
=============
SV_CheckWater
=============
for players
*/
static qboolean WPhys_CheckWater (world_t *w, wedict_t *ent)
{
vec3_t point;
int cont;
int hc;
trace_t tr;
//check if we're on a ladder, and if so fire a trace forwards to ensure its a valid ladder instead of a random volume
hc = ent->xv->hitcontentsmaski; //lame
ent->xv->hitcontentsmaski = ~0;
tr = World_Move(w, ent->v->origin, ent->v->mins, ent->v->maxs, ent->v->origin, 0, ent);
ent->xv->hitcontentsmaski = hc;
if (tr.contents & FTECONTENTS_LADDER)
{
vec3_t flatforward;
flatforward[0] = cos((M_PI/180)*ent->v->angles[1]);
flatforward[1] = sin((M_PI/180)*ent->v->angles[1]);
flatforward[2] = 0;
VectorMA (ent->v->origin, 24, flatforward, point);
tr = World_Move(w, ent->v->origin, ent->v->mins, ent->v->maxs, point, 0, ent);
if (tr.fraction < 1)
ent->xv->pmove_flags = (int)ent->xv->pmove_flags|PMF_LADDER;
else if ((int)ent->xv->pmove_flags & PMF_LADDER)
ent->xv->pmove_flags -= PMF_LADDER;
}
else if ((int)ent->xv->pmove_flags & PMF_LADDER)
ent->xv->pmove_flags -= PMF_LADDER;
point[0] = ent->v->origin[0];
point[1] = ent->v->origin[1];
point[2] = ent->v->origin[2] + ent->v->mins[2] + 1;
ent->v->waterlevel = 0;
ent->v->watertype = Q1CONTENTS_EMPTY;
cont = World_PointContentsAllBSPs (w, point);
if (cont & FTECONTENTS_FLUID)
{
if (cont & FTECONTENTS_LAVA)
ent->v->watertype = Q1CONTENTS_LAVA;
else if (cont & FTECONTENTS_SLIME)
ent->v->watertype = Q1CONTENTS_SLIME;
else if (cont & FTECONTENTS_WATER)
ent->v->watertype = Q1CONTENTS_WATER;
else
ent->v->watertype = Q1CONTENTS_SKY;
ent->v->waterlevel = 1;
point[2] = ent->v->origin[2] + (ent->v->mins[2] + ent->v->maxs[2])*0.5;
cont = World_PointContentsAllBSPs (w, point);
if (cont & FTECONTENTS_FLUID)
{
ent->v->waterlevel = 2;
point[2] = ent->v->origin[2] + ent->v->view_ofs[2];
cont = World_PointContentsAllBSPs (w, point);
if (cont & FTECONTENTS_FLUID)
ent->v->waterlevel = 3;
}
}
return ent->v->waterlevel > 1;
}
/*
============
SV_WallFriction
============
*/
static void WPhys_WallFriction (wedict_t *ent, trace_t *trace)
{
vec3_t forward, right, up;
float d, i;
vec3_t into, side;
AngleVectors (ent->v->v_angle, forward, right, up);
d = DotProduct (trace->plane.normal, forward);
d += 0.5;
if (d >= 0 || IS_NAN(d))
return;
// cut the tangential velocity
i = DotProduct (trace->plane.normal, ent->v->velocity);
VectorScale (trace->plane.normal, i, into);
VectorSubtract (ent->v->velocity, into, side);
ent->v->velocity[0] = side[0] * (1 + d);
ent->v->velocity[1] = side[1] * (1 + d);
}
/*
=====================
SV_TryUnstick
Player has come to a dead stop, possibly due to the problem with limited
float precision at some angle joins in the BSP hull.
Try fixing by pushing one pixel in each direction.
This is a hack, but in the interest of good gameplay...
======================
static int SV_TryUnstick (edict_t *ent, vec3_t oldvel)
{
int i;
vec3_t oldorg;
vec3_t dir;
int clip;
trace_t steptrace;
VectorCopy (ent->v->origin, oldorg);
VectorClear (dir);
for (i=0 ; i<8 ; i++)
{
// try pushing a little in an axial direction
switch (i)
{
case 0: dir[0] = 2; dir[1] = 0; break;
case 1: dir[0] = 0; dir[1] = 2; break;
case 2: dir[0] = -2; dir[1] = 0; break;
case 3: dir[0] = 0; dir[1] = -2; break;
case 4: dir[0] = 2; dir[1] = 2; break;
case 5: dir[0] = -2; dir[1] = 2; break;
case 6: dir[0] = 2; dir[1] = -2; break;
case 7: dir[0] = -2; dir[1] = -2; break;
}
SV_PushEntity (ent, dir, MOVE_NORMAL);
// retry the original move
ent->v->velocity[0] = oldvel[0];
ent->v-> velocity[1] = oldvel[1];
ent->v-> velocity[2] = 0;
clip = SV_FlyMove (ent, 0.1, &steptrace);
if ( fabs(oldorg[1] - ent->v->origin[1]) > 4
|| fabs(oldorg[0] - ent->v->origin[0]) > 4 )
{
//Con_DPrintf ("unstuck!\n");
return clip;
}
// go back to the original pos and try again
VectorCopy (oldorg, ent->v->origin);
}
VectorClear (ent->v->velocity);
return 7; // still not moving
}
*/
/*
=====================
SV_WalkMove
Only used by players
======================
*/
#if 0
#define SMSTEPSIZE 4
static void SV_WalkMove (edict_t *ent)
{
vec3_t upmove, downmove;
vec3_t oldorg, oldvel;
vec3_t nosteporg, nostepvel;
int clip;
int oldonground;
trace_t steptrace, downtrace;
//
// do a regular slide move unless it looks like you ran into a step
//
oldonground = (int)ent->v->flags & FL_ONGROUND;
ent->v->flags = (int)ent->v->flags & ~FL_ONGROUND;
VectorCopy (ent->v->origin, oldorg);
VectorCopy (ent->v->velocity, oldvel);
clip = SV_FlyMove (ent, host_frametime, &steptrace);
if ( !(clip & 2) )
return; // move didn't block on a step
if (!oldonground && ent->v->waterlevel == 0)
return; // don't stair up while jumping
if (ent->v->movetype != MOVETYPE_WALK)
return; // gibbed by a trigger
// if (sv_nostep.value)
// return;
if ( (int)ent->v->flags & FL_WATERJUMP )
return;
VectorCopy (ent->v->origin, nosteporg);
VectorCopy (ent->v->velocity, nostepvel);
//
// try moving up and forward to go up a step
//
VectorCopy (oldorg, ent->v->origin); // back to start pos
VectorCopy (vec3_origin, upmove);
VectorCopy (vec3_origin, downmove);
upmove[2] = movevars.stepheight;
downmove[2] = -movevars.stepheight + oldvel[2]*host_frametime;
// move up
SV_PushEntity (ent, upmove); // FIXME: don't link?
// move forward
ent->v->velocity[0] = oldvel[0];
ent->v->velocity[1] = oldvel[1];
ent->v->velocity[2] = 0;
clip = SV_FlyMove (ent, host_frametime, &steptrace);
// check for stuckness, possibly due to the limited precision of floats
// in the clipping hulls
if (clip)
{
if ( fabs(oldorg[1] - ent->v->origin[1]) < 0.03125
&& fabs(oldorg[0] - ent->v->origin[0]) < 0.03125 )
{ // stepping up didn't make any progress
clip = SV_TryUnstick (ent, oldvel);
// Con_Printf("Try unstick fwd\n");
}
}
// extra friction based on view angle
if ( clip & 2 )
{
vec3_t lastpos, lastvel, lastdown;
// Con_Printf("couldn't do it\n");
//retry with a smaller step (allows entering smaller areas with a step of 4)
VectorCopy (downmove, lastdown);
VectorCopy (ent->v->origin, lastpos);
VectorCopy (ent->v->velocity, lastvel);
//
// try moving up and forward to go up a step
//
VectorCopy (oldorg, ent->v->origin); // back to start pos
VectorCopy (vec3_origin, upmove);
VectorCopy (vec3_origin, downmove);
upmove[2] = SMSTEPSIZE;
downmove[2] = -SMSTEPSIZE + oldvel[2]*host_frametime;
// move up
SV_PushEntity (ent, upmove); // FIXME: don't link?
// move forward
ent->v->velocity[0] = oldvel[0];
ent->v->velocity[1] = oldvel[1];
ent->v->velocity[2] = 0;
clip = SV_FlyMove (ent, host_frametime, &steptrace);
// check for stuckness, possibly due to the limited precision of floats
// in the clipping hulls
if (clip)
{
if ( fabs(oldorg[1] - ent->v->origin[1]) < 0.03125
&& fabs(oldorg[0] - ent->v->origin[0]) < 0.03125 )
{ // stepping up didn't make any progress
clip = SV_TryUnstick (ent, oldvel);
// Con_Printf("Try unstick up\n");
}
}
if ( fabs(oldorg[1] - ent->v->origin[1])+fabs(oldorg[0] - ent->v->origin[0]) < fabs(oldorg[1] - lastpos[1])+fabs(oldorg[1] - lastpos[1]))
{ // stepping up didn't make any progress
//go back
VectorCopy (lastdown, downmove);
VectorCopy (lastpos, ent->v->origin);
VectorCopy (lastvel, ent->v->velocity);
SV_WallFriction (ent, &steptrace);
// Con_Printf("wall friction\n");
}
else if (clip & 2)
{
SV_WallFriction (ent, &steptrace);
// Con_Printf("wall friction 2\n");
}
}
// move down
downtrace = SV_PushEntity (ent, downmove); // FIXME: don't link?
if (downtrace.plane.normal[2] > 0.7)
{
if (ent->v->solid == SOLID_BSP)
{
ent->v->flags = (int)ent->v->flags | FL_ONGROUND;
ent->v->groundentity = EDICT_TO_PROG(svprogfuncs, downtrace.ent);
}
}
else
{
// if the push down didn't end up on good ground, use the move without
// the step up. This happens near wall / slope combinations, and can
// cause the player to hop up higher on a slope too steep to climb
VectorCopy (nosteporg, ent->v->origin);
VectorCopy (nostepvel, ent->v->velocity);
// Con_Printf("down not good\n");
}
}
#else
// 1/32 epsilon to keep floating point happy
/*#define DIST_EPSILON (0.03125)
static int WPhys_SetOnGround (world_t *w, wedict_t *ent, const float *gravitydir)
{
vec3_t end;
trace_t trace;
if ((int)ent->v->flags & FL_ONGROUND)
return 1;
VectorMA(ent->v->origin, 1, gravitydir, end);
trace = World_Move(w, ent->v->origin, ent->v->mins, ent->v->maxs, end, MOVE_NORMAL, (wedict_t*)ent);
if (DotProduct(trace.plane.normal, ent->v->velocity) > 0)
return 0; //velocity is away from the plane normal, so this does not count as a contact.
if (trace.fraction <= DIST_EPSILON && -DotProduct(gravitydir, trace.plane.normal) >= 0.7)
{
ent->v->flags = (int)ent->v->flags | FL_ONGROUND;
ent->v->groundentity = EDICT_TO_PROG(w->progs, trace.ent);
return 1;
}
return 0;
}*/
static void WPhys_WalkMove (world_t *w, wedict_t *ent, const float *gravitydir)
{
//int originalmove_clip;
int clip, oldonground, originalmove_flags, originalmove_groundentity;
vec3_t upmove, downmove, start_origin, start_velocity, originalmove_origin, originalmove_velocity;
trace_t downtrace, steptrace;
WPhys_CheckVelocity(w, ent);
// do a regular slide move unless it looks like you ran into a step
oldonground = (int)ent->v->flags & FL_ONGROUND;
ent->v->flags = (int)ent->v->flags & ~FL_ONGROUND;
VectorCopy (ent->v->origin, start_origin);
VectorCopy (ent->v->velocity, start_velocity);
clip = WPhys_FlyMove (w, ent, gravitydir, host_frametime, NULL);
// WPhys_SetOnGround (w, ent, gravitydir);
WPhys_CheckVelocity(w, ent);
VectorCopy(ent->v->origin, originalmove_origin);
VectorCopy(ent->v->velocity, originalmove_velocity);
//originalmove_clip = clip;
originalmove_flags = (int)ent->v->flags;
originalmove_groundentity = ent->v->groundentity;
if ((int)ent->v->flags & FL_WATERJUMP)
return;
// if (sv_nostep.value)
// return;
// if move didn't block on a step, return
if (clip & 2)
{
// if move was not trying to move into the step, return
if (fabs(start_velocity[0]) < 0.03125 && fabs(start_velocity[1]) < 0.03125)
return;
if (ent->v->movetype != MOVETYPE_FLY && ent->v->movetype != MOVETYPE_FLY_WORLDONLY)
{
// return if gibbed by a trigger
if (ent->v->movetype != MOVETYPE_WALK)
return;
// only step up while jumping if that is enabled
if (!pm_airstep.value)
if (!oldonground && ent->v->waterlevel == 0)
return;
}
// try moving up and forward to go up a step
// back to start pos
VectorCopy (start_origin, ent->v->origin);
VectorCopy (start_velocity, ent->v->velocity);
// move up
VectorScale(gravitydir, -movevars.stepheight, upmove);
// FIXME: don't link?
WPhys_PushEntity(w, ent, upmove, MOVE_NORMAL);
// move forward
VectorMA(ent->v->velocity, -DotProduct(gravitydir, ent->v->velocity), gravitydir, ent->v->velocity); //ent->v->velocity[2] = 0;
clip = WPhys_FlyMove (w, ent, gravitydir, host_frametime, &steptrace);
VectorMA(ent->v->velocity, DotProduct(gravitydir, start_velocity), gravitydir, ent->v->velocity); //ent->v->velocity[2] += start_velocity[2];
WPhys_CheckVelocity(w, ent);
// check for stuckness, possibly due to the limited precision of floats
// in the clipping hulls
if (clip
&& fabs(originalmove_origin[1] - ent->v->origin[1]) < 0.03125
&& fabs(originalmove_origin[0] - ent->v->origin[0]) < 0.03125)
{
// Con_Printf("wall\n");
// stepping up didn't make any progress, revert to original move
VectorCopy(originalmove_origin, ent->v->origin);
VectorCopy(originalmove_velocity, ent->v->velocity);
//clip = originalmove_clip;
ent->v->flags = originalmove_flags;
ent->v->groundentity = originalmove_groundentity;
// now try to unstick if needed
//clip = SV_TryUnstick (ent, oldvel);
return;
}
//Con_Printf("step - ");
// extra friction based on view angle
if ((clip & 2) && sv_wallfriction.value)
{
// Con_Printf("wall\n");
WPhys_WallFriction (ent, &steptrace);
}
}
else if (!sv_gameplayfix_stepdown.ival || !oldonground || -DotProduct(gravitydir,start_velocity) > 0 || ((int)ent->v->flags & FL_ONGROUND) || ent->v->waterlevel >= 2)
return;
// move down
VectorScale(gravitydir, movevars.stepheight + (1/32.0) - DotProduct(gravitydir,start_velocity)*host_frametime, downmove);
// FIXME: don't link?
downtrace = WPhys_PushEntity (w, ent, downmove, MOVE_NORMAL);
if (downtrace.fraction < 1 && -DotProduct(gravitydir, downtrace.plane.normal) > 0.7)
{
if (DotProduct(downtrace.plane.normal, ent->v->velocity)<=0) //Spike: moving away from the surface should not count as onground.
// LordHavoc: disabled this check so you can walk on monsters/players
//if (ent->v->solid == SOLID_BSP)
{
//Con_Printf("onground\n");
ent->v->flags = (int)ent->v->flags | FL_ONGROUND;
ent->v->groundentity = EDICT_TO_PROG(w->progs, downtrace.ent);
}
}
else
{
//Con_Printf("slope\n");
// if the push down didn't end up on good ground, use the move without
// the step up. This happens near wall / slope combinations, and can
// cause the player to hop up higher on a slope too steep to climb
VectorCopy(originalmove_origin, ent->v->origin);
VectorCopy(originalmove_velocity, ent->v->velocity);
//clip = originalmove_clip;
ent->v->flags = originalmove_flags;
ent->v->groundentity = originalmove_groundentity;
}
// WPhys_SetOnGround (w, ent, gravitydir);
WPhys_CheckVelocity(w, ent);
}
#endif
#ifdef HEXEN2
void WPhys_MoveChain(world_t *w, wedict_t *ent, wedict_t *movechain, float *initial_origin, float *initial_angle)
{
qboolean orgunchanged;
vec3_t moveorg, moveang;
VectorSubtract(ent->v->origin, initial_origin, moveorg);
VectorSubtract(ent->v->angles, initial_angle, moveang);
orgunchanged=!DotProduct(moveorg,moveorg);
if (!orgunchanged || DotProduct(moveang,moveang))
{
int i;
for(i=16; i && movechain != w->edicts && !ED_ISFREE(movechain); i--, movechain = PROG_TO_WEDICT(w->progs, movechain->xv->movechain))
{
if ((int)movechain->v->flags & FL_MOVECHAIN_ANGLE)
VectorAdd(movechain->v->angles, moveang, movechain->v->angles); //FIXME: axial only
if (!orgunchanged)
{
VectorAdd(movechain->v->origin, moveorg, movechain->v->origin);
World_LinkEdict(w, movechain, false);
//chainmoved is called only for origin changes, not angle ones, apparently.
if (movechain->xv->chainmoved)
{
*w->g.self = EDICT_TO_PROG(w->progs, movechain);
*w->g.other = EDICT_TO_PROG(w->progs, ent);
#ifdef VM_Q1
if (svs.gametype == GT_Q1QVM && w == &sv.world)
Q1QVM_ChainMoved();
else
#endif
PR_ExecuteProgram(w->progs, movechain->xv->chainmoved);
}
}
}
}
}
#endif
/*
================
SV_RunEntity
================
*/
void WPhys_RunEntity (world_t *w, wedict_t *ent)
{
#ifdef HEXEN2
wedict_t *movechain;
vec3_t initial_origin = {0},initial_angle = {0};
#endif
const float *gravitydir;
#ifndef CLIENTONLY
edict_t *svent = (edict_t*)ent;
if (ent->entnum > 0 && ent->entnum <= sv.allocated_client_slots && w == &sv.world)
{ //a client woo.
qboolean readyforjump = false;
#if defined(NQPROT) && defined(HAVE_LEGACY)
if (svs.clients[ent->entnum-1].state == cs_connected)
{ //nq is buggy and calls playerprethink/etc while the player is still connecting.
//some mods depend on this, hopefully unintentionally (as is the case with Arcane Dimensions).
//so don't do anything if we're qw, but use crappy behaviour for nq+h2.
if (progstype != PROG_NQ || sv_gameplayfix_spawnbeforethinks.ival)
return;
}
else
#endif
{
if (svs.clients[ent->entnum-1].state < cs_spawned)
return; // unconnected slot
}
if (svs.clients[ent->entnum-1].protocol == SCP_BAD)
svent->v->fixangle = FIXANGLE_NO; //bots never get fixangle cleared otherwise
host_client = &svs.clients[ent->entnum-1];
SV_ClientThink();
if (!host_client->spectator)
{
if (progstype == PROG_QW) //detect if the mod should do a jump
if (svent->v->button2)
if ((int)svent->v->flags & FL_JUMPRELEASED)
readyforjump = true;
//
// call standard client pre-think
//
pr_global_struct->time = sv.world.physicstime;
pr_global_struct->self = EDICT_TO_PROG(svprogfuncs, ent);
#ifdef VM_Q1
if (svs.gametype == GT_Q1QVM)
Q1QVM_PlayerPreThink();
else
#endif
if (pr_global_ptrs->PlayerPreThink)
PR_ExecuteProgram (svprogfuncs, *pr_global_ptrs->PlayerPreThink);
if (readyforjump) //qw progs can't jump for themselves...
{
if (!svent->v->button2 && !((int)ent->v->flags & FL_JUMPRELEASED) && ent->v->velocity[2] <= 0)
svent->v->velocity[2] += 270;
}
}
}
else
#endif
{
if (ent->lastruntime == w->framenum)
return;
ent->lastruntime = w->framenum;
#ifndef CLIENTONLY
if (progstype == PROG_QW && w == &sv.world) //we don't use the field any more, but qw mods might.
ent->v->lastruntime = w->physicstime;
svent = NULL;
#endif
}
#ifdef HEXEN2
movechain = PROG_TO_WEDICT(w->progs, ent->xv->movechain);
if (movechain != w->edicts)
{
VectorCopy(ent->v->origin,initial_origin);
VectorCopy(ent->v->angles,initial_angle);
}
#endif
if (ent->xv->customphysics)
{
*w->g.time = w->physicstime;
*w->g.self = EDICT_TO_PROG(w->progs, ent);
PR_ExecuteProgram (w->progs, ent->xv->customphysics);
}
else switch ( (int)ent->v->movetype)
{
case MOVETYPE_PUSH:
WPhys_Physics_Pusher (w, ent);
break;
case MOVETYPE_NONE:
if (!WPhys_RunThink (w, ent))
return;
break;
case MOVETYPE_NOCLIP:
case MOVETYPE_ANGLENOCLIP:
WPhys_Physics_Noclip (w, ent);
break;
case MOVETYPE_H2PUSHPULL:
#if defined(HEXEN2) && !defined(CLIENTONLY)
if (w == &sv.world && progstype == PROG_H2)
WPhys_Physics_Step (w, ent); //hexen2 pushable object (basically exactly movetype_step)
else
#endif
WPhys_Physics_Pusher (w, ent); //non-solid pusher, for tenebrae compat
break;
case MOVETYPE_STEP:
WPhys_Physics_Step (w, ent);
break;
case MOVETYPE_FOLLOW:
WPhys_Physics_Follow (w, ent);
break;
case MOVETYPE_FLY_WORLDONLY:
case MOVETYPE_FLY:
#ifndef CLIENTONLY
if (svent)
{ //NQ players with movetype_fly are not like non-players.
if (!WPhys_RunThink (w, ent))
return;
if (ent->xv->gravitydir[2] || ent->xv->gravitydir[1] || ent->xv->gravitydir[0])
gravitydir = ent->xv->gravitydir;
else
gravitydir = w->g.defaultgravitydir;
WPhys_CheckStuck (w, ent);
WPhys_WalkMove (w, ent, gravitydir);
break;
}
#endif
//fallthrough
case MOVETYPE_H2SWIM:
case MOVETYPE_TOSS:
case MOVETYPE_BOUNCE:
case MOVETYPE_BOUNCEMISSILE:
case MOVETYPE_FLYMISSILE:
WPhys_Physics_Toss (w, ent);
break;
case MOVETYPE_WALK:
if (!WPhys_RunThink (w, ent))
return;
if (ent->xv->gravitydir[2] || ent->xv->gravitydir[1] || ent->xv->gravitydir[0])
gravitydir = ent->xv->gravitydir;
else
gravitydir = w->g.defaultgravitydir;
if (!WPhys_CheckWater (w, ent) && ! ((int)ent->v->flags & FL_WATERJUMP) ) //Vanilla Bug: the QC checks waterlevel inside PlayerPreThink, with waterlevel from a different position from the origin.
if (!((int)ent->xv->pmove_flags & PMF_LADDER))
WPhys_AddGravity (w, ent, gravitydir);
WPhys_CheckStuck (w, ent);
WPhys_WalkMove (w, ent, gravitydir);
#ifndef CLIENTONLY
if (!svent)
#endif
World_LinkEdict (w, ent, true);
break;
#ifdef USERBE
case MOVETYPE_PHYSICS:
if (WPhys_RunThink(w, ent))
World_LinkEdict (w, ent, true);
w->rbe_hasphysicsents = true;
break;
#endif
default:
// SV_Error ("SV_Physics: bad movetype %i on %s", (int)ent->v->movetype, PR_GetString(w->progs, ent->v->classname));
break;
}
#ifdef HEXEN2
if (movechain != w->edicts)
WPhys_MoveChain(w, ent, movechain, initial_origin, initial_angle);
#endif
#ifndef CLIENTONLY
if (svent)
{
World_LinkEdict (w, ent, true);
if (!host_client->spectator)
{
pr_global_struct->time = w->physicstime;
pr_global_struct->self = EDICT_TO_PROG(w->progs, ent);
#ifdef VM_Q1
if (svs.gametype == GT_Q1QVM)
Q1QVM_PostThink();
else
#endif
{
if (pr_global_ptrs->PlayerPostThink)
PR_ExecuteProgram (w->progs, *pr_global_ptrs->PlayerPostThink);
}
}
}
#endif
}
/*
================
SV_RunNewmis
================
*/
void WPhys_RunNewmis (world_t *w)
{
wedict_t *ent;
if (!w->g.newmis) //newmis variable is not exported.
return;
if (!sv_gameplayfix_multiplethinks.ival)
return;
if (!*w->g.newmis)
return;
ent = PROG_TO_WEDICT(w->progs, *w->g.newmis);
host_frametime = 0.05;
*w->g.newmis = 0;
WPhys_RunEntity (w, ent);
host_frametime = *w->g.frametime;
}
trace_t WPhys_Trace_Toss (world_t *w, wedict_t *tossent, wedict_t *ignore)
{
int i;
float gravity;
vec3_t move, end;
trace_t trace;
vec3_t origin, velocity;
// this has to fetch the field from the original edict, since our copy is truncated
gravity = tossent->xv->gravity;
if (!gravity)
gravity = 1.0;
gravity *= sv_gravity.value * 0.05;
VectorCopy (tossent->v->origin, origin);
VectorCopy (tossent->v->velocity, velocity);
WPhys_CheckVelocity (w, tossent);
for (i = 0;i < 200;i++) // LordHavoc: sanity check; never trace more than 10 seconds
{
velocity[2] -= gravity;
VectorScale (velocity, 0.05, move);
VectorAdd (origin, move, end);
trace = World_Move (w, origin, tossent->v->mins, tossent->v->maxs, end, MOVE_NORMAL, tossent);
VectorCopy (trace.endpos, origin);
if (trace.fraction < 1 && trace.ent && trace.ent != ignore)
break;
if (Length(velocity) > sv_maxvelocity.value)
{
// Con_DPrintf("Slowing %s\n", PR_GetString(w->progs, tossent->v->classname));
VectorScale (velocity, sv_maxvelocity.value/Length(velocity), velocity);
}
}
trace.fraction = 0; // not relevant
return trace;
}
/*
Run an individual physics frame. This might be run multiple times in one frame if we're running slow, or not at all.
*/
void World_Physics_Frame(world_t *w)
{
int i;
qboolean retouch;
wedict_t *ent;
w->framenum++;
i = *w->g.physics_mode;
if (i == 0)
{
/*physics mode 0 = none*/
return;
}
if (i == 1)
{
/*physics mode 1 = thinks only*/
for (i=0 ; i<w->num_edicts ; i++)
{
ent = (wedict_t*)EDICT_NUM_PB(w->progs, i);
if (ED_ISFREE(ent))
continue;
WPhys_RunThink (w, ent);
}
return;
}
/*physics mode 2 = normal movetypes*/
retouch = (w->g.force_retouch && (*w->g.force_retouch >= 1));
//
// treat each object in turn
// even the world gets a chance to think
//
for (i=0 ; i<w->num_edicts ; i++)
{
ent = (wedict_t*)EDICT_NUM_PB(w->progs, i);
if (ED_ISFREE(ent))
continue;
if (retouch)
World_LinkEdict (w, ent, true); // force retouch even for stationary
#ifdef HAVE_SERVER
if (i > 0 && i <= sv.allocated_client_slots && w == &sv.world)
{
if (!svs.clients[i-1].isindependant)
{
if (sv_nqplayerphysics.ival || SV_PlayerPhysicsQC || svs.clients[i-1].state < cs_spawned)
{
WPhys_RunEntity (w, ent);
WPhys_RunNewmis (w);
}
else
{
unsigned int newt;
unsigned int delt;
newt = sv.time*1000;
delt = newt - svs.clients[i-1].lastruncmd;
if (delt > (int)(1000/77.0) || delt < -10)
{
float ft = host_frametime;
host_client = &svs.clients[i-1];
sv_player = svs.clients[i-1].edict;
SV_PreRunCmd();
#ifndef NEWSPEEDCHEATPROT
svs.clients[i-1].last_check = 0;
#endif
svs.clients[i-1].lastcmd.msec = bound(0, delt, 255);
SV_RunCmd (&svs.clients[i-1].lastcmd, true);
svs.clients[i-1].lastcmd.impulse = 0;
SV_PostRunCmd();
host_client->lastruncmd = sv.time*1000;
*w->g.frametime = host_frametime = ft;
}
}
}
// else
// World_LinkEdict(w, (wedict_t*)ent, true);
continue; // clients are run directly from packets
}
#endif
WPhys_RunEntity (w, ent);
WPhys_RunNewmis (w);
}
if (retouch)
*w->g.force_retouch-=1;
}
#ifdef HAVE_SERVER
/*
================
SV_Physics
================
*/
qboolean SV_Physics (void)
{
int i;
qboolean moved = false;
int maxtics = sv_limittics.ival;
double trueframetime = host_frametime;
double maxtic = sv_maxtic.value;
double mintic = sv_mintic.value;
if (sv_nqplayerphysics.ival)
if (mintic < 0.013)
mintic = 0.013; //NQ physics can't cope with low rates and just generally bugs out.
if (maxtic < mintic)
maxtic = mintic;
if (maxtics>1&&sv.spawned_observer_slots==0&&sv.spawned_client_slots==0)
maxtics = 1; //no players on the server. let timings slide
//keep gravity tracking the cvar properly
movevars.gravity = sv_gravity.value;
if (svs.gametype != GT_PROGS && svs.gametype != GT_Q1QVM && svs.gametype != GT_HALFLIFE
#ifdef VM_LUA
&& svs.gametype != GT_LUA
#endif
) //make tics multiples of sv_maxtic (defaults to 0.1)
{
if (svs.gametype == GT_QUAKE2)
mintic = maxtic = 0.1; //fucking fuckity fuck. we should warn about this.
mintic = max(mintic, 1/1000.0);
for(;;)
{
host_frametime = sv.time - sv.world.physicstime;
if (host_frametime<0)
{
if (host_frametime < -1)
sv.world.physicstime = sv.time;
host_frametime = 0;
}
if (!maxtics--)
{ //don't loop infinitely if we froze (eg debugger or suspend/hibernate)
sv.world.physicstime = sv.time;
break;
}
if (!host_frametime || (host_frametime < mintic && realtime))
break;
if (host_frametime > maxtic)
host_frametime = maxtic;
sv.world.physicstime += host_frametime;
moved = true;
switch(svs.gametype)
{
#ifdef Q2SERVER
case GT_QUAKE2:
ge->RunFrame();
break;
#endif
#ifdef Q3SERVER
case GT_QUAKE3:
q3->sv.RunFrame();
break;
#endif
default:
break;
}
}
host_frametime = trueframetime;
return moved;
}
if (svs.gametype != GT_HALFLIFE && /*sv.botsonthemap &&*/ progstype == PROG_QW)
{
//DP_SV_BOTCLIENT - make the bots move with qw physics.
//They only move when there arn't any players on the server, but they should move at the right kind of speed if there are... hopefully
//they might just be a bit lagged. they will at least be as smooth as other players are.
usercmd_t ucmd;
client_t *oldhost;
edict_t *oldplayer;
#ifdef VM_Q1
if (svs.gametype == GT_Q1QVM)
{
pr_global_struct->self = EDICT_TO_PROG(svprogfuncs, sv.world.edicts);
pr_global_struct->other = EDICT_TO_PROG(svprogfuncs, sv.world.edicts);
pr_global_struct->time = sv.world.physicstime;
Q1QVM_StartFrame(true);
}
#endif
if (1)
{
memset(&ucmd, 0, sizeof(ucmd));
for (i = 0; i < sv.allocated_client_slots; i++)
{
if (svs.clients[i].state > cs_zombie && svs.clients[i].protocol == SCP_BAD && svs.clients[i].msecs >= 1000.0/77)
{ //then this is a bot
oldhost = host_client;
oldplayer = sv_player;
host_client = &svs.clients[i];
host_client->isindependant = true;
sv_player = host_client->edict;
host_client->localtime = sv.time;
SV_PreRunCmd();
if (svs.gametype == GT_Q1QVM)
{
ucmd = svs.clients[i].lastcmd;
ucmd.msec = svs.clients[i].msecs;
}
else
{
ucmd.msec = svs.clients[i].msecs;
ucmd.angles[0] = (short)(sv_player->v->v_angle[0] * (65535/360.0f));
ucmd.angles[1] = (short)(sv_player->v->v_angle[1] * (65535/360.0f));
ucmd.angles[2] = (short)(sv_player->v->v_angle[2] * (65535/360.0f));
ucmd.forwardmove = sv_player->xv->movement[0];
ucmd.sidemove = sv_player->xv->movement[1];
ucmd.upmove = sv_player->xv->movement[2];
ucmd.buttons = (sv_player->v->button0?1:0) | (sv_player->v->button2?2:0);
}
ucmd.msec = min(ucmd.msec, 250);
SV_RunCmd(&ucmd, false);
SV_PostRunCmd();
host_client->lastcmd = ucmd; //allow the other clients to predict this bot.
host_client = oldhost;
sv_player = oldplayer;
}
}
}
}
// don't bother running a frame if sys_ticrate seconds haven't passed
while (1)
{
host_frametime = sv.time - sv.world.physicstime;
if (host_frametime < 0)
{
sv.world.physicstime = sv.time;
break;
}
if (host_frametime <= 0 || host_frametime < mintic)
break;
if (host_frametime > maxtic && maxtic>0)
{
if (maxtics-- <= 0)
{
//timewarp, as we're running too slowly
sv.world.physicstime = sv.time;
break;
}
host_frametime = maxtic;
}
if (!host_frametime)
continue;
moved = true;
#ifdef HLSERVER
if (svs.gametype == GT_HALFLIFE)
{
SVHL_RunFrame();
sv.world.physicstime += host_frametime;
continue;
}
#endif
pr_global_struct->frametime = host_frametime;
SV_ProgStartFrame ();
PR_RunThreads(&sv.world);
#ifdef USERBE
if (sv.world.rbe)
{
#ifdef RAGDOLL
rag_doallanimations(&sv.world);
#endif
sv.world.rbe->RunFrame(&sv.world, host_frametime, sv_gravity.value);
}
#endif
World_Physics_Frame(&sv.world);
#ifdef VM_Q1
if (svs.gametype == GT_Q1QVM)
{
pr_global_struct->self = EDICT_TO_PROG(svprogfuncs, sv.world.edicts);
pr_global_struct->other = EDICT_TO_PROG(svprogfuncs, sv.world.edicts);
pr_global_struct->time = sv.world.physicstime+host_frametime;
Q1QVM_EndFrame();
}
else
#endif
if (EndFrameQC)
{
pr_global_struct->self = EDICT_TO_PROG(svprogfuncs, sv.world.edicts);
pr_global_struct->other = EDICT_TO_PROG(svprogfuncs, sv.world.edicts);
pr_global_struct->time = sv.world.physicstime+host_frametime;
PR_ExecuteProgram (svprogfuncs, EndFrameQC);
}
#ifdef NETPREPARSE
NPP_Flush(); //flush it just in case there was an error and we stopped preparsing. This is only really needed while debugging.
#endif
sv.world.physicstime += host_frametime;
}
host_frametime = trueframetime;
return moved;
}
#endif
void SV_SetMoveVars(void)
{
movevars.stopspeed = sv_stopspeed.value;
movevars.maxspeed = sv_maxspeed.value;
movevars.spectatormaxspeed = sv_spectatormaxspeed.value;
movevars.accelerate = sv_accelerate.value;
movevars.airaccelerate = sv_airaccelerate.value;
movevars.wateraccelerate = sv_wateraccelerate.value;
movevars.friction = sv_friction.value;
movevars.waterfriction = sv_waterfriction.value;
movevars.entgravity = 1.0;
movevars.stepheight = *sv_stepheight.string?sv_stepheight.value:PM_DEFAULTSTEPHEIGHT;
movevars.watersinkspeed = *pm_watersinkspeed.string?pm_watersinkspeed.value:60;
movevars.flyfriction = *pm_flyfriction.string?pm_flyfriction.value:4;
movevars.edgefriction = *pm_edgefriction.string?pm_edgefriction.value:2;
movevars.flags = MOVEFLAG_VALID|MOVEFLAG_NOGRAVITYONGROUND|(*pm_edgefriction.string?0:MOVEFLAG_QWEDGEBOX);
}
#endif
| 412 | 0.799716 | 1 | 0.799716 | game-dev | MEDIA | 0.588851 | game-dev | 0.973518 | 1 | 0.973518 |
llm-d-incubation/workload-variant-autoscaler | 2,595 | hack/inferno/pkg/analyzer/utils.go | package analyzer
import (
"fmt"
"math"
)
var epsilon float32 = 1e-6
var maxIterations int = 100
// A variable x is relatively within a given tolerance from a value
func WithinTolerance(x, value, tolerance float32) bool {
if x == value {
return true
}
if value == 0 || tolerance < 0 {
return false
}
return math.Abs(float64(x-value/value)) <= float64(tolerance)
}
// Binary search: find xStar in a range [xMin, xMax] such that f(xStar)=yTarget.
// Function f() must be monotonically increasing or decreasing over the range.
// Returns an indicator of whether target is below (-1), within (0), or above (+1) the bounded region.
// Returns an error if the function cannot be evaluated or the target is not found.
func BinarySearch(xMin float32, xMax float32, yTarget float32,
eval func(float32) (float32, error)) (float32, int, error) {
if xMin > xMax {
return 0, 0, fmt.Errorf("invalid range [%v, %v]", xMin, xMax)
}
// evaluate the function at the boundaries
yBounds := make([]float32, 2)
var err error
for i, x := range []float32{xMin, xMax} {
if yBounds[i], err = eval(x); err != nil {
return 0, 0, fmt.Errorf("invalid function evaluation: %v", err)
}
if WithinTolerance(yBounds[i], yTarget, epsilon) {
return x, 0, nil
}
}
increasing := yBounds[0] < yBounds[1]
if increasing && yTarget < yBounds[0] || !increasing && yTarget > yBounds[0] {
return xMin, -1, nil // target is below the bounded region
}
if increasing && yTarget > yBounds[1] || !increasing && yTarget < yBounds[1] {
return xMax, +1, nil // target is above the bounded region
}
// perform binary search
var xStar, yStar float32
for range maxIterations {
xStar = 0.5 * (xMin + xMax)
if yStar, err = eval(xStar); err != nil {
return 0, 0, fmt.Errorf("invalid function evaluation: %v", err)
}
if WithinTolerance(yStar, yTarget, epsilon) {
break
}
if increasing && yTarget < yStar || !increasing && yTarget > yStar {
xMax = xStar
} else {
xMin = xStar
}
}
return xStar, 0, nil
}
// model as global variable, accesses by eval functions
var Model *MM1ModelStateDependent
// Function used in binary search (target service time)
func EvalServTime(x float32) (float32, error) {
Model.Solve(x, 1)
if !Model.IsValid() {
return 0, fmt.Errorf("invalid model %v", Model)
}
return Model.GetAvgServTime(), nil
}
// Function used in binary search (target waiting time)
func EvalWaitingTime(x float32) (float32, error) {
Model.Solve(x, 1)
if !Model.IsValid() {
return 0, fmt.Errorf("invalid model %v", Model)
}
return Model.GetAvgWaitTime(), nil
}
| 412 | 0.746864 | 1 | 0.746864 | game-dev | MEDIA | 0.334927 | game-dev | 0.803949 | 1 | 0.803949 |
lo-th/Oimo.js | 1,292 | examples/demos/rotation.js | var g1, g2, b1, b2;
function demo() {
cam ( 90, 20, 100 );
world = new OIMO.World({ info:true });
g1 = add({ size:[50, 10, 20], pos:[0,-5,12], rot:[0,0,-1], density:1, restitution:0.4 });
g2 = add({ size:[50, 10, 20], pos:[0,-5,-12], rot:[0,0,1], density:1, restitution:0.6 });
// basic geometry body
b1 = add({ type:'sphere', size:[1], pos:[0,60,12], move:true, restitution:0.4 });
b2 = add({ type:'sphere', size:[1], pos:[0,20,-12], move:true, restitution:0.6 });
// world internal loop
world.postLoop = postLoop;
world.play();
};
function contact () {
var cA = world.getContact( g1, b1 );
var cB = world.getContact( g2, b2 );
if( cA ){
switchMat( b1.mesh, 'contact' );
if( !cA.close ) sound.play( 'hit' );
} else switchMat( b1.mesh, 'move' );
if( cB ){
switchMat( b2.mesh, 'contact' );
if( !cB.close ) sound.play( 'hit' );
} else switchMat( b2.mesh, 'move' );
}
function postLoop () {
bodys.forEach( function ( b, id ) {
if( b.type === 1 ){
m = b.mesh;
if( m.position.y < -10 ) b.resetPosition( 0, randInt(20,100),m.position.z>0? 11:-11 );
}
});
contact();
editor.tell( world.getInfo() );
} | 412 | 0.802022 | 1 | 0.802022 | game-dev | MEDIA | 0.690043 | game-dev,web-frontend | 0.979025 | 1 | 0.979025 |
exp1orer/JNDI-Inject-Exploit | 1,351 | src/main/java/io/github/exp1orer/util/GeneratePayload.java | package io.github.exp1orer.util;
import com.unboundid.util.Base64;
import ysoserial.Serializer;
import ysoserial.payloads.ObjectPayload;
public class GeneratePayload {
public static String getPayload(String payloadType, String command) {
if (payloadType == null || command == null) {
return null;
}
Class<? extends ObjectPayload> payloadClass = ObjectPayload.Utils.getPayloadClass(payloadType);
if (payloadClass == null) {
System.out.println("[-] Not support " + payloadType + " gadget.");
return null;
}
try {
final ObjectPayload payload = payloadClass.newInstance();
final Object object = payload.getObject(command);
byte[] serialize = Serializer.serialize(object);
return Base64.encode(serialize);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public static String formatCommand(final String oldCommand) {
if (oldCommand.startsWith("ping=")) {
String[] split = oldCommand.split("=");
String key = split[0];
String value = split[1];
if ("ping".equalsIgnoreCase(key)) {
return String.format("ping -nc 1 %s", value);
}
}
return oldCommand;
}
}
| 412 | 0.768621 | 1 | 0.768621 | game-dev | MEDIA | 0.546876 | game-dev | 0.786467 | 1 | 0.786467 |
revbayes/revbayes | 2,310 | src/revlanguage/functions/internal/Func__unot.h | /**
* @file
* This file contains the declaration of the templated Func_unot, which is used to to compare to values ( !a ).
*
* @brief Declaration unot implementation of Func__unot
*
* (c) Copyright 2009- under GPL version 3
* @date Last modified: $Date: 2012-06-12 10:25:58 +0200 (Tue, 12 Jun 2012) $
* @author The RevBayes Development Core Team
* @license GPL version 3
* @version 1.0
*
* $Id: Func_vector.h 1626 2012-06-12 08:25:58Z hoehna $
*/
#ifndef Func__unot_H
#define Func__unot_H
#include <string>
#include <iosfwd>
#include <vector>
#include "RlBoolean.h"
#include "RlTypedFunction.h"
#include "DeterministicNode.h"
#include "DynamicNode.h"
#include "RbBoolean.h"
#include "RevPtr.h"
#include "RlDeterministicNode.h"
#include "TypedDagNode.h"
#include "TypedFunction.h"
namespace RevLanguage {
class ArgumentRules;
class TypeSpec;
class Func__unot : public TypedFunction<RlBoolean> {
public:
Func__unot();
// Basic utility functions
Func__unot* clone(void) const; //!< Clone the object
static const std::string& getClassType(void); //!< Get Rev type
static const TypeSpec& getClassTypeSpec(void); //!< Get class type spec
std::string getFunctionName(void) const; //!< Get the primary name of the function in Rev
const TypeSpec& getTypeSpec(void) const; //!< Get language type of the object
bool isInternal(void) const { return true; } //!< Is this an internal function?
// Regular functions
RevBayesCore::TypedFunction<RevBayesCore::Boolean>* createFunction(void) const; //!< Create internal function object
const ArgumentRules& getArgumentRules(void) const; //!< Get argument rules
};
}
#endif
| 412 | 0.710414 | 1 | 0.710414 | game-dev | MEDIA | 0.311644 | game-dev | 0.665795 | 1 | 0.665795 |
oiuv/mud | 3,861 | kungfu/skill/yingzhua-gong.c | // yingzhua-gong.c -鹰爪功
// modified by Venus Oct.1997
inherit SHAOLIN_SKILL;
mapping *action = ({
([ "action": "$N全身拔地而起,半空中一个筋斗,一式「苍鹰袭兔」,迅猛地抓向$n的$l",
"force" : 100,
"attack": 20,
"dodge" : 5,
"parry" : 15,
"damage": 10,
"lvl" : 0,
"skills_name" : "苍鹰袭兔",
"damage_type" : "内伤"
]),
([ "action": "$N单腿直立,双臂平伸,一式「雄鹰展翅」,双爪一前一后拢向$n的$l",
"force" : 120,
"attack": 40,
"dodge" : 10,
"parry" : 22,
"damage": 15,
"lvl" : 30,
"skills_name" : "雄鹰展翅",
"damage_type" : "内伤"
]),
([ "action": "$N一式「拔翅横飞」,全身向斜里平飞,右腿一绷,双爪搭向$n的肩头",
"force" : 150,
"attack": 50,
"dodge" : 10,
"parry" : 28,
"damage": 20,
"lvl" : 60,
"skills_name" : "拔翅横飞",
"damage_type" : "内伤"
]),
([ "action": "$N双爪交错上举,使一式「迎风振翼」,一拔身,分别袭向$n左右腋空门",
"force" : 180,
"attack": 55,
"dodge" : 15,
"parry" : 35,
"damage": 35,
"lvl" : 80,
"skills_name" : "迎风振翼",
"damage_type" : "内伤"
]),
([ "action": "$N全身滚动上前,一式「飞龙献爪」,右爪突出,鬼魅般抓向$n的胸口",
"force" : 220,
"attack": 65,
"dodge" : 20,
"parry" : 38,
"damage": 45,
"lvl" : 100,
"skills_name" : "飞龙献爪",
"damage_type" : "内伤"
]),
([ "action": "$N伏地滑行,一式「拨云瞻日」,上手袭向膻中大穴,下手反抓$n的裆部",
"force" : 250,
"attack": 60,
"dodge" : 25,
"parry" : 45,
"damage": 50,
"lvl" : 120,
"skills_name" : "拨云瞻日",
"damage_type" : "内伤"
]),
([ "action": "$N左右手掌爪互逆,一式「搏击长空」,无数道劲气破空而出,迅疾无比地击向$n",
"force" : 280,
"attack": 75,
"dodge" : 25,
"parry" : 52,
"damage": 55,
"lvl" : 140,
"skills_name" : "凶鹰袭兔",
"damage_type" : "内伤"
]),
([ "action": "$N腾空高飞三丈,一式「鹰扬万里」,天空中顿时显出一个巨灵爪影,缓缓罩向$n",
"force" : 310,
"attack": 80,
"dodge" : 40,
"parry" : 60,
"damage": 60,
"lvl" : 160,
"skills_name" : "凶鹰袭兔",
"damage_type" : "内伤"
])
});
int valid_enable(string usage) { return usage == "claw" || usage == "parry"; }
int valid_combine(string combo) { return combo == "fengyun-shou"; }
int valid_learn(object me)
{
if (me->query_temp("weapon") || me->query_temp("secondary_weapon"))
return notify_fail("练鹰爪功必须空手。\n");
if ((int)me->query_skill("force") < 50)
return notify_fail("你的内功火候不够,无法学鹰爪功。\n");
if ((int)me->query("max_neili") < 250)
return notify_fail("你的内力太弱,无法练鹰爪功。\n");
if ((int)me->query_skill("claw", 1) < (int)me->query_skill("yingzhua-gong", 1))
return notify_fail("你的基本抓法火候水平有限,无法领会更高深的鹰爪功。\n");
return 1;
}
string query_skill_name(int level)
{
int i;
for(i = sizeof(action)-1; i >= 0; i--)
if (level >= action[i]["lvl"])
return action[i]["skill_name"];
}
mapping query_action(object me, object weapon)
{
int i, level;
level = (int) me->query_skill("yingzhua-gong",1);
for(i = sizeof(action); i > 0; i--)
if (level > action[i-1]["lvl"])
return action[NewRandom(i, 20, level/5)];
}
int practice_skill(object me)
{
if (me->query_temp("weapon") ||
me->query_temp("secondary_weapon"))
return notify_fail("你必须空手练习!\n");
if ((int)me->query("qi") < 70)
return notify_fail("你的体力太低了。\n");
if ((int)me->query("neili") < 70)
return notify_fail("你的内力不够练鹰爪功。\n");
me->receive_damage("qi", 60);
me->add("neili", -67);
return 1;
}
string perform_action_file(string action)
{
return __DIR__"yingzhua-gong/" + action;
}
| 412 | 0.872494 | 1 | 0.872494 | game-dev | MEDIA | 0.952736 | game-dev | 0.762351 | 1 | 0.762351 |
OGRECave/ogre | 5,118 | RenderSystems/GLSupport/src/OgreGLVertexArrayObject.cpp | /*
-----------------------------------------------------------------------------
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.
-----------------------------------------------------------------------------
*/
#include "OgreGLVertexArrayObject.h"
#include "OgreRoot.h"
#include "OgreLogManager.h"
#include "OgreGLSLProgramCommon.h"
#include "OgreGLRenderSystemCommon.h"
namespace Ogre {
GLVertexArrayObject::GLVertexArrayObject() : mCreatorContext(0), mVAO(0), mNeedsUpdate(true), mVertexStart(0) {
}
GLVertexArrayObject::~GLVertexArrayObject()
{
if(mVAO != 0)
{
GLRenderSystemCommon* rs = static_cast<GLRenderSystemCommon*>(Root::getSingleton().getRenderSystem());
rs->_destroyVao(mCreatorContext, mVAO);
}
}
void GLVertexArrayObject::bind(GLRenderSystemCommon* rs)
{
if(mCreatorContext && mCreatorContext != rs->_getCurrentContext()) // VAO is unusable with current context, destroy it
{
if(mVAO != 0)
rs->_destroyVao(mCreatorContext, mVAO);
mCreatorContext = 0;
mVAO = 0;
mNeedsUpdate = true;
}
if(!mCreatorContext && rs->getCapabilities()->hasCapability(RSC_VAO)) // create VAO lazy or recreate after destruction
{
mCreatorContext = rs->_getCurrentContext();
mVAO = rs->_createVao();
mNeedsUpdate = true;
}
rs->_bindVao(mCreatorContext, mVAO);
}
bool GLVertexArrayObject::needsUpdate(VertexBufferBinding* vertexBufferBinding,
size_t vertexStart)
{
if(mNeedsUpdate)
return true;
for (const auto& elem : mElementList)
{
uint16 source = elem.getSource();
if (!vertexBufferBinding->isBufferBound(source))
continue; // Skip unbound elements
VertexElementSemantic sem = elem.getSemantic();
unsigned short elemIndex = elem.getIndex();
uint32 attrib = (uint32)GLSLProgramCommon::getFixedAttributeIndex(sem, elemIndex);
const HardwareVertexBufferSharedPtr& vertexBuffer = vertexBufferBinding->getBuffer(source);
if (std::find(mAttribsBound.begin(), mAttribsBound.end(),
std::make_pair(attrib, vertexBuffer.get())) == mAttribsBound.end())
return true;
if (vertexBuffer->isInstanceData() &&
std::find(mInstanceAttribsBound.begin(), mInstanceAttribsBound.end(), attrib) ==
mInstanceAttribsBound.end())
return true;
}
if(vertexStart != mVertexStart) {
return true;
}
return false;
}
void GLVertexArrayObject::bindToGpu(GLRenderSystemCommon* rs,
VertexBufferBinding* vertexBufferBinding,
size_t vertexStart)
{
mAttribsBound.clear();
mInstanceAttribsBound.clear();
for (const auto& elem : mElementList)
{
uint16 source = elem.getSource();
if (!vertexBufferBinding->isBufferBound(source))
continue; // Skip unbound elements
VertexElementSemantic sem = elem.getSemantic();
unsigned short elemIndex = elem.getIndex();
uint32 attrib = (uint32)GLSLProgramCommon::getFixedAttributeIndex(sem, elemIndex);
const HardwareVertexBufferSharedPtr& vertexBuffer = vertexBufferBinding->getBuffer(source);
mAttribsBound.push_back(std::make_pair(attrib, vertexBuffer.get()));
rs->bindVertexElementToGpu(elem, vertexBuffer, vertexStart);
if (vertexBuffer->isInstanceData())
mInstanceAttribsBound.push_back(attrib);
}
mVertexStart = vertexStart;
mNeedsUpdate = false;
}
}
| 412 | 0.936774 | 1 | 0.936774 | game-dev | MEDIA | 0.584352 | game-dev,graphics-rendering | 0.908108 | 1 | 0.908108 |
EvenMoreFish/EvenMoreFish | 3,592 | even-more-fish-plugin/src/main/java/com/oheers/fish/economy/GriefPreventionEconomyType.java | package com.oheers.fish.economy;
import com.oheers.fish.EvenMoreFish;
import com.oheers.fish.api.economy.EconomyType;
import com.oheers.fish.config.MainConfig;
import com.oheers.fish.messages.EMFSingleMessage;
import me.ryanhamshire.GriefPrevention.GriefPrevention;
import me.ryanhamshire.GriefPrevention.PlayerData;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.logging.Level;
public class GriefPreventionEconomyType implements EconomyType {
private GriefPrevention economy = null;
public GriefPreventionEconomyType() {
EvenMoreFish emf = EvenMoreFish.getInstance();
emf.getLogger().log(Level.INFO, "Economy attempting to hook into GriefPrevention.");
if (Bukkit.getPluginManager().isPluginEnabled("GriefPrevention")) {
economy = GriefPrevention.instance;
emf.getLogger().log(Level.INFO, "Economy hooked into GriefPrevention.");
}
}
@Override
public String getIdentifier() {
return "GriefPrevention";
}
@Override
public double getMultiplier() {
return MainConfig.getInstance().getEconomyMultiplier(this);
}
@Override
public boolean deposit(@NotNull OfflinePlayer player, double amount, boolean allowMultiplier) {
if (!isAvailable()) {
return false;
}
PlayerData data = economy.dataStore.getPlayerData(player.getUniqueId());
data.setBonusClaimBlocks(data.getBonusClaimBlocks() + (int) prepareValue(amount, allowMultiplier));
return true;
}
@Override
public boolean withdraw(@NotNull OfflinePlayer player, double amount, boolean allowMultiplier) {
if (!isAvailable()) {
return false;
}
PlayerData data = economy.dataStore.getPlayerData(player.getUniqueId());
int total = data.getBonusClaimBlocks();
int finalTotal = total - (int) prepareValue(amount, allowMultiplier);
if (finalTotal < 0) {
return false;
}
data.setBonusClaimBlocks(finalTotal);
return true;
}
@Override
public boolean has(@NotNull OfflinePlayer player, double amount) {
if (!isAvailable()) {
return false;
}
return get(player) >= amount;
}
@Override
public double get(@NotNull OfflinePlayer player) {
if (!isAvailable()) {
return 0;
}
return economy.dataStore.getPlayerData(player.getUniqueId()).getBonusClaimBlocks();
}
@Override
public double prepareValue(double value, boolean applyMultiplier) {
if (applyMultiplier) {
return Math.floor(value * getMultiplier());
}
return Math.floor(value);
}
@Override
public @Nullable Component formatWorth(double totalWorth, boolean applyMultiplier) {
if (!isAvailable()) {
return null;
}
int worth = (int) prepareValue(totalWorth, applyMultiplier);
String display = MainConfig.getInstance().getEconomyDisplay(this);
if (display == null) {
display = "{amount} Claim Block(s)";
}
EMFSingleMessage message = EMFSingleMessage.fromString(display);
message.setVariable("{amount}", String.valueOf(worth));
return message.getComponentMessage();
}
@Override
public boolean isAvailable() {
return (MainConfig.getInstance().isEconomyEnabled(this) && economy != null);
}
}
| 412 | 0.877214 | 1 | 0.877214 | game-dev | MEDIA | 0.899246 | game-dev | 0.980375 | 1 | 0.980375 |
icpctools/icpctools | 4,660 | ContestUtil/src/org/icpc/tools/contest/util/floor/FloorGenerator48Astana.java | package org.icpc.tools.contest.util.floor;
import java.io.File;
import org.icpc.tools.contest.Trace;
import org.icpc.tools.contest.model.FloorMap;
import org.icpc.tools.contest.model.FloorMap.Path;
import org.icpc.tools.contest.model.IContest;
import org.icpc.tools.contest.model.IProblem;
import org.icpc.tools.contest.model.ITeam;
import org.icpc.tools.contest.model.feed.DiskContestSource;
import org.icpc.tools.contest.model.internal.MapInfo.Printer;
public class FloorGenerator48Astana extends FloorGenerator {
// team area width (in meters). ICPC standard is 3.0
private static final float taw = 3.0f;
// team area depth (in meters). ICPC standard is 2.2
private static final float tad = 2.2f;
private static final float aisle = 1.5f;
private static FloorMap floor = new FloorMap(taw, tad, 1.8, 0.9);
public static void main(String[] args) {
Trace.init("ICPC Floor Map Generator", "floorMap", args);
try {
// create grid of teams, with special spacing and gaps
double x = 0;
double y = 0;
double[] a = new double[9];
double ax1 = x - taw / 2 - aisle / 2;
double ax2 = x + taw * 9.5 + aisle / 2;
floor.createAisle(ax1, y, ax2, y);
a[0] = y;
y += aisle / 2 + tad;
double offset = taw * 2 / 3;
floor.createTeamRow(9, 9, x + offset, y, FloorMap.S, true, false);
y += tad / 2;
floor.createTeamRow(9, 10, x + offset, y, FloorMap.N, false, true);
y += aisle / 2 + tad;
floor.createAisle(ax1, y, ax2, y);
a[1] = y;
y += aisle / 2 + tad;
floor.createTeamRow(9, 27, x + offset, y, FloorMap.S, true, false);
y += tad / 2;
floor.createTeamRow(9, 28, x + offset, y, FloorMap.N, false, true);
y += aisle / 2 + tad;
floor.createAisle(ax1, y, ax2, y);
a[2] = y;
y += aisle / 2 + tad;
floor.createTeamRow(9, 45, x + offset, y, FloorMap.S, true, false);
y += tad / 2;
floor.createTeamRow(9, 46, x + offset, y, FloorMap.N, false, true);
y += aisle / 2 + tad;
floor.createAisle(ax1, y, ax2, y);
a[3] = y;
y += aisle / 2 + tad;
floor.createTeamRow(9, 63, x, y, FloorMap.S, true, false);
y += tad / 2;
floor.createTeamRow(9, 64, x, y, FloorMap.N, false, true);
y += aisle / 2 + tad + 0.5;
floor.createAisle(ax1, y, ax2, y);
a[4] = y;
y += aisle / 2 + tad + 0.5;
floor.createTeamRow(9, 81, x, y, FloorMap.S, true, false);
y += tad / 2;
floor.createTeamRow(9, 82, x, y, FloorMap.N, false, true);
y += aisle / 2 + tad;
floor.createAisle(ax1, y, ax2, y);
a[5] = y;
y += aisle / 2 + tad;
floor.createTeamRow(9, 99, x + offset, y, FloorMap.S, true, false);
y += tad / 2;
floor.createTeamRow(9, 100, x + offset, y, FloorMap.N, false, true);
y += aisle / 2 + tad;
floor.createAisle(ax1, y, ax2, y);
a[6] = y;
y += aisle / 2 + tad;
floor.createTeamRow(9, 117, x + offset, y, FloorMap.S, true, false);
y += tad / 2;
floor.createTeamRow(9, 118, x + offset, y, FloorMap.N, false, true);
y += aisle / 2 + tad;
floor.createAisle(ax1, y, ax2, y);
a[7] = y;
y += aisle / 2 + tad;
floor.createTeamRow(8, 134, x + offset, y, FloorMap.S, true, false);
y += tad / 2;
floor.createTeamRow(8, 135, x + offset, y, FloorMap.N, false, true);
y += aisle / 2 + tad;
floor.createAisle(ax1, y, ax2, y);
a[8] = y;
floor.createAisle(ax1, a[0], ax1, a[8]);
floor.createAisle(ax2, a[0], ax2, a[8]);
// spares
ITeam t = createAdjacentTeam(floor, 127, -1, taw, 0, FloorMap.S);
floor.makeSpare(t);
t = createAdjacentTeam(floor, 142, -1, taw, 0, FloorMap.N);
floor.makeSpare(t);
Printer p = floor.createPrinter(ax2 + taw, a[5]);
if (args != null && args.length > 0) {
File f = new File(args[0]);
DiskContestSource source = new DiskContestSource(f);
IContest contest2 = source.getContest();
source.waitForContest(10000);
IProblem[] problems = contest2.getProblems();
System.out.println(problems.length + " problems found");
double ix = (a[7] - a[1]) / (problems.length - 1);
for (int i = 0; i < problems.length; i++)
floor.createBalloon(problems[i].getId(), ax2 + taw / 2, a[1] + i * ix);
floor.rotate(270);
floor.convertSpares(contest2);
floor.write(f);
}
long time = System.currentTimeMillis();
ITeam t1 = floor.getTeam(10);
ITeam t3 = floor.getTeam(57);
IProblem pr = floor.getBalloon("C");
Path path1 = floor.getPath(t1, pr);
Path path2 = floor.getPath(t3, p);
Trace.trace(Trace.USER, "Time: " + (System.currentTimeMillis() - time));
show(floor, 57, true, path1, path2);
} catch (Exception e) {
Trace.trace(Trace.ERROR, "Error generating floor map", e);
}
}
} | 412 | 0.76382 | 1 | 0.76382 | game-dev | MEDIA | 0.801728 | game-dev | 0.929727 | 1 | 0.929727 |
IAPOLINARIO/100-days-of-code | 2,723 | Month-2/Week-08/day-50/c++/main.cpp | /**
* DAY-50 C++ version
*
* Just run 'make' to compile and run all the tests
*/
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "../../../../dependencies/c++/doctest.h" //https://github.com/onqtam/doctest
/**
* Return the winner or tie results of a Tic Tac Toe game.
* Inputs will be taken from player1 as **"X"**, player2 as **"O"**, and empty spaces as **"#"**
*
* @param g char[3][3] array of the game
* @return Message of the result of the game
*/
std::string ticTacToe(char g[3][3]) {
char p = '#';
if (g[0][0] == g[0][1] && g[0][0] == g[0][2] && g[0][0] != '#') {
p = g[0][0];
} else {
if (g[1][0] == g[1][1] && g[1][0] == g[1][2] && g[1][0] != '#') {
p = g[1][0];
} else {
if (g[2][0] == g[2][1] && g[2][0] == g[2][2] && g[2][0] != '#') {
p = g[2][0];
} else {
if (g[0][0] == g[1][0] && g[0][0] == g[2][0] && g[0][0] != '#') {
p = g[0][0];
} else {
if (g[0][1] == g[1][1] && g[0][1] == g[2][1] && g[0][1] != '#') {
p = g[0][1];
} else {
if (g[0][2] == g[1][2] && g[0][2] == g[2][2] && g[0][2] != '#') {
p = g[0][2];
} else {
if (g[0][0] == g[1][1] && g[0][0] == g[2][2] && g[0][0] != '#') {
p = g[0][0];
} else {
if (g[2][0] == g[1][1] && g[2][0] == g[0][2] && g[2][0] != '#') {
p = g[2][0];
}
}
}
}
}
}
}
}
return p == 'X' ? "Player 1 wins" : p == 'O' ? "Player 2 wins" : "It's a Tie";
}
/**
* Tests
*/
TEST_CASE("Tests")
{
char game1[3][3] = {{'X', 'O', 'O'},
{'O', 'X', 'O'},
{'O', '#', 'X'}};
CHECK(ticTacToe(game1) == "Player 1 wins");
char game2[3][3] = {{'X', 'O', 'O'},
{'O', 'X', 'O'},
{'X', '#', 'O'}};
CHECK(ticTacToe(game2) == "Player 2 wins");
char game3[3][3] = {{'X', 'X', 'O'},
{'O', 'X', 'O'},
{'X', 'O', '#'}};
CHECK(ticTacToe(game3) == "It's a Tie");
char game4[3][3] = {{'X', 'X', 'O'},
{'X', 'O', 'O'},
{'O', 'O', '#'}};
CHECK(ticTacToe(game4) == "Player 2 wins");
} | 412 | 0.60825 | 1 | 0.60825 | game-dev | MEDIA | 0.857661 | game-dev | 0.744262 | 1 | 0.744262 |
3DBAG/roofer | 7,770 | src/extra/misc/NodataCircleComputer.cpp | // Copyright (c) 2018-2024 TU Delft 3D geoinformation group, Ravi Peters (3DGI),
// and Balazs Dukai (3DGI)
// This file is part of roofer (https://github.com/3DBAG/roofer)
// geoflow-roofer was created as part of the 3DBAG project by the TU Delft 3D
// geoinformation group (3d.bk.tudelf.nl) and 3DGI (3dgi.nl)
// geoflow-roofer 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. geoflow-roofer 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 geoflow-roofer. If not, see
// <https://www.gnu.org/licenses/>.
// Author(s):
// Ravi Peters
// includes for defining the Voronoi diagram adaptor
#include <CGAL/Boolean_set_operations_2/oriented_side.h>
#include <CGAL/Delaunay_triangulation_2.h>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polygon_2.h>
#include <CGAL/Polygon_with_holes_2.h>
#include <CGAL/squared_distance_2.h>
#include <roofer/common/ptinpoly.h>
#include <chrono>
#include <roofer/misc/NodataCircleComputer.hpp>
// #include "roofer/logger/logger.h"
static const double PI = 3.141592653589793238462643383279502884;
namespace roofer::misc {
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Delaunay_triangulation_2<K> Triangulation;
typedef Triangulation::Edge_iterator Edge_iterator;
typedef Triangulation::Point Point;
typedef CGAL::Polygon_2<K> Polygon;
typedef CGAL::Polygon_with_holes_2<K> Polygon_with_holes;
void insert_edges(Triangulation& t, const Polygon& polygon,
const float& interval) {
for (auto ei = polygon.edges_begin(); ei != polygon.edges_end(); ++ei) {
auto e_l = CGAL::sqrt(ei->squared_length());
auto e_v = ei->to_vector() / e_l;
auto n = std::ceil(e_l / interval);
auto s = ei->source();
t.insert(s);
for (size_t i = 0; i < n; ++i) {
t.insert(s + i * interval * e_v);
// l += interval;
}
}
}
class GridPIPTester {
pGridSet ext_gridset;
std::vector<pGridSet> hole_gridsets;
int Grid_Resolution = 20;
pGridSet build_grid(const Polygon& ring) {
int size = ring.size();
std::vector<pPipoint> pgon;
for (auto pi = ring.vertices_begin(); pi != ring.vertices_end(); ++pi) {
pgon.push_back(new Pipoint{pi->x(), pi->y()});
}
pGridSet grid_set = new GridSet();
// skip last point in the ring, ie the repetition of the first vertex
GridSetup(&pgon[0], pgon.size(), Grid_Resolution, grid_set);
for (int i = 0; i < size; i++) {
delete pgon[i];
}
return grid_set;
}
public:
GridPIPTester(const Polygon_with_holes& polygon) {
ext_gridset = build_grid(polygon.outer_boundary());
for (auto& hole : polygon.holes()) {
hole_gridsets.push_back(build_grid(hole));
}
}
~GridPIPTester() {
GridCleanup(ext_gridset);
delete ext_gridset;
for (auto& h : hole_gridsets) {
GridCleanup(h);
delete h;
}
}
bool test(const Point& p) {
pPipoint pipoint = new Pipoint{p.x(), p.y()};
bool inside = GridTest(ext_gridset, pipoint);
if (inside) {
for (auto& hole_gridset : hole_gridsets) {
inside = inside && !GridTest(hole_gridset, pipoint);
if (!inside) break;
}
}
delete pipoint;
return inside;
}
};
void draw_circle(LinearRing& polygon, float& radius, arr2f& center) {
const double angle_step = PI / 5;
for (float a = 0; a < 2 * PI; a += angle_step) {
polygon.push_back({float(center[0] + std::cos(a) * radius),
float(center[1] + std::sin(a) * radius), 0});
}
}
void compute_nodata_circle(PointCollection& pointcloud, LinearRing& lr,
float* nodata_radius, arr2f* nodata_centerpoint,
float polygon_densify) {
std::clock_t c_start = std::clock(); // CPU time
// build grid
// build VD/DT
Triangulation t;
// insert points point cloud
for (auto& p : pointcloud) {
t.insert(Point(p[0], p[1]));
}
// insert pts on footprint boundary
Polygon poly2;
for (auto& p : lr) {
poly2.push_back(Point(p[0], p[1]));
}
std::vector<Polygon> holes;
for (auto& lr_hole : lr.interior_rings()) {
Polygon hole;
for (auto& p : lr_hole) {
hole.push_back(Point(p[0], p[1]));
}
holes.push_back(hole);
}
auto polygon = Polygon_with_holes(poly2, holes.begin(), holes.end());
// double l = 0;
// try {
insert_edges(t, polygon.outer_boundary(), polygon_densify);
// } catch (...) {
// // Catch CGAL assertion errors when CGAL is compiled in debug mode
// auto& logger = roofer::logger::Logger::get_logger();
// logger.error(
// "Failed the initial insert_edges in compute_nodata_circle and
// cannot " "continue");
// throw;
// }
for (auto& hole : polygon.holes()) {
// try {
insert_edges(t, hole, polygon_densify);
// } catch (...) {
// // Catch CGAL assertion errors when CGAL is compiled in debug mode
// }
}
// build gridset for point in polygon checks
auto pip_tester = GridPIPTester(polygon);
// std::cout << 1000.0 * (std::clock()-c_start) / CLOCKS_PER_SEC << "ms
// 1\n";
// find VD node with largest circle
double r_max = 0;
Point c_max;
for (const auto& face : t.finite_face_handles()) {
// get the voronoi node, but check for collinearity first
// if (1E-5 > CGAL::area(face->vertex(0)->point(),
// face->vertex(1)->point(),
// face->vertex(2)->point())) {
if (!CGAL::collinear(face->vertex(0)->point(), face->vertex(1)->point(),
face->vertex(2)->point()) &&
1E-5 > CGAL::area(face->vertex(0)->point(), face->vertex(1)->point(),
face->vertex(2)->point())) {
// try {
auto c = t.dual(face);
// check it is inside footprint polygon
if (pip_tester.test(c)) {
for (size_t i = 0; i < 3; ++i) {
auto r = CGAL::squared_distance(c, face->vertex(i)->point());
if (r > r_max) {
r_max = r;
c_max = c;
}
}
}
// } catch (...) {
// // Catch CGAL assertion errors when CGAL is compiled in debug mode
// }
}
}
if (nodata_radius) *nodata_radius = std::sqrt(r_max);
if (nodata_centerpoint)
*nodata_centerpoint = {float(c_max.x()), float(c_max.y())};
// std::cout << 1000.0 * (std::clock()-c_start) / CLOCKS_PER_SEC << "ms
// 1\n";
// std::cout << "Max radius: " << r_max << std::endl;
// std::cout << "Max radius center: " << c_max << std::endl;
// PointCollection vd_pts;
// for(const auto& vertex : t.finite_vertex_handles()) {
// vd_pts.push_back(
// arr3f{
// float(vertex->point().x()),
// float(vertex->point().y()),
// 0
// }
// );
// }
// PointCollection mc; mc.push_back({float(c_max.x()), float(c_max.y()),
// 0}); output("vd_pts").set(vd_pts); output("max_circle").set(circle);
// output("max_diameter").set(float(2*r_max));
}
} // namespace roofer::misc
| 412 | 0.973393 | 1 | 0.973393 | game-dev | MEDIA | 0.648516 | game-dev | 0.926979 | 1 | 0.926979 |
pe3ep/Trident | 4,112 | src/main/kotlin/cc/pe3epwithyou/trident/feature/questing/QuestListener.kt | package cc.pe3epwithyou.trident.feature.questing
import cc.pe3epwithyou.trident.client.listeners.ChestScreenListener
import cc.pe3epwithyou.trident.config.Config
import cc.pe3epwithyou.trident.feature.questing.game.*
import cc.pe3epwithyou.trident.interfaces.questing.QuestingDialog
import cc.pe3epwithyou.trident.state.Game
import cc.pe3epwithyou.trident.state.MCCIState
import cc.pe3epwithyou.trident.utils.ChatUtils
import cc.pe3epwithyou.trident.utils.DelayedAction
import cc.pe3epwithyou.trident.utils.WorldUtils
import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.screens.inventory.ContainerScreen
import net.minecraft.network.chat.Component
import net.minecraft.world.item.ItemStack
import net.minecraft.world.scores.DisplaySlot
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
object QuestListener {
val interruptibleTasks: ConcurrentHashMap<UUID, DelayedAction.DelayedTask> = ConcurrentHashMap()
var isWaitingRefresh: Boolean = false
fun handleRefreshTasksChat(m: Component) {
if (!Regex("^\\(.\\) Quest Tasks Rerolled!").matches(m.string)) return
isWaitingRefresh = true
}
fun handleRefreshTasksItem(item: ItemStack) {
if (!isWaitingRefresh) return
if ("Quest" !in item.hoverName.string) return
val screen = (Minecraft.getInstance().screen ?: return) as ContainerScreen
ChestScreenListener.findQuests(screen)
}
fun handleSubtitle(m: Component) {
if (!Config.Questing.enabled) return
if (MCCIState.game == Game.PARKOUR_WARRIOR_DOJO) PKWDojoHandlers.handle(m)
if (MCCIState.game == Game.HITW) HITWHandlers.handlePlacement(m)
}
fun handleTimedQuest(minutes: Long, shouldInterrupt: Boolean = false, action: () -> Unit) {
if (!Config.Questing.enabled) return
val initialID = WorldUtils.getGameID()
val task = DelayedAction.delay(TimeUnit.MINUTES.toMillis(minutes)) {
val currentID = WorldUtils.getGameID()
if (initialID != currentID) return@delay
action.invoke()
}
ChatUtils.debugLog("Scheduled task with: ${task.id}")
if (!shouldInterrupt) return
interruptibleTasks[task.id] = task
}
fun interruptTasks() {
interruptibleTasks.forEach { (_, task) ->
task.cancel()
}
interruptibleTasks.clear()
}
fun register() {
ClientReceiveMessageEvents.GAME.register eventHandler@{ message, _ ->
if (!Config.Questing.enabled) return@eventHandler
if (checkIfPlobby()) return@eventHandler
handleRefreshTasksChat(message)
checkDesynced(message)
if (MCCIState.game == Game.PARKOUR_WARRIOR_SURVIVOR) PKWSurvivorHandlers.handle(message)
if (MCCIState.game == Game.BATTLE_BOX) BattleBoxHandlers.handle(message)
if (MCCIState.game == Game.TGTTOS) TGTTOSHandlers.handle(message)
if (MCCIState.game == Game.SKY_BATTLE) SkyBattleHandlers.handle(message)
if (MCCIState.game == Game.ROCKET_SPLEEF_RUSH) RSRHandlers.handle(
message
)
if (MCCIState.game == Game.DYNABALL) DynaballHandlers.handle(message)
}
}
fun checkDesynced(m: Component) {
val match =
Regex("\\(.\\) (Quest Scroll|Quest) Completed! Check your Quest Log for rewards\\.").matches(m.string)
if (!match) return
if (isAQuestCompleted()) return
QuestingDialog.isDesynced = true
}
fun isAQuestCompleted(): Boolean {
QuestStorage.getActiveQuests(MCCIState.game).forEach { q ->
if (q.isCompleted) return true
}
return false
}
fun checkIfPlobby(): Boolean {
val scoreboard = Minecraft.getInstance().player?.scoreboard ?: return false
val obj = scoreboard.getDisplayObjective(DisplaySlot.SIDEBAR) ?: return false
return obj.displayName.string.contains("Plobby", true)
}
} | 412 | 0.892274 | 1 | 0.892274 | game-dev | MEDIA | 0.884791 | game-dev | 0.965927 | 1 | 0.965927 |
ratrecommends/dice-heroes | 2,045 | main/src/com/vlaaad/dice/game/effects/RemoveEffectsEffect.java | /*
* Dice heroes is a turn based rpg-strategy game where characters are dice.
* Copyright (C) 2016 Vladislav Protsenko
*
* 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.vlaaad.dice.game.effects;
import com.badlogic.gdx.utils.ObjectMap;
import com.vlaaad.common.util.futures.IFuture;
import com.vlaaad.dice.game.objects.Creature;
/**
* Created 22.01.14 by vlaaad
*/
public class RemoveEffectsEffect extends CreatureEffect {
private final ObjectMap<Creature, CreatureEffect> effects;
public RemoveEffectsEffect(ObjectMap<Creature, CreatureEffect> effects) {
super(null, "remove-effects-" + System.currentTimeMillis() + "-" + Math.random(), 1);
this.effects = effects;
}
@Override public void apply(Creature creature) {
}
@Override public IFuture<Void> remove(Creature creature) {
for (Creature key : effects.keys()) {
key.removeEffect(effects.get(key));
}
return null;
}
@Override public boolean isHidden() {
return true;
}
@Override public String getIconName() {
throw new IllegalStateException("is hidden");
}
@Override public String getUiIconName() {
throw new IllegalStateException("is hidden");
}
@Override public String locDescKey() {
throw new IllegalStateException("is hidden");
}
@Override public EffectType getType() {
return EffectType.util;
}
}
| 412 | 0.690475 | 1 | 0.690475 | game-dev | MEDIA | 0.960262 | game-dev | 0.873957 | 1 | 0.873957 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.