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
microsoft/MixedReality-WorldLockingTools-Unity
1,485
Assets/MRTK/SDK/Experimental/ServiceManagers/Teleport/Scripts/TeleportSystemManager.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Teleport; using Microsoft.MixedReality.Toolkit.Utilities; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Experimental.Teleport { /// <summary> /// Service manager supporting running the teleport system, without requiring the MixedRealityToolkit object. /// </summary> [AddComponentMenu("Scripts/MRTK/SDK/TeleportSystemManager")] public class TeleportSystemManager : BaseServiceManager { [SerializeField] [Tooltip("The teleport system type that will be instantiated.")] [Implements(typeof(IMixedRealityTeleportSystem), TypeGrouping.ByNamespaceFlat)] private SystemType TeleportSystemType = null; private void Awake() { InitializeManager(); } protected override void OnDestroy() { UninitializeManager(); base.OnDestroy(); } /// <summary> /// Initialize the manager. /// </summary> private void InitializeManager() { // The teleport system class takes no arguments. Initialize<IMixedRealityTeleportSystem>(TeleportSystemType.Type); } /// <summary> /// Uninitialize the manager. /// </summary> private void UninitializeManager() { Uninitialize<IMixedRealityTeleportSystem>(); } } }
412
0.811224
1
0.811224
game-dev
MEDIA
0.785722
game-dev
0.776254
1
0.776254
OversizedSunCoreDev/ArtilleryEco
11,401
Artillery/Source/ArtilleryRuntime/Public/EssentialTypes/UArtilleryAbilityMinimum.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include <unordered_map> #include "GameplayEffectTypes.h" #include "Abilities/GameplayAbility.h" #include "GameplayAbilitySpecHandle.h" #include "Abilities/GameplayAbilityTypes.h" #include "GameplayEffect.h" #include "FGunKey.h" #include "GameplayTaskOwnerInterface.h" #include "GameplayTask.h" #include "UArtilleryAbilityMinimum.generated.h" /** * The phases of an Artillery ability are * * [Try: fail, start] * Prefire * Prefire Cosmetic * * [Activate] * Fire * Fire Cosmetic * * [Outro] * PostFire * PostFire Cosmetic * * * Either Commit OR end may be called. EACH of these is an instance, per actor, of UArtilleryPerActorAbilityMinimum. * This is somewhat unusual but allows us vast flexibility in how we lay out abilities. * * You'll note there's also a gun key here. While these are instanced abilities, the creation and storage of non-attribute * state is strictly prohibited. Doing so may break abruptly, and without explanation, in a myriad of ways. It's not supported. * * This means that we'll need to be thoughtful about how we use gameplay tags, so we may need to relax this rule. * Rollbacks with gameplay tags and longterm maintenance are both pretty nightmarish, though, so I'd need a solid arg. * * Otoh, looman likes them, and that's often a good sign. Technically, we could create a delta-tracking tag container. * It's not the worst idea. * * Like in the UGameplayAbility class it derives from... * // ---------------------------------------------------------------------------------------------------------------- // // The important functions: // // CanActivateAbility() - const function to see if ability is activatable. Callable by UI etc // // TryActivateAbility() - Attempts to activate the ability. Calls CanActivateAbility(). Input events can call this directly. // - Also handles instancing-per-execution logic and replication/prediction calls. // // CallActivateAbility() - Protected, non virtual function. Does some boilerplate 'pre activate' stuff, then calls ActivateAbility() // // ActivateAbility() - What the abilities *does*. This is what child classes want to override. // // CommitAbility() - Commits reources/cooldowns etc. ActivateAbility() must call this! // // CancelAbility() - Interrupts the ability (from an outside source). // // EndAbility() - The ability has ended. This is intended to be called by the ability to end itself. // // ---------------------------------------------------------------------------------------------------------------- The K2 functions are wrappers that expose native behavior to the BP graph, and serve a few other functions. Check out https://medium.com/trunk-of-code/how-to-easily-change-default-events-to-fit-your-needs-38e87cec16f0 */ enum FArtilleryStates { Fired, Canceled, CanceledAfterCommit }; DECLARE_DELEGATE_FourParams(FArtilleryAbilityStateAlert, FArtilleryStates, int, const FGameplayAbilityActorInfo*, const FGameplayAbilityActivationInfo); UCLASS(BlueprintType) class ARTILLERYRUNTIME_API UArtilleryPerActorAbilityMinimum : public UGameplayAbility { GENERATED_BODY() friend struct FArtilleryGun; public: //As you can see, they all call through to commit ability. FArtilleryAbilityStateAlert GunBinder; //ALMOST EVERYTHING THAT IS INTERESTING HAPPENS HERE RIGHT NOW. //ONLY ATTRIBUTES ARE REPLICATED. _AGAIN_. ONLY ATTRIBUTES ARE REPLICATED. UArtilleryPerActorAbilityMinimum(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer), MyGunKey() { NetExecutionPolicy = EGameplayAbilityNetExecutionPolicy::LocalOnly; ReplicationPolicy = EGameplayAbilityReplicationPolicy::ReplicateNo; InstancingPolicy = EGameplayAbilityInstancingPolicy::InstancedPerActor; }; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Latency Hiding") int AvailableDallyFrames = 0; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Gun") FGunKey MyGunKey; /* // Add the Ability's tags to the given GameplayEffectSpec. This is likely to be overridden per project. virtual void ApplyAbilityTagsToGameplayEffectSpec(FGameplayEffectSpec& Spec, FGameplayAbilitySpec* AbilitySpec) const; //this will likelybe where we set up how all artillery abilities behave regarding this. */ /*/* The following should likely be overridden differently for cosmetic and non-cosmetic ability base-classes. //Invoke a gameplay cue on the ability owner UFUNCTION(BlueprintCallable, Category = Ability, meta = (GameplayTagFilter = "GameplayCue"), DisplayName = "Execute GameplayCue On Owner", meta = (ScriptName = "ExecuteGameplayCue")) virtual void K2_ExecuteGameplayCue(FGameplayTag GameplayCueTag, FGameplayEffectContextHandle Context); //Invoke a gameplay cue on the ability owner, with extra parameters UFUNCTION(BlueprintCallable, Category = Ability, meta = (GameplayTagFilter = "GameplayCue"), DisplayName = "Execute GameplayCueWithParams On Owner", meta = (ScriptName = "ExecuteGameplayCueWithParams")) virtual void K2_ExecuteGameplayCueWithParams(FGameplayTag GameplayCueTag, const FGameplayCueParameters& GameplayCueParameters); //Adds a persistent gameplay cue to the ability owner. Optionally will remove if ability ends UFUNCTION(BlueprintCallable, Category = Ability, meta = (GameplayTagFilter = "GameplayCue"), DisplayName = "Add GameplayCue To Owner", meta = (ScriptName = "AddGameplayCue")) virtual void K2_AddGameplayCue(FGameplayTag GameplayCueTag, FGameplayEffectContextHandle Context, bool bRemoveOnAbilityEnd = true); // Adds a persistent gameplay cue to the ability owner. Optionally will remove if ability ends UFUNCTION(BlueprintCallable, Category = Ability, meta = (GameplayTagFilter = "GameplayCue"), DisplayName = "Add GameplayCueWithParams To Owner", meta = (ScriptName = "AddGameplayCueWithParams")) virtual void K2_AddGameplayCueWithParams(FGameplayTag GameplayCueTag, const FGameplayCueParameters& GameplayCueParameter, bool bRemoveOnAbilityEnd = true); // Removes a persistent gameplay cue from the ability owner UFUNCTION(BlueprintCallable, Category = Ability, meta = (GameplayTagFilter = "GameplayCue"), DisplayName = "Remove GameplayCue From Owner", meta = (ScriptName = "RemoveGameplayCue")) virtual void K2_RemoveGameplayCue(FGameplayTag GameplayCueTag); */ //here are a few others we'll likely NEED to override. ///** Returns the time in seconds remaining on the currently active cooldown. */ //UFUNCTION(BlueprintCallable, Category = Ability) //float GetCooldownTimeRemaining() const; //virtual float GetCooldownTimeRemaining(const FGameplayAbilityActorInfo* ActorInfo) const; //virtual const FGameplayTagContainer* GetCooldownTags() const; //virtual bool DoesAbilitySatisfyTagRequirements(const UAbilitySystemComponent& AbilitySystemComponent, const FGameplayTagContainer* SourceTags = nullptr, const FGameplayTagContainer* TargetTags = nullptr, OUT FGameplayTagContainer* OptionalRelevantTags = nullptr) const; //virtual bool IsBlockingOtherAbilities() const; /** * THIS IS SUPERSEDED BY ACTIVATEBYARTILLERY. */ virtual void ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, const FGameplayEventData* TriggerEventData) override; //InstancingPolicy is ALWAYS EGameplayAbilityInstancingPolicy::NonInstanced for artillery abilities. //Storing state outside of tags and game simulation attributes will not be replicated and will cause bugs during rollback. //Only implementation graphs in THIS function are called by artillery. Anything else will be ignored. //You MUST call end ability and commit ability as appropriate, or execution will not continue. //Prefire should use commit\end vs. cancel to signal if execution should continue, but all abilities can. UFUNCTION(BlueprintNativeEvent, Category = Ability, DisplayName = "Artillery Ability Implementation", meta=(ScriptName = "ArtilleryActivation")) void K2_ActivateViaArtillery(const FGameplayAbilityActorInfo& ActorInfo, const FGameplayEventData& Event, const FGunKey& MyGun); //Default behavior, override to use C++! virtual void K2_ActivateViaArtillery_Implementation(const FGameplayAbilityActorInfo& ActorInfo,const FGameplayEventData& Event, const FGunKey& MyGun) { } /** Do boilerplate init stuff and then call ActivateAbility */ //You get a much better sense of how this flows looking at the virtual void PreActivate(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, FOnGameplayAbilityEnded::FDelegate* OnGameplayAbilityEndedDelegate, const FGameplayEventData* TriggerEventData = nullptr) override; //HEADS UP. END ABILITY FOR ARTILLERY DOES NOT REPLICATE ANYTHING. IT DOES NOT CLEAR TIMERS OR ASYNC BECAUSE //YOU ARE NOT SUPPOSED TO USE THEM IN ARTILLERY. IF YOU DO, THEY WILL FAIL ONCE ROLLBACK IS IMPLEMENTED. //MAY GOD HAVE MERCY ON OUR SOULS. virtual void EndAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, bool bReplicateEndAbility, bool bWasCancelled) override; virtual bool CommitAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, OUT FGameplayTagContainer* OptionalRelevantTags = nullptr) override; /** Generates a GameplayEffectContextHandle from our owner and an optional TargetData.*/ FGameplayEffectContextHandle GetContextFromOwner(FGameplayAbilityTargetDataHandle OptionalTargetData) const override; /** Returns an effect context, given a specified actor info */ FGameplayEffectContextHandle MakeEffectContext(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo) const override; virtual void CancelAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, bool bReplicateCancelAbility) override; private: //these have no function in the Artillery ability sequence. void InputPressed(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo) override {}; void InputReleased(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo) override {}; /** Called from AbilityTask_WaitConfirmCancel to handle input confirming */ void OnWaitingForConfirmInputBegin() override {}; void OnWaitingForConfirmInputEnd() override {}; /** Ability sequences, and artillery in general, make use of only cosmetic events and cues where possible. */ void SendGameplayEvent(FGameplayTag EventTag, FGameplayEventData Payload) override {}; //TODO: Make sure this is actually obsolete. FOnGameplayAbilityEnded OnGameplayAbilityEnded; /** Notification that the ability has ended with data on how it was ended */ FGameplayAbilityEndedDelegate OnGameplayAbilityEndedWithData; /** Notification that the ability is being cancelled. Called before OnGameplayAbilityEnded. */ FOnGameplayAbilityCancelled OnGameplayAbilityCancelled; };
412
0.791354
1
0.791354
game-dev
MEDIA
0.987533
game-dev
0.623903
1
0.623903
drachelehre/mazer
2,833
player.py
import pygame from entity import * from constants import * from drill import * class Player(Entity): containers = () def __init__(self, x, y): super().__init__(x, y, PLAYER_SIZE) self.last_move_vec = None self.rotation = 0 self.add(*self.containers) self.timer = 0 self.drill_state = False self.drill_timer = 0.0 def triangle(self): up = pygame.Vector2(0, 1).rotate(self.rotation) right = pygame.Vector2(0, 1).rotate(self.rotation + 90) * self.size / 1.5 a = self.position + up * self.size b = self.position - up * self.size - right c = self.position - up * self.size + right return [a, b, c] def draw(self, screen): color = "yellow" if self.drill_state else "blue" pygame.draw.polygon(screen, color, self.triangle(), width=2) def rotate(self, dt): self.rotation += (PLAYER_TURN_SPEED * dt) def move(self, dt): forward = pygame.Vector2(0, 1).rotate(self.rotation) return forward * PLAYER_SPEED * dt def get_position(self): return self.position.x, self.position.y def update(self, dt): keys = pygame.key.get_pressed() move_vec = pygame.Vector2(0, 0) if keys[pygame.K_a] or keys[pygame.K_LEFT]: self.rotate(-dt) if keys[pygame.K_d] or keys[pygame.K_RIGHT]: self.rotate(dt) if keys[pygame.K_w] or keys[pygame.K_UP]: move_vec += self.move(dt) if keys[pygame.K_s] or keys[pygame.K_DOWN]: move_vec -= self.move(dt) self.position += move_vec self.last_move_vec = move_vec # store for sliding correction # game boundary resolution, no more wandering offscreen bounced = False normal = None if self.position.x < self.size: self.position.x = self.size normal = pygame.Vector2(1, 0) bounced = True elif self.position.x > SCREEN_WIDTH - self.size: self.position.x = SCREEN_WIDTH - self.size normal = pygame.Vector2(-1, 0) bounced = True if self.position.y < self.size: self.position.y = self.size normal = pygame.Vector2(0, 1) bounced = True elif self.position.y > SCREEN_HEIGHT - self.size: self.position.y = SCREEN_HEIGHT - self.size normal = pygame.Vector2(0, -1) bounced = True if bounced and self.last_move_vec.length() > 0: reflect = self.last_move_vec.reflect(normal) self.position += reflect * 0.5 if self.drill_state: self.drill_timer += dt if self.drill_timer > DRILL_DURATION: self.drill_state = False self.drill_timer = 0.0
412
0.748659
1
0.748659
game-dev
MEDIA
0.556436
game-dev
0.966468
1
0.966468
gazebosim/gazebo-classic
5,728
gazebo/gui/model/CollisionConfig_TEST.cc
/* * Copyright (C) 2015 Open Source Robotics Foundation * * 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. * */ #include "gazebo/gui/ConfigWidget.hh" #include "gazebo/gui/model/CollisionConfig.hh" #include "gazebo/gui/model/CollisionConfig_TEST.hh" #include "test_config.h" using namespace gazebo; using namespace gui; ///////////////////////////////////////////////// void CollisionConfig_TEST::Initialization() { gazebo::gui::CollisionConfig cc; QCOMPARE(cc.GetCollisionCount(), 0u); QVERIFY(cc.GetData("NotFound") == NULL); } ///////////////////////////////////////////////// void CollisionConfig_TEST::CollisionUpdates() { gazebo::gui::CollisionConfig cc; msgs::Collision c1, c2, c3; cc.AddCollision("c1", &c1); cc.AddCollision("c2", &c2); cc.AddCollision("c3", &c3); QCOMPARE(cc.GetCollisionCount(), 3u); QVERIFY(cc.GetData("c1") != NULL); QVERIFY(cc.GetData("c2") != NULL); QVERIFY(cc.GetData("c3") != NULL); QVERIFY(cc.GetData("NotFound") == NULL); msgs::CollisionPtr collisionMsgPtr(new msgs::Collision); collisionMsgPtr->set_laser_retro(0.0000789); cc.UpdateCollision("c1", collisionMsgPtr); bool foundConfig = false; for (const auto &it : cc.ConfigData()) { if (it.second->name == "c1") { const CollisionConfigData *configData = it.second; QCOMPARE(configData->configWidget->DoubleWidgetValue("laser_retro"), 0.0000789); foundConfig = true; break; } } QVERIFY(foundConfig); cc.Reset(); QCOMPARE(cc.GetCollisionCount(), 0u); QVERIFY(cc.GetData("c1") == NULL); QVERIFY(cc.GetData("c2") == NULL); QVERIFY(cc.GetData("c3") == NULL); } ///////////////////////////////////////////////// void CollisionConfig_TEST::GeometryUpdates() { gazebo::gui::CollisionConfig cc; msgs::Collision c1; cc.AddCollision("c1", &c1); const ignition::math::Vector3d size1(5, 10, 15); cc.SetGeometry("c1", size1, "unit_box"); ignition::math::Vector3d size2; std::string uri; cc.Geometry("c1", size2, uri); QCOMPARE(5.0, size2.X()); QCOMPARE(10.0, size2.Y()); QCOMPARE(15.0, size2.Z()); QCOMPARE(uri, std::string("")); ignition::math::Vector3d size3(0, 0, 0); cc.Geometry("NotFound", size3, uri); QCOMPARE(0.0, size3.X()); QCOMPARE(0.0, size3.Y()); QCOMPARE(0.0, size3.Z()); QCOMPARE(uri, std::string("")); } ///////////////////////////////////////////////// void CollisionConfig_TEST::AppliedSignal() { // Create a link inspector gazebo::gui::CollisionConfig *collisionConfig = new gazebo::gui::CollisionConfig(); QVERIFY(collisionConfig != NULL); // Connect signals connect(collisionConfig, SIGNAL(Applied()), this, SLOT(OnApply())); // Init it collisionConfig->Init(); QCOMPARE(g_appliedSignalCount, 0u); QCOMPARE(collisionConfig->GetCollisionCount(), 0u); // Get push buttons QList<QPushButton *> pushButtons = collisionConfig->findChildren<QPushButton *>(); QCOMPARE(pushButtons.size(), 3); // Add a collision pushButtons[0]->click(); QCOMPARE(collisionConfig->GetCollisionCount(), 1u); // Get spins QList<QDoubleSpinBox *> spins = collisionConfig->findChildren<QDoubleSpinBox *>(); QVERIFY(spins.size() == 33); // Get combo boxes QList<QComboBox *> combos = collisionConfig->findChildren<QComboBox *>(); QVERIFY(combos.size() == 2); // Edit collision pose (2~7) spins[2]->setValue(2.0); QTest::keyClick(spins[2], Qt::Key_Enter); QCOMPARE(g_appliedSignalCount, 1u); // Edit geometry (0) combos[0]->setCurrentIndex(2); QTest::keyClick(combos[0], Qt::Key_Enter); QCOMPARE(g_appliedSignalCount, 2u); delete collisionConfig; } ///////////////////////////////////////////////// void CollisionConfig_TEST::OnApply() { g_appliedSignalCount++; } ///////////////////////////////////////////////// void CollisionConfig_TEST::Restore() { CollisionConfig cc; msgs::Collision c1, c2, c3; cc.AddCollision("c1", &c1); cc.AddCollision("c2", &c2); QCOMPARE(cc.GetCollisionCount(), 2u); QVERIFY(cc.GetData("c1") != NULL); QVERIFY(cc.GetData("c2") != NULL); QVERIFY(cc.GetData("c3") == NULL); // Set this as the original data cc.Init(); // Add a collision and restore cc.AddCollision("c3", &c3); QCOMPARE(cc.GetCollisionCount(), 3u); QVERIFY(cc.GetData("c1") != NULL); QVERIFY(cc.GetData("c2") != NULL); QVERIFY(cc.GetData("c3") != NULL); cc.RestoreOriginalData(); QCOMPARE(cc.GetCollisionCount(), 2u); QVERIFY(cc.GetData("c1") != NULL); QVERIFY(cc.GetData("c2") != NULL); QVERIFY(cc.GetData("c3") == NULL); // Remove a collision and restore auto button = cc.findChild<QToolButton *>("removeCollisionButton_0"); QVERIFY(button); // Note that the confirmation dialog has been disabled for tests (issue #1963) button->click(); QCOMPARE(cc.GetCollisionCount(), 1u); QVERIFY(cc.GetData("c1") == NULL); QVERIFY(cc.GetData("c2") != NULL); QVERIFY(cc.GetData("c3") == NULL); cc.RestoreOriginalData(); QCOMPARE(cc.GetCollisionCount(), 2u); QVERIFY(cc.GetData("c1") != NULL); QVERIFY(cc.GetData("c2") != NULL); QVERIFY(cc.GetData("c3") == NULL); } // Generate a main function for the test QTEST_MAIN(CollisionConfig_TEST)
412
0.914522
1
0.914522
game-dev
MEDIA
0.699547
game-dev
0.860453
1
0.860453
MergHQ/CRYENGINE
31,860
Code/CryEngine/Cry3DEngine/EnvironmentPreset.cpp
// Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. #include "StdAfx.h" #include <Cry3DEngine/ITimeOfDay.h> #include "EnvironmentPreset.h" #include <CrySerialization/IArchive.h> #include <CrySerialization/IArchiveHost.h> #include <CrySerialization/ClassFactory.h> #include <CrySerialization/Enum.h> #include <CryMath/Bezier_impl.h> namespace { static const unsigned int sCurrentPresetVersion = 1; static const float sAnimTimeSecondsIn24h = 24.0f; // 24 hours = (sAnimTimeSecondsIn24h * SAnimTime::numTicksPerSecond) ticks static const float sBezierSplineKeyValueEpsilon = 0.001f; } CBezierSpline::CBezierSpline() { m_keys.reserve(2); } CBezierSpline::~CBezierSpline() { } void CBezierSpline::Init(float fDefaultValue) { m_keys.clear(); InsertKey(SAnimTime(0.0f), fDefaultValue); InsertKey(SAnimTime(sAnimTimeSecondsIn24h), fDefaultValue); } float CBezierSpline::Evaluate(float t) const { if (m_keys.size() == 0) return 0.0f; if (m_keys.size() == 1) return m_keys.front().m_controlPoint.m_value; const SAnimTime time(t); if (time <= m_keys.front().m_time) { return m_keys.front().m_controlPoint.m_value; } else if (time >= m_keys.back().m_time) { return m_keys.back().m_controlPoint.m_value; } const TKeyContainer::const_iterator it = std::upper_bound(m_keys.begin(), m_keys.end(), time, SCompKeyTime()); const TKeyContainer::const_iterator startIt = it - 1; if (startIt->m_controlPoint.m_outTangentType == SBezierControlPoint::ETangentType::Step) { return it->m_controlPoint.m_value; } if (it->m_controlPoint.m_inTangentType == SBezierControlPoint::ETangentType::Step) { return startIt->m_controlPoint.m_value; } const SAnimTime deltaTime = it->m_time - startIt->m_time; if (deltaTime == SAnimTime(0)) { return startIt->m_controlPoint.m_value; } const float timeInSegment = (time - startIt->m_time).ToFloat(); const SBezierKey* pKeyLeftOfSegment = (startIt != m_keys.begin()) ? &*(startIt - 1) : NULL; const SBezierKey* pKeyRightOfSegment = (startIt != (m_keys.end() - 2)) ? &*(startIt + 2) : NULL; const SBezierKey segmentStart = Bezier::ApplyOutTangent(*startIt, pKeyLeftOfSegment, *(startIt + 1)); const SBezierKey segmentEnd = Bezier::ApplyInTangent(*(startIt + 1), *startIt, pKeyRightOfSegment); const float factor = Bezier::InterpolationFactorFromX(timeInSegment, deltaTime.ToFloat(), segmentStart.m_controlPoint, segmentEnd.m_controlPoint); const float fResult = Bezier::EvaluateY(factor, segmentStart.m_controlPoint, segmentEnd.m_controlPoint); return fResult; } void CBezierSpline::InsertKey(SAnimTime time, float value) { SBezierKey key; key.m_time = time; key.m_controlPoint.m_value = value; const size_t nKeyNum = m_keys.size(); for (size_t i = 0; i < nKeyNum; ++i) { if (m_keys[i].m_time > time) { m_keys.insert(m_keys.begin() + i, key); return; } } m_keys.push_back(key); } void CBezierSpline::UpdateKeyForTime(float fTime, float value) { const SAnimTime time(fTime); const size_t nKeyNum = m_keys.size(); for (size_t i = 0; i < nKeyNum; ++i) { if (fabs(m_keys[i].m_time.ToFloat() - fTime) < sBezierSplineKeyValueEpsilon) { m_keys[i].m_controlPoint.m_value = value; return; } } InsertKey(time, value); } void CBezierSpline::Serialize(Serialization::IArchive& ar) { ar(m_keys, "keys"); } ////////////////////////////////////////////////////////////////////////// CTimeOfDayVariable::CTimeOfDayVariable() : m_id(ITimeOfDay::PARAM_TOTAL), m_type(ITimeOfDay::TYPE_FLOAT), m_name(NULL), m_displayName(NULL), m_group(NULL), m_minValue(0.0f), m_maxValue(0.0f), m_value(ZERO) { } CTimeOfDayVariable::~CTimeOfDayVariable() { } void CTimeOfDayVariable::Init(const char* group, const char* displayName, const char* name, ITimeOfDay::ETimeOfDayParamID nParamId, ITimeOfDay::EVariableType type, float defVal0, float defVal1, float defVal2) { m_id = nParamId; m_type = type; m_name = name; m_displayName = (displayName && *displayName) ? displayName : name; m_group = (group && *group) ? group : "Default"; if (ITimeOfDay::TYPE_FLOAT == type) { m_value.x = defVal0; m_minValue = defVal1; m_maxValue = defVal2; m_spline[0].Init(defVal0); } else if (ITimeOfDay::TYPE_COLOR == type) { m_value.x = defVal0; m_value.y = defVal1; m_value.z = defVal2; m_minValue = 0.0f; m_maxValue = 1.0f; m_spline[0].Init(defVal0); m_spline[1].Init(defVal1); m_spline[2].Init(defVal2); } } void CTimeOfDayVariable::Update(float time) { m_value = GetInterpolatedAt(time); } Vec3 CTimeOfDayVariable::GetInterpolatedAt(float t) const { Vec3 result; result.x = clamp_tpl(m_spline[0].Evaluate(t), m_minValue, m_maxValue); result.y = clamp_tpl(m_spline[1].Evaluate(t), m_minValue, m_maxValue); result.z = clamp_tpl(m_spline[2].Evaluate(t), m_minValue, m_maxValue); return result; } size_t CTimeOfDayVariable::GetSplineKeyCount(int nSpline) const { if (const CBezierSpline* pSpline = GetSpline(nSpline)) return pSpline->GetKeyCount(); return 0; } bool CTimeOfDayVariable::GetSplineKeys(int nSpline, SBezierKey* keysArray, unsigned int keysArraySize) const { if (const CBezierSpline* pSpline = GetSpline(nSpline)) { if (keysArraySize < pSpline->GetKeyCount()) return false; pSpline->GetKeys(keysArray); return true; } return false; } bool CTimeOfDayVariable::SetSplineKeys(int nSpline, const SBezierKey* keysArray, unsigned int keysArraySize) { if (CBezierSpline* pSpline = GetSpline(nSpline)) { pSpline->SetKeys(keysArray, keysArraySize); return true; } return false; } bool CTimeOfDayVariable::UpdateSplineKeyForTime(int nSpline, float fTime, float newKey) { if (CBezierSpline* pSpline = GetSpline(nSpline)) { pSpline->UpdateKeyForTime(fTime, newKey); return true; } return false; } void CTimeOfDayVariable::Serialize(Serialization::IArchive& ar) { ar(m_id, "id"); ar(m_type, "type"); ar(m_minValue, "minValue"); ar(m_maxValue, "maxValue"); ar(m_spline[0], "spline0"); ar(m_spline[1], "spline1"); ar(m_spline[2], "spline2"); } ////////////////////////////////////////////////////////////////////////// CEnvironmentPreset::CEnvironmentPreset() { ResetVariables(); } CEnvironmentPreset::~CEnvironmentPreset() { } void CEnvironmentPreset::ResetVariables() { const float fRecip255 = 1.0f / 255.0f; AddVar("Sun", "", "Sun color", ITimeOfDay::PARAM_SUN_COLOR, ITimeOfDay::TYPE_COLOR, 255.0f * fRecip255, 248.0f * fRecip255, 248.0f * fRecip255); AddVar("Sun", "Sun intensity (lux)", "Sun intensity", ITimeOfDay::PARAM_SUN_INTENSITY, ITimeOfDay::TYPE_FLOAT, 119000.0f, 0.0f, 550000.0f); AddVar("Sun", "", "Sun specular multiplier", ITimeOfDay::PARAM_SUN_SPECULAR_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 4.0f); AddVar("Fog", "Color (bottom)", "Fog color", ITimeOfDay::PARAM_FOG_COLOR, ITimeOfDay::TYPE_COLOR, 0.0f, 0.0f, 0.0f); AddVar("Fog", "Color (bottom) multiplier", "Fog color multiplier", ITimeOfDay::PARAM_FOG_COLOR_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 0.0f, 0.0f, 16.0f); AddVar("Fog", "Height (bottom)", "Fog height (bottom)", ITimeOfDay::PARAM_VOLFOG_HEIGHT, ITimeOfDay::TYPE_FLOAT, 0.0f, -5000.0f, 30000.0f); AddVar("Fog", "Density (bottom)", "Fog layer density (bottom)", ITimeOfDay::PARAM_VOLFOG_DENSITY, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 1.0f); AddVar("Fog", "Color (top)", "Fog color (top)", ITimeOfDay::PARAM_FOG_COLOR2, ITimeOfDay::TYPE_COLOR, 0.0f, 0.0f, 0.0f); AddVar("Fog", "Color (top) multiplier", "Fog color (top) multiplier", ITimeOfDay::PARAM_FOG_COLOR2_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 0.0f, 0.0f, 16.0f); AddVar("Fog", "Height (top)", "Fog height (top)", ITimeOfDay::PARAM_VOLFOG_HEIGHT2, ITimeOfDay::TYPE_FLOAT, 4000.0f, -5000.0f, 30000.0f); AddVar("Fog", "Density (top)", "Fog layer density (top)", ITimeOfDay::PARAM_VOLFOG_DENSITY2, ITimeOfDay::TYPE_FLOAT, 0.0f, 0.0f, 1.0f); AddVar("Fog", "Color height offset", "Fog color height offset", ITimeOfDay::PARAM_VOLFOG_HEIGHT_OFFSET, ITimeOfDay::TYPE_FLOAT, 0.0f, -1.0f, 1.0f); AddVar("Fog", "Color (radial)", "Fog color (radial)", ITimeOfDay::PARAM_FOG_RADIAL_COLOR, ITimeOfDay::TYPE_COLOR, 0.0f, 0.0f, 0.0f); AddVar("Fog", "Color (radial) multiplier", "Fog color (radial) multiplier", ITimeOfDay::PARAM_FOG_RADIAL_COLOR_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 0.0f, 0.0f, 16.0f); AddVar("Fog", "Radial size", "Fog radial size", ITimeOfDay::PARAM_VOLFOG_RADIAL_SIZE, ITimeOfDay::TYPE_FLOAT, 0.75f, 0.0f, 1.0f); AddVar("Fog", "Radial lobe", "Fog radial lobe", ITimeOfDay::PARAM_VOLFOG_RADIAL_LOBE, ITimeOfDay::TYPE_FLOAT, 0.5f, 0.0f, 1.0f); AddVar("Fog", "Global density", "Volumetric fog: Global density", ITimeOfDay::PARAM_VOLFOG_GLOBAL_DENSITY, ITimeOfDay::TYPE_FLOAT, 0.02f, 0.0f, 100.0f); AddVar("Fog", "Final density clamp", "Volumetric fog: Final density clamp", ITimeOfDay::PARAM_VOLFOG_FINAL_DENSITY_CLAMP, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 1.0f); AddVar("Fog", "Ramp start", "Volumetric fog: Ramp start", ITimeOfDay::PARAM_VOLFOG_RAMP_START, ITimeOfDay::TYPE_FLOAT, 0.0f, 0.0f, 30000.0f); AddVar("Fog", "Ramp end", "Volumetric fog: Ramp end", ITimeOfDay::PARAM_VOLFOG_RAMP_END, ITimeOfDay::TYPE_FLOAT, 100.0f, 0.0f, 30000.0f); AddVar("Fog", "Ramp influence", "Volumetric fog: Ramp influence", ITimeOfDay::PARAM_VOLFOG_RAMP_INFLUENCE, ITimeOfDay::TYPE_FLOAT, 0.0f, 0.0f, 1.0f); AddVar("Fog", "Shadow darkening", "Volumetric fog: Shadow darkening", ITimeOfDay::PARAM_VOLFOG_SHADOW_DARKENING, ITimeOfDay::TYPE_FLOAT, 0.25f, 0.0f, 1.0f); AddVar("Fog", "Shadow darkening sun", "Volumetric fog: Shadow darkening sun", ITimeOfDay::PARAM_VOLFOG_SHADOW_DARKENING_SUN, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 1.0f); AddVar("Fog", "Shadow darkening ambient", "Volumetric fog: Shadow darkening ambient", ITimeOfDay::PARAM_VOLFOG_SHADOW_DARKENING_AMBIENT, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 1.0f); AddVar("Fog", "Shadow range", "Volumetric fog: Shadow range", ITimeOfDay::PARAM_VOLFOG_SHADOW_RANGE, ITimeOfDay::TYPE_FLOAT, 0.1f, 0.0f, 1.0f); AddVar("Volumetric fog", "Height (bottom)", "Volumetric fog 2: Fog height (bottom)", ITimeOfDay::PARAM_VOLFOG2_HEIGHT, ITimeOfDay::TYPE_FLOAT, 0.0f, -5000.0f, 30000.0f); AddVar("Volumetric fog", "Density (bottom)", "Volumetric fog 2: Fog layer density (bottom)", ITimeOfDay::PARAM_VOLFOG2_DENSITY, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 1.0f); AddVar("Volumetric fog", "Height (top)", "Volumetric fog 2: Fog height (top)", ITimeOfDay::PARAM_VOLFOG2_HEIGHT2, ITimeOfDay::TYPE_FLOAT, 4000.0f, -5000.0f, 30000.0f); AddVar("Volumetric fog", "Density (top)", "Volumetric fog 2: Fog layer density (top)", ITimeOfDay::PARAM_VOLFOG2_DENSITY2, ITimeOfDay::TYPE_FLOAT, 0.0001f, 0.0f, 1.0f); AddVar("Volumetric fog", "Global density", "Volumetric fog 2: Global fog density", ITimeOfDay::PARAM_VOLFOG2_GLOBAL_DENSITY, ITimeOfDay::TYPE_FLOAT, 0.1f, 0.0f, 100.0f); AddVar("Volumetric fog", "Ramp start", "Volumetric fog 2: Ramp start", ITimeOfDay::PARAM_VOLFOG2_RAMP_START, ITimeOfDay::TYPE_FLOAT, 0.0f, 0.0f, 30000.0f); AddVar("Volumetric fog", "Ramp end", "Volumetric fog 2: Ramp end", ITimeOfDay::PARAM_VOLFOG2_RAMP_END, ITimeOfDay::TYPE_FLOAT, 0.0f, 0.0f, 30000.0f); AddVar("Volumetric fog", "Color (atmosphere)", "Volumetric fog 2: Fog albedo color (atmosphere)", ITimeOfDay::PARAM_VOLFOG2_COLOR1, ITimeOfDay::TYPE_COLOR, 1.0f, 1.0f, 1.0f); AddVar("Volumetric fog", "Anisotropy (atmosphere)", "Volumetric fog 2: Anisotropy factor (atmosphere)", ITimeOfDay::PARAM_VOLFOG2_ANISOTROPIC1, ITimeOfDay::TYPE_FLOAT, 0.2f, -1.0f, 1.0f); AddVar("Volumetric fog", "Color (sun radial)", "Volumetric fog 2: Fog albedo color (sun radial)", ITimeOfDay::PARAM_VOLFOG2_COLOR2, ITimeOfDay::TYPE_COLOR, 1.0f, 1.0f, 1.0f); AddVar("Volumetric fog", "Anisotropy (sun radial)", "Volumetric fog 2: Anisotropy factor (sun radial)", ITimeOfDay::PARAM_VOLFOG2_ANISOTROPIC2, ITimeOfDay::TYPE_FLOAT, 0.95f, -1.0f, 1.0f); AddVar("Volumetric fog", "Radial blend factor", "Volumetric fog 2: Blend factor for sun scattering", ITimeOfDay::PARAM_VOLFOG2_BLEND_FACTOR, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 1.0f); AddVar("Volumetric fog", "Radial blend mode", "Volumetric fog 2: Blend mode for sun scattering", ITimeOfDay::PARAM_VOLFOG2_BLEND_MODE, ITimeOfDay::TYPE_FLOAT, 0.0f, 0.0f, 1.0f); AddVar("Volumetric fog", "Range", "Volumetric fog 2: Maximum range of ray-marching", ITimeOfDay::PARAM_VOLFOG2_RANGE, ITimeOfDay::TYPE_FLOAT, 64.0f, 0.0f, 8192.0f); AddVar("Volumetric fog", "In-scattering", "Volumetric fog 2: In-scattering factor", ITimeOfDay::PARAM_VOLFOG2_INSCATTER, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 100.0f); AddVar("Volumetric fog", "Extinction", "Volumetric fog 2: Extinction factor", ITimeOfDay::PARAM_VOLFOG2_EXTINCTION, ITimeOfDay::TYPE_FLOAT, 0.3f, 0.0f, 100.0f); AddVar("Volumetric fog", "Color (entities)", "Volumetric fog 2: Fog albedo color (entities)", ITimeOfDay::PARAM_VOLFOG2_COLOR, ITimeOfDay::TYPE_COLOR, 1.0f, 1.0f, 1.0f); AddVar("Volumetric fog", "Anisotropy (entities)", "Volumetric fog 2: Anisotropy factor (entities)", ITimeOfDay::PARAM_VOLFOG2_ANISOTROPIC, ITimeOfDay::TYPE_FLOAT, 0.6f, -1.0f, 1.0f); AddVar("Volumetric fog", "Analytical fog visibility", "Volumetric fog 2: Analytical volumetric fog visibility", ITimeOfDay::PARAM_VOLFOG2_GLOBAL_FOG_VISIBILITY, ITimeOfDay::TYPE_FLOAT, 0.5f, 0.0f, 1.0f); AddVar("Volumetric fog", "Final density clamp", "Volumetric fog 2: Final density clamp", ITimeOfDay::PARAM_VOLFOG2_FINAL_DENSITY_CLAMP, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 1.0f); AddVar("Sky Light", "Sun intensity", "Sky light: Sun intensity", ITimeOfDay::PARAM_SKYLIGHT_SUN_INTENSITY, ITimeOfDay::TYPE_COLOR, 1.0f, 1.0f, 1.0f); AddVar("Sky Light", "Sun intensity multiplier", "Sky light: Sun intensity multiplier", ITimeOfDay::PARAM_SKYLIGHT_SUN_INTENSITY_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 50.0f, 0.0f, 1000.0f); AddVar("Sky Light", "Mie scattering", "Sky light: Mie scattering", ITimeOfDay::PARAM_SKYLIGHT_KM, ITimeOfDay::TYPE_FLOAT, 4.8f, 0.0f, 1000.0f); AddVar("Sky Light", "Rayleigh scattering", "Sky light: Rayleigh scattering", ITimeOfDay::PARAM_SKYLIGHT_KR, ITimeOfDay::TYPE_FLOAT, 2.0f, 0.0f, 1000.0f); AddVar("Sky Light", "Sun anisotropy factor", "Sky light: Sun anisotropy factor", ITimeOfDay::PARAM_SKYLIGHT_G, ITimeOfDay::TYPE_FLOAT, -0.997f, -0.9999f, 0.9999f); AddVar("Sky Light", "Wavelength (R)", "Sky light: Wavelength (R)", ITimeOfDay::PARAM_SKYLIGHT_WAVELENGTH_R, ITimeOfDay::TYPE_FLOAT, 694.0f, 380.0f, 780.0f); AddVar("Sky Light", "Wavelength (G)", "Sky light: Wavelength (G)", ITimeOfDay::PARAM_SKYLIGHT_WAVELENGTH_G, ITimeOfDay::TYPE_FLOAT, 597.0f, 380.0f, 780.0f); AddVar("Sky Light", "Wavelength (B)", "Sky light: Wavelength (B)", ITimeOfDay::PARAM_SKYLIGHT_WAVELENGTH_B, ITimeOfDay::TYPE_FLOAT, 488.0f, 380.0f, 780.0f); AddVar("Night Sky", "Horizon color", "Night sky: Horizon color", ITimeOfDay::PARAM_NIGHSKY_HORIZON_COLOR, ITimeOfDay::TYPE_COLOR, 222.0f * fRecip255, 148.0f * fRecip255, 47.0f * fRecip255); AddVar("Night Sky", "Zenith color", "Night sky: Zenith color", ITimeOfDay::PARAM_NIGHSKY_ZENITH_COLOR, ITimeOfDay::TYPE_COLOR, 17.0f * fRecip255, 38.0f * fRecip255, 78.0f * fRecip255); AddVar("Night Sky", "Zenith shift", "Night sky: Zenith shift", ITimeOfDay::PARAM_NIGHSKY_ZENITH_SHIFT, ITimeOfDay::TYPE_FLOAT, 0.25f, 0.0f, 16.0f); AddVar("Night Sky", "Star intensity", "Night sky: Star intensity", ITimeOfDay::PARAM_NIGHSKY_START_INTENSITY, ITimeOfDay::TYPE_FLOAT, 0.01f, 0.0f, 16.0f); AddVar("Night Sky", "Moon color", "Night sky: Moon color", ITimeOfDay::PARAM_NIGHSKY_MOON_COLOR, ITimeOfDay::TYPE_COLOR, 255.0f * fRecip255, 255.0f * fRecip255, 255.0f * fRecip255); AddVar("Night Sky", "Moon inner corona color", "Night sky: Moon inner corona color", ITimeOfDay::PARAM_NIGHSKY_MOON_INNERCORONA_COLOR, ITimeOfDay::TYPE_COLOR, 230.0f * fRecip255, 255.0f * fRecip255, 255.0f * fRecip255); AddVar("Night Sky", "Moon inner corona scale", "Night sky: Moon inner corona scale", ITimeOfDay::PARAM_NIGHSKY_MOON_INNERCORONA_SCALE, ITimeOfDay::TYPE_FLOAT, 0.499f, 0.0f, 2.0f); AddVar("Night Sky", "Moon outer corona color", "Night sky: Moon outer corona color", ITimeOfDay::PARAM_NIGHSKY_MOON_OUTERCORONA_COLOR, ITimeOfDay::TYPE_COLOR, 128.0f * fRecip255, 200.0f * fRecip255, 255.0f * fRecip255); AddVar("Night Sky", "Moon outer corona scale", "Night sky: Moon outer corona scale", ITimeOfDay::PARAM_NIGHSKY_MOON_OUTERCORONA_SCALE, ITimeOfDay::TYPE_FLOAT, 0.006f, 0.0f, 2.0f); AddVar("Night Sky Multiplier", "Horizon color", "Night sky: Horizon color multiplier", ITimeOfDay::PARAM_NIGHSKY_HORIZON_COLOR_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 0.0001f, 0.0f, 0.1f); AddVar("Night Sky Multiplier", "Zenith color", "Night sky: Zenith color multiplier", ITimeOfDay::PARAM_NIGHSKY_ZENITH_COLOR_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 0.00002f, 0.0f, 0.1f); AddVar("Night Sky Multiplier", "Moon color", "Night sky: Moon color multiplier", ITimeOfDay::PARAM_NIGHSKY_MOON_COLOR_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 0.01f, 0.0f, 0.1f); AddVar("Night Sky Multiplier", "Moon inner corona color", "Night sky: Moon inner corona color multiplier", ITimeOfDay::PARAM_NIGHSKY_MOON_INNERCORONA_COLOR_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 0.0001f, 0.0f, 0.1f); AddVar("Night Sky Multiplier", "Moon outer corona color", "Night sky: Moon outer corona color multiplier", ITimeOfDay::PARAM_NIGHSKY_MOON_OUTERCORONA_COLOR_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 0.00005f, 0.0f, 0.1f); AddVar("Cloud Shading", "Sun contribution", "Cloud shading: Sun light multiplier", ITimeOfDay::PARAM_CLOUDSHADING_SUNLIGHT_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 1.96f, 0.0f, 16.0f); AddVar("Cloud Shading", "Sky contribution", "Cloud shading: Sky light multiplier", ITimeOfDay::PARAM_CLOUDSHADING_SKYLIGHT_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 0.8f, 0.0f, 16.0f); AddVar("Cloud Shading", "Sun custom color", "Cloud shading: Sun custom color", ITimeOfDay::PARAM_CLOUDSHADING_SUNLIGHT_CUSTOM_COLOR, ITimeOfDay::TYPE_COLOR, 215.0f * fRecip255, 200.0f * fRecip255, 170.0f * fRecip255); AddVar("Cloud Shading", "Sun custom color multiplier", "Cloud shading: Sun custom color multiplier", ITimeOfDay::PARAM_CLOUDSHADING_SUNLIGHT_CUSTOM_COLOR_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 16.0f); AddVar("Cloud Shading", "Sun custom color influence", "Cloud shading: Sun custom color influence", ITimeOfDay::PARAM_CLOUDSHADING_SUNLIGHT_CUSTOM_COLOR_INFLUENCE, ITimeOfDay::TYPE_FLOAT, 0.0f, 0.0f, 1.0f); AddVar("Volumetric Clouds", "Global cloudiness", "Volumetric clouds: Global cloudiness", ITimeOfDay::PARAM_VOLCLOUD_GLOBAL_DENSITY, ITimeOfDay::TYPE_FLOAT, 0.5f, 0.0f, 1.0f); AddVar("Volumetric Clouds", "Clouds altitude", "Volumetric clouds: Clouds altitude", ITimeOfDay::PARAM_VOLCLOUD_HEIGHT, ITimeOfDay::TYPE_FLOAT, 1000.f, -4000.0f, 4000.0f); AddVar("Volumetric Clouds", "Clouds thickness", "Volumetric clouds: Clouds thickness", ITimeOfDay::PARAM_VOLCLOUD_THICKNESS, ITimeOfDay::TYPE_FLOAT, 1500.f, 0.0f, 8000.0f); AddVar("Volumetric Clouds", "Clouds edge turbulence", "Volumetric clouds: Clouds edge turbulence", ITimeOfDay::PARAM_VOLCLOUD_CLOUD_EDGE_TURBULENCE, ITimeOfDay::TYPE_FLOAT, 0.4f, 0.0f, 1.0f); AddVar("Volumetric Clouds", "Clouds edge threshold", "Volumetric clouds: Clouds edge threshold", ITimeOfDay::PARAM_VOLCLOUD_CLOUD_EDGE_THRESHOLD, ITimeOfDay::TYPE_FLOAT, 0.3f, 0.0f, 1.0f); AddVar("Volumetric Clouds", "Sun single scattering multiplier", "Volumetric clouds: Sun single scattering multiplier", ITimeOfDay::PARAM_VOLCLOUD_SUN_SINGLE_SCATTERING, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 10.0f); AddVar("Volumetric Clouds", "Sun low-order scattering multiplier", "Volumetric clouds: Sun low-order scattering multiplier", ITimeOfDay::PARAM_VOLCLOUD_SUN_LOW_ORDER_SCATTERING, ITimeOfDay::TYPE_FLOAT, 2.0f, 0.0f, 10.0f); AddVar("Volumetric Clouds", "Sun low-order scattering anisotropy", "Volumetric clouds: Sun low-order scattering anisotropy", ITimeOfDay::PARAM_VOLCLOUD_SUN_LOW_ORDER_SCATTERING_ANISTROPY, ITimeOfDay::TYPE_FLOAT, 0.2f, 0.0f, 0.999999f); AddVar("Volumetric Clouds", "Sun high-order scattering multiplier", "Volumetric clouds: Sun high-order scattering multiplier", ITimeOfDay::PARAM_VOLCLOUD_SUN_HIGH_ORDER_SCATTERING, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 10.0f); AddVar("Volumetric Clouds", "Sky lighting multiplier", "Volumetric clouds: Sky lighting multiplier", ITimeOfDay::PARAM_VOLCLOUD_SKY_LIGHTING_SCATTERING, ITimeOfDay::TYPE_FLOAT, 4.0f, 0.0f, 20.0f); AddVar("Volumetric Clouds", "Ground lighting multiplier", "Volumetric clouds: Ground lighting multiplier", ITimeOfDay::PARAM_VOLCLOUD_GOUND_LIGHTING_SCATTERING, ITimeOfDay::TYPE_FLOAT, 2.0f, 0.0f, 20.0f); AddVar("Volumetric Clouds", "Ground albedo", "Volumetric clouds: Ground albedo", ITimeOfDay::PARAM_VOLCLOUD_GROUND_LIGHTING_ALBEDO, ITimeOfDay::TYPE_COLOR, 0.19f, 0.2f, 0.15f); AddVar("Volumetric Clouds", "Multi-scattering attenuation", "Volumetric clouds: Multi-scattering attenuation", ITimeOfDay::PARAM_VOLCLOUD_MULTI_SCATTERING_ATTENUATION, ITimeOfDay::TYPE_FLOAT, 8.0f, 0.0f, 40.0f); AddVar("Volumetric Clouds", "Multi-scattering preservation", "Volumetric clouds: Multi-scattering preservation", ITimeOfDay::PARAM_VOLCLOUD_MULTI_SCATTERING_PRESERVATION, ITimeOfDay::TYPE_FLOAT, 0.4f, 0.0f, 1.0f); AddVar("Volumetric Clouds", "Powder shading effect", "Volumetric clouds: Powder shading effect", ITimeOfDay::PARAM_VOLCLOUD_POWDER_EFFECT, ITimeOfDay::TYPE_FLOAT, 6.0f, 0.0f, 20.0f); AddVar("Volumetric Clouds", "Absorption percentage", "Volumetric clouds: Absorption percentage", ITimeOfDay::PARAM_VOLCLOUD_ABSORPTION, ITimeOfDay::TYPE_FLOAT, 0.01f, 0.0f, 4.0f); AddVar("Volumetric Clouds", "Atmospheric albedo", "Volumetric clouds: Atmospheric albedo", ITimeOfDay::PARAM_VOLCLOUD_ATMOSPHERIC_ALBEDO, ITimeOfDay::TYPE_COLOR, 0.244f, 0.446f, 1.0f); AddVar("Volumetric Clouds", "Atmospheric scattering", "Volumetric clouds: Atmospheric scattering", ITimeOfDay::PARAM_VOLCLOUD_ATMOSPHERIC_SCATTERING, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 10.0f); AddVar("Volumetric Clouds", "Wind influence", "Volumetric clouds: Wind influence", ITimeOfDay::PARAM_VOLCLOUD_WIND_INFLUENCE, ITimeOfDay::TYPE_FLOAT, 0.0f, -1000.0f, 1000.0f); AddVar("Sun Rays Effect", "", "Sun shafts visibility", ITimeOfDay::PARAM_SUN_SHAFTS_VISIBILITY, ITimeOfDay::TYPE_FLOAT, 0.25f, 0.0f, 1.0f); AddVar("Sun Rays Effect", "", "Sun rays visibility", ITimeOfDay::PARAM_SUN_RAYS_VISIBILITY, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 10.0f); AddVar("Sun Rays Effect", "", "Sun rays attenuation", ITimeOfDay::PARAM_SUN_RAYS_ATTENUATION, ITimeOfDay::TYPE_FLOAT, 5.0f, 0.0f, 10.0f); AddVar("Sun Rays Effect", "", "Sun rays suncolor influence", ITimeOfDay::PARAM_SUN_RAYS_SUNCOLORINFLUENCE, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 1.0f); AddVar("Sun Rays Effect", "", "Sun rays custom color", ITimeOfDay::PARAM_SUN_RAYS_CUSTOMCOLOR, ITimeOfDay::TYPE_COLOR, 1.0f, 1.0f, 1.0f); AddVar("HDR", "", "Film curve shoulder scale", ITimeOfDay::PARAM_HDR_FILMCURVE_SHOULDER_SCALE, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 10.0f); AddVar("HDR", "", "Film curve midtones scale", ITimeOfDay::PARAM_HDR_FILMCURVE_LINEAR_SCALE, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 10.0f); AddVar("HDR", "", "Film curve toe scale", ITimeOfDay::PARAM_HDR_FILMCURVE_TOE_SCALE, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 10.0f); AddVar("HDR", "", "Film curve whitepoint", ITimeOfDay::PARAM_HDR_FILMCURVE_WHITEPOINT, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 10.0f); AddVar("HDR", "", "Saturation", ITimeOfDay::PARAM_HDR_COLORGRADING_COLOR_SATURATION, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 2.0f); AddVar("HDR", "", "Color balance", ITimeOfDay::PARAM_HDR_COLORGRADING_COLOR_BALANCE, ITimeOfDay::TYPE_COLOR, 1.0f, 1.0f, 1.0f); AddVar("HDR", "(Dep) Scene key", "Scene key", ITimeOfDay::PARAM_HDR_EYEADAPTATION_SCENEKEY, ITimeOfDay::TYPE_FLOAT, 0.18f, 0.0f, 1.0f); AddVar("HDR", "(Dep) Min exposure", "Min exposure", ITimeOfDay::PARAM_HDR_EYEADAPTATION_MIN_EXPOSURE, ITimeOfDay::TYPE_FLOAT, 0.36f, 0.0f, 10.0f); AddVar("HDR", "(Dep) Max exposure", "Max exposure", ITimeOfDay::PARAM_HDR_EYEADAPTATION_MAX_EXPOSURE, ITimeOfDay::TYPE_FLOAT, 2.8f, 0.0f, 10.0f); AddVar("HDR", "", "EV Min", ITimeOfDay::PARAM_HDR_EYEADAPTATION_EV_MIN, ITimeOfDay::TYPE_FLOAT, 4.5f, -10.0f, 20.0f); AddVar("HDR", "", "EV Max", ITimeOfDay::PARAM_HDR_EYEADAPTATION_EV_MAX, ITimeOfDay::TYPE_FLOAT, 17.0f, -10.0f, 20.0f); AddVar("HDR", "", "EV Auto compensation", ITimeOfDay::PARAM_HDR_EYEADAPTATION_EV_AUTO_COMPENSATION, ITimeOfDay::TYPE_FLOAT, 1.5f, -5.0f, 5.0f); AddVar("HDR", "", "Bloom amount", ITimeOfDay::PARAM_HDR_BLOOM_AMOUNT, ITimeOfDay::TYPE_FLOAT, 0.1f, 0.0f, 10.0f); AddVar("Filters", "Grain", "Filters: grain", ITimeOfDay::PARAM_COLORGRADING_FILTERS_GRAIN, ITimeOfDay::TYPE_FLOAT, 0.0f, 0.0f, 8.0f); // deprecated AddVar("Filters", "Photofilter color", "Filters: photofilter color", ITimeOfDay::PARAM_COLORGRADING_FILTERS_PHOTOFILTER_COLOR, ITimeOfDay::TYPE_COLOR, 0.952f, 0.517f, 0.09f); // deprecated AddVar("Filters", "Photofilter density", "Filters: photofilter density", ITimeOfDay::PARAM_COLORGRADING_FILTERS_PHOTOFILTER_DENSITY, ITimeOfDay::TYPE_FLOAT, 0.0f, 0.0f, 1.0f); // deprecated AddVar("Depth Of Field", "Focus range", "Dof: focus range", ITimeOfDay::PARAM_COLORGRADING_DOF_FOCUSRANGE, ITimeOfDay::TYPE_FLOAT, 1000.0f, 0.0f, 10000.0f); AddVar("Depth Of Field", "Blur amount", "Dof: blur amount", ITimeOfDay::PARAM_COLORGRADING_DOF_BLURAMOUNT, ITimeOfDay::TYPE_FLOAT, 0.0f, 0.0f, 1.0f); AddVar("Advanced", "", "Ocean fog color", ITimeOfDay::PARAM_OCEANFOG_COLOR, ITimeOfDay::TYPE_COLOR, 29.0f * fRecip255, 102.0f * fRecip255, 141.0f * fRecip255); AddVar("Advanced", "", "Ocean fog color multiplier", ITimeOfDay::PARAM_OCEANFOG_COLOR_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 1.0f); AddVar("Advanced", "", "Ocean fog density", ITimeOfDay::PARAM_OCEANFOG_DENSITY, ITimeOfDay::TYPE_FLOAT, 0.2f, 0.0f, 1.0f); AddVar("Advanced", "", "Skybox multiplier", ITimeOfDay::PARAM_SKYBOX_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 1.0f); const float arrDepthConstBias[] = { 1.0f, 1.0f, 1.9f, 3.0f, 2.0f, 2.0f, 2.0f, 2.0f }; const float arrDepthSlopeBias[] = { 4.0f, 2.0f, 0.24f, 0.24f, 0.5f, 0.5f, 0.5f, 0.5f }; AddVar("Shadows", "", "Cascade 0: Bias", ITimeOfDay::PARAM_SHADOWSC0_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthConstBias[0], 0.0f, 10.0f); AddVar("Shadows", "", "Cascade 0: Slope Bias", ITimeOfDay::PARAM_SHADOWSC0_SLOPE_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthSlopeBias[0], 0.0f, 500.0f); AddVar("Shadows", "", "Cascade 1: Bias", ITimeOfDay::PARAM_SHADOWSC1_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthConstBias[1], 0.0f, 10.0f); AddVar("Shadows", "", "Cascade 1: Slope Bias", ITimeOfDay::PARAM_SHADOWSC1_SLOPE_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthSlopeBias[1], 0.0f, 500.0f); AddVar("Shadows", "", "Cascade 2: Bias", ITimeOfDay::PARAM_SHADOWSC2_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthConstBias[2], 0.0f, 10.0f); AddVar("Shadows", "", "Cascade 2: Slope Bias", ITimeOfDay::PARAM_SHADOWSC2_SLOPE_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthSlopeBias[2], 0.0f, 500.0f); AddVar("Shadows", "", "Cascade 3: Bias", ITimeOfDay::PARAM_SHADOWSC3_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthConstBias[3], 0.0f, 10.0f); AddVar("Shadows", "", "Cascade 3: Slope Bias", ITimeOfDay::PARAM_SHADOWSC3_SLOPE_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthSlopeBias[3], 0.0f, 500.0f); AddVar("Shadows", "", "Cascade 4: Bias", ITimeOfDay::PARAM_SHADOWSC4_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthConstBias[4], 0.0f, 10.0f); AddVar("Shadows", "", "Cascade 4: Slope Bias", ITimeOfDay::PARAM_SHADOWSC4_SLOPE_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthSlopeBias[4], 0.0f, 500.0f); AddVar("Shadows", "", "Cascade 5: Bias", ITimeOfDay::PARAM_SHADOWSC5_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthConstBias[5], 0.0f, 10.0f); AddVar("Shadows", "", "Cascade 5: Slope Bias", ITimeOfDay::PARAM_SHADOWSC5_SLOPE_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthSlopeBias[5], 0.0f, 500.0f); AddVar("Shadows", "", "Cascade 6: Bias", ITimeOfDay::PARAM_SHADOWSC6_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthConstBias[6], 0.0f, 10.0f); AddVar("Shadows", "", "Cascade 6: Slope Bias", ITimeOfDay::PARAM_SHADOWSC6_SLOPE_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthSlopeBias[6], 0.0f, 500.0f); AddVar("Shadows", "", "Cascade 7: Bias", ITimeOfDay::PARAM_SHADOWSC7_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthConstBias[7], 0.0f, 10.0f); AddVar("Shadows", "", "Cascade 7: Slope Bias", ITimeOfDay::PARAM_SHADOWSC7_SLOPE_BIAS, ITimeOfDay::TYPE_FLOAT, arrDepthSlopeBias[7], 0.0f, 500.0f); AddVar("Shadows", "", "Shadow jittering", ITimeOfDay::PARAM_SHADOW_JITTERING, ITimeOfDay::TYPE_FLOAT, 2.5f, 0.f, 10.f); AddVar("Obsolete", "", "HDR dynamic power factor", ITimeOfDay::PARAM_HDR_DYNAMIC_POWER_FACTOR, ITimeOfDay::TYPE_FLOAT, 0.0f, -4.0f, 4.0f); AddVar("Obsolete", "", "Global illumination multiplier", ITimeOfDay::PARAM_GI_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 1.f, 0.f, 100.f); AddVar("Obsolete", "", "Sky brightening (terrain occlusion)", ITimeOfDay::PARAM_TERRAIN_OCCL_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 0.3f, 0.f, 1.f); AddVar("Obsolete", "", "Sun color multiplier", ITimeOfDay::PARAM_SUN_COLOR_MULTIPLIER, ITimeOfDay::TYPE_FLOAT, 1.0f, 0.0f, 16.0f); } void CEnvironmentPreset::Serialize(Serialization::IArchive& ar) { if (ar.isInput()) { unsigned int version = 0; const bool bReadResult = ar(version, "version"); if (bReadResult && (sCurrentPresetVersion == version)) { // read directly for (size_t i = 0; i < ITimeOfDay::PARAM_TOTAL; ++i) { ar(m_vars[i], "var"); } } else { // convert to current version for (size_t i = 0; i < ITimeOfDay::PARAM_TOTAL; ++i) { const CTimeOfDayVariable& var = m_vars[i]; CTimeOfDayVariable tempVar = var; ar(tempVar, "var"); if (!bReadResult) { //converting from initial version. //rescale time from [0..1] to [0..sAnimTimeSecondsIn24h] for (unsigned int i = 0; i < 3; ++i) { CBezierSpline* pSpline = tempVar.GetSpline(i); const size_t nKeyCount = pSpline->GetKeyCount(); if (!nKeyCount) continue; std::vector<SBezierKey> tempKeys; tempKeys.resize(nKeyCount); pSpline->GetKeys(&tempKeys[0]); for (unsigned int j = 0; j < nKeyCount; ++j) { SBezierKey& key = tempKeys[j]; key.m_time *= sAnimTimeSecondsIn24h; } pSpline->SetKeys(&tempKeys[0], nKeyCount); } } const ITimeOfDay::ETimeOfDayParamID id = tempVar.GetId(); if (id < ITimeOfDay::PARAM_TOTAL) m_vars[id] = tempVar; //update the actual var } } } else { ar(sCurrentPresetVersion, "version"); for (size_t i = 0; i < ITimeOfDay::PARAM_TOTAL; ++i) { ar(m_vars[i], "var"); } } } void CEnvironmentPreset::Update(float t) { t *= sAnimTimeSecondsIn24h; for (size_t i = 0; i < ITimeOfDay::PARAM_TOTAL; ++i) { m_vars[i].Update(t); } } CTimeOfDayVariable* CEnvironmentPreset::GetVar(const char* varName) { for (size_t i = 0; i < ITimeOfDay::PARAM_TOTAL; ++i) { if (strcmp(m_vars[i].GetName(), varName) == 0) { return &m_vars[i]; } } return NULL; } bool CEnvironmentPreset::InterpolateVarInRange(ITimeOfDay::ETimeOfDayParamID id, float fMin, float fMax, unsigned int nCount, Vec3* resultArray) const { const float fdx = 1.0f / float(nCount); float normX = 0.0f; for (unsigned int i = 0; i < nCount; ++i) { const float time = Lerp(fMin, fMax, normX); resultArray[i] = m_vars[id].GetInterpolatedAt(time); normX += fdx; } return true; } float CEnvironmentPreset::GetAnimTimeSecondsIn24h() { return sAnimTimeSecondsIn24h; } void CEnvironmentPreset::AddVar(const char* group, const char* displayName, const char* name, ITimeOfDay::ETimeOfDayParamID nParamId, ITimeOfDay::EVariableType type, float defVal0, float defVal1, float defVal2) { CTimeOfDayVariable& var = m_vars[nParamId]; var.Init(group, displayName, name, nParamId, type, defVal0, defVal1, defVal2); }
412
0.971535
1
0.971535
game-dev
MEDIA
0.638037
game-dev,graphics-rendering
0.889512
1
0.889512
Despector/Despector
6,269
src/main/java/org/spongepowered/despector/ast/SourceSet.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.ast; import static com.google.common.base.Preconditions.checkNotNull; import org.spongepowered.despector.Language; import org.spongepowered.despector.ast.type.EnumEntry; import org.spongepowered.despector.ast.type.InterfaceEntry; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.decompiler.Decompilers; import org.spongepowered.despector.util.serialization.AstSerializer; import org.spongepowered.despector.util.serialization.MessagePacker; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * A source set for types which are part of the obfuscated source being mapped. */ public class SourceSet { private Loader loader; private final Set<String> load_failed_cache = new HashSet<>(); private final Map<String, TypeEntry> classes = new HashMap<>(); private final Map<String, EnumEntry> enums = new HashMap<>(); private final Map<String, InterfaceEntry> interfaces = new HashMap<>(); private final Map<String, AnnotationType> annotations = new HashMap<>(); public SourceSet() { } public Loader getLoader() { return this.loader; } public void setLoader(Loader loader) { this.loader = loader; } /** * Inserts the given type into this source set. */ public void add(TypeEntry e) { checkNotNull(e); if (e instanceof EnumEntry) { this.enums.put(e.getName(), (EnumEntry) e); } else if (e instanceof InterfaceEntry) { this.interfaces.put(e.getName(), (InterfaceEntry) e); } this.classes.put(e.getName(), e); } /** * Gets the type with the given internal name. */ public TypeEntry get(String name) { checkNotNull(name); if (name.endsWith(";") || name.startsWith("[") || (name.length() == 1 && "BSIJFDCZ".indexOf(name.charAt(0)) != -1)) { throw new IllegalStateException(name + " is a descriptor not a type name"); } if (name.endsWith("[]")) { return get(name.substring(0, name.length() - 2)); } TypeEntry entry = this.classes.get(name); if (entry == null && this.loader != null && !this.load_failed_cache.contains(name)) { InputStream data = this.loader.find(name); if (data == null) { this.load_failed_cache.add(name); return null; } try { entry = Decompilers.get(Language.ANY).decompile(data, this); } catch (IOException e) { e.printStackTrace(); this.load_failed_cache.add(name); return null; } add(entry); } return entry; } public EnumEntry getEnum(String name) { EnumEntry entry = this.enums.get(name); return entry; } public InterfaceEntry getInterface(String name) { InterfaceEntry entry = this.interfaces.get(name); return entry; } /** * Gets all classes in the source set. This also includes all interfaces and * enums. */ public Collection<TypeEntry> getAllClasses() { return this.classes.values(); } /** * Gets all enum types in the source set. */ public Collection<EnumEntry> getAllEnums() { return this.enums.values(); } /** * Gets all interface types in the source set. */ public Collection<InterfaceEntry> getAllInterfaces() { return this.interfaces.values(); } public void addAnnotation(AnnotationType anno) { this.annotations.put(anno.getName(), anno); } /** * Gets the annotation type with the given internal name. */ public AnnotationType getAnnotationType(String name) { AnnotationType anno = this.annotations.get(name); if (anno == null) { anno = new AnnotationType(name); this.annotations.put(name, anno); } return anno; } public Collection<AnnotationType> getAllAnnotations() { return this.annotations.values(); } public void accept(AstVisitor visitor) { for (TypeEntry type : this.classes.values()) { type.accept(visitor); } } /** * Writes this source set to the given {@link MessagePacker}. */ public void writeTo(MessagePacker pack) throws IOException { pack.startMap(2); pack.writeString("version").writeInt(AstSerializer.VERSION); pack.writeString("classes"); pack.startArray(this.classes.size()); for (TypeEntry type : this.classes.values()) { type.writeTo(pack); } pack.endArray(); pack.endMap(); } /** * A loader which from which new types can be requested on demand. */ public static interface Loader { InputStream find(String name); } }
412
0.904362
1
0.904362
game-dev
MEDIA
0.450268
game-dev
0.990557
1
0.990557
cortex-command-community/Cortex-Command-Community-Project-Data
11,373
Data/Uzira.rte/Actors/Brains/Uzira/Uzira.lua
local setupMinionAIMode = function(self, minion) if self.minionsShouldGather then minion.AIMode = Actor.AIMODE_GOTO; minion:ClearMovePath(); minion:AddAIMOWaypoint(self); else minion.AIMode = Actor.AIMODE_SENTRY; local random = math.random(); if random < 0.25 then minion.AIMode = Actor.AIMODE_PATROL; elseif random < 0.35 then local target = MovableMan:GetClosestEnemyActor(minion.Team, self.Pos, self.enemySearchRadius, Vector()); if target then minion.AIMode = Actor.AIMODE_GOTO; minion:ClearMovePath(); minion:AddAIMOWaypoint(target); end elseif random < 0.45 then minion.AIMode = Actor.AIMODE_BRAINHUNT; end end end local handleMinionSpawning = function(self) if self.spawnTimer:IsPastSimTimeLimit() then self.spawnTimer:Reset(); self.spawnTimer:SetSimTimeLimitMS(self.baseSpawnTime); local funds = ActivityMan:GetActivity():GetTeamFunds(self.Team); local enemyCount = 0; if funds >= self.spawnCost or self.GoldCarried >= self.spawnCost then local spawnPos = self.Pos + Vector(0, self.Radius + RangeRand(0, self.spawnRadius)):RadRotate(RangeRand(-1, 1)); if SceneMan:CastMaxStrengthRay(self.Pos, spawnPos, 8) < self.spawnTerrainTolerance * 2 then local pointCount = 10; local radius = self.minionTemplate.Radius/math.sqrt(pointCount); local totalSurroundingTerrain = 0; local totalTolerance = self.spawnTerrainTolerance * pointCount; for i = 0, pointCount do local checkPos = spawnPos + Vector(math.sqrt(i) * radius, 0):RadRotate(i * 2.39996); local terrCheck = SceneMan:GetTerrMatter(checkPos.X, checkPos.Y); if terrCheck == rte.airID then totalSurroundingTerrain = totalSurroundingTerrain + self.spawnTerrainTolerance * 2; --Treat air as unsuitable terrain to spawn from else totalSurroundingTerrain = totalSurroundingTerrain + SceneMan:GetMaterialFromID(terrCheck).StructuralIntegrity; end if totalSurroundingTerrain > totalTolerance then break; end end if totalSurroundingTerrain < totalTolerance then local weapon = self.weapons[math.random(#self.weapons)]:Clone(); weapon.DeleteWhenRemovedFromParent = true; local newMinion = self.minionTemplate:Clone(); newMinion:AddInventoryItem(weapon); newMinion.Pos = spawnPos; newMinion.HFlipped = self.HFlipped; newMinion.RotAngle = RangeRand(-1.5, 1.5); self:setupMinionAIMode(newMinion); MovableMan:AddActor(newMinion); table.insert(self.minions, newMinion); if self.GoldCarried >= self.spawnCost then self.GoldCarried = self.GoldCarried - self.spawnCost; else ActivityMan:GetActivity():SetTeamFunds(funds - self.spawnCost, self.Team); end self.spawnTimer:SetSimTimeLimitMS(self.baseSpawnTime * #self.minions); local spawnSlice = self.minionManagementSubPieMenu:GetFirstPieSliceByPresetName(self.enableMinionSpawning and "DisableMinionSpawning" or "EnableMinionSpawning"); if spawnSlice then spawnSlice.Description = self.enableMinionSpawning and "Let the dead sleep..." or "Raise the living dead!"; end return; end end end if #self.minions == 0 and #self.frenziedMinions == 0 then local spawnSlice = self.minionManagementSubPieMenu:GetFirstPieSliceByPresetName(self.enableMinionSpawning and "DisableMinionSpawning" or "EnableMinionSpawning"); if spawnSlice then spawnSlice.Description = self.enableMinionSpawning and "From dust they came..." or "...To dust they return."; end end end end local cleanupDeadMinions = function(self) for i = 1, #self.minions do if not MovableMan:IsActor(self.minions[i]) or self.minions[i].Health <= 0 then table.remove(self.minions, i); end end for i = 1, #self.frenziedMinions do if not MovableMan:IsActor(self.frenziedMinions[i]) or self.frenziedMinions[i].Health <= 0 then table.remove(self.frenziedMinions, i); end end end local updateMinions = function(self) if self.updateMinionTimer:IsPastSimTimeLimit() then self.updateMinionTimer:Reset(); self:cleanupDeadMinions(); self.minionsFrenzyPieSlice.Enabled = false; local enemyCount = 0; for actor in MovableMan.Actors do if actor.Team ~= self.Team and actor.Team ~= Activity.NOTEAM and (actor.ClassName == "AHuman" or actor.ClassName == "ACrab") then enemyCount = enemyCount + 1; end end for i = 1, #self.minions do local minion = self.minions[i]; if SceneMan:ShortestDistance(self.Pos, minion.Pos, SceneMan.SceneWrapsX).Magnitude > self.minionDecayRadius then minion.Health = minion.Health - 1; for attachable in minion.Attachables do local smoke = CreateMOSParticle("Small Smoke Ball 1"); smoke.Pos = attachable.Pos; smoke.Lifetime = smoke.Lifetime * RangeRand(0.25, 1.5); MovableMan:AddParticle(smoke); if minion.Health < math.random(10) then minion:RemoveAttachable(attachable, true, true); if minion.Health > 0 then break; end end end if minion.Health <= 0 then ActivityMan:GetActivity():ReportDeath(minion.Team, -1); end end self.minionsFrenzyPieSlice.Enabled = true; if self.isAIControlled and #self.minions > enemyCount then self:SetNumberValue("MinionsFrenzy", 1); end end self:updateFrenziedMinions(); end if self:IsPlayerControlled() and self.HUDVisible then for _, minion in pairs(self.minions) do if minion.Age > 1000 then PrimitiveMan:DrawBitmapPrimitive(ActivityMan:GetActivity():ScreenOfPlayer(self:GetController().Player), minion.AboveHUDPos + Vector(0, math.sin(self.Age * 0.01) * 2 - 3), self.indicatorArrow, self.Team, 0, false, false); end end end end local updateFrenziedMinions = function(self) for i = 1, #self.frenziedMinions do local frenziedMinion = self.frenziedMinions[i]; local isBrainhunting = frenziedMinion.AIMode == Actor.AIMODE_BRAINHUNT; if math.random() < 0.25 then frenziedMinion.AIMode = isBrainhunting and Actor.AIMODE_GOTO or Actor.AIMODE_BRAINHUNT; isBrainhunting = not isBrainhunting; if not isBrainhunting then local target = MovableMan:GetClosestEnemyActor(frenziedMinion.Team, self.Pos, self.enemySearchRadius, Vector()); if target then frenziedMinion.AIMode = Actor.AIMODE_GOTO; frenziedMinion:AddAIMOWaypoint(target); else frenziedMinion.AIMode = Actor.AIMODE_BRAINHUNT; end end end if not isBrainhunting then if not frenziedMinion.MOMoveTarget or not MovableMan:IsActor(frenziedMinion.MOMoveTarget) then frenziedMinion.AIMode = Actor.AIMODE_BRAINHUNT; isBrainhunting = true; end end end end function Create(self) self.setupMinionAIMode = setupMinionAIMode; self.handleMinionSpawning = handleMinionSpawning; self.cleanupDeadMinions = cleanupDeadMinions; self.updateMinions = updateMinions; self.updateFrenziedMinions = updateFrenziedMinions; self.isAIControlled = not ActivityMan:GetActivity():PlayerHuman(self:GetController().Player); if self.isAIControlled then self.enableMinionSpawning = true; self:RemoveNumberValue("EnableNecromancy"); self.minionsShouldGather = false; self:RemoveNumberValue("MinionsGather"); end self.minionTemplate = CreateAHuman("Skeleton", "Uzira.rte"); self.minionTemplate.Team = self.Team; self.minionTemplate.HUDVisible = false; self.minionTemplate.PlayerControllable = false; self.minionTemplate.PinStrength = self.minionTemplate.Mass; self.minionTemplate:AddScript("Uzira.rte/Actors/Shared/Undead.lua"); self.weapons = {CreateHDFirearm("Blunderpop", "Uzira.rte"), CreateHDFirearm("Blunderbuss", "Uzira.rte"), CreateHDFirearm("Musket", "Uzira.rte"), CreateHDFirearm("Boomstick", "Uzira.rte"), CreateHDFirearm("Crossbow", "Uzira.rte")}; self.spawnRadius = math.max(FrameMan.PlayerScreenWidth, FrameMan.PlayerScreenHeight) * 0.1; self.minionDecayRadius = self.spawnRadius * 4 + self.minionTemplate.Radius; self.enemySearchRadius = self.minionDecayRadius; self.spawnTerrainTolerance = 70; self.spawnCost = self.minionTemplate:GetGoldValue(0, 1, 1); self.minions = {}; self.frenziedMinions = {}; self.spawnTimer = Timer(); self.baseSpawnTime = 750; self.spawnTimer:SetSimTimeLimitMS(self.baseSpawnTime); self.updateMinionTimer = Timer(); self.updateMinionTimer:SetSimTimeLimitMS(500); self.minionManagementSubPieMenu = self.PieMenu:GetFirstPieSliceByPresetName("MinionManagement").SubPieMenu; self.enableMinionSpawning = self:NumberValueExists("EnableMinionSpawning") and (self:GetNumberValue("EnableMinionSpawning") ~= 0) or true; self.minionManagementSubPieMenu:RemovePieSlicesByPresetName((self.enableMinionSpawning and "EnableMinionSpawning" or "DisableMinionSpawning")); self.minionsShouldGather = self:NumberValueExists("MinionsGather") and (self:GetNumberValue("MinionsGather") ~= 0) or false; self.minionManagementSubPieMenu:RemovePieSlicesByPresetName((self.minionsShouldGather and "MinionsGather" or "MinionsStandby")); self.minionsFrenzyPieSlice = self.minionManagementSubPieMenu:GetFirstPieSliceByPresetName("MinionsFrenzy"); self.minionsFrenzyPieSlice.Enabled = false; self.indicatorArrow = CreateMOSParticle("Indicator Arrow", "Uzira.rte"); end function Update(self) if self.isAIControlled and self:IsPlayerControlled() then self.isAIControlled = false; end if self:NumberValueExists("EnableMinionSpawning") then self.enableMinionSpawning = self:GetNumberValue("EnableMinionSpawning") ~= 0; self:RemoveNumberValue("EnableMinionSpawning"); local sliceNameToRemove = self.enableMinionSpawning and "EnableMinionSpawning" or "DisableMinionSpawning"; local sliceNameToAdd = self.enableMinionSpawning and "DisableMinionSpawning" or "EnableMinionSpawning"; self.minionManagementSubPieMenu:ReplacePieSlice(self.minionManagementSubPieMenu:GetFirstPieSliceByPresetName(sliceNameToRemove), CreatePieSlice(sliceNameToAdd, "Uzira.rte")); local newSlice = self.minionManagementSubPieMenu:GetFirstPieSliceByPresetName(sliceNameToAdd); if #self.minions == 0 and #self.frenziedMinions == 0 then newSlice.Description = self.enableMinionSpawning and "From dust they came..." or "...To dust they return."; else newSlice.Description = self.enableMinionSpawning and "Let the dead sleep..." or "Raise the living dead!"; end end if self:NumberValueExists("MinionsGather") then self.minionsShouldGather = self:GetNumberValue("MinionsGather") ~= 0; self:RemoveNumberValue("MinionsGather"); local sliceNameToRemove = self.minionsShouldGather and "MinionsGather" or "MinionsStandby"; local sliceNameToAdd = self.minionsShouldGather and "MinionsStandby" or "MinionsGather"; self.minionManagementSubPieMenu:ReplacePieSlice(self.minionManagementSubPieMenu:GetFirstPieSliceByPresetName(sliceNameToRemove), CreatePieSlice(sliceNameToAdd, "Uzira.rte")); self:cleanupDeadMinions(); for i = 1, #self.minions do self:setupMinionAIMode(self.minions[i]); end end if self:NumberValueExists("MinionsFrenzy") then self:RemoveNumberValue("MinionsFrenzy"); self:cleanupDeadMinions(); for i = 1, #self.minions do self.frenziedMinions[#self.frenziedMinions + 1] = self.minions[i]; end self.minions = {}; self:updateFrenziedMinions(); end if self.enableMinionSpawning then self:handleMinionSpawning(); else self.spawnTimer:Reset(); end self:updateMinions(); end
412
0.758102
1
0.758102
game-dev
MEDIA
0.99089
game-dev
0.924265
1
0.924265
lua9520/source-engine-2018-cstrike15_src
6,124
game/server/ai_speechfilter.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: An entity that can be used to control speech behaviour for a group // of NPCs. // //=============================================================================// #include "cbase.h" #include "ai_speechfilter.h" #ifndef CSTRIKE_DLL #include "ai_playerally.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" LINK_ENTITY_TO_CLASS( ai_speechfilter, CAI_SpeechFilter ); BEGIN_DATADESC( CAI_SpeechFilter ) DEFINE_KEYFIELD( m_iszSubject, FIELD_STRING, "subject" ), DEFINE_KEYFIELD( m_flIdleModifier, FIELD_FLOAT, "IdleModifier" ), DEFINE_KEYFIELD( m_bNeverSayHello, FIELD_BOOLEAN, "NeverSayHello" ), DEFINE_KEYFIELD( m_bDisabled, FIELD_BOOLEAN, "StartDisabled" ), DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ), DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ), DEFINE_INPUTFUNC( FIELD_FLOAT, "SetIdleModifier", InputSetIdleModifier ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CAI_SpeechFilter::Spawn( void ) { BaseClass::Spawn(); gEntList.AddListenerEntity( this ); } //----------------------------------------------------------------------------- // Purpose: Connect to all our NPCs //----------------------------------------------------------------------------- void CAI_SpeechFilter::Activate( void ) { BaseClass::Activate(); PopulateSubjectList( m_bDisabled ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CAI_SpeechFilter::UpdateOnRemove(void) { gEntList.RemoveListenerEntity( this ); BaseClass::UpdateOnRemove(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CAI_SpeechFilter::Enable( bool bEnable ) { m_bDisabled = !bEnable; PopulateSubjectList( m_bDisabled ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CAI_SpeechFilter::InputEnable( inputdata_t &inputdata ) { Enable( true ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CAI_SpeechFilter::InputDisable( inputdata_t &inputdata ) { Enable( false ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CAI_SpeechFilter::InputSetIdleModifier( inputdata_t &inputdata ) { m_flIdleModifier = inputdata.value.Float(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CAI_SpeechFilter::PopulateSubjectList( bool purge ) { // Populate the subject list. Try targetname first. CBaseEntity *pSearch = NULL; int iNumSubjects = 0; do { pSearch = gEntList.FindEntityByName( pSearch, m_iszSubject ); if ( pSearch ) { #ifndef CSTRIKE_DLL CAI_PlayerAlly *pAlly = dynamic_cast<CAI_PlayerAlly *>(pSearch); if ( pAlly ) { if( purge ) { pAlly->SetSpeechFilter( NULL ); } else { if( pAlly->GetSpeechFilter() != NULL ) { DevWarning("ai_speechfilter %s is slamming NPC %s's current speech filter.\n", STRING(GetEntityName()), STRING(pSearch->GetEntityName()) ); } pAlly->SetSpeechFilter( this ); } } else if ( pSearch->IsNPC() ) { DevWarning("ai_speechfilter %s tries to use %s as a subject, but it's not a talking NPC.\n", STRING(GetEntityName()), STRING(pSearch->GetEntityName()) ); } #endif iNumSubjects++; } } while( pSearch ); if ( !iNumSubjects ) { // No subjects found by targetname! Assume classname. do { pSearch = gEntList.FindEntityByClassname( pSearch, STRING(m_iszSubject) ); if( pSearch ) { #ifndef CSTRIKE_DLL CAI_PlayerAlly *pAlly = dynamic_cast<CAI_PlayerAlly *>(pSearch); if ( pAlly ) { if( purge ) { pAlly->SetSpeechFilter( NULL ); } else { if( pAlly->GetSpeechFilter() != NULL ) { DevWarning("ai_speechfilter %s is slamming NPC %s's current speech filter.\n", STRING(GetEntityName()), STRING(pSearch->GetEntityName()) ); } pAlly->SetSpeechFilter( this ); } } else if ( pSearch->IsNPC() ) { DevWarning("ai_speechfilter %s tries to use %s as a subject, but it's not a talking NPC.\n", STRING(GetEntityName()), STRING(pSearch->GetEntityName()) ); } #endif iNumSubjects++; } } while( pSearch ); } // If the subject list is still empty, we have an error! if ( !iNumSubjects ) { DevMsg( 2, "ai_speechfilter finds no subject(s) called: %s\n", STRING( m_iszSubject ) ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *pEntity - //----------------------------------------------------------------------------- void CAI_SpeechFilter::OnEntityCreated( CBaseEntity *pEntity ) { if ( !m_bDisabled && pEntity->NameMatches( m_iszSubject ) || pEntity->ClassMatches( m_iszSubject ) ) { #ifndef CSTRIKE_DLL CAI_PlayerAlly *pAlly = dynamic_cast<CAI_PlayerAlly *>(pEntity); if ( pAlly ) { pAlly->SetSpeechFilter( this ); } else if ( pEntity->IsNPC() ) { DevWarning("ai_speechfilter %s tries to use %s as a subject, but it's not a talking NPC.\n", STRING(GetEntityName()), STRING(pEntity->GetEntityName()) ); } #endif } } //----------------------------------------------------------------------------- // Purpose: // Input : *pEntity - //----------------------------------------------------------------------------- void CAI_SpeechFilter::OnEntityDeleted( CBaseEntity *pEntity ) { }
412
0.890474
1
0.890474
game-dev
MEDIA
0.943719
game-dev
0.933935
1
0.933935
volca02/openDarkEngine
3,313
src/services/room/Room.h
/****************************************************************************** * * This file is part of openDarkEngine project * Copyright (C) 2005-2009 openDarkEngine team * * 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 * * $Id$ * *****************************************************************************/ /** @file Room.h * @brief A single room in room database. */ #ifndef __ROOM_H #define __ROOM_H #include "Array.h" #include "File.h" #include "Plane.h" #include "Quaternion.h" #include "RoomCommon.h" #include "SharedPtr.h" #include "Vector3.h" #include "config.h" #include "integers.h" namespace Opde { /** @brief A single Room. Rooms are space bounded elements that are used * for sound propagation, path finding and as a script message sources. */ class Room { public: Room(RoomService *owner); ~Room(); void read(const FilePtr &sf); void write(const FilePtr &sf); int32_t getObjectID() const { return mObjectID; }; int16_t getRoomID() const { return mRoomID; }; bool isInside(const Vector3 &point); /** Gets portal for a given position * @param pos The position to find portal for * @return RoomPortal for the given point, or NULL if none found */ RoomPortal *getPortalForPoint(const Vector3 &pos); /** Attaches the given object to the room (into specified id set) * @param idset the id set to use (0/1 typically) * @param id the object id to attach */ void attachObj(size_t idset, int id); /** Detaches the given object from the room (into specified id set) * @param idset the id set to use (0/1 typically) * @param id the object id to detach */ void detachObj(size_t idset, int id); private: /// clears the room into an empty state, drops all allocations void clear(); /// Owner service RoomService *mOwner; /// Object ID int32_t mObjectID; /// Room number int16_t mRoomID; /// Center point of the room. Should not be in solid space or overlapping /// another room Vector3 mCenter; /// Bounding box as described by 6 enclosing planes Plane mPlanes[6]; /// Portal count uint32_t mPortalCount; /// Portal list SimpleArray<RoomPortal *> mPortals; /// Portal to portal distances (a 2d array, single index here for simplicity /// of allocations) float *mPortalDistances; typedef std::set<int> IDSet; typedef std::vector<IDSet> IDLists; /// lists of ID's IDLists mIDLists; }; /// Shared pointer to a room instance typedef shared_ptr<Room> RoomPtr; } // namespace Opde #endif
412
0.849901
1
0.849901
game-dev
MEDIA
0.167424
game-dev
0.518117
1
0.518117
ViaVersion/ViaFabricPlus
6,127
src/test/java/com/viaversion/viafabricplus/updater/UpdateTaskTest.java
/* * This file is part of ViaFabricPlus - https://github.com/ViaVersion/ViaFabricPlus * Copyright (C) 2021-2025 the original authors * - FlorianMichael/EnZaXD <florian.michael07@gmail.com> * - RK_01/RaphiMC * Copyright (C) 2023-2025 ViaVersion and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.viaversion.viafabricplus.updater; import com.viaversion.viafabricplus.features.item.filter_creative_tabs.VersionedRegistries; import com.viaversion.viafabricplus.protocoltranslator.impl.ViaFabricPlusMappingDataLoader; import com.viaversion.vialoader.util.VersionRange; import com.viaversion.viaversion.libs.gson.Gson; import com.viaversion.viaversion.libs.gson.GsonBuilder; import com.viaversion.viaversion.libs.gson.JsonObject; import java.io.FileWriter; import java.io.IOException; import net.lenni0451.reflect.stream.RStream; import net.minecraft.Bootstrap; import net.minecraft.GameVersion; import net.minecraft.SharedConstants; import net.minecraft.block.entity.BannerPatterns; import net.minecraft.enchantment.Enchantments; import net.minecraft.entity.effect.StatusEffect; import net.minecraft.item.Item; import net.minecraft.item.Items; import net.minecraft.registry.Registries; import net.minecraft.registry.RegistryKey; import net.minecraft.resource.PackVersion; import net.minecraft.resource.ResourceType; import org.junit.jupiter.api.Test; import static com.viaversion.viafabricplus.protocoltranslator.ProtocolTranslator.NATIVE_VERSION; public final class UpdateTaskTest { private static final Gson GSON = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); private static final String CURRENT_VERSION_RANGE = VersionRange.andNewer(NATIVE_VERSION).toString(); @Test public void update() { SharedConstants.createGameVersion(); Bootstrap.initialize(); if (SharedConstants.getProtocolVersion() != NATIVE_VERSION.getOriginalVersion()) { throw new UnsupportedOperationException("Please update ProtocolTranslator.NATIVE_VERSION to the current protocol version."); } updateVersionedRegistries(); updateResourcePacks(); } private static void updateVersionedRegistries() { final JsonObject data = ViaFabricPlusMappingDataLoader.INSTANCE.loadData("versioned-registries.json"); addMissingItems(data.getAsJsonObject("items")); addMissingEnchantments(data.getAsJsonObject("enchantments")); addMissingPatterns(data.getAsJsonObject("banner_patterns")); addMissingEffects(data.getAsJsonObject("effects")); UpdateTaskTest.write("versioned-registries.json", data); } private static void addMissingItems(final JsonObject items) { for (final Item item : Registries.ITEM) { if (VersionedRegistries.ITEM_DIFF.containsKey(item) || item == Items.AIR) { continue; } items.addProperty(Registries.ITEM.getId(item).toString(), CURRENT_VERSION_RANGE); } } private static void addMissingEnchantments(final JsonObject enchantments) { RStream.of(Enchantments.class).fields().forEach(fieldWrapper -> { final RegistryKey registryKey = fieldWrapper.get(); if (VersionedRegistries.ENCHANTMENT_DIFF.containsKey(registryKey)) { return; } enchantments.addProperty(registryKey.getValue().toString(), CURRENT_VERSION_RANGE); }); } private static void addMissingPatterns(final JsonObject patterns) { RStream.of(BannerPatterns.class).fields().forEach(fieldWrapper -> { final RegistryKey registryKey = fieldWrapper.get(); if (VersionedRegistries.PATTERN_DIFF.containsKey(registryKey)) { return; } patterns.addProperty(registryKey.getValue().toString(), CURRENT_VERSION_RANGE); }); } private static void addMissingEffects(final JsonObject effects) { for (final StatusEffect effect : Registries.STATUS_EFFECT) { if (VersionedRegistries.EFFECT_DIFF.containsKey(Registries.STATUS_EFFECT.getEntry(effect))) { continue; } effects.addProperty(Registries.STATUS_EFFECT.getId(effect).toString(), CURRENT_VERSION_RANGE); } } private static void updateResourcePacks() { final JsonObject data = ViaFabricPlusMappingDataLoader.INSTANCE.loadData("resource-pack-headers.json"); final GameVersion version = SharedConstants.getGameVersion(); if (data.has(version.name())) { return; } final PackVersion packVersion = version.packVersion(ResourceType.CLIENT_RESOURCES); final JsonObject packFormat = new JsonObject(); packFormat.addProperty("major", packVersion.major()); packFormat.addProperty("minor", packVersion.minor()); final JsonObject header = new JsonObject(); header.addProperty("version", version.protocolVersion()); header.add("pack_format", packFormat); data.add(version.name(), header); write("resource-pack-headers.json", data); } private static void write(final String name, final JsonObject data) { try (final FileWriter writer = new FileWriter("../src/main/resources/assets/viafabricplus/data/" + name)) { GSON.toJson(data, writer); } catch (IOException e) { throw new RuntimeException(e); } } }
412
0.90123
1
0.90123
game-dev
MEDIA
0.848558
game-dev
0.888409
1
0.888409
526077247/GenshinGamePlay
7,871
Assets/Scripts/Mono/Core/Object/LruCache.cs
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; using UnityEngine.UI; namespace TaoTie { public class LruCache<TKey, TValue>:IEnumerable<KeyValuePair<TKey, TValue>> { const int DEFAULT_CAPACITY = 255; int capacity; ReaderWriterLockSlim locker; Dictionary<TKey, TValue> dictionary; LinkedList<TKey> linkedList; Func<TKey, TValue, bool> checkCanPopFunc; Action<TKey, TValue> popCb; public LruCache() : this(DEFAULT_CAPACITY) { } public LruCache(int capacity) { locker = new ReaderWriterLockSlim(); this.capacity = capacity > 0 ? capacity : DEFAULT_CAPACITY; dictionary = new Dictionary<TKey, TValue>(DEFAULT_CAPACITY); linkedList = new LinkedList<TKey>(); } public void SetCheckCanPopCallback(Func<TKey,TValue, bool> func) { checkCanPopFunc = func; } public void SetPopCallback(Action<TKey, TValue> func) { popCb = func; } public TValue this[TKey t] { get { if(TryGet(t, out var res)) return res; throw new ArgumentException(); } set { Set(t, value); } } public void Set(TKey key, TValue value) { locker.EnterWriteLock(); try { if(checkCanPopFunc!=null) MakeFreeSpace(); dictionary[key] = value; linkedList.Remove(key); linkedList.AddFirst(key); if (checkCanPopFunc==null&&linkedList.Count > capacity) { dictionary.Remove(linkedList.Last.Value); linkedList.RemoveLast(); } } finally { locker.ExitWriteLock(); } } public Dictionary<TKey, TValue> GetAll() { return dictionary as Dictionary<TKey, TValue>; } public void Remove(TKey key) { locker.EnterWriteLock(); try { dictionary.Remove(key); linkedList.Remove(key); } finally { locker.ExitWriteLock(); } } public bool TryOnlyGet(TKey key, out TValue value) { bool b = dictionary.TryGetValue(key, out value); return b; } public bool TryGet(TKey key, out TValue value) { locker.EnterUpgradeableReadLock(); try { bool b = dictionary.TryGetValue(key, out value); if (b) { locker.EnterWriteLock(); try { linkedList.Remove(key); linkedList.AddFirst(key); } finally { locker.ExitWriteLock(); } } return b; } catch { throw; } finally { locker.ExitUpgradeableReadLock(); } } public bool ContainsKey(TKey key) { locker.EnterReadLock(); try { return dictionary.ContainsKey(key); } finally { locker.ExitReadLock(); } } public int Count { get { locker.EnterReadLock(); try { return dictionary.Count; } finally { locker.ExitReadLock(); } } } public int Capacity { get { locker.EnterReadLock(); try { return capacity; } finally { locker.ExitReadLock(); } } set { locker.EnterUpgradeableReadLock(); try { if (value > 0 && capacity != value) { locker.EnterWriteLock(); try { capacity = value; while (linkedList.Count > capacity) { linkedList.RemoveLast(); } } finally { locker.ExitWriteLock(); } } } finally { locker.ExitUpgradeableReadLock(); } } } public ICollection<TKey> Keys { get { locker.EnterReadLock(); try { return dictionary.Keys; } finally { locker.ExitReadLock(); } } } public ICollection<TValue> Values { get { locker.EnterReadLock(); try { return dictionary.Values; } finally { locker.ExitReadLock(); } } } //remotes elements to provide enough memory //returns last removed element or nil void MakeFreeSpace() { var key = linkedList.Last; var max_check_free_times = 10;// max check free times for avoid no tuple can free cause iterator much times; var curCheckFreeTime = 0; while(linkedList.Count + 1 > DEFAULT_CAPACITY){ if (key==null) break; var tuple_prev = key.Previous; if (checkCanPopFunc == null || checkCanPopFunc(key.Value, dictionary[key.Value])) { //can pop var value = dictionary[key.Value]; dictionary.Remove(key.Value); linkedList.Remove(key.Value); popCb?.Invoke(key.Value, value); } else { //the host say cannot pop curCheckFreeTime ++; if (curCheckFreeTime > max_check_free_times) { //lru cache detect check_free time is too much, please check code break; } } key = tuple_prev; } } public void CleanUp() { var key = linkedList.Last; int count = linkedList.Count; while(count > 0) { count--; var tuple_prev = key.Previous; if (checkCanPopFunc == null || checkCanPopFunc(key.Value, dictionary[key.Value])) { //can pop var value = dictionary[key.Value]; dictionary.Remove(key.Value); linkedList.Remove(key.Value); popCb?.Invoke(key.Value, value); } key = tuple_prev; } } public void Clear() { dictionary.Clear(); linkedList.Clear(); } IEnumerator IEnumerable.GetEnumerator() { foreach (var item in dictionary) { yield return item; } } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { foreach (var item in dictionary) { yield return item; } } } }
412
0.863861
1
0.863861
game-dev
MEDIA
0.239311
game-dev
0.973756
1
0.973756
DaFuqs/Spectrum
1,640
src/main/java/de/dafuqs/spectrum/networking/c2s_payloads/BindEnderSpliceToPlayerPayload.java
package de.dafuqs.spectrum.networking.c2s_payloads; import de.dafuqs.spectrum.items.magic_items.*; import de.dafuqs.spectrum.networking.*; import de.dafuqs.spectrum.registries.*; import net.fabricmc.fabric.api.networking.v1.*; import net.minecraft.network.*; import net.minecraft.network.codec.*; import net.minecraft.network.protocol.common.custom.*; import net.minecraft.server.level.*; import net.minecraft.world.entity.*; public record BindEnderSpliceToPlayerPayload(int entityId) implements CustomPacketPayload { public static final Type<BindEnderSpliceToPlayerPayload> ID = SpectrumC2SPackets.makeId("bind_ender_splice_to_player"); public static final StreamCodec<FriendlyByteBuf, BindEnderSpliceToPlayerPayload> CODEC = StreamCodec.composite(ByteBufCodecs.INT, BindEnderSpliceToPlayerPayload::entityId, BindEnderSpliceToPlayerPayload::new); @Override public Type<? extends CustomPacketPayload> type() { return ID; } public static ServerPlayNetworking.PlayPayloadHandler<BindEnderSpliceToPlayerPayload> getPayloadHandler() { return (payload, context) -> { ServerPlayer player = context.player(); Entity entity = player.level().getEntity(payload.entityId()); if (entity instanceof ServerPlayer targetPlayerEntity && player.distanceTo(targetPlayerEntity) < 8 && player.getMainHandItem().is(SpectrumItems.ENDER_SPLICE)) { EnderSpliceItem.setTeleportTargetPlayer(player.getMainHandItem(), targetPlayerEntity); player.playSound(SpectrumSoundEvents.ENDER_SPLICE_BOUND, 1.0F, 1.0F); targetPlayerEntity.playSound(SpectrumSoundEvents.ENDER_SPLICE_BOUND, 1.0F, 1.0F); } }; } }
412
0.858283
1
0.858283
game-dev
MEDIA
0.98277
game-dev,networking
0.804814
1
0.804814
StevenBaby/onix
3,403
src/kernel/arena.c
#include <onix/arena.h> #include <onix/memory.h> #include <onix/string.h> #include <onix/stdlib.h> #include <onix/assert.h> #define BUF_COUNT 4 // 堆内存缓存页数量 extern u32 free_pages; static arena_descriptor_t descriptors[DESC_COUNT]; // arena 初始化 void arena_init() { u32 block_size = 16; for (size_t i = 0; i < DESC_COUNT; i++) { arena_descriptor_t *desc = &descriptors[i]; desc->block_size = block_size; desc->total_block = (PAGE_SIZE - sizeof(arena_t)) / block_size; desc->page_count = 0; list_init(&desc->free_list); block_size <<= 1; // block *= 2; } } // 获得 arena 第 idx 块内存指针 static void *get_arena_block(arena_t *arena, u32 idx) { assert(arena->desc->total_block > idx); void *addr = (void *)(arena + 1); u32 gap = idx * arena->desc->block_size; return addr + gap; } static arena_t *get_block_arena(block_t *block) { return (arena_t *)((u32)block & 0xfffff000); } void *kmalloc(size_t size) { arena_descriptor_t *desc = NULL; arena_t *arena; block_t *block; char *addr; if (size > 1024) { u32 asize = size + sizeof(arena_t); u32 count = div_round_up(asize, PAGE_SIZE); arena = (arena_t *)alloc_kpage(count); memset(arena, 0, count * PAGE_SIZE); arena->large = true; arena->count = count; arena->desc = NULL; arena->magic = ONIX_MAGIC; addr = (char *)((u32)arena + sizeof(arena_t)); return addr; } for (size_t i = 0; i < DESC_COUNT; i++) { desc = &descriptors[i]; if (desc->block_size >= size) break; } assert(desc != NULL); if (list_empty(&desc->free_list)) { arena = (arena_t *)alloc_kpage(1); memset(arena, 0, PAGE_SIZE); desc->page_count++; arena->desc = desc; arena->large = false; arena->count = desc->total_block; arena->magic = ONIX_MAGIC; for (size_t i = 0; i < desc->total_block; i++) { block = get_arena_block(arena, i); assert(!list_search(&arena->desc->free_list, block)); list_push(&arena->desc->free_list, block); assert(list_search(&arena->desc->free_list, block)); } } block = list_pop(&desc->free_list); arena = get_block_arena(block); assert(arena->magic == ONIX_MAGIC && !arena->large); // memset(block, 0, desc->block_size); arena->count--; return block; } void kfree(void *ptr) { assert(ptr); block_t *block = (block_t *)ptr; arena_t *arena = get_block_arena(block); assert(arena->large == 1 || arena->large == 0); assert(arena->magic == ONIX_MAGIC); if (arena->large) { free_kpage((u32)arena, arena->count); return; } list_push(&arena->desc->free_list, block); arena->count++; if (arena->count == arena->desc->total_block && arena->desc->page_count > BUF_COUNT) { for (size_t i = 0; i < arena->desc->total_block; i++) { block = get_arena_block(arena, i); assert(list_search(&arena->desc->free_list, block)); list_remove(block); assert(!list_search(&arena->desc->free_list, block)); } arena->desc->page_count--; assert(arena->desc->page_count >= BUF_COUNT); free_kpage((u32)arena, 1); } }
412
0.790745
1
0.790745
game-dev
MEDIA
0.647681
game-dev
0.780201
1
0.780201
drodin/Stratagus
4,293
src/animation/animation_spawnunit.cpp
// _________ __ __ // / _____// |_____________ _/ |______ ____ __ __ ______ // \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/ // / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ | // /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ > // \/ \/ \//_____/ \/ // ______________________ ______________________ // T H E W A R B E G I N S // Stratagus - A free fantasy real time strategy game engine // /**@name animation_spawnunit.cpp - The animation SpawnUnit. */ // // (c) Copyright 2012 by Joris Dauphin // // 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; only version 2 of the 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 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. // //@{ /*---------------------------------------------------------------------------- -- Includes ----------------------------------------------------------------------------*/ #include "stratagus.h" #include "animation/animation_spawnunit.h" #include "../ai/ai_local.h" #include "commands.h" #include "map.h" #include "unit.h" /* virtual */ void CAnimation_SpawnUnit::Action(CUnit &unit, int &/*move*/, int /*scale*/) const { Assert(unit.Anim.Anim == this); const int offX = ParseAnimInt(unit, this->offXStr.c_str()); const int offY = ParseAnimInt(unit, this->offYStr.c_str()); const int range = ParseAnimInt(unit, this->rangeStr.c_str()); const int playerId = ParseAnimInt(unit, this->playerStr.c_str()); const SpawnUnit_Flags flags = (SpawnUnit_Flags)(ParseAnimFlags(unit, this->flagsStr.c_str())); CPlayer &player = Players[playerId]; const Vec2i pos(unit.tilePos.x + offX, unit.tilePos.y + offY); CUnitType *type = UnitTypeByIdent(this->unitTypeStr.c_str()); Assert(type); Vec2i resPos; DebugPrint("Creating a %s\n" _C_ type->Name.c_str()); FindNearestDrop(*type, pos, resPos, LookingW); if (SquareDistance(pos, resPos) <= square(range)) { CUnit *target = MakeUnit(*type, &player); if (target != NULL) { target->tilePos = resPos; target->Place(resPos); if (flags & SU_Summoned) { target->Summoned = GameCycle + 1; } if ((flags & SU_JoinToAIForce) && unit.Player->AiEnabled) { int force = unit.Player->Ai->Force.GetForce(unit); if (force != -1) { unit.Player->Ai->Force[force].Insert(*target); target->GroupId = unit.GroupId; CommandDefend(*target, unit, FlushCommands); } } //DropOutOnSide(*target, LookingW, NULL); } else { DebugPrint("Unable to allocate Unit"); } } } /* ** s = "unitType offX offY range player [flags]" */ /* virtual */ void CAnimation_SpawnUnit::Init(const char *s, lua_State *) { const std::string str(s); const size_t len = str.size(); size_t begin = 0; size_t end = str.find(' ', begin); this->unitTypeStr.assign(str, begin, end - begin); begin = std::min(len, str.find_first_not_of(' ', end)); end = std::min(len, str.find(' ', begin)); this->offXStr.assign(str, begin, end - begin); begin = std::min(len, str.find_first_not_of(' ', end)); end = std::min(len, str.find(' ', begin)); this->offYStr.assign(str, begin, end - begin); begin = std::min(len, str.find_first_not_of(' ', end)); end = std::min(len, str.find(' ', begin)); this->rangeStr.assign(str, begin, end - begin); begin = std::min(len, str.find_first_not_of(' ', end)); end = std::min(len, str.find(' ', begin)); this->playerStr.assign(str, begin, end - begin); begin = std::min(len, str.find_first_not_of(' ', end)); end = std::min(len, str.find(' ', begin)); if (begin != end) { this->flagsStr.assign(str, begin, end - begin); } } //@}
412
0.75314
1
0.75314
game-dev
MEDIA
0.910035
game-dev
0.941604
1
0.941604
magefree/mage
1,712
Mage.Sets/src/mage/cards/t/ThermalDetonator.java
package mage.cards.t; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.SacrificeSourceCost; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.DamageTargetEffect; import mage.abilities.keyword.SpaceflightAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.filter.common.FilterCreatureOrPlayer; import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.AbilityPredicate; import mage.target.common.TargetPermanentOrPlayer; import java.util.UUID; /** * @author NinthWorld */ public final class ThermalDetonator extends CardImpl { private static final FilterCreatureOrPlayer filter = new FilterCreatureOrPlayer("creature without spaceflight or target player"); static { filter.getPermanentFilter().add(Predicates.not(new AbilityPredicate(SpaceflightAbility.class))); } public ThermalDetonator(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{1}"); // {2}, Sacrifice Thermal Detonator: Thermal Detonator deals 2 damage to target creature without spaceflight or target player. Ability ability = new SimpleActivatedAbility(new DamageTargetEffect(2), new ManaCostsImpl<>("{2}")); ability.addCost(new SacrificeSourceCost()); ability.addTarget(new TargetPermanentOrPlayer(filter)); this.addAbility(ability); } private ThermalDetonator(final ThermalDetonator card) { super(card); } @Override public ThermalDetonator copy() { return new ThermalDetonator(this); } }
412
0.938007
1
0.938007
game-dev
MEDIA
0.985243
game-dev
0.975277
1
0.975277
exmex/KingdomRushFrontiers
9,243
cocos2d/external/Box2D/include/Box2D/Dynamics/b2Fixture.h
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_FIXTURE_H #define B2_FIXTURE_H #include "Box2D/Dynamics/b2Body.h" #include "Box2D/Collision/b2Collision.h" #include "Box2D/Collision/Shapes/b2Shape.h" class b2BlockAllocator; class b2Body; class b2BroadPhase; class b2Fixture; /// This holds contact filtering data. struct b2Filter { b2Filter() { categoryBits = 0x0001; maskBits = 0xFFFF; groupIndex = 0; } /// The collision category bits. Normally you would just set one bit. uint16 categoryBits; /// The collision mask bits. This states the categories that this /// shape would accept for collision. uint16 maskBits; /// Collision groups allow a certain group of objects to never collide (negative) /// or always collide (positive). Zero means no collision group. Non-zero group /// filtering always wins against the mask bits. int16 groupIndex; }; /// A fixture definition is used to create a fixture. This class defines an /// abstract fixture definition. You can reuse fixture definitions safely. struct b2FixtureDef { /// The constructor sets the default fixture definition values. b2FixtureDef() { shape = nullptr; userData = nullptr; friction = 0.2f; restitution = 0.0f; density = 0.0f; isSensor = false; } /// The shape, this must be set. The shape will be cloned, so you /// can create the shape on the stack. const b2Shape* shape; /// Use this to store application specific fixture data. void* userData; /// The friction coefficient, usually in the range [0,1]. float32 friction; /// The restitution (elasticity) usually in the range [0,1]. float32 restitution; /// The density, usually in kg/m^2. float32 density; /// A sensor shape collects contact information but never generates a collision /// response. bool isSensor; /// Contact filtering data. b2Filter filter; }; /// This proxy is used internally to connect fixtures to the broad-phase. struct b2FixtureProxy { b2AABB aabb; b2Fixture* fixture; int32 childIndex; int32 proxyId; }; /// A fixture is used to attach a shape to a body for collision detection. A fixture /// inherits its transform from its parent. Fixtures hold additional non-geometric data /// such as friction, collision filters, etc. /// Fixtures are created via b2Body::CreateFixture. /// @warning you cannot reuse fixtures. class b2Fixture { public: /// Get the type of the child shape. You can use this to down cast to the concrete shape. /// @return the shape type. b2Shape::Type GetType() const; /// Get the child shape. You can modify the child shape, however you should not change the /// number of vertices because this will crash some collision caching mechanisms. /// Manipulating the shape may lead to non-physical behavior. b2Shape* GetShape(); const b2Shape* GetShape() const; /// Set if this fixture is a sensor. void SetSensor(bool sensor); /// Is this fixture a sensor (non-solid)? /// @return the true if the shape is a sensor. bool IsSensor() const; /// Set the contact filtering data. This will not update contacts until the next time /// step when either parent body is active and awake. /// This automatically calls Refilter. void SetFilterData(const b2Filter& filter); /// Get the contact filtering data. const b2Filter& GetFilterData() const; /// Call this if you want to establish collision that was previously disabled by b2ContactFilter::ShouldCollide. void Refilter(); /// Get the parent body of this fixture. This is nullptr if the fixture is not attached. /// @return the parent body. b2Body* GetBody(); const b2Body* GetBody() const; /// Get the next fixture in the parent body's fixture list. /// @return the next shape. b2Fixture* GetNext(); const b2Fixture* GetNext() const; /// Get the user data that was assigned in the fixture definition. Use this to /// store your application specific data. void* GetUserData() const; /// Set the user data. Use this to store your application specific data. void SetUserData(void* data); /// Test a point for containment in this fixture. /// @param p a point in world coordinates. bool TestPoint(const b2Vec2& p) const; /// Cast a ray against this shape. /// @param output the ray-cast results. /// @param input the ray-cast input parameters. bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const; /// Get the mass data for this fixture. The mass data is based on the density and /// the shape. The rotational inertia is about the shape's origin. This operation /// may be expensive. void GetMassData(b2MassData* massData) const; /// Set the density of this fixture. This will _not_ automatically adjust the mass /// of the body. You must call b2Body::ResetMassData to update the body's mass. void SetDensity(float32 density); /// Get the density of this fixture. float32 GetDensity() const; /// Get the coefficient of friction. float32 GetFriction() const; /// Set the coefficient of friction. This will _not_ change the friction of /// existing contacts. void SetFriction(float32 friction); /// Get the coefficient of restitution. float32 GetRestitution() const; /// Set the coefficient of restitution. This will _not_ change the restitution of /// existing contacts. void SetRestitution(float32 restitution); /// Get the fixture's AABB. This AABB may be enlarge and/or stale. /// If you need a more accurate AABB, compute it using the shape and /// the body transform. const b2AABB& GetAABB(int32 childIndex) const; /// Dump this fixture to the log file. void Dump(int32 bodyIndex); protected: friend class b2Body; friend class b2World; friend class b2Contact; friend class b2ContactManager; b2Fixture(); // We need separation create/destroy functions from the constructor/destructor because // the destructor cannot access the allocator (no destructor arguments allowed by C++). void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def); void Destroy(b2BlockAllocator* allocator); // These support body activation/deactivation. void CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf); void DestroyProxies(b2BroadPhase* broadPhase); void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2); float32 m_density; b2Fixture* m_next; b2Body* m_body; b2Shape* m_shape; float32 m_friction; float32 m_restitution; b2FixtureProxy* m_proxies; int32 m_proxyCount; b2Filter m_filter; bool m_isSensor; void* m_userData; }; inline b2Shape::Type b2Fixture::GetType() const { return m_shape->GetType(); } inline b2Shape* b2Fixture::GetShape() { return m_shape; } inline const b2Shape* b2Fixture::GetShape() const { return m_shape; } inline bool b2Fixture::IsSensor() const { return m_isSensor; } inline const b2Filter& b2Fixture::GetFilterData() const { return m_filter; } inline void* b2Fixture::GetUserData() const { return m_userData; } inline void b2Fixture::SetUserData(void* data) { m_userData = data; } inline b2Body* b2Fixture::GetBody() { return m_body; } inline const b2Body* b2Fixture::GetBody() const { return m_body; } inline b2Fixture* b2Fixture::GetNext() { return m_next; } inline const b2Fixture* b2Fixture::GetNext() const { return m_next; } inline void b2Fixture::SetDensity(float32 density) { b2Assert(b2IsValid(density) && density >= 0.0f); m_density = density; } inline float32 b2Fixture::GetDensity() const { return m_density; } inline float32 b2Fixture::GetFriction() const { return m_friction; } inline void b2Fixture::SetFriction(float32 friction) { m_friction = friction; } inline float32 b2Fixture::GetRestitution() const { return m_restitution; } inline void b2Fixture::SetRestitution(float32 restitution) { m_restitution = restitution; } inline bool b2Fixture::TestPoint(const b2Vec2& p) const { return m_shape->TestPoint(m_body->GetTransform(), p); } inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const { return m_shape->RayCast(output, input, m_body->GetTransform(), childIndex); } inline void b2Fixture::GetMassData(b2MassData* massData) const { m_shape->ComputeMass(massData, m_density); } inline const b2AABB& b2Fixture::GetAABB(int32 childIndex) const { b2Assert(0 <= childIndex && childIndex < m_proxyCount); return m_proxies[childIndex].aabb; } #endif
412
0.958135
1
0.958135
game-dev
MEDIA
0.573579
game-dev,graphics-rendering
0.870232
1
0.870232
PulseBeat02/MurderRun
2,147
src/main/java/me/brandonli/murderrun/locale/minimessage/ArgumentTag.java
/* * This file is part of Murder Run, a spin-off game-mode of Dead by Daylight * Copyright (C) Brandon Li <https://brandonli.me/> * * 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 <https://www.gnu.org/licenses/>. */ package me.brandonli.murderrun.locale.minimessage; import java.util.List; import java.util.OptionalInt; import net.kyori.adventure.text.ComponentLike; import net.kyori.adventure.text.minimessage.Context; import net.kyori.adventure.text.minimessage.ParsingException; import net.kyori.adventure.text.minimessage.tag.Tag; import net.kyori.adventure.text.minimessage.tag.Tag.Argument; import net.kyori.adventure.text.minimessage.tag.resolver.ArgumentQueue; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import org.checkerframework.checker.nullness.qual.NonNull; public final class ArgumentTag implements TagResolver { private static final String NAME = "arg"; private final List<? extends ComponentLike> argumentComponents; public ArgumentTag(final List<? extends ComponentLike> argumentComponents) { this.argumentComponents = argumentComponents; } @Override public Tag resolve(final @NonNull String name, final ArgumentQueue arguments, final @NonNull Context ctx) throws ParsingException { final Argument pop = arguments.pop(); final OptionalInt optional = pop.asInt(); final int index = optional.orElseThrow(); final ComponentLike like = this.argumentComponents.get(index); return Tag.inserting(like); } @Override public boolean has(final String name) { return name.equals(NAME); } }
412
0.541679
1
0.541679
game-dev
MEDIA
0.758604
game-dev
0.760977
1
0.760977
GaijinEntertainment/DagorEngine
8,631
prog/3rdPartyLibs/phys/bullet-3/src/BulletSoftBody/btSparseSDF.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ ///btSparseSdf implementation by Nathanael Presson #ifndef BT_SPARSE_SDF_H #define BT_SPARSE_SDF_H #include "BulletCollision/CollisionDispatch/btCollisionObject.h" #include "BulletCollision/NarrowPhaseCollision/btGjkEpa2.h" // Fast Hash #if !defined(get16bits) #define get16bits(d) ((((unsigned int)(((const unsigned char*)(d))[1])) << 8) + (unsigned int)(((const unsigned char*)(d))[0])) #endif // // super hash function by Paul Hsieh // inline unsigned int HsiehHash(const char* data, int len) { unsigned int hash = len, tmp; len >>= 2; /* Main loop */ for (; len > 0; len--) { hash += get16bits(data); tmp = (get16bits(data + 2) << 11) ^ hash; hash = (hash << 16) ^ tmp; data += 2 * sizeof(unsigned short); hash += hash >> 11; } /* Force "avalanching" of final 127 bits */ hash ^= hash << 3; hash += hash >> 5; hash ^= hash << 4; hash += hash >> 17; hash ^= hash << 25; hash += hash >> 6; return hash; } template <const int CELLSIZE> struct btSparseSdf { // // Inner types // struct IntFrac { int b; int i; btScalar f; }; struct Cell { btScalar d[CELLSIZE + 1][CELLSIZE + 1][CELLSIZE + 1]; int c[3]; int puid; unsigned hash; const btCollisionShape* pclient; Cell* next; }; // // Fields // btAlignedObjectArray<Cell*> cells; btScalar voxelsz; btScalar m_defaultVoxelsz; int puid; int ncells; int m_clampCells; int nprobes; int nqueries; ~btSparseSdf() { Reset(); } // // Methods // // void Initialize(int hashsize = 2383, int clampCells = 256 * 1024) { //avoid a crash due to running out of memory, so clamp the maximum number of cells allocated //if this limit is reached, the SDF is reset (at the cost of some performance during the reset) m_clampCells = clampCells; cells.resize(hashsize, 0); m_defaultVoxelsz = 0.25; Reset(); } // void setDefaultVoxelsz(btScalar sz) { m_defaultVoxelsz = sz; } void Reset() { for (int i = 0, ni = cells.size(); i < ni; ++i) { Cell* pc = cells[i]; cells[i] = 0; while (pc) { Cell* pn = pc->next; delete pc; pc = pn; } } voxelsz = m_defaultVoxelsz; puid = 0; ncells = 0; nprobes = 1; nqueries = 1; } // void GarbageCollect(int lifetime = 256) { const int life = puid - lifetime; for (int i = 0; i < cells.size(); ++i) { Cell*& root = cells[i]; Cell* pp = 0; Cell* pc = root; while (pc) { Cell* pn = pc->next; if (pc->puid < life) { if (pp) pp->next = pn; else root = pn; delete pc; pc = pp; --ncells; } pp = pc; pc = pn; } } //printf("GC[%d]: %d cells, PpQ: %f\r\n",puid,ncells,nprobes/(btScalar)nqueries); nqueries = 1; nprobes = 1; ++puid; ///@todo: Reset puid's when int range limit is reached */ /* else setup a priority list... */ } // int RemoveReferences(btCollisionShape* pcs) { int refcount = 0; for (int i = 0; i < cells.size(); ++i) { Cell*& root = cells[i]; Cell* pp = 0; Cell* pc = root; while (pc) { Cell* pn = pc->next; if (pc->pclient == pcs) { if (pp) pp->next = pn; else root = pn; delete pc; pc = pp; ++refcount; } pp = pc; pc = pn; } } return (refcount); } // btScalar Evaluate(const btVector3& x, const btCollisionShape* shape, btVector3& normal, btScalar margin) { /* Lookup cell */ const btVector3 scx = x / voxelsz; const IntFrac ix = Decompose(scx.x()); const IntFrac iy = Decompose(scx.y()); const IntFrac iz = Decompose(scx.z()); const unsigned h = Hash(ix.b, iy.b, iz.b, shape); Cell*& root = cells[static_cast<int>(h % cells.size())]; Cell* c = root; ++nqueries; while (c) { ++nprobes; if ((c->hash == h) && (c->c[0] == ix.b) && (c->c[1] == iy.b) && (c->c[2] == iz.b) && (c->pclient == shape)) { break; } else { // printf("c->hash/c[0][1][2]=%d,%d,%d,%d\n", c->hash, c->c[0], c->c[1],c->c[2]); //printf("h,ixb,iyb,izb=%d,%d,%d,%d\n", h,ix.b, iy.b, iz.b); c = c->next; } } if (!c) { ++nprobes; ++ncells; //int sz = sizeof(Cell); if (ncells > m_clampCells) { //static int numResets = 0; //numResets++; //printf("numResets=%d\n",numResets); Reset(); } c = new Cell(); c->next = root; root = c; c->pclient = shape; c->hash = h; c->c[0] = ix.b; c->c[1] = iy.b; c->c[2] = iz.b; BuildCell(*c); } c->puid = puid; /* Extract infos */ const int o[] = {ix.i, iy.i, iz.i}; const btScalar d[] = {c->d[o[0] + 0][o[1] + 0][o[2] + 0], c->d[o[0] + 1][o[1] + 0][o[2] + 0], c->d[o[0] + 1][o[1] + 1][o[2] + 0], c->d[o[0] + 0][o[1] + 1][o[2] + 0], c->d[o[0] + 0][o[1] + 0][o[2] + 1], c->d[o[0] + 1][o[1] + 0][o[2] + 1], c->d[o[0] + 1][o[1] + 1][o[2] + 1], c->d[o[0] + 0][o[1] + 1][o[2] + 1]}; /* Normal */ #if 1 const btScalar gx[] = {d[1] - d[0], d[2] - d[3], d[5] - d[4], d[6] - d[7]}; const btScalar gy[] = {d[3] - d[0], d[2] - d[1], d[7] - d[4], d[6] - d[5]}; const btScalar gz[] = {d[4] - d[0], d[5] - d[1], d[7] - d[3], d[6] - d[2]}; normal.setX(Lerp(Lerp(gx[0], gx[1], iy.f), Lerp(gx[2], gx[3], iy.f), iz.f)); normal.setY(Lerp(Lerp(gy[0], gy[1], ix.f), Lerp(gy[2], gy[3], ix.f), iz.f)); normal.setZ(Lerp(Lerp(gz[0], gz[1], ix.f), Lerp(gz[2], gz[3], ix.f), iy.f)); normal.safeNormalize(); #else normal = btVector3(d[1] - d[0], d[3] - d[0], d[4] - d[0]).normalized(); #endif /* Distance */ const btScalar d0 = Lerp(Lerp(d[0], d[1], ix.f), Lerp(d[3], d[2], ix.f), iy.f); const btScalar d1 = Lerp(Lerp(d[4], d[5], ix.f), Lerp(d[7], d[6], ix.f), iy.f); return (Lerp(d0, d1, iz.f) - margin); } // void BuildCell(Cell& c) { const btVector3 org = btVector3((btScalar)c.c[0], (btScalar)c.c[1], (btScalar)c.c[2]) * CELLSIZE * voxelsz; for (int k = 0; k <= CELLSIZE; ++k) { const btScalar z = voxelsz * k + org.z(); for (int j = 0; j <= CELLSIZE; ++j) { const btScalar y = voxelsz * j + org.y(); for (int i = 0; i <= CELLSIZE; ++i) { const btScalar x = voxelsz * i + org.x(); c.d[i][j][k] = DistanceToShape(btVector3(x, y, z), c.pclient); } } } } // static inline btScalar DistanceToShape(const btVector3& x, const btCollisionShape* shape) { btTransform unit; unit.setIdentity(); if (shape->isConvex()) { btGjkEpaSolver2::sResults res; const btConvexShape* csh = static_cast<const btConvexShape*>(shape); return (btGjkEpaSolver2::SignedDistance(x, 0, csh, unit, res)); } return (0); } // static inline IntFrac Decompose(btScalar x) { /* That one need a lot of improvements... */ /* Remove test, faster floor... */ IntFrac r; x /= CELLSIZE; const int o = x < 0 ? (int)(-x + 1) : 0; x += o; r.b = (int)x; const btScalar k = (x - r.b) * CELLSIZE; r.i = (int)k; r.f = k - r.i; r.b -= o; return (r); } // static inline btScalar Lerp(btScalar a, btScalar b, btScalar t) { return (a + (b - a) * t); } // static inline unsigned int Hash(int x, int y, int z, const btCollisionShape* shape) { struct btS { int x, y, z, w; void* p; }; btS myset; //memset may be needed in case of additional (uninitialized) padding! //memset(&myset, 0, sizeof(btS)); myset.x = x; myset.y = y; myset.z = z; myset.w = 0; myset.p = (void*)shape; const char* ptr = (const char*)&myset; unsigned int result = HsiehHash(ptr, sizeof(btS)); return result; } }; #endif //BT_SPARSE_SDF_H
412
0.989437
1
0.989437
game-dev
MEDIA
0.670282
game-dev
0.992375
1
0.992375
curioswitch/curiostack
2,851
cafe-map/client/unity/Assets/GoogleMaps/Examples/SharedAssets/Scripts/InstructionsHandler.cs
using UnityEngine; using UnityEngine.Assertions; using UnityEngine.UI; namespace Google.Maps.Examples.Shared { /// <summary> /// This class controls the behavior of the instructions panel. /// It also adjusts the instructions displayed on screen based on the platform where /// the example is running. /// /// The Instructions component has two states controlled by the help button. /// When the button is clicked on, the instruction dialog is displayed, /// and The help button is disabled. /// When the dialog is closed, we re-activate the help button. /// /// This approach optimizes the UI real estate for the example. /// /// </summary> public class InstructionsHandler : MonoBehaviour { /// <summary> /// Information text adjusted depending on deployed platform. /// </summary> public Text InstructionsText; /// <summary> /// Dialog box controlled by the help button. /// </summary> public GameObject InstructionsDialog; /// <summary> /// Reference to Help button. /// </summary> public GameObject HelpButton; /// <summary> /// Glass panel used to block events when dialog is on. /// </summary> public GameObject GlassPanel; /// <summary> /// At start, update the instructions text based on the target platform, /// and hide the Instructions Dialog. /// </summary> private void Start() { Assert.IsNotNull(InstructionsText, "Instructions Text is not set!"); Assert.IsNotNull(InstructionsDialog, "Instructions Dialog is not set!"); Assert.IsNotNull(HelpButton, "Help button is not set!"); Assert.IsNotNull(GlassPanel, "GlassPanel is not set!"); InstructionsText.text = "Arrow keys for pitch and yaw.\nWSAD to move.\nQE for height." + "\n\nClick anywhere to close."; #if (UNITY_IOS || UNITY_ANDROID) && !UNITY_EDITOR InstructionsText.text = "Drag knob to move and rotate.\nUp and Down buttons for elevation." + "\nGyroscope for pitch. \nPinch screen to zoom.\n\nTap anywhere to close."; #endif ShowHideDialog(false); } /// <summary> /// Event triggered when the help button is clicked on. /// </summary> public void OnClick() { ShowHideDialog(true); } /// <summary> /// Event triggered by any click/touch on the glass panel. /// </summary> public void OnClose() { ShowHideDialog(false); } /// <summary> /// Helper function to hide or show the dialog panel and its associated elements. /// </summary> /// <param name="isVisible">Indicates if dialog should be visible or hidden.</param> private void ShowHideDialog(bool isVisible) { HelpButton.SetActive(!isVisible); InstructionsDialog.SetActive(isVisible); GlassPanel.SetActive(isVisible); } } }
412
0.926431
1
0.926431
game-dev
MEDIA
0.664305
game-dev,desktop-app
0.814858
1
0.814858
TheEpicBlock/PolyMc
6,423
src/main/java/io/github/theepicblock/polymc/api/PolyMap.java
/* * PolyMc * Copyright (C) 2020-2020 TheEpicBlock_TEB * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This 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 * Lesser 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, see <https://www.gnu.org/licenses>. */ package io.github.theepicblock.polymc.api; import io.github.theepicblock.polymc.api.block.BlockPoly; import io.github.theepicblock.polymc.api.entity.EntityPoly; import io.github.theepicblock.polymc.api.gui.GuiPoly; import io.github.theepicblock.polymc.api.item.ItemLocation; import io.github.theepicblock.polymc.api.item.ItemPoly; import io.github.theepicblock.polymc.api.resource.PolyMcResourcePack; import io.github.theepicblock.polymc.impl.Util; import io.github.theepicblock.polymc.impl.misc.logging.SimpleLogger; import io.github.theepicblock.polymc.mixins.entity.EntityAttributesFilteringMixin; import io.github.theepicblock.polymc.mixins.gui.GuiPolyImplementation; import io.github.theepicblock.polymc.mixins.item.CreativeItemStackFix; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.block.entity.BlockEntityType; import net.minecraft.component.ComponentType; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.attribute.EntityAttribute; import net.minecraft.entity.effect.StatusEffect; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.registry.Registries; import net.minecraft.registry.entry.RegistryEntry; import net.minecraft.screen.ScreenHandlerType; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.util.math.Direction; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; public interface PolyMap { /** * Converts the serverside representation of an item into a clientside one that should be sent to the client. */ ItemStack getClientItem(ItemStack serverItem, @Nullable ServerPlayerEntity player, @Nullable ItemLocation location); /** * Converts the serverside representation of a block into a clientside one that should be sent to the client. */ default BlockState getClientState(BlockState serverBlock, @Nullable ServerPlayerEntity player) { BlockPoly poly = this.getBlockPoly(serverBlock.getBlock()); if (poly == null) return serverBlock; return poly.getClientBlock(serverBlock); } /** * Get the raw id of the clientside blockstate. */ @ApiStatus.Internal default int getClientStateRawId(BlockState state, ServerPlayerEntity playerEntity) { BlockState clientState = this.getClientState(state, playerEntity); if (clientState == null) { clientState = Blocks.STONE.getDefaultState(); } return Block.STATE_IDS.getRawId(clientState); } /** * @return the {@link ItemPoly} that this PolyMap associates with this {@link Item}. */ ItemPoly getItemPoly(Item item); /** * @return the {@link BlockPoly} that this PolyMap associates with this {@link Block}. */ BlockPoly getBlockPoly(Block block); /** * @return the {@link GuiPoly} that this PolyMap associates with this {@link ScreenHandlerType}. */ GuiPoly getGuiPoly(ScreenHandlerType<?> serverGuiType); /** * @return the {@link EntityPoly} that this PolyMap associates with this {@link EntityType}. */ <T extends Entity> EntityPoly<T> getEntityPoly(EntityType<T> entity); /** * Reverts the clientside item into the serverside representation. * This should be the reverse of {@link #getClientItem(ItemStack, ServerPlayerEntity, ItemLocation)}. * For optimization reasons, this method only needs to be implemented for items gained by players in creative mode. * @see CreativeItemStackFix */ ItemStack reverseClientItem(ItemStack clientItem, @Nullable ServerPlayerEntity player); /** * Specifies if this map is meant for vanilla-like clients * This is used to disable/enable miscellaneous patches * @see io.github.theepicblock.polymc.mixins.CustomPacketDisabler * @see io.github.theepicblock.polymc.mixins.block.ResyncImplementation * @see io.github.theepicblock.polymc.impl.mixin.CustomBlockBreakingCheck#needsCustomBreaking(ServerPlayerEntity, BlockState) * @see GuiPolyImplementation * @see io.github.theepicblock.polymc.mixins.item.CustomRecipeFix */ boolean isVanillaLikeMap(); boolean hasBlockWizards(); /** * Specifies if the {@link BlockState} changes done around this block might require a resync. */ boolean shouldForceBlockStateSync(BlockState sourceState, BlockState clientState, Direction direction); @Nullable PolyMcResourcePack generateResourcePack(SimpleLogger logger); String dumpDebugInfo(); /** * Used for filtering out attributes unsupported by client. * @see EntityAttributesFilteringMixin */ default boolean canReceiveEntityAttribute(RegistryEntry<EntityAttribute> attribute) { return Util.isVanillaAndRegistered(attribute); } default boolean canReceiveBlockEntity(BlockEntityType<?> e) { return Util.isVanilla(Registries.BLOCK_ENTITY_TYPE.getId(e)); } default boolean canReceiveStatusEffect(RegistryEntry<StatusEffect> entry) { return Util.isVanillaAndRegistered(entry); } default boolean canReceiveEnchantment(RegistryEntry<Enchantment> entry) { return Util.isVanillaAndRegistered(entry); } default boolean canReceivePotion(RegistryEntry<Potion> entry) { return Util.isVanillaAndRegistered(entry); } default boolean canReceiveDataComponentType(ComponentType<?> type) { return Util.isVanilla(Registries.DATA_COMPONENT_TYPE.getId(type)); } }
412
0.618676
1
0.618676
game-dev
MEDIA
0.971439
game-dev
0.671097
1
0.671097
swgemu/Core3
1,924
MMOCoreORB/src/server/zone/packets/creature/CreatureObjectDeltaMessage4.h
/* Copyright <SWGEmu> See file COPYING for copying conditions.*/ #ifndef CREATUREOBJECTDELTAMESSAGE4_H_ #define CREATUREOBJECTDELTAMESSAGE4_H_ #include "server/zone/packets/DeltaMessage.h" class CreatureObjectDeltaMessage4 : public DeltaMessage { CreatureObject* creo; public: CreatureObjectDeltaMessage4(CreatureObject* cr) : DeltaMessage(cr->getObjectID(), 'CREO', 0x04) { creo = cr; } void updateAccelerationMultiplierBase() { addFloatUpdate(0x00, creo->getAccelerationMultiplierBase()); } void updateAccelerationMultiplierMod() { addFloatUpdate(0x01, creo->getAccelerationMultiplierMod()); } void updateSpeedMultiplierBase() { addFloatUpdate(0x04, creo->getSpeedMultiplierBase()); } void updateSpeedMultiplierMod() { addFloatUpdate(0x05, creo->getSpeedMultiplierMod()); } void updateListenToID(uint64 objectid) { startUpdate(0x06); insertLong(objectid); } void updateRunSpeed() { addFloatUpdate(0x07, creo->getRunSpeed()); } void updateSlopeModAngle() { addFloatUpdate(0x08, creo->getSlopeModAngle()); } void updateSlopeModPercent() { addFloatUpdate(0x09, creo->getSlopeModPercent()); } void updateTurnScale() { addFloatUpdate(0x0A, creo->getTurnScale()); } void updateWalkSpeed() { addFloatUpdate(0x0B, creo->getWalkSpeed()); } void updateWaterModPercent() { addFloatUpdate(0x0C, creo->getWaterModPercent()); } void updateSpeedAndAccelerationMods(bool sendSelf = true) { float aScale = creo->getAccelerationMultiplierMod(); float mScale = creo->getSpeedMultiplierMod(); float tScale = creo->getTurnScale(); if (aScale == 0.f && mScale == 0.f) { aScale = 0.1f; } if (mScale == 0.f && !sendSelf) { mScale = 0.1f; } addFloatUpdate(0x01, aScale); // accelerationMultiplierMod addFloatUpdate(0x05, mScale); // speedMultiplierMod addFloatUpdate(0x0A, tScale); // turnScale } }; #endif /*CREATUREOBJECTDELTAMESSAGE4_H_*/
412
0.743058
1
0.743058
game-dev
MEDIA
0.773618
game-dev
0.792319
1
0.792319
71/stadiacontroller
8,472
vigem.go
package stadiacontroller /* #include <stdint.h> typedef struct { uint16_t wButtons; uint8_t bLeftTrigger; uint8_t bRightTrigger; int16_t sThumbLX; int16_t sThumbLY; int16_t sThumbRX; int16_t sThumbRY; } xusb_report; */ import "C" import ( "errors" "unsafe" "golang.org/x/sys/windows" ) const ( VIGEM_ERROR_NONE = 0x20000000 VIGEM_ERROR_BUS_NOT_FOUND = 0xE0000001 VIGEM_ERROR_NO_FREE_SLOT = 0xE0000002 VIGEM_ERROR_INVALID_TARGET = 0xE0000003 VIGEM_ERROR_REMOVAL_FAILED = 0xE0000004 VIGEM_ERROR_ALREADY_CONNECTED = 0xE0000005 VIGEM_ERROR_TARGET_UNINITIALIZED = 0xE0000006 VIGEM_ERROR_TARGET_NOT_PLUGGED_IN = 0xE0000007 VIGEM_ERROR_BUS_VERSION_MISMATCH = 0xE0000008 VIGEM_ERROR_BUS_ACCESS_FAILED = 0xE0000009 VIGEM_ERROR_CALLBACK_ALREADY_REGISTERED = 0xE0000010 VIGEM_ERROR_CALLBACK_NOT_FOUND = 0xE0000011 VIGEM_ERROR_BUS_ALREADY_CONNECTED = 0xE0000012 VIGEM_ERROR_BUS_INVALID_HANDLE = 0xE0000013 VIGEM_ERROR_XUSB_USERINDEX_OUT_OF_RANGE = 0xE0000014 VIGEM_ERROR_MAX = VIGEM_ERROR_XUSB_USERINDEX_OUT_OF_RANGE + 1 ) var ( client = windows.NewLazyDLL("ViGEmClient.dll") procAlloc = client.NewProc("vigem_alloc") procFree = client.NewProc("vigem_free") procConnect = client.NewProc("vigem_connect") procDisconnect = client.NewProc("vigem_disconnect") procTargetAdd = client.NewProc("vigem_target_add") procTargetFree = client.NewProc("vigem_target_free") procTargetRemove = client.NewProc("vigem_target_remove") procTargetX360Alloc = client.NewProc("vigem_target_x360_alloc") procTargetX360RegisterNotification = client.NewProc("vigem_target_x360_register_notification") procTargetX360UnregisterNotification = client.NewProc("vigem_target_x360_unregister_notification") procTargetX360Update = client.NewProc("vigem_target_x360_update") ) type VigemError struct { code uint } func NewVigemError(rawCode uintptr) *VigemError { code := uint(rawCode) if code == VIGEM_ERROR_NONE { return nil } return &VigemError{code} } func (err *VigemError) Error() string { switch err.code { case VIGEM_ERROR_BUS_NOT_FOUND: return "bus not found" case VIGEM_ERROR_NO_FREE_SLOT: return "no free slot" case VIGEM_ERROR_INVALID_TARGET: return "invalid target" case VIGEM_ERROR_REMOVAL_FAILED: return "removal failed" case VIGEM_ERROR_ALREADY_CONNECTED: return "already connected" case VIGEM_ERROR_TARGET_UNINITIALIZED: return "target uninitialized" case VIGEM_ERROR_TARGET_NOT_PLUGGED_IN: return "target not plugged in" case VIGEM_ERROR_BUS_VERSION_MISMATCH: return "bus version mismatch" case VIGEM_ERROR_BUS_ACCESS_FAILED: return "bus access failed" case VIGEM_ERROR_CALLBACK_ALREADY_REGISTERED: return "callback already registered" case VIGEM_ERROR_CALLBACK_NOT_FOUND: return "callback not found" case VIGEM_ERROR_BUS_ALREADY_CONNECTED: return "bus already connected" case VIGEM_ERROR_BUS_INVALID_HANDLE: return "bus invalid handle" case VIGEM_ERROR_XUSB_USERINDEX_OUT_OF_RANGE: return "xusb userindex out of range" default: return "invalid code returned by ViGEm" } } type Emulator struct { handle uintptr onVibration func(vibration Vibration) } type Vibration struct { LargeMotor byte SmallMotor byte } func NewEmulator(onVibration func(vibration Vibration)) (*Emulator, error) { handle, _, err := procAlloc.Call() if !errors.Is(err, windows.ERROR_SUCCESS) { return nil, err } libErr, _, err := procConnect.Call(handle) if !errors.Is(err, windows.ERROR_SUCCESS) { return nil, err } if err := NewVigemError(libErr); err != nil { return nil, err } return &Emulator{handle, onVibration}, nil } func (e *Emulator) Close() error { procDisconnect.Call(e.handle) _, _, err := procFree.Call(e.handle) return err } func (e *Emulator) CreateXbox360Controller() (*Xbox360Controller, error) { handle, _, err := procTargetX360Alloc.Call() if !errors.Is(err, windows.ERROR_SUCCESS) { return nil, err } notificationHandler := func(client, target uintptr, largeMotor, smallMotor, ledNumber byte) uintptr { e.onVibration(Vibration{largeMotor, smallMotor}) return 0 } callback := windows.NewCallback(notificationHandler) return &Xbox360Controller{e, handle, false, callback}, nil } type x360NotificationHandler func(client, target uintptr, largeMotor, smallMotor, ledNumber byte) uintptr type Xbox360Controller struct { emulator *Emulator handle uintptr connected bool notificationHandler uintptr } func (c *Xbox360Controller) Close() error { _, _, err := procTargetFree.Call(c.handle) return err } func (c *Xbox360Controller) Connect() error { libErr, _, err := procTargetAdd.Call(c.emulator.handle, c.handle) if !errors.Is(err, windows.ERROR_SUCCESS) { return err } if err := NewVigemError(libErr); err != nil { return err } libErr, _, err = procTargetX360RegisterNotification.Call(c.emulator.handle, c.handle, c.notificationHandler) if !errors.Is(err, windows.ERROR_SUCCESS) { return err } if err := NewVigemError(libErr); err != nil { return err } c.connected = true return nil } func (c *Xbox360Controller) Disconnect() error { libErr, _, err := procTargetX360UnregisterNotification.Call(c.handle) if !errors.Is(err, windows.ERROR_SUCCESS) { return err } if err := NewVigemError(libErr); err != nil { return err } libErr, _, err = procTargetRemove.Call(c.emulator.handle, c.handle) if !errors.Is(err, windows.ERROR_SUCCESS) { return err } if err := NewVigemError(libErr); err != nil { return err } c.connected = false return nil } func (c *Xbox360Controller) Send(report *Xbox360ControllerReport) error { libErr, _, err := procTargetX360Update.Call(c.emulator.handle, c.handle, uintptr(unsafe.Pointer(&report.native))) if !errors.Is(err, windows.ERROR_SUCCESS) { return err } if err := NewVigemError(libErr); err != nil { return err } return nil } type Xbox360ControllerReport struct { native C.xusb_report Capture bool Assistant bool } // Bits that correspond to the Xbox 360 controller buttons. const ( Xbox360ControllerButtonUp = 0 Xbox360ControllerButtonDown = 1 Xbox360ControllerButtonLeft = 2 Xbox360ControllerButtonRight = 3 Xbox360ControllerButtonStart = 4 Xbox360ControllerButtonBack = 5 Xbox360ControllerButtonLeftThumb = 6 Xbox360ControllerButtonRightThumb = 7 Xbox360ControllerButtonLeftShoulder = 8 Xbox360ControllerButtonRightShoulder = 9 Xbox360ControllerButtonGuide = 10 Xbox360ControllerButtonA = 12 Xbox360ControllerButtonB = 13 Xbox360ControllerButtonX = 14 Xbox360ControllerButtonY = 15 ) func NewXbox360ControllerReport() Xbox360ControllerReport { return Xbox360ControllerReport{} } func (r *Xbox360ControllerReport) GetButtons() uint16 { return uint16(r.native.wButtons) } func (r *Xbox360ControllerReport) SetButtons(buttons uint16) { r.native.wButtons = C.uint16_t(buttons) } func (r *Xbox360ControllerReport) MaybeSetButton(shiftBy int, isSet bool) { if isSet { r.SetButton(shiftBy) } } func (r *Xbox360ControllerReport) SetButton(shiftBy int) { r.native.wButtons |= 1 << shiftBy } func (r *Xbox360ControllerReport) GetLeftTrigger() byte { return byte(r.native.bLeftTrigger) } func (r *Xbox360ControllerReport) SetLeftTrigger(value byte) { r.native.bLeftTrigger = C.uint8_t(value) } func (r *Xbox360ControllerReport) GetRightTrigger() byte { return byte(r.native.bRightTrigger) } func (r *Xbox360ControllerReport) SetRightTrigger(value byte) { r.native.bRightTrigger = C.uint8_t(value) } func (r *Xbox360ControllerReport) GetLeftThumb() (x, y int16) { return int16(r.native.sThumbLX), int16(r.native.sThumbLY) } func (r *Xbox360ControllerReport) SetLeftThumb(x, y int16) { r.native.sThumbLX = C.int16_t(x) r.native.sThumbLY = C.int16_t(y) } func (r *Xbox360ControllerReport) GetRightThumb() (x, y int16) { return int16(r.native.sThumbRX), int16(r.native.sThumbRY) } func (r *Xbox360ControllerReport) SetRightThumb(x, y int16) { r.native.sThumbRX = C.int16_t(x) r.native.sThumbRY = C.int16_t(y) }
412
0.819057
1
0.819057
game-dev
MEDIA
0.412796
game-dev
0.874191
1
0.874191
Ji-Rath/MassAIExample
1,233
Plugins/RTSFormations/Source/RTSFormations/Private/RTSAgentSubsystem.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "RTSAgentSubsystem.h" #include "LaunchEntityProcessor.h" #include "MassCommandBuffer.h" #include "MassEntitySubsystem.h" #include "Engine/World.h" void URTSAgentSubsystem::LaunchEntities(const FVector& Location, float Radius) const { TRACE_CPUPROFILER_EVENT_SCOPE(TEXT("LaunchEntities")); UMassEntitySubsystem* EntitySubsystem = GetWorld()->GetSubsystem<UMassEntitySubsystem>(); // Query items in radius TArray<FMassEntityHandle> Entities; const FBox Bounds(Location - FVector(Radius, Radius, 0.f), Location + FVector(Radius, Radius, 0.f)); AgentHashGrid.QuerySmall(Bounds,Entities); if (EntitySubsystem) { FLaunchEntityFragment LaunchEntityFragment; LaunchEntityFragment.Origin = Location; LaunchEntityFragment.Magnitude = 500.f; for(const FMassEntityHandle& Entity : Entities) { EntitySubsystem->GetEntityManager().Defer().PushCommand<FMassCommandAddFragmentInstances>(Entity, LaunchEntityFragment); } // hacky fix since I couldnt get observer working for the life of me if (Entities.Num()) GetWorld()->GetSubsystem<UMassSignalSubsystem>()->DelaySignalEntities(LaunchEntity, Entities,0.1f); } }
412
0.770145
1
0.770145
game-dev
MEDIA
0.926608
game-dev
0.934507
1
0.934507
GarageGames/Torque3D
8,654
Engine/lib/bullet/src/BulletCollision/CollisionDispatch/btConvex2dConvex2dAlgorithm.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btConvex2dConvex2dAlgorithm.h" //#include <stdio.h> #include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h" #include "BulletCollision/CollisionDispatch/btCollisionObject.h" #include "BulletCollision/CollisionShapes/btConvexShape.h" #include "BulletCollision/CollisionShapes/btCapsuleShape.h" #include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" #include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" #include "BulletCollision/CollisionShapes/btBoxShape.h" #include "BulletCollision/CollisionDispatch/btManifoldResult.h" #include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h" #include "BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h" #include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h" #include "BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h" #include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h" #include "BulletCollision/CollisionShapes/btSphereShape.h" #include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h" #include "BulletCollision/NarrowPhaseCollision/btGjkEpa2.h" #include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h" #include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h" btConvex2dConvex2dAlgorithm::CreateFunc::CreateFunc(btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* pdSolver) { m_simplexSolver = simplexSolver; m_pdSolver = pdSolver; } btConvex2dConvex2dAlgorithm::CreateFunc::~CreateFunc() { } btConvex2dConvex2dAlgorithm::btConvex2dConvex2dAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* pdSolver,int /* numPerturbationIterations */, int /* minimumPointsPerturbationThreshold */) : btActivatingCollisionAlgorithm(ci,body0Wrap,body1Wrap), m_simplexSolver(simplexSolver), m_pdSolver(pdSolver), m_ownManifold (false), m_manifoldPtr(mf), m_lowLevelOfDetail(false) { (void)body0Wrap; (void)body1Wrap; } btConvex2dConvex2dAlgorithm::~btConvex2dConvex2dAlgorithm() { if (m_ownManifold) { if (m_manifoldPtr) m_dispatcher->releaseManifold(m_manifoldPtr); } } void btConvex2dConvex2dAlgorithm ::setLowLevelOfDetail(bool useLowLevel) { m_lowLevelOfDetail = useLowLevel; } extern btScalar gContactBreakingThreshold; // // Convex-Convex collision algorithm // void btConvex2dConvex2dAlgorithm ::processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) { if (!m_manifoldPtr) { //swapped? m_manifoldPtr = m_dispatcher->getNewManifold(body0Wrap->getCollisionObject(),body1Wrap->getCollisionObject()); m_ownManifold = true; } resultOut->setPersistentManifold(m_manifoldPtr); //comment-out next line to test multi-contact generation //resultOut->getPersistentManifold()->clearManifold(); const btConvexShape* min0 = static_cast<const btConvexShape*>(body0Wrap->getCollisionShape()); const btConvexShape* min1 = static_cast<const btConvexShape*>(body1Wrap->getCollisionShape()); btVector3 normalOnB; btVector3 pointOnBWorld; { btGjkPairDetector::ClosestPointInput input; btGjkPairDetector gjkPairDetector(min0,min1,m_simplexSolver,m_pdSolver); //TODO: if (dispatchInfo.m_useContinuous) gjkPairDetector.setMinkowskiA(min0); gjkPairDetector.setMinkowskiB(min1); { input.m_maximumDistanceSquared = min0->getMargin() + min1->getMargin() + m_manifoldPtr->getContactBreakingThreshold(); input.m_maximumDistanceSquared*= input.m_maximumDistanceSquared; } input.m_transformA = body0Wrap->getWorldTransform(); input.m_transformB = body1Wrap->getWorldTransform(); gjkPairDetector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw); btVector3 v0,v1; btVector3 sepNormalWorldSpace; } if (m_ownManifold) { resultOut->refreshContactPoints(); } } btScalar btConvex2dConvex2dAlgorithm::calculateTimeOfImpact(btCollisionObject* col0,btCollisionObject* col1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) { (void)resultOut; (void)dispatchInfo; ///Rather then checking ALL pairs, only calculate TOI when motion exceeds threshold ///Linear motion for one of objects needs to exceed m_ccdSquareMotionThreshold ///col0->m_worldTransform, btScalar resultFraction = btScalar(1.); btScalar squareMot0 = (col0->getInterpolationWorldTransform().getOrigin() - col0->getWorldTransform().getOrigin()).length2(); btScalar squareMot1 = (col1->getInterpolationWorldTransform().getOrigin() - col1->getWorldTransform().getOrigin()).length2(); if (squareMot0 < col0->getCcdSquareMotionThreshold() && squareMot1 < col1->getCcdSquareMotionThreshold()) return resultFraction; //An adhoc way of testing the Continuous Collision Detection algorithms //One object is approximated as a sphere, to simplify things //Starting in penetration should report no time of impact //For proper CCD, better accuracy and handling of 'allowed' penetration should be added //also the mainloop of the physics should have a kind of toi queue (something like Brian Mirtich's application of Timewarp for Rigidbodies) /// Convex0 against sphere for Convex1 { btConvexShape* convex0 = static_cast<btConvexShape*>(col0->getCollisionShape()); btSphereShape sphere1(col1->getCcdSweptSphereRadius()); //todo: allow non-zero sphere sizes, for better approximation btConvexCast::CastResult result; btVoronoiSimplexSolver voronoiSimplex; //SubsimplexConvexCast ccd0(&sphere,min0,&voronoiSimplex); ///Simplification, one object is simplified as a sphere btGjkConvexCast ccd1( convex0 ,&sphere1,&voronoiSimplex); //ContinuousConvexCollision ccd(min0,min1,&voronoiSimplex,0); if (ccd1.calcTimeOfImpact(col0->getWorldTransform(),col0->getInterpolationWorldTransform(), col1->getWorldTransform(),col1->getInterpolationWorldTransform(),result)) { //store result.m_fraction in both bodies if (col0->getHitFraction()> result.m_fraction) col0->setHitFraction( result.m_fraction ); if (col1->getHitFraction() > result.m_fraction) col1->setHitFraction( result.m_fraction); if (resultFraction > result.m_fraction) resultFraction = result.m_fraction; } } /// Sphere (for convex0) against Convex1 { btConvexShape* convex1 = static_cast<btConvexShape*>(col1->getCollisionShape()); btSphereShape sphere0(col0->getCcdSweptSphereRadius()); //todo: allow non-zero sphere sizes, for better approximation btConvexCast::CastResult result; btVoronoiSimplexSolver voronoiSimplex; //SubsimplexConvexCast ccd0(&sphere,min0,&voronoiSimplex); ///Simplification, one object is simplified as a sphere btGjkConvexCast ccd1(&sphere0,convex1,&voronoiSimplex); //ContinuousConvexCollision ccd(min0,min1,&voronoiSimplex,0); if (ccd1.calcTimeOfImpact(col0->getWorldTransform(),col0->getInterpolationWorldTransform(), col1->getWorldTransform(),col1->getInterpolationWorldTransform(),result)) { //store result.m_fraction in both bodies if (col0->getHitFraction() > result.m_fraction) col0->setHitFraction( result.m_fraction); if (col1->getHitFraction() > result.m_fraction) col1->setHitFraction( result.m_fraction); if (resultFraction > result.m_fraction) resultFraction = result.m_fraction; } } return resultFraction; }
412
0.967297
1
0.967297
game-dev
MEDIA
0.985106
game-dev
0.976689
1
0.976689
tastybento/askyblock
16,217
src/com/wasteofplastic/askyblock/CoopPlay.java
/******************************************************************************* * This file is part of ASkyBlock. * * ASkyBlock 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. * * ASkyBlock 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 ASkyBlock. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package com.wasteofplastic.askyblock; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import com.wasteofplastic.askyblock.events.CoopJoinEvent; import com.wasteofplastic.askyblock.events.CoopLeaveEvent; import com.wasteofplastic.askyblock.util.Util; /** * Handles coop play interactions * * @author tastybento * */ public class CoopPlay { private static CoopPlay instance = new CoopPlay(ASkyBlock.getPlugin()); // Stores all the coop islands, the coop player, the location and the // inviter private final Map<UUID, HashMap<Location, UUID>> coopPlayers = new HashMap<>(); // Defines whether a player is on a coop island or not // private HashMap<UUID, Location> onCoopIsland = new HashMap<UUID, // Location>(); private ASkyBlock plugin; /** * @param plugin - ASkyBlock plugin object */ private CoopPlay(ASkyBlock plugin) { this.plugin = plugin; } /** * Adds a player to an island as a coop player. * * @param requester - coop requester * @param newPlayer - new player to add to the coop * @return true if successful, otherwise false */ public boolean addCoopPlayer(Player requester, Player newPlayer) { // plugin.getLogger().info("DEBUG: adding coop player"); // Find out which island this coop player is being requested to join Location islandLoc = null; if (plugin.getPlayers().inTeam(requester.getUniqueId())) { islandLoc = plugin.getPlayers().getTeamIslandLocation(requester.getUniqueId()); // Tell the team owner UUID leaderUUID = plugin.getPlayers().getTeamLeader(requester.getUniqueId()); // Check if only leader can coop if(Settings.onlyLeaderCanCoop && (!requester.getUniqueId().equals(leaderUUID))){ Util.sendMessage(requester, ChatColor.RED + plugin.myLocale(requester.getUniqueId()).cannotCoop); return false; } // Tell all the team members for (UUID member : plugin.getPlayers().getMembers(leaderUUID)) { // plugin.getLogger().info("DEBUG: " + member.toString()); if (!member.equals(requester.getUniqueId())) { Player player = plugin.getServer().getPlayer(member); if (player != null) { Util.sendMessage(player, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).coopInvited.replace("[name]", requester.getName()).replace("[player]", newPlayer.getName())); Util.sendMessage(player, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).coopUseExpel); } else { if (member.equals(leaderUUID)) { // offline - tell leader plugin.getMessages().setMessage(leaderUUID, plugin.myLocale(leaderUUID).coopInvited.replace("[name]", requester.getName()).replace("[player]", newPlayer.getName())); } } } } } else { islandLoc = plugin.getPlayers().getIslandLocation(requester.getUniqueId()); } Island coopIsland = plugin.getGrid().getIslandAt(islandLoc); if (coopIsland == null) { return false; } // Fire event and check if it is cancelled final CoopJoinEvent event = new CoopJoinEvent(newPlayer.getUniqueId(), coopIsland, requester.getUniqueId()); plugin.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return false; } // Add the coop to the list. If the location already exists then the new // requester will replace the old if (coopPlayers.containsKey(newPlayer.getUniqueId())) { // This is an existing player in the list // Add this island to the set coopPlayers.get(newPlayer.getUniqueId()).put(coopIsland.getCenter(), requester.getUniqueId()); } else { // First time. Create the hashmap HashMap<Location, UUID> loc = new HashMap<>(); loc.put(coopIsland.getCenter(), requester.getUniqueId()); coopPlayers.put(newPlayer.getUniqueId(), loc); } return true; } /** * Removes a coop player * * @param requester - requester * @param targetPlayer - player to remove * @return true if the player was a coop player, and false if not */ public boolean removeCoopPlayer(Player requester, Player targetPlayer) { return removeCoopPlayer(requester, targetPlayer.getUniqueId()); } /** * Returns the list of islands that this player is coop on or empty if none * * @param player - player to query * @return Set of locations */ public Set<Location> getCoopIslands(Player player) { if (coopPlayers.containsKey(player.getUniqueId())) { return coopPlayers.get(player.getUniqueId()).keySet(); } return new HashSet<Location>(); } /** * Gets a list of all the players that are currently coop on this island * * @param islandLoc - island location to query * @return List of UUID's of players that have coop rights to the island */ public List<UUID> getCoopPlayers(Location islandLoc) { Island coopIsland = plugin.getGrid().getIslandAt(islandLoc); List<UUID> result = new ArrayList<>(); if (coopIsland != null) { for (UUID player : coopPlayers.keySet()) { if (coopPlayers.get(player).containsKey(coopIsland.getCenter())) { result.add(player); } } } return result; } /** * Removes all coop players from an island - used when doing an island reset * * @param player - island player's UUID */ public void clearAllIslandCoops(UUID player) { // Remove any and all islands related to requester Island island = plugin.getGrid().getIsland(player); if (island == null) { return; } for (HashMap<Location, UUID> coopPlayer : coopPlayers.values()) { for (UUID inviter : coopPlayer.values()) { // Fire event final CoopLeaveEvent event = new CoopLeaveEvent(player, inviter, island); plugin.getServer().getPluginManager().callEvent(event); // Cannot be cancelled } coopPlayer.remove(island.getCenter()); } } /** * Deletes all coops from player. * Used when player logs out. * * @param player - player object */ public void clearMyCoops(Player player) { //plugin.getLogger().info("DEBUG: clear my coops - clearing coops memberships of " + player.getName()); Island coopIsland = plugin.getGrid().getIsland(player.getUniqueId()); if (coopPlayers.get(player.getUniqueId()) != null) { //plugin.getLogger().info("DEBUG: " + player.getName() + " is a member of a coop"); boolean notCancelled = false; for (UUID inviter : coopPlayers.get(player.getUniqueId()).values()) { // Fire event //plugin.getLogger().info("DEBUG: removing invite from " + plugin.getServer().getPlayer(inviter).getName()); final CoopLeaveEvent event = new CoopLeaveEvent(player.getUniqueId(), inviter, coopIsland); plugin.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { coopPlayers.get(player.getUniqueId()).remove(inviter); } else { notCancelled = true; } } // If the event was never cancelled, then delete the entry fully just in case. May not be needed. if (notCancelled) { coopPlayers.remove(player.getUniqueId()); } } } /** * Called when disabling the plugin */ public void saveCoops() { YamlConfiguration coopConfig = new YamlConfiguration(); for (UUID playerUUID : coopPlayers.keySet()) { coopConfig.set(playerUUID.toString(), getMyCoops(playerUUID)); } Util.saveYamlFile(coopConfig, "coops.yml", false); } public void loadCoops() { File coopFile = new File(plugin.getDataFolder(), "coops.yml"); if (!coopFile.exists()) { return; } YamlConfiguration coopConfig = new YamlConfiguration(); try { coopConfig.load(coopFile); } catch (IOException | InvalidConfigurationException e) { plugin.getLogger().severe("Could not load coop.yml file!"); } // Run through players for (String playerUUID : coopConfig.getValues(false).keySet()) { try { setMyCoops(UUID.fromString(playerUUID), coopConfig.getStringList(playerUUID)); } catch (Exception e) { plugin.getLogger().severe("Could not load coops for player UUID " + playerUUID + " skipping..."); } } } /** * Gets a serialize list of all the coops for this player. Used when saving the player * @param playerUUID - the player's UUID * @return List of island location | uuid of invitee */ private List<String> getMyCoops(UUID playerUUID) { List<String> result = new ArrayList<String>(); if (coopPlayers.containsKey(playerUUID)) { for (Entry<Location, UUID> entry : coopPlayers.get(playerUUID).entrySet()) { result.add(Util.getStringLocation(entry.getKey()) + "|" + entry.getValue().toString()); } } return result; } /** * Sets a player's coops from string. Used when loading a player. * @param playerUUID - the player's UUID * @param coops */ private void setMyCoops(UUID playerUUID, List<String> coops) { try { HashMap<Location, UUID> temp = new HashMap<Location, UUID>(); for (String coop : coops) { String[] split = coop.split("\\|"); if (split.length == 2) { Island coopIsland = plugin.getGrid().getIslandAt(Util.getLocationString(split[0])); if (coopIsland != null) { temp.put(coopIsland.getCenter(), UUID.fromString(split[1])); } } } coopPlayers.put(playerUUID, temp); } catch (Exception e) { plugin.getLogger().severe("Could not load coops for UUID " + playerUUID); e.printStackTrace(); } } /** * Goes through all the known coops and removes any that were invited by * clearer. Returns any inventory * Can be used when clearer logs out or when they are kicked or leave a team * * @param clearer - player to clear */ public void clearMyInvitedCoops(Player clearer) { //plugin.getLogger().info("DEBUG: clear my invited coops - clearing coops that were invited by " + clearer.getName()); Island coopIsland = plugin.getGrid().getIsland(clearer.getUniqueId()); for (UUID playerUUID : coopPlayers.keySet()) { Iterator<Entry<Location, UUID>> en = coopPlayers.get(playerUUID).entrySet().iterator(); while (en.hasNext()) { Entry<Location, UUID> entry = en.next(); // Check if this invite was sent by clearer if (entry.getValue().equals(clearer.getUniqueId())) { // Fire event final CoopLeaveEvent event = new CoopLeaveEvent(playerUUID, clearer.getUniqueId(), coopIsland); plugin.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { // Yes, so get the invitee (target) Player target = plugin.getServer().getPlayer(playerUUID); if (target != null) { Util.sendMessage(target, ChatColor.RED + plugin.myLocale(playerUUID).coopRemoved.replace("[name]", clearer.getName())); } else { plugin.getMessages().setMessage(playerUUID, ChatColor.RED + plugin.myLocale(playerUUID).coopRemoved.replace("[name]", clearer.getName())); } // Mark them as no longer on a coop island // setOnCoopIsland(players, null); // Remove this entry en.remove(); } // else do not remove } } } } /** * Removes all coop players from an island - used when doing an island reset * * @param island */ public void clearAllIslandCoops(Location island) { if (island == null) { return; } Island coopIsland = plugin.getGrid().getIslandAt(island); if (coopIsland == null) return; // Remove any and all islands related to requester for (HashMap<Location, UUID> coopPlayer : coopPlayers.values()) { // Fire event final CoopLeaveEvent event = new CoopLeaveEvent(coopPlayer.get(island), coopIsland.getOwner(), coopIsland); plugin.getServer().getPluginManager().callEvent(event); // Cannot be cancelled coopPlayer.remove(island); } } /** * @return the instance */ public static CoopPlay getInstance() { return instance; } public boolean removeCoopPlayer(Player requester, UUID targetPlayerUUID) { boolean removed = false; /* plugin.getLogger().info("DEBUG: requester is " + requester.getName()); plugin.getLogger().info("DEBUG: target = " + targetPlayerUUID.toString()); for (UUID key : coopPlayers.keySet()) { plugin.getLogger().info("DEBUG: " + key + " ==> " + coopPlayers.get(key)); }*/ // Only bother if the player is in the list if (coopPlayers.containsKey(targetPlayerUUID)) { Island coopIsland = plugin.getGrid().getIsland(requester.getUniqueId()); if (coopIsland != null) { // Fire event final CoopLeaveEvent event = new CoopLeaveEvent(targetPlayerUUID, requester.getUniqueId(), coopIsland); plugin.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { removed = coopPlayers.get(targetPlayerUUID).remove(coopIsland.getCenter()) != null; } } } return removed; } }
412
0.881641
1
0.881641
game-dev
MEDIA
0.74384
game-dev
0.819429
1
0.819429
PolarisSS13/Polaris
19,131
code/modules/clothing/under/accessories/armor.dm
/* // This file holds all of the accessories used as part of the modular armor system. At some point it might be wise to split this into multiple files. */ /obj/item/clothing/accessory/armor name = "armor accessory" desc = "You should never see this description. Ahelp this, please." icon_override = 'icons/mob/modular_armor.dmi' icon = 'icons/obj/clothing/modular_armor.dmi' icon_state = "pouches" w_class = ITEMSIZE_NORMAL /obj/item/clothing/accessory/armor/on_attached(var/obj/item/clothing/S, var/mob/user) if(ishuman(user)) var/mob/living/carbon/human/H = user if(H.wear_suit == S) if((body_parts_covered & ARMS) && istype(H.gloves, /obj/item/clothing)) var/obj/item/clothing/G = H.gloves if(G.body_parts_covered & ARMS) to_chat(H, "<span class='warning'>You can't wear \the [src] with \the [G], it's in the way.</span>") S.accessories -= src return else if((body_parts_covered & LEGS) && istype(H.shoes, /obj/item/clothing)) var/obj/item/clothing/Sh = H.shoes if(Sh.body_parts_covered & LEGS) to_chat(H, "<span class='warning'>You can't wear \the [src] with \the [Sh], it's in the way.</span>") S.accessories -= src return ..() /////////// //Pouches /////////// /obj/item/clothing/accessory/storage/pouches name = "storage pouches" desc = "A collection of black pouches that can be attached to a plate carrier. Carries up to two items." icon_override = 'icons/mob/modular_armor.dmi' icon = 'icons/obj/clothing/modular_armor.dmi' icon_state = "pouches" w_class = ITEMSIZE_NORMAL gender = PLURAL slot = ACCESSORY_SLOT_ARMOR_S slots = 2 /obj/item/clothing/accessory/storage/pouches/blue desc = "A collection of blue pouches that can be attached to a plate carrier. Carries up to two items." icon_state = "pouches_blue" /obj/item/clothing/accessory/storage/pouches/navy desc = "A collection of navy blue pouches that can be attached to a plate carrier. Carries up to two items." icon_state = "pouches_navy" /obj/item/clothing/accessory/storage/pouches/green desc = "A collection of green pouches that can be attached to a plate carrier. Carries up to two items." icon_state = "pouches_green" /obj/item/clothing/accessory/storage/pouches/tan desc = "A collection of tan pouches that can be attached to a plate carrier. Carries up to two items." icon_state = "pouches_tan" /obj/item/clothing/accessory/storage/pouches/large name = "large storage pouches" desc = "A collection of black pouches that can be attached to a plate carrier. Carries up to four items." icon_state = "lpouches" slots = 4 /obj/item/clothing/accessory/storage/pouches/large/blue desc = "A collection of blue pouches that can be attached to a plate carrier. Carries up to four items." icon_state = "lpouches_blue" /obj/item/clothing/accessory/storage/pouches/large/navy desc = "A collection of navy blue pouches that can be attached to a plate carrier. Carries up to four items." icon_state = "lpouches_navy" /obj/item/clothing/accessory/storage/pouches/large/green desc = "A collection of green pouches that can be attached to a plate carrier. Carries up to four items." icon_state = "lpouches_green" /obj/item/clothing/accessory/storage/pouches/large/tan desc = "A collection of tan pouches that can be attached to a plate carrier. Carries up to four items." icon_state = "lpouches_tan" //////////////// //Armor plates //////////////// /obj/item/clothing/accessory/armor/armorplate name = "light armor plate" desc = "A basic armor plate made of steel-reinforced synthetic fibers. Attaches to a plate carrier." icon_state = "armor_light" body_parts_covered = UPPER_TORSO|LOWER_TORSO armor = list(melee = 30, bullet = 15, laser = 40, energy = 10, bomb = 25, bio = 0, rad = 0) slot = ACCESSORY_SLOT_ARMOR_C /obj/item/clothing/accessory/armor/armorplate/explorer name = "explorer armor plate" desc = "A flexible plate made of synthetic fibers, designed to protect from the Sivian fauna. Attaches to a plate carrier." icon_state = "armor_light" armor = list(melee = 30, bullet = 20, laser = 20, energy = 20, bomb = 35, bio = 75, rad = 35) /obj/item/clothing/accessory/armor/armorplate/stab name = "mesh armor plate" desc = "A mesh armor plate made of steel-reinforced synthetic fibers, great for dealing with small blades. Attaches to a plate carrier." icon_state = "armor_stab" armor = list(melee = 30, bullet = 5, laser = 20, energy = 10, bomb = 15, bio = 0, rad = 0) armorsoak = list(melee = 7, bullet = 5, laser = 0, energy = 0, bomb = 0, bio = 0, rad = 0) /obj/item/clothing/accessory/armor/armorplate/blast name = "gel armor plate" desc = "A gel armor plate made of high-grade polymers, great for dealing with localized blasts. Attaches to a plate carrier." icon_state = "armor_blast" armor = list(melee = 25, bullet = 25, laser = 10, energy = 0, bomb = 30, bio = 0, rad = 0) armorsoak = list(melee = 5, bullet = 7, laser = 0, energy = 0, bomb = 40, bio = 0, rad = 0) /obj/item/clothing/accessory/armor/armorplate/medium name = "medium armor plate" desc = "A plasteel-reinforced synthetic armor plate, providing good protection. Attaches to a plate carrier." icon_state = "armor_medium" armor = list(melee = 40, bullet = 40, laser = 40, energy = 25, bomb = 30, bio = 0, rad = 0) /obj/item/clothing/accessory/armor/armorplate/tactical name = "tactical armor plate" desc = "A medium armor plate with additional ablative coating. Attaches to a plate carrier." icon_state = "armor_tactical" armor = list(melee = 40, bullet = 40, laser = 60, energy = 35, bomb = 30, bio = 0, rad = 0) /obj/item/clothing/accessory/armor/armorplate/merc name = "heavy armor plate" desc = "A ceramics-reinforced synthetic armor plate, providing state of of the art protection. Attaches to a plate carrier." icon_state = "armor_merc" armor = list(melee = 60, bullet = 60, laser = 60, energy = 40, bomb = 40, bio = 0, rad = 0) /obj/item/clothing/accessory/armor/armorplate/bulletproof name = "ballistic armor plate" desc = "A woven armor plate with additional plating, providing good protection against high-velocity trauma. Attaches to a plate carrier." icon_state = "armor_ballistic" slowdown = 0.5 armor = list(melee = 10, bullet = 70, laser = 10, energy = 10, bomb = 0, bio = 0, rad = 0) armorsoak = list(melee = 0, bullet = 10, laser = 0, energy = 5, bomb = 0, bio = 0, rad = 0) siemens_coefficient = 0.7 /obj/item/clothing/accessory/armor/armorplate/riot name = "riot armor plate" desc = "A thick armor plate with additional padding, providing good protection against low-velocity trauma. Attaches to a plate carrier." icon_state = "armor_riot" slowdown = 0.5 armor = list(melee = 70, bullet = 10, laser = 10, energy = 10, bomb = 0, bio = 0, rad = 0) armorsoak = list(melee = 10, bullet = 0, laser = 0, energy = 5, bomb = 0, bio = 0, rad = 0) siemens_coefficient = 0.7 /obj/item/clothing/accessory/armor/armorplate/laserproof name = "ablative armor plate" desc = "A durasteel-scaled synthetic armor plate, providing good protection against lasers. Attaches to a plate carrier." icon_state = "armor_ablative" slowdown = 0.5 armor = list(melee = 10, bullet = 10, laser = 70, energy = 50, bomb = 0, bio = 0, rad = 0) armorsoak = list(melee = 0, bullet = 0, laser = 10, energy = 15, bomb = 0, bio = 0, rad = 0) siemens_coefficient = 0.1 /obj/item/clothing/accessory/armor/armorplate/ablative/handle_shield(mob/user, var/damage, atom/damage_source = null, mob/attacker = null, var/def_zone = null, var/attack_text = "the attack") if(istype(damage_source, /obj/item/projectile/energy) || istype(damage_source, /obj/item/projectile/beam)) var/obj/item/projectile/P = damage_source if(P.reflected) return ..() var/reflectchance = 40 - round(damage/3) if(!(def_zone in list(BP_TORSO, BP_GROIN))) reflectchance /= 2 if(P.starting && prob(reflectchance)) visible_message("<span class='danger'>\The [user]'s [src.name] reflects [attack_text]!</span>") var/new_x = P.starting.x + pick(0, 0, 0, 0, 0, -1, 1, -2, 2) var/new_y = P.starting.y + pick(0, 0, 0, 0, 0, -1, 1, -2, 2) var/turf/curloc = get_turf(user) P.redirect(new_x, new_y, curloc, user) P.reflected = 1 return PROJECTILE_CONTINUE ////////////// //Arm guards ////////////// /obj/item/clothing/accessory/armor/armguards name = "arm guards" desc = "A pair of black arm pads reinforced with armor plating. Attaches to a plate carrier." // accessory_icons = list(slot_tie_str = 'icons/mob/modular_armor.dmi', slot_wear_suit_str = 'icons/mob/modular_armor.dmi') icon_state = "armguards" gender = PLURAL body_parts_covered = ARMS armor = list(melee = 40, bullet = 40, laser = 40, energy = 25, bomb = 30, bio = 0, rad = 0) slot = ACCESSORY_SLOT_ARMOR_A /obj/item/clothing/accessory/armor/armguards/blue desc = "A pair of blue arm pads reinforced with armor plating. Attaches to a plate carrier." icon_state = "armguards_blue" /obj/item/clothing/accessory/armor/armguards/navy desc = "A pair of navy blue arm pads reinforced with armor plating. Attaches to a plate carrier." icon_state = "armguards_navy" /obj/item/clothing/accessory/armor/armguards/green desc = "A pair of green arm pads reinforced with armor plating. Attaches to a plate carrier." icon_state = "armguards_green" /obj/item/clothing/accessory/armor/armguards/tan desc = "A pair of tan arm pads reinforced with armor plating. Attaches to a plate carrier." icon_state = "armguards_tan" /obj/item/clothing/accessory/armor/armguards/explorer name = "explorer arm guards" desc = "A pair of green arm pads reinforced with armor plating. Attaches to a plate carrier." icon_state = "armguards_green" armor = list(melee = 30, bullet = 20, laser = 20, energy = 20, bomb = 35, bio = 75, rad = 35) /obj/item/clothing/accessory/armor/armguards/merc name = "heavy arm guards" desc = "A pair of red-trimmed black arm pads reinforced with heavy armor plating. Attaches to a plate carrier." icon_state = "armguards_merc" armor = list(melee = 60, bullet = 60, laser = 60, energy = 40, bomb = 40, bio = 0, rad = 0) /obj/item/clothing/accessory/armor/armguards/laserproof name = "ablative arm guards" desc = "These arm guards will protect your arms from energy weapons." icon_state = "armguards_ablative" item_state_slots = list(slot_r_hand_str = "swat", slot_l_hand_str = "swat") siemens_coefficient = 0.1 //These don't cover the hands, so the siemens doesn't need to be worse than normal ablative. armor = list(melee = 10, bullet = 10, laser = 80, energy = 50, bomb = 0, bio = 0, rad = 0) /obj/item/clothing/accessory/armor/armguards/bulletproof name = "bullet resistant arm guards" desc = "These arm guards will protect your arms from ballistic weapons." icon_state = "armguards_ballistic" item_state_slots = list(slot_r_hand_str = "swat", slot_l_hand_str = "swat") siemens_coefficient = 0.7 armor = list(melee = 10, bullet = 80, laser = 10, energy = 50, bomb = 0, bio = 0, rad = 0) /obj/item/clothing/accessory/armor/armguards/riot name = "riot arm guards" desc = "These arm guards will protect your arms from close combat weapons." icon_state = "armguards_riot" item_state_slots = list(slot_r_hand_str = "swat", slot_l_hand_str = "swat") siemens_coefficient = 0.5 armor = list(melee = 80, bullet = 10, laser = 10, energy = 50, bomb = 0, bio = 0, rad = 0) ////////////// //Leg guards ////////////// /obj/item/clothing/accessory/armor/legguards name = "leg guards" desc = "A pair of armored leg pads in black. Attaches to a plate carrier." // accessory_icons = list(slot_tie_str = 'icons/mob/modular_armor.dmi', slot_wear_suit_str = 'icons/mob/modular_armor.dmi') icon_state = "legguards" gender = PLURAL body_parts_covered = LEGS armor = list(melee = 40, bullet = 40, laser = 40, energy = 25, bomb = 30, bio = 0, rad = 0) slot = ACCESSORY_SLOT_ARMOR_L /obj/item/clothing/accessory/armor/legguards/blue desc = "A pair of armored leg pads in blue. Attaches to a plate carrier." icon_state = "legguards_blue" /obj/item/clothing/accessory/armor/legguards/navy desc = "A pair of armored leg pads in navy blue. Attaches to a plate carrier." icon_state = "legguards_navy" /obj/item/clothing/accessory/armor/legguards/green desc = "A pair of armored leg pads in green. Attaches to a plate carrier." icon_state = "legguards_green" /obj/item/clothing/accessory/armor/legguards/tan desc = "A pair of armored leg pads in tan. Attaches to a plate carrier." icon_state = "legguards_tan" /obj/item/clothing/accessory/armor/legguards/explorer name = "explorer leg guards" desc = "A pair of armored leg pads in green. Attaches to a plate carrier." icon_state = "legguards_green" armor = list(melee = 30, bullet = 20, laser = 20, energy = 20, bomb = 35, bio = 75, rad = 35) /obj/item/clothing/accessory/armor/legguards/merc name = "heavy leg guards" desc = "A pair of heavily armored leg pads in red-trimmed black. Attaches to a plate carrier." icon_state = "legguards_merc" armor = list(melee = 60, bullet = 60, laser = 60, energy = 40, bomb = 40, bio = 0, rad = 0) /obj/item/clothing/accessory/armor/legguards/laserproof name = "ablative leg guards" desc = "These will protect your legs from energy weapons." icon_state = "legguards_ablative" item_state_slots = list(slot_r_hand_str = "jackboots", slot_l_hand_str = "jackboots") siemens_coefficient = 0.1 armor = list(melee = 10, bullet = 10, laser = 80, energy = 50, bomb = 0, bio = 0, rad = 0) /obj/item/clothing/accessory/armor/legguards/bulletproof name = "bullet resistant leg guards" desc = "These will protect your legs from ballistic weapons." icon_state = "legguards_ballistic" item_state_slots = list(slot_r_hand_str = "jackboots", slot_l_hand_str = "jackboots") siemens_coefficient = 0.7 armor = list(melee = 10, bullet = 80, laser = 10, energy = 10, bomb = 0, bio = 0, rad = 0) /obj/item/clothing/accessory/armor/legguards/riot name = "riot leg guards" desc = "These will protect your legs from close combat weapons." icon_state = "legguards_riot" item_state_slots = list(slot_r_hand_str = "jackboots", slot_l_hand_str = "jackboots") siemens_coefficient = 0.5 armor = list(melee = 80, bullet = 10, laser = 10, energy = 10, bomb = 0, bio = 0, rad = 0) ////////////////////////// //Decorative attachments ////////////////////////// /obj/item/clothing/accessory/armor/tag name = "\improper SCG Flag" desc = "An emblem depicting the Solar Confederate Government's flag." // accessory_icons = list(slot_tie_str = 'icons/mob/modular_armor.dmi', slot_wear_suit_str = 'icons/mob/modular_armor.dmi') icon_state = "solflag" slot = ACCESSORY_SLOT_ARMOR_M w_class = ITEMSIZE_SMALL /obj/item/clothing/accessory/armor/tag/sifguard name = "\improper Sif Defense Force crest" desc = "An emblem depicting the crest of the Sif Defense Force." icon_state = "ecflag" /obj/item/clothing/accessory/armor/tag/sec name = "\improper POLICE tag" desc = "An armor tag with the word POLICE printed in silver lettering on it." icon_state = "sectag" /obj/item/clothing/accessory/armor/tag/com name = "\improper SCG tag" desc = "An armor tag with the words SOLAR CONFEDERATE GOVERNMENT printed in gold lettering on it." icon_state = "comtag" /obj/item/clothing/accessory/armor/tag/nt name = "\improper NANOTRASEN tag" desc = "An armor tag with the word NANOTRASEN printed in red lettering on it and an accompanying company logo." icon_state = "nanotag" /obj/item/clothing/accessory/armor/tag/pcrc name = "\improper PCRC tag" desc = "An armor tag with the words PROXIMA CENTAURI RISK CONTROL printed in cyan lettering on it." icon_state = "pcrctag" /obj/item/clothing/accessory/armor/tag/hedberg name = "\improper HEDBERG-HAMMARSTROM tag" desc = "An armor tag with the name HEDBERG-HAMMARSTROM printed in olive-green lettering on it." icon_state = "saaretag" /obj/item/clothing/accessory/armor/tag/opos name = "\improper O+ blood patch" desc = "An embroidered patch indicating the wearer's blood type as O POSITIVE." icon_state = "opostag" /obj/item/clothing/accessory/armor/tag/oneg name = "\improper O- blood patch" desc = "An embroidered patch indicating the wearer's blood type as O NEGATIVE." icon_state = "onegtag" /obj/item/clothing/accessory/armor/tag/apos name = "\improper A+ blood patch" desc = "An embroidered patch indicating the wearer's blood type as A POSITIVE." icon_state = "apostag" /obj/item/clothing/accessory/armor/tag/aneg name = "\improper A- blood patch" desc = "An embroidered patch indicating the wearer's blood type as A NEGATIVE." icon_state = "anegtag" /obj/item/clothing/accessory/armor/tag/bpos name = "\improper B+ blood patch" desc = "An embroidered patch indicating the wearer's blood type as B POSITIVE." icon_state = "bpostag" /obj/item/clothing/accessory/armor/tag/bneg name = "\improper B- blood patch" desc = "An embroidered patch indicating the wearer's blood type as B NEGATIVE." icon_state = "bnegtag" /obj/item/clothing/accessory/armor/tag/abpos name = "\improper AB+ blood patch" desc = "An embroidered patch indicating the wearer's blood type as AB POSITIVE." icon_state = "abpostag" /obj/item/clothing/accessory/armor/tag/abneg name = "\improper AB- blood patch" desc = "An embroidered patch indicating the wearer's blood type as AB NEGATIVE." icon_state = "abnegtag" ///////////////// // Helmet Covers ///////////////// /obj/item/clothing/accessory/armor/helmcover name = "helmet cover" desc = "A fabric cover for armored helmets." icon_override = 'icons/mob/ties.dmi' icon = 'icons/obj/clothing/modular_armor.dmi' icon_state = "helmcover_blue" slot = ACCESSORY_SLOT_HELM_C /obj/item/clothing/accessory/armor/helmcover/blue name = "blue helmet cover" desc = "A fabric cover for armored helmets in a bright blue color." icon_state = "helmcover_blue" /obj/item/clothing/accessory/armor/helmcover/navy name = "navy blue helmet cover" desc = "A fabric cover for armored helmets. This one is colored navy blue." icon_state = "helmcover_navy" /obj/item/clothing/accessory/armor/helmcover/green name = "green helmet cover" desc = "A fabric cover for armored helmets. This one has a woodland camouflage pattern." icon_state = "helmcover_green" /obj/item/clothing/accessory/armor/helmcover/tan name = "tan helmet cover" desc = "A fabric cover for armored helmets. This one has a desert camouflage pattern." icon_state = "helmcover_tan" /obj/item/clothing/accessory/armor/helmcover/nt name = "\improper NanoTrasen helmet cover" desc = "A fabric cover for armored helmets. This one has NanoTrasen's colors." icon_state = "helmcover_nt" /obj/item/clothing/accessory/armor/helmcover/pcrc name = "\improper PCRC helmet cover" desc = "A fabric cover for armored helmets. This one is colored navy blue and has a tag in the back with the words PROXIMA CENTAURI RISK CONTROL printed in cyan lettering on it." icon_state = "helmcover_pcrc" /obj/item/clothing/accessory/armor/helmcover/saare name = "\improper SAARE helmet cover" desc = "A fabric cover for armored helmets. This one has SAARE's colors." icon_state = "helmcover_saare"
412
0.827497
1
0.827497
game-dev
MEDIA
0.99782
game-dev
0.614021
1
0.614021
OmniSharp/csharp-language-server-protocol
4,619
test/JsonRpc.Tests/CompositeHandlersManagerTests.cs
using System; using System.Reactive.Disposables; using FluentAssertions; using NSubstitute; using OmniSharp.Extensions.JsonRpc; using Xunit; using Xunit.Abstractions; namespace JsonRpc.Tests { public class CompositeHandlersManagerTests : AutoTestBase { public CompositeHandlersManagerTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } [Fact] public void Should_Add_Handler_Instance_To_Parent() { var parent = Substitute.For<IHandlersManager>(); parent.Add(Arg.Any<IJsonRpcHandler>(), Arg.Any<JsonRpcHandlerOptions>()).Returns(Disposable.Empty); var manager = new CompositeHandlersManager(parent); manager.Add(Substitute.For<IJsonRpcHandler>(), new JsonRpcHandlerOptions()); parent.Received(0).Add(Arg.Any<string>(), Arg.Any<IJsonRpcHandler>(), Arg.Any<JsonRpcHandlerOptions>()); parent.Received(1).Add(Arg.Any<IJsonRpcHandler>(), Arg.Any<JsonRpcHandlerOptions>()); manager.GetDisposable().Count.Should().Be(1); } [Fact] public void Should_Add_Named_Handler_Instance_To_Parent() { var parent = Substitute.For<IHandlersManager>(); parent.Add(Arg.Any<string>(), Arg.Any<IJsonRpcHandler>(), Arg.Any<JsonRpcHandlerOptions>()).Returns(Disposable.Empty); var manager = new CompositeHandlersManager(parent); manager.Add("mymethod", Substitute.For<IJsonRpcHandler>(), new JsonRpcHandlerOptions()); parent.Received(0).Add(Arg.Any<IJsonRpcHandler>(), Arg.Any<JsonRpcHandlerOptions>()); parent.Received(1).Add("mymethod", Arg.Any<IJsonRpcHandler>(), Arg.Any<JsonRpcHandlerOptions>()); manager.GetDisposable().Count.Should().Be(1); } [Fact] public void Should_Add_Handler_Factory_To_Parent() { var parent = Substitute.For<IHandlersManager>(); parent.Add(Arg.Any<JsonRpcHandlerFactory>(), Arg.Any<JsonRpcHandlerOptions>()).Returns(Disposable.Empty); var manager = new CompositeHandlersManager(parent); manager.Add(Substitute.For<JsonRpcHandlerFactory>(), new JsonRpcHandlerOptions()); parent.Received(0).Add(Arg.Any<string>(), Arg.Any<JsonRpcHandlerFactory>(), Arg.Any<JsonRpcHandlerOptions>()); parent.Received(1).Add(Arg.Any<JsonRpcHandlerFactory>(), Arg.Any<JsonRpcHandlerOptions>()); manager.GetDisposable().Count.Should().Be(1); } [Fact] public void Should_Add_Named_Handler_Factory_To_Parent() { var parent = Substitute.For<IHandlersManager>(); parent.Add(Arg.Any<string>(), Arg.Any<JsonRpcHandlerFactory>(), Arg.Any<JsonRpcHandlerOptions>()).Returns(Disposable.Empty); var manager = new CompositeHandlersManager(parent); manager.Add("mymethod", Substitute.For<JsonRpcHandlerFactory>(), new JsonRpcHandlerOptions()); parent.Received(0).Add(Arg.Any<JsonRpcHandlerFactory>(), Arg.Any<JsonRpcHandlerOptions>()); parent.Received(1).Add("mymethod", Arg.Any<JsonRpcHandlerFactory>(), Arg.Any<JsonRpcHandlerOptions>()); manager.GetDisposable().Count.Should().Be(1); } [Fact] public void Should_Add_Handler_Type_To_Parent() { var parent = Substitute.For<IHandlersManager>(); parent.Add(Arg.Any<Type>(), Arg.Any<JsonRpcHandlerOptions>()).Returns(Disposable.Empty); var manager = new CompositeHandlersManager(parent); manager.Add(Substitute.For<Type>(), new JsonRpcHandlerOptions()); parent.Received(0).Add(Arg.Any<string>(), Arg.Any<Type>(), Arg.Any<JsonRpcHandlerOptions>()); parent.Received(1).Add(Arg.Any<Type>(), Arg.Any<JsonRpcHandlerOptions>()); manager.GetDisposable().Count.Should().Be(1); } [Fact] public void Should_Add_Named_Handler_Type_To_Parent() { var parent = Substitute.For<IHandlersManager>(); parent.Add(Arg.Any<string>(), Arg.Any<Type>(), Arg.Any<JsonRpcHandlerOptions>()).Returns(Disposable.Empty); var manager = new CompositeHandlersManager(parent); manager.Add("mymethod", Substitute.For<Type>(), new JsonRpcHandlerOptions()); parent.Received(0).Add(Arg.Any<Type>(), Arg.Any<JsonRpcHandlerOptions>()); parent.Received(1).Add("mymethod", Arg.Any<Type>(), Arg.Any<JsonRpcHandlerOptions>()); manager.GetDisposable().Count.Should().Be(1); } } }
412
0.694478
1
0.694478
game-dev
MEDIA
0.193633
game-dev
0.798671
1
0.798671
ss14Starlight/space-station-14
4,064
Content.Shared/Singularity/Components/ContainmentFieldGeneratorComponent.cs
using Content.Shared.Physics; using Content.Shared.Tag; using Robust.Shared.GameStates; using Robust.Shared.Prototypes; using Robust.Shared.Serialization; using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype; namespace Content.Shared.Singularity.Components; [RegisterComponent, NetworkedComponent] public sealed partial class ContainmentFieldGeneratorComponent : Component { private int _powerBuffer; /// <summary> /// Store power with a cap. Decrease over time if not being powered from source. /// </summary> [DataField("powerBuffer")] public int PowerBuffer { get => _powerBuffer; set => _powerBuffer = Math.Clamp(value, 0, 25); //have this decrease over time if not hit by a bolt } /// <summary> /// The minimum the field generator needs to start generating a connection /// </summary> [ViewVariables(VVAccess.ReadWrite)] [DataField("powerMinimum")] public int PowerMinimum = 6; /// <summary> /// How much power should this field generator receive from a collision /// </summary> [ViewVariables(VVAccess.ReadWrite)] [DataField("power")] public int PowerReceived = 3; /// <summary> /// How much power should this field generator lose if not powered? /// </summary> [ViewVariables(VVAccess.ReadWrite)] [DataField("powerLoss")] public int PowerLoss = 2; /// <summary> /// Used to check if it's received power recently. /// </summary> [DataField("accumulator")] public float Accumulator; /// <summary> /// How many seconds should the generators wait before losing power? /// </summary> [DataField("threshold")] public float Threshold = 20f; /// <summary> /// How many tiles should this field check before giving up? /// </summary> [DataField("maxLength")] public float MaxLength = 8F; /// <summary> /// What collision should power this generator? /// It really shouldn't be anything but an emitter bolt but it's here for fun. /// </summary> [ViewVariables(VVAccess.ReadWrite)] [DataField("idTag", customTypeSerializer: typeof(PrototypeIdSerializer<TagPrototype>))] public string IDTag = "EmitterBolt"; /// <summary> /// Which fixture ID should test collision with from the entity that powers the generator? /// Prevents the generator from being powered by fly-by fixtures. /// </summary> [DataField] public string SourceFixtureId = "projectile"; /// <summary> /// Is the generator toggled on? /// </summary> [DataField] public bool Enabled; /// <summary> /// Is this generator connected to fields? /// </summary> [ViewVariables(VVAccess.ReadWrite)] public bool IsConnected; /// <summary> /// The masks the raycast should not go through /// </summary> [DataField("collisionMask")] public int CollisionMask = (int) (CollisionGroup.MobMask | CollisionGroup.Impassable | CollisionGroup.MachineMask | CollisionGroup.Opaque); /// <summary> /// A collection of connections that the generator has based on direction. /// Stores a list of fields connected between generators in this direction. /// </summary> [ViewVariables] public Dictionary<Direction, (Entity<ContainmentFieldGeneratorComponent>, List<EntityUid>)> Connections = new(); /// <summary> /// What fields should this spawn? /// </summary> [ViewVariables(VVAccess.ReadWrite)] [DataField("createdField", customTypeSerializer: typeof(PrototypeIdSerializer<EntityPrototype>))] public string CreatedField = "ContainmentField"; } [Serializable, NetSerializable] public enum ContainmentFieldGeneratorVisuals : byte { PowerLight, FieldLight, OnLight, } [Serializable, NetSerializable] public enum PowerLevelVisuals : byte { NoPower, LowPower, MediumPower, HighPower, } [Serializable, NetSerializable] public enum FieldLevelVisuals : byte { NoLevel, On, OneField, MultipleFields, }
412
0.799049
1
0.799049
game-dev
MEDIA
0.81229
game-dev
0.883542
1
0.883542
bloombloombloom/Bloom
3,772
src/DebugToolDrivers/Protocols/RiscVDebug/TriggerModule/Registers/MatchControl.hpp
#pragma once #include <cstdint> #include <optional> #include "src/DebugToolDrivers/Protocols/RiscVDebug/TriggerModule/TriggerModule.hpp" namespace DebugToolDrivers::Protocols::RiscVDebug::TriggerModule::Registers { struct MatchControl { enum class MatchMode: std::uint8_t { EQUAL = 0x00, TOP_BITS = 0x01, GREATER_THAN = 0x02, LESS_THAN = 0x03, MASK_LOW = 0x04, MASK_HIGH = 0x05, NOT_EQUAL = 0x08, NOT_TOP_BITS = 0x09, NOT_MASK_LOW = 0x0C, NOT_MASK_HIGH = 0x0D, }; enum class AccessSize: std::uint8_t { ANY = 0x00, SIZE_8 = 0x01, SIZE_16 = 0x02, SIZE_32 = 0x03, }; enum class CompareValueType: std::uint8_t { ADDRESS = 0x00, DATA = 0x01, }; bool load = false; bool store = false; bool execute = false; bool enabledInUserMode = false; bool enabledInSupervisorMode = false; bool enabledInMachineMode = false; MatchMode matchMode = MatchMode::EQUAL; bool chain = false; // TODO: Consider making this an enum TriggerAction action = TriggerAction::RAISE_BREAKPOINT_EXCEPTION; AccessSize accessSize = AccessSize::ANY; bool timing = false; // TODO: Consider making this an enum CompareValueType compareValueType = CompareValueType::ADDRESS; bool hit = false; static constexpr auto fromValue(RegisterValue value) { return MatchControl{ .load = static_cast<bool>(value & 0x01), .store = static_cast<bool>(value & (0x01 << 1)), .execute = static_cast<bool>(value & (0x01 << 2)), .enabledInUserMode = static_cast<bool>(value & (0x01 << 3)), .enabledInSupervisorMode = static_cast<bool>(value & (0x01 << 4)), .enabledInMachineMode = static_cast<bool>(value & (0x01 << 6)), .matchMode = static_cast<MatchMode>((value >> 7) & 0x0F), .chain = static_cast<bool>(value & (0x01 << 11)), .action = static_cast<TriggerAction>((value >> 12) & 0x0F), .accessSize = static_cast<AccessSize>( (((value >> 21) & 0x03) << 2) | ((value >> 16) & 0x03) ), .timing = static_cast<bool>(value & (0x01 << 18)), .compareValueType = static_cast<CompareValueType>((value >> 19) & 0x01), .hit = static_cast<bool>(value & (0x01 << 20)), }; } [[nodiscard]] constexpr RegisterValue value() const { return RegisterValue{0} | static_cast<RegisterValue>(this->load) | static_cast<RegisterValue>(this->store) << 1 | static_cast<RegisterValue>(this->execute) << 2 | static_cast<RegisterValue>(this->enabledInUserMode) << 3 | static_cast<RegisterValue>(this->enabledInSupervisorMode) << 4 | static_cast<RegisterValue>(this->enabledInMachineMode) << 6 | static_cast<RegisterValue>(this->matchMode) << 7 | static_cast<RegisterValue>(this->chain) << 11 | static_cast<RegisterValue>(this->action) << 12 | (static_cast<RegisterValue>(this->accessSize) & 0x03) << 16 | static_cast<RegisterValue>(this->timing) << 18 | static_cast<RegisterValue>(this->compareValueType) << 19 | static_cast<RegisterValue>(this->hit) << 20 | (static_cast<RegisterValue>(this->accessSize) >> 2) << 21 ; } }; }
412
0.942065
1
0.942065
game-dev
MEDIA
0.571246
game-dev
0.870218
1
0.870218
nftport/sample-unity3D-nft-metaverse-template
1,089
Assets/WebGLSupport/WebGLInput/Wrapper/IInputField.cs
using UnityEngine; using UnityEngine.UI; namespace WebGLSupport { public enum ContentType { Standard = 0, Autocorrected = 1, IntegerNumber = 2, DecimalNumber = 3, Alphanumeric = 4, Name = 5, EmailAddress = 6, Password = 7, Pin = 8, Custom = 9 } public enum LineType { SingleLine = 0, MultiLineSubmit = 1, MultiLineNewline = 2 } public interface IInputField { ContentType contentType { get; } LineType lineType { get; } int fontSize { get; } string text { get; set; } string placeholder { get; } int characterLimit { get; } int caretPosition { get; } bool isFocused { get; } int selectionFocusPosition { get; set; } int selectionAnchorPosition { get; set; } bool ReadOnly { get; } bool OnFocusSelectAll { get; } RectTransform RectTransform(); void ActivateInputField(); void DeactivateInputField(); void Rebuild(); } }
412
0.921598
1
0.921598
game-dev
MEDIA
0.289598
game-dev
0.979532
1
0.979532
mistertaftcreates/Godot_match_3
1,055
Bug Fixing and Structure 1/Scripts/slime_holder.gd
extends Node2D signal remove_slime # board values var slime_pieces = [] var width = 8 var height = 10 var slime = preload("res://Scenes/slime.tscn") func _ready(): pass func make_2d_array(): var array = []; for i in width: array.append([]); for j in height: array[i].append(null); return array; func _on_grid_make_slime(board_position): if slime_pieces.size() == 0: slime_pieces = make_2d_array() var current = slime.instance() add_child(current) current.position = Vector2(board_position.x * 64 + 64, -board_position.y * 64 + 800) slime_pieces[board_position.x][board_position.y] = current func _on_grid_damage_slime(board_position): if slime_pieces.size() != 0: if slime_pieces[board_position.x][board_position.y]: slime_pieces[board_position.x][board_position.y].take_damage(1) if slime_pieces[board_position.x][board_position.y].health <= 0: slime_pieces[board_position.x][board_position.y].queue_free() slime_pieces[board_position.x][board_position.y] = null emit_signal("remove_slime", board_position)
412
0.826146
1
0.826146
game-dev
MEDIA
0.908523
game-dev
0.830734
1
0.830734
google/syzkaller
3,797
prog/heatmap_test.go
// Copyright 2022 syzkaller project authors. All rights reserved. // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. package prog import ( "math/rand" "sort" "testing" "github.com/google/syzkaller/pkg/image" "github.com/google/syzkaller/pkg/testutil" ) func TestGenericHeatmap(t *testing.T) { t.Parallel() // A test case is some data with the regions the heatmap is permitted to choose. testData := []struct { data []byte regions []region }{ { // Normal usage test. []byte( "4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh" + "4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh" + "4eHh4eHh4eHh4eHh4Q5GTbHh4eHh4eHh4eHh4eHhcOHh4eHh4eHh4eHh4eHh4eHh4eHh4eEfNuHh4XPh" + "4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHjd+GRzcLh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh" + "4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4dpiSwpoReHh4eHh4eHh4eHh4eHh4eHh4eHh" + "4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4bGfM+Hh4eHh4eHh4eHh4eHh4eHh4eHh4eHh" + "4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh" + "4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh" + "4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh" + "mpNKOZnS4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh" + "4eHh4eHh4eHh4eHh4eHh4Q=="), []region{{128, 384}, {512, 576}}, }, { // Test all constant bytes, i.e. falling back to uniform selection. []byte( "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"), []region{{0, 324}}, // Anywhere in the data. }, } const tries = 10 iters := testutil.IterCount() / tries r := rand.New(testutil.RandSource(t)) for _, test := range testData { data, err := image.DecodeB64(test.data) if err != nil { t.Fatalf("bad decode: %v", err) } for i := 0; i < iters; i++ { hm := MakeGenericHeatmap(data, r).(*GenericHeatmap) for j := 0; j < tries; j++ { index := hm.ChooseLocation() if !checkIndex(index, len(data), test.regions) { hm.debugPrint(t, data, test.regions) t.Fatalf("selected index %d does not fall in a region", index) } } } } } // Check an index is within some regions. func checkIndex(index, maxIndex int, regions []region) bool { if index < 0 || index >= maxIndex { return false } for _, region := range regions { if region.start <= index && index < region.end { return true } } return false } type region struct { start int end int } func (hm *GenericHeatmap) debugPrint(t *testing.T, data []byte, regions []region) { // Print data. t.Logf("data: len = %d", len(data)) for j := 0; j < len(data); j += granularity { end := min(j+granularity, len(data)) t.Logf("%8d: %x", j*granularity, data[j:end]) } t.Log("\n") // Print selected regions in data. sort.Slice(regions, func(i, j int) bool { return regions[i].start < regions[j].start }) for j, region := range regions { t.Logf("region %4d: %8v - %8v", j, region.start, region.end) } t.Log("\n") // Print heatmap. t.Logf("generic heatmap (total segment length %d)", hm.length) for j, seg := range hm.segments { t.Logf("segment %4d: %8v - %8v", j, seg.offset, seg.offset+seg.length) } t.Log("\n\n\n") }
412
0.505221
1
0.505221
game-dev
MEDIA
0.34772
game-dev
0.614797
1
0.614797
Grimrukh/SoulsAI
1,676
ai_scripts/aiCommon/approach_setting_direction.lua
REGISTER_GOAL(GOAL_COMMON_ApproachSettingDirection, "ApproachSettingDirection") REGISTER_DBG_GOAL_PARAM(GOAL_COMMON_ApproachSettingDirection, 0, "ړΏ", 0) REGISTER_DBG_GOAL_PARAM(GOAL_COMMON_ApproachSettingDirection, 1, "B苗", 0) REGISTER_DBG_GOAL_PARAM(GOAL_COMMON_ApproachSettingDirection, 2, "Ώ", 0) REGISTER_DBG_GOAL_PARAM(GOAL_COMMON_ApproachSettingDirection, 3, "?", 0) REGISTER_DBG_GOAL_PARAM(GOAL_COMMON_ApproachSettingDirection, 4, "K[hEzStateԍ", 0) REGISTER_DBG_GOAL_PARAM(GOAL_COMMON_ApproachSettingDirection, 5, "ړ", 0) REGISTER_DBG_GOAL_PARAM(GOAL_COMMON_ApproachSettingDirection, 6, "wւ̋", 0) REGISTER_GOAL_NO_UPDATE(GOAL_COMMON_ApproachSettingDirection, true) REGISTER_GOAL_NO_INTERUPT(GOAL_COMMON_ApproachSettingDirection, true) function ApproachSettingDirection_Activate(ai, goal) local life_time = goal:GetLife() local targetType = goal:GetParam(0) local range = goal:GetParam(1) local turnTarget = goal:GetParam(2) local bWalk = goal:GetParam(3) local guardActionId = goal:GetParam(4) local moveTargetType = goal:GetParam(5) local distDir = goal:GetParam(6) goal:AddSubGoal(GOAL_COMMON_MoveToSomewhere, life_time, targetType, moveTargetType, range, turnTarget, bWalk, moveTargetType, distDir) if 0 < guardActionId then local targetDist = ai:GetDist(targetType) if range < targetDist then ai:DoEzAction(life_time, guardActionId) end end return end function ApproachSettingDirection_Update(ai, goal, dT) return end function ApproachSettingDirection_Terminate(ai, goal) return end function ApproachSettingDirection_Interupt(ai, goal) return false end return
412
0.781321
1
0.781321
game-dev
MEDIA
0.372504
game-dev
0.875075
1
0.875075
Danilo1301/GTASA_libModPolicia
27,470
ModPolicia/ModConfig.cpp
#include "ModConfig.h" #include <iostream> #include <fstream> #include <sys/stat.h> //#include <dirent.h> //#include "dlfcn.h" #include "mod/amlmod.h" #include "mod/logger.h" #include "mod/config.h" #include "iniconfig/INIFile.h" #include "menu/Window.h" #include "Mod.h" #include "Log.h" #include "Ped.h" #include "Vehicle.h" #include "Callouts.h" #include "Backup.h" #include "Trunk.h" #include "PoliceDepartment.h" #include "Stats.h" #include "Chase.h" #include "Pullover.h" #include "Ambulance.h" #include "systems/Names.h" #include "systems/Camera.h" #include "systems/BikePickpocket.h" #include "windows/WindowRadio.h" extern IMenuVSL* menuVSL; bool isDirExist(const std::string& path) { struct stat info; if (stat(path.c_str(), &info) != 0) { return false; } return (info.st_mode & S_IFDIR) != 0; } bool file_exists(const std::string& name) { std::ifstream f(name.c_str()); return f.good(); } std::vector<std::string> get_directories_name(const std::string& s) { std::vector<std::string> r; for (auto& p : std::filesystem::directory_iterator(s)) if (p.is_directory()) r.push_back(p.path().filename().string()); return r; } std::vector<std::string> get_files_name(const std::string& s) { std::vector<std::string> r; for (auto& p : std::filesystem::directory_iterator(s)) if (!p.is_directory()) r.push_back(p.path().filename().string()); return r; } // std::vector<VersionInfo*> VersionControl::m_Versions; std::string VersionControl::m_PrevVersion = ""; std::string VersionControl::m_CurrentVersion = ""; void VersionControl::SetVersion(std::string prevVersion, std::string currentVersion) { m_PrevVersion = prevVersion; m_CurrentVersion = currentVersion; } void VersionControl::AddVersion(std::string version) { VersionInfo* info = new VersionInfo(); info->version = version; m_Versions.push_back(info); } VersionInfo* VersionControl::GetVersionInfo(std::string version) { for(auto info : m_Versions) { if(info->version == version) return info; } return NULL; } void VersionControl::AddPatch(std::string version, std::function<void()> patch) { VersionInfo* info = GetVersionInfo(version); info->patches.push_back(patch); } void VersionControl::AddPatch(std::function<void()> patch) { for(auto info : m_Versions) { info->patches.push_back(patch); } } void VersionControl::ApplyPatches() { Log::Level(LOG_LEVEL::LOG_BOTH) << "VersionControl: ApplyPatches" << std::endl; auto prevVersion = m_PrevVersion; VersionInfo* prevInfo = NULL; if(prevVersion == m_CurrentVersion) { Log::Level(LOG_LEVEL::LOG_BOTH) << "VersionControl: Same version, no need to apply patches" << std::endl; return; } if(prevVersion == "unknown") { Log::Level(LOG_LEVEL::LOG_BOTH) << "VersionControl: Version is unknown, so its the first time run, no need to apply patches" << std::endl; return; } int index = 0; for(auto info : m_Versions) { if(info->version == prevVersion) { prevInfo = info; break; } index++; } while (index < m_Versions.size() - 1) { prevInfo = m_Versions[index]; Log::Level(LOG_LEVEL::LOG_BOTH) << "VersionControl: Processing index " << index << ", version " << prevInfo->version << std::endl; if(prevInfo->patches.size() > 0) { Log::Level(LOG_LEVEL::LOG_BOTH) << "VersionControl: Applying " << prevInfo->patches.size() << " patches..." << std::endl; } for(auto patch : prevInfo->patches) { patch(); } prevInfo->patches.clear(); index++; } } // std::string ModConfig::m_ConfigMainFolderName = "modPolicia"; bool ModConfig::EnableTestMenu = false; bool ModConfig::CreateTestOptionsInRadioMenu = false; bool ModConfig::EnableModWhenGameStarts = false; bool ModConfig::StartGameWithRadio = false; bool ModConfig::DrawInfoAbovePed = true; CVector2D ModConfig::MenuDefaultPosition = CVector2D(400, 200); void ModConfig::MakePaths() { CreateFolder(GetConfigFolder()); CreateFolder(GetConfigFolder() + "/data"); CreateFolder(GetConfigFolder() + "/data/bases"); CreateFolder(GetConfigFolder() + "/assets"); CreateFolder(GetConfigFolder() + "/audios"); } bool ModConfig::DirExists(std::string path) { return isDirExist(path); } bool ModConfig::FileExists(std::string path) { return file_exists(path); } std::vector<std::string> ModConfig::GetDirectoriesName(std::string path) { return get_directories_name(path); } std::vector<std::string> ModConfig::GetFilesName(std::string path) { return get_files_name(path); } void ModConfig::ConfigDelete(std::string path) { try { if (std::filesystem::remove(path)) Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: file " << path << " deleted" << std::endl; else Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: file " << path << " not found" << std::endl; } catch(const std::filesystem::filesystem_error& err) { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: delete file: filesystem error: " << err.what() << std::endl; } } std::string ModConfig::GetConfigFolder() { char path[0xFF]; snprintf(path, sizeof(path), "%s/%s", aml->GetConfigPath(), m_ConfigMainFolderName.c_str()); return path; } void ModConfig::CreateFolder(std::string path) { if (DirExists(path)) return; Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: CreateFolder " << path << std::endl; mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } void ModConfig::WriteToFile(std::string path, Json::Value value) { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: WriteToFile " << path << std::endl; Json::StyledWriter writer; std::string strJson = writer.write(value); std::ofstream file(path); file << strJson; file.close(); } Json::Value ModConfig::ReadFile(std::string path) { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: ReadFile " << path << std::endl; std::ifstream file(path); Json::Value value; Json::Reader reader; if (!reader.parse(file, value, true)) { //MessageBox(HWND_DESKTOP, std::string("Error loading " + path).c_str(), "GiroflexVSL", MB_ICONERROR); } return value; } void ModConfig::Save() { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: Save" << std::endl; MakePaths(); SaveSettings(); } void ModConfig::SaveSettings() { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: SaveSettings (settings.ini)" << std::endl; auto settingsFileDir = GetConfigFolder() + "/settings.ini"; INIFile file; auto generalSection = file.AddSection("General"); generalSection->AddLine(""); generalSection->AddLine("; Enables the test options in the radio menu"); generalSection->AddLine("; 0 = disabled | 1 = enabled"); generalSection->AddIntFromBool("enable_test_options_in_radio_menu", ModConfig::CreateTestOptionsInRadioMenu); generalSection->AddLine(""); generalSection->AddLine("; Starts the game with mod enabled"); generalSection->AddLine("; 0 = starts disabled | 1 = starts enabled"); generalSection->AddIntFromBool("enable_mod_when_game_starts", ModConfig::EnableModWhenGameStarts); generalSection->AddLine(""); generalSection->AddInt("time_between_callouts", Callouts::m_TimeBetweenCallouts); generalSection->AddInt("callout_message_duration", Callouts::CALLOUT_MESSAGE_DURATION); generalSection->AddInt("money_reward", PoliceDepartment::m_MoneyReward); generalSection->AddIntFromBool("enable_deep_log", Log::deepLogEnabled); generalSection->AddIntFromBool("pullover_play_animation", Pullover::PULLOVER_PLAY_ANIMATION); generalSection->AddIntFromBool("start_game_with_radio", ModConfig::StartGameWithRadio); generalSection->AddIntFromBool("draw_info_above_ped", ModConfig::DrawInfoAbovePed); generalSection->AddIntFromBool("transparent_radio_buttons", WindowRadio::m_TransparentButtons); generalSection->AddLine(""); generalSection->AddLine("; Distance that Ambulance and IML will spawn"); generalSection->AddFloat("spawn_emergency_vehicles_distance", Ambulance::SPAWN_EMERGENCY_VEHICLES_DISTANCE); generalSection->AddLine(""); generalSection->AddFloat("chase_vehicle_max_speed", Chase::CHASE_VEHICLE_MAX_SPEED); generalSection->AddFloat("time_between_bike_pickpockets", BikePickpocket::m_TimeBetweenPickpockets); generalSection->AddInt("iml_vehicle_id", Ambulance::m_IMLSystem->m_VehicleModelId); // auto chancesSection = file.AddSection("Chances"); chancesSection->AddFloat("CHANCE_PED_FORGETTING_DOCUMENTS_AT_HOME", Ped::CHANCE_PED_FORGETTING_DOCUMENTS_AT_HOME); chancesSection->AddFloat("CHANCE_PED_BEEING_DRUG_DEALER", Ped::CHANCE_PED_BEEING_DRUG_DEALER); chancesSection->AddFloat("CHANCE_PED_CONSUME_DRUGS", Ped::CHANCE_PED_CONSUME_DRUGS); chancesSection->AddFloat("CHANCE_PED_HAVING_EXPIRED_DRIVER_LICENSE", Ped::CHANCE_PED_HAVING_EXPIRED_DRIVER_LICENSE); chancesSection->AddFloat("CHANCE_PED_BEEING_WANTED", Ped::CHANCE_PED_BEEING_WANTED); chancesSection->AddFloat("CHANCE_VEHICLE_DECIDE_NOT_TO_RUN_AWAY", Vehicle::CHANCE_VEHICLE_DECIDE_NOT_TO_RUN_AWAY); chancesSection->AddFloat("CHANCE_VEHICLE_BEEING_STOLEN", Vehicle::CHANCE_VEHICLE_BEEING_STOLEN); // auto windowSection = file.AddSection("Window"); windowSection->AddFloat("position_x", Window::m_DefaultWindowPosition.x); windowSection->AddFloat("position_y", Window::m_DefaultWindowPosition.y); // auto cameraSection = file.AddSection("Camera"); cameraSection->AddCVector2D("position", Camera::m_Position); cameraSection->AddCVector2D("size", Camera::m_Size); auto menuSection = file.AddSection("Menu"); menuSection->AddCVector2D("position", ModConfig::MenuDefaultPosition); // file.Save(settingsFileDir); file.Destroy(); SaveDataSettings(); } void ModConfig::SaveDataSettings() { auto dataDir = GetConfigFolder() + "/data/"; //backupFile INIFile backupFile; for(auto backupVehicle : Backup::m_DataBackupVehicles) { auto backupSection = backupFile.AddSection("Backup_" + std::to_string(backupVehicle.vehicleModelId)); backupSection->AddInt("num_peds", backupVehicle.numPeds); backupSection->AddInt("weapon_id", backupVehicle.weaponId); } backupFile.Save(dataDir + "backup.ini"); backupFile.Destroy(); //trunk INIFile trunkFile; for(auto pair : Trunk::m_TrunkModels) { auto modelId = pair.first; auto trunkModelData = &pair.second; auto backupSection = trunkFile.AddSection("Trunk_" + std::to_string(modelId)); backupSection->AddCVector("position1", trunkModelData->trunkPositions[0]); backupSection->AddCVector("position2", trunkModelData->trunkPositions[1]); } trunkFile.Save(dataDir + "trunk.ini"); trunkFile.Destroy(); //pickups INIFile pickupsFile; auto pickupsSection = pickupsFile.AddSection("PICKUPS"); pickupsSection->AddInt("pickup_equipment_model_id", PoliceDepartment::m_PickupEquipmentId); pickupsSection->AddInt("pickup_duty_id", PoliceDepartment::m_PickupDutyId); pickupsSection->AddInt("pickup_partner_model_id", PoliceDepartment::m_PickupPartnerId); pickupsFile.Save(dataDir + "pickups.ini"); pickupsFile.Destroy(); //barriers INIFile barriersFile; auto barriersSection = barriersFile.AddSection("BARRIERS"); barriersSection->AddInt("barrier_roadblock_ped_id", Chase::m_BarrierModels[0].pedModelId); barriersSection->AddInt("barrier_roadblock_vehicle_id", Chase::m_BarrierModels[0].vehicleModelId); barriersSection->AddInt("barrier_spikes_ped_id", Chase::m_BarrierModels[1].pedModelId); barriersSection->AddInt("barrier_spikes_vehicle_id", Chase::m_BarrierModels[1].vehicleModelId); barriersFile.Save(dataDir + "barriers.ini"); barriersFile.Destroy(); } void ModConfig::SaveStats() { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: SaveStats (data/stats.ini)" << std::endl; auto dir = GetConfigFolder() + "/data/stats.ini"; INIFile file; auto section = file.AddSection("STATS"); section->AddInt("times_opened_game", Stats::TimesOpenedGame); section->AddInt("time_played", Stats::TimePlayed); file.Save(dir); file.Destroy(); } void ModConfig::Load() { MakePaths(); LoadSettings(); LoadStats(); PoliceDepartment::LoadBases(); InventoryItems::LoadItems(); auto languagesFolder = GetConfigFolder() + "/languages/"; menuVSL->LoadLanguagesFolder(languagesFolder); Names::Load(); } void ModConfig::LoadSettings() { auto settingsFileDir = GetConfigFolder() + "/settings.ini"; Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: LoadSettings (settings.ini)" << std::endl; if(ModConfig::FileExists(settingsFileDir)) { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: Settings file exists" << std::endl; } else { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: Settings file doesn't exist" << std::endl; } INIFile file; if (!file.Read(settingsFileDir)) { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: Error reading settings.ini (Not found)" << std::endl; return; } for(auto section : file.sections) { Log::Level(LOG_LEVEL::LOG_BOTH) << "Section: " << section->key << " has " << section->values.size() << " values" << std::endl; /* for(auto value : section->values) { Log::Level(LOG_LEVEL::LOG_BOTH) << value.first << "|" << value.second << std::endl; } */ } auto generalSections = file.GetSections("General"); if (generalSections.size() > 0) { auto generalSection = generalSections[0]; generalSection->GetBoolFromInt("enable_test_options_in_radio_menu", &ModConfig::CreateTestOptionsInRadioMenu); generalSection->GetBoolFromInt("enable_mod_when_game_starts", &ModConfig::EnableModWhenGameStarts); generalSection->GetInt("time_between_callouts", &Callouts::m_TimeBetweenCallouts); generalSection->GetInt("callout_message_duration", &Callouts::CALLOUT_MESSAGE_DURATION); generalSection->GetInt("money_reward", &PoliceDepartment::m_MoneyReward); generalSection->GetBoolFromInt("enable_deep_log", &Log::deepLogEnabled); generalSection->GetBoolFromInt("pullover_play_animation", &Pullover::PULLOVER_PLAY_ANIMATION); generalSection->GetBoolFromInt("start_game_with_radio", &ModConfig::StartGameWithRadio); generalSection->GetBoolFromInt("draw_info_above_ped", &ModConfig::DrawInfoAbovePed); generalSection->GetBoolFromInt("transparent_radio_buttons", &WindowRadio::m_TransparentButtons); generalSection->GetFloat("spawn_emergency_vehicles_distance", &Ambulance::SPAWN_EMERGENCY_VEHICLES_DISTANCE); generalSection->GetFloat("chase_vehicle_max_speed", &Chase::CHASE_VEHICLE_MAX_SPEED); generalSection->GetFloat("time_between_bike_pickpockets", &BikePickpocket::m_TimeBetweenPickpockets); generalSection->GetInt("iml_vehicle_id", &Ambulance::m_IMLSystem->m_VehicleModelId); } // auto chancesSections = file.GetSections("Chances"); if (chancesSections.size() > 0) { auto chancesSection = chancesSections[0]; chancesSection->GetFloat("CHANCE_PED_FORGETTING_DOCUMENTS_AT_HOME", &Ped::CHANCE_PED_FORGETTING_DOCUMENTS_AT_HOME); chancesSection->GetFloat("CHANCE_PED_BEEING_DRUG_DEALER", &Ped::CHANCE_PED_BEEING_DRUG_DEALER); chancesSection->GetFloat("CHANCE_PED_CONSUME_DRUGS", &Ped::CHANCE_PED_CONSUME_DRUGS); chancesSection->GetFloat("CHANCE_PED_HAVING_EXPIRED_DRIVER_LICENSE", &Ped::CHANCE_PED_HAVING_EXPIRED_DRIVER_LICENSE); chancesSection->GetFloat("CHANCE_PED_BEEING_WANTED", &Ped::CHANCE_PED_BEEING_WANTED); chancesSection->GetFloat("CHANCE_VEHICLE_DECIDE_NOT_TO_RUN_AWAY", &Vehicle::CHANCE_VEHICLE_DECIDE_NOT_TO_RUN_AWAY); chancesSection->GetFloat("CHANCE_VEHICLE_BEEING_STOLEN", &Vehicle::CHANCE_VEHICLE_BEEING_STOLEN); } // auto windowSections = file.GetSections("Window"); if (windowSections.size() > 0) { auto windowSection = windowSections[0]; windowSection->GetFloat("position_x", &Window::m_DefaultWindowPosition.x); windowSection->GetFloat("position_y", &Window::m_DefaultWindowPosition.y); } auto cameraSections = file.GetSections("Camera"); if (cameraSections.size() > 0) { auto cameraSection = cameraSections[0]; cameraSection->GetCVector2D("position", &Camera::m_Position); cameraSection->GetCVector2D("size", &Camera::m_Size); } auto menuSections = file.GetSections("Menu"); if (menuSections.size() > 0) { auto menuSection = menuSections[0]; menuSection->GetCVector2D("position", &ModConfig::MenuDefaultPosition); } Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: Success reading settings.ini" << std::endl; LoadDataSettings(); } void ModConfig::LoadDataSettings() { auto dataDir = GetConfigFolder() + "/data/"; INIFile backupFile; if (backupFile.Read(dataDir + "backup.ini")) { for(auto& backupVehicle : Backup::m_DataBackupVehicles) { std::string backupSectionName = "Backup_" + std::to_string(backupVehicle.vehicleModelId); auto sections = backupFile.GetSections(backupSectionName); if (sections.size() > 0) { auto section = sections[0]; section->GetInt("num_peds", &backupVehicle.numPeds); section->GetInt("weapon_id", &backupVehicle.weaponId); Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: Loaded " << backupSectionName << std::endl; } } } else { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: Error reading backup.ini (Not found)" << std::endl; } INIFile trunkFile; if (trunkFile.Read(dataDir + "trunk.ini")) { for(auto pair : Trunk::m_TrunkModels) { auto modelId = pair.first; auto trunkModelData = &Trunk::m_TrunkModels[modelId]; std::string sectionName = "Trunk_" + std::to_string(modelId); auto sections = trunkFile.GetSections(sectionName); if (sections.size() > 0) { auto section = sections[0]; section->GetCVector("position1", &trunkModelData->trunkPositions[0]); section->GetCVector("position2", &trunkModelData->trunkPositions[1]); Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: Loaded " << sectionName << std::endl; } } } else { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: Error reading trunk.ini (Not found)" << std::endl; } INIFile pickupFile; if (pickupFile.Read(dataDir + "pickups.ini")) { auto sections = pickupFile.GetSections("PICKUPS"); auto section = sections[0]; section->GetInt("pickup_equipment_model_id", &PoliceDepartment::m_PickupEquipmentId); section->GetInt("pickup_duty_id", &PoliceDepartment::m_PickupDutyId); section->GetInt("pickup_partner_model_id", &PoliceDepartment::m_PickupPartnerId); } else { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: Error reading pickups.ini (Not found)" << std::endl; } INIFile barriersFile; if (barriersFile.Read(dataDir + "barriers.ini")) { auto sections = barriersFile.GetSections("BARRIERS"); auto section = sections[0]; section->GetInt("barrier_roadblock_ped_id", &Chase::m_BarrierModels[0].pedModelId); section->GetInt("barrier_roadblock_vehicle_id", &Chase::m_BarrierModels[0].vehicleModelId); section->GetInt("barrier_spikes_ped_id", &Chase::m_BarrierModels[1].pedModelId); section->GetInt("barrier_spikes_vehicle_id", &Chase::m_BarrierModels[1].vehicleModelId); } else { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: Error reading barriers.ini (Not found)" << std::endl; } } void ModConfig::LoadStats() { auto dir = GetConfigFolder() + "/data/stats.ini"; INIFile file; if (!file.Read(dir)) { Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: Error reading stats.ini (Not found)" << std::endl; return; } auto sections = file.GetSections("STATS"); if (sections.size() > 0) { auto section = sections[0]; section->GetInt("times_opened_game", &Stats::TimesOpenedGame); section->GetInt("time_played", &Stats::TimePlayed); } } std::string ModConfig::ReadVersionFile() { std::string prevVersion = "unknown"; std::string path = GetConfigFolder() + "/version"; std::ifstream file; file.open(path); if (file.good()) { getline(file, prevVersion); } file.close(); Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: ReadVersionFile, version: " << prevVersion << std::endl; return prevVersion; } void ModConfig::DefineVersions() { if(VersionControl::m_Versions.size() > 0) return; VersionControl::AddVersion("0.1.0"); VersionControl::AddVersion("0.2.0"); VersionControl::AddVersion("0.3.0"); VersionControl::AddVersion("0.3.1"); VersionControl::AddVersion("0.4.0"); VersionControl::AddVersion("0.4.1"); VersionControl::AddVersion("0.5.0"); VersionControl::AddVersion("0.6.0"); VersionControl::AddVersion("0.7.0"); VersionControl::AddVersion("1.0.0"); VersionControl::AddVersion("1.0.1"); VersionControl::AddVersion("1.0.2"); VersionControl::AddVersion("1.1.0"); VersionControl::AddVersion("1.2.0"); VersionControl::AddVersion("1.3.0"); VersionControl::AddVersion("1.4.0"); VersionControl::AddVersion("1.4.1"); VersionControl::AddVersion("1.5.0"); VersionControl::AddVersion("1.6.0"); VersionControl::AddVersion("1.6.1"); VersionControl::AddVersion("1.6.2"); VersionControl::AddVersion("1.6.3"); VersionControl::AddVersion("1.6.4"); VersionControl::AddVersion("1.6.5"); VersionControl::AddVersion("1.7.0"); VersionControl::AddVersion("1.8.0"); VersionControl::AddVersion("1.9.0"); VersionControl::AddVersion("1.9.1"); VersionControl::AddVersion("1.9.2"); VersionControl::AddVersion("1.9.3"); VersionControl::SetVersion(ReadVersionFile(), GetModVersion()); } void ModConfig::ProcessVersionChanges_PreConfigLoad() { std::string prevVersion = ReadVersionFile(); std::string currentVersion = GetModVersion(); Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: [PRE] Updating from " << prevVersion << " to " << currentVersion << std::endl; VersionControl::AddPatch( [] () { Log::Level(LOG_LEVEL::LOG_BOTH) << "Patch (Audios) PRE" << std::endl; std::vector<std::string> oldAudios = { "HELI_APPROACHING_DISPATCH_1.wav", "HELI_APPROACHING_DISPATCH_2.wav", "HELI_NO_VISUAL_DISPATCH_1.wav", "HELI_NO_VISUAL_DISPATCH_2.wav", "REQUEST_BACKUP_BIKE_1.wav", "REQUEST_BACKUP_BIKE_2.wav", "REQUEST_BACKUP_FBI_1.wav", "REQUEST_BACKUP_FBI_2.wav", "REQUEST_BACKUP_HELI_1.wav", "REQUEST_BACKUP_HELI_2.wav", "REQUEST_BACKUP_LS_1.wav", "REQUEST_BACKUP_LS_2.wav", "REQUEST_BACKUP_LV_1.wav", "REQUEST_BACKUP_LV_2.wav", "REQUEST_BACKUP_RANGER_1.wav", "REQUEST_BACKUP_RANGER_2.wav", "REQUEST_BACKUP_SF_1.wav", "REQUEST_BACKUP_SF_2.wav", "REQUEST_BACKUP_SWAT_1.wav", "REQUEST_BACKUP_SWAT_2.wav", "UNIT_RESPONDING_DISPATCH_1.wav", "UNIT_RESPONDING_DISPATCH_2.wav", "UNIT_RESPONDING_DISPATCH_3.wav", "UNIT_RESPONDING_DISPATCH_4.wav", "SPIKES_DEPLOYED_1.wav", "SPIKES_DEPLOYED_2.wav", "SPIKES_DEPLOYED_3.wav", "SPIKES_DEPLOYED_4.wav", "SPIKES_DEPLOYED_5.wav", "REQUEST_ROADBLOCK_1.wav", "ASK_STOP_PEDESTRIAN.wav", "ASK_STOP_VEHICLE.wav", "ACCEPT_CALLOUT.wav", "PULLOVER_FREE_PED.wav", "ASK_FOR_DRIVERS_LICENSE.wav", //edited "ASK_FOR_ID.wav", //edited "CHECK_ID.wav", //edited "CHECK_VEHICLE_PLATE.wav", //editado "ID_OK.wav", //edited "ID_WITH_ARREST_WARRANT.wav", //edited "REQUEST_AMBULANCE.wav", //edited "REQUEST_CAR_TO_TRANSPORT_SUSPECT.wav", //edited "REQUEST_IML.wav", //edited "REQUEST_TOW_TRUCK.wav", //edited "VEHICLE_PLATE_OK.wav", //edited "VEHICLE_PLATE_STOLEN.wav" //edited }; auto audiosPath = ModConfig::GetConfigFolder() + "/audios/"; auto unusedPath = audiosPath + "/unused_audios/"; CreateFolder(unusedPath); for(auto wavName : oldAudios) { auto path = audiosPath + "/voices/" + wavName; if(!FileExists(path)) continue; auto newPath = unusedPath + wavName; Log::Level(LOG_LEVEL::LOG_BOTH) << "Moving to unused: " << wavName << std::endl; try { std::filesystem::rename(path, newPath); } catch (std::filesystem::filesystem_error& e) { Log::Level(LOG_LEVEL::LOG_BOTH) << "Could not move. Error: " << e.what() << std::endl; } } auto files = get_files_name(unusedPath); Log::Level(LOG_LEVEL::LOG_BOTH) << files.size() << " files in /unused_audios/" << std::endl; if(files.size() == 0) { ModConfig::ConfigDelete(unusedPath); } }); VersionControl::ApplyPatches(); } void ModConfig::ProcessVersionChanges_PostConfigLoad() { std::string prevVersion = ReadVersionFile(); std::string currentVersion = GetModVersion(); Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: [POST] Updating from " << prevVersion << " to " << currentVersion << std::endl; //patches VersionControl::AddPatch("1.0.2", [] () { Log::Level(LOG_LEVEL::LOG_BOTH) << "Patch 1.0.2 POST" << std::endl; Ped::CHANCE_PED_BEEING_DRUG_DEALER = 0.2f; Ped::CHANCE_PED_CONSUME_DRUGS = 0.4f; }); VersionControl::AddPatch("1.4.1", [] () { Log::Level(LOG_LEVEL::LOG_BOTH) << "Patch 1.4.1 POST" << std::endl; Stats::TimePlayed = 0; }); VersionControl::AddPatch("1.6.0", [] () { Log::Level(LOG_LEVEL::LOG_BOTH) << "Patch 1.6.0 POST" << std::endl; Ped::CHANCE_PED_BEEING_DRUG_DEALER = 0.1f; Ped::CHANCE_PED_CONSUME_DRUGS = 0.2f; }); VersionControl::ApplyPatches(); // Log::Level(LOG_LEVEL::LOG_BOTH) << "ModConfig: Saving version file" << std::endl; std::string path = GetConfigFolder() + "/version"; std::fstream file; file.open(path, std::fstream::out); file << currentVersion; file.close(); } std::string ModConfig::GetModVersion() { DefineVersions(); return VersionControl::m_Versions[VersionControl::m_Versions.size() - 1]->version; }
412
0.994081
1
0.994081
game-dev
MEDIA
0.21455
game-dev
0.93805
1
0.93805
snjo/Firespitter
14,792
Firespitter/customization/FStextureSwitch2.cs
using System; using System.Collections.Generic; using System.Text; using UnityEngine; using Firespitter.info; namespace Firespitter.customization { public class FStextureSwitch2 : PartModule { [KSPField] public int moduleID = 0; [KSPField] public string textureRootFolder = string.Empty; [KSPField] public string objectNames = string.Empty; [KSPField] public string textureNames = string.Empty; [KSPField] public string mapNames = string.Empty; [KSPField] public string textureDisplayNames = "Default"; [KSPField] public string nextButtonText = "Next Texture"; [KSPField] public string prevButtonText = "Previous Texture"; [KSPField] public string statusText = "Current Texture"; [KSPField(isPersistant = true)] public int selectedTexture = 0; [KSPField(isPersistant = true)] public string selectedTextureURL = string.Empty; [KSPField(isPersistant = true)] public string selectedMapURL = string.Empty; [KSPField] public bool showListButton = false; [KSPField] public bool debugMode = false; [KSPField] public bool switchableInFlight = false; [KSPField] public string additionalMapType = "_BumpMap"; [KSPField] public bool mapIsNormal = true; [KSPField] public bool repaintableEVA = true; //[KSPField] //public Vector4 GUIposition = new Vector4(FSGUIwindowID.standardRect.x, FSGUIwindowID.standardRect.y, FSGUIwindowID.standardRect.width, FSGUIwindowID.standardRect.height); [KSPField] public bool showPreviousButton = true; [KSPField] public bool useFuelSwitchModule = false; [KSPField] public string fuelTankSetups = "0"; [KSPField] public bool showInfo = true; [KSPField] public bool updateSymmetry = true; private List<Transform> targetObjectTransforms = new List<Transform>(); private List<List<Material>> targetMats = new List<List<Material>>(); private List<String> texList = new List<string>(); private List<String> mapList = new List<string>(); private List<String> objectList = new List<string>(); private List<String> textureDisplayList = new List<string>(); private List<int> fuelTankSetupList = new List<int>(); private FSfuelSwitch fuelSwitch; private bool initialized = false; FSdebugMessages debug; [KSPField(guiActiveEditor = true, guiName = "Current Texture")] public string currentTextureName = string.Empty; [KSPEvent(guiActive = false, guiActiveEditor = false, guiName = "Debug: Log Objects")] public void listAllObjects() { List<Transform> childList = ListChildren(part.transform); foreach (Transform t in childList) { Debug.Log("object: " + t.name); } } List<Transform> ListChildren(Transform a) { List<Transform> childList = new List<Transform>(); foreach (Transform b in a) { childList.Add(b); childList.AddRange(ListChildren(b)); } return childList; } [KSPEvent(guiActive = false, guiActiveEditor = true, guiName = "Next Texture")] public void nextTextureEvent() { selectedTexture++; if (selectedTexture >= texList.Count && selectedTexture >= mapList.Count) selectedTexture = 0; useTextureAll(true); } [KSPEvent(guiActive = false, guiActiveEditor = true, guiName = "Previous Texture")] public void previousTextureEvent() { selectedTexture--; if (selectedTexture < 0) selectedTexture = Mathf.Max(texList.Count - 1, mapList.Count-1); useTextureAll(true); } [KSPEvent(guiActiveUnfocused = true, unfocusedRange = 5f, guiActive = false, guiActiveEditor = false, guiName = "Repaint")] public void nextTextureEVAEvent() { nextTextureEvent(); } public void useTextureAll(bool calledByPlayer) { applyTexToPart(calledByPlayer); if (updateSymmetry) { for (int i = 0; i < part.symmetryCounterparts.Count; i++) { // check that the moduleID matches to make sure we don't target the wrong tex switcher FStextureSwitch2[] symSwitch = part.symmetryCounterparts[i].GetComponents<FStextureSwitch2>(); for (int j = 0; j < symSwitch.Length; j++) { if (symSwitch[j].moduleID == moduleID) { symSwitch[j].selectedTexture = selectedTexture; symSwitch[j].applyTexToPart(calledByPlayer); } } } } } private void applyTexToPart(bool calledByPlayer) { initializeData(); foreach (List<Material> matList in targetMats) { foreach (Material mat in matList) { useTextureOrMap(mat); } } if (useFuelSwitchModule) { debug.debugMessage("calling on FSfuelSwitch tank setup " + selectedTexture); if (selectedTexture < fuelTankSetupList.Count) fuelSwitch.selectTankSetup(fuelTankSetupList[selectedTexture], calledByPlayer); else debug.debugMessage("no such fuel tank setup"); if (calledByPlayer && HighLogic.LoadedSceneIsFlight) { //Do a screeen message of what we just swapped to! var msg = string.Format("Converted Tank to {0}", textureDisplayList[selectedTexture]); ScreenMessages.PostScreenMessage(msg, 5f, ScreenMessageStyle.UPPER_CENTER); } } } public void useTextureOrMap(Material targetMat) { if (targetMat != null) { useTexture(targetMat); useMap(targetMat); } else { debug.debugMessage("No target material in object."); } } private void useMap(Material targetMat) { debug.debugMessage("maplist count: " + mapList.Count + ", selectedTexture: " + selectedTexture + ", texlist Count: " + texList.Count); if (mapList.Count > selectedTexture) { if (GameDatabase.Instance.ExistsTexture(mapList[selectedTexture])) { debug.debugMessage("map " + mapList[selectedTexture] + " exists in db"); targetMat.SetTexture(additionalMapType, GameDatabase.Instance.GetTexture(mapList[selectedTexture], mapIsNormal)); selectedMapURL = mapList[selectedTexture]; if (selectedTexture < textureDisplayList.Count && texList.Count == 0) { currentTextureName = textureDisplayList[selectedTexture]; debug.debugMessage("setting currentTextureName to " + textureDisplayList[selectedTexture]); } else { debug.debugMessage("not setting currentTextureName. selectedTexture is " + selectedTexture + ", texDispList count is" + textureDisplayList.Count + ", texList count is " + texList.Count); } } else { debug.debugMessage("map " + mapList[selectedTexture] + " does not exist in db"); } } else { if (mapList.Count > selectedTexture) // why is this check here? will never happen. debug.debugMessage("no such map: " + mapList[selectedTexture]); else { debug.debugMessage("useMap, index out of range error, maplist count: " + mapList.Count + ", selectedTexture: " + selectedTexture); for (int i = 0; i < mapList.Count; i++) { debug.debugMessage("map " + i + ": " + mapList[i]); } } } } private void useTexture(Material targetMat) { if (texList.Count > selectedTexture) { if (GameDatabase.Instance.ExistsTexture(texList[selectedTexture])) { debug.debugMessage("assigning texture: " + texList[selectedTexture]); targetMat.mainTexture = GameDatabase.Instance.GetTexture(texList[selectedTexture], false); selectedTextureURL = texList[selectedTexture]; if (selectedTexture > textureDisplayList.Count - 1) currentTextureName = getTextureDisplayName(texList[selectedTexture]); else currentTextureName = textureDisplayList[selectedTexture]; } else { debug.debugMessage("no such texture: " + texList[selectedTexture]); } } } public override string GetInfo() { if (showInfo) { List<string> variantList; if (textureNames.Length > 0) { variantList = Tools.parseNames(textureNames); } else { variantList = Tools.parseNames(mapNames); } textureDisplayList = Tools.parseNames(textureDisplayNames); StringBuilder info = new StringBuilder(); info.AppendLine("Alternate textures available:"); if (variantList.Count == 0) { if (variantList.Count == 0) info.AppendLine("None"); } for (int i = 0; i < variantList.Count; i++) { if (i > textureDisplayList.Count - 1) info.AppendLine(getTextureDisplayName(variantList[i])); else info.AppendLine(textureDisplayList[i]); } info.AppendLine("\nUse the Next Texture button on the right click menu."); return info.ToString(); } else return string.Empty; } private string getTextureDisplayName(string longName) { string[] splitString = longName.Split('/'); return splitString[splitString.Length - 1]; } public override void OnStart(PartModule.StartState state) { initializeData(); useTextureAll(false); if (switchableInFlight) Events["nextTextureEvent"].guiActive = true; if (switchableInFlight && showPreviousButton) Events["previousTextureEvent"].guiActive = true; if (showListButton) Events["listAllObjects"].guiActiveEditor = true; if (!repaintableEVA) Events["nextTextureEVAEvent"].guiActiveUnfocused = false; if (!showPreviousButton) { Events["previousTextureEvent"].guiActive = false; Events["previousTextureEvent"].guiActiveEditor = false; } Events["nextTextureEvent"].guiName = nextButtonText; Events["previousTextureEvent"].guiName = prevButtonText; Fields["currentTextureName"].guiName = statusText; } // runs the kind of commands that would normally be in OnStart, if they have not already been run. In case a method is called upon externally, but values have not been set up yet private void initializeData() { if (!initialized) { debug = new FSdebugMessages(debugMode, "FStextureSwitch2"); // you can't have fuel switching without symmetry, it breaks the editor GUI. if (useFuelSwitchModule) updateSymmetry = true; objectList = Tools.parseNames(objectNames, true); texList = Tools.parseNames(textureNames, true, true, textureRootFolder); mapList = Tools.parseNames(mapNames, true, true, textureRootFolder); textureDisplayList = Tools.parseNames(textureDisplayNames); fuelTankSetupList = Tools.parseIntegers(fuelTankSetups); debug.debugMessage("found " + texList.Count + " textures, using number " + selectedTexture + ", found " + objectList.Count + " objects, " + mapList.Count + " maps"); foreach (String targetObjectName in objectList) { Transform[] targetObjectTransformArray = part.FindModelTransforms(targetObjectName); List<Material> matList = new List<Material>(); foreach (Transform t in targetObjectTransformArray) { if (t != null && t.gameObject.GetComponent<Renderer>() != null) // check for if the object even has a mesh. otherwise part list loading crashes { Material targetMat = t.gameObject.GetComponent<Renderer>().material; if (targetMat != null) { if (!matList.Contains(targetMat)) { matList.Add(targetMat); } } } } targetMats.Add(matList); } if (useFuelSwitchModule) { fuelSwitch = part.GetComponent<FSfuelSwitch>(); // only looking for first, not supporting multiple fuel switchers if (fuelSwitch == null) { useFuelSwitchModule = false; debug.debugMessage("no FSfuelSwitch module found, despite useFuelSwitchModule being true"); } } initialized = true; } } } }
412
0.950831
1
0.950831
game-dev
MEDIA
0.786594
game-dev,testing-qa
0.959861
1
0.959861
magefree/mage
3,348
Mage.Tests/src/test/java/org/mage/test/cards/single/rix/ReleaseToTheWindTest.java
package org.mage.test.cards.single.rix; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; /** * @author JayDi85 */ public class ReleaseToTheWindTest extends CardTestPlayerBase { @Test public void test_Exile_PermanentCard() { // Exile target nonland permanent. For as long as that card remains exiled, its owner may cast it without paying its mana cost. addCard(Zone.HAND, playerA, "Release to the Wind"); // {2}{U} addCard(Zone.BATTLEFIELD, playerA, "Island", 3); // addCard(Zone.BATTLEFIELD, playerB, "Grizzly Bears", 1); // exile castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Release to the Wind", "Grizzly Bears"); waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN); checkExileCount("after exile", 1, PhaseStep.PRECOMBAT_MAIN, playerB, "Grizzly Bears", 1); checkPlayableAbility("after exile - non owner can't play 1", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Grizzly Bears", false); // owner can play checkPlayableAbility("after exile - non owner can't play 2", 2, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Grizzly Bears", false); checkPlayableAbility("after exile - owner can play", 2, PhaseStep.PRECOMBAT_MAIN, playerB, "Cast Grizzly Bears", true); castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, "Grizzly Bears"); setStrictChooseMode(true); setStopAt(2, PhaseStep.END_TURN); execute(); assertPermanentCount(playerB, "Grizzly Bears", 1); } @Test public void test_Exile_ModalDoubleFacedCard() { // Exile target nonland permanent. For as long as that card remains exiled, its owner may cast it without paying its mana cost. addCard(Zone.HAND, playerA, "Release to the Wind"); // {2}{U} addCard(Zone.BATTLEFIELD, playerA, "Island", 3); // // Akoum Warrior {5}{R} - creature // Akoum Teeth - land addCard(Zone.HAND, playerA, "Akoum Warrior"); addCard(Zone.BATTLEFIELD, playerA, "Mountain", 6); // prepare mdf activateManaAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{T}: Add {R}", 6); castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Akoum Warrior"); waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA); checkPermanentCount("prepare", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Akoum Warrior", 1); // exile mdf creature castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Release to the Wind", "Akoum Warrior"); waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN); checkExileCount("after exile", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Akoum Warrior", 1); // you can cast mdf, but can't play a land checkPlayableAbility("after exile - can play mdf creature", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Akoum Warrior", true); checkPlayableAbility("after exile - can't play mdf land", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Play Akoum Teeth", false); // cast mdf again for free castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Akoum Warrior"); setStrictChooseMode(true); setStopAt(1, PhaseStep.END_TURN); execute(); assertPermanentCount(playerA, "Akoum Warrior", 1); } }
412
0.922657
1
0.922657
game-dev
MEDIA
0.811397
game-dev,testing-qa
0.813727
1
0.813727
clockworklabs/SpacetimeDB
2,256
demo/Blackholio/client-unity/Assets/Scripts/autogen/Reducers/CircleDecay.g.cs
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. #nullable enable using System; using SpacetimeDB.ClientApi; using System.Collections.Generic; using System.Runtime.Serialization; namespace SpacetimeDB.Types { public sealed partial class RemoteReducers : RemoteBase { public delegate void CircleDecayHandler(ReducerEventContext ctx, CircleDecayTimer timer); public event CircleDecayHandler? OnCircleDecay; public void CircleDecay(CircleDecayTimer timer) { conn.InternalCallReducer(new Reducer.CircleDecay(timer), this.SetCallReducerFlags.CircleDecayFlags); } public bool InvokeCircleDecay(ReducerEventContext ctx, Reducer.CircleDecay args) { if (OnCircleDecay == null) { if (InternalOnUnhandledReducerError != null) { switch (ctx.Event.Status) { case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; } } return false; } OnCircleDecay( ctx, args.Timer ); return true; } } public abstract partial class Reducer { [SpacetimeDB.Type] [DataContract] public sealed partial class CircleDecay : Reducer, IReducerArgs { [DataMember(Name = "_timer")] public CircleDecayTimer Timer; public CircleDecay(CircleDecayTimer Timer) { this.Timer = Timer; } public CircleDecay() { this.Timer = new(); } string IReducerArgs.ReducerName => "circle_decay"; } } public sealed partial class SetReducerFlags { internal CallReducerFlags CircleDecayFlags; public void CircleDecay(CallReducerFlags flags) => CircleDecayFlags = flags; } }
412
0.949728
1
0.949728
game-dev
MEDIA
0.187287
game-dev
0.962447
1
0.962447
lunar-sway/minestuck
1,890
src/main/java/com/mraof/minestuck/computer/ProgramType.java
package com.mraof.minestuck.computer; import com.mraof.minestuck.blockentity.ComputerBlockEntity; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import java.util.function.Function; public final class ProgramType<D extends ProgramType.Data> { private final EventHandler eventHandler; private final Function<Runnable, D> dataConstructor; public ProgramType(EventHandler eventHandler, Function<Runnable, D> dataConstructor) { this.eventHandler = eventHandler; this.dataConstructor = dataConstructor; } public EventHandler eventHandler() { return this.eventHandler; } public D newDataInstance(Runnable markDirty) { return this.dataConstructor.apply(markDirty); } @Override public String toString() { ResourceLocation key = ProgramTypes.REGISTRY.getKey(this); return key != null ? key.toString() : "unknown"; } public MutableComponent name() { ResourceLocation key = ProgramTypes.REGISTRY.getKey(this); return key != null ? Component.translatable("minestuck.program." + key.getPath()) : Component.literal("Unknown Program"); } public interface Data { void read(CompoundTag tag); CompoundTag write(); default CompoundTag writeForSync(ISburbComputer computer, MinecraftServer mcServer) { return write(); } } public enum EmptyData implements Data { INSTANCE; @Override public void read(CompoundTag tag) { } @Override public CompoundTag write() { return new CompoundTag(); } } public interface EventHandler { default void onDiskInserted(ComputerBlockEntity computer) { } default void onLoad(ComputerBlockEntity computer) { } default void onClosed(ComputerBlockEntity computer) { } } }
412
0.58684
1
0.58684
game-dev
MEDIA
0.981098
game-dev
0.829817
1
0.829817
ImLegiitXD/Dream-Advanced
37,166
dll/back/1.20/net/minecraft/world/entity/monster/piglin/PiglinAi.java
package net.minecraft.world.entity.monster.piglin; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.mojang.datafixers.util.Pair; import java.util.Collections; import java.util.List; import java.util.Optional; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; import net.minecraft.tags.ItemTags; import net.minecraft.util.RandomSource; import net.minecraft.util.TimeUtil; import net.minecraft.util.valueproviders.UniformInt; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.PathfinderMob; import net.minecraft.world.entity.ai.Brain; import net.minecraft.world.entity.ai.behavior.BackUpIfTooClose; import net.minecraft.world.entity.ai.behavior.BehaviorControl; import net.minecraft.world.entity.ai.behavior.BehaviorUtils; import net.minecraft.world.entity.ai.behavior.CopyMemoryWithExpiry; import net.minecraft.world.entity.ai.behavior.CrossbowAttack; import net.minecraft.world.entity.ai.behavior.DismountOrSkipMounting; import net.minecraft.world.entity.ai.behavior.DoNothing; import net.minecraft.world.entity.ai.behavior.EraseMemoryIf; import net.minecraft.world.entity.ai.behavior.GoToTargetLocation; import net.minecraft.world.entity.ai.behavior.GoToWantedItem; import net.minecraft.world.entity.ai.behavior.InteractWith; import net.minecraft.world.entity.ai.behavior.InteractWithDoor; import net.minecraft.world.entity.ai.behavior.LookAtTargetSink; import net.minecraft.world.entity.ai.behavior.MeleeAttack; import net.minecraft.world.entity.ai.behavior.Mount; import net.minecraft.world.entity.ai.behavior.MoveToTargetSink; import net.minecraft.world.entity.ai.behavior.OneShot; import net.minecraft.world.entity.ai.behavior.RandomStroll; import net.minecraft.world.entity.ai.behavior.RunOne; import net.minecraft.world.entity.ai.behavior.SetEntityLookTarget; import net.minecraft.world.entity.ai.behavior.SetEntityLookTargetSometimes; import net.minecraft.world.entity.ai.behavior.SetLookAndInteract; import net.minecraft.world.entity.ai.behavior.SetWalkTargetAwayFrom; import net.minecraft.world.entity.ai.behavior.SetWalkTargetFromAttackTargetIfTargetOutOfReach; import net.minecraft.world.entity.ai.behavior.SetWalkTargetFromLookTarget; import net.minecraft.world.entity.ai.behavior.StartAttacking; import net.minecraft.world.entity.ai.behavior.StartCelebratingIfTargetDead; import net.minecraft.world.entity.ai.behavior.StopAttackingIfTargetInvalid; import net.minecraft.world.entity.ai.behavior.StopBeingAngryIfTargetDead; import net.minecraft.world.entity.ai.behavior.TriggerGate; import net.minecraft.world.entity.ai.behavior.declarative.BehaviorBuilder; import net.minecraft.world.entity.ai.behavior.declarative.Trigger; import net.minecraft.world.entity.ai.memory.MemoryModuleType; import net.minecraft.world.entity.ai.sensing.Sensor; import net.minecraft.world.entity.ai.util.LandRandomPos; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.monster.hoglin.Hoglin; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.schedule.Activity; import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ArmorMaterials; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.storage.loot.BuiltInLootTables; import net.minecraft.world.level.storage.loot.LootParams; import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.Vec3; public class PiglinAi { public static final int REPELLENT_DETECTION_RANGE_HORIZONTAL = 8; public static final int REPELLENT_DETECTION_RANGE_VERTICAL = 4; public static final Item BARTERING_ITEM = Items.GOLD_INGOT; private static final int PLAYER_ANGER_RANGE = 16; private static final int ANGER_DURATION = 600; private static final int ADMIRE_DURATION = 120; private static final int MAX_DISTANCE_TO_WALK_TO_ITEM = 9; private static final int MAX_TIME_TO_WALK_TO_ITEM = 200; private static final int HOW_LONG_TIME_TO_DISABLE_ADMIRE_WALKING_IF_CANT_REACH_ITEM = 200; private static final int CELEBRATION_TIME = 300; protected static final UniformInt TIME_BETWEEN_HUNTS = TimeUtil.rangeOfSeconds(30, 120); private static final int BABY_FLEE_DURATION_AFTER_GETTING_HIT = 100; private static final int HIT_BY_PLAYER_MEMORY_TIMEOUT = 400; private static final int MAX_WALK_DISTANCE_TO_START_RIDING = 8; private static final UniformInt RIDE_START_INTERVAL = TimeUtil.rangeOfSeconds(10, 40); private static final UniformInt RIDE_DURATION = TimeUtil.rangeOfSeconds(10, 30); private static final UniformInt RETREAT_DURATION = TimeUtil.rangeOfSeconds(5, 20); private static final int MELEE_ATTACK_COOLDOWN = 20; private static final int EAT_COOLDOWN = 200; private static final int DESIRED_DISTANCE_FROM_ENTITY_WHEN_AVOIDING = 12; private static final int MAX_LOOK_DIST = 8; private static final int MAX_LOOK_DIST_FOR_PLAYER_HOLDING_LOVED_ITEM = 14; private static final int INTERACTION_RANGE = 8; private static final int MIN_DESIRED_DIST_FROM_TARGET_WHEN_HOLDING_CROSSBOW = 5; private static final float SPEED_WHEN_STRAFING_BACK_FROM_TARGET = 0.75F; private static final int DESIRED_DISTANCE_FROM_ZOMBIFIED = 6; private static final UniformInt AVOID_ZOMBIFIED_DURATION = TimeUtil.rangeOfSeconds(5, 7); private static final UniformInt BABY_AVOID_NEMESIS_DURATION = TimeUtil.rangeOfSeconds(5, 7); private static final float PROBABILITY_OF_CELEBRATION_DANCE = 0.1F; private static final float SPEED_MULTIPLIER_WHEN_AVOIDING = 1.0F; private static final float SPEED_MULTIPLIER_WHEN_RETREATING = 1.0F; private static final float SPEED_MULTIPLIER_WHEN_MOUNTING = 0.8F; private static final float SPEED_MULTIPLIER_WHEN_GOING_TO_WANTED_ITEM = 1.0F; private static final float SPEED_MULTIPLIER_WHEN_GOING_TO_CELEBRATE_LOCATION = 1.0F; private static final float SPEED_MULTIPLIER_WHEN_DANCING = 0.6F; private static final float SPEED_MULTIPLIER_WHEN_IDLING = 0.6F; protected static Brain<?> makeBrain(Piglin p_34841_, Brain<Piglin> p_34842_) { initCoreActivity(p_34842_); initIdleActivity(p_34842_); initAdmireItemActivity(p_34842_); initFightActivity(p_34841_, p_34842_); initCelebrateActivity(p_34842_); initRetreatActivity(p_34842_); initRideHoglinActivity(p_34842_); p_34842_.setCoreActivities(ImmutableSet.of(Activity.CORE)); p_34842_.setDefaultActivity(Activity.IDLE); p_34842_.useDefaultActivity(); return p_34842_; } protected static void initMemories(Piglin p_219206_, RandomSource p_219207_) { int i = TIME_BETWEEN_HUNTS.sample(p_219207_); p_219206_.getBrain().setMemoryWithExpiry(MemoryModuleType.HUNTED_RECENTLY, true, (long)i); } private static void initCoreActivity(Brain<Piglin> p_34821_) { p_34821_.addActivity(Activity.CORE, 0, ImmutableList.of(new LookAtTargetSink(45, 90), new MoveToTargetSink(), InteractWithDoor.create(), babyAvoidNemesis(), avoidZombified(), StopHoldingItemIfNoLongerAdmiring.create(), StartAdmiringItemIfSeen.create(120), StartCelebratingIfTargetDead.create(300, PiglinAi::wantsToDance), StopBeingAngryIfTargetDead.create())); } private static void initIdleActivity(Brain<Piglin> p_34892_) { p_34892_.addActivity(Activity.IDLE, 10, ImmutableList.of(SetEntityLookTarget.create(PiglinAi::isPlayerHoldingLovedItem, 14.0F), StartAttacking.<Piglin>create(AbstractPiglin::isAdult, PiglinAi::findNearestValidAttackTarget), BehaviorBuilder.triggerIf(Piglin::canHunt, StartHuntingHoglin.create()), avoidRepellent(), babySometimesRideBabyHoglin(), createIdleLookBehaviors(), createIdleMovementBehaviors(), SetLookAndInteract.create(EntityType.PLAYER, 4))); } private static void initFightActivity(Piglin p_34904_, Brain<Piglin> p_34905_) { p_34905_.addActivityAndRemoveMemoryWhenStopped(Activity.FIGHT, 10, ImmutableList.<net.minecraft.world.entity.ai.behavior.BehaviorControl<? super Piglin>>of(StopAttackingIfTargetInvalid.<Piglin>create((p_34981_) -> { return !isNearestValidAttackTarget(p_34904_, p_34981_); }), BehaviorBuilder.triggerIf(PiglinAi::hasCrossbow, BackUpIfTooClose.create(5, 0.75F)), SetWalkTargetFromAttackTargetIfTargetOutOfReach.create(1.0F), MeleeAttack.create(20), new CrossbowAttack(), RememberIfHoglinWasKilled.create(), EraseMemoryIf.create(PiglinAi::isNearZombified, MemoryModuleType.ATTACK_TARGET)), MemoryModuleType.ATTACK_TARGET); } private static void initCelebrateActivity(Brain<Piglin> p_34921_) { p_34921_.addActivityAndRemoveMemoryWhenStopped(Activity.CELEBRATE, 10, ImmutableList.of(avoidRepellent(), SetEntityLookTarget.create(PiglinAi::isPlayerHoldingLovedItem, 14.0F), StartAttacking.<Piglin>create(AbstractPiglin::isAdult, PiglinAi::findNearestValidAttackTarget), BehaviorBuilder.<Piglin>triggerIf((p_34804_) -> { return !p_34804_.isDancing(); }, GoToTargetLocation.create(MemoryModuleType.CELEBRATE_LOCATION, 2, 1.0F)), BehaviorBuilder.<Piglin>triggerIf(Piglin::isDancing, GoToTargetLocation.create(MemoryModuleType.CELEBRATE_LOCATION, 4, 0.6F)), new RunOne<Piglin>(ImmutableList.of(Pair.of(SetEntityLookTarget.create(EntityType.PIGLIN, 8.0F), 1), Pair.of(RandomStroll.stroll(0.6F, 2, 1), 1), Pair.of(new DoNothing(10, 20), 1)))), MemoryModuleType.CELEBRATE_LOCATION); } private static void initAdmireItemActivity(Brain<Piglin> p_34941_) { p_34941_.addActivityAndRemoveMemoryWhenStopped(Activity.ADMIRE_ITEM, 10, ImmutableList.of(GoToWantedItem.create(PiglinAi::isNotHoldingLovedItemInOffHand, 1.0F, true, 9), StopAdmiringIfItemTooFarAway.create(9), StopAdmiringIfTiredOfTryingToReachItem.create(200, 200)), MemoryModuleType.ADMIRING_ITEM); } private static void initRetreatActivity(Brain<Piglin> p_34959_) { p_34959_.addActivityAndRemoveMemoryWhenStopped(Activity.AVOID, 10, ImmutableList.of(SetWalkTargetAwayFrom.entity(MemoryModuleType.AVOID_TARGET, 1.0F, 12, true), createIdleLookBehaviors(), createIdleMovementBehaviors(), EraseMemoryIf.<Piglin>create(PiglinAi::wantsToStopFleeing, MemoryModuleType.AVOID_TARGET)), MemoryModuleType.AVOID_TARGET); } private static void initRideHoglinActivity(Brain<Piglin> p_34974_) { p_34974_.addActivityAndRemoveMemoryWhenStopped(Activity.RIDE, 10, ImmutableList.of(Mount.create(0.8F), SetEntityLookTarget.create(PiglinAi::isPlayerHoldingLovedItem, 8.0F), BehaviorBuilder.sequence(BehaviorBuilder.triggerIf(Entity::isPassenger), TriggerGate.triggerOneShuffled(ImmutableList.<Pair<? extends Trigger<? super LivingEntity>, Integer>>builder().addAll(createLookBehaviors()).add(Pair.of(BehaviorBuilder.triggerIf((p_258950_) -> { return true; }), 1)).build())), DismountOrSkipMounting.<Piglin>create(8, PiglinAi::wantsToStopRiding)), MemoryModuleType.RIDE_TARGET); } private static ImmutableList<Pair<OneShot<LivingEntity>, Integer>> createLookBehaviors() { return ImmutableList.of(Pair.of(SetEntityLookTarget.create(EntityType.PLAYER, 8.0F), 1), Pair.of(SetEntityLookTarget.create(EntityType.PIGLIN, 8.0F), 1), Pair.of(SetEntityLookTarget.create(8.0F), 1)); } private static RunOne<LivingEntity> createIdleLookBehaviors() { return new RunOne<>(ImmutableList.<Pair<? extends BehaviorControl<? super LivingEntity>, Integer>>builder().addAll(createLookBehaviors()).add(Pair.of(new DoNothing(30, 60), 1)).build()); } private static RunOne<Piglin> createIdleMovementBehaviors() { return new RunOne<>(ImmutableList.of(Pair.of(RandomStroll.stroll(0.6F), 2), Pair.of(InteractWith.of(EntityType.PIGLIN, 8, MemoryModuleType.INTERACTION_TARGET, 0.6F, 2), 2), Pair.of(BehaviorBuilder.triggerIf(PiglinAi::doesntSeeAnyPlayerHoldingLovedItem, SetWalkTargetFromLookTarget.create(0.6F, 3)), 2), Pair.of(new DoNothing(30, 60), 1))); } private static BehaviorControl<PathfinderMob> avoidRepellent() { return SetWalkTargetAwayFrom.pos(MemoryModuleType.NEAREST_REPELLENT, 1.0F, 8, false); } private static BehaviorControl<Piglin> babyAvoidNemesis() { return CopyMemoryWithExpiry.create(Piglin::isBaby, MemoryModuleType.NEAREST_VISIBLE_NEMESIS, MemoryModuleType.AVOID_TARGET, BABY_AVOID_NEMESIS_DURATION); } private static BehaviorControl<Piglin> avoidZombified() { return CopyMemoryWithExpiry.create(PiglinAi::isNearZombified, MemoryModuleType.NEAREST_VISIBLE_ZOMBIFIED, MemoryModuleType.AVOID_TARGET, AVOID_ZOMBIFIED_DURATION); } protected static void updateActivity(Piglin p_34899_) { Brain<Piglin> brain = p_34899_.getBrain(); Activity activity = brain.getActiveNonCoreActivity().orElse((Activity)null); brain.setActiveActivityToFirstValid(ImmutableList.of(Activity.ADMIRE_ITEM, Activity.FIGHT, Activity.AVOID, Activity.CELEBRATE, Activity.RIDE, Activity.IDLE)); Activity activity1 = brain.getActiveNonCoreActivity().orElse((Activity)null); if (activity != activity1) { getSoundForCurrentActivity(p_34899_).ifPresent(p_34899_::playSoundEvent); } p_34899_.setAggressive(brain.hasMemoryValue(MemoryModuleType.ATTACK_TARGET)); if (!brain.hasMemoryValue(MemoryModuleType.RIDE_TARGET) && isBabyRidingBaby(p_34899_)) { p_34899_.stopRiding(); } if (!brain.hasMemoryValue(MemoryModuleType.CELEBRATE_LOCATION)) { brain.eraseMemory(MemoryModuleType.DANCING); } p_34899_.setDancing(brain.hasMemoryValue(MemoryModuleType.DANCING)); } private static boolean isBabyRidingBaby(Piglin p_34993_) { if (!p_34993_.isBaby()) { return false; } else { Entity entity = p_34993_.getVehicle(); return entity instanceof Piglin && ((Piglin)entity).isBaby() || entity instanceof Hoglin && ((Hoglin)entity).isBaby(); } } protected static void pickUpItem(Piglin p_34844_, ItemEntity p_34845_) { stopWalking(p_34844_); ItemStack itemstack; if (p_34845_.getItem().is(Items.GOLD_NUGGET)) { p_34844_.take(p_34845_, p_34845_.getItem().getCount()); itemstack = p_34845_.getItem(); p_34845_.discard(); } else { p_34844_.take(p_34845_, 1); itemstack = removeOneItemFromItemEntity(p_34845_); } if (isLovedItem(itemstack)) { p_34844_.getBrain().eraseMemory(MemoryModuleType.TIME_TRYING_TO_REACH_ADMIRE_ITEM); holdInOffhand(p_34844_, itemstack); admireGoldItem(p_34844_); } else if (isFood(itemstack) && !hasEatenRecently(p_34844_)) { eat(p_34844_); } else { boolean flag = !p_34844_.equipItemIfPossible(itemstack).equals(ItemStack.EMPTY); if (!flag) { putInInventory(p_34844_, itemstack); } } } private static void holdInOffhand(Piglin p_34933_, ItemStack p_34934_) { if (isHoldingItemInOffHand(p_34933_)) { p_34933_.spawnAtLocation(p_34933_.getItemInHand(InteractionHand.OFF_HAND)); } p_34933_.holdInOffHand(p_34934_); } private static ItemStack removeOneItemFromItemEntity(ItemEntity p_34823_) { ItemStack itemstack = p_34823_.getItem(); ItemStack itemstack1 = itemstack.split(1); if (itemstack.isEmpty()) { p_34823_.discard(); } else { p_34823_.setItem(itemstack); } return itemstack1; } protected static void stopHoldingOffHandItem(Piglin p_34868_, boolean p_34869_) { ItemStack itemstack = p_34868_.getItemInHand(InteractionHand.OFF_HAND); p_34868_.setItemInHand(InteractionHand.OFF_HAND, ItemStack.EMPTY); if (p_34868_.isAdult()) { boolean flag = isBarterCurrency(itemstack); if (p_34869_ && flag) { throwItems(p_34868_, getBarterResponseItems(p_34868_)); } else if (!flag) { boolean flag1 = !p_34868_.equipItemIfPossible(itemstack).isEmpty(); if (!flag1) { putInInventory(p_34868_, itemstack); } } } else { boolean flag2 = !p_34868_.equipItemIfPossible(itemstack).isEmpty(); if (!flag2) { ItemStack itemstack1 = p_34868_.getMainHandItem(); if (isLovedItem(itemstack1)) { putInInventory(p_34868_, itemstack1); } else { throwItems(p_34868_, Collections.singletonList(itemstack1)); } p_34868_.holdInMainHand(itemstack); } } } protected static void cancelAdmiring(Piglin p_34928_) { if (isAdmiringItem(p_34928_) && !p_34928_.getOffhandItem().isEmpty()) { p_34928_.spawnAtLocation(p_34928_.getOffhandItem()); p_34928_.setItemInHand(InteractionHand.OFF_HAND, ItemStack.EMPTY); } } private static void putInInventory(Piglin p_34953_, ItemStack p_34954_) { ItemStack itemstack = p_34953_.addToInventory(p_34954_); throwItemsTowardRandomPos(p_34953_, Collections.singletonList(itemstack)); } private static void throwItems(Piglin p_34861_, List<ItemStack> p_34862_) { Optional<Player> optional = p_34861_.getBrain().getMemory(MemoryModuleType.NEAREST_VISIBLE_PLAYER); if (optional.isPresent()) { throwItemsTowardPlayer(p_34861_, optional.get(), p_34862_); } else { throwItemsTowardRandomPos(p_34861_, p_34862_); } } private static void throwItemsTowardRandomPos(Piglin p_34913_, List<ItemStack> p_34914_) { throwItemsTowardPos(p_34913_, p_34914_, getRandomNearbyPos(p_34913_)); } private static void throwItemsTowardPlayer(Piglin p_34851_, Player p_34852_, List<ItemStack> p_34853_) { throwItemsTowardPos(p_34851_, p_34853_, p_34852_.position()); } private static void throwItemsTowardPos(Piglin p_34864_, List<ItemStack> p_34865_, Vec3 p_34866_) { if (!p_34865_.isEmpty()) { p_34864_.swing(InteractionHand.OFF_HAND); for(ItemStack itemstack : p_34865_) { BehaviorUtils.throwItem(p_34864_, itemstack, p_34866_.add(0.0D, 1.0D, 0.0D)); } } } private static List<ItemStack> getBarterResponseItems(Piglin p_34997_) { LootTable loottable = p_34997_.level().getServer().getLootData().getLootTable(BuiltInLootTables.PIGLIN_BARTERING); List<ItemStack> list = loottable.getRandomItems((new LootParams.Builder((ServerLevel)p_34997_.level())).withParameter(LootContextParams.THIS_ENTITY, p_34997_).create(LootContextParamSets.PIGLIN_BARTER)); return list; } private static boolean wantsToDance(LivingEntity p_34811_, LivingEntity p_34812_) { if (p_34812_.getType() != EntityType.HOGLIN) { return false; } else { return RandomSource.create(p_34811_.level().getGameTime()).nextFloat() < 0.1F; } } protected static boolean wantsToPickup(Piglin p_34858_, ItemStack p_34859_) { if (p_34858_.isBaby() && p_34859_.is(ItemTags.IGNORED_BY_PIGLIN_BABIES)) { return false; } else if (p_34859_.is(ItemTags.PIGLIN_REPELLENTS)) { return false; } else if (isAdmiringDisabled(p_34858_) && p_34858_.getBrain().hasMemoryValue(MemoryModuleType.ATTACK_TARGET)) { return false; } else if (isBarterCurrency(p_34859_)) { return isNotHoldingLovedItemInOffHand(p_34858_); } else { boolean flag = p_34858_.canAddToInventory(p_34859_); if (p_34859_.is(Items.GOLD_NUGGET)) { return flag; } else if (isFood(p_34859_)) { return !hasEatenRecently(p_34858_) && flag; } else if (!isLovedItem(p_34859_)) { return p_34858_.canReplaceCurrentItem(p_34859_); } else { return isNotHoldingLovedItemInOffHand(p_34858_) && flag; } } } protected static boolean isLovedItem(ItemStack p_149966_) { return p_149966_.is(ItemTags.PIGLIN_LOVED); } private static boolean wantsToStopRiding(Piglin p_34835_, Entity p_34836_) { if (!(p_34836_ instanceof Mob mob)) { return false; } else { return !mob.isBaby() || !mob.isAlive() || wasHurtRecently(p_34835_) || wasHurtRecently(mob) || mob instanceof Piglin && mob.getVehicle() == null; } } private static boolean isNearestValidAttackTarget(Piglin p_34901_, LivingEntity p_34902_) { return findNearestValidAttackTarget(p_34901_).filter((p_34887_) -> { return p_34887_ == p_34902_; }).isPresent(); } private static boolean isNearZombified(Piglin p_34999_) { Brain<Piglin> brain = p_34999_.getBrain(); if (brain.hasMemoryValue(MemoryModuleType.NEAREST_VISIBLE_ZOMBIFIED)) { LivingEntity livingentity = brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_ZOMBIFIED).get(); return p_34999_.closerThan(livingentity, 6.0D); } else { return false; } } private static Optional<? extends LivingEntity> findNearestValidAttackTarget(Piglin p_35001_) { Brain<Piglin> brain = p_35001_.getBrain(); if (isNearZombified(p_35001_)) { return Optional.empty(); } else { Optional<LivingEntity> optional = BehaviorUtils.getLivingEntityFromUUIDMemory(p_35001_, MemoryModuleType.ANGRY_AT); if (optional.isPresent() && Sensor.isEntityAttackableIgnoringLineOfSight(p_35001_, optional.get())) { return optional; } else { if (brain.hasMemoryValue(MemoryModuleType.UNIVERSAL_ANGER)) { Optional<Player> optional1 = brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_ATTACKABLE_PLAYER); if (optional1.isPresent()) { return optional1; } } Optional<Mob> optional3 = brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_NEMESIS); if (optional3.isPresent()) { return optional3; } else { Optional<Player> optional2 = brain.getMemory(MemoryModuleType.NEAREST_TARGETABLE_PLAYER_NOT_WEARING_GOLD); return optional2.isPresent() && Sensor.isEntityAttackable(p_35001_, optional2.get()) ? optional2 : Optional.empty(); } } } } public static void angerNearbyPiglins(Player p_34874_, boolean p_34875_) { List<Piglin> list = p_34874_.level().getEntitiesOfClass(Piglin.class, p_34874_.getBoundingBox().inflate(16.0D)); list.stream().filter(PiglinAi::isIdle).filter((p_34881_) -> { return !p_34875_ || BehaviorUtils.canSee(p_34881_, p_34874_); }).forEach((p_289467_) -> { if (p_289467_.level().getGameRules().getBoolean(GameRules.RULE_UNIVERSAL_ANGER)) { setAngerTargetToNearestTargetablePlayerIfFound(p_289467_, p_34874_); } else { setAngerTarget(p_289467_, p_34874_); } }); } public static InteractionResult mobInteract(Piglin p_34847_, Player p_34848_, InteractionHand p_34849_) { ItemStack itemstack = p_34848_.getItemInHand(p_34849_); if (canAdmire(p_34847_, itemstack)) { ItemStack itemstack1 = itemstack.split(1); holdInOffhand(p_34847_, itemstack1); admireGoldItem(p_34847_); stopWalking(p_34847_); return InteractionResult.CONSUME; } else { return InteractionResult.PASS; } } protected static boolean canAdmire(Piglin p_34910_, ItemStack p_34911_) { return !isAdmiringDisabled(p_34910_) && !isAdmiringItem(p_34910_) && p_34910_.isAdult() && isBarterCurrency(p_34911_); } protected static void wasHurtBy(Piglin p_34838_, LivingEntity p_34839_) { if (!(p_34839_ instanceof Piglin)) { if (isHoldingItemInOffHand(p_34838_)) { stopHoldingOffHandItem(p_34838_, false); } Brain<Piglin> brain = p_34838_.getBrain(); brain.eraseMemory(MemoryModuleType.CELEBRATE_LOCATION); brain.eraseMemory(MemoryModuleType.DANCING); brain.eraseMemory(MemoryModuleType.ADMIRING_ITEM); if (p_34839_ instanceof Player) { brain.setMemoryWithExpiry(MemoryModuleType.ADMIRING_DISABLED, true, 400L); } getAvoidTarget(p_34838_).ifPresent((p_289470_) -> { if (p_289470_.getType() != p_34839_.getType()) { brain.eraseMemory(MemoryModuleType.AVOID_TARGET); } }); if (p_34838_.isBaby()) { brain.setMemoryWithExpiry(MemoryModuleType.AVOID_TARGET, p_34839_, 100L); if (Sensor.isEntityAttackableIgnoringLineOfSight(p_34838_, p_34839_)) { broadcastAngerTarget(p_34838_, p_34839_); } } else if (p_34839_.getType() == EntityType.HOGLIN && hoglinsOutnumberPiglins(p_34838_)) { setAvoidTargetAndDontHuntForAWhile(p_34838_, p_34839_); broadcastRetreat(p_34838_, p_34839_); } else { maybeRetaliate(p_34838_, p_34839_); } } } protected static void maybeRetaliate(AbstractPiglin p_34827_, LivingEntity p_34828_) { if (!p_34827_.getBrain().isActive(Activity.AVOID)) { if (Sensor.isEntityAttackableIgnoringLineOfSight(p_34827_, p_34828_)) { if (!BehaviorUtils.isOtherTargetMuchFurtherAwayThanCurrentAttackTarget(p_34827_, p_34828_, 4.0D)) { if (p_34828_.getType() == EntityType.PLAYER && p_34827_.level().getGameRules().getBoolean(GameRules.RULE_UNIVERSAL_ANGER)) { setAngerTargetToNearestTargetablePlayerIfFound(p_34827_, p_34828_); broadcastUniversalAnger(p_34827_); } else { setAngerTarget(p_34827_, p_34828_); broadcastAngerTarget(p_34827_, p_34828_); } } } } } public static Optional<SoundEvent> getSoundForCurrentActivity(Piglin p_34948_) { return p_34948_.getBrain().getActiveNonCoreActivity().map((p_34908_) -> { return getSoundForActivity(p_34948_, p_34908_); }); } private static SoundEvent getSoundForActivity(Piglin p_34855_, Activity p_34856_) { if (p_34856_ == Activity.FIGHT) { return SoundEvents.PIGLIN_ANGRY; } else if (p_34855_.isConverting()) { return SoundEvents.PIGLIN_RETREAT; } else if (p_34856_ == Activity.AVOID && isNearAvoidTarget(p_34855_)) { return SoundEvents.PIGLIN_RETREAT; } else if (p_34856_ == Activity.ADMIRE_ITEM) { return SoundEvents.PIGLIN_ADMIRING_ITEM; } else if (p_34856_ == Activity.CELEBRATE) { return SoundEvents.PIGLIN_CELEBRATE; } else if (seesPlayerHoldingLovedItem(p_34855_)) { return SoundEvents.PIGLIN_JEALOUS; } else { return isNearRepellent(p_34855_) ? SoundEvents.PIGLIN_RETREAT : SoundEvents.PIGLIN_AMBIENT; } } private static boolean isNearAvoidTarget(Piglin p_35003_) { Brain<Piglin> brain = p_35003_.getBrain(); return !brain.hasMemoryValue(MemoryModuleType.AVOID_TARGET) ? false : brain.getMemory(MemoryModuleType.AVOID_TARGET).get().closerThan(p_35003_, 12.0D); } protected static List<AbstractPiglin> getVisibleAdultPiglins(Piglin p_35005_) { return p_35005_.getBrain().getMemory(MemoryModuleType.NEAREST_VISIBLE_ADULT_PIGLINS).orElse(ImmutableList.of()); } private static List<AbstractPiglin> getAdultPiglins(AbstractPiglin p_34961_) { return p_34961_.getBrain().getMemory(MemoryModuleType.NEARBY_ADULT_PIGLINS).orElse(ImmutableList.of()); } public static boolean isWearingGold(LivingEntity p_34809_) { for(ItemStack itemstack : p_34809_.getArmorSlots()) { Item item = itemstack.getItem(); if (item instanceof ArmorItem && ((ArmorItem)item).getMaterial() == ArmorMaterials.GOLD) { return true; } } return false; } private static void stopWalking(Piglin p_35007_) { p_35007_.getBrain().eraseMemory(MemoryModuleType.WALK_TARGET); p_35007_.getNavigation().stop(); } private static BehaviorControl<LivingEntity> babySometimesRideBabyHoglin() { SetEntityLookTargetSometimes.Ticker setentitylooktargetsometimes$ticker = new SetEntityLookTargetSometimes.Ticker(RIDE_START_INTERVAL); return CopyMemoryWithExpiry.create((p_289472_) -> { return p_289472_.isBaby() && setentitylooktargetsometimes$ticker.tickDownAndCheck(p_289472_.level().random); }, MemoryModuleType.NEAREST_VISIBLE_BABY_HOGLIN, MemoryModuleType.RIDE_TARGET, RIDE_DURATION); } protected static void broadcastAngerTarget(AbstractPiglin p_34896_, LivingEntity p_34897_) { getAdultPiglins(p_34896_).forEach((p_289474_) -> { if (p_34897_.getType() != EntityType.HOGLIN || p_289474_.canHunt() && ((Hoglin)p_34897_).canBeHunted()) { setAngerTargetIfCloserThanCurrent(p_289474_, p_34897_); } }); } protected static void broadcastUniversalAnger(AbstractPiglin p_34825_) { getAdultPiglins(p_34825_).forEach((p_34991_) -> { getNearestVisibleTargetablePlayer(p_34991_).ifPresent((p_149964_) -> { setAngerTarget(p_34991_, p_149964_); }); }); } protected static void setAngerTarget(AbstractPiglin p_34925_, LivingEntity p_34926_) { if (Sensor.isEntityAttackableIgnoringLineOfSight(p_34925_, p_34926_)) { p_34925_.getBrain().eraseMemory(MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE); p_34925_.getBrain().setMemoryWithExpiry(MemoryModuleType.ANGRY_AT, p_34926_.getUUID(), 600L); if (p_34926_.getType() == EntityType.HOGLIN && p_34925_.canHunt()) { dontKillAnyMoreHoglinsForAWhile(p_34925_); } if (p_34926_.getType() == EntityType.PLAYER && p_34925_.level().getGameRules().getBoolean(GameRules.RULE_UNIVERSAL_ANGER)) { p_34925_.getBrain().setMemoryWithExpiry(MemoryModuleType.UNIVERSAL_ANGER, true, 600L); } } } private static void setAngerTargetToNearestTargetablePlayerIfFound(AbstractPiglin p_34945_, LivingEntity p_34946_) { Optional<Player> optional = getNearestVisibleTargetablePlayer(p_34945_); if (optional.isPresent()) { setAngerTarget(p_34945_, optional.get()); } else { setAngerTarget(p_34945_, p_34946_); } } private static void setAngerTargetIfCloserThanCurrent(AbstractPiglin p_34963_, LivingEntity p_34964_) { Optional<LivingEntity> optional = getAngerTarget(p_34963_); LivingEntity livingentity = BehaviorUtils.getNearestTarget(p_34963_, optional, p_34964_); if (!optional.isPresent() || optional.get() != livingentity) { setAngerTarget(p_34963_, livingentity); } } private static Optional<LivingEntity> getAngerTarget(AbstractPiglin p_34976_) { return BehaviorUtils.getLivingEntityFromUUIDMemory(p_34976_, MemoryModuleType.ANGRY_AT); } public static Optional<LivingEntity> getAvoidTarget(Piglin p_34987_) { return p_34987_.getBrain().hasMemoryValue(MemoryModuleType.AVOID_TARGET) ? p_34987_.getBrain().getMemory(MemoryModuleType.AVOID_TARGET) : Optional.empty(); } public static Optional<Player> getNearestVisibleTargetablePlayer(AbstractPiglin p_34894_) { return p_34894_.getBrain().hasMemoryValue(MemoryModuleType.NEAREST_VISIBLE_ATTACKABLE_PLAYER) ? p_34894_.getBrain().getMemory(MemoryModuleType.NEAREST_VISIBLE_ATTACKABLE_PLAYER) : Optional.empty(); } private static void broadcastRetreat(Piglin p_34930_, LivingEntity p_34931_) { getVisibleAdultPiglins(p_34930_).stream().filter((p_34985_) -> { return p_34985_ instanceof Piglin; }).forEach((p_34819_) -> { retreatFromNearestTarget((Piglin)p_34819_, p_34931_); }); } private static void retreatFromNearestTarget(Piglin p_34950_, LivingEntity p_34951_) { Brain<Piglin> brain = p_34950_.getBrain(); LivingEntity $$3 = BehaviorUtils.getNearestTarget(p_34950_, brain.getMemory(MemoryModuleType.AVOID_TARGET), p_34951_); $$3 = BehaviorUtils.getNearestTarget(p_34950_, brain.getMemory(MemoryModuleType.ATTACK_TARGET), $$3); setAvoidTargetAndDontHuntForAWhile(p_34950_, $$3); } private static boolean wantsToStopFleeing(Piglin p_35009_) { Brain<Piglin> brain = p_35009_.getBrain(); if (!brain.hasMemoryValue(MemoryModuleType.AVOID_TARGET)) { return true; } else { LivingEntity livingentity = brain.getMemory(MemoryModuleType.AVOID_TARGET).get(); EntityType<?> entitytype = livingentity.getType(); if (entitytype == EntityType.HOGLIN) { return piglinsEqualOrOutnumberHoglins(p_35009_); } else if (isZombified(entitytype)) { return !brain.isMemoryValue(MemoryModuleType.NEAREST_VISIBLE_ZOMBIFIED, livingentity); } else { return false; } } } private static boolean piglinsEqualOrOutnumberHoglins(Piglin p_35011_) { return !hoglinsOutnumberPiglins(p_35011_); } private static boolean hoglinsOutnumberPiglins(Piglin p_35013_) { int i = p_35013_.getBrain().getMemory(MemoryModuleType.VISIBLE_ADULT_PIGLIN_COUNT).orElse(0) + 1; int j = p_35013_.getBrain().getMemory(MemoryModuleType.VISIBLE_ADULT_HOGLIN_COUNT).orElse(0); return j > i; } private static void setAvoidTargetAndDontHuntForAWhile(Piglin p_34968_, LivingEntity p_34969_) { p_34968_.getBrain().eraseMemory(MemoryModuleType.ANGRY_AT); p_34968_.getBrain().eraseMemory(MemoryModuleType.ATTACK_TARGET); p_34968_.getBrain().eraseMemory(MemoryModuleType.WALK_TARGET); p_34968_.getBrain().setMemoryWithExpiry(MemoryModuleType.AVOID_TARGET, p_34969_, (long)RETREAT_DURATION.sample(p_34968_.level().random)); dontKillAnyMoreHoglinsForAWhile(p_34968_); } protected static void dontKillAnyMoreHoglinsForAWhile(AbstractPiglin p_34923_) { p_34923_.getBrain().setMemoryWithExpiry(MemoryModuleType.HUNTED_RECENTLY, true, (long)TIME_BETWEEN_HUNTS.sample(p_34923_.level().random)); } private static void eat(Piglin p_35015_) { p_35015_.getBrain().setMemoryWithExpiry(MemoryModuleType.ATE_RECENTLY, true, 200L); } private static Vec3 getRandomNearbyPos(Piglin p_35017_) { Vec3 vec3 = LandRandomPos.getPos(p_35017_, 4, 2); return vec3 == null ? p_35017_.position() : vec3; } private static boolean hasEatenRecently(Piglin p_35019_) { return p_35019_.getBrain().hasMemoryValue(MemoryModuleType.ATE_RECENTLY); } protected static boolean isIdle(AbstractPiglin p_34943_) { return p_34943_.getBrain().isActive(Activity.IDLE); } private static boolean hasCrossbow(LivingEntity p_34919_) { return p_34919_.isHolding(Items.CROSSBOW); } private static void admireGoldItem(LivingEntity p_34939_) { p_34939_.getBrain().setMemoryWithExpiry(MemoryModuleType.ADMIRING_ITEM, true, 120L); } private static boolean isAdmiringItem(Piglin p_35021_) { return p_35021_.getBrain().hasMemoryValue(MemoryModuleType.ADMIRING_ITEM); } private static boolean isBarterCurrency(ItemStack p_149968_) { return p_149968_.is(BARTERING_ITEM); } private static boolean isFood(ItemStack p_149970_) { return p_149970_.is(ItemTags.PIGLIN_FOOD); } private static boolean isNearRepellent(Piglin p_35023_) { return p_35023_.getBrain().hasMemoryValue(MemoryModuleType.NEAREST_REPELLENT); } private static boolean seesPlayerHoldingLovedItem(LivingEntity p_34972_) { return p_34972_.getBrain().hasMemoryValue(MemoryModuleType.NEAREST_PLAYER_HOLDING_WANTED_ITEM); } private static boolean doesntSeeAnyPlayerHoldingLovedItem(LivingEntity p_34983_) { return !seesPlayerHoldingLovedItem(p_34983_); } public static boolean isPlayerHoldingLovedItem(LivingEntity p_34884_) { return p_34884_.getType() == EntityType.PLAYER && p_34884_.isHolding(PiglinAi::isLovedItem); } private static boolean isAdmiringDisabled(Piglin p_35025_) { return p_35025_.getBrain().hasMemoryValue(MemoryModuleType.ADMIRING_DISABLED); } private static boolean wasHurtRecently(LivingEntity p_34989_) { return p_34989_.getBrain().hasMemoryValue(MemoryModuleType.HURT_BY); } private static boolean isHoldingItemInOffHand(Piglin p_35027_) { return !p_35027_.getOffhandItem().isEmpty(); } private static boolean isNotHoldingLovedItemInOffHand(Piglin p_35029_) { return p_35029_.getOffhandItem().isEmpty() || !isLovedItem(p_35029_.getOffhandItem()); } public static boolean isZombified(EntityType<?> p_34807_) { return p_34807_ == EntityType.ZOMBIFIED_PIGLIN || p_34807_ == EntityType.ZOGLIN; } }
412
0.514875
1
0.514875
game-dev
MEDIA
0.996936
game-dev
0.775762
1
0.775762
kubernetes-client/java
11,612
fluent/src/main/java/io/kubernetes/client/openapi/models/V1alpha1StorageVersionListFluent.java
package io.kubernetes.client.openapi.models; import java.lang.StringBuilder; import java.lang.SuppressWarnings; import io.kubernetes.client.fluent.Nested; import java.util.ArrayList; import java.lang.String; import java.util.function.Predicate; import java.lang.RuntimeException; import io.kubernetes.client.fluent.BaseFluent; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Objects; import java.util.Collection; import java.lang.Object; /** * Generated */ @SuppressWarnings("unchecked") public class V1alpha1StorageVersionListFluent<A extends io.kubernetes.client.openapi.models.V1alpha1StorageVersionListFluent<A>> extends BaseFluent<A>{ public V1alpha1StorageVersionListFluent() { } public V1alpha1StorageVersionListFluent(V1alpha1StorageVersionList instance) { this.copyInstance(instance); } private String apiVersion; private ArrayList<V1alpha1StorageVersionBuilder> items; private String kind; private V1ListMetaBuilder metadata; protected void copyInstance(V1alpha1StorageVersionList instance) { instance = instance != null ? instance : new V1alpha1StorageVersionList(); if (instance != null) { this.withApiVersion(instance.getApiVersion()); this.withItems(instance.getItems()); this.withKind(instance.getKind()); this.withMetadata(instance.getMetadata()); } } public String getApiVersion() { return this.apiVersion; } public A withApiVersion(String apiVersion) { this.apiVersion = apiVersion; return (A) this; } public boolean hasApiVersion() { return this.apiVersion != null; } public A addToItems(int index,V1alpha1StorageVersion item) { if (this.items == null) { this.items = new ArrayList(); } V1alpha1StorageVersionBuilder builder = new V1alpha1StorageVersionBuilder(item); if (index < 0 || index >= items.size()) { _visitables.get("items").add(builder); items.add(builder); } else { _visitables.get("items").add(builder); items.add(index, builder); } return (A) this; } public A setToItems(int index,V1alpha1StorageVersion item) { if (this.items == null) { this.items = new ArrayList(); } V1alpha1StorageVersionBuilder builder = new V1alpha1StorageVersionBuilder(item); if (index < 0 || index >= items.size()) { _visitables.get("items").add(builder); items.add(builder); } else { _visitables.get("items").add(builder); items.set(index, builder); } return (A) this; } public A addToItems(V1alpha1StorageVersion... items) { if (this.items == null) { this.items = new ArrayList(); } for (V1alpha1StorageVersion item : items) { V1alpha1StorageVersionBuilder builder = new V1alpha1StorageVersionBuilder(item); _visitables.get("items").add(builder); this.items.add(builder); } return (A) this; } public A addAllToItems(Collection<V1alpha1StorageVersion> items) { if (this.items == null) { this.items = new ArrayList(); } for (V1alpha1StorageVersion item : items) { V1alpha1StorageVersionBuilder builder = new V1alpha1StorageVersionBuilder(item); _visitables.get("items").add(builder); this.items.add(builder); } return (A) this; } public A removeFromItems(V1alpha1StorageVersion... items) { if (this.items == null) { return (A) this; } for (V1alpha1StorageVersion item : items) { V1alpha1StorageVersionBuilder builder = new V1alpha1StorageVersionBuilder(item); _visitables.get("items").remove(builder); this.items.remove(builder); } return (A) this; } public A removeAllFromItems(Collection<V1alpha1StorageVersion> items) { if (this.items == null) { return (A) this; } for (V1alpha1StorageVersion item : items) { V1alpha1StorageVersionBuilder builder = new V1alpha1StorageVersionBuilder(item); _visitables.get("items").remove(builder); this.items.remove(builder); } return (A) this; } public A removeMatchingFromItems(Predicate<V1alpha1StorageVersionBuilder> predicate) { if (items == null) { return (A) this; } Iterator<V1alpha1StorageVersionBuilder> each = items.iterator(); List visitables = _visitables.get("items"); while (each.hasNext()) { V1alpha1StorageVersionBuilder builder = each.next(); if (predicate.test(builder)) { visitables.remove(builder); each.remove(); } } return (A) this; } public List<V1alpha1StorageVersion> buildItems() { return this.items != null ? build(items) : null; } public V1alpha1StorageVersion buildItem(int index) { return this.items.get(index).build(); } public V1alpha1StorageVersion buildFirstItem() { return this.items.get(0).build(); } public V1alpha1StorageVersion buildLastItem() { return this.items.get(items.size() - 1).build(); } public V1alpha1StorageVersion buildMatchingItem(Predicate<V1alpha1StorageVersionBuilder> predicate) { for (V1alpha1StorageVersionBuilder item : items) { if (predicate.test(item)) { return item.build(); } } return null; } public boolean hasMatchingItem(Predicate<V1alpha1StorageVersionBuilder> predicate) { for (V1alpha1StorageVersionBuilder item : items) { if (predicate.test(item)) { return true; } } return false; } public A withItems(List<V1alpha1StorageVersion> items) { if (this.items != null) { this._visitables.get("items").clear(); } if (items != null) { this.items = new ArrayList(); for (V1alpha1StorageVersion item : items) { this.addToItems(item); } } else { this.items = null; } return (A) this; } public A withItems(V1alpha1StorageVersion... items) { if (this.items != null) { this.items.clear(); _visitables.remove("items"); } if (items != null) { for (V1alpha1StorageVersion item : items) { this.addToItems(item); } } return (A) this; } public boolean hasItems() { return this.items != null && !(this.items.isEmpty()); } public ItemsNested<A> addNewItem() { return new ItemsNested(-1, null); } public ItemsNested<A> addNewItemLike(V1alpha1StorageVersion item) { return new ItemsNested(-1, item); } public ItemsNested<A> setNewItemLike(int index,V1alpha1StorageVersion item) { return new ItemsNested(index, item); } public ItemsNested<A> editItem(int index) { if (index <= items.size()) { throw new RuntimeException(String.format("Can't edit %s. Index exceeds size.", "items")); } return this.setNewItemLike(index, this.buildItem(index)); } public ItemsNested<A> editFirstItem() { if (items.size() == 0) { throw new RuntimeException(String.format("Can't edit first %s. The list is empty.", "items")); } return this.setNewItemLike(0, this.buildItem(0)); } public ItemsNested<A> editLastItem() { int index = items.size() - 1; if (index < 0) { throw new RuntimeException(String.format("Can't edit last %s. The list is empty.", "items")); } return this.setNewItemLike(index, this.buildItem(index)); } public ItemsNested<A> editMatchingItem(Predicate<V1alpha1StorageVersionBuilder> predicate) { int index = -1; for (int i = 0;i < items.size();i++) { if (predicate.test(items.get(i))) { index = i; break; } } if (index < 0) { throw new RuntimeException(String.format("Can't edit matching %s. No match found.", "items")); } return this.setNewItemLike(index, this.buildItem(index)); } public String getKind() { return this.kind; } public A withKind(String kind) { this.kind = kind; return (A) this; } public boolean hasKind() { return this.kind != null; } public V1ListMeta buildMetadata() { return this.metadata != null ? this.metadata.build() : null; } public A withMetadata(V1ListMeta metadata) { this._visitables.remove("metadata"); if (metadata != null) { this.metadata = new V1ListMetaBuilder(metadata); this._visitables.get("metadata").add(this.metadata); } else { this.metadata = null; this._visitables.get("metadata").remove(this.metadata); } return (A) this; } public boolean hasMetadata() { return this.metadata != null; } public MetadataNested<A> withNewMetadata() { return new MetadataNested(null); } public MetadataNested<A> withNewMetadataLike(V1ListMeta item) { return new MetadataNested(item); } public MetadataNested<A> editMetadata() { return this.withNewMetadataLike(Optional.ofNullable(this.buildMetadata()).orElse(null)); } public MetadataNested<A> editOrNewMetadata() { return this.withNewMetadataLike(Optional.ofNullable(this.buildMetadata()).orElse(new V1ListMetaBuilder().build())); } public MetadataNested<A> editOrNewMetadataLike(V1ListMeta item) { return this.withNewMetadataLike(Optional.ofNullable(this.buildMetadata()).orElse(item)); } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || this.getClass() != o.getClass()) { return false; } if (!(super.equals(o))) { return false; } V1alpha1StorageVersionListFluent that = (V1alpha1StorageVersionListFluent) o; if (!(Objects.equals(apiVersion, that.apiVersion))) { return false; } if (!(Objects.equals(items, that.items))) { return false; } if (!(Objects.equals(kind, that.kind))) { return false; } if (!(Objects.equals(metadata, that.metadata))) { return false; } return true; } public int hashCode() { return Objects.hash(apiVersion, items, kind, metadata); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (!(apiVersion == null)) { sb.append("apiVersion:"); sb.append(apiVersion); sb.append(","); } if (!(items == null) && !(items.isEmpty())) { sb.append("items:"); sb.append(items); sb.append(","); } if (!(kind == null)) { sb.append("kind:"); sb.append(kind); sb.append(","); } if (!(metadata == null)) { sb.append("metadata:"); sb.append(metadata); } sb.append("}"); return sb.toString(); } public class ItemsNested<N> extends V1alpha1StorageVersionFluent<ItemsNested<N>> implements Nested<N>{ ItemsNested(int index,V1alpha1StorageVersion item) { this.index = index; this.builder = new V1alpha1StorageVersionBuilder(this, item); } V1alpha1StorageVersionBuilder builder; int index; public N and() { return (N) V1alpha1StorageVersionListFluent.this.setToItems(index, builder.build()); } public N endItem() { return and(); } } public class MetadataNested<N> extends V1ListMetaFluent<MetadataNested<N>> implements Nested<N>{ MetadataNested(V1ListMeta item) { this.builder = new V1ListMetaBuilder(this, item); } V1ListMetaBuilder builder; public N and() { return (N) V1alpha1StorageVersionListFluent.this.withMetadata(builder.build()); } public N endMetadata() { return and(); } } }
412
0.934212
1
0.934212
game-dev
MEDIA
0.51143
game-dev
0.978506
1
0.978506
gilbutITbook/006772
4,349
Unity 4.5.1/09/dokidoki_ganmodoki/Assets/Script/Character/Player/chrBehaviorBeast_Dog.cs
using UnityEngine; using System.Collections; // 소환수 개. public class chrBehaviorBeast_Dog : chrBehaviorBase { public Vector3 position_in_formation = Vector3.zero; private Vector3 move_target; // 이동할 위치. private Vector3 heading_target; // 향할 곳. //protected string move_target_item = ""; // 아이템을 목표로 이동할 때. protected string collision = ""; //public chrBehaviorLocal local_player = null; public bool in_formation = true; // 로컬 플레이어와 함께 이동한다(디버그용). // ---------------------------------------------------------------- // public enum STEP { NONE = -1, MOVE = 0, // 이동. STOP, // 정지. NUM, }; public Step<STEP> step = new Step<STEP>(STEP.NONE); //public STEP step = STEP.NONE; //public STEP next_step = STEP.NONE; //public float step_timer = 0.0f; // ================================================================ // // MonoBehaviour에서 상속. void Awake() { } void Start() { } void Update() { } // ================================================================ // public override void initialize() { base.initialize(); this.move_target = this.transform.position; } public override void start() { base.start(); this.step.set_next(STEP.STOP); } public override void execute() { base.execute(); float stop_to_move = 5.0f; float move_to_stop = 3.0f; chrBehaviorLocal player = PartyControl.get().getLocalPlayer(); // ---------------------------------------------------------------- // // 다음 상태로 전환할지 체크한다. switch(this.step.do_transition()) { case STEP.STOP: { Vector3 ditance_vector = player.control.getPosition() - this.control.getPosition(); ditance_vector.y = 0.0f; if(ditance_vector.magnitude >= stop_to_move) { this.step.set_next(STEP.MOVE); } } break; case STEP.MOVE: { Vector3 ditance_vector = player.control.getPosition() - this.control.getPosition(); ditance_vector.y = 0.0f; if(ditance_vector.magnitude <= move_to_stop) { this.step.set_next(STEP.STOP); } } break; } // ---------------------------------------------------------------- // // 상태 전환 시 초기화. while(this.step.get_next() != STEP.NONE) { switch(this.step.do_initialize()) { case STEP.MOVE: { this.move_target = player.control.getPosition(); this.heading_target = this.move_target; } break; } } // ---------------------------------------------------------------- // // 각 상태에서의 실행 처리. switch(this.step.do_execution(Time.deltaTime)) { case STEP.MOVE: { this.move_target = player.control.getPosition(); this.heading_target = this.move_target; this.exec_step_move(); } break; } this.collision = ""; // ---------------------------------------------------------------- // } // ================================================================ // // STEP.MOVE 실행. // 이동. protected void exec_step_move() { // ---------------------------------------------------------------- // // 이동(위치 좌표 보간). Vector3 position = this.control.getPosition(); float cur_dir = this.control.getDirection(); Vector3 dist = this.move_target - position; dist.y = 0.0f; float speed = 5.0f; float speed_per_frame = speed*Time.deltaTime; if(dist.magnitude < speed_per_frame) { // 멈춘다. this.control.cmdSetMotion("m002_idle", 0); dist = Vector3.zero; } else { // 걷는다. this.control.cmdSetMotion("m001_walk", 0); dist *= (speed_per_frame)/dist.magnitude; } position += dist; // 방향 보간 float tgt_dir; if(Vector3.Distance(this.heading_target, position) > 0.01f) { tgt_dir = Quaternion.LookRotation(this.heading_target - position).eulerAngles.y; } else { tgt_dir = cur_dir; } float dir_diff = tgt_dir - cur_dir; if(dir_diff > 180.0f) { dir_diff = dir_diff - 360.0f; } else if(dir_diff < -180.0f) { dir_diff = dir_diff + 360.0f; } //if(!gi.pointing.current && gi.shot.trigger_on) { //} else { dir_diff *= 0.1f; //} if(Mathf.Abs(dir_diff) < 1.0f) { cur_dir = tgt_dir; } else { cur_dir += dir_diff; } position.y = this.control.getPosition().y; this.control.cmdSetPosition(position); this.control.cmdSetDirection(cur_dir); } // ================================================================ // }
412
0.847931
1
0.847931
game-dev
MEDIA
0.967028
game-dev
0.9727
1
0.9727
lvfengchi/livox_laser_simulation
9,871
src/livox_ode_multiray_shape.cpp
// // Created by lfc on 2021/2/28. // #include "livox_laser_simulation/livox_ode_multiray_shape.h" #include <gazebo/common/Assert.hh> #include <gazebo/common/Exception.hh> #include <gazebo/physics/World.hh> #include <gazebo/physics/ode/ODECollision.hh> #include <gazebo/physics/ode/ODELink.hh> #include <gazebo/physics/ode/ODEMultiRayShape.hh> #include <gazebo/physics/ode/ODEPhysics.hh> #include <gazebo/physics/ode/ODERayShape.hh> #include <gazebo/physics/ode/ODETypes.hh> using namespace gazebo; using namespace physics; ////////////////////////////////////////////////// LivoxOdeMultiRayShape::LivoxOdeMultiRayShape(CollisionPtr _parent) : MultiRayShape(_parent) { this->SetName("ODE Multiray Shape"); // Create a space to contain the ray space this->superSpaceId = dSimpleSpaceCreate(0); // Create a space to contain all the rays this->raySpaceId = dSimpleSpaceCreate(this->superSpaceId); // Set collision bits dGeomSetCategoryBits((dGeomID)this->raySpaceId, GZ_SENSOR_COLLIDE); dGeomSetCollideBits((dGeomID)this->raySpaceId, ~GZ_SENSOR_COLLIDE); // These three lines may be unessecary ODELinkPtr pLink = boost::static_pointer_cast<ODELink>(this->collisionParent->GetLink()); pLink->SetSpaceId(this->raySpaceId); boost::static_pointer_cast<ODECollision>(this->collisionParent)->SetSpaceId(this->raySpaceId); } ////////////////////////////////////////////////// LivoxOdeMultiRayShape::~LivoxOdeMultiRayShape() { dSpaceSetCleanup(this->raySpaceId, 0); dSpaceDestroy(this->raySpaceId); dSpaceSetCleanup(this->superSpaceId, 0); dSpaceDestroy(this->superSpaceId); } ////////////////////////////////////////////////// void LivoxOdeMultiRayShape::UpdateRays() { ODEPhysicsPtr ode = boost::dynamic_pointer_cast<ODEPhysics>(this->GetWorld()->GetPhysicsEngine()); if (ode == NULL) gzthrow("Invalid physics engine. Must use ODE."); // Do we need to lock the physics engine here? YES! // especially when spawning models with sensors { boost::recursive_mutex::scoped_lock lock(*ode->GetPhysicsUpdateMutex()); // Do collision detection dSpaceCollide2((dGeomID)(this->superSpaceId), (dGeomID)(ode->GetSpaceId()), this, &UpdateCallback); } } ////////////////////////////////////////////////// void LivoxOdeMultiRayShape::UpdateCallback(void *_data, dGeomID _o1, dGeomID _o2) { dContactGeom contact; LivoxOdeMultiRayShape *self = NULL; self = static_cast<LivoxOdeMultiRayShape *>(_data); // Check space if (dGeomIsSpace(_o1) || dGeomIsSpace(_o2)) { if (dGeomGetSpace(_o1) == self->superSpaceId || dGeomGetSpace(_o2) == self->superSpaceId) dSpaceCollide2(_o1, _o2, self, &UpdateCallback); if (dGeomGetSpace(_o1) == self->raySpaceId || dGeomGetSpace(_o2) == self->raySpaceId) dSpaceCollide2(_o1, _o2, self, &UpdateCallback); } else { ODECollision *collision1 = NULL; ODECollision *collision2 = NULL; // Get pointers to the underlying collisions if (dGeomGetClass(_o1) == dGeomTransformClass) { collision1 = static_cast<ODECollision *>(dGeomGetData(dGeomTransformGetGeom(_o1))); } else collision1 = static_cast<ODECollision *>(dGeomGetData(_o1)); if (dGeomGetClass(_o2) == dGeomTransformClass) { collision2 = static_cast<ODECollision *>(dGeomGetData(dGeomTransformGetGeom(_o2))); } else { collision2 = static_cast<ODECollision *>(dGeomGetData(_o2)); } GZ_ASSERT(collision1, "collision1 is null"); GZ_ASSERT(collision2, "collision2 is null"); ODECollision *rayCollision = NULL; ODECollision *hitCollision = NULL; // Figure out which one is a ray; note that this assumes // that the ODE dRayClass is used *soley* by the RayCollision. if (dGeomGetClass(_o1) == dRayClass) { rayCollision = static_cast<ODECollision *>(collision1); hitCollision = static_cast<ODECollision *>(collision2); dGeomRaySetParams(_o1, 0, 0); dGeomRaySetClosestHit(_o1, 1); } else if (dGeomGetClass(_o2) == dRayClass) { GZ_ASSERT(rayCollision == NULL, "rayCollision is not null"); rayCollision = static_cast<ODECollision *>(collision2); hitCollision = static_cast<ODECollision *>(collision1); dGeomRaySetParams(_o2, 0, 0); dGeomRaySetClosestHit(_o2, 1); } // Check for ray/collision intersections if (rayCollision && hitCollision) { int n = dCollide(_o1, _o2, 1, &contact, sizeof(contact)); if (n > 0) { RayShapePtr shape = boost::static_pointer_cast<RayShape>(rayCollision->GetShape()); if (contact.depth < shape->GetLength()) { // gzerr << "LivoxOdeMultiRayShape UpdateCallback dSpaceCollide2 " // << " depth[" << contact.depth << "]" // << " position[" << contact.pos[0] // << ", " << contact.pos[1] // << ", " << contact.pos[2] // << ", " << "]" // << " ray[" << rayCollision->GetScopedName() << "]" // << " pose[" << rayCollision->GetWorldPose() << "]" // << " hit[" << hitCollision->GetScopedName() << "]" // << " pose[" << hitCollision->GetWorldPose() << "]" // << "\n"; shape->SetLength(contact.depth); shape->SetRetro(hitCollision->GetLaserRetro()); } } } } } ////////////////////////////////////////////////// void LivoxOdeMultiRayShape::AddRay(const math::Vector3 &_start, const math::Vector3 &_end) { MultiRayShape::AddRay(_start, _end); ODECollisionPtr odeCollision(new ODECollision(this->collisionParent->GetLink())); odeCollision->SetName("ode_ray_collision"); odeCollision->SetSpaceId(this->raySpaceId); ODERayShapePtr ray(new ODERayShape(odeCollision)); odeCollision->SetShape(ray); ray->SetPoints(_start, _end); this->rays.push_back(ray); } void LivoxOdeMultiRayShape::Init() { math::Vector3 start, end, axis; double yawAngle, pitchAngle; math::Quaternion ray; double yDiff; double horzMinAngle, horzMaxAngle; int horzSamples = 1; // double horzResolution = 1.0; double pDiff = 0; int vertSamples = 1; // double vertResolution = 1.0; double vertMinAngle = 0; double minRange, maxRange; this->rayElem = this->sdf->GetElement("ray"); this->scanElem = this->rayElem->GetElement("scan"); this->horzElem = this->scanElem->GetElement("horizontal"); this->rangeElem = this->rayElem->GetElement("range"); if (this->scanElem->HasElement("vertical")) { this->vertElem = this->scanElem->GetElement("vertical"); vertMinAngle = this->vertElem->Get<double>("min_angle"); double vertMaxAngle = this->vertElem->Get<double>("max_angle"); vertSamples = this->vertElem->Get<unsigned int>("samples"); // vertResolution = this->vertElem->Get<double>("resolution"); pDiff = vertMaxAngle - vertMinAngle; } horzMinAngle = this->horzElem->Get<double>("min_angle"); horzMaxAngle = this->horzElem->Get<double>("max_angle"); horzSamples = this->horzElem->Get<unsigned int>("samples"); // horzResolution = this->horzElem->Get<double>("resolution"); yDiff = horzMaxAngle - horzMinAngle; minRange = this->rangeElem->Get<double>("min"); maxRange = this->rangeElem->Get<double>("max"); // this->offset = this->collisionParent->GetRelativePose(); // Create an array of ray collisions // for (unsigned int j = 0; j < (unsigned int)vertSamples; ++j) // { // for (unsigned int i = 0; i < (unsigned int)horzSamples; ++i) // { // yawAngle = (horzSamples == 1) ? 0 : // i * yDiff / (horzSamples - 1) + horzMinAngle; // // pitchAngle = (vertSamples == 1)? 0 : // j * pDiff / (vertSamples - 1) + vertMinAngle; // // // since we're rotating a unit x vector, a pitch rotation will now be // // around the negative y axis // ray.SetFromEuler(math::Vector3(0.0, -pitchAngle, yawAngle)); // axis = this->offset.rot * ray * math::Vector3(1.0, 0.0, 0.0); // // start = (axis * minRange) + this->offset.pos; // end = (axis * maxRange) + this->offset.pos; // // this->AddRay(start, end); // } // } } double gazebo::physics::LivoxOdeMultiRayShape::GetRange(unsigned int _index) { if (_index >= this->rays.size()) { std::ostringstream stream; stream << "index[" << _index << "] out of range[0-" << this->rays.size() << "]"; gzthrow(stream.str()); } // Add min range, because we measured from min range. return this->GetMinRange() + this->rays[_index]->GetLength(); } void gazebo::physics::LivoxOdeMultiRayShape::Update() { // The measurable range is (max-min) static double fullRange = this->GetMaxRange() - this->GetMinRange(); // Reset the ray lengths and mark the collisions as dirty (so they get // redrawn) unsigned int ray_size = this->rays.size(); #pragma omp parallel for for (unsigned int i = 0; i < ray_size; i++) { this->rays[i]->SetLength(fullRange); this->rays[i]->SetRetro(0.0); // Get the global points of the line this->rays[i]->Update(); } // do actual collision checks this->UpdateRays(); // for plugin this->newLaserScans(); }
412
0.92135
1
0.92135
game-dev
MEDIA
0.694317
game-dev
0.982144
1
0.982144
project-topaz/topaz
5,907
scripts/zones/Windurst_Waters/npcs/Mashuu-Ajuu.lua
----------------------------------- -- Area: Windurst Waters -- NPC: Mashuu-Ajuu -- Starts and Finished Quest: Reap What You Sow -- Involved in Quest: Making the Grade -- !pos 129 -6 167 238 ----------------------------------- local ID = require("scripts/zones/Windurst_Waters/IDs") require("scripts/globals/settings") require("scripts/globals/keyitems") require("scripts/globals/quests") require("scripts/globals/titles") ----------------------------------- function onTrade(player, npc, trade) local reapstatus = player:getQuestStatus(WINDURST, tpz.quest.id.windurst.REAP_WHAT_YOU_SOW) if (reapstatus >= 1 and trade:getItemCount() == 1 and trade:getGil() == 0) then if (trade:hasItemQty(4565, 1) == true) then player:startEvent(475, 500, 131) -- REAP WHAT YOU SOW + GIL: Quest Turn In: Sobbing Fungus turned in elseif (trade:hasItemQty(4566, 1) == true) then player:startEvent(477, 700) -- REAP WHAT YOU SOW + GIL + Stationary Set: Deathball turned in end end end function onTrigger(player, npc) local reapstatus = player:getQuestStatus(WINDURST, tpz.quest.id.windurst.REAP_WHAT_YOU_SOW) if (player:getQuestStatus(WINDURST, tpz.quest.id.windurst.MAKING_THE_GRADE) == QUEST_ACCEPTED) then player:startEvent(448) -- During Making the GRADE elseif (reapstatus == QUEST_AVAILABLE) then rand = math.random(1, 2) if (rand == 1) then player:startEvent(463, 0, 4565, 572) -- REAP WHAT YOU SOW + HERB SEEDS: QUEST START else player:startEvent(429) -- Standard Conversation end elseif (reapstatus == QUEST_ACCEPTED) then rand = math.random(1, 2) if (rand == 1) then player:startEvent(464, 0, 4565, 572) -- REAP WHAT YOU SOW + HERB SEEDS: OBJECTIVE REMINDER else player:startEvent(476) -- Another Conversation During Quest end elseif (reapstatus == QUEST_COMPLETED and player:needToZone()) then player:startEvent(478) -- REAP WHAT YOU SOW: After Quest elseif (reapstatus == QUEST_COMPLETED and player:needToZone() == false and player:getCharVar("QuestReapSow_var") == 0) then rand = math.random(1, 2) if (rand == 1) then player:startEvent(479, 0, 4565, 572) -- REAP WHAT YOU SOW + HERB SEEDS: REPEATABLE QUEST START else player:startEvent(429) -- Standard Conversation end elseif (reapstatus == QUEST_COMPLETED and player:getCharVar("QuestReapSow_var") == 1) then rand = math.random(1, 2) if (rand == 1) then player:startEvent(464, 0, 4565, 572) -- REAP WHAT YOU SOW + HERB SEEDS: OBJECTIVE REMINDER else player:startEvent(476) -- Another Conversation During Quest end else player:startEvent(429) -- Standard Conversation end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if (((csid == 463 and option == 3) or (csid == 479 and option == 3)) and player:getFreeSlotsCount() == 0) then -- REAP WHAT YOU SOW + HERB SEEDS: QUEST START - ACCEPTED - INVENTORY FULL player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED, 572) elseif (csid == 463 and option == 3) then -- REAP WHAT YOU SOW + HERB SEEDS: QUEST START - ACCEPTED player:addQuest(WINDURST, tpz.quest.id.windurst.REAP_WHAT_YOU_SOW) player:addItem(572) player:messageSpecial(ID.text.ITEM_OBTAINED, 572) elseif ((csid == 475 or csid == 477) and player:getQuestStatus(WINDURST, tpz.quest.id.windurst.REAP_WHAT_YOU_SOW) == QUEST_ACCEPTED and player:getFreeSlotsCount() == 0) then -- inventory full on quest turn in player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED, 131) elseif (csid == 475) then -- REAP WHAT YOU SOW + 500 GIL: Quest Turn In: Sobbing Fungus turned in player:addGil(GIL_RATE*500) player:tradeComplete(trade) player:needToZone(true) if (player:getQuestStatus(WINDURST, tpz.quest.id.windurst.REAP_WHAT_YOU_SOW) == QUEST_ACCEPTED) then player:completeQuest(WINDURST, tpz.quest.id.windurst.REAP_WHAT_YOU_SOW) player:addFame(WINDURST, 75) player:addItem(131) player:messageSpecial(ID.text.ITEM_OBTAINED, 131) elseif (player:getQuestStatus(WINDURST, tpz.quest.id.windurst.REAP_WHAT_YOU_SOW) == QUEST_COMPLETED) then player:addFame(WINDURST, 8) player:setCharVar("QuestReapSow_var", 0) end elseif (csid == 477) then -- REAP WHAT YOU SOW + GIL + Stationary Set: Quest Turn In: Deathball turned in player:addGil(GIL_RATE*700) player:tradeComplete(trade) player:needToZone(true) if (player:getQuestStatus(WINDURST, tpz.quest.id.windurst.REAP_WHAT_YOU_SOW) == QUEST_ACCEPTED) then player:completeQuest(WINDURST, tpz.quest.id.windurst.REAP_WHAT_YOU_SOW) player:addFame(WINDURST, 75) player:addItem(131) player:messageSpecial(ID.text.ITEM_OBTAINED, 131) elseif (player:getQuestStatus(WINDURST, tpz.quest.id.windurst.REAP_WHAT_YOU_SOW) == QUEST_COMPLETED) then player:addFame(WINDURST, 8) player:setCharVar("QuestReapSow_var", 0) end elseif (csid == 479 and option == 3) then -- REAP WHAT YOU SOW + HERB SEEDS: REPEATABLE QUEST START - ACCEPTED player:setCharVar("QuestReapSow_var", 1) player:addItem(572) player:messageSpecial(ID.text.ITEM_OBTAINED, 572) end end
412
0.941984
1
0.941984
game-dev
MEDIA
0.975919
game-dev
0.911105
1
0.911105
DruidMech/UE4-CPP-Shooter-Series
2,240
Source Code Per Lesson/Section 2 - Project Setup/18 Mouse Input and Jumping/ShooterCharacter.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "ShooterCharacter.generated.h" UCLASS() class SHOOTER_API AShooterCharacter : public ACharacter { GENERATED_BODY() public: // Sets default values for this character's properties AShooterCharacter(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; /** Called for forwards/backwards input */ void MoveForward(float Value); /** Called for side to side input */ void MoveRight(float Value); /** * Called via input to turn at a given rate. * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate */ void TurnAtRate(float Rate); /** * Called via input to look up/down at a given rate. * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired rate */ void LookUpAtRate(float Rate); public: // Called every frame virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; private: /** Camera boom positioning the camera behind the character */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class USpringArmComponent* CameraBoom; /** Camera that follows the character */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class UCameraComponent* FollowCamera; /** Base turn rate, in deg/sec. Other scaling may affect final turn rate */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) float BaseTurnRate; /** Base look up/down rate, in deg/sec. Other scaling may affect final turn rate */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) float BaseLookUpRate; public: /** Returns CameraBoom subobject */ FORCEINLINE USpringArmComponent* GetCameraBoom() const { return CameraBoom; } /** Returns FollowCamera subobject */ FORCEINLINE UCameraComponent* GetFollowCamera() const { return FollowCamera; } };
412
0.876216
1
0.876216
game-dev
MEDIA
0.915086
game-dev
0.753632
1
0.753632
Glitchfiend/BiomesOPlenty
10,955
common/src/main/java/biomesoplenty/worldgen/feature/BOPNetherFeatures.java
/******************************************************************************* * Copyright 2022, the Glitchfiend Team. * All rights reserved. ******************************************************************************/ package biomesoplenty.worldgen.feature; import biomesoplenty.api.block.BOPBlocks; import biomesoplenty.api.block.BOPFluids; import biomesoplenty.worldgen.placement.BOPTreePlacements; import biomesoplenty.util.worldgen.BOPFeatureUtils; import biomesoplenty.init.ModTags; import com.google.common.collect.ImmutableList; import net.minecraft.core.Holder; import net.minecraft.core.HolderGetter; import net.minecraft.core.HolderSet; import net.minecraft.core.registries.Registries; import net.minecraft.data.worldgen.BootstrapContext; import net.minecraft.data.worldgen.features.FeatureUtils; import net.minecraft.resources.ResourceKey; import net.minecraft.util.valueproviders.UniformFloat; import net.minecraft.util.valueproviders.UniformInt; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.LakeFeature; import net.minecraft.world.level.levelgen.feature.WeightedPlacedFeature; import net.minecraft.world.level.levelgen.feature.configurations.*; import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; import net.minecraft.world.level.levelgen.placement.PlacedFeature; import net.minecraft.world.level.levelgen.structure.templatesystem.TagMatchTest; import net.minecraft.world.level.material.Fluids; public class BOPNetherFeatures { public static final ResourceKey<ConfiguredFeature<?, ?>> BLACKSTONE_BULB = BOPFeatureUtils.createKey("blackstone_bulb"); public static final ResourceKey<ConfiguredFeature<?, ?>> BLACKSTONE_SPINES = BOPFeatureUtils.createKey("blackstone_spines"); public static final ResourceKey<ConfiguredFeature<?, ?>> BLOOD_LAKE = BOPFeatureUtils.createKey("blood_lake"); public static final ResourceKey<ConfiguredFeature<?, ?>> BLOOD_SPRING = BOPFeatureUtils.createKey("blood_spring"); public static final ResourceKey<ConfiguredFeature<?, ?>> BRIMSTONE_BUD = BOPFeatureUtils.createKey("brimstone_bud"); public static final ResourceKey<ConfiguredFeature<?, ?>> BRIMSTONE_CLUSTER = BOPFeatureUtils.createKey("brimstone_cluster"); public static final ResourceKey<ConfiguredFeature<?, ?>> DEAD_GRASS = BOPFeatureUtils.createKey("dead_grass"); public static final ResourceKey<ConfiguredFeature<?, ?>> EYEBULB = BOPFeatureUtils.createKey("eyebulb"); public static final ResourceKey<ConfiguredFeature<?, ?>> FLESH_TENDON = BOPFeatureUtils.createKey("flesh_tendon"); public static final ResourceKey<ConfiguredFeature<?, ?>> HAIR = BOPFeatureUtils.createKey("hair"); public static final ResourceKey<ConfiguredFeature<?, ?>> HANGING_FLESH_TENDON = BOPFeatureUtils.createKey("hanging_flesh_tendon"); public static final ResourceKey<ConfiguredFeature<?, ?>> INFERNO_LAVA_LAKE = BOPFeatureUtils.createKey("inferno_lava_lake"); public static final ResourceKey<ConfiguredFeature<?, ?>> INFERNO_LAVA_SPRING = BOPFeatureUtils.createKey("inferno_lava_spring"); public static final ResourceKey<ConfiguredFeature<?, ?>> INFERNO_SPLATTER = BOPFeatureUtils.createKey("inferno_splatter"); public static final ResourceKey<ConfiguredFeature<?, ?>> LARGE_FUMAROLE = BOPFeatureUtils.createKey("large_fumarole"); public static final ResourceKey<ConfiguredFeature<?, ?>> LARGE_ROSE_QUARTZ = BOPFeatureUtils.createKey("large_rose_quartz"); public static final ResourceKey<ConfiguredFeature<?, ?>> NETHER_BONE_SPINE = BOPFeatureUtils.createKey("nether_bone_spine"); public static final ResourceKey<ConfiguredFeature<?, ?>> NETHER_BRAMBLE = BOPFeatureUtils.createKey("nether_bramble"); public static final ResourceKey<ConfiguredFeature<?, ?>> NETHER_VINES = BOPFeatureUtils.createKey("nether_vines"); public static final ResourceKey<ConfiguredFeature<?, ?>> OBSIDIAN_SPLATTER = BOPFeatureUtils.createKey("obsidian_splatter"); public static final ResourceKey<ConfiguredFeature<?, ?>> POROUS_FLESH = BOPFeatureUtils.createKey("porous_flesh"); public static final ResourceKey<ConfiguredFeature<?, ?>> PUS_BUBBLES = BOPFeatureUtils.createKey("pus_bubbles"); public static final ResourceKey<ConfiguredFeature<?, ?>> SMALL_CRYSTAL = BOPFeatureUtils.createKey("small_crystal"); public static final ResourceKey<ConfiguredFeature<?, ?>> SMALL_FUMAROLE = BOPFeatureUtils.createKey("small_fumarole"); public static final ResourceKey<ConfiguredFeature<?, ?>> SPROUTS_UNDERGROWTH = BOPFeatureUtils.createKey("sprouts_undergrowth"); public static final ResourceKey<ConfiguredFeature<?, ?>> TREES_UNDERGROWTH = BOPFeatureUtils.createKey("trees_undergrowth"); public static final ResourceKey<ConfiguredFeature<?, ?>> UNDERGROWTH_FLOWERS = BOPFeatureUtils.createKey("undergrowth_flowers"); public static void bootstrap(BootstrapContext<ConfiguredFeature<?, ?>> context) { HolderGetter<PlacedFeature> placedFeatureGetter = context.lookup(Registries.PLACED_FEATURE); final Holder<PlacedFeature> BIG_HELLBARK_TREE_CHECKED = placedFeatureGetter.getOrThrow(BOPTreePlacements.BIG_HELLBARK_TREE_CHECKED); final Holder<PlacedFeature> HELLBARK_TREE_CHECKED = placedFeatureGetter.getOrThrow(BOPTreePlacements.HELLBARK_TREE_CHECKED); register(context, BOPNetherFeatures.BLACKSTONE_BULB, Feature.RANDOM_PATCH, FeatureUtils.simplePatchConfiguration(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(BlockStateProvider.simple(BOPBlocks.BLACKSTONE_BULB)))); register(context, BOPNetherFeatures.BLACKSTONE_SPINES, Feature.RANDOM_PATCH, FeatureUtils.simplePatchConfiguration(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(BlockStateProvider.simple(BOPBlocks.BLACKSTONE_SPINES)))); register(context, BOPNetherFeatures.BLOOD_LAKE, BOPBaseFeatures.LAKE, new LakeFeature.Configuration(BlockStateProvider.simple(BOPBlocks.BLOOD), BlockStateProvider.simple(BOPBlocks.FLESH))); register(context, BOPNetherFeatures.BLOOD_SPRING, Feature.SPRING, new SpringConfiguration(BOPFluids.BLOOD.defaultFluidState(), false, 4, 1, HolderSet.direct(Block::builtInRegistryHolder, Blocks.NETHERRACK, BOPBlocks.FLESH, BOPBlocks.POROUS_FLESH))); register(context, BOPNetherFeatures.BRIMSTONE_BUD, Feature.RANDOM_PATCH, FeatureUtils.simplePatchConfiguration(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(BlockStateProvider.simple(BOPBlocks.BRIMSTONE_BUD)))); register(context, BOPNetherFeatures.BRIMSTONE_CLUSTER, Feature.RANDOM_PATCH, FeatureUtils.simplePatchConfiguration(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(BlockStateProvider.simple(BOPBlocks.BRIMSTONE_CLUSTER)))); register(context, BOPNetherFeatures.DEAD_GRASS, Feature.RANDOM_PATCH, FeatureUtils.simplePatchConfiguration(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(BlockStateProvider.simple(BOPBlocks.DEAD_GRASS)))); register(context, BOPNetherFeatures.EYEBULB, Feature.RANDOM_PATCH, FeatureUtils.simplePatchConfiguration(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(BlockStateProvider.simple(BOPBlocks.EYEBULB)))); register(context, BOPNetherFeatures.FLESH_TENDON, BOPBaseFeatures.FLESH_TENDON, NoneFeatureConfiguration.INSTANCE); register(context, BOPNetherFeatures.HAIR, Feature.RANDOM_PATCH, FeatureUtils.simplePatchConfiguration(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(BlockStateProvider.simple(BOPBlocks.HAIR)))); register(context, BOPNetherFeatures.HANGING_FLESH_TENDON, BOPBaseFeatures.HANGING_FLESH_TENDON, NoneFeatureConfiguration.INSTANCE); register(context, BOPNetherFeatures.INFERNO_LAVA_LAKE, BOPBaseFeatures.LAKE, new LakeFeature.Configuration(BlockStateProvider.simple(Blocks.LAVA), BlockStateProvider.simple(BOPBlocks.BRIMSTONE))); register(context, BOPNetherFeatures.INFERNO_LAVA_SPRING, Feature.SPRING, new SpringConfiguration(Fluids.LAVA.defaultFluidState(), false, 4, 1, HolderSet.direct(Block::builtInRegistryHolder, Blocks.NETHERRACK))); register(context, BOPNetherFeatures.INFERNO_SPLATTER, BOPBaseFeatures.INFERNO_SPLATTER, NoneFeatureConfiguration.INSTANCE); register(context, BOPNetherFeatures.LARGE_FUMAROLE, BOPBaseFeatures.LARGE_FUMAROLE, NoneFeatureConfiguration.INSTANCE); register(context, BOPNetherFeatures.LARGE_ROSE_QUARTZ, BOPBaseFeatures.LARGE_ROSE_QUARTZ, new LargeDripstoneConfiguration(30, UniformInt.of(3, 7), UniformFloat.of(0.3F, 1.8F), 0.33F, UniformFloat.of(0.3F, 0.9F), UniformFloat.of(0.4F, 1.0F), UniformFloat.of(0.0F, 0.3F), 4, 0.6F)); register(context, BOPNetherFeatures.NETHER_BONE_SPINE, BOPBaseFeatures.BONE_SPINE, NoneFeatureConfiguration.INSTANCE); register(context, BOPNetherFeatures.NETHER_BRAMBLE, BOPBaseFeatures.BRAMBLE, NoneFeatureConfiguration.INSTANCE); register(context, BOPNetherFeatures.NETHER_VINES, BOPBaseFeatures.NETHER_VINES, NoneFeatureConfiguration.INSTANCE); register(context, BOPNetherFeatures.OBSIDIAN_SPLATTER, BOPBaseFeatures.OBSIDIAN_SPLATTER, NoneFeatureConfiguration.INSTANCE); register(context, BOPNetherFeatures.POROUS_FLESH, Feature.ORE, new OreConfiguration(new TagMatchTest(ModTags.Blocks.FLESH), BOPBlocks.POROUS_FLESH.defaultBlockState(), 16)); register(context, BOPNetherFeatures.PUS_BUBBLES, Feature.RANDOM_PATCH, FeatureUtils.simplePatchConfiguration(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(BlockStateProvider.simple(BOPBlocks.PUS_BUBBLE)))); register(context, BOPNetherFeatures.SMALL_CRYSTAL, BOPBaseFeatures.SMALL_CRYSTAL, NoneFeatureConfiguration.INSTANCE); register(context, BOPNetherFeatures.SMALL_FUMAROLE, BOPBaseFeatures.SMALL_FUMAROLE, NoneFeatureConfiguration.INSTANCE); register(context, BOPNetherFeatures.SPROUTS_UNDERGROWTH, Feature.RANDOM_PATCH, FeatureUtils.simplePatchConfiguration(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(BlockStateProvider.simple(BOPBlocks.SPROUT)))); register(context, BOPNetherFeatures.TREES_UNDERGROWTH, Feature.RANDOM_SELECTOR, new RandomFeatureConfiguration(ImmutableList.of(new WeightedPlacedFeature(BIG_HELLBARK_TREE_CHECKED, 0.4F)), HELLBARK_TREE_CHECKED)); register(context, BOPNetherFeatures.UNDERGROWTH_FLOWERS, Feature.RANDOM_PATCH, FeatureUtils.simplePatchConfiguration(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(BlockStateProvider.simple(BOPBlocks.BURNING_BLOSSOM)))); } private static <FC extends FeatureConfiguration, F extends Feature<FC>> void register(BootstrapContext<ConfiguredFeature<?, ?>> context, ResourceKey<ConfiguredFeature<?, ?>> configuredFeatureKey, F feature, FC configuration) { context.register(configuredFeatureKey, new ConfiguredFeature<>(feature, configuration)); } }
412
0.750787
1
0.750787
game-dev
MEDIA
0.994567
game-dev
0.887611
1
0.887611
KentHaeger/SaveOurShip2-Old
2,599
Source/1.5/Thing_ArcholifePod.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Verse; using RimWorld; namespace SaveOurShip2 { class Thing_ArcholifePod : ThingWithComps { public override IEnumerable<FloatMenuOption> GetFloatMenuOptions(Pawn selPawn) { List<FloatMenuOption> options = new List<FloatMenuOption>(); options.AddRange(base.GetFloatMenuOptions(selPawn)); options.Add(new FloatMenuOption(TranslatorFormattedStringExtensions.Translate("SoS.CraftArchocat"), delegate { GeneratePawn("Archocat"); })); options.Add(new FloatMenuOption(TranslatorFormattedStringExtensions.Translate("SoS.CraftArchomutt"), delegate { GeneratePawn("Archomutt"); })); options.Add(new FloatMenuOption(TranslatorFormattedStringExtensions.Translate("SoS.CraftArchostrich"), delegate { GeneratePawn("Archostrich"); })); options.Add(new FloatMenuOption(TranslatorFormattedStringExtensions.Translate("SoS.CraftArchoffalo"), delegate { GeneratePawn("Archoffalo"); })); options.Add(new FloatMenuOption(TranslatorFormattedStringExtensions.Translate("SoS.CraftArchospider"), delegate { GeneratePawn("Archospider"); })); options.Add(new FloatMenuOption(TranslatorFormattedStringExtensions.Translate("SoS.CraftArcholope"), delegate { GeneratePawn("Archolope"); })); options.Add(new FloatMenuOption(TranslatorFormattedStringExtensions.Translate("SoS.CraftArchotortoise"), delegate { GeneratePawn("Archotortoise"); })); options.Add(new FloatMenuOption(TranslatorFormattedStringExtensions.Translate("SoS.CraftArchopanda"), delegate {GeneratePawn("Archopanda"); })); options.Add(new FloatMenuOption(TranslatorFormattedStringExtensions.Translate("SoS.CraftArchojerboa"), delegate { GeneratePawn("Archojerboa"); })); if(stackCount>=10) options.Add(new FloatMenuOption(TranslatorFormattedStringExtensions.Translate("SoS.CraftArchothrumbo"), delegate { GeneratePawn("Archothrumbo", 10); })); return options; } void GeneratePawn(string PawnKind, int numPods=1) { Pawn pawn = PawnGenerator.GeneratePawn(PawnKindDef.Named(PawnKind), Faction.OfPlayer); pawn.ageTracker.AgeBiologicalTicks = 0; pawn.ageTracker.AgeChronologicalTicks = 0; pawn.Position = this.Position; List<Hediff> diffs = new List<Hediff>(); foreach(Hediff diff in pawn.health.hediffSet.hediffs) { diffs.Add(diff); } foreach(Hediff diff in diffs) { pawn.health.RemoveHediff(diff); } pawn.SpawnSetup(this.Map, false); FleckMaker.Static(this.Position, this.Map, FleckDefOf.Smoke); this.SplitOff(numPods).Destroy(); } } }
412
0.846548
1
0.846548
game-dev
MEDIA
0.988914
game-dev
0.840247
1
0.840247
harvard-acc/gem5-aladdin
6,283
src/arch/arm/isa/bitfields.isa
// -*- mode:c++ -*- // Copyright (c) 2010, 2011, 2018 ARM Limited // All rights reserved // // The license below extends only to copyright in the software and shall // not be construed as granting a license to any other intellectual // property including but not limited to intellectual property relating // to a hardware implementation of the functionality of the software // licensed hereunder. You may use the software subject to the license // terms below provided that you ensure that this notice is replicated // unmodified and in its entirety in all distributions of the software, // modified or unmodified, in source code or in binary form. // // Copyright (c) 2007-2008 The Florida State University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer; // redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution; // neither the name of the copyright holders 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 // OWNER 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. // // Authors: Stephen Hines //////////////////////////////////////////////////////////////////// // // Bitfield definitions. // // Opcode fields def bitfield DECODERFAULT decoderFault; def bitfield ILLEGALEXEC illegalExecution; def bitfield ENCODING encoding; def bitfield OPCODE opcode; def bitfield MEDIA_OPCODE mediaOpcode; def bitfield MEDIA_OPCODE2 mediaOpcode2; def bitfield USEIMM useImm; def bitfield OPCODE_24 opcode24; def bitfield OPCODE_24_23 opcode24_23; def bitfield OPCODE_23_20 opcode23_20; def bitfield OPCODE_23_21 opcode23_21; def bitfield OPCODE_22 opcode22; def bitfield OPCODE_20 opcode20; def bitfield OPCODE_19_16 opcode19_16; def bitfield OPCODE_19 opcode19; def bitfield OPCODE_18 opcode18; def bitfield OPCODE_15_12 opcode15_12; def bitfield OPCODE_15 opcode15; def bitfield MISC_OPCODE miscOpcode; def bitfield OPC2 opc2; def bitfield OPCODE_7 opcode7; def bitfield OPCODE_6 opcode6; def bitfield OPCODE_4 opcode4; def bitfield IS_MISC isMisc; def bitfield SEVEN_AND_FOUR sevenAndFour; def bitfield THUMB thumb; def bitfield BIGTHUMB bigThumb; def bitfield AARCH64 aarch64; // Other def bitfield COND_CODE condCode; def bitfield S_FIELD sField; def bitfield RN rn; def bitfield RD rd; def bitfield RT rt; def bitfield SHIFT_SIZE shiftSize; def bitfield SHIFT shift; def bitfield RM rm; def bitfield RS rs; def bitfield PUSWL puswl; def bitfield PREPOST puswl.prepost; def bitfield UP puswl.up; def bitfield PSRUSER puswl.psruser; def bitfield WRITEBACK puswl.writeback; def bitfield LOADOP puswl.loadOp; def bitfield PUBWL pubwl; def bitfield IMM imm; def bitfield IMMED_11_0 immed11_0; def bitfield IMMED_7_0 immed7_0; def bitfield IMMED_HI_11_8 immedHi11_8; def bitfield IMMED_LO_3_0 immedLo3_0; def bitfield IMMED_23_0 immed23_0; def bitfield CPNUM cpNum; // Note that FP Regs are only 3 bits def bitfield FN fn; def bitfield FD fd; def bitfield FPREGIMM fpRegImm; // We can just use 3:0 for FM since the hard-wired FP regs are handled in // float_regfile.hh def bitfield FM fm; def bitfield FPIMM fpImm; def bitfield PUNWL punwl; // M5 instructions def bitfield M5FUNC m5Func; // 16 bit thumb bitfields def bitfield TOPCODE_15_13 topcode15_13; def bitfield TOPCODE_13_11 topcode13_11; def bitfield TOPCODE_12_11 topcode12_11; def bitfield TOPCODE_12_10 topcode12_10; def bitfield TOPCODE_11_9 topcode11_9; def bitfield TOPCODE_11_8 topcode11_8; def bitfield TOPCODE_10_9 topcode10_9; def bitfield TOPCODE_10_8 topcode10_8; def bitfield TOPCODE_9_6 topcode9_6; def bitfield TOPCODE_7 topcode7; def bitfield TOPCODE_7_6 topcode7_6; def bitfield TOPCODE_7_5 topcode7_5; def bitfield TOPCODE_7_4 topcode7_4; def bitfield TOPCODE_3_0 topcode3_0; // 32 bit thumb bitfields def bitfield HTOPCODE_12_11 htopcode12_11; def bitfield HTOPCODE_10_9 htopcode10_9; def bitfield HTOPCODE_9 htopcode9; def bitfield HTOPCODE_9_8 htopcode9_8; def bitfield HTOPCODE_9_5 htopcode9_5; def bitfield HTOPCODE_9_4 htopcode9_4; def bitfield HTOPCODE_8 htopcode8; def bitfield HTOPCODE_8_7 htopcode8_7; def bitfield HTOPCODE_8_6 htopcode8_6; def bitfield HTOPCODE_8_5 htopcode8_5; def bitfield HTOPCODE_7 htopcode7; def bitfield HTOPCODE_7_5 htopcode7_5; def bitfield HTOPCODE_6 htopcode6; def bitfield HTOPCODE_6_5 htopcode6_5; def bitfield HTOPCODE_5_4 htopcode5_4; def bitfield HTOPCODE_4 htopcode4; def bitfield HTRN htrn; def bitfield HTS hts; def bitfield LTOPCODE_15 ltopcode15; def bitfield LTOPCODE_11_8 ltopcode11_8; def bitfield LTOPCODE_7_6 ltopcode7_6; def bitfield LTOPCODE_7_4 ltopcode7_4; def bitfield LTOPCODE_4 ltopcode4; def bitfield LTRD ltrd; def bitfield LTCOPROC ltcoproc;
412
0.587716
1
0.587716
game-dev
MEDIA
0.407803
game-dev
0.765537
1
0.765537
Ormael13/CoCX
240,921
classes/classes/Scenes/NPCs/CeraphFollowerScene.as
/** * Created by aimozg on 03.01.14. */ package classes.Scenes.NPCs { import classes.*; import classes.BodyParts.Tail; import classes.GlobalFlags.kACHIEVEMENTS; import classes.GlobalFlags.kFLAGS; import classes.Scenes.SceneLib; import classes.display.SpriteDb; public class CeraphFollowerScene extends NPCAwareContent { public function CeraphFollowerScene() { } // CERAPH_ROLEPLAY_AS_DOMINIKA_COUNT:int = 389; // CERAPH_HIDING_DICK:int = 288; // TIMES_CERAPH_PORTAL_FUCKED:int = 438; //Capacity = 115; //Is Ceraph a follower? override public function ceraphIsFollower():Boolean { return flags[kFLAGS.CERAPH_FOLLOWER_PIERCING] > 0 || flags[kFLAGS.CERAPH_FOLLOWER_CARRY] > 0; } public function ceraphFollowerEncounter(forceCeraph:Boolean = false):void { if (forceCeraph) { ceraphFollowerAppearance(); return; } if (rand(24) == 0 && player.hasCock()) catgirlEncounter(); else if (rand(24) == 0 && flags[kFLAGS.CERAPH_RP_CORRUPT_DISABLED] == 0) carephCorruptionSlaves(); else if (rand(24) <= 1 && player.gender > 0) encounterZetsuko(); else ceraphFollowerAppearance(); } public function ceraphSprite():void { spriteSelect(SpriteDb.s_ceraphClothed); } //[Actually Ceraph] - public function ceraphFollowerAppearance(output:Boolean = true):void { if (output) clearOutput(); spriteSelect(SpriteDb.s_ceraphClothed); if (output) { outputText("You move to a secluded portion of your camp and mentally call for your tamed Omnibus.\n\nCeraph strides from around a boulder, as if by magic. The slave-demon wears her red-studded collar as always. However, instead of prancing around naked like she used to, she's arrived wearing a scandalous latex outfit that's as concealing as it is titillating. From the tips of her fingers all the way to her shoulders, she's sleeved in the glossy black material. At her neck, the top opens up, exposing the purple curves of her breasts, even though her nipples are hidden away by a clingy, scandalous scarlet bra, also of latex. It looks as though it would be effortless to tear away. A rubbery faux-corset hugs her waist, connected to the material over her arms and shoulders in the back. The crimson micro bikini bottom beneath it looks unfit for covering anything Ceraph has ever had between her legs, but it somehow seems to just barely be holding things together."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" Her demonic prick forms a ridge in the tight fabric, its head peeking ever-so-slightly over the top"); else outputText(" Thankfully, she seems to have removed or hidden her demonic cock somehow, so as not to disrupt her fragile outfit with unfeminine bulges"); outputText(". Tight buckles link her corset to the long thigh high boots over her legs, the platforms and heels adding nearly a foot to her height. Red stripes run right down the front of them and along the soles, as an imitation of laces.\n\n"); outputText("Ceraph's liquid black eyes twist, the surfaces spiralling inward to the pinpricks of her pupils. Her irises, now that you can see them, are purplish, like her skin, though they're glittery and as reflective as precious gems. The omnibus drops onto her knees before you, not looking you in the eye without a command. She whispers, \"<i>You called, [Master]?</i>\"\n\n"); outputText("Ceraph offhandedly mentions, \"<i>If you're into that sort of thing, [Master], I could take one of your <b>delectable</b> body-parts and use it with my harem. From what I understand, the original owner will often be able to experience the sensations of their gift while their consciousness is relaxed - while sleeping, usually.</i>\"\n\n"); outputText("<b>What will you do with your slave?</b> "); } menu(); addButton(0, "Sex", ceraphSexMenu).disableIf(player.lust < 33, "You aren't turned on enough for sex."); addButton(1, "Roleplay", followerCeraphRoleplay).disableIf(player.lust < 33, "You aren't turned on enough for sex."); addButton(5, "Partswap", giveFollowerBodyBits); if (flags[kFLAGS.PC_FETISH] < 3) addButton(6, "GetFetish", CeraphHandsOutNewFetishesLikePervCandy); if (flags[kFLAGS.PC_FETISH] > 0) addButton(7, "RemoveFetish", unfetishifyYourselfWithFollowerCeraph); addButton(8, flags[kFLAGS.CERAPH_HIDING_DICK] ? "Go Herm" : "Go Female", cawkTawgle); if (flags[kFLAGS.FOLLOWER_AT_FARM_CERAPH] == 0 && flags[kFLAGS.FARM_CORRUPTION_STARTED] == 1) addButton(10, "Farm Work", helpWithFarm); addButton(14, "Leave", camp.campSlavesMenu); } private function helpWithFarm():void { clearOutput(); ceraphSprite(); outputText("You ask Ceraph if she can help you with the farm you recently acquired."); outputText("\n\n\"<i>You mean work on a farm? Don’t be ridiculous, [name]!</i>\" She chortles, before coughing as she catches your expression. \"<i>I don’t think me or any of my pets are cut out for farming,</i>\" she says, tapping her chin. \"<i>Or at least not that kind you have in mind. But I could mark the place as being under demon protection if you like. I can only do it once,</i>\" she warns. \"<i>And it will wear off eventually.</i>\""); menu(); addButton(0, "Do It", doFarmShit); addButton(1, "Later", noFarmShitYet); } private function doFarmShit():void { clearOutput(); ceraphSprite(); outputText("\"<i>I’ll go over there tonight then,</i>\" she says. There’s a far-away gleam of excitement in her eyes as she tugs on a nipple; only now does it occur to you what ‘marked as being under demon protection’ might entail. \"<i>Anything else, [master]?</i>\""); flags[kFLAGS.FOLLOWER_AT_FARM_CERAPH] = 1; SceneLib.farm.farmCorruption.whitneyCorruption(10); ceraphFollowerAppearance(false); } private function noFarmShitYet():void { clearOutput(); ceraphSprite(); outputText("\"<i>Very well,</i>\" she smirks. \"<i>Anything else?</i>\""); ceraphFollowerAppearance(false); } private function ceraphSexMenu():void { menu(); addButton(0, "Fuck Pussy", fuckFollowerCeraphsVagoo).disableIf(!player.hasCock(), "Req. a cock."); addButton(1, "Get Tongued", followerCeraphTongueFucking).disableIf(!player.hasVagina(), "Req. a vagina."); addButton(2, "Please All", ceraphTentacleGrape).disableIf(!player.isHerm(), "Req. to be a herm."); addButton(3, "NippleFuck", stuffSomeNippleCunts).disableIf(!player.hasFuckableNipples(), "Req. to have nipplecunts."); addButton(4, "Penis Magic", portalFuckWithFollowerCeraph).disableIf(player.cockThatFits(100) < 0, "Req. a cock fitting 100 area."); addButton(5, "Lay Eggs", layEggsInSlaveCeraph).disableIf(!player.canOviposit(), "Req. an ovipositor."); addButton(14, "Back", ceraphFollowerAppearance); } private function followerCeraphRoleplay():void { clearOutput(); outputText("You tell Ceraph you'd like to do a little roleplaying. Her nipples turn hard under their latex bindings as she asks, \"<i>What will it be, [Master]? Shall I pretend you've just teased me into sexual submission, or would you like to switch things up and have your bottom play at being top again? Or maybe... you'd like me to shapeshift into some other girl, and do all the dirty, depraved things she never would?</i>\""); outputText("\n\nShe makes a gesture, and the surroundings take on a mountainous look. Of course, she can probably change that on a whim. What do you have Ceraph roleplay?"); menu(); addButton(0, "Defeat Her", ceraphScene.winChoices); addButton(1, "Lose to Her", ceraphScene.ceraphRapesYouBADDAWGYODIGGITY); addButton(2, "Be A Pet", sumissivenessToCeraphFollower) .disableIf(player.isGenderless(), "Not for genderless!"); addButtonDisabled(5, "???"); addButtonDisabled(6, "???"); addButtonDisabled(7, "???"); if (flags[kFLAGS.DOMINIKA_MET] > 0) addButton(5, "Dominika", cerminika) .disableIf(!player.hasCock(), "Req. a cock!"); if (player.hasStatusEffect(StatusEffects.Marble)) addButton(6, "Marble Play", sweetieNOOOO) .disableIf(!player.cockThatFits(70) < 0, "Req. a cock fitting 70 area!"); if (flags[kFLAGS.TIMES_FUCKED_URTA] > 0) addButton(7, "Urta Play", ceraphUrtaRoleplay) .disableIf(!player.isGenderless(), "Not for genderless!"); addButton(14, "Back", ceraphFollowerAppearance); } //*Ceraph is Defeated #4 - Offers Funtimes (Zeddited) public function submissiveCeraphOffer():void { spriteSelect(SpriteDb.s_ceraph); clearOutput(); outputText("Once again, Ceraph "); if (monster.HP < 1) outputText("drops on the ground in front of you, completely beaten."); else outputText("drops down and starts masturbating, practically fisting her drooling pussy while she pumps her demonic dick with reckless abandon."); outputText(" She "); if (monster.HP < 1) outputText("looks up at you and asks"); else outputText("manages to stop fapping long enough to look up at you and ask"); outputText(", \"<i>Why do I even bother?</i>\"\n\n"); outputText("You're a bit surprised by her tone - depression and defeat aren't exactly her style. The only thing you manage to respond with is "); if (player.cor < 33) outputText("a nervous chuckle"); else if (player.cor < 66) outputText("a surprised laugh"); else outputText("a bemused smirk"); outputText(". Ceraph presses on, \"<i>This whole time I've been trying to bring you into my harem, but I've ignored the obvious. Each time we've tangled, you come out on top... in more ways than one.</i>\" The demon looks up at you with meek, hooded eyes and says, \"<i>Perhaps I've had it backwards all along... I belong in your harem.</i>\"\n\n"); outputText("Letting your eyes play over the demon's exotic, sculpted skin, you can't help but be tempted by her offer... Ceraph sees you mulling it over and produces a collar as she purrs, \"<i>No pressure... [Master]. You could always just take me here like usual, and perhaps, the next time you'll stop being so lucky...</i>\"\n\n"); if (player.gender > 0 && player.lust >= 33) { outputText("Do you fuck her? (And if so, which of your body parts do you do it with?)"); ceraphScene.rapeOptions(cleanupAfterCombat); addButton(5, "Collar Her", collarCeraph); } else { outputText("Do you accept her offer?"); doYesNo(collarCeraph, cleanupAfterCombat); } } //Collar Ceraph After 4th Defeat + Rape: (Zeddited) private function collarCeraph():void { clearOutput(); spriteSelect(SpriteDb.s_ceraph); outputText("You reach down and snatch the collar from Ceraph's shaking hand. Turning it over in your grip, you get a feel for the soft, supple leather. Blood-red studs poke out around the black strap's surface, vaguely reminding you of a dog's collar, though with the aggression cranked up to max. The snap mechanism looks simple enough to connect, but you can't see any way to release the latch. It makes sense that Ceraph would have one-way collars; slaves shouldn't be able to remove the symbol of their station.\n\n"); outputText("Leaning over, you slide the collar around your new slave's suddenly flush neck, feeling her heart hammering away just beneath the skin. Snapping it closed, you muse "); if (player.cor < 33) outputText("that you never expected making a demon into your slave would factor into your quest. On one hand it seems wrong, but... she's a demon. The fewer you have opposing you, the easier it will be to end their threat completely."); else if (player.cor < 66) outputText("that taking a demon as a slave would've been abhorrent to you when you started this journey. Now, it's just a means to a very pleasurable end."); else { outputText("on how much you'll enjoy using the former dom as your personal "); if (player.hasCock()) outputText("cum-dump"); else outputText("tongue-slave"); outputText("."); } outputText(" Ceraph pulls herself up to her knees and kisses your [feet], a show of absolute submission and obedience.\n\n"); outputText("The defeated demon explains, \"<i>Though I am now and forever your slut, your slave, your bitch... those in my harem cannot be abandoned. I am sad to say I cannot live with you, [Master].</i>\" She sees the look forming in your eyes and hastily adds, \"<i>Oh, I'll still be at your beck and call, but if I can't make it, I'll be sure to send you one of my pets. Just rub this charm whenever you want my services, [Master], and I'll be there.</i>\" Ceraph holds out a tiny onyx bar tipped with rubies. The gems shine and glitter with their own inner light, while the black shaft seems to drink in everything around it, leaving behind darkness.\n\n"); outputText("Well, with a harem as large as hers, it makes sense that she'd have to keep them in her lair and tend to them. There's no way you could foster the people in your camp, and besides, since their Mistress is your slave, they're <b>now yours by extension, as well</b>. Ceraph reaches down to "); if (monster.lust >= monster.maxOverLust()) outputText("resume stroking"); else outputText("stroke"); outputText(" her nodule-studded demon-dick with her free hand. She whimpers, \"<i>Would my [Master] prefer to carry [his] slave's token, or wear it as a belly-button piercing?</i>\"\n\n"); if (player.hasKeyItem("Radiant shard") >= 0){ player.addKeyValue("Radiant shard",1,+1); } else { player.createKeyItem("Radiant shard", 1, 0, 0, 0); } outputText("\n\n<b>While considering her offer you get to looting from Ceraph inventory and find a shard of metal that seems to radiate untold power. You acquired a Radiant shard!</b>"); //[Carry] [Pierce] simpleChoices("Carry", carryCarephsToken, "Pierce", getCeraphFollowerPiercing, "", null, "", null, "", null); } //[Carry] private function carryCarephsToken():void { clearOutput(); spriteSelect(SpriteDb.s_ceraph); outputText("You inform your living property that you've heard quite enough about her piercings and snatch the token from her hand. Ceraph's eyes go wide and she nods, more than a little fearfully. Seeing the Omnibus so cowed brings a smile to your face.\n\n"); outputText("Ceraph asks, \"<i>So, before my [Master] leaves, would you like to fuck your new slut one of the old ways, one last time?</i>\"\n\n"); outputText("<b>(Received Key Item: Onyx Token)</b>\n\n"); flags[kFLAGS.CERAPH_FOLLOWER_CARRY] = 1; player.createKeyItem("Onyx Token - Ceraph's", 0, 0, 0, 0); //[Display Rape Options + Collar Option] if (player.lust >= 33 && player.gender > 0) outputText("Do you fuck her as a disobedient demon, one last time? (And if so, which of your body parts do you do it with?)"); ceraphScene.rapeOptions(cleanupAfterCombat); } //[Pierce] private function getCeraphFollowerPiercing():void { clearOutput(); spriteSelect(SpriteDb.s_ceraph); //Set belly button pierced as active flags[kFLAGS.CERAPH_FOLLOWER_PIERCING] = 1; outputText("You bare your midriff to your new slut with "); if (player.cor < 40) outputText("a little hesitation."); else outputText("a smirk, secure in your knowledge of her defeat."); outputText(" Ceraph shimmies forward and holds the oily stud against your midriff, pressing it into you with her palm. There's a moment of tingling warmth, followed by an ache of unholy numbness. When the demoness removes her hand, your belly-button is studded with the magical jewelry, glowing and not at the same time.\n\n"); outputText("There's no lingering compulsion, no mental assault, just a new piercing. You're kind of awestruck by the gesture - even though she seemed sincere, a small part of you still believed the fetish-obsessed demon was using this whole thing as a setup to trick you.\n\n"); outputText("Ceraph asks, \"<i>[Master], before you go, would you like to fuck your slut one of the old ways, one last time?</i>\""); //[Display Rape Options + Collar Option] if (player.lust >= 33 && player.gender > 0) outputText("Do you fuck her as a disobedient demon, one last time? (And if so, which of your body parts do you do it with?)"); ceraphScene.rapeOptions(cleanupAfterCombat); } //*Decision to Display Demonic Dick or Demur (pretty sure Fen mentioned wanting this -Z) private function cawkTawgle():void { clearOutput(); spriteSelect(SpriteDb.s_ceraphClothed); //Off if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) { outputText("You tell Ceraph that you want her to hide her demonic cock when she's around you. Your collared demoness nods, lowering her eyelids seductively. She slides a hand up the front of her latex panties, stroking her defiled member through the material once before concealing its form with fingers pointed down.\n\n"); outputText("She lets out a low hum, then suddenly arches her back as her hand sinks in an inch. \"<i>O-oh-oh!</i>\" she moans, pulling it away with a small string of pre-cum tying it to her now-bulgeless panties. Absently she licks the fluid from her fingers and asks, \"<i>Was there anything else, my [Master]?</i>\"\n\n"); //(set DemonDomDongDisplay to OFF) flags[kFLAGS.CERAPH_HIDING_DICK] = 1; } else { outputText("You tell Ceraph that you want her to have her demonic cock on display when around you. She nods, breaking into an eager smile, and slips a hand into the front of her latex panties. The veneer of rapt concentration on her face is only dispelled when you glance down at her crotch and notice her vigorously fingering her clitoris under the fabric, bowing out the surface as she flexes and caresses.\n\n"); outputText("A low moan gathers in intensity as Ceraph strokes, and then abruptly she jerks her hips forward as a bulge emerges between her fingertips and travels up the front of her undergarment. It overreaches the panty line and the purple glans peeks out, smeared and dribbling with copious pre-cum. She strokes the shaft almost automatically, as she addresses her next hopeful question to you. \"<i>Was there anything <b>else</b> you'd like to do, [Master]?</i>\" Clearly, this particular magical feat is very enjoyable to her, on a personal level."); //set DemonDomDongDisplay to ON) flags[kFLAGS.CERAPH_HIDING_DICK] = 0; } //To Ceraph follower menu doNext(ceraphFollowerAppearance); } //Volunteer for new fetishes! private function CeraphHandsOutNewFetishesLikePervCandy():void { clearOutput(); spriteSelect(SpriteDb.s_ceraphClothed); //*Fetish level = 0 if (flags[kFLAGS.PC_FETISH] == 0) { outputText("Ceraph comes forward on your command, whispering calmly as she "); if (player.earsPierced == 0) outputText("pulls a pair of gleaming, green piercings from a pouch. \"<i>Oh, don't worry [Master]; you're going to love this so much. These piercings are special, and they'll give you exactly what you want.</i>\""); else outputText("places her hands upon your pierced ears. She whispers softly, \"<i>Don't worry [Master], I can easily use the piercings you already have. It won't hurt.</i>\""); outputText("\n\n"); //(NOT PIERCED) if (player.earsPierced == 0) outputText("The demon places a hand on your forehead and rubs your temples. Numbness spreads through your body with every touch, until you can barely feel a thing. She snaps an earring into your left ear, and dizziness washes over you. A moment later she's piercing the other side, and the now-familiar vertigo that accompanies it seems to come and go quicker than before. "); //(PIERCED) else outputText("The demon rubs your ears in her hands, numbing them slightly. A gradual buzz builds behind your eyes, accompanied by a wave of dizziness. You blink and try to shake your head, but as numb as you are, it's quite difficult. After a few moments, the odd sensations pass, returning normal feeling to your ears and [face], much to your relief. "); outputText("You hope she doesn't take your [armor] while you're paralyzed, leaving you to roam the realm totally exposed. Confusion and waves of new desire battle in your mind as you try to come to grip with the odd thought.\n\n"); outputText("Ceraph watches your "); if (player.cockTotal() > 0) outputText("cock bounce in time with your fluttering heartbeats"); else if (player.hasVagina()) outputText("vagina get wetter and wetter"); else outputText("parted lips and confused expression"); outputText(" as the new thoughts and desires settle themselves inside you. She gives you a gentle pat and explains, \"<i>It's ok [Master]; you're an exhibitionist now. Would you like your piercing slave to give you even more?</i>\"\n\n"); outputText("Ceraph is right – <b>you're an exhibitionist now.</b>"); if (player.earsPierced == 0) { player.earsPierced = 1; player.earsPShort = "green gem-stone ear-studs"; player.earsPLong = "Green gem-stone ear-studs"; } flags[kFLAGS.PC_FETISH] = 1; dynStats("lus", 25, "cor", 1); } //*Fetish level = 1 else if (flags[kFLAGS.PC_FETISH] == 1) { outputText("Ceraph giggles as she closes in on you once again. Sighing, you lie there and allow your slave to massage your temples, using her magic to paralyze and numb your body. "); if (player.nipplesPierced == 0) { outputText("She's all too happy to build up the suspense as she pulls out a pair of shining black studs, \"<i>Oh, do you know what these are going to do? Well, how about I slide them into your "); if (player.hasFuckableNipples()) outputText("slutty"); else if (player.nippleLength < 1) outputText("cute"); else outputText("tight"); outputText(" nipples, and you tell me all about your fetishes and which one makes you the hottest. Oh, you'll love it [Master]!</i>\"\n\n"); } //If already pierced if (player.nipplesPierced > 0) outputText("She's all too happy to build up the suspense as she lays her hands on your pierced nipples, giving them a gentle tweak that you can barely feel. \"<i>Don't worry, [Master]. Imbuing your new fetish into you through these will be easy. Just tell me all about which fetishes make you the hottest while I do it, and see if you can guess your new kink.</i>\"\n\n"); //Business as usual! outputText("The demon doesn't give you a chance to reply; instead, she focuses on "); if (player.nipplesPierced > 0) outputText("your " + nippleDescript(0) + "s, circling her fingers all around the fleshy nubs. Goosebumps run over your body in a wave, accompanied by a similar chill and a pressure behind your temples. You shudder, but it quickly fades."); else outputText("aligning the business ends of the piercings with your sensitive nipple-flesh. Your right " + nippleDescript(0) + " is pierced in one smooth motion, nearly making you scream in pain. As she fastens it on, you feel goosebumps spread over your body in a wave. The second piercing doesn't seem to hurt as bad, but the sensation of spreading goosebumps is far more noticeable."); outputText(" Your eyes dart around, curious what fetish your demonic slave has given you this time.\n\n"); outputText("Ceraph smiles down at you and whimpers, \"<i>I hope you're pleased with the new fetish [Master]. Just think about how similar being paralyzed is to being tied down and tell me if you like it.</i>\"\n\n"); outputText("Your body goes beet-red as it suddenly tries to struggle against the invisible binding of her magic. It... it feels good! You nearly cry out with lust as the restraint turns you on more and more. Ceraph's magic has given you a fetish for being tied up! You nearly faint when you think of all the strange things in this land that might try to restrain you, and you know you have no hope of resisting if they ever catch you. <b>Though somehow you think you might enjoy being a bondage fetishist...</b>"); dynStats("lus", 25, "cor", 1); if (player.nipplesPierced == 0) { player.nipplesPierced = 1; player.nipplesPShort = "seamless black nipple-studs"; player.nipplesPLong = "Seamless black nipple-studs"; } flags[kFLAGS.PC_FETISH] = 2; } //*Fetish level = 2 else if (flags[kFLAGS.PC_FETISH] == 2) { outputText("The demoness pulls out a diamond-studded piercing and closes in on you, her cock peeking out of her panties, her pussy moist, and her hips swaying seductively as she advances. Ceraph gives you a serious look and warns you, \"<i>You realize you're not even going to be able to lift a hand against your foes after this? You really love a challenge, don't you [Master]?</i>\"\n\n"); outputText("The idea of facing the denizens of this land without even so much as the ability to throw a punch turns you on immensely, and you pant and gasp as "); if (player.cockTotal() > 0) { outputText("pre-cum oozes from "); if (player.cockTotal() > 1) outputText("each of "); outputText("your [cocks]."); } else if (player.hasVagina()) outputText("feminine moisture drools from between your lips and your " + clitDescript() + " turns into a hard button."); else outputText("your body aches for release."); outputText(" With an amused grin, Ceraph yanks down your gear and "); //[dicks] if (player.cockTotal() > 0) { outputText("grabs your " + cockDescript(0)); if (player.cocks[0].pierced > 0) outputText(", the old piercing clattering to the ground as it slides out, "); outputText(" and snaps the diamond stud through your sensitive flesh, making your vision haze red in pain.\n\n"); player.cocks[0].pierced = 1; player.cocks[0].pShortDesc = "diamond cock-stud"; player.cocks[0].pLongDesc = "Diamond cock-stud"; } //[cunts] else if (player.hasVagina()) { outputText("spreads your lips"); if (player.vaginas[0].clitPierced > 0) outputText(", the old piercing clattering to the ground as it slides out of your flesh, "); outputText(", getting ahold of the flesh around the base of your " + clitDescript() + ". With practiced ease, she snaps the piercing closed, attaching the diamond stud to you while the pain fuzzes your vision red.\n\n"); player.vaginas[0].clitPierced = 1; player.vaginas[0].clitPShort = "diamond clit-stud"; player.vaginas[0].clitPLong = "Diamond clit-stud"; } //[else] else { outputText("snaps the diamond stud into your eye-brow, piercing it"); if (player.eyebrowPierced > 0) outputText(" and discarding your old jewelry like a piece of garbage"); outputText(". It hurts more than it ought to, fuzzing your vision red.\n\n"); player.eyebrowPierced = 1; player.eyebrowPShort = "diamond eyebrow-stud"; player.eyebrowPLong = "Diamond eyebrow-stud"; } //Set fetish level flags[kFLAGS.PC_FETISH] = 3; outputText("As she finishes, you get up and attempt to test your slut's work. Raising your hand for a slap, you try to bring it down on Ceraph's face. She flinches, but the blow stops a few inches away from her, melting into a gentle caress. <b>You can no longer use basic physical attacks!</b> She drops to her knees and asks, \"<i>Have I displeased you? I can remove the compulsion in it if you like.</i>\"\n\n"); outputText("You rub a hand through the demon's pitch-black hair and let her know that it's exactly what you asked for.\n\n"); outputText("Ceraph gives an excited squeak and holds herself still, allowing you to pet her. Once you stop, she gives a disappointed sigh, but holds her position."); dynStats("lus", 25, "cor", 2); } doNext(ceraphFollowerAppearance); } //*Request Ceraph Remove a Fetish. (Zeddited) private function unfetishifyYourselfWithFollowerCeraph():void { clearOutput(); spriteSelect(SpriteDb.s_ceraphClothed); outputText("You ask Ceraph to remove one of the fetishes she generously donated earlier. She sighs and nods, saying, \"<i>[Master], are you sure? It isn't that easy to do, and I love knowing my owner is aroused by my piercings!</i>\"\n\n"); outputText("Growling in irritation, you tell her, \"<i>Yes, I would like a fetish removed.</i>\"\n\n"); outputText("The demoness slumps her shoulders and nods. She explains, \"<i>I have to do them in the reverse order that I added them... just hold still, okay?</i>\"\n\n"); outputText("Do you go through with it?"); //[Yes] [No] - back to follower menu simpleChoices("Yes", goThroughWithCeraphUnfetishification, "", null, "", null, "", null, "Leave", ceraphFollowerAppearance); } //*Ceraph Actually Removes The Fetish (Zeddited) private function goThroughWithCeraphUnfetishification():void { clearOutput(); spriteSelect(SpriteDb.s_ceraphClothed); outputText("Ceraph steps closer, her shining outfit squeaking from the movement. Her hands gently touch your forehead, though she tries to avoid meeting your gaze. The submissive slut keeps her eyes downcast, as is proper for a slave, and she begins to rub at your temples, working her magic to undo her mischief. Warmth surges out, rushing through your temples and leaving a slack looseness in its wake. Ceraph grunts and lets go, staggering back and panting. She mumbles, \"<i>So much harder... to take those without changing... something else.</i>\"\n\n"); outputText("After a few moments, she seems to recover, and she asks, \"<i>Was there something else you needed me here for, [Master], or did you just want to waste my time?</i>\"\n\n"); if (player.cor < 33) outputText("It seems there's still a spark of Ceraph's fire under all her submission."); else if (player.cor < 66) outputText("You sigh and wonder if you should punish her for giving you such lip."); else outputText("You slap her across the face for her temerity."); dynStats("tou", -1, "cor", 1); flags[kFLAGS.PC_FETISH]--; //Back to follower menu doNext(ceraphFollowerAppearance); } //*Fuck Ceraph's Pussy (Zeddited) private function fuckFollowerCeraphsVagoo():void { var x:Number = player.cockThatFits(115); if (x < 0) x = 0; var y:Number = player.cockThatFits2(115); clearOutput(); spriteSelect(SpriteDb.s_ceraphClothed); if (y < 0) sceneHunter.print("Check failed: 2 dicks fitting 115 area."); //*Summary: Bind Ceraph's arms behind her back and make her lie facedown in the dirt, then grab her ankles and wheelbarrow fuck her, with her face as the wheel. outputText("You let Ceraph know that you'll be using her pussy. She sighs and says, \"<i>Yes, [Master],</i>\" unable to hide the disappointment in her tone. Ceraph shifts, the panties of her outfit fading away to reveal her dripping cunny"); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" and half-erect, throbbing cock"); outputText(". "); if (player.cor < 33) outputText("She gets down on all fours, then lays her cheek in the dirt. Her arms cross behind her back, suddenly bound there by the abrupt appearance of those same panties, tied in a knot. Supported by only her knees, her tits, shoulders, and her face, she asks, \"<i>Grab me and fuck me [Master], please grind your slave's face in the dirt!</i>\"\n\n"); else if (player.cor < 66) outputText("She gets down on all fours, then lays her cheek in the dirt. Her arms cross behind her back, and you pin them there for her, smiling as her panties appear as if by magic, tied in a binding knot around her wrists. With only her knees and upper body supporting her, Ceraph begs, \"<i>Be rough with me.</i>\"\n\n"); else { outputText("You push her onto all fours, then grab her arms and fold them behind her back, grinding her face into the dirt. The demoness groans, her pussy dripping "); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText("and her dick releasing a squirt of pre-cum "); outputText("as she gets more turned on by the rough, sexual play. Suddenly, as if by magic, her panties appear around her wrists, and you tie them tightly to bind her securely. With only her knees and upper body supporting her, Ceraph begs, \"<i>Be rough with me.</i>\"\n\n"); } if (player.cor < 33) outputText("Well, that wasn't quite what you would have thought of doing, but you've got a good idea what she wants, and you may as well go along with it. The idea of taking her in such a rough, hard way stirs something primal within you, and you have an easy time slipping into a meaner, rougher persona."); else if (player.cor < 66) outputText("Well, with a request like that, you'll have no problem fucking her rough and hard. The situation evokes something primal within you, and the inviting delta between Ceraph's thighs practically beckons you to ravage it."); else outputText("With an invitation like that, there's no way you'll decline. Looking over her, a predatory thrill runs through you, urging you to utterly violate her."); outputText(" You grab Ceraph's thighs"); if (player.str < 60) outputText(" and heave, lifting her up off the ground and forcing her to straddle you."); else outputText(" and easily lift her, forcing her to straddle you."); outputText(" Dragging the demon back, you bring her slutty, sodden puss up to your " + cockDescript(x)); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(", ignoring the rope of dangling pre-cum that hangs from her bumpy prick."); else outputText(", feeling the heat washing off her mons and onto your " + player.cockHead(x) + "."); outputText(" Yanking back, you bury all " + num2Text(Math.round(player.cocks[x].cockLength)) + " inches of your " + cockDescript(x) + " into Ceraph's unholy, warm snatch, "); if (player.cockArea(x) > 150) outputText("distorting her body around the sheer bulk of your massive member.\n\n"); else outputText("immersing yourself in the decadent wetness.\n\n"); outputText("For a moment, the two of you simply stay like that: you buried to the hilt and her moaning in the dirt. Ceraph's arms are flexing against her bondage as if she could rip through the latex panties by sheer force; though she could free herself by magic, she's chosen to struggle in futility. Perhaps she accepts her bondage as a true submissive slut should? Deciding it's time to reward her, you squeeze her thighs again and languidly withdraw, gazing at the marvelous wetness now soaking your tool. The demoness whimpers at the emptiness, her voice carrying only simpering, anguished desire. Lazily, you slide back, gently rocking her body when your crotches clasp together, twisting Ceraph's face.\n\n"); outputText("Your slut moans, \"<i>Ohhhh, yesssssss,</i>\" while you slide home, culminating in an inarticulate gurgle. Heavy drops of drool hang from her lips, turning the earth below into a thin layer of viscous mud for your pet to pillow her head in while you rail her. Starting slow, you gently work your whore's pussy over, gleefully watching her girlish lube drip from the puffy, purple lips of her sex. "); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText("Her cock dangles towards the ground, dripping thick ropes of pre-spunk as readily as her pussy. "); outputText("Somehow, she feels as tight around your " + cockDescript(x) + " as any virgin and three times as wet. The gentle claps of genital against genital send ripples through Ceraph, smearing her cheek in the growing mud-puddle while her tits wobble dangerously inside the sheer latex bra.\n\n"); outputText("\"<i>M-more! Harder, [Master]!</i>\" the demon pants as she crosses her legs behind your back, as if it could somehow stop you from pulling the whole way out. You hold her one-handed, just long enough to crack your palm against her tight, toned ass, and then you pick up the pace. Now that you're fucking her faster, the slut isn't even trying to talk anymore. Her hair is plastered against her scalp, stained brown by the mud, and her arms are slack in the restraints. Ceraph gives every impression of being utterly resigned to being fucked like a toy, used without care for her own feelings or emotions. Knowing that you've taken a powerful dominatrix and turned her into... this - it sends a chill up your back, invigorating your fast-pumping hips.\n\n"); //(DOUBLE PENN!) if (y >= 0) { outputText("A wicked idea crosses your mind, and you reach down to grab your " + cockDescript(y) + ", aiming it at the flexing asshole just above the slave's squelching snatch. Your next thrust plows it deep into Ceraph's anus, thankfully lubricated by the demon's constant squirting. Growling at the mounting, doubling pleasure, you resume your tempo and slam both your cocks hilt-deep in Ceraph. "); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText("She squeals and sprays a thick rope of jizz from her bloated cock. It seems a little prostate pressure was all it took to put her maleness over the edge. "); outputText("Your slave's reaction is to wiggle her backside at you and curl her tail about your waist, trying to pull you even further into her body. Delirious and high on pleasure, you " + player.mf("chuckle", "giggle") + " and pound away, heedless of anything but your own pending climax."); if (player.cockTotal() >= 3) { outputText(" Sadly, your extra penis"); if (player.cockTotal() > 3) outputText("es have nothing to do but slide across her cheeks, dripping pre-cum all over her smooth skin."); else outputText(" has nothing to do but slide across her cheeks, dripping pre-cum all over her smooth skin."); } outputText("\n\n"); } //(Single Penn!) else { outputText("Working the bitch harder and harder, you start slamming your " + cockDescript(x) + " so violently into the captive puss that Ceraph's sliding a few inches through the mud with each push. Her cunt starts squeezing and contracting, tightening even more than you would have thought imaginable. With such a vice-like twat, you're having a hard time even pushing back inside. Sighing, you hilt yourself and let the wringing, milking tightness work you. Not wanting to let your slave assume control of the situation, you start spanking her, bringing your palm down hard enough on her ass to leave hand-prints behind from the blows. Her tail curls about your waist protectively"); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" while her cock spews ropes of pre-cum into the dirt"); outputText(". Holding still for the sucking, squeezing embrace, there's little on your mind but punishing your slut and enjoying the feel of your coming climax.\n\n"); } outputText("With a shuddering explosion of warmth, you cum. Ceraph groans loud and low, her pussy happily caressing your " + cockDescript(x) + " as it spews its potent load into her demonic womb. "); if (y >= 0) outputText("Her asshole likewise gleefully devours the seed from your " + cockDescript(y) + ", flexing wildly from the fluid injection. "); outputText("You hold yourself there, deep inside the wanton hole"); if (y >= 0) outputText("s"); outputText(" and basting the corrupt slave's tunnel"); if (y >= 0) outputText("s"); outputText(" with sloppy spooge. Ceraph screams, \"<i>Yes! Yes! Fuck me! Fill me! Use me [Master]! Pump me full of cum while you grind my whorish face in the dirt!</i>\" Her voice goes ragged, high-pitched and screaming"); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(", and her cock starts pumping more demonic spunk into the mud"); outputText(". It trails off, though her pussy continues teasing your " + cockDescript(x) + ", wringing the last of your seed from your [balls].\n\n"); outputText("Ceraph sighs, "); if (player.cumQ() >= 700) outputText("rubbing her "); if (player.cumQ() >= 1400) outputText("bloated, "); if (player.cumQ() >= 700) outputText("bulging belly as she purrs, "); else outputText("purring, "); outputText("\"<i>Thank you... you're such a good dom for a horny bitch like me.</i>\"\n\n"); outputText("You smirk and drop her into her own muddy cum-puddle, then help her up to her feet. She's filthy, debased, and dripping ropes of your goo. Ceraph gives you a kiss on your "); if (player.tallness >= 80) outputText("chest"); else if (player.tallness >= 60) outputText("lips"); else outputText("forehead"); outputText(" and mouths, \"<i>Thank you.</i>\"\n\n"); outputText("Nodding, you give her ass a slap and send her off, noting Ceraph has freed her hands at some point and returned them to their normal position. She hasn't done anything about the sexual filth coating her body, but knowing her, she probably doesn't want to."); player.sexReward("vaginalFluids","Dick"); dynStats("sen", -2, "cor", .25); endEncounter(); } //*Ceraph TongueFucks The PC (Zeddited) private function followerCeraphTongueFucking():void { clearOutput(); spriteSelect(SpriteDb.s_ceraphClothed); outputText("Desirous of being pleasured by your demonic slave, you spread out your [legs] to allow easy access to your " + vaginaDescript()); if (player.hasCock()) outputText(" and " + multiCockDescriptLight()); outputText(".\n\n"); outputText("\"<i>Serve me with your tongue,</i>\" you command.\n\n"); outputText("Ceraph nods, the barest hint of a twinkle in her eyes as she drops down to her knees in order to examine your vulva. She meekly kisses your slit, planting her wet lips against your " + vaginaDescript() + " for but a moment. The demoness looks up you and licks you starting from your taint, through your labia, around your "); if (player.lust < 50) outputText("still-hooded"); else outputText("engorged"); outputText(" clit, and stops over your sensitive pubic skin. Then, her tongue begins to extend from her mouth, hanging further and further down as if it were unspooling from a hidden reel in her throat. Ceraph doesn't stop letting out more of the slippery organ until she's got three feet of tongue dangling between her tits. Just looking at it there, undulating below your mons, makes you wet.\n\n"); outputText("With a sharp intake of breath, she reels in the prodigious proboscis, shortening it down to a more usable ten or eleven inches. Starting between her parted lips, the tongue thickens, becoming cylindrical in shape and widening until you're sure it's at least two inches across. Veins pulsate and texture the demon's tongue as it fills, giving it a decidedly... phallic appearance. The transformation finishes, capping Ceraph's cock-like tongue with a rounded, penile cap that completes the illusion.\n\n"); outputText("The tainted slut winks and licks at you with the crown, coating it in moist, feminine wetness, letting you feel the warmth of her tongue-cock upon your flesh. It feels wonderful, like being licked by a thick, flexible prick that's been slathered in saliva. Slowly, agonizingly slowly, it works its way into your passage, pushing past your engorged outer lips to snuggle into your "); if (player.wetness() < 3) outputText("moist"); else if (player.wetness() < 4) outputText("wet"); else outputText("soaking"); outputText(" canal. She twists her flexible mouth-dick inside you, making sure to rub over your g-spot, and then she slides another few inches in, forcing what feels like half of it inside you.\n\n"); outputText("Now breathing heavily, your " + hipDescript() + " begin trembling, aching to mount the invading member, fuck it, mate with it; anything to sate your growing desires. Ceraph gives you a knowing wink and sidles forward, sliding the last several inches through your spread nether-lips into the velvety embrace of your " + vaginaDescript() + ". You can feel it, squirming and rubbing inside you, twisting through your pussy with a slow, maddening purpose. From time to time it brushes your cervix, but never hard, never painfully. At the same time, it seems to always be in contact with your most sensitive places. It makes you wonder if Ceraph has practiced this on herself at some point, and you briefly entertain the notion of the demon bent over, vigorously fucking her box with her perverted tongue-prick ravaging her purple pussy.\n\n"); outputText("A jolt of pleasure blasts the image from your mind and nearly takes your [legs] out from under you. With a start, you realize Ceraph has opened her lips wide enough to slurp your " + clitDescript() + " into her mouth, and somehow, she's produced a second tongue to service it. With the stimulation of a tentacular tongue constantly hitting your g-spot and a second oral organ "); if (player.clitLength >= 3) outputText("fellating"); else outputText("licking"); outputText(" at your " + clitDescript() + ", you start to shudder, trying to stave off what you know is coming. You don't want Ceraph to get too uppity, thinking she can get you off this fast, but you're dangerously close, and her pumping, teasing mouth-cock is relentless.\n\n"); outputText("You grab Ceraph's head and mash it against your sodden, constricting box, as you command, \"<i>Drink my cum, bitch. Swallow all of your Mistress' slick leavings. And don't think for a minute I won't punish you if you miss any.</i>\"\n\n"); outputText("Ceraph closes her eyes and hums, her twin tongues redoubling their efforts inside you. Every nerve ending inside your climaxing quim seems to explode at once, and with your back arched, you cum on your slave's face. Ceraph gurgles in happiness, her voice muffled by the plush, feminine flesh quivering over her face. She happily swallows every ounce of fluid you produce"); if (player.wetness() >= 5) outputText(", even though her cheeks are bulging and her throat struggles to devour all of the fountaining girl-spunk."); else if (player.wetness() >= 4) outputText(", even though her cheeks are slightly bulged and she's gulping it down."); else if (player.wetness() >= 3) outputText(", even though she has to gulp it down from time to time."); else if (player.wetness() >= 2) outputText(", even though you produce enough for her to gulp."); else outputText(", even though your pussy doesn't gush like most of the corrupted creatures in this realm."); outputText(" Still shaking and clenching, you start to come down, still holding Ceraph in her proper place. She doesn't show any sign of discomfort, and as a matter of fact, once you deign to look down at her, her eyes are twinkling happily and her face is flushed. "); if (flags[kFLAGS.CERAPH_TIMES_LICKED] == 0) outputText("Did she... get off with her tongue?\n\nSeeing the confusion on your face, Ceraph releases your spit-slathered genitals, her tongue returns to normal, and she says, \"<i>Mmm, of course, dear. If only men knew what they were missing... tasting a woman's pussy while it climaxes on your cock is divine.</i>\"\n\n"); else outputText("Shuddering, Ceraph returns her tongue to normal and slides it out of your tender quim with a knowing smile.\n\n\"<i>I'll never get tired of that, [Master],</i>\" she quips.\n\n"); outputText("You pull her back to your " + vaginaDescript() + " to lick the last of your lady-spunk from your nethers, then send her on her way with a smile on your face. Your expression widens when you see Ceraph stagger, still a bit shaky from her own orgasm."); flags[kFLAGS.CERAPH_TIMES_LICKED]++; player.sexReward("saliva", "Vaginal"); dynStats("sen", -2 ,"cor", .25); endEncounter(); } //*Ceraph goes full tentacle and double penetrates herms (+ standard dick BJ if ceraph dick toggle is on) (Zeddited) private function ceraphTentacleGrape():void { clearOutput(); spriteSelect(SpriteDb.s_ceraphClothed); outputText("You tear off your [armor] and instruct Ceraph, \"<i>Please me. All of me.</i>\" To her credit, Ceraph only spends a moment eyeing you before she springs into action. Her panties vanish into shreds of flying latex, utterly demolished by the sudden growth of a pair of purple, undulating tendrils, each tipped with a swollen cockhead. Squeezing up behind them is a third, slower tentacle. Unlike its brothers, this one is capped with a sucking orifice, drooling clear slime and ringed by nub-like nodules, peeking out from folds of skin that remind you of clitoral hoods."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" You can vaguely see Ceraph's hard, demonic-dick underneath all the waving tentacles. She must have taken your command to keep her dick out for your use quite literally, even though there's little chance you'll get to put it anywhere."); outputText("\n\n"); outputText("The two amethyst cocks wind their way over your [legs] and lift you into the air with unholy strength, dangling you upside down while they crawl over your body, the smooth skin rubbing and stroking at your " + player.skinFurScales() + ". They curl up and slide through your hands, allowing you to feel the inhuman warmth of Ceraph's passion. Smiling, you indulge your slave, marvelling at the incredible degree of control she has over her shape-shifting. Ceraph slides the two phallic tendrils between your loins and butt-cheeks, threading one in from the front and the other from the back. They grind on your " + vaginaDescript() + " and " + assholeDescript() + ", teasing you, giving time for you to get as wet as possible.\n\n"); outputText("A warm, sucking orifice aligns itself with your [cocks], making obscene squelching noises as it dilates to take "); if (player.cockTotal() == 1) outputText("all of your girth"); else outputText("in all of your members simultaneously"); outputText(". You arch your back in pleasure, trying to push even more of your tingling cock-flesh into the tentacle-pussy. The interior is FLOODED with lube, so much that it leaks from the clit-ringed seal at your "); if (player.hasSheath()) outputText("sheath"); else outputText("base"); outputText(". Even better, there are what feels like thousands of wriggling cilia squirming in the syrupy tunnel, each of them caressing and licking at " + sMultiCockDesc() + " repeatedly. Like thousands of hungry tongues, they seem to set off every nerve in your [cocks], nearly making you forget the rhythmic, pulsating suction of the tendril as it fellates you.\n\n"); outputText("You get so distracted by this that you forget your " + vaginaDescript() + " for a moment, at least until the two fat cock-heads pressing at your lips and pucker jerk your attention back. They hesitate for but a moment, just long enough to drool pre-cum over your orifices before slithering inside. Each enormous, bulbous head spreads you wide. They stretch your holes loose until each of them pops inside, the undulating tentacles pushing their tips as deeply inside you as they can. Feeling utterly violated, completely full, and mercilessly fucked, you gasp and drool, every sexual part of your body being attended to by Ceraph's perfectly crafted sex-tools."); player.cuntChange(24, true, true, false); player.buttChange(24, true, true, false); outputText("\n\n"); outputText("Whipping through air increasingly humid with evaporating sweat and sexual juices, you find yourself suspended before Ceraph, hanging upside down. Her eyes are low, lidded and filled with lust, much like you imagine your own must appear. She's softly panting, small bursts of pleasure escaping her slightly parted lips with each thrust of the tentacles into your body and each pulsation of your trapped cock"); if (player.cockTotal() > 1) outputText("s"); outputText(". She exhales, \"<i>Might... might your slave... have a kiss, [Master]?</i>\"\n\n"); outputText("You smile and nod, licking your lips as the tentacles bring you lower and closer, still fucking you. Ceraph latches onto your lips, her tongue making love to your mouth while you hang, suspended in her tendrils' grip. Spit-slathered mouths press together harder, and you french-kiss your demonic slave as passionately as you can, trying to do to her mouth what her cocks are doing to your " + vaginaDescript() + " and " + assholeDescript() + ". You swoon, lost in the fast-fucking, slow-sucking, and eager tongue-thrusting of each other's oral orifices.\n\n"); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0 && flags[kFLAGS.CERAPH_PUNISHED] == 0) { outputText("Suddenly pulling you back, Ceraph lowers you down further, spearing her pulsating, pre-cum soaked prick into your throat. You gurgle from the sudden intrusion and the slippery, sweet cream she's leaking. She might need a punishment later, but for now, there's nothing to do but suck. You slurp and lick, the motions coming easy to you thanks to the silken caresses of the sloppy cunt-tentacle's cilia around your own [cocks]. Her nodules bulge out in your mouth, rippling in wave-like motions from her base up to the fat cock-tip, signalling that her orgasm is at hand. The thick, textured cock explodes, pouring Ceraph's load straight into your mouth. At the same time, the dick-tentacles in your pussy and ass release their own seed, stuffing your womb and rectal cavity so full of cum that you're left with a bit of extra pudge in your belly. You swallow and gulp, trying to keep up with the demon's hot, spouting jizz. After a moment, Ceraph's control loosens, and you're pulled up into the air, temporarily freeing your mouth.\n\n"); } else outputText("Suddenly pulling you away, Ceraph throws her head back and moans. You can feel the tentacles piston faster, and through your haze of arousal, you realize she's about to orgasm. The warning does little to prepare you for what's coming, and as one, the twin tentacles blast cum deep into your nethers and asshole, stuffing both body cavities full of potent demon-sperm. It's warm - hot even - and your innards tingle and soak in the corruptive spooge while they continue to pump more inside. After a few spurts, you feel absolutely stuffed and even have a bit of extra pudge on your belly from the hefty fluid-filling.\n\n"); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText("Ceraph's cock sprays cum all over her belly as her climax winds on, her poor, ignored prick blasting seed with reckless abandon.\n\n"); outputText("Your body seizes up and explodes with pleasure, spraying sexual fluids into and over Ceraph's new additions. The cunt-tentacle "); if (player.cumQ() >= 800) outputText("bulges wide from the sheer size, sucking"); else outputText("sucks"); outputText(" down your cum as it erupts from your [cocks]. As it swallows every drop, you hazily wonder what she'll do with it all, but then the still-fucking tentacles move faster, spraying their cum out from your too-packed orifices to rain over both of you. Your " + vaginaDescript() + " and " + assholeDescript() + " flutter and contract, involuntarily squeezing the purple-skinned invaders for even greater levels of sensations. It's too much and too hard. You black out with a moan of satiated pleasure.\n\n"); outputText("You come to in a puddle of cum, both yours and Ceraph's. The demoness is sitting down across from you, her appearance returned to normal. She brightens when she wakes and kneels, saying, \"<i>Thank you for allowing me to serve you so... completely, [Master]. It was... thrilling.</i>\"\n\n"); player.sexReward("cum", "Vaginal"); player.sexReward("vaginalFluids","Dick"); dynStats("sen", -2, "cor", .25); if (!player.isGoblinoid()) player.knockUp(PregnancyStore.PREGNANCY_IMP, PregnancyStore.INCUBATION_IMP - 32, 61); //Ceraph causes faster pregnancies if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0 && flags[kFLAGS.CERAPH_PUNISHED] == 0) { outputText("You smirk and wonder if you should punish her for stuffing her cock down your throat. Do you?"); simpleChoices("Punish", punishCeraphForSurpriseThroatFuck, "", null, "", null, "", null, "Leave", explorer.done); } //ELSE: else { outputText("You nod graciously and begin to clean up, dismissing your personal demon... for now."); endEncounter(); } } //[Punish Her] private function punishCeraphForSurpriseThroatFuck():void { spriteSelect(SpriteDb.s_ceraphClothed); flags[kFLAGS.CERAPH_PUNISHED] = 1; clearOutput(); outputText("You grab hold of Ceraph, bending the surprised demoness over a rock and laying into her ass. She whimpers, but manages not to cry, even as you turn her purple butt into a black and blue canvas. With each slap you deliver, you dictate that her cock is only allowed near your mouth at YOUR discretion, not a worthless slave's. By the end, she's sniffling and nodding, murmuring, \"<i>Yes [Master],</i>\" over and over again.</i>\"\n\n"); outputText("You let the demon go with her pride bruised. There's little doubt to be had - she'll never make that mistake again."); endEncounter(); } //Siamese Catgirl Twins - TDM (Zeddited, nya) public function catgirlEncounter():void { clearOutput(); //requires that the PC have a cock, just to keep it simple, no centaurs and probably not slimes outputText("You call on Ceraph, but are a bit taken aback when she doesn't appear right away. You look around to see if you might have missed her, then spot something else streaking towards you from the wastes. It is kicking up so much dust that you don't have time to see what it is before it "); if (!player.hasPerk(PerkLib.Evade) && player.spe / 5 + rand(20) < 22) outputText("flies into you, knocking you to the ground. After a moment, you find yourself faced with a pair of overeager cat-morphs grinning down at you."); else outputText("just barely misses you and crashes into the ground behind you. After a moment, two bodies disentangle themselves from the impact site. Once they stand up, you can see that a pair of overeager cat morphs have arrived in your camp."); outputText("\n\n"); //describing your new friends outputText("You study them for a few moments. They have glossy, soft, and pliable fur covering most of their bodies, generally with a whitish or mother-of-pearl tone. That color gives way to darker layers on their legs and face, giving them a mischievous, owlish look. They have feline legs with paws, but their arms look more like fuzzy hands with pads. Long, flexible tails swish behind them, and pointy cat ears adorn the tops of their heads. Their chests bear generous E-cup breasts, with small bare patches further down where other pairs of nipples poke out. They have kittenish, clear blue eyes that lend an air of innocence to them, but the small horns on their foreheads suggest anything but. Being Ceraph's pets, they are predictably perforated with piercings on their ears and tails. One thing that plays over and over in the back of your mind is that the two are completely identical; <b>you're facing a pair of siamese cat twins</b>!\n\n"); outputText("As a chorus, the two start to speak. \"<i>Mistress Ceraph couldn't come, so she has sent us to help you with your needs; the sisters are here for your pleasure.</i>\" The choice is yours; do you play with these furry, eager, cat-faced girls, or send them away?\n\n"); //player chooses sex, no sex(, extermination) simpleChoices("Sex", fuckCeraphsCatgirls, "", null, "", null, "", null, "Leave", declineCeraphsCatgirls); } //No sex private function declineCeraphsCatgirls():void { clearOutput(); outputText("You shake your head at the kitty sisters and tell them that you aren't interested in fucking cats; you wanted the sexy demoness you were promised. The two mewl meekly before slumping away."); //to camp menu doNext(playerMenu); } //SEX! private function fuckCeraphsCatgirls():void { clearOutput(); var x:Number = player.biggestCockIndex(); outputText("You smile at them and say that you'd be happy to have them for your pleasure; their horns suggest that they'll be quite a trip. The two purr happily and instruct you to lie on your back to start the fun. You relax as directed and the cat slaves unfasten your [armor] from your body. As they work, they make sure to gently stroke every inch of your newly exposed flesh with their soft furry hands as it's revealed; all the while moving closer and closer to your most personal parts. When " + oMultiCockDesc() + " finally tastes the air, it gets even more attention.\n\n"); //purrfect tit fuck outputText("You can't help but put your hands to their heads and start rubbing and scratching them behind their ears. Suddenly, one of them steps back as the other moves down in front of your " + cockDescript(x) + " and pulls it inside her breasts. In response, both your hands end up on her head, forcing it down onto your cock, and you feel your manhood start to vibrate as the catgirl begins to purr. You cry out in pleasure at your shaft being massaged by soft-furred breastflesh while she hums into the tip.\n\n"); //play with da boobies outputText("The other sister has been looking for something else to rub herself on, and she seems to have decided on your " + chestDesc() + ". While your lower half is being covered by one cat (which is fine too), the other moves to your top half and drapes her breasts over your head while she gropes and plays with your " + nippleDescript(0) + "s."); if (player.biggestLactation() > 1) outputText(" When some of your milk seeps out, she leans forward and latches onto a nipple eagerly, alternating between sucking on the tip and licking the drops off of it."); else { outputText(" She seems to delight in playing with her chest, modest though it may be, pushing it into your face and tweaking the fuzzy nipples just past your nose. You blow a raspberry and shake your face into her cleavage, "); if (rand(5) == 0) outputText(" but some of the fur tickles your nose a bit <i>too</i> deeply; you deliver a sudden sneeze into her bosom, causing it to heave and jiggle."); else outputText("vibrating it wildly back and forth."); } outputText(" Her sister, watching all this, shakes with muffled laughter delivered directly into your cockhead, sending rough jolts of sensation down the shaft and forcing out a drop of pre-cum.\n\n"); outputText("The cat lying on your face sits up as her sister's eyes glimmer desirously upon tasting the drop; apparently she has recognized the expression, because she looks down at you and says, \"<i>Please, don't give all your rich, tasty cream to my sister. She always steals my fair share, the bad kitty!</i>\" Her meaning is obvious in context, moreso when she moves around to your groin, trying to shoulder her sibling aside and "); if (player.cockTotal() == 1) outputText("sliding her hand between the furry tits, down the base of your " + cockDescript(x) + "."); else outputText("grabbing the lonely, neglected dickflesh left outside the warm embrace of her sister's breasts and shoving them into her own while caressing the tip with her tongue."); outputText("\n\n"); outputText("Thanks to all the stimulation from before, their expert tongues almost immediately bring your body to a shuddering orgasm, and " + sMultiCockDesc() + " "); if (player.cumQ() >= 1000) outputText("unleashes a torrent of ejaculate, coating the two girls liberally; each yowls in happiness, slurping at the nearby cock-head and swallowing mightily."); else if (player.cumQ() >= 300) outputText("lets out a generous load of 'cream' which each girl sloppily gulps down, lapping at the jism and its source roughly."); else outputText("squeezes out a few immodest squirts of semen, which the girls push and fight over, each vying to be the one to gulp down the next stroke."); outputText("\n\n"); outputText("You relax on your back, spent from the treatment and the orgasm; the kitty twins"); if (player.cumQ() >= 1000) outputText(" clean the remnants off of their fur eagerly, mollified by the sheer amount into actually helping lick each other clean with their tongues, and"); outputText(" thank you for the 'cream'. You nod weakly and they jump to their feet and swish their tails at you, then depart.\n\n"); //lust to 0, corruption +0.5 player.sexReward("no", "Dick"); //end scene endEncounter(); } private function ceraphUrtaRoleplay():void { SceneLib.urta.urtaSprite(); clearOutput(); outputText("\"<i>Roleplay? My [Master] is wonderfully exploitative with [his] pet's lewd body,</i>\" Ceraph purrs, lips curling into a sly smile. Holding your arms at your sides, you nod at the subjugated demon, indicating that she should strip you. Keeping her eyes averted, she obediently complies, removing your [armor] piece by piece until you stand nude, in all your splendor. Turning upon her, you issue your curt command, briefly describing the form that she is to take. Surprisingly, she knows exactly who you're talking about. \"<i>Ah, the fox-bitch,</i>\" she muses, eyes flashing solid black again for a moment. \"<i>She's been such a thorn in my side for so long... letting you defile her will be a particularly intense pleasure, [Master].</i>\"\n\n"); outputText("Breathing deeply, she shudders, her whole body shaking like a dog coming out of the rain. When she finishes her spasm, you see that her lavender skin is now covered by a fine coat of grey fur which grows and thickens in seconds until there is no trace of her smooth flesh or her latex outfit. She bites her lower lip and the long, thin appendage curling from the demon's ass puffs outward into a bushy fox tail while the hair on her scalp fades to a smoky, ashen color, streaked with black highlights. Seizing her curling horns, Ceraph strokes them languidly, the bone melting in her grasp like putty, allowing her to sculpt them into sharp, narrow ears that twitch uncertainly. Placing her fingers at the bridge of her nose and her thumb under her jaw, she cocks her head to one side and yanks forward, her skull deforming as the front of her face is pulled into a vulpine muzzle, lips thickening into a glistening black pucker as she blows you a kiss.\n\n"); outputText("Sweeping her hands about in deference, Ceraph curtseys to you and raises her stolen face, eyes twinkling green behind her medium-length bangs. \"<i>With your permission, [Master], the final touch.</i>\" You nod, a grin already creeping at the sides of your mouth. Eagerly, the fiend takes hold of her demonic shaft- hard as much from the transformation as your lascivious stare- both hands wrapping around the demonic phallus gingerly. Licking a long, pink tongue over her inky lips, the shapeshifter begins to jerk herself off, sliding her palms up and down the pulsing, bumpy dick with quickening strokes. Her mouth hangs open and she rolls her eyes up as the frantic pace sends her furred chest wobbling and her lashing tail twitching frantically behind her. Gradually, you notice that her brutal pace seems to be lengthening the demon's organ, swelling firmness bloating it larger and longer, purplish hue darkening and darkening until it fades to a ruddy burgundy at the tip, fading to a velvet black at the base. \"<i>Oh [Master], your wish is my command</i>\" she gasps, her oily voice turning richer and huskier with every syllable, until it is an exact echo of Urta's. The resculpted horsecock throbbing in her hands lurches forward to its full 20 inches as her tip flares out, thick jets of ropey cum bursting from the fox-girl's equine member. As it jerks in her hands, a fuzzy, ebony sac drops from the puffy sheath of her jizzing cock, trembling balls dropping heavily into the scrotum. When she's finally done, the captain of Tel'Adre's City Guards stands before you, panting, her still-dripping cock in one hand, a tall bottle of whisky in the other, creamy pools of cum all around her.\n\n"); outputText("\"<i>Oh! [name]! I, um, didn't expect to find you here! This... this isn't what it looks like,</i>\" she apologizes, flushing deeply, nervous shame sending humiliated shivers through her shoulders. She longingly eyes the bottle in her hand and, without lifting her head, raises her eyes to yours, silently asking what she should do."); //[Drink][Sober] menu(); addButton(0, "Sober", ceraphUrtaRoleplaySober).disableIf(!player.hasCock(), "Req. a cock."); addButton(1, "Drunk", ceraphUrtaRoleplayDrunk).disableIf(!player.hasVagina(), "Req. a vagina."); } //DRANK AS FCUK //[Drunk] (female/herm only. No centaurs) private function ceraphUrtaRoleplayDrunk():void { clearOutput(); SceneLib.urta.urtaSprite(); outputText("You wish her a cheerful 'bottom's up,' relief washing over her face as she seeks shelter in the blissful oblivion of alcohol. Lifting the bottle's fluted neck to her polished lips, Urta throws back her head and begins swallowing. Her throat bulges in rhythmic gulps, air bubbling up through the liquor as the whiskey steadily vanishes into her shame-thirsty gullet. Her face flushes deeper, the bitter sting of booze taking her mind off of the embarrassment of her equine attributes. Her cock throbs in the open air with each noisy glug, dollops of cum still drooling from her engorged member. Finishing the entire bottle, the fox-morph wetly sucks down a fresh lungful of air, her expression floating somewhere between stimulated joy and dazed confusion. She looks closely at the bottle and blinks several times. \"<i>Wh- what did you put in this?</i>\"\n\n"); outputText("With a shrug, you admit that you're impressed she noticed the little additive. It seemed unlikely she would've tasted much of anything with how quickly she slurped down her liquid vice. Grinning, you ask her how the black egg tasted. Urta's mouth hangs open, inebriation sinking its talons into her brain one by one, but after a moment, the realization dawns on her. Before she can voice her outrage, the change begins, Urta's body cringing with twisting spasms. She drops the bottle and clutches at her stomach, but when she raises her hands again, strands of light grey fur scatter into the wind from between her fingers. Falling to her knees, she begins itching, frantically, more of her ashen hair sloughing off as if she were shedding uncontrollably. Watching the girl paw at herself wildly, you bend down, close to her face, and when her head turns up to speak, you give the vixen a flick across her nose. She snatches her sensitive muzzle with a whine, hands wrapping around it as she writhes on the ground, fur falling away with each trembling shake.\n\n"); outputText("When Urta finally stops shuddering, the vulpine guard looks very different. The silken coat of grey fur that once patterned her lean, athletic torso has been removed, to reveal the soft caramel of her dusky-hued skin. While her lower legs and pawed feet retain their leaden pelt, they now more closely resemble stockings than natural body hair. Her tail seems unaffected as well, fluffy fur twitching from the junction just above her taut ass, raw sienna globes shining from the sweat of her transformation. Moving your gaze further along her dark amber body, you find two sharp, sliver fox ears poking out of the black-striped argentine hair on her head. Beyond these spots, however, it seems the girl has lost all of the fox hair that previously covered her, from her knees up to her eyebrows. Shaking her head, the Captain of Tel'Adre's city guard takes her hands from her face and almost leaps backward in surprise. Her muzzle is gone, replaced with a small, humanoid nose and plump, ebony lips just beneath it. Her startlingly human features cause the intoxicated girl to press her fingers against the burnt sugar of her skin, soft flesh highlighting the high cheekbones of her feminine face. She runs a hand through her hair, not sure what to think and too drunk to form an opinion.\n\n"); outputText("Grasping her shoulders and lifting her gaze to yours, you stare into Urta's emerald eyes. With a signing breath, you whisper that she's never looked more beautiful, and press forward, your lips eagerly finding hers. She twists her head too far to the side, trying to compensate for a muzzle that's no longer there before giggling into your mouth and turning back too far, bumping her nose against yours. She lets out a brief bark of laughter and moistly kisses your forehead, running her hands unsteadily down your " + player.skinFurScales() + ". \"<i>So, you like me this way, huh? Well, now it's my turn. Bottom's up!</i>\" She pushes you backwards harder than she'd intended, knocking your head against the soft ground before grabbing your " + hipDescript() + " and flipping you onto your " + allChestDesc() + ". Looking back over your shoulder, you see the girl tweaking her pale, pink nipples which stiffly rise from the generous swell of her olive breasts. A warm, firm thwack between your ass cheeks tells you that neither the alcohol nor her first orgasm has affected the herm's raging hardness. As she slides her cock up and down, between the pillowy orbs of your rump, you can feel every contour of her twenty inch horsecock- from its bulging veins to the ringed lip of her fleshy sheath to the smooth, cool skin of her refilling scrotum, heavily slapping against your inner thighs. You squeeze your [butt] in time with her long strokes, stroking the shaft between your globes as she quickens the pace. She can't keep her hands off her new body, it seems, the guards-woman rubbing her palms over her breasts, belly, arms, and hips, feeling her flawless flesh as eagerly as she hotdogs your [butt].\n\n"); dynStats("lus", 125, "scale", false); //[Next] doNext(ceraphUrtaRoleplayDrunk2); } private function ceraphUrtaRoleplayDrunk2():void { clearOutput(); SceneLib.urta.urtaSprite(); outputText("The cock sliding up your backside throbs in anticipation and you realize that Urta's over-stimulated herself. Lips parting in a whorish moan, she climaxes, her fingers digging into her soft, smooth skin as her massive shaft flares thicker than you've seen before, gouts of thick jizz arcing from her head. You can feel the voluminous loads surging between your cheeks before bursting from her tip and cresting through the air before splattering down in cords of creamy cum. All along your back, neck, hair, and face, sticky wads of spunk douse you in the fox-girl's excitement and you squeeze your rear as tightly as you can to massage out every last ladle of her rich seed. She bathes you a pale off-white but to your surprise, she's still moaning and stroking the skin of her changed body. \"<i>It's not enough,</i>\" she mumbles, \"<i>I need more.</i>\" You start to rise, but the drunk girl slams her palms onto your shoulders, planting you back into the ground, body horizontal beneath her. Sliding backwards, her engorged cockhead presses insistently against the juncture of your hips, still bubbling with dollops of cum. \"<i>It's too sensitive,</i>\" she whines, pinning your lower body between her muscled legs. Your struggles to get out from under the drunk, horny girl are fruitless, so you turn your head and see that her throbbing sac is- if anything- even larger than before, her cock still rock hard as she guides it up against your " + vaginaDescript() + ".\n\n"); outputText("\"<i>Oh damnit, damnit, damnit,</i>\" Utra chants as she presses her erection against your drooling slit, the equine inches slipping along the sweat-oiled plumpness of your thighs. Inching forward, she presses the flared tip of her head against your tender lips, the distended flesh struggling against the tightness of your snatch, lubricated depths unwillingly parting bit by bit until finally, the bulbous cockhead slips into you, your cunt tightening down around it, firmly locking the guard captain inside you. \"<i>Ah! Ffffffuck!</i>\" she curses. \"<i>How are you always so tight?</i>\" she groans, happily. Unable to restrain herself, she begins bucking in place, sliding the first three inches of her throbbing member back and forth inside you, savoring the ripples her rocking motion sends through your [butt], your hypnotic hips mesmerizing the girl riding you. Raising an amber hand, she cracks an open palm against your tender ass as she drives another two inches inside you, your gut lurching with the force. You try to "); if (player.isGoo() || player.isNaga()) outputText("wriggle to a wider stance"); else outputText("spread your legs"); outputText(" to make the penetration easier, but the vixen has your lower body firmly trapped between her knees, keeping your hips as tightly clenched as possible, heart-shaped rump throbbing at the fleshy weight within you. \"<i>Don't you love the long arm of the law?</i>\" she snickers, hiccupping as she gives you another swat across your [skin], this time plunging half her length into your " + vaginaDescript() + ", stealing the breath from your lungs. Your squirting honey leaks from between your lips, lubricating the girl's shaft all the way to the ring of her sheath. You can feel the ten inches of her shaft inside you lifting your abdomen off the ground a few inches and it's all you can do to dig your fingers into the dirt as she thrusts rapidly, shallow pulses leaving every inch of your body jiggling under her."); player.cuntChange(60, true, true, false); outputText("\n\n"); outputText("Pounding you faster and faster, you can feel her cock swelling within you dangerously. Rutting frantically, she leans down, pressing her smooth sienna skin against your jizz-soaked back, her tits rubbing the fox-girl's spunk into your [skin]. Lowering her head, she whispers into your ear, \"<i>No condoms for sneaky bitches who spike drinks,</i>\" her husky voice right on the edge. \"<i>Fur isn't the only thing I've lost. I'm potent again,</i>\" she drunkenly insists. \"<i>I can feel it in my big, swollen balls."); if (amilyFollower() || marbleFollower() || izmaFollower()) outputText(" After I knock you up, try explaining the fox tails on your kids to those other bitches."); outputText("</i>\" Reaching out to brace herself, Urta grabs your shoulder with her left hand, but her right goes wild and she ends up hooking her fingers in your mouth, jerking your cheek to the side. With the added grip, she wriggles deeper, the remaining inches snaking into your uterus until the elephantine flare rubs against your cervix, the bottom ridge of her fleshy sheath teasingly flicking against your swollen clit. Sensations crash over you: the gentle curves of her fit abdomen stroking your ass, her wobbling chest pressing button-stiff nipples into your back, the sweet taste of your tongue stroking the fingers in your mouth. It is too much and your body clenches down in a gushing orgasm on the invading member, drool leaking from your gaping mouth as your heavily lidded eyes lose focus, allowing the fox-girl to use you to her heart's content.\n\n"); outputText("When she cums for the third time, you can feel the blast directly on your cervix, the force of her load parting the muscled sphincter, ropes of newly virile seed flooding your womb. The weight of her distended scrotum pulses between your thighs and your belly bulges under the impregnating torrent. Urta's body tenses as she inundates your depths with the excess of her loins, the influx cascading through your uterus to burst like a tide, your body flush with her pouring jizz."); if (player.hasCock()) outputText(" " + SMultiCockDesc() + " releases its own glut in a sympathetic climax that turns the dirt under your body into sticky mud as your inflating gut spreads out from either side of your belly. Still cumming, Urta presses her lips to the back of your neck, kissing you softly in a gesture that almost seems to convey a sense of ownership as much as tenderness. When she finally withdraws from your over-filled pussy, the glut of her semen bubbles out of your body in rolling waves of alabaster cream. She rises, unsteadily, to stand over you, her cock finally drooping, thick strands of spunk still dripping between her engorged urethra and your spasming cunt. \"<i>Hey, I can finally take a shower without smelling like a wet dog afterwards,</i>\" she realizes, happily. She reaches a hand down to help you up, her expression one of blissful satisfaction, but the experience was too much for you and you pass out. The last thing you see is the warm halo of her caramel face and the caring sparkle of her leafy eyes."); outputText("\n\n"); outputText("You wake up before long and find yourself cleaned, though still a little sticky, as if someone had used their tongue to wash the cum from your " + player.skinFurScales() + "."); player.sexReward("cum","Vaginal"); dynStats("sen", -2, "cor", 2); //Preggers chance! if (player.hasVagina() && player.totalFertility() >= rand(45) && player.canGetPregnant() && !player.impregnationRacialCheck()) { player.knockUp(PregnancyStore.PREGNANCY_IMP, PregnancyStore.INCUBATION_IMP - 32, 61); //Ceraph causes faster pregnancies trace("PC KNOCKED UP WITH CERAPH IMPS"); } endEncounter(); } //[Sober] private function ceraphUrtaRoleplaySober():void { SceneLib.urta.urtaSprite(); clearOutput(); outputText("You tell Urta to put the bottle down. She won't need that, not anymore. She looks at you in confusion, setting the whiskey to one side, curling her tail between her legs to cover her throbbing member. Closing the distance between the two of you, she stiffens when you wrap an arm around the small of her back and bring the other hand up to her chin. She doesn't have to be ashamed anymore, you explain, because you know the cure for her curse. The fox-morph's eyes light up, her mouth parting but not daring to speak or even breathe. Stroking a thumb along the line of her jaw, you close your eyes and nod slowly, pulling her into an embrace tight enough for you to feel the fluttering pulse of her body heat sinking through your " + player.skinFurScales() + ". You can tell by the wobbling of her lower lip that she is dying to ask how, but you merely brush the dappled-grey bangs from her eyes, staring into the guard's emerald irises. You can feel the soft intake of her breath as it catches in her throat and she leans toward you ever so slightly, blushing. You meet her halfway, obsidian-warm lips pressing against yours tentatively at first, before gaining confidence. She sinks deeper into the embrace, the tight tension knotting her back slowly easing as surrenders her self-conscious shame for unabashed passion, relishing the intimacy of your caress. When you draw back from the intoxicating fever of the fox girl, you whisper one word to her: \"<i>Love.</i>\"\n\n"); outputText("Urta stares silently, her expression shocked at first, before her restraint crumbles, tears welling in her eyes. \"<i>Th-thank you [name]. I love you too! From the moment I met you, I barely dared to hope, but... oh thank you!</i>\" She throws her arms around your shoulders and hugs you with all her might, body trembling with joy. A moment later, her strength gives out and she sinks to her knees. \"<i>Ah!</i>\" she gasps in surprise, her cock twitching in the air. The massive, rock-hard shaft begins to shrink, inches of flesh sinking upward into her midnight sheath while her throbbing balls recede upward, into her abdomen, growing smaller with each passing moment. The horsecock shrinks down to twelve inches, then six, then three, the flared tip barely poking above the fine, ebony fuzz of her groin before her sheath too is pulled between her legs. Her balls vanish, body sealing over the purified orbs, the skin of her sac pulled tight until there is no trace they ever existed. Her cock is similarly cleansed, flesh healing over the blight of her male organ in the blink of an eye, leaving her pussy untouched, glistening with excitement.\n\n"); outputText("The herm, at last restored to a pure woman, rubs the healed expanse of her abdomen, unbelieving, before leaping to her feet and excitedly seizing both of your hands. \"<i>I'm normal! No longer a freak! Oh, [name], I can never repay you for this. You've given me a new life! Please... won't you,</i>\" she gazes at you with a flush of anticipation, \"<i>won't you make love to me?</i>\" Pulling your hands to her hips, she steps close enough to kiss, but merely presses her forehead against your own, viridian eyes no longer clouded with coarse lust. Instead, they practically glow with the girl's ardor, her smile authentic and honest. Unblinking, you gaze into her eyes for a moment that stretches into an eternity, cupping a hand around her cheek. She reads your acceptance as clearly as if you'd been yelling it from the mountaintops and she returns your gentle smile, nuzzling her nose against yours.\n\n"); outputText("Drawing you back to your cot, Urta sits on the cushioned bedding, knees spread as she leans back and braces herself on her elbows. You sink between her muscled thighs, rubbing your palms up the dusky fur of her hips as you bring your head toward her leaking pussy. The delicate folds of her labia are as dark as her nose, but there is a certain elegance in their plush depths, like the petals of a black rose guarding the nectar of the flower. You trace your tongue around the edge of her vulva, warm skin tingling with the faintest trace of the athletic guardswoman's perfumed sweat, exciting the tip of your tongue and making you draw it back into your mouth to savor the untainted taste of the girl's body. Placing small kisses on the puffy lips of her sex, you draw the girl's skin into your mouth with a gentle sucking, nibbling at the fox's flesh with only your lips as you gradually, achingly work your way up to the polished nub of her clitoris, engorged from your teasing oral stimulation. You stroke the sensitive flesh with the tip of your nose, brushing the swell of your lower lip across Urta's joy-buzzer. She moans, her hips swaying back and forth in time to your movements."); if (player.horns.count > 0) outputText(" Unable to keep her hands at her sides, but unwilling to stand between your mouth and her slit, the fox-girl takes hold of your horns, pulling your face tightly against her mound, her chest tight with a barely audible squeak of delight. Stroking the tip of your tongue at the curtain of her sex, you allow her the barest trace of penetration before drawing back and placing a wet kiss on her clit. Enough foreplay."); dynStats("lus", 200, "scale", false); //[Next] doNext(ceraphUrtaRoleplaySober2); } private function ceraphUrtaRoleplaySober2():void { hideUpDown(); SceneLib.urta.urtaSprite(); clearOutput(); outputText("You rise and run your hands along the lighter fur of her toned abs. \"<i>Please,</i>\" she whispers, \"<i>I want to feel you inside me.</i>\" Your [cock] is all too willing, throbbing meat sliding up and down her lubricated lips as you slowly rock back and forth. Bracing your tip at the pucker of her honey-slick passage, you take one of her hands in yours, entwining your fingers with a squeeze as you push into her. Urta jolts with a sharp intake of breath before relaxing herself and closing her eyes to focus on the sensation of your inflamed shaft parting her inner walls. You push in deeper, amazed at how wet she is already, the strength of her love for you intensifying every motion. Despite all the sexual encounters she's had before this moment, in this single instant, it's as if she's experiencing pleasure for the first time. Aching bliss coursing through her limbs, it's all she can do to gasp and slowly toss her head side to side as you sink deeper into the girl, her recesses filling with the almost liquid heat of your throbbing member."); if (player.biggestCockArea() > 150) outputText(" Even your tremendous size is no impediment to blessing the girl with your passion- every inch of her body gives way as you sink into her beyond the limits you would normally expect, as if her body were perfectly tailored to yours."); outputText("\n\n"); outputText("When you finally bottom out, the two of you are already panting, the sheer rapture of the penetration coaxing the two of you to the precipice of orgasm. You stop moving, just drinking in the moist pressure of her body clenching around you. Urta, in turn, can only wordlessly move her lips at the ecstasy of being so utterly filled, her breasts heaving on her chest, shimmering onyx nipples glinting at the tips of her mammaries. When the two of you feel you have mastered yourselves, you begin to pull back out, her trembling cunny grasping at your [cock] as if regretting every lost inch. With a steady pace, you begin to thrust into the guard captain, her hips matching your motions eagerly. She strokes the tips of her fingers along your " + chestDesc() + ", wrapping her hand around the side of your neck as the two of you rock the cot back and forth. The vixen's pussy splashes with each pounding advance of your engorged shaft, her twinkling honey running between her thighs in gleaming rivulets. She locks her ankles around your [butt], using her legs to speed up your pace until you find yourself fucking the vulpine woman at a frenzied pitch. The two of you noisily, wetly slam against one another hard enough for the sounds of your passion to carry all over your camp and into the surrounding forest, cries of moaning gratification piercing the air.\n\n"); outputText("When the two of you reach the crest of your climax this time, neither of you has the strength to hold back, triumphantly surging toward your simultaneous orgasms. Urta squeezes your hand so tightly your knuckles crack in her hands while her legs pull your " + hipDescript() + " into an iron embrace. Your " + cockDescript(player.biggestCockIndex()) + " releases its fertile load into the girl's depths, liquid weight flooding her ravished canal with the creamy testament of your love. She holds you inside her desperately, her pliant, sable lips murmuring her devotion to you with shuddering whispers. When you finally finish, she keeps you within her a minute longer, savoring the sensation of your shaft surrounded by the rapturous warmth of your seed, before finally releasing her grip, allowing you to withdraw. Sighing happily, she rubs her pussy lips as you slip out, a pearl bead of your jizz bubbling from her stuffed uterus. She runs her fingertips through the spunk, massaging the cum against the folds of her glistening labia. \"<i>You know,</i>\" she playfully murmurs, \"<i>now that my curse is broken, I'm not barren anymore.</i>\" She closes her eyes and takes a deep breath, cooing about the feeling of your silken sperm pressing against her waiting womb. You smile, despite yourself.\n\n"); outputText("Retrieving your [armor], when you turn around again, Urta is gone, the moment vanishing like a drop of water in an endless sea. \"<i>Thank you, [Master],</i>\" Ceraph's voice demurely whispers, gratitude floating on the wind."); player.sexReward("vaginalFluids","Dick"); dynStats("sen", -2, "cor", 2); endEncounter(); } //Corrupting the Innocent with optional gangbang -Luka (Zeddited) (with Shake N' Bake) (and Shambles helped) //Demon cock supplied for PCs without one. //This probably does not fit Pure PCs either. This should probably give the PC massive Corruption increase too. //PC gets to pick if they want to offer the girl to be gangbanged by the imps or not. //You will be fucking her with an audience. //NOTE: This will probably need an alternate version for centaurs. Goo and Nagas should be fine. //NOTE2: Fen you might want to store the variable for the PC's cock type and cock size. public function carephCorruptionSlaves():void { clearOutput(); outputText("You call on Ceraph, but rather than the familiar sight of the purple omnibus, you see a human girl being brought into the camp by a gang of imps. They approach you and pull the girl's collar down, forcing her to kneel before you.\n\n"); outputText("One of the imps steps forward and opens a letter, then begins reading. \"<i>Lady Ceraph apologizes to her [Master], but she finds herself unable to service you. So she has sent this human as an offering for the [Master] to corrupt. To this end, she has prepared a concoction for you. Drinking this will provide you with what you need for the job, [Master].</i>\"\n\n"); //(Very High Corruption) if (player.cor >= 75) { outputText("You glare at the imp, asking if Ceraph's implying you're not able to fuck this girl by yourself.\n\n"); outputText("The imp recoils and offers a quick apology. \"<i>No, of course not, [Master]. Forgive us, we did not wish to offend.</i>\"\n\n"); outputText("Gruffly, you dismiss him with a wave of your hand. The imp bows, thankful for your mercy.\n\n"); } outputText("He closes the scroll and holds out a bubbling black vial labelled \"<i>Drink me!</i>\" to you. The other imps form a line behind the girl.\n\n"); outputText("Do you accept the 'offering' of the girl and drink the potion?"); //[Yes][No] simpleChoices("Yes", ceraphLackeyCorruption, "", null, "", null, "", null, "Leave", makeCarephsLackeysLeave); } //[=No=] private function makeCarephsLackeysLeave():void { clearOutput(); outputText("You wave the imps away and tell them that you're not interested. One of the imps protests, \"<i>But, [Master]-</i>\" You cut him off before he has a chance to finish, saying that you wanted Ceraph, not some human girl! Then, you toss the potion away and tell them to take the girl away.\n\n"); outputText("\"<i>Y-Yes, [Master]...</i>\" the imps reply meekly, pulling on the collar to drag the girl away."); doNext(camp.campSlavesMenu); } //[=Yes=] private function ceraphLackeyCorruption():void { clearOutput(); outputText("You grin and tell the imps that you will accept Ceraph's offering. Then you circle the girl, appraising her.\n\n"); outputText("She is quite beautiful... about 5'4\" tall, with shoulder-length blonde hair. Her face is covered by a blindfold, which you forcefully yank from her. She gasps in fear and looks at you; her eyes are blue like the ocean, while her lips are pink and full.\n\n"); outputText("You gaze lower to appraise her breasts, guessing that they're at least a fair D-cup, and see that she's wearing a pair of nipple clamps connected by a chain. Her hands are held behind her by a pair of leather cuffs.\n\n"); outputText("You reach down between her legs, spreading them to probe her pussy; she gasps as you do so. You feel her pussy and realize it's moist... ha! The bitch is enjoying her predicament! You show her your glistening fingers and she looks away in shame.\n\n"); outputText("The vial of black fluid, that the imps offered you, tastes sour and thick, and as it slides down your throat you can feel it burning a path of liquid heat through your throat. The liquid settles in your belly and the heat spreads through your body; then focuses on your crotch.\n\n"); //Cock obtained from this is human-looking, so you'd trigger the next paragraph too. //(if PC has no cock) if (!player.hasCock()) { outputText("Intense pleasure overcomes you as you feel blood rush to your groin; "); if (player.hasVagina()) outputText("your " + clitDescript() + " swells"); else outputText("a small bump forms on your mons"); outputText(", then develops into a huge 16-inch long, 3-inch thick erection! The tip practically explodes from the foreskin vainly trying to contain it. "); } var x:Number; var demon:Boolean = false; x = player.biggestCockIndex(); if (player.hasCock()) { if (player.cocks[x].cockType == CockTypesEnum.DEMON) demon = true; } //(else if PC's cock is below cock area 48) if (player.cockArea(player.biggestCockIndex()) < 48 && player.hasCock()) { outputText("Your " + cockDescript(x) + " throbs, veins bulging as it grows larger, ballooning to a generous 20-inch long, 3-inch thick size. "); } //(if PC's cock is not demonic or pc has/had no cock prior) if (!player.hasCock() || !demon) { outputText("A heady, musky scent emanates from your cock, then its color changes abruptly to a shiny inhuman purple hue and tiny sensitive nodules form along the length of the shaft; the crown develops a circle of rubbery protrusions that grow larger as you become more aroused.\n\n"); } else { outputText("You stroke your demonic prick, bringing it to full mast; it throbs as if knowing what is coming.\n\n"); } outputText("You admire the pulsating demonic member as pre-cum leaks from the tip, lubricating your shaft and dripping obscene gobs into the dirt; the girl looks at you, terrified. The imps stare at your tainted dick and the girl's fearful expression, panting with arousal as their own cocks harden at the sight.\n\n"); outputText("You order them to remove the girl's bindings and hold her down. They quickly oblige, removing the leather cuff and pinning the girl down, then spreading her legs to allow you better access to her moist tunnel.\n\n"); outputText("You grab her hips and tease the poor girl by rubbing your nubbly shaft against her clit, forcing moans of unwanted pleasure out of her; moments later she screams in orgasm, her pussy juices already splashing against your "); if (player.hasBalls()) outputText("scrotum and "); outputText(player.legs() + ". The imps on her extremities laugh at the girl as she relaxes and her head slumps into the ground; you motion for the imps to release her and step back, then align yourself with her pussy.\n\n"); //(if PC is above 60 cock area) if (player.cockArea(x) >= 60) { outputText("It's clear to see that if you push inside her with a member of your size, you will rip her apart; thankfully, one of the imps steps forward with a vial containing a bluish fluid and forces it down her throat. She drinks without resistance, then gasps as she orgasms once more, juices splattering about as her cunt seemingly grows elastic and wet enough for you to push the tip of your massive demonic cock inside her effortlessly.\n\n"); } outputText("You plunge into her warm depths, and she moans as your shaft forcibly forces her walls apart. When your hips finally collide she screams, \"<i>Yessss!</i>\" and orgasms once more, milking your shaft with powerful contractions even as you begin pounding her in earnest. Something in Ceraph's concoction must be playing havoc with your nerve endings; the newly-found sensitiveness of your shaft and the stimulation from her pussy are too much to contain and you burst inside her, shooting jet after jet of cum inside the girl's stretched pussy.\n\n"); outputText("You empty "); if (player.hasBalls()) outputText("your balls"); else outputText("yourself"); outputText(", and yet your hips continue pounding the girl as if they had a mind of their own. Her legs grab onto your waist as she lifts herself off the ground and into your arms with newfound strength. She closes her eyes for a moment, then opens them with an almost desperate glare. \"<i>More!</i>\" she demands hungrily. Her previously ocean-blue eyes have turned into little neon pink pills of lust set on tableaux of darkness that used to be her white sclera. Looking into those eyes, you feel like you're only too happy to oblige her request.\n\n"); outputText("You fuck her powerfully, the sweat dripping from your bodies mixing with each other as she does her best to rub herself on you, sending shocks of electric pleasure racing through both your bodies; the imps watch rapt, masturbating openly to the show you're putting on. With a groan and a powerful piston, you reach your second climax; this in turn triggers yet another orgasm within the girl.\n\n"); outputText("Once again you're unable to stop your rabid pounding as the girl screams and her skin turns a light purple. Neither of your unholy lusts sated, you fuck each other again in earnest, your thick demonic cock pounding into her abused fuckhole and pushing out little squelches of semen, while she gyrates her hips to coax more out of you to take its place. The vicious cycle continues for many orgasms; each time you cum into her, she loses another part of her humanity to become more demon-like. First new horns grow on her head, then her hair turns as pink as her irises, elongating to reach her lower back. Her hands develop black claws that she uses to scratch at your skin, her feet growing demonic heels to further complete her lewd mien. Her butt inflates and her breasts enlarge, filling out and giving her an hourglass figure most girls back in Ingnam would kill for; the clamps on her nipples break apart as they grow in size and milk explodes from their tips to join the pool of mixed fluids that's formed under the two of you.\n\n"); outputText("Her tongue grows serpentine and undulates hypnotically, and she puts it to good use by invading your mouth and throat to leverage you into a wet french kiss. Finally, with one last desperate thrust, you pump her with the final load of cum that completes her transformation. Large bat-like wings sprout from her shoulders and a spade-tipped tail bursts from above her ass. She closes her mouth around yours and screams in ecstasy as she finally releases you and slumps to the ground, panting. You follow in suit, dropping on top her and resting your head on her breasts.\n\n"); outputText("She strokes your head, giggling, \"<i>I hope you enjoyed our little tryst, [Master]. Lady Ceraph wasn't lying when she said you were one hell of a fuck.</i>\" You lift your head in surprise; did she become a demon on purpose?\n\n"); outputText("\"<i>No, silly!</i>\" she responds, seemingly reading your thoughts. \"<i>I've been a succubus for years now. It's just that I find the idea of being subdued and converted into a sex machine so hot... mmm... you can thank mistress Ceraph for this particular fetish,</i>\" she says, turning her head to the side to show you a small glowing black stud on her ear.\n\n"); //(if PC's dick is not demonic naturally) if (!demon) outputText("You lift yourself off her and sit in the dirt; she grins and slowly crawls toward you to take your demonic prick into her mouth, sucking with so much pressure you fear she will swallow your cock whole. Slowly, you feel something trickle out of your sensitive cock and into her mouth, then she pulls away with a <b>POP</b>. \"<i>This should take care of the medicine, [Master].</i>\" True to her word, you watch as your cock slowly reverts its coloration"); //[(if PC didn't have a cock) if (!demon && !player.hasCock()) outputText(", then the temporary phallus shrinks and disappears back into your crotch"); if (!demon) outputText(".\n\n"); outputText("She smiles at you seductively, licking her lips. A slapping sound along with multiple pants and gasps catches your attention; both you and the succubus look around for its source. The imps that brought the succubus for you are still masturbating furiously. She looks at you with an eyebrow raised and says, \"<i>There is only one more thing you have to do to completely subdue me. Order me to pleasure those lowly imps.</i>\"\n\n"); outputText("Do you?"); player.sexReward("vaginalFluids","Dick"); dynStats("cor", 5); //[Yes][No][Never Again] simpleChoices("Yes", acceptMoreCeraphFauxCorruption, "No", declineCeraphFauxCorruption, "", null, "", null, "Never Again", iQuitCeraphCorruptionDemons); } //[=Never Again - Fuck this nerd shit=] private function iQuitCeraphCorruptionDemons():void { clearOutput(); outputText("You tell her, loudly and in no uncertain terms, that you have no interest in playing make-believe with her, and that next time Ceraph can come herself or have an ACTUAL innocent brought for you to corrupt.\n\n"); outputText("Chagrined, she unfurls her wings and flies off, the imps quickly wilting and following suit."); //(disable repeat of scene) flags[kFLAGS.CERAPH_RP_CORRUPT_DISABLED] = 1; endEncounter(); } //[=No=] private function declineCeraphFauxCorruption():void { clearOutput(); outputText("You tell her you have no interest in granting release to lowly imps. If they want pleasure, then they should earn it themselves.\n\n"); outputText("\"<i>Sorry boys, " + player.mf("Master's", "Mistress") + " orders.</i>\" She extends her wings and flies away, and the horny imps follow suit, still busy masturbating. A 'pit-pat-pat' sound follows them, the noise of their pre-cum hitting the dry dirt from on high.\n\n"); endEncounter(); } //[=Yes=] private function acceptMoreCeraphFauxCorruption():void { clearOutput(); outputText("You smirk, seeing that this might be interesting... so you order her to pleasure the imps, all of them at the same time.\n\n"); outputText("The imps' eyes glow at your command, and they only stop masturbating long enough to pounce on the succubus and drag her to the ground. She just smiles, offering no resistance as the imps hurry to fill her mouth, pussy, and ass, not to mention keeping her hands busy.\n\n"); outputText("The sight is arousing; the imps tug, grope and pull at the succubus, all while brutally fucking her. The huge deposit you made inside her tight vagina splatters about with each wet slap of the imp fucking her pussy; the one inside her ass pushes brutally, as if trying to climb up her anus cockfirst; the one on her mouth makes use of her breasts whenever he pulls out; and finally the ones using her hands splatter pre on top of her, painting her purple skin white.\n\n"); outputText("The show doesn't last long, however. The imps quickly climax with echoing cries. The one using her mouth cums so hard that some ejaculate backflows out of the succubus' nose. The ones using her ass and pussy fill their respective holes, pulling out in the last spurt to paint the succubus' body in spooge. Her hands, of course, complete the job by painting whatever was left with the last two imp dicks. By the end of the ordeal, the succubus is coughing and sputtering.\n\n"); outputText("\"<i>Look at what happened to me... used and transformed, then forced to service a bunch of dirty imps... Thank you, [Master],</i>\" she moans with a lewd smile.\n\n"); outputText("Licking the cum off her body, she sashays towards you to give you a little peck on the cheek. \"<i>Hmm, you're such a good [Master], I might have to leave Ceraph's harem and join yours instead. See you around, hot stuff.</i>\" She rounds up the tired imps and extends her wings, setting off alongside them."); dynStats("lus", 5, "cor", 2); endEncounter(); } //(not optimized in any way for centaur) //(should probably add a cock-limit of like, whatever you want, cuz you're fucking her butt) private function sweetieNOOOO():void { spriteSelect(SpriteDb.s_marble); clearOutput(); //requires PC to have Marble as follower or have removed Marble from game via rape attempt and confrontation outputText("\"<i>Aaaah, not satisfied with me, [Master]?</i>\" Ceraph huffs, feigning exasperation. She pointedly runs a hand along her muscular thigh, up her taut belly, and around one of her perfectly-formed lilac breasts. \"<i>And what did you have in mind for our... playtime?</i>\"\n\n"); outputText("After taking a moment to form your thoughts, you begin describing a tall country-style girl, with huge breasts and an aptitude for pet names. Ceraph cuts you off with a high-pitched cackle, and she actually slaps her palm against her forehead in her excitement. \"<i>Marble?</i>\" she asks between bouts of laughter. \"<i>You want me to turn into that cow? Oh, [Master], but you surely are a mystery to me.</i>\" A sharp stare from you cuts off her reverie, and she sobers instantly, going so far as to cringe. \"<i>My apologies, " + player.mf("sir", "madam") + "... your wish is my command.</i>\"\n\n"); outputText("First, she gestures once again at the environment, changing from a mountainous terrain to the inside of... Whitney's barn? Sure enough, you look past her and see a milker "); if (player.hasKeyItem("Breast Milker - Installed At Whitney's Farm") >= 0) outputText("similar to the one you got from the factory."); else outputText("not too different from the ones you've seen in Ingnam, although modified for human use, it seems."); outputText(" Any more exploration of your environment is put on hold as your gaze falls back to Ceraph. Her latex ensemble shimmers and slackens, the strategic peep-holes closing up with unremarkable cotton. The material reforms until she's left with a pair of overalls and a button-up blouse that are both at least four sizes too big. "); //([if first time] if (flags[kFLAGS.CERAPH_RP_MARBLE_COUNT] == 0) outputText("Seeing your confused stare, she simply answers with, \"<i>Ah, do be patient... sweetie,</i>\" and goes back to her work."); else outputText("You simply chuckle knowingly at the apparent size disparity of the garment."); outputText(" She reaches up and takes a tentative grasp of her curved, demonic horns, straightening and molding them into more bovine models. The spade-tip of her tail shrinks, then puffs out with hair, and the whole appendage droops as it becomes remarkably more cow-like. Almost as an afterthought, she paces up to you and slowly strips you of your [armor]. She teases " + oMultiCockDesc() + " a bit before gliding back to her previous position.\n\n"); outputText("With a wink to you, Ceraph raises her hands, pinching the center of her left palm into a sharp syringe-like tip, then repeating the motion with her right. Meticulously, she unbuttons her oversized blouse, lets her overalls drop to her waist, and releases a steadying breath. She cups her breasts, lining the points up with her stiff, quivering nipples, and plunges them in, groaning excitedly in both pain and arousal. Bulges form at her forearms, working their way down into her waiting hands. The bulges, you discern, treat her new needle-palms as a funnel; they shrink and disappear from her arms as their mass is transferred to her breast. A significant surge of growth in her squashed bosom supports the theory, and Ceraph winces in ecstasy from the feeling. The new volume makes audible sloshing sounds. More bulges begin, traveling in waves toward her waiting bosom. Although already quite ponderous, the omnibus' former bust pales in comparison to the still-swelling rack she's pumping full of fluid. The flesh begins pushing into her arm-cradle and the growth goes on until finally coming to a rest at roughly HH-sized measurements. She retracts the tiny spikes from her suddenly and ponderously larger nubs, leaving only a dribble of - milk, it must be - in their wake. The demoness struggles to pull her blouse over her bloated boobs, eventually managing to button it with a good amount of strain.\n\n"); outputText("Ceraph plops down onto her beautiful bubble butt, removing her boots and grabbing up one of her feet. She palms the demonic high-heel and pushes, a sharp crack accompanying the retreat of the bone back up into her foot. She mirrors the process with the other, then begins massaging her perfectly normal feet roughly. Her applications widen and shorten the extremities, shaping them into the cloven hooves of a cow. She shudders, her knees knocking together as auburn fur sprouts from the bottom of the thigh down to her new hooves. Ceraph attempts to stand, wobbling a bit. \"<i>Getting used to hooves with no heel support at the same time... tricky,</i>\" she muses, regaining her footing on her now-digitigrade legs. \"<i>Moving on...</i>\"\n\n"); outputText("The increasingly cow-like omnibus takes a grip on either side of her hips and, with an ecstatic cry, tugs outward, widening her hips and throwing her gait off even more. She sticks her thumb into her mouth and blows, and though you suspect that's simply for theatrics, her thighs thicken and her butt plumps up, filling up her overalls perfectly. Ceraph reaches up and pinches her own cheeks, rounding her angled features off into a more rounded, softer visage. With a snap of her fingers, a blossom of creamy-colored skin starts at her nose, running along her face and down her neck, enveloping the previously purple hue. "); //([if real Marble has cock] if (flags[kFLAGS.MARBLE_DICK_LENGTH] > 0 && flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText("Her nubbly member presumably shifts its color from royal purple to a lighter, brownish tone as well, inflating to the familiar seven-inch measurement; at least, so you'd judge by the sudden bulge in the overalls. "); outputText("A ruffle of her hair sparks a similar coloration shift to the same brown as her leg fur, and the black of her eyes shift to whites with brown irises.\n\n"); outputText("\"<i>One last touch,</i>\" she moans as her whole frame begins to jostle about. With a shake, her entire body leaps up a couple inches in height, and another, and another until she's roughly the same size as that familiar cowgirl."); if (flags[kFLAGS.CERAPH_RP_MARBLE_DISABLED] == 1) doNext(postUdderChoice); else { outputText(" \"<i>Now then, [Master]... or, should I say, Sweetie,</i>\" she breathes, her sultry tones smoothing into an earthy, slightly drawn-out accent, \"<i>there's one more detail that she - sorry, I - don't have; would you like me to have... an udder?</i>\"\n\n"); outputText("The question strikes you as a curious one. Do you want your make-believe Marble to make an udder, or is she better off without?"); //[yep] [no way jose] simpleChoices("Udder", yesUdderPWEASE, "No Udder", noUdderPlz, "Never Udder", noUdderPlz, "", null, "", null); } } //[in a pig's eye, pal] private function noUdderPlz(perm:Boolean = false):void { clearOutput(); spriteSelect(SpriteDb.s_marble); if (perm) flags[kFLAGS.CERAPH_RP_MARBLE_DISABLED] = 1; outputText("A sharp head-shake is the only declination she needs. \"<i>Of course, Sweetie, that wouldn't be very... Marble-like, would it?</i>\"\n\n"); flags[kFLAGS.CERAPH_UDDERS_DISABLED] = 0; postUdderChoice(); } //[of course honey-buns] private function yesUdderPWEASE():void { clearOutput(); spriteSelect(SpriteDb.s_marble); outputText("A brightening of your eyes and a slight part of your lips clues her in to your answer. She pulls her blouse up over her belly, tucking it into her cleavage to keep it out of the way. As you watch, Ceraph pinches two spots right above her belly button, and she moves her fingers away to reveal... nipples! She repeats the process a few inches lower, then frames the four nubs with her thumb and forefinger, taking a deep breath in anticipation. The demoness flexes her belly muscles, and a familiar bulge pops up, nipples lengthening to match. Liquid can also be heard splashing around her pink protrusion, and she can't help but give the thing a little slap. Both of you delight in the subsequent jostling and splashing of the milk inside. Her cheeks bulge with exertion as the milk-sack grows, burgeoning larger and wider with more and more milk before finally flopping heavily down above her crotch. She sighs in relief, then slips her top back over her new udder, taking apparent pride in the four small stains forming in the fabric.\n\n"); flags[kFLAGS.CERAPH_UDDERS_DISABLED] = 1; postUdderChoice(); } private function postUdderChoice(newl:Boolean = false):void { spriteSelect(SpriteDb.s_marble); if (newl) clearOutput(); outputText("That out of the way, she pulls her overall back over her shoulders and turns her back to you, waiting several seconds before turning around. \"<i>Sweetie!?</i>\" she exclaims in horror, eyes wide and arms flung in front of her as she cowers from you. \"<i>What-... what are you doing...</i>\"\n\n"); outputText("'Marble' backs up, tripping over a bucket and falling onto her spacious ass. \"<i>Please, don't hook me up to that milker, sweetie... anything but that!</i>\" An evil smirk graces your lips as you catch up to her intention; you regard the cowgirl omnibus, her face a mask of terror and her body all a-tremble. She manages a small squeak of terror as you approach and take a handful of her voluminous hair, dragging her over to the indicated stall. Her blubbering sobs don't cease as you ready the equipment"); //([if udder] if (flags[kFLAGS.CERAPH_UDDERS_DISABLED] == 1) outputText(", making sure to prep four extra tubes for her udder"); outputText(". You idly reach over and rip her strained blouse right off, sliding the overall straps off her shoulders and exposing her massive HH-cups. Despite her protests, her sunken nipples quickly snap to attention, milk leaking freely from the excited things. You reach over and flick the machine on, dragging 'Marble' across to it. You're aware of the actual cowgirl's fear of bondage, so you take great pleasure in chaining her understudy's hands to two overhanging shackles and dangling the two cups in front of her huge tits. The suction is just strong enough to draw her nipples towards the hoses. Her scream of protest is stifled by a strangled cry as you jam the two cups home, the machine instantly kicking in."); //([if udder] if (flags[kFLAGS.CERAPH_UDDERS_DISABLED] == 1) outputText(" The four others quickly follow, the udder-cups sucking onto the nubs like hungry children."); outputText("\n\n"); outputText("Marble's entire frame is jostled with each alternating piston of the milkers, her eyes rolling back from the feeling of the rough milking. \"<i>S-stop,</i>\" she pants, thighs twitching in barely-suppressed arousal. You laugh as you raise her to her hooves, leaving her bent double with her bosom and its attachments nearly brushing the ground. Her cow-sized butt is raised in front of you and swaying from side to side from her pent-up arousal. Slowly, drawing out her high-pitched groans of protest, you slide her overalls down over her posterior, letting them drop to the floor. Despite her continued pleadings, you ease your pointer and middle fingers into her dripping cunt, eliciting a gasp from the tied-up cowgirl. \"<i>Please, d-don't... my vagina...</i>\" she moans, struggling in vain against her bindings as she tries to shake you away from her. Marble's resistance only makes your [cocks] harder, however, and you're about ready to punish her for her impudence.\n\n"); outputText("You sink your fingers into Marble's butt flesh, jostling and kneading her rump like stubborn dough. The bound-up bovine wiggles around, her arousal slowly enervating her natural disgust for such treatment. Before long, her leaky fuck-box upgrades to a veritable downpour of fem-spunk, and her babble of protests is intermittently interrupted by a \"<i>Fuck me!</i>\" or a \"<i>Please, champion...</i>\" A cackle rolls out of your throat as you regard your nearly mind-broken cum-slut. With a particularly evil plan in mind, you grab up " + oMultiCockDesc() + " and line it up with her tight pucker. It's anal time! \"<i>No, sweetie, no!</i>\" she pleads, trembling enough to cause a minor boobquake against her still-pumping milkers. You pause, going so far as to release your grip on the cock, and she heaves a sigh of relief. Before she can even finish the exhalation, you dangle your newest find in front of her eyes; a large funnel, complete with a tube. Her protest is interrupted when you jam the funnel down her throat, stopping just short of suffocating her. Tears well up in her eyes as you produce another nearby accommodation: a flagon of a thick, creamy substance. Judging from the potent smell, it's minotaur cum... and fresh, too. Addictive fluid... well, perhaps she needs a taste of her own 'medicine'.\n\n"); outputText("She can be <b>your</b> slave, for once.\n\n"); outputText("Marble's eyes bulge as you begin pouring the cum-container into the funnel, filling it up to the brim with mino-spunk. Reminiscent of an overzealous squirrel, her cheeks puff as the semen filters down her throat and flows back into her mouth. With no outlet other than her stomach, she's forced to swallow the offending liquid, tears streaming down her face freely at your treatment. You merely laugh and roughly squeeze her cheeks, causing her to momentarily choke on the stuff and dribble a bit out of the corner of her mouth. Satisfied with the progress, you move back behind her wide-set booty and spread her cheeks once more. Muffled screams aside, her exposed butt is all the invitation you need. Once again snatching " + oMultiCockDesc() + ", you prod her a few times before simply jamming it in, taking perverse pleasure in her suddenly higher-pitched screams. Remarkably, her anus yields to your penis in a wonderful way; not loose by any definition, but certainly not even impeding your progress. You wonder how faithful Ceraph's representation is to the source material; are cowgirl colons such wonderful things? Your crotch smacks against her luscious cheeks, and you waste no time in drawing back through her depths and ramming it home once more.\n\n"); outputText("Marble, nipples reddened and elongated by the constant, ever-present milking and belly swollen from the minotaur seed she's still being forced to swallow, hums throatily. Her mind must be completely gone, by now... she's your sexual tool, your slave, your fucktoy, and she's gone from protesting to outright encouraging it. Her hips pump in time with yours, her sexual fluid spattering the front of your legs with the sheer amount of it. Under such a willing, perfectly accommodating colon like this, you're not long in feeling "); if (player.hasBalls()) outputText("your [balls] tightening"); else outputText("a readiness in your body"); outputText(", and you wind up for one last thrust into her depths. "); var cum:Number = player.cumQ(); if (cum < 50) outputText("Her ass has no problem in taking your ejaculatory package, lapping it up like it was nothing."); else if (cum < 250) outputText("She groans a bit from the amount of seed you pump into her butt, but she doesn't seem overly concerned by it."); else if (cum < 750) outputText("Her belly actually bulges out a bit more as you shoot your sperm into her perfect butthole, but her only response is an approving grunt."); else if (cum < 2000) outputText("Normal girls might not be able to take this much cum at one time, but 'Marble' simply bucks her hips happily as her belly is stretched as least as large as her boobs to make room for the load."); else outputText("Her entire body writhes in ecstatic bliss as your gigantic load pumps into her, wave after wave of baby-batter inflating her gut so full of cum. By the time you're done, her navel is an outtie; what's more, it's actually scraping the barn floor, and if her arms were free, you don't doubt she'd be rubbing happily at it."); if (cum >= 10000) outputText(" Marble's body convulses so hard it actually dislodges the funnel, dragging the tube free of her mouth. \"<i>SWEETIE!</i>\" she screams, grinding herself against you as her stomach burgeons forward, filled with enough seed to propagate an entire city of goblins for months. \"<i>MORE!</i>\" You're able to give her just that, bloating her billowing belly obscenely, stretching the creamy skin to its near-breaking point with your virility. Even if you wanted to pull out, you couldn't, not with her anal walls clamped onto your [cock] like this. Her belly actually gains enough mass to nearly fill up the stall, pushing her tits up into her chin."); if (player.cockTotal() == 2) outputText(" Your other cock sprays "); else if (player.cockTotal() > 2) outputText(" Your other cocks spray "); if (player.cockTotal() > 1) { outputText("a "); if (cum < 50) outputText("gentle"); else if (cum < 250) outputText("generous"); else if (cum < 750) outputText("heady"); else if (cum < 1500) outputText("wild"); else outputText("massive"); outputText(" amount of semen all over the nearby stalls and equipment"); if (cum >= 250 && cum < 1000) outputText(", spattering the entire area"); else if (cum >= 1000 && cum < 3000) outputText(", drenching the area in white"); else if (cum >= 3000) outputText(", coating the area in a thick sheet of alabaster"); outputText("."); } outputText("\n\n"); outputText("Finally spent, you free yourself of Marble's butt and straighten, moving to the side to take in just how far the cowgirl has fallen. The milkers' storage tanks are fit to bust from the amount of cream your cumslut has pumped into them, but Marble herself is staring at you with heavy-lidded eyes. You don't even remove her restraints, just dismissively press a foot into her gut"); if (cum >= 2000 && player.cor >= 66) outputText(" and chuckle at the drizzle of semen that issues from her butt and mouth"); outputText(". After a few more moments of observation, you turn away, planting your hands on your hips victoriously. You simply thank the cowgirl, and she responds with a satisfied moan. Suddenly, a massive splashing sound - as if gallons of liquid were suddenly released - reaches your ears, and the barn shimmers and fades into the familiar setting of your camp. You feel a hand on your shoulder, and you glance down to see a creamy-colored hand, veins of purple creeping along the surface and inching up her fingers. \"<i>Thank you, [Master],</i>\" Ceraph replies amiably, tittering to herself. \"<i>You've got some kinks to work out, don't you? I like that.</i>\"\n\n"); outputText("Her grip fades, and you turn around to see... nothing. She's simply gone, vanished without a trace. No... not without a trace, you realize. Right near where the milker used to lie sits a lone cowbell, lying in a pool of what you can only assume to be cum. You reach for it, but it disappears as well, turned into a small puff of smoke and dispersing with the wind. \"<i>Bye, sweetie,</i>\" the disembodied voice of your demonic slave whispers into your ear, mocking tones interspersed with a promise of further pleasure."); //end (stat changes?) player.sexReward("vaginalFluids","Dick"); dynStats("lib", 1, "sen", -5, "cor", 3); endEncounter(); } //NOTES: //Ceraph roleplay. [Dominika] option. There is text for the first time you do it, then transformation text that is intended to play at the front of every scene. //After that is a scene tailored more specifically for the PC. Intention is to give nagas and centaurs and all that their own scene. Currently only scene is for PCs with a dick - should be naga-compatible. private function cerminika():void { spriteSelect(SpriteDb.s_uncloaked_dominika); clearOutput(); //[first time] if (flags[kFLAGS.CERAPH_ROLEPLAY_AS_DOMINIKA_COUNT] == 0) { outputText("\"<i>Who?</i>\" Ceraph asks.\n\n"); outputText("You explain about the dark-lipped witch to your demon whore. \"<i>Mmm, tattoos, that's gonna be rough,</i>\" she muses, licking her lower lip in thought. \"<i>Think about her for a moment?</i>\" You were already thinking of Dominika given that you were explaining who she was to Ceraph, but you suppose dealing with her idiocy is the price you pay for the sex. Still, you acknowledge that you are. Ceraph places her hands on your forehead and closes her eyes for a few moments, before purring and grinning. \"<i>Oo, she's cute. Ask her if she likes piercings.</i>\"\n\n"); } outputText("Taking a deep breath, Ceraph closes her eyes. When she opens them again their darkness has been replaced by bright white sclera, and brilliant blue irises. Starting at the roots her hair brightens and blondes, pulling itself up into a stylized bun. The demon's face shifts and squirms beneath the flesh, bones and muscle settling into subtle differences and adapting the cabalist's features. Eyelashes adjust and shrink, losing the excessive glamour of the demonic and gaining a more down to earth and natural appearance. Throughout the process her skin gradually shifts in hue to a more tanned shade, now resembling a color someone could actually be born with.\n\n"); outputText("Her figure retracts somewhat, growing slighter and shorter. Previously obscene breasts diminish in size, and Ceraph removes her outfit to prevent undue damage. Before your eyes her areolae shrink and change, nipples becoming positively petite. Arms slender, shifting to a physique more expected of a sorceress. Her demonic heels pull into her feet, the soles paling far more than the rest of her skin. Amusingly, her ass plumpens somewhat, achieving the jiggle of the non-athletic. Between her legs Ceraph's pussy becomes dignified and neat"); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" while her cock shrinks to what looks approximately like six inches of meat, an outright tiny penis for Mareth"); outputText(".\n\n"); outputText("Though much of her shrinks, her lips grow. While unsurprising, it remains very enjoyable to watch. Her lower lip rounds and swells, while her upper grows further defined. Like a bruise, they darken, until no color but a glossy void remains. As though they were being drawn directly into her skin, the lines of her tattoos begin to spread, starting from a single circle across her breast until the latticework of ink covers her tanned body.\n\n"); outputText("Dominika stands before you, nude and unrestricted. She licks her lips slowly.\n\n"); outputText("\"<i>Champion,</i>\" those dark lips purr, \"<i>You have done everything I could have asked you for.</i>\" She runs a hand along your cheek, stepping in close and caressing your arm. \"<i>I owe you more than I can express.</i>\" Her hand roams up into your hair, brushing through it before cupping the back of your head. Dominika pulls you into a deep kiss, pressing her lips to yours in a breath-stealing passion. Her tongue rolls into your mouth as though it intends to steal yours away, her leg eventually rising up and curling around you."); //[CERAPH COCK: if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" Her dick presses up into your crotch."); outputText(" \"<i>I dare say,</i>\" she purrs between the kiss, pressing her forehead to yours, \"<i>You may have seduced me, champion.</i>\"\n\n"); outputText("Pressing her hands on your shoulders she eases you down, straddling your lap. \"<i>I linger in chastity out of fear that my dignity shall be taken from me in this land,</i>\" she purrs softly, tracing her hand across your chest. "); if (player.biggestTitSize() >= 0) outputText("She casually and playfully gives the gentlest squeeze to your " + chestDesc() + ". "); outputText("\"<i>But if I can rely on you – perhaps I do not need to worry.</i>\" She pulls your [armor] away, letting her hands roam hungrily across your body. Blatantly turned on, her pussy rubs its juices against your crotch"); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(", and her prick has remained firm and hard"); outputText(". Her tongue roams hungrily over her inky lips, and an almost predatory grin sets across her features as she pulls up your [cock]. Her fingernails cup under your head delicately and carefully tease you, rubbing her palm into the underside of your shaft.\n\n"); outputText("\"<i>How long,</i>\" she purrs, \"<i>Have you wanted to really be inside me?</i>\"\n\n"); outputText("Dominika slides her body back, rubbing the softness of her folds against your [cock]. "); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText("The very base of her prick teases the veins of your own shaft, but she seems focused on the pleasure of her cunt for now. "); outputText("She grins at you as she reaches the top of your cock, grinding back and forth across it. \"<i>Mmm,</i>\" she muses quietly, biting her lower lip for a moment. \"<i>It's been a long time since I let someone have me. I forgot just how... warm a prick can feel down there.</i>\" Her pussy casually clenches, brushing herself across your tip. \"<i>You should feel honored.</i>\"\n\n"); outputText("You grab her hips and pull her into your lap. The warmth and wetness of her pussy engulfs your shaft immediately, clinging to you incredibly tightly. She gives a surprised noise at the sudden aggression, placing her hands on your belly. The holier-than-thou act is cute, but you're here to fuck and no amount of preening is going to keep you from that. \"<i>I-I see that you've longed for this as well!</i>\" she gasps out, attempting to keep some dignity while her cheeks flush."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" The degree that her cock abruptly shoots straight up is perhaps the most amusing part of the act."); outputText(" You simply smirk at her, starting to bounce her into your lap and shoving your [cock] deeper inside. Once more she bites her lip, fingers digging into your stomach. No matter how classy she wants to appear, you can quite easily feel how wet she is"); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(", and the heat of her prick bouncing into your lap"); outputText(". \"<i>Hey,</i>\" she gasps, \"<i>Don't you want to savor it?</i>\"\n\n"); outputText("You slap her tit.\n\n"); outputText("The inability to frame her expression and hang it on a tree in your campsite is the greatest injustice the world has ever known. Her black lips sit in a stunned part as she stares at you, even as you hump away at her sopping mound. She blinks a few times, shakes her head once, the entire disbelief package. Eventually her hands slide down her side to find your own, rubbing over your fingers as they hold her hips. Then, sharply and surprisingly painfully, she digs her fingernails into your wrists, forcing you to let go. \"<i>No,</i>\" she says with a wicked grin as she brings your hands to the side of your head, leaning forward and slowly undulating her hips in your lap. \"<i>Really. Enjoy me.</i>\"\n\n"); outputText("You give her a carefully crafted retort that demonstrates your intellectual superiority, but she just gives you a fake smile and pats your cheek. Eyes half-closed she slowly slides herself along you, enjoying the sensation of each inch of your [cock] as it brushes along her walls. \"<i>Mmmm,</i>\" she lets herself purr out, \"<i>Worth... the wait.</i>\" Her toes curl slightly, one of her legs shifting back slightly to alter the angle you enter her at. It seems to work how she wants it to, as a deep, satisfied breath accompanies the next downward slide of her hips."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" A single bead of pre-cum forms slowly at the tip of her prick, growing larger until it finally slips down into the curve of her head, sliding down her shaft and into your lap."); outputText(" She brushes her hair back behind her ear, sitting up straighter. In her quest to indulge in and feel your prick against all the warm flesh inside, she's neglected to keep you pinned.\n\n"); outputText("Grabbing her shoulders, you surprise her once more by twisting and rolling on top of her. \"<i>No!</i>\" she shouts immediately, knowing your plot, \"<i>You " + player.mf("bastard", "bitch") + "! No one puts me on my own back!</i>\" You remind her that facts need more proof than the assumption that things will never change. She spits at you, but you take solace in the fact that your hands are over her wrists and your [cock] is shoved so deep in Dominika there's a chance she could spit up cum when you're done rather than swallow it. Presuming, of course, that her vagina is connected to her stomach, which it probably is not.\n\n"); outputText("Yet. You haven't decided what you'll make her put in her mouth now that she's here.\n\n"); outputText("\"<i>F-fuck!</i>\" Those dark lips manage to stammer out, \"<i>Stop fucking me! Let me ride you, you piece of shit!</i>\" She manages to pull her hands free from the grip you have on them, only to beat on your chest a few times and push futilely against it. "); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText("Her prick bounces between her belly and yours as you take her. "); outputText("For your part you have no interest in slowing down, gripping back onto her hips and pounding away at the delightfully tight cunt presently dominated by your [cock]. More in charge than you were before, you have a chance to truly appreciate the sensation of her labia being shoved apart for your needs. Absolutely soaked with her needy juices, it's easy to penetrate the sorceress. Forcing so much of her sopping nectar out is making a terrible mess of her thighs, but given how stuck up she's been about finally letting you take her, she could stand to get a little messy. Her fingernails claw at your collarbone"); if (player.biggestTitSize() >= 1) outputText(" and slap at your own chest"); outputText(", hissing bloody murder while at the same time trying not to groan so much that she completely reveals how much she's enjoying having you piston away into her nethers. In that regard, she is failing.\n\n"); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText("A light spurt of pre-cum from her prick warms the flesh where your hips meet. "); outputText("Slowly her fingers trail up to your shoulders, gripping you tightly and gritting her teeth as you thrust. Sweating and grunting in tempered exertion from the pounding you put her through, the bun in her hair begins to fall apart. Some of her blonde locks cling to her forehead. Her legs curl around you, rubbing against your body and clenching with each strangled gasp coming from her dark lips. The backs of her heels dig into your backside, rubbing in as she pins you closer. You think little of it, until you attempt to take a deep thrust only to be rudely tugged back in by her feet. Gripping you tighter with her hands and holding onto the back of your head, she hisses happily, rocking her hips against you to feel your [cock] shift inside. \"<i>I said enjoy me,</i>\" she hisses wickedly, licking her ebony lips and casually nipping at you. \"<i>Stay here, " + player.mf("handsome", "gorgeous") + ".</i>\"\n\n"); outputText("You had no intentions of letting her control the pace before, and you aren't interested in letting her do so now. Feigning acceptance of her authority for now, you allow her to settle you into a tight, intimate thrusting. You pierce into her damp mound, deeper and deeper, letting her inner walls squeeze you harder than her hands. Holding onto Dominika's back, you wait for the perfect moment. The right shortness of breath, the proper shudder that rocks through her body. It arrives, her eyes half-lidded as she gazes past you with a gasping moan, and you seize the opportunity. A sorceress' grip is only so strong, and it takes a single firm movement to break her hold on you, pulling out in the process. Her eyes open quickly, recognizing that you're doing something, but she's too late to stop you. You grab her wrists and spin her in place, forcing her face and those dark lips into the dirt."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" You can practically hear her rock-hard cock kicking up the ground."); outputText(" \"<i>What the fuck are you-</i>\" she begins, before shouting \"<i>Don't you DARE!</i>\"\n\n"); outputText("Grinding your prick between her dusky cheeks, you had already decided that you very much dared and didn't particularly care about her inevitable protests. You calmly taunt her and her helplessness, pushing your fingers into her blonde locks as you hold her down and completely destroy any semblance of a nice, ordered hairdo. \"<i>Stay away from my butt!</i>\" she eventually explicitly shouts, ruining the mystique of intruding upon it.\n\n"); outputText("\"<i>No,</i>\" you respond.\n\n"); outputText("It's surprisingly easy to spear yourself into the cabalist's plush posterior. You had expected a woman of her nature to be tighter than she is, but the pussy juices soaking your [cock] are sufficient for a slippery and enjoyable entry. She grunts and gasps dissatisfaction, but there's a deepness in her breath that betrays the excitement building within. At the same time, she seems curiously nervous, and shakes not just in pleasure.\n\n"); outputText("\"<i>P-please,</i>\" she stammers out, even as her asshole clenches around you. Though it was easy to force yourself into Dominika's puckered button, you're impressed at how well her colon squeezes your shaft. There's no blown-out anal whore here, just a petite fucktunnel the perfect size to be broken by your [cock]. You part aside her bunghole, claiming her ass in your name – colonizing her colon. The entire reason those cheeks exist is cushioning for your crotch as you pound away at her, the juices her cunt left on your cock squirting out as your prick dominates every inch of those fleshy walls. \"<i>Please,</i>\" she gets out again, \"<i>I've held out... so long...</i>\" She turns her head to look at you. Tucked just behind the part of her hair, two small horns push from her skull. A moment of confusion takes you, before it is replaced by a knowing smirk. Jeering at the corrupted sorceress, you mock her inability to defend herself. Without her chastity belt to protect her from the pleasure of the demon realm, it is free to feed upon her body and devour what purity remained, leaving behind just another succubus. \"<i>Don't... make me cum,</i>\" she gasps.\n\n"); outputText("Under most circumstances you would have no opposition to denying a slut like her an orgasm, but considering the precipice she dangles over, you don't feel bad giving her a push. Your [cock] continues its obscene assault on her backside, splitting her juicy cheeks to either side as you bend her guts to your dick's will. Dominika lets out a moan that seems as though she may have intended it to be a scream of frustration, but her body is too far gone into pleasure to protest. Like ink running through paper a deep dark purple begins to spread from her tattoos. The color runs into itself and grows larger, leaving behind no lines where it joins. The tan of her skin begins to disappear under the corruption. \"<i>You " + player.mf("bastard", "bitch") + ",</i>\" she pants, shuddering as the horns grow larger. \"<i>You would destroy my humanity... just for your pleasure?</i>\"\n\n"); outputText("\"<i>Yes,</i>\" you answer calmly.\n\n"); outputText("She wails in mixed frustration and pleasure, juices splattering against the ground as her hungry cunt grows hornier. A darkness overtakes her eyes, and her nails grow long and sharp, and through it all your [cock] continues to degrade her ass. As though a heartbeat pumping blood through her body, each thrust spreads the color over her skin a little more. Her feet push and scrabble lightly against the ground in tormented frustration, but she is helpless beneath you. You go without stopping, only slowing when wings unexpectedly burst from her shoulder blades, dark and starry.\n\n"); outputText("Grabbing your sorceress-cum-succubus fucktoy firmly around the hips, you go upright, lifting her off the ground and bouncing her against your body. Moaning and squirting her juices against the ground, Dominika lifts her legs to help you, swelling indigo tits bouncing from your forceful thrusts."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" Her prick has become engorged and infernal, covered with abnormal bumps and veins. It practically spits up pre-cum, gurgling with a greatly increased supply."); outputText(" \"<i>Take it then,</i>\" she gasps, \"<i>Take me... j-just give me... moreeeee...</i>\" Her long nails – more slutclaws than anything else – dig into your arms as you hold her up almost painfully. Squealing ecstatically, a long demonic tongue slips past her full corrupted ebony lips, slapping against her collarbone as her eyes roll up in pleasure. Blonder and fuller, her hair naturally pulls back into an exaggerated bimbo-esque bun, and her horns have grown large and sinister.\n\n"); outputText("Satisfied with the ruined chastity of the former scholar, you wrap your arms around her hips and give a few final gut-wrenching slams into her dominated pucker. Each one makes her squeal and gasp, and each one brings you one step closer to the shuddering eruption that is that slut's purpose. Groping one of the whorish slutbags on her chest, you hold her to your body not out of intimacy, but dominance. There is no mistaking your absolute control over her as the first thick blasts of cum spew into her abused ass and clog her cockhole. Whimpering and clutching at you, all she can do is squeal and gasp your name, spitting your praises for destroying her dignity."); //[Player has large cum production: if (player.cumQ() >= 500) outputText(" You dump loads in her as though she's an addict who hasn't fed for days, bloating and humiliating her with the sheer volume of spunk that now inflates her belly. Not as though the demon whore has much humility left to take."); else outputText(" She shudders as your [cock] fills her guts with warmth, hips seizing as she rides out her assgasm."); outputText(" Her cunt nearly waterfalls her juices, squirting obscenely as she rides out the pleasure."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" The demonic prick placed between her legs stops bouncing only because of how rock-hard it is as it spews her own filthy fucksludge across her body, splattering onto her tits and across her face. The volume of off-white cream it spews out takes even longer to finish than you do, painting her obscenely."); outputText("\n\n"); outputText("Her hands drag across your chest as she slinks off you, moaning and shaking. You shift back on your ass to sit down after the long fuck, only to smirk as she eventually crawls back up to you."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" Her own filthy jizz has already been licked clean by her hungry mouth, so as not to dirty your handsome prick."); outputText(" The demoness laps at your [cock], cleaning it of spunk, sweat, and all the various filth it accumulates, sucking and dragging her fat, midnight lips across them. Dominika purrs her happiness, her joy at being forced into such a whorish form.\n\n"); outputText("\"<i>Was that good?</i>\" Ceraph asks in her own voice, immediately ruining the illusion. \"<i>"); //[Player has huge dick: if (player.biggestCockArea() >= 75) outputText("I doubt her ass could actually take you so well, but... I wanted my [master] to enjoy a perfect asshole. Sue me. "); outputText("I hope that little slut appreciates what she's missing out on.</i>\" She laps at your dick a few more times in the corrupted cabalist's visage, eventually sitting upright and slipping around behind you to massage your shoulders.\n\n"); outputText("\"<i>That said,</i>\" she whispers in your ear, \"<i>If you get a chance to do that to that cunt, do invite me.</i>\""); player.sexReward("vaginalFluids","Dick"); dynStats("sen", -2, "cor", 2); flags[kFLAGS.CERAPH_ROLEPLAY_AS_DOMINIKA_COUNT]++; endEncounter(); } /*Ceraph's Harem: Zetsuko [Introduction] ▶[FuckVagina] requires penis ▶[GetTongued] requires vagina ▶[Banana?] silly mode ▶[Leave] [Introduction]*/ //(First Time): public function encounterZetsuko():void { clearOutput(); flags[kFLAGS.ZETSUKO_MET]++; //First time if (flags[kFLAGS.ZETSUKO_MET] == 1) { outputText("You call on Ceraph, but rather than the purple-skinned demoness you were expecting, you are surprised to see a fox-eared girl appear in a wash of corrupted violet flames. She steps out of the portal and shakes off the flames as if they are water, and you take a moment to look her over. The first thing you notice is that her arms are bound in a white straitjacket that is open at the chest, allowing her F-cup breasts to swing freely. Four large fox tails twist erratically in the air behind her, and you can see a pair of small horns poking up from her hair in front of her large triangular ears. Her body and face are covered in tribal tattoos, and her somewhat maniacal amber eyes are framed nicely by a head of messy auburn hair with black highlights. Like many of Ceraph's harem members, she is adorned with numerous piercings and studs — almost too many to count them all — as well as a large studded collar. Once you have had time to take it all in, she speaks.\n\n"); outputText("\"<i>Zetsuko apologizes for Mistress's absence, " + player.mf("Master", "other Mistress") + ". Mistress wasn't able to be here, so she sent Zetsuko instead. She hopes Zetsuko will be to your liking...</i>\"\n\n"); outputText("She punctuates her sentence with a creepy grin that shows off her oversized canine teeth, an evil gleam in her eyes hinting at an inner turmoil boiling just under the surface. As she licks her lips with an almost animalistic hunger, you see that her tongue is extremely long and sports a large stud as well. You quirk your brow at her peculiar manner of speech, but try your best to parse the information.\n\n"); outputText("\"<i>Zetsuko was wondering if [Master] could perhaps... loosen her jacket?</i>\" she says, struggling in her straitjacket a bit. \"<i>Mistress tied it a little too tightly...</i>\"\n\n"); outputText("When she turns to offer you her bindings, you spot a small note pinned to her back, and reach out to take it. It seems to have been written to you by Ceraph.\n\n"); outputText("\"<i>[Master],\n\nI'm deeply sorry that I cannot be there to serve you in person, but I have sent Zetsuko here in my stead. If you are reading this note, she has likely already tried to get you to release her bindings. Respectfully, I would advise you that under no circumstances should you oblige her request. Zetsuko has 'discipline' problems, as you may soon find out, and while my piercings suppress most of her more defiant tendencies, she has a frustratingly stubborn will. She should not be able to raise a hand against you without your consent, but that would not stop her from trying, believe me. Despite her 'difficulties,' she does have some enhancements that I think you'll really enjoy, as long as you don't fall for any of her tricks.\n\n"); outputText("Your Loyal Servant,\nCeraph\n\nP.S. Just in case she does get out, the safety word is 'banana.'\nP.P.S. Don't stick anything important in her mouth.\nP.P.P.S. Just to clarify, I mean the one on her face.</i>\"\n\n"); outputText("You give a confused blink, re-reading the last line. As you begin to wonder what it means, Zetsuko spins around and plops down on her cushy rear, looking up at you indignantly.\n\n"); outputText("\"<i>[Master] isn't going to let Zetsuko out, is [he]? Hehe... Too smart... Zetsuko is a bad girl, yes... many bad habits, trying to trick [Master]. Mistress tries to teach her, but Zetsuko has far too much fun being bad.</i>\"\n\n"); outputText("Her legs are splayed out lewdly, and at last you start to understand what Ceraph meant in her note as your eyes are drawn to Zetsuko's drooling cunt. Drooling, in this case, being literal — as you watch, an obscenely long tongue lined with studs is slithering its way out of her vagina, licking along the outer edges of her labia and dripping with what appears to be a mixture of saliva and pussy juices. Thankfully, there don't seem to be any teeth, but the way that enormous tongue is wriggling around is so disturbingly erotic that you can't seem to pull your eyes away long enough to check.\n\n"); outputText("\"<i>Is Zetsuko's pussy to [Master]'s liking?</i>\" she says, laying on her back and spreading her legs further to proudly display her freakish appendage to you, putting on a display as she begins to tongue her own clit, flicking her hood piercing gently.\n\n"); } //(Subsequent times): else { outputText("You call on Ceraph, but rather than the purple-skinned demoness you were expecting, Zetsuko appears in a wash of corrupted violet flames, turning to you with a wide, toothy grin.\n\n"); outputText("\"<i>Zetsuko apologizes for Mistress's absence, " + player.mf("Master", "other Mistress") + ". Mistress wasn't able to be here, so she sent Zetsuko instead. Zetsuko was hoping perhaps today [Master] would deign to loosen Zetsuko's bonds?</i>\"\n\n"); outputText("You tell her that you have no plans to let her loose today, which causes her to pout a little, though Ceraph's piercings seem to keep her from being actively defiant. Your eyes are drawn down to watch as her obscenely long tongue unfurls from between the folds of her pussy, slathering slick juices along the insides of her thighs in anticipation."); } outputText("Will you make use of Zetsuko now, or send her back to Ceraph?"); if (silly()) outputText("\n\nYou also remember Ceraph's note had mentioned something about a safety word... what was it again?"); menu(); addButton(0, "FuckVagina", fuckZetsukosTonguepussy).disableIf(!player.hasCock(), "Req. a cock."); addButton(1, "GetTongued", getTonguedByZetsuko).disableIf(!player.hasVagina(), "Req. a vagina."); if (silly()) addButton(2, "Banana", zetsukoBanana); addButton(4, "Leave", noZetsukoLoveToday); } //▶[FuckVagina] requires penis private function fuckZetsukosTonguepussy():void { clearOutput(); var x:Number = player.biggestCockIndex(); outputText("Your lust and curiosity get the best of you as the sight of that licentious tongue wriggling around between her legs sends a heat to your groin, blood rushing into your [cocks]. Zetsuko lays flat on her back, grinning up at you as her pussy licks itself in anticipation, and as you lower yourself down, her tongue snakes out even more, beginning to wrap itself around " + oMultiCockDesc() + " and slathering it with her saliva-like juices. Your sensitive member can feel that the surface of her tongue is covered in hundreds of tiny bumps and nubs that massage your shaft, and the multiple studs that line it rub you sensually as the bizarre organ coils around your " + cockDescript(x) + " like a snake, the very tip gently stimulating around the edges of your urethra.\n\n"); outputText("You marvel at the incredible degree of control she seems to have over her tongue, watching as it begins to stroke and squeeze along your shaft, coating you in slick saliva from base to tip. Its grip around you tightens up a bit, and you can feel it tugging you down gently, drawing your " + cockDescript(x) + " ever closer to her entrance. Her vagina lips spread open as you approach, gaping wide like a hungry mouth, and as it does so, you can see that the inner surface of her pussy has a number of soft bumpy nodules lining it in a downward spiral pattern.\n\n"); outputText("\"<i>Zetsuko can't wait to have " + player.mf("Master's", "Mistress's") + " dick in her pussy... she knows [Master] will just love it...</i>\" she says, wiggling her hips a bit as she pulls you up against her entrance, her lips sucking on the tip gently."); if (player.cockArea(x) >= 100) outputText(" You wonder just how she plans to fit you inside, but there's not much you can do about it at this point. You'll just have to trust that she knows what she's doing, crazy or not."); outputText(" As you begin to grope her enormous jiggling breasts, you keep looking down to watch as her tongue slithers along your length, stretching out across it and then squeezing tight. It begins to contract, the motion squeezing the first inch or so of your cock inside, and she sends up a moan, repeating the motion again and again, each time pulling a bit more of you inside.\n\n"); outputText("In no time at all, you "); if (player.cockArea(x) >= 100) outputText("somehow "); outputText("find yourself up to the hilt inside the strangely-textured orifice, while her tongue slides along the underside of your cock. It curls along underneath you, "); if (player.hasBalls()) outputText("slithering across your [balls], "); else if (player.hasVagina()) outputText("gently licking the outer edges of your labia, "); outputText("moving along to the back, "); if (player.hasBalls() || player.hasVagina()) outputText("and "); outputText("teasing your " + assholeDescript() + " gently. You gather up a mound of her soft tit flesh in each hand and begin squeezing along them lustfully, pushing on her pierced nipples with your thumbs gently while her tongue continues to lick and pleasure everything within its reach.\n\n"); outputText("\"<i>Ooo-oohh! " + player.mf("Master's", "Mistress's") + " cock tastes so good in Zetsuko's pussy!</i>\" she moans, rolling her eyes back as you feel her begin to \"<i>suck</i>\" on your " + cockDescript(x) + " deeply, rocking her hips back and forth. The suction inside her drooling cunt feels like one of the most intense deepthroats you've ever felt, and you forget for a moment that it's coming from her vagina until Zetsuko's loudest moan yet snaps you back to reality.\n\n"); outputText("Deciding to give the crazy slut a little payback for so rudely interrupting your fantasy, you reach down and begin to twist the studs in her nipples lightly, grinning like a maniac as her slavering cunt suddenly clenches up around you from the sensations.\n\n"); outputText("\"<i>Ahh! Yes, [Master]! Punish bad Zetsuko! More, more, please!</i>\"\n\n"); outputText("As you continue to torture her nipples, she arches her back in ecstasy and begins to buck wildly, her pussy-tongue slapping around erratically now, flinging saliva-juices everywhere. The tongue in her normal mouth is hanging out now, long enough to reach her chest, her eyes rolled back with a blissful grin on her face. You can feel your climax coming on, and apparently Zetsuko can too as she yells out between moans, \"<i>Ah! [Master], give Zetsuko your tasty cum!</i>\"\n\n"); outputText("With the way her pussy and tongue are squeezing you now, it would be nearly impossible not to indulge her request. Your " + cockDescript(x) + " twitches inside her, releasing a creamy deluge that causes Zetsuko to begin drooling from both ends. \"<i>Oooh... so good, so thick, so creamy... Fill Zetsuko up, yes!</i>\""); if (player.cumQ() <= 100) outputText(" Your orgasm ends quicker than it seems Zetsuko wanted it to, the last of your few thin streams of cum spraying into her pussy. It seems to suck on you all the harder, as if trying to dredge out just a few more drops."); else if (player.cumQ() <= 500) outputText(" You fire creamy ribbons of cum into her, feeding what seems to be a never-ending hunger for semen as her pussy clenches and squeezes you for every drop. Her tongue wraps around your member and squeezes along the length inside her to force out the remaining contents of your urethra, and a strong swallowing motion inside her vagina carries your thick load away."); else outputText(" The strong sucking motions of her cunt milk your shaft for everything it has, her pussy greedily swallowing load after load of your hot spunk. Her walls continue to milk you even as her abdomen begins to swell with the volume of your seed, growing outward into a gravid, jiggling belly. When your orgasm finally ends, Zetsuko looks like she's several months pregnant, and she has a look of utter satisfaction on her face. \"<i>NNnnnaaaaahhhhh.... Zetsuko... is full.</i>\""); outputText("\n\n"); outputText("Her pussy continues to suck on you gently as you pull out, and when your " + cockDescript(x) + " finally comes free of her bizarre lovehole, her tongue gently swirls around the lips before retracting itself inside. You back up, wondering if you should help the bound kitsune to her feet, but as you are considering this, she flashes you a crazed grin and is suddenly bathed in purple flames, disappearing before your eyes.\n\n"); outputText("\"<i>Zetsuko hopes to taste [Master] again sometime...</i>\""); player.sexReward("vaginalFluids","Dick"); dynStats("lib", .25, "sen", -5, "cor", 2); endEncounter(); } //▶[GetTongued] requires vagina private function getTonguedByZetsuko():void { clearOutput(); var x:Number = -1; if (player.hasCock()) x = player.biggestCockIndex(); outputText("Heat rushes to your groin as you stare at the outlandish appendage wriggling between Zetsuko's legs, feeling yourself becoming wet with anticipation. Seeking to entice you further, she rolls herself back, placing most of her weight on her shoulders as she curls her lower body up into the air, her tongue slithering back and forth along her thighs.\n\n"); outputText("\"<i>Pleeeease, let Zetsuko taste Mistress's pussy?</i>\" she says, grinning up at you as you approach. \"<i>She's certain her tongue can please Mistress greatly...</i>\"\n\n"); outputText("The salacious organ slithers toward you, caressing the outer lips of your " + vaginaDescript(0) + " and gently prodding your " + clitDescript() + " before receding, making what can only be described as a \"<i>come hither</i>\" motion. You take a step forward, pressing your hips up against the heavy cushions of her ass, and her tongue immediately curls toward your groin, "); if (x >= 0) outputText("wrapping itself around your " + cockDescript(x) + " and squeezing momentarily before "); outputText("heading straight toward your slit.\n\n"); outputText("As the tip begins to probe your depths, you can feel that the surface of her tongue is covered in hundreds of tiny nubs and bumps that give it an incredible texture. You can't help letting out a lewd moan as the muscular organ pushes yet deeper still inside you, flexing and contorting into various shapes to augment the intense sensations.\n\n"); if (x >= 0) { outputText("In a somewhat impressive feat of contortion, Zetsuko brings her feet in toward her groin to stimulate your [cocks], lifting "); if (player.cockTotal() == 1) outputText("it"); else outputText("them"); outputText(" up using her toes and stroking along the underside of the shaft"); if (player.cockTotal() > 1) outputText("s"); outputText(" with the soles of her feet. Her toes are surprisingly dextrous, able to curl around and grip your " + cockDescript(x) + " lightly, gently pinching and tugging at the skin just under the head and manipulating your throbbing member"); if (player.cockTotal() > 1) outputText("s"); outputText(" almost as skillfully as if she were using her hands!\n\n"); } outputText("You slide your hips forward, curling her body back further and resting your weight on the pillowy cushions of her bottom, riding down onto her tongue and shivering deliriously. You can feel it plumbing your depths, slithering into you and filling every nook and cranny as it swells and flows along your walls to take up every last bit of room you have. The degree of control she has over it is simply incredible, becoming thicker to stretch your " + vaginaDescript(0) + " and then suddenly retracting to swirl itself into a spiralling tendril that drills your hole lewdly.\n\n"); outputText("\"<i>Oooh, Mistress's pussy is delicious!</i>\"\n\n"); outputText("Grabbing hold of her thighs, you begin to rock yourself back and forth across her tongue, moaning powerfully as you feel it begin to thrust in and out of you now. The numerous studs that line the center of the organ begin to press firmly against the roof of your " + vaginaDescript(0) + ", stimulating your G-spot and flicking your " + clitDescript() + " each time her tongue dives back inside you. Your fingers dig into her flesh like a vice now as you grind yourself down on the indecent tendril, moaning salaciously as the waves of your climax begin to overtake you.\n\n"); outputText("Your " + vaginaDescript(0) + " cinches tight around Zetsuko's tongue, and it continues to wriggle inside you while you ride out your orgasm."); if (x >= 0) { outputText(" " + SMultiCockDesc() + " twitches powerfully between her feet, "); if (player.cumQ() <= 100) outputText("spurting a healthy spray of hot cum all over her face and chest."); else if (player.cumQ() <= 500) outputText("distending visibly as it begins to pump out thick streams of spunk all over her waiting face and tits."); else outputText("unleashing a heavy downpouring of cum all over her face and tits that soaks through her straitjacket and mats her hair down with your thick load."); outputText(" She grins lasciviously and opens her mouth to reveal her other freakishly long studded tongue, using it to lap up your spunk hungrily and clean herself off. \"<i>Mistress's cum is so tasty...</i>\""); } outputText("\n\n"); outputText("The slick juices of your climax trickle down, pooling inside Zetsuko's gaping pussy"); if (player.wetness() >= 4) outputText(" and overflowing to dribble down her bountiful ass cheeks and stomach"); outputText(". You hear an odd gurgling sound, and watch as the puddle of juices slowly begins to drain down into her vagina, a visible swallowing motion carrying it away inside her. \"<i>MMmmmm... Zetsuko loves the taste of Mistress's juices...</i>\"\n\n"); outputText("Fully spent, you pull yourself back, grasping Zetsuko's still-writhing tongue in your hand and sliding it out of you, letting her lower body thump to the ground. You watch as her tongue gently swirls around the lips and then retracts within the bizarre orifice, looking for all the world to be an ordinary — if slightly overstretched — pussy. You wonder if you should help her up for a moment, but as you are considering reaching down to bring her to her feet, she is suddenly bathed in corrupted flames, disappearing before your eyes.\n\n"); outputText("\"<i>Zetsuko hopes to taste [Master] again sometime...</i>\""); player.sexReward("saliva"); dynStats("lib", .25, "sen", -5, "cor", 2); endEncounter(); } //▶[Banana?] silly mode private function zetsukoBanana():void { clearOutput(); outputText("Banana? What the flying fuck is a banana?\n\n"); outputText("Banana.\n\nBanana banana banana. Just saying it feels kind of funny, so you say it a few more times just to be sure. Yep, still funny.\n\n"); outputText("\"<i>FUCKING MARAE PLEASE STOP SAYING BANANA — FUCK!!</i>\"\n\n"); outputText("You hear a thud and turn to see Zetsuko lying face-down on the ground, struggling in vain to get back up with her arms bound. She finally manages to wrench herself into a kneeling position, panting from exertion. Her forehead has a big blotch of dirt on it like she has been repeatedly slamming it on the ground.\n\n"); outputText("Banana.\n\n"); outputText("\"<i>FUCK!</i>\"\n\n"); outputText("As the word leaves your lips, you see the studs on Zetsuko's collar glow, and she is suddenly forced down to the ground again, face mashed in the dirt and her ass raised high while her pussy-tongue flails about wildly between her thighs.\n\n"); outputText("\"<i>Hah... hah... Zetsuko dislikes... those fruit... immensely,</i>\" she says, avoiding speaking the word aloud herself as she tries to lift herself back up yet again.\n\n"); outputText("Oh, so a banana is a fruit? *THUD*\n\n"); outputText("\"<i>FUCK!</i>\"\n\n"); outputText("You'll take that as a yes.\n\n"); endEncounter(); } private function noZetsukoLoveToday():void { clearOutput(); outputText("You tell her to be gone; you wanted Ceraph, not some lowly slave that can't even be bothered to show you proper respect. You order her to tell Ceraph not to waste your time with undisciplined servants that she's too inept to properly break.\n\n"); outputText("\"<i>Oohoh, Mistress is certain to be FURIOUS with Zetsuko...</i>\" she says, licking her lips and showing off the numerous studs that line her normal tongue as well. \"<i>Zetsuko cannot wait...</i>\""); doNext(camp.campSlavesMenu); } private function giveFollowerBodyBits():void { spriteSelect(SpriteDb.s_ceraphClothed); clearOutput(); outputText("You ask Ceraph just what all giving up a body-part would entail. Your submissive demonic slut presses herself against you, stroking her hands under your [armor] as she answers, \"<i>Well, [Master], I would use my body-shifting black magics to remove a choice portion of your 'fun-bits', if you know my meaning."); if (player.hasCock() || player.hasVagina() || player.hasBreasts()) { if (player.hasCock()) outputText(" I could take your cock."); if (player.hasVagina()) outputText(" I could remove your snatch. Don't worry, once it's off of you, anything I put in it won't wind up in your womb."); if (player.hasBreasts()) outputText(" I could even make off with your tits if you like."); } else outputText(" Sadly, you don't have anything that would be worth taking right now. A true shame, my [Master]."); outputText("</i>\""); if (player.gender > 0 || player.biggestTitSize() > 0) { outputText("\n\nYou scratch your head as she prattles on, growing more animated and a touch aroused. \"<i>Then, I can fly back to the harem and add them to my collection. My pets do so love when I give them an exotic endowment and then spend all night teasing it. Could you imagine it? Going to bed at night and dreaming of all the debauched things my slaves and I are doing, over and over?</i>\""); outputText("\n\nWell, that's quite the pitch she's put together. Do you want to give her something?\n"); var wang:Function =null; var smallestWang:Function =null; var vag:Function =null; var breasts:Function =null; var breasts2:Function =null; var breasts3:Function =null; if (player.hasCock()) { outputText("\nYou can give her your [if (cocks == 1) penis|biggest penis or smallest penis]."); wang = ceraphFollowerCockTaking; if (player.cockTotal() > 1) smallestWang = createCallBackFunction(ceraphFollowerCockTaking,true); } if (player.hasVagina()) { outputText("\nYour vagina would probably give you the most amazing sensations while being used in Ceraph's orgies."); vag = ceraphFollowerCuntTaking; } if (player.biggestTitSize() >= 1) { outputText("\nDo you really need your boobs?"); breasts = ceraphFollowerTitTaking; if (player.bRows() > 1) breasts2 = createCallBackFunction(ceraphFollowerTitTaking,1); if (player.bRows() > 2) breasts3 = createCallBackFunction(ceraphFollowerTitTaking,2); } //[(Biggest )Penis] [Smallest Penis][Vagina] [TopBreastRow] [2ndBreastRow] [3rdBreastRow] choices("Penis", wang, "Smallest Penis", smallestWang, "Vagina", vag, "Breasts", breasts, "BreastsRow2", breasts2, "BreastsRow3", breasts3, "", null, "", null, "", null, "Back", ceraphFollowerAppearance); } else doNext(ceraphFollowerAppearance); } private function ceraphFollowerCockTaking(smallest:Boolean = false):void { spriteSelect(SpriteDb.s_ceraphClothed); clearOutput(); var x:int = player.biggestCockIndex(); if (smallest) x = player.smallestCockIndex(); var y:int = x + 1; outputText("You sigh and undress enough to point at your [cock " + y + "], indicating that Ceraph is welcome to have it. Ceraph titters, \"<i>With pleasure, my [Master].</i>\""); outputText("\n\nCeraph's fingers feel unexpectedly hot as they brush your " + cockDescript(x) + ", as if she had just come out of a heated tub. You don't have long to ponder that little detail as they pinch into a tight ring"); if (player.cocks[x].cockThickness >= 4) outputText(", compressing your massive girth into the rigid shaft"); outputText(", slowly closing. It should hurt but it doesn't, it just feels warmer and warmer, and then with a sudden 'PYOING!', Ceraph is holding your " + cockDescript(x)); if (player.hasBalls() && player.cockTotal() == 1) { outputText(" and balls"); //Gotcher balls! player.balls = 0; player.ballSize = 1; } if (player.cockTotal() == 1) { player.removeStatusEffect(StatusEffects.Infested); player.buff("Infested").remove(); } outputText(" in her hand! At the base there's smooth flesh and an arcane mark, somehow keeping the disembodied dick alive to pulse and squirm in her grasp. The place on your groin is left completely smooth and featureless, as if it had never been there at all."); outputText("\n\nCeraph runs a finger up and down the length, setting off fireworks in your brain – you can still feel it! The demoness laughs and says, \"<i>Don't worry, that will fade once I get it further away, though you know what to expect at night, right? For now, enjoy the pleasure! Oh, and thank you again for this, you won't regret it. If you do, no refunds.</i>\""); outputText("\n\nShe pirouettes away, practically dancing into the sky while she strokes and teases the cock you just lost. You shudder and shake as orgasm wracks your body, your cum falling like rain thousands of feet away. You swear, you can hear your pet laughing."); player.orgasm(); dynStats("sen", -2, "cor", 5); flags[kFLAGS.CERAPH_OWNED_DICKS]++; player.removeCock(x, 1); endEncounter(); } private function ceraphFollowerCuntTaking():void { spriteSelect(SpriteDb.s_ceraphClothed); clearOutput(); outputText("You undress, just enough to point at your [vagina]. Ceraph smiles happily and muses, \"<i>I have just the troublesome slut that could learn a thing or two by having her mouth replaced by a pussy. Face-fucking is such an effective discipline technique, thank you dear.</i>\""); outputText("\n\nCeraph's fingernails stab at your [skin.type] painfully, dragging them in a circular motion around your vulva. The pain of the action fades to a gentle, throbbing heat while her fingers go deeper, corkscrewing through your flesh. A second later she pulls back, a featureless pillar of flesh wrapped in skin and sitting in her hand, topped with your " + vaginaDescript() + ". The other end is capped with a strange, arcane mark, seemingly tattooed into the skin. You glance down, expecting to find your groin ruined, but the spot your vagina once occupied is replaced with bare, unmarked skin."); outputText("\n\nThe demon slips a finger into her hand-held pussy, and you inexplicably moan, still feeling every sensation with perfect clarity. She plays with it for a few more seconds, the gentle 'schlick-schlick-schlick' of her fingers carrying through the air before she seems to tire of teasing you."); outputText("\n\n\"<i>Oh don't mind the feelings, they'll fade once I get farther away and get this stuffed into one of my pets. Thank you again, [Master] for supporting your pet's ever-growing harem. I'll be sure and put the new pocket-pussy to use right away so that you'll have some good dreams soon. I'll miss seeing it on you though, so if you would, please replace it. </i>\" instructs Ceraph with an air of feigned meekness."); outputText("\n\nYou work your jaw in consternation, trying to stay upright as Ceraph starts to fly away, amusing herself by masturbating your old cunt as she flies. The lewd squishes seem to hang in the air, and you're helpless to do naught but writhe in the dirt and moan as you're brought to orgasm from a nonexistent vagina. It seems as soon as she leaves camp she forgets she's supposed to be YOUR subservient bitch."); player.removeVagina(0, 1); //(-100 lust, -1 fetish, +1 vagina toy status) player.orgasm(); dynStats("sen", -2, "cor", 5); flags[kFLAGS.CERAPH_OWNED_PUSSIES]++; endEncounter(); } private function ceraphFollowerTitTaking(rowNum:int = 0):void { spriteSelect(SpriteDb.s_ceraphClothed); clearOutput(); var x:Number = rowNum; //Store nipplecuntz or milks if (player.breastRows[x].fuckable) flags[kFLAGS.CERAPH_STOLEN_BODYPART] = 4; else if (player.lactationQ() >= 100) flags[kFLAGS.CERAPH_STOLEN_BODYPART] = 5; else flags[kFLAGS.CERAPH_STOLEN_BODYPART] = 3; outputText("You pull down your [armor] to bare your bosom to Ceraph and indicate that you'd like her to take it. She smiles like a cat who's gotten the cream and whispers, \"<i>Your wish is my command, [Master].</i>\""); outputText("\n\nCeraph bounces your " + breastDescript(x) + " in her hands, playing with them for just a few seconds before she digs her nails in and pulls. Your tits stretch for a moment, pulled tight while Ceraph giggles cruelly. Heat blooms inside your chest, vivid tingles radiating from Ceraph's fingertips deep inside you. At last, it peaks and with a deep 'POMF', your tit-flesh separates from your body. You look closely at the departing bosom – where it once joined with your body, it's covered in healthy pink skin and intricate, arcane tattoos. Meanwhile, "); //More than 1 set of tits and not on bottom row? if (x < player.breastRows.length - 1 && player.breastRows.length > 1) { //If only 1 row below if (x >= player.breastRows.length - 2) outputText("your torso has shifted and your " + breastDescript(x + 1) + " have moved up to fill the void."); //Multiple below else outputText("your torso has shifted and your other breasts have moved up to fill the void."); player.removeBreastRow(x, 1); } //Top row is only row else if (x == 0) { outputText("your now-flat chest slowly gains two tiny, quarter-inch nipples."); player.breastRows[0].breastRating = 0; player.nippleLength = .25; player.breastRows[0].breasts = 2; player.breastRows[0].nipplesPerBreast = 1; player.breastRows[0].fuckable = false; player.breastRows[0].lactationMultiplier = 0; } //everybody else else { outputText("your torso leaves the now-empty spot as a flat, featureless void."); player.removeBreastRow(x, 1); } //Oh shit something went wrong. if (player.breastRows.length == 0) outputText("<b>ERROR! ERROR! Please contact Fenoxo and reload your game if you don't want your save messed up.</b>"); outputText("\n\n"); outputText("You gasp when Ceraph "); if (flags[kFLAGS.CERAPH_STOLEN_BODYPART] == 3) outputText("rolls the nipples in her hands"); else if (flags[kFLAGS.CERAPH_STOLEN_BODYPART] == 4) outputText("pushes her fingertips inside the leaky nipple-cunts"); else outputText("squeezes out a squirt of milk"); outputText(", going a little weak in the knees. Ceraph laughs and lowers the bouncy orbs down between her legs, and you can feel every little bump and nodule of her corrupted cock as she tit-fucks herself on your disembodied breasts.\n\n"); outputText("\"<i>Oh oh, does someone like having a nice hard cock buried in her tits? Maybe I should've left these on you so that I could get the full benefit before I left. Maybe next time,</i>\" taunts the demoness while she continues to tit-fuck herself on your former bosom. \"<i>Don't worry, [Master], I'll be sure to give them a good home. You should get plenty of nice dreams out of these sweater puppies!</i>\"\n\n"); outputText("Ceraph turns and prances off through the rocks, tweaking your nipples HARD every few moments to remind you of your choice. She vanishes before long, leaving you to deal with the slowly dwindling sensation of her cock in your tits.\n\n"); //(-1 fetish, +1 tit toy status) dynStats("lus", 20, "cor", 5); flags[kFLAGS.CERAPH_OWNED_TITS]++; endEncounter(); } //NippleCunt Stuffing (Ceraph grows dick-nipples to plow your lusty twats!) private function stuffSomeNippleCunts():void { spriteSelect(SpriteDb.s_ceraphClothed); clearOutput(); outputText("Wanting to take advantage of some of the more extreme of your body's changes, you pull down your [armor] to bare your hungry nipple-twats, the well-lubricated tips of your nipples slowly opening in anticipation of what's to come. You kick the discarded gear aside and command, \"<i>Slave, fuck my nipples.</i>\""); outputText("\n\nCeraph looks at you, then down at your chest, and finally back up at you with a look of incredulousness glinting in her eyes. \"<i>You want... [Master] is... kinky,</i>\" she coos, peeling out of her tight outfit to bare her demonic bosom. Your demonic slave approaches, hips swaying as her bottom falls away to display her puffy purple womanhood"); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" and proud demon-dick"); outputText(". She grabs your [chest] to examine, and her fingers probe hesitantly around the entrances of your budding chest-cunnies. Ceraph smiles with wicked intent. Her fingers thrust in forcefully, drawing a sensual moan from your lips as she violates "); if (player.totalNipples() > 2) outputText("two of "); outputText("your tit-pussies."); outputText("\n\nThe demoness' digits forcefully enter you again and again, pushed in to the knuckle. Juices drip down the swells of your breasts as Ceraph gets a feel for your depth, width and sensitive spots. Her probing fingers casually rape your areola, and it feels goddamn good."); if (player.totalNipples() > 2) outputText(" She moves from pussy to pussy with ease, exploring every single one of your myriad holes, a gleeful smile on her face."); if (player.lactationQ() > 0) outputText(" A squirt of breastmilk nearly takes your slave in the eye, your milk letting down uncontrollably from the tit-puckering finger-fuck."); if (player.hasCock()) outputText(" [EachCock] is so hard by this point that it's smearing its pre-cum all over Ceraph's belly, but she doesn't mind."); if (player.hasVagina()) outputText(" As for your [vagina], you've grown more than wet enough for a hard dicking, but honestly, right now, all you want is your [nipples] to be perfectly and completely fucked."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" The fetishistic slut's sloppy cock is dribbling on your hip, neglected and aroused. Poor thing."); outputText("\n\nSatisfied with her work, your submissive Omnibus steps back to look at you. Your [skin] is flushed. Every inch of your underboob is wet with lubricant[if (isLactating = true) and milk]. Your [nipples] are a soggy, inflamed mess. Worst of all, you're panting like some bitch in heat. Your slave is just out of arm's reach, watching you with a knowing smile. Her own purple-hued dermis is tinted rose, though she seems to be hiding her arousal better than you. You growl, \"<i>I said, fuck my gods damned nipples!</i>\" at her and jiggle your dripping teats for emphasis."); outputText("\n\nCeraph frowns with distaste, but she answers, \"<i>[Master], please, shapeshifting takes time and preparation. However, I believe I am almost ready to serve you. Watch me change, for you...</i>\" Ceraph cups her own sizable breasts in her palms and begins to rub them. Her nipples, while already hard, pop out further, elongating with a well-timed, breathy exhalation of pleasure from their owner."); if (player.bRows() > 1) { outputText(" A second later, "); if (player.bRows() == 2) outputText("another row of female flesh begins"); else outputText("more rows of female flesh begin"); outputText(" to sprout beneath her top pair, the demoness's chest mimicking yours in size and structure. While the top pair of super-sized nipples continue to grow into massive teats, Ceraph repeats her caresses lower, and the newly-formed nipples mimic their big brothers, filling out to obscene length."); } outputText(" At first, the changes make her areola look more like something that belongs on an udder, but as they enlarge beyond even that, you realize they're taking on a distinctly masculine shape, with a slight ridge just below their bulbous tips. After growing out almost seven inches, the upward-curving nipples stop filling out. Ceraph has sprouted nipple-dicks!"); if (player.averageNipplesPerBreast() > 1) outputText(" She strokes them, one by one, and they split down the middle, dividing into a multitude of penises, a perfect match to your quad-nipplecunts."); outputText("\n\nYou cannot help but gape at the lascivious demonette's new form. She's absolutely, unquestioningly built for sex, from her wide hips and well-defined pussy-lips to the absolutely obscene growths she's produced for your whims. Ceraph brushes her hair back and asks, \"<i>I take it you like the look, [Master]?</i>\" You nod and stick your fingers into your chest, pulling open the holes to tempt her. It's hard to bite back the moan that wells up in your throat, but you manage, somehow, to keep your expression placid and seductive."); outputText("\n\nYour freakishly-endowed minion steps forward with an enthusiastic expression plastered on her face, taking care and time to line up each of her tit-mounted tools with your [nipples]. Ceraph glances up at you deferentially, and you nod, perhaps a bit more eagerly than you intended to. At once, " + num2Text(player.totalNipples()) + " shafts are sliding into your udder-mounted vaginas, their pulsating demon-flesh wetly stroking your multiple interiors in perfect, exquisite sync. A sense of barely-understood bliss erupts from your chest-pussies as they're taken, utterly filled. It's difficult to think, let alone stand under such circumstances, and you clutch on to Ceraph's shoulders, pulling her down to the ground atop you."); outputText("\n\nYour pet demon immediately gives in to her instincts and begins to raise and lower herself atop you. At the bottom of each stroke, fluids squirt from your violated holes and the pairs of docked boobflesh squish outward, bulging obscenely. Interlocked bodies grind together in the throes of passion, Ceraph going faster and faster, filling the air with squishing slaps of intercourse. Soon, she is going so fast that it's impossible to pick apart the myriad of sultry sounds, not that you can think properly at present to try. You lie there to simply enjoy the sex, wallowing in it like a sow in mud."); outputText("\n\nCeraph chews on her lower lip in nervous pleasure as she bobs up and down atop you, and in a moment of surprising clarity, you order, \"<i>Slave, kiss me.</i>\" She does so with gusto, her purple-hued mouth instantly locking to yours, tongues twisting around each other like warring snakes. It's almost enough to make you forget the pounding rhythm of her lube-soaked tits slapping against your own, ALMOST. The turgid tit-cocks feel even bigger with every pistoning movement in and out of your cavities. You realize she's getting close to orgasm, and a moment later, it dawns on your lust-fogged mind that you too are about to climax."); outputText("\n\nBiting down on Ceraph's lower lip, you get her to pull back long enough for you to command, \"<i>Cum inside me pet, fill my tits!</i>\" Ceraph's violet eyes cross ever so slightly, the black sclera glittering with moisture as her eyelids flutter in rapture. She throws herself down on top of you with bruising force, bottoming out all " + num2Text(player.totalNipples()) + " twitching dicks inside you, just in time to release their creamy cargo. Gods, she's filling you up so good! You reach up with your hands and squeeze the edges of your [chest] hard enough to feel the rigid, cum-spouting flesh inside you. Jizz wells up from each entrance in sync as you begin to tremble and shake. Ceraph lets out a low moan as she fills you"); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(", her cock spouting its own ivory wetness onto your belly in sympathetic release."); else outputText(", her pussy dripping weakly in sympathetic release."); outputText(" Her hands run through your [hair] and pull your [face] into her shoulder. She holds you tightly, clingingly even. If you weren't so enraptured by the sensation of your sperm-filled nipples, you might actually care."); outputText("\n\nThe two of you slowly relax, dueling climaxes winding down to return some level of sanity at last. As soon as the demoness' eyes uncross, she stands up, " + num2Text(player.totalNipples()) + " dicks sliding free of clutching, spunk-stuffed twats at once. You gasp and shudder, the sensitive flesh nearly setting you off again. As she stretches, Ceraph's new appendages shrink, losing their masculinity and even faster their size. You rise while trying to ignore the runnels of demon-spunk that spout from your well-fucked chest, your [chest] wobbling fantastically with the extra fluid weight. Ceraph leans over to suck a [nipple] into her mouth, and after a few quick swallows, she sighs contently."); outputText("\n\n\"<i>Delicious, my [Master],</i>\" the demoness coos as her wings unfurl, \"<i>Please, let's do this again.</i>\" She leaps into the sky and flies off, no doubt to tend to her own pets."); player.sexReward("cum","Vaginal"); dynStats("sen", 2, "cor", 1); endEncounter(); } //Portal Fuck (AKA Ceraph Hung Out With Cinnabar, Req's PC dick) private function portalFuckWithFollowerCeraph():void { spriteSelect(SpriteDb.s_ceraphClothed); clearOutput(); var x:int = player.cockThatFits(100); var y:int = x + 1; //FIRST TIME: if (flags[kFLAGS.TIMES_CERAPH_PORTAL_FUCKED] == 0) { outputText("You undress and ask Ceraph if she has any ideas to mix things up. Your demon smiles and answers, \"<i>Oh, I think I have just the thing: a pair of trinkets I picked up at the bazaar. There's a... gifted prostitute there who I would love to have in my harem, but alas, if I am to have access to that cursed place, I must abide by their rules.</i>\" A shadow clouds the greedy demoness's expression at that admission, but she continues on, \"<i>I was able to get her to produce for me two magical cock-rings. They're powerfully enchanted with white AND black magic.</i>\""); outputText("\n\nCareph smiles knowingly, still not revealing their true purpose. With an impatient wave of your hand, you command her to finish. She harrumphs, \"<i>Fine, take all the drama out of it! These cock-rings create portals, portals to anywhere the user desires. You could put one on, and have your dick rammed into my throat, simply by imagining it. You could sit there, in a chair, masturbating yourself with the ring and actually manage to fuck my hot little cunt at the same time.</i>\""); outputText("\n\nYou look at the golden rings a bit skeptically, but Ceraph assures you, \"<i>Trust me, they work. I resized one of them to fit me perfectly, and I'll often use it to keep my pets in line, no matter what part of my lair they're in - even the sensory deprivation tanks."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 1) outputText(" Of course, you don't seem to like that appendage, so my ring won't get much use today, will it?"); outputText("</i>\""); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 1) outputText(" Ceraph twirls one of the rings into her palm, where it promptly vanishes in a puff of purple smoke."); outputText("\n\nThe mauve miscreant tosses the ring to you, still warm from her body heat and tingling with embedded magic. You sit down in a simple chair and turn it over in your hand before deciding to go with one of her suggestions. \"<i>Slave!</i>\" you bark, \"<i>Lie on your back before me with your legs spread.</i>\""); } else { outputText("You suggest Ceraph retrieve her fantastically enchanted cock-rings, and with an impish smile, your slave produces a pair of them in puffs of purple smoke."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 1) outputText(" She sadly teleports one of them away, knowing you've commanded her to stay female for you."); outputText(" The mauve miscreant tosses your ring to you, still warm from her body heat and tingling with the embedded magic. She requests, \"<i>Please, [Master], do me like you did before! It was so hot for you to watch me like that!</i>\""); } outputText("\n\nCeraph obediently lies on the ground beneath you and spreads the flawless purple skin of her thighs apart to reveal her womanhood"); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" and eager cock"); outputText(". She scoots her ass up so that it's resting against your [legs] and the front side of the chair, a tantalizing heart-shaped butt just within arms' reach. You give it a slap, which garners a delighted coo from the tainted slut."); outputText("\n\nNow that everything is in position, it's time for the moment of truth. You push the ring down on your [cockHead " + y + "] until the warm metal frame is snugly secured just above your [sheath]. The tingling you could feel when it was in your hand was a mild pinprick compared to the prickling sensations it shoots through your [cock " + y + "]. They aren't unpleasant, but they are certainly intense, and combined with the tightness of the ring, they keep you nice and hard."); if (flags[kFLAGS.TIMES_CERAPH_PORTAL_FUCKED] == 0) outputText(" Well, your dick doesn't look any different, aside from the gilden adornment stuck near the bottom. Now, if it were hilt-deep in the demon's cunt, that would be something!"); else outputText(" Well, no sense wasting time! You look down at Ceraph's moist box and imagine your dick spearing through her folds."); outputText("\n\nWhite light flashes along with a wave of tingling pinpricks under the ring on your [cock " + y + "]! You blink and look down, seeing a strange arcane symbol INSIDE the cock-ring's center. That glimmering glyph has become the terminus of your suddenly-stunted, plateau-like member. Ceraph's coo of pleasure tears your gaze further down, and you see a matching glyph just above her pussy, with the rest of your [cock " + y + "] completely buried into her wetness. You don't just see it, you can feel it too. Her wet snugness is molding around your girth, yielding to the intrusion like a glove wrapping around a hand."); outputText("\n\nExperimentally, you grab the ring and move it slightly. Taking it up slides your dick partway out of her cunt, more flesh appearing by magic on your loins as the glyph is pushed away. Moving it down diminishes your visible erection, but it also fucks Ceraph's twat. The demoness's gaze is riveted on her magic-illuminated snatch, watching happily as you experimentally plunge in and out of her sodden box."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText("\n\nNot one to be outdone, your pet takes the other ring and begins to force it down her nubby demonic dong. The gold-gilt dick-jewelry settles quite firmly just above her creamy pussy, and with a matching flash of light, her own member disappears. Surprisingly, it doesn't appear in any of your orifices. A quick glance her way reveals just where her dick wound up - in her mouth. Ceraphs glossy lips are spread in a wide 'o', a thick demon-dick holding them open as she bobs her head up and down. Greedy slurps and muffled moans drift up from her through the autofellatio, and you watch excitedly while masturbating yourself with her cunt."); outputText("\n\nYou make good use of your new toy, pulling it up to just below the head before slamming it down hard, all the way to your [sheath]. It feels every bit as good as fucking her normally, but without having to actually move your whole body, you're able to relax and enjoy the experience more. As an added benefit, you can see the way your pet slut's purple nether-lips blush as she gets more aroused, moisture spilling out around your thickness to drizzle through her asscrack. With your free hand, you grope one of the slaves contoured cheeks, feeling its heft, its softness, and its lewd jiggles. You begin to moan, enjoying this more than you ought to, yet helpless to slow your pumping hand."); outputText("\n\nThere's no stopping the surging passion as it races through you, and with a throaty sigh, you release your seed. It's amazing, from this vantage you can do more than just experience your orgasm, you can watch it happen. You can see the underside of your disembodied cock bulging with each urethra-stretching load.[if (cumQuantity > 500) Jizz foams at her lips as her belly rounds, and you're treated to the sight of Ceraph's bellybutton suddenly becoming an outtie.][if (cumQuantity > 1000) A moment later, her stomach rounds further, taking on a positively pregnant appearance.][if (cumQuantity > 1500) Spunky rivers pump from the demon's overfull womb as it loses its ability to stretch any further.] You sigh and idly move the portal up and down, fucking through the sloshing, sperm-filled mess that the demon's cunt has turned into. Delightful."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText("\n\nCeraph gurgles happily for a second, then her cheeks bulge. Her throat begins working, and you realize she's cumming into her own mouth. By the look of how squirrel-like her visage has become, she can barely manage to swallow a mouthful before the next is stuffing her full, dribbles of pearly cream running freely from the corners of her mouth. Ceraph quietly gulps and swallows over and over until her dick finally begins to soften, spent at last."); outputText("\n\nYou stand up and stretch, your cock still lodged tight in Ceraph's cooch. Alas, all good things must come to an end, and with one slow tug, you remove the ring from your [cock " + y + "] (and your maleness from her cunt). You toss the borrowed item back to her, letting it fall on your slave's heaving bosom as she tries to recover, a fucked-out mess in the dirt. You turn to get dressed, and when you glance back, Ceraph is gone, until the next time you call for her."); player.sexReward("vaginalFluids","Dick"); dynStats("cor", 1); awardAchievement("Now You're Fucking With Portals", kACHIEVEMENTS.GENERAL_FUCK_WITH_PORTALS, true, true); flags[kFLAGS.TIMES_CERAPH_PORTAL_FUCKED]++; endEncounter(); } private function layEggsInSlaveCeraph():void { clearOutput(); //Either Type on Ceraph Follower: Finished (Posthuman) (Zedit) outputText("You "); if (!player.isTaur()) outputText("absently rub the sensitive bulge in your abdomen as you "); outputText("regard your slave. There certainly is something she could do for you. Imperiously, you let her know that you have a load you wish to get rid of, and you intend to plant it in her."); //[if (cocks > 0) if (player.hasCock()) outputText(" Ceraph glances at the bulge in your [armor] quickly before she demurely lowers her eyes. A wicked smile plays across her beautiful face as she responds, \"<i>Yes, [master].</i>\""); else outputText(" Ceraph frowns as she glances towards your crotch. She is disciplined enough to answer you quickly, however, with a sharp \"<i>Yes, [master].</i>\""); outputText("\n\nYou command her to turn around and bend over. Your demonic slave hastens to comply, presenting her latex-covered sex to you brazenly. The shimmering scrap of fabric hovers on the bare edge of decency; the strip is so narrow, you can see her puffy outer lips bulging out on both sides."); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText(" The whole garment creaks and strains under the pressure of her hardening member."); outputText("\n\nYou frown. Your slut knows that you're going to use her as an egg dump; how does she expect you to do that with panties in the way? Growling, you grasp the shear latex around the waistband, right beneath her twisting tail, and [if (strength < 80) haul upwards.|pull upwards with such force that Ceraph is left dangling from the bikini bottom.] The omnibus screams as the fabric cuts into the soft flesh of her sex"); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText("; unable to keep it penned up, her demonic cock spills out the side, waving back and forth obscenely as you saw the offending garment into her crotch"); outputText("."); outputText("\n\n\"<i>Stop!</i>\" Ceraph cries as you jerk the bottoms back and forth savagely, \"<i>I'll take them off, [Master]! I'm sorry!</i>\""); outputText("\n\nYou roll your eyes and drop her to the dirt. Knowing that she could have vaporized her clothing with a thought, had she been inclined, you let her make a show of slowly, painfully peeling off the bottoms before she resumes her original position, on her knees with her round, purple ass facing you."); outputText("\n\nYour ovipositor slips free of its sheath as you size up your slave's collection of holes"); if (!player.isTaur()) outputText(", and your fingers tremble slightly as you trace its segmented length, leaving a trail of lubricating mucus from tip to base"); outputText(". When you order your demonic slut to present her pussy to you, she slides an impeccably manicured hand between her thighs, opening her dark, glistening lips for you."); outputText("\n\nSurely, she can do better than that. You step forward and plant one [foot] against her ass, shoving her face forward into the campsite dirt. \"<i>Wider,</i>\" you order. She arches her back and reaches with both hands; each takes a violet lip and pulls it, exposing the inside of her vulva to you. You see her hole gaping open and overflowing with juices, leaving a long strand of goo dangling between her thighs."); outputText("\n\nShe is doing better, but why not see how far she can take her tainted body? \"<i>Wider!</i>\" you bark. Without missing a beat, Ceraph slips her fingers inside her sopping box itself and pulls it open until you can see inside her. A veritable forest of feelers and growths in various shades of purple and black writhe on every inner surface of her vagina. Actually seeing them move makes you feel a little nauseous, but at the same time, you can't help but note the tingling arousal spreading up from your groin."); outputText("\n\nAt the back of her vagina, the omnibus's cervix almost glows, several shades lighter than the surrounding flesh. You smile and order her to open it. Ceraph grunts with effort, but you are rewarded by the sight of the tiny slit dilating. There is certainly something to be said for how... accommodating demonic corruption can make a creature's body."); outputText("\n\nYou position yourself behind your slave and begin slowly working your ovipositor into her. With her fingers still pulling her sex open, all you feel is the slight tickling as the longest of the growths stroke your alien member. Ceraph coos beneath you as the tapered head of your egg tube butts up against her cervix. You barely have to exert any pressure to get into her tainted womb, as it welcomes you by sliding open further. Your breathing becomes rough as you feel muscles inside your abdomen contract, bringing the first egg from deep inside you; your demon whore goes crazy as she feels the base of your organ swelling, grinding her ass against your hips."); outputText("\n\nAs your eggs travel towards your tip, they swell your organ until it rubs the sides of her distended pussy. It feels as if the hot flesh is trying to close around your pseudo-prick like a mouth, making obscene sucking noises and dripping a steady stream of the frothed, mixed lubricant from both you and your slave."); outputText("\n\nThe feeling is too much for you to bear, and you cum as you spurt your first egg deep into Ceraph's body. "); if (player.gender > 0) outputText("Your orgasm spatters your degraded demon's rear, adding to the sopping mess your ovipositor is leaving. "); outputText("More eggs follow the first, each one triggering a miniature orgasm for your slut as it fills her up. She screams and shudders, but is careful not to let go of her pussy. What a considerate slave, you think, as you watch her belly expand with your eggs. The faux-corset melts away as Ceraph quickly goes from bloated to filled to bursting. The surface of Ceraph's stomach actually ripples slightly under the pressure of dozens and dozens of your eggs."); outputText("\n\nFinally, after a few minutes that feel like a blissful eternity, you feel empty. You let your slave know that you are going to pull out, and that if she lets a single egg out of her stretched-out pussy, you will sew it shut for her. Your spent ovipositor slides from her packed cunt, accompanied by a gush of lube. While Ceraph's sex gapes lewdly at you, you are proud to see she manages to keep all your eggs inside her. You pat the slut's sensitive cunny, sending her into gasping spasms."); outputText("\n\nHumming a happy tune to yourself as you walk around Ceraph's twitching form, you grab a handful of her hair and pull her up off the ground. Her face is crusted with dirt and her sparkling, gem-like eyes stare senselessly at you. You rub your ovipositor over her head, carefully wiping your mingled lubes off on her hair before retracting the organ back into its holding sleeve. \"<i>That will be all,</i>\" you tell her, and she smiles dreamily at you. You turn around to gather your things, and don't bother to look back."); player.dumpEggs(); player.sexReward("Default","Default",true,false); endEncounter(); } //Ceraph Pegging + Bonus Petplay! //Adds "Submission" option to the roleplay menu. private function sumissivenessToCeraphFollower():void { clearOutput(); spriteSelect(SpriteDb.s_ceraphClothed); outputText("When you broach the idea of submitting to your fetish queen, delight washes across Ceraph's face. Before another word can be spoken, she lashes out with her whip (where did she get that from?) and catches you around the neck with the taut leather, yanking hard enough to drag you to the ground and make you sputter for air. The shining leather slides off as soon as your hands hit the ground, but the demoness is already standing above you, pushing on you with her stiletto-like heels to roll you aside."); outputText("\n\n\"<i>That's a better place for a useless little " + player.mf("boy", "girl") + " like you, down in the dirt where you belong,</i>\" the demoness declares, pacing back and forth. She crouches next to you and whispers in your ear, \"<i>The safe word is 'apple', you pitiful pig.</i>\""); outputText("\n\nYou nod meekly, awed by the demonic dominatrix's imposing, self-assured aura of command."); outputText("\n\n\"<i>Bend over, slut,</i>\" Ceraph commands."); outputText("\n\nYou start to stand up, but Ceraph again lashes out with her whip, striking you across the back four or five times. It's hard to keep count through the pain. Stinging welts rise on your [skin], and a heady thrill runs through your groin. You're totally stiff by the time she finishes the punishment, and it's plainly visible to the cruel hermaphrodite above."); outputText("\n\nScowling down at you, Ceraph commands, \"<i>Pets don't get to sit up - they roll over in the mud and crawl on your hands and knees like the beasts they are. Remember that, [name]. You aren't a person.</i>\" Her whip lightly smacks your hip. \"<i>You're a pet.</i>\" SMACK! \"<i>A slave.</i>\" CRACK! \"<i>Property.</i>\" SNAP!"); outputText("\n\nYou mewl pathetically under the blows but do your best to present yourself as ordered, rolling over and climbing up, [armor] covered in grime. Worse still, your excitement is showing in more ways than one"); if (player.gender == 3) { outputText(", both in the hardness of your manhood"); if (player.cockTotal() > 1) outputText("s"); outputText(" and the moisture leaking from under your equipment"); } else if (player.gender == 2) outputText(", what with the beads of moisture forming between your legs"); else outputText(". Your hardness is easily visible to anyone who knows where to look, and the demoness definitely knows where to look"); outputText("."); outputText("\n\nCeraph smirks and asks, \"<i>Does my subby slut like it when I play rough? Or did you just get hard when you realized how right I am? There's no shame in enjoying your station, pet. After all, animals are there to please their owners.</i>\" She strokes your " + hairDescript() + " with an unfamiliar gentleness. It's like a pleasant balm after the rough whipping, and you find yourself leaning into it, accepting the demeaning affection just to feel something that doesn't hurt."); outputText("\n\n\"<i>Good " + player.mf("boy", "girl") + ",</i>\" the purple-skinned dom coos as she begins to undress you, keeping you on the ground the whole time. \"<i>Let's get you out of these pesky clothes. Good pets are naked, and I can see how <b>hard</b> you're trying to be a good pet.</i>\" Her hand dances across "); if (player.hasCock()) outputText("[oneCock]"); else outputText("your rigid clit"); outputText(" with ticklishly-soft touches"); if (player.hasBalls()) outputText(" before gently squeezing your [sack]"); outputText(", savoring your state. You groan out loud at the sudden sensation, and a bead of "); if (player.hasCock()) outputText("pre-cum has begun to form on your [cockHead biggest]"); else outputText("girl-cum has begun to form at your quivering entrance"); outputText(". The crystal-clear droplet of congealed lust slowly begins to dangle down, connected for a few seconds by a string of moisture before it snaps and disappears into the dirt."); outputText("\n\n\"Oh, pet is dripping?</i>\" Ceraph wonders aloud as she stands and pivots, immediately taking a seat on your back. \"<i>Perhaps pet is feeling a little pent up.</i>\" She loops the whip around your neck and tugs slightly, enough to make you realize that she could control your breathing right now, if she wanted to. The damnable magic of that whip has your blood boiling, and the erotic tingle of the treated leather against your " + player.skinFurScales() + " doesn't help. Another drop falls, and you start to answer, \"<i>Yes...</i>\""); outputText("\n\nThe word is choked off as soon as its started. Ceraph lectures, \"<i>Pet, that isn't how you speak! If you're going to be more than a useless submissive, you need to learn how to communicate. Now, if you want me to ease that pressure, you can mewl like a cat or bark like a dog once for yes. Do it twice for no, and we can go for a walk.</i>\" The crushing pressure around your windpipe is relaxed, and you are given a chance to respond."); if (player.hasCock()) outputText("\n\n(Agreeing could result in some humiliating milking...)"); else outputText("\n\n(Agreeing could result in some humiliating pegging...)"); //+50 lust, affected by resistance dynStats("lus", 50, "scale", false); menu(); //[Mewl once] [Bark once] [Either twice][Apple] addButton(0, "Mewl Once", barkToCeraphOnce, false); addButton(1, "Bark Once", barkToCeraphOnce, true); addButton(2, "Meow Twice", barkOrMeowTwiceToCeraph, false); addButton(3, "Bark Twice", barkOrMeowTwiceToCeraph, true); addButton(4, "Apple", sayAppleToCeraph); } //[Apple] private function sayAppleToCeraph():void { clearOutput(); spriteSelect(SpriteDb.s_ceraphClothed); outputText("Fuck this! \"<i>Apple!</i>\""); outputText("\n\nCeraph gets up with a shocked expression painted on her violet features. \"<i>Didn't you have any fun?</i>\" she asks. \"<i>We were just about to the good part!</i>\""); outputText("\n\nYou tell her that it wasn't fun in the slightest, and you want out."); outputText("\n\n\"<i>Well, okay then... [Master]...</i>\" she grumbles."); endEncounter(); } //[Either Once] private function barkToCeraphOnce(dog:Boolean = true):void { clearOutput(); spriteSelect(SpriteDb.s_ceraphClothed); outputText("\"<i>"); if (dog) outputText("Arf!</i>\" you bark"); else outputText("Meowwwww!</i>\" you mew"); outputText(", loud and almost proudly"); if (player.tailType > Tail.NONE) outputText(", wagging your tail excitedly"); outputText("."); outputText("\n\nCeraph casually pulls her panties a bit lower to "); if (flags[kFLAGS.CERAPH_HIDING_DICK] == 0) outputText("ease the pressure on her tightly-contained phallus"); else outputText("allow a penis to grow, fully-formed from where her clit was"); outputText(". The stalk of her cock drips with the swampy cunt-lubricant her delta exudes, and she pumps it a few times to make it stand long and erect, nine inches of pulsating, demonic horror. Tiny nodules decorate the shaft in concentric rings to stimulated anyone lucky enough to experience her cock. As Ceraph eyes your backside, you realize that you're going to be feeling it before long."); outputText("\n\n\"<i>"); if (dog) outputText("ARF! ARF!"); else outputText("REOOOOW!"); outputText("</i>\" you "); if (dog) outputText("bark"); else outputText("meow"); outputText(" in distress, trying to crawl away. You didn't mean to get "); if (player.hasCock()) outputText("milked "); else outputText("fucked "); outputText("like... like that! Her whip snaps taut before dragging you back. You scrabble in the dirt for a half-second, choking yourself before you give up and sag limply down at her feet. Slowly, you lift your [butt] up into the air to allow Ceraph access, regretfully yielding to her like you should have initially."); outputText("\n\nSWAT! Her hand claps against a cheek, lingering to squeeze the raw flesh after the spank. She explains, \"<i>That was for resisting, and this...</i>\" You feel a slick, wet warmth at your tender, rear opening. \"<i>...is for being my obedient, playful little "); if (dog) outputText("doggie"); else outputText("kitty-cat"); outputText(".</i>\" Her hips press the hot spear harder against your [asshole]. "); if (player.ass.analLooseness == 0) { outputText("Even though you're a virgin, the cunt-slick tool worms its way into your rectum with ease, the nodules massaging your sorely-stretched anal ring as it accommodates to handle the bigger width, forever ruined by Ceraph's boner."); } else if (player.analCapacity() < 20) outputText("Even though you're pretty tight, the cunt-slick tool slides into your rectum with ease, the semi-soft nodules massaging your anal ring as it adjusts to the heated impalement."); else if (player.ass.analLooseness >= 4) outputText("The cunt-slick tool has no problem wiggling inside your well-used and abused asshole, hilted in a split second, the hundreds of nubs gently caressing your anal ring like a lover as they nestle inside you."); else outputText("The cunt-slick tool slides right on in thanks to your capacitative anus, the gentle nubs each massaging your snug ring as they slide on through."); outputText(" You groan as you're taken by your owner, catching yourself halfway and arresting the pleasured grunt as soon as you can, but it doesn't matter - the damage is already done."); player.buttChange(16, true, true, false); outputText("\n\nThere's a ring of larger bumps, just around the edges of Ceraph's glans, and they catch on something inside you as she grinds through your butthole, sending heat-spikes of inadvertent pleasure through "); if (player.hasCock()) outputText("your twitching maleness"); else if (player.hasVagina()) outputText("to your achingly empty pussy"); if (player.cockTotal() > 1) outputText("es"); outputText(". Almost immediately, you squirt out a huge dollop of "); if (player.hasCock()) outputText("pre-cum"); else outputText("lady spunk"); outputText(". It dangles heavily enough to "); if (player.hasCock()) outputText("make your [cock biggest] bob below"); else outputText("tantalize and tease your clit"); outputText(", and you give up another grunt of pleasure while your hips press harder against your owner's."); outputText("\n\nCeraph's hands fall on either side of your waist. She reassures, \"<i>I treat my pets well, [name].</i>\" Her hips pull out, the nubby, textured tool bouncing and grinding all along your insides as she continues. \"<i>I make them happy to be pets...</i>\" That thick, demonic dick pushes back in a little harder, pushing your arms down so that your face is pressed into the dirt. \"<i>...Happy to be owned, because obedience IS pleasure.</i>\" Ceraph adjusts the angle so the blunted tip of her erection "); if (player.hasCock()) outputText("rams straight into your inner, cock-milk reserve"); else outputText("rubs against your quivering vaginal walls, stimulating you from the inside out"); outputText(", and fireworks start to go off inside your brain."); outputText("\n\n"); if (player.hasCock()) outputText("Dick-milk"); else outputText("Love-juice"); outputText(" drizzles from "); if (player.hasCock()) outputText("[eachCock]"); else outputText("your slightly parted twat"); outputText(" into a pool on the floor as you're expertly brought to a tingly, body-quivering, anal orgasm. It can barely be called an ejaculation, really. The "); if (player.gender == 2) outputText("fem-"); outputText("cum is just "); if (player.hasCock()) outputText("sliding"); else outputText("pouring"); outputText(" smoothly out of it as your "); if (player.hasCock()) outputText("inner reservoir is squeezed"); else outputText("cunt walls are stimulated through your anal walls"); outputText(". Ceraph continues to push, but her dicktip slips off its mark, and she quickly buries herself back inside, each nodule responsible for small blurts of jism as they slip across your orgasmically tightening "); if (player.hasCock()) outputText("prostate"); else outputText("walls"); outputText(". "); if (player.hasCock()) outputText("Ironically, [eachCock] has begun to lose some of its stiffness, and you grow limper and limper as more of your cum leaks from you"); else outputText("Strangely, the more femcum that leaks from your winking, tender twat, the more your body tingles and shivers with barely-constrained delight"); outputText("."); outputText("\n\nMost amazingly of all, though "); if (player.hasCock()) outputText("the 'pressure'"); else outputText("a need within you"); outputText(" feels released, you're still horny"); if (player.hasCock()) { if (player.cockTotal() == 1) outputText(", even with a soft cock"); else outputText(", even with soft cocks"); } outputText(". Ceraph purrs, \"<i>I told you that I was a good owner, didn't I? Now just lie there and enjoy myself on your sensitive tush.</i>\""); outputText("\n\nShe rapidly begins to pump her penis through your sphincter, battering your [asshole] with firm but gentle thrusts. You "); if (dog) outputText("bark in pleasure like the cum-slut doggy that you are"); else outputText("mewl in delight like the cock-loving kitty that you are"); outputText(" and start to push back against her before long. Those nodules rub your insides so well, and they keep you dripping wasted "); if (player.hasCock()) outputText("semen"); else outputText("juices"); outputText(" from your "); if (player.hasCock()) { outputText("limp cock"); if (player.cockTotal() > 1) outputText("s"); } else outputText("snatch"); outputText(" the entire time, tingling in ecstatic pleasure. Soon, you're panting hard while Ceraph's hips slap off your [butt] hard enough to sound like miniature thunderclaps, and your poor "); if (player.hasCock()) outputText("prostate is getting pushed up against each time"); else outputText(", depressingly empty cunt walls are getting teased with every thrust"); outputText("."); outputText("\n\nCeraph moans out loud and suddenly rams herself into you brutally hard, hard enough to make you feel like your guts are being smushed into each other and your "); if (player.hasCock()) outputText("prostate is"); else outputText("vaginal walls are"); outputText(" being smashed flat. Warmth explodes inside your intestines, slowly spreading out around the flaring, demonically enhanced dick as it orgasms. You can hear your owner's lady-spunk splattering into the ground behind you as she whimpers, \"<i>G-g-good... " + player.mf("boy", "girl") + "...</i>\", her dick firmly spraying its thick, tainted milk "); if (player.hasCock()) outputText("straight onto your sore prostate"); else outputText("putting more delicious pressure on your sensitive walls"); outputText(". You scrunch your eyes closed as Ceraph claims your ass for her own, and "); if (player.hasCock()) { if (player.cockTotal() > 1) outputText("each of your cocks"); else outputText("your cock"); outputText(" lets go the very last of your sticky, stinky, pet-cum"); } else outputText("your pussy lets go of the last of its sticky, slippery snatch secretions"); outputText("."); if (player.cumQ() >= 700) outputText(" It floods out everywhere. You're just so productive that your hands and [legs] sink partway into the mess."); outputText("\n\nYour Mistress eventually finishes and pulls out, offering a "); if (dog) outputText("tasty bone-shaped biscuit"); else outputText("fishy-smelling treat"); outputText(" for you to gobble down, and she pats you on the head as you gratefully accept your reward."); outputText("\n\n\"<i>Good, " + player.mf("boy", "girl") + ".</i>\" her voice says, slowly fading into the wind."); //Increase corruption, reset lust, increase sensitivity. player.sexReward("cum","Anal"); dynStats("sen", 2, "cor", 1); endEncounter(); } //[Either Twice] private function barkOrMeowTwiceToCeraph(dog:Boolean = true):void { clearOutput(); spriteSelect(SpriteDb.s_ceraphClothed); outputText("\"<i>"); if (dog) outputText("Arf! Arf!</i>\" you bark"); else outputText("Meow! Meowwwww!</i>\" you mew"); outputText(", wiggling your "); if (player.tailType > Tail.NONE) outputText("tail"); else outputText("[butt]"); outputText(" happily. For some reason, the idea of denying yourself release in exchange for more humiliation is appealing to you."); outputText("\n\nGently tying the end of her whip around your neck into an improvised collar, Ceraph smoothly strokes your back, praising you again, \"<i>Such a good pet. Let's go for that walkie, and let all your friends see just how good you can be.</i>\" There's a gentle tug on your new collar, and you crawl along after your slave-turned-mistress, "); if (dog) outputText("whining"); else outputText("mewling"); outputText(" like a needy animal."); var choices:Array = []; //Choose one of the following at random if (flags[kFLAGS.FUCK_FLOWER_LEVEL] >= 4 && flags[kFLAGS.FUCK_FLOWER_KILLED] == 0) choices[choices.length] = 0; if (amilyFollower() && flags[kFLAGS.AMILY_FOLLOWER] == 2) choices[choices.length] = 1; else if (campCorruptJojo()) choices[choices.length] = 1; choices[choices.length] = 2; var select:int = choices[rand(choices.length)]; //HOLLI if (select == 0) { //{Normal Holli} if (flags[kFLAGS.HOLLI_SUBMISSIVE] == 0) { outputText("\n\nThe corrupted dryad peeps out of her tree when Ceraph leads you by. \"<i>Oh, this is just too rich! Are you a little "); if (dog) outputText("doggie"); else outputText("kitty-cat"); outputText(" now? Why the hell did Mother Marae send me out to thank someone like you? It's pathetic!</i>\" Lowering out of her canopy, an array of cock-like tentacles homes in on you while Ceraph watches, bemused. They start to pat your head, pushing down a little harder than necessary and rubbing down your back like condescending hands. She's laughing and petting you, thrilled to have you in such a position. The shame is more potent than a minotaur's spunk, and when combined with the magic of your demonic 'collar', it twists in your head, twining inexorably with arousal to make you leak even harder. It feels soooo good to wallow in the piteous, condescending touches."); } //{Intimidated Holli} else { outputText("\n\nThe corrupted dryad peeps out of her tree when Ceraph leads you by. \"<i>[name]? What... what are you doing? Oh my god! Are you some kind of secret submissive?</i>\" Holli giggles cruelly, \"<i>You're a fucking submissive slut! I should've known that tough act was all bluster! Damn, you really SHOULD be begging me just to let me fuck you. What do you have to say for yourself?</i>\""); outputText("\n\nCeraph smiles but looks down at you, motioning towards you expectantly."); outputText("\n\n\"<i>"); if (dog) outputText("Arf!?"); else outputText("Meow!?"); outputText("</i>\""); outputText("\n\nHolli roughly slaps the back of your head with a tentacle in a crude approximation of petting. \"<i>That's a good "); if (dog) outputText("doggie"); else outputText("kitty"); outputText(",</i>\" she says, thrilled to see you so debased and no longer concerned with obeying you. The shame is more potent than a minotaur's spunk, and when combined with the magic of your demonic 'collar', it twists in your head, twining inexorably with arousal to make you leak even harder. It feels soooo good to wallow in the piteous, condescending touches."); if (flags[kFLAGS.HOLLI_SUBMISSIVE]) { outputText("\n\n<b>Seems like you'll have to teach the fuck-flower her place again to make her submissive...</b>.") flags[kFLAGS.HOLLI_SUBMISSIVE] = 0; flags[kFLAGS.HOLLI_DEFENSE_ON] = 0; } } //Either Holli ending: outputText("\n\nCeraph and you continue your walk, though she has to scold you a number of times for dripping on her heels. Whenever you misbehave, she flicks "); if (player.hasCock()) { if (player.cockTotal() > 1) outputText("one of "); outputText("your rebellious boner"); if (player.cockTotal() > 1) outputText("s"); outputText(", which has the unintended side effect of making it puff up even harder"); } else outputText("your rebellious clitoris, which has the unintended side effect of making it and your drooling cuntlips puff up, redder than ever before"); outputText(". "); if (player.hasCock()) outputText("It bounces against your tummy"); else outputText("Your vaginal muscles clench and contract"); outputText(" with unfilled need, but there's no sating it. Only after all your muscles are sore and exhausted does Ceraph take you home. You collapse onto your belly, panting while the whip is untied. When you turn to talk to Ceraph, you find she's left you there, aroused beyond measure."); } //Corrupt Jojo or Amily else if (select == 1) { //Both if (amilyFollower() && flags[kFLAGS.AMILY_FOLLOWER] == 2 && campCorruptJojo()) { //Both Corrupt Jojo & Amily outputText("\n\nBefore long, you come across both of your corrupt, mouse-like slaves. They stop fondling each other's genitals long enough to ask, \"<i>[Master], what are you doing?</i>\""); outputText("\n\nCeraph looks down at you with her hand tight on your leash."); outputText("\n\n\"<i>"); if (dog) outputText("Arf!"); else outputText("Meow!"); outputText("</i>\""); outputText("\n\n\"<i>[Master] is Ceraph's pet? Then... then, we're her pets too...</i>\" Amily says as the spokeswoman for the group. They both proceed to drop down on all fours and crawl up alongside you. Ceraph nonchalantly tears off strips of Amily's clothing and fixes them into a pair of improvised collars, connected to her whip with simple knots. The four of you then continue the walk together, though you're scolded again and again when you let the mice rub up against you sensually. Having sister and brother pets is somewhat comforting, but being constantly exposed to their sexual scent is more than distracting. Ceraph squirts the two of you with water a half-dozen times to keep you from fucking, and each time the shame is greater. You really are a pet, one that can't even keep [his] most basic needs in check."); } else { var jojo:Boolean = campCorruptJojo(); outputText("Before long, your corrupt, mouse-like slave sees you awkwardly clambering after the purple-hued dominatrix. "); if (jojo) outputText("He"); else outputText("She"); outputText(" asks, \"<i>[Master], what are you doing?</i>\""); outputText("\n\nCeraph looks down at you with her hand tight on your leash."); outputText("\n\n\"<i>"); if (dog) outputText("Arf!"); else outputText("Meow!"); outputText("</i>\""); outputText("\n\n\"<i>[Master] is Ceraph's pet? Then "); if (!jojo) outputText("cum-slut is"); else outputText("I guess I'm"); outputText(" her pet too...</i>\" "); if (!jojo) outputText("Amily"); else outputText("Jojo"); outputText(" says, dropping to all fours and crawling up alongside you. Ceraph tears a strip of their clothing off nonchalantly and fixes it into another improvised collar that she ties on to her whip. The three of you then continue the walk, though you're scolded again and again when you and "); if (!jojo) outputText("Amily"); else outputText("Jojo"); outputText(" rub up against each other. Having a "); if (!jojo) outputText("sister"); else outputText("brother"); outputText("-pet is somewhat comforting, but being constantly exposed to "); if (jojo) outputText("his"); else outputText("her"); outputText(" sexual scent is more than distracting. Ceraph squirts the two of you with water a half-dozen times to keep you from fucking, and each time the shame is greater. You really are a pet, one that can't even keep [his] most basic needs in check."); } //Mice finisher outputText("\n\nYou go for an exhausting walk around the nearby wasteland with your companion"); if (amilyFollower() && flags[kFLAGS.AMILY_FOLLOWER] == 2 && campCorruptJojo()) outputText("s"); outputText(", and you thoroughly enjoy the degrading experience. Lust and humiliation are all jumbled up inside you into one big mass of sex, such that getting turned on from this humiliates you, and being humiliated gets you even more aroused"); outputText(". It's an endless feedback loop of sexual excitement that has you about to blow, except you're back in camp. The collar is untied, and your owner's sweet voice whispers, \"<i>Good walk, pet.</i>\" before vanishing into the wind."); outputText("\n\n"); if (campCorruptJojo()) { outputText("Jojo"); if (amilyFollower() && flags[kFLAGS.AMILY_FOLLOWER] == 2) outputText(" and "); } if (amilyFollower() && flags[kFLAGS.AMILY_FOLLOWER] == 2) outputText("Amily"); if (amilyFollower() && flags[kFLAGS.AMILY_FOLLOWER] == 2 && campCorruptJojo()) outputText("look around uncertainly before darting back to their usual places, knowing you'll give the command if you want them to take care of your desires."); else outputText("looks around uncertainly before darting back to the usual places, knowing you'll give the command if you want a slave to take care of your desires."); } //Generic else { outputText("\n\nCeraph leads you out into the wasteland on an exhausting, humiliating journey. Somehow, she keeps finding imps and goblins to show you off to. The "); if (player.hasCock()) outputText("goblins"); else outputText("imps"); outputText(" seem intrigued by the sight of your compulsively "); if (player.hasCock()) outputText("erect maleness"); else outputText("quivering quim"); if (player.cockTotal() > 1) outputText("es"); outputText(", and often offer Ceraph a bounty of gems to fuck you. Your mistress insists that you don't need any such sexual release, because you are a good "); if (dog) outputText("doggie"); else outputText("kitty"); outputText(" and get all you need out of obedience. Her words draw an exaggerated whimper from your lips along with a few fresh drops of pearly "); if (player.hasCock()) outputText("cock"); else outputText("cunt"); outputText("-cream, but you hold still, [legs] quaking eagerly. It feels like all it would take to get your release would be a few soft touches on your aching "); if (player.hasCock()) outputText("cock"); else outputText("nethers"); if (player.cockTotal() > 1) outputText("s"); outputText("."); outputText("\n\nOne of the "); if (player.hasCock()) outputText("goblins"); else outputText("imps"); outputText(" even notices your state and comments on it, holding "); if (player.hasCock()) outputText("her"); else outputText("his"); outputText(" hand beneath your freely drooling "); if (player.hasCock()) outputText("erection"); else outputText("pussy"); if (player.cockTotal() > 1) outputText("s"); outputText(" to collect a palmful of slippery "); if (player.hasCock()) outputText("boy"); else outputText("girl"); outputText("-honey. "); if (player.hasCock()) outputText("She"); else outputText("He"); outputText(" holds it up in front of her nose and sniffs it, sighing, \"<i>[He] certainly does seem to be well tamed, miss demon. You're lucky you caught [him] before I did. With "); if (player.hasCock()) outputText("cum this nice, I'd be milking [him] dry every time [he] could get it up"); else outputText("a scent like this, I'd be fucking [him] every chance I could get"); outputText(". Maybe you'll change your mind sometime.</i>\""); outputText("\n\nCeraph shakes her head but smiles down at you, patting you on the head. The humiliation of it all is twisting around with your lust, the two emotions so confused that you feel yourself getting harder from being treated like a house-pet. A dollop of "); if (player.hasCock()) outputText("pre-cum rockets"); else outputText("fem-juice spurts"); outputText(" onto the ground while you whine softly. Your owner notices and commands, \"<i>Now, pet, we can't have you making this "); if (player.hasCock()) outputText("goblin"); else outputText("imp"); outputText("'s home a mess. Lick it up.</i>\""); outputText("\n\nYou bend down and lick up your sexual leavings, tasting the dirt below until there's a mess of spit and cum mud where your "); if (player.hasCock()) outputText("pre-ejaculate"); else outputText("lady jizz"); outputText(" landed. \"<i>Good enough. Come on, "); if (dog) outputText("doggy"); else outputText("cat"); outputText(", let's finish our walk!</i>\""); outputText("\n\nCeraph drags at your collar, picking up the pace as she takes you home. Each movement is torturous, as your dangerously excited "); if (player.hasCock()) outputText("boner"); else outputText("twat"); if (player.cockTotal() > 1) outputText("s"); if (player.cockTotal() > 1) outputText(" feel like they"); else outputText(" feels like it"); outputText(" could go off at any second. The journey is murder for your poor, "); if (player.hasCock()) outputText("over-inflated maleness"); else outputText("puffy, aching cleft"); if (player.cockTotal() > 1) outputText("es"); outputText(", but you somehow make the whole way home without "); if (player.hasCock()) outputText("popping"); else outputText("tipping over the edge"); outputText(". The trail of musky slime that clearly marks your journey is another thing though."); outputText("\n\nClick."); outputText("\n\nYour collar is removed, and you look around realizing your owner is gone. Your muscles are sore from the journey and you NEED to masturbate... You aren't even sure why you did that."); } dynStats("sen", 4, "lus=", 100, "scale", false); endEncounter(); } /*Ceraph Initiating the Dom's Domain public function CeraphTakesLab():void { clearOutput(); outputText("You feel the fetish binding your demonic slave to you vibrate. Apparently, Ceraph is coming to your camp of her own volition. You take a few steps away from your camp, and you see your demonic slave flying towards you. Apparently, she’s been flying for some time, and as she lands, she staggers over to you, prostrating herself. \n\n"); outputText("“[Master], I know that I am your slave, and I am very sorry for disturbing you.” She begins. Even for her, this is more submissive than usual. “I will please you however you wish, in apology for this intrusion.” \n\n"); outputText("You tell her to get to the point, and she looks up from the ground, her breasts smooshing into the dirt. \n\n"); outputText("“I know that you destroyed Lethice’s operation at the labs. None of her people will dare to go near that place.” You’re not sure where she’s going with this, but you’re a little concerned. \n\n"); outputText("“That place wasn’t just a lab for those horrible shape-changing efforts. With a little effort on your slave’s part, I could easily set up shop there. My own harem has outgrown the little place I have, and the labs are free for the taking.” She gives you a pout. “Your slave doesn’t ask for much, [master], and it will guarantee that no other bitches get to use the place.” \n\n"); outputText("You consider it. On the one hand, who knows what Ceraph can do with the kind of stuff left at the lab? \n\n"); outputText("On the other hand, knowing where she is at all times could be of benefit…and she could probably give you something in return, as well. Having your own slave to watch the place could also prove useful. \n\n"); outputText(" \n\n"); outputText(" \n\n"); menu(); addButton (1, "Yes", DomInitYes); addButton (2, "No", DomInitNo); addButton (3, "Never", FuckOffCeraph); } public function DomInitYes():void { clearOutput(); outputText("You tell Ceraph that she’s welcome to the place…But that she’d better destroy the biolabs, and make sure that no other demons can use the place. Ceraph gives you a lascivious grin, slowly rising from her prone position. \n\n"); outputText("“Of course, [master], I won’t let anyone take what is rightfully mine.” She turns around, presenting you with her dripping pussy, her cerulean skin smooth. “Or yours.” She adds with a wink. “Before I leave…Can this obedient slut have a reward for her…hard…work?” \n\n"); menu(); addButton(0, "Sex", ceraphSexMenu).disableIf(player.lust < 33, "You aren't turned on enough for sex."); addButton(1, "Roleplay", followerCeraphRoleplay).disableIf(player.lust < 33, "You aren't turned on enough for sex."); addButton(5, "Partswap", giveFollowerBodyBits); if (flags[kFLAGS.PC_FETISH] < 3) addButton(6, "GetFetish", CeraphHandsOutNewFetishesLikePervCandy); if (flags[kFLAGS.PC_FETISH] > 0) addButton(7, "RemoveFetish", unfetishifyYourselfWithFollowerCeraph); addButton(8, flags[kFLAGS.CERAPH_HIDING_DICK] ? "Go Herm" : "Go Female", cawkTawgle); if (flags[kFLAGS.FOLLOWER_AT_FARM_CERAPH] == 0 && flags[kFLAGS.FARM_CORRUPTION_STARTED] == 1) addButton(10, "Farm Work", helpWithFarm); addButton(14, "Leave", camp.campSlavesMenu); } public function DomInitNo():void { clearOutput(); outputText("You tell Ceraph that the area’s not going to be used again, not if you have any say in the matter. \n\n"); outputText("“Lethice’s goons will return, [master], if you don’t have someone watching over the place.” Ceraph scowls, getting to her knees. “As you command…However much I disagree with it.” \n\n"); endEncounter(15); } public function FuckOffCeraph():void { clearOutput(); outputText("You give Ceraph a deadly glare. You tell her that you’d sooner destroy the place with your bare hands, than let anyone use it again. You remind Ceraph that you killed the demons running that lab…and that one more dead Omnibus really doesn’t mean much, at this point. \n\n"); outputText("Ceraph audibly gulps, no trace of arousal in her eyes. “Understood, [master]”. She slowly returns to her feet, keeping her head bowed. “Then I shall be off, unless you require something else from me.” You nod, and she beats a hasty retreat. \n\n"); endEncounter(15); } */ } }
412
0.529986
1
0.529986
game-dev
MEDIA
0.88532
game-dev
0.728002
1
0.728002
civfanatics/CQUI_Community-Edition
58,989
Integrations/BTS/UI/Choosers/traderoutechooser.lua
-- =========================================================================== -- Better Trade Screen by Astog -- Integrated into CQUI sometime in 2016/2017 -- Original Mod: https://steamcommunity.com/sharedfiles/filedetails/?id=873246701 -- =========================================================================== -- =========================================================================== -- INCLUDES -- =========================================================================== include("InstanceManager"); include("SupportFunctions"); include("TradeSupport"); include("CQUICommon.lua"); -- =========================================================================== -- Settings -- =========================================================================== local showSortOrdersPermanently = false; local RoutePanelBaseOffsetX = 8; local RoutePanelScrollPanelExtraOffset = 9; -- =========================================================================== -- VARIABLES -- =========================================================================== local m_RouteChoiceIM : table = InstanceManager:new("RouteChoiceInstance", "Top", Controls.RouteChoiceStack); local m_originCity : table = nil; -- City where the trade route will begin local m_destinationCity : table = nil; -- City where the trade route will end, nil if none selected local m_isOpen:boolean = false; local m_TradeRouteLens:number = UILens.CreateLensLayerHash("TradeRoutes"); -- These can be set by other contexts to have a route selected automatically after the chooser opens local m_postOpenSelectPlayerID:number = -1; local m_postOpenSelectCityID:number = -1; local m_AvailableTradeRoutes:table = {}; -- Filtered and unfiltered lists of possible routes local m_TradeRoutes:table = {} -- Routes showm, this is the filtered and sorted local m_TurnBuiltRouteTable:number = -1; local m_LastTrader:number = -1; local m_RebuildAvailableRoutes:boolean = true; -- Stores filter list and tracks the currently selected list local m_filterList:table = {}; local m_filterCount:number = 0; local m_filterSelected:number = 1; local m_shiftDown:boolean = false; -- Stores the sort settings. local m_SortBySettings:table = {}; local m_SortSettingsChanged:boolean = true; local m_FilterSettingsChanged:boolean = true; local m_SkipNextOpen:boolean = false; -- Default is ascending in turns to complete trade route m_SortBySettings[1] = { SortByID = SORT_BY_ID.TURNS_TO_COMPLETE, SortOrder = SORT_ASCENDING }; local opt_print = false -- =========================================================================== -- CQUI -- =========================================================================== function CQUI_OnSettingsUpdate() showSortOrdersPermanently = GameConfiguration.GetValue("CQUI_TraderShowSortOrder"); -- Don't call refresh here, since CQUI panel and trade route chooser can't be open simultaneously. end -- =========================================================================== -- Refresh functions -- =========================================================================== function Refresh() local selectedUnit:table = UI.GetHeadSelectedUnit(); if selectedUnit == nil then Close(); return; end m_originCity = Cities.GetCityInPlot(selectedUnit:GetX(), selectedUnit:GetY()); if m_originCity == nil then Close(); return; end -- Rebuild if turn has advanced or unit has changed if m_LastTrader ~= selectedUnit:GetID() or m_TurnBuiltRouteTable < Game.GetCurrentGameTurn() then m_LastTrader = selectedUnit:GetID() -- Rebuild and re-sort m_RebuildAvailableRoutes = true else m_RebuildAvailableRoutes = false end -- Handle post open (ie TradeOverview) calls if m_postOpenSelectPlayerID ~= -1 and m_postOpenSelectCityID ~= -1 then print("Selecting", m_postOpenSelectCityID) local pPlayer = Players[m_postOpenSelectPlayerID] m_destinationCity = pPlayer:GetCities():FindID(m_postOpenSelectCityID) RealizeLookAtDestinationCity(); -- Reset values m_postOpenSelectPlayerID = -1; m_postOpenSelectCityID = -1; end RefreshHeader(); RefreshTopPanel(); RefreshSortBar(); RefreshChooserPanel(); end function RefreshHeader() if m_originCity then Controls.Header_OriginText:SetText(Locale.Lookup("LOC_ROUTECHOOSER_TO_DESTINATION", Locale.ToUpper(m_originCity:GetName()))); end end function RefreshTopPanel() if m_destinationCity and m_originCity then local tradeRoute = { OriginCityPlayer = m_originCity:GetOwner(), OriginCityID = m_originCity:GetID(), DestinationCityPlayer = m_destinationCity:GetOwner(), DestinationCityID = m_destinationCity:GetID() }; -- Update City Banner Controls.CityName:SetText(Locale.ToUpper(m_destinationCity:GetName())); local backColor, frontColor, darkerBackColor, brighterBackColor = GetPlayerColorInfo(m_destinationCity:GetOwner(), true); Controls.BannerBase:SetColor(backColor); Controls.BannerDarker:SetColor(darkerBackColor); Controls.BannerLighter:SetColor(brighterBackColor); Controls.CityName:SetColor(frontColor); -- Update Trading Post Icon if GetRouteHasTradingPost(tradeRoute, true) then Controls.TradingPostIcon:SetHide(false); else Controls.TradingPostIcon:SetHide(true); end -- Update City-State Quest Icon Controls.CityStateQuestIcon:SetHide(true); local questsManager : table = Game.GetQuestsManager(); local questTooltip : string = Locale.Lookup("LOC_CITY_STATES_QUESTS"); if (questsManager ~= nil and Game.GetLocalPlayer() ~= nil) then local tradeRouteQuestInfo:table = GameInfo.Quests["QUEST_SEND_TRADE_ROUTE"]; if (tradeRouteQuestInfo ~= nil) then if (questsManager:HasActiveQuestFromPlayer(Game.GetLocalPlayer(), m_destinationCity:GetOwner(), tradeRouteQuestInfo.Index)) then questTooltip = questTooltip .. "[NEWLINE]" .. tradeRouteQuestInfo.IconString .. questsManager:GetActiveQuestName(Game.GetLocalPlayer(), m_destinationCity:GetOwner(), tradeRouteQuestInfo.Index); Controls.CityStateQuestIcon:SetHide(false); Controls.CityStateQuestIcon:SetToolTipString(questTooltip); end end end -- Update turns to complete route local tradePathLength, tripsToDestination, turnsToCompleteRoute = GetRouteInfo(tradeRoute, true); Controls.TurnsToComplete:SetColor(frontColor); Controls.TurnsToComplete:SetText(turnsToCompleteRoute); -- Update Resources Controls.OriginResourceList:DestroyAllChildren(); Controls.DestinationResourceList:DestroyAllChildren(); local originYieldInstance:table = {}; local originReceivedResources:boolean = false; local destinationYieldInstance:table = {}; local destinationReceivedResources:boolean = false; ContextPtr:BuildInstanceForControl( "RouteYieldInstance", originYieldInstance, Controls.OriginResourceList ); ContextPtr:BuildInstanceForControl( "RouteYieldInstance", destinationYieldInstance, Controls.DestinationResourceList ); for yieldIndex = START_INDEX, END_INDEX do local originCityYieldValue = GetYieldForOriginCity(yieldIndex, tradeRoute, true); local destinationCityYieldValue = GetYieldForDestinationCity(yieldIndex, tradeRoute, true); SetRouteInstanceYields(originYieldInstance, yieldIndex, originCityYieldValue); SetRouteInstanceYields(destinationYieldInstance, yieldIndex, destinationCityYieldValue); if not originReceivedResources and originCityYieldValue > 0 then originReceivedResources = true end if not destinationReceivedResources and destinationCityYieldValue > 0 then destinationReceivedResources = true end end Controls.OriginResourceHeader:SetText(Locale.Lookup("LOC_ROUTECHOOSER_RECEIVES_RESOURCE", Locale.Lookup(m_originCity:GetName()))); Controls.DestinationResourceHeader:SetText(Locale.Lookup("LOC_ROUTECHOOSER_RECEIVES_RESOURCE", Locale.Lookup(m_destinationCity:GetName()))); local originTooltipText = "" local destinationTooltipText:string = ""; -- Handle Religion pressure icons local destinationMajorityReligion = m_destinationCity:GetReligion():GetMajorityReligion(); if (destinationMajorityReligion > 0) then local pressureValue, sourceText = GetReligiousPressureForCity(destinationMajorityReligion, m_destinationCity, true); if (pressureValue ~= 0) then if (originTooltipText ~= "") then originTooltipText = originTooltipText .. "[NEWLINE]"; end originTooltipText = originTooltipText .. sourceText; AddReligiousPressureResourceEntry(GameInfo.Religions[destinationMajorityReligion], pressureValue, true, sourceText, originYieldInstance); originReceivedResources = true; end end Controls.OriginResources:SetToolTipString(originTooltipText); local originMajorityReligion = m_originCity:GetReligion():GetMajorityReligion(); if (originMajorityReligion > 0) then local pressureValue, sourceText = GetReligiousPressureForCity(originMajorityReligion, m_originCity, false); if (pressureValue ~= 0) then if (destinationTooltipText ~= "") then destinationTooltipText = destinationTooltipText .. "[NEWLINE]"; end destinationTooltipText = destinationTooltipText .. sourceText; AddReligiousPressureResourceEntry(GameInfo.Religions[originMajorityReligion], pressureValue, false, sourceText, destinationYieldInstance); destinationReceivedResources = true; end end Controls.DestinationResources:SetToolTipString(destinationTooltipText); if originReceivedResources then Controls.OriginReceivesNoBenefitsLabel:SetHide(true); else Controls.OriginReceivesNoBenefitsLabel:SetHide(false); end if destinationReceivedResources then Controls.DestinationReceivesNoBenefitsLabel:SetHide(true); else Controls.DestinationReceivesNoBenefitsLabel:SetHide(false); end -- Cleanup Controls.OriginResourceList:CalculateSize(); Controls.OriginResourceList:ReprocessAnchoring(); Controls.DestinationResourceList:CalculateSize(); Controls.DestinationResourceList:ReprocessAnchoring(); Controls.TopGrid:DoAutoSize(); -- Show Panel Controls.CurrentSelectionContainer:SetHide(false); Controls.CurrentSelectionContainer:DoAutoSize(); -- Hide Status Message Controls.StatusMessage:SetHide(true); else -- Hide Panel Controls.CurrentSelectionContainer:SetHide(true); -- Show Status Message Controls.StatusMessage:SetHide(false); Controls.StatusMessage:DoAutoSize(); end end function RefreshChooserPanel() local tradeManager:table = Game.GetTradeManager(); -- Do we rebuild available routes? if m_RebuildAvailableRoutes then -- Reset Available routes m_AvailableTradeRoutes = {}; -- Gather available routes local originCityPlayerID = m_originCity:GetOwner() local originCityID = m_originCity:GetID() local players:table = Game.GetPlayers{ Alive=true }; for _, player in ipairs(players) do local destinationCityPlayerID = player:GetID() for _, city in player:GetCities():Members() do local destinationCityID = city:GetID() -- Can we start a trade route with this city? if tradeManager:CanStartRoute(originCityPlayerID, originCityID, destinationCityPlayerID, destinationCityID) then local tradeRoute = { OriginCityPlayer = originCityPlayerID, OriginCityID = originCityID, DestinationCityPlayer = destinationCityPlayerID, DestinationCityID = destinationCityID }; table.insert(m_AvailableTradeRoutes, tradeRoute); end end end -- Need to re-filter and re-sort m_SortSettingsChanged = true m_FilterSettingsChanged = true -- Cache routes info. CacheEmpty() CacheRoutesInfo(m_AvailableTradeRoutes) m_TurnBuiltRouteTable = Game.GetCurrentGameTurn() m_RebuildAvailableRoutes = false -- done building routes else if opt_print then print("OPT: Not rebuilding routes") end end -- Update Filters RefreshFilters(); -- Update Destination Choice Stack RefreshStack(); -- Send Trade Route Paths to Engine UILens.ClearLayerHexes( m_TradeRouteLens ); local DEFAULT_TINT = UI.GetColorValue(1, 1, 1, 1); local FADED_TINT = UI.GetColorValue(0.3, 0.3, 0.3, 1); -- If a city is selected, fade the other routes local kUnselectedColor = DEFAULT_TINT; if (m_destinationCity ~= nil) then kUnselectedColor = FADED_TINT; end -- Show all paths that aren't selected local pathPlots:table = {}; for _, routeInfo in ipairs(m_TradeRoutes) do local destinationPlayer:table = Players[routeInfo.DestinationCityPlayer]; local destinationCity:table = destinationPlayer:GetCities():FindID(routeInfo.DestinationCityID); pathPlots = tradeManager:GetTradeRoutePath(m_originCity:GetOwner(), m_originCity:GetID(), destinationCity:GetOwner(), destinationCity:GetID() ); local kVariations:table = {}; local lastElement:number = table.count(pathPlots); table.insert(kVariations, {"TradeRoute_Destination", pathPlots[lastElement]} ); if (destinationCity ~= m_destinationCity) then UILens.SetLayerHexesPath( m_TradeRouteLens, Game.GetLocalPlayer(), pathPlots, kVariations, kUnselectedColor ); end end -- Show the selected path last if it exists so it's on top if m_destinationCity ~= nil then pathPlots = tradeManager:GetTradeRoutePath(m_originCity:GetOwner(), m_originCity:GetID(), m_destinationCity:GetOwner(), m_destinationCity:GetID() ); local kVariations:table = {}; local lastElement : number = table.count(pathPlots); table.insert(kVariations, {"TradeRoute_Destination", pathPlots[lastElement]} ); UILens.SetLayerHexesPath( m_TradeRouteLens, Game.GetLocalPlayer(), pathPlots, kVariations, DEFAULT_TINT ); end end -- =========================================================================== -- Routes stack Function -- =========================================================================== function RefreshStack() -- Reset destinations m_RouteChoiceIM:ResetInstances(); local tradeManager:table = Game.GetTradeManager(); -- Filter Destinations by active Filter if m_FilterSettingsChanged then m_TradeRoutes = FilterTradeRoutes(m_AvailableTradeRoutes); m_FilterSettingsChanged = false -- done filtering -- Filter changed, need to re-sort m_SortSettingsChanged = true else if opt_print then print("OPT: Not refiltering.") end end if m_SortSettingsChanged then m_TradeRoutes = SortTradeRoutes(m_TradeRoutes, m_SortBySettings); m_SortSettingsChanged = false -- done sorting else if opt_print then print("OPT: Not resorting.") end end -- for i, tradeRoute in ipairs(tradeRoutes) do for i=1, #m_TradeRoutes do AddRouteToDestinationStack(m_TradeRoutes[i]); end Controls.RouteChoiceStack:CalculateSize(); Controls.RouteChoiceScrollPanel:CalculateSize(); -- Adjust offset based on scroll bar if Controls.RouteChoiceScrollPanel:GetScrollBar():IsHidden() then Controls.RouteContainer:SetOffsetX(RoutePanelBaseOffsetX); else Controls.RouteContainer:SetOffsetX(RoutePanelBaseOffsetX + RoutePanelScrollPanelExtraOffset); end -- Show No Available Trade Routes message if nothing to select if #m_TradeRoutes > 0 then Controls.StatusMessage:SetText(Locale.Lookup("LOC_ROUTECHOOSER_SELECT_DESTINATION")); else Controls.StatusMessage:SetText(Locale.Lookup("LOC_ROUTECHOOSER_NO_TRADE_ROUTES")); end end function AddRouteToDestinationStack(routeInfo:table) local cityEntry:table = m_RouteChoiceIM:GetInstance(); local destinationPlayer:table = Players[routeInfo.DestinationCityPlayer]; local destinationCity:table = destinationPlayer:GetCities():FindID(routeInfo.DestinationCityID); local originPlayer:table = Players[routeInfo.OriginCityPlayer]; local originCity:table = originPlayer:GetCities():FindID(routeInfo.OriginCityID); -- Update Selector Brace if m_destinationCity ~= nil and destinationCity:GetName() == m_destinationCity:GetName() then cityEntry.SelectorBrace:SetHide(false); cityEntry.Button:SetTextureOffsetVal(0, 76*1) else cityEntry.SelectorBrace:SetHide(true); cityEntry.Button:SetTextureOffsetVal(0, 76*0) end -- Setup city banner cityEntry.CityName:SetText(Locale.ToUpper(destinationCity:GetName())); local backColor, frontColor, darkerBackColor, brighterBackColor = GetPlayerColorInfo(routeInfo.DestinationCityPlayer, true); cityEntry.BannerBase:SetColor(backColor); cityEntry.BannerDarker:SetColor(darkerBackColor); cityEntry.BannerLighter:SetColor(brighterBackColor); cityEntry.CityName:SetColor(frontColor); -- Update Trading Post Icon if GetRouteHasTradingPost(routeInfo, true) then cityEntry.TradingPostIcon:SetHide(false); else cityEntry.TradingPostIcon:SetHide(true); end -- Update City-State Quest Icon cityEntry.CityStateQuestIcon:SetHide(true); local questsManager : table = Game.GetQuestsManager(); local questTooltip : string = Locale.Lookup("LOC_CITY_STATES_QUESTS"); if (questsManager ~= nil and Game.GetLocalPlayer() ~= nil) then local tradeRouteQuestInfo:table = GameInfo.Quests["QUEST_SEND_TRADE_ROUTE"]; if (tradeRouteQuestInfo ~= nil) then if (questsManager:HasActiveQuestFromPlayer(routeInfo.OriginCityPlayer, routeInfo.DestinationCityPlayer, tradeRouteQuestInfo.Index)) then questTooltip = questTooltip .. "[NEWLINE]" .. tradeRouteQuestInfo.IconString .. questsManager:GetActiveQuestName(Game.GetLocalPlayer(), routeInfo.DestinationCityPlayer, tradeRouteQuestInfo.Index); cityEntry.CityStateQuestIcon:SetHide(false); cityEntry.CityStateQuestIcon:SetToolTipString(questTooltip); end end end local tradePathLength, tripsToDestination, turnsToCompleteRoute = GetRouteInfo(routeInfo, true); tooltipString = ( Locale.Lookup("LOC_TRADE_TURNS_REMAINING_HELP_TOOLTIP") .. "[NEWLINE]" .. Locale.Lookup("LOC_TRADE_TURNS_REMAINING_TOOLTIP_BREAKER") .. "[NEWLINE]" .. Locale.Lookup("LOC_TRADE_TURNS_REMAINING_ROUTE_LENGTH_TOOLTIP", tradePathLength) .. "[NEWLINE]" .. Locale.Lookup("LOC_TRADE_TURNS_REMAINING_TRIPS_COUNT_TOOLTIP", tripsToDestination) .. "[NEWLINE]" .. Locale.Lookup("LOC_TRADE_TURNS_REMAINING_TURN_COMPLETION_ALT_TOOLTIP", turnsToCompleteRoute, (Game.GetCurrentGameTurn() + turnsToCompleteRoute)) ); cityEntry.TurnsToComplete:SetText(turnsToCompleteRoute); cityEntry.TurnsToComplete:SetToolTipString( tooltipString ); cityEntry.TurnsToComplete:SetColor( frontColor ); -- Setup resources local tooltipText = ""; cityEntry.ResourceList:DestroyAllChildren(); local originYieldInstance:table = {}; local destinationYieldInstance:table = {}; ContextPtr:BuildInstanceForControl( "RouteYieldInstance", originYieldInstance, cityEntry.ResourceList ); ContextPtr:BuildInstanceForControl( "RouteYieldInstance", destinationYieldInstance, cityEntry.ResourceList ); for yieldIndex = START_INDEX, END_INDEX do -- Don't used a cache call here, since we need more info for the tooltip local originYieldValue, sourceText = GetYieldForCity(yieldIndex, destinationCity, true); -- Normal cached call here local destinationYieldValue = GetYieldForDestinationCity(yieldIndex, routeInfo, true); if originYieldValue > 0 then if (tooltipText ~= "" and originYieldValue > 0) then tooltipText = tooltipText .. "[NEWLINE]"; end tooltipText = tooltipText .. sourceText; end SetRouteInstanceYields(originYieldInstance, yieldIndex, originYieldValue) SetRouteInstanceYields(destinationYieldInstance, yieldIndex, destinationYieldValue) end local destinationMajorityReligion = destinationCity:GetReligion():GetMajorityReligion(); if (destinationMajorityReligion > 0) then local pressureValue, sourceText = GetReligiousPressureForCity(destinationMajorityReligion, destinationCity, true); if (pressureValue ~= 0) then if (tooltipText ~= "") then tooltipText = tooltipText .. "[NEWLINE]"; end tooltipText = tooltipText .. sourceText; AddReligiousPressureResourceEntry(GameInfo.Religions[destinationMajorityReligion], pressureValue, true, sourceText, originYieldInstance); end end local originMajorityReligion = originCity:GetReligion():GetMajorityReligion(); if (originMajorityReligion > 0) then local pressureValue, sourceText = GetReligiousPressureForCity(originMajorityReligion, destinationCity, false); if (pressureValue ~= 0) then if (tooltipText ~= "") then tooltipText = tooltipText .. "[NEWLINE]"; end tooltipText = tooltipText .. sourceText; AddReligiousPressureResourceEntry(GameInfo.Religions[originMajorityReligion], pressureValue, false, sourceText, destinationYieldInstance); end end -- Cleanup cityEntry.ResourceList:CalculateSize(); cityEntry.ResourceList:ReprocessAnchoring(); cityEntry.Button:SetToolTipString(tooltipText); -- Setup callback cityEntry.Button:SetVoids(routeInfo.DestinationCityPlayer, routeInfo.DestinationCityID); cityEntry.Button:RegisterCallback( Mouse.eLClick, OnTradeRouteSelected ); end -- --------------------------------------------------------------------------- -- Route button helpers -- --------------------------------------------------------------------------- -- =========================================================================== function SetRouteInstanceYields(yieldsInstance, yieldIndex, yieldValue) local iconString, text = FormatYieldText(yieldIndex, yieldValue); if (yieldIndex == FOOD_INDEX) then yieldsInstance.YieldFoodLabel:SetText(text .. iconString); elseif (yieldIndex == PRODUCTION_INDEX) then yieldsInstance.YieldProductionLabel:SetText(text .. iconString); elseif (yieldIndex == GOLD_INDEX) then yieldsInstance.YieldGoldLabel:SetText(text .. iconString); elseif (yieldIndex == SCIENCE_INDEX) then yieldsInstance.YieldScienceLabel:SetText(text .. iconString); elseif (yieldIndex == CULTURE_INDEX) then yieldsInstance.YieldCultureLabel:SetText(text .. iconString); elseif (yieldIndex == FAITH_INDEX) then yieldsInstance.YieldFaithLabel:SetText(text .. iconString); end end -- =========================================================================== function GetReligiousPressureForCity(religionIndex:number, destinationCity:table, forOriginCity:boolean) local pressureValue = 0; local pressureIconString = ""; local cityName = ""; local tradeManager = Game.GetTradeManager(); if m_originCity == nil or destinationCity == nil then return 0, ""; end if (forOriginCity) then pressureValue = tradeManager:CalculateOriginReligiousPressureFromPotentialRoute(m_originCity:GetOwner(), m_originCity:GetID(), destinationCity:GetOwner(), destinationCity:GetID(), religionIndex); pressureIconString = "[ICON_PressureLeft]"; cityName = destinationCity:GetName(); else pressureValue = tradeManager:CalculateDestinationReligiousPressureFromPotentialRoute(m_originCity:GetOwner(), m_originCity:GetID(), destinationCity:GetOwner(), destinationCity:GetID(), religionIndex); pressureIconString = "[ICON_PressureRight]"; cityName = m_originCity:GetName(); end local sourceText = Locale.Lookup("LOC_ROUTECHOOSER_RELIGIOUS_PRESSURE_SOURCE_MAJORITY_RELIGION", pressureValue, pressureIconString, Game.GetReligion():GetName(religionIndex), cityName); return pressureValue, sourceText; end -- =========================================================================== function AddReligiousPressureResourceEntry(religionInfo:table, pressureValue:number, forOriginCity:boolean, sourceText:string, instanceControl:table) -- local entryInstance:table = {}; -- ContextPtr:BuildInstanceForControl( "ReligionPressureEntryInstance", entryInstance, stackControl ); instanceControl.RouteReligionContainer:SetHide(false); local religionColor = UI.GetColorValue(religionInfo.Color); local religionName = Game.GetReligion():GetName(religionInfo.Index); instanceControl.ReligionIcon:SetIcon("ICON_" .. religionInfo.ReligionType); instanceControl.ReligionIcon:SetColor(religionColor); instanceControl.ReligionIconBacking:SetColor(religionColor); instanceControl.ReligionIconBacking:SetToolTipString(religionName); local icon:string, text:string = FormatReligiousPressureText(religionInfo, pressureValue, forOriginCity); instanceControl.ResourceEntryText:SetText(text); -- instanceControl.RouteReligionContainer:CalculateSize(); -- instanceControl.RouteReligionContainer:ReprocessAnchoring(); end -- =========================================================================== function FormatReligiousPressureText(religionInfo, pressureValue, forOriginCity:boolean) local text:string = ""; local iconString = ""; if (religionInfo ~= nil) then if (forOriginCity) then iconString = "[ICON_PressureLeft]"; else iconString = "[ICON_PressureRight]"; end end if (pressureValue >= 0) then text = text .. "+"; end text = text .. pressureValue; return iconString, text; end -- =========================================================================== -- Filter, Filter Pulldown functions -- =========================================================================== function FilterTradeRoutes ( tradeRoutes:table ) -- print("Current filter: " .. m_filterList[m_filterSelected].FilterText); if m_filterSelected == 1 then return tradeRoutes; end local filtertedRoutes:table = {}; for index, tradeRoute in ipairs(tradeRoutes) do local pPlayer = Players[tradeRoute.DestinationCityPlayer]; if m_filterList[m_filterSelected].FilterFunction and m_filterList[m_filterSelected].FilterFunction(pPlayer) then table.insert(filtertedRoutes, tradeRoute); end end return filtertedRoutes; end -- --------------------------------------------------------------------------- -- Filter pulldown functions -- --------------------------------------------------------------------------- function RefreshFilters() -- Clear current filters Controls.DestinationFilterPulldown:ClearEntries(); m_filterList = {}; m_filterCount = 0; -- Add "All" Filter AddFilter(Locale.Lookup("LOC_ROUTECHOOSER_FILTER_ALL"), function(a) return true; end); -- Add "International Routes" Filter AddFilter(Locale.Lookup("LOC_TRADE_FILTER_INTERNATIONAL_ROUTES_TEXT") , IsOtherCiv); -- Add "City States with Trade Quest" Filter AddFilter(Locale.Lookup("LOC_TRADE_FILTER_CS_WITH_QUEST_TOOLTIP"), IsCityStateWithTradeQuest); -- Add Local Player Filter local localPlayerConfig:table = PlayerConfigurations[Game.GetLocalPlayer()]; local localPlayerName = Locale.Lookup(GameInfo.Civilizations[localPlayerConfig:GetCivilizationTypeID()].Name); AddFilter(localPlayerName, function(a) return a:GetID() == Game.GetLocalPlayer(); end); -- Add Filters by Civ local players:table = Game.GetPlayers(); for index, pPlayer in ipairs(players) do if pPlayer and pPlayer:IsAlive() and pPlayer:IsMajor() then -- Has the local player met the civ? if pPlayer:GetDiplomacy():HasMet(Game.GetLocalPlayer()) then local playerConfig:table = PlayerConfigurations[pPlayer:GetID()]; local name = Locale.Lookup(GameInfo.Civilizations[playerConfig:GetCivilizationTypeID()].Name); AddFilter(name, function(a) return a:GetID() == pPlayer:GetID() end); end end end -- Add "City States" Filter AddFilter(Locale.Lookup("LOC_HUD_REPORTS_CITY_STATE"), IsCityState); -- Add filters to pulldown for index, filter in ipairs(m_filterList) do AddFilterEntry(index); end -- Select first filter Controls.FilterButton:SetText(m_filterList[m_filterSelected].FilterText); -- Calculate Internals Controls.DestinationFilterPulldown:CalculateInternals(); UpdateFilterArrow(); end function AddFilter( filterName:string, filterFunction ) -- Make sure we don't add duplicate filters for index, filter in ipairs(m_filterList) do if filter.FilterText == filterName then return; end end m_filterCount = m_filterCount + 1; m_filterList[m_filterCount] = {FilterText=filterName, FilterFunction=filterFunction}; end function AddFilterEntry( filterIndex:number ) local filterEntry:table = {}; Controls.DestinationFilterPulldown:BuildEntry( "FilterEntry", filterEntry ); filterEntry.Button:SetText(m_filterList[filterIndex].FilterText); filterEntry.Button:SetVoids(i, filterIndex); end function UpdateFilterArrow() if Controls.DestinationFilterPulldown:IsOpen() then Controls.PulldownOpenedArrow:SetHide(true); Controls.PulldownClosedArrow:SetHide(false); else Controls.PulldownOpenedArrow:SetHide(false); Controls.PulldownClosedArrow:SetHide(true); end end function OnFilterSelected( index:number, filterIndex:number ) m_filterSelected = filterIndex; Controls.FilterButton:SetText(m_filterList[m_filterSelected].FilterText); m_FilterSettingsChanged = true Refresh(); end -- =========================================================================== -- Sort bar functions -- =========================================================================== -- Hides all the ascending/descending arrows function ResetSortBar() Controls.FoodDescArrow:SetHide(true); Controls.ProductionDescArrow:SetHide(true); Controls.GoldDescArrow:SetHide(true); Controls.ScienceDescArrow:SetHide(true); Controls.CultureDescArrow:SetHide(true); Controls.FaithDescArrow:SetHide(true); Controls.TurnsToCompleteDescArrow:SetHide(true); Controls.FoodAscArrow:SetHide(true); Controls.ProductionAscArrow:SetHide(true); Controls.GoldAscArrow:SetHide(true); Controls.ScienceAscArrow:SetHide(true); Controls.CultureAscArrow:SetHide(true); Controls.FaithAscArrow:SetHide(true); Controls.TurnsToCompleteAscArrow:SetHide(true); end function RefreshSortBar() RefreshSortButtons( m_SortBySettings ); if showSortOrdersPermanently or m_shiftDown then -- Hide the order texts HideSortOrderLabels(); -- Show them based on current settings ShowSortOrderLabels(); end end function ShowSortOrderLabels() -- Refresh and show sort orders RefreshSortOrderLabels( m_SortBySettings ); end function HideSortOrderLabels() Controls.FoodSortOrder:SetHide(true); Controls.ProductionSortOrder:SetHide(true); Controls.GoldSortOrder:SetHide(true); Controls.ScienceSortOrder:SetHide(true); Controls.CultureSortOrder:SetHide(true); Controls.FaithSortOrder:SetHide(true); Controls.TurnsToCompleteSortOrder:SetHide(true); end -- Shows and hides arrows based on the passed sort order function SetSortArrow( ascArrow:table, descArrow:table, sortOrder:number ) if sortOrder == SORT_ASCENDING then descArrow:SetHide(true); ascArrow:SetHide(false); else descArrow:SetHide(false); ascArrow:SetHide(true); end end function RefreshSortButtons( sortSettings:table ) -- Hide all arrows ResetSortBar(); -- Set disabled color Controls.FoodSortButton:SetColorByName("ButtonDisabledCS"); Controls.ProductionSortButton:SetColorByName("ButtonDisabledCS"); Controls.GoldSortButton:SetColorByName("ButtonDisabledCS"); Controls.ScienceSortButton:SetColorByName("ButtonDisabledCS"); Controls.CultureSortButton:SetColorByName("ButtonDisabledCS"); Controls.FaithSortButton:SetColorByName("ButtonDisabledCS"); Controls.TurnsToCompleteSortButton:SetColorByName("ButtonDisabledCS"); -- Go through settings and display arrows for index, sortEntry in ipairs(sortSettings) do if sortEntry.SortByID == SORT_BY_ID.FOOD then SetSortArrow(Controls.FoodAscArrow, Controls.FoodDescArrow, sortEntry.SortOrder) Controls.FoodSortButton:SetColorByName("ButtonCS"); elseif sortEntry.SortByID == SORT_BY_ID.PRODUCTION then SetSortArrow(Controls.ProductionAscArrow, Controls.ProductionDescArrow, sortEntry.SortOrder) Controls.ProductionSortButton:SetColorByName("ButtonCS"); elseif sortEntry.SortByID == SORT_BY_ID.GOLD then SetSortArrow(Controls.GoldAscArrow, Controls.GoldDescArrow, sortEntry.SortOrder) Controls.GoldSortButton:SetColorByName("ButtonCS"); elseif sortEntry.SortByID == SORT_BY_ID.SCIENCE then SetSortArrow(Controls.ScienceAscArrow, Controls.ScienceDescArrow, sortEntry.SortOrder) Controls.ScienceSortButton:SetColorByName("ButtonCS"); elseif sortEntry.SortByID == SORT_BY_ID.CULTURE then SetSortArrow(Controls.CultureAscArrow, Controls.CultureDescArrow, sortEntry.SortOrder) Controls.CultureSortButton:SetColorByName("ButtonCS"); elseif sortEntry.SortByID == SORT_BY_ID.FAITH then SetSortArrow(Controls.FaithAscArrow, Controls.FaithDescArrow, sortEntry.SortOrder) Controls.FaithSortButton:SetColorByName("ButtonCS"); elseif sortEntry.SortByID == SORT_BY_ID.TURNS_TO_COMPLETE then SetSortArrow(Controls.TurnsToCompleteAscArrow, Controls.TurnsToCompleteDescArrow, sortEntry.SortOrder) Controls.TurnsToCompleteSortButton:SetColorByName("ButtonCS"); end end end function RefreshSortOrderLabels( sortSettings:table ) for index, sortEntry in ipairs(sortSettings) do if sortEntry.SortByID == SORT_BY_ID.FOOD then Controls.FoodSortOrder:SetHide(false); Controls.FoodSortOrder:SetText(index); Controls.FoodSortOrder:SetColorByName("ResFoodLabelCS"); elseif sortEntry.SortByID == SORT_BY_ID.PRODUCTION then Controls.ProductionSortOrder:SetHide(false); Controls.ProductionSortOrder:SetText(index); Controls.ProductionSortOrder:SetColorByName("ResProductionLabelCS"); elseif sortEntry.SortByID == SORT_BY_ID.GOLD then Controls.GoldSortOrder:SetHide(false); Controls.GoldSortOrder:SetText(index); Controls.GoldSortOrder:SetColorByName("ResGoldLabelCS"); elseif sortEntry.SortByID == SORT_BY_ID.SCIENCE then Controls.ScienceSortOrder:SetHide(false); Controls.ScienceSortOrder:SetText(index); Controls.ScienceSortOrder:SetColorByName("ResScienceLabelCS"); elseif sortEntry.SortByID == SORT_BY_ID.CULTURE then Controls.CultureSortOrder:SetHide(false); Controls.CultureSortOrder:SetText(index); Controls.CultureSortOrder:SetColorByName("ResCultureLabelCS"); elseif sortEntry.SortByID == SORT_BY_ID.FAITH then Controls.FaithSortOrder:SetHide(false); Controls.FaithSortOrder:SetText(index); Controls.FaithSortOrder:SetColorByName("ResFaithLabelCS"); elseif sortEntry.SortByID == SORT_BY_ID.TURNS_TO_COMPLETE then Controls.TurnsToCompleteSortOrder:SetHide(false); Controls.TurnsToCompleteSortOrder:SetText(index); end end end -- =========================================================================== -- General Helper functions -- =========================================================================== -- --------------------------------------------------------------------------- -- Trade route helper functions -- --------------------------------------------------------------------------- function TradeRouteSelected( cityOwner:number, cityID:number ) local player:table = Players[cityOwner]; if player then local pCity:table = player:GetCities():FindID(cityID); if pCity ~= nil then m_destinationCity = pCity; else error("Unable to find city '".. tostring(cityID).."' for creating a trade route."); end end Refresh(); end function GetYieldForCity(yieldIndex:number, city:table, originCity:boolean) local tradeManager = Game.GetTradeManager(); local yieldInfo = GameInfo.Yields[yieldIndex]; local totalValue = 0; local partialValue = 0; local sourceText = ""; -- From route if (originCity) then partialValue = tradeManager:CalculateOriginYieldFromPotentialRoute(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID(), yieldIndex); else partialValue = tradeManager:CalculateDestinationYieldFromPotentialRoute(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID(), yieldIndex); end totalValue = totalValue + partialValue; if (partialValue > 0 and yieldInfo ~= nil) then if (sourceText ~= "") then sourceText = sourceText .. "[NEWLINE]"; end sourceText = sourceText .. Locale.Lookup("LOC_ROUTECHOOSER_YIELD_SOURCE_DISTRICTS", partialValue, yieldInfo.IconString, yieldInfo.Name, city:GetName()); end -- From path if (originCity) then partialValue = tradeManager:CalculateOriginYieldFromPath(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID(), yieldIndex); else partialValue = tradeManager:CalculateDestinationYieldFromPath(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID(), yieldIndex); end totalValue = totalValue + partialValue; if (partialValue > 0 and yieldInfo ~= nil) then if (sourceText ~= "") then sourceText = sourceText .. "[NEWLINE]"; end sourceText = sourceText .. Locale.Lookup("LOC_ROUTECHOOSER_YIELD_SOURCE_TRADING_POSTS", partialValue, yieldInfo.IconString, yieldInfo.Name); end -- From modifiers local resourceID = -1; if (originCity) then partialValue = tradeManager:CalculateOriginYieldFromModifiers(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID(), yieldIndex, resourceID); else partialValue = tradeManager:CalculateDestinationYieldFromModifiers(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID(), yieldIndex, resourceID); end totalValue = totalValue + partialValue; if (partialValue > 0 and yieldInfo ~= nil) then if (sourceText ~= "") then sourceText = sourceText .. "[NEWLINE]"; end sourceText = sourceText .. Locale.Lookup("LOC_ROUTECHOOSER_YIELD_SOURCE_BONUSES", partialValue, yieldInfo.IconString, yieldInfo.Name); end -- Adriaman -- CQUI Note: This is taken from fixes made by a user of BTS on the BTS Steam Workshop Page (Adriaman) -- Overall modifiers / multipliers local kYieldMultiplier = 1 if m_originCity:GetOwner() ~= city:GetOwner() then if (originCity) then local pPlayerTrade:table = Players[m_originCity:GetOwner()]:GetTrade(); kYieldMultiplier = pPlayerTrade:GetInternationalYieldModifier(yieldIndex); else local pPlayerTrade:table = Players[city:GetOwner()]:GetTrade(); kYieldMultiplier = pPlayerTrade:GetInternationalYieldModifier(yieldIndex); end end local totalBeforeMultiplier:number = totalValue; local total:number = totalBeforeMultiplier; local multiplier:number = kYieldMultiplier; if total > 0 and multiplier ~= 1 then total = totalBeforeMultiplier * multiplier; local valueFromMultiplier:number = total - totalBeforeMultiplier; local multiplierAsPercent:number = (multiplier * 100) - 100; if sourceText ~= "" then sourceText = sourceText .. "[NEWLINE]"; end sourceText = sourceText .. Locale.Lookup("LOC_ROUTECHOOSER_YIELD_SOURCE_MULTIPLIERS", valueFromMultiplier, yieldInfo.IconString, yieldInfo.Name, multiplierAsPercent); totalValue = total end return totalValue, sourceText; end -- =========================================================================== -- Look at the plot of the destination city. -- Not always done when selected, as sometimes the TradeOverview will be -- open and it's going to perform it's own lookat. -- =========================================================================== function RealizeLookAtDestinationCity() if m_destinationCity == nil then UI.DataError("TradeRouteChooser cannot look at a NIL destination."); return; end local locX :number = m_destinationCity:GetX(); local locY :number = m_destinationCity:GetY(); local screenXOff:number = 0.6; -- Change offset if the TradeOveriew (exists and) is open as well. local pContextControl:table = ContextPtr:LookUpControl("/InGame/TradeOverview"); if pContextControl == nil then UI.DataError("Cannot determine if partial screen \"/InGame/TradeOverview\" is visible because it wasn't found at that path."); elseif not pContextControl:IsHidden() then screenXOff = 0.42; end UI.LookAtPlotScreenPosition( locX, locY, screenXOff, 0.5 ); -- Look at 60% over from left side of screen end -- =========================================================================== -- UI Button Callback -- =========================================================================== function OnTradeRouteSelected( cityOwner:number, cityID:number ) TradeRouteSelected( cityOwner, cityID ); RealizeLookAtDestinationCity(); LuaEvents.TradeRouteChooser_RouteConsidered(); end function OnRepeatRouteCheckbox() if not Controls.RepeatRouteCheckbox:IsChecked() then Controls.FromTopSortEntryCheckbox:SetCheck(false); end end function OnFromTopSortEntryCheckbox() -- FromTopSortEntryCheckbox is tied to RepeatRouteCheckbox if Controls.FromTopSortEntryCheckbox:IsChecked() then Controls.RepeatRouteCheckbox:SetCheck(true); end end function RequestTradeRoute() local selectedUnit = UI.GetHeadSelectedUnit(); if m_destinationCity and selectedUnit then local operationParams = {}; operationParams[UnitOperationTypes.PARAM_X0] = m_destinationCity:GetX(); operationParams[UnitOperationTypes.PARAM_Y0] = m_destinationCity:GetY(); operationParams[UnitOperationTypes.PARAM_X1] = selectedUnit:GetX(); operationParams[UnitOperationTypes.PARAM_Y1] = selectedUnit:GetY(); if (UnitManager.CanStartOperation(selectedUnit, UnitOperationTypes.MAKE_TRADE_ROUTE, nil, operationParams)) then UnitManager.RequestOperation(selectedUnit, UnitOperationTypes.MAKE_TRADE_ROUTE, operationParams); UI.SetInterfaceMode(InterfaceModeTypes.SELECTION); UI.PlaySound("START_TRADE_ROUTE"); -- Automated Handlers if Controls.RepeatRouteCheckbox:IsChecked() and Controls.FromTopSortEntryCheckbox:IsChecked() then AutomateTrader(selectedUnit:GetID(), true, m_SortBySettings); elseif Controls.RepeatRouteCheckbox:IsChecked() then AutomateTrader(selectedUnit:GetID(), true); else AutomateTrader(selectedUnit:GetID(), false); end end return true; end return false; end -- --------------------------------------------------------------------------- -- Sort bar insert buttons -- --------------------------------------------------------------------------- function OnGeneralSortBy(descArrowControl, sortByID) -- If shift is not being pressed, reset sort settings if not m_shiftDown then m_SortBySettings = {}; end -- Sort based on currently showing icon toggled if descArrowControl:IsHidden() then InsertSortEntry(sortByID, SORT_DESCENDING, m_SortBySettings); else InsertSortEntry(sortByID, SORT_ASCENDING, m_SortBySettings); end m_SortSettingsChanged = true Refresh(); end function OnSortByFood() OnGeneralSortBy(Controls.FoodDescArrow, SORT_BY_ID.FOOD) end function OnSortByProduction() OnGeneralSortBy(Controls.ProductionDescArrow, SORT_BY_ID.PRODUCTION) end function OnSortByGold() OnGeneralSortBy(Controls.GoldDescArrow, SORT_BY_ID.GOLD) end function OnSortByScience() OnGeneralSortBy(Controls.ScienceDescArrow, SORT_BY_ID.SCIENCE) end function OnSortByCulture() OnGeneralSortBy(Controls.CultureDescArrow, SORT_BY_ID.CULTURE) end function OnSortByFaith() OnGeneralSortBy(Controls.FaithDescArrow, SORT_BY_ID.FAITH) end function OnSortByTurnsToComplete() OnGeneralSortBy(Controls.TurnsToCompleteDescArrow, SORT_BY_ID.TURNS_TO_COMPLETE) end -- --------------------------------------------------------------------------- -- Sort bar delete buttons -- --------------------------------------------------------------------------- function OnGeneralNotSortBy(sortByID) RemoveSortEntry(sortByID, m_SortBySettings); m_SortSettingsChanged = true Refresh(); end function OnNotSortByFood() OnGeneralNotSortBy(SORT_BY_ID.FOOD) end function OnNotSortByProduction() OnGeneralNotSortBy(SORT_BY_ID.PRODUCTION) end function OnNotSortByGold() OnGeneralNotSortBy(SORT_BY_ID.GOLD) end function OnNotSortByScience() OnGeneralNotSortBy(SORT_BY_ID.SCIENCE) end function OnNotSortByCulture() OnGeneralNotSortBy(SORT_BY_ID.CULTURE) end function OnNotSortByFaith() OnGeneralNotSortBy(SORT_BY_ID.FAITH) end function OnNotSortByTurnsToComplete() OnGeneralNotSortBy(SORT_BY_ID.TURNS_TO_COMPLETE) end -- =========================================================================== -- Rise/Hide and refresh Trade UI -- =========================================================================== function OnInterfaceModeChanged( oldMode:number, newMode:number ) if (oldMode == InterfaceModeTypes.MAKE_TRADE_ROUTE) then Close(); end if (newMode == InterfaceModeTypes.MAKE_TRADE_ROUTE) then Open(); end end function OnClose() Close(); if UI.GetInterfaceMode() == InterfaceModeTypes.MAKE_TRADE_ROUTE then UI.SetInterfaceMode(InterfaceModeTypes.SELECTION); end end function Close() LuaEvents.TradeRouteChooser_SetTradeUnitStatus(""); UILens.ClearLayerHexes(m_TradeRouteLens); ContextPtr:SetHide(true); m_isOpen = false; if UILens.IsLensActive(m_TradeRouteLens) then -- Make sure to switch back to default lens UILens.SetActive("Default"); end end function Open() LuaEvents.TradeRouteChooser_SetTradeUnitStatus("LOC_HUD_UNIT_PANEL_CHOOSING_TRADE_ROUTE"); ContextPtr:SetHide(false); m_isOpen = true; m_destinationCity = nil; Controls.RepeatRouteCheckbox:SetCheck(false); Controls.FromTopSortEntryCheckbox:SetCheck(false); -- Play Open Animation Controls.RouteChooserSlideAnim:SetToBeginning(); Controls.RouteChooserSlideAnim:Play(); -- Switch to TradeRoute Lens UILens.SetActive(m_TradeRouteLens); LuaEvents.TradeRouteChooser_Open(); local selectedUnit:table = UI.GetHeadSelectedUnit(); local selectedUnitID:number = selectedUnit:GetID(); -- Select last route if one exists local lastRoute:table = GetLastRouteForTrader(selectedUnitID); if lastRoute ~= nil then -- print_debug("Last route for trader " .. selectedUnitID .. ": " .. GetTradeRouteString(lastRoute)); originCity = Cities.GetCityInPlot(selectedUnit:GetX(), selectedUnit:GetY()); -- Don't select the route, if trader was transferred if lastRoute.OriginCityID ~= originCity:GetID() then -- print_debug("Trader was transferred. Not selecting the last route") elseif IsRoutePossible(originCity:GetOwner(), originCity:GetID(), lastRoute.DestinationCityPlayer, DestinationCityID) then local destinationPlayer:table = Players[lastRoute.DestinationCityPlayer]; m_destinationCity = destinationPlayer:GetCities():FindID(lastRoute.DestinationCityID); else -- print_debug("Route is no longer valid."); end else -- print_debug("No last route was found for trader " .. selectedUnitID); end Refresh(); end function CheckNeedsToOpen() if m_SkipNextOpen then m_SkipNextOpen = false return end local selectedUnit:table = UI.GetHeadSelectedUnit(); if selectedUnit ~= nil then local selectedUnitInfo:table = GameInfo.Units[selectedUnit:GetUnitType()]; if selectedUnitInfo ~= nil and selectedUnitInfo.MakeTradeRoute == true then local activityType:number = UnitManager.GetActivityType(selectedUnit); if activityType == ActivityTypes.ACTIVITY_AWAKE and selectedUnit:GetMovesRemaining() > 0 then -- If we're open and this is a trade unit then just refresh if not ContextPtr:IsHidden() then Refresh(); else UI.SetInterfaceMode(InterfaceModeTypes.MAKE_TRADE_ROUTE); end -- Early out so we don't call Close() return; end end end -- If we're open and this unit is not a trade unit then close if not ContextPtr:IsHidden() then Close(); end end function OnSkipNextOpen() m_SkipNextOpen = true end -- =========================================================================== -- UI Events -- =========================================================================== function OnInit( isReload:boolean ) if isReload then LuaEvents.GameDebug_GetValues( "TradeRouteChooser" ); end end function OnShutdown() -- Cache values for hotloading... LuaEvents.GameDebug_AddValue("TradeRouteChooser", "filterIndex", m_filterSelected ); LuaEvents.GameDebug_AddValue("TradeRouteChooser", "destinationCity", m_destinationCity ); end -- =========================================================================== -- LUA Event -- Set cached values back after a hotload. -- ===========================================================================s function OnGameDebugReturn( context:string, contextTable:table ) if context ~= "TradeRouteChooser" then return; end if contextTable["filterIndex"] ~= nil then m_filterSelected = contextTable["filterIndex"]; end if contextTable["destinationCity"] ~= nil then m_destinationCity = contextTable["destinationCity"]; end Refresh(); end -- =========================================================================== -- GAME Event -- City was selected so close route chooser -- =========================================================================== function OnCitySelectionChanged(owner, ID, i, j, k, bSelected, bEditable) if not ContextPtr:IsHidden() and owner == Game.GetLocalPlayer() then OnClose(); end end -- =========================================================================== -- GAME Event -- Unit was selected so close route chooser -- =========================================================================== function OnUnitSelectionChanged( playerID:number, unitID:number, hexI:number, hexJ:number, hexK:number, bSelected:boolean, bEditable:boolean ) -- Make sure we're the local player and not observing if playerID ~= Game.GetLocalPlayer() or playerID == -1 then return; end -- Don't call open/close if TradeOverview is open (needed to make TradeOriginChooser open from TradeOverview) -- local pContextControl:table = ContextPtr:LookUpControl("/InGame/TradeOverview"); -- if pContextControl == nil then -- print("Cannot determine if partial screen \"/InGame/TradeOverview\" is visible because it wasn't found at that path."); -- elseif not pContextControl:IsHidden() then -- print("Trade Overview Panel is open. Not opening Make Trade Route screen.") -- return -- end -- If this is a de-selection event then close if not bSelected then OnClose(); return; end CheckNeedsToOpen() end function OnLocalPlayerTurnEnd() if(GameConfiguration.IsHotseat()) then OnClose(); end -- Clear cache to keep memory used low CacheEmpty() end function OnUnitActivityChanged( playerID :number, unitID :number, eActivityType :number) -- Make sure we're the local player and not observing if playerID ~= Game.GetLocalPlayer() or playerID == -1 then return; end CheckNeedsToOpen(); end function OnPolicyChanged( ePlayer ) if not ContextPtr:IsHidden() and ePlayer == Game.GetLocalPlayer() then Refresh(); end end -- =========================================================================== -- Input -- UI Event Handler -- =========================================================================== function KeyDownHandler( key:number ) if key == Keys.VK_SHIFT then m_shiftDown = true; if not showSortOrdersPermanently then ShowSortOrderLabels(); end -- let it fall through end return false; end function KeyUpHandler( key:number ) if key == Keys.VK_SHIFT then m_shiftDown = false; if not showSortOrdersPermanently then HideSortOrderLabels(); end -- let it fall through end if key == Keys.VK_RETURN then if m_destinationCity then RequestTradeRoute(); end -- Dont let it fall through return true; end if key == Keys.VK_ESCAPE then OnClose(); -- AZURENCY : on ESC also unselect the unit --return true; end return false; end function OnInputHandler( pInputStruct:table ) local uiMsg = pInputStruct:GetMessageType(); if uiMsg == KeyEvents.KeyDown then return KeyDownHandler( pInputStruct:GetKey() ); end if uiMsg == KeyEvents.KeyUp then return KeyUpHandler( pInputStruct:GetKey() ); end return false; end -- =========================================================================== function OnSelectRouteFromOverview( destinationOwnerID:number, destinationCityID:number ) m_postOpenSelectPlayerID = destinationOwnerID; m_postOpenSelectCityID = destinationCityID; CheckNeedsToOpen() end -- =========================================================================== -- Setup -- =========================================================================== function InitButton(control, callbackLClick, callbackRClick) control:RegisterCallback(Mouse.eLClick, callbackLClick) if callbackRClick ~= nil then control:RegisterCallback(Mouse.eRClick, callbackRClick) end control:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over") end) end function Initialize() print("Initializing BTS Trade Route Chooser"); TradeSupportAutomater_Initialize(); -- CQUI Handlers LuaEvents.CQUI_SettingsUpdate.Add( CQUI_OnSettingsUpdate ); -- Context Events ContextPtr:SetInitHandler( OnInit ); ContextPtr:SetShutdown( OnShutdown ); ContextPtr:SetInputHandler( OnInputHandler, true ); -- Lua Events LuaEvents.GameDebug_Return.Add( OnGameDebugReturn ); -- Context Events LuaEvents.TradeRouteChooser_SkipOpen.Add( OnSkipNextOpen ) LuaEvents.TradeOverview_SelectRouteFromOverview.Add( OnSelectRouteFromOverview ); LuaEvents.TradeRouteChooser_Close.Add( OnClose ) -- Game Engine Events Events.InterfaceModeChanged.Add( OnInterfaceModeChanged ); Events.CitySelectionChanged.Add( OnCitySelectionChanged ); Events.UnitSelectionChanged.Add( OnUnitSelectionChanged ); Events.UnitActivityChanged.Add( OnUnitActivityChanged ); Events.LocalPlayerTurnEnd.Add( OnLocalPlayerTurnEnd ); Events.GovernmentPolicyChanged.Add( OnPolicyChanged ); Events.GovernmentPolicyObsoleted.Add( OnPolicyChanged ); -- Control Events InitButton(Controls.BeginRouteButton, RequestTradeRoute) InitButton(Controls.Header_CloseButton, OnClose ) -- Filter Controls.FilterButton:RegisterCallback( Mouse.eLClick, UpdateFilterArrow ); Controls.DestinationFilterPulldown:RegisterSelectionCallback( OnFilterSelected ); -- Control events - checkboxes InitButton(Controls.RepeatRouteCheckbox, OnRepeatRouteCheckbox ); InitButton(Controls.FromTopSortEntryCheckbox, OnFromTopSortEntryCheckbox ); -- Control events - sort bar InitButton(Controls.FoodSortButton, OnSortByFood, OnNotSortByFood) InitButton(Controls.ProductionSortButton, OnSortByProduction, OnNotSortByProduction) InitButton(Controls.GoldSortButton, OnSortByGold, OnNotSortByGold) InitButton(Controls.ScienceSortButton, OnSortByScience, OnNotSortByScience) InitButton(Controls.CultureSortButton, OnSortByCulture, OnNotSortByCulture) InitButton(Controls.FaithSortButton, OnSortByFaith, OnNotSortByFaith) InitButton(Controls.TurnsToCompleteSortButton, OnSortByTurnsToComplete, OnNotSortByTurnsToComplete) end Initialize();
412
0.88955
1
0.88955
game-dev
MEDIA
0.736292
game-dev
0.91719
1
0.91719
opentibia/yatc
3,876
mapui.h
////////////////////////////////////////////////////////////////////// // Yet Another Tibia Client ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// // 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. ////////////////////////////////////////////////////////////////////// #ifndef __MAPUI_H #define __MAPUI_H #include "gamecontent/map.h" #include "popup.h" #include "gamecontent/globalvars.h" struct vertex; class MapUI { public: MapUI(); ~MapUI(); void renderMap(); inline void setPos(int x, int y) { m_x = x; m_y = y; } inline void setSize(int w, int h) { m_w = w; m_h = h; } inline int getWidth() const { return m_w; } inline int getHeight() const { return m_h; } void useItem(int x, int y, const Thing* &thing, uint32_t &retx, uint32_t &rety, uint32_t &retz, int &stackpos, bool &extended); void useItemExtended(int x, int y, const Thing* &thing, uint32_t &retx, uint32_t &rety, uint32_t &retz, int &stackpos); void attackCreature(int x, int y, const Creature* &creature); void lookAtItem(int x, int y, const Thing* &thing, uint32_t &retx, uint32_t &rety, uint32_t &retz, int &stackpos); void dragThing(int x, int y, const Thing* &thing, uint32_t &retx, uint32_t &rety, uint32_t &retz, int &stackpos); void useItem(Tile* tile, const Thing* &thing, int &stackpos, bool &extended); void lookAtItem(Tile* tile, const Thing* &thing, int &stackpos); bool handlePopup(int x, int y); Tile* translateClickToTile(int x, int y, uint32_t &retx, uint32_t &rety, uint32_t &retz); Tile* translateClickToTile(int x, int y) {uint32_t ax,ay,az; return translateClickToTile(x,y,ax,ay,az);} static void makePopup(Popup*popup,void*owner,void*arg); std::list<Direction> getPathTo(int scrx, int scry); int getMinZ(Position pos = GlobalVariables::getPlayerPosition()); void drawPublicMessages(Position pos, float walkoffx, float walkoffy); void drawPrivateMessages(); private: int m_x, m_y; int m_w, m_h; uint32_t m_vpw; uint32_t m_vph; int m_minz; float m_scale; Position m_lastRightclickTilePos; uint32_t m_popupCreatureID; static void onLookAt(Popup::Item *parent); static void onUse(Popup::Item *parent); static void onAttack(Popup::Item *parent); static void onFollow(Popup::Item *parent); static void onMessageTo(Popup::Item *parent); static void onAddVIP(Popup::Item *parent); static void onInviteToParty(Popup::Item *parent); static void onRevokeInvite(Popup::Item *parent); static void onAcceptInvite(Popup::Item *parent); static void onSharedExp(Popup::Item *parent); static void onPassLeadership(Popup::Item *parent); static void onLeaveParty(Popup::Item *parent); static void onUnimplemented(Popup::Item *parent); vertex* lightmap; protected: void drawTileEffects(Tile* tile, int screenx, int screeny, float scale, uint32_t tile_height); void drawTileGhosts(int x, int y, int z, int screenx, int screeny, float scale, uint32_t tile_height); void fillLightCircle(int x, int y, int radius, uint16_t color); bool isVisible(const Position& pos); }; #endif
412
0.680373
1
0.680373
game-dev
MEDIA
0.638042
game-dev
0.699615
1
0.699615
Talberon/solstandard
2,936
SolStandard/Entity/Unit/Actions/Item/DeployRecallPointAction.cs
using System; using System.Collections.Generic; using SolStandard.Containers.Components.Global; using SolStandard.Containers.Components.World.SubContext.Movement; using SolStandard.Entity.General; using SolStandard.Entity.General.Item; using SolStandard.Map; using SolStandard.Map.Elements; using SolStandard.Map.Elements.Cursor; using SolStandard.Utility.Assets; using SolStandard.Utility.Events; namespace SolStandard.Entity.Unit.Actions.Item { public class DeployRecallPointAction : UnitAction { private readonly RecallCharm recallSource; public DeployRecallPointAction(RecallCharm recallSource, int[] deployRange) : base( icon: recallSource.Icon.Clone(), name: "Set Recall Point", description: "Single Use. " + Environment.NewLine + "Deploy a recall point that can be teleported to by reusing " + recallSource.Name + "." + Environment.NewLine + "Expires after recall source is used again." + Environment.NewLine + "Recall ID: " + recallSource.RecallId, tileSprite: MapDistanceTile.GetTileSprite(MapDistanceTile.TileType.Action), range: deployRange, freeAction: false ) { this.recallSource = recallSource; } public override void ExecuteAction(MapSlice targetSlice) { if (CanPlaceRecallPointAtTarget(targetSlice)) { recallSource.DeployRecall(); RecallPoint recallPoint = GenerateRecallPoint(recallSource.RecallId, targetSlice); var eventQueue = new Queue<IEvent>(); eventQueue.Enqueue(new PlaceEntityOnMapEvent(recallPoint, Layer.Entities, AssetManager.CombatBlockSFX)); eventQueue.Enqueue(new WaitFramesEvent(10)); eventQueue.Enqueue(new EndTurnEvent()); GlobalEventQueue.QueueEvents(eventQueue); } else { GlobalContext.WorldContext.MapContainer.AddNewToastAtMapCursor( "Invalid target! Place on movable tile without terrain entity in range.", 50 ); AssetManager.WarningSFX.Play(); } } private static bool CanPlaceRecallPointAtTarget(MapSlice targetSlice) { return targetSlice.TerrainEntity == null && targetSlice.DynamicEntity != null && UnitMovingPhase.CanEndMoveAtCoordinates(targetSlice.MapCoordinates); } private static RecallPoint GenerateRecallPoint(string sourceId, MapSlice targetSlice) { return new RecallPoint( sourceId, SkillIconProvider.GetSkillIcon(SkillIcon.Blink, GameDriver.CellSizeVector), targetSlice.MapCoordinates ); } } }
412
0.851296
1
0.851296
game-dev
MEDIA
0.402995
game-dev
0.913327
1
0.913327
Angry-Pixel/The-Betweenlands
2,055
src/main/java/thebetweenlands/client/audio/ambience/list/SpiritTreeAmbienceType.java
package thebetweenlands.client.audio.ambience.list; import net.minecraft.client.Minecraft; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import thebetweenlands.api.storage.ILocalStorage; import thebetweenlands.client.audio.ambience.AmbienceLayer; import thebetweenlands.client.audio.ambience.AmbienceType; import thebetweenlands.common.registries.AmbienceRegistry; import thebetweenlands.common.registries.SoundRegistry; import thebetweenlands.common.world.storage.BetweenlandsWorldStorage; import thebetweenlands.common.world.storage.location.EnumLocationType; import thebetweenlands.common.world.storage.location.LocationStorage; public class SpiritTreeAmbienceType extends AmbienceType { private double getClosestSpiritTree() { BetweenlandsWorldStorage worldStorage = BetweenlandsWorldStorage.forWorld(Minecraft.getMinecraft().world); double closestSpiritTree = -1; for(ILocalStorage storage : worldStorage.getLocalStorageHandler().getLoadedStorages()) { if(storage instanceof LocationStorage && ((LocationStorage)storage).getType() == EnumLocationType.SPIRIT_TREE) { double dist = Minecraft.getMinecraft().player.getPositionVector().distanceTo(storage.getBoundingBox().getCenter()); if(dist < 75) { if(closestSpiritTree < 0 || dist < closestSpiritTree) { closestSpiritTree = dist; } } } } return closestSpiritTree; } @Override public boolean isActive() { return this.getClosestSpiritTree() >= 0; } @Override public AmbienceLayer getAmbienceLayer() { return AmbienceRegistry.BASE_LAYER; } @Override public int getPriority() { return 999; } @Override public SoundCategory getCategory() { return SoundCategory.AMBIENT; } @Override public SoundEvent getSound() { return SoundRegistry.AMBIENT_SNOWFALL; } @Override public float getVolume() { return 0.0F; } @Override public float getLowerPriorityVolume() { float strength = 1.0F - (float)Math.max(0, (this.getClosestSpiritTree() - 20) / (75.0F - 20)); return 1.0F - strength; } }
412
0.941332
1
0.941332
game-dev
MEDIA
0.930487
game-dev
0.964726
1
0.964726
LiveOverflow/PwnAdventure3
2,368
tools/linux/part8_eggs.cpp
#include <dlfcn.h> #include <set> #include <map> #include <functional> #include <string> #include <vector> #include "libGameLogic.h" // cd clients/linux_updated/PwnAdventure3_Data/PwnAdventure3/PwnAdventure3/Binaries/Linux // g++ part8_eggs.cpp -shared -fPIC -std=c++11 -o part8_eggs.so // LD_PRELOAD=part8_eggs.so ./PwnAdventure3-Linux-Shipping bool frozen = false; Vector3 frozen_pos; void Player::Chat(const char *msg) { printf("[chat] msg=\"%s\"\n", msg); if(strncmp("tp ", msg, 3) == 0) { Vector3 new_pos; sscanf(msg+3, "%f %f %f", &(new_pos.x), &(new_pos.y), &(new_pos.z)); this->SetPosition(new_pos); frozen_pos = this->GetPosition(); } else if(strncmp("tpz ", msg, 4) == 0) { Vector3 new_pos = this->GetPosition(); sscanf(msg+4, "%f", &(new_pos.z)); this->SetPosition(new_pos); frozen_pos = this->GetPosition(); } else if(strncmp("!", msg, 1) == 0) { frozen_pos = this->GetPosition(); if(frozen) frozen = false; else frozen = true; } else if(strncmp("actors", msg, 6)==0) { // get the address of the global variable GameWorld ClientWorld* world = *((ClientWorld**)(dlsym(RTLD_NEXT, "GameWorld"))); // loop over all actors in the world for (ActorRef<IActor> _iactor : world->m_actors) { Actor* actor = ((Actor*)(_iactor.m_object)); Vector3 pos = actor->GetPosition(); printf("[actor] %s: %.2f %.2f %.2f\n", actor->GetDisplayName(), pos.x, pos.y, pos.z); } } } bool Player::CanJump() { return 1; } void World::Tick(float f) { // see libGameLogic.h for the class/object definitions ClientWorld* world = *((ClientWorld**)(dlsym(RTLD_NEXT, "GameWorld"))); IPlayer* iplayer = world->m_activePlayer.m_object; Player* player = ((Player*)(iplayer)); //Actor* actor = ((Actor*)(iplayer)); //printf("[LO] IPlayer.GetPlayerName: %s\n", iplayer->GetPlayerName()); //printf("[LO] player->m_mana: %d\n", player->m_mana); player->m_walkingSpeed = 99999; player->m_jumpSpeed = 999; player->m_jumpHoldTime = 99999; if(frozen) { Vector3 vel = player->GetVelocity(); printf("velo: %.2f / %.2f / %.2f\n", vel.x, vel.y, vel.z); player->SetPosition(frozen_pos); //player->SetVelocity(Vector3(0,0,60)); } }
412
0.625866
1
0.625866
game-dev
MEDIA
0.821505
game-dev
0.764856
1
0.764856
AmiBlitz/AmiBlitz3
7,900
Sourcecodes/Includes/OS/libraries/amigaguide.ab3
; XTRA ; Embedded .xtra Header ; ; General Info ; ------------------------------------------------------- ; ExePath = "" ; ExeFile = "" ; CreateIcon = 1 ; Residents = "" ; ; Compiler ; ------------------------------------------------------- ; StringBuffer = 10240 ; MakeSmallest = 0 ; FuncOptimize = 1 ; Version = 0.0.0 ; NumberOfBuilds = 0 ; ; Debugger ; ------------------------------------------------------- ; CliArgs = "" ; StackSize = 8191 ; RuntimeDebug = 1 ; DebugInfo = 0 ; CreateDbgFile = 0 ; OverflowCheck = 0 ; AssemblerCheck = 0 ; InterruptCheck = 1 ; AutoRun = 1 ; ; Editor ; ------------------------------------------------------- ; CursorLine = 1 ; CursorColumn = 1 ; LabelSearch = "" ; LabelRemark = 0 ; LabelAll = 0 ; LabelCase = 0 ; LabelPosition = 0 ; ; Blitz Objects ; ------------------------------------------------------- ; Max File = 5 ; Max GadgetList = 5 ; Max Shape = 100 ; Max Bank = 5 ; Max MenuList = 5 ; Max GTList = 20 ; Max Palette = 4 ; Max BitMap = 10 ; Max Screen = 5 ; Max IntuiFont = 5 ; Max BlitzFont = 4 ; Max Window = 20 ; Max IconInfo = 1 ; Max MUIObject = 50 ; Max AsyncReq = 4 ; Max Req-Lib = 5 ; Max GTMenuList = 5 ; Max Console = 5 ; Max TCPSock = 5 ; Max Tape = 5 ; Max TagList = 5 ; Max Database = 16 ; Max Sound = 10 ; Max MedModule = 8 ; Max Buffer = 10 ; Max Queue = 10 ; Max Sprite = 20 ; Max Module = 5 ; Max Slice = 10 ; Max Page = 4 ; Max CopList = 10 ; Max PTModule = 5 ; Max Anim = 10 ; Max NChunky = 50 ; Max Chunky = 20 ; Max Stencil = 5 ; Max XBSound = 10 ; /XTRA CNIF @#LIBRARIES_AMIGAGUIDE_H=0 #LIBRARIES_AMIGAGUIDE_H = 1 ; ; $VER: amigaguide.ab3 40.0 (02.03.94) ; CNIF @#EXEC_TYPES_H=0 XINCLUDE"exec/types.ab3" CEND ;EXEC_TYPES_H CNIF @#EXEC_LISTS_H=0 XINCLUDE"exec/lists.ab3" CEND ;EXEC_LISTS_H CNIF @#EXEC_NODES_H=0 XINCLUDE"exec/nodes.ab3" CEND ;EXEC_NODES_H CNIF @#EXEC_SEMAPHORES_H=0 XINCLUDE"exec/semaphores.ab3" CEND ;EXEC_SEMAPHORES_H CNIF @#INTUITION_INTUITION_H=0 XINCLUDE"intuition/intuition.ab3" CEND ;INTUITION_INTUITION_H CNIF @#INTUITION_SCREENS_H=0 XINCLUDE"intuition/screens.ab3" CEND ;INTUITION_SCREENS_H CNIF @#INTUITION_CLASSUSR_H=0 XINCLUDE"intuition/classusr.ab3" CEND ;INTUITION_CLASSUSR_H CNIF @#DOS_DOS_H=0 XINCLUDE"dos/dos.ab3" CEND ;DOS_DOS_H CNIF @#UTILITY_TAGITEM_H=0 XINCLUDE"utility/tagitem.ab3" CEND ;UTILITY_TAGITEM_H ;#ifndef APSH_TOOL_ID #APSH_TOOL_ID=11000 #StartupMsgID=(#APSH_TOOL_ID+1);/* Startup message */ #LoginToolID=(#APSH_TOOL_ID+2);/* Login a tool SIPC port */ #LogoutToolID=(#APSH_TOOL_ID+3);/* Logout a tool SIPC port */ #ShutdownMsgID=(#APSH_TOOL_ID+4);/* Shutdown message */ #ActivateToolID=(#APSH_TOOL_ID+5);/* Activate tool */ #DeactivateToolID=(#APSH_TOOL_ID+6);/* Deactivate tool */ #ActiveToolID=(#APSH_TOOL_ID+7);/* Tool Active */ #InactiveToolID=(#APSH_TOOL_ID+8);/* Tool Inactive */ #ToolStatusID=(#APSH_TOOL_ID+9);/* Status message */ #ToolCmdID=(#APSH_TOOL_ID+10);/* Tool command message */ #ToolCmdReplyID=(#APSH_TOOL_ID+11);/* Reply to tool command */ #ShutdownToolID=(#APSH_TOOL_ID+12);/* Shutdown tool */ ;#endif ;/* Attributes accepted by GetAmigaGuideAttr() */ #AGA_Dummy=(#TAG_USER) #AGA_Path=(#AGA_Dummy+1) #AGA_XRefList=(#AGA_Dummy+2) #AGA_Activate=(#AGA_Dummy+3) #AGA_Context=(#AGA_Dummy+4) #AGA_HelpGroup=(#AGA_Dummy+5) ;/* (ULONG) Unique identifier */ ;typedef void *AMIGAGUIDECONTEXT; NEWTYPE.AmigaGuideMsg agm_Msg.Message;/* Embedded Exec message structure */ agm_Type.l ;/* Type of message */ *agm_Data.b ;/* Pointer to message data */ agm_DSize.l ;/* Size of message data */ agm_DType.l ;/* Type of message data */ agm_Pri_Ret.l ;/* Primary return value */ agm_Sec_Ret.l ;/* Secondary return value */ *agm_System1.b *agm_System2.b End NEWTYPE NEWTYPE.nag_Context *nag_Context.b End NEWTYPE ;/* Allocation description structure */ NEWTYPE.NewAmigaGuide *nag_Lock.b ;/* Lock on the document directory */ *nag_Name.b ;/* Name of document file */ *nag_Screen.Screen;/* Screen to place windows within */ *nag_PubScreen.b ;/* Public screen name to open on */ *nag_HostPort.b ;/* Application's ARexx port name */ *nag_ClientPort.b ;/* Name to assign to the clients ARexx port */ *nag_BaseName.b ;/* Base name of the application */ nag_Flags.l ;/* Flags */ *nag_Context.nag_Context ;/* NULL terminated context table */ *nag_Node.b ;/* Node to align on first (defaults to Main) */ nag_Line.l ;/* Line to align on */ *nag_Extens.TagItem;/* Tag array extension */ *nag_Client.w ;/* Private! MUST be NULL */ End NEWTYPE ;/* public Client flags */ #HTF_LOAD_INDEX=(1 LSL 0);/* Force load the index at init time */ #HTF_LOAD_ALL=(1 LSL 1);/* Force load the entire database at init */ #HTF_CACHE_NODE=(1 LSL 2);/* Cache each node as visited */ #HTF_CACHE_DB=(1 LSL 3);/* Keep the buffers around until expunge */ #HTF_UNIQUE=(1 LSL 15);/* Unique ARexx port name */ #HTF_NOACTIVATE=(1 LSL 16);/* Don't activate window */ #HTFC_SYSGADS=$80000000 ;/* Callback function ID's */ #HTH_OPEN=0 #HTH_CLOSE=1 #HTERR_NOT_ENOUGH_MEMORY=100 #HTERR_CANT_OPEN_DATABASE=101 #HTERR_CANT_FIND_NODE=102 #HTERR_CANT_OPEN_NODE=103 #HTERR_CANT_OPEN_WINDOW=104 #HTERR_INVALID_COMMAND=105 #HTERR_CANT_COMPLETE=106 #HTERR_PORT_CLOSED=107 #HTERR_CANT_CREATE_PORT=108 #HTERR_KEYWORD_NOT_FOUND=113 ;typedef struct AmigaGuideHost *AMIGAGUIDEHOST; ;/* Cross reference node */ NEWTYPE.XRef xr_Node.Node;/* Embedded node */ xr_Pad.w ;/* Padding */ *xr_DF.b ;DocFile;/* Document defined in */ Where is this type defined? *xr_File.b ;/* Name of document file */ *xr_Name.b ;/* Name of item */ xr_Line.l ;/* Line defined at */ End NEWTYPE #XRSIZE=SizeOf.XRef ;/* Types of cross reference nodes */ #XR_GENERIC=0 #XR_FUNCTION=1 #XR_COMMAND=2 #XR_INCLUDE=3 #XR_MACRO=4 #XR_STRUCT=5 #XR_FIELD=6 #XR_TYPEDEF=7 #XR_DEFINE=8 ;/* Callback handle */ NEWTYPE.AmigaGuideHost agh_Dispatcher.Hook;/* Dispatcher */ agh_Reserved.l ;/* Must be 0 */ agh_Flags.l agh_UseCnt.l ;/* Number of open nodes */ *agh_SystemData.b ;/* Reserved for system use */ *agh_UserData.b ;/* Anything you want... */ End NEWTYPE ;/* Methods */ #HM_FINDNODE=1 #HM_OPENNODE=2 #HM_CLOSENODE=3 #HM_EXPUNGE=10;/* Expunge DataBase */ ;/* HM_FINDNODE */ NEWTYPE.opFindHost MethodID.l *ofh_Attrs.TagItem;/* R: Additional attributes */ *ofh_Node.b ;/* R: Name of node */ *ofh_TOC.b ;/* W: Table of Contents */ *ofh_Title.b ;/* W: Title to give to the node */ *ofh_Next.b ;/* W: Next node to browse to */ *ofh_Prev.b ;/* W: Previous node to browse to */ End NEWTYPE ;/* HM_OPENNODE, HM_CLOSENODE */ NEWTYPE.opNodeIO MethodID.l *onm_Attrs.TagItem;/* R: Additional attributes */ *onm_Node.b ;/* R: Node name and arguments */ *onm_FileName.b ;/* W: File name buffer */ *onm_DocBuffer.b ;/* W: Node buffer */ onm_BuffLen.l ;/* W: Size of buffer */ onm_Flags.l ;/* RW: Control flags */ End NEWTYPE ;/* onm_Flags */ #HTNF_KEEP=(1 LSL 0);/* Don't flush this node until database is ; * closed. */ #HTNF_RESERVED1=(1 LSL 1);/* Reserved for system use */ #HTNF_RESERVED2=(1 LSL 2);/* Reserved for system use */ #HTNF_ASCII=(1 LSL 3);/* Node is straight ASCII */ #HTNF_RESERVED3=(1 LSL 4);/* Reserved for system use */ #HTNF_CLEAN=(1 LSL 5);/* Remove the node from the database */ #HTNF_DONE=(1 LSL 6);/* Done with node */ ;/* onm_Attrs */ #HTNA_Dummy=(#TAG_USER) #HTNA_Screen=(#HTNA_Dummy+1);/* (struct Screen *) Screen that window resides in */ #HTNA_Pens=(#HTNA_Dummy+2);/* Pen array (from DrawInfo) */ #HTNA_Rectangle=(#HTNA_Dummy+3);/* Window box */ #HTNA_HelpGroup=(#HTNA_Dummy+5);/* (ULONG) unique identifier */ ;/* HM_EXPUNGE */ NEWTYPE.opExpungeNode MethodID.l *oen_Attrs.TagItem;/* R: Additional attributes */ End NEWTYPE CEND
412
0.835298
1
0.835298
game-dev
MEDIA
0.305565
game-dev
0.815829
1
0.815829
hengband/hengband
16,971
src/player/player-skill.cpp
#include "player/player-skill.h" #include "player-base/player-class.h" #include "player-base/player-race.h" #include "player-info/class-info.h" #include "player/player-realm.h" #include "sv-definition/sv-weapon-types.h" #include "system/floor/floor-info.h" #include "system/item-entity.h" #include "system/monrace/monrace-definition.h" #include "system/monster-entity.h" #include "system/player-type-definition.h" #include "system/redrawing-flags-updater.h" #include "util/bit-flags-calculator.h" /* Proficiency of weapons and misc. skills (except riding) */ constexpr SUB_EXP WEAPON_EXP_UNSKILLED = 0; constexpr SUB_EXP WEAPON_EXP_BEGINNER = 4000; constexpr SUB_EXP WEAPON_EXP_SKILLED = 6000; constexpr SUB_EXP WEAPON_EXP_EXPERT = 7000; constexpr SUB_EXP WEAPON_EXP_MASTER = 8000; /* Proficiency of riding */ constexpr SUB_EXP RIDING_EXP_UNSKILLED = 0; constexpr SUB_EXP RIDING_EXP_BEGINNER = 500; constexpr SUB_EXP RIDING_EXP_SKILLED = 2000; constexpr SUB_EXP RIDING_EXP_EXPERT = 5000; constexpr SUB_EXP RIDING_EXP_MASTER = 8000; /* Proficiency of spells */ constexpr SUB_EXP SPELL_EXP_UNSKILLED = 0; constexpr SUB_EXP SPELL_EXP_BEGINNER = 900; constexpr SUB_EXP SPELL_EXP_SKILLED = 1200; constexpr SUB_EXP SPELL_EXP_EXPERT = 1400; constexpr SUB_EXP SPELL_EXP_MASTER = 1600; /* * The skill table */ std::vector<skill_table> class_skills_info; namespace { using GainAmountList = std::array<int, enum2i(PlayerSkillRank::MASTER)>; void gain_attack_skill_exp(PlayerType *player_ptr, short &exp, const GainAmountList &gain_amount_list) { auto gain_amount = 0; auto calc_gain_amount = [&gain_amount_list, exp](PlayerSkillRank rank, int next_rank_exp) { return std::min(gain_amount_list[enum2i(rank)], next_rank_exp - exp); }; if (exp < WEAPON_EXP_BEGINNER) { gain_amount = calc_gain_amount(PlayerSkillRank::UNSKILLED, WEAPON_EXP_BEGINNER); } else if (exp < WEAPON_EXP_SKILLED) { gain_amount = calc_gain_amount(PlayerSkillRank::BEGINNER, WEAPON_EXP_SKILLED); } else if ((exp < WEAPON_EXP_EXPERT) && (player_ptr->lev > 19)) { gain_amount = calc_gain_amount(PlayerSkillRank::SKILLED, WEAPON_EXP_EXPERT); } else if ((exp < WEAPON_EXP_MASTER) && (player_ptr->lev > 34)) { gain_amount = calc_gain_amount(PlayerSkillRank::EXPERT, WEAPON_EXP_MASTER); } exp += static_cast<short>(gain_amount); RedrawingFlagsUpdater::get_instance().set_flag(StatusRecalculatingFlag::BONUS); } void gain_spell_skill_exp_aux(PlayerType *player_ptr, short &exp, const GainAmountList &gain_amount_list, int spell_level) { const auto dlev = player_ptr->current_floor_ptr->dun_level; const auto plev = player_ptr->lev; auto gain_amount = 0; auto calc_gain_amount = [&gain_amount_list, exp](PlayerSkillRank rank, int next_rank_exp) { return std::min(gain_amount_list[enum2i(rank)], next_rank_exp - exp); }; if (exp < SPELL_EXP_BEGINNER) { gain_amount = calc_gain_amount(PlayerSkillRank::UNSKILLED, SPELL_EXP_BEGINNER); } else if (exp < SPELL_EXP_SKILLED) { if ((dlev > 4) && ((dlev + 10) > plev)) { gain_amount = calc_gain_amount(PlayerSkillRank::BEGINNER, SPELL_EXP_SKILLED); } } else if (exp < SPELL_EXP_EXPERT) { if (((dlev + 5) > plev) && ((dlev + 5) > spell_level)) { gain_amount = calc_gain_amount(PlayerSkillRank::SKILLED, SPELL_EXP_EXPERT); } } else if (exp < SPELL_EXP_MASTER) { if (((dlev + 5) > plev) && (dlev > spell_level)) { gain_amount = calc_gain_amount(PlayerSkillRank::EXPERT, SPELL_EXP_MASTER); } } exp += static_cast<short>(gain_amount); RedrawingFlagsUpdater::get_instance().set_flag(StatusRecalculatingFlag::BONUS); } } PlayerSkill::PlayerSkill(PlayerType *player_ptr) : player_ptr(player_ptr) { } SUB_EXP PlayerSkill::weapon_exp_at(PlayerSkillRank rank) { switch (rank) { case PlayerSkillRank::UNSKILLED: return WEAPON_EXP_UNSKILLED; case PlayerSkillRank::BEGINNER: return WEAPON_EXP_BEGINNER; case PlayerSkillRank::SKILLED: return WEAPON_EXP_SKILLED; case PlayerSkillRank::EXPERT: return WEAPON_EXP_EXPERT; case PlayerSkillRank::MASTER: return WEAPON_EXP_MASTER; } return WEAPON_EXP_UNSKILLED; } SUB_EXP PlayerSkill::spell_exp_at(PlayerSkillRank rank) { switch (rank) { case PlayerSkillRank::UNSKILLED: return SPELL_EXP_UNSKILLED; case PlayerSkillRank::BEGINNER: return SPELL_EXP_BEGINNER; case PlayerSkillRank::SKILLED: return SPELL_EXP_SKILLED; case PlayerSkillRank::EXPERT: return SPELL_EXP_EXPERT; case PlayerSkillRank::MASTER: return SPELL_EXP_MASTER; } return SPELL_EXP_UNSKILLED; } /*! * @brief 武器や各種スキル(騎乗以外)の抽象的表現ランクを返す。 / Return proficiency level of weapons and misc. skills (except riding) * @param weapon_exp 経験値 * @return ランク値 */ PlayerSkillRank PlayerSkill::weapon_skill_rank(int weapon_exp) { if (weapon_exp < WEAPON_EXP_BEGINNER) { return PlayerSkillRank::UNSKILLED; } else if (weapon_exp < WEAPON_EXP_SKILLED) { return PlayerSkillRank::BEGINNER; } else if (weapon_exp < WEAPON_EXP_EXPERT) { return PlayerSkillRank::SKILLED; } else if (weapon_exp < WEAPON_EXP_MASTER) { return PlayerSkillRank::EXPERT; } else { return PlayerSkillRank::MASTER; } } bool PlayerSkill::valid_weapon_exp(int weapon_exp) { return (WEAPON_EXP_UNSKILLED <= weapon_exp) && (weapon_exp <= WEAPON_EXP_MASTER); } /*! * @brief 騎乗スキルの抽象的ランクを返す。 / Return proficiency level of riding * @param riding_exp 経験値 * @return ランク値 */ PlayerSkillRank PlayerSkill::riding_skill_rank(int riding_exp) { if (RIDING_EXP_UNSKILLED <= riding_exp && riding_exp < RIDING_EXP_BEGINNER) { return PlayerSkillRank::UNSKILLED; } else if (riding_exp < RIDING_EXP_SKILLED) { return PlayerSkillRank::BEGINNER; } else if (riding_exp < RIDING_EXP_EXPERT) { return PlayerSkillRank::SKILLED; } else if (riding_exp < RIDING_EXP_MASTER) { return PlayerSkillRank::EXPERT; } else { return PlayerSkillRank::MASTER; } } /*! * @brief プレイヤーの呪文レベルの抽象的ランクを返す。 / Return proficiency level of spells * @param spell_exp 経験値 * @return ランク値 */ PlayerSkillRank PlayerSkill::spell_skill_rank(int spell_exp) { if (spell_exp < SPELL_EXP_BEGINNER) { return PlayerSkillRank::UNSKILLED; } else if (spell_exp < SPELL_EXP_SKILLED) { return PlayerSkillRank::BEGINNER; } else if (spell_exp < SPELL_EXP_EXPERT) { return PlayerSkillRank::SKILLED; } else if (spell_exp < SPELL_EXP_MASTER) { return PlayerSkillRank::EXPERT; } else { return PlayerSkillRank::MASTER; } } concptr PlayerSkill::skill_name(PlayerSkillKindType skill) { switch (skill) { case PlayerSkillKindType::MARTIAL_ARTS: return _("マーシャルアーツ", "Martial Arts"); case PlayerSkillKindType::TWO_WEAPON: return _("二刀流", "Dual Wielding"); case PlayerSkillKindType::RIDING: return _("乗馬", "Riding"); case PlayerSkillKindType::SHIELD: return _("盾", "Shield"); case PlayerSkillKindType::MAX: break; } return _("不明", "Unknown"); } concptr PlayerSkill::skill_rank_str(PlayerSkillRank rank) { switch (rank) { case PlayerSkillRank::UNSKILLED: return _("[初心者]", "[Unskilled]"); case PlayerSkillRank::BEGINNER: return _("[入門者]", "[Beginner]"); case PlayerSkillRank::SKILLED: return _("[熟練者]", "[Skilled]"); case PlayerSkillRank::EXPERT: return _("[エキスパート]", "[Expert]"); case PlayerSkillRank::MASTER: return _("[達人]", "[Master]"); } return _("[不明]", "[Unknown]"); } void PlayerSkill::gain_melee_weapon_exp(const ItemEntity *o_ptr) { const GainAmountList gain_amount_list{ { 80, 10, 1, (one_in_(2) ? 1 : 0) } }; constexpr GainAmountList others_gain_amount_list{ { 8, 1, 0, 0 } }; const auto tval = o_ptr->bi_key.tval(); for (auto sval = 0U; sval < this->player_ptr->weapon_exp[tval].size(); ++sval) { auto &now_exp = this->player_ptr->weapon_exp[tval][sval]; if (now_exp < this->player_ptr->weapon_exp_max[tval][sval]) { gain_attack_skill_exp(this->player_ptr, now_exp, (static_cast<int>(sval) == o_ptr->bi_key.sval()) ? gain_amount_list : others_gain_amount_list); } } } void PlayerSkill::gain_range_weapon_exp(const ItemEntity *o_ptr) { constexpr GainAmountList gain_amount_list{ { 80, 25, 10, 2 } }; constexpr GainAmountList others_gain_amount_list{ { 8, 2, 0, 0 } }; const auto tval = o_ptr->bi_key.tval(); for (auto sval = 0U; sval < this->player_ptr->weapon_exp[tval].size(); ++sval) { auto &now_exp = this->player_ptr->weapon_exp[tval][sval]; if (now_exp < this->player_ptr->weapon_exp_max[tval][sval]) { gain_attack_skill_exp(this->player_ptr, now_exp, (static_cast<int>(sval) == o_ptr->bi_key.sval()) ? gain_amount_list : others_gain_amount_list); } } } void PlayerSkill::gain_martial_arts_skill_exp() { if (this->player_ptr->skill_exp[PlayerSkillKindType::MARTIAL_ARTS] < class_skills_info[enum2i(this->player_ptr->pclass)].s_max[PlayerSkillKindType::MARTIAL_ARTS]) { const GainAmountList gain_amount_list{ 40, 5, 1, (one_in_(3) ? 1 : 0) }; gain_attack_skill_exp(this->player_ptr, this->player_ptr->skill_exp[PlayerSkillKindType::MARTIAL_ARTS], gain_amount_list); } } void PlayerSkill::gain_two_weapon_skill_exp() { if (this->player_ptr->skill_exp[PlayerSkillKindType::TWO_WEAPON] < class_skills_info[enum2i(this->player_ptr->pclass)].s_max[PlayerSkillKindType::TWO_WEAPON]) { const GainAmountList gain_amount_list{ 80, 4, 1, (one_in_(3) ? 1 : 0) }; gain_attack_skill_exp(this->player_ptr, this->player_ptr->skill_exp[PlayerSkillKindType::TWO_WEAPON], gain_amount_list); } } void PlayerSkill::gain_riding_skill_exp_on_melee_attack(const MonraceDefinition &monrace) { auto now_exp = this->player_ptr->skill_exp[PlayerSkillKindType::RIDING]; auto max_exp = class_skills_info[enum2i(this->player_ptr->pclass)].s_max[PlayerSkillKindType::RIDING]; if (now_exp >= max_exp) { return; } auto riding_level = this->player_ptr->current_floor_ptr->m_list[this->player_ptr->riding].get_monrace().level; int inc = 0; if ((now_exp / 200 - 5) < monrace.level) { inc += 1; } if ((now_exp / 100) < riding_level) { if ((now_exp / 100 + 15) < riding_level) { inc += 1 + (riding_level - (now_exp / 100 + 15)); } else { inc += 1; } } this->player_ptr->skill_exp[PlayerSkillKindType::RIDING] = std::min<SUB_EXP>(max_exp, now_exp + inc); RedrawingFlagsUpdater::get_instance().set_flag(StatusRecalculatingFlag::BONUS); } void PlayerSkill::gain_riding_skill_exp_on_range_attack() { auto now_exp = this->player_ptr->skill_exp[PlayerSkillKindType::RIDING]; auto max_exp = class_skills_info[enum2i(this->player_ptr->pclass)].s_max[PlayerSkillKindType::RIDING]; if (now_exp >= max_exp) { return; } const auto &floor = *this->player_ptr->current_floor_ptr; const auto &monster = floor.m_list[this->player_ptr->riding]; const auto &monrace = monster.get_monrace(); if (((this->player_ptr->skill_exp[PlayerSkillKindType::RIDING] - (RIDING_EXP_BEGINNER * 2)) / 200 < monrace.level) && one_in_(2)) { this->player_ptr->skill_exp[PlayerSkillKindType::RIDING] += 1; RedrawingFlagsUpdater::get_instance().set_flag(StatusRecalculatingFlag::BONUS); } } void PlayerSkill::gain_riding_skill_exp_on_fall_off_check(int dam) { auto now_exp = this->player_ptr->skill_exp[PlayerSkillKindType::RIDING]; auto max_exp = class_skills_info[enum2i(this->player_ptr->pclass)].s_max[PlayerSkillKindType::RIDING]; if (now_exp >= max_exp || max_exp <= 1000) { return; } auto riding_level = this->player_ptr->current_floor_ptr->m_list[this->player_ptr->riding].get_monrace().level; if ((dam / 2 + riding_level) <= (now_exp / 30 + 10)) { return; } int inc = 0; if ((now_exp / 100 + 15) < riding_level) { inc += 1 + (riding_level - (now_exp / 100 + 15)); } else { inc += 1; } this->player_ptr->skill_exp[PlayerSkillKindType::RIDING] = std::min<SUB_EXP>(max_exp, now_exp + inc); RedrawingFlagsUpdater::get_instance().set_flag(StatusRecalculatingFlag::BONUS); } void PlayerSkill::gain_spell_skill_exp(RealmType realm, int spell_idx) { PlayerRealm pr(this->player_ptr); auto is_valid_realm = PlayerRealm::is_magic(realm) || (realm == RealmType::MUSIC) || (realm == RealmType::HEX); is_valid_realm &= pr.realm1().equals(realm) || pr.realm2().equals(realm); const auto is_valid_spell_idx = (0 <= spell_idx) && (spell_idx < 32); if (!is_valid_realm || !is_valid_spell_idx) { return; } constexpr GainAmountList gain_amount_list_first{ { 60, 8, 2, 1 } }; constexpr GainAmountList gain_amount_list_second{ { 60, 8, 2, 0 } }; const auto is_first_realm = pr.realm1().equals(realm); const auto &spell = PlayerRealm::get_spell_info(realm, spell_idx); gain_spell_skill_exp_aux(this->player_ptr, this->player_ptr->spell_exp[spell_idx + (is_first_realm ? 0 : 32)], (is_first_realm ? gain_amount_list_first : gain_amount_list_second), spell.slevel); } void PlayerSkill::gain_continuous_spell_skill_exp(RealmType realm, int spell_idx) { if (((spell_idx < 0) || (32 <= spell_idx)) || ((realm != RealmType::MUSIC) && (realm != RealmType::HEX))) { return; } const auto &spell = PlayerRealm::get_spell_info(realm, spell_idx); const GainAmountList gain_amount_list{ 5, (one_in_(2) ? 1 : 0), (one_in_(5) ? 1 : 0), (one_in_(5) ? 1 : 0) }; gain_spell_skill_exp_aux(this->player_ptr, this->player_ptr->spell_exp[spell_idx], gain_amount_list, spell.slevel); } PlayerSkillRank PlayerSkill::gain_spell_skill_exp_over_learning(int spell_idx) { if ((spell_idx < 0) || (static_cast<int>(std::size(this->player_ptr->spell_exp)) <= spell_idx)) { return PlayerSkillRank::UNSKILLED; } auto &exp = this->player_ptr->spell_exp[spell_idx]; if (exp >= SPELL_EXP_EXPERT) { exp = SPELL_EXP_MASTER; } else if (exp >= SPELL_EXP_SKILLED) { if (spell_idx >= 32) { exp = SPELL_EXP_EXPERT; } else { exp += SPELL_EXP_EXPERT - SPELL_EXP_SKILLED; } } else if (exp >= SPELL_EXP_BEGINNER) { exp = SPELL_EXP_SKILLED + (exp - SPELL_EXP_BEGINNER) * 2 / 3; } else { exp = SPELL_EXP_BEGINNER + exp / 3; } RedrawingFlagsUpdater::get_instance().set_flag(StatusRecalculatingFlag::BONUS); return PlayerSkill::spell_skill_rank(exp); } /*! * @brief 呪文の経験値を返す / * Returns experience of a spell * @param use_realm 魔法領域 * @param spell_idx 呪文ID * @return 経験値 */ EXP PlayerSkill::exp_of_spell(RealmType realm, int spell_idx) const { PlayerClass pc(this->player_ptr); PlayerRealm pr(this->player_ptr); if (pc.equals(PlayerClassType::SORCERER)) { return SPELL_EXP_MASTER; } else if (pc.equals(PlayerClassType::RED_MAGE)) { return SPELL_EXP_SKILLED; } else if (pr.realm1().equals(realm)) { return this->player_ptr->spell_exp[spell_idx]; } else if (pr.realm2().equals(realm)) { return this->player_ptr->spell_exp[spell_idx + 32]; } else { return 0; } } /*! * @brief 特別な武器スキル最大値の適用を行う * 性格セクシーギャルの場合ムチスキルの最大値が達人になる * 種族マーフォークの場合三叉槍とトライデントのスキルが達人になる * (但し、いずれも職業がスペルマスターではない場合に限る) */ void PlayerSkill::apply_special_weapon_skill_max_values() { this->player_ptr->weapon_exp_max = class_skills_info[enum2i(this->player_ptr->pclass)].w_max; if (PlayerClass(this->player_ptr).equals(PlayerClassType::SORCERER)) { return; } auto &w_exp_max = this->player_ptr->weapon_exp_max; if (this->player_ptr->ppersonality == PERSONALITY_SEXY) { w_exp_max[ItemKindType::HAFTED][SV_WHIP] = PlayerSkill::weapon_exp_at(PlayerSkillRank::MASTER); } if (PlayerRace(player_ptr).equals(PlayerRaceType::MERFOLK)) { w_exp_max[ItemKindType::POLEARM][SV_TRIDENT] = PlayerSkill::weapon_exp_at(PlayerSkillRank::MASTER); w_exp_max[ItemKindType::POLEARM][SV_TRIFURCATE_SPEAR] = PlayerSkill::weapon_exp_at(PlayerSkillRank::MASTER); } } /*! * @brief 武器スキル経験値を最大値で制限する */ void PlayerSkill::limit_weapon_skills_by_max_value() { for (auto tval : TV_WEAPON_RANGE) { auto &exp_table = this->player_ptr->weapon_exp[tval]; const auto &max_exp_table = this->player_ptr->weapon_exp_max[tval]; for (auto i = 0U; i < exp_table.size(); ++i) { exp_table[i] = std::min(exp_table[i], max_exp_table[i]); } } }
412
0.786361
1
0.786361
game-dev
MEDIA
0.988558
game-dev
0.559797
1
0.559797
SinlessDevil/ZenjectTemplate
29,944
Assets/Plugins/UniTask/Runtime/UniTaskExtensions.cs
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member using System; using System.Collections; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Cysharp.Threading.Tasks.Internal; namespace Cysharp.Threading.Tasks { public static partial class UniTaskExtensions { /// <summary> /// Convert Task[T] -> UniTask[T]. /// </summary> public static UniTask<T> AsUniTask<T>(this Task<T> task, bool useCurrentSynchronizationContext = true) { var promise = new UniTaskCompletionSource<T>(); task.ContinueWith((x, state) => { var p = (UniTaskCompletionSource<T>)state; switch (x.Status) { case TaskStatus.Canceled: p.TrySetCanceled(); break; case TaskStatus.Faulted: p.TrySetException(x.Exception.InnerException ?? x.Exception); break; case TaskStatus.RanToCompletion: p.TrySetResult(x.Result); break; default: throw new NotSupportedException(); } }, promise, useCurrentSynchronizationContext ? TaskScheduler.FromCurrentSynchronizationContext() : TaskScheduler.Current); return promise.Task; } /// <summary> /// Convert Task -> UniTask. /// </summary> public static UniTask AsUniTask(this Task task, bool useCurrentSynchronizationContext = true) { var promise = new UniTaskCompletionSource(); task.ContinueWith((x, state) => { var p = (UniTaskCompletionSource)state; switch (x.Status) { case TaskStatus.Canceled: p.TrySetCanceled(); break; case TaskStatus.Faulted: p.TrySetException(x.Exception.InnerException ?? x.Exception); break; case TaskStatus.RanToCompletion: p.TrySetResult(); break; default: throw new NotSupportedException(); } }, promise, useCurrentSynchronizationContext ? TaskScheduler.FromCurrentSynchronizationContext() : TaskScheduler.Current); return promise.Task; } public static Task<T> AsTask<T>(this UniTask<T> task) { try { UniTask<T>.Awaiter awaiter; try { awaiter = task.GetAwaiter(); } catch (Exception ex) { return Task.FromException<T>(ex); } if (awaiter.IsCompleted) { try { var result = awaiter.GetResult(); return Task.FromResult(result); } catch (Exception ex) { return Task.FromException<T>(ex); } } var tcs = new TaskCompletionSource<T>(); awaiter.SourceOnCompleted(state => { using (var tuple = (StateTuple<TaskCompletionSource<T>, UniTask<T>.Awaiter>)state) { var (inTcs, inAwaiter) = tuple; try { var result = inAwaiter.GetResult(); inTcs.SetResult(result); } catch (Exception ex) { inTcs.SetException(ex); } } }, StateTuple.Create(tcs, awaiter)); return tcs.Task; } catch (Exception ex) { return Task.FromException<T>(ex); } } public static Task AsTask(this UniTask task) { try { UniTask.Awaiter awaiter; try { awaiter = task.GetAwaiter(); } catch (Exception ex) { return Task.FromException(ex); } if (awaiter.IsCompleted) { try { awaiter.GetResult(); // check token valid on Succeeded return Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } var tcs = new TaskCompletionSource<object>(); awaiter.SourceOnCompleted(state => { using (var tuple = (StateTuple<TaskCompletionSource<object>, UniTask.Awaiter>)state) { var (inTcs, inAwaiter) = tuple; try { inAwaiter.GetResult(); inTcs.SetResult(null); } catch (Exception ex) { inTcs.SetException(ex); } } }, StateTuple.Create(tcs, awaiter)); return tcs.Task; } catch (Exception ex) { return Task.FromException(ex); } } public static AsyncLazy ToAsyncLazy(this UniTask task) { return new AsyncLazy(task); } public static AsyncLazy<T> ToAsyncLazy<T>(this UniTask<T> task) { return new AsyncLazy<T>(task); } /// <summary> /// Ignore task result when cancel raised first. /// </summary> public static UniTask AttachExternalCancellation(this UniTask task, CancellationToken cancellationToken) { if (!cancellationToken.CanBeCanceled) { return task; } if (cancellationToken.IsCancellationRequested) { task.Forget(); return UniTask.FromCanceled(cancellationToken); } if (task.Status.IsCompleted()) { return task; } return new UniTask(new AttachExternalCancellationSource(task, cancellationToken), 0); } /// <summary> /// Ignore task result when cancel raised first. /// </summary> public static UniTask<T> AttachExternalCancellation<T>(this UniTask<T> task, CancellationToken cancellationToken) { if (!cancellationToken.CanBeCanceled) { return task; } if (cancellationToken.IsCancellationRequested) { task.Forget(); return UniTask.FromCanceled<T>(cancellationToken); } if (task.Status.IsCompleted()) { return task; } return new UniTask<T>(new AttachExternalCancellationSource<T>(task, cancellationToken), 0); } sealed class AttachExternalCancellationSource : IUniTaskSource { static readonly Action<object> cancellationCallbackDelegate = CancellationCallback; CancellationToken cancellationToken; CancellationTokenRegistration tokenRegistration; UniTaskCompletionSourceCore<AsyncUnit> core; public AttachExternalCancellationSource(UniTask task, CancellationToken cancellationToken) { this.cancellationToken = cancellationToken; this.tokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallbackDelegate, this); RunTask(task).Forget(); } async UniTaskVoid RunTask(UniTask task) { try { await task; core.TrySetResult(AsyncUnit.Default); } catch (Exception ex) { core.TrySetException(ex); } finally { tokenRegistration.Dispose(); } } static void CancellationCallback(object state) { var self = (AttachExternalCancellationSource)state; self.core.TrySetCanceled(self.cancellationToken); } public void GetResult(short token) { core.GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } } sealed class AttachExternalCancellationSource<T> : IUniTaskSource<T> { static readonly Action<object> cancellationCallbackDelegate = CancellationCallback; CancellationToken cancellationToken; CancellationTokenRegistration tokenRegistration; UniTaskCompletionSourceCore<T> core; public AttachExternalCancellationSource(UniTask<T> task, CancellationToken cancellationToken) { this.cancellationToken = cancellationToken; this.tokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallbackDelegate, this); RunTask(task).Forget(); } async UniTaskVoid RunTask(UniTask<T> task) { try { core.TrySetResult(await task); } catch (Exception ex) { core.TrySetException(ex); } finally { tokenRegistration.Dispose(); } } static void CancellationCallback(object state) { var self = (AttachExternalCancellationSource<T>)state; self.core.TrySetCanceled(self.cancellationToken); } void IUniTaskSource.GetResult(short token) { core.GetResult(token); } public T GetResult(short token) { return core.GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } } #if UNITY_2018_3_OR_NEWER public static IEnumerator ToCoroutine<T>(this UniTask<T> task, Action<T> resultHandler = null, Action<Exception> exceptionHandler = null) { return new ToCoroutineEnumerator<T>(task, resultHandler, exceptionHandler); } public static IEnumerator ToCoroutine(this UniTask task, Action<Exception> exceptionHandler = null) { return new ToCoroutineEnumerator(task, exceptionHandler); } public static async UniTask Timeout(this UniTask task, TimeSpan timeout, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming timeoutCheckTiming = PlayerLoopTiming.Update, CancellationTokenSource taskCancellationTokenSource = null) { var delayCancellationTokenSource = new CancellationTokenSource(); var timeoutTask = UniTask.Delay(timeout, delayType, timeoutCheckTiming, delayCancellationTokenSource.Token).SuppressCancellationThrow(); int winArgIndex; bool taskResultIsCanceled; try { (winArgIndex, taskResultIsCanceled, _) = await UniTask.WhenAny(task.SuppressCancellationThrow(), timeoutTask); } catch { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); throw; } // timeout if (winArgIndex == 1) { if (taskCancellationTokenSource != null) { taskCancellationTokenSource.Cancel(); taskCancellationTokenSource.Dispose(); } throw new TimeoutException("Exceed Timeout:" + timeout); } else { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); } if (taskResultIsCanceled) { Error.ThrowOperationCanceledException(); } } public static async UniTask<T> Timeout<T>(this UniTask<T> task, TimeSpan timeout, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming timeoutCheckTiming = PlayerLoopTiming.Update, CancellationTokenSource taskCancellationTokenSource = null) { var delayCancellationTokenSource = new CancellationTokenSource(); var timeoutTask = UniTask.Delay(timeout, delayType, timeoutCheckTiming, delayCancellationTokenSource.Token).SuppressCancellationThrow(); int winArgIndex; (bool IsCanceled, T Result) taskResult; try { (winArgIndex, taskResult, _) = await UniTask.WhenAny(task.SuppressCancellationThrow(), timeoutTask); } catch { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); throw; } // timeout if (winArgIndex == 1) { if (taskCancellationTokenSource != null) { taskCancellationTokenSource.Cancel(); taskCancellationTokenSource.Dispose(); } throw new TimeoutException("Exceed Timeout:" + timeout); } else { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); } if (taskResult.IsCanceled) { Error.ThrowOperationCanceledException(); } return taskResult.Result; } /// <summary> /// Timeout with suppress OperationCanceledException. Returns (bool, IsCanceled). /// </summary> public static async UniTask<bool> TimeoutWithoutException(this UniTask task, TimeSpan timeout, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming timeoutCheckTiming = PlayerLoopTiming.Update, CancellationTokenSource taskCancellationTokenSource = null) { var delayCancellationTokenSource = new CancellationTokenSource(); var timeoutTask = UniTask.Delay(timeout, delayType, timeoutCheckTiming, delayCancellationTokenSource.Token).SuppressCancellationThrow(); int winArgIndex; bool taskResultIsCanceled; try { (winArgIndex, taskResultIsCanceled, _) = await UniTask.WhenAny(task.SuppressCancellationThrow(), timeoutTask); } catch { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); return true; } // timeout if (winArgIndex == 1) { if (taskCancellationTokenSource != null) { taskCancellationTokenSource.Cancel(); taskCancellationTokenSource.Dispose(); } return true; } else { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); } if (taskResultIsCanceled) { return true; } return false; } /// <summary> /// Timeout with suppress OperationCanceledException. Returns (bool IsTimeout, T Result). /// </summary> public static async UniTask<(bool IsTimeout, T Result)> TimeoutWithoutException<T>(this UniTask<T> task, TimeSpan timeout, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming timeoutCheckTiming = PlayerLoopTiming.Update, CancellationTokenSource taskCancellationTokenSource = null) { var delayCancellationTokenSource = new CancellationTokenSource(); var timeoutTask = UniTask.Delay(timeout, delayType, timeoutCheckTiming, delayCancellationTokenSource.Token).SuppressCancellationThrow(); int winArgIndex; (bool IsCanceled, T Result) taskResult; try { (winArgIndex, taskResult, _) = await UniTask.WhenAny(task.SuppressCancellationThrow(), timeoutTask); } catch { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); return (true, default); } // timeout if (winArgIndex == 1) { if (taskCancellationTokenSource != null) { taskCancellationTokenSource.Cancel(); taskCancellationTokenSource.Dispose(); } return (true, default); } else { delayCancellationTokenSource.Cancel(); delayCancellationTokenSource.Dispose(); } if (taskResult.IsCanceled) { return (true, default); } return (false, taskResult.Result); } #endif public static void Forget(this UniTask task) { var awaiter = task.GetAwaiter(); if (awaiter.IsCompleted) { try { awaiter.GetResult(); } catch (Exception ex) { UniTaskScheduler.PublishUnobservedTaskException(ex); } } else { awaiter.SourceOnCompleted(state => { using (var t = (StateTuple<UniTask.Awaiter>)state) { try { t.Item1.GetResult(); } catch (Exception ex) { UniTaskScheduler.PublishUnobservedTaskException(ex); } } }, StateTuple.Create(awaiter)); } } public static void Forget(this UniTask task, Action<Exception> exceptionHandler, bool handleExceptionOnMainThread = true) { if (exceptionHandler == null) { Forget(task); } else { ForgetCoreWithCatch(task, exceptionHandler, handleExceptionOnMainThread).Forget(); } } static async UniTaskVoid ForgetCoreWithCatch(UniTask task, Action<Exception> exceptionHandler, bool handleExceptionOnMainThread) { try { await task; } catch (Exception ex) { try { if (handleExceptionOnMainThread) { #if UNITY_2018_3_OR_NEWER await UniTask.SwitchToMainThread(); #endif } exceptionHandler(ex); } catch (Exception ex2) { UniTaskScheduler.PublishUnobservedTaskException(ex2); } } } public static void Forget<T>(this UniTask<T> task) { var awaiter = task.GetAwaiter(); if (awaiter.IsCompleted) { try { awaiter.GetResult(); } catch (Exception ex) { UniTaskScheduler.PublishUnobservedTaskException(ex); } } else { awaiter.SourceOnCompleted(state => { using (var t = (StateTuple<UniTask<T>.Awaiter>)state) { try { t.Item1.GetResult(); } catch (Exception ex) { UniTaskScheduler.PublishUnobservedTaskException(ex); } } }, StateTuple.Create(awaiter)); } } public static void Forget<T>(this UniTask<T> task, Action<Exception> exceptionHandler, bool handleExceptionOnMainThread = true) { if (exceptionHandler == null) { task.Forget(); } else { ForgetCoreWithCatch(task, exceptionHandler, handleExceptionOnMainThread).Forget(); } } static async UniTaskVoid ForgetCoreWithCatch<T>(UniTask<T> task, Action<Exception> exceptionHandler, bool handleExceptionOnMainThread) { try { await task; } catch (Exception ex) { try { if (handleExceptionOnMainThread) { #if UNITY_2018_3_OR_NEWER await UniTask.SwitchToMainThread(); #endif } exceptionHandler(ex); } catch (Exception ex2) { UniTaskScheduler.PublishUnobservedTaskException(ex2); } } } public static async UniTask ContinueWith<T>(this UniTask<T> task, Action<T> continuationFunction) { continuationFunction(await task); } public static async UniTask ContinueWith<T>(this UniTask<T> task, Func<T, UniTask> continuationFunction) { await continuationFunction(await task); } public static async UniTask<TR> ContinueWith<T, TR>(this UniTask<T> task, Func<T, TR> continuationFunction) { return continuationFunction(await task); } public static async UniTask<TR> ContinueWith<T, TR>(this UniTask<T> task, Func<T, UniTask<TR>> continuationFunction) { return await continuationFunction(await task); } public static async UniTask ContinueWith(this UniTask task, Action continuationFunction) { await task; continuationFunction(); } public static async UniTask ContinueWith(this UniTask task, Func<UniTask> continuationFunction) { await task; await continuationFunction(); } public static async UniTask<T> ContinueWith<T>(this UniTask task, Func<T> continuationFunction) { await task; return continuationFunction(); } public static async UniTask<T> ContinueWith<T>(this UniTask task, Func<UniTask<T>> continuationFunction) { await task; return await continuationFunction(); } public static async UniTask<T> Unwrap<T>(this UniTask<UniTask<T>> task) { return await await task; } public static async UniTask Unwrap(this UniTask<UniTask> task) { await await task; } public static async UniTask<T> Unwrap<T>(this Task<UniTask<T>> task) { return await await task; } public static async UniTask<T> Unwrap<T>(this Task<UniTask<T>> task, bool continueOnCapturedContext) { return await await task.ConfigureAwait(continueOnCapturedContext); } public static async UniTask Unwrap(this Task<UniTask> task) { await await task; } public static async UniTask Unwrap(this Task<UniTask> task, bool continueOnCapturedContext) { await await task.ConfigureAwait(continueOnCapturedContext); } public static async UniTask<T> Unwrap<T>(this UniTask<Task<T>> task) { return await await task; } public static async UniTask<T> Unwrap<T>(this UniTask<Task<T>> task, bool continueOnCapturedContext) { return await (await task).ConfigureAwait(continueOnCapturedContext); } public static async UniTask Unwrap(this UniTask<Task> task) { await await task; } public static async UniTask Unwrap(this UniTask<Task> task, bool continueOnCapturedContext) { await (await task).ConfigureAwait(continueOnCapturedContext); } #if UNITY_2018_3_OR_NEWER sealed class ToCoroutineEnumerator : IEnumerator { bool completed; UniTask task; Action<Exception> exceptionHandler = null; bool isStarted = false; ExceptionDispatchInfo exception; public ToCoroutineEnumerator(UniTask task, Action<Exception> exceptionHandler) { completed = false; this.exceptionHandler = exceptionHandler; this.task = task; } async UniTaskVoid RunTask(UniTask task) { try { await task; } catch (Exception ex) { if (exceptionHandler != null) { exceptionHandler(ex); } else { this.exception = ExceptionDispatchInfo.Capture(ex); } } finally { completed = true; } } public object Current => null; public bool MoveNext() { if (!isStarted) { isStarted = true; RunTask(task).Forget(); } if (exception != null) { exception.Throw(); return false; } return !completed; } void IEnumerator.Reset() { } } sealed class ToCoroutineEnumerator<T> : IEnumerator { bool completed; Action<T> resultHandler = null; Action<Exception> exceptionHandler = null; bool isStarted = false; UniTask<T> task; object current = null; ExceptionDispatchInfo exception; public ToCoroutineEnumerator(UniTask<T> task, Action<T> resultHandler, Action<Exception> exceptionHandler) { completed = false; this.task = task; this.resultHandler = resultHandler; this.exceptionHandler = exceptionHandler; } async UniTaskVoid RunTask(UniTask<T> task) { try { var value = await task; current = value; // boxed if T is struct... if (resultHandler != null) { resultHandler(value); } } catch (Exception ex) { if (exceptionHandler != null) { exceptionHandler(ex); } else { this.exception = ExceptionDispatchInfo.Capture(ex); } } finally { completed = true; } } public object Current => current; public bool MoveNext() { if (!isStarted) { isStarted = true; RunTask(task).Forget(); } if (exception != null) { exception.Throw(); return false; } return !completed; } void IEnumerator.Reset() { } } #endif } }
412
0.975615
1
0.975615
game-dev
MEDIA
0.449007
game-dev
0.97154
1
0.97154
lunar-sway/minestuck
1,694
src/main/java/com/mraof/minestuck/item/loot/conditions/ConsortLootCondition.java
package com.mraof.minestuck.item.loot.conditions; import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import com.mraof.minestuck.entity.consort.EnumConsort; import com.mraof.minestuck.item.loot.MSLootTables; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType; import java.util.List; @MethodsReturnNonnullByDefault public class ConsortLootCondition implements LootItemCondition { public static final MapCodec<ConsortLootCondition> CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group(EnumConsort.SINGLE_OR_LIST_CODEC.fieldOf("consort").forGetter(condition -> condition.consorts)) .apply(instance, ConsortLootCondition::new)); private final List<EnumConsort> consorts; public ConsortLootCondition(List<EnumConsort> consorts) { this.consorts = consorts; } @Override public LootItemConditionType getType() { return MSLootTables.CONSORT_CONDITION.get(); } @Override public boolean test(LootContext context) { Entity entity = context.getParamOrNull(LootContextParams.THIS_ENTITY); if(entity != null) for(EnumConsort type : consorts) if(type.isConsort(entity)) return true; return false; } public static Builder builder(EnumConsort... consorts) { return () -> new ConsortLootCondition(List.of(consorts)); } }
412
0.673475
1
0.673475
game-dev
MEDIA
0.990794
game-dev
0.894673
1
0.894673
cuberite/cuberite
2,285
src/Simulator/SandSimulator.h
#pragma once #include "Simulator.h" #include "../IniFile.h" // fwd: class cChunk; /** Per-chunk data for the simulator, specified individual chunks to simulate; Data is not used */ typedef cCoordWithIntList cSandSimulatorChunkData; /** Despite the class name, this simulator takes care of all blocks that fall when suspended in the air. */ class cSandSimulator : public cSimulator { public: cSandSimulator(cWorld & a_World, cIniFile & a_IniFile); /** Returns true if a falling-able block can start falling through the specified block type */ static bool CanStartFallingThrough(BLOCKTYPE a_BlockType); /** Returns true if an already-falling block can pass through the specified block type (e. g. torch) */ static bool CanContinueFallThrough(BLOCKTYPE a_BlockType); /** Returns true if the falling block rematerializing will replace the specified block type (e. g. tall grass) */ static bool IsReplacedOnRematerialization(BLOCKTYPE a_BlockType); /** Returns true if the specified block breaks falling blocks while they fall through it (e. g. halfslabs) */ static bool DoesBreakFallingThrough(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta); /** Called when a block finishes falling at the specified coords, either by insta-fall, or through cFallingBlock entity. It either rematerializes the block (a_FallingBlockType) at the specified coords, or creates a pickup, based on the block currently present in the world at the dest specified coords. */ static void FinishFalling( cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_FallingBlockType, NIBBLETYPE a_FallingBlockMeta ); static bool IsAllowedBlock(BLOCKTYPE a_BlockType); private: virtual void SimulateChunk(std::chrono::milliseconds a_Dt, int a_ChunkX, int a_ChunkZ, cChunk * a_Chunk) override; bool m_IsInstantFall; // If set to true, blocks don't fall using cFallingBlock entity, but instantly instead int m_TotalBlocks; // Total number of blocks currently in the queue for simulating virtual void AddBlock(cChunk & a_Chunk, Vector3i a_Position, BLOCKTYPE a_Block) override; /** Performs the instant fall of the block - removes it from top, Finishes it at the bottom */ void DoInstantFall(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ); };
412
0.947245
1
0.947245
game-dev
MEDIA
0.669097
game-dev
0.723787
1
0.723787
magefree/mage
2,123
Mage.Sets/src/mage/cards/s/SpontaneousMutation.java
package mage.cards.s; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.dynamicvalue.DynamicValue; import mage.abilities.dynamicvalue.common.CardsInControllerGraveyardCount; import mage.abilities.dynamicvalue.common.SignInversionDynamicValue; import mage.abilities.dynamicvalue.common.StaticValue; import mage.abilities.effects.common.AttachEffect; import mage.abilities.effects.common.continuous.BoostEnchantedEffect; import mage.abilities.keyword.EnchantAbility; import mage.abilities.keyword.FlashAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.SubType; import mage.target.TargetPermanent; import mage.target.common.TargetCreaturePermanent; import java.util.UUID; /** * @author LevelX2 */ public final class SpontaneousMutation extends CardImpl { private static final DynamicValue value = new SignInversionDynamicValue(new CardsInControllerGraveyardCount()); public SpontaneousMutation(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{U}"); this.subtype.add(SubType.AURA); // Flash this.addAbility(FlashAbility.getInstance()); // Enchant creature TargetPermanent auraTarget = new TargetCreaturePermanent(); this.getSpellAbility().addTarget(auraTarget); this.getSpellAbility().addEffect(new AttachEffect(Outcome.Detriment)); Ability ability = new EnchantAbility(auraTarget); this.addAbility(ability); // Enchanted creature gets -X/-0, where X is the number of cards in your graveyard. this.addAbility(new SimpleStaticAbility(new BoostEnchantedEffect(value, StaticValue.get(0)) .setText("enchanted creature gets -X/-0, where X is the number of cards in your graveyard"))); } private SpontaneousMutation(final SpontaneousMutation card) { super(card); } @Override public SpontaneousMutation copy() { return new SpontaneousMutation(this); } }
412
0.956639
1
0.956639
game-dev
MEDIA
0.973513
game-dev
0.986429
1
0.986429
11011010/BFA-Frankenstein-Core
3,958
src/server/database/Database/Implementation/WorldDatabase.h
/* * 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/>. */ #ifndef _WORLDDATABASE_H #define _WORLDDATABASE_H #include "MySQLConnection.h" enum WorldDatabaseStatements : uint32 { /* Naming standard for defines: {DB}_{SEL/INS/UPD/DEL/REP}_{Summary of data changed} When updating more than one field, consider looking at the calling function name for a suiting suffix. */ WORLD_SEL_QUEST_POOLS, WORLD_DEL_CRELINKED_RESPAWN, WORLD_REP_CREATURE_LINKED_RESPAWN, WORLD_SEL_CREATURE_TEXT, WORLD_SEL_SMART_SCRIPTS, WORLD_SEL_SMARTAI_WP, WORLD_SEL_ARCHAEOLOGY_DIGSITES, WORLD_SEL_ARCHAEOLOGY_ARTIFACT, WORLD_DEL_GAMEOBJECT, WORLD_DEL_EVENT_GAMEOBJECT, WORLD_INS_GRAVEYARD_ZONE, WORLD_DEL_GRAVEYARD_ZONE, WORLD_INS_GAME_TELE, WORLD_DEL_GAME_TELE, WORLD_INS_NPC_VENDOR, WORLD_DEL_NPC_VENDOR, WORLD_SEL_NPC_VENDOR_REF, WORLD_UPD_CREATURE_MOVEMENT_TYPE, WORLD_UPD_CREATURE_FACTION, WORLD_UPD_CREATURE_NPCFLAG, WORLD_UPD_CREATURE_POSITION, WORLD_UPD_CREATURE_SPAWN_DISTANCE, WORLD_UPD_CREATURE_SPAWN_TIME_SECS, WORLD_INS_CREATURE_FORMATION, WORLD_INS_WAYPOINT_DATA, WORLD_DEL_WAYPOINT_DATA, WORLD_UPD_WAYPOINT_DATA_POINT, WORLD_UPD_WAYPOINT_DATA_POSITION, WORLD_UPD_WAYPOINT_DATA_WPGUID, WORLD_UPD_WAYPOINT_DATA_ALL_WPGUID, WORLD_SEL_WAYPOINT_DATA_MAX_ID, WORLD_SEL_WAYPOINT_DATA_BY_ID, WORLD_SEL_WAYPOINT_DATA_POS_BY_ID, WORLD_SEL_WAYPOINT_DATA_POS_FIRST_BY_ID, WORLD_SEL_WAYPOINT_DATA_POS_LAST_BY_ID, WORLD_SEL_WAYPOINT_DATA_BY_WPGUID, WORLD_SEL_WAYPOINT_DATA_ALL_BY_WPGUID, WORLD_SEL_WAYPOINT_DATA_MAX_POINT, WORLD_SEL_WAYPOINT_DATA_BY_POS, WORLD_SEL_WAYPOINT_DATA_WPGUID_BY_ID, WORLD_SEL_WAYPOINT_DATA_ACTION, WORLD_SEL_WAYPOINT_SCRIPTS_MAX_ID, WORLD_UPD_CREATURE_ADDON_PATH, WORLD_INS_CREATURE_ADDON, WORLD_DEL_CREATURE_ADDON, WORLD_SEL_CREATURE_ADDON_BY_GUID, WORLD_INS_WAYPOINT_SCRIPT, WORLD_DEL_WAYPOINT_SCRIPT, WORLD_UPD_WAYPOINT_SCRIPT_ID, WORLD_UPD_WAYPOINT_SCRIPT_X, WORLD_UPD_WAYPOINT_SCRIPT_Y, WORLD_UPD_WAYPOINT_SCRIPT_Z, WORLD_UPD_WAYPOINT_SCRIPT_O, WORLD_SEL_WAYPOINT_SCRIPT_ID_BY_GUID, WORLD_DEL_CREATURE, WORLD_SEL_COMMANDS, WORLD_SEL_CREATURE_TEMPLATE, WORLD_SEL_WAYPOINT_SCRIPT_BY_ID, WORLD_SEL_CREATURE_BY_ID, WORLD_SEL_GAMEOBJECT_NEAREST, WORLD_SEL_CREATURE_NEAREST, WORLD_SEL_GAMEOBJECT_TARGET, WORLD_INS_CREATURE, WORLD_DEL_GAME_EVENT_CREATURE, WORLD_DEL_GAME_EVENT_MODEL_EQUIP, WORLD_INS_GAMEOBJECT, WORLD_SEL_DISABLES, WORLD_INS_DISABLES, WORLD_DEL_DISABLES, WORLD_UPD_CREATURE_ZONE_AREA_DATA, WORLD_UPD_GAMEOBJECT_ZONE_AREA_DATA, WORLD_SEL_GUILD_REWARDS_REQ_ACHIEVEMENTS, MAX_WORLDDATABASE_STATEMENTS }; class TC_DATABASE_API WorldDatabaseConnection : public MySQLConnection { public: typedef WorldDatabaseStatements Statements; //- Constructors for sync and async connections WorldDatabaseConnection(MySQLConnectionInfo& connInfo); WorldDatabaseConnection(ProducerConsumerQueue<SQLOperation*>* q, MySQLConnectionInfo& connInfo); ~WorldDatabaseConnection(); //- Loads database type specific prepared statements void DoPrepareStatements() override; }; #endif
412
0.761228
1
0.761228
game-dev
MEDIA
0.928265
game-dev
0.517341
1
0.517341
goonstation/goonstation-2016
1,425
code/datums/effects/system/harmless_smoke_spread.dm
///////////////////////////////////////////// //// SMOKE SYSTEMS // direct can be optinally added when set_up, to make the smoke always travel in one direction // in case you wanted a vent to always smoke north for example ///////////////////////////////////////////// /datum/effects/system/harmless_smoke_spread var/number = 3 var/cardinals = 0 var/turf/location var/atom/holder var/total_smoke = 0 // To stop it being spammed and lagging! var/direction /datum/effects/system/harmless_smoke_spread/proc/set_up(n = 5, c = 0, loca, direct) if(n > 10) n = 10 number = n cardinals = c if(istype(loca, /turf/)) location = loca else location = get_turf(loca) if(direct) direction = direct /datum/effects/system/harmless_smoke_spread/proc/attach(atom/atom) holder = atom /datum/effects/system/harmless_smoke_spread/proc/start() var/i = 0 for(i=0, i<src.number, i++) if(src.total_smoke > 20) return spawn(0) if(holder) src.location = get_turf(holder) var/obj/effects/harmless_smoke/smoke = unpool(/obj/effects/harmless_smoke) smoke.set_loc(src.location) src.total_smoke++ var/direction = src.direction if(!direction) if(src.cardinals) direction = pick(cardinal) else direction = pick(alldirs) for(var/j=0, j<pick(0,1,1,1,2,2,2,3), j++) sleep(10) step(smoke,direction) spawn(75+rand(10,30)) if (smoke) pool(smoke) src.total_smoke--
412
0.524553
1
0.524553
game-dev
MEDIA
0.497621
game-dev
0.696366
1
0.696366
ineedbots/iw3_bot_warfare
4,901
maps/mp/gametypes/_callbacksetup.gsx
// Callback Setup // This script provides the hooks from code into script for the gametype callback functions. // Cod4x bootstrapping custom scripts //============================================================================= // Code Callback functions /*================ Called by code after the level's main script function has run. ================*/ CodeCallback_StartGameType() { // If the gametype has not beed started, run the startup if ( !isDefined( level.gametypestarted ) || !level.gametypestarted ) { [[level.callbackStartGameType]](); level.gametypestarted = true; // so we know that the gametype has been started up level thread scripts\mp\bots_adapter_cod4x::init(); level thread scripts\mp\bots_chat::init(); level thread scripts\mp\bots_menu::init(); level thread scripts\mp\bots_wp_editor::init(); level thread scripts\mp\bots::init(); } } /*================ Called when a player begins connecting to the server. Called again for every map change or tournement restart. Return undefined if the client should be allowed, otherwise return a string with the reason for denial. Otherwise, the client will be sent the current gamestate and will eventually get to ClientBegin. firstTime will be qtrue the very first time a client connects to the server machine, but qfalse on map changes and tournement restarts. ================*/ CodeCallback_PlayerConnect() { self endon( "disconnect" ); [[level.callbackPlayerConnect]](); } /*================ Called when a player drops from the server. Will not be called between levels. self is the player that is disconnecting. ================*/ CodeCallback_PlayerDisconnect() { self notify( "disconnect" ); [[level.callbackPlayerDisconnect]](); } /*================ Called when a player has taken damage. self is the player that took damage. ================*/ CodeCallback_PlayerDamage( eInflictor, eAttacker, iDamage, iDFlags, sMeansOfDeath, sWeapon, vPoint, vDir, sHitLoc, timeOffset ) { self endon( "disconnect" ); [[level.callbackPlayerDamage]]( eInflictor, eAttacker, iDamage, iDFlags, sMeansOfDeath, sWeapon, vPoint, vDir, sHitLoc, timeOffset ); } /*================ Called when a player has been killed. self is the player that was killed. ================*/ CodeCallback_PlayerKilled( eInflictor, eAttacker, iDamage, sMeansOfDeath, sWeapon, vDir, sHitLoc, timeOffset, deathAnimDuration ) { self endon( "disconnect" ); [[level.callbackPlayerKilled]]( eInflictor, eAttacker, iDamage, sMeansOfDeath, sWeapon, vDir, sHitLoc, timeOffset, deathAnimDuration ); } /*================ Called when a player has been killed, but has last stand perk. self is the player that was killed. ================*/ CodeCallback_PlayerLastStand( eInflictor, eAttacker, iDamage, sMeansOfDeath, sWeapon, vDir, sHitLoc, timeOffset, deathAnimDuration ) { self endon( "disconnect" ); [[level.callbackPlayerLastStand]]( eInflictor, eAttacker, iDamage, sMeansOfDeath, sWeapon, vDir, sHitLoc, timeOffset, deathAnimDuration ); } //============================================================================= /*================ Setup any misc callbacks stuff like defines and default callbacks ================*/ SetupCallbacks() { SetDefaultCallbacks(); // Set defined for damage flags used in the playerDamage callback level.iDFLAGS_RADIUS = 1; level.iDFLAGS_NO_ARMOR = 2; level.iDFLAGS_NO_KNOCKBACK = 4; level.iDFLAGS_PENETRATION = 8; level.iDFLAGS_NO_TEAM_PROTECTION = 16; level.iDFLAGS_NO_PROTECTION = 32; level.iDFLAGS_PASSTHRU = 64; } /*================ Called from the gametype script to store off the default callback functions. This allows the callbacks to be overridden by level script, but not lost. ================*/ SetDefaultCallbacks() { level.callbackStartGameType = maps\mp\gametypes\_globallogic::Callback_StartGameType; level.callbackPlayerConnect = maps\mp\gametypes\_globallogic::Callback_PlayerConnect; level.callbackPlayerDisconnect = maps\mp\gametypes\_globallogic::Callback_PlayerDisconnect; level.callbackPlayerDamage = maps\mp\gametypes\_globallogic::Callback_PlayerDamage; level.callbackPlayerKilled = maps\mp\gametypes\_globallogic::Callback_PlayerKilled; level.callbackPlayerLastStand = maps\mp\gametypes\_globallogic::Callback_PlayerLastStand; } /*================ Called when a gametype is not supported. ================*/ AbortLevel() { println( "Aborting level - gametype is not supported" ); level.callbackStartGameType = ::callbackVoid; level.callbackPlayerConnect = ::callbackVoid; level.callbackPlayerDisconnect = ::callbackVoid; level.callbackPlayerDamage = ::callbackVoid; level.callbackPlayerKilled = ::callbackVoid; level.callbackPlayerLastStand = ::callbackVoid; setdvar( "g_gametype", "dm" ); exitLevel( false ); } /*================ ================*/ callbackVoid() { }
412
0.936604
1
0.936604
game-dev
MEDIA
0.944251
game-dev
0.865508
1
0.865508
katalash/DSMapStudio
1,071
HKX2/Autogen/hclSimulationSetupMeshMapOptions.cs
using SoulsFormats; using System.Collections.Generic; using System.Numerics; namespace HKX2 { public partial class hclSimulationSetupMeshMapOptions : IHavokObject { public virtual uint Signature { get => 2828547247; } public bool m_collapseVertices; public float m_collapseThreshold; public hclVertexSelectionInput m_vertexSelection; public virtual void Read(PackFileDeserializer des, BinaryReaderEx br) { m_collapseVertices = br.ReadBoolean(); br.ReadUInt16(); br.ReadByte(); m_collapseThreshold = br.ReadSingle(); m_vertexSelection = new hclVertexSelectionInput(); m_vertexSelection.Read(des, br); } public virtual void Write(PackFileSerializer s, BinaryWriterEx bw) { bw.WriteBoolean(m_collapseVertices); bw.WriteUInt16(0); bw.WriteByte(0); bw.WriteSingle(m_collapseThreshold); m_vertexSelection.Write(s, bw); } } }
412
0.841163
1
0.841163
game-dev
MEDIA
0.714015
game-dev,networking
0.827179
1
0.827179
ProjectSkyfire/SkyFire_548
1,501
src/server/game/Movement/Spline/MoveSplineInitArgs.h
/* * This file is part of Project SkyFire https://www.projectskyfire.org. * See LICENSE.md file for Copyright information */ #ifndef SKYFIRESERVER_MOVESPLINEINIT_ARGS_H #define SKYFIRESERVER_MOVESPLINEINIT_ARGS_H #include "MoveSplineFlag.h" #include <G3D/Vector3.h> class Unit; namespace Movement { typedef std::vector<Vector3> PointsArray; union FacingInfo { struct { float x, y, z; } f; uint64 target; float angle; FacingInfo() : angle(0.0f) { f.x = 0.0f; f.y = 0.0f; f.z = 0.0f; } }; struct MoveSplineInitArgs { MoveSplineInitArgs(size_t path_capacity = 16) : path_Idx_offset(0), velocity(0.f), parabolic_amplitude(0.f), time_perc(0.f), splineId(0), initialOrientation(0.f), HasVelocity(false), TransformForTransport(true) { path.reserve(path_capacity); } PointsArray path; FacingInfo facing; MoveSplineFlag flags; int32 path_Idx_offset; float velocity; float parabolic_amplitude; float time_perc; uint32 splineId; float initialOrientation; bool HasVelocity; bool TransformForTransport; /** Returns true to show that the arguments were configured correctly and MoveSpline initialization will succeed. */ bool Validate(Unit* unit) const; private: bool _checkPathBounds() const; }; } #endif // SKYFIRESERVER_MOVESPLINEINIT_ARGS_H
412
0.890076
1
0.890076
game-dev
MEDIA
0.930662
game-dev
0.600443
1
0.600443
Hex27/TerraformGenerator
3,227
common/src/main/java/org/terraform/coregen/populatordata/PopulatorDataColumn.java
package org.terraform.coregen.populatordata; import org.bukkit.Material; import org.bukkit.block.Biome; import org.bukkit.block.data.BlockData; import org.bukkit.entity.EntityType; import org.jetbrains.annotations.NotNull; import org.terraform.coregen.TerraLootTable; import org.terraform.data.TerraformWorld; /** * Same thing as the spigot one, but it will forcefully constrain internal x and z */ public class PopulatorDataColumn extends PopulatorDataAbstract { private final PopulatorDataAbstract delegate; int constrainX = 0; int constrainZ = 0; public PopulatorDataColumn(PopulatorDataAbstract delegate) { this.delegate = delegate; } public void setConstraints(int constrainX, int constrainZ) { this.constrainX = constrainX; this.constrainZ = constrainZ; } @Override public @NotNull Material getType(int x, int y, int z) { if (x != constrainX || z != constrainZ) { throw new IllegalArgumentException("Column Constraint Read Violation"); } return delegate.getType(x, y, z); } @Override public BlockData getBlockData(int x, int y, int z) { if (x != constrainX || z != constrainZ) { throw new IllegalArgumentException("Column Constraint Read Violation"); } return delegate.getBlockData(x, y, z); } @Override public void setType(int x, int y, int z, Material type) { if (x != constrainX || z != constrainZ) { throw new IllegalArgumentException("Column Constraint Write Violation"); } delegate.setType(x, y, z, type); } @Override public void setBlockData(int x, int y, int z, @NotNull BlockData data) { if (x != constrainX || z != constrainZ) { throw new IllegalArgumentException("Column Constraint Write Violation"); } delegate.setBlockData(x, y, z, data); } @Override public Biome getBiome(int rawX, int rawZ) { return delegate.getBiome(rawX, rawZ); } @Override public void addEntity(int rawX, int rawY, int rawZ, EntityType type) { if (rawX != constrainX || rawZ != constrainZ) { throw new IllegalArgumentException("Column Constraint Write Violation"); } delegate.addEntity(rawX, rawY, rawZ, type); } @Override public int getChunkX() { return delegate.getChunkX(); } @Override public int getChunkZ() { return delegate.getChunkZ(); } @Override public void setSpawner(int rawX, int rawY, int rawZ, EntityType type) { if (rawX != constrainX || rawZ != constrainZ) { throw new IllegalArgumentException("Column Constraint Write Violation"); } delegate.setSpawner(rawX, rawY, rawZ, type); } @Override public void lootTableChest(int x, int y, int z, TerraLootTable table) { if (x != constrainX || z != constrainZ) { throw new IllegalArgumentException("Column Constraint Write Violation"); } delegate.lootTableChest(x, y, z, table); } @Override public @NotNull TerraformWorld getTerraformWorld() { return delegate.getTerraformWorld(); } }
412
0.736216
1
0.736216
game-dev
MEDIA
0.269903
game-dev
0.75295
1
0.75295
GregTechCEu/GregTech
3,655
src/main/java/gregtech/api/gui/resources/ModifyGuiTexture.java
package gregtech.api.gui.resources; import net.minecraft.util.ResourceLocation; import com.google.gson.JsonObject; import java.io.File; import java.util.Arrays; import java.util.List; public class ModifyGuiTexture implements IGuiTexture { public static List<String> TYPES = Arrays.asList("resource", "url", "text", "color", "file"); private IGuiTexture texture; public ModifyGuiTexture(IGuiTexture texture) { this.texture = texture; if (texture == null) { this.texture = new TextTexture("texture.modify_gui_texture.missing", 0xff000000); } } public IGuiTexture getTexture() { return texture; } public void setTexture(IGuiTexture texture) { if (texture != null) { this.texture = texture; } } public String getTypeName() { if (texture instanceof TextureArea) { return "resource"; } else if (texture instanceof URLTexture) { return "url"; } else if (texture instanceof TextTexture) { return "text"; } else if (texture instanceof ColorRectTexture) { return "color"; } else if (texture instanceof FileTexture) { return "file"; } else { return null; } } @Override public void draw(double x, double y, int width, int height) { texture.draw(x, y, width, height); } @Override public void updateTick() { texture.updateTick(); } public JsonObject saveConfig() { JsonObject config = new JsonObject(); if (texture instanceof TextureArea) { config.addProperty("type", "resource"); config.addProperty("resource", ((TextureArea) texture).imageLocation.toString()); } else if (texture instanceof URLTexture) { config.addProperty("type", "url"); config.addProperty("url", ((URLTexture) texture).url); } else if (texture instanceof TextTexture) { config.addProperty("type", "text"); config.addProperty("text", ((TextTexture) texture).text); config.addProperty("color", ((TextTexture) texture).color); } else if (texture instanceof ColorRectTexture) { config.addProperty("type", "color"); config.addProperty("color", ((ColorRectTexture) texture).color); } else if (texture instanceof FileTexture) { config.addProperty("type", "file"); if (((FileTexture) texture).file != null) { config.addProperty("file", ((FileTexture) texture).file.getPath()); } else { config.addProperty("file", (String) null); } } else { return null; } return config; } public void loadConfig(JsonObject config) { try { switch (config.get("type").getAsString()) { case "resource": setTexture(new TextureArea(new ResourceLocation(config.get("resource").getAsString()), 0.0, 0.0, 1.0, 1.0)); case "url": setTexture(new URLTexture(config.get("url").getAsString())); case "text": setTexture(new TextTexture(config.get("text").getAsString(), config.get("color").getAsInt())); case "color": setTexture(new ColorRectTexture(config.get("color").getAsInt())); case "file": setTexture(new FileTexture(new File(config.get("file").getAsString()))); } } catch (Exception ignored) {} } }
412
0.81037
1
0.81037
game-dev
MEDIA
0.642532
game-dev
0.84937
1
0.84937
Um-Mitternacht/Bewitchment
4,762
src/main/java/com/bewitchment/common/block/BlockWitchesOven.java
package com.bewitchment.common.block; import com.bewitchment.Bewitchment; import com.bewitchment.common.block.tile.entity.TileEntityWitchesOven; import com.bewitchment.common.block.util.ModBlockContainer; import com.bewitchment.common.handler.GuiHandler; import net.minecraft.block.BlockHorizontal; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.SoundEvents; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.Random; @SuppressWarnings({"deprecation", "NullableProblems"}) public class BlockWitchesOven extends ModBlockContainer { public static final PropertyBool LIT = PropertyBool.create("lit"); private static final AxisAlignedBB BOX = new AxisAlignedBB(1 / 16d, 0, 1 / 16d, 15 / 16d, 1, 15 / 16d); public BlockWitchesOven() { super(Bewitchment.instance, "witches_oven", Material.IRON, SoundType.METAL, 5, 30, "pickaxe", GuiHandler.ModGui.OVEN.ordinal()); setDefaultState(blockState.getBaseState().withProperty(BlockHorizontal.FACING, EnumFacing.SOUTH).withProperty(LIT, false)); } @Override public TileEntity createNewTileEntity(World world, int meta) { return new TileEntityWitchesOven(); } @Override public IBlockState getStateFromMeta(int meta) { return getDefaultState().withProperty(BlockHorizontal.FACING, EnumFacing.HORIZONTALS[meta & 7]).withProperty(LIT, (meta & 8) > 0); } @Override public int getMetaFromState(IBlockState state) { return state.getValue(BlockHorizontal.FACING).getHorizontalIndex() | (state.getValue(LIT) ? 1 : 0) << 3; } @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) { return BOX; } @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand) { if (state.getValue(LIT)) { EnumFacing facing = state.getValue(BlockHorizontal.FACING); double d0 = pos.getX() + 0.425d; double d1 = pos.getY() + 0.3 + 0.75 * (rand.nextDouble() * 8 / 16d); double d2 = pos.getZ() + 0.425d; double d4 = rand.nextDouble() * 0.6d - 0.3d; if (rand.nextDouble() < 0.1) world.playSound(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5, SoundEvents.BLOCK_FURNACE_FIRE_CRACKLE, SoundCategory.BLOCKS, 1, 1, false); switch (facing) { case WEST: world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d0 - 0.52d, d1, d2 + d4, 0, 0, 0d); world.spawnParticle(EnumParticleTypes.FLAME, d0 - 0.52d, d1, d2 + d4, 0, 0, 0d); break; case EAST: world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d0 + 0.52d, d1, d2 + d4, 0, 0, 0d); world.spawnParticle(EnumParticleTypes.FLAME, d0 + 0.52d, d1, d2 + d4, 0, 0, 0d); break; case NORTH: world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d0 + d4, d1, d2 - 0.52d, 0, 0, 0d); world.spawnParticle(EnumParticleTypes.FLAME, d0 + d4, d1, d2 - 0.52d, 0, 0, 0d); break; case SOUTH: world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d0 + d4, d1, d2 + 0.52d, 0, 0, 0d); world.spawnParticle(EnumParticleTypes.FLAME, d0 + d4, d1, d2 + 0.52d, 0, 0, 0d); } } } @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, BlockHorizontal.FACING, LIT); } @Override public int getLightValue(IBlockState state, IBlockAccess world, BlockPos pos) { return state.getValue(LIT) ? 13 : 0; } @Override public IBlockState getStateForPlacement(World world, BlockPos pos, EnumFacing face, float hitX, float hitY, float hitZ, int meta, EntityLivingBase living, EnumHand hand) { return getDefaultState().withProperty(BlockHorizontal.FACING, EnumFacing.fromAngle(living.rotationYaw).getOpposite()); } }
412
0.859047
1
0.859047
game-dev
MEDIA
0.997701
game-dev
0.621778
1
0.621778
MATTYOneInc/AionEncomBase_Java8
3,462
AL-Game/src/com/aionemu/gameserver/services/events/DisplayService.java
/* * * 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 com.aionemu.gameserver.services.events; import com.aionemu.gameserver.model.Race; import com.aionemu.gameserver.model.gameobjects.Item; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.model.templates.item.ArmorType; /** * @author Rinzler (Encom) */ public class DisplayService { public static int getDisplayTemplate(Player player, Item item) { if (player.isBandit() || player.isFFA()) { if (item.getItemTemplate().isWeapon()) { switch (item.getItemTemplate().getWeaponType()) { case SWORD_1H: // Boundless Long Sword Of Glory. return 100002013; case MACE_1H: // Boundless Mace Of Glory. return 100101495; case DAGGER_1H: // Boundless Dagger Of Glory. return 100201676; case ORB_2H: // Boundless Orb Of Glory. return 100501453; case BOOK_2H: // Boundless Spellbook Of Glory. return 100601571; case SWORD_2H: // Boundless Great Sword Of Glory. return 100901530; case POLEARM_2H: // Boundless Polearm Of Glory. return 101301414; case STAFF_2H: // Boundless Staff Of Glory. return 101501516; case BOW: // Boundless Bow Of Glory. return 101701511; case GUN_1H: // Boundless Magic Gun Of Glory. return 101801346; case CANNON_2H: // Boundless Magic Cannon Of Glory. return 101901251; case HARP_2H: // Boundless String Instrument Of Glory. return 102001374; case KEYBLADE_2H: // Boundless Keyblade Of Glory. return 102101189; default: return 100002013; // is by default. } } else if (player.isFFA() && item.getEquipmentSlot() == 8) { // Executioner's Outfit. return 110901014; } else if (player.isFFA() && item.getEquipmentSlot() == 4) { // Executioner's Mask. return 125045594; } else if (item.getItemTemplate().getArmorType() == ArmorType.SHIELD) { return 115001971; // Boundless Shield Of Glory. } else if (item.getEquipmentSlot() == 8 && player.getBattleground() != null) { if (player.getRace() == Race.ELYOS) { return 110101255; // Elite Legion Uniform. } else { return 110101257; // Elite Legion Uniform. } } else { return item.getItemSkinTemplate().getTemplateId(); } } else { return item.getItemSkinTemplate().getTemplateId(); } } public static String getDisplayName(Player player) { if (player.isBandit()) { return "[PK] Bandit"; } else if (player.isFFA()) { return "Opponent"; } else if (player.getBattleground() != null) { return player.getPlayerClass().name(); } else { return player.getName(); } } public static String getDisplayLegionName(Player player) { if (player.isBandit()) { return "Wanted"; } else if (player.isFFA()) { return "Free For All"; } else { return player.getLegion().getLegionName(); } } }
412
0.868252
1
0.868252
game-dev
MEDIA
0.991843
game-dev
0.857416
1
0.857416
Flemmli97/Flan
30,831
common/src/main/java/io/github/flemmli97/flan/player/PlayerClaimData.java
package io.github.flemmli97.flan.player; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.github.flemmli97.flan.Flan; import io.github.flemmli97.flan.api.data.IPermissionContainer; import io.github.flemmli97.flan.api.data.IPlayerData; import io.github.flemmli97.flan.api.permission.BuiltinPermission; import io.github.flemmli97.flan.api.permission.PermissionManager; import io.github.flemmli97.flan.claim.Claim; import io.github.flemmli97.flan.claim.ClaimStorage; import io.github.flemmli97.flan.claim.ClaimUtils; import io.github.flemmli97.flan.commands.PendingCommand; import io.github.flemmli97.flan.config.ConfigHandler; import io.github.flemmli97.flan.event.ItemInteractEvents; import io.github.flemmli97.flan.platform.integration.permissions.PermissionNodeHandler; import io.github.flemmli97.flan.player.display.ClaimDisplay; import io.github.flemmli97.flan.player.display.DisplayBox; import io.github.flemmli97.flan.player.display.EnumDisplayType; import io.github.flemmli97.flan.scoreboard.ClaimCriterias; import io.github.flemmli97.flan.utils.IPlayerClaimImpl; import io.github.flemmli97.flan.utils.TeleportUtils; import net.minecraft.ChatFormatting; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.HoverEvent; import net.minecraft.network.chat.Style; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.storage.LevelResource; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; import net.minecraft.world.scores.criteria.ObjectiveCriteria; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; public class PlayerClaimData implements IPlayerData { public static final ResourceLocation MINING_SPEED_MOD = ResourceLocation.fromNamespaceAndPath(Flan.MODID, "mining_speed_modifier"); private final UUID editDisplay = UUID.randomUUID(); private final UUID display3D = UUID.randomUUID(); private int claimBlocks, additionalClaimBlocks, confirmTick, actionCooldown; //Scoreboard tracking private int usedBlocks; private int lastBlockTick, trappedTick = -1, deathPickupTick; private Vec3 trappedPos; private BlockPos tpPos; private ClaimMode editMode = ClaimMode.DEFAULT; private Claim editingClaim; private ClaimDisplay displayEditing; private BlockPos firstCorner; private final Set<ClaimDisplay> claimDisplayList = new HashSet<>(); private final Set<ClaimDisplay> displayToAdd = new HashSet<>(); private final ServerPlayer player; private boolean adminIgnoreClaim, claimBlockMessage; private PendingCommand pendingCommand; private final Map<String, Map<ResourceLocation, Boolean>> defaultGroups = new HashMap<>(); private boolean shouldProtectDrop, calculateShouldDrop = true; private final Map<UUID, Map<UUID, Long>> fakePlayerNotif = new HashMap<>(); private boolean fakePlayerNotification = true; private long lastClaimTime; public final ClientBlockDisplayTracker clientBlockDisplayTracker; public int claimingRange = 64; public PlayerClaimData(ServerPlayer player) { this.player = player; this.claimBlocks = ConfigHandler.CONFIG.startingBlocks; this.clientBlockDisplayTracker = new ClientBlockDisplayTracker(player); } public static PlayerClaimData get(ServerPlayer player) { return ((IPlayerClaimImpl) player).flan$get(); } @Override public int getClaimBlocks() { return Math.min(this.claimBlocks, PermissionNodeHandler.INSTANCE.permVal(this.player, PermissionNodeHandler.PERM_CLAIM_BLOCKS_CAP, this.claimBlocks)) + PermissionNodeHandler.INSTANCE.permVal(this.player, PermissionNodeHandler.PERM_CLAIM_BLOCKS_BONUS, 0); } public void setClaimBlocks(int amount) { this.claimBlocks = amount; updateScoreFor(this.player, ClaimCriterias.AMOUNT, this.claimBlocks + this.additionalClaimBlocks); updateScoreFor(this.player, ClaimCriterias.FREE, this.claimBlocks + this.additionalClaimBlocks - this.usedBlocks); } public void addClaimBlocksDirect(int amount) { this.setClaimBlocks(this.claimBlocks + amount); } public boolean addClaimBlocks(int amount) { if (this.canIncrease(this.claimBlocks + amount)) { this.setClaimBlocks(this.claimBlocks + amount); return true; } return false; } private boolean canIncrease(int blocks) { return PermissionNodeHandler.INSTANCE.permBelowEqVal(this.player, PermissionNodeHandler.PERM_CLAIM_BLOCKS, blocks, ConfigHandler.CONFIG.maxClaimBlocks); } @Override public int getAdditionalClaims() { return this.additionalClaimBlocks; } @Override public void setAdditionalClaims(int amount) { this.additionalClaimBlocks = Math.max(0, amount); updateScoreFor(this.player, ClaimCriterias.AMOUNT, this.claimBlocks + this.additionalClaimBlocks); updateScoreFor(this.player, ClaimCriterias.FREE, this.claimBlocks + this.additionalClaimBlocks - this.usedBlocks); } @Override public boolean canUseClaimBlocks(int amount) { if (ConfigHandler.CONFIG.maxClaimBlocks == -1) return true; return amount <= this.remainingClaimBlocks(); } @Override public int usedClaimBlocks() { return this.calculateUsedClaimBlocks(); } @Override public int remainingClaimBlocks() { return this.getClaimBlocks() + this.getAdditionalClaims() - this.usedClaimBlocks(); } public long nextClaimCooldown() { return ConfigHandler.CONFIG.claimingCooldown <= 0 ? 0 : Math.max(0, this.player.level().getGameTime() - this.lastClaimTime - ConfigHandler.CONFIG.claimingCooldown); } public void updateLastClaim() { this.lastClaimTime = this.player.level().getGameTime(); } /** * To prevent double processing. most notably when right clicking on a block and the block doesnt do anything -> * block onUse -> item use. Might be a better way but for now this. But also handles having * same items on both hands triggering */ public void setClaimActionCooldown() { this.actionCooldown = 10; } public boolean claimCooldown() { return this.actionCooldown > 0; } public Claim currentEdit() { return this.editingClaim; } public void setEditClaim(Claim claim, int height) { if (claim != null) this.displayEditing = new ClaimDisplay(claim, EnumDisplayType.EDIT, height); else if (this.displayEditing != null) { this.displayEditing.onRemoved(this.player); this.displayEditing = null; } this.editingClaim = claim; } public void addDisplayClaim(IPermissionContainer cont, EnumDisplayType type, int height) { this.addDisplayClaim(cont, type, height, true); } private void addDisplayClaim(IPermissionContainer cont, EnumDisplayType type, int height, boolean override) { if (cont instanceof Claim claim) { this.addDisplayClaim(new ClaimDisplay(claim, type, height), override); if (type == EnumDisplayType.MAIN) { for (Claim sub : claim.getAllSubclaims()) this.addDisplayClaim(new ClaimDisplay(sub, EnumDisplayType.SUB, height), override); } } } public void addDisplayClaim(DisplayBox display, EnumDisplayType type, int height) { this.addDisplayClaim(new ClaimDisplay(display, this.player.serverLevel(), type, height), true); } private void addDisplayClaim(ClaimDisplay display, boolean override) { if (override || !this.claimDisplayList.contains(display)) this.displayToAdd.add(display); } public ClaimMode getClaimMode() { if (this.editingClaim != null && this.editingClaim.is3d()) return this.editMode.isSubclaim ? ClaimMode.SUBCLAIM_3D : ClaimMode.DEFAULT_3D; if (!ConfigHandler.CONFIG.main3dClaims && !this.editMode.isSubclaim) return ClaimMode.DEFAULT; return this.editMode; } public void setEditMode(ClaimMode mode) { this.editMode = mode; this.setEditClaim(null, 0); this.setEditingCorner(null); } public BlockPos editingCorner() { return this.firstCorner; } public void setEditingCorner(BlockPos pos) { if (pos != null) { this.clientBlockDisplayTracker.resetFakeBlocks(this.display3D); } else { this.clientBlockDisplayTracker.resetFakeBlocks(this.editDisplay); } this.firstCorner = pos; } public int runPendingCommand(boolean deny) { int res = -1; if (this.pendingCommand != null) { if (deny) res = this.pendingCommand.runCommand(); else { this.pendingCommand.deny(); res = 0; } } this.pendingCommand = null; return res; } public void deferCommand(PendingCommand flag) { this.pendingCommand = flag; this.confirmTick = 400; } public void setAdminIgnoreClaim(boolean flag) { this.adminIgnoreClaim = flag; } public boolean isAdminIgnoreClaim() { return this.adminIgnoreClaim; } public Map<String, Map<ResourceLocation, Boolean>> playerDefaultGroups() { return this.defaultGroups; } public boolean editDefaultPerms(String group, ResourceLocation perm, int mode) { if (PermissionManager.getInstance().isGlobalPermission(perm) || ConfigHandler.CONFIG.globallyDefined(this.player.serverLevel(), perm)) return false; if (mode > 1) mode = -1; boolean has = this.defaultGroups.containsKey(group); Map<ResourceLocation, Boolean> perms = has ? this.defaultGroups.get(group) : new HashMap<>(); if (mode == -1) perms.remove(perm); else perms.put(perm, mode == 1); if (!has) this.defaultGroups.put(group, perms); return true; } public boolean setTrappedRescue() { Claim claim = ((IPlayerClaimImpl) this.player).flan$getCurrentClaim(); if (this.trappedTick < 0 && claim != null && !this.player.getUUID().equals(claim.getOwner())) { this.trappedTick = 101; this.trappedPos = this.player.position(); return true; } return false; } public boolean setTeleportTo(BlockPos tp) { if (this.trappedTick < 0) { this.trappedTick = 101; this.trappedPos = this.player.position(); this.tpPos = tp; return true; } return false; } public void tick(Claim currentClaim) { boolean tool = ConfigHandler.isClaimingTool(this.player.getMainHandItem()) || ConfigHandler.isClaimingTool(this.player.getOffhandItem()); boolean stick = ConfigHandler.isInspectionTool(this.player.getMainHandItem()) || ConfigHandler.isInspectionTool(this.player.getOffhandItem()); this.claimDisplayList.removeIf(display -> { boolean remove = display.display(this.player, !tool && !stick) || display.equals(this.displayEditing); if (remove) display.onRemoved(this.player); return remove || this.displayToAdd.contains(display); }); this.displayToAdd.forEach(add -> { if (!add.equals(this.displayEditing)) this.claimDisplayList.add(add); }); this.displayToAdd.clear(); if (++this.lastBlockTick > ConfigHandler.CONFIG.ticksForNextBlock) { this.addClaimBlocks(1); this.lastBlockTick = 0; } if (tool && ItemInteractEvents.canPlayerClaim(this.player.serverLevel(), this.player)) { this.claimingRange = this.getClaimMode().is3d && this.editingCorner() != null ? 10 : 64; BlockPos pos = ItemInteractEvents.rayTargetPos(this.player); if (pos != null && !pos.equals(this.firstCorner)) { this.clientBlockDisplayTracker.displayFakeBlocks(this.display3D, new ClientBlockDisplayTracker.DisplayData(pos, Blocks.YELLOW_WOOL.defaultBlockState())); } else { this.clientBlockDisplayTracker.resetFakeBlocks(this.display3D); } } else { this.clientBlockDisplayTracker.resetFakeBlocks(this.display3D); this.claimingRange = 64; } if (this.firstCorner != null && this.player.tickCount % 3 == 0) { this.clientBlockDisplayTracker.displayFakeBlocks(this.editDisplay, new ClientBlockDisplayTracker.DisplayData( this.firstCorner, Blocks.SEA_LANTERN.defaultBlockState() )); } if (--this.confirmTick < 0) this.pendingCommand = null; if (this.displayEditing != null) this.displayEditing.display(this.player, !tool && !stick); if (!tool) { this.setEditingCorner(null); this.setEditClaim(null, 0); } if (!tool && !stick) { this.claimBlockMessage = false; } else if (!this.claimBlockMessage) { this.claimBlockMessage = true; if (tool && this.shouldDisplayClaimToolMessage()) { this.player.displayClientMessage(ClaimUtils.translatedText("flan.claimBlocksFormat", this.getClaimBlocks(), this.getAdditionalClaims(), this.usedClaimBlocks(), this.remainingClaimBlocks(), ChatFormatting.GOLD), false); this.player.displayClientMessage(ClaimUtils.translatedText("flan.claimModeFormat", Component.translatable(this.getClaimMode().translationKey).withStyle(ChatFormatting.AQUA, ChatFormatting.BOLD), ChatFormatting.GOLD), true); } this.displayClaims(currentClaim); } if ((tool || stick) && this.player.tickCount % 20 == 0) { this.displayClaims(currentClaim); } this.actionCooldown--; if (--this.trappedTick >= 0) { if (this.trappedTick == 0) { if (this.tpPos != null) { BlockPos.MutableBlockPos tpTo = this.tpPos.mutable(); Vec3 offset = new Vec3(this.tpPos.getX() + 0.5, this.tpPos.getY() + 0.01, this.tpPos.getZ() + 0.5).subtract(this.player.position()); int yHighest = this.player.level().getChunk(this.tpPos.getX() >> 4, this.tpPos.getZ() >> 4).getHeight(Heightmap.Types.MOTION_BLOCKING, this.tpPos.getX() & 15, this.tpPos.getZ() & 15); AABB box = this.player.getBoundingBox().move(offset); if (tpTo.getY() < yHighest) { while (tpTo.getY() < yHighest) { if (this.player.level().noCollision(this.player, box)) break; tpTo.set(tpTo.getX(), tpTo.getY() + 1, tpTo.getZ()); box = box.move(0, 1, 0); } tpTo.set(tpTo.getX(), tpTo.getY() + 1, tpTo.getZ()); } else tpTo.set(tpTo.getX(), yHighest, tpTo.getZ()); if (this.player.isPassenger()) this.player.stopRiding(); this.player.teleportTo(tpTo.getX() + 0.5, tpTo.getY(), tpTo.getZ() + 0.5); this.tpPos = null; } else { Vec3 tp = TeleportUtils.getTeleportPos(this.player, this.player.position(), ClaimStorage.get(this.player.serverLevel()), new TeleportUtils.Area2D(((IPlayerClaimImpl) this.player).flan$getCurrentClaim().getDimensions()), TeleportUtils.roundedBlockPos(this.player.position()).mutable(), (claim, nPos) -> false); if (this.player.isPassenger()) this.player.stopRiding(); this.player.teleportTo(tp.x(), tp.y(), tp.z()); } } else if (this.player.position().distanceToSqr(this.trappedPos) > 0.15) { this.trappedTick = -1; this.trappedPos = null; this.player.displayClientMessage(ClaimUtils.translatedText("flan.trappedMove", ChatFormatting.RED), false); } } this.deathPickupTick--; if (!this.player.isDeadOrDying()) this.calculateShouldDrop = true; } private void displayClaims(Claim currentClaim) { if (ConfigHandler.CONFIG.nearbyClaimsToolDisplay > 0) { for (Claim claim : ClaimStorage.get(this.player.serverLevel()) .getNearbyClaims(this.player.serverLevel(), this.player.blockPosition(), ConfigHandler.CONFIG.nearbyClaimsToolDisplay, ConfigHandler.CONFIG.nearbyClaimsToolDisplay)) { this.addDisplayClaim(claim, EnumDisplayType.MAIN, this.player.blockPosition().getY(), false); } } else { this.addDisplayClaim(currentClaim, EnumDisplayType.MAIN, this.player.blockPosition().getY(), false); } } private boolean shouldDisplayClaimToolMessage() { return ItemInteractEvents.canClaimWorld(this.player.serverLevel(), this.player) && ConfigHandler.CONFIG.maxClaimBlocks > 0; } public void unlockDeathItems() { this.deathPickupTick = 1200; } public boolean deathItemsUnlocked() { return this.deathPickupTick > 0; } public void clone(PlayerClaimData data) { this.claimBlocks = data.claimBlocks; this.additionalClaimBlocks = data.additionalClaimBlocks; this.defaultGroups.clear(); this.defaultGroups.putAll(data.defaultGroups); if (data.setDeathItemOwner()) { this.player.displayClientMessage(ClaimUtils.translatedText("flan.unlockDropsCmd", "/flan unlockDrops", ChatFormatting.GOLD), false); } } public void updateScoreboard() { int claims = this.updateClaimScores(); updateScoreFor(this.player, ClaimCriterias.USED, this.usedBlocks); updateScoreFor(this.player, ClaimCriterias.FREE, this.claimBlocks + this.additionalClaimBlocks - this.usedBlocks); updateScoreFor(this.player, ClaimCriterias.CLAIMS, claims); } private int updateClaimScores() { int usedClaimsBlocks = 0; int claimsAmount = 0; for (ServerLevel level : this.player.getServer().getAllLevels()) { Collection<Claim> claims = ClaimStorage.get(level).allClaimsFromPlayer(this.player.getUUID()); if (claims != null) { usedClaimsBlocks += claims.stream().filter(claim -> !claim.isAdminClaim()).mapToInt(Claim::getPlane).sum(); claimsAmount += claims.size(); } } this.usedBlocks = usedClaimsBlocks; return claimsAmount; } private int calculateUsedClaimBlocks() { int usedClaimsBlocks = 0; for (ServerLevel level : this.player.getServer().getAllLevels()) { Collection<Claim> claims = ClaimStorage.get(level).allClaimsFromPlayer(this.player.getUUID()); if (claims != null) { usedClaimsBlocks += claims.stream().filter(claim -> !claim.isAdminClaim()).mapToInt(Claim::getPlane).sum(); } } return usedClaimsBlocks; } public boolean setDeathItemOwner() { if (!this.player.isDeadOrDying()) return false; if (this.calculateShouldDrop) { BlockPos rounded = TeleportUtils.roundedBlockPos(this.player.position().add(0, this.player.getEyeHeight(this.player.getPose()), 0)); this.shouldProtectDrop = ClaimStorage.get(this.player.serverLevel()).getForPermissionCheck(rounded) .canInteract(this.player, BuiltinPermission.LOCKITEMS, rounded) && !this.player.getServer().getGameRules().getBoolean(GameRules.RULE_KEEPINVENTORY); this.calculateShouldDrop = false; } return this.shouldProtectDrop; } public void setFakePlayerNotif(boolean on) { this.fakePlayerNotification = on; } public boolean hasFakePlayerNotificationOn() { return this.fakePlayerNotification; } public void notifyFakePlayerInteraction(ServerPlayer fakePlayer, BlockPos pos, Claim claim) { if (!this.fakePlayerNotification) return; Map<UUID, Long> map = this.fakePlayerNotif.computeIfAbsent(claim.getClaimID(), o -> new HashMap<>()); Long last = map.get(fakePlayer.getUUID()); if (last == null || this.player.serverLevel().getGameTime() - 1200 > last) { Component claimMsg = ClaimUtils.translatedText("flan.fakePlayerNotification1", claim.getLevel().dimension().location().toString(), pos, ChatFormatting.DARK_RED); this.player.sendSystemMessage(claimMsg); String cmdStr = String.format("/flan fakePlayer add %s", fakePlayer.getUUID()); Component cmd = ClaimUtils.translatedText("flan.clickableComponent") .withStyle(Style.EMPTY.withColor(ChatFormatting.GOLD) .withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, cmdStr)) .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal(cmdStr)))); Component msg = ClaimUtils.translatedText("flan.fakePlayerNotification2", cmd); this.player.sendSystemMessage(msg); cmdStr = "/flan fakePlayer"; cmd = ClaimUtils.translatedText("flan.clickableComponent") .withStyle(Style.EMPTY.withColor(ChatFormatting.GOLD) .withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, cmdStr)) .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal(cmdStr)))); msg = ClaimUtils.translatedText("flan.fakePlayerNotification3", cmd); this.player.sendSystemMessage(msg); map.put(fakePlayer.getUUID(), this.player.serverLevel().getGameTime()); } } public void save(MinecraftServer server) { Flan.log("Saving player data for player {} with uuid {}", this.player.getName(), this.player.getUUID()); Path dir = ConfigHandler.getPlayerSavePath(server); try { Path file = dir.resolve(this.player.getUUID() + ".json"); try { Files.createDirectories(dir); Files.createFile(file); } catch (FileAlreadyExistsException ignored) { } JsonObject obj = new JsonObject(); obj.addProperty("ClaimBlocks", this.claimBlocks); obj.addProperty("AdditionalBlocks", this.additionalClaimBlocks); obj.addProperty("LastSeen", LocalDateTime.now().format(Flan.ONLINE_TIME_FORMATTER)); JsonObject defPerm = new JsonObject(); this.defaultGroups.forEach((key, value) -> { JsonObject perm = new JsonObject(); value.forEach((key1, value1) -> perm.addProperty(key1.toString(), value1)); defPerm.add(key, perm); }); obj.add("DefaultGroups", defPerm); obj.addProperty("FakePlayerNotification", this.fakePlayerNotification); JsonWriter jsonWriter = ConfigHandler.GSON.newJsonWriter(Files.newBufferedWriter(file, StandardCharsets.UTF_8)); ConfigHandler.GSON.toJson(obj, jsonWriter); jsonWriter.close(); } catch (IOException e) { Flan.LOGGER.error(e); } } public void read(MinecraftServer server) { Flan.log("Reading player data for player {} with uuid {}", this.player.getName(), this.player.getUUID()); try { Path file = ConfigHandler.getPlayerSavePath(server).resolve(this.player.getUUID() + ".json"); if (!Files.exists(file)) { Flan.log("No player data found for player {} with uuid {}", this.player.getName(), this.player.getUUID()); return; } JsonReader reader = ConfigHandler.GSON.newJsonReader(Files.newBufferedReader(file, StandardCharsets.UTF_8)); JsonObject obj = ConfigHandler.GSON.fromJson(reader, JsonObject.class); reader.close(); Flan.debug("Read following json data {} from file {}", obj, file.getFileName()); JsonElement claimBlockEl = obj.get("ClaimBlocks"); if (claimBlockEl.isJsonPrimitive()) this.claimBlocks = claimBlockEl.getAsInt(); this.additionalClaimBlocks = obj.get("AdditionalBlocks").getAsInt(); JsonObject defP = ConfigHandler.fromJson(obj, "DefaultGroups"); defP.entrySet().forEach(e -> { if (e.getValue().isJsonObject()) { e.getValue().getAsJsonObject().entrySet().forEach(p -> this.editDefaultPerms(e.getKey(), BuiltinPermission.tryLegacy(p.getKey()), p.getValue().getAsBoolean() ? 1 : 0)); } }); this.fakePlayerNotification = ConfigHandler.fromJson(obj, "FakePlayerNotification", true); updateScoreFor(this.player, ClaimCriterias.AMOUNT, this.claimBlocks + this.additionalClaimBlocks); this.updateClaimScores(); } catch (IOException e) { Flan.LOGGER.error(e); } } public static void updateScoreFor(ServerPlayer player, ObjectiveCriteria criterion, int val) { player.getScoreboard().forAllObjectives(criterion, player, (scoreboardPlayerScore) -> scoreboardPlayerScore.set(val)); } public static void editForOfflinePlayer(MinecraftServer server, UUID uuid, int additionalClaimBlocks, boolean base) { Flan.log("Adding {} addional claimblocks for offline player with uuid {}", additionalClaimBlocks, uuid); Path dir = ConfigHandler.getPlayerSavePath(server); try { Path file = dir.resolve(uuid.toString() + ".json"); try { Files.createDirectories(dir); Files.createFile(file); } catch (FileAlreadyExistsException ignored) { } JsonReader reader = ConfigHandler.GSON.newJsonReader(Files.newBufferedReader(file, StandardCharsets.UTF_8)); JsonObject obj = ConfigHandler.GSON.fromJson(reader, JsonObject.class); reader.close(); if (obj == null) obj = new JsonObject(); if (base) { int blocks = ConfigHandler.fromJson(obj, "ClaimBlocks", 0); obj.addProperty("ClaimBlocks", blocks + additionalClaimBlocks); } else { int additionalBlocks = ConfigHandler.fromJson(obj, "AdditionalBlocks", 0); obj.addProperty("AdditionalBlocks", additionalBlocks + additionalClaimBlocks); } Flan.debug("Attempting to write following json data {} to file {}", obj, file.getFileName()); JsonWriter jsonWriter = ConfigHandler.GSON.newJsonWriter(Files.newBufferedWriter(file, StandardCharsets.UTF_8)); ConfigHandler.GSON.toJson(obj, jsonWriter); jsonWriter.close(); } catch (IOException e) { Flan.LOGGER.error(e); } } public static boolean readGriefPreventionPlayerData(MinecraftServer server, CommandSourceStack src) { Flan.log("Reading grief prevention data"); File griefPrevention = server.getWorldPath(LevelResource.ROOT).resolve("plugins/GriefPreventionData/PlayerData").toFile(); if (!griefPrevention.exists()) { src.sendSuccess(() -> ClaimUtils.translatedText("flan.cantFindData", griefPrevention.getAbsolutePath(), ChatFormatting.DARK_RED), false); return false; } for (File f : griefPrevention.listFiles()) { try { if (f.getName().contains(".")) continue; if (f.getName().startsWith("$")) { } else { BufferedReader reader = new BufferedReader(new FileReader(f)); ServerPlayer player = server.getPlayerList().getPlayer(UUID.fromString(f.getName())); if (player != null) { PlayerClaimData data = PlayerClaimData.get(player); reader.readLine(); data.claimBlocks = Integer.parseInt(reader.readLine()); data.additionalClaimBlocks = Integer.parseInt(reader.readLine()); } else { File dir = new File(server.getWorldPath(LevelResource.PLAYER_DATA_DIR).toFile(), "/claimData/"); if (!dir.exists()) dir.mkdir(); File file = new File(dir, f.getName() + ".json"); if (!file.exists()) file.createNewFile(); reader.readLine(); FileWriter writer = new FileWriter(file); JsonObject obj = new JsonObject(); obj.addProperty("ClaimBlocks", reader.readLine()); obj.addProperty("AdditionalBlocks", reader.readLine()); ConfigHandler.GSON.toJson(obj, writer); writer.close(); } reader.close(); } } catch (Exception e) { src.sendSuccess(() -> ClaimUtils.translatedText("flan.errorFile", f.getName(), ChatFormatting.RED), false); } } return true; } }
412
0.949127
1
0.949127
game-dev
MEDIA
0.917503
game-dev
0.948316
1
0.948316
ServUO/ServUO
1,502
Scripts/Items/Artifacts/Equipment/Clothing/MysticsGarb.cs
using System; namespace Server.Items { public class MysticsGarb : Robe { public override bool IsArtifact { get { return true; } } public override int LabelNumber { get { return 1113649; } } // Mystic's Garb [Constructable] public MysticsGarb() : base() { ItemID = 0x4000; Hue = 1420; Attributes.BonusMana = 5; Attributes.LowerManaCost = 1; } public MysticsGarb(Serial serial) : base(serial) { } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } public override bool CanBeWornByGargoyles { get { return true; } } public override Race RequiredRace { get { return Race.Gargoyle; } } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)1); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); if (version == 0) ItemID = 0x4000; } } }
412
0.828036
1
0.828036
game-dev
MEDIA
0.364462
game-dev
0.86603
1
0.86603
ChengF3ng233/Aluminium
30,343
src/main/java/net/optifine/config/ConnectedParser.java
package net.optifine.config; import net.minecraft.block.Block; import net.minecraft.block.BlockDoublePlant; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.src.Config; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.util.IStringSerializable; import net.minecraft.util.ResourceLocation; import net.minecraft.world.biome.BiomeGenBase; import net.optifine.ConnectedProperties; import net.optifine.util.EntityUtils; import java.lang.reflect.Array; import java.util.*; public class ConnectedParser { private String context = null; public static final VillagerProfession[] PROFESSIONS_INVALID = new VillagerProfession[0]; public static final EnumDyeColor[] DYE_COLORS_INVALID = new EnumDyeColor[0]; private static final INameGetter<Enum> NAME_GETTER_ENUM = new INameGetter<Enum>() { public String getName(Enum en) { return en.name(); } }; private static final INameGetter<EnumDyeColor> NAME_GETTER_DYE_COLOR = new INameGetter<EnumDyeColor>() { public String getName(EnumDyeColor col) { return col.getName(); } }; public ConnectedParser(String context) { this.context = context; } public String parseName(String path) { String s = path; int i = path.lastIndexOf(47); if (i >= 0) { s = path.substring(i + 1); } int j = s.lastIndexOf(46); if (j >= 0) { s = s.substring(0, j); } return s; } public String parseBasePath(String path) { int i = path.lastIndexOf(47); return i < 0 ? "" : path.substring(0, i); } public MatchBlock[] parseMatchBlocks(String propMatchBlocks) { if (propMatchBlocks == null) { return null; } else { List list = new ArrayList(); String[] astring = Config.tokenize(propMatchBlocks, " "); for (int i = 0; i < astring.length; ++i) { String s = astring[i]; MatchBlock[] amatchblock = this.parseMatchBlock(s); if (amatchblock != null) { list.addAll(Arrays.asList(amatchblock)); } } MatchBlock[] amatchblock1 = (MatchBlock[]) list.toArray(new MatchBlock[list.size()]); return amatchblock1; } } public IBlockState parseBlockState(String str, IBlockState def) { MatchBlock[] amatchblock = this.parseMatchBlock(str); if (amatchblock == null) { return def; } else if (amatchblock.length != 1) { return def; } else { MatchBlock matchblock = amatchblock[0]; int i = matchblock.getBlockId(); Block block = Block.getBlockById(i); return block.getDefaultState(); } } public MatchBlock[] parseMatchBlock(String blockStr) { if (blockStr == null) { return null; } else { blockStr = blockStr.trim(); if (blockStr.length() <= 0) { return null; } else { String[] astring = Config.tokenize(blockStr, ":"); String s = "minecraft"; int i = 0; if (astring.length > 1 && this.isFullBlockName(astring)) { s = astring[0]; i = 1; } else { s = "minecraft"; i = 0; } String s1 = astring[i]; String[] astring1 = Arrays.copyOfRange(astring, i + 1, astring.length); Block[] ablock = this.parseBlockPart(s, s1); if (ablock == null) { return null; } else { MatchBlock[] amatchblock = new MatchBlock[ablock.length]; for (int j = 0; j < ablock.length; ++j) { Block block = ablock[j]; int k = Block.getIdFromBlock(block); int[] aint = null; if (astring1.length > 0) { aint = this.parseBlockMetadatas(block, astring1); if (aint == null) { return null; } } MatchBlock matchblock = new MatchBlock(k, aint); amatchblock[j] = matchblock; } return amatchblock; } } } } public boolean isFullBlockName(String[] parts) { if (parts.length < 2) { return false; } else { String s = parts[1]; return s.length() >= 1 && (!this.startsWithDigit(s) && !s.contains("=")); } } public boolean startsWithDigit(String str) { if (str == null) { return false; } else if (str.length() < 1) { return false; } else { char c0 = str.charAt(0); return Character.isDigit(c0); } } public Block[] parseBlockPart(String domain, String blockPart) { if (this.startsWithDigit(blockPart)) { int[] aint = this.parseIntList(blockPart); if (aint == null) { return null; } else { Block[] ablock1 = new Block[aint.length]; for (int j = 0; j < aint.length; ++j) { int i = aint[j]; Block block1 = Block.getBlockById(i); if (block1 == null) { this.warn("Block not found for id: " + i); return null; } ablock1[j] = block1; } return ablock1; } } else { String s = domain + ":" + blockPart; Block block = Block.getBlockFromName(s); if (block == null) { this.warn("Block not found for name: " + s); return null; } else { Block[] ablock = new Block[]{block}; return ablock; } } } public int[] parseBlockMetadatas(Block block, String[] params) { if (params.length <= 0) { return null; } else { String s = params[0]; if (this.startsWithDigit(s)) { int[] aint = this.parseIntList(s); return aint; } else { IBlockState iblockstate = block.getDefaultState(); Collection collection = iblockstate.getPropertyNames(); Map<IProperty, List<Comparable>> map = new HashMap(); for (int i = 0; i < params.length; ++i) { String s1 = params[i]; if (s1.length() > 0) { String[] astring = Config.tokenize(s1, "="); if (astring.length != 2) { this.warn("Invalid block property: " + s1); return null; } String s2 = astring[0]; String s3 = astring[1]; IProperty iproperty = ConnectedProperties.getProperty(s2, collection); if (iproperty == null) { this.warn("Property not found: " + s2 + ", block: " + block); return null; } List<Comparable> list = map.get(s2); if (list == null) { list = new ArrayList(); map.put(iproperty, list); } String[] astring1 = Config.tokenize(s3, ","); for (int j = 0; j < astring1.length; ++j) { String s4 = astring1[j]; Comparable comparable = parsePropertyValue(iproperty, s4); if (comparable == null) { this.warn("Property value not found: " + s4 + ", property: " + s2 + ", block: " + block); return null; } list.add(comparable); } } } if (map.isEmpty()) { return null; } else { List<Integer> list1 = new ArrayList(); for (int k = 0; k < 16; ++k) { int l = k; try { IBlockState iblockstate1 = this.getStateFromMeta(block, l); if (this.matchState(iblockstate1, map)) { list1.add(Integer.valueOf(l)); } } catch (IllegalArgumentException var18) { } } if (list1.size() == 16) { return null; } else { int[] aint1 = new int[list1.size()]; for (int i1 = 0; i1 < aint1.length; ++i1) { aint1[i1] = list1.get(i1).intValue(); } return aint1; } } } } } private IBlockState getStateFromMeta(Block block, int md) { try { IBlockState iblockstate = block.getStateFromMeta(md); if (block == Blocks.double_plant && md > 7) { IBlockState iblockstate1 = block.getStateFromMeta(md & 7); iblockstate = iblockstate.withProperty(BlockDoublePlant.VARIANT, iblockstate1.getValue(BlockDoublePlant.VARIANT)); } return iblockstate; } catch (IllegalArgumentException var5) { return block.getDefaultState(); } } public static Comparable parsePropertyValue(IProperty prop, String valStr) { Class oclass = prop.getValueClass(); Comparable comparable = parseValue(valStr, oclass); if (comparable == null) { Collection collection = prop.getAllowedValues(); comparable = getPropertyValue(valStr, collection); } return comparable; } public static Comparable getPropertyValue(String value, Collection propertyValues) { for (Object o : propertyValues) { Comparable comparable = (Comparable) o; if (getValueName(comparable).equals(value)) { return comparable; } } return null; } private static Object getValueName(Comparable obj) { if (obj instanceof IStringSerializable) { IStringSerializable istringserializable = (IStringSerializable) obj; return istringserializable.getName(); } else { return obj.toString(); } } public static Comparable parseValue(String str, Class cls) { return cls == String.class ? str : (cls == Boolean.class ? Boolean.valueOf(str) : (cls == Float.class ? Float.valueOf(str) : (cls == Double.class ? Double.valueOf(str) : (cls == Integer.class ? Integer.valueOf(str) : (cls == Long.class ? Long.valueOf(str) : null))))); } public boolean matchState(IBlockState bs, Map<IProperty, List<Comparable>> mapPropValues) { for (IProperty iproperty : mapPropValues.keySet()) { List<Comparable> list = mapPropValues.get(iproperty); Comparable comparable = bs.getValue(iproperty); if (comparable == null) { return false; } if (!list.contains(comparable)) { return false; } } return true; } public BiomeGenBase[] parseBiomes(String str) { if (str == null) { return null; } else { str = str.trim(); boolean flag = false; if (str.startsWith("!")) { flag = true; str = str.substring(1); } String[] astring = Config.tokenize(str, " "); List list = new ArrayList(); for (int i = 0; i < astring.length; ++i) { String s = astring[i]; BiomeGenBase biomegenbase = this.findBiome(s); if (biomegenbase == null) { this.warn("Biome not found: " + s); } else { list.add(biomegenbase); } } if (flag) { List<BiomeGenBase> list1 = new ArrayList(Arrays.asList(BiomeGenBase.getBiomeGenArray())); list1.removeAll(list); list = list1; } BiomeGenBase[] abiomegenbase = (BiomeGenBase[]) list.toArray(new BiomeGenBase[list.size()]); return abiomegenbase; } } public BiomeGenBase findBiome(String biomeName) { biomeName = biomeName.toLowerCase(); if (biomeName.equals("nether")) { return BiomeGenBase.hell; } else { BiomeGenBase[] abiomegenbase = BiomeGenBase.getBiomeGenArray(); for (int i = 0; i < abiomegenbase.length; ++i) { BiomeGenBase biomegenbase = abiomegenbase[i]; if (biomegenbase != null) { String s = biomegenbase.biomeName.replace(" ", "").toLowerCase(); if (s.equals(biomeName)) { return biomegenbase; } } } return null; } } public int parseInt(String str, int defVal) { if (str == null) { return defVal; } else { str = str.trim(); int i = Config.parseInt(str, -1); if (i < 0) { this.warn("Invalid number: " + str); return defVal; } else { return i; } } } public int[] parseIntList(String str) { if (str == null) { return null; } else { List<Integer> list = new ArrayList(); String[] astring = Config.tokenize(str, " ,"); for (int i = 0; i < astring.length; ++i) { String s = astring[i]; if (s.contains("-")) { String[] astring1 = Config.tokenize(s, "-"); if (astring1.length != 2) { this.warn("Invalid interval: " + s + ", when parsing: " + str); } else { int k = Config.parseInt(astring1[0], -1); int l = Config.parseInt(astring1[1], -1); if (k >= 0 && l >= 0 && k <= l) { for (int i1 = k; i1 <= l; ++i1) { list.add(Integer.valueOf(i1)); } } else { this.warn("Invalid interval: " + s + ", when parsing: " + str); } } } else { int j = Config.parseInt(s, -1); if (j < 0) { this.warn("Invalid number: " + s + ", when parsing: " + str); } else { list.add(Integer.valueOf(j)); } } } int[] aint = new int[list.size()]; for (int j1 = 0; j1 < aint.length; ++j1) { aint[j1] = list.get(j1).intValue(); } return aint; } } public boolean[] parseFaces(String str, boolean[] defVal) { if (str == null) { return defVal; } else { EnumSet enumset = EnumSet.allOf(EnumFacing.class); String[] astring = Config.tokenize(str, " ,"); for (int i = 0; i < astring.length; ++i) { String s = astring[i]; if (s.equals("sides")) { enumset.add(EnumFacing.NORTH); enumset.add(EnumFacing.SOUTH); enumset.add(EnumFacing.WEST); enumset.add(EnumFacing.EAST); } else if (s.equals("all")) { enumset.addAll(Arrays.asList(EnumFacing.VALUES)); } else { EnumFacing enumfacing = this.parseFace(s); if (enumfacing != null) { enumset.add(enumfacing); } } } boolean[] aboolean = new boolean[EnumFacing.VALUES.length]; for (int j = 0; j < aboolean.length; ++j) { aboolean[j] = enumset.contains(EnumFacing.VALUES[j]); } return aboolean; } } public EnumFacing parseFace(String str) { str = str.toLowerCase(); if (!str.equals("bottom") && !str.equals("down")) { if (!str.equals("top") && !str.equals("up")) { if (str.equals("north")) { return EnumFacing.NORTH; } else if (str.equals("south")) { return EnumFacing.SOUTH; } else if (str.equals("east")) { return EnumFacing.EAST; } else if (str.equals("west")) { return EnumFacing.WEST; } else { Config.warn("Unknown face: " + str); return null; } } else { return EnumFacing.UP; } } else { return EnumFacing.DOWN; } } public void dbg(String str) { Config.dbg(this.context + ": " + str); } public void warn(String str) { Config.warn(this.context + ": " + str); } public RangeListInt parseRangeListInt(String str) { if (str == null) { return null; } else { RangeListInt rangelistint = new RangeListInt(); String[] astring = Config.tokenize(str, " ,"); for (int i = 0; i < astring.length; ++i) { String s = astring[i]; RangeInt rangeint = this.parseRangeInt(s); if (rangeint == null) { return null; } rangelistint.addRange(rangeint); } return rangelistint; } } private RangeInt parseRangeInt(String str) { if (str == null) { return null; } else if (str.indexOf(45) >= 0) { String[] astring = Config.tokenize(str, "-"); if (astring.length != 2) { this.warn("Invalid range: " + str); return null; } else { int j = Config.parseInt(astring[0], -1); int k = Config.parseInt(astring[1], -1); if (j >= 0 && k >= 0) { return new RangeInt(j, k); } else { this.warn("Invalid range: " + str); return null; } } } else { int i = Config.parseInt(str, -1); if (i < 0) { this.warn("Invalid integer: " + str); return null; } else { return new RangeInt(i, i); } } } public boolean parseBoolean(String str, boolean defVal) { if (str == null) { return defVal; } else { String s = str.toLowerCase().trim(); if (s.equals("true")) { return true; } else if (s.equals("false")) { return false; } else { this.warn("Invalid boolean: " + str); return defVal; } } } public Boolean parseBooleanObject(String str) { if (str == null) { return null; } else { String s = str.toLowerCase().trim(); if (s.equals("true")) { return Boolean.TRUE; } else if (s.equals("false")) { return Boolean.FALSE; } else { this.warn("Invalid boolean: " + str); return null; } } } public static int parseColor(String str, int defVal) { if (str == null) { return defVal; } else { str = str.trim(); try { int i = Integer.parseInt(str, 16) & 16777215; return i; } catch (NumberFormatException var3) { return defVal; } } } public static int parseColor4(String str, int defVal) { if (str == null) { return defVal; } else { str = str.trim(); try { int i = (int) (Long.parseLong(str, 16) & -1L); return i; } catch (NumberFormatException var3) { return defVal; } } } public EnumWorldBlockLayer parseBlockRenderLayer(String str, EnumWorldBlockLayer def) { if (str == null) { return def; } else { str = str.toLowerCase().trim(); EnumWorldBlockLayer[] aenumworldblocklayer = EnumWorldBlockLayer.values(); for (int i = 0; i < aenumworldblocklayer.length; ++i) { EnumWorldBlockLayer enumworldblocklayer = aenumworldblocklayer[i]; if (str.equals(enumworldblocklayer.name().toLowerCase())) { return enumworldblocklayer; } } return def; } } public <T> T parseObject(String str, T[] objs, INameGetter nameGetter, String property) { if (str == null) { return null; } else { String s = str.toLowerCase().trim(); for (int i = 0; i < objs.length; ++i) { T t = objs[i]; String s1 = nameGetter.getName(t); if (s1 != null && s1.toLowerCase().equals(s)) { return t; } } this.warn("Invalid " + property + ": " + str); return null; } } public <T> T[] parseObjects(String str, T[] objs, INameGetter nameGetter, String property, T[] errValue) { if (str == null) { return null; } else { str = str.toLowerCase().trim(); String[] astring = Config.tokenize(str, " "); T[] at = (T[]) Array.newInstance(objs.getClass().getComponentType(), astring.length); for (int i = 0; i < astring.length; ++i) { String s = astring[i]; T t = this.parseObject(s, objs, nameGetter, property); if (t == null) { return errValue; } at[i] = t; } return at; } } public Enum parseEnum(String str, Enum[] enums, String property) { return this.parseObject(str, enums, NAME_GETTER_ENUM, property); } public Enum[] parseEnums(String str, Enum[] enums, String property, Enum[] errValue) { return this.parseObjects(str, enums, NAME_GETTER_ENUM, property, errValue); } public EnumDyeColor[] parseDyeColors(String str, String property, EnumDyeColor[] errValue) { return this.parseObjects(str, EnumDyeColor.values(), NAME_GETTER_DYE_COLOR, property, errValue); } public Weather[] parseWeather(String str, String property, Weather[] errValue) { return this.parseObjects(str, Weather.values(), NAME_GETTER_ENUM, property, errValue); } public NbtTagValue parseNbtTagValue(String path, String value) { return path != null && value != null ? new NbtTagValue(path, value) : null; } public VillagerProfession[] parseProfessions(String profStr) { if (profStr == null) { return null; } else { List<VillagerProfession> list = new ArrayList(); String[] astring = Config.tokenize(profStr, " "); for (int i = 0; i < astring.length; ++i) { String s = astring[i]; VillagerProfession villagerprofession = this.parseProfession(s); if (villagerprofession == null) { this.warn("Invalid profession: " + s); return PROFESSIONS_INVALID; } list.add(villagerprofession); } if (list.isEmpty()) { return null; } else { VillagerProfession[] avillagerprofession = list.toArray(new VillagerProfession[list.size()]); return avillagerprofession; } } } private VillagerProfession parseProfession(String str) { str = str.toLowerCase(); String[] astring = Config.tokenize(str, ":"); if (astring.length > 2) { return null; } else { String s = astring[0]; String s1 = null; if (astring.length > 1) { s1 = astring[1]; } int i = parseProfessionId(s); if (i < 0) { return null; } else { int[] aint = null; if (s1 != null) { aint = parseCareerIds(i, s1); if (aint == null) { return null; } } return new VillagerProfession(i, aint); } } } private static int parseProfessionId(String str) { int i = Config.parseInt(str, -1); return i >= 0 ? i : (str.equals("farmer") ? 0 : (str.equals("librarian") ? 1 : (str.equals("priest") ? 2 : (str.equals("blacksmith") ? 3 : (str.equals("butcher") ? 4 : (str.equals("nitwit") ? 5 : -1)))))); } private static int[] parseCareerIds(int prof, String str) { Set<Integer> set = new HashSet(); String[] astring = Config.tokenize(str, ","); for (int i = 0; i < astring.length; ++i) { String s = astring[i]; int j = parseCareerId(prof, s); if (j < 0) { return null; } set.add(Integer.valueOf(j)); } Integer[] ainteger = set.toArray(new Integer[set.size()]); int[] aint = new int[ainteger.length]; for (int k = 0; k < aint.length; ++k) { aint[k] = ainteger[k].intValue(); } return aint; } private static int parseCareerId(int prof, String str) { int i = Config.parseInt(str, -1); if (i >= 0) { return i; } else { if (prof == 0) { if (str.equals("farmer")) { return 1; } if (str.equals("fisherman")) { return 2; } if (str.equals("shepherd")) { return 3; } if (str.equals("fletcher")) { return 4; } } if (prof == 1) { if (str.equals("librarian")) { return 1; } if (str.equals("cartographer")) { return 2; } } if (prof == 2 && str.equals("cleric")) { return 1; } else { if (prof == 3) { if (str.equals("armor")) { return 1; } if (str.equals("weapon")) { return 2; } if (str.equals("tool")) { return 3; } } if (prof == 4) { if (str.equals("butcher")) { return 1; } if (str.equals("leather")) { return 2; } } return prof == 5 && str.equals("nitwit") ? 1 : -1; } } } public int[] parseItems(String str) { str = str.trim(); Set<Integer> set = new TreeSet(); String[] astring = Config.tokenize(str, " "); for (int i = 0; i < astring.length; ++i) { String s = astring[i]; ResourceLocation resourcelocation = new ResourceLocation(s); Item item = Item.itemRegistry.getObject(resourcelocation); if (item == null) { this.warn("Item not found: " + s); } else { int j = Item.getIdFromItem(item); if (j < 0) { this.warn("Item has no ID: " + item + ", name: " + s); } else { set.add(new Integer(j)); } } } Integer[] ainteger = set.toArray(new Integer[set.size()]); int[] aint = Config.toPrimitive(ainteger); return aint; } public int[] parseEntities(String str) { str = str.trim(); Set<Integer> set = new TreeSet(); String[] astring = Config.tokenize(str, " "); for (int i = 0; i < astring.length; ++i) { String s = astring[i]; int j = EntityUtils.getEntityIdByName(s); if (j < 0) { this.warn("Entity not found: " + s); } else { set.add(new Integer(j)); } } Integer[] ainteger = set.toArray(new Integer[set.size()]); int[] aint = Config.toPrimitive(ainteger); return aint; } }
412
0.917429
1
0.917429
game-dev
MEDIA
0.80971
game-dev
0.943079
1
0.943079
ClusterVR/ClusterCreatorKit
2,746
Editor/Custom/VisualElementEditor.cs
using System.Linq; using ClusterVR.CreatorKit.Validator; using UnityEditor; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; namespace ClusterVR.CreatorKit.Editor.Custom { public abstract class VisualElementEditor : UnityEditor.Editor { public override VisualElement CreateInspectorGUI() { var container = new VisualElement(); var iterator = serializedObject.GetIterator(); if (!iterator.NextVisible(true)) { return container; } while (iterator.NextVisible(false)) { var propertyField = CreateField(iterator.Copy()); if (iterator.propertyPath == "m_Script" && serializedObject.targetObject != null) { propertyField.SetEnabled(false); } container.Add(propertyField); } container.Bind(serializedObject); ComponentValidationMessage(container); return container; } protected virtual VisualElement CreateField(SerializedProperty serializedProperty) { return serializedProperty.propertyType switch { SerializedPropertyType.Quaternion => QuaternionField.Create(serializedProperty.displayName, serializedProperty), _ => new PropertyField(serializedProperty) { name = "PropertyField:" + serializedProperty.propertyPath }, }; } protected PropertyField FindPropertyField(VisualElement container, string propertyName) { return container.Children() .OfType<PropertyField>() .First(c => c.bindingPath == propertyName); } void ComponentValidationMessage(VisualElement container) { var warningContainer = new IMGUIContainer(() => { foreach (var obj in targets) { if (obj is MonoBehaviour component) { var attr = (ComponentValidatorAttribute[]) component.GetType().GetCustomAttributes(typeof(ComponentValidatorAttribute), true); foreach (var validator in attr) { if (!validator.Validate(component, out UnityEditor.MessageType type, out string message)) { EditorGUILayout.HelpBox(message, type); return; } } } } }); container.Add(warningContainer); } } }
412
0.883499
1
0.883499
game-dev
MEDIA
0.834485
game-dev
0.973472
1
0.973472
sergev/vak-opensource
5,892
languages/c++/lunar-landing/optimize.cpp
#include <iostream> #include <random> #include <time.h> #include "rocket.h" // // Print vector. // std::ostream &operator<<(std::ostream &out, const std::vector<unsigned> &vec) { out << '{'; for (const auto &item : vec) { out << ' ' << item; } out << " }"; return out; } // // Print array. // std::ostream &operator<<(std::ostream &out, const std::array<unsigned, 8> &arr) { out << '{'; for (const auto &item : arr) { out << ' ' << item; } out << " }"; return out; } // // Play game with given control. // Return the resulting impact velocity (in mph). // double play_game(const std::vector<unsigned> &control) { Rocket game; double score = game.play_vector(control); //std::cout << "Impact velocity " << score << " mph, control " << control << std::endl; return score; } // // Given a control and it's score, vary it's item with given index // to find a better score. Return the new control and score // (or old values, in case no enhancement has been made). // std::vector<unsigned> optimize_control(std::vector<unsigned> control, unsigned index, double &score) { double initial_score = score; // Increase control at given index. while (control[index] < 200) { auto new_control = control; // make a copy new_control[index] += 1; auto new_score = play_game(new_control); if (new_score > score) { // It got worse. break; } control = new_control; score = new_score; } if (score < initial_score) { // Found better control. return control; } // Decrease control at given index. while (control[index] > 8) { auto new_control = control; // make a copy new_control[index] -= 1; auto new_score = play_game(new_control); if (new_score > score) { // It got worse. break; } control = new_control; score = new_score; } return control; } // // Play a series of games starting with initial control, // and optimize it according to the given variant. // Print the best score (minimal) and appropriate control. // void optimize_variant(const std::array<unsigned, 8> &variant, const std::vector<unsigned> &initial_control, const double initial_score, std::vector<unsigned> &best_control, double &best_score) { std::vector<unsigned> control = initial_control; double score = initial_score; double last_score; do { last_score = score; for (auto const index : variant) { control = optimize_control(control, 8 + index, score); } } while (score < last_score); // Stop when no enhancement anymore #if 0 // Print the score. if (score < initial_score) { std::cout << "Score " << score << ", control " << control << ", variant " << variant << std::endl; } #endif // Update the best score if (score < best_score) { best_score = score; best_control = control; } } // // Start with a given control and optimize it's items // in order defined by all permutations. // Try all variants one by one. // Return the best control, and update the best score. // std::vector<unsigned> optimize_control(const std::vector<unsigned> &initial_control, double &best_score) { std::array<unsigned, 8> variant = { 0, 1, 2, 3, 4, 5, 6, 7 }; const double initial_score = play_game(initial_control); // First pass. std::vector<unsigned> best_control = initial_control; best_score = initial_score; do { optimize_variant(variant, initial_control, initial_score, best_control, best_score); } while (std::next_permutation(variant.begin(), variant.end())); // Second pass. auto initial_control2 = best_control; auto initial_score2 = best_score; do { optimize_variant(variant, initial_control2, initial_score2, best_control, best_score); } while (std::next_permutation(variant.begin(), variant.end())); return best_control; } // // Start with a fixed control and optimize it. // Print the best score and control. // int main1() { const std::vector<unsigned> initial_control = { 0, 0, 0, 0, 0, 0, 0, // First, free fall for 70 seconds 180, 180, 180, 180, 180, 180, 180, 180, // Slow down for next 80 seconds }; double best_score; auto best_control = optimize_control(initial_control, best_score); // Print the best score and control. std::cout << "The best score " << best_score << ", control " << best_control << std::endl; return 0; } // // Start with ramdom control and optimize it. // Print the best score and control. // int main() { // Enable random generator. std::uniform_int_distribution<std::mt19937::result_type> large(170, 200); std::uniform_int_distribution<std::mt19937::result_type> small(8, 30); std::mt19937 random; random.seed(time(nullptr)); for (;;) { const std::vector<unsigned> initial_control = { // First, free fall for 70 seconds. 0, 0, 0, 0, 0, 0, 0, // Slow down for next 90 seconds. 200, large(random), large(random), large(random), large(random), large(random), large(random), large(random), small(random), }; double best_score; auto best_control = optimize_control(initial_control, best_score); // Print the best score and control. std::cout << "The best score " << best_score << ", control " << best_control << std::endl; } return 0; }
412
0.602871
1
0.602871
game-dev
MEDIA
0.520133
game-dev,testing-qa,ml-ai
0.714659
1
0.714659
MohistMC/Youer
1,220
src/main/java/org/bukkit/event/entity/EntitySpawnEvent.java
package org.bukkit.event.entity; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called when an entity is spawned into a world. * <p> * If an Entity Spawn event is cancelled, the entity will not spawn. */ public class EntitySpawnEvent extends EntityEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean canceled; public EntitySpawnEvent(@NotNull final Entity spawnee) { super(spawnee); } @Override public boolean isCancelled() { return canceled; } @Override public void setCancelled(boolean cancel) { canceled = cancel; } /** * Gets the location at which the entity is spawning. * * @return The location at which the entity is spawning */ @NotNull public Location getLocation() { return getEntity().getLocation(); } @NotNull @Override public HandlerList getHandlers() { return handlers; } @NotNull public static HandlerList getHandlerList() { return handlers; } }
412
0.840956
1
0.840956
game-dev
MEDIA
0.943795
game-dev
0.820917
1
0.820917
Alecaddd/Sunset-theme
33,129
Lesson 36/js/ace/mode-lsl.js
ace.define("ace/mode/lsl_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(e,t,n){"use strict";function s(){var e=this.createKeywordMapper({"constant.language.float.lsl":"DEG_TO_RAD|PI|PI_BY_TWO|RAD_TO_DEG|SQRT2|TWO_PI","constant.language.integer.lsl":"ACTIVE|AGENT|AGENT_ALWAYS_RUN|AGENT_ATTACHMENTS|AGENT_AUTOPILOT|AGENT_AWAY|AGENT_BUSY|AGENT_BY_LEGACY_NAME|AGENT_BY_USERNAME|AGENT_CROUCHING|AGENT_FLYING|AGENT_IN_AIR|AGENT_LIST_PARCEL|AGENT_LIST_PARCEL_OWNER|AGENT_LIST_REGION|AGENT_MOUSELOOK|AGENT_ON_OBJECT|AGENT_SCRIPTED|AGENT_SITTING|AGENT_TYPING|AGENT_WALKING|ALL_SIDES|ANIM_ON|ATTACH_AVATAR_CENTER|ATTACH_BACK|ATTACH_BELLY|ATTACH_CHEST|ATTACH_CHIN|ATTACH_HEAD|ATTACH_HUD_BOTTOM|ATTACH_HUD_BOTTOM_LEFT|ATTACH_HUD_BOTTOM_RIGHT|ATTACH_HUD_CENTER_1|ATTACH_HUD_CENTER_2|ATTACH_HUD_TOP_CENTER|ATTACH_HUD_TOP_LEFT|ATTACH_HUD_TOP_RIGHT|ATTACH_LEAR|ATTACH_LEFT_PEC|ATTACH_LEYE|ATTACH_LFOOT|ATTACH_LHAND|ATTACH_LHIP|ATTACH_LLARM|ATTACH_LLLEG|ATTACH_LSHOULDER|ATTACH_LUARM|ATTACH_LULEG|ATTACH_MOUTH|ATTACH_NECK|ATTACH_NOSE|ATTACH_PELVIS|ATTACH_REAR|ATTACH_REYE|ATTACH_RFOOT|ATTACH_RHAND|ATTACH_RHIP|ATTACH_RIGHT_PEC|ATTACH_RLARM|ATTACH_RLLEG|ATTACH_RSHOULDER|ATTACH_RUARM|ATTACH_RULEG|AVOID_CHARACTERS|AVOID_DYNAMIC_OBSTACLES|AVOID_NONE|CAMERA_ACTIVE|CAMERA_BEHINDNESS_ANGLE|CAMERA_BEHINDNESS_LAG|CAMERA_DISTANCE|CAMERA_FOCUS|CAMERA_FOCUS_LAG|CAMERA_FOCUS_LOCKED|CAMERA_FOCUS_OFFSET|CAMERA_FOCUS_THRESHOLD|CAMERA_PITCH|CAMERA_POSITION|CAMERA_POSITION_LAG|CAMERA_POSITION_LOCKED|CAMERA_POSITION_THRESHOLD|CHANGED_ALLOWED_DROP|CHANGED_COLOR|CHANGED_INVENTORY|CHANGED_LINK|CHANGED_MEDIA|CHANGED_OWNER|CHANGED_REGION|CHANGED_REGION_START|CHANGED_SCALE|CHANGED_SHAPE|CHANGED_TELEPORT|CHANGED_TEXTURE|CHARACTER_ACCOUNT_FOR_SKIPPED_FRAMES|CHARACTER_AVOIDANCE_MODE|CHARACTER_CMD_JUMP|CHARACTER_CMD_SMOOTH_STOP|CHARACTER_CMD_STOP|CHARACTER_DESIRED_SPEED|CHARACTER_DESIRED_TURN_SPEED|CHARACTER_LENGTH|CHARACTER_MAX_ACCEL|CHARACTER_MAX_DECEL|CHARACTER_MAX_SPEED|CHARACTER_MAX_TURN_RADIUS|CHARACTER_ORIENTATION|CHARACTER_RADIUS|CHARACTER_STAY_WITHIN_PARCEL|CHARACTER_TYPE|CHARACTER_TYPE_A|CHARACTER_TYPE_B|CHARACTER_TYPE_C|CHARACTER_TYPE_D|CHARACTER_TYPE_NONE|CLICK_ACTION_BUY|CLICK_ACTION_NONE|CLICK_ACTION_OPEN|CLICK_ACTION_OPEN_MEDIA|CLICK_ACTION_PAY|CLICK_ACTION_PLAY|CLICK_ACTION_SIT|CLICK_ACTION_TOUCH|CONTENT_TYPE_ATOM|CONTENT_TYPE_FORM|CONTENT_TYPE_HTML|CONTENT_TYPE_JSON|CONTENT_TYPE_LLSD|CONTENT_TYPE_RSS|CONTENT_TYPE_TEXT|CONTENT_TYPE_XHTML|CONTENT_TYPE_XML|CONTROL_BACK|CONTROL_DOWN|CONTROL_FWD|CONTROL_LBUTTON|CONTROL_LEFT|CONTROL_ML_LBUTTON|CONTROL_RIGHT|CONTROL_ROT_LEFT|CONTROL_ROT_RIGHT|CONTROL_UP|DATA_BORN|DATA_NAME|DATA_ONLINE|DATA_PAYINFO|DATA_SIM_POS|DATA_SIM_RATING|DATA_SIM_STATUS|DEBUG_CHANNEL|DENSITY|ERR_GENERIC|ERR_MALFORMED_PARAMS|ERR_PARCEL_PERMISSIONS|ERR_RUNTIME_PERMISSIONS|ERR_THROTTLED|ESTATE_ACCESS_ALLOWED_AGENT_ADD|ESTATE_ACCESS_ALLOWED_AGENT_REMOVE|ESTATE_ACCESS_ALLOWED_GROUP_ADD|ESTATE_ACCESS_ALLOWED_GROUP_REMOVE|ESTATE_ACCESS_BANNED_AGENT_ADD|ESTATE_ACCESS_BANNED_AGENT_REMOVE|FALSE|FORCE_DIRECT_PATH|FRICTION|GCNP_RADIUS|GCNP_STATIC|GRAVITY_MULTIPLIER|HORIZONTAL|HTTP_BODY_MAXLENGTH|HTTP_BODY_TRUNCATED|HTTP_CUSTOM_HEADER|HTTP_METHOD|HTTP_MIMETYPE|HTTP_PRAGMA_NO_CACHE|HTTP_VERBOSE_THROTTLE|HTTP_VERIFY_CERT|INVENTORY_ALL|INVENTORY_ANIMATION|INVENTORY_BODYPART|INVENTORY_CLOTHING|INVENTORY_GESTURE|INVENTORY_LANDMARK|INVENTORY_NONE|INVENTORY_NOTECARD|INVENTORY_OBJECT|INVENTORY_SCRIPT|INVENTORY_SOUND|INVENTORY_TEXTURE|JSON_APPEND|KFM_CMD_PAUSE|KFM_CMD_PLAY|KFM_CMD_SET_MODE|KFM_CMD_STOP|KFM_COMMAND|KFM_DATA|KFM_FORWARD|KFM_LOOP|KFM_MODE|KFM_PING_PONG|KFM_REVERSE|KFM_ROTATION|KFM_TRANSLATION|LAND_LEVEL|LAND_LOWER|LAND_NOISE|LAND_RAISE|LAND_REVERT|LAND_SMOOTH|LINK_ALL_CHILDREN|LINK_ALL_OTHERS|LINK_ROOT|LINK_SET|LINK_THIS|LIST_STAT_GEOMETRIC_MEAN|LIST_STAT_MAX|LIST_STAT_MEAN|LIST_STAT_MEDIAN|LIST_STAT_MIN|LIST_STAT_NUM_COUNT|LIST_STAT_RANGE|LIST_STAT_STD_DEV|LIST_STAT_SUM|LIST_STAT_SUM_SQUARES|LOOP|MASK_BASE|MASK_EVERYONE|MASK_GROUP|MASK_NEXT|MASK_OWNER|OBJECT_ATTACHED_POINT|OBJECT_BODY_SHAPE_TYPE|OBJECT_CHARACTER_TIME|OBJECT_CLICK_ACTION|OBJECT_CREATOR|OBJECT_DESC|OBJECT_GROUP|OBJECT_HOVER_HEIGHT|OBJECT_LAST_OWNER_ID|OBJECT_NAME|OBJECT_OWNER|OBJECT_PATHFINDING_TYPE|OBJECT_PHANTOM|OBJECT_PHYSICS|OBJECT_PHYSICS_COST|OBJECT_POS|OBJECT_PRIM_EQUIVALENCE|OBJECT_RENDER_WEIGHT|OBJECT_RETURN_PARCEL|OBJECT_RETURN_PARCEL_OWNER|OBJECT_RETURN_REGION|OBJECT_ROOT|OBJECT_ROT|OBJECT_RUNNING_SCRIPT_COUNT|OBJECT_SCRIPT_MEMORY|OBJECT_SCRIPT_TIME|OBJECT_SERVER_COST|OBJECT_STREAMING_COST|OBJECT_TEMP_ON_REZ|OBJECT_TOTAL_SCRIPT_COUNT|OBJECT_UNKNOWN_DETAIL|OBJECT_VELOCITY|OPT_AVATAR|OPT_CHARACTER|OPT_EXCLUSION_VOLUME|OPT_LEGACY_LINKSET|OPT_MATERIAL_VOLUME|OPT_OTHER|OPT_STATIC_OBSTACLE|OPT_WALKABLE|PARCEL_COUNT_GROUP|PARCEL_COUNT_OTHER|PARCEL_COUNT_OWNER|PARCEL_COUNT_SELECTED|PARCEL_COUNT_TEMP|PARCEL_COUNT_TOTAL|PARCEL_DETAILS_AREA|PARCEL_DETAILS_DESC|PARCEL_DETAILS_GROUP|PARCEL_DETAILS_ID|PARCEL_DETAILS_NAME|PARCEL_DETAILS_OWNER|PARCEL_DETAILS_SEE_AVATARS|PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY|PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS|PARCEL_FLAG_ALLOW_CREATE_OBJECTS|PARCEL_FLAG_ALLOW_DAMAGE|PARCEL_FLAG_ALLOW_FLY|PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY|PARCEL_FLAG_ALLOW_GROUP_SCRIPTS|PARCEL_FLAG_ALLOW_LANDMARK|PARCEL_FLAG_ALLOW_SCRIPTS|PARCEL_FLAG_ALLOW_TERRAFORM|PARCEL_FLAG_LOCAL_SOUND_ONLY|PARCEL_FLAG_RESTRICT_PUSHOBJECT|PARCEL_FLAG_USE_ACCESS_GROUP|PARCEL_FLAG_USE_ACCESS_LIST|PARCEL_FLAG_USE_BAN_LIST|PARCEL_FLAG_USE_LAND_PASS_LIST|PARCEL_MEDIA_COMMAND_AGENT|PARCEL_MEDIA_COMMAND_AUTO_ALIGN|PARCEL_MEDIA_COMMAND_DESC|PARCEL_MEDIA_COMMAND_LOOP|PARCEL_MEDIA_COMMAND_LOOP_SET|PARCEL_MEDIA_COMMAND_PAUSE|PARCEL_MEDIA_COMMAND_PLAY|PARCEL_MEDIA_COMMAND_SIZE|PARCEL_MEDIA_COMMAND_STOP|PARCEL_MEDIA_COMMAND_TEXTURE|PARCEL_MEDIA_COMMAND_TIME|PARCEL_MEDIA_COMMAND_TYPE|PARCEL_MEDIA_COMMAND_UNLOAD|PARCEL_MEDIA_COMMAND_URL|PASS_ALWAYS|PASS_IF_NOT_HANDLED|PASS_NEVER|PASSIVE|PATROL_PAUSE_AT_WAYPOINTS|PAYMENT_INFO_ON_FILE|PAYMENT_INFO_USED|PAY_DEFAULT|PAY_HIDE|PERMISSION_ATTACH|PERMISSION_CHANGE_LINKS|PERMISSION_CONTROL_CAMERA|PERMISSION_DEBIT|PERMISSION_OVERRIDE_ANIMATIONS|PERMISSION_RETURN_OBJECTS|PERMISSION_SILENT_ESTATE_MANAGEMENT|PERMISSION_TAKE_CONTROLS|PERMISSION_TELEPORT|PERMISSION_TRACK_CAMERA|PERMISSION_TRIGGER_ANIMATION|PERM_ALL|PERM_COPY|PERM_MODIFY|PERM_MOVE|PERM_TRANSFER|PING_PONG|PRIM_ALPHA_MODE|PRIM_ALPHA_MODE_BLEND|PRIM_ALPHA_MODE_EMISSIVE|PRIM_ALPHA_MODE_MASK|PRIM_ALPHA_MODE_NONE|PRIM_BUMP_BARK|PRIM_BUMP_BLOBS|PRIM_BUMP_BRICKS|PRIM_BUMP_BRIGHT|PRIM_BUMP_CHECKER|PRIM_BUMP_CONCRETE|PRIM_BUMP_DARK|PRIM_BUMP_DISKS|PRIM_BUMP_GRAVEL|PRIM_BUMP_LARGETILE|PRIM_BUMP_NONE|PRIM_BUMP_SHINY|PRIM_BUMP_SIDING|PRIM_BUMP_STONE|PRIM_BUMP_STUCCO|PRIM_BUMP_SUCTION|PRIM_BUMP_TILE|PRIM_BUMP_WEAVE|PRIM_BUMP_WOOD|PRIM_COLOR|PRIM_DESC|PRIM_FLEXIBLE|PRIM_FULLBRIGHT|PRIM_GLOW|PRIM_HOLE_CIRCLE|PRIM_HOLE_DEFAULT|PRIM_HOLE_SQUARE|PRIM_HOLE_TRIANGLE|PRIM_LINK_TARGET|PRIM_MATERIAL|PRIM_MATERIAL_FLESH|PRIM_MATERIAL_GLASS|PRIM_MATERIAL_METAL|PRIM_MATERIAL_PLASTIC|PRIM_MATERIAL_RUBBER|PRIM_MATERIAL_STONE|PRIM_MATERIAL_WOOD|PRIM_MEDIA_ALT_IMAGE_ENABLE|PRIM_MEDIA_AUTO_LOOP|PRIM_MEDIA_AUTO_PLAY|PRIM_MEDIA_AUTO_SCALE|PRIM_MEDIA_AUTO_ZOOM|PRIM_MEDIA_CONTROLS|PRIM_MEDIA_CONTROLS_MINI|PRIM_MEDIA_CONTROLS_STANDARD|PRIM_MEDIA_CURRENT_URL|PRIM_MEDIA_FIRST_CLICK_INTERACT|PRIM_MEDIA_HEIGHT_PIXELS|PRIM_MEDIA_HOME_URL|PRIM_MEDIA_MAX_HEIGHT_PIXELS|PRIM_MEDIA_MAX_URL_LENGTH|PRIM_MEDIA_MAX_WHITELIST_COUNT|PRIM_MEDIA_MAX_WHITELIST_SIZE|PRIM_MEDIA_MAX_WIDTH_PIXELS|PRIM_MEDIA_PARAM_MAX|PRIM_MEDIA_PERMS_CONTROL|PRIM_MEDIA_PERMS_INTERACT|PRIM_MEDIA_PERM_ANYONE|PRIM_MEDIA_PERM_GROUP|PRIM_MEDIA_PERM_NONE|PRIM_MEDIA_PERM_OWNER|PRIM_MEDIA_WHITELIST|PRIM_MEDIA_WHITELIST_ENABLE|PRIM_MEDIA_WIDTH_PIXELS|PRIM_NAME|PRIM_NORMAL|PRIM_OMEGA|PRIM_PHANTOM|PRIM_PHYSICS|PRIM_PHYSICS_SHAPE_CONVEX|PRIM_PHYSICS_SHAPE_NONE|PRIM_PHYSICS_SHAPE_PRIM|PRIM_PHYSICS_SHAPE_TYPE|PRIM_POINT_LIGHT|PRIM_POSITION|PRIM_POS_LOCAL|PRIM_ROTATION|PRIM_ROT_LOCAL|PRIM_SCULPT_FLAG_INVERT|PRIM_SCULPT_FLAG_MIRROR|PRIM_SCULPT_TYPE_CYLINDER|PRIM_SCULPT_TYPE_MASK|PRIM_SCULPT_TYPE_PLANE|PRIM_SCULPT_TYPE_SPHERE|PRIM_SCULPT_TYPE_TORUS|PRIM_SHINY_HIGH|PRIM_SHINY_LOW|PRIM_SHINY_MEDIUM|PRIM_SHINY_NONE|PRIM_SIZE|PRIM_SLICE|PRIM_SPECULAR|PRIM_TEMP_ON_REZ|PRIM_TEXGEN|PRIM_TEXGEN_DEFAULT|PRIM_TEXGEN_PLANAR|PRIM_TEXT|PRIM_TEXTURE|PRIM_TYPE|PRIM_TYPE_BOX|PRIM_TYPE_CYLINDER|PRIM_TYPE_PRISM|PRIM_TYPE_RING|PRIM_TYPE_SCULPT|PRIM_TYPE_SPHERE|PRIM_TYPE_TORUS|PRIM_TYPE_TUBE|PROFILE_NONE|PROFILE_SCRIPT_MEMORY|PSYS_PART_BF_DEST_COLOR|PSYS_PART_BF_ONE|PSYS_PART_BF_ONE_MINUS_DEST_COLOR|PSYS_PART_BF_ONE_MINUS_SOURCE_ALPHA|PSYS_PART_BF_ONE_MINUS_SOURCE_COLOR|PSYS_PART_BF_SOURCE_ALPHA|PSYS_PART_BF_SOURCE_COLOR|PSYS_PART_BF_ZERO|PSYS_PART_BLEND_FUNC_DEST|PSYS_PART_BLEND_FUNC_SOURCE|PSYS_PART_BOUNCE_MASK|PSYS_PART_EMISSIVE_MASK|PSYS_PART_END_ALPHA|PSYS_PART_END_COLOR|PSYS_PART_END_GLOW|PSYS_PART_END_SCALE|PSYS_PART_FLAGS|PSYS_PART_FOLLOW_SRC_MASK|PSYS_PART_FOLLOW_VELOCITY_MASK|PSYS_PART_INTERP_COLOR_MASK|PSYS_PART_INTERP_SCALE_MASK|PSYS_PART_MAX_AGE|PSYS_PART_RIBBON_MASK|PSYS_PART_START_ALPHA|PSYS_PART_START_COLOR|PSYS_PART_START_GLOW|PSYS_PART_START_SCALE|PSYS_PART_TARGET_LINEAR_MASK|PSYS_PART_TARGET_POS_MASK|PSYS_PART_WIND_MASK|PSYS_SRC_ACCEL|PSYS_SRC_ANGLE_BEGIN|PSYS_SRC_ANGLE_END|PSYS_SRC_BURST_PART_COUNT|PSYS_SRC_BURST_RADIUS|PSYS_SRC_BURST_RATE|PSYS_SRC_BURST_SPEED_MAX|PSYS_SRC_BURST_SPEED_MIN|PSYS_SRC_MAX_AGE|PSYS_SRC_OMEGA|PSYS_SRC_PATTERN|PSYS_SRC_PATTERN_ANGLE|PSYS_SRC_PATTERN_ANGLE_CONE|PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY|PSYS_SRC_PATTERN_DROP|PSYS_SRC_PATTERN_EXPLODE|PSYS_SRC_TARGET_KEY|PSYS_SRC_TEXTURE|PUBLIC_CHANNEL|PURSUIT_FUZZ_FACTOR|PURSUIT_GOAL_TOLERANCE|PURSUIT_INTERCEPT|PURSUIT_OFFSET|PU_EVADE_HIDDEN|PU_EVADE_SPOTTED|PU_FAILURE_DYNAMIC_PATHFINDING_DISABLED|PU_FAILURE_INVALID_GOAL|PU_FAILURE_INVALID_START|PU_FAILURE_NO_NAVMESH|PU_FAILURE_NO_VALID_DESTINATION|PU_FAILURE_OTHER|PU_FAILURE_PARCEL_UNREACHABLE|PU_FAILURE_TARGET_GONE|PU_FAILURE_UNREACHABLE|PU_GOAL_REACHED|PU_SLOWDOWN_DISTANCE_REACHED|RCERR_CAST_TIME_EXCEEDED|RCERR_SIM_PERF_LOW|RCERR_UNKNOWN|RC_DATA_FLAGS|RC_DETECT_PHANTOM|RC_GET_LINK_NUM|RC_GET_NORMAL|RC_GET_ROOT_KEY|RC_MAX_HITS|RC_REJECT_AGENTS|RC_REJECT_LAND|RC_REJECT_NONPHYSICAL|RC_REJECT_PHYSICAL|RC_REJECT_TYPES|REGION_FLAG_ALLOW_DAMAGE|REGION_FLAG_ALLOW_DIRECT_TELEPORT|REGION_FLAG_BLOCK_FLY|REGION_FLAG_BLOCK_TERRAFORM|REGION_FLAG_DISABLE_COLLISIONS|REGION_FLAG_DISABLE_PHYSICS|REGION_FLAG_FIXED_SUN|REGION_FLAG_RESTRICT_PUSHOBJECT|REGION_FLAG_SANDBOX|REMOTE_DATA_CHANNEL|REMOTE_DATA_REPLY|REMOTE_DATA_REQUEST|REQUIRE_LINE_OF_SIGHT|RESTITUTION|REVERSE|ROTATE|SCALE|SCRIPTED|SIM_STAT_PCT_CHARS_STEPPED|SMOOTH|STATUS_BLOCK_GRAB|STATUS_BLOCK_GRAB_OBJECT|STATUS_BOUNDS_ERROR|STATUS_CAST_SHADOWS|STATUS_DIE_AT_EDGE|STATUS_INTERNAL_ERROR|STATUS_MALFORMED_PARAMS|STATUS_NOT_FOUND|STATUS_NOT_SUPPORTED|STATUS_OK|STATUS_PHANTOM|STATUS_PHYSICS|STATUS_RETURN_AT_EDGE|STATUS_ROTATE_X|STATUS_ROTATE_Y|STATUS_ROTATE_Z|STATUS_SANDBOX|STATUS_TYPE_MISMATCH|STATUS_WHITELIST_FAILED|STRING_TRIM|STRING_TRIM_HEAD|STRING_TRIM_TAIL|TOUCH_INVALID_FACE|TRAVERSAL_TYPE|TRAVERSAL_TYPE_FAST|TRAVERSAL_TYPE_NONE|TRAVERSAL_TYPE_SLOW|TRUE|TYPE_FLOAT|TYPE_INTEGER|TYPE_INVALID|TYPE_KEY|TYPE_ROTATION|TYPE_STRING|TYPE_VECTOR|VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY|VEHICLE_ANGULAR_DEFLECTION_TIMESCALE|VEHICLE_ANGULAR_FRICTION_TIMESCALE|VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE|VEHICLE_ANGULAR_MOTOR_DIRECTION|VEHICLE_ANGULAR_MOTOR_TIMESCALE|VEHICLE_BANKING_EFFICIENCY|VEHICLE_BANKING_MIX|VEHICLE_BANKING_TIMESCALE|VEHICLE_BUOYANCY|VEHICLE_FLAG_CAMERA_DECOUPLED|VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT|VEHICLE_FLAG_HOVER_TERRAIN_ONLY|VEHICLE_FLAG_HOVER_UP_ONLY|VEHICLE_FLAG_HOVER_WATER_ONLY|VEHICLE_FLAG_LIMIT_MOTOR_UP|VEHICLE_FLAG_LIMIT_ROLL_ONLY|VEHICLE_FLAG_MOUSELOOK_BANK|VEHICLE_FLAG_MOUSELOOK_STEER|VEHICLE_FLAG_NO_DEFLECTION_UP|VEHICLE_HOVER_EFFICIENCY|VEHICLE_HOVER_HEIGHT|VEHICLE_HOVER_TIMESCALE|VEHICLE_LINEAR_DEFLECTION_EFFICIENCY|VEHICLE_LINEAR_DEFLECTION_TIMESCALE|VEHICLE_LINEAR_FRICTION_TIMESCALE|VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE|VEHICLE_LINEAR_MOTOR_DIRECTION|VEHICLE_LINEAR_MOTOR_OFFSET|VEHICLE_LINEAR_MOTOR_TIMESCALE|VEHICLE_REFERENCE_FRAME|VEHICLE_TYPE_AIRPLANE|VEHICLE_TYPE_BALLOON|VEHICLE_TYPE_BOAT|VEHICLE_TYPE_CAR|VEHICLE_TYPE_NONE|VEHICLE_TYPE_SLED|VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY|VEHICLE_VERTICAL_ATTRACTION_TIMESCALE|VERTICAL|WANDER_PAUSE_AT_WAYPOINTS|XP_ERROR_EXPERIENCES_DISABLED|XP_ERROR_EXPERIENCE_DISABLED|XP_ERROR_EXPERIENCE_SUSPENDED|XP_ERROR_INVALID_EXPERIENCE|XP_ERROR_INVALID_PARAMETERS|XP_ERROR_KEY_NOT_FOUND|XP_ERROR_MATURITY_EXCEEDED|XP_ERROR_NONE|XP_ERROR_NOT_FOUND|XP_ERROR_NOT_PERMITTED|XP_ERROR_NO_EXPERIENCE|XP_ERROR_QUOTA_EXCEEDED|XP_ERROR_RETRY_UPDATE|XP_ERROR_STORAGE_EXCEPTION|XP_ERROR_STORE_DISABLED|XP_ERROR_THROTTLED|XP_ERROR_UNKNOWN_ERROR","constant.language.integer.boolean.lsl":"FALSE|TRUE","constant.language.quaternion.lsl":"ZERO_ROTATION","constant.language.string.lsl":"EOF|JSON_ARRAY|JSON_DELETE|JSON_FALSE|JSON_INVALID|JSON_NULL|JSON_NUMBER|JSON_OBJECT|JSON_STRING|JSON_TRUE|NULL_KEY|TEXTURE_BLANK|TEXTURE_DEFAULT|TEXTURE_MEDIA|TEXTURE_PLYWOOD|TEXTURE_TRANSPARENT|URL_REQUEST_DENIED|URL_REQUEST_GRANTED","constant.language.vector.lsl":"TOUCH_INVALID_TEXCOORD|TOUCH_INVALID_VECTOR|ZERO_VECTOR","invalid.broken.lsl":"LAND_LARGE_BRUSH|LAND_MEDIUM_BRUSH|LAND_SMALL_BRUSH","invalid.deprecated.lsl":"ATTACH_LPEC|ATTACH_RPEC|DATA_RATING|OBJECT_ATTACHMENT_GEOMETRY_BYTES|OBJECT_ATTACHMENT_SURFACE_AREA|PRIM_CAST_SHADOWS|PRIM_MATERIAL_LIGHT|PRIM_TYPE_LEGACY|PSYS_SRC_INNERANGLE|PSYS_SRC_OUTERANGLE|VEHICLE_FLAG_NO_FLY_UP|llClearExperiencePermissions|llCloud|llGetExperienceList|llMakeExplosion|llMakeFire|llMakeFountain|llMakeSmoke|llRemoteDataSetRegion|llSound|llSoundPreload|llXorBase64Strings|llXorBase64StringsCorrect","invalid.illegal.lsl":"event","invalid.unimplemented.lsl":"CHARACTER_MAX_ANGULAR_ACCEL|CHARACTER_MAX_ANGULAR_SPEED|CHARACTER_TURN_SPEED_MULTIPLIER|PERMISSION_CHANGE_JOINTS|PERMISSION_CHANGE_PERMISSIONS|PERMISSION_EXPERIENCE|PERMISSION_RELEASE_OWNERSHIP|PERMISSION_REMAP_CONTROLS|PRIM_PHYSICS_MATERIAL|PSYS_SRC_OBJ_REL_MASK|llCollisionSprite|llPointAt|llRefreshPrimURL|llReleaseCamera|llRemoteLoadScript|llSetPrimURL|llStopPointAt|llTakeCamera","reserved.godmode.lsl":"llGodLikeRezObject|llSetInventoryPermMask|llSetObjectPermMask","reserved.log.lsl":"print","keyword.control.lsl":"do|else|for|if|jump|return|while","storage.type.lsl":"float|integer|key|list|quaternion|rotation|string|vector","support.function.lsl":"llAbs|llAcos|llAddToLandBanList|llAddToLandPassList|llAdjustSoundVolume|llAgentInExperience|llAllowInventoryDrop|llAngleBetween|llApplyImpulse|llApplyRotationalImpulse|llAsin|llAtan2|llAttachToAvatar|llAttachToAvatarTemp|llAvatarOnLinkSitTarget|llAvatarOnSitTarget|llAxes2Rot|llAxisAngle2Rot|llBase64ToInteger|llBase64ToString|llBreakAllLinks|llBreakLink|llCSV2List|llCastRay|llCeil|llClearCameraParams|llClearLinkMedia|llClearPrimMedia|llCloseRemoteDataChannel|llCollisionFilter|llCollisionSound|llCos|llCreateCharacter|llCreateKeyValue|llCreateLink|llDataSizeKeyValue|llDeleteCharacter|llDeleteKeyValue|llDeleteSubList|llDeleteSubString|llDetachFromAvatar|llDetectedGrab|llDetectedGroup|llDetectedKey|llDetectedLinkNumber|llDetectedName|llDetectedOwner|llDetectedPos|llDetectedRot|llDetectedTouchBinormal|llDetectedTouchFace|llDetectedTouchNormal|llDetectedTouchPos|llDetectedTouchST|llDetectedTouchUV|llDetectedType|llDetectedVel|llDialog|llDie|llDumpList2String|llEdgeOfWorld|llEjectFromLand|llEmail|llEscapeURL|llEuler2Rot|llEvade|llExecCharacterCmd|llFabs|llFleeFrom|llFloor|llForceMouselook|llFrand|llGenerateKey|llGetAccel|llGetAgentInfo|llGetAgentLanguage|llGetAgentList|llGetAgentSize|llGetAlpha|llGetAndResetTime|llGetAnimation|llGetAnimationList|llGetAnimationOverride|llGetAttached|llGetAttachedList|llGetBoundingBox|llGetCameraPos|llGetCameraRot|llGetCenterOfMass|llGetClosestNavPoint|llGetColor|llGetCreator|llGetDate|llGetDisplayName|llGetEnergy|llGetEnv|llGetExperienceDetails|llGetExperienceErrorMessage|llGetForce|llGetFreeMemory|llGetFreeURLs|llGetGMTclock|llGetGeometricCenter|llGetHTTPHeader|llGetInventoryCreator|llGetInventoryKey|llGetInventoryName|llGetInventoryNumber|llGetInventoryPermMask|llGetInventoryType|llGetKey|llGetLandOwnerAt|llGetLinkKey|llGetLinkMedia|llGetLinkName|llGetLinkNumber|llGetLinkNumberOfSides|llGetLinkPrimitiveParams|llGetListEntryType|llGetListLength|llGetLocalPos|llGetLocalRot|llGetMass|llGetMassMKS|llGetMaxScaleFactor|llGetMemoryLimit|llGetMinScaleFactor|llGetNextEmail|llGetNotecardLine|llGetNumberOfNotecardLines|llGetNumberOfPrims|llGetNumberOfSides|llGetObjectDesc|llGetObjectDetails|llGetObjectMass|llGetObjectName|llGetObjectPermMask|llGetObjectPrimCount|llGetOmega|llGetOwner|llGetOwnerKey|llGetParcelDetails|llGetParcelFlags|llGetParcelMaxPrims|llGetParcelMusicURL|llGetParcelPrimCount|llGetParcelPrimOwners|llGetPermissions|llGetPermissionsKey|llGetPhysicsMaterial|llGetPos|llGetPrimMediaParams|llGetPrimitiveParams|llGetRegionAgentCount|llGetRegionCorner|llGetRegionFPS|llGetRegionFlags|llGetRegionName|llGetRegionTimeDilation|llGetRootPosition|llGetRootRotation|llGetRot|llGetSPMaxMemory|llGetScale|llGetScriptName|llGetScriptState|llGetSimStats|llGetSimulatorHostname|llGetStartParameter|llGetStaticPath|llGetStatus|llGetSubString|llGetSunDirection|llGetTexture|llGetTextureOffset|llGetTextureRot|llGetTextureScale|llGetTime|llGetTimeOfDay|llGetTimestamp|llGetTorque|llGetUnixTime|llGetUsedMemory|llGetUsername|llGetVel|llGetWallclock|llGiveInventory|llGiveInventoryList|llGiveMoney|llGround|llGroundContour|llGroundNormal|llGroundRepel|llGroundSlope|llHTTPRequest|llHTTPResponse|llInsertString|llInstantMessage|llIntegerToBase64|llJson2List|llJsonGetValue|llJsonSetValue|llJsonValueType|llKey2Name|llKeyCountKeyValue|llKeysKeyValue|llLinkParticleSystem|llLinkSitTarget|llList2CSV|llList2Float|llList2Integer|llList2Json|llList2Key|llList2List|llList2ListStrided|llList2Rot|llList2String|llList2Vector|llListFindList|llListInsertList|llListRandomize|llListReplaceList|llListSort|llListStatistics|llListen|llListenControl|llListenRemove|llLoadURL|llLog|llLog10|llLookAt|llLoopSound|llLoopSoundMaster|llLoopSoundSlave|llMD5String|llManageEstateAccess|llMapDestination|llMessageLinked|llMinEventDelay|llModPow|llModifyLand|llMoveToTarget|llNavigateTo|llOffsetTexture|llOpenRemoteDataChannel|llOverMyLand|llOwnerSay|llParcelMediaCommandList|llParcelMediaQuery|llParseString2List|llParseStringKeepNulls|llParticleSystem|llPassCollisions|llPassTouches|llPatrolPoints|llPlaySound|llPlaySoundSlave|llPow|llPreloadSound|llPursue|llPushObject|llReadKeyValue|llRegionSay|llRegionSayTo|llReleaseControls|llReleaseURL|llRemoteDataReply|llRemoteLoadScriptPin|llRemoveFromLandBanList|llRemoveFromLandPassList|llRemoveInventory|llRemoveVehicleFlags|llRequestAgentData|llRequestDisplayName|llRequestExperiencePermissions|llRequestInventoryData|llRequestPermissions|llRequestSecureURL|llRequestSimulatorData|llRequestURL|llRequestUsername|llResetAnimationOverride|llResetLandBanList|llResetLandPassList|llResetOtherScript|llResetScript|llResetTime|llReturnObjectsByID|llReturnObjectsByOwner|llRezAtRoot|llRezObject|llRot2Angle|llRot2Axis|llRot2Euler|llRot2Fwd|llRot2Left|llRot2Up|llRotBetween|llRotLookAt|llRotTarget|llRotTargetRemove|llRotateTexture|llRound|llSHA1String|llSameGroup|llSay|llScaleByFactor|llScaleTexture|llScriptDanger|llScriptProfiler|llSendRemoteData|llSensor|llSensorRemove|llSensorRepeat|llSetAlpha|llSetAngularVelocity|llSetAnimationOverride|llSetBuoyancy|llSetCameraAtOffset|llSetCameraEyeOffset|llSetCameraParams|llSetClickAction|llSetColor|llSetContentType|llSetDamage|llSetForce|llSetForceAndTorque|llSetHoverHeight|llSetKeyframedMotion|llSetLinkAlpha|llSetLinkCamera|llSetLinkColor|llSetLinkMedia|llSetLinkPrimitiveParams|llSetLinkPrimitiveParamsFast|llSetLinkTexture|llSetLinkTextureAnim|llSetLocalRot|llSetMemoryLimit|llSetObjectDesc|llSetObjectName|llSetParcelMusicURL|llSetPayPrice|llSetPhysicsMaterial|llSetPos|llSetPrimMediaParams|llSetPrimitiveParams|llSetRegionPos|llSetRemoteScriptAccessPin|llSetRot|llSetScale|llSetScriptState|llSetSitText|llSetSoundQueueing|llSetSoundRadius|llSetStatus|llSetText|llSetTexture|llSetTextureAnim|llSetTimerEvent|llSetTorque|llSetTouchText|llSetVehicleFlags|llSetVehicleFloatParam|llSetVehicleRotationParam|llSetVehicleType|llSetVehicleVectorParam|llSetVelocity|llShout|llSin|llSitTarget|llSleep|llSqrt|llStartAnimation|llStopAnimation|llStopHover|llStopLookAt|llStopMoveToTarget|llStopSound|llStringLength|llStringToBase64|llStringTrim|llSubStringIndex|llTakeControls|llTan|llTarget|llTargetOmega|llTargetRemove|llTeleportAgent|llTeleportAgentGlobalCoords|llTeleportAgentHome|llTextBox|llToLower|llToUpper|llTransferLindenDollars|llTriggerSound|llTriggerSoundLimited|llUnSit|llUnescapeURL|llUpdateCharacter|llUpdateKeyValue|llVecDist|llVecMag|llVecNorm|llVolumeDetect|llWanderWithin|llWater|llWhisper|llWind|llXorBase64","support.function.event.lsl":"at_rot_target|at_target|attach|changed|collision|collision_end|collision_start|control|dataserver|email|experience_permissions|experience_permissions_denied|http_request|http_response|land_collision|land_collision_end|land_collision_start|link_message|listen|money|moving_end|moving_start|no_sensor|not_at_rot_target|not_at_target|object_rez|on_rez|path_update|remote_data|run_time_permissions|sensor|state_entry|state_exit|timer|touch|touch_end|touch_start|transaction_result"},"identifier");this.$rules={start:[{token:"comment.line.double-slash.lsl",regex:"\\/\\/.*$"},{token:"comment.block.begin.lsl",regex:"\\/\\*",next:"comment"},{token:"string.quoted.double.lsl",start:'"',end:'"',next:[{token:"constant.character.escape.lsl",regex:/\\[tn"\\]/}]},{token:"constant.numeric.lsl",regex:"(0[xX][0-9a-fA-F]+|[+-]?[0-9]+(?:(?:\\.[0-9]*)?(?:[eE][+-]?[0-9]+)?)?)\\b"},{token:"entity.name.state.lsl",regex:"\\b((state)\\s+[A-Za-z_]\\w*|default)\\b"},{token:e,regex:"\\b[a-zA-Z_][a-zA-Z0-9_]*\\b"},{token:"support.function.user-defined.lsl",regex:/\b([a-zA-Z_]\w*)(?=\(.*?\))/},{token:"keyword.operator.lsl",regex:"\\+\\+|\\-\\-|<<|>>|&&?|\\|\\|?|\\^|~|[!%<>=*+\\-\\/]=?"},{token:"invalid.illegal.keyword.operator.lsl",regex:":=?"},{token:"punctuation.operator.lsl",regex:"\\,|\\;"},{token:"paren.lparen.lsl",regex:"[\\[\\(\\{]"},{token:"paren.rparen.lsl",regex:"[\\]\\)\\}]"},{token:"text.lsl",regex:"\\s+"}],comment:[{token:"comment.block.end.lsl",regex:"\\*\\/",next:"start"},{defaultToken:"comment.block.lsl"}]},this.normalizeRules()}var r=e("../lib/oop"),i=e("./text_highlight_rules").TextHighlightRules;r.inherits(s,i),t.LSLHighlightRules=s}),ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(e,t,n){"use strict";var r=e("../range").Range,i=function(){};(function(){this.checkOutdent=function(e,t){return/^\s+$/.test(e)?/^\s*\}/.test(t):!1},this.autoOutdent=function(e,t){var n=e.getLine(t),i=n.match(/^(\s*\})/);if(!i)return 0;var s=i[1].length,o=e.findMatchingBracket({row:t,column:s});if(!o||o.row==t)return 0;var u=this.$getIndent(e.getLine(o.row));e.replace(new r(t,0,t,s-1),u)},this.$getIndent=function(e){return e.match(/^\s*/)[0]}}).call(i.prototype),t.MatchingBraceOutdent=i}),ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"],function(e,t,n){"use strict";var r=e("../../lib/oop"),i=e("../behaviour").Behaviour,s=e("../../token_iterator").TokenIterator,o=e("../../lib/lang"),u=["text","paren.rparen","punctuation.operator"],a=["text","paren.rparen","punctuation.operator","comment"],f,l={},c=function(e){var t=-1;e.multiSelect&&(t=e.selection.index,l.rangeCount!=e.multiSelect.rangeCount&&(l={rangeCount:e.multiSelect.rangeCount}));if(l[t])return f=l[t];f=l[t]={autoInsertedBrackets:0,autoInsertedRow:-1,autoInsertedLineEnd:"",maybeInsertedBrackets:0,maybeInsertedRow:-1,maybeInsertedLineStart:"",maybeInsertedLineEnd:""}},h=function(e,t,n,r){var i=e.end.row-e.start.row;return{text:n+t+r,selection:[0,e.start.column+1,i,e.end.column+(i?0:1)]}},p=function(){this.add("braces","insertion",function(e,t,n,r,i){var s=n.getCursorPosition(),u=r.doc.getLine(s.row);if(i=="{"){c(n);var a=n.getSelectionRange(),l=r.doc.getTextRange(a);if(l!==""&&l!=="{"&&n.getWrapBehavioursEnabled())return h(a,l,"{","}");if(p.isSaneInsertion(n,r))return/[\]\}\)]/.test(u[s.column])||n.inMultiSelectMode?(p.recordAutoInsert(n,r,"}"),{text:"{}",selection:[1,1]}):(p.recordMaybeInsert(n,r,"{"),{text:"{",selection:[1,1]})}else if(i=="}"){c(n);var d=u.substring(s.column,s.column+1);if(d=="}"){var v=r.$findOpeningBracket("}",{column:s.column+1,row:s.row});if(v!==null&&p.isAutoInsertedClosing(s,u,i))return p.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}else{if(i=="\n"||i=="\r\n"){c(n);var m="";p.isMaybeInsertedClosing(s,u)&&(m=o.stringRepeat("}",f.maybeInsertedBrackets),p.clearMaybeInsertedClosing());var d=u.substring(s.column,s.column+1);if(d==="}"){var g=r.findMatchingBracket({row:s.row,column:s.column+1},"}");if(!g)return null;var y=this.$getIndent(r.getLine(g.row))}else{if(!m){p.clearMaybeInsertedClosing();return}var y=this.$getIndent(u)}var b=y+r.getTabString();return{text:"\n"+b+"\n"+y+m,selection:[1,b.length,1,b.length]}}p.clearMaybeInsertedClosing()}}),this.add("braces","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="{"){c(n);var o=r.doc.getLine(i.start.row),u=o.substring(i.end.column,i.end.column+1);if(u=="}")return i.end.column++,i;f.maybeInsertedBrackets--}}),this.add("parens","insertion",function(e,t,n,r,i){if(i=="("){c(n);var s=n.getSelectionRange(),o=r.doc.getTextRange(s);if(o!==""&&n.getWrapBehavioursEnabled())return h(s,o,"(",")");if(p.isSaneInsertion(n,r))return p.recordAutoInsert(n,r,")"),{text:"()",selection:[1,1]}}else if(i==")"){c(n);var u=n.getCursorPosition(),a=r.doc.getLine(u.row),f=a.substring(u.column,u.column+1);if(f==")"){var l=r.$findOpeningBracket(")",{column:u.column+1,row:u.row});if(l!==null&&p.isAutoInsertedClosing(u,a,i))return p.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="("){c(n);var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u==")")return i.end.column++,i}}),this.add("brackets","insertion",function(e,t,n,r,i){if(i=="["){c(n);var s=n.getSelectionRange(),o=r.doc.getTextRange(s);if(o!==""&&n.getWrapBehavioursEnabled())return h(s,o,"[","]");if(p.isSaneInsertion(n,r))return p.recordAutoInsert(n,r,"]"),{text:"[]",selection:[1,1]}}else if(i=="]"){c(n);var u=n.getCursorPosition(),a=r.doc.getLine(u.row),f=a.substring(u.column,u.column+1);if(f=="]"){var l=r.$findOpeningBracket("]",{column:u.column+1,row:u.row});if(l!==null&&p.isAutoInsertedClosing(u,a,i))return p.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}}),this.add("brackets","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="["){c(n);var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u=="]")return i.end.column++,i}}),this.add("string_dquotes","insertion",function(e,t,n,r,i){if(i=='"'||i=="'"){c(n);var s=i,o=n.getSelectionRange(),u=r.doc.getTextRange(o);if(u!==""&&u!=="'"&&u!='"'&&n.getWrapBehavioursEnabled())return h(o,u,s,s);if(!u){var a=n.getCursorPosition(),f=r.doc.getLine(a.row),l=f.substring(a.column-1,a.column),p=f.substring(a.column,a.column+1),d=r.getTokenAt(a.row,a.column),v=r.getTokenAt(a.row,a.column+1);if(l=="\\"&&d&&/escape/.test(d.type))return null;var m=d&&/string|escape/.test(d.type),g=!v||/string|escape/.test(v.type),y;if(p==s)y=m!==g;else{if(m&&!g)return null;if(m&&g)return null;var b=r.$mode.tokenRe;b.lastIndex=0;var w=b.test(l);b.lastIndex=0;var E=b.test(l);if(w||E)return null;if(p&&!/[\s;,.})\]\\]/.test(p))return null;y=!0}return{text:y?s+s:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&(s=='"'||s=="'")){c(n);var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u==s)return i.end.column++,i}})};p.isSaneInsertion=function(e,t){var n=e.getCursorPosition(),r=new s(t,n.row,n.column);if(!this.$matchTokenType(r.getCurrentToken()||"text",u)){var i=new s(t,n.row,n.column+1);if(!this.$matchTokenType(i.getCurrentToken()||"text",u))return!1}return r.stepForward(),r.getCurrentTokenRow()!==n.row||this.$matchTokenType(r.getCurrentToken()||"text",a)},p.$matchTokenType=function(e,t){return t.indexOf(e.type||e)>-1},p.recordAutoInsert=function(e,t,n){var r=e.getCursorPosition(),i=t.doc.getLine(r.row);this.isAutoInsertedClosing(r,i,f.autoInsertedLineEnd[0])||(f.autoInsertedBrackets=0),f.autoInsertedRow=r.row,f.autoInsertedLineEnd=n+i.substr(r.column),f.autoInsertedBrackets++},p.recordMaybeInsert=function(e,t,n){var r=e.getCursorPosition(),i=t.doc.getLine(r.row);this.isMaybeInsertedClosing(r,i)||(f.maybeInsertedBrackets=0),f.maybeInsertedRow=r.row,f.maybeInsertedLineStart=i.substr(0,r.column)+n,f.maybeInsertedLineEnd=i.substr(r.column),f.maybeInsertedBrackets++},p.isAutoInsertedClosing=function(e,t,n){return f.autoInsertedBrackets>0&&e.row===f.autoInsertedRow&&n===f.autoInsertedLineEnd[0]&&t.substr(e.column)===f.autoInsertedLineEnd},p.isMaybeInsertedClosing=function(e,t){return f.maybeInsertedBrackets>0&&e.row===f.maybeInsertedRow&&t.substr(e.column)===f.maybeInsertedLineEnd&&t.substr(0,e.column)==f.maybeInsertedLineStart},p.popAutoInsertedClosing=function(){f.autoInsertedLineEnd=f.autoInsertedLineEnd.substr(1),f.autoInsertedBrackets--},p.clearMaybeInsertedClosing=function(){f&&(f.maybeInsertedBrackets=0,f.maybeInsertedRow=-1)},r.inherits(p,i),t.CstyleBehaviour=p}),ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(e,t,n){"use strict";var r=e("../../lib/oop"),i=e("../../range").Range,s=e("./fold_mode").FoldMode,o=t.FoldMode=function(e){e&&(this.foldingStartMarker=new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/,"|"+e.start)),this.foldingStopMarker=new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/,"|"+e.end)))};r.inherits(o,s),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.singleLineBlockCommentRe=/^\s*(\/\*).*\*\/\s*$/,this.tripleStarBlockCommentRe=/^\s*(\/\*\*\*).*\*\/\s*$/,this.startRegionRe=/^\s*(\/\*|\/\/)#?region\b/,this._getFoldWidgetBase=this.getFoldWidget,this.getFoldWidget=function(e,t,n){var r=e.getLine(n);if(this.singleLineBlockCommentRe.test(r)&&!this.startRegionRe.test(r)&&!this.tripleStarBlockCommentRe.test(r))return"";var i=this._getFoldWidgetBase(e,t,n);return!i&&this.startRegionRe.test(r)?"start":i},this.getFoldWidgetRange=function(e,t,n,r){var i=e.getLine(n);if(this.startRegionRe.test(i))return this.getCommentRegionBlock(e,i,n);var s=i.match(this.foldingStartMarker);if(s){var o=s.index;if(s[1])return this.openingBracketBlock(e,s[1],n,o);var u=e.getCommentFoldRange(n,o+s[0].length,1);return u&&!u.isMultiLine()&&(r?u=this.getSectionRange(e,n):t!="all"&&(u=null)),u}if(t==="markbegin")return;var s=i.match(this.foldingStopMarker);if(s){var o=s.index+s[0].length;return s[1]?this.closingBracketBlock(e,s[1],n,o):e.getCommentFoldRange(n,o,-1)}},this.getSectionRange=function(e,t){var n=e.getLine(t),r=n.search(/\S/),s=t,o=n.length;t+=1;var u=t,a=e.getLength();while(++t<a){n=e.getLine(t);var f=n.search(/\S/);if(f===-1)continue;if(r>f)break;var l=this.getFoldWidgetRange(e,"all",t);if(l){if(l.start.row<=s)break;if(l.isMultiLine())t=l.end.row;else if(r==f)break}u=t}return new i(s,o,u,e.getLine(u).length)},this.getCommentRegionBlock=function(e,t,n){var r=t.search(/\s*$/),s=e.getLength(),o=n,u=/^\s*(?:\/\*|\/\/|--)#?(end)?region\b/,a=1;while(++n<s){t=e.getLine(n);var f=u.exec(t);if(!f)continue;f[1]?a--:a++;if(!a)break}var l=n;if(l>o)return new i(o,r,l,t.length)}}.call(o.prototype)}),ace.define("ace/mode/lsl",["require","exports","module","ace/mode/lsl_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/text","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle","ace/lib/oop"],function(e,t,n){"use strict";var r=e("./lsl_highlight_rules").LSLHighlightRules,i=e("./matching_brace_outdent").MatchingBraceOutdent,s=e("../range").Range,o=e("./text").Mode,u=e("./behaviour/cstyle").CstyleBehaviour,a=e("./folding/cstyle").FoldMode,f=e("../lib/oop"),l=function(){this.HighlightRules=r,this.$outdent=new i,this.$behaviour=new u,this.foldingRules=new a};f.inherits(l,o),function(){this.lineCommentStart=["//"],this.blockComment={start:"/*",end:"*/"},this.getNextLineIndent=function(e,t,n){var r=this.$getIndent(t),i=this.getTokenizer().getLineTokens(t,e),s=i.tokens,o=i.state;if(s.length&&s[s.length-1].type==="comment.block.lsl")return r;if(e==="start"){var u=t.match(/^.*[\{\(\[]\s*$/);u&&(r+=n)}return r},this.checkOutdent=function(e,t,n){return this.$outdent.checkOutdent(t,n)},this.autoOutdent=function(e,t,n){this.$outdent.autoOutdent(t,n)},this.$id="ace/mode/lsl"}.call(l.prototype),t.Mode=l})
412
0.921304
1
0.921304
game-dev
MEDIA
0.85226
game-dev
0.524107
1
0.524107
jafkc2/KC-Overlay
6,792
src/components/PlayerTable.vue
<template> <div class="table-container" data-tauri-drag-region> <table> <thead> <tr class="head-tr"> <th v-if="loading" class="user-th">Carregando jogadores...</th> <th v-else-if="wait_time > 0" class="user-th">Espere {{ wait_time }} segundos.</th> <th v-else class="user-th">{{ players.length }} jogadores ({{ format_stats(settings) }})</th> <th v-if="settings.show_ws">WS</th> <th v-if="settings.show_wlr">WLR</th> <th v-if="settings.show_fkdr && settings.stats_type.type.includes('Bedwars')">FKDR</th> <th v-else-if="settings.stats_type.type == 'TheBridge'">Pontos</th> <th v-if="settings.show_kdr">KDR</th> <th v-if="settings.show_wins">Vitórias</th> <th v-if="settings.show_losses">Derrotas</th> </tr> </thead> <tbody> <tr v-for="player in players"> <td class="user-td"> <div class="username"> <img :src="'https://mc-heads.net/avatar/' + player.skin_hash" /> <span v-if="player.is_nicked" :style="{ color: nicked_color }">[nicked]</span> <div v-else-if="is_marked(player, settings.marked_players)" :style="{ color: 'rgb(255, 0, 0)'}"> <span class="level">[{{ player.stats.content.level }}</span> <div class="symbol_div"> <span class="symbol">{{ player.stats.content.level_symbol }}</span> </div> <span>]</span> </div> <div v-else :style="{ color: rgb_style(player.stats.content.level_color) }"> <span class="level">[{{ player.stats.content.level }}</span> <div class="symbol_div"> <span class="symbol">{{ player.stats.content.level_symbol }}</span> </div> <span>]</span> </div> <span v-if="is_marked(player, settings.marked_players)" :style="{ color: 'rgb(255, 0, 0)' }">{{ player.username }}</span> <span v-else :style="{ color: rgb_style(player.username_color) }">{{ player.username }}</span> <span v-if="player.clan && is_marked(player, settings.marked_players)" :style="{ color: 'rgb(255, 0, 0)' }">[{{ player.clan }}]</span> <span v-else-if="player.clan" :style="{ color: rgb_style(player.clan_color) }">[{{ player.clan }}]</span> <img v-if="player.is_possible_cheater" src="/radioactive.svg" class="player-indicator" /> <img v-if="player.stats.type == 'Bedwars' && player.stats.content.losses / player.stats.content.final_deaths > 1.5 && player.stats.content.losses / player.stats.content.final_deaths < 2" src="/knife.svg" /> <img v-if="player.stats.type == 'Bedwars' && player.stats.content.losses / player.stats.content.final_deaths > 2" src="/knife2.svg" /> <img v-if="player.is_muted" src="/mute.svg" /> <span v-if="settings.show_bans && player.bans > 0">{{ player.bans }}</span> <img v-if="settings.show_bans && player.bans > 0" src="/hammer.svg" /> </div> </td> <td v-if="settings.show_ws" :style="{ color: get_ws_color(player, settings.marked_players) }" class="stat" :class="{ 'super': player.stats.content.winstreak >= 100 }">{{ player.stats.content.winstreak == 0 ? '-' : player.stats.content.winstreak }}</td> <td v-if="settings.show_wlr" :style="{ color: get_wlr_color(player, settings.marked_players) }" class="stat" :class="{ 'super': player.stats.content.winrate >= 8 }">{{ player.stats.content.winrate.toFixed(2) }}</td> <td v-if="player.stats.type == 'TheBridge'" class="stat">{{ player.stats.content.points }}</td> <td v-if="player.stats.type == 'Bedwars' && settings.show_fkdr" :style="{ color: get_fkdr_color(player, settings.marked_players) }" class="stat" :class="{ 'super': player.stats.content.final_kill_death_ratio >= 50 }">{{ player.stats.content.final_kill_death_ratio.toFixed(2) }}</td> <td v-if="settings.show_kdr" :style="{ color: get_kdr_color(player, settings.marked_players) }" class="stat" :class="{ 'super': player.stats.content.kill_death_ratio >= 4 }">{{ player.stats.content.kill_death_ratio.toFixed(2) }}</td> <td v-if="settings.show_wins" :style="{ color: get_wins_color(player, settings.marked_players) }">{{ player.stats.content.wins }}</td> <td v-if="settings.show_losses" :style="{ color: get_losses_color(player, settings.marked_players) }">{{ player.stats.content.losses }}</td> </tr> </tbody> </table> </div> </template> <script setup lang="ts"> import { listen } from "@tauri-apps/api/event"; import type { Player, Rgb, Settings } from "../types.ts"; import { get_ws_color, get_wlr_color, get_fkdr_color, get_kdr_color, format_stats, get_wins_color, get_losses_color, is_marked } from "../util.ts"; import { ref } from "vue"; function rgb_style(rgb: Rgb): string { return `rgb(${rgb.red}, ${rgb.green}, ${rgb.blue})`; } const nicked_color = "rgb(255, 255, 0)"; let wait_time = ref(0); listen("wait", async (event) => { wait_time.value = event.payload as number; while (wait_time.value > 0) { await new Promise(resolve => setTimeout(resolve, 1000)); wait_time.value -= 1; } }); interface Props { party_players: Player[]; players: Player[]; loading: boolean; settings: Settings; } defineProps<Props>(); </script> <style scoped> .table-container { padding-top: 10px; max-height: 380px; overflow-y: auto; } table { padding-top: 299px; border-collapse: collapse; line-height: 0px; } th { font-size: 13px; } th, td { text-align: center; padding: 0px 6.5px; } .user-td, .user-th { text-align: left; width: 300px; white-space: nowrap; text-overflow: ellipsis; } .head-tr { margin-bottom: 20px; height: 10px; } .username { display: flex; text-align: center; vertical-align: top; align-items: center; } .username img { width: 16px; height: 16px; image-rendering: pixelated; margin-right: 5px; position: relative; top: 40%; transform: translateY(-20%); } .symbol_div { display: inline-block; } .level { margin-right: 0; } .symbol { font-size: 15px; position: relative; bottom: 10px; } span { margin-right: 2px; font-size: 14px; line-height: 1.5; } .player_row { display: flex; line-height: 12px; } </style>
412
0.802318
1
0.802318
game-dev
MEDIA
0.317782
game-dev
0.922453
1
0.922453
LanternPowered/Lantern
7,462
src/main/java/org/lanternpowered/server/world/extent/worker/LanternBlockVolumeWorker.java
/* * This file is part of LanternServer, licensed under the MIT License (MIT). * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.lanternpowered.server.world.extent.worker; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.flowpowered.math.vector.Vector3i; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.world.extent.BlockVolume; import org.spongepowered.api.world.extent.MutableBlockVolume; import org.spongepowered.api.world.extent.UnmodifiableBlockVolume; import org.spongepowered.api.world.extent.worker.BlockVolumeWorker; import org.spongepowered.api.world.extent.worker.procedure.BlockVolumeMapper; import org.spongepowered.api.world.extent.worker.procedure.BlockVolumeMerger; import org.spongepowered.api.world.extent.worker.procedure.BlockVolumeReducer; import org.spongepowered.api.world.extent.worker.procedure.BlockVolumeVisitor; import java.util.function.BiFunction; public class LanternBlockVolumeWorker<V extends BlockVolume> implements BlockVolumeWorker<V> { protected final V volume; public LanternBlockVolumeWorker(V volume) { this.volume = checkNotNull(volume, "volume"); } @Override public V getVolume() { return this.volume; } @Override public void map(BlockVolumeMapper mapper, MutableBlockVolume destination) { final Vector3i offset = align(destination); final int xOffset = offset.getX(); final int yOffset = offset.getY(); final int zOffset = offset.getZ(); final UnmodifiableBlockVolume unmodifiableVolume = this.volume.getUnmodifiableBlockView(); final int xMin = unmodifiableVolume.getBlockMin().getX(); final int yMin = unmodifiableVolume.getBlockMin().getY(); final int zMin = unmodifiableVolume.getBlockMin().getZ(); final int xMax = unmodifiableVolume.getBlockMax().getX(); final int yMax = unmodifiableVolume.getBlockMax().getY(); final int zMax = unmodifiableVolume.getBlockMax().getZ(); for (int z = zMin; z <= zMax; z++) { for (int y = yMin; y <= yMax; y++) { for (int x = xMin; x <= xMax; x++) { final BlockState block = mapper.map(unmodifiableVolume, x, y, z); destination.setBlock(x + xOffset, y + yOffset, z + zOffset, block); } } } } @Override public void merge(BlockVolume second, BlockVolumeMerger merger, MutableBlockVolume destination) { final Vector3i offsetSecond = align(second); final int xOffsetSecond = offsetSecond.getX(); final int yOffsetSecond = offsetSecond.getY(); final int zOffsetSecond = offsetSecond.getZ(); final Vector3i offsetDestination = align(destination); final int xOffsetDestination = offsetDestination.getX(); final int yOffsetDestination = offsetDestination.getY(); final int zOffsetDestination = offsetDestination.getZ(); final UnmodifiableBlockVolume firstUnmodifiableVolume = this.volume.getUnmodifiableBlockView(); final int xMin = firstUnmodifiableVolume.getBlockMin().getX(); final int yMin = firstUnmodifiableVolume.getBlockMin().getY(); final int zMin = firstUnmodifiableVolume.getBlockMin().getZ(); final int xMax = firstUnmodifiableVolume.getBlockMax().getX(); final int yMax = firstUnmodifiableVolume.getBlockMax().getY(); final int zMax = firstUnmodifiableVolume.getBlockMax().getZ(); final UnmodifiableBlockVolume secondUnmodifiableVolume = second.getUnmodifiableBlockView(); for (int z = zMin; z <= zMax; z++) { for (int y = yMin; y <= yMax; y++) { for (int x = xMin; x <= xMax; x++) { final BlockState block = merger.merge(firstUnmodifiableVolume, x, y, z, secondUnmodifiableVolume, x + xOffsetSecond, y + yOffsetSecond, z + zOffsetSecond); destination.setBlock(x + xOffsetDestination, y + yOffsetDestination, z + zOffsetDestination, block); } } } } @Override public void iterate(BlockVolumeVisitor<V> visitor) { final int xMin = this.volume.getBlockMin().getX(); final int yMin = this.volume.getBlockMin().getY(); final int zMin = this.volume.getBlockMin().getZ(); final int xMax = this.volume.getBlockMax().getX(); final int yMax = this.volume.getBlockMax().getY(); final int zMax = this.volume.getBlockMax().getZ(); for (int z = zMin; z <= zMax; z++) { for (int y = yMin; y <= yMax; y++) { for (int x = xMin; x <= xMax; x++) { visitor.visit(this.volume, x, y, z); } } } } @Override public <T> T reduce(BlockVolumeReducer<T> reducer, BiFunction<T, T, T> merge, T identity) { final UnmodifiableBlockVolume unmodifiableVolume = this.volume.getUnmodifiableBlockView(); final int xMin = unmodifiableVolume.getBlockMin().getX(); final int yMin = unmodifiableVolume.getBlockMin().getY(); final int zMin = unmodifiableVolume.getBlockMin().getZ(); final int xMax = unmodifiableVolume.getBlockMax().getX(); final int yMax = unmodifiableVolume.getBlockMax().getY(); final int zMax = unmodifiableVolume.getBlockMax().getZ(); T reduction = identity; for (int z = zMin; z <= zMax; z++) { for (int y = yMin; y <= yMax; y++) { for (int x = xMin; x <= xMax; x++) { reduction = reducer.reduce(unmodifiableVolume, x, y, z, reduction); } } } return reduction; } private Vector3i align(BlockVolume other) { final Vector3i thisSize = this.volume.getBlockSize(); final Vector3i otherSize = other.getBlockSize(); checkArgument(otherSize.getX() >= thisSize.getX() && otherSize.getY() >= thisSize.getY() && otherSize.getY() >= thisSize.getY(), "Other volume is smaller than work volume"); return other.getBlockMin().sub(this.volume.getBlockMin()); } }
412
0.909447
1
0.909447
game-dev
MEDIA
0.619565
game-dev
0.968219
1
0.968219
AlexGyver/RipCalendar
7,543
libraries/pgm_utils/README_EN.md
This is an automatic translation, may be incorrect in some places. See sources and examples! # pgm_utils A set of convenient tools for working with Progmem, C ++ wrapping for standard PGM functions - one function for reading any data - Reading multidimensional arrays - Reading the array of lines ## compatibility Compatible with all arduino platforms (used arduino functions) ## Content - [use] (#usage) - [versions] (#varsions) - [installation] (# Install) - [bugs and feedback] (#fedback) <a id="usage"> </a> ## Usage ### macros and functions `` `CPP // Synonym Constring __flashstringhelper* FSTR // Transform pgm_p to fstr Fpstr (x) // Place the single value of VAL type t in Progmem under the name NAME PGM_VAL (T, NAME, VAL) // Place a single value of VAL type t (class, structure) in Progmem under the name NAME, transfer the list for initialization Pgm_struct (t, name, ...) // Place the string string in Progmem under the name NAME Pgm_str (name, str) // Place the lines in Progmem and in the list of signs under the name NAME Pgm_str_list (name, ...) // Place the lines in Progmem and in the list of signs + create an object Stringlist with the name NAME // Create a Progmem massif NAME_LIST and lines NAME_LIST_0, ... NAME_LIST_N Pgm_str_list_obj (name, ...) // Create an object pgm :: Stringlist with a calculated number of lines Make_str_list (name) // Place an array of type t in progmem under the name NAME Pgm_array (t, name, ...) // Place arrays of type T in the Progmem array of signs under the name NAME Pgm_array_list (t, name, ...) // Create an object pgm :: type T with the calculated array calculated Make_array (t, name) // Create a Progmem Massive type T and an object of class PGM :: Array from it // Create a Progmem massif name_arr Pgm_array_obj (t, name, ...) // Read data of any type T pgm_read (const t* ptr); `` ` ### classes #### `Template <Typename T> PGM :: Array` Reading one -dimensional array `` `CPP Array (const* arr, size_t len ​​= 0); // The length of the array.0 If not indicated during initialization Size_t Length (); // Get a value by index T Operator [] (int IDX); `` ` ### `Template <Typename T> PGM :: ArrayList` Reading an array of array of indicators for arrays `` `CPP Arraylist (const t ** arr, size_t len ​​= 0); // The length of the array.0 If not indicated during initialization Size_t Length (); // Read the array as pgm :: Array by index Array <t> operator [] (int IDX); `` ` ### `pgm :: pstring` Working with Progemem a line `` `CPP Pstring (pgm_p str, size_t len ​​= 0); // Print Size_t Printto (Print & P); // Line length Size_t Length (); // Bring to Char [] VOID TOSTR (Char* BUF); // Bring to String String Tostring (); // compare with the line Bool Compare (Consta Char* str); Bool Operator == (Consta Char* str); // compare with the line Bool Compare (Constation String & STR); Bool Operator == (COST String & STR); // Get like flashstringhelper* Fstr f_str (); // Get a symbol Char Operator [] (int IDX); Operator pgm_p (); Operator FSTR (); Pgm_p pstr; `` ` ### `pgm :: stringlist` Working with an array of array of signs `` `CPP Stringlist (const char ** arr, size_t len ​​= 0); // The length of the array.0 If not indicated during initialization S.Ize_t Length (); // Get a line Pstring Operator [] (int IDX); `` ` ### Note `Pgm_str_list (name," str1 "," str2 "," str3 ")` unfolds in: `` `CPP const char name_0 [] progmem = "str1"; const char name_1 [] progmem = "str2"; const char name_2 [] progmem = "str3"; const char* const name [] = {name_0, name_1, name_2}; `` ` > Maximum number of lines - `128` ### Examples ### values `` `CPP Pgm_val (int, vali, 123); PGM_VAL (FLOAT, VALF, 3.14); Struct test { byte i; Chard [10]; }; Pgm_struct (test, ptest, 10, "test"); VOID FOO () { Serial.println (pgm_read (& vali));// 123 Serial.println (pgm_read (& valf));// 3.14 Test T = pgm_read (& ptest); Serial.println (T.I);// 10 Serial.println (T.str);// test } `` ` ### lines `` `CPP PGM_STR (PGMSTR, "HELLO"); VOID FOO () { PGM :: pstring pstr (pgmstr); Serial.println (pstr);// Hello Serial.println (pstr.length ());// 5 for (int i = 0; i <pstr.length (); i ++) { Serial.print (pstr [i]); } Serial.println (); // When working with String, use f_str ()! // This is the best of all String s = pgmstr.f_str (); s += pgmstr.f_str (); } `` ` ### MASSIVES `` `CPP Pgm_array (byte, pgmarrb, 1, 2, 3);// PGM massif Pgm_array (int, pgmarri, 123, 456, 789);// PGM massif Pgm_array_obj (Float, Arrf, 1.12, 2.34, 3.45);// Array + object PGM :: Array VOID FOO () { // The length is unknown PGM :: Array <Byte> arrb (pgmarrb); Serial.println (arrb [1]);// 2 // length is counted in MAKE PGM :: Array <THet> arri = make_array (int, pgmarri); Serial.println (arri [1]);// 456 Serial.println (arri.length ());// 3 // Ready object Serial.println (arrf [1]);// 2.34 } `` ` #### Arrays of the lines `` `CPP Pgm_str_list (pstrlist, "String 1", "Kek", "Hello"); Pgm_str_list_obj (pstrlist_obj, "str1", "str2", "str3"); VOID FOO () { PGM :: Stringlist List (Pstrlist); // pgm :: stringlist list = make_str_list (pstrlist);// here the length is known Serial.println (list.length ()); Serial.println (list [1]); Serial.println (list [1] .Length ()); Serial.println (list [0] == "string 1"); // str1, str2, str3 for (int i = 0; i <pstrlist_obj.length (); i ++) { Serial.println (pstrlist_obj [i]); } } `` ` <a id="versions"> </a> ## versions - V1.0 <a id="install"> </a> ## Installation - The library can be found by the name ** pgm_utils ** and installed through the library manager in: - Arduino ide - Arduino ide v2 - Platformio - [download the library] (https://github.com/gyverlibs/pgm_utils/archive/refs/heads/main.zip) .Zip archive for manual installation: - unpack and put in * C: \ Program Files (X86) \ Arduino \ Libraries * (Windows X64) - unpack and put in * C: \ Program Files \ Arduino \ Libraries * (Windows X32) - unpack and put in *documents/arduino/libraries/ * - (Arduino id) Automatic installation from. Zip: * sketch/connect the library/add .Zip library ... * and specify downloaded archive - Read more detailed instructions for installing libraries [here] (https://alexgyver.ru/arduino-first/#%D0%A3%D1%81%D1%82%D0%B0%BD%D0%BE%BE%BE%BED0%B2%D0%BA%D0%B0_%D0%B1%D0%B8%D0%B1%D0%BB%D0%B8%D0%BE%D1%82%D0%B5%D0%BA) ### Update - I recommend always updating the library: errors and bugs are corrected in the new versions, as well as optimization and new features are added - through the IDE library manager: find the library how to install and click "update" - Manually: ** remove the folder with the old version **, and then put a new one in its place.“Replacement” cannot be done: sometimes in new versions, files that remain when replacing are deleted and can lead to errors! <a id="feedback"> </a> ## bugs and feedback Create ** Issue ** when you find the bugs, and better immediately write to the mail [alex@alexgyver.ru] (mailto: alex@alexgyver.ru) The library is open for refinement and your ** pull Request ** 'ow! When reporting about bugs or incorrect work of the library, it is necessary to indicate: - The version of the library - What is MK used - SDK version (for ESP) - version of Arduino ide - Is it correctCranberries are built -in examples that use the functions and designs that lead to a bug in your code - what code has been loaded, what work was expected from it and how it works in reality - Ideally, attach the minimum code in which the bug is observed.Not a canvas of a thousand lines, but a minimum code
412
0.643719
1
0.643719
game-dev
MEDIA
0.259909
game-dev
0.735782
1
0.735782
PascalCorpsman/FPC_DOOM
7,442
src/units/p_plats.pas
Unit p_plats; {$MODE ObjFPC}{$H+} Interface Uses ufpc_doom_types, Classes, SysUtils , info_types , p_spec ; Var activeplats: Array[0..MAXPLATS - 1] Of pplat_t; Function EV_DoPlat(line: Pline_t; _type: plattype_e; amount: int): int; Procedure EV_StopPlat(line: Pline_t); Procedure T_PlatRaise(mo: Pmobj_t); Implementation Uses sounds, doomstat , d_mode , i_system, i_timer , m_fixed, m_random , p_setup, p_tick, p_floor , s_sound ; Var AllocatedPlats: Array Of Pplat_t = Nil; Procedure P_RemoveActivePlat(plat: Pplat_t); Var i: int; Begin For i := 0 To MAXPLATS - 1 Do Begin If (plat = activeplats[i]) Then Begin (activeplats[i])^.sector^.specialdata := Nil; P_RemoveThinker(@(activeplats[i])^.thinker); activeplats[i] := Nil; exit; End; End; I_Error('P_RemoveActivePlat: can''t find plat!'); End; // // Move a plat up and down // Procedure T_PlatRaise(mo: Pmobj_t); Var plat: Pplat_t; res: result_e; Begin plat := Pplat_t(mo); Case (plat^.status) Of up: Begin res := T_MovePlane(plat^.sector, plat^.speed, plat^.high, plat^.crush, 0, 1); If (plat^._type = raiseAndChange) Or (plat^._type = raiseToNearestAndChange) Then Begin If ((leveltime And 7) = 0) Then S_StartSound(@plat^.sector^.soundorg, sfx_stnmov); End; If (res = crushed) And ((Not plat^.crush)) Then Begin plat^.count := plat^.wait; plat^.status := down; S_StartSound(@plat^.sector^.soundorg, sfx_pstart); End Else Begin If (res = pastdest) Then Begin plat^.count := plat^.wait; plat^.status := waiting; S_StartSound(@plat^.sector^.soundorg, sfx_pstop); Case (plat^._type) Of blazeDWUS, downWaitUpStay: Begin P_RemoveActivePlat(plat); End; raiseAndChange, raiseToNearestAndChange: Begin // In versions <= v1.2 (at least), platform types besides // downWaitUpStay always remain active. If (gameversion > exe_doom_1_2) Then P_RemoveActivePlat(plat); End; End; End; End; End; down: Begin res := T_MovePlane(plat^.sector, plat^.speed, plat^.low, false, 0, -1); If (res = pastdest) Then Begin plat^.count := plat^.wait; plat^.status := waiting; S_StartSound(@plat^.sector^.soundorg, sfx_pstop); End; End; waiting: Begin plat^.count := plat^.count - 1; If (plat^.count = 0) Then Begin If (plat^.sector^.floorheight = plat^.low) Then plat^.status := up Else plat^.status := down; S_StartSound(@plat^.sector^.soundorg, sfx_pstart); End; End; in_stasis: Begin End; End; End; Procedure P_ActivateInStasis(tag: int); Var i: int; Begin For i := 0 To MAXPLATS - 1 Do Begin If assigned(activeplats[i]) And ((activeplats[i])^.tag = tag) And ((activeplats[i])^.status = in_stasis) Then Begin (activeplats[i])^.status := (activeplats[i])^.oldstatus; (activeplats[i])^.thinker._function.acp1 := @T_PlatRaise; End; End; End; Procedure P_AddActivePlat(plat: Pplat_t); Var i: int; Begin For i := 0 To MAXPLATS - 1 Do Begin If (activeplats[i] = Nil) Then Begin activeplats[i] := plat; exit; End; End; I_Error('P_AddActivePlat: no more plats!'); End; // // Do Platforms // "amount" is only used for SOME platforms. // Function EV_DoPlat(line: Pline_t; _type: plattype_e; amount: int): int; Var rtn: int; plat: Pplat_t; secnum: int; sec: Psector_t; Begin secnum := -1; rtn := 0; // Activate all <type> plats that are in_stasis Case (_type) Of perpetualRaise: Begin P_ActivateInStasis(line^.tag); End; End; secnum := P_FindSectorFromLineTag(line, secnum); While (secnum >= 0) Do Begin sec := @sectors[secnum]; If assigned(sec^.specialdata) Then Begin secnum := P_FindSectorFromLineTag(line, secnum); continue; End; // Find lowest & highest floors around sector rtn := 1; new(plat); setlength(AllocatedPlats, high(AllocatedPlats) + 2); AllocatedPlats[high(AllocatedPlats)] := plat; P_AddThinker(@plat^.thinker); plat^._type := _Type; plat^.sector := sec; plat^.sector^.specialdata := plat; plat^.thinker._Function.acp1 := @T_PlatRaise; plat^.crush := false; plat^.tag := line^.tag; Case (_type) Of raiseToNearestAndChange: Begin plat^.speed := PLATSPEED Div 2; sec^.floorpic := sides[line^.sidenum[0]].sector^.floorpic; plat^.high := P_FindNextHighestFloor(sec, sec^.floorheight); plat^.wait := 0; plat^.status := up; // NO MORE DAMAGE, IF APPLICABLE sec^.special := 0; S_StartSound(@sec^.soundorg, sfx_stnmov); End; raiseAndChange: Begin plat^.speed := PLATSPEED Div 2; sec^.floorpic := sides[line^.sidenum[0]].sector^.floorpic; plat^.high := sec^.floorheight + amount * FRACUNIT; plat^.wait := 0; plat^.status := up; S_StartSound(@sec^.soundorg, sfx_stnmov); End; downWaitUpStay: Begin plat^.speed := PLATSPEED * 4; plat^.low := P_FindLowestFloorSurrounding(sec); If (plat^.low > sec^.floorheight) Then plat^.low := sec^.floorheight; plat^.high := sec^.floorheight; plat^.wait := TICRATE * PLATWAIT; plat^.status := down; S_StartSound(@sec^.soundorg, sfx_pstart); End; blazeDWUS: Begin plat^.speed := PLATSPEED * 8; plat^.low := P_FindLowestFloorSurrounding(sec); If (plat^.low > sec^.floorheight) Then plat^.low := sec^.floorheight; plat^.high := sec^.floorheight; plat^.wait := TICRATE * PLATWAIT; plat^.status := down; S_StartSound(@sec^.soundorg, sfx_pstart); End; perpetualRaise: Begin plat^.speed := PLATSPEED; plat^.low := P_FindLowestFloorSurrounding(sec); If (plat^.low > sec^.floorheight) Then plat^.low := sec^.floorheight; plat^.high := P_FindHighestFloorSurrounding(sec); If (plat^.high < sec^.floorheight) Then plat^.high := sec^.floorheight; plat^.wait := TICRATE * PLATWAIT; plat^.status := plat_e(P_Random() And 1); S_StartSound(@sec^.soundorg, sfx_pstart); End; End; P_AddActivePlat(plat); secnum := P_FindSectorFromLineTag(line, secnum); End; result := rtn; End; Procedure EV_StopPlat(line: Pline_t); Var j: int; Begin For j := 0 To MAXPLATS - 1 Do If assigned(activeplats[j]) And (activeplats[j]^.status <> in_stasis) And (activeplats[j]^.tag = line^.tag) Then Begin activeplats[j]^.oldstatus := activeplats[j]^.status; activeplats[j]^.status := in_stasis; activeplats[j]^.thinker._function.acv := Nil; End; End; Var i: int; Finalization For i := 0 To high(AllocatedPlats) Do Begin Dispose(AllocatedPlats[i]); End; setlength(AllocatedPlats, 0); End.
412
0.659853
1
0.659853
game-dev
MEDIA
0.69987
game-dev
0.992025
1
0.992025
Benedikt05/BetterAltay
1,559
src/pocketmine/block/Pumpkin.php
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\block; use pocketmine\item\Item; use pocketmine\math\Vector3; use pocketmine\Player; class Pumpkin extends Solid{ protected $id = self::PUMPKIN; public function __construct(int $meta = 0){ $this->meta = $meta; } public function getHardness() : float{ return 1; } public function getToolType() : int{ return BlockToolType::TYPE_AXE; } public function getName() : string{ return "Pumpkin"; } public function place(Item $item, Block $blockReplace, Block $blockClicked, int $face, Vector3 $clickVector, Player $player = null) : bool{ if($player instanceof Player){ $this->meta = ((int) $player->getDirection() + 1) % 4; } $this->getLevelNonNull()->setBlock($blockReplace, $this, true, true); return true; } public function getVariantBitmask() : int{ return 0; } }
412
0.84865
1
0.84865
game-dev
MEDIA
0.912444
game-dev
0.888678
1
0.888678
GeyserMC/MCProtocolLib
3,592
protocol/src/main/java/org/geysermc/mcprotocollib/protocol/packet/ingame/clientbound/level/ClientboundMapItemDataPacket.java
package org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.level; import io.netty.buffer.ByteBuf; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NonNull; import lombok.With; import net.kyori.adventure.text.Component; import org.geysermc.mcprotocollib.protocol.codec.MinecraftPacket; import org.geysermc.mcprotocollib.protocol.codec.MinecraftTypes; import org.geysermc.mcprotocollib.protocol.data.game.level.map.MapData; import org.geysermc.mcprotocollib.protocol.data.game.level.map.MapIcon; import org.geysermc.mcprotocollib.protocol.data.game.level.map.MapIconType; @Data @With @AllArgsConstructor public class ClientboundMapItemDataPacket implements MinecraftPacket { private final int mapId; private final byte scale; private final boolean locked; private final @NonNull MapIcon[] icons; private final MapData data; public ClientboundMapItemDataPacket(int mapId, byte scale, boolean locked, @NonNull MapIcon[] icons) { this(mapId, scale, locked, icons, null); } public ClientboundMapItemDataPacket(ByteBuf in) { this.mapId = MinecraftTypes.readVarInt(in); this.scale = in.readByte(); this.locked = in.readBoolean(); boolean hasIcons = in.readBoolean(); this.icons = new MapIcon[hasIcons ? MinecraftTypes.readVarInt(in) : 0]; if (hasIcons) { for (int index = 0; index < this.icons.length; index++) { int type = MinecraftTypes.readVarInt(in); int x = in.readByte(); int z = in.readByte(); int rotation = in.readByte(); Component displayName = MinecraftTypes.readNullable(in, MinecraftTypes::readComponent); this.icons[index] = new MapIcon(x, z, MapIconType.from(type), rotation, displayName); } } int columns = in.readUnsignedByte(); if (columns > 0) { int rows = in.readUnsignedByte(); int x = in.readUnsignedByte(); int y = in.readUnsignedByte(); byte[] data = MinecraftTypes.readByteArray(in); this.data = new MapData(columns, rows, x, y, data); } else { this.data = null; } } @Override public void serialize(ByteBuf out) { MinecraftTypes.writeVarInt(out, this.mapId); out.writeByte(this.scale); out.writeBoolean(this.locked); if (this.icons.length != 0) { out.writeBoolean(true); MinecraftTypes.writeVarInt(out, this.icons.length); for (MapIcon icon : this.icons) { int type = icon.getIconType().ordinal(); MinecraftTypes.writeVarInt(out, type); out.writeByte(icon.getCenterX()); out.writeByte(icon.getCenterZ()); out.writeByte(icon.getIconRotation()); MinecraftTypes.writeNullable(out, icon.getDisplayName(), MinecraftTypes::writeComponent); } } else { out.writeBoolean(false); } if (this.data != null && this.data.getColumns() != 0) { out.writeByte(this.data.getColumns()); out.writeByte(this.data.getRows()); out.writeByte(this.data.getX()); out.writeByte(this.data.getY()); MinecraftTypes.writeVarInt(out, this.data.getData().length); out.writeBytes(this.data.getData()); } else { out.writeByte(0); } } @Override public boolean shouldRunOnGameThread() { return true; } }
412
0.709145
1
0.709145
game-dev
MEDIA
0.922293
game-dev,networking
0.897931
1
0.897931
paulcwarren/spring-content
1,412
spring-content-encryption/src/main/java/internal/org/springframework/content/fragments/DecryptedResource.java
package internal.org.springframework.content.fragments; import java.io.IOException; import java.io.InputStream; import org.springframework.core.io.AbstractResource; import org.springframework.core.io.InputStreamSource; import org.springframework.core.io.Resource; /** * A resource that will be decrypted on-demand */ class DecryptedResource extends AbstractResource { private final InputStreamSource decryptedInputStreamSource; private final Resource originalResource; DecryptedResource(InputStreamSource decryptedInputStreamSource, Resource originalResource) { this.decryptedInputStreamSource = decryptedInputStreamSource; this.originalResource = originalResource; } @Override public InputStream getInputStream() throws IOException { return decryptedInputStreamSource.getInputStream(); } @Override public boolean exists() { return originalResource.exists(); } @Override public long contentLength() throws IOException { return originalResource.contentLength(); } @Override public long lastModified() throws IOException { return originalResource.lastModified(); } @Override public String getFilename() { return originalResource.getFilename(); } @Override public String getDescription() { return "Decrypted " + originalResource.getDescription(); } }
412
0.67806
1
0.67806
game-dev
MEDIA
0.15438
game-dev
0.790533
1
0.790533
kopaka1822/ImageViewer
1,987
ImageConsole/Commands/Filter/FilterParameterCommand.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ImageFramework.Model; using ImageFramework.Model.Filter.Parameter; namespace ImageConsole.Commands.Filter { public class FilterParameterCommand : Command { public FilterParameterCommand() : base("-filterparam", "index \"param name\" value", "sets the parameter of the filter at index") { } public override void Execute(List<string> arguments, Models model) { var reader = new ParameterReader(arguments); var idx = reader.ReadInt("index"); var name = reader.ReadString("param name"); foreach (var fp in model.Filter.Filter[idx].Parameters) { if (fp.GetBase().Name == name) { switch (fp.GetParamterType()) { case ParameterType.Float: fp.GetFloatModel().Value = reader.ReadFloat("value"); break; case ParameterType.Int: case ParameterType.Enum: fp.GetIntModel().Value = reader.ReadInt("value"); break; case ParameterType.Bool: fp.GetBoolModel().Value = reader.ReadBool("value"); break; } reader.ExpectNoMoreArgs(); return; } } foreach (var tp in model.Filter.Filter[idx].TextureParameters) { if (tp.Name == name) { tp.Source = reader.ReadInt("value"); reader.ExpectNoMoreArgs(); return; } } throw new Exception($"parameter {name} not found"); } } }
412
0.933307
1
0.933307
game-dev
MEDIA
0.810757
game-dev
0.926179
1
0.926179
kbengine/kbengine
30,844
kbe/src/lib/navigation/DetourNavMesh.h
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.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. // #ifndef DETOURNAVMESH_H #define DETOURNAVMESH_H #include "DetourAlloc.h" #include "DetourStatus.h" // Undefine (or define in a build cofnig) the following line to use 64bit polyref. // Generally not needed, useful for very large worlds. // Note: tiles build using 32bit refs are not compatible with 64bit refs! //#define DT_POLYREF64 1 #ifdef DT_POLYREF64 // TODO: figure out a multiplatform version of uint64_t // - maybe: https://code.google.com/p/msinttypes/ // - or: http://www.azillionmonkeys.com/qed/pstdint.h #include <stdint.h> #endif // Note: If you want to use 64-bit refs, change the types of both dtPolyRef & dtTileRef. // It is also recommended that you change dtHashRef() to a proper 64-bit hash. /// A handle to a polygon within a navigation mesh tile. /// @ingroup detour #ifdef DT_POLYREF64 static const unsigned int DT_SALT_BITS = 16; static const unsigned int DT_TILE_BITS = 28; static const unsigned int DT_POLY_BITS = 20; typedef uint64_t dtPolyRef; #else typedef unsigned int dtPolyRef; #endif /// A handle to a tile within a navigation mesh. /// @ingroup detour #ifdef DT_POLYREF64 typedef uint64_t dtTileRef; #else typedef unsigned int dtTileRef; #endif /// The maximum number of vertices per navigation polygon. /// @ingroup detour static const int DT_VERTS_PER_POLYGON = 6; /// @{ /// @name Tile Serialization Constants /// These constants are used to detect whether a navigation tile's data /// and state format is compatible with the current build. /// /// A magic number used to detect compatibility of navigation tile data. static const int DT_NAVMESH_MAGIC = 'D'<<24 | 'N'<<16 | 'A'<<8 | 'V'; /// A version number used to detect compatibility of navigation tile data. static const int DT_NAVMESH_VERSION = 7; /// A magic number used to detect the compatibility of navigation tile states. static const int DT_NAVMESH_STATE_MAGIC = 'D'<<24 | 'N'<<16 | 'M'<<8 | 'S'; /// A version number used to detect compatibility of navigation tile states. static const int DT_NAVMESH_STATE_VERSION = 1; /// @} /// A flag that indicates that an entity links to an external entity. /// (E.g. A polygon edge is a portal that links to another polygon.) static const unsigned short DT_EXT_LINK = 0x8000; /// A value that indicates the entity does not link to anything. static const unsigned int DT_NULL_LINK = 0xffffffff; /// A flag that indicates that an off-mesh connection can be traversed in both directions. (Is bidirectional.) static const unsigned int DT_OFFMESH_CON_BIDIR = 1; /// The maximum number of user defined area ids. /// @ingroup detour static const int DT_MAX_AREAS = 64; /// Tile flags used for various functions and fields. /// For an example, see dtNavMesh::addTile(). enum dtTileFlags { /// The navigation mesh owns the tile memory and is responsible for freeing it. DT_TILE_FREE_DATA = 0x01, }; /// Vertex flags returned by dtNavMeshQuery::findStraightPath. enum dtStraightPathFlags { DT_STRAIGHTPATH_START = 0x01, ///< The vertex is the start position in the path. DT_STRAIGHTPATH_END = 0x02, ///< The vertex is the end position in the path. DT_STRAIGHTPATH_OFFMESH_CONNECTION = 0x04, ///< The vertex is the start of an off-mesh connection. }; /// Options for dtNavMeshQuery::findStraightPath. enum dtStraightPathOptions { DT_STRAIGHTPATH_AREA_CROSSINGS = 0x01, ///< Add a vertex at every polygon edge crossing where area changes. DT_STRAIGHTPATH_ALL_CROSSINGS = 0x02, ///< Add a vertex at every polygon edge crossing. }; /// Options for dtNavMeshQuery::initSlicedFindPath and updateSlicedFindPath enum dtFindPathOptions { DT_FINDPATH_ANY_ANGLE = 0x02, ///< use raycasts during pathfind to "shortcut" (raycast still consider costs) }; /// Options for dtNavMeshQuery::raycast enum dtRaycastOptions { DT_RAYCAST_USE_COSTS = 0x01, ///< Raycast should calculate movement cost along the ray and fill RaycastHit::cost }; /// Limit raycasting during any angle pahfinding /// The limit is given as a multiple of the character radius static const float DT_RAY_CAST_LIMIT_PROPORTIONS = 50.0f; /// Flags representing the type of a navigation mesh polygon. enum dtPolyTypes { /// The polygon is a standard convex polygon that is part of the surface of the mesh. DT_POLYTYPE_GROUND = 0, /// The polygon is an off-mesh connection consisting of two vertices. DT_POLYTYPE_OFFMESH_CONNECTION = 1, }; /// Defines a polygon within a dtMeshTile object. /// @ingroup detour struct dtPoly { /// Index to first link in linked list. (Or #DT_NULL_LINK if there is no link.) unsigned int firstLink; /// The indices of the polygon's vertices. /// The actual vertices are located in dtMeshTile::verts. unsigned short verts[DT_VERTS_PER_POLYGON]; /// Packed data representing neighbor polygons references and flags for each edge. unsigned short neis[DT_VERTS_PER_POLYGON]; /// The user defined polygon flags. unsigned short flags; /// The number of vertices in the polygon. unsigned char vertCount; /// The bit packed area id and polygon type. /// @note Use the structure's set and get methods to acess this value. unsigned char areaAndtype; /// Sets the user defined area id. [Limit: < #DT_MAX_AREAS] inline void setArea(unsigned char a) { areaAndtype = (areaAndtype & 0xc0) | (a & 0x3f); } /// Sets the polygon type. (See: #dtPolyTypes.) inline void setType(unsigned char t) { areaAndtype = (areaAndtype & 0x3f) | (t << 6); } /// Gets the user defined area id. inline unsigned char getArea() const { return areaAndtype & 0x3f; } /// Gets the polygon type. (See: #dtPolyTypes) inline unsigned char getType() const { return areaAndtype >> 6; } }; /// Defines the location of detail sub-mesh data within a dtMeshTile. struct dtPolyDetail { unsigned int vertBase; ///< The offset of the vertices in the dtMeshTile::detailVerts array. unsigned int triBase; ///< The offset of the triangles in the dtMeshTile::detailTris array. unsigned char vertCount; ///< The number of vertices in the sub-mesh. unsigned char triCount; ///< The number of triangles in the sub-mesh. }; /// Defines a link between polygons. /// @note This structure is rarely if ever used by the end user. /// @see dtMeshTile struct dtLink { dtPolyRef ref; ///< Neighbour reference. (The neighbor that is linked to.) unsigned int next; ///< Index of the next link. unsigned char edge; ///< Index of the polygon edge that owns this link. unsigned char side; ///< If a boundary link, defines on which side the link is. unsigned char bmin; ///< If a boundary link, defines the minimum sub-edge area. unsigned char bmax; ///< If a boundary link, defines the maximum sub-edge area. }; /// Bounding volume node. /// @note This structure is rarely if ever used by the end user. /// @see dtMeshTile struct dtBVNode { unsigned short bmin[3]; ///< Minimum bounds of the node's AABB. [(x, y, z)] unsigned short bmax[3]; ///< Maximum bounds of the node's AABB. [(x, y, z)] int i; ///< The node's index. (Negative for escape sequence.) }; /// Defines an navigation mesh off-mesh connection within a dtMeshTile object. /// An off-mesh connection is a user defined traversable connection made up to two vertices. struct dtOffMeshConnection { /// The endpoints of the connection. [(ax, ay, az, bx, by, bz)] float pos[6]; /// The radius of the endpoints. [Limit: >= 0] float rad; /// The polygon reference of the connection within the tile. unsigned short poly; /// Link flags. /// @note These are not the connection's user defined flags. Those are assigned via the /// connection's dtPoly definition. These are link flags used for internal purposes. unsigned char flags; /// End point side. unsigned char side; /// The id of the offmesh connection. (User assigned when the navigation mesh is built.) unsigned int userId; }; /// Provides high level information related to a dtMeshTile object. /// @ingroup detour struct dtMeshHeader { int magic; ///< Tile magic number. (Used to identify the data format.) int version; ///< Tile data format version number. int x; ///< The x-position of the tile within the dtNavMesh tile grid. (x, y, layer) int y; ///< The y-position of the tile within the dtNavMesh tile grid. (x, y, layer) int layer; ///< The layer of the tile within the dtNavMesh tile grid. (x, y, layer) unsigned int userId; ///< The user defined id of the tile. int polyCount; ///< The number of polygons in the tile. int vertCount; ///< The number of vertices in the tile. int maxLinkCount; ///< The number of allocated links. int detailMeshCount; ///< The number of sub-meshes in the detail mesh. /// The number of unique vertices in the detail mesh. (In addition to the polygon vertices.) int detailVertCount; int detailTriCount; ///< The number of triangles in the detail mesh. int bvNodeCount; ///< The number of bounding volume nodes. (Zero if bounding volumes are disabled.) int offMeshConCount; ///< The number of off-mesh connections. int offMeshBase; ///< The index of the first polygon which is an off-mesh connection. float walkableHeight; ///< The height of the agents using the tile. float walkableRadius; ///< The radius of the agents using the tile. float walkableClimb; ///< The maximum climb height of the agents using the tile. float bmin[3]; ///< The minimum bounds of the tile's AABB. [(x, y, z)] float bmax[3]; ///< The maximum bounds of the tile's AABB. [(x, y, z)] /// The bounding volume quantization factor. float bvQuantFactor; }; /// Defines a navigation mesh tile. /// @ingroup detour struct dtMeshTile { unsigned int salt; ///< Counter describing modifications to the tile. unsigned int linksFreeList; ///< Index to the next free link. dtMeshHeader* header; ///< The tile header. dtPoly* polys; ///< The tile polygons. [Size: dtMeshHeader::polyCount] float* verts; ///< The tile vertices. [Size: dtMeshHeader::vertCount] dtLink* links; ///< The tile links. [Size: dtMeshHeader::maxLinkCount] dtPolyDetail* detailMeshes; ///< The tile's detail sub-meshes. [Size: dtMeshHeader::detailMeshCount] /// The detail mesh's unique vertices. [(x, y, z) * dtMeshHeader::detailVertCount] float* detailVerts; /// The detail mesh's triangles. [(vertA, vertB, vertC) * dtMeshHeader::detailTriCount] unsigned char* detailTris; /// The tile bounding volume nodes. [Size: dtMeshHeader::bvNodeCount] /// (Will be null if bounding volumes are disabled.) dtBVNode* bvTree; dtOffMeshConnection* offMeshCons; ///< The tile off-mesh connections. [Size: dtMeshHeader::offMeshConCount] unsigned char* data; ///< The tile data. (Not directly accessed under normal situations.) int dataSize; ///< Size of the tile data. int flags; ///< Tile flags. (See: #dtTileFlags) dtMeshTile* next; ///< The next free tile, or the next tile in the spatial grid. private: dtMeshTile(const dtMeshTile&); dtMeshTile& operator=(const dtMeshTile&); }; /// Configuration parameters used to define multi-tile navigation meshes. /// The values are used to allocate space during the initialization of a navigation mesh. /// @see dtNavMesh::init() /// @ingroup detour struct dtNavMeshParams { float orig[3]; ///< The world space origin of the navigation mesh's tile space. [(x, y, z)] float tileWidth; ///< The width of each tile. (Along the x-axis.) float tileHeight; ///< The height of each tile. (Along the z-axis.) int maxTiles; ///< The maximum number of tiles the navigation mesh can contain. int maxPolys; ///< The maximum number of polygons each tile can contain. }; /// A navigation mesh based on tiles of convex polygons. /// @ingroup detour class dtNavMesh { public: dtNavMesh(); ~dtNavMesh(); /// @{ /// @name Initialization and Tile Management /// Initializes the navigation mesh for tiled use. /// @param[in] params Initialization parameters. /// @return The status flags for the operation. dtStatus init(const dtNavMeshParams* params); /// Initializes the navigation mesh for single tile use. /// @param[in] data Data of the new tile. (See: #dtCreateNavMeshData) /// @param[in] dataSize The data size of the new tile. /// @param[in] flags The tile flags. (See: #dtTileFlags) /// @return The status flags for the operation. /// @see dtCreateNavMeshData dtStatus init(unsigned char* data, const int dataSize, const int flags); /// The navigation mesh initialization params. const dtNavMeshParams* getParams() const; /// Adds a tile to the navigation mesh. /// @param[in] data Data for the new tile mesh. (See: #dtCreateNavMeshData) /// @param[in] dataSize Data size of the new tile mesh. /// @param[in] flags Tile flags. (See: #dtTileFlags) /// @param[in] lastRef The desired reference for the tile. (When reloading a tile.) [opt] [Default: 0] /// @param[out] result The tile reference. (If the tile was succesfully added.) [opt] /// @return The status flags for the operation. dtStatus addTile(unsigned char* data, int dataSize, int flags, dtTileRef lastRef, dtTileRef* result); /// Removes the specified tile from the navigation mesh. /// @param[in] ref The reference of the tile to remove. /// @param[out] data Data associated with deleted tile. /// @param[out] dataSize Size of the data associated with deleted tile. /// @return The status flags for the operation. dtStatus removeTile(dtTileRef ref, unsigned char** data, int* dataSize); /// @} /// @{ /// @name Query Functions /// Calculates the tile grid location for the specified world position. /// @param[in] pos The world position for the query. [(x, y, z)] /// @param[out] tx The tile's x-location. (x, y) /// @param[out] ty The tile's y-location. (x, y) void calcTileLoc(const float* pos, int* tx, int* ty) const; /// Gets the tile at the specified grid location. /// @param[in] x The tile's x-location. (x, y, layer) /// @param[in] y The tile's y-location. (x, y, layer) /// @param[in] layer The tile's layer. (x, y, layer) /// @return The tile, or null if the tile does not exist. const dtMeshTile* getTileAt(const int x, const int y, const int layer) const; /// Gets all tiles at the specified grid location. (All layers.) /// @param[in] x The tile's x-location. (x, y) /// @param[in] y The tile's y-location. (x, y) /// @param[out] tiles A pointer to an array of tiles that will hold the result. /// @param[in] maxTiles The maximum tiles the tiles parameter can hold. /// @return The number of tiles returned in the tiles array. int getTilesAt(const int x, const int y, dtMeshTile const** tiles, const int maxTiles) const; /// Gets the tile reference for the tile at specified grid location. /// @param[in] x The tile's x-location. (x, y, layer) /// @param[in] y The tile's y-location. (x, y, layer) /// @param[in] layer The tile's layer. (x, y, layer) /// @return The tile reference of the tile, or 0 if there is none. dtTileRef getTileRefAt(int x, int y, int layer) const; /// Gets the tile reference for the specified tile. /// @param[in] tile The tile. /// @return The tile reference of the tile. dtTileRef getTileRef(const dtMeshTile* tile) const; /// Gets the tile for the specified tile reference. /// @param[in] ref The tile reference of the tile to retrieve. /// @return The tile for the specified reference, or null if the /// reference is invalid. const dtMeshTile* getTileByRef(dtTileRef ref) const; /// The maximum number of tiles supported by the navigation mesh. /// @return The maximum number of tiles supported by the navigation mesh. int getMaxTiles() const; /// Gets the tile at the specified index. /// @param[in] i The tile index. [Limit: 0 >= index < #getMaxTiles()] /// @return The tile at the specified index. const dtMeshTile* getTile(int i) const; /// Gets the tile and polygon for the specified polygon reference. /// @param[in] ref The reference for the a polygon. /// @param[out] tile The tile containing the polygon. /// @param[out] poly The polygon. /// @return The status flags for the operation. dtStatus getTileAndPolyByRef(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const; /// Returns the tile and polygon for the specified polygon reference. /// @param[in] ref A known valid reference for a polygon. /// @param[out] tile The tile containing the polygon. /// @param[out] poly The polygon. void getTileAndPolyByRefUnsafe(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const; /// Checks the validity of a polygon reference. /// @param[in] ref The polygon reference to check. /// @return True if polygon reference is valid for the navigation mesh. bool isValidPolyRef(dtPolyRef ref) const; /// Gets the polygon reference for the tile's base polygon. /// @param[in] tile The tile. /// @return The polygon reference for the base polygon in the specified tile. dtPolyRef getPolyRefBase(const dtMeshTile* tile) const; /// Gets the endpoints for an off-mesh connection, ordered by "direction of travel". /// @param[in] prevRef The reference of the polygon before the connection. /// @param[in] polyRef The reference of the off-mesh connection polygon. /// @param[out] startPos The start position of the off-mesh connection. [(x, y, z)] /// @param[out] endPos The end position of the off-mesh connection. [(x, y, z)] /// @return The status flags for the operation. dtStatus getOffMeshConnectionPolyEndPoints(dtPolyRef prevRef, dtPolyRef polyRef, float* startPos, float* endPos) const; /// Gets the specified off-mesh connection. /// @param[in] ref The polygon reference of the off-mesh connection. /// @return The specified off-mesh connection, or null if the polygon reference is not valid. const dtOffMeshConnection* getOffMeshConnectionByRef(dtPolyRef ref) const; /// @} /// @{ /// @name State Management /// These functions do not effect #dtTileRef or #dtPolyRef's. /// Sets the user defined flags for the specified polygon. /// @param[in] ref The polygon reference. /// @param[in] flags The new flags for the polygon. /// @return The status flags for the operation. dtStatus setPolyFlags(dtPolyRef ref, unsigned short flags); /// Gets the user defined flags for the specified polygon. /// @param[in] ref The polygon reference. /// @param[out] resultFlags The polygon flags. /// @return The status flags for the operation. dtStatus getPolyFlags(dtPolyRef ref, unsigned short* resultFlags) const; /// Sets the user defined area for the specified polygon. /// @param[in] ref The polygon reference. /// @param[in] area The new area id for the polygon. [Limit: < #DT_MAX_AREAS] /// @return The status flags for the operation. dtStatus setPolyArea(dtPolyRef ref, unsigned char area); /// Gets the user defined area for the specified polygon. /// @param[in] ref The polygon reference. /// @param[out] resultArea The area id for the polygon. /// @return The status flags for the operation. dtStatus getPolyArea(dtPolyRef ref, unsigned char* resultArea) const; /// Gets the size of the buffer required by #storeTileState to store the specified tile's state. /// @param[in] tile The tile. /// @return The size of the buffer required to store the state. int getTileStateSize(const dtMeshTile* tile) const; /// Stores the non-structural state of the tile in the specified buffer. (Flags, area ids, etc.) /// @param[in] tile The tile. /// @param[out] data The buffer to store the tile's state in. /// @param[in] maxDataSize The size of the data buffer. [Limit: >= #getTileStateSize] /// @return The status flags for the operation. dtStatus storeTileState(const dtMeshTile* tile, unsigned char* data, const int maxDataSize) const; /// Restores the state of the tile. /// @param[in] tile The tile. /// @param[in] data The new state. (Obtained from #storeTileState.) /// @param[in] maxDataSize The size of the state within the data buffer. /// @return The status flags for the operation. dtStatus restoreTileState(dtMeshTile* tile, const unsigned char* data, const int maxDataSize); /// @} /// @{ /// @name Encoding and Decoding /// These functions are generally meant for internal use only. /// Derives a standard polygon reference. /// @note This function is generally meant for internal use only. /// @param[in] salt The tile's salt value. /// @param[in] it The index of the tile. /// @param[in] ip The index of the polygon within the tile. inline dtPolyRef encodePolyId(unsigned int salt, unsigned int it, unsigned int ip) const { #ifdef DT_POLYREF64 return ((dtPolyRef)salt << (DT_POLY_BITS+DT_TILE_BITS)) | ((dtPolyRef)it << DT_POLY_BITS) | (dtPolyRef)ip; #else return ((dtPolyRef)salt << (m_polyBits+m_tileBits)) | ((dtPolyRef)it << m_polyBits) | (dtPolyRef)ip; #endif } /// Decodes a standard polygon reference. /// @note This function is generally meant for internal use only. /// @param[in] ref The polygon reference to decode. /// @param[out] salt The tile's salt value. /// @param[out] it The index of the tile. /// @param[out] ip The index of the polygon within the tile. /// @see #encodePolyId inline void decodePolyId(dtPolyRef ref, unsigned int& salt, unsigned int& it, unsigned int& ip) const { #ifdef DT_POLYREF64 const dtPolyRef saltMask = ((dtPolyRef)1<<DT_SALT_BITS)-1; const dtPolyRef tileMask = ((dtPolyRef)1<<DT_TILE_BITS)-1; const dtPolyRef polyMask = ((dtPolyRef)1<<DT_POLY_BITS)-1; salt = (unsigned int)((ref >> (DT_POLY_BITS+DT_TILE_BITS)) & saltMask); it = (unsigned int)((ref >> DT_POLY_BITS) & tileMask); ip = (unsigned int)(ref & polyMask); #else const dtPolyRef saltMask = ((dtPolyRef)1<<m_saltBits)-1; const dtPolyRef tileMask = ((dtPolyRef)1<<m_tileBits)-1; const dtPolyRef polyMask = ((dtPolyRef)1<<m_polyBits)-1; salt = (unsigned int)((ref >> (m_polyBits+m_tileBits)) & saltMask); it = (unsigned int)((ref >> m_polyBits) & tileMask); ip = (unsigned int)(ref & polyMask); #endif } /// Extracts a tile's salt value from the specified polygon reference. /// @note This function is generally meant for internal use only. /// @param[in] ref The polygon reference. /// @see #encodePolyId inline unsigned int decodePolyIdSalt(dtPolyRef ref) const { #ifdef DT_POLYREF64 const dtPolyRef saltMask = ((dtPolyRef)1<<DT_SALT_BITS)-1; return (unsigned int)((ref >> (DT_POLY_BITS+DT_TILE_BITS)) & saltMask); #else const dtPolyRef saltMask = ((dtPolyRef)1<<m_saltBits)-1; return (unsigned int)((ref >> (m_polyBits+m_tileBits)) & saltMask); #endif } /// Extracts the tile's index from the specified polygon reference. /// @note This function is generally meant for internal use only. /// @param[in] ref The polygon reference. /// @see #encodePolyId inline unsigned int decodePolyIdTile(dtPolyRef ref) const { #ifdef DT_POLYREF64 const dtPolyRef tileMask = ((dtPolyRef)1<<DT_TILE_BITS)-1; return (unsigned int)((ref >> DT_POLY_BITS) & tileMask); #else const dtPolyRef tileMask = ((dtPolyRef)1<<m_tileBits)-1; return (unsigned int)((ref >> m_polyBits) & tileMask); #endif } /// Extracts the polygon's index (within its tile) from the specified polygon reference. /// @note This function is generally meant for internal use only. /// @param[in] ref The polygon reference. /// @see #encodePolyId inline unsigned int decodePolyIdPoly(dtPolyRef ref) const { #ifdef DT_POLYREF64 const dtPolyRef polyMask = ((dtPolyRef)1<<DT_POLY_BITS)-1; return (unsigned int)(ref & polyMask); #else const dtPolyRef polyMask = ((dtPolyRef)1<<m_polyBits)-1; return (unsigned int)(ref & polyMask); #endif } /// @} private: // Explicitly disabled copy constructor and copy assignment operator. dtNavMesh(const dtNavMesh&); dtNavMesh& operator=(const dtNavMesh&); /// Returns pointer to tile in the tile array. dtMeshTile* getTile(int i); /// Returns neighbour tile based on side. int getTilesAt(const int x, const int y, dtMeshTile** tiles, const int maxTiles) const; /// Returns neighbour tile based on side. int getNeighbourTilesAt(const int x, const int y, const int side, dtMeshTile** tiles, const int maxTiles) const; /// Returns all polygons in neighbour tile based on portal defined by the segment. int findConnectingPolys(const float* va, const float* vb, const dtMeshTile* tile, int side, dtPolyRef* con, float* conarea, int maxcon) const; /// Builds internal polygons links for a tile. void connectIntLinks(dtMeshTile* tile); /// Builds internal polygons links for a tile. void baseOffMeshLinks(dtMeshTile* tile); /// Builds external polygon links for a tile. void connectExtLinks(dtMeshTile* tile, dtMeshTile* target, int side); /// Builds external polygon links for a tile. void connectExtOffMeshLinks(dtMeshTile* tile, dtMeshTile* target, int side); /// Removes external links at specified side. void unconnectLinks(dtMeshTile* tile, dtMeshTile* target); // TODO: These methods are duplicates from dtNavMeshQuery, but are needed for off-mesh connection finding. /// Queries polygons within a tile. int queryPolygonsInTile(const dtMeshTile* tile, const float* qmin, const float* qmax, dtPolyRef* polys, const int maxPolys) const; /// Find nearest polygon within a tile. dtPolyRef findNearestPolyInTile(const dtMeshTile* tile, const float* center, const float* halfExtents, float* nearestPt) const; /// Returns closest point on polygon. void closestPointOnPoly(dtPolyRef ref, const float* pos, float* closest, bool* posOverPoly) const; dtNavMeshParams m_params; ///< Current initialization params. TODO: do not store this info twice. float m_orig[3]; ///< Origin of the tile (0,0) float m_tileWidth, m_tileHeight; ///< Dimensions of each tile. int m_maxTiles; ///< Max number of tiles. int m_tileLutSize; ///< Tile hash lookup size (must be pot). int m_tileLutMask; ///< Tile hash lookup mask. dtMeshTile** m_posLookup; ///< Tile hash lookup. dtMeshTile* m_nextFree; ///< Freelist of tiles. dtMeshTile* m_tiles; ///< List of tiles. #ifndef DT_POLYREF64 unsigned int m_saltBits; ///< Number of salt bits in the tile ID. unsigned int m_tileBits; ///< Number of tile bits in the tile ID. unsigned int m_polyBits; ///< Number of poly bits in the tile ID. #endif }; /// Allocates a navigation mesh object using the Detour allocator. /// @return A navigation mesh that is ready for initialization, or null on failure. /// @ingroup detour dtNavMesh* dtAllocNavMesh(); /// Frees the specified navigation mesh object using the Detour allocator. /// @param[in] navmesh A navigation mesh allocated using #dtAllocNavMesh /// @ingroup detour void dtFreeNavMesh(dtNavMesh* navmesh); #endif // DETOURNAVMESH_H /////////////////////////////////////////////////////////////////////////// // This section contains detailed documentation for members that don't have // a source file. It reduces clutter in the main section of the header. /** @typedef dtPolyRef @par Polygon references are subject to the same invalidate/preserve/restore rules that apply to #dtTileRef's. If the #dtTileRef for the polygon's tile changes, the polygon reference becomes invalid. Changing a polygon's flags, area id, etc. does not impact its polygon reference. @typedef dtTileRef @par The following changes will invalidate a tile reference: - The referenced tile has been removed from the navigation mesh. - The navigation mesh has been initialized using a different set of #dtNavMeshParams. A tile reference is preserved/restored if the tile is added to a navigation mesh initialized with the original #dtNavMeshParams and is added at the original reference location. (E.g. The lastRef parameter is used with dtNavMesh::addTile.) Basically, if the storage structure of a tile changes, its associated tile reference changes. @var unsigned short dtPoly::neis[DT_VERTS_PER_POLYGON] @par Each entry represents data for the edge starting at the vertex of the same index. E.g. The entry at index n represents the edge data for vertex[n] to vertex[n+1]. A value of zero indicates the edge has no polygon connection. (It makes up the border of the navigation mesh.) The information can be extracted as follows: @code neighborRef = neis[n] & 0xff; // Get the neighbor polygon reference. if (neis[n] & #DT_EX_LINK) { // The edge is an external (portal) edge. } @endcode @var float dtMeshHeader::bvQuantFactor @par This value is used for converting between world and bounding volume coordinates. For example: @code const float cs = 1.0f / tile->header->bvQuantFactor; const dtBVNode* n = &tile->bvTree[i]; if (n->i >= 0) { // This is a leaf node. float worldMinX = tile->header->bmin[0] + n->bmin[0]*cs; float worldMinY = tile->header->bmin[0] + n->bmin[1]*cs; // Etc... } @endcode @struct dtMeshTile @par Tiles generally only exist within the context of a dtNavMesh object. Some tile content is optional. For example, a tile may not contain any off-mesh connections. In this case the associated pointer will be null. If a detail mesh exists it will share vertices with the base polygon mesh. Only the vertices unique to the detail mesh will be stored in #detailVerts. @warning Tiles returned by a dtNavMesh object are not guarenteed to be populated. For example: The tile at a location might not have been loaded yet, or may have been removed. In this case, pointers will be null. So if in doubt, check the polygon count in the tile's header to determine if a tile has polygons defined. @var float dtOffMeshConnection::pos[6] @par For a properly built navigation mesh, vertex A will always be within the bounds of the mesh. Vertex B is not required to be within the bounds of the mesh. */
412
0.967507
1
0.967507
game-dev
MEDIA
0.525798
game-dev
0.636335
1
0.636335
drmabuse19/RedM_VORP_server
6,376
bcc-oil/client/CriminalMissionsSetup.lua
local T = Translation.Langs[Config.Lang] ------- Oil Wagon Robbery Setup ----- Robableoilwagon, Roboilwagondeadcheck = 0, false local fillcoords = nil RegisterNetEvent('bcc-oil:RobOilWagon', function() Inmission = true Robableoilwagon = joaat('oilwagon02x') modelload(Robableoilwagon) --Coord Randomization fillcoords = CoordRandom(Config.OilWagonrobberyLocations) --Wagon Spawn Robableoilwagon = CreateVehicle(Robableoilwagon, fillcoords.wagonLocation, fillcoords.wagonHeading, true, true) TriggerEvent('bcc-oil:roboilwagonhelper') Citizen.InvokeNative(0x23f74c2fda6e7c61, 953018525, Robableoilwagon) FreezeEntityPosition(Robableoilwagon, true) VORPcore.NotifyRightTip(T.RobOilWagonOpeningtext, 4000) --Waypoint Setup VORPutils.Gps:SetGps(fillcoords.wagonLocation) --Distance Check Setup local cw = GetEntityCoords(Robableoilwagon) distcheck(cw.x, cw.y, cw.z, 30, PlayerPedId()) ClearGpsMultiRoute() if Roboilwagondeadcheck then VORPcore.NotifyRightTip(T.Missionfailed, 4000) DeleteEntity(Robableoilwagon) return end VORPcore.NotifyRightTip(T.RobOilWagonKillGaurds, 4000) --Spawning enemy Peds MutltiPedSpawnDeadCheck(fillcoords.pedlocation, 'wagonrob') end) function roboilwagonreturnwagon() --Init Setup FreezeEntityPosition(Robableoilwagon, false) VORPcore.NotifyRightTip(T.RobOilWagonReturnWagon, 4000) --Blip and Waypoint Setup local blip1 = BlipWaypoin(fillcoords.returnlocation.x, fillcoords.returnlocation.y, fillcoords.returnlocation.z, T.RobOilWagonReturnBlip) --Distance Check Setup for returning the wagon distcheck(fillcoords.returnlocation.x, fillcoords.returnlocation.y, fillcoords.returnlocation.z, 10, Robableoilwagon) ClearGpsMultiRoute() if Roboilwagondeadcheck then RemoveBlip(blip1) VORPcore.NotifyRightTip(T.Missionfailed, 4000) DeleteEntity(Robableoilwagon) return end --End of mission setup Inmission = false FreezeEntityPosition(Robableoilwagon, true) RemoveBlip(blip1) TaskLeaveAnyVehicle(PlayerPedId(), 0, 0) Wait(4000) DeleteEntity(Robableoilwagon) VORPcore.NotifyRightTip(T.RobOilWagonSuccess, 4000) TriggerServerEvent('bcc-oil:RobberyPayout') end function finishOilCompanyRobbery() Inmission = false VORPcore.NotifyRightTip(T.RobberySuccess, 4000) TriggerServerEvent('bcc-oil:RobberyPayout') end --Deadcheck event AddEventHandler('bcc-oil:roboilwagonhelper', function() Wait(400) while Inmission do Wait(100) if IsEntityDead(PlayerPedId()) or GetEntityHealth(Robableoilwagon) == 0 or not DoesEntityExist(Robableoilwagon) then Roboilwagondeadcheck = true Inmission = false Wait(3000) Roboilwagondeadcheck = false break end end end) --Rob Oil Company Variables Setup Roboilcodeadcheck = false local fillcoords2, missionoverend3dtext = nil, false RegisterNetEvent('bcc-oil:RobOilCo', function() VORPcore.NotifyRightTip(T.RobOilCoBlip, 4000) Inmission = true TriggerEvent('bcc-oil:roboilcohelper') --Coord Randomization fillcoords2 = CoordRandom(Config.RobOilCompany) --Blip and Waypoint Setup local blip1 = BlipWaypoin(fillcoords2.lootlocation.x, fillcoords2.lootlocation.y, fillcoords2.lootlocation.z, T.RobOilCoBlip) --Distance Check Setup for close to lockpick Location distcheck(fillcoords2.lootlocation.x, fillcoords2.lootlocation.y, fillcoords2.lootlocation.z, 5, PlayerPedId()) ClearGpsMultiRoute() if Roboilcodeadcheck then RemoveBlip(blip1) VORPcore.NotifyRightTip(T.Missionfailed, 4000) return end RemoveBlip(blip1) local cfg = { focus = true, -- Should minigame take nui focus cursor = true, -- Should minigame have cursor (required for lockpick) maxattempts = Config.LockPick.MaxAttemptsPerLock, -- How many fail attempts are allowed before game over threshold = Config.LockPick.difficulty, -- +- threshold to the stage degree (bigger number means easier) hintdelay = Config.LockPick.hintdelay, --milliseconds delay on when the circle will shake to show lockpick is in the right position. stages = { { deg = 25 -- 0-360 degrees }, { deg = 0 -- 0-360 degrees }, { deg = 300 -- 0-360 degrees } } } while true do Wait(5) local pl = GetEntityCoords(PlayerPedId()) local dist = GetDistanceBetweenCoords(fillcoords2.lootlocation.x, fillcoords2.lootlocation.y, fillcoords2.lootlocation.z, pl.x, pl.y, pl.z, true) if dist < 3 then if IsControlJustReleased(0, 0x760A9C6F) then MiniGame.Start('lockpick', cfg, function(result) if result.unlocked then if not Config.RobOilCoEnemyPeds then missionoverend3dtext = true --sets var true which is used to disable the 3d text from showing Inmission = false VORPcore.NotifyRightTip(T.RobberySuccess, 4000) TriggerServerEvent('bcc-oil:OilCoRobberyPayout', fillcoords2) else MutltiPedSpawnDeadCheck(Config.RobOilCoEnemyPedsLocations, 'oilcorob') Inmission = false end else if not Config.RobOilCoEnemyPeds then missionoverend3dtext = true --sets var true which is used to disable the 3d text from showing Inmission = false VORPcore.NotifyRightTip(T.Missionfailed, 4000) else MutltiPedSpawnDeadCheck(Config.RobOilCoEnemyPedsLocations, 'oilcorob') Inmission = false end end end) break end elseif dist > 200 then Wait(2000) end end end) AddEventHandler('bcc-oil:roboilcohelper', function() while Inmission do Wait(5) local pl = GetEntityCoords(PlayerPedId()) local dist = GetDistanceBetweenCoords(pl.x, pl.y, pl.z, fillcoords2.lootlocation.x, fillcoords2.lootlocation.y, fillcoords2.lootlocation.z, true) if dist < 15 then if not missionoverend3dtext then BccUtils.Misc.DrawText3D(fillcoords2.lootlocation.x, fillcoords2.lootlocation.y, fillcoords2.lootlocation.z, T.PressGToLockPick) else missionoverend3dtext = false break end elseif dist > 200 then Wait(2000) end if IsEntityDead(PlayerPedId()) then Inmission = false Roboilcodeadcheck = true Wait(10000) Roboilcodeadcheck = false end end end)
412
0.938799
1
0.938799
game-dev
MEDIA
0.78925
game-dev,testing-qa
0.968122
1
0.968122
jorio/Bugdom
9,161
src/Enemies/Enemy_Larva.c
/****************************/ /* ENEMY: LARVA.C */ /* (c)1999 Pangea Software */ /* By Brian Greenstone */ /****************************/ /****************************/ /* EXTERNALS */ /****************************/ #include "game.h" /****************************/ /* PROTOTYPES */ /****************************/ static void MoveLarva(ObjNode *theNode); static void MoveLarvaOnSpline(ObjNode *theNode); static void MoveLarva_Walk(ObjNode *theNode); static void MoveLarva_Wait(ObjNode *theNode); static void MoveLarva_Squished(ObjNode *theNode); static void MoveLarva_Dead(ObjNode *theNode); /****************************/ /* CONSTANTS */ /****************************/ #define MAX_LARVA 5 #define LARVA_CHASE_RANGE 700.0f #define LARVA_TURN_SPEED 3.0f #define LARVA_CHASE_SPEED 100.0f #define LARVA_CHASE_RANGE2 80.0f #define LARVA_SPLINE_SPEED 70.0f #define MAX_LARVA_RANGE (LARVA_CHASE_RANGE+1000.0f) // max distance this enemy can go from init coord #define LARVA_HEALTH 1.0f #define LARVA_DAMAGE 0.1f #define LARVA_SCALE .5f enum { LARVA_ANIM_WAIT, LARVA_ANIM_WALK, LARVA_ANIM_SQUISHED, LARVA_ANIM_DEAD }; /*********************/ /* VARIABLES */ /*********************/ /************************ ADD LARVA ENEMY *************************/ Boolean AddEnemy_Larva(TerrainItemEntryType *itemPtr, long x, long z) { ObjNode *newObj; if (gNumEnemies >= MAX_ENEMIES) // keep from getting absurd return(false); if (gNumEnemyOfKind[ENEMY_KIND_LARVA] >= MAX_LARVA) return(false); /* MAKE DEFAULT SKELETON ENEMY */ newObj = MakeEnemySkeleton(SKELETON_TYPE_LARVA,x,z,LARVA_SCALE); if (newObj == nil) return(false); newObj->TerrainItemPtr = itemPtr; /* SET BETTER INFO */ newObj->MoveCall = MoveLarva; // set move call newObj->Health = LARVA_HEALTH; newObj->Damage = LARVA_DAMAGE; newObj->Kind = ENEMY_KIND_LARVA; /* SET COLLISION INFO */ newObj->CType |= CTYPE_AUTOTARGET|CTYPE_AUTOTARGETJUMP|CTYPE_BOPPABLE|CTYPE_SPIKED|CTYPE_KICKABLE; SetObjectCollisionBounds(newObj, 70,0,-40,40,40,-40); gNumEnemies++; gNumEnemyOfKind[ENEMY_KIND_LARVA]++; return(true); } /************************ MAKE LARVA ENEMY *************************/ ObjNode *MakeLarvaEnemy(float x, float z) { ObjNode *newObj; if (gNumEnemyOfKind[ENEMY_KIND_LARVA] >= 5) // only allow n return(nil); /* MAKE DEFAULT SKELETON ENEMY */ newObj = MakeEnemySkeleton(SKELETON_TYPE_LARVA,x,z,LARVA_SCALE); if (newObj == nil) return(nil); /* SET BETTER INFO */ newObj->MoveCall = MoveLarva; // set move call newObj->Health = LARVA_HEALTH; newObj->Damage = LARVA_DAMAGE; newObj->Kind = ENEMY_KIND_LARVA; newObj->Rot.y = RandomFloat()*PI2; // random aim /* SET COLLISION INFO */ newObj->CType |= CTYPE_AUTOTARGET|CTYPE_AUTOTARGETJUMP|CTYPE_BOPPABLE|CTYPE_SPIKED|CTYPE_KICKABLE; SetObjectCollisionBounds(newObj, 70,0,-40,40,40,-40); gNumEnemies++; gNumEnemyOfKind[ENEMY_KIND_LARVA]++; return(newObj); } /********************* MOVE LARVA **************************/ static void MoveLarva(ObjNode *theNode) { static void(*myMoveTable[])(ObjNode *) = { MoveLarva_Wait, MoveLarva_Walk, MoveLarva_Squished, MoveLarva_Dead }; if (TrackTerrainItem(theNode)) // just check to see if it's gone { DeleteEnemy(theNode); return; } GetObjectInfo(theNode); myMoveTable[theNode->Skeleton->AnimNum](theNode); } /********************** MOVE LARVA: WALK ******************************/ static void MoveLarva_Walk(ObjNode *theNode) { float fps = gFramesPerSecondFrac; float r; theNode->Skeleton->AnimSpeed = 2.0f; /* MOVE TOWARD PLAYER */ TurnObjectTowardTarget(theNode, &gCoord, gMyCoord.x, gMyCoord.z, LARVA_TURN_SPEED, false); r = theNode->Rot.y; gDelta.x = sin(r) * -LARVA_CHASE_SPEED; gDelta.z = cos(r) * -LARVA_CHASE_SPEED; gCoord.x += gDelta.x * fps; gCoord.z += gDelta.z * fps; gCoord.y = GetTerrainHeightAtCoord(gCoord.x, gCoord.z, FLOOR); // calc y coord /**********************/ /* DO ENEMY COLLISION */ /**********************/ if (DoEnemyCollisionDetect(theNode,DEFAULT_ENEMY_COLLISION_CTYPES)) return; UpdateEnemy(theNode); } /********************** MOVE LARVA: WAIT ******************************/ static void MoveLarva_Wait(ObjNode *theNode) { TurnObjectTowardTarget(theNode, &gCoord, gMyCoord.x, gMyCoord.z, LARVA_TURN_SPEED, false); /* SEE IF CLOSE ENOUGH TO ATTACK */ if (CalcQuickDistance(gCoord.x, gCoord.z, gMyCoord.x, gMyCoord.z) < LARVA_CHASE_RANGE) { MorphToSkeletonAnim(theNode->Skeleton, LARVA_ANIM_WALK, 7); } /**********************/ /* DO ENEMY COLLISION */ /**********************/ if (DoEnemyCollisionDetect(theNode,DEFAULT_ENEMY_COLLISION_CTYPES)) return; UpdateEnemy(theNode); } /********************** MOVE LARVA: SQUISHED ******************************/ static void MoveLarva_Squished(ObjNode *theNode) { UpdateEnemy(theNode); } /********************** MOVE LARVA: DEAD ******************************/ static void MoveLarva_Dead(ObjNode *theNode) { if (theNode->StatusBits & STATUS_BIT_ISCULLED) // if was culled on last frame and is far enough away, then delete it { DeleteEnemy(theNode); return; } } #pragma mark - /************************ PRIME LARVA ENEMY *************************/ Boolean PrimeEnemy_Larva(long splineNum, SplineItemType *itemPtr) { ObjNode *newObj; float x,z,placement; /* GET SPLINE INFO */ placement = itemPtr->placement; GetCoordOnSpline(&(*gSplineList)[splineNum], placement, &x, &z); /* MAKE DEFAULT SKELETON ENEMY */ newObj = MakeEnemySkeleton(SKELETON_TYPE_LARVA,x,z, LARVA_SCALE); if (newObj == nil) return(false); DetachObject(newObj); // detach this object from the linked list newObj->SplineItemPtr = itemPtr; newObj->SplineNum = splineNum; SetSkeletonAnim(newObj->Skeleton, LARVA_ANIM_WALK); /* SET BETTER INFO */ newObj->StatusBits |= STATUS_BIT_ONSPLINE; newObj->SplinePlacement = placement; newObj->SplineMoveCall = MoveLarvaOnSpline; // set move call newObj->Health = LARVA_HEALTH; newObj->Damage = LARVA_DAMAGE; newObj->Kind = ENEMY_KIND_LARVA; newObj->CType |= CTYPE_AUTOTARGET|CTYPE_AUTOTARGETJUMP|CTYPE_BOPPABLE|CTYPE_SPIKED; /* SET COLLISION INFO */ SetObjectCollisionBounds(newObj, 70,0,-40,40,40,-40); /* ADD SPLINE OBJECT TO SPLINE OBJECT LIST */ AddToSplineObjectList(newObj); return(true); } /******************** MOVE LARVA ON SPLINE ***************************/ // // NOTE: This is called for every Larva on the spline in the entire level. // The isVisible flag determines if this particular one is in visible range. // It actually means the enemy is on an active supertile. // static void MoveLarvaOnSpline(ObjNode *theNode) { Boolean isVisible; isVisible = IsSplineItemVisible(theNode); // update its visibility /* MOVE ALONG THE SPLINE */ IncreaseSplineIndex(theNode, LARVA_SPLINE_SPEED); GetObjectCoordOnSpline(theNode, &theNode->Coord.x, &theNode->Coord.z); /***************************/ /* UPDATE STUFF IF VISIBLE */ /***************************/ if (isVisible) { theNode->Skeleton->AnimSpeed = 2.0f; /* START/UPDATE BUZZ */ if (theNode->EffectChannel == -1) theNode->EffectChannel = PlayEffect3D(EFFECT_BUZZ, &theNode->Coord); else Update3DSoundChannel(EFFECT_BUZZ, &theNode->EffectChannel, &theNode->Coord); theNode->Rot.y = CalcYAngleFromPointToPoint(theNode->Rot.y, theNode->OldCoord.x, theNode->OldCoord.z, // calc y rot aim theNode->Coord.x, theNode->Coord.z); theNode->Coord.y = GetTerrainHeightAtCoord(theNode->Coord.x, theNode->Coord.z, FLOOR); // calc y coord UpdateObjectTransforms(theNode); // update transforms CalcObjectBoxFromNode(theNode); // update collision box /*********************************/ /* SEE IF CLOSE ENOUGH TO ATTACK */ /*********************************/ if (CalcQuickDistance(theNode->Coord.x, theNode->Coord.z, gMyCoord.x, gMyCoord.z) < LARVA_CHASE_RANGE2) { /* REMOVE FROM SPLINE */ DetachEnemyFromSpline(theNode, MoveLarva); } } /* NOT VISIBLE */ else { StopObjectStreamEffect(theNode); } } #pragma mark - /****************** LARVA GOT BOPPED ************************/ // // Called during player collision handler. // void LarvaGotBopped(ObjNode *enemy) { /* IF ON SPLINE, DETACH */ DetachEnemyFromSpline(enemy, MoveLarva); SetSkeletonAnim(enemy->Skeleton, LARVA_ANIM_SQUISHED); /* FLATTEN */ enemy->Scale.y *= .2f; UpdateObjectTransforms(enemy); enemy->CType = 0; } /******************* KILL LARVA **********************/ Boolean KillLarva(ObjNode *theNode) { theNode->TerrainItemPtr = nil; // dont ever come back MorphToSkeletonAnim(theNode->Skeleton, LARVA_ANIM_DEAD, 3.0); theNode->CType = CTYPE_MISC; return(false); }
412
0.861938
1
0.861938
game-dev
MEDIA
0.945826
game-dev
0.988658
1
0.988658
MilkyEngineer/Multithreading_UnrealFestGC24
3,444
Source/SaveGame/Private/SaveGameCharacter.cpp
// Copyright Epic Games, Inc. All Rights Reserved. #include "SaveGameCharacter.h" #include "SaveGameProjectile.h" #include "Animation/AnimInstance.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "EnhancedInputComponent.h" #include "EnhancedInputSubsystems.h" ////////////////////////////////////////////////////////////////////////// // ASaveGameCharacter ASaveGameCharacter::ASaveGameCharacter() { // Character doesnt have a rifle at start bHasRifle = false; // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(55.f, 96.0f); // Create a CameraComponent FirstPersonCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("FirstPersonCamera")); FirstPersonCameraComponent->SetupAttachment(GetCapsuleComponent()); FirstPersonCameraComponent->SetRelativeLocation(FVector(-10.f, 0.f, 60.f)); // Position the camera FirstPersonCameraComponent->bUsePawnControlRotation = true; // Create a mesh component that will be used when being viewed from a '1st person' view (when controlling this pawn) Mesh1P = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("CharacterMesh1P")); Mesh1P->SetOnlyOwnerSee(true); Mesh1P->SetupAttachment(FirstPersonCameraComponent); Mesh1P->bCastDynamicShadow = false; Mesh1P->CastShadow = false; //Mesh1P->SetRelativeRotation(FRotator(0.9f, -19.19f, 5.2f)); Mesh1P->SetRelativeLocation(FVector(-30.f, 0.f, -150.f)); } void ASaveGameCharacter::BeginPlay() { // Call the base class Super::BeginPlay(); //Add Input Mapping Context if (APlayerController* PlayerController = Cast<APlayerController>(Controller)) { if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PlayerController->GetLocalPlayer())) { Subsystem->AddMappingContext(DefaultMappingContext, 0); } } } //////////////////////////////////////////////////////////////////////////// Input void ASaveGameCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { // Set up action bindings if (UEnhancedInputComponent* EnhancedInputComponent = CastChecked<UEnhancedInputComponent>(PlayerInputComponent)) { //Jumping EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Triggered, this, &ACharacter::Jump); EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Completed, this, &ACharacter::StopJumping); //Moving EnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered, this, &ASaveGameCharacter::Move); //Looking EnhancedInputComponent->BindAction(LookAction, ETriggerEvent::Triggered, this, &ASaveGameCharacter::Look); } } void ASaveGameCharacter::Move(const FInputActionValue& Value) { // input is a Vector2D FVector2D MovementVector = Value.Get<FVector2D>(); if (Controller != nullptr) { // add movement AddMovementInput(GetActorForwardVector(), MovementVector.Y); AddMovementInput(GetActorRightVector(), MovementVector.X); } } void ASaveGameCharacter::Look(const FInputActionValue& Value) { // input is a Vector2D FVector2D LookAxisVector = Value.Get<FVector2D>(); if (Controller != nullptr) { // add yaw and pitch input to controller AddControllerYawInput(LookAxisVector.X); AddControllerPitchInput(LookAxisVector.Y); } } void ASaveGameCharacter::SetHasRifle(bool bNewHasRifle) { bHasRifle = bNewHasRifle; } bool ASaveGameCharacter::GetHasRifle() { return bHasRifle; }
412
0.911314
1
0.911314
game-dev
MEDIA
0.934296
game-dev
0.746862
1
0.746862
OpenRA/OpenRA
6,096
OpenRA.Mods.Common/Lint/CheckSequences.cs
#region Copyright & License Information /* * Copyright (c) The OpenRA Developers and Contributors * This file is part of OpenRA, which is free software. It is made * available to you 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. For more * information, see COPYING. */ #endregion using System; using System.Collections.Generic; using System.Linq; using OpenRA.Graphics; using OpenRA.Mods.Common.Traits.Render; using OpenRA.Server; using OpenRA.Traits; namespace OpenRA.Mods.Common.Lint { sealed class CheckSequences : ILintSequencesPass, ILintServerMapPass { void ILintServerMapPass.Run(Action<string> emitError, Action<string> emitWarning, ModData modData, MapPreview map, Ruleset mapRules) { using (var sequences = new SequenceSet(map, modData, map.TileSet, map.SequenceDefinitions)) { Run(emitError, emitWarning, mapRules, sequences); } } void ILintSequencesPass.Run(Action<string> emitError, Action<string> emitWarning, ModData modData, Ruleset rules, SequenceSet sequences) { Run(emitError, emitWarning, rules, sequences); } static void Run(Action<string> emitError, Action<string> emitWarning, Ruleset rules, SequenceSet sequences) { var factions = rules.Actors[SystemActors.World].TraitInfos<FactionInfo>().Select(f => f.InternalName).ToArray(); foreach (var actorInfo in rules.Actors) { // Catch TypeDictionary errors. try { var images = new HashSet<string>(); // Actors may have 0 or 1 RenderSprites traits. var renderInfo = actorInfo.Value.TraitInfoOrDefault<RenderSpritesInfo>(); if (renderInfo != null) { images.Add(renderInfo.GetImage(actorInfo.Value, null).ToLowerInvariant()); // Some actors define faction-specific artwork. foreach (var faction in factions) images.Add(renderInfo.GetImage(actorInfo.Value, faction).ToLowerInvariant()); } foreach (var traitInfo in actorInfo.Value.TraitInfos<TraitInfo>()) { // Remove the "Info" suffix. var traitName = traitInfo.GetType().Name; traitName = traitName[..^4]; var fields = Utility.GetFields(traitInfo.GetType()); foreach (var field in fields) { var sequenceReference = Utility.GetCustomAttributes<SequenceReferenceAttribute>(field, true).FirstOrDefault(); if (sequenceReference == null) continue; // Some sequences may specify their own Image override. IEnumerable<string> sequenceImages = images; if (!string.IsNullOrEmpty(sequenceReference.ImageReference)) { var imageField = fields.First(f => f.Name == sequenceReference.ImageReference); var imageOverride = (string)imageField.GetValue(traitInfo); if (string.IsNullOrEmpty(imageOverride)) { if (!sequenceReference.AllowNullImage) emitError($"Actor type `{actorInfo.Value.Name}` trait `{traitName}` must define a value for `{sequenceReference.ImageReference}`."); continue; } sequenceImages = [imageOverride.ToLowerInvariant()]; } foreach (var sequence in LintExts.GetFieldValues(traitInfo, field, sequenceReference.DictionaryReference)) { if (string.IsNullOrEmpty(sequence)) continue; foreach (var i in sequenceImages) { if (sequenceReference.Prefix) { // TODO: Remove prefixed sequence references and instead use explicit lists of lintable references. if (!sequences.Sequences(i).Any(s => s.StartsWith(sequence, StringComparison.Ordinal))) emitWarning( $"Actor type `{actorInfo.Value.Name}` trait `{traitName}` field `{field.Name}` " + $"defines a prefix `{sequence}` that does not match any sequences on image `{i}`."); } else if (!sequences.HasSequence(i, sequence)) emitError( $"Actor type `{actorInfo.Value.Name}` trait `{traitName}` field `{field.Name}` " + $"references an undefined sequence `{sequence}` on image `{i}`."); } } } } } catch (InvalidOperationException e) { emitError($"{e.Message} (Actor type `{actorInfo.Key}`)"); } } foreach (var weaponInfo in rules.Weapons) { var projectileInfo = weaponInfo.Value.Projectile; if (projectileInfo == null) continue; var fields = Utility.GetFields(projectileInfo.GetType()); foreach (var field in fields) { var sequenceReference = Utility.GetCustomAttributes<SequenceReferenceAttribute>(field, true).FirstOrDefault(); if (sequenceReference == null) continue; // All weapon sequences must specify their corresponding image. var image = (string)fields.First(f => f.Name == sequenceReference.ImageReference).GetValue(projectileInfo); if (string.IsNullOrEmpty(image)) { if (!sequenceReference.AllowNullImage) emitError($"Weapon type `{weaponInfo.Key}` projectile field `{sequenceReference.ImageReference}` must define a value."); continue; } image = image.ToLowerInvariant(); foreach (var sequence in LintExts.GetFieldValues(projectileInfo, field, sequenceReference.DictionaryReference)) { if (string.IsNullOrEmpty(sequence)) continue; if (sequenceReference.Prefix) { // TODO: Remove prefixed sequence references and instead use explicit lists of lintable references. if (!sequences.Sequences(image).Any(s => s.StartsWith(sequence, StringComparison.Ordinal))) emitWarning( $"Weapon type `{weaponInfo.Key}` projectile field `{field.Name}` " + $"defines a prefix `{sequence}` that does not match any sequences on image `{image}`."); } else if (!sequences.HasSequence(image, sequence)) emitError( $"Weapon type `{weaponInfo.Key}` projectile field `{field.Name}` " + $"references an undefined sequence `{sequence}` on image `{image}`."); } } } } } }
412
0.888838
1
0.888838
game-dev
MEDIA
0.526732
game-dev
0.863945
1
0.863945
angband/angband
16,751
src/borg/borg-home-power.c
/** * \file borg-home-power.c * \brief Determine the power value of the home * this is used to decide what items are best to keep at home * * Copyright (c) 1997 Ben Harrison, James E. Wilson, Robert A. Koeneke * Copyright (c) 2007-9 Andi Sidwell, Chris Carr, Ed Graham, Erik Osheim * * This work is free software; you can redistribute it and/or modify it * under the terms of either: * * a) the GNU General Public License as published by the Free Software * Foundation, version 2, or * * b) the "Angband License": * This software may be copied and distributed for educational, research, * and not for profit purposes provided that this copyright and statement * are included in all such copies. Other copyrights may also apply. */ #include "borg-home-power.h" #ifdef ALLOW_BORG #include "borg-home-notice.h" #include "borg-magic.h" #include "borg-trait.h" /* * Helper function -- calculate power of equipment in the home */ static int32_t borg_power_home_aux1(void) { int32_t value = 0L; /* This would be better separated by item type (so 1 bonus for resist cold * armor */ /* 1 bonus for resist cold shield... but that would take a bunch more * code. */ /* try to collect at least 2 of each resist/power (for swapping) */ /* This can be used to get rid of extra artifacts... */ /* spare lite sources. Artifacts only */ if (num_LIGHT == 1) value += 150L; else if (num_LIGHT == 2) value += 170L; else if (num_LIGHT > 2) value += 170L + (num_LIGHT - 2) * 5L; if (num_slow_digest == 1) value += 50L; else if (num_slow_digest == 2) value += 70L; else if (num_slow_digest > 2) value += 70L + (num_slow_digest - 2) * 5L; if (num_regenerate == 1) value += 75L; else if (num_regenerate == 2) value += 100L; else if (num_regenerate > 2) value += 100L + (num_regenerate - 2) * 10L; if (num_telepathy == 1) value += 1000L; else if (num_telepathy == 2) value += 1500L; else if (num_telepathy > 2) value += 1500L + (num_telepathy - 2) * 10L; if (num_see_inv == 1) value += 800L; else if (num_see_inv == 2) value += 1200L; else if (num_see_inv > 2) value += 1200L + (num_see_inv - 2) * 10L; if (num_ffall == 1) value += 10L; else if (num_ffall == 2) value += 15L; else if (num_ffall > 2) value += 15L + (num_ffall - 2) * 1L; if (num_free_act == 1) value += 1000L; else if (num_free_act == 2) value += 1500L; else if (num_free_act > 2) value += 1500L + (num_free_act - 2) * 10L; if (num_hold_life == 1) value += 1000L; else if (num_hold_life == 2) value += 1500L; else if (num_hold_life > 2) value += 1500L + (num_hold_life - 2) * 10L; if (num_resist_acid == 1) value += 1000L; else if (num_resist_acid == 2) value += 1500L; else if (num_resist_acid > 2) value += 1500L + (num_resist_acid - 2) * 1L; if (num_immune_acid == 1) value += 3000L; else if (num_immune_acid == 2) value += 5000L; else if (num_immune_acid > 2) value += 5000L + (num_immune_acid - 2) * 30L; if (num_resist_elec == 1) value += 1000L; else if (num_resist_elec == 2) value += 1500L; else if (num_resist_elec > 2) value += 1500L + (num_resist_elec - 2) * 1L; if (num_immune_elec == 1) value += 3000L; else if (num_immune_elec == 2) value += 5000L; else if (num_immune_elec > 2) value += 5000L + (num_immune_elec - 2) * 30L; if (num_resist_fire == 1) value += 1000L; else if (num_resist_fire == 2) value += 1500L; else if (num_resist_fire > 2) value += 1500L + (num_resist_fire - 2) * 1L; if (num_immune_fire == 1) value += 3000L; else if (num_immune_fire == 2) value += 5000L; else if (num_immune_fire > 2) value += 5000L + (num_immune_fire - 2) * 30L; if (num_resist_cold == 1) value += 1000L; else if (num_resist_cold == 2) value += 1500L; else if (num_resist_cold > 2) value += 1500L + (num_resist_cold - 2) * 1L; if (num_immune_cold == 1) value += 3000L; else if (num_immune_cold == 2) value += 5000L; else if (num_immune_cold > 2) value += 5000L + (num_immune_cold - 2) * 30L; if (num_resist_pois == 1) value += 5000L; else if (num_resist_pois == 2) value += 9000L; else if (num_resist_pois > 2) value += 9000L + (num_resist_pois - 2) * 40L; if (num_resist_conf == 1) value += 2000L; else if (num_resist_conf == 2) value += 8000L; else if (num_resist_conf > 2) value += 8000L + (num_resist_conf - 2) * 45L; if (num_resist_sound == 1) value += 500L; else if (num_resist_sound == 2) value += 700L; else if (num_resist_sound > 2) value += 700L + (num_resist_sound - 2) * 30L; if (num_resist_LIGHT == 1) value += 100L; else if (num_resist_LIGHT == 2) value += 150L; else if (num_resist_LIGHT > 2) value += 150L + (num_resist_LIGHT - 2) * 1L; if (num_resist_dark == 1) value += 100L; else if (num_resist_dark == 2) value += 150L; else if (num_resist_dark > 2) value += 150L + (num_resist_dark - 2) * 1L; if (num_resist_chaos == 1) value += 1000L; else if (num_resist_chaos == 2) value += 1500L; else if (num_resist_chaos > 2) value += 1500L + (num_resist_chaos - 2) * 10L; if (num_resist_disen == 1) value += 5000L; else if (num_resist_disen == 2) value += 7000L; else if (num_resist_disen > 2) value += 7000L + (num_resist_disen - 2) * 35L; if (num_resist_shard == 1) value += 100L; else if (num_resist_shard == 2) value += 150L; else if (num_resist_shard > 2) value += 150L + (num_resist_shard - 2) * 1L; if (num_resist_nexus == 1) value += 200L; else if (num_resist_nexus == 2) value += 300L; else if (num_resist_nexus > 2) value += 300L + (num_resist_nexus - 2) * 2L; if (num_resist_blind == 1) value += 500L; else if (num_resist_blind == 2) value += 1000L; else if (num_resist_blind > 2) value += 1000L + (num_resist_blind - 2) * 5L; if (num_resist_neth == 1) value += 3000L; else if (num_resist_neth == 2) value += 4000L; else if (num_resist_neth > 2) value += 4000L + (num_resist_neth - 2) * 45L; /* stat gain items as well...(good to carry ring of dex +6 in */ /* house even if I don't need it right now) */ if (home_stat_add[STAT_STR] < 9) value += home_stat_add[STAT_STR] * 300L; else if (home_stat_add[STAT_STR] < 15) value += 9 * 300L + (home_stat_add[STAT_STR] - 9) * 200L; else value += 9 * 300L + 6 * 200L + (home_stat_add[STAT_STR] - 15) * 1L; if (home_stat_add[STAT_DEX] < 9) value += home_stat_add[STAT_DEX] * 300L; else if (home_stat_add[STAT_DEX] < 15) value += 9 * 300L + (home_stat_add[STAT_DEX] - 9) * 200L; else value += 9 * 300L + 6 * 200L + (home_stat_add[STAT_DEX] - 15) * 1L; /* HACK extra con for thorin and other such things */ if (home_stat_add[STAT_CON] < 15) value += home_stat_add[STAT_CON] * 300L; else if (home_stat_add[STAT_CON] < 21) value += 15 * 300L + (home_stat_add[STAT_CON] - 15) * 200L; else value += 15 * 300L + 6 * 200L + (home_stat_add[STAT_CON] - 21) * 1L; /* spell stat is only bonused for spell casters. */ int spell_stat = borg_spell_stat(); if (spell_stat >= 0) { if (home_stat_add[spell_stat] < 20) value += home_stat_add[spell_stat] * 400L; else if (home_stat_add[spell_stat] < 26) value += 20 * 400L + (home_stat_add[spell_stat] - 20) * 300L; else value += 20 * 100L + 6 * 300L + (home_stat_add[spell_stat] - 26) * 5L; } /* Sustains */ if (num_sustain_str == 1) value += 200L; else if (num_sustain_str == 2) value += 250L; else if (num_sustain_str > 2) value += 250L + (num_sustain_str - 2) * 1L; if (num_sustain_int == 1) value += 200L; else if (num_sustain_int == 2) value += 250L; else if (num_sustain_int > 2) value += 250L + (num_sustain_int - 2) * 1L; if (num_sustain_wis == 1) value += 200L; else if (num_sustain_wis == 2) value += 250L; else if (num_sustain_wis > 2) value += 250L + (num_sustain_wis - 2) * 1L; if (num_sustain_con == 1) value += 200L; else if (num_sustain_con == 2) value += 250L; else if (num_sustain_con > 2) value += 250L + (num_sustain_con - 2) * 1L; if (num_sustain_dex == 1) value += 200L; else if (num_sustain_dex == 2) value += 250L; else if (num_sustain_dex > 2) value += 250L + (num_sustain_dex - 2) * 1L; if (num_sustain_all == 1) value += 1000L; else if (num_sustain_all == 2) value += 1500L; else if (num_sustain_all > 2) value += 1500L + (num_sustain_all - 2) * 1L; /* do a minus for too many duplicates. This way we do not store */ /* useless items and spread out types of items. */ if (num_weapons > 5) value -= (num_weapons - 5) * 2000L; else if (num_weapons > 1) value -= (num_weapons - 1) * 100L; if (num_bow > 2) value -= (num_bow - 2) * 1000L; if (num_rings > 6) value -= (num_rings - 6) * 4000L; else if (num_rings > 4) value -= (num_rings - 4) * 2000L; if (num_neck > 3) value -= (num_neck - 3) * 1500L; else if (num_neck > 3) value -= (num_neck - 3) * 700L; if (num_armor > 6) value -= (num_armor - 6) * 1000L; if (num_cloaks > 3) value -= (num_cloaks - 3) * 1000L; if (num_shields > 3) value -= (num_shields - 3) * 1000L; if (num_hats > 4) value -= (num_hats - 4) * 1000L; if (num_gloves > 3) value -= (num_gloves - 3) * 1000L; if (num_boots > 3) value -= (num_boots - 3) * 1000L; value += home_damage; /* if edged and priest, small penalty */ value -= num_edged_weapon * 50L; /* if gloves and mage or ranger and not FA/Dex, dump it. */ value -= num_bad_gloves * 3000L; /* do not allow duplication of items. */ value -= num_duplicate_items * 50000L; /* Return the value */ return (value); } /* * Helper function -- calculate power of items in the home * * The weird calculations help spread out the purchase order */ static int32_t borg_power_home_aux2(void) { int k, book; int32_t value = 0L; /*** Basic abilities ***/ /* Collect food */ if (borg.trait[BI_MAXCLEVEL] < 10) { for (k = 0; k < kb_info[TV_FOOD].max_stack && k < num_food; k++) value += 8000L - k * 10L; } /* Collect ident */ for (k = 0; k < kb_info[TV_SCROLL].max_stack && k < num_ident; k++) value += 2000L - k * 10L; /* Collect enchantments armour */ if (borg.trait[BI_CLEVEL] < 45) { for (k = 0; k < kb_info[TV_SCROLL].max_stack && k < num_enchant_to_a; k++) value += 500L - k * 10L; } /* Collect enchantments to hit */ if (borg.trait[BI_CLEVEL] < 45) { for (k = 0; k < kb_info[TV_SCROLL].max_stack && k < num_enchant_to_h; k++) value += 500L - k * 10L; } /* Collect enchantments to dam */ if (borg.trait[BI_CLEVEL] < 45) { for (k = 0; k < kb_info[TV_SCROLL].max_stack && k < num_enchant_to_d; k++) value += 500L - k * 10L; } /* Collect pfe */ for (k = 0; k < kb_info[TV_SCROLL].max_stack && k < num_pfe; k++) value += 500L - k * 10L; /* Collect glyphs */ for (k = 0; k < kb_info[TV_SCROLL].max_stack && k < num_glyph; k++) value += 500L - k * 10L; /* Reward Genocide scrolls. Just scrolls, mainly used for Morgoth */ for (k = 0; k < (kb_info[TV_SCROLL].max_stack * 2) && k < num_genocide; k++) value += 500L - k * 10L; /* Reward Mass Genocide scrolls. Just scrolls, mainly used for Morgoth */ for (k = 0; k < (kb_info[TV_SCROLL].max_stack * 2) && k < num_mass_genocide; k++) value += 500L; /* Collect Recharge ability */ for (k = 0; k < kb_info[TV_SCROLL].max_stack && k < num_recharge; k++) value += 500L - k * 10L; /* Reward Resistance Potions for Warriors */ if (borg.trait[BI_CLASS] == CLASS_WARRIOR && borg.trait[BI_MAXDEPTH] > 20 && borg.trait[BI_MAXDEPTH] < 80) { k = 0; for (; k < kb_info[TV_POTION].max_stack && k < num_pot_rheat; k++) value += 100L - k * 10L; for (; k < kb_info[TV_POTION].max_stack && k < num_pot_rcold; k++) value += 100L - k * 10L; } /* Collect recall - stick to 5 spare, for if you run out of money */ for (k = 0; k < 5 && k < num_recall; k++) value += 100L; /* Collect escape (staff of teleport) */ for (k = 0; k < 85 && k < num_escape; k++) value += 2000L - k * 10L; /* Collect only one stack worth of teleport staffs at home */ for (k = kb_info[TV_STAFF].max_stack; k < num_tele_staves; k++) value -= 50000L; /* Collect teleport */ for (k = 0; k < 85 && k < num_teleport; k++) value += 5000L; /* Collect phase */ if (borg.trait[BI_MAXCLEVEL] < 10) { for (k = 0; k < kb_info[TV_SCROLL].max_stack && k < num_phase; k++) value += 5000L; } /* Collect Speed */ /* for (k = 0; k < 85 && k < num_speed; k++) value += 5000L - k*10L; */ /* collect mana/ */ if (borg.trait[BI_MAXSP] > 1) { for (k = 0; k < kb_info[TV_POTION].max_stack && k < num_mana; k++) value += 6000L - k * 8L; } /* Level 1 priests are given a Potion of Healing. It is better * for them to sell that potion and buy equipment or several * Cure Crits with it. */ if (borg.trait[BI_CLEVEL] == 1) { k = 0; for (; k < 10 && k < num_heal; k++) value -= 5000L; } /*** Healing ***/ /* Collect cure critical */ for (k = 0; k < kb_info[TV_POTION].max_stack && k < num_cure_critical; k++) value += 1500L - k * 10L; /* Collect heal, *Heal*, Life */ for (k = 0; k < 90 && k < num_heal; k++) value += 3000L; for (k = 0; k < 198 && k < num_ezheal; k++) value += 8000L; for (k = 0; k < 198 && k < num_life; k++) value += 9000L; /* junk cure serious if we have some in the home */ /* don't bother keeping them if high level */ if (borg.trait[BI_CLEVEL] > 35) for (k = 0; k < 90 && k < num_cure_serious; k++) value -= 1500L - k * 10L; /*** Various ***/ /* Fixing Stats */ if (borg.trait[BI_CLEVEL] == 50 && num_fix_exp) value -= 7500L; if (borg.trait[BI_CLEVEL] > 35 && borg.trait[BI_CLEVEL] <= 49) for (k = 0; k < 70 && k < num_fix_exp; k++) value += 1000L - k * 10L; else if (borg.trait[BI_CLEVEL] <= 35) for (k = 0; k < 5 && k < num_fix_exp; k++) value += 1000L - k * 10L; /*** books ***/ /* Reward books */ for (book = 0; book < 9; book++) { /* only collect books up to level 14. */ /* After that, just buy them, they are always in stock*/ if (borg.trait[BI_CLEVEL] < 15) { /* Collect up to 5 copies of each normal book */ for (k = 0; k < 5 && k < num_book[book]; k++) { /* Only stockpile useful books */ if (num_book[book]) value += 5000L - k * 10L; } } } /* Reward artifacts in the home */ value += num_artifact * 500L; /* Reward certain types of egos in the home */ value += num_ego * 5000L; /* Only allow unid'd stuff if we can't id them */ if (home_un_id) value += (home_un_id - borg.trait[BI_AID]) * 1005L; /* Return the value */ return (value); } /* * Calculate the "power" of the home */ int32_t borg_power_home(void) { int32_t value = 0L; /* Process the home equipment */ value += borg_power_home_aux1(); /* Process the home inventory */ value += borg_power_home_aux2(); /* Return the value */ return (value); } #endif
412
0.698961
1
0.698961
game-dev
MEDIA
0.931109
game-dev
0.815337
1
0.815337
MrCrayfish/MrCrayfishVehicleMod
10,207
src/main/java/com/mrcrayfish/vehicle/entity/vehicle/MopedEntity.java
package com.mrcrayfish.vehicle.entity.vehicle; import com.google.common.collect.ImmutableMap; import com.mrcrayfish.vehicle.client.raytrace.EntityRayTracer; import com.mrcrayfish.vehicle.common.inventory.IAttachableChest; import com.mrcrayfish.vehicle.common.inventory.IStorage; import com.mrcrayfish.vehicle.common.inventory.StorageInventory; import com.mrcrayfish.vehicle.entity.MotorcycleEntity; import com.mrcrayfish.vehicle.init.ModEntities; import com.mrcrayfish.vehicle.inventory.container.StorageContainer; import com.mrcrayfish.vehicle.network.PacketHandler; import com.mrcrayfish.vehicle.network.message.MessageAttachChest; import com.mrcrayfish.vehicle.network.message.MessageOpenStorage; import com.mrcrayfish.vehicle.util.InventoryUtil; import net.minecraft.block.Blocks; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.item.ItemEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryHelper; import net.minecraft.inventory.ItemStackHelper; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.nbt.CompoundNBT; import net.minecraft.network.datasync.DataParameter; import net.minecraft.network.datasync.DataSerializers; import net.minecraft.network.datasync.EntityDataManager; import net.minecraft.util.Hand; import net.minecraft.util.NonNullList; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvents; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.util.Constants; import javax.annotation.Nullable; import java.util.Map; /** * Author: MrCrayfish */ public class MopedEntity extends MotorcycleEntity implements IStorage, IAttachableChest { private static final DataParameter<Boolean> CHEST = EntityDataManager.defineId(MopedEntity.class, DataSerializers.BOOLEAN); private static final DataParameter<Boolean> CHEST_OPEN = EntityDataManager.defineId(MopedEntity.class, DataSerializers.BOOLEAN); @Nullable private StorageInventory inventory; @OnlyIn(Dist.CLIENT) private float openProgress; @OnlyIn(Dist.CLIENT) private float prevOpenProgress; public MopedEntity(EntityType<? extends MopedEntity> type, World worldIn) { super(type, worldIn); this.initInventory(); } @Override public void defineSynchedData() { super.defineSynchedData(); this.entityData.define(CHEST, false); this.entityData.define(CHEST_OPEN, false); } @Override protected void readAdditionalSaveData(CompoundNBT compound) { super.readAdditionalSaveData(compound); if(compound.getBoolean("ChestAttached")) { this.setChest(true); this.initInventory(); this.readInventories(compound); } } @Override protected void addAdditionalSaveData(CompoundNBT compound) { super.addAdditionalSaveData(compound); if(this.hasChest()) { compound.putBoolean("ChestAttached", true); this.writeInventories(compound); } } public boolean hasChest() { return this.hasChest(""); } @Override public boolean hasChest(String key) { return this.entityData.get(CHEST); } public void setChest(boolean chest) { this.entityData.set(CHEST, chest); } private void initInventory() { StorageInventory original = this.inventory; this.inventory = new ChestInventory(this, this.getDisplayName(), 3); // Copies the inventory if it exists already over to the new instance if(original != null) { for(int i = 0; i < original.getContainerSize(); i++) { ItemStack stack = original.getItem(i); if(!stack.isEmpty()) { this.inventory.setItem(i, stack.copy()); } } } } @Override public Map<String, StorageInventory> getStorageInventories() { if(this.hasChest() && this.inventory != null) { return ImmutableMap.of("Chest", this.inventory); } return ImmutableMap.of(); } @Override protected void onVehicleDestroyed(LivingEntity entity) { super.onVehicleDestroyed(entity); if(this.hasChest() && this.inventory != null) { InventoryHelper.dropContents(this.level, this, this.inventory); } } @Override public void attachChest(String key, ItemStack stack) { if(!stack.isEmpty() && stack.getItem() == Items.CHEST) { this.setChest(true); this.initInventory(); CompoundNBT itemTag = stack.getTag(); if(itemTag != null) { CompoundNBT blockEntityTag = itemTag.getCompound("BlockEntityTag"); if(!blockEntityTag.isEmpty() && blockEntityTag.contains("Items", Constants.NBT.TAG_LIST)) { NonNullList<ItemStack> chestInventory = NonNullList.withSize(27, ItemStack.EMPTY); ItemStackHelper.loadAllItems(blockEntityTag, chestInventory); for(int i = 0; i < chestInventory.size(); i++) { this.inventory.setItem(i, chestInventory.get(i)); } } } } } @Override public void removeChest(String key) { if(this.hasChest() && this.inventory != null) { Vector3d target = this.getChestPosition(); InventoryUtil.dropInventoryItems(this.level, target.x, target.y, target.z, this.inventory); this.setChest(false); this.level.playSound(null, this.getX(), this.getY(), this.getZ(), SoundEvents.ITEM_BREAK, SoundCategory.BLOCKS, 1.0F, 1.0F); this.level.addFreshEntity(new ItemEntity(level, target.x, target.y, target.z, new ItemStack(Blocks.CHEST))); this.inventory = null; } } @Override public void tick() { super.tick(); if(this.hasChest()) { // Updates the chest open state if(!this.level.isClientSide()) { this.entityData.set(CHEST_OPEN, this.getPlayerCountInChest() > 0); } else { // Updates the open progress for the animation this.prevOpenProgress = this.openProgress; if(this.entityData.get(CHEST_OPEN)) { this.openProgress = Math.min(1.0F, this.openProgress + 0.1F); } else { float lastOpenProgress = this.openProgress; this.openProgress = Math.max(0.0F, this.openProgress - 0.1F); if(this.openProgress < 0.5F && lastOpenProgress >= 0.5F) { Vector3d target = this.getChestPosition(); this.level.playLocalSound(target.x, target.y, target.z, SoundEvents.CHEST_CLOSE, this.getSoundSource(), 0.5F, this.level.random.nextFloat() * 0.1F + 0.9F, false); } } } } } protected Vector3d getChestPosition() { return new Vector3d(0, 1.0, -0.75).yRot(-(this.yRot) * 0.017453292F).add(this.position()); } protected int getPlayerCountInChest() { if(!this.hasChest()) { return 0; } int count = 0; for(PlayerEntity player : this.level.getEntitiesOfClass(PlayerEntity.class, this.getBoundingBox().inflate(5.0F))) { if(player.containerMenu instanceof StorageContainer) { IInventory container = ((StorageContainer) player.containerMenu).getStorageInventory(); if(container == this.inventory) { count++; } } } return count; } @OnlyIn(Dist.CLIENT) public static void registerInteractionBoxes() { EntityRayTracer.instance().registerInteractionBox(ModEntities.MOPED.get(), () -> { return createScaledBoundingBox(-3.5, 8.0, -7.0, 3.5, 15.0, -14.0, 0.0625); }, (entity, rightClick) -> { if(rightClick) { PacketHandler.getPlayChannel().sendToServer(new MessageOpenStorage(entity.getId(), "Chest")); Minecraft.getInstance().player.swing(Hand.MAIN_HAND); } }, MopedEntity::hasChest); EntityRayTracer.instance().registerInteractionBox(ModEntities.MOPED.get(), () -> { return createScaledBoundingBox(-4.0, 7.0, -6.5, 4.0, 8.0, -14.5, 0.0625); }, (entity, rightClick) -> { if(rightClick) { PacketHandler.getPlayChannel().sendToServer(new MessageAttachChest(entity.getId(), "Chest")); Minecraft.getInstance().player.swing(Hand.MAIN_HAND); } }, entity -> !entity.hasChest()); } @OnlyIn(Dist.CLIENT) public float getOpenProgress() { return this.openProgress; } @OnlyIn(Dist.CLIENT) public float getPrevOpenProgress() { return this.prevOpenProgress; } public class ChestInventory extends StorageInventory { public ChestInventory(Entity entity, ITextComponent displayName, int rows) { super(entity, displayName, rows); } @Override public void startOpen(PlayerEntity player) { Vector3d target = MopedEntity.this.getChestPosition(); player.level.playSound(null, target.x, target.y, target.z, SoundEvents.CHEST_OPEN, MopedEntity.this.getSoundSource(), 0.5F, 0.9F); } } }
412
0.817549
1
0.817549
game-dev
MEDIA
0.987196
game-dev
0.962817
1
0.962817
r4dius/Iso2God
5,894
Chilano.Xbox360.Iso/GDFEntryNode.cs
namespace Chilano.Xbox360.Iso; public class GDFEntryNode { public enum TreeNodeBalance { LeftLeft, LeftRight, RightRight, RightLeft, Balanced } public GDFEntryNode Parent; public GDFEntryNode Left; public GDFEntryNode Right; public GDFDirEntry Key; public GDFEntryNode() { } public GDFEntryNode(GDFEntryNode Parent) { this.Parent = Parent; } public GDFEntryNode(GDFDirEntry Key) { this.Key = Key; } public static void Insert(GDFEntryNode Root, GDFDirEntry NewKey) { if (Root.Key == null) { Root.Key = NewKey; } else { int num = Root.Key.Name.CompareTo(NewKey.Name); if (num > 0) { if (Root.Left == null) { Root.Left = new GDFEntryNode(Root); } Insert(Root.Left, NewKey); } else if (num < 0) { if (Root.Right == null) { Root.Right = new GDFEntryNode(Root); } Insert(Root.Right, NewKey); } } if (Root.Parent != null && Root.Parent.Parent != null) { Rebalance(Root.Parent.Parent, Root.Parent, GetBalance(Root)); } } public static TreeNodeBalance GetBalance(GDFEntryNode Root) { int num = 0; if (Root.Parent != null) { if (Root.Parent.Left != null) { num++; } if (Root.Parent.Right != null) { num--; } if (Root.Parent.Parent != null) { if (num > 0) { if (Root.Parent.Parent.Left != null && Root.Parent.Parent.Right == null) { return TreeNodeBalance.LeftLeft; } if (Root.Parent.Parent.Right != null && Root.Parent.Parent.Left == null) { return TreeNodeBalance.RightLeft; } } if (num < 0) { if (Root.Parent.Parent.Left != null && Root.Parent.Parent.Right == null) { return TreeNodeBalance.LeftRight; } if (Root.Parent.Parent.Right != null && Root.Parent.Parent.Left == null) { return TreeNodeBalance.RightRight; } } } } return TreeNodeBalance.Balanced; } public static GDFEntryNode Rebalance(GDFEntryNode Root, GDFEntryNode Pivot, TreeNodeBalance Balance) { return Balance switch { TreeNodeBalance.RightRight => RotateLeft(Root, Pivot), TreeNodeBalance.RightLeft => RotateRightLeft(Root, Pivot), TreeNodeBalance.LeftLeft => RotateRight(Root, Pivot), TreeNodeBalance.LeftRight => RotateLeftRight(Root, Pivot), _ => null, }; } private static GDFEntryNode RotateRight(GDFEntryNode Root, GDFEntryNode Pivot) { Root.Left = null; Pivot.Right = Root; if (Root.Parent == null) { Pivot.Parent = null; Root.Parent = Pivot; } else { if (Root.Parent.Right == Root) { Root.Parent.Right = Pivot; } else { Root.Parent.Left = Pivot; } Root.Parent = Pivot; } return Pivot; } private static GDFEntryNode RotateLeft(GDFEntryNode Root, GDFEntryNode Pivot) { Root.Right = null; Pivot.Left = Root; if (Root.Parent == null) { Pivot.Parent = null; Root.Parent = Pivot; } else { if (Root.Parent.Right == Root) { Root.Parent.Right = Pivot; } else { Root.Parent.Left = Pivot; } Root.Parent = Pivot; } return Pivot; } private static GDFEntryNode RotateLeftRight(GDFEntryNode Root, GDFEntryNode Pivot) { GDFEntryNode right = Pivot.Right; Root.Left = right.Right; Pivot.Right = right.Left; right.Left = Pivot; right.Right = Root; if (Root.Parent == null) { right.Parent = null; Root.Parent = right; Pivot.Parent = right; } else { right.Parent = Root.Parent; if (Root.Parent.Right == Root) { Root.Parent.Right = right; } else { Root.Parent.Left = right; } Root.Parent = right; Pivot.Parent = right; } return right; } private static GDFEntryNode RotateRightLeft(GDFEntryNode Root, GDFEntryNode Pivot) { GDFEntryNode left = Pivot.Left; Pivot.Left = left.Right; Root.Right = left.Left; left.Right = Pivot; left.Left = Root; if (Root.Parent == null) { left.Parent = null; Root.Parent = left; Pivot.Parent = left; } else { left.Parent = Root.Parent; if (Root.Parent.Right == Root) { Root.Parent.Right = left; } else { Root.Parent.Left = left; } Root.Parent = left; Pivot.Parent = left; } return left; } }
412
0.751828
1
0.751828
game-dev
MEDIA
0.091229
game-dev
0.666931
1
0.666931
ismail0234/Subnautica-Below-Zero-Multiplayer
1,265
Subnautica.Events/Patches/Events/Game/SubNameInputDeselected.cs
namespace Subnautica.Events.Patches.Events.Game { using HarmonyLib; using Subnautica.API.Features; using Subnautica.Events.EventArgs; using System; [HarmonyPatch(typeof(global::SubNameInput), nameof(global::SubNameInput.OnDeselect))] public class SubNameInputDeselected { private static void Prefix(global::SubNameInput __instance) { if (Network.IsMultiplayerActive) { var detail = SubnameInputDetail.GetInformation(__instance.gameObject); if (detail.TechType == TechType.None) { return; } try { SubNameInputDeselectedEventArgs args = new SubNameInputDeselectedEventArgs(detail.UniqueId, detail.TechType, __instance.inputField.text, __instance.colorData[0].image.color, __instance.colorData[1].image.color, __instance.colorData[2].image.color, __instance.colorData[3].image.color); Handlers.Game.OnSubNameInputDeselected(args); } catch (Exception e) { Log.Error($"SubNameInputDeselected.Prefix: {e}\n{e.StackTrace}"); } } } } }
412
0.771784
1
0.771784
game-dev
MEDIA
0.559977
game-dev
0.724738
1
0.724738
leandrovieiraa/FreeHorrorGameKit
2,262
Assets/Standard Assets/CrossPlatformInput/Scripts/PlatformSpecific/StandaloneInput.cs
using System; using UnityEngine; namespace UnityStandardAssets.CrossPlatformInput.PlatformSpecific { public class StandaloneInput : VirtualInput { public override float GetAxis(string name, bool raw) { return raw ? Input.GetAxisRaw(name) : Input.GetAxis(name); } public override bool GetButton(string name) { return Input.GetButton(name); } public override bool GetButtonDown(string name) { return Input.GetButtonDown(name); } public override bool GetButtonUp(string name) { return Input.GetButtonUp(name); } public override void SetButtonDown(string name) { throw new Exception( " This is not possible to be called for standalone input. Please check your platform and code where this is called"); } public override void SetButtonUp(string name) { throw new Exception( " This is not possible to be called for standalone input. Please check your platform and code where this is called"); } public override void SetAxisPositive(string name) { throw new Exception( " This is not possible to be called for standalone input. Please check your platform and code where this is called"); } public override void SetAxisNegative(string name) { throw new Exception( " This is not possible to be called for standalone input. Please check your platform and code where this is called"); } public override void SetAxisZero(string name) { throw new Exception( " This is not possible to be called for standalone input. Please check your platform and code where this is called"); } public override void SetAxis(string name, float value) { throw new Exception( " This is not possible to be called for standalone input. Please check your platform and code where this is called"); } public override Vector3 MousePosition() { return Input.mousePosition; } } }
412
0.783638
1
0.783638
game-dev
MEDIA
0.432191
game-dev
0.573765
1
0.573765
incoherentsoftware/defect-process
7,893
src/Player/MovementSkill/All/GrappleSkill/Projectile/Towards.hs
module Player.MovementSkill.All.GrappleSkill.Projectile.Towards ( grappleProjTowardsNonEnemyCollision , grappleProjTowardsEnemyCollision ) where import qualified Data.List as L import qualified Data.Set as S import Attack.Hit import Collision import Configs.All.PlayerSkill.Grapple import Constants import InfoMsg.Util import Msg import Player.MovementSkill as MS import Player.MovementSkill.All.GrappleSkill.Data import Player.MovementSkill.All.GrappleSkill.Projectile.Data import Player.MovementSkill.All.GrappleSkill.Projectile.Util import Projectile as P import Util hitSoundFilePath = "event:/SFX Events/Player/Skills/grapple-hit" :: FilePath initialVelYUnscaled = -600.0 :: Float grappleProjTowardsUpdate :: MsgsRead UpdateProjectileMsgsPhase m => ProjectileUpdate GrappleProjData m grappleProjTowardsUpdate grappleProj = let processInfoMsg :: Projectile GrappleProjData -> InfoMsgPayload -> Projectile GrappleProjData processInfoMsg proj d = case d of InfoMsgPlayer playerInfo | [startPos, endPos] <- hitboxVertices (projectileHitbox proj) -> let playerPos = playerInfoPos playerInfo dirVec = vecNormalize $ startPos `vecSub` endPos dist = vecDist endPos playerPos startPos' = endPos `vecAdd` (dirVec `vecMul` dist) in proj { _data = (P._data proj) {_playerPos = playerPos} , _hitbox = const $ lineHitbox startPos' endPos } _ -> proj processMovingPlatformMsgs :: Projectile GrappleProjData -> [CollisionMsgPayload] -> Projectile GrappleProjData processMovingPlatformMsgs proj [] = proj processMovingPlatformMsgs proj (p:ps) = case p of CollisionMsgMovingPlatform platHbx projectedPlatHbx | projHbx `intersectsHitbox` projectedPlatHbx -> let offset = Pos2 (hitboxLeft projectedPlatHbx - hitboxLeft platHbx) 0.0 startPos = hitboxStartVertex projHbx endPos = hitboxEndVertex projHbx -- accumulates floating point error, but doesn't matter since short-lived endPos' = endPos `vecAdd` offset in proj {_hitbox = const $ lineHitbox startPos endPos'} _ -> processMovingPlatformMsgs proj ps where projHbx = projectileHitbox proj in do grappleProj' <- L.foldl' processInfoMsg grappleProj <$> readMsgs processMovingPlatformMsgs grappleProj' <$> readMsgs grappleProjTowardsCollision :: Pos2 -> Overshoot -> Maybe Direction -> Projectile GrappleProjData -> [Msg ThinkCollisionMsgsPhase] grappleProjTowardsCollision intersectPos@(Pos2 intersectX _) overshoot faceDir grappleProj = [ mkMsgTo (ProjectileMsgUpdate updateProj) grappleProjId , mkMsgEx (PlayerMsgSetVelocity initialVel) MsgEndOrder , mkMsgEx (PlayerMsgSetDirection dir) MsgAfterNormalOrder , mkMsgEx (PlayerMsgUpdateMovementSkill updateTowards) MsgEndOrder , mkMsg $ AudioMsgPlaySound hitSoundFilePath intersectPos , mkMsg $ WorldMsgHitlag (_projHitlag cfg) ] where grappleProjData = P._data grappleProj cfg = _config (grappleProjData :: GrappleProjData) targetVel = playerTowardsVel (grappleProjStartPos grappleProj) intersectPos cfg Pos2 grappleStartX _ = grappleProjStartPos grappleProj dir = if intersectX < grappleStartX then LeftDir else RightDir grappleProjId = P._msgId grappleProj initialVelY | _playerTouchingGround grappleProjData && vecY targetVel > 0.0 = let targetVecY = vecY $ vecNormalize (toVec2 targetVel) in initialVelYUnscaled * targetVecY | otherwise = 0.0 initialVel | initialVelY < 0.0 = Vel2 (vecX targetVel) initialVelY | otherwise = targetVel projStartVisualPos = \p -> let pData = P._data p playerPos = _playerPos pData playerPos' = playerPos `vecAdd` (toPos2 $ targetVel `vecMul` timeStep) handsOffset = _playerTowardsHandsOffset cfg `vecFlip` dir in playerPos' `vecAdd` handsOffset updateProj = \p -> p { _data = (P._data p) { _startVisualPos = projStartVisualPos , _startPosVel = targetVel } , _ttl = _projTowardsSecs cfg , _update = grappleProjTowardsUpdate , _registeredCollisions = S.empty } updateTowards = \ms -> let grappleStatus = TowardsGrappling intersectPos initialVelY (_playerTowardsActiveMaxSecs cfg) overshoot faceDir in ms { MS._data = (MS._data ms) { _status = grappleStatus , _projectileMsgId = P._msgId grappleProj } :: GrappleData , _status = ActiveCancelableMovement } grappleProjTowardsNonEnemyCollision :: Pos2 -> Hitbox -> Projectile GrappleProjData -> [Msg ThinkCollisionMsgsPhase] grappleProjTowardsNonEnemyCollision intersectPos collisionHbx grappleProj = effectMsg:grappleProjTowardsCollision intersectPos AllowOvershoot Nothing grappleProj where effectMsg = grappleProjSurfaceEffectMsg intersectPos collisionHbx grappleProjTowardsEnemyCollision :: CollisionEntity e => Pos2 -> Pos2 -> e -> Projectile GrappleProjData -> [Msg ThinkCollisionMsgsPhase] grappleProjTowardsEnemyCollision startPos intersectPos enemy grappleProj = [ mkMsgToEx (EnemyMsgSetHangtime $ _enemyTowardsHangtimeSecs cfg) enemyId MsgAfterNormalOrder , mkMsgTo (HurtMsgAttackHit grappleHit) enemyId ] ++ towardsMsgs ++ grappleProjHitEffectMsgs intersectPos where cfg = _config (P._data grappleProj :: GrappleProjData) startX = vecX startPos Pos2 intersectX intersectY = intersectPos enemyHbx = collisionEntityHitbox enemy hbxLeft = hitboxLeft enemyHbx hbxRight = hitboxRight enemyHbx xOffset = _playerTowardsXOffset cfg (intersectX', faceDir) | intersectX < startX = (hbxRight + xOffset, Just LeftDir) | otherwise = (hbxLeft - xOffset, Just RightDir) intersectPos' = Pos2 intersectX' intersectY hitstunMultiplier = (vecDist startPos intersectPos / _playerGrappleSpeed cfg) * _projHitstunMultiplier cfg grappleProjId = P._msgId grappleProj grappleHit = (mkAttackHitEmpty grappleProjId intersectPos') { _dir = Just $ if vecX intersectPos' > vecX startPos then RightDir else LeftDir , _damage = _projDamage cfg , _stagger = _projStagger cfg , _isRanged = True , _hitstunMultiplier = hitstunMultiplier } enemyId = collisionEntityMsgId enemy towardsMsgs = grappleProjTowardsCollision intersectPos' PreventOvershoot faceDir grappleProj
412
0.720882
1
0.720882
game-dev
MEDIA
0.893512
game-dev
0.733792
1
0.733792
magefree/mage
1,118
Mage.Sets/src/mage/cards/s/SymbioticBeast.java
package mage.cards.s; import java.util.UUID; import mage.MageInt; import mage.abilities.common.DiesSourceTriggeredAbility; import mage.abilities.effects.common.CreateTokenEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.game.permanent.token.InsectToken; /** * * @author Temba21 */ public final class SymbioticBeast extends CardImpl { public SymbioticBeast(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{4}{G}{G}"); this.subtype.add(SubType.INSECT); this.subtype.add(SubType.BEAST); this.power = new MageInt(4); this.toughness = new MageInt(4); // When Symbiotic Beast dies, create four 1/1 green Insect creature tokens. this.addAbility(new DiesSourceTriggeredAbility(new CreateTokenEffect(new InsectToken(), 4))); } private SymbioticBeast(final SymbioticBeast card) { super(card); } @Override public SymbioticBeast copy() { return new SymbioticBeast(this); } }
412
0.93263
1
0.93263
game-dev
MEDIA
0.848082
game-dev
0.737115
1
0.737115
EricDDK/billiards_cocos2d
2,571
Billiards/frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ControlSaturationBrightnessPicker.lua
-------------------------------- -- @module ControlSaturationBrightnessPicker -- @extend Control -- @parent_module cc -------------------------------- -- -- @function [parent=#ControlSaturationBrightnessPicker] getShadow -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#ControlSaturationBrightnessPicker] initWithTargetAndPos -- @param self -- @param #cc.Node target -- @param #vec2_table pos -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ControlSaturationBrightnessPicker] getStartPos -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- -- @function [parent=#ControlSaturationBrightnessPicker] getOverlay -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#ControlSaturationBrightnessPicker] getSlider -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#ControlSaturationBrightnessPicker] getBackground -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#ControlSaturationBrightnessPicker] getSaturation -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#ControlSaturationBrightnessPicker] getBrightness -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#ControlSaturationBrightnessPicker] create -- @param self -- @param #cc.Node target -- @param #vec2_table pos -- @return ControlSaturationBrightnessPicker#ControlSaturationBrightnessPicker ret (return value: cc.ControlSaturationBrightnessPicker) -------------------------------- -- -- @function [parent=#ControlSaturationBrightnessPicker] setEnabled -- @param self -- @param #bool enabled -- @return ControlSaturationBrightnessPicker#ControlSaturationBrightnessPicker self (return value: cc.ControlSaturationBrightnessPicker) -------------------------------- -- js ctor -- @function [parent=#ControlSaturationBrightnessPicker] ControlSaturationBrightnessPicker -- @param self -- @return ControlSaturationBrightnessPicker#ControlSaturationBrightnessPicker self (return value: cc.ControlSaturationBrightnessPicker) return nil
412
0.823097
1
0.823097
game-dev
MEDIA
0.591274
game-dev
0.87474
1
0.87474
ja2-stracciatella/ja2-stracciatella
5,847
src/externalized/policy/DefaultGamePolicy.cc
#include "DefaultGamePolicy.h" #include "Types.h" DefaultGamePolicy::DefaultGamePolicy(const JsonValue& json) { auto gp = json.toObject(); extra_hotkeys = gp.getOptionalBool("extra_hotkeys", true); can_enter_turnbased = gp.getOptionalBool("can_enter_turnbased"); middle_mouse_look = gp.getOptionalBool("middle_mouse_look", true); f_draw_item_shadow = gp.getOptionalBool("draw_item_shadow", true); target_fps = gp.getOptionalInt("target_fps", 40); game_durations_multiplier = gp.getOptionalDouble("game_durations_multiplier", 1.0); starting_cash_easy = gp.getOptionalInt("starting_cash_easy", 45000); starting_cash_medium = gp.getOptionalInt("starting_cash_medium", 35000); starting_cash_hard = gp.getOptionalInt("starting_cash_hard", 30000); f_drop_everything = gp.getOptionalBool("drop_everything"); f_all_dropped_visible = gp.getOptionalBool("all_drops_visible"); multiple_interrupts = gp.getOptionalBool("multiple_interrupts"); enemy_weapon_minimal_status = gp.getOptionalInt("enemy_weapon_minimal_status", 0); squad_size = gp.getOptionalUInt("squad_size", 6); auto ai = gp["ai"].toObject(); ai_better_aiming_choice = ai.getOptionalBool("better_aiming_choice"); ai_go_prone_more_often = ai.getOptionalBool("go_prone_more_often"); threshold_cth_head = ai.getOptionalInt("threshold_cth_head", 67); threshold_cth_legs = ai.getOptionalInt("threshold_cth_legs", 67); avoid_ambushes = ai.getOptionalBool("avoid_ambushes"); stay_on_rooftop = ai.getOptionalBool("stay_on_rooftop"); enemy_elite_minimum_level = gp.getOptionalInt("enemy_elite_minimum_level", 6); enemy_elite_maximum_level = gp.getOptionalInt("enemy_elite_maximum_level", 10); gui_extras = gp.getOptionalBool("gui_extras", true); extra_attachments = gp.getOptionalBool("extra_attachments"); skip_sleep_explanation = gp.getOptionalBool("skip_sleep_explanation"); pablo_wont_steal = gp.getOptionalBool("pablo_wont_steal"); critical_damage_head_multiplier = gp.getOptionalDouble("tactical_head_damage_multiplier", 1.5); critical_damage_legs_multiplier = gp.getOptionalDouble("tactical_legs_damage_multiplier", 0.5); chance_to_hit_maximum = gp.getOptionalInt("chance_to_hit_maximum", 99); chance_to_hit_minimum = gp.getOptionalInt("chance_to_hit_minimum", 1); aim_bonus_per_std_ap = gp.getOptionalInt("aim_bonus_per_std_ap", 10); aim_bonus_sniperscope = gp.getOptionalInt("aim_bonus_sniperscope", 20); aim_bonus_laserscope = gp.getOptionalInt("aim_bonus_laserscope", 20); range_penalty_silencer = gp.getOptionalInt("range_penalty_silencer", 0); range_bonus_barrel_extender = gp.getOptionalInt("range_bonus_barrel_extender", 100); always_show_cursor_in_tactical = gp.getOptionalBool("always_show_cursor_in_tactical", false); show_hit_chance = gp.getOptionalBool("show_hit_chance", false); website_loading_time_scale = gp.getOptionalDouble("website_loading_time_scale", 1.0); diagonally_interactable_doors = gp.getOptionalBool("diagonally_interactable_doors", false); auto imp = gp["imp"].toObject(); imp_load_saved_merc_by_nickname = imp.getOptionalBool("load_saved_merc_by_nickname"); imp_load_keep_inventory = imp.getOptionalBool("load_keep_inventory"); imp_attribute_max = imp.getOptionalInt("max_attribute_points", 85); imp_attribute_min = imp.getOptionalInt("min_attribute_points", 35); imp_attribute_zero_bonus = imp.getOptionalInt("zero_attribute_points_bonus", 15); imp_attribute_bonus = imp.getOptionalInt("bonus_attribute_points", 40); imp_pick_skills_directly = imp.getOptionalBool("pick_skills_directly"); merc_online_min_days = gp.getOptionalUInt("merc_online_min_days", 1); merc_online_max_days = gp.getOptionalUInt("merc_online_max_days", 2); auto progress = gp["progress"].toObject(); progress_event_madlab_min = progress.getOptionalInt("event_madlab_min", 35); progress_event_mike_min = progress.getOptionalInt("event_mike_min", 50); progress_event_iggy_min = progress.getOptionalInt("event_iggy_min", 70); kills_per_point_easy = progress.getOptionalInt("kills_per_point_easy", 7); kills_per_point_medium = progress.getOptionalInt("kills_per_point_medium", 10); kills_per_point_hard = progress.getOptionalInt("kills_per_point_hard", 15); progress_weight_kills = progress.getOptionalDouble("weight_kills", 25.0); progress_weight_control = progress.getOptionalDouble("weight_control", 25.0); progress_weight_income = progress.getOptionalDouble("weight_income", 50.0); unhired_merc_deaths_easy = gp.getOptionalInt("unhired_merc_deaths_easy", 1); unhired_merc_deaths_medium = gp.getOptionalInt("unhired_merc_deaths_medium", 2); unhired_merc_deaths_hard = gp.getOptionalInt("unhired_merc_deaths_hard", 3); auto campaign = gp["campaign"].toObject(); ST::string sector_string = campaign.getOptionalString("start_sector"); start_sector = SGPSector::FromShortString(!sector_string.empty() ? sector_string : "A9").AsByte(); reveal_start_sector = campaign.getOptionalBool("start_sector_revealed", false); } /** Check if a hotkey is enabled. */ bool DefaultGamePolicy::isHotkeyEnabled(UIMode mode, HotkeyModifier modifier, uint32_t key) const { if(mode == UI_Tactical) { if(modifier == HKMOD_None) { switch(key) { case 'j': return extra_hotkeys; } } else if(modifier == HKMOD_CTRL) { switch(key) { case 'n': case 'q': return extra_hotkeys; } } else if(modifier == HKMOD_SHIFT) { switch(key) { case 'j': return extra_hotkeys; } } else if(modifier == HKMOD_ALT) { switch(key) { case 'r': return extra_hotkeys; } } else if(modifier == HKMOD_CTRL_SHIFT) { switch(key) { case 'r': return extra_hotkeys; } } } if(mode == UI_Map) { if(modifier == HKMOD_CTRL) { switch(key) { case 'i': return extra_hotkeys; } } } return false; }
412
0.910888
1
0.910888
game-dev
MEDIA
0.9655
game-dev
0.962281
1
0.962281
GwennaelBuchet/SceneGraph.js
3,406
examples/01_Basic_Shapes/11_Slider/js/class.main.js
var CGMain = CGSGView.extend({ initialize : function(canvas) { this._super(canvas); this.initializeCanvas(); this.createScene(); this.startPlaying(); }, initializeCanvas : function() { this.viewDimension = cgsgGetRealViewportDimension(); this.setCanvasDimension(this.viewDimension); }, createScene : function() { var root = new CGSGNode(0, 0); CGSG.sceneGraph.addNode(root, null); var master = new CGSGNodeSlider(50, 100, 600, 20); root.addChild(master); master.setValue(-7); master.isResizable = true; master.isDraggable = true; var masterValueLabel = new CGSGNodeText(20, 20, (Math.floor(master.getValueAsRangeRatio()*10000)/100)+" %"); root.addChild(masterValueLabel); var slave = new CGSGNodeSlider(50, 200, 600, 20); root.addChild(slave); slave.valueColor = '#880000'; slave.setValue(-7); slave.isResizable = true; slave.isDraggable = true; var check = new CGSGNodeSlider(50, 300, 600, 10); root.addChild(check); check.valueColor = '#880044'; check.setValue(7.5); check.setMin(5); check.setMax(-5); check.isResizable = true; check.isDraggable = true; var masterSlideSlaveListener = (function(event) { var slider = event.observable.getParentSlider(); slave.setValue(slider.value); }).bind(this); var masterValueLabelMasterSlideListener = (function(event) { var slider = event.observable.getParentSlider(); masterValueLabel.setText((Math.floor(slider.value*100)/100) + " or " + (Math.floor(slider.getValueAsRangeRatio()*10000)/100)+" %", true); }).bind(this); var checkSlideSlaveEndListener = (function(event) { var slider = event.observable.getParentSlider(); slave.setValue(slider.value); }).bind(this); CGSG.eventManager.bindHandler(check.getHandle(), cgsgEventTypes.ON_DRAG_END, checkSlideSlaveEndListener); CGSG.eventManager.bindHandler(master.getHandle(), cgsgEventTypes.ON_DRAG, masterSlideSlaveListener); CGSG.eventManager.bindHandler(master.getHandle(), cgsgEventTypes.ON_DRAG, masterValueLabelMasterSlideListener); var red = new CGSGNodeSlider(50, 400, 300, 10); root.addChild(red); red.setMin(0); red.setMax(255); red.setValue(0); var green = new CGSGNodeSlider(50, 450, 300, 10); root.addChild(green); green.setMin(0); green.setMax(255); green.setValue(0); var blue = new CGSGNodeSlider(50, 500, 300, 10); root.addChild(blue); blue.setMin(0); blue.setMax(255); blue.setValue(0); var rgbListener = (function() { red.valueColor = CGSGColor.rgb2hex(Math.floor(red.value), 0, 0); green.valueColor = CGSGColor.rgb2hex(0, Math.floor(green.value), 0); blue.valueColor = CGSGColor.rgb2hex(0, 0, Math.floor(blue.value)); check.valueColor = CGSGColor.rgb2hex(Math.floor(red.value), Math.floor(green.value), Math.floor(blue.value)); }).bind(this); CGSG.eventManager.bindHandler(red.getHandle(), cgsgEventTypes.ON_DRAG, rgbListener); CGSG.eventManager.bindHandler(green.getHandle(), cgsgEventTypes.ON_DRAG, rgbListener); CGSG.eventManager.bindHandler(blue.getHandle(), cgsgEventTypes.ON_DRAG, rgbListener); } });
412
0.6691
1
0.6691
game-dev
MEDIA
0.714805
game-dev,testing-qa
0.880274
1
0.880274
Pico-Developer/PICO-Unity-Integration-SDK
10,418
Runtime/Scripts/SecureMR/Component/Operator/PXR_SecureMROperator.cs
#if !PICO_OPENXR_SDK using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Unity.XR.PXR.SecureMR { public class PXR_SecureMROperator : MonoBehaviour { public SecureMROperatorType operatorType; public PXR_SecureMROperatorConfig operatorConfig; public PXR_SecureMROperand[] operands; public PXR_SecureMRResult[] results; internal Operator Operator; public void InitializeOperator(PXR_SecureMRPipeline pipeline) { switch (operatorType) { case SecureMROperatorType.Unknown: break; case SecureMROperatorType.ArithmeticCompose: { if (operatorConfig != null && operatorConfig is PXR_SecureMRArithmeticComposeOperatorConfig opConfig) { ArithmeticComposeOperatorConfiguration arithmeticComposeOperatorConfig = new ArithmeticComposeOperatorConfiguration(opConfig.configText); Operator = pipeline.pipeline.CreateOperator<ArithmeticComposeOperator>(arithmeticComposeOperatorConfig); } } break; case SecureMROperatorType.Nms: { if (operatorConfig != null && operatorConfig is PXR_SecureMRNmsOperatorConfig opConfig) { NmsOperatorConfiguration nmsOperatorConfig = new NmsOperatorConfiguration(opConfig.threshold); Operator = pipeline.pipeline.CreateOperator<NmsOperator>(nmsOperatorConfig); } } break; case SecureMROperatorType.ElementwiseMin: { Operator = pipeline.pipeline.CreateOperator<ElementwiseMinOperator>(); } break; case SecureMROperatorType.ElementwiseMax: { Operator = pipeline.pipeline.CreateOperator<ElementwiseMaxOperator>(); } break; case SecureMROperatorType.ElementwiseMultiply: { Operator = pipeline.pipeline.CreateOperator<ElementwiseMultiplyOperator>(); } break; case SecureMROperatorType.CustomizedCompare: { if (operatorConfig != null && operatorConfig is PXR_SecureMRComparisonOperatorConfig opConfig) { ComparisonOperatorConfiguration comparisonOperatorConfig = new ComparisonOperatorConfiguration(opConfig.comparison); Operator = pipeline.pipeline.CreateOperator<CustomizedCompareOperator>(comparisonOperatorConfig); } } break; case SecureMROperatorType.ElementwiseOr: { Operator = pipeline.pipeline.CreateOperator<ElementwiseOrOperator>(); } break; case SecureMROperatorType.ElementwiseAnd: { Operator = pipeline.pipeline.CreateOperator<ElementwiseAndOperator>(); } break; case SecureMROperatorType.All: { Operator = pipeline.pipeline.CreateOperator<AllOperator>(); } break; case SecureMROperatorType.Any: { Operator = pipeline.pipeline.CreateOperator<AnyOperator>(); } break; case SecureMROperatorType.SolvePnP: { Operator = pipeline.pipeline.CreateOperator<SolvePnPOperator>(); } break; case SecureMROperatorType.GetAffine: { Operator = pipeline.pipeline.CreateOperator<GetAffineOperator>(); } break; case SecureMROperatorType.ApplyAffine: { Operator = pipeline.pipeline.CreateOperator<ApplyAffineOperator>(); } break; case SecureMROperatorType.ApplyAffinePoint: { Operator = pipeline.pipeline.CreateOperator<ApplyAffinePointOperator>(); } break; case SecureMROperatorType.UvTo3DInCameraSpace: { Operator = pipeline.pipeline.CreateOperator<UvTo3DInCameraSpaceOperator>(); } break; case SecureMROperatorType.Assignment: { Operator = pipeline.pipeline.CreateOperator<AssignmentOperator>(); } break; case SecureMROperatorType.RunModelInference: { if (operatorConfig != null && operatorConfig is PXR_SecureMRModelOperatorConfiguration opConfig) { var modelOperatorConfiguration = opConfig.CreateModelOperatorConfiguration(); Operator = pipeline.pipeline.CreateOperator<RunModelInferenceOperator>(modelOperatorConfiguration); } } break; case SecureMROperatorType.Normalize: { if (operatorConfig != null && operatorConfig is PXR_SecureMRNormalizeOperatorConfig opConfig) { NormalizeOperatorConfiguration normalizeOperatorConfig = new NormalizeOperatorConfiguration(opConfig.normalizeType); Operator = pipeline.pipeline.CreateOperator<NormalizeOperator>(normalizeOperatorConfig); } } break; case SecureMROperatorType.CameraSpaceToWorld: { Operator = pipeline.pipeline.CreateOperator<CameraSpaceToWorldOperator>(); } break; case SecureMROperatorType.RectifiedVstAccess: { Operator = pipeline.pipeline.CreateOperator<RectifiedVstAccessOperator>(); } break; case SecureMROperatorType.Argmax: { Operator = pipeline.pipeline.CreateOperator<ArgmaxOperator>(); } break; case SecureMROperatorType.ConvertColor: { if (operatorConfig != null && operatorConfig is PXR_SecureMRColorConvertOperatorConfig opConfig) { ColorConvertOperatorConfiguration colorConvertOperatorConfig = new ColorConvertOperatorConfiguration(opConfig.covert); Operator = pipeline.pipeline.CreateOperator<ConvertColorOperator>(colorConvertOperatorConfig); } } break; case SecureMROperatorType.SortVector: { Operator = pipeline.pipeline.CreateOperator<SortVectorOperator>(); } break; case SecureMROperatorType.Inversion: { Operator = pipeline.pipeline.CreateOperator<InversionOperator>(); } break; case SecureMROperatorType.GetTransformMatrix: { Operator = pipeline.pipeline.CreateOperator<GetTransformMatrixOperator>(); } break; case SecureMROperatorType.SortMatrix: { if (operatorConfig != null && operatorConfig is PXR_SecureMRSortMatrixOperatorConfig opConfig) { SortMatrixOperatorConfiguration colorConvertOperatorConfig = new SortMatrixOperatorConfiguration(opConfig.sortType); Operator = pipeline.pipeline.CreateOperator<SortMatrixOperator>(colorConvertOperatorConfig); } } break; case SecureMROperatorType.SwitchGltfRenderStatus: { Operator = pipeline.pipeline.CreateOperator<SwitchGltfRenderStatusOperator>(); } break; case SecureMROperatorType.UpdateGltf: { if (operatorConfig != null && operatorConfig is PXR_SecureMRUpdateGltfOperatorConfig opConfig) { UpdateGltfOperatorConfiguration colorConvertOperatorConfig = new UpdateGltfOperatorConfiguration(opConfig.attribute); Operator = pipeline.pipeline.CreateOperator<UpdateGltfOperator>(colorConvertOperatorConfig); } } break; case SecureMROperatorType.RenderText: { if (operatorConfig != null && operatorConfig is PXR_SecureMRRenderTextOperatorConfig opConfig) { RenderTextOperatorConfiguration colorConvertOperatorConfig = new RenderTextOperatorConfiguration(opConfig.typeface, opConfig.languageAndLocale, opConfig.width, opConfig.height); Operator = pipeline.pipeline.CreateOperator<UpdateGltfOperator>(colorConvertOperatorConfig); } } break; case SecureMROperatorType.LoadTexture: { Operator = pipeline.pipeline.CreateOperator<LoadTextureOperator>(); } break; default: throw new ArgumentOutOfRangeException(); } } public void InitializeParameters() { for (int i = 0; i < operands.Length; i++) { Operator.SetOperand(operands[i].name, operands[i].tensor.tensor); } for (int i = 0; i < results.Length; i++) { Operator.SetResult(results[i].name, results[i].tensor.tensor); } } } } #endif
412
0.74015
1
0.74015
game-dev
MEDIA
0.643161
game-dev
0.90657
1
0.90657
mjaun/android-anuto
2,841
app/src/main/java/ch/logixisland/anuto/entity/effect/TeleportedMarker.java
package ch.logixisland.anuto.entity.effect; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import ch.logixisland.anuto.engine.logic.GameEngine; import ch.logixisland.anuto.engine.logic.entity.Entity; import ch.logixisland.anuto.engine.logic.loop.TickListener; import ch.logixisland.anuto.engine.render.Drawable; import ch.logixisland.anuto.engine.render.Layers; import ch.logixisland.anuto.util.math.Function; import ch.logixisland.anuto.util.math.SampledFunction; public class TeleportedMarker extends Effect implements Entity.Listener { private static final float MARKER_MIN_RADIUS = 0.1f; private static final float MARKER_MAX_RADIUS = 0.2f; private static final float MARKER_SPEED = 1f; private static class StaticData implements TickListener { private SampledFunction mScaleFunction; private Paint mPaint; @Override public void tick() { mScaleFunction.step(); } } private class MarkerDrawable implements Drawable { private MarkerDrawable() { } @Override public int getLayer() { return Layers.SHOT; } @Override public void draw(Canvas canvas) { canvas.drawCircle( getPosition().x(), getPosition().y(), mStaticData.mScaleFunction.getValue(), mStaticData.mPaint); } } private final Entity mMarked; private StaticData mStaticData; private final MarkerDrawable mDrawable; public TeleportedMarker(Entity marked) { super(marked); mMarked = marked; mMarked.addListener(this); mDrawable = new MarkerDrawable(); } @Override public Object initStatic() { StaticData s = new StaticData(); s.mScaleFunction = Function.sine() .multiply((MARKER_MAX_RADIUS - MARKER_MIN_RADIUS) / 2) .offset((MARKER_MAX_RADIUS + MARKER_MIN_RADIUS) / 2) .stretch(GameEngine.TARGET_FRAME_RATE / MARKER_SPEED / (float) Math.PI) .sample(); s.mPaint = new Paint(); s.mPaint.setStyle(Paint.Style.FILL); s.mPaint.setColor(Color.MAGENTA); s.mPaint.setAlpha(30); getGameEngine().add(s); return s; } @Override public void init() { super.init(); mStaticData = (StaticData) getStaticData(); getGameEngine().add(mDrawable); } @Override public void clean() { super.clean(); getGameEngine().remove(mDrawable); } @Override public void tick() { super.tick(); setPosition(mMarked.getPosition()); } @Override public void entityRemoved(Entity entity) { remove(); } }
412
0.846799
1
0.846799
game-dev
MEDIA
0.886187
game-dev
0.933115
1
0.933115